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