Add a DRBG to each SSL object
[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_VXWORKS)
17 # include <sys/times.h>
18 #elif !defined(OPENSSL_SYS_WIN32)
19 # include <sys/time.h>
20 #endif
21
22 static void get_current_time(struct timeval *t);
23 static int dtls1_handshake_write(SSL *s);
24 static size_t dtls1_link_min_mtu(void);
25
26 /* XDTLS:  figure out the right values */
27 static const size_t g_probable_mtu[] = { 1500, 512, 256 };
28
29 const SSL3_ENC_METHOD DTLSv1_enc_data = {
30     tls1_enc,
31     tls1_mac,
32     tls1_setup_key_block,
33     tls1_generate_master_secret,
34     tls1_change_cipher_state,
35     tls1_final_finish_mac,
36     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
37     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
38     tls1_alert_code,
39     tls1_export_keying_material,
40     SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV,
41     dtls1_set_handshake_header,
42     dtls1_close_construct_packet,
43     dtls1_handshake_write
44 };
45
46 const SSL3_ENC_METHOD DTLSv1_2_enc_data = {
47     tls1_enc,
48     tls1_mac,
49     tls1_setup_key_block,
50     tls1_generate_master_secret,
51     tls1_change_cipher_state,
52     tls1_final_finish_mac,
53     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
54     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
55     tls1_alert_code,
56     tls1_export_keying_material,
57     SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS
58         | SSL_ENC_FLAG_SHA256_PRF | SSL_ENC_FLAG_TLS1_2_CIPHERS,
59     dtls1_set_handshake_header,
60     dtls1_close_construct_packet,
61     dtls1_handshake_write
62 };
63
64 long dtls1_default_timeout(void)
65 {
66     /*
67      * 2 hours, the 24 hours mentioned in the DTLSv1 spec is way too long for
68      * http, the cache would over fill
69      */
70     return (60 * 60 * 2);
71 }
72
73 int dtls1_new(SSL *s)
74 {
75     DTLS1_STATE *d1;
76
77     if (!DTLS_RECORD_LAYER_new(&s->rlayer)) {
78         return 0;
79     }
80
81     if (!ssl3_new(s))
82         return 0;
83     if ((d1 = OPENSSL_zalloc(sizeof(*d1))) == NULL) {
84         ssl3_free(s);
85         return 0;
86     }
87
88     d1->buffered_messages = pqueue_new();
89     d1->sent_messages = pqueue_new();
90
91     if (s->server) {
92         d1->cookie_len = sizeof(s->d1->cookie);
93     }
94
95     d1->link_mtu = 0;
96     d1->mtu = 0;
97
98     if (d1->buffered_messages == NULL || d1->sent_messages == NULL) {
99         pqueue_free(d1->buffered_messages);
100         pqueue_free(d1->sent_messages);
101         OPENSSL_free(d1);
102         ssl3_free(s);
103         return 0;
104     }
105
106     s->d1 = d1;
107
108     if (!s->method->ssl_clear(s))
109         return 0;
110
111     return 1;
112 }
113
114 static void dtls1_clear_queues(SSL *s)
115 {
116     dtls1_clear_received_buffer(s);
117     dtls1_clear_sent_buffer(s);
118 }
119
120 void dtls1_clear_received_buffer(SSL *s)
121 {
122     pitem *item = NULL;
123     hm_fragment *frag = NULL;
124
125     while ((item = pqueue_pop(s->d1->buffered_messages)) != NULL) {
126         frag = (hm_fragment *)item->data;
127         dtls1_hm_fragment_free(frag);
128         pitem_free(item);
129     }
130 }
131
132 void dtls1_clear_sent_buffer(SSL *s)
133 {
134     pitem *item = NULL;
135     hm_fragment *frag = NULL;
136
137     while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
138         frag = (hm_fragment *)item->data;
139         dtls1_hm_fragment_free(frag);
140         pitem_free(item);
141     }
142 }
143
144
145 void dtls1_free(SSL *s)
146 {
147     DTLS_RECORD_LAYER_free(&s->rlayer);
148
149     ssl3_free(s);
150
151     dtls1_clear_queues(s);
152
153     pqueue_free(s->d1->buffered_messages);
154     pqueue_free(s->d1->sent_messages);
155
156     OPENSSL_free(s->d1);
157     s->d1 = NULL;
158 }
159
160 int dtls1_clear(SSL *s)
161 {
162     pqueue *buffered_messages;
163     pqueue *sent_messages;
164     size_t mtu;
165     size_t link_mtu;
166
167     DTLS_RECORD_LAYER_clear(&s->rlayer);
168
169     if (s->d1) {
170         buffered_messages = s->d1->buffered_messages;
171         sent_messages = s->d1->sent_messages;
172         mtu = s->d1->mtu;
173         link_mtu = s->d1->link_mtu;
174
175         dtls1_clear_queues(s);
176
177         memset(s->d1, 0, sizeof(*s->d1));
178
179         if (s->server) {
180             s->d1->cookie_len = sizeof(s->d1->cookie);
181         }
182
183         if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) {
184             s->d1->mtu = mtu;
185             s->d1->link_mtu = link_mtu;
186         }
187
188         s->d1->buffered_messages = buffered_messages;
189         s->d1->sent_messages = sent_messages;
190     }
191
192     if (!ssl3_clear(s))
193         return 0;
194
195     if (s->method->version == DTLS_ANY_VERSION)
196         s->version = DTLS_MAX_VERSION;
197 #ifndef OPENSSL_NO_DTLS1_METHOD
198     else if (s->options & SSL_OP_CISCO_ANYCONNECT)
199         s->client_version = s->version = DTLS1_BAD_VER;
200 #endif
201     else
202         s->version = s->method->version;
203
204     return 1;
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     size_t 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
386     dtls1_start_timer(s);
387     return dtls1_retransmit_buffered_messages(s);
388 }
389
390 static void get_current_time(struct timeval *t)
391 {
392 #if defined(_WIN32)
393     SYSTEMTIME st;
394     union {
395         unsigned __int64 ul;
396         FILETIME ft;
397     } now;
398
399     GetSystemTime(&st);
400     SystemTimeToFileTime(&st, &now.ft);
401     /* re-bias to 1/1/1970 */
402 # ifdef  __MINGW32__
403     now.ul -= 116444736000000000ULL;
404 # else
405     /* *INDENT-OFF* */
406     now.ul -= 116444736000000000UI64;
407     /* *INDENT-ON* */
408 # endif
409     t->tv_sec = (long)(now.ul / 10000000);
410     t->tv_usec = ((int)(now.ul % 10000000)) / 10;
411 #else
412     gettimeofday(t, NULL);
413 #endif
414 }
415
416 #define LISTEN_SUCCESS              2
417 #define LISTEN_SEND_VERIFY_REQUEST  1
418
419 #ifndef OPENSSL_NO_SOCK
420 int DTLSv1_listen(SSL *s, BIO_ADDR *client)
421 {
422     int next, n, ret = 0, clearpkt = 0;
423     unsigned char cookie[DTLS1_COOKIE_LENGTH];
424     unsigned char seq[SEQ_NUM_SIZE];
425     const unsigned char *data;
426     unsigned char *buf;
427     size_t fragoff, fraglen, msglen;
428     unsigned int rectype, versmajor, msgseq, msgtype, clientvers, cookielen;
429     BIO *rbio, *wbio;
430     BUF_MEM *bufm;
431     BIO_ADDR *tmpclient = NULL;
432     PACKET pkt, msgpkt, msgpayload, session, cookiepkt;
433
434     if (s->handshake_func == NULL) {
435         /* Not properly initialized yet */
436         SSL_set_accept_state(s);
437     }
438
439     /* Ensure there is no state left over from a previous invocation */
440     if (!SSL_clear(s))
441         return -1;
442
443     ERR_clear_error();
444
445     rbio = SSL_get_rbio(s);
446     wbio = SSL_get_wbio(s);
447
448     if (!rbio || !wbio) {
449         SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_BIO_NOT_SET);
450         return -1;
451     }
452
453     /*
454      * We only peek at incoming ClientHello's until we're sure we are going to
455      * to respond with a HelloVerifyRequest. If its a ClientHello with a valid
456      * cookie then we leave it in the BIO for accept to handle.
457      */
458     BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 1, NULL);
459
460     /*
461      * Note: This check deliberately excludes DTLS1_BAD_VER because that version
462      * requires the MAC to be calculated *including* the first ClientHello
463      * (without the cookie). Since DTLSv1_listen is stateless that cannot be
464      * supported. DTLS1_BAD_VER must use cookies in a stateful manner (e.g. via
465      * SSL_accept)
466      */
467     if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
468         SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNSUPPORTED_SSL_VERSION);
469         return -1;
470     }
471
472     if (s->init_buf == NULL) {
473         if ((bufm = BUF_MEM_new()) == NULL) {
474             SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
475             return -1;
476         }
477
478         if (!BUF_MEM_grow(bufm, SSL3_RT_MAX_PLAIN_LENGTH)) {
479             BUF_MEM_free(bufm);
480             SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
481             return -1;
482         }
483         s->init_buf = bufm;
484     }
485     buf = (unsigned char *)s->init_buf->data;
486
487     do {
488         /* Get a packet */
489
490         clear_sys_error();
491         /*
492          * Technically a ClientHello could be SSL3_RT_MAX_PLAIN_LENGTH
493          * + DTLS1_RT_HEADER_LENGTH bytes long. Normally init_buf does not store
494          * the record header as well, but we do here. We've set up init_buf to
495          * be the standard size for simplicity. In practice we shouldn't ever
496          * receive a ClientHello as long as this. If we do it will get dropped
497          * in the record length check below.
498          */
499         n = BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
500
501         if (n <= 0) {
502             if (BIO_should_retry(rbio)) {
503                 /* Non-blocking IO */
504                 goto end;
505             }
506             return -1;
507         }
508
509         /* If we hit any problems we need to clear this packet from the BIO */
510         clearpkt = 1;
511
512         if (!PACKET_buf_init(&pkt, buf, n)) {
513             SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_INTERNAL_ERROR);
514             return -1;
515         }
516
517         /*
518          * Parse the received record. If there are any problems with it we just
519          * dump it - with no alert. RFC6347 says this "Unlike TLS, DTLS is
520          * resilient in the face of invalid records (e.g., invalid formatting,
521          * length, MAC, etc.).  In general, invalid records SHOULD be silently
522          * discarded, thus preserving the association; however, an error MAY be
523          * logged for diagnostic purposes."
524          */
525
526         /* this packet contained a partial record, dump it */
527         if (n < DTLS1_RT_HEADER_LENGTH) {
528             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_RECORD_TOO_SMALL);
529             goto end;
530         }
531
532         if (s->msg_callback)
533             s->msg_callback(0, 0, SSL3_RT_HEADER, buf,
534                             DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
535
536         /* Get the record header */
537         if (!PACKET_get_1(&pkt, &rectype)
538             || !PACKET_get_1(&pkt, &versmajor)) {
539             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
540             goto end;
541         }
542
543         if (rectype != SSL3_RT_HANDSHAKE) {
544             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE);
545             goto end;
546         }
547
548         /*
549          * Check record version number. We only check that the major version is
550          * the same.
551          */
552         if (versmajor != DTLS1_VERSION_MAJOR) {
553             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
554             goto end;
555         }
556
557         if (!PACKET_forward(&pkt, 1)
558             /* Save the sequence number: 64 bits, with top 2 bytes = epoch */
559             || !PACKET_copy_bytes(&pkt, seq, SEQ_NUM_SIZE)
560             || !PACKET_get_length_prefixed_2(&pkt, &msgpkt)) {
561             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
562             goto end;
563         }
564         /*
565          * We allow data remaining at the end of the packet because there could
566          * be a second record (but we ignore it)
567          */
568
569         /* This is an initial ClientHello so the epoch has to be 0 */
570         if (seq[0] != 0 || seq[1] != 0) {
571             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE);
572             goto end;
573         }
574
575         /* Get a pointer to the raw message for the later callback */
576         data = PACKET_data(&msgpkt);
577
578         /* Finished processing the record header, now process the message */
579         if (!PACKET_get_1(&msgpkt, &msgtype)
580             || !PACKET_get_net_3_len(&msgpkt, &msglen)
581             || !PACKET_get_net_2(&msgpkt, &msgseq)
582             || !PACKET_get_net_3_len(&msgpkt, &fragoff)
583             || !PACKET_get_net_3_len(&msgpkt, &fraglen)
584             || !PACKET_get_sub_packet(&msgpkt, &msgpayload, fraglen)
585             || PACKET_remaining(&msgpkt) != 0) {
586             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
587             goto end;
588         }
589
590         if (msgtype != SSL3_MT_CLIENT_HELLO) {
591             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE);
592             goto end;
593         }
594
595         /* Message sequence number can only be 0 or 1 */
596         if (msgseq > 2) {
597             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_INVALID_SEQUENCE_NUMBER);
598             goto end;
599         }
600
601         /*
602          * We don't support fragment reassembly for ClientHellos whilst
603          * listening because that would require server side state (which is
604          * against the whole point of the ClientHello/HelloVerifyRequest
605          * mechanism). Instead we only look at the first ClientHello fragment
606          * and require that the cookie must be contained within it.
607          */
608         if (fragoff != 0 || fraglen > msglen) {
609             /* Non initial ClientHello fragment (or bad fragment) */
610             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_FRAGMENTED_CLIENT_HELLO);
611             goto end;
612         }
613
614         if (s->msg_callback)
615             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, data,
616                             fraglen + DTLS1_HM_HEADER_LENGTH, s,
617                             s->msg_callback_arg);
618
619         if (!PACKET_get_net_2(&msgpayload, &clientvers)) {
620             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
621             goto end;
622         }
623
624         /*
625          * Verify client version is supported
626          */
627         if (DTLS_VERSION_LT(clientvers, (unsigned int)s->method->version) &&
628             s->method->version != DTLS_ANY_VERSION) {
629             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_WRONG_VERSION_NUMBER);
630             goto end;
631         }
632
633         if (!PACKET_forward(&msgpayload, SSL3_RANDOM_SIZE)
634             || !PACKET_get_length_prefixed_1(&msgpayload, &session)
635             || !PACKET_get_length_prefixed_1(&msgpayload, &cookiepkt)) {
636             /*
637              * Could be malformed or the cookie does not fit within the initial
638              * ClientHello fragment. Either way we can't handle it.
639              */
640             SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
641             goto end;
642         }
643
644         /*
645          * Check if we have a cookie or not. If not we need to send a
646          * HelloVerifyRequest.
647          */
648         if (PACKET_remaining(&cookiepkt) == 0) {
649             next = LISTEN_SEND_VERIFY_REQUEST;
650         } else {
651             /*
652              * We have a cookie, so lets check it.
653              */
654             if (s->ctx->app_verify_cookie_cb == NULL) {
655                 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_NO_VERIFY_COOKIE_CALLBACK);
656                 /* This is fatal */
657                 return -1;
658             }
659             if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookiepkt),
660                     (unsigned int)PACKET_remaining(&cookiepkt)) == 0) {
661                 /*
662                  * We treat invalid cookies in the same was as no cookie as
663                  * per RFC6347
664                  */
665                 next = LISTEN_SEND_VERIFY_REQUEST;
666             } else {
667                 /* Cookie verification succeeded */
668                 next = LISTEN_SUCCESS;
669             }
670         }
671
672         if (next == LISTEN_SEND_VERIFY_REQUEST) {
673             WPACKET wpkt;
674             unsigned int version;
675             size_t wreclen;
676
677             /*
678              * There was no cookie in the ClientHello so we need to send a
679              * HelloVerifyRequest. If this fails we do not worry about trying
680              * to resend, we just drop it.
681              */
682
683             /*
684              * Dump the read packet, we don't need it any more. Ignore return
685              * value
686              */
687             BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 0, NULL);
688             BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
689             BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 1, NULL);
690
691             /* Generate the cookie */
692             if (s->ctx->app_gen_cookie_cb == NULL ||
693                 s->ctx->app_gen_cookie_cb(s, cookie, &cookielen) == 0 ||
694                 cookielen > 255) {
695                 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
696                 /* This is fatal */
697                 return -1;
698             }
699
700             /*
701              * Special case: for hello verify request, client version 1.0 and we
702              * haven't decided which version to use yet send back using version
703              * 1.0 header: otherwise some clients will ignore it.
704              */
705             version = (s->method->version == DTLS_ANY_VERSION) ? DTLS1_VERSION
706                                                                : s->version;
707
708             /* Construct the record and message headers */
709             if (!WPACKET_init(&wpkt, s->init_buf)
710                     || !WPACKET_put_bytes_u8(&wpkt, SSL3_RT_HANDSHAKE)
711                     || !WPACKET_put_bytes_u16(&wpkt, version)
712                        /*
713                         * Record sequence number is always the same as in the
714                         * received ClientHello
715                         */
716                     || !WPACKET_memcpy(&wpkt, seq, SEQ_NUM_SIZE)
717                        /* End of record, start sub packet for message */
718                     || !WPACKET_start_sub_packet_u16(&wpkt)
719                        /* Message type */
720                     || !WPACKET_put_bytes_u8(&wpkt,
721                                              DTLS1_MT_HELLO_VERIFY_REQUEST)
722                        /*
723                         * Message length - doesn't follow normal TLS convention:
724                         * the length isn't the last thing in the message header.
725                         * We'll need to fill this in later when we know the
726                         * length. Set it to zero for now
727                         */
728                     || !WPACKET_put_bytes_u24(&wpkt, 0)
729                        /*
730                         * Message sequence number is always 0 for a
731                         * HelloVerifyRequest
732                         */
733                     || !WPACKET_put_bytes_u16(&wpkt, 0)
734                        /*
735                         * We never fragment a HelloVerifyRequest, so fragment
736                         * offset is 0
737                         */
738                     || !WPACKET_put_bytes_u24(&wpkt, 0)
739                        /*
740                         * Fragment length is the same as message length, but
741                         * this *is* the last thing in the message header so we
742                         * can just start a sub-packet. No need to come back
743                         * later for this one.
744                         */
745                     || !WPACKET_start_sub_packet_u24(&wpkt)
746                        /* Create the actual HelloVerifyRequest body */
747                     || !dtls_raw_hello_verify_request(&wpkt, cookie, cookielen)
748                        /* Close message body */
749                     || !WPACKET_close(&wpkt)
750                        /* Close record body */
751                     || !WPACKET_close(&wpkt)
752                     || !WPACKET_get_total_written(&wpkt, &wreclen)
753                     || !WPACKET_finish(&wpkt)) {
754                 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_INTERNAL_ERROR);
755                 WPACKET_cleanup(&wpkt);
756                 /* This is fatal */
757                 return -1;
758             }
759
760             /*
761              * Fix up the message len in the message header. Its the same as the
762              * fragment len which has been filled in by WPACKET, so just copy
763              * that. Destination for the message len is after the record header
764              * plus one byte for the message content type. The source is the
765              * last 3 bytes of the message header
766              */
767             memcpy(&buf[DTLS1_RT_HEADER_LENGTH + 1],
768                    &buf[DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH - 3],
769                    3);
770
771             if (s->msg_callback)
772                 s->msg_callback(1, 0, SSL3_RT_HEADER, buf,
773                                 DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
774
775             if ((tmpclient = BIO_ADDR_new()) == NULL) {
776                 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
777                 goto end;
778             }
779
780             /*
781              * This is unnecessary if rbio and wbio are one and the same - but
782              * maybe they're not. We ignore errors here - some BIOs do not
783              * support this.
784              */
785             if (BIO_dgram_get_peer(rbio, tmpclient) > 0) {
786                 (void)BIO_dgram_set_peer(wbio, tmpclient);
787             }
788             BIO_ADDR_free(tmpclient);
789             tmpclient = NULL;
790
791             /* TODO(size_t): convert this call */
792             if (BIO_write(wbio, buf, wreclen) < (int)wreclen) {
793                 if (BIO_should_retry(wbio)) {
794                     /*
795                      * Non-blocking IO...but we're stateless, so we're just
796                      * going to drop this packet.
797                      */
798                     goto end;
799                 }
800                 return -1;
801             }
802
803             if (BIO_flush(wbio) <= 0) {
804                 if (BIO_should_retry(wbio)) {
805                     /*
806                      * Non-blocking IO...but we're stateless, so we're just
807                      * going to drop this packet.
808                      */
809                     goto end;
810                 }
811                 return -1;
812             }
813         }
814     } while (next != LISTEN_SUCCESS);
815
816     /*
817      * Set expected sequence numbers to continue the handshake.
818      */
819     s->d1->handshake_read_seq = 1;
820     s->d1->handshake_write_seq = 1;
821     s->d1->next_handshake_write_seq = 1;
822     DTLS_RECORD_LAYER_set_write_sequence(&s->rlayer, seq);
823
824     /*
825      * We are doing cookie exchange, so make sure we set that option in the
826      * SSL object
827      */
828     SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE);
829
830     /*
831      * Tell the state machine that we've done the initial hello verify
832      * exchange
833      */
834     ossl_statem_set_hello_verify_done(s);
835
836     /*
837      * Some BIOs may not support this. If we fail we clear the client address
838      */
839     if (BIO_dgram_get_peer(rbio, client) <= 0)
840         BIO_ADDR_clear(client);
841
842     ret = 1;
843     clearpkt = 0;
844  end:
845     BIO_ADDR_free(tmpclient);
846     BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 0, NULL);
847     if (clearpkt) {
848         /* Dump this packet. Ignore return value */
849         BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
850     }
851     return ret;
852 }
853 #endif
854
855 static int dtls1_handshake_write(SSL *s)
856 {
857     return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
858 }
859
860 int dtls1_shutdown(SSL *s)
861 {
862     int ret;
863 #ifndef OPENSSL_NO_SCTP
864     BIO *wbio;
865
866     wbio = SSL_get_wbio(s);
867     if (wbio != NULL && BIO_dgram_is_sctp(wbio) &&
868         !(s->shutdown & SSL_SENT_SHUTDOWN)) {
869         ret = BIO_dgram_sctp_wait_for_dry(wbio);
870         if (ret < 0)
871             return -1;
872
873         if (ret == 0)
874             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
875                      NULL);
876     }
877 #endif
878     ret = ssl3_shutdown(s);
879 #ifndef OPENSSL_NO_SCTP
880     BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
881 #endif
882     return ret;
883 }
884
885 int dtls1_query_mtu(SSL *s)
886 {
887     if (s->d1->link_mtu) {
888         s->d1->mtu =
889             s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
890         s->d1->link_mtu = 0;
891     }
892
893     /* AHA!  Figure out the MTU, and stick to the right size */
894     if (s->d1->mtu < dtls1_min_mtu(s)) {
895         if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
896             s->d1->mtu =
897                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
898
899             /*
900              * I've seen the kernel return bogus numbers when it doesn't know
901              * (initial write), so just make sure we have a reasonable number
902              */
903             if (s->d1->mtu < dtls1_min_mtu(s)) {
904                 /* Set to min mtu */
905                 s->d1->mtu = dtls1_min_mtu(s);
906                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
907                          (long)s->d1->mtu, NULL);
908             }
909         } else
910             return 0;
911     }
912     return 1;
913 }
914
915 static size_t dtls1_link_min_mtu(void)
916 {
917     return (g_probable_mtu[(sizeof(g_probable_mtu) /
918                             sizeof(g_probable_mtu[0])) - 1]);
919 }
920
921 size_t dtls1_min_mtu(SSL *s)
922 {
923     return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
924 }
925
926 size_t DTLS_get_data_mtu(const SSL *s)
927 {
928     size_t mac_overhead, int_overhead, blocksize, ext_overhead;
929     const SSL_CIPHER *ciph = SSL_get_current_cipher(s);
930     size_t mtu = s->d1->mtu;
931
932     if (ciph == NULL)
933         return 0;
934
935     if (!ssl_cipher_get_overhead(ciph, &mac_overhead, &int_overhead,
936                                  &blocksize, &ext_overhead))
937         return 0;
938
939     if (SSL_READ_ETM(s))
940         ext_overhead += mac_overhead;
941     else
942         int_overhead += mac_overhead;
943
944     /* Subtract external overhead (e.g. IV/nonce, separate MAC) */
945     if (ext_overhead + DTLS1_RT_HEADER_LENGTH >= mtu)
946         return 0;
947     mtu -= ext_overhead + DTLS1_RT_HEADER_LENGTH;
948
949     /* Round encrypted payload down to cipher block size (for CBC etc.)
950      * No check for overflow since 'mtu % blocksize' cannot exceed mtu. */
951     if (blocksize)
952         mtu -= (mtu % blocksize);
953
954     /* Subtract internal overhead (e.g. CBC padding len byte) */
955     if (int_overhead >= mtu)
956         return 0;
957     mtu -= int_overhead;
958
959     return mtu;
960 }