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