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/bio.h>
11 #include <openssl/ssl.h>
12 #include <openssl/err.h>
13 #include "../../ssl_local.h"
14 #include "../record_local.h"
15 
16 typedef struct dtls_bitmap_st {
17     /* Track 64 packets */
18     uint64_t map;
19     /* Max record number seen so far, 64-bit value in big-endian encoding */
20     unsigned char max_seq_num[SEQ_NUM_SIZE];
21 } DTLS_BITMAP;
22 
23 typedef struct ssl_mac_buf_st {
24     unsigned char *mac;
25     int alloced;
26 } SSL_MAC_BUF;
27 
28 typedef struct tls_buffer_st {
29     /* at least SSL3_RT_MAX_PACKET_SIZE bytes */
30     unsigned char *buf;
31     /* default buffer size (or 0 if no default set) */
32     size_t default_len;
33     /* buffer size */
34     size_t len;
35     /* where to 'copy from' */
36     size_t offset;
37     /* how many bytes left */
38     size_t left;
39     /* 'buf' is from application for KTLS */
40     int app_buffer;
41     /* The type of data stored in this buffer. Only used for writing */
42     int type;
43 } TLS_BUFFER;
44 
45 typedef struct tls_rl_record_st {
46     /* Record layer version */
47     /* r */
48     int rec_version;
49     /* type of record */
50     /* r */
51     int type;
52     /* How many bytes available */
53     /* rw */
54     size_t length;
55     /*
56      * How many bytes were available before padding was removed? This is used
57      * to implement the MAC check in constant time for CBC records.
58      */
59     /* rw */
60     size_t orig_len;
61     /* read/write offset into 'buf' */
62     /* r */
63     size_t off;
64     /* pointer to the record data */
65     /* rw */
66     unsigned char *data;
67     /* where the decode bytes are */
68     /* rw */
69     unsigned char *input;
70     /* only used with decompression - malloc()ed */
71     /* r */
72     unsigned char *comp;
73     /* epoch number, needed by DTLS1 */
74     /* r */
75     uint16_t epoch;
76     /* sequence number, needed by DTLS1 */
77     /* r */
78     unsigned char seq_num[SEQ_NUM_SIZE];
79 } TLS_RL_RECORD;
80 
81 /* Macros/functions provided by the TLS_RL_RECORD component */
82 
83 #define TLS_RL_RECORD_set_type(r, t)              ((r)->type = (t))
84 #define TLS_RL_RECORD_set_rec_version(r, v)       ((r)->rec_version = (v))
85 #define TLS_RL_RECORD_get_length(r)               ((r)->length)
86 #define TLS_RL_RECORD_set_length(r, l)            ((r)->length = (l))
87 #define TLS_RL_RECORD_add_length(r, l)            ((r)->length += (l))
88 #define TLS_RL_RECORD_set_data(r, d)              ((r)->data = (d))
89 #define TLS_RL_RECORD_set_input(r, i)             ((r)->input = (i))
90 #define TLS_RL_RECORD_reset_input(r)              ((r)->input = (r)->data)
91 
92 
93 /* Protocol version specific function pointers */
94 struct record_functions_st {
95     /*
96      * Returns either OSSL_RECORD_RETURN_SUCCESS, OSSL_RECORD_RETURN_FATAL or
97      * OSSL_RECORD_RETURN_NON_FATAL_ERR if we can keep trying to find an
98      * alternative record layer.
99      */
100     int (*set_crypto_state)(OSSL_RECORD_LAYER *rl, int level,
101                             unsigned char *key, size_t keylen,
102                             unsigned char *iv, size_t ivlen,
103                             unsigned char *mackey, size_t mackeylen,
104                             const EVP_CIPHER *ciph,
105                             size_t taglen,
106                             int mactype,
107                             const EVP_MD *md,
108                             COMP_METHOD *comp);
109 
110     /*
111      * Returns:
112      *    0: if the record is publicly invalid, or an internal error, or AEAD
113      *       decryption failed, or EtM decryption failed.
114      *    1: Success or MtE decryption failed (MAC will be randomised)
115      */
116     int (*cipher)(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *recs, size_t n_recs,
117                   int sending, SSL_MAC_BUF *macs, size_t macsize);
118     /* Returns 1 for success or 0 for error */
119     int (*mac)(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec, unsigned char *md,
120                int sending);
121 
122     /* Return 1 for success or 0 for error */
123     int (*set_protocol_version)(OSSL_RECORD_LAYER *rl, int version);
124 
125     /* Read related functions */
126 
127     int (*read_n)(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
128                   int clearold, size_t *readbytes);
129 
130     int (*get_more_records)(OSSL_RECORD_LAYER *rl);
131 
132     /* Return 1 for success or 0 for error */
133     int (*validate_record_header)(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec);
134 
135     /* Return 1 for success or 0 for error */
136     int (*post_process_record)(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec);
137 
138     /* Write related functions */
139 
140     size_t (*get_max_records)(OSSL_RECORD_LAYER *rl, uint8_t type, size_t len,
141                               size_t maxfrag, size_t *preffrag);
142 
143     /* Return 1 for success or 0 for error */
144     int (*write_records)(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
145                          size_t numtempl);
146 
147     /* Allocate the rl->wbuf buffers. Return 1 for success or 0 for error */
148     int (*allocate_write_buffers)(OSSL_RECORD_LAYER *rl,
149                                   OSSL_RECORD_TEMPLATE *templates,
150                                   size_t numtempl, size_t *prefix);
151 
152     /*
153      * Initialise the packets in the |pkt| array using the buffers in |rl->wbuf|.
154      * Some protocol versions may use the space in |prefixtempl| to add
155      * an artificial template in front of the |templates| array and hence may
156      * initialise 1 more WPACKET than there are templates. |*wpinited|
157      * returns the number of WPACKETs in |pkt| that were successfully
158      * initialised. This must be 0 on entry and will be filled in even on error.
159      */
160     int (*initialise_write_packets)(OSSL_RECORD_LAYER *rl,
161                                     OSSL_RECORD_TEMPLATE *templates,
162                                     size_t numtempl,
163                                     OSSL_RECORD_TEMPLATE *prefixtempl,
164                                     WPACKET *pkt,
165                                     TLS_BUFFER *bufs,
166                                     size_t *wpinited);
167 
168     /* Get the actual record type to be used for a given template */
169     uint8_t (*get_record_type)(OSSL_RECORD_LAYER *rl,
170                                OSSL_RECORD_TEMPLATE *template);
171 
172     /* Write the record header data to the WPACKET */
173     int (*prepare_record_header)(OSSL_RECORD_LAYER *rl, WPACKET *thispkt,
174                                  OSSL_RECORD_TEMPLATE *templ,
175                                  uint8_t rectype,
176                                  unsigned char **recdata);
177 
178     int (*add_record_padding)(OSSL_RECORD_LAYER *rl,
179                               OSSL_RECORD_TEMPLATE *thistempl,
180                               WPACKET *thispkt,
181                               TLS_RL_RECORD *thiswr);
182 
183     /*
184      * This applies any mac that might be necessary, ensures that we have enough
185      * space in the WPACKET to perform the encryption and sets up the
186      * TLS_RL_RECORD ready for that encryption.
187      */
188     int (*prepare_for_encryption)(OSSL_RECORD_LAYER *rl,
189                                   size_t mac_size,
190                                   WPACKET *thispkt,
191                                   TLS_RL_RECORD *thiswr);
192 
193     /*
194      * Any updates required to the record after encryption has been applied. For
195      * example, adding a MAC if using encrypt-then-mac
196      */
197     int (*post_encryption_processing)(OSSL_RECORD_LAYER *rl,
198                                       size_t mac_size,
199                                       OSSL_RECORD_TEMPLATE *thistempl,
200                                       WPACKET *thispkt,
201                                       TLS_RL_RECORD *thiswr);
202 
203     /*
204      * Some record layer implementations need to do some custom preparation of
205      * the BIO before we write to it. KTLS does this to prevent coalescing of
206      * control and data messages.
207      */
208     int (*prepare_write_bio)(OSSL_RECORD_LAYER *rl, int type);
209 };
210 
211 struct ossl_record_layer_st {
212     OSSL_LIB_CTX *libctx;
213     const char *propq;
214     int isdtls;
215     int version;
216     int role;
217     int direction;
218     int level;
219     const EVP_MD *md;
220     /* DTLS only */
221     uint16_t epoch;
222 
223     /*
224      * A BIO containing any data read in the previous epoch that was destined
225      * for this epoch
226      */
227     BIO *prev;
228 
229     /* The transport BIO */
230     BIO *bio;
231 
232     /*
233      * A BIO where we will send any data read by us that is destined for the
234      * next epoch.
235      */
236     BIO *next;
237 
238     /* Types match the equivalent fields in the SSL object */
239     uint64_t options;
240     uint32_t mode;
241 
242     /* write IO goes into here */
243     TLS_BUFFER wbuf[SSL_MAX_PIPELINES + 1];
244 
245     /* Next wbuf with pending data still to write */
246     size_t nextwbuf;
247 
248     /* How many pipelines can be used to write data */
249     size_t numwpipes;
250 
251     /* read IO goes into here */
252     TLS_BUFFER rbuf;
253     /* each decoded record goes in here */
254     TLS_RL_RECORD rrec[SSL_MAX_PIPELINES];
255 
256     /* How many records have we got available in the rrec buffer */
257     size_t num_recs;
258 
259     /* The record number in the rrec buffer that can be read next */
260     size_t curr_rec;
261 
262     /* The number of records that have been released via tls_release_record */
263     size_t num_released;
264 
265     /* where we are when reading */
266     int rstate;
267 
268     /* used internally to point at a raw packet */
269     unsigned char *packet;
270     size_t packet_length;
271 
272     /* Sequence number for the next record */
273     unsigned char sequence[SEQ_NUM_SIZE];
274 
275     /* Alert code to be used if an error occurs */
276     int alert;
277 
278     /*
279      * Read as many input bytes as possible (for non-blocking reads)
280      */
281     int read_ahead;
282 
283     /* The number of consecutive empty records we have received */
284     size_t empty_record_count;
285 
286     /*
287      * Do we need to send a prefix empty record before application data as a
288      * countermeasure against known-IV weakness (necessary for SSLv3 and
289      * TLSv1.0)
290      */
291     int need_empty_fragments;
292 
293     /* cryptographic state */
294     EVP_CIPHER_CTX *enc_ctx;
295 
296     /* TLSv1.3 MAC ctx, only used with integrity-only cipher */
297     EVP_MAC_CTX *mac_ctx;
298 
299     /* Explicit IV length */
300     size_t eivlen;
301 
302     /* used for mac generation */
303     EVP_MD_CTX *md_ctx;
304 
305     /* compress/uncompress */
306     COMP_CTX *compctx;
307 
308     /* Set to 1 if this is the first handshake. 0 otherwise */
309     int is_first_handshake;
310 
311     /*
312      * The smaller of the configured and negotiated maximum fragment length
313      * or SSL3_RT_MAX_PLAIN_LENGTH if none
314      */
315     unsigned int max_frag_len;
316 
317     /* The maximum amount of early data we can receive/send */
318     uint32_t max_early_data;
319 
320     /* The amount of early data that we have sent/received */
321     size_t early_data_count;
322 
323     /* TLSv1.3 record padding */
324     size_t block_padding;
325     size_t hs_padding;
326 
327     /* Only used by SSLv3 */
328     unsigned char mac_secret[EVP_MAX_MD_SIZE];
329 
330     /* TLSv1.0/TLSv1.1/TLSv1.2 */
331     int use_etm;
332 
333     /* Flags for GOST ciphers */
334     int stream_mac;
335     int tlstree;
336 
337     /* TLSv1.3 fields */
338     unsigned char *iv;     /* static IV */
339     unsigned char *nonce;  /* part of static IV followed by sequence number */
340     int allow_plain_alerts;
341 
342     /* TLS "any" fields */
343     /* Set to true if this is the first record in a connection */
344     unsigned int is_first_record;
345 
346     size_t taglen;
347 
348     /* DTLS received handshake records (processed and unprocessed) */
349     struct pqueue_st *unprocessed_rcds;
350     struct pqueue_st *processed_rcds;
351 
352     /* records being received in the current epoch */
353     DTLS_BITMAP bitmap;
354     /* renegotiation starts a new set of sequence numbers */
355     DTLS_BITMAP next_bitmap;
356 
357     /*
358      * Whether we are currently in a handshake or not. Only maintained for DTLS
359      */
360     int in_init;
361 
362     /* Callbacks */
363     void *cbarg;
364     OSSL_FUNC_rlayer_skip_early_data_fn *skip_early_data;
365     OSSL_FUNC_rlayer_msg_callback_fn *msg_callback;
366     OSSL_FUNC_rlayer_security_fn *security;
367     OSSL_FUNC_rlayer_padding_fn *padding;
368 
369     size_t max_pipelines;
370 
371     /* Function pointers for version specific functions */
372     const struct record_functions_st *funcs;
373 };
374 
375 typedef struct dtls_rlayer_record_data_st {
376     unsigned char *packet;
377     size_t packet_length;
378     TLS_BUFFER rbuf;
379     TLS_RL_RECORD rrec;
380 } DTLS_RLAYER_RECORD_DATA;
381 
382 extern const struct record_functions_st ssl_3_0_funcs;
383 extern const struct record_functions_st tls_1_funcs;
384 extern const struct record_functions_st tls_1_3_funcs;
385 extern const struct record_functions_st tls_any_funcs;
386 extern const struct record_functions_st dtls_1_funcs;
387 extern const struct record_functions_st dtls_any_funcs;
388 
389 void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
390                        const char *fmt, ...);
391 
392 #define RLAYERfatal(rl, al, r) RLAYERfatal_data((rl), (al), (r), NULL)
393 #define RLAYERfatal_data                                           \
394     (ERR_new(),                                                    \
395      ERR_set_debug(OPENSSL_FILE, OPENSSL_LINE, OPENSSL_FUNC),      \
396      ossl_rlayer_fatal)
397 
398 #define RLAYER_USE_EXPLICIT_IV(rl) ((rl)->version == TLS1_1_VERSION \
399                                     || (rl)->version == TLS1_2_VERSION \
400                                     || (rl)->version == DTLS1_BAD_VER \
401                                     || (rl)->version == DTLS1_VERSION \
402                                     || (rl)->version == DTLS1_2_VERSION)
403 
404 void ossl_tls_rl_record_set_seq_num(TLS_RL_RECORD *r,
405                                     const unsigned char *seq_num);
406 
407 int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
408                                      EVP_CIPHER_CTX *ctx,
409                                      const EVP_CIPHER *ciph,
410                                      const EVP_MD *md);
411 
412 int tls_increment_sequence_ctr(OSSL_RECORD_LAYER *rl);
413 int tls_alloc_buffers(OSSL_RECORD_LAYER *rl);
414 int tls_free_buffers(OSSL_RECORD_LAYER *rl);
415 
416 int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
417                        int clearold, size_t *readbytes);
418 int tls_get_more_records(OSSL_RECORD_LAYER *rl);
419 int dtls_get_more_records(OSSL_RECORD_LAYER *rl);
420 
421 int dtls_prepare_record_header(OSSL_RECORD_LAYER *rl,
422                                WPACKET *thispkt,
423                                OSSL_RECORD_TEMPLATE *templ,
424                                uint8_t rectype,
425                                unsigned char **recdata);
426 int dtls_post_encryption_processing(OSSL_RECORD_LAYER *rl,
427                                     size_t mac_size,
428                                     OSSL_RECORD_TEMPLATE *thistempl,
429                                     WPACKET *thispkt,
430                                     TLS_RL_RECORD *thiswr);
431 
432 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version);
433 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *re);
434 int tls_do_compress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *wr);
435 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec);
436 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec);
437 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec);
438 
439 int
440 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
441                          int role, int direction, int level,
442                          const EVP_CIPHER *ciph, size_t taglen,
443                          const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
444                          BIO *transport, BIO *next,
445                          const OSSL_PARAM *settings, const OSSL_PARAM *options,
446                          const OSSL_DISPATCH *fns, void *cbarg,
447                          OSSL_RECORD_LAYER **retrl);
448 int tls_free(OSSL_RECORD_LAYER *rl);
449 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl);
450 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl);
451 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl);
452 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl, uint8_t type, size_t len,
453                            size_t maxfrag, size_t *preffrag);
454 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
455                       size_t numtempl);
456 int tls_retry_write_records(OSSL_RECORD_LAYER *rl);
457 int tls_get_alert_code(OSSL_RECORD_LAYER *rl);
458 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio);
459 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
460                     uint8_t *type, const unsigned char **data, size_t *datalen,
461                     uint16_t *epoch, unsigned char *seq_num);
462 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle, size_t length);
463 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version);
464 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version);
465 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow);
466 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first);
467 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines);
468 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
469                    const char **longstr);
470 int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options);
471 const COMP_METHOD *tls_get_compression(OSSL_RECORD_LAYER *rl);
472 void tls_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len);
473 int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl);
474 int tls_setup_write_buffer(OSSL_RECORD_LAYER *rl, size_t numwpipes,
475                            size_t firstlen, size_t nextlen);
476 
477 int tls_write_records_multiblock(OSSL_RECORD_LAYER *rl,
478                                  OSSL_RECORD_TEMPLATE *templates,
479                                  size_t numtempl);
480 
481 size_t tls_get_max_records_default(OSSL_RECORD_LAYER *rl, uint8_t type,
482                                    size_t len,
483                                    size_t maxfrag, size_t *preffrag);
484 size_t tls_get_max_records_multiblock(OSSL_RECORD_LAYER *rl, uint8_t type,
485                                       size_t len, size_t maxfrag,
486                                       size_t *preffrag);
487 int tls_allocate_write_buffers_default(OSSL_RECORD_LAYER *rl,
488                                        OSSL_RECORD_TEMPLATE *templates,
489                                        size_t numtempl, size_t *prefix);
490 int tls_initialise_write_packets_default(OSSL_RECORD_LAYER *rl,
491                                          OSSL_RECORD_TEMPLATE *templates,
492                                          size_t numtempl,
493                                          OSSL_RECORD_TEMPLATE *prefixtempl,
494                                          WPACKET *pkt,
495                                          TLS_BUFFER *bufs,
496                                          size_t *wpinited);
497 int tls1_allocate_write_buffers(OSSL_RECORD_LAYER *rl,
498                                 OSSL_RECORD_TEMPLATE *templates,
499                                 size_t numtempl, size_t *prefix);
500 int tls1_initialise_write_packets(OSSL_RECORD_LAYER *rl,
501                                   OSSL_RECORD_TEMPLATE *templates,
502                                   size_t numtempl,
503                                   OSSL_RECORD_TEMPLATE *prefixtempl,
504                                   WPACKET *pkt,
505                                   TLS_BUFFER *bufs,
506                                   size_t *wpinited);
507 int tls_prepare_record_header_default(OSSL_RECORD_LAYER *rl,
508                                       WPACKET *thispkt,
509                                       OSSL_RECORD_TEMPLATE *templ,
510                                       uint8_t rectype,
511                                       unsigned char **recdata);
512 int tls_prepare_for_encryption_default(OSSL_RECORD_LAYER *rl,
513                                        size_t mac_size,
514                                        WPACKET *thispkt,
515                                        TLS_RL_RECORD *thiswr);
516 int tls_post_encryption_processing_default(OSSL_RECORD_LAYER *rl,
517                                            size_t mac_size,
518                                            OSSL_RECORD_TEMPLATE *thistempl,
519                                            WPACKET *thispkt,
520                                            TLS_RL_RECORD *thiswr);
521 int tls_write_records_default(OSSL_RECORD_LAYER *rl,
522                               OSSL_RECORD_TEMPLATE *templates,
523                               size_t numtempl);
524 
525 /* Macros/functions provided by the TLS_BUFFER component */
526 
527 #define TLS_BUFFER_get_buf(b)              ((b)->buf)
528 #define TLS_BUFFER_set_buf(b, n)           ((b)->buf = (n))
529 #define TLS_BUFFER_get_len(b)              ((b)->len)
530 #define TLS_BUFFER_get_left(b)             ((b)->left)
531 #define TLS_BUFFER_set_left(b, l)          ((b)->left = (l))
532 #define TLS_BUFFER_sub_left(b, l)          ((b)->left -= (l))
533 #define TLS_BUFFER_get_offset(b)           ((b)->offset)
534 #define TLS_BUFFER_set_offset(b, o)        ((b)->offset = (o))
535 #define TLS_BUFFER_add_offset(b, o)        ((b)->offset += (o))
536 #define TLS_BUFFER_set_app_buffer(b, l)    ((b)->app_buffer = (l))
537 #define TLS_BUFFER_is_app_buffer(b)        ((b)->app_buffer)
538 
539 void ossl_tls_buffer_release(TLS_BUFFER *b);
540