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