1 /*
2  *  SSL client with certificate authentication
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 #define MBEDTLS_ALLOW_PRIVATE_ACCESS
9 
10 #include "ssl_test_lib.h"
11 
12 #if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
13 #include "test/psa_crypto_helpers.h"
14 #endif /* MBEDTLS_USE_PSA_CRYPTO || MBEDTLS_SSL_PROTO_TLS1_3 */
15 
16 #if defined(MBEDTLS_SSL_TEST_IMPOSSIBLE)
main(void)17 int main(void)
18 {
19     mbedtls_printf(MBEDTLS_SSL_TEST_IMPOSSIBLE);
20     mbedtls_exit(0);
21 }
22 #elif !defined(MBEDTLS_SSL_CLI_C)
main(void)23 int main(void)
24 {
25     mbedtls_printf("MBEDTLS_SSL_CLI_C not defined.\n");
26     mbedtls_exit(0);
27 }
28 #else /* !MBEDTLS_SSL_TEST_IMPOSSIBLE && MBEDTLS_SSL_CLI_C */
29 
30 /* Size of memory to be allocated for the heap, when using the library's memory
31  * management and MBEDTLS_MEMORY_BUFFER_ALLOC_C is enabled. */
32 #define MEMORY_HEAP_SIZE      120000
33 
34 #define MAX_REQUEST_SIZE      20000
35 #define MAX_REQUEST_SIZE_STR "20000"
36 
37 #define DFL_SERVER_NAME         "localhost"
38 #define DFL_SERVER_ADDR         NULL
39 #define DFL_SERVER_PORT         "4433"
40 #define DFL_REQUEST_PAGE        "/"
41 #define DFL_REQUEST_SIZE        -1
42 #define DFL_DEBUG_LEVEL         0
43 #define DFL_CONTEXT_CRT_CB      0
44 #define DFL_NBIO                0
45 #define DFL_EVENT               0
46 #define DFL_READ_TIMEOUT        0
47 #define DFL_MAX_RESEND          0
48 #define DFL_CA_FILE             ""
49 #define DFL_CA_PATH             ""
50 #define DFL_CRT_FILE            ""
51 #define DFL_KEY_FILE            ""
52 #define DFL_KEY_OPAQUE          0
53 #define DFL_KEY_PWD             ""
54 #define DFL_PSK                 ""
55 #define DFL_EARLY_DATA          MBEDTLS_SSL_EARLY_DATA_DISABLED
56 #define DFL_PSK_OPAQUE          0
57 #define DFL_PSK_IDENTITY        "Client_identity"
58 #define DFL_ECJPAKE_PW          NULL
59 #define DFL_ECJPAKE_PW_OPAQUE   0
60 #define DFL_EC_MAX_OPS          -1
61 #define DFL_FORCE_CIPHER        0
62 #define DFL_TLS1_3_KEX_MODES    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_ALL
63 #define DFL_RENEGOTIATION       MBEDTLS_SSL_RENEGOTIATION_DISABLED
64 #define DFL_ALLOW_LEGACY        -2
65 #define DFL_RENEGOTIATE         0
66 #define DFL_EXCHANGES           1
67 #define DFL_MIN_VERSION         -1
68 #define DFL_MAX_VERSION         -1
69 #define DFL_SHA1                -1
70 #define DFL_AUTH_MODE           -1
71 #define DFL_MFL_CODE            MBEDTLS_SSL_MAX_FRAG_LEN_NONE
72 #define DFL_TRUNC_HMAC          -1
73 #define DFL_RECSPLIT            -1
74 #define DFL_DHMLEN              -1
75 #define DFL_RECONNECT           0
76 #define DFL_RECO_SERVER_NAME    NULL
77 #define DFL_RECO_DELAY          0
78 #define DFL_RECO_MODE           1
79 #define DFL_CID_ENABLED         0
80 #define DFL_CID_VALUE           ""
81 #define DFL_CID_ENABLED_RENEGO  -1
82 #define DFL_CID_VALUE_RENEGO    NULL
83 #define DFL_RECONNECT_HARD      0
84 #define DFL_TICKETS             MBEDTLS_SSL_SESSION_TICKETS_ENABLED
85 #define DFL_ALPN_STRING         NULL
86 #define DFL_GROUPS              NULL
87 #define DFL_SIG_ALGS            NULL
88 #define DFL_TRANSPORT           MBEDTLS_SSL_TRANSPORT_STREAM
89 #define DFL_HS_TO_MIN           0
90 #define DFL_HS_TO_MAX           0
91 #define DFL_DTLS_MTU            -1
92 #define DFL_DGRAM_PACKING        1
93 #define DFL_FALLBACK            -1
94 #define DFL_EXTENDED_MS         -1
95 #define DFL_ETM                 -1
96 #define DFL_SERIALIZE           0
97 #define DFL_CONTEXT_FILE        ""
98 #define DFL_EXTENDED_MS_ENFORCE -1
99 #define DFL_CA_CALLBACK         0
100 #define DFL_EAP_TLS             0
101 #define DFL_REPRODUCIBLE        0
102 #define DFL_NSS_KEYLOG          0
103 #define DFL_NSS_KEYLOG_FILE     NULL
104 #define DFL_SKIP_CLOSE_NOTIFY   0
105 #define DFL_QUERY_CONFIG_MODE   0
106 #define DFL_USE_SRTP            0
107 #define DFL_SRTP_FORCE_PROFILE  0
108 #define DFL_SRTP_MKI            ""
109 #define DFL_KEY_OPAQUE_ALG      "none"
110 
111 #define GET_REQUEST "GET %s HTTP/1.0\r\nExtra-header: "
112 #define GET_REQUEST_END "\r\n\r\n"
113 
114 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
115 #define USAGE_CONTEXT_CRT_CB \
116     "    context_crt_cb=%%d   This determines whether the CRT verification callback is bound\n" \
117     "                        to the SSL configuration of the SSL context.\n" \
118     "                        Possible values:\n" \
119     "                        - 0 (default): Use CRT callback bound to configuration\n" \
120     "                        - 1: Use CRT callback bound to SSL context\n"
121 #else
122 #define USAGE_CONTEXT_CRT_CB ""
123 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
124 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
125 #if defined(MBEDTLS_FS_IO)
126 #define USAGE_IO \
127     "    ca_file=%%s          The single file containing the top-level CA(s) you fully trust\n" \
128     "                        default: \"\" (pre-loaded)\n" \
129     "                        use \"none\" to skip loading any top-level CAs.\n" \
130     "    ca_path=%%s          The path containing the top-level CA(s) you fully trust\n" \
131     "                        default: \"\" (pre-loaded) (overrides ca_file)\n" \
132     "                        use \"none\" to skip loading any top-level CAs.\n" \
133     "    crt_file=%%s         Your own cert and chain (in bottom to top order, top may be omitted)\n" \
134     "                        default: \"\" (pre-loaded)\n" \
135     "    key_file=%%s         default: \"\" (pre-loaded)\n" \
136     "    key_pwd=%%s          Password for key specified by key_file argument\n" \
137     "                        default: none\n"
138 #else
139 #define USAGE_IO \
140     "    No file operations available (MBEDTLS_FS_IO not defined)\n"
141 #endif /* MBEDTLS_FS_IO */
142 #else /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
143 #define USAGE_IO ""
144 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
145 #if defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
146 #define USAGE_KEY_OPAQUE \
147     "    key_opaque=%%d       Handle your private key as if it were opaque\n" \
148     "                        default: 0 (disabled)\n"
149 #else
150 #define USAGE_KEY_OPAQUE ""
151 #endif
152 
153 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
154 #define USAGE_CID \
155     "    cid=%%d             Disable (0) or enable (1) the use of the DTLS Connection ID extension.\n" \
156     "                       default: 0 (disabled)\n"     \
157     "    cid_renego=%%d      Disable (0) or enable (1) the use of the DTLS Connection ID extension during renegotiation.\n" \
158     "                       default: same as 'cid' parameter\n"     \
159     "    cid_val=%%s          The CID to use for incoming messages (in hex, without 0x).\n"  \
160     "                        default: \"\"\n" \
161     "    cid_val_renego=%%s   The CID to use for incoming messages (in hex, without 0x) after renegotiation.\n"  \
162     "                        default: same as 'cid_val' parameter\n"
163 #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
164 #define USAGE_CID ""
165 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
166 
167 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
168 #define USAGE_PSK_RAW                                               \
169     "    psk=%%s              default: \"\" (disabled)\n"     \
170     "                          The PSK values are in hex, without 0x.\n" \
171     "    psk_identity=%%s     default: \"Client_identity\"\n"
172 #if defined(MBEDTLS_USE_PSA_CRYPTO)
173 #define USAGE_PSK_SLOT                          \
174     "    psk_opaque=%%d       default: 0 (don't use opaque static PSK)\n"     \
175     "                          Enable this to store the PSK configured through command line\n" \
176     "                          parameter `psk` in a PSA-based key slot.\n" \
177     "                          Note: Currently only supported in conjunction with\n"                  \
178     "                          the use of min_version to force TLS 1.2 and force_ciphersuite \n"      \
179     "                          to force a particular PSK-only ciphersuite.\n"                         \
180     "                          Note: This is to test integration of PSA-based opaque PSKs with\n"     \
181     "                          Mbed TLS only. Production systems are likely to configure Mbed TLS\n"  \
182     "                          with prepopulated key slots instead of importing raw key material.\n"
183 #else
184 #define USAGE_PSK_SLOT ""
185 #endif /* MBEDTLS_USE_PSA_CRYPTO */
186 #define USAGE_PSK USAGE_PSK_RAW USAGE_PSK_SLOT
187 #else
188 #define USAGE_PSK ""
189 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
190 
191 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
192 #define USAGE_CA_CALLBACK                       \
193     "   ca_callback=%%d       default: 0 (disabled)\n"      \
194     "                         Enable this to use the trusted certificate callback function\n"
195 #else
196 #define USAGE_CA_CALLBACK ""
197 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
198 
199 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
200 #define USAGE_TICKETS                                       \
201     "    tickets=%%d          default: 1 (enabled)\n"
202 #else
203 #define USAGE_TICKETS ""
204 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
205 
206 #define USAGE_EAP_TLS                                       \
207     "    eap_tls=%%d          default: 0 (disabled)\n"
208 #define USAGE_NSS_KEYLOG                                    \
209     "    nss_keylog=%%d          default: 0 (disabled)\n"               \
210     "                             This cannot be used with eap_tls=1\n"
211 #define USAGE_NSS_KEYLOG_FILE                               \
212     "    nss_keylog_file=%%s\n"
213 #if defined(MBEDTLS_SSL_DTLS_SRTP)
214 #define USAGE_SRTP \
215     "    use_srtp=%%d         default: 0 (disabled)\n" \
216     "                          This cannot be used with eap_tls=1 or " \
217     "                          nss_keylog=1\n"             \
218     "    srtp_force_profile=%%d  default: 0 (all enabled)\n"   \
219     "                        available profiles:\n"       \
220     "                        1 - SRTP_AES128_CM_HMAC_SHA1_80\n"  \
221     "                        2 - SRTP_AES128_CM_HMAC_SHA1_32\n"  \
222     "                        3 - SRTP_NULL_HMAC_SHA1_80\n"       \
223     "                        4 - SRTP_NULL_HMAC_SHA1_32\n"       \
224     "    mki=%%s              default: \"\" (in hex, without 0x)\n"
225 #else /* MBEDTLS_SSL_DTLS_SRTP */
226 #define USAGE_SRTP ""
227 #endif
228 
229 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
230 #define USAGE_MAX_FRAG_LEN                                      \
231     "    max_frag_len=%%d     default: 16384 (tls default)\n"   \
232     "                        options: 512, 1024, 2048, 4096\n"
233 #else
234 #define USAGE_MAX_FRAG_LEN ""
235 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
236 
237 #if defined(MBEDTLS_DHM_C)
238 #define USAGE_DHMLEN \
239     "    dhmlen=%%d           default: (library default: 1024 bits)\n"
240 #else
241 #define USAGE_DHMLEN
242 #endif
243 
244 #if defined(MBEDTLS_SSL_ALPN)
245 #define USAGE_ALPN \
246     "    alpn=%%s             default: \"\" (disabled)\n"   \
247     "                        example: spdy/1,http/1.1\n"
248 #else
249 #define USAGE_ALPN ""
250 #endif /* MBEDTLS_SSL_ALPN */
251 
252 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS) || \
253     (defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED) && \
254     defined(PSA_WANT_ALG_FFDH))
255 #define USAGE_GROUPS \
256     "    groups=a,b,c,d      default: \"default\" (library default)\n"        \
257     "                        example: \"secp521r1,brainpoolP512r1\"\n"        \
258     "                        - use \"none\" for empty list\n"                 \
259     "                        - see mbedtls_ecp_curve_list()\n"                \
260     "                          for acceptable EC group names\n"               \
261     "                        - the following ffdh groups are supported:\n"    \
262     "                          ffdhe2048, ffdhe3072, ffdhe4096, ffdhe6144,\n" \
263     "                          ffdhe8192\n"
264 #else
265 #define USAGE_GROUPS ""
266 #endif
267 
268 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
269 #define USAGE_SIG_ALGS \
270     "    sig_algs=a,b,c,d      default: \"default\" (library default)\n"  \
271     "                          example: \"ecdsa_secp256r1_sha256,ecdsa_secp384r1_sha384\"\n"
272 #else
273 #define USAGE_SIG_ALGS ""
274 #endif
275 
276 #if defined(MBEDTLS_SSL_PROTO_DTLS)
277 #define USAGE_DTLS \
278     "    dtls=%%d             default: 0 (TLS)\n"                           \
279     "    hs_timeout=%%d-%%d    default: (library default: 1000-60000)\n"    \
280     "                        range of DTLS handshake timeouts in millisecs\n" \
281     "    mtu=%%d              default: (library default: unlimited)\n"  \
282     "    dgram_packing=%%d    default: 1 (allowed)\n"                   \
283     "                        allow or forbid packing of multiple\n" \
284     "                        records within a single datgram.\n"
285 #else
286 #define USAGE_DTLS ""
287 #endif
288 
289 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
290 #define USAGE_EMS \
291     "    extended_ms=0/1     default: (library default: on)\n"
292 #else
293 #define USAGE_EMS ""
294 #endif
295 
296 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
297 #define USAGE_ETM \
298     "    etm=0/1             default: (library default: on)\n"
299 #else
300 #define USAGE_ETM ""
301 #endif
302 
303 #define USAGE_REPRODUCIBLE \
304     "    reproducible=0/1     default: 0 (disabled)\n"
305 
306 #if defined(MBEDTLS_SSL_RENEGOTIATION)
307 #define USAGE_RENEGO \
308     "    renegotiation=%%d    default: 0 (disabled)\n"      \
309     "    renegotiate=%%d      default: 0 (disabled)\n"
310 #else
311 #define USAGE_RENEGO ""
312 #endif
313 
314 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
315 #if defined(MBEDTLS_USE_PSA_CRYPTO)
316 #define USAGE_ECJPAKE \
317     "    ecjpake_pw=%%s           default: none (disabled)\n"   \
318     "    ecjpake_pw_opaque=%%d    default: 0 (disabled)\n"
319 #else /* MBEDTLS_USE_PSA_CRYPTO */
320 #define USAGE_ECJPAKE \
321     "    ecjpake_pw=%%s           default: none (disabled)\n"
322 #endif /* MBEDTLS_USE_PSA_CRYPTO */
323 #else /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
324 #define USAGE_ECJPAKE ""
325 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
326 
327 #if defined(MBEDTLS_ECP_RESTARTABLE)
328 #define USAGE_ECRESTART \
329     "    ec_max_ops=%%s       default: library default (restart disabled)\n"
330 #else
331 #define USAGE_ECRESTART ""
332 #endif
333 
334 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
335 #define USAGE_SERIALIZATION \
336     "    serialize=%%d        default: 0 (do not serialize/deserialize)\n"     \
337     "                        options: 1 (serialize)\n"                         \
338     "                                 2 (serialize with re-initialization)\n"  \
339     "    context_file=%%s     The file path to write a serialized connection\n" \
340     "                        in the form of base64 code (serialize option\n"   \
341     "                        must be set)\n"                                   \
342     "                         default: \"\" (do nothing)\n"                    \
343     "                         option: a file path\n"
344 #else
345 #define USAGE_SERIALIZATION ""
346 #endif
347 
348 #if defined(MBEDTLS_SSL_EARLY_DATA)
349 #define USAGE_EARLY_DATA \
350     "    early_data=%%d        default: 0 (disabled)\n"      \
351     "                        options: 0 (disabled), 1 (enabled)\n"
352 #else
353 #define USAGE_EARLY_DATA ""
354 #endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_PROTO_TLS1_3 */
355 
356 #define USAGE_KEY_OPAQUE_ALGS \
357     "    key_opaque_algs=%%s  Allowed opaque key algorithms.\n"                      \
358     "                        comma-separated pair of values among the following:\n"    \
359     "                        rsa-sign-pkcs1, rsa-sign-pss, rsa-sign-pss-sha256,\n"     \
360     "                        rsa-sign-pss-sha384, rsa-sign-pss-sha512, rsa-decrypt,\n" \
361     "                        ecdsa-sign, ecdh, none (only acceptable for\n"            \
362     "                        the second value).\n"                                     \
363 
364 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
365 #define USAGE_TLS1_3_KEY_EXCHANGE_MODES \
366     "    tls13_kex_modes=%%s   default: all\n"     \
367     "                          options: psk, psk_ephemeral, psk_all, ephemeral,\n"     \
368     "                                   ephemeral_all, all, psk_or_ephemeral\n"
369 #else
370 #define USAGE_TLS1_3_KEY_EXCHANGE_MODES ""
371 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
372 
373 /* USAGE is arbitrarily split to stay under the portable string literal
374  * length limit: 4095 bytes in C99. */
375 #define USAGE1 \
376     "\n usage: ssl_client2 param=<>...\n"                   \
377     "\n acceptable parameters:\n"                           \
378     "    server_name=%%s      default: localhost\n"         \
379     "    server_addr=%%s      default: given by name\n"     \
380     "    server_port=%%d      default: 4433\n"              \
381     "    request_page=%%s     default: \".\"\n"             \
382     "    request_size=%%d     default: about 34 (basic request)\n"           \
383     "                        (minimum: 0, max: " MAX_REQUEST_SIZE_STR ")\n"  \
384                                                                       "                        If 0, in the first exchange only an empty\n"    \
385                                                                       "                        application data message is sent followed by\n" \
386                                                                       "                        a second non-empty message before attempting\n" \
387                                                                       "                        to read a response from the server\n"           \
388                                                                       "    debug_level=%%d      default: 0 (disabled)\n"             \
389                                                                       "    build_version=%%d    default: none (disabled)\n"                     \
390                                                                       "                        option: 1 (print build version only and stop)\n" \
391                                                                       "    nbio=%%d             default: 0 (blocking I/O)\n"         \
392                                                                       "                        options: 1 (non-blocking), 2 (added delays)\n"   \
393                                                                       "    event=%%d            default: 0 (loop)\n"                            \
394                                                                       "                        options: 1 (level-triggered, implies nbio=1),\n" \
395                                                                       "    read_timeout=%%d     default: 0 ms (no timeout)\n"        \
396                                                                       "    max_resend=%%d       default: 0 (no resend on timeout)\n" \
397                                                                       "    skip_close_notify=%%d default: 0 (send close_notify)\n" \
398                                                                       "\n"                                                    \
399     USAGE_DTLS                                              \
400     USAGE_CID                                               \
401     USAGE_SRTP                                              \
402     "\n"
403 #define USAGE2 \
404     "    auth_mode=%%s        default: (library default: none)\n" \
405     "                        options: none, optional, required\n" \
406     USAGE_IO                                                \
407     USAGE_KEY_OPAQUE                                        \
408     USAGE_CA_CALLBACK                                       \
409     "\n"                                                    \
410     USAGE_PSK                                               \
411     USAGE_ECJPAKE                                           \
412     USAGE_ECRESTART                                         \
413     "\n"
414 #define USAGE3 \
415     "    allow_legacy=%%d     default: (library default: no)\n"   \
416     USAGE_RENEGO                                            \
417     "    exchanges=%%d        default: 1\n"                 \
418     "    reconnect=%%d        number of reconnections using session resumption\n" \
419     "                        default: 0 (disabled)\n"       \
420     "    reco_server_name=%%s  default: NULL\n"             \
421     "    reco_delay=%%d       default: 0 milliseconds\n"         \
422     "    reco_mode=%%d        0: copy session, 1: serialize session\n" \
423     "                        default: 1\n"      \
424     "    reconnect_hard=%%d   default: 0 (disabled)\n"      \
425     USAGE_TICKETS                                           \
426     USAGE_EAP_TLS                                           \
427     USAGE_MAX_FRAG_LEN                                      \
428     USAGE_CONTEXT_CRT_CB                                    \
429     USAGE_ALPN                                              \
430     USAGE_EMS                                               \
431     USAGE_ETM                                               \
432     USAGE_REPRODUCIBLE                                      \
433     USAGE_GROUPS                                            \
434     USAGE_SIG_ALGS                                          \
435     USAGE_EARLY_DATA                                        \
436     USAGE_DHMLEN                                            \
437     USAGE_KEY_OPAQUE_ALGS                                   \
438     "\n"
439 
440 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
441 #define TLS1_3_VERSION_OPTIONS  ", tls13"
442 #else /* MBEDTLS_SSL_PROTO_TLS1_3 */
443 #define TLS1_3_VERSION_OPTIONS  ""
444 #endif /* !MBEDTLS_SSL_PROTO_TLS1_3 */
445 
446 #define USAGE4 \
447     "    allow_sha1=%%d       default: 0\n"                                   \
448     "    min_version=%%s      default: (library default: tls12)\n"            \
449     "    max_version=%%s      default: (library default: tls12)\n"            \
450     "    force_version=%%s    default: \"\" (none)\n"                         \
451     "                         options: tls12, dtls12" TLS1_3_VERSION_OPTIONS  \
452     "\n\n"                                                                    \
453     "    force_ciphersuite=<name>    default: all enabled\n"                  \
454     USAGE_TLS1_3_KEY_EXCHANGE_MODES                                           \
455     "    query_config=<name>         return 0 if the specified\n"             \
456     "                                configuration macro is defined and 1\n"  \
457     "                                otherwise. The expansion of the macro\n" \
458     "                                is printed if it is defined\n"           \
459     USAGE_SERIALIZATION                                                       \
460     " acceptable ciphersuite names:\n"
461 
462 /*
463  * global options
464  */
465 struct options {
466     const char *server_name;    /* hostname of the server (client only)     */
467     const char *server_addr;    /* address of the server (client only)      */
468     const char *server_port;    /* port on which the ssl service runs       */
469     int debug_level;            /* level of debugging                       */
470     int nbio;                   /* should I/O be blocking?                  */
471     int event;                  /* loop or event-driven IO? level or edge triggered? */
472     uint32_t read_timeout;      /* timeout on mbedtls_ssl_read() in milliseconds     */
473     int max_resend;             /* DTLS times to resend on read timeout     */
474     const char *request_page;   /* page on server to request                */
475     int request_size;           /* pad request with header to requested size */
476     const char *ca_file;        /* the file with the CA certificate(s)      */
477     const char *ca_path;        /* the path with the CA certificate(s) reside */
478     const char *crt_file;       /* the file with the client certificate     */
479     const char *key_file;       /* the file with the client key             */
480     int key_opaque;             /* handle private key as if it were opaque  */
481 #if defined(MBEDTLS_USE_PSA_CRYPTO)
482     int psk_opaque;
483 #endif
484 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
485     int ca_callback;            /* Use callback for trusted certificate list */
486 #endif
487     const char *key_pwd;        /* the password for the client key          */
488     const char *psk;            /* the pre-shared key                       */
489     const char *psk_identity;   /* the pre-shared key identity              */
490     const char *ecjpake_pw;     /* the EC J-PAKE password                   */
491 #if defined(MBEDTLS_USE_PSA_CRYPTO)
492     int ecjpake_pw_opaque;      /* set to 1 to use the opaque method for setting the password */
493 #endif
494     int ec_max_ops;             /* EC consecutive operations limit          */
495     int force_ciphersuite[2];   /* protocol/ciphersuite to use, or all      */
496 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
497     int tls13_kex_modes;        /* supported TLS 1.3 key exchange modes     */
498 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
499     int renegotiation;          /* enable / disable renegotiation           */
500     int allow_legacy;           /* allow legacy renegotiation               */
501     int renegotiate;            /* attempt renegotiation?                   */
502     int renego_delay;           /* delay before enforcing renegotiation     */
503     int exchanges;              /* number of data exchanges                 */
504     int min_version;            /* minimum protocol version accepted        */
505     int max_version;            /* maximum protocol version accepted        */
506     int allow_sha1;             /* flag for SHA-1 support                   */
507     int auth_mode;              /* verify mode for connection               */
508     unsigned char mfl_code;     /* code for maximum fragment length         */
509     int trunc_hmac;             /* negotiate truncated hmac or not          */
510     int recsplit;               /* enable record splitting?                 */
511     int dhmlen;                 /* minimum DHM params len in bits           */
512     int reconnect;              /* attempt to resume session                */
513     const char *reco_server_name;     /* hostname of the server (re-connect)     */
514     int reco_delay;             /* delay in seconds before resuming session */
515     int reco_mode;              /* how to keep the session around           */
516     int reconnect_hard;         /* unexpectedly reconnect from the same port */
517     int tickets;                /* enable / disable session tickets         */
518     const char *groups;         /* list of supported groups                 */
519     const char *sig_algs;       /* supported TLS 1.3 signature algorithms   */
520     const char *alpn_string;    /* ALPN supported protocols                 */
521     int transport;              /* TLS or DTLS?                             */
522     uint32_t hs_to_min;         /* Initial value of DTLS handshake timer    */
523     uint32_t hs_to_max;         /* Max value of DTLS handshake timer        */
524     int dtls_mtu;               /* UDP Maximum transport unit for DTLS       */
525     int fallback;               /* is this a fallback connection?           */
526     int dgram_packing;          /* allow/forbid datagram packing            */
527     int extended_ms;            /* negotiate extended master secret?        */
528     int etm;                    /* negotiate encrypt then mac?              */
529     int context_crt_cb;         /* use context-specific CRT verify callback */
530     int eap_tls;                /* derive EAP-TLS keying material?          */
531     int nss_keylog;             /* export NSS key log material              */
532     const char *nss_keylog_file; /* NSS key log file                        */
533     int cid_enabled;            /* whether to use the CID extension or not  */
534     int cid_enabled_renego;     /* whether to use the CID extension or not
535                                  * during renegotiation                     */
536     const char *cid_val;        /* the CID to use for incoming messages     */
537     int serialize;              /* serialize/deserialize connection         */
538     const char *context_file;   /* the file to write a serialized connection
539                                  * in the form of base64 code (serialize
540                                  * option must be set)                      */
541     const char *cid_val_renego; /* the CID to use for incoming messages
542                                  * after renegotiation                      */
543     int reproducible;           /* make communication reproducible          */
544     int skip_close_notify;      /* skip sending the close_notify alert      */
545 #if defined(MBEDTLS_SSL_EARLY_DATA)
546     int early_data;             /* support for early data                   */
547 #endif
548     int query_config_mode;      /* whether to read config                   */
549     int use_srtp;               /* Support SRTP                             */
550     int force_srtp_profile;     /* SRTP protection profile to use or all    */
551     const char *mki;            /* The dtls mki value to use                */
552     const char *key_opaque_alg1; /* Allowed opaque key alg 1                */
553     const char *key_opaque_alg2; /* Allowed Opaque key alg 2                */
554 } opt;
555 
556 #include "ssl_test_common_source.c"
557 
558 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
559 static unsigned char peer_crt_info[1024];
560 
561 /*
562  * Enabled if debug_level > 1 in code below
563  */
my_verify(void * data,mbedtls_x509_crt * crt,int depth,uint32_t * flags)564 static int my_verify(void *data, mbedtls_x509_crt *crt,
565                      int depth, uint32_t *flags)
566 {
567     char buf[1024];
568     ((void) data);
569 
570     mbedtls_printf("\nVerify requested for (Depth %d):\n", depth);
571 
572 #if !defined(MBEDTLS_X509_REMOVE_INFO)
573     mbedtls_x509_crt_info(buf, sizeof(buf) - 1, "", crt);
574     if (depth == 0) {
575         memcpy(peer_crt_info, buf, sizeof(buf));
576     }
577 
578     if (opt.debug_level == 0) {
579         return 0;
580     }
581 
582     mbedtls_printf("%s", buf);
583 #else
584     ((void) crt);
585     ((void) depth);
586 #endif
587 
588     if ((*flags) == 0) {
589         mbedtls_printf("  This certificate has no flags\n");
590     } else {
591         x509_crt_verify_info(buf, sizeof(buf), "  ! ", *flags);
592         mbedtls_printf("%s\n", buf);
593     }
594 
595     return 0;
596 }
597 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
598 
599 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
report_cid_usage(mbedtls_ssl_context * ssl,const char * additional_description)600 int report_cid_usage(mbedtls_ssl_context *ssl,
601                      const char *additional_description)
602 {
603     int ret;
604     unsigned char peer_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX];
605     size_t peer_cid_len;
606     int cid_negotiated;
607 
608     if (opt.transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
609         return 0;
610     }
611 
612     /* Check if the use of a CID has been negotiated,
613      * but don't ask for the CID value and length.
614      *
615      * Note: Here and below, we're demonstrating the various ways
616      *       in which mbedtls_ssl_get_peer_cid() can be called,
617      *       depending on whether or not the length/value of the
618      *       peer's CID is needed.
619      *
620      *       An actual application, however, should use
621      *       just one call to mbedtls_ssl_get_peer_cid(). */
622     ret = mbedtls_ssl_get_peer_cid(ssl, &cid_negotiated,
623                                    NULL, NULL);
624     if (ret != 0) {
625         mbedtls_printf(" failed\n  ! mbedtls_ssl_get_peer_cid returned -0x%x\n\n",
626                        (unsigned int) -ret);
627         return ret;
628     }
629 
630     if (cid_negotiated == MBEDTLS_SSL_CID_DISABLED) {
631         if (opt.cid_enabled == MBEDTLS_SSL_CID_ENABLED) {
632             mbedtls_printf("(%s) Use of Connection ID was rejected by the server.\n",
633                            additional_description);
634         }
635     } else {
636         size_t idx = 0;
637         mbedtls_printf("(%s) Use of Connection ID has been negotiated.\n",
638                        additional_description);
639 
640         /* Ask for just the length of the peer's CID. */
641         ret = mbedtls_ssl_get_peer_cid(ssl, &cid_negotiated,
642                                        NULL, &peer_cid_len);
643         if (ret != 0) {
644             mbedtls_printf(" failed\n  ! mbedtls_ssl_get_peer_cid returned -0x%x\n\n",
645                            (unsigned int) -ret);
646             return ret;
647         }
648 
649         /* Ask for just length + value of the peer's CID. */
650         ret = mbedtls_ssl_get_peer_cid(ssl, &cid_negotiated,
651                                        peer_cid, &peer_cid_len);
652         if (ret != 0) {
653             mbedtls_printf(" failed\n  ! mbedtls_ssl_get_peer_cid returned -0x%x\n\n",
654                            (unsigned int) -ret);
655             return ret;
656         }
657         mbedtls_printf("(%s) Peer CID (length %u Bytes): ",
658                        additional_description,
659                        (unsigned) peer_cid_len);
660         while (idx < peer_cid_len) {
661             mbedtls_printf("%02x ", peer_cid[idx]);
662             idx++;
663         }
664         mbedtls_printf("\n");
665     }
666 
667     return 0;
668 }
669 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
670 
ssl_save_session_serialize(mbedtls_ssl_context * ssl,unsigned char ** session_data,size_t * session_data_len)671 static int ssl_save_session_serialize(mbedtls_ssl_context *ssl,
672                                       unsigned char **session_data,
673                                       size_t *session_data_len)
674 {
675     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
676     mbedtls_ssl_session exported_session;
677 
678     /* free any previously saved data */
679     if (*session_data != NULL) {
680         mbedtls_platform_zeroize(*session_data, *session_data_len);
681         mbedtls_free(*session_data);
682         *session_data = NULL;
683         *session_data_len = 0;
684     }
685 
686     mbedtls_ssl_session_init(&exported_session);
687     ret = mbedtls_ssl_get_session(ssl, &exported_session);
688     if (ret != 0) {
689         mbedtls_printf(
690             "failed\n  ! mbedtls_ssl_get_session() returned -%#02x\n",
691             (unsigned) -ret);
692         goto exit;
693     }
694 
695     /* get size of the buffer needed */
696     mbedtls_ssl_session_save(&exported_session, NULL, 0, session_data_len);
697     *session_data = mbedtls_calloc(1, *session_data_len);
698     if (*session_data == NULL) {
699         mbedtls_printf(" failed\n  ! alloc %u bytes for session data\n",
700                        (unsigned) *session_data_len);
701         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
702         goto exit;
703     }
704 
705     /* actually save session data */
706     if ((ret = mbedtls_ssl_session_save(&exported_session,
707                                         *session_data, *session_data_len,
708                                         session_data_len)) != 0) {
709         mbedtls_printf(" failed\n  ! mbedtls_ssl_session_saved returned -0x%04x\n\n",
710                        (unsigned int) -ret);
711         goto exit;
712     }
713 
714 exit:
715     mbedtls_ssl_session_free(&exported_session);
716     return ret;
717 }
718 
main(int argc,char * argv[])719 int main(int argc, char *argv[])
720 {
721     int ret = 0, len, tail_len, i, written, frags, retry_left;
722     int query_config_ret = 0;
723     mbedtls_net_context server_fd;
724     io_ctx_t io_ctx;
725 
726 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
727     uint16_t sig_alg_list[SIG_ALG_LIST_SIZE];
728 #endif
729 
730     unsigned char buf[MAX_REQUEST_SIZE + 1];
731 
732 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
733     unsigned char psk[MBEDTLS_PSK_MAX_LEN];
734     size_t psk_len = 0;
735 #endif
736 
737 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
738     unsigned char cid[MBEDTLS_SSL_CID_IN_LEN_MAX];
739     unsigned char cid_renego[MBEDTLS_SSL_CID_IN_LEN_MAX];
740     size_t cid_len = 0;
741     size_t cid_renego_len = 0;
742 #endif
743 
744 #if defined(MBEDTLS_SSL_ALPN)
745     const char *alpn_list[ALPN_LIST_SIZE];
746 #endif
747 
748 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
749     unsigned char alloc_buf[MEMORY_HEAP_SIZE];
750 #endif
751     uint16_t group_list[GROUP_LIST_SIZE];
752 #if defined(MBEDTLS_SSL_DTLS_SRTP)
753     unsigned char mki[MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH];
754     size_t mki_len = 0;
755 #endif
756 
757     const char *pers = "ssl_client2";
758 
759 #if defined(MBEDTLS_USE_PSA_CRYPTO)
760 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
761     mbedtls_svc_key_id_t slot = MBEDTLS_SVC_KEY_ID_INIT;
762     psa_algorithm_t alg = 0;
763     psa_key_attributes_t key_attributes;
764 #endif
765     psa_status_t status;
766 #elif defined(MBEDTLS_SSL_PROTO_TLS1_3)
767     psa_status_t status;
768 #endif
769 
770     rng_context_t rng;
771     mbedtls_ssl_context ssl;
772     mbedtls_ssl_config conf;
773     mbedtls_ssl_session saved_session;
774     unsigned char *session_data = NULL;
775     size_t session_data_len = 0;
776 #if defined(MBEDTLS_TIMING_C)
777     mbedtls_timing_delay_context timer;
778 #endif
779 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
780     uint32_t flags;
781     mbedtls_x509_crt cacert;
782     mbedtls_x509_crt clicert;
783     mbedtls_pk_context pkey;
784     mbedtls_x509_crt_profile crt_profile_for_test = mbedtls_x509_crt_profile_default;
785 #if defined(MBEDTLS_USE_PSA_CRYPTO)
786     mbedtls_svc_key_id_t key_slot = MBEDTLS_SVC_KEY_ID_INIT; /* invalid key slot */
787 #endif
788 #endif  /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
789     char *p, *q;
790     const int *list;
791 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
792     unsigned char *context_buf = NULL;
793     size_t context_buf_len;
794 #endif
795     unsigned char eap_tls_keymaterial[16];
796     unsigned char eap_tls_iv[8];
797     const char *eap_tls_label = "client EAP encryption";
798     eap_tls_keys eap_tls_keying;
799 #if defined(MBEDTLS_SSL_DTLS_SRTP)
800     /*! master keys and master salt for SRTP generated during handshake */
801     unsigned char dtls_srtp_key_material[MBEDTLS_TLS_SRTP_MAX_KEY_MATERIAL_LENGTH];
802     const char *dtls_srtp_label = "EXTRACTOR-dtls_srtp";
803     dtls_srtp_keys dtls_srtp_keying;
804     const mbedtls_ssl_srtp_profile default_profiles[] = {
805         MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_80,
806         MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_32,
807         MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_80,
808         MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_32,
809         MBEDTLS_TLS_SRTP_UNSET
810     };
811 #endif /* MBEDTLS_SSL_DTLS_SRTP */
812 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \
813     defined(MBEDTLS_USE_PSA_CRYPTO)
814     mbedtls_svc_key_id_t ecjpake_pw_slot = MBEDTLS_SVC_KEY_ID_INIT; /* ecjpake password key slot */
815 #endif /* MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
816 
817 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
818     mbedtls_memory_buffer_alloc_init(alloc_buf, sizeof(alloc_buf));
819 #endif
820 
821 #if defined(MBEDTLS_TEST_HOOKS)
822     test_hooks_init();
823 #endif /* MBEDTLS_TEST_HOOKS */
824 
825     /*
826      * Make sure memory references are valid.
827      */
828     mbedtls_net_init(&server_fd);
829     mbedtls_ssl_init(&ssl);
830     mbedtls_ssl_config_init(&conf);
831     memset(&saved_session, 0, sizeof(mbedtls_ssl_session));
832     rng_init(&rng);
833 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
834     mbedtls_x509_crt_init(&cacert);
835     mbedtls_x509_crt_init(&clicert);
836     mbedtls_pk_init(&pkey);
837 #endif
838 #if defined(MBEDTLS_SSL_ALPN)
839     memset((void *) alpn_list, 0, sizeof(alpn_list));
840 #endif
841 
842 #if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
843     status = psa_crypto_init();
844     if (status != PSA_SUCCESS) {
845         mbedtls_fprintf(stderr, "Failed to initialize PSA Crypto implementation: %d\n",
846                         (int) status);
847         ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
848         goto exit;
849     }
850 #endif  /* MBEDTLS_USE_PSA_CRYPTO || MBEDTLS_SSL_PROTO_TLS1_3 */
851 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
852     mbedtls_test_enable_insecure_external_rng();
853 #endif  /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
854 
855     if (argc < 2) {
856 usage:
857         if (ret == 0) {
858             ret = 1;
859         }
860 
861         mbedtls_printf(USAGE1);
862         mbedtls_printf(USAGE2);
863         mbedtls_printf(USAGE3);
864         mbedtls_printf(USAGE4);
865 
866         list = mbedtls_ssl_list_ciphersuites();
867         while (*list) {
868             mbedtls_printf(" %-42s", mbedtls_ssl_get_ciphersuite_name(*list));
869             list++;
870             if (!*list) {
871                 break;
872             }
873             mbedtls_printf(" %s\n", mbedtls_ssl_get_ciphersuite_name(*list));
874             list++;
875         }
876         mbedtls_printf("\n");
877         goto exit;
878     }
879 
880     opt.server_name         = DFL_SERVER_NAME;
881     opt.server_addr         = DFL_SERVER_ADDR;
882     opt.server_port         = DFL_SERVER_PORT;
883     opt.debug_level         = DFL_DEBUG_LEVEL;
884     opt.cid_enabled         = DFL_CID_ENABLED;
885     opt.cid_val             = DFL_CID_VALUE;
886     opt.cid_enabled_renego  = DFL_CID_ENABLED_RENEGO;
887     opt.cid_val_renego      = DFL_CID_VALUE_RENEGO;
888     opt.nbio                = DFL_NBIO;
889     opt.event               = DFL_EVENT;
890     opt.context_crt_cb      = DFL_CONTEXT_CRT_CB;
891     opt.read_timeout        = DFL_READ_TIMEOUT;
892     opt.max_resend          = DFL_MAX_RESEND;
893     opt.request_page        = DFL_REQUEST_PAGE;
894     opt.request_size        = DFL_REQUEST_SIZE;
895     opt.ca_file             = DFL_CA_FILE;
896     opt.ca_path             = DFL_CA_PATH;
897     opt.crt_file            = DFL_CRT_FILE;
898     opt.key_file            = DFL_KEY_FILE;
899     opt.key_opaque          = DFL_KEY_OPAQUE;
900     opt.key_pwd             = DFL_KEY_PWD;
901     opt.psk                 = DFL_PSK;
902 #if defined(MBEDTLS_USE_PSA_CRYPTO)
903     opt.psk_opaque          = DFL_PSK_OPAQUE;
904 #endif
905 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
906     opt.ca_callback         = DFL_CA_CALLBACK;
907 #endif
908     opt.psk_identity        = DFL_PSK_IDENTITY;
909     opt.ecjpake_pw          = DFL_ECJPAKE_PW;
910 #if defined(MBEDTLS_USE_PSA_CRYPTO)
911     opt.ecjpake_pw_opaque   = DFL_ECJPAKE_PW_OPAQUE;
912 #endif
913     opt.ec_max_ops          = DFL_EC_MAX_OPS;
914     opt.force_ciphersuite[0] = DFL_FORCE_CIPHER;
915 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
916     opt.tls13_kex_modes     = DFL_TLS1_3_KEX_MODES;
917 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
918     opt.renegotiation       = DFL_RENEGOTIATION;
919     opt.allow_legacy        = DFL_ALLOW_LEGACY;
920     opt.renegotiate         = DFL_RENEGOTIATE;
921     opt.exchanges           = DFL_EXCHANGES;
922     opt.min_version         = DFL_MIN_VERSION;
923     opt.max_version         = DFL_MAX_VERSION;
924     opt.allow_sha1          = DFL_SHA1;
925     opt.auth_mode           = DFL_AUTH_MODE;
926     opt.mfl_code            = DFL_MFL_CODE;
927     opt.trunc_hmac          = DFL_TRUNC_HMAC;
928     opt.recsplit            = DFL_RECSPLIT;
929     opt.dhmlen              = DFL_DHMLEN;
930     opt.reconnect           = DFL_RECONNECT;
931     opt.reco_server_name    = DFL_RECO_SERVER_NAME;
932     opt.reco_delay          = DFL_RECO_DELAY;
933     opt.reco_mode           = DFL_RECO_MODE;
934     opt.reconnect_hard      = DFL_RECONNECT_HARD;
935     opt.tickets             = DFL_TICKETS;
936     opt.alpn_string         = DFL_ALPN_STRING;
937     opt.groups              = DFL_GROUPS;
938     opt.sig_algs            = DFL_SIG_ALGS;
939 #if defined(MBEDTLS_SSL_EARLY_DATA)
940     opt.early_data          = DFL_EARLY_DATA;
941 #endif
942     opt.transport           = DFL_TRANSPORT;
943     opt.hs_to_min           = DFL_HS_TO_MIN;
944     opt.hs_to_max           = DFL_HS_TO_MAX;
945     opt.dtls_mtu            = DFL_DTLS_MTU;
946     opt.fallback            = DFL_FALLBACK;
947     opt.extended_ms         = DFL_EXTENDED_MS;
948     opt.etm                 = DFL_ETM;
949     opt.dgram_packing       = DFL_DGRAM_PACKING;
950     opt.serialize           = DFL_SERIALIZE;
951     opt.context_file        = DFL_CONTEXT_FILE;
952     opt.eap_tls             = DFL_EAP_TLS;
953     opt.reproducible        = DFL_REPRODUCIBLE;
954     opt.nss_keylog          = DFL_NSS_KEYLOG;
955     opt.nss_keylog_file     = DFL_NSS_KEYLOG_FILE;
956     opt.skip_close_notify   = DFL_SKIP_CLOSE_NOTIFY;
957     opt.query_config_mode   = DFL_QUERY_CONFIG_MODE;
958     opt.use_srtp            = DFL_USE_SRTP;
959     opt.force_srtp_profile  = DFL_SRTP_FORCE_PROFILE;
960     opt.mki                 = DFL_SRTP_MKI;
961     opt.key_opaque_alg1     = DFL_KEY_OPAQUE_ALG;
962     opt.key_opaque_alg2     = DFL_KEY_OPAQUE_ALG;
963 
964     for (i = 1; i < argc; i++) {
965         p = argv[i];
966         if ((q = strchr(p, '=')) == NULL) {
967             goto usage;
968         }
969         *q++ = '\0';
970 
971         if (strcmp(p, "server_name") == 0) {
972             opt.server_name = q;
973         } else if (strcmp(p, "server_addr") == 0) {
974             opt.server_addr = q;
975         } else if (strcmp(p, "server_port") == 0) {
976             opt.server_port = q;
977         } else if (strcmp(p, "dtls") == 0) {
978             int t = atoi(q);
979             if (t == 0) {
980                 opt.transport = MBEDTLS_SSL_TRANSPORT_STREAM;
981             } else if (t == 1) {
982                 opt.transport = MBEDTLS_SSL_TRANSPORT_DATAGRAM;
983             } else {
984                 goto usage;
985             }
986         } else if (strcmp(p, "debug_level") == 0) {
987             opt.debug_level = atoi(q);
988             if (opt.debug_level < 0 || opt.debug_level > 65535) {
989                 goto usage;
990             }
991         } else if (strcmp(p, "build_version") == 0) {
992             if (strcmp(q, "1") == 0) {
993                 mbedtls_printf("build version: %s (build %d)\n",
994                                MBEDTLS_VERSION_STRING_FULL,
995                                MBEDTLS_VERSION_NUMBER);
996                 goto exit;
997             }
998         } else if (strcmp(p, "context_crt_cb") == 0) {
999             opt.context_crt_cb = atoi(q);
1000             if (opt.context_crt_cb != 0 && opt.context_crt_cb != 1) {
1001                 goto usage;
1002             }
1003         } else if (strcmp(p, "nbio") == 0) {
1004             opt.nbio = atoi(q);
1005             if (opt.nbio < 0 || opt.nbio > 2) {
1006                 goto usage;
1007             }
1008         } else if (strcmp(p, "event") == 0) {
1009             opt.event = atoi(q);
1010             if (opt.event < 0 || opt.event > 2) {
1011                 goto usage;
1012             }
1013         } else if (strcmp(p, "read_timeout") == 0) {
1014             opt.read_timeout = atoi(q);
1015         } else if (strcmp(p, "max_resend") == 0) {
1016             opt.max_resend = atoi(q);
1017             if (opt.max_resend < 0) {
1018                 goto usage;
1019             }
1020         } else if (strcmp(p, "request_page") == 0) {
1021             opt.request_page = q;
1022         } else if (strcmp(p, "request_size") == 0) {
1023             opt.request_size = atoi(q);
1024             if (opt.request_size < 0 ||
1025                 opt.request_size > MAX_REQUEST_SIZE) {
1026                 goto usage;
1027             }
1028         } else if (strcmp(p, "ca_file") == 0) {
1029             opt.ca_file = q;
1030         } else if (strcmp(p, "ca_path") == 0) {
1031             opt.ca_path = q;
1032         } else if (strcmp(p, "crt_file") == 0) {
1033             opt.crt_file = q;
1034         } else if (strcmp(p, "key_file") == 0) {
1035             opt.key_file = q;
1036         } else if (strcmp(p, "key_pwd") == 0) {
1037             opt.key_pwd = q;
1038         }
1039 #if defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1040         else if (strcmp(p, "key_opaque") == 0) {
1041             opt.key_opaque = atoi(q);
1042         }
1043 #endif
1044 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1045         else if (strcmp(p, "cid") == 0) {
1046             opt.cid_enabled = atoi(q);
1047             if (opt.cid_enabled != 0 && opt.cid_enabled != 1) {
1048                 goto usage;
1049             }
1050         } else if (strcmp(p, "cid_renego") == 0) {
1051             opt.cid_enabled_renego = atoi(q);
1052             if (opt.cid_enabled_renego != 0 && opt.cid_enabled_renego != 1) {
1053                 goto usage;
1054             }
1055         } else if (strcmp(p, "cid_val") == 0) {
1056             opt.cid_val = q;
1057         } else if (strcmp(p, "cid_val_renego") == 0) {
1058             opt.cid_val_renego = q;
1059         }
1060 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1061         else if (strcmp(p, "psk") == 0) {
1062             opt.psk = q;
1063         }
1064 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1065         else if (strcmp(p, "psk_opaque") == 0) {
1066             opt.psk_opaque = atoi(q);
1067         }
1068 #endif
1069 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
1070         else if (strcmp(p, "ca_callback") == 0) {
1071             opt.ca_callback = atoi(q);
1072         }
1073 #endif
1074         else if (strcmp(p, "psk_identity") == 0) {
1075             opt.psk_identity = q;
1076         } else if (strcmp(p, "ecjpake_pw") == 0) {
1077             opt.ecjpake_pw = q;
1078         }
1079 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1080         else if (strcmp(p, "ecjpake_pw_opaque") == 0) {
1081             opt.ecjpake_pw_opaque = atoi(q);
1082         }
1083 #endif
1084         else if (strcmp(p, "ec_max_ops") == 0) {
1085             opt.ec_max_ops = atoi(q);
1086         } else if (strcmp(p, "force_ciphersuite") == 0) {
1087             opt.force_ciphersuite[0] = mbedtls_ssl_get_ciphersuite_id(q);
1088 
1089             if (opt.force_ciphersuite[0] == 0) {
1090                 ret = 2;
1091                 goto usage;
1092             }
1093             opt.force_ciphersuite[1] = 0;
1094         } else if (strcmp(p, "renegotiation") == 0) {
1095             opt.renegotiation = (atoi(q)) ?
1096                                 MBEDTLS_SSL_RENEGOTIATION_ENABLED :
1097                                 MBEDTLS_SSL_RENEGOTIATION_DISABLED;
1098         } else if (strcmp(p, "allow_legacy") == 0) {
1099             switch (atoi(q)) {
1100                 case -1:
1101                     opt.allow_legacy = MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE;
1102                     break;
1103                 case 0:
1104                     opt.allow_legacy = MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION;
1105                     break;
1106                 case 1:
1107                     opt.allow_legacy = MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION;
1108                     break;
1109                 default: goto usage;
1110             }
1111         } else if (strcmp(p, "renegotiate") == 0) {
1112             opt.renegotiate = atoi(q);
1113             if (opt.renegotiate < 0 || opt.renegotiate > 1) {
1114                 goto usage;
1115             }
1116         } else if (strcmp(p, "exchanges") == 0) {
1117             opt.exchanges = atoi(q);
1118             if (opt.exchanges < 1) {
1119                 goto usage;
1120             }
1121         } else if (strcmp(p, "reconnect") == 0) {
1122             opt.reconnect = atoi(q);
1123             if (opt.reconnect < 0 || opt.reconnect > 2) {
1124                 goto usage;
1125             }
1126         } else if (strcmp(p, "reco_server_name") == 0) {
1127             opt.reco_server_name = q;
1128         } else if (strcmp(p, "reco_delay") == 0) {
1129             opt.reco_delay = atoi(q);
1130             if (opt.reco_delay < 0) {
1131                 goto usage;
1132             }
1133         } else if (strcmp(p, "reco_mode") == 0) {
1134             opt.reco_mode = atoi(q);
1135             if (opt.reco_mode < 0) {
1136                 goto usage;
1137             }
1138         } else if (strcmp(p, "reconnect_hard") == 0) {
1139             opt.reconnect_hard = atoi(q);
1140             if (opt.reconnect_hard < 0 || opt.reconnect_hard > 1) {
1141                 goto usage;
1142             }
1143         } else if (strcmp(p, "tickets") == 0) {
1144             opt.tickets = atoi(q);
1145             if (opt.tickets < 0) {
1146                 goto usage;
1147             }
1148         } else if (strcmp(p, "alpn") == 0) {
1149             opt.alpn_string = q;
1150         } else if (strcmp(p, "extended_ms") == 0) {
1151             switch (atoi(q)) {
1152                 case 0:
1153                     opt.extended_ms = MBEDTLS_SSL_EXTENDED_MS_DISABLED;
1154                     break;
1155                 case 1:
1156                     opt.extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
1157                     break;
1158                 default: goto usage;
1159             }
1160         } else if (strcmp(p, "groups") == 0) {
1161             opt.groups = q;
1162         }
1163 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1164         else if (strcmp(p, "sig_algs") == 0) {
1165             opt.sig_algs = q;
1166         }
1167 #endif
1168         else if (strcmp(p, "etm") == 0) {
1169             switch (atoi(q)) {
1170                 case 0: opt.etm = MBEDTLS_SSL_ETM_DISABLED; break;
1171                 case 1: opt.etm = MBEDTLS_SSL_ETM_ENABLED; break;
1172                 default: goto usage;
1173             }
1174         }
1175 
1176 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1177 #if defined(MBEDTLS_SSL_EARLY_DATA)
1178         else if (strcmp(p, "early_data") == 0) {
1179             switch (atoi(q)) {
1180                 case 0:
1181                     opt.early_data = MBEDTLS_SSL_EARLY_DATA_DISABLED;
1182                     break;
1183                 case 1:
1184                     opt.early_data = MBEDTLS_SSL_EARLY_DATA_ENABLED;
1185                     break;
1186                 default: goto usage;
1187             }
1188         }
1189 #endif /* MBEDTLS_SSL_EARLY_DATA */
1190 
1191         else if (strcmp(p, "tls13_kex_modes") == 0) {
1192             if (strcmp(q, "psk") == 0) {
1193                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
1194             } else if (strcmp(q, "psk_ephemeral") == 0) {
1195                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
1196             } else if (strcmp(q, "ephemeral") == 0) {
1197                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL;
1198             } else if (strcmp(q, "ephemeral_all") == 0) {
1199                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ALL;
1200             } else if (strcmp(q, "psk_all") == 0) {
1201                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL;
1202             } else if (strcmp(q, "all") == 0) {
1203                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_ALL;
1204             } else if (strcmp(q, "psk_or_ephemeral") == 0) {
1205                 opt.tls13_kex_modes = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK |
1206                                       MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL;
1207             } else {
1208                 goto usage;
1209             }
1210         }
1211 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1212         else if (strcmp(p, "min_version") == 0) {
1213             if (strcmp(q, "tls12") == 0 ||
1214                 strcmp(q, "dtls12") == 0) {
1215                 opt.min_version = MBEDTLS_SSL_VERSION_TLS1_2;
1216             }
1217 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1218             else if (strcmp(q, "tls13") == 0) {
1219                 opt.min_version = MBEDTLS_SSL_VERSION_TLS1_3;
1220             }
1221 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1222             else {
1223                 goto usage;
1224             }
1225         } else if (strcmp(p, "max_version") == 0) {
1226             if (strcmp(q, "tls12") == 0 ||
1227                 strcmp(q, "dtls12") == 0) {
1228                 opt.max_version = MBEDTLS_SSL_VERSION_TLS1_2;
1229             }
1230 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1231             else if (strcmp(q, "tls13") == 0) {
1232                 opt.max_version = MBEDTLS_SSL_VERSION_TLS1_3;
1233             }
1234 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1235             else {
1236                 goto usage;
1237             }
1238         } else if (strcmp(p, "allow_sha1") == 0) {
1239             switch (atoi(q)) {
1240                 case 0:     opt.allow_sha1 = 0;   break;
1241                 case 1:     opt.allow_sha1 = 1;    break;
1242                 default:    goto usage;
1243             }
1244         } else if (strcmp(p, "force_version") == 0) {
1245             if (strcmp(q, "tls12") == 0) {
1246                 opt.min_version = MBEDTLS_SSL_VERSION_TLS1_2;
1247                 opt.max_version = MBEDTLS_SSL_VERSION_TLS1_2;
1248             } else if (strcmp(q, "dtls12") == 0) {
1249                 opt.min_version = MBEDTLS_SSL_VERSION_TLS1_2;
1250                 opt.max_version = MBEDTLS_SSL_VERSION_TLS1_2;
1251                 opt.transport = MBEDTLS_SSL_TRANSPORT_DATAGRAM;
1252             }
1253 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1254             else if (strcmp(q, "tls13") == 0) {
1255                 opt.min_version = MBEDTLS_SSL_VERSION_TLS1_3;
1256                 opt.max_version = MBEDTLS_SSL_VERSION_TLS1_3;
1257             }
1258 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1259             else {
1260                 goto usage;
1261             }
1262         } else if (strcmp(p, "auth_mode") == 0) {
1263             if (strcmp(q, "none") == 0) {
1264                 opt.auth_mode = MBEDTLS_SSL_VERIFY_NONE;
1265             } else if (strcmp(q, "optional") == 0) {
1266                 opt.auth_mode = MBEDTLS_SSL_VERIFY_OPTIONAL;
1267             } else if (strcmp(q, "required") == 0) {
1268                 opt.auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
1269             } else {
1270                 goto usage;
1271             }
1272         } else if (strcmp(p, "max_frag_len") == 0) {
1273             if (strcmp(q, "512") == 0) {
1274                 opt.mfl_code = MBEDTLS_SSL_MAX_FRAG_LEN_512;
1275             } else if (strcmp(q, "1024") == 0) {
1276                 opt.mfl_code = MBEDTLS_SSL_MAX_FRAG_LEN_1024;
1277             } else if (strcmp(q, "2048") == 0) {
1278                 opt.mfl_code = MBEDTLS_SSL_MAX_FRAG_LEN_2048;
1279             } else if (strcmp(q, "4096") == 0) {
1280                 opt.mfl_code = MBEDTLS_SSL_MAX_FRAG_LEN_4096;
1281             } else {
1282                 goto usage;
1283             }
1284         } else if (strcmp(p, "trunc_hmac") == 0) {
1285             switch (atoi(q)) {
1286                 case 0: opt.trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_DISABLED; break;
1287                 case 1: opt.trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED; break;
1288                 default: goto usage;
1289             }
1290         } else if (strcmp(p, "hs_timeout") == 0) {
1291             if ((p = strchr(q, '-')) == NULL) {
1292                 goto usage;
1293             }
1294             *p++ = '\0';
1295             opt.hs_to_min = atoi(q);
1296             opt.hs_to_max = atoi(p);
1297             if (opt.hs_to_min == 0 || opt.hs_to_max < opt.hs_to_min) {
1298                 goto usage;
1299             }
1300         } else if (strcmp(p, "mtu") == 0) {
1301             opt.dtls_mtu = atoi(q);
1302             if (opt.dtls_mtu < 0) {
1303                 goto usage;
1304             }
1305         } else if (strcmp(p, "dgram_packing") == 0) {
1306             opt.dgram_packing = atoi(q);
1307             if (opt.dgram_packing != 0 &&
1308                 opt.dgram_packing != 1) {
1309                 goto usage;
1310             }
1311         } else if (strcmp(p, "recsplit") == 0) {
1312             opt.recsplit = atoi(q);
1313             if (opt.recsplit < 0 || opt.recsplit > 1) {
1314                 goto usage;
1315             }
1316         } else if (strcmp(p, "dhmlen") == 0) {
1317             opt.dhmlen = atoi(q);
1318             if (opt.dhmlen < 0) {
1319                 goto usage;
1320             }
1321         } else if (strcmp(p, "query_config") == 0) {
1322             opt.query_config_mode = 1;
1323             query_config_ret = query_config(q);
1324             goto exit;
1325         } else if (strcmp(p, "serialize") == 0) {
1326             opt.serialize = atoi(q);
1327             if (opt.serialize < 0 || opt.serialize > 2) {
1328                 goto usage;
1329             }
1330         } else if (strcmp(p, "context_file") == 0) {
1331             opt.context_file = q;
1332         } else if (strcmp(p, "eap_tls") == 0) {
1333             opt.eap_tls = atoi(q);
1334             if (opt.eap_tls < 0 || opt.eap_tls > 1) {
1335                 goto usage;
1336             }
1337         } else if (strcmp(p, "reproducible") == 0) {
1338             opt.reproducible = 1;
1339         } else if (strcmp(p, "nss_keylog") == 0) {
1340             opt.nss_keylog = atoi(q);
1341             if (opt.nss_keylog < 0 || opt.nss_keylog > 1) {
1342                 goto usage;
1343             }
1344         } else if (strcmp(p, "nss_keylog_file") == 0) {
1345             opt.nss_keylog_file = q;
1346         } else if (strcmp(p, "skip_close_notify") == 0) {
1347             opt.skip_close_notify = atoi(q);
1348             if (opt.skip_close_notify < 0 || opt.skip_close_notify > 1) {
1349                 goto usage;
1350             }
1351         } else if (strcmp(p, "use_srtp") == 0) {
1352             opt.use_srtp = atoi(q);
1353         } else if (strcmp(p, "srtp_force_profile") == 0) {
1354             opt.force_srtp_profile = atoi(q);
1355         } else if (strcmp(p, "mki") == 0) {
1356             opt.mki = q;
1357         } else if (strcmp(p, "key_opaque_algs") == 0) {
1358             if (key_opaque_alg_parse(q, &opt.key_opaque_alg1,
1359                                      &opt.key_opaque_alg2) != 0) {
1360                 goto usage;
1361             }
1362         } else {
1363             goto usage;
1364         }
1365     }
1366 
1367     if (opt.nss_keylog != 0 && opt.eap_tls != 0) {
1368         mbedtls_printf("Error: eap_tls and nss_keylog options cannot be used together.\n");
1369         goto usage;
1370     }
1371 
1372     /* Event-driven IO is incompatible with the above custom
1373      * receive and send functions, as the polling builds on
1374      * refers to the underlying net_context. */
1375     if (opt.event == 1 && opt.nbio != 1) {
1376         mbedtls_printf("Warning: event-driven IO mandates nbio=1 - overwrite\n");
1377         opt.nbio = 1;
1378     }
1379 
1380 #if defined(MBEDTLS_DEBUG_C)
1381     mbedtls_debug_set_threshold(opt.debug_level);
1382 #endif
1383 
1384 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
1385     /*
1386      * Unhexify the pre-shared key if any is given
1387      */
1388     if (strlen(opt.psk)) {
1389         if (mbedtls_test_unhexify(psk, sizeof(psk),
1390                                   opt.psk, &psk_len) != 0) {
1391             mbedtls_printf("pre-shared key not valid\n");
1392             goto exit;
1393         }
1394     }
1395 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
1396 
1397 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1398     if (opt.psk_opaque != 0) {
1399         if (opt.psk == NULL) {
1400             mbedtls_printf("psk_opaque set but no psk to be imported specified.\n");
1401             ret = 2;
1402             goto usage;
1403         }
1404 
1405         if (opt.force_ciphersuite[0] <= 0) {
1406             mbedtls_printf(
1407                 "opaque PSKs are only supported in conjunction with forcing TLS 1.2 and a PSK-only ciphersuite through the 'force_ciphersuite' option.\n");
1408             ret = 2;
1409             goto usage;
1410         }
1411     }
1412 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1413 
1414     if (opt.force_ciphersuite[0] > 0) {
1415         const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
1416         ciphersuite_info =
1417             mbedtls_ssl_ciphersuite_from_id(opt.force_ciphersuite[0]);
1418 
1419         if (opt.max_version != -1 &&
1420             ciphersuite_info->min_tls_version > opt.max_version) {
1421             mbedtls_printf("forced ciphersuite not allowed with this protocol version\n");
1422             ret = 2;
1423             goto usage;
1424         }
1425         if (opt.min_version != -1 &&
1426             ciphersuite_info->max_tls_version < opt.min_version) {
1427             mbedtls_printf("forced ciphersuite not allowed with this protocol version\n");
1428             ret = 2;
1429             goto usage;
1430         }
1431 
1432         /* If the server selects a version that's not supported by
1433          * this suite, then there will be no common ciphersuite... */
1434         if (opt.max_version == -1 ||
1435             opt.max_version > ciphersuite_info->max_tls_version) {
1436             opt.max_version = ciphersuite_info->max_tls_version;
1437         }
1438         if (opt.min_version < ciphersuite_info->min_tls_version) {
1439             opt.min_version = ciphersuite_info->min_tls_version;
1440             /* DTLS starts with TLS 1.2 */
1441             if (opt.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
1442                 opt.min_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1443                 opt.min_version = MBEDTLS_SSL_VERSION_TLS1_2;
1444             }
1445         }
1446 
1447 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1448 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
1449         if (opt.psk_opaque != 0) {
1450             /* Determine KDF algorithm the opaque PSK will be used in. */
1451 #if defined(MBEDTLS_MD_CAN_SHA384)
1452             if (ciphersuite_info->mac == MBEDTLS_MD_SHA384) {
1453                 alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_384);
1454             } else
1455 #endif /* MBEDTLS_MD_CAN_SHA384 */
1456             alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_256);
1457         }
1458 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
1459 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1460     }
1461 
1462 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1463     if (mbedtls_test_unhexify(cid, sizeof(cid),
1464                               opt.cid_val, &cid_len) != 0) {
1465         mbedtls_printf("CID not valid\n");
1466         goto exit;
1467     }
1468 
1469     /* Keep CID settings for renegotiation unless
1470      * specified otherwise. */
1471     if (opt.cid_enabled_renego == DFL_CID_ENABLED_RENEGO) {
1472         opt.cid_enabled_renego = opt.cid_enabled;
1473     }
1474     if (opt.cid_val_renego == DFL_CID_VALUE_RENEGO) {
1475         opt.cid_val_renego = opt.cid_val;
1476     }
1477 
1478     if (mbedtls_test_unhexify(cid_renego, sizeof(cid_renego),
1479                               opt.cid_val_renego, &cid_renego_len) != 0) {
1480         mbedtls_printf("CID not valid\n");
1481         goto exit;
1482     }
1483 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1484 
1485     if (opt.groups != NULL) {
1486         if (parse_groups(opt.groups, group_list, GROUP_LIST_SIZE) != 0) {
1487             goto exit;
1488         }
1489     }
1490 
1491 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1492     if (opt.sig_algs != NULL) {
1493         p = (char *) opt.sig_algs;
1494         i = 0;
1495 
1496         /* Leave room for a final MBEDTLS_TLS1_3_SIG_NONE in signature algorithm list (sig_alg_list). */
1497         while (i < SIG_ALG_LIST_SIZE - 1 && *p != '\0') {
1498             q = p;
1499 
1500             /* Terminate the current string */
1501             while (*p != ',' && *p != '\0') {
1502                 p++;
1503             }
1504             if (*p == ',') {
1505                 *p++ = '\0';
1506             }
1507 
1508             if (strcmp(q, "rsa_pkcs1_sha256") == 0) {
1509                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA256;
1510             } else if (strcmp(q, "rsa_pkcs1_sha384") == 0) {
1511                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA384;
1512             } else if (strcmp(q, "rsa_pkcs1_sha512") == 0) {
1513                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA512;
1514             } else if (strcmp(q, "ecdsa_secp256r1_sha256") == 0) {
1515                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_ECDSA_SECP256R1_SHA256;
1516             } else if (strcmp(q, "ecdsa_secp384r1_sha384") == 0) {
1517                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_ECDSA_SECP384R1_SHA384;
1518             } else if (strcmp(q, "ecdsa_secp521r1_sha512") == 0) {
1519                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_ECDSA_SECP521R1_SHA512;
1520             } else if (strcmp(q, "rsa_pss_rsae_sha256") == 0) {
1521                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256;
1522             } else if (strcmp(q, "rsa_pss_rsae_sha384") == 0) {
1523                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384;
1524             } else if (strcmp(q, "rsa_pss_rsae_sha512") == 0) {
1525                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512;
1526             } else if (strcmp(q, "ed25519") == 0) {
1527                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_ED25519;
1528             } else if (strcmp(q, "ed448") == 0) {
1529                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_ED448;
1530             } else if (strcmp(q, "rsa_pss_pss_sha256") == 0) {
1531                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PSS_PSS_SHA256;
1532             } else if (strcmp(q, "rsa_pss_pss_sha384") == 0) {
1533                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PSS_PSS_SHA384;
1534             } else if (strcmp(q, "rsa_pss_pss_sha512") == 0) {
1535                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PSS_PSS_SHA512;
1536             } else if (strcmp(q, "rsa_pkcs1_sha1") == 0) {
1537                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA1;
1538             } else if (strcmp(q, "ecdsa_sha1") == 0) {
1539                 sig_alg_list[i++] = MBEDTLS_TLS1_3_SIG_ECDSA_SHA1;
1540             } else {
1541                 ret = -1;
1542                 mbedtls_printf("unknown signature algorithm \"%s\"\n", q);
1543                 mbedtls_print_supported_sig_algs();
1544                 goto exit;
1545             }
1546         }
1547 
1548         if (i == (SIG_ALG_LIST_SIZE - 1) && *p != '\0') {
1549             mbedtls_printf("signature algorithm list too long, maximum %d",
1550                            SIG_ALG_LIST_SIZE - 1);
1551             goto exit;
1552         }
1553 
1554         sig_alg_list[i] = MBEDTLS_TLS1_3_SIG_NONE;
1555     }
1556 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
1557 
1558 #if defined(MBEDTLS_SSL_ALPN)
1559     if (opt.alpn_string != NULL) {
1560         p = (char *) opt.alpn_string;
1561         i = 0;
1562 
1563         /* Leave room for a final NULL in alpn_list */
1564         while (i < ALPN_LIST_SIZE - 1 && *p != '\0') {
1565             alpn_list[i++] = p;
1566 
1567             /* Terminate the current string and move on to next one */
1568             while (*p != ',' && *p != '\0') {
1569                 p++;
1570             }
1571             if (*p == ',') {
1572                 *p++ = '\0';
1573             }
1574         }
1575     }
1576 #endif /* MBEDTLS_SSL_ALPN */
1577 
1578     mbedtls_printf("build version: %s (build %d)\n",
1579                    MBEDTLS_VERSION_STRING_FULL, MBEDTLS_VERSION_NUMBER);
1580 
1581     /*
1582      * 0. Initialize the RNG and the session data
1583      */
1584     mbedtls_printf("\n  . Seeding the random number generator...");
1585     fflush(stdout);
1586 
1587     ret = rng_seed(&rng, opt.reproducible, pers);
1588     if (ret != 0) {
1589         goto exit;
1590     }
1591     mbedtls_printf(" ok\n");
1592 
1593 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1594     /*
1595      * 1.1. Load the trusted CA
1596      */
1597     mbedtls_printf("  . Loading the CA root certificate ...");
1598     fflush(stdout);
1599 
1600     if (strcmp(opt.ca_path, "none") == 0 ||
1601         strcmp(opt.ca_file, "none") == 0) {
1602         ret = 0;
1603     } else
1604 #if defined(MBEDTLS_FS_IO)
1605     if (strlen(opt.ca_path)) {
1606         ret = mbedtls_x509_crt_parse_path(&cacert, opt.ca_path);
1607     } else if (strlen(opt.ca_file)) {
1608         ret = mbedtls_x509_crt_parse_file(&cacert, opt.ca_file);
1609     } else
1610 #endif
1611     {
1612 #if defined(MBEDTLS_PEM_PARSE_C)
1613         for (i = 0; mbedtls_test_cas[i] != NULL; i++) {
1614             ret = mbedtls_x509_crt_parse(&cacert,
1615                                          (const unsigned char *) mbedtls_test_cas[i],
1616                                          mbedtls_test_cas_len[i]);
1617             if (ret != 0) {
1618                 break;
1619             }
1620         }
1621 #endif /* MBEDTLS_PEM_PARSE_C */
1622         if (ret == 0) {
1623             for (i = 0; mbedtls_test_cas_der[i] != NULL; i++) {
1624                 ret = mbedtls_x509_crt_parse_der(&cacert,
1625                                                  (const unsigned char *) mbedtls_test_cas_der[i],
1626                                                  mbedtls_test_cas_der_len[i]);
1627                 if (ret != 0) {
1628                     break;
1629                 }
1630             }
1631         }
1632     }
1633     if (ret < 0) {
1634         mbedtls_printf(" failed\n  !  mbedtls_x509_crt_parse returned -0x%x\n\n",
1635                        (unsigned int) -ret);
1636         goto exit;
1637     }
1638 
1639     mbedtls_printf(" ok (%d skipped)\n", ret);
1640 
1641     /*
1642      * 1.2. Load own certificate and private key
1643      *
1644      * (can be skipped if client authentication is not required)
1645      */
1646     mbedtls_printf("  . Loading the client cert. and key...");
1647     fflush(stdout);
1648 
1649     if (strcmp(opt.crt_file, "none") == 0) {
1650         ret = 0;
1651     } else
1652 #if defined(MBEDTLS_FS_IO)
1653     if (strlen(opt.crt_file)) {
1654         ret = mbedtls_x509_crt_parse_file(&clicert, opt.crt_file);
1655     } else
1656 #endif
1657     { ret = mbedtls_x509_crt_parse(&clicert,
1658                                    (const unsigned char *) mbedtls_test_cli_crt,
1659                                    mbedtls_test_cli_crt_len); }
1660     if (ret != 0) {
1661         mbedtls_printf(" failed\n  !  mbedtls_x509_crt_parse returned -0x%x\n\n",
1662                        (unsigned int) -ret);
1663         goto exit;
1664     }
1665 
1666     if (strcmp(opt.key_file, "none") == 0) {
1667         ret = 0;
1668     } else
1669 #if defined(MBEDTLS_FS_IO)
1670     if (strlen(opt.key_file)) {
1671         ret = mbedtls_pk_parse_keyfile(&pkey, opt.key_file, opt.key_pwd, rng_get, &rng);
1672     } else
1673 #endif
1674     { ret = mbedtls_pk_parse_key(&pkey,
1675                                  (const unsigned char *) mbedtls_test_cli_key,
1676                                  mbedtls_test_cli_key_len, NULL, 0, rng_get, &rng); }
1677     if (ret != 0) {
1678         mbedtls_printf(" failed\n  !  mbedtls_pk_parse_key returned -0x%x\n\n",
1679                        (unsigned int) -ret);
1680         goto exit;
1681     }
1682 
1683 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1684     if (opt.key_opaque != 0) {
1685         psa_algorithm_t psa_alg, psa_alg2 = PSA_ALG_NONE;
1686         psa_key_usage_t usage = 0;
1687 
1688         if (key_opaque_set_alg_usage(opt.key_opaque_alg1,
1689                                      opt.key_opaque_alg2,
1690                                      &psa_alg, &psa_alg2,
1691                                      &usage,
1692                                      mbedtls_pk_get_type(&pkey)) == 0) {
1693             ret = mbedtls_pk_wrap_as_opaque(&pkey, &key_slot, psa_alg,
1694                                             usage, psa_alg2);
1695             if (ret != 0) {
1696                 mbedtls_printf(" failed\n  !  "
1697                                "mbedtls_pk_wrap_as_opaque returned -0x%x\n\n",
1698                                (unsigned int)  -ret);
1699                 goto exit;
1700             }
1701         }
1702     }
1703 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1704 
1705     mbedtls_printf(" ok (key type: %s)\n",
1706                    strlen(opt.key_file) || strlen(opt.key_opaque_alg1) ?
1707                    mbedtls_pk_get_name(&pkey) : "none");
1708 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
1709 
1710     /*
1711      * 2. Setup stuff
1712      */
1713     mbedtls_printf("  . Setting up the SSL/TLS structure...");
1714     fflush(stdout);
1715 
1716     if ((ret = mbedtls_ssl_config_defaults(&conf,
1717                                            MBEDTLS_SSL_IS_CLIENT,
1718                                            opt.transport,
1719                                            MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1720         mbedtls_printf(" failed\n  ! mbedtls_ssl_config_defaults returned -0x%x\n\n",
1721                        (unsigned int) -ret);
1722         goto exit;
1723     }
1724 
1725 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1726     /* The default algorithms profile disables SHA-1, but our tests still
1727        rely on it heavily. */
1728     if (opt.allow_sha1 > 0) {
1729         crt_profile_for_test.allowed_mds |= MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1);
1730         mbedtls_ssl_conf_cert_profile(&conf, &crt_profile_for_test);
1731         mbedtls_ssl_conf_sig_algs(&conf, ssl_sig_algs_for_test);
1732     }
1733     if (opt.context_crt_cb == 0) {
1734         mbedtls_ssl_conf_verify(&conf, my_verify, NULL);
1735     }
1736 
1737     memset(peer_crt_info, 0, sizeof(peer_crt_info));
1738 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
1739 
1740 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1741     if (opt.cid_enabled == 1 || opt.cid_enabled_renego == 1) {
1742         if (opt.cid_enabled == 1        &&
1743             opt.cid_enabled_renego == 1 &&
1744             cid_len != cid_renego_len) {
1745             mbedtls_printf("CID length must not change during renegotiation\n");
1746             goto usage;
1747         }
1748 
1749         if (opt.cid_enabled == 1) {
1750             ret = mbedtls_ssl_conf_cid(&conf, cid_len,
1751                                        MBEDTLS_SSL_UNEXPECTED_CID_IGNORE);
1752         } else {
1753             ret = mbedtls_ssl_conf_cid(&conf, cid_renego_len,
1754                                        MBEDTLS_SSL_UNEXPECTED_CID_IGNORE);
1755         }
1756 
1757         if (ret != 0) {
1758             mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_cid_len returned -%#04x\n\n",
1759                            (unsigned int) -ret);
1760             goto exit;
1761         }
1762     }
1763 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1764 
1765     if (opt.auth_mode != DFL_AUTH_MODE) {
1766         mbedtls_ssl_conf_authmode(&conf, opt.auth_mode);
1767     }
1768 
1769 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1770     if (opt.hs_to_min != DFL_HS_TO_MIN || opt.hs_to_max != DFL_HS_TO_MAX) {
1771         mbedtls_ssl_conf_handshake_timeout(&conf, opt.hs_to_min,
1772                                            opt.hs_to_max);
1773     }
1774 
1775     if (opt.dgram_packing != DFL_DGRAM_PACKING) {
1776         mbedtls_ssl_set_datagram_packing(&ssl, opt.dgram_packing);
1777     }
1778 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1779 
1780 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1781     if ((ret = mbedtls_ssl_conf_max_frag_len(&conf, opt.mfl_code)) != 0) {
1782         mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_max_frag_len returned %d\n\n",
1783                        ret);
1784         goto exit;
1785     }
1786 #endif
1787 
1788 #if defined(MBEDTLS_SSL_DTLS_SRTP)
1789     const mbedtls_ssl_srtp_profile forced_profile[] =
1790     { opt.force_srtp_profile, MBEDTLS_TLS_SRTP_UNSET };
1791     if (opt.use_srtp == 1) {
1792         if (opt.force_srtp_profile != 0) {
1793             ret = mbedtls_ssl_conf_dtls_srtp_protection_profiles(&conf, forced_profile);
1794         } else {
1795             ret = mbedtls_ssl_conf_dtls_srtp_protection_profiles(&conf, default_profiles);
1796         }
1797 
1798         if (ret != 0) {
1799             mbedtls_printf(" failed\n  ! "
1800                            "mbedtls_ssl_conf_dtls_srtp_protection_profiles returned %d\n\n",
1801                            ret);
1802             goto exit;
1803         }
1804 
1805     } else if (opt.force_srtp_profile != 0) {
1806         mbedtls_printf(" failed\n  ! must enable use_srtp to force srtp profile\n\n");
1807         goto exit;
1808     }
1809 #endif /* MBEDTLS_SSL_DTLS_SRTP */
1810 
1811 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1812     if (opt.extended_ms != DFL_EXTENDED_MS) {
1813         mbedtls_ssl_conf_extended_master_secret(&conf, opt.extended_ms);
1814     }
1815 #endif
1816 
1817 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1818     if (opt.etm != DFL_ETM) {
1819         mbedtls_ssl_conf_encrypt_then_mac(&conf, opt.etm);
1820     }
1821 #endif
1822 
1823 #if defined(MBEDTLS_DHM_C)
1824     if (opt.dhmlen != DFL_DHMLEN) {
1825         mbedtls_ssl_conf_dhm_min_bitlen(&conf, opt.dhmlen);
1826     }
1827 #endif
1828 
1829 #if defined(MBEDTLS_SSL_ALPN)
1830     if (opt.alpn_string != NULL) {
1831         if ((ret = mbedtls_ssl_conf_alpn_protocols(&conf, alpn_list)) != 0) {
1832             mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_alpn_protocols returned %d\n\n",
1833                            ret);
1834             goto exit;
1835         }
1836     }
1837 #endif
1838 
1839     if (opt.reproducible) {
1840 #if defined(MBEDTLS_HAVE_TIME)
1841 #if defined(MBEDTLS_PLATFORM_TIME_ALT)
1842         mbedtls_platform_set_time(dummy_constant_time);
1843 #else
1844         fprintf(stderr, "Warning: reproducible option used without constant time\n");
1845 #endif
1846 #endif  /* MBEDTLS_HAVE_TIME */
1847     }
1848     mbedtls_ssl_conf_rng(&conf, rng_get, &rng);
1849     mbedtls_ssl_conf_dbg(&conf, my_debug, stdout);
1850 
1851     mbedtls_ssl_conf_read_timeout(&conf, opt.read_timeout);
1852 
1853 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
1854     mbedtls_ssl_conf_session_tickets(&conf, opt.tickets);
1855 #endif
1856 
1857     if (opt.force_ciphersuite[0] != DFL_FORCE_CIPHER) {
1858         mbedtls_ssl_conf_ciphersuites(&conf, opt.force_ciphersuite);
1859     }
1860 
1861 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1862     mbedtls_ssl_conf_tls13_key_exchange_modes(&conf, opt.tls13_kex_modes);
1863 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1864 
1865     if (opt.allow_legacy != DFL_ALLOW_LEGACY) {
1866         mbedtls_ssl_conf_legacy_renegotiation(&conf, opt.allow_legacy);
1867     }
1868 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1869     mbedtls_ssl_conf_renegotiation(&conf, opt.renegotiation);
1870 #endif
1871 
1872 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1873     if (strcmp(opt.ca_path, "none") != 0 &&
1874         strcmp(opt.ca_file, "none") != 0) {
1875 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
1876         if (opt.ca_callback != 0) {
1877             mbedtls_ssl_conf_ca_cb(&conf, ca_callback, &cacert);
1878         } else
1879 #endif
1880         mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
1881     }
1882     if (strcmp(opt.crt_file, "none") != 0 &&
1883         strcmp(opt.key_file, "none") != 0) {
1884         if ((ret = mbedtls_ssl_conf_own_cert(&conf, &clicert, &pkey)) != 0) {
1885             mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_own_cert returned %d\n\n",
1886                            ret);
1887             goto exit;
1888         }
1889     }
1890 #endif  /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
1891 
1892 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS) || \
1893     (defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED) && \
1894     defined(PSA_WANT_ALG_FFDH))
1895     if (opt.groups != NULL &&
1896         strcmp(opt.groups, "default") != 0) {
1897         mbedtls_ssl_conf_groups(&conf, group_list);
1898     }
1899 #endif
1900 
1901 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1902     if (opt.sig_algs != NULL) {
1903         mbedtls_ssl_conf_sig_algs(&conf, sig_alg_list);
1904     }
1905 #endif
1906 
1907 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
1908 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1909     if (opt.psk_opaque != 0) {
1910         key_attributes = psa_key_attributes_init();
1911         psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
1912         psa_set_key_algorithm(&key_attributes, alg);
1913         psa_set_key_type(&key_attributes, PSA_KEY_TYPE_DERIVE);
1914 
1915         status = psa_import_key(&key_attributes, psk, psk_len, &slot);
1916         if (status != PSA_SUCCESS) {
1917             ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
1918             goto exit;
1919         }
1920 
1921         if ((ret = mbedtls_ssl_conf_psk_opaque(&conf, slot,
1922                                                (const unsigned char *) opt.psk_identity,
1923                                                strlen(opt.psk_identity))) != 0) {
1924             mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_psk_opaque returned %d\n\n",
1925                            ret);
1926             goto exit;
1927         }
1928     } else
1929 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1930     if (psk_len > 0) {
1931         ret = mbedtls_ssl_conf_psk(&conf, psk, psk_len,
1932                                    (const unsigned char *) opt.psk_identity,
1933                                    strlen(opt.psk_identity));
1934         if (ret != 0) {
1935             mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_psk returned %d\n\n", ret);
1936             goto exit;
1937         }
1938     }
1939 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
1940 
1941     if (opt.min_version != DFL_MIN_VERSION) {
1942         mbedtls_ssl_conf_min_tls_version(&conf, opt.min_version);
1943     }
1944 
1945     if (opt.max_version != DFL_MAX_VERSION) {
1946         mbedtls_ssl_conf_max_tls_version(&conf, opt.max_version);
1947     }
1948 
1949 #if defined(MBEDTLS_SSL_EARLY_DATA)
1950     mbedtls_ssl_tls13_conf_early_data(&conf, opt.early_data);
1951 #endif /* MBEDTLS_SSL_EARLY_DATA */
1952 
1953     if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
1954         mbedtls_printf(" failed\n  ! mbedtls_ssl_setup returned -0x%x\n\n",
1955                        (unsigned int) -ret);
1956         goto exit;
1957     }
1958 
1959     if (opt.eap_tls != 0) {
1960         mbedtls_ssl_set_export_keys_cb(&ssl, eap_tls_key_derivation,
1961                                        &eap_tls_keying);
1962     } else if (opt.nss_keylog != 0) {
1963         mbedtls_ssl_set_export_keys_cb(&ssl,
1964                                        nss_keylog_export,
1965                                        NULL);
1966     }
1967 #if defined(MBEDTLS_SSL_DTLS_SRTP)
1968     else if (opt.use_srtp != 0) {
1969         mbedtls_ssl_set_export_keys_cb(&ssl, dtls_srtp_key_derivation,
1970                                        &dtls_srtp_keying);
1971     }
1972 #endif /* MBEDTLS_SSL_DTLS_SRTP */
1973 
1974 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
1975     if ((ret = mbedtls_ssl_set_hostname(&ssl, opt.server_name)) != 0) {
1976         mbedtls_printf(" failed\n  ! mbedtls_ssl_set_hostname returned %d\n\n",
1977                        ret);
1978         goto exit;
1979     }
1980 #endif
1981 
1982 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1983     if (opt.ecjpake_pw != DFL_ECJPAKE_PW) {
1984 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1985         if (opt.ecjpake_pw_opaque != DFL_ECJPAKE_PW_OPAQUE) {
1986             psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1987 
1988             psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
1989             psa_set_key_algorithm(&attributes, PSA_ALG_JPAKE);
1990             psa_set_key_type(&attributes, PSA_KEY_TYPE_PASSWORD);
1991 
1992             status = psa_import_key(&attributes,
1993                                     (const unsigned char *) opt.ecjpake_pw,
1994                                     strlen(opt.ecjpake_pw),
1995                                     &ecjpake_pw_slot);
1996             if (status != PSA_SUCCESS) {
1997                 mbedtls_printf(" failed\n  ! psa_import_key returned %d\n\n",
1998                                status);
1999                 goto exit;
2000             }
2001             if ((ret = mbedtls_ssl_set_hs_ecjpake_password_opaque(&ssl,
2002                                                                   ecjpake_pw_slot)) != 0) {
2003                 mbedtls_printf(
2004                     " failed\n  ! mbedtls_ssl_set_hs_ecjpake_password_opaque returned %d\n\n",
2005                     ret);
2006                 goto exit;
2007             }
2008             mbedtls_printf("using opaque password\n");
2009         } else
2010 #endif  /* MBEDTLS_USE_PSA_CRYPTO */
2011         {
2012             if ((ret = mbedtls_ssl_set_hs_ecjpake_password(&ssl,
2013                                                            (const unsigned char *) opt.ecjpake_pw,
2014                                                            strlen(opt.ecjpake_pw))) != 0) {
2015                 mbedtls_printf(" failed\n  ! mbedtls_ssl_set_hs_ecjpake_password returned %d\n\n",
2016                                ret);
2017                 goto exit;
2018             }
2019         }
2020     }
2021 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2022 
2023 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2024     if (opt.context_crt_cb == 1) {
2025         mbedtls_ssl_set_verify(&ssl, my_verify, NULL);
2026     }
2027 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2028 
2029     io_ctx.ssl = &ssl;
2030     io_ctx.net = &server_fd;
2031     mbedtls_ssl_set_bio(&ssl, &io_ctx, send_cb, recv_cb,
2032                         opt.nbio == 0 ? recv_timeout_cb : NULL);
2033 
2034 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2035     if (opt.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
2036         if ((ret = mbedtls_ssl_set_cid(&ssl, opt.cid_enabled,
2037                                        cid, cid_len)) != 0) {
2038             mbedtls_printf(" failed\n  ! mbedtls_ssl_set_cid returned %d\n\n",
2039                            ret);
2040             goto exit;
2041         }
2042     }
2043 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2044 
2045 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2046     if (opt.dtls_mtu != DFL_DTLS_MTU) {
2047         mbedtls_ssl_set_mtu(&ssl, opt.dtls_mtu);
2048     }
2049 #endif
2050 
2051 #if defined(MBEDTLS_TIMING_C)
2052     mbedtls_ssl_set_timer_cb(&ssl, &timer, mbedtls_timing_set_delay,
2053                              mbedtls_timing_get_delay);
2054 #endif
2055 
2056 #if defined(MBEDTLS_ECP_RESTARTABLE)
2057     if (opt.ec_max_ops != DFL_EC_MAX_OPS) {
2058         mbedtls_ecp_set_max_ops(opt.ec_max_ops);
2059     }
2060 #endif
2061 
2062 #if defined(MBEDTLS_SSL_DTLS_SRTP)
2063     if (opt.use_srtp != 0 && strlen(opt.mki) != 0) {
2064         if (mbedtls_test_unhexify(mki, sizeof(mki),
2065                                   opt.mki, &mki_len) != 0) {
2066             mbedtls_printf("mki value not valid hex\n");
2067             goto exit;
2068         }
2069 
2070         mbedtls_ssl_conf_srtp_mki_value_supported(&conf, MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED);
2071         if ((ret = mbedtls_ssl_dtls_srtp_set_mki_value(&ssl, mki,
2072                                                        (uint16_t) strlen(opt.mki) / 2)) != 0) {
2073             mbedtls_printf(" failed\n  ! mbedtls_ssl_dtls_srtp_set_mki_value returned %d\n\n", ret);
2074             goto exit;
2075         }
2076     }
2077 #endif
2078 
2079     mbedtls_printf(" ok\n");
2080 
2081     /*
2082      * 3. Start the connection
2083      */
2084     if (opt.server_addr == NULL) {
2085         opt.server_addr = opt.server_name;
2086     }
2087 
2088     mbedtls_printf("  . Connecting to %s/%s/%s...",
2089                    opt.transport == MBEDTLS_SSL_TRANSPORT_STREAM ? "tcp" : "udp",
2090                    opt.server_addr, opt.server_port);
2091     fflush(stdout);
2092 
2093     if ((ret = mbedtls_net_connect(&server_fd,
2094                                    opt.server_addr, opt.server_port,
2095                                    opt.transport == MBEDTLS_SSL_TRANSPORT_STREAM ?
2096                                    MBEDTLS_NET_PROTO_TCP : MBEDTLS_NET_PROTO_UDP)) != 0) {
2097         mbedtls_printf(" failed\n  ! mbedtls_net_connect returned -0x%x\n\n",
2098                        (unsigned int) -ret);
2099         goto exit;
2100     }
2101 
2102     if (opt.nbio > 0) {
2103         ret = mbedtls_net_set_nonblock(&server_fd);
2104     } else {
2105         ret = mbedtls_net_set_block(&server_fd);
2106     }
2107     if (ret != 0) {
2108         mbedtls_printf(" failed\n  ! net_set_(non)block() returned -0x%x\n\n",
2109                        (unsigned int) -ret);
2110         goto exit;
2111     }
2112 
2113     mbedtls_printf(" ok\n");
2114 
2115     /*
2116      * 4. Handshake
2117      */
2118     mbedtls_printf("  . Performing the SSL/TLS handshake...");
2119     fflush(stdout);
2120 
2121     while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
2122         if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
2123             ret != MBEDTLS_ERR_SSL_WANT_WRITE &&
2124             ret != MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
2125             mbedtls_printf(" failed\n  ! mbedtls_ssl_handshake returned -0x%x\n",
2126                            (unsigned int) -ret);
2127             if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
2128                 mbedtls_printf(
2129                     "    Unable to verify the server's certificate. "
2130                     "Either it is invalid,\n"
2131                     "    or you didn't set ca_file or ca_path "
2132                     "to an appropriate value.\n"
2133                     "    Alternatively, you may want to use "
2134                     "auth_mode=optional for testing purposes if "
2135                     "not using TLS 1.3.\n"
2136                     "    For TLS 1.3 server, try `ca_path=/etc/ssl/certs/`"
2137                     "or other folder that has root certificates\n");
2138             }
2139             mbedtls_printf("\n");
2140             goto exit;
2141         }
2142 
2143 #if defined(MBEDTLS_ECP_RESTARTABLE)
2144         if (ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
2145             continue;
2146         }
2147 #endif
2148 
2149         /* For event-driven IO, wait for socket to become available */
2150         if (opt.event == 1 /* level triggered IO */) {
2151 #if defined(MBEDTLS_TIMING_C)
2152             ret = idle(&server_fd, &timer, ret);
2153 #else
2154             ret = idle(&server_fd, ret);
2155 #endif
2156             if (ret != 0) {
2157                 goto exit;
2158             }
2159         }
2160     }
2161 
2162     {
2163         int suite_id = mbedtls_ssl_get_ciphersuite_id_from_ssl(&ssl);
2164         const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
2165         ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(suite_id);
2166 
2167         mbedtls_printf(" ok\n    [ Protocol is %s ]\n"
2168                        "    [ Ciphersuite is %s ]\n"
2169                        "    [ Key size is %u ]\n",
2170                        mbedtls_ssl_get_version(&ssl),
2171                        mbedtls_ssl_ciphersuite_get_name(ciphersuite_info),
2172                        (unsigned int)
2173                        mbedtls_ssl_ciphersuite_get_cipher_key_bitlen(ciphersuite_info));
2174     }
2175 
2176     if ((ret = mbedtls_ssl_get_record_expansion(&ssl)) >= 0) {
2177         mbedtls_printf("    [ Record expansion is %d ]\n", ret);
2178     } else {
2179         mbedtls_printf("    [ Record expansion is unknown ]\n");
2180     }
2181 
2182 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
2183     mbedtls_printf("    [ Maximum incoming record payload length is %u ]\n",
2184                    (unsigned int) mbedtls_ssl_get_max_in_record_payload(&ssl));
2185     mbedtls_printf("    [ Maximum outgoing record payload length is %u ]\n",
2186                    (unsigned int) mbedtls_ssl_get_max_out_record_payload(&ssl));
2187 #endif
2188 
2189 #if defined(MBEDTLS_SSL_ALPN)
2190     if (opt.alpn_string != NULL) {
2191         const char *alp = mbedtls_ssl_get_alpn_protocol(&ssl);
2192         mbedtls_printf("    [ Application Layer Protocol is %s ]\n",
2193                        alp ? alp : "(none)");
2194     }
2195 #endif
2196 
2197     if (opt.eap_tls != 0) {
2198         size_t j = 0;
2199 
2200         if ((ret = mbedtls_ssl_tls_prf(eap_tls_keying.tls_prf_type,
2201                                        eap_tls_keying.master_secret,
2202                                        sizeof(eap_tls_keying.master_secret),
2203                                        eap_tls_label,
2204                                        eap_tls_keying.randbytes,
2205                                        sizeof(eap_tls_keying.randbytes),
2206                                        eap_tls_keymaterial,
2207                                        sizeof(eap_tls_keymaterial)))
2208             != 0) {
2209             mbedtls_printf(" failed\n  ! mbedtls_ssl_tls_prf returned -0x%x\n\n",
2210                            (unsigned int) -ret);
2211             goto exit;
2212         }
2213 
2214         mbedtls_printf("    EAP-TLS key material is:");
2215         for (j = 0; j < sizeof(eap_tls_keymaterial); j++) {
2216             if (j % 8 == 0) {
2217                 mbedtls_printf("\n    ");
2218             }
2219             mbedtls_printf("%02x ", eap_tls_keymaterial[j]);
2220         }
2221         mbedtls_printf("\n");
2222 
2223         if ((ret = mbedtls_ssl_tls_prf(eap_tls_keying.tls_prf_type, NULL, 0,
2224                                        eap_tls_label,
2225                                        eap_tls_keying.randbytes,
2226                                        sizeof(eap_tls_keying.randbytes),
2227                                        eap_tls_iv,
2228                                        sizeof(eap_tls_iv))) != 0) {
2229             mbedtls_printf(" failed\n  ! mbedtls_ssl_tls_prf returned -0x%x\n\n",
2230                            (unsigned int) -ret);
2231             goto exit;
2232         }
2233 
2234         mbedtls_printf("    EAP-TLS IV is:");
2235         for (j = 0; j < sizeof(eap_tls_iv); j++) {
2236             if (j % 8 == 0) {
2237                 mbedtls_printf("\n    ");
2238             }
2239             mbedtls_printf("%02x ", eap_tls_iv[j]);
2240         }
2241         mbedtls_printf("\n");
2242     }
2243 
2244 #if defined(MBEDTLS_SSL_DTLS_SRTP)
2245     else if (opt.use_srtp != 0) {
2246         size_t j = 0;
2247         mbedtls_dtls_srtp_info dtls_srtp_negotiation_result;
2248         mbedtls_ssl_get_dtls_srtp_negotiation_result(&ssl, &dtls_srtp_negotiation_result);
2249 
2250         if (dtls_srtp_negotiation_result.chosen_dtls_srtp_profile
2251             == MBEDTLS_TLS_SRTP_UNSET) {
2252             mbedtls_printf("    Unable to negotiate "
2253                            "the use of DTLS-SRTP\n");
2254         } else {
2255             if ((ret = mbedtls_ssl_tls_prf(dtls_srtp_keying.tls_prf_type,
2256                                            dtls_srtp_keying.master_secret,
2257                                            sizeof(dtls_srtp_keying.master_secret),
2258                                            dtls_srtp_label,
2259                                            dtls_srtp_keying.randbytes,
2260                                            sizeof(dtls_srtp_keying.randbytes),
2261                                            dtls_srtp_key_material,
2262                                            sizeof(dtls_srtp_key_material)))
2263                 != 0) {
2264                 mbedtls_printf(" failed\n  ! mbedtls_ssl_tls_prf returned -0x%x\n\n",
2265                                (unsigned int) -ret);
2266                 goto exit;
2267             }
2268 
2269             mbedtls_printf("    DTLS-SRTP key material is:");
2270             for (j = 0; j < sizeof(dtls_srtp_key_material); j++) {
2271                 if (j % 8 == 0) {
2272                     mbedtls_printf("\n    ");
2273                 }
2274                 mbedtls_printf("%02x ", dtls_srtp_key_material[j]);
2275             }
2276             mbedtls_printf("\n");
2277 
2278             /* produce a less readable output used to perform automatic checks
2279              * - compare client and server output
2280              * - interop test with openssl which client produces this kind of output
2281              */
2282             mbedtls_printf("    Keying material: ");
2283             for (j = 0; j < sizeof(dtls_srtp_key_material); j++) {
2284                 mbedtls_printf("%02X", dtls_srtp_key_material[j]);
2285             }
2286             mbedtls_printf("\n");
2287 
2288             if (dtls_srtp_negotiation_result.mki_len > 0) {
2289                 mbedtls_printf("    DTLS-SRTP mki value: ");
2290                 for (j = 0; j < dtls_srtp_negotiation_result.mki_len; j++) {
2291                     mbedtls_printf("%02X", dtls_srtp_negotiation_result.mki_value[j]);
2292                 }
2293             } else {
2294                 mbedtls_printf("    DTLS-SRTP no mki value negotiated");
2295             }
2296             mbedtls_printf("\n");
2297         }
2298     }
2299 #endif /* MBEDTLS_SSL_DTLS_SRTP */
2300     if (opt.reconnect != 0 && ssl.tls_version != MBEDTLS_SSL_VERSION_TLS1_3) {
2301         mbedtls_printf("  . Saving session for reuse...");
2302         fflush(stdout);
2303 
2304         if (opt.reco_mode == 1) {
2305             if ((ret = ssl_save_session_serialize(&ssl,
2306                                                   &session_data, &session_data_len)) != 0) {
2307                 mbedtls_printf(" failed\n  ! ssl_save_session_serialize returned -0x%04x\n\n",
2308                                (unsigned int) -ret);
2309                 goto exit;
2310             }
2311 
2312         } else {
2313             if ((ret = mbedtls_ssl_get_session(&ssl, &saved_session)) != 0) {
2314                 mbedtls_printf(" failed\n  ! mbedtls_ssl_get_session returned -0x%x\n\n",
2315                                (unsigned int) -ret);
2316                 goto exit;
2317             }
2318         }
2319 
2320         mbedtls_printf(" ok\n");
2321 
2322         if (opt.reco_mode == 1) {
2323             mbedtls_printf("    [ Saved %u bytes of session data]\n",
2324                            (unsigned) session_data_len);
2325         }
2326     }
2327 
2328 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2329     /*
2330      * 5. Verify the server certificate
2331      */
2332     mbedtls_printf("  . Verifying peer X.509 certificate...");
2333 
2334     if ((flags = mbedtls_ssl_get_verify_result(&ssl)) != 0) {
2335         char vrfy_buf[512];
2336         mbedtls_printf(" failed\n");
2337 
2338         x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf),
2339                              "  ! ", flags);
2340 
2341         mbedtls_printf("%s\n", vrfy_buf);
2342     } else {
2343         mbedtls_printf(" ok\n");
2344     }
2345 
2346 #if !defined(MBEDTLS_X509_REMOVE_INFO)
2347     mbedtls_printf("  . Peer certificate information    ...\n");
2348     mbedtls_printf("%s\n", peer_crt_info);
2349 #endif /* !MBEDTLS_X509_REMOVE_INFO */
2350 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2351 
2352 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2353     ret = report_cid_usage(&ssl, "initial handshake");
2354     if (ret != 0) {
2355         goto exit;
2356     }
2357 
2358     if (opt.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
2359         if ((ret = mbedtls_ssl_set_cid(&ssl, opt.cid_enabled_renego,
2360                                        cid_renego,
2361                                        cid_renego_len)) != 0) {
2362             mbedtls_printf(" failed\n  ! mbedtls_ssl_set_cid returned %d\n\n",
2363                            ret);
2364             goto exit;
2365         }
2366     }
2367 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2368 
2369 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2370     if (opt.renegotiate) {
2371         /*
2372          * Perform renegotiation (this must be done when the server is waiting
2373          * for input from our side).
2374          */
2375         mbedtls_printf("  . Performing renegotiation...");
2376         fflush(stdout);
2377         while ((ret = mbedtls_ssl_renegotiate(&ssl)) != 0) {
2378             if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
2379                 ret != MBEDTLS_ERR_SSL_WANT_WRITE &&
2380                 ret != MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
2381                 mbedtls_printf(" failed\n  ! mbedtls_ssl_renegotiate returned %d\n\n",
2382                                ret);
2383                 goto exit;
2384             }
2385 
2386 #if defined(MBEDTLS_ECP_RESTARTABLE)
2387             if (ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
2388                 continue;
2389             }
2390 #endif
2391 
2392             /* For event-driven IO, wait for socket to become available */
2393             if (opt.event == 1 /* level triggered IO */) {
2394 #if defined(MBEDTLS_TIMING_C)
2395                 idle(&server_fd, &timer, ret);
2396 #else
2397                 idle(&server_fd, ret);
2398 #endif
2399             }
2400 
2401         }
2402         mbedtls_printf(" ok\n");
2403     }
2404 #endif /* MBEDTLS_SSL_RENEGOTIATION */
2405 
2406 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2407     ret = report_cid_usage(&ssl, "after renegotiation");
2408     if (ret != 0) {
2409         goto exit;
2410     }
2411 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2412 
2413     /*
2414      * 6. Write the GET request
2415      */
2416     retry_left = opt.max_resend;
2417 send_request:
2418     mbedtls_printf("  > Write to server:");
2419     fflush(stdout);
2420 
2421     len = mbedtls_snprintf((char *) buf, sizeof(buf) - 1, GET_REQUEST,
2422                            opt.request_page);
2423     tail_len = (int) strlen(GET_REQUEST_END);
2424 
2425     /* Add padding to GET request to reach opt.request_size in length */
2426     if (opt.request_size != DFL_REQUEST_SIZE &&
2427         len + tail_len < opt.request_size) {
2428         memset(buf + len, 'A', opt.request_size - len - tail_len);
2429         len += opt.request_size - len - tail_len;
2430     }
2431 
2432     strncpy((char *) buf + len, GET_REQUEST_END, sizeof(buf) - len - 1);
2433     len += tail_len;
2434 
2435     /* Truncate if request size is smaller than the "natural" size */
2436     if (opt.request_size != DFL_REQUEST_SIZE &&
2437         len > opt.request_size) {
2438         len = opt.request_size;
2439 
2440         /* Still end with \r\n unless that's really not possible */
2441         if (len >= 2) {
2442             buf[len - 2] = '\r';
2443         }
2444         if (len >= 1) {
2445             buf[len - 1] = '\n';
2446         }
2447     }
2448 
2449     if (opt.transport == MBEDTLS_SSL_TRANSPORT_STREAM) {
2450         written = 0;
2451         frags = 0;
2452 
2453         do {
2454             while ((ret = mbedtls_ssl_write(&ssl, buf + written,
2455                                             len - written)) < 0) {
2456                 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
2457                     ret != MBEDTLS_ERR_SSL_WANT_WRITE &&
2458                     ret != MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
2459                     mbedtls_printf(" failed\n  ! mbedtls_ssl_write returned -0x%x\n\n",
2460                                    (unsigned int) -ret);
2461                     goto exit;
2462                 }
2463 
2464                 /* For event-driven IO, wait for socket to become available */
2465                 if (opt.event == 1 /* level triggered IO */) {
2466 #if defined(MBEDTLS_TIMING_C)
2467                     idle(&server_fd, &timer, ret);
2468 #else
2469                     idle(&server_fd, ret);
2470 #endif
2471                 }
2472             }
2473 
2474             frags++;
2475             written += ret;
2476         } while (written < len);
2477     } else { /* Not stream, so datagram */
2478         while (1) {
2479             ret = mbedtls_ssl_write(&ssl, buf, len);
2480 
2481 #if defined(MBEDTLS_ECP_RESTARTABLE)
2482             if (ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
2483                 continue;
2484             }
2485 #endif
2486 
2487             if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
2488                 ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
2489                 break;
2490             }
2491 
2492             /* For event-driven IO, wait for socket to become available */
2493             if (opt.event == 1 /* level triggered IO */) {
2494 #if defined(MBEDTLS_TIMING_C)
2495                 idle(&server_fd, &timer, ret);
2496 #else
2497                 idle(&server_fd, ret);
2498 #endif
2499             }
2500         }
2501 
2502         if (ret < 0) {
2503             mbedtls_printf(" failed\n  ! mbedtls_ssl_write returned %d\n\n",
2504                            ret);
2505             goto exit;
2506         }
2507 
2508         frags = 1;
2509         written = ret;
2510 
2511         if (written < len) {
2512             mbedtls_printf(" warning\n  ! request didn't fit into single datagram and "
2513                            "was truncated to size %u", (unsigned) written);
2514         }
2515     }
2516 
2517     buf[written] = '\0';
2518     mbedtls_printf(" %d bytes written in %d fragments\n\n%s\n",
2519                    written, frags, (char *) buf);
2520 
2521     /* Send a non-empty request if request_size == 0 */
2522     if (len == 0) {
2523         opt.request_size = DFL_REQUEST_SIZE;
2524         goto send_request;
2525     }
2526 
2527     /*
2528      * 7. Read the HTTP response
2529      */
2530 
2531     /*
2532      * TLS and DTLS need different reading styles (stream vs datagram)
2533      */
2534     if (opt.transport == MBEDTLS_SSL_TRANSPORT_STREAM) {
2535 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_SESSION_TICKETS)
2536         int ticket_id = 0;
2537 #endif
2538         do {
2539             len = sizeof(buf) - 1;
2540             memset(buf, 0, sizeof(buf));
2541             ret = mbedtls_ssl_read(&ssl, buf, len);
2542 
2543 #if defined(MBEDTLS_ECP_RESTARTABLE)
2544             if (ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
2545                 continue;
2546             }
2547 #endif
2548 
2549             if (ret == MBEDTLS_ERR_SSL_WANT_READ ||
2550                 ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
2551                 /* For event-driven IO, wait for socket to become available */
2552                 if (opt.event == 1 /* level triggered IO */) {
2553 #if defined(MBEDTLS_TIMING_C)
2554                     idle(&server_fd, &timer, ret);
2555 #else
2556                     idle(&server_fd, ret);
2557 #endif
2558                 }
2559                 continue;
2560             }
2561 
2562             if (ret <= 0) {
2563                 switch (ret) {
2564                     case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
2565                         mbedtls_printf(" connection was closed gracefully\n");
2566                         ret = 0;
2567                         goto close_notify;
2568 
2569                     case 0:
2570                     case MBEDTLS_ERR_NET_CONN_RESET:
2571                         mbedtls_printf(" connection was reset by peer\n");
2572                         ret = 0;
2573                         goto reconnect;
2574 
2575 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2576 
2577 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
2578                     case MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET:
2579                         /* We were waiting for application data but got
2580                          * a NewSessionTicket instead. */
2581                         mbedtls_printf(" got new session ticket ( %d ).\n",
2582                                        ticket_id++);
2583                         if (opt.reconnect != 0) {
2584                             mbedtls_printf("  . Saving session for reuse...");
2585                             fflush(stdout);
2586 
2587                             if (opt.reco_mode == 1) {
2588                                 if ((ret = ssl_save_session_serialize(&ssl,
2589                                                                       &session_data,
2590                                                                       &session_data_len)) != 0) {
2591                                     mbedtls_printf(
2592                                         " failed\n  ! ssl_save_session_serialize returned -0x%04x\n\n",
2593                                         (unsigned int) -ret);
2594                                     goto exit;
2595                                 }
2596                             } else {
2597                                 if ((ret = mbedtls_ssl_get_session(&ssl, &saved_session)) != 0) {
2598                                     mbedtls_printf(
2599                                         " failed\n  ! mbedtls_ssl_get_session returned -0x%x\n\n",
2600                                         (unsigned int) -ret);
2601                                     goto exit;
2602                                 }
2603                             }
2604 
2605                             mbedtls_printf(" ok\n");
2606 
2607                             if (opt.reco_mode == 1) {
2608                                 mbedtls_printf("    [ Saved %u bytes of session data]\n",
2609                                                (unsigned) session_data_len);
2610                             }
2611                         }
2612                         continue;
2613 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
2614 
2615 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
2616 
2617                     default:
2618                         mbedtls_printf(" mbedtls_ssl_read returned -0x%x\n",
2619                                        (unsigned int) -ret);
2620                         goto exit;
2621                 }
2622             }
2623 
2624             len = ret;
2625             buf[len] = '\0';
2626             mbedtls_printf("  < Read from server: %d bytes read\n\n%s", len, (char *) buf);
2627             fflush(stdout);
2628             /* End of message should be detected according to the syntax of the
2629              * application protocol (eg HTTP), just use a dummy test here. */
2630             if (ret > 0 && buf[len-1] == '\n') {
2631                 ret = 0;
2632                 break;
2633             }
2634         } while (1);
2635     } else { /* Not stream, so datagram */
2636         len = sizeof(buf) - 1;
2637         memset(buf, 0, sizeof(buf));
2638 
2639         while (1) {
2640             ret = mbedtls_ssl_read(&ssl, buf, len);
2641 
2642 #if defined(MBEDTLS_ECP_RESTARTABLE)
2643             if (ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
2644                 continue;
2645             }
2646 #endif
2647 
2648             if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
2649                 ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
2650                 break;
2651             }
2652 
2653             /* For event-driven IO, wait for socket to become available */
2654             if (opt.event == 1 /* level triggered IO */) {
2655 #if defined(MBEDTLS_TIMING_C)
2656                 idle(&server_fd, &timer, ret);
2657 #else
2658                 idle(&server_fd, ret);
2659 #endif
2660             }
2661         }
2662 
2663         if (ret <= 0) {
2664             switch (ret) {
2665                 case MBEDTLS_ERR_SSL_TIMEOUT:
2666                     mbedtls_printf(" timeout\n");
2667                     if (retry_left-- > 0) {
2668                         goto send_request;
2669                     }
2670                     goto exit;
2671 
2672                 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
2673                     mbedtls_printf(" connection was closed gracefully\n");
2674                     ret = 0;
2675                     goto close_notify;
2676 
2677                 default:
2678                     mbedtls_printf(" mbedtls_ssl_read returned -0x%x\n", (unsigned int) -ret);
2679                     goto exit;
2680             }
2681         }
2682 
2683         len = ret;
2684         buf[len] = '\0';
2685         mbedtls_printf("  < Read from server: %d bytes read\n\n%s", len, (char *) buf);
2686         ret = 0;
2687     }
2688 
2689     /*
2690      * 7b. Simulate hard reset and reconnect from same port?
2691      */
2692     if (opt.reconnect_hard != 0) {
2693         opt.reconnect_hard = 0;
2694 
2695         mbedtls_printf("  . Restarting connection from same port...");
2696         fflush(stdout);
2697 
2698 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2699         memset(peer_crt_info, 0, sizeof(peer_crt_info));
2700 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2701 
2702         if ((ret = mbedtls_ssl_session_reset(&ssl)) != 0) {
2703             mbedtls_printf(" failed\n  ! mbedtls_ssl_session_reset returned -0x%x\n\n",
2704                            (unsigned int) -ret);
2705             goto exit;
2706         }
2707 
2708         while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
2709             if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
2710                 ret != MBEDTLS_ERR_SSL_WANT_WRITE &&
2711                 ret != MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
2712                 mbedtls_printf(" failed\n  ! mbedtls_ssl_handshake returned -0x%x\n\n",
2713                                (unsigned int) -ret);
2714                 goto exit;
2715             }
2716 
2717             /* For event-driven IO, wait for socket to become available */
2718             if (opt.event == 1 /* level triggered IO */) {
2719 #if defined(MBEDTLS_TIMING_C)
2720                 idle(&server_fd, &timer, ret);
2721 #else
2722                 idle(&server_fd, ret);
2723 #endif
2724             }
2725         }
2726 
2727         mbedtls_printf(" ok\n");
2728 
2729         goto send_request;
2730     }
2731 
2732     /*
2733      * 7c. Simulate serialize/deserialize and go back to data exchange
2734      */
2735 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
2736     if (opt.serialize != 0) {
2737         size_t buf_len;
2738 
2739         mbedtls_printf("  . Serializing live connection...");
2740 
2741         ret = mbedtls_ssl_context_save(&ssl, NULL, 0, &buf_len);
2742         if (ret != MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL) {
2743             mbedtls_printf(" failed\n  ! mbedtls_ssl_context_save returned "
2744                            "-0x%x\n\n", (unsigned int) -ret);
2745 
2746             goto exit;
2747         }
2748 
2749         if ((context_buf = mbedtls_calloc(1, buf_len)) == NULL) {
2750             mbedtls_printf(" failed\n  ! Couldn't allocate buffer for "
2751                            "serialized context");
2752 
2753             goto exit;
2754         }
2755         context_buf_len = buf_len;
2756 
2757         if ((ret = mbedtls_ssl_context_save(&ssl, context_buf,
2758                                             buf_len, &buf_len)) != 0) {
2759             mbedtls_printf(" failed\n  ! mbedtls_ssl_context_save returned "
2760                            "-0x%x\n\n", (unsigned int) -ret);
2761 
2762             goto exit;
2763         }
2764 
2765         mbedtls_printf(" ok\n");
2766 
2767         /* Save serialized context to the 'opt.context_file' as a base64 code */
2768         if (0 < strlen(opt.context_file)) {
2769             FILE *b64_file;
2770             uint8_t *b64_buf;
2771             size_t b64_len;
2772 
2773             mbedtls_printf("  . Save serialized context to a file... ");
2774 
2775             mbedtls_base64_encode(NULL, 0, &b64_len, context_buf, buf_len);
2776 
2777             if ((b64_buf = mbedtls_calloc(1, b64_len)) == NULL) {
2778                 mbedtls_printf("failed\n  ! Couldn't allocate buffer for "
2779                                "the base64 code\n");
2780                 goto exit;
2781             }
2782 
2783             if ((ret = mbedtls_base64_encode(b64_buf, b64_len, &b64_len,
2784                                              context_buf, buf_len)) != 0) {
2785                 mbedtls_printf("failed\n  ! mbedtls_base64_encode returned "
2786                                "-0x%x\n", (unsigned int) -ret);
2787                 mbedtls_free(b64_buf);
2788                 goto exit;
2789             }
2790 
2791             if ((b64_file = fopen(opt.context_file, "w")) == NULL) {
2792                 mbedtls_printf("failed\n  ! Cannot open '%s' for writing.\n",
2793                                opt.context_file);
2794                 mbedtls_free(b64_buf);
2795                 goto exit;
2796             }
2797 
2798             if (b64_len != fwrite(b64_buf, 1, b64_len, b64_file)) {
2799                 mbedtls_printf("failed\n  ! fwrite(%ld bytes) failed\n",
2800                                (long) b64_len);
2801                 mbedtls_free(b64_buf);
2802                 fclose(b64_file);
2803                 goto exit;
2804             }
2805 
2806             mbedtls_free(b64_buf);
2807             fclose(b64_file);
2808 
2809             mbedtls_printf("ok\n");
2810         }
2811 
2812         if (opt.serialize == 1) {
2813             /* nothing to do here, done by context_save() already */
2814             mbedtls_printf("  . Context has been reset... ok\n");
2815         }
2816 
2817         if (opt.serialize == 2) {
2818             mbedtls_printf("  . Freeing and reinitializing context...");
2819 
2820             mbedtls_ssl_free(&ssl);
2821 
2822             mbedtls_ssl_init(&ssl);
2823 
2824             if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
2825                 mbedtls_printf(" failed\n  ! mbedtls_ssl_setup returned "
2826                                "-0x%x\n\n", (unsigned int) -ret);
2827                 goto exit;
2828             }
2829 
2830             if (opt.nbio == 2) {
2831                 mbedtls_ssl_set_bio(&ssl, &server_fd, delayed_send,
2832                                     delayed_recv, NULL);
2833             } else {
2834                 mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send,
2835                                     mbedtls_net_recv,
2836                                     opt.nbio == 0 ? mbedtls_net_recv_timeout : NULL);
2837             }
2838 
2839 #if defined(MBEDTLS_TIMING_C)
2840             mbedtls_ssl_set_timer_cb(&ssl, &timer,
2841                                      mbedtls_timing_set_delay,
2842                                      mbedtls_timing_get_delay);
2843 #endif /* MBEDTLS_TIMING_C */
2844 
2845             mbedtls_printf(" ok\n");
2846         }
2847 
2848         mbedtls_printf("  . Deserializing connection...");
2849 
2850         if ((ret = mbedtls_ssl_context_load(&ssl, context_buf,
2851                                             buf_len)) != 0) {
2852             mbedtls_printf("failed\n  ! mbedtls_ssl_context_load returned "
2853                            "-0x%x\n\n", (unsigned int) -ret);
2854 
2855             goto exit;
2856         }
2857 
2858         mbedtls_free(context_buf);
2859         context_buf = NULL;
2860         context_buf_len = 0;
2861 
2862         mbedtls_printf(" ok\n");
2863     }
2864 #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */
2865 
2866     /*
2867      * 7d. Continue doing data exchanges?
2868      */
2869     if (--opt.exchanges > 0) {
2870         goto send_request;
2871     }
2872 
2873     /*
2874      * 8. Done, cleanly close the connection
2875      */
2876 close_notify:
2877     mbedtls_printf("  . Closing the connection...");
2878     fflush(stdout);
2879 
2880     /*
2881      * Most of the time sending a close_notify before closing is the right
2882      * thing to do. However, when the server already knows how many messages
2883      * are expected and closes the connection by itself, this alert becomes
2884      * redundant. Sometimes with DTLS this redundancy becomes a problem by
2885      * leading to a race condition where the server might close the connection
2886      * before seeing the alert, and since UDP is connection-less when the
2887      * alert arrives it will be seen as a new connection, which will fail as
2888      * the alert is clearly not a valid ClientHello. This may cause spurious
2889      * failures in tests that use DTLS and resumption with ssl_server2 in
2890      * ssl-opt.sh, avoided by enabling skip_close_notify client-side.
2891      */
2892     if (opt.skip_close_notify == 0) {
2893         /* No error checking, the connection might be closed already */
2894         do {
2895             ret = mbedtls_ssl_close_notify(&ssl);
2896         } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
2897         ret = 0;
2898     }
2899 
2900     mbedtls_printf(" done\n");
2901 
2902     /*
2903      * 9. Reconnect?
2904      */
2905 reconnect:
2906     if (opt.reconnect != 0) {
2907         --opt.reconnect;
2908 
2909         mbedtls_net_free(&server_fd);
2910 
2911 #if defined(MBEDTLS_TIMING_C)
2912         if (opt.reco_delay > 0) {
2913             mbedtls_net_usleep(1000 * opt.reco_delay);
2914         }
2915 #endif
2916 
2917         mbedtls_printf("  . Reconnecting with saved session...");
2918 
2919 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
2920         memset(peer_crt_info, 0, sizeof(peer_crt_info));
2921 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
2922 
2923         if ((ret = mbedtls_ssl_session_reset(&ssl)) != 0) {
2924             mbedtls_printf(" failed\n  ! mbedtls_ssl_session_reset returned -0x%x\n\n",
2925                            (unsigned int) -ret);
2926             goto exit;
2927         }
2928 
2929         if (opt.reco_mode == 1) {
2930             if ((ret = mbedtls_ssl_session_load(&saved_session,
2931                                                 session_data,
2932                                                 session_data_len)) != 0) {
2933                 mbedtls_printf(" failed\n  ! mbedtls_ssl_session_load returned -0x%x\n\n",
2934                                (unsigned int) -ret);
2935                 goto exit;
2936             }
2937         }
2938 
2939         if ((ret = mbedtls_ssl_set_session(&ssl, &saved_session)) != 0) {
2940             mbedtls_printf(" failed\n  ! mbedtls_ssl_set_session returned -0x%x\n\n",
2941                            (unsigned int) -ret);
2942             goto exit;
2943         }
2944 
2945 #if defined(MBEDTLS_X509_CRT_PARSE_C)
2946         if (opt.reco_server_name != NULL &&
2947             (ret = mbedtls_ssl_set_hostname(&ssl,
2948                                             opt.reco_server_name)) != 0) {
2949             mbedtls_printf(" failed\n  ! mbedtls_ssl_set_hostname returned %d\n\n",
2950                            ret);
2951             goto exit;
2952         }
2953 #endif
2954 
2955         if ((ret = mbedtls_net_connect(&server_fd,
2956                                        opt.server_addr, opt.server_port,
2957                                        opt.transport == MBEDTLS_SSL_TRANSPORT_STREAM ?
2958                                        MBEDTLS_NET_PROTO_TCP : MBEDTLS_NET_PROTO_UDP)) != 0) {
2959             mbedtls_printf(" failed\n  ! mbedtls_net_connect returned -0x%x\n\n",
2960                            (unsigned int) -ret);
2961             goto exit;
2962         }
2963 
2964         if (opt.nbio > 0) {
2965             ret = mbedtls_net_set_nonblock(&server_fd);
2966         } else {
2967             ret = mbedtls_net_set_block(&server_fd);
2968         }
2969         if (ret != 0) {
2970             mbedtls_printf(" failed\n  ! net_set_(non)block() returned -0x%x\n\n",
2971                            (unsigned int) -ret);
2972             goto exit;
2973         }
2974 
2975         while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
2976             if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
2977                 ret != MBEDTLS_ERR_SSL_WANT_WRITE &&
2978                 ret != MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
2979                 mbedtls_printf(" failed\n  ! mbedtls_ssl_handshake returned -0x%x\n\n",
2980                                (unsigned int) -ret);
2981                 goto exit;
2982             }
2983         }
2984 
2985         mbedtls_printf(" ok\n");
2986 
2987         goto send_request;
2988     }
2989 
2990     /*
2991      * Cleanup and exit
2992      */
2993 exit:
2994 #ifdef MBEDTLS_ERROR_C
2995     if (ret != 0) {
2996         char error_buf[100];
2997         mbedtls_strerror(ret, error_buf, 100);
2998         mbedtls_printf("Last error was: -0x%X - %s\n\n", (unsigned int) -ret, error_buf);
2999     }
3000 #endif
3001 
3002     mbedtls_net_free(&server_fd);
3003 
3004     mbedtls_ssl_free(&ssl);
3005     mbedtls_ssl_config_free(&conf);
3006     mbedtls_ssl_session_free(&saved_session);
3007 
3008     if (session_data != NULL) {
3009         mbedtls_platform_zeroize(session_data, session_data_len);
3010     }
3011     mbedtls_free(session_data);
3012 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
3013     if (context_buf != NULL) {
3014         mbedtls_platform_zeroize(context_buf, context_buf_len);
3015     }
3016     mbedtls_free(context_buf);
3017 #endif
3018 
3019 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
3020     mbedtls_x509_crt_free(&clicert);
3021     mbedtls_x509_crt_free(&cacert);
3022     mbedtls_pk_free(&pkey);
3023 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3024     psa_destroy_key(key_slot);
3025 #endif
3026 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
3027 
3028 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED) && \
3029     defined(MBEDTLS_USE_PSA_CRYPTO)
3030     if (opt.psk_opaque != 0) {
3031         /* This is ok even if the slot hasn't been
3032          * initialized (we might have jumed here
3033          * immediately because of bad cmd line params,
3034          * for example). */
3035         status = psa_destroy_key(slot);
3036         if ((status != PSA_SUCCESS) &&
3037             (opt.query_config_mode == DFL_QUERY_CONFIG_MODE)) {
3038             mbedtls_printf("Failed to destroy key slot %u - error was %d",
3039                            (unsigned) MBEDTLS_SVC_KEY_ID_GET_KEY_ID(slot),
3040                            (int) status);
3041             if (ret == 0) {
3042                 ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
3043             }
3044         }
3045     }
3046 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED &&
3047           MBEDTLS_USE_PSA_CRYPTO */
3048 
3049 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \
3050     defined(MBEDTLS_USE_PSA_CRYPTO)
3051     /*
3052      * In case opaque keys it's the user responsibility to keep the key valid
3053      * for the duration of the handshake and destroy it at the end
3054      */
3055     if ((opt.ecjpake_pw_opaque != DFL_ECJPAKE_PW_OPAQUE)) {
3056         psa_key_attributes_t check_attributes = PSA_KEY_ATTRIBUTES_INIT;
3057 
3058         /* Verify that the key is still valid before destroying it */
3059         if (psa_get_key_attributes(ecjpake_pw_slot, &check_attributes) !=
3060             PSA_SUCCESS) {
3061             if (ret == 0) {
3062                 ret = 1;
3063             }
3064             mbedtls_printf("The EC J-PAKE password key has unexpectedly been already destroyed\n");
3065         } else {
3066             psa_destroy_key(ecjpake_pw_slot);
3067         }
3068     }
3069 #endif  /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED && MBEDTLS_USE_PSA_CRYPTO */
3070 
3071 #if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
3072     const char *message = mbedtls_test_helper_is_psa_leaking();
3073     if (message) {
3074         if (ret == 0) {
3075             ret = 1;
3076         }
3077         mbedtls_printf("PSA memory leak detected: %s\n",  message);
3078     }
3079 #endif /* MBEDTLS_USE_PSA_CRYPTO || MBEDTLS_SSL_PROTO_TLS1_3 */
3080 
3081     /* For builds with MBEDTLS_TEST_USE_PSA_CRYPTO_RNG psa crypto
3082      * resources are freed by rng_free(). */
3083 #if (defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)) && \
3084     !defined(MBEDTLS_TEST_USE_PSA_CRYPTO_RNG)
3085     mbedtls_psa_crypto_free();
3086 #endif
3087 
3088     rng_free(&rng);
3089 
3090 #if defined(MBEDTLS_TEST_HOOKS)
3091     if (test_hooks_failure_detected()) {
3092         if (ret == 0) {
3093             ret = 1;
3094         }
3095         mbedtls_printf("Test hooks detected errors.\n");
3096     }
3097     test_hooks_free();
3098 #endif /* MBEDTLS_TEST_HOOKS */
3099 
3100 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
3101 #if defined(MBEDTLS_MEMORY_DEBUG)
3102     mbedtls_memory_buffer_alloc_status();
3103 #endif
3104     mbedtls_memory_buffer_alloc_free();
3105 #endif  /* MBEDTLS_MEMORY_BUFFER_ALLOC_C */
3106 
3107     // Shell can not handle large exit numbers -> 1 for errors
3108     if (ret < 0) {
3109         ret = 1;
3110     }
3111 
3112     if (opt.query_config_mode == DFL_QUERY_CONFIG_MODE) {
3113         mbedtls_exit(ret);
3114     } else {
3115         mbedtls_exit(query_config_ret);
3116     }
3117 }
3118 #endif /* !MBEDTLS_SSL_TEST_IMPOSSIBLE && MBEDTLS_SSL_CLI_C */
3119