dtls13.c 80 KB

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