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