2 * Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved.
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
12 #include <openssl/objects.h>
13 #include <openssl/rand.h>
16 #if defined(OPENSSL_SYS_VMS)
17 # include <sys/timeb.h>
18 #elif defined(OPENSSL_SYS_VXWORKS)
19 # include <sys/times.h>
20 #elif !defined(OPENSSL_SYS_WIN32)
21 # include <sys/time.h>
24 static void get_current_time(struct timeval *t);
25 static int dtls1_set_handshake_header(SSL *s, int type, unsigned long len);
26 static int dtls1_handshake_write(SSL *s);
27 static unsigned int dtls1_link_min_mtu(void);
29 /* XDTLS: figure out the right values */
30 static const unsigned int g_probable_mtu[] = { 1500, 512, 256 };
32 const SSL3_ENC_METHOD DTLSv1_enc_data = {
36 tls1_generate_master_secret,
37 tls1_change_cipher_state,
38 tls1_final_finish_mac,
39 TLS1_FINISH_MAC_LENGTH,
40 TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
41 TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
43 tls1_export_keying_material,
44 SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV,
45 DTLS1_HM_HEADER_LENGTH,
46 dtls1_set_handshake_header,
50 const SSL3_ENC_METHOD DTLSv1_2_enc_data = {
54 tls1_generate_master_secret,
55 tls1_change_cipher_state,
56 tls1_final_finish_mac,
57 TLS1_FINISH_MAC_LENGTH,
58 TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
59 TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
61 tls1_export_keying_material,
62 SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS
63 | SSL_ENC_FLAG_SHA256_PRF | SSL_ENC_FLAG_TLS1_2_CIPHERS,
64 DTLS1_HM_HEADER_LENGTH,
65 dtls1_set_handshake_header,
69 long dtls1_default_timeout(void)
72 * 2 hours, the 24 hours mentioned in the DTLSv1 spec is way too long for
73 * http, the cache would over fill
82 if (!DTLS_RECORD_LAYER_new(&s->rlayer)) {
88 if ((d1 = OPENSSL_zalloc(sizeof(*d1))) == NULL) {
93 d1->buffered_messages = pqueue_new();
94 d1->sent_messages = pqueue_new();
97 d1->cookie_len = sizeof(s->d1->cookie);
103 if (d1->buffered_messages == NULL || d1->sent_messages == NULL) {
104 pqueue_free(d1->buffered_messages);
105 pqueue_free(d1->sent_messages);
112 s->method->ssl_clear(s);
116 static void dtls1_clear_queues(SSL *s)
118 dtls1_clear_received_buffer(s);
119 dtls1_clear_sent_buffer(s);
122 void dtls1_clear_received_buffer(SSL *s)
125 hm_fragment *frag = NULL;
127 while ((item = pqueue_pop(s->d1->buffered_messages)) != NULL) {
128 frag = (hm_fragment *)item->data;
129 dtls1_hm_fragment_free(frag);
134 void dtls1_clear_sent_buffer(SSL *s)
137 hm_fragment *frag = NULL;
139 while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
140 frag = (hm_fragment *)item->data;
141 dtls1_hm_fragment_free(frag);
147 void dtls1_free(SSL *s)
149 DTLS_RECORD_LAYER_free(&s->rlayer);
153 dtls1_clear_queues(s);
155 pqueue_free(s->d1->buffered_messages);
156 pqueue_free(s->d1->sent_messages);
162 void dtls1_clear(SSL *s)
164 pqueue *buffered_messages;
165 pqueue *sent_messages;
167 unsigned int link_mtu;
169 DTLS_RECORD_LAYER_clear(&s->rlayer);
172 buffered_messages = s->d1->buffered_messages;
173 sent_messages = s->d1->sent_messages;
175 link_mtu = s->d1->link_mtu;
177 dtls1_clear_queues(s);
179 memset(s->d1, 0, sizeof(*s->d1));
182 s->d1->cookie_len = sizeof(s->d1->cookie);
185 if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) {
187 s->d1->link_mtu = link_mtu;
190 s->d1->buffered_messages = buffered_messages;
191 s->d1->sent_messages = sent_messages;
196 if (s->method->version == DTLS_ANY_VERSION)
197 s->version = DTLS_MAX_VERSION;
198 #ifndef OPENSSL_NO_DTLS1_METHOD
199 else if (s->options & SSL_OP_CISCO_ANYCONNECT)
200 s->client_version = s->version = DTLS1_BAD_VER;
203 s->version = s->method->version;
206 long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg)
211 case DTLS_CTRL_GET_TIMEOUT:
212 if (dtls1_get_timeout(s, (struct timeval *)parg) != NULL) {
216 case DTLS_CTRL_HANDLE_TIMEOUT:
217 ret = dtls1_handle_timeout(s);
219 case DTLS_CTRL_SET_LINK_MTU:
220 if (larg < (long)dtls1_link_min_mtu())
222 s->d1->link_mtu = larg;
224 case DTLS_CTRL_GET_LINK_MIN_MTU:
225 return (long)dtls1_link_min_mtu();
226 case SSL_CTRL_SET_MTU:
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
231 if (larg < (long)dtls1_link_min_mtu() - DTLS1_MAX_MTU_OVERHEAD)
236 ret = ssl3_ctrl(s, cmd, larg, parg);
242 void dtls1_start_timer(SSL *s)
244 #ifndef OPENSSL_NO_SCTP
245 /* Disable timer for SCTP */
246 if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
247 memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
252 /* If timer is not set, initialize duration with 1 second */
253 if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
254 s->d1->timeout_duration = 1;
257 /* Set timeout to current time */
258 get_current_time(&(s->d1->next_timeout));
260 /* Add duration to current time */
261 s->d1->next_timeout.tv_sec += s->d1->timeout_duration;
262 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
263 &(s->d1->next_timeout));
266 struct timeval *dtls1_get_timeout(SSL *s, struct timeval *timeleft)
268 struct timeval timenow;
270 /* If no timeout is set, just return NULL */
271 if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
275 /* Get current time */
276 get_current_time(&timenow);
278 /* If timer already expired, set remaining time to 0 */
279 if (s->d1->next_timeout.tv_sec < timenow.tv_sec ||
280 (s->d1->next_timeout.tv_sec == timenow.tv_sec &&
281 s->d1->next_timeout.tv_usec <= timenow.tv_usec)) {
282 memset(timeleft, 0, sizeof(*timeleft));
286 /* Calculate time left until timer expires */
287 memcpy(timeleft, &(s->d1->next_timeout), sizeof(struct timeval));
288 timeleft->tv_sec -= timenow.tv_sec;
289 timeleft->tv_usec -= timenow.tv_usec;
290 if (timeleft->tv_usec < 0) {
292 timeleft->tv_usec += 1000000;
296 * If remaining time is less than 15 ms, set it to 0 to prevent issues
297 * because of small divergences with socket timeouts.
299 if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000) {
300 memset(timeleft, 0, sizeof(*timeleft));
306 int dtls1_is_timer_expired(SSL *s)
308 struct timeval timeleft;
310 /* Get time left until timeout, return false if no timer running */
311 if (dtls1_get_timeout(s, &timeleft) == NULL) {
315 /* Return false if timer is not expired yet */
316 if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) {
320 /* Timer expired, so return true */
324 void dtls1_double_timeout(SSL *s)
326 s->d1->timeout_duration *= 2;
327 if (s->d1->timeout_duration > 60)
328 s->d1->timeout_duration = 60;
329 dtls1_start_timer(s);
332 void dtls1_stop_timer(SSL *s)
334 /* Reset everything */
335 memset(&s->d1->timeout, 0, sizeof(s->d1->timeout));
336 memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
337 s->d1->timeout_duration = 1;
338 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
339 &(s->d1->next_timeout));
340 /* Clear retransmission buffer */
341 dtls1_clear_sent_buffer(s);
344 int dtls1_check_timeout_num(SSL *s)
348 s->d1->timeout.num_alerts++;
350 /* Reduce MTU after 2 unsuccessful retransmissions */
351 if (s->d1->timeout.num_alerts > 2
352 && !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
354 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0, NULL);
355 if (mtu < s->d1->mtu)
359 if (s->d1->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT) {
360 /* fail the connection, enough alerts have been sent */
361 SSLerr(SSL_F_DTLS1_CHECK_TIMEOUT_NUM, SSL_R_READ_TIMEOUT_EXPIRED);
368 int dtls1_handle_timeout(SSL *s)
370 /* if no timer is expired, don't do anything */
371 if (!dtls1_is_timer_expired(s)) {
375 dtls1_double_timeout(s);
377 if (dtls1_check_timeout_num(s) < 0)
380 s->d1->timeout.read_timeouts++;
381 if (s->d1->timeout.read_timeouts > DTLS1_TMO_READ_COUNT) {
382 s->d1->timeout.read_timeouts = 1;
384 #ifndef OPENSSL_NO_HEARTBEATS
385 if (s->tlsext_hb_pending) {
386 s->tlsext_hb_pending = 0;
387 return dtls1_heartbeat(s);
391 dtls1_start_timer(s);
392 return dtls1_retransmit_buffered_messages(s);
395 static void get_current_time(struct timeval *t)
405 SystemTimeToFileTime(&st, &now.ft);
406 /* re-bias to 1/1/1970 */
408 now.ul -= 116444736000000000ULL;
411 now.ul -= 116444736000000000UI64;
414 t->tv_sec = (long)(now.ul / 10000000);
415 t->tv_usec = ((int)(now.ul % 10000000)) / 10;
416 #elif defined(OPENSSL_SYS_VMS)
419 t->tv_sec = (long)tb.time;
420 t->tv_usec = (long)tb.millitm * 1000;
422 gettimeofday(t, NULL);
426 #define LISTEN_SUCCESS 2
427 #define LISTEN_SEND_VERIFY_REQUEST 1
429 #ifndef OPENSSL_NO_SOCK
430 int DTLSv1_listen(SSL *s, BIO_ADDR *client)
432 int next, n, ret = 0, clearpkt = 0;
433 unsigned char cookie[DTLS1_COOKIE_LENGTH];
434 unsigned char seq[SEQ_NUM_SIZE];
435 const unsigned char *data;
436 unsigned char *p, *buf;
437 unsigned long reclen, fragoff, fraglen, msglen;
438 unsigned int rectype, versmajor, msgseq, msgtype, clientvers, cookielen;
441 BIO_ADDR *tmpclient = NULL;
442 PACKET pkt, msgpkt, msgpayload, session, cookiepkt;
444 /* Ensure there is no state left over from a previous invocation */
450 rbio = SSL_get_rbio(s);
451 wbio = SSL_get_wbio(s);
453 if (!rbio || !wbio) {
454 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_BIO_NOT_SET);
459 * We only peek at incoming ClientHello's until we're sure we are going to
460 * to respond with a HelloVerifyRequest. If its a ClientHello with a valid
461 * cookie then we leave it in the BIO for accept to handle.
463 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 1, NULL);
466 * Note: This check deliberately excludes DTLS1_BAD_VER because that version
467 * requires the MAC to be calculated *including* the first ClientHello
468 * (without the cookie). Since DTLSv1_listen is stateless that cannot be
469 * supported. DTLS1_BAD_VER must use cookies in a stateful manner (e.g. via
472 if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
473 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNSUPPORTED_SSL_VERSION);
477 if (s->init_buf == NULL) {
478 if ((bufm = BUF_MEM_new()) == NULL) {
479 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
483 if (!BUF_MEM_grow(bufm, SSL3_RT_MAX_PLAIN_LENGTH)) {
485 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
490 buf = (unsigned char *)s->init_buf->data;
497 * Technically a ClientHello could be SSL3_RT_MAX_PLAIN_LENGTH
498 * + DTLS1_RT_HEADER_LENGTH bytes long. Normally init_buf does not store
499 * the record header as well, but we do here. We've set up init_buf to
500 * be the standard size for simplicity. In practice we shouldn't ever
501 * receive a ClientHello as long as this. If we do it will get dropped
502 * in the record length check below.
504 n = BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
507 if (BIO_should_retry(rbio)) {
508 /* Non-blocking IO */
514 /* If we hit any problems we need to clear this packet from the BIO */
517 if (!PACKET_buf_init(&pkt, buf, n)) {
518 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_INTERNAL_ERROR);
523 * Parse the received record. If there are any problems with it we just
524 * dump it - with no alert. RFC6347 says this "Unlike TLS, DTLS is
525 * resilient in the face of invalid records (e.g., invalid formatting,
526 * length, MAC, etc.). In general, invalid records SHOULD be silently
527 * discarded, thus preserving the association; however, an error MAY be
528 * logged for diagnostic purposes."
531 /* this packet contained a partial record, dump it */
532 if (n < DTLS1_RT_HEADER_LENGTH) {
533 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_RECORD_TOO_SMALL);
538 s->msg_callback(0, 0, SSL3_RT_HEADER, buf,
539 DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
541 /* Get the record header */
542 if (!PACKET_get_1(&pkt, &rectype)
543 || !PACKET_get_1(&pkt, &versmajor)) {
544 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
548 if (rectype != SSL3_RT_HANDSHAKE) {
549 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE);
554 * Check record version number. We only check that the major version is
557 if (versmajor != DTLS1_VERSION_MAJOR) {
558 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
562 if (!PACKET_forward(&pkt, 1)
563 /* Save the sequence number: 64 bits, with top 2 bytes = epoch */
564 || !PACKET_copy_bytes(&pkt, seq, SEQ_NUM_SIZE)
565 || !PACKET_get_length_prefixed_2(&pkt, &msgpkt)) {
566 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
570 * We allow data remaining at the end of the packet because there could
571 * be a second record (but we ignore it)
574 /* This is an initial ClientHello so the epoch has to be 0 */
575 if (seq[0] != 0 || seq[1] != 0) {
576 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE);
580 /* Get a pointer to the raw message for the later callback */
581 data = PACKET_data(&msgpkt);
583 /* Finished processing the record header, now process the message */
584 if (!PACKET_get_1(&msgpkt, &msgtype)
585 || !PACKET_get_net_3(&msgpkt, &msglen)
586 || !PACKET_get_net_2(&msgpkt, &msgseq)
587 || !PACKET_get_net_3(&msgpkt, &fragoff)
588 || !PACKET_get_net_3(&msgpkt, &fraglen)
589 || !PACKET_get_sub_packet(&msgpkt, &msgpayload, fraglen)
590 || PACKET_remaining(&msgpkt) != 0) {
591 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
595 if (msgtype != SSL3_MT_CLIENT_HELLO) {
596 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE);
600 /* Message sequence number can only be 0 or 1 */
602 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_INVALID_SEQUENCE_NUMBER);
607 * We don't support fragment reassembly for ClientHellos whilst
608 * listening because that would require server side state (which is
609 * against the whole point of the ClientHello/HelloVerifyRequest
610 * mechanism). Instead we only look at the first ClientHello fragment
611 * and require that the cookie must be contained within it.
613 if (fragoff != 0 || fraglen > msglen) {
614 /* Non initial ClientHello fragment (or bad fragment) */
615 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_FRAGMENTED_CLIENT_HELLO);
620 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, data,
621 fraglen + DTLS1_HM_HEADER_LENGTH, s,
622 s->msg_callback_arg);
624 if (!PACKET_get_net_2(&msgpayload, &clientvers)) {
625 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
630 * Verify client version is supported
632 if (DTLS_VERSION_LT(clientvers, (unsigned int)s->method->version) &&
633 s->method->version != DTLS_ANY_VERSION) {
634 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_WRONG_VERSION_NUMBER);
638 if (!PACKET_forward(&msgpayload, SSL3_RANDOM_SIZE)
639 || !PACKET_get_length_prefixed_1(&msgpayload, &session)
640 || !PACKET_get_length_prefixed_1(&msgpayload, &cookiepkt)) {
642 * Could be malformed or the cookie does not fit within the initial
643 * ClientHello fragment. Either way we can't handle it.
645 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
650 * Check if we have a cookie or not. If not we need to send a
651 * HelloVerifyRequest.
653 if (PACKET_remaining(&cookiepkt) == 0) {
654 next = LISTEN_SEND_VERIFY_REQUEST;
657 * We have a cookie, so lets check it.
659 if (s->ctx->app_verify_cookie_cb == NULL) {
660 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_NO_VERIFY_COOKIE_CALLBACK);
664 if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookiepkt),
665 PACKET_remaining(&cookiepkt)) ==
668 * We treat invalid cookies in the same was as no cookie as
671 next = LISTEN_SEND_VERIFY_REQUEST;
673 /* Cookie verification succeeded */
674 next = LISTEN_SUCCESS;
678 if (next == LISTEN_SEND_VERIFY_REQUEST) {
680 * There was no cookie in the ClientHello so we need to send a
681 * HelloVerifyRequest. If this fails we do not worry about trying
682 * to resend, we just drop it.
686 * Dump the read packet, we don't need it any more. Ignore return
689 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 0, NULL);
690 BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
691 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 1, NULL);
693 /* Generate the cookie */
694 if (s->ctx->app_gen_cookie_cb == NULL ||
695 s->ctx->app_gen_cookie_cb(s, cookie, &cookielen) == 0 ||
697 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
702 p = &buf[DTLS1_RT_HEADER_LENGTH];
703 msglen = dtls_raw_hello_verify_request(p + DTLS1_HM_HEADER_LENGTH,
706 *p++ = DTLS1_MT_HELLO_VERIFY_REQUEST;
711 /* Message sequence number is always 0 for a HelloVerifyRequest */
715 * We never fragment a HelloVerifyRequest, so fragment offset is 0
716 * and fragment length is message length
721 /* Set reclen equal to length of whole handshake message */
722 reclen = msglen + DTLS1_HM_HEADER_LENGTH;
724 /* Add the record header */
727 *(p++) = SSL3_RT_HANDSHAKE;
729 * Special case: for hello verify request, client version 1.0 and we
730 * haven't decided which version to use yet send back using version
731 * 1.0 header: otherwise some clients will ignore it.
733 if (s->method->version == DTLS_ANY_VERSION) {
734 *(p++) = DTLS1_VERSION >> 8;
735 *(p++) = DTLS1_VERSION & 0xff;
737 *(p++) = s->version >> 8;
738 *(p++) = s->version & 0xff;
742 * Record sequence number is always the same as in the received
745 memcpy(p, seq, SEQ_NUM_SIZE);
752 * Set reclen equal to length of whole record including record
755 reclen += DTLS1_RT_HEADER_LENGTH;
758 s->msg_callback(1, 0, SSL3_RT_HEADER, buf,
759 DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
761 if ((tmpclient = BIO_ADDR_new()) == NULL) {
762 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
767 * This is unnecessary if rbio and wbio are one and the same - but
768 * maybe they're not. We ignore errors here - some BIOs do not
771 if (BIO_dgram_get_peer(rbio, tmpclient) > 0) {
772 (void)BIO_dgram_set_peer(wbio, tmpclient);
774 BIO_ADDR_free(tmpclient);
777 if (BIO_write(wbio, buf, reclen) < (int)reclen) {
778 if (BIO_should_retry(wbio)) {
780 * Non-blocking IO...but we're stateless, so we're just
781 * going to drop this packet.
788 if (BIO_flush(wbio) <= 0) {
789 if (BIO_should_retry(wbio)) {
791 * Non-blocking IO...but we're stateless, so we're just
792 * going to drop this packet.
799 } while (next != LISTEN_SUCCESS);
802 * Set expected sequence numbers to continue the handshake.
804 s->d1->handshake_read_seq = 1;
805 s->d1->handshake_write_seq = 1;
806 s->d1->next_handshake_write_seq = 1;
807 DTLS_RECORD_LAYER_set_write_sequence(&s->rlayer, seq);
810 * We are doing cookie exchange, so make sure we set that option in the
813 SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE);
816 * Tell the state machine that we've done the initial hello verify
819 ossl_statem_set_hello_verify_done(s);
822 * Some BIOs may not support this. If we fail we clear the client address
824 if (BIO_dgram_get_peer(rbio, client) <= 0)
825 BIO_ADDR_clear(client);
830 BIO_ADDR_free(tmpclient);
831 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 0, NULL);
833 /* Dump this packet. Ignore return value */
834 BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
840 static int dtls1_set_handshake_header(SSL *s, int htype, unsigned long len)
842 dtls1_set_message_header(s, htype, len, 0, len);
843 s->init_num = (int)len + DTLS1_HM_HEADER_LENGTH;
845 /* Buffer the message to handle re-xmits */
847 if (!dtls1_buffer_message(s, 0))
853 static int dtls1_handshake_write(SSL *s)
855 return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
858 #ifndef OPENSSL_NO_HEARTBEATS
860 # define HEARTBEAT_SIZE(payload, padding) ( \
861 1 /* heartbeat type */ + \
862 2 /* heartbeat length */ + \
863 (payload) + (padding))
865 # define HEARTBEAT_SIZE_STD(payload) HEARTBEAT_SIZE(payload, 16)
867 int dtls1_process_heartbeat(SSL *s, unsigned char *p, unsigned int length)
870 unsigned short hbtype;
871 unsigned int payload;
872 unsigned int padding = 16; /* Use minimum padding */
875 s->msg_callback(0, s->version, DTLS1_RT_HEARTBEAT,
876 p, length, s, s->msg_callback_arg);
878 /* Read type and payload length */
879 if (HEARTBEAT_SIZE_STD(0) > length)
880 return 0; /* silently discard */
881 if (length > SSL3_RT_MAX_PLAIN_LENGTH)
882 return 0; /* silently discard per RFC 6520 sec. 4 */
886 if (HEARTBEAT_SIZE_STD(payload) > length)
887 return 0; /* silently discard per RFC 6520 sec. 4 */
890 if (hbtype == TLS1_HB_REQUEST) {
891 unsigned char *buffer, *bp;
892 unsigned int write_length = HEARTBEAT_SIZE(payload, padding);
895 if (write_length > SSL3_RT_MAX_PLAIN_LENGTH)
898 /* Allocate memory for the response. */
899 buffer = OPENSSL_malloc(write_length);
904 /* Enter response type, length and copy payload */
905 *bp++ = TLS1_HB_RESPONSE;
907 memcpy(bp, pl, payload);
910 if (RAND_bytes(bp, padding) <= 0) {
911 OPENSSL_free(buffer);
915 r = dtls1_write_bytes(s, DTLS1_RT_HEARTBEAT, buffer, write_length);
917 if (r >= 0 && s->msg_callback)
918 s->msg_callback(1, s->version, DTLS1_RT_HEARTBEAT,
919 buffer, write_length, s, s->msg_callback_arg);
921 OPENSSL_free(buffer);
925 } else if (hbtype == TLS1_HB_RESPONSE) {
929 * We only send sequence numbers (2 bytes unsigned int), and 16
930 * random bytes, so we just try to read the sequence number
934 if (payload == 18 && seq == s->tlsext_hb_seq) {
937 s->tlsext_hb_pending = 0;
944 int dtls1_heartbeat(SSL *s)
946 unsigned char *buf, *p;
948 unsigned int payload = 18; /* Sequence number + random bytes */
949 unsigned int padding = 16; /* Use minimum padding */
952 /* Only send if peer supports and accepts HB requests... */
953 if (!(s->tlsext_heartbeat & SSL_DTLSEXT_HB_ENABLED) ||
954 s->tlsext_heartbeat & SSL_DTLSEXT_HB_DONT_SEND_REQUESTS) {
955 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
959 /* ...and there is none in flight yet... */
960 if (s->tlsext_hb_pending) {
961 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
965 /* ...and no handshake in progress. */
966 if (SSL_in_init(s) || ossl_statem_get_in_handshake(s)) {
967 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
972 * Create HeartBeat message, we just use a sequence number
973 * as payload to distinguish different messages and add
976 size = HEARTBEAT_SIZE(payload, padding);
977 buf = OPENSSL_malloc(size);
979 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_MALLOC_FAILURE);
984 *p++ = TLS1_HB_REQUEST;
985 /* Payload length (18 bytes here) */
987 /* Sequence number */
988 s2n(s->tlsext_hb_seq, p);
989 /* 16 random bytes */
990 if (RAND_bytes(p, 16) <= 0) {
991 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
996 if (RAND_bytes(p, padding) <= 0) {
997 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
1001 ret = dtls1_write_bytes(s, DTLS1_RT_HEARTBEAT, buf, size);
1003 if (s->msg_callback)
1004 s->msg_callback(1, s->version, DTLS1_RT_HEARTBEAT,
1005 buf, size, s, s->msg_callback_arg);
1007 dtls1_start_timer(s);
1008 s->tlsext_hb_pending = 1;
1018 int dtls1_shutdown(SSL *s)
1021 #ifndef OPENSSL_NO_SCTP
1024 wbio = SSL_get_wbio(s);
1025 if (wbio != NULL && BIO_dgram_is_sctp(wbio) &&
1026 !(s->shutdown & SSL_SENT_SHUTDOWN)) {
1027 ret = BIO_dgram_sctp_wait_for_dry(wbio);
1032 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
1036 ret = ssl3_shutdown(s);
1037 #ifndef OPENSSL_NO_SCTP
1038 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
1043 int dtls1_query_mtu(SSL *s)
1045 if (s->d1->link_mtu) {
1047 s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
1048 s->d1->link_mtu = 0;
1051 /* AHA! Figure out the MTU, and stick to the right size */
1052 if (s->d1->mtu < dtls1_min_mtu(s)) {
1053 if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
1055 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
1058 * I've seen the kernel return bogus numbers when it doesn't know
1059 * (initial write), so just make sure we have a reasonable number
1061 if (s->d1->mtu < dtls1_min_mtu(s)) {
1062 /* Set to min mtu */
1063 s->d1->mtu = dtls1_min_mtu(s);
1064 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
1073 static unsigned int dtls1_link_min_mtu(void)
1075 return (g_probable_mtu[(sizeof(g_probable_mtu) /
1076 sizeof(g_probable_mtu[0])) - 1]);
1079 unsigned int dtls1_min_mtu(SSL *s)
1081 return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));