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