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