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