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