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