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