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