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,
47 dtls1_set_handshake_header2,
48 dtls1_close_construct_packet,
52 const SSL3_ENC_METHOD DTLSv1_2_enc_data = {
56 tls1_generate_master_secret,
57 tls1_change_cipher_state,
58 tls1_final_finish_mac,
59 TLS1_FINISH_MAC_LENGTH,
60 TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
61 TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
63 tls1_export_keying_material,
64 SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS
65 | SSL_ENC_FLAG_SHA256_PRF | SSL_ENC_FLAG_TLS1_2_CIPHERS,
66 DTLS1_HM_HEADER_LENGTH,
67 dtls1_set_handshake_header,
68 dtls1_set_handshake_header2,
69 dtls1_close_construct_packet,
73 long dtls1_default_timeout(void)
76 * 2 hours, the 24 hours mentioned in the DTLSv1 spec is way too long for
77 * http, the cache would over fill
86 if (!DTLS_RECORD_LAYER_new(&s->rlayer)) {
92 if ((d1 = OPENSSL_zalloc(sizeof(*d1))) == NULL) {
97 d1->buffered_messages = pqueue_new();
98 d1->sent_messages = pqueue_new();
101 d1->cookie_len = sizeof(s->d1->cookie);
107 if (d1->buffered_messages == NULL || d1->sent_messages == NULL) {
108 pqueue_free(d1->buffered_messages);
109 pqueue_free(d1->sent_messages);
116 s->method->ssl_clear(s);
120 static void dtls1_clear_queues(SSL *s)
122 dtls1_clear_received_buffer(s);
123 dtls1_clear_sent_buffer(s);
126 void dtls1_clear_received_buffer(SSL *s)
129 hm_fragment *frag = NULL;
131 while ((item = pqueue_pop(s->d1->buffered_messages)) != NULL) {
132 frag = (hm_fragment *)item->data;
133 dtls1_hm_fragment_free(frag);
138 void dtls1_clear_sent_buffer(SSL *s)
141 hm_fragment *frag = NULL;
143 while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
144 frag = (hm_fragment *)item->data;
145 dtls1_hm_fragment_free(frag);
151 void dtls1_free(SSL *s)
153 DTLS_RECORD_LAYER_free(&s->rlayer);
157 dtls1_clear_queues(s);
159 pqueue_free(s->d1->buffered_messages);
160 pqueue_free(s->d1->sent_messages);
166 void dtls1_clear(SSL *s)
168 pqueue *buffered_messages;
169 pqueue *sent_messages;
171 unsigned int link_mtu;
173 DTLS_RECORD_LAYER_clear(&s->rlayer);
176 buffered_messages = s->d1->buffered_messages;
177 sent_messages = s->d1->sent_messages;
179 link_mtu = s->d1->link_mtu;
181 dtls1_clear_queues(s);
183 memset(s->d1, 0, sizeof(*s->d1));
186 s->d1->cookie_len = sizeof(s->d1->cookie);
189 if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) {
191 s->d1->link_mtu = link_mtu;
194 s->d1->buffered_messages = buffered_messages;
195 s->d1->sent_messages = sent_messages;
200 if (s->method->version == DTLS_ANY_VERSION)
201 s->version = DTLS_MAX_VERSION;
202 #ifndef OPENSSL_NO_DTLS1_METHOD
203 else if (s->options & SSL_OP_CISCO_ANYCONNECT)
204 s->client_version = s->version = DTLS1_BAD_VER;
207 s->version = s->method->version;
210 long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg)
215 case DTLS_CTRL_GET_TIMEOUT:
216 if (dtls1_get_timeout(s, (struct timeval *)parg) != NULL) {
220 case DTLS_CTRL_HANDLE_TIMEOUT:
221 ret = dtls1_handle_timeout(s);
223 case DTLS_CTRL_SET_LINK_MTU:
224 if (larg < (long)dtls1_link_min_mtu())
226 s->d1->link_mtu = larg;
228 case DTLS_CTRL_GET_LINK_MIN_MTU:
229 return (long)dtls1_link_min_mtu();
230 case SSL_CTRL_SET_MTU:
232 * We may not have a BIO set yet so can't call dtls1_min_mtu()
233 * We'll have to make do with dtls1_link_min_mtu() and max overhead
235 if (larg < (long)dtls1_link_min_mtu() - DTLS1_MAX_MTU_OVERHEAD)
240 ret = ssl3_ctrl(s, cmd, larg, parg);
246 void dtls1_start_timer(SSL *s)
248 #ifndef OPENSSL_NO_SCTP
249 /* Disable timer for SCTP */
250 if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
251 memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
256 /* If timer is not set, initialize duration with 1 second */
257 if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
258 s->d1->timeout_duration = 1;
261 /* Set timeout to current time */
262 get_current_time(&(s->d1->next_timeout));
264 /* Add duration to current time */
265 s->d1->next_timeout.tv_sec += s->d1->timeout_duration;
266 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
267 &(s->d1->next_timeout));
270 struct timeval *dtls1_get_timeout(SSL *s, struct timeval *timeleft)
272 struct timeval timenow;
274 /* If no timeout is set, just return NULL */
275 if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
279 /* Get current time */
280 get_current_time(&timenow);
282 /* If timer already expired, set remaining time to 0 */
283 if (s->d1->next_timeout.tv_sec < timenow.tv_sec ||
284 (s->d1->next_timeout.tv_sec == timenow.tv_sec &&
285 s->d1->next_timeout.tv_usec <= timenow.tv_usec)) {
286 memset(timeleft, 0, sizeof(*timeleft));
290 /* Calculate time left until timer expires */
291 memcpy(timeleft, &(s->d1->next_timeout), sizeof(struct timeval));
292 timeleft->tv_sec -= timenow.tv_sec;
293 timeleft->tv_usec -= timenow.tv_usec;
294 if (timeleft->tv_usec < 0) {
296 timeleft->tv_usec += 1000000;
300 * If remaining time is less than 15 ms, set it to 0 to prevent issues
301 * because of small divergences with socket timeouts.
303 if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000) {
304 memset(timeleft, 0, sizeof(*timeleft));
310 int dtls1_is_timer_expired(SSL *s)
312 struct timeval timeleft;
314 /* Get time left until timeout, return false if no timer running */
315 if (dtls1_get_timeout(s, &timeleft) == NULL) {
319 /* Return false if timer is not expired yet */
320 if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) {
324 /* Timer expired, so return true */
328 void dtls1_double_timeout(SSL *s)
330 s->d1->timeout_duration *= 2;
331 if (s->d1->timeout_duration > 60)
332 s->d1->timeout_duration = 60;
333 dtls1_start_timer(s);
336 void dtls1_stop_timer(SSL *s)
338 /* Reset everything */
339 memset(&s->d1->timeout, 0, sizeof(s->d1->timeout));
340 memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
341 s->d1->timeout_duration = 1;
342 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
343 &(s->d1->next_timeout));
344 /* Clear retransmission buffer */
345 dtls1_clear_sent_buffer(s);
348 int dtls1_check_timeout_num(SSL *s)
352 s->d1->timeout.num_alerts++;
354 /* Reduce MTU after 2 unsuccessful retransmissions */
355 if (s->d1->timeout.num_alerts > 2
356 && !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
358 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0, NULL);
359 if (mtu < s->d1->mtu)
363 if (s->d1->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT) {
364 /* fail the connection, enough alerts have been sent */
365 SSLerr(SSL_F_DTLS1_CHECK_TIMEOUT_NUM, SSL_R_READ_TIMEOUT_EXPIRED);
372 int dtls1_handle_timeout(SSL *s)
374 /* if no timer is expired, don't do anything */
375 if (!dtls1_is_timer_expired(s)) {
379 dtls1_double_timeout(s);
381 if (dtls1_check_timeout_num(s) < 0)
384 s->d1->timeout.read_timeouts++;
385 if (s->d1->timeout.read_timeouts > DTLS1_TMO_READ_COUNT) {
386 s->d1->timeout.read_timeouts = 1;
388 #ifndef OPENSSL_NO_HEARTBEATS
389 if (s->tlsext_hb_pending) {
390 s->tlsext_hb_pending = 0;
391 return dtls1_heartbeat(s);
395 dtls1_start_timer(s);
396 return dtls1_retransmit_buffered_messages(s);
399 static void get_current_time(struct timeval *t)
409 SystemTimeToFileTime(&st, &now.ft);
410 /* re-bias to 1/1/1970 */
412 now.ul -= 116444736000000000ULL;
415 now.ul -= 116444736000000000UI64;
418 t->tv_sec = (long)(now.ul / 10000000);
419 t->tv_usec = ((int)(now.ul % 10000000)) / 10;
420 #elif defined(OPENSSL_SYS_VMS)
423 t->tv_sec = (long)tb.time;
424 t->tv_usec = (long)tb.millitm * 1000;
426 gettimeofday(t, NULL);
430 #define LISTEN_SUCCESS 2
431 #define LISTEN_SEND_VERIFY_REQUEST 1
433 #ifndef OPENSSL_NO_SOCK
434 int DTLSv1_listen(SSL *s, BIO_ADDR *client)
436 int next, n, ret = 0, clearpkt = 0;
437 unsigned char cookie[DTLS1_COOKIE_LENGTH];
438 unsigned char seq[SEQ_NUM_SIZE];
439 const unsigned char *data;
440 unsigned char *p, *buf;
441 unsigned long reclen, fragoff, fraglen, msglen;
442 unsigned int rectype, versmajor, msgseq, msgtype, clientvers, cookielen;
445 BIO_ADDR *tmpclient = NULL;
446 PACKET pkt, msgpkt, msgpayload, session, cookiepkt;
448 /* Ensure there is no state left over from a previous invocation */
454 rbio = SSL_get_rbio(s);
455 wbio = SSL_get_wbio(s);
457 if (!rbio || !wbio) {
458 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_BIO_NOT_SET);
463 * We only peek at incoming ClientHello's until we're sure we are going to
464 * to respond with a HelloVerifyRequest. If its a ClientHello with a valid
465 * cookie then we leave it in the BIO for accept to handle.
467 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 1, NULL);
470 * Note: This check deliberately excludes DTLS1_BAD_VER because that version
471 * requires the MAC to be calculated *including* the first ClientHello
472 * (without the cookie). Since DTLSv1_listen is stateless that cannot be
473 * supported. DTLS1_BAD_VER must use cookies in a stateful manner (e.g. via
476 if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
477 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNSUPPORTED_SSL_VERSION);
481 if (s->init_buf == NULL) {
482 if ((bufm = BUF_MEM_new()) == NULL) {
483 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
487 if (!BUF_MEM_grow(bufm, SSL3_RT_MAX_PLAIN_LENGTH)) {
489 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
494 buf = (unsigned char *)s->init_buf->data;
501 * Technically a ClientHello could be SSL3_RT_MAX_PLAIN_LENGTH
502 * + DTLS1_RT_HEADER_LENGTH bytes long. Normally init_buf does not store
503 * the record header as well, but we do here. We've set up init_buf to
504 * be the standard size for simplicity. In practice we shouldn't ever
505 * receive a ClientHello as long as this. If we do it will get dropped
506 * in the record length check below.
508 n = BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
511 if (BIO_should_retry(rbio)) {
512 /* Non-blocking IO */
518 /* If we hit any problems we need to clear this packet from the BIO */
521 if (!PACKET_buf_init(&pkt, buf, n)) {
522 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_INTERNAL_ERROR);
527 * Parse the received record. If there are any problems with it we just
528 * dump it - with no alert. RFC6347 says this "Unlike TLS, DTLS is
529 * resilient in the face of invalid records (e.g., invalid formatting,
530 * length, MAC, etc.). In general, invalid records SHOULD be silently
531 * discarded, thus preserving the association; however, an error MAY be
532 * logged for diagnostic purposes."
535 /* this packet contained a partial record, dump it */
536 if (n < DTLS1_RT_HEADER_LENGTH) {
537 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_RECORD_TOO_SMALL);
542 s->msg_callback(0, 0, SSL3_RT_HEADER, buf,
543 DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
545 /* Get the record header */
546 if (!PACKET_get_1(&pkt, &rectype)
547 || !PACKET_get_1(&pkt, &versmajor)) {
548 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
552 if (rectype != SSL3_RT_HANDSHAKE) {
553 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE);
558 * Check record version number. We only check that the major version is
561 if (versmajor != DTLS1_VERSION_MAJOR) {
562 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
566 if (!PACKET_forward(&pkt, 1)
567 /* Save the sequence number: 64 bits, with top 2 bytes = epoch */
568 || !PACKET_copy_bytes(&pkt, seq, SEQ_NUM_SIZE)
569 || !PACKET_get_length_prefixed_2(&pkt, &msgpkt)) {
570 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
574 * We allow data remaining at the end of the packet because there could
575 * be a second record (but we ignore it)
578 /* This is an initial ClientHello so the epoch has to be 0 */
579 if (seq[0] != 0 || seq[1] != 0) {
580 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE);
584 /* Get a pointer to the raw message for the later callback */
585 data = PACKET_data(&msgpkt);
587 /* Finished processing the record header, now process the message */
588 if (!PACKET_get_1(&msgpkt, &msgtype)
589 || !PACKET_get_net_3(&msgpkt, &msglen)
590 || !PACKET_get_net_2(&msgpkt, &msgseq)
591 || !PACKET_get_net_3(&msgpkt, &fragoff)
592 || !PACKET_get_net_3(&msgpkt, &fraglen)
593 || !PACKET_get_sub_packet(&msgpkt, &msgpayload, fraglen)
594 || PACKET_remaining(&msgpkt) != 0) {
595 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
599 if (msgtype != SSL3_MT_CLIENT_HELLO) {
600 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE);
604 /* Message sequence number can only be 0 or 1 */
606 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_INVALID_SEQUENCE_NUMBER);
611 * We don't support fragment reassembly for ClientHellos whilst
612 * listening because that would require server side state (which is
613 * against the whole point of the ClientHello/HelloVerifyRequest
614 * mechanism). Instead we only look at the first ClientHello fragment
615 * and require that the cookie must be contained within it.
617 if (fragoff != 0 || fraglen > msglen) {
618 /* Non initial ClientHello fragment (or bad fragment) */
619 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_FRAGMENTED_CLIENT_HELLO);
624 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, data,
625 fraglen + DTLS1_HM_HEADER_LENGTH, s,
626 s->msg_callback_arg);
628 if (!PACKET_get_net_2(&msgpayload, &clientvers)) {
629 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
634 * Verify client version is supported
636 if (DTLS_VERSION_LT(clientvers, (unsigned int)s->method->version) &&
637 s->method->version != DTLS_ANY_VERSION) {
638 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_WRONG_VERSION_NUMBER);
642 if (!PACKET_forward(&msgpayload, SSL3_RANDOM_SIZE)
643 || !PACKET_get_length_prefixed_1(&msgpayload, &session)
644 || !PACKET_get_length_prefixed_1(&msgpayload, &cookiepkt)) {
646 * Could be malformed or the cookie does not fit within the initial
647 * ClientHello fragment. Either way we can't handle it.
649 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH);
654 * Check if we have a cookie or not. If not we need to send a
655 * HelloVerifyRequest.
657 if (PACKET_remaining(&cookiepkt) == 0) {
658 next = LISTEN_SEND_VERIFY_REQUEST;
661 * We have a cookie, so lets check it.
663 if (s->ctx->app_verify_cookie_cb == NULL) {
664 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_NO_VERIFY_COOKIE_CALLBACK);
668 if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookiepkt),
669 PACKET_remaining(&cookiepkt)) ==
672 * We treat invalid cookies in the same was as no cookie as
675 next = LISTEN_SEND_VERIFY_REQUEST;
677 /* Cookie verification succeeded */
678 next = LISTEN_SUCCESS;
682 if (next == LISTEN_SEND_VERIFY_REQUEST) {
684 * There was no cookie in the ClientHello so we need to send a
685 * HelloVerifyRequest. If this fails we do not worry about trying
686 * to resend, we just drop it.
690 * Dump the read packet, we don't need it any more. Ignore return
693 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 0, NULL);
694 BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
695 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 1, NULL);
697 /* Generate the cookie */
698 if (s->ctx->app_gen_cookie_cb == NULL ||
699 s->ctx->app_gen_cookie_cb(s, cookie, &cookielen) == 0 ||
701 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
706 p = &buf[DTLS1_RT_HEADER_LENGTH];
707 msglen = dtls_raw_hello_verify_request(p + DTLS1_HM_HEADER_LENGTH,
710 *p++ = DTLS1_MT_HELLO_VERIFY_REQUEST;
715 /* Message sequence number is always 0 for a HelloVerifyRequest */
719 * We never fragment a HelloVerifyRequest, so fragment offset is 0
720 * and fragment length is message length
725 /* Set reclen equal to length of whole handshake message */
726 reclen = msglen + DTLS1_HM_HEADER_LENGTH;
728 /* Add the record header */
731 *(p++) = SSL3_RT_HANDSHAKE;
733 * Special case: for hello verify request, client version 1.0 and we
734 * haven't decided which version to use yet send back using version
735 * 1.0 header: otherwise some clients will ignore it.
737 if (s->method->version == DTLS_ANY_VERSION) {
738 *(p++) = DTLS1_VERSION >> 8;
739 *(p++) = DTLS1_VERSION & 0xff;
741 *(p++) = s->version >> 8;
742 *(p++) = s->version & 0xff;
746 * Record sequence number is always the same as in the received
749 memcpy(p, seq, SEQ_NUM_SIZE);
756 * Set reclen equal to length of whole record including record
759 reclen += DTLS1_RT_HEADER_LENGTH;
762 s->msg_callback(1, 0, SSL3_RT_HEADER, buf,
763 DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
765 if ((tmpclient = BIO_ADDR_new()) == NULL) {
766 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
771 * This is unnecessary if rbio and wbio are one and the same - but
772 * maybe they're not. We ignore errors here - some BIOs do not
775 if (BIO_dgram_get_peer(rbio, tmpclient) > 0) {
776 (void)BIO_dgram_set_peer(wbio, tmpclient);
778 BIO_ADDR_free(tmpclient);
781 if (BIO_write(wbio, buf, reclen) < (int)reclen) {
782 if (BIO_should_retry(wbio)) {
784 * Non-blocking IO...but we're stateless, so we're just
785 * going to drop this packet.
792 if (BIO_flush(wbio) <= 0) {
793 if (BIO_should_retry(wbio)) {
795 * Non-blocking IO...but we're stateless, so we're just
796 * going to drop this packet.
803 } while (next != LISTEN_SUCCESS);
806 * Set expected sequence numbers to continue the handshake.
808 s->d1->handshake_read_seq = 1;
809 s->d1->handshake_write_seq = 1;
810 s->d1->next_handshake_write_seq = 1;
811 DTLS_RECORD_LAYER_set_write_sequence(&s->rlayer, seq);
814 * We are doing cookie exchange, so make sure we set that option in the
817 SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE);
820 * Tell the state machine that we've done the initial hello verify
823 ossl_statem_set_hello_verify_done(s);
826 * Some BIOs may not support this. If we fail we clear the client address
828 if (BIO_dgram_get_peer(rbio, client) <= 0)
829 BIO_ADDR_clear(client);
834 BIO_ADDR_free(tmpclient);
835 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 0, NULL);
837 /* Dump this packet. Ignore return value */
838 BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
844 static int dtls1_set_handshake_header(SSL *s, int htype, unsigned long len)
846 dtls1_set_message_header(s, htype, len, 0, len);
847 s->init_num = (int)len + DTLS1_HM_HEADER_LENGTH;
849 /* Buffer the message to handle re-xmits */
851 if (!dtls1_buffer_message(s, 0))
857 static int dtls1_handshake_write(SSL *s)
859 return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
862 #ifndef OPENSSL_NO_HEARTBEATS
864 # define HEARTBEAT_SIZE(payload, padding) ( \
865 1 /* heartbeat type */ + \
866 2 /* heartbeat length */ + \
867 (payload) + (padding))
869 # define HEARTBEAT_SIZE_STD(payload) HEARTBEAT_SIZE(payload, 16)
871 int dtls1_process_heartbeat(SSL *s, unsigned char *p, unsigned int length)
874 unsigned short hbtype;
875 unsigned int payload;
876 unsigned int padding = 16; /* Use minimum padding */
879 s->msg_callback(0, s->version, DTLS1_RT_HEARTBEAT,
880 p, length, s, s->msg_callback_arg);
882 /* Read type and payload length */
883 if (HEARTBEAT_SIZE_STD(0) > length)
884 return 0; /* silently discard */
885 if (length > SSL3_RT_MAX_PLAIN_LENGTH)
886 return 0; /* silently discard per RFC 6520 sec. 4 */
890 if (HEARTBEAT_SIZE_STD(payload) > length)
891 return 0; /* silently discard per RFC 6520 sec. 4 */
894 if (hbtype == TLS1_HB_REQUEST) {
895 unsigned char *buffer, *bp;
896 unsigned int write_length = HEARTBEAT_SIZE(payload, padding);
899 if (write_length > SSL3_RT_MAX_PLAIN_LENGTH)
902 /* Allocate memory for the response. */
903 buffer = OPENSSL_malloc(write_length);
908 /* Enter response type, length and copy payload */
909 *bp++ = TLS1_HB_RESPONSE;
911 memcpy(bp, pl, payload);
914 if (RAND_bytes(bp, padding) <= 0) {
915 OPENSSL_free(buffer);
919 r = dtls1_write_bytes(s, DTLS1_RT_HEARTBEAT, buffer, write_length);
921 if (r >= 0 && s->msg_callback)
922 s->msg_callback(1, s->version, DTLS1_RT_HEARTBEAT,
923 buffer, write_length, s, s->msg_callback_arg);
925 OPENSSL_free(buffer);
929 } else if (hbtype == TLS1_HB_RESPONSE) {
933 * We only send sequence numbers (2 bytes unsigned int), and 16
934 * random bytes, so we just try to read the sequence number
938 if (payload == 18 && seq == s->tlsext_hb_seq) {
941 s->tlsext_hb_pending = 0;
948 int dtls1_heartbeat(SSL *s)
950 unsigned char *buf, *p;
952 unsigned int payload = 18; /* Sequence number + random bytes */
953 unsigned int padding = 16; /* Use minimum padding */
956 /* Only send if peer supports and accepts HB requests... */
957 if (!(s->tlsext_heartbeat & SSL_DTLSEXT_HB_ENABLED) ||
958 s->tlsext_heartbeat & SSL_DTLSEXT_HB_DONT_SEND_REQUESTS) {
959 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
963 /* ...and there is none in flight yet... */
964 if (s->tlsext_hb_pending) {
965 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
969 /* ...and no handshake in progress. */
970 if (SSL_in_init(s) || ossl_statem_get_in_handshake(s)) {
971 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
976 * Create HeartBeat message, we just use a sequence number
977 * as payload to distinguish different messages and add
980 size = HEARTBEAT_SIZE(payload, padding);
981 buf = OPENSSL_malloc(size);
983 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_MALLOC_FAILURE);
988 *p++ = TLS1_HB_REQUEST;
989 /* Payload length (18 bytes here) */
991 /* Sequence number */
992 s2n(s->tlsext_hb_seq, p);
993 /* 16 random bytes */
994 if (RAND_bytes(p, 16) <= 0) {
995 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
1000 if (RAND_bytes(p, padding) <= 0) {
1001 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
1005 ret = dtls1_write_bytes(s, DTLS1_RT_HEARTBEAT, buf, size);
1007 if (s->msg_callback)
1008 s->msg_callback(1, s->version, DTLS1_RT_HEARTBEAT,
1009 buf, size, s, s->msg_callback_arg);
1011 dtls1_start_timer(s);
1012 s->tlsext_hb_pending = 1;
1022 int dtls1_shutdown(SSL *s)
1025 #ifndef OPENSSL_NO_SCTP
1028 wbio = SSL_get_wbio(s);
1029 if (wbio != NULL && BIO_dgram_is_sctp(wbio) &&
1030 !(s->shutdown & SSL_SENT_SHUTDOWN)) {
1031 ret = BIO_dgram_sctp_wait_for_dry(wbio);
1036 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
1040 ret = ssl3_shutdown(s);
1041 #ifndef OPENSSL_NO_SCTP
1042 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
1047 int dtls1_query_mtu(SSL *s)
1049 if (s->d1->link_mtu) {
1051 s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
1052 s->d1->link_mtu = 0;
1055 /* AHA! Figure out the MTU, and stick to the right size */
1056 if (s->d1->mtu < dtls1_min_mtu(s)) {
1057 if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
1059 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
1062 * I've seen the kernel return bogus numbers when it doesn't know
1063 * (initial write), so just make sure we have a reasonable number
1065 if (s->d1->mtu < dtls1_min_mtu(s)) {
1066 /* Set to min mtu */
1067 s->d1->mtu = dtls1_min_mtu(s);
1068 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
1077 static unsigned int dtls1_link_min_mtu(void)
1079 return (g_probable_mtu[(sizeof(g_probable_mtu) /
1080 sizeof(g_probable_mtu[0])) - 1]);
1083 unsigned int dtls1_min_mtu(SSL *s)
1085 return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));