a217480b0805844befbd30a49718928f79d94e2e
[openssl.git] / ssl / d1_lib.c
1 /*
2  * Copyright 2005-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 "internal/e_os.h"
11 #include <stdio.h>
12 #include <openssl/objects.h>
13 #include <openssl/rand.h>
14 #include "ssl_local.h"
15 #include "internal/time.h"
16
17 static int dtls1_handshake_write(SSL_CONNECTION *s);
18 static size_t dtls1_link_min_mtu(void);
19
20 /* XDTLS:  figure out the right values */
21 static const size_t g_probable_mtu[] = { 1500, 512, 256 };
22
23 const SSL3_ENC_METHOD DTLSv1_enc_data = {
24     tls1_setup_key_block,
25     tls1_generate_master_secret,
26     tls1_change_cipher_state,
27     tls1_final_finish_mac,
28     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
29     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
30     tls1_alert_code,
31     tls1_export_keying_material,
32     SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV,
33     dtls1_set_handshake_header,
34     dtls1_close_construct_packet,
35     dtls1_handshake_write
36 };
37
38 const SSL3_ENC_METHOD DTLSv1_2_enc_data = {
39     tls1_setup_key_block,
40     tls1_generate_master_secret,
41     tls1_change_cipher_state,
42     tls1_final_finish_mac,
43     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
44     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
45     tls1_alert_code,
46     tls1_export_keying_material,
47     SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS
48         | SSL_ENC_FLAG_SHA256_PRF | SSL_ENC_FLAG_TLS1_2_CIPHERS,
49     dtls1_set_handshake_header,
50     dtls1_close_construct_packet,
51     dtls1_handshake_write
52 };
53
54 OSSL_TIME dtls1_default_timeout(void)
55 {
56     /*
57      * 2 hours, the 24 hours mentioned in the DTLSv1 spec is way too long for
58      * http, the cache would over fill
59      */
60     return ossl_seconds2time(60 * 60 * 2);
61 }
62
63 int dtls1_new(SSL *ssl)
64 {
65     DTLS1_STATE *d1;
66     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
67
68     if (s == NULL)
69         return 0;
70
71     if (!DTLS_RECORD_LAYER_new(&s->rlayer)) {
72         return 0;
73     }
74
75     if (!ssl3_new(ssl))
76         return 0;
77     if ((d1 = OPENSSL_zalloc(sizeof(*d1))) == NULL) {
78         ssl3_free(ssl);
79         return 0;
80     }
81
82     d1->buffered_messages = pqueue_new();
83     d1->sent_messages = pqueue_new();
84
85     if (s->server) {
86         d1->cookie_len = sizeof(s->d1->cookie);
87     }
88
89     d1->link_mtu = 0;
90     d1->mtu = 0;
91
92     if (d1->buffered_messages == NULL || d1->sent_messages == NULL) {
93         pqueue_free(d1->buffered_messages);
94         pqueue_free(d1->sent_messages);
95         OPENSSL_free(d1);
96         ssl3_free(ssl);
97         return 0;
98     }
99
100     s->d1 = d1;
101
102     if (!ssl->method->ssl_clear(ssl))
103         return 0;
104
105     return 1;
106 }
107
108 static void dtls1_clear_queues(SSL_CONNECTION *s)
109 {
110     dtls1_clear_received_buffer(s);
111     dtls1_clear_sent_buffer(s);
112 }
113
114 void dtls1_clear_received_buffer(SSL_CONNECTION *s)
115 {
116     pitem *item = NULL;
117     hm_fragment *frag = NULL;
118
119     while ((item = pqueue_pop(s->d1->buffered_messages)) != NULL) {
120         frag = (hm_fragment *)item->data;
121         dtls1_hm_fragment_free(frag);
122         pitem_free(item);
123     }
124 }
125
126 void dtls1_clear_sent_buffer(SSL_CONNECTION *s)
127 {
128     pitem *item = NULL;
129     hm_fragment *frag = NULL;
130
131     while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
132         frag = (hm_fragment *)item->data;
133         dtls1_hm_fragment_free(frag);
134         pitem_free(item);
135     }
136 }
137
138
139 void dtls1_free(SSL *ssl)
140 {
141     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
142
143     if (s == NULL)
144         return;
145
146     DTLS_RECORD_LAYER_free(&s->rlayer);
147
148     ssl3_free(ssl);
149
150     if (s->d1 != NULL) {
151         dtls1_clear_queues(s);
152         pqueue_free(s->d1->buffered_messages);
153         pqueue_free(s->d1->sent_messages);
154     }
155
156     OPENSSL_free(s->d1);
157     s->d1 = NULL;
158 }
159
160 int dtls1_clear(SSL *ssl)
161 {
162     pqueue *buffered_messages;
163     pqueue *sent_messages;
164     size_t mtu;
165     size_t link_mtu;
166
167     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
168
169     if (s == NULL)
170         return 0;
171
172     DTLS_RECORD_LAYER_clear(&s->rlayer);
173
174     if (s->d1) {
175         DTLS_timer_cb timer_cb = s->d1->timer_cb;
176
177         buffered_messages = s->d1->buffered_messages;
178         sent_messages = s->d1->sent_messages;
179         mtu = s->d1->mtu;
180         link_mtu = s->d1->link_mtu;
181
182         dtls1_clear_queues(s);
183
184         memset(s->d1, 0, sizeof(*s->d1));
185
186         /* Restore the timer callback from previous state */
187         s->d1->timer_cb = timer_cb;
188
189         if (s->server) {
190             s->d1->cookie_len = sizeof(s->d1->cookie);
191         }
192
193         if (SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU) {
194             s->d1->mtu = mtu;
195             s->d1->link_mtu = link_mtu;
196         }
197
198         s->d1->buffered_messages = buffered_messages;
199         s->d1->sent_messages = sent_messages;
200     }
201
202     if (!ssl3_clear(ssl))
203         return 0;
204
205     if (ssl->method->version == DTLS_ANY_VERSION)
206         s->version = DTLS_MAX_VERSION_INTERNAL;
207 #ifndef OPENSSL_NO_DTLS1_METHOD
208     else if (s->options & SSL_OP_CISCO_ANYCONNECT)
209         s->client_version = s->version = DTLS1_BAD_VER;
210 #endif
211     else
212         s->version = ssl->method->version;
213
214     return 1;
215 }
216
217 long dtls1_ctrl(SSL *ssl, int cmd, long larg, void *parg)
218 {
219     int ret = 0;
220     OSSL_TIME t;
221     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
222
223     if (s == NULL)
224         return 0;
225
226     switch (cmd) {
227     case DTLS_CTRL_GET_TIMEOUT:
228         if (dtls1_get_timeout(s, &t)) {
229             *(struct timeval *)parg = ossl_time_to_timeval(t);
230             ret = 1;
231         }
232         break;
233     case DTLS_CTRL_HANDLE_TIMEOUT:
234         ret = dtls1_handle_timeout(s);
235         break;
236     case DTLS_CTRL_SET_LINK_MTU:
237         if (larg < (long)dtls1_link_min_mtu())
238             return 0;
239         s->d1->link_mtu = larg;
240         return 1;
241     case DTLS_CTRL_GET_LINK_MIN_MTU:
242         return (long)dtls1_link_min_mtu();
243     case SSL_CTRL_SET_MTU:
244         /*
245          *  We may not have a BIO set yet so can't call dtls1_min_mtu()
246          *  We'll have to make do with dtls1_link_min_mtu() and max overhead
247          */
248         if (larg < (long)dtls1_link_min_mtu() - DTLS1_MAX_MTU_OVERHEAD)
249             return 0;
250         s->d1->mtu = larg;
251         return larg;
252     default:
253         ret = ssl3_ctrl(ssl, cmd, larg, parg);
254         break;
255     }
256     return ret;
257 }
258
259 static void dtls1_bio_set_next_timeout(BIO * bio, const DTLS1_STATE *d1)
260 {
261     struct timeval tv = ossl_time_to_timeval(d1->next_timeout);
262
263     BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &tv);
264 }
265
266 void dtls1_start_timer(SSL_CONNECTION *s)
267 {
268     OSSL_TIME duration;
269     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
270
271 #ifndef OPENSSL_NO_SCTP
272     /* Disable timer for SCTP */
273     if (BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {
274         s->d1->next_timeout = ossl_time_zero();
275         return;
276     }
277 #endif
278
279     /*
280      * If timer is not set, initialize duration with 1 second or
281      * a user-specified value if the timer callback is installed.
282      */
283     if (ossl_time_is_zero(s->d1->next_timeout)) {
284         if (s->d1->timer_cb != NULL)
285             s->d1->timeout_duration_us = s->d1->timer_cb(ssl, 0);
286         else
287             s->d1->timeout_duration_us = 1000000;
288     }
289
290     /* Set timeout to current time plus duration */
291     duration = ossl_us2time(s->d1->timeout_duration_us);
292     s->d1->next_timeout = ossl_time_add(ossl_time_now(), duration);
293
294     /* set s->d1->next_timeout into ssl->rbio interface */
295     dtls1_bio_set_next_timeout(SSL_get_rbio(ssl), s->d1);
296 }
297
298 int dtls1_get_timeout(const SSL_CONNECTION *s, OSSL_TIME *timeleft)
299 {
300     OSSL_TIME timenow;
301
302     /* If no timeout is set, just return NULL */
303     if (ossl_time_is_zero(s->d1->next_timeout))
304         return 0;
305
306     /* Get current time */
307     timenow = ossl_time_now();
308
309     /*
310      * If timer already expired or if remaining time is less than 15 ms,
311      * set it to 0 to prevent issues because of small divergences with
312      * socket timeouts.
313      */
314     *timeleft = ossl_time_subtract(s->d1->next_timeout, timenow);
315     if (ossl_time_compare(*timeleft, ossl_ms2time(15)) <= 0)
316         *timeleft = ossl_time_zero();
317     return 1;
318 }
319
320 int dtls1_is_timer_expired(SSL_CONNECTION *s)
321 {
322     OSSL_TIME timeleft;
323
324     /* Get time left until timeout, return false if no timer running */
325     if (!dtls1_get_timeout(s, &timeleft))
326         return 0;
327
328     /* Return false if timer is not expired yet */
329     if (!ossl_time_is_zero(timeleft))
330         return 0;
331
332     /* Timer expired, so return true */
333     return 1;
334 }
335
336 static void dtls1_double_timeout(SSL_CONNECTION *s)
337 {
338     s->d1->timeout_duration_us *= 2;
339     if (s->d1->timeout_duration_us > 60000000)
340         s->d1->timeout_duration_us = 60000000;
341 }
342
343 void dtls1_stop_timer(SSL_CONNECTION *s)
344 {
345     /* Reset everything */
346     s->d1->timeout_num_alerts = 0;
347     s->d1->next_timeout = ossl_time_zero();
348     s->d1->timeout_duration_us = 1000000;
349     dtls1_bio_set_next_timeout(s->rbio, s->d1);
350     /* Clear retransmission buffer */
351     dtls1_clear_sent_buffer(s);
352 }
353
354 int dtls1_check_timeout_num(SSL_CONNECTION *s)
355 {
356     size_t mtu;
357     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
358
359     s->d1->timeout_num_alerts++;
360
361     /* Reduce MTU after 2 unsuccessful retransmissions */
362     if (s->d1->timeout_num_alerts > 2
363         && !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
364         mtu =
365             BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0, NULL);
366         if (mtu < s->d1->mtu)
367             s->d1->mtu = mtu;
368     }
369
370     if (s->d1->timeout_num_alerts > DTLS1_TMO_ALERT_COUNT) {
371         /* fail the connection, enough alerts have been sent */
372         SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_READ_TIMEOUT_EXPIRED);
373         return -1;
374     }
375
376     return 0;
377 }
378
379 int dtls1_handle_timeout(SSL_CONNECTION *s)
380 {
381     /* if no timer is expired, don't do anything */
382     if (!dtls1_is_timer_expired(s)) {
383         return 0;
384     }
385
386     if (s->d1->timer_cb != NULL)
387         s->d1->timeout_duration_us = s->d1->timer_cb(SSL_CONNECTION_GET_SSL(s),
388                                                      s->d1->timeout_duration_us);
389     else
390         dtls1_double_timeout(s);
391
392     if (dtls1_check_timeout_num(s) < 0) {
393         /* SSLfatal() already called */
394         return -1;
395     }
396
397     dtls1_start_timer(s);
398     /* Calls SSLfatal() if required */
399     return dtls1_retransmit_buffered_messages(s);
400 }
401
402 #define LISTEN_SUCCESS              2
403 #define LISTEN_SEND_VERIFY_REQUEST  1
404
405 #ifndef OPENSSL_NO_SOCK
406 int DTLSv1_listen(SSL *ssl, BIO_ADDR *client)
407 {
408     int next, n, ret = 0;
409     unsigned char cookie[DTLS1_COOKIE_LENGTH];
410     unsigned char seq[SEQ_NUM_SIZE];
411     const unsigned char *data;
412     unsigned char *buf = NULL, *wbuf;
413     size_t fragoff, fraglen, msglen;
414     unsigned int rectype, versmajor, msgseq, msgtype, clientvers, cookielen;
415     BIO *rbio, *wbio;
416     BIO_ADDR *tmpclient = NULL;
417     PACKET pkt, msgpkt, msgpayload, session, cookiepkt;
418     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
419
420     if (s == NULL)
421         return -1;
422
423     if (s->handshake_func == NULL) {
424         /* Not properly initialized yet */
425         SSL_set_accept_state(ssl);
426     }
427
428     /* Ensure there is no state left over from a previous invocation */
429     if (!SSL_clear(ssl))
430         return -1;
431
432     ERR_clear_error();
433
434     rbio = SSL_get_rbio(ssl);
435     wbio = SSL_get_wbio(ssl);
436
437     if (!rbio || !wbio) {
438         ERR_raise(ERR_LIB_SSL, SSL_R_BIO_NOT_SET);
439         return -1;
440     }
441
442     /*
443      * Note: This check deliberately excludes DTLS1_BAD_VER because that version
444      * requires the MAC to be calculated *including* the first ClientHello
445      * (without the cookie). Since DTLSv1_listen is stateless that cannot be
446      * supported. DTLS1_BAD_VER must use cookies in a stateful manner (e.g. via
447      * SSL_accept)
448      */
449     if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
450         ERR_raise(ERR_LIB_SSL, SSL_R_UNSUPPORTED_SSL_VERSION);
451         return -1;
452     }
453
454     buf = OPENSSL_malloc(DTLS1_RT_HEADER_LENGTH + SSL3_RT_MAX_PLAIN_LENGTH);
455     if (buf == NULL)
456         return -1;
457     wbuf = OPENSSL_malloc(DTLS1_RT_HEADER_LENGTH + SSL3_RT_MAX_PLAIN_LENGTH);
458     if (wbuf == NULL) {
459         OPENSSL_free(buf);
460         return -1;
461     }
462
463     do {
464         /* Get a packet */
465
466         clear_sys_error();
467         n = BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH
468                                 + DTLS1_RT_HEADER_LENGTH);
469         if (n <= 0) {
470             if (BIO_should_retry(rbio)) {
471                 /* Non-blocking IO */
472                 goto end;
473             }
474             ret = -1;
475             goto end;
476         }
477
478         if (!PACKET_buf_init(&pkt, buf, n)) {
479             ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
480             ret = -1;
481             goto end;
482         }
483
484         /*
485          * Parse the received record. If there are any problems with it we just
486          * dump it - with no alert. RFC6347 says this "Unlike TLS, DTLS is
487          * resilient in the face of invalid records (e.g., invalid formatting,
488          * length, MAC, etc.).  In general, invalid records SHOULD be silently
489          * discarded, thus preserving the association; however, an error MAY be
490          * logged for diagnostic purposes."
491          */
492
493         /* this packet contained a partial record, dump it */
494         if (n < DTLS1_RT_HEADER_LENGTH) {
495             ERR_raise(ERR_LIB_SSL, SSL_R_RECORD_TOO_SMALL);
496             goto end;
497         }
498
499         if (s->msg_callback)
500             s->msg_callback(0, 0, SSL3_RT_HEADER, buf,
501                             DTLS1_RT_HEADER_LENGTH, ssl, s->msg_callback_arg);
502
503         /* Get the record header */
504         if (!PACKET_get_1(&pkt, &rectype)
505             || !PACKET_get_1(&pkt, &versmajor)) {
506             ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
507             goto end;
508         }
509
510         if (rectype != SSL3_RT_HANDSHAKE) {
511             ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
512             goto end;
513         }
514
515         /*
516          * Check record version number. We only check that the major version is
517          * the same.
518          */
519         if (versmajor != DTLS1_VERSION_MAJOR) {
520             ERR_raise(ERR_LIB_SSL, SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
521             goto end;
522         }
523
524         if (!PACKET_forward(&pkt, 1)
525             /* Save the sequence number: 64 bits, with top 2 bytes = epoch */
526             || !PACKET_copy_bytes(&pkt, seq, SEQ_NUM_SIZE)
527             || !PACKET_get_length_prefixed_2(&pkt, &msgpkt)) {
528             ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
529             goto end;
530         }
531         /*
532          * We allow data remaining at the end of the packet because there could
533          * be a second record (but we ignore it)
534          */
535
536         /* This is an initial ClientHello so the epoch has to be 0 */
537         if (seq[0] != 0 || seq[1] != 0) {
538             ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
539             goto end;
540         }
541
542         /* Get a pointer to the raw message for the later callback */
543         data = PACKET_data(&msgpkt);
544
545         /* Finished processing the record header, now process the message */
546         if (!PACKET_get_1(&msgpkt, &msgtype)
547             || !PACKET_get_net_3_len(&msgpkt, &msglen)
548             || !PACKET_get_net_2(&msgpkt, &msgseq)
549             || !PACKET_get_net_3_len(&msgpkt, &fragoff)
550             || !PACKET_get_net_3_len(&msgpkt, &fraglen)
551             || !PACKET_get_sub_packet(&msgpkt, &msgpayload, fraglen)
552             || PACKET_remaining(&msgpkt) != 0) {
553             ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
554             goto end;
555         }
556
557         if (msgtype != SSL3_MT_CLIENT_HELLO) {
558             ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
559             goto end;
560         }
561
562         /* Message sequence number can only be 0 or 1 */
563         if (msgseq > 2) {
564             ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_SEQUENCE_NUMBER);
565             goto end;
566         }
567
568         /*
569          * We don't support fragment reassembly for ClientHellos whilst
570          * listening because that would require server side state (which is
571          * against the whole point of the ClientHello/HelloVerifyRequest
572          * mechanism). Instead we only look at the first ClientHello fragment
573          * and require that the cookie must be contained within it.
574          */
575         if (fragoff != 0 || fraglen > msglen) {
576             /* Non initial ClientHello fragment (or bad fragment) */
577             ERR_raise(ERR_LIB_SSL, SSL_R_FRAGMENTED_CLIENT_HELLO);
578             goto end;
579         }
580
581         if (s->msg_callback)
582             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, data,
583                             fraglen + DTLS1_HM_HEADER_LENGTH, ssl,
584                             s->msg_callback_arg);
585
586         if (!PACKET_get_net_2(&msgpayload, &clientvers)) {
587             ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
588             goto end;
589         }
590
591         /*
592          * Verify client version is supported
593          */
594         if (DTLS_VERSION_LT(clientvers, (unsigned int)ssl->method->version) &&
595             ssl->method->version != DTLS_ANY_VERSION) {
596             ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_VERSION_NUMBER);
597             goto end;
598         }
599
600         if (!PACKET_forward(&msgpayload, SSL3_RANDOM_SIZE)
601             || !PACKET_get_length_prefixed_1(&msgpayload, &session)
602             || !PACKET_get_length_prefixed_1(&msgpayload, &cookiepkt)) {
603             /*
604              * Could be malformed or the cookie does not fit within the initial
605              * ClientHello fragment. Either way we can't handle it.
606              */
607             ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
608             goto end;
609         }
610
611         /*
612          * Check if we have a cookie or not. If not we need to send a
613          * HelloVerifyRequest.
614          */
615         if (PACKET_remaining(&cookiepkt) == 0) {
616             next = LISTEN_SEND_VERIFY_REQUEST;
617         } else {
618             /*
619              * We have a cookie, so lets check it.
620              */
621             if (ssl->ctx->app_verify_cookie_cb == NULL) {
622                 ERR_raise(ERR_LIB_SSL, SSL_R_NO_VERIFY_COOKIE_CALLBACK);
623                 /* This is fatal */
624                 ret = -1;
625                 goto end;
626             }
627             if (ssl->ctx->app_verify_cookie_cb(ssl, PACKET_data(&cookiepkt),
628                     (unsigned int)PACKET_remaining(&cookiepkt)) == 0) {
629                 /*
630                  * We treat invalid cookies in the same was as no cookie as
631                  * per RFC6347
632                  */
633                 next = LISTEN_SEND_VERIFY_REQUEST;
634             } else {
635                 /* Cookie verification succeeded */
636                 next = LISTEN_SUCCESS;
637             }
638         }
639
640         if (next == LISTEN_SEND_VERIFY_REQUEST) {
641             WPACKET wpkt;
642             unsigned int version;
643             size_t wreclen;
644
645             /*
646              * There was no cookie in the ClientHello so we need to send a
647              * HelloVerifyRequest. If this fails we do not worry about trying
648              * to resend, we just drop it.
649              */
650
651             /* Generate the cookie */
652             if (ssl->ctx->app_gen_cookie_cb == NULL ||
653                 ssl->ctx->app_gen_cookie_cb(ssl, cookie, &cookielen) == 0 ||
654                 cookielen > 255) {
655                 ERR_raise(ERR_LIB_SSL, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
656                 /* This is fatal */
657                 ret = -1;
658                 goto end;
659             }
660
661             /*
662              * Special case: for hello verify request, client version 1.0 and we
663              * haven't decided which version to use yet send back using version
664              * 1.0 header: otherwise some clients will ignore it.
665              */
666             version = (ssl->method->version == DTLS_ANY_VERSION) ? DTLS1_VERSION
667                                                                  : s->version;
668
669             /* Construct the record and message headers */
670             if (!WPACKET_init_static_len(&wpkt,
671                                          wbuf,
672                                          ssl_get_max_send_fragment(s)
673                                          + DTLS1_RT_HEADER_LENGTH,
674                                          0)
675                     || !WPACKET_put_bytes_u8(&wpkt, SSL3_RT_HANDSHAKE)
676                     || !WPACKET_put_bytes_u16(&wpkt, version)
677                        /*
678                         * Record sequence number is always the same as in the
679                         * received ClientHello
680                         */
681                     || !WPACKET_memcpy(&wpkt, seq, SEQ_NUM_SIZE)
682                        /* End of record, start sub packet for message */
683                     || !WPACKET_start_sub_packet_u16(&wpkt)
684                        /* Message type */
685                     || !WPACKET_put_bytes_u8(&wpkt,
686                                              DTLS1_MT_HELLO_VERIFY_REQUEST)
687                        /*
688                         * Message length - doesn't follow normal TLS convention:
689                         * the length isn't the last thing in the message header.
690                         * We'll need to fill this in later when we know the
691                         * length. Set it to zero for now
692                         */
693                     || !WPACKET_put_bytes_u24(&wpkt, 0)
694                        /*
695                         * Message sequence number is always 0 for a
696                         * HelloVerifyRequest
697                         */
698                     || !WPACKET_put_bytes_u16(&wpkt, 0)
699                        /*
700                         * We never fragment a HelloVerifyRequest, so fragment
701                         * offset is 0
702                         */
703                     || !WPACKET_put_bytes_u24(&wpkt, 0)
704                        /*
705                         * Fragment length is the same as message length, but
706                         * this *is* the last thing in the message header so we
707                         * can just start a sub-packet. No need to come back
708                         * later for this one.
709                         */
710                     || !WPACKET_start_sub_packet_u24(&wpkt)
711                        /* Create the actual HelloVerifyRequest body */
712                     || !dtls_raw_hello_verify_request(&wpkt, cookie, cookielen)
713                        /* Close message body */
714                     || !WPACKET_close(&wpkt)
715                        /* Close record body */
716                     || !WPACKET_close(&wpkt)
717                     || !WPACKET_get_total_written(&wpkt, &wreclen)
718                     || !WPACKET_finish(&wpkt)) {
719                 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
720                 WPACKET_cleanup(&wpkt);
721                 /* This is fatal */
722                 ret = -1;
723                 goto end;
724             }
725
726             /*
727              * Fix up the message len in the message header. Its the same as the
728              * fragment len which has been filled in by WPACKET, so just copy
729              * that. Destination for the message len is after the record header
730              * plus one byte for the message content type. The source is the
731              * last 3 bytes of the message header
732              */
733             memcpy(&wbuf[DTLS1_RT_HEADER_LENGTH + 1],
734                    &wbuf[DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH - 3],
735                    3);
736
737             if (s->msg_callback)
738                 s->msg_callback(1, 0, SSL3_RT_HEADER, buf,
739                                 DTLS1_RT_HEADER_LENGTH, ssl,
740                                 s->msg_callback_arg);
741
742             if ((tmpclient = BIO_ADDR_new()) == NULL) {
743                 ERR_raise(ERR_LIB_SSL, ERR_R_BIO_LIB);
744                 goto end;
745             }
746
747             /*
748              * This is unnecessary if rbio and wbio are one and the same - but
749              * maybe they're not. We ignore errors here - some BIOs do not
750              * support this.
751              */
752             if (BIO_dgram_get_peer(rbio, tmpclient) > 0) {
753                 (void)BIO_dgram_set_peer(wbio, tmpclient);
754             }
755             BIO_ADDR_free(tmpclient);
756             tmpclient = NULL;
757
758             if (BIO_write(wbio, wbuf, wreclen) < (int)wreclen) {
759                 if (BIO_should_retry(wbio)) {
760                     /*
761                      * Non-blocking IO...but we're stateless, so we're just
762                      * going to drop this packet.
763                      */
764                     goto end;
765                 }
766                 ret = -1;
767                 goto end;
768             }
769
770             if (BIO_flush(wbio) <= 0) {
771                 if (BIO_should_retry(wbio)) {
772                     /*
773                      * Non-blocking IO...but we're stateless, so we're just
774                      * going to drop this packet.
775                      */
776                     goto end;
777                 }
778                 ret = -1;
779                 goto end;
780             }
781         }
782     } while (next != LISTEN_SUCCESS);
783
784     /*
785      * Set expected sequence numbers to continue the handshake.
786      */
787     s->d1->handshake_read_seq = 1;
788     s->d1->handshake_write_seq = 1;
789     s->d1->next_handshake_write_seq = 1;
790     s->rlayer.wrlmethod->increment_sequence_ctr(s->rlayer.wrl);
791
792     /*
793      * We are doing cookie exchange, so make sure we set that option in the
794      * SSL object
795      */
796     SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);
797
798     /*
799      * Tell the state machine that we've done the initial hello verify
800      * exchange
801      */
802     ossl_statem_set_hello_verify_done(s);
803
804     /*
805      * Some BIOs may not support this. If we fail we clear the client address
806      */
807     if (BIO_dgram_get_peer(rbio, client) <= 0)
808         BIO_ADDR_clear(client);
809
810     /* Buffer the record for use by the record layer */
811     if (BIO_write(s->rlayer.rrlnext, buf, n) != n) {
812         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
813         ret = -1;
814         goto end;
815     }
816
817     /*
818      * Reset the record layer - but this time we can use the record we just
819      * buffered in s->rlayer.rrlnext
820      */
821     if (!ssl_set_new_record_layer(s,
822                                   DTLS_ANY_VERSION,
823                                   OSSL_RECORD_DIRECTION_READ,
824                                   OSSL_RECORD_PROTECTION_LEVEL_NONE, NULL, 0,
825                                   NULL, 0, NULL, 0, NULL,  0, NULL, 0,
826                                   NID_undef, NULL, NULL, NULL)) {
827         /* SSLfatal already called */
828         ret = -1;
829         goto end;
830     }
831
832     ret = 1;
833  end:
834     BIO_ADDR_free(tmpclient);
835     OPENSSL_free(buf);
836     OPENSSL_free(wbuf);
837     return ret;
838 }
839 #endif
840
841 static int dtls1_handshake_write(SSL_CONNECTION *s)
842 {
843     return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
844 }
845
846 int dtls1_shutdown(SSL *s)
847 {
848     int ret;
849 #ifndef OPENSSL_NO_SCTP
850     BIO *wbio;
851     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
852
853     if (s == NULL)
854         return -1;
855
856     wbio = SSL_get_wbio(s);
857     if (wbio != NULL && BIO_dgram_is_sctp(wbio) &&
858         !(sc->shutdown & SSL_SENT_SHUTDOWN)) {
859         ret = BIO_dgram_sctp_wait_for_dry(wbio);
860         if (ret < 0)
861             return -1;
862
863         if (ret == 0)
864             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
865                      NULL);
866     }
867 #endif
868     ret = ssl3_shutdown(s);
869 #ifndef OPENSSL_NO_SCTP
870     BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
871 #endif
872     return ret;
873 }
874
875 int dtls1_query_mtu(SSL_CONNECTION *s)
876 {
877     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
878
879     if (s->d1->link_mtu) {
880         s->d1->mtu =
881             s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(ssl));
882         s->d1->link_mtu = 0;
883     }
884
885     /* AHA!  Figure out the MTU, and stick to the right size */
886     if (s->d1->mtu < dtls1_min_mtu(s)) {
887         if (!(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
888             s->d1->mtu =
889                 BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
890
891             /*
892              * I've seen the kernel return bogus numbers when it doesn't know
893              * (initial write), so just make sure we have a reasonable number
894              */
895             if (s->d1->mtu < dtls1_min_mtu(s)) {
896                 /* Set to min mtu */
897                 s->d1->mtu = dtls1_min_mtu(s);
898                 BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SET_MTU,
899                          (long)s->d1->mtu, NULL);
900             }
901         } else
902             return 0;
903     }
904     return 1;
905 }
906
907 static size_t dtls1_link_min_mtu(void)
908 {
909     return (g_probable_mtu[(sizeof(g_probable_mtu) /
910                             sizeof(g_probable_mtu[0])) - 1]);
911 }
912
913 size_t dtls1_min_mtu(SSL_CONNECTION *s)
914 {
915     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
916
917     return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(ssl));
918 }
919
920 size_t DTLS_get_data_mtu(const SSL *ssl)
921 {
922     size_t mac_overhead, int_overhead, blocksize, ext_overhead;
923     const SSL_CIPHER *ciph = SSL_get_current_cipher(ssl);
924     size_t mtu;
925     const SSL_CONNECTION *s = SSL_CONNECTION_FROM_CONST_SSL_ONLY(ssl);
926
927     if (s == NULL)
928         return 0;
929
930     mtu = s->d1->mtu;
931
932     if (ciph == NULL)
933         return 0;
934
935     if (!ssl_cipher_get_overhead(ciph, &mac_overhead, &int_overhead,
936                                  &blocksize, &ext_overhead))
937         return 0;
938
939     if (SSL_READ_ETM(s))
940         ext_overhead += mac_overhead;
941     else
942         int_overhead += mac_overhead;
943
944     /* Subtract external overhead (e.g. IV/nonce, separate MAC) */
945     if (ext_overhead + DTLS1_RT_HEADER_LENGTH >= mtu)
946         return 0;
947     mtu -= ext_overhead + DTLS1_RT_HEADER_LENGTH;
948
949     /* Round encrypted payload down to cipher block size (for CBC etc.)
950      * No check for overflow since 'mtu % blocksize' cannot exceed mtu. */
951     if (blocksize)
952         mtu -= (mtu % blocksize);
953
954     /* Subtract internal overhead (e.g. CBC padding len byte) */
955     if (int_overhead >= mtu)
956         return 0;
957     mtu -= int_overhead;
958
959     return mtu;
960 }
961
962 void DTLS_set_timer_cb(SSL *ssl, DTLS_timer_cb cb)
963 {
964     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
965
966     if (s == NULL)
967         return;
968
969     s->d1->timer_cb = cb;
970 }