xref: /openssl/ssl/record/methods/tls13_meth.c (revision 7d91d5ba)
1 /*
2  * Copyright 2022-2024 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <openssl/evp.h>
11 #include <openssl/core_names.h>
12 #include "../../ssl_local.h"
13 #include "../record_local.h"
14 #include "recmethod_local.h"
15 
tls13_set_crypto_state(OSSL_RECORD_LAYER * rl,int level,unsigned char * key,size_t keylen,unsigned char * iv,size_t ivlen,unsigned char * mackey,size_t mackeylen,const EVP_CIPHER * ciph,size_t taglen,int mactype,const EVP_MD * md,COMP_METHOD * comp)16 static int tls13_set_crypto_state(OSSL_RECORD_LAYER *rl, int level,
17                                   unsigned char *key, size_t keylen,
18                                   unsigned char *iv, size_t ivlen,
19                                   unsigned char *mackey, size_t mackeylen,
20                                   const EVP_CIPHER *ciph,
21                                   size_t taglen,
22                                   int mactype,
23                                   const EVP_MD *md,
24                                   COMP_METHOD *comp)
25 {
26     EVP_CIPHER_CTX *ciph_ctx;
27     EVP_MAC_CTX *mac_ctx;
28     EVP_MAC *mac;
29     OSSL_PARAM params[2], *p = params;
30     int mode;
31     int enc = (rl->direction == OSSL_RECORD_DIRECTION_WRITE) ? 1 : 0;
32 
33     rl->iv = OPENSSL_malloc(ivlen);
34     if (rl->iv == NULL)
35         return OSSL_RECORD_RETURN_FATAL;
36 
37     rl->nonce = OPENSSL_malloc(ivlen);
38     if (rl->nonce == NULL)
39         return OSSL_RECORD_RETURN_FATAL;
40 
41     memcpy(rl->iv, iv, ivlen);
42 
43     /* Integrity only */
44     if (EVP_CIPHER_is_a(ciph, "NULL") && mactype == NID_hmac && md != NULL) {
45         mac = EVP_MAC_fetch(rl->libctx, "HMAC", rl->propq);
46         if (mac == NULL
47             || (mac_ctx = rl->mac_ctx = EVP_MAC_CTX_new(mac)) == NULL) {
48             EVP_MAC_free(mac);
49             ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
50             return OSSL_RECORD_RETURN_FATAL;
51         }
52         EVP_MAC_free(mac);
53         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
54                                                 (char *)EVP_MD_name(md), 0);
55         *p = OSSL_PARAM_construct_end();
56         if (!EVP_MAC_init(mac_ctx, key, keylen, params)) {
57             ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
58             return OSSL_RECORD_RETURN_FATAL;
59         }
60         goto end;
61     }
62 
63     ciph_ctx = rl->enc_ctx = EVP_CIPHER_CTX_new();
64     if (ciph_ctx == NULL) {
65         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
66         return OSSL_RECORD_RETURN_FATAL;
67     }
68 
69     mode = EVP_CIPHER_get_mode(ciph);
70 
71     if (EVP_CipherInit_ex(ciph_ctx, ciph, NULL, NULL, NULL, enc) <= 0
72         || EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen,
73                                NULL) <= 0
74         || (mode == EVP_CIPH_CCM_MODE
75             && EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_TAG, taglen,
76                                    NULL) <= 0)
77         || EVP_CipherInit_ex(ciph_ctx, NULL, NULL, key, NULL, enc) <= 0) {
78         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
79         return OSSL_RECORD_RETURN_FATAL;
80     }
81  end:
82     return OSSL_RECORD_RETURN_SUCCESS;
83 }
84 
tls13_cipher(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * recs,size_t n_recs,int sending,SSL_MAC_BUF * mac,size_t macsize)85 static int tls13_cipher(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *recs,
86                         size_t n_recs, int sending, SSL_MAC_BUF *mac,
87                         size_t macsize)
88 {
89     EVP_CIPHER_CTX *enc_ctx;
90     unsigned char recheader[SSL3_RT_HEADER_LENGTH];
91     unsigned char tag[EVP_MAX_MD_SIZE];
92     size_t nonce_len, offset, loop, hdrlen, taglen;
93     unsigned char *staticiv;
94     unsigned char *nonce;
95     unsigned char *seq = rl->sequence;
96     int lenu, lenf;
97     TLS_RL_RECORD *rec = &recs[0];
98     WPACKET wpkt;
99     const EVP_CIPHER *cipher;
100     EVP_MAC_CTX *mac_ctx = NULL;
101     int mode;
102 
103     if (n_recs != 1) {
104         /* Should not happen */
105         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
106         return 0;
107     }
108 
109     enc_ctx = rl->enc_ctx; /* enc_ctx is ignored when rl->mac_ctx != NULL */
110     staticiv = rl->iv;
111     nonce = rl->nonce;
112 
113     if (enc_ctx == NULL && rl->mac_ctx == NULL) {
114         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
115         return 0;
116     }
117 
118     /*
119      * If we're sending an alert and ctx != NULL then we must be forcing
120      * plaintext alerts. If we're reading and ctx != NULL then we allow
121      * plaintext alerts at certain points in the handshake. If we've got this
122      * far then we have already validated that a plaintext alert is ok here.
123      */
124     if (rec->type == SSL3_RT_ALERT) {
125         memmove(rec->data, rec->input, rec->length);
126         rec->input = rec->data;
127         return 1;
128     }
129 
130     /* For integrity-only ciphers, nonce_len is same as MAC size */
131     if (rl->mac_ctx != NULL) {
132         nonce_len = EVP_MAC_CTX_get_mac_size(rl->mac_ctx);
133     } else {
134         int ivlen = EVP_CIPHER_CTX_get_iv_length(enc_ctx);
135 
136         if (ivlen < 0) {
137             /* Should not happen */
138             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
139             return 0;
140         }
141         nonce_len = (size_t)ivlen;
142     }
143 
144     if (!sending) {
145         /*
146          * Take off tag. There must be at least one byte of content type as
147          * well as the tag
148          */
149         if (rec->length < rl->taglen + 1)
150             return 0;
151         rec->length -= rl->taglen;
152     }
153 
154     /* Set up nonce: part of static IV followed by sequence number */
155     if (nonce_len < SEQ_NUM_SIZE) {
156         /* Should not happen */
157         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
158         return 0;
159     }
160     offset = nonce_len - SEQ_NUM_SIZE;
161     memcpy(nonce, staticiv, offset);
162     for (loop = 0; loop < SEQ_NUM_SIZE; loop++)
163         nonce[offset + loop] = staticiv[offset + loop] ^ seq[loop];
164 
165     if (!tls_increment_sequence_ctr(rl)) {
166         /* RLAYERfatal already called */
167         return 0;
168     }
169 
170     /* Set up the AAD */
171     if (!WPACKET_init_static_len(&wpkt, recheader, sizeof(recheader), 0)
172             || !WPACKET_put_bytes_u8(&wpkt, rec->type)
173             || !WPACKET_put_bytes_u16(&wpkt, rec->rec_version)
174             || !WPACKET_put_bytes_u16(&wpkt, rec->length + rl->taglen)
175             || !WPACKET_get_total_written(&wpkt, &hdrlen)
176             || hdrlen != SSL3_RT_HEADER_LENGTH
177             || !WPACKET_finish(&wpkt)) {
178         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
179         WPACKET_cleanup(&wpkt);
180         return 0;
181     }
182 
183     if (rl->mac_ctx != NULL) {
184         int ret = 0;
185 
186         if ((mac_ctx = EVP_MAC_CTX_dup(rl->mac_ctx)) == NULL
187             || !EVP_MAC_update(mac_ctx, nonce, nonce_len)
188             || !EVP_MAC_update(mac_ctx, recheader, sizeof(recheader))
189             || !EVP_MAC_update(mac_ctx, rec->input, rec->length)
190             || !EVP_MAC_final(mac_ctx, tag, &taglen, rl->taglen)) {
191             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
192             goto end_mac;
193         }
194 
195         if (sending) {
196             memcpy(rec->data + rec->length, tag, rl->taglen);
197             rec->length += rl->taglen;
198         } else if (CRYPTO_memcmp(tag, rec->data + rec->length,
199                                  rl->taglen) != 0) {
200             goto end_mac;
201         }
202         ret = 1;
203     end_mac:
204         EVP_MAC_CTX_free(mac_ctx);
205         return ret;
206     }
207 
208     cipher = EVP_CIPHER_CTX_get0_cipher(enc_ctx);
209     if (cipher == NULL) {
210         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
211         return 0;
212     }
213     mode = EVP_CIPHER_get_mode(cipher);
214 
215     if (EVP_CipherInit_ex(enc_ctx, NULL, NULL, NULL, nonce, sending) <= 0
216         || (!sending && EVP_CIPHER_CTX_ctrl(enc_ctx, EVP_CTRL_AEAD_SET_TAG,
217                                             rl->taglen,
218                                             rec->data + rec->length) <= 0)) {
219         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
220         return 0;
221     }
222 
223     /*
224      * For CCM we must explicitly set the total plaintext length before we add
225      * any AAD.
226      */
227     if ((mode == EVP_CIPH_CCM_MODE
228                  && EVP_CipherUpdate(enc_ctx, NULL, &lenu, NULL,
229                                      (unsigned int)rec->length) <= 0)
230             || EVP_CipherUpdate(enc_ctx, NULL, &lenu, recheader,
231                                 sizeof(recheader)) <= 0
232             || EVP_CipherUpdate(enc_ctx, rec->data, &lenu, rec->input,
233                                 (unsigned int)rec->length) <= 0
234             || EVP_CipherFinal_ex(enc_ctx, rec->data + lenu, &lenf) <= 0
235             || (size_t)(lenu + lenf) != rec->length) {
236         return 0;
237     }
238     if (sending) {
239         /* Add the tag */
240         if (EVP_CIPHER_CTX_ctrl(enc_ctx, EVP_CTRL_AEAD_GET_TAG, rl->taglen,
241                                 rec->data + rec->length) <= 0) {
242             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
243             return 0;
244         }
245         rec->length += rl->taglen;
246     }
247 
248     return 1;
249 }
250 
tls13_validate_record_header(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * rec)251 static int tls13_validate_record_header(OSSL_RECORD_LAYER *rl,
252                                         TLS_RL_RECORD *rec)
253 {
254     if (rec->type != SSL3_RT_APPLICATION_DATA
255             && (rec->type != SSL3_RT_CHANGE_CIPHER_SPEC
256                 || !rl->is_first_handshake)
257             && (rec->type != SSL3_RT_ALERT || !rl->allow_plain_alerts)) {
258         RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
259         return 0;
260     }
261 
262     if (rec->rec_version != TLS1_2_VERSION) {
263         RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_WRONG_VERSION_NUMBER);
264         return 0;
265     }
266 
267     if (rec->length > SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH) {
268         RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
269                     SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
270         return 0;
271     }
272     return 1;
273 }
274 
tls13_post_process_record(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * rec)275 static int tls13_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
276 {
277     /* Skip this if we've received a plaintext alert */
278     if (rec->type != SSL3_RT_ALERT) {
279         size_t end;
280 
281         if (rec->length == 0
282                 || rec->type != SSL3_RT_APPLICATION_DATA) {
283             RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
284                         SSL_R_BAD_RECORD_TYPE);
285             return 0;
286         }
287 
288         /* Strip trailing padding */
289         for (end = rec->length - 1; end > 0 && rec->data[end] == 0; end--)
290             continue;
291 
292         rec->length = end;
293         rec->type = rec->data[end];
294     }
295 
296     if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
297         RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
298         return 0;
299     }
300 
301     if (!tls13_common_post_process_record(rl, rec)) {
302         /* RLAYERfatal already called */
303         return 0;
304     }
305 
306     return 1;
307 }
308 
tls13_get_record_type(OSSL_RECORD_LAYER * rl,OSSL_RECORD_TEMPLATE * template)309 static uint8_t tls13_get_record_type(OSSL_RECORD_LAYER *rl,
310                                      OSSL_RECORD_TEMPLATE *template)
311 {
312     if (rl->allow_plain_alerts && template->type == SSL3_RT_ALERT)
313         return SSL3_RT_ALERT;
314 
315     /*
316      * Aside from the above case we always use the application data record type
317      * when encrypting in TLSv1.3. The "inner" record type encodes the "real"
318      * record type from the template.
319      */
320     return SSL3_RT_APPLICATION_DATA;
321 }
322 
tls13_add_record_padding(OSSL_RECORD_LAYER * rl,OSSL_RECORD_TEMPLATE * thistempl,WPACKET * thispkt,TLS_RL_RECORD * thiswr)323 static int tls13_add_record_padding(OSSL_RECORD_LAYER *rl,
324                                     OSSL_RECORD_TEMPLATE *thistempl,
325                                     WPACKET *thispkt,
326                                     TLS_RL_RECORD *thiswr)
327 {
328     size_t rlen;
329 
330     /* Nothing to be done in the case of a plaintext alert */
331     if (rl->allow_plain_alerts && thistempl->type != SSL3_RT_ALERT)
332         return 1;
333 
334     if (!WPACKET_put_bytes_u8(thispkt, thistempl->type)) {
335         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
336         return 0;
337     }
338     TLS_RL_RECORD_add_length(thiswr, 1);
339 
340     /* Add TLS1.3 padding */
341     rlen = TLS_RL_RECORD_get_length(thiswr);
342     if (rlen < rl->max_frag_len) {
343         size_t padding = 0;
344         size_t max_padding = rl->max_frag_len - rlen;
345 
346         /*
347          * We might want to change the "else if" below so that
348          * library-added padding can still happen even if there
349          * is an application-layer callback. The reason being
350          * the application may not be aware that the effectiveness
351          * of ECH could be damaged if the callback e.g. only
352          * padded application data. However, doing so would be
353          * a change that could break some application that has
354          * a client and server that both know what padding they
355          * like, and that dislike any other padding. That'd need
356          * one of those to have been updated though so the
357          * probability may be low enough that we could change
358          * the "else if" below to just an "if" and pick the
359          * larger of the library and callback's idea of padding.
360          * (Still subject to max_padding though.)
361          */
362         if (rl->padding != NULL) {
363             padding = rl->padding(rl->cbarg, thistempl->type, rlen);
364         } else if (rl->block_padding > 0 || rl->hs_padding > 0) {
365             size_t mask, bp = 0, remainder;
366 
367             /*
368              * pad handshake or alert messages based on |hs_padding|
369              * but application data based on |block_padding|
370              */
371             if (thistempl->type == SSL3_RT_HANDSHAKE && rl->hs_padding > 0)
372                 bp = rl->hs_padding;
373             else if (thistempl->type == SSL3_RT_ALERT && rl->hs_padding > 0)
374                 bp = rl->hs_padding;
375             else if (thistempl->type == SSL3_RT_APPLICATION_DATA
376                      && rl->block_padding > 0)
377                 bp = rl->block_padding;
378             if (bp > 0) {
379                 mask = bp - 1;
380                 /* optimize for power of 2 */
381                 if ((bp & mask) == 0)
382                     remainder = rlen & mask;
383                 else
384                     remainder = rlen % bp;
385                 /* don't want to add a block of padding if we don't have to */
386                 if (remainder == 0)
387                     padding = 0;
388                 else
389                     padding = bp - remainder;
390             }
391         }
392         if (padding > 0) {
393             /* do not allow the record to exceed max plaintext length */
394             if (padding > max_padding)
395                 padding = max_padding;
396             if (!WPACKET_memset(thispkt, 0, padding)) {
397                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
398                             ERR_R_INTERNAL_ERROR);
399                 return 0;
400             }
401             TLS_RL_RECORD_add_length(thiswr, padding);
402         }
403     }
404 
405     return 1;
406 }
407 
408 const struct record_functions_st tls_1_3_funcs = {
409     tls13_set_crypto_state,
410     tls13_cipher,
411     NULL,
412     tls_default_set_protocol_version,
413     tls_default_read_n,
414     tls_get_more_records,
415     tls13_validate_record_header,
416     tls13_post_process_record,
417     tls_get_max_records_default,
418     tls_write_records_default,
419     tls_allocate_write_buffers_default,
420     tls_initialise_write_packets_default,
421     tls13_get_record_type,
422     tls_prepare_record_header_default,
423     tls13_add_record_padding,
424     tls_prepare_for_encryption_default,
425     tls_post_encryption_processing_default,
426     NULL
427 };
428