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