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