picotls.c 285 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238
  1. /*
  2. * Copyright (c) 2016 DeNA Co., Ltd., Kazuho Oku
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to
  6. * deal in the Software without restriction, including without limitation the
  7. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. * sell copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. * IN THE SOFTWARE.
  21. */
  22. #ifdef _WINDOWS
  23. #include "wincompat.h"
  24. #endif
  25. #include <assert.h>
  26. #include <stdarg.h>
  27. #include <stddef.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #ifndef _WINDOWS
  32. #include <errno.h>
  33. #include <pthread.h>
  34. #include <unistd.h>
  35. #include <arpa/inet.h>
  36. #include <sys/time.h>
  37. #endif
  38. #ifdef __linux__
  39. #include <sys/syscall.h>
  40. #endif
  41. #include "picotls.h"
  42. #if PICOTLS_USE_DTRACE
  43. #include "picotls-probes.h"
  44. #endif
  45. #define PTLS_MAX_PLAINTEXT_RECORD_SIZE 16384
  46. #define PTLS_MAX_ENCRYPTED_RECORD_SIZE (16384 + 256)
  47. #define PTLS_RECORD_VERSION_MAJOR 3
  48. #define PTLS_RECORD_VERSION_MINOR 3
  49. #define PTLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC 20
  50. #define PTLS_CONTENT_TYPE_ALERT 21
  51. #define PTLS_CONTENT_TYPE_HANDSHAKE 22
  52. #define PTLS_CONTENT_TYPE_APPDATA 23
  53. #define PTLS_PSK_KE_MODE_PSK 0
  54. #define PTLS_PSK_KE_MODE_PSK_DHE 1
  55. #define PTLS_HANDSHAKE_HEADER_SIZE 4
  56. #define PTLS_EXTENSION_TYPE_SERVER_NAME 0
  57. #define PTLS_EXTENSION_TYPE_STATUS_REQUEST 5
  58. #define PTLS_EXTENSION_TYPE_SUPPORTED_GROUPS 10
  59. #define PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS 13
  60. #define PTLS_EXTENSION_TYPE_ALPN 16
  61. #define PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE 20
  62. #define PTLS_EXTENSION_TYPE_COMPRESS_CERTIFICATE 27
  63. #define PTLS_EXTENSION_TYPE_PRE_SHARED_KEY 41
  64. #define PTLS_EXTENSION_TYPE_EARLY_DATA 42
  65. #define PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS 43
  66. #define PTLS_EXTENSION_TYPE_COOKIE 44
  67. #define PTLS_EXTENSION_TYPE_PSK_KEY_EXCHANGE_MODES 45
  68. #define PTLS_EXTENSION_TYPE_CERTIFICATE_AUTHORITIES 47
  69. #define PTLS_EXTENSION_TYPE_KEY_SHARE 51
  70. #define PTLS_EXTENSION_TYPE_TICKET_REQUEST 58
  71. #define PTLS_EXTENSION_TYPE_ECH_OUTER_EXTENSIONS 0xfd00
  72. #define PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO 0xfe0d
  73. #define PTLS_SERVER_NAME_TYPE_HOSTNAME 0
  74. #define PTLS_ECH_CONFIG_VERSION 0xfe0d
  75. #define PTLS_ECH_CLIENT_HELLO_TYPE_OUTER 0
  76. #define PTLS_ECH_CLIENT_HELLO_TYPE_INNER 1
  77. #define PTLS_ECH_CONFIRM_LENGTH 8
  78. static const char ech_info_prefix[8] = "tls ech";
  79. #define PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING "TLS 1.3, server CertificateVerify"
  80. #define PTLS_CLIENT_CERTIFICATE_VERIFY_CONTEXT_STRING "TLS 1.3, client CertificateVerify"
  81. #define PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE \
  82. (64 + sizeof(PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING) + PTLS_MAX_DIGEST_SIZE * 2)
  83. #define PTLS_EARLY_DATA_MAX_DELAY 10000 /* max. RTT (in msec) to permit early data */
  84. #ifndef PTLS_MAX_EARLY_DATA_SKIP_SIZE
  85. #define PTLS_MAX_EARLY_DATA_SKIP_SIZE 65536
  86. #endif
  87. #if defined(PTLS_DEBUG) && PTLS_DEBUG
  88. #define PTLS_DEBUGF(...) fprintf(stderr, __VA_ARGS__)
  89. #else
  90. #define PTLS_DEBUGF(...)
  91. #endif
  92. #ifndef PTLS_MEMORY_DEBUG
  93. #define PTLS_MEMORY_DEBUG 0
  94. #endif
  95. #if PICOTLS_USE_DTRACE
  96. #define PTLS_PROBE0(LABEL, tls) \
  97. do { \
  98. if (PTLS_UNLIKELY(PICOTLS_##LABEL##_ENABLED())) \
  99. PICOTLS_##LABEL(tls); \
  100. } while (0)
  101. #define PTLS_PROBE(LABEL, tls, ...) \
  102. do { \
  103. if (PTLS_UNLIKELY(PICOTLS_##LABEL##_ENABLED())) \
  104. PICOTLS_##LABEL((tls), __VA_ARGS__); \
  105. } while (0)
  106. #else
  107. #define PTLS_PROBE0(LABEL, tls)
  108. #define PTLS_PROBE(LABEL, tls, ...)
  109. #endif
  110. /**
  111. * list of supported versions in the preferred order
  112. */
  113. static const uint16_t supported_versions[] = {PTLS_PROTOCOL_VERSION_TLS13};
  114. static const uint8_t hello_retry_random[PTLS_HELLO_RANDOM_SIZE] = {0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, 0x1D, 0x8C,
  115. 0x02, 0x1E, 0x65, 0xB8, 0x91, 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB,
  116. 0x8C, 0x5E, 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C};
  117. struct st_ptls_traffic_protection_t {
  118. uint8_t secret[PTLS_MAX_DIGEST_SIZE];
  119. size_t epoch;
  120. /* the following fields are not used if the key_change callback is set */
  121. ptls_aead_context_t *aead;
  122. uint64_t seq;
  123. unsigned tls12 : 1;
  124. uint64_t tls12_enc_record_iv;
  125. };
  126. struct st_ptls_record_message_emitter_t {
  127. ptls_message_emitter_t super;
  128. size_t rec_start;
  129. };
  130. struct st_ptls_signature_algorithms_t {
  131. uint16_t list[16]; /* expand? */
  132. size_t count;
  133. };
  134. struct st_ptls_certificate_request_t {
  135. /**
  136. * context.base becomes non-NULL when a CertificateRequest is pending for processing
  137. */
  138. ptls_iovec_t context;
  139. struct st_ptls_signature_algorithms_t signature_algorithms;
  140. };
  141. struct st_decoded_ech_config_t {
  142. uint8_t id;
  143. ptls_hpke_kem_t *kem;
  144. ptls_iovec_t public_key;
  145. ptls_hpke_cipher_suite_t *cipher;
  146. uint8_t max_name_length;
  147. ptls_iovec_t public_name;
  148. ptls_iovec_t bytes;
  149. };
  150. /**
  151. * Properties for ECH. Iff ECH is used and not rejected, `aead` is non-NULL.
  152. */
  153. struct st_ptls_ech_t {
  154. uint8_t offered : 1;
  155. uint8_t offered_grease : 1;
  156. uint8_t accepted : 1;
  157. uint8_t config_id;
  158. ptls_hpke_kem_t *kem;
  159. ptls_hpke_cipher_suite_t *cipher;
  160. ptls_aead_context_t *aead;
  161. uint8_t inner_client_random[PTLS_HELLO_RANDOM_SIZE];
  162. struct {
  163. ptls_iovec_t enc;
  164. uint8_t max_name_length;
  165. char *public_name;
  166. /**
  167. * retains a copy of entire ECH extension so that it can be replayed in the 2nd CH when ECH is rejected via HRR
  168. */
  169. ptls_iovec_t first_ech;
  170. } client;
  171. };
  172. struct st_ptls_t {
  173. /**
  174. * the context
  175. */
  176. ptls_context_t *ctx;
  177. /**
  178. * the state
  179. */
  180. enum en_ptls_state_t {
  181. PTLS_STATE_CLIENT_HANDSHAKE_START,
  182. PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO,
  183. PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO,
  184. PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS,
  185. PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE,
  186. PTLS_STATE_CLIENT_EXPECT_CERTIFICATE,
  187. PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY,
  188. PTLS_STATE_CLIENT_EXPECT_FINISHED,
  189. PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO,
  190. PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO,
  191. PTLS_STATE_SERVER_GENERATING_CERTIFICATE_VERIFY,
  192. PTLS_STATE_SERVER_EXPECT_CERTIFICATE,
  193. PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY,
  194. /* ptls_send can be called if the state is below here */
  195. PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA,
  196. PTLS_STATE_SERVER_EXPECT_FINISHED,
  197. PTLS_STATE_POST_HANDSHAKE_MIN,
  198. PTLS_STATE_CLIENT_POST_HANDSHAKE = PTLS_STATE_POST_HANDSHAKE_MIN,
  199. PTLS_STATE_SERVER_POST_HANDSHAKE
  200. } state;
  201. /**
  202. * receive buffers
  203. */
  204. struct {
  205. ptls_buffer_t rec;
  206. ptls_buffer_t mess;
  207. } recvbuf;
  208. /**
  209. * key schedule
  210. */
  211. ptls_key_schedule_t *key_schedule;
  212. /**
  213. * values used for record protection
  214. */
  215. struct {
  216. struct st_ptls_traffic_protection_t dec;
  217. struct st_ptls_traffic_protection_t enc;
  218. } traffic_protection;
  219. /**
  220. * server-name passed using SNI
  221. */
  222. char *server_name;
  223. /**
  224. * result of ALPN
  225. */
  226. char *negotiated_protocol;
  227. /**
  228. * selected key-exchange
  229. */
  230. ptls_key_exchange_algorithm_t *key_share;
  231. /**
  232. * selected cipher-suite
  233. */
  234. ptls_cipher_suite_t *cipher_suite;
  235. /**
  236. * ClientHello.random that appears on the wire. When ECH is used, that of inner CH is retained separately.
  237. */
  238. uint8_t client_random[PTLS_HELLO_RANDOM_SIZE];
  239. /**
  240. * exporter master secret (either 0rtt or 1rtt)
  241. */
  242. struct {
  243. uint8_t *early;
  244. uint8_t *one_rtt;
  245. } exporter_master_secret;
  246. /**
  247. * ECH
  248. */
  249. struct st_ptls_ech_t ech;
  250. /* flags */
  251. unsigned is_server : 1;
  252. unsigned is_psk_handshake : 1;
  253. unsigned send_change_cipher_spec : 1;
  254. unsigned needs_key_update : 1;
  255. unsigned key_update_send_request : 1;
  256. #if PTLS_HAVE_LOG
  257. /**
  258. * see ptls_log
  259. */
  260. ptls_log_conn_state_t log_state;
  261. #endif
  262. struct {
  263. uint32_t active_conns;
  264. uint32_t generation;
  265. } log_sni;
  266. /**
  267. * misc.
  268. */
  269. union {
  270. struct {
  271. ptls_iovec_t legacy_session_id;
  272. uint8_t legacy_session_id_buf[32];
  273. ptls_key_exchange_context_t *key_share_ctx;
  274. unsigned offered_psk : 1;
  275. /**
  276. * if 1-RTT write key is active
  277. */
  278. unsigned using_early_data : 1;
  279. struct st_ptls_certificate_request_t certificate_request;
  280. } client;
  281. struct {
  282. uint8_t pending_traffic_secret[PTLS_MAX_DIGEST_SIZE];
  283. uint32_t early_data_skipped_bytes; /* if not UINT32_MAX, the server is skipping early data */
  284. uint8_t num_tickets_to_send;
  285. ptls_async_job_t *async_job;
  286. } server;
  287. };
  288. /**
  289. * certificate verify; will be used by the client and the server (if require_client_authentication is set)
  290. */
  291. struct {
  292. int (*cb)(void *verify_ctx, uint16_t algo, ptls_iovec_t data, ptls_iovec_t signature);
  293. void *verify_ctx;
  294. } certificate_verify;
  295. /**
  296. * handshake traffic secret to be commisioned (an array of `uint8_t [PTLS_MAX_DIGEST_SIZE]` or NULL)
  297. */
  298. uint8_t *pending_handshake_secret;
  299. /**
  300. * user data
  301. */
  302. void *data_ptr;
  303. };
  304. struct st_ptls_record_t {
  305. uint8_t type;
  306. uint16_t version;
  307. size_t length;
  308. const uint8_t *fragment;
  309. };
  310. #define MAX_UNKNOWN_EXTENSIONS 16
  311. #define MAX_CERTIFICATE_TYPES 8
  312. struct st_ptls_client_hello_t {
  313. uint16_t legacy_version;
  314. const uint8_t *random_bytes;
  315. ptls_iovec_t legacy_session_id;
  316. struct {
  317. const uint8_t *ids;
  318. size_t count;
  319. } compression_methods;
  320. uint16_t selected_version;
  321. ptls_iovec_t cipher_suites;
  322. ptls_iovec_t negotiated_groups;
  323. ptls_iovec_t key_shares;
  324. struct st_ptls_signature_algorithms_t signature_algorithms;
  325. ptls_iovec_t server_name;
  326. struct {
  327. ptls_iovec_t list[16];
  328. size_t count;
  329. } alpn;
  330. struct {
  331. uint16_t list[16];
  332. size_t count;
  333. } cert_compression_algos;
  334. struct {
  335. ptls_iovec_t all;
  336. ptls_iovec_t tbs;
  337. ptls_iovec_t ch1_hash;
  338. ptls_iovec_t signature;
  339. unsigned sent_key_share : 1;
  340. } cookie;
  341. struct {
  342. uint8_t list[MAX_CERTIFICATE_TYPES];
  343. size_t count;
  344. } server_certificate_types;
  345. unsigned status_request : 1;
  346. struct {
  347. uint8_t new_session_count;
  348. uint8_t resumption_count;
  349. } ticket_request;
  350. /**
  351. * ECH: payload.base != NULL indicates that the extension was received
  352. */
  353. struct {
  354. uint8_t type;
  355. uint8_t config_id;
  356. ptls_hpke_cipher_suite_id_t cipher_suite;
  357. ptls_iovec_t enc;
  358. ptls_iovec_t payload;
  359. } ech;
  360. struct {
  361. const uint8_t *hash_end;
  362. struct {
  363. ptls_client_hello_psk_identity_t list[4];
  364. size_t count;
  365. } identities;
  366. unsigned ke_modes;
  367. unsigned early_data_indication : 1;
  368. unsigned is_last_extension : 1;
  369. } psk;
  370. ptls_raw_extension_t unknown_extensions[MAX_UNKNOWN_EXTENSIONS + 1];
  371. size_t first_extension_at;
  372. };
  373. struct st_ptls_server_hello_t {
  374. uint8_t random_[PTLS_HELLO_RANDOM_SIZE];
  375. ptls_iovec_t legacy_session_id;
  376. int is_retry_request;
  377. union {
  378. ptls_iovec_t peerkey;
  379. struct {
  380. uint16_t selected_group;
  381. ptls_iovec_t cookie;
  382. const uint8_t *ech;
  383. } retry_request;
  384. };
  385. };
  386. struct st_ptls_key_schedule_t {
  387. unsigned generation; /* early secret (1), hanshake secret (2), master secret (3) */
  388. uint8_t secret[PTLS_MAX_DIGEST_SIZE];
  389. size_t num_hashes;
  390. struct {
  391. ptls_hash_algorithm_t *algo;
  392. ptls_hash_context_t *ctx, *ctx_outer;
  393. } hashes[1];
  394. };
  395. struct st_ptls_extension_decoder_t {
  396. uint16_t type;
  397. int (*cb)(ptls_t *tls, void *arg, const uint8_t *src, const uint8_t *const end);
  398. };
  399. struct st_ptls_extension_bitmap_t {
  400. uint64_t bits;
  401. };
  402. static const uint8_t zeroes_of_max_digest_size[PTLS_MAX_DIGEST_SIZE] = {0};
  403. static ptls_aead_context_t *new_aead(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, int is_enc, const void *secret,
  404. ptls_iovec_t hash_value, const char *label_prefix);
  405. static int server_finish_handshake(ptls_t *tls, ptls_message_emitter_t *emitter, int send_cert_verify,
  406. struct st_ptls_signature_algorithms_t *signature_algorithms);
  407. static int is_supported_version(uint16_t v)
  408. {
  409. size_t i;
  410. for (i = 0; i != PTLS_ELEMENTSOF(supported_versions); ++i)
  411. if (supported_versions[i] == v)
  412. return 1;
  413. return 0;
  414. }
  415. static int extension_bitmap_testandset(struct st_ptls_extension_bitmap_t *bitmap, int hstype, uint16_t extid)
  416. {
  417. #define HSTYPE_TO_BIT(hstype) ((uint64_t)1 << ((hstype) + 1)) /* min(hstype) is -1 (PSEUDO_HRR) */
  418. #define DEFINE_BIT(abbrev, hstype) static const uint64_t abbrev = HSTYPE_TO_BIT(PTLS_HANDSHAKE_TYPE_##hstype)
  419. #define EXT(candext, allowed_bits) \
  420. do { \
  421. if (PTLS_UNLIKELY(extid == PTLS_EXTENSION_TYPE_##candext)) { \
  422. allowed_hs_bits = allowed_bits; \
  423. goto Found; \
  424. } \
  425. ext_bitmap_mask <<= 1; \
  426. } while (0)
  427. DEFINE_BIT(CH, CLIENT_HELLO);
  428. DEFINE_BIT(SH, SERVER_HELLO);
  429. DEFINE_BIT(HRR, PSEUDO_HRR);
  430. DEFINE_BIT(EE, ENCRYPTED_EXTENSIONS);
  431. DEFINE_BIT(CR, CERTIFICATE_REQUEST);
  432. DEFINE_BIT(CT, CERTIFICATE);
  433. DEFINE_BIT(NST, NEW_SESSION_TICKET);
  434. uint64_t allowed_hs_bits, ext_bitmap_mask = 1;
  435. /* clang-format off */
  436. /* RFC 8446 section 4.2: "The table below indicates the messages where a given extension may appear... If an implementation
  437. * receives an extension which it recognizes and which is not specified for the message in which it appears, it MUST abort the
  438. * handshake with an "illegal_parameter" alert.
  439. *
  440. * +-------------------------+---------------+
  441. * + Extension | Allowed |
  442. * +-------------------------+---------------+ */
  443. EXT( SERVER_NAME , CH + EE );
  444. EXT( STATUS_REQUEST , CH + CR + CT );
  445. EXT( SUPPORTED_GROUPS , CH + EE );
  446. EXT( SIGNATURE_ALGORITHMS , CH + CR );
  447. EXT( ALPN , CH + EE );
  448. EXT( SERVER_CERTIFICATE_TYPE , CH + EE );
  449. EXT( KEY_SHARE , CH + SH + HRR );
  450. EXT( PRE_SHARED_KEY , CH + SH );
  451. EXT( PSK_KEY_EXCHANGE_MODES , CH );
  452. EXT( EARLY_DATA , CH + EE + NST );
  453. EXT( COOKIE , CH + HRR );
  454. EXT( SUPPORTED_VERSIONS , CH + SH + HRR );
  455. EXT( COMPRESS_CERTIFICATE , CH + CR ); /* from RFC 8879 */
  456. EXT( ENCRYPTED_CLIENT_HELLO , CH + HRR + EE ); /* from draft-ietf-tls-esni-15 */
  457. EXT( ECH_OUTER_EXTENSIONS , 0 );
  458. /* +-----------------------------------------+ */
  459. /* clang-format on */
  460. return 1;
  461. Found:
  462. if ((allowed_hs_bits & HSTYPE_TO_BIT(hstype)) == 0)
  463. return 0;
  464. if ((bitmap->bits & ext_bitmap_mask) != 0)
  465. return 0;
  466. bitmap->bits |= ext_bitmap_mask;
  467. return 1;
  468. #undef HSTYPE_TO_BIT
  469. #undef DEFINE_ABBREV
  470. #undef EXT
  471. }
  472. #ifndef ntoh16
  473. static uint16_t ntoh16(const uint8_t *src)
  474. {
  475. return (uint16_t)src[0] << 8 | src[1];
  476. }
  477. #endif
  478. #ifndef ntoh24
  479. static uint32_t ntoh24(const uint8_t *src)
  480. {
  481. return (uint32_t)src[0] << 16 | (uint32_t)src[1] << 8 | src[2];
  482. }
  483. #endif
  484. #ifndef ntoh32
  485. static uint32_t ntoh32(const uint8_t *src)
  486. {
  487. return (uint32_t)src[0] << 24 | (uint32_t)src[1] << 16 | (uint32_t)src[2] << 8 | src[3];
  488. }
  489. #endif
  490. #ifndef ntoh64
  491. static uint64_t ntoh64(const uint8_t *src)
  492. {
  493. return (uint64_t)src[0] << 56 | (uint64_t)src[1] << 48 | (uint64_t)src[2] << 40 | (uint64_t)src[3] << 32 |
  494. (uint64_t)src[4] << 24 | (uint64_t)src[5] << 16 | (uint64_t)src[6] << 8 | src[7];
  495. }
  496. #endif
  497. static void encode64(uint8_t *dst, uint64_t v)
  498. {
  499. for (size_t i = 0; i < 8; ++i)
  500. dst[i] = (uint8_t)(v >> (56 - 8 * i));
  501. }
  502. static char *duplicate_as_str(const void *src, size_t len)
  503. {
  504. char *dst;
  505. if ((dst = malloc(len + 1)) == NULL)
  506. return NULL;
  507. memcpy(dst, src, len);
  508. dst[len] = '\0';
  509. return dst;
  510. }
  511. void ptls_buffer__release_memory(ptls_buffer_t *buf)
  512. {
  513. ptls_clear_memory(buf->base, buf->off);
  514. if (buf->is_allocated) {
  515. #ifdef _WINDOWS
  516. if (buf->align_bits != 0) {
  517. _aligned_free(buf->base);
  518. } else {
  519. free(buf->base);
  520. }
  521. #else
  522. free(buf->base);
  523. #endif
  524. }
  525. }
  526. int ptls_buffer_reserve(ptls_buffer_t *buf, size_t delta)
  527. {
  528. return ptls_buffer_reserve_aligned(buf, delta, 0);
  529. }
  530. int ptls_buffer_reserve_aligned(ptls_buffer_t *buf, size_t delta, uint8_t align_bits)
  531. {
  532. if (buf->base == NULL)
  533. return PTLS_ERROR_NO_MEMORY;
  534. if (PTLS_MEMORY_DEBUG || buf->capacity < buf->off + delta ||
  535. (buf->align_bits < align_bits && ((uintptr_t)buf->base & (((uintptr_t)1 << align_bits) - 1)) != 0)) {
  536. void *newp;
  537. size_t new_capacity = buf->capacity;
  538. if (new_capacity < 1024)
  539. new_capacity = 1024;
  540. while (new_capacity < buf->off + delta) {
  541. new_capacity *= 2;
  542. }
  543. if (align_bits != 0) {
  544. #ifdef _WINDOWS
  545. if ((newp = _aligned_malloc(new_capacity, (size_t)1 << align_bits)) == NULL)
  546. return PTLS_ERROR_NO_MEMORY;
  547. #else
  548. if (posix_memalign(&newp, 1 << align_bits, new_capacity) != 0)
  549. return PTLS_ERROR_NO_MEMORY;
  550. #endif
  551. } else {
  552. if ((newp = malloc(new_capacity)) == NULL)
  553. return PTLS_ERROR_NO_MEMORY;
  554. }
  555. memcpy(newp, buf->base, buf->off);
  556. ptls_buffer__release_memory(buf);
  557. buf->base = newp;
  558. buf->capacity = new_capacity;
  559. buf->is_allocated = 1;
  560. buf->align_bits = align_bits;
  561. }
  562. return 0;
  563. }
  564. int ptls_buffer__do_pushv(ptls_buffer_t *buf, const void *src, size_t len)
  565. {
  566. int ret;
  567. if (len == 0)
  568. return 0;
  569. if ((ret = ptls_buffer_reserve(buf, len)) != 0)
  570. return ret;
  571. memcpy(buf->base + buf->off, src, len);
  572. buf->off += len;
  573. return 0;
  574. }
  575. int ptls_buffer__adjust_quic_blocksize(ptls_buffer_t *buf, size_t body_size)
  576. {
  577. uint8_t sizebuf[PTLS_ENCODE_QUICINT_CAPACITY];
  578. size_t sizelen = ptls_encode_quicint(sizebuf, body_size) - sizebuf;
  579. /* adjust amount of space before body_size to `sizelen` bytes */
  580. if (sizelen != 1) {
  581. int ret;
  582. if ((ret = ptls_buffer_reserve(buf, sizelen - 1)) != 0)
  583. return ret;
  584. memmove(buf->base + buf->off - body_size - 1 + sizelen, buf->base + buf->off - body_size, body_size);
  585. buf->off += sizelen - 1;
  586. }
  587. /* write the size */
  588. memcpy(buf->base + buf->off - body_size - sizelen, sizebuf, sizelen);
  589. return 0;
  590. }
  591. int ptls_buffer__adjust_asn1_blocksize(ptls_buffer_t *buf, size_t body_size)
  592. {
  593. fprintf(stderr, "unimplemented\n");
  594. abort();
  595. }
  596. int ptls_buffer_push_asn1_ubigint(ptls_buffer_t *buf, const void *bignum, size_t size)
  597. {
  598. const uint8_t *p = bignum, *const end = p + size;
  599. int ret;
  600. /* skip zeroes */
  601. for (; end - p >= 1; ++p)
  602. if (*p != 0)
  603. break;
  604. /* emit */
  605. ptls_buffer_push(buf, 2);
  606. ptls_buffer_push_asn1_block(buf, {
  607. if (*p >= 0x80)
  608. ptls_buffer_push(buf, 0);
  609. if (p != end) {
  610. ptls_buffer_pushv(buf, p, end - p);
  611. } else {
  612. ptls_buffer_pushv(buf, "", 1);
  613. }
  614. });
  615. ret = 0;
  616. Exit:
  617. return ret;
  618. }
  619. #if PTLS_FUZZ_HANDSHAKE
  620. static size_t aead_encrypt(struct st_ptls_traffic_protection_t *ctx, void *output, const void *input, size_t inlen,
  621. uint8_t content_type)
  622. {
  623. memcpy(output, input, inlen);
  624. memcpy(output + inlen, &content_type, 1);
  625. return inlen + 1 + 16;
  626. }
  627. static int aead_decrypt(struct st_ptls_traffic_protection_t *ctx, void *output, size_t *outlen, const void *input, size_t inlen)
  628. {
  629. if (inlen < 16) {
  630. return PTLS_ALERT_BAD_RECORD_MAC;
  631. }
  632. memcpy(output, input, inlen - 16);
  633. *outlen = inlen - 16; /* removing the 16 bytes of tag */
  634. return 0;
  635. }
  636. #else
  637. static void build_aad(uint8_t aad[5], size_t reclen)
  638. {
  639. aad[0] = PTLS_CONTENT_TYPE_APPDATA;
  640. aad[1] = PTLS_RECORD_VERSION_MAJOR;
  641. aad[2] = PTLS_RECORD_VERSION_MINOR;
  642. aad[3] = (uint8_t)(reclen >> 8);
  643. aad[4] = (uint8_t)reclen;
  644. }
  645. static size_t aead_encrypt(struct st_ptls_traffic_protection_t *ctx, void *output, const void *input, size_t inlen,
  646. uint8_t content_type)
  647. {
  648. ptls_iovec_t invec[2] = {ptls_iovec_init(input, inlen), ptls_iovec_init(&content_type, 1)};
  649. uint8_t aad[5];
  650. build_aad(aad, inlen + 1 + ctx->aead->algo->tag_size);
  651. ptls_aead_encrypt_v(ctx->aead, output, invec, PTLS_ELEMENTSOF(invec), ctx->seq++, aad, sizeof(aad));
  652. return inlen + 1 + ctx->aead->algo->tag_size;
  653. }
  654. static int aead_decrypt(struct st_ptls_traffic_protection_t *ctx, void *output, size_t *outlen, const void *input, size_t inlen)
  655. {
  656. uint8_t aad[5];
  657. build_aad(aad, inlen);
  658. if ((*outlen = ptls_aead_decrypt(ctx->aead, output, input, inlen, ctx->seq, aad, sizeof(aad))) == SIZE_MAX)
  659. return PTLS_ALERT_BAD_RECORD_MAC;
  660. ++ctx->seq;
  661. return 0;
  662. }
  663. #endif /* #if PTLS_FUZZ_HANDSHAKE */
  664. static void build_tls12_aad(uint8_t *aad, uint8_t type, uint64_t seq, uint16_t length)
  665. {
  666. for (size_t i = 0; i < 8; ++i)
  667. aad[i] = (uint8_t)(seq >> (56 - i * 8));
  668. aad[8] = type;
  669. aad[9] = PTLS_RECORD_VERSION_MAJOR;
  670. aad[10] = PTLS_RECORD_VERSION_MINOR;
  671. aad[11] = length >> 8;
  672. aad[12] = (uint8_t)length;
  673. }
  674. #define buffer_push_record(buf, type, block) \
  675. do { \
  676. ptls_buffer_push((buf), (type), PTLS_RECORD_VERSION_MAJOR, PTLS_RECORD_VERSION_MINOR); \
  677. ptls_buffer_push_block((buf), 2, block); \
  678. } while (0)
  679. static int buffer_push_encrypted_records(ptls_buffer_t *buf, uint8_t type, const uint8_t *src, size_t len,
  680. struct st_ptls_traffic_protection_t *enc)
  681. {
  682. int ret = 0;
  683. while (len != 0) {
  684. size_t chunk_size = len;
  685. if (chunk_size > PTLS_MAX_PLAINTEXT_RECORD_SIZE)
  686. chunk_size = PTLS_MAX_PLAINTEXT_RECORD_SIZE;
  687. if (enc->tls12) {
  688. buffer_push_record(buf, type, {
  689. /* reserve memory */
  690. if ((ret = ptls_buffer_reserve_aligned(
  691. buf, enc->aead->algo->tls12.record_iv_size + chunk_size + enc->aead->algo->tag_size,
  692. enc->aead->algo->align_bits)) != 0)
  693. goto Exit;
  694. /* determine nonce, as well as prepending that walue as the record IV (AES-GCM) */
  695. uint64_t nonce;
  696. if (enc->aead->algo->tls12.record_iv_size != 0) {
  697. assert(enc->aead->algo->tls12.record_iv_size == 8);
  698. nonce = enc->tls12_enc_record_iv++;
  699. encode64(buf->base + buf->off, nonce);
  700. buf->off += 8;
  701. } else {
  702. nonce = enc->seq;
  703. }
  704. /* build AAD */
  705. uint8_t aad[PTLS_TLS12_AAD_SIZE];
  706. build_tls12_aad(aad, type, enc->seq, (uint16_t)chunk_size);
  707. /* encrypt */
  708. buf->off += ptls_aead_encrypt(enc->aead, buf->base + buf->off, src, chunk_size, nonce, aad, sizeof(aad));
  709. ++enc->seq;
  710. });
  711. } else {
  712. buffer_push_record(buf, PTLS_CONTENT_TYPE_APPDATA, {
  713. if ((ret = ptls_buffer_reserve_aligned(buf, chunk_size + enc->aead->algo->tag_size + 1,
  714. enc->aead->algo->align_bits)) != 0)
  715. goto Exit;
  716. buf->off += aead_encrypt(enc, buf->base + buf->off, src, chunk_size, type);
  717. });
  718. }
  719. src += chunk_size;
  720. len -= chunk_size;
  721. }
  722. Exit:
  723. return ret;
  724. }
  725. static int buffer_encrypt_record(ptls_buffer_t *buf, size_t rec_start, struct st_ptls_traffic_protection_t *enc)
  726. {
  727. size_t bodylen = buf->off - rec_start - 5;
  728. uint8_t *tmpbuf, type = buf->base[rec_start];
  729. int ret;
  730. /* Fast path: do in-place encryption if only one record needs to be emitted. (For simplicity, do not take this path if TLS 1.2
  731. * is used, as this function will be called no more than once per connection, for encrypting an alert.) */
  732. if (!enc->tls12 && bodylen <= PTLS_MAX_PLAINTEXT_RECORD_SIZE) {
  733. size_t overhead = 1 + enc->aead->algo->tag_size;
  734. if ((ret = ptls_buffer_reserve_aligned(buf, overhead, enc->aead->algo->align_bits)) != 0)
  735. return ret;
  736. size_t encrypted_len = aead_encrypt(enc, buf->base + rec_start + 5, buf->base + rec_start + 5, bodylen, type);
  737. assert(encrypted_len == bodylen + overhead);
  738. buf->off += overhead;
  739. buf->base[rec_start] = PTLS_CONTENT_TYPE_APPDATA;
  740. buf->base[rec_start + 3] = (encrypted_len >> 8) & 0xff;
  741. buf->base[rec_start + 4] = encrypted_len & 0xff;
  742. return 0;
  743. }
  744. /* move plaintext to temporary buffer */
  745. if ((tmpbuf = malloc(bodylen)) == NULL) {
  746. ret = PTLS_ERROR_NO_MEMORY;
  747. goto Exit;
  748. }
  749. memcpy(tmpbuf, buf->base + rec_start + 5, bodylen);
  750. ptls_clear_memory(buf->base + rec_start, bodylen + 5);
  751. buf->off = rec_start;
  752. /* push encrypted records */
  753. ret = buffer_push_encrypted_records(buf, type, tmpbuf, bodylen, enc);
  754. Exit:
  755. if (tmpbuf != NULL) {
  756. ptls_clear_memory(tmpbuf, bodylen);
  757. free(tmpbuf);
  758. }
  759. return ret;
  760. }
  761. static int begin_record_message(ptls_message_emitter_t *_self)
  762. {
  763. struct st_ptls_record_message_emitter_t *self = (void *)_self;
  764. int ret;
  765. self->rec_start = self->super.buf->off;
  766. ptls_buffer_push(self->super.buf, PTLS_CONTENT_TYPE_HANDSHAKE, PTLS_RECORD_VERSION_MAJOR, PTLS_RECORD_VERSION_MINOR, 0, 0);
  767. ret = 0;
  768. Exit:
  769. return ret;
  770. }
  771. static int commit_record_message(ptls_message_emitter_t *_self)
  772. {
  773. struct st_ptls_record_message_emitter_t *self = (void *)_self;
  774. int ret;
  775. if (self->super.enc->aead != NULL) {
  776. ret = buffer_encrypt_record(self->super.buf, self->rec_start, self->super.enc);
  777. } else {
  778. /* TODO allow CH,SH,HRR above 16KB */
  779. size_t sz = self->super.buf->off - self->rec_start - 5;
  780. assert(sz <= PTLS_MAX_PLAINTEXT_RECORD_SIZE);
  781. self->super.buf->base[self->rec_start + 3] = (uint8_t)(sz >> 8);
  782. self->super.buf->base[self->rec_start + 4] = (uint8_t)(sz);
  783. ret = 0;
  784. }
  785. return ret;
  786. }
  787. #define buffer_push_extension(buf, type, block) \
  788. do { \
  789. ptls_buffer_push16((buf), (type)); \
  790. ptls_buffer_push_block((buf), 2, block); \
  791. } while (0);
  792. #define decode_open_extensions(src, end, hstype, exttype, block) \
  793. do { \
  794. struct st_ptls_extension_bitmap_t bitmap = {0}; \
  795. ptls_decode_open_block((src), end, 2, { \
  796. while ((src) != end) { \
  797. if ((ret = ptls_decode16((exttype), &(src), end)) != 0) \
  798. goto Exit; \
  799. if (!extension_bitmap_testandset(&bitmap, (hstype), *(exttype))) { \
  800. ret = PTLS_ALERT_ILLEGAL_PARAMETER; \
  801. goto Exit; \
  802. } \
  803. ptls_decode_open_block((src), end, 2, block); \
  804. } \
  805. }); \
  806. } while (0)
  807. #define decode_extensions(src, end, hstype, exttype, block) \
  808. do { \
  809. decode_open_extensions((src), end, hstype, exttype, block); \
  810. ptls_decode_assert_block_close((src), end); \
  811. } while (0)
  812. int ptls_decode8(uint8_t *value, const uint8_t **src, const uint8_t *end)
  813. {
  814. if (*src == end)
  815. return PTLS_ALERT_DECODE_ERROR;
  816. *value = *(*src)++;
  817. return 0;
  818. }
  819. int ptls_decode16(uint16_t *value, const uint8_t **src, const uint8_t *end)
  820. {
  821. if (end - *src < 2)
  822. return PTLS_ALERT_DECODE_ERROR;
  823. *value = ntoh16(*src);
  824. *src += 2;
  825. return 0;
  826. }
  827. int ptls_decode24(uint32_t *value, const uint8_t **src, const uint8_t *end)
  828. {
  829. if (end - *src < 3)
  830. return PTLS_ALERT_DECODE_ERROR;
  831. *value = ((uint32_t)(*src)[0] << 16) | ((uint32_t)(*src)[1] << 8) | (*src)[2];
  832. *src += 3;
  833. return 0;
  834. }
  835. int ptls_decode32(uint32_t *value, const uint8_t **src, const uint8_t *end)
  836. {
  837. if (end - *src < 4)
  838. return PTLS_ALERT_DECODE_ERROR;
  839. *value = ntoh32(*src);
  840. *src += 4;
  841. return 0;
  842. }
  843. int ptls_decode64(uint64_t *value, const uint8_t **src, const uint8_t *end)
  844. {
  845. if (end - *src < 8)
  846. return PTLS_ALERT_DECODE_ERROR;
  847. *value = ntoh64(*src);
  848. *src += 8;
  849. return 0;
  850. }
  851. uint64_t ptls_decode_quicint(const uint8_t **src, const uint8_t *end)
  852. {
  853. if (PTLS_UNLIKELY(*src == end))
  854. return UINT64_MAX;
  855. uint8_t b = *(*src)++;
  856. if (PTLS_LIKELY(b <= 0x3f))
  857. return b;
  858. uint64_t v = b & 0x3f;
  859. unsigned bytes_left = (1 << (b >> 6)) - 1;
  860. if (PTLS_UNLIKELY((size_t)(end - *src) < bytes_left))
  861. return UINT64_MAX;
  862. do {
  863. v = (v << 8) | *(*src)++;
  864. } while (--bytes_left != 0);
  865. return v;
  866. }
  867. static void log_secret(ptls_t *tls, const char *type, ptls_iovec_t secret)
  868. {
  869. char hexbuf[PTLS_MAX_DIGEST_SIZE * 2 + 1];
  870. PTLS_PROBE(NEW_SECRET, tls, type, ptls_hexdump(hexbuf, secret.base, secret.len));
  871. PTLS_LOG_CONN(new_secret, tls, { PTLS_LOG_ELEMENT_SAFESTR(label, type); });
  872. if (tls->ctx->log_event != NULL)
  873. tls->ctx->log_event->cb(tls->ctx->log_event, tls, type, "%s", ptls_hexdump(hexbuf, secret.base, secret.len));
  874. }
  875. /**
  876. * This function preserves the flags and modes (e.g., `offered`, `accepted`, `cipher`), they can be used afterwards.
  877. */
  878. static void clear_ech(struct st_ptls_ech_t *ech, int is_server)
  879. {
  880. if (ech->aead != NULL) {
  881. ptls_aead_free(ech->aead);
  882. ech->aead = NULL;
  883. }
  884. ptls_clear_memory(ech->inner_client_random, PTLS_HELLO_RANDOM_SIZE);
  885. if (!is_server) {
  886. free(ech->client.enc.base);
  887. ech->client.enc = ptls_iovec_init(NULL, 0);
  888. if (ech->client.public_name != NULL) {
  889. free(ech->client.public_name);
  890. ech->client.public_name = NULL;
  891. }
  892. free(ech->client.first_ech.base);
  893. ech->client.first_ech = ptls_iovec_init(NULL, 0);
  894. }
  895. }
  896. /**
  897. * Decodes one ECHConfigContents (tls-esni-15 section 4). `decoded->kem` and `cipher` may be NULL even when the function returns
  898. * zero, if the corresponding entries are not found.
  899. */
  900. static int decode_one_ech_config(ptls_hpke_kem_t **kems, ptls_hpke_cipher_suite_t **ciphers,
  901. struct st_decoded_ech_config_t *decoded, const uint8_t **src, const uint8_t *const end)
  902. {
  903. char *public_name_buf = NULL;
  904. int ret;
  905. *decoded = (struct st_decoded_ech_config_t){0};
  906. if ((ret = ptls_decode8(&decoded->id, src, end)) != 0)
  907. goto Exit;
  908. uint16_t kem_id;
  909. if ((ret = ptls_decode16(&kem_id, src, end)) != 0)
  910. goto Exit;
  911. for (size_t i = 0; kems[i] != NULL; ++i) {
  912. if (kems[i]->id == kem_id) {
  913. decoded->kem = kems[i];
  914. break;
  915. }
  916. }
  917. ptls_decode_open_block(*src, end, 2, {
  918. if (*src == end) {
  919. ret = PTLS_ALERT_DECODE_ERROR;
  920. goto Exit;
  921. }
  922. decoded->public_key = ptls_iovec_init(*src, end - *src);
  923. *src = end;
  924. });
  925. ptls_decode_open_block(*src, end, 2, {
  926. do {
  927. uint16_t kdf_id;
  928. uint16_t aead_id;
  929. if ((ret = ptls_decode16(&kdf_id, src, end)) != 0)
  930. goto Exit;
  931. if ((ret = ptls_decode16(&aead_id, src, end)) != 0)
  932. goto Exit;
  933. if (decoded->cipher == NULL) {
  934. for (size_t i = 0; ciphers[i] != NULL; ++i) {
  935. if (ciphers[i]->id.kdf == kdf_id && ciphers[i]->id.aead == aead_id) {
  936. decoded->cipher = ciphers[i];
  937. break;
  938. }
  939. }
  940. }
  941. } while (*src != end);
  942. });
  943. if ((ret = ptls_decode8(&decoded->max_name_length, src, end)) != 0)
  944. goto Exit;
  945. #define SKIP_DECODED() \
  946. do { \
  947. decoded->kem = NULL; \
  948. decoded->cipher = NULL; \
  949. } while (0)
  950. /* Decode public_name. The specification requires clients to ignore (upon parsing ESNIConfigList) or reject (upon handshake)
  951. * public names that are not DNS names or IPv4 addresses. We ignore IPv4 and v6 addresses during parsing (IPv6 addresses never
  952. * looks like DNS names), and delegate the responsibility of rejecting non-DNS names to the certificate verify callback. */
  953. ptls_decode_open_block(*src, end, 1, {
  954. if (*src == end) {
  955. ret = PTLS_ALERT_DECODE_ERROR;
  956. goto Exit;
  957. }
  958. if ((public_name_buf = duplicate_as_str(*src, end - *src)) == NULL) {
  959. ret = PTLS_ERROR_NO_MEMORY;
  960. goto Exit;
  961. }
  962. if (ptls_server_name_is_ipaddr(public_name_buf)) {
  963. SKIP_DECODED();
  964. } else {
  965. decoded->public_name = ptls_iovec_init(*src, end - *src);
  966. }
  967. *src = end;
  968. });
  969. ptls_decode_block(*src, end, 2, {
  970. while (*src < end) {
  971. uint16_t type;
  972. if ((ret = ptls_decode16(&type, src, end)) != 0)
  973. goto Exit;
  974. ptls_decode_open_block(*src, end, 2, { *src = end; });
  975. /* if a critital extension is found, indicate that the config cannot be used */
  976. if ((type & 0x8000) != 0)
  977. SKIP_DECODED();
  978. }
  979. });
  980. #undef SKIP_DECODED
  981. Exit:
  982. free(public_name_buf);
  983. return ret;
  984. }
  985. static int client_decode_ech_config_list(ptls_context_t *ctx, struct st_decoded_ech_config_t *decoded, ptls_iovec_t config_list)
  986. {
  987. const uint8_t *src = config_list.base, *const end = src + config_list.len;
  988. int match_found = 0, ret;
  989. *decoded = (struct st_decoded_ech_config_t){0};
  990. ptls_decode_block(src, end, 2, {
  991. do {
  992. const uint8_t *config_start = src;
  993. uint16_t version;
  994. if ((ret = ptls_decode16(&version, &src, end)) != 0)
  995. goto Exit;
  996. ptls_decode_open_block(src, end, 2, {
  997. /* If the block is the one that we recognize, parse it, then adopt if if possible. Otherwise, skip. */
  998. if (version == PTLS_ECH_CONFIG_VERSION) {
  999. struct st_decoded_ech_config_t thisconf;
  1000. if ((ret = decode_one_ech_config(ctx->ech.client.kems, ctx->ech.client.ciphers, &thisconf, &src, end)) != 0)
  1001. goto Exit;
  1002. if (!match_found && thisconf.kem != NULL && thisconf.cipher != NULL) {
  1003. *decoded = thisconf;
  1004. decoded->bytes = ptls_iovec_init(config_start, end - config_start);
  1005. match_found = 1;
  1006. }
  1007. } else {
  1008. src = end;
  1009. }
  1010. });
  1011. } while (src != end);
  1012. });
  1013. ret = 0;
  1014. Exit:
  1015. if (ret != 0)
  1016. *decoded = (struct st_decoded_ech_config_t){0};
  1017. return ret;
  1018. }
  1019. static int client_setup_ech(struct st_ptls_ech_t *ech, struct st_decoded_ech_config_t *decoded,
  1020. void (*random_bytes)(void *, size_t))
  1021. {
  1022. ptls_buffer_t infobuf;
  1023. uint8_t infobuf_smallbuf[256];
  1024. int ret;
  1025. /* setup `enc` and `aead` by running HPKE */
  1026. ptls_buffer_init(&infobuf, infobuf_smallbuf, sizeof(infobuf_smallbuf));
  1027. ptls_buffer_pushv(&infobuf, ech_info_prefix, sizeof(ech_info_prefix));
  1028. ptls_buffer_pushv(&infobuf, decoded->bytes.base, decoded->bytes.len);
  1029. if ((ret = ptls_hpke_setup_base_s(decoded->kem, decoded->cipher, &ech->client.enc, &ech->aead, decoded->public_key,
  1030. ptls_iovec_init(infobuf.base, infobuf.off))) != 0)
  1031. goto Exit;
  1032. /* setup the rest */
  1033. ech->config_id = decoded->id;
  1034. ech->kem = decoded->kem;
  1035. ech->cipher = decoded->cipher;
  1036. random_bytes(ech->inner_client_random, PTLS_HELLO_RANDOM_SIZE);
  1037. ech->client.max_name_length = decoded->max_name_length;
  1038. if ((ech->client.public_name = duplicate_as_str(decoded->public_name.base, decoded->public_name.len)) == NULL) {
  1039. ret = PTLS_ERROR_NO_MEMORY;
  1040. goto Exit;
  1041. }
  1042. Exit:
  1043. if (ret != 0)
  1044. clear_ech(ech, 0);
  1045. return ret;
  1046. }
  1047. static void client_setup_ech_grease(struct st_ptls_ech_t *ech, void (*random_bytes)(void *, size_t), ptls_hpke_kem_t **kems,
  1048. ptls_hpke_cipher_suite_t **ciphers, const char *sni_name)
  1049. {
  1050. static const size_t x25519_key_size = 32;
  1051. uint8_t random_secret[PTLS_AES128_KEY_SIZE + PTLS_AES_IV_SIZE];
  1052. /* pick up X25519, AES-128-GCM or bail out */
  1053. for (size_t i = 0; kems[i] != NULL; ++i) {
  1054. if (kems[i]->id == PTLS_HPKE_KEM_X25519_SHA256) {
  1055. ech->kem = kems[i];
  1056. break;
  1057. }
  1058. }
  1059. for (size_t i = 0; ciphers[i] != NULL; ++i) {
  1060. if (ciphers[i]->id.kdf == PTLS_HPKE_HKDF_SHA256 && ciphers[i]->id.aead == PTLS_HPKE_AEAD_AES_128_GCM) {
  1061. ech->cipher = ciphers[i];
  1062. break;
  1063. }
  1064. }
  1065. if (ech->kem == NULL || ech->cipher == NULL)
  1066. goto Fail;
  1067. /* aead is generated from random */
  1068. random_bytes(random_secret, sizeof(random_secret));
  1069. ech->aead = ptls_aead_new_direct(ech->cipher->aead, 1, random_secret, random_secret + PTLS_AES128_KEY_SIZE);
  1070. /* `enc` is random bytes */
  1071. if ((ech->client.enc.base = malloc(x25519_key_size)) == NULL)
  1072. goto Fail;
  1073. ech->client.enc.len = x25519_key_size;
  1074. random_bytes(ech->client.enc.base, ech->client.enc.len);
  1075. /* setup the rest (inner_client_random is left zeros) */
  1076. random_bytes(&ech->config_id, sizeof(ech->config_id));
  1077. ech->client.max_name_length = 64;
  1078. if ((ech->client.public_name = duplicate_as_str(sni_name, strlen(sni_name))) == NULL)
  1079. goto Fail;
  1080. return;
  1081. Fail:
  1082. clear_ech(ech, 0);
  1083. }
  1084. #define ECH_CONFIRMATION_SERVER_HELLO "ech accept confirmation"
  1085. #define ECH_CONFIRMATION_HRR "hrr ech accept confirmation"
  1086. static int ech_calc_confirmation(ptls_key_schedule_t *sched, void *dst, const uint8_t *inner_random, const char *label,
  1087. ptls_iovec_t message)
  1088. {
  1089. ptls_hash_context_t *hash = NULL;
  1090. uint8_t secret[PTLS_MAX_DIGEST_SIZE], transcript_hash[PTLS_MAX_DIGEST_SIZE];
  1091. int ret;
  1092. /* calc transcript hash using the modified ServerHello / HRR */
  1093. if ((hash = sched->hashes[0].ctx->clone_(sched->hashes[0].ctx)) == NULL) {
  1094. ret = PTLS_ERROR_NO_MEMORY;
  1095. goto Exit;
  1096. }
  1097. hash->update(hash, message.base, message.len);
  1098. hash->final(hash, transcript_hash, PTLS_HASH_FINAL_MODE_FREE);
  1099. hash = NULL;
  1100. /* HKDF extract and expand */
  1101. if ((ret = ptls_hkdf_extract(sched->hashes[0].algo, secret, ptls_iovec_init(NULL, 0),
  1102. ptls_iovec_init(inner_random, PTLS_HELLO_RANDOM_SIZE))) != 0)
  1103. goto Exit;
  1104. if ((ret = ptls_hkdf_expand_label(sched->hashes[0].algo, dst, 8, ptls_iovec_init(secret, sched->hashes[0].algo->digest_size),
  1105. label, ptls_iovec_init(transcript_hash, sched->hashes[0].algo->digest_size), NULL)) != 0)
  1106. goto Exit;
  1107. Exit:
  1108. ptls_clear_memory(secret, sizeof(secret));
  1109. ptls_clear_memory(transcript_hash, sizeof(transcript_hash));
  1110. if (hash != NULL)
  1111. hash->final(hash, NULL, PTLS_HASH_FINAL_MODE_FREE);
  1112. return ret;
  1113. }
  1114. static void key_schedule_free(ptls_key_schedule_t *sched)
  1115. {
  1116. size_t i;
  1117. ptls_clear_memory(sched->secret, sizeof(sched->secret));
  1118. for (i = 0; i != sched->num_hashes; ++i) {
  1119. sched->hashes[i].ctx->final(sched->hashes[i].ctx, NULL, PTLS_HASH_FINAL_MODE_FREE);
  1120. if (sched->hashes[i].ctx_outer != NULL)
  1121. sched->hashes[i].ctx_outer->final(sched->hashes[i].ctx_outer, NULL, PTLS_HASH_FINAL_MODE_FREE);
  1122. }
  1123. free(sched);
  1124. }
  1125. static ptls_key_schedule_t *key_schedule_new(ptls_cipher_suite_t *preferred, ptls_cipher_suite_t **offered, int use_outer)
  1126. {
  1127. #define FOREACH_HASH(block) \
  1128. do { \
  1129. ptls_cipher_suite_t *cs; \
  1130. if ((cs = preferred) != NULL) { \
  1131. block \
  1132. } \
  1133. if (offered != NULL) { \
  1134. size_t i, j; \
  1135. for (i = 0; (cs = offered[i]) != NULL; ++i) { \
  1136. if (preferred == NULL || cs->hash != preferred->hash) { \
  1137. for (j = 0; j != i; ++j) \
  1138. if (cs->hash == offered[j]->hash) \
  1139. break; \
  1140. if (j == i) { \
  1141. block \
  1142. } \
  1143. } \
  1144. } \
  1145. } \
  1146. } while (0)
  1147. ptls_key_schedule_t *sched;
  1148. { /* allocate */
  1149. size_t num_hashes = 0;
  1150. FOREACH_HASH({ ++num_hashes; });
  1151. if ((sched = malloc(offsetof(ptls_key_schedule_t, hashes) + sizeof(sched->hashes[0]) * num_hashes)) == NULL)
  1152. return NULL;
  1153. *sched = (ptls_key_schedule_t){0};
  1154. }
  1155. /* setup the hash algos and contexts */
  1156. FOREACH_HASH({
  1157. sched->hashes[sched->num_hashes].algo = cs->hash;
  1158. if ((sched->hashes[sched->num_hashes].ctx = cs->hash->create()) == NULL)
  1159. goto Fail;
  1160. if (use_outer) {
  1161. if ((sched->hashes[sched->num_hashes].ctx_outer = cs->hash->create()) == NULL)
  1162. goto Fail;
  1163. } else {
  1164. sched->hashes[sched->num_hashes].ctx_outer = NULL;
  1165. }
  1166. ++sched->num_hashes;
  1167. });
  1168. return sched;
  1169. Fail:
  1170. key_schedule_free(sched);
  1171. return NULL;
  1172. #undef FOREACH_HASH
  1173. }
  1174. static int key_schedule_extract(ptls_key_schedule_t *sched, ptls_iovec_t ikm)
  1175. {
  1176. int ret;
  1177. if (ikm.base == NULL)
  1178. ikm = ptls_iovec_init(zeroes_of_max_digest_size, sched->hashes[0].algo->digest_size);
  1179. if (sched->generation != 0 &&
  1180. (ret = ptls_hkdf_expand_label(sched->hashes[0].algo, sched->secret, sched->hashes[0].algo->digest_size,
  1181. ptls_iovec_init(sched->secret, sched->hashes[0].algo->digest_size), "derived",
  1182. ptls_iovec_init(sched->hashes[0].algo->empty_digest, sched->hashes[0].algo->digest_size),
  1183. NULL)) != 0)
  1184. return ret;
  1185. ++sched->generation;
  1186. ret = ptls_hkdf_extract(sched->hashes[0].algo, sched->secret,
  1187. ptls_iovec_init(sched->secret, sched->hashes[0].algo->digest_size), ikm);
  1188. PTLS_DEBUGF("%s: %u, %02x%02x\n", __FUNCTION__, sched->generation, (int)sched->secret[0], (int)sched->secret[1]);
  1189. return ret;
  1190. }
  1191. static int key_schedule_select_cipher(ptls_key_schedule_t *sched, ptls_cipher_suite_t *cs, int reset, ptls_iovec_t reset_ikm)
  1192. {
  1193. size_t found_slot = SIZE_MAX, i;
  1194. int ret;
  1195. assert(sched->generation == 1);
  1196. /* find the one, while freeing others */
  1197. for (i = 0; i != sched->num_hashes; ++i) {
  1198. if (sched->hashes[i].algo == cs->hash) {
  1199. assert(found_slot == SIZE_MAX);
  1200. found_slot = i;
  1201. } else {
  1202. sched->hashes[i].ctx->final(sched->hashes[i].ctx, NULL, PTLS_HASH_FINAL_MODE_FREE);
  1203. if (sched->hashes[i].ctx_outer != NULL)
  1204. sched->hashes[i].ctx_outer->final(sched->hashes[i].ctx_outer, NULL, PTLS_HASH_FINAL_MODE_FREE);
  1205. }
  1206. }
  1207. if (found_slot != 0) {
  1208. sched->hashes[0] = sched->hashes[found_slot];
  1209. reset = 1;
  1210. }
  1211. sched->num_hashes = 1;
  1212. /* recalculate the hash if a different hash as been selected than the one we used for calculating the early secrets */
  1213. if (reset) {
  1214. --sched->generation;
  1215. memset(sched->secret, 0, sizeof(sched->secret));
  1216. if ((ret = key_schedule_extract(sched, reset_ikm)) != 0)
  1217. goto Exit;
  1218. }
  1219. ret = 0;
  1220. Exit:
  1221. return ret;
  1222. }
  1223. static void key_schedule_select_outer(ptls_key_schedule_t *sched)
  1224. {
  1225. /* This function is called when receiving a cleartext message (Server Hello), after the cipher-suite is determined (and hence
  1226. * the hash also), if ECH was offered */
  1227. assert(sched->generation == 1);
  1228. assert(sched->num_hashes == 1);
  1229. assert(sched->hashes[0].ctx_outer != NULL);
  1230. sched->hashes[0].ctx->final(sched->hashes[0].ctx, NULL, PTLS_HASH_FINAL_MODE_FREE);
  1231. sched->hashes[0].ctx = sched->hashes[0].ctx_outer;
  1232. sched->hashes[0].ctx_outer = NULL;
  1233. }
  1234. void ptls__key_schedule_update_hash(ptls_key_schedule_t *sched, const uint8_t *msg, size_t msglen, int use_outer)
  1235. {
  1236. size_t i;
  1237. PTLS_DEBUGF("%s:%p:len=%zu\n", __FUNCTION__, sched, msglen);
  1238. for (i = 0; i != sched->num_hashes; ++i) {
  1239. ptls_hash_context_t *ctx = use_outer ? sched->hashes[i].ctx_outer : sched->hashes[i].ctx;
  1240. ctx->update(ctx, msg, msglen);
  1241. #if defined(PTLS_DEBUG) && PTLS_DEBUG
  1242. {
  1243. uint8_t digest[PTLS_MAX_DIGEST_SIZE];
  1244. ctx->final(ctx, digest, PTLS_HASH_FINAL_MODE_SNAPSHOT);
  1245. PTLS_DEBUGF(" %zu: %02x%02x%02x%02x\n", i, digest[0], digest[1], digest[2], digest[3]);
  1246. }
  1247. #endif
  1248. }
  1249. }
  1250. static void key_schedule_update_ch1hash_prefix(ptls_key_schedule_t *sched)
  1251. {
  1252. uint8_t prefix[4] = {PTLS_HANDSHAKE_TYPE_MESSAGE_HASH, 0, 0, (uint8_t)sched->hashes[0].algo->digest_size};
  1253. ptls__key_schedule_update_hash(sched, prefix, sizeof(prefix), 0);
  1254. }
  1255. static void key_schedule_extract_ch1hash(ptls_key_schedule_t *sched, uint8_t *hash)
  1256. {
  1257. assert(sched->hashes[0].ctx_outer == NULL);
  1258. sched->hashes[0].ctx->final(sched->hashes[0].ctx, hash, PTLS_HASH_FINAL_MODE_RESET);
  1259. }
  1260. static void key_schedule_transform_post_ch1hash(ptls_key_schedule_t *sched)
  1261. {
  1262. size_t digest_size = sched->hashes[0].algo->digest_size;
  1263. ptls_hash_context_t *hashes[3] = {sched->hashes[0].ctx, sched->hashes[0].ctx_outer, NULL};
  1264. uint8_t ch1hash[PTLS_MAX_DIGEST_SIZE];
  1265. uint8_t prefix[4] = {PTLS_HANDSHAKE_TYPE_MESSAGE_HASH, 0, 0, (uint8_t)digest_size};
  1266. for (size_t i = 0; hashes[i] != NULL; ++i) {
  1267. hashes[i]->final(hashes[i], ch1hash, PTLS_HASH_FINAL_MODE_RESET);
  1268. hashes[i]->update(hashes[i], prefix, sizeof(prefix));
  1269. hashes[i]->update(hashes[i], ch1hash, digest_size);
  1270. }
  1271. ptls_clear_memory(ch1hash, sizeof(ch1hash));
  1272. }
  1273. static int derive_secret_with_hash(ptls_key_schedule_t *sched, void *secret, const char *label, const uint8_t *hash)
  1274. {
  1275. int ret = ptls_hkdf_expand_label(sched->hashes[0].algo, secret, sched->hashes[0].algo->digest_size,
  1276. ptls_iovec_init(sched->secret, sched->hashes[0].algo->digest_size), label,
  1277. ptls_iovec_init(hash, sched->hashes[0].algo->digest_size), NULL);
  1278. PTLS_DEBUGF("%s: (label=%s, hash=%02x%02x) => %02x%02x\n", __FUNCTION__, label, hash[0], hash[1], ((uint8_t *)secret)[0],
  1279. ((uint8_t *)secret)[1]);
  1280. return ret;
  1281. }
  1282. static int derive_secret(ptls_key_schedule_t *sched, void *secret, const char *label)
  1283. {
  1284. uint8_t hash_value[PTLS_MAX_DIGEST_SIZE];
  1285. sched->hashes[0].ctx->final(sched->hashes[0].ctx, hash_value, PTLS_HASH_FINAL_MODE_SNAPSHOT);
  1286. int ret = derive_secret_with_hash(sched, secret, label, hash_value);
  1287. ptls_clear_memory(hash_value, sizeof(hash_value));
  1288. return ret;
  1289. }
  1290. static int derive_secret_with_empty_digest(ptls_key_schedule_t *sched, void *secret, const char *label)
  1291. {
  1292. return derive_secret_with_hash(sched, secret, label, sched->hashes[0].algo->empty_digest);
  1293. }
  1294. static int derive_exporter_secret(ptls_t *tls, int is_early)
  1295. {
  1296. int ret;
  1297. if (!tls->ctx->use_exporter)
  1298. return 0;
  1299. uint8_t **slot = is_early ? &tls->exporter_master_secret.early : &tls->exporter_master_secret.one_rtt;
  1300. assert(*slot == NULL);
  1301. if ((*slot = malloc(tls->key_schedule->hashes[0].algo->digest_size)) == NULL)
  1302. return PTLS_ERROR_NO_MEMORY;
  1303. if ((ret = derive_secret(tls->key_schedule, *slot, is_early ? "e exp master" : "exp master")) != 0)
  1304. return ret;
  1305. log_secret(tls, is_early ? "EARLY_EXPORTER_SECRET" : "EXPORTER_SECRET",
  1306. ptls_iovec_init(*slot, tls->key_schedule->hashes[0].algo->digest_size));
  1307. return 0;
  1308. }
  1309. static void free_exporter_master_secret(ptls_t *tls, int is_early)
  1310. {
  1311. uint8_t *slot = is_early ? tls->exporter_master_secret.early : tls->exporter_master_secret.one_rtt;
  1312. if (slot == NULL)
  1313. return;
  1314. assert(tls->key_schedule != NULL);
  1315. ptls_clear_memory(slot, tls->key_schedule->hashes[0].algo->digest_size);
  1316. free(slot);
  1317. }
  1318. static int derive_resumption_secret(ptls_key_schedule_t *sched, uint8_t *secret, ptls_iovec_t nonce)
  1319. {
  1320. int ret;
  1321. if ((ret = derive_secret(sched, secret, "res master")) != 0)
  1322. goto Exit;
  1323. if ((ret = ptls_hkdf_expand_label(sched->hashes[0].algo, secret, sched->hashes[0].algo->digest_size,
  1324. ptls_iovec_init(secret, sched->hashes[0].algo->digest_size), "resumption", nonce, NULL)) != 0)
  1325. goto Exit;
  1326. Exit:
  1327. if (ret != 0)
  1328. ptls_clear_memory(secret, sched->hashes[0].algo->digest_size);
  1329. return ret;
  1330. }
  1331. static int decode_new_session_ticket(ptls_t *tls, uint32_t *lifetime, uint32_t *age_add, ptls_iovec_t *nonce, ptls_iovec_t *ticket,
  1332. uint32_t *max_early_data_size, const uint8_t *src, const uint8_t *const end)
  1333. {
  1334. uint16_t exttype;
  1335. int ret;
  1336. if ((ret = ptls_decode32(lifetime, &src, end)) != 0)
  1337. goto Exit;
  1338. if ((ret = ptls_decode32(age_add, &src, end)) != 0)
  1339. goto Exit;
  1340. ptls_decode_open_block(src, end, 1, {
  1341. *nonce = ptls_iovec_init(src, end - src);
  1342. src = end;
  1343. });
  1344. ptls_decode_open_block(src, end, 2, {
  1345. if (src == end) {
  1346. ret = PTLS_ALERT_DECODE_ERROR;
  1347. goto Exit;
  1348. }
  1349. *ticket = ptls_iovec_init(src, end - src);
  1350. src = end;
  1351. });
  1352. *max_early_data_size = 0;
  1353. decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET, &exttype, {
  1354. if (tls->ctx->on_extension != NULL &&
  1355. (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET, exttype,
  1356. ptls_iovec_init(src, end - src)) != 0))
  1357. goto Exit;
  1358. switch (exttype) {
  1359. case PTLS_EXTENSION_TYPE_EARLY_DATA:
  1360. if ((ret = ptls_decode32(max_early_data_size, &src, end)) != 0)
  1361. goto Exit;
  1362. break;
  1363. default:
  1364. src = end;
  1365. break;
  1366. }
  1367. });
  1368. ret = 0;
  1369. Exit:
  1370. return ret;
  1371. }
  1372. static int decode_stored_session_ticket(ptls_t *tls, ptls_key_exchange_algorithm_t **key_share, ptls_cipher_suite_t **cs,
  1373. ptls_iovec_t *secret, uint32_t *obfuscated_ticket_age, ptls_iovec_t *ticket,
  1374. uint32_t *max_early_data_size, const uint8_t *src, const uint8_t *const end)
  1375. {
  1376. uint16_t kxid, csid;
  1377. uint32_t lifetime, age_add;
  1378. uint64_t obtained_at, now;
  1379. ptls_iovec_t nonce;
  1380. int ret;
  1381. /* decode */
  1382. if ((ret = ptls_decode64(&obtained_at, &src, end)) != 0)
  1383. goto Exit;
  1384. if ((ret = ptls_decode16(&kxid, &src, end)) != 0)
  1385. goto Exit;
  1386. if ((ret = ptls_decode16(&csid, &src, end)) != 0)
  1387. goto Exit;
  1388. ptls_decode_open_block(src, end, 3, {
  1389. if ((ret = decode_new_session_ticket(tls, &lifetime, &age_add, &nonce, ticket, max_early_data_size, src, end)) != 0)
  1390. goto Exit;
  1391. src = end;
  1392. });
  1393. ptls_decode_block(src, end, 2, {
  1394. *secret = ptls_iovec_init(src, end - src);
  1395. src = end;
  1396. });
  1397. { /* determine the key-exchange */
  1398. ptls_key_exchange_algorithm_t **cand;
  1399. for (cand = tls->ctx->key_exchanges; *cand != NULL; ++cand)
  1400. if ((*cand)->id == kxid)
  1401. break;
  1402. if (*cand == NULL) {
  1403. ret = PTLS_ERROR_LIBRARY;
  1404. goto Exit;
  1405. }
  1406. *key_share = *cand;
  1407. }
  1408. { /* determine the cipher-suite */
  1409. ptls_cipher_suite_t **cand;
  1410. for (cand = tls->ctx->cipher_suites; *cand != NULL; ++cand)
  1411. if ((*cand)->id == csid)
  1412. break;
  1413. if (*cand == NULL) {
  1414. ret = PTLS_ERROR_LIBRARY;
  1415. goto Exit;
  1416. }
  1417. *cs = *cand;
  1418. }
  1419. /* calculate obfuscated_ticket_age */
  1420. now = tls->ctx->get_time->cb(tls->ctx->get_time);
  1421. if (!(obtained_at <= now && now - obtained_at < 7 * 86400 * 1000)) {
  1422. ret = PTLS_ERROR_LIBRARY;
  1423. goto Exit;
  1424. }
  1425. *obfuscated_ticket_age = (uint32_t)(now - obtained_at) + age_add;
  1426. ret = 0;
  1427. Exit:
  1428. return ret;
  1429. }
  1430. static int get_traffic_key(ptls_hash_algorithm_t *algo, void *key, size_t key_size, int is_iv, const void *secret,
  1431. ptls_iovec_t hash_value, const char *label_prefix)
  1432. {
  1433. return ptls_hkdf_expand_label(algo, key, key_size, ptls_iovec_init(secret, algo->digest_size), is_iv ? "iv" : "key", hash_value,
  1434. label_prefix);
  1435. }
  1436. static int get_traffic_keys(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, void *key, void *iv, const void *secret,
  1437. ptls_iovec_t hash_value, const char *label_prefix)
  1438. {
  1439. int ret;
  1440. if ((ret = get_traffic_key(hash, key, aead->key_size, 0, secret, hash_value, label_prefix)) != 0 ||
  1441. (ret = get_traffic_key(hash, iv, aead->iv_size, 1, secret, hash_value, label_prefix)) != 0) {
  1442. ptls_clear_memory(key, aead->key_size);
  1443. ptls_clear_memory(iv, aead->iv_size);
  1444. }
  1445. return ret;
  1446. }
  1447. static int setup_traffic_protection(ptls_t *tls, int is_enc, const char *secret_label, size_t epoch, uint64_t seq, int skip_notify)
  1448. {
  1449. static const char *log_labels[2][4] = {
  1450. {NULL, "CLIENT_EARLY_TRAFFIC_SECRET", "CLIENT_HANDSHAKE_TRAFFIC_SECRET", "CLIENT_TRAFFIC_SECRET_0"},
  1451. {NULL, NULL, "SERVER_HANDSHAKE_TRAFFIC_SECRET", "SERVER_TRAFFIC_SECRET_0"}};
  1452. struct st_ptls_traffic_protection_t *ctx = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
  1453. if (secret_label != NULL) {
  1454. int ret;
  1455. if ((ret = derive_secret(tls->key_schedule, ctx->secret, secret_label)) != 0)
  1456. return ret;
  1457. }
  1458. ctx->epoch = epoch;
  1459. log_secret(tls, log_labels[ptls_is_server(tls) == is_enc][epoch],
  1460. ptls_iovec_init(ctx->secret, tls->key_schedule->hashes[0].algo->digest_size));
  1461. /* special path for applications having their own record layer */
  1462. if (tls->ctx->update_traffic_key != NULL) {
  1463. if (skip_notify)
  1464. return 0;
  1465. return tls->ctx->update_traffic_key->cb(tls->ctx->update_traffic_key, tls, is_enc, epoch, ctx->secret);
  1466. }
  1467. if (ctx->aead != NULL)
  1468. ptls_aead_free(ctx->aead);
  1469. if ((ctx->aead = ptls_aead_new(tls->cipher_suite->aead, tls->cipher_suite->hash, is_enc, ctx->secret,
  1470. tls->ctx->hkdf_label_prefix__obsolete)) == NULL)
  1471. return PTLS_ERROR_NO_MEMORY; /* TODO obtain error from ptls_aead_new */
  1472. ctx->seq = seq;
  1473. #if defined(PTLS_DEBUG) && PTLS_DEBUG
  1474. {
  1475. uint8_t static_iv[PTLS_MAX_IV_SIZE];
  1476. ptls_aead_get_iv(ctx->aead, static_iv);
  1477. PTLS_DEBUGF("[%s] %02x%02x,%02x%02x\n", log_labels[ptls_is_server(tls)][epoch], (unsigned)ctx->secret[0],
  1478. (unsigned)ctx->secret[1], static_iv[0], static_iv[1]);
  1479. }
  1480. #endif
  1481. return 0;
  1482. }
  1483. static int commission_handshake_secret(ptls_t *tls)
  1484. {
  1485. int is_enc = !ptls_is_server(tls);
  1486. assert(tls->pending_handshake_secret != NULL);
  1487. memcpy((is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec)->secret, tls->pending_handshake_secret,
  1488. PTLS_MAX_DIGEST_SIZE);
  1489. ptls_clear_memory(tls->pending_handshake_secret, PTLS_MAX_DIGEST_SIZE);
  1490. free(tls->pending_handshake_secret);
  1491. tls->pending_handshake_secret = NULL;
  1492. return setup_traffic_protection(tls, is_enc, NULL, 2, 0, 1);
  1493. }
  1494. static void log_client_random(ptls_t *tls)
  1495. {
  1496. #if PICOTLS_USE_DTRACE
  1497. char buf[sizeof(tls->client_random) * 2 + 1];
  1498. #endif
  1499. PTLS_PROBE(CLIENT_RANDOM, tls, ptls_hexdump(buf, tls->client_random, sizeof(tls->client_random)));
  1500. PTLS_LOG_CONN(client_random, tls, { PTLS_LOG_ELEMENT_HEXDUMP(bytes, tls->client_random, sizeof(tls->client_random)); });
  1501. }
  1502. #define SESSION_IDENTIFIER_MAGIC "ptls0001" /* the number should be changed upon incompatible format change */
  1503. #define SESSION_IDENTIFIER_MAGIC_SIZE (sizeof(SESSION_IDENTIFIER_MAGIC) - 1)
  1504. static int encode_session_identifier(ptls_context_t *ctx, ptls_buffer_t *buf, uint32_t ticket_age_add, ptls_iovec_t ticket_nonce,
  1505. ptls_key_schedule_t *sched, const char *server_name, uint16_t key_exchange_id, uint16_t csid,
  1506. const char *negotiated_protocol)
  1507. {
  1508. int ret = 0;
  1509. ptls_buffer_push_block(buf, 2, {
  1510. /* format id */
  1511. ptls_buffer_pushv(buf, SESSION_IDENTIFIER_MAGIC, SESSION_IDENTIFIER_MAGIC_SIZE);
  1512. /* date */
  1513. ptls_buffer_push64(buf, ctx->get_time->cb(ctx->get_time));
  1514. /* resumption master secret */
  1515. ptls_buffer_push_block(buf, 2, {
  1516. if ((ret = ptls_buffer_reserve(buf, sched->hashes[0].algo->digest_size)) != 0)
  1517. goto Exit;
  1518. if ((ret = derive_resumption_secret(sched, buf->base + buf->off, ticket_nonce)) != 0)
  1519. goto Exit;
  1520. buf->off += sched->hashes[0].algo->digest_size;
  1521. });
  1522. /* key-exchange */
  1523. ptls_buffer_push16(buf, key_exchange_id);
  1524. /* cipher-suite */
  1525. ptls_buffer_push16(buf, csid);
  1526. /* ticket_age_add */
  1527. ptls_buffer_push32(buf, ticket_age_add);
  1528. /* session ID context */
  1529. ptls_buffer_push_block(buf, 2, {
  1530. if (ctx->ticket_context.is_set) {
  1531. ptls_buffer_pushv(buf, ctx->ticket_context.bytes, sizeof(ctx->ticket_context.bytes));
  1532. } else if (server_name != NULL) {
  1533. ptls_buffer_pushv(buf, server_name, strlen(server_name));
  1534. }
  1535. });
  1536. /* alpn */
  1537. ptls_buffer_push_block(buf, 1, {
  1538. if (negotiated_protocol != NULL)
  1539. ptls_buffer_pushv(buf, negotiated_protocol, strlen(negotiated_protocol));
  1540. });
  1541. });
  1542. Exit:
  1543. return ret;
  1544. }
  1545. int decode_session_identifier(uint64_t *issued_at, ptls_iovec_t *psk, uint32_t *ticket_age_add, ptls_iovec_t *ticket_ctx,
  1546. uint16_t *key_exchange_id, uint16_t *csid, ptls_iovec_t *negotiated_protocol, const uint8_t *src,
  1547. const uint8_t *const end)
  1548. {
  1549. int ret = 0;
  1550. ptls_decode_block(src, end, 2, {
  1551. if (end - src < SESSION_IDENTIFIER_MAGIC_SIZE ||
  1552. memcmp(src, SESSION_IDENTIFIER_MAGIC, SESSION_IDENTIFIER_MAGIC_SIZE) != 0) {
  1553. ret = PTLS_ALERT_DECODE_ERROR;
  1554. goto Exit;
  1555. }
  1556. src += SESSION_IDENTIFIER_MAGIC_SIZE;
  1557. if ((ret = ptls_decode64(issued_at, &src, end)) != 0)
  1558. goto Exit;
  1559. ptls_decode_open_block(src, end, 2, {
  1560. *psk = ptls_iovec_init(src, end - src);
  1561. src = end;
  1562. });
  1563. if ((ret = ptls_decode16(key_exchange_id, &src, end)) != 0)
  1564. goto Exit;
  1565. if ((ret = ptls_decode16(csid, &src, end)) != 0)
  1566. goto Exit;
  1567. if ((ret = ptls_decode32(ticket_age_add, &src, end)) != 0)
  1568. goto Exit;
  1569. ptls_decode_open_block(src, end, 2, {
  1570. *ticket_ctx = ptls_iovec_init(src, end - src);
  1571. src = end;
  1572. });
  1573. ptls_decode_open_block(src, end, 1, {
  1574. *negotiated_protocol = ptls_iovec_init(src, end - src);
  1575. src = end;
  1576. });
  1577. });
  1578. Exit:
  1579. return ret;
  1580. }
  1581. static size_t build_certificate_verify_signdata(uint8_t *data, ptls_key_schedule_t *sched, const char *context_string)
  1582. {
  1583. size_t datalen = 0;
  1584. memset(data + datalen, 32, 64);
  1585. datalen += 64;
  1586. memcpy(data + datalen, context_string, strlen(context_string) + 1);
  1587. datalen += strlen(context_string) + 1;
  1588. sched->hashes[0].ctx->final(sched->hashes[0].ctx, data + datalen, PTLS_HASH_FINAL_MODE_SNAPSHOT);
  1589. datalen += sched->hashes[0].algo->digest_size;
  1590. assert(datalen <= PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE);
  1591. return datalen;
  1592. }
  1593. static int calc_verify_data(void *output, ptls_key_schedule_t *sched, const void *secret)
  1594. {
  1595. ptls_hash_context_t *hmac;
  1596. uint8_t digest[PTLS_MAX_DIGEST_SIZE];
  1597. int ret;
  1598. if ((ret = ptls_hkdf_expand_label(sched->hashes[0].algo, digest, sched->hashes[0].algo->digest_size,
  1599. ptls_iovec_init(secret, sched->hashes[0].algo->digest_size), "finished",
  1600. ptls_iovec_init(NULL, 0), NULL)) != 0)
  1601. return ret;
  1602. if ((hmac = ptls_hmac_create(sched->hashes[0].algo, digest, sched->hashes[0].algo->digest_size)) == NULL) {
  1603. ptls_clear_memory(digest, sizeof(digest));
  1604. return PTLS_ERROR_NO_MEMORY;
  1605. }
  1606. sched->hashes[0].ctx->final(sched->hashes[0].ctx, digest, PTLS_HASH_FINAL_MODE_SNAPSHOT);
  1607. PTLS_DEBUGF("%s: %02x%02x,%02x%02x\n", __FUNCTION__, ((uint8_t *)secret)[0], ((uint8_t *)secret)[1], digest[0], digest[1]);
  1608. hmac->update(hmac, digest, sched->hashes[0].algo->digest_size);
  1609. ptls_clear_memory(digest, sizeof(digest));
  1610. hmac->final(hmac, output, PTLS_HASH_FINAL_MODE_FREE);
  1611. return 0;
  1612. }
  1613. static int verify_finished(ptls_t *tls, ptls_iovec_t message)
  1614. {
  1615. uint8_t verify_data[PTLS_MAX_DIGEST_SIZE];
  1616. int ret;
  1617. if (PTLS_HANDSHAKE_HEADER_SIZE + tls->key_schedule->hashes[0].algo->digest_size != message.len) {
  1618. ret = PTLS_ALERT_DECODE_ERROR;
  1619. goto Exit;
  1620. }
  1621. if ((ret = calc_verify_data(verify_data, tls->key_schedule, tls->traffic_protection.dec.secret)) != 0)
  1622. goto Exit;
  1623. if (!ptls_mem_equal(message.base + PTLS_HANDSHAKE_HEADER_SIZE, verify_data, tls->key_schedule->hashes[0].algo->digest_size)) {
  1624. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  1625. goto Exit;
  1626. }
  1627. Exit:
  1628. ptls_clear_memory(verify_data, sizeof(verify_data));
  1629. return ret;
  1630. }
  1631. static int send_finished(ptls_t *tls, ptls_message_emitter_t *emitter)
  1632. {
  1633. int ret;
  1634. ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_FINISHED, {
  1635. if ((ret = ptls_buffer_reserve(emitter->buf, tls->key_schedule->hashes[0].algo->digest_size)) != 0)
  1636. goto Exit;
  1637. if ((ret = calc_verify_data(emitter->buf->base + emitter->buf->off, tls->key_schedule,
  1638. tls->traffic_protection.enc.secret)) != 0)
  1639. goto Exit;
  1640. emitter->buf->off += tls->key_schedule->hashes[0].algo->digest_size;
  1641. });
  1642. Exit:
  1643. return ret;
  1644. }
  1645. static int send_session_ticket(ptls_t *tls, ptls_message_emitter_t *emitter)
  1646. {
  1647. ptls_hash_context_t *msghash_backup = tls->key_schedule->hashes[0].ctx->clone_(tls->key_schedule->hashes[0].ctx);
  1648. ptls_buffer_t session_id;
  1649. char session_id_smallbuf[128];
  1650. uint32_t ticket_age_add;
  1651. int ret = 0;
  1652. assert(tls->ctx->ticket_lifetime != 0);
  1653. assert(tls->ctx->encrypt_ticket != NULL);
  1654. ptls_buffer_init(&session_id, session_id_smallbuf, sizeof(session_id_smallbuf));
  1655. { /* calculate verify-data that will be sent by the client */
  1656. size_t orig_off = emitter->buf->off;
  1657. if (tls->pending_handshake_secret != NULL && !tls->ctx->omit_end_of_early_data) {
  1658. assert(tls->state == PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA);
  1659. ptls_buffer_push_message_body(emitter->buf, tls->key_schedule, PTLS_HANDSHAKE_TYPE_END_OF_EARLY_DATA, {});
  1660. emitter->buf->off = orig_off;
  1661. }
  1662. ptls_buffer_push_message_body(emitter->buf, tls->key_schedule, PTLS_HANDSHAKE_TYPE_FINISHED, {
  1663. if ((ret = ptls_buffer_reserve(emitter->buf, tls->key_schedule->hashes[0].algo->digest_size)) != 0)
  1664. goto Exit;
  1665. if ((ret = calc_verify_data(emitter->buf->base + emitter->buf->off, tls->key_schedule,
  1666. tls->pending_handshake_secret != NULL ? tls->pending_handshake_secret
  1667. : tls->traffic_protection.dec.secret)) != 0)
  1668. goto Exit;
  1669. emitter->buf->off += tls->key_schedule->hashes[0].algo->digest_size;
  1670. });
  1671. emitter->buf->off = orig_off;
  1672. }
  1673. tls->ctx->random_bytes(&ticket_age_add, sizeof(ticket_age_add));
  1674. /* build the raw nsk */
  1675. if (tls->key_share != NULL && (ret = encode_session_identifier(tls->ctx, &session_id, ticket_age_add, ptls_iovec_init(NULL, 0),
  1676. tls->key_schedule, tls->server_name, tls->key_share->id,
  1677. tls->cipher_suite->id, tls->negotiated_protocol)) != 0)
  1678. goto Exit;
  1679. /* encrypt and send */
  1680. ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET, {
  1681. ptls_buffer_push32(emitter->buf, tls->ctx->ticket_lifetime);
  1682. ptls_buffer_push32(emitter->buf, ticket_age_add);
  1683. ptls_buffer_push_block(emitter->buf, 1, {});
  1684. ptls_buffer_push_block(emitter->buf, 2, {
  1685. if ((ret = tls->ctx->encrypt_ticket->cb(tls->ctx->encrypt_ticket, tls, 1, emitter->buf,
  1686. ptls_iovec_init(session_id.base, session_id.off))) != 0)
  1687. goto Exit;
  1688. });
  1689. ptls_buffer_push_block(emitter->buf, 2, {
  1690. if (tls->ctx->max_early_data_size != 0)
  1691. buffer_push_extension(emitter->buf, PTLS_EXTENSION_TYPE_EARLY_DATA,
  1692. { ptls_buffer_push32(emitter->buf, tls->ctx->max_early_data_size); });
  1693. });
  1694. });
  1695. Exit:
  1696. ptls_buffer_dispose(&session_id);
  1697. /* restore handshake state */
  1698. tls->key_schedule->hashes[0].ctx->final(tls->key_schedule->hashes[0].ctx, NULL, PTLS_HASH_FINAL_MODE_FREE);
  1699. tls->key_schedule->hashes[0].ctx = msghash_backup;
  1700. return ret;
  1701. }
  1702. static int push_change_cipher_spec(ptls_t *tls, ptls_message_emitter_t *emitter)
  1703. {
  1704. int ret;
  1705. /* check if we are requested to (or still need to) */
  1706. if (!tls->send_change_cipher_spec) {
  1707. ret = 0;
  1708. goto Exit;
  1709. }
  1710. /* CCS is a record, can only be sent when using a record-based protocol. */
  1711. if (emitter->begin_message != begin_record_message) {
  1712. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  1713. goto Exit;
  1714. }
  1715. /* emit CCS */
  1716. buffer_push_record(emitter->buf, PTLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC, { ptls_buffer_push(emitter->buf, 1); });
  1717. tls->send_change_cipher_spec = 0;
  1718. ret = 0;
  1719. Exit:
  1720. return ret;
  1721. }
  1722. static int push_additional_extensions(ptls_handshake_properties_t *properties, ptls_buffer_t *sendbuf)
  1723. {
  1724. int ret;
  1725. if (properties != NULL && properties->additional_extensions != NULL) {
  1726. ptls_raw_extension_t *ext;
  1727. for (ext = properties->additional_extensions; ext->type != UINT16_MAX; ++ext) {
  1728. buffer_push_extension(sendbuf, ext->type, { ptls_buffer_pushv(sendbuf, ext->data.base, ext->data.len); });
  1729. }
  1730. }
  1731. ret = 0;
  1732. Exit:
  1733. return ret;
  1734. }
  1735. static int push_signature_algorithms(ptls_verify_certificate_t *vc, ptls_buffer_t *sendbuf)
  1736. {
  1737. /* The list sent when verify callback is not registered */
  1738. static const uint16_t default_algos[] = {PTLS_SIGNATURE_RSA_PSS_RSAE_SHA256, PTLS_SIGNATURE_ECDSA_SECP256R1_SHA256,
  1739. PTLS_SIGNATURE_RSA_PKCS1_SHA256, PTLS_SIGNATURE_RSA_PKCS1_SHA1, UINT16_MAX};
  1740. int ret;
  1741. ptls_buffer_push_block(sendbuf, 2, {
  1742. for (const uint16_t *p = vc != NULL ? vc->algos : default_algos; *p != UINT16_MAX; ++p)
  1743. ptls_buffer_push16(sendbuf, *p);
  1744. });
  1745. ret = 0;
  1746. Exit:
  1747. return ret;
  1748. }
  1749. static int decode_signature_algorithms(struct st_ptls_signature_algorithms_t *sa, const uint8_t **src, const uint8_t *end)
  1750. {
  1751. int ret;
  1752. ptls_decode_block(*src, end, 2, {
  1753. do {
  1754. uint16_t id;
  1755. if ((ret = ptls_decode16(&id, src, end)) != 0)
  1756. goto Exit;
  1757. if (sa->count < PTLS_ELEMENTSOF(sa->list))
  1758. sa->list[sa->count++] = id;
  1759. } while (*src != end);
  1760. });
  1761. ret = 0;
  1762. Exit:
  1763. return ret;
  1764. }
  1765. /**
  1766. * @param hash optional argument for restricting the underlying hash algorithm
  1767. */
  1768. static int select_cipher(ptls_cipher_suite_t **selected, ptls_cipher_suite_t **candidates, const uint8_t *src,
  1769. const uint8_t *const end, int server_preference, int server_chacha_priority, ptls_hash_algorithm_t *hash)
  1770. {
  1771. size_t found_index = SIZE_MAX;
  1772. int ret;
  1773. while (src != end) {
  1774. uint16_t id;
  1775. if ((ret = ptls_decode16(&id, &src, end)) != 0)
  1776. goto Exit;
  1777. for (size_t i = 0; candidates[i] != NULL; ++i) {
  1778. if (candidates[i]->id == id && (hash == NULL || candidates[i]->hash == hash)) {
  1779. if (server_preference && !(server_chacha_priority && id == PTLS_CIPHER_SUITE_CHACHA20_POLY1305_SHA256)) {
  1780. /* preserve smallest matching index, and proceed to the next input */
  1781. if (i < found_index) {
  1782. found_index = i;
  1783. break;
  1784. }
  1785. } else {
  1786. /* return the pointer matching to the first input that can be used */
  1787. *selected = candidates[i];
  1788. goto Exit;
  1789. }
  1790. }
  1791. }
  1792. /* first position of the server list matched (server_preference) */
  1793. if (found_index == 0)
  1794. break;
  1795. /* server preference is overridden only if the first entry of client-provided list is chachapoly */
  1796. server_chacha_priority = 0;
  1797. }
  1798. if (found_index != SIZE_MAX) {
  1799. *selected = candidates[found_index];
  1800. ret = 0;
  1801. } else {
  1802. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  1803. }
  1804. Exit:
  1805. return ret;
  1806. }
  1807. static int push_key_share_entry(ptls_buffer_t *buf, uint16_t group, ptls_iovec_t pubkey)
  1808. {
  1809. int ret;
  1810. ptls_buffer_push16(buf, group);
  1811. ptls_buffer_push_block(buf, 2, { ptls_buffer_pushv(buf, pubkey.base, pubkey.len); });
  1812. ret = 0;
  1813. Exit:
  1814. return ret;
  1815. }
  1816. static int decode_key_share_entry(uint16_t *group, ptls_iovec_t *key_exchange, const uint8_t **src, const uint8_t *const end)
  1817. {
  1818. int ret;
  1819. if ((ret = ptls_decode16(group, src, end)) != 0)
  1820. goto Exit;
  1821. ptls_decode_open_block(*src, end, 2, {
  1822. *key_exchange = ptls_iovec_init(*src, end - *src);
  1823. *src = end;
  1824. });
  1825. Exit:
  1826. return ret;
  1827. }
  1828. static int select_key_share(ptls_key_exchange_algorithm_t **selected, ptls_iovec_t *peer_key,
  1829. ptls_key_exchange_algorithm_t **candidates, const uint8_t **src, const uint8_t *const end,
  1830. int expect_one)
  1831. {
  1832. int ret;
  1833. *selected = NULL;
  1834. if (expect_one && *src == end) {
  1835. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  1836. goto Exit;
  1837. }
  1838. while (*src != end) {
  1839. uint16_t group;
  1840. ptls_iovec_t key;
  1841. if ((ret = decode_key_share_entry(&group, &key, src, end)) != 0)
  1842. goto Exit;
  1843. ptls_key_exchange_algorithm_t **c = candidates;
  1844. for (; *c != NULL; ++c) {
  1845. if (*selected == NULL && (*c)->id == group) {
  1846. *selected = *c;
  1847. *peer_key = key;
  1848. }
  1849. }
  1850. if (expect_one) {
  1851. ret = *selected != NULL ? 0 : PTLS_ALERT_ILLEGAL_PARAMETER;
  1852. goto Exit;
  1853. }
  1854. }
  1855. ret = 0;
  1856. Exit:
  1857. return ret;
  1858. }
  1859. static int emit_server_name_extension(ptls_buffer_t *buf, const char *server_name)
  1860. {
  1861. int ret;
  1862. ptls_buffer_push_block(buf, 2, {
  1863. ptls_buffer_push(buf, PTLS_SERVER_NAME_TYPE_HOSTNAME);
  1864. ptls_buffer_push_block(buf, 2, { ptls_buffer_pushv(buf, server_name, strlen(server_name)); });
  1865. });
  1866. ret = 0;
  1867. Exit:
  1868. return ret;
  1869. }
  1870. /**
  1871. * Within the outer ECH extension, returns the number of bytes that preceeds the AEAD-encrypted payload.
  1872. */
  1873. static inline size_t outer_ech_header_size(size_t enc_size)
  1874. {
  1875. return 10 + enc_size;
  1876. }
  1877. /**
  1878. * Flag to indicate which of ClientHelloInner, EncodedClientHelloInner, ClientHelloOuter is to be generated. When ECH is inactive,
  1879. * only ClientHelloInner is used.
  1880. */
  1881. enum encode_ch_mode { ENCODE_CH_MODE_INNER, ENCODE_CH_MODE_ENCODED_INNER, ENCODE_CH_MODE_OUTER };
  1882. static int encode_client_hello(ptls_context_t *ctx, ptls_buffer_t *sendbuf, enum encode_ch_mode mode, int is_second_flight,
  1883. ptls_handshake_properties_t *properties, const void *client_random,
  1884. ptls_key_exchange_context_t *key_share_ctx, const char *sni_name, ptls_iovec_t legacy_session_id,
  1885. struct st_ptls_ech_t *ech, size_t *ech_size_offset, ptls_iovec_t ech_replay, ptls_iovec_t psk_secret,
  1886. ptls_iovec_t psk_identity, uint32_t obfuscated_ticket_age, size_t psk_binder_size,
  1887. ptls_iovec_t *cookie, int using_early_data)
  1888. {
  1889. int ret;
  1890. assert(mode == ENCODE_CH_MODE_INNER || ech != NULL);
  1891. ptls_buffer_push_message_body(sendbuf, NULL, PTLS_HANDSHAKE_TYPE_CLIENT_HELLO, {
  1892. /* legacy_version */
  1893. ptls_buffer_push16(sendbuf, 0x0303);
  1894. /* random_bytes */
  1895. ptls_buffer_pushv(sendbuf, client_random, PTLS_HELLO_RANDOM_SIZE);
  1896. /* lecagy_session_id */
  1897. ptls_buffer_push_block(sendbuf, 1, {
  1898. if (mode != ENCODE_CH_MODE_ENCODED_INNER)
  1899. ptls_buffer_pushv(sendbuf, legacy_session_id.base, legacy_session_id.len);
  1900. });
  1901. /* cipher_suites */
  1902. ptls_buffer_push_block(sendbuf, 2, {
  1903. ptls_cipher_suite_t **cs = ctx->cipher_suites;
  1904. for (; *cs != NULL; ++cs)
  1905. ptls_buffer_push16(sendbuf, (*cs)->id);
  1906. });
  1907. /* legacy_compression_methods */
  1908. ptls_buffer_push_block(sendbuf, 1, { ptls_buffer_push(sendbuf, 0); });
  1909. /* extensions */
  1910. ptls_buffer_push_block(sendbuf, 2, {
  1911. if (mode == ENCODE_CH_MODE_OUTER) {
  1912. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO, {
  1913. size_t ext_payload_from = sendbuf->off;
  1914. ptls_buffer_push(sendbuf, PTLS_ECH_CLIENT_HELLO_TYPE_OUTER);
  1915. ptls_buffer_push16(sendbuf, ech->cipher->id.kdf);
  1916. ptls_buffer_push16(sendbuf, ech->cipher->id.aead);
  1917. ptls_buffer_push(sendbuf, ech->config_id);
  1918. ptls_buffer_push_block(sendbuf, 2, {
  1919. if (!is_second_flight)
  1920. ptls_buffer_pushv(sendbuf, ech->client.enc.base, ech->client.enc.len);
  1921. });
  1922. ptls_buffer_push_block(sendbuf, 2, {
  1923. assert(sendbuf->off - ext_payload_from ==
  1924. outer_ech_header_size(is_second_flight ? 0 : ech->client.enc.len));
  1925. if ((ret = ptls_buffer_reserve(sendbuf, *ech_size_offset)) != 0)
  1926. goto Exit;
  1927. memset(sendbuf->base + sendbuf->off, 0, *ech_size_offset);
  1928. sendbuf->off += *ech_size_offset;
  1929. *ech_size_offset = sendbuf->off - *ech_size_offset;
  1930. });
  1931. });
  1932. } else if (ech->aead != NULL) {
  1933. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO,
  1934. { ptls_buffer_push(sendbuf, PTLS_ECH_CLIENT_HELLO_TYPE_INNER); });
  1935. } else if (ech_replay.base != NULL) {
  1936. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO,
  1937. { ptls_buffer_pushv(sendbuf, ech_replay.base, ech_replay.len); });
  1938. }
  1939. if (mode == ENCODE_CH_MODE_ENCODED_INNER) {
  1940. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ECH_OUTER_EXTENSIONS, {
  1941. ptls_buffer_push_block(sendbuf, 1, { ptls_buffer_push16(sendbuf, PTLS_EXTENSION_TYPE_KEY_SHARE); });
  1942. });
  1943. } else {
  1944. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_KEY_SHARE, {
  1945. ptls_buffer_push_block(sendbuf, 2, {
  1946. if (key_share_ctx != NULL &&
  1947. (ret = push_key_share_entry(sendbuf, key_share_ctx->algo->id, key_share_ctx->pubkey)) != 0)
  1948. goto Exit;
  1949. });
  1950. });
  1951. }
  1952. if (sni_name != NULL) {
  1953. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_NAME, {
  1954. if ((ret = emit_server_name_extension(sendbuf, sni_name)) != 0)
  1955. goto Exit;
  1956. });
  1957. }
  1958. if (properties != NULL && properties->client.negotiated_protocols.count != 0) {
  1959. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ALPN, {
  1960. ptls_buffer_push_block(sendbuf, 2, {
  1961. size_t i;
  1962. for (i = 0; i != properties->client.negotiated_protocols.count; ++i) {
  1963. ptls_buffer_push_block(sendbuf, 1, {
  1964. ptls_iovec_t p = properties->client.negotiated_protocols.list[i];
  1965. ptls_buffer_pushv(sendbuf, p.base, p.len);
  1966. });
  1967. }
  1968. });
  1969. });
  1970. }
  1971. if (ctx->decompress_certificate != NULL) {
  1972. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_COMPRESS_CERTIFICATE, {
  1973. ptls_buffer_push_block(sendbuf, 1, {
  1974. const uint16_t *algo = ctx->decompress_certificate->supported_algorithms;
  1975. assert(*algo != UINT16_MAX);
  1976. for (; *algo != UINT16_MAX; ++algo)
  1977. ptls_buffer_push16(sendbuf, *algo);
  1978. });
  1979. });
  1980. }
  1981. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS, {
  1982. ptls_buffer_push_block(sendbuf, 1, {
  1983. size_t i;
  1984. for (i = 0; i != PTLS_ELEMENTSOF(supported_versions); ++i)
  1985. ptls_buffer_push16(sendbuf, supported_versions[i]);
  1986. });
  1987. });
  1988. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS, {
  1989. if ((ret = push_signature_algorithms(ctx->verify_certificate, sendbuf)) != 0)
  1990. goto Exit;
  1991. });
  1992. if (ctx->key_exchanges != NULL) {
  1993. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SUPPORTED_GROUPS, {
  1994. ptls_key_exchange_algorithm_t **algo = ctx->key_exchanges;
  1995. ptls_buffer_push_block(sendbuf, 2, {
  1996. for (; *algo != NULL; ++algo)
  1997. ptls_buffer_push16(sendbuf, (*algo)->id);
  1998. });
  1999. });
  2000. }
  2001. if (cookie != NULL && cookie->base != NULL) {
  2002. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_COOKIE, {
  2003. ptls_buffer_push_block(sendbuf, 2, { ptls_buffer_pushv(sendbuf, cookie->base, cookie->len); });
  2004. });
  2005. }
  2006. if (ctx->use_raw_public_keys) {
  2007. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE, {
  2008. ptls_buffer_push_block(sendbuf, 1, { ptls_buffer_push(sendbuf, PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY); });
  2009. });
  2010. }
  2011. if (ctx->save_ticket != NULL &&
  2012. (ctx->ticket_requests.client.new_session_count != 0 || ctx->ticket_requests.client.resumption_count != 0)) {
  2013. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_TICKET_REQUEST, {
  2014. ptls_buffer_push(sendbuf, ctx->ticket_requests.client.new_session_count,
  2015. ctx->ticket_requests.client.resumption_count);
  2016. });
  2017. }
  2018. if ((ret = push_additional_extensions(properties, sendbuf)) != 0)
  2019. goto Exit;
  2020. if (ctx->save_ticket != NULL || psk_secret.base != NULL) {
  2021. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_PSK_KEY_EXCHANGE_MODES, {
  2022. ptls_buffer_push_block(sendbuf, 1, {
  2023. if (!ctx->require_dhe_on_psk)
  2024. ptls_buffer_push(sendbuf, PTLS_PSK_KE_MODE_PSK);
  2025. ptls_buffer_push(sendbuf, PTLS_PSK_KE_MODE_PSK_DHE);
  2026. });
  2027. });
  2028. }
  2029. if (psk_secret.base != NULL) {
  2030. if (using_early_data && !is_second_flight)
  2031. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_EARLY_DATA, {});
  2032. /* pre-shared key "MUST be the last extension in the ClientHello" (draft-17 section 4.2.6) */
  2033. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_PRE_SHARED_KEY, {
  2034. ptls_buffer_push_block(sendbuf, 2, {
  2035. ptls_buffer_push_block(sendbuf, 2, {
  2036. if (mode == ENCODE_CH_MODE_OUTER) {
  2037. if ((ret = ptls_buffer_reserve(sendbuf, psk_identity.len)) != 0)
  2038. goto Exit;
  2039. ctx->random_bytes(sendbuf->base + sendbuf->off, psk_identity.len);
  2040. sendbuf->off += psk_identity.len;
  2041. } else {
  2042. ptls_buffer_pushv(sendbuf, psk_identity.base, psk_identity.len);
  2043. }
  2044. });
  2045. uint32_t age;
  2046. if (mode == ENCODE_CH_MODE_OUTER) {
  2047. ctx->random_bytes(&age, sizeof(age));
  2048. } else {
  2049. age = obfuscated_ticket_age;
  2050. }
  2051. ptls_buffer_push32(sendbuf, age);
  2052. });
  2053. /* allocate space for PSK binder. The space is filled initially filled by a random value (meeting the
  2054. * requirement of ClientHelloOuter), and later gets filled with the correct binder value if necessary. */
  2055. ptls_buffer_push_block(sendbuf, 2, {
  2056. ptls_buffer_push_block(sendbuf, 1, {
  2057. if ((ret = ptls_buffer_reserve(sendbuf, psk_binder_size)) != 0)
  2058. goto Exit;
  2059. ctx->random_bytes(sendbuf->base + sendbuf->off, psk_binder_size);
  2060. sendbuf->off += psk_binder_size;
  2061. });
  2062. });
  2063. });
  2064. }
  2065. });
  2066. });
  2067. Exit:
  2068. return ret;
  2069. }
  2070. static int send_client_hello(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_handshake_properties_t *properties,
  2071. ptls_iovec_t *cookie)
  2072. {
  2073. struct {
  2074. ptls_iovec_t secret;
  2075. ptls_iovec_t identity;
  2076. const char *label;
  2077. } psk = {{NULL}};
  2078. uint32_t obfuscated_ticket_age = 0;
  2079. const char *sni_name = NULL;
  2080. size_t mess_start, msghash_off;
  2081. uint8_t binder_key[PTLS_MAX_DIGEST_SIZE];
  2082. ptls_buffer_t encoded_ch_inner;
  2083. int ret, is_second_flight = tls->key_schedule != NULL;
  2084. ptls_buffer_init(&encoded_ch_inner, "", 0);
  2085. if (tls->server_name != NULL && !ptls_server_name_is_ipaddr(tls->server_name))
  2086. sni_name = tls->server_name;
  2087. /* try to use ECH (ignore broken ECHConfigList; it is delivered insecurely) */
  2088. if (properties != NULL) {
  2089. if (!is_second_flight && sni_name != NULL && tls->ctx->ech.client.ciphers != NULL) {
  2090. if (properties->client.ech.configs.len != 0) {
  2091. struct st_decoded_ech_config_t decoded;
  2092. client_decode_ech_config_list(tls->ctx, &decoded, properties->client.ech.configs);
  2093. if (decoded.kem != NULL && decoded.cipher != NULL) {
  2094. if ((ret = client_setup_ech(&tls->ech, &decoded, tls->ctx->random_bytes)) != 0)
  2095. goto Exit;
  2096. }
  2097. } else {
  2098. /* zero-length config indicates ECH greasing */
  2099. client_setup_ech_grease(&tls->ech, tls->ctx->random_bytes, tls->ctx->ech.client.kems, tls->ctx->ech.client.ciphers,
  2100. sni_name);
  2101. }
  2102. }
  2103. }
  2104. /* use external PSK if provided */
  2105. if (tls->ctx->pre_shared_key.identity.base != NULL) {
  2106. if (!is_second_flight) {
  2107. tls->client.offered_psk = 1;
  2108. for (size_t i = 0; tls->ctx->cipher_suites[i] != NULL; ++i) {
  2109. if (tls->ctx->cipher_suites[i]->hash == tls->ctx->pre_shared_key.hash) {
  2110. tls->cipher_suite = tls->ctx->cipher_suites[i];
  2111. break;
  2112. }
  2113. }
  2114. assert(tls->cipher_suite != NULL && "no compatible cipher-suite provided that matches psk.hash");
  2115. if (properties != NULL && properties->client.max_early_data_size != NULL) {
  2116. tls->client.using_early_data = 1;
  2117. *properties->client.max_early_data_size = SIZE_MAX;
  2118. }
  2119. } else {
  2120. assert(tls->cipher_suite != NULL && tls->cipher_suite->hash == tls->ctx->pre_shared_key.hash);
  2121. }
  2122. psk.secret = tls->ctx->pre_shared_key.secret;
  2123. psk.identity = tls->ctx->pre_shared_key.identity;
  2124. psk.label = "ext binder";
  2125. }
  2126. /* try to setup resumption-related data, unless external PSK is used */
  2127. if (psk.secret.base == NULL && properties != NULL && properties->client.session_ticket.base != NULL &&
  2128. tls->ctx->key_exchanges != NULL) {
  2129. ptls_key_exchange_algorithm_t *key_share = NULL;
  2130. ptls_cipher_suite_t *cipher_suite = NULL;
  2131. uint32_t max_early_data_size;
  2132. if (decode_stored_session_ticket(tls, &key_share, &cipher_suite, &psk.secret, &obfuscated_ticket_age, &psk.identity,
  2133. &max_early_data_size, properties->client.session_ticket.base,
  2134. properties->client.session_ticket.base + properties->client.session_ticket.len) == 0) {
  2135. psk.label = "res binder";
  2136. tls->client.offered_psk = 1;
  2137. /* key-share selected by HRR should not be overridden */
  2138. if (tls->key_share == NULL)
  2139. tls->key_share = key_share;
  2140. tls->cipher_suite = cipher_suite;
  2141. if (!is_second_flight && max_early_data_size != 0 && properties->client.max_early_data_size != NULL) {
  2142. tls->client.using_early_data = 1;
  2143. *properties->client.max_early_data_size = max_early_data_size;
  2144. }
  2145. } else {
  2146. psk.secret = ptls_iovec_init(NULL, 0);
  2147. }
  2148. }
  2149. /* send 0-RTT related signals back to the client */
  2150. if (properties != NULL) {
  2151. if (tls->client.using_early_data) {
  2152. properties->client.early_data_acceptance = PTLS_EARLY_DATA_ACCEPTANCE_UNKNOWN;
  2153. } else {
  2154. if (properties->client.max_early_data_size != NULL)
  2155. *properties->client.max_early_data_size = 0;
  2156. properties->client.early_data_acceptance = PTLS_EARLY_DATA_REJECTED;
  2157. }
  2158. }
  2159. /* use the default key share if still not undetermined */
  2160. if (tls->key_share == NULL && tls->ctx->key_exchanges != NULL &&
  2161. !(properties != NULL && properties->client.negotiate_before_key_exchange))
  2162. tls->key_share = tls->ctx->key_exchanges[0];
  2163. /* instantiate key share context */
  2164. assert(tls->client.key_share_ctx == NULL);
  2165. if (tls->key_share != NULL) {
  2166. if ((ret = tls->key_share->create(tls->key_share, &tls->client.key_share_ctx)) != 0)
  2167. goto Exit;
  2168. }
  2169. /* initialize key schedule */
  2170. if (!is_second_flight) {
  2171. if ((tls->key_schedule = key_schedule_new(tls->cipher_suite, tls->ctx->cipher_suites, tls->ech.aead != NULL)) == NULL) {
  2172. ret = PTLS_ERROR_NO_MEMORY;
  2173. goto Exit;
  2174. }
  2175. if ((ret = key_schedule_extract(tls->key_schedule, psk.secret)) != 0)
  2176. goto Exit;
  2177. }
  2178. /* start generating CH */
  2179. if ((ret = emitter->begin_message(emitter)) != 0)
  2180. goto Exit;
  2181. mess_start = msghash_off = emitter->buf->off;
  2182. /* generate true (inner) CH */
  2183. if ((ret = encode_client_hello(tls->ctx, emitter->buf, ENCODE_CH_MODE_INNER, is_second_flight, properties,
  2184. tls->ech.aead != NULL ? tls->ech.inner_client_random : tls->client_random,
  2185. tls->client.key_share_ctx, sni_name, tls->client.legacy_session_id, &tls->ech, NULL,
  2186. tls->ech.client.first_ech, psk.secret, psk.identity, obfuscated_ticket_age,
  2187. tls->key_schedule->hashes[0].algo->digest_size, cookie, tls->client.using_early_data)) != 0)
  2188. goto Exit;
  2189. /* update the message hash, filling in the PSK binder HMAC if necessary */
  2190. if (psk.secret.base != NULL) {
  2191. size_t psk_binder_off = emitter->buf->off - (3 + tls->key_schedule->hashes[0].algo->digest_size);
  2192. if ((ret = derive_secret_with_empty_digest(tls->key_schedule, binder_key, psk.label)) != 0)
  2193. goto Exit;
  2194. ptls__key_schedule_update_hash(tls->key_schedule, emitter->buf->base + msghash_off, psk_binder_off - msghash_off, 0);
  2195. msghash_off = psk_binder_off;
  2196. if ((ret = calc_verify_data(emitter->buf->base + psk_binder_off + 3, tls->key_schedule, binder_key)) != 0)
  2197. goto Exit;
  2198. }
  2199. ptls__key_schedule_update_hash(tls->key_schedule, emitter->buf->base + msghash_off, emitter->buf->off - msghash_off, 0);
  2200. /* ECH */
  2201. if (tls->ech.aead != NULL) {
  2202. /* build EncodedCHInner */
  2203. if ((ret = encode_client_hello(tls->ctx, &encoded_ch_inner, ENCODE_CH_MODE_ENCODED_INNER, is_second_flight, properties,
  2204. tls->ech.inner_client_random, tls->client.key_share_ctx, sni_name,
  2205. tls->client.legacy_session_id, &tls->ech, NULL, ptls_iovec_init(NULL, 0), psk.secret,
  2206. psk.identity, obfuscated_ticket_age, tls->key_schedule->hashes[0].algo->digest_size, cookie,
  2207. tls->client.using_early_data)) != 0)
  2208. goto Exit;
  2209. if (psk.secret.base != NULL)
  2210. memcpy(encoded_ch_inner.base + encoded_ch_inner.off - tls->key_schedule->hashes[0].algo->digest_size,
  2211. emitter->buf->base + emitter->buf->off - tls->key_schedule->hashes[0].algo->digest_size,
  2212. tls->key_schedule->hashes[0].algo->digest_size);
  2213. { /* pad EncodedCHInner (following draft-ietf-tls-esni-15 6.1.3) */
  2214. size_t padding_len;
  2215. if (sni_name != NULL) {
  2216. padding_len = strlen(sni_name);
  2217. if (padding_len < tls->ech.client.max_name_length)
  2218. padding_len = tls->ech.client.max_name_length;
  2219. } else {
  2220. padding_len = tls->ech.client.max_name_length + 9;
  2221. }
  2222. size_t final_len = encoded_ch_inner.off - PTLS_HANDSHAKE_HEADER_SIZE + padding_len;
  2223. final_len = (final_len + 31) / 32 * 32;
  2224. padding_len = final_len - (encoded_ch_inner.off - PTLS_HANDSHAKE_HEADER_SIZE);
  2225. if (padding_len != 0) {
  2226. if ((ret = ptls_buffer_reserve(&encoded_ch_inner, padding_len)) != 0)
  2227. goto Exit;
  2228. memset(encoded_ch_inner.base + encoded_ch_inner.off, 0, padding_len);
  2229. encoded_ch_inner.off += padding_len;
  2230. }
  2231. }
  2232. /* flush CHInner, build CHOuterAAD */
  2233. emitter->buf->off = mess_start;
  2234. size_t ech_payload_size = encoded_ch_inner.off - PTLS_HANDSHAKE_HEADER_SIZE + tls->ech.aead->algo->tag_size,
  2235. ech_size_offset = ech_payload_size;
  2236. if ((ret = encode_client_hello(tls->ctx, emitter->buf, ENCODE_CH_MODE_OUTER, is_second_flight, properties,
  2237. tls->client_random, tls->client.key_share_ctx, tls->ech.client.public_name,
  2238. tls->client.legacy_session_id, &tls->ech, &ech_size_offset, ptls_iovec_init(NULL, 0),
  2239. psk.secret, psk.identity, obfuscated_ticket_age,
  2240. tls->key_schedule->hashes[0].algo->digest_size, cookie, tls->client.using_early_data)) != 0)
  2241. goto Exit;
  2242. /* overwrite ECH payload */
  2243. ptls_aead_encrypt(tls->ech.aead, emitter->buf->base + ech_size_offset, encoded_ch_inner.base + PTLS_HANDSHAKE_HEADER_SIZE,
  2244. encoded_ch_inner.off - PTLS_HANDSHAKE_HEADER_SIZE, is_second_flight,
  2245. emitter->buf->base + mess_start + PTLS_HANDSHAKE_HEADER_SIZE,
  2246. emitter->buf->off - (mess_start + PTLS_HANDSHAKE_HEADER_SIZE));
  2247. /* keep the copy of the 1st ECH extension so that we can send it again in 2nd CH in response to rejection with HRR */
  2248. if (!is_second_flight) {
  2249. size_t len = outer_ech_header_size(tls->ech.client.enc.len) + ech_payload_size;
  2250. if ((tls->ech.client.first_ech.base = malloc(len)) == NULL) {
  2251. ret = PTLS_ERROR_NO_MEMORY;
  2252. goto Exit;
  2253. }
  2254. memcpy(tls->ech.client.first_ech.base,
  2255. emitter->buf->base + ech_size_offset - outer_ech_header_size(tls->ech.client.enc.len), len);
  2256. tls->ech.client.first_ech.len = len;
  2257. if (properties->client.ech.configs.len != 0) {
  2258. tls->ech.offered = 1;
  2259. } else {
  2260. tls->ech.offered_grease = 1;
  2261. }
  2262. }
  2263. /* update hash */
  2264. ptls__key_schedule_update_hash(tls->key_schedule, emitter->buf->base + mess_start, emitter->buf->off - mess_start, 1);
  2265. }
  2266. /* commit CH to the record layer */
  2267. if ((ret = emitter->commit_message(emitter)) != 0)
  2268. goto Exit;
  2269. if (tls->client.using_early_data) {
  2270. assert(!is_second_flight);
  2271. if ((ret = setup_traffic_protection(tls, 1, "c e traffic", 1, 0, 0)) != 0)
  2272. goto Exit;
  2273. if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
  2274. goto Exit;
  2275. }
  2276. if (psk.secret.base != NULL && !is_second_flight) {
  2277. if ((ret = derive_exporter_secret(tls, 1)) != 0)
  2278. goto Exit;
  2279. }
  2280. tls->state = cookie == NULL ? PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO : PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO;
  2281. ret = PTLS_ERROR_IN_PROGRESS;
  2282. Exit:
  2283. ptls_buffer_dispose(&encoded_ch_inner);
  2284. ptls_clear_memory(binder_key, sizeof(binder_key));
  2285. return ret;
  2286. }
  2287. ptls_cipher_suite_t *ptls_find_cipher_suite(ptls_cipher_suite_t **cipher_suites, uint16_t id)
  2288. {
  2289. ptls_cipher_suite_t **cs;
  2290. if (cipher_suites == NULL)
  2291. return NULL;
  2292. for (cs = cipher_suites; *cs != NULL && (*cs)->id != id; ++cs)
  2293. ;
  2294. return *cs;
  2295. }
  2296. static int decode_server_hello(ptls_t *tls, struct st_ptls_server_hello_t *sh, const uint8_t *src, const uint8_t *const end)
  2297. {
  2298. int ret;
  2299. *sh = (struct st_ptls_server_hello_t){{0}};
  2300. /* ignore legacy-version */
  2301. if (end - src < 2) {
  2302. ret = PTLS_ALERT_DECODE_ERROR;
  2303. goto Exit;
  2304. }
  2305. src += 2;
  2306. /* random */
  2307. if (end - src < PTLS_HELLO_RANDOM_SIZE) {
  2308. ret = PTLS_ALERT_DECODE_ERROR;
  2309. goto Exit;
  2310. }
  2311. sh->is_retry_request = memcmp(src, hello_retry_random, PTLS_HELLO_RANDOM_SIZE) == 0;
  2312. src += PTLS_HELLO_RANDOM_SIZE;
  2313. /* legacy_session_id */
  2314. ptls_decode_open_block(src, end, 1, {
  2315. if (end - src > 32) {
  2316. ret = PTLS_ALERT_DECODE_ERROR;
  2317. goto Exit;
  2318. }
  2319. sh->legacy_session_id = ptls_iovec_init(src, end - src);
  2320. src = end;
  2321. });
  2322. { /* select cipher_suite */
  2323. uint16_t csid;
  2324. if ((ret = ptls_decode16(&csid, &src, end)) != 0)
  2325. goto Exit;
  2326. if ((tls->cipher_suite = ptls_find_cipher_suite(tls->ctx->cipher_suites, csid)) == NULL) {
  2327. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2328. goto Exit;
  2329. }
  2330. }
  2331. { /* legacy_compression_method */
  2332. uint8_t method;
  2333. if ((ret = ptls_decode8(&method, &src, end)) != 0)
  2334. goto Exit;
  2335. if (method != 0) {
  2336. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2337. goto Exit;
  2338. }
  2339. }
  2340. if (sh->is_retry_request)
  2341. sh->retry_request.selected_group = UINT16_MAX;
  2342. uint16_t exttype, found_version = UINT16_MAX, selected_psk_identity = UINT16_MAX;
  2343. decode_extensions(src, end, sh->is_retry_request ? PTLS_HANDSHAKE_TYPE_PSEUDO_HRR : PTLS_HANDSHAKE_TYPE_SERVER_HELLO, &exttype,
  2344. {
  2345. if (tls->ctx->on_extension != NULL &&
  2346. (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_SERVER_HELLO,
  2347. exttype, ptls_iovec_init(src, end - src)) != 0))
  2348. goto Exit;
  2349. switch (exttype) {
  2350. case PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS:
  2351. if ((ret = ptls_decode16(&found_version, &src, end)) != 0)
  2352. goto Exit;
  2353. break;
  2354. case PTLS_EXTENSION_TYPE_KEY_SHARE:
  2355. if (tls->ctx->key_exchanges == NULL) {
  2356. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  2357. goto Exit;
  2358. }
  2359. if (sh->is_retry_request) {
  2360. if ((ret = ptls_decode16(&sh->retry_request.selected_group, &src, end)) != 0)
  2361. goto Exit;
  2362. } else {
  2363. uint16_t group;
  2364. if ((ret = decode_key_share_entry(&group, &sh->peerkey, &src, end)) != 0)
  2365. goto Exit;
  2366. if (src != end) {
  2367. ret = PTLS_ALERT_DECODE_ERROR;
  2368. goto Exit;
  2369. }
  2370. if (tls->key_share == NULL || tls->key_share->id != group) {
  2371. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2372. goto Exit;
  2373. }
  2374. }
  2375. break;
  2376. case PTLS_EXTENSION_TYPE_COOKIE:
  2377. assert(sh->is_retry_request);
  2378. ptls_decode_block(src, end, 2, {
  2379. if (src == end) {
  2380. ret = PTLS_ALERT_DECODE_ERROR;
  2381. goto Exit;
  2382. }
  2383. sh->retry_request.cookie = ptls_iovec_init(src, end - src);
  2384. src = end;
  2385. });
  2386. break;
  2387. case PTLS_EXTENSION_TYPE_PRE_SHARED_KEY:
  2388. assert(!sh->is_retry_request);
  2389. if ((ret = ptls_decode16(&selected_psk_identity, &src, end)) != 0)
  2390. goto Exit;
  2391. break;
  2392. case PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO:
  2393. assert(sh->is_retry_request);
  2394. if (!(tls->ech.offered || tls->ech.offered_grease)) {
  2395. ret = PTLS_ALERT_UNSUPPORTED_EXTENSION;
  2396. goto Exit;
  2397. }
  2398. if (end - src != PTLS_ECH_CONFIRM_LENGTH) {
  2399. ret = PTLS_ALERT_DECODE_ERROR;
  2400. goto Exit;
  2401. }
  2402. sh->retry_request.ech = src;
  2403. src = end;
  2404. break;
  2405. default:
  2406. src = end;
  2407. break;
  2408. }
  2409. });
  2410. if (!is_supported_version(found_version)) {
  2411. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2412. goto Exit;
  2413. }
  2414. if (!sh->is_retry_request) {
  2415. if (selected_psk_identity != UINT16_MAX) {
  2416. if (!tls->client.offered_psk) {
  2417. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2418. goto Exit;
  2419. }
  2420. if (selected_psk_identity != 0) {
  2421. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2422. goto Exit;
  2423. }
  2424. tls->is_psk_handshake = 1;
  2425. }
  2426. if (sh->peerkey.base == NULL && !tls->is_psk_handshake) {
  2427. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2428. goto Exit;
  2429. }
  2430. }
  2431. ret = 0;
  2432. Exit:
  2433. return ret;
  2434. }
  2435. static int handle_hello_retry_request(ptls_t *tls, ptls_message_emitter_t *emitter, struct st_ptls_server_hello_t *sh,
  2436. ptls_iovec_t message, ptls_handshake_properties_t *properties)
  2437. {
  2438. int ret;
  2439. if (tls->client.key_share_ctx != NULL) {
  2440. tls->client.key_share_ctx->on_exchange(&tls->client.key_share_ctx, 1, NULL, ptls_iovec_init(NULL, 0));
  2441. tls->client.key_share_ctx = NULL;
  2442. }
  2443. if (tls->client.using_early_data) {
  2444. /* release traffic encryption key so that 2nd CH goes out in cleartext, but keep the epoch at 1 since we've already
  2445. * called derive-secret */
  2446. if (tls->ctx->update_traffic_key == NULL) {
  2447. assert(tls->traffic_protection.enc.aead != NULL);
  2448. ptls_aead_free(tls->traffic_protection.enc.aead);
  2449. tls->traffic_protection.enc.aead = NULL;
  2450. }
  2451. tls->client.using_early_data = 0;
  2452. }
  2453. if (sh->retry_request.selected_group != UINT16_MAX) {
  2454. /* we offer the first key_exchanges[0] as KEY_SHARE unless client.negotiate_before_key_exchange is set */
  2455. ptls_key_exchange_algorithm_t **cand;
  2456. for (cand = tls->ctx->key_exchanges; *cand != NULL; ++cand)
  2457. if ((*cand)->id == sh->retry_request.selected_group)
  2458. break;
  2459. if (*cand == NULL) {
  2460. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2461. goto Exit;
  2462. }
  2463. tls->key_share = *cand;
  2464. } else if (tls->key_share != NULL) {
  2465. /* retain the key-share using in first CH, if server does not specify one */
  2466. } else {
  2467. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2468. goto Exit;
  2469. }
  2470. ret = send_client_hello(tls, emitter, properties, &sh->retry_request.cookie);
  2471. Exit:
  2472. return ret;
  2473. }
  2474. static int client_ech_select_hello(ptls_t *tls, ptls_iovec_t message, size_t confirm_hash_off, const char *label)
  2475. {
  2476. uint8_t confirm_hash_delivered[PTLS_ECH_CONFIRM_LENGTH], confirm_hash_expected[PTLS_ECH_CONFIRM_LENGTH];
  2477. int ret = 0;
  2478. /* Determine if ECH has been accepted by checking the confirmation hash. `confirm_hash_off` set to zero indicates that HRR was
  2479. * received wo. ECH extension, which is an indication that ECH was rejected. */
  2480. if (confirm_hash_off != 0) {
  2481. memcpy(confirm_hash_delivered, message.base + confirm_hash_off, sizeof(confirm_hash_delivered));
  2482. memset(message.base + confirm_hash_off, 0, sizeof(confirm_hash_delivered));
  2483. if ((ret = ech_calc_confirmation(tls->key_schedule, confirm_hash_expected, tls->ech.inner_client_random, label, message)) !=
  2484. 0)
  2485. goto Exit;
  2486. tls->ech.accepted = ptls_mem_equal(confirm_hash_delivered, confirm_hash_expected, sizeof(confirm_hash_delivered));
  2487. memcpy(message.base + confirm_hash_off, confirm_hash_delivered, sizeof(confirm_hash_delivered));
  2488. if (tls->ech.accepted)
  2489. goto Exit;
  2490. }
  2491. /* dispose ECH AEAD state to indicate rejection, adopting outer CH for the rest of the handshake */
  2492. ptls_aead_free(tls->ech.aead);
  2493. tls->ech.aead = NULL;
  2494. key_schedule_select_outer(tls->key_schedule);
  2495. Exit:
  2496. PTLS_PROBE(ECH_SELECTION, tls, !!tls->ech.accepted);
  2497. PTLS_LOG_CONN(ech_selection, tls, { PTLS_LOG_ELEMENT_BOOL(is_ech, tls->ech.accepted); });
  2498. ptls_clear_memory(confirm_hash_expected, sizeof(confirm_hash_expected));
  2499. return ret;
  2500. }
  2501. static int client_handle_hello(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message,
  2502. ptls_handshake_properties_t *properties)
  2503. {
  2504. struct st_ptls_server_hello_t sh;
  2505. ptls_iovec_t ecdh_secret = {NULL};
  2506. int ret;
  2507. if ((ret = decode_server_hello(tls, &sh, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.base + message.len)) != 0)
  2508. goto Exit;
  2509. if (!(sh.legacy_session_id.len == tls->client.legacy_session_id.len &&
  2510. ptls_mem_equal(sh.legacy_session_id.base, tls->client.legacy_session_id.base, tls->client.legacy_session_id.len))) {
  2511. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2512. goto Exit;
  2513. }
  2514. if (sh.is_retry_request) {
  2515. if ((ret = key_schedule_select_cipher(tls->key_schedule, tls->cipher_suite, 0, tls->ctx->pre_shared_key.secret)) != 0)
  2516. goto Exit;
  2517. key_schedule_transform_post_ch1hash(tls->key_schedule);
  2518. if (tls->ech.aead != NULL) {
  2519. size_t confirm_hash_off = 0;
  2520. if (tls->ech.offered) {
  2521. if (sh.retry_request.ech != NULL)
  2522. confirm_hash_off = sh.retry_request.ech - message.base;
  2523. } else {
  2524. assert(tls->ech.offered_grease);
  2525. }
  2526. if ((ret = client_ech_select_hello(tls, message, confirm_hash_off, ECH_CONFIRMATION_HRR)) != 0)
  2527. goto Exit;
  2528. }
  2529. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  2530. return handle_hello_retry_request(tls, emitter, &sh, message, properties);
  2531. }
  2532. if ((ret = key_schedule_select_cipher(tls->key_schedule, tls->cipher_suite, tls->client.offered_psk && !tls->is_psk_handshake,
  2533. ptls_iovec_init(NULL, 0))) != 0)
  2534. goto Exit;
  2535. /* check if ECH is accepted */
  2536. if (tls->ech.aead != NULL) {
  2537. size_t confirm_hash_off = 0;
  2538. if (tls->ech.offered) {
  2539. confirm_hash_off =
  2540. PTLS_HANDSHAKE_HEADER_SIZE + 2 /* legacy_version */ + PTLS_HELLO_RANDOM_SIZE - PTLS_ECH_CONFIRM_LENGTH;
  2541. } else {
  2542. assert(tls->ech.offered_grease);
  2543. }
  2544. if ((ret = client_ech_select_hello(tls, message, confirm_hash_off, ECH_CONFIRMATION_SERVER_HELLO)) != 0)
  2545. goto Exit;
  2546. }
  2547. /* clear sensitive and space-consuming ECH state, now that are done with handling sending and decoding Hellos */
  2548. clear_ech(&tls->ech, 0);
  2549. if (tls->key_schedule->hashes[0].ctx_outer != NULL) {
  2550. tls->key_schedule->hashes[0].ctx_outer->final(tls->key_schedule->hashes[0].ctx_outer, NULL, PTLS_HASH_FINAL_MODE_FREE);
  2551. tls->key_schedule->hashes[0].ctx_outer = NULL;
  2552. }
  2553. /* if the client offered external PSK but the server did not use that, we call it a handshake failure */
  2554. if (tls->ctx->pre_shared_key.identity.base != NULL && !tls->is_psk_handshake) {
  2555. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  2556. goto Exit;
  2557. }
  2558. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  2559. if (sh.peerkey.base != NULL) {
  2560. if ((ret = tls->client.key_share_ctx->on_exchange(&tls->client.key_share_ctx, 1, &ecdh_secret, sh.peerkey)) != 0) {
  2561. assert(ecdh_secret.base == NULL);
  2562. goto Exit;
  2563. }
  2564. }
  2565. if ((ret = key_schedule_extract(tls->key_schedule, ecdh_secret)) != 0)
  2566. goto Exit;
  2567. if ((ret = setup_traffic_protection(tls, 0, "s hs traffic", 2, 0, 0)) != 0)
  2568. goto Exit;
  2569. if (tls->client.using_early_data) {
  2570. if ((tls->pending_handshake_secret = malloc(PTLS_MAX_DIGEST_SIZE)) == NULL) {
  2571. ret = PTLS_ERROR_NO_MEMORY;
  2572. goto Exit;
  2573. }
  2574. if ((ret = derive_secret(tls->key_schedule, tls->pending_handshake_secret, "c hs traffic")) != 0)
  2575. goto Exit;
  2576. if (tls->ctx->update_traffic_key != NULL &&
  2577. (ret = tls->ctx->update_traffic_key->cb(tls->ctx->update_traffic_key, tls, 1, 2, tls->pending_handshake_secret)) != 0)
  2578. goto Exit;
  2579. } else {
  2580. if ((ret = setup_traffic_protection(tls, 1, "c hs traffic", 2, 0, 0)) != 0)
  2581. goto Exit;
  2582. }
  2583. tls->state = PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS;
  2584. ret = PTLS_ERROR_IN_PROGRESS;
  2585. Exit:
  2586. if (ecdh_secret.base != NULL) {
  2587. ptls_clear_memory(ecdh_secret.base, ecdh_secret.len);
  2588. free(ecdh_secret.base);
  2589. }
  2590. return ret;
  2591. }
  2592. static int should_collect_unknown_extension(ptls_t *tls, ptls_handshake_properties_t *properties, uint16_t type)
  2593. {
  2594. return properties != NULL && properties->collect_extension != NULL && properties->collect_extension(tls, properties, type);
  2595. }
  2596. static int collect_unknown_extension(ptls_t *tls, uint16_t type, const uint8_t *src, const uint8_t *const end,
  2597. ptls_raw_extension_t *slots)
  2598. {
  2599. size_t i;
  2600. for (i = 0; slots[i].type != UINT16_MAX; ++i) {
  2601. assert(i < MAX_UNKNOWN_EXTENSIONS);
  2602. if (slots[i].type == type)
  2603. return PTLS_ALERT_ILLEGAL_PARAMETER;
  2604. }
  2605. if (i < MAX_UNKNOWN_EXTENSIONS) {
  2606. slots[i].type = type;
  2607. slots[i].data = ptls_iovec_init(src, end - src);
  2608. slots[i + 1].type = UINT16_MAX;
  2609. }
  2610. return 0;
  2611. }
  2612. static int report_unknown_extensions(ptls_t *tls, ptls_handshake_properties_t *properties, ptls_raw_extension_t *slots)
  2613. {
  2614. if (properties != NULL && properties->collect_extension != NULL) {
  2615. assert(properties->collected_extensions != NULL);
  2616. return properties->collected_extensions(tls, properties, slots);
  2617. } else {
  2618. return 0;
  2619. }
  2620. }
  2621. static int client_handle_encrypted_extensions(ptls_t *tls, ptls_iovec_t message, ptls_handshake_properties_t *properties)
  2622. {
  2623. const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
  2624. uint16_t type;
  2625. static const ptls_raw_extension_t no_unknown_extensions = {UINT16_MAX};
  2626. ptls_raw_extension_t *unknown_extensions = (ptls_raw_extension_t *)&no_unknown_extensions;
  2627. int ret, skip_early_data = 1;
  2628. uint8_t server_offered_cert_type = PTLS_CERTIFICATE_TYPE_X509;
  2629. decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS, &type, {
  2630. if (tls->ctx->on_extension != NULL &&
  2631. (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS, type,
  2632. ptls_iovec_init(src, end - src)) != 0))
  2633. goto Exit;
  2634. switch (type) {
  2635. case PTLS_EXTENSION_TYPE_SERVER_NAME:
  2636. if (src != end) {
  2637. ret = PTLS_ALERT_DECODE_ERROR;
  2638. goto Exit;
  2639. }
  2640. if (!(tls->server_name != NULL && !ptls_server_name_is_ipaddr(tls->server_name))) {
  2641. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2642. goto Exit;
  2643. }
  2644. break;
  2645. case PTLS_EXTENSION_TYPE_ALPN:
  2646. ptls_decode_block(src, end, 2, {
  2647. ptls_decode_open_block(src, end, 1, {
  2648. if (src == end) {
  2649. ret = PTLS_ALERT_DECODE_ERROR;
  2650. goto Exit;
  2651. }
  2652. if ((ret = ptls_set_negotiated_protocol(tls, (const char *)src, end - src)) != 0)
  2653. goto Exit;
  2654. src = end;
  2655. });
  2656. if (src != end) {
  2657. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  2658. goto Exit;
  2659. }
  2660. });
  2661. break;
  2662. case PTLS_EXTENSION_TYPE_EARLY_DATA:
  2663. if (!tls->client.using_early_data) {
  2664. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2665. goto Exit;
  2666. }
  2667. skip_early_data = 0;
  2668. break;
  2669. case PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE:
  2670. if (end - src != 1) {
  2671. ret = PTLS_ALERT_DECODE_ERROR;
  2672. goto Exit;
  2673. }
  2674. server_offered_cert_type = *src;
  2675. src = end;
  2676. break;
  2677. case PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO: {
  2678. /* accept retry_configs only if we offered ECH but rejected */
  2679. if (!((tls->ech.offered || tls->ech.offered_grease) && !ptls_is_ech_handshake(tls, NULL, NULL, NULL))) {
  2680. ret = PTLS_ALERT_UNSUPPORTED_EXTENSION;
  2681. goto Exit;
  2682. }
  2683. /* parse retry_config, and if it is applicable, provide that to the application */
  2684. struct st_decoded_ech_config_t decoded;
  2685. if ((ret = client_decode_ech_config_list(tls->ctx, &decoded, ptls_iovec_init(src, end - src))) != 0)
  2686. goto Exit;
  2687. if (decoded.kem != NULL && decoded.cipher != NULL && properties != NULL &&
  2688. properties->client.ech.retry_configs != NULL) {
  2689. if ((properties->client.ech.retry_configs->base = malloc(end - src)) == NULL) {
  2690. ret = PTLS_ERROR_NO_MEMORY;
  2691. goto Exit;
  2692. }
  2693. memcpy(properties->client.ech.retry_configs->base, src, end - src);
  2694. properties->client.ech.retry_configs->len = end - src;
  2695. }
  2696. src = end;
  2697. } break;
  2698. default:
  2699. if (should_collect_unknown_extension(tls, properties, type)) {
  2700. if (unknown_extensions == &no_unknown_extensions) {
  2701. if ((unknown_extensions = malloc(sizeof(*unknown_extensions) * (MAX_UNKNOWN_EXTENSIONS + 1))) == NULL) {
  2702. ret = PTLS_ERROR_NO_MEMORY;
  2703. goto Exit;
  2704. }
  2705. unknown_extensions[0].type = UINT16_MAX;
  2706. }
  2707. if ((ret = collect_unknown_extension(tls, type, src, end, unknown_extensions)) != 0)
  2708. goto Exit;
  2709. }
  2710. break;
  2711. }
  2712. src = end;
  2713. });
  2714. if (server_offered_cert_type !=
  2715. (tls->ctx->use_raw_public_keys ? PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY : PTLS_CERTIFICATE_TYPE_X509)) {
  2716. ret = PTLS_ALERT_UNSUPPORTED_CERTIFICATE;
  2717. goto Exit;
  2718. }
  2719. if (tls->client.using_early_data) {
  2720. if (skip_early_data)
  2721. tls->client.using_early_data = 0;
  2722. if (properties != NULL)
  2723. properties->client.early_data_acceptance = skip_early_data ? PTLS_EARLY_DATA_REJECTED : PTLS_EARLY_DATA_ACCEPTED;
  2724. }
  2725. if ((ret = report_unknown_extensions(tls, properties, unknown_extensions)) != 0)
  2726. goto Exit;
  2727. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  2728. tls->state =
  2729. tls->is_psk_handshake ? PTLS_STATE_CLIENT_EXPECT_FINISHED : PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE;
  2730. ret = PTLS_ERROR_IN_PROGRESS;
  2731. Exit:
  2732. if (unknown_extensions != &no_unknown_extensions)
  2733. free(unknown_extensions);
  2734. return ret;
  2735. }
  2736. static int decode_certificate_request(ptls_t *tls, struct st_ptls_certificate_request_t *cr, const uint8_t *src,
  2737. const uint8_t *const end)
  2738. {
  2739. int ret;
  2740. uint16_t exttype = 0;
  2741. /* certificate request context */
  2742. ptls_decode_open_block(src, end, 1, {
  2743. size_t len = end - src;
  2744. if (len > 255) {
  2745. ret = PTLS_ALERT_DECODE_ERROR;
  2746. goto Exit;
  2747. }
  2748. if ((cr->context.base = malloc(len != 0 ? len : 1)) == NULL) {
  2749. ret = PTLS_ERROR_NO_MEMORY;
  2750. goto Exit;
  2751. }
  2752. cr->context.len = len;
  2753. memcpy(cr->context.base, src, len);
  2754. src = end;
  2755. });
  2756. /* decode extensions */
  2757. decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST, &exttype, {
  2758. if (tls->ctx->on_extension != NULL &&
  2759. (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST, exttype,
  2760. ptls_iovec_init(src, end - src)) != 0))
  2761. goto Exit;
  2762. switch (exttype) {
  2763. case PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS:
  2764. if ((ret = decode_signature_algorithms(&cr->signature_algorithms, &src, end)) != 0)
  2765. goto Exit;
  2766. break;
  2767. }
  2768. src = end;
  2769. });
  2770. if (cr->signature_algorithms.count == 0) {
  2771. ret = PTLS_ALERT_MISSING_EXTENSION;
  2772. goto Exit;
  2773. }
  2774. ret = 0;
  2775. Exit:
  2776. return ret;
  2777. }
  2778. int ptls_build_certificate_message(ptls_buffer_t *buf, ptls_iovec_t context, ptls_iovec_t *certificates, size_t num_certificates,
  2779. ptls_iovec_t ocsp_status)
  2780. {
  2781. int ret;
  2782. ptls_buffer_push_block(buf, 1, { ptls_buffer_pushv(buf, context.base, context.len); });
  2783. ptls_buffer_push_block(buf, 3, {
  2784. size_t i;
  2785. for (i = 0; i != num_certificates; ++i) {
  2786. ptls_buffer_push_block(buf, 3, { ptls_buffer_pushv(buf, certificates[i].base, certificates[i].len); });
  2787. ptls_buffer_push_block(buf, 2, {
  2788. if (i == 0 && ocsp_status.len != 0) {
  2789. buffer_push_extension(buf, PTLS_EXTENSION_TYPE_STATUS_REQUEST, {
  2790. ptls_buffer_push(buf, 1); /* status_type == ocsp */
  2791. ptls_buffer_push_block(buf, 3, { ptls_buffer_pushv(buf, ocsp_status.base, ocsp_status.len); });
  2792. });
  2793. }
  2794. });
  2795. }
  2796. });
  2797. ret = 0;
  2798. Exit:
  2799. return ret;
  2800. }
  2801. static int default_emit_certificate_cb(ptls_emit_certificate_t *_self, ptls_t *tls, ptls_message_emitter_t *emitter,
  2802. ptls_key_schedule_t *key_sched, ptls_iovec_t context, int push_status_request,
  2803. const uint16_t *compress_algos, size_t num_compress_algos)
  2804. {
  2805. int ret;
  2806. ptls_push_message(emitter, key_sched, PTLS_HANDSHAKE_TYPE_CERTIFICATE, {
  2807. if ((ret = ptls_build_certificate_message(emitter->buf, context, tls->ctx->certificates.list, tls->ctx->certificates.count,
  2808. ptls_iovec_init(NULL, 0))) != 0)
  2809. goto Exit;
  2810. });
  2811. ret = 0;
  2812. Exit:
  2813. return ret;
  2814. }
  2815. static int send_certificate(ptls_t *tls, ptls_message_emitter_t *emitter,
  2816. struct st_ptls_signature_algorithms_t *signature_algorithms, ptls_iovec_t context,
  2817. int push_status_request, const uint16_t *compress_algos, size_t num_compress_algos)
  2818. {
  2819. int ret;
  2820. if (signature_algorithms->count == 0) {
  2821. ret = PTLS_ALERT_MISSING_EXTENSION;
  2822. goto Exit;
  2823. }
  2824. { /* send Certificate (or the equivalent) */
  2825. static ptls_emit_certificate_t default_emit_certificate = {default_emit_certificate_cb};
  2826. ptls_emit_certificate_t *emit_certificate =
  2827. tls->ctx->emit_certificate != NULL ? tls->ctx->emit_certificate : &default_emit_certificate;
  2828. Redo:
  2829. if ((ret = emit_certificate->cb(emit_certificate, tls, emitter, tls->key_schedule, context, push_status_request,
  2830. compress_algos, num_compress_algos)) != 0) {
  2831. if (ret == PTLS_ERROR_DELEGATE) {
  2832. assert(emit_certificate != &default_emit_certificate);
  2833. emit_certificate = &default_emit_certificate;
  2834. goto Redo;
  2835. }
  2836. goto Exit;
  2837. }
  2838. }
  2839. Exit:
  2840. return ret;
  2841. }
  2842. static int send_certificate_verify(ptls_t *tls, ptls_message_emitter_t *emitter,
  2843. struct st_ptls_signature_algorithms_t *signature_algorithms, const char *context_string)
  2844. {
  2845. size_t start_off = emitter->buf->off;
  2846. int ret;
  2847. if (tls->ctx->sign_certificate == NULL)
  2848. return 0;
  2849. /* build and send CertificateVerify */
  2850. ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY, {
  2851. ptls_buffer_t *sendbuf = emitter->buf;
  2852. size_t algo_off = sendbuf->off;
  2853. ptls_buffer_push16(sendbuf, 0); /* filled in later */
  2854. ptls_buffer_push_block(sendbuf, 2, {
  2855. uint16_t algo;
  2856. uint8_t data[PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE];
  2857. size_t datalen = build_certificate_verify_signdata(data, tls->key_schedule, context_string);
  2858. if ((ret = tls->ctx->sign_certificate->cb(
  2859. tls->ctx->sign_certificate, tls, tls->is_server ? &tls->server.async_job : NULL, &algo, sendbuf,
  2860. ptls_iovec_init(data, datalen), signature_algorithms != NULL ? signature_algorithms->list : NULL,
  2861. signature_algorithms != NULL ? signature_algorithms->count : 0)) != 0) {
  2862. if (ret == PTLS_ERROR_ASYNC_OPERATION) {
  2863. assert(tls->is_server || !"async operation only supported on the server-side");
  2864. assert(tls->server.async_job != NULL);
  2865. /* Reset the output to the end of the previous handshake message. CertificateVerify will be rebuilt when the
  2866. * async operation completes. */
  2867. emitter->buf->off = start_off;
  2868. } else {
  2869. assert(tls->server.async_job == NULL);
  2870. }
  2871. goto Exit;
  2872. }
  2873. assert(tls->server.async_job == NULL);
  2874. sendbuf->base[algo_off] = (uint8_t)(algo >> 8);
  2875. sendbuf->base[algo_off + 1] = (uint8_t)algo;
  2876. });
  2877. });
  2878. Exit:
  2879. return ret;
  2880. }
  2881. static int client_handle_certificate_request(ptls_t *tls, ptls_iovec_t message, ptls_handshake_properties_t *properties)
  2882. {
  2883. const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
  2884. int ret = 0;
  2885. assert(!tls->is_psk_handshake && "state machine asserts that this message is never delivered when PSK is used");
  2886. if ((ret = decode_certificate_request(tls, &tls->client.certificate_request, src, end)) != 0)
  2887. return ret;
  2888. /* This field SHALL be zero length unless used for the post-handshake authentication exchanges (section 4.3.2) */
  2889. if (tls->client.certificate_request.context.len != 0)
  2890. return PTLS_ALERT_ILLEGAL_PARAMETER;
  2891. tls->state = PTLS_STATE_CLIENT_EXPECT_CERTIFICATE;
  2892. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  2893. return PTLS_ERROR_IN_PROGRESS;
  2894. }
  2895. static int handle_certificate(ptls_t *tls, const uint8_t *src, const uint8_t *end, int *got_certs)
  2896. {
  2897. ptls_iovec_t certs[16];
  2898. size_t num_certs = 0;
  2899. int ret = 0;
  2900. /* certificate request context */
  2901. ptls_decode_open_block(src, end, 1, {
  2902. if (src != end) {
  2903. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  2904. goto Exit;
  2905. }
  2906. });
  2907. /* certificate_list */
  2908. ptls_decode_block(src, end, 3, {
  2909. while (src != end) {
  2910. ptls_decode_open_block(src, end, 3, {
  2911. if (num_certs < PTLS_ELEMENTSOF(certs))
  2912. certs[num_certs++] = ptls_iovec_init(src, end - src);
  2913. src = end;
  2914. });
  2915. uint16_t type;
  2916. decode_open_extensions(src, end, PTLS_HANDSHAKE_TYPE_CERTIFICATE, &type, {
  2917. if (tls->ctx->on_extension != NULL &&
  2918. (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_CERTIFICATE, type,
  2919. ptls_iovec_init(src, end - src)) != 0))
  2920. goto Exit;
  2921. src = end;
  2922. });
  2923. }
  2924. });
  2925. if (tls->ctx->verify_certificate != NULL) {
  2926. const char *server_name = NULL;
  2927. if (!ptls_is_server(tls)) {
  2928. if (tls->ech.offered && !ptls_is_ech_handshake(tls, NULL, NULL, NULL)) {
  2929. server_name = tls->ech.client.public_name;
  2930. } else {
  2931. server_name = tls->server_name;
  2932. }
  2933. }
  2934. if ((ret = tls->ctx->verify_certificate->cb(tls->ctx->verify_certificate, tls, server_name, &tls->certificate_verify.cb,
  2935. &tls->certificate_verify.verify_ctx, certs, num_certs)) != 0)
  2936. goto Exit;
  2937. }
  2938. *got_certs = num_certs != 0;
  2939. Exit:
  2940. return ret;
  2941. }
  2942. static int client_do_handle_certificate(ptls_t *tls, const uint8_t *src, const uint8_t *end)
  2943. {
  2944. int got_certs, ret;
  2945. if ((ret = handle_certificate(tls, src, end, &got_certs)) != 0)
  2946. return ret;
  2947. if (!got_certs)
  2948. return PTLS_ALERT_ILLEGAL_PARAMETER;
  2949. return 0;
  2950. }
  2951. static int client_handle_certificate(ptls_t *tls, ptls_iovec_t message)
  2952. {
  2953. int ret;
  2954. if ((ret = client_do_handle_certificate(tls, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.base + message.len)) != 0)
  2955. return ret;
  2956. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  2957. tls->state = PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY;
  2958. return PTLS_ERROR_IN_PROGRESS;
  2959. }
  2960. static int client_handle_compressed_certificate(ptls_t *tls, ptls_iovec_t message)
  2961. {
  2962. const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
  2963. uint16_t algo;
  2964. uint32_t uncompressed_size;
  2965. uint8_t *uncompressed = NULL;
  2966. int ret;
  2967. if (tls->ctx->decompress_certificate == NULL) {
  2968. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  2969. goto Exit;
  2970. }
  2971. /* decode */
  2972. if ((ret = ptls_decode16(&algo, &src, end)) != 0)
  2973. goto Exit;
  2974. if ((ret = ptls_decode24(&uncompressed_size, &src, end)) != 0)
  2975. goto Exit;
  2976. if (uncompressed_size > 65536) { /* TODO find a sensible number */
  2977. ret = PTLS_ALERT_BAD_CERTIFICATE;
  2978. goto Exit;
  2979. }
  2980. if ((uncompressed = malloc(uncompressed_size)) == NULL) {
  2981. ret = PTLS_ERROR_NO_MEMORY;
  2982. goto Exit;
  2983. }
  2984. ptls_decode_block(src, end, 3, {
  2985. if ((ret = tls->ctx->decompress_certificate->cb(tls->ctx->decompress_certificate, tls, algo,
  2986. ptls_iovec_init(uncompressed, uncompressed_size),
  2987. ptls_iovec_init(src, end - src))) != 0)
  2988. goto Exit;
  2989. src = end;
  2990. });
  2991. /* handle */
  2992. if ((ret = client_do_handle_certificate(tls, uncompressed, uncompressed + uncompressed_size)) != 0)
  2993. goto Exit;
  2994. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  2995. tls->state = PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY;
  2996. ret = PTLS_ERROR_IN_PROGRESS;
  2997. Exit:
  2998. free(uncompressed);
  2999. return ret;
  3000. }
  3001. static int server_handle_certificate(ptls_t *tls, ptls_iovec_t message)
  3002. {
  3003. int got_certs, ret;
  3004. if ((ret = handle_certificate(tls, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.base + message.len, &got_certs)) != 0)
  3005. return ret;
  3006. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  3007. if (got_certs) {
  3008. tls->state = PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY;
  3009. } else {
  3010. /* Client did not provide certificate, and the verifier says we can fail open. Therefore, the next message is Finished. */
  3011. tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
  3012. }
  3013. return PTLS_ERROR_IN_PROGRESS;
  3014. }
  3015. static int handle_certificate_verify(ptls_t *tls, ptls_iovec_t message, const char *context_string)
  3016. {
  3017. const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
  3018. uint16_t algo;
  3019. ptls_iovec_t signature;
  3020. uint8_t signdata[PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE];
  3021. size_t signdata_size;
  3022. int ret;
  3023. /* decode */
  3024. if ((ret = ptls_decode16(&algo, &src, end)) != 0)
  3025. goto Exit;
  3026. ptls_decode_block(src, end, 2, {
  3027. signature = ptls_iovec_init(src, end - src);
  3028. src = end;
  3029. });
  3030. signdata_size = build_certificate_verify_signdata(signdata, tls->key_schedule, context_string);
  3031. if (tls->certificate_verify.cb != NULL) {
  3032. ret = tls->certificate_verify.cb(tls->certificate_verify.verify_ctx, algo, ptls_iovec_init(signdata, signdata_size),
  3033. signature);
  3034. } else {
  3035. ret = 0;
  3036. }
  3037. ptls_clear_memory(signdata, signdata_size);
  3038. tls->certificate_verify.cb = NULL;
  3039. if (ret != 0) {
  3040. goto Exit;
  3041. }
  3042. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  3043. Exit:
  3044. return ret;
  3045. }
  3046. static int client_handle_certificate_verify(ptls_t *tls, ptls_iovec_t message)
  3047. {
  3048. int ret = handle_certificate_verify(tls, message, PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING);
  3049. if (ret == 0) {
  3050. tls->state = PTLS_STATE_CLIENT_EXPECT_FINISHED;
  3051. ret = PTLS_ERROR_IN_PROGRESS;
  3052. }
  3053. return ret;
  3054. }
  3055. static int server_handle_certificate_verify(ptls_t *tls, ptls_iovec_t message)
  3056. {
  3057. int ret = handle_certificate_verify(tls, message, PTLS_CLIENT_CERTIFICATE_VERIFY_CONTEXT_STRING);
  3058. if (ret == 0) {
  3059. tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
  3060. ret = PTLS_ERROR_IN_PROGRESS;
  3061. }
  3062. return ret;
  3063. }
  3064. static int client_handle_finished(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message)
  3065. {
  3066. uint8_t send_secret[PTLS_MAX_DIGEST_SIZE];
  3067. int alert_ech_required = tls->ech.offered && !ptls_is_ech_handshake(tls, NULL, NULL, NULL), ret;
  3068. if ((ret = verify_finished(tls, message)) != 0)
  3069. goto Exit;
  3070. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  3071. /* update traffic keys by using messages upto ServerFinished, but commission them after sending ClientFinished */
  3072. if ((ret = key_schedule_extract(tls->key_schedule, ptls_iovec_init(NULL, 0))) != 0)
  3073. goto Exit;
  3074. if ((ret = setup_traffic_protection(tls, 0, "s ap traffic", 3, 0, 0)) != 0)
  3075. goto Exit;
  3076. if ((ret = derive_secret(tls->key_schedule, send_secret, "c ap traffic")) != 0)
  3077. goto Exit;
  3078. if ((ret = derive_exporter_secret(tls, 0)) != 0)
  3079. goto Exit;
  3080. /* if sending early data, emit EOED and commision the client handshake traffic secret */
  3081. if (tls->pending_handshake_secret != NULL) {
  3082. assert(tls->traffic_protection.enc.aead != NULL || tls->ctx->update_traffic_key != NULL);
  3083. if (tls->client.using_early_data && !tls->ctx->omit_end_of_early_data)
  3084. ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_END_OF_EARLY_DATA, {});
  3085. tls->client.using_early_data = 0;
  3086. if ((ret = commission_handshake_secret(tls)) != 0)
  3087. goto Exit;
  3088. }
  3089. if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
  3090. goto Exit;
  3091. if (!alert_ech_required && tls->client.certificate_request.context.base != NULL) {
  3092. if ((ret = send_certificate(tls, emitter, &tls->client.certificate_request.signature_algorithms,
  3093. tls->client.certificate_request.context, 0, NULL, 0)) == 0)
  3094. ret = send_certificate_verify(tls, emitter, &tls->client.certificate_request.signature_algorithms,
  3095. PTLS_CLIENT_CERTIFICATE_VERIFY_CONTEXT_STRING);
  3096. free(tls->client.certificate_request.context.base);
  3097. tls->client.certificate_request.context = ptls_iovec_init(NULL, 0);
  3098. if (ret != 0)
  3099. goto Exit;
  3100. }
  3101. ret = send_finished(tls, emitter);
  3102. memcpy(tls->traffic_protection.enc.secret, send_secret, sizeof(send_secret));
  3103. if ((ret = setup_traffic_protection(tls, 1, NULL, 3, 0, 0)) != 0)
  3104. goto Exit;
  3105. tls->state = PTLS_STATE_CLIENT_POST_HANDSHAKE;
  3106. /* if ECH was rejected, close the connection with ECH_REQUIRED alert after verifying messages up to Finished */
  3107. if (alert_ech_required)
  3108. ret = PTLS_ALERT_ECH_REQUIRED;
  3109. Exit:
  3110. ptls_clear_memory(send_secret, sizeof(send_secret));
  3111. return ret;
  3112. }
  3113. static int client_handle_new_session_ticket(ptls_t *tls, ptls_iovec_t message)
  3114. {
  3115. const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
  3116. ptls_iovec_t ticket_nonce;
  3117. int ret;
  3118. { /* verify the format */
  3119. uint32_t ticket_lifetime, ticket_age_add, max_early_data_size;
  3120. ptls_iovec_t ticket;
  3121. if ((ret = decode_new_session_ticket(tls, &ticket_lifetime, &ticket_age_add, &ticket_nonce, &ticket, &max_early_data_size,
  3122. src, end)) != 0)
  3123. return ret;
  3124. }
  3125. /* do nothing if use of session ticket is disabled */
  3126. if (tls->ctx->save_ticket == NULL)
  3127. return 0;
  3128. /* save the extension, along with the key of myself */
  3129. ptls_buffer_t ticket_buf;
  3130. ptls_buffer_init(&ticket_buf, "", 0);
  3131. ptls_buffer_push64(&ticket_buf, tls->ctx->get_time->cb(tls->ctx->get_time));
  3132. ptls_buffer_push16(&ticket_buf, tls->key_share->id);
  3133. ptls_buffer_push16(&ticket_buf, tls->cipher_suite->id);
  3134. ptls_buffer_push_block(&ticket_buf, 3, { ptls_buffer_pushv(&ticket_buf, src, end - src); });
  3135. ptls_buffer_push_block(&ticket_buf, 2, {
  3136. if ((ret = ptls_buffer_reserve(&ticket_buf, tls->key_schedule->hashes[0].algo->digest_size)) != 0)
  3137. goto Exit;
  3138. if ((ret = derive_resumption_secret(tls->key_schedule, ticket_buf.base + ticket_buf.off, ticket_nonce)) != 0)
  3139. goto Exit;
  3140. ticket_buf.off += tls->key_schedule->hashes[0].algo->digest_size;
  3141. });
  3142. if ((ret = tls->ctx->save_ticket->cb(tls->ctx->save_ticket, tls, ptls_iovec_init(ticket_buf.base, ticket_buf.off))) != 0)
  3143. goto Exit;
  3144. ret = 0;
  3145. Exit:
  3146. ptls_buffer_dispose(&ticket_buf);
  3147. return ret;
  3148. }
  3149. static int client_hello_decode_server_name(ptls_iovec_t *name, const uint8_t **src, const uint8_t *const end)
  3150. {
  3151. int ret = 0;
  3152. ptls_decode_open_block(*src, end, 2, {
  3153. do {
  3154. uint8_t type;
  3155. if ((ret = ptls_decode8(&type, src, end)) != 0)
  3156. goto Exit;
  3157. ptls_decode_open_block(*src, end, 2, {
  3158. switch (type) {
  3159. case PTLS_SERVER_NAME_TYPE_HOSTNAME:
  3160. if (memchr(*src, '\0', end - *src) != 0) {
  3161. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  3162. goto Exit;
  3163. }
  3164. *name = ptls_iovec_init(*src, end - *src);
  3165. break;
  3166. default:
  3167. break;
  3168. }
  3169. *src = end;
  3170. });
  3171. } while (*src != end);
  3172. });
  3173. Exit:
  3174. return ret;
  3175. }
  3176. static int select_negotiated_group(ptls_key_exchange_algorithm_t **selected, ptls_key_exchange_algorithm_t **candidates,
  3177. const uint8_t *src, const uint8_t *const end)
  3178. {
  3179. int ret;
  3180. ptls_decode_block(src, end, 2, {
  3181. while (src != end) {
  3182. uint16_t group;
  3183. if ((ret = ptls_decode16(&group, &src, end)) != 0)
  3184. goto Exit;
  3185. ptls_key_exchange_algorithm_t **c = candidates;
  3186. for (; *c != NULL; ++c) {
  3187. if ((*c)->id == group) {
  3188. *selected = *c;
  3189. return 0;
  3190. }
  3191. }
  3192. }
  3193. });
  3194. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  3195. Exit:
  3196. return ret;
  3197. }
  3198. static int decode_client_hello(ptls_context_t *ctx, struct st_ptls_client_hello_t *ch, const uint8_t *src, const uint8_t *const end,
  3199. ptls_handshake_properties_t *properties, ptls_t *tls_cbarg)
  3200. {
  3201. const uint8_t *start = src;
  3202. uint16_t exttype = 0;
  3203. int ret;
  3204. /* decode protocol version (do not bare to decode something older than TLS 1.0) */
  3205. if ((ret = ptls_decode16(&ch->legacy_version, &src, end)) != 0)
  3206. goto Exit;
  3207. if (ch->legacy_version < 0x0301) {
  3208. ret = PTLS_ALERT_PROTOCOL_VERSION;
  3209. goto Exit;
  3210. }
  3211. /* skip random */
  3212. if (end - src < PTLS_HELLO_RANDOM_SIZE) {
  3213. ret = PTLS_ALERT_DECODE_ERROR;
  3214. goto Exit;
  3215. }
  3216. ch->random_bytes = src;
  3217. src += PTLS_HELLO_RANDOM_SIZE;
  3218. /* skip legacy_session_id */
  3219. ptls_decode_open_block(src, end, 1, {
  3220. if (end - src > 32) {
  3221. ret = PTLS_ALERT_DECODE_ERROR;
  3222. goto Exit;
  3223. }
  3224. ch->legacy_session_id = ptls_iovec_init(src, end - src);
  3225. src = end;
  3226. });
  3227. /* decode and select from ciphersuites */
  3228. ptls_decode_open_block(src, end, 2, {
  3229. if ((end - src) % 2 != 0) {
  3230. ret = PTLS_ALERT_DECODE_ERROR;
  3231. goto Exit;
  3232. }
  3233. ch->cipher_suites = ptls_iovec_init(src, end - src);
  3234. src = end;
  3235. });
  3236. /* decode legacy_compression_methods */
  3237. ptls_decode_open_block(src, end, 1, {
  3238. if (src == end) {
  3239. ret = PTLS_ALERT_DECODE_ERROR;
  3240. goto Exit;
  3241. }
  3242. ch->compression_methods.ids = src;
  3243. ch->compression_methods.count = end - src;
  3244. src = end;
  3245. });
  3246. /* In TLS versions 1.2 and earlier CH might not have an extensions block (or they might, see what OpenSSL 1.0.0 sends); so bail
  3247. * out if that is the case after parsing the main variables. Zero is returned as it is a valid ClientHello. However
  3248. * `ptls_t::selected_version` remains zero indicating that no compatible version were found. */
  3249. if (src == end) {
  3250. ret = 0;
  3251. goto Exit;
  3252. }
  3253. /* decode extensions */
  3254. ch->first_extension_at = src - start + 2;
  3255. decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_CLIENT_HELLO, &exttype, {
  3256. ch->psk.is_last_extension = 0;
  3257. if (ctx->on_extension != NULL && tls_cbarg != NULL &&
  3258. (ret = ctx->on_extension->cb(ctx->on_extension, tls_cbarg, PTLS_HANDSHAKE_TYPE_CLIENT_HELLO, exttype,
  3259. ptls_iovec_init(src, end - src)) != 0))
  3260. goto Exit;
  3261. switch (exttype) {
  3262. case PTLS_EXTENSION_TYPE_SERVER_NAME:
  3263. if ((ret = client_hello_decode_server_name(&ch->server_name, &src, end)) != 0)
  3264. goto Exit;
  3265. if (src != end) {
  3266. ret = PTLS_ALERT_DECODE_ERROR;
  3267. goto Exit;
  3268. }
  3269. break;
  3270. case PTLS_EXTENSION_TYPE_ALPN:
  3271. ptls_decode_block(src, end, 2, {
  3272. do {
  3273. ptls_decode_open_block(src, end, 1, {
  3274. /* rfc7301 3.1: empty strings MUST NOT be included */
  3275. if (src == end) {
  3276. ret = PTLS_ALERT_DECODE_ERROR;
  3277. goto Exit;
  3278. }
  3279. if (ch->alpn.count < PTLS_ELEMENTSOF(ch->alpn.list))
  3280. ch->alpn.list[ch->alpn.count++] = ptls_iovec_init(src, end - src);
  3281. src = end;
  3282. });
  3283. } while (src != end);
  3284. });
  3285. break;
  3286. case PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE:
  3287. ptls_decode_block(src, end, 1, {
  3288. size_t list_size = end - src;
  3289. /* RFC7250 4.1: No empty list, no list with single x509 element */
  3290. if (list_size == 0 || (list_size == 1 && *src == PTLS_CERTIFICATE_TYPE_X509)) {
  3291. ret = PTLS_ALERT_DECODE_ERROR;
  3292. goto Exit;
  3293. }
  3294. do {
  3295. if (ch->server_certificate_types.count < PTLS_ELEMENTSOF(ch->server_certificate_types.list))
  3296. ch->server_certificate_types.list[ch->server_certificate_types.count++] = *src;
  3297. src++;
  3298. } while (src != end);
  3299. });
  3300. break;
  3301. case PTLS_EXTENSION_TYPE_COMPRESS_CERTIFICATE:
  3302. ptls_decode_block(src, end, 1, {
  3303. do {
  3304. uint16_t id;
  3305. if ((ret = ptls_decode16(&id, &src, end)) != 0)
  3306. goto Exit;
  3307. if (ch->cert_compression_algos.count < PTLS_ELEMENTSOF(ch->cert_compression_algos.list))
  3308. ch->cert_compression_algos.list[ch->cert_compression_algos.count++] = id;
  3309. } while (src != end);
  3310. });
  3311. break;
  3312. case PTLS_EXTENSION_TYPE_SUPPORTED_GROUPS:
  3313. ch->negotiated_groups = ptls_iovec_init(src, end - src);
  3314. break;
  3315. case PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS:
  3316. if ((ret = decode_signature_algorithms(&ch->signature_algorithms, &src, end)) != 0)
  3317. goto Exit;
  3318. break;
  3319. case PTLS_EXTENSION_TYPE_KEY_SHARE:
  3320. ch->key_shares = ptls_iovec_init(src, end - src);
  3321. break;
  3322. case PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS:
  3323. ptls_decode_block(src, end, 1, {
  3324. size_t selected_index = PTLS_ELEMENTSOF(supported_versions);
  3325. do {
  3326. size_t i;
  3327. uint16_t v;
  3328. if ((ret = ptls_decode16(&v, &src, end)) != 0)
  3329. goto Exit;
  3330. for (i = 0; i != selected_index; ++i) {
  3331. if (supported_versions[i] == v) {
  3332. selected_index = i;
  3333. break;
  3334. }
  3335. }
  3336. } while (src != end);
  3337. if (selected_index != PTLS_ELEMENTSOF(supported_versions))
  3338. ch->selected_version = supported_versions[selected_index];
  3339. });
  3340. break;
  3341. case PTLS_EXTENSION_TYPE_COOKIE:
  3342. if (properties == NULL || properties->server.cookie.key == NULL) {
  3343. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  3344. goto Exit;
  3345. }
  3346. ch->cookie.all = ptls_iovec_init(src, end - src);
  3347. ptls_decode_block(src, end, 2, {
  3348. ch->cookie.tbs.base = (void *)src;
  3349. ptls_decode_open_block(src, end, 2, {
  3350. ptls_decode_open_block(src, end, 1, {
  3351. ch->cookie.ch1_hash = ptls_iovec_init(src, end - src);
  3352. src = end;
  3353. });
  3354. uint8_t sent_key_share;
  3355. if ((ret = ptls_decode8(&sent_key_share, &src, end)) != 0)
  3356. goto Exit;
  3357. switch (sent_key_share) {
  3358. case 0:
  3359. assert(!ch->cookie.sent_key_share);
  3360. break;
  3361. case 1:
  3362. ch->cookie.sent_key_share = 1;
  3363. break;
  3364. default:
  3365. ret = PTLS_ALERT_DECODE_ERROR;
  3366. goto Exit;
  3367. }
  3368. });
  3369. ch->cookie.tbs.len = src - ch->cookie.tbs.base;
  3370. ptls_decode_block(src, end, 1, {
  3371. ch->cookie.signature = ptls_iovec_init(src, end - src);
  3372. src = end;
  3373. });
  3374. });
  3375. break;
  3376. case PTLS_EXTENSION_TYPE_PRE_SHARED_KEY: {
  3377. size_t num_identities = 0;
  3378. ptls_decode_open_block(src, end, 2, {
  3379. do {
  3380. ptls_client_hello_psk_identity_t psk = {{NULL}};
  3381. ptls_decode_open_block(src, end, 2, {
  3382. if (end - src < 1) {
  3383. ret = PTLS_ALERT_DECODE_ERROR;
  3384. goto Exit;
  3385. }
  3386. psk.identity = ptls_iovec_init(src, end - src);
  3387. src = end;
  3388. });
  3389. if ((ret = ptls_decode32(&psk.obfuscated_ticket_age, &src, end)) != 0)
  3390. goto Exit;
  3391. if (ch->psk.identities.count < PTLS_ELEMENTSOF(ch->psk.identities.list))
  3392. ch->psk.identities.list[ch->psk.identities.count++] = psk;
  3393. ++num_identities;
  3394. } while (src != end);
  3395. });
  3396. ch->psk.hash_end = src;
  3397. ptls_decode_block(src, end, 2, {
  3398. size_t num_binders = 0;
  3399. do {
  3400. ptls_decode_open_block(src, end, 1, {
  3401. if (num_binders < ch->psk.identities.count)
  3402. ch->psk.identities.list[num_binders].binder = ptls_iovec_init(src, end - src);
  3403. src = end;
  3404. });
  3405. ++num_binders;
  3406. } while (src != end);
  3407. if (num_identities != num_binders) {
  3408. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  3409. goto Exit;
  3410. }
  3411. });
  3412. ch->psk.is_last_extension = 1;
  3413. } break;
  3414. case PTLS_EXTENSION_TYPE_PSK_KEY_EXCHANGE_MODES:
  3415. ptls_decode_block(src, end, 1, {
  3416. do {
  3417. uint8_t mode;
  3418. if ((ret = ptls_decode8(&mode, &src, end)) != 0)
  3419. goto Exit;
  3420. if (mode < sizeof(ch->psk.ke_modes) * 8)
  3421. ch->psk.ke_modes |= 1u << mode;
  3422. } while (src != end);
  3423. });
  3424. break;
  3425. case PTLS_EXTENSION_TYPE_EARLY_DATA:
  3426. ch->psk.early_data_indication = 1;
  3427. break;
  3428. case PTLS_EXTENSION_TYPE_STATUS_REQUEST:
  3429. ch->status_request = 1;
  3430. break;
  3431. case PTLS_EXTENSION_TYPE_TICKET_REQUEST:
  3432. if (end - src != 2) {
  3433. ret = PTLS_ALERT_DECODE_ERROR;
  3434. goto Exit;
  3435. }
  3436. ch->ticket_request.new_session_count = *src++;
  3437. ch->ticket_request.resumption_count = *src++;
  3438. break;
  3439. case PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO:
  3440. if ((ret = ptls_decode8(&ch->ech.type, &src, end)) != 0)
  3441. goto Exit;
  3442. switch (ch->ech.type) {
  3443. case PTLS_ECH_CLIENT_HELLO_TYPE_OUTER:
  3444. if ((ret = ptls_decode16(&ch->ech.cipher_suite.kdf, &src, end)) != 0 ||
  3445. (ret = ptls_decode16(&ch->ech.cipher_suite.aead, &src, end)) != 0)
  3446. goto Exit;
  3447. if ((ret = ptls_decode8(&ch->ech.config_id, &src, end)) != 0)
  3448. goto Exit;
  3449. ptls_decode_open_block(src, end, 2, {
  3450. ch->ech.enc = ptls_iovec_init(src, end - src);
  3451. src = end;
  3452. });
  3453. ptls_decode_open_block(src, end, 2, {
  3454. if (src == end) {
  3455. ret = PTLS_ALERT_DECODE_ERROR;
  3456. goto Exit;
  3457. }
  3458. ch->ech.payload = ptls_iovec_init(src, end - src);
  3459. src = end;
  3460. });
  3461. break;
  3462. case PTLS_ECH_CLIENT_HELLO_TYPE_INNER:
  3463. if (src != end) {
  3464. ret = PTLS_ALERT_DECODE_ERROR;
  3465. goto Exit;
  3466. }
  3467. ch->ech.payload = ptls_iovec_init("", 0); /* non-zero base indicates that the extension was received */
  3468. break;
  3469. default:
  3470. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  3471. goto Exit;
  3472. }
  3473. src = end;
  3474. break;
  3475. default:
  3476. if (tls_cbarg != NULL && should_collect_unknown_extension(tls_cbarg, properties, exttype)) {
  3477. if ((ret = collect_unknown_extension(tls_cbarg, exttype, src, end, ch->unknown_extensions)) != 0)
  3478. goto Exit;
  3479. }
  3480. break;
  3481. }
  3482. src = end;
  3483. });
  3484. ret = 0;
  3485. Exit:
  3486. return ret;
  3487. }
  3488. static int rebuild_ch_inner_extensions(ptls_buffer_t *buf, const uint8_t **src, const uint8_t *const end, const uint8_t *outer_ext,
  3489. const uint8_t *outer_ext_end)
  3490. {
  3491. int ret;
  3492. ptls_buffer_push_block(buf, 2, {
  3493. ptls_decode_open_block(*src, end, 2, {
  3494. while (*src != end) {
  3495. uint16_t exttype;
  3496. if ((ret = ptls_decode16(&exttype, src, end)) != 0)
  3497. goto Exit;
  3498. ptls_decode_open_block(*src, end, 2, {
  3499. if (exttype == PTLS_EXTENSION_TYPE_ECH_OUTER_EXTENSIONS) {
  3500. ptls_decode_open_block(*src, end, 1, {
  3501. do {
  3502. uint16_t reftype;
  3503. uint16_t outertype;
  3504. uint16_t outersize;
  3505. if ((ret = ptls_decode16(&reftype, src, end)) != 0)
  3506. goto Exit;
  3507. if (reftype == PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO) {
  3508. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  3509. goto Exit;
  3510. }
  3511. while (1) {
  3512. if (ptls_decode16(&outertype, &outer_ext, outer_ext_end) != 0 ||
  3513. ptls_decode16(&outersize, &outer_ext, outer_ext_end) != 0) {
  3514. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  3515. goto Exit;
  3516. }
  3517. assert(outer_ext_end - outer_ext >= outersize);
  3518. if (outertype == reftype)
  3519. break;
  3520. outer_ext += outersize;
  3521. }
  3522. buffer_push_extension(buf, reftype, {
  3523. ptls_buffer_pushv(buf, outer_ext, outersize);
  3524. outer_ext += outersize;
  3525. });
  3526. } while (*src != end);
  3527. });
  3528. } else {
  3529. buffer_push_extension(buf, exttype, {
  3530. ptls_buffer_pushv(buf, *src, end - *src);
  3531. *src = end;
  3532. });
  3533. }
  3534. });
  3535. }
  3536. });
  3537. });
  3538. Exit:
  3539. return ret;
  3540. }
  3541. static int rebuild_ch_inner(ptls_buffer_t *buf, const uint8_t *src, const uint8_t *const end,
  3542. struct st_ptls_client_hello_t *outer_ch, const uint8_t *outer_ext, const uint8_t *outer_ext_end)
  3543. {
  3544. #define COPY_BLOCK(capacity) \
  3545. do { \
  3546. ptls_decode_open_block(src, end, (capacity), { \
  3547. ptls_buffer_push_block(buf, (capacity), { ptls_buffer_pushv(buf, src, end - src); }); \
  3548. src = end; \
  3549. }); \
  3550. } while (0)
  3551. int ret;
  3552. ptls_buffer_push_message_body(buf, NULL, PTLS_HANDSHAKE_TYPE_CLIENT_HELLO, {
  3553. { /* legacy_version */
  3554. uint16_t legacy_version;
  3555. if ((ret = ptls_decode16(&legacy_version, &src, end)) != 0)
  3556. goto Exit;
  3557. ptls_buffer_push16(buf, legacy_version);
  3558. }
  3559. /* hello random */
  3560. if (end - src < PTLS_HELLO_RANDOM_SIZE) {
  3561. ret = PTLS_ALERT_DECODE_ERROR;
  3562. goto Exit;
  3563. }
  3564. ptls_buffer_pushv(buf, src, PTLS_HELLO_RANDOM_SIZE);
  3565. src += PTLS_HELLO_RANDOM_SIZE;
  3566. ptls_decode_open_block(src, end, 1, {
  3567. if (src != end) {
  3568. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  3569. goto Exit;
  3570. }
  3571. });
  3572. ptls_buffer_push_block(buf, 1,
  3573. { ptls_buffer_pushv(buf, outer_ch->legacy_session_id.base, outer_ch->legacy_session_id.len); });
  3574. /* cipher-suites and legacy-compression-methods */
  3575. COPY_BLOCK(2);
  3576. COPY_BLOCK(1);
  3577. /* extensions */
  3578. if ((ret = rebuild_ch_inner_extensions(buf, &src, end, outer_ext, outer_ext_end)) != 0)
  3579. goto Exit;
  3580. });
  3581. /* padding must be all zero */
  3582. for (; src != end; ++src) {
  3583. if (*src != '\0') {
  3584. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  3585. goto Exit;
  3586. }
  3587. }
  3588. Exit:
  3589. return ret;
  3590. #undef COPY_BLOCK
  3591. }
  3592. /* Wrapper function for invoking the on_client_hello callback, taking an exhaustive list of parameters as arguments. The intention
  3593. * is to not miss setting them as we add new parameters to the struct. */
  3594. static inline int call_on_client_hello_cb(ptls_t *tls, ptls_iovec_t server_name, ptls_iovec_t raw_message,
  3595. ptls_iovec_t cipher_suites, ptls_iovec_t *alpns, size_t num_alpns,
  3596. const uint16_t *sig_algos, size_t num_sig_algos, const uint16_t *cert_comp_algos,
  3597. size_t num_cert_comp_algos, const uint8_t *server_cert_types,
  3598. size_t num_server_cert_types, const ptls_client_hello_psk_identity_t *psk_identities,
  3599. size_t num_psk_identities, int incompatible_version)
  3600. {
  3601. if (tls->ctx->on_client_hello == NULL)
  3602. return 0;
  3603. ptls_on_client_hello_parameters_t params = {server_name,
  3604. raw_message,
  3605. cipher_suites,
  3606. {alpns, num_alpns},
  3607. {sig_algos, num_sig_algos},
  3608. {cert_comp_algos, num_cert_comp_algos},
  3609. {server_cert_types, num_server_cert_types},
  3610. {psk_identities, num_psk_identities},
  3611. incompatible_version};
  3612. return tls->ctx->on_client_hello->cb(tls->ctx->on_client_hello, tls, &params);
  3613. }
  3614. static int check_client_hello_constraints(ptls_context_t *ctx, struct st_ptls_client_hello_t *ch, const void *prev_random,
  3615. int ech_is_inner_ch, ptls_iovec_t raw_message, ptls_t *tls_cbarg)
  3616. {
  3617. int is_second_flight = prev_random != 0;
  3618. /* The following check is necessary so that we would be able to track the connection in SSLKEYLOGFILE, even though it might not
  3619. * be for the safety of the protocol. */
  3620. if (is_second_flight && !ptls_mem_equal(ch->random_bytes, prev_random, PTLS_HELLO_RANDOM_SIZE))
  3621. return PTLS_ALERT_HANDSHAKE_FAILURE;
  3622. /* bail out if CH cannot be handled as TLS 1.3 */
  3623. if (!is_supported_version(ch->selected_version)) {
  3624. /* ECH: server MUST abort with an "illegal_parameter" alert if the client offers TLS 1.2 or below (draft-15 7.1) */
  3625. if (ech_is_inner_ch)
  3626. return PTLS_ALERT_ILLEGAL_PARAMETER;
  3627. /* fail with PROTOCOL_VERSION alert, after providing the applications the raw CH and SNI to help them fallback */
  3628. if (!is_second_flight) {
  3629. int ret;
  3630. if ((ret = call_on_client_hello_cb(tls_cbarg, ch->server_name, raw_message, ch->cipher_suites, ch->alpn.list,
  3631. ch->alpn.count, NULL, 0, NULL, 0, NULL, 0, NULL, 0, 1)) != 0)
  3632. return ret;
  3633. }
  3634. return PTLS_ALERT_PROTOCOL_VERSION;
  3635. }
  3636. /* Check TLS 1.3-specific constraints. Hereafter, we might exit without calling on_client_hello. That's fine because this CH is
  3637. * ought to be rejected. */
  3638. if (ch->legacy_version <= 0x0300) {
  3639. /* RFC 8446 Appendix D.5: any endpoint receiving a Hello message with legacy_version set to 0x0300 MUST abort the handshake
  3640. * with a "protocol_version" alert. */
  3641. return PTLS_ALERT_PROTOCOL_VERSION;
  3642. }
  3643. if (!(ch->compression_methods.count == 1 && ch->compression_methods.ids[0] == 0))
  3644. return PTLS_ALERT_ILLEGAL_PARAMETER;
  3645. /* pre-shared key */
  3646. if (ch->psk.hash_end != NULL) {
  3647. /* PSK must be the last extension */
  3648. if (!ch->psk.is_last_extension)
  3649. return PTLS_ALERT_ILLEGAL_PARAMETER;
  3650. } else {
  3651. if (ch->psk.early_data_indication)
  3652. return PTLS_ALERT_ILLEGAL_PARAMETER;
  3653. }
  3654. if (ech_is_inner_ch && ch->ech.payload.base == NULL)
  3655. return PTLS_ALERT_ILLEGAL_PARAMETER;
  3656. if (ch->ech.payload.base != NULL &&
  3657. ch->ech.type != (ech_is_inner_ch ? PTLS_ECH_CLIENT_HELLO_TYPE_INNER : PTLS_ECH_CLIENT_HELLO_TYPE_OUTER))
  3658. return PTLS_ALERT_ILLEGAL_PARAMETER;
  3659. return 0;
  3660. }
  3661. static int vec_is_string(ptls_iovec_t x, const char *y)
  3662. {
  3663. return strncmp((const char *)x.base, y, x.len) == 0 && y[x.len] == '\0';
  3664. }
  3665. /**
  3666. * Looks for a PSK identity that can be used, and if found, updates the handshake state and returns the necessary variables. If
  3667. * `ptls_context_t::pre_shared_key` is set, only tries handshake using those keys provided. Otherwise, tries resumption.
  3668. */
  3669. static int try_psk_handshake(ptls_t *tls, size_t *psk_index, int *accept_early_data, struct st_ptls_client_hello_t *ch,
  3670. ptls_iovec_t ch_trunc, int is_second_flight)
  3671. {
  3672. ptls_buffer_t decbuf;
  3673. ptls_iovec_t secret, ticket_ctx, ticket_negotiated_protocol;
  3674. uint64_t issue_at, now = tls->ctx->get_time->cb(tls->ctx->get_time);
  3675. uint32_t age_add;
  3676. uint16_t ticket_key_exchange_id, ticket_csid;
  3677. uint8_t binder_key[PTLS_MAX_DIGEST_SIZE];
  3678. int ret;
  3679. ptls_buffer_init(&decbuf, "", 0);
  3680. for (*psk_index = 0; *psk_index < ch->psk.identities.count; ++*psk_index) {
  3681. ptls_client_hello_psk_identity_t *identity = ch->psk.identities.list + *psk_index;
  3682. /* negotiate using fixed pre-shared key */
  3683. if (tls->ctx->pre_shared_key.identity.base != NULL) {
  3684. if (identity->identity.len == tls->ctx->pre_shared_key.identity.len &&
  3685. memcmp(identity->identity.base, tls->ctx->pre_shared_key.identity.base, identity->identity.len) == 0) {
  3686. *accept_early_data = ch->psk.early_data_indication && *psk_index == 0;
  3687. tls->key_share = NULL;
  3688. secret = tls->ctx->pre_shared_key.secret;
  3689. goto Found;
  3690. }
  3691. continue;
  3692. }
  3693. /* decrypt ticket and decode */
  3694. if (tls->ctx->encrypt_ticket == NULL || tls->ctx->key_exchanges == NULL)
  3695. continue;
  3696. int can_accept_early_data = *psk_index == 0;
  3697. decbuf.off = 0;
  3698. switch (tls->ctx->encrypt_ticket->cb(tls->ctx->encrypt_ticket, tls, 0, &decbuf, identity->identity)) {
  3699. case 0: /* decrypted */
  3700. break;
  3701. case PTLS_ERROR_REJECT_EARLY_DATA: /* decrypted, but early data is rejected */
  3702. can_accept_early_data = 0;
  3703. break;
  3704. default: /* decryption failure */
  3705. continue;
  3706. }
  3707. if (decode_session_identifier(&issue_at, &secret, &age_add, &ticket_ctx, &ticket_key_exchange_id, &ticket_csid,
  3708. &ticket_negotiated_protocol, decbuf.base, decbuf.base + decbuf.off) != 0)
  3709. continue;
  3710. /* check age */
  3711. if (now < issue_at)
  3712. continue;
  3713. if (now - issue_at > (uint64_t)tls->ctx->ticket_lifetime * 1000)
  3714. continue;
  3715. *accept_early_data = 0;
  3716. if (ch->psk.early_data_indication && can_accept_early_data) {
  3717. /* accept early-data if abs(diff) between the reported age and the actual age is within += 10 seconds */
  3718. int64_t delta = (now - issue_at) - (identity->obfuscated_ticket_age - age_add);
  3719. if (delta < 0)
  3720. delta = -delta;
  3721. if (tls->ctx->max_early_data_size != 0 && delta <= PTLS_EARLY_DATA_MAX_DELAY)
  3722. *accept_early_data = 1;
  3723. }
  3724. /* check ticket context */
  3725. if (tls->ctx->ticket_context.is_set) {
  3726. if (!(ticket_ctx.len == sizeof(tls->ctx->ticket_context.bytes) &&
  3727. memcmp(ticket_ctx.base, tls->ctx->ticket_context.bytes, ticket_ctx.len) == 0))
  3728. continue;
  3729. } else {
  3730. /* check server-name */
  3731. if (ticket_ctx.len != 0) {
  3732. if (tls->server_name == NULL)
  3733. continue;
  3734. if (!vec_is_string(ticket_ctx, tls->server_name))
  3735. continue;
  3736. } else {
  3737. if (tls->server_name != NULL)
  3738. continue;
  3739. }
  3740. }
  3741. { /* check key-exchange */
  3742. ptls_key_exchange_algorithm_t **a;
  3743. for (a = tls->ctx->key_exchanges; *a != NULL && (*a)->id != ticket_key_exchange_id; ++a)
  3744. ;
  3745. if (*a == NULL)
  3746. continue;
  3747. tls->key_share = *a;
  3748. }
  3749. /* check cipher-suite */
  3750. if (ticket_csid != tls->cipher_suite->id)
  3751. continue;
  3752. /* check negotiated-protocol */
  3753. if (ticket_negotiated_protocol.len != 0) {
  3754. if (tls->negotiated_protocol == NULL)
  3755. continue;
  3756. if (!vec_is_string(ticket_negotiated_protocol, tls->negotiated_protocol))
  3757. continue;
  3758. }
  3759. /* check the length of the decrypted psk and the PSK binder */
  3760. if (secret.len != tls->key_schedule->hashes[0].algo->digest_size)
  3761. continue;
  3762. if (ch->psk.identities.list[*psk_index].binder.len != tls->key_schedule->hashes[0].algo->digest_size)
  3763. continue;
  3764. /* found */
  3765. goto Found;
  3766. }
  3767. /* not found */
  3768. *psk_index = SIZE_MAX;
  3769. *accept_early_data = 0;
  3770. tls->key_share = NULL;
  3771. ret = 0;
  3772. goto Exit;
  3773. Found:
  3774. if (!is_second_flight && (ret = key_schedule_extract(tls->key_schedule, secret)) != 0)
  3775. goto Exit;
  3776. if ((ret = derive_secret_with_empty_digest(tls->key_schedule, binder_key,
  3777. tls->ctx->pre_shared_key.secret.base != NULL ? "ext binder" : "res binder")) != 0)
  3778. goto Exit;
  3779. ptls__key_schedule_update_hash(tls->key_schedule, ch_trunc.base, ch_trunc.len, 0);
  3780. if ((ret = calc_verify_data(binder_key /* to conserve space, reuse binder_key for storing verify_data */, tls->key_schedule,
  3781. binder_key)) != 0)
  3782. goto Exit;
  3783. if (!ptls_mem_equal(ch->psk.identities.list[*psk_index].binder.base, binder_key,
  3784. tls->key_schedule->hashes[0].algo->digest_size)) {
  3785. ret = PTLS_ALERT_DECRYPT_ERROR;
  3786. goto Exit;
  3787. }
  3788. ret = 0;
  3789. Exit:
  3790. ptls_buffer_dispose(&decbuf);
  3791. ptls_clear_memory(binder_key, sizeof(binder_key));
  3792. return ret;
  3793. }
  3794. static int calc_cookie_signature(ptls_t *tls, ptls_handshake_properties_t *properties,
  3795. ptls_key_exchange_algorithm_t *negotiated_group, ptls_iovec_t tbs, uint8_t *sig)
  3796. {
  3797. ptls_hash_algorithm_t *algo = tls->ctx->cipher_suites[0]->hash;
  3798. ptls_hash_context_t *hctx;
  3799. if ((hctx = ptls_hmac_create(algo, properties->server.cookie.key, algo->digest_size)) == NULL)
  3800. return PTLS_ERROR_NO_MEMORY;
  3801. #define UPDATE_BLOCK(p, _len) \
  3802. do { \
  3803. size_t len = (_len); \
  3804. assert(len < UINT8_MAX); \
  3805. uint8_t len8 = (uint8_t)len; \
  3806. hctx->update(hctx, &len8, 1); \
  3807. hctx->update(hctx, (p), len); \
  3808. } while (0)
  3809. #define UPDATE16(_v) \
  3810. do { \
  3811. uint16_t v = (_v); \
  3812. uint8_t b[2] = {v >> 8, v & 0xff}; \
  3813. hctx->update(hctx, b, 2); \
  3814. } while (0)
  3815. UPDATE_BLOCK(tls->client_random, sizeof(tls->client_random));
  3816. UPDATE_BLOCK(tls->server_name, tls->server_name != NULL ? strlen(tls->server_name) : 0);
  3817. UPDATE16(tls->cipher_suite->id);
  3818. UPDATE16(negotiated_group != NULL ? negotiated_group->id : 0);
  3819. UPDATE_BLOCK(properties->server.cookie.additional_data.base, properties->server.cookie.additional_data.len);
  3820. UPDATE_BLOCK(tbs.base, tbs.len);
  3821. #undef UPDATE_BLOCK
  3822. #undef UPDATE16
  3823. hctx->final(hctx, sig, PTLS_HASH_FINAL_MODE_FREE);
  3824. return 0;
  3825. }
  3826. static int certificate_type_exists(uint8_t *list, size_t count, uint8_t desired_type)
  3827. {
  3828. /* empty type list means that we default to x509 */
  3829. if (desired_type == PTLS_CERTIFICATE_TYPE_X509 && count == 0)
  3830. return 1;
  3831. for (size_t i = 0; i < count; i++) {
  3832. if (list[i] == desired_type)
  3833. return 1;
  3834. }
  3835. return 0;
  3836. }
  3837. static int server_handle_hello(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message,
  3838. ptls_handshake_properties_t *properties)
  3839. {
  3840. #define EMIT_SERVER_HELLO(sched, fill_rand, extensions, post_action) \
  3841. do { \
  3842. size_t sh_start_off; \
  3843. ptls_push_message(emitter, NULL, PTLS_HANDSHAKE_TYPE_SERVER_HELLO, { \
  3844. sh_start_off = emitter->buf->off - PTLS_HANDSHAKE_HEADER_SIZE; \
  3845. ptls_buffer_push16(emitter->buf, 0x0303 /* legacy version */); \
  3846. if ((ret = ptls_buffer_reserve(emitter->buf, PTLS_HELLO_RANDOM_SIZE)) != 0) \
  3847. goto Exit; \
  3848. do { \
  3849. fill_rand \
  3850. } while (0); \
  3851. emitter->buf->off += PTLS_HELLO_RANDOM_SIZE; \
  3852. ptls_buffer_push_block(emitter->buf, 1, \
  3853. { ptls_buffer_pushv(emitter->buf, ch->legacy_session_id.base, ch->legacy_session_id.len); }); \
  3854. ptls_buffer_push16(emitter->buf, tls->cipher_suite->id); \
  3855. ptls_buffer_push(emitter->buf, 0); \
  3856. ptls_buffer_push_block(emitter->buf, 2, { \
  3857. buffer_push_extension(emitter->buf, PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS, \
  3858. { ptls_buffer_push16(emitter->buf, ch->selected_version); }); \
  3859. do { \
  3860. extensions \
  3861. } while (0); \
  3862. }); \
  3863. }); \
  3864. do { \
  3865. post_action \
  3866. } while (0); \
  3867. ptls__key_schedule_update_hash((sched), emitter->buf->base + sh_start_off, emitter->buf->off - sh_start_off, 0); \
  3868. } while (0)
  3869. #define EMIT_HELLO_RETRY_REQUEST(sched, negotiated_group, additional_extensions, post_action) \
  3870. EMIT_SERVER_HELLO((sched), { memcpy(emitter->buf->base + emitter->buf->off, hello_retry_random, PTLS_HELLO_RANDOM_SIZE); }, \
  3871. { \
  3872. ptls_key_exchange_algorithm_t *_negotiated_group = (negotiated_group); \
  3873. if (_negotiated_group != NULL) { \
  3874. buffer_push_extension(emitter->buf, PTLS_EXTENSION_TYPE_KEY_SHARE, \
  3875. { ptls_buffer_push16(emitter->buf, _negotiated_group->id); }); \
  3876. } \
  3877. do { \
  3878. additional_extensions \
  3879. } while (0); \
  3880. }, \
  3881. post_action)
  3882. struct st_ptls_client_hello_t *ch;
  3883. struct {
  3884. ptls_key_exchange_algorithm_t *algorithm;
  3885. ptls_iovec_t peer_key;
  3886. } key_share = {NULL};
  3887. struct {
  3888. uint8_t *encoded_ch_inner;
  3889. uint8_t *ch_outer_aad;
  3890. ptls_buffer_t ch_inner;
  3891. } ech = {NULL};
  3892. enum { HANDSHAKE_MODE_FULL, HANDSHAKE_MODE_PSK, HANDSHAKE_MODE_PSK_DHE } mode;
  3893. size_t psk_index = SIZE_MAX;
  3894. ptls_iovec_t pubkey = {0}, ecdh_secret = {0};
  3895. int accept_early_data = 0, is_second_flight = tls->state == PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO, ret;
  3896. ptls_buffer_init(&ech.ch_inner, "", 0);
  3897. if ((ch = malloc(sizeof(*ch))) == NULL) {
  3898. ret = PTLS_ERROR_NO_MEMORY;
  3899. goto Exit;
  3900. }
  3901. *ch = (struct st_ptls_client_hello_t){.unknown_extensions = {{UINT16_MAX}}};
  3902. /* decode ClientHello */
  3903. if ((ret = decode_client_hello(tls->ctx, ch, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.base + message.len, properties,
  3904. tls)) != 0)
  3905. goto Exit;
  3906. if ((ret = check_client_hello_constraints(tls->ctx, ch, is_second_flight ? tls->client_random : NULL, 0, message, tls)) != 0)
  3907. goto Exit;
  3908. if (!is_second_flight) {
  3909. memcpy(tls->client_random, ch->random_bytes, PTLS_HELLO_RANDOM_SIZE);
  3910. log_client_random(tls);
  3911. } else {
  3912. /* consistency check for ECH extension in response to HRR */
  3913. if (tls->ech.aead != NULL) {
  3914. if (ch->ech.payload.base == NULL) {
  3915. ret = PTLS_ALERT_MISSING_EXTENSION;
  3916. goto Exit;
  3917. }
  3918. if (!(ch->ech.config_id == tls->ech.config_id && ch->ech.cipher_suite.kdf == tls->ech.cipher->id.kdf &&
  3919. ch->ech.cipher_suite.aead == tls->ech.cipher->id.aead && ch->ech.enc.len == 0)) {
  3920. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  3921. goto Exit;
  3922. }
  3923. }
  3924. }
  3925. /* ECH */
  3926. if (ch->ech.payload.base != NULL) {
  3927. if (ch->ech.type != PTLS_ECH_CLIENT_HELLO_TYPE_OUTER) {
  3928. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  3929. goto Exit;
  3930. }
  3931. if (!is_second_flight)
  3932. tls->ech.offered = 1;
  3933. /* obtain AEAD context for opening inner CH */
  3934. if (!is_second_flight && ch->ech.payload.base != NULL && tls->ctx->ech.server.create_opener != NULL) {
  3935. if ((tls->ech.aead = tls->ctx->ech.server.create_opener->cb(
  3936. tls->ctx->ech.server.create_opener, &tls->ech.kem, &tls->ech.cipher, tls, ch->ech.config_id,
  3937. ch->ech.cipher_suite, ch->ech.enc, ptls_iovec_init(ech_info_prefix, sizeof(ech_info_prefix)))) != NULL)
  3938. tls->ech.config_id = ch->ech.config_id;
  3939. }
  3940. if (!is_second_flight) {
  3941. PTLS_PROBE(ECH_SELECTION, tls, tls->ech.aead != NULL);
  3942. PTLS_LOG_CONN(ech_selection, tls, { PTLS_LOG_ELEMENT_BOOL(is_ech, tls->ech.aead != NULL); });
  3943. }
  3944. if (tls->ech.aead != NULL) {
  3945. /* now that AEAD context is available, create AAD and decrypt inner CH */
  3946. if ((ech.encoded_ch_inner = malloc(ch->ech.payload.len - tls->ech.aead->algo->tag_size)) == NULL ||
  3947. (ech.ch_outer_aad = malloc(message.len - PTLS_HANDSHAKE_HEADER_SIZE)) == NULL) {
  3948. ret = PTLS_ERROR_NO_MEMORY;
  3949. goto Exit;
  3950. }
  3951. memcpy(ech.ch_outer_aad, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.len - PTLS_HANDSHAKE_HEADER_SIZE);
  3952. memset(ech.ch_outer_aad + (ch->ech.payload.base - (message.base + PTLS_HANDSHAKE_HEADER_SIZE)), 0, ch->ech.payload.len);
  3953. if (ptls_aead_decrypt(tls->ech.aead, ech.encoded_ch_inner, ch->ech.payload.base, ch->ech.payload.len, is_second_flight,
  3954. ech.ch_outer_aad, message.len - PTLS_HANDSHAKE_HEADER_SIZE) != SIZE_MAX) {
  3955. tls->ech.accepted = 1;
  3956. /* successfully decrypted EncodedCHInner, build CHInner */
  3957. if ((ret = rebuild_ch_inner(&ech.ch_inner, ech.encoded_ch_inner,
  3958. ech.encoded_ch_inner + ch->ech.payload.len - tls->ech.aead->algo->tag_size, ch,
  3959. message.base + PTLS_HANDSHAKE_HEADER_SIZE + ch->first_extension_at,
  3960. message.base + message.len)) != 0)
  3961. goto Exit;
  3962. /* treat inner ch as the message being received, re-decode it */
  3963. message = ptls_iovec_init(ech.ch_inner.base, ech.ch_inner.off);
  3964. *ch = (struct st_ptls_client_hello_t){.unknown_extensions = {{UINT16_MAX}}};
  3965. if ((ret = decode_client_hello(tls->ctx, ch, ech.ch_inner.base + PTLS_HANDSHAKE_HEADER_SIZE,
  3966. ech.ch_inner.base + ech.ch_inner.off, properties, tls)) != 0)
  3967. goto Exit;
  3968. if ((ret = check_client_hello_constraints(tls->ctx, ch, is_second_flight ? tls->ech.inner_client_random : NULL, 1,
  3969. message, tls)) != 0)
  3970. goto Exit;
  3971. if (!is_second_flight)
  3972. memcpy(tls->ech.inner_client_random, ch->random_bytes, PTLS_HELLO_RANDOM_SIZE);
  3973. } else if (is_second_flight) {
  3974. /* decryption failure of inner CH in 2nd CH is fatal */
  3975. ret = PTLS_ALERT_DECRYPT_ERROR;
  3976. goto Exit;
  3977. } else {
  3978. /* decryption failure of 1st CH indicates key mismatch; dispose of AEAD context to indicate adoption of outerCH */
  3979. ptls_aead_free(tls->ech.aead);
  3980. tls->ech.aead = NULL;
  3981. }
  3982. }
  3983. } else if (tls->ech.offered) {
  3984. assert(is_second_flight);
  3985. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  3986. goto Exit;
  3987. }
  3988. if (tls->ctx->require_dhe_on_psk)
  3989. ch->psk.ke_modes &= ~(1u << PTLS_PSK_KE_MODE_PSK);
  3990. /* handle client_random, legacy_session_id, SNI, ESNI */
  3991. if (!is_second_flight) {
  3992. if (ch->legacy_session_id.len != 0)
  3993. tls->send_change_cipher_spec = 1;
  3994. ptls_iovec_t server_name = {NULL};
  3995. if (ch->server_name.base != NULL)
  3996. server_name = ch->server_name;
  3997. if ((ret = call_on_client_hello_cb(tls, server_name, message, ch->cipher_suites, ch->alpn.list, ch->alpn.count,
  3998. ch->signature_algorithms.list, ch->signature_algorithms.count,
  3999. ch->cert_compression_algos.list, ch->cert_compression_algos.count,
  4000. ch->server_certificate_types.list, ch->server_certificate_types.count,
  4001. ch->psk.identities.list, ch->psk.identities.count, 0)) != 0)
  4002. goto Exit;
  4003. if (!certificate_type_exists(ch->server_certificate_types.list, ch->server_certificate_types.count,
  4004. tls->ctx->use_raw_public_keys ? PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY
  4005. : PTLS_CERTIFICATE_TYPE_X509)) {
  4006. ret = PTLS_ALERT_UNSUPPORTED_CERTIFICATE;
  4007. goto Exit;
  4008. }
  4009. } else {
  4010. if (ch->psk.early_data_indication) {
  4011. ret = PTLS_ALERT_DECODE_ERROR;
  4012. goto Exit;
  4013. }
  4014. /* We compare SNI only when the value is saved by the on_client_hello callback. This should be OK because we are
  4015. * ignoring the value unless the callback saves the server-name. */
  4016. if (tls->server_name != NULL) {
  4017. size_t l = strlen(tls->server_name);
  4018. if (!(ch->server_name.len == l && memcmp(ch->server_name.base, tls->server_name, l) == 0)) {
  4019. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  4020. goto Exit;
  4021. }
  4022. }
  4023. }
  4024. { /* select (or check) cipher-suite, create key_schedule */
  4025. ptls_cipher_suite_t *cs;
  4026. if ((ret = select_cipher(&cs, tls->ctx->cipher_suites, ch->cipher_suites.base,
  4027. ch->cipher_suites.base + ch->cipher_suites.len, tls->ctx->server_cipher_preference,
  4028. tls->ctx->server_cipher_chacha_priority, tls->ctx->pre_shared_key.hash)) != 0)
  4029. goto Exit;
  4030. if (!is_second_flight) {
  4031. tls->cipher_suite = cs;
  4032. if ((tls->key_schedule = key_schedule_new(cs, NULL, 0)) == NULL) {
  4033. ret = PTLS_ERROR_NO_MEMORY;
  4034. goto Exit;
  4035. }
  4036. } else {
  4037. if (tls->cipher_suite != cs) {
  4038. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  4039. goto Exit;
  4040. }
  4041. }
  4042. }
  4043. /* select key_share */
  4044. if (key_share.algorithm == NULL && ch->key_shares.base != NULL && tls->ctx->key_exchanges != NULL) {
  4045. const uint8_t *src = ch->key_shares.base, *const end = src + ch->key_shares.len;
  4046. ptls_decode_block(src, end, 2, {
  4047. if ((ret = select_key_share(&key_share.algorithm, &key_share.peer_key, tls->ctx->key_exchanges, &src, end, 0)) != 0)
  4048. goto Exit;
  4049. });
  4050. }
  4051. if (!is_second_flight) {
  4052. if (ch->cookie.all.len != 0 && key_share.algorithm != NULL) {
  4053. { /* use cookie to check the integrity of the handshake, and update the context */
  4054. uint8_t sig[PTLS_MAX_DIGEST_SIZE];
  4055. size_t sigsize = tls->ctx->cipher_suites[0]->hash->digest_size;
  4056. if ((ret = calc_cookie_signature(tls, properties, key_share.algorithm, ch->cookie.tbs, sig)) != 0)
  4057. goto Exit;
  4058. if (!(ch->cookie.signature.len == sigsize && ptls_mem_equal(ch->cookie.signature.base, sig, sigsize))) {
  4059. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  4060. goto Exit;
  4061. }
  4062. }
  4063. /* integrity check passed; update states */
  4064. key_schedule_update_ch1hash_prefix(tls->key_schedule);
  4065. ptls__key_schedule_update_hash(tls->key_schedule, ch->cookie.ch1_hash.base, ch->cookie.ch1_hash.len, 0);
  4066. key_schedule_extract(tls->key_schedule,
  4067. tls->ctx->pre_shared_key.secret /* this argument will be a zero-length vector unless external PSK
  4068. is used, and that's fine; we never resume when sending HRR */);
  4069. /* ... reusing sendbuf to rebuild HRR for hash calculation */
  4070. size_t hrr_start = emitter->buf->off;
  4071. EMIT_HELLO_RETRY_REQUEST(tls->key_schedule, ch->cookie.sent_key_share ? key_share.algorithm : NULL,
  4072. {
  4073. buffer_push_extension(emitter->buf, PTLS_EXTENSION_TYPE_COOKIE, {
  4074. ptls_buffer_pushv(emitter->buf, ch->cookie.all.base, ch->cookie.all.len);
  4075. });
  4076. },
  4077. {});
  4078. emitter->buf->off = hrr_start;
  4079. is_second_flight = 1;
  4080. } else if (ch->key_shares.base != NULL && tls->ctx->key_exchanges != NULL &&
  4081. (key_share.algorithm == NULL || (properties != NULL && properties->server.enforce_retry))) {
  4082. /* send HelloRetryRequest, when trying to negotiate the key share but enforced by config or upon key-share mismatch */
  4083. if (ch->negotiated_groups.base == NULL) {
  4084. ret = PTLS_ALERT_MISSING_EXTENSION;
  4085. goto Exit;
  4086. }
  4087. ptls_key_exchange_algorithm_t *negotiated_group;
  4088. if ((ret = select_negotiated_group(&negotiated_group, tls->ctx->key_exchanges, ch->negotiated_groups.base,
  4089. ch->negotiated_groups.base + ch->negotiated_groups.len)) != 0)
  4090. goto Exit;
  4091. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  4092. assert(tls->key_schedule->generation == 0);
  4093. /* Either send a stateless retry (w. cookies) or a stateful one. When sending the latter, run the state machine. At the
  4094. * moment, stateless retry is disabled when ECH is used (do we need to support it?). */
  4095. int retry_uses_cookie =
  4096. properties != NULL && properties->server.retry_uses_cookie && !ptls_is_ech_handshake(tls, NULL, NULL, NULL);
  4097. if (!retry_uses_cookie) {
  4098. key_schedule_transform_post_ch1hash(tls->key_schedule);
  4099. key_schedule_extract(tls->key_schedule, tls->ctx->pre_shared_key.secret /* see comment above */);
  4100. }
  4101. size_t ech_confirm_off = 0;
  4102. EMIT_HELLO_RETRY_REQUEST(
  4103. tls->key_schedule, key_share.algorithm != NULL ? NULL : negotiated_group,
  4104. {
  4105. ptls_buffer_t *sendbuf = emitter->buf;
  4106. if (ptls_is_ech_handshake(tls, NULL, NULL, NULL)) {
  4107. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO, {
  4108. if ((ret = ptls_buffer_reserve(sendbuf, PTLS_ECH_CONFIRM_LENGTH)) != 0)
  4109. goto Exit;
  4110. memset(sendbuf->base + sendbuf->off, 0, PTLS_ECH_CONFIRM_LENGTH);
  4111. ech_confirm_off = sendbuf->off;
  4112. sendbuf->off += PTLS_ECH_CONFIRM_LENGTH;
  4113. });
  4114. }
  4115. if (retry_uses_cookie) {
  4116. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_COOKIE, {
  4117. ptls_buffer_push_block(sendbuf, 2, {
  4118. /* push to-be-signed data */
  4119. size_t tbs_start = sendbuf->off;
  4120. ptls_buffer_push_block(sendbuf, 2, {
  4121. /* first block of the cookie data is the hash(ch1) */
  4122. ptls_buffer_push_block(sendbuf, 1, {
  4123. size_t sz = tls->cipher_suite->hash->digest_size;
  4124. if ((ret = ptls_buffer_reserve(sendbuf, sz)) != 0)
  4125. goto Exit;
  4126. key_schedule_extract_ch1hash(tls->key_schedule, sendbuf->base + sendbuf->off);
  4127. sendbuf->off += sz;
  4128. });
  4129. /* second is if we have sent key_share extension */
  4130. ptls_buffer_push(sendbuf, key_share.algorithm == NULL);
  4131. /* we can add more data here */
  4132. });
  4133. size_t tbs_len = sendbuf->off - tbs_start;
  4134. /* push the signature */
  4135. ptls_buffer_push_block(sendbuf, 1, {
  4136. size_t sz = tls->ctx->cipher_suites[0]->hash->digest_size;
  4137. if ((ret = ptls_buffer_reserve(sendbuf, sz)) != 0)
  4138. goto Exit;
  4139. if ((ret = calc_cookie_signature(tls, properties, negotiated_group,
  4140. ptls_iovec_init(sendbuf->base + tbs_start, tbs_len),
  4141. sendbuf->base + sendbuf->off)) != 0)
  4142. goto Exit;
  4143. sendbuf->off += sz;
  4144. });
  4145. });
  4146. });
  4147. }
  4148. },
  4149. {
  4150. if (ech_confirm_off != 0 &&
  4151. (ret = ech_calc_confirmation(
  4152. tls->key_schedule, emitter->buf->base + ech_confirm_off, tls->ech.inner_client_random,
  4153. ECH_CONFIRMATION_HRR,
  4154. ptls_iovec_init(emitter->buf->base + sh_start_off, emitter->buf->off - sh_start_off))) != 0)
  4155. goto Exit;
  4156. });
  4157. if (retry_uses_cookie) {
  4158. if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
  4159. goto Exit;
  4160. ret = PTLS_ERROR_STATELESS_RETRY;
  4161. } else {
  4162. tls->state = PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO;
  4163. if (ch->psk.early_data_indication)
  4164. tls->server.early_data_skipped_bytes = 0;
  4165. ret = PTLS_ERROR_IN_PROGRESS;
  4166. }
  4167. goto Exit;
  4168. }
  4169. }
  4170. /* handle unknown extensions */
  4171. if ((ret = report_unknown_extensions(tls, properties, ch->unknown_extensions)) != 0)
  4172. goto Exit;
  4173. /* try psk handshake */
  4174. if (ch->psk.hash_end != 0 && (ch->psk.ke_modes & ((1u << PTLS_PSK_KE_MODE_PSK) | (1u << PTLS_PSK_KE_MODE_PSK_DHE))) != 0 &&
  4175. !tls->ctx->require_client_authentication &&
  4176. ((!is_second_flight && tls->ctx->encrypt_ticket != NULL) || tls->ctx->pre_shared_key.identity.base != NULL)) {
  4177. if ((ret = try_psk_handshake(tls, &psk_index, &accept_early_data, ch,
  4178. ptls_iovec_init(message.base, ch->psk.hash_end - message.base), is_second_flight)) != 0) {
  4179. goto Exit;
  4180. }
  4181. }
  4182. /* If the server was setup to use an external PSK but failed to agree, abort the handshake. Because external PSK is a form of
  4183. * mutual authentication, it makes sense to abort (at least as the default). */
  4184. if (tls->ctx->pre_shared_key.identity.base != NULL && psk_index == SIZE_MAX) {
  4185. ret = PTLS_ALERT_UNKNOWN_PSK_IDENTITY;
  4186. goto Exit;
  4187. }
  4188. /* If client authentication is enabled, we always force a full handshake.
  4189. * TODO: Check for `post_handshake_auth` extension and if that is present, do not force full handshake!
  4190. * Remove also the check `!require_client_authentication` above.
  4191. *
  4192. * adjust key_schedule, determine handshake mode
  4193. */
  4194. if (psk_index == SIZE_MAX || tls->ctx->require_client_authentication) {
  4195. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  4196. if (!is_second_flight) {
  4197. assert(tls->key_schedule->generation == 0);
  4198. key_schedule_extract(tls->key_schedule, ptls_iovec_init(NULL, 0));
  4199. }
  4200. mode = HANDSHAKE_MODE_FULL;
  4201. if (properties != NULL)
  4202. properties->server.selected_psk_binder.len = 0;
  4203. } else {
  4204. ptls__key_schedule_update_hash(tls->key_schedule, ch->psk.hash_end, message.base + message.len - ch->psk.hash_end, 0);
  4205. if ((ch->psk.ke_modes & (1u << PTLS_PSK_KE_MODE_PSK)) != 0) {
  4206. mode = HANDSHAKE_MODE_PSK;
  4207. } else {
  4208. assert((ch->psk.ke_modes & (1u << PTLS_PSK_KE_MODE_PSK_DHE)) != 0);
  4209. mode = HANDSHAKE_MODE_PSK_DHE;
  4210. }
  4211. tls->is_psk_handshake = 1;
  4212. if (properties != NULL) {
  4213. ptls_iovec_t *selected = &ch->psk.identities.list[psk_index].binder;
  4214. memcpy(properties->server.selected_psk_binder.base, selected->base, selected->len);
  4215. properties->server.selected_psk_binder.len = selected->len;
  4216. }
  4217. }
  4218. /* determine number of tickets to send */
  4219. if (ch->psk.ke_modes != 0 && tls->ctx->ticket_lifetime != 0) {
  4220. if (ch->ticket_request.new_session_count != 0) {
  4221. tls->server.num_tickets_to_send =
  4222. tls->is_psk_handshake ? ch->ticket_request.resumption_count : ch->ticket_request.new_session_count;
  4223. } else {
  4224. tls->server.num_tickets_to_send = 1;
  4225. }
  4226. uint8_t max_tickets = tls->ctx->ticket_requests.server.max_count;
  4227. if (max_tickets == 0)
  4228. max_tickets = PTLS_DEFAULT_MAX_TICKETS_TO_SERVE;
  4229. if (tls->server.num_tickets_to_send > max_tickets)
  4230. tls->server.num_tickets_to_send = max_tickets;
  4231. } else {
  4232. tls->server.num_tickets_to_send = 0;
  4233. }
  4234. if (accept_early_data && tls->ctx->max_early_data_size != 0 && psk_index == 0) {
  4235. if ((tls->pending_handshake_secret = malloc(PTLS_MAX_DIGEST_SIZE)) == NULL) {
  4236. ret = PTLS_ERROR_NO_MEMORY;
  4237. goto Exit;
  4238. }
  4239. if ((ret = derive_exporter_secret(tls, 1)) != 0)
  4240. goto Exit;
  4241. if ((ret = setup_traffic_protection(tls, 0, "c e traffic", 1, 0, 0)) != 0)
  4242. goto Exit;
  4243. }
  4244. /* run key-exchange, to obtain pubkey and secret */
  4245. if (mode != HANDSHAKE_MODE_PSK) {
  4246. if (key_share.algorithm == NULL) {
  4247. ret = ch->key_shares.base != NULL ? PTLS_ALERT_HANDSHAKE_FAILURE : PTLS_ALERT_MISSING_EXTENSION;
  4248. goto Exit;
  4249. }
  4250. if ((ret = key_share.algorithm->exchange(key_share.algorithm, &pubkey, &ecdh_secret, key_share.peer_key)) != 0) {
  4251. assert(pubkey.base == NULL);
  4252. assert(ecdh_secret.base == NULL);
  4253. goto Exit;
  4254. }
  4255. tls->key_share = key_share.algorithm;
  4256. }
  4257. { /* send ServerHello */
  4258. size_t ech_confirm_off = 0;
  4259. EMIT_SERVER_HELLO(
  4260. tls->key_schedule,
  4261. {
  4262. tls->ctx->random_bytes(emitter->buf->base + emitter->buf->off, PTLS_HELLO_RANDOM_SIZE);
  4263. /* when accepting CHInner, last 8 byte of SH.random is zero for the handshake transcript */
  4264. if (ptls_is_ech_handshake(tls, NULL, NULL, NULL)) {
  4265. ech_confirm_off = emitter->buf->off + PTLS_HELLO_RANDOM_SIZE - PTLS_ECH_CONFIRM_LENGTH;
  4266. memset(emitter->buf->base + ech_confirm_off, 0, PTLS_ECH_CONFIRM_LENGTH);
  4267. }
  4268. },
  4269. {
  4270. ptls_buffer_t *sendbuf = emitter->buf;
  4271. if (mode != HANDSHAKE_MODE_PSK) {
  4272. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_KEY_SHARE, {
  4273. ptls_buffer_push16(sendbuf, key_share.algorithm->id);
  4274. ptls_buffer_push_block(sendbuf, 2, { ptls_buffer_pushv(sendbuf, pubkey.base, pubkey.len); });
  4275. });
  4276. }
  4277. if (mode != HANDSHAKE_MODE_FULL) {
  4278. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_PRE_SHARED_KEY,
  4279. { ptls_buffer_push16(sendbuf, (uint16_t)psk_index); });
  4280. }
  4281. },
  4282. {
  4283. if (ech_confirm_off != 0 &&
  4284. (ret = ech_calc_confirmation(
  4285. tls->key_schedule, emitter->buf->base + ech_confirm_off, tls->ech.inner_client_random,
  4286. ECH_CONFIRMATION_SERVER_HELLO,
  4287. ptls_iovec_init(emitter->buf->base + sh_start_off, emitter->buf->off - sh_start_off))) != 0)
  4288. goto Exit;
  4289. });
  4290. }
  4291. /* processing of ECH is complete; dispose state */
  4292. clear_ech(&tls->ech, 1);
  4293. if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
  4294. goto Exit;
  4295. /* create protection contexts for the handshake */
  4296. assert(tls->key_schedule->generation == 1);
  4297. key_schedule_extract(tls->key_schedule, ecdh_secret);
  4298. if ((ret = setup_traffic_protection(tls, 1, "s hs traffic", 2, 0, 0)) != 0)
  4299. goto Exit;
  4300. if (tls->pending_handshake_secret != NULL) {
  4301. if ((ret = derive_secret(tls->key_schedule, tls->pending_handshake_secret, "c hs traffic")) != 0)
  4302. goto Exit;
  4303. if (tls->ctx->update_traffic_key != NULL &&
  4304. (ret = tls->ctx->update_traffic_key->cb(tls->ctx->update_traffic_key, tls, 0, 2, tls->pending_handshake_secret)) != 0)
  4305. goto Exit;
  4306. } else {
  4307. if ((ret = setup_traffic_protection(tls, 0, "c hs traffic", 2, 0, 0)) != 0)
  4308. goto Exit;
  4309. if (ch->psk.early_data_indication)
  4310. tls->server.early_data_skipped_bytes = 0;
  4311. }
  4312. /* send EncryptedExtensions */
  4313. ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS, {
  4314. ptls_buffer_t *sendbuf = emitter->buf;
  4315. ptls_buffer_push_block(sendbuf, 2, {
  4316. if (tls->server_name != NULL) {
  4317. /* In this event, the server SHALL include an extension of type "server_name" in the (extended) server hello.
  4318. * The "extension_data" field of this extension SHALL be empty. (RFC 6066 section 3) */
  4319. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_NAME, {});
  4320. }
  4321. if (tls->ctx->use_raw_public_keys) {
  4322. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE,
  4323. { ptls_buffer_push(sendbuf, PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY); });
  4324. }
  4325. if (tls->negotiated_protocol != NULL) {
  4326. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ALPN, {
  4327. ptls_buffer_push_block(sendbuf, 2, {
  4328. ptls_buffer_push_block(sendbuf, 1, {
  4329. ptls_buffer_pushv(sendbuf, tls->negotiated_protocol, strlen(tls->negotiated_protocol));
  4330. });
  4331. });
  4332. });
  4333. }
  4334. if (tls->pending_handshake_secret != NULL)
  4335. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_EARLY_DATA, {});
  4336. /* send ECH retry_configs, if ECH was offered by rejected, even though we (the server) could have accepted ECH */
  4337. if (tls->ech.offered && !ptls_is_ech_handshake(tls, NULL, NULL, NULL) && tls->ctx->ech.server.create_opener != NULL &&
  4338. tls->ctx->ech.server.retry_configs.len != 0)
  4339. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO, {
  4340. ptls_buffer_pushv(sendbuf, tls->ctx->ech.server.retry_configs.base, tls->ctx->ech.server.retry_configs.len);
  4341. });
  4342. if (ch->ticket_request.new_session_count != 0 && tls->server.num_tickets_to_send != 0)
  4343. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_TICKET_REQUEST,
  4344. { ptls_buffer_push(sendbuf, tls->server.num_tickets_to_send); });
  4345. if ((ret = push_additional_extensions(properties, sendbuf)) != 0)
  4346. goto Exit;
  4347. });
  4348. });
  4349. if (mode == HANDSHAKE_MODE_FULL) {
  4350. /* send certificate request if client authentication is activated */
  4351. if (tls->ctx->require_client_authentication) {
  4352. ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST, {
  4353. ptls_buffer_t *sendbuf = emitter->buf;
  4354. /* certificate_request_context: this field SHALL be zero length, unless the certificate request is used for post-
  4355. * handshake authentication. */
  4356. ptls_buffer_push(sendbuf, 0);
  4357. /* extensions */
  4358. ptls_buffer_push_block(sendbuf, 2, {
  4359. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS, {
  4360. if ((ret = push_signature_algorithms(tls->ctx->verify_certificate, sendbuf)) != 0)
  4361. goto Exit;
  4362. });
  4363. /* certificate authorities entension */
  4364. if (tls->ctx->client_ca_names.count > 0) {
  4365. buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_CERTIFICATE_AUTHORITIES, {
  4366. ptls_buffer_push_block(sendbuf, 2, {
  4367. for (size_t i = 0; i != tls->ctx->client_ca_names.count; ++i) {
  4368. ptls_buffer_push_block(sendbuf, 2, {
  4369. ptls_iovec_t name = tls->ctx->client_ca_names.list[i];
  4370. ptls_buffer_pushv(sendbuf, name.base, name.len);
  4371. });
  4372. }
  4373. });
  4374. });
  4375. }
  4376. });
  4377. });
  4378. if (ret != 0) {
  4379. goto Exit;
  4380. }
  4381. }
  4382. /* send certificate */
  4383. if ((ret = send_certificate(tls, emitter, &ch->signature_algorithms, ptls_iovec_init(NULL, 0), ch->status_request,
  4384. ch->cert_compression_algos.list, ch->cert_compression_algos.count)) != 0)
  4385. goto Exit;
  4386. /* send certificateverify, finished, and complete the handshake */
  4387. if ((ret = server_finish_handshake(tls, emitter, 1, &ch->signature_algorithms)) != 0)
  4388. goto Exit;
  4389. } else {
  4390. /* send finished, and complete the handshake */
  4391. if ((ret = server_finish_handshake(tls, emitter, 0, NULL)) != 0)
  4392. goto Exit;
  4393. }
  4394. Exit:
  4395. free(pubkey.base);
  4396. if (ecdh_secret.base != NULL) {
  4397. ptls_clear_memory(ecdh_secret.base, ecdh_secret.len);
  4398. free(ecdh_secret.base);
  4399. }
  4400. free(ech.encoded_ch_inner);
  4401. free(ech.ch_outer_aad);
  4402. ptls_buffer_dispose(&ech.ch_inner);
  4403. free(ch);
  4404. return ret;
  4405. #undef EMIT_SERVER_HELLO
  4406. #undef EMIT_HELLO_RETRY_REQUEST
  4407. }
  4408. static int server_finish_handshake(ptls_t *tls, ptls_message_emitter_t *emitter, int send_cert_verify,
  4409. struct st_ptls_signature_algorithms_t *signature_algorithms)
  4410. {
  4411. int ret;
  4412. if (send_cert_verify) {
  4413. if ((ret = send_certificate_verify(tls, emitter, signature_algorithms, PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING)) !=
  4414. 0) {
  4415. if (ret == PTLS_ERROR_ASYNC_OPERATION) {
  4416. tls->state = PTLS_STATE_SERVER_GENERATING_CERTIFICATE_VERIFY;
  4417. }
  4418. goto Exit;
  4419. }
  4420. }
  4421. if ((ret = send_finished(tls, emitter)) != 0)
  4422. goto Exit;
  4423. assert(tls->key_schedule->generation == 2);
  4424. if ((ret = key_schedule_extract(tls->key_schedule, ptls_iovec_init(NULL, 0))) != 0)
  4425. goto Exit;
  4426. if ((ret = setup_traffic_protection(tls, 1, "s ap traffic", 3, 0, 0)) != 0)
  4427. goto Exit;
  4428. if ((ret = derive_secret(tls->key_schedule, tls->server.pending_traffic_secret, "c ap traffic")) != 0)
  4429. goto Exit;
  4430. if ((ret = derive_exporter_secret(tls, 0)) != 0)
  4431. goto Exit;
  4432. if (tls->pending_handshake_secret != NULL) {
  4433. if (tls->ctx->omit_end_of_early_data) {
  4434. if ((ret = commission_handshake_secret(tls)) != 0)
  4435. goto Exit;
  4436. tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
  4437. } else {
  4438. tls->state = PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA;
  4439. }
  4440. } else if (tls->ctx->require_client_authentication) {
  4441. tls->state = PTLS_STATE_SERVER_EXPECT_CERTIFICATE;
  4442. } else {
  4443. tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
  4444. }
  4445. /* send session ticket if necessary */
  4446. if (tls->server.num_tickets_to_send != 0) {
  4447. assert(tls->ctx->ticket_lifetime != 0);
  4448. for (uint8_t i = 0; i < tls->server.num_tickets_to_send; ++i)
  4449. if ((ret = send_session_ticket(tls, emitter)) != 0)
  4450. goto Exit;
  4451. }
  4452. if (tls->ctx->require_client_authentication) {
  4453. ret = PTLS_ERROR_IN_PROGRESS;
  4454. } else {
  4455. ret = 0;
  4456. }
  4457. Exit:
  4458. return ret;
  4459. }
  4460. static int server_handle_end_of_early_data(ptls_t *tls, ptls_iovec_t message)
  4461. {
  4462. int ret;
  4463. if ((ret = commission_handshake_secret(tls)) != 0)
  4464. goto Exit;
  4465. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  4466. tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
  4467. ret = PTLS_ERROR_IN_PROGRESS;
  4468. Exit:
  4469. return ret;
  4470. }
  4471. static int server_handle_finished(ptls_t *tls, ptls_iovec_t message)
  4472. {
  4473. int ret;
  4474. if ((ret = verify_finished(tls, message)) != 0)
  4475. return ret;
  4476. memcpy(tls->traffic_protection.dec.secret, tls->server.pending_traffic_secret, sizeof(tls->server.pending_traffic_secret));
  4477. ptls_clear_memory(tls->server.pending_traffic_secret, sizeof(tls->server.pending_traffic_secret));
  4478. if ((ret = setup_traffic_protection(tls, 0, NULL, 3, 0, 0)) != 0)
  4479. return ret;
  4480. ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
  4481. tls->state = PTLS_STATE_SERVER_POST_HANDSHAKE;
  4482. return 0;
  4483. }
  4484. static int update_traffic_key(ptls_t *tls, int is_enc)
  4485. {
  4486. struct st_ptls_traffic_protection_t *tp = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
  4487. uint8_t secret[PTLS_MAX_DIGEST_SIZE];
  4488. int ret;
  4489. ptls_hash_algorithm_t *hash = tls->key_schedule->hashes[0].algo;
  4490. if ((ret = ptls_hkdf_expand_label(hash, secret, hash->digest_size, ptls_iovec_init(tp->secret, hash->digest_size),
  4491. "traffic upd", ptls_iovec_init(NULL, 0), NULL)) != 0)
  4492. goto Exit;
  4493. memcpy(tp->secret, secret, sizeof(secret));
  4494. ret = setup_traffic_protection(tls, is_enc, NULL, 3, 0, 1);
  4495. Exit:
  4496. ptls_clear_memory(secret, sizeof(secret));
  4497. return ret;
  4498. }
  4499. static int handle_key_update(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message)
  4500. {
  4501. const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
  4502. int ret;
  4503. /* validate */
  4504. if (end - src != 1 || *src > 1)
  4505. return PTLS_ALERT_DECODE_ERROR;
  4506. /* update receive key */
  4507. if ((ret = update_traffic_key(tls, 0)) != 0)
  4508. return ret;
  4509. if (*src) {
  4510. if (tls->ctx->update_traffic_key != NULL)
  4511. return PTLS_ALERT_UNEXPECTED_MESSAGE;
  4512. tls->needs_key_update = 1;
  4513. }
  4514. return 0;
  4515. }
  4516. static int parse_record_header(struct st_ptls_record_t *rec, const uint8_t *src)
  4517. {
  4518. rec->type = src[0];
  4519. rec->version = ntoh16(src + 1);
  4520. rec->length = ntoh16(src + 3);
  4521. if (rec->length >
  4522. (size_t)(rec->type == PTLS_CONTENT_TYPE_APPDATA ? PTLS_MAX_ENCRYPTED_RECORD_SIZE : PTLS_MAX_PLAINTEXT_RECORD_SIZE))
  4523. return PTLS_ALERT_DECODE_ERROR;
  4524. return 0;
  4525. }
  4526. static int parse_record(ptls_t *tls, struct st_ptls_record_t *rec, const uint8_t *src, size_t *len)
  4527. {
  4528. int ret;
  4529. assert(*len != 0);
  4530. /* Check if the first byte is something that we can handle, otherwise do not bother parsing / buffering the entire record as it
  4531. * is obviously broken. SSL 2.0 handshakes fall into this path as well. */
  4532. if (tls->recvbuf.rec.base == NULL) {
  4533. uint8_t type = src[0];
  4534. switch (type) {
  4535. case PTLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC:
  4536. case PTLS_CONTENT_TYPE_ALERT:
  4537. case PTLS_CONTENT_TYPE_HANDSHAKE:
  4538. case PTLS_CONTENT_TYPE_APPDATA:
  4539. break;
  4540. default:
  4541. return PTLS_ALERT_DECODE_ERROR;
  4542. }
  4543. }
  4544. if (tls->recvbuf.rec.base == NULL && *len >= 5) {
  4545. /* fast path */
  4546. if ((ret = parse_record_header(rec, src)) != 0)
  4547. return ret;
  4548. if (5 + rec->length <= *len) {
  4549. rec->fragment = src + 5;
  4550. *len = rec->length + 5;
  4551. return 0;
  4552. }
  4553. }
  4554. /* slow path */
  4555. const uint8_t *const end = src + *len;
  4556. *rec = (struct st_ptls_record_t){0};
  4557. if (tls->recvbuf.rec.base == NULL) {
  4558. ptls_buffer_init(&tls->recvbuf.rec, "", 0);
  4559. if ((ret = ptls_buffer_reserve(&tls->recvbuf.rec, 5)) != 0)
  4560. return ret;
  4561. }
  4562. /* fill and parse the header */
  4563. while (tls->recvbuf.rec.off < 5) {
  4564. if (src == end)
  4565. return PTLS_ERROR_IN_PROGRESS;
  4566. tls->recvbuf.rec.base[tls->recvbuf.rec.off++] = *src++;
  4567. }
  4568. if ((ret = parse_record_header(rec, tls->recvbuf.rec.base)) != 0)
  4569. return ret;
  4570. /* fill the fragment */
  4571. size_t addlen = rec->length + 5 - tls->recvbuf.rec.off;
  4572. if (addlen != 0) {
  4573. if ((ret = ptls_buffer_reserve(&tls->recvbuf.rec, addlen)) != 0)
  4574. return ret;
  4575. if (addlen > (size_t)(end - src))
  4576. addlen = end - src;
  4577. if (addlen != 0) {
  4578. memcpy(tls->recvbuf.rec.base + tls->recvbuf.rec.off, src, addlen);
  4579. tls->recvbuf.rec.off += addlen;
  4580. src += addlen;
  4581. }
  4582. }
  4583. /* set rec->fragment if a complete record has been parsed */
  4584. if (tls->recvbuf.rec.off == rec->length + 5) {
  4585. rec->fragment = tls->recvbuf.rec.base + 5;
  4586. ret = 0;
  4587. } else {
  4588. ret = PTLS_ERROR_IN_PROGRESS;
  4589. }
  4590. *len -= end - src;
  4591. return ret;
  4592. }
  4593. static void update_open_count(ptls_context_t *ctx, ssize_t delta)
  4594. {
  4595. if (ctx->update_open_count != NULL)
  4596. ctx->update_open_count->cb(ctx->update_open_count, delta);
  4597. }
  4598. static ptls_t *new_instance(ptls_context_t *ctx, int is_server)
  4599. {
  4600. ptls_t *tls;
  4601. /* check consistency of `ptls_context_t` before instantiating a connection object */
  4602. assert(ctx->get_time != NULL && "please set ctx->get_time to `&ptls_get_time`; see #92");
  4603. if (ctx->pre_shared_key.identity.base != NULL) {
  4604. assert(ctx->pre_shared_key.identity.len != 0 && ctx->pre_shared_key.secret.base != NULL &&
  4605. ctx->pre_shared_key.secret.len != 0 && ctx->pre_shared_key.hash != NULL &&
  4606. "`ptls_context_t::pre_shared_key` in incosistent state");
  4607. } else {
  4608. assert(ctx->pre_shared_key.identity.len == 0 && ctx->pre_shared_key.secret.base == NULL &&
  4609. ctx->pre_shared_key.secret.len == 0 && ctx->pre_shared_key.hash == NULL &&
  4610. "`ptls_context_t::pre_shared_key` in inconsitent state");
  4611. }
  4612. if ((tls = malloc(sizeof(*tls))) == NULL)
  4613. return NULL;
  4614. update_open_count(ctx, 1);
  4615. *tls = (ptls_t){ctx};
  4616. tls->is_server = is_server;
  4617. tls->send_change_cipher_spec = ctx->send_change_cipher_spec;
  4618. #if PTLS_HAVE_LOG
  4619. if (ptls_log_conn_state_override != NULL) {
  4620. tls->log_state = *ptls_log_conn_state_override;
  4621. } else {
  4622. ptls_log_init_conn_state(&tls->log_state, ctx->random_bytes);
  4623. }
  4624. #endif
  4625. return tls;
  4626. }
  4627. ptls_t *ptls_client_new(ptls_context_t *ctx)
  4628. {
  4629. ptls_t *tls = new_instance(ctx, 0);
  4630. tls->state = PTLS_STATE_CLIENT_HANDSHAKE_START;
  4631. tls->ctx->random_bytes(tls->client_random, sizeof(tls->client_random));
  4632. log_client_random(tls);
  4633. if (tls->send_change_cipher_spec) {
  4634. tls->client.legacy_session_id =
  4635. ptls_iovec_init(tls->client.legacy_session_id_buf, sizeof(tls->client.legacy_session_id_buf));
  4636. tls->ctx->random_bytes(tls->client.legacy_session_id.base, tls->client.legacy_session_id.len);
  4637. }
  4638. PTLS_PROBE(NEW, tls, 0);
  4639. PTLS_LOG_CONN(new, tls, { PTLS_LOG_ELEMENT_BOOL(is_server, 0); });
  4640. return tls;
  4641. }
  4642. ptls_t *ptls_server_new(ptls_context_t *ctx)
  4643. {
  4644. ptls_t *tls = new_instance(ctx, 1);
  4645. tls->state = PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO;
  4646. tls->server.early_data_skipped_bytes = UINT32_MAX;
  4647. PTLS_PROBE(NEW, tls, 1);
  4648. PTLS_LOG_CONN(new, tls, { PTLS_LOG_ELEMENT_BOOL(is_server, 1); });
  4649. return tls;
  4650. }
  4651. #define export_tls_params(output, is_server, session_reused, protocol_version, cipher, client_random, server_name, \
  4652. negotiated_protocol, ver_block) \
  4653. do { \
  4654. const char *_server_name = (server_name); \
  4655. ptls_iovec_t _negotiated_protocol = (negotiated_protocol); \
  4656. ptls_buffer_push_block((output), 2, { \
  4657. ptls_buffer_push((output), (is_server)); \
  4658. ptls_buffer_push((output), (session_reused)); \
  4659. ptls_buffer_push16((output), (protocol_version)); \
  4660. ptls_buffer_push16((output), (cipher)->id); \
  4661. ptls_buffer_pushv((output), (client_random), PTLS_HELLO_RANDOM_SIZE); \
  4662. ptls_buffer_push_block((output), 2, { \
  4663. size_t len = _server_name != NULL ? strlen(_server_name) : 0; \
  4664. ptls_buffer_pushv((output), _server_name, len); \
  4665. }); \
  4666. ptls_buffer_push_block((output), 2, \
  4667. { ptls_buffer_pushv((output), _negotiated_protocol.base, _negotiated_protocol.len); }); \
  4668. ptls_buffer_push_block((output), 2, {ver_block}); /* version-specific block */ \
  4669. ptls_buffer_push_block((output), 2, {}); /* for future extensions */ \
  4670. }); \
  4671. } while (0)
  4672. static int export_tls12_params(ptls_buffer_t *output, int is_server, int session_reused, ptls_cipher_suite_t *cipher,
  4673. const void *client_random, const char *server_name, ptls_iovec_t negotiated_protocol,
  4674. const void *enc_key, const void *enc_iv, uint64_t enc_seq, uint64_t enc_record_iv,
  4675. const void *dec_key, const void *dec_iv, uint64_t dec_seq)
  4676. {
  4677. int ret;
  4678. export_tls_params(output, is_server, session_reused, PTLS_PROTOCOL_VERSION_TLS12, cipher, client_random, server_name,
  4679. negotiated_protocol, {
  4680. ptls_buffer_pushv(output, enc_key, cipher->aead->key_size);
  4681. ptls_buffer_pushv(output, enc_iv, cipher->aead->tls12.fixed_iv_size);
  4682. ptls_buffer_push64(output, enc_seq);
  4683. if (cipher->aead->tls12.record_iv_size != 0)
  4684. ptls_buffer_push64(output, enc_record_iv);
  4685. ptls_buffer_pushv(output, dec_key, cipher->aead->key_size);
  4686. ptls_buffer_pushv(output, dec_iv, cipher->aead->tls12.fixed_iv_size);
  4687. ptls_buffer_push64(output, dec_seq);
  4688. });
  4689. ret = 0;
  4690. Exit:
  4691. return ret;
  4692. }
  4693. int ptls_build_tls12_export_params(ptls_context_t *ctx, ptls_buffer_t *output, int is_server, int session_reused,
  4694. ptls_cipher_suite_t *cipher, const void *master_secret, const void *hello_randoms,
  4695. uint64_t next_send_record_iv, const char *server_name, ptls_iovec_t negotiated_protocol)
  4696. {
  4697. assert(cipher->aead->tls12.fixed_iv_size + cipher->aead->tls12.record_iv_size != 0 || !"given cipher-suite supports TLS/1.2");
  4698. uint8_t key_block[(PTLS_MAX_SECRET_SIZE + PTLS_MAX_IV_SIZE) * 2];
  4699. size_t key_block_len = (cipher->aead->key_size + cipher->aead->tls12.fixed_iv_size) * 2;
  4700. int ret;
  4701. assert(key_block_len <= sizeof(key_block));
  4702. /* generate key block */
  4703. if ((ret =
  4704. ptls_tls12_phash(cipher->hash, key_block, key_block_len, ptls_iovec_init(master_secret, PTLS_TLS12_MASTER_SECRET_SIZE),
  4705. "key expansion", ptls_iovec_init(hello_randoms, PTLS_HELLO_RANDOM_SIZE * 2))) != 0)
  4706. goto Exit;
  4707. /* determine key locations */
  4708. struct {
  4709. const void *key;
  4710. const void *iv;
  4711. } client_secret, server_secret, *enc_secret = is_server ? &server_secret : &client_secret,
  4712. *dec_secret = is_server ? &client_secret : &server_secret;
  4713. client_secret.key = key_block;
  4714. server_secret.key = key_block + cipher->aead->key_size;
  4715. client_secret.iv = key_block + cipher->aead->key_size * 2;
  4716. server_secret.iv = key_block + cipher->aead->key_size * 2 + cipher->aead->tls12.fixed_iv_size;
  4717. /* Serialize prams. Sequence number of the first application record is 1, because Finished is the only message sent after
  4718. * ChangeCipherSpec. */
  4719. ret = export_tls12_params(output, is_server, session_reused, cipher, (uint8_t *)hello_randoms + PTLS_HELLO_RANDOM_SIZE,
  4720. server_name, negotiated_protocol, enc_secret->key, enc_secret->iv, 1, next_send_record_iv,
  4721. dec_secret->key, dec_secret->iv, 1);
  4722. Exit:
  4723. ptls_clear_memory(key_block, sizeof(key_block));
  4724. return ret;
  4725. }
  4726. int ptls_export(ptls_t *tls, ptls_buffer_t *output)
  4727. {
  4728. ptls_iovec_t negotiated_protocol =
  4729. ptls_iovec_init(tls->negotiated_protocol, tls->negotiated_protocol != NULL ? strlen(tls->negotiated_protocol) : 0);
  4730. int ret;
  4731. if (tls->state != PTLS_STATE_SERVER_POST_HANDSHAKE) {
  4732. ret = PTLS_ERROR_LIBRARY;
  4733. goto Exit;
  4734. }
  4735. if (ptls_get_protocol_version(tls) == PTLS_PROTOCOL_VERSION_TLS13) {
  4736. export_tls_params(output, tls->is_server, tls->is_psk_handshake, PTLS_PROTOCOL_VERSION_TLS13, tls->cipher_suite,
  4737. tls->client_random, tls->server_name, negotiated_protocol, {
  4738. ptls_buffer_pushv(output, tls->traffic_protection.enc.secret, tls->cipher_suite->hash->digest_size);
  4739. ptls_buffer_push64(output, tls->traffic_protection.enc.seq);
  4740. ptls_buffer_pushv(output, tls->traffic_protection.dec.secret, tls->cipher_suite->hash->digest_size);
  4741. ptls_buffer_push64(output, tls->traffic_protection.dec.seq);
  4742. });
  4743. ret = 0;
  4744. } else {
  4745. if ((ret = export_tls12_params(output, tls->is_server, tls->is_psk_handshake, tls->cipher_suite, tls->client_random,
  4746. tls->server_name, negotiated_protocol, tls->traffic_protection.enc.secret,
  4747. tls->traffic_protection.enc.secret + PTLS_MAX_SECRET_SIZE, tls->traffic_protection.enc.seq,
  4748. tls->traffic_protection.enc.tls12_enc_record_iv, tls->traffic_protection.dec.secret,
  4749. tls->traffic_protection.dec.secret + PTLS_MAX_SECRET_SIZE,
  4750. tls->traffic_protection.dec.seq)) != 0)
  4751. goto Exit;
  4752. }
  4753. Exit:
  4754. return ret;
  4755. }
  4756. static int import_tls12_traffic_protection(ptls_t *tls, int is_enc, const uint8_t **src, const uint8_t *const end)
  4757. {
  4758. struct st_ptls_traffic_protection_t *tp = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
  4759. if ((size_t)(end - *src) < tls->cipher_suite->aead->key_size + tls->cipher_suite->aead->tls12.fixed_iv_size + sizeof(uint64_t))
  4760. return PTLS_ALERT_DECODE_ERROR;
  4761. /* set properties */
  4762. memcpy(tp->secret, *src, tls->cipher_suite->aead->key_size);
  4763. *src += tls->cipher_suite->aead->key_size;
  4764. memcpy(tp->secret + PTLS_MAX_SECRET_SIZE, *src, tls->cipher_suite->aead->tls12.fixed_iv_size);
  4765. *src += tls->cipher_suite->aead->tls12.fixed_iv_size;
  4766. if (ptls_decode64(&tp->seq, src, end) != 0)
  4767. return PTLS_ALERT_DECODE_ERROR;
  4768. if (is_enc && tls->cipher_suite->aead->tls12.record_iv_size != 0) {
  4769. if (ptls_decode64(&tp->tls12_enc_record_iv, src, end) != 0)
  4770. return PTLS_ALERT_DECODE_ERROR;
  4771. }
  4772. tp->tls12 = 1;
  4773. /* instantiate aead */
  4774. if ((tp->aead = ptls_aead_new_direct(tls->cipher_suite->aead, is_enc, tp->secret, tp->secret + PTLS_MAX_SECRET_SIZE)) == NULL)
  4775. return PTLS_ERROR_NO_MEMORY;
  4776. return 0;
  4777. }
  4778. static int import_tls13_traffic_protection(ptls_t *tls, int is_enc, const uint8_t **src, const uint8_t *const end)
  4779. {
  4780. struct st_ptls_traffic_protection_t *tp = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
  4781. /* set properties */
  4782. memcpy(tp->secret, *src, tls->cipher_suite->hash->digest_size);
  4783. *src += tls->cipher_suite->hash->digest_size;
  4784. if (ptls_decode64(&tp->seq, src, end) != 0)
  4785. return PTLS_ALERT_DECODE_ERROR;
  4786. if (setup_traffic_protection(tls, is_enc, NULL, 3, tp->seq, 0) != 0)
  4787. return PTLS_ERROR_INCOMPATIBLE_KEY;
  4788. return 0;
  4789. }
  4790. int ptls_import(ptls_context_t *ctx, ptls_t **tls, ptls_iovec_t params)
  4791. {
  4792. const uint8_t *src = params.base, *const end = src + params.len;
  4793. uint16_t protocol_version, csid;
  4794. int ret;
  4795. *tls = NULL;
  4796. /* TODO handle flags like psk_handshake, ech_handshake as we add support for TLS/1.3 import */
  4797. ptls_decode_block(src, end, 2, {
  4798. /* instantiate, based on the is_server flag */
  4799. if (end - src < 2) {
  4800. ret = PTLS_ALERT_DECODE_ERROR;
  4801. goto Exit;
  4802. }
  4803. if ((*tls = new_instance(ctx, *src++)) == NULL) {
  4804. ret = PTLS_ERROR_NO_MEMORY;
  4805. goto Exit;
  4806. }
  4807. (*tls)->is_psk_handshake = *src++;
  4808. /* determine protocol version and cipher suite */
  4809. if ((ret = ptls_decode16(&protocol_version, &src, end)) != 0)
  4810. goto Exit;
  4811. if ((ret = ptls_decode16(&csid, &src, end)) != 0)
  4812. goto Exit;
  4813. /* other version-independent stuff */
  4814. if (end - src < PTLS_HELLO_RANDOM_SIZE) {
  4815. ret = PTLS_ALERT_DECODE_ERROR;
  4816. goto Exit;
  4817. }
  4818. memcpy((*tls)->client_random, src, PTLS_HELLO_RANDOM_SIZE);
  4819. src += PTLS_HELLO_RANDOM_SIZE;
  4820. ptls_decode_open_block(src, end, 2, {
  4821. if (src != end) {
  4822. if ((ret = ptls_set_server_name(*tls, (const char *)src, end - src)) != 0)
  4823. goto Exit;
  4824. src = end;
  4825. }
  4826. });
  4827. ptls_decode_open_block(src, end, 2, {
  4828. if (src != end) {
  4829. if ((ret = ptls_set_negotiated_protocol(*tls, (const char *)src, end - src)) != 0)
  4830. goto Exit;
  4831. src = end;
  4832. }
  4833. });
  4834. /* version-dependent stuff */
  4835. ptls_decode_open_block(src, end, 2, {
  4836. switch (protocol_version) {
  4837. case PTLS_PROTOCOL_VERSION_TLS12:
  4838. (*tls)->cipher_suite = ptls_find_cipher_suite(ctx->tls12_cipher_suites, csid);
  4839. if ((*tls)->cipher_suite == NULL) {
  4840. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  4841. goto Exit;
  4842. }
  4843. /* setup AEAD keys */
  4844. if ((ret = import_tls12_traffic_protection(*tls, 1, &src, end)) != 0)
  4845. goto Exit;
  4846. if ((ret = import_tls12_traffic_protection(*tls, 0, &src, end)) != 0)
  4847. goto Exit;
  4848. break;
  4849. case PTLS_PROTOCOL_VERSION_TLS13:
  4850. (*tls)->cipher_suite = ptls_find_cipher_suite(ctx->cipher_suites, csid);
  4851. if ((*tls)->cipher_suite == NULL) {
  4852. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  4853. goto Exit;
  4854. }
  4855. /* setup AEAD keys */
  4856. if (((*tls)->key_schedule = key_schedule_new((*tls)->cipher_suite, NULL, (*tls)->ech.aead != NULL)) == NULL) {
  4857. ret = PTLS_ERROR_NO_MEMORY;
  4858. goto Exit;
  4859. }
  4860. if ((ret = import_tls13_traffic_protection(*tls, 1, &src, end)) != 0)
  4861. goto Exit;
  4862. if ((ret = import_tls13_traffic_protection(*tls, 0, &src, end)) != 0)
  4863. goto Exit;
  4864. break;
  4865. default:
  4866. ret = PTLS_ALERT_ILLEGAL_PARAMETER;
  4867. goto Exit;
  4868. }
  4869. });
  4870. /* extensions */
  4871. ptls_decode_open_block(src, end, 2, {
  4872. src = end; /* unused */
  4873. });
  4874. });
  4875. (*tls)->state = ptls_is_server(*tls) ? PTLS_STATE_SERVER_POST_HANDSHAKE : PTLS_STATE_CLIENT_POST_HANDSHAKE;
  4876. Exit:
  4877. if (ret != 0) {
  4878. if (*tls != NULL) {
  4879. ptls_free(*tls);
  4880. *tls = NULL;
  4881. }
  4882. }
  4883. return ret;
  4884. }
  4885. void ptls_free(ptls_t *tls)
  4886. {
  4887. PTLS_PROBE0(FREE, tls);
  4888. PTLS_LOG_CONN(free, tls, {});
  4889. ptls_buffer_dispose(&tls->recvbuf.rec);
  4890. ptls_buffer_dispose(&tls->recvbuf.mess);
  4891. free_exporter_master_secret(tls, 1);
  4892. free_exporter_master_secret(tls, 0);
  4893. if (tls->key_schedule != NULL)
  4894. key_schedule_free(tls->key_schedule);
  4895. if (tls->traffic_protection.dec.aead != NULL)
  4896. ptls_aead_free(tls->traffic_protection.dec.aead);
  4897. if (tls->traffic_protection.enc.aead != NULL)
  4898. ptls_aead_free(tls->traffic_protection.enc.aead);
  4899. free(tls->server_name);
  4900. free(tls->negotiated_protocol);
  4901. clear_ech(&tls->ech, tls->is_server);
  4902. if (tls->is_server) {
  4903. if (tls->server.async_job != NULL)
  4904. tls->server.async_job->destroy_(tls->server.async_job);
  4905. } else {
  4906. if (tls->client.key_share_ctx != NULL)
  4907. tls->client.key_share_ctx->on_exchange(&tls->client.key_share_ctx, 1, NULL, ptls_iovec_init(NULL, 0));
  4908. if (tls->client.certificate_request.context.base != NULL)
  4909. free(tls->client.certificate_request.context.base);
  4910. }
  4911. if (tls->certificate_verify.cb != NULL)
  4912. tls->certificate_verify.cb(tls->certificate_verify.verify_ctx, 0, ptls_iovec_init(NULL, 0), ptls_iovec_init(NULL, 0));
  4913. if (tls->pending_handshake_secret != NULL) {
  4914. ptls_clear_memory(tls->pending_handshake_secret, PTLS_MAX_DIGEST_SIZE);
  4915. free(tls->pending_handshake_secret);
  4916. }
  4917. update_open_count(tls->ctx, -1);
  4918. ptls_clear_memory(tls, sizeof(*tls));
  4919. free(tls);
  4920. }
  4921. ptls_context_t *ptls_get_context(ptls_t *tls)
  4922. {
  4923. return tls->ctx;
  4924. }
  4925. void ptls_set_context(ptls_t *tls, ptls_context_t *ctx)
  4926. {
  4927. update_open_count(ctx, 1);
  4928. update_open_count(tls->ctx, -1);
  4929. tls->ctx = ctx;
  4930. }
  4931. ptls_async_job_t *ptls_get_async_job(ptls_t *tls)
  4932. {
  4933. return tls->server.async_job;
  4934. }
  4935. ptls_iovec_t ptls_get_client_random(ptls_t *tls)
  4936. {
  4937. return ptls_iovec_init(tls->client_random, PTLS_HELLO_RANDOM_SIZE);
  4938. }
  4939. ptls_cipher_suite_t *ptls_get_cipher(ptls_t *tls)
  4940. {
  4941. return tls->cipher_suite;
  4942. }
  4943. uint16_t ptls_get_protocol_version(ptls_t *tls)
  4944. {
  4945. if (tls->traffic_protection.enc.tls12)
  4946. return PTLS_PROTOCOL_VERSION_TLS12;
  4947. return PTLS_PROTOCOL_VERSION_TLS13;
  4948. }
  4949. int ptls_get_traffic_keys(ptls_t *tls, int is_enc, uint8_t *key, uint8_t *iv, uint64_t *seq)
  4950. {
  4951. struct st_ptls_traffic_protection_t *ctx = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
  4952. int ret;
  4953. if ((ret = get_traffic_keys(tls->cipher_suite->aead, tls->cipher_suite->hash, key, iv, ctx->secret, ptls_iovec_init(NULL, 0),
  4954. NULL)) != 0)
  4955. return ret;
  4956. *seq = ctx->seq;
  4957. return 0;
  4958. }
  4959. const char *ptls_get_server_name(ptls_t *tls)
  4960. {
  4961. return tls->server_name;
  4962. }
  4963. int ptls_set_server_name(ptls_t *tls, const char *server_name, size_t server_name_len)
  4964. {
  4965. char *duped = NULL;
  4966. if (server_name != NULL &&
  4967. (duped = duplicate_as_str(server_name, server_name_len != 0 ? server_name_len : strlen(server_name))) == NULL)
  4968. return PTLS_ERROR_NO_MEMORY;
  4969. free(tls->server_name);
  4970. tls->server_name = duped;
  4971. return 0;
  4972. }
  4973. const char *ptls_get_negotiated_protocol(ptls_t *tls)
  4974. {
  4975. return tls->negotiated_protocol;
  4976. }
  4977. int ptls_set_negotiated_protocol(ptls_t *tls, const char *protocol, size_t protocol_len)
  4978. {
  4979. char *duped = NULL;
  4980. if (protocol != NULL && (duped = duplicate_as_str(protocol, protocol_len != 0 ? protocol_len : strlen(protocol))) == NULL)
  4981. return PTLS_ERROR_NO_MEMORY;
  4982. free(tls->negotiated_protocol);
  4983. tls->negotiated_protocol = duped;
  4984. return 0;
  4985. }
  4986. int ptls_handshake_is_complete(ptls_t *tls)
  4987. {
  4988. return tls->state >= PTLS_STATE_POST_HANDSHAKE_MIN;
  4989. }
  4990. int ptls_is_psk_handshake(ptls_t *tls)
  4991. {
  4992. return tls->is_psk_handshake;
  4993. }
  4994. int ptls_is_ech_handshake(ptls_t *tls, uint8_t *config_id, ptls_hpke_kem_t **kem, ptls_hpke_cipher_suite_t **cipher)
  4995. {
  4996. if (tls->ech.accepted) {
  4997. if (config_id != NULL)
  4998. *config_id = tls->ech.config_id;
  4999. if (kem != NULL)
  5000. *kem = tls->ech.kem;
  5001. if (cipher != NULL)
  5002. *cipher = tls->ech.cipher;
  5003. return 1;
  5004. }
  5005. return 0;
  5006. }
  5007. void **ptls_get_data_ptr(ptls_t *tls)
  5008. {
  5009. return &tls->data_ptr;
  5010. }
  5011. ptls_log_conn_state_t *ptls_get_log_state(ptls_t *tls)
  5012. {
  5013. #if PTLS_HAVE_LOG
  5014. return &tls->log_state;
  5015. #else
  5016. return &ptls_log.dummy_conn_state;
  5017. #endif
  5018. }
  5019. static int handle_client_handshake_message(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message, int is_end_of_record,
  5020. ptls_handshake_properties_t *properties)
  5021. {
  5022. uint8_t type = message.base[0];
  5023. int ret;
  5024. switch (tls->state) {
  5025. case PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO:
  5026. case PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO:
  5027. if (type == PTLS_HANDSHAKE_TYPE_SERVER_HELLO && is_end_of_record) {
  5028. ret = client_handle_hello(tls, emitter, message, properties);
  5029. } else {
  5030. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5031. }
  5032. break;
  5033. case PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS:
  5034. if (type == PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS) {
  5035. ret = client_handle_encrypted_extensions(tls, message, properties);
  5036. } else {
  5037. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5038. }
  5039. break;
  5040. case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE:
  5041. if (type == PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST) {
  5042. ret = client_handle_certificate_request(tls, message, properties);
  5043. break;
  5044. }
  5045. /* fall through */
  5046. case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE:
  5047. switch (type) {
  5048. case PTLS_HANDSHAKE_TYPE_CERTIFICATE:
  5049. ret = client_handle_certificate(tls, message);
  5050. break;
  5051. case PTLS_HANDSHAKE_TYPE_COMPRESSED_CERTIFICATE:
  5052. ret = client_handle_compressed_certificate(tls, message);
  5053. break;
  5054. default:
  5055. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5056. break;
  5057. }
  5058. break;
  5059. case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY:
  5060. if (type == PTLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY) {
  5061. ret = client_handle_certificate_verify(tls, message);
  5062. } else {
  5063. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5064. }
  5065. break;
  5066. case PTLS_STATE_CLIENT_EXPECT_FINISHED:
  5067. if (type == PTLS_HANDSHAKE_TYPE_FINISHED && is_end_of_record) {
  5068. ret = client_handle_finished(tls, emitter, message);
  5069. } else {
  5070. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5071. }
  5072. break;
  5073. case PTLS_STATE_CLIENT_POST_HANDSHAKE:
  5074. switch (type) {
  5075. case PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET:
  5076. ret = client_handle_new_session_ticket(tls, message);
  5077. break;
  5078. case PTLS_HANDSHAKE_TYPE_KEY_UPDATE:
  5079. ret = handle_key_update(tls, emitter, message);
  5080. break;
  5081. default:
  5082. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5083. break;
  5084. }
  5085. break;
  5086. default:
  5087. assert(!"unexpected state");
  5088. ret = PTLS_ALERT_INTERNAL_ERROR;
  5089. break;
  5090. }
  5091. PTLS_PROBE(RECEIVE_MESSAGE, tls, message.base[0], message.base + PTLS_HANDSHAKE_HEADER_SIZE,
  5092. message.len - PTLS_HANDSHAKE_HEADER_SIZE, ret);
  5093. PTLS_LOG_CONN(receive_message, tls, {
  5094. PTLS_LOG_ELEMENT_UNSIGNED(message, message.base[0]);
  5095. PTLS_LOG_ELEMENT_UNSIGNED(len, message.len - PTLS_HANDSHAKE_HEADER_SIZE);
  5096. PTLS_LOG_ELEMENT_SIGNED(result, ret);
  5097. });
  5098. return ret;
  5099. }
  5100. static int handle_server_handshake_message(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message, int is_end_of_record,
  5101. ptls_handshake_properties_t *properties)
  5102. {
  5103. uint8_t type = message.base[0];
  5104. int ret;
  5105. switch (tls->state) {
  5106. case PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO:
  5107. case PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO:
  5108. if (type == PTLS_HANDSHAKE_TYPE_CLIENT_HELLO && is_end_of_record) {
  5109. ret = server_handle_hello(tls, emitter, message, properties);
  5110. } else {
  5111. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  5112. }
  5113. break;
  5114. case PTLS_STATE_SERVER_EXPECT_CERTIFICATE:
  5115. if (type == PTLS_HANDSHAKE_TYPE_CERTIFICATE) {
  5116. ret = server_handle_certificate(tls, message);
  5117. } else {
  5118. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5119. }
  5120. break;
  5121. case PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY:
  5122. if (type == PTLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY) {
  5123. ret = server_handle_certificate_verify(tls, message);
  5124. } else {
  5125. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5126. }
  5127. break;
  5128. case PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA:
  5129. assert(!tls->ctx->omit_end_of_early_data);
  5130. if (type == PTLS_HANDSHAKE_TYPE_END_OF_EARLY_DATA) {
  5131. ret = server_handle_end_of_early_data(tls, message);
  5132. } else {
  5133. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5134. }
  5135. break;
  5136. case PTLS_STATE_SERVER_EXPECT_FINISHED:
  5137. if (type == PTLS_HANDSHAKE_TYPE_FINISHED && is_end_of_record) {
  5138. ret = server_handle_finished(tls, message);
  5139. } else {
  5140. ret = PTLS_ALERT_HANDSHAKE_FAILURE;
  5141. }
  5142. break;
  5143. case PTLS_STATE_SERVER_POST_HANDSHAKE:
  5144. switch (type) {
  5145. case PTLS_HANDSHAKE_TYPE_KEY_UPDATE:
  5146. ret = handle_key_update(tls, emitter, message);
  5147. break;
  5148. default:
  5149. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5150. break;
  5151. }
  5152. break;
  5153. default:
  5154. assert(!"unexpected state");
  5155. ret = PTLS_ALERT_INTERNAL_ERROR;
  5156. break;
  5157. }
  5158. PTLS_PROBE(RECEIVE_MESSAGE, tls, message.base[0], message.base + PTLS_HANDSHAKE_HEADER_SIZE,
  5159. message.len - PTLS_HANDSHAKE_HEADER_SIZE, ret);
  5160. PTLS_LOG_CONN(receive_message, tls, {
  5161. PTLS_LOG_ELEMENT_UNSIGNED(message, message.base[0]);
  5162. PTLS_LOG_ELEMENT_UNSIGNED(len, message.len - PTLS_HANDSHAKE_HEADER_SIZE);
  5163. PTLS_LOG_ELEMENT_SIGNED(result, ret);
  5164. });
  5165. return ret;
  5166. }
  5167. static int handle_alert(ptls_t *tls, const uint8_t *src, size_t len)
  5168. {
  5169. if (len != 2)
  5170. return PTLS_ALERT_DECODE_ERROR;
  5171. uint8_t desc = src[1];
  5172. /* all fatal alerts and USER_CANCELLED warning tears down the connection immediately, regardless of the transmitted level */
  5173. return PTLS_ALERT_TO_PEER_ERROR(desc);
  5174. }
  5175. static int message_buffer_is_overflow(ptls_context_t *ctx, size_t size)
  5176. {
  5177. if (ctx->max_buffer_size == 0)
  5178. return 0;
  5179. if (size <= ctx->max_buffer_size)
  5180. return 0;
  5181. return 1;
  5182. }
  5183. static int handle_handshake_record(ptls_t *tls,
  5184. int (*cb)(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message,
  5185. int is_end_of_record, ptls_handshake_properties_t *properties),
  5186. ptls_message_emitter_t *emitter, struct st_ptls_record_t *rec,
  5187. ptls_handshake_properties_t *properties)
  5188. {
  5189. int ret;
  5190. /* handshake */
  5191. if (rec->type != PTLS_CONTENT_TYPE_HANDSHAKE)
  5192. return PTLS_ALERT_DECODE_ERROR;
  5193. /* flatten the unhandled messages */
  5194. const uint8_t *src, *src_end;
  5195. if (tls->recvbuf.mess.base == NULL) {
  5196. src = rec->fragment;
  5197. src_end = src + rec->length;
  5198. } else {
  5199. if (message_buffer_is_overflow(tls->ctx, tls->recvbuf.mess.off + rec->length))
  5200. return PTLS_ALERT_HANDSHAKE_FAILURE;
  5201. if ((ret = ptls_buffer_reserve(&tls->recvbuf.mess, rec->length)) != 0)
  5202. return ret;
  5203. memcpy(tls->recvbuf.mess.base + tls->recvbuf.mess.off, rec->fragment, rec->length);
  5204. tls->recvbuf.mess.off += rec->length;
  5205. src = tls->recvbuf.mess.base;
  5206. src_end = src + tls->recvbuf.mess.off;
  5207. }
  5208. /* handle the messages */
  5209. ret = PTLS_ERROR_IN_PROGRESS;
  5210. while (src_end - src >= 4) {
  5211. size_t mess_len = 4 + ntoh24(src + 1);
  5212. if (src_end - src < (int)mess_len)
  5213. break;
  5214. ret = cb(tls, emitter, ptls_iovec_init(src, mess_len), src_end - src == mess_len, properties);
  5215. switch (ret) {
  5216. case 0:
  5217. case PTLS_ERROR_ASYNC_OPERATION:
  5218. case PTLS_ERROR_IN_PROGRESS:
  5219. break;
  5220. default:
  5221. ptls_buffer_dispose(&tls->recvbuf.mess);
  5222. return ret;
  5223. }
  5224. src += mess_len;
  5225. }
  5226. /* keep last partial message in buffer */
  5227. if (src != src_end) {
  5228. size_t new_size = src_end - src;
  5229. if (message_buffer_is_overflow(tls->ctx, new_size))
  5230. return PTLS_ALERT_HANDSHAKE_FAILURE;
  5231. if (tls->recvbuf.mess.base == NULL) {
  5232. ptls_buffer_init(&tls->recvbuf.mess, "", 0);
  5233. if ((ret = ptls_buffer_reserve(&tls->recvbuf.mess, new_size)) != 0)
  5234. return ret;
  5235. memcpy(tls->recvbuf.mess.base, src, new_size);
  5236. } else {
  5237. memmove(tls->recvbuf.mess.base, src, new_size);
  5238. }
  5239. tls->recvbuf.mess.off = new_size;
  5240. ret = PTLS_ERROR_IN_PROGRESS;
  5241. } else {
  5242. ptls_buffer_dispose(&tls->recvbuf.mess);
  5243. }
  5244. return ret;
  5245. }
  5246. static int handle_input(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_buffer_t *decryptbuf, const void *input, size_t *inlen,
  5247. ptls_handshake_properties_t *properties)
  5248. {
  5249. struct st_ptls_record_t rec;
  5250. int ret;
  5251. /* extract the record */
  5252. if ((ret = parse_record(tls, &rec, input, inlen)) != 0)
  5253. return ret;
  5254. assert(rec.fragment != NULL);
  5255. /* decrypt the record */
  5256. if (rec.type == PTLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC) {
  5257. if (tls->state < PTLS_STATE_POST_HANDSHAKE_MIN) {
  5258. if (!(rec.length == 1 && rec.fragment[0] == 0x01))
  5259. return PTLS_ALERT_ILLEGAL_PARAMETER;
  5260. } else {
  5261. return PTLS_ALERT_HANDSHAKE_FAILURE;
  5262. }
  5263. ret = PTLS_ERROR_IN_PROGRESS;
  5264. goto NextRecord;
  5265. }
  5266. if (tls->traffic_protection.dec.aead != NULL && rec.type != PTLS_CONTENT_TYPE_ALERT) {
  5267. size_t decrypted_length;
  5268. if (rec.type != PTLS_CONTENT_TYPE_APPDATA)
  5269. return PTLS_ALERT_HANDSHAKE_FAILURE;
  5270. if ((ret = ptls_buffer_reserve(decryptbuf, 5 + rec.length)) != 0)
  5271. return ret;
  5272. if ((ret = aead_decrypt(&tls->traffic_protection.dec, decryptbuf->base + decryptbuf->off, &decrypted_length, rec.fragment,
  5273. rec.length)) != 0) {
  5274. if (tls->is_server && tls->server.early_data_skipped_bytes != UINT32_MAX)
  5275. goto ServerSkipEarlyData;
  5276. return ret;
  5277. }
  5278. rec.length = decrypted_length;
  5279. rec.fragment = decryptbuf->base + decryptbuf->off;
  5280. /* skip padding */
  5281. for (; rec.length != 0; --rec.length)
  5282. if (rec.fragment[rec.length - 1] != 0)
  5283. break;
  5284. if (rec.length == 0)
  5285. return PTLS_ALERT_UNEXPECTED_MESSAGE;
  5286. rec.type = rec.fragment[--rec.length];
  5287. } else if (rec.type == PTLS_CONTENT_TYPE_APPDATA && tls->is_server && tls->server.early_data_skipped_bytes != UINT32_MAX) {
  5288. goto ServerSkipEarlyData;
  5289. }
  5290. if (tls->recvbuf.mess.base != NULL || rec.type == PTLS_CONTENT_TYPE_HANDSHAKE) {
  5291. /* handshake record */
  5292. ret = handle_handshake_record(tls, tls->is_server ? handle_server_handshake_message : handle_client_handshake_message,
  5293. emitter, &rec, properties);
  5294. } else {
  5295. /* handling of an alert or an application record */
  5296. switch (rec.type) {
  5297. case PTLS_CONTENT_TYPE_APPDATA:
  5298. if (tls->state >= PTLS_STATE_POST_HANDSHAKE_MIN) {
  5299. decryptbuf->off += rec.length;
  5300. ret = 0;
  5301. } else if (tls->state == PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA) {
  5302. if (tls->traffic_protection.dec.aead != NULL)
  5303. decryptbuf->off += rec.length;
  5304. ret = 0;
  5305. } else {
  5306. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5307. }
  5308. break;
  5309. case PTLS_CONTENT_TYPE_ALERT:
  5310. ret = handle_alert(tls, rec.fragment, rec.length);
  5311. break;
  5312. default:
  5313. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5314. break;
  5315. }
  5316. }
  5317. NextRecord:
  5318. ptls_buffer_dispose(&tls->recvbuf.rec);
  5319. return ret;
  5320. ServerSkipEarlyData:
  5321. tls->server.early_data_skipped_bytes += (uint32_t)rec.length;
  5322. if (tls->server.early_data_skipped_bytes > PTLS_MAX_EARLY_DATA_SKIP_SIZE)
  5323. return PTLS_ALERT_HANDSHAKE_FAILURE;
  5324. ret = PTLS_ERROR_IN_PROGRESS;
  5325. goto NextRecord;
  5326. }
  5327. static int handle_input_tls12(ptls_t *tls, ptls_buffer_t *decryptbuf, const void *input, size_t *inlen)
  5328. {
  5329. struct st_ptls_record_t rec;
  5330. int ret;
  5331. /* extract the record, or bail out */
  5332. if ((ret = parse_record(tls, &rec, input, inlen)) != 0)
  5333. return ret;
  5334. assert(rec.fragment != NULL);
  5335. const uint8_t *src = rec.fragment, *end = src + rec.length;
  5336. uint64_t nonce;
  5337. uint8_t aad[PTLS_TLS12_AAD_SIZE];
  5338. /* determine the nonce */
  5339. if (tls->traffic_protection.dec.aead->algo->tls12.record_iv_size != 0) {
  5340. assert(tls->traffic_protection.dec.aead->algo->tls12.record_iv_size == 8);
  5341. if ((ret = ptls_decode64(&nonce, &src, end)) != 0)
  5342. goto Exit;
  5343. } else {
  5344. nonce = tls->traffic_protection.dec.seq;
  5345. }
  5346. /* determine cleartext length */
  5347. size_t textlen = end - src;
  5348. if (textlen < tls->traffic_protection.dec.aead->algo->tag_size) {
  5349. ret = PTLS_ALERT_BAD_RECORD_MAC;
  5350. goto Exit;
  5351. }
  5352. textlen -= tls->traffic_protection.dec.aead->algo->tag_size;
  5353. /* build aad */
  5354. build_tls12_aad(aad, rec.type, tls->traffic_protection.dec.seq, (uint16_t)textlen);
  5355. /* decrypt input to decryptbuf */
  5356. if ((ret = ptls_buffer_reserve(decryptbuf, textlen)) != 0)
  5357. goto Exit;
  5358. if (ptls_aead_decrypt(tls->traffic_protection.dec.aead, decryptbuf->base + decryptbuf->off, src, end - src, nonce, aad,
  5359. sizeof(aad)) != textlen) {
  5360. ret = PTLS_ALERT_BAD_RECORD_MAC;
  5361. goto Exit;
  5362. }
  5363. ++tls->traffic_protection.dec.seq;
  5364. /* record-type specific action */
  5365. switch (rec.type) {
  5366. case PTLS_CONTENT_TYPE_APPDATA:
  5367. /* if application data, retain the bytes being decrypted */
  5368. decryptbuf->off += textlen;
  5369. break;
  5370. case PTLS_CONTENT_TYPE_ALERT:
  5371. /* submit alert without adjusting decryptbuf, so that the decrypted data would be dropped after handling the alert */
  5372. ret = handle_alert(tls, decryptbuf->base + decryptbuf->off, textlen);
  5373. break;
  5374. default:
  5375. ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
  5376. break;
  5377. }
  5378. Exit:
  5379. ptls_buffer_dispose(&tls->recvbuf.rec);
  5380. ptls_clear_memory(aad, sizeof(aad));
  5381. return 0;
  5382. }
  5383. static void init_record_message_emitter(ptls_t *tls, struct st_ptls_record_message_emitter_t *emitter, ptls_buffer_t *sendbuf)
  5384. {
  5385. *emitter = (struct st_ptls_record_message_emitter_t){
  5386. {sendbuf, &tls->traffic_protection.enc, 5, begin_record_message, commit_record_message}};
  5387. }
  5388. int ptls_handshake(ptls_t *tls, ptls_buffer_t *_sendbuf, const void *input, size_t *inlen, ptls_handshake_properties_t *properties)
  5389. {
  5390. struct st_ptls_record_message_emitter_t emitter;
  5391. int ret;
  5392. assert(tls->state < PTLS_STATE_POST_HANDSHAKE_MIN);
  5393. init_record_message_emitter(tls, &emitter, _sendbuf);
  5394. size_t sendbuf_orig_off = emitter.super.buf->off;
  5395. /* special handlings */
  5396. switch (tls->state) {
  5397. case PTLS_STATE_CLIENT_HANDSHAKE_START: {
  5398. assert(input == NULL || *inlen == 0);
  5399. return send_client_hello(tls, &emitter.super, properties, NULL);
  5400. }
  5401. case PTLS_STATE_SERVER_GENERATING_CERTIFICATE_VERIFY:
  5402. return server_finish_handshake(tls, &emitter.super, 1, NULL);
  5403. default:
  5404. break;
  5405. }
  5406. const uint8_t *src = input, *const src_end = src + *inlen;
  5407. ptls_buffer_t decryptbuf;
  5408. ptls_buffer_init(&decryptbuf, "", 0);
  5409. /* perform handhake until completion or until all the input has been swallowed */
  5410. ret = PTLS_ERROR_IN_PROGRESS;
  5411. while (ret == PTLS_ERROR_IN_PROGRESS && src != src_end) {
  5412. size_t consumed = src_end - src;
  5413. ret = handle_input(tls, &emitter.super, &decryptbuf, src, &consumed, properties);
  5414. src += consumed;
  5415. assert(decryptbuf.off == 0);
  5416. }
  5417. ptls_buffer_dispose(&decryptbuf);
  5418. switch (ret) {
  5419. case 0:
  5420. case PTLS_ERROR_IN_PROGRESS:
  5421. case PTLS_ERROR_STATELESS_RETRY:
  5422. case PTLS_ERROR_ASYNC_OPERATION:
  5423. break;
  5424. default:
  5425. /* Flush handshake messages that have been written partially. ECH_REQUIRED sticks out because it is a message sent
  5426. * post-handshake compared to other alerts that are generating *during* the handshake. */
  5427. if (ret != PTLS_ALERT_ECH_REQUIRED) {
  5428. ptls_clear_memory(emitter.super.buf->base + sendbuf_orig_off, emitter.super.buf->off - sendbuf_orig_off);
  5429. emitter.super.buf->off = sendbuf_orig_off;
  5430. }
  5431. /* send alert immediately */
  5432. if (PTLS_ERROR_GET_CLASS(ret) != PTLS_ERROR_CLASS_PEER_ALERT)
  5433. if (ptls_send_alert(tls, emitter.super.buf, PTLS_ALERT_LEVEL_FATAL,
  5434. PTLS_ERROR_GET_CLASS(ret) == PTLS_ERROR_CLASS_SELF_ALERT ? ret : PTLS_ALERT_INTERNAL_ERROR) != 0)
  5435. emitter.super.buf->off = sendbuf_orig_off;
  5436. break;
  5437. }
  5438. *inlen -= src_end - src;
  5439. return ret;
  5440. }
  5441. int ptls_receive(ptls_t *tls, ptls_buffer_t *decryptbuf, const void *_input, size_t *inlen)
  5442. {
  5443. const uint8_t *input = (const uint8_t *)_input, *const end = input + *inlen;
  5444. size_t decryptbuf_orig_size = decryptbuf->off;
  5445. int ret = 0;
  5446. assert(tls->state >= PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA);
  5447. /* loop until we decrypt some application data (or an error) */
  5448. while (ret == 0 && input != end && decryptbuf_orig_size == decryptbuf->off) {
  5449. size_t consumed = end - input;
  5450. if (tls->traffic_protection.dec.tls12) {
  5451. ret = handle_input_tls12(tls, decryptbuf, input, &consumed);
  5452. } else {
  5453. ret = handle_input(tls, NULL, decryptbuf, input, &consumed, NULL);
  5454. }
  5455. input += consumed;
  5456. switch (ret) {
  5457. case 0:
  5458. break;
  5459. case PTLS_ERROR_IN_PROGRESS:
  5460. ret = 0;
  5461. break;
  5462. case PTLS_ERROR_CLASS_PEER_ALERT + PTLS_ALERT_CLOSE_NOTIFY:
  5463. /* TODO send close alert */
  5464. break;
  5465. default:
  5466. if (PTLS_ERROR_GET_CLASS(ret) == PTLS_ERROR_CLASS_SELF_ALERT) {
  5467. /* TODO send alert */
  5468. }
  5469. break;
  5470. }
  5471. }
  5472. *inlen -= end - input;
  5473. return ret;
  5474. }
  5475. static int update_send_key(ptls_t *tls, ptls_buffer_t *_sendbuf, int request_update)
  5476. {
  5477. struct st_ptls_record_message_emitter_t emitter;
  5478. int ret;
  5479. init_record_message_emitter(tls, &emitter, _sendbuf);
  5480. size_t sendbuf_orig_off = emitter.super.buf->off;
  5481. ptls_push_message(&emitter.super, NULL, PTLS_HANDSHAKE_TYPE_KEY_UPDATE,
  5482. { ptls_buffer_push(emitter.super.buf, !!request_update); });
  5483. if ((ret = update_traffic_key(tls, 1)) != 0)
  5484. goto Exit;
  5485. ret = 0;
  5486. Exit:
  5487. if (ret != 0)
  5488. emitter.super.buf->off = sendbuf_orig_off;
  5489. return ret;
  5490. }
  5491. int ptls_send(ptls_t *tls, ptls_buffer_t *sendbuf, const void *input, size_t inlen)
  5492. {
  5493. assert(tls->traffic_protection.enc.aead != NULL);
  5494. /* "For AES-GCM, up to 2^24.5 full-size records (about 24 million) may be encrypted on a given connection while keeping a
  5495. * safety margin of approximately 2^-57 for Authenticated Encryption (AE) security." (RFC 8446 section 5.5).
  5496. *
  5497. * Key updates do not happen with tls 1.2, check `key_schedule` to see if we are using tls/1.3
  5498. */
  5499. if (tls->traffic_protection.enc.seq >= 16777216 && tls->key_schedule != NULL)
  5500. tls->needs_key_update = 1;
  5501. if (tls->needs_key_update) {
  5502. int ret;
  5503. if ((ret = update_send_key(tls, sendbuf, tls->key_update_send_request)) != 0)
  5504. return ret;
  5505. tls->needs_key_update = 0;
  5506. tls->key_update_send_request = 0;
  5507. }
  5508. return buffer_push_encrypted_records(sendbuf, PTLS_CONTENT_TYPE_APPDATA, input, inlen, &tls->traffic_protection.enc);
  5509. }
  5510. int ptls_update_key(ptls_t *tls, int request_update)
  5511. {
  5512. assert(tls->ctx->update_traffic_key == NULL);
  5513. tls->needs_key_update = 1;
  5514. tls->key_update_send_request = request_update;
  5515. return 0;
  5516. }
  5517. size_t ptls_get_record_overhead(ptls_t *tls)
  5518. {
  5519. ptls_aead_algorithm_t *algo = tls->traffic_protection.enc.aead->algo;
  5520. if (tls->traffic_protection.enc.tls12) {
  5521. return 5 + algo->tls12.record_iv_size + algo->tag_size;
  5522. } else {
  5523. return 6 + algo->tag_size;
  5524. }
  5525. }
  5526. int ptls_send_alert(ptls_t *tls, ptls_buffer_t *sendbuf, uint8_t level, uint8_t description)
  5527. {
  5528. size_t rec_start = sendbuf->off;
  5529. int ret = 0;
  5530. buffer_push_record(sendbuf, PTLS_CONTENT_TYPE_ALERT, { ptls_buffer_push(sendbuf, level, description); });
  5531. /* encrypt the alert if we have the encryption keys, unless when it is the early data key */
  5532. if (tls->traffic_protection.enc.aead != NULL && !(tls->state <= PTLS_STATE_CLIENT_EXPECT_FINISHED)) {
  5533. if ((ret = buffer_encrypt_record(sendbuf, rec_start, &tls->traffic_protection.enc)) != 0)
  5534. goto Exit;
  5535. }
  5536. Exit:
  5537. return ret;
  5538. }
  5539. int ptls_export_secret(ptls_t *tls, void *output, size_t outlen, const char *label, ptls_iovec_t context_value, int is_early)
  5540. {
  5541. ptls_hash_algorithm_t *algo = tls->key_schedule->hashes[0].algo;
  5542. uint8_t *master_secret = is_early ? tls->exporter_master_secret.early : tls->exporter_master_secret.one_rtt,
  5543. derived_secret[PTLS_MAX_DIGEST_SIZE], context_value_hash[PTLS_MAX_DIGEST_SIZE];
  5544. int ret;
  5545. if (master_secret == NULL) {
  5546. if (is_early) {
  5547. switch (tls->state) {
  5548. case PTLS_STATE_CLIENT_HANDSHAKE_START:
  5549. case PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO:
  5550. ret = PTLS_ERROR_IN_PROGRESS;
  5551. break;
  5552. default:
  5553. ret = PTLS_ERROR_NOT_AVAILABLE;
  5554. break;
  5555. }
  5556. } else {
  5557. ret = PTLS_ERROR_IN_PROGRESS;
  5558. }
  5559. return ret;
  5560. }
  5561. if ((ret = ptls_calc_hash(algo, context_value_hash, context_value.base, context_value.len)) != 0)
  5562. return ret;
  5563. if ((ret = ptls_hkdf_expand_label(algo, derived_secret, algo->digest_size, ptls_iovec_init(master_secret, algo->digest_size),
  5564. label, ptls_iovec_init(algo->empty_digest, algo->digest_size), NULL)) != 0)
  5565. goto Exit;
  5566. ret = ptls_hkdf_expand_label(algo, output, outlen, ptls_iovec_init(derived_secret, algo->digest_size), "exporter",
  5567. ptls_iovec_init(context_value_hash, algo->digest_size), NULL);
  5568. Exit:
  5569. ptls_clear_memory(derived_secret, sizeof(derived_secret));
  5570. ptls_clear_memory(context_value_hash, sizeof(context_value_hash));
  5571. return ret;
  5572. }
  5573. struct st_picotls_hmac_context_t {
  5574. ptls_hash_context_t super;
  5575. ptls_hash_algorithm_t *algo;
  5576. ptls_hash_context_t *hash;
  5577. uint8_t key[1];
  5578. };
  5579. static void hmac_update(ptls_hash_context_t *_ctx, const void *src, size_t len)
  5580. {
  5581. struct st_picotls_hmac_context_t *ctx = (struct st_picotls_hmac_context_t *)_ctx;
  5582. ctx->hash->update(ctx->hash, src, len);
  5583. }
  5584. static void hmac_apply_key(struct st_picotls_hmac_context_t *ctx, uint8_t pad)
  5585. {
  5586. size_t i;
  5587. for (i = 0; i != ctx->algo->block_size; ++i)
  5588. ctx->key[i] ^= pad;
  5589. ctx->hash->update(ctx->hash, ctx->key, ctx->algo->block_size);
  5590. for (i = 0; i != ctx->algo->block_size; ++i)
  5591. ctx->key[i] ^= pad;
  5592. }
  5593. static void hmac_final(ptls_hash_context_t *_ctx, void *md, ptls_hash_final_mode_t mode)
  5594. {
  5595. struct st_picotls_hmac_context_t *ctx = (struct st_picotls_hmac_context_t *)_ctx;
  5596. assert(mode != PTLS_HASH_FINAL_MODE_SNAPSHOT || !"not supported");
  5597. if (md != NULL) {
  5598. ctx->hash->final(ctx->hash, md, PTLS_HASH_FINAL_MODE_RESET);
  5599. hmac_apply_key(ctx, 0x5c);
  5600. ctx->hash->update(ctx->hash, md, ctx->algo->digest_size);
  5601. }
  5602. ctx->hash->final(ctx->hash, md, mode);
  5603. switch (mode) {
  5604. case PTLS_HASH_FINAL_MODE_FREE:
  5605. ptls_clear_memory(ctx->key, ctx->algo->block_size);
  5606. free(ctx);
  5607. break;
  5608. case PTLS_HASH_FINAL_MODE_RESET:
  5609. hmac_apply_key(ctx, 0x36);
  5610. break;
  5611. default:
  5612. assert(!"FIXME");
  5613. break;
  5614. }
  5615. }
  5616. int ptls_calc_hash(ptls_hash_algorithm_t *algo, void *output, const void *src, size_t len)
  5617. {
  5618. ptls_hash_context_t *ctx;
  5619. if ((ctx = algo->create()) == NULL)
  5620. return PTLS_ERROR_NO_MEMORY;
  5621. ctx->update(ctx, src, len);
  5622. ctx->final(ctx, output, PTLS_HASH_FINAL_MODE_FREE);
  5623. return 0;
  5624. }
  5625. ptls_hash_context_t *ptls_hmac_create(ptls_hash_algorithm_t *algo, const void *key, size_t key_size)
  5626. {
  5627. struct st_picotls_hmac_context_t *ctx;
  5628. assert(key_size <= algo->block_size);
  5629. if ((ctx = malloc(offsetof(struct st_picotls_hmac_context_t, key) + algo->block_size)) == NULL)
  5630. return NULL;
  5631. *ctx = (struct st_picotls_hmac_context_t){{hmac_update, hmac_final}, algo};
  5632. if ((ctx->hash = algo->create()) == NULL) {
  5633. free(ctx);
  5634. return NULL;
  5635. }
  5636. memset(ctx->key, 0, algo->block_size);
  5637. memcpy(ctx->key, key, key_size);
  5638. hmac_apply_key(ctx, 0x36);
  5639. return &ctx->super;
  5640. }
  5641. int ptls_hkdf_extract(ptls_hash_algorithm_t *algo, void *output, ptls_iovec_t salt, ptls_iovec_t ikm)
  5642. {
  5643. ptls_hash_context_t *hash;
  5644. if (salt.len == 0)
  5645. salt = ptls_iovec_init(zeroes_of_max_digest_size, algo->digest_size);
  5646. if ((hash = ptls_hmac_create(algo, salt.base, salt.len)) == NULL)
  5647. return PTLS_ERROR_NO_MEMORY;
  5648. hash->update(hash, ikm.base, ikm.len);
  5649. hash->final(hash, output, PTLS_HASH_FINAL_MODE_FREE);
  5650. return 0;
  5651. }
  5652. int ptls_hkdf_expand(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t prk, ptls_iovec_t info)
  5653. {
  5654. ptls_hash_context_t *hmac = NULL;
  5655. size_t i;
  5656. uint8_t digest[PTLS_MAX_DIGEST_SIZE];
  5657. for (i = 0; (i * algo->digest_size) < outlen; ++i) {
  5658. if (hmac == NULL) {
  5659. if ((hmac = ptls_hmac_create(algo, prk.base, prk.len)) == NULL)
  5660. return PTLS_ERROR_NO_MEMORY;
  5661. } else {
  5662. hmac->update(hmac, digest, algo->digest_size);
  5663. }
  5664. hmac->update(hmac, info.base, info.len);
  5665. uint8_t gen = (uint8_t)(i + 1);
  5666. hmac->update(hmac, &gen, 1);
  5667. hmac->final(hmac, digest, 1);
  5668. size_t off_start = i * algo->digest_size, off_end = off_start + algo->digest_size;
  5669. if (off_end > outlen)
  5670. off_end = outlen;
  5671. memcpy((uint8_t *)output + off_start, digest, off_end - off_start);
  5672. }
  5673. if (hmac != NULL)
  5674. hmac->final(hmac, NULL, PTLS_HASH_FINAL_MODE_FREE);
  5675. ptls_clear_memory(digest, algo->digest_size);
  5676. return 0;
  5677. }
  5678. int ptls_hkdf_expand_label(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t secret, const char *label,
  5679. ptls_iovec_t hash_value, const char *label_prefix)
  5680. {
  5681. ptls_buffer_t hkdf_label;
  5682. uint8_t hkdf_label_buf[80];
  5683. int ret;
  5684. ptls_buffer_init(&hkdf_label, hkdf_label_buf, sizeof(hkdf_label_buf));
  5685. ptls_buffer_push16(&hkdf_label, (uint16_t)outlen);
  5686. ptls_buffer_push_block(&hkdf_label, 1, {
  5687. if (label_prefix == NULL)
  5688. label_prefix = PTLS_HKDF_EXPAND_LABEL_PREFIX;
  5689. ptls_buffer_pushv(&hkdf_label, label_prefix, strlen(label_prefix));
  5690. ptls_buffer_pushv(&hkdf_label, label, strlen(label));
  5691. });
  5692. ptls_buffer_push_block(&hkdf_label, 1, { ptls_buffer_pushv(&hkdf_label, hash_value.base, hash_value.len); });
  5693. ret = ptls_hkdf_expand(algo, output, outlen, secret, ptls_iovec_init(hkdf_label.base, hkdf_label.off));
  5694. Exit:
  5695. ptls_buffer_dispose(&hkdf_label);
  5696. return ret;
  5697. }
  5698. int ptls_tls12_phash(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t secret, const char *label,
  5699. ptls_iovec_t seed)
  5700. {
  5701. ptls_hash_context_t *hmac;
  5702. uint8_t An[PTLS_MAX_DIGEST_SIZE];
  5703. size_t output_off = 0;
  5704. if ((hmac = ptls_hmac_create(algo, secret.base, secret.len)) == NULL)
  5705. return PTLS_ERROR_NO_MEMORY;
  5706. /* A(1) = HMAC_hash(secret, label + seed) */
  5707. if (label != NULL)
  5708. hmac->update(hmac, label, strlen(label));
  5709. hmac->update(hmac, seed.base, seed.len);
  5710. hmac->final(hmac, An, PTLS_HASH_FINAL_MODE_RESET);
  5711. while (1) {
  5712. /* output += HMAC_hash(secret, A(i) + label + seed) */
  5713. hmac->update(hmac, An, algo->digest_size);
  5714. if (label != NULL)
  5715. hmac->update(hmac, label, strlen(label));
  5716. hmac->update(hmac, seed.base, seed.len);
  5717. if (outlen - output_off <= algo->digest_size) {
  5718. /* digest of last chunk is at first written to An then the necessary bytes are copied to output */
  5719. hmac->final(hmac, An, PTLS_HASH_FINAL_MODE_FREE);
  5720. memcpy((uint8_t *)output + output_off, An, outlen - output_off);
  5721. break;
  5722. }
  5723. hmac->final(hmac, (uint8_t *)output + output_off, PTLS_HASH_FINAL_MODE_RESET);
  5724. output_off += algo->digest_size;
  5725. /* A(i) = HMAC_hash(secret, A(i-1)) */
  5726. hmac->update(hmac, An, algo->digest_size);
  5727. hmac->final(hmac, An, PTLS_HASH_FINAL_MODE_RESET);
  5728. }
  5729. ptls_clear_memory(An, algo->digest_size);
  5730. return 0;
  5731. }
  5732. ptls_cipher_context_t *ptls_cipher_new(ptls_cipher_algorithm_t *algo, int is_enc, const void *key)
  5733. {
  5734. ptls_cipher_context_t *ctx;
  5735. if ((ctx = (ptls_cipher_context_t *)malloc(algo->context_size)) == NULL)
  5736. return NULL;
  5737. *ctx = (ptls_cipher_context_t){algo};
  5738. if (algo->setup_crypto(ctx, is_enc, key) != 0) {
  5739. free(ctx);
  5740. ctx = NULL;
  5741. }
  5742. return ctx;
  5743. }
  5744. void ptls_cipher_free(ptls_cipher_context_t *ctx)
  5745. {
  5746. ctx->do_dispose(ctx);
  5747. free(ctx);
  5748. }
  5749. ptls_aead_context_t *new_aead(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, int is_enc, const void *secret,
  5750. ptls_iovec_t hash_value, const char *label_prefix)
  5751. {
  5752. ptls_aead_context_t *ctx = NULL;
  5753. struct {
  5754. uint8_t key[PTLS_MAX_SECRET_SIZE];
  5755. uint8_t iv[PTLS_MAX_IV_SIZE];
  5756. } key_iv;
  5757. int ret;
  5758. if ((ret = get_traffic_keys(aead, hash, key_iv.key, key_iv.iv, secret, hash_value, label_prefix)) != 0)
  5759. goto Exit;
  5760. ctx = ptls_aead_new_direct(aead, is_enc, key_iv.key, key_iv.iv);
  5761. Exit:
  5762. ptls_clear_memory(&key_iv, sizeof(key_iv));
  5763. return ctx;
  5764. }
  5765. ptls_aead_context_t *ptls_aead_new(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, int is_enc, const void *secret,
  5766. const char *label_prefix)
  5767. {
  5768. return new_aead(aead, hash, is_enc, secret, ptls_iovec_init(NULL, 0), label_prefix);
  5769. }
  5770. ptls_aead_context_t *ptls_aead_new_direct(ptls_aead_algorithm_t *aead, int is_enc, const void *key, const void *iv)
  5771. {
  5772. ptls_aead_context_t *ctx;
  5773. if ((ctx = (ptls_aead_context_t *)malloc(aead->context_size)) == NULL)
  5774. return NULL;
  5775. *ctx = (ptls_aead_context_t){aead};
  5776. if (aead->setup_crypto(ctx, is_enc, key, iv) != 0) {
  5777. free(ctx);
  5778. return NULL;
  5779. }
  5780. return ctx;
  5781. }
  5782. void ptls_aead_free(ptls_aead_context_t *ctx)
  5783. {
  5784. ctx->dispose_crypto(ctx);
  5785. free(ctx);
  5786. }
  5787. void ptls_aead_xor_iv(ptls_aead_context_t *ctx, const void *_bytes, size_t len)
  5788. {
  5789. const uint8_t *bytes = _bytes;
  5790. uint8_t iv[PTLS_MAX_IV_SIZE];
  5791. ptls_aead_get_iv(ctx, iv);
  5792. for (size_t i = 0; i < len; ++i)
  5793. iv[i] ^= bytes[i];
  5794. ptls_aead_set_iv(ctx, iv);
  5795. }
  5796. void ptls_aead__build_iv(ptls_aead_algorithm_t *algo, uint8_t *iv, const uint8_t *static_iv, uint64_t seq)
  5797. {
  5798. size_t iv_size = algo->iv_size, i;
  5799. const uint8_t *s = static_iv;
  5800. uint8_t *d = iv;
  5801. /* build iv */
  5802. for (i = iv_size - 8; i != 0; --i)
  5803. *d++ = *s++;
  5804. i = 64;
  5805. do {
  5806. i -= 8;
  5807. *d++ = *s++ ^ (uint8_t)(seq >> i);
  5808. } while (i != 0);
  5809. }
  5810. static void clear_memory(void *p, size_t len)
  5811. {
  5812. if (len != 0)
  5813. memset(p, 0, len);
  5814. }
  5815. void (*volatile ptls_clear_memory)(void *p, size_t len) = clear_memory;
  5816. static int mem_equal(const void *_x, const void *_y, size_t len)
  5817. {
  5818. const volatile uint8_t *x = _x, *y = _y;
  5819. uint8_t t = 0;
  5820. for (; len != 0; --len)
  5821. t |= *x++ ^ *y++;
  5822. return t == 0;
  5823. }
  5824. int (*volatile ptls_mem_equal)(const void *x, const void *y, size_t len) = mem_equal;
  5825. static uint64_t get_time(ptls_get_time_t *self)
  5826. {
  5827. struct timeval tv;
  5828. gettimeofday(&tv, NULL);
  5829. return (uint64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
  5830. }
  5831. ptls_get_time_t ptls_get_time = {get_time};
  5832. int ptls_is_server(ptls_t *tls)
  5833. {
  5834. return tls->is_server;
  5835. }
  5836. struct st_ptls_raw_message_emitter_t {
  5837. ptls_message_emitter_t super;
  5838. size_t start_off;
  5839. size_t *epoch_offsets;
  5840. };
  5841. static int begin_raw_message(ptls_message_emitter_t *_self)
  5842. {
  5843. struct st_ptls_raw_message_emitter_t *self = (void *)_self;
  5844. self->start_off = self->super.buf->off;
  5845. return 0;
  5846. }
  5847. static int commit_raw_message(ptls_message_emitter_t *_self)
  5848. {
  5849. struct st_ptls_raw_message_emitter_t *self = (void *)_self;
  5850. size_t epoch;
  5851. /* epoch is the key epoch, with the only exception being 2nd CH generated after 0-RTT key */
  5852. epoch = self->super.enc->epoch;
  5853. if (epoch == 1 && self->super.buf->base[self->start_off] == PTLS_HANDSHAKE_TYPE_CLIENT_HELLO)
  5854. epoch = 0;
  5855. for (++epoch; epoch < 5; ++epoch) {
  5856. assert(self->epoch_offsets[epoch] == self->start_off);
  5857. self->epoch_offsets[epoch] = self->super.buf->off;
  5858. }
  5859. self->start_off = SIZE_MAX;
  5860. return 0;
  5861. }
  5862. size_t ptls_get_read_epoch(ptls_t *tls)
  5863. {
  5864. switch (tls->state) {
  5865. case PTLS_STATE_CLIENT_HANDSHAKE_START:
  5866. case PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO:
  5867. case PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO:
  5868. case PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO:
  5869. case PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO:
  5870. return 0; /* plaintext */
  5871. case PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA:
  5872. assert(!tls->ctx->omit_end_of_early_data);
  5873. return 1; /* 0-rtt */
  5874. case PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS:
  5875. case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE:
  5876. case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE:
  5877. case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY:
  5878. case PTLS_STATE_CLIENT_EXPECT_FINISHED:
  5879. case PTLS_STATE_SERVER_GENERATING_CERTIFICATE_VERIFY:
  5880. case PTLS_STATE_SERVER_EXPECT_CERTIFICATE:
  5881. case PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY:
  5882. case PTLS_STATE_SERVER_EXPECT_FINISHED:
  5883. return 2; /* handshake */
  5884. case PTLS_STATE_CLIENT_POST_HANDSHAKE:
  5885. case PTLS_STATE_SERVER_POST_HANDSHAKE:
  5886. return 3; /* 1-rtt */
  5887. default:
  5888. assert(!"invalid state");
  5889. return SIZE_MAX;
  5890. }
  5891. }
  5892. int ptls_handle_message(ptls_t *tls, ptls_buffer_t *sendbuf, size_t epoch_offsets[5], size_t in_epoch, const void *input,
  5893. size_t inlen, ptls_handshake_properties_t *properties)
  5894. {
  5895. return tls->is_server ? ptls_server_handle_message(tls, sendbuf, epoch_offsets, in_epoch, input, inlen, properties)
  5896. : ptls_client_handle_message(tls, sendbuf, epoch_offsets, in_epoch, input, inlen, properties);
  5897. }
  5898. int ptls_client_handle_message(ptls_t *tls, ptls_buffer_t *sendbuf, size_t epoch_offsets[5], size_t in_epoch, const void *input,
  5899. size_t inlen, ptls_handshake_properties_t *properties)
  5900. {
  5901. assert(!tls->is_server);
  5902. struct st_ptls_raw_message_emitter_t emitter = {
  5903. {sendbuf, &tls->traffic_protection.enc, 0, begin_raw_message, commit_raw_message}, SIZE_MAX, epoch_offsets};
  5904. struct st_ptls_record_t rec = {PTLS_CONTENT_TYPE_HANDSHAKE, 0, inlen, input};
  5905. if (input == NULL)
  5906. return send_client_hello(tls, &emitter.super, properties, NULL);
  5907. if (ptls_get_read_epoch(tls) != in_epoch)
  5908. return PTLS_ALERT_UNEXPECTED_MESSAGE;
  5909. return handle_handshake_record(tls, handle_client_handshake_message, &emitter.super, &rec, properties);
  5910. }
  5911. int ptls_server_handle_message(ptls_t *tls, ptls_buffer_t *sendbuf, size_t epoch_offsets[5], size_t in_epoch, const void *input,
  5912. size_t inlen, ptls_handshake_properties_t *properties)
  5913. {
  5914. assert(tls->is_server);
  5915. struct st_ptls_raw_message_emitter_t emitter = {
  5916. {sendbuf, &tls->traffic_protection.enc, 0, begin_raw_message, commit_raw_message}, SIZE_MAX, epoch_offsets};
  5917. struct st_ptls_record_t rec = {PTLS_CONTENT_TYPE_HANDSHAKE, 0, inlen, input};
  5918. if (tls->state == PTLS_STATE_SERVER_GENERATING_CERTIFICATE_VERIFY) {
  5919. assert(input == NULL || inlen == 0);
  5920. return server_finish_handshake(tls, &emitter.super, 1, NULL);
  5921. }
  5922. assert(input != NULL);
  5923. if (ptls_get_read_epoch(tls) != in_epoch)
  5924. return PTLS_ALERT_UNEXPECTED_MESSAGE;
  5925. return handle_handshake_record(tls, handle_server_handshake_message, &emitter.super, &rec, properties);
  5926. }
  5927. /**
  5928. * checks if given name looks like an IP address
  5929. */
  5930. int ptls_server_name_is_ipaddr(const char *name)
  5931. {
  5932. #ifdef AF_INET
  5933. struct sockaddr_in sin;
  5934. if (inet_pton(AF_INET, name, &sin) == 1)
  5935. return 1;
  5936. #endif
  5937. #ifdef AF_INET6
  5938. struct sockaddr_in6 sin6;
  5939. if (inet_pton(AF_INET6, name, &sin6) == 1)
  5940. return 1;
  5941. #endif
  5942. return 0;
  5943. }
  5944. int ptls_ech_encode_config(ptls_buffer_t *buf, uint8_t config_id, ptls_hpke_kem_t *kem, ptls_iovec_t public_key,
  5945. ptls_hpke_cipher_suite_t **ciphers, uint8_t max_name_length, const char *public_name)
  5946. {
  5947. int ret;
  5948. ptls_buffer_push16(buf, PTLS_ECH_CONFIG_VERSION);
  5949. ptls_buffer_push_block(buf, 2, {
  5950. ptls_buffer_push(buf, config_id);
  5951. ptls_buffer_push16(buf, kem->id);
  5952. ptls_buffer_push_block(buf, 2, { ptls_buffer_pushv(buf, public_key.base, public_key.len); });
  5953. ptls_buffer_push_block(buf, 2, {
  5954. for (size_t i = 0; ciphers[i] != NULL; ++i) {
  5955. ptls_buffer_push16(buf, ciphers[i]->id.kdf);
  5956. ptls_buffer_push16(buf, ciphers[i]->id.aead);
  5957. }
  5958. });
  5959. ptls_buffer_push(buf, max_name_length);
  5960. ptls_buffer_push_block(buf, 1, { ptls_buffer_pushv(buf, public_name, strlen(public_name)); });
  5961. ptls_buffer_push_block(buf, 2, {/* extensions */});
  5962. });
  5963. Exit:
  5964. return ret;
  5965. }
  5966. static char *byte_to_hex(char *dst, uint8_t v)
  5967. {
  5968. *dst++ = "0123456789abcdef"[v >> 4];
  5969. *dst++ = "0123456789abcdef"[v & 0xf];
  5970. return dst;
  5971. }
  5972. char *ptls_hexdump(char *dst, const void *_src, size_t len)
  5973. {
  5974. char *buf = dst;
  5975. const uint8_t *src = _src;
  5976. for (size_t i = 0; i != len; ++i)
  5977. dst = byte_to_hex(dst, src[i]);
  5978. *dst = '\0';
  5979. return buf;
  5980. }
  5981. char *ptls_jsonescape(char *buf, const char *unsafe_str, size_t len)
  5982. {
  5983. char *dst = buf;
  5984. const uint8_t *src = (const uint8_t *)unsafe_str, *end = src + len;
  5985. for (; src != end; ++src) {
  5986. switch (*src) {
  5987. #define MAP(ch, escaped) \
  5988. case ch: \
  5989. memcpy(dst, (escaped), sizeof(escaped) - 1); \
  5990. dst += sizeof(escaped) - 1; \
  5991. break
  5992. MAP('"', "\\\"");
  5993. MAP('\\', "\\\\");
  5994. MAP('/', "\\/");
  5995. MAP('\b', "\\b");
  5996. MAP('\f', "\\f");
  5997. MAP('\n', "\\n");
  5998. MAP('\r', "\\r");
  5999. MAP('\t', "\\t");
  6000. #undef MAP
  6001. default:
  6002. if (*src < 0x20 || *src == 0x7f) {
  6003. *dst++ = '\\';
  6004. *dst++ = 'u';
  6005. *dst++ = '0';
  6006. *dst++ = '0';
  6007. dst = byte_to_hex(dst, *src);
  6008. } else {
  6009. *dst++ = *src;
  6010. }
  6011. break;
  6012. }
  6013. }
  6014. *dst = '\0';
  6015. return dst;
  6016. }
  6017. void ptls_build_v4_mapped_v6_address(struct in6_addr *v6, const struct in_addr *v4)
  6018. {
  6019. *v6 = (struct in6_addr){.s6_addr[10] = 0xff, .s6_addr[11] = 0xff};
  6020. memcpy(&v6->s6_addr[12], &v4->s_addr, 4);
  6021. }
  6022. struct st_ptls_log_t ptls_log = {
  6023. .dummy_conn_state = {.random_ = 1 /* never log */},
  6024. ._generation = 1, /* starts from 1 so that recalc can be forced by setting to zero (i.e., the initial) */
  6025. };
  6026. PTLS_THREADLOCAL ptls_log_conn_state_t *ptls_log_conn_state_override = NULL;
  6027. #if PTLS_HAVE_LOG
  6028. static struct {
  6029. /**
  6030. * list of connections; the slot is connected if points != NULL
  6031. */
  6032. struct {
  6033. /**
  6034. * file descriptor
  6035. */
  6036. int fd;
  6037. /**
  6038. * see `ptls_log_add_fd`
  6039. */
  6040. char *points;
  6041. /**
  6042. *
  6043. */
  6044. char *snis;
  6045. /**
  6046. * list of addresses terminated by ip6addr_any
  6047. */
  6048. struct in6_addr *addresses;
  6049. /**
  6050. *
  6051. */
  6052. float sample_ratio;
  6053. /**
  6054. *
  6055. */
  6056. unsigned appdata : 1;
  6057. } conns[sizeof(((struct st_ptls_log_state_t *)NULL)->active_conns) * 8];
  6058. /**
  6059. * counts the number of writes that failed
  6060. */
  6061. size_t num_lost;
  6062. /**
  6063. * anchor of the single-linked list of log points; the tail refers to itself (i.e., point->next == point)
  6064. */
  6065. struct st_ptls_log_point_t *points;
  6066. /**
  6067. *
  6068. */
  6069. pthread_mutex_t mutex;
  6070. } logctx = {.mutex = PTHREAD_MUTEX_INITIALIZER};
  6071. static PTLS_THREADLOCAL struct {
  6072. ptls_buffer_t buf; /* buf.base == NULL upon failre */
  6073. char smallbuf[128];
  6074. struct {
  6075. char buf[sizeof(",\"tid\":-9223372036854775808")];
  6076. size_t len;
  6077. } tid;
  6078. } logbuf;
  6079. static void close_log_fd(size_t slot)
  6080. {
  6081. assert(logctx.conns[slot].fd >= 0 && logctx.conns[slot].points != NULL);
  6082. close(logctx.conns[slot].fd);
  6083. /* clear the connection information */
  6084. logctx.conns[slot].fd = -1;
  6085. logctx.conns[slot].sample_ratio = 0;
  6086. free(logctx.conns[slot].points);
  6087. logctx.conns[slot].points = NULL;
  6088. free(logctx.conns[slot].snis);
  6089. logctx.conns[slot].snis = NULL;
  6090. free(logctx.conns[slot].addresses);
  6091. logctx.conns[slot].addresses = NULL;
  6092. logctx.conns[slot].appdata = 0;
  6093. ++ptls_log._generation;
  6094. }
  6095. static char *duplicate_stringlist(const char *input)
  6096. {
  6097. if (input == NULL)
  6098. return strdup("");
  6099. char *result;
  6100. const char *in_tail;
  6101. for (in_tail = input; in_tail[0] != '\0'; in_tail += strlen(in_tail) + 1)
  6102. ;
  6103. ++in_tail;
  6104. if ((result = malloc(in_tail - input)) == NULL)
  6105. return NULL;
  6106. memcpy(result, input, in_tail - input);
  6107. return result;
  6108. }
  6109. static int is_in_stringlist(const char *list, const char *search_for)
  6110. {
  6111. if (list[0] == '\0')
  6112. return 1;
  6113. if (search_for == NULL)
  6114. return 0;
  6115. for (const char *element = list; element[0] != '\0'; element += strlen(element) + 1)
  6116. if (strcmp(element, search_for) == 0)
  6117. return 1;
  6118. return 0;
  6119. }
  6120. static int is_in_addresslist(const struct in6_addr *list, const struct in6_addr *search_for)
  6121. {
  6122. #define IS_EQUAL(x, y) (memcmp((x), (y), sizeof(struct in6_addr)) == 0)
  6123. if (IS_EQUAL(&list[0], &in6addr_any))
  6124. return 1;
  6125. if (IS_EQUAL(search_for, &in6addr_any))
  6126. return 0;
  6127. for (const struct in6_addr *element = list; !IS_EQUAL(element, &in6addr_any); ++element)
  6128. if (IS_EQUAL(element, search_for))
  6129. return 1;
  6130. return 0;
  6131. #undef IS_EQUAL
  6132. }
  6133. void ptls_log__recalc_point(int caller_locked, struct st_ptls_log_point_t *point)
  6134. {
  6135. if (!caller_locked)
  6136. pthread_mutex_lock(&logctx.mutex);
  6137. if (point->state.generation != ptls_log._generation) {
  6138. /* update active bitmap */
  6139. uint32_t new_active = 0;
  6140. for (size_t slot = 0; slot < PTLS_ELEMENTSOF(logctx.conns); ++slot)
  6141. if (logctx.conns[slot].points != NULL && is_in_stringlist(logctx.conns[slot].points, point->name))
  6142. new_active |= (uint32_t)1 << slot;
  6143. point->state.active_conns = new_active;
  6144. point->state.generation = ptls_log._generation;
  6145. }
  6146. if (!caller_locked)
  6147. pthread_mutex_unlock(&logctx.mutex);
  6148. }
  6149. void ptls_log__recalc_conn(int caller_locked, struct st_ptls_log_conn_state_t *conn, const char *(*get_sni)(void *),
  6150. void *get_sni_arg)
  6151. {
  6152. if (!caller_locked)
  6153. pthread_mutex_lock(&logctx.mutex);
  6154. if (conn->state.generation != ptls_log._generation) {
  6155. /* update active bitmap */
  6156. uint32_t new_active = 0;
  6157. const char *sni = get_sni != NULL ? get_sni(get_sni_arg) : NULL;
  6158. for (size_t slot = 0; slot < PTLS_ELEMENTSOF(logctx.conns); ++slot) {
  6159. if (logctx.conns[slot].points != NULL && conn->random_ < logctx.conns[slot].sample_ratio &&
  6160. is_in_stringlist(logctx.conns[slot].snis, sni) && is_in_addresslist(logctx.conns[slot].addresses, &conn->address)) {
  6161. new_active |= (uint32_t)1 << slot;
  6162. }
  6163. }
  6164. conn->state.active_conns = new_active;
  6165. conn->state.generation = ptls_log._generation;
  6166. }
  6167. if (!caller_locked)
  6168. pthread_mutex_unlock(&logctx.mutex);
  6169. }
  6170. static int expand_logbuf_or_invalidate(const char *prefix, size_t prefix_len, size_t capacity)
  6171. {
  6172. if (logbuf.buf.base == NULL)
  6173. return 0;
  6174. if (ptls_buffer_reserve(&logbuf.buf, prefix_len + capacity) != 0) {
  6175. ptls_buffer_dispose(&logbuf.buf);
  6176. assert(logbuf.buf.base == NULL);
  6177. return 0;
  6178. }
  6179. memcpy(logbuf.buf.base + logbuf.buf.off, prefix, prefix_len);
  6180. logbuf.buf.off += prefix_len;
  6181. return 1;
  6182. }
  6183. __attribute__((format(printf, 4, 5))) static void pushf_logbuf_or_invalidate(const char *prefix, size_t prefix_len, size_t capacity,
  6184. const char *fmt, ...)
  6185. {
  6186. if (!expand_logbuf_or_invalidate(prefix, prefix_len, capacity))
  6187. return;
  6188. va_list args;
  6189. va_start(args, fmt);
  6190. int l = vsnprintf((char *)logbuf.buf.base + logbuf.buf.off, logbuf.buf.capacity - logbuf.buf.off, fmt, args);
  6191. va_end(args);
  6192. assert(l < logbuf.buf.capacity - logbuf.buf.off && "insufficent capacity");
  6193. logbuf.buf.off += l;
  6194. }
  6195. void ptls_log__do_push_element_safestr(const char *prefix, size_t prefix_len, const char *s, size_t l)
  6196. {
  6197. if (expand_logbuf_or_invalidate(prefix, prefix_len, l + 2)) {
  6198. logbuf.buf.base[logbuf.buf.off++] = '"';
  6199. memcpy(logbuf.buf.base + logbuf.buf.off, s, l);
  6200. logbuf.buf.off += l;
  6201. logbuf.buf.base[logbuf.buf.off++] = '"';
  6202. }
  6203. }
  6204. void ptls_log__do_push_element_unsafestr(const char *prefix, size_t prefix_len, const char *s, size_t l)
  6205. {
  6206. if (expand_logbuf_or_invalidate(prefix, prefix_len, l * (sizeof("\\uXXXX") - 1) + 2)) {
  6207. logbuf.buf.base[logbuf.buf.off++] = '"';
  6208. logbuf.buf.off = (uint8_t *)ptls_jsonescape((char *)logbuf.buf.base + logbuf.buf.off, s, l) - logbuf.buf.base;
  6209. logbuf.buf.base[logbuf.buf.off++] = '"';
  6210. }
  6211. }
  6212. void ptls_log__do_push_element_hexdump(const char *prefix, size_t prefix_len, const void *s, size_t l)
  6213. {
  6214. if (expand_logbuf_or_invalidate(prefix, prefix_len, l * 2 + 2)) {
  6215. logbuf.buf.base[logbuf.buf.off++] = '"';
  6216. ptls_hexdump((char *)logbuf.buf.base + logbuf.buf.off, s, l);
  6217. logbuf.buf.off += l * 2;
  6218. logbuf.buf.base[logbuf.buf.off++] = '"';
  6219. }
  6220. }
  6221. void ptls_log__do_push_element_signed32(const char *prefix, size_t prefix_len, int32_t v)
  6222. {
  6223. pushf_logbuf_or_invalidate(prefix, prefix_len, sizeof("-2147483648"), "%" PRId32, v);
  6224. }
  6225. void ptls_log__do_push_element_signed64(const char *prefix, size_t prefix_len, int64_t v)
  6226. {
  6227. pushf_logbuf_or_invalidate(prefix, prefix_len, sizeof("-9223372036854775808"), "%" PRId64, v);
  6228. }
  6229. void ptls_log__do_push_element_unsigned32(const char *prefix, size_t prefix_len, uint32_t v)
  6230. {
  6231. pushf_logbuf_or_invalidate(prefix, prefix_len, sizeof("4294967295"), "%" PRIu32, v);
  6232. }
  6233. void ptls_log__do_push_element_unsigned64(const char *prefix, size_t prefix_len, uint64_t v)
  6234. {
  6235. pushf_logbuf_or_invalidate(prefix, prefix_len, sizeof("18446744073709551615"), "%" PRIu64, v);
  6236. }
  6237. void ptls_log__do_push_element_bool(const char *prefix, size_t prefix_len, int v)
  6238. {
  6239. if (expand_logbuf_or_invalidate(prefix, prefix_len, 5)) {
  6240. if (v) {
  6241. memcpy(logbuf.buf.base + logbuf.buf.off, "true", 4);
  6242. logbuf.buf.off += 4;
  6243. } else {
  6244. memcpy(logbuf.buf.base + logbuf.buf.off, "false", 5);
  6245. logbuf.buf.off += 5;
  6246. }
  6247. }
  6248. }
  6249. void ptls_log__do_write_start(struct st_ptls_log_point_t *point, int add_time)
  6250. {
  6251. assert(logbuf.buf.base == NULL);
  6252. ptls_buffer_init(&logbuf.buf, logbuf.smallbuf, sizeof(logbuf.smallbuf));
  6253. /* add module and type name */
  6254. const char *colon_at = strchr(point->name, ':');
  6255. int written = snprintf((char *)logbuf.buf.base, logbuf.buf.capacity, "{\"module\":\"%.*s\",\"type\":\"%s\"",
  6256. (int)(colon_at - point->name), point->name, colon_at + 1);
  6257. /* obtain and stringify thread id once */
  6258. if (logbuf.tid.len == 0) {
  6259. #if defined(__linux__)
  6260. logbuf.tid.len = sprintf(logbuf.tid.buf, ",\"tid\":%" PRId64, (int64_t)syscall(SYS_gettid));
  6261. #elif defined(__APPLE__)
  6262. uint64_t t = 0;
  6263. (void)pthread_threadid_np(NULL, &t);
  6264. logbuf.tid.len = sprintf(logbuf.tid.buf, ",\"tid\":%" PRIu64, t);
  6265. #else
  6266. /* other platforms: skip emitting tid, by keeping logbuf.tid.len == 0 */
  6267. #endif
  6268. }
  6269. /* append tid */
  6270. assert(written > 0 && written + logbuf.tid.len < logbuf.buf.capacity);
  6271. memcpy((char *)logbuf.buf.base + written, logbuf.tid.buf, logbuf.tid.len + 1);
  6272. written += logbuf.tid.len;
  6273. /* append time if requested */
  6274. if (add_time) {
  6275. struct timeval tv;
  6276. gettimeofday(&tv, NULL);
  6277. written += snprintf((char *)logbuf.buf.base + written, logbuf.buf.capacity - written, ",\"time\":%" PRIu64,
  6278. (uint64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000);
  6279. }
  6280. assert(written > 0 && written < logbuf.buf.capacity && "caller MUST provide smallbuf suffient to emit the prefix");
  6281. logbuf.buf.off = (size_t)written;
  6282. }
  6283. int ptls_log__do_write_end(struct st_ptls_log_point_t *point, struct st_ptls_log_conn_state_t *conn, const char *(*get_sni)(void *),
  6284. void *get_sni_arg, int includes_appdata)
  6285. {
  6286. if (!expand_logbuf_or_invalidate("}\n", 2, 0))
  6287. return 0;
  6288. int needs_appdata = 0;
  6289. pthread_mutex_lock(&logctx.mutex);
  6290. /* calc the active conn bits, updating stale information if necessary */
  6291. if (point->state.generation != ptls_log._generation)
  6292. ptls_log__recalc_point(1, point);
  6293. uint32_t active = point->state.active_conns;
  6294. if (conn != NULL && conn->state.generation != ptls_log._generation) {
  6295. ptls_log__recalc_conn(1, conn, get_sni, get_sni_arg);
  6296. active &= conn->state.active_conns;
  6297. }
  6298. /* iterate through the active connctions */
  6299. for (size_t slot = 0; active != 0; ++slot, active >>= 1) {
  6300. if ((active & 1) == 0)
  6301. continue;
  6302. assert(logctx.conns[slot].points != NULL);
  6303. if (logctx.conns[slot].appdata != includes_appdata) {
  6304. if (!includes_appdata && ptls_log.may_include_appdata)
  6305. needs_appdata = 1;
  6306. continue;
  6307. }
  6308. /* write */
  6309. ssize_t wret;
  6310. while ((wret = write(logctx.conns[slot].fd, logbuf.buf.base, logbuf.buf.off)) == -1 && errno == EINTR)
  6311. ;
  6312. if (wret == logbuf.buf.off) {
  6313. /* success */
  6314. } else if (wret > 0 || (wret == -1 && (errno == EAGAIN || errno == EWOULDBLOCK))) {
  6315. /* partial write or buffer full */
  6316. ++logctx.num_lost;
  6317. } else {
  6318. /* write error; close and unregister the connection */
  6319. close_log_fd(slot);
  6320. }
  6321. }
  6322. pthread_mutex_unlock(&logctx.mutex);
  6323. if (includes_appdata)
  6324. assert(!needs_appdata);
  6325. ptls_buffer_dispose(&logbuf.buf);
  6326. assert(logbuf.buf.base == NULL);
  6327. return needs_appdata;
  6328. }
  6329. #endif
  6330. void ptls_log_init_conn_state(ptls_log_conn_state_t *state, void (*random_bytes)(void *, size_t))
  6331. {
  6332. uint32_t r;
  6333. random_bytes(&r, sizeof(r));
  6334. *state = (ptls_log_conn_state_t){
  6335. .random_ = (float)r / ((uint64_t)UINT32_MAX + 1), /* [0..1), so that any(r) < sample_ratio where sample_ratio is [0..1] */
  6336. .address = in6addr_any,
  6337. };
  6338. }
  6339. size_t ptls_log_num_lost(void)
  6340. {
  6341. #if PTLS_HAVE_LOG
  6342. return logctx.num_lost;
  6343. #else
  6344. return 0;
  6345. #endif
  6346. }
  6347. int ptls_log_add_fd(int fd, float sample_ratio, const char *_points, const char *_snis, const char *_addresses, int appdata)
  6348. {
  6349. #if PTLS_HAVE_LOG
  6350. char *points = NULL, *snis = NULL;
  6351. struct in6_addr *addresses = NULL;
  6352. int ret;
  6353. pthread_mutex_lock(&logctx.mutex);
  6354. if ((points = duplicate_stringlist(_points)) == NULL) {
  6355. ret = PTLS_ERROR_NO_MEMORY;
  6356. goto Exit;
  6357. }
  6358. if ((snis = duplicate_stringlist(_snis)) == NULL) {
  6359. ret = PTLS_ERROR_NO_MEMORY;
  6360. goto Exit;
  6361. }
  6362. {
  6363. size_t num_addresses = 0;
  6364. for (const char *input = _addresses; input != NULL && *input != '\0'; input += strlen(input) + 1)
  6365. ++num_addresses;
  6366. if ((addresses = malloc(sizeof(*addresses) * (num_addresses + 1))) == NULL) {
  6367. ret = PTLS_ERROR_NO_MEMORY;
  6368. goto Exit;
  6369. }
  6370. size_t index = 0;
  6371. for (const char *input = _addresses; input != NULL && *input != '\0'; input += strlen(input) + 1) {
  6372. /* note: for consistency to the handling of points, erroneous input is ignored. V4 addresses will use the mapped form
  6373. * (::ffff:192.0.2.1) */
  6374. if (!inet_pton(AF_INET6, input, &addresses[index])) {
  6375. struct in_addr v4;
  6376. if (!inet_pton(AF_INET, input, &v4))
  6377. continue;
  6378. ptls_build_v4_mapped_v6_address(&addresses[index], &v4);
  6379. }
  6380. if (memcmp(&addresses[index], &in6addr_any, sizeof(struct in6_addr)) == 0)
  6381. continue;
  6382. ++index;
  6383. }
  6384. addresses[index] = in6addr_any;
  6385. }
  6386. /* find slot, or return if not available */
  6387. size_t slot_index;
  6388. for (slot_index = 0; slot_index < PTLS_ELEMENTSOF(logctx.conns); ++slot_index)
  6389. if (logctx.conns[slot_index].points == NULL)
  6390. break;
  6391. if (slot_index == PTLS_ELEMENTSOF(logctx.conns)) {
  6392. ret = PTLS_ERROR_NO_MEMORY;
  6393. goto Exit;
  6394. }
  6395. /* setup the slot */
  6396. logctx.conns[slot_index].fd = fd;
  6397. logctx.conns[slot_index].points = points;
  6398. logctx.conns[slot_index].snis = snis;
  6399. logctx.conns[slot_index].addresses = addresses;
  6400. logctx.conns[slot_index].sample_ratio = sample_ratio;
  6401. logctx.conns[slot_index].appdata = appdata;
  6402. ++ptls_log._generation;
  6403. ret = 0; /* success */
  6404. Exit:
  6405. pthread_mutex_unlock(&logctx.mutex);
  6406. if (ret != 0) {
  6407. free(points);
  6408. free(snis);
  6409. free(addresses);
  6410. }
  6411. return ret;
  6412. #else
  6413. return PTLS_ERROR_NOT_AVAILABLE;
  6414. #endif
  6415. }