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)
119 hm_fragment *frag = NULL;
121 while ((item = pqueue_pop(s->d1->buffered_messages)) != NULL) {
122 frag = (hm_fragment *)item->data;
123 dtls1_hm_fragment_free(frag);
127 while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
128 frag = (hm_fragment *)item->data;
129 dtls1_hm_fragment_free(frag);
134 void dtls1_free(SSL *s)
136 DTLS_RECORD_LAYER_free(&s->rlayer);
140 dtls1_clear_queues(s);
142 pqueue_free(s->d1->buffered_messages);
143 pqueue_free(s->d1->sent_messages);
149 void dtls1_clear(SSL *s)
151 pqueue *buffered_messages;
152 pqueue *sent_messages;
154 unsigned int link_mtu;
156 DTLS_RECORD_LAYER_clear(&s->rlayer);
159 buffered_messages = s->d1->buffered_messages;
160 sent_messages = s->d1->sent_messages;
162 link_mtu = s->d1->link_mtu;
164 dtls1_clear_queues(s);
166 memset(s->d1, 0, sizeof(*s->d1));
169 s->d1->cookie_len = sizeof(s->d1->cookie);
172 if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) {
174 s->d1->link_mtu = link_mtu;
177 s->d1->buffered_messages = buffered_messages;
178 s->d1->sent_messages = sent_messages;
182 if (s->options & SSL_OP_CISCO_ANYCONNECT)
183 s->client_version = s->version = DTLS1_BAD_VER;
184 else if (s->method->version == DTLS_ANY_VERSION)
185 s->version = DTLS_MAX_VERSION;
187 s->version = s->method->version;
190 long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg)
195 case DTLS_CTRL_GET_TIMEOUT:
196 if (dtls1_get_timeout(s, (struct timeval *)parg) != NULL) {
200 case DTLS_CTRL_HANDLE_TIMEOUT:
201 ret = dtls1_handle_timeout(s);
203 case DTLS_CTRL_SET_LINK_MTU:
204 if (larg < (long)dtls1_link_min_mtu())
206 s->d1->link_mtu = larg;
208 case DTLS_CTRL_GET_LINK_MIN_MTU:
209 return (long)dtls1_link_min_mtu();
210 case SSL_CTRL_SET_MTU:
212 * We may not have a BIO set yet so can't call dtls1_min_mtu()
213 * We'll have to make do with dtls1_link_min_mtu() and max overhead
215 if (larg < (long)dtls1_link_min_mtu() - DTLS1_MAX_MTU_OVERHEAD)
220 ret = ssl3_ctrl(s, cmd, larg, parg);
226 void dtls1_start_timer(SSL *s)
228 #ifndef OPENSSL_NO_SCTP
229 /* Disable timer for SCTP */
230 if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
231 memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
236 /* If timer is not set, initialize duration with 1 second */
237 if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
238 s->d1->timeout_duration = 1;
241 /* Set timeout to current time */
242 get_current_time(&(s->d1->next_timeout));
244 /* Add duration to current time */
245 s->d1->next_timeout.tv_sec += s->d1->timeout_duration;
246 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
247 &(s->d1->next_timeout));
250 struct timeval *dtls1_get_timeout(SSL *s, struct timeval *timeleft)
252 struct timeval timenow;
254 /* If no timeout is set, just return NULL */
255 if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
259 /* Get current time */
260 get_current_time(&timenow);
262 /* If timer already expired, set remaining time to 0 */
263 if (s->d1->next_timeout.tv_sec < timenow.tv_sec ||
264 (s->d1->next_timeout.tv_sec == timenow.tv_sec &&
265 s->d1->next_timeout.tv_usec <= timenow.tv_usec)) {
266 memset(timeleft, 0, sizeof(*timeleft));
270 /* Calculate time left until timer expires */
271 memcpy(timeleft, &(s->d1->next_timeout), sizeof(struct timeval));
272 timeleft->tv_sec -= timenow.tv_sec;
273 timeleft->tv_usec -= timenow.tv_usec;
274 if (timeleft->tv_usec < 0) {
276 timeleft->tv_usec += 1000000;
280 * If remaining time is less than 15 ms, set it to 0 to prevent issues
281 * because of small divergences with socket timeouts.
283 if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000) {
284 memset(timeleft, 0, sizeof(*timeleft));
290 int dtls1_is_timer_expired(SSL *s)
292 struct timeval timeleft;
294 /* Get time left until timeout, return false if no timer running */
295 if (dtls1_get_timeout(s, &timeleft) == NULL) {
299 /* Return false if timer is not expired yet */
300 if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) {
304 /* Timer expired, so return true */
308 void dtls1_double_timeout(SSL *s)
310 s->d1->timeout_duration *= 2;
311 if (s->d1->timeout_duration > 60)
312 s->d1->timeout_duration = 60;
313 dtls1_start_timer(s);
316 void dtls1_stop_timer(SSL *s)
318 /* Reset everything */
319 memset(&s->d1->timeout, 0, sizeof(s->d1->timeout));
320 memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
321 s->d1->timeout_duration = 1;
322 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
323 &(s->d1->next_timeout));
324 /* Clear retransmission buffer */
325 dtls1_clear_record_buffer(s);
328 int dtls1_check_timeout_num(SSL *s)
332 s->d1->timeout.num_alerts++;
334 /* Reduce MTU after 2 unsuccessful retransmissions */
335 if (s->d1->timeout.num_alerts > 2
336 && !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
338 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0,
340 if (mtu < s->d1->mtu)
344 if (s->d1->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT) {
345 /* fail the connection, enough alerts have been sent */
346 SSLerr(SSL_F_DTLS1_CHECK_TIMEOUT_NUM, SSL_R_READ_TIMEOUT_EXPIRED);
353 int dtls1_handle_timeout(SSL *s)
355 /* if no timer is expired, don't do anything */
356 if (!dtls1_is_timer_expired(s)) {
360 dtls1_double_timeout(s);
362 if (dtls1_check_timeout_num(s) < 0)
365 s->d1->timeout.read_timeouts++;
366 if (s->d1->timeout.read_timeouts > DTLS1_TMO_READ_COUNT) {
367 s->d1->timeout.read_timeouts = 1;
369 #ifndef OPENSSL_NO_HEARTBEATS
370 if (s->tlsext_hb_pending) {
371 s->tlsext_hb_pending = 0;
372 return dtls1_heartbeat(s);
376 dtls1_start_timer(s);
377 return dtls1_retransmit_buffered_messages(s);
380 static void get_current_time(struct timeval *t)
390 SystemTimeToFileTime(&st, &now.ft);
392 now.ul -= 116444736000000000ULL;
394 now.ul -= 116444736000000000UI64; /* re-bias to 1/1/1970 */
396 t->tv_sec = (long)(now.ul / 10000000);
397 t->tv_usec = ((int)(now.ul % 10000000)) / 10;
398 #elif defined(OPENSSL_SYS_VMS)
401 t->tv_sec = (long)tb.time;
402 t->tv_usec = (long)tb.millitm * 1000;
404 gettimeofday(t, NULL);
409 #define LISTEN_SUCCESS 2
410 #define LISTEN_SEND_VERIFY_REQUEST 1
412 #ifndef OPENSSL_NO_SOCK
413 int DTLSv1_listen(SSL *s, BIO_ADDR *client)
415 int next, n, ret = 0, clearpkt = 0;
416 unsigned char cookie[DTLS1_COOKIE_LENGTH];
417 unsigned char seq[SEQ_NUM_SIZE];
418 const unsigned char *data;
419 unsigned char *p, *buf;
420 unsigned long reclen, fragoff, fraglen, msglen;
421 unsigned int rectype, versmajor, msgseq, msgtype, clientvers, cookielen;
424 BIO_ADDR *tmpclient = NULL;
425 PACKET pkt, msgpkt, msgpayload, session, cookiepkt;
427 /* Ensure there is no state left over from a previous invocation */
433 rbio = SSL_get_rbio(s);
434 wbio = SSL_get_wbio(s);
436 if (!rbio || !wbio) {
437 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_BIO_NOT_SET);
442 * We only peek at incoming ClientHello's until we're sure we are going to
443 * to respond with a HelloVerifyRequest. If its a ClientHello with a valid
444 * cookie then we leave it in the BIO for accept to handle.
446 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 1, NULL);
449 * Note: This check deliberately excludes DTLS1_BAD_VER because that version
450 * requires the MAC to be calculated *including* the first ClientHello
451 * (without the cookie). Since DTLSv1_listen is stateless that cannot be
452 * supported. DTLS1_BAD_VER must use cookies in a stateful manner (e.g. via
455 if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
456 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNSUPPORTED_SSL_VERSION);
460 if (s->init_buf == NULL) {
461 if ((bufm = BUF_MEM_new()) == NULL) {
462 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
466 if (!BUF_MEM_grow(bufm, SSL3_RT_MAX_PLAIN_LENGTH)) {
468 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
473 buf = (unsigned char *)s->init_buf->data;
480 * Technically a ClientHello could be SSL3_RT_MAX_PLAIN_LENGTH
481 * + DTLS1_RT_HEADER_LENGTH bytes long. Normally init_buf does not store
482 * the record header as well, but we do here. We've set up init_buf to
483 * be the standard size for simplicity. In practice we shouldn't ever
484 * receive a ClientHello as long as this. If we do it will get dropped
485 * in the record length check below.
487 n = BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
490 if (BIO_should_retry(rbio)) {
491 /* Non-blocking IO */
497 /* If we hit any problems we need to clear this packet from the BIO */
500 if (!PACKET_buf_init(&pkt, buf, n)) {
501 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_INTERNAL_ERROR);
506 * Parse the received record. If there are any problems with it we just
507 * dump it - with no alert. RFC6347 says this "Unlike TLS, DTLS is
508 * resilient in the face of invalid records (e.g., invalid formatting,
509 * length, MAC, etc.). In general, invalid records SHOULD be silently
510 * discarded, thus preserving the association; however, an error MAY be
511 * logged for diagnostic purposes."
514 /* this packet contained a partial record, dump it */
515 if (n < DTLS1_RT_HEADER_LENGTH) {
516 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_RECORD_TOO_SMALL);
521 s->msg_callback(0, 0, SSL3_RT_HEADER, buf,
522 DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
524 /* Get the record header */
525 if (!PACKET_get_1(&pkt, &rectype)
526 || !PACKET_get_1(&pkt, &versmajor)) {
527 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
531 if (rectype != SSL3_RT_HANDSHAKE) {
532 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE);
537 * Check record version number. We only check that the major version is
540 if (versmajor != DTLS1_VERSION_MAJOR) {
541 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
545 if (!PACKET_forward(&pkt, 1)
546 /* Save the sequence number: 64 bits, with top 2 bytes = epoch */
547 || !PACKET_copy_bytes(&pkt, seq, SEQ_NUM_SIZE)
548 || !PACKET_get_length_prefixed_2(&pkt, &msgpkt)) {
549 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
553 * We allow data remaining at the end of the packet because there could
554 * be a second record (but we ignore it)
557 /* This is an initial ClientHello so the epoch has to be 0 */
558 if (seq[0] != 0 || seq[1] != 0) {
559 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE);
563 /* Get a pointer to the raw message for the later callback */
564 data = PACKET_data(&msgpkt);
566 /* Finished processing the record header, now process the message */
567 if (!PACKET_get_1(&msgpkt, &msgtype)
568 || !PACKET_get_net_3(&msgpkt, &msglen)
569 || !PACKET_get_net_2(&msgpkt, &msgseq)
570 || !PACKET_get_net_3(&msgpkt, &fragoff)
571 || !PACKET_get_net_3(&msgpkt, &fraglen)
572 || !PACKET_get_sub_packet(&msgpkt, &msgpayload, fraglen)
573 || PACKET_remaining(&msgpkt) != 0) {
574 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
578 if (msgtype != SSL3_MT_CLIENT_HELLO) {
579 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE);
583 /* Message sequence number can only be 0 or 1 */
585 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_INVALID_SEQUENCE_NUMBER);
590 * We don't support fragment reassembly for ClientHellos whilst
591 * listening because that would require server side state (which is
592 * against the whole point of the ClientHello/HelloVerifyRequest
593 * mechanism). Instead we only look at the first ClientHello fragment
594 * and require that the cookie must be contained within it.
596 if (fragoff != 0 || fraglen > msglen) {
597 /* Non initial ClientHello fragment (or bad fragment) */
598 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_FRAGMENTED_CLIENT_HELLO);
603 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, data,
604 fraglen + DTLS1_HM_HEADER_LENGTH, s,
605 s->msg_callback_arg);
607 if (!PACKET_get_net_2(&msgpayload, &clientvers)) {
608 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
613 * Verify client version is supported
615 if (DTLS_VERSION_LT(clientvers, (unsigned int)s->method->version) &&
616 s->method->version != DTLS_ANY_VERSION) {
617 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_WRONG_VERSION_NUMBER);
621 if (!PACKET_forward(&msgpayload, SSL3_RANDOM_SIZE)
622 || !PACKET_get_length_prefixed_1(&msgpayload, &session)
623 || !PACKET_get_length_prefixed_1(&msgpayload, &cookiepkt)) {
625 * Could be malformed or the cookie does not fit within the initial
626 * ClientHello fragment. Either way we can't handle it.
628 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
633 * Check if we have a cookie or not. If not we need to send a
634 * HelloVerifyRequest.
636 if (PACKET_remaining(&cookiepkt) == 0) {
637 next = LISTEN_SEND_VERIFY_REQUEST;
640 * We have a cookie, so lets check it.
642 if (s->ctx->app_verify_cookie_cb == NULL) {
643 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_NO_VERIFY_COOKIE_CALLBACK);
647 if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookiepkt),
648 PACKET_remaining(&cookiepkt)) ==
651 * We treat invalid cookies in the same was as no cookie as
654 next = LISTEN_SEND_VERIFY_REQUEST;
656 /* Cookie verification succeeded */
657 next = LISTEN_SUCCESS;
661 if (next == LISTEN_SEND_VERIFY_REQUEST) {
663 * There was no cookie in the ClientHello so we need to send a
664 * HelloVerifyRequest. If this fails we do not worry about trying
665 * to resend, we just drop it.
669 * Dump the read packet, we don't need it any more. Ignore return
672 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 0, NULL);
673 BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
674 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 1, NULL);
676 /* Generate the cookie */
677 if (s->ctx->app_gen_cookie_cb == NULL ||
678 s->ctx->app_gen_cookie_cb(s, cookie, &cookielen) == 0 ||
680 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
685 p = &buf[DTLS1_RT_HEADER_LENGTH];
686 msglen = dtls_raw_hello_verify_request(p + DTLS1_HM_HEADER_LENGTH,
689 *p++ = DTLS1_MT_HELLO_VERIFY_REQUEST;
694 /* Message sequence number is always 0 for a HelloVerifyRequest */
698 * We never fragment a HelloVerifyRequest, so fragment offset is 0
699 * and fragment length is message length
704 /* Set reclen equal to length of whole handshake message */
705 reclen = msglen + DTLS1_HM_HEADER_LENGTH;
707 /* Add the record header */
710 *(p++) = SSL3_RT_HANDSHAKE;
712 * Special case: for hello verify request, client version 1.0 and we
713 * haven't decided which version to use yet send back using version
714 * 1.0 header: otherwise some clients will ignore it.
716 if (s->method->version == DTLS_ANY_VERSION) {
717 *(p++) = DTLS1_VERSION >> 8;
718 *(p++) = DTLS1_VERSION & 0xff;
720 *(p++) = s->version >> 8;
721 *(p++) = s->version & 0xff;
725 * Record sequence number is always the same as in the received
728 memcpy(p, seq, SEQ_NUM_SIZE);
735 * Set reclen equal to length of whole record including record
738 reclen += DTLS1_RT_HEADER_LENGTH;
741 s->msg_callback(1, 0, SSL3_RT_HEADER, buf,
742 DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
745 if ((tmpclient = BIO_ADDR_new()) == NULL) {
746 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
751 * This is unnecessary if rbio and wbio are one and the same - but
752 * maybe they're not. We ignore errors here - some BIOs do not
755 if (BIO_dgram_get_peer(rbio, tmpclient) > 0) {
756 (void)BIO_dgram_set_peer(wbio, tmpclient);
758 BIO_ADDR_free(tmpclient);
761 if (BIO_write(wbio, buf, reclen) < (int)reclen) {
762 if (BIO_should_retry(wbio)) {
764 * Non-blocking IO...but we're stateless, so we're just
765 * going to drop this packet.
772 if (BIO_flush(wbio) <= 0) {
773 if (BIO_should_retry(wbio)) {
775 * Non-blocking IO...but we're stateless, so we're just
776 * going to drop this packet.
783 } while (next != LISTEN_SUCCESS);
786 * Set expected sequence numbers to continue the handshake.
788 s->d1->handshake_read_seq = 1;
789 s->d1->handshake_write_seq = 1;
790 s->d1->next_handshake_write_seq = 1;
791 DTLS_RECORD_LAYER_set_write_sequence(&s->rlayer, seq);
794 * We are doing cookie exchange, so make sure we set that option in the
797 SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE);
800 * Tell the state machine that we've done the initial hello verify
803 ossl_statem_set_hello_verify_done(s);
805 /* Some BIOs may not support this. If we fail we clear the client address */
806 if (BIO_dgram_get_peer(rbio, client) <= 0)
807 BIO_ADDR_clear(client);
812 BIO_ADDR_free(tmpclient);
813 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 0, NULL);
815 /* Dump this packet. Ignore return value */
816 BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
822 static int dtls1_set_handshake_header(SSL *s, int htype, unsigned long len)
824 dtls1_set_message_header(s, htype, len, 0, len);
825 s->init_num = (int)len + DTLS1_HM_HEADER_LENGTH;
827 /* Buffer the message to handle re-xmits */
829 if (!dtls1_buffer_message(s, 0))
835 static int dtls1_handshake_write(SSL *s)
837 return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
840 #ifndef OPENSSL_NO_HEARTBEATS
842 #define HEARTBEAT_SIZE(payload, padding) ( \
843 1 /* heartbeat type */ + \
844 2 /* heartbeat length */ + \
845 (payload) + (padding))
847 #define HEARTBEAT_SIZE_STD(payload) HEARTBEAT_SIZE(payload, 16)
849 int dtls1_process_heartbeat(SSL *s, unsigned char *p, unsigned int length)
852 unsigned short hbtype;
853 unsigned int payload;
854 unsigned int padding = 16; /* Use minimum padding */
857 s->msg_callback(0, s->version, DTLS1_RT_HEARTBEAT,
858 p, length, s, s->msg_callback_arg);
860 /* Read type and payload length */
861 if (HEARTBEAT_SIZE_STD(0) > length)
862 return 0; /* silently discard */
863 if (length > SSL3_RT_MAX_PLAIN_LENGTH)
864 return 0; /* silently discard per RFC 6520 sec. 4 */
868 if (HEARTBEAT_SIZE_STD(payload) > length)
869 return 0; /* silently discard per RFC 6520 sec. 4 */
872 if (hbtype == TLS1_HB_REQUEST) {
873 unsigned char *buffer, *bp;
874 unsigned int write_length = HEARTBEAT_SIZE(payload, padding);
877 if (write_length > SSL3_RT_MAX_PLAIN_LENGTH)
880 /* Allocate memory for the response. */
881 buffer = OPENSSL_malloc(write_length);
886 /* Enter response type, length and copy payload */
887 *bp++ = TLS1_HB_RESPONSE;
889 memcpy(bp, pl, payload);
892 if (RAND_bytes(bp, padding) <= 0) {
893 OPENSSL_free(buffer);
897 r = dtls1_write_bytes(s, DTLS1_RT_HEARTBEAT, buffer, write_length);
899 if (r >= 0 && s->msg_callback)
900 s->msg_callback(1, s->version, DTLS1_RT_HEARTBEAT,
901 buffer, write_length, s, s->msg_callback_arg);
903 OPENSSL_free(buffer);
907 } else if (hbtype == TLS1_HB_RESPONSE) {
911 * We only send sequence numbers (2 bytes unsigned int), and 16
912 * random bytes, so we just try to read the sequence number
916 if (payload == 18 && seq == s->tlsext_hb_seq) {
919 s->tlsext_hb_pending = 0;
926 int dtls1_heartbeat(SSL *s)
928 unsigned char *buf, *p;
930 unsigned int payload = 18; /* Sequence number + random bytes */
931 unsigned int padding = 16; /* Use minimum padding */
934 /* Only send if peer supports and accepts HB requests... */
935 if (!(s->tlsext_heartbeat & SSL_DTLSEXT_HB_ENABLED) ||
936 s->tlsext_heartbeat & SSL_DTLSEXT_HB_DONT_SEND_REQUESTS) {
937 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
941 /* ...and there is none in flight yet... */
942 if (s->tlsext_hb_pending) {
943 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
947 /* ...and no handshake in progress. */
948 if (SSL_in_init(s) || ossl_statem_get_in_handshake(s)) {
949 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
954 * Create HeartBeat message, we just use a sequence number
955 * as payload to distinguish different messages and add
958 size = HEARTBEAT_SIZE(payload, padding);
959 buf = OPENSSL_malloc(size);
961 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_MALLOC_FAILURE);
966 *p++ = TLS1_HB_REQUEST;
967 /* Payload length (18 bytes here) */
969 /* Sequence number */
970 s2n(s->tlsext_hb_seq, p);
971 /* 16 random bytes */
972 if (RAND_bytes(p, 16) <= 0) {
973 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
978 if (RAND_bytes(p, padding) <= 0) {
979 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
983 ret = dtls1_write_bytes(s, DTLS1_RT_HEARTBEAT, buf, size);
986 s->msg_callback(1, s->version, DTLS1_RT_HEARTBEAT,
988 s, s->msg_callback_arg);
990 dtls1_start_timer(s);
991 s->tlsext_hb_pending = 1;
1001 int dtls1_shutdown(SSL *s)
1004 #ifndef OPENSSL_NO_SCTP
1007 wbio = SSL_get_wbio(s);
1008 if (wbio != NULL && BIO_dgram_is_sctp(wbio) &&
1009 !(s->shutdown & SSL_SENT_SHUTDOWN)) {
1010 ret = BIO_dgram_sctp_wait_for_dry(wbio);
1015 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
1019 ret = ssl3_shutdown(s);
1020 #ifndef OPENSSL_NO_SCTP
1021 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
1026 int dtls1_query_mtu(SSL *s)
1028 if (s->d1->link_mtu) {
1030 s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
1031 s->d1->link_mtu = 0;
1034 /* AHA! Figure out the MTU, and stick to the right size */
1035 if (s->d1->mtu < dtls1_min_mtu(s)) {
1036 if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
1038 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
1041 * I've seen the kernel return bogus numbers when it doesn't know
1042 * (initial write), so just make sure we have a reasonable number
1044 if (s->d1->mtu < dtls1_min_mtu(s)) {
1045 /* Set to min mtu */
1046 s->d1->mtu = dtls1_min_mtu(s);
1047 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
1056 static unsigned int dtls1_link_min_mtu(void)
1058 return (g_probable_mtu[(sizeof(g_probable_mtu) /
1059 sizeof(g_probable_mtu[0])) - 1]);
1062 unsigned int dtls1_min_mtu(SSL *s)
1064 return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));