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