1 /*
2  *  SSL client with options
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 #define MBEDTLS_ALLOW_PRIVATE_ACCESS
9 
10 #include "ssl_test_lib.h"
11 
12 #if defined(MBEDTLS_SSL_TEST_IMPOSSIBLE)
main(void)13 int main(void)
14 {
15     mbedtls_printf(MBEDTLS_SSL_TEST_IMPOSSIBLE);
16     mbedtls_exit(0);
17 }
18 #elif !defined(MBEDTLS_SSL_SRV_C)
main(void)19 int main(void)
20 {
21     mbedtls_printf("MBEDTLS_SSL_SRV_C not defined.\n");
22     mbedtls_exit(0);
23 }
24 #else /* !MBEDTLS_SSL_TEST_IMPOSSIBLE && MBEDTLS_SSL_SRV_C */
25 
26 #include <stdint.h>
27 
28 #if !defined(_MSC_VER)
29 #include <inttypes.h>
30 #endif
31 
32 #if !defined(_WIN32)
33 #include <signal.h>
34 #endif
35 
36 #if defined(MBEDTLS_SSL_CACHE_C)
37 #include "mbedtls/ssl_cache.h"
38 #endif
39 
40 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_TICKET_C)
41 #include "mbedtls/ssl_ticket.h"
42 #endif
43 
44 #if defined(MBEDTLS_SSL_COOKIE_C)
45 #include "mbedtls/ssl_cookie.h"
46 #endif
47 
48 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) && defined(MBEDTLS_FS_IO)
49 #define SNI_OPTION
50 #endif
51 
52 #if defined(_WIN32)
53 #include <windows.h>
54 #endif
55 
56 #if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
57 #include "test/psa_crypto_helpers.h"
58 #endif
59 
60 #include "mbedtls/pk.h"
61 #include "mbedtls/dhm.h"
62 
63 /* Size of memory to be allocated for the heap, when using the library's memory
64  * management and MBEDTLS_MEMORY_BUFFER_ALLOC_C is enabled. */
65 #define MEMORY_HEAP_SIZE        180000
66 
67 #define DFL_SERVER_ADDR         NULL
68 #define DFL_SERVER_PORT         "4433"
69 #define DFL_RESPONSE_SIZE       -1
70 #define DFL_DEBUG_LEVEL         0
71 #define DFL_NBIO                0
72 #define DFL_EVENT               0
73 #define DFL_READ_TIMEOUT        0
74 #define DFL_CA_FILE             ""
75 #define DFL_CA_PATH             ""
76 #define DFL_CRT_FILE            ""
77 #define DFL_KEY_FILE            ""
78 #define DFL_KEY_OPAQUE          0
79 #define DFL_KEY_PWD             ""
80 #define DFL_CRT_FILE2           ""
81 #define DFL_KEY_FILE2           ""
82 #define DFL_KEY_PWD2            ""
83 #define DFL_ASYNC_OPERATIONS    "-"
84 #define DFL_ASYNC_PRIVATE_DELAY1 (-1)
85 #define DFL_ASYNC_PRIVATE_DELAY2 (-1)
86 #define DFL_ASYNC_PRIVATE_ERROR  (0)
87 #define DFL_PSK                 ""
88 #define DFL_PSK_OPAQUE          0
89 #define DFL_PSK_LIST_OPAQUE     0
90 #define DFL_PSK_IDENTITY        "Client_identity"
91 #define DFL_ECJPAKE_PW          NULL
92 #define DFL_ECJPAKE_PW_OPAQUE   0
93 #define DFL_PSK_LIST            NULL
94 #define DFL_FORCE_CIPHER        0
95 #define DFL_TLS1_3_KEX_MODES    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_ALL
96 #define DFL_RENEGOTIATION       MBEDTLS_SSL_RENEGOTIATION_DISABLED
97 #define DFL_ALLOW_LEGACY        -2
98 #define DFL_RENEGOTIATE         0
99 #define DFL_RENEGO_DELAY        -2
100 #define DFL_RENEGO_PERIOD       ((uint64_t) -1)
101 #define DFL_EXCHANGES           1
102 #define DFL_MIN_VERSION         -1
103 #define DFL_MAX_VERSION         -1
104 #define DFL_SHA1                -1
105 #define DFL_CID_ENABLED         0
106 #define DFL_CID_VALUE           ""
107 #define DFL_CID_ENABLED_RENEGO  -1
108 #define DFL_CID_VALUE_RENEGO    NULL
109 #define DFL_AUTH_MODE           -1
110 #define DFL_CERT_REQ_CA_LIST    MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED
111 #define DFL_CERT_REQ_DN_HINT    0
112 #define DFL_MFL_CODE            MBEDTLS_SSL_MAX_FRAG_LEN_NONE
113 #define DFL_TRUNC_HMAC          -1
114 #define DFL_TICKETS             MBEDTLS_SSL_SESSION_TICKETS_ENABLED
115 #define DFL_DUMMY_TICKET        0
116 #define DFL_TICKET_ROTATE       0
117 #define DFL_TICKET_TIMEOUT      86400
118 #define DFL_TICKET_AEAD         MBEDTLS_CIPHER_AES_256_GCM
119 #define DFL_CACHE_MAX           -1
120 #define DFL_CACHE_TIMEOUT       -1
121 #define DFL_CACHE_REMOVE        0
122 #define DFL_SNI                 NULL
123 #define DFL_ALPN_STRING         NULL
124 #define DFL_GROUPS              NULL
125 #define DFL_MAX_EARLY_DATA_SIZE 0
126 #define DFL_SIG_ALGS            NULL
127 #define DFL_DHM_FILE            NULL
128 #define DFL_TRANSPORT           MBEDTLS_SSL_TRANSPORT_STREAM
129 #define DFL_COOKIES             1
130 #define DFL_ANTI_REPLAY         -1
131 #define DFL_HS_TO_MIN           0
132 #define DFL_HS_TO_MAX           0
133 #define DFL_DTLS_MTU            -1
134 #define DFL_BADMAC_LIMIT        -1
135 #define DFL_DGRAM_PACKING        1
136 #define DFL_EXTENDED_MS         -1
137 #define DFL_ETM                 -1
138 #define DFL_SERIALIZE           0
139 #define DFL_CONTEXT_FILE        ""
140 #define DFL_EXTENDED_MS_ENFORCE -1
141 #define DFL_CA_CALLBACK         0
142 #define DFL_EAP_TLS             0
143 #define DFL_REPRODUCIBLE        0
144 #define DFL_NSS_KEYLOG          0
145 #define DFL_NSS_KEYLOG_FILE     NULL
146 #define DFL_QUERY_CONFIG_MODE   0
147 #define DFL_USE_SRTP            0
148 #define DFL_SRTP_FORCE_PROFILE  0
149 #define DFL_SRTP_SUPPORT_MKI    0
150 #define DFL_KEY_OPAQUE_ALG      "none"
151 
152 #define LONG_RESPONSE "<p>01-blah-blah-blah-blah-blah-blah-blah-blah-blah\r\n" \
153                       "02-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah\r\n"  \
154                       "03-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah\r\n"  \
155                       "04-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah\r\n"  \
156                       "05-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah\r\n"  \
157                       "06-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah\r\n"  \
158                       "07-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah</p>\r\n"
159 
160 /* Uncomment LONG_RESPONSE at the end of HTTP_RESPONSE to test sending longer
161  * packets (for fragmentation purposes) */
162 #define HTTP_RESPONSE \
163     "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" \
164     "<h2>Mbed TLS Test Server</h2>\r\n" \
165     "<p>Successful connection using: %s</p>\r\n" // LONG_RESPONSE
166 
167 /*
168  * Size of the basic I/O buffer. Able to hold our default response.
169  */
170 #define DFL_IO_BUF_LEN      200
171 
172 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
173 #if defined(MBEDTLS_FS_IO)
174 #define USAGE_IO \
175     "    ca_file=%%s          The single file containing the top-level CA(s) you fully trust\n" \
176     "                        default: \"\" (pre-loaded)\n" \
177     "                        use \"none\" to skip loading any top-level CAs.\n" \
178     "    ca_path=%%s          The path containing the top-level CA(s) you fully trust\n" \
179     "                        default: \"\" (pre-loaded) (overrides ca_file)\n" \
180     "                        use \"none\" to skip loading any top-level CAs.\n" \
181     "    crt_file=%%s         Your own cert and chain (in bottom to top order, top may be omitted)\n" \
182     "                        default: see note after key_file2\n" \
183     "    key_file=%%s         default: see note after key_file2\n" \
184     "    key_pwd=%%s          Password for key specified by key_file argument\n" \
185     "                        default: none\n" \
186     "    crt_file2=%%s        Your second cert and chain (in bottom to top order, top may be omitted)\n" \
187     "                        default: see note after key_file2\n" \
188     "    key_file2=%%s        default: see note below\n" \
189     "                        note: if neither crt_file/key_file nor crt_file2/key_file2 are used,\n" \
190     "                              preloaded certificate(s) and key(s) are used if available\n" \
191     "    key_pwd2=%%s         Password for key specified by key_file2 argument\n" \
192     "                        default: none\n" \
193     "    dhm_file=%%s        File containing Diffie-Hellman parameters\n" \
194     "                       default: preloaded parameters\n"
195 #else
196 #define USAGE_IO \
197     "\n"                                                    \
198     "    No file operations available (MBEDTLS_FS_IO not defined)\n" \
199     "\n"
200 #endif /* MBEDTLS_FS_IO */
201 #else
202 #define USAGE_IO ""
203 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
204 #if defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
205 #define USAGE_KEY_OPAQUE \
206     "    key_opaque=%%d       Handle your private keys as if they were opaque\n" \
207     "                        default: 0 (disabled)\n"
208 #else
209 #define USAGE_KEY_OPAQUE ""
210 #endif
211 
212 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
213 #define USAGE_SSL_ASYNC \
214     "    async_operations=%%c...   d=decrypt, s=sign (default: -=off)\n" \
215     "    async_private_delay1=%%d  Asynchronous delay for key_file or preloaded key\n" \
216     "    async_private_delay2=%%d  Asynchronous delay for key_file2 and sni\n" \
217     "                              default: -1 (not asynchronous)\n" \
218     "    async_private_error=%%d   Async callback error injection (default=0=none,\n" \
219     "                              1=start, 2=cancel, 3=resume, negative=first time only)"
220 #else
221 #define USAGE_SSL_ASYNC ""
222 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
223 
224 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
225 #define USAGE_CID \
226     "    cid=%%d             Disable (0) or enable (1) the use of the DTLS Connection ID extension.\n" \
227     "                       default: 0 (disabled)\n"     \
228     "    cid_renego=%%d      Disable (0) or enable (1) the use of the DTLS Connection ID extension during renegotiation.\n" \
229     "                       default: same as 'cid' parameter\n"     \
230     "    cid_val=%%s          The CID to use for incoming messages (in hex, without 0x).\n"  \
231     "                        default: \"\"\n" \
232     "    cid_val_renego=%%s   The CID to use for incoming messages (in hex, without 0x) after renegotiation.\n"  \
233     "                        default: same as 'cid_val' parameter\n"
234 #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
235 #define USAGE_CID ""
236 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
237 
238 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
239 #define USAGE_PSK_RAW                                               \
240     "    psk=%%s              default: \"\" (disabled)\n"     \
241     "                          The PSK values are in hex, without 0x.\n" \
242     "    psk_list=%%s         default: \"\"\n"                          \
243     "                          A list of (PSK identity, PSK value) pairs.\n" \
244     "                          The PSK values are in hex, without 0x.\n" \
245     "                          id1,psk1[,id2,psk2[,...]]\n"             \
246     "    psk_identity=%%s     default: \"Client_identity\"\n"
247 #if defined(MBEDTLS_USE_PSA_CRYPTO)
248 #define USAGE_PSK_SLOT                          \
249     "    psk_opaque=%%d       default: 0 (don't use opaque static PSK)\n"     \
250     "                          Enable this to store the PSK configured through command line\n" \
251     "                          parameter `psk` in a PSA-based key slot.\n" \
252     "                          Note: Currently only supported in conjunction with\n"                  \
253     "                          the use of min_version to force TLS 1.2 and force_ciphersuite \n"      \
254     "                          to force a particular PSK-only ciphersuite.\n"                         \
255     "                          Note: This is to test integration of PSA-based opaque PSKs with\n"     \
256     "                          Mbed TLS only. Production systems are likely to configure Mbed TLS\n"  \
257     "                          with prepopulated key slots instead of importing raw key material.\n" \
258     "    psk_list_opaque=%%d  default: 0 (don't use opaque dynamic PSKs)\n"     \
259     "                          Enable this to store the list of dynamically chosen PSKs configured\n" \
260     "                          through the command line parameter `psk_list` in PSA-based key slots.\n" \
261     "                          Note: Currently only supported in conjunction with\n" \
262     "                          the use of min_version to force TLS 1.2 and force_ciphersuite \n" \
263     "                          to force a particular PSK-only ciphersuite.\n" \
264     "                          Note: This is to test integration of PSA-based opaque PSKs with\n" \
265     "                          Mbed TLS only. Production systems are likely to configure Mbed TLS\n" \
266     "                          with prepopulated key slots instead of importing raw key material.\n"
267 #else
268 #define USAGE_PSK_SLOT ""
269 #endif /* MBEDTLS_USE_PSA_CRYPTO */
270 #define USAGE_PSK USAGE_PSK_RAW USAGE_PSK_SLOT
271 #else
272 #define USAGE_PSK ""
273 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
274 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
275 #define USAGE_CA_CALLBACK                       \
276     "   ca_callback=%%d       default: 0 (disabled)\n"      \
277     "                         Enable this to use the trusted certificate callback function\n"
278 #else
279 #define USAGE_CA_CALLBACK ""
280 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
281 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_TICKET_C)
282 #define USAGE_TICKETS                                       \
283     "    tickets=%%d          default: 1 (enabled)\n"       \
284     "    ticket_rotate=%%d    default: 0 (disabled)\n"      \
285     "    ticket_timeout=%%d   default: 86400 (one day)\n"   \
286     "    ticket_aead=%%s      default: \"AES-256-GCM\"\n"
287 #else
288 #define USAGE_TICKETS ""
289 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_TICKET_C */
290 
291 #define USAGE_EAP_TLS                                       \
292     "    eap_tls=%%d          default: 0 (disabled)\n"
293 #define USAGE_NSS_KEYLOG                                    \
294     "    nss_keylog=%%d          default: 0 (disabled)\n"   \
295     "                             This cannot be used with eap_tls=1\n"
296 #define USAGE_NSS_KEYLOG_FILE                               \
297     "    nss_keylog_file=%%s\n"
298 #if defined(MBEDTLS_SSL_DTLS_SRTP)
299 #define USAGE_SRTP \
300     "    use_srtp=%%d         default: 0 (disabled)\n" \
301     "    srtp_force_profile=%%d  default: 0 (all enabled)\n"   \
302     "                        available profiles:\n"       \
303     "                        1 - SRTP_AES128_CM_HMAC_SHA1_80\n"  \
304     "                        2 - SRTP_AES128_CM_HMAC_SHA1_32\n"  \
305     "                        3 - SRTP_NULL_HMAC_SHA1_80\n"       \
306     "                        4 - SRTP_NULL_HMAC_SHA1_32\n"       \
307     "    support_mki=%%d     default: 0 (not supported)\n"
308 #else /* MBEDTLS_SSL_DTLS_SRTP */
309 #define USAGE_SRTP ""
310 #endif
311 
312 #if defined(MBEDTLS_SSL_CACHE_C)
313 #define USAGE_CACHE                                             \
314     "    cache_max=%%d        default: cache default (50)\n"    \
315     "    cache_remove=%%d     default: 0 (don't remove)\n"
316 #if defined(MBEDTLS_HAVE_TIME)
317 #define USAGE_CACHE_TIME \
318     "    cache_timeout=%%d    default: cache default (1d)\n"
319 #else
320 #define USAGE_CACHE_TIME ""
321 #endif
322 #else
323 #define USAGE_CACHE ""
324 #define USAGE_CACHE_TIME ""
325 #endif /* MBEDTLS_SSL_CACHE_C */
326 
327 #if defined(SNI_OPTION)
328 #if defined(MBEDTLS_X509_CRL_PARSE_C)
329 #define SNI_CRL              ",crl"
330 #else
331 #define SNI_CRL              ""
332 #endif
333 
334 #define USAGE_SNI                                                           \
335     "    sni=%%s              name1,cert1,key1,ca1"SNI_CRL ",auth1[,...]\n"  \
336                                                            "                        default: disabled\n"
337 #else
338 #define USAGE_SNI ""
339 #endif /* SNI_OPTION */
340 
341 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
342 #define USAGE_MAX_FRAG_LEN                                      \
343     "    max_frag_len=%%d     default: 16384 (tls default)\n"   \
344     "                        options: 512, 1024, 2048, 4096\n"
345 #else
346 #define USAGE_MAX_FRAG_LEN ""
347 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
348 
349 #if defined(MBEDTLS_SSL_ALPN)
350 #define USAGE_ALPN \
351     "    alpn=%%s             default: \"\" (disabled)\n"   \
352     "                        example: spdy/1,http/1.1\n"
353 #else
354 #define USAGE_ALPN ""
355 #endif /* MBEDTLS_SSL_ALPN */
356 
357 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
358 #define USAGE_COOKIES \
359     "    cookies=0/1/-1      default: 1 (enabled)\n"        \
360     "                        0: disabled, -1: library default (broken)\n"
361 #else
362 #define USAGE_COOKIES ""
363 #endif
364 
365 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
366 #define USAGE_ANTI_REPLAY \
367     "    anti_replay=0/1     default: (library default: enabled)\n"
368 #else
369 #define USAGE_ANTI_REPLAY ""
370 #endif
371 
372 #define USAGE_BADMAC_LIMIT \
373     "    badmac_limit=%%d     default: (library default: disabled)\n"
374 
375 #if defined(MBEDTLS_SSL_PROTO_DTLS)
376 #define USAGE_DTLS \
377     "    dtls=%%d             default: 0 (TLS)\n"                           \
378     "    hs_timeout=%%d-%%d    default: (library default: 1000-60000)\n"    \
379     "                        range of DTLS handshake timeouts in millisecs\n" \
380     "    mtu=%%d              default: (library default: unlimited)\n"  \
381     "    dgram_packing=%%d    default: 1 (allowed)\n"                   \
382     "                        allow or forbid packing of multiple\n" \
383     "                        records within a single datgram.\n"
384 #else
385 #define USAGE_DTLS ""
386 #endif
387 
388 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
389 #define USAGE_EMS \
390     "    extended_ms=0/1     default: (library default: on)\n"
391 #else
392 #define USAGE_EMS ""
393 #endif
394 
395 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
396 #define USAGE_ETM \
397     "    etm=0/1             default: (library default: on)\n"
398 #else
399 #define USAGE_ETM ""
400 #endif
401 
402 #define USAGE_REPRODUCIBLE \
403     "    reproducible=0/1     default: 0 (disabled)\n"
404 
405 #if defined(MBEDTLS_SSL_RENEGOTIATION)
406 #define USAGE_RENEGO \
407     "    renegotiation=%%d    default: 0 (disabled)\n"      \
408     "    renegotiate=%%d      default: 0 (disabled)\n"      \
409     "    renego_delay=%%d     default: -2 (library default)\n" \
410     "    renego_period=%%d    default: (2^64 - 1 for TLS, 2^48 - 1 for DTLS)\n"
411 #else
412 #define USAGE_RENEGO ""
413 #endif
414 
415 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
416 #if defined(MBEDTLS_USE_PSA_CRYPTO)
417 #define USAGE_ECJPAKE \
418     "    ecjpake_pw=%%s           default: none (disabled)\n"   \
419     "    ecjpake_pw_opaque=%%d    default: 0 (disabled)\n"
420 #else /* MBEDTLS_USE_PSA_CRYPTO */
421 #define USAGE_ECJPAKE \
422     "    ecjpake_pw=%%s           default: none (disabled)\n"
423 #endif /* MBEDTLS_USE_PSA_CRYPTO */
424 #else /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
425 #define USAGE_ECJPAKE ""
426 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
427 
428 #if defined(MBEDTLS_SSL_EARLY_DATA)
429 #define USAGE_EARLY_DATA \
430     "    max_early_data_size=%%d default: -1 (disabled)\n"             \
431     "                            options: -1 (disabled), "           \
432     "                                     >= 0 (enabled, max amount of early data )\n"
433 #else
434 #define USAGE_EARLY_DATA ""
435 #endif /* MBEDTLS_SSL_EARLY_DATA */
436 
437 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS) || \
438     (defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED) && \
439     defined(PSA_WANT_ALG_FFDH))
440 #define USAGE_GROUPS \
441     "    groups=a,b,c,d      default: \"default\" (library default)\n"  \
442     "                        example: \"secp521r1,brainpoolP512r1\"\n"  \
443     "                        - use \"none\" for empty list\n"           \
444     "                        - see mbedtls_ecp_curve_list()\n"                \
445     "                          for acceptable EC group names\n"               \
446     "                        - the following ffdh groups are supported:\n"    \
447     "                          ffdhe2048, ffdhe3072, ffdhe4096, ffdhe6144,\n" \
448     "                          ffdhe8192\n"
449 #else
450 #define USAGE_GROUPS ""
451 #endif
452 
453 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
454 #define USAGE_SIG_ALGS \
455     "    sig_algs=a,b,c,d      default: \"default\" (library default)\n"  \
456     "                          example: \"ecdsa_secp256r1_sha256,ecdsa_secp384r1_sha384\"\n"
457 #else
458 #define USAGE_SIG_ALGS ""
459 #endif
460 
461 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
462 #define USAGE_SERIALIZATION \
463     "    serialize=%%d        default: 0 (do not serialize/deserialize)\n"     \
464     "                        options: 1 (serialize)\n"                         \
465     "                                 2 (serialize with re-initialization)\n"  \
466     "    context_file=%%s     The file path to write a serialized connection\n" \
467     "                        in the form of base64 code (serialize option\n"   \
468     "                        must be set)\n"                                   \
469     "                         default: \"\" (do nothing)\n"                    \
470     "                         option: a file path\n"
471 #else
472 #define USAGE_SERIALIZATION ""
473 #endif
474 
475 #define USAGE_KEY_OPAQUE_ALGS \
476     "    key_opaque_algs=%%s  Allowed opaque key 1 algorithms.\n"                      \
477     "                        comma-separated pair of values among the following:\n"    \
478     "                        rsa-sign-pkcs1, rsa-sign-pss, rsa-sign-pss-sha256,\n"     \
479     "                        rsa-sign-pss-sha384, rsa-sign-pss-sha512, rsa-decrypt,\n" \
480     "                        ecdsa-sign, ecdh, none (only acceptable for\n"            \
481     "                        the second value).\n"                                     \
482     "    key_opaque_algs2=%%s Allowed opaque key 2 algorithms.\n"                      \
483     "                        comma-separated pair of values among the following:\n"    \
484     "                        rsa-sign-pkcs1, rsa-sign-pss, rsa-sign-pss-sha256,\n"     \
485     "                        rsa-sign-pss-sha384, rsa-sign-pss-sha512, rsa-decrypt,\n" \
486     "                        ecdsa-sign, ecdh, none (only acceptable for\n"            \
487     "                        the second value).\n"
488 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
489 #define USAGE_TLS1_3_KEY_EXCHANGE_MODES \
490     "    tls13_kex_modes=%%s   default: all\n"     \
491     "                          options: psk, psk_ephemeral, psk_all, ephemeral,\n"  \
492     "                                   ephemeral_all, all, psk_or_ephemeral\n"
493 #else
494 #define USAGE_TLS1_3_KEY_EXCHANGE_MODES ""
495 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
496 
497 
498 /* USAGE is arbitrarily split to stay under the portable string literal
499  * length limit: 4095 bytes in C99. */
500 #define USAGE1 \
501     "\n usage: ssl_server2 param=<>...\n"                   \
502     "\n acceptable parameters:\n"                           \
503     "    server_addr=%%s      default: (all interfaces)\n"  \
504     "    server_port=%%d      default: 4433\n"              \
505     "    debug_level=%%d      default: 0 (disabled)\n"      \
506     "    build_version=%%d    default: none (disabled)\n"                     \
507     "                        option: 1 (print build version only and stop)\n" \
508     "    buffer_size=%%d      default: 200 \n" \
509     "                         (minimum: 1)\n" \
510     "    response_size=%%d    default: about 152 (basic response)\n" \
511     "                          (minimum: 0, max: 16384)\n" \
512     "                          increases buffer_size if bigger\n" \
513     "    nbio=%%d             default: 0 (blocking I/O)\n"  \
514     "                        options: 1 (non-blocking), 2 (added delays)\n" \
515     "    event=%%d            default: 0 (loop)\n"                            \
516     "                        options: 1 (level-triggered, implies nbio=1),\n" \
517     "    read_timeout=%%d     default: 0 ms (no timeout)\n"    \
518     "\n"                                                    \
519     USAGE_DTLS                                              \
520     USAGE_SRTP                                              \
521     USAGE_COOKIES                                           \
522     USAGE_ANTI_REPLAY                                       \
523     USAGE_BADMAC_LIMIT                                      \
524     "\n"
525 #define USAGE2 \
526     "    auth_mode=%%s        default: (library default: none)\n"      \
527     "                        options: none, optional, required\n" \
528     "    cert_req_ca_list=%%d default: 1 (send ca list)\n"  \
529     "                        options: 1 (send ca list), 0 (don't send)\n" \
530     "                                 2 (send conf dn hint), 3 (send hs dn hint)\n" \
531     USAGE_IO                                                \
532     USAGE_KEY_OPAQUE                                        \
533     "\n"                                                    \
534     USAGE_PSK                                               \
535     USAGE_CA_CALLBACK                                       \
536     USAGE_ECJPAKE                                           \
537     "\n"
538 #define USAGE3 \
539     "    allow_legacy=%%d     default: (library default: no)\n"      \
540     USAGE_RENEGO                                            \
541     "    exchanges=%%d        default: 1\n"                 \
542     "\n"                                                    \
543     USAGE_TICKETS                                           \
544     USAGE_EAP_TLS                                           \
545     USAGE_REPRODUCIBLE                                      \
546     USAGE_NSS_KEYLOG                                        \
547     USAGE_NSS_KEYLOG_FILE                                   \
548     USAGE_CACHE                                             \
549     USAGE_CACHE_TIME                                        \
550     USAGE_MAX_FRAG_LEN                                      \
551     USAGE_ALPN                                              \
552     USAGE_EMS                                               \
553     USAGE_ETM                                               \
554     USAGE_GROUPS                                            \
555     USAGE_SIG_ALGS                                          \
556     USAGE_KEY_OPAQUE_ALGS                                   \
557     "\n"
558 
559 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
560 #define TLS1_3_VERSION_OPTIONS  ", tls13"
561 #else /* MBEDTLS_SSL_PROTO_TLS1_3 */
562 #define TLS1_3_VERSION_OPTIONS  ""
563 #endif /* !MBEDTLS_SSL_PROTO_TLS1_3 */
564 
565 #define USAGE4 \
566     USAGE_SSL_ASYNC                                         \
567     USAGE_SNI                                               \
568     "    allow_sha1=%%d       default: 0\n"                                   \
569     "    min_version=%%s      default: (library default: tls12)\n"            \
570     "    max_version=%%s      default: (library default: tls12)\n"            \
571     "    force_version=%%s    default: \"\" (none)\n"                         \
572     "                         options: tls12, dtls12" TLS1_3_VERSION_OPTIONS  \
573     "\n\n"                                                                    \
574     "    force_ciphersuite=<name>    default: all enabled\n"                  \
575     USAGE_TLS1_3_KEY_EXCHANGE_MODES                                           \
576     "    query_config=<name>         return 0 if the specified\n"             \
577     "                                configuration macro is defined and 1\n"  \
578     "                                otherwise. The expansion of the macro\n" \
579     "                                is printed if it is defined\n"           \
580     USAGE_SERIALIZATION                                                       \
581     " acceptable ciphersuite names:\n"
582 
583 #define PUT_UINT64_BE(out_be, in_le, i)                                   \
584     {                                                                       \
585         (out_be)[(i) + 0] = (unsigned char) (((in_le) >> 56) & 0xFF);    \
586         (out_be)[(i) + 1] = (unsigned char) (((in_le) >> 48) & 0xFF);    \
587         (out_be)[(i) + 2] = (unsigned char) (((in_le) >> 40) & 0xFF);    \
588         (out_be)[(i) + 3] = (unsigned char) (((in_le) >> 32) & 0xFF);    \
589         (out_be)[(i) + 4] = (unsigned char) (((in_le) >> 24) & 0xFF);    \
590         (out_be)[(i) + 5] = (unsigned char) (((in_le) >> 16) & 0xFF);    \
591         (out_be)[(i) + 6] = (unsigned char) (((in_le) >> 8) & 0xFF);    \
592         (out_be)[(i) + 7] = (unsigned char) (((in_le) >> 0) & 0xFF);    \
593     }
594 
595 /* This is global so it can be easily accessed by callback functions */
596 rng_context_t rng;
597 
598 /*
599  * global options
600  */
601 struct options {
602     const char *server_addr;    /* address on which the ssl service runs    */
603     const char *server_port;    /* port on which the ssl service runs       */
604     int debug_level;            /* level of debugging                       */
605     int nbio;                   /* should I/O be blocking?                  */
606     int event;                  /* loop or event-driven IO? level or edge triggered? */
607     uint32_t read_timeout;      /* timeout on mbedtls_ssl_read() in milliseconds    */
608     int response_size;          /* pad response with header to requested size */
609     uint16_t buffer_size;       /* IO buffer size */
610     const char *ca_file;        /* the file with the CA certificate(s)      */
611     const char *ca_path;        /* the path with the CA certificate(s) reside */
612     const char *crt_file;       /* the file with the server certificate     */
613     const char *key_file;       /* the file with the server key             */
614     int key_opaque;             /* handle private key as if it were opaque  */
615     const char *key_pwd;        /* the password for the server key          */
616     const char *crt_file2;      /* the file with the 2nd server certificate */
617     const char *key_file2;      /* the file with the 2nd server key         */
618     const char *key_pwd2;       /* the password for the 2nd server key      */
619     const char *async_operations; /* supported SSL asynchronous operations  */
620     int async_private_delay1;   /* number of times f_async_resume needs to be called for key 1, or -1 for no async */
621     int async_private_delay2;   /* number of times f_async_resume needs to be called for key 2, or -1 for no async */
622     int async_private_error;    /* inject error in async private callback */
623 #if defined(MBEDTLS_USE_PSA_CRYPTO)
624     int psk_opaque;
625     int psk_list_opaque;
626 #endif
627 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
628     int ca_callback;            /* Use callback for trusted certificate list */
629 #endif
630     const char *psk;            /* the pre-shared key                       */
631     const char *psk_identity;   /* the pre-shared key identity              */
632     char *psk_list;             /* list of PSK id/key pairs for callback    */
633     const char *ecjpake_pw;     /* the EC J-PAKE password                   */
634 #if defined(MBEDTLS_USE_PSA_CRYPTO)
635     int ecjpake_pw_opaque;      /* set to 1 to use the opaque method for setting the password */
636 #endif
637     int force_ciphersuite[2];   /* protocol/ciphersuite to use, or all      */
638 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
639     int tls13_kex_modes;        /* supported TLS 1.3 key exchange modes     */
640 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
641     int renegotiation;          /* enable / disable renegotiation           */
642     int allow_legacy;           /* allow legacy renegotiation               */
643     int renegotiate;            /* attempt renegotiation?                   */
644     int renego_delay;           /* delay before enforcing renegotiation     */
645     uint64_t renego_period;     /* period for automatic renegotiation       */
646     int exchanges;              /* number of data exchanges                 */
647     int min_version;            /* minimum protocol version accepted        */
648     int max_version;            /* maximum protocol version accepted        */
649     int allow_sha1;             /* flag for SHA-1 support                   */
650     int auth_mode;              /* verify mode for connection               */
651     int cert_req_ca_list;       /* should we send the CA list?              */
652     int cert_req_dn_hint;       /* mode to set DN hints for CA list to send */
653     unsigned char mfl_code;     /* code for maximum fragment length         */
654     int trunc_hmac;             /* accept truncated hmac?                   */
655     int tickets;                /* enable / disable session tickets         */
656     int dummy_ticket;           /* enable / disable dummy ticket generator  */
657     int ticket_rotate;          /* session ticket rotate (code coverage)    */
658     int ticket_timeout;         /* session ticket lifetime                  */
659     int ticket_aead;            /* session ticket protection                */
660     int cache_max;              /* max number of session cache entries      */
661 #if defined(MBEDTLS_HAVE_TIME)
662     int cache_timeout;          /* expiration delay of session cache entries*/
663 #endif
664     int cache_remove;           /* enable / disable cache entry removal     */
665     char *sni;                  /* string describing sni information        */
666     const char *groups;         /* list of supported groups                 */
667     const char *sig_algs;       /* supported TLS 1.3 signature algorithms   */
668     const char *alpn_string;    /* ALPN supported protocols                 */
669     const char *dhm_file;       /* the file with the DH parameters          */
670     int extended_ms;            /* allow negotiation of extended MS?        */
671     int etm;                    /* allow negotiation of encrypt-then-MAC?   */
672     int transport;              /* TLS or DTLS?                             */
673     int cookies;                /* Use cookies for DTLS? -1 to break them   */
674     int anti_replay;            /* Use anti-replay for DTLS? -1 for default */
675     uint32_t hs_to_min;         /* Initial value of DTLS handshake timer    */
676     uint32_t hs_to_max;         /* Max value of DTLS handshake timer        */
677     int dtls_mtu;               /* UDP Maximum transport unit for DTLS       */
678     int dgram_packing;          /* allow/forbid datagram packing            */
679     int badmac_limit;           /* Limit of records with bad MAC            */
680     int eap_tls;                /* derive EAP-TLS keying material?          */
681     int nss_keylog;             /* export NSS key log material              */
682     const char *nss_keylog_file; /* NSS key log file                        */
683     int cid_enabled;            /* whether to use the CID extension or not  */
684     int cid_enabled_renego;     /* whether to use the CID extension or not
685                                  * during renegotiation                     */
686     const char *cid_val;        /* the CID to use for incoming messages     */
687     int serialize;              /* serialize/deserialize connection         */
688     const char *context_file;   /* the file to write a serialized connection
689                                  * in the form of base64 code (serialize
690                                  * option must be set)                      */
691     const char *cid_val_renego; /* the CID to use for incoming messages
692                                  * after renegotiation                      */
693     int reproducible;           /* make communication reproducible          */
694     uint32_t max_early_data_size; /* max amount of early data               */
695     int query_config_mode;      /* whether to read config                   */
696     int use_srtp;               /* Support SRTP                             */
697     int force_srtp_profile;     /* SRTP protection profile to use or all    */
698     int support_mki;            /* The dtls mki mki support                 */
699     const char *key1_opaque_alg1; /* Allowed opaque key 1 alg 1            */
700     const char *key1_opaque_alg2; /* Allowed opaque key 1 alg 2            */
701     const char *key2_opaque_alg1; /* Allowed opaque key 2 alg 1            */
702     const char *key2_opaque_alg2; /* Allowed opaque key 2 alg 2            */
703 } opt;
704 
705 #include "ssl_test_common_source.c"
706 
707 /*
708  * Return authmode from string, or -1 on error
709  */
get_auth_mode(const char * s)710 static int get_auth_mode(const char *s)
711 {
712     if (strcmp(s, "none") == 0) {
713         return MBEDTLS_SSL_VERIFY_NONE;
714     }
715     if (strcmp(s, "optional") == 0) {
716         return MBEDTLS_SSL_VERIFY_OPTIONAL;
717     }
718     if (strcmp(s, "required") == 0) {
719         return MBEDTLS_SSL_VERIFY_REQUIRED;
720     }
721 
722     return -1;
723 }
724 
725 /*
726  * Used by sni_parse and psk_parse to handle comma-separated lists
727  */
728 #define GET_ITEM(dst)         \
729     do                          \
730     {                           \
731         (dst) = p;              \
732         while (*p != ',')      \
733         if (++p > end)     \
734         goto error;     \
735         *p++ = '\0';            \
736     } while (0)
737 
738 #if defined(SNI_OPTION)
739 typedef struct _sni_entry sni_entry;
740 
741 struct _sni_entry {
742     const char *name;
743     mbedtls_x509_crt *cert;
744     mbedtls_pk_context *key;
745     mbedtls_x509_crt *ca;
746     mbedtls_x509_crl *crl;
747     int authmode;
748     sni_entry *next;
749 };
750 
sni_free(sni_entry * head)751 void sni_free(sni_entry *head)
752 {
753     sni_entry *cur = head, *next;
754 
755     while (cur != NULL) {
756         mbedtls_x509_crt_free(cur->cert);
757         mbedtls_free(cur->cert);
758 
759         mbedtls_pk_free(cur->key);
760         mbedtls_free(cur->key);
761 
762         mbedtls_x509_crt_free(cur->ca);
763         mbedtls_free(cur->ca);
764 #if defined(MBEDTLS_X509_CRL_PARSE_C)
765         mbedtls_x509_crl_free(cur->crl);
766         mbedtls_free(cur->crl);
767 #endif
768         next = cur->next;
769         mbedtls_free(cur);
770         cur = next;
771     }
772 }
773 
774 /*
775  * Parse a string of sextuples name1,crt1,key1,ca1,crl1,auth1[,...]
776  * into a usable sni_entry list. For ca1, crl1, auth1, the special value
777  * '-' means unset. If ca1 is unset, then crl1 is ignored too.
778  *
779  * Modifies the input string! This is not production quality!
780  */
sni_parse(char * sni_string)781 sni_entry *sni_parse(char *sni_string)
782 {
783     sni_entry *cur = NULL, *new = NULL;
784     char *p = sni_string;
785     char *end = p;
786     char *crt_file, *key_file, *ca_file, *auth_str;
787 #if defined(MBEDTLS_X509_CRL_PARSE_C)
788     char *crl_file;
789 #endif
790 
791     while (*end != '\0') {
792         ++end;
793     }
794     *end = ',';
795 
796     while (p <= end) {
797         if ((new = mbedtls_calloc(1, sizeof(sni_entry))) == NULL) {
798             sni_free(cur);
799             return NULL;
800         }
801 
802         GET_ITEM(new->name);
803         GET_ITEM(crt_file);
804         GET_ITEM(key_file);
805         GET_ITEM(ca_file);
806 #if defined(MBEDTLS_X509_CRL_PARSE_C)
807         GET_ITEM(crl_file);
808 #endif
809         GET_ITEM(auth_str);
810 
811         if ((new->cert = mbedtls_calloc(1, sizeof(mbedtls_x509_crt))) == NULL ||
812             (new->key = mbedtls_calloc(1, sizeof(mbedtls_pk_context))) == NULL) {
813             goto error;
814         }
815 
816         mbedtls_x509_crt_init(new->cert);
817         mbedtls_pk_init(new->key);
818 
819         if (mbedtls_x509_crt_parse_file(new->cert, crt_file) != 0 ||
820             mbedtls_pk_parse_keyfile(new->key, key_file, "", rng_get, &rng) != 0) {
821             goto error;
822         }
823 
824         if (strcmp(ca_file, "-") != 0) {
825             if ((new->ca = mbedtls_calloc(1, sizeof(mbedtls_x509_crt))) == NULL) {
826                 goto error;
827             }
828 
829             mbedtls_x509_crt_init(new->ca);
830 
831             if (mbedtls_x509_crt_parse_file(new->ca, ca_file) != 0) {
832                 goto error;
833             }
834         }
835 
836 #if defined(MBEDTLS_X509_CRL_PARSE_C)
837         if (strcmp(crl_file, "-") != 0) {
838             if ((new->crl = mbedtls_calloc(1, sizeof(mbedtls_x509_crl))) == NULL) {
839                 goto error;
840             }
841 
842             mbedtls_x509_crl_init(new->crl);
843 
844             if (mbedtls_x509_crl_parse_file(new->crl, crl_file) != 0) {
845                 goto error;
846             }
847         }
848 #endif
849 
850         if (strcmp(auth_str, "-") != 0) {
851             if ((new->authmode = get_auth_mode(auth_str)) < 0) {
852                 goto error;
853             }
854         } else {
855             new->authmode = DFL_AUTH_MODE;
856         }
857 
858         new->next = cur;
859         cur = new;
860     }
861 
862     return cur;
863 
864 error:
865     sni_free(new);
866     sni_free(cur);
867     return NULL;
868 }
869 
870 /*
871  * SNI callback.
872  */
sni_callback(void * p_info,mbedtls_ssl_context * ssl,const unsigned char * name,size_t name_len)873 int sni_callback(void *p_info, mbedtls_ssl_context *ssl,
874                  const unsigned char *name, size_t name_len)
875 {
876     const sni_entry *cur = (const sni_entry *) p_info;
877 
878     /* preserve behavior which checks for SNI match in sni_callback() for
879      * the benefits of tests using sni_callback(), even though the actual
880      * certificate assignment has moved to certificate selection callback
881      * in this application.  This exercises sni_callback and cert_callback
882      * even though real applications might choose to do this differently.
883      * Application might choose to save name and name_len in user_data for
884      * later use in certificate selection callback.
885      */
886     while (cur != NULL) {
887         if (name_len == strlen(cur->name) &&
888             memcmp(name, cur->name, name_len) == 0) {
889             void *p;
890             *(const void **)&p = cur;
891             mbedtls_ssl_set_user_data_p(ssl, p);
892             return 0;
893         }
894 
895         cur = cur->next;
896     }
897 
898     return -1;
899 }
900 
901 /*
902  * server certificate selection callback.
903  */
cert_callback(mbedtls_ssl_context * ssl)904 int cert_callback(mbedtls_ssl_context *ssl)
905 {
906     const sni_entry *cur = (sni_entry *) mbedtls_ssl_get_user_data_p(ssl);
907     if (cur != NULL) {
908         /*(exercise mbedtls_ssl_get_hs_sni(); not otherwise used here)*/
909         size_t name_len;
910         const unsigned char *name = mbedtls_ssl_get_hs_sni(ssl, &name_len);
911         if (strlen(cur->name) != name_len ||
912             memcmp(cur->name, name, name_len) != 0) {
913             return MBEDTLS_ERR_SSL_DECODE_ERROR;
914         }
915 
916         if (cur->ca != NULL) {
917             mbedtls_ssl_set_hs_ca_chain(ssl, cur->ca, cur->crl);
918         }
919 
920         if (cur->authmode != DFL_AUTH_MODE) {
921             mbedtls_ssl_set_hs_authmode(ssl, cur->authmode);
922         }
923 
924         return mbedtls_ssl_set_hs_own_cert(ssl, cur->cert, cur->key);
925     }
926 
927     return 0;
928 }
929 
930 #endif /* SNI_OPTION */
931 
932 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
933 
934 typedef struct _psk_entry psk_entry;
935 
936 struct _psk_entry {
937     const char *name;
938     size_t key_len;
939     unsigned char key[MBEDTLS_PSK_MAX_LEN];
940 #if defined(MBEDTLS_USE_PSA_CRYPTO)
941     mbedtls_svc_key_id_t slot;
942 #endif /* MBEDTLS_USE_PSA_CRYPTO */
943     psk_entry *next;
944 };
945 
946 /*
947  * Free a list of psk_entry's
948  */
psk_free(psk_entry * head)949 int psk_free(psk_entry *head)
950 {
951     psk_entry *next;
952 
953     while (head != NULL) {
954 #if defined(MBEDTLS_USE_PSA_CRYPTO)
955         psa_status_t status;
956         mbedtls_svc_key_id_t const slot = head->slot;
957 
958         if (MBEDTLS_SVC_KEY_ID_GET_KEY_ID(slot) != 0) {
959             status = psa_destroy_key(slot);
960             if (status != PSA_SUCCESS) {
961                 return status;
962             }
963         }
964 #endif /* MBEDTLS_USE_PSA_CRYPTO */
965 
966         next = head->next;
967         mbedtls_free(head);
968         head = next;
969     }
970 
971     return 0;
972 }
973 
974 /*
975  * Parse a string of pairs name1,key1[,name2,key2[,...]]
976  * into a usable psk_entry list.
977  *
978  * Modifies the input string! This is not production quality!
979  */
psk_parse(char * psk_string)980 psk_entry *psk_parse(char *psk_string)
981 {
982     psk_entry *cur = NULL, *new = NULL;
983     char *p = psk_string;
984     char *end = p;
985     char *key_hex;
986 
987     while (*end != '\0') {
988         ++end;
989     }
990     *end = ',';
991 
992     while (p <= end) {
993         if ((new = mbedtls_calloc(1, sizeof(psk_entry))) == NULL) {
994             goto error;
995         }
996 
997         memset(new, 0, sizeof(psk_entry));
998 
999         GET_ITEM(new->name);
1000         GET_ITEM(key_hex);
1001 
1002         if (mbedtls_test_unhexify(new->key, MBEDTLS_PSK_MAX_LEN,
1003                                   key_hex, &new->key_len) != 0) {
1004             goto error;
1005         }
1006 
1007         new->next = cur;
1008         cur = new;
1009     }
1010 
1011     return cur;
1012 
1013 error:
1014     psk_free(new);
1015     psk_free(cur);
1016     return 0;
1017 }
1018 
1019 /*
1020  * PSK callback
1021  */
psk_callback(void * p_info,mbedtls_ssl_context * ssl,const unsigned char * name,size_t name_len)1022 int psk_callback(void *p_info, mbedtls_ssl_context *ssl,
1023                  const unsigned char *name, size_t name_len)
1024 {
1025     psk_entry *cur = (psk_entry *) p_info;
1026 
1027     while (cur != NULL) {
1028         if (name_len == strlen(cur->name) &&
1029             memcmp(name, cur->name, name_len) == 0) {
1030 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1031             if (MBEDTLS_SVC_KEY_ID_GET_KEY_ID(cur->slot) != 0) {
1032                 return mbedtls_ssl_set_hs_psk_opaque(ssl, cur->slot);
1033             } else
1034 #endif
1035             return mbedtls_ssl_set_hs_psk(ssl, cur->key, cur->key_len);
1036         }
1037 
1038         cur = cur->next;
1039     }
1040 
1041     return -1;
1042 }
1043 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
1044 
1045 static mbedtls_net_context listen_fd, client_fd;
1046 
1047 /* Interruption handler to ensure clean exit (for valgrind testing) */
1048 #if !defined(_WIN32)
1049 static int received_sigterm = 0;
term_handler(int sig)1050 void term_handler(int sig)
1051 {
1052     ((void) sig);
1053     received_sigterm = 1;
1054     mbedtls_net_free(&listen_fd);   /* causes mbedtls_net_accept() to abort */
1055     mbedtls_net_free(&client_fd);   /* causes net_read() to abort */
1056 }
1057 #endif
1058 
1059 /** Return true if \p ret is a status code indicating that there is an
1060  * operation in progress on an SSL connection, and false if it indicates
1061  * success or a fatal error.
1062  *
1063  * The possible operations in progress are:
1064  *
1065  * - A read, when the SSL input buffer does not contain a full message.
1066  * - A write, when the SSL output buffer contains some data that has not
1067  *   been sent over the network yet.
1068  * - An asynchronous callback that has not completed yet. */
mbedtls_status_is_ssl_in_progress(int ret)1069 static int mbedtls_status_is_ssl_in_progress(int ret)
1070 {
1071     return ret == MBEDTLS_ERR_SSL_WANT_READ ||
1072            ret == MBEDTLS_ERR_SSL_WANT_WRITE ||
1073            ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS;
1074 }
1075 
1076 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
1077 typedef struct {
1078     mbedtls_x509_crt *cert; /*!< Certificate corresponding to the key */
1079     mbedtls_pk_context *pk; /*!< Private key */
1080     unsigned delay; /*!< Number of resume steps to go through */
1081     unsigned pk_owned : 1; /*!< Whether to free the pk object on exit */
1082 } ssl_async_key_slot_t;
1083 
1084 typedef enum {
1085     SSL_ASYNC_INJECT_ERROR_NONE = 0, /*!< Let the callbacks succeed */
1086     SSL_ASYNC_INJECT_ERROR_START, /*!< Inject error during start */
1087     SSL_ASYNC_INJECT_ERROR_CANCEL, /*!< Close the connection after async start */
1088     SSL_ASYNC_INJECT_ERROR_RESUME, /*!< Inject error during resume */
1089 #define SSL_ASYNC_INJECT_ERROR_MAX SSL_ASYNC_INJECT_ERROR_RESUME
1090 } ssl_async_inject_error_t;
1091 
1092 typedef struct {
1093     ssl_async_key_slot_t slots[4]; /* key, key2, sni1, sni2 */
1094     size_t slots_used;
1095     ssl_async_inject_error_t inject_error;
1096     int (*f_rng)(void *, unsigned char *, size_t);
1097     void *p_rng;
1098 } ssl_async_key_context_t;
1099 
ssl_async_set_key(ssl_async_key_context_t * ctx,mbedtls_x509_crt * cert,mbedtls_pk_context * pk,int pk_take_ownership,unsigned delay)1100 int ssl_async_set_key(ssl_async_key_context_t *ctx,
1101                       mbedtls_x509_crt *cert,
1102                       mbedtls_pk_context *pk,
1103                       int pk_take_ownership,
1104                       unsigned delay)
1105 {
1106     if (ctx->slots_used >= sizeof(ctx->slots) / sizeof(*ctx->slots)) {
1107         return -1;
1108     }
1109     ctx->slots[ctx->slots_used].cert = cert;
1110     ctx->slots[ctx->slots_used].pk = pk;
1111     ctx->slots[ctx->slots_used].delay = delay;
1112     ctx->slots[ctx->slots_used].pk_owned = pk_take_ownership;
1113     ++ctx->slots_used;
1114     return 0;
1115 }
1116 
1117 #define SSL_ASYNC_INPUT_MAX_SIZE 512
1118 
1119 typedef enum {
1120     ASYNC_OP_SIGN,
1121     ASYNC_OP_DECRYPT,
1122 } ssl_async_operation_type_t;
1123 
1124 typedef struct {
1125     unsigned slot;
1126     ssl_async_operation_type_t operation_type;
1127     mbedtls_md_type_t md_alg;
1128     unsigned char input[SSL_ASYNC_INPUT_MAX_SIZE];
1129     size_t input_len;
1130     unsigned remaining_delay;
1131 } ssl_async_operation_context_t;
1132 
1133 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1134 
1135 /* Note that ssl_async_operation_type_t and the array below need to be kept in sync!
1136  * `ssl_async_operation_names[op]` is the name of op for each value `op`
1137  * of type `ssl_async_operation_type_t`. */
1138 static const char *const ssl_async_operation_names[] =
1139 {
1140     "sign",
1141     "decrypt",
1142 };
1143 
ssl_async_start(mbedtls_ssl_context * ssl,mbedtls_x509_crt * cert,ssl_async_operation_type_t op_type,mbedtls_md_type_t md_alg,const unsigned char * input,size_t input_len)1144 static int ssl_async_start(mbedtls_ssl_context *ssl,
1145                            mbedtls_x509_crt *cert,
1146                            ssl_async_operation_type_t op_type,
1147                            mbedtls_md_type_t md_alg,
1148                            const unsigned char *input,
1149                            size_t input_len)
1150 {
1151     ssl_async_key_context_t *config_data =
1152         mbedtls_ssl_conf_get_async_config_data(ssl->conf);
1153     unsigned slot;
1154     ssl_async_operation_context_t *ctx = NULL;
1155     const char *op_name = ssl_async_operation_names[op_type];
1156 
1157     {
1158         char dn[100];
1159         if (mbedtls_x509_dn_gets(dn, sizeof(dn), &cert->subject) > 0) {
1160             mbedtls_printf("Async %s callback: looking for DN=%s\n",
1161                            op_name, dn);
1162         }
1163     }
1164 
1165     /* Look for a private key that matches the public key in cert.
1166      * Since this test code has the private key inside Mbed TLS,
1167      * we call mbedtls_pk_check_pair to match a private key with the
1168      * public key. */
1169     for (slot = 0; slot < config_data->slots_used; slot++) {
1170         if (mbedtls_pk_check_pair(&cert->pk,
1171                                   config_data->slots[slot].pk,
1172                                   rng_get, &rng) == 0) {
1173             break;
1174         }
1175     }
1176     if (slot == config_data->slots_used) {
1177         mbedtls_printf("Async %s callback: no key matches this certificate.\n",
1178                        op_name);
1179         return MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH;
1180     }
1181     mbedtls_printf("Async %s callback: using key slot %u, delay=%u.\n",
1182                    op_name, slot, config_data->slots[slot].delay);
1183 
1184     if (config_data->inject_error == SSL_ASYNC_INJECT_ERROR_START) {
1185         mbedtls_printf("Async %s callback: injected error\n", op_name);
1186         return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
1187     }
1188 
1189     if (input_len > SSL_ASYNC_INPUT_MAX_SIZE) {
1190         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
1191     }
1192 
1193     ctx = mbedtls_calloc(1, sizeof(*ctx));
1194     if (ctx == NULL) {
1195         return MBEDTLS_ERR_SSL_ALLOC_FAILED;
1196     }
1197     ctx->slot = slot;
1198     ctx->operation_type = op_type;
1199     ctx->md_alg = md_alg;
1200     memcpy(ctx->input, input, input_len);
1201     ctx->input_len = input_len;
1202     ctx->remaining_delay = config_data->slots[slot].delay;
1203     mbedtls_ssl_set_async_operation_data(ssl, ctx);
1204 
1205     if (ctx->remaining_delay == 0) {
1206         return 0;
1207     } else {
1208         return MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS;
1209     }
1210 }
1211 
ssl_async_sign(mbedtls_ssl_context * ssl,mbedtls_x509_crt * cert,mbedtls_md_type_t md_alg,const unsigned char * hash,size_t hash_len)1212 static int ssl_async_sign(mbedtls_ssl_context *ssl,
1213                           mbedtls_x509_crt *cert,
1214                           mbedtls_md_type_t md_alg,
1215                           const unsigned char *hash,
1216                           size_t hash_len)
1217 {
1218     return ssl_async_start(ssl, cert,
1219                            ASYNC_OP_SIGN, md_alg,
1220                            hash, hash_len);
1221 }
1222 
ssl_async_decrypt(mbedtls_ssl_context * ssl,mbedtls_x509_crt * cert,const unsigned char * input,size_t input_len)1223 static int ssl_async_decrypt(mbedtls_ssl_context *ssl,
1224                              mbedtls_x509_crt *cert,
1225                              const unsigned char *input,
1226                              size_t input_len)
1227 {
1228     return ssl_async_start(ssl, cert,
1229                            ASYNC_OP_DECRYPT, MBEDTLS_MD_NONE,
1230                            input, input_len);
1231 }
1232 
ssl_async_resume(mbedtls_ssl_context * ssl,unsigned char * output,size_t * output_len,size_t output_size)1233 static int ssl_async_resume(mbedtls_ssl_context *ssl,
1234                             unsigned char *output,
1235                             size_t *output_len,
1236                             size_t output_size)
1237 {
1238     ssl_async_operation_context_t *ctx = mbedtls_ssl_get_async_operation_data(ssl);
1239     ssl_async_key_context_t *config_data =
1240         mbedtls_ssl_conf_get_async_config_data(ssl->conf);
1241     ssl_async_key_slot_t *key_slot = &config_data->slots[ctx->slot];
1242     int ret;
1243     const char *op_name;
1244 
1245     if (ctx->remaining_delay > 0) {
1246         --ctx->remaining_delay;
1247         mbedtls_printf("Async resume (slot %u): call %u more times.\n",
1248                        ctx->slot, ctx->remaining_delay);
1249         return MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS;
1250     }
1251 
1252     switch (ctx->operation_type) {
1253         case ASYNC_OP_DECRYPT:
1254             ret = mbedtls_pk_decrypt(key_slot->pk,
1255                                      ctx->input, ctx->input_len,
1256                                      output, output_len, output_size,
1257                                      config_data->f_rng, config_data->p_rng);
1258             break;
1259         case ASYNC_OP_SIGN:
1260             ret = mbedtls_pk_sign(key_slot->pk,
1261                                   ctx->md_alg,
1262                                   ctx->input, ctx->input_len,
1263                                   output, output_size, output_len,
1264                                   config_data->f_rng, config_data->p_rng);
1265             break;
1266         default:
1267             mbedtls_printf(
1268                 "Async resume (slot %u): unknown operation type %ld. This shouldn't happen.\n",
1269                 ctx->slot,
1270                 (long) ctx->operation_type);
1271             mbedtls_free(ctx);
1272             return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
1273             break;
1274     }
1275 
1276     op_name = ssl_async_operation_names[ctx->operation_type];
1277 
1278     if (config_data->inject_error == SSL_ASYNC_INJECT_ERROR_RESUME) {
1279         mbedtls_printf("Async resume callback: %s done but injected error\n",
1280                        op_name);
1281         mbedtls_free(ctx);
1282         return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
1283     }
1284 
1285     mbedtls_printf("Async resume (slot %u): %s done, status=%d.\n",
1286                    ctx->slot, op_name, ret);
1287     mbedtls_free(ctx);
1288     return ret;
1289 }
1290 
ssl_async_cancel(mbedtls_ssl_context * ssl)1291 static void ssl_async_cancel(mbedtls_ssl_context *ssl)
1292 {
1293     ssl_async_operation_context_t *ctx = mbedtls_ssl_get_async_operation_data(ssl);
1294     mbedtls_printf("Async cancel callback.\n");
1295     mbedtls_free(ctx);
1296 }
1297 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
1298 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
1299 
1300 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1301 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
psa_setup_psk_key_slot(mbedtls_svc_key_id_t * slot,psa_algorithm_t alg,unsigned char * psk,size_t psk_len)1302 static psa_status_t psa_setup_psk_key_slot(mbedtls_svc_key_id_t *slot,
1303                                            psa_algorithm_t alg,
1304                                            unsigned char *psk,
1305                                            size_t psk_len)
1306 {
1307     psa_status_t status;
1308     psa_key_attributes_t key_attributes;
1309 
1310     key_attributes = psa_key_attributes_init();
1311     psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
1312     psa_set_key_algorithm(&key_attributes, alg);
1313     psa_set_key_type(&key_attributes, PSA_KEY_TYPE_DERIVE);
1314 
1315     status = psa_import_key(&key_attributes, psk, psk_len, slot);
1316     if (status != PSA_SUCCESS) {
1317         fprintf(stderr, "IMPORT\n");
1318         return status;
1319     }
1320 
1321     return PSA_SUCCESS;
1322 }
1323 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
1324 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1325 
1326 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
report_cid_usage(mbedtls_ssl_context * ssl,const char * additional_description)1327 int report_cid_usage(mbedtls_ssl_context *ssl,
1328                      const char *additional_description)
1329 {
1330     int ret;
1331     unsigned char peer_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX];
1332     size_t peer_cid_len;
1333     int cid_negotiated;
1334 
1335     if (opt.transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1336         return 0;
1337     }
1338 
1339     /* Check if the use of a CID has been negotiated */
1340     ret = mbedtls_ssl_get_peer_cid(ssl, &cid_negotiated,
1341                                    peer_cid, &peer_cid_len);
1342     if (ret != 0) {
1343         mbedtls_printf(" failed\n  ! mbedtls_ssl_get_peer_cid returned -0x%x\n\n",
1344                        (unsigned int) -ret);
1345         return ret;
1346     }
1347 
1348     if (cid_negotiated == MBEDTLS_SSL_CID_DISABLED) {
1349         if (opt.cid_enabled == MBEDTLS_SSL_CID_ENABLED) {
1350             mbedtls_printf("(%s) Use of Connection ID was not offered by client.\n",
1351                            additional_description);
1352         }
1353     } else {
1354         size_t idx = 0;
1355         mbedtls_printf("(%s) Use of Connection ID has been negotiated.\n",
1356                        additional_description);
1357         mbedtls_printf("(%s) Peer CID (length %u Bytes): ",
1358                        additional_description,
1359                        (unsigned) peer_cid_len);
1360         while (idx < peer_cid_len) {
1361             mbedtls_printf("%02x ", peer_cid[idx]);
1362             idx++;
1363         }
1364         mbedtls_printf("\n");
1365     }
1366 
1367     return 0;
1368 }
1369 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1370 
1371 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_HAVE_TIME)
put_unaligned_uint32(void * p,uint32_t x)1372 static inline void put_unaligned_uint32(void *p, uint32_t x)
1373 {
1374     memcpy(p, &x, sizeof(x));
1375 }
1376 
1377 /* Functions for session ticket tests */
dummy_ticket_write(void * p_ticket,const mbedtls_ssl_session * session,unsigned char * start,const unsigned char * end,size_t * tlen,uint32_t * ticket_lifetime)1378 int dummy_ticket_write(void *p_ticket, const mbedtls_ssl_session *session,
1379                        unsigned char *start, const unsigned char *end,
1380                        size_t *tlen, uint32_t *ticket_lifetime)
1381 {
1382     int ret;
1383     unsigned char *p = start;
1384     size_t clear_len;
1385     ((void) p_ticket);
1386 
1387     if (end - p < 4) {
1388         return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1389     }
1390     put_unaligned_uint32(p, 7 * 24 * 3600);
1391     *ticket_lifetime = 7 * 24 * 3600;
1392     p += 4;
1393 
1394     /* Dump session state */
1395     if ((ret = mbedtls_ssl_session_save(session, p, end - p,
1396                                         &clear_len)) != 0) {
1397         return ret;
1398     }
1399 
1400     *tlen = 4 + clear_len;
1401 
1402     return 0;
1403 }
1404 
dummy_ticket_parse(void * p_ticket,mbedtls_ssl_session * session,unsigned char * buf,size_t len)1405 int dummy_ticket_parse(void *p_ticket, mbedtls_ssl_session *session,
1406                        unsigned char *buf, size_t len)
1407 {
1408     int ret;
1409     ((void) p_ticket);
1410 
1411     if ((ret = mbedtls_ssl_session_load(session, buf + 4, len - 4)) != 0) {
1412         return ret;
1413     }
1414 
1415     switch (opt.dummy_ticket % 11) {
1416         case 1:
1417             return MBEDTLS_ERR_SSL_INVALID_MAC;
1418         case 2:
1419             return MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED;
1420         case 3:
1421             session->start = mbedtls_time(NULL) + 10;
1422             break;
1423         case 4:
1424             session->start = mbedtls_time(NULL) - 10 - 7 * 24 * 3600;
1425             break;
1426         case 5:
1427             session->start = mbedtls_time(NULL) - 10;
1428             break;
1429         case 6:
1430             session->start = mbedtls_time(NULL);
1431 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1432             session->ticket_age_add -= 1000;
1433 #endif
1434             break;
1435 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1436         case 7:
1437             session->ticket_flags = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_NONE;
1438             break;
1439         case 8:
1440             session->ticket_flags = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
1441             break;
1442         case 9:
1443             session->ticket_flags = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
1444             break;
1445         case 10:
1446             session->ticket_flags = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL;
1447             break;
1448 #endif
1449         default:
1450             break;
1451     }
1452 
1453     return ret;
1454 }
1455 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_HAVE_TIME */
1456 
main(int argc,char * argv[])1457 int main(int argc, char *argv[])
1458 {
1459     int ret = 0, len, written, frags, exchanges_left;
1460     int query_config_ret = 0;
1461     io_ctx_t io_ctx;
1462     unsigned char *buf = 0;
1463 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
1464 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1465     psa_algorithm_t alg = 0;
1466     mbedtls_svc_key_id_t psk_slot = MBEDTLS_SVC_KEY_ID_INIT;
1467 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1468     unsigned char psk[MBEDTLS_PSK_MAX_LEN];
1469     size_t psk_len = 0;
1470     psk_entry *psk_info = NULL;
1471 #endif
1472     const char *pers = "ssl_server2";
1473     unsigned char client_ip[16] = { 0 };
1474     size_t cliip_len;
1475 #if defined(MBEDTLS_SSL_COOKIE_C)
1476     mbedtls_ssl_cookie_ctx cookie_ctx;
1477 #endif
1478 
1479     mbedtls_ssl_context ssl;
1480     mbedtls_ssl_config conf;
1481 #if defined(MBEDTLS_TIMING_C)
1482     mbedtls_timing_delay_context timer;
1483 #endif
1484 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1485     unsigned char renego_period[8] = { 0 };
1486 #endif
1487 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1488     uint32_t flags;
1489     mbedtls_x509_crt cacert;
1490     mbedtls_x509_crt srvcert;
1491     mbedtls_pk_context pkey;
1492     mbedtls_x509_crt srvcert2;
1493     mbedtls_pk_context pkey2;
1494     mbedtls_x509_crt_profile crt_profile_for_test = mbedtls_x509_crt_profile_default;
1495 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1496     mbedtls_svc_key_id_t key_slot = MBEDTLS_SVC_KEY_ID_INIT; /* invalid key slot */
1497     mbedtls_svc_key_id_t key_slot2 = MBEDTLS_SVC_KEY_ID_INIT; /* invalid key slot */
1498 #endif
1499     int key_cert_init = 0, key_cert_init2 = 0;
1500 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
1501 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
1502     ssl_async_key_context_t ssl_async_keys;
1503 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
1504 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_FS_IO)
1505     mbedtls_dhm_context dhm;
1506 #endif
1507 #if defined(MBEDTLS_SSL_CACHE_C)
1508     mbedtls_ssl_cache_context cache;
1509 #endif
1510 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_TICKET_C)
1511     mbedtls_ssl_ticket_context ticket_ctx;
1512 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_TICKET_C */
1513 #if defined(SNI_OPTION)
1514     sni_entry *sni_info = NULL;
1515 #endif
1516     uint16_t group_list[GROUP_LIST_SIZE];
1517 #if defined(MBEDTLS_SSL_ALPN)
1518     const char *alpn_list[ALPN_LIST_SIZE];
1519 #endif
1520 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
1521     unsigned char alloc_buf[MEMORY_HEAP_SIZE];
1522 #endif
1523 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1524     unsigned char cid[MBEDTLS_SSL_CID_IN_LEN_MAX];
1525     unsigned char cid_renego[MBEDTLS_SSL_CID_IN_LEN_MAX];
1526     size_t cid_len = 0;
1527     size_t cid_renego_len = 0;
1528 #endif
1529 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
1530     unsigned char *context_buf = NULL;
1531     size_t context_buf_len = 0;
1532 #endif
1533 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \
1534     defined(MBEDTLS_USE_PSA_CRYPTO)
1535     mbedtls_svc_key_id_t ecjpake_pw_slot = MBEDTLS_SVC_KEY_ID_INIT; /* ecjpake password key slot */
1536 #endif /* MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1537 
1538 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1539     uint16_t sig_alg_list[SIG_ALG_LIST_SIZE];
1540 #endif
1541 
1542     int i;
1543     char *p, *q;
1544     const int *list;
1545 #if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
1546     psa_status_t status;
1547 #endif
1548     unsigned char eap_tls_keymaterial[16];
1549     unsigned char eap_tls_iv[8];
1550     const char *eap_tls_label = "client EAP encryption";
1551     eap_tls_keys eap_tls_keying;
1552 #if defined(MBEDTLS_SSL_DTLS_SRTP)
1553     /*! master keys and master salt for SRTP generated during handshake */
1554     unsigned char dtls_srtp_key_material[MBEDTLS_TLS_SRTP_MAX_KEY_MATERIAL_LENGTH];
1555     const char *dtls_srtp_label = "EXTRACTOR-dtls_srtp";
1556     dtls_srtp_keys dtls_srtp_keying;
1557     const mbedtls_ssl_srtp_profile default_profiles[] = {
1558         MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_80,
1559         MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_32,
1560         MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_80,
1561         MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_32,
1562         MBEDTLS_TLS_SRTP_UNSET
1563     };
1564 #endif /* MBEDTLS_SSL_DTLS_SRTP */
1565 
1566 #if defined(MBEDTLS_SSL_EARLY_DATA)
1567     int tls13_early_data_enabled = MBEDTLS_SSL_EARLY_DATA_DISABLED;
1568 #endif
1569 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
1570     mbedtls_memory_buffer_alloc_init(alloc_buf, sizeof(alloc_buf));
1571 #if defined(MBEDTLS_MEMORY_DEBUG)
1572     size_t current_heap_memory, peak_heap_memory, heap_blocks;
1573 #endif  /* MBEDTLS_MEMORY_DEBUG */
1574 #endif  /* MBEDTLS_MEMORY_BUFFER_ALLOC_C */
1575 
1576 #if defined(MBEDTLS_TEST_HOOKS)
1577     test_hooks_init();
1578 #endif /* MBEDTLS_TEST_HOOKS */
1579 
1580     /*
1581      * Make sure memory references are valid in case we exit early.
1582      */
1583     mbedtls_net_init(&client_fd);
1584     mbedtls_net_init(&listen_fd);
1585     mbedtls_ssl_init(&ssl);
1586     mbedtls_ssl_config_init(&conf);
1587     rng_init(&rng);
1588 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1589     mbedtls_x509_crt_init(&cacert);
1590     mbedtls_x509_crt_init(&srvcert);
1591     mbedtls_pk_init(&pkey);
1592     mbedtls_x509_crt_init(&srvcert2);
1593     mbedtls_pk_init(&pkey2);
1594 #endif
1595 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
1596     memset(&ssl_async_keys, 0, sizeof(ssl_async_keys));
1597 #endif
1598 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_FS_IO)
1599     mbedtls_dhm_init(&dhm);
1600 #endif
1601 #if defined(MBEDTLS_SSL_CACHE_C)
1602     mbedtls_ssl_cache_init(&cache);
1603 #endif
1604 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_TICKET_C)
1605     mbedtls_ssl_ticket_init(&ticket_ctx);
1606 #endif
1607 #if defined(MBEDTLS_SSL_ALPN)
1608     memset((void *) alpn_list, 0, sizeof(alpn_list));
1609 #endif
1610 #if defined(MBEDTLS_SSL_COOKIE_C)
1611     mbedtls_ssl_cookie_init(&cookie_ctx);
1612 #endif
1613 
1614 #if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
1615     status = psa_crypto_init();
1616     if (status != PSA_SUCCESS) {
1617         mbedtls_fprintf(stderr, "Failed to initialize PSA Crypto implementation: %d\n",
1618                         (int) status);
1619         ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
1620         goto exit;
1621     }
1622 #endif  /* MBEDTLS_USE_PSA_CRYPTO */
1623 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
1624     mbedtls_test_enable_insecure_external_rng();
1625 #endif  /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
1626 
1627 #if !defined(_WIN32)
1628     /* Abort cleanly on SIGTERM and SIGINT */
1629     signal(SIGTERM, term_handler);
1630     signal(SIGINT, term_handler);
1631 #endif
1632 
1633     if (argc < 2) {
1634 usage:
1635         if (ret == 0) {
1636             ret = 1;
1637         }
1638 
1639         mbedtls_printf(USAGE1);
1640         mbedtls_printf(USAGE2);
1641         mbedtls_printf(USAGE3);
1642         mbedtls_printf(USAGE4);
1643 
1644         list = mbedtls_ssl_list_ciphersuites();
1645         while (*list) {
1646             mbedtls_printf(" %-42s", mbedtls_ssl_get_ciphersuite_name(*list));
1647             list++;
1648             if (!*list) {
1649                 break;
1650             }
1651             mbedtls_printf(" %s\n", mbedtls_ssl_get_ciphersuite_name(*list));
1652             list++;
1653         }
1654         mbedtls_printf("\n");
1655         goto exit;
1656     }
1657 
1658     opt.buffer_size         = DFL_IO_BUF_LEN;
1659     opt.server_addr         = DFL_SERVER_ADDR;
1660     opt.server_port         = DFL_SERVER_PORT;
1661     opt.debug_level         = DFL_DEBUG_LEVEL;
1662     opt.event               = DFL_EVENT;
1663     opt.response_size       = DFL_RESPONSE_SIZE;
1664     opt.nbio                = DFL_NBIO;
1665     opt.cid_enabled         = DFL_CID_ENABLED;
1666     opt.cid_enabled_renego  = DFL_CID_ENABLED_RENEGO;
1667     opt.cid_val             = DFL_CID_VALUE;
1668     opt.cid_val_renego      = DFL_CID_VALUE_RENEGO;
1669     opt.read_timeout        = DFL_READ_TIMEOUT;
1670     opt.ca_file             = DFL_CA_FILE;
1671     opt.ca_path             = DFL_CA_PATH;
1672     opt.crt_file            = DFL_CRT_FILE;
1673     opt.key_file            = DFL_KEY_FILE;
1674     opt.key_opaque          = DFL_KEY_OPAQUE;
1675     opt.key_pwd             = DFL_KEY_PWD;
1676     opt.crt_file2           = DFL_CRT_FILE2;
1677     opt.key_file2           = DFL_KEY_FILE2;
1678     opt.key_pwd2            = DFL_KEY_PWD2;
1679     opt.async_operations    = DFL_ASYNC_OPERATIONS;
1680     opt.async_private_delay1 = DFL_ASYNC_PRIVATE_DELAY1;
1681     opt.async_private_delay2 = DFL_ASYNC_PRIVATE_DELAY2;
1682     opt.async_private_error = DFL_ASYNC_PRIVATE_ERROR;
1683     opt.psk                 = DFL_PSK;
1684 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1685     opt.psk_opaque          = DFL_PSK_OPAQUE;
1686     opt.psk_list_opaque     = DFL_PSK_LIST_OPAQUE;
1687 #endif
1688 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
1689     opt.ca_callback         = DFL_CA_CALLBACK;
1690 #endif
1691     opt.psk_identity        = DFL_PSK_IDENTITY;
1692     opt.psk_list            = DFL_PSK_LIST;
1693     opt.ecjpake_pw          = DFL_ECJPAKE_PW;
1694 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1695     opt.ecjpake_pw_opaque   = DFL_ECJPAKE_PW_OPAQUE;
1696 #endif
1697     opt.force_ciphersuite[0] = DFL_FORCE_CIPHER;
1698 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1699     opt.tls13_kex_modes     = DFL_TLS1_3_KEX_MODES;
1700 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1701     opt.renegotiation       = DFL_RENEGOTIATION;
1702     opt.allow_legacy        = DFL_ALLOW_LEGACY;
1703     opt.renegotiate         = DFL_RENEGOTIATE;
1704     opt.renego_delay        = DFL_RENEGO_DELAY;
1705     opt.renego_period       = DFL_RENEGO_PERIOD;
1706     opt.exchanges           = DFL_EXCHANGES;
1707     opt.min_version         = DFL_MIN_VERSION;
1708     opt.max_version         = DFL_MAX_VERSION;
1709     opt.allow_sha1          = DFL_SHA1;
1710     opt.auth_mode           = DFL_AUTH_MODE;
1711     opt.cert_req_ca_list    = DFL_CERT_REQ_CA_LIST;
1712     opt.cert_req_dn_hint    = DFL_CERT_REQ_DN_HINT;
1713     opt.mfl_code            = DFL_MFL_CODE;
1714     opt.trunc_hmac          = DFL_TRUNC_HMAC;
1715     opt.tickets             = DFL_TICKETS;
1716     opt.dummy_ticket        = DFL_DUMMY_TICKET;
1717     opt.ticket_rotate       = DFL_TICKET_ROTATE;
1718     opt.ticket_timeout      = DFL_TICKET_TIMEOUT;
1719     opt.ticket_aead         = DFL_TICKET_AEAD;
1720     opt.cache_max           = DFL_CACHE_MAX;
1721 #if defined(MBEDTLS_HAVE_TIME)
1722     opt.cache_timeout       = DFL_CACHE_TIMEOUT;
1723 #endif
1724     opt.cache_remove        = DFL_CACHE_REMOVE;
1725     opt.sni                 = DFL_SNI;
1726     opt.alpn_string         = DFL_ALPN_STRING;
1727     opt.groups              = DFL_GROUPS;
1728     opt.max_early_data_size = DFL_MAX_EARLY_DATA_SIZE;
1729     opt.sig_algs            = DFL_SIG_ALGS;
1730     opt.dhm_file            = DFL_DHM_FILE;
1731     opt.transport           = DFL_TRANSPORT;
1732     opt.cookies             = DFL_COOKIES;
1733     opt.anti_replay         = DFL_ANTI_REPLAY;
1734     opt.hs_to_min           = DFL_HS_TO_MIN;
1735     opt.hs_to_max           = DFL_HS_TO_MAX;
1736     opt.dtls_mtu            = DFL_DTLS_MTU;
1737     opt.dgram_packing       = DFL_DGRAM_PACKING;
1738     opt.badmac_limit        = DFL_BADMAC_LIMIT;
1739     opt.extended_ms         = DFL_EXTENDED_MS;
1740     opt.etm                 = DFL_ETM;
1741     opt.serialize           = DFL_SERIALIZE;
1742     opt.context_file        = DFL_CONTEXT_FILE;
1743     opt.eap_tls             = DFL_EAP_TLS;
1744     opt.reproducible        = DFL_REPRODUCIBLE;
1745     opt.nss_keylog          = DFL_NSS_KEYLOG;
1746     opt.nss_keylog_file     = DFL_NSS_KEYLOG_FILE;
1747     opt.query_config_mode   = DFL_QUERY_CONFIG_MODE;
1748     opt.use_srtp            = DFL_USE_SRTP;
1749     opt.force_srtp_profile  = DFL_SRTP_FORCE_PROFILE;
1750     opt.support_mki         = DFL_SRTP_SUPPORT_MKI;
1751     opt.key1_opaque_alg1   = DFL_KEY_OPAQUE_ALG;
1752     opt.key1_opaque_alg2   = DFL_KEY_OPAQUE_ALG;
1753     opt.key2_opaque_alg1   = DFL_KEY_OPAQUE_ALG;
1754     opt.key2_opaque_alg2   = DFL_KEY_OPAQUE_ALG;
1755 
1756     for (i = 1; i < argc; i++) {
1757         p = argv[i];
1758         if ((q = strchr(p, '=')) == NULL) {
1759             goto usage;
1760         }
1761         *q++ = '\0';
1762 
1763         if (strcmp(p, "server_port") == 0) {
1764             opt.server_port = q;
1765         } else if (strcmp(p, "server_addr") == 0) {
1766             opt.server_addr = q;
1767         } else if (strcmp(p, "dtls") == 0) {
1768             int t = atoi(q);
1769             if (t == 0) {
1770                 opt.transport = MBEDTLS_SSL_TRANSPORT_STREAM;
1771             } else if (t == 1) {
1772                 opt.transport = MBEDTLS_SSL_TRANSPORT_DATAGRAM;
1773             } else {
1774                 goto usage;
1775             }
1776         } else if (strcmp(p, "debug_level") == 0) {
1777             opt.debug_level = atoi(q);
1778             if (opt.debug_level < 0 || opt.debug_level > 65535) {
1779                 goto usage;
1780             }
1781         } else if (strcmp(p, "build_version") == 0) {
1782             if (strcmp(q, "1") == 0) {
1783                 mbedtls_printf("build version: %s (build %d)\n",
1784                                MBEDTLS_VERSION_STRING_FULL,
1785                                MBEDTLS_VERSION_NUMBER);
1786                 goto exit;
1787             }
1788         } else if (strcmp(p, "nbio") == 0) {
1789             opt.nbio = atoi(q);
1790             if (opt.nbio < 0 || opt.nbio > 2) {
1791                 goto usage;
1792             }
1793         } else if (strcmp(p, "event") == 0) {
1794             opt.event = atoi(q);
1795             if (opt.event < 0 || opt.event > 2) {
1796                 goto usage;
1797             }
1798         } else if (strcmp(p, "read_timeout") == 0) {
1799             opt.read_timeout = atoi(q);
1800         } else if (strcmp(p, "buffer_size") == 0) {
1801             opt.buffer_size = atoi(q);
1802             if (opt.buffer_size < 1) {
1803                 goto usage;
1804             }
1805         } else if (strcmp(p, "response_size") == 0) {
1806             opt.response_size = atoi(q);
1807             if (opt.response_size < 0 || opt.response_size > MBEDTLS_SSL_OUT_CONTENT_LEN) {
1808                 goto usage;
1809             }
1810             if (opt.buffer_size < opt.response_size) {
1811                 opt.buffer_size = opt.response_size;
1812             }
1813         } else if (strcmp(p, "ca_file") == 0) {
1814             opt.ca_file = q;
1815         } else if (strcmp(p, "ca_path") == 0) {
1816             opt.ca_path = q;
1817         } else if (strcmp(p, "crt_file") == 0) {
1818             opt.crt_file = q;
1819         } else if (strcmp(p, "key_file") == 0) {
1820             opt.key_file = q;
1821         } else if (strcmp(p, "key_pwd") == 0) {
1822             opt.key_pwd = q;
1823         }
1824 #if defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1825         else if (strcmp(p, "key_opaque") == 0) {
1826             opt.key_opaque = atoi(q);
1827         }
1828 #endif
1829         else if (strcmp(p, "crt_file2") == 0) {
1830             opt.crt_file2 = q;
1831         } else if (strcmp(p, "key_file2") == 0) {
1832             opt.key_file2 = q;
1833         } else if (strcmp(p, "key_pwd2") == 0) {
1834             opt.key_pwd2 = q;
1835         } else if (strcmp(p, "dhm_file") == 0) {
1836             opt.dhm_file = q;
1837         }
1838 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
1839         else if (strcmp(p, "async_operations") == 0) {
1840             opt.async_operations = q;
1841         } else if (strcmp(p, "async_private_delay1") == 0) {
1842             opt.async_private_delay1 = atoi(q);
1843         } else if (strcmp(p, "async_private_delay2") == 0) {
1844             opt.async_private_delay2 = atoi(q);
1845         } else if (strcmp(p, "async_private_error") == 0) {
1846             int n = atoi(q);
1847             if (n < -SSL_ASYNC_INJECT_ERROR_MAX ||
1848                 n > SSL_ASYNC_INJECT_ERROR_MAX) {
1849                 ret = 2;
1850                 goto usage;
1851             }
1852             opt.async_private_error = n;
1853         }
1854 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
1855 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1856         else if (strcmp(p, "cid") == 0) {
1857             opt.cid_enabled = atoi(q);
1858             if (opt.cid_enabled != 0 && opt.cid_enabled != 1) {
1859                 goto usage;
1860             }
1861         } else if (strcmp(p, "cid_renego") == 0) {
1862             opt.cid_enabled_renego = atoi(q);
1863             if (opt.cid_enabled_renego != 0 && opt.cid_enabled_renego != 1) {
1864                 goto usage;
1865             }
1866         } else if (strcmp(p, "cid_val") == 0) {
1867             opt.cid_val = q;
1868         } else if (strcmp(p, "cid_val_renego") == 0) {
1869             opt.cid_val_renego = q;
1870         }
1871 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1872         else if (strcmp(p, "psk") == 0) {
1873             opt.psk = q;
1874         }
1875 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1876         else if (strcmp(p, "psk_opaque") == 0) {
1877             opt.psk_opaque = atoi(q);
1878         } else if (strcmp(p, "psk_list_opaque") == 0) {
1879             opt.psk_list_opaque = atoi(q);
1880         }
1881 #endif
1882 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
1883         else if (strcmp(p, "ca_callback") == 0) {
1884             opt.ca_callback = atoi(q);
1885         }
1886 #endif
1887         else if (strcmp(p, "psk_identity") == 0) {
1888             opt.psk_identity = q;
1889         } else if (strcmp(p, "psk_list") == 0) {
1890             opt.psk_list = q;
1891         } else if (strcmp(p, "ecjpake_pw") == 0) {
1892             opt.ecjpake_pw = q;
1893         }
1894 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1895         else if (strcmp(p, "ecjpake_pw_opaque") == 0) {
1896             opt.ecjpake_pw_opaque = atoi(q);
1897         }
1898 #endif
1899         else if (strcmp(p, "force_ciphersuite") == 0) {
1900             opt.force_ciphersuite[0] = mbedtls_ssl_get_ciphersuite_id(q);
1901 
1902             if (opt.force_ciphersuite[0] == 0) {
1903                 ret = 2;
1904                 goto usage;
1905             }
1906             opt.force_ciphersuite[1] = 0;
1907         } else if (strcmp(p, "groups") == 0) {
1908             opt.groups = q;
1909         }
1910 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1911         else if (strcmp(p, "sig_algs") == 0) {
1912             opt.sig_algs = q;
1913         }
1914 #endif
1915 #if defined(MBEDTLS_SSL_EARLY_DATA)
1916         else if (strcmp(p, "max_early_data_size") == 0) {
1917             long long value = atoll(q);
1918             tls13_early_data_enabled =
1919                 value >= 0 ? MBEDTLS_SSL_EARLY_DATA_ENABLED :
1920                 MBEDTLS_SSL_EARLY_DATA_DISABLED;
1921             if (tls13_early_data_enabled) {
1922                 opt.max_early_data_size = atoi(q);
1923             }
1924         }
1925 #endif /* MBEDTLS_SSL_EARLY_DATA */
1926         else if (strcmp(p, "renegotiation") == 0) {
1927             opt.renegotiation = (atoi(q)) ?
1928                                 MBEDTLS_SSL_RENEGOTIATION_ENABLED :
1929                                 MBEDTLS_SSL_RENEGOTIATION_DISABLED;
1930         } else if (strcmp(p, "allow_legacy") == 0) {
1931             switch (atoi(q)) {
1932                 case -1:
1933                     opt.allow_legacy = MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE;
1934                     break;
1935                 case 0:
1936                     opt.allow_legacy = MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION;
1937                     break;
1938                 case 1:
1939                     opt.allow_legacy = MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION;
1940                     break;
1941                 default: goto usage;
1942             }
1943         } else if (strcmp(p, "renegotiate") == 0) {
1944             opt.renegotiate = atoi(q);
1945             if (opt.renegotiate < 0 || opt.renegotiate > 1) {
1946                 goto usage;
1947             }
1948         } else if (strcmp(p, "renego_delay") == 0) {
1949             opt.renego_delay = atoi(q);
1950         } else if (strcmp(p, "renego_period") == 0) {
1951 #if defined(_MSC_VER)
1952             opt.renego_period = _strtoui64(q, NULL, 10);
1953 #else
1954             if (sscanf(q, "%" SCNu64, &opt.renego_period) != 1) {
1955                 goto usage;
1956             }
1957 #endif /* _MSC_VER */
1958             if (opt.renego_period < 2) {
1959                 goto usage;
1960             }
1961         } else if (strcmp(p, "exchanges") == 0) {
1962             opt.exchanges = atoi(q);
1963             if (opt.exchanges < 0) {
1964                 goto usage;
1965             }
1966         }
1967 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1968         else if (strcmp(p, "tls13_kex_modes") == 0) {
1969             if (strcmp(q, "psk") == 0) {
1970                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
1971             } else if (strcmp(q, "psk_ephemeral") == 0) {
1972                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
1973             } else if (strcmp(q, "ephemeral") == 0) {
1974                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL;
1975             } else if (strcmp(q, "ephemeral_all") == 0) {
1976                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ALL;
1977             } else if (strcmp(q, "psk_all") == 0) {
1978                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL;
1979             } else if (strcmp(q, "all") == 0) {
1980                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_ALL;
1981             }
1982             /* The purpose of `psk_or_ephemeral` is to improve test coverage. That
1983              * is not recommended in practice.
1984              * `psk_or_ephemeral` exists in theory, we need this mode to test if
1985              * this setting work correctly. With this key exchange setting, server
1986              * should always perform `ephemeral` handshake. `psk` or `psk_ephemeral`
1987              * is not expected.
1988              */
1989             else if (strcmp(q, "psk_or_ephemeral") == 0) {
1990                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK |
1991                                       MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL;
1992             } else {
1993                 goto usage;
1994             }
1995         }
1996 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1997 
1998         else if (strcmp(p, "min_version") == 0) {
1999             if (strcmp(q, "tls12") == 0 ||
2000                 strcmp(q, "dtls12") == 0) {
2001                 opt.min_version = MBEDTLS_SSL_VERSION_TLS1_2;
2002             }
2003 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2004             else if (strcmp(q, "tls13") == 0) {
2005                 opt.min_version = MBEDTLS_SSL_VERSION_TLS1_3;
2006             }
2007 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2008             else {
2009                 goto usage;
2010             }
2011         } else if (strcmp(p, "max_version") == 0) {
2012             if (strcmp(q, "tls12") == 0 ||
2013                 strcmp(q, "dtls12") == 0) {
2014                 opt.max_version = MBEDTLS_SSL_VERSION_TLS1_2;
2015             }
2016 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2017             else if (strcmp(q, "tls13") == 0) {
2018                 opt.max_version = MBEDTLS_SSL_VERSION_TLS1_3;
2019             }
2020 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2021             else {
2022                 goto usage;
2023             }
2024         } else if (strcmp(p, "allow_sha1") == 0) {
2025             switch (atoi(q)) {
2026                 case 0:     opt.allow_sha1 = 0;   break;
2027                 case 1:     opt.allow_sha1 = 1;    break;
2028                 default:    goto usage;
2029             }
2030         } else if (strcmp(p, "force_version") == 0) {
2031             if (strcmp(q, "tls12") == 0) {
2032                 opt.min_version = MBEDTLS_SSL_VERSION_TLS1_2;
2033                 opt.max_version = MBEDTLS_SSL_VERSION_TLS1_2;
2034             } else if (strcmp(q, "dtls12") == 0) {
2035                 opt.min_version = MBEDTLS_SSL_VERSION_TLS1_2;
2036                 opt.max_version = MBEDTLS_SSL_VERSION_TLS1_2;
2037                 opt.transport = MBEDTLS_SSL_TRANSPORT_DATAGRAM;
2038             }
2039 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2040             else if (strcmp(q, "tls13") == 0) {
2041                 opt.min_version = MBEDTLS_SSL_VERSION_TLS1_3;
2042                 opt.max_version = MBEDTLS_SSL_VERSION_TLS1_3;
2043             }
2044 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2045             else {
2046                 goto usage;
2047             }
2048         } else if (strcmp(p, "auth_mode") == 0) {
2049             if ((opt.auth_mode = get_auth_mode(q)) < 0) {
2050                 goto usage;
2051             }
2052         } else if (strcmp(p, "cert_req_ca_list") == 0) {
2053             opt.cert_req_ca_list = atoi(q);
2054             if (opt.cert_req_ca_list < 0 || opt.cert_req_ca_list > 3) {
2055                 goto usage;
2056             }
2057             if (opt.cert_req_ca_list > 1) {
2058                 opt.cert_req_dn_hint = opt.cert_req_ca_list;
2059                 opt.cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED;
2060             }
2061         } else if (strcmp(p, "max_frag_len") == 0) {
2062             if (strcmp(q, "512") == 0) {
2063                 opt.mfl_code = MBEDTLS_SSL_MAX_FRAG_LEN_512;
2064             } else if (strcmp(q, "1024") == 0) {
2065                 opt.mfl_code = MBEDTLS_SSL_MAX_FRAG_LEN_1024;
2066             } else if (strcmp(q, "2048") == 0) {
2067                 opt.mfl_code = MBEDTLS_SSL_MAX_FRAG_LEN_2048;
2068             } else if (strcmp(q, "4096") == 0) {
2069                 opt.mfl_code = MBEDTLS_SSL_MAX_FRAG_LEN_4096;
2070             } else {
2071                 goto usage;
2072             }
2073         } else if (strcmp(p, "alpn") == 0) {
2074             opt.alpn_string = q;
2075         } else if (strcmp(p, "trunc_hmac") == 0) {
2076             switch (atoi(q)) {
2077                 case 0: opt.trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_DISABLED; break;
2078                 case 1: opt.trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED; break;
2079                 default: goto usage;
2080             }
2081         } else if (strcmp(p, "extended_ms") == 0) {
2082             switch (atoi(q)) {
2083                 case 0:
2084                     opt.extended_ms = MBEDTLS_SSL_EXTENDED_MS_DISABLED;
2085                     break;
2086                 case 1:
2087                     opt.extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
2088                     break;
2089                 default: goto usage;
2090             }
2091         } else if (strcmp(p, "etm") == 0) {
2092             switch (atoi(q)) {
2093                 case 0: opt.etm = MBEDTLS_SSL_ETM_DISABLED; break;
2094                 case 1: opt.etm = MBEDTLS_SSL_ETM_ENABLED; break;
2095                 default: goto usage;
2096             }
2097         } else if (strcmp(p, "tickets") == 0) {
2098             opt.tickets = atoi(q);
2099             if (opt.tickets < 0) {
2100                 goto usage;
2101             }
2102         } else if (strcmp(p, "dummy_ticket") == 0) {
2103             opt.dummy_ticket = atoi(q);
2104             if (opt.dummy_ticket < 0) {
2105                 goto usage;
2106             }
2107         } else if (strcmp(p, "ticket_rotate") == 0) {
2108             opt.ticket_rotate = atoi(q);
2109             if (opt.ticket_rotate < 0 || opt.ticket_rotate > 1) {
2110                 goto usage;
2111             }
2112         } else if (strcmp(p, "ticket_timeout") == 0) {
2113             opt.ticket_timeout = atoi(q);
2114             if (opt.ticket_timeout < 0) {
2115                 goto usage;
2116             }
2117         } else if (strcmp(p, "ticket_aead") == 0) {
2118             const mbedtls_cipher_info_t *ci = mbedtls_cipher_info_from_string(q);
2119 
2120             if (ci == NULL) {
2121                 goto usage;
2122             }
2123             opt.ticket_aead = mbedtls_cipher_info_get_type(ci);
2124         } else if (strcmp(p, "cache_max") == 0) {
2125             opt.cache_max = atoi(q);
2126             if (opt.cache_max < 0) {
2127                 goto usage;
2128             }
2129         }
2130 #if defined(MBEDTLS_HAVE_TIME)
2131         else if (strcmp(p, "cache_timeout") == 0) {
2132             opt.cache_timeout = atoi(q);
2133             if (opt.cache_timeout < 0) {
2134                 goto usage;
2135             }
2136         }
2137 #endif
2138         else if (strcmp(p, "cache_remove") == 0) {
2139             opt.cache_remove = atoi(q);
2140             if (opt.cache_remove < 0 || opt.cache_remove > 1) {
2141                 goto usage;
2142             }
2143         } else if (strcmp(p, "cookies") == 0) {
2144             opt.cookies = atoi(q);
2145             if (opt.cookies < -1 || opt.cookies > 1) {
2146                 goto usage;
2147             }
2148         } else if (strcmp(p, "anti_replay") == 0) {
2149             opt.anti_replay = atoi(q);
2150             if (opt.anti_replay < 0 || opt.anti_replay > 1) {
2151                 goto usage;
2152             }
2153         } else if (strcmp(p, "badmac_limit") == 0) {
2154             opt.badmac_limit = atoi(q);
2155             if (opt.badmac_limit < 0) {
2156                 goto usage;
2157             }
2158         } else if (strcmp(p, "hs_timeout") == 0) {
2159             if ((p = strchr(q, '-')) == NULL) {
2160                 goto usage;
2161             }
2162             *p++ = '\0';
2163             opt.hs_to_min = atoi(q);
2164             opt.hs_to_max = atoi(p);
2165             if (opt.hs_to_min == 0 || opt.hs_to_max < opt.hs_to_min) {
2166                 goto usage;
2167             }
2168         } else if (strcmp(p, "mtu") == 0) {
2169             opt.dtls_mtu = atoi(q);
2170             if (opt.dtls_mtu < 0) {
2171                 goto usage;
2172             }
2173         } else if (strcmp(p, "dgram_packing") == 0) {
2174             opt.dgram_packing = atoi(q);
2175             if (opt.dgram_packing != 0 &&
2176                 opt.dgram_packing != 1) {
2177                 goto usage;
2178             }
2179         } else if (strcmp(p, "sni") == 0) {
2180             opt.sni = q;
2181         } else if (strcmp(p, "query_config") == 0) {
2182             opt.query_config_mode = 1;
2183             query_config_ret = query_config(q);
2184             goto exit;
2185         } else if (strcmp(p, "serialize") == 0) {
2186             opt.serialize = atoi(q);
2187             if (opt.serialize < 0 || opt.serialize > 2) {
2188                 goto usage;
2189             }
2190         } else if (strcmp(p, "context_file") == 0) {
2191             opt.context_file = q;
2192         } else if (strcmp(p, "eap_tls") == 0) {
2193             opt.eap_tls = atoi(q);
2194             if (opt.eap_tls < 0 || opt.eap_tls > 1) {
2195                 goto usage;
2196             }
2197         } else if (strcmp(p, "reproducible") == 0) {
2198             opt.reproducible = 1;
2199         } else if (strcmp(p, "nss_keylog") == 0) {
2200             opt.nss_keylog = atoi(q);
2201             if (opt.nss_keylog < 0 || opt.nss_keylog > 1) {
2202                 goto usage;
2203             }
2204         } else if (strcmp(p, "nss_keylog_file") == 0) {
2205             opt.nss_keylog_file = q;
2206         } else if (strcmp(p, "use_srtp") == 0) {
2207             opt.use_srtp = atoi(q);
2208         } else if (strcmp(p, "srtp_force_profile") == 0) {
2209             opt.force_srtp_profile = atoi(q);
2210         } else if (strcmp(p, "support_mki") == 0) {
2211             opt.support_mki = atoi(q);
2212         } else if (strcmp(p, "key_opaque_algs") == 0) {
2213             if (key_opaque_alg_parse(q, &opt.key1_opaque_alg1,
2214                                      &opt.key1_opaque_alg2) != 0) {
2215                 goto usage;
2216             }
2217         } else if (strcmp(p, "key_opaque_algs2") == 0) {
2218             if (key_opaque_alg_parse(q, &opt.key2_opaque_alg1,
2219                                      &opt.key2_opaque_alg2) != 0) {
2220                 goto usage;
2221             }
2222         } else {
2223             goto usage;
2224         }
2225     }
2226 
2227     if (opt.nss_keylog != 0 && opt.eap_tls != 0) {
2228         mbedtls_printf("Error: eap_tls and nss_keylog options cannot be used together.\n");
2229         goto usage;
2230     }
2231 
2232     /* Event-driven IO is incompatible with the above custom
2233      * receive and send functions, as the polling builds on
2234      * refers to the underlying net_context. */
2235     if (opt.event == 1 && opt.nbio != 1) {
2236         mbedtls_printf("Warning: event-driven IO mandates nbio=1 - overwrite\n");
2237         opt.nbio = 1;
2238     }
2239 
2240 #if defined(MBEDTLS_DEBUG_C)
2241     mbedtls_debug_set_threshold(opt.debug_level);
2242 #endif
2243 
2244     /* buf will alternatively contain the input read from the client and the
2245      * response that's about to be sent, plus a null byte in each case. */
2246     size_t buf_content_size = opt.buffer_size;
2247     /* The default response contains the ciphersuite name. Leave enough
2248      * room for that plus some margin. */
2249     if (buf_content_size < strlen(HTTP_RESPONSE) + 80) {
2250         buf_content_size = strlen(HTTP_RESPONSE) + 80;
2251     }
2252     if (opt.response_size != DFL_RESPONSE_SIZE &&
2253         buf_content_size < (size_t) opt.response_size) {
2254         buf_content_size = opt.response_size;
2255     }
2256     buf = mbedtls_calloc(1, buf_content_size + 1);
2257     if (buf == NULL) {
2258         mbedtls_printf("Could not allocate %lu bytes\n",
2259                        (unsigned long) buf_content_size + 1);
2260         ret = 3;
2261         goto exit;
2262     }
2263 
2264 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2265     if (opt.psk_opaque != 0) {
2266         if (strlen(opt.psk) == 0) {
2267             mbedtls_printf("psk_opaque set but no psk to be imported specified.\n");
2268             ret = 2;
2269             goto usage;
2270         }
2271 
2272         if (opt.force_ciphersuite[0] <= 0) {
2273             mbedtls_printf(
2274                 "opaque PSKs are only supported in conjunction with forcing TLS 1.2 and a PSK-only ciphersuite through the 'force_ciphersuite' option.\n");
2275             ret = 2;
2276             goto usage;
2277         }
2278     }
2279 
2280     if (opt.psk_list_opaque != 0) {
2281         if (opt.psk_list == NULL) {
2282             mbedtls_printf("psk_slot set but no psk to be imported specified.\n");
2283             ret = 2;
2284             goto usage;
2285         }
2286 
2287         if (opt.force_ciphersuite[0] <= 0) {
2288             mbedtls_printf(
2289                 "opaque PSKs are only supported in conjunction with forcing TLS 1.2 and a PSK-only ciphersuite through the 'force_ciphersuite' option.\n");
2290             ret = 2;
2291             goto usage;
2292         }
2293     }
2294 #endif /* MBEDTLS_USE_PSA_CRYPTO */
2295 
2296     if (opt.force_ciphersuite[0] > 0) {
2297         const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
2298         ciphersuite_info =
2299             mbedtls_ssl_ciphersuite_from_id(opt.force_ciphersuite[0]);
2300 
2301         if (opt.max_version != -1 &&
2302             ciphersuite_info->min_tls_version > opt.max_version) {
2303             mbedtls_printf("forced ciphersuite not allowed with this protocol version\n");
2304             ret = 2;
2305             goto usage;
2306         }
2307         if (opt.min_version != -1 &&
2308             ciphersuite_info->max_tls_version < opt.min_version) {
2309             mbedtls_printf("forced ciphersuite not allowed with this protocol version\n");
2310             ret = 2;
2311             goto usage;
2312         }
2313 
2314         /* If we select a version that's not supported by
2315          * this suite, then there will be no common ciphersuite... */
2316         if (opt.max_version == -1 ||
2317             opt.max_version > ciphersuite_info->max_tls_version) {
2318             opt.max_version = ciphersuite_info->max_tls_version;
2319         }
2320         if (opt.min_version < ciphersuite_info->min_tls_version) {
2321             opt.min_version = ciphersuite_info->min_tls_version;
2322         }
2323 
2324 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2325 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
2326         if (opt.psk_opaque != 0 || opt.psk_list_opaque != 0) {
2327             /* Determine KDF algorithm the opaque PSK will be used in. */
2328 #if defined(MBEDTLS_MD_CAN_SHA384)
2329             if (ciphersuite_info->mac == MBEDTLS_MD_SHA384) {
2330                 alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_384);
2331             } else
2332 #endif /* MBEDTLS_MD_CAN_SHA384 */
2333             alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_256);
2334         }
2335 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
2336 #endif /* MBEDTLS_USE_PSA_CRYPTO */
2337     }
2338 
2339 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2340     if (mbedtls_test_unhexify(cid, sizeof(cid),
2341                               opt.cid_val, &cid_len) != 0) {
2342         mbedtls_printf("CID not valid hex\n");
2343         goto exit;
2344     }
2345 
2346     /* Keep CID settings for renegotiation unless
2347      * specified otherwise. */
2348     if (opt.cid_enabled_renego == DFL_CID_ENABLED_RENEGO) {
2349         opt.cid_enabled_renego = opt.cid_enabled;
2350     }
2351     if (opt.cid_val_renego == DFL_CID_VALUE_RENEGO) {
2352         opt.cid_val_renego = opt.cid_val;
2353     }
2354 
2355     if (mbedtls_test_unhexify(cid_renego, sizeof(cid_renego),
2356                               opt.cid_val_renego, &cid_renego_len) != 0) {
2357         mbedtls_printf("CID not valid hex\n");
2358         goto exit;
2359     }
2360 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2361 
2362 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
2363     /*
2364      * Unhexify the pre-shared key and parse the list if any given
2365      */
2366     if (mbedtls_test_unhexify(psk, sizeof(psk),
2367                               opt.psk, &psk_len) != 0) {
2368         mbedtls_printf("pre-shared key not valid hex\n");
2369         goto exit;
2370     }
2371 
2372     if (opt.psk_list != NULL) {
2373         if ((psk_info = psk_parse(opt.psk_list)) == NULL) {
2374             mbedtls_printf("psk_list invalid");
2375             goto exit;
2376         }
2377     }
2378 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
2379 
2380     if (opt.groups != NULL) {
2381         if (parse_groups(opt.groups, group_list, GROUP_LIST_SIZE) != 0) {
2382             goto exit;
2383         }
2384     }
2385 
2386 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2387     if (opt.sig_algs != NULL) {
2388         p = (char *) opt.sig_algs;
2389         i = 0;
2390 
2391         /* Leave room for a final MBEDTLS_TLS1_3_SIG_NONE in signature algorithm list (sig_alg_list). */
2392         while (i < SIG_ALG_LIST_SIZE - 1 && *p != '\0') {
2393             q = p;
2394 
2395             /* Terminate the current string */
2396             while (*p != ',' && *p != '\0') {
2397                 p++;
2398             }
2399             if (*p == ',') {
2400                 *p++ = '\0';
2401             }
2402 
2403             if (strcmp(q, "rsa_pkcs1_sha256") == 0) {
2404                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA256;
2405             } else if (strcmp(q, "rsa_pkcs1_sha384") == 0) {
2406                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA384;
2407             } else if (strcmp(q, "rsa_pkcs1_sha512") == 0) {
2408                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA512;
2409             } else if (strcmp(q, "ecdsa_secp256r1_sha256") == 0) {
2410                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_ECDSA_SECP256R1_SHA256;
2411             } else if (strcmp(q, "ecdsa_secp384r1_sha384") == 0) {
2412                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_ECDSA_SECP384R1_SHA384;
2413             } else if (strcmp(q, "ecdsa_secp521r1_sha512") == 0) {
2414                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_ECDSA_SECP521R1_SHA512;
2415             } else if (strcmp(q, "rsa_pss_rsae_sha256") == 0) {
2416                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256;
2417             } else if (strcmp(q, "rsa_pss_rsae_sha384") == 0) {
2418                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384;
2419             } else if (strcmp(q, "rsa_pss_rsae_sha512") == 0) {
2420                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512;
2421             } else if (strcmp(q, "ed25519") == 0) {
2422                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_ED25519;
2423             } else if (strcmp(q, "ed448") == 0) {
2424                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_ED448;
2425             } else if (strcmp(q, "rsa_pss_pss_sha256") == 0) {
2426                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PSS_PSS_SHA256;
2427             } else if (strcmp(q, "rsa_pss_pss_sha384") == 0) {
2428                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PSS_PSS_SHA384;
2429             } else if (strcmp(q, "rsa_pss_pss_sha512") == 0) {
2430                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PSS_PSS_SHA512;
2431             } else if (strcmp(q, "rsa_pkcs1_sha1") == 0) {
2432                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA1;
2433             } else if (strcmp(q, "ecdsa_sha1") == 0) {
2434                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_ECDSA_SHA1;
2435             } else {
2436                 ret = -1;
2437                 mbedtls_printf("unknown signature algorithm \"%s\"\n", q);
2438                 mbedtls_print_supported_sig_algs();
2439                 goto exit;
2440             }
2441         }
2442 
2443         if (i == (SIG_ALG_LIST_SIZE - 1) && *p != '\0') {
2444             mbedtls_printf("signature algorithm list too long, maximum %d",
2445                            SIG_ALG_LIST_SIZE - 1);
2446             goto exit;
2447         }
2448 
2449         sig_alg_list[i] = MBEDTLS_TLS1_3_SIG_NONE;
2450     }
2451 #endif
2452 
2453 #if defined(MBEDTLS_SSL_ALPN)
2454     if (opt.alpn_string != NULL) {
2455         p = (char *) opt.alpn_string;
2456         i = 0;
2457 
2458         /* Leave room for a final NULL in alpn_list */
2459         while (i < ALPN_LIST_SIZE - 1 && *p != '\0') {
2460             alpn_list[i++] = p;
2461 
2462             /* Terminate the current string and move on to next one */
2463             while (*p != ',' && *p != '\0') {
2464                 p++;
2465             }
2466             if (*p == ',') {
2467                 *p++ = '\0';
2468             }
2469         }
2470     }
2471 #endif /* MBEDTLS_SSL_ALPN */
2472 
2473     mbedtls_printf("build version: %s (build %d)\n",
2474                    MBEDTLS_VERSION_STRING_FULL, MBEDTLS_VERSION_NUMBER);
2475 
2476     /*
2477      * 0. Initialize the RNG and the session data
2478      */
2479     mbedtls_printf("\n  . Seeding the random number generator...");
2480     fflush(stdout);
2481 
2482     ret = rng_seed(&rng, opt.reproducible, pers);
2483     if (ret != 0) {
2484         goto exit;
2485     }
2486     mbedtls_printf(" ok\n");
2487 
2488 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2489     /*
2490      * 1.1. Load the trusted CA
2491      */
2492     mbedtls_printf("  . Loading the CA root certificate ...");
2493     fflush(stdout);
2494 
2495     if (strcmp(opt.ca_path, "none") == 0 ||
2496         strcmp(opt.ca_file, "none") == 0) {
2497         ret = 0;
2498     } else
2499 #if defined(MBEDTLS_FS_IO)
2500     if (strlen(opt.ca_path)) {
2501         ret = mbedtls_x509_crt_parse_path(&cacert, opt.ca_path);
2502     } else if (strlen(opt.ca_file)) {
2503         ret = mbedtls_x509_crt_parse_file(&cacert, opt.ca_file);
2504     } else
2505 #endif
2506     {
2507 #if defined(MBEDTLS_PEM_PARSE_C)
2508         for (i = 0; mbedtls_test_cas[i] != NULL; i++) {
2509             ret = mbedtls_x509_crt_parse(&cacert,
2510                                          (const unsigned char *) mbedtls_test_cas[i],
2511                                          mbedtls_test_cas_len[i]);
2512             if (ret != 0) {
2513                 break;
2514             }
2515         }
2516 #endif /* MBEDTLS_PEM_PARSE_C */
2517         if (ret == 0) {
2518             for (i = 0; mbedtls_test_cas_der[i] != NULL; i++) {
2519                 ret = mbedtls_x509_crt_parse_der(&cacert,
2520                                                  (const unsigned char *) mbedtls_test_cas_der[i],
2521                                                  mbedtls_test_cas_der_len[i]);
2522                 if (ret != 0) {
2523                     break;
2524                 }
2525             }
2526         }
2527     }
2528     if (ret < 0) {
2529         mbedtls_printf(" failed\n  !  mbedtls_x509_crt_parse returned -0x%x\n\n",
2530                        (unsigned int) -ret);
2531         goto exit;
2532     }
2533 
2534     mbedtls_printf(" ok (%d skipped)\n", ret);
2535 
2536     /*
2537      * 1.2. Load own certificate and private key
2538      */
2539     mbedtls_printf("  . Loading the server cert. and key...");
2540     fflush(stdout);
2541 
2542 #if defined(MBEDTLS_FS_IO)
2543     if (strlen(opt.crt_file) && strcmp(opt.crt_file, "none") != 0) {
2544         key_cert_init++;
2545         if ((ret = mbedtls_x509_crt_parse_file(&srvcert, opt.crt_file)) != 0) {
2546             mbedtls_printf(" failed\n  !  mbedtls_x509_crt_parse_file returned -0x%x\n\n",
2547                            (unsigned int) -ret);
2548             goto exit;
2549         }
2550     }
2551     if (strlen(opt.key_file) && strcmp(opt.key_file, "none") != 0) {
2552         key_cert_init++;
2553         if ((ret = mbedtls_pk_parse_keyfile(&pkey, opt.key_file,
2554                                             opt.key_pwd, rng_get, &rng)) != 0) {
2555             mbedtls_printf(" failed\n  !  mbedtls_pk_parse_keyfile returned -0x%x\n\n",
2556                            (unsigned int) -ret);
2557             goto exit;
2558         }
2559     }
2560     if (key_cert_init == 1) {
2561         mbedtls_printf(" failed\n  !  crt_file without key_file or vice-versa\n\n");
2562         goto exit;
2563     }
2564 
2565     if (strlen(opt.crt_file2) && strcmp(opt.crt_file2, "none") != 0) {
2566         key_cert_init2++;
2567         if ((ret = mbedtls_x509_crt_parse_file(&srvcert2, opt.crt_file2)) != 0) {
2568             mbedtls_printf(" failed\n  !  mbedtls_x509_crt_parse_file(2) returned -0x%x\n\n",
2569                            (unsigned int) -ret);
2570             goto exit;
2571         }
2572     }
2573     if (strlen(opt.key_file2) && strcmp(opt.key_file2, "none") != 0) {
2574         key_cert_init2++;
2575         if ((ret = mbedtls_pk_parse_keyfile(&pkey2, opt.key_file2,
2576                                             opt.key_pwd2, rng_get, &rng)) != 0) {
2577             mbedtls_printf(" failed\n  !  mbedtls_pk_parse_keyfile(2) returned -0x%x\n\n",
2578                            (unsigned int) -ret);
2579             goto exit;
2580         }
2581     }
2582     if (key_cert_init2 == 1) {
2583         mbedtls_printf(" failed\n  !  crt_file2 without key_file2 or vice-versa\n\n");
2584         goto exit;
2585     }
2586 #endif
2587     if (key_cert_init == 0 &&
2588         strcmp(opt.crt_file, "none") != 0 &&
2589         strcmp(opt.key_file, "none") != 0 &&
2590         key_cert_init2 == 0 &&
2591         strcmp(opt.crt_file2, "none") != 0 &&
2592         strcmp(opt.key_file2, "none") != 0) {
2593 #if defined(MBEDTLS_RSA_C)
2594         if ((ret = mbedtls_x509_crt_parse(&srvcert,
2595                                           (const unsigned char *) mbedtls_test_srv_crt_rsa,
2596                                           mbedtls_test_srv_crt_rsa_len)) != 0) {
2597             mbedtls_printf(" failed\n  !  mbedtls_x509_crt_parse returned -0x%x\n\n",
2598                            (unsigned int) -ret);
2599             goto exit;
2600         }
2601         if ((ret = mbedtls_pk_parse_key(&pkey,
2602                                         (const unsigned char *) mbedtls_test_srv_key_rsa,
2603                                         mbedtls_test_srv_key_rsa_len, NULL, 0,
2604                                         rng_get, &rng)) != 0) {
2605             mbedtls_printf(" failed\n  !  mbedtls_pk_parse_key returned -0x%x\n\n",
2606                            (unsigned int) -ret);
2607             goto exit;
2608         }
2609         key_cert_init = 2;
2610 #endif /* MBEDTLS_RSA_C */
2611 #if defined(MBEDTLS_PK_CAN_ECDSA_SOME)
2612         if ((ret = mbedtls_x509_crt_parse(&srvcert2,
2613                                           (const unsigned char *) mbedtls_test_srv_crt_ec,
2614                                           mbedtls_test_srv_crt_ec_len)) != 0) {
2615             mbedtls_printf(" failed\n  !  x509_crt_parse2 returned -0x%x\n\n",
2616                            (unsigned int) -ret);
2617             goto exit;
2618         }
2619         if ((ret = mbedtls_pk_parse_key(&pkey2,
2620                                         (const unsigned char *) mbedtls_test_srv_key_ec,
2621                                         mbedtls_test_srv_key_ec_len, NULL, 0,
2622                                         rng_get, &rng)) != 0) {
2623             mbedtls_printf(" failed\n  !  pk_parse_key2 returned -0x%x\n\n",
2624                            (unsigned int) -ret);
2625             goto exit;
2626         }
2627         key_cert_init2 = 2;
2628 #endif /* MBEDTLS_PK_CAN_ECDSA_SOME */
2629     }
2630 
2631 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2632     if (opt.key_opaque != 0) {
2633         psa_algorithm_t psa_alg, psa_alg2 = PSA_ALG_NONE;
2634         psa_key_usage_t psa_usage = 0;
2635 
2636         if (key_opaque_set_alg_usage(opt.key1_opaque_alg1,
2637                                      opt.key1_opaque_alg2,
2638                                      &psa_alg, &psa_alg2,
2639                                      &psa_usage,
2640                                      mbedtls_pk_get_type(&pkey)) == 0) {
2641             ret = mbedtls_pk_wrap_as_opaque(&pkey, &key_slot,
2642                                             psa_alg, psa_usage, psa_alg2);
2643 
2644             if (ret != 0) {
2645                 mbedtls_printf(" failed\n  !  "
2646                                "mbedtls_pk_wrap_as_opaque returned -0x%x\n\n",
2647                                (unsigned int)  -ret);
2648                 goto exit;
2649             }
2650         }
2651 
2652         psa_alg = PSA_ALG_NONE; psa_alg2 = PSA_ALG_NONE;
2653         psa_usage = 0;
2654 
2655         if (key_opaque_set_alg_usage(opt.key2_opaque_alg1,
2656                                      opt.key2_opaque_alg2,
2657                                      &psa_alg, &psa_alg2,
2658                                      &psa_usage,
2659                                      mbedtls_pk_get_type(&pkey2)) == 0) {
2660             ret = mbedtls_pk_wrap_as_opaque(&pkey2, &key_slot2,
2661                                             psa_alg, psa_usage, psa_alg2);
2662 
2663             if (ret != 0) {
2664                 mbedtls_printf(" failed\n  !  "
2665                                "mbedtls_pk_wrap_as_opaque returned -0x%x\n\n",
2666                                (unsigned int)  -ret);
2667                 goto exit;
2668             }
2669         }
2670     }
2671 #endif /* MBEDTLS_USE_PSA_CRYPTO */
2672 
2673     mbedtls_printf(" ok (key types: %s, %s)\n",
2674                    key_cert_init ? mbedtls_pk_get_name(&pkey) : "none",
2675                    key_cert_init2 ? mbedtls_pk_get_name(&pkey2) : "none");
2676 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2677 
2678 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_FS_IO)
2679     if (opt.dhm_file != NULL) {
2680         mbedtls_printf("  . Loading DHM parameters...");
2681         fflush(stdout);
2682 
2683         if ((ret = mbedtls_dhm_parse_dhmfile(&dhm, opt.dhm_file)) != 0) {
2684             mbedtls_printf(" failed\n  ! mbedtls_dhm_parse_dhmfile returned -0x%04X\n\n",
2685                            (unsigned int) -ret);
2686             goto exit;
2687         }
2688 
2689         mbedtls_printf(" ok\n");
2690     }
2691 #endif
2692 
2693 #if defined(SNI_OPTION)
2694     if (opt.sni != NULL) {
2695         mbedtls_printf("  . Setting up SNI information...");
2696         fflush(stdout);
2697 
2698         if ((sni_info = sni_parse(opt.sni)) == NULL) {
2699             mbedtls_printf(" failed\n");
2700             goto exit;
2701         }
2702 
2703         mbedtls_printf(" ok\n");
2704     }
2705 #endif /* SNI_OPTION */
2706 
2707     /*
2708      * 2. Setup stuff
2709      */
2710     mbedtls_printf("  . Setting up the SSL/TLS structure...");
2711     fflush(stdout);
2712 
2713     if ((ret = mbedtls_ssl_config_defaults(&conf,
2714                                            MBEDTLS_SSL_IS_SERVER,
2715                                            opt.transport,
2716                                            MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
2717         mbedtls_printf(" failed\n  ! mbedtls_ssl_config_defaults returned -0x%x\n\n",
2718                        (unsigned int) -ret);
2719         goto exit;
2720     }
2721 
2722 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2723     /* The default algorithms profile disables SHA-1, but our tests still
2724        rely on it heavily. Hence we allow it here. A real-world server
2725        should use the default profile unless there is a good reason not to. */
2726     if (opt.allow_sha1 > 0) {
2727         crt_profile_for_test.allowed_mds |= MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1);
2728         mbedtls_ssl_conf_cert_profile(&conf, &crt_profile_for_test);
2729         mbedtls_ssl_conf_sig_algs(&conf, ssl_sig_algs_for_test);
2730     }
2731 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2732 
2733     if (opt.auth_mode != DFL_AUTH_MODE) {
2734         mbedtls_ssl_conf_authmode(&conf, opt.auth_mode);
2735     }
2736 
2737     if (opt.cert_req_ca_list != DFL_CERT_REQ_CA_LIST) {
2738         mbedtls_ssl_conf_cert_req_ca_list(&conf, opt.cert_req_ca_list);
2739     }
2740 
2741 #if defined(MBEDTLS_SSL_EARLY_DATA)
2742     mbedtls_ssl_tls13_conf_early_data(&conf, tls13_early_data_enabled);
2743     if (tls13_early_data_enabled == MBEDTLS_SSL_EARLY_DATA_ENABLED) {
2744         mbedtls_ssl_tls13_conf_max_early_data_size(
2745             &conf, opt.max_early_data_size);
2746     }
2747 #endif /* MBEDTLS_SSL_EARLY_DATA */
2748 
2749 #if defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
2750     /* exercise setting DN hints for server certificate request
2751      * (Intended for use where the client cert expected has been signed by
2752      *  a specific CA which is an intermediate in a CA chain, not the root) */
2753     if (opt.cert_req_dn_hint == 2 && key_cert_init2) {
2754         mbedtls_ssl_conf_dn_hints(&conf, &srvcert2);
2755     }
2756 #endif
2757 
2758 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2759     if (opt.hs_to_min != DFL_HS_TO_MIN || opt.hs_to_max != DFL_HS_TO_MAX) {
2760         mbedtls_ssl_conf_handshake_timeout(&conf, opt.hs_to_min, opt.hs_to_max);
2761     }
2762 
2763     if (opt.dgram_packing != DFL_DGRAM_PACKING) {
2764         mbedtls_ssl_set_datagram_packing(&ssl, opt.dgram_packing);
2765     }
2766 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2767 
2768 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
2769     if ((ret = mbedtls_ssl_conf_max_frag_len(&conf, opt.mfl_code)) != 0) {
2770         mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_max_frag_len returned %d\n\n", ret);
2771         goto exit;
2772     }
2773 #endif
2774 
2775 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2776     if (opt.cid_enabled == 1 || opt.cid_enabled_renego == 1) {
2777         if (opt.cid_enabled == 1        &&
2778             opt.cid_enabled_renego == 1 &&
2779             cid_len != cid_renego_len) {
2780             mbedtls_printf("CID length must not change during renegotiation\n");
2781             goto usage;
2782         }
2783 
2784         if (opt.cid_enabled == 1) {
2785             ret = mbedtls_ssl_conf_cid(&conf, cid_len,
2786                                        MBEDTLS_SSL_UNEXPECTED_CID_IGNORE);
2787         } else {
2788             ret = mbedtls_ssl_conf_cid(&conf, cid_renego_len,
2789                                        MBEDTLS_SSL_UNEXPECTED_CID_IGNORE);
2790         }
2791 
2792         if (ret != 0) {
2793             mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_cid_len returned -%#04x\n\n",
2794                            (unsigned int) -ret);
2795             goto exit;
2796         }
2797     }
2798 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2799 
2800 #if defined(MBEDTLS_SSL_DTLS_SRTP)
2801     const mbedtls_ssl_srtp_profile forced_profile[] =
2802     { opt.force_srtp_profile, MBEDTLS_TLS_SRTP_UNSET };
2803     if (opt.use_srtp == 1) {
2804         if (opt.force_srtp_profile != 0) {
2805             ret = mbedtls_ssl_conf_dtls_srtp_protection_profiles(&conf, forced_profile);
2806         } else {
2807             ret = mbedtls_ssl_conf_dtls_srtp_protection_profiles(&conf, default_profiles);
2808         }
2809 
2810         if (ret != 0) {
2811             mbedtls_printf(
2812                 " failed\n  ! mbedtls_ssl_conf_dtls_srtp_protection_profiles returned %d\n\n",
2813                 ret);
2814             goto exit;
2815         }
2816 
2817         mbedtls_ssl_conf_srtp_mki_value_supported(&conf,
2818                                                   opt.support_mki ?
2819                                                   MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED :
2820                                                   MBEDTLS_SSL_DTLS_SRTP_MKI_UNSUPPORTED);
2821 
2822     } else if (opt.force_srtp_profile != 0) {
2823         mbedtls_printf(" failed\n  ! must enable use_srtp to force srtp profile\n\n");
2824         goto exit;
2825     }
2826 #endif /* MBEDTLS_SSL_DTLS_SRTP */
2827 
2828 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
2829     if (opt.extended_ms != DFL_EXTENDED_MS) {
2830         mbedtls_ssl_conf_extended_master_secret(&conf, opt.extended_ms);
2831     }
2832 #endif
2833 
2834 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
2835     if (opt.etm != DFL_ETM) {
2836         mbedtls_ssl_conf_encrypt_then_mac(&conf, opt.etm);
2837     }
2838 #endif
2839 
2840 #if defined(MBEDTLS_SSL_ALPN)
2841     if (opt.alpn_string != NULL) {
2842         if ((ret = mbedtls_ssl_conf_alpn_protocols(&conf, alpn_list)) != 0) {
2843             mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_alpn_protocols returned %d\n\n", ret);
2844             goto exit;
2845         }
2846     }
2847 #endif
2848 
2849     if (opt.reproducible) {
2850 #if defined(MBEDTLS_HAVE_TIME)
2851 #if defined(MBEDTLS_PLATFORM_TIME_ALT)
2852         mbedtls_platform_set_time(dummy_constant_time);
2853 #else
2854         fprintf(stderr, "Warning: reproducible option used without constant time\n");
2855 #endif
2856 #endif  /* MBEDTLS_HAVE_TIME */
2857     }
2858     mbedtls_ssl_conf_rng(&conf, rng_get, &rng);
2859     mbedtls_ssl_conf_dbg(&conf, my_debug, stdout);
2860 
2861 #if defined(MBEDTLS_SSL_CACHE_C)
2862     if (opt.cache_max != -1) {
2863         mbedtls_ssl_cache_set_max_entries(&cache, opt.cache_max);
2864     }
2865 
2866 #if defined(MBEDTLS_HAVE_TIME)
2867     if (opt.cache_timeout != -1) {
2868         mbedtls_ssl_cache_set_timeout(&cache, opt.cache_timeout);
2869     }
2870 #endif
2871 
2872     mbedtls_ssl_conf_session_cache(&conf, &cache,
2873                                    mbedtls_ssl_cache_get,
2874                                    mbedtls_ssl_cache_set);
2875 #endif
2876 
2877 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_TICKET_C)
2878     if (opt.tickets != MBEDTLS_SSL_SESSION_TICKETS_DISABLED) {
2879 #if defined(MBEDTLS_HAVE_TIME)
2880         if (opt.dummy_ticket) {
2881             mbedtls_ssl_conf_session_tickets_cb(&conf,
2882                                                 dummy_ticket_write,
2883                                                 dummy_ticket_parse,
2884                                                 NULL);
2885         } else
2886 #endif /* MBEDTLS_HAVE_TIME */
2887         {
2888             if ((ret = mbedtls_ssl_ticket_setup(&ticket_ctx,
2889                                                 rng_get, &rng,
2890                                                 opt.ticket_aead,
2891                                                 opt.ticket_timeout)) != 0) {
2892                 mbedtls_printf(
2893                     " failed\n  ! mbedtls_ssl_ticket_setup returned %d\n\n",
2894                     ret);
2895                 goto exit;
2896             }
2897 
2898             mbedtls_ssl_conf_session_tickets_cb(&conf,
2899                                                 mbedtls_ssl_ticket_write,
2900                                                 mbedtls_ssl_ticket_parse,
2901                                                 &ticket_ctx);
2902         }
2903 
2904 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2905         mbedtls_ssl_conf_new_session_tickets(&conf, opt.tickets);
2906 #endif
2907         /* exercise manual ticket rotation (not required for typical use)
2908          * (used for external synchronization of session ticket encryption keys)
2909          */
2910         if (opt.ticket_rotate) {
2911             unsigned char kbuf[MBEDTLS_SSL_TICKET_MAX_KEY_BYTES];
2912             unsigned char name[MBEDTLS_SSL_TICKET_KEY_NAME_BYTES];
2913             if ((ret = rng_get(&rng, name, sizeof(name))) != 0 ||
2914                 (ret = rng_get(&rng, kbuf, sizeof(kbuf))) != 0 ||
2915                 (ret = mbedtls_ssl_ticket_rotate(&ticket_ctx,
2916                                                  name, sizeof(name), kbuf, sizeof(kbuf),
2917                                                  opt.ticket_timeout)) != 0) {
2918                 mbedtls_printf(" failed\n  ! mbedtls_ssl_ticket_rotate returned %d\n\n", ret);
2919                 goto exit;
2920             }
2921         }
2922     }
2923 #endif
2924 
2925 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2926     if (opt.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
2927 #if defined(MBEDTLS_SSL_COOKIE_C)
2928         if (opt.cookies > 0) {
2929             if ((ret = mbedtls_ssl_cookie_setup(&cookie_ctx,
2930                                                 rng_get, &rng)) != 0) {
2931                 mbedtls_printf(" failed\n  ! mbedtls_ssl_cookie_setup returned %d\n\n", ret);
2932                 goto exit;
2933             }
2934 
2935             mbedtls_ssl_conf_dtls_cookies(&conf, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check,
2936                                           &cookie_ctx);
2937         } else
2938 #endif /* MBEDTLS_SSL_COOKIE_C */
2939 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
2940         if (opt.cookies == 0) {
2941             mbedtls_ssl_conf_dtls_cookies(&conf, NULL, NULL, NULL);
2942         } else
2943 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
2944         {
2945             ; /* Nothing to do */
2946         }
2947 
2948 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
2949         if (opt.anti_replay != DFL_ANTI_REPLAY) {
2950             mbedtls_ssl_conf_dtls_anti_replay(&conf, opt.anti_replay);
2951         }
2952 #endif
2953 
2954         if (opt.badmac_limit != DFL_BADMAC_LIMIT) {
2955             mbedtls_ssl_conf_dtls_badmac_limit(&conf, opt.badmac_limit);
2956         }
2957     }
2958 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2959 
2960     if (opt.force_ciphersuite[0] != DFL_FORCE_CIPHER) {
2961         mbedtls_ssl_conf_ciphersuites(&conf, opt.force_ciphersuite);
2962     }
2963 
2964 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2965     mbedtls_ssl_conf_tls13_key_exchange_modes(&conf, opt.tls13_kex_modes);
2966 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2967 
2968     if (opt.allow_legacy != DFL_ALLOW_LEGACY) {
2969         mbedtls_ssl_conf_legacy_renegotiation(&conf, opt.allow_legacy);
2970     }
2971 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2972     mbedtls_ssl_conf_renegotiation(&conf, opt.renegotiation);
2973 
2974     if (opt.renego_delay != DFL_RENEGO_DELAY) {
2975         mbedtls_ssl_conf_renegotiation_enforced(&conf, opt.renego_delay);
2976     }
2977 
2978     if (opt.renego_period != DFL_RENEGO_PERIOD) {
2979         PUT_UINT64_BE(renego_period, opt.renego_period, 0);
2980         mbedtls_ssl_conf_renegotiation_period(&conf, renego_period);
2981     }
2982 #endif
2983 
2984 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2985     if (strcmp(opt.ca_path, "none") != 0 &&
2986         strcmp(opt.ca_file, "none") != 0) {
2987 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
2988         if (opt.ca_callback != 0) {
2989             mbedtls_ssl_conf_ca_cb(&conf, ca_callback, &cacert);
2990         } else
2991 #endif
2992         mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
2993     }
2994     if (key_cert_init) {
2995         mbedtls_pk_context *pk = &pkey;
2996 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
2997         if (opt.async_private_delay1 >= 0) {
2998             ret = ssl_async_set_key(&ssl_async_keys, &srvcert, pk, 0,
2999                                     opt.async_private_delay1);
3000             if (ret < 0) {
3001                 mbedtls_printf("  Test error: ssl_async_set_key failed (%d)\n",
3002                                ret);
3003                 goto exit;
3004             }
3005             pk = NULL;
3006         }
3007 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3008         if ((ret = mbedtls_ssl_conf_own_cert(&conf, &srvcert, pk)) != 0) {
3009             mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_own_cert returned %d\n\n", ret);
3010             goto exit;
3011         }
3012     }
3013     if (key_cert_init2) {
3014         mbedtls_pk_context *pk = &pkey2;
3015 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3016         if (opt.async_private_delay2 >= 0) {
3017             ret = ssl_async_set_key(&ssl_async_keys, &srvcert2, pk, 0,
3018                                     opt.async_private_delay2);
3019             if (ret < 0) {
3020                 mbedtls_printf("  Test error: ssl_async_set_key failed (%d)\n",
3021                                ret);
3022                 goto exit;
3023             }
3024             pk = NULL;
3025         }
3026 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3027         if ((ret = mbedtls_ssl_conf_own_cert(&conf, &srvcert2, pk)) != 0) {
3028             mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_own_cert returned %d\n\n", ret);
3029             goto exit;
3030         }
3031     }
3032 
3033 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3034     if (opt.async_operations[0] != '-') {
3035         mbedtls_ssl_async_sign_t *sign = NULL;
3036         mbedtls_ssl_async_decrypt_t *decrypt = NULL;
3037         const char *r;
3038         for (r = opt.async_operations; *r; r++) {
3039             switch (*r) {
3040                 case 'd':
3041                     decrypt = ssl_async_decrypt;
3042                     break;
3043                 case 's':
3044                     sign = ssl_async_sign;
3045                     break;
3046             }
3047         }
3048         ssl_async_keys.inject_error = (opt.async_private_error < 0 ?
3049                                        -opt.async_private_error :
3050                                        opt.async_private_error);
3051         ssl_async_keys.f_rng = rng_get;
3052         ssl_async_keys.p_rng = &rng;
3053         mbedtls_ssl_conf_async_private_cb(&conf,
3054                                           sign,
3055                                           decrypt,
3056                                           ssl_async_resume,
3057                                           ssl_async_cancel,
3058                                           &ssl_async_keys);
3059     }
3060 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3061 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
3062 
3063 #if defined(SNI_OPTION)
3064     if (opt.sni != NULL) {
3065         mbedtls_ssl_conf_sni(&conf, sni_callback, sni_info);
3066         mbedtls_ssl_conf_cert_cb(&conf, cert_callback);
3067 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3068         if (opt.async_private_delay2 >= 0) {
3069             sni_entry *cur;
3070             for (cur = sni_info; cur != NULL; cur = cur->next) {
3071                 ret = ssl_async_set_key(&ssl_async_keys,
3072                                         cur->cert, cur->key, 1,
3073                                         opt.async_private_delay2);
3074                 if (ret < 0) {
3075                     mbedtls_printf("  Test error: ssl_async_set_key failed (%d)\n",
3076                                    ret);
3077                     goto exit;
3078                 }
3079                 cur->key = NULL;
3080             }
3081         }
3082 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3083     }
3084 #endif
3085 
3086 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS) || \
3087     (defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED) && \
3088     defined(PSA_WANT_ALG_FFDH))
3089     if (opt.groups != NULL &&
3090         strcmp(opt.groups, "default") != 0) {
3091         mbedtls_ssl_conf_groups(&conf, group_list);
3092     }
3093 #endif
3094 
3095 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
3096     if (opt.sig_algs != NULL) {
3097         mbedtls_ssl_conf_sig_algs(&conf, sig_alg_list);
3098     }
3099 #endif
3100 
3101 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
3102 
3103     if (strlen(opt.psk) != 0 && strlen(opt.psk_identity) != 0) {
3104 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3105         if (opt.psk_opaque != 0) {
3106             /* The algorithm has already been determined earlier. */
3107             status = psa_setup_psk_key_slot(&psk_slot, alg, psk, psk_len);
3108             if (status != PSA_SUCCESS) {
3109                 fprintf(stderr, "SETUP FAIL\n");
3110                 ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
3111                 goto exit;
3112             }
3113             if ((ret = mbedtls_ssl_conf_psk_opaque(&conf, psk_slot,
3114                                                    (const unsigned char *) opt.psk_identity,
3115                                                    strlen(opt.psk_identity))) != 0) {
3116                 mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_psk_opaque returned %d\n\n",
3117                                ret);
3118                 goto exit;
3119             }
3120         } else
3121 #endif /* MBEDTLS_USE_PSA_CRYPTO */
3122         if (psk_len > 0) {
3123             ret = mbedtls_ssl_conf_psk(&conf, psk, psk_len,
3124                                        (const unsigned char *) opt.psk_identity,
3125                                        strlen(opt.psk_identity));
3126             if (ret != 0) {
3127                 mbedtls_printf("  failed\n  mbedtls_ssl_conf_psk returned -0x%04X\n\n",
3128                                (unsigned int) -ret);
3129                 goto exit;
3130             }
3131         }
3132     }
3133 
3134     if (opt.psk_list != NULL) {
3135 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3136         if (opt.psk_list_opaque != 0) {
3137             psk_entry *cur_psk;
3138             for (cur_psk = psk_info; cur_psk != NULL; cur_psk = cur_psk->next) {
3139 
3140                 status = psa_setup_psk_key_slot(&cur_psk->slot, alg,
3141                                                 cur_psk->key,
3142                                                 cur_psk->key_len);
3143                 if (status != PSA_SUCCESS) {
3144                     ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
3145                     goto exit;
3146                 }
3147             }
3148         }
3149 #endif /* MBEDTLS_USE_PSA_CRYPTO */
3150 
3151         mbedtls_ssl_conf_psk_cb(&conf, psk_callback, psk_info);
3152     }
3153 #endif
3154 
3155 #if defined(MBEDTLS_DHM_C)
3156     /*
3157      * Use different group than default DHM group
3158      */
3159 #if defined(MBEDTLS_FS_IO)
3160     if (opt.dhm_file != NULL) {
3161         ret = mbedtls_ssl_conf_dh_param_ctx(&conf, &dhm);
3162     }
3163 #endif
3164     if (ret != 0) {
3165         mbedtls_printf("  failed\n  mbedtls_ssl_conf_dh_param returned -0x%04X\n\n",
3166                        (unsigned int) -ret);
3167         goto exit;
3168     }
3169 #endif
3170 
3171     if (opt.min_version != DFL_MIN_VERSION) {
3172         mbedtls_ssl_conf_min_tls_version(&conf, opt.min_version);
3173     }
3174 
3175     if (opt.max_version != DFL_MIN_VERSION) {
3176         mbedtls_ssl_conf_max_tls_version(&conf, opt.max_version);
3177     }
3178 
3179     if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
3180         mbedtls_printf(" failed\n  ! mbedtls_ssl_setup returned -0x%x\n\n", (unsigned int) -ret);
3181         goto exit;
3182     }
3183 
3184     if (opt.eap_tls != 0) {
3185         mbedtls_ssl_set_export_keys_cb(&ssl, eap_tls_key_derivation,
3186                                        &eap_tls_keying);
3187     } else if (opt.nss_keylog != 0) {
3188         mbedtls_ssl_set_export_keys_cb(&ssl,
3189                                        nss_keylog_export,
3190                                        NULL);
3191     }
3192 #if defined(MBEDTLS_SSL_DTLS_SRTP)
3193     else if (opt.use_srtp != 0) {
3194         mbedtls_ssl_set_export_keys_cb(&ssl, dtls_srtp_key_derivation,
3195                                        &dtls_srtp_keying);
3196     }
3197 #endif /* MBEDTLS_SSL_DTLS_SRTP */
3198 
3199     io_ctx.ssl = &ssl;
3200     io_ctx.net = &client_fd;
3201     mbedtls_ssl_set_bio(&ssl, &io_ctx, send_cb, recv_cb,
3202                         opt.nbio == 0 ? recv_timeout_cb : NULL);
3203 
3204 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3205     if (opt.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3206         if ((ret = mbedtls_ssl_set_cid(&ssl, opt.cid_enabled,
3207                                        cid, cid_len)) != 0) {
3208             mbedtls_printf(" failed\n  ! mbedtls_ssl_set_cid returned %d\n\n",
3209                            ret);
3210             goto exit;
3211         }
3212     }
3213 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3214 
3215 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3216     if (opt.dtls_mtu != DFL_DTLS_MTU) {
3217         mbedtls_ssl_set_mtu(&ssl, opt.dtls_mtu);
3218     }
3219 #endif
3220 
3221 #if defined(MBEDTLS_TIMING_C)
3222     mbedtls_ssl_set_timer_cb(&ssl, &timer, mbedtls_timing_set_delay,
3223                              mbedtls_timing_get_delay);
3224 #endif
3225 
3226     mbedtls_printf(" ok\n");
3227 
3228     /*
3229      * 3. Setup the listening TCP socket
3230      */
3231     mbedtls_printf("  . Bind on %s://%s:%s/ ...",
3232                    opt.transport == MBEDTLS_SSL_TRANSPORT_STREAM ? "tcp" : "udp",
3233                    opt.server_addr ? opt.server_addr : "*",
3234                    opt.server_port);
3235     fflush(stdout);
3236 
3237     if ((ret = mbedtls_net_bind(&listen_fd, opt.server_addr, opt.server_port,
3238                                 opt.transport == MBEDTLS_SSL_TRANSPORT_STREAM ?
3239                                 MBEDTLS_NET_PROTO_TCP : MBEDTLS_NET_PROTO_UDP)) != 0) {
3240         mbedtls_printf(" failed\n  ! mbedtls_net_bind returned -0x%x\n\n", (unsigned int) -ret);
3241         goto exit;
3242     }
3243     mbedtls_printf(" ok\n");
3244 
3245 reset:
3246 #if !defined(_WIN32)
3247     if (received_sigterm) {
3248         mbedtls_printf(" interrupted by SIGTERM (not in net_accept())\n");
3249         if (ret == MBEDTLS_ERR_NET_INVALID_CONTEXT) {
3250             ret = 0;
3251         }
3252 
3253         goto exit;
3254     }
3255 #endif
3256 
3257     if (ret == MBEDTLS_ERR_SSL_CLIENT_RECONNECT) {
3258         mbedtls_printf("  ! Client initiated reconnection from same port\n");
3259         goto handshake;
3260     }
3261 
3262 #ifdef MBEDTLS_ERROR_C
3263     if (ret != 0) {
3264         char error_buf[100];
3265         mbedtls_strerror(ret, error_buf, 100);
3266         mbedtls_printf("Last error was: %d - %s\n\n", ret, error_buf);
3267     }
3268 #endif
3269 
3270     mbedtls_net_free(&client_fd);
3271 
3272     mbedtls_ssl_session_reset(&ssl);
3273 
3274     /*
3275      * 3. Wait until a client connects
3276      */
3277     mbedtls_printf("  . Waiting for a remote connection ...");
3278     fflush(stdout);
3279 
3280     if ((ret = mbedtls_net_accept(&listen_fd, &client_fd,
3281                                   client_ip, sizeof(client_ip), &cliip_len)) != 0) {
3282 #if !defined(_WIN32)
3283         if (received_sigterm) {
3284             mbedtls_printf(" interrupted by SIGTERM (in net_accept())\n");
3285             if (ret == MBEDTLS_ERR_NET_ACCEPT_FAILED) {
3286                 ret = 0;
3287             }
3288 
3289             goto exit;
3290         }
3291 #endif
3292 
3293         mbedtls_printf(" failed\n  ! mbedtls_net_accept returned -0x%x\n\n", (unsigned int) -ret);
3294         goto exit;
3295     }
3296 
3297     if (opt.nbio > 0) {
3298         ret = mbedtls_net_set_nonblock(&client_fd);
3299     } else {
3300         ret = mbedtls_net_set_block(&client_fd);
3301     }
3302     if (ret != 0) {
3303         mbedtls_printf(" failed\n  ! net_set_(non)block() returned -0x%x\n\n", (unsigned int) -ret);
3304         goto exit;
3305     }
3306 
3307     mbedtls_ssl_conf_read_timeout(&conf, opt.read_timeout);
3308 
3309 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
3310     if (opt.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3311         if ((ret = mbedtls_ssl_set_client_transport_id(&ssl,
3312                                                        client_ip, cliip_len)) != 0) {
3313             mbedtls_printf(" failed\n  ! mbedtls_ssl_set_client_transport_id() returned -0x%x\n\n",
3314                            (unsigned int) -ret);
3315             goto exit;
3316         }
3317     }
3318 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
3319 
3320 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
3321     if (opt.ecjpake_pw != DFL_ECJPAKE_PW) {
3322 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3323         if (opt.ecjpake_pw_opaque != DFL_ECJPAKE_PW_OPAQUE) {
3324             psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3325 
3326             psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
3327             psa_set_key_algorithm(&attributes, PSA_ALG_JPAKE);
3328             psa_set_key_type(&attributes, PSA_KEY_TYPE_PASSWORD);
3329 
3330             status = psa_import_key(&attributes,
3331                                     (const unsigned char *) opt.ecjpake_pw,
3332                                     strlen(opt.ecjpake_pw),
3333                                     &ecjpake_pw_slot);
3334             if (status != PSA_SUCCESS) {
3335                 mbedtls_printf(" failed\n  ! psa_import_key returned %d\n\n",
3336                                status);
3337                 goto exit;
3338             }
3339             if ((ret = mbedtls_ssl_set_hs_ecjpake_password_opaque(&ssl,
3340                                                                   ecjpake_pw_slot)) != 0) {
3341                 mbedtls_printf(
3342                     " failed\n  ! mbedtls_ssl_set_hs_ecjpake_password_opaque returned %d\n\n",
3343                     ret);
3344                 goto exit;
3345             }
3346             mbedtls_printf("using opaque password\n");
3347         } else
3348 #endif  /* MBEDTLS_USE_PSA_CRYPTO */
3349         {
3350             if ((ret = mbedtls_ssl_set_hs_ecjpake_password(&ssl,
3351                                                            (const unsigned char *) opt.ecjpake_pw,
3352                                                            strlen(opt.ecjpake_pw))) != 0) {
3353                 mbedtls_printf(" failed\n  ! mbedtls_ssl_set_hs_ecjpake_password returned %d\n\n",
3354                                ret);
3355                 goto exit;
3356             }
3357         }
3358     }
3359 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
3360 
3361 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
3362 #if defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
3363     /* exercise setting DN hints for server certificate request
3364      * (Intended for use where the client cert expected has been signed by
3365      *  a specific CA which is an intermediate in a CA chain, not the root)
3366      * (Additionally, the CA choice would typically be influenced by SNI
3367      *  if being set per-handshake using mbedtls_ssl_set_hs_dn_hints()) */
3368     if (opt.cert_req_dn_hint == 3 && key_cert_init2) {
3369         mbedtls_ssl_set_hs_dn_hints(&ssl, &srvcert2);
3370     }
3371 #endif
3372 #endif
3373 
3374     mbedtls_printf(" ok\n");
3375 
3376     /*
3377      * 4. Handshake
3378      */
3379 handshake:
3380     mbedtls_printf("  . Performing the SSL/TLS handshake...");
3381     fflush(stdout);
3382 
3383     while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
3384 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3385         if (ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS &&
3386             ssl_async_keys.inject_error == SSL_ASYNC_INJECT_ERROR_CANCEL) {
3387             mbedtls_printf(" cancelling on injected error\n");
3388             break;
3389         }
3390 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3391 
3392         if (!mbedtls_status_is_ssl_in_progress(ret)) {
3393             break;
3394         }
3395 
3396         /* For event-driven IO, wait for socket to become available */
3397         if (opt.event == 1 /* level triggered IO */) {
3398 #if defined(MBEDTLS_TIMING_C)
3399             ret = idle(&client_fd, &timer, ret);
3400 #else
3401             ret = idle(&client_fd, ret);
3402 #endif
3403             if (ret != 0) {
3404                 goto reset;
3405             }
3406         }
3407     }
3408 
3409     if (ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) {
3410         mbedtls_printf(" hello verification requested\n");
3411         ret = 0;
3412         goto reset;
3413     } else if (ret != 0) {
3414         mbedtls_printf(" failed\n  ! mbedtls_ssl_handshake returned -0x%x\n\n",
3415                        (unsigned int) -ret);
3416 
3417 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
3418         if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
3419             char vrfy_buf[512];
3420             flags = mbedtls_ssl_get_verify_result(&ssl);
3421 
3422             x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), "  ! ", flags);
3423 
3424             mbedtls_printf("%s\n", vrfy_buf);
3425         }
3426 #endif
3427 
3428 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3429         if (opt.async_private_error < 0) {
3430             /* Injected error only the first time round, to test reset */
3431             ssl_async_keys.inject_error = SSL_ASYNC_INJECT_ERROR_NONE;
3432         }
3433 #endif
3434         goto reset;
3435     } else { /* ret == 0 */
3436         int suite_id = mbedtls_ssl_get_ciphersuite_id_from_ssl(&ssl);
3437         const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
3438         ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(suite_id);
3439 
3440         mbedtls_printf(" ok\n    [ Protocol is %s ]\n"
3441                        "    [ Ciphersuite is %s ]\n"
3442                        "    [ Key size is %u ]\n",
3443                        mbedtls_ssl_get_version(&ssl),
3444                        mbedtls_ssl_ciphersuite_get_name(ciphersuite_info),
3445                        (unsigned int)
3446                        mbedtls_ssl_ciphersuite_get_cipher_key_bitlen(ciphersuite_info));
3447     }
3448 
3449     if ((ret = mbedtls_ssl_get_record_expansion(&ssl)) >= 0) {
3450         mbedtls_printf("    [ Record expansion is %d ]\n", ret);
3451     } else {
3452         mbedtls_printf("    [ Record expansion is unknown ]\n");
3453     }
3454 
3455 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
3456     mbedtls_printf("    [ Maximum incoming record payload length is %u ]\n",
3457                    (unsigned int) mbedtls_ssl_get_max_in_record_payload(&ssl));
3458     mbedtls_printf("    [ Maximum outgoing record payload length is %u ]\n",
3459                    (unsigned int) mbedtls_ssl_get_max_out_record_payload(&ssl));
3460 #endif
3461 
3462 #if defined(MBEDTLS_SSL_ALPN)
3463     if (opt.alpn_string != NULL) {
3464         const char *alp = mbedtls_ssl_get_alpn_protocol(&ssl);
3465         mbedtls_printf("    [ Application Layer Protocol is %s ]\n",
3466                        alp ? alp : "(none)");
3467     }
3468 #endif
3469 
3470 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
3471     /*
3472      * 5. Verify the client certificate
3473      */
3474     mbedtls_printf("  . Verifying peer X.509 certificate...");
3475 
3476     if ((flags = mbedtls_ssl_get_verify_result(&ssl)) != 0) {
3477         char vrfy_buf[512];
3478 
3479         mbedtls_printf(" failed\n");
3480 
3481         x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), "  ! ", flags);
3482         mbedtls_printf("%s\n", vrfy_buf);
3483     } else {
3484         mbedtls_printf(" ok\n");
3485     }
3486 
3487 #if !defined(MBEDTLS_X509_REMOVE_INFO)
3488     if (mbedtls_ssl_get_peer_cert(&ssl) != NULL) {
3489         char crt_buf[512];
3490 
3491         mbedtls_printf("  . Peer certificate information    ...\n");
3492         mbedtls_x509_crt_info(crt_buf, sizeof(crt_buf), "      ",
3493                               mbedtls_ssl_get_peer_cert(&ssl));
3494         mbedtls_printf("%s\n", crt_buf);
3495     }
3496 #endif /* MBEDTLS_X509_REMOVE_INFO */
3497 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
3498 
3499     if (opt.eap_tls != 0) {
3500         size_t j = 0;
3501 
3502         if ((ret = mbedtls_ssl_tls_prf(eap_tls_keying.tls_prf_type,
3503                                        eap_tls_keying.master_secret,
3504                                        sizeof(eap_tls_keying.master_secret),
3505                                        eap_tls_label,
3506                                        eap_tls_keying.randbytes,
3507                                        sizeof(eap_tls_keying.randbytes),
3508                                        eap_tls_keymaterial,
3509                                        sizeof(eap_tls_keymaterial)))
3510             != 0) {
3511             mbedtls_printf(" failed\n  ! mbedtls_ssl_tls_prf returned -0x%x\n\n",
3512                            (unsigned int) -ret);
3513             goto reset;
3514         }
3515 
3516         mbedtls_printf("    EAP-TLS key material is:");
3517         for (j = 0; j < sizeof(eap_tls_keymaterial); j++) {
3518             if (j % 8 == 0) {
3519                 mbedtls_printf("\n    ");
3520             }
3521             mbedtls_printf("%02x ", eap_tls_keymaterial[j]);
3522         }
3523         mbedtls_printf("\n");
3524 
3525         if ((ret = mbedtls_ssl_tls_prf(eap_tls_keying.tls_prf_type, NULL, 0,
3526                                        eap_tls_label,
3527                                        eap_tls_keying.randbytes,
3528                                        sizeof(eap_tls_keying.randbytes),
3529                                        eap_tls_iv,
3530                                        sizeof(eap_tls_iv))) != 0) {
3531             mbedtls_printf(" failed\n  ! mbedtls_ssl_tls_prf returned -0x%x\n\n",
3532                            (unsigned int) -ret);
3533             goto reset;
3534         }
3535 
3536         mbedtls_printf("    EAP-TLS IV is:");
3537         for (j = 0; j < sizeof(eap_tls_iv); j++) {
3538             if (j % 8 == 0) {
3539                 mbedtls_printf("\n    ");
3540             }
3541             mbedtls_printf("%02x ", eap_tls_iv[j]);
3542         }
3543         mbedtls_printf("\n");
3544     }
3545 
3546 #if defined(MBEDTLS_SSL_DTLS_SRTP)
3547     else if (opt.use_srtp != 0) {
3548         size_t j = 0;
3549         mbedtls_dtls_srtp_info dtls_srtp_negotiation_result;
3550         mbedtls_ssl_get_dtls_srtp_negotiation_result(&ssl, &dtls_srtp_negotiation_result);
3551 
3552         if (dtls_srtp_negotiation_result.chosen_dtls_srtp_profile
3553             == MBEDTLS_TLS_SRTP_UNSET) {
3554             mbedtls_printf("    Unable to negotiate "
3555                            "the use of DTLS-SRTP\n");
3556         } else {
3557             if ((ret = mbedtls_ssl_tls_prf(dtls_srtp_keying.tls_prf_type,
3558                                            dtls_srtp_keying.master_secret,
3559                                            sizeof(dtls_srtp_keying.master_secret),
3560                                            dtls_srtp_label,
3561                                            dtls_srtp_keying.randbytes,
3562                                            sizeof(dtls_srtp_keying.randbytes),
3563                                            dtls_srtp_key_material,
3564                                            sizeof(dtls_srtp_key_material)))
3565                 != 0) {
3566                 mbedtls_printf(" failed\n  ! mbedtls_ssl_tls_prf returned -0x%x\n\n",
3567                                (unsigned int) -ret);
3568                 goto exit;
3569             }
3570 
3571             mbedtls_printf("    DTLS-SRTP key material is:");
3572             for (j = 0; j < sizeof(dtls_srtp_key_material); j++) {
3573                 if (j % 8 == 0) {
3574                     mbedtls_printf("\n    ");
3575                 }
3576                 mbedtls_printf("%02x ", dtls_srtp_key_material[j]);
3577             }
3578             mbedtls_printf("\n");
3579 
3580             /* produce a less readable output used to perform automatic checks
3581              * - compare client and server output
3582              * - interop test with openssl which client produces this kind of output
3583              */
3584             mbedtls_printf("    Keying material: ");
3585             for (j = 0; j < sizeof(dtls_srtp_key_material); j++) {
3586                 mbedtls_printf("%02X", dtls_srtp_key_material[j]);
3587             }
3588             mbedtls_printf("\n");
3589 
3590             if (dtls_srtp_negotiation_result.mki_len > 0) {
3591                 mbedtls_printf("    DTLS-SRTP mki value: ");
3592                 for (j = 0; j < dtls_srtp_negotiation_result.mki_len; j++) {
3593                     mbedtls_printf("%02X", dtls_srtp_negotiation_result.mki_value[j]);
3594                 }
3595             } else {
3596                 mbedtls_printf("    DTLS-SRTP no mki value negotiated");
3597             }
3598             mbedtls_printf("\n");
3599 
3600         }
3601     }
3602 #endif /* MBEDTLS_SSL_DTLS_SRTP */
3603 
3604 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3605     ret = report_cid_usage(&ssl, "initial handshake");
3606     if (ret != 0) {
3607         goto exit;
3608     }
3609 
3610     if (opt.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3611         if ((ret = mbedtls_ssl_set_cid(&ssl, opt.cid_enabled_renego,
3612                                        cid_renego, cid_renego_len)) != 0) {
3613             mbedtls_printf(" failed\n  ! mbedtls_ssl_set_cid returned %d\n\n",
3614                            ret);
3615             goto exit;
3616         }
3617     }
3618 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3619 
3620 #if defined(MBEDTLS_MEMORY_DEBUG)
3621     mbedtls_memory_buffer_alloc_cur_get(&current_heap_memory, &heap_blocks);
3622     mbedtls_memory_buffer_alloc_max_get(&peak_heap_memory, &heap_blocks);
3623     mbedtls_printf("Heap memory usage after handshake: %lu bytes. Peak memory usage was %lu\n",
3624                    (unsigned long) current_heap_memory, (unsigned long) peak_heap_memory);
3625 #endif  /* MBEDTLS_MEMORY_DEBUG */
3626 
3627     if (opt.exchanges == 0) {
3628         goto close_notify;
3629     }
3630 
3631     exchanges_left = opt.exchanges;
3632 data_exchange:
3633     /*
3634      * 6. Read the HTTP Request
3635      */
3636     mbedtls_printf("  < Read from client:");
3637     fflush(stdout);
3638 
3639     /*
3640      * TLS and DTLS need different reading styles (stream vs datagram)
3641      */
3642     if (opt.transport == MBEDTLS_SSL_TRANSPORT_STREAM) {
3643         do {
3644             int terminated = 0;
3645             len = opt.buffer_size;
3646             memset(buf, 0, opt.buffer_size);
3647             ret = mbedtls_ssl_read(&ssl, buf, len);
3648 
3649             if (mbedtls_status_is_ssl_in_progress(ret)) {
3650                 if (opt.event == 1 /* level triggered IO */) {
3651 #if defined(MBEDTLS_TIMING_C)
3652                     idle(&client_fd, &timer, ret);
3653 #else
3654                     idle(&client_fd, ret);
3655 #endif
3656                 }
3657 
3658                 continue;
3659             }
3660 
3661             if (ret <= 0) {
3662                 switch (ret) {
3663                     case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
3664                         mbedtls_printf(" connection was closed gracefully\n");
3665                         goto close_notify;
3666 
3667                     case 0:
3668                     case MBEDTLS_ERR_NET_CONN_RESET:
3669                         mbedtls_printf(" connection was reset by peer\n");
3670                         ret = MBEDTLS_ERR_NET_CONN_RESET;
3671                         goto reset;
3672 
3673                     default:
3674                         mbedtls_printf(" mbedtls_ssl_read returned -0x%x\n", (unsigned int) -ret);
3675                         goto reset;
3676                 }
3677             }
3678 
3679             if (mbedtls_ssl_get_bytes_avail(&ssl) == 0) {
3680                 len = ret;
3681                 buf[len] = '\0';
3682                 mbedtls_printf(" %d bytes read\n\n%s\n", len, (char *) buf);
3683 
3684                 /* End of message should be detected according to the syntax of the
3685                  * application protocol (eg HTTP), just use a dummy test here. */
3686                 if (buf[len - 1] == '\n') {
3687                     terminated = 1;
3688                 }
3689             } else {
3690                 int extra_len, ori_len;
3691                 unsigned char *larger_buf;
3692 
3693                 ori_len = ret;
3694                 extra_len = (int) mbedtls_ssl_get_bytes_avail(&ssl);
3695 
3696                 larger_buf = mbedtls_calloc(1, ori_len + extra_len + 1);
3697                 if (larger_buf == NULL) {
3698                     mbedtls_printf("  ! memory allocation failed\n");
3699                     ret = 1;
3700                     goto reset;
3701                 }
3702 
3703                 memset(larger_buf, 0, ori_len + extra_len);
3704                 memcpy(larger_buf, buf, ori_len);
3705 
3706                 /* This read should never fail and get the whole cached data */
3707                 ret = mbedtls_ssl_read(&ssl, larger_buf + ori_len, extra_len);
3708                 if (ret != extra_len ||
3709                     mbedtls_ssl_get_bytes_avail(&ssl) != 0) {
3710                     mbedtls_printf("  ! mbedtls_ssl_read failed on cached data\n");
3711                     ret = 1;
3712                     goto reset;
3713                 }
3714 
3715                 larger_buf[ori_len + extra_len] = '\0';
3716                 mbedtls_printf(" %d bytes read (%d + %d)\n\n%s\n",
3717                                ori_len + extra_len, ori_len, extra_len,
3718                                (char *) larger_buf);
3719 
3720                 /* End of message should be detected according to the syntax of the
3721                  * application protocol (eg HTTP), just use a dummy test here. */
3722                 if (larger_buf[ori_len + extra_len - 1] == '\n') {
3723                     terminated = 1;
3724                 }
3725 
3726                 mbedtls_free(larger_buf);
3727             }
3728 
3729             if (terminated) {
3730                 ret = 0;
3731                 break;
3732             }
3733         } while (1);
3734     } else { /* Not stream, so datagram */
3735         len = opt.buffer_size;
3736         memset(buf, 0, opt.buffer_size);
3737 
3738         do {
3739             /* Without the call to `mbedtls_ssl_check_pending`, it might
3740              * happen that the client sends application data in the same
3741              * datagram as the Finished message concluding the handshake.
3742              * In this case, the application data would be ready to be
3743              * processed while the underlying transport wouldn't signal
3744              * any further incoming data.
3745              *
3746              * See the test 'Event-driven I/O: session-id resume, UDP packing'
3747              * in tests/ssl-opt.sh.
3748              */
3749 
3750             /* For event-driven IO, wait for socket to become available */
3751             if (mbedtls_ssl_check_pending(&ssl) == 0 &&
3752                 opt.event == 1 /* level triggered IO */) {
3753 #if defined(MBEDTLS_TIMING_C)
3754                 idle(&client_fd, &timer, MBEDTLS_ERR_SSL_WANT_READ);
3755 #else
3756                 idle(&client_fd, MBEDTLS_ERR_SSL_WANT_READ);
3757 #endif
3758             }
3759 
3760             ret = mbedtls_ssl_read(&ssl, buf, len);
3761 
3762             /* Note that even if `mbedtls_ssl_check_pending` returns true,
3763              * it can happen that the subsequent call to `mbedtls_ssl_read`
3764              * returns `MBEDTLS_ERR_SSL_WANT_READ`, because the pending messages
3765              * might be discarded (e.g. because they are retransmissions). */
3766         } while (mbedtls_status_is_ssl_in_progress(ret));
3767 
3768         if (ret <= 0) {
3769             switch (ret) {
3770                 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
3771                     mbedtls_printf(" connection was closed gracefully\n");
3772                     goto close_notify;
3773 
3774                 default:
3775                     mbedtls_printf(" mbedtls_ssl_read returned -0x%x\n", (unsigned int) -ret);
3776                     goto reset;
3777             }
3778         }
3779 
3780         len = ret;
3781         buf[len] = '\0';
3782         mbedtls_printf(" %d bytes read\n\n%s", len, (char *) buf);
3783         ret = 0;
3784     }
3785 
3786     /*
3787      * 7a. Request renegotiation while client is waiting for input from us.
3788      * (only on the first exchange, to be able to test retransmission)
3789      */
3790 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3791     if (opt.renegotiate && exchanges_left == opt.exchanges) {
3792         mbedtls_printf("  . Requestion renegotiation...");
3793         fflush(stdout);
3794 
3795         while ((ret = mbedtls_ssl_renegotiate(&ssl)) != 0) {
3796             if (!mbedtls_status_is_ssl_in_progress(ret)) {
3797                 mbedtls_printf(" failed\n  ! mbedtls_ssl_renegotiate returned %d\n\n", ret);
3798                 goto reset;
3799             }
3800 
3801             /* For event-driven IO, wait for socket to become available */
3802             if (opt.event == 1 /* level triggered IO */) {
3803 #if defined(MBEDTLS_TIMING_C)
3804                 idle(&client_fd, &timer, ret);
3805 #else
3806                 idle(&client_fd, ret);
3807 #endif
3808             }
3809         }
3810 
3811         mbedtls_printf(" ok\n");
3812     }
3813 #endif /* MBEDTLS_SSL_RENEGOTIATION */
3814 
3815 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
3816     ret = report_cid_usage(&ssl, "after renegotiation");
3817     if (ret != 0) {
3818         goto exit;
3819     }
3820 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
3821 
3822     /*
3823      * 7. Write the 200 Response
3824      */
3825     mbedtls_printf("  > Write to client:");
3826     fflush(stdout);
3827 
3828     /* If the format of the response changes, make sure there is enough
3829      * room in buf (buf_content_size calculation above). */
3830     len = sprintf((char *) buf, HTTP_RESPONSE,
3831                   mbedtls_ssl_get_ciphersuite(&ssl));
3832 
3833     /* Add padding to the response to reach opt.response_size in length */
3834     if (opt.response_size != DFL_RESPONSE_SIZE &&
3835         len < opt.response_size) {
3836         memset(buf + len, 'B', opt.response_size - len);
3837         len += opt.response_size - len;
3838     }
3839 
3840     /* Truncate if response size is smaller than the "natural" size */
3841     if (opt.response_size != DFL_RESPONSE_SIZE &&
3842         len > opt.response_size) {
3843         len = opt.response_size;
3844 
3845         /* Still end with \r\n unless that's really not possible */
3846         if (len >= 2) {
3847             buf[len - 2] = '\r';
3848         }
3849         if (len >= 1) {
3850             buf[len - 1] = '\n';
3851         }
3852     }
3853 
3854     if (opt.transport == MBEDTLS_SSL_TRANSPORT_STREAM) {
3855         for (written = 0, frags = 0; written < len; written += ret, frags++) {
3856             while ((ret = mbedtls_ssl_write(&ssl, buf + written, len - written))
3857                    <= 0) {
3858                 if (ret == MBEDTLS_ERR_NET_CONN_RESET) {
3859                     mbedtls_printf(" failed\n  ! peer closed the connection\n\n");
3860                     goto reset;
3861                 }
3862 
3863                 if (!mbedtls_status_is_ssl_in_progress(ret)) {
3864                     mbedtls_printf(" failed\n  ! mbedtls_ssl_write returned %d\n\n", ret);
3865                     goto reset;
3866                 }
3867 
3868                 /* For event-driven IO, wait for socket to become available */
3869                 if (opt.event == 1 /* level triggered IO */) {
3870 #if defined(MBEDTLS_TIMING_C)
3871                     idle(&client_fd, &timer, ret);
3872 #else
3873                     idle(&client_fd, ret);
3874 #endif
3875                 }
3876             }
3877         }
3878     } else { /* Not stream, so datagram */
3879         while (1) {
3880             ret = mbedtls_ssl_write(&ssl, buf, len);
3881 
3882             if (!mbedtls_status_is_ssl_in_progress(ret)) {
3883                 break;
3884             }
3885 
3886             /* For event-driven IO, wait for socket to become available */
3887             if (opt.event == 1 /* level triggered IO */) {
3888 #if defined(MBEDTLS_TIMING_C)
3889                 idle(&client_fd, &timer, ret);
3890 #else
3891                 idle(&client_fd, ret);
3892 #endif
3893             }
3894         }
3895 
3896         if (ret < 0) {
3897             mbedtls_printf(" failed\n  ! mbedtls_ssl_write returned %d\n\n", ret);
3898             goto reset;
3899         }
3900 
3901         frags = 1;
3902         written = ret;
3903     }
3904 
3905     buf[written] = '\0';
3906     mbedtls_printf(" %d bytes written in %d fragments\n\n%s\n", written, frags, (char *) buf);
3907     ret = 0;
3908 
3909     /*
3910      * 7b. Simulate serialize/deserialize and go back to data exchange
3911      */
3912 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
3913     if (opt.serialize != 0) {
3914         size_t buf_len;
3915 
3916         mbedtls_printf("  . Serializing live connection...");
3917 
3918         ret = mbedtls_ssl_context_save(&ssl, NULL, 0, &buf_len);
3919         if (ret != MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL) {
3920             mbedtls_printf(" failed\n  ! mbedtls_ssl_context_save returned "
3921                            "-0x%x\n\n", (unsigned int) -ret);
3922 
3923             goto exit;
3924         }
3925 
3926         if ((context_buf = mbedtls_calloc(1, buf_len)) == NULL) {
3927             mbedtls_printf(" failed\n  ! Couldn't allocate buffer for "
3928                            "serialized context");
3929 
3930             goto exit;
3931         }
3932         context_buf_len = buf_len;
3933 
3934         if ((ret = mbedtls_ssl_context_save(&ssl, context_buf,
3935                                             buf_len, &buf_len)) != 0) {
3936             mbedtls_printf(" failed\n  ! mbedtls_ssl_context_save returned "
3937                            "-0x%x\n\n", (unsigned int) -ret);
3938 
3939             goto exit;
3940         }
3941 
3942         mbedtls_printf(" ok\n");
3943 
3944         /* Save serialized context to the 'opt.context_file' as a base64 code */
3945         if (0 < strlen(opt.context_file)) {
3946             FILE *b64_file;
3947             uint8_t *b64_buf;
3948             size_t b64_len;
3949 
3950             mbedtls_printf("  . Save serialized context to a file... ");
3951 
3952             mbedtls_base64_encode(NULL, 0, &b64_len, context_buf, buf_len);
3953 
3954             if ((b64_buf = mbedtls_calloc(1, b64_len)) == NULL) {
3955                 mbedtls_printf("failed\n  ! Couldn't allocate buffer for "
3956                                "the base64 code\n");
3957                 goto exit;
3958             }
3959 
3960             if ((ret = mbedtls_base64_encode(b64_buf, b64_len, &b64_len,
3961                                              context_buf, buf_len)) != 0) {
3962                 mbedtls_printf("failed\n  ! mbedtls_base64_encode returned "
3963                                "-0x%x\n", (unsigned int) -ret);
3964                 mbedtls_free(b64_buf);
3965                 goto exit;
3966             }
3967 
3968             if ((b64_file = fopen(opt.context_file, "w")) == NULL) {
3969                 mbedtls_printf("failed\n  ! Cannot open '%s' for writing.\n",
3970                                opt.context_file);
3971                 mbedtls_free(b64_buf);
3972                 goto exit;
3973             }
3974 
3975             if (b64_len != fwrite(b64_buf, 1, b64_len, b64_file)) {
3976                 mbedtls_printf("failed\n  ! fwrite(%ld bytes) failed\n",
3977                                (long) b64_len);
3978                 mbedtls_free(b64_buf);
3979                 fclose(b64_file);
3980                 goto exit;
3981             }
3982 
3983             mbedtls_free(b64_buf);
3984             fclose(b64_file);
3985 
3986             mbedtls_printf("ok\n");
3987         }
3988 
3989         /*
3990          * This simulates a workflow where you have a long-lived server
3991          * instance, potentially with a pool of ssl_context objects, and you
3992          * just want to re-use one while the connection is inactive: in that
3993          * case you can just reset() it, and then it's ready to receive
3994          * serialized data from another connection (or the same here).
3995          */
3996         if (opt.serialize == 1) {
3997             /* nothing to do here, done by context_save() already */
3998             mbedtls_printf("  . Context has been reset... ok\n");
3999         }
4000 
4001         /*
4002          * This simulates a workflow where you have one server instance per
4003          * connection, and want to release it entire when the connection is
4004          * inactive, and spawn it again when needed again - this would happen
4005          * between ssl_free() and ssl_init() below, together with any other
4006          * teardown/startup code needed - for example, preparing the
4007          * ssl_config again (see section 3 "setup stuff" in this file).
4008          */
4009         if (opt.serialize == 2) {
4010             mbedtls_printf("  . Freeing and reinitializing context...");
4011 
4012             mbedtls_ssl_free(&ssl);
4013 
4014             mbedtls_ssl_init(&ssl);
4015 
4016             if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
4017                 mbedtls_printf(" failed\n  ! mbedtls_ssl_setup returned "
4018                                "-0x%x\n\n", (unsigned int) -ret);
4019                 goto exit;
4020             }
4021 
4022             /*
4023              * This illustrates the minimum amount of things you need to set
4024              * up, however you could set up much more if desired, for example
4025              * if you want to share your set up code between the case of
4026              * establishing a new connection and this case.
4027              */
4028             if (opt.nbio == 2) {
4029                 mbedtls_ssl_set_bio(&ssl, &client_fd, delayed_send,
4030                                     delayed_recv, NULL);
4031             } else {
4032                 mbedtls_ssl_set_bio(&ssl, &client_fd, mbedtls_net_send,
4033                                     mbedtls_net_recv,
4034                                     opt.nbio == 0 ? mbedtls_net_recv_timeout : NULL);
4035             }
4036 
4037 #if defined(MBEDTLS_TIMING_C)
4038             mbedtls_ssl_set_timer_cb(&ssl, &timer,
4039                                      mbedtls_timing_set_delay,
4040                                      mbedtls_timing_get_delay);
4041 #endif /* MBEDTLS_TIMING_C */
4042 
4043             mbedtls_printf(" ok\n");
4044         }
4045 
4046         mbedtls_printf("  . Deserializing connection...");
4047 
4048         if ((ret = mbedtls_ssl_context_load(&ssl, context_buf,
4049                                             buf_len)) != 0) {
4050             mbedtls_printf("failed\n  ! mbedtls_ssl_context_load returned "
4051                            "-0x%x\n\n", (unsigned int) -ret);
4052 
4053             goto exit;
4054         }
4055 
4056         mbedtls_free(context_buf);
4057         context_buf = NULL;
4058         context_buf_len = 0;
4059 
4060         mbedtls_printf(" ok\n");
4061     }
4062 #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */
4063 
4064     /*
4065      * 7c. Continue doing data exchanges?
4066      */
4067     if (--exchanges_left > 0) {
4068         goto data_exchange;
4069     }
4070 
4071     /*
4072      * 8. Done, cleanly close the connection
4073      */
4074 close_notify:
4075     mbedtls_printf("  . Closing the connection...");
4076 
4077     /* No error checking, the connection might be closed already */
4078     do {
4079         ret = mbedtls_ssl_close_notify(&ssl);
4080     } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
4081     ret = 0;
4082 
4083     mbedtls_printf(" done\n");
4084 
4085 #if defined(MBEDTLS_SSL_CACHE_C)
4086     if (opt.cache_remove > 0) {
4087         mbedtls_ssl_cache_remove(&cache, ssl.session->id, ssl.session->id_len);
4088     }
4089 #endif
4090 
4091     goto reset;
4092 
4093     /*
4094      * Cleanup and exit
4095      */
4096 exit:
4097 #ifdef MBEDTLS_ERROR_C
4098     if (ret != 0) {
4099         char error_buf[100];
4100         mbedtls_strerror(ret, error_buf, 100);
4101         mbedtls_printf("Last error was: -0x%X - %s\n\n", (unsigned int) -ret, error_buf);
4102     }
4103 #endif
4104 
4105     if (opt.query_config_mode == DFL_QUERY_CONFIG_MODE) {
4106         mbedtls_printf("  . Cleaning up...");
4107         fflush(stdout);
4108     }
4109 
4110     mbedtls_net_free(&client_fd);
4111     mbedtls_net_free(&listen_fd);
4112 
4113     mbedtls_ssl_free(&ssl);
4114     mbedtls_ssl_config_free(&conf);
4115 
4116 #if defined(MBEDTLS_SSL_CACHE_C)
4117     mbedtls_ssl_cache_free(&cache);
4118 #endif
4119 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_TICKET_C)
4120     mbedtls_ssl_ticket_free(&ticket_ctx);
4121 #endif
4122 #if defined(MBEDTLS_SSL_COOKIE_C)
4123     mbedtls_ssl_cookie_free(&cookie_ctx);
4124 #endif
4125 
4126 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
4127     if (context_buf != NULL) {
4128         mbedtls_platform_zeroize(context_buf, context_buf_len);
4129     }
4130     mbedtls_free(context_buf);
4131 #endif
4132 
4133 #if defined(SNI_OPTION)
4134     sni_free(sni_info);
4135 #endif
4136 
4137 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
4138     ret = psk_free(psk_info);
4139     if ((ret != 0) && (opt.query_config_mode == DFL_QUERY_CONFIG_MODE)) {
4140         mbedtls_printf("Failed to list of opaque PSKs - error was %d\n", ret);
4141     }
4142 #endif
4143 
4144 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
4145     mbedtls_x509_crt_free(&cacert);
4146     mbedtls_x509_crt_free(&srvcert);
4147     mbedtls_pk_free(&pkey);
4148     mbedtls_x509_crt_free(&srvcert2);
4149     mbedtls_pk_free(&pkey2);
4150 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4151     psa_destroy_key(key_slot);
4152     psa_destroy_key(key_slot2);
4153 #endif
4154 #endif
4155 
4156 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_FS_IO)
4157     mbedtls_dhm_free(&dhm);
4158 #endif
4159 
4160 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
4161     for (i = 0; (size_t) i < ssl_async_keys.slots_used; i++) {
4162         if (ssl_async_keys.slots[i].pk_owned) {
4163             mbedtls_pk_free(ssl_async_keys.slots[i].pk);
4164             mbedtls_free(ssl_async_keys.slots[i].pk);
4165             ssl_async_keys.slots[i].pk = NULL;
4166         }
4167     }
4168 #endif
4169 
4170 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED) && \
4171     defined(MBEDTLS_USE_PSA_CRYPTO)
4172     if (opt.psk_opaque != 0) {
4173         /* This is ok even if the slot hasn't been
4174          * initialized (we might have jumed here
4175          * immediately because of bad cmd line params,
4176          * for example). */
4177         status = psa_destroy_key(psk_slot);
4178         if ((status != PSA_SUCCESS) &&
4179             (opt.query_config_mode == DFL_QUERY_CONFIG_MODE)) {
4180             mbedtls_printf("Failed to destroy key slot %u - error was %d",
4181                            (unsigned) MBEDTLS_SVC_KEY_ID_GET_KEY_ID(psk_slot),
4182                            (int) status);
4183         }
4184     }
4185 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED &&
4186           MBEDTLS_USE_PSA_CRYPTO */
4187 
4188 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \
4189     defined(MBEDTLS_USE_PSA_CRYPTO)
4190     /*
4191      * In case opaque keys it's the user responsibility to keep the key valid
4192      * for the duration of the handshake and destroy it at the end
4193      */
4194     if ((opt.ecjpake_pw_opaque != DFL_ECJPAKE_PW_OPAQUE)) {
4195         psa_key_attributes_t check_attributes = PSA_KEY_ATTRIBUTES_INIT;
4196 
4197         /* Verify that the key is still valid before destroying it */
4198         if (psa_get_key_attributes(ecjpake_pw_slot, &check_attributes) !=
4199             PSA_SUCCESS) {
4200             if (ret == 0) {
4201                 ret = 1;
4202             }
4203             mbedtls_printf("The EC J-PAKE password key has unexpectedly been already destroyed\n");
4204         } else {
4205             psa_destroy_key(ecjpake_pw_slot);
4206         }
4207     }
4208 #endif  /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED && MBEDTLS_USE_PSA_CRYPTO */
4209 
4210 #if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
4211     const char *message = mbedtls_test_helper_is_psa_leaking();
4212     if (message) {
4213         if (ret == 0) {
4214             ret = 1;
4215         }
4216         mbedtls_printf("PSA memory leak detected: %s\n",  message);
4217     }
4218 #endif
4219 
4220     /* For builds with MBEDTLS_TEST_USE_PSA_CRYPTO_RNG psa crypto
4221      * resources are freed by rng_free(). */
4222 #if (defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)) \
4223     && !defined(MBEDTLS_TEST_USE_PSA_CRYPTO_RNG)
4224     mbedtls_psa_crypto_free();
4225 #endif
4226 
4227     rng_free(&rng);
4228 
4229     mbedtls_free(buf);
4230 
4231 #if defined(MBEDTLS_TEST_HOOKS)
4232     /* Let test hooks detect errors such as resource leaks.
4233      * Don't do it in query_config mode, because some test code prints
4234      * information to stdout and this gets mixed with the regular output. */
4235     if (opt.query_config_mode == DFL_QUERY_CONFIG_MODE) {
4236         if (test_hooks_failure_detected()) {
4237             if (ret == 0) {
4238                 ret = 1;
4239             }
4240             mbedtls_printf("Test hooks detected errors.\n");
4241         }
4242     }
4243     test_hooks_free();
4244 #endif /* MBEDTLS_TEST_HOOKS */
4245 
4246 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
4247 #if defined(MBEDTLS_MEMORY_DEBUG)
4248     mbedtls_memory_buffer_alloc_status();
4249 #endif
4250     mbedtls_memory_buffer_alloc_free();
4251 #endif  /* MBEDTLS_MEMORY_BUFFER_ALLOC_C */
4252 
4253     if (opt.query_config_mode == DFL_QUERY_CONFIG_MODE) {
4254         mbedtls_printf(" done.\n");
4255     }
4256 
4257     // Shell can not handle large exit numbers -> 1 for errors
4258     if (ret < 0) {
4259         ret = 1;
4260     }
4261 
4262     if (opt.query_config_mode == DFL_QUERY_CONFIG_MODE) {
4263         mbedtls_exit(ret);
4264     } else {
4265         mbedtls_exit(query_config_ret);
4266     }
4267 }
4268 #endif /* !MBEDTLS_SSL_TEST_IMPOSSIBLE && MBEDTLS_SSL_SRV_C */
4269