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