quic_channel.c 126 KB

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