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