4 * \brief Internal functions shared by the SSL modules
7 * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
8 * SPDX-License-Identifier: Apache-2.0
10 * Licensed under the Apache License, Version 2.0 (the "License"); you may
11 * not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
18 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
22 * This file is part of mbed TLS (https://tls.mbed.org)
24 #ifndef MBEDTLS_SSL_INTERNAL_H
25 #define MBEDTLS_SSL_INTERNAL_H
27 #if !defined(MBEDTLS_CONFIG_FILE)
30 #include MBEDTLS_CONFIG_FILE
36 #if defined(MBEDTLS_USE_PSA_CRYPTO)
37 #include "psa/crypto.h"
40 #if defined(MBEDTLS_MD5_C)
44 #if defined(MBEDTLS_SHA1_C)
48 #if defined(MBEDTLS_SHA256_C)
52 #if defined(MBEDTLS_SHA512_C)
56 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
60 #if defined(MBEDTLS_USE_PSA_CRYPTO)
61 #include "psa/crypto.h"
63 #endif /* MBEDTLS_USE_PSA_CRYPTO */
65 #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
66 !defined(inline) && !defined(__cplusplus)
67 #define inline __inline
70 /* Determine minimum supported version */
71 #define MBEDTLS_SSL_MIN_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3
73 #if defined(MBEDTLS_SSL_PROTO_SSL3)
74 #define MBEDTLS_SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_0
76 #if defined(MBEDTLS_SSL_PROTO_TLS1)
77 #define MBEDTLS_SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1
79 #if defined(MBEDTLS_SSL_PROTO_TLS1_1)
80 #define MBEDTLS_SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_2
82 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
83 #define MBEDTLS_SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_3
84 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
85 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 */
86 #endif /* MBEDTLS_SSL_PROTO_TLS1 */
87 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
89 #define MBEDTLS_SSL_MIN_VALID_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1
90 #define MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3
92 /* Determine maximum supported version */
93 #define MBEDTLS_SSL_MAX_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3
95 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
96 #define MBEDTLS_SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_3
98 #if defined(MBEDTLS_SSL_PROTO_TLS1_1)
99 #define MBEDTLS_SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_2
101 #if defined(MBEDTLS_SSL_PROTO_TLS1)
102 #define MBEDTLS_SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1
104 #if defined(MBEDTLS_SSL_PROTO_SSL3)
105 #define MBEDTLS_SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_0
106 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
107 #endif /* MBEDTLS_SSL_PROTO_TLS1 */
108 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 */
109 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
111 /* Shorthand for restartable ECC */
112 #if defined(MBEDTLS_ECP_RESTARTABLE) && \
113 defined(MBEDTLS_SSL_CLI_C) && \
114 defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
115 defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
116 #define MBEDTLS_SSL__ECP_RESTARTABLE
119 #define MBEDTLS_SSL_INITIAL_HANDSHAKE 0
120 #define MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS 1 /* In progress */
121 #define MBEDTLS_SSL_RENEGOTIATION_DONE 2 /* Done or aborted */
122 #define MBEDTLS_SSL_RENEGOTIATION_PENDING 3 /* Requested (server only) */
125 * DTLS retransmission states, see RFC 6347 4.2.4
127 * The SENDING state is merged in PREPARING for initial sends,
128 * but is distinct for resends.
130 * Note: initial state is wrong for server, but is not used anyway.
132 #define MBEDTLS_SSL_RETRANS_PREPARING 0
133 #define MBEDTLS_SSL_RETRANS_SENDING 1
134 #define MBEDTLS_SSL_RETRANS_WAITING 2
135 #define MBEDTLS_SSL_RETRANS_FINISHED 3
138 * Allow extra bytes for record, authentication and encryption overhead:
139 * counter (8) + header (5) + IV(16) + MAC (16-48) + padding (0-256)
140 * and allow for a maximum of 1024 of compression expansion if
143 #if defined(MBEDTLS_ZLIB_SUPPORT)
144 #define MBEDTLS_SSL_COMPRESSION_ADD 1024
146 #define MBEDTLS_SSL_COMPRESSION_ADD 0
149 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \
150 ( defined(MBEDTLS_CIPHER_MODE_CBC) && \
151 ( defined(MBEDTLS_AES_C) || \
152 defined(MBEDTLS_CAMELLIA_C) || \
153 defined(MBEDTLS_ARIA_C) || \
154 defined(MBEDTLS_DES_C) ) )
155 #define MBEDTLS_SSL_SOME_MODES_USE_MAC
158 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
159 /* Ciphersuites using HMAC */
160 #if defined(MBEDTLS_SHA512_C)
161 #define MBEDTLS_SSL_MAC_ADD 48 /* SHA-384 used for HMAC */
162 #elif defined(MBEDTLS_SHA256_C)
163 #define MBEDTLS_SSL_MAC_ADD 32 /* SHA-256 used for HMAC */
165 #define MBEDTLS_SSL_MAC_ADD 20 /* SHA-1 used for HMAC */
167 #else /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
168 /* AEAD ciphersuites: GCM and CCM use a 128 bits tag */
169 #define MBEDTLS_SSL_MAC_ADD 16
172 #if defined(MBEDTLS_CIPHER_MODE_CBC)
173 #define MBEDTLS_SSL_PADDING_ADD 256
175 #define MBEDTLS_SSL_PADDING_ADD 0
178 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
179 #define MBEDTLS_SSL_MAX_CID_EXPANSION MBEDTLS_SSL_CID_PADDING_GRANULARITY
181 #define MBEDTLS_SSL_MAX_CID_EXPANSION 0
184 #define MBEDTLS_SSL_PAYLOAD_OVERHEAD ( MBEDTLS_SSL_COMPRESSION_ADD + \
185 MBEDTLS_MAX_IV_LENGTH + \
186 MBEDTLS_SSL_MAC_ADD + \
187 MBEDTLS_SSL_PADDING_ADD + \
188 MBEDTLS_SSL_MAX_CID_EXPANSION \
191 #define MBEDTLS_SSL_IN_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \
192 ( MBEDTLS_SSL_IN_CONTENT_LEN ) )
194 #define MBEDTLS_SSL_OUT_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \
195 ( MBEDTLS_SSL_OUT_CONTENT_LEN ) )
197 /* The maximum number of buffered handshake messages. */
198 #define MBEDTLS_SSL_MAX_BUFFERED_HS 4
200 /* Maximum length we can advertise as our max content length for
201 RFC 6066 max_fragment_length extension negotiation purposes
202 (the lesser of both sizes, if they are unequal.)
204 #define MBEDTLS_TLS_EXT_ADV_CONTENT_LEN ( \
205 (MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_OUT_CONTENT_LEN) \
206 ? ( MBEDTLS_SSL_OUT_CONTENT_LEN ) \
207 : ( MBEDTLS_SSL_IN_CONTENT_LEN ) \
211 * Check that we obey the standard's message size bounds
214 #if MBEDTLS_SSL_MAX_CONTENT_LEN > 16384
215 #error "Bad configuration - record content too large."
218 #if MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN
219 #error "Bad configuration - incoming record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN."
222 #if MBEDTLS_SSL_OUT_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN
223 #error "Bad configuration - outgoing record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN."
226 #if MBEDTLS_SSL_IN_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048
227 #error "Bad configuration - incoming protected record payload too large."
230 #if MBEDTLS_SSL_OUT_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048
231 #error "Bad configuration - outgoing protected record payload too large."
234 /* Calculate buffer sizes */
236 /* Note: Even though the TLS record header is only 5 bytes
237 long, we're internally using 8 bytes to store the
238 implicit sequence number. */
239 #define MBEDTLS_SSL_HEADER_LEN 13
241 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
242 #define MBEDTLS_SSL_IN_BUFFER_LEN \
243 ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_IN_PAYLOAD_LEN ) )
245 #define MBEDTLS_SSL_IN_BUFFER_LEN \
246 ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_IN_PAYLOAD_LEN ) \
247 + ( MBEDTLS_SSL_CID_IN_LEN_MAX ) )
250 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
251 #define MBEDTLS_SSL_OUT_BUFFER_LEN \
252 ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_OUT_PAYLOAD_LEN ) )
254 #define MBEDTLS_SSL_OUT_BUFFER_LEN \
255 ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_OUT_PAYLOAD_LEN ) \
256 + ( MBEDTLS_SSL_CID_OUT_LEN_MAX ) )
259 #ifdef MBEDTLS_ZLIB_SUPPORT
260 /* Compression buffer holds both IN and OUT buffers, so should be size of the larger */
261 #define MBEDTLS_SSL_COMPRESS_BUFFER_LEN ( \
262 ( MBEDTLS_SSL_IN_BUFFER_LEN > MBEDTLS_SSL_OUT_BUFFER_LEN ) \
263 ? MBEDTLS_SSL_IN_BUFFER_LEN \
264 : MBEDTLS_SSL_OUT_BUFFER_LEN \
269 * TLS extension flags (for extensions with outgoing ServerHello content
270 * that need it (e.g. for RENEGOTIATION_INFO the server already knows because
271 * of state of the renegotiation flag, so no indicator is required)
273 #define MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT (1 << 0)
274 #define MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK (1 << 1)
280 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
281 defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
283 * Abstraction for a grid of allowed signature-hash-algorithm pairs.
285 struct mbedtls_ssl_sig_hash_set_t
287 /* At the moment, we only need to remember a single suitable
288 * hash algorithm per signature algorithm. As long as that's
289 * the case - and we don't need a general lookup function -
290 * we can implement the sig-hash-set as a map from signatures
291 * to hash algorithms. */
292 mbedtls_md_type_t rsa;
293 mbedtls_md_type_t ecdsa;
295 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
296 MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
298 typedef int mbedtls_ssl_tls_prf_cb( const unsigned char *secret, size_t slen,
300 const unsigned char *random, size_t rlen,
301 unsigned char *dstbuf, size_t dlen );
303 * This structure contains the parameters only needed during handshake.
305 struct mbedtls_ssl_handshake_params
308 * Handshake specific crypto variables
311 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
312 defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
313 mbedtls_ssl_sig_hash_set_t hash_algs; /*!< Set of suitable sig-hash pairs */
315 #if defined(MBEDTLS_DHM_C)
316 mbedtls_dhm_context dhm_ctx; /*!< DHM key exchange */
318 #if defined(MBEDTLS_ECDH_C)
319 mbedtls_ecdh_context ecdh_ctx; /*!< ECDH key exchange */
321 #if defined(MBEDTLS_USE_PSA_CRYPTO)
322 psa_ecc_curve_t ecdh_psa_curve;
323 psa_key_handle_t ecdh_psa_privkey;
324 unsigned char ecdh_psa_peerkey[MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH];
325 size_t ecdh_psa_peerkey_len;
326 #endif /* MBEDTLS_USE_PSA_CRYPTO */
327 #endif /* MBEDTLS_ECDH_C */
329 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
330 mbedtls_ecjpake_context ecjpake_ctx; /*!< EC J-PAKE key exchange */
331 #if defined(MBEDTLS_SSL_CLI_C)
332 unsigned char *ecjpake_cache; /*!< Cache for ClientHello ext */
333 size_t ecjpake_cache_len; /*!< Length of cached data */
335 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
336 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
337 defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
338 const mbedtls_ecp_curve_info **curves; /*!< Supported elliptic curves */
340 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
341 #if defined(MBEDTLS_USE_PSA_CRYPTO)
342 psa_key_handle_t psk_opaque; /*!< Opaque PSK from the callback */
343 #endif /* MBEDTLS_USE_PSA_CRYPTO */
344 unsigned char *psk; /*!< PSK from the callback */
345 size_t psk_len; /*!< Length of PSK from callback */
346 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
347 #if defined(MBEDTLS_X509_CRT_PARSE_C)
348 mbedtls_ssl_key_cert *key_cert; /*!< chosen key/cert pair (server) */
349 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
350 int sni_authmode; /*!< authmode from SNI callback */
351 mbedtls_ssl_key_cert *sni_key_cert; /*!< key/cert list from SNI */
352 mbedtls_x509_crt *sni_ca_chain; /*!< trusted CAs from SNI callback */
353 mbedtls_x509_crl *sni_ca_crl; /*!< trusted CAs CRLs from SNI */
354 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
355 #endif /* MBEDTLS_X509_CRT_PARSE_C */
356 #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
357 int ecrs_enabled; /*!< Handshake supports EC restart? */
358 mbedtls_x509_crt_restart_ctx ecrs_ctx; /*!< restart context */
359 enum { /* this complements ssl->state with info on intra-state operations */
360 ssl_ecrs_none = 0, /*!< nothing going on (yet) */
361 ssl_ecrs_crt_verify, /*!< Certificate: crt_verify() */
362 ssl_ecrs_ske_start_processing, /*!< ServerKeyExchange: pk_verify() */
363 ssl_ecrs_cke_ecdh_calc_secret, /*!< ClientKeyExchange: ECDH step 2 */
364 ssl_ecrs_crt_vrfy_sign, /*!< CertificateVerify: pk_sign() */
365 } ecrs_state; /*!< current (or last) operation */
366 mbedtls_x509_crt *ecrs_peer_cert; /*!< The peer's CRT chain. */
367 size_t ecrs_n; /*!< place for saving a length */
369 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
370 !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
371 mbedtls_pk_context peer_pubkey; /*!< The public key from the peer. */
372 #endif /* MBEDTLS_X509_CRT_PARSE_C && !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
373 #if defined(MBEDTLS_SSL_PROTO_DTLS)
374 unsigned int out_msg_seq; /*!< Outgoing handshake sequence number */
375 unsigned int in_msg_seq; /*!< Incoming handshake sequence number */
377 unsigned char *verify_cookie; /*!< Cli: HelloVerifyRequest cookie
379 unsigned char verify_cookie_len; /*!< Cli: cookie length
380 Srv: flag for sending a cookie */
382 uint32_t retransmit_timeout; /*!< Current value of timeout */
383 unsigned char retransmit_state; /*!< Retransmission state */
384 mbedtls_ssl_flight_item *flight; /*!< Current outgoing flight */
385 mbedtls_ssl_flight_item *cur_msg; /*!< Current message in flight */
386 unsigned char *cur_msg_p; /*!< Position in current message */
387 unsigned int in_flight_start_seq; /*!< Minimum message sequence in the
388 flight being received */
389 mbedtls_ssl_transform *alt_transform_out; /*!< Alternative transform for
390 resending messages */
391 unsigned char alt_out_ctr[8]; /*!< Alternative record epoch/counter
392 for resending messages */
394 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
395 /* The state of CID configuration in this handshake. */
397 uint8_t cid_in_use; /*!< This indicates whether the use of the CID extension
398 * has been negotiated. Possible values are
399 * #MBEDTLS_SSL_CID_ENABLED and
400 * #MBEDTLS_SSL_CID_DISABLED. */
401 unsigned char peer_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ]; /*! The peer's CID */
402 uint8_t peer_cid_len; /*!< The length of
404 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
408 size_t total_bytes_buffered; /*!< Cumulative size of heap allocated
409 * buffers used for message buffering. */
411 uint8_t seen_ccs; /*!< Indicates if a CCS message has
412 * been seen in the current flight. */
414 struct mbedtls_ssl_hs_buffer
416 unsigned is_valid : 1;
417 unsigned is_fragmented : 1;
418 unsigned is_complete : 1;
421 } hs[MBEDTLS_SSL_MAX_BUFFERED_HS];
432 uint16_t mtu; /*!< Handshake mtu, used to fragment outgoing messages */
433 #endif /* MBEDTLS_SSL_PROTO_DTLS */
438 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
439 defined(MBEDTLS_SSL_PROTO_TLS1_1)
440 mbedtls_md5_context fin_md5;
441 mbedtls_sha1_context fin_sha1;
443 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
444 #if defined(MBEDTLS_SHA256_C)
445 #if defined(MBEDTLS_USE_PSA_CRYPTO)
446 psa_hash_operation_t fin_sha256_psa;
448 mbedtls_sha256_context fin_sha256;
451 #if defined(MBEDTLS_SHA512_C)
452 #if defined(MBEDTLS_USE_PSA_CRYPTO)
453 psa_hash_operation_t fin_sha384_psa;
455 mbedtls_sha512_context fin_sha512;
458 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
460 void (*update_checksum)(mbedtls_ssl_context *, const unsigned char *, size_t);
461 void (*calc_verify)(mbedtls_ssl_context *, unsigned char *);
462 void (*calc_finished)(mbedtls_ssl_context *, unsigned char *, int);
463 mbedtls_ssl_tls_prf_cb *tls_prf;
465 mbedtls_ssl_ciphersuite_t const *ciphersuite_info;
467 size_t pmslen; /*!< premaster length */
469 unsigned char randbytes[64]; /*!< random bytes */
470 unsigned char premaster[MBEDTLS_PREMASTER_SIZE];
471 /*!< premaster secret */
473 int resume; /*!< session resume indicator*/
474 int max_major_ver; /*!< max. major version client*/
475 int max_minor_ver; /*!< max. minor version client*/
476 int cli_exts; /*!< client extension presence*/
478 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
479 int new_session_ticket; /*!< use NewSessionTicket? */
480 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
481 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
482 int extended_ms; /*!< use Extended Master Secret? */
485 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
486 unsigned int async_in_progress : 1; /*!< an asynchronous operation is in progress */
487 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
489 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
490 /** Asynchronous operation context. This field is meant for use by the
491 * asynchronous operation callbacks (mbedtls_ssl_config::f_async_sign_start,
492 * mbedtls_ssl_config::f_async_decrypt_start,
493 * mbedtls_ssl_config::f_async_resume, mbedtls_ssl_config::f_async_cancel).
494 * The library does not use it internally. */
495 void *user_async_ctx;
496 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
499 typedef struct mbedtls_ssl_hs_buffer mbedtls_ssl_hs_buffer;
502 * Representation of decryption/encryption transformations on records
504 * There are the following general types of record transformations:
505 * - Stream transformations (TLS versions <= 1.2 only)
506 * Transformation adding a MAC and applying a stream-cipher
507 * to the authenticated message.
508 * - CBC block cipher transformations ([D]TLS versions <= 1.2 only)
509 * In addition to the distinction of the order of encryption and
510 * authentication, there's a fundamental difference between the
511 * handling in SSL3 & TLS 1.0 and TLS 1.1 and TLS 1.2: For SSL3
512 * and TLS 1.0, the final IV after processing a record is used
513 * as the IV for the next record. No explicit IV is contained
514 * in an encrypted record. The IV for the first record is extracted
515 * at key extraction time. In contrast, for TLS 1.1 and 1.2, no
516 * IV is generated at key extraction time, but every encrypted
517 * record is explicitly prefixed by the IV with which it was encrypted.
518 * - AEAD transformations ([D]TLS versions >= 1.2 only)
519 * These come in two fundamentally different versions, the first one
520 * used in TLS 1.2, excluding ChaChaPoly ciphersuites, and the second
521 * one used for ChaChaPoly ciphersuites in TLS 1.2 as well as for TLS 1.3.
522 * In the first transformation, the IV to be used for a record is obtained
523 * as the concatenation of an explicit, static 4-byte IV and the 8-byte
524 * record sequence number, and explicitly prepending this sequence number
525 * to the encrypted record. In contrast, in the second transformation
526 * the IV is obtained by XOR'ing a static IV obtained at key extraction
527 * time with the 8-byte record sequence number, without prepending the
528 * latter to the encrypted record.
530 * In addition to type and version, the following parameters are relevant:
531 * - The symmetric cipher algorithm to be used.
532 * - The (static) encryption/decryption keys for the cipher.
533 * - For stream/CBC, the type of message digest to be used.
534 * - For stream/CBC, (static) encryption/decryption keys for the digest.
535 * - For AEAD transformations, the size (potentially 0) of an explicit,
536 * random initialization vector placed in encrypted records.
537 * - For some transformations (currently AEAD and CBC in SSL3 and TLS 1.0)
538 * an implicit IV. It may be static (e.g. AEAD) or dynamic (e.g. CBC)
539 * and (if present) is combined with the explicit IV in a transformation-
540 * dependent way (e.g. appending in TLS 1.2 and XOR'ing in TLS 1.3).
541 * - For stream/CBC, a flag determining the order of encryption and MAC.
542 * - The details of the transformation depend on the SSL/TLS version.
543 * - The length of the authentication tag.
545 * Note: Except for CBC in SSL3 and TLS 1.0, these parameters are
546 * constant across multiple encryption/decryption operations.
547 * For CBC, the implicit IV needs to be updated after each
550 * The struct below refines this abstract view as follows:
551 * - The cipher underlying the transformation is managed in
552 * cipher contexts cipher_ctx_{enc/dec}, which must have the
553 * same cipher type. The mode of these cipher contexts determines
554 * the type of the transformation in the sense above: e.g., if
555 * the type is MBEDTLS_CIPHER_AES_256_CBC resp. MBEDTLS_CIPHER_AES_192_GCM
556 * then the transformation has type CBC resp. AEAD.
557 * - The cipher keys are never stored explicitly but
558 * are maintained within cipher_ctx_{enc/dec}.
559 * - For stream/CBC transformations, the message digest contexts
560 * used for the MAC's are stored in md_ctx_{enc/dec}. These contexts
561 * are unused for AEAD transformations.
562 * - For stream/CBC transformations and versions > SSL3, the
563 * MAC keys are not stored explicitly but maintained within
565 * - For stream/CBC transformations and version SSL3, the MAC
566 * keys are stored explicitly in mac_enc, mac_dec and have
567 * a fixed size of 20 bytes. These fields are unused for
568 * AEAD transformations or transformations >= TLS 1.0.
569 * - For transformations using an implicit IV maintained within
570 * the transformation context, its contents are stored within
572 * - The value of ivlen indicates the length of the IV.
573 * This is redundant in case of stream/CBC transformations
574 * which always use 0 resp. the cipher's block length as the
575 * IV length, but is needed for AEAD ciphers and may be
576 * different from the underlying cipher's block length
578 * - The field fixed_ivlen is nonzero for AEAD transformations only
579 * and indicates the length of the static part of the IV which is
580 * constant throughout the communication, and which is stored in
581 * the first fixed_ivlen bytes of the iv_{enc/dec} arrays.
582 * Note: For CBC in SSL3 and TLS 1.0, the fields iv_{enc/dec}
583 * still store IV's for continued use across multiple transformations,
584 * so it is not true that fixed_ivlen == 0 means that iv_{enc/dec} are
586 * - minor_ver denotes the SSL/TLS version
587 * - For stream/CBC transformations, maclen denotes the length of the
588 * authentication tag, while taglen is unused and 0.
589 * - For AEAD transformations, taglen denotes the length of the
590 * authentication tag, while maclen is unused and 0.
591 * - For CBC transformations, encrypt_then_mac determines the
592 * order of encryption and authentication. This field is unused
593 * in other transformations.
596 struct mbedtls_ssl_transform
599 * Session specific crypto layer
601 size_t minlen; /*!< min. ciphertext length */
602 size_t ivlen; /*!< IV length */
603 size_t fixed_ivlen; /*!< Fixed part of IV (AEAD) */
604 size_t maclen; /*!< MAC(CBC) len */
605 size_t taglen; /*!< TAG(AEAD) len */
607 unsigned char iv_enc[16]; /*!< IV (encryption) */
608 unsigned char iv_dec[16]; /*!< IV (decryption) */
610 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
612 #if defined(MBEDTLS_SSL_PROTO_SSL3)
613 /* Needed only for SSL v3.0 secret */
614 unsigned char mac_enc[20]; /*!< SSL v3.0 secret (enc) */
615 unsigned char mac_dec[20]; /*!< SSL v3.0 secret (dec) */
616 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
618 mbedtls_md_context_t md_ctx_enc; /*!< MAC (encryption) */
619 mbedtls_md_context_t md_ctx_dec; /*!< MAC (decryption) */
621 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
622 int encrypt_then_mac; /*!< flag for EtM activation */
625 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
627 mbedtls_cipher_context_t cipher_ctx_enc; /*!< encryption context */
628 mbedtls_cipher_context_t cipher_ctx_dec; /*!< decryption context */
631 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
634 unsigned char in_cid [ MBEDTLS_SSL_CID_OUT_LEN_MAX ];
635 unsigned char out_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ];
636 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
639 * Session specific compression layer
641 #if defined(MBEDTLS_ZLIB_SUPPORT)
642 z_stream ctx_deflate; /*!< compression context */
643 z_stream ctx_inflate; /*!< decompression context */
648 * Internal representation of record frames
650 * Instances come in two flavors:
652 * These always have data_offset = 0
654 * These have data_offset set to the amount of
655 * pre-expansion during record protection. Concretely,
656 * this is the length of the fixed part of the explicit IV
657 * used for encryption, or 0 if no explicit IV is used
658 * (e.g. for CBC in TLS 1.0, or stream ciphers).
660 * The reason for the data_offset in the unencrypted case
661 * is to allow for in-place conversion of an unencrypted to
662 * an encrypted record. If the offset wasn't included, the
663 * encrypted content would need to be shifted afterwards to
664 * make space for the fixed IV.
667 #if MBEDTLS_SSL_CID_OUT_LEN_MAX > MBEDTLS_SSL_CID_IN_LEN_MAX
668 #define MBEDTLS_SSL_CID_LEN_MAX MBEDTLS_SSL_CID_OUT_LEN_MAX
670 #define MBEDTLS_SSL_CID_LEN_MAX MBEDTLS_SSL_CID_IN_LEN_MAX
675 uint8_t ctr[8]; /* Record sequence number */
676 uint8_t type; /* Record type */
677 uint8_t ver[2]; /* SSL/TLS version */
679 unsigned char *buf; /* Memory buffer enclosing the record content */
680 size_t buf_len; /* Buffer length */
681 size_t data_offset; /* Offset of record content */
682 size_t data_len; /* Length of record content */
684 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
685 uint8_t cid_len; /* Length of the CID (0 if not present) */
686 unsigned char cid[ MBEDTLS_SSL_CID_LEN_MAX ]; /* The CID */
687 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
690 #if defined(MBEDTLS_X509_CRT_PARSE_C)
692 * List of certificate + private key pairs
694 struct mbedtls_ssl_key_cert
696 mbedtls_x509_crt *cert; /*!< cert */
697 mbedtls_pk_context *key; /*!< private key */
698 mbedtls_ssl_key_cert *next; /*!< next key/cert pair */
700 #endif /* MBEDTLS_X509_CRT_PARSE_C */
702 #if defined(MBEDTLS_SSL_PROTO_DTLS)
704 * List of handshake messages kept around for resending
706 struct mbedtls_ssl_flight_item
708 unsigned char *p; /*!< message, including handshake headers */
709 size_t len; /*!< length of p */
710 unsigned char type; /*!< type of the message: handshake or CCS */
711 mbedtls_ssl_flight_item *next; /*!< next handshake message(s) */
713 #endif /* MBEDTLS_SSL_PROTO_DTLS */
715 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
716 defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
718 /* Find an entry in a signature-hash set matching a given hash algorithm. */
719 mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,
720 mbedtls_pk_type_t sig_alg );
721 /* Add a signature-hash-pair to a signature-hash set */
722 void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,
723 mbedtls_pk_type_t sig_alg,
724 mbedtls_md_type_t md_alg );
725 /* Allow exactly one hash algorithm for each signature. */
726 void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,
727 mbedtls_md_type_t md_alg );
729 /* Setup an empty signature-hash set */
730 static inline void mbedtls_ssl_sig_hash_set_init( mbedtls_ssl_sig_hash_set_t *set )
732 mbedtls_ssl_sig_hash_set_const_hash( set, MBEDTLS_MD_NONE );
735 #endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&
736 MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
739 * \brief Free referenced items in an SSL transform context and clear
742 * \param transform SSL transform context
744 void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform );
747 * \brief Free referenced items in an SSL handshake context and clear
750 * \param ssl SSL context
752 void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl );
754 int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl );
755 int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl );
756 void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl );
758 int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl );
760 void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl );
761 int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl );
763 int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl );
764 int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl );
765 void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl );
768 * \brief Update record layer
770 * This function roughly separates the implementation
771 * of the logic of (D)TLS from the implementation
772 * of the secure transport.
774 * \param ssl The SSL context to use.
775 * \param update_hs_digest This indicates if the handshake digest
776 * should be automatically updated in case
777 * a handshake message is found.
779 * \return 0 or non-zero error code.
781 * \note A clarification on what is called 'record layer' here
782 * is in order, as many sensible definitions are possible:
784 * The record layer takes as input an untrusted underlying
785 * transport (stream or datagram) and transforms it into
786 * a serially multiplexed, secure transport, which
787 * conceptually provides the following:
789 * (1) Three datagram based, content-agnostic transports
790 * for handshake, alert and CCS messages.
791 * (2) One stream- or datagram-based transport
792 * for application data.
793 * (3) Functionality for changing the underlying transform
794 * securing the contents.
796 * The interface to this functionality is given as follows:
799 * [Currently implemented by mbedtls_ssl_read_record]
801 * Check if and on which of the four 'ports' data is pending:
802 * Nothing, a controlling datagram of type (1), or application
803 * data (2). In any case data is present, internal buffers
804 * provide access to the data for the user to process it.
805 * Consumption of type (1) datagrams is done automatically
806 * on the next update, invalidating that the internal buffers
807 * for previous datagrams, while consumption of application
808 * data (2) is user-controlled.
810 * b Reading of application data
811 * [Currently manual adaption of ssl->in_offt pointer]
813 * As mentioned in the last paragraph, consumption of data
814 * is different from the automatic consumption of control
815 * datagrams (1) because application data is treated as a stream.
817 * c Tracking availability of application data
818 * [Currently manually through decreasing ssl->in_msglen]
820 * For efficiency and to retain datagram semantics for
821 * application data in case of DTLS, the record layer
822 * provides functionality for checking how much application
823 * data is still available in the internal buffer.
825 * d Changing the transformation securing the communication.
827 * Given an opaque implementation of the record layer in the
828 * above sense, it should be possible to implement the logic
829 * of (D)TLS on top of it without the need to know anything
830 * about the record layer's internals. This is done e.g.
831 * in all the handshake handling functions, and in the
832 * application data reading function mbedtls_ssl_read.
834 * \note The above tries to give a conceptual picture of the
835 * record layer, but the current implementation deviates
836 * from it in some places. For example, our implementation of
837 * the update functionality through mbedtls_ssl_read_record
838 * discards datagrams depending on the current state, which
839 * wouldn't fall under the record layer's responsibility
840 * following the above definition.
843 int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl,
844 unsigned update_hs_digest );
845 int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want );
847 int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl );
848 int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush );
849 int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl );
851 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl );
852 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl );
854 int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl );
855 int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl );
857 int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl );
858 int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl );
860 void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
861 const mbedtls_ssl_ciphersuite_t *ciphersuite_info );
863 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
864 int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex );
867 #if defined(MBEDTLS_PK_C)
868 unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk );
869 unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type );
870 mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig );
873 mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash );
874 unsigned char mbedtls_ssl_hash_from_md_alg( int md );
875 int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md );
877 #if defined(MBEDTLS_ECP_C)
878 int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id );
881 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
882 int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,
883 mbedtls_md_type_t md );
886 #if defined(MBEDTLS_X509_CRT_PARSE_C)
887 static inline mbedtls_pk_context *mbedtls_ssl_own_key( mbedtls_ssl_context *ssl )
889 mbedtls_ssl_key_cert *key_cert;
891 if( ssl->handshake != NULL && ssl->handshake->key_cert != NULL )
892 key_cert = ssl->handshake->key_cert;
894 key_cert = ssl->conf->key_cert;
896 return( key_cert == NULL ? NULL : key_cert->key );
899 static inline mbedtls_x509_crt *mbedtls_ssl_own_cert( mbedtls_ssl_context *ssl )
901 mbedtls_ssl_key_cert *key_cert;
903 if( ssl->handshake != NULL && ssl->handshake->key_cert != NULL )
904 key_cert = ssl->handshake->key_cert;
906 key_cert = ssl->conf->key_cert;
908 return( key_cert == NULL ? NULL : key_cert->cert );
912 * Check usage of a certificate wrt extensions:
913 * keyUsage, extendedKeyUsage (later), and nSCertType (later).
915 * Warning: cert_endpoint is the endpoint of the cert (ie, of our peer when we
916 * check a cert we received from them)!
918 * Return 0 if everything is OK, -1 if not.
920 int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,
921 const mbedtls_ssl_ciphersuite_t *ciphersuite,
924 #endif /* MBEDTLS_X509_CRT_PARSE_C */
926 void mbedtls_ssl_write_version( int major, int minor, int transport,
927 unsigned char ver[2] );
928 void mbedtls_ssl_read_version( int *major, int *minor, int transport,
929 const unsigned char ver[2] );
931 static inline size_t mbedtls_ssl_in_hdr_len( const mbedtls_ssl_context *ssl )
933 return( (size_t) ( ssl->in_iv - ssl->in_hdr ) );
936 static inline size_t mbedtls_ssl_out_hdr_len( const mbedtls_ssl_context *ssl )
938 return( (size_t) ( ssl->out_iv - ssl->out_hdr ) );
941 static inline size_t mbedtls_ssl_hs_hdr_len( const mbedtls_ssl_context *ssl )
943 #if defined(MBEDTLS_SSL_PROTO_DTLS)
944 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
952 #if defined(MBEDTLS_SSL_PROTO_DTLS)
953 void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl );
954 void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl );
955 int mbedtls_ssl_resend( mbedtls_ssl_context *ssl );
956 int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl );
959 /* Visible for testing purposes only */
960 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
961 int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl );
962 void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl );
965 int mbedtls_ssl_session_copy( mbedtls_ssl_session *dst,
966 const mbedtls_ssl_session *src );
968 /* constant-time buffer comparison */
969 static inline int mbedtls_ssl_safer_memcmp( const void *a, const void *b, size_t n )
972 volatile const unsigned char *A = (volatile const unsigned char *) a;
973 volatile const unsigned char *B = (volatile const unsigned char *) b;
974 volatile unsigned char diff = 0;
976 for( i = 0; i < n; i++ )
978 /* Read volatile data in order before computing diff.
979 * This avoids IAR compiler warning:
980 * 'the order of volatile accesses is undefined ..' */
981 unsigned char x = A[i], y = B[i];
988 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
989 defined(MBEDTLS_SSL_PROTO_TLS1_1)
990 int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,
991 unsigned char *output,
992 unsigned char *data, size_t data_len );
993 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
994 MBEDTLS_SSL_PROTO_TLS1_1 */
996 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
997 defined(MBEDTLS_SSL_PROTO_TLS1_2)
998 /* The hash buffer must have at least MBEDTLS_MD_MAX_SIZE bytes of length. */
999 int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
1000 unsigned char *hash, size_t *hashlen,
1001 unsigned char *data, size_t data_len,
1002 mbedtls_md_type_t md_alg );
1003 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
1004 MBEDTLS_SSL_PROTO_TLS1_2 */
1010 void mbedtls_ssl_transform_init( mbedtls_ssl_transform *transform );
1011 int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl,
1012 mbedtls_ssl_transform *transform,
1013 mbedtls_record *rec,
1014 int (*f_rng)(void *, unsigned char *, size_t),
1016 int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context *ssl,
1017 mbedtls_ssl_transform *transform,
1018 mbedtls_record *rec );
1020 #endif /* ssl_internal.h */