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