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