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