1TLS 1.3 support
2===============
3
4Overview
5--------
6
7Mbed TLS provides a partial implementation of the TLS 1.3 protocol defined in
8the "Support description" section below. The TLS 1.3 support enablement
9is controlled by the MBEDTLS_SSL_PROTO_TLS1_3 configuration option.
10
11The development of the TLS 1.3 protocol is based on the TLS 1.3 prototype
12located at https://github.com/hannestschofenig/mbedtls. The prototype is
13itself based on a version of the development branch that we aim to keep as
14recent as possible (ideally the head) by merging regularly commits of the
15development branch into the prototype. The section "Prototype upstreaming
16status" below describes what remains to be upstreamed.
17
18
19Support description
20-------------------
21
22- Overview
23
24  - Mbed TLS implements both the client and the server side of the TLS 1.3
25    protocol.
26
27  - Mbed TLS supports ECDHE key establishment.
28
29  - Mbed TLS does not support DHE key establishment.
30
31  - Mbed TLS supports pre-shared keys for key establishment, pre-shared keys
32    provisioned externally as well as provisioned via the ticket mechanism.
33
34  - Mbed TLS supports session resumption via the ticket mechanism.
35
36  - Mbed TLS does not support sending or receiving early data (0-RTT data).
37
38- Supported cipher suites: depends on the library configuration. Potentially
39  all of them:
40  TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256,
41  TLS_AES_128_CCM_SHA256 and TLS_AES_128_CCM_8_SHA256.
42
43- Supported ClientHello extensions:
44
45  | Extension                    | Support |
46  | ---------------------------- | ------- |
47  | server_name                  | YES     |
48  | max_fragment_length          | no      |
49  | status_request               | no      |
50  | supported_groups             | YES     |
51  | signature_algorithms         | YES     |
52  | use_srtp                     | no      |
53  | heartbeat                    | no      |
54  | apln                         | YES     |
55  | signed_certificate_timestamp | no      |
56  | client_certificate_type      | no      |
57  | server_certificate_type      | no      |
58  | padding                      | no      |
59  | key_share                    | YES     |
60  | pre_shared_key               | YES     |
61  | psk_key_exchange_modes       | YES     |
62  | early_data                   | no      |
63  | cookie                       | no      |
64  | supported_versions           | YES     |
65  | certificate_authorities      | no      |
66  | post_handshake_auth          | no      |
67  | signature_algorithms_cert    | no      |
68
69
70- Supported groups: depends on the library configuration.
71  Potentially all ECDHE groups:
72  secp256r1, x25519, secp384r1, x448 and secp521r1.
73
74  Finite field groups (DHE) are not supported.
75
76- Supported signature algorithms (both for certificates and CertificateVerify):
77  depends on the library configuration.
78  Potentially:
79  ecdsa_secp256r1_sha256, ecdsa_secp384r1_sha384, ecdsa_secp521r1_sha512,
80  rsa_pkcs1_sha256, rsa_pkcs1_sha384, rsa_pkcs1_sha512, rsa_pss_rsae_sha256,
81  rsa_pss_rsae_sha384 and rsa_pss_rsae_sha512.
82
83  Note that in absence of an application profile standard specifying otherwise
84  rsa_pkcs1_sha256, rsa_pss_rsae_sha256 and ecdsa_secp256r1_sha256 are
85  mandatory (see section 9.1 of the specification).
86
87- Supported versions:
88
89  - TLS 1.2 and TLS 1.3 with version negotiation on client and server side.
90
91  - TLS 1.2 and TLS 1.3 can be enabled in the build independently of each
92    other.
93
94- Compatibility with existing SSL/TLS build options:
95
96  The TLS 1.3 implementation is compatible with nearly all TLS 1.2
97  configuration options in the sense that when enabling TLS 1.3 in the library
98  there is rarely any need to modify the configuration from that used for
99  TLS 1.2. There are two exceptions though: the TLS 1.3 implementation requires
100  MBEDTLS_PSA_CRYPTO_C and MBEDTLS_SSL_KEEP_PEER_CERTIFICATE, so these options
101  must be enabled.
102
103  Most of the Mbed TLS SSL/TLS related options are not supported or not
104  applicable to the TLS 1.3 implementation:
105
106  | Mbed TLS configuration option            | Support |
107  | ---------------------------------------- | ------- |
108  | MBEDTLS_SSL_ALL_ALERT_MESSAGES           | no      |
109  | MBEDTLS_SSL_ASYNC_PRIVATE                | no      |
110  | MBEDTLS_SSL_CONTEXT_SERIALIZATION        | no      |
111  | MBEDTLS_SSL_DEBUG_ALL                    | no      |
112  | MBEDTLS_SSL_ENCRYPT_THEN_MAC             | n/a     |
113  | MBEDTLS_SSL_EXTENDED_MASTER_SECRET       | n/a     |
114  | MBEDTLS_SSL_KEEP_PEER_CERTIFICATE        | no (1)  |
115  | MBEDTLS_SSL_RENEGOTIATION                | n/a     |
116  | MBEDTLS_SSL_MAX_FRAGMENT_LENGTH          | no      |
117  |                                          |         |
118  | MBEDTLS_SSL_SESSION_TICKETS              | yes     |
119  | MBEDTLS_SSL_SERVER_NAME_INDICATION       | yes     |
120  | MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH       | no      |
121  |                                          |         |
122  | MBEDTLS_ECP_RESTARTABLE                  | no      |
123  | MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED     | no      |
124  |                                          |         |
125  | MBEDTLS_KEY_EXCHANGE_PSK_ENABLED         | n/a (2) |
126  | MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED     | n/a     |
127  | MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED   | n/a     |
128  | MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED     | n/a     |
129  | MBEDTLS_KEY_EXCHANGE_RSA_ENABLED         | n/a     |
130  | MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED     | n/a     |
131  | MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED   | n/a     |
132  | MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED | n/a     |
133  | MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED  | n/a     |
134  | MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED    | n/a     |
135  | MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED     | n/a     |
136  |                                          |         |
137  | MBEDTLS_PSA_CRYPTO_C                     | no (1)  |
138  | MBEDTLS_USE_PSA_CRYPTO                   | yes     |
139
140  (1) These options must remain in their default state of enabled.
141  (2) See the TLS 1.3 specific build options section below.
142
143- TLS 1.3 specific build options:
144
145  - MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE enables the support for middlebox
146    compatibility mode as defined in section D.4 of RFC 8446.
147
148  - MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED enables the support for
149    the PSK key exchange mode as defined by RFC 8446. If it is the only key
150    exchange mode enabled, the TLS 1.3 implementation does not contain any code
151    related to key exchange protocols, certificates and signatures.
152
153  - MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED enables the
154    support for the ephemeral key exchange mode. If it is the only key exchange
155    mode enabled, the TLS 1.3 implementation does not contain any code related
156    to PSK based key exchange. The ephemeral key exchange mode requires at least
157    one of the key exchange protocol allowed by the TLS 1.3 specification, the
158    parsing and validation of x509 certificates and at least one signature
159    algorithm allowed by the TLS 1.3 specification for signature computing and
160    verification.
161
162  - MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED enables the
163    support for the PSK ephemeral key exchange mode. If it is the only key
164    exchange mode enabled, the TLS 1.3 implementation does not contain any code
165    related to certificates and signatures. The PSK ephemeral key exchange
166    mode requires at least one of the key exchange protocol allowed by the
167    TLS 1.3 specification.
168
169
170Prototype upstreaming status
171----------------------------
172
173The following parts of the TLS 1.3 prototype remain to be upstreamed:
174
175- Sending (client) and receiving (server) early data (0-RTT data).
176
177- New TLS Message Processing Stack (MPS)
178
179  The TLS 1.3 prototype is developed alongside a rewrite of the TLS messaging layer,
180  encompassing low-level details such as record parsing, handshake reassembly, and
181  DTLS retransmission state machine.
182
183  MPS has the following components:
184  - Layer 1 (Datagram handling)
185  - Layer 2 (Record handling)
186  - Layer 3 (Message handling)
187  - Layer 4 (Retransmission State Machine)
188  - Reader  (Abstracted pointer arithmetic and reassembly logic for incoming data)
189  - Writer  (Abstracted pointer arithmetic and fragmentation logic for outgoing data)
190
191  Of those components, the following have been upstreamed
192  as part of `MBEDTLS_SSL_PROTO_TLS1_3`:
193
194  - Reader ([`library/mps_reader.h`](../../library/mps_reader.h))
195
196
197Coding rules checklist for TLS 1.3
198----------------------------------
199
200The following coding rules are aimed to be a checklist for TLS 1.3 upstreaming
201work to reduce review rounds and the number of comments in each round. They
202come along (do NOT replace) the project coding rules
203(https://mbed-tls.readthedocs.io/en/latest/kb/development/mbedtls-coding-standards). They have been
204established and discussed following the review of #4882 that was the
205PR upstreaming the first part of TLS 1.3 ClientHello writing code.
206
207TLS 1.3 specific coding rules:
208
209  - TLS 1.3 specific C modules, headers, static functions names are prefixed
210    with `ssl_tls13_`. The same applies to structures and types that are
211    internal to C modules.
212
213  - TLS 1.3 specific exported functions, structures and types are
214    prefixed with `mbedtls_ssl_tls13_`.
215
216  - Use TLS1_3 in TLS 1.3 specific macros.
217
218  - The names of macros and variables related to a field or structure in the
219    TLS 1.3 specification should contain as far as possible the field name as
220    it is in the specification. If the field name is "too long" and we prefer
221    to introduce some kind of abbreviation of it, use the same abbreviation
222    everywhere in the code.
223
224    Example 1: #define CLIENT_HELLO_RANDOM_LEN 32, macro for the length of the
225        `random` field of the ClientHello message.
226
227    Example 2 (consistent abbreviation): `mbedtls_ssl_tls13_write_sig_alg_ext()`
228        and `MBEDTLS_TLS_EXT_SIG_ALG`, `sig_alg` standing for
229        `signature_algorithms`.
230
231  - Regarding vectors that are represented by a length followed by their value
232    in the data exchanged between servers and clients:
233
234    - Use `<vector name>_len` for the name of a variable used to compute the
235      length in bytes of the vector, where <vector name> is the name of the
236      vector as defined in the TLS 1.3 specification.
237
238    - Use `p_<vector_name>_len` for the name of a variable intended to hold
239      the address of the first byte of the vector length.
240
241    - Use `<vector_name>` for the name of a variable intended to hold the
242      address of the first byte of the vector value.
243
244    - Use `<vector_name>_end` for the name of a variable intended to hold
245      the address of the first byte past the vector value.
246
247    Those idioms should lower the risk of mis-using one of the address in place
248    of another one which could potentially lead to some nasty issues.
249
250    Example: `cipher_suites` vector of ClientHello in
251             `ssl_tls13_write_client_hello_cipher_suites()`
252    ```
253    size_t cipher_suites_len;
254    unsigned char *p_cipher_suites_len;
255    unsigned char *cipher_suites;
256    ```
257
258  - Where applicable, use:
259    - the macros to extract a byte from a multi-byte integer MBEDTLS_BYTE_{0-8}.
260    - the macros to write in memory in big-endian order a multi-byte integer
261      MBEDTLS_PUT_UINT{8|16|32|64}_BE.
262    - the macros to read from memory a multi-byte integer in big-endian order
263      MBEDTLS_GET_UINT{8|16|32|64}_BE.
264    - the macro to check for space when writing into an output buffer
265      `MBEDTLS_SSL_CHK_BUF_PTR`.
266    - the macro to check for data when reading from an input buffer
267      `MBEDTLS_SSL_CHK_BUF_READ_PTR`.
268
269    These macros were introduced after the prototype was written thus are
270    likely not to be used in prototype where we now would use them in
271    development.
272
273    The three first types, MBEDTLS_BYTE_{0-8}, MBEDTLS_PUT_UINT{8|16|32|64}_BE
274    and MBEDTLS_GET_UINT{8|16|32|64}_BE improve the readability of the code and
275    reduce the risk of writing or reading bytes in the wrong order.
276
277    The two last types, `MBEDTLS_SSL_CHK_BUF_PTR` and
278    `MBEDTLS_SSL_CHK_BUF_READ_PTR`, improve the readability of the code and
279    reduce the risk of error in the non-completely-trivial arithmetic to
280    check that we do not write or read past the end of a data buffer. The
281    usage of those macros combined with the following rule mitigate the risk
282    to read/write past the end of a data buffer.
283
284    Examples:
285    ```
286    hs_hdr[1] = MBEDTLS_BYTE_2( total_hs_len );
287    MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS, p, 0 );
288    MBEDTLS_SSL_CHK_BUF_PTR( p, end, 7 );
289    ```
290
291  - To mitigate what happened here
292    (https://github.com/Mbed-TLS/mbedtls/pull/4882#discussion_r701704527) from
293    happening again, use always a local variable named `p` for the reading
294    pointer in functions parsing TLS 1.3 data, and for the writing pointer in
295    functions writing data into an output buffer and only that variable. The
296    name `p` has been chosen as it was already widely used in TLS code.
297
298  - When an TLS 1.3 structure is written or read by a function or as part of
299    a function, provide as documentation the definition of the structure as
300    it is in the TLS 1.3 specification.
301
302General coding rules:
303
304  - We prefer grouping "related statement lines" by not adding blank lines
305    between them.
306
307    Example 1:
308    ```
309    ret = ssl_tls13_write_client_hello_cipher_suites( ssl, buf, end, &output_len );
310    if( ret != 0 )
311        return( ret );
312    buf += output_len;
313    ```
314
315    Example 2:
316    ```
317    MBEDTLS_SSL_CHK_BUF_PTR( cipher_suites_iter, end, 2 );
318    MBEDTLS_PUT_UINT16_BE( cipher_suite, cipher_suites_iter, 0 );
319    cipher_suites_iter += 2;
320    ```
321
322  - Use macros for constants that are used in different functions, different
323    places in the code. When a constant is used only locally in a function
324    (like the length in bytes of the vector lengths in functions reading and
325    writing TLS handshake message) there is no need to define a macro for it.
326
327    Example: `#define CLIENT_HELLO_RANDOM_LEN 32`
328
329  - When declaring a pointer the dereferencing operator should be prepended to
330    the pointer name not appended to the pointer type:
331
332    Example: `mbedtls_ssl_context *ssl;`
333
334  - Maximum line length is 80 characters.
335
336    Exceptions:
337
338    - string literals can extend beyond 80 characters as we do not want to
339      split them to ease their search in the code base.
340
341    - A line can be more than 80 characters by a few characters if just looking
342      at the 80 first characters is enough to fully understand the line. For
343      example it is generally fine if some closure characters like ";" or ")"
344      are beyond the 80 characters limit.
345
346    If a line becomes too long due to a refactoring (for example renaming a
347    function to a longer name, or indenting a block more), avoid rewrapping
348    lines in the same commit: it makes the review harder. Make one commit with
349    the longer lines and another commit with just the rewrapping.
350
351  - When in successive lines, functions and macros parameters should be aligned
352    vertically.
353
354    Example:
355    ```
356    int mbedtls_ssl_start_handshake_msg( mbedtls_ssl_context *ssl,
357                                         unsigned hs_type,
358                                         unsigned char **buf,
359                                         size_t *buf_len );
360    ```
361
362  - When a function's parameters span several lines, group related parameters
363    together if possible.
364
365    For example, prefer:
366
367    ```
368    mbedtls_ssl_start_handshake_msg( ssl, hs_type,
369                                     buf, buf_len );
370    ```
371    over
372    ```
373    mbedtls_ssl_start_handshake_msg( ssl, hs_type, buf,
374                                     buf_len );
375    ```
376    even if it fits.
377
378
379Overview of handshake code organization
380---------------------------------------
381
382The TLS 1.3 handshake protocol is implemented as a state machine. The
383functions `mbedtls_ssl_tls13_handshake_{client,server}_step` are the top level
384functions of that implementation. They are implemented as a switch over all the
385possible states of the state machine.
386
387Most of the states are either dedicated to the processing or writing of an
388handshake message.
389
390The implementation does not go systematically through all states as this would
391result in too many checks of whether something needs to be done or not in a
392given state to be duplicated across several state handlers. For example, on
393client side, the states related to certificate parsing and validation are
394bypassed if the handshake is based on a pre-shared key and thus does not
395involve certificates.
396
397On the contrary, the implementation goes systematically though some states
398even if they could be bypassed if it helps in minimizing when and where inbound
399and outbound keys are updated. The `MBEDTLS_SSL_CLIENT_CERTIFICATE` state on
400client side is a example of that.
401
402The names of the handlers processing/writing an handshake message are
403prefixed with `(mbedtls_)ssl_tls13_{process,write}`. To ease the maintenance and
404reduce the risk of bugs, the code of the message processing and writing
405handlers is split into a sequence of stages.
406
407The sending of data to the peer only occurs in `mbedtls_ssl_handshake_step`
408between the calls to the handlers and as a consequence handlers do not have to
409care about the MBEDTLS_ERR_SSL_WANT_WRITE error code. Furthermore, all pending
410data are flushed before to call the next handler. That way, handlers do not
411have to worry about pending data when changing outbound keys.
412
413### Message processing handlers
414For message processing handlers, the stages are:
415
416* coordination stage: check if the state should be bypassed. This stage is
417optional. The check is either purely based on the reading of the value of some
418fields of the SSL context or based on the reading of the type of the next
419message. The latter occurs when it is not known what the next handshake message
420will be, an example of that on client side being if we are going to receive a
421CertificateRequest message or not. The intent is, apart from the next record
422reading to not modify the SSL context as this stage may be repeated if the
423next handshake message has not been received yet.
424
425* fetching stage: at this stage we are sure of the type of the handshake
426message we must receive next and we try to fetch it. If we did not go through
427a coordination stage involving the next record type reading, the next
428handshake message may not have been received yet, the handler returns with
429`MBEDTLS_ERR_SSL_WANT_READ` without changing the current state and it will be
430called again later.
431
432* pre-processing stage: prepare the SSL context for the message parsing. This
433stage is optional. Any processing that must be done before the parsing of the
434message or that can be done to simplify the parsing code. Some simple and
435partial parsing of the handshake message may append at that stage like in the
436ServerHello message pre-processing.
437
438* parsing stage: parse the message and restrict as much as possible any
439update of the SSL context. The idea of the pre-processing/parsing/post-processing
440organization is to concentrate solely on the parsing in the parsing function to
441reduce the size of its code and to simplify it.
442
443* post-processing stage: following the parsing, further update of the SSL
444context to prepare for the next incoming and outgoing messages. This stage is
445optional. For example, secret and key computations occur at this stage, as well
446as handshake messages checksum update.
447
448* state change: the state change is done in the main state handler to ease the
449navigation of the state machine transitions.
450
451
452### Message writing handlers
453For message writing handlers, the stages are:
454
455* coordination stage: check if the state should be bypassed. This stage is
456optional. The check is based on the value of some fields of the SSL context.
457
458* preparation stage: prepare for the message writing. This stage is optional.
459Any processing that must be done before the writing of the message or that can
460be done to simplify the writing code.
461
462* writing stage: write the message and restrict as much as possible any update
463of the SSL context. The idea of the preparation/writing/finalization
464organization is to concentrate solely on the writing in the writing function to
465reduce the size of its code and simplify it.
466
467* finalization stage: following the writing, further update of the SSL
468context to prepare for the next incoming and outgoing messages. This stage is
469optional. For example, handshake secret and key computation occur at that
470stage (ServerHello writing finalization), switching to handshake keys for
471outbound message on server side as well.
472
473* state change: the state change is done in the main state handler to ease
474the navigation of the state machine transitions.
475
476
477Writing and reading early or 0-RTT data
478---------------------------------------
479
480An application function to write and send a buffer of data to a server through
481TLS may plausibly look like:
482
483```
484int write_data( mbedtls_ssl_context *ssl,
485                const unsigned char *data_to_write,
486                size_t data_to_write_len,
487                size_t *data_written )
488{
489    *data_written = 0;
490
491    while( *data_written < data_to_write_len )
492    {
493        ret = mbedtls_ssl_write( ssl, data_to_write + *data_written,
494                                 data_to_write_len - *data_written );
495
496        if( ret < 0 &&
497            ret != MBEDTLS_ERR_SSL_WANT_READ &&
498            ret != MBEDTLS_ERR_SSL_WANT_WRITE )
499        {
500            return( ret );
501        }
502
503        *data_written += ret;
504    }
505
506    return( 0 );
507}
508```
509where ssl is the SSL context to use, data_to_write the address of the data
510buffer and data_to_write_len the number of data bytes. The handshake may
511not be completed, not even started for the SSL context ssl when the function is
512called and in that case the mbedtls_ssl_write() API takes care transparently of
513completing the handshake before to write and send data to the server. The
514mbedtls_ssl_write() may not been able to write and send all data in one go thus
515the need for a loop calling it as long as there are still data to write and
516send.
517
518An application function to write and send early data and only early data,
519data sent during the first flight of client messages while the handshake is in
520its initial phase, would look completely similar but the call to
521mbedtls_ssl_write_early_data() instead of mbedtls_ssl_write().
522```
523int write_early_data( mbedtls_ssl_context *ssl,
524                      const unsigned char *data_to_write,
525                      size_t data_to_write_len,
526                      size_t *data_written )
527{
528    *data_written = 0;
529
530    while( *data_written < data_to_write_len )
531    {
532        ret = mbedtls_ssl_write_early_data( ssl, data_to_write + *data_written,
533                                            data_to_write_len - *data_written );
534
535        if( ret < 0 &&
536            ret != MBEDTLS_ERR_SSL_WANT_READ &&
537            ret != MBEDTLS_ERR_SSL_WANT_WRITE )
538        {
539            return( ret );
540        }
541
542        *data_written += ret;
543    }
544
545    return( 0 );
546}
547```
548Note that compared to write_data(), write_early_data() can also return
549MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA and that should be handled
550specifically by the user of write_early_data(). A fresh SSL context (typically
551just after a call to mbedtls_ssl_setup() or mbedtls_ssl_session_reset()) would
552be expected when calling `write_early_data`.
553
554All together, code to write and send a buffer of data as long as possible as
555early data and then as standard post-handshake application data could
556plausibly look like:
557
558```
559ret = write_early_data( ssl, data_to_write, data_to_write_len,
560                        &early_data_written );
561if( ret < 0 &&
562    ret != MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA )
563{
564    goto error;
565}
566
567ret = write_data( ssl, data_to_write + early_data_written,
568                  data_to_write_len - early_data_written, &data_written );
569if( ret < 0 )
570    goto error;
571
572data_written += early_data_written;
573```
574
575Finally, taking into account that the server may reject early data, application
576code to write and send a buffer of data could plausibly look like:
577```
578ret = write_early_data( ssl, data_to_write, data_to_write_len,
579                        &early_data_written );
580if( ret < 0 &&
581    ret != MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA )
582{
583    goto error;
584}
585
586/*
587 * Make sure the handshake is completed as it is a requisite to
588 * mbedtls_ssl_get_early_data_status().
589 */
590while( !mbedtls_ssl_is_handshake_over( ssl ) )
591{
592    ret = mbedtls_ssl_handshake( ssl );
593    if( ret < 0 &&
594        ret != MBEDTLS_ERR_SSL_WANT_READ &&
595        ret != MBEDTLS_ERR_SSL_WANT_WRITE )
596    {
597        goto error;
598    }
599}
600
601ret = mbedtls_ssl_get_early_data_status( ssl );
602if( ret < 0 )
603    goto error;
604
605if( ret == MBEDTLS_SSL_EARLY_DATA_STATUS_REJECTED )
606   early_data_written = 0;
607
608ret = write_data( ssl, data_to_write + early_data_written,
609                  data_to_write_len - early_data_written, &data_written );
610if( ret < 0 )
611    goto error;
612
613data_written += early_data_written;
614```
615
616Basically, the same holds for reading early data on the server side without the
617complication of possible rejection. An application function to read early data
618into a given buffer could plausibly look like:
619```
620int read_early_data( mbedtls_ssl_context *ssl,
621                     unsigned char *buffer,
622                     size_t buffer_size,
623                     size_t *data_len )
624{
625    *data_len = 0;
626
627    while( *data_len < buffer_size )
628    {
629        ret = mbedtls_ssl_read_early_data( ssl, buffer + *data_len,
630                                           buffer_size - *data_len );
631
632        if( ret < 0 &&
633            ret != MBEDTLS_ERR_SSL_WANT_READ &&
634            ret != MBEDTLS_ERR_SSL_WANT_WRITE )
635        {
636            return( ret );
637        }
638
639        *data_len += ret;
640    }
641
642    return( 0 );
643}
644```
645with again calls to read_early_data() expected to be done with a fresh SSL
646context.
647