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