Path: blob/main/crypto/openssl/ssl/statem/statem_dtls.c
108036 views
/*1* Copyright 2005-2025 The OpenSSL Project Authors. All Rights Reserved.2*3* Licensed under the Apache License 2.0 (the "License"). You may not use4* this file except in compliance with the License. You can obtain a copy5* in the file LICENSE in the source distribution or at6* https://www.openssl.org/source/license.html7*/89#include <assert.h>10#include <limits.h>11#include <string.h>12#include <stdio.h>13#include "../ssl_local.h"14#include "statem_local.h"15#include "internal/cryptlib.h"16#include "internal/ssl_unwrap.h"17#include <openssl/buffer.h>1819#define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)2021#define RSMBLY_BITMASK_MARK(bitmask, start, end) \22{ \23if ((end) - (start) <= 8) { \24long ii; \25for (ii = (start); ii < (end); ii++) \26bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \27} else { \28long ii; \29bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \30for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) \31bitmask[ii] = 0xff; \32bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \33} \34}3536#define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) \37{ \38long ii; \39is_complete = 1; \40if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) \41is_complete = 0; \42if (is_complete) \43for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0; ii--) \44if (bitmask[ii] != 0xff) { \45is_complete = 0; \46break; \47} \48}4950static const unsigned char bitmask_start_values[] = {510xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x8052};53static const unsigned char bitmask_end_values[] = {540xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f55};5657static void dtls1_fix_message_header(SSL_CONNECTION *s, size_t frag_off,58size_t frag_len);59static unsigned char *dtls1_write_message_header(SSL_CONNECTION *s,60unsigned char *p);61static void dtls1_set_message_header_int(SSL_CONNECTION *s, unsigned char mt,62size_t len,63unsigned short seq_num,64size_t frag_off,65size_t frag_len);66static int dtls_get_reassembled_message(SSL_CONNECTION *s, int *errtype,67size_t *len);6869static hm_fragment *dtls1_hm_fragment_new(size_t frag_len, int reassembly)70{71hm_fragment *frag = NULL;72unsigned char *buf = NULL;73unsigned char *bitmask = NULL;7475if ((frag = OPENSSL_zalloc(sizeof(*frag))) == NULL)76return NULL;7778if (frag_len) {79if ((buf = OPENSSL_malloc(frag_len)) == NULL) {80OPENSSL_free(frag);81return NULL;82}83}8485/* zero length fragment gets zero frag->fragment */86frag->fragment = buf;8788/* Initialize reassembly bitmask if necessary */89if (reassembly) {90bitmask = OPENSSL_zalloc(RSMBLY_BITMASK_SIZE(frag_len));91if (bitmask == NULL) {92OPENSSL_free(buf);93OPENSSL_free(frag);94return NULL;95}96}9798frag->reassembly = bitmask;99100return frag;101}102103void dtls1_hm_fragment_free(hm_fragment *frag)104{105if (!frag)106return;107108OPENSSL_free(frag->fragment);109OPENSSL_free(frag->reassembly);110OPENSSL_free(frag);111}112113/*114* send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or115* SSL3_RT_CHANGE_CIPHER_SPEC)116*/117int dtls1_do_write(SSL_CONNECTION *s, uint8_t type)118{119int ret;120size_t written;121size_t curr_mtu;122int retry = 1;123size_t len, frag_off, overhead, used_len;124SSL *ssl = SSL_CONNECTION_GET_SSL(s);125SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);126uint8_t saved_payload[DTLS1_HM_HEADER_LENGTH];127128if (!dtls1_query_mtu(s))129return -1;130131if (s->d1->mtu < dtls1_min_mtu(s))132/* should have something reasonable now */133return -1;134135if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE) {136if (!ossl_assert(s->init_num == s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH))137return -1;138}139140overhead = s->rlayer.wrlmethod->get_max_record_overhead(s->rlayer.wrl);141142frag_off = 0;143s->rwstate = SSL_NOTHING;144145/* s->init_num shouldn't ever be < 0...but just in case */146while (s->init_num > 0) {147if (type == SSL3_RT_HANDSHAKE && s->init_off != 0) {148/* We must be writing a fragment other than the first one */149150if (frag_off > 0) {151/* This is the first attempt at writing out this fragment */152153if (s->init_off <= DTLS1_HM_HEADER_LENGTH) {154/*155* Each fragment that was already sent must at least have156* contained the message header plus one other byte.157* Therefore |init_off| must have progressed by at least158* |DTLS1_HM_HEADER_LENGTH + 1| bytes. If not something went159* wrong.160*/161return -1;162}163164/*165* Adjust |init_off| and |init_num| to allow room for a new166* message header for this fragment.167*/168s->init_off -= DTLS1_HM_HEADER_LENGTH;169s->init_num += DTLS1_HM_HEADER_LENGTH;170} else {171/*172* We must have been called again after a retry so use the173* fragment offset from our last attempt. We do not need174* to adjust |init_off| and |init_num| as above, because175* that should already have been done before the retry.176*/177frag_off = s->d1->w_msg_hdr.frag_off;178}179}180181used_len = BIO_wpending(s->wbio) + overhead;182if (s->d1->mtu > used_len)183curr_mtu = s->d1->mtu - used_len;184else185curr_mtu = 0;186187if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {188/*189* grr.. we could get an error if MTU picked was wrong190*/191ret = BIO_flush(s->wbio);192if (ret <= 0) {193s->rwstate = SSL_WRITING;194return ret;195}196if (s->d1->mtu > overhead + DTLS1_HM_HEADER_LENGTH) {197curr_mtu = s->d1->mtu - overhead;198} else {199/* Shouldn't happen */200return -1;201}202}203204/*205* We just checked that s->init_num > 0 so this cast should be safe206*/207if (((unsigned int)s->init_num) > curr_mtu)208len = curr_mtu;209else210len = s->init_num;211212if (len > ssl_get_max_send_fragment(s))213len = ssl_get_max_send_fragment(s);214215/*216* XDTLS: this function is too long. split out the CCS part217*/218if (type == SSL3_RT_HANDSHAKE) {219if (len < DTLS1_HM_HEADER_LENGTH) {220/*221* len is so small that we really can't do anything sensible222* so fail223*/224return -1;225}226dtls1_fix_message_header(s, frag_off, len - DTLS1_HM_HEADER_LENGTH);227228/*229* Save the data that will be overwritten by230* dtls1_write_messsage_header so no corruption occurs when using231* a msg callback.232*/233if (s->msg_callback && s->init_off != 0)234memcpy(saved_payload, &s->init_buf->data[s->init_off],235sizeof(saved_payload));236237dtls1_write_message_header(s,238(unsigned char *)&s->init_buf->data[s->init_off]);239}240241ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off], len,242&written);243244if (type == SSL3_RT_HANDSHAKE && s->msg_callback && s->init_off != 0)245memcpy(&s->init_buf->data[s->init_off], saved_payload,246sizeof(saved_payload));247248if (ret <= 0) {249/*250* might need to update MTU here, but we don't know which251* previous packet caused the failure -- so can't really252* retransmit anything. continue as if everything is fine and253* wait for an alert to handle the retransmit254*/255if (retry && BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0) {256if (!(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {257if (!dtls1_query_mtu(s))258return -1;259/* Have one more go */260retry = 0;261} else262return -1;263} else {264return -1;265}266} else {267268/*269* bad if this assert fails, only part of the handshake message270* got sent. but why would this happen?271*/272if (!ossl_assert(len == written))273return -1;274275/*276* We should not exceed the MTU size. If compression is in use277* then the max record overhead calculation is unreliable so we do278* not check in that case. We use assert rather than ossl_assert279* because in a production build, if this assert were ever to fail,280* then the best thing to do is probably carry on regardless.281*/282assert(s->s3.tmp.new_compression != NULL283|| BIO_wpending(s->wbio) <= (int)s->d1->mtu);284285if (type == SSL3_RT_HANDSHAKE && !s->d1->retransmitting) {286/*287* should not be done for 'Hello Request's, but in that case288* we'll ignore the result anyway289*/290unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off];291const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;292size_t xlen;293294if (frag_off == 0 && s->version != DTLS1_BAD_VER) {295/*296* reconstruct message header is if it is being sent in297* single fragment298*/299*p++ = msg_hdr->type;300l2n3(msg_hdr->msg_len, p);301s2n(msg_hdr->seq, p);302l2n3(0, p);303l2n3(msg_hdr->msg_len, p);304p -= DTLS1_HM_HEADER_LENGTH;305xlen = written;306} else {307p += DTLS1_HM_HEADER_LENGTH;308xlen = written - DTLS1_HM_HEADER_LENGTH;309}310311if (!ssl3_finish_mac(s, p, xlen))312return -1;313}314315if (written == s->init_num) {316if (s->msg_callback)317s->msg_callback(1, s->version, type, s->init_buf->data,318s->init_off + s->init_num, ussl,319s->msg_callback_arg);320321s->init_off = 0; /* done writing this message */322s->init_num = 0;323324return 1;325}326s->init_off += written;327s->init_num -= written;328written -= DTLS1_HM_HEADER_LENGTH;329frag_off += written;330331/*332* We save the fragment offset for the next fragment so we have it333* available in case of an IO retry. We don't know the length of the334* next fragment yet so just set that to 0 for now. It will be335* updated again later.336*/337dtls1_fix_message_header(s, frag_off, 0);338}339}340return 0;341}342343int dtls_get_message(SSL_CONNECTION *s, int *mt)344{345struct hm_header_st *msg_hdr;346unsigned char *p;347size_t msg_len;348size_t tmplen;349int errtype;350351msg_hdr = &s->d1->r_msg_hdr;352memset(msg_hdr, 0, sizeof(*msg_hdr));353354again:355if (!dtls_get_reassembled_message(s, &errtype, &tmplen)) {356if (errtype == DTLS1_HM_BAD_FRAGMENT357|| errtype == DTLS1_HM_FRAGMENT_RETRY) {358/* bad fragment received */359goto again;360}361return 0;362}363364*mt = s->s3.tmp.message_type;365366p = (unsigned char *)s->init_buf->data;367368if (*mt == SSL3_MT_CHANGE_CIPHER_SPEC) {369if (s->msg_callback) {370s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,371p, 1, SSL_CONNECTION_GET_USER_SSL(s),372s->msg_callback_arg);373}374/*375* This isn't a real handshake message so skip the processing below.376*/377return 1;378}379380msg_len = msg_hdr->msg_len;381382/* reconstruct message header */383*(p++) = msg_hdr->type;384l2n3(msg_len, p);385s2n(msg_hdr->seq, p);386l2n3(0, p);387l2n3(msg_len, p);388389memset(msg_hdr, 0, sizeof(*msg_hdr));390391s->d1->handshake_read_seq++;392393s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;394395return 1;396}397398/*399* Actually we already have the message body - but this is an opportunity for400* DTLS to do any further processing it wants at the same point that TLS would401* be asked for the message body.402*/403int dtls_get_message_body(SSL_CONNECTION *s, size_t *len)404{405unsigned char *msg = (unsigned char *)s->init_buf->data;406size_t msg_len = s->init_num + DTLS1_HM_HEADER_LENGTH;407408if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {409/* Nothing to be done */410goto end;411}412/*413* If receiving Finished, record MAC of prior handshake messages for414* Finished verification.415*/416if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {417/* SSLfatal() already called */418return 0;419}420421if (s->version == DTLS1_BAD_VER) {422msg += DTLS1_HM_HEADER_LENGTH;423msg_len -= DTLS1_HM_HEADER_LENGTH;424}425426if (!ssl3_finish_mac(s, msg, msg_len))427return 0;428429if (s->msg_callback)430s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,431s->init_buf->data, s->init_num + DTLS1_HM_HEADER_LENGTH,432SSL_CONNECTION_GET_USER_SSL(s), s->msg_callback_arg);433434end:435*len = s->init_num;436return 1;437}438439/*440* dtls1_max_handshake_message_len returns the maximum number of bytes441* permitted in a DTLS handshake message for |s|. The minimum is 16KB, but442* may be greater if the maximum certificate list size requires it.443*/444static size_t dtls1_max_handshake_message_len(const SSL_CONNECTION *s)445{446size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;447if (max_len < s->max_cert_list)448return s->max_cert_list;449return max_len;450}451452static int dtls1_preprocess_fragment(SSL_CONNECTION *s,453struct hm_header_st *msg_hdr)454{455size_t frag_off, frag_len, msg_len;456457msg_len = msg_hdr->msg_len;458frag_off = msg_hdr->frag_off;459frag_len = msg_hdr->frag_len;460461/* sanity checking */462if ((frag_off + frag_len) > msg_len463|| msg_len > dtls1_max_handshake_message_len(s)) {464SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);465return 0;466}467468if (s->d1->r_msg_hdr.frag_off == 0) { /* first fragment */469/*470* msg_len is limited to 2^24, but is effectively checked against471* dtls_max_handshake_message_len(s) above472*/473if (!BUF_MEM_grow_clean(s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH)) {474SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);475return 0;476}477478s->s3.tmp.message_size = msg_len;479s->d1->r_msg_hdr.msg_len = msg_len;480s->s3.tmp.message_type = msg_hdr->type;481s->d1->r_msg_hdr.type = msg_hdr->type;482s->d1->r_msg_hdr.seq = msg_hdr->seq;483} else if (msg_len != s->d1->r_msg_hdr.msg_len) {484/*485* They must be playing with us! BTW, failure to enforce upper limit486* would open possibility for buffer overrun.487*/488SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);489return 0;490}491492return 1;493}494495/*496* Returns 1 if there is a buffered fragment available, 0 if not, or -1 on a497* fatal error.498*/499static int dtls1_retrieve_buffered_fragment(SSL_CONNECTION *s, size_t *len)500{501/*-502* (0) check whether the desired fragment is available503* if so:504* (1) copy over the fragment to s->init_buf->data[]505* (2) update s->init_num506*/507pitem *item;508piterator iter;509hm_fragment *frag;510int ret;511int chretran = 0;512513iter = pqueue_iterator(s->d1->buffered_messages);514do {515item = pqueue_next(&iter);516if (item == NULL)517return 0;518519frag = (hm_fragment *)item->data;520521if (frag->msg_header.seq < s->d1->handshake_read_seq) {522pitem *next;523hm_fragment *nextfrag;524525if (!s->server526|| frag->msg_header.seq != 0527|| s->d1->handshake_read_seq != 1528|| s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {529/*530* This is a stale message that has been buffered so clear it.531* It is safe to pop this message from the queue even though532* we have an active iterator533*/534pqueue_pop(s->d1->buffered_messages);535dtls1_hm_fragment_free(frag);536pitem_free(item);537item = NULL;538frag = NULL;539} else {540/*541* We have fragments for a ClientHello without a cookie,542* even though we have sent a HelloVerifyRequest. It is possible543* that the HelloVerifyRequest got lost and this is a544* retransmission of the original ClientHello545*/546next = pqueue_next(&iter);547if (next != NULL) {548nextfrag = (hm_fragment *)next->data;549if (nextfrag->msg_header.seq == s->d1->handshake_read_seq) {550/*551* We have fragments for both a ClientHello without552* cookie and one with. Ditch the one without.553*/554pqueue_pop(s->d1->buffered_messages);555dtls1_hm_fragment_free(frag);556pitem_free(item);557item = next;558frag = nextfrag;559} else {560chretran = 1;561}562} else {563chretran = 1;564}565}566}567} while (item == NULL);568569/* Don't return if reassembly still in progress */570if (frag->reassembly != NULL)571return 0;572573if (s->d1->handshake_read_seq == frag->msg_header.seq || chretran) {574size_t frag_len = frag->msg_header.frag_len;575pqueue_pop(s->d1->buffered_messages);576577/* Calls SSLfatal() as required */578ret = dtls1_preprocess_fragment(s, &frag->msg_header);579580if (ret && frag->msg_header.frag_len > 0) {581unsigned char *p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;582memcpy(&p[frag->msg_header.frag_off], frag->fragment,583frag->msg_header.frag_len);584}585586dtls1_hm_fragment_free(frag);587pitem_free(item);588589if (ret) {590if (chretran) {591/*592* We got a new ClientHello with a message sequence of 0.593* Reset the read/write sequences back to the beginning.594* We process it like this is the first time we've seen a595* ClientHello from the client.596*/597s->d1->handshake_read_seq = 0;598s->d1->next_handshake_write_seq = 0;599}600*len = frag_len;601return 1;602}603604/* Fatal error */605s->init_num = 0;606return -1;607} else {608return 0;609}610}611612static int dtls1_reassemble_fragment(SSL_CONNECTION *s,613const struct hm_header_st *msg_hdr)614{615hm_fragment *frag = NULL;616pitem *item = NULL;617int i = -1, is_complete;618unsigned char seq64be[8];619size_t frag_len = msg_hdr->frag_len;620size_t readbytes;621SSL *ssl = SSL_CONNECTION_GET_SSL(s);622623if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len || msg_hdr->msg_len > dtls1_max_handshake_message_len(s))624goto err;625626if (frag_len == 0) {627return DTLS1_HM_FRAGMENT_RETRY;628}629630/* Try to find item in queue */631memset(seq64be, 0, sizeof(seq64be));632seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);633seq64be[7] = (unsigned char)msg_hdr->seq;634item = pqueue_find(s->d1->buffered_messages, seq64be);635636if (item == NULL) {637frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);638if (frag == NULL)639goto err;640memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));641frag->msg_header.frag_len = frag->msg_header.msg_len;642frag->msg_header.frag_off = 0;643} else {644frag = (hm_fragment *)item->data;645if (frag->msg_header.msg_len != msg_hdr->msg_len) {646item = NULL;647frag = NULL;648goto err;649}650}651652/*653* If message is already reassembled, this must be a retransmit and can654* be dropped. In this case item != NULL and so frag does not need to be655* freed.656*/657if (frag->reassembly == NULL) {658unsigned char devnull[256];659660while (frag_len) {661i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,662devnull,663frag_len > sizeof(devnull) ? sizeof(devnull) : frag_len, 0, &readbytes);664if (i <= 0)665goto err;666frag_len -= readbytes;667}668return DTLS1_HM_FRAGMENT_RETRY;669}670671/* read the body of the fragment (header has already been read */672i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,673frag->fragment + msg_hdr->frag_off,674frag_len, 0, &readbytes);675if (i <= 0 || readbytes != frag_len)676i = -1;677if (i <= 0)678goto err;679680RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,681(long)(msg_hdr->frag_off + frag_len));682683if (!ossl_assert(msg_hdr->msg_len > 0))684goto err;685RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,686is_complete);687688if (is_complete) {689OPENSSL_free(frag->reassembly);690frag->reassembly = NULL;691}692693if (item == NULL) {694item = pitem_new(seq64be, frag);695if (item == NULL) {696i = -1;697goto err;698}699700item = pqueue_insert(s->d1->buffered_messages, item);701/*702* pqueue_insert fails iff a duplicate item is inserted. However,703* |item| cannot be a duplicate. If it were, |pqueue_find|, above,704* would have returned it and control would never have reached this705* branch.706*/707if (!ossl_assert(item != NULL))708goto err;709}710711return DTLS1_HM_FRAGMENT_RETRY;712713err:714if (item == NULL)715dtls1_hm_fragment_free(frag);716return -1;717}718719static int dtls1_process_out_of_seq_message(SSL_CONNECTION *s,720const struct hm_header_st *msg_hdr)721{722int i = -1;723hm_fragment *frag = NULL;724pitem *item = NULL;725unsigned char seq64be[8];726size_t frag_len = msg_hdr->frag_len;727size_t readbytes;728SSL *ssl = SSL_CONNECTION_GET_SSL(s);729730if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)731goto err;732733/* Try to find item in queue, to prevent duplicate entries */734memset(seq64be, 0, sizeof(seq64be));735seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);736seq64be[7] = (unsigned char)msg_hdr->seq;737item = pqueue_find(s->d1->buffered_messages, seq64be);738739/*740* If we already have an entry and this one is a fragment, don't discard741* it and rather try to reassemble it.742*/743if (item != NULL && frag_len != msg_hdr->msg_len)744item = NULL;745746/*747* Discard the message if sequence number was already there, is too far748* in the future, already in the queue or if we received a FINISHED749* before the SERVER_HELLO, which then must be a stale retransmit.750*/751if (msg_hdr->seq <= s->d1->handshake_read_seq || msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL || (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED)) {752unsigned char devnull[256];753754while (frag_len) {755i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,756devnull,757frag_len > sizeof(devnull) ? sizeof(devnull) : frag_len, 0, &readbytes);758if (i <= 0)759goto err;760frag_len -= readbytes;761}762} else {763if (frag_len != msg_hdr->msg_len) {764return dtls1_reassemble_fragment(s, msg_hdr);765}766767if (frag_len > dtls1_max_handshake_message_len(s))768goto err;769770frag = dtls1_hm_fragment_new(frag_len, 0);771if (frag == NULL)772goto err;773774memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));775776if (frag_len) {777/*778* read the body of the fragment (header has already been read779*/780i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,781frag->fragment, frag_len, 0,782&readbytes);783if (i <= 0 || readbytes != frag_len)784i = -1;785if (i <= 0)786goto err;787}788789item = pitem_new(seq64be, frag);790if (item == NULL)791goto err;792793item = pqueue_insert(s->d1->buffered_messages, item);794/*795* pqueue_insert fails iff a duplicate item is inserted. However,796* |item| cannot be a duplicate. If it were, |pqueue_find|, above,797* would have returned it. Then, either |frag_len| !=798* |msg_hdr->msg_len| in which case |item| is set to NULL and it will799* have been processed with |dtls1_reassemble_fragment|, above, or800* the record will have been discarded.801*/802if (!ossl_assert(item != NULL))803goto err;804}805806return DTLS1_HM_FRAGMENT_RETRY;807808err:809if (item == NULL)810dtls1_hm_fragment_free(frag);811return 0;812}813814static int dtls_get_reassembled_message(SSL_CONNECTION *s, int *errtype,815size_t *len)816{817size_t mlen, frag_off, frag_len;818int i, ret;819uint8_t recvd_type;820struct hm_header_st msg_hdr;821size_t readbytes;822SSL *ssl = SSL_CONNECTION_GET_SSL(s);823SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);824int chretran = 0;825unsigned char *p;826827*errtype = 0;828829p = (unsigned char *)s->init_buf->data;830831redo:832/* see if we have the required fragment already */833ret = dtls1_retrieve_buffered_fragment(s, &frag_len);834if (ret < 0) {835/* SSLfatal() already called */836return 0;837}838if (ret > 0) {839s->init_num = frag_len;840*len = frag_len;841return 1;842}843844/* read handshake message header */845i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type, p,846DTLS1_HM_HEADER_LENGTH, 0, &readbytes);847if (i <= 0) { /* nbio, or an error */848s->rwstate = SSL_READING;849*len = 0;850return 0;851}852if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {853if (p[0] != SSL3_MT_CCS) {854SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,855SSL_R_BAD_CHANGE_CIPHER_SPEC);856goto f_err;857}858859s->init_num = readbytes - 1;860s->init_msg = s->init_buf->data + 1;861s->s3.tmp.message_type = SSL3_MT_CHANGE_CIPHER_SPEC;862s->s3.tmp.message_size = readbytes - 1;863*len = readbytes - 1;864return 1;865}866867/* Handshake fails if message header is incomplete */868if (readbytes != DTLS1_HM_HEADER_LENGTH) {869SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);870goto f_err;871}872873/* parse the message fragment header */874dtls1_get_message_header(p, &msg_hdr);875876mlen = msg_hdr.msg_len;877frag_off = msg_hdr.frag_off;878frag_len = msg_hdr.frag_len;879880/*881* We must have at least frag_len bytes left in the record to be read.882* Fragments must not span records.883*/884if (frag_len > s->rlayer.tlsrecs[s->rlayer.curr_rec].length) {885SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);886goto f_err;887}888889/*890* if this is a future (or stale) message it gets buffered891* (or dropped)--no further processing at this time892* While listening, we accept seq 1 (ClientHello with cookie)893* although we're still expecting seq 0 (ClientHello)894*/895if (msg_hdr.seq != s->d1->handshake_read_seq) {896if (!s->server897|| msg_hdr.seq != 0898|| s->d1->handshake_read_seq != 1899|| p[0] != SSL3_MT_CLIENT_HELLO900|| s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {901*errtype = dtls1_process_out_of_seq_message(s, &msg_hdr);902return 0;903}904/*905* We received a ClientHello and sent back a HelloVerifyRequest. We906* now seem to have received a retransmitted initial ClientHello. That907* is allowed (possibly our HelloVerifyRequest got lost).908*/909chretran = 1;910}911912if (frag_len && frag_len < mlen) {913*errtype = dtls1_reassemble_fragment(s, &msg_hdr);914return 0;915}916917if (!s->server918&& s->d1->r_msg_hdr.frag_off == 0919&& s->statem.hand_state != TLS_ST_OK920&& p[0] == SSL3_MT_HELLO_REQUEST) {921/*922* The server may always send 'Hello Request' messages -- we are923* doing a handshake anyway now, so ignore them if their format is924* correct. Does not count for 'Finished' MAC.925*/926if (p[1] == 0 && p[2] == 0 && p[3] == 0) {927if (s->msg_callback)928s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,929p, DTLS1_HM_HEADER_LENGTH, ussl,930s->msg_callback_arg);931932s->init_num = 0;933goto redo;934} else { /* Incorrectly formatted Hello request */935936SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);937goto f_err;938}939}940941if (!dtls1_preprocess_fragment(s, &msg_hdr)) {942/* SSLfatal() already called */943goto f_err;944}945946if (frag_len > 0) {947/* dtls1_preprocess_fragment() above could reallocate init_buf */948p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;949950i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,951&p[frag_off], frag_len, 0, &readbytes);952953/*954* This shouldn't ever fail due to NBIO because we already checked955* that we have enough data in the record956*/957if (i <= 0) {958s->rwstate = SSL_READING;959*len = 0;960return 0;961}962} else {963readbytes = 0;964}965966/*967* XDTLS: an incorrectly formatted fragment should cause the handshake968* to fail969*/970if (readbytes != frag_len) {971SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);972goto f_err;973}974975if (chretran) {976/*977* We got a new ClientHello with a message sequence of 0.978* Reset the read/write sequences back to the beginning.979* We process it like this is the first time we've seen a ClientHello980* from the client.981*/982s->d1->handshake_read_seq = 0;983s->d1->next_handshake_write_seq = 0;984}985986/*987* Note that s->init_num is *not* used as current offset in988* s->init_buf->data, but as a counter summing up fragments' lengths: as989* soon as they sum up to handshake packet length, we assume we have got990* all the fragments.991*/992*len = s->init_num = frag_len;993return 1;994995f_err:996s->init_num = 0;997*len = 0;998return 0;999}10001001/*-1002* for these 2 messages, we need to1003* ssl->session->read_sym_enc assign1004* ssl->session->read_compression assign1005* ssl->session->read_hash assign1006*/1007CON_FUNC_RETURN dtls_construct_change_cipher_spec(SSL_CONNECTION *s,1008WPACKET *pkt)1009{1010if (s->version == DTLS1_BAD_VER) {1011s->d1->next_handshake_write_seq++;10121013if (!WPACKET_put_bytes_u16(pkt, s->d1->handshake_write_seq)) {1014SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1015return CON_FUNC_ERROR;1016}1017}10181019return CON_FUNC_SUCCESS;1020}10211022#ifndef OPENSSL_NO_SCTP1023/*1024* Wait for a dry event. Should only be called at a point in the handshake1025* where we are not expecting any data from the peer except an alert.1026*/1027WORK_STATE dtls_wait_for_dry(SSL_CONNECTION *s)1028{1029int ret, errtype;1030size_t len;1031SSL *ssl = SSL_CONNECTION_GET_SSL(s);10321033/* read app data until dry event */1034ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(ssl));1035if (ret < 0) {1036SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1037return WORK_ERROR;1038}10391040if (ret == 0) {1041/*1042* We're not expecting any more messages from the peer at this point -1043* but we could get an alert. If an alert is waiting then we will never1044* return successfully. Therefore we attempt to read a message. This1045* should never succeed but will process any waiting alerts.1046*/1047if (dtls_get_reassembled_message(s, &errtype, &len)) {1048/* The call succeeded! This should never happen */1049SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);1050return WORK_ERROR;1051}10521053s->s3.in_read_app_data = 2;1054s->rwstate = SSL_READING;1055BIO_clear_retry_flags(SSL_get_rbio(ssl));1056BIO_set_retry_read(SSL_get_rbio(ssl));1057return WORK_MORE_A;1058}1059return WORK_FINISHED_CONTINUE;1060}1061#endif10621063int dtls1_read_failed(SSL_CONNECTION *s, int code)1064{1065SSL *ssl = SSL_CONNECTION_GET_SSL(s);10661067if (code > 0) {1068SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1069return 0;1070}10711072if (!dtls1_is_timer_expired(s) || ossl_statem_in_error(s)) {1073/*1074* not a timeout, none of our business, let higher layers handle1075* this. in fact it's probably an error1076*/1077return code;1078}1079/* done, no need to send a retransmit */1080if (!SSL_in_init(ssl)) {1081BIO_set_flags(SSL_get_rbio(ssl), BIO_FLAGS_READ);1082return code;1083}10841085return dtls1_handle_timeout(s);1086}10871088int dtls1_get_queue_priority(unsigned short seq, int is_ccs)1089{1090/*1091* The index of the retransmission queue actually is the message sequence1092* number, since the queue only contains messages of a single handshake.1093* However, the ChangeCipherSpec has no message sequence number and so1094* using only the sequence will result in the CCS and Finished having the1095* same index. To prevent this, the sequence number is multiplied by 2.1096* In case of a CCS 1 is subtracted. This does not only differ CSS and1097* Finished, it also maintains the order of the index (important for1098* priority queues) and fits in the unsigned short variable.1099*/1100return seq * 2 - is_ccs;1101}11021103int dtls1_retransmit_buffered_messages(SSL_CONNECTION *s)1104{1105pqueue *sent = s->d1->sent_messages;1106piterator iter;1107pitem *item;1108hm_fragment *frag;1109int found = 0;11101111iter = pqueue_iterator(sent);11121113for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {1114frag = (hm_fragment *)item->data;1115if (dtls1_retransmit_message(s, (unsigned short)dtls1_get_queue_priority(frag->msg_header.seq, frag->msg_header.is_ccs), &found) <= 0)1116return -1;1117}11181119return 1;1120}11211122int dtls1_buffer_message(SSL_CONNECTION *s, int is_ccs)1123{1124pitem *item;1125hm_fragment *frag;1126unsigned char seq64be[8];11271128/*1129* this function is called immediately after a message has been1130* serialized1131*/1132if (!ossl_assert(s->init_off == 0))1133return 0;11341135frag = dtls1_hm_fragment_new(s->init_num, 0);1136if (frag == NULL)1137return 0;11381139memcpy(frag->fragment, s->init_buf->data, s->init_num);11401141if (is_ccs) {1142/* For DTLS1_BAD_VER the header length is non-standard */1143if (!ossl_assert(s->d1->w_msg_hdr.msg_len + ((s->version == DTLS1_BAD_VER) ? 3 : DTLS1_CCS_HEADER_LENGTH)1144== (unsigned int)s->init_num)) {1145dtls1_hm_fragment_free(frag);1146return 0;1147}1148} else {1149if (!ossl_assert(s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num)) {1150dtls1_hm_fragment_free(frag);1151return 0;1152}1153}11541155frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;1156frag->msg_header.seq = s->d1->w_msg_hdr.seq;1157frag->msg_header.type = s->d1->w_msg_hdr.type;1158frag->msg_header.frag_off = 0;1159frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;1160frag->msg_header.is_ccs = is_ccs;11611162/* save current state */1163frag->msg_header.saved_retransmit_state.wrlmethod = s->rlayer.wrlmethod;1164frag->msg_header.saved_retransmit_state.wrl = s->rlayer.wrl;11651166memset(seq64be, 0, sizeof(seq64be));1167seq64be[6] = (unsigned char)(dtls1_get_queue_priority(frag->msg_header.seq,1168frag->msg_header.is_ccs)1169>> 8);1170seq64be[7] = (unsigned char)(dtls1_get_queue_priority(frag->msg_header.seq,1171frag->msg_header.is_ccs));11721173item = pitem_new(seq64be, frag);1174if (item == NULL) {1175dtls1_hm_fragment_free(frag);1176return 0;1177}11781179pqueue_insert(s->d1->sent_messages, item);1180return 1;1181}11821183int dtls1_retransmit_message(SSL_CONNECTION *s, unsigned short seq, int *found)1184{1185int ret;1186/* XDTLS: for now assuming that read/writes are blocking */1187pitem *item;1188hm_fragment *frag;1189unsigned long header_length;1190unsigned char seq64be[8];1191struct dtls1_retransmit_state saved_state;11921193/* XDTLS: the requested message ought to be found, otherwise error */1194memset(seq64be, 0, sizeof(seq64be));1195seq64be[6] = (unsigned char)(seq >> 8);1196seq64be[7] = (unsigned char)seq;11971198item = pqueue_find(s->d1->sent_messages, seq64be);1199if (item == NULL) {1200SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);1201*found = 0;1202return 0;1203}12041205*found = 1;1206frag = (hm_fragment *)item->data;12071208if (frag->msg_header.is_ccs)1209header_length = DTLS1_CCS_HEADER_LENGTH;1210else1211header_length = DTLS1_HM_HEADER_LENGTH;12121213memcpy(s->init_buf->data, frag->fragment,1214frag->msg_header.msg_len + header_length);1215s->init_num = frag->msg_header.msg_len + header_length;12161217dtls1_set_message_header_int(s, frag->msg_header.type,1218frag->msg_header.msg_len,1219frag->msg_header.seq, 0,1220frag->msg_header.frag_len);12211222/* save current state */1223saved_state.wrlmethod = s->rlayer.wrlmethod;1224saved_state.wrl = s->rlayer.wrl;12251226s->d1->retransmitting = 1;12271228/* restore state in which the message was originally sent */1229s->rlayer.wrlmethod = frag->msg_header.saved_retransmit_state.wrlmethod;1230s->rlayer.wrl = frag->msg_header.saved_retransmit_state.wrl;12311232/*1233* The old wrl may be still pointing at an old BIO. Update it to what we're1234* using now.1235*/1236s->rlayer.wrlmethod->set1_bio(s->rlayer.wrl, s->wbio);12371238ret = dtls1_do_write(s, frag->msg_header.is_ccs ? SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);12391240/* restore current state */1241s->rlayer.wrlmethod = saved_state.wrlmethod;1242s->rlayer.wrl = saved_state.wrl;12431244s->d1->retransmitting = 0;12451246(void)BIO_flush(s->wbio);1247return ret;1248}12491250void dtls1_set_message_header(SSL_CONNECTION *s,1251unsigned char mt, size_t len,1252size_t frag_off, size_t frag_len)1253{1254if (frag_off == 0) {1255s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;1256s->d1->next_handshake_write_seq++;1257}12581259dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,1260frag_off, frag_len);1261}12621263/* don't actually do the writing, wait till the MTU has been retrieved */1264static void1265dtls1_set_message_header_int(SSL_CONNECTION *s, unsigned char mt,1266size_t len, unsigned short seq_num,1267size_t frag_off, size_t frag_len)1268{1269struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;12701271msg_hdr->type = mt;1272msg_hdr->msg_len = len;1273msg_hdr->seq = seq_num;1274msg_hdr->frag_off = frag_off;1275msg_hdr->frag_len = frag_len;1276}12771278static void1279dtls1_fix_message_header(SSL_CONNECTION *s, size_t frag_off, size_t frag_len)1280{1281struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;12821283msg_hdr->frag_off = frag_off;1284msg_hdr->frag_len = frag_len;1285}12861287static unsigned char *dtls1_write_message_header(SSL_CONNECTION *s,1288unsigned char *p)1289{1290struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;12911292*p++ = msg_hdr->type;1293l2n3(msg_hdr->msg_len, p);12941295s2n(msg_hdr->seq, p);1296l2n3(msg_hdr->frag_off, p);1297l2n3(msg_hdr->frag_len, p);12981299return p;1300}13011302void dtls1_get_message_header(const unsigned char *data, struct hm_header_st *msg_hdr)1303{1304memset(msg_hdr, 0, sizeof(*msg_hdr));1305msg_hdr->type = *(data++);1306n2l3(data, msg_hdr->msg_len);13071308n2s(data, msg_hdr->seq);1309n2l3(data, msg_hdr->frag_off);1310n2l3(data, msg_hdr->frag_len);1311}13121313int dtls1_set_handshake_header(SSL_CONNECTION *s, WPACKET *pkt, int htype)1314{1315unsigned char *header;13161317if (htype == SSL3_MT_CHANGE_CIPHER_SPEC) {1318s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;1319dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,1320s->d1->handshake_write_seq, 0, 0);1321if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS))1322return 0;1323} else {1324dtls1_set_message_header(s, htype, 0, 0, 0);1325/*1326* We allocate space at the start for the message header. This gets1327* filled in later1328*/1329if (!WPACKET_allocate_bytes(pkt, DTLS1_HM_HEADER_LENGTH, &header)1330|| !WPACKET_start_sub_packet(pkt))1331return 0;1332}13331334return 1;1335}13361337int dtls1_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)1338{1339size_t msglen;13401341if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))1342|| !WPACKET_get_length(pkt, &msglen)1343|| msglen > INT_MAX)1344return 0;13451346if (htype != SSL3_MT_CHANGE_CIPHER_SPEC) {1347s->d1->w_msg_hdr.msg_len = msglen - DTLS1_HM_HEADER_LENGTH;1348s->d1->w_msg_hdr.frag_len = msglen - DTLS1_HM_HEADER_LENGTH;1349}1350s->init_num = (int)msglen;1351s->init_off = 0;13521353if (htype != DTLS1_MT_HELLO_VERIFY_REQUEST) {1354/* Buffer the message to handle re-xmits */1355if (!dtls1_buffer_message(s, htype == SSL3_MT_CHANGE_CIPHER_SPEC ? 1 : 0))1356return 0;1357}13581359return 1;1360}136113621363