quickjs-tart

quickjs-based runtime for wallet-core logic
Log | Files | Refs | README | LICENSE

ssl_server2.c (167598B)


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