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