1 /**
2  * \file ssl.h
3  *
4  * \brief SSL/TLS functions.
5  */
6 /*
7  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
8  *  SPDX-License-Identifier: Apache-2.0
9  *
10  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
11  *  not use this file except in compliance with the License.
12  *  You may obtain a copy of the License at
13  *
14  *  http://www.apache.org/licenses/LICENSE-2.0
15  *
16  *  Unless required by applicable law or agreed to in writing, software
17  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
18  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  *  See the License for the specific language governing permissions and
20  *  limitations under the License.
21  *
22  *  This file is part of mbed TLS (https://tls.mbed.org)
23  */
24 #ifndef MBEDTLS_SSL_H
25 #define MBEDTLS_SSL_H
26 
27 #if !defined(MBEDTLS_CONFIG_FILE)
28 #include "config.h"
29 #else
30 #include MBEDTLS_CONFIG_FILE
31 #endif
32 
33 #include "bignum.h"
34 #include "ecp.h"
35 
36 #include "ssl_ciphersuites.h"
37 
38 #if defined(MBEDTLS_X509_CRT_PARSE_C)
39 #include "x509_crt.h"
40 #include "x509_crl.h"
41 #endif
42 
43 #if defined(MBEDTLS_DHM_C)
44 #include "dhm.h"
45 #endif
46 
47 #if defined(MBEDTLS_ECDH_C)
48 #include "ecdh.h"
49 #endif
50 
51 #if defined(MBEDTLS_ZLIB_SUPPORT)
52 
53 #if defined(MBEDTLS_DEPRECATED_WARNING)
54 #warning "Record compression support via MBEDTLS_ZLIB_SUPPORT is deprecated and will be removed in the next major revision of the library"
55 #endif
56 
57 #if defined(MBEDTLS_DEPRECATED_REMOVED)
58 #error "Record compression support via MBEDTLS_ZLIB_SUPPORT is deprecated and cannot be used if MBEDTLS_DEPRECATED_REMOVED is set"
59 #endif
60 
61 #include "zlib.h"
62 #endif
63 
64 #if defined(MBEDTLS_HAVE_TIME)
65 #include "platform_time.h"
66 #endif
67 
68 /*
69  * SSL Error codes
70  */
71 #define MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE               -0x7080  /**< The requested feature is not available. */
72 #define MBEDTLS_ERR_SSL_BAD_INPUT_DATA                    -0x7100  /**< Bad input parameters to function. */
73 #define MBEDTLS_ERR_SSL_INVALID_MAC                       -0x7180  /**< Verification of the message MAC failed. */
74 #define MBEDTLS_ERR_SSL_INVALID_RECORD                    -0x7200  /**< An invalid SSL record was received. */
75 #define MBEDTLS_ERR_SSL_CONN_EOF                          -0x7280  /**< The connection indicated an EOF. */
76 #define MBEDTLS_ERR_SSL_UNKNOWN_CIPHER                    -0x7300  /**< An unknown cipher was received. */
77 #define MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN                  -0x7380  /**< The server has no ciphersuites in common with the client. */
78 #define MBEDTLS_ERR_SSL_NO_RNG                            -0x7400  /**< No RNG was provided to the SSL module. */
79 #define MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE             -0x7480  /**< No client certification received from the client, but required by the authentication mode. */
80 #define MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE             -0x7500  /**< Our own certificate(s) is/are too large to send in an SSL message. */
81 #define MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED              -0x7580  /**< The own certificate is not set, but needed by the server. */
82 #define MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED              -0x7600  /**< The own private key or pre-shared key is not set, but needed. */
83 #define MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED                 -0x7680  /**< No CA Chain is set, but required to operate. */
84 #define MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE                -0x7700  /**< An unexpected message was received from our peer. */
85 #define MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE               -0x7780  /**< A fatal alert message was received from our peer. */
86 #define MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED                -0x7800  /**< Verification of our peer failed. */
87 #define MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY                 -0x7880  /**< The peer notified us that the connection is going to be closed. */
88 #define MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO               -0x7900  /**< Processing of the ClientHello handshake message failed. */
89 #define MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO               -0x7980  /**< Processing of the ServerHello handshake message failed. */
90 #define MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE                -0x7A00  /**< Processing of the Certificate handshake message failed. */
91 #define MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST        -0x7A80  /**< Processing of the CertificateRequest handshake message failed. */
92 #define MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE        -0x7B00  /**< Processing of the ServerKeyExchange handshake message failed. */
93 #define MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE          -0x7B80  /**< Processing of the ServerHelloDone handshake message failed. */
94 #define MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE        -0x7C00  /**< Processing of the ClientKeyExchange handshake message failed. */
95 #define MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP     -0x7C80  /**< Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public. */
96 #define MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS     -0x7D00  /**< Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret. */
97 #define MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY         -0x7D80  /**< Processing of the CertificateVerify handshake message failed. */
98 #define MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC         -0x7E00  /**< Processing of the ChangeCipherSpec handshake message failed. */
99 #define MBEDTLS_ERR_SSL_BAD_HS_FINISHED                   -0x7E80  /**< Processing of the Finished handshake message failed. */
100 #define MBEDTLS_ERR_SSL_ALLOC_FAILED                      -0x7F00  /**< Memory allocation failed */
101 #define MBEDTLS_ERR_SSL_HW_ACCEL_FAILED                   -0x7F80  /**< Hardware acceleration function returned with error */
102 #define MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH              -0x6F80  /**< Hardware acceleration function skipped / left alone data */
103 #define MBEDTLS_ERR_SSL_COMPRESSION_FAILED                -0x6F00  /**< Processing of the compression / decompression failed */
104 #define MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION           -0x6E80  /**< Handshake protocol not within min/max boundaries */
105 #define MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET         -0x6E00  /**< Processing of the NewSessionTicket handshake message failed. */
106 #define MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED            -0x6D80  /**< Session ticket has expired. */
107 #define MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH                  -0x6D00  /**< Public key type mismatch (eg, asked for RSA key exchange and presented EC key) */
108 #define MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY                  -0x6C80  /**< Unknown identity received (eg, PSK identity) */
109 #define MBEDTLS_ERR_SSL_INTERNAL_ERROR                    -0x6C00  /**< Internal error (eg, unexpected failure in lower-level module) */
110 #define MBEDTLS_ERR_SSL_COUNTER_WRAPPING                  -0x6B80  /**< A counter would wrap (eg, too many messages exchanged). */
111 #define MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO       -0x6B00  /**< Unexpected message at ServerHello in renegotiation. */
112 #define MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED             -0x6A80  /**< DTLS client must retry for hello verification */
113 #define MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL                  -0x6A00  /**< A buffer is too small to receive or write a message */
114 #define MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE             -0x6980  /**< None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages). */
115 #define MBEDTLS_ERR_SSL_WANT_READ                         -0x6900  /**< No data of requested type currently available on underlying transport. */
116 #define MBEDTLS_ERR_SSL_WANT_WRITE                        -0x6880  /**< Connection requires a write call. */
117 #define MBEDTLS_ERR_SSL_TIMEOUT                           -0x6800  /**< The operation timed out. */
118 #define MBEDTLS_ERR_SSL_CLIENT_RECONNECT                  -0x6780  /**< The client initiated a reconnect from the same port. */
119 #define MBEDTLS_ERR_SSL_UNEXPECTED_RECORD                 -0x6700  /**< Record header looks valid but is not expected. */
120 #define MBEDTLS_ERR_SSL_NON_FATAL                         -0x6680  /**< The alert message received indicates a non-fatal error. */
121 #define MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH               -0x6600  /**< Couldn't set the hash for verifying CertificateVerify */
122 #define MBEDTLS_ERR_SSL_CONTINUE_PROCESSING               -0x6580  /**< Internal-only message signaling that further message-processing should be done */
123 #define MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS                 -0x6500  /**< The asynchronous operation is not completed yet. */
124 #define MBEDTLS_ERR_SSL_EARLY_MESSAGE                     -0x6480  /**< Internal-only message signaling that a message arrived early. */
125 #define MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS                -0x7000  /**< A cryptographic operation is in progress. Try again later. */
126 
127 /*
128  * Various constants
129  */
130 #define MBEDTLS_SSL_MAJOR_VERSION_3             3
131 #define MBEDTLS_SSL_MINOR_VERSION_0             0   /*!< SSL v3.0 */
132 #define MBEDTLS_SSL_MINOR_VERSION_1             1   /*!< TLS v1.0 */
133 #define MBEDTLS_SSL_MINOR_VERSION_2             2   /*!< TLS v1.1 */
134 #define MBEDTLS_SSL_MINOR_VERSION_3             3   /*!< TLS v1.2 */
135 
136 #define MBEDTLS_SSL_TRANSPORT_STREAM            0   /*!< TLS      */
137 #define MBEDTLS_SSL_TRANSPORT_DATAGRAM          1   /*!< DTLS     */
138 
139 #define MBEDTLS_SSL_MAX_HOST_NAME_LEN           255 /*!< Maximum host name defined in RFC 1035 */
140 
141 /* RFC 6066 section 4, see also mfl_code_to_length in ssl_tls.c
142  * NONE must be zero so that memset()ing structure to zero works */
143 #define MBEDTLS_SSL_MAX_FRAG_LEN_NONE           0   /*!< don't use this extension   */
144 #define MBEDTLS_SSL_MAX_FRAG_LEN_512            1   /*!< MaxFragmentLength 2^9      */
145 #define MBEDTLS_SSL_MAX_FRAG_LEN_1024           2   /*!< MaxFragmentLength 2^10     */
146 #define MBEDTLS_SSL_MAX_FRAG_LEN_2048           3   /*!< MaxFragmentLength 2^11     */
147 #define MBEDTLS_SSL_MAX_FRAG_LEN_4096           4   /*!< MaxFragmentLength 2^12     */
148 #define MBEDTLS_SSL_MAX_FRAG_LEN_INVALID        5   /*!< first invalid value        */
149 
150 #define MBEDTLS_SSL_IS_CLIENT                   0
151 #define MBEDTLS_SSL_IS_SERVER                   1
152 
153 #define MBEDTLS_SSL_IS_NOT_FALLBACK             0
154 #define MBEDTLS_SSL_IS_FALLBACK                 1
155 
156 #define MBEDTLS_SSL_EXTENDED_MS_DISABLED        0
157 #define MBEDTLS_SSL_EXTENDED_MS_ENABLED         1
158 
159 #define MBEDTLS_SSL_ETM_DISABLED                0
160 #define MBEDTLS_SSL_ETM_ENABLED                 1
161 
162 #define MBEDTLS_SSL_COMPRESS_NULL               0
163 #define MBEDTLS_SSL_COMPRESS_DEFLATE            1
164 
165 #define MBEDTLS_SSL_VERIFY_NONE                 0
166 #define MBEDTLS_SSL_VERIFY_OPTIONAL             1
167 #define MBEDTLS_SSL_VERIFY_REQUIRED             2
168 #define MBEDTLS_SSL_VERIFY_UNSET                3 /* Used only for sni_authmode */
169 /* Modify for AliOS Things begin. 2019-06-17 */
170 #define MBEDTLS_SSL_VERIFY_COMPARE              4
171 /* Modify for AliOS Things end. 2019-06-17 */
172 
173 #define MBEDTLS_SSL_LEGACY_RENEGOTIATION        0
174 #define MBEDTLS_SSL_SECURE_RENEGOTIATION        1
175 
176 #define MBEDTLS_SSL_RENEGOTIATION_DISABLED      0
177 #define MBEDTLS_SSL_RENEGOTIATION_ENABLED       1
178 
179 #define MBEDTLS_SSL_ANTI_REPLAY_DISABLED        0
180 #define MBEDTLS_SSL_ANTI_REPLAY_ENABLED         1
181 
182 #define MBEDTLS_SSL_RENEGOTIATION_NOT_ENFORCED  -1
183 #define MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT  16
184 
185 #define MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION     0
186 #define MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION  1
187 #define MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE      2
188 
189 #define MBEDTLS_SSL_TRUNC_HMAC_DISABLED         0
190 #define MBEDTLS_SSL_TRUNC_HMAC_ENABLED          1
191 #define MBEDTLS_SSL_TRUNCATED_HMAC_LEN          10  /* 80 bits, rfc 6066 section 7 */
192 
193 #define MBEDTLS_SSL_SESSION_TICKETS_DISABLED     0
194 #define MBEDTLS_SSL_SESSION_TICKETS_ENABLED      1
195 
196 #define MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED    0
197 #define MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED     1
198 
199 #define MBEDTLS_SSL_ARC4_ENABLED                0
200 #define MBEDTLS_SSL_ARC4_DISABLED               1
201 
202 #define MBEDTLS_SSL_PRESET_DEFAULT              0
203 #define MBEDTLS_SSL_PRESET_SUITEB               2
204 
205 #define MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED       1
206 #define MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED      0
207 
208 /*
209  * Default range for DTLS retransmission timer value, in milliseconds.
210  * RFC 6347 4.2.4.1 says from 1 second to 60 seconds.
211  */
212 #define MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN    1000
213 #define MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX   60000
214 
215 /**
216  * \name SECTION: Module settings
217  *
218  * The configuration options you can set for this module are in this section.
219  * Either change them in config.h or define them on the compiler command line.
220  * \{
221  */
222 
223 #if !defined(MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME)
224 #define MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME     86400 /**< Lifetime of session tickets (if enabled) */
225 #endif
226 
227 /*
228  * Maximum fragment length in bytes,
229  * determines the size of each of the two internal I/O buffers.
230  *
231  * Note: the RFC defines the default size of SSL / TLS messages. If you
232  * change the value here, other clients / servers may not be able to
233  * communicate with you anymore. Only change this value if you control
234  * both sides of the connection and have it reduced at both sides, or
235  * if you're using the Max Fragment Length extension and you know all your
236  * peers are using it too!
237  */
238 #if !defined(MBEDTLS_SSL_MAX_CONTENT_LEN)
239 #define MBEDTLS_SSL_MAX_CONTENT_LEN         16384   /**< Size of the input / output buffer */
240 #endif
241 
242 #if !defined(MBEDTLS_SSL_IN_CONTENT_LEN)
243 #define MBEDTLS_SSL_IN_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN
244 #endif
245 
246 #if !defined(MBEDTLS_SSL_OUT_CONTENT_LEN)
247 #define MBEDTLS_SSL_OUT_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN
248 #endif
249 
250 /*
251  * Maximum number of heap-allocated bytes for the purpose of
252  * DTLS handshake message reassembly and future message buffering.
253  */
254 #if !defined(MBEDTLS_SSL_DTLS_MAX_BUFFERING)
255 #define MBEDTLS_SSL_DTLS_MAX_BUFFERING 32768
256 #endif
257 
258 /* \} name SECTION: Module settings */
259 
260 /*
261  * Length of the verify data for secure renegotiation
262  */
263 #if defined(MBEDTLS_SSL_PROTO_SSL3)
264 #define MBEDTLS_SSL_VERIFY_DATA_MAX_LEN 36
265 #else
266 #define MBEDTLS_SSL_VERIFY_DATA_MAX_LEN 12
267 #endif
268 
269 /*
270  * Signaling ciphersuite values (SCSV)
271  */
272 #define MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO    0xFF   /**< renegotiation info ext */
273 #define MBEDTLS_SSL_FALLBACK_SCSV_VALUE         0x5600 /**< RFC 7507 section 2 */
274 
275 /*
276  * Supported Signature and Hash algorithms (For TLS 1.2)
277  * RFC 5246 section 7.4.1.4.1
278  */
279 #define MBEDTLS_SSL_HASH_NONE                0
280 #define MBEDTLS_SSL_HASH_MD5                 1
281 #define MBEDTLS_SSL_HASH_SHA1                2
282 #define MBEDTLS_SSL_HASH_SHA224              3
283 #define MBEDTLS_SSL_HASH_SHA256              4
284 #define MBEDTLS_SSL_HASH_SHA384              5
285 #define MBEDTLS_SSL_HASH_SHA512              6
286 
287 #define MBEDTLS_SSL_SIG_ANON                 0
288 #define MBEDTLS_SSL_SIG_RSA                  1
289 #define MBEDTLS_SSL_SIG_ECDSA                3
290 
291 /*
292  * Client Certificate Types
293  * RFC 5246 section 7.4.4 plus RFC 4492 section 5.5
294  */
295 #define MBEDTLS_SSL_CERT_TYPE_RSA_SIGN       1
296 #define MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN    64
297 
298 /*
299  * Message, alert and handshake types
300  */
301 #define MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC     20
302 #define MBEDTLS_SSL_MSG_ALERT                  21
303 #define MBEDTLS_SSL_MSG_HANDSHAKE              22
304 #define MBEDTLS_SSL_MSG_APPLICATION_DATA       23
305 
306 #define MBEDTLS_SSL_ALERT_LEVEL_WARNING         1
307 #define MBEDTLS_SSL_ALERT_LEVEL_FATAL           2
308 
309 #define MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY           0  /* 0x00 */
310 #define MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE    10  /* 0x0A */
311 #define MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC        20  /* 0x14 */
312 #define MBEDTLS_SSL_ALERT_MSG_DECRYPTION_FAILED     21  /* 0x15 */
313 #define MBEDTLS_SSL_ALERT_MSG_RECORD_OVERFLOW       22  /* 0x16 */
314 #define MBEDTLS_SSL_ALERT_MSG_DECOMPRESSION_FAILURE 30  /* 0x1E */
315 #define MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE     40  /* 0x28 */
316 #define MBEDTLS_SSL_ALERT_MSG_NO_CERT               41  /* 0x29 */
317 #define MBEDTLS_SSL_ALERT_MSG_BAD_CERT              42  /* 0x2A */
318 #define MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT      43  /* 0x2B */
319 #define MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED          44  /* 0x2C */
320 #define MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED          45  /* 0x2D */
321 #define MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN          46  /* 0x2E */
322 #define MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER     47  /* 0x2F */
323 #define MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA            48  /* 0x30 */
324 #define MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED         49  /* 0x31 */
325 #define MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR          50  /* 0x32 */
326 #define MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR         51  /* 0x33 */
327 #define MBEDTLS_SSL_ALERT_MSG_EXPORT_RESTRICTION    60  /* 0x3C */
328 #define MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION      70  /* 0x46 */
329 #define MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY 71  /* 0x47 */
330 #define MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR        80  /* 0x50 */
331 #define MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK 86  /* 0x56 */
332 #define MBEDTLS_SSL_ALERT_MSG_USER_CANCELED         90  /* 0x5A */
333 #define MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION     100  /* 0x64 */
334 #define MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT      110  /* 0x6E */
335 #define MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME    112  /* 0x70 */
336 #define MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY 115  /* 0x73 */
337 #define MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL 120 /* 0x78 */
338 
339 #define MBEDTLS_SSL_HS_HELLO_REQUEST            0
340 #define MBEDTLS_SSL_HS_CLIENT_HELLO             1
341 #define MBEDTLS_SSL_HS_SERVER_HELLO             2
342 #define MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST     3
343 #define MBEDTLS_SSL_HS_NEW_SESSION_TICKET       4
344 #define MBEDTLS_SSL_HS_CERTIFICATE             11
345 #define MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE     12
346 #define MBEDTLS_SSL_HS_CERTIFICATE_REQUEST     13
347 #define MBEDTLS_SSL_HS_SERVER_HELLO_DONE       14
348 #define MBEDTLS_SSL_HS_CERTIFICATE_VERIFY      15
349 #define MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE     16
350 #define MBEDTLS_SSL_HS_FINISHED                20
351 
352 /*
353  * TLS extensions
354  */
355 #define MBEDTLS_TLS_EXT_SERVERNAME                   0
356 #define MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME          0
357 
358 #define MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH          1
359 
360 #define MBEDTLS_TLS_EXT_TRUNCATED_HMAC               4
361 
362 #define MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES   10
363 #define MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS     11
364 
365 #define MBEDTLS_TLS_EXT_SIG_ALG                     13
366 
367 #define MBEDTLS_TLS_EXT_ALPN                        16
368 
369 #define MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC            22 /* 0x16 */
370 #define MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET  0x0017 /* 23 */
371 
372 #define MBEDTLS_TLS_EXT_SESSION_TICKET              35
373 
374 #define MBEDTLS_TLS_EXT_ECJPAKE_KKPP               256 /* experimental */
375 
376 #define MBEDTLS_TLS_EXT_RENEGOTIATION_INFO      0xFF01
377 
378 /*
379  * Size defines
380  */
381 #if !defined(MBEDTLS_PSK_MAX_LEN)
382 #define MBEDTLS_PSK_MAX_LEN            32 /* 256 bits */
383 #endif
384 
385 /* Dummy type used only for its size */
386 union mbedtls_ssl_premaster_secret
387 {
388 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
389     unsigned char _pms_rsa[48];                         /* RFC 5246 8.1.1 */
390 #endif
391 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
392     unsigned char _pms_dhm[MBEDTLS_MPI_MAX_SIZE];      /* RFC 5246 8.1.2 */
393 #endif
394 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)    || \
395     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)  || \
396     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)     || \
397     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
398     unsigned char _pms_ecdh[MBEDTLS_ECP_MAX_BYTES];    /* RFC 4492 5.10 */
399 #endif
400 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
401     unsigned char _pms_psk[4 + 2 * MBEDTLS_PSK_MAX_LEN];       /* RFC 4279 2 */
402 #endif
403 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
404     unsigned char _pms_dhe_psk[4 + MBEDTLS_MPI_MAX_SIZE
405                                  + MBEDTLS_PSK_MAX_LEN];       /* RFC 4279 3 */
406 #endif
407 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
408     unsigned char _pms_rsa_psk[52 + MBEDTLS_PSK_MAX_LEN];      /* RFC 4279 4 */
409 #endif
410 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
411     unsigned char _pms_ecdhe_psk[4 + MBEDTLS_ECP_MAX_BYTES
412                                    + MBEDTLS_PSK_MAX_LEN];     /* RFC 5489 2 */
413 #endif
414 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
415     unsigned char _pms_ecjpake[32];     /* Thread spec: SHA-256 output */
416 #endif
417 };
418 
419 #define MBEDTLS_PREMASTER_SIZE     sizeof( union mbedtls_ssl_premaster_secret )
420 
421 #ifdef __cplusplus
422 extern "C" {
423 #endif
424 
425 /*
426  * SSL state machine
427  */
428 typedef enum
429 {
430     MBEDTLS_SSL_HELLO_REQUEST,
431     MBEDTLS_SSL_CLIENT_HELLO,
432     MBEDTLS_SSL_SERVER_HELLO,
433     MBEDTLS_SSL_SERVER_CERTIFICATE,
434     MBEDTLS_SSL_SERVER_KEY_EXCHANGE,
435     MBEDTLS_SSL_CERTIFICATE_REQUEST,
436     MBEDTLS_SSL_SERVER_HELLO_DONE,
437     MBEDTLS_SSL_CLIENT_CERTIFICATE,
438     MBEDTLS_SSL_CLIENT_KEY_EXCHANGE,
439     MBEDTLS_SSL_CERTIFICATE_VERIFY,
440     MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC,
441     MBEDTLS_SSL_CLIENT_FINISHED,
442     MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC,
443     MBEDTLS_SSL_SERVER_FINISHED,
444     MBEDTLS_SSL_FLUSH_BUFFERS,
445     MBEDTLS_SSL_HANDSHAKE_WRAPUP,
446     MBEDTLS_SSL_HANDSHAKE_OVER,
447     MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET,
448     MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT,
449 }
450 mbedtls_ssl_states;
451 
452 /**
453  * \brief          Callback type: send data on the network.
454  *
455  * \note           That callback may be either blocking or non-blocking.
456  *
457  * \param ctx      Context for the send callback (typically a file descriptor)
458  * \param buf      Buffer holding the data to send
459  * \param len      Length of the data to send
460  *
461  * \return         The callback must return the number of bytes sent if any,
462  *                 or a non-zero error code.
463  *                 If performing non-blocking I/O, \c MBEDTLS_ERR_SSL_WANT_WRITE
464  *                 must be returned when the operation would block.
465  *
466  * \note           The callback is allowed to send fewer bytes than requested.
467  *                 It must always return the number of bytes actually sent.
468  */
469 typedef int mbedtls_ssl_send_t( void *ctx,
470                                 const unsigned char *buf,
471                                 size_t len );
472 
473 /**
474  * \brief          Callback type: receive data from the network.
475  *
476  * \note           That callback may be either blocking or non-blocking.
477  *
478  * \param ctx      Context for the receive callback (typically a file
479  *                 descriptor)
480  * \param buf      Buffer to write the received data to
481  * \param len      Length of the receive buffer
482  *
483  * \return         The callback must return the number of bytes received,
484  *                 or a non-zero error code.
485  *                 If performing non-blocking I/O, \c MBEDTLS_ERR_SSL_WANT_READ
486  *                 must be returned when the operation would block.
487  *
488  * \note           The callback may receive fewer bytes than the length of the
489  *                 buffer. It must always return the number of bytes actually
490  *                 received and written to the buffer.
491  */
492 typedef int mbedtls_ssl_recv_t( void *ctx,
493                                 unsigned char *buf,
494                                 size_t len );
495 
496 /**
497  * \brief          Callback type: receive data from the network, with timeout
498  *
499  * \note           That callback must block until data is received, or the
500  *                 timeout delay expires, or the operation is interrupted by a
501  *                 signal.
502  *
503  * \param ctx      Context for the receive callback (typically a file descriptor)
504  * \param buf      Buffer to write the received data to
505  * \param len      Length of the receive buffer
506  * \param timeout  Maximum nomber of millisecondes to wait for data
507  *                 0 means no timeout (potentially waiting forever)
508  *
509  * \return         The callback must return the number of bytes received,
510  *                 or a non-zero error code:
511  *                 \c MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out,
512  *                 \c MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal.
513  *
514  * \note           The callback may receive fewer bytes than the length of the
515  *                 buffer. It must always return the number of bytes actually
516  *                 received and written to the buffer.
517  */
518 typedef int mbedtls_ssl_recv_timeout_t( void *ctx,
519                                         unsigned char *buf,
520                                         size_t len,
521                                         uint32_t timeout );
522 /**
523  * \brief          Callback type: set a pair of timers/delays to watch
524  *
525  * \param ctx      Context pointer
526  * \param int_ms   Intermediate delay in milliseconds
527  * \param fin_ms   Final delay in milliseconds
528  *                 0 cancels the current timer.
529  *
530  * \note           This callback must at least store the necessary information
531  *                 for the associated \c mbedtls_ssl_get_timer_t callback to
532  *                 return correct information.
533  *
534  * \note           If using a event-driven style of programming, an event must
535  *                 be generated when the final delay is passed. The event must
536  *                 cause a call to \c mbedtls_ssl_handshake() with the proper
537  *                 SSL context to be scheduled. Care must be taken to ensure
538  *                 that at most one such call happens at a time.
539  *
540  * \note           Only one timer at a time must be running. Calling this
541  *                 function while a timer is running must cancel it. Cancelled
542  *                 timers must not generate any event.
543  */
544 typedef void mbedtls_ssl_set_timer_t( void * ctx,
545                                       uint32_t int_ms,
546                                       uint32_t fin_ms );
547 
548 /**
549  * \brief          Callback type: get status of timers/delays
550  *
551  * \param ctx      Context pointer
552  *
553  * \return         This callback must return:
554  *                 -1 if cancelled (fin_ms == 0),
555  *                  0 if none of the delays have passed,
556  *                  1 if only the intermediate delay has passed,
557  *                  2 if the final delay has passed.
558  */
559 typedef int mbedtls_ssl_get_timer_t( void * ctx );
560 
561 /* Defined below */
562 typedef struct mbedtls_ssl_session mbedtls_ssl_session;
563 typedef struct mbedtls_ssl_context mbedtls_ssl_context;
564 typedef struct mbedtls_ssl_config  mbedtls_ssl_config;
565 
566 /* Defined in ssl_internal.h */
567 typedef struct mbedtls_ssl_transform mbedtls_ssl_transform;
568 typedef struct mbedtls_ssl_handshake_params mbedtls_ssl_handshake_params;
569 typedef struct mbedtls_ssl_sig_hash_set_t mbedtls_ssl_sig_hash_set_t;
570 #if defined(MBEDTLS_X509_CRT_PARSE_C)
571 typedef struct mbedtls_ssl_key_cert mbedtls_ssl_key_cert;
572 #endif
573 #if defined(MBEDTLS_SSL_PROTO_DTLS)
574 typedef struct mbedtls_ssl_flight_item mbedtls_ssl_flight_item;
575 #endif
576 
577 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
578 #if defined(MBEDTLS_X509_CRT_PARSE_C)
579 /**
580  * \brief           Callback type: start external signature operation.
581  *
582  *                  This callback is called during an SSL handshake to start
583  *                  a signature decryption operation using an
584  *                  external processor. The parameter \p cert contains
585  *                  the public key; it is up to the callback function to
586  *                  determine how to access the associated private key.
587  *
588  *                  This function typically sends or enqueues a request, and
589  *                  does not wait for the operation to complete. This allows
590  *                  the handshake step to be non-blocking.
591  *
592  *                  The parameters \p ssl and \p cert are guaranteed to remain
593  *                  valid throughout the handshake. On the other hand, this
594  *                  function must save the contents of \p hash if the value
595  *                  is needed for later processing, because the \p hash buffer
596  *                  is no longer valid after this function returns.
597  *
598  *                  This function may call mbedtls_ssl_set_async_operation_data()
599  *                  to store an operation context for later retrieval
600  *                  by the resume or cancel callback.
601  *
602  * \note            For RSA signatures, this function must produce output
603  *                  that is consistent with PKCS#1 v1.5 in the same way as
604  *                  mbedtls_rsa_pkcs1_sign(). Before the private key operation,
605  *                  apply the padding steps described in RFC 8017, section 9.2
606  *                  "EMSA-PKCS1-v1_5" as follows.
607  *                  - If \p md_alg is #MBEDTLS_MD_NONE, apply the PKCS#1 v1.5
608  *                    encoding, treating \p hash as the DigestInfo to be
609  *                    padded. In other words, apply EMSA-PKCS1-v1_5 starting
610  *                    from step 3, with `T = hash` and `tLen = hash_len`.
611  *                  - If `md_alg != MBEDTLS_MD_NONE`, apply the PKCS#1 v1.5
612  *                    encoding, treating \p hash as the hash to be encoded and
613  *                    padded. In other words, apply EMSA-PKCS1-v1_5 starting
614  *                    from step 2, with `digestAlgorithm` obtained by calling
615  *                    mbedtls_oid_get_oid_by_md() on \p md_alg.
616  *
617  * \note            For ECDSA signatures, the output format is the DER encoding
618  *                  `Ecdsa-Sig-Value` defined in
619  *                  [RFC 4492 section 5.4](https://tools.ietf.org/html/rfc4492#section-5.4).
620  *
621  * \param ssl             The SSL connection instance. It should not be
622  *                        modified other than via
623  *                        mbedtls_ssl_set_async_operation_data().
624  * \param cert            Certificate containing the public key.
625  *                        In simple cases, this is one of the pointers passed to
626  *                        mbedtls_ssl_conf_own_cert() when configuring the SSL
627  *                        connection. However, if other callbacks are used, this
628  *                        property may not hold. For example, if an SNI callback
629  *                        is registered with mbedtls_ssl_conf_sni(), then
630  *                        this callback determines what certificate is used.
631  * \param md_alg          Hash algorithm.
632  * \param hash            Buffer containing the hash. This buffer is
633  *                        no longer valid when the function returns.
634  * \param hash_len        Size of the \c hash buffer in bytes.
635  *
636  * \return          0 if the operation was started successfully and the SSL
637  *                  stack should call the resume callback immediately.
638  * \return          #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation
639  *                  was started successfully and the SSL stack should return
640  *                  immediately without calling the resume callback yet.
641  * \return          #MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH if the external
642  *                  processor does not support this key. The SSL stack will
643  *                  use the private key object instead.
644  * \return          Any other error indicates a fatal failure and is
645  *                  propagated up the call chain. The callback should
646  *                  use \c MBEDTLS_ERR_PK_xxx error codes, and <b>must not</b>
647  *                  use \c MBEDTLS_ERR_SSL_xxx error codes except as
648  *                  directed in the documentation of this callback.
649  */
650 typedef int mbedtls_ssl_async_sign_t( mbedtls_ssl_context *ssl,
651                                       mbedtls_x509_crt *cert,
652                                       mbedtls_md_type_t md_alg,
653                                       const unsigned char *hash,
654                                       size_t hash_len );
655 
656 /**
657  * \brief           Callback type: start external decryption operation.
658  *
659  *                  This callback is called during an SSL handshake to start
660  *                  an RSA decryption operation using an
661  *                  external processor. The parameter \p cert contains
662  *                  the public key; it is up to the callback function to
663  *                  determine how to access the associated private key.
664  *
665  *                  This function typically sends or enqueues a request, and
666  *                  does not wait for the operation to complete. This allows
667  *                  the handshake step to be non-blocking.
668  *
669  *                  The parameters \p ssl and \p cert are guaranteed to remain
670  *                  valid throughout the handshake. On the other hand, this
671  *                  function must save the contents of \p input if the value
672  *                  is needed for later processing, because the \p input buffer
673  *                  is no longer valid after this function returns.
674  *
675  *                  This function may call mbedtls_ssl_set_async_operation_data()
676  *                  to store an operation context for later retrieval
677  *                  by the resume or cancel callback.
678  *
679  * \warning         RSA decryption as used in TLS is subject to a potential
680  *                  timing side channel attack first discovered by Bleichenbacher
681  *                  in 1998. This attack can be remotely exploitable
682  *                  in practice. To avoid this attack, you must ensure that
683  *                  if the callback performs an RSA decryption, the time it
684  *                  takes to execute and return the result does not depend
685  *                  on whether the RSA decryption succeeded or reported
686  *                  invalid padding.
687  *
688  * \param ssl             The SSL connection instance. It should not be
689  *                        modified other than via
690  *                        mbedtls_ssl_set_async_operation_data().
691  * \param cert            Certificate containing the public key.
692  *                        In simple cases, this is one of the pointers passed to
693  *                        mbedtls_ssl_conf_own_cert() when configuring the SSL
694  *                        connection. However, if other callbacks are used, this
695  *                        property may not hold. For example, if an SNI callback
696  *                        is registered with mbedtls_ssl_conf_sni(), then
697  *                        this callback determines what certificate is used.
698  * \param input           Buffer containing the input ciphertext. This buffer
699  *                        is no longer valid when the function returns.
700  * \param input_len       Size of the \p input buffer in bytes.
701  *
702  * \return          0 if the operation was started successfully and the SSL
703  *                  stack should call the resume callback immediately.
704  * \return          #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation
705  *                  was started successfully and the SSL stack should return
706  *                  immediately without calling the resume callback yet.
707  * \return          #MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH if the external
708  *                  processor does not support this key. The SSL stack will
709  *                  use the private key object instead.
710  * \return          Any other error indicates a fatal failure and is
711  *                  propagated up the call chain. The callback should
712  *                  use \c MBEDTLS_ERR_PK_xxx error codes, and <b>must not</b>
713  *                  use \c MBEDTLS_ERR_SSL_xxx error codes except as
714  *                  directed in the documentation of this callback.
715  */
716 typedef int mbedtls_ssl_async_decrypt_t( mbedtls_ssl_context *ssl,
717                                          mbedtls_x509_crt *cert,
718                                          const unsigned char *input,
719                                          size_t input_len );
720 #endif /* MBEDTLS_X509_CRT_PARSE_C */
721 
722 /**
723  * \brief           Callback type: resume external operation.
724  *
725  *                  This callback is called during an SSL handshake to resume
726  *                  an external operation started by the
727  *                  ::mbedtls_ssl_async_sign_t or
728  *                  ::mbedtls_ssl_async_decrypt_t callback.
729  *
730  *                  This function typically checks the status of a pending
731  *                  request or causes the request queue to make progress, and
732  *                  does not wait for the operation to complete. This allows
733  *                  the handshake step to be non-blocking.
734  *
735  *                  This function may call mbedtls_ssl_get_async_operation_data()
736  *                  to retrieve an operation context set by the start callback.
737  *                  It may call mbedtls_ssl_set_async_operation_data() to modify
738  *                  this context.
739  *
740  *                  Note that when this function returns a status other than
741  *                  #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, it must free any
742  *                  resources associated with the operation.
743  *
744  * \param ssl             The SSL connection instance. It should not be
745  *                        modified other than via
746  *                        mbedtls_ssl_set_async_operation_data().
747  * \param output          Buffer containing the output (signature or decrypted
748  *                        data) on success.
749  * \param output_len      On success, number of bytes written to \p output.
750  * \param output_size     Size of the \p output buffer in bytes.
751  *
752  * \return          0 if output of the operation is available in the
753  *                  \p output buffer.
754  * \return          #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation
755  *                  is still in progress. Subsequent requests for progress
756  *                  on the SSL connection will call the resume callback
757  *                  again.
758  * \return          Any other error means that the operation is aborted.
759  *                  The SSL handshake is aborted. The callback should
760  *                  use \c MBEDTLS_ERR_PK_xxx error codes, and <b>must not</b>
761  *                  use \c MBEDTLS_ERR_SSL_xxx error codes except as
762  *                  directed in the documentation of this callback.
763  */
764 typedef int mbedtls_ssl_async_resume_t( mbedtls_ssl_context *ssl,
765                                         unsigned char *output,
766                                         size_t *output_len,
767                                         size_t output_size );
768 
769 /**
770  * \brief           Callback type: cancel external operation.
771  *
772  *                  This callback is called if an SSL connection is closed
773  *                  while an asynchronous operation is in progress. Note that
774  *                  this callback is not called if the
775  *                  ::mbedtls_ssl_async_resume_t callback has run and has
776  *                  returned a value other than
777  *                  #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, since in that case
778  *                  the asynchronous operation has already completed.
779  *
780  *                  This function may call mbedtls_ssl_get_async_operation_data()
781  *                  to retrieve an operation context set by the start callback.
782  *
783  * \param ssl             The SSL connection instance. It should not be
784  *                        modified.
785  */
786 typedef void mbedtls_ssl_async_cancel_t( mbedtls_ssl_context *ssl );
787 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
788 
789 /*
790  * This structure is used for storing current session data.
791  */
792 struct mbedtls_ssl_session
793 {
794 #if defined(MBEDTLS_HAVE_TIME)
795     mbedtls_time_t start;       /*!< starting time      */
796 #endif
797     int ciphersuite;            /*!< chosen ciphersuite */
798     int compression;            /*!< chosen compression */
799     size_t id_len;              /*!< session id length  */
800     unsigned char id[32];       /*!< session identifier */
801     unsigned char master[48];   /*!< the master secret  */
802 
803 #if defined(MBEDTLS_X509_CRT_PARSE_C)
804     mbedtls_x509_crt *peer_cert;        /*!< peer X.509 cert chain */
805 #endif /* MBEDTLS_X509_CRT_PARSE_C */
806     uint32_t verify_result;          /*!<  verification result     */
807 
808 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
809     unsigned char *ticket;      /*!< RFC 5077 session ticket */
810     size_t ticket_len;          /*!< session ticket length   */
811     uint32_t ticket_lifetime;   /*!< ticket lifetime hint    */
812 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
813 
814 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
815     unsigned char mfl_code;     /*!< MaxFragmentLength negotiated by peer */
816 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
817 
818 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
819     int trunc_hmac;             /*!< flag for truncated hmac activation   */
820 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
821 
822 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
823     int encrypt_then_mac;       /*!< flag for EtM activation                */
824 #endif
825 };
826 
827 /**
828  * SSL/TLS configuration to be shared between mbedtls_ssl_context structures.
829  */
830 struct mbedtls_ssl_config
831 {
832     /* Group items by size (largest first) to minimize padding overhead */
833 
834     /*
835      * Pointers
836      */
837 
838     const int *ciphersuite_list[4]; /*!< allowed ciphersuites per version   */
839 
840     /** Callback for printing debug output                                  */
841     void (*f_dbg)(void *, int, const char *, int, const char *);
842     void *p_dbg;                    /*!< context for the debug function     */
843 
844     /** Callback for getting (pseudo-)random numbers                        */
845     int  (*f_rng)(void *, unsigned char *, size_t);
846     void *p_rng;                    /*!< context for the RNG function       */
847 
848     /** Callback to retrieve a session from the cache                       */
849     int (*f_get_cache)(void *, mbedtls_ssl_session *);
850     /** Callback to store a session into the cache                          */
851     int (*f_set_cache)(void *, const mbedtls_ssl_session *);
852     void *p_cache;                  /*!< context for cache callbacks        */
853 
854 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
855     /** Callback for setting cert according to SNI extension                */
856     int (*f_sni)(void *, mbedtls_ssl_context *, const unsigned char *, size_t);
857     void *p_sni;                    /*!< context for SNI callback           */
858 #endif
859 
860 #if defined(MBEDTLS_X509_CRT_PARSE_C)
861     /** Callback to customize X.509 certificate chain verification          */
862     int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *);
863     void *p_vrfy;                   /*!< context for X.509 verify calllback */
864 #endif
865 
866 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
867     /** Callback to retrieve PSK key from identity                          */
868     int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *, size_t);
869     void *p_psk;                    /*!< context for PSK callback           */
870 #endif
871 
872 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
873     /** Callback to create & write a cookie for ClientHello veirifcation    */
874     int (*f_cookie_write)( void *, unsigned char **, unsigned char *,
875                            const unsigned char *, size_t );
876     /** Callback to verify validity of a ClientHello cookie                 */
877     int (*f_cookie_check)( void *, const unsigned char *, size_t,
878                            const unsigned char *, size_t );
879     void *p_cookie;                 /*!< context for the cookie callbacks   */
880 #endif
881 
882 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_SRV_C)
883     /** Callback to create & write a session ticket                         */
884     int (*f_ticket_write)( void *, const mbedtls_ssl_session *,
885             unsigned char *, const unsigned char *, size_t *, uint32_t * );
886     /** Callback to parse a session ticket into a session structure         */
887     int (*f_ticket_parse)( void *, mbedtls_ssl_session *, unsigned char *, size_t);
888     void *p_ticket;                 /*!< context for the ticket callbacks   */
889 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_SRV_C */
890 
891 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
892     /** Callback to export key block and master secret                      */
893     int (*f_export_keys)( void *, const unsigned char *,
894             const unsigned char *, size_t, size_t, size_t );
895     void *p_export_keys;            /*!< context for key export callback    */
896 #endif
897 
898 #if defined(MBEDTLS_X509_CRT_PARSE_C)
899     const mbedtls_x509_crt_profile *cert_profile; /*!< verification profile */
900     mbedtls_ssl_key_cert *key_cert; /*!< own certificate/key pair(s)        */
901     mbedtls_x509_crt *ca_chain;     /*!< trusted CAs                        */
902     mbedtls_x509_crl *ca_crl;       /*!< trusted CAs CRLs                   */
903 #endif /* MBEDTLS_X509_CRT_PARSE_C */
904 
905 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
906 #if defined(MBEDTLS_X509_CRT_PARSE_C)
907     mbedtls_ssl_async_sign_t *f_async_sign_start; /*!< start asynchronous signature operation */
908     mbedtls_ssl_async_decrypt_t *f_async_decrypt_start; /*!< start asynchronous decryption operation */
909 #endif /* MBEDTLS_X509_CRT_PARSE_C */
910     mbedtls_ssl_async_resume_t *f_async_resume; /*!< resume asynchronous operation */
911     mbedtls_ssl_async_cancel_t *f_async_cancel; /*!< cancel asynchronous operation */
912     void *p_async_config_data; /*!< Configuration data set by mbedtls_ssl_conf_async_private_cb(). */
913 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
914 
915 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
916     const int *sig_hashes;          /*!< allowed signature hashes           */
917 #endif
918 
919 #if defined(MBEDTLS_ECP_C)
920     const mbedtls_ecp_group_id *curve_list; /*!< allowed curves             */
921 #endif
922 
923 #if defined(MBEDTLS_DHM_C)
924     mbedtls_mpi dhm_P;              /*!< prime modulus for DHM              */
925     mbedtls_mpi dhm_G;              /*!< generator for DHM                  */
926 #endif
927 
928 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
929     unsigned char *psk;             /*!< pre-shared key. This field should
930                                          only be set via
931                                          mbedtls_ssl_conf_psk() */
932     size_t         psk_len;         /*!< length of the pre-shared key. This
933                                          field should only be set via
934                                          mbedtls_ssl_conf_psk() */
935     unsigned char *psk_identity;    /*!< identity for PSK negotiation. This
936                                          field should only be set via
937                                          mbedtls_ssl_conf_psk() */
938     size_t         psk_identity_len;/*!< length of identity. This field should
939                                          only be set via
940                                          mbedtls_ssl_conf_psk() */
941 #endif
942 
943 #if defined(MBEDTLS_SSL_ALPN)
944     const char **alpn_list;         /*!< ordered list of protocols          */
945 #endif
946 
947     /*
948      * Numerical settings (int then char)
949      */
950 
951     uint32_t read_timeout;          /*!< timeout for mbedtls_ssl_read (ms)  */
952 
953 #if defined(MBEDTLS_SSL_PROTO_DTLS)
954     uint32_t hs_timeout_min;        /*!< initial value of the handshake
955                                          retransmission timeout (ms)        */
956     uint32_t hs_timeout_max;        /*!< maximum value of the handshake
957                                          retransmission timeout (ms)        */
958 #endif
959 
960 #if defined(MBEDTLS_SSL_RENEGOTIATION)
961     int renego_max_records;         /*!< grace period for renegotiation     */
962     unsigned char renego_period[8]; /*!< value of the record counters
963                                          that triggers renegotiation        */
964 #endif
965 
966 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
967     unsigned int badmac_limit;      /*!< limit of records with a bad MAC    */
968 #endif
969 
970 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
971     unsigned int dhm_min_bitlen;    /*!< min. bit length of the DHM prime   */
972 #endif
973 
974     unsigned char max_major_ver;    /*!< max. major version used            */
975     unsigned char max_minor_ver;    /*!< max. minor version used            */
976     unsigned char min_major_ver;    /*!< min. major version used            */
977     unsigned char min_minor_ver;    /*!< min. minor version used            */
978 
979     /*
980      * Flags (bitfields)
981      */
982 
983     unsigned int endpoint : 1;      /*!< 0: client, 1: server               */
984     unsigned int transport : 1;     /*!< stream (TLS) or datagram (DTLS)    */
985     /* Modify for AliOS Things begin. 2019-06-17 */
986     unsigned int authmode : 3;      /*!< MBEDTLS_SSL_VERIFY_XXX             */
987     /* Modify for AliOS Things end. 2019-06-17 */
988     /* needed even with renego disabled for LEGACY_BREAK_HANDSHAKE          */
989     unsigned int allow_legacy_renegotiation : 2 ; /*!< MBEDTLS_LEGACY_XXX   */
990 #if defined(MBEDTLS_ARC4_C)
991     unsigned int arc4_disabled : 1; /*!< blacklist RC4 ciphersuites?        */
992 #endif
993 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
994     unsigned int mfl_code : 3;      /*!< desired fragment length            */
995 #endif
996 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
997     unsigned int encrypt_then_mac : 1 ; /*!< negotiate encrypt-then-mac?    */
998 #endif
999 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1000     unsigned int extended_ms : 1;   /*!< negotiate extended master secret?  */
1001 #endif
1002 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
1003     unsigned int anti_replay : 1;   /*!< detect and prevent replay?         */
1004 #endif
1005 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
1006     unsigned int cbc_record_splitting : 1;  /*!< do cbc record splitting    */
1007 #endif
1008 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1009     unsigned int disable_renegotiation : 1; /*!< disable renegotiation?     */
1010 #endif
1011 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
1012     unsigned int trunc_hmac : 1;    /*!< negotiate truncated hmac?          */
1013 #endif
1014 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
1015     unsigned int session_tickets : 1;   /*!< use session tickets?           */
1016 #endif
1017 #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
1018     unsigned int fallback : 1;      /*!< is this a fallback?                */
1019 #endif
1020 #if defined(MBEDTLS_SSL_SRV_C)
1021     unsigned int cert_req_ca_list : 1;  /*!< enable sending CA list in
1022                                           Certificate Request messages?     */
1023 #endif
1024 };
1025 
1026 
1027 struct mbedtls_ssl_context
1028 {
1029     const mbedtls_ssl_config *conf; /*!< configuration information          */
1030 
1031     /*
1032      * Miscellaneous
1033      */
1034     int state;                  /*!< SSL handshake: current state     */
1035 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1036     int renego_status;          /*!< Initial, in progress, pending?   */
1037     int renego_records_seen;    /*!< Records since renego request, or with DTLS,
1038                                   number of retransmissions of request if
1039                                   renego_max_records is < 0           */
1040 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1041 
1042     int major_ver;              /*!< equal to  MBEDTLS_SSL_MAJOR_VERSION_3    */
1043     int minor_ver;              /*!< either 0 (SSL3) or 1 (TLS1.0)    */
1044 
1045 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
1046     unsigned badmac_seen;       /*!< records with a bad MAC received    */
1047 #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */
1048 
1049     mbedtls_ssl_send_t *f_send; /*!< Callback for network send */
1050     mbedtls_ssl_recv_t *f_recv; /*!< Callback for network receive */
1051     mbedtls_ssl_recv_timeout_t *f_recv_timeout;
1052                                 /*!< Callback for network receive with timeout */
1053 
1054     void *p_bio;                /*!< context for I/O operations   */
1055 
1056     /*
1057      * Session layer
1058      */
1059     mbedtls_ssl_session *session_in;            /*!<  current session data (in)   */
1060     mbedtls_ssl_session *session_out;           /*!<  current session data (out)  */
1061     mbedtls_ssl_session *session;               /*!<  negotiated session data     */
1062     mbedtls_ssl_session *session_negotiate;     /*!<  session data in negotiation */
1063 
1064     mbedtls_ssl_handshake_params *handshake;    /*!<  params required only during
1065                                               the handshake process        */
1066 
1067     /*
1068      * Record layer transformations
1069      */
1070     mbedtls_ssl_transform *transform_in;        /*!<  current transform params (in)   */
1071     mbedtls_ssl_transform *transform_out;       /*!<  current transform params (in)   */
1072     mbedtls_ssl_transform *transform;           /*!<  negotiated transform params     */
1073     mbedtls_ssl_transform *transform_negotiate; /*!<  transform params in negotiation */
1074 
1075     /*
1076      * Timers
1077      */
1078     void *p_timer;              /*!< context for the timer callbacks */
1079 
1080     mbedtls_ssl_set_timer_t *f_set_timer;       /*!< set timer callback */
1081     mbedtls_ssl_get_timer_t *f_get_timer;       /*!< get timer callback */
1082 
1083     /*
1084      * Record layer (incoming data)
1085      */
1086     unsigned char *in_buf;      /*!< input buffer                     */
1087     unsigned char *in_ctr;      /*!< 64-bit incoming message counter
1088                                      TLS: maintained by us
1089                                      DTLS: read from peer             */
1090     unsigned char *in_hdr;      /*!< start of record header           */
1091     unsigned char *in_len;      /*!< two-bytes message length field   */
1092     unsigned char *in_iv;       /*!< ivlen-byte IV                    */
1093     unsigned char *in_msg;      /*!< message contents (in_iv+ivlen)   */
1094     unsigned char *in_offt;     /*!< read offset in application data  */
1095 
1096     int in_msgtype;             /*!< record header: message type      */
1097     size_t in_msglen;           /*!< record header: message length    */
1098     size_t in_left;             /*!< amount of data read so far       */
1099 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1100     uint16_t in_epoch;          /*!< DTLS epoch for incoming records  */
1101     size_t next_record_offset;  /*!< offset of the next record in datagram
1102                                      (equal to in_left if none)       */
1103 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1104 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
1105     uint64_t in_window_top;     /*!< last validated record seq_num    */
1106     uint64_t in_window;         /*!< bitmask for replay detection     */
1107 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
1108 
1109     size_t in_hslen;            /*!< current handshake message length,
1110                                      including the handshake header   */
1111     int nb_zero;                /*!< # of 0-length encrypted messages */
1112 
1113     int keep_current_message;   /*!< drop or reuse current message
1114                                      on next call to record layer? */
1115 
1116 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1117     uint8_t disable_datagram_packing;  /*!< Disable packing multiple records
1118                                         *   within a single datagram.  */
1119 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1120 
1121     /*
1122      * Record layer (outgoing data)
1123      */
1124     unsigned char *out_buf;     /*!< output buffer                    */
1125     unsigned char *out_ctr;     /*!< 64-bit outgoing message counter  */
1126     unsigned char *out_hdr;     /*!< start of record header           */
1127     unsigned char *out_len;     /*!< two-bytes message length field   */
1128     unsigned char *out_iv;      /*!< ivlen-byte IV                    */
1129     unsigned char *out_msg;     /*!< message contents (out_iv+ivlen)  */
1130 
1131     int out_msgtype;            /*!< record header: message type      */
1132     size_t out_msglen;          /*!< record header: message length    */
1133     size_t out_left;            /*!< amount of data not yet written   */
1134 
1135     unsigned char cur_out_ctr[8]; /*!<  Outgoing record sequence  number. */
1136 
1137 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1138     uint16_t mtu;               /*!< path mtu, used to fragment outgoing messages */
1139 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1140 
1141 #if defined(MBEDTLS_ZLIB_SUPPORT)
1142     unsigned char *compress_buf;        /*!<  zlib data buffer        */
1143 #endif /* MBEDTLS_ZLIB_SUPPORT */
1144 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
1145     signed char split_done;     /*!< current record already splitted? */
1146 #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
1147 
1148     /*
1149      * PKI layer
1150      */
1151     int client_auth;                    /*!<  flag for client auth.   */
1152 
1153     /*
1154      * User settings
1155      */
1156 #if defined(MBEDTLS_X509_CRT_PARSE_C)
1157     char *hostname;             /*!< expected peer CN for verification
1158                                      (and SNI if available)                 */
1159 #endif /* MBEDTLS_X509_CRT_PARSE_C */
1160 
1161 #if defined(MBEDTLS_SSL_ALPN)
1162     const char *alpn_chosen;    /*!<  negotiated protocol                   */
1163 #endif /* MBEDTLS_SSL_ALPN */
1164 
1165     /*
1166      * Information for DTLS hello verify
1167      */
1168 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
1169     unsigned char  *cli_id;         /*!<  transport-level ID of the client  */
1170     size_t          cli_id_len;     /*!<  length of cli_id                  */
1171 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
1172 
1173     /*
1174      * Secure renegotiation
1175      */
1176     /* needed to know when to send extension on server */
1177     int secure_renegotiation;           /*!<  does peer support legacy or
1178                                               secure renegotiation           */
1179 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1180     size_t verify_data_len;             /*!<  length of verify data stored   */
1181     char own_verify_data[MBEDTLS_SSL_VERIFY_DATA_MAX_LEN]; /*!<  previous handshake verify data */
1182     char peer_verify_data[MBEDTLS_SSL_VERIFY_DATA_MAX_LEN]; /*!<  previous handshake verify data */
1183 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1184 };
1185 
1186 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
1187 
1188 #define MBEDTLS_SSL_CHANNEL_OUTBOUND    0
1189 #define MBEDTLS_SSL_CHANNEL_INBOUND     1
1190 
1191 extern int (*mbedtls_ssl_hw_record_init)(mbedtls_ssl_context *ssl,
1192                 const unsigned char *key_enc, const unsigned char *key_dec,
1193                 size_t keylen,
1194                 const unsigned char *iv_enc,  const unsigned char *iv_dec,
1195                 size_t ivlen,
1196                 const unsigned char *mac_enc, const unsigned char *mac_dec,
1197                 size_t maclen);
1198 extern int (*mbedtls_ssl_hw_record_activate)(mbedtls_ssl_context *ssl, int direction);
1199 extern int (*mbedtls_ssl_hw_record_reset)(mbedtls_ssl_context *ssl);
1200 extern int (*mbedtls_ssl_hw_record_write)(mbedtls_ssl_context *ssl);
1201 extern int (*mbedtls_ssl_hw_record_read)(mbedtls_ssl_context *ssl);
1202 extern int (*mbedtls_ssl_hw_record_finish)(mbedtls_ssl_context *ssl);
1203 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
1204 
1205 /**
1206  * \brief               Return the name of the ciphersuite associated with the
1207  *                      given ID
1208  *
1209  * \param ciphersuite_id SSL ciphersuite ID
1210  *
1211  * \return              a string containing the ciphersuite name
1212  */
1213 const char *mbedtls_ssl_get_ciphersuite_name( const int ciphersuite_id );
1214 
1215 /**
1216  * \brief               Return the ID of the ciphersuite associated with the
1217  *                      given name
1218  *
1219  * \param ciphersuite_name SSL ciphersuite name
1220  *
1221  * \return              the ID with the ciphersuite or 0 if not found
1222  */
1223 int mbedtls_ssl_get_ciphersuite_id( const char *ciphersuite_name );
1224 
1225 /**
1226  * \brief          Initialize an SSL context
1227  *                 Just makes the context ready for mbedtls_ssl_setup() or
1228  *                 mbedtls_ssl_free()
1229  *
1230  * \param ssl      SSL context
1231  */
1232 void mbedtls_ssl_init( mbedtls_ssl_context *ssl );
1233 
1234 /**
1235  * \brief          Set up an SSL context for use
1236  *
1237  * \note           No copy of the configuration context is made, it can be
1238  *                 shared by many mbedtls_ssl_context structures.
1239  *
1240  * \warning        The conf structure will be accessed during the session.
1241  *                 It must not be modified or freed as long as the session
1242  *                 is active.
1243  *
1244  * \warning        This function must be called exactly once per context.
1245  *                 Calling mbedtls_ssl_setup again is not supported, even
1246  *                 if no session is active.
1247  *
1248  * \param ssl      SSL context
1249  * \param conf     SSL configuration to use
1250  *
1251  * \return         0 if successful, or MBEDTLS_ERR_SSL_ALLOC_FAILED if
1252  *                 memory allocation failed
1253  */
1254 int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
1255                        const mbedtls_ssl_config *conf );
1256 
1257 /**
1258  * \brief          Reset an already initialized SSL context for re-use
1259  *                 while retaining application-set variables, function
1260  *                 pointers and data.
1261  *
1262  * \param ssl      SSL context
1263  * \return         0 if successful, or MBEDTLS_ERR_SSL_ALLOC_FAILED,
1264                    MBEDTLS_ERR_SSL_HW_ACCEL_FAILED or
1265  *                 MBEDTLS_ERR_SSL_COMPRESSION_FAILED
1266  */
1267 int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl );
1268 
1269 /**
1270  * \brief          Set the current endpoint type
1271  *
1272  * \param conf     SSL configuration
1273  * \param endpoint must be MBEDTLS_SSL_IS_CLIENT or MBEDTLS_SSL_IS_SERVER
1274  */
1275 void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint );
1276 
1277 /**
1278  * \brief           Set the transport type (TLS or DTLS).
1279  *                  Default: TLS
1280  *
1281  * \note            For DTLS, you must either provide a recv callback that
1282  *                  doesn't block, or one that handles timeouts, see
1283  *                  \c mbedtls_ssl_set_bio(). You also need to provide timer
1284  *                  callbacks with \c mbedtls_ssl_set_timer_cb().
1285  *
1286  * \param conf      SSL configuration
1287  * \param transport transport type:
1288  *                  MBEDTLS_SSL_TRANSPORT_STREAM for TLS,
1289  *                  MBEDTLS_SSL_TRANSPORT_DATAGRAM for DTLS.
1290  */
1291 void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport );
1292 
1293 /**
1294  * \brief          Set the certificate verification mode
1295  *                 Default: NONE on server, REQUIRED on client
1296  *
1297  * \param conf     SSL configuration
1298  * \param authmode can be:
1299  *
1300  *  MBEDTLS_SSL_VERIFY_NONE:      peer certificate is not checked
1301  *                        (default on server)
1302  *                        (insecure on client)
1303  *
1304  *  MBEDTLS_SSL_VERIFY_OPTIONAL:  peer certificate is checked, however the
1305  *                        handshake continues even if verification failed;
1306  *                        mbedtls_ssl_get_verify_result() can be called after the
1307  *                        handshake is complete.
1308  *
1309  *  MBEDTLS_SSL_VERIFY_REQUIRED:  peer *must* present a valid certificate,
1310  *                        handshake is aborted if verification failed.
1311  *                        (default on client)
1312  *
1313  * \note On client, MBEDTLS_SSL_VERIFY_REQUIRED is the recommended mode.
1314  * With MBEDTLS_SSL_VERIFY_OPTIONAL, the user needs to call mbedtls_ssl_get_verify_result() at
1315  * the right time(s), which may not be obvious, while REQUIRED always perform
1316  * the verification as soon as possible. For example, REQUIRED was protecting
1317  * against the "triple handshake" attack even before it was found.
1318  */
1319 void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode );
1320 
1321 #if defined(MBEDTLS_X509_CRT_PARSE_C)
1322 /**
1323  * \brief          Set the verification callback (Optional).
1324  *
1325  *                 If set, the verify callback is called for each
1326  *                 certificate in the chain. For implementation
1327  *                 information, please see \c mbedtls_x509_crt_verify()
1328  *
1329  * \param conf     SSL configuration
1330  * \param f_vrfy   verification function
1331  * \param p_vrfy   verification parameter
1332  */
1333 void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,
1334                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
1335                      void *p_vrfy );
1336 #endif /* MBEDTLS_X509_CRT_PARSE_C */
1337 
1338 /**
1339  * \brief          Set the random number generator callback
1340  *
1341  * \param conf     SSL configuration
1342  * \param f_rng    RNG function
1343  * \param p_rng    RNG parameter
1344  */
1345 void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,
1346                   int (*f_rng)(void *, unsigned char *, size_t),
1347                   void *p_rng );
1348 
1349 /**
1350  * \brief          Set the debug callback
1351  *
1352  *                 The callback has the following argument:
1353  *                 void *           opaque context for the callback
1354  *                 int              debug level
1355  *                 const char *     file name
1356  *                 int              line number
1357  *                 const char *     message
1358  *
1359  * \param conf     SSL configuration
1360  * \param f_dbg    debug function
1361  * \param p_dbg    debug parameter
1362  */
1363 void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
1364                   void (*f_dbg)(void *, int, const char *, int, const char *),
1365                   void  *p_dbg );
1366 
1367 /**
1368  * \brief          Set the underlying BIO callbacks for write, read and
1369  *                 read-with-timeout.
1370  *
1371  * \param ssl      SSL context
1372  * \param p_bio    parameter (context) shared by BIO callbacks
1373  * \param f_send   write callback
1374  * \param f_recv   read callback
1375  * \param f_recv_timeout blocking read callback with timeout.
1376  *
1377  * \note           One of f_recv or f_recv_timeout can be NULL, in which case
1378  *                 the other is used. If both are non-NULL, f_recv_timeout is
1379  *                 used and f_recv is ignored (as if it were NULL).
1380  *
1381  * \note           The two most common use cases are:
1382  *                 - non-blocking I/O, f_recv != NULL, f_recv_timeout == NULL
1383  *                 - blocking I/O, f_recv == NULL, f_recv_timout != NULL
1384  *
1385  * \note           For DTLS, you need to provide either a non-NULL
1386  *                 f_recv_timeout callback, or a f_recv that doesn't block.
1387  *
1388  * \note           See the documentations of \c mbedtls_ssl_sent_t,
1389  *                 \c mbedtls_ssl_recv_t and \c mbedtls_ssl_recv_timeout_t for
1390  *                 the conventions those callbacks must follow.
1391  *
1392  * \note           On some platforms, net_sockets.c provides
1393  *                 \c mbedtls_net_send(), \c mbedtls_net_recv() and
1394  *                 \c mbedtls_net_recv_timeout() that are suitable to be used
1395  *                 here.
1396  */
1397 void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
1398                           void *p_bio,
1399                           mbedtls_ssl_send_t *f_send,
1400                           mbedtls_ssl_recv_t *f_recv,
1401                           mbedtls_ssl_recv_timeout_t *f_recv_timeout );
1402 
1403 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1404 /**
1405  * \brief          Set the Maximum Tranport Unit (MTU).
1406  *                 Special value: 0 means unset (no limit).
1407  *                 This represents the maximum size of a datagram payload
1408  *                 handled by the transport layer (usually UDP) as determined
1409  *                 by the network link and stack. In practice, this controls
1410  *                 the maximum size datagram the DTLS layer will pass to the
1411  *                 \c f_send() callback set using \c mbedtls_ssl_set_bio().
1412  *
1413  * \note           The limit on datagram size is converted to a limit on
1414  *                 record payload by subtracting the current overhead of
1415  *                 encapsulation and encryption/authentication if any.
1416  *
1417  * \note           This can be called at any point during the connection, for
1418  *                 example when a Path Maximum Transfer Unit (PMTU)
1419  *                 estimate becomes available from other sources,
1420  *                 such as lower (or higher) protocol layers.
1421  *
1422  * \note           This setting only controls the size of the packets we send,
1423  *                 and does not restrict the size of the datagrams we're
1424  *                 willing to receive. Client-side, you can request the
1425  *                 server to use smaller records with \c
1426  *                 mbedtls_ssl_conf_max_frag_len().
1427  *
1428  * \note           If both a MTU and a maximum fragment length have been
1429  *                 configured (or negotiated with the peer), the resulting
1430  *                 lower limit on record payload (see first note) is used.
1431  *
1432  * \note           This can only be used to decrease the maximum size
1433  *                 of datagrams (hence records, see first note) sent. It
1434  *                 cannot be used to increase the maximum size of records over
1435  *                 the limit set by #MBEDTLS_SSL_OUT_CONTENT_LEN.
1436  *
1437  * \note           Values lower than the current record layer expansion will
1438  *                 result in an error when trying to send data.
1439  *
1440  * \note           Using record compression together with a non-zero MTU value
1441  *                 will result in an error when trying to send data.
1442  *
1443  * \param ssl      SSL context
1444  * \param mtu      Value of the path MTU in bytes
1445  */
1446 void mbedtls_ssl_set_mtu( mbedtls_ssl_context *ssl, uint16_t mtu );
1447 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1448 
1449 /**
1450  * \brief          Set the timeout period for mbedtls_ssl_read()
1451  *                 (Default: no timeout.)
1452  *
1453  * \param conf     SSL configuration context
1454  * \param timeout  Timeout value in milliseconds.
1455  *                 Use 0 for no timeout (default).
1456  *
1457  * \note           With blocking I/O, this will only work if a non-NULL
1458  *                 \c f_recv_timeout was set with \c mbedtls_ssl_set_bio().
1459  *                 With non-blocking I/O, this will only work if timer
1460  *                 callbacks were set with \c mbedtls_ssl_set_timer_cb().
1461  *
1462  * \note           With non-blocking I/O, you may also skip this function
1463  *                 altogether and handle timeouts at the application layer.
1464  */
1465 void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout );
1466 
1467 /**
1468  * \brief          Set the timer callbacks (Mandatory for DTLS.)
1469  *
1470  * \param ssl      SSL context
1471  * \param p_timer  parameter (context) shared by timer callbacks
1472  * \param f_set_timer   set timer callback
1473  * \param f_get_timer   get timer callback. Must return:
1474  *
1475  * \note           See the documentation of \c mbedtls_ssl_set_timer_t and
1476  *                 \c mbedtls_ssl_get_timer_t for the conventions this pair of
1477  *                 callbacks must follow.
1478  *
1479  * \note           On some platforms, timing.c provides
1480  *                 \c mbedtls_timing_set_delay() and
1481  *                 \c mbedtls_timing_get_delay() that are suitable for using
1482  *                 here, except if using an event-driven style.
1483  *
1484  * \note           See also the "DTLS tutorial" article in our knowledge base.
1485  *                 https://tls.mbed.org/kb/how-to/dtls-tutorial
1486  */
1487 void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
1488                                void *p_timer,
1489                                mbedtls_ssl_set_timer_t *f_set_timer,
1490                                mbedtls_ssl_get_timer_t *f_get_timer );
1491 
1492 /**
1493  * \brief           Callback type: generate and write session ticket
1494  *
1495  * \note            This describes what a callback implementation should do.
1496  *                  This callback should generate an encrypted and
1497  *                  authenticated ticket for the session and write it to the
1498  *                  output buffer. Here, ticket means the opaque ticket part
1499  *                  of the NewSessionTicket structure of RFC 5077.
1500  *
1501  * \param p_ticket  Context for the callback
1502  * \param session   SSL session to be written in the ticket
1503  * \param start     Start of the output buffer
1504  * \param end       End of the output buffer
1505  * \param tlen      On exit, holds the length written
1506  * \param lifetime  On exit, holds the lifetime of the ticket in seconds
1507  *
1508  * \return          0 if successful, or
1509  *                  a specific MBEDTLS_ERR_XXX code.
1510  */
1511 typedef int mbedtls_ssl_ticket_write_t( void *p_ticket,
1512                                         const mbedtls_ssl_session *session,
1513                                         unsigned char *start,
1514                                         const unsigned char *end,
1515                                         size_t *tlen,
1516                                         uint32_t *lifetime );
1517 
1518 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
1519 /**
1520  * \brief           Callback type: Export key block and master secret
1521  *
1522  * \note            This is required for certain uses of TLS, e.g. EAP-TLS
1523  *                  (RFC 5216) and Thread. The key pointers are ephemeral and
1524  *                  therefore must not be stored. The master secret and keys
1525  *                  should not be used directly except as an input to a key
1526  *                  derivation function.
1527  *
1528  * \param p_expkey  Context for the callback
1529  * \param ms        Pointer to master secret (fixed length: 48 bytes)
1530  * \param kb        Pointer to key block, see RFC 5246 section 6.3
1531  *                  (variable length: 2 * maclen + 2 * keylen + 2 * ivlen).
1532  * \param maclen    MAC length
1533  * \param keylen    Key length
1534  * \param ivlen     IV length
1535  *
1536  * \return          0 if successful, or
1537  *                  a specific MBEDTLS_ERR_XXX code.
1538  */
1539 typedef int mbedtls_ssl_export_keys_t( void *p_expkey,
1540                                 const unsigned char *ms,
1541                                 const unsigned char *kb,
1542                                 size_t maclen,
1543                                 size_t keylen,
1544                                 size_t ivlen );
1545 #endif /* MBEDTLS_SSL_EXPORT_KEYS */
1546 
1547 /**
1548  * \brief           Callback type: parse and load session ticket
1549  *
1550  * \note            This describes what a callback implementation should do.
1551  *                  This callback should parse a session ticket as generated
1552  *                  by the corresponding mbedtls_ssl_ticket_write_t function,
1553  *                  and, if the ticket is authentic and valid, load the
1554  *                  session.
1555  *
1556  * \note            The implementation is allowed to modify the first len
1557  *                  bytes of the input buffer, eg to use it as a temporary
1558  *                  area for the decrypted ticket contents.
1559  *
1560  * \param p_ticket  Context for the callback
1561  * \param session   SSL session to be loaded
1562  * \param buf       Start of the buffer containing the ticket
1563  * \param len       Length of the ticket.
1564  *
1565  * \return          0 if successful, or
1566  *                  MBEDTLS_ERR_SSL_INVALID_MAC if not authentic, or
1567  *                  MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED if expired, or
1568  *                  any other non-zero code for other failures.
1569  */
1570 typedef int mbedtls_ssl_ticket_parse_t( void *p_ticket,
1571                                         mbedtls_ssl_session *session,
1572                                         unsigned char *buf,
1573                                         size_t len );
1574 
1575 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_SRV_C)
1576 /**
1577  * \brief           Configure SSL session ticket callbacks (server only).
1578  *                  (Default: none.)
1579  *
1580  * \note            On server, session tickets are enabled by providing
1581  *                  non-NULL callbacks.
1582  *
1583  * \note            On client, use \c mbedtls_ssl_conf_session_tickets().
1584  *
1585  * \param conf      SSL configuration context
1586  * \param f_ticket_write    Callback for writing a ticket
1587  * \param f_ticket_parse    Callback for parsing a ticket
1588  * \param p_ticket          Context shared by the two callbacks
1589  */
1590 void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,
1591         mbedtls_ssl_ticket_write_t *f_ticket_write,
1592         mbedtls_ssl_ticket_parse_t *f_ticket_parse,
1593         void *p_ticket );
1594 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_SRV_C */
1595 
1596 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
1597 /**
1598  * \brief           Configure key export callback.
1599  *                  (Default: none.)
1600  *
1601  * \note            See \c mbedtls_ssl_export_keys_t.
1602  *
1603  * \param conf      SSL configuration context
1604  * \param f_export_keys     Callback for exporting keys
1605  * \param p_export_keys     Context for the callback
1606  */
1607 void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,
1608         mbedtls_ssl_export_keys_t *f_export_keys,
1609         void *p_export_keys );
1610 #endif /* MBEDTLS_SSL_EXPORT_KEYS */
1611 
1612 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
1613 /**
1614  * \brief           Configure asynchronous private key operation callbacks.
1615  *
1616  * \param conf              SSL configuration context
1617  * \param f_async_sign      Callback to start a signature operation. See
1618  *                          the description of ::mbedtls_ssl_async_sign_t
1619  *                          for more information. This may be \c NULL if the
1620  *                          external processor does not support any signature
1621  *                          operation; in this case the private key object
1622  *                          associated with the certificate will be used.
1623  * \param f_async_decrypt   Callback to start a decryption operation. See
1624  *                          the description of ::mbedtls_ssl_async_decrypt_t
1625  *                          for more information. This may be \c NULL if the
1626  *                          external processor does not support any decryption
1627  *                          operation; in this case the private key object
1628  *                          associated with the certificate will be used.
1629  * \param f_async_resume    Callback to resume an asynchronous operation. See
1630  *                          the description of ::mbedtls_ssl_async_resume_t
1631  *                          for more information. This may not be \c NULL unless
1632  *                          \p f_async_sign and \p f_async_decrypt are both
1633  *                          \c NULL.
1634  * \param f_async_cancel    Callback to cancel an asynchronous operation. See
1635  *                          the description of ::mbedtls_ssl_async_cancel_t
1636  *                          for more information. This may be \c NULL if
1637  *                          no cleanup is needed.
1638  * \param config_data       A pointer to configuration data which can be
1639  *                          retrieved with
1640  *                          mbedtls_ssl_conf_get_async_config_data(). The
1641  *                          library stores this value without dereferencing it.
1642  */
1643 void mbedtls_ssl_conf_async_private_cb( mbedtls_ssl_config *conf,
1644                                         mbedtls_ssl_async_sign_t *f_async_sign,
1645                                         mbedtls_ssl_async_decrypt_t *f_async_decrypt,
1646                                         mbedtls_ssl_async_resume_t *f_async_resume,
1647                                         mbedtls_ssl_async_cancel_t *f_async_cancel,
1648                                         void *config_data );
1649 
1650 /**
1651  * \brief           Retrieve the configuration data set by
1652  *                  mbedtls_ssl_conf_async_private_cb().
1653  *
1654  * \param conf      SSL configuration context
1655  * \return          The configuration data set by
1656  *                  mbedtls_ssl_conf_async_private_cb().
1657  */
1658 void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf );
1659 
1660 /**
1661  * \brief           Retrieve the asynchronous operation user context.
1662  *
1663  * \note            This function may only be called while a handshake
1664  *                  is in progress.
1665  *
1666  * \param ssl       The SSL context to access.
1667  *
1668  * \return          The asynchronous operation user context that was last
1669  *                  set during the current handshake. If
1670  *                  mbedtls_ssl_set_async_operation_data() has not yet been
1671  *                  called during the current handshake, this function returns
1672  *                  \c NULL.
1673  */
1674 void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl );
1675 
1676 /**
1677  * \brief           Retrieve the asynchronous operation user context.
1678  *
1679  * \note            This function may only be called while a handshake
1680  *                  is in progress.
1681  *
1682  * \param ssl       The SSL context to access.
1683  * \param ctx       The new value of the asynchronous operation user context.
1684  *                  Call mbedtls_ssl_get_async_operation_data() later during the
1685  *                  same handshake to retrieve this value.
1686  */
1687 void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl,
1688                                  void *ctx );
1689 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
1690 
1691 /**
1692  * \brief          Callback type: generate a cookie
1693  *
1694  * \param ctx      Context for the callback
1695  * \param p        Buffer to write to,
1696  *                 must be updated to point right after the cookie
1697  * \param end      Pointer to one past the end of the output buffer
1698  * \param info     Client ID info that was passed to
1699  *                 \c mbedtls_ssl_set_client_transport_id()
1700  * \param ilen     Length of info in bytes
1701  *
1702  * \return         The callback must return 0 on success,
1703  *                 or a negative error code.
1704  */
1705 typedef int mbedtls_ssl_cookie_write_t( void *ctx,
1706                                 unsigned char **p, unsigned char *end,
1707                                 const unsigned char *info, size_t ilen );
1708 
1709 /**
1710  * \brief          Callback type: verify a cookie
1711  *
1712  * \param ctx      Context for the callback
1713  * \param cookie   Cookie to verify
1714  * \param clen     Length of cookie
1715  * \param info     Client ID info that was passed to
1716  *                 \c mbedtls_ssl_set_client_transport_id()
1717  * \param ilen     Length of info in bytes
1718  *
1719  * \return         The callback must return 0 if cookie is valid,
1720  *                 or a negative error code.
1721  */
1722 typedef int mbedtls_ssl_cookie_check_t( void *ctx,
1723                                 const unsigned char *cookie, size_t clen,
1724                                 const unsigned char *info, size_t ilen );
1725 
1726 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
1727 /**
1728  * \brief           Register callbacks for DTLS cookies
1729  *                  (Server only. DTLS only.)
1730  *
1731  *                  Default: dummy callbacks that fail, in order to force you to
1732  *                  register working callbacks (and initialize their context).
1733  *
1734  *                  To disable HelloVerifyRequest, register NULL callbacks.
1735  *
1736  * \warning         Disabling hello verification allows your server to be used
1737  *                  for amplification in DoS attacks against other hosts.
1738  *                  Only disable if you known this can't happen in your
1739  *                  particular environment.
1740  *
1741  * \note            See comments on \c mbedtls_ssl_handshake() about handling
1742  *                  the MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED that is expected
1743  *                  on the first handshake attempt when this is enabled.
1744  *
1745  * \note            This is also necessary to handle client reconnection from
1746  *                  the same port as described in RFC 6347 section 4.2.8 (only
1747  *                  the variant with cookies is supported currently). See
1748  *                  comments on \c mbedtls_ssl_read() for details.
1749  *
1750  * \param conf              SSL configuration
1751  * \param f_cookie_write    Cookie write callback
1752  * \param f_cookie_check    Cookie check callback
1753  * \param p_cookie          Context for both callbacks
1754  */
1755 void mbedtls_ssl_conf_dtls_cookies( mbedtls_ssl_config *conf,
1756                            mbedtls_ssl_cookie_write_t *f_cookie_write,
1757                            mbedtls_ssl_cookie_check_t *f_cookie_check,
1758                            void *p_cookie );
1759 
1760 /**
1761  * \brief          Set client's transport-level identification info.
1762  *                 (Server only. DTLS only.)
1763  *
1764  *                 This is usually the IP address (and port), but could be
1765  *                 anything identify the client depending on the underlying
1766  *                 network stack. Used for HelloVerifyRequest with DTLS.
1767  *                 This is *not* used to route the actual packets.
1768  *
1769  * \param ssl      SSL context
1770  * \param info     Transport-level info identifying the client (eg IP + port)
1771  * \param ilen     Length of info in bytes
1772  *
1773  * \note           An internal copy is made, so the info buffer can be reused.
1774  *
1775  * \return         0 on success,
1776  *                 MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used on client,
1777  *                 MBEDTLS_ERR_SSL_ALLOC_FAILED if out of memory.
1778  */
1779 int mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl,
1780                                  const unsigned char *info,
1781                                  size_t ilen );
1782 
1783 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
1784 
1785 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
1786 /**
1787  * \brief          Enable or disable anti-replay protection for DTLS.
1788  *                 (DTLS only, no effect on TLS.)
1789  *                 Default: enabled.
1790  *
1791  * \param conf     SSL configuration
1792  * \param mode     MBEDTLS_SSL_ANTI_REPLAY_ENABLED or MBEDTLS_SSL_ANTI_REPLAY_DISABLED.
1793  *
1794  * \warning        Disabling this is a security risk unless the application
1795  *                 protocol handles duplicated packets in a safe way. You
1796  *                 should not disable this without careful consideration.
1797  *                 However, if your application already detects duplicated
1798  *                 packets and needs information about them to adjust its
1799  *                 transmission strategy, then you'll want to disable this.
1800  */
1801 void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode );
1802 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
1803 
1804 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
1805 /**
1806  * \brief          Set a limit on the number of records with a bad MAC
1807  *                 before terminating the connection.
1808  *                 (DTLS only, no effect on TLS.)
1809  *                 Default: 0 (disabled).
1810  *
1811  * \param conf     SSL configuration
1812  * \param limit    Limit, or 0 to disable.
1813  *
1814  * \note           If the limit is N, then the connection is terminated when
1815  *                 the Nth non-authentic record is seen.
1816  *
1817  * \note           Records with an invalid header are not counted, only the
1818  *                 ones going through the authentication-decryption phase.
1819  *
1820  * \note           This is a security trade-off related to the fact that it's
1821  *                 often relatively easy for an active attacker ot inject UDP
1822  *                 datagrams. On one hand, setting a low limit here makes it
1823  *                 easier for such an attacker to forcibly terminated a
1824  *                 connection. On the other hand, a high limit or no limit
1825  *                 might make us waste resources checking authentication on
1826  *                 many bogus packets.
1827  */
1828 void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit );
1829 #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */
1830 
1831 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1832 
1833 /**
1834  * \brief          Allow or disallow packing of multiple handshake records
1835  *                 within a single datagram.
1836  *
1837  * \param ssl           The SSL context to configure.
1838  * \param allow_packing This determines whether datagram packing may
1839  *                      be used or not. A value of \c 0 means that every
1840  *                      record will be sent in a separate datagram; a
1841  *                      value of \c 1 means that, if space permits,
1842  *                      multiple handshake messages (including CCS) belonging to
1843  *                      a single flight may be packed within a single datagram.
1844  *
1845  * \note           This is enabled by default and should only be disabled
1846  *                 for test purposes, or if datagram packing causes
1847  *                 interoperability issues with peers that don't support it.
1848  *
1849  * \note           Allowing datagram packing reduces the network load since
1850  *                 there's less overhead if multiple messages share the same
1851  *                 datagram. Also, it increases the handshake efficiency
1852  *                 since messages belonging to a single datagram will not
1853  *                 be reordered in transit, and so future message buffering
1854  *                 or flight retransmission (if no buffering is used) as
1855  *                 means to deal with reordering are needed less frequently.
1856  *
1857  * \note           Application records are not affected by this option and
1858  *                 are currently always sent in separate datagrams.
1859  *
1860  */
1861 void mbedtls_ssl_set_datagram_packing( mbedtls_ssl_context *ssl,
1862                                        unsigned allow_packing );
1863 
1864 /**
1865  * \brief          Set retransmit timeout values for the DTLS handshake.
1866  *                 (DTLS only, no effect on TLS.)
1867  *
1868  * \param conf     SSL configuration
1869  * \param min      Initial timeout value in milliseconds.
1870  *                 Default: 1000 (1 second).
1871  * \param max      Maximum timeout value in milliseconds.
1872  *                 Default: 60000 (60 seconds).
1873  *
1874  * \note           Default values are from RFC 6347 section 4.2.4.1.
1875  *
1876  * \note           The 'min' value should typically be slightly above the
1877  *                 expected round-trip time to your peer, plus whatever time
1878  *                 it takes for the peer to process the message. For example,
1879  *                 if your RTT is about 600ms and you peer needs up to 1s to
1880  *                 do the cryptographic operations in the handshake, then you
1881  *                 should set 'min' slightly above 1600. Lower values of 'min'
1882  *                 might cause spurious resends which waste network resources,
1883  *                 while larger value of 'min' will increase overall latency
1884  *                 on unreliable network links.
1885  *
1886  * \note           The more unreliable your network connection is, the larger
1887  *                 your max / min ratio needs to be in order to achieve
1888  *                 reliable handshakes.
1889  *
1890  * \note           Messages are retransmitted up to log2(ceil(max/min)) times.
1891  *                 For example, if min = 1s and max = 5s, the retransmit plan
1892  *                 goes: send ... 1s -> resend ... 2s -> resend ... 4s ->
1893  *                 resend ... 5s -> give up and return a timeout error.
1894  */
1895 void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max );
1896 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1897 
1898 #if defined(MBEDTLS_SSL_SRV_C)
1899 /**
1900  * \brief          Set the session cache callbacks (server-side only)
1901  *                 If not set, no session resuming is done (except if session
1902  *                 tickets are enabled too).
1903  *
1904  *                 The session cache has the responsibility to check for stale
1905  *                 entries based on timeout. See RFC 5246 for recommendations.
1906  *
1907  *                 Warning: session.peer_cert is cleared by the SSL/TLS layer on
1908  *                 connection shutdown, so do not cache the pointer! Either set
1909  *                 it to NULL or make a full copy of the certificate.
1910  *
1911  *                 The get callback is called once during the initial handshake
1912  *                 to enable session resuming. The get function has the
1913  *                 following parameters: (void *parameter, mbedtls_ssl_session *session)
1914  *                 If a valid entry is found, it should fill the master of
1915  *                 the session object with the cached values and return 0,
1916  *                 return 1 otherwise. Optionally peer_cert can be set as well
1917  *                 if it is properly present in cache entry.
1918  *
1919  *                 The set callback is called once during the initial handshake
1920  *                 to enable session resuming after the entire handshake has
1921  *                 been finished. The set function has the following parameters:
1922  *                 (void *parameter, const mbedtls_ssl_session *session). The function
1923  *                 should create a cache entry for future retrieval based on
1924  *                 the data in the session structure and should keep in mind
1925  *                 that the mbedtls_ssl_session object presented (and all its referenced
1926  *                 data) is cleared by the SSL/TLS layer when the connection is
1927  *                 terminated. It is recommended to add metadata to determine if
1928  *                 an entry is still valid in the future. Return 0 if
1929  *                 successfully cached, return 1 otherwise.
1930  *
1931  * \param conf           SSL configuration
1932  * \param p_cache        parmater (context) for both callbacks
1933  * \param f_get_cache    session get callback
1934  * \param f_set_cache    session set callback
1935  */
1936 void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
1937         void *p_cache,
1938         int (*f_get_cache)(void *, mbedtls_ssl_session *),
1939         int (*f_set_cache)(void *, const mbedtls_ssl_session *) );
1940 #endif /* MBEDTLS_SSL_SRV_C */
1941 
1942 #if defined(MBEDTLS_SSL_CLI_C)
1943 /**
1944  * \brief          Request resumption of session (client-side only)
1945  *                 Session data is copied from presented session structure.
1946  *
1947  * \param ssl      SSL context
1948  * \param session  session context
1949  *
1950  * \return         0 if successful,
1951  *                 MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed,
1952  *                 MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used server-side or
1953  *                 arguments are otherwise invalid
1954  *
1955  * \sa             mbedtls_ssl_get_session()
1956  */
1957 int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session );
1958 #endif /* MBEDTLS_SSL_CLI_C */
1959 
1960 /**
1961  * \brief               Set the list of allowed ciphersuites and the preference
1962  *                      order. First in the list has the highest preference.
1963  *                      (Overrides all version-specific lists)
1964  *
1965  *                      The ciphersuites array is not copied, and must remain
1966  *                      valid for the lifetime of the ssl_config.
1967  *
1968  *                      Note: The server uses its own preferences
1969  *                      over the preference of the client unless
1970  *                      MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE is defined!
1971  *
1972  * \param conf          SSL configuration
1973  * \param ciphersuites  0-terminated list of allowed ciphersuites
1974  */
1975 void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
1976                                    const int *ciphersuites );
1977 
1978 /**
1979  * \brief               Set the list of allowed ciphersuites and the
1980  *                      preference order for a specific version of the protocol.
1981  *                      (Only useful on the server side)
1982  *
1983  *                      The ciphersuites array is not copied, and must remain
1984  *                      valid for the lifetime of the ssl_config.
1985  *
1986  * \param conf          SSL configuration
1987  * \param ciphersuites  0-terminated list of allowed ciphersuites
1988  * \param major         Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3
1989  *                      supported)
1990  * \param minor         Minor version number (MBEDTLS_SSL_MINOR_VERSION_0,
1991  *                      MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2,
1992  *                      MBEDTLS_SSL_MINOR_VERSION_3 supported)
1993  *
1994  * \note                With DTLS, use MBEDTLS_SSL_MINOR_VERSION_2 for DTLS 1.0
1995  *                      and MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2
1996  */
1997 void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
1998                                        const int *ciphersuites,
1999                                        int major, int minor );
2000 
2001 #if defined(MBEDTLS_X509_CRT_PARSE_C)
2002 /**
2003  * \brief          Set the X.509 security profile used for verification
2004  *
2005  * \note           The restrictions are enforced for all certificates in the
2006  *                 chain. However, signatures in the handshake are not covered
2007  *                 by this setting but by \b mbedtls_ssl_conf_sig_hashes().
2008  *
2009  * \param conf     SSL configuration
2010  * \param profile  Profile to use
2011  */
2012 void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
2013                                     const mbedtls_x509_crt_profile *profile );
2014 
2015 /**
2016  * \brief          Set the data required to verify peer certificate
2017  *
2018  * \note           See \c mbedtls_x509_crt_verify() for notes regarding the
2019  *                 parameters ca_chain (maps to trust_ca for that function)
2020  *                 and ca_crl.
2021  *
2022  * \param conf     SSL configuration
2023  * \param ca_chain trusted CA chain (meaning all fully trusted top-level CAs)
2024  * \param ca_crl   trusted CA CRLs
2025  */
2026 void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
2027                                mbedtls_x509_crt *ca_chain,
2028                                mbedtls_x509_crl *ca_crl );
2029 
2030 /**
2031  * \brief          Set own certificate chain and private key
2032  *
2033  * \note           own_cert should contain in order from the bottom up your
2034  *                 certificate chain. The top certificate (self-signed)
2035  *                 can be omitted.
2036  *
2037  * \note           On server, this function can be called multiple times to
2038  *                 provision more than one cert/key pair (eg one ECDSA, one
2039  *                 RSA with SHA-256, one RSA with SHA-1). An adequate
2040  *                 certificate will be selected according to the client's
2041  *                 advertised capabilities. In case mutliple certificates are
2042  *                 adequate, preference is given to the one set by the first
2043  *                 call to this function, then second, etc.
2044  *
2045  * \note           On client, only the first call has any effect. That is,
2046  *                 only one client certificate can be provisioned. The
2047  *                 server's preferences in its CertficateRequest message will
2048  *                 be ignored and our only cert will be sent regardless of
2049  *                 whether it matches those preferences - the server can then
2050  *                 decide what it wants to do with it.
2051  *
2052  * \note           The provided \p pk_key needs to match the public key in the
2053  *                 first certificate in \p own_cert, or all handshakes using
2054  *                 that certificate will fail. It is your responsibility
2055  *                 to ensure that; this function will not perform any check.
2056  *                 You may use mbedtls_pk_check_pair() in order to perform
2057  *                 this check yourself, but be aware that this function can
2058  *                 be computationally expensive on some key types.
2059  *
2060  * \param conf     SSL configuration
2061  * \param own_cert own public certificate chain
2062  * \param pk_key   own private key
2063  *
2064  * \return         0 on success or MBEDTLS_ERR_SSL_ALLOC_FAILED
2065  */
2066 int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
2067                               mbedtls_x509_crt *own_cert,
2068                               mbedtls_pk_context *pk_key );
2069 #endif /* MBEDTLS_X509_CRT_PARSE_C */
2070 
2071 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
2072 /**
2073  * \brief          Set the Pre Shared Key (PSK) and the expected identity name
2074  *
2075  * \note           This is mainly useful for clients. Servers will usually
2076  *                 want to use \c mbedtls_ssl_conf_psk_cb() instead.
2077  *
2078  * \note           Currently clients can only register one pre-shared key.
2079  *                 In other words, the servers' identity hint is ignored.
2080  *                 Support for setting multiple PSKs on clients and selecting
2081  *                 one based on the identity hint is not a planned feature but
2082  *                 feedback is welcomed.
2083  *
2084  * \param conf     SSL configuration
2085  * \param psk      pointer to the pre-shared key
2086  * \param psk_len  pre-shared key length
2087  * \param psk_identity      pointer to the pre-shared key identity
2088  * \param psk_identity_len  identity key length
2089  *
2090  * \return         0 if successful or MBEDTLS_ERR_SSL_ALLOC_FAILED
2091  */
2092 int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
2093                 const unsigned char *psk, size_t psk_len,
2094                 const unsigned char *psk_identity, size_t psk_identity_len );
2095 
2096 
2097 /**
2098  * \brief          Set the Pre Shared Key (PSK) for the current handshake
2099  *
2100  * \note           This should only be called inside the PSK callback,
2101  *                 ie the function passed to \c mbedtls_ssl_conf_psk_cb().
2102  *
2103  * \param ssl      SSL context
2104  * \param psk      pointer to the pre-shared key
2105  * \param psk_len  pre-shared key length
2106  *
2107  * \return         0 if successful or MBEDTLS_ERR_SSL_ALLOC_FAILED
2108  */
2109 int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,
2110                             const unsigned char *psk, size_t psk_len );
2111 
2112 /**
2113  * \brief          Set the PSK callback (server-side only).
2114  *
2115  *                 If set, the PSK callback is called for each
2116  *                 handshake where a PSK ciphersuite was negotiated.
2117  *                 The caller provides the identity received and wants to
2118  *                 receive the actual PSK data and length.
2119  *
2120  *                 The callback has the following parameters: (void *parameter,
2121  *                 mbedtls_ssl_context *ssl, const unsigned char *psk_identity,
2122  *                 size_t identity_len)
2123  *                 If a valid PSK identity is found, the callback should use
2124  *                 \c mbedtls_ssl_set_hs_psk() on the ssl context to set the
2125  *                 correct PSK and return 0.
2126  *                 Any other return value will result in a denied PSK identity.
2127  *
2128  * \note           If you set a PSK callback using this function, then you
2129  *                 don't need to set a PSK key and identity using
2130  *                 \c mbedtls_ssl_conf_psk().
2131  *
2132  * \param conf     SSL configuration
2133  * \param f_psk    PSK identity function
2134  * \param p_psk    PSK identity parameter
2135  */
2136 void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
2137                      int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
2138                                   size_t),
2139                      void *p_psk );
2140 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
2141 
2142 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
2143 
2144 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
2145 
2146 #if defined(MBEDTLS_DEPRECATED_WARNING)
2147 #define MBEDTLS_DEPRECATED    __attribute__((deprecated))
2148 #else
2149 #define MBEDTLS_DEPRECATED
2150 #endif
2151 
2152 /**
2153  * \brief          Set the Diffie-Hellman public P and G values,
2154  *                 read as hexadecimal strings (server-side only)
2155  *                 (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG])
2156  *
2157  * \param conf     SSL configuration
2158  * \param dhm_P    Diffie-Hellman-Merkle modulus
2159  * \param dhm_G    Diffie-Hellman-Merkle generator
2160  *
2161  * \deprecated     Superseded by \c mbedtls_ssl_conf_dh_param_bin.
2162  *
2163  * \return         0 if successful
2164  */
2165 MBEDTLS_DEPRECATED int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf,
2166                                                   const char *dhm_P,
2167                                                   const char *dhm_G );
2168 
2169 #endif /* MBEDTLS_DEPRECATED_REMOVED */
2170 
2171 /**
2172  * \brief          Set the Diffie-Hellman public P and G values
2173  *                 from big-endian binary presentations.
2174  *                 (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG]_BIN)
2175  *
2176  * \param conf     SSL configuration
2177  * \param dhm_P    Diffie-Hellman-Merkle modulus in big-endian binary form
2178  * \param P_len    Length of DHM modulus
2179  * \param dhm_G    Diffie-Hellman-Merkle generator in big-endian binary form
2180  * \param G_len    Length of DHM generator
2181  *
2182  * \return         0 if successful
2183  */
2184 int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,
2185                                    const unsigned char *dhm_P, size_t P_len,
2186                                    const unsigned char *dhm_G,  size_t G_len );
2187 
2188 /**
2189  * \brief          Set the Diffie-Hellman public P and G values,
2190  *                 read from existing context (server-side only)
2191  *
2192  * \param conf     SSL configuration
2193  * \param dhm_ctx  Diffie-Hellman-Merkle context
2194  *
2195  * \return         0 if successful
2196  */
2197 int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx );
2198 #endif /* MBEDTLS_DHM_C && defined(MBEDTLS_SSL_SRV_C) */
2199 
2200 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
2201 /**
2202  * \brief          Set the minimum length for Diffie-Hellman parameters.
2203  *                 (Client-side only.)
2204  *                 (Default: 1024 bits.)
2205  *
2206  * \param conf     SSL configuration
2207  * \param bitlen   Minimum bit length of the DHM prime
2208  */
2209 void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,
2210                                       unsigned int bitlen );
2211 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
2212 
2213 #if defined(MBEDTLS_ECP_C)
2214 /**
2215  * \brief          Set the allowed curves in order of preference.
2216  *                 (Default: all defined curves.)
2217  *
2218  *                 On server: this only affects selection of the ECDHE curve;
2219  *                 the curves used for ECDH and ECDSA are determined by the
2220  *                 list of available certificates instead.
2221  *
2222  *                 On client: this affects the list of curves offered for any
2223  *                 use. The server can override our preference order.
2224  *
2225  *                 Both sides: limits the set of curves accepted for use in
2226  *                 ECDHE and in the peer's end-entity certificate.
2227  *
2228  * \note           This has no influence on which curves are allowed inside the
2229  *                 certificate chains, see \c mbedtls_ssl_conf_cert_profile()
2230  *                 for that. For the end-entity certificate however, the key
2231  *                 will be accepted only if it is allowed both by this list
2232  *                 and by the cert profile.
2233  *
2234  * \note           This list should be ordered by decreasing preference
2235  *                 (preferred curve first).
2236  *
2237  * \param conf     SSL configuration
2238  * \param curves   Ordered list of allowed curves,
2239  *                 terminated by MBEDTLS_ECP_DP_NONE.
2240  */
2241 void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
2242                               const mbedtls_ecp_group_id *curves );
2243 #endif /* MBEDTLS_ECP_C */
2244 
2245 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
2246 /**
2247  * \brief          Set the allowed hashes for signatures during the handshake.
2248  *                 (Default: all available hashes except MD5.)
2249  *
2250  * \note           This only affects which hashes are offered and can be used
2251  *                 for signatures during the handshake. Hashes for message
2252  *                 authentication and the TLS PRF are controlled by the
2253  *                 ciphersuite, see \c mbedtls_ssl_conf_ciphersuites(). Hashes
2254  *                 used for certificate signature are controlled by the
2255  *                 verification profile, see \c mbedtls_ssl_conf_cert_profile().
2256  *
2257  * \note           This list should be ordered by decreasing preference
2258  *                 (preferred hash first).
2259  *
2260  * \param conf     SSL configuration
2261  * \param hashes   Ordered list of allowed signature hashes,
2262  *                 terminated by \c MBEDTLS_MD_NONE.
2263  */
2264 void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
2265                                   const int *hashes );
2266 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
2267 
2268 #if defined(MBEDTLS_X509_CRT_PARSE_C)
2269 /**
2270  * \brief          Set or reset the hostname to check against the received
2271  *                 server certificate. It sets the ServerName TLS extension,
2272  *                 too, if that extension is enabled. (client-side only)
2273  *
2274  * \param ssl      SSL context
2275  * \param hostname the server hostname, may be NULL to clear hostname
2276 
2277  * \note           Maximum hostname length MBEDTLS_SSL_MAX_HOST_NAME_LEN.
2278  *
2279  * \return         0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on
2280  *                 allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on
2281  *                 too long input hostname.
2282  *
2283  *                 Hostname set to the one provided on success (cleared
2284  *                 when NULL). On allocation failure hostname is cleared.
2285  *                 On too long input failure, old hostname is unchanged.
2286  */
2287 int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname );
2288 #endif /* MBEDTLS_X509_CRT_PARSE_C */
2289 
2290 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2291 /**
2292  * \brief          Set own certificate and key for the current handshake
2293  *
2294  * \note           Same as \c mbedtls_ssl_conf_own_cert() but for use within
2295  *                 the SNI callback.
2296  *
2297  * \param ssl      SSL context
2298  * \param own_cert own public certificate chain
2299  * \param pk_key   own private key
2300  *
2301  * \return         0 on success or MBEDTLS_ERR_SSL_ALLOC_FAILED
2302  */
2303 int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,
2304                                  mbedtls_x509_crt *own_cert,
2305                                  mbedtls_pk_context *pk_key );
2306 
2307 /**
2308  * \brief          Set the data required to verify peer certificate for the
2309  *                 current handshake
2310  *
2311  * \note           Same as \c mbedtls_ssl_conf_ca_chain() but for use within
2312  *                 the SNI callback.
2313  *
2314  * \param ssl      SSL context
2315  * \param ca_chain trusted CA chain (meaning all fully trusted top-level CAs)
2316  * \param ca_crl   trusted CA CRLs
2317  */
2318 void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,
2319                                   mbedtls_x509_crt *ca_chain,
2320                                   mbedtls_x509_crl *ca_crl );
2321 
2322 /**
2323  * \brief          Set authmode for the current handshake.
2324  *
2325  * \note           Same as \c mbedtls_ssl_conf_authmode() but for use within
2326  *                 the SNI callback.
2327  *
2328  * \param ssl      SSL context
2329  * \param authmode MBEDTLS_SSL_VERIFY_NONE, MBEDTLS_SSL_VERIFY_OPTIONAL or
2330  *                 MBEDTLS_SSL_VERIFY_REQUIRED
2331  */
2332 void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,
2333                                   int authmode );
2334 
2335 /**
2336  * \brief          Set server side ServerName TLS extension callback
2337  *                 (optional, server-side only).
2338  *
2339  *                 If set, the ServerName callback is called whenever the
2340  *                 server receives a ServerName TLS extension from the client
2341  *                 during a handshake. The ServerName callback has the
2342  *                 following parameters: (void *parameter, mbedtls_ssl_context *ssl,
2343  *                 const unsigned char *hostname, size_t len). If a suitable
2344  *                 certificate is found, the callback must set the
2345  *                 certificate(s) and key(s) to use with \c
2346  *                 mbedtls_ssl_set_hs_own_cert() (can be called repeatedly),
2347  *                 and may optionally adjust the CA and associated CRL with \c
2348  *                 mbedtls_ssl_set_hs_ca_chain() as well as the client
2349  *                 authentication mode with \c mbedtls_ssl_set_hs_authmode(),
2350  *                 then must return 0. If no matching name is found, the
2351  *                 callback must either set a default cert, or
2352  *                 return non-zero to abort the handshake at this point.
2353  *
2354  * \param conf     SSL configuration
2355  * \param f_sni    verification function
2356  * \param p_sni    verification parameter
2357  */
2358 void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
2359                   int (*f_sni)(void *, mbedtls_ssl_context *, const unsigned char *,
2360                                size_t),
2361                   void *p_sni );
2362 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
2363 
2364 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2365 /**
2366  * \brief          Set the EC J-PAKE password for current handshake.
2367  *
2368  * \note           An internal copy is made, and destroyed as soon as the
2369  *                 handshake is completed, or when the SSL context is reset or
2370  *                 freed.
2371  *
2372  * \note           The SSL context needs to be already set up. The right place
2373  *                 to call this function is between \c mbedtls_ssl_setup() or
2374  *                 \c mbedtls_ssl_reset() and \c mbedtls_ssl_handshake().
2375  *
2376  * \param ssl      SSL context
2377  * \param pw       EC J-PAKE password (pre-shared secret)
2378  * \param pw_len   length of pw in bytes
2379  *
2380  * \return         0 on success, or a negative error code.
2381  */
2382 int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
2383                                          const unsigned char *pw,
2384                                          size_t pw_len );
2385 #endif /*MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2386 
2387 #if defined(MBEDTLS_SSL_ALPN)
2388 /**
2389  * \brief          Set the supported Application Layer Protocols.
2390  *
2391  * \param conf     SSL configuration
2392  * \param protos   Pointer to a NULL-terminated list of supported protocols,
2393  *                 in decreasing preference order. The pointer to the list is
2394  *                 recorded by the library for later reference as required, so
2395  *                 the lifetime of the table must be atleast as long as the
2396  *                 lifetime of the SSL configuration structure.
2397  *
2398  * \return         0 on success, or MBEDTLS_ERR_SSL_BAD_INPUT_DATA.
2399  */
2400 int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos );
2401 
2402 /**
2403  * \brief          Get the name of the negotiated Application Layer Protocol.
2404  *                 This function should be called after the handshake is
2405  *                 completed.
2406  *
2407  * \param ssl      SSL context
2408  *
2409  * \return         Protcol name, or NULL if no protocol was negotiated.
2410  */
2411 const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl );
2412 #endif /* MBEDTLS_SSL_ALPN */
2413 
2414 /**
2415  * \brief          Set the maximum supported version sent from the client side
2416  *                 and/or accepted at the server side
2417  *                 (Default: MBEDTLS_SSL_MAX_MAJOR_VERSION, MBEDTLS_SSL_MAX_MINOR_VERSION)
2418  *
2419  * \note           This ignores ciphersuites from higher versions.
2420  *
2421  * \note           With DTLS, use MBEDTLS_SSL_MINOR_VERSION_2 for DTLS 1.0 and
2422  *                 MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2
2423  *
2424  * \param conf     SSL configuration
2425  * \param major    Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3 supported)
2426  * \param minor    Minor version number (MBEDTLS_SSL_MINOR_VERSION_0,
2427  *                 MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2,
2428  *                 MBEDTLS_SSL_MINOR_VERSION_3 supported)
2429  */
2430 void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor );
2431 
2432 /**
2433  * \brief          Set the minimum accepted SSL/TLS protocol version
2434  *                 (Default: TLS 1.0)
2435  *
2436  * \note           Input outside of the SSL_MAX_XXXXX_VERSION and
2437  *                 SSL_MIN_XXXXX_VERSION range is ignored.
2438  *
2439  * \note           MBEDTLS_SSL_MINOR_VERSION_0 (SSL v3) should be avoided.
2440  *
2441  * \note           With DTLS, use MBEDTLS_SSL_MINOR_VERSION_2 for DTLS 1.0 and
2442  *                 MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2
2443  *
2444  * \param conf     SSL configuration
2445  * \param major    Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3 supported)
2446  * \param minor    Minor version number (MBEDTLS_SSL_MINOR_VERSION_0,
2447  *                 MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2,
2448  *                 MBEDTLS_SSL_MINOR_VERSION_3 supported)
2449  */
2450 void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor );
2451 
2452 #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
2453 /**
2454  * \brief          Set the fallback flag (client-side only).
2455  *                 (Default: MBEDTLS_SSL_IS_NOT_FALLBACK).
2456  *
2457  * \note           Set to MBEDTLS_SSL_IS_FALLBACK when preparing a fallback
2458  *                 connection, that is a connection with max_version set to a
2459  *                 lower value than the value you're willing to use. Such
2460  *                 fallback connections are not recommended but are sometimes
2461  *                 necessary to interoperate with buggy (version-intolerant)
2462  *                 servers.
2463  *
2464  * \warning        You should NOT set this to MBEDTLS_SSL_IS_FALLBACK for
2465  *                 non-fallback connections! This would appear to work for a
2466  *                 while, then cause failures when the server is upgraded to
2467  *                 support a newer TLS version.
2468  *
2469  * \param conf     SSL configuration
2470  * \param fallback MBEDTLS_SSL_IS_NOT_FALLBACK or MBEDTLS_SSL_IS_FALLBACK
2471  */
2472 void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback );
2473 #endif /* MBEDTLS_SSL_FALLBACK_SCSV && MBEDTLS_SSL_CLI_C */
2474 
2475 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
2476 /**
2477  * \brief           Enable or disable Encrypt-then-MAC
2478  *                  (Default: MBEDTLS_SSL_ETM_ENABLED)
2479  *
2480  * \note            This should always be enabled, it is a security
2481  *                  improvement, and should not cause any interoperability
2482  *                  issue (used only if the peer supports it too).
2483  *
2484  * \param conf      SSL configuration
2485  * \param etm       MBEDTLS_SSL_ETM_ENABLED or MBEDTLS_SSL_ETM_DISABLED
2486  */
2487 void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm );
2488 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
2489 
2490 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
2491 /**
2492  * \brief           Enable or disable Extended Master Secret negotiation.
2493  *                  (Default: MBEDTLS_SSL_EXTENDED_MS_ENABLED)
2494  *
2495  * \note            This should always be enabled, it is a security fix to the
2496  *                  protocol, and should not cause any interoperability issue
2497  *                  (used only if the peer supports it too).
2498  *
2499  * \param conf      SSL configuration
2500  * \param ems       MBEDTLS_SSL_EXTENDED_MS_ENABLED or MBEDTLS_SSL_EXTENDED_MS_DISABLED
2501  */
2502 void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems );
2503 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
2504 
2505 #if defined(MBEDTLS_ARC4_C)
2506 /**
2507  * \brief          Disable or enable support for RC4
2508  *                 (Default: MBEDTLS_SSL_ARC4_DISABLED)
2509  *
2510  * \warning        Use of RC4 in DTLS/TLS has been prohibited by RFC 7465
2511  *                 for security reasons. Use at your own risk.
2512  *
2513  * \note           This function is deprecated and will likely be removed in
2514  *                 a future version of the library.
2515  *                 RC4 is disabled by default at compile time and needs to be
2516  *                 actively enabled for use with legacy systems.
2517  *
2518  * \param conf     SSL configuration
2519  * \param arc4     MBEDTLS_SSL_ARC4_ENABLED or MBEDTLS_SSL_ARC4_DISABLED
2520  */
2521 void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 );
2522 #endif /* MBEDTLS_ARC4_C */
2523 
2524 #if defined(MBEDTLS_SSL_SRV_C)
2525 /**
2526  * \brief          Whether to send a list of acceptable CAs in
2527  *                 CertificateRequest messages.
2528  *                 (Default: do send)
2529  *
2530  * \param conf     SSL configuration
2531  * \param cert_req_ca_list   MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED or
2532  *                          MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED
2533  */
2534 void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,
2535                                           char cert_req_ca_list );
2536 #endif /* MBEDTLS_SSL_SRV_C */
2537 
2538 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
2539 /**
2540  * \brief          Set the maximum fragment length to emit and/or negotiate
2541  *                 (Default: the smaller of MBEDTLS_SSL_IN_CONTENT_LEN and
2542  *                 MBEDTLS_SSL_OUT_CONTENT_LEN, usually 2^14 bytes)
2543  *                 (Server: set maximum fragment length to emit,
2544  *                 usually negotiated by the client during handshake
2545  *                 (Client: set maximum fragment length to emit *and*
2546  *                 negotiate with the server during handshake)
2547  *
2548  * \note           With TLS, this currently only affects ApplicationData (sent
2549  *                 with \c mbedtls_ssl_read()), not handshake messages.
2550  *                 With DTLS, this affects both ApplicationData and handshake.
2551  *
2552  * \note           This sets the maximum length for a record's payload,
2553  *                 excluding record overhead that will be added to it, see
2554  *                 \c mbedtls_ssl_get_record_expansion().
2555  *
2556  * \note           For DTLS, it is also possible to set a limit for the total
2557  *                 size of daragrams passed to the transport layer, including
2558  *                 record overhead, see \c mbedtls_ssl_set_mtu().
2559  *
2560  * \param conf     SSL configuration
2561  * \param mfl_code Code for maximum fragment length (allowed values:
2562  *                 MBEDTLS_SSL_MAX_FRAG_LEN_512,  MBEDTLS_SSL_MAX_FRAG_LEN_1024,
2563  *                 MBEDTLS_SSL_MAX_FRAG_LEN_2048, MBEDTLS_SSL_MAX_FRAG_LEN_4096)
2564  *
2565  * \return         0 if successful or MBEDTLS_ERR_SSL_BAD_INPUT_DATA
2566  */
2567 int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code );
2568 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
2569 
2570 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
2571 /**
2572  * \brief          Activate negotiation of truncated HMAC
2573  *                 (Default: MBEDTLS_SSL_TRUNC_HMAC_DISABLED)
2574  *
2575  * \param conf     SSL configuration
2576  * \param truncate Enable or disable (MBEDTLS_SSL_TRUNC_HMAC_ENABLED or
2577  *                                    MBEDTLS_SSL_TRUNC_HMAC_DISABLED)
2578  */
2579 void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate );
2580 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
2581 
2582 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
2583 /**
2584  * \brief          Enable / Disable 1/n-1 record splitting
2585  *                 (Default: MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED)
2586  *
2587  * \note           Only affects SSLv3 and TLS 1.0, not higher versions.
2588  *                 Does not affect non-CBC ciphersuites in any version.
2589  *
2590  * \param conf     SSL configuration
2591  * \param split    MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED or
2592  *                 MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED
2593  */
2594 void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split );
2595 #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
2596 
2597 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
2598 /**
2599  * \brief          Enable / Disable session tickets (client only).
2600  *                 (Default: MBEDTLS_SSL_SESSION_TICKETS_ENABLED.)
2601  *
2602  * \note           On server, use \c mbedtls_ssl_conf_session_tickets_cb().
2603  *
2604  * \param conf     SSL configuration
2605  * \param use_tickets   Enable or disable (MBEDTLS_SSL_SESSION_TICKETS_ENABLED or
2606  *                                         MBEDTLS_SSL_SESSION_TICKETS_DISABLED)
2607  */
2608 void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets );
2609 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
2610 
2611 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2612 /**
2613  * \brief          Enable / Disable renegotiation support for connection when
2614  *                 initiated by peer
2615  *                 (Default: MBEDTLS_SSL_RENEGOTIATION_DISABLED)
2616  *
2617  * \warning        It is recommended to always disable renegotation unless you
2618  *                 know you need it and you know what you're doing. In the
2619  *                 past, there have been several issues associated with
2620  *                 renegotiation or a poor understanding of its properties.
2621  *
2622  * \note           Server-side, enabling renegotiation also makes the server
2623  *                 susceptible to a resource DoS by a malicious client.
2624  *
2625  * \param conf    SSL configuration
2626  * \param renegotiation     Enable or disable (MBEDTLS_SSL_RENEGOTIATION_ENABLED or
2627  *                                             MBEDTLS_SSL_RENEGOTIATION_DISABLED)
2628  */
2629 void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation );
2630 #endif /* MBEDTLS_SSL_RENEGOTIATION */
2631 
2632 /**
2633  * \brief          Prevent or allow legacy renegotiation.
2634  *                 (Default: MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION)
2635  *
2636  *                 MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION allows connections to
2637  *                 be established even if the peer does not support
2638  *                 secure renegotiation, but does not allow renegotiation
2639  *                 to take place if not secure.
2640  *                 (Interoperable and secure option)
2641  *
2642  *                 MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION allows renegotiations
2643  *                 with non-upgraded peers. Allowing legacy renegotiation
2644  *                 makes the connection vulnerable to specific man in the
2645  *                 middle attacks. (See RFC 5746)
2646  *                 (Most interoperable and least secure option)
2647  *
2648  *                 MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE breaks off connections
2649  *                 if peer does not support secure renegotiation. Results
2650  *                 in interoperability issues with non-upgraded peers
2651  *                 that do not support renegotiation altogether.
2652  *                 (Most secure option, interoperability issues)
2653  *
2654  * \param conf     SSL configuration
2655  * \param allow_legacy  Prevent or allow (SSL_NO_LEGACY_RENEGOTIATION,
2656  *                                        SSL_ALLOW_LEGACY_RENEGOTIATION or
2657  *                                        MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE)
2658  */
2659 void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy );
2660 
2661 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2662 /**
2663  * \brief          Enforce renegotiation requests.
2664  *                 (Default: enforced, max_records = 16)
2665  *
2666  *                 When we request a renegotiation, the peer can comply or
2667  *                 ignore the request. This function allows us to decide
2668  *                 whether to enforce our renegotiation requests by closing
2669  *                 the connection if the peer doesn't comply.
2670  *
2671  *                 However, records could already be in transit from the peer
2672  *                 when the request is emitted. In order to increase
2673  *                 reliability, we can accept a number of records before the
2674  *                 expected handshake records.
2675  *
2676  *                 The optimal value is highly dependent on the specific usage
2677  *                 scenario.
2678  *
2679  * \note           With DTLS and server-initiated renegotiation, the
2680  *                 HelloRequest is retransmited every time mbedtls_ssl_read() times
2681  *                 out or receives Application Data, until:
2682  *                 - max_records records have beens seen, if it is >= 0, or
2683  *                 - the number of retransmits that would happen during an
2684  *                 actual handshake has been reached.
2685  *                 Please remember the request might be lost a few times
2686  *                 if you consider setting max_records to a really low value.
2687  *
2688  * \warning        On client, the grace period can only happen during
2689  *                 mbedtls_ssl_read(), as opposed to mbedtls_ssl_write() and mbedtls_ssl_renegotiate()
2690  *                 which always behave as if max_record was 0. The reason is,
2691  *                 if we receive application data from the server, we need a
2692  *                 place to write it, which only happens during mbedtls_ssl_read().
2693  *
2694  * \param conf     SSL configuration
2695  * \param max_records Use MBEDTLS_SSL_RENEGOTIATION_NOT_ENFORCED if you don't want to
2696  *                 enforce renegotiation, or a non-negative value to enforce
2697  *                 it but allow for a grace period of max_records records.
2698  */
2699 void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records );
2700 
2701 /**
2702  * \brief          Set record counter threshold for periodic renegotiation.
2703  *                 (Default: 2^48 - 1)
2704  *
2705  *                 Renegotiation is automatically triggered when a record
2706  *                 counter (outgoing or ingoing) crosses the defined
2707  *                 threshold. The default value is meant to prevent the
2708  *                 connection from being closed when the counter is about to
2709  *                 reached its maximal value (it is not allowed to wrap).
2710  *
2711  *                 Lower values can be used to enforce policies such as "keys
2712  *                 must be refreshed every N packets with cipher X".
2713  *
2714  *                 The renegotiation period can be disabled by setting
2715  *                 conf->disable_renegotiation to
2716  *                 MBEDTLS_SSL_RENEGOTIATION_DISABLED.
2717  *
2718  * \note           When the configured transport is
2719  *                 MBEDTLS_SSL_TRANSPORT_DATAGRAM the maximum renegotiation
2720  *                 period is 2^48 - 1, and for MBEDTLS_SSL_TRANSPORT_STREAM,
2721  *                 the maximum renegotiation period is 2^64 - 1.
2722  *
2723  * \param conf     SSL configuration
2724  * \param period   The threshold value: a big-endian 64-bit number.
2725  */
2726 void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
2727                                    const unsigned char period[8] );
2728 #endif /* MBEDTLS_SSL_RENEGOTIATION */
2729 
2730 /**
2731  * \brief          Check if there is data already read from the
2732  *                 underlying transport but not yet processed.
2733  *
2734  * \param ssl      SSL context
2735  *
2736  * \return         0 if nothing's pending, 1 otherwise.
2737  *
2738  * \note           This is different in purpose and behaviour from
2739  *                 \c mbedtls_ssl_get_bytes_avail in that it considers
2740  *                 any kind of unprocessed data, not only unread
2741  *                 application data. If \c mbedtls_ssl_get_bytes
2742  *                 returns a non-zero value, this function will
2743  *                 also signal pending data, but the converse does
2744  *                 not hold. For example, in DTLS there might be
2745  *                 further records waiting to be processed from
2746  *                 the current underlying transport's datagram.
2747  *
2748  * \note           If this function returns 1 (data pending), this
2749  *                 does not imply that a subsequent call to
2750  *                 \c mbedtls_ssl_read will provide any data;
2751  *                 e.g., the unprocessed data might turn out
2752  *                 to be an alert or a handshake message.
2753  *
2754  * \note           This function is useful in the following situation:
2755  *                 If the SSL/TLS module successfully returns from an
2756  *                 operation - e.g. a handshake or an application record
2757  *                 read - and you're awaiting incoming data next, you
2758  *                 must not immediately idle on the underlying transport
2759  *                 to have data ready, but you need to check the value
2760  *                 of this function first. The reason is that the desired
2761  *                 data might already be read but not yet processed.
2762  *                 If, in contrast, a previous call to the SSL/TLS module
2763  *                 returned MBEDTLS_ERR_SSL_WANT_READ, it is not necessary
2764  *                 to call this function, as the latter error code entails
2765  *                 that all internal data has been processed.
2766  *
2767  */
2768 int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl );
2769 
2770 /**
2771  * \brief          Return the number of application data bytes
2772  *                 remaining to be read from the current record.
2773  *
2774  * \param ssl      SSL context
2775  *
2776  * \return         How many bytes are available in the application
2777  *                 data record read buffer.
2778  *
2779  * \note           When working over a datagram transport, this is
2780  *                 useful to detect the current datagram's boundary
2781  *                 in case \c mbedtls_ssl_read has written the maximal
2782  *                 amount of data fitting into the input buffer.
2783  *
2784  */
2785 size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl );
2786 
2787 /**
2788  * \brief          Return the result of the certificate verification
2789  *
2790  * \param ssl      The SSL context to use.
2791  *
2792  * \return         \c 0 if the certificate verification was successful.
2793  * \return         \c -1u if the result is not available. This may happen
2794  *                 e.g. if the handshake aborts early, or a verification
2795  *                 callback returned a fatal error.
2796  * \return         A bitwise combination of \c MBEDTLS_X509_BADCERT_XXX
2797  *                 and \c MBEDTLS_X509_BADCRL_XXX failure flags; see x509.h.
2798  */
2799 uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl );
2800 
2801 /**
2802  * \brief          Return the name of the current ciphersuite
2803  *
2804  * \param ssl      SSL context
2805  *
2806  * \return         a string containing the ciphersuite name
2807  */
2808 const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl );
2809 
2810 /**
2811  * \brief          Return the current SSL version (SSLv3/TLSv1/etc)
2812  *
2813  * \param ssl      SSL context
2814  *
2815  * \return         a string containing the SSL version
2816  */
2817 const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl );
2818 
2819 /**
2820  * \brief          Return the (maximum) number of bytes added by the record
2821  *                 layer: header + encryption/MAC overhead (inc. padding)
2822  *
2823  * \note           This function is not available (always returns an error)
2824  *                 when record compression is enabled.
2825  *
2826  * \param ssl      SSL context
2827  *
2828  * \return         Current maximum record expansion in bytes, or
2829  *                 MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE if compression is
2830  *                 enabled, which makes expansion much less predictable
2831  */
2832 int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl );
2833 
2834 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
2835 /**
2836  * \brief          Return the maximum fragment length (payload, in bytes).
2837  *                 This is the value negotiated with peer if any,
2838  *                 or the locally configured value.
2839  *
2840  * \sa             mbedtls_ssl_conf_max_frag_len()
2841  * \sa             mbedtls_ssl_get_max_record_payload()
2842  *
2843  * \param ssl      SSL context
2844  *
2845  * \return         Current maximum fragment length.
2846  */
2847 size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl );
2848 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
2849 
2850 /**
2851  * \brief          Return the current maximum outgoing record payload in bytes.
2852  *                 This takes into account the config.h setting \c
2853  *                 MBEDTLS_SSL_OUT_CONTENT_LEN, the configured and negotiated
2854  *                 max fragment length extension if used, and for DTLS the
2855  *                 path MTU as configured and current record expansion.
2856  *
2857  * \note           With DTLS, \c mbedtls_ssl_write() will return an error if
2858  *                 called with a larger length value.
2859  *                 With TLS, \c mbedtls_ssl_write() will fragment the input if
2860  *                 necessary and return the number of bytes written; it is up
2861  *                 to the caller to call \c mbedtls_ssl_write() again in
2862  *                 order to send the remaining bytes if any.
2863  *
2864  * \note           This function is not available (always returns an error)
2865  *                 when record compression is enabled.
2866  *
2867  * \sa             mbedtls_ssl_set_mtu()
2868  * \sa             mbedtls_ssl_get_max_frag_len()
2869  * \sa             mbedtls_ssl_get_record_expansion()
2870  *
2871  * \param ssl      SSL context
2872  *
2873  * \return         Current maximum payload for an outgoing record,
2874  *                 or a negative error code.
2875  */
2876 int mbedtls_ssl_get_max_out_record_payload( const mbedtls_ssl_context *ssl );
2877 
2878 #if defined(MBEDTLS_X509_CRT_PARSE_C)
2879 /**
2880  * \brief          Return the peer certificate from the current connection
2881  *
2882  *                 Note: Can be NULL in case no certificate was sent during
2883  *                 the handshake. Different calls for the same connection can
2884  *                 return the same or different pointers for the same
2885  *                 certificate and even a different certificate altogether.
2886  *                 The peer cert CAN change in a single connection if
2887  *                 renegotiation is performed.
2888  *
2889  * \param ssl      SSL context
2890  *
2891  * \return         the current peer certificate
2892  */
2893 const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl );
2894 #endif /* MBEDTLS_X509_CRT_PARSE_C */
2895 
2896 #if defined(MBEDTLS_SSL_CLI_C)
2897 /**
2898  * \brief          Save session in order to resume it later (client-side only)
2899  *                 Session data is copied to presented session structure.
2900  *
2901  *
2902  * \param ssl      SSL context
2903  * \param session  session context
2904  *
2905  * \return         0 if successful,
2906  *                 MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed,
2907  *                 MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used server-side or
2908  *                 arguments are otherwise invalid.
2909  *
2910  * \note           Only the server certificate is copied, and not the full chain,
2911  *                 so you should not attempt to validate the certificate again
2912  *                 by calling \c mbedtls_x509_crt_verify() on it.
2913  *                 Instead, you should use the results from the verification
2914  *                 in the original handshake by calling \c mbedtls_ssl_get_verify_result()
2915  *                 after loading the session again into a new SSL context
2916  *                 using \c mbedtls_ssl_set_session().
2917  *
2918  * \note           Once the session object is not needed anymore, you should
2919  *                 free it by calling \c mbedtls_ssl_session_free().
2920  *
2921  * \sa             mbedtls_ssl_set_session()
2922  */
2923 int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *session );
2924 #endif /* MBEDTLS_SSL_CLI_C */
2925 
2926 /**
2927  * \brief          Perform the SSL handshake
2928  *
2929  * \param ssl      SSL context
2930  *
2931  * \return         \c 0 if successful.
2932  * \return         #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE
2933  *                 if the handshake is incomplete and waiting for data to
2934  *                 be available for reading from or writing to the underlying
2935  *                 transport - in this case you must call this function again
2936  *                 when the underlying transport is ready for the operation.
2937  * \return         #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous
2938  *                 operation is in progress (see
2939  *                 mbedtls_ssl_conf_async_private_cb()) - in this case you
2940  *                 must call this function again when the operation is ready.
2941  * \return         #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic
2942  *                 operation is in progress (see mbedtls_ecp_set_max_ops()) -
2943  *                 in this case you must call this function again to complete
2944  *                 the handshake when you're done attending other tasks.
2945  * \return         #MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED if DTLS is in use
2946  *                 and the client did not demonstrate reachability yet - in
2947  *                 this case you must stop using the context (see below).
2948  * \return         Another SSL error code - in this case you must stop using
2949  *                 the context (see below).
2950  *
2951  * \warning        If this function returns something other than
2952  *                 \c 0,
2953  *                 #MBEDTLS_ERR_SSL_WANT_READ,
2954  *                 #MBEDTLS_ERR_SSL_WANT_WRITE,
2955  *                 #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or
2956  *                 #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS,
2957  *                 you must stop using the SSL context for reading or writing,
2958  *                 and either free it or call \c mbedtls_ssl_session_reset()
2959  *                 on it before re-using it for a new connection; the current
2960  *                 connection must be closed.
2961  *
2962  * \note           If DTLS is in use, then you may choose to handle
2963  *                 #MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED specially for logging
2964  *                 purposes, as it is an expected return value rather than an
2965  *                 actual error, but you still need to reset/free the context.
2966  *
2967  * \note           Remarks regarding event-driven DTLS:
2968  *                 If the function returns #MBEDTLS_ERR_SSL_WANT_READ, no datagram
2969  *                 from the underlying transport layer is currently being processed,
2970  *                 and it is safe to idle until the timer or the underlying transport
2971  *                 signal a new event. This is not true for a successful handshake,
2972  *                 in which case the datagram of the underlying transport that is
2973  *                 currently being processed might or might not contain further
2974  *                 DTLS records.
2975  */
2976 int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl );
2977 
2978 /**
2979  * \brief          Perform a single step of the SSL handshake
2980  *
2981  * \note           The state of the context (ssl->state) will be at
2982  *                 the next state after this function returns \c 0. Do not
2983  *                 call this function if state is MBEDTLS_SSL_HANDSHAKE_OVER.
2984  *
2985  * \param ssl      SSL context
2986  *
2987  * \return         See mbedtls_ssl_handshake().
2988  *
2989  * \warning        If this function returns something other than \c 0,
2990  *                 #MBEDTLS_ERR_SSL_WANT_READ, #MBEDTLS_ERR_SSL_WANT_WRITE,
2991  *                 #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or
2992  *                 #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, you must stop using
2993  *                 the SSL context for reading or writing, and either free it
2994  *                 or call \c mbedtls_ssl_session_reset() on it before
2995  *                 re-using it for a new connection; the current connection
2996  *                 must be closed.
2997  */
2998 int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl );
2999 
3000 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3001 /**
3002  * \brief          Initiate an SSL renegotiation on the running connection.
3003  *                 Client: perform the renegotiation right now.
3004  *                 Server: request renegotiation, which will be performed
3005  *                 during the next call to mbedtls_ssl_read() if honored by
3006  *                 client.
3007  *
3008  * \param ssl      SSL context
3009  *
3010  * \return         0 if successful, or any mbedtls_ssl_handshake() return
3011  *                 value except #MBEDTLS_ERR_SSL_CLIENT_RECONNECT that can't
3012  *                 happen during a renegotiation.
3013  *
3014  * \warning        If this function returns something other than \c 0,
3015  *                 #MBEDTLS_ERR_SSL_WANT_READ, #MBEDTLS_ERR_SSL_WANT_WRITE,
3016  *                 #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or
3017  *                 #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, you must stop using
3018  *                 the SSL context for reading or writing, and either free it
3019  *                 or call \c mbedtls_ssl_session_reset() on it before
3020  *                 re-using it for a new connection; the current connection
3021  *                 must be closed.
3022  *
3023  */
3024 int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl );
3025 #endif /* MBEDTLS_SSL_RENEGOTIATION */
3026 
3027 /**
3028  * \brief          Read at most 'len' application data bytes
3029  *
3030  * \param ssl      SSL context
3031  * \param buf      buffer that will hold the data
3032  * \param len      maximum number of bytes to read
3033  *
3034  * \return         The (positive) number of bytes read if successful.
3035  * \return         \c 0 if the read end of the underlying transport was closed
3036  *                 - in this case you must stop using the context (see below).
3037  * \return         #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE
3038  *                 if the handshake is incomplete and waiting for data to
3039  *                 be available for reading from or writing to the underlying
3040  *                 transport - in this case you must call this function again
3041  *                 when the underlying transport is ready for the operation.
3042  * \return         #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous
3043  *                 operation is in progress (see
3044  *                 mbedtls_ssl_conf_async_private_cb()) - in this case you
3045  *                 must call this function again when the operation is ready.
3046  * \return         #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic
3047  *                 operation is in progress (see mbedtls_ecp_set_max_ops()) -
3048  *                 in this case you must call this function again to complete
3049  *                 the handshake when you're done attending other tasks.
3050  * \return         #MBEDTLS_ERR_SSL_CLIENT_RECONNECT if we're at the server
3051  *                 side of a DTLS connection and the client is initiating a
3052  *                 new connection using the same source port. See below.
3053  * \return         Another SSL error code - in this case you must stop using
3054  *                 the context (see below).
3055  *
3056  * \warning        If this function returns something other than
3057  *                 a positive value,
3058  *                 #MBEDTLS_ERR_SSL_WANT_READ,
3059  *                 #MBEDTLS_ERR_SSL_WANT_WRITE,
3060  *                 #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS,
3061  *                 #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS or
3062  *                 #MBEDTLS_ERR_SSL_CLIENT_RECONNECT,
3063  *                 you must stop using the SSL context for reading or writing,
3064  *                 and either free it or call \c mbedtls_ssl_session_reset()
3065  *                 on it before re-using it for a new connection; the current
3066  *                 connection must be closed.
3067  *
3068  * \note           When this function returns #MBEDTLS_ERR_SSL_CLIENT_RECONNECT
3069  *                 (which can only happen server-side), it means that a client
3070  *                 is initiating a new connection using the same source port.
3071  *                 You can either treat that as a connection close and wait
3072  *                 for the client to resend a ClientHello, or directly
3073  *                 continue with \c mbedtls_ssl_handshake() with the same
3074  *                 context (as it has been reset internally). Either way, you
3075  *                 must make sure this is seen by the application as a new
3076  *                 connection: application state, if any, should be reset, and
3077  *                 most importantly the identity of the client must be checked
3078  *                 again. WARNING: not validating the identity of the client
3079  *                 again, or not transmitting the new identity to the
3080  *                 application layer, would allow authentication bypass!
3081  *
3082  * \note           Remarks regarding event-driven DTLS:
3083  *                 - If the function returns #MBEDTLS_ERR_SSL_WANT_READ, no datagram
3084  *                   from the underlying transport layer is currently being processed,
3085  *                   and it is safe to idle until the timer or the underlying transport
3086  *                   signal a new event.
3087  *                 - This function may return MBEDTLS_ERR_SSL_WANT_READ even if data was
3088  *                   initially available on the underlying transport, as this data may have
3089  *                   been only e.g. duplicated messages or a renegotiation request.
3090  *                   Therefore, you must be prepared to receive MBEDTLS_ERR_SSL_WANT_READ even
3091  *                   when reacting to an incoming-data event from the underlying transport.
3092  *                 - On success, the datagram of the underlying transport that is currently
3093  *                   being processed may contain further DTLS records. You should call
3094  *                   \c mbedtls_ssl_check_pending to check for remaining records.
3095  *
3096  */
3097 int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len );
3098 
3099 /**
3100  * \brief          Try to write exactly 'len' application data bytes
3101  *
3102  * \warning        This function will do partial writes in some cases. If the
3103  *                 return value is non-negative but less than length, the
3104  *                 function must be called again with updated arguments:
3105  *                 buf + ret, len - ret (if ret is the return value) until
3106  *                 it returns a value equal to the last 'len' argument.
3107  *
3108  * \param ssl      SSL context
3109  * \param buf      buffer holding the data
3110  * \param len      how many bytes must be written
3111  *
3112  * \return         The (non-negative) number of bytes actually written if
3113  *                 successful (may be less than \p len).
3114  * \return         #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE
3115  *                 if the handshake is incomplete and waiting for data to
3116  *                 be available for reading from or writing to the underlying
3117  *                 transport - in this case you must call this function again
3118  *                 when the underlying transport is ready for the operation.
3119  * \return         #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous
3120  *                 operation is in progress (see
3121  *                 mbedtls_ssl_conf_async_private_cb()) - in this case you
3122  *                 must call this function again when the operation is ready.
3123  * \return         #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic
3124  *                 operation is in progress (see mbedtls_ecp_set_max_ops()) -
3125  *                 in this case you must call this function again to complete
3126  *                 the handshake when you're done attending other tasks.
3127  * \return         Another SSL error code - in this case you must stop using
3128  *                 the context (see below).
3129  *
3130  * \warning        If this function returns something other than
3131  *                 a non-negative value,
3132  *                 #MBEDTLS_ERR_SSL_WANT_READ,
3133  *                 #MBEDTLS_ERR_SSL_WANT_WRITE,
3134  *                 #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or
3135  *                 #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS,
3136  *                 you must stop using the SSL context for reading or writing,
3137  *                 and either free it or call \c mbedtls_ssl_session_reset()
3138  *                 on it before re-using it for a new connection; the current
3139  *                 connection must be closed.
3140  *
3141  * \note           When this function returns #MBEDTLS_ERR_SSL_WANT_WRITE/READ,
3142  *                 it must be called later with the *same* arguments,
3143  *                 until it returns a value greater that or equal to 0. When
3144  *                 the function returns #MBEDTLS_ERR_SSL_WANT_WRITE there may be
3145  *                 some partial data in the output buffer, however this is not
3146  *                 yet sent.
3147  *
3148  * \note           If the requested length is greater than the maximum
3149  *                 fragment length (either the built-in limit or the one set
3150  *                 or negotiated with the peer), then:
3151  *                 - with TLS, less bytes than requested are written.
3152  *                 - with DTLS, MBEDTLS_ERR_SSL_BAD_INPUT_DATA is returned.
3153  *                 \c mbedtls_ssl_get_max_frag_len() may be used to query the
3154  *                 active maximum fragment length.
3155  *
3156  * \note           Attempting to write 0 bytes will result in an empty TLS
3157  *                 application record being sent.
3158  */
3159 int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len );
3160 
3161 /**
3162  * \brief           Send an alert message
3163  *
3164  * \param ssl       SSL context
3165  * \param level     The alert level of the message
3166  *                  (MBEDTLS_SSL_ALERT_LEVEL_WARNING or MBEDTLS_SSL_ALERT_LEVEL_FATAL)
3167  * \param message   The alert message (SSL_ALERT_MSG_*)
3168  *
3169  * \return          0 if successful, or a specific SSL error code.
3170  *
3171  * \note           If this function returns something other than 0 or
3172  *                 MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using
3173  *                 the SSL context for reading or writing, and either free it or
3174  *                 call \c mbedtls_ssl_session_reset() on it before re-using it
3175  *                 for a new connection; the current connection must be closed.
3176  */
3177 int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl,
3178                             unsigned char level,
3179                             unsigned char message );
3180 /**
3181  * \brief          Notify the peer that the connection is being closed
3182  *
3183  * \param ssl      SSL context
3184  *
3185  * \return          0 if successful, or a specific SSL error code.
3186  *
3187  * \note           If this function returns something other than 0 or
3188  *                 MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using
3189  *                 the SSL context for reading or writing, and either free it or
3190  *                 call \c mbedtls_ssl_session_reset() on it before re-using it
3191  *                 for a new connection; the current connection must be closed.
3192  */
3193 int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl );
3194 
3195 /**
3196  * \brief          Free referenced items in an SSL context and clear memory
3197  *
3198  * \param ssl      SSL context
3199  */
3200 void mbedtls_ssl_free( mbedtls_ssl_context *ssl );
3201 
3202 /**
3203  * \brief          Initialize an SSL configuration context
3204  *                 Just makes the context ready for
3205  *                 mbedtls_ssl_config_defaults() or mbedtls_ssl_config_free().
3206  *
3207  * \note           You need to call mbedtls_ssl_config_defaults() unless you
3208  *                 manually set all of the relevent fields yourself.
3209  *
3210  * \param conf     SSL configuration context
3211  */
3212 void mbedtls_ssl_config_init( mbedtls_ssl_config *conf );
3213 
3214 /**
3215  * \brief          Load reasonnable default SSL configuration values.
3216  *                 (You need to call mbedtls_ssl_config_init() first.)
3217  *
3218  * \param conf     SSL configuration context
3219  * \param endpoint MBEDTLS_SSL_IS_CLIENT or MBEDTLS_SSL_IS_SERVER
3220  * \param transport MBEDTLS_SSL_TRANSPORT_STREAM for TLS, or
3221  *                  MBEDTLS_SSL_TRANSPORT_DATAGRAM for DTLS
3222  * \param preset   a MBEDTLS_SSL_PRESET_XXX value
3223  *
3224  * \note           See \c mbedtls_ssl_conf_transport() for notes on DTLS.
3225  *
3226  * \return         0 if successful, or
3227  *                 MBEDTLS_ERR_XXX_ALLOC_FAILED on memory allocation error.
3228  */
3229 int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
3230                                  int endpoint, int transport, int preset );
3231 
3232 /**
3233  * \brief          Free an SSL configuration context
3234  *
3235  * \param conf     SSL configuration context
3236  */
3237 void mbedtls_ssl_config_free( mbedtls_ssl_config *conf );
3238 
3239 /**
3240  * \brief          Initialize SSL session structure
3241  *
3242  * \param session  SSL session
3243  */
3244 void mbedtls_ssl_session_init( mbedtls_ssl_session *session );
3245 
3246 /**
3247  * \brief          Free referenced items in an SSL session including the
3248  *                 peer certificate and clear memory
3249  *
3250  * \note           A session object can be freed even if the SSL context
3251  *                 that was used to retrieve the session is still in use.
3252  *
3253  * \param session  SSL session
3254  */
3255 void mbedtls_ssl_session_free( mbedtls_ssl_session *session );
3256 
3257 #ifdef __cplusplus
3258 }
3259 #endif
3260 
3261 #endif /* ssl.h */
3262