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