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;
441 unsigned long 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 unsigned int version;
688 * There was no cookie in the ClientHello so we need to send a
689 * HelloVerifyRequest. If this fails we do not worry about trying
690 * to resend, we just drop it.
694 * Dump the read packet, we don't need it any more. Ignore return
697 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 0, NULL);
698 BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
699 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 1, NULL);
701 /* Generate the cookie */
702 if (s->ctx->app_gen_cookie_cb == NULL ||
703 s->ctx->app_gen_cookie_cb(s, cookie, &cookielen) == 0 ||
705 SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
711 * Special case: for hello verify request, client version 1.0 and we
712 * haven't decided which version to use yet send back using version
713 * 1.0 header: otherwise some clients will ignore it.
715 version = (s->method->version == DTLS_ANY_VERSION) ? DTLS1_VERSION
718 /* Construct the record and message headers */
719 if (!WPACKET_init(&wpkt, s->init_buf)
720 || !WPACKET_put_bytes_u8(&wpkt, SSL3_RT_HANDSHAKE)
721 || !WPACKET_put_bytes_u16(&wpkt, version)
723 * Record sequence number is always the same as in the
724 * received ClientHello
726 || !WPACKET_memcpy(&wpkt, seq, SEQ_NUM_SIZE)
727 /* End of record, start sub packet for message */
728 || !WPACKET_start_sub_packet_u16(&wpkt)
730 || !WPACKET_put_bytes_u8(&wpkt,
731 DTLS1_MT_HELLO_VERIFY_REQUEST)
733 * Message length - doesn't follow normal TLS convention:
734 * the length isn't the last thing in the message header.
735 * We'll need to fill this in later when we know the
736 * length. Set it to zero for now
738 || !WPACKET_put_bytes_u24(&wpkt, 0)
740 * Message sequence number is always 0 for a
743 || !WPACKET_put_bytes_u16(&wpkt, 0)
745 * We never fragment a HelloVerifyRequest, so fragment
748 || !WPACKET_put_bytes_u24(&wpkt, 0)
750 * Fragment length is the same as message length, but
751 * this *is* the last thing in the message header so we
752 * can just start a sub-packet. No need to come back
753 * later for this one.
755 || !WPACKET_start_sub_packet_u24(&wpkt)
756 /* Create the actual HelloVerifyRequest body */
757 || !dtls_raw_hello_verify_request(&wpkt, cookie, cookielen)
758 /* Close message body */
759 || !WPACKET_close(&wpkt)
760 /* Close record body */
761 || !WPACKET_close(&wpkt)
762 || !WPACKET_get_total_written(&wpkt, &wreclen)
763 || !WPACKET_finish(&wpkt)) {
764 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_INTERNAL_ERROR);
765 WPACKET_cleanup(&wpkt);
771 * Fix up the message len in the message header. Its the same as the
772 * fragment len which has been filled in by WPACKET, so just copy
773 * that. Destination for the message len is after the record header
774 * plus one byte for the message content type. The source is the
775 * last 3 bytes of the message header
777 memcpy(&buf[DTLS1_RT_HEADER_LENGTH + 1],
778 &buf[DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH - 3],
782 s->msg_callback(1, 0, SSL3_RT_HEADER, buf,
783 DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
785 if ((tmpclient = BIO_ADDR_new()) == NULL) {
786 SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE);
791 * This is unnecessary if rbio and wbio are one and the same - but
792 * maybe they're not. We ignore errors here - some BIOs do not
795 if (BIO_dgram_get_peer(rbio, tmpclient) > 0) {
796 (void)BIO_dgram_set_peer(wbio, tmpclient);
798 BIO_ADDR_free(tmpclient);
801 if (BIO_write(wbio, buf, wreclen) < (int)wreclen) {
802 if (BIO_should_retry(wbio)) {
804 * Non-blocking IO...but we're stateless, so we're just
805 * going to drop this packet.
812 if (BIO_flush(wbio) <= 0) {
813 if (BIO_should_retry(wbio)) {
815 * Non-blocking IO...but we're stateless, so we're just
816 * going to drop this packet.
823 } while (next != LISTEN_SUCCESS);
826 * Set expected sequence numbers to continue the handshake.
828 s->d1->handshake_read_seq = 1;
829 s->d1->handshake_write_seq = 1;
830 s->d1->next_handshake_write_seq = 1;
831 DTLS_RECORD_LAYER_set_write_sequence(&s->rlayer, seq);
834 * We are doing cookie exchange, so make sure we set that option in the
837 SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE);
840 * Tell the state machine that we've done the initial hello verify
843 ossl_statem_set_hello_verify_done(s);
846 * Some BIOs may not support this. If we fail we clear the client address
848 if (BIO_dgram_get_peer(rbio, client) <= 0)
849 BIO_ADDR_clear(client);
854 BIO_ADDR_free(tmpclient);
855 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 0, NULL);
857 /* Dump this packet. Ignore return value */
858 BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH);
864 static int dtls1_set_handshake_header(SSL *s, int htype, unsigned long len)
866 dtls1_set_message_header(s, htype, len, 0, len);
867 s->init_num = (int)len + DTLS1_HM_HEADER_LENGTH;
869 /* Buffer the message to handle re-xmits */
871 if (!dtls1_buffer_message(s, 0))
877 static int dtls1_handshake_write(SSL *s)
879 return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
882 #ifndef OPENSSL_NO_HEARTBEATS
884 # define HEARTBEAT_SIZE(payload, padding) ( \
885 1 /* heartbeat type */ + \
886 2 /* heartbeat length */ + \
887 (payload) + (padding))
889 # define HEARTBEAT_SIZE_STD(payload) HEARTBEAT_SIZE(payload, 16)
891 int dtls1_process_heartbeat(SSL *s, unsigned char *p, unsigned int length)
894 unsigned short hbtype;
895 unsigned int payload;
896 unsigned int padding = 16; /* Use minimum padding */
899 s->msg_callback(0, s->version, DTLS1_RT_HEARTBEAT,
900 p, length, s, s->msg_callback_arg);
902 /* Read type and payload length */
903 if (HEARTBEAT_SIZE_STD(0) > length)
904 return 0; /* silently discard */
905 if (length > SSL3_RT_MAX_PLAIN_LENGTH)
906 return 0; /* silently discard per RFC 6520 sec. 4 */
910 if (HEARTBEAT_SIZE_STD(payload) > length)
911 return 0; /* silently discard per RFC 6520 sec. 4 */
914 if (hbtype == TLS1_HB_REQUEST) {
915 unsigned char *buffer, *bp;
916 unsigned int write_length = HEARTBEAT_SIZE(payload, padding);
919 if (write_length > SSL3_RT_MAX_PLAIN_LENGTH)
922 /* Allocate memory for the response. */
923 buffer = OPENSSL_malloc(write_length);
928 /* Enter response type, length and copy payload */
929 *bp++ = TLS1_HB_RESPONSE;
931 memcpy(bp, pl, payload);
934 if (RAND_bytes(bp, padding) <= 0) {
935 OPENSSL_free(buffer);
939 r = dtls1_write_bytes(s, DTLS1_RT_HEARTBEAT, buffer, write_length);
941 if (r >= 0 && s->msg_callback)
942 s->msg_callback(1, s->version, DTLS1_RT_HEARTBEAT,
943 buffer, write_length, s, s->msg_callback_arg);
945 OPENSSL_free(buffer);
949 } else if (hbtype == TLS1_HB_RESPONSE) {
953 * We only send sequence numbers (2 bytes unsigned int), and 16
954 * random bytes, so we just try to read the sequence number
958 if (payload == 18 && seq == s->tlsext_hb_seq) {
961 s->tlsext_hb_pending = 0;
968 int dtls1_heartbeat(SSL *s)
970 unsigned char *buf, *p;
972 unsigned int payload = 18; /* Sequence number + random bytes */
973 unsigned int padding = 16; /* Use minimum padding */
976 /* Only send if peer supports and accepts HB requests... */
977 if (!(s->tlsext_heartbeat & SSL_DTLSEXT_HB_ENABLED) ||
978 s->tlsext_heartbeat & SSL_DTLSEXT_HB_DONT_SEND_REQUESTS) {
979 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
983 /* ...and there is none in flight yet... */
984 if (s->tlsext_hb_pending) {
985 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
989 /* ...and no handshake in progress. */
990 if (SSL_in_init(s) || ossl_statem_get_in_handshake(s)) {
991 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
996 * Create HeartBeat message, we just use a sequence number
997 * as payload to distinguish different messages and add
1000 size = HEARTBEAT_SIZE(payload, padding);
1001 buf = OPENSSL_malloc(size);
1003 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_MALLOC_FAILURE);
1008 *p++ = TLS1_HB_REQUEST;
1009 /* Payload length (18 bytes here) */
1011 /* Sequence number */
1012 s2n(s->tlsext_hb_seq, p);
1013 /* 16 random bytes */
1014 if (RAND_bytes(p, 16) <= 0) {
1015 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
1019 /* Random padding */
1020 if (RAND_bytes(p, padding) <= 0) {
1021 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
1025 ret = dtls1_write_bytes(s, DTLS1_RT_HEARTBEAT, buf, size);
1027 if (s->msg_callback)
1028 s->msg_callback(1, s->version, DTLS1_RT_HEARTBEAT,
1029 buf, size, s, s->msg_callback_arg);
1031 dtls1_start_timer(s);
1032 s->tlsext_hb_pending = 1;
1042 int dtls1_shutdown(SSL *s)
1045 #ifndef OPENSSL_NO_SCTP
1048 wbio = SSL_get_wbio(s);
1049 if (wbio != NULL && BIO_dgram_is_sctp(wbio) &&
1050 !(s->shutdown & SSL_SENT_SHUTDOWN)) {
1051 ret = BIO_dgram_sctp_wait_for_dry(wbio);
1056 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
1060 ret = ssl3_shutdown(s);
1061 #ifndef OPENSSL_NO_SCTP
1062 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
1067 int dtls1_query_mtu(SSL *s)
1069 if (s->d1->link_mtu) {
1071 s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
1072 s->d1->link_mtu = 0;
1075 /* AHA! Figure out the MTU, and stick to the right size */
1076 if (s->d1->mtu < dtls1_min_mtu(s)) {
1077 if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
1079 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
1082 * I've seen the kernel return bogus numbers when it doesn't know
1083 * (initial write), so just make sure we have a reasonable number
1085 if (s->d1->mtu < dtls1_min_mtu(s)) {
1086 /* Set to min mtu */
1087 s->d1->mtu = dtls1_min_mtu(s);
1088 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
1097 static unsigned int dtls1_link_min_mtu(void)
1099 return (g_probable_mtu[(sizeof(g_probable_mtu) /
1100 sizeof(g_probable_mtu[0])) - 1]);
1103 unsigned int dtls1_min_mtu(SSL *s)
1105 return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));