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