Debian Codegraph @

crt/s2n/tls/s2n_record_write.c

raw symbols SCIP
1 /*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License").
5 * You may not use this file except in compliance with the License.
6 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15
16 #include <stdint.h>
17
18 #include "crypto/s2n_cipher.h"
19 #include "crypto/s2n_hmac.h"
20 #include "crypto/s2n_sequence.h"
21 #include "error/s2n_errno.h"
22 #include "stuffer/s2n_stuffer.h"
23 #include "tls/s2n_cipher_suites.h"
24 #include "tls/s2n_connection.h"
25 #include "tls/s2n_crypto.h"
26 #include "tls/s2n_ktls.h"
27 #include "tls/s2n_record.h"
28 #include "utils/s2n_blob.h"
29 #include "utils/s2n_random.h"
30 #include "utils/s2n_safety.h"
31
32 extern uint8_t s2n_unknown_protocol_version;
33
34 /* In TLS1.3 the record type is obfuscated as APPLICATION_DATA once the handshake begins to be encrypted.
35 * The real record type is encrypted and written in the final byte of the record.
36 * In TLS1.2 the record type is always cleartext. */
37 #define RECORD_TYPE(is_tls13_record, content_type) (is_tls13_record ? TLS_APPLICATION_DATA : content_type)
38
39 /* How much overhead does the IV, MAC, TAG and padding bytes introduce ? */
40 static S2N_RESULT s2n_tls_record_overhead(struct s2n_connection *conn, uint16_t *out)
41 {
42 RESULT_ENSURE_REF(conn);
43 RESULT_ENSURE_MUT(out);
44 struct s2n_crypto_parameters *active = conn->server;
45
46 if (conn->mode == S2N_CLIENT) {
47 active = conn->client;
48 }
49
50 uint8_t extra = 0;
51 RESULT_GUARD_POSIX(s2n_hmac_digest_size(active->cipher_suite->record_alg->hmac_alg, &extra));
52
53 if (active->cipher_suite->record_alg->cipher->type == S2N_CBC) {
54 /* Subtract one for the padding length byte */
55 extra += 1;
56
57 if (conn->actual_protocol_version > S2N_TLS10) {
58 extra += active->cipher_suite->record_alg->cipher->io.cbc.record_iv_size;
59 }
60 } else if (active->cipher_suite->record_alg->cipher->type == S2N_AEAD) {
61 extra += active->cipher_suite->record_alg->cipher->io.aead.tag_size;
62 extra += active->cipher_suite->record_alg->cipher->io.aead.record_iv_size;
63 } else if (active->cipher_suite->record_alg->cipher->type == S2N_COMPOSITE && conn->actual_protocol_version > S2N_TLS10) {
64 extra += active->cipher_suite->record_alg->cipher->io.comp.record_iv_size;
65 }
66
67 *out = extra;
68
69 return S2N_RESULT_OK;
70 }
71
72 /* This function returns maximum size of plaintext data to write for the payload.
73 * Record overheads are not included here.
74 */
75 S2N_RESULT s2n_record_max_write_payload_size(struct s2n_connection *conn, uint16_t *max_fragment_size)
76 {
77 RESULT_ENSURE_REF(conn);
78 RESULT_ENSURE_REF(conn->config);
79 RESULT_ENSURE_MUT(max_fragment_size);
80 RESULT_ENSURE(conn->max_outgoing_fragment_length > 0, S2N_ERR_FRAGMENT_LENGTH_TOO_SMALL);
81
82 *max_fragment_size = S2N_MIN(conn->max_outgoing_fragment_length, S2N_TLS_MAXIMUM_FRAGMENT_LENGTH);
83
84 /* If a custom send buffer is configured, ensure it will be large enough for the payload.
85 * That may mean we need a smaller fragment size.
86 */
87 uint32_t send_buffer_override = conn->config->send_buffer_size_override;
88 if (send_buffer_override) {
89 uint16_t max_record_size = 0;
90 RESULT_GUARD(s2n_record_max_write_size(conn, *max_fragment_size, &max_record_size));
91 if (send_buffer_override < max_record_size) {
92 size_t overhead = (max_record_size - *max_fragment_size);
93 RESULT_ENSURE_GT(send_buffer_override, overhead);
94 *max_fragment_size = send_buffer_override - overhead;
95 }
96 }
97
98 return S2N_RESULT_OK;
99 }
100
101 S2N_RESULT s2n_record_max_write_size(struct s2n_connection *conn, uint16_t max_fragment_size, uint16_t *max_record_size)
102 {
103 RESULT_ENSURE_REF(conn);
104 RESULT_ENSURE_MUT(max_record_size);
105
106 if (!IS_NEGOTIATED(conn)) {
107 *max_record_size = S2N_TLS_MAX_RECORD_LEN_FOR(max_fragment_size);
108 } else if (conn->actual_protocol_version < S2N_TLS13) {
109 *max_record_size = S2N_TLS12_MAX_RECORD_LEN_FOR(max_fragment_size);
110 } else {
111 *max_record_size = S2N_TLS13_MAX_RECORD_LEN_FOR(max_fragment_size);
112 }
113 return S2N_RESULT_OK;
114 }
115
116 /* Find the largest size that will fit within an ethernet frame for a "small" payload */
117 S2N_RESULT s2n_record_min_write_payload_size(struct s2n_connection *conn, uint16_t *payload_size)
118 {
119 RESULT_ENSURE_REF(conn);
120 RESULT_ENSURE_MUT(payload_size);
121
122 /* remove ethernet, TCP/IP and TLS header overheads */
123 /* We pessimistically assume that it's an Ipv6 header (40 bytes) vs an Ipv4
124 * header (20 bytes) to avoid having to care about the IP protocol. */
125 const uint16_t min_outgoing_fragment_length = ETH_MTU - IP_V6_HEADER_LENGTH
126 - TCP_HEADER_LENGTH - TCP_OPTIONS_LENGTH - S2N_TLS_RECORD_HEADER_LENGTH;
127
128 RESULT_ENSURE(min_outgoing_fragment_length <= S2N_TLS_MAXIMUM_FRAGMENT_LENGTH, S2N_ERR_FRAGMENT_LENGTH_TOO_LARGE);
129 uint16_t size = min_outgoing_fragment_length;
130
131 const struct s2n_crypto_parameters *active = conn->mode == S2N_CLIENT ? conn->client : conn->server;
132
133 /* Round the fragment size down to be block aligned */
134 if (active->cipher_suite->record_alg->cipher->type == S2N_CBC) {
135 size -= size % active->cipher_suite->record_alg->cipher->io.cbc.block_size;
136 } else if (active->cipher_suite->record_alg->cipher->type == S2N_COMPOSITE) {
137 size -= size % active->cipher_suite->record_alg->cipher->io.comp.block_size;
138 /* Composite digest length */
139 size -= active->cipher_suite->record_alg->cipher->io.comp.mac_key_size;
140 /* Padding length byte */
141 size -= 1;
142 }
143
144 /* If TLS1.3, remove content type */
145 if (conn->actual_protocol_version >= S2N_TLS13) {
146 RESULT_ENSURE(size > S2N_TLS_CONTENT_TYPE_LENGTH, S2N_ERR_FRAGMENT_LENGTH_TOO_SMALL);
147 size -= S2N_TLS_CONTENT_TYPE_LENGTH;
148 }
149
150 /* subtract overheads of a TLS record */
151 uint16_t overhead = 0;
152 RESULT_GUARD(s2n_tls_record_overhead(conn, &overhead));
153 RESULT_ENSURE(size > overhead, S2N_ERR_FRAGMENT_LENGTH_TOO_SMALL);
154 size -= overhead;
155
156 RESULT_ENSURE(size > 0, S2N_ERR_FRAGMENT_LENGTH_TOO_SMALL);
157 RESULT_ENSURE(size <= ETH_MTU, S2N_ERR_FRAGMENT_LENGTH_TOO_LARGE);
158
159 *payload_size = size;
160
161 return S2N_RESULT_OK;
162 }
163
164 int s2n_record_write_protocol_version(struct s2n_connection *conn, uint8_t record_type, struct s2n_stuffer *out)
165 {
166 uint8_t record_protocol_version = conn->actual_protocol_version;
167
168 /**
169 *= https://www.rfc-editor.org/rfc/rfc8446#section-5.1
170 *# This version value is historical, deriving from the use of 0x0301 for
171 *# TLS 1.0 and 0x0300 for SSL 3.0. In order to maximize backward
172 *# compatibility, a record containing an initial ClientHello SHOULD have
173 *# version 0x0301 (reflecting TLS 1.0)
174 *
175 * We set actual_protocol_version early for clients, but we do not
176 * use that assumed value here in case we are talking to a legacy
177 * server that expects TLS1.0.
178 *
179 * Both TLS 1.3 early data and a deserialized connection will
180 * send data without the server_protocol_version being known. However,
181 * the record type would be set to APPLICATION_DATA in their cases
182 * so this check is avoided.
183 **/
184 if (conn->server_protocol_version == s2n_unknown_protocol_version
185 && record_type == TLS_HANDSHAKE) {
186 record_protocol_version = S2N_MIN(record_protocol_version, S2N_TLS10);
187 }
188
189 /**
190 *= https://www.rfc-editor.org/rfc/rfc8446#section-5.1
191 *# legacy_record_version: MUST be set to 0x0303 for all records
192 *# generated by a TLS 1.3 implementation other than an initial
193 *# ClientHello (i.e., one not generated after a HelloRetryRequest),
194 *# where it MAY also be 0x0301 for compatibility purposes.
195 **/
196 record_protocol_version = S2N_MIN(record_protocol_version, S2N_TLS12);
197
198 /* Never send an empty protocol version.
199 * If the protocol version is unknown, default to TLS1.0 like we do for initial ClientHellos.
200 */
201 if (record_protocol_version == s2n_unknown_protocol_version) {
202 record_protocol_version = S2N_TLS10;
203 }
204
205 uint8_t protocol_version[S2N_TLS_PROTOCOL_VERSION_LEN];
206 protocol_version[0] = record_protocol_version / 10;
207 protocol_version[1] = record_protocol_version % 10;
208
209 POSIX_GUARD(s2n_stuffer_write_bytes(out, protocol_version, S2N_TLS_PROTOCOL_VERSION_LEN));
210
211 return 0;
212 }
213
214 static inline int s2n_record_encrypt(
215 struct s2n_connection *conn,
216 const struct s2n_cipher_suite *cipher_suite,
217 struct s2n_session_key *session_key,
218 struct s2n_blob *iv,
219 struct s2n_blob *aad,
220 struct s2n_blob *en,
221 uint8_t *implicit_iv, uint16_t block_size)
222 {
223 POSIX_ENSURE_REF(en->data);
224
225 switch (cipher_suite->record_alg->cipher->type) {
226 case S2N_STREAM:
227 POSIX_GUARD(cipher_suite->record_alg->cipher->io.stream.encrypt(session_key, en, en));
228 break;
229 case S2N_CBC:
230 POSIX_GUARD(cipher_suite->record_alg->cipher->io.cbc.encrypt(session_key, iv, en, en));
231
232 /* Copy the last encrypted block to be the next IV */
233 if (conn->actual_protocol_version < S2N_TLS11) {
234 POSIX_ENSURE_GTE(en->size, block_size);
235 POSIX_CHECKED_MEMCPY(implicit_iv, en->data + en->size - block_size, block_size);
236 }
237 break;
238 case S2N_AEAD:
239 POSIX_GUARD(cipher_suite->record_alg->cipher->io.aead.encrypt(session_key, iv, aad, en, en));
240 break;
241 case S2N_COMPOSITE:
242 /* This will: compute mac, append padding, append padding length, and encrypt */
243 POSIX_GUARD(cipher_suite->record_alg->cipher->io.comp.encrypt(session_key, iv, en, en));
244
245 /* Copy the last encrypted block to be the next IV */
246 POSIX_ENSURE_GTE(en->size, block_size);
247 POSIX_CHECKED_MEMCPY(implicit_iv, en->data + en->size - block_size, block_size);
248 break;
249 default:
250 POSIX_BAIL(S2N_ERR_CIPHER_TYPE);
251 break;
252 }
253
254 return 0;
255 }
256
257 static S2N_RESULT s2n_record_write_mac(struct s2n_connection *conn, struct s2n_blob *record_header,
258 struct s2n_blob *plaintext, struct s2n_stuffer *out, uint32_t *bytes_written)
259 {
260 RESULT_ENSURE_REF(conn);
261 RESULT_ENSURE_REF(conn->server);
262 RESULT_ENSURE_REF(conn->client);
263 RESULT_ENSURE_REF(record_header);
264 RESULT_ENSURE_REF(plaintext);
265 RESULT_ENSURE_REF(out);
266 RESULT_ENSURE_REF(bytes_written);
267 *bytes_written = 0;
268
269 struct s2n_hmac_state *mac = &conn->server->server_record_mac;
270 const struct s2n_cipher_suite *cipher_suite = conn->server->cipher_suite;
271 uint8_t *sequence_number = conn->server->server_sequence_number;
272
273 if (conn->mode == S2N_CLIENT) {
274 mac = &conn->client->client_record_mac;
275 cipher_suite = conn->client->cipher_suite;
276 sequence_number = conn->client->client_sequence_number;
277 }
278
279 RESULT_ENSURE_REF(cipher_suite);
280 RESULT_ENSURE_REF(cipher_suite->record_alg);
281
282 if (cipher_suite->record_alg->hmac_alg == S2N_HMAC_NONE) {
283 /* If the S2N_HMAC_NONE algorithm is specified, a MAC should not be explicitly written.
284 * This is the case for AEAD and Composite cipher types, where the MAC is written as part
285 * of encryption. This is also the case for plaintext handshake records, where the null
286 * stream cipher is used.
287 */
288 return S2N_RESULT_OK;
289 }
290
291 /**
292 *= https://www.rfc-editor.org/rfc/rfc5246#section-6.2.3.1
293 *# The MAC is generated as:
294 *#
295 *# MAC(MAC_write_key, seq_num +
296 */
297 RESULT_GUARD_POSIX(s2n_hmac_update(mac, sequence_number, S2N_TLS_SEQUENCE_NUM_LEN));
298
299 struct s2n_stuffer header_stuffer = { 0 };
300 RESULT_GUARD_POSIX(s2n_stuffer_init_written(&header_stuffer, record_header));
301
302 /**
303 *= https://www.rfc-editor.org/rfc/rfc5246#section-6.2.3.1
304 *# TLSCompressed.type +
305 */
306 void *record_type_byte = s2n_stuffer_raw_read(&header_stuffer, sizeof(uint8_t));
307 RESULT_ENSURE_REF(record_type_byte);
308 RESULT_GUARD_POSIX(s2n_hmac_update(mac, record_type_byte, sizeof(uint8_t)));
309
310 /**
311 *= https://www.rfc-editor.org/rfc/rfc5246#section-6.2.3.1
312 *# TLSCompressed.version +
313 */
314 void *protocol_version_bytes = s2n_stuffer_raw_read(&header_stuffer, S2N_TLS_PROTOCOL_VERSION_LEN);
315 RESULT_ENSURE_REF(protocol_version_bytes);
316 if (conn->actual_protocol_version > S2N_SSLv3) {
317 /* SSLv3 doesn't include the protocol version in the MAC. */
318 RESULT_GUARD_POSIX(s2n_hmac_update(mac, protocol_version_bytes, S2N_TLS_PROTOCOL_VERSION_LEN));
319 }
320
321 /**
322 *= https://www.rfc-editor.org/rfc/rfc5246#section-6.2.3.1
323 *# TLSCompressed.length +
324 *
325 * Note that the length field refers to the length of the plaintext content, not the length of
326 * TLSCiphertext fragment written to the record header, which accounts for additional fields
327 * such as the padding and MAC.
328 */
329 uint8_t content_length_bytes[sizeof(uint16_t)] = { 0 };
330 struct s2n_blob content_length_blob = { 0 };
331 RESULT_GUARD_POSIX(s2n_blob_init(&content_length_blob, content_length_bytes, sizeof(content_length_bytes)));
332 struct s2n_stuffer content_length_stuffer = { 0 };
333 RESULT_GUARD_POSIX(s2n_stuffer_init(&content_length_stuffer, &content_length_blob));
334 RESULT_GUARD_POSIX(s2n_stuffer_write_uint16(&content_length_stuffer, plaintext->size));
335 RESULT_GUARD_POSIX(s2n_hmac_update(mac, content_length_bytes, sizeof(content_length_bytes)));
336
337 /**
338 *= https://www.rfc-editor.org/rfc/rfc5246#section-6.2.3.1
339 *# TLSCompressed.fragment);
340 *#
341 *# where "+" denotes concatenation.
342 */
343 RESULT_GUARD_POSIX(s2n_hmac_update(mac, plaintext->data, plaintext->size));
344
345 uint8_t mac_digest_size = 0;
346 RESULT_GUARD_POSIX(s2n_hmac_digest_size(mac->alg, &mac_digest_size));
347 uint8_t *digest = s2n_stuffer_raw_write(out, mac_digest_size);
348 RESULT_ENSURE_REF(digest);
349 RESULT_GUARD_POSIX(s2n_hmac_digest(mac, digest, mac_digest_size));
350 *bytes_written = mac_digest_size;
351
352 RESULT_GUARD_POSIX(s2n_hmac_reset(mac));
353
354 return S2N_RESULT_OK;
355 }
356
357 int s2n_record_writev(struct s2n_connection *conn, uint8_t content_type, const struct iovec *in, int in_count, size_t offs, size_t to_write)
358 {
359 if (conn->ktls_send_enabled) {
360 return s2n_ktls_record_writev(conn, content_type, in, in_count, offs, to_write);
361 }
362
363 struct s2n_blob iv = { 0 };
364 uint8_t padding = 0;
365 uint16_t block_size = 0;
366 uint8_t aad_iv[S2N_TLS_MAX_IV_LEN] = { 0 };
367
368 /* In TLS 1.3, handle CCS message as unprotected records */
369 struct s2n_crypto_parameters *current_client_crypto = conn->client;
370 struct s2n_crypto_parameters *current_server_crypto = conn->server;
371 if (conn->actual_protocol_version == S2N_TLS13 && content_type == TLS_CHANGE_CIPHER_SPEC) {
372 POSIX_ENSURE_REF(conn->initial);
373 conn->client = conn->initial;
374 conn->server = conn->initial;
375 }
376
377 uint8_t *sequence_number = conn->server->server_sequence_number;
378 struct s2n_session_key *session_key = &conn->server->server_key;
379 const struct s2n_cipher_suite *cipher_suite = conn->server->cipher_suite;
380 uint8_t *implicit_iv = conn->server->server_implicit_iv;
381
382 if (conn->mode == S2N_CLIENT) {
383 sequence_number = conn->client->client_sequence_number;
384 session_key = &conn->client->client_key;
385 cipher_suite = conn->client->cipher_suite;
386 implicit_iv = conn->client->client_implicit_iv;
387 }
388
389 /* The NULL stream cipher MUST NEVER be used for ApplicationData.
390 * Writing ApplicationData unencrypted defeats the purpose of TLS. */
391 if (cipher_suite->record_alg->cipher == &s2n_null_cipher) {
392 POSIX_ENSURE(content_type != TLS_APPLICATION_DATA, S2N_ERR_ENCRYPT);
393 }
394
395 const int is_tls13_record = cipher_suite->record_alg->flags & S2N_TLS13_RECORD_AEAD_NONCE;
396 s2n_stack_blob(aad, is_tls13_record ? S2N_TLS13_AAD_LEN : S2N_TLS_MAX_AAD_LEN, S2N_TLS_MAX_AAD_LEN);
397
398 /* If we aren't buffering multiple records, then the output stuffer should be empty. */
399 if (!conn->multirecord_send) {
400 POSIX_ENSURE(s2n_stuffer_data_available(&conn->out) == 0, S2N_ERR_RECORD_STUFFER_NEEDS_DRAINING);
401 }
402
403 /* Before we do anything, we need to figure out what the length of the
404 * fragment is going to be.
405 */
406 uint16_t max_write_payload_size = 0;
407 POSIX_GUARD_RESULT(s2n_record_max_write_payload_size(conn, &max_write_payload_size));
408 const uint16_t data_bytes_to_take = S2N_MIN(to_write, max_write_payload_size);
409
410 uint16_t extra = 0;
411 POSIX_GUARD_RESULT(s2n_tls_record_overhead(conn, &extra));
412
413 /* If we have padding to worry about, figure that out too */
414 if (cipher_suite->record_alg->cipher->type == S2N_CBC) {
415 block_size = cipher_suite->record_alg->cipher->io.cbc.block_size;
416 if (((data_bytes_to_take + extra) % block_size)) {
417 padding = block_size - ((data_bytes_to_take + extra) % block_size);
418 }
419 } else if (cipher_suite->record_alg->cipher->type == S2N_COMPOSITE) {
420 block_size = cipher_suite->record_alg->cipher->io.comp.block_size;
421 }
422
423 if (s2n_stuffer_is_freed(&conn->out)) {
424 /* If the output buffer has not been allocated yet, allocate
425 * at least enough memory to hold a record with the local maximum fragment length.
426 *
427 * The local maximum fragment length is:
428 * 1) The local default configured for new connections
429 * 2) The local value set by the user via s2n_connection_prefer_throughput()
430 * or s2n_connection_prefer_low_latency()
431 * 3) On the server, the minimum of the local value and the value negotiated with the
432 * client via the max_fragment_length extension
433 *
434 * Because this only occurs if the output buffer has not been allocated,
435 * it does NOT resize existing buffers.
436 */
437 uint16_t max_wire_record_size = 0;
438 POSIX_GUARD_RESULT(s2n_record_max_write_size(conn, max_write_payload_size, &max_wire_record_size));
439
440 uint32_t buffer_size = S2N_MAX(conn->config->send_buffer_size_override, max_wire_record_size);
441 POSIX_GUARD(s2n_stuffer_growable_alloc(&conn->out, buffer_size));
442 }
443
444 /* A record only local stuffer used to avoid tainting the conn->out stuffer or overwriting
445 * previous records. It should be used to add an individual record to the out stuffer.
446 */
447 struct s2n_blob record_blob = { 0 };
448 struct s2n_stuffer record_stuffer = { 0 };
449 POSIX_GUARD(s2n_blob_init(&record_blob,
450 conn->out.blob.data + conn->out.write_cursor,
451 s2n_stuffer_space_remaining(&conn->out)));
452 POSIX_GUARD(s2n_stuffer_init(&record_stuffer, &record_blob));
453
454 /* Now that we know the length, start writing the record */
455 uint8_t record_type = RECORD_TYPE(is_tls13_record, content_type);
456 POSIX_GUARD(s2n_stuffer_write_uint8(&record_stuffer, record_type));
457 POSIX_GUARD(s2n_record_write_protocol_version(conn, record_type, &record_stuffer));
458
459 /* Compute non-payload parts of the MAC(seq num, type, proto vers, fragment length) for composite ciphers.
460 * Composite "encrypt" will MAC the payload data and fill in padding.
461 */
462 if (cipher_suite->record_alg->cipher->type == S2N_COMPOSITE) {
463 /* Only fragment length is needed for MAC, but the EVP ctrl function needs fragment length + eiv len. */
464 uint16_t payload_and_eiv_len = data_bytes_to_take;
465 if (conn->actual_protocol_version > S2N_TLS10) {
466 payload_and_eiv_len += block_size;
467 }
468
469 /* Outputs number of extra bytes required for MAC and padding */
470 int pad_and_mac_len = 0;
471 POSIX_GUARD(cipher_suite->record_alg->cipher->io.comp.initial_hmac(session_key, sequence_number, content_type, conn->actual_protocol_version,
472 payload_and_eiv_len, &pad_and_mac_len));
473 extra += pad_and_mac_len;
474 }
475
476 /* TLS 1.3 protected record occupies one extra byte for content type */
477 if (is_tls13_record) {
478 extra += S2N_TLS_CONTENT_TYPE_LENGTH;
479 }
480
481 /* Rewrite the length to be the actual fragment length */
482 const uint16_t actual_fragment_length = data_bytes_to_take + padding + extra;
483 /* ensure actual_fragment_length + S2N_TLS_RECORD_HEADER_LENGTH <= max record length */
484 const uint16_t max_record_length = is_tls13_record ? S2N_TLS13_MAXIMUM_RECORD_LENGTH : S2N_TLS_MAXIMUM_RECORD_LENGTH;
485 S2N_ERROR_IF(actual_fragment_length + S2N_TLS_RECORD_HEADER_LENGTH > max_record_length, S2N_ERR_RECORD_LENGTH_TOO_LARGE);
486 POSIX_GUARD(s2n_stuffer_write_uint16(&record_stuffer, actual_fragment_length));
487
488 /* If we're AEAD, write the sequence number as an IV, and generate the AAD */
489 if (cipher_suite->record_alg->cipher->type == S2N_AEAD) {
490 struct s2n_stuffer iv_stuffer = { 0 };
491 POSIX_GUARD(s2n_blob_init(&iv, aad_iv, sizeof(aad_iv)));
492 POSIX_GUARD(s2n_stuffer_init(&iv_stuffer, &iv));
493
494 if (cipher_suite->record_alg->flags & S2N_TLS12_AES_GCM_AEAD_NONCE) {
495 /* Partially explicit nonce. See RFC 5288 Section 3 */
496 POSIX_GUARD(s2n_stuffer_write_bytes(&record_stuffer, sequence_number, S2N_TLS_SEQUENCE_NUM_LEN));
497 POSIX_GUARD(s2n_stuffer_write_bytes(&iv_stuffer, implicit_iv, cipher_suite->record_alg->cipher->io.aead.fixed_iv_size));
498 POSIX_GUARD(s2n_stuffer_write_bytes(&iv_stuffer, sequence_number, S2N_TLS_SEQUENCE_NUM_LEN));
499 } else if (cipher_suite->record_alg->flags & S2N_TLS12_CHACHA_POLY_AEAD_NONCE || is_tls13_record) {
500 /* Fully implicit nonce. See RFC7905 Section 2 */
501 uint8_t four_zeroes[4] = { 0 };
502 POSIX_GUARD(s2n_stuffer_write_bytes(&iv_stuffer, four_zeroes, 4));
503 POSIX_GUARD(s2n_stuffer_write_bytes(&iv_stuffer, sequence_number, S2N_TLS_SEQUENCE_NUM_LEN));
504 for (int i = 0; i < cipher_suite->record_alg->cipher->io.aead.fixed_iv_size; i++) {
505 aad_iv[i] = aad_iv[i] ^ implicit_iv[i];
506 }
507 } else {
508 POSIX_BAIL(S2N_ERR_INVALID_NONCE_TYPE);
509 }
510
511 /* Set the IV size to the amount of data written */
512 iv.size = s2n_stuffer_data_available(&iv_stuffer);
513 if (is_tls13_record) {
514 POSIX_GUARD_RESULT(s2n_tls13_aead_aad_init(data_bytes_to_take + S2N_TLS_CONTENT_TYPE_LENGTH, cipher_suite->record_alg->cipher->io.aead.tag_size, &aad));
515 } else {
516 POSIX_GUARD_RESULT(s2n_aead_aad_init(conn, sequence_number, content_type, data_bytes_to_take, &aad));
517 }
518 } else if (cipher_suite->record_alg->cipher->type == S2N_CBC || cipher_suite->record_alg->cipher->type == S2N_COMPOSITE) {
519 POSIX_GUARD(s2n_blob_init(&iv, implicit_iv, block_size));
520
521 /* For TLS1.1/1.2; write the IV with random data */
522 if (conn->actual_protocol_version > S2N_TLS10) {
523 POSIX_GUARD_RESULT(s2n_get_public_random_data(&iv));
524 if (cipher_suite->record_alg->cipher->type == S2N_COMPOSITE) {
525 /* Write a separate random block to the record. This will be used along with the previously generated
526 * iv blob to generate the final explicit_iv for this record.
527 *
528 * How? Openssl's AES-CBC stitched encrypt populates the first block of application data with:
529 * AES(Key, XOR(iv, initial_block))
530 *
531 * If we make initial_block a random block unrelated to random_iv, explicit IV for this record
532 * is random value based on the two random blobs we just generated:
533 * AES(Key, XOR(random_iv, explicit_iv_placeholder) == AES(Key, XOR(random_iv, random_iv2))
534 *
535 * NOTE: We can't use the same random IV blob as both the initial block and IV since it will result in:
536 * AES(Key, XOR(random_iv, random_iv)) == AES(Key, 0), which will be shared by all records in this session.
537 */
538 struct s2n_blob explicit_iv_placeholder = { 0 };
539 uint8_t zero_block[S2N_TLS_MAX_IV_LEN] = { 0 };
540 POSIX_GUARD(s2n_blob_init(&explicit_iv_placeholder, zero_block, block_size));
541 POSIX_GUARD_RESULT(s2n_get_public_random_data(&explicit_iv_placeholder));
542 POSIX_GUARD(s2n_stuffer_write(&record_stuffer, &explicit_iv_placeholder));
543 } else {
544 /* We can write the explicit IV directly to the record for non composite CBC because
545 * s2n starts AES *after* the explicit IV.
546 */
547 POSIX_GUARD(s2n_stuffer_write(&record_stuffer, &iv));
548 }
549 }
550 }
551
552 /* Write the plaintext data */
553 POSIX_GUARD(s2n_stuffer_writev_bytes(&record_stuffer, in, in_count, offs, data_bytes_to_take));
554 void *orig_write_ptr = record_stuffer.blob.data + record_stuffer.write_cursor - data_bytes_to_take;
555
556 /* Write the MAC */
557 struct s2n_blob header_blob = { 0 };
558 POSIX_GUARD(s2n_blob_slice(&record_blob, &header_blob, 0, S2N_TLS_RECORD_HEADER_LENGTH));
559 struct s2n_blob plaintext_blob = { 0 };
560 POSIX_GUARD(s2n_blob_init(&plaintext_blob, orig_write_ptr, data_bytes_to_take));
561 uint32_t mac_digest_size = 0;
562 POSIX_GUARD_RESULT(s2n_record_write_mac(conn, &header_blob, &plaintext_blob, &record_stuffer, &mac_digest_size));
563
564 /* We are done with this sequence number, so we can increment it */
565 struct s2n_blob seq = { 0 };
566 POSIX_GUARD(s2n_blob_init(&seq, sequence_number, S2N_TLS_SEQUENCE_NUM_LEN));
567 POSIX_GUARD(s2n_increment_sequence_number(&seq));
568
569 /* Write content type for TLS 1.3 record (RFC 8446 Section 5.2) */
570 if (is_tls13_record) {
571 POSIX_GUARD(s2n_stuffer_write_uint8(&record_stuffer, content_type));
572 }
573
574 if (cipher_suite->record_alg->cipher->type == S2N_CBC) {
575 /* Include padding bytes, each with the value 'p', and
576 * include an extra padding length byte, also with the value 'p'.
577 */
578 for (int i = 0; i <= padding; i++) {
579 POSIX_GUARD(s2n_stuffer_write_uint8(&record_stuffer, padding));
580 }
581 }
582
583 /* Rewind to rewrite/encrypt the packet */
584 POSIX_GUARD(s2n_stuffer_rewrite(&record_stuffer));
585
586 /* Skip the header */
587 POSIX_GUARD(s2n_stuffer_skip_write(&record_stuffer, S2N_TLS_RECORD_HEADER_LENGTH));
588
589 uint16_t encrypted_length = data_bytes_to_take + mac_digest_size;
590 switch (cipher_suite->record_alg->cipher->type) {
591 case S2N_AEAD:
592 POSIX_GUARD(s2n_stuffer_skip_write(&record_stuffer, cipher_suite->record_alg->cipher->io.aead.record_iv_size));
593 encrypted_length += cipher_suite->record_alg->cipher->io.aead.tag_size;
594 if (is_tls13_record) {
595 /* one extra byte for content type */
596 encrypted_length += S2N_TLS_CONTENT_TYPE_LENGTH;
597 }
598 break;
599 case S2N_CBC:
600 if (conn->actual_protocol_version > S2N_TLS10) {
601 /* Leave the IV alone and unencrypted */
602 POSIX_GUARD(s2n_stuffer_skip_write(&record_stuffer, iv.size));
603 }
604 /* Encrypt the padding and the padding length byte too */
605 encrypted_length += padding + 1;
606 break;
607 case S2N_COMPOSITE:
608 /* Composite CBC expects a pointer starting at explicit IV: [Explicit IV | fragment | MAC | padding | padding len ]
609 * extra will account for the explicit IV len(if applicable), MAC digest len, padding len + padding byte.
610 */
611 encrypted_length += extra;
612 break;
613 default:
614 break;
615 }
616
617 /* Check that stuffer have enough space to write encrypted record, because raw_write cannot expand tainted stuffer */
618 S2N_ERROR_IF(s2n_stuffer_space_remaining(&record_stuffer) < encrypted_length, S2N_ERR_RECORD_STUFFER_SIZE);
619
620 /* Do the encryption */
621 struct s2n_blob en = { .size = encrypted_length, .data = s2n_stuffer_raw_write(&record_stuffer, encrypted_length) };
622 POSIX_GUARD(s2n_record_encrypt(conn, cipher_suite, session_key, &iv, &aad, &en, implicit_iv, block_size));
623
624 /* Sync the out stuffer write cursor with the record stuffer. */
625 POSIX_GUARD(s2n_stuffer_skip_write(&conn->out, s2n_stuffer_data_available(&record_stuffer)));
626
627 if (conn->actual_protocol_version == S2N_TLS13 && content_type == TLS_CHANGE_CIPHER_SPEC) {
628 conn->client = current_client_crypto;
629 conn->server = current_server_crypto;
630 }
631
632 return data_bytes_to_take;
633 }
634
635 S2N_RESULT s2n_record_write(struct s2n_connection *conn, uint8_t content_type, struct s2n_blob *in)
636 {
637 struct iovec iov;
638 iov.iov_base = in->data;
639 iov.iov_len = in->size;
640 int written = s2n_record_writev(conn, content_type, &iov, 1, 0, in->size);
641 RESULT_GUARD_POSIX(written);
642 RESULT_ENSURE((uint32_t) written == in->size, S2N_ERR_FRAGMENT_LENGTH_TOO_LARGE);
643 return S2N_RESULT_OK;
644 }