dtls13.c 75 KB

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