dtls13.c 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582
  1. /* dtls13.c
  2. *
  3. * Copyright (C) 2006-2022 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #ifdef WOLFSSL_DTLS13
  26. #include <wolfssl/error-ssl.h>
  27. #include <wolfssl/internal.h>
  28. #include <wolfssl/ssl.h>
  29. #include <wolfssl/wolfcrypt/aes.h>
  30. #include <wolfssl/wolfcrypt/error-crypt.h>
  31. #include <wolfssl/wolfcrypt/kdf.h>
  32. #include <wolfssl/wolfcrypt/logging.h>
  33. #include <wolfssl/wolfcrypt/types.h>
  34. #ifdef NO_INLINE
  35. #include <wolfssl/wolfcrypt/misc.h>
  36. #else
  37. #define WOLFSSL_MISC_INCLUDED
  38. #include <wolfcrypt/src/misc.c>
  39. #endif
  40. /**
  41. * enum rnDirection - distinguish between RecordNumber Enc/Dec
  42. * PROTECT: encrypt the Record Number
  43. * DEPROTECT: decrypt the Record Number
  44. */
  45. enum rnDirection {
  46. PROTECT = 0,
  47. DEPROTECT,
  48. };
  49. /**
  50. * struct Dtls13HandshakeHeader: represent DTLS Handshake header
  51. * @msg_type: type of message (client_hello,server_hello,etc)
  52. * @length: length of the message
  53. * @messageSeq: message sequence number (used for reordering and retransmission)
  54. * @fragmentOffset: this is the offset of the data in the complete message. For
  55. * an unfragmented message this is always zero
  56. * @fragmentLength: length of this fragment (if not fragmented @fragmentLength
  57. * is always equal to @length)
  58. */
  59. typedef struct Dtls13HandshakeHeader {
  60. byte msg_type;
  61. byte length[3];
  62. byte messageSeq[2];
  63. byte fragmentOffset[3];
  64. byte fragmentLength[3];
  65. } Dtls13HandshakeHeader;
  66. /**
  67. * struct Dtls13Recordplaintextheader: represent header of unprotected DTLSv1.3
  68. * record
  69. * @contentType: content type of the record (handshake, applicationData, etc)
  70. * @legacyversionrecord: legacy version field
  71. * @epoch: epoch number (lower 16 bits)
  72. * @sequenceNumber: sequence number (lower 16 bits)
  73. * @length: length of the record
  74. */
  75. typedef struct Dtls13RecordPlaintextHeader {
  76. byte contentType;
  77. ProtocolVersion legacyVersionRecord;
  78. byte epoch[2];
  79. byte sequenceNumber[6];
  80. byte length[2];
  81. } Dtls13RecordPlaintextHeader;
  82. /* size of the len field in the unified header */
  83. #define DTLS13_LEN_SIZE 2
  84. /* size of the mask used to encrypt/decrypt Record Number */
  85. #define DTLS13_RN_MASK_SIZE 16
  86. /* size of the flags in the unified header */
  87. #define DTLS13_HDR_FLAGS_SIZE 1
  88. /* size of the sequence number wher SEQ_LEN_BIT is present */
  89. #define DTLS13_SEQ_16_LEN 2
  90. /* size of the sequence number wher SEQ_LEN_BIT is not present */
  91. #define DTLS13_SEQ_8_LEN 1
  92. /* fixed bits mask to detect unified header */
  93. #define DTLS13_FIXED_BITS_MASK (0x111 << 5)
  94. /* fixed bits value to detect unified header */
  95. #define DTLS13_FIXED_BITS (0x1 << 5)
  96. /* ConnectionID present bit in the unified header flags */
  97. #define DTLS13_CID_BIT (0x1 << 4)
  98. /* Sequence number is 16 bits if this bit is into unified header flags */
  99. #define DTLS13_SEQ_LEN_BIT (0x1 << 3)
  100. /* Length field is present if this bit is into unified header flags */
  101. #define DTLS13_LEN_BIT (0x1 << 2)
  102. /* For now, the size of the outgoing DTLSv1.3 record header is fixed to 5 bytes
  103. (8 bit header flags + 16bit record number + 16 bit length). In the future, we
  104. can dynamically choose to remove the length from the header to save
  105. space. Also it will need to account for client connection ID when
  106. supported. */
  107. #define DTLS13_UNIFIED_HEADER_SIZE 5
  108. #define DTLS13_MIN_CIPHERTEXT 16
  109. #define DTLS13_MIN_RTX_INTERVAL 1
  110. WOLFSSL_METHOD* wolfDTLSv1_3_client_method_ex(void* heap)
  111. {
  112. WOLFSSL_METHOD* method;
  113. WOLFSSL_ENTER("DTLSv1_3_client_method_ex");
  114. method = (WOLFSSL_METHOD*)XMALLOC(sizeof(WOLFSSL_METHOD), heap,
  115. DYNAMIC_TYPE_METHOD);
  116. if (method)
  117. InitSSL_Method(method, MakeDTLSv1_3());
  118. return method;
  119. }
  120. WOLFSSL_METHOD* wolfDTLSv1_3_server_method_ex(void* heap)
  121. {
  122. WOLFSSL_METHOD* method;
  123. WOLFSSL_ENTER("DTLSv1_3_server_method_ex");
  124. method = (WOLFSSL_METHOD*)XMALLOC(sizeof(WOLFSSL_METHOD), heap,
  125. DYNAMIC_TYPE_METHOD);
  126. if (method) {
  127. InitSSL_Method(method, MakeDTLSv1_3());
  128. method->side = WOLFSSL_SERVER_END;
  129. }
  130. return method;
  131. }
  132. WOLFSSL_METHOD* wolfDTLSv1_3_client_method(void)
  133. {
  134. return wolfDTLSv1_3_client_method_ex(NULL);
  135. }
  136. WOLFSSL_METHOD* wolfDTLSv1_3_server_method(void)
  137. {
  138. return wolfDTLSv1_3_server_method_ex(NULL);
  139. }
  140. int Dtls13RlAddPlaintextHeader(WOLFSSL* ssl, byte* out,
  141. enum ContentType content_type, word16 length)
  142. {
  143. Dtls13RecordPlaintextHeader* hdr;
  144. word32 seq[2];
  145. int ret;
  146. hdr = (Dtls13RecordPlaintextHeader*)out;
  147. hdr->contentType = content_type;
  148. hdr->legacyVersionRecord.major = DTLS_MAJOR;
  149. hdr->legacyVersionRecord.minor = DTLSv1_2_MINOR;
  150. ret = Dtls13GetSeq(ssl, CUR_ORDER, seq, 1);
  151. if (ret != 0)
  152. return ret;
  153. /* seq[0] combines the epoch and 16 MSB of sequence number. We write on the
  154. epoch field and will overflow to the first two bytes of the sequence
  155. number */
  156. c32toa(seq[0], hdr->epoch);
  157. c32toa(seq[1], &hdr->sequenceNumber[2]);
  158. c16toa(length, hdr->length);
  159. return 0;
  160. }
  161. static int Dtls13HandshakeAddHeaderFrag(WOLFSSL* ssl, byte* output,
  162. enum HandShakeType msg_type, word32 frag_offset, word32 frag_length,
  163. word32 msg_length)
  164. {
  165. Dtls13HandshakeHeader* hdr;
  166. hdr = (Dtls13HandshakeHeader*)output;
  167. hdr->msg_type = msg_type;
  168. c32to24((word32)msg_length, hdr->length);
  169. c16toa(ssl->keys.dtls_handshake_number, hdr->messageSeq);
  170. c32to24(frag_offset, hdr->fragmentOffset);
  171. c32to24(frag_length, hdr->fragmentLength);
  172. return 0;
  173. }
  174. static byte Dtls13TypeIsEncrypted(enum HandShakeType hs_type)
  175. {
  176. int ret = 0;
  177. switch (hs_type) {
  178. case hello_request:
  179. case hello_verify_request:
  180. case client_hello:
  181. case hello_retry_request:
  182. case server_hello:
  183. break;
  184. case encrypted_extensions:
  185. case session_ticket:
  186. case end_of_early_data:
  187. case certificate:
  188. case server_key_exchange:
  189. case certificate_request:
  190. case server_hello_done:
  191. case certificate_verify:
  192. case client_key_exchange:
  193. case finished:
  194. case certificate_status:
  195. case key_update:
  196. case change_cipher_hs:
  197. case message_hash:
  198. case no_shake:
  199. ret = 1;
  200. }
  201. return ret;
  202. }
  203. static int Dtls13GetRnMask(WOLFSSL* ssl, const byte* ciphertext, byte* mask,
  204. enum rnDirection dir)
  205. {
  206. RecordNumberCiphers* c;
  207. int ret;
  208. if (dir == PROTECT)
  209. c = &ssl->dtlsRecordNumberEncrypt;
  210. else
  211. c = &ssl->dtlsRecordNumberDecrypt;
  212. #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM)
  213. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm ||
  214. ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm) {
  215. if (c->aes == NULL)
  216. return BAD_STATE_E;
  217. return wc_AesEncryptDirect(c->aes, mask, ciphertext);
  218. }
  219. #endif /* HAVE_AESGCM || HAVE_AESCCM */
  220. #ifdef HAVE_CHACHA
  221. if (ssl->specs.bulk_cipher_algorithm == wolfssl_chacha) {
  222. word32 counter;
  223. if (c->chacha == NULL)
  224. return BAD_STATE_E;
  225. /* assuming CIPHER[0..3] should be interpreted as little endian 32-bits
  226. integer. The draft rfc isn't really clear on that. See sec 4.2.3 of
  227. the draft. See also Section 2.3 of the Chacha RFC. */
  228. XMEMCPY(&counter, ciphertext, sizeof(counter));
  229. #ifdef BIG_ENDIAN
  230. counter = ByteReverseWord32(counter);
  231. #endif /* BIG_ENDIAN */
  232. ret = wc_Chacha_SetIV(c->chacha, &ciphertext[4], counter);
  233. if (ret != 0)
  234. return ret;
  235. XMEMSET(mask, 0, DTLS13_RN_MASK_SIZE);
  236. return wc_Chacha_Process(c->chacha, mask, mask, DTLS13_RN_MASK_SIZE);
  237. }
  238. #endif /* HAVE_CHACHA */
  239. return NOT_COMPILED_IN;
  240. }
  241. static int Dtls13EncryptDecryptRecordNumber(WOLFSSL* ssl, byte* seq,
  242. int SeqLength, const byte* ciphertext, enum rnDirection dir)
  243. {
  244. byte mask[DTLS13_RN_MASK_SIZE];
  245. int ret;
  246. ret = Dtls13GetRnMask(ssl, ciphertext, mask, dir);
  247. if (ret != 0)
  248. return ret;
  249. xorbuf(seq, mask, SeqLength);
  250. return 0;
  251. }
  252. static byte Dtls13RtxMsgNeedsAck(WOLFSSL* ssl, enum HandShakeType hs)
  253. {
  254. #ifndef NO_WOLFSSL_SERVER
  255. /* we send an ACK when processing the finished message. In this case either
  256. we already sent an ACK for client's Certificate/CertificateVerify or they
  257. are in our list of seen records and will be included in the ACK
  258. message */
  259. if (ssl->options.side == WOLFSSL_SERVER_END && (hs == finished))
  260. return 1;
  261. #else
  262. (void)ssl;
  263. #endif /* NO_WOLFSSL_SERVER */
  264. if (hs == session_ticket || hs == key_update)
  265. return 1;
  266. return 0;
  267. }
  268. static void Dtls13MsgWasProcessed(WOLFSSL* ssl, enum HandShakeType hs)
  269. {
  270. ssl->keys.dtls_expected_peer_handshake_number++;
  271. /* we need to send ACKs on the last message of a flight that needs explicit
  272. acknowledgment */
  273. ssl->dtls13Rtx.sendAcks = Dtls13RtxMsgNeedsAck(ssl, hs);
  274. }
  275. int Dtls13ProcessBufferedMessages(WOLFSSL* ssl)
  276. {
  277. DtlsMsg* msg = ssl->dtls_rx_msg_list;
  278. word32 idx = 0;
  279. int ret = 0;
  280. WOLFSSL_ENTER("Dtls13ProcessBufferedMessages()");
  281. while (msg != NULL) {
  282. idx = 0;
  283. /* message not in order */
  284. if (ssl->keys.dtls_expected_peer_handshake_number != msg->seq)
  285. break;
  286. /* message not complete */
  287. if (msg->fragSz != msg->sz)
  288. break;
  289. ret = DoTls13HandShakeMsgType(ssl, msg->msg, &idx, msg->type, msg->sz,
  290. msg->sz);
  291. /* processing certificate_request triggers a connect. The error came
  292. * from there, the message can be considered processed successfully */
  293. if (ret == 0 || (msg->type == certificate_request &&
  294. ssl->options.handShakeDone && ret == WC_PENDING_E)) {
  295. Dtls13MsgWasProcessed(ssl, (enum HandShakeType)msg->type);
  296. ssl->dtls_rx_msg_list = msg->next;
  297. DtlsMsgDelete(msg, ssl->heap);
  298. msg = ssl->dtls_rx_msg_list;
  299. ssl->dtls_rx_msg_list_sz--;
  300. }
  301. if (ret != 0)
  302. break;
  303. }
  304. WOLFSSL_LEAVE("dtls13_process_buffered_messages()", ret);
  305. return ret;
  306. }
  307. static int Dtls13NextMessageComplete(WOLFSSL* ssl)
  308. {
  309. return ssl->dtls_rx_msg_list != NULL &&
  310. ssl->dtls_rx_msg_list->fragSz == ssl->dtls_rx_msg_list->sz &&
  311. ssl->dtls_rx_msg_list->seq ==
  312. ssl->keys.dtls_expected_peer_handshake_number;
  313. }
  314. static WC_INLINE int FragIsInOutputBuffer(WOLFSSL* ssl, const byte* frag)
  315. {
  316. const byte* OutputBuffer = ssl->buffers.outputBuffer.buffer;
  317. word32 OutputBufferSize = ssl->buffers.outputBuffer.bufferSize;
  318. return frag >= OutputBuffer && frag < OutputBuffer + OutputBufferSize;
  319. }
  320. static int Dtls13SendFragFromBuffer(WOLFSSL* ssl, byte* output, word16 length)
  321. {
  322. byte* buf;
  323. int ret;
  324. if (FragIsInOutputBuffer(ssl, output))
  325. return BAD_FUNC_ARG;
  326. ret = CheckAvailableSize(ssl, length);
  327. if (ret != 0)
  328. return ret;
  329. buf = ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.length;
  330. XMEMCPY(buf, output, length);
  331. ssl->buffers.outputBuffer.length += length;
  332. return SendBuffered(ssl);
  333. }
  334. static int Dtls13SendNow(WOLFSSL* ssl, enum HandShakeType handshakeType)
  335. {
  336. if (!ssl->options.groupMessages || ssl->dtls13SendingFragments)
  337. return 1;
  338. if (handshakeType == client_hello || handshakeType == hello_retry_request ||
  339. handshakeType == finished || handshakeType == session_ticket ||
  340. handshakeType == session_ticket || handshakeType == key_update ||
  341. (handshakeType == certificate_request &&
  342. ssl->options.handShakeState == HANDSHAKE_DONE))
  343. return 1;
  344. return 0;
  345. }
  346. /* Handshake header DTLS only fields are not inlcuded in the transcript hash */
  347. int Dtls13HashHandshake(WOLFSSL* ssl, const byte* output, word16 length)
  348. {
  349. int ret;
  350. if (length < DTLS_HANDSHAKE_HEADER_SZ)
  351. return BAD_FUNC_ARG;
  352. /* msg_type(1) + length (3) */
  353. ret = HashRaw(ssl, output, OPAQUE32_LEN);
  354. if (ret != 0)
  355. return ret;
  356. output += OPAQUE32_LEN;
  357. length -= OPAQUE32_LEN;
  358. /* message_seq(2) + fragment_offset(3) + fragment_length(3) */
  359. output += OPAQUE64_LEN;
  360. length -= OPAQUE64_LEN;
  361. return HashRaw(ssl, output, length);
  362. }
  363. static int Dtls13SendFragment(WOLFSSL* ssl, byte* output, word16 output_size,
  364. word16 length, enum HandShakeType handshakeType, int hashOutput,
  365. int sendImmediately)
  366. {
  367. word16 recordHeaderLength;
  368. word16 recordLength;
  369. byte isProtected;
  370. int sendLength;
  371. byte* msg;
  372. int ret;
  373. if (output_size < length)
  374. return BUFFER_ERROR;
  375. isProtected = Dtls13TypeIsEncrypted(handshakeType);
  376. recordHeaderLength = Dtls13GetRlHeaderLength(ssl, isProtected);
  377. if (length <= recordHeaderLength)
  378. return BUFFER_ERROR;
  379. recordLength = length - recordHeaderLength;
  380. if (!isProtected) {
  381. ret = Dtls13RlAddPlaintextHeader(ssl, output, handshake, recordLength);
  382. if (ret != 0)
  383. return ret;
  384. }
  385. else {
  386. msg = output + recordHeaderLength;
  387. if (length <= recordHeaderLength)
  388. return BUFFER_ERROR;
  389. if (hashOutput) {
  390. ret = Dtls13HashHandshake(ssl, msg, recordLength);
  391. if (ret != 0)
  392. return ret;
  393. }
  394. sendLength = BuildTls13Message(ssl, output, output_size, msg,
  395. recordLength, handshake, 0, 0, 0);
  396. if (sendLength < 0)
  397. return sendLength;
  398. length = (word16)sendLength;
  399. }
  400. if (!FragIsInOutputBuffer(ssl, output))
  401. return Dtls13SendFragFromBuffer(ssl, output, length);
  402. ssl->buffers.outputBuffer.length += length;
  403. ret = 0;
  404. if (sendImmediately)
  405. ret = SendBuffered(ssl);
  406. return ret;
  407. }
  408. static void Dtls13FreeFragmentsBuffer(WOLFSSL* ssl)
  409. {
  410. XFREE(ssl->dtls13FragmentsBuffer.buffer, ssl->heap,
  411. DYNAMIC_TYPE_TMP_BUFFER);
  412. ssl->dtls13FragmentsBuffer.buffer = NULL;
  413. ssl->dtls13SendingFragments = 0;
  414. ssl->dtls13MessageLength = ssl->dtls13FragOffset = 0;
  415. }
  416. static WC_INLINE void Dtls13FreeRtxBufferRecord(WOLFSSL* ssl,
  417. Dtls13RtxRecord* r)
  418. {
  419. (void)ssl;
  420. XFREE(r->data, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  421. XFREE(r, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  422. }
  423. static Dtls13RtxRecord* Dtls13RtxNewRecord(WOLFSSL* ssl, byte* data,
  424. word16 length, enum HandShakeType handshakeType, w64wrapper seq)
  425. {
  426. w64wrapper epochNumber;
  427. Dtls13RtxRecord* r;
  428. WOLFSSL_ENTER("Dtls13RtxNewRecord");
  429. if (ssl->dtls13EncryptEpoch == NULL)
  430. return NULL;
  431. epochNumber = ssl->dtls13EncryptEpoch->epochNumber;
  432. r = (Dtls13RtxRecord*)XMALLOC(sizeof(*r), ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  433. if (r == NULL)
  434. return NULL;
  435. r->data = (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  436. if (r->data == NULL) {
  437. XFREE(r, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  438. return NULL;
  439. }
  440. XMEMCPY(r->data, data, length);
  441. r->epoch = epochNumber;
  442. r->length = length;
  443. r->next = NULL;
  444. r->handshakeType = handshakeType;
  445. r->seq[0] = seq;
  446. r->rnIdx = 1;
  447. return r;
  448. }
  449. static void Dtls13RtxAddRecord(Dtls13Rtx* fsm, Dtls13RtxRecord* r)
  450. {
  451. WOLFSSL_ENTER("Dtls13RtxAddRecord");
  452. *fsm->rtxRecordTailPtr = r;
  453. fsm->rtxRecordTailPtr = &r->next;
  454. r->next = NULL;
  455. }
  456. static void Dtls13RtxRecordUnlink(WOLFSSL* ssl, Dtls13RtxRecord** prevNext,
  457. Dtls13RtxRecord* r)
  458. {
  459. /* if r was at the tail of the list, update the tail pointer */
  460. if (r->next == NULL)
  461. ssl->dtls13Rtx.rtxRecordTailPtr = prevNext;
  462. /* unlink */
  463. *prevNext = r->next;
  464. }
  465. static void Dtls13RtxFlushBuffered(WOLFSSL* ssl, byte keepNewSessionTicket)
  466. {
  467. Dtls13RtxRecord *r, **prevNext;
  468. WOLFSSL_ENTER("Dtls13RtxFlushBuffered");
  469. prevNext = &ssl->dtls13Rtx.rtxRecords;
  470. r = ssl->dtls13Rtx.rtxRecords;
  471. /* we process the head at the end */
  472. while (r != NULL) {
  473. if (keepNewSessionTicket && r->handshakeType == session_ticket) {
  474. prevNext = &r->next;
  475. r = r->next;
  476. continue;
  477. }
  478. *prevNext = r->next;
  479. Dtls13FreeRtxBufferRecord(ssl, r);
  480. r = *prevNext;
  481. }
  482. ssl->dtls13Rtx.rtxRecordTailPtr = prevNext;
  483. }
  484. static Dtls13RecordNumber* Dtls13NewRecordNumber(WOLFSSL* ssl, w64wrapper epoch,
  485. w64wrapper seq)
  486. {
  487. Dtls13RecordNumber* rn;
  488. rn = (Dtls13RecordNumber*)XMALLOC(sizeof(*rn), ssl->heap,
  489. DYNAMIC_TYPE_DTLS_MSG);
  490. if (rn == NULL)
  491. return NULL;
  492. rn->next = NULL;
  493. rn->epoch = epoch;
  494. rn->seq = seq;
  495. return rn;
  496. }
  497. static int Dtls13RtxAddAck(WOLFSSL* ssl, w64wrapper epoch, w64wrapper seq)
  498. {
  499. Dtls13RecordNumber* rn;
  500. WOLFSSL_ENTER("Dtls13RtxAddAck");
  501. rn = Dtls13NewRecordNumber(ssl, epoch, seq);
  502. if (rn == NULL)
  503. return MEMORY_E;
  504. rn->next = ssl->dtls13Rtx.seenRecords;
  505. ssl->dtls13Rtx.seenRecords = rn;
  506. return 0;
  507. }
  508. static void Dtls13RtxFlushAcks(WOLFSSL* ssl)
  509. {
  510. Dtls13RecordNumber *list, *rn;
  511. (void)ssl;
  512. WOLFSSL_ENTER("Dtls13RtxFlushAcks");
  513. list = ssl->dtls13Rtx.seenRecords;
  514. while (list != NULL) {
  515. rn = list;
  516. list = rn->next;
  517. XFREE(rn, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  518. }
  519. ssl->dtls13Rtx.seenRecords = NULL;
  520. }
  521. static int Dtls13DetectDisruption(WOLFSSL* ssl, word32 fragOffset)
  522. {
  523. /* retransmission. The other peer may have lost our flight or our ACKs. We
  524. don't account this as a disruption */
  525. if (ssl->keys.dtls_peer_handshake_number <
  526. ssl->keys.dtls_expected_peer_handshake_number)
  527. return 0;
  528. /* out of order message */
  529. if (ssl->keys.dtls_peer_handshake_number >
  530. ssl->keys.dtls_expected_peer_handshake_number) {
  531. return 1;
  532. }
  533. /* first fragment of in-order message */
  534. if (fragOffset == 0)
  535. return 0;
  536. /* is not the next fragment in the message (the check is not 100% perfect,
  537. in the worst case, we don't detect the disruption and wait for the other
  538. peer retransmission) */
  539. if (ssl->dtls_rx_msg_list == NULL ||
  540. ssl->dtls_rx_msg_list->fragSz != fragOffset) {
  541. return 1;
  542. }
  543. return 0;
  544. }
  545. static void Dtls13RtxRemoveCurAck(WOLFSSL* ssl)
  546. {
  547. Dtls13RecordNumber *rn, **prevNext;
  548. prevNext = &ssl->dtls13Rtx.seenRecords;
  549. rn = ssl->dtls13Rtx.seenRecords;
  550. while (rn != NULL) {
  551. if (w64Equal(rn->epoch, ssl->keys.curEpoch64) &&
  552. w64Equal(rn->seq, ssl->keys.curSeq)) {
  553. *prevNext = rn->next;
  554. XFREE(rn, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  555. return;
  556. }
  557. prevNext = &rn->next;
  558. rn = rn->next;
  559. }
  560. }
  561. static void Dtls13MaybeSaveClientHello(WOLFSSL* ssl)
  562. {
  563. Dtls13RtxRecord *r, **prev_next;
  564. r = ssl->dtls13Rtx.rtxRecords;
  565. prev_next = &ssl->dtls13Rtx.rtxRecords;
  566. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  567. ssl->options.connectState >= CLIENT_HELLO_SENT &&
  568. ssl->options.connectState <= HELLO_AGAIN_REPLY &&
  569. ssl->options.downgrade && ssl->options.minDowngrade >= DTLSv1_2_MINOR) {
  570. while (r != NULL) {
  571. if (r->handshakeType == client_hello) {
  572. Dtls13RtxRecordUnlink(ssl, prev_next, r);
  573. if (ssl->dtls13ClientHello != NULL)
  574. XFREE(ssl->dtls13ClientHello, ssl->heap,
  575. DYNAMIC_TYPE_DTLS_MSG);
  576. ssl->dtls13ClientHello = r->data;
  577. ssl->dtls13ClientHelloSz = r->length;
  578. r->data = NULL;
  579. Dtls13FreeRtxBufferRecord(ssl, r);
  580. return;
  581. }
  582. prev_next = &r->next;
  583. r = r->next;
  584. }
  585. }
  586. }
  587. static int Dtls13RtxMsgRecvd(WOLFSSL* ssl, enum HandShakeType hs,
  588. word32 fragOffset)
  589. {
  590. WOLFSSL_ENTER("Dtls13RtxMsgRecvd");
  591. if (!ssl->options.handShakeDone &&
  592. ssl->keys.dtls_peer_handshake_number >=
  593. ssl->keys.dtls_expected_peer_handshake_number) {
  594. if (hs == server_hello)
  595. Dtls13MaybeSaveClientHello(ssl);
  596. /* In the handshake, receiving part of the next flight, acknowledge the
  597. sent flight. The only exception is, on the server side, receiving the
  598. last client flight does not ACK any sent new_session_ticket
  599. messages. */
  600. Dtls13RtxFlushBuffered(ssl, 1);
  601. }
  602. if (ssl->keys.dtls_peer_handshake_number <
  603. ssl->keys.dtls_expected_peer_handshake_number) {
  604. /* retransmission detected. */
  605. ssl->dtls13Rtx.retransmit = 1;
  606. /* the other peer may have retransmitted because an ACK for a flight
  607. that needs explicit ACK was lost.*/
  608. if (ssl->dtls13Rtx.seenRecords != NULL)
  609. ssl->dtls13Rtx.sendAcks = (byte)ssl->options.dtls13SendMoreAcks;
  610. }
  611. if (ssl->keys.dtls_peer_handshake_number ==
  612. ssl->keys.dtls_expected_peer_handshake_number &&
  613. ssl->options.handShakeDone && hs == certificate_request) {
  614. /* the current record, containing a post-handshake certificate request,
  615. is implicitly acknowledged by the
  616. certificate/certificate_verify/finished flight we are about to
  617. send. Please note that if the certificate request came out-of-order
  618. and we didn't send an ACK (sendMoreAcks == 0 and the missing
  619. packet(s) arrive before that fast timeout expired), then we will send
  620. both the ACK and the flight. While unnecessary this it's harmless, it
  621. should be rare and simplifies the code. Otherwise, it would be
  622. necessary to track which record number contained a CertificateRequest
  623. with a particular context id */
  624. Dtls13RtxRemoveCurAck(ssl);
  625. }
  626. if (ssl->options.dtls13SendMoreAcks &&
  627. Dtls13DetectDisruption(ssl, fragOffset)) {
  628. WOLFSSL_MSG("Disruption detected");
  629. ssl->dtls13Rtx.sendAcks = 1;
  630. }
  631. return 0;
  632. }
  633. void Dtls13FreeFsmResources(WOLFSSL* ssl)
  634. {
  635. Dtls13RtxFlushAcks(ssl);
  636. Dtls13RtxFlushBuffered(ssl, 0);
  637. }
  638. static int Dtls13SendOneFragmentRtx(WOLFSSL* ssl,
  639. enum HandShakeType handshakeType, word16 outputSize, byte* message,
  640. word32 length, int hashOutput)
  641. {
  642. Dtls13RtxRecord* rtxRecord;
  643. word16 recordHeaderLength;
  644. byte isProtected;
  645. int ret;
  646. isProtected = Dtls13TypeIsEncrypted(handshakeType);
  647. recordHeaderLength = Dtls13GetRlHeaderLength(ssl, isProtected);
  648. rtxRecord = Dtls13RtxNewRecord(ssl, message + recordHeaderLength,
  649. (word16)(length - recordHeaderLength), handshakeType,
  650. ssl->dtls13EncryptEpoch->nextSeqNumber);
  651. if (rtxRecord == NULL)
  652. return MEMORY_E;
  653. ret = Dtls13SendFragment(ssl, message, outputSize, (word16)length,
  654. handshakeType, hashOutput, Dtls13SendNow(ssl, handshakeType));
  655. if (ret == 0 || ret == WANT_WRITE)
  656. Dtls13RtxAddRecord(&ssl->dtls13Rtx, rtxRecord);
  657. else
  658. Dtls13FreeRtxBufferRecord(ssl, rtxRecord);
  659. return ret;
  660. }
  661. static int Dtls13SendFragmentedInternal(WOLFSSL* ssl)
  662. {
  663. int fragLength, rlHeaderLength;
  664. int remainingSize, maxFragment;
  665. int recordLength;
  666. byte isEncrypted;
  667. byte* output;
  668. int ret;
  669. isEncrypted = Dtls13TypeIsEncrypted(
  670. (enum HandShakeType)ssl->dtls13FragHandshakeType);
  671. rlHeaderLength = Dtls13GetRlHeaderLength(ssl, isEncrypted);
  672. maxFragment = wolfSSL_GetMaxFragSize(ssl, MAX_RECORD_SIZE);
  673. remainingSize = ssl->dtls13MessageLength - ssl->dtls13FragOffset;
  674. while (remainingSize > 0) {
  675. fragLength = maxFragment - rlHeaderLength - DTLS_HANDSHAKE_HEADER_SZ;
  676. recordLength = maxFragment;
  677. if (fragLength > remainingSize) {
  678. fragLength = remainingSize;
  679. recordLength =
  680. fragLength + rlHeaderLength + DTLS_HANDSHAKE_HEADER_SZ;
  681. }
  682. ret = CheckAvailableSize(ssl, recordLength + MAX_MSG_EXTRA);
  683. if (ret != 0)
  684. return ret;
  685. output =
  686. ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.length;
  687. ret = Dtls13HandshakeAddHeaderFrag(ssl, output + rlHeaderLength,
  688. (enum HandShakeType)ssl->dtls13FragHandshakeType,
  689. ssl->dtls13FragOffset, fragLength, ssl->dtls13MessageLength);
  690. if (ret != 0) {
  691. Dtls13FreeFragmentsBuffer(ssl);
  692. return ret;
  693. }
  694. XMEMCPY(output + rlHeaderLength + DTLS_HANDSHAKE_HEADER_SZ,
  695. ssl->dtls13FragmentsBuffer.buffer + ssl->dtls13FragOffset,
  696. fragLength);
  697. ret = Dtls13SendOneFragmentRtx(ssl,
  698. (enum HandShakeType)ssl->dtls13FragHandshakeType,
  699. recordLength + MAX_MSG_EXTRA, output, recordLength, 0);
  700. if (ret == WANT_WRITE) {
  701. ssl->dtls13FragOffset += fragLength;
  702. return ret;
  703. }
  704. if (ret != 0) {
  705. Dtls13FreeFragmentsBuffer(ssl);
  706. return ret;
  707. }
  708. ssl->dtls13FragOffset += fragLength;
  709. remainingSize -= fragLength;
  710. }
  711. /* we sent all fragments */
  712. Dtls13FreeFragmentsBuffer(ssl);
  713. return 0;
  714. }
  715. static int Dtls13SendFragmented(WOLFSSL* ssl, byte* message, word16 length,
  716. enum HandShakeType handshake_type, int hash_output)
  717. {
  718. int rlHeaderLength;
  719. byte isEncrypted;
  720. int messageSize;
  721. int ret;
  722. if (ssl->dtls13SendingFragments != 0) {
  723. WOLFSSL_MSG(
  724. "dtls13_send_fragmented() invoked while already sending fragments");
  725. return BAD_STATE_E;
  726. }
  727. isEncrypted = Dtls13TypeIsEncrypted(handshake_type);
  728. rlHeaderLength = Dtls13GetRlHeaderLength(ssl, isEncrypted);
  729. if (length < rlHeaderLength)
  730. return INCOMPLETE_DATA;
  731. /* DTLSv1.3 do not consider fragmentation for hash transcript. Build the
  732. hash now pretending fragmentation will not happen */
  733. if (hash_output) {
  734. ret = Dtls13HashHandshake(ssl, message + rlHeaderLength,
  735. length - rlHeaderLength);
  736. if (ret != 0)
  737. return ret;
  738. }
  739. messageSize = length - rlHeaderLength - DTLS_HANDSHAKE_HEADER_SZ;
  740. ssl->dtls13FragmentsBuffer.buffer =
  741. (byte*)XMALLOC(messageSize, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  742. if (ssl->dtls13FragmentsBuffer.buffer == NULL)
  743. return MEMORY_E;
  744. XMEMCPY(ssl->dtls13FragmentsBuffer.buffer,
  745. message + rlHeaderLength + DTLS_HANDSHAKE_HEADER_SZ, messageSize);
  746. ssl->dtls13MessageLength = messageSize;
  747. ssl->dtls13FragHandshakeType = handshake_type;
  748. ssl->dtls13SendingFragments = 1;
  749. return Dtls13SendFragmentedInternal(ssl);
  750. }
  751. static WC_INLINE word8 Dtls13GetEpochBits(w64wrapper epoch)
  752. {
  753. return w64GetLow32(epoch) & EE_MASK;
  754. }
  755. #ifdef WOLFSSL_DTLS_CID
  756. static byte Dtls13GetCidTxSize(WOLFSSL* ssl)
  757. {
  758. unsigned int cidSz;
  759. int ret;
  760. ret = wolfSSL_dtls_cid_get_tx_size(ssl, &cidSz);
  761. if (ret != WOLFSSL_SUCCESS)
  762. return 0;
  763. return (byte)cidSz;
  764. }
  765. static byte Dtls13GetCidRxSize(WOLFSSL* ssl)
  766. {
  767. unsigned int cidSz;
  768. int ret;
  769. ret = wolfSSL_dtls_cid_get_rx_size(ssl, &cidSz);
  770. if (ret != WOLFSSL_SUCCESS)
  771. return 0;
  772. return (byte)cidSz;
  773. }
  774. static int Dtls13AddCID(WOLFSSL* ssl, byte* flags, byte* out, word16* idx)
  775. {
  776. byte cidSize;
  777. int ret;
  778. if (!wolfSSL_dtls_cid_is_enabled(ssl))
  779. return 0;
  780. cidSize = Dtls13GetCidTxSize(ssl);
  781. /* no cid */
  782. if (cidSize == 0)
  783. return 0;
  784. *flags |= DTLS13_CID_BIT;
  785. /* we know that we have at least cidSize of space */
  786. ret = wolfSSL_dtls_cid_get_tx(ssl, out + *idx, cidSize);
  787. if (ret != WOLFSSL_SUCCESS)
  788. return ret;
  789. *idx += cidSize;
  790. return 0;
  791. }
  792. static int Dtls13UnifiedHeaderParseCID(WOLFSSL* ssl, byte flags,
  793. const byte* input, word16 inputSize, word16* idx)
  794. {
  795. unsigned int _cidSz;
  796. int ret;
  797. if (flags & DTLS13_CID_BIT) {
  798. if (!wolfSSL_dtls_cid_is_enabled(ssl)) {
  799. WOLFSSL_MSG("CID while no negotiated CID, ignoring");
  800. return DTLS_CID_ERROR;
  801. }
  802. if (!DtlsCIDCheck(ssl, input + *idx, inputSize - *idx)) {
  803. WOLFSSL_MSG("Not matching or wrong CID, ignoring");
  804. return DTLS_CID_ERROR;
  805. }
  806. ret = wolfSSL_dtls_cid_get_rx_size(ssl, &_cidSz);
  807. if (ret != WOLFSSL_SUCCESS)
  808. return ret;
  809. *idx += _cidSz;
  810. return 0;
  811. }
  812. /* CID not present */
  813. if (wolfSSL_dtls_cid_is_enabled(ssl)) {
  814. ret = wolfSSL_dtls_cid_get_rx_size(ssl, &_cidSz);
  815. if (ret != WOLFSSL_SUCCESS)
  816. return ret;
  817. if (_cidSz != 0) {
  818. WOLFSSL_MSG("expecting CID, ignoring");
  819. return DTLS_CID_ERROR;
  820. }
  821. }
  822. return 0;
  823. }
  824. #else
  825. #define Dtls13AddCID(a, b, c, d) 0
  826. #define Dtls13GetCidRxSize(a) 0
  827. #define Dtls13GetCidTxSize(a) 0
  828. #define Dtls13UnifiedHeaderParseCID(a, b, c, d, e) 0
  829. #endif /* WOLFSSL_DTLS_CID */
  830. /**
  831. * dtls13RlAddCiphertextHeader() - add record layer header in the buffer
  832. * @ssl: ssl object
  833. * @out: output buffer where to put the header
  834. * @length: length of the record
  835. */
  836. int Dtls13RlAddCiphertextHeader(WOLFSSL* ssl, byte* out, word16 length)
  837. {
  838. word16 seqNumber, idx;
  839. byte* flags;
  840. int ret;
  841. if (out == NULL)
  842. return BAD_FUNC_ARG;
  843. if (ssl->dtls13EncryptEpoch == NULL)
  844. return BAD_STATE_E;
  845. flags = out;
  846. /* header fixed bits */
  847. *flags = DTLS13_FIXED_BITS;
  848. /* epoch bits */
  849. *flags |= Dtls13GetEpochBits(ssl->dtls13EncryptEpoch->epochNumber);
  850. idx = DTLS13_HDR_FLAGS_SIZE;
  851. ret = Dtls13AddCID(ssl, flags, out, &idx);
  852. if (ret != 0)
  853. return ret;
  854. /* include 16-bit seq */
  855. *flags |= DTLS13_SEQ_LEN_BIT;
  856. /* include 16-bit length */
  857. *flags |= DTLS13_LEN_BIT;
  858. seqNumber = (word16)w64GetLow32(ssl->dtls13EncryptEpoch->nextSeqNumber);
  859. c16toa(seqNumber, out + idx);
  860. idx += OPAQUE16_LEN;
  861. c16toa(length, out + idx);
  862. return 0;
  863. }
  864. /**
  865. * Dtls13HandshakeAddHeader() - add handshake layer header
  866. * @ssl: ssl object
  867. * @output: output buffer
  868. * @msg_type: handshake type
  869. * @length: length of the message
  870. */
  871. int Dtls13HandshakeAddHeader(WOLFSSL* ssl, byte* output,
  872. enum HandShakeType msg_type, word32 length)
  873. {
  874. Dtls13HandshakeHeader* hdr;
  875. hdr = (Dtls13HandshakeHeader*)output;
  876. hdr->msg_type = msg_type;
  877. c32to24((word32)length, hdr->length);
  878. c16toa(ssl->keys.dtls_handshake_number, hdr->messageSeq);
  879. /* send unfragmented first */
  880. c32to24(0, hdr->fragmentOffset);
  881. c32to24((word32)length, hdr->fragmentLength);
  882. return 0;
  883. }
  884. /**
  885. * Dtls13EncryptRecordNumber() - encrypt record number in the header
  886. * @ssl: ssl object
  887. * @hdr: header
  888. *
  889. * Further info rfc draft 43 sec 4.2.3
  890. */
  891. int Dtls13EncryptRecordNumber(WOLFSSL* ssl, byte* hdr, word16 recordLength)
  892. {
  893. int seqLength;
  894. int hdrLength;
  895. int cidSz;
  896. if (ssl == NULL || hdr == NULL)
  897. return BAD_FUNC_ARG;
  898. /* we need at least a 16 bytes of ciphertext to encrypt record number see
  899. 4.2.3*/
  900. if (recordLength < Dtls13GetRlHeaderLength(ssl, 1) + DTLS13_MIN_CIPHERTEXT)
  901. return BUFFER_ERROR;
  902. seqLength = (*hdr & DTLS13_LEN_BIT) ? DTLS13_SEQ_16_LEN : DTLS13_SEQ_8_LEN;
  903. cidSz = Dtls13GetCidTxSize(ssl);
  904. /* header flags + seq number + CID size*/
  905. hdrLength = OPAQUE8_LEN + seqLength + cidSz;
  906. /* length present */
  907. if (*hdr & DTLS13_LEN_BIT)
  908. hdrLength += DTLS13_LEN_SIZE;
  909. return Dtls13EncryptDecryptRecordNumber(ssl,
  910. /* seq number offset */
  911. hdr + OPAQUE8_LEN + cidSz,
  912. /* seq size */
  913. seqLength,
  914. /* cipher text */
  915. hdr + hdrLength, PROTECT);
  916. }
  917. /**
  918. * Dtls13GetRlHeaderLength() - get record layer header length
  919. * @ssl: ssl object
  920. * @isEncrypted: whether the record will be protected or not
  921. *
  922. * returns the length of the record layer header in bytes.
  923. */
  924. word16 Dtls13GetRlHeaderLength(WOLFSSL* ssl, byte isEncrypted)
  925. {
  926. (void)ssl;
  927. if (!isEncrypted)
  928. return DTLS_RECORD_HEADER_SZ;
  929. return DTLS13_UNIFIED_HEADER_SIZE + Dtls13GetCidTxSize(ssl);
  930. }
  931. /**
  932. * Dtls13GetHeadersLength() - return length of record + handshake header
  933. * @ssl: ssl oject
  934. * @type: type of handshake in the message
  935. */
  936. word16 Dtls13GetHeadersLength(WOLFSSL* ssl, enum HandShakeType type)
  937. {
  938. byte isEncrypted;
  939. isEncrypted = Dtls13TypeIsEncrypted(type);
  940. return Dtls13GetRlHeaderLength(ssl, isEncrypted) + DTLS_HANDSHAKE_HEADER_SZ;
  941. }
  942. /**
  943. * Dtls13IsUnifiedHeader() - check if header is a DTLS unified header
  944. * @header_flags: first byte of the header
  945. *
  946. * Further info: dtls v1.3 draft43 section 4
  947. */
  948. int Dtls13IsUnifiedHeader(byte hdrFirstByte)
  949. {
  950. if (hdrFirstByte == alert || hdrFirstByte == handshake ||
  951. hdrFirstByte == ack)
  952. return 0;
  953. return ((hdrFirstByte & DTLS13_FIXED_BITS_MASK) == DTLS13_FIXED_BITS);
  954. }
  955. int Dtls13ReconstructSeqNumber(WOLFSSL* ssl, Dtls13UnifiedHdrInfo* hdrInfo,
  956. w64wrapper* out)
  957. {
  958. word16 expectedLowBits;
  959. word16 seqLowBits;
  960. w64wrapper temp;
  961. word32 out32;
  962. word32 shift;
  963. word16 mask;
  964. byte wrap = 0;
  965. if (hdrInfo->seqHiPresent) {
  966. seqLowBits = (hdrInfo->seqHi << 8) | hdrInfo->seqLo;
  967. mask = 0xffff;
  968. shift = (1 << 16);
  969. }
  970. else {
  971. seqLowBits = hdrInfo->seqLo;
  972. mask = 0xff;
  973. shift = (1 << 8);
  974. }
  975. /* *out = (nextPeerSeqNumber & ~mask) | seqLowbits */
  976. out32 = w64GetLow32(ssl->dtls13DecryptEpoch->nextPeerSeqNumber);
  977. expectedLowBits = out32 & mask;
  978. out32 = (out32 & ~mask) | seqLowBits;
  979. *out = ssl->dtls13DecryptEpoch->nextPeerSeqNumber;
  980. w64SetLow32(out, out32);
  981. if (seqLowBits >= expectedLowBits) {
  982. if ((word32)(seqLowBits - expectedLowBits) > shift / 2) {
  983. temp = w64Sub32(*out, shift, &wrap);
  984. if (!wrap)
  985. *out = temp;
  986. return 0;
  987. }
  988. }
  989. else {
  990. /* seqLowbits < expectedLowBits */
  991. if ((word32)(expectedLowBits - seqLowBits) > shift / 2) {
  992. temp = w64Add32(*out, shift, &wrap);
  993. if (!wrap)
  994. *out = temp;
  995. return 0;
  996. }
  997. }
  998. return 0;
  999. }
  1000. int Dtls13ReconstructEpochNumber(WOLFSSL* ssl, byte epochBits,
  1001. w64wrapper* epoch)
  1002. {
  1003. w64wrapper _epoch;
  1004. Dtls13Epoch* e;
  1005. byte found;
  1006. int i;
  1007. if (Dtls13GetEpochBits(ssl->dtls13PeerEpoch) == epochBits) {
  1008. *epoch = ssl->dtls13PeerEpoch;
  1009. return 0;
  1010. }
  1011. w64Zero(&_epoch);
  1012. for (i = 0; i < DTLS13_EPOCH_SIZE; ++i) {
  1013. e = &ssl->dtls13Epochs[i];
  1014. if (!e->isValid)
  1015. continue;
  1016. if (Dtls13GetEpochBits(e->epochNumber) != epochBits)
  1017. continue;
  1018. if (w64GT(e->epochNumber, _epoch)) {
  1019. found = 1;
  1020. _epoch = e->epochNumber;
  1021. }
  1022. }
  1023. if (found) {
  1024. *epoch = _epoch;
  1025. return 0;
  1026. }
  1027. return SEQUENCE_ERROR;
  1028. }
  1029. int Dtls13GetUnifiedHeaderSize(WOLFSSL* ssl, const byte input, word16* size)
  1030. {
  1031. (void)ssl;
  1032. if (size == NULL)
  1033. return BAD_FUNC_ARG;
  1034. /* flags (1) + CID + seq 8bit (1) */
  1035. *size = OPAQUE8_LEN + Dtls13GetCidRxSize(ssl) + OPAQUE8_LEN;
  1036. if (input & DTLS13_SEQ_LEN_BIT)
  1037. *size += OPAQUE8_LEN;
  1038. if (input & DTLS13_LEN_BIT)
  1039. *size += OPAQUE16_LEN;
  1040. return 0;
  1041. }
  1042. /**
  1043. * Dtls13ParseUnifiedRecordLayer() - parse DTLS unified header
  1044. * @ssl: [in] ssl object
  1045. * @input: [in] buffer where the header is
  1046. * @inputSize: [in] size of the input buffer
  1047. * @hdrInfo: [out] header info struct
  1048. *
  1049. * It parse the header and put the relevant information inside @hdrInfo. Further
  1050. * info: draft43 section 4
  1051. *
  1052. * return 0 on success
  1053. */
  1054. int Dtls13ParseUnifiedRecordLayer(WOLFSSL* ssl, const byte* input,
  1055. word16 inputSize, Dtls13UnifiedHdrInfo* hdrInfo)
  1056. {
  1057. byte seqLen, hasLength;
  1058. byte* seqNum;
  1059. byte flags;
  1060. word16 idx;
  1061. int ret;
  1062. if (input == NULL || inputSize < DTLS13_HDR_FLAGS_SIZE)
  1063. return BAD_FUNC_ARG;
  1064. flags = *input;
  1065. idx = DTLS13_HDR_FLAGS_SIZE;
  1066. ret = Dtls13UnifiedHeaderParseCID(ssl, flags, input, inputSize, &idx);
  1067. if (ret != 0)
  1068. return ret;
  1069. seqNum = (byte*)input + idx;
  1070. seqLen = (flags & DTLS13_SEQ_LEN_BIT) != 0 ? DTLS13_SEQ_16_LEN
  1071. : DTLS13_SEQ_8_LEN;
  1072. hasLength = flags & DTLS13_LEN_BIT;
  1073. hdrInfo->epochBits = flags & EE_MASK;
  1074. idx += seqLen;
  1075. if (inputSize < idx)
  1076. return BUFFER_ERROR;
  1077. if (hasLength) {
  1078. if (inputSize < idx + DTLS13_LEN_SIZE)
  1079. return BUFFER_ERROR;
  1080. ato16(input + idx, &hdrInfo->recordLength);
  1081. idx += DTLS13_LEN_SIZE;
  1082. }
  1083. else {
  1084. /* length not present. The size of the record is the all the remaining
  1085. data received with this datagram */
  1086. hdrInfo->recordLength = inputSize - idx;
  1087. }
  1088. /* minimum size for a dtls1.3 packet is 16 bytes (to have enough ciphertext
  1089. to create record number xor mask). (draft 43 - Sec 4.2.3) */
  1090. if (hdrInfo->recordLength < DTLS13_RN_MASK_SIZE)
  1091. return LENGTH_ERROR;
  1092. ret = Dtls13EncryptDecryptRecordNumber(ssl, seqNum, seqLen, input + idx,
  1093. DEPROTECT);
  1094. if (ret != 0)
  1095. return ret;
  1096. if (seqLen == DTLS13_SEQ_16_LEN) {
  1097. hdrInfo->seqHiPresent = 1;
  1098. hdrInfo->seqHi = seqNum[0];
  1099. hdrInfo->seqLo = seqNum[1];
  1100. }
  1101. else {
  1102. hdrInfo->seqHiPresent = 0;
  1103. hdrInfo->seqLo = seqNum[0];
  1104. }
  1105. return 0;
  1106. }
  1107. int Dtls13RecordRecvd(WOLFSSL* ssl)
  1108. {
  1109. int ret;
  1110. if (ssl->curRL.type != handshake)
  1111. return 0;
  1112. if (!ssl->options.dtls13SendMoreAcks)
  1113. ssl->dtls13FastTimeout = 1;
  1114. ret = Dtls13RtxAddAck(ssl, ssl->keys.curEpoch64, ssl->keys.curSeq);
  1115. if (ret != 0)
  1116. WOLFSSL_MSG("can't save ack fragment");
  1117. return ret;
  1118. }
  1119. static void Dtls13RtxMoveToEndOfList(WOLFSSL* ssl, Dtls13RtxRecord** prevNext,
  1120. Dtls13RtxRecord* r)
  1121. {
  1122. /* already at the end */
  1123. if (r->next == NULL)
  1124. return;
  1125. Dtls13RtxRecordUnlink(ssl, prevNext, r);
  1126. /* add to the end */
  1127. Dtls13RtxAddRecord(&ssl->dtls13Rtx, r);
  1128. }
  1129. static int Dtls13RtxSendBuffered(WOLFSSL* ssl)
  1130. {
  1131. word16 headerLength;
  1132. Dtls13RtxRecord *r, **prevNext;
  1133. w64wrapper seq;
  1134. byte* output;
  1135. int isLast;
  1136. int sendSz;
  1137. word32 now;
  1138. int ret;
  1139. WOLFSSL_ENTER("Dtls13RtxSendBuffered");
  1140. now = LowResTimer();
  1141. if (now - ssl->dtls13Rtx.lastRtx < DTLS13_MIN_RTX_INTERVAL) {
  1142. #ifdef WOLFSSL_DEBUG_TLS
  1143. WOLFSSL_MSG("Avoid too fast retransmission");
  1144. #endif /* WOLFSSL_DEBUG_TLS */
  1145. return 0;
  1146. }
  1147. ssl->dtls13Rtx.lastRtx = now;
  1148. r = ssl->dtls13Rtx.rtxRecords;
  1149. prevNext = &ssl->dtls13Rtx.rtxRecords;
  1150. while (r != NULL) {
  1151. isLast = r->next == NULL;
  1152. WOLFSSL_MSG("Dtls13Rtx One Record");
  1153. headerLength = Dtls13GetRlHeaderLength(ssl, !w64IsZero(r->epoch));
  1154. sendSz = r->length + headerLength;
  1155. if (!w64IsZero(r->epoch))
  1156. sendSz += MAX_MSG_EXTRA;
  1157. ret = CheckAvailableSize(ssl, sendSz);
  1158. if (ret != 0)
  1159. return ret;
  1160. output =
  1161. ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.length;
  1162. XMEMCPY(output + headerLength, r->data, r->length);
  1163. if (!w64Equal(ssl->dtls13EncryptEpoch->epochNumber, r->epoch)) {
  1164. ret = Dtls13SetEpochKeys(ssl, r->epoch, ENCRYPT_SIDE_ONLY);
  1165. if (ret != 0)
  1166. return ret;
  1167. }
  1168. seq = ssl->dtls13EncryptEpoch->nextSeqNumber;
  1169. ret = Dtls13SendFragment(ssl, output, sendSz, r->length + headerLength,
  1170. (enum HandShakeType)r->handshakeType, 0,
  1171. isLast || !ssl->options.groupMessages);
  1172. if (ret != 0 && ret != WANT_WRITE)
  1173. return ret;
  1174. if (r->rnIdx >= DTLS13_RETRANS_RN_SIZE)
  1175. r->rnIdx = 0;
  1176. #ifdef WOLFSSL_DEBUG_TLS
  1177. WOLFSSL_MSG_EX("tracking r hs: %d with seq: %ld", r->handshakeType,
  1178. seq);
  1179. #endif /* WOLFSSL_DEBUG_TLS */
  1180. r->seq[r->rnIdx] = seq;
  1181. r->rnIdx++;
  1182. if (ret == WANT_WRITE) {
  1183. /* this fragment will be sent eventually. Move it to the end of the
  1184. list so next time we start with a new one. */
  1185. Dtls13RtxMoveToEndOfList(ssl, prevNext, r);
  1186. return ret;
  1187. }
  1188. prevNext = &r->next;
  1189. r = r->next;
  1190. }
  1191. return 0;
  1192. }
  1193. /**
  1194. * Dtls13HandshakeRecv() - process an handshake message. Deal with
  1195. fragmentation if needed
  1196. * @ssl: [in] ssl object
  1197. * @input: [in] input buffer
  1198. * @size: [in] input buffer size
  1199. * @type: [out] content type
  1200. * @processedSize: [out] amount of byte processed
  1201. *
  1202. * returns 0 on success
  1203. */
  1204. static int _Dtls13HandshakeRecv(WOLFSSL* ssl, byte* input, word32 size,
  1205. word32* processedSize)
  1206. {
  1207. word32 fragOff, fragLength;
  1208. byte isComplete, isFirst;
  1209. byte usingAsyncCrypto;
  1210. word32 messageLength;
  1211. byte handshakeType;
  1212. word32 idx;
  1213. int ret;
  1214. idx = 0;
  1215. ret = GetDtlsHandShakeHeader(ssl, input, &idx, &handshakeType,
  1216. &messageLength, &fragOff, &fragLength, size);
  1217. if (ret != 0)
  1218. return PARSE_ERROR;
  1219. if (idx + fragLength > size) {
  1220. WOLFSSL_ERROR(INCOMPLETE_DATA);
  1221. return INCOMPLETE_DATA;
  1222. }
  1223. if (fragOff + fragLength > messageLength)
  1224. return BUFFER_ERROR;
  1225. if (handshakeType == client_hello &&
  1226. /* Only when receiving an unverified ClientHello */
  1227. ssl->options.serverState < SERVER_HELLO_COMPLETE) {
  1228. /* To be able to operate in stateless mode, we assume the ClientHello
  1229. * is in order and we use its Handshake Message number and Sequence
  1230. * Number for our Tx. */
  1231. ssl->keys.dtls_expected_peer_handshake_number =
  1232. ssl->keys.dtls_handshake_number =
  1233. ssl->keys.dtls_peer_handshake_number;
  1234. ssl->dtls13Epochs[0].nextSeqNumber = ssl->keys.curSeq;
  1235. }
  1236. ret = Dtls13RtxMsgRecvd(ssl, (enum HandShakeType)handshakeType, fragOff);
  1237. if (ret != 0)
  1238. return ret;
  1239. if (ssl->keys.dtls_peer_handshake_number <
  1240. ssl->keys.dtls_expected_peer_handshake_number) {
  1241. #ifdef WOLFSSL_DEBUG_TLS
  1242. WOLFSSL_MSG(
  1243. "DTLS1.3 retransmission detected - discard and schedule a rtx");
  1244. #endif /* WOLFSSL_DEBUG_TLS */
  1245. /* ignore the message */
  1246. *processedSize = idx + fragLength + ssl->keys.padSz;
  1247. return 0;
  1248. }
  1249. isFirst = fragOff == 0;
  1250. isComplete = isFirst && fragLength == messageLength;
  1251. usingAsyncCrypto = ssl->devId != INVALID_DEVID;
  1252. /* store the message if any of the following: (a) incomplete message, (b)
  1253. * out of order message or (c) if using async crypto. In (c) the processing
  1254. * of the message can return WC_PENDING_E, it's easier to handle this error
  1255. * if the message is stored in the buffer.
  1256. */
  1257. if (!isComplete ||
  1258. ssl->keys.dtls_peer_handshake_number >
  1259. ssl->keys.dtls_expected_peer_handshake_number ||
  1260. usingAsyncCrypto) {
  1261. DtlsMsgStore(ssl, w64GetLow32(ssl->keys.curEpoch64),
  1262. ssl->keys.dtls_peer_handshake_number,
  1263. input + DTLS_HANDSHAKE_HEADER_SZ, messageLength, handshakeType,
  1264. fragOff, fragLength, ssl->heap);
  1265. *processedSize = idx + fragLength + ssl->keys.padSz;
  1266. if (Dtls13NextMessageComplete(ssl))
  1267. return Dtls13ProcessBufferedMessages(ssl);
  1268. return 0;
  1269. }
  1270. ret = DoTls13HandShakeMsgType(ssl, input, &idx, handshakeType,
  1271. messageLength, size);
  1272. if (ret != 0)
  1273. return ret;
  1274. Dtls13MsgWasProcessed(ssl, (enum HandShakeType)handshakeType);
  1275. *processedSize = idx;
  1276. /* check if we have buffered some message */
  1277. if (Dtls13NextMessageComplete(ssl))
  1278. return Dtls13ProcessBufferedMessages(ssl);
  1279. return 0;
  1280. }
  1281. int Dtls13HandshakeRecv(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  1282. word32 totalSz)
  1283. {
  1284. word32 maxSize, processedSize = 0;
  1285. byte* message;
  1286. int ret;
  1287. message = input + *inOutIdx;
  1288. maxSize = totalSz - *inOutIdx;
  1289. ret = _Dtls13HandshakeRecv(ssl, message, maxSize, &processedSize);
  1290. *inOutIdx += processedSize;
  1291. return ret;
  1292. }
  1293. /**
  1294. * Dtls13FragmentsContinue() - keep sending pending fragments
  1295. * @ssl: ssl object
  1296. */
  1297. int Dtls13FragmentsContinue(WOLFSSL* ssl)
  1298. {
  1299. int ret;
  1300. ret = Dtls13SendFragmentedInternal(ssl);
  1301. if (ret == 0)
  1302. ssl->keys.dtls_handshake_number++;
  1303. return ret;
  1304. }
  1305. /**
  1306. * Dtls13AddHeaders() - setup handshake header
  1307. * @output: output buffer at the start of the record
  1308. * @length: length of the full message, included headers
  1309. * @hsType: handshake type
  1310. * @ssl: ssl object
  1311. *
  1312. * This function add the handshake headers and leaves space for the record
  1313. * layer. The real record layer will be added in dtls_send() for unprotected
  1314. * messages and in BuildTls13message() for protected messages.
  1315. *
  1316. * returns 0 on success, -1 otherwise
  1317. */
  1318. int Dtls13AddHeaders(byte* output, word32 length, enum HandShakeType hsType,
  1319. WOLFSSL* ssl)
  1320. {
  1321. word16 handshakeOffset;
  1322. int isEncrypted;
  1323. isEncrypted = Dtls13TypeIsEncrypted(hsType);
  1324. handshakeOffset = Dtls13GetRlHeaderLength(ssl, isEncrypted);
  1325. /* The record header is placed by either Dtls13HandshakeSend() or
  1326. BuildTls13Message() */
  1327. return Dtls13HandshakeAddHeader(ssl, output + handshakeOffset, hsType,
  1328. length);
  1329. }
  1330. /**
  1331. * Dtls13HandshakeSend() - send an handshake message. Fragment if necessary.
  1332. *
  1333. * @ssl: ssl object
  1334. * @message: message where the buffer is in. Handshake header already in place.
  1335. * @output_size: size of the @message buffer
  1336. * @length: length of the message including headers
  1337. * @handshakeType: handshake type of the message
  1338. * @hashOutput: if true add the message to the transcript hash
  1339. *
  1340. */
  1341. int Dtls13HandshakeSend(WOLFSSL* ssl, byte* message, word16 outputSize,
  1342. word16 length, enum HandShakeType handshakeType, int hashOutput)
  1343. {
  1344. int maxFrag;
  1345. int maxLen;
  1346. int ret;
  1347. if (ssl->dtls13EncryptEpoch == NULL)
  1348. return BAD_STATE_E;
  1349. /* if we are here, the message is built */
  1350. ssl->options.buildingMsg = 0;
  1351. if (!ssl->options.handShakeDone) {
  1352. /* during the handshake, if we are sending a new flight, we can flush
  1353. our ACK list. When sending client
  1354. [certificate/certificate_verify]/finished flight, we may flush an ACK
  1355. for a newSessionticket message, sent by the server just after sending
  1356. its finished message. This should not be a problem. That message
  1357. arrived out-of-order (before the server finished) so likely an ACK
  1358. was already sent. In the worst case we will ACK the server
  1359. retranmission*/
  1360. if (handshakeType == certificate || handshakeType == finished ||
  1361. handshakeType == server_hello || handshakeType == client_hello)
  1362. Dtls13RtxFlushAcks(ssl);
  1363. }
  1364. /* we want to send always with the highest epoch */
  1365. if (!w64Equal(ssl->dtls13EncryptEpoch->epochNumber, ssl->dtls13Epoch)) {
  1366. ret = Dtls13SetEpochKeys(ssl, ssl->dtls13Epoch, ENCRYPT_SIDE_ONLY);
  1367. if (ret != 0)
  1368. return ret;
  1369. }
  1370. maxFrag = wolfSSL_GetMaxFragSize(ssl, MAX_RECORD_SIZE);
  1371. maxLen = length;
  1372. if (handshakeType == key_update)
  1373. ssl->dtls13WaitKeyUpdateAck = 1;
  1374. if (maxLen < maxFrag) {
  1375. ret = Dtls13SendOneFragmentRtx(ssl, handshakeType, outputSize, message,
  1376. length, hashOutput);
  1377. if (ret == 0 || ret == WANT_WRITE)
  1378. ssl->keys.dtls_handshake_number++;
  1379. }
  1380. else {
  1381. ret = Dtls13SendFragmented(ssl, message, length, handshakeType,
  1382. hashOutput);
  1383. if (ret == 0)
  1384. ssl->keys.dtls_handshake_number++;
  1385. }
  1386. return ret;
  1387. }
  1388. #define SN_LABEL_SZ 2
  1389. static const byte snLabel[SN_LABEL_SZ + 1] = "sn";
  1390. /**
  1391. * Dtls13DeriveSnKeys() - derive the key used to encrypt the record number
  1392. * @ssl: ssl object
  1393. * @provision: which side (CLIENT or SERVER) to provision
  1394. */
  1395. int Dtls13DeriveSnKeys(WOLFSSL* ssl, int provision)
  1396. {
  1397. byte key_dig[MAX_PRF_DIG];
  1398. int ret = 0;
  1399. if (provision & PROVISION_CLIENT) {
  1400. WOLFSSL_MSG("Derive SN Client key");
  1401. ret = Tls13DeriveKey(ssl, key_dig, ssl->specs.key_size,
  1402. ssl->clientSecret, snLabel, SN_LABEL_SZ, ssl->specs.mac_algorithm,
  1403. 0);
  1404. if (ret != 0)
  1405. goto end;
  1406. XMEMCPY(ssl->keys.client_sn_key, key_dig, ssl->specs.key_size);
  1407. }
  1408. if (provision & PROVISION_SERVER) {
  1409. WOLFSSL_MSG("Derive SN Server key");
  1410. ret = Tls13DeriveKey(ssl, key_dig, ssl->specs.key_size,
  1411. ssl->serverSecret, snLabel, SN_LABEL_SZ, ssl->specs.mac_algorithm,
  1412. 0);
  1413. if (ret != 0)
  1414. goto end;
  1415. XMEMCPY(ssl->keys.server_sn_key, key_dig, ssl->specs.key_size);
  1416. }
  1417. end:
  1418. ForceZero(key_dig, MAX_PRF_DIG);
  1419. return ret;
  1420. }
  1421. static int Dtls13InitAesCipher(WOLFSSL* ssl, RecordNumberCiphers* cipher,
  1422. const byte* key, word16 keySize)
  1423. {
  1424. int ret;
  1425. if (cipher->aes == NULL) {
  1426. cipher->aes =
  1427. (Aes*)XMALLOC(sizeof(Aes), ssl->heap, DYNAMIC_TYPE_CIPHER);
  1428. if (cipher->aes == NULL)
  1429. return MEMORY_E;
  1430. }
  1431. else {
  1432. wc_AesFree(cipher->aes);
  1433. }
  1434. XMEMSET(cipher->aes, 0, sizeof(*cipher->aes));
  1435. ret = wc_AesInit(cipher->aes, ssl->heap, INVALID_DEVID);
  1436. if (ret != 0)
  1437. return ret;
  1438. return wc_AesSetKey(cipher->aes, key, keySize, NULL, AES_ENCRYPTION);
  1439. }
  1440. #ifdef HAVE_CHACHA
  1441. static int Dtls13InitChaChaCipher(RecordNumberCiphers* c, byte* key,
  1442. word16 keySize, void* heap)
  1443. {
  1444. (void)heap;
  1445. if (c->chacha == NULL) {
  1446. c->chacha = (ChaCha*)XMALLOC(sizeof(ChaCha), heap, DYNAMIC_TYPE_CIPHER);
  1447. if (c->chacha == NULL)
  1448. return MEMORY_E;
  1449. }
  1450. return wc_Chacha_SetKey(c->chacha, key, keySize);
  1451. }
  1452. #endif /* HAVE_CHACHA */
  1453. struct Dtls13Epoch* Dtls13GetEpoch(WOLFSSL* ssl, w64wrapper epochNumber)
  1454. {
  1455. Dtls13Epoch* e;
  1456. int i;
  1457. for (i = 0; i < DTLS13_EPOCH_SIZE; ++i) {
  1458. e = &ssl->dtls13Epochs[i];
  1459. if (w64Equal(e->epochNumber, epochNumber) && e->isValid)
  1460. return e;
  1461. }
  1462. return NULL;
  1463. }
  1464. static void Dtls13EpochCopyKeys(WOLFSSL* ssl, Dtls13Epoch* e, Keys* k, int side)
  1465. {
  1466. byte clientWrite, serverWrite;
  1467. byte enc, dec;
  1468. WOLFSSL_ENTER("Dtls13SetEpochKeys");
  1469. clientWrite = serverWrite = 0;
  1470. enc = dec = 0;
  1471. switch (side) {
  1472. case ENCRYPT_SIDE_ONLY:
  1473. if (ssl->options.side == WOLFSSL_CLIENT_END)
  1474. clientWrite = 1;
  1475. if (ssl->options.side == WOLFSSL_SERVER_END)
  1476. serverWrite = 1;
  1477. enc = 1;
  1478. break;
  1479. case DECRYPT_SIDE_ONLY:
  1480. if (ssl->options.side == WOLFSSL_CLIENT_END)
  1481. serverWrite = 1;
  1482. if (ssl->options.side == WOLFSSL_SERVER_END)
  1483. clientWrite = 1;
  1484. dec = 1;
  1485. break;
  1486. case ENCRYPT_AND_DECRYPT_SIDE:
  1487. clientWrite = serverWrite = 1;
  1488. enc = dec = 1;
  1489. break;
  1490. }
  1491. if (clientWrite) {
  1492. XMEMCPY(e->client_write_key, k->client_write_key,
  1493. sizeof(e->client_write_key));
  1494. XMEMCPY(e->client_write_IV, k->client_write_IV,
  1495. sizeof(e->client_write_IV));
  1496. XMEMCPY(e->client_sn_key, k->client_sn_key, sizeof(e->client_sn_key));
  1497. }
  1498. if (serverWrite) {
  1499. XMEMCPY(e->server_write_key, k->server_write_key,
  1500. sizeof(e->server_write_key));
  1501. XMEMCPY(e->server_write_IV, k->server_write_IV,
  1502. sizeof(e->server_write_IV));
  1503. XMEMCPY(e->server_sn_key, k->server_sn_key, sizeof(e->server_sn_key));
  1504. }
  1505. if (enc)
  1506. XMEMCPY(e->aead_enc_imp_IV, k->aead_enc_imp_IV,
  1507. sizeof(e->aead_enc_imp_IV));
  1508. if (dec)
  1509. XMEMCPY(e->aead_dec_imp_IV, k->aead_dec_imp_IV,
  1510. sizeof(e->aead_dec_imp_IV));
  1511. }
  1512. /* For storing the sequence number we use a word32[2] array here, instead of
  1513. word64. This is to reuse existing code */
  1514. int Dtls13GetSeq(WOLFSSL* ssl, int order, word32* seq, byte increment)
  1515. {
  1516. w64wrapper* nativeSeq;
  1517. if (order == PEER_ORDER) {
  1518. nativeSeq = &ssl->keys.curSeq;
  1519. /* never increment seq number for curent record. In DTLS seq number are
  1520. explicit */
  1521. increment = 0;
  1522. }
  1523. else if (order == CUR_ORDER) {
  1524. if (ssl->dtls13EncryptEpoch == NULL) {
  1525. return BAD_STATE_E;
  1526. }
  1527. nativeSeq = &ssl->dtls13EncryptEpoch->nextSeqNumber;
  1528. }
  1529. else {
  1530. return BAD_FUNC_ARG;
  1531. }
  1532. seq[0] = w64GetHigh32(*nativeSeq);
  1533. seq[1] = w64GetLow32(*nativeSeq);
  1534. #ifdef WOLFSSL_DEBUG_TLS
  1535. WOLFSSL_MSG_EX("Dtls13GetSeq(): using seq: %ld", *nativeSeq);
  1536. #endif /* WOLFSSL_DEBUG_TLS */
  1537. if (increment) {
  1538. w64Increment(nativeSeq);
  1539. /* seq number wrapped up */
  1540. if (w64IsZero(*nativeSeq))
  1541. return BAD_STATE_E;
  1542. }
  1543. return 0;
  1544. }
  1545. static Dtls13Epoch* Dtls13NewEpochSlot(WOLFSSL* ssl)
  1546. {
  1547. Dtls13Epoch *e, *oldest = NULL;
  1548. w64wrapper oldestNumber;
  1549. int i;
  1550. /* FIXME: add max function */
  1551. oldestNumber = w64From32((word32)-1, (word32)-1);
  1552. oldest = NULL;
  1553. for (i = 0; i < DTLS13_EPOCH_SIZE; ++i) {
  1554. e = &ssl->dtls13Epochs[i];
  1555. if (!e->isValid)
  1556. return e;
  1557. if (!w64Equal(e->epochNumber, ssl->dtls13Epoch) &&
  1558. !w64Equal(e->epochNumber, ssl->dtls13PeerEpoch) &&
  1559. w64LT(e->epochNumber, oldestNumber))
  1560. oldest = e;
  1561. }
  1562. if (oldest == NULL)
  1563. return NULL;
  1564. e = oldest;
  1565. #ifdef WOLFSSL_DEBUG_TLS
  1566. WOLFSSL_MSG_EX("Delete epoch: %d", e->epochNumber);
  1567. #endif /* WOLFSSL_DEBUG_TLS */
  1568. XMEMSET(e, 0, sizeof(*e));
  1569. return e;
  1570. }
  1571. int Dtls13NewEpoch(WOLFSSL* ssl, w64wrapper epochNumber, int side)
  1572. {
  1573. Dtls13Epoch* e;
  1574. #ifdef WOLFSSL_DEBUG_TLS
  1575. WOLFSSL_MSG_EX("New epoch: %d", w64GetLow32(epochNumber));
  1576. #endif /* WOLFSSL_DEBUG_TLS */
  1577. e = Dtls13GetEpoch(ssl, epochNumber);
  1578. if (e == NULL) {
  1579. e = Dtls13NewEpochSlot(ssl);
  1580. if (e == NULL)
  1581. return BAD_STATE_E;
  1582. }
  1583. Dtls13EpochCopyKeys(ssl, e, &ssl->keys, side);
  1584. if (!e->isValid) {
  1585. /* fresh epoch, initialize fields */
  1586. e->epochNumber = epochNumber;
  1587. e->isValid = 1;
  1588. e->side = side;
  1589. }
  1590. else if (e->side != side) {
  1591. /* epoch used for the other side already. update side */
  1592. e->side = ENCRYPT_AND_DECRYPT_SIDE;
  1593. }
  1594. return 0;
  1595. }
  1596. int Dtls13SetEpochKeys(WOLFSSL* ssl, w64wrapper epochNumber,
  1597. enum encrypt_side side)
  1598. {
  1599. byte clientWrite, serverWrite;
  1600. Dtls13Epoch* e;
  1601. byte enc, dec;
  1602. WOLFSSL_ENTER("Dtls13SetEpochKeys");
  1603. clientWrite = serverWrite = 0;
  1604. enc = dec = 0;
  1605. switch (side) {
  1606. case ENCRYPT_SIDE_ONLY:
  1607. if (ssl->options.side == WOLFSSL_CLIENT_END)
  1608. clientWrite = 1;
  1609. if (ssl->options.side == WOLFSSL_SERVER_END)
  1610. serverWrite = 1;
  1611. enc = 1;
  1612. break;
  1613. case DECRYPT_SIDE_ONLY:
  1614. if (ssl->options.side == WOLFSSL_CLIENT_END)
  1615. serverWrite = 1;
  1616. if (ssl->options.side == WOLFSSL_SERVER_END)
  1617. clientWrite = 1;
  1618. dec = 1;
  1619. break;
  1620. case ENCRYPT_AND_DECRYPT_SIDE:
  1621. clientWrite = serverWrite = 1;
  1622. enc = dec = 1;
  1623. break;
  1624. }
  1625. e = Dtls13GetEpoch(ssl, epochNumber);
  1626. /* we don't have the requested key */
  1627. if (e == NULL)
  1628. return BAD_STATE_E;
  1629. if (e->side != ENCRYPT_AND_DECRYPT_SIDE && e->side != side)
  1630. return BAD_STATE_E;
  1631. if (enc)
  1632. ssl->dtls13EncryptEpoch = e;
  1633. if (dec)
  1634. ssl->dtls13DecryptEpoch = e;
  1635. /* epoch 0 has no key to copy */
  1636. if (w64IsZero(epochNumber))
  1637. return 0;
  1638. if (clientWrite) {
  1639. XMEMCPY(ssl->keys.client_write_key, e->client_write_key,
  1640. sizeof(ssl->keys.client_write_key));
  1641. XMEMCPY(ssl->keys.client_write_IV, e->client_write_IV,
  1642. sizeof(ssl->keys.client_write_IV));
  1643. XMEMCPY(ssl->keys.client_sn_key, e->client_sn_key,
  1644. sizeof(ssl->keys.client_sn_key));
  1645. }
  1646. if (serverWrite) {
  1647. XMEMCPY(ssl->keys.server_write_key, e->server_write_key,
  1648. sizeof(ssl->keys.server_write_key));
  1649. XMEMCPY(ssl->keys.server_write_IV, e->server_write_IV,
  1650. sizeof(ssl->keys.server_write_IV));
  1651. XMEMCPY(ssl->keys.server_sn_key, e->server_sn_key,
  1652. sizeof(ssl->keys.server_sn_key));
  1653. }
  1654. if (enc)
  1655. XMEMCPY(ssl->keys.aead_enc_imp_IV, e->aead_enc_imp_IV,
  1656. sizeof(ssl->keys.aead_enc_imp_IV));
  1657. if (dec)
  1658. XMEMCPY(ssl->keys.aead_dec_imp_IV, e->aead_dec_imp_IV,
  1659. sizeof(ssl->keys.aead_dec_imp_IV));
  1660. return SetKeysSide(ssl, side);
  1661. }
  1662. int Dtls13SetRecordNumberKeys(WOLFSSL* ssl, enum encrypt_side side)
  1663. {
  1664. RecordNumberCiphers* enc = NULL;
  1665. RecordNumberCiphers* dec = NULL;
  1666. byte *encKey = NULL, *decKey = NULL;
  1667. int ret;
  1668. if (ssl == NULL) {
  1669. return BAD_FUNC_ARG;
  1670. }
  1671. switch (side) {
  1672. case ENCRYPT_SIDE_ONLY:
  1673. enc = &ssl->dtlsRecordNumberEncrypt;
  1674. break;
  1675. case DECRYPT_SIDE_ONLY:
  1676. dec = &ssl->dtlsRecordNumberDecrypt;
  1677. break;
  1678. case ENCRYPT_AND_DECRYPT_SIDE:
  1679. enc = &ssl->dtlsRecordNumberEncrypt;
  1680. dec = &ssl->dtlsRecordNumberDecrypt;
  1681. break;
  1682. }
  1683. if (enc) {
  1684. if (ssl->options.side == WOLFSSL_CLIENT_END)
  1685. encKey = ssl->keys.client_sn_key;
  1686. else
  1687. encKey = ssl->keys.server_sn_key;
  1688. }
  1689. if (dec) {
  1690. if (ssl->options.side == WOLFSSL_CLIENT_END)
  1691. decKey = ssl->keys.server_sn_key;
  1692. else
  1693. decKey = ssl->keys.client_sn_key;
  1694. }
  1695. /* DTLSv1.3 supports only AEAD algorithm. */
  1696. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
  1697. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm ||
  1698. ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm) {
  1699. if (enc) {
  1700. ret = Dtls13InitAesCipher(ssl, enc, encKey, ssl->specs.key_size);
  1701. if (ret != 0)
  1702. return ret;
  1703. #ifdef WOLFSSL_DEBUG_TLS
  1704. WOLFSSL_MSG("Provisioning AES Record Number enc key:");
  1705. WOLFSSL_BUFFER(encKey, ssl->specs.key_size);
  1706. #endif /* WOLFSSL_DEBUG_TLS */
  1707. }
  1708. if (dec) {
  1709. ret = Dtls13InitAesCipher(ssl, dec, decKey, ssl->specs.key_size);
  1710. if (ret != 0)
  1711. return ret;
  1712. #ifdef WOLFSSL_DEBUG_TLS
  1713. WOLFSSL_MSG("Provisioning AES Record Number dec key:");
  1714. WOLFSSL_BUFFER(decKey, ssl->specs.key_size);
  1715. #endif /* WOLFSSL_DEBUG_TLS */
  1716. }
  1717. return 0;
  1718. }
  1719. #endif /* BUILD_AESGCM || HAVE_AESCCM */
  1720. #ifdef HAVE_CHACHA
  1721. if (ssl->specs.bulk_cipher_algorithm == wolfssl_chacha) {
  1722. if (enc) {
  1723. ret = Dtls13InitChaChaCipher(enc, encKey, ssl->specs.key_size,
  1724. ssl->heap);
  1725. if (ret != 0)
  1726. return ret;
  1727. #ifdef WOLFSSL_DEBUG_TLS
  1728. WOLFSSL_MSG("Provisioning CHACHA Record Number enc key:");
  1729. WOLFSSL_BUFFER(encKey, ssl->specs.key_size);
  1730. #endif /* WOLFSSL_DEBUG_TLS */
  1731. }
  1732. if (dec) {
  1733. ret = Dtls13InitChaChaCipher(dec, decKey, ssl->specs.key_size,
  1734. ssl->heap);
  1735. if (ret != 0)
  1736. return ret;
  1737. #ifdef WOLFSSL_DEBUG_TLS
  1738. WOLFSSL_MSG("Provisioning CHACHA Record Number dec key:");
  1739. WOLFSSL_BUFFER(decKey, ssl->specs.key_size);
  1740. #endif /* WOLFSSL_DEBUG_TLS */
  1741. }
  1742. return 0;
  1743. }
  1744. #endif /* HAVE_CHACHA */
  1745. return NOT_COMPILED_IN;
  1746. }
  1747. /* 64 bits epoch + 64 bits sequence */
  1748. #define DTLS13_RN_SIZE 16
  1749. static int Dtls13GetAckListLength(Dtls13RecordNumber* list, word16* length)
  1750. {
  1751. int numberElements;
  1752. numberElements = 0;
  1753. /* TODO: check that we don't exceed the maximum length */
  1754. while (list != NULL) {
  1755. list = list->next;
  1756. numberElements++;
  1757. }
  1758. *length = DTLS13_RN_SIZE * numberElements;
  1759. return 0;
  1760. }
  1761. static int Dtls13WriteAckMessage(WOLFSSL* ssl,
  1762. Dtls13RecordNumber* recordNumberList, word32* length)
  1763. {
  1764. word16 msgSz, headerLength;
  1765. byte *output, *ackMessage;
  1766. word32 sendSz;
  1767. int ret;
  1768. sendSz = 0;
  1769. if (ssl->dtls13EncryptEpoch == NULL)
  1770. return BAD_STATE_E;
  1771. if (w64IsZero(ssl->dtls13EncryptEpoch->epochNumber)) {
  1772. /* unprotected ACK */
  1773. headerLength = DTLS_RECORD_HEADER_SZ;
  1774. }
  1775. else {
  1776. headerLength = Dtls13GetRlHeaderLength(ssl, 1);
  1777. sendSz += MAX_MSG_EXTRA;
  1778. }
  1779. ret = Dtls13GetAckListLength(recordNumberList, &msgSz);
  1780. if (ret != 0)
  1781. return ret;
  1782. sendSz += headerLength;
  1783. /* ACK list 2 bytes length field */
  1784. sendSz += OPAQUE16_LEN;
  1785. /* ACK list */
  1786. sendSz += msgSz;
  1787. ret = CheckAvailableSize(ssl, sendSz);
  1788. if (ret != 0)
  1789. return ret;
  1790. output =
  1791. ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.length;
  1792. ackMessage = output + headerLength;
  1793. c16toa(msgSz, ackMessage);
  1794. ackMessage += OPAQUE16_LEN;
  1795. while (recordNumberList != NULL) {
  1796. c64toa(&recordNumberList->epoch, ackMessage);
  1797. ackMessage += OPAQUE64_LEN;
  1798. c64toa(&recordNumberList->seq, ackMessage);
  1799. ackMessage += OPAQUE64_LEN;
  1800. recordNumberList = recordNumberList->next;
  1801. }
  1802. *length = msgSz + OPAQUE16_LEN;
  1803. return 0;
  1804. }
  1805. static int Dtls13RtxIsTrackedByRn(const Dtls13RtxRecord* r, w64wrapper epoch,
  1806. w64wrapper seq)
  1807. {
  1808. int i;
  1809. if (!w64Equal(r->epoch, epoch))
  1810. return 0;
  1811. for (i = 0; i < r->rnIdx; ++i) {
  1812. if (w64Equal(r->seq[i], seq))
  1813. return 1;
  1814. }
  1815. return 0;
  1816. }
  1817. static int Dtls13KeyUpdateAckReceived(WOLFSSL* ssl)
  1818. {
  1819. int ret;
  1820. w64Increment(&ssl->dtls13Epoch);
  1821. /* Epoch wrapped up */
  1822. if (w64IsZero(ssl->dtls13Epoch))
  1823. return BAD_STATE_E;
  1824. ret = DeriveTls13Keys(ssl, update_traffic_key, ENCRYPT_SIDE_ONLY, 1);
  1825. if (ret != 0)
  1826. return ret;
  1827. ret = Dtls13NewEpoch(ssl, ssl->dtls13Epoch, ENCRYPT_SIDE_ONLY);
  1828. if (ret != 0)
  1829. return ret;
  1830. return Dtls13SetEpochKeys(ssl, ssl->dtls13Epoch, ENCRYPT_SIDE_ONLY);
  1831. }
  1832. #ifdef WOLFSSL_DEBUG_TLS
  1833. static void Dtls13PrintRtxRecord(Dtls13RtxRecord* r)
  1834. {
  1835. int i;
  1836. WOLFSSL_MSG_EX("r: hs: %d epoch: %ld", r->handshakeType, r->epoch);
  1837. for (i = 0; i < r->rnIdx; i++)
  1838. WOLFSSL_MSG_EX("seq: %ld", r->seq[i]);
  1839. }
  1840. #endif /* WOLFSSL_DEBUG_TLS */
  1841. static void Dtls13RtxRemoveRecord(WOLFSSL* ssl, w64wrapper epoch,
  1842. w64wrapper seq)
  1843. {
  1844. Dtls13RtxRecord *r, **prevNext;
  1845. prevNext = &ssl->dtls13Rtx.rtxRecords;
  1846. r = ssl->dtls13Rtx.rtxRecords;
  1847. while (r != NULL) {
  1848. #ifdef WOLFSSL_DEBUG_TLS
  1849. Dtls13PrintRtxRecord(r);
  1850. #endif /* WOLFSSL_DEBUG_TLS */
  1851. if (Dtls13RtxIsTrackedByRn(r, epoch, seq)) {
  1852. #ifdef WOLFSSL_DEBUG_TLS
  1853. WOLFSSL_MSG("removing record");
  1854. #endif /* WOLFSSL_DEBUG_TLS */
  1855. Dtls13RtxRecordUnlink(ssl, prevNext, r);
  1856. Dtls13FreeRtxBufferRecord(ssl, r);
  1857. return;
  1858. }
  1859. prevNext = &r->next;
  1860. r = r->next;
  1861. }
  1862. return;
  1863. }
  1864. int Dtls13DoScheduledWork(WOLFSSL* ssl)
  1865. {
  1866. int ret;
  1867. WOLFSSL_ENTER("Dtls13DoScheduledWork");
  1868. ssl->dtls13SendingAckOrRtx = 1;
  1869. if (ssl->dtls13Rtx.sendAcks) {
  1870. ssl->dtls13Rtx.sendAcks = 0;
  1871. ret = SendDtls13Ack(ssl);
  1872. if (ret != 0)
  1873. return ret;
  1874. }
  1875. if (ssl->dtls13Rtx.retransmit) {
  1876. ssl->dtls13Rtx.retransmit = 0;
  1877. ret = Dtls13RtxSendBuffered(ssl);
  1878. if (ret != 0)
  1879. return ret;
  1880. }
  1881. ssl->dtls13SendingAckOrRtx = 0;
  1882. return 0;
  1883. }
  1884. /* Send ACKs when available after a timeout but only retransmit the last
  1885. * flight after a long timeout */
  1886. int Dtls13RtxTimeout(WOLFSSL* ssl)
  1887. {
  1888. int ret = 0;
  1889. if (ssl->dtls13Rtx.seenRecords != NULL) {
  1890. ssl->dtls13Rtx.sendAcks = 0;
  1891. /* reset fast timeout as we are sending ACKs */
  1892. ssl->dtls13FastTimeout = 0;
  1893. ret = SendDtls13Ack(ssl);
  1894. if (ret != 0)
  1895. return ret;
  1896. }
  1897. /* we have two timeouts, a shorter (dtls13FastTimeout = 1) and a longer
  1898. one. When the shorter expires we only send ACKs, as it normally means
  1899. that some messages we are waiting for dont't arrive yet. But we
  1900. retransmit our buffered messages only if the longer timeout
  1901. expires. fastTimeout is 1/4 of the longer timeout */
  1902. if (ssl->dtls13FastTimeout) {
  1903. ssl->dtls13FastTimeout = 0;
  1904. return 0;
  1905. }
  1906. /* Increase timeout on long timeout */
  1907. if (DtlsMsgPoolTimeout(ssl) != 0)
  1908. return -1;
  1909. return Dtls13RtxSendBuffered(ssl);
  1910. }
  1911. static int Dtls13RtxHasKeyUpdateBuffered(WOLFSSL* ssl)
  1912. {
  1913. Dtls13RtxRecord* r = ssl->dtls13Rtx.rtxRecords;
  1914. while (r != NULL) {
  1915. if (r->handshakeType == key_update)
  1916. return 1;
  1917. r = r->next;
  1918. }
  1919. return 0;
  1920. }
  1921. int DoDtls13Ack(WOLFSSL* ssl, const byte* input, word32 inputSize,
  1922. word32* processedSize)
  1923. {
  1924. const byte* ackMessage;
  1925. w64wrapper epoch, seq;
  1926. word16 length;
  1927. int ret;
  1928. int i;
  1929. if (inputSize < OPAQUE16_LEN)
  1930. return BUFFER_ERROR;
  1931. ato16(input, &length);
  1932. if (inputSize < (word32)(OPAQUE16_LEN + length))
  1933. return BUFFER_ERROR;
  1934. if (length % (DTLS13_RN_SIZE) != 0)
  1935. return PARSE_ERROR;
  1936. ackMessage = input + OPAQUE16_LEN;
  1937. for (i = 0; i < length; i += DTLS13_RN_SIZE) {
  1938. ato64(ackMessage + i, &epoch);
  1939. ato64(ackMessage + i + OPAQUE64_LEN, &seq);
  1940. Dtls13RtxRemoveRecord(ssl, epoch, seq);
  1941. }
  1942. /* last client flight was completely acknowledged by the server. Handshake
  1943. is complete. */
  1944. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  1945. ssl->options.connectState == WAIT_FINISHED_ACK &&
  1946. ssl->dtls13Rtx.rtxRecords == NULL) {
  1947. ssl->options.serverState = SERVER_FINISHED_ACKED;
  1948. }
  1949. if (ssl->dtls13WaitKeyUpdateAck) {
  1950. if (!Dtls13RtxHasKeyUpdateBuffered(ssl)) {
  1951. /* we removed the KeyUpdate message because it was ACKed */
  1952. ssl->dtls13WaitKeyUpdateAck = 0;
  1953. ret = Dtls13KeyUpdateAckReceived(ssl);
  1954. if (ret != 0)
  1955. return ret;
  1956. }
  1957. }
  1958. *processedSize = length + OPAQUE16_LEN;
  1959. /* After the handshake, not retransmitting here may incur in some extra time
  1960. in case a post-handshake authentication message is lost, because the ACK
  1961. mechanism does not shortcut the retransmission timer. If, on the other
  1962. hand, we retransmit we may do extra retransmissions of unrelated messages
  1963. in the queue. ex: we send KeyUpdate, CertificateRequest that are
  1964. unrelated between each other, receiving the ACK for the KeyUpdate will
  1965. trigger re-sending the CertificateRequest before the timeout.*/
  1966. /* TODO: be more smart about when doing retransmission looking in the
  1967. retransmission queue or based on the type of message removed from the
  1968. seen record list */
  1969. if (ssl->dtls13Rtx.rtxRecords != NULL)
  1970. ssl->dtls13Rtx.retransmit = 1;
  1971. return 0;
  1972. }
  1973. int SendDtls13Ack(WOLFSSL* ssl)
  1974. {
  1975. word32 outputSize;
  1976. int headerSize;
  1977. word32 length;
  1978. byte* output;
  1979. int ret;
  1980. if (ssl->dtls13EncryptEpoch == NULL)
  1981. return BAD_STATE_E;
  1982. WOLFSSL_ENTER("SendDtls13Ack");
  1983. ret = 0;
  1984. /* The handshake is not complete and the client didn't setup the TRAFFIC0
  1985. epoch yet */
  1986. if (ssl->options.side == WOLFSSL_SERVER_END &&
  1987. !ssl->options.handShakeDone &&
  1988. w64GTE(ssl->dtls13Epoch, w64From32(0, DTLS13_EPOCH_TRAFFIC0))) {
  1989. ret = Dtls13SetEpochKeys(ssl, w64From32(0, DTLS13_EPOCH_HANDSHAKE),
  1990. ENCRYPT_SIDE_ONLY);
  1991. }
  1992. else if (!w64Equal(ssl->dtls13Epoch,
  1993. ssl->dtls13EncryptEpoch->epochNumber)) {
  1994. ret = Dtls13SetEpochKeys(ssl, ssl->dtls13Epoch, ENCRYPT_SIDE_ONLY);
  1995. }
  1996. if (ret != 0)
  1997. return ret;
  1998. if (w64IsZero(ssl->dtls13EncryptEpoch->epochNumber)) {
  1999. ret = Dtls13WriteAckMessage(ssl, ssl->dtls13Rtx.seenRecords, &length);
  2000. if (ret != 0)
  2001. return ret;
  2002. output =
  2003. ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.length;
  2004. ret = Dtls13RlAddPlaintextHeader(ssl, output, ack, length);
  2005. if (ret != 0)
  2006. return ret;
  2007. ssl->buffers.outputBuffer.length += length + DTLS_RECORD_HEADER_SZ;
  2008. }
  2009. else {
  2010. ret = Dtls13WriteAckMessage(ssl, ssl->dtls13Rtx.seenRecords, &length);
  2011. if (ret != 0)
  2012. return ret;
  2013. output =
  2014. ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.length;
  2015. outputSize = ssl->buffers.outputBuffer.bufferSize -
  2016. ssl->buffers.outputBuffer.length;
  2017. headerSize = Dtls13GetRlHeaderLength(ssl, 1);
  2018. ret = BuildTls13Message(ssl, output, outputSize, output + headerSize,
  2019. length, ack, 0, 0, 0);
  2020. if (ret < 0)
  2021. return ret;
  2022. ssl->buffers.outputBuffer.length += ret;
  2023. }
  2024. Dtls13RtxFlushAcks(ssl);
  2025. return SendBuffered(ssl);
  2026. }
  2027. static int Dtls13RtxRecordMatchesReqCtx(Dtls13RtxRecord* r, byte* ctx,
  2028. byte ctxLen)
  2029. {
  2030. if (r->handshakeType != certificate_request)
  2031. return 0;
  2032. if (r->length <= ctxLen + 1)
  2033. return 0;
  2034. return XMEMCMP(ctx, r->data + 1, ctxLen) == 0;
  2035. }
  2036. int Dtls13RtxProcessingCertificate(WOLFSSL* ssl, byte* input, word32 inputSize)
  2037. {
  2038. Dtls13RtxRecord* rtxRecord = ssl->dtls13Rtx.rtxRecords;
  2039. Dtls13RtxRecord** prevNext = &ssl->dtls13Rtx.rtxRecords;
  2040. byte ctxLength;
  2041. WOLFSSL_ENTER("Dtls13RtxProcessingCertificate");
  2042. if (inputSize <= 1) {
  2043. WOLFSSL_MSG("Malformed Certificate");
  2044. return BAD_FUNC_ARG;
  2045. }
  2046. ctxLength = *input;
  2047. if (inputSize < (word32)ctxLength + OPAQUE8_LEN) {
  2048. WOLFSSL_MSG("Malformed Certificate");
  2049. return BAD_FUNC_ARG;
  2050. }
  2051. while (rtxRecord != NULL) {
  2052. if (Dtls13RtxRecordMatchesReqCtx(rtxRecord, input + 1, ctxLength)) {
  2053. Dtls13RtxRecordUnlink(ssl, prevNext, rtxRecord);
  2054. Dtls13FreeRtxBufferRecord(ssl, rtxRecord);
  2055. return 0;
  2056. }
  2057. prevNext = &rtxRecord->next;
  2058. rtxRecord = rtxRecord->next;
  2059. }
  2060. /* This isn't an error since we just can't find a Dtls13RtxRecord that
  2061. * matches the Request Context. Request Context validity is checked
  2062. * later. */
  2063. WOLFSSL_MSG("Can't find any previous Certificate Request");
  2064. return 0;
  2065. }
  2066. int wolfSSL_dtls13_has_pending_msg(WOLFSSL* ssl)
  2067. {
  2068. return ssl->dtls13Rtx.rtxRecords != NULL;
  2069. }
  2070. #endif /* WOLFSSL_DTLS13 */