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