quic_channel.c 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803
  1. /*
  2. * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <openssl/rand.h>
  10. #include <openssl/err.h>
  11. #include "internal/quic_channel.h"
  12. #include "internal/quic_error.h"
  13. #include "internal/quic_rx_depack.h"
  14. #include "../ssl_local.h"
  15. #include "quic_channel_local.h"
  16. /*
  17. * NOTE: While this channel implementation currently has basic server support,
  18. * this functionality has been implemented for internal testing purposes and is
  19. * not suitable for network use. In particular, it does not implement address
  20. * validation, anti-amplification or retry logic.
  21. *
  22. * TODO(QUIC SERVER): Implement address validation and anti-amplification
  23. * TODO(QUIC SERVER): Implement retry logic
  24. */
  25. #define INIT_DCID_LEN 8
  26. #define INIT_CRYPTO_RECV_BUF_LEN 16384
  27. #define INIT_CRYPTO_SEND_BUF_LEN 16384
  28. #define INIT_APP_BUF_LEN 8192
  29. /*
  30. * Interval before we force a PING to ensure NATs don't timeout. This is based
  31. * on the lowest commonly seen value of 30 seconds as cited in RFC 9000 s.
  32. * 10.1.2.
  33. */
  34. #define MAX_NAT_INTERVAL (ossl_ms2time(25000))
  35. /*
  36. * Our maximum ACK delay on the TX side. This is up to us to choose. Note that
  37. * this could differ from QUIC_DEFAULT_MAX_DELAY in future as that is a protocol
  38. * value which determines the value of the maximum ACK delay if the
  39. * max_ack_delay transport parameter is not set.
  40. */
  41. #define DEFAULT_MAX_ACK_DELAY QUIC_DEFAULT_MAX_ACK_DELAY
  42. static void ch_save_err_state(QUIC_CHANNEL *ch);
  43. static void ch_rx_pre(QUIC_CHANNEL *ch);
  44. static int ch_rx(QUIC_CHANNEL *ch, int channel_only);
  45. static int ch_tx(QUIC_CHANNEL *ch);
  46. static void ch_tick(QUIC_TICK_RESULT *res, void *arg, uint32_t flags);
  47. static int ch_tick_tls(QUIC_CHANNEL *ch, int channel_only);
  48. static void ch_rx_handle_packet(QUIC_CHANNEL *ch, int channel_only);
  49. static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch);
  50. static int ch_retry(QUIC_CHANNEL *ch,
  51. const unsigned char *retry_token,
  52. size_t retry_token_len,
  53. const QUIC_CONN_ID *retry_scid);
  54. static void ch_cleanup(QUIC_CHANNEL *ch);
  55. static int ch_generate_transport_params(QUIC_CHANNEL *ch);
  56. static int ch_on_transport_params(const unsigned char *params,
  57. size_t params_len,
  58. void *arg);
  59. static int ch_on_handshake_alert(void *arg, unsigned char alert_code);
  60. static int ch_on_handshake_complete(void *arg);
  61. static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
  62. uint32_t suite_id, EVP_MD *md,
  63. const unsigned char *secret,
  64. size_t secret_len,
  65. void *arg);
  66. static int ch_on_crypto_recv_record(const unsigned char **buf,
  67. size_t *bytes_read, void *arg);
  68. static int ch_on_crypto_release_record(size_t bytes_read, void *arg);
  69. static int crypto_ensure_empty(QUIC_RSTREAM *rstream);
  70. static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
  71. size_t *consumed, void *arg);
  72. static OSSL_TIME get_time(void *arg);
  73. static uint64_t get_stream_limit(int uni, void *arg);
  74. static int rx_late_validate(QUIC_PN pn, int pn_space, void *arg);
  75. static void rxku_detected(QUIC_PN pn, void *arg);
  76. static int ch_retry(QUIC_CHANNEL *ch,
  77. const unsigned char *retry_token,
  78. size_t retry_token_len,
  79. const QUIC_CONN_ID *retry_scid);
  80. static void ch_update_idle(QUIC_CHANNEL *ch);
  81. static int ch_discard_el(QUIC_CHANNEL *ch,
  82. uint32_t enc_level);
  83. static void ch_on_idle_timeout(QUIC_CHANNEL *ch);
  84. static void ch_update_idle(QUIC_CHANNEL *ch);
  85. static void ch_update_ping_deadline(QUIC_CHANNEL *ch);
  86. static void ch_stateless_reset(QUIC_CHANNEL *ch);
  87. static void ch_raise_net_error(QUIC_CHANNEL *ch);
  88. static void ch_on_terminating_timeout(QUIC_CHANNEL *ch);
  89. static void ch_start_terminating(QUIC_CHANNEL *ch,
  90. const QUIC_TERMINATE_CAUSE *tcause,
  91. int force_immediate);
  92. static int ch_stateless_reset_token_handler(const unsigned char *data, size_t datalen, void *arg);
  93. static void ch_default_packet_handler(QUIC_URXE *e, void *arg);
  94. static int ch_server_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
  95. const QUIC_CONN_ID *peer_scid,
  96. const QUIC_CONN_ID *peer_dcid);
  97. static void ch_on_txp_ack_tx(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space,
  98. void *arg);
  99. static void ch_rx_handle_version_neg(QUIC_CHANNEL *ch, OSSL_QRX_PKT *pkt);
  100. static void ch_raise_version_neg_failure(QUIC_CHANNEL *ch);
  101. DEFINE_LHASH_OF_EX(QUIC_SRT_ELEM);
  102. static int gen_rand_conn_id(OSSL_LIB_CTX *libctx, size_t len, QUIC_CONN_ID *cid)
  103. {
  104. if (len > QUIC_MAX_CONN_ID_LEN)
  105. return 0;
  106. cid->id_len = (unsigned char)len;
  107. if (RAND_bytes_ex(libctx, cid->id, len, len * 8) != 1) {
  108. ERR_raise(ERR_LIB_SSL, ERR_R_RAND_LIB);
  109. cid->id_len = 0;
  110. return 0;
  111. }
  112. return 1;
  113. }
  114. static unsigned long chan_reset_token_hash(const QUIC_SRT_ELEM *a)
  115. {
  116. unsigned long h;
  117. assert(sizeof(h) <= sizeof(a->token));
  118. memcpy(&h, &a->token, sizeof(h));
  119. return h;
  120. }
  121. static int chan_reset_token_cmp(const QUIC_SRT_ELEM *a, const QUIC_SRT_ELEM *b)
  122. {
  123. /* RFC 9000 s. 10.3.1:
  124. * When comparing a datagram to stateless reset token values,
  125. * endpoints MUST perform the comparison without leaking
  126. * information about the value of the token. For example,
  127. * performing this comparison in constant time protects the
  128. * value of individual stateless reset tokens from information
  129. * leakage through timing side channels.
  130. *
  131. * TODO(QUIC FUTURE): make this a memcmp when obfuscation is done and update
  132. * comment above.
  133. */
  134. return CRYPTO_memcmp(&a->token, &b->token, sizeof(a->token));
  135. }
  136. static int reset_token_obfuscate(QUIC_SRT_ELEM *out, const unsigned char *in)
  137. {
  138. /*
  139. * TODO(QUIC FUTURE): update this to AES encrypt the token in ECB mode with a
  140. * random (per channel) key.
  141. */
  142. memcpy(&out->token, in, sizeof(out->token));
  143. return 1;
  144. }
  145. /*
  146. * Add a stateless reset token to the channel
  147. */
  148. static int chan_add_reset_token(QUIC_CHANNEL *ch, const unsigned char *new,
  149. uint64_t seq_num)
  150. {
  151. QUIC_SRT_ELEM *srte;
  152. int err;
  153. /* Add to list by sequence number (always the tail) */
  154. if ((srte = OPENSSL_malloc(sizeof(*srte))) == NULL)
  155. return 0;
  156. ossl_list_stateless_reset_tokens_init_elem(srte);
  157. ossl_list_stateless_reset_tokens_insert_tail(&ch->srt_list_seq, srte);
  158. reset_token_obfuscate(srte, new);
  159. srte->seq_num = seq_num;
  160. lh_QUIC_SRT_ELEM_insert(ch->srt_hash_tok, srte);
  161. err = lh_QUIC_SRT_ELEM_error(ch->srt_hash_tok);
  162. if (err > 0) {
  163. ossl_list_stateless_reset_tokens_remove(&ch->srt_list_seq, srte);
  164. OPENSSL_free(srte);
  165. return 0;
  166. }
  167. return 1;
  168. }
  169. /*
  170. * Remove a stateless reset token from the channel
  171. * If the token isn't known, we just ignore the remove request which is safe.
  172. */
  173. static void chan_remove_reset_token(QUIC_CHANNEL *ch, uint64_t seq_num)
  174. {
  175. QUIC_SRT_ELEM *srte;
  176. /*
  177. * Because the list is ordered and we only ever remove CIDs in order,
  178. * this loop should never iterate, but safer to provide the option.
  179. */
  180. for (srte = ossl_list_stateless_reset_tokens_head(&ch->srt_list_seq);
  181. srte != NULL;
  182. srte = ossl_list_stateless_reset_tokens_next(srte)) {
  183. if (srte->seq_num > seq_num)
  184. return;
  185. if (srte->seq_num == seq_num) {
  186. ossl_list_stateless_reset_tokens_remove(&ch->srt_list_seq, srte);
  187. (void)lh_QUIC_SRT_ELEM_delete(ch->srt_hash_tok, srte);
  188. OPENSSL_free(srte);
  189. return;
  190. }
  191. }
  192. }
  193. /*
  194. * This is called by the demux whenever a new datagram arrives
  195. *
  196. * TODO(QUIC FUTURE): optimise this to only be called for unparsable packets
  197. */
  198. static int ch_stateless_reset_token_handler(const unsigned char *data,
  199. size_t datalen, void *arg)
  200. {
  201. QUIC_SRT_ELEM srte;
  202. QUIC_CHANNEL *ch = (QUIC_CHANNEL *)arg;
  203. /*
  204. * Perform some fast and cheap checks for a packet not being a stateless
  205. * reset token. RFC 9000 s. 10.3 specifies this layout for stateless
  206. * reset packets:
  207. *
  208. * Stateless Reset {
  209. * Fixed Bits (2) = 1,
  210. * Unpredictable Bits (38..),
  211. * Stateless Reset Token (128),
  212. * }
  213. *
  214. * It also specifies:
  215. * However, endpoints MUST treat any packet ending in a valid
  216. * stateless reset token as a Stateless Reset, as other QUIC
  217. * versions might allow the use of a long header.
  218. *
  219. * We can rapidly check for the minimum length and that the first pair
  220. * of bits in the first byte are 01 or 11.
  221. *
  222. * The function returns 1 if it is a stateless reset packet, 0 if it isn't
  223. * and -1 if an error was encountered.
  224. */
  225. if (datalen < QUIC_STATELESS_RESET_TOKEN_LEN + 5 || (0100 & *data) != 0100)
  226. return 0;
  227. memset(&srte, 0, sizeof(srte));
  228. if (!reset_token_obfuscate(&srte, data + datalen - sizeof(srte.token)))
  229. return -1;
  230. return lh_QUIC_SRT_ELEM_retrieve(ch->srt_hash_tok, &srte) != NULL;
  231. }
  232. /*
  233. * QUIC Channel Initialization and Teardown
  234. * ========================================
  235. */
  236. #define DEFAULT_INIT_CONN_RXFC_WND (768 * 1024)
  237. #define DEFAULT_CONN_RXFC_MAX_WND_MUL 20
  238. #define DEFAULT_INIT_STREAM_RXFC_WND (512 * 1024)
  239. #define DEFAULT_STREAM_RXFC_MAX_WND_MUL 12
  240. #define DEFAULT_INIT_CONN_MAX_STREAMS 100
  241. static int ch_init(QUIC_CHANNEL *ch)
  242. {
  243. OSSL_QUIC_TX_PACKETISER_ARGS txp_args = {0};
  244. OSSL_QTX_ARGS qtx_args = {0};
  245. OSSL_QRX_ARGS qrx_args = {0};
  246. QUIC_TLS_ARGS tls_args = {0};
  247. uint32_t pn_space;
  248. size_t rx_short_cid_len = ch->is_server ? INIT_DCID_LEN : 0;
  249. ossl_list_stateless_reset_tokens_init(&ch->srt_list_seq);
  250. ch->srt_hash_tok = lh_QUIC_SRT_ELEM_new(&chan_reset_token_hash,
  251. &chan_reset_token_cmp);
  252. if (ch->srt_hash_tok == NULL)
  253. goto err;
  254. /* For clients, generate our initial DCID. */
  255. if (!ch->is_server
  256. && !gen_rand_conn_id(ch->libctx, INIT_DCID_LEN, &ch->init_dcid))
  257. goto err;
  258. /* We plug in a network write BIO to the QTX later when we get one. */
  259. qtx_args.libctx = ch->libctx;
  260. qtx_args.mdpl = QUIC_MIN_INITIAL_DGRAM_LEN;
  261. ch->rx_max_udp_payload_size = qtx_args.mdpl;
  262. ch->ping_deadline = ossl_time_infinite();
  263. ch->qtx = ossl_qtx_new(&qtx_args);
  264. if (ch->qtx == NULL)
  265. goto err;
  266. ch->txpim = ossl_quic_txpim_new();
  267. if (ch->txpim == NULL)
  268. goto err;
  269. ch->cfq = ossl_quic_cfq_new();
  270. if (ch->cfq == NULL)
  271. goto err;
  272. if (!ossl_quic_txfc_init(&ch->conn_txfc, NULL))
  273. goto err;
  274. /*
  275. * Note: The TP we transmit governs what the peer can transmit and thus
  276. * applies to the RXFC.
  277. */
  278. ch->tx_init_max_stream_data_bidi_local = DEFAULT_INIT_STREAM_RXFC_WND;
  279. ch->tx_init_max_stream_data_bidi_remote = DEFAULT_INIT_STREAM_RXFC_WND;
  280. ch->tx_init_max_stream_data_uni = DEFAULT_INIT_STREAM_RXFC_WND;
  281. if (!ossl_quic_rxfc_init(&ch->conn_rxfc, NULL,
  282. DEFAULT_INIT_CONN_RXFC_WND,
  283. DEFAULT_CONN_RXFC_MAX_WND_MUL *
  284. DEFAULT_INIT_CONN_RXFC_WND,
  285. get_time, ch))
  286. goto err;
  287. for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space)
  288. if (!ossl_quic_rxfc_init_standalone(&ch->crypto_rxfc[pn_space],
  289. INIT_CRYPTO_RECV_BUF_LEN,
  290. get_time, ch))
  291. goto err;
  292. if (!ossl_quic_rxfc_init_standalone(&ch->max_streams_bidi_rxfc,
  293. DEFAULT_INIT_CONN_MAX_STREAMS,
  294. get_time, ch))
  295. goto err;
  296. if (!ossl_quic_rxfc_init_standalone(&ch->max_streams_uni_rxfc,
  297. DEFAULT_INIT_CONN_MAX_STREAMS,
  298. get_time, ch))
  299. goto err;
  300. if (!ossl_statm_init(&ch->statm))
  301. goto err;
  302. ch->have_statm = 1;
  303. ch->cc_method = &ossl_cc_newreno_method;
  304. if ((ch->cc_data = ch->cc_method->new(get_time, ch)) == NULL)
  305. goto err;
  306. if ((ch->ackm = ossl_ackm_new(get_time, ch, &ch->statm,
  307. ch->cc_method, ch->cc_data)) == NULL)
  308. goto err;
  309. if (!ossl_quic_stream_map_init(&ch->qsm, get_stream_limit, ch,
  310. &ch->max_streams_bidi_rxfc,
  311. &ch->max_streams_uni_rxfc,
  312. ch->is_server))
  313. goto err;
  314. ch->have_qsm = 1;
  315. /* We use a zero-length SCID. */
  316. txp_args.cur_dcid = ch->init_dcid;
  317. txp_args.ack_delay_exponent = 3;
  318. txp_args.qtx = ch->qtx;
  319. txp_args.txpim = ch->txpim;
  320. txp_args.cfq = ch->cfq;
  321. txp_args.ackm = ch->ackm;
  322. txp_args.qsm = &ch->qsm;
  323. txp_args.conn_txfc = &ch->conn_txfc;
  324. txp_args.conn_rxfc = &ch->conn_rxfc;
  325. txp_args.max_streams_bidi_rxfc = &ch->max_streams_bidi_rxfc;
  326. txp_args.max_streams_uni_rxfc = &ch->max_streams_uni_rxfc;
  327. txp_args.cc_method = ch->cc_method;
  328. txp_args.cc_data = ch->cc_data;
  329. txp_args.now = get_time;
  330. txp_args.now_arg = ch;
  331. for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
  332. ch->crypto_send[pn_space] = ossl_quic_sstream_new(INIT_CRYPTO_SEND_BUF_LEN);
  333. if (ch->crypto_send[pn_space] == NULL)
  334. goto err;
  335. txp_args.crypto[pn_space] = ch->crypto_send[pn_space];
  336. }
  337. ch->txp = ossl_quic_tx_packetiser_new(&txp_args);
  338. if (ch->txp == NULL)
  339. goto err;
  340. ossl_quic_tx_packetiser_set_ack_tx_cb(ch->txp, ch_on_txp_ack_tx, ch);
  341. if ((ch->demux = ossl_quic_demux_new(/*BIO=*/NULL,
  342. /*Short CID Len=*/rx_short_cid_len,
  343. get_time, ch)) == NULL)
  344. goto err;
  345. /*
  346. * Setup a handler to detect stateless reset tokens.
  347. */
  348. ossl_quic_demux_set_stateless_reset_handler(ch->demux,
  349. &ch_stateless_reset_token_handler,
  350. ch);
  351. /*
  352. * If we are a server, setup our handler for packets not corresponding to
  353. * any known DCID on our end. This is for handling clients establishing new
  354. * connections.
  355. */
  356. if (ch->is_server)
  357. ossl_quic_demux_set_default_handler(ch->demux,
  358. ch_default_packet_handler,
  359. ch);
  360. qrx_args.libctx = ch->libctx;
  361. qrx_args.demux = ch->demux;
  362. qrx_args.short_conn_id_len = rx_short_cid_len;
  363. qrx_args.max_deferred = 32;
  364. if ((ch->qrx = ossl_qrx_new(&qrx_args)) == NULL)
  365. goto err;
  366. if (!ossl_qrx_set_late_validation_cb(ch->qrx,
  367. rx_late_validate,
  368. ch))
  369. goto err;
  370. if (!ossl_qrx_set_key_update_cb(ch->qrx,
  371. rxku_detected,
  372. ch))
  373. goto err;
  374. if (!ch->is_server && !ossl_qrx_add_dst_conn_id(ch->qrx, &txp_args.cur_scid))
  375. goto err;
  376. for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
  377. ch->crypto_recv[pn_space] = ossl_quic_rstream_new(NULL, NULL, 0);
  378. if (ch->crypto_recv[pn_space] == NULL)
  379. goto err;
  380. }
  381. /* Plug in the TLS handshake layer. */
  382. tls_args.s = ch->tls;
  383. tls_args.crypto_send_cb = ch_on_crypto_send;
  384. tls_args.crypto_send_cb_arg = ch;
  385. tls_args.crypto_recv_rcd_cb = ch_on_crypto_recv_record;
  386. tls_args.crypto_recv_rcd_cb_arg = ch;
  387. tls_args.crypto_release_rcd_cb = ch_on_crypto_release_record;
  388. tls_args.crypto_release_rcd_cb_arg = ch;
  389. tls_args.yield_secret_cb = ch_on_handshake_yield_secret;
  390. tls_args.yield_secret_cb_arg = ch;
  391. tls_args.got_transport_params_cb = ch_on_transport_params;
  392. tls_args.got_transport_params_cb_arg= ch;
  393. tls_args.handshake_complete_cb = ch_on_handshake_complete;
  394. tls_args.handshake_complete_cb_arg = ch;
  395. tls_args.alert_cb = ch_on_handshake_alert;
  396. tls_args.alert_cb_arg = ch;
  397. tls_args.is_server = ch->is_server;
  398. if ((ch->qtls = ossl_quic_tls_new(&tls_args)) == NULL)
  399. goto err;
  400. ch->tx_max_ack_delay = DEFAULT_MAX_ACK_DELAY;
  401. ch->rx_max_ack_delay = QUIC_DEFAULT_MAX_ACK_DELAY;
  402. ch->rx_ack_delay_exp = QUIC_DEFAULT_ACK_DELAY_EXP;
  403. ch->rx_active_conn_id_limit = QUIC_MIN_ACTIVE_CONN_ID_LIMIT;
  404. ch->max_idle_timeout = QUIC_DEFAULT_IDLE_TIMEOUT;
  405. ch->tx_enc_level = QUIC_ENC_LEVEL_INITIAL;
  406. ch->rx_enc_level = QUIC_ENC_LEVEL_INITIAL;
  407. ch->txku_threshold_override = UINT64_MAX;
  408. ossl_ackm_set_tx_max_ack_delay(ch->ackm, ossl_ms2time(ch->tx_max_ack_delay));
  409. ossl_ackm_set_rx_max_ack_delay(ch->ackm, ossl_ms2time(ch->rx_max_ack_delay));
  410. /*
  411. * Determine the QUIC Transport Parameters and serialize the transport
  412. * parameters block. (For servers, we do this later as we must defer
  413. * generation until we have received the client's transport parameters.)
  414. */
  415. if (!ch->is_server && !ch_generate_transport_params(ch))
  416. goto err;
  417. ch_update_idle(ch);
  418. ossl_quic_reactor_init(&ch->rtor, ch_tick, ch,
  419. ch_determine_next_tick_deadline(ch));
  420. return 1;
  421. err:
  422. ch_cleanup(ch);
  423. return 0;
  424. }
  425. static void ch_cleanup(QUIC_CHANNEL *ch)
  426. {
  427. QUIC_SRT_ELEM *srte, *srte_next;
  428. uint32_t pn_space;
  429. if (ch->ackm != NULL)
  430. for (pn_space = QUIC_PN_SPACE_INITIAL;
  431. pn_space < QUIC_PN_SPACE_NUM;
  432. ++pn_space)
  433. ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
  434. ossl_quic_tx_packetiser_free(ch->txp);
  435. ossl_quic_txpim_free(ch->txpim);
  436. ossl_quic_cfq_free(ch->cfq);
  437. ossl_qtx_free(ch->qtx);
  438. if (ch->cc_data != NULL)
  439. ch->cc_method->free(ch->cc_data);
  440. if (ch->have_statm)
  441. ossl_statm_destroy(&ch->statm);
  442. ossl_ackm_free(ch->ackm);
  443. if (ch->have_qsm)
  444. ossl_quic_stream_map_cleanup(&ch->qsm);
  445. for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
  446. ossl_quic_sstream_free(ch->crypto_send[pn_space]);
  447. ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
  448. }
  449. ossl_qrx_pkt_release(ch->qrx_pkt);
  450. ch->qrx_pkt = NULL;
  451. ossl_quic_tls_free(ch->qtls);
  452. ossl_qrx_free(ch->qrx);
  453. ossl_quic_demux_free(ch->demux);
  454. OPENSSL_free(ch->local_transport_params);
  455. OPENSSL_free((char *)ch->terminate_cause.reason);
  456. OSSL_ERR_STATE_free(ch->err_state);
  457. OPENSSL_free(ch->ack_range_scratch);
  458. /* Free the stateless reset tokens */
  459. for (srte = ossl_list_stateless_reset_tokens_head(&ch->srt_list_seq);
  460. srte != NULL;
  461. srte = srte_next) {
  462. srte_next = ossl_list_stateless_reset_tokens_next(srte);
  463. ossl_list_stateless_reset_tokens_remove(&ch->srt_list_seq, srte);
  464. (void)lh_QUIC_SRT_ELEM_delete(ch->srt_hash_tok, srte);
  465. OPENSSL_free(srte);
  466. }
  467. lh_QUIC_SRT_ELEM_free(ch->srt_hash_tok);
  468. }
  469. QUIC_CHANNEL *ossl_quic_channel_new(const QUIC_CHANNEL_ARGS *args)
  470. {
  471. QUIC_CHANNEL *ch = NULL;
  472. if ((ch = OPENSSL_zalloc(sizeof(*ch))) == NULL)
  473. return NULL;
  474. ch->libctx = args->libctx;
  475. ch->propq = args->propq;
  476. ch->is_server = args->is_server;
  477. ch->tls = args->tls;
  478. ch->mutex = args->mutex;
  479. ch->now_cb = args->now_cb;
  480. ch->now_cb_arg = args->now_cb_arg;
  481. if (!ch_init(ch)) {
  482. OPENSSL_free(ch);
  483. return NULL;
  484. }
  485. return ch;
  486. }
  487. void ossl_quic_channel_free(QUIC_CHANNEL *ch)
  488. {
  489. if (ch == NULL)
  490. return;
  491. ch_cleanup(ch);
  492. OPENSSL_free(ch);
  493. }
  494. /* Set mutator callbacks for test framework support */
  495. int ossl_quic_channel_set_mutator(QUIC_CHANNEL *ch,
  496. ossl_mutate_packet_cb mutatecb,
  497. ossl_finish_mutate_cb finishmutatecb,
  498. void *mutatearg)
  499. {
  500. if (ch->qtx == NULL)
  501. return 0;
  502. ossl_qtx_set_mutator(ch->qtx, mutatecb, finishmutatecb, mutatearg);
  503. return 1;
  504. }
  505. int ossl_quic_channel_get_peer_addr(QUIC_CHANNEL *ch, BIO_ADDR *peer_addr)
  506. {
  507. if (!ch->addressed_mode)
  508. return 0;
  509. *peer_addr = ch->cur_peer_addr;
  510. return 1;
  511. }
  512. int ossl_quic_channel_set_peer_addr(QUIC_CHANNEL *ch, const BIO_ADDR *peer_addr)
  513. {
  514. if (ch->state != QUIC_CHANNEL_STATE_IDLE)
  515. return 0;
  516. if (peer_addr == NULL || BIO_ADDR_family(peer_addr) == AF_UNSPEC) {
  517. BIO_ADDR_clear(&ch->cur_peer_addr);
  518. ch->addressed_mode = 0;
  519. return 1;
  520. }
  521. ch->cur_peer_addr = *peer_addr;
  522. ch->addressed_mode = 1;
  523. return 1;
  524. }
  525. QUIC_REACTOR *ossl_quic_channel_get_reactor(QUIC_CHANNEL *ch)
  526. {
  527. return &ch->rtor;
  528. }
  529. QUIC_STREAM_MAP *ossl_quic_channel_get_qsm(QUIC_CHANNEL *ch)
  530. {
  531. return &ch->qsm;
  532. }
  533. OSSL_STATM *ossl_quic_channel_get_statm(QUIC_CHANNEL *ch)
  534. {
  535. return &ch->statm;
  536. }
  537. QUIC_STREAM *ossl_quic_channel_get_stream_by_id(QUIC_CHANNEL *ch,
  538. uint64_t stream_id)
  539. {
  540. return ossl_quic_stream_map_get_by_id(&ch->qsm, stream_id);
  541. }
  542. int ossl_quic_channel_is_active(const QUIC_CHANNEL *ch)
  543. {
  544. return ch != NULL && ch->state == QUIC_CHANNEL_STATE_ACTIVE;
  545. }
  546. int ossl_quic_channel_is_closing(const QUIC_CHANNEL *ch)
  547. {
  548. return ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING;
  549. }
  550. static int ossl_quic_channel_is_draining(const QUIC_CHANNEL *ch)
  551. {
  552. return ch->state == QUIC_CHANNEL_STATE_TERMINATING_DRAINING;
  553. }
  554. static int ossl_quic_channel_is_terminating(const QUIC_CHANNEL *ch)
  555. {
  556. return ossl_quic_channel_is_closing(ch)
  557. || ossl_quic_channel_is_draining(ch);
  558. }
  559. int ossl_quic_channel_is_terminated(const QUIC_CHANNEL *ch)
  560. {
  561. return ch->state == QUIC_CHANNEL_STATE_TERMINATED;
  562. }
  563. int ossl_quic_channel_is_term_any(const QUIC_CHANNEL *ch)
  564. {
  565. return ossl_quic_channel_is_terminating(ch)
  566. || ossl_quic_channel_is_terminated(ch);
  567. }
  568. const QUIC_TERMINATE_CAUSE *
  569. ossl_quic_channel_get_terminate_cause(const QUIC_CHANNEL *ch)
  570. {
  571. return ossl_quic_channel_is_term_any(ch) ? &ch->terminate_cause : NULL;
  572. }
  573. int ossl_quic_channel_is_handshake_complete(const QUIC_CHANNEL *ch)
  574. {
  575. return ch->handshake_complete;
  576. }
  577. int ossl_quic_channel_is_handshake_confirmed(const QUIC_CHANNEL *ch)
  578. {
  579. return ch->handshake_confirmed;
  580. }
  581. QUIC_DEMUX *ossl_quic_channel_get0_demux(QUIC_CHANNEL *ch)
  582. {
  583. return ch->demux;
  584. }
  585. CRYPTO_MUTEX *ossl_quic_channel_get_mutex(QUIC_CHANNEL *ch)
  586. {
  587. return ch->mutex;
  588. }
  589. int ossl_quic_channel_has_pending(const QUIC_CHANNEL *ch)
  590. {
  591. return ossl_quic_demux_has_pending(ch->demux)
  592. || ossl_qrx_processed_read_pending(ch->qrx);
  593. }
  594. /*
  595. * QUIC Channel: Callbacks from Miscellaneous Subsidiary Components
  596. * ================================================================
  597. */
  598. /* Used by various components. */
  599. static OSSL_TIME get_time(void *arg)
  600. {
  601. QUIC_CHANNEL *ch = arg;
  602. if (ch->now_cb == NULL)
  603. return ossl_time_now();
  604. return ch->now_cb(ch->now_cb_arg);
  605. }
  606. /* Used by QSM. */
  607. static uint64_t get_stream_limit(int uni, void *arg)
  608. {
  609. QUIC_CHANNEL *ch = arg;
  610. return uni ? ch->max_local_streams_uni : ch->max_local_streams_bidi;
  611. }
  612. /*
  613. * Called by QRX to determine if a packet is potentially invalid before trying
  614. * to decrypt it.
  615. */
  616. static int rx_late_validate(QUIC_PN pn, int pn_space, void *arg)
  617. {
  618. QUIC_CHANNEL *ch = arg;
  619. /* Potential duplicates should not be processed. */
  620. if (!ossl_ackm_is_rx_pn_processable(ch->ackm, pn, pn_space))
  621. return 0;
  622. return 1;
  623. }
  624. /*
  625. * Triggers a TXKU (whether spontaneous or solicited). Does not check whether
  626. * spontaneous TXKU is currently allowed.
  627. */
  628. QUIC_NEEDS_LOCK
  629. static void ch_trigger_txku(QUIC_CHANNEL *ch)
  630. {
  631. uint64_t next_pn
  632. = ossl_quic_tx_packetiser_get_next_pn(ch->txp, QUIC_PN_SPACE_APP);
  633. if (!ossl_quic_pn_valid(next_pn)
  634. || !ossl_qtx_trigger_key_update(ch->qtx)) {
  635. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
  636. "key update");
  637. return;
  638. }
  639. ch->txku_in_progress = 1;
  640. ch->txku_pn = next_pn;
  641. ch->rxku_expected = ch->ku_locally_initiated;
  642. }
  643. QUIC_NEEDS_LOCK
  644. static int txku_in_progress(QUIC_CHANNEL *ch)
  645. {
  646. if (ch->txku_in_progress
  647. && ossl_ackm_get_largest_acked(ch->ackm, QUIC_PN_SPACE_APP) >= ch->txku_pn) {
  648. OSSL_TIME pto = ossl_ackm_get_pto_duration(ch->ackm);
  649. /*
  650. * RFC 9001 s. 6.5: Endpoints SHOULD wait three times the PTO before
  651. * initiating a key update after receiving an acknowledgment that
  652. * confirms that the previous key update was received.
  653. *
  654. * Note that by the above wording, this period starts from when we get
  655. * the ack for a TXKU-triggering packet, not when the TXKU is initiated.
  656. * So we defer TXKU cooldown deadline calculation to this point.
  657. */
  658. ch->txku_in_progress = 0;
  659. ch->txku_cooldown_deadline = ossl_time_add(get_time(ch),
  660. ossl_time_multiply(pto, 3));
  661. }
  662. return ch->txku_in_progress;
  663. }
  664. QUIC_NEEDS_LOCK
  665. static int txku_allowed(QUIC_CHANNEL *ch)
  666. {
  667. return ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT /* Sanity check. */
  668. /* Strict RFC 9001 criterion for TXKU. */
  669. && ch->handshake_confirmed
  670. && !txku_in_progress(ch);
  671. }
  672. QUIC_NEEDS_LOCK
  673. static int txku_recommendable(QUIC_CHANNEL *ch)
  674. {
  675. if (!txku_allowed(ch))
  676. return 0;
  677. return
  678. /* Recommended RFC 9001 criterion for TXKU. */
  679. ossl_time_compare(get_time(ch), ch->txku_cooldown_deadline) >= 0
  680. /* Some additional sensible criteria. */
  681. && !ch->rxku_in_progress
  682. && !ch->rxku_pending_confirm;
  683. }
  684. QUIC_NEEDS_LOCK
  685. static int txku_desirable(QUIC_CHANNEL *ch)
  686. {
  687. uint64_t cur_pkt_count, max_pkt_count, thresh_pkt_count;
  688. const uint32_t enc_level = QUIC_ENC_LEVEL_1RTT;
  689. /* Check AEAD limit to determine if we should perform a spontaneous TXKU. */
  690. cur_pkt_count = ossl_qtx_get_cur_epoch_pkt_count(ch->qtx, enc_level);
  691. max_pkt_count = ossl_qtx_get_max_epoch_pkt_count(ch->qtx, enc_level);
  692. thresh_pkt_count = max_pkt_count / 2;
  693. if (ch->txku_threshold_override != UINT64_MAX)
  694. thresh_pkt_count = ch->txku_threshold_override;
  695. return cur_pkt_count >= thresh_pkt_count;
  696. }
  697. QUIC_NEEDS_LOCK
  698. static void ch_maybe_trigger_spontaneous_txku(QUIC_CHANNEL *ch)
  699. {
  700. if (!txku_recommendable(ch) || !txku_desirable(ch))
  701. return;
  702. ch->ku_locally_initiated = 1;
  703. ch_trigger_txku(ch);
  704. }
  705. QUIC_NEEDS_LOCK
  706. static int rxku_allowed(QUIC_CHANNEL *ch)
  707. {
  708. /*
  709. * RFC 9001 s. 6.1: An endpoint MUST NOT initiate a key update prior to
  710. * having confirmed the handshake (Section 4.1.2).
  711. *
  712. * RFC 9001 s. 6.1: An endpoint MUST NOT initiate a subsequent key update
  713. * unless it has received an acknowledgment for a packet that was sent
  714. * protected with keys from the current key phase.
  715. *
  716. * RFC 9001 s. 6.2: If an endpoint detects a second update before it has
  717. * sent any packets with updated keys containing an acknowledgment for the
  718. * packet that initiated the key update, it indicates that its peer has
  719. * updated keys twice without awaiting confirmation. An endpoint MAY treat
  720. * such consecutive key updates as a connection error of type
  721. * KEY_UPDATE_ERROR.
  722. */
  723. return ch->handshake_confirmed && !ch->rxku_pending_confirm;
  724. }
  725. /*
  726. * Called when the QRX detects a new RX key update event.
  727. */
  728. enum rxku_decision {
  729. DECISION_RXKU_ONLY,
  730. DECISION_PROTOCOL_VIOLATION,
  731. DECISION_SOLICITED_TXKU
  732. };
  733. /* Called when the QRX detects a key update has occurred. */
  734. QUIC_NEEDS_LOCK
  735. static void rxku_detected(QUIC_PN pn, void *arg)
  736. {
  737. QUIC_CHANNEL *ch = arg;
  738. enum rxku_decision decision;
  739. OSSL_TIME pto;
  740. /*
  741. * Note: rxku_in_progress is always 0 here as an RXKU cannot be detected
  742. * when we are still in UPDATING or COOLDOWN (see quic_record_rx.h).
  743. */
  744. assert(!ch->rxku_in_progress);
  745. if (!rxku_allowed(ch))
  746. /* Is RXKU even allowed at this time? */
  747. decision = DECISION_PROTOCOL_VIOLATION;
  748. else if (ch->ku_locally_initiated)
  749. /*
  750. * If this key update was locally initiated (meaning that this detected
  751. * RXKU event is a result of our own spontaneous TXKU), we do not
  752. * trigger another TXKU; after all, to do so would result in an infinite
  753. * ping-pong of key updates. We still process it as an RXKU.
  754. */
  755. decision = DECISION_RXKU_ONLY;
  756. else
  757. /*
  758. * Otherwise, a peer triggering a KU means we have to trigger a KU also.
  759. */
  760. decision = DECISION_SOLICITED_TXKU;
  761. if (decision == DECISION_PROTOCOL_VIOLATION) {
  762. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_KEY_UPDATE_ERROR,
  763. 0, "RX key update again too soon");
  764. return;
  765. }
  766. pto = ossl_ackm_get_pto_duration(ch->ackm);
  767. ch->ku_locally_initiated = 0;
  768. ch->rxku_in_progress = 1;
  769. ch->rxku_pending_confirm = 1;
  770. ch->rxku_trigger_pn = pn;
  771. ch->rxku_update_end_deadline = ossl_time_add(get_time(ch), pto);
  772. ch->rxku_expected = 0;
  773. if (decision == DECISION_SOLICITED_TXKU)
  774. /* NOT gated by usual txku_allowed() */
  775. ch_trigger_txku(ch);
  776. /*
  777. * Ordinarily, we only generate ACK when some ACK-eliciting frame has been
  778. * received. In some cases, this may not occur for a long time, for example
  779. * if transmission of application data is going in only one direction and
  780. * nothing else is happening with the connection. However, since the peer
  781. * cannot initiate a subsequent (spontaneous) TXKU until its prior
  782. * (spontaneous or solicited) TXKU has completed - meaning that prior
  783. * TXKU's trigger packet (or subsequent packet) has been acknowledged, this
  784. * can lead to very long times before a TXKU is considered 'completed'.
  785. * Optimise this by forcing ACK generation after triggering TXKU.
  786. * (Basically, we consider a RXKU event something that is 'ACK-eliciting',
  787. * which it more or less should be; it is necessarily separate from ordinary
  788. * processing of ACK-eliciting frames as key update is not indicated via a
  789. * frame.)
  790. */
  791. ossl_quic_tx_packetiser_schedule_ack(ch->txp, QUIC_PN_SPACE_APP);
  792. }
  793. /* Called per tick to handle RXKU timer events. */
  794. QUIC_NEEDS_LOCK
  795. static void ch_rxku_tick(QUIC_CHANNEL *ch)
  796. {
  797. if (!ch->rxku_in_progress
  798. || ossl_time_compare(get_time(ch), ch->rxku_update_end_deadline) < 0)
  799. return;
  800. ch->rxku_update_end_deadline = ossl_time_infinite();
  801. ch->rxku_in_progress = 0;
  802. if (!ossl_qrx_key_update_timeout(ch->qrx, /*normal=*/1))
  803. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
  804. "RXKU cooldown internal error");
  805. }
  806. QUIC_NEEDS_LOCK
  807. static void ch_on_txp_ack_tx(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space,
  808. void *arg)
  809. {
  810. QUIC_CHANNEL *ch = arg;
  811. if (pn_space != QUIC_PN_SPACE_APP || !ch->rxku_pending_confirm
  812. || !ossl_quic_frame_ack_contains_pn(ack, ch->rxku_trigger_pn))
  813. return;
  814. /*
  815. * Defer clearing rxku_pending_confirm until TXP generate call returns
  816. * successfully.
  817. */
  818. ch->rxku_pending_confirm_done = 1;
  819. }
  820. /*
  821. * QUIC Channel: Handshake Layer Event Handling
  822. * ============================================
  823. */
  824. static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
  825. size_t *consumed, void *arg)
  826. {
  827. int ret;
  828. QUIC_CHANNEL *ch = arg;
  829. uint32_t enc_level = ch->tx_enc_level;
  830. uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
  831. QUIC_SSTREAM *sstream = ch->crypto_send[pn_space];
  832. if (!ossl_assert(sstream != NULL))
  833. return 0;
  834. ret = ossl_quic_sstream_append(sstream, buf, buf_len, consumed);
  835. return ret;
  836. }
  837. static int crypto_ensure_empty(QUIC_RSTREAM *rstream)
  838. {
  839. size_t avail = 0;
  840. int is_fin = 0;
  841. if (rstream == NULL)
  842. return 1;
  843. if (!ossl_quic_rstream_available(rstream, &avail, &is_fin))
  844. return 0;
  845. return avail == 0;
  846. }
  847. static int ch_on_crypto_recv_record(const unsigned char **buf,
  848. size_t *bytes_read, void *arg)
  849. {
  850. QUIC_CHANNEL *ch = arg;
  851. QUIC_RSTREAM *rstream;
  852. int is_fin = 0; /* crypto stream is never finished, so we don't use this */
  853. uint32_t i;
  854. /*
  855. * After we move to a later EL we must not allow our peer to send any new
  856. * bytes in the crypto stream on a previous EL. Retransmissions of old bytes
  857. * are allowed.
  858. *
  859. * In practice we will only move to a new EL when we have consumed all bytes
  860. * which should be sent on the crypto stream at a previous EL. For example,
  861. * the Handshake EL should not be provisioned until we have completely
  862. * consumed a TLS 1.3 ServerHello. Thus when we provision an EL the output
  863. * of ossl_quic_rstream_available() should be 0 for all lower ELs. Thus if a
  864. * given EL is available we simply ensure we have not received any further
  865. * bytes at a lower EL.
  866. */
  867. for (i = QUIC_ENC_LEVEL_INITIAL; i < ch->rx_enc_level; ++i)
  868. if (i != QUIC_ENC_LEVEL_0RTT &&
  869. !crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
  870. /* Protocol violation (RFC 9001 s. 4.1.3) */
  871. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
  872. OSSL_QUIC_FRAME_TYPE_CRYPTO,
  873. "crypto stream data in wrong EL");
  874. return 0;
  875. }
  876. rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)];
  877. if (rstream == NULL)
  878. return 0;
  879. return ossl_quic_rstream_get_record(rstream, buf, bytes_read,
  880. &is_fin);
  881. }
  882. static int ch_on_crypto_release_record(size_t bytes_read, void *arg)
  883. {
  884. QUIC_CHANNEL *ch = arg;
  885. QUIC_RSTREAM *rstream;
  886. OSSL_RTT_INFO rtt_info;
  887. uint32_t rx_pn_space = ossl_quic_enc_level_to_pn_space(ch->rx_enc_level);
  888. rstream = ch->crypto_recv[rx_pn_space];
  889. if (rstream == NULL)
  890. return 0;
  891. ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(ch), &rtt_info);
  892. if (!ossl_quic_rxfc_on_retire(&ch->crypto_rxfc[rx_pn_space], bytes_read,
  893. rtt_info.smoothed_rtt))
  894. return 0;
  895. return ossl_quic_rstream_release_record(rstream, bytes_read);
  896. }
  897. static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
  898. uint32_t suite_id, EVP_MD *md,
  899. const unsigned char *secret,
  900. size_t secret_len,
  901. void *arg)
  902. {
  903. QUIC_CHANNEL *ch = arg;
  904. uint32_t i;
  905. if (enc_level < QUIC_ENC_LEVEL_HANDSHAKE || enc_level >= QUIC_ENC_LEVEL_NUM)
  906. /* Invalid EL. */
  907. return 0;
  908. if (direction) {
  909. /* TX */
  910. if (enc_level <= ch->tx_enc_level)
  911. /*
  912. * Does not make sense for us to try and provision an EL we have already
  913. * attained.
  914. */
  915. return 0;
  916. if (!ossl_qtx_provide_secret(ch->qtx, enc_level,
  917. suite_id, md,
  918. secret, secret_len))
  919. return 0;
  920. ch->tx_enc_level = enc_level;
  921. } else {
  922. /* RX */
  923. if (enc_level <= ch->rx_enc_level)
  924. /*
  925. * Does not make sense for us to try and provision an EL we have already
  926. * attained.
  927. */
  928. return 0;
  929. /*
  930. * Ensure all crypto streams for previous ELs are now empty of available
  931. * data.
  932. */
  933. for (i = QUIC_ENC_LEVEL_INITIAL; i < enc_level; ++i)
  934. if (!crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
  935. /* Protocol violation (RFC 9001 s. 4.1.3) */
  936. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
  937. OSSL_QUIC_FRAME_TYPE_CRYPTO,
  938. "crypto stream data in wrong EL");
  939. return 0;
  940. }
  941. if (!ossl_qrx_provide_secret(ch->qrx, enc_level,
  942. suite_id, md,
  943. secret, secret_len))
  944. return 0;
  945. ch->have_new_rx_secret = 1;
  946. ch->rx_enc_level = enc_level;
  947. }
  948. return 1;
  949. }
  950. static int ch_on_handshake_complete(void *arg)
  951. {
  952. QUIC_CHANNEL *ch = arg;
  953. if (!ossl_assert(!ch->handshake_complete))
  954. return 0; /* this should not happen twice */
  955. if (!ossl_assert(ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT))
  956. return 0;
  957. if (!ch->got_remote_transport_params) {
  958. /*
  959. * Was not a valid QUIC handshake if we did not get valid transport
  960. * params.
  961. */
  962. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_CRYPTO_MISSING_EXT,
  963. OSSL_QUIC_FRAME_TYPE_CRYPTO,
  964. "no transport parameters received");
  965. return 0;
  966. }
  967. /* Don't need transport parameters anymore. */
  968. OPENSSL_free(ch->local_transport_params);
  969. ch->local_transport_params = NULL;
  970. /* Tell the QRX it can now process 1-RTT packets. */
  971. ossl_qrx_allow_1rtt_processing(ch->qrx);
  972. /* Tell TXP the handshake is complete. */
  973. ossl_quic_tx_packetiser_notify_handshake_complete(ch->txp);
  974. ch->handshake_complete = 1;
  975. if (ch->is_server) {
  976. /*
  977. * On the server, the handshake is confirmed as soon as it is complete.
  978. */
  979. ossl_quic_channel_on_handshake_confirmed(ch);
  980. ossl_quic_tx_packetiser_schedule_handshake_done(ch->txp);
  981. }
  982. return 1;
  983. }
  984. static int ch_on_handshake_alert(void *arg, unsigned char alert_code)
  985. {
  986. QUIC_CHANNEL *ch = arg;
  987. /*
  988. * RFC 9001 s. 4.4: More specifically, servers MUST NOT send post-handshake
  989. * TLS CertificateRequest messages, and clients MUST treat receipt of such
  990. * messages as a connection error of type PROTOCOL_VIOLATION.
  991. */
  992. if (alert_code == SSL_AD_UNEXPECTED_MESSAGE
  993. && ch->handshake_complete
  994. && ossl_quic_tls_is_cert_request(ch->qtls))
  995. ossl_quic_channel_raise_protocol_error(ch,
  996. QUIC_ERR_PROTOCOL_VIOLATION,
  997. 0,
  998. "Post-handshake TLS "
  999. "CertificateRequest received");
  1000. /*
  1001. * RFC 9001 s. 4.6.1: Servers MUST NOT send the early_data extension with a
  1002. * max_early_data_size field set to any value other than 0xffffffff. A
  1003. * client MUST treat receipt of a NewSessionTicket that contains an
  1004. * early_data extension with any other value as a connection error of type
  1005. * PROTOCOL_VIOLATION.
  1006. */
  1007. else if (alert_code == SSL_AD_ILLEGAL_PARAMETER
  1008. && ch->handshake_complete
  1009. && ossl_quic_tls_has_bad_max_early_data(ch->qtls))
  1010. ossl_quic_channel_raise_protocol_error(ch,
  1011. QUIC_ERR_PROTOCOL_VIOLATION,
  1012. 0,
  1013. "Bad max_early_data received");
  1014. else
  1015. ossl_quic_channel_raise_protocol_error(ch,
  1016. QUIC_ERR_CRYPTO_ERR_BEGIN
  1017. + alert_code,
  1018. 0, "handshake alert");
  1019. return 1;
  1020. }
  1021. /*
  1022. * QUIC Channel: Transport Parameter Handling
  1023. * ==========================================
  1024. */
  1025. /*
  1026. * Called by handshake layer when we receive QUIC Transport Parameters from the
  1027. * peer. Note that these are not authenticated until the handshake is marked
  1028. * as complete.
  1029. */
  1030. #define TP_REASON_SERVER_ONLY(x) \
  1031. x " may not be sent by a client"
  1032. #define TP_REASON_DUP(x) \
  1033. x " appears multiple times"
  1034. #define TP_REASON_MALFORMED(x) \
  1035. x " is malformed"
  1036. #define TP_REASON_EXPECTED_VALUE(x) \
  1037. x " does not match expected value"
  1038. #define TP_REASON_NOT_RETRY(x) \
  1039. x " sent when not performing a retry"
  1040. #define TP_REASON_REQUIRED(x) \
  1041. x " was not sent but is required"
  1042. #define TP_REASON_INTERNAL_ERROR(x) \
  1043. x " encountered internal error"
  1044. static void txfc_bump_cwm_bidi(QUIC_STREAM *s, void *arg)
  1045. {
  1046. if (!ossl_quic_stream_is_bidi(s)
  1047. || ossl_quic_stream_is_server_init(s))
  1048. return;
  1049. ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg);
  1050. }
  1051. static void txfc_bump_cwm_uni(QUIC_STREAM *s, void *arg)
  1052. {
  1053. if (ossl_quic_stream_is_bidi(s)
  1054. || ossl_quic_stream_is_server_init(s))
  1055. return;
  1056. ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg);
  1057. }
  1058. static void do_update(QUIC_STREAM *s, void *arg)
  1059. {
  1060. QUIC_CHANNEL *ch = arg;
  1061. ossl_quic_stream_map_update_state(&ch->qsm, s);
  1062. }
  1063. static int ch_on_transport_params(const unsigned char *params,
  1064. size_t params_len,
  1065. void *arg)
  1066. {
  1067. QUIC_CHANNEL *ch = arg;
  1068. PACKET pkt;
  1069. uint64_t id, v;
  1070. size_t len;
  1071. const unsigned char *body;
  1072. int got_orig_dcid = 0;
  1073. int got_initial_scid = 0;
  1074. int got_retry_scid = 0;
  1075. int got_initial_max_data = 0;
  1076. int got_initial_max_stream_data_bidi_local = 0;
  1077. int got_initial_max_stream_data_bidi_remote = 0;
  1078. int got_initial_max_stream_data_uni = 0;
  1079. int got_initial_max_streams_bidi = 0;
  1080. int got_initial_max_streams_uni = 0;
  1081. int got_stateless_reset_token = 0;
  1082. int got_preferred_addr = 0;
  1083. int got_ack_delay_exp = 0;
  1084. int got_max_ack_delay = 0;
  1085. int got_max_udp_payload_size = 0;
  1086. int got_max_idle_timeout = 0;
  1087. int got_active_conn_id_limit = 0;
  1088. int got_disable_active_migration = 0;
  1089. QUIC_CONN_ID cid;
  1090. const char *reason = "bad transport parameter";
  1091. if (ch->got_remote_transport_params) {
  1092. reason = "multiple transport parameter extensions";
  1093. goto malformed;
  1094. }
  1095. if (!PACKET_buf_init(&pkt, params, params_len)) {
  1096. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
  1097. "internal error (packet buf init)");
  1098. return 0;
  1099. }
  1100. while (PACKET_remaining(&pkt) > 0) {
  1101. if (!ossl_quic_wire_peek_transport_param(&pkt, &id))
  1102. goto malformed;
  1103. switch (id) {
  1104. case QUIC_TPARAM_ORIG_DCID:
  1105. if (got_orig_dcid) {
  1106. reason = TP_REASON_DUP("ORIG_DCID");
  1107. goto malformed;
  1108. }
  1109. if (ch->is_server) {
  1110. reason = TP_REASON_SERVER_ONLY("ORIG_DCID");
  1111. goto malformed;
  1112. }
  1113. if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
  1114. reason = TP_REASON_MALFORMED("ORIG_DCID");
  1115. goto malformed;
  1116. }
  1117. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  1118. /* Must match our initial DCID. */
  1119. if (!ossl_quic_conn_id_eq(&ch->init_dcid, &cid)) {
  1120. reason = TP_REASON_EXPECTED_VALUE("ORIG_DCID");
  1121. goto malformed;
  1122. }
  1123. #endif
  1124. got_orig_dcid = 1;
  1125. break;
  1126. case QUIC_TPARAM_RETRY_SCID:
  1127. if (ch->is_server) {
  1128. reason = TP_REASON_SERVER_ONLY("RETRY_SCID");
  1129. goto malformed;
  1130. }
  1131. if (got_retry_scid) {
  1132. reason = TP_REASON_DUP("RETRY_SCID");
  1133. goto malformed;
  1134. }
  1135. if (!ch->doing_retry) {
  1136. reason = TP_REASON_NOT_RETRY("RETRY_SCID");
  1137. goto malformed;
  1138. }
  1139. if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
  1140. reason = TP_REASON_MALFORMED("RETRY_SCID");
  1141. goto malformed;
  1142. }
  1143. /* Must match Retry packet SCID. */
  1144. if (!ossl_quic_conn_id_eq(&ch->retry_scid, &cid)) {
  1145. reason = TP_REASON_EXPECTED_VALUE("RETRY_SCID");
  1146. goto malformed;
  1147. }
  1148. got_retry_scid = 1;
  1149. break;
  1150. case QUIC_TPARAM_INITIAL_SCID:
  1151. if (got_initial_scid) {
  1152. /* must not appear more than once */
  1153. reason = TP_REASON_DUP("INITIAL_SCID");
  1154. goto malformed;
  1155. }
  1156. if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
  1157. reason = TP_REASON_MALFORMED("INITIAL_SCID");
  1158. goto malformed;
  1159. }
  1160. /* Must match SCID of first Initial packet from server. */
  1161. if (!ossl_quic_conn_id_eq(&ch->init_scid, &cid)) {
  1162. reason = TP_REASON_EXPECTED_VALUE("INITIAL_SCID");
  1163. goto malformed;
  1164. }
  1165. got_initial_scid = 1;
  1166. break;
  1167. case QUIC_TPARAM_INITIAL_MAX_DATA:
  1168. if (got_initial_max_data) {
  1169. /* must not appear more than once */
  1170. reason = TP_REASON_DUP("INITIAL_MAX_DATA");
  1171. goto malformed;
  1172. }
  1173. if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
  1174. reason = TP_REASON_MALFORMED("INITIAL_MAX_DATA");
  1175. goto malformed;
  1176. }
  1177. ossl_quic_txfc_bump_cwm(&ch->conn_txfc, v);
  1178. got_initial_max_data = 1;
  1179. break;
  1180. case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL:
  1181. if (got_initial_max_stream_data_bidi_local) {
  1182. /* must not appear more than once */
  1183. reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
  1184. goto malformed;
  1185. }
  1186. if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
  1187. reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
  1188. goto malformed;
  1189. }
  1190. /*
  1191. * This is correct; the BIDI_LOCAL TP governs streams created by
  1192. * the endpoint which sends the TP, i.e., our peer.
  1193. */
  1194. ch->rx_init_max_stream_data_bidi_remote = v;
  1195. got_initial_max_stream_data_bidi_local = 1;
  1196. break;
  1197. case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE:
  1198. if (got_initial_max_stream_data_bidi_remote) {
  1199. /* must not appear more than once */
  1200. reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
  1201. goto malformed;
  1202. }
  1203. if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
  1204. reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
  1205. goto malformed;
  1206. }
  1207. /*
  1208. * This is correct; the BIDI_REMOTE TP governs streams created
  1209. * by the endpoint which receives the TP, i.e., us.
  1210. */
  1211. ch->rx_init_max_stream_data_bidi_local = v;
  1212. /* Apply to all existing streams. */
  1213. ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_bidi, &v);
  1214. got_initial_max_stream_data_bidi_remote = 1;
  1215. break;
  1216. case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI:
  1217. if (got_initial_max_stream_data_uni) {
  1218. /* must not appear more than once */
  1219. reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_UNI");
  1220. goto malformed;
  1221. }
  1222. if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
  1223. reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_UNI");
  1224. goto malformed;
  1225. }
  1226. ch->rx_init_max_stream_data_uni = v;
  1227. /* Apply to all existing streams. */
  1228. ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_uni, &v);
  1229. got_initial_max_stream_data_uni = 1;
  1230. break;
  1231. case QUIC_TPARAM_ACK_DELAY_EXP:
  1232. if (got_ack_delay_exp) {
  1233. /* must not appear more than once */
  1234. reason = TP_REASON_DUP("ACK_DELAY_EXP");
  1235. goto malformed;
  1236. }
  1237. if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
  1238. || v > QUIC_MAX_ACK_DELAY_EXP) {
  1239. reason = TP_REASON_MALFORMED("ACK_DELAY_EXP");
  1240. goto malformed;
  1241. }
  1242. ch->rx_ack_delay_exp = (unsigned char)v;
  1243. got_ack_delay_exp = 1;
  1244. break;
  1245. case QUIC_TPARAM_MAX_ACK_DELAY:
  1246. if (got_max_ack_delay) {
  1247. /* must not appear more than once */
  1248. reason = TP_REASON_DUP("MAX_ACK_DELAY");
  1249. goto malformed;
  1250. }
  1251. if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
  1252. || v >= (((uint64_t)1) << 14)) {
  1253. reason = TP_REASON_MALFORMED("MAX_ACK_DELAY");
  1254. goto malformed;
  1255. }
  1256. ch->rx_max_ack_delay = v;
  1257. ossl_ackm_set_rx_max_ack_delay(ch->ackm,
  1258. ossl_ms2time(ch->rx_max_ack_delay));
  1259. got_max_ack_delay = 1;
  1260. break;
  1261. case QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI:
  1262. if (got_initial_max_streams_bidi) {
  1263. /* must not appear more than once */
  1264. reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_BIDI");
  1265. goto malformed;
  1266. }
  1267. if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
  1268. || v > (((uint64_t)1) << 60)) {
  1269. reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_BIDI");
  1270. goto malformed;
  1271. }
  1272. assert(ch->max_local_streams_bidi == 0);
  1273. ch->max_local_streams_bidi = v;
  1274. got_initial_max_streams_bidi = 1;
  1275. break;
  1276. case QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI:
  1277. if (got_initial_max_streams_uni) {
  1278. /* must not appear more than once */
  1279. reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_UNI");
  1280. goto malformed;
  1281. }
  1282. if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
  1283. || v > (((uint64_t)1) << 60)) {
  1284. reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_UNI");
  1285. goto malformed;
  1286. }
  1287. assert(ch->max_local_streams_uni == 0);
  1288. ch->max_local_streams_uni = v;
  1289. got_initial_max_streams_uni = 1;
  1290. break;
  1291. case QUIC_TPARAM_MAX_IDLE_TIMEOUT:
  1292. if (got_max_idle_timeout) {
  1293. /* must not appear more than once */
  1294. reason = TP_REASON_DUP("MAX_IDLE_TIMEOUT");
  1295. goto malformed;
  1296. }
  1297. if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
  1298. reason = TP_REASON_MALFORMED("MAX_IDLE_TIMEOUT");
  1299. goto malformed;
  1300. }
  1301. if (v > 0 && v < ch->max_idle_timeout)
  1302. ch->max_idle_timeout = v;
  1303. ch_update_idle(ch);
  1304. got_max_idle_timeout = 1;
  1305. break;
  1306. case QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE:
  1307. if (got_max_udp_payload_size) {
  1308. /* must not appear more than once */
  1309. reason = TP_REASON_DUP("MAX_UDP_PAYLOAD_SIZE");
  1310. goto malformed;
  1311. }
  1312. if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
  1313. || v < QUIC_MIN_INITIAL_DGRAM_LEN) {
  1314. reason = TP_REASON_MALFORMED("MAX_UDP_PAYLOAD_SIZE");
  1315. goto malformed;
  1316. }
  1317. ch->rx_max_udp_payload_size = v;
  1318. got_max_udp_payload_size = 1;
  1319. break;
  1320. case QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT:
  1321. if (got_active_conn_id_limit) {
  1322. /* must not appear more than once */
  1323. reason = TP_REASON_DUP("ACTIVE_CONN_ID_LIMIT");
  1324. goto malformed;
  1325. }
  1326. if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
  1327. || v < QUIC_MIN_ACTIVE_CONN_ID_LIMIT) {
  1328. reason = TP_REASON_MALFORMED("ACTIVE_CONN_ID_LIMIT");
  1329. goto malformed;
  1330. }
  1331. ch->rx_active_conn_id_limit = v;
  1332. got_active_conn_id_limit = 1;
  1333. break;
  1334. case QUIC_TPARAM_STATELESS_RESET_TOKEN:
  1335. if (got_stateless_reset_token) {
  1336. reason = TP_REASON_DUP("STATELESS_RESET_TOKEN");
  1337. goto malformed;
  1338. }
  1339. /*
  1340. * We must ensure a client doesn't send them because we don't have
  1341. * processing for them.
  1342. *
  1343. * TODO(QUIC SERVER): remove this restriction
  1344. */
  1345. if (ch->is_server) {
  1346. reason = TP_REASON_SERVER_ONLY("STATELESS_RESET_TOKEN");
  1347. goto malformed;
  1348. }
  1349. body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
  1350. if (body == NULL || len != QUIC_STATELESS_RESET_TOKEN_LEN) {
  1351. reason = TP_REASON_MALFORMED("STATELESS_RESET_TOKEN");
  1352. goto malformed;
  1353. }
  1354. if (!chan_add_reset_token(ch, body, ch->cur_remote_seq_num)) {
  1355. reason = TP_REASON_INTERNAL_ERROR("STATELESS_RESET_TOKEN");
  1356. goto malformed;
  1357. }
  1358. got_stateless_reset_token = 1;
  1359. break;
  1360. case QUIC_TPARAM_PREFERRED_ADDR:
  1361. {
  1362. /* TODO(QUIC FUTURE): Handle preferred address. */
  1363. QUIC_PREFERRED_ADDR pfa;
  1364. if (got_preferred_addr) {
  1365. reason = TP_REASON_DUP("PREFERRED_ADDR");
  1366. goto malformed;
  1367. }
  1368. /*
  1369. * RFC 9000 s. 18.2: "A server that chooses a zero-length
  1370. * connection ID MUST NOT provide a preferred address.
  1371. * Similarly, a server MUST NOT include a zero-length connection
  1372. * ID in this transport parameter. A client MUST treat a
  1373. * violation of these requirements as a connection error of type
  1374. * TRANSPORT_PARAMETER_ERROR."
  1375. */
  1376. if (ch->is_server) {
  1377. reason = TP_REASON_SERVER_ONLY("PREFERRED_ADDR");
  1378. goto malformed;
  1379. }
  1380. if (ch->cur_remote_dcid.id_len == 0) {
  1381. reason = "PREFERRED_ADDR provided for zero-length CID";
  1382. goto malformed;
  1383. }
  1384. if (!ossl_quic_wire_decode_transport_param_preferred_addr(&pkt, &pfa)) {
  1385. reason = TP_REASON_MALFORMED("PREFERRED_ADDR");
  1386. goto malformed;
  1387. }
  1388. if (pfa.cid.id_len == 0) {
  1389. reason = "zero-length CID in PREFERRED_ADDR";
  1390. goto malformed;
  1391. }
  1392. got_preferred_addr = 1;
  1393. }
  1394. break;
  1395. case QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION:
  1396. /* We do not currently handle migration, so nothing to do. */
  1397. if (got_disable_active_migration) {
  1398. /* must not appear more than once */
  1399. reason = TP_REASON_DUP("DISABLE_ACTIVE_MIGRATION");
  1400. goto malformed;
  1401. }
  1402. body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
  1403. if (body == NULL || len > 0) {
  1404. reason = TP_REASON_MALFORMED("DISABLE_ACTIVE_MIGRATION");
  1405. goto malformed;
  1406. }
  1407. got_disable_active_migration = 1;
  1408. break;
  1409. default:
  1410. /*
  1411. * Skip over and ignore.
  1412. *
  1413. * RFC 9000 s. 7.4: We SHOULD treat duplicated transport parameters
  1414. * as a connection error, but we are not required to. Currently,
  1415. * handle this programmatically by checking for duplicates in the
  1416. * parameters that we recognise, as above, but don't bother
  1417. * maintaining a list of duplicates for anything we don't recognise.
  1418. */
  1419. body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id,
  1420. &len);
  1421. if (body == NULL)
  1422. goto malformed;
  1423. break;
  1424. }
  1425. }
  1426. if (!got_initial_scid) {
  1427. reason = TP_REASON_REQUIRED("INITIAL_SCID");
  1428. goto malformed;
  1429. }
  1430. if (!ch->is_server) {
  1431. if (!got_orig_dcid) {
  1432. reason = TP_REASON_REQUIRED("ORIG_DCID");
  1433. goto malformed;
  1434. }
  1435. if (ch->doing_retry && !got_retry_scid) {
  1436. reason = TP_REASON_REQUIRED("RETRY_SCID");
  1437. goto malformed;
  1438. }
  1439. }
  1440. ch->got_remote_transport_params = 1;
  1441. if (got_initial_max_data || got_initial_max_stream_data_bidi_remote
  1442. || got_initial_max_streams_bidi || got_initial_max_streams_uni)
  1443. /*
  1444. * If FC credit was bumped, we may now be able to send. Update all
  1445. * streams.
  1446. */
  1447. ossl_quic_stream_map_visit(&ch->qsm, do_update, ch);
  1448. /* If we are a server, we now generate our own transport parameters. */
  1449. if (ch->is_server && !ch_generate_transport_params(ch)) {
  1450. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
  1451. "internal error");
  1452. return 0;
  1453. }
  1454. return 1;
  1455. malformed:
  1456. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_TRANSPORT_PARAMETER_ERROR,
  1457. 0, reason);
  1458. return 0;
  1459. }
  1460. /*
  1461. * Called when we want to generate transport parameters. This is called
  1462. * immediately at instantiation time for a client and after we receive the
  1463. * client's transport parameters for a server.
  1464. */
  1465. static int ch_generate_transport_params(QUIC_CHANNEL *ch)
  1466. {
  1467. int ok = 0;
  1468. BUF_MEM *buf_mem = NULL;
  1469. WPACKET wpkt;
  1470. int wpkt_valid = 0;
  1471. size_t buf_len = 0;
  1472. if (ch->local_transport_params != NULL)
  1473. goto err;
  1474. if ((buf_mem = BUF_MEM_new()) == NULL)
  1475. goto err;
  1476. if (!WPACKET_init(&wpkt, buf_mem))
  1477. goto err;
  1478. wpkt_valid = 1;
  1479. if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION,
  1480. NULL, 0) == NULL)
  1481. goto err;
  1482. if (ch->is_server) {
  1483. if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_ORIG_DCID,
  1484. &ch->init_dcid))
  1485. goto err;
  1486. if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_INITIAL_SCID,
  1487. &ch->cur_local_cid))
  1488. goto err;
  1489. } else {
  1490. /* Client always uses an empty SCID. */
  1491. if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_INITIAL_SCID,
  1492. NULL, 0) == NULL)
  1493. goto err;
  1494. }
  1495. if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_IDLE_TIMEOUT,
  1496. ch->max_idle_timeout))
  1497. goto err;
  1498. if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE,
  1499. QUIC_MIN_INITIAL_DGRAM_LEN))
  1500. goto err;
  1501. if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT,
  1502. QUIC_MIN_ACTIVE_CONN_ID_LIMIT))
  1503. goto err;
  1504. if (ch->tx_max_ack_delay != QUIC_DEFAULT_MAX_ACK_DELAY
  1505. && !ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_ACK_DELAY,
  1506. ch->tx_max_ack_delay))
  1507. goto err;
  1508. if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_DATA,
  1509. ossl_quic_rxfc_get_cwm(&ch->conn_rxfc)))
  1510. goto err;
  1511. /* Send the default CWM for a new RXFC. */
  1512. if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL,
  1513. ch->tx_init_max_stream_data_bidi_local))
  1514. goto err;
  1515. if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE,
  1516. ch->tx_init_max_stream_data_bidi_remote))
  1517. goto err;
  1518. if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI,
  1519. ch->tx_init_max_stream_data_uni))
  1520. goto err;
  1521. if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI,
  1522. ossl_quic_rxfc_get_cwm(&ch->max_streams_bidi_rxfc)))
  1523. goto err;
  1524. if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI,
  1525. ossl_quic_rxfc_get_cwm(&ch->max_streams_uni_rxfc)))
  1526. goto err;
  1527. if (!WPACKET_finish(&wpkt))
  1528. goto err;
  1529. wpkt_valid = 0;
  1530. if (!WPACKET_get_total_written(&wpkt, &buf_len))
  1531. goto err;
  1532. ch->local_transport_params = (unsigned char *)buf_mem->data;
  1533. buf_mem->data = NULL;
  1534. if (!ossl_quic_tls_set_transport_params(ch->qtls, ch->local_transport_params,
  1535. buf_len))
  1536. goto err;
  1537. ok = 1;
  1538. err:
  1539. if (wpkt_valid)
  1540. WPACKET_cleanup(&wpkt);
  1541. BUF_MEM_free(buf_mem);
  1542. return ok;
  1543. }
  1544. /*
  1545. * QUIC Channel: Ticker-Mutator
  1546. * ============================
  1547. */
  1548. /*
  1549. * The central ticker function called by the reactor. This does everything, or
  1550. * at least everything network I/O related. Best effort - not allowed to fail
  1551. * "loudly".
  1552. */
  1553. static void ch_tick(QUIC_TICK_RESULT *res, void *arg, uint32_t flags)
  1554. {
  1555. OSSL_TIME now, deadline;
  1556. QUIC_CHANNEL *ch = arg;
  1557. int channel_only = (flags & QUIC_REACTOR_TICK_FLAG_CHANNEL_ONLY) != 0;
  1558. /*
  1559. * When we tick the QUIC connection, we do everything we need to do
  1560. * periodically. In order, we:
  1561. *
  1562. * - handle any incoming data from the network;
  1563. * - handle any timer events which are due to fire (ACKM, etc.)
  1564. * - write any data to the network due to be sent, to the extent
  1565. * possible;
  1566. * - determine the time at which we should next be ticked.
  1567. */
  1568. /* If we are in the TERMINATED state, there is nothing to do. */
  1569. if (ossl_quic_channel_is_terminated(ch)) {
  1570. res->net_read_desired = 0;
  1571. res->net_write_desired = 0;
  1572. res->tick_deadline = ossl_time_infinite();
  1573. return;
  1574. }
  1575. /*
  1576. * If we are in the TERMINATING state, check if the terminating timer has
  1577. * expired.
  1578. */
  1579. if (ossl_quic_channel_is_terminating(ch)) {
  1580. now = get_time(ch);
  1581. if (ossl_time_compare(now, ch->terminate_deadline) >= 0) {
  1582. ch_on_terminating_timeout(ch);
  1583. res->net_read_desired = 0;
  1584. res->net_write_desired = 0;
  1585. res->tick_deadline = ossl_time_infinite();
  1586. return; /* abort normal processing, nothing to do */
  1587. }
  1588. }
  1589. if (!ch->inhibit_tick) {
  1590. /* Handle RXKU timeouts. */
  1591. ch_rxku_tick(ch);
  1592. /* Handle any incoming data from network. */
  1593. ch_rx_pre(ch);
  1594. do {
  1595. /* Process queued incoming packets. */
  1596. ch->did_tls_tick = 0;
  1597. ch->have_new_rx_secret = 0;
  1598. ch_rx(ch, channel_only);
  1599. /*
  1600. * Allow the handshake layer to check for any new incoming data and
  1601. * generate new outgoing data.
  1602. */
  1603. if (!ch->did_tls_tick)
  1604. ch_tick_tls(ch, channel_only);
  1605. /*
  1606. * If the handshake layer gave us a new secret, we need to do RX
  1607. * again because packets that were not previously processable and
  1608. * were deferred might now be processable.
  1609. *
  1610. * TODO(QUIC FUTURE): Consider handling this in the yield_secret callback.
  1611. */
  1612. } while (ch->have_new_rx_secret);
  1613. }
  1614. /*
  1615. * Handle any timer events which are due to fire; namely, the loss
  1616. * detection deadline and the idle timeout.
  1617. *
  1618. * ACKM ACK generation deadline is polled by TXP, so we don't need to
  1619. * handle it here.
  1620. */
  1621. now = get_time(ch);
  1622. if (ossl_time_compare(now, ch->idle_deadline) >= 0) {
  1623. /*
  1624. * Idle timeout differs from normal protocol violation because we do
  1625. * not send a CONN_CLOSE frame; go straight to TERMINATED.
  1626. */
  1627. if (!ch->inhibit_tick)
  1628. ch_on_idle_timeout(ch);
  1629. res->net_read_desired = 0;
  1630. res->net_write_desired = 0;
  1631. res->tick_deadline = ossl_time_infinite();
  1632. return;
  1633. }
  1634. if (!ch->inhibit_tick) {
  1635. deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
  1636. if (!ossl_time_is_zero(deadline)
  1637. && ossl_time_compare(now, deadline) >= 0)
  1638. ossl_ackm_on_timeout(ch->ackm);
  1639. /* If a ping is due, inform TXP. */
  1640. if (ossl_time_compare(now, ch->ping_deadline) >= 0) {
  1641. int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level);
  1642. ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space);
  1643. /*
  1644. * If we have no CC budget at this time we cannot process the above
  1645. * PING request immediately. In any case we have scheduled the
  1646. * request so bump the ping deadline. If we don't do this we will
  1647. * busy-loop endlessly as the above deadline comparison condition
  1648. * will still be met.
  1649. */
  1650. ch_update_ping_deadline(ch);
  1651. }
  1652. /* Write any data to the network due to be sent. */
  1653. ch_tx(ch);
  1654. /* Do stream GC. */
  1655. ossl_quic_stream_map_gc(&ch->qsm);
  1656. }
  1657. /* Determine the time at which we should next be ticked. */
  1658. res->tick_deadline = ch_determine_next_tick_deadline(ch);
  1659. /*
  1660. * Always process network input unless we are now terminated.
  1661. * Although we had not terminated at the beginning of this tick, network
  1662. * errors in ch_rx_pre() or ch_tx() may have caused us to transition to the
  1663. * Terminated state.
  1664. */
  1665. res->net_read_desired = !ossl_quic_channel_is_terminated(ch);
  1666. /* We want to write to the network if we have any in our queue. */
  1667. res->net_write_desired
  1668. = (!ossl_quic_channel_is_terminated(ch)
  1669. && ossl_qtx_get_queue_len_datagrams(ch->qtx) > 0);
  1670. }
  1671. static int ch_tick_tls(QUIC_CHANNEL *ch, int channel_only)
  1672. {
  1673. uint64_t error_code;
  1674. const char *error_msg;
  1675. ERR_STATE *error_state = NULL;
  1676. if (channel_only)
  1677. return 1;
  1678. ch->did_tls_tick = 1;
  1679. ossl_quic_tls_tick(ch->qtls);
  1680. if (ossl_quic_tls_get_error(ch->qtls, &error_code, &error_msg,
  1681. &error_state)) {
  1682. ossl_quic_channel_raise_protocol_error_state(ch, error_code, 0,
  1683. error_msg, error_state);
  1684. return 0;
  1685. }
  1686. return 1;
  1687. }
  1688. /* Process incoming datagrams, if any. */
  1689. static void ch_rx_pre(QUIC_CHANNEL *ch)
  1690. {
  1691. int ret;
  1692. if (!ch->is_server && !ch->have_sent_any_pkt)
  1693. return;
  1694. /*
  1695. * Get DEMUX to BIO_recvmmsg from the network and queue incoming datagrams
  1696. * to the appropriate QRX instance.
  1697. */
  1698. ret = ossl_quic_demux_pump(ch->demux);
  1699. if (ret == QUIC_DEMUX_PUMP_RES_STATELESS_RESET)
  1700. ch_stateless_reset(ch);
  1701. else if (ret == QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL)
  1702. /*
  1703. * We don't care about transient failure, but permanent failure means we
  1704. * should tear down the connection as though a protocol violation
  1705. * occurred. Skip straight to the Terminating state as there is no point
  1706. * trying to send CONNECTION_CLOSE frames if the network BIO is not
  1707. * operating correctly.
  1708. */
  1709. ch_raise_net_error(ch);
  1710. }
  1711. /* Check incoming forged packet limit and terminate connection if needed. */
  1712. static void ch_rx_check_forged_pkt_limit(QUIC_CHANNEL *ch)
  1713. {
  1714. uint32_t enc_level;
  1715. uint64_t limit = UINT64_MAX, l;
  1716. for (enc_level = QUIC_ENC_LEVEL_INITIAL;
  1717. enc_level < QUIC_ENC_LEVEL_NUM;
  1718. ++enc_level)
  1719. {
  1720. /*
  1721. * Different ELs can have different AEADs which can in turn impose
  1722. * different limits, so use the lowest value of any currently valid EL.
  1723. */
  1724. if ((ch->el_discarded & (1U << enc_level)) != 0)
  1725. continue;
  1726. if (enc_level > ch->rx_enc_level)
  1727. break;
  1728. l = ossl_qrx_get_max_forged_pkt_count(ch->qrx, enc_level);
  1729. if (l < limit)
  1730. limit = l;
  1731. }
  1732. if (ossl_qrx_get_cur_forged_pkt_count(ch->qrx) < limit)
  1733. return;
  1734. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_AEAD_LIMIT_REACHED, 0,
  1735. "forgery limit");
  1736. }
  1737. /* Process queued incoming packets and handle frames, if any. */
  1738. static int ch_rx(QUIC_CHANNEL *ch, int channel_only)
  1739. {
  1740. int handled_any = 0;
  1741. const int closing = ossl_quic_channel_is_closing(ch);
  1742. if (!ch->is_server && !ch->have_sent_any_pkt)
  1743. /*
  1744. * We have not sent anything yet, therefore there is no need to check
  1745. * for incoming data.
  1746. */
  1747. return 1;
  1748. for (;;) {
  1749. assert(ch->qrx_pkt == NULL);
  1750. if (!ossl_qrx_read_pkt(ch->qrx, &ch->qrx_pkt))
  1751. break;
  1752. /* Track the amount of data received while in the closing state */
  1753. if (closing)
  1754. ossl_quic_tx_packetiser_record_received_closing_bytes(
  1755. ch->txp, ch->qrx_pkt->hdr->len);
  1756. if (!handled_any) {
  1757. ch_update_idle(ch);
  1758. ch_update_ping_deadline(ch);
  1759. }
  1760. ch_rx_handle_packet(ch, channel_only); /* best effort */
  1761. /*
  1762. * Regardless of the outcome of frame handling, unref the packet.
  1763. * This will free the packet unless something added another
  1764. * reference to it during frame processing.
  1765. */
  1766. ossl_qrx_pkt_release(ch->qrx_pkt);
  1767. ch->qrx_pkt = NULL;
  1768. ch->have_sent_ack_eliciting_since_rx = 0;
  1769. handled_any = 1;
  1770. }
  1771. ch_rx_check_forged_pkt_limit(ch);
  1772. /*
  1773. * When in TERMINATING - CLOSING, generate a CONN_CLOSE frame whenever we
  1774. * process one or more incoming packets.
  1775. */
  1776. if (handled_any && closing)
  1777. ch->conn_close_queued = 1;
  1778. return 1;
  1779. }
  1780. static int bio_addr_eq(const BIO_ADDR *a, const BIO_ADDR *b)
  1781. {
  1782. if (BIO_ADDR_family(a) != BIO_ADDR_family(b))
  1783. return 0;
  1784. switch (BIO_ADDR_family(a)) {
  1785. case AF_INET:
  1786. return !memcmp(&a->s_in.sin_addr,
  1787. &b->s_in.sin_addr,
  1788. sizeof(a->s_in.sin_addr))
  1789. && a->s_in.sin_port == b->s_in.sin_port;
  1790. #if OPENSSL_USE_IPV6
  1791. case AF_INET6:
  1792. return !memcmp(&a->s_in6.sin6_addr,
  1793. &b->s_in6.sin6_addr,
  1794. sizeof(a->s_in6.sin6_addr))
  1795. && a->s_in6.sin6_port == b->s_in6.sin6_port;
  1796. #endif
  1797. default:
  1798. return 0; /* not supported */
  1799. }
  1800. return 1;
  1801. }
  1802. /* Handles the packet currently in ch->qrx_pkt->hdr. */
  1803. static void ch_rx_handle_packet(QUIC_CHANNEL *ch, int channel_only)
  1804. {
  1805. uint32_t enc_level;
  1806. int old_have_processed_any_pkt = ch->have_processed_any_pkt;
  1807. assert(ch->qrx_pkt != NULL);
  1808. /*
  1809. * RFC 9000 s. 10.2.1 Closing Connection State:
  1810. * An endpoint that is closing is not required to process any
  1811. * received frame.
  1812. */
  1813. if (!ossl_quic_channel_is_active(ch))
  1814. return;
  1815. if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)) {
  1816. if (!ch->have_received_enc_pkt) {
  1817. ch->cur_remote_dcid = ch->init_scid = ch->qrx_pkt->hdr->src_conn_id;
  1818. ch->have_received_enc_pkt = 1;
  1819. /*
  1820. * We change to using the SCID in the first Initial packet as the
  1821. * DCID.
  1822. */
  1823. ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->init_scid);
  1824. }
  1825. enc_level = ossl_quic_pkt_type_to_enc_level(ch->qrx_pkt->hdr->type);
  1826. if ((ch->el_discarded & (1U << enc_level)) != 0)
  1827. /* Do not process packets from ELs we have already discarded. */
  1828. return;
  1829. }
  1830. /*
  1831. * RFC 9000 s. 9.6: "If a client receives packets from a new server address
  1832. * when the client has not initiated a migration to that address, the client
  1833. * SHOULD discard these packets."
  1834. *
  1835. * We need to be a bit careful here as due to the BIO abstraction layer an
  1836. * application is liable to be weird and lie to us about peer addresses.
  1837. * Only apply this check if we actually are using a real AF_INET or AF_INET6
  1838. * address.
  1839. */
  1840. if (!ch->is_server
  1841. && ch->qrx_pkt->peer != NULL
  1842. && (
  1843. BIO_ADDR_family(&ch->cur_peer_addr) == AF_INET
  1844. #if OPENSSL_USE_IPV6
  1845. || BIO_ADDR_family(&ch->cur_peer_addr) == AF_INET6
  1846. #endif
  1847. )
  1848. && !bio_addr_eq(ch->qrx_pkt->peer, &ch->cur_peer_addr))
  1849. return;
  1850. if (!ch->is_server
  1851. && ch->have_received_enc_pkt
  1852. && ossl_quic_pkt_type_has_scid(ch->qrx_pkt->hdr->type)) {
  1853. /*
  1854. * RFC 9000 s. 7.2: "Once a client has received a valid Initial packet
  1855. * from the server, it MUST discard any subsequent packet it receives on
  1856. * that connection with a different SCID."
  1857. */
  1858. if (!ossl_quic_conn_id_eq(&ch->qrx_pkt->hdr->src_conn_id,
  1859. &ch->init_scid))
  1860. return;
  1861. }
  1862. if (ossl_quic_pkt_type_has_version(ch->qrx_pkt->hdr->type)
  1863. && ch->qrx_pkt->hdr->version != QUIC_VERSION_1)
  1864. /*
  1865. * RFC 9000 s. 5.2.1: If a client receives a packet that uses a
  1866. * different version than it initially selected, it MUST discard the
  1867. * packet. We only ever use v1, so require it.
  1868. */
  1869. return;
  1870. ch->have_processed_any_pkt = 1;
  1871. /*
  1872. * RFC 9000 s. 17.2: "An endpoint MUST treat receipt of a packet that has a
  1873. * non-zero value for [the reserved bits] after removing both packet and
  1874. * header protection as a connection error of type PROTOCOL_VIOLATION."
  1875. */
  1876. if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)
  1877. && ch->qrx_pkt->hdr->reserved != 0) {
  1878. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
  1879. 0, "packet header reserved bits");
  1880. return;
  1881. }
  1882. /* Handle incoming packet. */
  1883. switch (ch->qrx_pkt->hdr->type) {
  1884. case QUIC_PKT_TYPE_RETRY:
  1885. if (ch->doing_retry || ch->is_server)
  1886. /*
  1887. * It is not allowed to ask a client to do a retry more than
  1888. * once. Clients may not send retries.
  1889. */
  1890. return;
  1891. /*
  1892. * RFC 9000 s 17.2.5.2: After the client has received and processed an
  1893. * Initial or Retry packet from the server, it MUST discard any
  1894. * subsequent Retry packets that it receives.
  1895. */
  1896. if (ch->have_received_enc_pkt)
  1897. return;
  1898. if (ch->qrx_pkt->hdr->len <= QUIC_RETRY_INTEGRITY_TAG_LEN)
  1899. /* Packets with zero-length Retry Tokens are invalid. */
  1900. return;
  1901. /*
  1902. * TODO(QUIC FUTURE): Theoretically this should probably be in the QRX.
  1903. * However because validation is dependent on context (namely the
  1904. * client's initial DCID) we can't do this cleanly. In the future we
  1905. * should probably add a callback to the QRX to let it call us (via
  1906. * the DEMUX) and ask us about the correct original DCID, rather
  1907. * than allow the QRX to emit a potentially malformed packet to the
  1908. * upper layers. However, special casing this will do for now.
  1909. */
  1910. if (!ossl_quic_validate_retry_integrity_tag(ch->libctx,
  1911. ch->propq,
  1912. ch->qrx_pkt->hdr,
  1913. &ch->init_dcid))
  1914. /* Malformed retry packet, ignore. */
  1915. return;
  1916. if (!ch_retry(ch, ch->qrx_pkt->hdr->data,
  1917. ch->qrx_pkt->hdr->len - QUIC_RETRY_INTEGRITY_TAG_LEN,
  1918. &ch->qrx_pkt->hdr->src_conn_id))
  1919. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR,
  1920. 0, "handling retry packet");
  1921. break;
  1922. case QUIC_PKT_TYPE_0RTT:
  1923. if (!ch->is_server)
  1924. /* Clients should never receive 0-RTT packets. */
  1925. return;
  1926. /*
  1927. * TODO(QUIC 0RTT): Implement 0-RTT on the server side. We currently
  1928. * do not need to implement this as a client can only do 0-RTT if we
  1929. * have given it permission to in a previous session.
  1930. */
  1931. break;
  1932. case QUIC_PKT_TYPE_INITIAL:
  1933. case QUIC_PKT_TYPE_HANDSHAKE:
  1934. case QUIC_PKT_TYPE_1RTT:
  1935. if (ch->is_server && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_HANDSHAKE)
  1936. /*
  1937. * We automatically drop INITIAL EL keys when first successfully
  1938. * decrypting a HANDSHAKE packet, as per the RFC.
  1939. */
  1940. ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
  1941. if (ch->rxku_in_progress
  1942. && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_1RTT
  1943. && ch->qrx_pkt->pn >= ch->rxku_trigger_pn
  1944. && ch->qrx_pkt->key_epoch < ossl_qrx_get_key_epoch(ch->qrx)) {
  1945. /*
  1946. * RFC 9001 s. 6.4: Packets with higher packet numbers MUST be
  1947. * protected with either the same or newer packet protection keys
  1948. * than packets with lower packet numbers. An endpoint that
  1949. * successfully removes protection with old keys when newer keys
  1950. * were used for packets with lower packet numbers MUST treat this
  1951. * as a connection error of type KEY_UPDATE_ERROR.
  1952. */
  1953. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_KEY_UPDATE_ERROR,
  1954. 0, "new packet with old keys");
  1955. break;
  1956. }
  1957. if (!ch->is_server
  1958. && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_INITIAL
  1959. && ch->qrx_pkt->hdr->token_len > 0) {
  1960. /*
  1961. * RFC 9000 s. 17.2.2: Clients that receive an Initial packet with a
  1962. * non-zero Token Length field MUST either discard the packet or
  1963. * generate a connection error of type PROTOCOL_VIOLATION.
  1964. *
  1965. * TODO(QUIC FUTURE): consider the implications of RFC 9000 s. 10.2.3
  1966. * Immediate Close during the Handshake:
  1967. * However, at the cost of reducing feedback about
  1968. * errors for legitimate peers, some forms of denial of
  1969. * service can be made more difficult for an attacker
  1970. * if endpoints discard illegal packets rather than
  1971. * terminating a connection with CONNECTION_CLOSE. For
  1972. * this reason, endpoints MAY discard packets rather
  1973. * than immediately close if errors are detected in
  1974. * packets that lack authentication.
  1975. * I.e. should we drop this packet instead of closing the connection?
  1976. */
  1977. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
  1978. 0, "client received initial token");
  1979. break;
  1980. }
  1981. /* This packet contains frames, pass to the RXDP. */
  1982. ossl_quic_handle_frames(ch, ch->qrx_pkt); /* best effort */
  1983. if (ch->did_crypto_frame)
  1984. ch_tick_tls(ch, channel_only);
  1985. break;
  1986. case QUIC_PKT_TYPE_VERSION_NEG:
  1987. /*
  1988. * "A client MUST discard any Version Negotiation packet if it has
  1989. * received and successfully processed any other packet."
  1990. */
  1991. if (!old_have_processed_any_pkt)
  1992. ch_rx_handle_version_neg(ch, ch->qrx_pkt);
  1993. break;
  1994. default:
  1995. assert(0);
  1996. break;
  1997. }
  1998. }
  1999. static void ch_rx_handle_version_neg(QUIC_CHANNEL *ch, OSSL_QRX_PKT *pkt)
  2000. {
  2001. /*
  2002. * We do not support version negotiation at this time. As per RFC 9000 s.
  2003. * 6.2., we MUST abandon the connection attempt if we receive a Version
  2004. * Negotiation packet, unless we have already successfully processed another
  2005. * incoming packet, or the packet lists the QUIC version we want to use.
  2006. */
  2007. PACKET vpkt;
  2008. unsigned long v;
  2009. if (!PACKET_buf_init(&vpkt, pkt->hdr->data, pkt->hdr->len))
  2010. return;
  2011. while (PACKET_remaining(&vpkt) > 0) {
  2012. if (!PACKET_get_net_4(&vpkt, &v))
  2013. break;
  2014. if ((uint32_t)v == QUIC_VERSION_1)
  2015. return;
  2016. }
  2017. /* No match, this is a failure case. */
  2018. ch_raise_version_neg_failure(ch);
  2019. }
  2020. static void ch_raise_version_neg_failure(QUIC_CHANNEL *ch)
  2021. {
  2022. QUIC_TERMINATE_CAUSE tcause = {0};
  2023. tcause.error_code = QUIC_ERR_CONNECTION_REFUSED;
  2024. tcause.reason = "version negotiation failure";
  2025. tcause.reason_len = strlen(tcause.reason);
  2026. /*
  2027. * Skip TERMINATING state; this is not considered a protocol error and we do
  2028. * not send CONNECTION_CLOSE.
  2029. */
  2030. ch_start_terminating(ch, &tcause, 1);
  2031. }
  2032. /*
  2033. * This is called by the demux when we get a packet not destined for any known
  2034. * DCID.
  2035. */
  2036. static void ch_default_packet_handler(QUIC_URXE *e, void *arg)
  2037. {
  2038. QUIC_CHANNEL *ch = arg;
  2039. PACKET pkt;
  2040. QUIC_PKT_HDR hdr;
  2041. if (!ossl_assert(ch->is_server))
  2042. goto undesirable;
  2043. /*
  2044. * We only support one connection to our server currently, so if we already
  2045. * started one, ignore any new connection attempts.
  2046. */
  2047. if (ch->state != QUIC_CHANNEL_STATE_IDLE)
  2048. goto undesirable;
  2049. /*
  2050. * We have got a packet for an unknown DCID. This might be an attempt to
  2051. * open a new connection.
  2052. */
  2053. if (e->data_len < QUIC_MIN_INITIAL_DGRAM_LEN)
  2054. goto undesirable;
  2055. if (!PACKET_buf_init(&pkt, ossl_quic_urxe_data(e), e->data_len))
  2056. goto err;
  2057. /*
  2058. * We set short_conn_id_len to SIZE_MAX here which will cause the decode
  2059. * operation to fail if we get a 1-RTT packet. This is fine since we only
  2060. * care about Initial packets.
  2061. */
  2062. if (!ossl_quic_wire_decode_pkt_hdr(&pkt, SIZE_MAX, 1, 0, &hdr, NULL))
  2063. goto undesirable;
  2064. switch (hdr.version) {
  2065. case QUIC_VERSION_1:
  2066. break;
  2067. case QUIC_VERSION_NONE:
  2068. default:
  2069. /* Unknown version or proactive version negotiation request, bail. */
  2070. /* TODO(QUIC SERVER): Handle version negotiation on server side */
  2071. goto undesirable;
  2072. }
  2073. /*
  2074. * We only care about Initial packets which might be trying to establish a
  2075. * connection.
  2076. */
  2077. if (hdr.type != QUIC_PKT_TYPE_INITIAL)
  2078. goto undesirable;
  2079. /*
  2080. * Assume this is a valid attempt to initiate a connection.
  2081. *
  2082. * We do not register the DCID in the initial packet we received and that
  2083. * DCID is not actually used again, thus after provisioning the correct
  2084. * Initial keys derived from it (which is done in the call below) we pass
  2085. * the received packet directly to the QRX so that it can process it as a
  2086. * one-time thing, instead of going through the usual DEMUX DCID-based
  2087. * routing.
  2088. */
  2089. if (!ch_server_on_new_conn(ch, &e->peer,
  2090. &hdr.src_conn_id,
  2091. &hdr.dst_conn_id))
  2092. goto err;
  2093. ossl_qrx_inject_urxe(ch->qrx, e);
  2094. return;
  2095. err:
  2096. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
  2097. "internal error");
  2098. undesirable:
  2099. ossl_quic_demux_release_urxe(ch->demux, e);
  2100. }
  2101. /* Try to generate packets and if possible, flush them to the network. */
  2102. static int ch_tx(QUIC_CHANNEL *ch)
  2103. {
  2104. QUIC_TXP_STATUS status;
  2105. int res;
  2106. /*
  2107. * RFC 9000 s. 10.2.2: Draining Connection State:
  2108. * While otherwise identical to the closing state, an endpoint
  2109. * in the draining state MUST NOT send any packets.
  2110. * and:
  2111. * An endpoint MUST NOT send further packets.
  2112. */
  2113. if (ossl_quic_channel_is_draining(ch))
  2114. return 0;
  2115. if (ossl_quic_channel_is_closing(ch)) {
  2116. /*
  2117. * While closing, only send CONN_CLOSE if we've received more traffic
  2118. * from the peer. Once we tell the TXP to generate CONN_CLOSE, all
  2119. * future calls to it generate CONN_CLOSE frames, so otherwise we would
  2120. * just constantly generate CONN_CLOSE frames.
  2121. *
  2122. * Confirming to RFC 9000 s. 10.2.1 Closing Connection State:
  2123. * An endpoint SHOULD limit the rate at which it generates
  2124. * packets in the closing state.
  2125. */
  2126. if (!ch->conn_close_queued)
  2127. return 0;
  2128. ch->conn_close_queued = 0;
  2129. }
  2130. /* Do TXKU if we need to. */
  2131. ch_maybe_trigger_spontaneous_txku(ch);
  2132. ch->rxku_pending_confirm_done = 0;
  2133. /* Loop until we stop generating packets to send */
  2134. do {
  2135. /*
  2136. * Send packet, if we need to. Best effort. The TXP consults the CC and
  2137. * applies any limitations imposed by it, so we don't need to do it here.
  2138. *
  2139. * Best effort. In particular if TXP fails for some reason we should
  2140. * still flush any queued packets which we already generated.
  2141. */
  2142. res = ossl_quic_tx_packetiser_generate(ch->txp, &status);
  2143. if (status.sent_pkt > 0) {
  2144. ch->have_sent_any_pkt = 1; /* Packet(s) were sent */
  2145. /*
  2146. * RFC 9000 s. 10.1. 'An endpoint also restarts its idle timer when
  2147. * sending an ack-eliciting packet if no other ack-eliciting packets
  2148. * have been sent since last receiving and processing a packet.'
  2149. */
  2150. if (status.sent_ack_eliciting
  2151. && !ch->have_sent_ack_eliciting_since_rx) {
  2152. ch_update_idle(ch);
  2153. ch->have_sent_ack_eliciting_since_rx = 1;
  2154. }
  2155. if (!ch->is_server && status.sent_handshake)
  2156. /*
  2157. * RFC 9001 s. 4.9.1: A client MUST discard Initial keys when it
  2158. * first sends a Handshake packet.
  2159. */
  2160. ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
  2161. if (ch->rxku_pending_confirm_done)
  2162. ch->rxku_pending_confirm = 0;
  2163. ch_update_ping_deadline(ch);
  2164. }
  2165. if (!res) {
  2166. /*
  2167. * One case where TXP can fail is if we reach a TX PN of 2**62 - 1.
  2168. * As per RFC 9000 s. 12.3, if this happens we MUST close the
  2169. * connection without sending a CONNECTION_CLOSE frame. This is
  2170. * actually handled as an emergent consequence of our design, as the
  2171. * TX packetiser will never transmit another packet when the TX PN
  2172. * reaches the limit.
  2173. *
  2174. * Calling the below function terminates the connection; its attempt
  2175. * to schedule a CONNECTION_CLOSE frame will not actually cause a
  2176. * packet to be transmitted for this reason.
  2177. */
  2178. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR,
  2179. 0,
  2180. "internal error (txp generate)");
  2181. break;
  2182. }
  2183. } while (status.sent_pkt > 0);
  2184. /* Flush packets to network. */
  2185. switch (ossl_qtx_flush_net(ch->qtx)) {
  2186. case QTX_FLUSH_NET_RES_OK:
  2187. case QTX_FLUSH_NET_RES_TRANSIENT_FAIL:
  2188. /* Best effort, done for now. */
  2189. break;
  2190. case QTX_FLUSH_NET_RES_PERMANENT_FAIL:
  2191. default:
  2192. /* Permanent underlying network BIO, start terminating. */
  2193. ch_raise_net_error(ch);
  2194. break;
  2195. }
  2196. return 1;
  2197. }
  2198. /* Determine next tick deadline. */
  2199. static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch)
  2200. {
  2201. OSSL_TIME deadline;
  2202. int i;
  2203. if (ossl_quic_channel_is_terminated(ch))
  2204. return ossl_time_infinite();
  2205. deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
  2206. if (ossl_time_is_zero(deadline))
  2207. deadline = ossl_time_infinite();
  2208. /*
  2209. * Check the ack deadline for all enc_levels that are actually provisioned.
  2210. * ACKs aren't restricted by CC.
  2211. */
  2212. for (i = 0; i < QUIC_ENC_LEVEL_NUM; i++) {
  2213. if (ossl_qtx_is_enc_level_provisioned(ch->qtx, i)) {
  2214. deadline = ossl_time_min(deadline,
  2215. ossl_ackm_get_ack_deadline(ch->ackm,
  2216. ossl_quic_enc_level_to_pn_space(i)));
  2217. }
  2218. }
  2219. /*
  2220. * When do we need to send an ACK-eliciting packet to reset the idle
  2221. * deadline timer for the peer?
  2222. */
  2223. if (!ossl_time_is_infinite(ch->ping_deadline))
  2224. deadline = ossl_time_min(deadline, ch->ping_deadline);
  2225. /* Apply TXP wakeup deadline. */
  2226. deadline = ossl_time_min(deadline,
  2227. ossl_quic_tx_packetiser_get_deadline(ch->txp));
  2228. /* Is the terminating timer armed? */
  2229. if (ossl_quic_channel_is_terminating(ch))
  2230. deadline = ossl_time_min(deadline,
  2231. ch->terminate_deadline);
  2232. else if (!ossl_time_is_infinite(ch->idle_deadline))
  2233. deadline = ossl_time_min(deadline,
  2234. ch->idle_deadline);
  2235. /* When does the RXKU process complete? */
  2236. if (ch->rxku_in_progress)
  2237. deadline = ossl_time_min(deadline, ch->rxku_update_end_deadline);
  2238. return deadline;
  2239. }
  2240. /*
  2241. * QUIC Channel: Network BIO Configuration
  2242. * =======================================
  2243. */
  2244. /* Determines whether we can support a given poll descriptor. */
  2245. static int validate_poll_descriptor(const BIO_POLL_DESCRIPTOR *d)
  2246. {
  2247. if (d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD && d->value.fd < 0) {
  2248. ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
  2249. return 0;
  2250. }
  2251. return 1;
  2252. }
  2253. BIO *ossl_quic_channel_get_net_rbio(QUIC_CHANNEL *ch)
  2254. {
  2255. return ch->net_rbio;
  2256. }
  2257. BIO *ossl_quic_channel_get_net_wbio(QUIC_CHANNEL *ch)
  2258. {
  2259. return ch->net_wbio;
  2260. }
  2261. static int ch_update_poll_desc(QUIC_CHANNEL *ch, BIO *net_bio, int for_write)
  2262. {
  2263. BIO_POLL_DESCRIPTOR d = {0};
  2264. if (net_bio == NULL
  2265. || (!for_write && !BIO_get_rpoll_descriptor(net_bio, &d))
  2266. || (for_write && !BIO_get_wpoll_descriptor(net_bio, &d)))
  2267. /* Non-pollable BIO */
  2268. d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
  2269. if (!validate_poll_descriptor(&d))
  2270. return 0;
  2271. if (for_write)
  2272. ossl_quic_reactor_set_poll_w(&ch->rtor, &d);
  2273. else
  2274. ossl_quic_reactor_set_poll_r(&ch->rtor, &d);
  2275. return 1;
  2276. }
  2277. int ossl_quic_channel_update_poll_descriptors(QUIC_CHANNEL *ch)
  2278. {
  2279. int ok = 1;
  2280. if (!ch_update_poll_desc(ch, ch->net_rbio, /*for_write=*/0))
  2281. ok = 0;
  2282. if (!ch_update_poll_desc(ch, ch->net_wbio, /*for_write=*/1))
  2283. ok = 0;
  2284. return ok;
  2285. }
  2286. /*
  2287. * QUIC_CHANNEL does not ref any BIO it is provided with, nor is any ref
  2288. * transferred to it. The caller (i.e., QUIC_CONNECTION) is responsible for
  2289. * ensuring the BIO lasts until the channel is freed or the BIO is switched out
  2290. * for another BIO by a subsequent successful call to this function.
  2291. */
  2292. int ossl_quic_channel_set_net_rbio(QUIC_CHANNEL *ch, BIO *net_rbio)
  2293. {
  2294. if (ch->net_rbio == net_rbio)
  2295. return 1;
  2296. if (!ch_update_poll_desc(ch, net_rbio, /*for_write=*/0))
  2297. return 0;
  2298. ossl_quic_demux_set_bio(ch->demux, net_rbio);
  2299. ch->net_rbio = net_rbio;
  2300. return 1;
  2301. }
  2302. int ossl_quic_channel_set_net_wbio(QUIC_CHANNEL *ch, BIO *net_wbio)
  2303. {
  2304. if (ch->net_wbio == net_wbio)
  2305. return 1;
  2306. if (!ch_update_poll_desc(ch, net_wbio, /*for_write=*/1))
  2307. return 0;
  2308. ossl_qtx_set_bio(ch->qtx, net_wbio);
  2309. ch->net_wbio = net_wbio;
  2310. return 1;
  2311. }
  2312. /*
  2313. * QUIC Channel: Lifecycle Events
  2314. * ==============================
  2315. */
  2316. int ossl_quic_channel_start(QUIC_CHANNEL *ch)
  2317. {
  2318. if (ch->is_server)
  2319. /*
  2320. * This is not used by the server. The server moves to active
  2321. * automatically on receiving an incoming connection.
  2322. */
  2323. return 0;
  2324. if (ch->state != QUIC_CHANNEL_STATE_IDLE)
  2325. /* Calls to connect are idempotent */
  2326. return 1;
  2327. /* Inform QTX of peer address. */
  2328. if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
  2329. return 0;
  2330. /* Plug in secrets for the Initial EL. */
  2331. if (!ossl_quic_provide_initial_secret(ch->libctx,
  2332. ch->propq,
  2333. &ch->init_dcid,
  2334. ch->is_server,
  2335. ch->qrx, ch->qtx))
  2336. return 0;
  2337. /* Change state. */
  2338. ch->state = QUIC_CHANNEL_STATE_ACTIVE;
  2339. ch->doing_proactive_ver_neg = 0; /* not currently supported */
  2340. /* Handshake layer: start (e.g. send CH). */
  2341. if (!ch_tick_tls(ch, /*channel_only=*/0))
  2342. return 0;
  2343. ossl_quic_reactor_tick(&ch->rtor, 0); /* best effort */
  2344. return 1;
  2345. }
  2346. /* Start a locally initiated connection shutdown. */
  2347. void ossl_quic_channel_local_close(QUIC_CHANNEL *ch, uint64_t app_error_code,
  2348. const char *app_reason)
  2349. {
  2350. QUIC_TERMINATE_CAUSE tcause = {0};
  2351. if (ossl_quic_channel_is_term_any(ch))
  2352. return;
  2353. tcause.app = 1;
  2354. tcause.error_code = app_error_code;
  2355. tcause.reason = app_reason;
  2356. tcause.reason_len = app_reason != NULL ? strlen(app_reason) : 0;
  2357. ch_start_terminating(ch, &tcause, 0);
  2358. }
  2359. static void free_token(const unsigned char *buf, size_t buf_len, void *arg)
  2360. {
  2361. OPENSSL_free((unsigned char *)buf);
  2362. }
  2363. /* Called when a server asks us to do a retry. */
  2364. static int ch_retry(QUIC_CHANNEL *ch,
  2365. const unsigned char *retry_token,
  2366. size_t retry_token_len,
  2367. const QUIC_CONN_ID *retry_scid)
  2368. {
  2369. void *buf;
  2370. /*
  2371. * RFC 9000 s. 17.2.5.1: "A client MUST discard a Retry packet that contains
  2372. * a SCID field that is identical to the DCID field of its initial packet."
  2373. */
  2374. if (ossl_quic_conn_id_eq(&ch->init_dcid, retry_scid))
  2375. return 1;
  2376. /* We change to using the SCID in the Retry packet as the DCID. */
  2377. if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, retry_scid))
  2378. return 0;
  2379. /*
  2380. * Now we retry. We will release the Retry packet immediately, so copy
  2381. * the token.
  2382. */
  2383. if ((buf = OPENSSL_memdup(retry_token, retry_token_len)) == NULL)
  2384. return 0;
  2385. if (!ossl_quic_tx_packetiser_set_initial_token(ch->txp, buf,
  2386. retry_token_len,
  2387. free_token, NULL)) {
  2388. /*
  2389. * This may fail if the token we receive is too big for us to ever be
  2390. * able to transmit in an outgoing Initial packet.
  2391. */
  2392. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INVALID_TOKEN, 0,
  2393. "received oversize token");
  2394. OPENSSL_free(buf);
  2395. return 0;
  2396. }
  2397. ch->retry_scid = *retry_scid;
  2398. ch->doing_retry = 1;
  2399. /*
  2400. * We need to stimulate the Initial EL to generate the first CRYPTO frame
  2401. * again. We can do this most cleanly by simply forcing the ACKM to consider
  2402. * the first Initial packet as lost, which it effectively was as the server
  2403. * hasn't processed it. This also maintains the desired behaviour with e.g.
  2404. * PNs not resetting and so on.
  2405. *
  2406. * The PN we used initially is always zero, because QUIC does not allow
  2407. * repeated retries.
  2408. */
  2409. if (!ossl_ackm_mark_packet_pseudo_lost(ch->ackm, QUIC_PN_SPACE_INITIAL,
  2410. /*PN=*/0))
  2411. return 0;
  2412. /*
  2413. * Plug in new secrets for the Initial EL. This is the only time we change
  2414. * the secrets for an EL after we already provisioned it.
  2415. */
  2416. if (!ossl_quic_provide_initial_secret(ch->libctx,
  2417. ch->propq,
  2418. &ch->retry_scid,
  2419. /*is_server=*/0,
  2420. ch->qrx, ch->qtx))
  2421. return 0;
  2422. return 1;
  2423. }
  2424. /* Called when an EL is to be discarded. */
  2425. static int ch_discard_el(QUIC_CHANNEL *ch,
  2426. uint32_t enc_level)
  2427. {
  2428. if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_1RTT))
  2429. return 0;
  2430. if ((ch->el_discarded & (1U << enc_level)) != 0)
  2431. /* Already done. */
  2432. return 1;
  2433. /* Best effort for all of these. */
  2434. ossl_quic_tx_packetiser_discard_enc_level(ch->txp, enc_level);
  2435. ossl_qrx_discard_enc_level(ch->qrx, enc_level);
  2436. ossl_qtx_discard_enc_level(ch->qtx, enc_level);
  2437. if (enc_level != QUIC_ENC_LEVEL_0RTT) {
  2438. uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
  2439. ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
  2440. /* We should still have crypto streams at this point. */
  2441. if (!ossl_assert(ch->crypto_send[pn_space] != NULL)
  2442. || !ossl_assert(ch->crypto_recv[pn_space] != NULL))
  2443. return 0;
  2444. /* Get rid of the crypto stream state for the EL. */
  2445. ossl_quic_sstream_free(ch->crypto_send[pn_space]);
  2446. ch->crypto_send[pn_space] = NULL;
  2447. ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
  2448. ch->crypto_recv[pn_space] = NULL;
  2449. }
  2450. ch->el_discarded |= (1U << enc_level);
  2451. return 1;
  2452. }
  2453. /* Intended to be called by the RXDP. */
  2454. int ossl_quic_channel_on_handshake_confirmed(QUIC_CHANNEL *ch)
  2455. {
  2456. if (ch->handshake_confirmed)
  2457. return 1;
  2458. if (!ch->handshake_complete) {
  2459. /*
  2460. * Does not make sense for handshake to be confirmed before it is
  2461. * completed.
  2462. */
  2463. ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
  2464. OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE,
  2465. "handshake cannot be confirmed "
  2466. "before it is completed");
  2467. return 0;
  2468. }
  2469. ch_discard_el(ch, QUIC_ENC_LEVEL_HANDSHAKE);
  2470. ch->handshake_confirmed = 1;
  2471. ossl_ackm_on_handshake_confirmed(ch->ackm);
  2472. return 1;
  2473. }
  2474. /*
  2475. * Master function used when we want to start tearing down a connection:
  2476. *
  2477. * - If the connection is still IDLE we can go straight to TERMINATED;
  2478. *
  2479. * - If we are already TERMINATED this is a no-op.
  2480. *
  2481. * - If we are TERMINATING - CLOSING and we have now got a CONNECTION_CLOSE
  2482. * from the peer (tcause->remote == 1), we move to TERMINATING - DRAINING.
  2483. *
  2484. * - If we are TERMINATING - DRAINING, we remain here until the terminating
  2485. * timer expires.
  2486. *
  2487. * - Otherwise, we are in ACTIVE and move to TERMINATING - CLOSING.
  2488. * if we caused the termination (e.g. we have sent a CONNECTION_CLOSE). Note
  2489. * that we are considered to have caused a termination if we sent the first
  2490. * CONNECTION_CLOSE frame, even if it is caused by a peer protocol
  2491. * violation. If the peer sent the first CONNECTION_CLOSE frame, we move to
  2492. * TERMINATING - DRAINING.
  2493. *
  2494. * We record the termination cause structure passed on the first call only.
  2495. * Any successive calls have their termination cause data discarded;
  2496. * once we start sending a CONNECTION_CLOSE frame, we don't change the details
  2497. * in it.
  2498. *
  2499. * This conforms to RFC 9000 s. 10.2.1: Closing Connection State:
  2500. * To minimize the state that an endpoint maintains for a closing
  2501. * connection, endpoints MAY send the exact same packet in response
  2502. * to any received packet.
  2503. *
  2504. * We don't drop any connection state (specifically packet protection keys)
  2505. * even though we are permitted to. This conforms to RFC 9000 s. 10.2.1:
  2506. * Closing Connection State:
  2507. * An endpoint MAY retain packet protection keys for incoming
  2508. * packets to allow it to read and process a CONNECTION_CLOSE frame.
  2509. *
  2510. * Note that we do not conform to these two from the same section:
  2511. * An endpoint's selected connection ID and the QUIC version
  2512. * are sufficient information to identify packets for a closing
  2513. * connection; the endpoint MAY discard all other connection state.
  2514. * and:
  2515. * An endpoint MAY drop packet protection keys when entering the
  2516. * closing state and send a packet containing a CONNECTION_CLOSE
  2517. * frame in response to any UDP datagram that is received.
  2518. */
  2519. static void copy_tcause(QUIC_TERMINATE_CAUSE *dst,
  2520. const QUIC_TERMINATE_CAUSE *src)
  2521. {
  2522. dst->error_code = src->error_code;
  2523. dst->frame_type = src->frame_type;
  2524. dst->app = src->app;
  2525. dst->remote = src->remote;
  2526. dst->reason = NULL;
  2527. dst->reason_len = 0;
  2528. if (src->reason != NULL && src->reason_len > 0) {
  2529. size_t l = src->reason_len;
  2530. char *r;
  2531. if (l >= SIZE_MAX)
  2532. --l;
  2533. /*
  2534. * If this fails, dst->reason becomes NULL and we simply do not use a
  2535. * reason. This ensures termination is infallible.
  2536. */
  2537. dst->reason = r = OPENSSL_memdup(src->reason, l + 1);
  2538. if (r == NULL)
  2539. return;
  2540. r[l] = '\0';
  2541. dst->reason_len = l;
  2542. }
  2543. }
  2544. static void ch_start_terminating(QUIC_CHANNEL *ch,
  2545. const QUIC_TERMINATE_CAUSE *tcause,
  2546. int force_immediate)
  2547. {
  2548. /* No point sending anything if we haven't sent anything yet. */
  2549. if (!ch->have_sent_any_pkt)
  2550. force_immediate = 1;
  2551. switch (ch->state) {
  2552. default:
  2553. case QUIC_CHANNEL_STATE_IDLE:
  2554. copy_tcause(&ch->terminate_cause, tcause);
  2555. ch_on_terminating_timeout(ch);
  2556. break;
  2557. case QUIC_CHANNEL_STATE_ACTIVE:
  2558. copy_tcause(&ch->terminate_cause, tcause);
  2559. if (!force_immediate) {
  2560. ch->state = tcause->remote ? QUIC_CHANNEL_STATE_TERMINATING_DRAINING
  2561. : QUIC_CHANNEL_STATE_TERMINATING_CLOSING;
  2562. /*
  2563. * RFC 9000 s. 10.2 Immediate Close
  2564. * These states SHOULD persist for at least three times
  2565. * the current PTO interval as defined in [QUIC-RECOVERY].
  2566. */
  2567. ch->terminate_deadline
  2568. = ossl_time_add(get_time(ch),
  2569. ossl_time_multiply(ossl_ackm_get_pto_duration(ch->ackm),
  2570. 3));
  2571. if (!tcause->remote) {
  2572. OSSL_QUIC_FRAME_CONN_CLOSE f = {0};
  2573. /* best effort */
  2574. f.error_code = ch->terminate_cause.error_code;
  2575. f.frame_type = ch->terminate_cause.frame_type;
  2576. f.is_app = ch->terminate_cause.app;
  2577. f.reason = (char *)ch->terminate_cause.reason;
  2578. f.reason_len = ch->terminate_cause.reason_len;
  2579. ossl_quic_tx_packetiser_schedule_conn_close(ch->txp, &f);
  2580. /*
  2581. * RFC 9000 s. 10.2.2 Draining Connection State:
  2582. * An endpoint that receives a CONNECTION_CLOSE frame MAY
  2583. * send a single packet containing a CONNECTION_CLOSE
  2584. * frame before entering the draining state, using a
  2585. * NO_ERROR code if appropriate
  2586. */
  2587. ch->conn_close_queued = 1;
  2588. }
  2589. } else {
  2590. ch_on_terminating_timeout(ch);
  2591. }
  2592. break;
  2593. case QUIC_CHANNEL_STATE_TERMINATING_CLOSING:
  2594. if (force_immediate)
  2595. ch_on_terminating_timeout(ch);
  2596. else if (tcause->remote)
  2597. /*
  2598. * RFC 9000 s. 10.2.2 Draining Connection State:
  2599. * An endpoint MAY enter the draining state from the
  2600. * closing state if it receives a CONNECTION_CLOSE frame,
  2601. * which indicates that the peer is also closing or draining.
  2602. */
  2603. ch->state = QUIC_CHANNEL_STATE_TERMINATING_DRAINING;
  2604. break;
  2605. case QUIC_CHANNEL_STATE_TERMINATING_DRAINING:
  2606. /*
  2607. * Other than in the force-immediate case, we remain here until the
  2608. * timeout expires.
  2609. */
  2610. if (force_immediate)
  2611. ch_on_terminating_timeout(ch);
  2612. break;
  2613. case QUIC_CHANNEL_STATE_TERMINATED:
  2614. /* No-op. */
  2615. break;
  2616. }
  2617. }
  2618. /* For RXDP use. */
  2619. void ossl_quic_channel_on_remote_conn_close(QUIC_CHANNEL *ch,
  2620. OSSL_QUIC_FRAME_CONN_CLOSE *f)
  2621. {
  2622. QUIC_TERMINATE_CAUSE tcause = {0};
  2623. if (!ossl_quic_channel_is_active(ch))
  2624. return;
  2625. tcause.remote = 1;
  2626. tcause.app = f->is_app;
  2627. tcause.error_code = f->error_code;
  2628. tcause.frame_type = f->frame_type;
  2629. tcause.reason = f->reason;
  2630. tcause.reason_len = f->reason_len;
  2631. ch_start_terminating(ch, &tcause, 0);
  2632. }
  2633. static void free_frame_data(unsigned char *buf, size_t buf_len, void *arg)
  2634. {
  2635. OPENSSL_free(buf);
  2636. }
  2637. static int ch_enqueue_retire_conn_id(QUIC_CHANNEL *ch, uint64_t seq_num)
  2638. {
  2639. BUF_MEM *buf_mem = NULL;
  2640. WPACKET wpkt;
  2641. size_t l;
  2642. chan_remove_reset_token(ch, seq_num);
  2643. if ((buf_mem = BUF_MEM_new()) == NULL)
  2644. goto err;
  2645. if (!WPACKET_init(&wpkt, buf_mem))
  2646. goto err;
  2647. if (!ossl_quic_wire_encode_frame_retire_conn_id(&wpkt, seq_num)) {
  2648. WPACKET_cleanup(&wpkt);
  2649. goto err;
  2650. }
  2651. WPACKET_finish(&wpkt);
  2652. if (!WPACKET_get_total_written(&wpkt, &l))
  2653. goto err;
  2654. if (ossl_quic_cfq_add_frame(ch->cfq, 1, QUIC_PN_SPACE_APP,
  2655. OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID, 0,
  2656. (unsigned char *)buf_mem->data, l,
  2657. free_frame_data, NULL) == NULL)
  2658. goto err;
  2659. buf_mem->data = NULL;
  2660. BUF_MEM_free(buf_mem);
  2661. return 1;
  2662. err:
  2663. ossl_quic_channel_raise_protocol_error(ch,
  2664. QUIC_ERR_INTERNAL_ERROR,
  2665. OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
  2666. "internal error enqueueing retire conn id");
  2667. BUF_MEM_free(buf_mem);
  2668. return 0;
  2669. }
  2670. void ossl_quic_channel_on_new_conn_id(QUIC_CHANNEL *ch,
  2671. OSSL_QUIC_FRAME_NEW_CONN_ID *f)
  2672. {
  2673. uint64_t new_remote_seq_num = ch->cur_remote_seq_num;
  2674. uint64_t new_retire_prior_to = ch->cur_retire_prior_to;
  2675. if (!ossl_quic_channel_is_active(ch))
  2676. return;
  2677. /* We allow only two active connection ids; first check some constraints */
  2678. if (ch->cur_remote_dcid.id_len == 0) {
  2679. /* Changing from 0 length connection id is disallowed */
  2680. ossl_quic_channel_raise_protocol_error(ch,
  2681. QUIC_ERR_PROTOCOL_VIOLATION,
  2682. OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
  2683. "zero length connection id in use");
  2684. return;
  2685. }
  2686. if (f->seq_num > new_remote_seq_num)
  2687. new_remote_seq_num = f->seq_num;
  2688. if (f->retire_prior_to > new_retire_prior_to)
  2689. new_retire_prior_to = f->retire_prior_to;
  2690. /*
  2691. * RFC 9000-5.1.1: An endpoint MUST NOT provide more connection IDs
  2692. * than the peer's limit.
  2693. *
  2694. * After processing a NEW_CONNECTION_ID frame and adding and retiring
  2695. * active connection IDs, if the number of active connection IDs exceeds
  2696. * the value advertised in its active_connection_id_limit transport
  2697. * parameter, an endpoint MUST close the connection with an error of
  2698. * type CONNECTION_ID_LIMIT_ERROR.
  2699. */
  2700. if (new_remote_seq_num - new_retire_prior_to > 1) {
  2701. ossl_quic_channel_raise_protocol_error(ch,
  2702. QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
  2703. OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
  2704. "active_connection_id limit violated");
  2705. return;
  2706. }
  2707. /*
  2708. * RFC 9000-5.1.1: An endpoint MAY send connection IDs that temporarily
  2709. * exceed a peer's limit if the NEW_CONNECTION_ID frame also requires
  2710. * the retirement of any excess, by including a sufficiently large
  2711. * value in the Retire Prior To field.
  2712. *
  2713. * RFC 9000-5.1.2: An endpoint SHOULD allow for sending and tracking
  2714. * a number of RETIRE_CONNECTION_ID frames of at least twice the value
  2715. * of the active_connection_id_limit transport parameter. An endpoint
  2716. * MUST NOT forget a connection ID without retiring it, though it MAY
  2717. * choose to treat having connection IDs in need of retirement that
  2718. * exceed this limit as a connection error of type CONNECTION_ID_LIMIT_ERROR.
  2719. *
  2720. * We are a little bit more liberal than the minimum mandated.
  2721. */
  2722. if (new_retire_prior_to - ch->cur_retire_prior_to > 10) {
  2723. ossl_quic_channel_raise_protocol_error(ch,
  2724. QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
  2725. OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
  2726. "retiring connection id limit violated");
  2727. return;
  2728. }
  2729. if (new_remote_seq_num > ch->cur_remote_seq_num) {
  2730. /* Add new stateless reset token */
  2731. if (!chan_add_reset_token(ch, f->stateless_reset.token,
  2732. new_remote_seq_num)) {
  2733. ossl_quic_channel_raise_protocol_error(
  2734. ch, QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
  2735. OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
  2736. "unable to store stateless reset token");
  2737. return;
  2738. }
  2739. ch->cur_remote_seq_num = new_remote_seq_num;
  2740. ch->cur_remote_dcid = f->conn_id;
  2741. ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid);
  2742. }
  2743. /*
  2744. * RFC 9000-5.1.2: Upon receipt of an increased Retire Prior To
  2745. * field, the peer MUST stop using the corresponding connection IDs
  2746. * and retire them with RETIRE_CONNECTION_ID frames before adding the
  2747. * newly provided connection ID to the set of active connection IDs.
  2748. */
  2749. /*
  2750. * Note: RFC 9000 s. 19.15 says:
  2751. * "An endpoint that receives a NEW_CONNECTION_ID frame with a sequence
  2752. * number smaller than the Retire Prior To field of a previously received
  2753. * NEW_CONNECTION_ID frame MUST send a corresponding
  2754. * RETIRE_CONNECTION_ID frame that retires the newly received connection
  2755. * ID, unless it has already done so for that sequence number."
  2756. *
  2757. * Since we currently always queue RETIRE_CONN_ID frames based on the Retire
  2758. * Prior To field of a NEW_CONNECTION_ID frame immediately upon receiving
  2759. * that NEW_CONNECTION_ID frame, by definition this will always be met.
  2760. * This may change in future when we change our CID handling.
  2761. */
  2762. while (new_retire_prior_to > ch->cur_retire_prior_to) {
  2763. if (!ch_enqueue_retire_conn_id(ch, ch->cur_retire_prior_to))
  2764. break;
  2765. ++ch->cur_retire_prior_to;
  2766. }
  2767. }
  2768. static void ch_save_err_state(QUIC_CHANNEL *ch)
  2769. {
  2770. if (ch->err_state == NULL)
  2771. ch->err_state = OSSL_ERR_STATE_new();
  2772. if (ch->err_state == NULL)
  2773. return;
  2774. OSSL_ERR_STATE_save(ch->err_state);
  2775. }
  2776. static void ch_stateless_reset(QUIC_CHANNEL *ch)
  2777. {
  2778. QUIC_TERMINATE_CAUSE tcause = {0};
  2779. tcause.error_code = QUIC_ERR_NO_ERROR;
  2780. ch_start_terminating(ch, &tcause, 1);
  2781. }
  2782. static void ch_raise_net_error(QUIC_CHANNEL *ch)
  2783. {
  2784. QUIC_TERMINATE_CAUSE tcause = {0};
  2785. ch->net_error = 1;
  2786. ERR_raise_data(ERR_LIB_SSL, SSL_R_QUIC_NETWORK_ERROR,
  2787. "connection terminated due to network error");
  2788. ch_save_err_state(ch);
  2789. tcause.error_code = QUIC_ERR_INTERNAL_ERROR;
  2790. /*
  2791. * Skip Terminating state and go directly to Terminated, no point trying to
  2792. * send CONNECTION_CLOSE if we cannot communicate.
  2793. */
  2794. ch_start_terminating(ch, &tcause, 1);
  2795. }
  2796. int ossl_quic_channel_net_error(QUIC_CHANNEL *ch)
  2797. {
  2798. return ch->net_error;
  2799. }
  2800. void ossl_quic_channel_restore_err_state(QUIC_CHANNEL *ch)
  2801. {
  2802. if (ch == NULL)
  2803. return;
  2804. OSSL_ERR_STATE_restore(ch->err_state);
  2805. }
  2806. void ossl_quic_channel_raise_protocol_error_loc(QUIC_CHANNEL *ch,
  2807. uint64_t error_code,
  2808. uint64_t frame_type,
  2809. const char *reason,
  2810. ERR_STATE *err_state,
  2811. const char *src_file,
  2812. int src_line,
  2813. const char *src_func)
  2814. {
  2815. QUIC_TERMINATE_CAUSE tcause = {0};
  2816. int err_reason = error_code == QUIC_ERR_INTERNAL_ERROR
  2817. ? ERR_R_INTERNAL_ERROR : SSL_R_QUIC_PROTOCOL_ERROR;
  2818. const char *err_str = ossl_quic_err_to_string(error_code);
  2819. const char *err_str_pfx = " (", *err_str_sfx = ")";
  2820. const char *ft_str = NULL;
  2821. const char *ft_str_pfx = " (", *ft_str_sfx = ")";
  2822. if (ch->protocol_error)
  2823. /* Only the first call to this function matters. */
  2824. return;
  2825. if (err_str == NULL) {
  2826. err_str = "";
  2827. err_str_pfx = "";
  2828. err_str_sfx = "";
  2829. }
  2830. /*
  2831. * If we were provided an underlying error state, restore it and then append
  2832. * our ERR on top as a "cover letter" error.
  2833. */
  2834. if (err_state != NULL)
  2835. OSSL_ERR_STATE_restore(err_state);
  2836. if (frame_type != 0) {
  2837. ft_str = ossl_quic_frame_type_to_string(frame_type);
  2838. if (ft_str == NULL) {
  2839. ft_str = "";
  2840. ft_str_pfx = "";
  2841. ft_str_sfx = "";
  2842. }
  2843. ERR_raise_data(ERR_LIB_SSL, err_reason,
  2844. "QUIC error code: 0x%llx%s%s%s "
  2845. "(triggered by frame type: 0x%llx%s%s%s), reason: \"%s\"",
  2846. (unsigned long long) error_code,
  2847. err_str_pfx, err_str, err_str_sfx,
  2848. (unsigned long long) frame_type,
  2849. ft_str_pfx, ft_str, ft_str_sfx,
  2850. reason);
  2851. } else {
  2852. ERR_raise_data(ERR_LIB_SSL, err_reason,
  2853. "QUIC error code: 0x%llx%s%s%s, reason: \"%s\"",
  2854. (unsigned long long) error_code,
  2855. err_str_pfx, err_str, err_str_sfx,
  2856. reason);
  2857. }
  2858. if (src_file != NULL)
  2859. ERR_set_debug(src_file, src_line, src_func);
  2860. ch_save_err_state(ch);
  2861. tcause.error_code = error_code;
  2862. tcause.frame_type = frame_type;
  2863. tcause.reason = reason;
  2864. tcause.reason_len = strlen(reason);
  2865. ch->protocol_error = 1;
  2866. ch_start_terminating(ch, &tcause, 0);
  2867. }
  2868. /*
  2869. * Called once the terminating timer expires, meaning we move from TERMINATING
  2870. * to TERMINATED.
  2871. */
  2872. static void ch_on_terminating_timeout(QUIC_CHANNEL *ch)
  2873. {
  2874. ch->state = QUIC_CHANNEL_STATE_TERMINATED;
  2875. }
  2876. /*
  2877. * Determines the effective idle timeout duration. This is based on the idle
  2878. * timeout values that we and our peer signalled in transport parameters
  2879. * but have some limits applied.
  2880. */
  2881. static OSSL_TIME ch_get_effective_idle_timeout_duration(QUIC_CHANNEL *ch)
  2882. {
  2883. OSSL_TIME pto;
  2884. if (ch->max_idle_timeout == 0)
  2885. return ossl_time_infinite();
  2886. /*
  2887. * RFC 9000 s. 10.1: Idle Timeout
  2888. * To avoid excessively small idle timeout periods, endpoints
  2889. * MUST increase the idle timeout period to be at least three
  2890. * times the current Probe Timeout (PTO). This allows for
  2891. * multiple PTOs to expire, and therefore multiple probes to
  2892. * be sent and lost, prior to idle timeout.
  2893. */
  2894. pto = ossl_ackm_get_pto_duration(ch->ackm);
  2895. return ossl_time_max(ossl_ms2time(ch->max_idle_timeout),
  2896. ossl_time_multiply(pto, 3));
  2897. }
  2898. /*
  2899. * Updates our idle deadline. Called when an event happens which should bump the
  2900. * idle timeout.
  2901. */
  2902. static void ch_update_idle(QUIC_CHANNEL *ch)
  2903. {
  2904. ch->idle_deadline = ossl_time_add(get_time(ch),
  2905. ch_get_effective_idle_timeout_duration(ch));
  2906. }
  2907. /*
  2908. * Updates our ping deadline, which determines when we next generate a ping if
  2909. * we don't have any other ACK-eliciting frames to send.
  2910. */
  2911. static void ch_update_ping_deadline(QUIC_CHANNEL *ch)
  2912. {
  2913. OSSL_TIME max_span, idle_duration;
  2914. idle_duration = ch_get_effective_idle_timeout_duration(ch);
  2915. if (ossl_time_is_infinite(idle_duration)) {
  2916. ch->ping_deadline = ossl_time_infinite();
  2917. return;
  2918. }
  2919. /*
  2920. * Maximum amount of time without traffic before we send a PING to keep
  2921. * the connection open. Usually we use max_idle_timeout/2, but ensure
  2922. * the period never exceeds the assumed NAT interval to ensure NAT
  2923. * devices don't have their state time out (RFC 9000 s. 10.1.2).
  2924. */
  2925. max_span = ossl_time_divide(idle_duration, 2);
  2926. max_span = ossl_time_min(max_span, MAX_NAT_INTERVAL);
  2927. ch->ping_deadline = ossl_time_add(get_time(ch), max_span);
  2928. }
  2929. /* Called when the idle timeout expires. */
  2930. static void ch_on_idle_timeout(QUIC_CHANNEL *ch)
  2931. {
  2932. /*
  2933. * Idle timeout does not have an error code associated with it because a
  2934. * CONN_CLOSE is never sent for it. We shouldn't use this data once we reach
  2935. * TERMINATED anyway.
  2936. */
  2937. ch->terminate_cause.app = 0;
  2938. ch->terminate_cause.error_code = UINT64_MAX;
  2939. ch->terminate_cause.frame_type = 0;
  2940. ch->state = QUIC_CHANNEL_STATE_TERMINATED;
  2941. }
  2942. /* Called when we, as a server, get a new incoming connection. */
  2943. static int ch_server_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
  2944. const QUIC_CONN_ID *peer_scid,
  2945. const QUIC_CONN_ID *peer_dcid)
  2946. {
  2947. if (!ossl_assert(ch->state == QUIC_CHANNEL_STATE_IDLE && ch->is_server))
  2948. return 0;
  2949. /* Generate a SCID we will use for the connection. */
  2950. if (!gen_rand_conn_id(ch->libctx, INIT_DCID_LEN,
  2951. &ch->cur_local_cid))
  2952. return 0;
  2953. /* Note our newly learnt peer address and CIDs. */
  2954. ch->cur_peer_addr = *peer;
  2955. ch->init_dcid = *peer_dcid;
  2956. ch->cur_remote_dcid = *peer_scid;
  2957. /* Inform QTX of peer address. */
  2958. if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
  2959. return 0;
  2960. /* Inform TXP of desired CIDs. */
  2961. if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid))
  2962. return 0;
  2963. if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_cid))
  2964. return 0;
  2965. /* Plug in secrets for the Initial EL. */
  2966. if (!ossl_quic_provide_initial_secret(ch->libctx,
  2967. ch->propq,
  2968. &ch->init_dcid,
  2969. /*is_server=*/1,
  2970. ch->qrx, ch->qtx))
  2971. return 0;
  2972. /* Register our local CID in the DEMUX. */
  2973. if (!ossl_qrx_add_dst_conn_id(ch->qrx, &ch->cur_local_cid))
  2974. return 0;
  2975. /* Change state. */
  2976. ch->state = QUIC_CHANNEL_STATE_ACTIVE;
  2977. ch->doing_proactive_ver_neg = 0; /* not currently supported */
  2978. return 1;
  2979. }
  2980. SSL *ossl_quic_channel_get0_ssl(QUIC_CHANNEL *ch)
  2981. {
  2982. return ch->tls;
  2983. }
  2984. static int ch_init_new_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs,
  2985. int can_send, int can_recv)
  2986. {
  2987. uint64_t rxfc_wnd;
  2988. int server_init = ossl_quic_stream_is_server_init(qs);
  2989. int local_init = (ch->is_server == server_init);
  2990. int is_uni = !ossl_quic_stream_is_bidi(qs);
  2991. if (can_send)
  2992. if ((qs->sstream = ossl_quic_sstream_new(INIT_APP_BUF_LEN)) == NULL)
  2993. goto err;
  2994. if (can_recv)
  2995. if ((qs->rstream = ossl_quic_rstream_new(NULL, NULL, 0)) == NULL)
  2996. goto err;
  2997. /* TXFC */
  2998. if (!ossl_quic_txfc_init(&qs->txfc, &ch->conn_txfc))
  2999. goto err;
  3000. if (ch->got_remote_transport_params) {
  3001. /*
  3002. * If we already got peer TPs we need to apply the initial CWM credit
  3003. * now. If we didn't already get peer TPs this will be done
  3004. * automatically for all extant streams when we do.
  3005. */
  3006. if (can_send) {
  3007. uint64_t cwm;
  3008. if (is_uni)
  3009. cwm = ch->rx_init_max_stream_data_uni;
  3010. else if (local_init)
  3011. cwm = ch->rx_init_max_stream_data_bidi_local;
  3012. else
  3013. cwm = ch->rx_init_max_stream_data_bidi_remote;
  3014. ossl_quic_txfc_bump_cwm(&qs->txfc, cwm);
  3015. }
  3016. }
  3017. /* RXFC */
  3018. if (!can_recv)
  3019. rxfc_wnd = 0;
  3020. else if (is_uni)
  3021. rxfc_wnd = ch->tx_init_max_stream_data_uni;
  3022. else if (local_init)
  3023. rxfc_wnd = ch->tx_init_max_stream_data_bidi_local;
  3024. else
  3025. rxfc_wnd = ch->tx_init_max_stream_data_bidi_remote;
  3026. if (!ossl_quic_rxfc_init(&qs->rxfc, &ch->conn_rxfc,
  3027. rxfc_wnd,
  3028. DEFAULT_STREAM_RXFC_MAX_WND_MUL * rxfc_wnd,
  3029. get_time, ch))
  3030. goto err;
  3031. return 1;
  3032. err:
  3033. ossl_quic_sstream_free(qs->sstream);
  3034. qs->sstream = NULL;
  3035. ossl_quic_rstream_free(qs->rstream);
  3036. qs->rstream = NULL;
  3037. return 0;
  3038. }
  3039. static uint64_t *ch_get_local_stream_next_ordinal_ptr(QUIC_CHANNEL *ch,
  3040. int is_uni)
  3041. {
  3042. return is_uni ? &ch->next_local_stream_ordinal_uni
  3043. : &ch->next_local_stream_ordinal_bidi;
  3044. }
  3045. int ossl_quic_channel_is_new_local_stream_admissible(QUIC_CHANNEL *ch,
  3046. int is_uni)
  3047. {
  3048. uint64_t *p_next_ordinal = ch_get_local_stream_next_ordinal_ptr(ch, is_uni);
  3049. return ossl_quic_stream_map_is_local_allowed_by_stream_limit(&ch->qsm,
  3050. *p_next_ordinal,
  3051. is_uni);
  3052. }
  3053. QUIC_STREAM *ossl_quic_channel_new_stream_local(QUIC_CHANNEL *ch, int is_uni)
  3054. {
  3055. QUIC_STREAM *qs;
  3056. int type;
  3057. uint64_t stream_id, *p_next_ordinal;
  3058. type = ch->is_server ? QUIC_STREAM_INITIATOR_SERVER
  3059. : QUIC_STREAM_INITIATOR_CLIENT;
  3060. p_next_ordinal = ch_get_local_stream_next_ordinal_ptr(ch, is_uni);
  3061. if (is_uni)
  3062. type |= QUIC_STREAM_DIR_UNI;
  3063. else
  3064. type |= QUIC_STREAM_DIR_BIDI;
  3065. if (*p_next_ordinal >= ((uint64_t)1) << 62)
  3066. return NULL;
  3067. stream_id = ((*p_next_ordinal) << 2) | type;
  3068. if ((qs = ossl_quic_stream_map_alloc(&ch->qsm, stream_id, type)) == NULL)
  3069. return NULL;
  3070. /* Locally-initiated stream, so we always want a send buffer. */
  3071. if (!ch_init_new_stream(ch, qs, /*can_send=*/1, /*can_recv=*/!is_uni))
  3072. goto err;
  3073. ++*p_next_ordinal;
  3074. return qs;
  3075. err:
  3076. ossl_quic_stream_map_release(&ch->qsm, qs);
  3077. return NULL;
  3078. }
  3079. QUIC_STREAM *ossl_quic_channel_new_stream_remote(QUIC_CHANNEL *ch,
  3080. uint64_t stream_id)
  3081. {
  3082. uint64_t peer_role;
  3083. int is_uni;
  3084. QUIC_STREAM *qs;
  3085. peer_role = ch->is_server
  3086. ? QUIC_STREAM_INITIATOR_CLIENT
  3087. : QUIC_STREAM_INITIATOR_SERVER;
  3088. if ((stream_id & QUIC_STREAM_INITIATOR_MASK) != peer_role)
  3089. return NULL;
  3090. is_uni = ((stream_id & QUIC_STREAM_DIR_MASK) == QUIC_STREAM_DIR_UNI);
  3091. qs = ossl_quic_stream_map_alloc(&ch->qsm, stream_id,
  3092. stream_id & (QUIC_STREAM_INITIATOR_MASK
  3093. | QUIC_STREAM_DIR_MASK));
  3094. if (qs == NULL)
  3095. return NULL;
  3096. if (!ch_init_new_stream(ch, qs, /*can_send=*/!is_uni, /*can_recv=*/1))
  3097. goto err;
  3098. if (ch->incoming_stream_auto_reject)
  3099. ossl_quic_channel_reject_stream(ch, qs);
  3100. else
  3101. ossl_quic_stream_map_push_accept_queue(&ch->qsm, qs);
  3102. return qs;
  3103. err:
  3104. ossl_quic_stream_map_release(&ch->qsm, qs);
  3105. return NULL;
  3106. }
  3107. void ossl_quic_channel_set_incoming_stream_auto_reject(QUIC_CHANNEL *ch,
  3108. int enable,
  3109. uint64_t aec)
  3110. {
  3111. ch->incoming_stream_auto_reject = (enable != 0);
  3112. ch->incoming_stream_auto_reject_aec = aec;
  3113. }
  3114. void ossl_quic_channel_reject_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs)
  3115. {
  3116. ossl_quic_stream_map_stop_sending_recv_part(&ch->qsm, qs,
  3117. ch->incoming_stream_auto_reject_aec);
  3118. ossl_quic_stream_map_reset_stream_send_part(&ch->qsm, qs,
  3119. ch->incoming_stream_auto_reject_aec);
  3120. qs->deleted = 1;
  3121. ossl_quic_stream_map_update_state(&ch->qsm, qs);
  3122. }
  3123. /* Replace local connection ID in TXP and DEMUX for testing purposes. */
  3124. int ossl_quic_channel_replace_local_cid(QUIC_CHANNEL *ch,
  3125. const QUIC_CONN_ID *conn_id)
  3126. {
  3127. /* Remove the current local CID from the DEMUX. */
  3128. if (!ossl_qrx_remove_dst_conn_id(ch->qrx, &ch->cur_local_cid))
  3129. return 0;
  3130. ch->cur_local_cid = *conn_id;
  3131. /* Set in the TXP, used only for long header packets. */
  3132. if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_cid))
  3133. return 0;
  3134. /* Register our new local CID in the DEMUX. */
  3135. if (!ossl_qrx_add_dst_conn_id(ch->qrx, &ch->cur_local_cid))
  3136. return 0;
  3137. return 1;
  3138. }
  3139. void ossl_quic_channel_set_msg_callback(QUIC_CHANNEL *ch,
  3140. ossl_msg_cb msg_callback,
  3141. SSL *msg_callback_ssl)
  3142. {
  3143. ch->msg_callback = msg_callback;
  3144. ch->msg_callback_ssl = msg_callback_ssl;
  3145. ossl_qtx_set_msg_callback(ch->qtx, msg_callback, msg_callback_ssl);
  3146. ossl_quic_tx_packetiser_set_msg_callback(ch->txp, msg_callback,
  3147. msg_callback_ssl);
  3148. ossl_qrx_set_msg_callback(ch->qrx, msg_callback, msg_callback_ssl);
  3149. }
  3150. void ossl_quic_channel_set_msg_callback_arg(QUIC_CHANNEL *ch,
  3151. void *msg_callback_arg)
  3152. {
  3153. ch->msg_callback_arg = msg_callback_arg;
  3154. ossl_qtx_set_msg_callback_arg(ch->qtx, msg_callback_arg);
  3155. ossl_quic_tx_packetiser_set_msg_callback_arg(ch->txp, msg_callback_arg);
  3156. ossl_qrx_set_msg_callback_arg(ch->qrx, msg_callback_arg);
  3157. }
  3158. void ossl_quic_channel_set_txku_threshold_override(QUIC_CHANNEL *ch,
  3159. uint64_t tx_pkt_threshold)
  3160. {
  3161. ch->txku_threshold_override = tx_pkt_threshold;
  3162. }
  3163. uint64_t ossl_quic_channel_get_tx_key_epoch(QUIC_CHANNEL *ch)
  3164. {
  3165. return ossl_qtx_get_key_epoch(ch->qtx);
  3166. }
  3167. uint64_t ossl_quic_channel_get_rx_key_epoch(QUIC_CHANNEL *ch)
  3168. {
  3169. return ossl_qrx_get_key_epoch(ch->qrx);
  3170. }
  3171. int ossl_quic_channel_trigger_txku(QUIC_CHANNEL *ch)
  3172. {
  3173. if (!txku_allowed(ch))
  3174. return 0;
  3175. ch->ku_locally_initiated = 1;
  3176. ch_trigger_txku(ch);
  3177. return 1;
  3178. }
  3179. int ossl_quic_channel_ping(QUIC_CHANNEL *ch)
  3180. {
  3181. int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level);
  3182. ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space);
  3183. return 1;
  3184. }
  3185. void ossl_quic_channel_set_inhibit_tick(QUIC_CHANNEL *ch, int inhibit)
  3186. {
  3187. ch->inhibit_tick = (inhibit != 0);
  3188. }
  3189. uint16_t ossl_quic_channel_get_diag_num_rx_ack(QUIC_CHANNEL *ch)
  3190. {
  3191. return ch->diag_num_rx_ack;
  3192. }
  3193. void ossl_quic_channel_get_diag_local_cid(QUIC_CHANNEL *ch, QUIC_CONN_ID *cid)
  3194. {
  3195. *cid = ch->cur_local_cid;
  3196. }