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