xref: /freebsd/crypto/openssl/ssl/d1_lib.c (revision f25b8c9fb4f58cf61adb47d7570abe7caa6d385d)
1 /*
2  * Copyright 2005-2025 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 
dtls1_default_timeout(void)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 
dtls1_new(SSL * ssl)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 
dtls1_clear_queues(SSL_CONNECTION * s)110 static void dtls1_clear_queues(SSL_CONNECTION *s)
111 {
112     dtls1_clear_received_buffer(s);
113     dtls1_clear_sent_buffer(s);
114 }
115 
dtls1_clear_received_buffer(SSL_CONNECTION * s)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 
dtls1_clear_sent_buffer(SSL_CONNECTION * s)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 
dtls1_free(SSL * ssl)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 
dtls1_clear(SSL * ssl)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 
dtls1_ctrl(SSL * ssl,int cmd,long larg,void * parg)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 
dtls1_bio_set_next_timeout(BIO * bio,const DTLS1_STATE * d1)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 
dtls1_start_timer(SSL_CONNECTION * s)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 
dtls1_get_timeout(const SSL_CONNECTION * s,OSSL_TIME * timeleft)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 
dtls1_is_timer_expired(SSL_CONNECTION * s)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 
dtls1_double_timeout(SSL_CONNECTION * s)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 
dtls1_stop_timer(SSL_CONNECTION * s)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 
dtls1_check_timeout_num(SSL_CONNECTION * s)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 
dtls1_handle_timeout(SSL_CONNECTION * s)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     /* Calls SSLfatal() if required */
410     return dtls1_retransmit_buffered_messages(s);
411 }
412 
413 #define LISTEN_SUCCESS 2
414 #define LISTEN_SEND_VERIFY_REQUEST 1
415 
416 #ifndef OPENSSL_NO_SOCK
DTLSv1_listen(SSL * ssl,BIO_ADDR * client)417 int DTLSv1_listen(SSL *ssl, BIO_ADDR *client)
418 {
419     int next, n, ret = 0;
420     unsigned char cookie[DTLS1_COOKIE_LENGTH];
421     unsigned char seq[SEQ_NUM_SIZE];
422     const unsigned char *data;
423     unsigned char *buf = NULL, *wbuf;
424     size_t fragoff, fraglen, msglen;
425     unsigned int rectype, versmajor, versminor, msgseq, msgtype, clientvers, cookielen;
426     BIO *rbio, *wbio;
427     BIO_ADDR *tmpclient = NULL;
428     PACKET pkt, msgpkt, msgpayload, session, cookiepkt;
429     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
430 
431     if (s == NULL)
432         return -1;
433 
434     if (s->handshake_func == NULL) {
435         /* Not properly initialized yet */
436         SSL_set_accept_state(ssl);
437     }
438 
439     /* Ensure there is no state left over from a previous invocation */
440     if (!SSL_clear(ssl))
441         return -1;
442 
443     ERR_clear_error();
444 
445     rbio = SSL_get_rbio(ssl);
446     wbio = SSL_get_wbio(ssl);
447 
448     if (!rbio || !wbio) {
449         ERR_raise(ERR_LIB_SSL, SSL_R_BIO_NOT_SET);
450         return -1;
451     }
452 
453     /*
454      * Note: This check deliberately excludes DTLS1_BAD_VER because that version
455      * requires the MAC to be calculated *including* the first ClientHello
456      * (without the cookie). Since DTLSv1_listen is stateless that cannot be
457      * supported. DTLS1_BAD_VER must use cookies in a stateful manner (e.g. via
458      * SSL_accept)
459      */
460     if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
461         ERR_raise(ERR_LIB_SSL, SSL_R_UNSUPPORTED_SSL_VERSION);
462         return -1;
463     }
464 
465     buf = OPENSSL_malloc(DTLS1_RT_HEADER_LENGTH + SSL3_RT_MAX_PLAIN_LENGTH);
466     if (buf == NULL)
467         return -1;
468     wbuf = OPENSSL_malloc(DTLS1_RT_HEADER_LENGTH + SSL3_RT_MAX_PLAIN_LENGTH);
469     if (wbuf == NULL) {
470         OPENSSL_free(buf);
471         return -1;
472     }
473 
474     do {
475         /* Get a packet */
476 
477         clear_sys_error();
478         n = BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH + DTLS1_RT_HEADER_LENGTH);
479         if (n <= 0) {
480             if (BIO_should_retry(rbio)) {
481                 /* Non-blocking IO */
482                 goto end;
483             }
484             ret = -1;
485             goto end;
486         }
487 
488         if (!PACKET_buf_init(&pkt, buf, n)) {
489             ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
490             ret = -1;
491             goto end;
492         }
493 
494         /*
495          * Parse the received record. If there are any problems with it we just
496          * dump it - with no alert. RFC6347 says this "Unlike TLS, DTLS is
497          * resilient in the face of invalid records (e.g., invalid formatting,
498          * length, MAC, etc.).  In general, invalid records SHOULD be silently
499          * discarded, thus preserving the association; however, an error MAY be
500          * logged for diagnostic purposes."
501          */
502 
503         /* this packet contained a partial record, dump it */
504         if (n < DTLS1_RT_HEADER_LENGTH) {
505             ERR_raise(ERR_LIB_SSL, SSL_R_RECORD_TOO_SMALL);
506             goto end;
507         }
508 
509         /* Get the record header */
510         if (!PACKET_get_1(&pkt, &rectype)
511             || !PACKET_get_1(&pkt, &versmajor)
512             || !PACKET_get_1(&pkt, &versminor)) {
513             ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
514             goto end;
515         }
516 
517         if (s->msg_callback)
518             s->msg_callback(0, (versmajor << 8) | versminor, SSL3_RT_HEADER, buf,
519                 DTLS1_RT_HEADER_LENGTH, ssl, s->msg_callback_arg);
520 
521         if (rectype != SSL3_RT_HANDSHAKE) {
522             ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
523             goto end;
524         }
525 
526         /*
527          * Check record version number. We only check that the major version is
528          * the same.
529          */
530         if (versmajor != DTLS1_VERSION_MAJOR) {
531             ERR_raise(ERR_LIB_SSL, SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
532             goto end;
533         }
534 
535         /* Save the sequence number: 64 bits, with top 2 bytes = epoch */
536         if (!PACKET_copy_bytes(&pkt, seq, SEQ_NUM_SIZE)
537             || !PACKET_get_length_prefixed_2(&pkt, &msgpkt)) {
538             ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
539             goto end;
540         }
541         /*
542          * We allow data remaining at the end of the packet because there could
543          * be a second record (but we ignore it)
544          */
545 
546         /* This is an initial ClientHello so the epoch has to be 0 */
547         if (seq[0] != 0 || seq[1] != 0) {
548             ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
549             goto end;
550         }
551 
552         /* Get a pointer to the raw message for the later callback */
553         data = PACKET_data(&msgpkt);
554 
555         /* Finished processing the record header, now process the message */
556         if (!PACKET_get_1(&msgpkt, &msgtype)
557             || !PACKET_get_net_3_len(&msgpkt, &msglen)
558             || !PACKET_get_net_2(&msgpkt, &msgseq)
559             || !PACKET_get_net_3_len(&msgpkt, &fragoff)
560             || !PACKET_get_net_3_len(&msgpkt, &fraglen)
561             || !PACKET_get_sub_packet(&msgpkt, &msgpayload, fraglen)
562             || PACKET_remaining(&msgpkt) != 0) {
563             ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
564             goto end;
565         }
566 
567         if (msgtype != SSL3_MT_CLIENT_HELLO) {
568             ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
569             goto end;
570         }
571 
572         /* Message sequence number can only be 0 or 1 */
573         if (msgseq > 1) {
574             ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_SEQUENCE_NUMBER);
575             goto end;
576         }
577 
578         /*
579          * We don't support fragment reassembly for ClientHellos whilst
580          * listening because that would require server side state (which is
581          * against the whole point of the ClientHello/HelloVerifyRequest
582          * mechanism). Instead we only look at the first ClientHello fragment
583          * and require that the cookie must be contained within it.
584          */
585         if (fragoff != 0 || fraglen > msglen) {
586             /* Non initial ClientHello fragment (or bad fragment) */
587             ERR_raise(ERR_LIB_SSL, SSL_R_FRAGMENTED_CLIENT_HELLO);
588             goto end;
589         }
590 
591         if (s->msg_callback)
592             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, data,
593                 fraglen + DTLS1_HM_HEADER_LENGTH, ssl,
594                 s->msg_callback_arg);
595 
596         if (!PACKET_get_net_2(&msgpayload, &clientvers)) {
597             ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
598             goto end;
599         }
600 
601         /*
602          * Verify client version is supported
603          */
604         if (DTLS_VERSION_LT(clientvers, (unsigned int)ssl->method->version) && ssl->method->version != DTLS_ANY_VERSION) {
605             ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_VERSION_NUMBER);
606             goto end;
607         }
608 
609         if (!PACKET_forward(&msgpayload, SSL3_RANDOM_SIZE)
610             || !PACKET_get_length_prefixed_1(&msgpayload, &session)
611             || !PACKET_get_length_prefixed_1(&msgpayload, &cookiepkt)) {
612             /*
613              * Could be malformed or the cookie does not fit within the initial
614              * ClientHello fragment. Either way we can't handle it.
615              */
616             ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
617             goto end;
618         }
619 
620         /*
621          * Check if we have a cookie or not. If not we need to send a
622          * HelloVerifyRequest.
623          */
624         if (PACKET_remaining(&cookiepkt) == 0) {
625             next = LISTEN_SEND_VERIFY_REQUEST;
626         } else {
627             /*
628              * We have a cookie, so lets check it.
629              */
630             if (ssl->ctx->app_verify_cookie_cb == NULL) {
631                 ERR_raise(ERR_LIB_SSL, SSL_R_NO_VERIFY_COOKIE_CALLBACK);
632                 /* This is fatal */
633                 ret = -1;
634                 goto end;
635             }
636             if (ssl->ctx->app_verify_cookie_cb(ssl, PACKET_data(&cookiepkt),
637                     (unsigned int)PACKET_remaining(&cookiepkt))
638                 == 0) {
639                 /*
640                  * We treat invalid cookies in the same was as no cookie as
641                  * per RFC6347
642                  */
643                 next = LISTEN_SEND_VERIFY_REQUEST;
644             } else {
645                 /* Cookie verification succeeded */
646                 next = LISTEN_SUCCESS;
647             }
648         }
649 
650         if (next == LISTEN_SEND_VERIFY_REQUEST) {
651             WPACKET wpkt;
652             unsigned int version;
653             size_t wreclen;
654 
655             /*
656              * There was no cookie in the ClientHello so we need to send a
657              * HelloVerifyRequest. If this fails we do not worry about trying
658              * to resend, we just drop it.
659              */
660 
661             /* Generate the cookie */
662             if (ssl->ctx->app_gen_cookie_cb == NULL || ssl->ctx->app_gen_cookie_cb(ssl, cookie, &cookielen) == 0 || cookielen > 255) {
663                 ERR_raise(ERR_LIB_SSL, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
664                 /* This is fatal */
665                 ret = -1;
666                 goto end;
667             }
668 
669             /*
670              * Special case: for hello verify request, client version 1.0 and we
671              * haven't decided which version to use yet send back using version
672              * 1.0 header: otherwise some clients will ignore it.
673              */
674             version = (ssl->method->version == DTLS_ANY_VERSION) ? DTLS1_VERSION
675                                                                  : s->version;
676 
677             /* Construct the record and message headers */
678             if (!WPACKET_init_static_len(&wpkt,
679                     wbuf,
680                     ssl_get_max_send_fragment(s)
681                         + DTLS1_RT_HEADER_LENGTH,
682                     0)
683                 || !WPACKET_put_bytes_u8(&wpkt, SSL3_RT_HANDSHAKE)
684                 || !WPACKET_put_bytes_u16(&wpkt, version)
685                 /*
686                  * Record sequence number is always the same as in the
687                  * received ClientHello
688                  */
689                 || !WPACKET_memcpy(&wpkt, seq, SEQ_NUM_SIZE)
690                 /* End of record, start sub packet for message */
691                 || !WPACKET_start_sub_packet_u16(&wpkt)
692                 /* Message type */
693                 || !WPACKET_put_bytes_u8(&wpkt,
694                     DTLS1_MT_HELLO_VERIFY_REQUEST)
695                 /*
696                  * Message length - doesn't follow normal TLS convention:
697                  * the length isn't the last thing in the message header.
698                  * We'll need to fill this in later when we know the
699                  * length. Set it to zero for now
700                  */
701                 || !WPACKET_put_bytes_u24(&wpkt, 0)
702                 /*
703                  * Message sequence number is always 0 for a
704                  * HelloVerifyRequest
705                  */
706                 || !WPACKET_put_bytes_u16(&wpkt, 0)
707                 /*
708                  * We never fragment a HelloVerifyRequest, so fragment
709                  * offset is 0
710                  */
711                 || !WPACKET_put_bytes_u24(&wpkt, 0)
712                 /*
713                  * Fragment length is the same as message length, but
714                  * this *is* the last thing in the message header so we
715                  * can just start a sub-packet. No need to come back
716                  * later for this one.
717                  */
718                 || !WPACKET_start_sub_packet_u24(&wpkt)
719                 /* Create the actual HelloVerifyRequest body */
720                 || !dtls_raw_hello_verify_request(&wpkt, cookie, cookielen)
721                 /* Close message body */
722                 || !WPACKET_close(&wpkt)
723                 /* Close record body */
724                 || !WPACKET_close(&wpkt)
725                 || !WPACKET_get_total_written(&wpkt, &wreclen)
726                 || !WPACKET_finish(&wpkt)) {
727                 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
728                 WPACKET_cleanup(&wpkt);
729                 /* This is fatal */
730                 ret = -1;
731                 goto end;
732             }
733 
734             /*
735              * Fix up the message len in the message header. Its the same as the
736              * fragment len which has been filled in by WPACKET, so just copy
737              * that. Destination for the message len is after the record header
738              * plus one byte for the message content type. The source is the
739              * last 3 bytes of the message header
740              */
741             memcpy(&wbuf[DTLS1_RT_HEADER_LENGTH + 1],
742                 &wbuf[DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH - 3],
743                 3);
744 
745             if (s->msg_callback)
746                 s->msg_callback(1, version, SSL3_RT_HEADER, wbuf,
747                     DTLS1_RT_HEADER_LENGTH, ssl,
748                     s->msg_callback_arg);
749 
750             if ((tmpclient = BIO_ADDR_new()) == NULL) {
751                 ERR_raise(ERR_LIB_SSL, ERR_R_BIO_LIB);
752                 goto end;
753             }
754 
755             /*
756              * This is unnecessary if rbio and wbio are one and the same - but
757              * maybe they're not. We ignore errors here - some BIOs do not
758              * support this.
759              */
760             if (BIO_dgram_get_peer(rbio, tmpclient) > 0) {
761                 (void)BIO_dgram_set_peer(wbio, tmpclient);
762             }
763             BIO_ADDR_free(tmpclient);
764             tmpclient = NULL;
765 
766             if (BIO_write(wbio, wbuf, wreclen) < (int)wreclen) {
767                 if (BIO_should_retry(wbio)) {
768                     /*
769                      * Non-blocking IO...but we're stateless, so we're just
770                      * going to drop this packet.
771                      */
772                     goto end;
773                 }
774                 ret = -1;
775                 goto end;
776             }
777 
778             if (BIO_flush(wbio) <= 0) {
779                 if (BIO_should_retry(wbio)) {
780                     /*
781                      * Non-blocking IO...but we're stateless, so we're just
782                      * going to drop this packet.
783                      */
784                     goto end;
785                 }
786                 ret = -1;
787                 goto end;
788             }
789         }
790     } while (next != LISTEN_SUCCESS);
791 
792     /*
793      * Set expected sequence numbers to continue the handshake.
794      */
795     s->d1->handshake_read_seq = 1;
796     s->d1->handshake_write_seq = 1;
797     s->d1->next_handshake_write_seq = 1;
798     s->rlayer.wrlmethod->increment_sequence_ctr(s->rlayer.wrl);
799 
800     /*
801      * We are doing cookie exchange, so make sure we set that option in the
802      * SSL object
803      */
804     SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);
805 
806     /*
807      * Tell the state machine that we've done the initial hello verify
808      * exchange
809      */
810     ossl_statem_set_hello_verify_done(s);
811 
812     /*
813      * Some BIOs may not support this. If we fail we clear the client address
814      */
815     if (BIO_dgram_get_peer(rbio, client) <= 0)
816         BIO_ADDR_clear(client);
817 
818     /* Buffer the record for use by the record layer */
819     if (BIO_write(s->rlayer.rrlnext, buf, n) != n) {
820         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
821         ret = -1;
822         goto end;
823     }
824 
825     /*
826      * Reset the record layer - but this time we can use the record we just
827      * buffered in s->rlayer.rrlnext
828      */
829     if (!ssl_set_new_record_layer(s,
830             DTLS_ANY_VERSION,
831             OSSL_RECORD_DIRECTION_READ,
832             OSSL_RECORD_PROTECTION_LEVEL_NONE, NULL, 0,
833             NULL, 0, NULL, 0, NULL, 0, NULL, 0,
834             NID_undef, NULL, NULL, NULL)) {
835         /* SSLfatal already called */
836         ret = -1;
837         goto end;
838     }
839 
840     ret = 1;
841 end:
842     BIO_ADDR_free(tmpclient);
843     OPENSSL_free(buf);
844     OPENSSL_free(wbuf);
845     return ret;
846 }
847 #endif
848 
dtls1_handshake_write(SSL_CONNECTION * s)849 static int dtls1_handshake_write(SSL_CONNECTION *s)
850 {
851     return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
852 }
853 
dtls1_shutdown(SSL * s)854 int dtls1_shutdown(SSL *s)
855 {
856     int ret;
857 #ifndef OPENSSL_NO_SCTP
858     BIO *wbio;
859     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
860 
861     if (sc == NULL)
862         return -1;
863 
864     wbio = SSL_get_wbio(s);
865     if (wbio != NULL && BIO_dgram_is_sctp(wbio) && !(sc->shutdown & SSL_SENT_SHUTDOWN)) {
866         ret = BIO_dgram_sctp_wait_for_dry(wbio);
867         if (ret < 0)
868             return -1;
869 
870         if (ret == 0)
871             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
872                 NULL);
873     }
874 #endif
875     ret = ssl3_shutdown(s);
876 #ifndef OPENSSL_NO_SCTP
877     BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
878 #endif
879     return ret;
880 }
881 
dtls1_query_mtu(SSL_CONNECTION * s)882 int dtls1_query_mtu(SSL_CONNECTION *s)
883 {
884     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
885 
886     if (s->d1->link_mtu) {
887         s->d1->mtu = s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(ssl));
888         s->d1->link_mtu = 0;
889     }
890 
891     /* AHA!  Figure out the MTU, and stick to the right size */
892     if (s->d1->mtu < dtls1_min_mtu(s)) {
893         if (!(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
894             s->d1->mtu = BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
895 
896             /*
897              * I've seen the kernel return bogus numbers when it doesn't know
898              * (initial write), so just make sure we have a reasonable number
899              */
900             if (s->d1->mtu < dtls1_min_mtu(s)) {
901                 /* Set to min mtu */
902                 s->d1->mtu = dtls1_min_mtu(s);
903                 BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SET_MTU,
904                     (long)s->d1->mtu, NULL);
905             }
906         } else
907             return 0;
908     }
909     return 1;
910 }
911 
dtls1_link_min_mtu(void)912 static size_t dtls1_link_min_mtu(void)
913 {
914     return (g_probable_mtu[(sizeof(g_probable_mtu) / sizeof(g_probable_mtu[0])) - 1]);
915 }
916 
dtls1_min_mtu(SSL_CONNECTION * s)917 size_t dtls1_min_mtu(SSL_CONNECTION *s)
918 {
919     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
920 
921     return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(ssl));
922 }
923 
DTLS_get_data_mtu(const SSL * ssl)924 size_t DTLS_get_data_mtu(const SSL *ssl)
925 {
926     size_t mac_overhead, int_overhead, blocksize, ext_overhead;
927     const SSL_CIPHER *ciph = SSL_get_current_cipher(ssl);
928     size_t mtu;
929     const SSL_CONNECTION *s = SSL_CONNECTION_FROM_CONST_SSL_ONLY(ssl);
930 
931     if (s == NULL)
932         return 0;
933 
934     mtu = s->d1->mtu;
935 
936     if (ciph == NULL)
937         return 0;
938 
939     if (!ssl_cipher_get_overhead(ciph, &mac_overhead, &int_overhead,
940             &blocksize, &ext_overhead))
941         return 0;
942 
943     if (SSL_READ_ETM(s))
944         ext_overhead += mac_overhead;
945     else
946         int_overhead += mac_overhead;
947 
948     /* Subtract external overhead (e.g. IV/nonce, separate MAC) */
949     if (ext_overhead + DTLS1_RT_HEADER_LENGTH >= mtu)
950         return 0;
951     mtu -= ext_overhead + DTLS1_RT_HEADER_LENGTH;
952 
953     /* Round encrypted payload down to cipher block size (for CBC etc.)
954      * No check for overflow since 'mtu % blocksize' cannot exceed mtu. */
955     if (blocksize)
956         mtu -= (mtu % blocksize);
957 
958     /* Subtract internal overhead (e.g. CBC padding len byte) */
959     if (int_overhead >= mtu)
960         return 0;
961     mtu -= int_overhead;
962 
963     return mtu;
964 }
965 
DTLS_set_timer_cb(SSL * ssl,DTLS_timer_cb cb)966 void DTLS_set_timer_cb(SSL *ssl, DTLS_timer_cb cb)
967 {
968     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
969 
970     if (s == NULL)
971         return;
972 
973     s->d1->timer_cb = cb;
974 }
975