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