Pass the dtls record version to the record layer msg_callback function.
[openssl.git] / ssl / record / methods / dtls_meth.c
1 /*
2  * Copyright 2018-2023 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 <assert.h>
11 #include "../../ssl_local.h"
12 #include "../record_local.h"
13 #include "recmethod_local.h"
14
15 /* mod 128 saturating subtract of two 64-bit values in big-endian order */
16 static int satsub64be(const unsigned char *v1, const unsigned char *v2)
17 {
18     int64_t ret;
19     uint64_t l1, l2;
20
21     n2l8(v1, l1);
22     n2l8(v2, l2);
23
24     ret = l1 - l2;
25
26     /* We do not permit wrap-around */
27     if (l1 > l2 && ret < 0)
28         return 128;
29     else if (l2 > l1 && ret > 0)
30         return -128;
31
32     if (ret > 128)
33         return 128;
34     else if (ret < -128)
35         return -128;
36     else
37         return (int)ret;
38 }
39
40 static int dtls_record_replay_check(OSSL_RECORD_LAYER *rl, DTLS_BITMAP *bitmap)
41 {
42     int cmp;
43     unsigned int shift;
44     const unsigned char *seq = rl->sequence;
45
46     cmp = satsub64be(seq, bitmap->max_seq_num);
47     if (cmp > 0) {
48         ossl_tls_rl_record_set_seq_num(&rl->rrec[0], seq);
49         return 1;               /* this record in new */
50     }
51     shift = -cmp;
52     if (shift >= sizeof(bitmap->map) * 8)
53         return 0;               /* stale, outside the window */
54     else if (bitmap->map & ((uint64_t)1 << shift))
55         return 0;               /* record previously received */
56
57     ossl_tls_rl_record_set_seq_num(&rl->rrec[0], seq);
58     return 1;
59 }
60
61 static void dtls_record_bitmap_update(OSSL_RECORD_LAYER *rl,
62                                       DTLS_BITMAP *bitmap)
63 {
64     int cmp;
65     unsigned int shift;
66     const unsigned char *seq = rl->sequence;
67
68     cmp = satsub64be(seq, bitmap->max_seq_num);
69     if (cmp > 0) {
70         shift = cmp;
71         if (shift < sizeof(bitmap->map) * 8)
72             bitmap->map <<= shift, bitmap->map |= 1UL;
73         else
74             bitmap->map = 1UL;
75         memcpy(bitmap->max_seq_num, seq, SEQ_NUM_SIZE);
76     } else {
77         shift = -cmp;
78         if (shift < sizeof(bitmap->map) * 8)
79             bitmap->map |= (uint64_t)1 << shift;
80     }
81 }
82
83 static DTLS_BITMAP *dtls_get_bitmap(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rr,
84                                     unsigned int *is_next_epoch)
85 {
86     *is_next_epoch = 0;
87
88     /* In current epoch, accept HM, CCS, DATA, & ALERT */
89     if (rr->epoch == rl->epoch)
90         return &rl->bitmap;
91
92     /*
93      * We can only handle messages from the next epoch if we have already
94      * processed all of the unprocessed records from the previous epoch
95      */
96     else if (rr->epoch == (unsigned long)(rl->epoch + 1)
97              && rl->unprocessed_rcds.epoch != rl->epoch) {
98         *is_next_epoch = 1;
99         return &rl->next_bitmap;
100     }
101
102     return NULL;
103 }
104
105 static void dtls_set_in_init(OSSL_RECORD_LAYER *rl, int in_init)
106 {
107     rl->in_init = in_init;
108 }
109
110 static int dtls_process_record(OSSL_RECORD_LAYER *rl, DTLS_BITMAP *bitmap)
111 {
112     int i;
113     int enc_err;
114     TLS_RL_RECORD *rr;
115     int imac_size;
116     size_t mac_size = 0;
117     unsigned char md[EVP_MAX_MD_SIZE];
118     SSL_MAC_BUF macbuf = { NULL, 0 };
119     int ret = 0;
120
121     rr = &rl->rrec[0];
122
123     /*
124      * At this point, rl->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length,
125      * and we have that many bytes in rl->packet
126      */
127     rr->input = &(rl->packet[DTLS1_RT_HEADER_LENGTH]);
128
129     /*
130      * ok, we can now read from 'rl->packet' data into 'rr'. rr->input
131      * points at rr->length bytes, which need to be copied into rr->data by
132      * either the decryption or by the decompression. When the data is 'copied'
133      * into the rr->data buffer, rr->input will be pointed at the new buffer
134      */
135
136     /*
137      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
138      * bytes of encrypted compressed stuff.
139      */
140
141     /* check is not needed I believe */
142     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
143         RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
144         return 0;
145     }
146
147     /* decrypt in place in 'rr->input' */
148     rr->data = rr->input;
149     rr->orig_len = rr->length;
150
151     if (rl->md_ctx != NULL) {
152         const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
153
154         if (tmpmd != NULL) {
155             imac_size = EVP_MD_get_size(tmpmd);
156             if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
157                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
158                 return 0;
159             }
160             mac_size = (size_t)imac_size;
161         }
162     }
163
164     if (rl->use_etm && rl->md_ctx != NULL) {
165         unsigned char *mac;
166
167         if (rr->orig_len < mac_size) {
168             RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
169             return 0;
170         }
171         rr->length -= mac_size;
172         mac = rr->data + rr->length;
173         i = rl->funcs->mac(rl, rr, md, 0 /* not send */);
174         if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
175             RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
176                         SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
177             return 0;
178         }
179         /*
180          * We've handled the mac now - there is no MAC inside the encrypted
181          * record
182          */
183         mac_size = 0;
184     }
185
186     /*
187      * Set a mark around the packet decryption attempt.  This is DTLS, so
188      * bad packets are just ignored, and we don't want to leave stray
189      * errors in the queue from processing bogus junk that we ignored.
190      */
191     ERR_set_mark();
192     enc_err = rl->funcs->cipher(rl, rr, 1, 0, &macbuf, mac_size);
193
194     /*-
195      * enc_err is:
196      *    0: if the record is publicly invalid, or an internal error, or AEAD
197      *       decryption failed, or ETM decryption failed.
198      *    1: Success or MTE decryption failed (MAC will be randomised)
199      */
200     if (enc_err == 0) {
201         ERR_pop_to_mark();
202         if (rl->alert != SSL_AD_NO_ALERT) {
203             /* RLAYERfatal() already called */
204             goto end;
205         }
206         /* For DTLS we simply ignore bad packets. */
207         rr->length = 0;
208         rl->packet_length = 0;
209         goto end;
210     }
211     ERR_clear_last_mark();
212     OSSL_TRACE_BEGIN(TLS) {
213         BIO_printf(trc_out, "dec %zd\n", rr->length);
214         BIO_dump_indent(trc_out, rr->data, rr->length, 4);
215     } OSSL_TRACE_END(TLS);
216
217     /* r->length is now the compressed data plus mac */
218     if (!rl->use_etm
219             && (rl->enc_ctx != NULL)
220             && (EVP_MD_CTX_get0_md(rl->md_ctx) != NULL)) {
221         /* rl->md_ctx != NULL => mac_size != -1 */
222
223         i = rl->funcs->mac(rl, rr, md, 0 /* not send */);
224         if (i == 0 || macbuf.mac == NULL
225             || CRYPTO_memcmp(md, macbuf.mac, mac_size) != 0)
226             enc_err = 0;
227         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
228             enc_err = 0;
229     }
230
231     if (enc_err == 0) {
232         /* decryption failed, silently discard message */
233         rr->length = 0;
234         rl->packet_length = 0;
235         goto end;
236     }
237
238     /* r->length is now just compressed */
239     if (rl->compctx != NULL) {
240         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
241             RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
242                         SSL_R_COMPRESSED_LENGTH_TOO_LONG);
243             goto end;
244         }
245         if (!tls_do_uncompress(rl, rr)) {
246             RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE, SSL_R_BAD_DECOMPRESSION);
247             goto end;
248         }
249     }
250
251     /*
252      * Check if the received packet overflows the current Max Fragment
253      * Length setting.
254      */
255     if (rr->length > rl->max_frag_len) {
256         RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
257         goto end;
258     }
259
260     rr->off = 0;
261     /*-
262      * So at this point the following is true
263      * ssl->s3.rrec.type   is the type of record
264      * ssl->s3.rrec.length == number of bytes in record
265      * ssl->s3.rrec.off    == offset to first valid byte
266      * ssl->s3.rrec.data   == where to take bytes from, increment
267      *                        after use :-).
268      */
269
270     /* we have pulled in a full packet so zero things */
271     rl->packet_length = 0;
272
273     /* Mark receipt of record. */
274     dtls_record_bitmap_update(rl, bitmap);
275
276     ret = 1;
277  end:
278     if (macbuf.alloced)
279         OPENSSL_free(macbuf.mac);
280     return ret;
281 }
282
283 static int dtls_rlayer_buffer_record(OSSL_RECORD_LAYER *rl, record_pqueue *queue,
284                                      unsigned char *priority)
285 {
286     DTLS_RLAYER_RECORD_DATA *rdata;
287     pitem *item;
288
289     /* Limit the size of the queue to prevent DOS attacks */
290     if (pqueue_size(queue->q) >= 100)
291         return 0;
292
293     rdata = OPENSSL_malloc(sizeof(*rdata));
294     item = pitem_new(priority, rdata);
295     if (rdata == NULL || item == NULL) {
296         OPENSSL_free(rdata);
297         pitem_free(item);
298         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
299         return -1;
300     }
301
302     rdata->packet = rl->packet;
303     rdata->packet_length = rl->packet_length;
304     memcpy(&(rdata->rbuf), &rl->rbuf, sizeof(TLS_BUFFER));
305     memcpy(&(rdata->rrec), &rl->rrec[0], sizeof(TLS_RL_RECORD));
306
307     item->data = rdata;
308
309     rl->packet = NULL;
310     rl->packet_length = 0;
311     memset(&rl->rbuf, 0, sizeof(TLS_BUFFER));
312     memset(&rl->rrec[0], 0, sizeof(rl->rrec[0]));
313
314     if (!tls_setup_read_buffer(rl)) {
315         /* RLAYERfatal() already called */
316         OPENSSL_free(rdata->rbuf.buf);
317         OPENSSL_free(rdata);
318         pitem_free(item);
319         return -1;
320     }
321
322     if (pqueue_insert(queue->q, item) == NULL) {
323         /* Must be a duplicate so ignore it */
324         OPENSSL_free(rdata->rbuf.buf);
325         OPENSSL_free(rdata);
326         pitem_free(item);
327     }
328
329     return 1;
330 }
331
332 /* copy buffered record into OSSL_RECORD_LAYER structure */
333 static int dtls_copy_rlayer_record(OSSL_RECORD_LAYER *rl, pitem *item)
334 {
335     DTLS_RLAYER_RECORD_DATA *rdata;
336
337     rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
338
339     ossl_tls_buffer_release(&rl->rbuf);
340
341     rl->packet = rdata->packet;
342     rl->packet_length = rdata->packet_length;
343     memcpy(&rl->rbuf, &(rdata->rbuf), sizeof(TLS_BUFFER));
344     memcpy(&rl->rrec[0], &(rdata->rrec), sizeof(TLS_RL_RECORD));
345
346     /* Set proper sequence number for mac calculation */
347     memcpy(&(rl->sequence[2]), &(rdata->packet[5]), 6);
348
349     return 1;
350 }
351
352 static int dtls_retrieve_rlayer_buffered_record(OSSL_RECORD_LAYER *rl,
353                                                 record_pqueue *queue)
354 {
355     pitem *item;
356
357     item = pqueue_pop(queue->q);
358     if (item) {
359         dtls_copy_rlayer_record(rl, item);
360
361         OPENSSL_free(item->data);
362         pitem_free(item);
363
364         return 1;
365     }
366
367     return 0;
368 }
369
370 /*-
371  * Call this to get a new input record.
372  * It will return <= 0 if more data is needed, normally due to an error
373  * or non-blocking IO.
374  * When it finishes, one packet has been decoded and can be found in
375  * ssl->s3.rrec.type    - is the type of record
376  * ssl->s3.rrec.data    - data
377  * ssl->s3.rrec.length  - number of bytes
378  */
379 int dtls_get_more_records(OSSL_RECORD_LAYER *rl)
380 {
381     int ssl_major, ssl_minor;
382     int rret;
383     size_t more, n;
384     TLS_RL_RECORD *rr;
385     unsigned char *p = NULL;
386     DTLS_BITMAP *bitmap;
387     unsigned int is_next_epoch;
388
389     rl->num_recs = 0;
390     rl->curr_rec = 0;
391     rl->num_released = 0;
392
393     rr = rl->rrec;
394
395     if (rl->rbuf.buf == NULL) {
396         if (!tls_setup_read_buffer(rl)) {
397             /* RLAYERfatal() already called */
398             return OSSL_RECORD_RETURN_FATAL;
399         }
400     }
401
402  again:
403     /* if we're renegotiating, then there may be buffered records */
404     if (dtls_retrieve_rlayer_buffered_record(rl, &rl->processed_rcds)) {
405         rl->num_recs = 1;
406         return OSSL_RECORD_RETURN_SUCCESS;
407     }
408
409     /* get something from the wire */
410
411     /* check if we have the header */
412     if ((rl->rstate != SSL_ST_READ_BODY) ||
413         (rl->packet_length < DTLS1_RT_HEADER_LENGTH)) {
414         rret = rl->funcs->read_n(rl, DTLS1_RT_HEADER_LENGTH,
415                                  TLS_BUFFER_get_len(&rl->rbuf), 0, 1, &n);
416         /* read timeout is handled by dtls1_read_bytes */
417         if (rret < OSSL_RECORD_RETURN_SUCCESS) {
418             /* RLAYERfatal() already called if appropriate */
419             return rret;         /* error or non-blocking */
420         }
421
422         /* this packet contained a partial record, dump it */
423         if (rl->packet_length != DTLS1_RT_HEADER_LENGTH) {
424             rl->packet_length = 0;
425             goto again;
426         }
427
428         rl->rstate = SSL_ST_READ_BODY;
429
430         p = rl->packet;
431
432         /* Pull apart the header into the DTLS1_RECORD */
433         rr->type = *(p++);
434         ssl_major = *(p++);
435         ssl_minor = *(p++);
436         rr->rec_version = (ssl_major << 8) | ssl_minor;
437
438         /* sequence number is 64 bits, with top 2 bytes = epoch */
439         n2s(p, rr->epoch);
440
441         memcpy(&(rl->sequence[2]), p, 6);
442         p += 6;
443
444         n2s(p, rr->length);
445
446         if (rl->msg_callback != NULL)
447             rl->msg_callback(0, rr->rec_version, SSL3_RT_HEADER, rl->packet, DTLS1_RT_HEADER_LENGTH,
448                              rl->cbarg);
449
450         /*
451          * Lets check the version. We tolerate alerts that don't have the exact
452          * version number (e.g. because of protocol version errors)
453          */
454         if (!rl->is_first_record && rr->type != SSL3_RT_ALERT) {
455             if (rr->rec_version != rl->version) {
456                 /* unexpected version, silently discard */
457                 rr->length = 0;
458                 rl->packet_length = 0;
459                 goto again;
460             }
461         }
462
463         if (ssl_major !=
464                 (rl->version == DTLS_ANY_VERSION ? DTLS1_VERSION_MAJOR
465                                                  : rl->version >> 8)) {
466             /* wrong version, silently discard record */
467             rr->length = 0;
468             rl->packet_length = 0;
469             goto again;
470         }
471
472         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
473             /* record too long, silently discard it */
474             rr->length = 0;
475             rl->packet_length = 0;
476             goto again;
477         }
478
479         /*
480          * If received packet overflows maximum possible fragment length then
481          * silently discard it
482          */
483         if (rr->length > rl->max_frag_len + SSL3_RT_MAX_ENCRYPTED_OVERHEAD) {
484             /* record too long, silently discard it */
485             rr->length = 0;
486             rl->packet_length = 0;
487             goto again;
488         }
489
490         /* now rl->rstate == SSL_ST_READ_BODY */
491     }
492
493     /* rl->rstate == SSL_ST_READ_BODY, get and decode the data */
494
495     if (rr->length > rl->packet_length - DTLS1_RT_HEADER_LENGTH) {
496         /* now rl->packet_length == DTLS1_RT_HEADER_LENGTH */
497         more = rr->length;
498         rret = rl->funcs->read_n(rl, more, more, 1, 1, &n);
499         /* this packet contained a partial record, dump it */
500         if (rret < OSSL_RECORD_RETURN_SUCCESS || n != more) {
501             if (rl->alert != SSL_AD_NO_ALERT) {
502                 /* read_n() called RLAYERfatal() */
503                 return OSSL_RECORD_RETURN_FATAL;
504             }
505             rr->length = 0;
506             rl->packet_length = 0;
507             goto again;
508         }
509
510         /*
511          * now n == rr->length,
512          * and rl->packet_length ==  DTLS1_RT_HEADER_LENGTH + rr->length
513          */
514     }
515     /* set state for later operations */
516     rl->rstate = SSL_ST_READ_HEADER;
517
518     /* match epochs.  NULL means the packet is dropped on the floor */
519     bitmap = dtls_get_bitmap(rl, rr, &is_next_epoch);
520     if (bitmap == NULL) {
521         rr->length = 0;
522         rl->packet_length = 0; /* dump this record */
523         goto again;             /* get another record */
524     }
525 #ifndef OPENSSL_NO_SCTP
526     /* Only do replay check if no SCTP bio */
527     if (!BIO_dgram_is_sctp(rl->bio)) {
528 #endif
529         /* Check whether this is a repeat, or aged record. */
530         if (!dtls_record_replay_check(rl, bitmap)) {
531             rr->length = 0;
532             rl->packet_length = 0; /* dump this record */
533             goto again;         /* get another record */
534         }
535 #ifndef OPENSSL_NO_SCTP
536     }
537 #endif
538
539     /* just read a 0 length packet */
540     if (rr->length == 0)
541         goto again;
542
543     /*
544      * If this record is from the next epoch (either HM or ALERT), and a
545      * handshake is currently in progress, buffer it since it cannot be
546      * processed at this time.
547      */
548     if (is_next_epoch) {
549         if (rl->in_init) {
550             if (dtls_rlayer_buffer_record(rl, &(rl->unprocessed_rcds),
551                                           rr->seq_num) < 0) {
552                 /* RLAYERfatal() already called */
553                 return OSSL_RECORD_RETURN_FATAL;
554             }
555         }
556         rr->length = 0;
557         rl->packet_length = 0;
558         goto again;
559     }
560
561     if (!dtls_process_record(rl, bitmap)) {
562         if (rl->alert != SSL_AD_NO_ALERT) {
563             /* dtls_process_record() called RLAYERfatal */
564             return OSSL_RECORD_RETURN_FATAL;
565         }
566         rr->length = 0;
567         rl->packet_length = 0; /* dump this record */
568         goto again;             /* get another record */
569     }
570
571     if (rl->funcs->post_process_record && !rl->funcs->post_process_record(rl, rr)) {
572         /* RLAYERfatal already called */
573         return OSSL_RECORD_RETURN_FATAL;
574     }
575
576     rl->num_recs = 1;
577     return OSSL_RECORD_RETURN_SUCCESS;
578 }
579
580 static int dtls_free(OSSL_RECORD_LAYER *rl)
581 {
582     TLS_BUFFER *rbuf;
583     size_t left, written;
584     pitem *item;
585     DTLS_RLAYER_RECORD_DATA *rdata;
586     int ret = 1;
587
588     rbuf = &rl->rbuf;
589
590     left = rbuf->left;
591     if (left > 0) {
592         /*
593          * This record layer is closing but we still have data left in our
594          * buffer. It must be destined for the next epoch - so push it there.
595          */
596         ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
597         rbuf->left = 0;
598     }
599
600     if (rl->unprocessed_rcds.q != NULL) {
601         while ((item = pqueue_pop(rl->unprocessed_rcds.q)) != NULL) {
602             rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
603             /* Push to the next record layer */
604             ret &= BIO_write_ex(rl->next, rdata->packet, rdata->packet_length,
605                                 &written);
606             OPENSSL_free(rdata->rbuf.buf);
607             OPENSSL_free(item->data);
608             pitem_free(item);
609         }
610         pqueue_free(rl->unprocessed_rcds.q);
611     }
612
613     if (rl->processed_rcds.q != NULL) {
614         while ((item = pqueue_pop(rl->processed_rcds.q)) != NULL) {
615             rdata = (DTLS_RLAYER_RECORD_DATA *)item->data;
616             OPENSSL_free(rdata->rbuf.buf);
617             OPENSSL_free(item->data);
618             pitem_free(item);
619         }
620         pqueue_free(rl->processed_rcds.q);
621     }
622
623     return tls_free(rl) && ret;
624 }
625
626 static int
627 dtls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
628                       int role, int direction, int level, uint16_t epoch,
629                       unsigned char *secret, size_t secretlen,
630                       unsigned char *key, size_t keylen, unsigned char *iv,
631                       size_t ivlen, unsigned char *mackey, size_t mackeylen,
632                       const EVP_CIPHER *ciph, size_t taglen,
633                       int mactype,
634                       const EVP_MD *md, COMP_METHOD *comp,
635                       const EVP_MD *kdfdigest, BIO *prev, BIO *transport,
636                       BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
637                       const OSSL_PARAM *settings, const OSSL_PARAM *options,
638                       const OSSL_DISPATCH *fns, void *cbarg, void *rlarg,
639                       OSSL_RECORD_LAYER **retrl)
640 {
641     int ret;
642
643     ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
644                                    key, keylen, iv, ivlen, mackey, mackeylen,
645                                    ciph, taglen, mactype, md, comp, prev,
646                                    transport, next, local, peer, settings,
647                                    options, fns, cbarg, retrl);
648
649     if (ret != OSSL_RECORD_RETURN_SUCCESS)
650         return ret;
651
652     (*retrl)->unprocessed_rcds.q = pqueue_new();
653     (*retrl)->processed_rcds.q = pqueue_new();
654     if ((*retrl)->unprocessed_rcds.q == NULL
655             || (*retrl)->processed_rcds.q == NULL) {
656         dtls_free(*retrl);
657         *retrl = NULL;
658         ERR_raise(ERR_LIB_SSL, ERR_R_SSL_LIB);
659         return OSSL_RECORD_RETURN_FATAL;
660     }
661
662     (*retrl)->unprocessed_rcds.epoch = epoch + 1;
663     (*retrl)->processed_rcds.epoch = epoch;
664
665     (*retrl)->isdtls = 1;
666     (*retrl)->epoch = epoch;
667     (*retrl)->in_init = 1;
668
669     switch (vers) {
670     case DTLS_ANY_VERSION:
671         (*retrl)->funcs = &dtls_any_funcs;
672         break;
673     case DTLS1_2_VERSION:
674     case DTLS1_VERSION:
675     case DTLS1_BAD_VER:
676         (*retrl)->funcs = &dtls_1_funcs;
677         break;
678     default:
679         /* Should not happen */
680         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
681         ret = OSSL_RECORD_RETURN_FATAL;
682         goto err;
683     }
684
685     ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
686                                             ivlen, mackey, mackeylen, ciph,
687                                             taglen, mactype, md, comp);
688
689  err:
690     if (ret != OSSL_RECORD_RETURN_SUCCESS) {
691         dtls_free(*retrl);
692         *retrl = NULL;
693     }
694     return ret;
695 }
696
697 int dtls_prepare_record_header(OSSL_RECORD_LAYER *rl,
698                                WPACKET *thispkt,
699                                OSSL_RECORD_TEMPLATE *templ,
700                                uint8_t rectype,
701                                unsigned char **recdata)
702 {
703     size_t maxcomplen;
704
705     *recdata = NULL;
706
707     maxcomplen = templ->buflen;
708     if (rl->compctx != NULL)
709         maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
710
711     if (!WPACKET_put_bytes_u8(thispkt, rectype)
712             || !WPACKET_put_bytes_u16(thispkt, templ->version)
713             || !WPACKET_put_bytes_u16(thispkt, rl->epoch)
714             || !WPACKET_memcpy(thispkt, &(rl->sequence[2]), 6)
715             || !WPACKET_start_sub_packet_u16(thispkt)
716             || (rl->eivlen > 0
717                 && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
718             || (maxcomplen > 0
719                 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
720                                           recdata))) {
721         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
722         return 0;
723     }
724
725     return 1;
726 }
727
728 int dtls_post_encryption_processing(OSSL_RECORD_LAYER *rl,
729                                     size_t mac_size,
730                                     OSSL_RECORD_TEMPLATE *thistempl,
731                                     WPACKET *thispkt,
732                                     TLS_RL_RECORD *thiswr)
733 {
734     if (!tls_post_encryption_processing_default(rl, mac_size, thistempl,
735                                                 thispkt, thiswr)) {
736         /* RLAYERfatal() already called */
737         return 0;
738     }
739
740     return tls_increment_sequence_ctr(rl);
741 }
742
743 static size_t dtls_get_max_record_overhead(OSSL_RECORD_LAYER *rl)
744 {
745     size_t blocksize = 0;
746
747     if (rl->enc_ctx != NULL &&
748         (EVP_CIPHER_CTX_get_mode(rl->enc_ctx) == EVP_CIPH_CBC_MODE))
749         blocksize = EVP_CIPHER_CTX_get_block_size(rl->enc_ctx);
750
751     /*
752      * If we have a cipher in place then the tag is mandatory. If the cipher is
753      * CBC mode then an explicit IV is also mandatory. If we know the digest,
754      * then we check it is consistent with the taglen. In the case of stitched
755      * ciphers or AEAD ciphers we don't now the digest (or there isn't one) so
756      * we just trust that the taglen is correct.
757      */
758     assert(rl->enc_ctx == NULL  || ((blocksize == 0 || rl->eivlen > 0)
759                                     && rl->taglen > 0));
760     assert(rl->md == NULL || (int)rl->taglen == EVP_MD_size(rl->md));
761
762     /*
763      * Record overhead consists of the record header, the explicit IV, any
764      * expansion due to cbc padding, and the mac/tag len. There could be
765      * further expansion due to compression - but we don't know what this will
766      * be without knowing the length of the data. However when this function is
767      * called we don't know what the length will be yet - so this is a catch-22.
768      * We *could* use SSL_3_RT_MAX_COMPRESSED_OVERHEAD which is an upper limit
769      * for the maximum record size. But this value is larger than our fallback
770      * MTU size - so isn't very helpful. We just ignore potential expansion
771      * due to compression.
772      */
773     return DTLS1_RT_HEADER_LENGTH + rl->eivlen + blocksize + rl->taglen;
774 }
775
776 const OSSL_RECORD_METHOD ossl_dtls_record_method = {
777     dtls_new_record_layer,
778     dtls_free,
779     tls_unprocessed_read_pending,
780     tls_processed_read_pending,
781     tls_app_data_pending,
782     tls_get_max_records,
783     tls_write_records,
784     tls_retry_write_records,
785     tls_read_record,
786     tls_release_record,
787     tls_get_alert_code,
788     tls_set1_bio,
789     tls_set_protocol_version,
790     NULL,
791     tls_set_first_handshake,
792     tls_set_max_pipelines,
793     dtls_set_in_init,
794     tls_get_state,
795     tls_set_options,
796     tls_get_compression,
797     tls_set_max_frag_len,
798     dtls_get_max_record_overhead,
799     tls_increment_sequence_ctr,
800     tls_alloc_buffers,
801     tls_free_buffers
802 };