tls13.c 387 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979
  1. /* tls13.c
  2. *
  3. * Copyright (C) 2006-2022 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. /*
  22. * BUILD_GCM
  23. * Enables AES-GCM ciphersuites.
  24. * HAVE_AESCCM
  25. * Enables AES-CCM ciphersuites.
  26. * HAVE_SESSION_TICKET
  27. * Enables session tickets - required for TLS 1.3 resumption.
  28. * NO_PSK
  29. * Do not enable Pre-Shared Keys.
  30. * HAVE_KEYING_MATERIAL
  31. * Enables exporting keying material based on section 7.5 of RFC 8446.
  32. * WOLFSSL_ASYNC_CRYPT
  33. * Enables the use of asynchronous cryptographic operations.
  34. * This is available for ciphers and certificates.
  35. * HAVE_CHACHA && HAVE_POLY1305
  36. * Enables use of CHACHA20-POLY1305 ciphersuites.
  37. * WOLFSSL_DEBUG_TLS
  38. * Writes out details of TLS 1.3 protocol including handshake message buffers
  39. * and key generation input and output.
  40. * WOLFSSL_EARLY_DATA
  41. * Allow 0-RTT Handshake using Early Data extensions and handshake message
  42. * WOLFSSL_EARLY_DATA_GROUP
  43. * Group EarlyData message with ClientHello when sending
  44. * WOLFSSL_NO_SERVER_GROUPS_EXT
  45. * Do not send the server's groups in an extension when the server's top
  46. * preference is not in client's list.
  47. * WOLFSSL_POST_HANDSHAKE_AUTH
  48. * Allow TLS v1.3 code to perform post-handshake authentication of the
  49. * client.
  50. * WOLFSSL_SEND_HRR_COOKIE
  51. * Send a cookie in hello_retry_request message to enable stateless tracking
  52. * of ClientHello replies.
  53. * WOLFSSL_TLS13
  54. * Enable TLS 1.3 protocol implementation.
  55. * WOLFSSL_TLS13_MIDDLEBOX_COMPAT
  56. * Enable middlebox compatibility in the TLS 1.3 handshake.
  57. * This includes sending ChangeCipherSpec before encrypted messages and
  58. * including a session id.
  59. * WOLFSSL_TLS13_SHA512
  60. * Allow generation of SHA-512 digests in handshake - no ciphersuite
  61. * requires SHA-512 at this time.
  62. * WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
  63. * Allow a NewSessionTicket message to be sent by server before Client's
  64. * Finished message.
  65. * See TLS v1.3 specification, Section 4.6.1, Paragraph 4 (Note).
  66. * WOLFSSL_PSK_ONE_ID
  67. * When only one PSK ID is used and only one call to the PSK callback can
  68. * be made per connect.
  69. * You cannot use wc_psk_client_cs_callback type callback on client.
  70. * WOLFSSL_CHECK_ALERT_ON_ERR
  71. * Check for alerts during the handshake in the event of an error.
  72. * WOLFSSL_NO_CLIENT_CERT_ERROR
  73. * Requires client to set a client certificate
  74. * WOLFSSL_PSK_MULTI_ID_PER_CS
  75. * When multiple PSK identities are available for the same cipher suite.
  76. * Sets the first byte of the client identity to the count of identites
  77. * that have been seen so far for the cipher suite.
  78. */
  79. #ifdef HAVE_CONFIG_H
  80. #include <config.h>
  81. #endif
  82. #include <wolfssl/wolfcrypt/settings.h>
  83. #ifdef WOLFSSL_TLS13
  84. #ifdef HAVE_SESSION_TICKET
  85. #include <wolfssl/wolfcrypt/wc_port.h>
  86. #endif
  87. #ifndef WOLFCRYPT_ONLY
  88. #ifdef HAVE_ERRNO_H
  89. #include <errno.h>
  90. #endif
  91. #if defined(__MACH__) || defined(__FreeBSD__)
  92. #include <sys/time.h>
  93. #endif /* __MACH__ || __FreeBSD__ */
  94. #include <wolfssl/internal.h>
  95. #include <wolfssl/error-ssl.h>
  96. #include <wolfssl/wolfcrypt/asn.h>
  97. #include <wolfssl/wolfcrypt/dh.h>
  98. #include <wolfssl/wolfcrypt/kdf.h>
  99. #ifdef NO_INLINE
  100. #include <wolfssl/wolfcrypt/misc.h>
  101. #else
  102. #define WOLFSSL_MISC_INCLUDED
  103. #include <wolfcrypt/src/misc.c>
  104. #endif
  105. #ifdef __sun
  106. #include <sys/filio.h>
  107. #endif
  108. #ifndef TRUE
  109. #define TRUE 1
  110. #endif
  111. #ifndef FALSE
  112. #define FALSE 0
  113. #endif
  114. #ifndef HAVE_HKDF
  115. #ifndef _MSC_VER
  116. #error "The build option HAVE_HKDF is required for TLS 1.3"
  117. #else
  118. #pragma message("error: The build option HAVE_HKDF is required for TLS 1.3")
  119. #endif
  120. #endif
  121. #ifndef HAVE_TLS_EXTENSIONS
  122. #ifndef _MSC_VER
  123. #error "The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3"
  124. #else
  125. #pragma message("error: The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3")
  126. #endif
  127. #endif
  128. /* Set ret to error value and jump to label.
  129. *
  130. * err The error value to set.
  131. * eLabel The label to jump to.
  132. */
  133. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  134. /* Size of the TLS v1.3 label use when deriving keys. */
  135. #define TLS13_PROTOCOL_LABEL_SZ 6
  136. /* The protocol label for TLS v1.3. */
  137. static const byte tls13ProtocolLabel[TLS13_PROTOCOL_LABEL_SZ + 1] = "tls13 ";
  138. #ifdef WOLFSSL_DTLS13
  139. #define DTLS13_PROTOCOL_LABEL_SZ 6
  140. static const byte dtls13ProtocolLabel[DTLS13_PROTOCOL_LABEL_SZ + 1] = "dtls13";
  141. #endif /* WOLFSSL_DTLS13 */
  142. /* Derive a key from a message.
  143. *
  144. * ssl The SSL/TLS object.
  145. * output The buffer to hold the derived key.
  146. * outputLen The length of the derived key.
  147. * secret The secret used to derive the key (HMAC secret).
  148. * label The label used to distinguish the context.
  149. * labelLen The length of the label.
  150. * msg The message data to derive key from.
  151. * msgLen The length of the message data to derive key from.
  152. * hashAlgo The hash algorithm to use in the HMAC.
  153. * returns 0 on success, otherwise failure.
  154. */
  155. static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen,
  156. const byte* secret, const byte* label, word32 labelLen,
  157. byte* msg, int msgLen, int hashAlgo)
  158. {
  159. byte hash[WC_MAX_DIGEST_SIZE];
  160. Digest digest;
  161. word32 hashSz = 0;
  162. const byte* protocol;
  163. word32 protocolLen;
  164. int digestAlg = -1;
  165. int ret = BAD_FUNC_ARG;
  166. switch (hashAlgo) {
  167. #ifndef NO_WOLFSSL_SHA256
  168. case sha256_mac:
  169. ret = wc_InitSha256_ex(&digest.sha256, ssl->heap, INVALID_DEVID);
  170. if (ret == 0) {
  171. ret = wc_Sha256Update(&digest.sha256, msg, msgLen);
  172. if (ret == 0)
  173. ret = wc_Sha256Final(&digest.sha256, hash);
  174. wc_Sha256Free(&digest.sha256);
  175. }
  176. hashSz = WC_SHA256_DIGEST_SIZE;
  177. digestAlg = WC_SHA256;
  178. break;
  179. #endif
  180. #ifdef WOLFSSL_SHA384
  181. case sha384_mac:
  182. ret = wc_InitSha384_ex(&digest.sha384, ssl->heap, INVALID_DEVID);
  183. if (ret == 0) {
  184. ret = wc_Sha384Update(&digest.sha384, msg, msgLen);
  185. if (ret == 0)
  186. ret = wc_Sha384Final(&digest.sha384, hash);
  187. wc_Sha384Free(&digest.sha384);
  188. }
  189. hashSz = WC_SHA384_DIGEST_SIZE;
  190. digestAlg = WC_SHA384;
  191. break;
  192. #endif
  193. #ifdef WOLFSSL_TLS13_SHA512
  194. case sha512_mac:
  195. ret = wc_InitSha512_ex(&digest.sha512, ssl->heap, INVALID_DEVID);
  196. if (ret == 0) {
  197. ret = wc_Sha512Update(&digest.sha512, msg, msgLen);
  198. if (ret == 0)
  199. ret = wc_Sha512Final(&digest.sha512, hash);
  200. wc_Sha512Free(&digest.sha512);
  201. }
  202. hashSz = WC_SHA512_DIGEST_SIZE;
  203. digestAlg = WC_SHA512;
  204. break;
  205. #endif
  206. default:
  207. digestAlg = -1;
  208. break;
  209. }
  210. if (digestAlg < 0)
  211. return HASH_TYPE_E;
  212. if (ret != 0)
  213. return ret;
  214. switch (ssl->version.minor) {
  215. case TLSv1_3_MINOR:
  216. protocol = tls13ProtocolLabel;
  217. protocolLen = TLS13_PROTOCOL_LABEL_SZ;
  218. break;
  219. #ifdef WOLFSSL_DTLS13
  220. case DTLSv1_3_MINOR:
  221. if (!ssl->options.dtls)
  222. return VERSION_ERROR;
  223. protocol = dtls13ProtocolLabel;
  224. protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
  225. break;
  226. #endif /* WOLFSSL_DTLS13 */
  227. default:
  228. return VERSION_ERROR;
  229. }
  230. if (outputLen == -1)
  231. outputLen = hashSz;
  232. PRIVATE_KEY_UNLOCK();
  233. ret = wc_Tls13_HKDF_Expand_Label(output, outputLen, secret, hashSz,
  234. protocol, protocolLen, label, labelLen,
  235. hash, hashSz, digestAlg);
  236. PRIVATE_KEY_LOCK();
  237. return ret;
  238. }
  239. /* Derive a key.
  240. *
  241. * ssl The SSL/TLS object.
  242. * output The buffer to hold the derived key.
  243. * outputLen The length of the derived key.
  244. * secret The secret used to derive the key (HMAC secret).
  245. * label The label used to distinguish the context.
  246. * labelLen The length of the label.
  247. * hashAlgo The hash algorithm to use in the HMAC.
  248. * includeMsgs Whether to include a hash of the handshake messages so far.
  249. * returns 0 on success, otherwise failure.
  250. */
  251. int Tls13DeriveKey(WOLFSSL* ssl, byte* output, int outputLen,
  252. const byte* secret, const byte* label, word32 labelLen,
  253. int hashAlgo, int includeMsgs)
  254. {
  255. int ret = 0;
  256. byte hash[WC_MAX_DIGEST_SIZE];
  257. word32 hashSz = 0;
  258. word32 hashOutSz = 0;
  259. const byte* protocol;
  260. word32 protocolLen;
  261. int digestAlg = 0;
  262. switch (hashAlgo) {
  263. #ifndef NO_SHA256
  264. case sha256_mac:
  265. hashSz = WC_SHA256_DIGEST_SIZE;
  266. digestAlg = WC_SHA256;
  267. if (includeMsgs)
  268. ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
  269. break;
  270. #endif
  271. #ifdef WOLFSSL_SHA384
  272. case sha384_mac:
  273. hashSz = WC_SHA384_DIGEST_SIZE;
  274. digestAlg = WC_SHA384;
  275. if (includeMsgs)
  276. ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
  277. break;
  278. #endif
  279. #ifdef WOLFSSL_TLS13_SHA512
  280. case sha512_mac:
  281. hashSz = WC_SHA512_DIGEST_SIZE;
  282. digestAlg = WC_SHA512;
  283. if (includeMsgs)
  284. ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
  285. break;
  286. #endif
  287. default:
  288. ret = HASH_TYPE_E;
  289. break;
  290. }
  291. if (ret != 0)
  292. return ret;
  293. protocol = tls13ProtocolLabel;
  294. protocolLen = TLS13_PROTOCOL_LABEL_SZ;
  295. #ifdef WOLFSSL_DTLS13
  296. if (ssl->options.dtls) {
  297. protocol = dtls13ProtocolLabel;
  298. protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
  299. }
  300. #endif /* WOLFSSL_DTLS13 */
  301. if (outputLen == -1)
  302. outputLen = hashSz;
  303. if (includeMsgs)
  304. hashOutSz = hashSz;
  305. /* hash buffer may not be fully initialized, but the sending length won't
  306. * extend beyond the initialized span.
  307. */
  308. PRAGMA_GCC_DIAG_PUSH;
  309. PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"");
  310. PRIVATE_KEY_UNLOCK();
  311. #if defined(HAVE_FIPS) && defined(wc_Tls13_HKDF_Expand_Label)
  312. ret = wc_Tls13_HKDF_Expand_Label_fips(output, outputLen, secret, hashSz,
  313. protocol, protocolLen, label, labelLen,
  314. hash, hashOutSz, digestAlg);
  315. #else
  316. ret = wc_Tls13_HKDF_Expand_Label(output, outputLen, secret, hashSz,
  317. protocol, protocolLen, label, labelLen,
  318. hash, hashOutSz, digestAlg);
  319. #endif
  320. PRIVATE_KEY_LOCK();
  321. #ifdef WOLFSSL_CHECK_MEM_ZERO
  322. wc_MemZero_Add("TLS 1.3 derived key", output, outputLen);
  323. #endif
  324. return ret;
  325. PRAGMA_GCC_DIAG_POP;
  326. }
  327. /* Convert TLS mac ID to a hash algorithm ID
  328. *
  329. * mac Mac ID to convert
  330. * returns hash ID on success, or the NONE type.
  331. */
  332. static WC_INLINE int mac2hash(int mac)
  333. {
  334. int hash;
  335. switch (mac) {
  336. #ifndef NO_SHA256
  337. case sha256_mac:
  338. hash = WC_SHA256;
  339. break;
  340. #endif
  341. #ifdef WOLFSSL_SHA384
  342. case sha384_mac:
  343. hash = WC_SHA384;
  344. break;
  345. #endif
  346. #ifdef WOLFSSL_TLS13_SHA512
  347. case sha512_mac:
  348. hash = WC_SHA512;
  349. break;
  350. #endif
  351. default:
  352. hash = WC_HASH_TYPE_NONE;
  353. }
  354. return hash;
  355. }
  356. #ifndef NO_PSK
  357. /* The length of the binder key label. */
  358. #define BINDER_KEY_LABEL_SZ 10
  359. /* The binder key label. */
  360. static const byte binderKeyLabel[BINDER_KEY_LABEL_SZ + 1] =
  361. "ext binder";
  362. /* Derive the binder key.
  363. *
  364. * ssl The SSL/TLS object.
  365. * key The derived key.
  366. * returns 0 on success, otherwise failure.
  367. */
  368. static int DeriveBinderKey(WOLFSSL* ssl, byte* key)
  369. {
  370. WOLFSSL_MSG("Derive Binder Key");
  371. if (ssl == NULL || ssl->arrays == NULL) {
  372. return BAD_FUNC_ARG;
  373. }
  374. return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
  375. binderKeyLabel, BINDER_KEY_LABEL_SZ,
  376. NULL, 0, ssl->specs.mac_algorithm);
  377. }
  378. #endif /* !NO_PSK */
  379. #if defined(HAVE_SESSION_TICKET) && \
  380. (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
  381. /* The length of the binder key resume label. */
  382. #define BINDER_KEY_RESUME_LABEL_SZ 10
  383. /* The binder key resume label. */
  384. static const byte binderKeyResumeLabel[BINDER_KEY_RESUME_LABEL_SZ + 1] =
  385. "res binder";
  386. /* Derive the binder resumption key.
  387. *
  388. * ssl The SSL/TLS object.
  389. * key The derived key.
  390. * returns 0 on success, otherwise failure.
  391. */
  392. static int DeriveBinderKeyResume(WOLFSSL* ssl, byte* key)
  393. {
  394. WOLFSSL_MSG("Derive Binder Key - Resumption");
  395. if (ssl == NULL || ssl->arrays == NULL) {
  396. return BAD_FUNC_ARG;
  397. }
  398. return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
  399. binderKeyResumeLabel, BINDER_KEY_RESUME_LABEL_SZ,
  400. NULL, 0, ssl->specs.mac_algorithm);
  401. }
  402. #endif /* HAVE_SESSION_TICKET && (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) */
  403. #ifdef WOLFSSL_EARLY_DATA
  404. /* The length of the early traffic label. */
  405. #define EARLY_TRAFFIC_LABEL_SZ 11
  406. /* The early traffic label. */
  407. static const byte earlyTrafficLabel[EARLY_TRAFFIC_LABEL_SZ + 1] =
  408. "c e traffic";
  409. /* Derive the early traffic key.
  410. *
  411. * ssl The SSL/TLS object.
  412. * key The derived key.
  413. * returns 0 on success, otherwise failure.
  414. */
  415. static int DeriveEarlyTrafficSecret(WOLFSSL* ssl, byte* key)
  416. {
  417. int ret;
  418. WOLFSSL_MSG("Derive Early Traffic Secret");
  419. if (ssl == NULL || ssl->arrays == NULL) {
  420. return BAD_FUNC_ARG;
  421. }
  422. ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->secret,
  423. earlyTrafficLabel, EARLY_TRAFFIC_LABEL_SZ,
  424. ssl->specs.mac_algorithm, 1);
  425. #ifdef HAVE_SECRET_CALLBACK
  426. if (ret == 0 && ssl->tls13SecretCb != NULL) {
  427. ret = ssl->tls13SecretCb(ssl, CLIENT_EARLY_TRAFFIC_SECRET, key,
  428. ssl->specs.hash_size, ssl->tls13SecretCtx);
  429. if (ret != 0) {
  430. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  431. return TLS13_SECRET_CB_E;
  432. }
  433. }
  434. #ifdef OPENSSL_EXTRA
  435. if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
  436. ret = ssl->tls13KeyLogCb(ssl, CLIENT_EARLY_TRAFFIC_SECRET, key,
  437. ssl->specs.hash_size, NULL);
  438. if (ret != 0) {
  439. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  440. return TLS13_SECRET_CB_E;
  441. }
  442. }
  443. #endif /* OPENSSL_EXTRA */
  444. #endif /* HAVE_SECRET_CALLBACK */
  445. return ret;
  446. }
  447. #endif
  448. /* The length of the client handshake label. */
  449. #define CLIENT_HANDSHAKE_LABEL_SZ 12
  450. /* The client handshake label. */
  451. static const byte clientHandshakeLabel[CLIENT_HANDSHAKE_LABEL_SZ + 1] =
  452. "c hs traffic";
  453. /* Derive the client handshake key.
  454. *
  455. * ssl The SSL/TLS object.
  456. * key The derived key.
  457. * returns 0 on success, otherwise failure.
  458. */
  459. static int DeriveClientHandshakeSecret(WOLFSSL* ssl, byte* key)
  460. {
  461. int ret;
  462. WOLFSSL_MSG("Derive Client Handshake Secret");
  463. if (ssl == NULL || ssl->arrays == NULL) {
  464. return BAD_FUNC_ARG;
  465. }
  466. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_Ver >= 115)
  467. (void)key;
  468. ret = tsip_DeriveClientHandshakeSecret(ssl);
  469. if (ret != CRYPTOCB_UNAVAILABLE) {
  470. return ret;
  471. }
  472. #endif
  473. ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret,
  474. clientHandshakeLabel, CLIENT_HANDSHAKE_LABEL_SZ,
  475. ssl->specs.mac_algorithm, 1);
  476. #ifdef HAVE_SECRET_CALLBACK
  477. if (ret == 0 && ssl->tls13SecretCb != NULL) {
  478. ret = ssl->tls13SecretCb(ssl, CLIENT_HANDSHAKE_TRAFFIC_SECRET, key,
  479. ssl->specs.hash_size, ssl->tls13SecretCtx);
  480. if (ret != 0) {
  481. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  482. return TLS13_SECRET_CB_E;
  483. }
  484. }
  485. #ifdef OPENSSL_EXTRA
  486. if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
  487. ret = ssl->tls13KeyLogCb(ssl, CLIENT_HANDSHAKE_TRAFFIC_SECRET, key,
  488. ssl->specs.hash_size, NULL);
  489. if (ret != 0) {
  490. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  491. return TLS13_SECRET_CB_E;
  492. }
  493. }
  494. #endif /* OPENSSL_EXTRA */
  495. #endif /* HAVE_SECRET_CALLBACK */
  496. return ret;
  497. }
  498. /* The length of the server handshake label. */
  499. #define SERVER_HANDSHAKE_LABEL_SZ 12
  500. /* The server handshake label. */
  501. static const byte serverHandshakeLabel[SERVER_HANDSHAKE_LABEL_SZ + 1] =
  502. "s hs traffic";
  503. /* Derive the server handshake key.
  504. *
  505. * ssl The SSL/TLS object.
  506. * key The derived key.
  507. * returns 0 on success, otherwise failure.
  508. */
  509. static int DeriveServerHandshakeSecret(WOLFSSL* ssl, byte* key)
  510. {
  511. int ret;
  512. WOLFSSL_MSG("Derive Server Handshake Secret");
  513. if (ssl == NULL || ssl->arrays == NULL) {
  514. return BAD_FUNC_ARG;
  515. }
  516. ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret,
  517. serverHandshakeLabel, SERVER_HANDSHAKE_LABEL_SZ,
  518. ssl->specs.mac_algorithm, 1);
  519. #ifdef HAVE_SECRET_CALLBACK
  520. if (ret == 0 && ssl->tls13SecretCb != NULL) {
  521. ret = ssl->tls13SecretCb(ssl, SERVER_HANDSHAKE_TRAFFIC_SECRET, key,
  522. ssl->specs.hash_size, ssl->tls13SecretCtx);
  523. if (ret != 0) {
  524. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  525. return TLS13_SECRET_CB_E;
  526. }
  527. }
  528. #ifdef OPENSSL_EXTRA
  529. if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
  530. ret = ssl->tls13KeyLogCb(ssl, SERVER_HANDSHAKE_TRAFFIC_SECRET, key,
  531. ssl->specs.hash_size, NULL);
  532. if (ret != 0) {
  533. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  534. return TLS13_SECRET_CB_E;
  535. }
  536. }
  537. #endif /* OPENSSL_EXTRA */
  538. #endif /* HAVE_SECRET_CALLBACK */
  539. return ret;
  540. }
  541. /* The length of the client application traffic label. */
  542. #define CLIENT_APP_LABEL_SZ 12
  543. /* The client application traffic label. */
  544. static const byte clientAppLabel[CLIENT_APP_LABEL_SZ + 1] =
  545. "c ap traffic";
  546. /* Derive the client application traffic key.
  547. *
  548. * ssl The SSL/TLS object.
  549. * key The derived key.
  550. * returns 0 on success, otherwise failure.
  551. */
  552. static int DeriveClientTrafficSecret(WOLFSSL* ssl, byte* key)
  553. {
  554. int ret;
  555. WOLFSSL_MSG("Derive Client Traffic Secret");
  556. if (ssl == NULL || ssl->arrays == NULL) {
  557. return BAD_FUNC_ARG;
  558. }
  559. ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
  560. clientAppLabel, CLIENT_APP_LABEL_SZ,
  561. ssl->specs.mac_algorithm, 1);
  562. #ifdef HAVE_SECRET_CALLBACK
  563. if (ret == 0 && ssl->tls13SecretCb != NULL) {
  564. ret = ssl->tls13SecretCb(ssl, CLIENT_TRAFFIC_SECRET, key,
  565. ssl->specs.hash_size, ssl->tls13SecretCtx);
  566. if (ret != 0) {
  567. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  568. return TLS13_SECRET_CB_E;
  569. }
  570. }
  571. #ifdef OPENSSL_EXTRA
  572. if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
  573. ret = ssl->tls13KeyLogCb(ssl, CLIENT_TRAFFIC_SECRET, key,
  574. ssl->specs.hash_size, NULL);
  575. if (ret != 0) {
  576. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  577. return TLS13_SECRET_CB_E;
  578. }
  579. }
  580. #endif /* OPENSSL_EXTRA */
  581. #endif /* HAVE_SECRET_CALLBACK */
  582. return ret;
  583. }
  584. /* The length of the server application traffic label. */
  585. #define SERVER_APP_LABEL_SZ 12
  586. /* The server application traffic label. */
  587. static const byte serverAppLabel[SERVER_APP_LABEL_SZ + 1] =
  588. "s ap traffic";
  589. /* Derive the server application traffic key.
  590. *
  591. * ssl The SSL/TLS object.
  592. * key The derived key.
  593. * returns 0 on success, otherwise failure.
  594. */
  595. static int DeriveServerTrafficSecret(WOLFSSL* ssl, byte* key)
  596. {
  597. int ret;
  598. WOLFSSL_MSG("Derive Server Traffic Secret");
  599. if (ssl == NULL || ssl->arrays == NULL) {
  600. return BAD_FUNC_ARG;
  601. }
  602. ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
  603. serverAppLabel, SERVER_APP_LABEL_SZ,
  604. ssl->specs.mac_algorithm, 1);
  605. #ifdef HAVE_SECRET_CALLBACK
  606. if (ret == 0 && ssl->tls13SecretCb != NULL) {
  607. ret = ssl->tls13SecretCb(ssl, SERVER_TRAFFIC_SECRET, key,
  608. ssl->specs.hash_size, ssl->tls13SecretCtx);
  609. if (ret != 0) {
  610. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  611. return TLS13_SECRET_CB_E;
  612. }
  613. }
  614. #ifdef OPENSSL_EXTRA
  615. if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
  616. ret = ssl->tls13KeyLogCb(ssl, SERVER_TRAFFIC_SECRET, key,
  617. ssl->specs.hash_size, NULL);
  618. if (ret != 0) {
  619. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  620. return TLS13_SECRET_CB_E;
  621. }
  622. }
  623. #endif /* OPENSSL_EXTRA */
  624. #endif /* HAVE_SECRET_CALLBACK */
  625. return ret;
  626. }
  627. #ifdef HAVE_KEYING_MATERIAL
  628. /* The length of the exporter master secret label. */
  629. #define EXPORTER_MASTER_LABEL_SZ 10
  630. /* The exporter master secret label. */
  631. static const byte exporterMasterLabel[EXPORTER_MASTER_LABEL_SZ + 1] =
  632. "exp master";
  633. /* Derive the exporter secret.
  634. *
  635. * ssl The SSL/TLS object.
  636. * key The derived key.
  637. * returns 0 on success, otherwise failure.
  638. */
  639. static int DeriveExporterSecret(WOLFSSL* ssl, byte* key)
  640. {
  641. int ret;
  642. WOLFSSL_ENTER("Derive Exporter Secret");
  643. if (ssl == NULL || ssl->arrays == NULL) {
  644. return BAD_FUNC_ARG;
  645. }
  646. ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
  647. exporterMasterLabel, EXPORTER_MASTER_LABEL_SZ,
  648. ssl->specs.mac_algorithm, 1);
  649. #ifdef HAVE_SECRET_CALLBACK
  650. if (ret == 0 && ssl->tls13SecretCb != NULL) {
  651. ret = ssl->tls13SecretCb(ssl, EXPORTER_SECRET, key,
  652. ssl->specs.hash_size, ssl->tls13SecretCtx);
  653. if (ret != 0) {
  654. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  655. return TLS13_SECRET_CB_E;
  656. }
  657. }
  658. #ifdef OPENSSL_EXTRA
  659. if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
  660. ret = ssl->tls13KeyLogCb(ssl, EXPORTER_SECRET, key,
  661. ssl->specs.hash_size, NULL);
  662. if (ret != 0) {
  663. WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
  664. return TLS13_SECRET_CB_E;
  665. }
  666. }
  667. #endif /* OPENSSL_EXTRA */
  668. #endif /* HAVE_SECRET_CALLBACK */
  669. return ret;
  670. }
  671. /* The length of the exporter label. */
  672. #define EXPORTER_LABEL_SZ 8
  673. /* The exporter label. */
  674. static const byte exporterLabel[EXPORTER_LABEL_SZ + 1] =
  675. "exporter";
  676. /* Hash("") */
  677. #ifndef NO_SHA256
  678. static const byte emptySHA256Hash[] = {
  679. 0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, 0x1C, 0x14, 0x9A, 0xFB, 0xF4, 0xC8,
  680. 0x99, 0x6F, 0xB9, 0x24, 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C,
  681. 0xA4, 0x95, 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55
  682. };
  683. #endif
  684. #ifdef WOLFSSL_SHA384
  685. static const byte emptySHA384Hash[] = {
  686. 0x38, 0xB0, 0x60, 0xA7, 0x51, 0xAC, 0x96, 0x38, 0x4C, 0xD9, 0x32, 0x7E,
  687. 0xB1, 0xB1, 0xE3, 0x6A, 0x21, 0xFD, 0xB7, 0x11, 0x14, 0xBE, 0x07, 0x43,
  688. 0x4C, 0x0C, 0xC7, 0xBF, 0x63, 0xF6, 0xE1, 0xDA, 0x27, 0x4E, 0xDE, 0xBF,
  689. 0xE7, 0x6F, 0x65, 0xFB, 0xD5, 0x1A, 0xD2, 0xF1, 0x48, 0x98, 0xB9, 0x5B
  690. };
  691. #endif
  692. #ifdef WOLFSSL_TLS13_SHA512
  693. static const byte emptySHA512Hash[] = {
  694. 0xCF, 0x83, 0xE1, 0x35, 0x7E, 0xEF, 0xB8, 0xBD, 0xF1, 0x54, 0x28, 0x50,
  695. 0xD6, 0x6D, 0x80, 0x07, 0xD6, 0x20, 0xE4, 0x05, 0x0B, 0x57, 0x15, 0xDC,
  696. 0x83, 0xF4, 0xA9, 0x21, 0xD3, 0x6C, 0xE9, 0xCE, 0x47, 0xD0, 0xD1, 0x3C,
  697. 0x5D, 0x85, 0xF2, 0xB0, 0xFF, 0x83, 0x18, 0xD2, 0x87, 0x7E, 0xEC, 0x2F,
  698. 0x63, 0xB9, 0x31, 0xBD, 0x47, 0x41, 0x7A, 0x81, 0xA5, 0x38, 0x32, 0x7A,
  699. 0xF9, 0x27, 0xDA, 0x3E
  700. };
  701. #endif
  702. /**
  703. * Implement section 7.5 of RFC 8446
  704. * @return 0 on success
  705. * <0 on failure
  706. */
  707. int Tls13_Exporter(WOLFSSL* ssl, unsigned char *out, size_t outLen,
  708. const char *label, size_t labelLen,
  709. const unsigned char *context, size_t contextLen)
  710. {
  711. int ret;
  712. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  713. int hashLen = 0;
  714. byte hashOut[WC_MAX_DIGEST_SIZE];
  715. const byte* emptyHash = NULL;
  716. byte firstExpand[WC_MAX_DIGEST_SIZE];
  717. const byte* protocol = tls13ProtocolLabel;
  718. word32 protocolLen = TLS13_PROTOCOL_LABEL_SZ;
  719. if (ssl->version.minor != TLSv1_3_MINOR)
  720. return VERSION_ERROR;
  721. switch (ssl->specs.mac_algorithm) {
  722. #ifndef NO_SHA256
  723. case sha256_mac:
  724. hashType = WC_HASH_TYPE_SHA256;
  725. hashLen = WC_SHA256_DIGEST_SIZE;
  726. emptyHash = emptySHA256Hash;
  727. break;
  728. #endif
  729. #ifdef WOLFSSL_SHA384
  730. case sha384_mac:
  731. hashType = WC_HASH_TYPE_SHA384;
  732. hashLen = WC_SHA384_DIGEST_SIZE;
  733. emptyHash = emptySHA384Hash;
  734. break;
  735. #endif
  736. #ifdef WOLFSSL_TLS13_SHA512
  737. case sha512_mac:
  738. hashType = WC_HASH_TYPE_SHA512;
  739. hashLen = WC_SHA512_DIGEST_SIZE;
  740. emptyHash = emptySHA512Hash;
  741. break;
  742. #endif
  743. }
  744. /* Derive-Secret(Secret, label, "") */
  745. PRIVATE_KEY_UNLOCK();
  746. ret = wc_Tls13_HKDF_Expand_Label(firstExpand, hashLen,
  747. ssl->arrays->exporterSecret, hashLen,
  748. protocol, protocolLen, (byte*)label, (word32)labelLen,
  749. emptyHash, hashLen, hashType);
  750. PRIVATE_KEY_LOCK();
  751. if (ret != 0)
  752. return ret;
  753. /* Hash(context_value) */
  754. ret = wc_Hash(hashType, context, (word32)contextLen, hashOut, WC_MAX_DIGEST_SIZE);
  755. if (ret != 0)
  756. return ret;
  757. PRIVATE_KEY_UNLOCK();
  758. ret = wc_Tls13_HKDF_Expand_Label(out, (word32)outLen, firstExpand, hashLen,
  759. protocol, protocolLen, exporterLabel, EXPORTER_LABEL_SZ,
  760. hashOut, hashLen, hashType);
  761. PRIVATE_KEY_LOCK();
  762. return ret;
  763. }
  764. #endif
  765. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  766. /* The length of the resumption master secret label. */
  767. #define RESUME_MASTER_LABEL_SZ 10
  768. /* The resumption master secret label. */
  769. static const byte resumeMasterLabel[RESUME_MASTER_LABEL_SZ + 1] =
  770. "res master";
  771. /* Derive the resumption secret.
  772. *
  773. * ssl The SSL/TLS object.
  774. * key The derived key.
  775. * returns 0 on success, otherwise failure.
  776. */
  777. int DeriveResumptionSecret(WOLFSSL* ssl, byte* key)
  778. {
  779. byte* masterSecret;
  780. WOLFSSL_MSG("Derive Resumption Secret");
  781. if (ssl == NULL) {
  782. return BAD_FUNC_ARG;
  783. }
  784. if (ssl->arrays != NULL) {
  785. masterSecret = ssl->arrays->masterSecret;
  786. }
  787. else {
  788. masterSecret = ssl->session->masterSecret;
  789. }
  790. return Tls13DeriveKey(ssl, key, -1, masterSecret, resumeMasterLabel,
  791. RESUME_MASTER_LABEL_SZ, ssl->specs.mac_algorithm, 1);
  792. }
  793. #endif
  794. /* Length of the finished label. */
  795. #define FINISHED_LABEL_SZ 8
  796. /* Finished label for generating finished key. */
  797. static const byte finishedLabel[FINISHED_LABEL_SZ+1] = "finished";
  798. /* Derive the finished secret.
  799. *
  800. * ssl The SSL/TLS object.
  801. * key The key to use with the HMAC.
  802. * secret The derived secret.
  803. * returns 0 on success, otherwise failure.
  804. */
  805. static int DeriveFinishedSecret(WOLFSSL* ssl, byte* key, byte* secret)
  806. {
  807. WOLFSSL_MSG("Derive Finished Secret");
  808. return Tls13DeriveKey(ssl, secret, -1, key, finishedLabel, FINISHED_LABEL_SZ,
  809. ssl->specs.mac_algorithm, 0);
  810. }
  811. /* The length of the application traffic label. */
  812. #define APP_TRAFFIC_LABEL_SZ 11
  813. /* The application traffic label. */
  814. static const byte appTrafficLabel[APP_TRAFFIC_LABEL_SZ + 1] =
  815. "traffic upd";
  816. /* Update the traffic secret.
  817. *
  818. * ssl The SSL/TLS object.
  819. * secret The previous secret and derived secret.
  820. * returns 0 on success, otherwise failure.
  821. */
  822. static int DeriveTrafficSecret(WOLFSSL* ssl, byte* secret)
  823. {
  824. WOLFSSL_MSG("Derive New Application Traffic Secret");
  825. return Tls13DeriveKey(ssl, secret, -1, secret,
  826. appTrafficLabel, APP_TRAFFIC_LABEL_SZ,
  827. ssl->specs.mac_algorithm, 0);
  828. }
  829. static int Tls13_HKDF_Extract(WOLFSSL *ssl, byte* prk, const byte* salt, int saltLen,
  830. byte* ikm, int ikmLen, int digest)
  831. {
  832. int ret;
  833. #ifdef HAVE_PK_CALLBACKS
  834. void *cb_ctx = ssl->HkdfExtractCtx;
  835. CallbackHKDFExtract cb = ssl->ctx->HkdfExtractCb;
  836. if (cb != NULL) {
  837. ret = cb(prk, salt, saltLen, ikm, ikmLen, digest, cb_ctx);
  838. }
  839. else
  840. #endif
  841. {
  842. (void)ssl;
  843. ret = wc_Tls13_HKDF_Extract(prk, salt, saltLen, ikm, ikmLen, digest);
  844. }
  845. return ret;
  846. }
  847. /* Derive the early secret using HKDF Extract.
  848. *
  849. * ssl The SSL/TLS object.
  850. */
  851. int DeriveEarlySecret(WOLFSSL* ssl)
  852. {
  853. int ret;
  854. WOLFSSL_MSG("Derive Early Secret");
  855. if (ssl == NULL || ssl->arrays == NULL) {
  856. return BAD_FUNC_ARG;
  857. }
  858. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  859. ret = tsip_Tls13DeriveEarlySecret(ssl);
  860. if (ret != CRYPTOCB_UNAVAILABLE)
  861. return ret;
  862. #endif
  863. PRIVATE_KEY_UNLOCK();
  864. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  865. ret = Tls13_HKDF_Extract(ssl, ssl->arrays->secret, NULL, 0,
  866. ssl->arrays->psk_key, ssl->arrays->psk_keySz,
  867. mac2hash(ssl->specs.mac_algorithm));
  868. #else
  869. ret = Tls13_HKDF_Extract(ssl, ssl->arrays->secret, NULL, 0,
  870. ssl->arrays->masterSecret, 0, mac2hash(ssl->specs.mac_algorithm));
  871. #endif
  872. PRIVATE_KEY_LOCK();
  873. return ret;
  874. }
  875. /* The length of the derived label. */
  876. #define DERIVED_LABEL_SZ 7
  877. /* The derived label. */
  878. static const byte derivedLabel[DERIVED_LABEL_SZ + 1] =
  879. "derived";
  880. /* Derive the handshake secret using HKDF Extract.
  881. *
  882. * ssl The SSL/TLS object.
  883. */
  884. int DeriveHandshakeSecret(WOLFSSL* ssl)
  885. {
  886. byte key[WC_MAX_DIGEST_SIZE];
  887. int ret;
  888. WOLFSSL_MSG("Derive Handshake Secret");
  889. if (ssl == NULL || ssl->arrays == NULL) {
  890. return BAD_FUNC_ARG;
  891. }
  892. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  893. ret = tsip_Tls13DeriveHandshakeSecret(ssl);
  894. if (ret != CRYPTOCB_UNAVAILABLE)
  895. return ret;
  896. #endif
  897. ret = DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
  898. derivedLabel, DERIVED_LABEL_SZ,
  899. NULL, 0, ssl->specs.mac_algorithm);
  900. if (ret != 0)
  901. return ret;
  902. PRIVATE_KEY_UNLOCK();
  903. ret = Tls13_HKDF_Extract(ssl, ssl->arrays->preMasterSecret,
  904. key, ssl->specs.hash_size,
  905. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz,
  906. mac2hash(ssl->specs.mac_algorithm));
  907. PRIVATE_KEY_LOCK();
  908. return ret;
  909. }
  910. /* Derive the master secret using HKDF Extract.
  911. *
  912. * ssl The SSL/TLS object.
  913. */
  914. int DeriveMasterSecret(WOLFSSL* ssl)
  915. {
  916. byte key[WC_MAX_DIGEST_SIZE];
  917. int ret;
  918. WOLFSSL_MSG("Derive Master Secret");
  919. if (ssl == NULL || ssl->arrays == NULL) {
  920. return BAD_FUNC_ARG;
  921. }
  922. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  923. ret = tsip_Tls13DeriveMasterSecret(ssl);
  924. if (ret != CRYPTOCB_UNAVAILABLE)
  925. return ret;
  926. #endif
  927. ret = DeriveKeyMsg(ssl, key, -1, ssl->arrays->preMasterSecret,
  928. derivedLabel, DERIVED_LABEL_SZ,
  929. NULL, 0, ssl->specs.mac_algorithm);
  930. if (ret != 0)
  931. return ret;
  932. PRIVATE_KEY_UNLOCK();
  933. ret = Tls13_HKDF_Extract(ssl, ssl->arrays->masterSecret,
  934. key, ssl->specs.hash_size,
  935. ssl->arrays->masterSecret, 0, mac2hash(ssl->specs.mac_algorithm));
  936. PRIVATE_KEY_LOCK();
  937. #ifdef HAVE_KEYING_MATERIAL
  938. if (ret != 0)
  939. return ret;
  940. /* Calculate exporter secret only when saving arrays */
  941. if (ssl->options.saveArrays)
  942. ret = DeriveExporterSecret(ssl, ssl->arrays->exporterSecret);
  943. #endif
  944. return ret;
  945. }
  946. #if defined(HAVE_SESSION_TICKET)
  947. /* Length of the resumption label. */
  948. #define RESUMPTION_LABEL_SZ 10
  949. /* Resumption label for generating PSK associated with the ticket. */
  950. static const byte resumptionLabel[RESUMPTION_LABEL_SZ+1] = "resumption";
  951. /* Derive the PSK associated with the ticket.
  952. *
  953. * ssl The SSL/TLS object.
  954. * nonce The nonce to derive with.
  955. * nonceLen The length of the nonce to derive with.
  956. * secret The derived secret.
  957. * returns 0 on success, otherwise failure.
  958. */
  959. int DeriveResumptionPSK(WOLFSSL* ssl, byte* nonce, byte nonceLen, byte* secret)
  960. {
  961. int digestAlg;
  962. /* Only one protocol version defined at this time. */
  963. const byte* protocol = tls13ProtocolLabel;
  964. word32 protocolLen = TLS13_PROTOCOL_LABEL_SZ;
  965. int ret;
  966. WOLFSSL_MSG("Derive Resumption PSK");
  967. switch (ssl->specs.mac_algorithm) {
  968. #ifndef NO_SHA256
  969. case sha256_mac:
  970. digestAlg = WC_SHA256;
  971. break;
  972. #endif
  973. #ifdef WOLFSSL_SHA384
  974. case sha384_mac:
  975. digestAlg = WC_SHA384;
  976. break;
  977. #endif
  978. #ifdef WOLFSSL_TLS13_SHA512
  979. case sha512_mac:
  980. digestAlg = WC_SHA512;
  981. break;
  982. #endif
  983. default:
  984. return BAD_FUNC_ARG;
  985. }
  986. PRIVATE_KEY_UNLOCK();
  987. ret = wc_Tls13_HKDF_Expand_Label(secret, ssl->specs.hash_size,
  988. ssl->session->masterSecret, ssl->specs.hash_size,
  989. protocol, protocolLen, resumptionLabel,
  990. RESUMPTION_LABEL_SZ, nonce, nonceLen, digestAlg);
  991. PRIVATE_KEY_LOCK();
  992. return ret;
  993. }
  994. #endif /* HAVE_SESSION_TICKET */
  995. /* Calculate the HMAC of message data to this point.
  996. *
  997. * ssl The SSL/TLS object.
  998. * key The HMAC key.
  999. * hash The hash result - verify data.
  1000. * returns length of verify data generated.
  1001. */
  1002. static int BuildTls13HandshakeHmac(WOLFSSL* ssl, byte* key, byte* hash,
  1003. word32* pHashSz)
  1004. {
  1005. Hmac verifyHmac;
  1006. int hashType = WC_SHA256;
  1007. int hashSz = WC_SHA256_DIGEST_SIZE;
  1008. int ret = BAD_FUNC_ARG;
  1009. if (ssl == NULL || key == NULL || hash == NULL) {
  1010. return BAD_FUNC_ARG;
  1011. }
  1012. /* Get the hash of the previous handshake messages. */
  1013. switch (ssl->specs.mac_algorithm) {
  1014. #ifndef NO_SHA256
  1015. case sha256_mac:
  1016. hashType = WC_SHA256;
  1017. hashSz = WC_SHA256_DIGEST_SIZE;
  1018. ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
  1019. break;
  1020. #endif /* !NO_SHA256 */
  1021. #ifdef WOLFSSL_SHA384
  1022. case sha384_mac:
  1023. hashType = WC_SHA384;
  1024. hashSz = WC_SHA384_DIGEST_SIZE;
  1025. ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
  1026. break;
  1027. #endif /* WOLFSSL_SHA384 */
  1028. #ifdef WOLFSSL_TLS13_SHA512
  1029. case sha512_mac:
  1030. hashType = WC_SHA512;
  1031. hashSz = WC_SHA512_DIGEST_SIZE;
  1032. ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
  1033. break;
  1034. #endif /* WOLFSSL_TLS13_SHA512 */
  1035. default:
  1036. break;
  1037. }
  1038. if (ret != 0)
  1039. return ret;
  1040. #ifdef WOLFSSL_DEBUG_TLS
  1041. WOLFSSL_MSG(" Key");
  1042. WOLFSSL_BUFFER(key, ssl->specs.hash_size);
  1043. WOLFSSL_MSG(" Msg Hash");
  1044. WOLFSSL_BUFFER(hash, hashSz);
  1045. #endif
  1046. /* Calculate the verify data. */
  1047. ret = wc_HmacInit(&verifyHmac, ssl->heap, ssl->devId);
  1048. if (ret == 0) {
  1049. ret = wc_HmacSetKey(&verifyHmac, hashType, key, ssl->specs.hash_size);
  1050. if (ret == 0)
  1051. ret = wc_HmacUpdate(&verifyHmac, hash, hashSz);
  1052. if (ret == 0)
  1053. ret = wc_HmacFinal(&verifyHmac, hash);
  1054. wc_HmacFree(&verifyHmac);
  1055. }
  1056. #ifdef WOLFSSL_DEBUG_TLS
  1057. WOLFSSL_MSG(" Hash");
  1058. WOLFSSL_BUFFER(hash, hashSz);
  1059. #endif
  1060. if (pHashSz)
  1061. *pHashSz = hashSz;
  1062. return ret;
  1063. }
  1064. /* The length of the label to use when deriving keys. */
  1065. #define WRITE_KEY_LABEL_SZ 3
  1066. /* The length of the label to use when deriving IVs. */
  1067. #define WRITE_IV_LABEL_SZ 2
  1068. /* The label to use when deriving keys. */
  1069. static const byte writeKeyLabel[WRITE_KEY_LABEL_SZ+1] = "key";
  1070. /* The label to use when deriving IVs. */
  1071. static const byte writeIVLabel[WRITE_IV_LABEL_SZ+1] = "iv";
  1072. /* Derive the keys and IVs for TLS v1.3.
  1073. *
  1074. * ssl The SSL/TLS object.
  1075. * secret early_data_key when deriving the key and IV for encrypting early
  1076. * data application data and end_of_early_data messages.
  1077. * handshake_key when deriving keys and IVs for encrypting handshake
  1078. * messages.
  1079. * traffic_key when deriving first keys and IVs for encrypting
  1080. * traffic messages.
  1081. * update_traffic_key when deriving next keys and IVs for encrypting
  1082. * traffic messages.
  1083. * side ENCRYPT_SIDE_ONLY when only encryption secret needs to be derived.
  1084. * DECRYPT_SIDE_ONLY when only decryption secret needs to be derived.
  1085. * ENCRYPT_AND_DECRYPT_SIDE when both secret needs to be derived.
  1086. * store 1 indicates to derive the keys and IVs from derived secret and
  1087. * store ready for provisioning.
  1088. * returns 0 on success, otherwise failure.
  1089. */
  1090. int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store)
  1091. {
  1092. int ret = BAD_FUNC_ARG; /* Assume failure */
  1093. int i = 0;
  1094. #ifdef WOLFSSL_SMALL_STACK
  1095. byte* key_dig;
  1096. #else
  1097. byte key_dig[MAX_PRF_DIG];
  1098. #endif
  1099. int provision;
  1100. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  1101. ret = tsip_Tls13DeriveKeys(ssl, secret, side);
  1102. if (ret != CRYPTOCB_UNAVAILABLE) {
  1103. return ret;
  1104. }
  1105. ret = BAD_FUNC_ARG; /* Assume failure */
  1106. #endif
  1107. #ifdef WOLFSSL_SMALL_STACK
  1108. key_dig = (byte*)XMALLOC(MAX_PRF_DIG, ssl->heap, DYNAMIC_TYPE_DIGEST);
  1109. if (key_dig == NULL)
  1110. return MEMORY_E;
  1111. #endif
  1112. if (side == ENCRYPT_AND_DECRYPT_SIDE) {
  1113. provision = PROVISION_CLIENT_SERVER;
  1114. }
  1115. else {
  1116. provision = ((ssl->options.side != WOLFSSL_CLIENT_END) ^
  1117. (side == ENCRYPT_SIDE_ONLY)) ? PROVISION_CLIENT :
  1118. PROVISION_SERVER;
  1119. }
  1120. /* Derive the appropriate secret to use in the HKDF. */
  1121. switch (secret) {
  1122. #ifdef WOLFSSL_EARLY_DATA
  1123. case early_data_key:
  1124. ret = DeriveEarlyTrafficSecret(ssl, ssl->clientSecret);
  1125. if (ret != 0)
  1126. goto end;
  1127. break;
  1128. #endif
  1129. case handshake_key:
  1130. if (provision & PROVISION_CLIENT) {
  1131. ret = DeriveClientHandshakeSecret(ssl,
  1132. ssl->clientSecret);
  1133. if (ret != 0)
  1134. goto end;
  1135. }
  1136. if (provision & PROVISION_SERVER) {
  1137. ret = DeriveServerHandshakeSecret(ssl,
  1138. ssl->serverSecret);
  1139. if (ret != 0)
  1140. goto end;
  1141. }
  1142. break;
  1143. case traffic_key:
  1144. if (provision & PROVISION_CLIENT) {
  1145. ret = DeriveClientTrafficSecret(ssl, ssl->clientSecret);
  1146. if (ret != 0)
  1147. goto end;
  1148. }
  1149. if (provision & PROVISION_SERVER) {
  1150. ret = DeriveServerTrafficSecret(ssl, ssl->serverSecret);
  1151. if (ret != 0)
  1152. goto end;
  1153. }
  1154. break;
  1155. case update_traffic_key:
  1156. if (provision & PROVISION_CLIENT) {
  1157. ret = DeriveTrafficSecret(ssl, ssl->clientSecret);
  1158. if (ret != 0)
  1159. goto end;
  1160. }
  1161. if (provision & PROVISION_SERVER) {
  1162. ret = DeriveTrafficSecret(ssl, ssl->serverSecret);
  1163. if (ret != 0)
  1164. goto end;
  1165. }
  1166. break;
  1167. default:
  1168. break;
  1169. }
  1170. #ifdef WOLFSSL_QUIC
  1171. if (WOLFSSL_IS_QUIC(ssl)) {
  1172. ret = wolfSSL_quic_forward_secrets(ssl, secret, side);
  1173. if (ret != 0)
  1174. goto end;
  1175. }
  1176. #endif /* WOLFSSL_QUIC */
  1177. if (!store)
  1178. goto end;
  1179. /* Key data = client key | server key | client IV | server IV */
  1180. if (provision & PROVISION_CLIENT) {
  1181. /* Derive the client key. */
  1182. WOLFSSL_MSG("Derive Client Key");
  1183. ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
  1184. ssl->clientSecret, writeKeyLabel,
  1185. WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0);
  1186. if (ret != 0)
  1187. goto end;
  1188. i += ssl->specs.key_size;
  1189. }
  1190. if (provision & PROVISION_SERVER) {
  1191. /* Derive the server key. */
  1192. WOLFSSL_MSG("Derive Server Key");
  1193. ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
  1194. ssl->serverSecret, writeKeyLabel,
  1195. WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0);
  1196. if (ret != 0)
  1197. goto end;
  1198. i += ssl->specs.key_size;
  1199. }
  1200. if (provision & PROVISION_CLIENT) {
  1201. /* Derive the client IV. */
  1202. WOLFSSL_MSG("Derive Client IV");
  1203. ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
  1204. ssl->clientSecret, writeIVLabel,
  1205. WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0);
  1206. if (ret != 0)
  1207. goto end;
  1208. i += ssl->specs.iv_size;
  1209. }
  1210. if (provision & PROVISION_SERVER) {
  1211. /* Derive the server IV. */
  1212. WOLFSSL_MSG("Derive Server IV");
  1213. ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
  1214. ssl->serverSecret, writeIVLabel,
  1215. WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0);
  1216. if (ret != 0)
  1217. goto end;
  1218. i += ssl->specs.iv_size;
  1219. }
  1220. /* Store keys and IVs but don't activate them. */
  1221. ret = StoreKeys(ssl, key_dig, provision);
  1222. #ifdef WOLFSSL_DTLS13
  1223. if (ret != 0)
  1224. goto end;
  1225. if (ssl->options.dtls) {
  1226. ret = Dtls13DeriveSnKeys(ssl, provision);
  1227. if (ret != 0)
  1228. return ret;
  1229. }
  1230. #endif /* WOLFSSL_DTLS13 */
  1231. end:
  1232. ForceZero(key_dig, i);
  1233. #ifdef WOLFSSL_SMALL_STACK
  1234. XFREE(key_dig, ssl->heap, DYNAMIC_TYPE_DIGEST);
  1235. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  1236. wc_MemZero_Check(key_dig, MAX_PRF_DIG);
  1237. #endif
  1238. if (ret != 0) {
  1239. WOLFSSL_ERROR_VERBOSE(ret);
  1240. }
  1241. return ret;
  1242. }
  1243. #if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  1244. #ifndef NO_ASN_TIME
  1245. #if defined(USER_TICKS)
  1246. #if 0
  1247. word32 TimeNowInMilliseconds(void)
  1248. {
  1249. /*
  1250. write your own clock tick function if don't want gettimeofday()
  1251. needs millisecond accuracy but doesn't have to correlated to EPOCH
  1252. */
  1253. }
  1254. #endif
  1255. #elif defined(TIME_OVERRIDES)
  1256. #if !defined(NO_ASN) && !defined(NO_ASN_TIME)
  1257. word32 TimeNowInMilliseconds(void)
  1258. {
  1259. return (word32) wc_Time(0) * 1000;
  1260. }
  1261. #else
  1262. #ifndef HAVE_TIME_T_TYPE
  1263. typedef long time_t;
  1264. #endif
  1265. extern time_t XTIME(time_t * timer);
  1266. /* The time in milliseconds.
  1267. * Used for tickets to represent difference between when first seen and when
  1268. * sending.
  1269. *
  1270. * returns the time in milliseconds as a 32-bit value.
  1271. */
  1272. word32 TimeNowInMilliseconds(void)
  1273. {
  1274. return (word32) XTIME(0) * 1000;
  1275. }
  1276. #endif
  1277. #elif defined(XTIME_MS)
  1278. word32 TimeNowInMilliseconds(void)
  1279. {
  1280. return (word32)XTIME_MS(0);
  1281. }
  1282. #elif defined(USE_WINDOWS_API)
  1283. /* The time in milliseconds.
  1284. * Used for tickets to represent difference between when first seen and when
  1285. * sending.
  1286. *
  1287. * returns the time in milliseconds as a 32-bit value.
  1288. */
  1289. word32 TimeNowInMilliseconds(void)
  1290. {
  1291. static int init = 0;
  1292. static LARGE_INTEGER freq;
  1293. LARGE_INTEGER count;
  1294. if (!init) {
  1295. QueryPerformanceFrequency(&freq);
  1296. init = 1;
  1297. }
  1298. QueryPerformanceCounter(&count);
  1299. return (word32)(count.QuadPart / (freq.QuadPart / 1000));
  1300. }
  1301. #elif defined(HAVE_RTP_SYS)
  1302. #include "rtptime.h"
  1303. /* The time in milliseconds.
  1304. * Used for tickets to represent difference between when first seen and when
  1305. * sending.
  1306. *
  1307. * returns the time in milliseconds as a 32-bit value.
  1308. */
  1309. word32 TimeNowInMilliseconds(void)
  1310. {
  1311. return (word32)rtp_get_system_sec() * 1000;
  1312. }
  1313. #elif defined(WOLFSSL_DEOS)
  1314. word32 TimeNowInMilliseconds(void)
  1315. {
  1316. const word32 systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
  1317. word32 *systemTickPtr = systemTickPointer();
  1318. return (word32) (*systemTickPtr/systemTickTimeInHz) * 1000;
  1319. }
  1320. #elif defined(MICRIUM)
  1321. /* The time in milliseconds.
  1322. * Used for tickets to represent difference between when first seen and when
  1323. * sending.
  1324. *
  1325. * returns the time in milliseconds as a 32-bit value.
  1326. */
  1327. word32 TimeNowInMilliseconds(void)
  1328. {
  1329. OS_TICK ticks = 0;
  1330. OS_ERR err;
  1331. ticks = OSTimeGet(&err);
  1332. return (word32) (ticks / OSCfg_TickRate_Hz) * 1000;
  1333. }
  1334. #elif defined(MICROCHIP_TCPIP_V5)
  1335. /* The time in milliseconds.
  1336. * Used for tickets to represent difference between when first seen and when
  1337. * sending.
  1338. *
  1339. * returns the time in milliseconds as a 32-bit value.
  1340. */
  1341. word32 TimeNowInMilliseconds(void)
  1342. {
  1343. return (word32) (TickGet() / (TICKS_PER_SECOND / 1000));
  1344. }
  1345. #elif defined(MICROCHIP_TCPIP)
  1346. #if defined(MICROCHIP_MPLAB_HARMONY)
  1347. #include <system/tmr/sys_tmr.h>
  1348. /* The time in milliseconds.
  1349. * Used for tickets to represent difference between when first seen and when
  1350. * sending.
  1351. *
  1352. * returns the time in milliseconds as a 32-bit value.
  1353. */
  1354. word32 TimeNowInMilliseconds(void)
  1355. {
  1356. return (word32)(SYS_TMR_TickCountGet() /
  1357. (SYS_TMR_TickCounterFrequencyGet() / 1000));
  1358. }
  1359. #else
  1360. /* The time in milliseconds.
  1361. * Used for tickets to represent difference between when first seen and when
  1362. * sending.
  1363. *
  1364. * returns the time in milliseconds as a 32-bit value.
  1365. */
  1366. word32 TimeNowInMilliseconds(void)
  1367. {
  1368. return (word32)(SYS_TICK_Get() / (SYS_TICK_TicksPerSecondGet() / 1000));
  1369. }
  1370. #endif
  1371. #elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
  1372. /* The time in milliseconds.
  1373. * Used for tickets to represent difference between when first seen and when
  1374. * sending.
  1375. *
  1376. * returns the time in milliseconds as a 32-bit value.
  1377. */
  1378. word32 TimeNowInMilliseconds(void)
  1379. {
  1380. TIME_STRUCT mqxTime;
  1381. _time_get_elapsed(&mqxTime);
  1382. return (word32) mqxTime.SECONDS * 1000;
  1383. }
  1384. #elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
  1385. #include "include/task.h"
  1386. /* The time in milliseconds.
  1387. * Used for tickets to represent difference between when first seen and when
  1388. * sending.
  1389. *
  1390. * returns the time in milliseconds as a 32-bit value.
  1391. */
  1392. word32 TimeNowInMilliseconds(void)
  1393. {
  1394. return (unsigned int)(((float)xTaskGetTickCount()) /
  1395. (configTICK_RATE_HZ / 1000));
  1396. }
  1397. #elif defined(FREESCALE_KSDK_BM)
  1398. #include "lwip/sys.h" /* lwIP */
  1399. /* The time in milliseconds.
  1400. * Used for tickets to represent difference between when first seen and when
  1401. * sending.
  1402. *
  1403. * returns the time in milliseconds as a 32-bit value.
  1404. */
  1405. word32 TimeNowInMilliseconds(void)
  1406. {
  1407. return sys_now();
  1408. }
  1409. #elif defined(WOLFSSL_TIRTOS)
  1410. /* The time in milliseconds.
  1411. * Used for tickets to represent difference between when first seen and when
  1412. * sending.
  1413. *
  1414. * returns the time in milliseconds as a 32-bit value.
  1415. */
  1416. word32 TimeNowInMilliseconds(void)
  1417. {
  1418. return (word32) Seconds_get() * 1000;
  1419. }
  1420. #elif defined(WOLFSSL_UTASKER)
  1421. /* The time in milliseconds.
  1422. * Used for tickets to represent difference between when first seen and when
  1423. * sending.
  1424. *
  1425. * returns the time in milliseconds as a 32-bit value.
  1426. */
  1427. word32 TimeNowInMilliseconds(void)
  1428. {
  1429. return (word32)(uTaskerSystemTick / (TICK_RESOLUTION / 1000));
  1430. }
  1431. #elif defined(WOLFSSL_LINUXKM)
  1432. word32 TimeNowInMilliseconds(void)
  1433. {
  1434. s64 t;
  1435. #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0)
  1436. struct timespec ts;
  1437. getnstimeofday(&ts);
  1438. t = ts.tv_sec * (s64)1000;
  1439. t += ts.tv_nsec / (s64)1000000;
  1440. #else
  1441. struct timespec64 ts;
  1442. #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 0, 0)
  1443. ts = current_kernel_time64();
  1444. #else
  1445. ktime_get_coarse_real_ts64(&ts);
  1446. #endif
  1447. t = ts.tv_sec * 1000L;
  1448. t += ts.tv_nsec / 1000000L;
  1449. #endif
  1450. return (word32)t;
  1451. }
  1452. #elif defined(WOLFSSL_QNX_CAAM)
  1453. word32 TimeNowInMilliseconds(void)
  1454. {
  1455. struct timespec now;
  1456. clock_gettime(CLOCK_REALTIME, &now);
  1457. return (word32)(now.tv_sec * 1000 + now.tv_nsec / 1000000);
  1458. }
  1459. #elif defined(FUSION_RTOS)
  1460. /* The time in milliseconds.
  1461. * Used for tickets to represent difference between when first seen and when
  1462. * sending.
  1463. *
  1464. * returns the time in milliseconds as a 32-bit value.
  1465. */
  1466. word32 TimeNowInMilliseconds(void)
  1467. {
  1468. struct timeval now;
  1469. if (FCL_GETTIMEOFDAY(&now, 0) < 0)
  1470. return (word32)GETTIME_ERROR; /* TODO: return 0 for failure */
  1471. /* Convert to milliseconds number. */
  1472. return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
  1473. }
  1474. #elif defined(WOLFSSL_ZEPHYR)
  1475. word32 TimeNowInMilliseconds(void)
  1476. {
  1477. #if defined(CONFIG_ARCH_POSIX)
  1478. k_cpu_idle();
  1479. #endif
  1480. return (word32)k_uptime_get() / 1000;
  1481. }
  1482. #else
  1483. /* The time in milliseconds.
  1484. * Used for tickets to represent difference between when first seen and when
  1485. * sending.
  1486. *
  1487. * returns the time in milliseconds as a 32-bit value.
  1488. */
  1489. word32 TimeNowInMilliseconds(void)
  1490. {
  1491. struct timeval now;
  1492. if (gettimeofday(&now, 0) < 0)
  1493. return (word32)GETTIME_ERROR; /* TODO: return 0 for failure */
  1494. /* Convert to milliseconds number. */
  1495. return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
  1496. }
  1497. #endif
  1498. #else
  1499. /* user must supply time in milliseconds function:
  1500. * word32 TimeNowInMilliseconds(void);
  1501. * The response is milliseconds elapsed
  1502. */
  1503. #endif /* !NO_ASN_TIME */
  1504. #endif /* HAVE_SESSION_TICKET || !NO_PSK */
  1505. /* Extract the handshake header information.
  1506. *
  1507. * ssl The SSL/TLS object.
  1508. * input The buffer holding the message data.
  1509. * inOutIdx On entry, the index into the buffer of the handshake data.
  1510. * On exit, the start of the handshake data.
  1511. * type Type of handshake message.
  1512. * size The length of the handshake message data.
  1513. * totalSz The total size of data in the buffer.
  1514. * returns BUFFER_E if there is not enough input data and 0 on success.
  1515. */
  1516. static int GetHandshakeHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  1517. byte* type, word32* size, word32 totalSz)
  1518. {
  1519. const byte* ptr = input + *inOutIdx;
  1520. (void)ssl;
  1521. *inOutIdx += HANDSHAKE_HEADER_SZ;
  1522. if (*inOutIdx > totalSz)
  1523. return BUFFER_E;
  1524. *type = ptr[0];
  1525. c24to32(&ptr[1], size);
  1526. return 0;
  1527. }
  1528. /* Add record layer header to message.
  1529. *
  1530. * output The buffer to write the record layer header into.
  1531. * length The length of the record data.
  1532. * type The type of record message.
  1533. * ssl The SSL/TLS object.
  1534. */
  1535. static void AddTls13RecordHeader(byte* output, word32 length, byte type,
  1536. WOLFSSL* ssl)
  1537. {
  1538. RecordLayerHeader* rl;
  1539. rl = (RecordLayerHeader*)output;
  1540. rl->type = type;
  1541. rl->pvMajor = ssl->version.major;
  1542. /* NOTE: May be TLSv1_MINOR when sending first ClientHello. */
  1543. rl->pvMinor = TLSv1_2_MINOR;
  1544. c16toa((word16)length, rl->length);
  1545. }
  1546. /* Add handshake header to message.
  1547. *
  1548. * output The buffer to write the handshake header into.
  1549. * length The length of the handshake data.
  1550. * fragOffset The offset of the fragment data. (DTLS)
  1551. * fragLength The length of the fragment data. (DTLS)
  1552. * type The type of handshake message.
  1553. * ssl The SSL/TLS object. (DTLS)
  1554. */
  1555. static void AddTls13HandShakeHeader(byte* output, word32 length,
  1556. word32 fragOffset, word32 fragLength,
  1557. byte type, WOLFSSL* ssl)
  1558. {
  1559. HandShakeHeader* hs;
  1560. (void)fragOffset;
  1561. (void)fragLength;
  1562. (void)ssl;
  1563. #ifdef WOLFSSL_DTLS13
  1564. /* message_hash type is used for a syntetic message that replaces the first
  1565. ClientHello in the hash transcript when using HelloRetryRequest. It will
  1566. never be transmitted and, as the DTLS-only fields must not be considered
  1567. when computing the hash transcript, we can avoid to use the DTLS
  1568. handshake header. */
  1569. if (ssl->options.dtls && type != message_hash) {
  1570. Dtls13HandshakeAddHeader(ssl, output, (enum HandShakeType)type, length);
  1571. return;
  1572. }
  1573. #endif /* WOLFSSL_DTLS13 */
  1574. /* handshake header */
  1575. hs = (HandShakeHeader*)output;
  1576. hs->type = type;
  1577. c32to24(length, hs->length);
  1578. }
  1579. /* Add both record layer and handshake header to message.
  1580. *
  1581. * output The buffer to write the headers into.
  1582. * length The length of the handshake data.
  1583. * type The type of record layer message.
  1584. * ssl The SSL/TLS object. (DTLS)
  1585. */
  1586. static void AddTls13Headers(byte* output, word32 length, byte type,
  1587. WOLFSSL* ssl)
  1588. {
  1589. word32 lengthAdj = HANDSHAKE_HEADER_SZ;
  1590. word32 outputAdj = RECORD_HEADER_SZ;
  1591. #ifdef WOLFSSL_DTLS13
  1592. if (ssl->options.dtls) {
  1593. Dtls13AddHeaders(output, length, (enum HandShakeType)type, ssl);
  1594. return;
  1595. }
  1596. #endif /* WOLFSSL_DTLS13 */
  1597. AddTls13RecordHeader(output, length + lengthAdj, handshake, ssl);
  1598. AddTls13HandShakeHeader(output + outputAdj, length, 0, length, type, ssl);
  1599. }
  1600. #if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) \
  1601. && !defined(NO_CERTS)
  1602. /* Add both record layer and fragment handshake header to message.
  1603. *
  1604. * output The buffer to write the headers into.
  1605. * fragOffset The offset of the fragment data. (DTLS)
  1606. * fragLength The length of the fragment data. (DTLS)
  1607. * length The length of the handshake data.
  1608. * type The type of record layer message.
  1609. * ssl The SSL/TLS object. (DTLS)
  1610. */
  1611. static void AddTls13FragHeaders(byte* output, word32 fragSz, word32 fragOffset,
  1612. word32 length, byte type, WOLFSSL* ssl)
  1613. {
  1614. word32 lengthAdj = HANDSHAKE_HEADER_SZ;
  1615. word32 outputAdj = RECORD_HEADER_SZ;
  1616. (void)fragSz;
  1617. #ifdef WOLFSSL_DTLS13
  1618. /* we ignore fragmentation fields here because fragmentation logic for
  1619. DTLS1.3 is inside dtls13_handshake_send(). */
  1620. if (ssl->options.dtls) {
  1621. Dtls13AddHeaders(output, length, (enum HandShakeType)type, ssl);
  1622. return;
  1623. }
  1624. #endif /* WOLFSSL_DTLS13 */
  1625. AddTls13RecordHeader(output, fragSz + lengthAdj, handshake, ssl);
  1626. AddTls13HandShakeHeader(output + outputAdj, length, fragOffset, fragSz,
  1627. type, ssl);
  1628. }
  1629. #endif /* (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) && !NO_CERTS */
  1630. /* Write the sequence number into the buffer.
  1631. * No DTLS v1.3 support.
  1632. *
  1633. * ssl The SSL/TLS object.
  1634. * verifyOrder Which set of sequence numbers to use.
  1635. * out The buffer to write into.
  1636. */
  1637. static WC_INLINE void WriteSEQTls13(WOLFSSL* ssl, int verifyOrder, byte* out)
  1638. {
  1639. word32 seq[2] = {0, 0};
  1640. if (ssl->options.dtls) {
  1641. #ifdef WOLFSSL_DTLS13
  1642. Dtls13GetSeq(ssl, verifyOrder, seq, 1);
  1643. #endif /* WOLFSSL_DTLS13 */
  1644. }
  1645. else if (verifyOrder) {
  1646. seq[0] = ssl->keys.peer_sequence_number_hi;
  1647. seq[1] = ssl->keys.peer_sequence_number_lo++;
  1648. /* handle rollover */
  1649. if (seq[1] > ssl->keys.peer_sequence_number_lo)
  1650. ssl->keys.peer_sequence_number_hi++;
  1651. }
  1652. else {
  1653. seq[0] = ssl->keys.sequence_number_hi;
  1654. seq[1] = ssl->keys.sequence_number_lo++;
  1655. /* handle rollover */
  1656. if (seq[1] > ssl->keys.sequence_number_lo)
  1657. ssl->keys.sequence_number_hi++;
  1658. }
  1659. c32toa(seq[0], out);
  1660. c32toa(seq[1], out + OPAQUE32_LEN);
  1661. }
  1662. /* Build the nonce for TLS v1.3 encryption and decryption.
  1663. *
  1664. * ssl The SSL/TLS object.
  1665. * nonce The nonce data to use when encrypting or decrypting.
  1666. * iv The derived IV.
  1667. * order The side on which the message is to be or was sent.
  1668. */
  1669. static WC_INLINE void BuildTls13Nonce(WOLFSSL* ssl, byte* nonce, const byte* iv,
  1670. int order)
  1671. {
  1672. int i;
  1673. /* The nonce is the IV with the sequence XORed into the last bytes. */
  1674. WriteSEQTls13(ssl, order, nonce + AEAD_NONCE_SZ - SEQ_SZ);
  1675. for (i = 0; i < AEAD_NONCE_SZ - SEQ_SZ; i++)
  1676. nonce[i] = iv[i];
  1677. for (; i < AEAD_NONCE_SZ; i++)
  1678. nonce[i] ^= iv[i];
  1679. }
  1680. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  1681. /* Encrypt with ChaCha20 and create authentication tag with Poly1305.
  1682. *
  1683. * ssl The SSL/TLS object.
  1684. * output The buffer to write encrypted data and authentication tag into.
  1685. * May be the same pointer as input.
  1686. * input The data to encrypt.
  1687. * sz The number of bytes to encrypt.
  1688. * nonce The nonce to use with ChaCha20.
  1689. * aad The additional authentication data.
  1690. * aadSz The size of the addition authentication data.
  1691. * tag The authentication tag buffer.
  1692. * returns 0 on success, otherwise failure.
  1693. */
  1694. static int ChaCha20Poly1305_Encrypt(WOLFSSL* ssl, byte* output,
  1695. const byte* input, word16 sz, byte* nonce,
  1696. const byte* aad, word16 aadSz, byte* tag)
  1697. {
  1698. int ret = 0;
  1699. byte poly[CHACHA20_256_KEY_SIZE];
  1700. /* Poly1305 key is 256 bits of zero encrypted with ChaCha20. */
  1701. XMEMSET(poly, 0, sizeof(poly));
  1702. /* Set the nonce for ChaCha and get Poly1305 key. */
  1703. ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 0);
  1704. if (ret != 0)
  1705. return ret;
  1706. /* Create Poly1305 key using ChaCha20 keystream. */
  1707. ret = wc_Chacha_Process(ssl->encrypt.chacha, poly, poly, sizeof(poly));
  1708. if (ret != 0)
  1709. return ret;
  1710. #ifdef WOLFSSL_CHECK_MEM_ZERO
  1711. wc_MemZero_Add("ChaCha20Poly1305_Encrypt poly", poly, sizeof(poly));
  1712. #endif
  1713. ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 1);
  1714. if (ret != 0)
  1715. return ret;
  1716. /* Encrypt the plain text. */
  1717. ret = wc_Chacha_Process(ssl->encrypt.chacha, output, input, sz);
  1718. if (ret != 0) {
  1719. ForceZero(poly, sizeof(poly));
  1720. #ifdef WOLFSSL_CHECK_MEM_ZERO
  1721. wc_MemZero_Check(poly, sizeof(poly));
  1722. #endif
  1723. return ret;
  1724. }
  1725. /* Set key for Poly1305. */
  1726. ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly, sizeof(poly));
  1727. ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
  1728. #ifdef WOLFSSL_CHECK_MEM_ZERO
  1729. wc_MemZero_Check(poly, sizeof(poly));
  1730. #endif
  1731. if (ret != 0)
  1732. return ret;
  1733. /* Add authentication code of encrypted data to end. */
  1734. ret = wc_Poly1305_MAC(ssl->auth.poly1305, aad, aadSz, output, sz, tag,
  1735. POLY1305_AUTH_SZ);
  1736. return ret;
  1737. }
  1738. #endif
  1739. #ifdef HAVE_NULL_CIPHER
  1740. /* Create authentication tag and copy data over input.
  1741. *
  1742. * ssl The SSL/TLS object.
  1743. * output The buffer to copy data into.
  1744. * May be the same pointer as input.
  1745. * input The data.
  1746. * sz The number of bytes of data.
  1747. * nonce The nonce to use with authentication.
  1748. * aad The additional authentication data.
  1749. * aadSz The size of the addition authentication data.
  1750. * tag The authentication tag buffer.
  1751. * returns 0 on success, otherwise failure.
  1752. */
  1753. static int Tls13IntegrityOnly_Encrypt(WOLFSSL* ssl, byte* output,
  1754. const byte* input, word16 sz,
  1755. const byte* nonce,
  1756. const byte* aad, word16 aadSz, byte* tag)
  1757. {
  1758. int ret;
  1759. /* HMAC: nonce | aad | input */
  1760. ret = wc_HmacUpdate(ssl->encrypt.hmac, nonce, HMAC_NONCE_SZ);
  1761. if (ret == 0)
  1762. ret = wc_HmacUpdate(ssl->encrypt.hmac, aad, aadSz);
  1763. if (ret == 0)
  1764. ret = wc_HmacUpdate(ssl->encrypt.hmac, input, sz);
  1765. if (ret == 0)
  1766. ret = wc_HmacFinal(ssl->encrypt.hmac, tag);
  1767. /* Copy the input to output if not the same buffer */
  1768. if (ret == 0 && output != input)
  1769. XMEMCPY(output, input, sz);
  1770. return ret;
  1771. }
  1772. #endif
  1773. /* Encrypt data for TLS v1.3.
  1774. *
  1775. * ssl The SSL/TLS object.
  1776. * output The buffer to write encrypted data and authentication tag into.
  1777. * May be the same pointer as input.
  1778. * input The record header and data to encrypt.
  1779. * sz The number of bytes to encrypt.
  1780. * aad The additional authentication data.
  1781. * aadSz The size of the addition authentication data.
  1782. * asyncOkay If non-zero can return WC_PENDING_E, otherwise blocks on crypto
  1783. * returns 0 on success, otherwise failure.
  1784. */
  1785. static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input,
  1786. word16 sz, const byte* aad, word16 aadSz, int asyncOkay)
  1787. {
  1788. int ret = 0;
  1789. word16 dataSz = sz - ssl->specs.aead_mac_size;
  1790. word16 macSz = ssl->specs.aead_mac_size;
  1791. word32 nonceSz = 0;
  1792. #ifdef WOLFSSL_ASYNC_CRYPT
  1793. WC_ASYNC_DEV* asyncDev = NULL;
  1794. word32 event_flags = WC_ASYNC_FLAG_CALL_AGAIN;
  1795. #endif
  1796. WOLFSSL_ENTER("EncryptTls13");
  1797. (void)output;
  1798. (void)input;
  1799. (void)sz;
  1800. (void)dataSz;
  1801. (void)macSz;
  1802. (void)asyncOkay;
  1803. (void)nonceSz;
  1804. #ifdef WOLFSSL_ASYNC_CRYPT
  1805. if (ssl->error == WC_PENDING_E) {
  1806. ssl->error = 0; /* clear async */
  1807. }
  1808. #endif
  1809. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  1810. ret = tsip_Tls13AesEncrypt(ssl, output, input, dataSz);
  1811. if (ret != CRYPTOCB_UNAVAILABLE) {
  1812. if (ret > 0) {
  1813. ret = 0; /* tsip_Tls13AesEncrypt returns output size */
  1814. }
  1815. return ret;
  1816. }
  1817. ret = 0;
  1818. #endif /* WOLFSSL_RENESAS_TSIP_TLS && WOLFSSL_RENESAS_TSIP_VER >= 115 */
  1819. switch (ssl->encrypt.state) {
  1820. case CIPHER_STATE_BEGIN:
  1821. {
  1822. #ifdef WOLFSSL_DEBUG_TLS
  1823. WOLFSSL_MSG("Data to encrypt");
  1824. WOLFSSL_BUFFER(input, dataSz);
  1825. WOLFSSL_MSG("Additional Authentication Data");
  1826. WOLFSSL_BUFFER(aad, aadSz);
  1827. #endif
  1828. #ifdef WOLFSSL_CIPHER_TEXT_CHECK
  1829. if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) {
  1830. XMEMCPY(ssl->encrypt.sanityCheck, input,
  1831. min(dataSz, sizeof(ssl->encrypt.sanityCheck)));
  1832. }
  1833. #endif
  1834. #ifdef CIPHER_NONCE
  1835. if (ssl->encrypt.nonce == NULL) {
  1836. ssl->encrypt.nonce = (byte*)XMALLOC(AEAD_NONCE_SZ,
  1837. ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  1838. #ifdef WOLFSSL_CHECK_MEM_ZERO
  1839. if (ssl->encrypt.nonce != NULL) {
  1840. wc_MemZero_Add("EncryptTls13 nonce", ssl->encrypt.nonce,
  1841. AEAD_NONCE_SZ);
  1842. }
  1843. #endif
  1844. }
  1845. if (ssl->encrypt.nonce == NULL)
  1846. return MEMORY_E;
  1847. BuildTls13Nonce(ssl, ssl->encrypt.nonce, ssl->keys.aead_enc_imp_IV,
  1848. CUR_ORDER);
  1849. #endif
  1850. /* Advance state and proceed */
  1851. ssl->encrypt.state = CIPHER_STATE_DO;
  1852. }
  1853. FALL_THROUGH;
  1854. case CIPHER_STATE_DO:
  1855. {
  1856. switch (ssl->specs.bulk_cipher_algorithm) {
  1857. #ifdef BUILD_AESGCM
  1858. case wolfssl_aes_gcm:
  1859. #ifdef WOLFSSL_ASYNC_CRYPT
  1860. /* initialize event */
  1861. asyncDev = &ssl->encrypt.aes->asyncDev;
  1862. ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
  1863. if (ret != 0)
  1864. break;
  1865. #endif
  1866. nonceSz = AESGCM_NONCE_SZ;
  1867. #if ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
  1868. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
  1869. ret = wc_AesGcmEncrypt(ssl->encrypt.aes, output, input,
  1870. dataSz, ssl->encrypt.nonce, nonceSz,
  1871. output + dataSz, macSz, aad, aadSz);
  1872. #else
  1873. ret = wc_AesGcmSetExtIV(ssl->encrypt.aes,
  1874. ssl->encrypt.nonce, nonceSz);
  1875. if (ret == 0) {
  1876. ret = wc_AesGcmEncrypt_ex(ssl->encrypt.aes, output,
  1877. input, dataSz, ssl->encrypt.nonce, nonceSz,
  1878. output + dataSz, macSz, aad, aadSz);
  1879. }
  1880. #endif
  1881. break;
  1882. #endif
  1883. #ifdef HAVE_AESCCM
  1884. case wolfssl_aes_ccm:
  1885. #ifdef WOLFSSL_ASYNC_CRYPT
  1886. /* initialize event */
  1887. asyncDev = &ssl->encrypt.aes->asyncDev;
  1888. ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
  1889. if (ret != 0)
  1890. break;
  1891. #endif
  1892. nonceSz = AESCCM_NONCE_SZ;
  1893. #if ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
  1894. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
  1895. ret = wc_AesCcmEncrypt(ssl->encrypt.aes, output, input,
  1896. dataSz, ssl->encrypt.nonce, nonceSz,
  1897. output + dataSz, macSz, aad, aadSz);
  1898. #else
  1899. ret = wc_AesCcmSetNonce(ssl->encrypt.aes,
  1900. ssl->encrypt.nonce, nonceSz);
  1901. if (ret == 0) {
  1902. ret = wc_AesCcmEncrypt_ex(ssl->encrypt.aes, output,
  1903. input, dataSz, ssl->encrypt.nonce, nonceSz,
  1904. output + dataSz, macSz, aad, aadSz);
  1905. }
  1906. #endif
  1907. break;
  1908. #endif
  1909. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  1910. case wolfssl_chacha:
  1911. ret = ChaCha20Poly1305_Encrypt(ssl, output, input, dataSz,
  1912. ssl->encrypt.nonce, aad, aadSz, output + dataSz);
  1913. break;
  1914. #endif
  1915. #ifdef HAVE_NULL_CIPHER
  1916. case wolfssl_cipher_null:
  1917. ret = Tls13IntegrityOnly_Encrypt(ssl, output, input, dataSz,
  1918. ssl->encrypt.nonce, aad, aadSz, output + dataSz);
  1919. break;
  1920. #endif
  1921. default:
  1922. WOLFSSL_MSG("wolfSSL Encrypt programming error");
  1923. return ENCRYPT_ERROR;
  1924. }
  1925. /* Advance state */
  1926. ssl->encrypt.state = CIPHER_STATE_END;
  1927. #ifdef WOLFSSL_ASYNC_CRYPT
  1928. if (ret == WC_PENDING_E) {
  1929. /* if async is not okay, then block */
  1930. if (!asyncOkay) {
  1931. ret = wc_AsyncWait(ret, asyncDev, event_flags);
  1932. }
  1933. else {
  1934. /* If pending, then leave and return will resume below */
  1935. return wolfSSL_AsyncPush(ssl, asyncDev);
  1936. }
  1937. }
  1938. #endif
  1939. }
  1940. FALL_THROUGH;
  1941. case CIPHER_STATE_END:
  1942. {
  1943. #ifdef WOLFSSL_DEBUG_TLS
  1944. #ifdef CIPHER_NONCE
  1945. WOLFSSL_MSG("Nonce");
  1946. WOLFSSL_BUFFER(ssl->encrypt.nonce, ssl->specs.iv_size);
  1947. #endif
  1948. WOLFSSL_MSG("Encrypted data");
  1949. WOLFSSL_BUFFER(output, dataSz);
  1950. WOLFSSL_MSG("Authentication Tag");
  1951. WOLFSSL_BUFFER(output + dataSz, macSz);
  1952. #endif
  1953. #ifdef WOLFSSL_CIPHER_TEXT_CHECK
  1954. if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null &&
  1955. XMEMCMP(output, ssl->encrypt.sanityCheck,
  1956. min(dataSz, sizeof(ssl->encrypt.sanityCheck))) == 0) {
  1957. WOLFSSL_MSG("EncryptTls13 sanity check failed! Glitch?");
  1958. return ENCRYPT_ERROR;
  1959. }
  1960. ForceZero(ssl->encrypt.sanityCheck,
  1961. sizeof(ssl->encrypt.sanityCheck));
  1962. #endif
  1963. #ifdef WOLFSSL_CHECK_MEM_ZERO
  1964. if ((ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) &&
  1965. (output != input) && (ret == 0)) {
  1966. wc_MemZero_Add("TLS 1.3 Encrypt plaintext", input, sz);
  1967. }
  1968. #endif
  1969. #ifdef CIPHER_NONCE
  1970. ForceZero(ssl->encrypt.nonce, AEAD_NONCE_SZ);
  1971. #endif
  1972. break;
  1973. }
  1974. default:
  1975. break;
  1976. }
  1977. /* Reset state */
  1978. ssl->encrypt.state = CIPHER_STATE_BEGIN;
  1979. return ret;
  1980. }
  1981. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  1982. /* Decrypt with ChaCha20 and check authentication tag with Poly1305.
  1983. *
  1984. * ssl The SSL/TLS object.
  1985. * output The buffer to write decrypted data into.
  1986. * May be the same pointer as input.
  1987. * input The data to decrypt.
  1988. * sz The number of bytes to decrypt.
  1989. * nonce The nonce to use with ChaCha20.
  1990. * aad The additional authentication data.
  1991. * aadSz The size of the addition authentication data.
  1992. * tagIn The authentication tag data from packet.
  1993. * returns 0 on success, otherwise failure.
  1994. */
  1995. static int ChaCha20Poly1305_Decrypt(WOLFSSL* ssl, byte* output,
  1996. const byte* input, word16 sz, byte* nonce,
  1997. const byte* aad, word16 aadSz,
  1998. const byte* tagIn)
  1999. {
  2000. int ret;
  2001. byte tag[POLY1305_AUTH_SZ];
  2002. byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for mac */
  2003. /* Poly1305 key is 256 bits of zero encrypted with ChaCha20. */
  2004. XMEMSET(poly, 0, sizeof(poly));
  2005. /* Set nonce and get Poly1305 key. */
  2006. ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 0);
  2007. if (ret != 0)
  2008. return ret;
  2009. /* Use ChaCha20 keystream to get Poly1305 key for tag. */
  2010. ret = wc_Chacha_Process(ssl->decrypt.chacha, poly, poly, sizeof(poly));
  2011. if (ret != 0)
  2012. return ret;
  2013. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2014. wc_MemZero_Add("ChaCha20Poly1305_Decrypt poly", poly, sizeof(poly));
  2015. #endif
  2016. ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 1);
  2017. if (ret != 0) {
  2018. ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
  2019. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2020. wc_MemZero_Check(poly, sizeof(poly));
  2021. #endif
  2022. return ret;
  2023. }
  2024. /* Set key for Poly1305. */
  2025. ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly, sizeof(poly));
  2026. ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
  2027. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2028. wc_MemZero_Check(poly, sizeof(poly));
  2029. #endif
  2030. if (ret != 0)
  2031. return ret;
  2032. /* Generate authentication tag for encrypted data. */
  2033. if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, aad, aadSz, input, sz, tag,
  2034. sizeof(tag))) != 0) {
  2035. return ret;
  2036. }
  2037. /* Check tag sent along with packet. */
  2038. if (ConstantCompare(tagIn, tag, POLY1305_AUTH_SZ) != 0) {
  2039. WOLFSSL_MSG("MAC did not match");
  2040. return VERIFY_MAC_ERROR;
  2041. }
  2042. /* If the tag was good decrypt message. */
  2043. ret = wc_Chacha_Process(ssl->decrypt.chacha, output, input, sz);
  2044. return ret;
  2045. }
  2046. #endif
  2047. #ifdef HAVE_NULL_CIPHER
  2048. /* Check HMAC tag and copy over input.
  2049. *
  2050. * ssl The SSL/TLS object.
  2051. * output The buffer to copy data into.
  2052. * May be the same pointer as input.
  2053. * input The data.
  2054. * sz The number of bytes of data.
  2055. * nonce The nonce to use with authentication.
  2056. * aad The additional authentication data.
  2057. * aadSz The size of the addition authentication data.
  2058. * tagIn The authentication tag data from packet.
  2059. * returns 0 on success, otherwise failure.
  2060. */
  2061. static int Tls13IntegrityOnly_Decrypt(WOLFSSL* ssl, byte* output,
  2062. const byte* input, word16 sz,
  2063. const byte* nonce,
  2064. const byte* aad, word16 aadSz,
  2065. const byte* tagIn)
  2066. {
  2067. int ret;
  2068. byte hmac[WC_MAX_DIGEST_SIZE];
  2069. /* HMAC: nonce | aad | input */
  2070. ret = wc_HmacUpdate(ssl->decrypt.hmac, nonce, HMAC_NONCE_SZ);
  2071. if (ret == 0)
  2072. ret = wc_HmacUpdate(ssl->decrypt.hmac, aad, aadSz);
  2073. if (ret == 0)
  2074. ret = wc_HmacUpdate(ssl->decrypt.hmac, input, sz);
  2075. if (ret == 0)
  2076. ret = wc_HmacFinal(ssl->decrypt.hmac, hmac);
  2077. /* Check authentication tag matches */
  2078. if (ret == 0 && ConstantCompare(tagIn, hmac, ssl->specs.hash_size) != 0)
  2079. ret = DECRYPT_ERROR;
  2080. /* Copy the input to output if not the same buffer */
  2081. if (ret == 0 && output != input)
  2082. XMEMCPY(output, input, sz);
  2083. return ret;
  2084. }
  2085. #endif
  2086. /* Decrypt data for TLS v1.3.
  2087. *
  2088. * ssl The SSL/TLS object.
  2089. * output The buffer to write decrypted data into.
  2090. * May be the same pointer as input.
  2091. * input The data to decrypt and authentication tag.
  2092. * sz The length of the encrypted data plus authentication tag.
  2093. * aad The additional authentication data.
  2094. * aadSz The size of the addition authentication data.
  2095. * returns 0 on success, otherwise failure.
  2096. */
  2097. int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz,
  2098. const byte* aad, word16 aadSz)
  2099. {
  2100. int ret = 0;
  2101. word16 dataSz = sz - ssl->specs.aead_mac_size;
  2102. word16 macSz = ssl->specs.aead_mac_size;
  2103. word32 nonceSz = 0;
  2104. WOLFSSL_ENTER("DecryptTls13");
  2105. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  2106. ret = tsip_Tls13AesDecrypt(ssl, output, input, sz);
  2107. if (ret != CRYPTOCB_UNAVAILABLE) {
  2108. #ifndef WOLFSSL_EARLY_DATA
  2109. if (ret < 0) {
  2110. ret = VERIFY_MAC_ERROR;
  2111. WOLFSSL_ERROR_VERBOSE(ret);
  2112. }
  2113. #endif
  2114. return ret;
  2115. }
  2116. #endif
  2117. #ifdef WOLFSSL_ASYNC_CRYPT
  2118. ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state);
  2119. if (ret != WC_NOT_PENDING_E) {
  2120. /* check for still pending */
  2121. if (ret == WC_PENDING_E)
  2122. return ret;
  2123. ssl->error = 0; /* clear async */
  2124. /* let failures through so CIPHER_STATE_END logic is run */
  2125. }
  2126. else
  2127. #endif
  2128. {
  2129. /* Reset state */
  2130. ret = 0;
  2131. ssl->decrypt.state = CIPHER_STATE_BEGIN;
  2132. }
  2133. (void)output;
  2134. (void)input;
  2135. (void)sz;
  2136. (void)dataSz;
  2137. (void)macSz;
  2138. (void)nonceSz;
  2139. switch (ssl->decrypt.state) {
  2140. case CIPHER_STATE_BEGIN:
  2141. {
  2142. #ifdef WOLFSSL_DEBUG_TLS
  2143. WOLFSSL_MSG("Data to decrypt");
  2144. WOLFSSL_BUFFER(input, dataSz);
  2145. WOLFSSL_MSG("Additional Authentication Data");
  2146. WOLFSSL_BUFFER(aad, aadSz);
  2147. WOLFSSL_MSG("Authentication tag");
  2148. WOLFSSL_BUFFER(input + dataSz, macSz);
  2149. #endif
  2150. #ifdef CIPHER_NONCE
  2151. if (ssl->decrypt.nonce == NULL) {
  2152. ssl->decrypt.nonce = (byte*)XMALLOC(AEAD_NONCE_SZ,
  2153. ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  2154. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2155. if (ssl->decrypt.nonce != NULL) {
  2156. wc_MemZero_Add("DecryptTls13 nonce", ssl->decrypt.nonce,
  2157. AEAD_NONCE_SZ);
  2158. }
  2159. #endif
  2160. }
  2161. if (ssl->decrypt.nonce == NULL)
  2162. return MEMORY_E;
  2163. BuildTls13Nonce(ssl, ssl->decrypt.nonce, ssl->keys.aead_dec_imp_IV,
  2164. PEER_ORDER);
  2165. #endif
  2166. /* Advance state and proceed */
  2167. ssl->decrypt.state = CIPHER_STATE_DO;
  2168. }
  2169. FALL_THROUGH;
  2170. case CIPHER_STATE_DO:
  2171. {
  2172. switch (ssl->specs.bulk_cipher_algorithm) {
  2173. #ifdef BUILD_AESGCM
  2174. case wolfssl_aes_gcm:
  2175. #ifdef WOLFSSL_ASYNC_CRYPT
  2176. /* initialize event */
  2177. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
  2178. WC_ASYNC_FLAG_NONE);
  2179. if (ret != 0)
  2180. break;
  2181. #endif
  2182. nonceSz = AESGCM_NONCE_SZ;
  2183. ret = wc_AesGcmDecrypt(ssl->decrypt.aes, output, input,
  2184. dataSz, ssl->decrypt.nonce, nonceSz,
  2185. input + dataSz, macSz, aad, aadSz);
  2186. #ifdef WOLFSSL_ASYNC_CRYPT
  2187. if (ret == WC_PENDING_E) {
  2188. ret = wolfSSL_AsyncPush(ssl,
  2189. &ssl->decrypt.aes->asyncDev);
  2190. }
  2191. #endif
  2192. break;
  2193. #endif
  2194. #ifdef HAVE_AESCCM
  2195. case wolfssl_aes_ccm:
  2196. #ifdef WOLFSSL_ASYNC_CRYPT
  2197. /* initialize event */
  2198. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
  2199. WC_ASYNC_FLAG_NONE);
  2200. if (ret != 0)
  2201. break;
  2202. #endif
  2203. nonceSz = AESCCM_NONCE_SZ;
  2204. ret = wc_AesCcmDecrypt(ssl->decrypt.aes, output, input,
  2205. dataSz, ssl->decrypt.nonce, nonceSz,
  2206. input + dataSz, macSz, aad, aadSz);
  2207. #ifdef WOLFSSL_ASYNC_CRYPT
  2208. if (ret == WC_PENDING_E) {
  2209. ret = wolfSSL_AsyncPush(ssl,
  2210. &ssl->decrypt.aes->asyncDev);
  2211. }
  2212. #endif
  2213. break;
  2214. #endif
  2215. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  2216. case wolfssl_chacha:
  2217. ret = ChaCha20Poly1305_Decrypt(ssl, output, input, dataSz,
  2218. ssl->decrypt.nonce, aad, aadSz, input + dataSz);
  2219. break;
  2220. #endif
  2221. #ifdef HAVE_NULL_CIPHER
  2222. case wolfssl_cipher_null:
  2223. ret = Tls13IntegrityOnly_Decrypt(ssl, output, input, dataSz,
  2224. ssl->decrypt.nonce, aad, aadSz, input + dataSz);
  2225. break;
  2226. #endif
  2227. default:
  2228. WOLFSSL_MSG("wolfSSL Decrypt programming error");
  2229. return DECRYPT_ERROR;
  2230. }
  2231. /* Advance state */
  2232. ssl->decrypt.state = CIPHER_STATE_END;
  2233. #ifdef WOLFSSL_ASYNC_CRYPT
  2234. /* If pending, leave now */
  2235. if (ret == WC_PENDING_E) {
  2236. return ret;
  2237. }
  2238. #endif
  2239. }
  2240. FALL_THROUGH;
  2241. case CIPHER_STATE_END:
  2242. {
  2243. #ifdef WOLFSSL_DEBUG_TLS
  2244. #ifdef CIPHER_NONCE
  2245. WOLFSSL_MSG("Nonce");
  2246. WOLFSSL_BUFFER(ssl->decrypt.nonce, ssl->specs.iv_size);
  2247. #endif
  2248. WOLFSSL_MSG("Decrypted data");
  2249. WOLFSSL_BUFFER(output, dataSz);
  2250. #endif
  2251. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2252. if ((ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) &&
  2253. (ret == 0)) {
  2254. wc_MemZero_Add("TLS 1.3 Decrypted data", output, sz);
  2255. }
  2256. #endif
  2257. #ifdef CIPHER_NONCE
  2258. ForceZero(ssl->decrypt.nonce, AEAD_NONCE_SZ);
  2259. #endif
  2260. break;
  2261. }
  2262. default:
  2263. break;
  2264. }
  2265. if (ret < 0) {
  2266. WOLFSSL_ERROR_VERBOSE(ret);
  2267. }
  2268. return ret;
  2269. }
  2270. /* Persistable BuildTls13Message arguments */
  2271. typedef struct BuildMsg13Args {
  2272. word32 sz;
  2273. word32 idx;
  2274. word32 headerSz;
  2275. word16 size;
  2276. } BuildMsg13Args;
  2277. static void FreeBuildMsg13Args(WOLFSSL* ssl, void* pArgs)
  2278. {
  2279. BuildMsg13Args* args = (BuildMsg13Args*)pArgs;
  2280. (void)ssl;
  2281. (void)args;
  2282. /* no allocations in BuildTls13Message */
  2283. }
  2284. /* Build SSL Message, encrypted.
  2285. * TLS v1.3 encryption is AEAD only.
  2286. *
  2287. * ssl The SSL/TLS object.
  2288. * output The buffer to write record message to.
  2289. * outSz Size of the buffer being written into.
  2290. * input The record data to encrypt (excluding record header).
  2291. * inSz The size of the record data.
  2292. * type The recorder header content type.
  2293. * hashOutput Whether to hash the unencrypted record data.
  2294. * sizeOnly Only want the size of the record message.
  2295. * asyncOkay If non-zero can return WC_PENDING_E, otherwise blocks on crypto
  2296. * returns the size of the encrypted record message or negative value on error.
  2297. */
  2298. int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input,
  2299. int inSz, int type, int hashOutput, int sizeOnly, int asyncOkay)
  2300. {
  2301. int ret;
  2302. BuildMsg13Args* args;
  2303. BuildMsg13Args lcl_args;
  2304. WOLFSSL_ENTER("BuildTls13Message");
  2305. #ifdef WOLFSSL_ASYNC_CRYPT
  2306. ret = WC_NOT_PENDING_E;
  2307. if (asyncOkay) {
  2308. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  2309. if (ssl->async == NULL) {
  2310. ssl->async = (struct WOLFSSL_ASYNC*)
  2311. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  2312. DYNAMIC_TYPE_ASYNC);
  2313. if (ssl->async == NULL)
  2314. return MEMORY_E;
  2315. }
  2316. args = (BuildMsg13Args*)ssl->async->args;
  2317. ret = wolfSSL_AsyncPop(ssl, &ssl->options.buildMsgState);
  2318. if (ret != WC_NOT_PENDING_E) {
  2319. /* Check for error */
  2320. if (ret < 0)
  2321. goto exit_buildmsg;
  2322. }
  2323. }
  2324. else
  2325. #endif
  2326. {
  2327. args = &lcl_args;
  2328. }
  2329. /* Reset state */
  2330. #ifdef WOLFSSL_ASYNC_CRYPT
  2331. if (ret == WC_NOT_PENDING_E)
  2332. #endif
  2333. {
  2334. ret = 0;
  2335. ssl->options.buildMsgState = BUILD_MSG_BEGIN;
  2336. XMEMSET(args, 0, sizeof(BuildMsg13Args));
  2337. args->headerSz = RECORD_HEADER_SZ;
  2338. #ifdef WOLFSSL_DTLS13
  2339. if (ssl->options.dtls)
  2340. args->headerSz = Dtls13GetRlHeaderLength(1);
  2341. #endif /* WOLFSSL_DTLS13 */
  2342. args->sz = args->headerSz + inSz;
  2343. args->idx = args->headerSz;
  2344. #ifdef WOLFSSL_ASYNC_CRYPT
  2345. if (asyncOkay)
  2346. ssl->async->freeArgs = FreeBuildMsg13Args;
  2347. #endif
  2348. }
  2349. switch (ssl->options.buildMsgState) {
  2350. case BUILD_MSG_BEGIN:
  2351. {
  2352. /* catch mistaken sizeOnly parameter */
  2353. if (sizeOnly) {
  2354. if (output || input) {
  2355. WOLFSSL_MSG("BuildTls13Message with sizeOnly "
  2356. "doesn't need input or output");
  2357. return BAD_FUNC_ARG;
  2358. }
  2359. }
  2360. else if (output == NULL || input == NULL) {
  2361. return BAD_FUNC_ARG;
  2362. }
  2363. /* Record layer content type at the end of record data. */
  2364. args->sz++;
  2365. /* Authentication data at the end. */
  2366. args->sz += ssl->specs.aead_mac_size;
  2367. if (sizeOnly)
  2368. return args->sz;
  2369. if (args->sz > (word32)outSz) {
  2370. WOLFSSL_MSG("Oops, want to write past output buffer size");
  2371. return BUFFER_E;
  2372. }
  2373. /* Record data length. */
  2374. args->size = (word16)(args->sz - args->headerSz);
  2375. /* Write/update the record header with the new size.
  2376. * Always have the content type as application data for encrypted
  2377. * messages in TLS v1.3.
  2378. */
  2379. if (ssl->options.dtls) {
  2380. #ifdef WOLFSSL_DTLS13
  2381. Dtls13RlAddCiphertextHeader(ssl, output, args->size);
  2382. #endif /* WOLFSSL_DTLS13 */
  2383. }
  2384. else {
  2385. AddTls13RecordHeader(output, args->size, application_data, ssl);
  2386. }
  2387. /* TLS v1.3 can do in place encryption. */
  2388. if (input != output + args->idx)
  2389. XMEMCPY(output + args->idx, input, inSz);
  2390. args->idx += inSz;
  2391. ssl->options.buildMsgState = BUILD_MSG_HASH;
  2392. }
  2393. FALL_THROUGH;
  2394. case BUILD_MSG_HASH:
  2395. {
  2396. if (hashOutput) {
  2397. ret = HashOutput(ssl, output, args->headerSz + inSz, 0);
  2398. if (ret != 0)
  2399. goto exit_buildmsg;
  2400. }
  2401. /* The real record content type goes at the end of the data. */
  2402. output[args->idx++] = (byte)type;
  2403. ssl->options.buildMsgState = BUILD_MSG_ENCRYPT;
  2404. }
  2405. FALL_THROUGH;
  2406. case BUILD_MSG_ENCRYPT:
  2407. {
  2408. #ifdef WOLFSSL_QUIC
  2409. if (WOLFSSL_IS_QUIC(ssl)) {
  2410. /* QUIC does not use encryption of the TLS Record Layer.
  2411. * Return the original length + added headers
  2412. * and restore it in the record header. */
  2413. AddTls13RecordHeader(output, inSz, type, ssl);
  2414. ret = args->headerSz + inSz;
  2415. goto exit_buildmsg;
  2416. }
  2417. #endif
  2418. #ifdef ATOMIC_USER
  2419. if (ssl->ctx->MacEncryptCb) {
  2420. /* User Record Layer Callback handling */
  2421. byte* mac = output + args->idx;
  2422. output += args->headerSz;
  2423. ret = ssl->ctx->MacEncryptCb(ssl, mac, output, inSz, type, 0,
  2424. output, output, args->size, ssl->MacEncryptCtx);
  2425. }
  2426. else
  2427. #endif
  2428. {
  2429. const byte* aad = output;
  2430. output += args->headerSz;
  2431. ret = EncryptTls13(ssl, output, output, args->size, aad,
  2432. (word16)args->headerSz, asyncOkay);
  2433. #ifdef WOLFSSL_DTLS13
  2434. if (ret == 0 && ssl->options.dtls) {
  2435. /* AAD points to the header. Reuse the variable */
  2436. ret = Dtls13EncryptRecordNumber(ssl, (byte*)aad, args->sz);
  2437. }
  2438. #endif /* WOLFSSL_DTLS13 */
  2439. }
  2440. break;
  2441. }
  2442. default:
  2443. break;
  2444. }
  2445. exit_buildmsg:
  2446. WOLFSSL_LEAVE("BuildTls13Message", ret);
  2447. #ifdef WOLFSSL_ASYNC_CRYPT
  2448. if (ret == WC_PENDING_E) {
  2449. return ret;
  2450. }
  2451. #endif
  2452. /* make sure build message state is reset */
  2453. ssl->options.buildMsgState = BUILD_MSG_BEGIN;
  2454. /* return sz on success */
  2455. if (ret == 0) {
  2456. ret = args->sz;
  2457. }
  2458. else {
  2459. WOLFSSL_ERROR_VERBOSE(ret);
  2460. }
  2461. /* Final cleanup */
  2462. #ifdef WOLFSSL_ASYNC_CRYPT
  2463. if (asyncOkay)
  2464. FreeAsyncCtx(ssl, 0);
  2465. else
  2466. #endif
  2467. FreeBuildMsg13Args(ssl, args);
  2468. return ret;
  2469. }
  2470. #if !defined(NO_WOLFSSL_CLIENT) || (!defined(NO_WOLFSSL_SERVER) && \
  2471. (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
  2472. defined(WOLFSSL_PSK_ONE_ID)) \
  2473. /* Find the cipher suite in the suites set in the SSL.
  2474. *
  2475. * ssl SSL/TLS object.
  2476. * suite Cipher suite to look for.
  2477. * returns 1 when suite is found in SSL/TLS object's list and 0 otherwise.
  2478. */
  2479. static int FindSuiteSSL(WOLFSSL* ssl, byte* suite)
  2480. {
  2481. word16 i;
  2482. for (i = 0; i < ssl->suites->suiteSz; i += 2) {
  2483. if (ssl->suites->suites[i+0] == suite[0] &&
  2484. ssl->suites->suites[i+1] == suite[1]) {
  2485. return 1;
  2486. }
  2487. }
  2488. return 0;
  2489. }
  2490. #endif
  2491. #ifndef NO_PSK
  2492. /* Get the MAC algorithm for the TLS 1.3 cipher suite.
  2493. *
  2494. * @param [in] suite.
  2495. * @return A value from wc_MACAlgorithm enumeration.
  2496. */
  2497. byte SuiteMac(byte* suite)
  2498. {
  2499. byte mac = no_mac;
  2500. if (suite[0] == TLS13_BYTE) {
  2501. switch (suite[1]) {
  2502. #ifdef BUILD_TLS_AES_128_GCM_SHA256
  2503. case TLS_AES_128_GCM_SHA256:
  2504. mac = sha256_mac;
  2505. break;
  2506. #endif
  2507. #ifdef BUILD_TLS_CHACHA20_POLY1305_SHA256
  2508. case TLS_CHACHA20_POLY1305_SHA256:
  2509. mac = sha256_mac;
  2510. break;
  2511. #endif
  2512. #ifdef BUILD_TLS_AES_128_CCM_SHA256
  2513. case TLS_AES_128_CCM_SHA256:
  2514. mac = sha256_mac;
  2515. break;
  2516. #endif
  2517. #ifdef BUILD_TLS_AES_128_CCM_8_SHA256
  2518. case TLS_AES_128_CCM_8_SHA256:
  2519. mac = sha256_mac;
  2520. break;
  2521. #endif
  2522. #ifdef BUILD_TLS_AES_256_GCM_SHA384
  2523. case TLS_AES_256_GCM_SHA384:
  2524. mac = sha384_mac;
  2525. break;
  2526. #endif
  2527. default:
  2528. break;
  2529. }
  2530. }
  2531. #ifdef HAVE_NULL_CIPHER
  2532. else if (suite[0] == ECC_BYTE) {
  2533. switch (suite[1]) {
  2534. #ifdef BUILD_TLS_SHA256_SHA256
  2535. case TLS_SHA256_SHA256:
  2536. mac = sha256_mac;
  2537. break;
  2538. #endif
  2539. #ifdef BUILD_TLS_SHA384_SHA384
  2540. case TLS_SHA384_SHA384:
  2541. mac = sha384_mac;
  2542. break;
  2543. #endif
  2544. default:
  2545. break;
  2546. }
  2547. }
  2548. #endif
  2549. return mac;
  2550. }
  2551. #endif
  2552. #if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
  2553. /* Create Cookie extension using the hash of the first ClientHello.
  2554. *
  2555. * ssl SSL/TLS object.
  2556. * hash The hash data.
  2557. * hashSz The size of the hash data in bytes.
  2558. * returns 0 on success, otherwise failure.
  2559. */
  2560. static int CreateCookie(WOLFSSL* ssl, byte* hash, byte hashSz)
  2561. {
  2562. int ret;
  2563. byte mac[WC_MAX_DIGEST_SIZE] = {0};
  2564. Hmac cookieHmac;
  2565. byte cookieType = 0;
  2566. byte macSz = 0;
  2567. #if !defined(NO_SHA) && defined(NO_SHA256)
  2568. cookieType = SHA;
  2569. macSz = WC_SHA_DIGEST_SIZE;
  2570. #endif /* NO_SHA */
  2571. #ifndef NO_SHA256
  2572. cookieType = WC_SHA256;
  2573. macSz = WC_SHA256_DIGEST_SIZE;
  2574. #endif /* NO_SHA256 */
  2575. ret = wc_HmacInit(&cookieHmac, ssl->heap, INVALID_DEVID);
  2576. if (ret == 0) {
  2577. ret = wc_HmacSetKey(&cookieHmac, cookieType,
  2578. ssl->buffers.tls13CookieSecret.buffer,
  2579. ssl->buffers.tls13CookieSecret.length);
  2580. }
  2581. if (ret == 0)
  2582. ret = wc_HmacUpdate(&cookieHmac, hash, hashSz);
  2583. #ifdef WOLFSSL_DTLS13
  2584. /* Tie cookie to peer address */
  2585. if (ret == 0) {
  2586. if (ssl->options.dtls && ssl->buffers.dtlsCtx.peer.sz > 0) {
  2587. ret = wc_HmacUpdate(&cookieHmac, ssl->buffers.dtlsCtx.peer.sa,
  2588. ssl->buffers.dtlsCtx.peer.sz);
  2589. }
  2590. }
  2591. #endif
  2592. if (ret == 0)
  2593. ret = wc_HmacFinal(&cookieHmac, mac);
  2594. wc_HmacFree(&cookieHmac);
  2595. if (ret != 0)
  2596. return ret;
  2597. /* The cookie data is the hash and the integrity check. */
  2598. return TLSX_Cookie_Use(ssl, hash, hashSz, mac, macSz, 1);
  2599. }
  2600. #endif
  2601. #define HRR_MAX_HS_HEADER_SZ HANDSHAKE_HEADER_SZ
  2602. /* Restart the handshake hash with a hash of the previous messages.
  2603. *
  2604. * ssl The SSL/TLS object.
  2605. * returns 0 on success, otherwise failure.
  2606. */
  2607. int RestartHandshakeHash(WOLFSSL* ssl)
  2608. {
  2609. int ret;
  2610. Hashes hashes;
  2611. byte header[HRR_MAX_HS_HEADER_SZ] = {0};
  2612. byte* hash = NULL;
  2613. byte hashSz = 0;
  2614. ret = BuildCertHashes(ssl, &hashes);
  2615. if (ret != 0)
  2616. return ret;
  2617. switch (ssl->specs.mac_algorithm) {
  2618. #ifndef NO_SHA256
  2619. case sha256_mac:
  2620. hash = hashes.sha256;
  2621. break;
  2622. #endif
  2623. #ifdef WOLFSSL_SHA384
  2624. case sha384_mac:
  2625. hash = hashes.sha384;
  2626. break;
  2627. #endif
  2628. #ifdef WOLFSSL_TLS13_SHA512
  2629. case sha512_mac:
  2630. hash = hashes.sha512;
  2631. break;
  2632. #endif
  2633. }
  2634. hashSz = ssl->specs.hash_size;
  2635. /* check hash */
  2636. if (hash == NULL && hashSz > 0)
  2637. return BAD_FUNC_ARG;
  2638. AddTls13HandShakeHeader(header, hashSz, 0, 0, message_hash, ssl);
  2639. #ifdef WOLFSSL_DEBUG_TLS
  2640. WOLFSSL_MSG("Restart Hash");
  2641. WOLFSSL_BUFFER(hash, hashSz);
  2642. #endif
  2643. #if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
  2644. if (ssl->options.sendCookie && ssl->options.side == WOLFSSL_SERVER_END) {
  2645. byte cookie[OPAQUE8_LEN + WC_MAX_DIGEST_SIZE + OPAQUE16_LEN * 2];
  2646. TLSX* ext;
  2647. word32 idx = 0;
  2648. /* Cookie Data = Hash Len | Hash | CS | KeyShare Group */
  2649. cookie[idx++] = hashSz;
  2650. if (hash)
  2651. XMEMCPY(cookie + idx, hash, hashSz);
  2652. idx += hashSz;
  2653. cookie[idx++] = ssl->options.cipherSuite0;
  2654. cookie[idx++] = ssl->options.cipherSuite;
  2655. if ((ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE)) != NULL) {
  2656. KeyShareEntry* kse = (KeyShareEntry*)ext->data;
  2657. c16toa(kse->group, cookie + idx);
  2658. idx += OPAQUE16_LEN;
  2659. }
  2660. return CreateCookie(ssl, cookie, idx);
  2661. }
  2662. #endif
  2663. ret = InitHandshakeHashes(ssl);
  2664. if (ret != 0)
  2665. return ret;
  2666. ret = HashRaw(ssl, header, sizeof(header));
  2667. if (ret != 0)
  2668. return ret;
  2669. return HashRaw(ssl, hash, hashSz);
  2670. }
  2671. #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
  2672. /* The value in the random field of a ServerHello to indicate
  2673. * HelloRetryRequest.
  2674. */
  2675. static byte helloRetryRequestRandom[] = {
  2676. 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
  2677. 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
  2678. 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
  2679. 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
  2680. };
  2681. #endif
  2682. #ifndef NO_WOLFSSL_CLIENT
  2683. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  2684. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_PSK_ONE_ID) && \
  2685. !defined(NO_PSK)
  2686. /**
  2687. * convert mac algorithm to WOLFSSL_EVP_MD
  2688. * @param mac_alg mac algorithm
  2689. * @return const WOLFSSL_EVP_MD on successful, otherwise NULL
  2690. */
  2691. static const WOLFSSL_EVP_MD* ssl_handshake_md(const byte mac_alg)
  2692. {
  2693. switch(mac_alg) {
  2694. case no_mac:
  2695. #ifndef NO_MD5
  2696. case md5_mac:
  2697. return wolfSSL_EVP_md5();
  2698. #endif
  2699. #ifndef NO_SHA
  2700. case sha_mac:
  2701. return wolfSSL_EVP_sha1();
  2702. #endif
  2703. #ifdef WOLFSSL_SHA224
  2704. case sha224_mac:
  2705. return wolfSSL_EVP_sha224();
  2706. #endif
  2707. case sha256_mac:
  2708. return wolfSSL_EVP_sha256();
  2709. #ifdef WOLFSSL_SHA384
  2710. case sha384_mac:
  2711. return wolfSSL_EVP_sha384();
  2712. #endif
  2713. #ifdef WOLFSSL_SHA512
  2714. case sha512_mac:
  2715. return wolfSSL_EVP_sha512();
  2716. #endif
  2717. case rmd_mac:
  2718. case blake2b_mac:
  2719. WOLFSSL_MSG("no suitable EVP_MD");
  2720. return NULL;
  2721. default:
  2722. WOLFSSL_MSG("Unknown mac algorithm");
  2723. return NULL;
  2724. }
  2725. }
  2726. #endif
  2727. /* Setup pre-shared key based on the details in the extension data.
  2728. *
  2729. * ssl SSL/TLS object.
  2730. * psk Pre-shared key extension data.
  2731. * clientHello Whether called from client_hello construction.
  2732. * returns 0 on success, PSK_KEY_ERROR when the client PSK callback fails and
  2733. * other negative value on failure.
  2734. */
  2735. static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk, int clientHello)
  2736. {
  2737. #if defined(HAVE_SESSION_TICKET) || !defined(WOLFSSL_PSK_ONE_ID)
  2738. int ret;
  2739. #endif
  2740. byte suite[2];
  2741. if (psk == NULL)
  2742. return BAD_FUNC_ARG;
  2743. suite[0] = ssl->options.cipherSuite0;
  2744. suite[1] = ssl->options.cipherSuite;
  2745. #ifdef HAVE_SESSION_TICKET
  2746. if (psk->resumption) {
  2747. if (clientHello) {
  2748. /* Ensure cipher suite is supported or changed suite to one with
  2749. * the same MAC algorithm. */
  2750. if (!FindSuiteSSL(ssl, suite)) {
  2751. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  2752. return PSK_KEY_ERROR;
  2753. }
  2754. /* Setting mac for binder and keys for deriving EarlyData. */
  2755. ret = SetCipherSpecs(ssl);
  2756. if (ret != 0)
  2757. return ret;
  2758. }
  2759. #ifdef WOLFSSL_EARLY_DATA
  2760. if (ssl->session->maxEarlyDataSz == 0)
  2761. ssl->earlyData = no_early_data;
  2762. #endif
  2763. /* Resumption PSK is master secret. */
  2764. ssl->arrays->psk_keySz = ssl->specs.hash_size;
  2765. if ((ret = DeriveResumptionPSK(ssl, ssl->session->ticketNonce.data,
  2766. ssl->session->ticketNonce.len, ssl->arrays->psk_key)) != 0) {
  2767. return ret;
  2768. }
  2769. if (!clientHello) {
  2770. /* CLIENT: using secret in ticket for peer authentication. */
  2771. ssl->options.peerAuthGood = 1;
  2772. }
  2773. }
  2774. #endif
  2775. #ifndef NO_PSK
  2776. if (!psk->resumption) {
  2777. /* Get the pre-shared key. */
  2778. #ifndef WOLFSSL_PSK_ONE_ID
  2779. const char* cipherName = NULL;
  2780. #ifdef OPENSSL_EXTRA
  2781. WOLFSSL_SESSION* psksession = NULL;
  2782. #endif
  2783. /* Set the client identity to use. */
  2784. XMEMSET(ssl->arrays->client_identity, 0,
  2785. sizeof(ssl->arrays->client_identity));
  2786. XMEMCPY(ssl->arrays->client_identity, psk->identity, psk->identityLen);
  2787. #ifdef WOLFSSL_DEBUG_TLS
  2788. WOLFSSL_MSG("PSK cipher suite:");
  2789. WOLFSSL_MSG(GetCipherNameInternal(psk->cipherSuite0, psk->cipherSuite));
  2790. #endif
  2791. /* Get the pre-shared key. */
  2792. #ifdef OPENSSL_EXTRA
  2793. if (ssl->options.session_psk_cb != NULL) {
  2794. const unsigned char* id = NULL;
  2795. size_t idlen = 0;
  2796. const WOLFSSL_EVP_MD* handshake_md = NULL;
  2797. if (ssl->msgsReceived.got_hello_retry_request >= 1) {
  2798. handshake_md = ssl_handshake_md(ssl->specs.mac_algorithm);
  2799. }
  2800. /* OpenSSL compatible callback that gets cached session. */
  2801. if (ssl->options.session_psk_cb(ssl, handshake_md, &id, &idlen,
  2802. &psksession) == 0) {
  2803. wolfSSL_FreeSession(ssl->ctx, psksession);
  2804. WOLFSSL_MSG("psk session callback failed");
  2805. return PSK_KEY_ERROR;
  2806. }
  2807. if (psksession != NULL) {
  2808. if (idlen > MAX_PSK_KEY_LEN) {
  2809. wolfSSL_FreeSession(ssl->ctx, psksession);
  2810. WOLFSSL_MSG("psk key length is too long");
  2811. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  2812. return PSK_KEY_ERROR;
  2813. }
  2814. ssl->arrays->psk_keySz = (word32)idlen;
  2815. XMEMCPY(ssl->arrays->psk_key, id, idlen);
  2816. suite[0] = psksession->cipherSuite0;
  2817. suite[1] = psksession->cipherSuite;
  2818. /* Not needed anymore. */
  2819. wolfSSL_FreeSession(ssl->ctx, psksession);
  2820. /* Leave pointer not NULL to indicate success with callback. */
  2821. }
  2822. }
  2823. if (psksession != NULL) {
  2824. /* Don't try other callbacks - we have an answer. */
  2825. }
  2826. else
  2827. #endif /* OPENSSL_EXTRA */
  2828. if (ssl->options.client_psk_cs_cb != NULL) {
  2829. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  2830. ssl->arrays->client_identity[0] = 0;
  2831. #endif
  2832. /* Lookup key again for next identity. */
  2833. ssl->arrays->psk_keySz = ssl->options.client_psk_cs_cb(
  2834. ssl, ssl->arrays->server_hint,
  2835. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  2836. ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
  2837. GetCipherNameInternal(psk->cipherSuite0, psk->cipherSuite));
  2838. if (clientHello) {
  2839. /* Use PSK cipher suite. */
  2840. ssl->options.cipherSuite0 = psk->cipherSuite0;
  2841. ssl->options.cipherSuite = psk->cipherSuite;
  2842. }
  2843. else {
  2844. byte pskCS[2] = { psk->cipherSuite0, psk->cipherSuite };
  2845. /* Ensure PSK and negotiated cipher suites have same hash. */
  2846. if (SuiteMac(pskCS) != SuiteMac(suite)) {
  2847. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  2848. return PSK_KEY_ERROR;
  2849. }
  2850. /* Negotiated cipher suite is to be used - update PSK. */
  2851. psk->cipherSuite0 = suite[0];
  2852. psk->cipherSuite = suite[1];
  2853. }
  2854. }
  2855. else if (ssl->options.client_psk_tls13_cb != NULL) {
  2856. byte cipherSuite0;
  2857. byte cipherSuite;
  2858. int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
  2859. ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(ssl,
  2860. ssl->arrays->server_hint, ssl->arrays->client_identity,
  2861. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
  2862. &cipherName);
  2863. if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
  2864. &cipherSuite, &cipherSuiteFlags) != 0) {
  2865. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  2866. return PSK_KEY_ERROR;
  2867. }
  2868. ssl->options.cipherSuite0 = cipherSuite0;
  2869. ssl->options.cipherSuite = cipherSuite;
  2870. (void)cipherSuiteFlags;
  2871. }
  2872. else {
  2873. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  2874. ssl->arrays->server_hint, ssl->arrays->client_identity,
  2875. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  2876. ssl->options.cipherSuite0 = TLS13_BYTE;
  2877. ssl->options.cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
  2878. }
  2879. if (ssl->arrays->psk_keySz == 0 ||
  2880. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  2881. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  2882. return PSK_KEY_ERROR;
  2883. }
  2884. ret = SetCipherSpecs(ssl);
  2885. if (ret != 0)
  2886. return ret;
  2887. #else
  2888. /* PSK information loaded during setting of default TLS extensions. */
  2889. #endif /* !WOLFSSL_PSK_ONE_ID */
  2890. if (!clientHello && (psk->cipherSuite0 != suite[0] ||
  2891. psk->cipherSuite != suite[1])) {
  2892. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  2893. return PSK_KEY_ERROR;
  2894. }
  2895. if (!clientHello) {
  2896. /* CLIENT: using PSK for peer authentication. */
  2897. ssl->options.peerAuthGood = 1;
  2898. }
  2899. }
  2900. #endif
  2901. if (ssl->options.noPskDheKe) {
  2902. ssl->arrays->preMasterSz = 0;
  2903. }
  2904. /* Derive the early secret using the PSK. */
  2905. return DeriveEarlySecret(ssl);
  2906. }
  2907. /* Derive and write the binders into the ClientHello in space left when
  2908. * writing the Pre-Shared Key extension.
  2909. *
  2910. * ssl The SSL/TLS object.
  2911. * output The buffer containing the ClientHello.
  2912. * idx The index at the end of the completed ClientHello.
  2913. * returns 0 on success and otherwise failure.
  2914. */
  2915. static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx)
  2916. {
  2917. int ret;
  2918. TLSX* ext;
  2919. PreSharedKey* current;
  2920. byte binderKey[WC_MAX_DIGEST_SIZE];
  2921. word16 len;
  2922. WOLFSSL_ENTER("WritePSKBinders");
  2923. ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  2924. if (ext == NULL)
  2925. return SANITY_MSG_E;
  2926. /* Get the size of the binders to determine where to write binders. */
  2927. ret = TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
  2928. client_hello, &len);
  2929. if (ret < 0)
  2930. return ret;
  2931. idx -= len;
  2932. /* Hash truncated ClientHello - up to binders. */
  2933. #ifdef WOLFSSL_DTLS13
  2934. if (ssl->options.dtls)
  2935. ret = Dtls13HashHandshake(ssl, output + Dtls13GetRlHeaderLength(0),
  2936. idx - Dtls13GetRlHeaderLength(0));
  2937. else
  2938. #endif /* WOLFSSL_DTLS13 */
  2939. ret = HashOutput(ssl, output, idx, 0);
  2940. if (ret != 0)
  2941. return ret;
  2942. current = (PreSharedKey*)ext->data;
  2943. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2944. if (current != NULL) {
  2945. wc_MemZero_Add("WritePSKBinders binderKey", binderKey,
  2946. sizeof(binderKey));
  2947. }
  2948. #endif
  2949. /* Calculate the binder for each identity based on previous handshake data.
  2950. */
  2951. while (current != NULL) {
  2952. if ((ret = SetupPskKey(ssl, current, 1)) != 0)
  2953. break;
  2954. #ifdef HAVE_SESSION_TICKET
  2955. if (current->resumption)
  2956. ret = DeriveBinderKeyResume(ssl, binderKey);
  2957. #endif
  2958. #ifndef NO_PSK
  2959. if (!current->resumption)
  2960. ret = DeriveBinderKey(ssl, binderKey);
  2961. #endif
  2962. if (ret != 0)
  2963. break;
  2964. /* Derive the Finished message secret. */
  2965. ret = DeriveFinishedSecret(ssl, binderKey,
  2966. ssl->keys.client_write_MAC_secret);
  2967. if (ret != 0)
  2968. break;
  2969. /* Build the HMAC of the handshake message data = binder. */
  2970. ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret,
  2971. current->binder, &current->binderLen);
  2972. if (ret != 0)
  2973. break;
  2974. current = current->next;
  2975. }
  2976. ForceZero(binderKey, sizeof(binderKey));
  2977. #ifdef WOLFSSL_CHECK_MEM_ZERO
  2978. wc_MemZero_Check(binderKey, sizeof(binderKey));
  2979. #endif
  2980. if (ret != 0)
  2981. return ret;
  2982. /* Data entered into extension, now write to message. */
  2983. ret = TLSX_PreSharedKey_WriteBinders((PreSharedKey*)ext->data, output + idx,
  2984. client_hello, &len);
  2985. if (ret < 0)
  2986. return ret;
  2987. /* Hash binders to complete the hash of the ClientHello. */
  2988. ret = HashRaw(ssl, output + idx, len);
  2989. if (ret < 0)
  2990. return ret;
  2991. #ifdef WOLFSSL_EARLY_DATA
  2992. if (ssl->earlyData != no_early_data) {
  2993. if ((ret = SetupPskKey(ssl, (PreSharedKey*)ext->data, 1)) != 0)
  2994. return ret;
  2995. /* Derive early data encryption key. */
  2996. ret = DeriveTls13Keys(ssl, early_data_key, ENCRYPT_SIDE_ONLY, 1);
  2997. if (ret != 0)
  2998. return ret;
  2999. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  3000. return ret;
  3001. #ifdef WOLFSSL_DTLS13
  3002. if (ssl->options.dtls) {
  3003. ret = Dtls13NewEpoch(
  3004. ssl, w64From32(0x0, DTLS13_EPOCH_EARLYDATA), ENCRYPT_SIDE_ONLY);
  3005. if (ret != 0)
  3006. return ret;
  3007. }
  3008. #endif /* WOLFSSL_DTLS13 */
  3009. }
  3010. #endif
  3011. WOLFSSL_LEAVE("WritePSKBinders", ret);
  3012. return ret;
  3013. }
  3014. #endif
  3015. /* handle generation of TLS 1.3 client_hello (1) */
  3016. /* Send a ClientHello message to the server.
  3017. * Include the information required to start a handshake with servers using
  3018. * protocol versions less than TLS v1.3.
  3019. * Only a client will send this message.
  3020. *
  3021. * ssl The SSL/TLS object.
  3022. * returns 0 on success and otherwise failure.
  3023. */
  3024. typedef struct Sch13Args {
  3025. byte* output;
  3026. word32 idx;
  3027. int sendSz;
  3028. word16 length;
  3029. } Sch13Args;
  3030. int SendTls13ClientHello(WOLFSSL* ssl)
  3031. {
  3032. int ret;
  3033. #ifdef WOLFSSL_ASYNC_CRYPT
  3034. Sch13Args* args = NULL;
  3035. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  3036. #else
  3037. Sch13Args args[1];
  3038. #endif
  3039. byte major, tls12minor;
  3040. WOLFSSL_START(WC_FUNC_CLIENT_HELLO_SEND);
  3041. WOLFSSL_ENTER("SendTls13ClientHello");
  3042. if (ssl == NULL) {
  3043. return BAD_FUNC_ARG;
  3044. }
  3045. ssl->options.buildingMsg = 1;
  3046. major = SSLv3_MAJOR;
  3047. tls12minor = TLSv1_2_MINOR;
  3048. #ifdef WOLFSSL_DTLS13
  3049. if (ssl->options.dtls) {
  3050. major = DTLS_MAJOR;
  3051. tls12minor = DTLSv1_2_MINOR;
  3052. }
  3053. #endif /* WOLFSSL_DTLS */
  3054. #ifdef HAVE_SESSION_TICKET
  3055. if (ssl->options.resuming &&
  3056. (ssl->session->version.major != ssl->version.major ||
  3057. ssl->session->version.minor != ssl->version.minor)) {
  3058. #ifndef WOLFSSL_NO_TLS12
  3059. if (ssl->session->version.major == ssl->version.major &&
  3060. ssl->session->version.minor < ssl->version.minor) {
  3061. /* Cannot resume with a different protocol version. */
  3062. ssl->options.resuming = 0;
  3063. ssl->version.major = ssl->session->version.major;
  3064. ssl->version.minor = ssl->session->version.minor;
  3065. return SendClientHello(ssl);
  3066. }
  3067. else
  3068. #endif
  3069. {
  3070. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3071. return VERSION_ERROR;
  3072. }
  3073. }
  3074. #endif
  3075. if (ssl->suites == NULL) {
  3076. WOLFSSL_MSG("Bad suites pointer in SendTls13ClientHello");
  3077. return SUITES_ERROR;
  3078. }
  3079. #ifdef WOLFSSL_ASYNC_CRYPT
  3080. if (ssl->async == NULL) {
  3081. ssl->async = (struct WOLFSSL_ASYNC*)
  3082. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  3083. DYNAMIC_TYPE_ASYNC);
  3084. if (ssl->async == NULL)
  3085. return MEMORY_E;
  3086. ssl->async->freeArgs = NULL;
  3087. }
  3088. args = (Sch13Args*)ssl->async->args;
  3089. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  3090. if (ret != WC_NOT_PENDING_E) {
  3091. /* Check for error */
  3092. if (ret < 0)
  3093. return ret;
  3094. }
  3095. else
  3096. #endif
  3097. {
  3098. /* Reset state */
  3099. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  3100. XMEMSET(args, 0, sizeof(Sch13Args));
  3101. }
  3102. switch (ssl->options.asyncState) {
  3103. case TLS_ASYNC_BEGIN:
  3104. {
  3105. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  3106. #ifdef WOLFSSL_DTLS13
  3107. if (ssl->options.dtls)
  3108. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  3109. #endif /* WOLFSSL_DTLS13 */
  3110. /* Version | Random | Session Id | Cipher Suites | Compression */
  3111. args->length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->suites->suiteSz +
  3112. SUITE_LEN + COMP_LEN + ENUM_LEN;
  3113. #ifdef WOLFSSL_QUIC
  3114. if (WOLFSSL_IS_QUIC(ssl)) {
  3115. /* RFC 9001 ch. 8.4 sessionID in ClientHello MUST be 0 length */
  3116. ssl->session->sessionIDSz = 0;
  3117. ssl->options.tls13MiddleBoxCompat = 0;
  3118. }
  3119. else
  3120. #endif
  3121. #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
  3122. {
  3123. args->length += ID_LEN;
  3124. ssl->options.tls13MiddleBoxCompat = 1;
  3125. }
  3126. #else
  3127. if (ssl->session->sessionIDSz > 0)
  3128. args->length += ssl->session->sessionIDSz;
  3129. #endif
  3130. #ifdef WOLFSSL_DTLS13
  3131. if (ssl->options.dtls) {
  3132. /* legacy_cookie_id len */
  3133. args->length += ENUM_LEN;
  3134. /* server sent us an HelloVerifyRequest and we allow downgrade */
  3135. if (ssl->arrays->cookieSz > 0 && ssl->options.downgrade)
  3136. args->length += ssl->arrays->cookieSz;
  3137. }
  3138. #endif /* WOLFSSL_DTLS13 */
  3139. /* Advance state and proceed */
  3140. ssl->options.asyncState = TLS_ASYNC_BUILD;
  3141. } /* case TLS_ASYNC_BEGIN */
  3142. FALL_THROUGH;
  3143. case TLS_ASYNC_BUILD:
  3144. case TLS_ASYNC_DO:
  3145. {
  3146. /* Auto populate extensions supported unless user defined. */
  3147. if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
  3148. return ret;
  3149. /* Advance state and proceed */
  3150. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  3151. } /* case TLS_ASYNC_BUILD */
  3152. FALL_THROUGH;
  3153. case TLS_ASYNC_FINALIZE:
  3154. {
  3155. #ifdef WOLFSSL_EARLY_DATA
  3156. #ifndef NO_PSK
  3157. if (!ssl->options.resuming &&
  3158. ssl->options.client_psk_tls13_cb == NULL &&
  3159. ssl->options.client_psk_cb == NULL)
  3160. #else
  3161. if (!ssl->options.resuming)
  3162. #endif
  3163. ssl->earlyData = no_early_data;
  3164. if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
  3165. ssl->earlyData = no_early_data;
  3166. if (ssl->earlyData == no_early_data)
  3167. TLSX_Remove(&ssl->extensions, TLSX_EARLY_DATA, ssl->heap);
  3168. if (ssl->earlyData != no_early_data &&
  3169. (ret = TLSX_EarlyData_Use(ssl, 0)) < 0) {
  3170. return ret;
  3171. }
  3172. #endif
  3173. #ifdef WOLFSSL_QUIC
  3174. if (WOLFSSL_IS_QUIC(ssl) && IsAtLeastTLSv1_3(ssl->version)) {
  3175. ret = wolfSSL_quic_add_transport_extensions(ssl, client_hello);
  3176. if (ret != 0)
  3177. return ret;
  3178. }
  3179. #endif
  3180. /* Include length of TLS extensions. */
  3181. ret = TLSX_GetRequestSize(ssl, client_hello, &args->length);
  3182. if (ret != 0)
  3183. return ret;
  3184. /* Total message size. */
  3185. args->sendSz = args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  3186. #ifdef WOLFSSL_DTLS13
  3187. if (ssl->options.dtls)
  3188. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  3189. #endif /* WOLFSSL_DTLS13 */
  3190. /* Check buffers are big enough and grow if needed. */
  3191. if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0)
  3192. return ret;
  3193. /* Get position in output buffer to write new message to. */
  3194. args->output = ssl->buffers.outputBuffer.buffer +
  3195. ssl->buffers.outputBuffer.length;
  3196. /* Put the record and handshake headers on. */
  3197. AddTls13Headers(args->output, args->length, client_hello, ssl);
  3198. /* Protocol version - negotiation now in extension: supported_versions. */
  3199. args->output[args->idx++] = major;
  3200. args->output[args->idx++] = tls12minor;
  3201. /* Keep for downgrade. */
  3202. ssl->chVersion = ssl->version;
  3203. if (ssl->arrays == NULL) {
  3204. return BAD_FUNC_ARG;
  3205. }
  3206. /* Client Random */
  3207. if (ssl->options.connectState == CONNECT_BEGIN) {
  3208. ret = wc_RNG_GenerateBlock(ssl->rng, args->output + args->idx, RAN_LEN);
  3209. if (ret != 0)
  3210. return ret;
  3211. /* Store random for possible second ClientHello. */
  3212. XMEMCPY(ssl->arrays->clientRandom, args->output + args->idx, RAN_LEN);
  3213. }
  3214. else
  3215. XMEMCPY(args->output + args->idx, ssl->arrays->clientRandom, RAN_LEN);
  3216. args->idx += RAN_LEN;
  3217. if (ssl->session->sessionIDSz > 0) {
  3218. /* Session resumption for old versions of protocol. */
  3219. args->output[args->idx++] = ID_LEN;
  3220. XMEMCPY(args->output + args->idx, ssl->session->sessionID,
  3221. ssl->session->sessionIDSz);
  3222. args->idx += ID_LEN;
  3223. }
  3224. else {
  3225. #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
  3226. if (ssl->options.tls13MiddleBoxCompat) {
  3227. args->output[args->idx++] = ID_LEN;
  3228. XMEMCPY(args->output + args->idx, ssl->arrays->clientRandom, ID_LEN);
  3229. args->idx += ID_LEN;
  3230. }
  3231. else
  3232. #endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
  3233. {
  3234. /* TLS v1.3 does not use session id - 0 length. */
  3235. args->output[args->idx++] = 0;
  3236. }
  3237. }
  3238. #ifdef WOLFSSL_DTLS13
  3239. if (ssl->options.dtls) {
  3240. args->output[args->idx++] = ssl->arrays->cookieSz;
  3241. if (ssl->arrays->cookieSz > 0) {
  3242. /* We have a cookie saved, so the server sent us an
  3243. * HelloVerifyRequest, it means it is a v1.2 server */
  3244. if (!ssl->options.downgrade)
  3245. return VERSION_ERROR;
  3246. XMEMCPY(args->output + args->idx, ssl->arrays->cookie,
  3247. ssl->arrays->cookieSz);
  3248. args->idx += ssl->arrays->cookieSz;
  3249. }
  3250. }
  3251. #endif /* WOLFSSL_DTLS13 */
  3252. /* Cipher suites */
  3253. c16toa(ssl->suites->suiteSz, args->output + args->idx);
  3254. args->idx += OPAQUE16_LEN;
  3255. XMEMCPY(args->output + args->idx, &ssl->suites->suites,
  3256. ssl->suites->suiteSz);
  3257. args->idx += ssl->suites->suiteSz;
  3258. #ifdef WOLFSSL_DEBUG_TLS
  3259. {
  3260. int ii;
  3261. WOLFSSL_MSG("Ciphers:");
  3262. for (ii = 0 ; ii < ssl->suites->suiteSz; ii += 2) {
  3263. WOLFSSL_MSG(GetCipherNameInternal(ssl->suites->suites[ii+0],
  3264. ssl->suites->suites[ii+1]));
  3265. }
  3266. }
  3267. #endif
  3268. /* Compression not supported in TLS v1.3. */
  3269. args->output[args->idx++] = COMP_LEN;
  3270. args->output[args->idx++] = NO_COMPRESSION;
  3271. /* Write out extensions for a request. */
  3272. args->length = 0;
  3273. ret = TLSX_WriteRequest(ssl, args->output + args->idx, client_hello,
  3274. &args->length);
  3275. if (ret != 0)
  3276. return ret;
  3277. args->idx += args->length;
  3278. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  3279. /* Resumption has a specific set of extensions and binder is calculated
  3280. * for each identity.
  3281. */
  3282. if (TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY)) {
  3283. ret = WritePSKBinders(ssl, args->output, args->idx);
  3284. }
  3285. else
  3286. #endif
  3287. {
  3288. #ifdef WOLFSSL_DTLS13
  3289. if (ssl->options.dtls)
  3290. ret = Dtls13HashHandshake(ssl,
  3291. args->output + Dtls13GetRlHeaderLength(0),
  3292. args->idx - Dtls13GetRlHeaderLength(0));
  3293. else
  3294. #endif /* WOLFSSL_DTLS13 */
  3295. ret = HashOutput(ssl, args->output, args->idx, 0);
  3296. }
  3297. if (ret != 0)
  3298. return ret;
  3299. ssl->options.clientState = CLIENT_HELLO_COMPLETE;
  3300. #ifdef WOLFSSL_CALLBACKS
  3301. if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
  3302. if (ssl->toInfoOn) {
  3303. AddPacketInfo(ssl, "ClientHello", handshake, args->output, args->sendSz,
  3304. WRITE_PROTO, ssl->heap);
  3305. }
  3306. #endif
  3307. ssl->options.buildingMsg = 0;
  3308. #ifdef WOLFSSL_DTLS13
  3309. if (ssl->options.dtls) {
  3310. ret = Dtls13HandshakeSend(ssl, args->output, args->sendSz,
  3311. args->idx, client_hello, 0);
  3312. WOLFSSL_LEAVE("SendTls13ClientHello", ret);
  3313. WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
  3314. return ret;
  3315. }
  3316. #endif /* WOLFSSL_DTLS13 */
  3317. ssl->buffers.outputBuffer.length += args->sendSz;
  3318. /* Advance state and proceed */
  3319. ssl->options.asyncState = TLS_ASYNC_END;
  3320. /* case TLS_ASYNC_BUILD */
  3321. FALL_THROUGH;
  3322. case TLS_ASYNC_END:
  3323. #ifdef WOLFSSL_EARLY_DATA_GROUP
  3324. /* QUIC needs to forward records at their encryption level
  3325. * and is therefore unable to group here */
  3326. if (ssl->earlyData == no_early_data || WOLFSSL_IS_QUIC(ssl))
  3327. #endif
  3328. ret = SendBuffered(ssl);
  3329. break;
  3330. }
  3331. default:
  3332. ret = INPUT_CASE_ERROR;
  3333. } /* switch (ssl->options.asyncState) */
  3334. #ifdef WOLFSSL_ASYNC_CRYPT
  3335. if (ret == 0)
  3336. FreeAsyncCtx(ssl, 0);
  3337. #endif
  3338. WOLFSSL_LEAVE("SendTls13ClientHello", ret);
  3339. WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
  3340. return ret;
  3341. }
  3342. #if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_CLIENT)
  3343. static int Dtls13DoDowngrade(WOLFSSL* ssl)
  3344. {
  3345. int ret;
  3346. if (ssl->dtls13ClientHello == NULL)
  3347. return BAD_STATE_E;
  3348. /* v1.3 and v1.2 hash messages to compute the transcript hash. When we are
  3349. * using DTLSv1.3 we hash the first clientHello following v1.3 but the
  3350. * server can negotiate a lower version. So we need to re-hash the
  3351. * clientHello to adhere to DTLS <= v1.2 rules. */
  3352. ret = InitHandshakeHashes(ssl);
  3353. if (ret != 0)
  3354. return ret;
  3355. ret = HashRaw(ssl, ssl->dtls13ClientHello, ssl->dtls13ClientHelloSz);
  3356. XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  3357. ssl->dtls13ClientHello = NULL;
  3358. ssl->dtls13ClientHelloSz = 0;
  3359. ssl->keys.dtls_sequence_number_hi =
  3360. w64GetHigh32(ssl->dtls13EncryptEpoch->nextSeqNumber);
  3361. ssl->keys.dtls_sequence_number_lo =
  3362. w64GetLow32(ssl->dtls13EncryptEpoch->nextSeqNumber);
  3363. return ret;
  3364. }
  3365. #endif /* WOLFSSL_DTLS13 && !WOLFSSL_NO_CLIENT*/
  3366. /* handle processing of TLS 1.3 server_hello (2) and hello_retry_request (6) */
  3367. /* Handle the ServerHello message from the server.
  3368. * Only a client will receive this message.
  3369. *
  3370. * ssl The SSL/TLS object.
  3371. * input The message buffer.
  3372. * inOutIdx On entry, the index into the message buffer of ServerHello.
  3373. * On exit, the index of byte after the ServerHello message.
  3374. * helloSz The length of the current handshake message.
  3375. * returns 0 on success and otherwise failure.
  3376. */
  3377. typedef struct Dsh13Args {
  3378. ProtocolVersion pv;
  3379. word32 idx;
  3380. word32 begin;
  3381. const byte* sessId;
  3382. word16 totalExtSz;
  3383. byte sessIdSz;
  3384. byte extMsgType;
  3385. } Dsh13Args;
  3386. int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  3387. word32 helloSz, byte* extMsgType)
  3388. {
  3389. int ret;
  3390. byte suite[2];
  3391. byte tls12minor;
  3392. #ifdef WOLFSSL_ASYNC_CRYPT
  3393. Dsh13Args* args = NULL;
  3394. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  3395. #else
  3396. Dsh13Args args[1];
  3397. #endif
  3398. WOLFSSL_START(WC_FUNC_SERVER_HELLO_DO);
  3399. WOLFSSL_ENTER("DoTls13ServerHello");
  3400. tls12minor = TLSv1_2_MINOR;
  3401. #ifdef WOLFSSL_DTLS13
  3402. if (ssl->options.dtls)
  3403. tls12minor = DTLSv1_2_MINOR;
  3404. #endif /* WOLFSSL_DTLS13 */
  3405. if (ssl == NULL || ssl->arrays == NULL)
  3406. return BAD_FUNC_ARG;
  3407. #ifdef WOLFSSL_ASYNC_CRYPT
  3408. if (ssl->async == NULL) {
  3409. ssl->async = (struct WOLFSSL_ASYNC*)
  3410. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  3411. DYNAMIC_TYPE_ASYNC);
  3412. if (ssl->async == NULL)
  3413. return MEMORY_E;
  3414. ssl->async->freeArgs = NULL;
  3415. }
  3416. args = (Dsh13Args*)ssl->async->args;
  3417. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  3418. if (ret != WC_NOT_PENDING_E) {
  3419. /* Check for error */
  3420. if (ret < 0) {
  3421. if (ret == WC_PENDING_E) {
  3422. /* Mark message as not received so it can process again */
  3423. ssl->msgsReceived.got_server_hello = 0;
  3424. }
  3425. return ret;
  3426. }
  3427. }
  3428. else
  3429. #endif
  3430. {
  3431. /* Reset state */
  3432. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  3433. XMEMSET(args, 0, sizeof(Dsh13Args));
  3434. }
  3435. switch (ssl->options.asyncState) {
  3436. case TLS_ASYNC_BEGIN:
  3437. {
  3438. byte b;
  3439. #ifdef WOLFSSL_CALLBACKS
  3440. if (ssl->hsInfoOn) AddPacketName(ssl, "ServerHello");
  3441. if (ssl->toInfoOn) AddLateName("ServerHello", &ssl->timeoutInfo);
  3442. #endif
  3443. /* Protocol version length check. */
  3444. if (helloSz < OPAQUE16_LEN)
  3445. return BUFFER_ERROR;
  3446. args->idx = *inOutIdx;
  3447. args->begin = args->idx;
  3448. /* Protocol version */
  3449. XMEMCPY(&args->pv, input + args->idx, OPAQUE16_LEN);
  3450. args->idx += OPAQUE16_LEN;
  3451. #ifdef WOLFSSL_DTLS
  3452. if (ssl->options.dtls &&
  3453. (args->pv.major != DTLS_MAJOR || args->pv.minor == DTLS_BOGUS_MINOR))
  3454. return VERSION_ERROR;
  3455. #endif /* WOLFSSL_DTLS */
  3456. #ifndef WOLFSSL_NO_TLS12
  3457. {
  3458. byte wantDowngrade;
  3459. wantDowngrade = args->pv.major == ssl->version.major &&
  3460. args->pv.minor < TLSv1_2_MINOR;
  3461. #ifdef WOLFSSL_DTLS13
  3462. if (ssl->options.dtls)
  3463. wantDowngrade = args->pv.major == ssl->version.major &&
  3464. args->pv.minor > DTLSv1_2_MINOR;
  3465. #endif /* WOLFSSL_DTLS13 */
  3466. if (wantDowngrade && ssl->options.downgrade) {
  3467. /* Force client hello version 1.2 to work for static RSA. */
  3468. ssl->chVersion.minor = TLSv1_2_MINOR;
  3469. ssl->version.minor = TLSv1_2_MINOR;
  3470. #ifdef WOLFSSL_DTLS13
  3471. if (ssl->options.dtls) {
  3472. ssl->chVersion.minor = DTLSv1_2_MINOR;
  3473. ssl->version.minor = DTLSv1_2_MINOR;
  3474. ret = Dtls13DoDowngrade(ssl);
  3475. if (ret != 0)
  3476. return ret;
  3477. }
  3478. #endif /* WOLFSSL_DTLS13 */
  3479. return DoServerHello(ssl, input, inOutIdx, helloSz);
  3480. }
  3481. }
  3482. #endif
  3483. if (args->pv.major != ssl->version.major ||
  3484. args->pv.minor != tls12minor) {
  3485. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3486. return VERSION_ERROR;
  3487. }
  3488. /* Random and session id length check */
  3489. if ((args->idx - args->begin) + RAN_LEN + ENUM_LEN > helloSz)
  3490. return BUFFER_ERROR;
  3491. /* Check if hello retry request */
  3492. if (XMEMCMP(input + args->idx, helloRetryRequestRandom, RAN_LEN) == 0) {
  3493. WOLFSSL_MSG("HelloRetryRequest format");
  3494. *extMsgType = hello_retry_request;
  3495. /* A HelloRetryRequest comes in as an ServerHello for MiddleBox compat.
  3496. * Found message to be a HelloRetryRequest.
  3497. * Don't allow more than one HelloRetryRequest or ServerHello.
  3498. */
  3499. if (ssl->msgsReceived.got_hello_retry_request) {
  3500. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  3501. return DUPLICATE_MSG_E;
  3502. }
  3503. }
  3504. args->extMsgType = *extMsgType;
  3505. /* Server random - keep for debugging. */
  3506. XMEMCPY(ssl->arrays->serverRandom, input + args->idx, RAN_LEN);
  3507. args->idx += RAN_LEN;
  3508. /* Session id */
  3509. args->sessIdSz = input[args->idx++];
  3510. if ((args->idx - args->begin) + args->sessIdSz > helloSz)
  3511. return BUFFER_ERROR;
  3512. args->sessId = input + args->idx;
  3513. args->idx += args->sessIdSz;
  3514. ssl->options.haveSessionId = 1;
  3515. /* Ciphersuite and compression check */
  3516. if ((args->idx - args->begin) + OPAQUE16_LEN + OPAQUE8_LEN > helloSz)
  3517. return BUFFER_ERROR;
  3518. /* Set the cipher suite from the message. */
  3519. ssl->options.cipherSuite0 = input[args->idx++];
  3520. ssl->options.cipherSuite = input[args->idx++];
  3521. #ifdef WOLFSSL_DEBUG_TLS
  3522. WOLFSSL_MSG("Chosen cipher suite:");
  3523. WOLFSSL_MSG(GetCipherNameInternal(ssl->options.cipherSuite0,
  3524. ssl->options.cipherSuite));
  3525. #endif
  3526. /* Compression */
  3527. b = input[args->idx++];
  3528. if (b != 0) {
  3529. WOLFSSL_MSG("Must be no compression types in list");
  3530. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  3531. return INVALID_PARAMETER;
  3532. }
  3533. if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz) {
  3534. if (!ssl->options.downgrade)
  3535. return BUFFER_ERROR;
  3536. #ifndef WOLFSSL_NO_TLS12
  3537. /* Force client hello version 1.2 to work for static RSA. */
  3538. ssl->chVersion.minor = TLSv1_2_MINOR;
  3539. ssl->version.minor = TLSv1_2_MINOR;
  3540. #ifdef WOLFSSL_DTLS13
  3541. if (ssl->options.dtls) {
  3542. ssl->chVersion.minor = DTLSv1_2_MINOR;
  3543. ssl->version.minor = DTLSv1_2_MINOR;
  3544. ret = Dtls13DoDowngrade(ssl);
  3545. if (ret != 0)
  3546. return ret;
  3547. }
  3548. #endif /* WOLFSSL_DTLS13 */
  3549. #endif
  3550. ssl->options.haveEMS = 0;
  3551. if (args->pv.minor < ssl->options.minDowngrade)
  3552. return VERSION_ERROR;
  3553. #ifndef WOLFSSL_NO_TLS12
  3554. return DoServerHello(ssl, input, inOutIdx, helloSz);
  3555. #else
  3556. return VERSION_ERROR;
  3557. #endif
  3558. }
  3559. if ((args->idx - args->begin) < helloSz) {
  3560. int foundVersion;
  3561. /* Get extension length and length check. */
  3562. if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
  3563. return BUFFER_ERROR;
  3564. ato16(&input[args->idx], &args->totalExtSz);
  3565. args->idx += OPAQUE16_LEN;
  3566. if ((args->idx - args->begin) + args->totalExtSz > helloSz)
  3567. return BUFFER_ERROR;
  3568. /* Need to negotiate version first. */
  3569. if ((ret = TLSX_ParseVersion(ssl, input + args->idx,
  3570. args->totalExtSz, *extMsgType, &foundVersion))) {
  3571. return ret;
  3572. }
  3573. if (!foundVersion) {
  3574. if (!ssl->options.downgrade) {
  3575. WOLFSSL_MSG("Server trying to downgrade to version less than "
  3576. "TLS v1.3");
  3577. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3578. return VERSION_ERROR;
  3579. }
  3580. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  3581. defined(WOLFSSL_WPAS_SMALL)
  3582. /* Check if client has disabled TLS 1.2 */
  3583. if (args->pv.minor == TLSv1_2_MINOR &&
  3584. (ssl->options.mask & SSL_OP_NO_TLSv1_2) == SSL_OP_NO_TLSv1_2) {
  3585. WOLFSSL_MSG("\tOption set to not allow TLSv1.2");
  3586. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3587. return VERSION_ERROR;
  3588. }
  3589. #endif
  3590. if (!ssl->options.dtls &&
  3591. args->pv.minor < ssl->options.minDowngrade) {
  3592. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3593. return VERSION_ERROR;
  3594. }
  3595. if (ssl->options.dtls &&
  3596. args->pv.minor > ssl->options.minDowngrade) {
  3597. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3598. return VERSION_ERROR;
  3599. }
  3600. ssl->version.minor = args->pv.minor;
  3601. #ifdef WOLFSSL_DTLS13
  3602. if (ssl->options.dtls) {
  3603. ret = Dtls13DoDowngrade(ssl);
  3604. if (ret != 0)
  3605. return ret;
  3606. }
  3607. #endif /* WOLFSSL_DTLS13 */
  3608. }
  3609. }
  3610. #ifdef WOLFSSL_DTLS13
  3611. /* we are sure that version is >= v1.3 now, we can get rid of buffered
  3612. * ClientHello that was buffered to re-compute the hash in case of
  3613. * downgrade */
  3614. if (ssl->options.dtls && ssl->dtls13ClientHello != NULL) {
  3615. XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  3616. ssl->dtls13ClientHello = NULL;
  3617. ssl->dtls13ClientHelloSz = 0;
  3618. }
  3619. #endif /* WOLFSSL_DTLS13 */
  3620. /* Advance state and proceed */
  3621. ssl->options.asyncState = TLS_ASYNC_BUILD;
  3622. } /* case TLS_ASYNC_BEGIN */
  3623. FALL_THROUGH;
  3624. case TLS_ASYNC_BUILD:
  3625. case TLS_ASYNC_DO:
  3626. {
  3627. /* restore message type */
  3628. *extMsgType = args->extMsgType;
  3629. if (args->totalExtSz > 0) {
  3630. /* Parse and handle extensions. */
  3631. ret = TLSX_Parse(ssl, input + args->idx, args->totalExtSz,
  3632. *extMsgType, NULL);
  3633. if (ret != 0) {
  3634. #ifdef WOLFSSL_ASYNC_CRYPT
  3635. /* Handle async operation */
  3636. if (ret == WC_PENDING_E) {
  3637. /* Mark message as not received so it can process again */
  3638. ssl->msgsReceived.got_server_hello = 0;
  3639. }
  3640. #endif
  3641. return ret;
  3642. }
  3643. if (*extMsgType == hello_retry_request) {
  3644. /* Update counts to reflect change of message type. */
  3645. ssl->msgsReceived.got_hello_retry_request = 1;
  3646. ssl->msgsReceived.got_server_hello = 0;
  3647. }
  3648. args->idx += args->totalExtSz;
  3649. }
  3650. *inOutIdx = args->idx;
  3651. ssl->options.serverState = SERVER_HELLO_COMPLETE;
  3652. #ifdef HAVE_SECRET_CALLBACK
  3653. if (ssl->sessionSecretCb != NULL
  3654. #ifdef HAVE_SESSION_TICKET
  3655. && ssl->session->ticketLen > 0
  3656. #endif
  3657. ) {
  3658. int secretSz = SECRET_LEN;
  3659. ret = ssl->sessionSecretCb(ssl, ssl->session->masterSecret,
  3660. &secretSz, ssl->sessionSecretCtx);
  3661. if (ret != 0 || secretSz != SECRET_LEN) {
  3662. WOLFSSL_ERROR_VERBOSE(SESSION_SECRET_CB_E);
  3663. return SESSION_SECRET_CB_E;
  3664. }
  3665. }
  3666. #endif /* HAVE_SECRET_CALLBACK */
  3667. /* Version only negotiated in extensions for TLS v1.3.
  3668. * Only now do we know how to deal with session id.
  3669. */
  3670. if (!IsAtLeastTLSv1_3(ssl->version)) {
  3671. #ifndef WOLFSSL_NO_TLS12
  3672. ssl->arrays->sessionIDSz = args->sessIdSz;
  3673. if (ssl->arrays->sessionIDSz > ID_LEN) {
  3674. WOLFSSL_MSG("Invalid session ID size");
  3675. ssl->arrays->sessionIDSz = 0;
  3676. return BUFFER_ERROR;
  3677. }
  3678. else if (ssl->arrays->sessionIDSz) {
  3679. XMEMCPY(ssl->arrays->sessionID, args->sessId,
  3680. ssl->arrays->sessionIDSz);
  3681. ssl->options.haveSessionId = 1;
  3682. }
  3683. /* Force client hello version 1.2 to work for static RSA. */
  3684. ssl->chVersion.minor = TLSv1_2_MINOR;
  3685. /* Complete TLS v1.2 processing of ServerHello. */
  3686. ret = CompleteServerHello(ssl);
  3687. #else
  3688. WOLFSSL_MSG("Client using higher version, fatal error");
  3689. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  3690. ret = VERSION_ERROR;
  3691. #endif
  3692. WOLFSSL_LEAVE("DoTls13ServerHello", ret);
  3693. return ret;
  3694. }
  3695. /* Advance state and proceed */
  3696. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  3697. } /* case TLS_ASYNC_BUILD || TLS_ASYNC_DO */
  3698. FALL_THROUGH;
  3699. case TLS_ASYNC_FINALIZE:
  3700. {
  3701. #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
  3702. if (ssl->options.tls13MiddleBoxCompat) {
  3703. if (args->sessIdSz == 0) {
  3704. WOLFSSL_MSG("args->sessIdSz == 0");
  3705. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  3706. return INVALID_PARAMETER;
  3707. }
  3708. if (ssl->session->sessionIDSz != 0) {
  3709. if (ssl->session->sessionIDSz != args->sessIdSz ||
  3710. XMEMCMP(ssl->session->sessionID, args->sessId,
  3711. args->sessIdSz) != 0) {
  3712. WOLFSSL_MSG("session id doesn't match");
  3713. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  3714. return INVALID_PARAMETER;
  3715. }
  3716. }
  3717. else if (XMEMCMP(ssl->arrays->clientRandom, args->sessId,
  3718. args->sessIdSz) != 0) {
  3719. WOLFSSL_MSG("session id doesn't match client random");
  3720. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  3721. return INVALID_PARAMETER;
  3722. }
  3723. else
  3724. #endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
  3725. #ifdef WOLFSSL_QUIC
  3726. if (WOLFSSL_IS_QUIC(ssl)) {
  3727. if (args->sessIdSz != 0) {
  3728. WOLFSSL_MSG("args->sessIdSz != 0");
  3729. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  3730. return INVALID_PARAMETER;
  3731. }
  3732. }
  3733. else
  3734. #endif /* WOLFSSL_QUIC */
  3735. if (args->sessIdSz != ssl->session->sessionIDSz || (args->sessIdSz > 0 &&
  3736. XMEMCMP(ssl->session->sessionID, args->sessId, args->sessIdSz) != 0))
  3737. {
  3738. WOLFSSL_MSG("Server sent different session id");
  3739. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  3740. return INVALID_PARAMETER;
  3741. }
  3742. ret = SetCipherSpecs(ssl);
  3743. if (ret != 0)
  3744. return ret;
  3745. #ifdef HAVE_NULL_CIPHER
  3746. if (ssl->options.cipherSuite0 == ECC_BYTE &&
  3747. (ssl->options.cipherSuite == TLS_SHA256_SHA256 ||
  3748. ssl->options.cipherSuite == TLS_SHA384_SHA384)) {
  3749. ;
  3750. }
  3751. else
  3752. #endif
  3753. /* Check that the negotiated ciphersuite matches protocol version. */
  3754. if (ssl->options.cipherSuite0 != TLS13_BYTE) {
  3755. WOLFSSL_MSG("Server sent non-TLS13 cipher suite in TLS 1.3 packet");
  3756. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  3757. return INVALID_PARAMETER;
  3758. }
  3759. suite[0] = ssl->options.cipherSuite0;
  3760. suite[1] = ssl->options.cipherSuite;
  3761. if (!FindSuiteSSL(ssl, suite)) {
  3762. WOLFSSL_MSG("Cipher suite not supported on client");
  3763. WOLFSSL_ERROR_VERBOSE(MATCH_SUITE_ERROR);
  3764. return MATCH_SUITE_ERROR;
  3765. }
  3766. if (*extMsgType == server_hello) {
  3767. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  3768. PreSharedKey* psk = NULL;
  3769. TLSX* ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  3770. if (ext != NULL)
  3771. psk = (PreSharedKey*)ext->data;
  3772. while (psk != NULL && !psk->chosen)
  3773. psk = psk->next;
  3774. if (psk == NULL) {
  3775. ssl->options.resuming = 0;
  3776. ssl->arrays->psk_keySz = 0;
  3777. XMEMSET(ssl->arrays->psk_key, 0, MAX_PSK_KEY_LEN);
  3778. }
  3779. else {
  3780. if ((ret = SetupPskKey(ssl, psk, 0)) != 0)
  3781. return ret;
  3782. ssl->options.pskNegotiated = 1;
  3783. }
  3784. #endif
  3785. ssl->keys.encryptionOn = 1;
  3786. ssl->options.serverState = SERVER_HELLO_COMPLETE;
  3787. }
  3788. else {
  3789. ssl->options.tls1_3 = 1;
  3790. ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
  3791. ret = RestartHandshakeHash(ssl);
  3792. }
  3793. break;
  3794. } /* case TLS_ASYNC_FINALIZE */
  3795. default:
  3796. ret = INPUT_CASE_ERROR;
  3797. } /* switch (ssl->options.asyncState) */
  3798. #ifdef WOLFSSL_ASYNC_CRYPT
  3799. if (ret == 0)
  3800. FreeAsyncCtx(ssl, 0);
  3801. #endif
  3802. WOLFSSL_LEAVE("DoTls13ServerHello", ret);
  3803. WOLFSSL_END(WC_FUNC_SERVER_HELLO_DO);
  3804. return ret;
  3805. }
  3806. /* handle processing TLS 1.3 encrypted_extensions (8) */
  3807. /* Parse and handle an EncryptedExtensions message.
  3808. * Only a client will receive this message.
  3809. *
  3810. * ssl The SSL/TLS object.
  3811. * input The message buffer.
  3812. * inOutIdx On entry, the index into the message buffer of
  3813. * EncryptedExtensions.
  3814. * On exit, the index of byte after the EncryptedExtensions
  3815. * message.
  3816. * totalSz The length of the current handshake message.
  3817. * returns 0 on success and otherwise failure.
  3818. */
  3819. static int DoTls13EncryptedExtensions(WOLFSSL* ssl, const byte* input,
  3820. word32* inOutIdx, word32 totalSz)
  3821. {
  3822. int ret;
  3823. word32 begin = *inOutIdx;
  3824. word32 i = begin;
  3825. word16 totalExtSz;
  3826. WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
  3827. WOLFSSL_ENTER("DoTls13EncryptedExtensions");
  3828. #ifdef WOLFSSL_CALLBACKS
  3829. if (ssl->hsInfoOn) AddPacketName(ssl, "EncryptedExtensions");
  3830. if (ssl->toInfoOn) AddLateName("EncryptedExtensions", &ssl->timeoutInfo);
  3831. #endif
  3832. /* Length field of extension data. */
  3833. if (totalSz < OPAQUE16_LEN)
  3834. return BUFFER_ERROR;
  3835. ato16(&input[i], &totalExtSz);
  3836. i += OPAQUE16_LEN;
  3837. /* Extension data. */
  3838. if (i - begin + totalExtSz > totalSz)
  3839. return BUFFER_ERROR;
  3840. if ((ret = TLSX_Parse(ssl, input + i, totalExtSz, encrypted_extensions,
  3841. NULL))) {
  3842. return ret;
  3843. }
  3844. /* Move index to byte after message. */
  3845. *inOutIdx = i + totalExtSz;
  3846. /* Always encrypted. */
  3847. *inOutIdx += ssl->keys.padSz;
  3848. #ifdef WOLFSSL_EARLY_DATA
  3849. if (ssl->earlyData != no_early_data) {
  3850. TLSX* ext = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  3851. if (ext == NULL || !ext->val)
  3852. ssl->earlyData = no_early_data;
  3853. }
  3854. #endif
  3855. #ifdef WOLFSSL_EARLY_DATA
  3856. if (ssl->earlyData == no_early_data) {
  3857. ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
  3858. if (ret != 0)
  3859. return ret;
  3860. }
  3861. #endif
  3862. ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
  3863. WOLFSSL_LEAVE("DoTls13EncryptedExtensions", ret);
  3864. WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
  3865. return ret;
  3866. }
  3867. #ifndef NO_CERTS
  3868. /* handle processing TLS v1.3 certificate_request (13) */
  3869. /* Handle a TLS v1.3 CertificateRequest message.
  3870. * This message is always encrypted.
  3871. * Only a client will receive this message.
  3872. *
  3873. * ssl The SSL/TLS object.
  3874. * input The message buffer.
  3875. * inOutIdx On entry, the index into the message buffer of CertificateRequest.
  3876. * On exit, the index of byte after the CertificateRequest message.
  3877. * size The length of the current handshake message.
  3878. * returns 0 on success and otherwise failure.
  3879. */
  3880. static int DoTls13CertificateRequest(WOLFSSL* ssl, const byte* input,
  3881. word32* inOutIdx, word32 size)
  3882. {
  3883. word16 len;
  3884. word32 begin = *inOutIdx;
  3885. int ret = 0;
  3886. Suites peerSuites;
  3887. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  3888. CertReqCtx* certReqCtx;
  3889. #endif
  3890. WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_DO);
  3891. WOLFSSL_ENTER("DoTls13CertificateRequest");
  3892. XMEMSET(&peerSuites, 0, sizeof(Suites));
  3893. #ifdef WOLFSSL_CALLBACKS
  3894. if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateRequest");
  3895. if (ssl->toInfoOn) AddLateName("CertificateRequest", &ssl->timeoutInfo);
  3896. #endif
  3897. if (OPAQUE8_LEN > size)
  3898. return BUFFER_ERROR;
  3899. /* Length of the request context. */
  3900. len = input[(*inOutIdx)++];
  3901. if ((*inOutIdx - begin) + len > size)
  3902. return BUFFER_ERROR;
  3903. if (ssl->options.connectState < FINISHED_DONE && len > 0)
  3904. return BUFFER_ERROR;
  3905. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  3906. /* CertReqCtx has one byte at end for context value.
  3907. * Increase size to handle other implementations sending more than one byte.
  3908. * That is, allocate extra space, over one byte, to hold the context value.
  3909. */
  3910. certReqCtx = (CertReqCtx*)XMALLOC(sizeof(CertReqCtx) + len - 1, ssl->heap,
  3911. DYNAMIC_TYPE_TMP_BUFFER);
  3912. if (certReqCtx == NULL)
  3913. return MEMORY_E;
  3914. certReqCtx->next = ssl->certReqCtx;
  3915. certReqCtx->len = len;
  3916. XMEMCPY(&certReqCtx->ctx, input + *inOutIdx, len);
  3917. ssl->certReqCtx = certReqCtx;
  3918. #endif
  3919. *inOutIdx += len;
  3920. /* TODO: Add support for more extensions:
  3921. * signed_certificate_timestamp, certificate_authorities, oid_filters.
  3922. */
  3923. /* Certificate extensions */
  3924. if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
  3925. return BUFFER_ERROR;
  3926. ato16(input + *inOutIdx, &len);
  3927. *inOutIdx += OPAQUE16_LEN;
  3928. if ((*inOutIdx - begin) + len > size)
  3929. return BUFFER_ERROR;
  3930. if (len == 0)
  3931. return INVALID_PARAMETER;
  3932. if ((ret = TLSX_Parse(ssl, input + *inOutIdx, len, certificate_request,
  3933. &peerSuites))) {
  3934. return ret;
  3935. }
  3936. *inOutIdx += len;
  3937. if ((ssl->buffers.certificate && ssl->buffers.certificate->buffer &&
  3938. ((ssl->buffers.key && ssl->buffers.key->buffer)
  3939. #ifdef HAVE_PK_CALLBACKS
  3940. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  3941. #endif
  3942. ))
  3943. #ifdef OPENSSL_EXTRA
  3944. || ssl->ctx->certSetupCb != NULL
  3945. #endif
  3946. ) {
  3947. if (PickHashSigAlgo(ssl, peerSuites.hashSigAlgo,
  3948. peerSuites.hashSigAlgoSz) != 0) {
  3949. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  3950. return INVALID_PARAMETER;
  3951. }
  3952. ssl->options.sendVerify = SEND_CERT;
  3953. }
  3954. else {
  3955. #ifndef WOLFSSL_NO_CLIENT_CERT_ERROR
  3956. ssl->options.sendVerify = SEND_BLANK_CERT;
  3957. #else
  3958. WOLFSSL_MSG("Certificate required but none set on client");
  3959. SendAlert(ssl, alert_fatal, illegal_parameter);
  3960. WOLFSSL_ERROR_VERBOSE(NO_CERT_ERROR);
  3961. return NO_CERT_ERROR;
  3962. #endif
  3963. }
  3964. /* This message is always encrypted so add encryption padding. */
  3965. *inOutIdx += ssl->keys.padSz;
  3966. WOLFSSL_LEAVE("DoTls13CertificateRequest", ret);
  3967. WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_DO);
  3968. return ret;
  3969. }
  3970. #endif /* !NO_CERTS */
  3971. #endif /* !NO_WOLFSSL_CLIENT */
  3972. #ifndef NO_WOLFSSL_SERVER
  3973. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  3974. /* Refine list of supported cipher suites to those common to server and client.
  3975. *
  3976. * ssl SSL/TLS object.
  3977. * peerSuites The peer's advertised list of supported cipher suites.
  3978. */
  3979. static void RefineSuites(WOLFSSL* ssl, Suites* peerSuites)
  3980. {
  3981. byte suites[WOLFSSL_MAX_SUITE_SZ];
  3982. word16 suiteSz = 0;
  3983. word16 i, j;
  3984. XMEMSET(suites, 0, WOLFSSL_MAX_SUITE_SZ);
  3985. for (i = 0; i < ssl->suites->suiteSz; i += 2) {
  3986. for (j = 0; j < peerSuites->suiteSz; j += 2) {
  3987. if (ssl->suites->suites[i+0] == peerSuites->suites[j+0] &&
  3988. ssl->suites->suites[i+1] == peerSuites->suites[j+1]) {
  3989. suites[suiteSz++] = peerSuites->suites[j+0];
  3990. suites[suiteSz++] = peerSuites->suites[j+1];
  3991. }
  3992. }
  3993. }
  3994. ssl->suites->suiteSz = suiteSz;
  3995. XMEMCPY(ssl->suites->suites, &suites, sizeof(suites));
  3996. #ifdef WOLFSSL_DEBUG_TLS
  3997. {
  3998. int ii;
  3999. WOLFSSL_MSG("Refined Ciphers:");
  4000. for (ii = 0 ; ii < ssl->suites->suiteSz; ii += 2) {
  4001. WOLFSSL_MSG(GetCipherNameInternal(ssl->suites->suites[ii+0],
  4002. ssl->suites->suites[ii+1]));
  4003. }
  4004. }
  4005. #endif
  4006. }
  4007. #ifndef NO_PSK
  4008. /* Attempt to find the PSK (not session ticket) that matches.
  4009. *
  4010. * @param [in, out] ssl The SSL/TLS object.
  4011. * @param [in] psk A pre-shared key from the extension.
  4012. * @param [out] suite Cipher suite to use with PSK.
  4013. * @param [out] err Error code.
  4014. * PSK_KEY_ERROR when key is too big or ticket age is
  4015. * invalid,
  4016. * UNSUPPORTED_SUITE on invalid suite.
  4017. * Other error when attempting to derive early secret.
  4018. * @return 1 when a match found - but check error code.
  4019. * @return 0 when no match found.
  4020. */
  4021. static int FindPsk(WOLFSSL* ssl, PreSharedKey* psk, byte* suite, int* err)
  4022. {
  4023. int ret = 0;
  4024. int found = 0;
  4025. const char* cipherName = NULL;
  4026. byte cipherSuite0 = TLS13_BYTE;
  4027. byte cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
  4028. Arrays* sa = ssl->arrays;
  4029. if (ssl->options.server_psk_tls13_cb != NULL) {
  4030. sa->psk_keySz = ssl->options.server_psk_tls13_cb(ssl,
  4031. sa->client_identity, sa->psk_key, MAX_PSK_KEY_LEN, &cipherName);
  4032. if (sa->psk_keySz != 0) {
  4033. int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
  4034. found = (GetCipherSuiteFromName(cipherName, &cipherSuite0,
  4035. &cipherSuite, &cipherSuiteFlags) == 0);
  4036. (void)cipherSuiteFlags;
  4037. }
  4038. }
  4039. if (!found && (ssl->options.server_psk_cb != NULL)) {
  4040. sa->psk_keySz = ssl->options.server_psk_cb(ssl,
  4041. sa->client_identity, sa->psk_key,
  4042. MAX_PSK_KEY_LEN);
  4043. found = (sa->psk_keySz != 0);
  4044. }
  4045. if (found) {
  4046. if (sa->psk_keySz > MAX_PSK_KEY_LEN) {
  4047. ret = PSK_KEY_ERROR;
  4048. WOLFSSL_ERROR_VERBOSE(ret);
  4049. }
  4050. if (ret == 0) {
  4051. #ifndef WOLFSSL_PSK_ONE_ID
  4052. /* Check whether PSK ciphersuite is in SSL. */
  4053. found = (suite[0] == cipherSuite0) && (suite[1] == cipherSuite);
  4054. #else
  4055. /* Check whether PSK ciphersuite is in SSL. */
  4056. suite[0] = cipherSuite0;
  4057. suite[1] = cipherSuite;
  4058. found = FindSuiteSSL(ssl, suite);
  4059. #endif
  4060. }
  4061. if ((ret == 0) && found) {
  4062. /* Default to ciphersuite if cb doesn't specify. */
  4063. ssl->options.resuming = 0;
  4064. /* Don't send certificate request when using PSK. */
  4065. ssl->options.verifyPeer = 0;
  4066. /* PSK age is always zero. */
  4067. if (psk->ticketAge != ssl->session->ticketAdd) {
  4068. ret = PSK_KEY_ERROR;
  4069. WOLFSSL_ERROR_VERBOSE(ret);
  4070. }
  4071. }
  4072. if ((ret == 0) && found) {
  4073. /* Set PSK ciphersuite into SSL. */
  4074. ssl->options.cipherSuite0 = suite[0];
  4075. ssl->options.cipherSuite = suite[1];
  4076. ret = SetCipherSpecs(ssl);
  4077. }
  4078. if ((ret == 0) && found) {
  4079. /* Derive the early secret using the PSK. */
  4080. ret = DeriveEarlySecret(ssl);
  4081. }
  4082. if ((ret == 0) && found) {
  4083. /* PSK negotiation has succeeded */
  4084. ssl->options.isPSK = 1;
  4085. /* SERVER: using PSK for peer authentication. */
  4086. ssl->options.peerAuthGood = 1;
  4087. }
  4088. }
  4089. *err = ret;
  4090. return found;
  4091. }
  4092. #endif
  4093. /* Handle any Pre-Shared Key (PSK) extension.
  4094. * Find a PSK that supports the cipher suite passed in.
  4095. *
  4096. * ssl SSL/TLS object.
  4097. * suite Cipher suite to find PSK for.
  4098. * usingPSK 1=Indicates handshake is using Pre-Shared Keys (2=Ephemeral)
  4099. * first Set to 1 if first in extension
  4100. * returns 0 on success and otherwise failure.
  4101. */
  4102. static int DoPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 inputSz,
  4103. byte* suite, int* usingPSK, int* first)
  4104. {
  4105. int ret = 0;
  4106. TLSX* ext;
  4107. PreSharedKey* current;
  4108. byte binderKey[WC_MAX_DIGEST_SIZE];
  4109. byte binder[WC_MAX_DIGEST_SIZE];
  4110. word32 binderLen;
  4111. WOLFSSL_ENTER("DoPreSharedKeys");
  4112. ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  4113. if (ext == NULL) {
  4114. WOLFSSL_MSG("No pre shared extension keys found");
  4115. return BAD_FUNC_ARG;
  4116. }
  4117. /* Look through all client's pre-shared keys for a match. */
  4118. current = (PreSharedKey*)ext->data;
  4119. while (current != NULL) {
  4120. #ifndef NO_PSK
  4121. if (current->identityLen > MAX_PSK_ID_LEN) {
  4122. return BUFFER_ERROR;
  4123. }
  4124. XMEMCPY(ssl->arrays->client_identity, current->identity,
  4125. current->identityLen);
  4126. ssl->arrays->client_identity[current->identityLen] = '\0';
  4127. #endif
  4128. #ifdef HAVE_SESSION_TICKET
  4129. /* Decode the identity. */
  4130. ret = DoClientTicket(ssl, current->identity, current->identityLen);
  4131. #ifdef WOLFSSL_ASYNC_CRYPT
  4132. if (ret == WC_PENDING_E)
  4133. return ret;
  4134. #endif
  4135. if (ret == WOLFSSL_TICKET_RET_OK) {
  4136. word32 now;
  4137. sword64 diff;
  4138. now = TimeNowInMilliseconds();
  4139. if (now == (word32)GETTIME_ERROR)
  4140. return now;
  4141. /* Difference between now and time ticket constructed
  4142. * (from decrypted ticket). */
  4143. diff = now;
  4144. diff -= ssl->session->ticketSeen;
  4145. if (diff > (sword64)ssl->timeout * 1000 ||
  4146. diff > (sword64)TLS13_MAX_TICKET_AGE * 1000) {
  4147. current = current->next;
  4148. continue;
  4149. }
  4150. /* Subtract client's ticket age and unobfuscate. */
  4151. diff -= current->ticketAge;
  4152. diff += ssl->session->ticketAdd;
  4153. /* Check session and ticket age timeout.
  4154. * Allow +/- 1000 milliseconds on ticket age.
  4155. */
  4156. if (diff < -1000 || diff - MAX_TICKET_AGE_DIFF * 1000 > 1000) {
  4157. current = current->next;
  4158. continue;
  4159. }
  4160. #ifndef WOLFSSL_PSK_ONE_ID
  4161. /* Check whether resumption is possible based on suites in SSL and
  4162. * ciphersuite in ticket.
  4163. */
  4164. if ((suite[0] != ssl->session->cipherSuite0) ||
  4165. (suite[1] != ssl->session->cipherSuite)) {
  4166. current = current->next;
  4167. continue;
  4168. }
  4169. #else
  4170. suite[0] = ssl->session->cipherSuite0;
  4171. suite[1] = ssl->session->cipherSuite;
  4172. if (!FindSuiteSSL(ssl, suite)) {
  4173. current = current->next;
  4174. continue;
  4175. }
  4176. #endif
  4177. /* SERVER: using secret in session ticket for peer auth. */
  4178. ssl->options.peerAuthGood = 1;
  4179. #ifdef WOLFSSL_EARLY_DATA
  4180. ssl->options.maxEarlyDataSz = ssl->session->maxEarlyDataSz;
  4181. #endif
  4182. /* Use the same cipher suite as before and set up for use. */
  4183. ssl->options.cipherSuite0 = ssl->session->cipherSuite0;
  4184. ssl->options.cipherSuite = ssl->session->cipherSuite;
  4185. ret = SetCipherSpecs(ssl);
  4186. if (ret != 0)
  4187. return ret;
  4188. /* Resumption PSK is resumption master secret. */
  4189. ssl->arrays->psk_keySz = ssl->specs.hash_size;
  4190. if ((ret = DeriveResumptionPSK(ssl, ssl->session->ticketNonce.data,
  4191. ssl->session->ticketNonce.len, ssl->arrays->psk_key)) != 0) {
  4192. return ret;
  4193. }
  4194. /* Derive the early secret using the PSK. */
  4195. ret = DeriveEarlySecret(ssl);
  4196. if (ret != 0)
  4197. return ret;
  4198. /* Hash data up to binders for deriving binders in PSK extension. */
  4199. ret = HashInput(ssl, input, inputSz);
  4200. if (ret < 0)
  4201. return ret;
  4202. /* Derive the binder key to use with HMAC. */
  4203. ret = DeriveBinderKeyResume(ssl, binderKey);
  4204. if (ret != 0)
  4205. return ret;
  4206. }
  4207. else
  4208. #endif
  4209. #ifndef NO_PSK
  4210. if (FindPsk(ssl, current, suite, &ret)) {
  4211. if (ret != 0)
  4212. return ret;
  4213. ret = HashInput(ssl, input, inputSz);
  4214. if (ret < 0)
  4215. return ret;
  4216. /* Derive the binder key to use with HMAC. */
  4217. ret = DeriveBinderKey(ssl, binderKey);
  4218. if (ret != 0)
  4219. return ret;
  4220. }
  4221. else
  4222. #endif
  4223. {
  4224. current = current->next;
  4225. continue;
  4226. }
  4227. ssl->options.sendVerify = 0;
  4228. /* Derive the Finished message secret. */
  4229. ret = DeriveFinishedSecret(ssl, binderKey,
  4230. ssl->keys.client_write_MAC_secret);
  4231. if (ret != 0)
  4232. return ret;
  4233. /* Derive the binder and compare with the one in the extension. */
  4234. ret = BuildTls13HandshakeHmac(ssl,
  4235. ssl->keys.client_write_MAC_secret, binder, &binderLen);
  4236. if (ret != 0)
  4237. return ret;
  4238. if (binderLen != current->binderLen ||
  4239. XMEMCMP(binder, current->binder, binderLen) != 0) {
  4240. WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
  4241. return BAD_BINDER;
  4242. }
  4243. /* This PSK works, no need to try any more. */
  4244. current->chosen = 1;
  4245. ext->resp = 1;
  4246. break;
  4247. }
  4248. if (current == NULL) {
  4249. #ifdef WOLFSSL_PSK_ID_PROTECTION
  4250. #ifndef NO_CERTS
  4251. if (ssl->buffers.certChainCnt != 0)
  4252. return 0;
  4253. #endif
  4254. WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
  4255. return BAD_BINDER;
  4256. #else
  4257. return 0;
  4258. #endif
  4259. }
  4260. *first = (current == ext->data);
  4261. *usingPSK = 1;
  4262. WOLFSSL_LEAVE("DoPreSharedKeys", ret);
  4263. return ret;
  4264. }
  4265. /* Handle any Pre-Shared Key (PSK) extension.
  4266. * Must do this in ClientHello as it requires a hash of the truncated message.
  4267. * Don't know size of binders until Pre-Shared Key extension has been parsed.
  4268. *
  4269. * ssl SSL/TLS object.
  4270. * input ClientHello message.
  4271. * helloSz Size of the ClientHello message (including binders if present).
  4272. * clSuites Client's cipher suite list.
  4273. * usingPSK Indicates handshake is using Pre-Shared Keys.
  4274. */
  4275. static int CheckPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 helloSz,
  4276. Suites* clSuites, int* usingPSK)
  4277. {
  4278. int ret;
  4279. TLSX* ext;
  4280. word16 bindersLen;
  4281. int first = 0;
  4282. #ifndef WOLFSSL_PSK_ONE_ID
  4283. int i;
  4284. int j;
  4285. #else
  4286. byte suite[2];
  4287. #endif
  4288. WOLFSSL_ENTER("CheckPreSharedKeys");
  4289. ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  4290. if (ext == NULL) {
  4291. #ifdef WOLFSSL_EARLY_DATA
  4292. ssl->earlyData = no_early_data;
  4293. #endif
  4294. /* Hash data up to binders for deriving binders in PSK extension. */
  4295. ret = HashInput(ssl, input, helloSz);
  4296. return ret;
  4297. }
  4298. /* Extensions pushed on stack/list and PSK must be last. */
  4299. if (ssl->extensions != ext) {
  4300. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  4301. return PSK_KEY_ERROR;
  4302. }
  4303. /* Assume we are going to resume with a pre-shared key. */
  4304. ssl->options.resuming = 1;
  4305. /* Find the pre-shared key extension and calculate hash of truncated
  4306. * ClientHello for binders.
  4307. */
  4308. ret = TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
  4309. client_hello, &bindersLen);
  4310. if (ret < 0)
  4311. return ret;
  4312. /* Refine list for PSK processing. */
  4313. RefineSuites(ssl, clSuites);
  4314. #ifndef WOLFSSL_PSK_ONE_ID
  4315. if (usingPSK == NULL)
  4316. return BAD_FUNC_ARG;
  4317. if (!ssl->options.useClientOrder) {
  4318. /* Server order - server list has only common suites from refining. */
  4319. for (i = 0; !(*usingPSK) && i < ssl->suites->suiteSz; i += 2) {
  4320. ret = DoPreSharedKeys(ssl, input, helloSz - bindersLen,
  4321. ssl->suites->suites + i, usingPSK, &first);
  4322. if (ret != 0) {
  4323. return ret;
  4324. }
  4325. }
  4326. }
  4327. else {
  4328. /* Client order */
  4329. for (j = 0; !(*usingPSK) && j < clSuites->suiteSz; j += 2) {
  4330. for (i = 0; !(*usingPSK) && i < ssl->suites->suiteSz; i += 2) {
  4331. ret = DoPreSharedKeys(ssl, input, helloSz - bindersLen,
  4332. ssl->suites->suites + i, usingPSK, &first);
  4333. if (ret != 0)
  4334. return ret;
  4335. }
  4336. }
  4337. }
  4338. #else
  4339. ret = DoPreSharedKeys(ssl, input, helloSz - bindersLen, suite, usingPSK,
  4340. &first);
  4341. if (ret != 0)
  4342. return ret;
  4343. #endif
  4344. /* Hash the rest of the ClientHello. */
  4345. ret = HashRaw(ssl, input + helloSz - bindersLen, bindersLen);
  4346. if (ret != 0)
  4347. return ret;
  4348. if (*usingPSK != 0) {
  4349. word16 modes;
  4350. #ifdef WOLFSSL_EARLY_DATA
  4351. TLSX* extEarlyData;
  4352. extEarlyData = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  4353. if (extEarlyData != NULL) {
  4354. /* Check if accepting early data and first PSK. */
  4355. if (ssl->earlyData != no_early_data && first) {
  4356. extEarlyData->resp = 1;
  4357. /* Derive early data decryption key. */
  4358. ret = DeriveTls13Keys(ssl, early_data_key, DECRYPT_SIDE_ONLY,
  4359. 1);
  4360. if (ret != 0)
  4361. return ret;
  4362. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  4363. return ret;
  4364. #ifdef WOLFSSL_DTLS13
  4365. if (ssl->options.dtls) {
  4366. ret = Dtls13NewEpoch(ssl,
  4367. w64From32(0x0, DTLS13_EPOCH_EARLYDATA),
  4368. DECRYPT_SIDE_ONLY);
  4369. if (ret != 0)
  4370. return ret;
  4371. }
  4372. #endif /* WOLFSSL_DTLS13 */
  4373. ssl->earlyData = process_early_data;
  4374. }
  4375. else
  4376. extEarlyData->resp = 0;
  4377. }
  4378. #endif
  4379. /* Get the PSK key exchange modes the client wants to negotiate. */
  4380. ext = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  4381. if (ext == NULL) {
  4382. WOLFSSL_ERROR_VERBOSE(MISSING_HANDSHAKE_DATA);
  4383. return MISSING_HANDSHAKE_DATA;
  4384. }
  4385. modes = ext->val;
  4386. #ifdef HAVE_SUPPORTED_CURVES
  4387. ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  4388. /* Use (EC)DHE for forward-security if possible. */
  4389. if ((modes & (1 << PSK_DHE_KE)) != 0 && !ssl->options.noPskDheKe &&
  4390. ext != NULL) {
  4391. /* Only use named group used in last session. */
  4392. ssl->namedGroup = ssl->session->namedGroup;
  4393. *usingPSK = 2; /* generate new ephemeral key */
  4394. }
  4395. else
  4396. #endif
  4397. {
  4398. if ((modes & (1 << PSK_KE)) == 0) {
  4399. WOLFSSL_MSG("psk_ke mode does not allow key share");
  4400. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  4401. return PSK_KEY_ERROR;
  4402. }
  4403. ssl->options.noPskDheKe = 1;
  4404. ssl->arrays->preMasterSz = 0;
  4405. *usingPSK = 1;
  4406. }
  4407. }
  4408. #ifdef WOLFSSL_PSK_ID_PROTECTION
  4409. else {
  4410. #ifndef NO_CERTS
  4411. if (ssl->buffers.certChainCnt != 0)
  4412. return 0;
  4413. #endif
  4414. WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
  4415. return BAD_BINDER;
  4416. }
  4417. #endif
  4418. WOLFSSL_LEAVE("CheckPreSharedKeys", ret);
  4419. return 0;
  4420. }
  4421. #endif /* HAVE_SESSION_TICKET || !NO_PSK */
  4422. #if defined(WOLFSSL_SEND_HRR_COOKIE)
  4423. /* Check that the Cookie data's integrity.
  4424. *
  4425. * ssl SSL/TLS object.
  4426. * cookie The cookie data - hash and MAC.
  4427. * cookieSz The length of the cookie data in bytes.
  4428. * returns Length of the hash on success, otherwise failure.
  4429. */
  4430. static int CheckCookie(WOLFSSL* ssl, byte* cookie, byte cookieSz)
  4431. {
  4432. int ret;
  4433. byte mac[WC_MAX_DIGEST_SIZE] = {0};
  4434. Hmac cookieHmac;
  4435. byte cookieType = 0;
  4436. byte macSz = 0;
  4437. #if !defined(NO_SHA) && defined(NO_SHA256)
  4438. cookieType = SHA;
  4439. macSz = WC_SHA_DIGEST_SIZE;
  4440. #endif /* NO_SHA */
  4441. #ifndef NO_SHA256
  4442. cookieType = WC_SHA256;
  4443. macSz = WC_SHA256_DIGEST_SIZE;
  4444. #endif /* NO_SHA256 */
  4445. if (cookieSz < ssl->specs.hash_size + macSz)
  4446. return HRR_COOKIE_ERROR;
  4447. cookieSz -= macSz;
  4448. ret = wc_HmacInit(&cookieHmac, ssl->heap, INVALID_DEVID);
  4449. if (ret == 0) {
  4450. ret = wc_HmacSetKey(&cookieHmac, cookieType,
  4451. ssl->buffers.tls13CookieSecret.buffer,
  4452. ssl->buffers.tls13CookieSecret.length);
  4453. }
  4454. if (ret == 0)
  4455. ret = wc_HmacUpdate(&cookieHmac, cookie, cookieSz);
  4456. #ifdef WOLFSSL_DTLS13
  4457. /* Tie cookie to peer address */
  4458. if (ret == 0) {
  4459. if (ssl->options.dtls && ssl->buffers.dtlsCtx.peer.sz > 0) {
  4460. ret = wc_HmacUpdate(&cookieHmac, ssl->buffers.dtlsCtx.peer.sa,
  4461. ssl->buffers.dtlsCtx.peer.sz);
  4462. }
  4463. }
  4464. #endif
  4465. if (ret == 0)
  4466. ret = wc_HmacFinal(&cookieHmac, mac);
  4467. wc_HmacFree(&cookieHmac);
  4468. if (ret != 0)
  4469. return ret;
  4470. if (ConstantCompare(cookie + cookieSz, mac, macSz) != 0) {
  4471. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  4472. return HRR_COOKIE_ERROR;
  4473. }
  4474. return cookieSz;
  4475. }
  4476. /* Length of the KeyShare Extension */
  4477. #define HRR_KEY_SHARE_SZ (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
  4478. /* Length of the Supported Versions Extension */
  4479. #define HRR_VERSIONS_SZ (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
  4480. /* Length of the Cookie Extension excluding cookie data */
  4481. #define HRR_COOKIE_HDR_SZ (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
  4482. /* PV | Random | Session Id | CipherSuite | Compression | Ext Len */
  4483. #define HRR_BODY_SZ (VERSION_SZ + RAN_LEN + ENUM_LEN + ID_LEN + \
  4484. SUITE_LEN + COMP_LEN + OPAQUE16_LEN)
  4485. /* HH | PV | CipherSuite | Ext Len | Key Share | Supported Version | Cookie */
  4486. #define MAX_HRR_SZ (HRR_MAX_HS_HEADER_SZ + \
  4487. HRR_BODY_SZ + \
  4488. HRR_KEY_SHARE_SZ + \
  4489. HRR_VERSIONS_SZ + \
  4490. HRR_COOKIE_HDR_SZ)
  4491. /* Restart the handshake hash from the cookie value.
  4492. *
  4493. * ssl SSL/TLS object.
  4494. * cookie Cookie data from client.
  4495. * returns 0 on success, otherwise failure.
  4496. */
  4497. static int RestartHandshakeHashWithCookie(WOLFSSL* ssl, Cookie* cookie)
  4498. {
  4499. byte header[HRR_MAX_HS_HEADER_SZ] = {0};
  4500. byte hrr[MAX_HRR_SZ] = {0};
  4501. int hrrIdx;
  4502. word32 idx;
  4503. byte hashSz;
  4504. byte* cookieData;
  4505. byte cookieDataSz;
  4506. word16 length;
  4507. int keyShareExt = 0;
  4508. int ret;
  4509. cookieDataSz = ret = CheckCookie(ssl, &cookie->data, cookie->len);
  4510. if (ret < 0)
  4511. return ret;
  4512. hashSz = cookie->data;
  4513. cookieData = &cookie->data;
  4514. idx = OPAQUE8_LEN;
  4515. /* Restart handshake hash with synthetic message hash. */
  4516. AddTls13HandShakeHeader(header, hashSz, 0, 0, message_hash, ssl);
  4517. if ((ret = InitHandshakeHashes(ssl)) != 0)
  4518. return ret;
  4519. if ((ret = HashRaw(ssl, header, sizeof(header))) != 0)
  4520. return ret;
  4521. #ifdef WOLFSSL_DEBUG_TLS
  4522. WOLFSSL_MSG("Restart Hash from Cookie");
  4523. WOLFSSL_BUFFER(cookieData + idx, hashSz);
  4524. #endif
  4525. if ((ret = HashRaw(ssl, cookieData + idx, hashSz)) != 0)
  4526. return ret;
  4527. /* Reconstruct the HelloRetryMessage for handshake hash. */
  4528. length = HRR_BODY_SZ - ID_LEN + ssl->session->sessionIDSz +
  4529. HRR_COOKIE_HDR_SZ + cookie->len;
  4530. length += HRR_VERSIONS_SZ;
  4531. /* HashSz (1 byte) + Hash (HashSz bytes) + CipherSuite (2 bytes) */
  4532. if (cookieDataSz > OPAQUE8_LEN + hashSz + OPAQUE16_LEN) {
  4533. keyShareExt = 1;
  4534. length += HRR_KEY_SHARE_SZ;
  4535. }
  4536. AddTls13HandShakeHeader(hrr, length, 0, 0, server_hello, ssl);
  4537. idx += hashSz;
  4538. hrrIdx = HANDSHAKE_HEADER_SZ;
  4539. #ifdef WOLFSSL_DTLS13
  4540. if (ssl->options.dtls)
  4541. hrrIdx += DTLS_HANDSHAKE_EXTRA;
  4542. #endif /* WOLFSSL_DTLS13 */
  4543. /* The negotiated protocol version. */
  4544. hrr[hrrIdx++] = ssl->version.major;
  4545. hrr[hrrIdx++] = ssl->options.dtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR;
  4546. /* HelloRetryRequest message has fixed value for random. */
  4547. XMEMCPY(hrr + hrrIdx, helloRetryRequestRandom, RAN_LEN);
  4548. hrrIdx += RAN_LEN;
  4549. hrr[hrrIdx++] = ssl->session->sessionIDSz;
  4550. if (ssl->session->sessionIDSz > 0) {
  4551. XMEMCPY(hrr + hrrIdx, ssl->session->sessionID, ssl->session->sessionIDSz);
  4552. hrrIdx += ssl->session->sessionIDSz;
  4553. }
  4554. /* Cipher Suite */
  4555. hrr[hrrIdx++] = cookieData[idx++];
  4556. hrr[hrrIdx++] = cookieData[idx++];
  4557. /* Compression not supported in TLS v1.3. */
  4558. hrr[hrrIdx++] = 0;
  4559. /* Extensions' length */
  4560. length -= HRR_BODY_SZ - ID_LEN + ssl->session->sessionIDSz;
  4561. c16toa(length, hrr + hrrIdx);
  4562. hrrIdx += 2;
  4563. /* Optional KeyShare Extension */
  4564. if (keyShareExt) {
  4565. c16toa(TLSX_KEY_SHARE, hrr + hrrIdx);
  4566. hrrIdx += 2;
  4567. c16toa(OPAQUE16_LEN, hrr + hrrIdx);
  4568. hrrIdx += 2;
  4569. hrr[hrrIdx++] = cookieData[idx++];
  4570. hrr[hrrIdx++] = cookieData[idx++];
  4571. }
  4572. c16toa(TLSX_SUPPORTED_VERSIONS, hrr + hrrIdx);
  4573. hrrIdx += 2;
  4574. c16toa(OPAQUE16_LEN, hrr + hrrIdx);
  4575. hrrIdx += 2;
  4576. #ifdef WOLFSSL_TLS13_DRAFT
  4577. hrr[hrrIdx++] = TLS_DRAFT_MAJOR;
  4578. hrr[hrrIdx++] = TLS_DRAFT_MINOR;
  4579. #else
  4580. hrr[hrrIdx++] = ssl->version.major;
  4581. hrr[hrrIdx++] = ssl->version.minor;
  4582. #endif
  4583. /* Mandatory Cookie Extension */
  4584. c16toa(TLSX_COOKIE, hrr + hrrIdx);
  4585. hrrIdx += 2;
  4586. c16toa(cookie->len + OPAQUE16_LEN, hrr + hrrIdx);
  4587. hrrIdx += 2;
  4588. c16toa(cookie->len, hrr + hrrIdx);
  4589. hrrIdx += 2;
  4590. #ifdef WOLFSSL_DEBUG_TLS
  4591. WOLFSSL_MSG("Reconstructed HelloRetryRequest");
  4592. WOLFSSL_BUFFER(hrr, hrrIdx);
  4593. WOLFSSL_MSG("Cookie");
  4594. WOLFSSL_BUFFER(cookieData, cookie->len);
  4595. #endif
  4596. #ifdef WOLFSSL_DTLS13
  4597. if (ssl->options.dtls) {
  4598. ret = Dtls13HashHandshake(ssl, hrr, hrrIdx);
  4599. }
  4600. else
  4601. #endif /* WOLFSSL_DTLS13 */
  4602. {
  4603. ret = HashRaw(ssl, hrr, hrrIdx);
  4604. }
  4605. if (ret != 0)
  4606. return ret;
  4607. return HashRaw(ssl, cookieData, cookie->len);
  4608. }
  4609. #endif
  4610. /* Do SupportedVersion extension for TLS v1.3+ otherwise it is not.
  4611. *
  4612. * ssl The SSL/TLS object.
  4613. * input The message buffer.
  4614. * i The index into the message buffer of ClientHello.
  4615. * helloSz The length of the current handshake message.
  4616. * returns 0 on success and otherwise failure.
  4617. */
  4618. static int DoTls13SupportedVersions(WOLFSSL* ssl, const byte* input, word32 i,
  4619. word32 helloSz, int* wantDowngrade)
  4620. {
  4621. int ret;
  4622. byte b;
  4623. word16 suiteSz;
  4624. word16 totalExtSz;
  4625. int foundVersion = 0;
  4626. /* Client random */
  4627. i += RAN_LEN;
  4628. /* Session id - not used in TLS v1.3 */
  4629. b = input[i++];
  4630. if (i + b > helloSz) {
  4631. return BUFFER_ERROR;
  4632. }
  4633. i += b;
  4634. #ifdef WOLFSSL_DTLS13
  4635. if (ssl->options.dtls) {
  4636. /* legacy_cookie - not used in DTLS v1.3 */
  4637. b = input[i++];
  4638. if (i + b > helloSz) {
  4639. return BUFFER_ERROR;
  4640. }
  4641. i += b;
  4642. }
  4643. #endif /* WOLFSSL_DTLS13 */
  4644. /* Cipher suites */
  4645. if (i + OPAQUE16_LEN > helloSz)
  4646. return BUFFER_ERROR;
  4647. ato16(input + i, &suiteSz);
  4648. i += OPAQUE16_LEN;
  4649. if (i + suiteSz + 1 > helloSz)
  4650. return BUFFER_ERROR;
  4651. i += suiteSz;
  4652. /* Compression */
  4653. b = input[i++];
  4654. if (i + b > helloSz)
  4655. return BUFFER_ERROR;
  4656. i += b;
  4657. /* TLS 1.3 must have extensions */
  4658. if (i < helloSz) {
  4659. if (i + OPAQUE16_LEN > helloSz)
  4660. return BUFFER_ERROR;
  4661. ato16(&input[i], &totalExtSz);
  4662. i += OPAQUE16_LEN;
  4663. if (totalExtSz != helloSz - i)
  4664. return BUFFER_ERROR;
  4665. /* Need to negotiate version first. */
  4666. if ((ret = TLSX_ParseVersion(ssl, input + i, totalExtSz, client_hello,
  4667. &foundVersion))) {
  4668. return ret;
  4669. }
  4670. }
  4671. *wantDowngrade = !foundVersion || !IsAtLeastTLSv1_3(ssl->version);
  4672. return 0;
  4673. }
  4674. /* Handle a ClientHello handshake message.
  4675. * If the protocol version in the message is not TLS v1.3 or higher, use
  4676. * DoClientHello()
  4677. * Only a server will receive this message.
  4678. *
  4679. * ssl The SSL/TLS object.
  4680. * input The message buffer.
  4681. * inOutIdx On entry, the index into the message buffer of ClientHello.
  4682. * On exit, the index of byte after the ClientHello message and
  4683. * padding.
  4684. * helloSz The length of the current handshake message.
  4685. * returns 0 on success and otherwise failure.
  4686. */
  4687. typedef struct Dch13Args {
  4688. ProtocolVersion pv;
  4689. Suites* clSuites;
  4690. word32 idx;
  4691. word32 begin;
  4692. int usingPSK;
  4693. } Dch13Args;
  4694. static void FreeDch13Args(WOLFSSL* ssl, void* pArgs)
  4695. {
  4696. Dch13Args* args = (Dch13Args*)pArgs;
  4697. (void)ssl;
  4698. if (args && args->clSuites) {
  4699. XFREE(args->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES);
  4700. args->clSuites = NULL;
  4701. }
  4702. }
  4703. int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  4704. word32 helloSz)
  4705. {
  4706. int ret;
  4707. #ifdef WOLFSSL_ASYNC_CRYPT
  4708. Dch13Args* args = NULL;
  4709. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  4710. #else
  4711. Dch13Args args[1];
  4712. #endif
  4713. WOLFSSL_START(WC_FUNC_CLIENT_HELLO_DO);
  4714. WOLFSSL_ENTER("DoTls13ClientHello");
  4715. #ifdef WOLFSSL_ASYNC_CRYPT
  4716. if (ssl->async == NULL) {
  4717. ssl->async = (struct WOLFSSL_ASYNC*)
  4718. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  4719. DYNAMIC_TYPE_ASYNC);
  4720. if (ssl->async == NULL)
  4721. ERROR_OUT(MEMORY_E, exit_dch);
  4722. }
  4723. args = (Dch13Args*)ssl->async->args;
  4724. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  4725. if (ret != WC_NOT_PENDING_E) {
  4726. /* Check for error */
  4727. if (ret < 0) {
  4728. goto exit_dch;
  4729. }
  4730. }
  4731. else
  4732. #endif
  4733. {
  4734. /* Reset state */
  4735. ret = VERSION_ERROR;
  4736. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  4737. XMEMSET(args, 0, sizeof(Dch13Args));
  4738. #ifdef WOLFSSL_ASYNC_CRYPT
  4739. ssl->async->freeArgs = FreeDch13Args;
  4740. #endif
  4741. }
  4742. switch (ssl->options.asyncState) {
  4743. case TLS_ASYNC_BEGIN:
  4744. {
  4745. byte b;
  4746. byte sessIdSz;
  4747. int wantDowngrade = 0;
  4748. word16 totalExtSz = 0;
  4749. #ifdef WOLFSSL_CALLBACKS
  4750. if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
  4751. if (ssl->toInfoOn) AddLateName("ClientHello", &ssl->timeoutInfo);
  4752. #endif
  4753. args->idx = *inOutIdx;
  4754. args->begin = args->idx;
  4755. /* protocol version, random and session id length check */
  4756. if (OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz) {
  4757. ERROR_OUT(BUFFER_ERROR, exit_dch);
  4758. }
  4759. /* Protocol version */
  4760. XMEMCPY(&args->pv, input + args->idx, OPAQUE16_LEN);
  4761. ssl->chVersion = args->pv; /* store */
  4762. args->idx += OPAQUE16_LEN;
  4763. /* this check pass for DTLS Major (0xff) */
  4764. if (args->pv.major < SSLv3_MAJOR) {
  4765. WOLFSSL_MSG("Legacy version field contains unsupported value");
  4766. #ifdef WOLFSSL_MYSQL_COMPATIBLE
  4767. SendAlert(ssl, alert_fatal, wc_protocol_version);
  4768. #else
  4769. SendAlert(ssl, alert_fatal, protocol_version);
  4770. #endif
  4771. ERROR_OUT(INVALID_PARAMETER, exit_dch);
  4772. }
  4773. #ifdef WOLFSSL_DTLS13
  4774. if (ssl->options.dtls &&
  4775. args->pv.major == DTLS_MAJOR && args->pv.minor > DTLSv1_2_MINOR) {
  4776. wantDowngrade = 1;
  4777. ssl->version.minor = args->pv.minor;
  4778. }
  4779. #endif /* WOLFSSL_DTLS13 */
  4780. if (!ssl->options.dtls) {
  4781. /* Legacy protocol version cannot negotiate TLS 1.3 or higher. */
  4782. if (args->pv.major > SSLv3_MAJOR || (args->pv.major == SSLv3_MAJOR &&
  4783. args->pv.minor >= TLSv1_3_MINOR)) {
  4784. args->pv.major = SSLv3_MAJOR;
  4785. args->pv.minor = TLSv1_2_MINOR;
  4786. wantDowngrade = 1;
  4787. ssl->version.minor = args->pv.minor;
  4788. }
  4789. /* Legacy version must be [ SSLv3_MAJOR, TLSv1_2_MINOR ] for TLS v1.3 */
  4790. else if (args->pv.major == SSLv3_MAJOR &&
  4791. args->pv.minor < TLSv1_2_MINOR) {
  4792. wantDowngrade = 1;
  4793. ssl->version.minor = args->pv.minor;
  4794. }
  4795. }
  4796. if (!wantDowngrade) {
  4797. ret = DoTls13SupportedVersions(ssl, input + args->begin,
  4798. args->idx - args->begin, helloSz, &wantDowngrade);
  4799. if (ret < 0)
  4800. goto exit_dch;
  4801. }
  4802. if (wantDowngrade) {
  4803. #ifndef WOLFSSL_NO_TLS12
  4804. if (!ssl->options.downgrade) {
  4805. WOLFSSL_MSG("Client trying to connect with lesser version than "
  4806. "TLS v1.3");
  4807. #if defined(WOLFSSL_EXTRA_ALERTS) || defined(OPENSSL_EXTRA)
  4808. SendAlert(ssl, alert_fatal, handshake_failure);
  4809. #endif
  4810. ERROR_OUT(VERSION_ERROR, exit_dch);
  4811. }
  4812. if ((!ssl->options.dtls
  4813. && args->pv.minor < ssl->options.minDowngrade) ||
  4814. (ssl->options.dtls && args->pv.minor > ssl->options.minDowngrade)) {
  4815. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  4816. #if defined(WOLFSSL_EXTRA_ALERTS) || defined(OPENSSL_EXTRA)
  4817. SendAlert(ssl, alert_fatal, handshake_failure);
  4818. #endif
  4819. ERROR_OUT(VERSION_ERROR, exit_dch);
  4820. }
  4821. ret = HashInput(ssl, input + args->begin, helloSz);
  4822. if (ret == 0) {
  4823. ret = DoClientHello(ssl, input, inOutIdx, helloSz);
  4824. }
  4825. goto exit_dch;
  4826. #else
  4827. WOLFSSL_MSG("Client trying to connect with lesser version than "
  4828. "TLS v1.3");
  4829. ERROR_OUT(VERSION_ERROR, exit_dch);
  4830. #endif
  4831. }
  4832. /* From here on we are a TLS 1.3 ClientHello. */
  4833. /* Client random */
  4834. XMEMCPY(ssl->arrays->clientRandom, input + args->idx, RAN_LEN);
  4835. args->idx += RAN_LEN;
  4836. #ifdef WOLFSSL_DEBUG_TLS
  4837. WOLFSSL_MSG("client random");
  4838. WOLFSSL_BUFFER(ssl->arrays->clientRandom, RAN_LEN);
  4839. #endif
  4840. sessIdSz = input[args->idx++];
  4841. if (sessIdSz != ID_LEN && sessIdSz != 0)
  4842. ERROR_OUT(INVALID_PARAMETER, exit_dch);
  4843. if (sessIdSz + args->idx > helloSz) {
  4844. ERROR_OUT(BUFFER_ERROR, exit_dch);
  4845. }
  4846. ssl->session->sessionIDSz = sessIdSz;
  4847. if (sessIdSz == ID_LEN) {
  4848. XMEMCPY(ssl->session->sessionID, input + args->idx, sessIdSz);
  4849. args->idx += ID_LEN;
  4850. }
  4851. #ifdef WOLFSSL_DTLS13
  4852. /* legacy_cookie */
  4853. if (ssl->options.dtls)
  4854. args->idx += OPAQUE8_LEN;
  4855. #endif /* WOLFSSL_DTLS13 */
  4856. args->clSuites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap,
  4857. DYNAMIC_TYPE_SUITES);
  4858. if (args->clSuites == NULL) {
  4859. ERROR_OUT(MEMORY_E, exit_dch);
  4860. }
  4861. /* Cipher suites */
  4862. if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
  4863. ERROR_OUT(BUFFER_ERROR, exit_dch);
  4864. ato16(&input[args->idx], &args->clSuites->suiteSz);
  4865. args->idx += OPAQUE16_LEN;
  4866. /* suites and compression length check */
  4867. if ((args->idx - args->begin) + args->clSuites->suiteSz + OPAQUE8_LEN > helloSz)
  4868. ERROR_OUT(BUFFER_ERROR, exit_dch);
  4869. if (args->clSuites->suiteSz > WOLFSSL_MAX_SUITE_SZ)
  4870. ERROR_OUT(BUFFER_ERROR, exit_dch);
  4871. XMEMCPY(args->clSuites->suites, input + args->idx, args->clSuites->suiteSz);
  4872. args->idx += args->clSuites->suiteSz;
  4873. args->clSuites->hashSigAlgoSz = 0;
  4874. /* Compression */
  4875. b = input[args->idx++];
  4876. if ((args->idx - args->begin) + b > helloSz)
  4877. ERROR_OUT(BUFFER_ERROR, exit_dch);
  4878. if (b != COMP_LEN) {
  4879. WOLFSSL_MSG("Must be one compression type in list");
  4880. ERROR_OUT(INVALID_PARAMETER, exit_dch);
  4881. }
  4882. b = input[args->idx++];
  4883. if (b != NO_COMPRESSION) {
  4884. WOLFSSL_MSG("Must be no compression type in list");
  4885. ERROR_OUT(INVALID_PARAMETER, exit_dch);
  4886. }
  4887. /* Extensions */
  4888. if ((args->idx - args->begin) == helloSz)
  4889. ERROR_OUT(BUFFER_ERROR, exit_dch);
  4890. if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
  4891. ERROR_OUT(BUFFER_ERROR, exit_dch);
  4892. ato16(&input[args->idx], &totalExtSz);
  4893. args->idx += OPAQUE16_LEN;
  4894. if ((args->idx - args->begin) + totalExtSz > helloSz)
  4895. ERROR_OUT(BUFFER_ERROR, exit_dch);
  4896. /* Auto populate extensions supported unless user defined. */
  4897. if ((ret = TLSX_PopulateExtensions(ssl, 1)) != 0)
  4898. goto exit_dch;
  4899. /* Parse extensions */
  4900. if ((ret = TLSX_Parse(ssl, input + args->idx, totalExtSz, client_hello,
  4901. args->clSuites))) {
  4902. goto exit_dch;
  4903. }
  4904. #ifdef HAVE_SNI
  4905. if ((ret = SNI_Callback(ssl)) != 0)
  4906. return ret;
  4907. ssl->options.side = WOLFSSL_SERVER_END;
  4908. #endif
  4909. args->idx += totalExtSz;
  4910. ssl->options.haveSessionId = 1;
  4911. ssl->options.sendVerify = SEND_CERT;
  4912. #if defined(WOLFSSL_SEND_HRR_COOKIE)
  4913. if (ssl->options.sendCookie &&
  4914. (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE
  4915. #ifdef WOLFSSL_DTLS13
  4916. /* Always check for a valid cookie since we may have already
  4917. * sent a HRR but we reset the state. */
  4918. || ssl->options.dtls
  4919. #endif
  4920. )) {
  4921. TLSX* ext = TLSX_Find(ssl->extensions, TLSX_COOKIE);
  4922. if (ext != NULL) {
  4923. /* Ensure the cookie came from client and isn't the one in the
  4924. * response - HelloRetryRequest.
  4925. */
  4926. if (ext->resp == 0) {
  4927. ret = RestartHandshakeHashWithCookie(ssl, (Cookie*)ext->data);
  4928. #ifdef WOLFSSL_DTLS13
  4929. /* Send a new cookie request */
  4930. if (ret == HRR_COOKIE_ERROR && ssl->options.dtls)
  4931. ssl->options.serverState = NULL_STATE;
  4932. else
  4933. #endif
  4934. if (ret != 0)
  4935. goto exit_dch;
  4936. ssl->options.serverState = SERVER_HELLO_COMPLETE;
  4937. }
  4938. else {
  4939. #ifdef WOLFSSL_DTLS13
  4940. if (ssl->options.dtls)
  4941. ssl->options.serverState = NULL_STATE;
  4942. else
  4943. #endif
  4944. ERROR_OUT(HRR_COOKIE_ERROR, exit_dch);
  4945. }
  4946. }
  4947. else
  4948. #ifdef WOLFSSL_DTLS13
  4949. if (!ssl->options.dtls)
  4950. #endif
  4951. ERROR_OUT(HRR_COOKIE_ERROR, exit_dch);
  4952. }
  4953. #endif
  4954. #if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
  4955. defined(HAVE_TLS_EXTENSIONS)
  4956. ret = CheckPreSharedKeys(ssl, input + args->begin, helloSz, args->clSuites,
  4957. &args->usingPSK);
  4958. if (ret != 0)
  4959. goto exit_dch;
  4960. #else
  4961. if ((ret = HashInput(ssl, input + args->begin, helloSz)) != 0)
  4962. goto exit_dch;
  4963. #endif
  4964. #if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
  4965. defined(HAVE_TLS_EXTENSIONS)
  4966. if (!args->usingPSK)
  4967. #endif
  4968. {
  4969. /* Not using PSK so don't require no KE. */
  4970. ssl->options.noPskDheKe = 0;
  4971. #ifndef NO_CERTS
  4972. if (TLSX_Find(ssl->extensions, TLSX_KEY_SHARE) == NULL) {
  4973. WOLFSSL_MSG("Client did not send a KeyShare extension");
  4974. SendAlert(ssl, alert_fatal, missing_extension);
  4975. ERROR_OUT(INCOMPLETE_DATA, exit_dch);
  4976. }
  4977. if (TLSX_Find(ssl->extensions, TLSX_SIGNATURE_ALGORITHMS) == NULL) {
  4978. WOLFSSL_MSG("Client did not send a SignatureAlgorithms extension");
  4979. SendAlert(ssl, alert_fatal, missing_extension);
  4980. ERROR_OUT(INCOMPLETE_DATA, exit_dch);
  4981. }
  4982. #else
  4983. ERROR_OUT(INVALID_PARAMETER, exit_dch);
  4984. #endif
  4985. }
  4986. /* Advance state and proceed */
  4987. ssl->options.asyncState = TLS_ASYNC_BUILD;
  4988. } /* case TLS_ASYNC_BEGIN */
  4989. FALL_THROUGH;
  4990. case TLS_ASYNC_BUILD:
  4991. case TLS_ASYNC_DO:
  4992. {
  4993. #ifndef NO_CERTS
  4994. if (!args->usingPSK) {
  4995. if ((ret = MatchSuite(ssl, args->clSuites)) < 0) {
  4996. #ifdef WOLFSSL_ASYNC_CRYPT
  4997. if (ret == WC_PENDING_E)
  4998. goto exit_dch;
  4999. #endif
  5000. WOLFSSL_MSG("Unsupported cipher suite, ClientHello");
  5001. SendAlert(ssl, alert_fatal, handshake_failure);
  5002. goto exit_dch;
  5003. }
  5004. }
  5005. else
  5006. #endif
  5007. #ifdef HAVE_SUPPORTED_CURVES
  5008. if (args->usingPSK == 2) {
  5009. /* Pick key share and Generate a new key if not present. */
  5010. int doHelloRetry = 0;
  5011. ret = TLSX_KeyShare_Establish(ssl, &doHelloRetry);
  5012. if (doHelloRetry) {
  5013. ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
  5014. if (ret != WC_PENDING_E)
  5015. ret = 0; /* for hello_retry return 0 */
  5016. }
  5017. if (ret != 0)
  5018. goto exit_dch;
  5019. }
  5020. #endif
  5021. /* Advance state and proceed */
  5022. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  5023. } /* case TLS_ASYNC_BUILD || TLS_ASYNC_DO */
  5024. FALL_THROUGH;
  5025. case TLS_ASYNC_FINALIZE:
  5026. {
  5027. *inOutIdx = args->idx;
  5028. ssl->options.clientState = CLIENT_HELLO_COMPLETE;
  5029. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  5030. ssl->options.pskNegotiated = (args->usingPSK != 0);
  5031. #endif
  5032. if (!args->usingPSK) {
  5033. #ifndef NO_CERTS
  5034. #ifdef HAVE_NULL_CIPHER
  5035. if (ssl->options.cipherSuite0 == ECC_BYTE &&
  5036. (ssl->options.cipherSuite == TLS_SHA256_SHA256 ||
  5037. ssl->options.cipherSuite == TLS_SHA384_SHA384)) {
  5038. ;
  5039. }
  5040. else
  5041. #endif
  5042. /* Check that the negotiated ciphersuite matches protocol version. */
  5043. if (ssl->options.cipherSuite0 != TLS13_BYTE) {
  5044. WOLFSSL_MSG("Negotiated ciphersuite from lesser version than "
  5045. "TLS v1.3");
  5046. SendAlert(ssl, alert_fatal, handshake_failure);
  5047. ERROR_OUT(VERSION_ERROR, exit_dch);
  5048. }
  5049. #ifdef HAVE_SESSION_TICKET
  5050. if (ssl->options.resuming) {
  5051. ssl->options.resuming = 0;
  5052. XMEMSET(ssl->arrays->psk_key, 0, ssl->specs.hash_size);
  5053. }
  5054. #endif
  5055. /* Derive early secret for handshake secret. */
  5056. if ((ret = DeriveEarlySecret(ssl)) != 0)
  5057. goto exit_dch;
  5058. #endif /* !NO_CERTS */
  5059. }
  5060. break;
  5061. } /* case TLS_ASYNC_FINALIZE */
  5062. default:
  5063. ret = INPUT_CASE_ERROR;
  5064. } /* switch (ssl->options.asyncState) */
  5065. #if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  5066. /* We are using DTLSv13 and set the HRR cookie secret, use the cookie to
  5067. perform a return-routability check. */
  5068. if (ret == 0 && ssl->options.dtls && ssl->options.sendCookie &&
  5069. ssl->options.serverState < SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  5070. /* ssl->options.serverState < SERVER_HELLO_RETRY_REQUEST_COMPLETE
  5071. so the client already provided a good KeyShareEntry. In this case
  5072. we don't add the KEY_SHARE extension to the HelloRetryRequest or
  5073. in the Cookie. The RFC8446 forbids to select a supported group
  5074. with KeyShare extension in HelloRetryRequest if the client
  5075. already provided a KeyShareEntry for that group. See rfc8446
  5076. section 4.1.4 */
  5077. TLSX_Remove(&ssl->extensions, TLSX_KEY_SHARE, ssl->heap);
  5078. /* send an HRR (see wolfSSL_Accept_TLSv13()) */
  5079. ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
  5080. }
  5081. #endif /* WOLFSSL_DTLS13 */
  5082. exit_dch:
  5083. WOLFSSL_LEAVE("DoTls13ClientHello", ret);
  5084. #ifdef WOLFSSL_ASYNC_CRYPT
  5085. if (ret == WC_PENDING_E) {
  5086. ssl->msgsReceived.got_client_hello = 0;
  5087. return ret;
  5088. }
  5089. #endif
  5090. FreeDch13Args(ssl, args);
  5091. #ifdef WOLFSSL_ASYNC_CRYPT
  5092. FreeAsyncCtx(ssl, 0);
  5093. #endif
  5094. WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
  5095. if (ret != 0) {
  5096. WOLFSSL_ERROR_VERBOSE(ret);
  5097. }
  5098. return ret;
  5099. }
  5100. /* Send TLS v1.3 ServerHello message to client.
  5101. * Only a server will send this message.
  5102. *
  5103. * ssl The SSL/TLS object.
  5104. * returns 0 on success, otherwise failure.
  5105. */
  5106. /* handle generation of TLS 1.3 server_hello (2) */
  5107. int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType)
  5108. {
  5109. int ret;
  5110. byte* output;
  5111. word16 length;
  5112. word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  5113. int sendSz;
  5114. WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND);
  5115. WOLFSSL_ENTER("SendTls13ServerHello");
  5116. if (extMsgType == hello_retry_request) {
  5117. WOLFSSL_MSG("wolfSSL Doing HelloRetryRequest");
  5118. if ((ret = RestartHandshakeHash(ssl)) < 0)
  5119. return ret;
  5120. }
  5121. ssl->options.buildingMsg = 1;
  5122. #ifdef WOLFSSL_DTLS13
  5123. if (ssl->options.dtls)
  5124. idx = DTLS_RECORD_HEADER_SZ + DTLS_HANDSHAKE_HEADER_SZ;
  5125. #endif /* WOLFSSL_DTLS13 */
  5126. /* Protocol version, server random, session id, cipher suite, compression
  5127. * and extensions.
  5128. */
  5129. length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->session->sessionIDSz +
  5130. SUITE_LEN + COMP_LEN;
  5131. ret = TLSX_GetResponseSize(ssl, extMsgType, &length);
  5132. if (ret != 0)
  5133. return ret;
  5134. sendSz = idx + length;
  5135. /* Check buffers are big enough and grow if needed. */
  5136. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  5137. return ret;
  5138. /* Get position in output buffer to write new message to. */
  5139. output = ssl->buffers.outputBuffer.buffer +
  5140. ssl->buffers.outputBuffer.length;
  5141. /* Put the record and handshake headers on. */
  5142. AddTls13Headers(output, length, server_hello, ssl);
  5143. /* The protocol version must be TLS v1.2 for middleboxes. */
  5144. output[idx++] = ssl->version.major;
  5145. output[idx++] = ssl->options.dtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR;
  5146. if (extMsgType == server_hello) {
  5147. /* Generate server random. */
  5148. if ((ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN)) != 0)
  5149. return ret;
  5150. }
  5151. else {
  5152. /* HelloRetryRequest message has fixed value for random. */
  5153. XMEMCPY(output + idx, helloRetryRequestRandom, RAN_LEN);
  5154. }
  5155. /* Store in SSL for debugging. */
  5156. XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
  5157. idx += RAN_LEN;
  5158. #ifdef WOLFSSL_DEBUG_TLS
  5159. WOLFSSL_MSG("Server random");
  5160. WOLFSSL_BUFFER(ssl->arrays->serverRandom, RAN_LEN);
  5161. #endif
  5162. output[idx++] = ssl->session->sessionIDSz;
  5163. if (ssl->session->sessionIDSz > 0) {
  5164. XMEMCPY(output + idx, ssl->session->sessionID, ssl->session->sessionIDSz);
  5165. idx += ssl->session->sessionIDSz;
  5166. }
  5167. /* Chosen cipher suite */
  5168. output[idx++] = ssl->options.cipherSuite0;
  5169. output[idx++] = ssl->options.cipherSuite;
  5170. #ifdef WOLFSSL_DEBUG_TLS
  5171. WOLFSSL_MSG("Chosen cipher suite:");
  5172. WOLFSSL_MSG(GetCipherNameInternal(ssl->options.cipherSuite0,
  5173. ssl->options.cipherSuite));
  5174. #endif
  5175. /* Compression not supported in TLS v1.3. */
  5176. output[idx++] = 0;
  5177. /* Extensions */
  5178. ret = TLSX_WriteResponse(ssl, output + idx, extMsgType, NULL);
  5179. if (ret != 0)
  5180. return ret;
  5181. #ifdef WOLFSSL_SEND_HRR_COOKIE
  5182. if (ssl->options.sendCookie && extMsgType == hello_retry_request) {
  5183. /* Reset the hashes from here. We will be able to restart the hashes
  5184. * from the cookie in RestartHandshakeHashWithCookie */
  5185. ret = InitHandshakeHashes(ssl);
  5186. }
  5187. else
  5188. #endif
  5189. {
  5190. #ifdef WOLFSSL_DTLS13
  5191. if (ssl->options.dtls) {
  5192. ret = Dtls13HashHandshake(ssl,
  5193. output + Dtls13GetRlHeaderLength(0) ,
  5194. sendSz - Dtls13GetRlHeaderLength(0));
  5195. }
  5196. else
  5197. #endif /* WOLFSSL_DTLS13 */
  5198. {
  5199. ret = HashOutput(ssl, output, sendSz, 0);
  5200. }
  5201. }
  5202. if (ret != 0)
  5203. return ret;
  5204. #ifdef WOLFSSL_CALLBACKS
  5205. if (ssl->hsInfoOn)
  5206. AddPacketName(ssl, "ServerHello");
  5207. if (ssl->toInfoOn) {
  5208. AddPacketInfo(ssl, "ServerHello", handshake, output, sendSz,
  5209. WRITE_PROTO, ssl->heap);
  5210. }
  5211. #endif
  5212. if (extMsgType == server_hello)
  5213. ssl->options.serverState = SERVER_HELLO_COMPLETE;
  5214. ssl->options.buildingMsg = 0;
  5215. #ifdef WOLFSSL_DTLS13
  5216. if (ssl->options.dtls) {
  5217. ret = Dtls13HandshakeSend(ssl, output, sendSz, sendSz,
  5218. extMsgType, 0);
  5219. WOLFSSL_LEAVE("SendTls13ServerHello", ret);
  5220. WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
  5221. return ret;
  5222. }
  5223. #endif /* WOLFSSL_DTLS13 */
  5224. ssl->buffers.outputBuffer.length += sendSz;
  5225. if (!ssl->options.groupMessages || extMsgType != server_hello)
  5226. ret = SendBuffered(ssl);
  5227. WOLFSSL_LEAVE("SendTls13ServerHello", ret);
  5228. WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
  5229. return ret;
  5230. }
  5231. /* handle generation of TLS 1.3 encrypted_extensions (8) */
  5232. /* Send the rest of the extensions encrypted under the handshake key.
  5233. * This message is always encrypted in TLS v1.3.
  5234. * Only a server will send this message.
  5235. *
  5236. * ssl The SSL/TLS object.
  5237. * returns 0 on success, otherwise failure.
  5238. */
  5239. static int SendTls13EncryptedExtensions(WOLFSSL* ssl)
  5240. {
  5241. int ret;
  5242. byte* output;
  5243. word16 length = 0;
  5244. word32 idx;
  5245. int sendSz;
  5246. WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
  5247. WOLFSSL_ENTER("SendTls13EncryptedExtensions");
  5248. ssl->options.buildingMsg = 1;
  5249. ssl->keys.encryptionOn = 1;
  5250. #ifdef WOLFSSL_DTLS13
  5251. if (ssl->options.dtls) {
  5252. idx = Dtls13GetHeadersLength(encrypted_extensions);
  5253. }
  5254. else
  5255. #endif /* WOLFSSL_DTLS13 */
  5256. {
  5257. idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  5258. }
  5259. #if defined(HAVE_SUPPORTED_CURVES) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  5260. if ((ret = TLSX_SupportedCurve_CheckPriority(ssl)) != 0)
  5261. return ret;
  5262. #endif
  5263. /* Derive the handshake secret now that we are at first message to be
  5264. * encrypted under the keys.
  5265. */
  5266. if ((ret = DeriveHandshakeSecret(ssl)) != 0)
  5267. return ret;
  5268. if ((ret = DeriveTls13Keys(ssl, handshake_key,
  5269. ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0)
  5270. return ret;
  5271. /* Setup encrypt/decrypt keys for following messages. */
  5272. #ifdef WOLFSSL_EARLY_DATA
  5273. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  5274. return ret;
  5275. if (ssl->earlyData != process_early_data) {
  5276. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  5277. return ret;
  5278. }
  5279. #else
  5280. if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0)
  5281. return ret;
  5282. #endif
  5283. #ifdef WOLFSSL_QUIC
  5284. if (IsAtLeastTLSv1_3(ssl->version) && WOLFSSL_IS_QUIC(ssl)) {
  5285. ret = wolfSSL_quic_add_transport_extensions(ssl, encrypted_extensions);
  5286. if (ret != 0)
  5287. return ret;
  5288. }
  5289. #endif
  5290. #ifdef WOLFSSL_DTLS13
  5291. if (ssl->options.dtls) {
  5292. w64wrapper epochHandshake = w64From32(0, DTLS13_EPOCH_HANDSHAKE);
  5293. ssl->dtls13Epoch = epochHandshake;
  5294. ret = Dtls13NewEpoch(
  5295. ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE);
  5296. if (ret != 0)
  5297. return ret;
  5298. ret = Dtls13SetEpochKeys(
  5299. ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE);
  5300. if (ret != 0)
  5301. return ret;
  5302. }
  5303. #endif /* WOLFSSL_DTLS13 */
  5304. ret = TLSX_GetResponseSize(ssl, encrypted_extensions, &length);
  5305. if (ret != 0)
  5306. return ret;
  5307. sendSz = idx + length;
  5308. /* Encryption always on. */
  5309. sendSz += MAX_MSG_EXTRA;
  5310. /* Check buffers are big enough and grow if needed. */
  5311. ret = CheckAvailableSize(ssl, sendSz);
  5312. if (ret != 0)
  5313. return ret;
  5314. /* Get position in output buffer to write new message to. */
  5315. output = ssl->buffers.outputBuffer.buffer +
  5316. ssl->buffers.outputBuffer.length;
  5317. /* Put the record and handshake headers on. */
  5318. AddTls13Headers(output, length, encrypted_extensions, ssl);
  5319. ret = TLSX_WriteResponse(ssl, output + idx, encrypted_extensions, NULL);
  5320. if (ret != 0)
  5321. return ret;
  5322. idx += length;
  5323. #ifdef WOLFSSL_CALLBACKS
  5324. if (ssl->hsInfoOn)
  5325. AddPacketName(ssl, "EncryptedExtensions");
  5326. if (ssl->toInfoOn) {
  5327. AddPacketInfo(ssl, "EncryptedExtensions", handshake, output,
  5328. sendSz, WRITE_PROTO, ssl->heap);
  5329. }
  5330. #endif
  5331. #ifdef WOLFSSL_DTLS13
  5332. if (ssl->options.dtls) {
  5333. ssl->options.buildingMsg = 0;
  5334. ret = Dtls13HandshakeSend(ssl, output, sendSz, idx,
  5335. encrypted_extensions, 1);
  5336. if (ret == 0)
  5337. ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
  5338. WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
  5339. WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
  5340. return ret;
  5341. }
  5342. #endif /* WOLFSSL_DTLS13 */
  5343. /* This handshake message is always encrypted. */
  5344. sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
  5345. idx - RECORD_HEADER_SZ, handshake, 1, 0, 0);
  5346. if (sendSz < 0)
  5347. return sendSz;
  5348. ssl->buffers.outputBuffer.length += sendSz;
  5349. ssl->options.buildingMsg = 0;
  5350. ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
  5351. if (!ssl->options.groupMessages)
  5352. ret = SendBuffered(ssl);
  5353. WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
  5354. WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
  5355. return ret;
  5356. }
  5357. #ifndef NO_CERTS
  5358. /* handle generation TLS v1.3 certificate_request (13) */
  5359. /* Send the TLS v1.3 CertificateRequest message.
  5360. * This message is always encrypted in TLS v1.3.
  5361. * Only a server will send this message.
  5362. *
  5363. * ssl SSL/TLS object.
  5364. * reqCtx Request context.
  5365. * reqCtxLen Length of context. 0 when sending as part of handshake.
  5366. * returns 0 on success, otherwise failure.
  5367. */
  5368. static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx,
  5369. int reqCtxLen)
  5370. {
  5371. byte* output;
  5372. int ret;
  5373. int sendSz;
  5374. word32 i;
  5375. word16 reqSz;
  5376. TLSX* ext;
  5377. WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_SEND);
  5378. WOLFSSL_ENTER("SendTls13CertificateRequest");
  5379. ssl->options.buildingMsg = 1;
  5380. if (ssl->options.side == WOLFSSL_SERVER_END)
  5381. InitSuitesHashSigAlgo(ssl->suites, 1, 1, 1, 1,
  5382. 0, 1, ssl->buffers.keySz);
  5383. ext = TLSX_Find(ssl->extensions, TLSX_SIGNATURE_ALGORITHMS);
  5384. if (ext == NULL)
  5385. return EXT_MISSING;
  5386. ext->resp = 0;
  5387. i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  5388. #ifdef WOLFSSL_DTLS13
  5389. if (ssl->options.dtls)
  5390. i = Dtls13GetRlHeaderLength(1) + DTLS_HANDSHAKE_HEADER_SZ;
  5391. #endif /* WOLFSSL_DTLS13 */
  5392. reqSz = (word16)(OPAQUE8_LEN + reqCtxLen);
  5393. ret = TLSX_GetRequestSize(ssl, certificate_request, &reqSz);
  5394. if (ret != 0)
  5395. return ret;
  5396. sendSz = i + reqSz;
  5397. /* Always encrypted and make room for padding. */
  5398. sendSz += MAX_MSG_EXTRA;
  5399. /* Check buffers are big enough and grow if needed. */
  5400. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  5401. return ret;
  5402. /* Get position in output buffer to write new message to. */
  5403. output = ssl->buffers.outputBuffer.buffer +
  5404. ssl->buffers.outputBuffer.length;
  5405. /* Put the record and handshake headers on. */
  5406. AddTls13Headers(output, reqSz, certificate_request, ssl);
  5407. /* Certificate request context. */
  5408. output[i++] = (byte)reqCtxLen;
  5409. if (reqCtxLen != 0) {
  5410. XMEMCPY(output + i, reqCtx, reqCtxLen);
  5411. i += reqCtxLen;
  5412. }
  5413. /* Certificate extensions. */
  5414. reqSz = 0;
  5415. ret = TLSX_WriteRequest(ssl, output + i, certificate_request, &reqSz);
  5416. if (ret != 0)
  5417. return ret;
  5418. i += reqSz;
  5419. #ifdef WOLFSSL_DTLS13
  5420. if (ssl->options.dtls) {
  5421. ssl->options.buildingMsg = 0;
  5422. ret =
  5423. Dtls13HandshakeSend(ssl, output, sendSz, i, certificate_request, 1);
  5424. WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
  5425. WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
  5426. return ret;
  5427. }
  5428. #endif /* WOLFSSL_DTLS13 */
  5429. /* Always encrypted. */
  5430. sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
  5431. i - RECORD_HEADER_SZ, handshake, 1, 0, 0);
  5432. if (sendSz < 0)
  5433. return sendSz;
  5434. #ifdef WOLFSSL_CALLBACKS
  5435. if (ssl->hsInfoOn)
  5436. AddPacketName(ssl, "CertificateRequest");
  5437. if (ssl->toInfoOn) {
  5438. AddPacketInfo(ssl, "CertificateRequest", handshake, output,
  5439. sendSz, WRITE_PROTO, ssl->heap);
  5440. }
  5441. #endif
  5442. ssl->buffers.outputBuffer.length += sendSz;
  5443. ssl->options.buildingMsg = 0;
  5444. if (!ssl->options.groupMessages)
  5445. ret = SendBuffered(ssl);
  5446. WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
  5447. WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
  5448. return ret;
  5449. }
  5450. #endif /* NO_CERTS */
  5451. #endif /* NO_WOLFSSL_SERVER */
  5452. #ifndef NO_CERTS
  5453. #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  5454. defined(HAVE_ED448) || defined(HAVE_PQC)
  5455. /* Encode the signature algorithm into buffer.
  5456. *
  5457. * hashalgo The hash algorithm.
  5458. * hsType The signature type.
  5459. * output The buffer to encode into.
  5460. */
  5461. static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output)
  5462. {
  5463. switch (hsType) {
  5464. #ifdef HAVE_ECC
  5465. case ecc_dsa_sa_algo:
  5466. output[0] = hashAlgo;
  5467. output[1] = ecc_dsa_sa_algo;
  5468. break;
  5469. #endif
  5470. #ifdef HAVE_ED25519
  5471. /* ED25519: 0x0807 */
  5472. case ed25519_sa_algo:
  5473. output[0] = ED25519_SA_MAJOR;
  5474. output[1] = ED25519_SA_MINOR;
  5475. (void)hashAlgo;
  5476. break;
  5477. #endif
  5478. #ifdef HAVE_ED448
  5479. /* ED448: 0x0808 */
  5480. case ed448_sa_algo:
  5481. output[0] = ED448_SA_MAJOR;
  5482. output[1] = ED448_SA_MINOR;
  5483. (void)hashAlgo;
  5484. break;
  5485. #endif
  5486. #ifndef NO_RSA
  5487. /* PSS signatures: 0x080[4-6] */
  5488. case rsa_pss_sa_algo:
  5489. output[0] = rsa_pss_sa_algo;
  5490. output[1] = hashAlgo;
  5491. break;
  5492. #endif
  5493. #ifdef HAVE_PQC
  5494. #ifdef HAVE_FALCON
  5495. case falcon_level1_sa_algo:
  5496. output[0] = FALCON_LEVEL1_SA_MAJOR;
  5497. output[1] = FALCON_LEVEL1_SA_MINOR;
  5498. break;
  5499. case falcon_level5_sa_algo:
  5500. output[0] = FALCON_LEVEL5_SA_MAJOR;
  5501. output[1] = FALCON_LEVEL5_SA_MINOR;
  5502. break;
  5503. #endif
  5504. #ifdef HAVE_DILITHIUM
  5505. case dilithium_level2_sa_algo:
  5506. output[0] = DILITHIUM_LEVEL2_SA_MAJOR;
  5507. output[1] = DILITHIUM_LEVEL2_SA_MINOR;
  5508. break;
  5509. case dilithium_level3_sa_algo:
  5510. output[0] = DILITHIUM_LEVEL3_SA_MAJOR;
  5511. output[1] = DILITHIUM_LEVEL3_SA_MINOR;
  5512. break;
  5513. case dilithium_level5_sa_algo:
  5514. output[0] = DILITHIUM_LEVEL5_SA_MAJOR;
  5515. output[1] = DILITHIUM_LEVEL5_SA_MINOR;
  5516. break;
  5517. case dilithium_aes_level2_sa_algo:
  5518. output[0] = DILITHIUM_AES_LEVEL2_SA_MAJOR;
  5519. output[1] = DILITHIUM_AES_LEVEL2_SA_MINOR;
  5520. break;
  5521. case dilithium_aes_level3_sa_algo:
  5522. output[0] = DILITHIUM_AES_LEVEL3_SA_MAJOR;
  5523. output[1] = DILITHIUM_AES_LEVEL3_SA_MINOR;
  5524. break;
  5525. case dilithium_aes_level5_sa_algo:
  5526. output[0] = DILITHIUM_AES_LEVEL5_SA_MAJOR;
  5527. output[1] = DILITHIUM_AES_LEVEL5_SA_MINOR;
  5528. break;
  5529. #endif
  5530. #endif
  5531. default:
  5532. break;
  5533. }
  5534. }
  5535. /* Decode the signature algorithm.
  5536. *
  5537. * input The encoded signature algorithm.
  5538. * hashalgo The hash algorithm.
  5539. * hsType The signature type.
  5540. * returns INVALID_PARAMETER if not recognized and 0 otherwise.
  5541. */
  5542. static WC_INLINE int DecodeTls13SigAlg(byte* input, byte* hashAlgo,
  5543. byte* hsType)
  5544. {
  5545. int ret = 0;
  5546. switch (input[0]) {
  5547. case NEW_SA_MAJOR:
  5548. /* PSS signatures: 0x080[4-6] */
  5549. if (input[1] >= sha256_mac && input[1] <= sha512_mac) {
  5550. *hsType = input[0];
  5551. *hashAlgo = input[1];
  5552. }
  5553. #ifdef HAVE_ED25519
  5554. /* ED25519: 0x0807 */
  5555. else if (input[1] == ED25519_SA_MINOR) {
  5556. *hsType = ed25519_sa_algo;
  5557. /* Hash performed as part of sign/verify operation. */
  5558. *hashAlgo = sha512_mac;
  5559. }
  5560. #endif
  5561. #ifdef HAVE_ED448
  5562. /* ED448: 0x0808 */
  5563. else if (input[1] == ED448_SA_MINOR) {
  5564. *hsType = ed448_sa_algo;
  5565. /* Hash performed as part of sign/verify operation. */
  5566. *hashAlgo = sha512_mac;
  5567. }
  5568. #endif
  5569. else
  5570. ret = INVALID_PARAMETER;
  5571. break;
  5572. #ifdef HAVE_PQC
  5573. case PQC_SA_MAJOR:
  5574. #if defined(HAVE_FALCON)
  5575. if (input[1] == FALCON_LEVEL1_SA_MINOR) {
  5576. *hsType = falcon_level1_sa_algo;
  5577. /* Hash performed as part of sign/verify operation. */
  5578. *hashAlgo = sha512_mac;
  5579. } else if (input[1] == FALCON_LEVEL5_SA_MINOR) {
  5580. *hsType = falcon_level5_sa_algo;
  5581. /* Hash performed as part of sign/verify operation. */
  5582. *hashAlgo = sha512_mac;
  5583. }
  5584. else
  5585. #endif /* HAVE_FALCON */
  5586. #if defined(HAVE_DILITHIUM)
  5587. if (input[1] == DILITHIUM_LEVEL2_SA_MINOR) {
  5588. *hsType = dilithium_level2_sa_algo;
  5589. /* Hash performed as part of sign/verify operation. */
  5590. *hashAlgo = sha512_mac;
  5591. } else if (input[1] == DILITHIUM_LEVEL3_SA_MINOR) {
  5592. *hsType = dilithium_level3_sa_algo;
  5593. /* Hash performed as part of sign/verify operation. */
  5594. *hashAlgo = sha512_mac;
  5595. } else if (input[1] == DILITHIUM_LEVEL5_SA_MINOR) {
  5596. *hsType = dilithium_level5_sa_algo;
  5597. /* Hash performed as part of sign/verify operation. */
  5598. *hashAlgo = sha512_mac;
  5599. } else if (input[1] == DILITHIUM_AES_LEVEL2_SA_MINOR) {
  5600. *hsType = dilithium_aes_level2_sa_algo;
  5601. /* Hash performed as part of sign/verify operation. */
  5602. *hashAlgo = sha512_mac;
  5603. } else if (input[1] == DILITHIUM_AES_LEVEL3_SA_MINOR) {
  5604. *hsType = dilithium_aes_level3_sa_algo;
  5605. /* Hash performed as part of sign/verify operation. */
  5606. *hashAlgo = sha512_mac;
  5607. } else if (input[1] == DILITHIUM_AES_LEVEL5_SA_MINOR) {
  5608. *hsType = dilithium_aes_level5_sa_algo;
  5609. /* Hash performed as part of sign/verify operation. */
  5610. *hashAlgo = sha512_mac;
  5611. }
  5612. else
  5613. #endif /* HAVE_DILITHIUM */
  5614. {
  5615. ret = INVALID_PARAMETER;
  5616. }
  5617. break;
  5618. #endif
  5619. default:
  5620. *hashAlgo = input[0];
  5621. *hsType = input[1];
  5622. break;
  5623. }
  5624. return ret;
  5625. }
  5626. /* Get the hash of the messages so far.
  5627. *
  5628. * ssl The SSL/TLS object.
  5629. * hash The buffer to write the hash to.
  5630. * returns the length of the hash.
  5631. */
  5632. static WC_INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash)
  5633. {
  5634. int ret = 0;
  5635. switch (ssl->specs.mac_algorithm) {
  5636. #ifndef NO_SHA256
  5637. case sha256_mac:
  5638. ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
  5639. if (ret == 0)
  5640. ret = WC_SHA256_DIGEST_SIZE;
  5641. break;
  5642. #endif /* !NO_SHA256 */
  5643. #ifdef WOLFSSL_SHA384
  5644. case sha384_mac:
  5645. ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
  5646. if (ret == 0)
  5647. ret = WC_SHA384_DIGEST_SIZE;
  5648. break;
  5649. #endif /* WOLFSSL_SHA384 */
  5650. #ifdef WOLFSSL_TLS13_SHA512
  5651. case sha512_mac:
  5652. ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
  5653. if (ret == 0)
  5654. ret = WC_SHA512_DIGEST_SIZE;
  5655. break;
  5656. #endif /* WOLFSSL_TLS13_SHA512 */
  5657. default:
  5658. break;
  5659. }
  5660. return ret;
  5661. }
  5662. /* The length of the certificate verification label - client and server. */
  5663. #define CERT_VFY_LABEL_SZ 34
  5664. /* The server certificate verification label. */
  5665. static const byte serverCertVfyLabel[CERT_VFY_LABEL_SZ] =
  5666. "TLS 1.3, server CertificateVerify";
  5667. /* The client certificate verification label. */
  5668. static const byte clientCertVfyLabel[CERT_VFY_LABEL_SZ] =
  5669. "TLS 1.3, client CertificateVerify";
  5670. /* The number of prefix bytes for signature data. */
  5671. #define SIGNING_DATA_PREFIX_SZ 64
  5672. /* The prefix byte in the signature data. */
  5673. #define SIGNING_DATA_PREFIX_BYTE 0x20
  5674. /* Maximum length of the signature data. */
  5675. #define MAX_SIG_DATA_SZ (SIGNING_DATA_PREFIX_SZ + \
  5676. CERT_VFY_LABEL_SZ + \
  5677. WC_MAX_DIGEST_SIZE)
  5678. /* Create the signature data for TLS v1.3 certificate verification.
  5679. *
  5680. * ssl The SSL/TLS object.
  5681. * sigData The signature data.
  5682. * sigDataSz The length of the signature data.
  5683. * check Indicates this is a check not create.
  5684. */
  5685. static int CreateSigData(WOLFSSL* ssl, byte* sigData, word16* sigDataSz,
  5686. int check)
  5687. {
  5688. word16 idx;
  5689. int side = ssl->options.side;
  5690. int ret;
  5691. /* Signature Data = Prefix | Label | Handshake Hash */
  5692. XMEMSET(sigData, SIGNING_DATA_PREFIX_BYTE, SIGNING_DATA_PREFIX_SZ);
  5693. idx = SIGNING_DATA_PREFIX_SZ;
  5694. if ((side == WOLFSSL_SERVER_END && check) ||
  5695. (side == WOLFSSL_CLIENT_END && !check)) {
  5696. XMEMCPY(&sigData[idx], clientCertVfyLabel, CERT_VFY_LABEL_SZ);
  5697. }
  5698. if ((side == WOLFSSL_CLIENT_END && check) ||
  5699. (side == WOLFSSL_SERVER_END && !check)) {
  5700. XMEMCPY(&sigData[idx], serverCertVfyLabel, CERT_VFY_LABEL_SZ);
  5701. }
  5702. idx += CERT_VFY_LABEL_SZ;
  5703. ret = GetMsgHash(ssl, &sigData[idx]);
  5704. if (ret < 0)
  5705. return ret;
  5706. *sigDataSz = (word16)(idx + ret);
  5707. ret = 0;
  5708. return ret;
  5709. }
  5710. #ifndef NO_RSA
  5711. /* Encode the PKCS #1.5 RSA signature.
  5712. *
  5713. * sig The buffer to place the encoded signature into.
  5714. * sigData The data to be signed.
  5715. * sigDataSz The size of the data to be signed.
  5716. * hashAlgo The hash algorithm to use when signing.
  5717. * returns the length of the encoded signature or negative on error.
  5718. */
  5719. static int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz,
  5720. int sigAlgo, int hashAlgo)
  5721. {
  5722. Digest digest;
  5723. int hashSz = 0;
  5724. int ret = BAD_FUNC_ARG;
  5725. byte* hash;
  5726. (void)sigAlgo;
  5727. hash = sig;
  5728. /* Digest the signature data. */
  5729. switch (hashAlgo) {
  5730. #ifndef NO_WOLFSSL_SHA256
  5731. case sha256_mac:
  5732. ret = wc_InitSha256(&digest.sha256);
  5733. if (ret == 0) {
  5734. ret = wc_Sha256Update(&digest.sha256, sigData, sigDataSz);
  5735. if (ret == 0)
  5736. ret = wc_Sha256Final(&digest.sha256, hash);
  5737. wc_Sha256Free(&digest.sha256);
  5738. }
  5739. hashSz = WC_SHA256_DIGEST_SIZE;
  5740. break;
  5741. #endif
  5742. #ifdef WOLFSSL_SHA384
  5743. case sha384_mac:
  5744. ret = wc_InitSha384(&digest.sha384);
  5745. if (ret == 0) {
  5746. ret = wc_Sha384Update(&digest.sha384, sigData, sigDataSz);
  5747. if (ret == 0)
  5748. ret = wc_Sha384Final(&digest.sha384, hash);
  5749. wc_Sha384Free(&digest.sha384);
  5750. }
  5751. hashSz = WC_SHA384_DIGEST_SIZE;
  5752. break;
  5753. #endif
  5754. #ifdef WOLFSSL_SHA512
  5755. case sha512_mac:
  5756. ret = wc_InitSha512(&digest.sha512);
  5757. if (ret == 0) {
  5758. ret = wc_Sha512Update(&digest.sha512, sigData, sigDataSz);
  5759. if (ret == 0)
  5760. ret = wc_Sha512Final(&digest.sha512, hash);
  5761. wc_Sha512Free(&digest.sha512);
  5762. }
  5763. hashSz = WC_SHA512_DIGEST_SIZE;
  5764. break;
  5765. #endif
  5766. }
  5767. if (ret != 0)
  5768. return ret;
  5769. return hashSz;
  5770. }
  5771. #endif /* !NO_RSA */
  5772. #ifdef HAVE_ECC
  5773. /* Encode the ECC signature.
  5774. *
  5775. * sigData The data to be signed.
  5776. * sigDataSz The size of the data to be signed.
  5777. * hashAlgo The hash algorithm to use when signing.
  5778. * returns the length of the encoded signature or negative on error.
  5779. */
  5780. static int CreateECCEncodedSig(byte* sigData, int sigDataSz, int hashAlgo)
  5781. {
  5782. Digest digest;
  5783. int hashSz = 0;
  5784. int ret = BAD_FUNC_ARG;
  5785. /* Digest the signature data. */
  5786. switch (hashAlgo) {
  5787. #ifndef NO_WOLFSSL_SHA256
  5788. case sha256_mac:
  5789. ret = wc_InitSha256(&digest.sha256);
  5790. if (ret == 0) {
  5791. ret = wc_Sha256Update(&digest.sha256, sigData, sigDataSz);
  5792. if (ret == 0)
  5793. ret = wc_Sha256Final(&digest.sha256, sigData);
  5794. wc_Sha256Free(&digest.sha256);
  5795. }
  5796. hashSz = WC_SHA256_DIGEST_SIZE;
  5797. break;
  5798. #endif
  5799. #ifdef WOLFSSL_SHA384
  5800. case sha384_mac:
  5801. ret = wc_InitSha384(&digest.sha384);
  5802. if (ret == 0) {
  5803. ret = wc_Sha384Update(&digest.sha384, sigData, sigDataSz);
  5804. if (ret == 0)
  5805. ret = wc_Sha384Final(&digest.sha384, sigData);
  5806. wc_Sha384Free(&digest.sha384);
  5807. }
  5808. hashSz = WC_SHA384_DIGEST_SIZE;
  5809. break;
  5810. #endif
  5811. #ifdef WOLFSSL_SHA512
  5812. case sha512_mac:
  5813. ret = wc_InitSha512(&digest.sha512);
  5814. if (ret == 0) {
  5815. ret = wc_Sha512Update(&digest.sha512, sigData, sigDataSz);
  5816. if (ret == 0)
  5817. ret = wc_Sha512Final(&digest.sha512, sigData);
  5818. wc_Sha512Free(&digest.sha512);
  5819. }
  5820. hashSz = WC_SHA512_DIGEST_SIZE;
  5821. break;
  5822. #endif
  5823. default:
  5824. break;
  5825. }
  5826. if (ret != 0)
  5827. return ret;
  5828. return hashSz;
  5829. }
  5830. #endif /* HAVE_ECC */
  5831. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  5832. /* Check that the decrypted signature matches the encoded signature
  5833. * based on the digest of the signature data.
  5834. *
  5835. * ssl The SSL/TLS object.
  5836. * sigAlgo The signature algorithm used to generate signature.
  5837. * hashAlgo The hash algorithm used to generate signature.
  5838. * decSig The decrypted signature.
  5839. * decSigSz The size of the decrypted signature.
  5840. * returns 0 on success, otherwise failure.
  5841. */
  5842. static int CheckRSASignature(WOLFSSL* ssl, int sigAlgo, int hashAlgo,
  5843. byte* decSig, word32 decSigSz)
  5844. {
  5845. int ret = 0;
  5846. byte sigData[MAX_SIG_DATA_SZ];
  5847. word16 sigDataSz;
  5848. word32 sigSz;
  5849. ret = CreateSigData(ssl, sigData, &sigDataSz, 1);
  5850. if (ret != 0)
  5851. return ret;
  5852. if (sigAlgo == rsa_pss_sa_algo) {
  5853. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  5854. ret = ConvertHashPss(hashAlgo, &hashType, NULL);
  5855. if (ret < 0)
  5856. return ret;
  5857. /* PSS signature can be done in-place */
  5858. ret = CreateRSAEncodedSig(sigData, sigData, sigDataSz,
  5859. sigAlgo, hashAlgo);
  5860. if (ret < 0)
  5861. return ret;
  5862. sigSz = ret;
  5863. ret = wc_RsaPSS_CheckPadding(sigData, sigSz, decSig, decSigSz,
  5864. hashType);
  5865. }
  5866. return ret;
  5867. }
  5868. #endif /* !NO_RSA && WC_RSA_PSS */
  5869. #endif /* !NO_RSA || HAVE_ECC */
  5870. #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
  5871. /* Get the next certificate from the list for writing into the TLS v1.3
  5872. * Certificate message.
  5873. *
  5874. * data The certificate list.
  5875. * length The length of the certificate data in the list.
  5876. * idx The index of the next certificate.
  5877. * returns the length of the certificate data. 0 indicates no more certificates
  5878. * in the list.
  5879. */
  5880. static word32 NextCert(byte* data, word32 length, word32* idx)
  5881. {
  5882. word32 len;
  5883. /* Is index at end of list. */
  5884. if (*idx == length)
  5885. return 0;
  5886. /* Length of the current ASN.1 encoded certificate. */
  5887. c24to32(data + *idx, &len);
  5888. /* Include the length field. */
  5889. len += 3;
  5890. /* Move index to next certificate and return the current certificate's
  5891. * length.
  5892. */
  5893. *idx += len;
  5894. return len;
  5895. }
  5896. /* Add certificate data and empty extension to output up to the fragment size.
  5897. *
  5898. * ssl SSL/TLS object.
  5899. * cert The certificate data to write out.
  5900. * len The length of the certificate data.
  5901. * extSz Length of the extension data with the certificate.
  5902. * idx The start of the certificate data to write out.
  5903. * fragSz The maximum size of this fragment.
  5904. * output The buffer to write to.
  5905. * returns the number of bytes written.
  5906. */
  5907. static word32 AddCertExt(WOLFSSL* ssl, byte* cert, word32 len, word16 extSz,
  5908. word32 idx, word32 fragSz, byte* output)
  5909. {
  5910. word32 i = 0;
  5911. word32 copySz = min(len - idx, fragSz);
  5912. if (idx < len) {
  5913. XMEMCPY(output, cert + idx, copySz);
  5914. i = copySz;
  5915. if (copySz == fragSz)
  5916. return i;
  5917. }
  5918. copySz = len + extSz - idx - i;
  5919. if (extSz == OPAQUE16_LEN) {
  5920. if (copySz <= fragSz) {
  5921. /* Empty extension */
  5922. output[i++] = 0;
  5923. output[i++] = 0;
  5924. }
  5925. }
  5926. else {
  5927. byte* certExts = ssl->buffers.certExts->buffer + idx + i - len;
  5928. /* Put out as much of the extensions' data as will fit in fragment. */
  5929. if (copySz > fragSz - i)
  5930. copySz = fragSz - i;
  5931. XMEMCPY(output + i, certExts, copySz);
  5932. i += copySz;
  5933. }
  5934. return i;
  5935. }
  5936. /* handle generation TLS v1.3 certificate (11) */
  5937. /* Send the certificate for this end and any CAs that help with validation.
  5938. * This message is always encrypted in TLS v1.3.
  5939. *
  5940. * ssl The SSL/TLS object.
  5941. * returns 0 on success, otherwise failure.
  5942. */
  5943. static int SendTls13Certificate(WOLFSSL* ssl)
  5944. {
  5945. int ret = 0;
  5946. word32 certSz, certChainSz, headerSz, listSz, payloadSz;
  5947. word16 extSz = 0;
  5948. word32 length, maxFragment;
  5949. word32 len = 0;
  5950. word32 idx = 0;
  5951. word32 offset = OPAQUE16_LEN;
  5952. byte* p = NULL;
  5953. byte certReqCtxLen = 0;
  5954. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  5955. byte* certReqCtx = NULL;
  5956. #endif
  5957. #ifdef OPENSSL_EXTRA
  5958. WOLFSSL_X509* x509 = NULL;
  5959. WOLFSSL_EVP_PKEY* pkey = NULL;
  5960. #endif
  5961. WOLFSSL_START(WC_FUNC_CERTIFICATE_SEND);
  5962. WOLFSSL_ENTER("SendTls13Certificate");
  5963. ssl->options.buildingMsg = 1;
  5964. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  5965. if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->certReqCtx != NULL) {
  5966. certReqCtxLen = ssl->certReqCtx->len;
  5967. certReqCtx = &ssl->certReqCtx->ctx;
  5968. }
  5969. #endif
  5970. #ifdef OPENSSL_EXTRA
  5971. /* call client cert callback if no cert has been loaded */
  5972. if ((ssl->ctx->CBClientCert != NULL) &&
  5973. (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer)) {
  5974. ret = ssl->ctx->CBClientCert(ssl, &x509, &pkey);
  5975. if (ret == 1) {
  5976. if ((wolfSSL_CTX_use_certificate(ssl->ctx, x509) == WOLFSSL_SUCCESS) &&
  5977. (wolfSSL_CTX_use_PrivateKey(ssl->ctx, pkey) == WOLFSSL_SUCCESS)) {
  5978. ssl->options.sendVerify = SEND_CERT;
  5979. }
  5980. wolfSSL_X509_free(x509);
  5981. wolfSSL_EVP_PKEY_free(pkey);
  5982. }
  5983. }
  5984. #endif
  5985. if (ssl->options.sendVerify == SEND_BLANK_CERT) {
  5986. certSz = 0;
  5987. certChainSz = 0;
  5988. headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ;
  5989. length = headerSz;
  5990. listSz = 0;
  5991. }
  5992. else {
  5993. #ifdef OPENSSL_EXTRA
  5994. if ((ret = CertSetupCbWrapper(ssl)) != 0)
  5995. return ret;
  5996. #endif
  5997. if (!ssl->buffers.certificate) {
  5998. WOLFSSL_MSG("Send Cert missing certificate buffer");
  5999. return BUFFER_ERROR;
  6000. }
  6001. /* Certificate Data */
  6002. certSz = ssl->buffers.certificate->length;
  6003. /* Cert Req Ctx Len | Cert Req Ctx | Cert List Len | Cert Data Len */
  6004. headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ +
  6005. CERT_HEADER_SZ;
  6006. ret = TLSX_GetResponseSize(ssl, certificate, &extSz);
  6007. if (ret < 0)
  6008. return ret;
  6009. /* Create extensions' data if none already present. */
  6010. if (extSz > OPAQUE16_LEN && ssl->buffers.certExts == NULL) {
  6011. ret = AllocDer(&ssl->buffers.certExts, extSz, CERT_TYPE, ssl->heap);
  6012. if (ret < 0)
  6013. return ret;
  6014. extSz = 0;
  6015. ret = TLSX_WriteResponse(ssl, ssl->buffers.certExts->buffer,
  6016. certificate, &extSz);
  6017. if (ret < 0)
  6018. return ret;
  6019. }
  6020. /* Length of message data with one certificate and extensions. */
  6021. length = headerSz + certSz + extSz;
  6022. /* Length of list data with one certificate and extensions. */
  6023. listSz = CERT_HEADER_SZ + certSz + extSz;
  6024. /* Send rest of chain if sending cert (chain has leading size/s). */
  6025. if (certSz > 0 && ssl->buffers.certChainCnt > 0) {
  6026. p = ssl->buffers.certChain->buffer;
  6027. /* Chain length including extensions. */
  6028. certChainSz = ssl->buffers.certChain->length +
  6029. OPAQUE16_LEN * ssl->buffers.certChainCnt;
  6030. length += certChainSz;
  6031. listSz += certChainSz;
  6032. }
  6033. else
  6034. certChainSz = 0;
  6035. }
  6036. payloadSz = length;
  6037. if (ssl->fragOffset != 0)
  6038. length -= (ssl->fragOffset + headerSz);
  6039. maxFragment = wolfSSL_GetMaxFragSize(ssl, MAX_RECORD_SIZE);
  6040. while (length > 0 && ret == 0) {
  6041. byte* output = NULL;
  6042. word32 fragSz = 0;
  6043. word32 i = RECORD_HEADER_SZ;
  6044. int sendSz = RECORD_HEADER_SZ;
  6045. #ifdef WOLFSSL_DTLS13
  6046. if (ssl->options.dtls) {
  6047. i = Dtls13GetRlHeaderLength(1);
  6048. sendSz = (int)i;
  6049. }
  6050. #endif /* WOLFSSL_DTLS13 */
  6051. if (ssl->fragOffset == 0) {
  6052. if (headerSz + certSz + extSz + certChainSz <=
  6053. maxFragment - HANDSHAKE_HEADER_SZ) {
  6054. fragSz = headerSz + certSz + extSz + certChainSz;
  6055. }
  6056. #ifdef WOLFSSL_DTLS13
  6057. else if (ssl->options.dtls){
  6058. /* short-circuit the fragmentation logic here. DTLS
  6059. fragmentation will be done in dtls13HandshakeSend() */
  6060. fragSz = headerSz + certSz + extSz + certChainSz;
  6061. }
  6062. #endif /* WOLFSSL_DTLS13 */
  6063. else {
  6064. fragSz = maxFragment - HANDSHAKE_HEADER_SZ;
  6065. }
  6066. sendSz += fragSz + HANDSHAKE_HEADER_SZ;
  6067. i += HANDSHAKE_HEADER_SZ;
  6068. #ifdef WOLFSSL_DTLS13
  6069. if (ssl->options.dtls) {
  6070. sendSz += DTLS_HANDSHAKE_EXTRA;
  6071. i += DTLS_HANDSHAKE_EXTRA;
  6072. }
  6073. #endif /* WOLFSSL_DTLS13 */
  6074. }
  6075. else {
  6076. fragSz = min(length, maxFragment);
  6077. sendSz += fragSz;
  6078. }
  6079. sendSz += MAX_MSG_EXTRA;
  6080. /* Check buffers are big enough and grow if needed. */
  6081. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  6082. return ret;
  6083. /* Get position in output buffer to write new message to. */
  6084. output = ssl->buffers.outputBuffer.buffer +
  6085. ssl->buffers.outputBuffer.length;
  6086. if (ssl->fragOffset == 0) {
  6087. AddTls13FragHeaders(output, fragSz, 0, payloadSz, certificate, ssl);
  6088. /* Request context. */
  6089. output[i++] = certReqCtxLen;
  6090. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  6091. if (certReqCtxLen > 0) {
  6092. XMEMCPY(output + i, certReqCtx, certReqCtxLen);
  6093. i += certReqCtxLen;
  6094. }
  6095. #endif
  6096. length -= OPAQUE8_LEN + certReqCtxLen;
  6097. fragSz -= OPAQUE8_LEN + certReqCtxLen;
  6098. /* Certificate list length. */
  6099. c32to24(listSz, output + i);
  6100. i += CERT_HEADER_SZ;
  6101. length -= CERT_HEADER_SZ;
  6102. fragSz -= CERT_HEADER_SZ;
  6103. /* Leaf certificate data length. */
  6104. if (certSz > 0) {
  6105. c32to24(certSz, output + i);
  6106. i += CERT_HEADER_SZ;
  6107. length -= CERT_HEADER_SZ;
  6108. fragSz -= CERT_HEADER_SZ;
  6109. }
  6110. }
  6111. else
  6112. AddTls13RecordHeader(output, fragSz, handshake, ssl);
  6113. if (certSz > 0 && ssl->fragOffset < certSz + extSz) {
  6114. /* Put in the leaf certificate with extensions. */
  6115. word32 copySz = AddCertExt(ssl, ssl->buffers.certificate->buffer,
  6116. certSz, extSz, ssl->fragOffset, fragSz, output + i);
  6117. i += copySz;
  6118. ssl->fragOffset += copySz;
  6119. length -= copySz;
  6120. fragSz -= copySz;
  6121. if (ssl->fragOffset == certSz + extSz)
  6122. FreeDer(&ssl->buffers.certExts);
  6123. }
  6124. if (certChainSz > 0 && fragSz > 0) {
  6125. /* Put in the CA certificates with empty extensions. */
  6126. while (fragSz > 0) {
  6127. word32 l;
  6128. if (offset == len + OPAQUE16_LEN) {
  6129. /* Find next CA certificate to write out. */
  6130. offset = 0;
  6131. /* Point to the start of current cert in chain buffer. */
  6132. p = ssl->buffers.certChain->buffer + idx;
  6133. len = NextCert(ssl->buffers.certChain->buffer,
  6134. ssl->buffers.certChain->length, &idx);
  6135. if (len == 0)
  6136. break;
  6137. }
  6138. /* Write out certificate and empty extension. */
  6139. l = AddCertExt(ssl, p, len, OPAQUE16_LEN, offset, fragSz,
  6140. output + i);
  6141. i += l;
  6142. ssl->fragOffset += l;
  6143. length -= l;
  6144. fragSz -= l;
  6145. offset += l;
  6146. }
  6147. }
  6148. if ((int)i - RECORD_HEADER_SZ < 0) {
  6149. WOLFSSL_MSG("Send Cert bad inputSz");
  6150. return BUFFER_E;
  6151. }
  6152. #ifdef WOLFSSL_DTLS13
  6153. if (ssl->options.dtls) {
  6154. /* DTLS1.3 uses a separate variable and logic for fragments */
  6155. ssl->options.buildingMsg = 0;
  6156. ssl->fragOffset = 0;
  6157. ret = Dtls13HandshakeSend(ssl, output, sendSz, i, certificate, 1);
  6158. }
  6159. else
  6160. #endif /* WOLFSSL_DTLS13 */
  6161. {
  6162. /* This message is always encrypted. */
  6163. sendSz = BuildTls13Message(ssl, output, sendSz,
  6164. output + RECORD_HEADER_SZ, i - RECORD_HEADER_SZ, handshake, 1,
  6165. 0, 0);
  6166. if (sendSz < 0)
  6167. return sendSz;
  6168. #ifdef WOLFSSL_CALLBACKS
  6169. if (ssl->hsInfoOn)
  6170. AddPacketName(ssl, "Certificate");
  6171. if (ssl->toInfoOn) {
  6172. AddPacketInfo(ssl, "Certificate", handshake, output,
  6173. sendSz, WRITE_PROTO, ssl->heap);
  6174. }
  6175. #endif
  6176. ssl->buffers.outputBuffer.length += sendSz;
  6177. ssl->options.buildingMsg = 0;
  6178. if (!ssl->options.groupMessages)
  6179. ret = SendBuffered(ssl);
  6180. }
  6181. }
  6182. if (ret != WANT_WRITE) {
  6183. /* Clean up the fragment offset. */
  6184. ssl->options.buildingMsg = 0;
  6185. ssl->fragOffset = 0;
  6186. if (ssl->options.side == WOLFSSL_SERVER_END)
  6187. ssl->options.serverState = SERVER_CERT_COMPLETE;
  6188. }
  6189. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  6190. if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->certReqCtx != NULL) {
  6191. CertReqCtx* ctx = ssl->certReqCtx;
  6192. ssl->certReqCtx = ssl->certReqCtx->next;
  6193. XFREE(ctx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  6194. }
  6195. #endif
  6196. WOLFSSL_LEAVE("SendTls13Certificate", ret);
  6197. WOLFSSL_END(WC_FUNC_CERTIFICATE_SEND);
  6198. return ret;
  6199. }
  6200. #if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  6201. defined(HAVE_ED448) || defined(HAVE_PQC)) && \
  6202. (!defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH))
  6203. typedef struct Scv13Args {
  6204. byte* output; /* not allocated */
  6205. byte* verify; /* not allocated */
  6206. word32 idx;
  6207. word32 sigLen;
  6208. int sendSz;
  6209. word16 length;
  6210. byte sigAlgo;
  6211. byte* sigData;
  6212. word16 sigDataSz;
  6213. } Scv13Args;
  6214. static void FreeScv13Args(WOLFSSL* ssl, void* pArgs)
  6215. {
  6216. Scv13Args* args = (Scv13Args*)pArgs;
  6217. (void)ssl;
  6218. if (args && args->sigData) {
  6219. XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  6220. args->sigData = NULL;
  6221. }
  6222. }
  6223. /* handle generation TLS v1.3 certificate_verify (15) */
  6224. /* Send the TLS v1.3 CertificateVerify message.
  6225. * A hash of all the message so far is used.
  6226. * The signed data is:
  6227. * 0x20 * 64 | context string | 0x00 | hash of messages
  6228. * This message is always encrypted in TLS v1.3.
  6229. *
  6230. * ssl The SSL/TLS object.
  6231. * returns 0 on success, otherwise failure.
  6232. */
  6233. static int SendTls13CertificateVerify(WOLFSSL* ssl)
  6234. {
  6235. int ret = 0;
  6236. buffer* sig = &ssl->buffers.sig;
  6237. #ifdef WOLFSSL_ASYNC_CRYPT
  6238. Scv13Args* args = NULL;
  6239. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  6240. #else
  6241. Scv13Args args[1];
  6242. #endif
  6243. #ifdef WOLFSSL_DTLS13
  6244. int recordLayerHdrExtra;
  6245. #endif /* WOLFSSL_DTLS13 */
  6246. WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_SEND);
  6247. WOLFSSL_ENTER("SendTls13CertificateVerify");
  6248. ssl->options.buildingMsg = 1;
  6249. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  6250. ret = tsip_Tls13SendCertVerify(ssl);
  6251. if (ret != CRYPTOCB_UNAVAILABLE) {
  6252. goto exit_scv;
  6253. }
  6254. ret = 0;
  6255. #endif /* WOLFSSL_RENESAS_TSIP_TLS && WOLFSSL_RENESAS_TSIP_VER >= 115 */
  6256. #ifdef WOLFSSL_DTLS13
  6257. /* can be negative */
  6258. if (ssl->options.dtls)
  6259. recordLayerHdrExtra = Dtls13GetRlHeaderLength(1) - RECORD_HEADER_SZ;
  6260. else
  6261. recordLayerHdrExtra = 0;
  6262. #endif /* WOLFSSL_DTLS13 */
  6263. #ifdef WOLFSSL_ASYNC_CRYPT
  6264. if (ssl->async == NULL) {
  6265. ssl->async = (struct WOLFSSL_ASYNC*)
  6266. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  6267. DYNAMIC_TYPE_ASYNC);
  6268. if (ssl->async == NULL)
  6269. ERROR_OUT(MEMORY_E, exit_scv);
  6270. }
  6271. args = (Scv13Args*)ssl->async->args;
  6272. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  6273. if (ret != WC_NOT_PENDING_E) {
  6274. /* Check for error */
  6275. if (ret < 0)
  6276. goto exit_scv;
  6277. }
  6278. else
  6279. #endif
  6280. {
  6281. /* Reset state */
  6282. ret = 0;
  6283. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  6284. XMEMSET(args, 0, sizeof(Scv13Args));
  6285. #ifdef WOLFSSL_ASYNC_CRYPT
  6286. ssl->async->freeArgs = FreeScv13Args;
  6287. #endif
  6288. }
  6289. switch(ssl->options.asyncState)
  6290. {
  6291. case TLS_ASYNC_BEGIN:
  6292. {
  6293. if (ssl->options.sendVerify == SEND_BLANK_CERT) {
  6294. return 0; /* sent blank cert, can't verify */
  6295. }
  6296. args->sendSz = MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA;
  6297. /* Always encrypted. */
  6298. args->sendSz += MAX_MSG_EXTRA;
  6299. /* check for available size */
  6300. if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
  6301. goto exit_scv;
  6302. }
  6303. /* get output buffer */
  6304. args->output = ssl->buffers.outputBuffer.buffer +
  6305. ssl->buffers.outputBuffer.length;
  6306. /* Advance state and proceed */
  6307. ssl->options.asyncState = TLS_ASYNC_BUILD;
  6308. } /* case TLS_ASYNC_BEGIN */
  6309. FALL_THROUGH;
  6310. case TLS_ASYNC_BUILD:
  6311. {
  6312. int rem = ssl->buffers.outputBuffer.bufferSize
  6313. - ssl->buffers.outputBuffer.length
  6314. - RECORD_HEADER_SZ - HANDSHAKE_HEADER_SZ;
  6315. /* idx is used to track verify pointer offset to output */
  6316. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  6317. args->verify =
  6318. &args->output[RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ];
  6319. #ifdef WOLFSSL_DTLS13
  6320. if (ssl->options.dtls) {
  6321. rem -= recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
  6322. args->idx += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
  6323. args->verify += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
  6324. }
  6325. #endif /* WOLFSSL_DTLS13 */
  6326. if (ssl->buffers.key == NULL) {
  6327. #ifdef HAVE_PK_CALLBACKS
  6328. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
  6329. args->length = GetPrivateKeySigSize(ssl);
  6330. else
  6331. #endif
  6332. ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
  6333. }
  6334. else {
  6335. ret = DecodePrivateKey(ssl, &args->length);
  6336. if (ret != 0)
  6337. goto exit_scv;
  6338. }
  6339. if (rem < 0 || args->length > rem) {
  6340. ERROR_OUT(BUFFER_E, exit_scv);
  6341. }
  6342. if (args->length == 0) {
  6343. ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
  6344. }
  6345. /* Add signature algorithm. */
  6346. if (ssl->hsType == DYNAMIC_TYPE_RSA)
  6347. args->sigAlgo = rsa_pss_sa_algo;
  6348. #ifdef HAVE_ECC
  6349. else if (ssl->hsType == DYNAMIC_TYPE_ECC)
  6350. args->sigAlgo = ecc_dsa_sa_algo;
  6351. #endif
  6352. #ifdef HAVE_ED25519
  6353. else if (ssl->hsType == DYNAMIC_TYPE_ED25519)
  6354. args->sigAlgo = ed25519_sa_algo;
  6355. #endif
  6356. #ifdef HAVE_ED448
  6357. else if (ssl->hsType == DYNAMIC_TYPE_ED448)
  6358. args->sigAlgo = ed448_sa_algo;
  6359. #endif
  6360. #if defined(HAVE_PQC)
  6361. #if defined(HAVE_FALCON)
  6362. else if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
  6363. falcon_key* fkey = (falcon_key*)ssl->hsKey;
  6364. byte level = 0;
  6365. if (wc_falcon_get_level(fkey, &level) != 0) {
  6366. ERROR_OUT(ALGO_ID_E, exit_scv);
  6367. }
  6368. if (level == 1) {
  6369. args->sigAlgo = falcon_level1_sa_algo;
  6370. }
  6371. else if (level == 5) {
  6372. args->sigAlgo = falcon_level5_sa_algo;
  6373. }
  6374. else {
  6375. ERROR_OUT(ALGO_ID_E, exit_scv);
  6376. }
  6377. }
  6378. #endif /* HAVE_FALCON */
  6379. #if defined(HAVE_DILITHIUM)
  6380. else if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) {
  6381. dilithium_key* fkey = (dilithium_key*)ssl->hsKey;
  6382. byte level = 0;
  6383. byte sym = 0;
  6384. if (wc_dilithium_get_level_and_sym(fkey, &level, &sym) != 0) {
  6385. ERROR_OUT(ALGO_ID_E, exit_scv);
  6386. }
  6387. if ((level == 2) && (sym == SHAKE_VARIANT)) {
  6388. args->sigAlgo = dilithium_level2_sa_algo;
  6389. }
  6390. else if ((level == 3) && (sym == SHAKE_VARIANT)) {
  6391. args->sigAlgo = dilithium_level3_sa_algo;
  6392. }
  6393. else if ((level == 5) && (sym == SHAKE_VARIANT)) {
  6394. args->sigAlgo = dilithium_level5_sa_algo;
  6395. }
  6396. else if ((level == 2) && (sym == AES_VARIANT)) {
  6397. args->sigAlgo = dilithium_aes_level2_sa_algo;
  6398. }
  6399. else if ((level == 3) && (sym == AES_VARIANT)) {
  6400. args->sigAlgo = dilithium_aes_level3_sa_algo;
  6401. }
  6402. else if ((level == 5) && (sym == AES_VARIANT)) {
  6403. args->sigAlgo = dilithium_aes_level5_sa_algo;
  6404. }
  6405. else {
  6406. ERROR_OUT(ALGO_ID_E, exit_scv);
  6407. }
  6408. }
  6409. #endif /* HAVE_DILITHIUM */
  6410. #endif /* HAVE_PQC */
  6411. else {
  6412. ERROR_OUT(ALGO_ID_E, exit_scv);
  6413. }
  6414. EncodeSigAlg(ssl->suites->hashAlgo, args->sigAlgo, args->verify);
  6415. if (ssl->hsType == DYNAMIC_TYPE_RSA) {
  6416. int sigLen = MAX_SIG_DATA_SZ;
  6417. if (args->length > MAX_SIG_DATA_SZ)
  6418. sigLen = args->length;
  6419. args->sigData = (byte*)XMALLOC(sigLen, ssl->heap,
  6420. DYNAMIC_TYPE_SIGNATURE);
  6421. }
  6422. else {
  6423. args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
  6424. DYNAMIC_TYPE_SIGNATURE);
  6425. }
  6426. if (args->sigData == NULL) {
  6427. ERROR_OUT(MEMORY_E, exit_scv);
  6428. }
  6429. /* Create the data to be signed. */
  6430. ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 0);
  6431. if (ret != 0)
  6432. goto exit_scv;
  6433. #ifndef NO_RSA
  6434. if (ssl->hsType == DYNAMIC_TYPE_RSA) {
  6435. /* build encoded signature buffer */
  6436. sig->length = WC_MAX_DIGEST_SIZE;
  6437. sig->buffer = (byte*)XMALLOC(sig->length, ssl->heap,
  6438. DYNAMIC_TYPE_SIGNATURE);
  6439. if (sig->buffer == NULL) {
  6440. ERROR_OUT(MEMORY_E, exit_scv);
  6441. }
  6442. ret = CreateRSAEncodedSig(sig->buffer, args->sigData,
  6443. args->sigDataSz, args->sigAlgo, ssl->suites->hashAlgo);
  6444. if (ret < 0)
  6445. goto exit_scv;
  6446. sig->length = ret;
  6447. ret = 0;
  6448. /* Maximum size of RSA Signature. */
  6449. args->sigLen = args->length;
  6450. }
  6451. #endif /* !NO_RSA */
  6452. #ifdef HAVE_ECC
  6453. if (ssl->hsType == DYNAMIC_TYPE_ECC) {
  6454. sig->length = args->sendSz - args->idx - HASH_SIG_SIZE -
  6455. VERIFY_HEADER;
  6456. ret = CreateECCEncodedSig(args->sigData,
  6457. args->sigDataSz, ssl->suites->hashAlgo);
  6458. if (ret < 0)
  6459. goto exit_scv;
  6460. args->sigDataSz = (word16)ret;
  6461. ret = 0;
  6462. }
  6463. #endif /* HAVE_ECC */
  6464. #ifdef HAVE_ED25519
  6465. if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
  6466. ret = Ed25519CheckPubKey(ssl);
  6467. if (ret < 0) {
  6468. ERROR_OUT(ret, exit_scv);
  6469. }
  6470. sig->length = ED25519_SIG_SIZE;
  6471. }
  6472. #endif /* HAVE_ED25519 */
  6473. #ifdef HAVE_ED448
  6474. if (ssl->hsType == DYNAMIC_TYPE_ED448) {
  6475. ret = Ed448CheckPubKey(ssl);
  6476. if (ret < 0) {
  6477. ERROR_OUT(ret, exit_scv);
  6478. }
  6479. sig->length = ED448_SIG_SIZE;
  6480. }
  6481. #endif /* HAVE_ED448 */
  6482. #if defined(HAVE_PQC)
  6483. #if defined(HAVE_FALCON)
  6484. if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
  6485. sig->length = FALCON_MAX_SIG_SIZE;
  6486. }
  6487. #endif
  6488. #if defined(HAVE_DILITHIUM)
  6489. if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) {
  6490. sig->length = DILITHIUM_MAX_SIG_SIZE;
  6491. }
  6492. #endif
  6493. #endif /* HAVE_PQC */
  6494. /* Advance state and proceed */
  6495. ssl->options.asyncState = TLS_ASYNC_DO;
  6496. } /* case TLS_ASYNC_BUILD */
  6497. FALL_THROUGH;
  6498. case TLS_ASYNC_DO:
  6499. {
  6500. #ifdef HAVE_ECC
  6501. if (ssl->hsType == DYNAMIC_TYPE_ECC) {
  6502. ret = EccSign(ssl, args->sigData, args->sigDataSz,
  6503. args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
  6504. (word32*)&sig->length, (ecc_key*)ssl->hsKey,
  6505. #ifdef HAVE_PK_CALLBACKS
  6506. ssl->buffers.key
  6507. #else
  6508. NULL
  6509. #endif
  6510. );
  6511. args->length = (word16)sig->length;
  6512. }
  6513. #endif /* HAVE_ECC */
  6514. #ifdef HAVE_ED25519
  6515. if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
  6516. ret = Ed25519Sign(ssl, args->sigData, args->sigDataSz,
  6517. args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
  6518. (word32*)&sig->length, (ed25519_key*)ssl->hsKey,
  6519. #ifdef HAVE_PK_CALLBACKS
  6520. ssl->buffers.key
  6521. #else
  6522. NULL
  6523. #endif
  6524. );
  6525. args->length = (word16)sig->length;
  6526. }
  6527. #endif
  6528. #ifdef HAVE_ED448
  6529. if (ssl->hsType == DYNAMIC_TYPE_ED448) {
  6530. ret = Ed448Sign(ssl, args->sigData, args->sigDataSz,
  6531. args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
  6532. (word32*)&sig->length, (ed448_key*)ssl->hsKey,
  6533. #ifdef HAVE_PK_CALLBACKS
  6534. ssl->buffers.key
  6535. #else
  6536. NULL
  6537. #endif
  6538. );
  6539. args->length = (word16)sig->length;
  6540. }
  6541. #endif
  6542. #if defined(HAVE_PQC)
  6543. #if defined(HAVE_FALCON)
  6544. if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
  6545. ret = wc_falcon_sign_msg(args->sigData, args->sigDataSz,
  6546. args->verify + HASH_SIG_SIZE +
  6547. VERIFY_HEADER, (word32*)&sig->length,
  6548. (falcon_key*)ssl->hsKey);
  6549. args->length = (word16)sig->length;
  6550. }
  6551. #endif
  6552. #if defined(HAVE_DILITHIUM)
  6553. if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) {
  6554. ret = wc_dilithium_sign_msg(args->sigData, args->sigDataSz,
  6555. args->verify + HASH_SIG_SIZE +
  6556. VERIFY_HEADER, (word32*)&sig->length,
  6557. (dilithium_key*)ssl->hsKey);
  6558. args->length = (word16)sig->length;
  6559. }
  6560. #endif
  6561. #endif /* HAVE_PQC */
  6562. #ifndef NO_RSA
  6563. if (ssl->hsType == DYNAMIC_TYPE_RSA) {
  6564. ret = RsaSign(ssl, sig->buffer, (word32)sig->length,
  6565. args->verify + HASH_SIG_SIZE + VERIFY_HEADER, &args->sigLen,
  6566. args->sigAlgo, ssl->suites->hashAlgo,
  6567. (RsaKey*)ssl->hsKey,
  6568. ssl->buffers.key
  6569. );
  6570. if (ret == 0) {
  6571. args->length = (word16)args->sigLen;
  6572. XMEMCPY(args->sigData,
  6573. args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
  6574. args->sigLen);
  6575. }
  6576. }
  6577. #endif /* !NO_RSA */
  6578. /* Check for error */
  6579. if (ret != 0) {
  6580. goto exit_scv;
  6581. }
  6582. /* Add signature length. */
  6583. c16toa(args->length, args->verify + HASH_SIG_SIZE);
  6584. /* Advance state and proceed */
  6585. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  6586. } /* case TLS_ASYNC_DO */
  6587. FALL_THROUGH;
  6588. case TLS_ASYNC_VERIFY:
  6589. {
  6590. #ifndef NO_RSA
  6591. if (ssl->hsType == DYNAMIC_TYPE_RSA) {
  6592. /* check for signature faults */
  6593. ret = VerifyRsaSign(ssl, args->sigData, args->sigLen,
  6594. sig->buffer, (word32)sig->length, args->sigAlgo,
  6595. ssl->suites->hashAlgo, (RsaKey*)ssl->hsKey,
  6596. ssl->buffers.key
  6597. );
  6598. }
  6599. #endif /* !NO_RSA */
  6600. /* Check for error */
  6601. if (ret != 0) {
  6602. goto exit_scv;
  6603. }
  6604. /* Advance state and proceed */
  6605. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  6606. } /* case TLS_ASYNC_VERIFY */
  6607. FALL_THROUGH;
  6608. case TLS_ASYNC_FINALIZE:
  6609. {
  6610. /* Put the record and handshake headers on. */
  6611. AddTls13Headers(args->output, args->length + HASH_SIG_SIZE +
  6612. VERIFY_HEADER, certificate_verify, ssl);
  6613. args->sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
  6614. args->length + HASH_SIG_SIZE + VERIFY_HEADER;
  6615. #ifdef WOLFSSL_DTLS13
  6616. if (ssl->options.dtls)
  6617. args->sendSz += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
  6618. #endif /* WOLFSSL_DTLS13 */
  6619. /* Advance state and proceed */
  6620. ssl->options.asyncState = TLS_ASYNC_END;
  6621. } /* case TLS_ASYNC_FINALIZE */
  6622. FALL_THROUGH;
  6623. case TLS_ASYNC_END:
  6624. {
  6625. #ifdef WOLFSSL_DTLS13
  6626. if (ssl->options.dtls) {
  6627. ssl->options.buildingMsg = 0;
  6628. ret = Dtls13HandshakeSend(ssl, args->output,
  6629. MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA + MAX_MSG_EXTRA,
  6630. args->sendSz, certificate_verify, 1);
  6631. if (ret != 0)
  6632. goto exit_scv;
  6633. break;
  6634. }
  6635. #endif /* WOLFSSL_DTLS13 */
  6636. /* This message is always encrypted. */
  6637. ret = BuildTls13Message(ssl, args->output,
  6638. MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA,
  6639. args->output + RECORD_HEADER_SZ,
  6640. args->sendSz - RECORD_HEADER_SZ, handshake,
  6641. 1, 0, 0);
  6642. if (ret < 0) {
  6643. goto exit_scv;
  6644. }
  6645. else {
  6646. args->sendSz = ret;
  6647. ret = 0;
  6648. }
  6649. #ifdef WOLFSSL_CALLBACKS
  6650. if (ssl->hsInfoOn)
  6651. AddPacketName(ssl, "CertificateVerify");
  6652. if (ssl->toInfoOn) {
  6653. AddPacketInfo(ssl, "CertificateVerify", handshake,
  6654. args->output, args->sendSz, WRITE_PROTO, ssl->heap);
  6655. }
  6656. #endif
  6657. ssl->buffers.outputBuffer.length += args->sendSz;
  6658. ssl->options.buildingMsg = 0;
  6659. if (!ssl->options.groupMessages)
  6660. ret = SendBuffered(ssl);
  6661. break;
  6662. }
  6663. default:
  6664. ret = INPUT_CASE_ERROR;
  6665. } /* switch(ssl->options.asyncState) */
  6666. exit_scv:
  6667. WOLFSSL_LEAVE("SendTls13CertificateVerify", ret);
  6668. WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_SEND);
  6669. #ifdef WOLFSSL_ASYNC_CRYPT
  6670. /* Handle async operation */
  6671. if (ret == WC_PENDING_E) {
  6672. return ret;
  6673. }
  6674. #endif /* WOLFSSL_ASYNC_CRYPT */
  6675. /* Final cleanup */
  6676. FreeScv13Args(ssl, args);
  6677. FreeKeyExchange(ssl);
  6678. #ifdef WOLFSSL_ASYNC_IO
  6679. /* Cleanup async */
  6680. FreeAsyncCtx(ssl, 0);
  6681. #endif
  6682. if (ret != 0) {
  6683. WOLFSSL_ERROR_VERBOSE(ret);
  6684. }
  6685. return ret;
  6686. }
  6687. #endif
  6688. #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */
  6689. #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  6690. /* handle processing TLS v1.3 certificate (11) */
  6691. /* Parse and handle a TLS v1.3 Certificate message.
  6692. *
  6693. * ssl The SSL/TLS object.
  6694. * input The message buffer.
  6695. * inOutIdx On entry, the index into the message buffer of Certificate.
  6696. * On exit, the index of byte after the Certificate message.
  6697. * totalSz The length of the current handshake message.
  6698. * returns 0 on success and otherwise failure.
  6699. */
  6700. static int DoTls13Certificate(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  6701. word32 totalSz)
  6702. {
  6703. int ret = 0;
  6704. WOLFSSL_START(WC_FUNC_CERTIFICATE_DO);
  6705. WOLFSSL_ENTER("DoTls13Certificate");
  6706. #ifdef WOLFSSL_DTLS13
  6707. if (ssl->options.dtls && ssl->options.handShakeDone) {
  6708. /* certificate needs some special care after the handshake */
  6709. ret = Dtls13RtxProcessingCertificate(
  6710. ssl, input + *inOutIdx, totalSz);
  6711. }
  6712. #endif /* WOLFSSL_DTLS13 */
  6713. if (ret == 0)
  6714. ret = ProcessPeerCerts(ssl, input, inOutIdx, totalSz);
  6715. if (ret == 0) {
  6716. #if !defined(NO_WOLFSSL_CLIENT)
  6717. if (ssl->options.side == WOLFSSL_CLIENT_END)
  6718. ssl->options.serverState = SERVER_CERT_COMPLETE;
  6719. #endif
  6720. #if !defined(NO_WOLFSSL_SERVER) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  6721. if (ssl->options.side == WOLFSSL_SERVER_END &&
  6722. ssl->options.handShakeState == HANDSHAKE_DONE) {
  6723. /* reset handshake states */
  6724. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  6725. ssl->options.acceptState = TICKET_SENT;
  6726. ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
  6727. }
  6728. #endif
  6729. }
  6730. WOLFSSL_LEAVE("DoTls13Certificate", ret);
  6731. WOLFSSL_END(WC_FUNC_CERTIFICATE_DO);
  6732. return ret;
  6733. }
  6734. #endif
  6735. #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  6736. defined(HAVE_ED448)
  6737. typedef struct Dcv13Args {
  6738. byte* output; /* not allocated */
  6739. word32 sendSz;
  6740. word16 sz;
  6741. word32 sigSz;
  6742. word32 idx;
  6743. word32 begin;
  6744. byte hashAlgo;
  6745. byte sigAlgo;
  6746. byte* sigData;
  6747. word16 sigDataSz;
  6748. } Dcv13Args;
  6749. static void FreeDcv13Args(WOLFSSL* ssl, void* pArgs)
  6750. {
  6751. Dcv13Args* args = (Dcv13Args*)pArgs;
  6752. if (args && args->sigData != NULL) {
  6753. XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  6754. args->sigData = NULL;
  6755. }
  6756. (void)ssl;
  6757. }
  6758. /* handle processing TLS v1.3 certificate_verify (15) */
  6759. /* Parse and handle a TLS v1.3 CertificateVerify message.
  6760. *
  6761. * ssl The SSL/TLS object.
  6762. * input The message buffer.
  6763. * inOutIdx On entry, the index into the message buffer of
  6764. * CertificateVerify.
  6765. * On exit, the index of byte after the CertificateVerify message.
  6766. * totalSz The length of the current handshake message.
  6767. * returns 0 on success and otherwise failure.
  6768. */
  6769. static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input,
  6770. word32* inOutIdx, word32 totalSz)
  6771. {
  6772. int ret = 0;
  6773. buffer* sig = &ssl->buffers.sig;
  6774. #ifdef WOLFSSL_ASYNC_CRYPT
  6775. Dcv13Args* args = NULL;
  6776. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  6777. #else
  6778. Dcv13Args args[1];
  6779. #endif
  6780. WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_DO);
  6781. WOLFSSL_ENTER("DoTls13CertificateVerify");
  6782. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  6783. ret = tsip_Tls13CertificateVerify(ssl, input, inOutIdx, totalSz);
  6784. if (ret != CRYPTOCB_UNAVAILABLE) {
  6785. goto exit_dcv;
  6786. }
  6787. ret = 0;
  6788. #endif
  6789. #ifdef WOLFSSL_ASYNC_CRYPT
  6790. if (ssl->async == NULL) {
  6791. ssl->async = (struct WOLFSSL_ASYNC*)
  6792. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  6793. DYNAMIC_TYPE_ASYNC);
  6794. if (ssl->async == NULL)
  6795. ERROR_OUT(MEMORY_E, exit_dcv);
  6796. }
  6797. args = (Dcv13Args*)ssl->async->args;
  6798. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  6799. if (ret != WC_NOT_PENDING_E) {
  6800. /* Check for error */
  6801. if (ret < 0)
  6802. goto exit_dcv;
  6803. }
  6804. else
  6805. #endif
  6806. {
  6807. /* Reset state */
  6808. ret = 0;
  6809. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  6810. XMEMSET(args, 0, sizeof(Dcv13Args));
  6811. args->hashAlgo = sha_mac;
  6812. args->sigAlgo = anonymous_sa_algo;
  6813. args->idx = *inOutIdx;
  6814. args->begin = *inOutIdx;
  6815. #ifdef WOLFSSL_ASYNC_CRYPT
  6816. ssl->async->freeArgs = FreeDcv13Args;
  6817. #endif
  6818. }
  6819. switch(ssl->options.asyncState)
  6820. {
  6821. case TLS_ASYNC_BEGIN:
  6822. {
  6823. #ifdef WOLFSSL_CALLBACKS
  6824. if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateVerify");
  6825. if (ssl->toInfoOn) AddLateName("CertificateVerify",
  6826. &ssl->timeoutInfo);
  6827. #endif
  6828. /* Advance state and proceed */
  6829. ssl->options.asyncState = TLS_ASYNC_BUILD;
  6830. } /* case TLS_ASYNC_BEGIN */
  6831. FALL_THROUGH;
  6832. case TLS_ASYNC_BUILD:
  6833. {
  6834. int validSigAlgo;
  6835. /* Signature algorithm. */
  6836. if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN > totalSz) {
  6837. ERROR_OUT(BUFFER_ERROR, exit_dcv);
  6838. }
  6839. ret = DecodeTls13SigAlg(input + args->idx, &args->hashAlgo,
  6840. &args->sigAlgo);
  6841. if (ret < 0)
  6842. goto exit_dcv;
  6843. args->idx += OPAQUE16_LEN;
  6844. /* Signature length. */
  6845. if ((args->idx - args->begin) + OPAQUE16_LEN > totalSz) {
  6846. ERROR_OUT(BUFFER_ERROR, exit_dcv);
  6847. }
  6848. ato16(input + args->idx, &args->sz);
  6849. args->idx += OPAQUE16_LEN;
  6850. /* Signature data. */
  6851. if ((args->idx - args->begin) + args->sz > totalSz ||
  6852. args->sz > ENCRYPT_LEN) {
  6853. ERROR_OUT(BUFFER_ERROR, exit_dcv);
  6854. }
  6855. /* Check for public key of required type. */
  6856. /* Assume invalid unless signature algo matches the key provided */
  6857. validSigAlgo = 0;
  6858. #ifdef HAVE_ED25519
  6859. if (args->sigAlgo == ed25519_sa_algo) {
  6860. WOLFSSL_MSG("Peer sent ED25519 sig");
  6861. validSigAlgo = (ssl->peerEd25519Key != NULL) &&
  6862. ssl->peerEd25519KeyPresent;
  6863. }
  6864. #endif
  6865. #ifdef HAVE_ED448
  6866. if (args->sigAlgo == ed448_sa_algo) {
  6867. WOLFSSL_MSG("Peer sent ED448 sig");
  6868. validSigAlgo = (ssl->peerEd448Key != NULL) &&
  6869. ssl->peerEd448KeyPresent;
  6870. }
  6871. #endif
  6872. #ifdef HAVE_ECC
  6873. if (args->sigAlgo == ecc_dsa_sa_algo) {
  6874. WOLFSSL_MSG("Peer sent ECC sig");
  6875. validSigAlgo = (ssl->peerEccDsaKey != NULL) &&
  6876. ssl->peerEccDsaKeyPresent;
  6877. }
  6878. #endif
  6879. #ifdef HAVE_PQC
  6880. if (args->sigAlgo == falcon_level1_sa_algo) {
  6881. WOLFSSL_MSG("Peer sent Falcon Level 1 sig");
  6882. validSigAlgo = (ssl->peerFalconKey != NULL) &&
  6883. ssl->peerFalconKeyPresent;
  6884. }
  6885. if (args->sigAlgo == falcon_level5_sa_algo) {
  6886. WOLFSSL_MSG("Peer sent Falcon Level 5 sig");
  6887. validSigAlgo = (ssl->peerFalconKey != NULL) &&
  6888. ssl->peerFalconKeyPresent;
  6889. }
  6890. if (args->sigAlgo == dilithium_level2_sa_algo) {
  6891. WOLFSSL_MSG("Peer sent Dilithium Level 2 sig");
  6892. validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
  6893. ssl->peerDilithiumKeyPresent;
  6894. }
  6895. if (args->sigAlgo == dilithium_level3_sa_algo) {
  6896. WOLFSSL_MSG("Peer sent Dilithium Level 3 sig");
  6897. validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
  6898. ssl->peerDilithiumKeyPresent;
  6899. }
  6900. if (args->sigAlgo == dilithium_level5_sa_algo) {
  6901. WOLFSSL_MSG("Peer sent Dilithium Level 5 sig");
  6902. validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
  6903. ssl->peerDilithiumKeyPresent;
  6904. }
  6905. if (args->sigAlgo == dilithium_aes_level2_sa_algo) {
  6906. WOLFSSL_MSG("Peer sent Dilithium AES Level 2 sig");
  6907. validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
  6908. ssl->peerDilithiumKeyPresent;
  6909. }
  6910. if (args->sigAlgo == dilithium_aes_level3_sa_algo) {
  6911. WOLFSSL_MSG("Peer sent Dilithium AES Level 3 sig");
  6912. validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
  6913. ssl->peerDilithiumKeyPresent;
  6914. }
  6915. if (args->sigAlgo == dilithium_aes_level5_sa_algo) {
  6916. WOLFSSL_MSG("Peer sent Dilithium AES Level 5 sig");
  6917. validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
  6918. ssl->peerDilithiumKeyPresent;
  6919. }
  6920. #endif
  6921. #ifndef NO_RSA
  6922. if (args->sigAlgo == rsa_sa_algo) {
  6923. WOLFSSL_MSG("Peer sent PKCS#1.5 algo - not valid TLS 1.3");
  6924. ERROR_OUT(INVALID_PARAMETER, exit_dcv);
  6925. }
  6926. if (args->sigAlgo == rsa_pss_sa_algo) {
  6927. WOLFSSL_MSG("Peer sent RSA sig");
  6928. validSigAlgo = (ssl->peerRsaKey != NULL) &&
  6929. ssl->peerRsaKeyPresent;
  6930. }
  6931. #endif
  6932. if (!validSigAlgo) {
  6933. WOLFSSL_MSG("Sig algo doesn't correspond to certficate");
  6934. ERROR_OUT(SIG_VERIFY_E, exit_dcv);
  6935. }
  6936. sig->buffer = (byte*)XMALLOC(args->sz, ssl->heap,
  6937. DYNAMIC_TYPE_SIGNATURE);
  6938. if (sig->buffer == NULL) {
  6939. ERROR_OUT(MEMORY_E, exit_dcv);
  6940. }
  6941. sig->length = args->sz;
  6942. XMEMCPY(sig->buffer, input + args->idx, args->sz);
  6943. #ifdef HAVE_ECC
  6944. if (ssl->peerEccDsaKeyPresent) {
  6945. WOLFSSL_MSG("Doing ECC peer cert verify");
  6946. args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
  6947. DYNAMIC_TYPE_SIGNATURE);
  6948. if (args->sigData == NULL) {
  6949. ERROR_OUT(MEMORY_E, exit_dcv);
  6950. }
  6951. ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
  6952. if (ret != 0)
  6953. goto exit_dcv;
  6954. ret = CreateECCEncodedSig(args->sigData,
  6955. args->sigDataSz, args->hashAlgo);
  6956. if (ret < 0)
  6957. goto exit_dcv;
  6958. args->sigDataSz = (word16)ret;
  6959. ret = 0;
  6960. }
  6961. #endif
  6962. #ifdef HAVE_ED25519
  6963. if (ssl->peerEd25519KeyPresent) {
  6964. WOLFSSL_MSG("Doing ED25519 peer cert verify");
  6965. args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
  6966. DYNAMIC_TYPE_SIGNATURE);
  6967. if (args->sigData == NULL) {
  6968. ERROR_OUT(MEMORY_E, exit_dcv);
  6969. }
  6970. CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
  6971. ret = 0;
  6972. }
  6973. #endif
  6974. #ifdef HAVE_ED448
  6975. if (ssl->peerEd448KeyPresent) {
  6976. WOLFSSL_MSG("Doing ED448 peer cert verify");
  6977. args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
  6978. DYNAMIC_TYPE_SIGNATURE);
  6979. if (args->sigData == NULL) {
  6980. ERROR_OUT(MEMORY_E, exit_dcv);
  6981. }
  6982. CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
  6983. ret = 0;
  6984. }
  6985. #endif
  6986. #ifdef HAVE_PQC
  6987. if (ssl->peerFalconKeyPresent) {
  6988. WOLFSSL_MSG("Doing Falcon peer cert verify");
  6989. args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
  6990. DYNAMIC_TYPE_SIGNATURE);
  6991. if (args->sigData == NULL) {
  6992. ERROR_OUT(MEMORY_E, exit_dcv);
  6993. }
  6994. CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
  6995. ret = 0;
  6996. }
  6997. if (ssl->peerDilithiumKeyPresent) {
  6998. WOLFSSL_MSG("Doing Dilithium peer cert verify");
  6999. args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
  7000. DYNAMIC_TYPE_SIGNATURE);
  7001. if (args->sigData == NULL) {
  7002. ERROR_OUT(MEMORY_E, exit_dcv);
  7003. }
  7004. CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
  7005. ret = 0;
  7006. }
  7007. #endif
  7008. /* Advance state and proceed */
  7009. ssl->options.asyncState = TLS_ASYNC_DO;
  7010. } /* case TLS_ASYNC_BUILD */
  7011. FALL_THROUGH;
  7012. case TLS_ASYNC_DO:
  7013. {
  7014. #ifndef NO_RSA
  7015. if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
  7016. ret = RsaVerify(ssl, sig->buffer, (word32)sig->length, &args->output,
  7017. args->sigAlgo, args->hashAlgo, ssl->peerRsaKey,
  7018. #ifdef HAVE_PK_CALLBACKS
  7019. &ssl->buffers.peerRsaKey
  7020. #else
  7021. NULL
  7022. #endif
  7023. );
  7024. if (ret >= 0) {
  7025. args->sendSz = ret;
  7026. ret = 0;
  7027. }
  7028. }
  7029. #endif /* !NO_RSA */
  7030. #ifdef HAVE_ECC
  7031. if (ssl->peerEccDsaKeyPresent) {
  7032. ret = EccVerify(ssl, input + args->idx, args->sz,
  7033. args->sigData, args->sigDataSz,
  7034. ssl->peerEccDsaKey,
  7035. #ifdef HAVE_PK_CALLBACKS
  7036. &ssl->buffers.peerEccDsaKey
  7037. #else
  7038. NULL
  7039. #endif
  7040. );
  7041. if (ret >= 0) {
  7042. /* CLIENT/SERVER: data verified with public key from
  7043. * certificate. */
  7044. ssl->options.peerAuthGood = 1;
  7045. FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
  7046. ssl->peerEccDsaKeyPresent = 0;
  7047. }
  7048. }
  7049. #endif /* HAVE_ECC */
  7050. #ifdef HAVE_ED25519
  7051. if (ssl->peerEd25519KeyPresent) {
  7052. ret = Ed25519Verify(ssl, input + args->idx, args->sz,
  7053. args->sigData, args->sigDataSz,
  7054. ssl->peerEd25519Key,
  7055. #ifdef HAVE_PK_CALLBACKS
  7056. &ssl->buffers.peerEd25519Key
  7057. #else
  7058. NULL
  7059. #endif
  7060. );
  7061. if (ret >= 0) {
  7062. /* CLIENT/SERVER: data verified with public key from
  7063. * certificate. */
  7064. ssl->options.peerAuthGood = 1;
  7065. FreeKey(ssl, DYNAMIC_TYPE_ED25519,
  7066. (void**)&ssl->peerEd25519Key);
  7067. ssl->peerEd25519KeyPresent = 0;
  7068. }
  7069. }
  7070. #endif
  7071. #ifdef HAVE_ED448
  7072. if (ssl->peerEd448KeyPresent) {
  7073. ret = Ed448Verify(ssl, input + args->idx, args->sz,
  7074. args->sigData, args->sigDataSz,
  7075. ssl->peerEd448Key,
  7076. #ifdef HAVE_PK_CALLBACKS
  7077. &ssl->buffers.peerEd448Key
  7078. #else
  7079. NULL
  7080. #endif
  7081. );
  7082. if (ret >= 0) {
  7083. /* CLIENT/SERVER: data verified with public key from
  7084. * certificate. */
  7085. ssl->options.peerAuthGood = 1;
  7086. FreeKey(ssl, DYNAMIC_TYPE_ED448,
  7087. (void**)&ssl->peerEd448Key);
  7088. ssl->peerEd448KeyPresent = 0;
  7089. }
  7090. }
  7091. #endif
  7092. #if defined(HAVE_PQC) && defined(HAVE_FALCON)
  7093. if (ssl->peerFalconKeyPresent) {
  7094. int res = 0;
  7095. WOLFSSL_MSG("Doing Falcon peer cert verify");
  7096. ret = wc_falcon_verify_msg(input + args->idx, args->sz,
  7097. args->sigData, args->sigDataSz,
  7098. &res, ssl->peerFalconKey);
  7099. if ((ret >= 0) && (res == 1)) {
  7100. /* CLIENT/SERVER: data verified with public key from
  7101. * certificate. */
  7102. ssl->options.peerAuthGood = 1;
  7103. FreeKey(ssl, DYNAMIC_TYPE_FALCON,
  7104. (void**)&ssl->peerFalconKey);
  7105. ssl->peerFalconKeyPresent = 0;
  7106. }
  7107. }
  7108. #endif /* HAVE_PQC && HAVE_FALCON */
  7109. #if defined(HAVE_PQC) && defined(HAVE_DILITHIUM)
  7110. if (ssl->peerDilithiumKeyPresent) {
  7111. int res = 0;
  7112. WOLFSSL_MSG("Doing Dilithium peer cert verify");
  7113. ret = wc_dilithium_verify_msg(input + args->idx, args->sz,
  7114. args->sigData, args->sigDataSz,
  7115. &res, ssl->peerDilithiumKey);
  7116. if ((ret >= 0) && (res == 1)) {
  7117. /* CLIENT/SERVER: data verified with public key from
  7118. * certificate. */
  7119. ssl->options.peerAuthGood = 1;
  7120. FreeKey(ssl, DYNAMIC_TYPE_DILITHIUM,
  7121. (void**)&ssl->peerDilithiumKey);
  7122. ssl->peerDilithiumKeyPresent = 0;
  7123. }
  7124. }
  7125. #endif /* HAVE_PQC && HAVE_DILITHIUM */
  7126. /* Check for error */
  7127. if (ret != 0) {
  7128. goto exit_dcv;
  7129. }
  7130. /* Advance state and proceed */
  7131. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  7132. } /* case TLS_ASYNC_DO */
  7133. FALL_THROUGH;
  7134. case TLS_ASYNC_VERIFY:
  7135. {
  7136. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  7137. if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
  7138. ret = CheckRSASignature(ssl, args->sigAlgo, args->hashAlgo,
  7139. args->output, args->sendSz);
  7140. if (ret != 0)
  7141. goto exit_dcv;
  7142. /* CLIENT/SERVER: data verified with public key from
  7143. * certificate. */
  7144. ssl->peerRsaKeyPresent = 0;
  7145. FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
  7146. ssl->options.peerAuthGood = 1;
  7147. }
  7148. #endif /* !NO_RSA && WC_RSA_PSS */
  7149. /* Advance state and proceed */
  7150. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  7151. } /* case TLS_ASYNC_VERIFY */
  7152. FALL_THROUGH;
  7153. case TLS_ASYNC_FINALIZE:
  7154. {
  7155. ssl->options.havePeerVerify = 1;
  7156. /* Set final index */
  7157. args->idx += args->sz;
  7158. *inOutIdx = args->idx;
  7159. /* Encryption is always on: add padding */
  7160. *inOutIdx += ssl->keys.padSz;
  7161. /* Advance state and proceed */
  7162. ssl->options.asyncState = TLS_ASYNC_END;
  7163. #if !defined(NO_WOLFSSL_CLIENT)
  7164. if (ssl->options.side == WOLFSSL_CLIENT_END)
  7165. ssl->options.serverState = SERVER_CERT_VERIFY_COMPLETE;
  7166. #endif
  7167. } /* case TLS_ASYNC_FINALIZE */
  7168. FALL_THROUGH;
  7169. case TLS_ASYNC_END:
  7170. {
  7171. break;
  7172. }
  7173. default:
  7174. ret = INPUT_CASE_ERROR;
  7175. } /* switch(ssl->options.asyncState) */
  7176. exit_dcv:
  7177. WOLFSSL_LEAVE("DoTls13CertificateVerify", ret);
  7178. WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_DO);
  7179. #ifdef WOLFSSL_ASYNC_CRYPT
  7180. /* Handle async operation */
  7181. if (ret == WC_PENDING_E) {
  7182. /* Mark message as not received so it can process again */
  7183. ssl->msgsReceived.got_certificate_verify = 0;
  7184. return ret;
  7185. }
  7186. else
  7187. #endif /* WOLFSSL_ASYNC_CRYPT */
  7188. if (ret != 0) {
  7189. WOLFSSL_ERROR_VERBOSE(ret);
  7190. if (ret != INVALID_PARAMETER) {
  7191. SendAlert(ssl, alert_fatal, decrypt_error);
  7192. }
  7193. }
  7194. /* Final cleanup */
  7195. FreeDcv13Args(ssl, args);
  7196. FreeKeyExchange(ssl);
  7197. #ifdef WOLFSSL_ASYNC_IO
  7198. /* Cleanup async */
  7199. FreeAsyncCtx(ssl, 0);
  7200. #endif
  7201. return ret;
  7202. }
  7203. #endif /* !NO_RSA || HAVE_ECC */
  7204. #endif /* !NO_CERTS */
  7205. /* Parse and handle a TLS v1.3 Finished message.
  7206. *
  7207. * ssl The SSL/TLS object.
  7208. * input The message buffer.
  7209. * inOutIdx On entry, the index into the message buffer of Finished.
  7210. * On exit, the index of byte after the Finished message and padding.
  7211. * size Length of message data.
  7212. * totalSz Length of remaining data in the message buffer.
  7213. * sniff Indicates whether we are sniffing packets.
  7214. * returns 0 on success and otherwise failure.
  7215. */
  7216. int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  7217. word32 size, word32 totalSz, int sniff)
  7218. {
  7219. int ret;
  7220. word32 finishedSz = 0;
  7221. byte* secret;
  7222. byte mac[WC_MAX_DIGEST_SIZE];
  7223. WOLFSSL_START(WC_FUNC_FINISHED_DO);
  7224. WOLFSSL_ENTER("DoTls13Finished");
  7225. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  7226. /* verify the client sent certificate if required */
  7227. if (ssl->options.side == WOLFSSL_SERVER_END && !ssl->options.resuming &&
  7228. (ssl->options.mutualAuth || ssl->options.failNoCert)) {
  7229. #ifdef OPENSSL_COMPATIBLE_DEFAULTS
  7230. if (ssl->options.isPSK) {
  7231. WOLFSSL_MSG("TLS v1.3 client used PSK but cert required. Allowing "
  7232. "for OpenSSL compatibility");
  7233. }
  7234. else
  7235. #endif
  7236. if (!ssl->options.havePeerCert || !ssl->options.havePeerVerify) {
  7237. ret = NO_PEER_CERT; /* NO_PEER_VERIFY */
  7238. WOLFSSL_MSG("TLS v1.3 client did not present peer cert");
  7239. DoCertFatalAlert(ssl, ret);
  7240. return ret;
  7241. }
  7242. }
  7243. #endif
  7244. /* check against totalSz */
  7245. if (*inOutIdx + size > totalSz)
  7246. return BUFFER_E;
  7247. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  7248. ret = tsip_Tls13HandleFinished(ssl, input, inOutIdx, size, totalSz);
  7249. if (ret == 0) {
  7250. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  7251. return ret;
  7252. }
  7253. if (ret == VERIFY_FINISHED_ERROR) {
  7254. SendAlert(ssl, alert_fatal, decrypt_error);
  7255. return ret;
  7256. }
  7257. if (ret != CRYPTOCB_UNAVAILABLE) {
  7258. /* other errors */
  7259. return ret;
  7260. }
  7261. ret = 0;
  7262. #endif /* WOLFSSL_RENESAS_TSIP_TLS && WOLFSSL_RENESAS_TSIP_VER >= 115 */
  7263. if (ssl->options.handShakeDone) {
  7264. ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
  7265. ssl->keys.client_write_MAC_secret);
  7266. if (ret != 0)
  7267. return ret;
  7268. secret = ssl->keys.client_write_MAC_secret;
  7269. }
  7270. else if (ssl->options.side == WOLFSSL_CLIENT_END) {
  7271. /* All the handshake messages have been received to calculate
  7272. * client and server finished keys.
  7273. */
  7274. ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
  7275. ssl->keys.client_write_MAC_secret);
  7276. if (ret != 0)
  7277. return ret;
  7278. ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
  7279. ssl->keys.server_write_MAC_secret);
  7280. if (ret != 0)
  7281. return ret;
  7282. secret = ssl->keys.server_write_MAC_secret;
  7283. }
  7284. else {
  7285. secret = ssl->keys.client_write_MAC_secret;
  7286. }
  7287. if (sniff == NO_SNIFF) {
  7288. ret = BuildTls13HandshakeHmac(ssl, secret, mac, &finishedSz);
  7289. #ifdef WOLFSSL_HAVE_TLS_UNIQUE
  7290. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  7291. XMEMCPY(ssl->serverFinished, mac, finishedSz);
  7292. ssl->serverFinished_len = finishedSz;
  7293. }
  7294. else {
  7295. XMEMCPY(ssl->clientFinished, mac, finishedSz);
  7296. ssl->clientFinished_len = finishedSz;
  7297. }
  7298. #endif /* WOLFSSL_HAVE_TLS_UNIQUE */
  7299. if (ret != 0)
  7300. return ret;
  7301. if (size != finishedSz)
  7302. return BUFFER_ERROR;
  7303. }
  7304. #ifdef WOLFSSL_CALLBACKS
  7305. if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
  7306. if (ssl->toInfoOn) AddLateName("Finished", &ssl->timeoutInfo);
  7307. #endif
  7308. if (sniff == NO_SNIFF) {
  7309. /* Actually check verify data. */
  7310. if (XMEMCMP(input + *inOutIdx, mac, size) != 0){
  7311. WOLFSSL_MSG("Verify finished error on hashes");
  7312. SendAlert(ssl, alert_fatal, decrypt_error);
  7313. WOLFSSL_ERROR_VERBOSE(VERIFY_FINISHED_ERROR);
  7314. return VERIFY_FINISHED_ERROR;
  7315. }
  7316. }
  7317. /* Force input exhaustion at ProcessReply by consuming padSz. */
  7318. *inOutIdx += size + ssl->keys.padSz;
  7319. if (ssl->options.side == WOLFSSL_SERVER_END &&
  7320. !ssl->options.handShakeDone) {
  7321. #ifdef WOLFSSL_EARLY_DATA
  7322. if (ssl->earlyData != no_early_data) {
  7323. if ((ret = DeriveTls13Keys(ssl, no_key, DECRYPT_SIDE_ONLY, 1)) != 0)
  7324. return ret;
  7325. }
  7326. #endif
  7327. /* Setup keys for application data messages from client. */
  7328. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  7329. return ret;
  7330. }
  7331. #ifndef NO_WOLFSSL_CLIENT
  7332. if (ssl->options.side == WOLFSSL_CLIENT_END)
  7333. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  7334. #endif
  7335. #ifndef NO_WOLFSSL_SERVER
  7336. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7337. ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
  7338. ssl->options.handShakeState = HANDSHAKE_DONE;
  7339. ssl->options.handShakeDone = 1;
  7340. }
  7341. #endif
  7342. #if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_EARLY_DATA)
  7343. if (ssl->options.dtls && ssl->earlyData > early_data_ext) {
  7344. /* DTLSv1.3 has no EndOfearlydata messages. We stop processing EarlyData
  7345. as soon we receive the client's finished message */
  7346. ssl->earlyData = done_early_data;
  7347. }
  7348. #endif /* WOLFSSL_DTLS13 && WOLFSSL_EARLY_DATA */
  7349. #if defined(WOLFSSL_QUIC) && defined(WOLFSSL_EARLY_DATA)
  7350. if (WOLFSSL_IS_QUIC(ssl) && ssl->earlyData > early_data_ext) {
  7351. /* QUIC has no EndOfEarlyData messages. We stop processing EarlyData
  7352. as soon we receive the client's finished message */
  7353. ssl->earlyData = done_early_data;
  7354. }
  7355. #endif /* WOLFSSL_QUIC && WOLFSSL_EARLY_DATA */
  7356. WOLFSSL_LEAVE("DoTls13Finished", 0);
  7357. WOLFSSL_END(WC_FUNC_FINISHED_DO);
  7358. return 0;
  7359. }
  7360. #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
  7361. /* Send the TLS v1.3 Finished message.
  7362. *
  7363. * ssl The SSL/TLS object.
  7364. * returns 0 on success, otherwise failure.
  7365. */
  7366. static int SendTls13Finished(WOLFSSL* ssl)
  7367. {
  7368. int sendSz;
  7369. int finishedSz = ssl->specs.hash_size;
  7370. byte* input;
  7371. byte* output;
  7372. int ret;
  7373. int headerSz = HANDSHAKE_HEADER_SZ;
  7374. int outputSz;
  7375. byte* secret;
  7376. #ifdef WOLFSSL_DTLS13
  7377. int dtlsRet = 0, isDtls = 0;
  7378. #endif /* WOLFSSL_DTLS13 */
  7379. WOLFSSL_START(WC_FUNC_FINISHED_SEND);
  7380. WOLFSSL_ENTER("SendTls13Finished");
  7381. ssl->options.buildingMsg = 1;
  7382. #ifdef WOLFSSL_DTLS13
  7383. if (ssl->options.dtls) {
  7384. headerSz = DTLS_HANDSHAKE_HEADER_SZ;
  7385. /* using isDtls instead of ssl->options.dtls will abide clang static
  7386. analyzer on unsing an uninitialized value */
  7387. isDtls = 1;
  7388. }
  7389. #endif /* WOLFSSL_DTLS13 */
  7390. outputSz = WC_MAX_DIGEST_SIZE + DTLS_HANDSHAKE_HEADER_SZ + MAX_MSG_EXTRA;
  7391. /* Check buffers are big enough and grow if needed. */
  7392. if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
  7393. return ret;
  7394. /* get output buffer */
  7395. output = ssl->buffers.outputBuffer.buffer +
  7396. ssl->buffers.outputBuffer.length;
  7397. input = output + RECORD_HEADER_SZ;
  7398. #ifdef WOLFSSL_DTLS13
  7399. if (isDtls)
  7400. input = output + Dtls13GetRlHeaderLength(1);
  7401. #endif /* WOLFSSL_DTLS13 */
  7402. AddTls13HandShakeHeader(input, finishedSz, 0, finishedSz, finished, ssl);
  7403. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
  7404. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  7405. ret = tsip_Tls13SendFinished(ssl, output, outputSz, input, 1);
  7406. if (ret != CRYPTOCB_UNAVAILABLE) {
  7407. return ret;
  7408. }
  7409. ret = 0;
  7410. }
  7411. #endif /* WOLFSSL_RENESAS_TSIP_TLS && WOLFSSL_RENESAS_TSIP_VER >= 115 */
  7412. /* make finished hashes */
  7413. if (ssl->options.handShakeDone) {
  7414. ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
  7415. ssl->keys.client_write_MAC_secret);
  7416. if (ret != 0)
  7417. return ret;
  7418. secret = ssl->keys.client_write_MAC_secret;
  7419. }
  7420. else if (ssl->options.side == WOLFSSL_CLIENT_END)
  7421. secret = ssl->keys.client_write_MAC_secret;
  7422. else {
  7423. /* All the handshake messages have been done to calculate client and
  7424. * server finished keys.
  7425. */
  7426. ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
  7427. ssl->keys.client_write_MAC_secret);
  7428. if (ret != 0)
  7429. return ret;
  7430. ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
  7431. ssl->keys.server_write_MAC_secret);
  7432. if (ret != 0)
  7433. return ret;
  7434. secret = ssl->keys.server_write_MAC_secret;
  7435. }
  7436. ret = BuildTls13HandshakeHmac(ssl, secret, &input[headerSz], NULL);
  7437. if (ret != 0)
  7438. return ret;
  7439. #ifdef WOLFSSL_HAVE_TLS_UNIQUE
  7440. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  7441. XMEMCPY(ssl->clientFinished, &input[headerSz], finishedSz);
  7442. ssl->clientFinished_len = finishedSz;
  7443. }
  7444. else {
  7445. XMEMCPY(ssl->serverFinished, &input[headerSz], finishedSz);
  7446. ssl->serverFinished_len = finishedSz;
  7447. }
  7448. #endif /* WOLFSSL_HAVE_TLS_UNIQUE */
  7449. #ifdef WOLFSSL_DTLS13
  7450. if (isDtls) {
  7451. dtlsRet = Dtls13HandshakeSend(ssl, output, outputSz,
  7452. Dtls13GetRlHeaderLength(1) + headerSz + finishedSz, finished, 1);
  7453. if (dtlsRet != 0 && dtlsRet != WANT_WRITE)
  7454. return ret;
  7455. } else
  7456. #endif /* WOLFSSL_DTLS13 */
  7457. {
  7458. /* This message is always encrypted. */
  7459. sendSz = BuildTls13Message(ssl, output, outputSz, input,
  7460. headerSz + finishedSz, handshake, 1, 0, 0);
  7461. if (sendSz < 0) {
  7462. WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR);
  7463. return BUILD_MSG_ERROR;
  7464. }
  7465. #ifdef WOLFSSL_CALLBACKS
  7466. if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
  7467. if (ssl->toInfoOn) {
  7468. AddPacketInfo(ssl, "Finished", handshake, output, sendSz,
  7469. WRITE_PROTO, ssl->heap);
  7470. }
  7471. #endif
  7472. ssl->buffers.outputBuffer.length += sendSz;
  7473. ssl->options.buildingMsg = 0;
  7474. }
  7475. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7476. #ifdef WOLFSSL_EARLY_DATA
  7477. byte storeTrafficDecKeys = ssl->earlyData == no_early_data;
  7478. #endif
  7479. /* Can send application data now. */
  7480. if ((ret = DeriveMasterSecret(ssl)) != 0)
  7481. return ret;
  7482. /* Last use of preMasterSecret - zeroize as soon as possible. */
  7483. ForceZero(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  7484. #ifdef WOLFSSL_EARLY_DATA
  7485. #ifdef WOLFSSL_DTLS13
  7486. /* DTLS13 dynamically change keys and it needs all
  7487. the keys in ssl->keys to save the keying material */
  7488. if (isDtls)
  7489. storeTrafficDecKeys = 1;
  7490. #endif /* WOLFSSL_DTLS13 */
  7491. if ((ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_SIDE_ONLY, 1))
  7492. != 0) {
  7493. return ret;
  7494. }
  7495. if ((ret = DeriveTls13Keys(ssl, traffic_key, DECRYPT_SIDE_ONLY,
  7496. storeTrafficDecKeys)) != 0) {
  7497. return ret;
  7498. }
  7499. #else
  7500. if ((ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_AND_DECRYPT_SIDE,
  7501. 1)) != 0) {
  7502. return ret;
  7503. }
  7504. #endif
  7505. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  7506. return ret;
  7507. #ifdef WOLFSSL_DTLS13
  7508. if (isDtls) {
  7509. w64wrapper epochTraffic0;
  7510. epochTraffic0 = w64From32(0, DTLS13_EPOCH_TRAFFIC0);
  7511. ssl->dtls13Epoch = epochTraffic0;
  7512. ssl->dtls13PeerEpoch = epochTraffic0;
  7513. ret = Dtls13NewEpoch(
  7514. ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
  7515. if (ret != 0)
  7516. return ret;
  7517. ret = Dtls13SetEpochKeys(
  7518. ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
  7519. if (ret != 0)
  7520. return ret;
  7521. }
  7522. #endif /* WOLFSSL_DTLS13 */
  7523. }
  7524. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  7525. !ssl->options.handShakeDone) {
  7526. #ifdef WOLFSSL_EARLY_DATA
  7527. if (ssl->earlyData != no_early_data) {
  7528. if ((ret = DeriveTls13Keys(ssl, no_key, ENCRYPT_AND_DECRYPT_SIDE,
  7529. 1)) != 0) {
  7530. return ret;
  7531. }
  7532. }
  7533. #endif
  7534. /* Setup keys for application data messages. */
  7535. if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0)
  7536. return ret;
  7537. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  7538. ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret);
  7539. if (ret != 0)
  7540. return ret;
  7541. #endif
  7542. #ifdef WOLFSSL_DTLS13
  7543. if (isDtls) {
  7544. w64wrapper epochTraffic0;
  7545. epochTraffic0 = w64From32(0, DTLS13_EPOCH_TRAFFIC0);
  7546. ssl->dtls13Epoch = epochTraffic0;
  7547. ssl->dtls13PeerEpoch = epochTraffic0;
  7548. ret = Dtls13NewEpoch(
  7549. ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
  7550. if (ret != 0)
  7551. return ret;
  7552. ret = Dtls13SetEpochKeys(
  7553. ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
  7554. if (ret != 0)
  7555. return ret;
  7556. }
  7557. #endif /* WOLFSSL_DTLS13 */
  7558. }
  7559. #ifndef NO_WOLFSSL_CLIENT
  7560. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  7561. ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
  7562. ssl->options.handShakeState = HANDSHAKE_DONE;
  7563. ssl->options.handShakeDone = 1;
  7564. }
  7565. #endif
  7566. #ifndef NO_WOLFSSL_SERVER
  7567. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7568. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  7569. }
  7570. #endif
  7571. #ifdef WOLFSSL_DTLS13
  7572. if (isDtls) {
  7573. WOLFSSL_LEAVE("SendTls13Finished", ret);
  7574. WOLFSSL_END(WC_FUNC_FINISHED_SEND);
  7575. return dtlsRet;
  7576. }
  7577. #endif /* WOLFSSL_DTLS13 */
  7578. if ((ret = SendBuffered(ssl)) != 0)
  7579. return ret;
  7580. WOLFSSL_LEAVE("SendTls13Finished", ret);
  7581. WOLFSSL_END(WC_FUNC_FINISHED_SEND);
  7582. return ret;
  7583. }
  7584. #endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */
  7585. /* handle generation TLS v1.3 key_update (24) */
  7586. /* Send the TLS v1.3 KeyUpdate message.
  7587. *
  7588. * ssl The SSL/TLS object.
  7589. * returns 0 on success, otherwise failure.
  7590. */
  7591. static int SendTls13KeyUpdate(WOLFSSL* ssl)
  7592. {
  7593. int sendSz;
  7594. byte* input;
  7595. byte* output;
  7596. int ret;
  7597. int headerSz = HANDSHAKE_HEADER_SZ;
  7598. int outputSz;
  7599. word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  7600. WOLFSSL_START(WC_FUNC_KEY_UPDATE_SEND);
  7601. WOLFSSL_ENTER("SendTls13KeyUpdate");
  7602. #ifdef WOLFSSL_DTLS13
  7603. if (ssl->options.dtls)
  7604. i = Dtls13GetRlHeaderLength(1) + DTLS_HANDSHAKE_HEADER_SZ;
  7605. #endif /* WOLFSSL_DTLS13 */
  7606. outputSz = OPAQUE8_LEN + MAX_MSG_EXTRA;
  7607. /* Check buffers are big enough and grow if needed. */
  7608. if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
  7609. return ret;
  7610. /* get output buffer */
  7611. output = ssl->buffers.outputBuffer.buffer +
  7612. ssl->buffers.outputBuffer.length;
  7613. input = output + RECORD_HEADER_SZ;
  7614. #ifdef WOLFSSL_DTLS13
  7615. if (ssl->options.dtls)
  7616. input = output + Dtls13GetRlHeaderLength(1);
  7617. #endif /* WOLFSSL_DTLS13 */
  7618. AddTls13Headers(output, OPAQUE8_LEN, key_update, ssl);
  7619. /* If:
  7620. * 1. I haven't sent a KeyUpdate requesting a response and
  7621. * 2. This isn't responding to peer KeyUpdate requiring a response then,
  7622. * I want a response.
  7623. */
  7624. ssl->keys.updateResponseReq = output[i++] =
  7625. !ssl->keys.updateResponseReq && !ssl->keys.keyUpdateRespond;
  7626. /* Sent response, no longer need to respond. */
  7627. ssl->keys.keyUpdateRespond = 0;
  7628. #ifdef WOLFSSL_DTLS13
  7629. if (ssl->options.dtls) {
  7630. ret = Dtls13HandshakeSend(ssl, output, outputSz,
  7631. OPAQUE8_LEN + Dtls13GetRlHeaderLength(1) + DTLS_HANDSHAKE_HEADER_SZ,
  7632. key_update, 0);
  7633. }
  7634. else
  7635. #endif /* WOLFSSL_DTLS13 */
  7636. {
  7637. /* This message is always encrypted. */
  7638. sendSz = BuildTls13Message(ssl, output, outputSz, input,
  7639. headerSz + OPAQUE8_LEN, handshake, 0, 0, 0);
  7640. if (sendSz < 0)
  7641. return BUILD_MSG_ERROR;
  7642. #ifdef WOLFSSL_CALLBACKS
  7643. if (ssl->hsInfoOn) AddPacketName(ssl, "KeyUpdate");
  7644. if (ssl->toInfoOn) {
  7645. AddPacketInfo(ssl, "KeyUpdate", handshake, output, sendSz,
  7646. WRITE_PROTO, ssl->heap);
  7647. }
  7648. #endif
  7649. ssl->buffers.outputBuffer.length += sendSz;
  7650. ret = SendBuffered(ssl);
  7651. if (ret != 0 && ret != WANT_WRITE)
  7652. return ret;
  7653. }
  7654. /* In DTLS we must wait for the ack before setting up the new keys */
  7655. if (!ssl->options.dtls) {
  7656. /* Future traffic uses new encryption keys. */
  7657. if ((ret = DeriveTls13Keys(
  7658. ssl, update_traffic_key, ENCRYPT_SIDE_ONLY, 1))
  7659. != 0)
  7660. return ret;
  7661. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  7662. return ret;
  7663. }
  7664. WOLFSSL_LEAVE("SendTls13KeyUpdate", ret);
  7665. WOLFSSL_END(WC_FUNC_KEY_UPDATE_SEND);
  7666. return ret;
  7667. }
  7668. /* handle processing TLS v1.3 key_update (24) */
  7669. /* Parse and handle a TLS v1.3 KeyUpdate message.
  7670. *
  7671. * ssl The SSL/TLS object.
  7672. * input The message buffer.
  7673. * inOutIdx On entry, the index into the message buffer of Finished.
  7674. * On exit, the index of byte after the Finished message and padding.
  7675. * totalSz The length of the current handshake message.
  7676. * returns 0 on success and otherwise failure.
  7677. */
  7678. static int DoTls13KeyUpdate(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  7679. word32 totalSz)
  7680. {
  7681. int ret;
  7682. word32 i = *inOutIdx;
  7683. WOLFSSL_START(WC_FUNC_KEY_UPDATE_DO);
  7684. WOLFSSL_ENTER("DoTls13KeyUpdate");
  7685. /* check against totalSz */
  7686. if (OPAQUE8_LEN != totalSz)
  7687. return BUFFER_E;
  7688. switch (input[i]) {
  7689. case update_not_requested:
  7690. /* This message in response to any outstanding request. */
  7691. ssl->keys.keyUpdateRespond = 0;
  7692. ssl->keys.updateResponseReq = 0;
  7693. break;
  7694. case update_requested:
  7695. /* New key update requiring a response. */
  7696. ssl->keys.keyUpdateRespond = 1;
  7697. break;
  7698. default:
  7699. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  7700. return INVALID_PARAMETER;
  7701. }
  7702. /* Move index to byte after message. */
  7703. *inOutIdx += totalSz;
  7704. /* Always encrypted. */
  7705. *inOutIdx += ssl->keys.padSz;
  7706. /* Future traffic uses new decryption keys. */
  7707. if ((ret = DeriveTls13Keys(ssl, update_traffic_key, DECRYPT_SIDE_ONLY, 1))
  7708. != 0) {
  7709. return ret;
  7710. }
  7711. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  7712. return ret;
  7713. #ifdef WOLFSSL_DTLS13
  7714. if (ssl->options.dtls) {
  7715. w64Increment(&ssl->dtls13PeerEpoch);
  7716. ret = Dtls13NewEpoch(ssl, ssl->dtls13PeerEpoch, DECRYPT_SIDE_ONLY);
  7717. if (ret != 0)
  7718. return ret;
  7719. ret = Dtls13SetEpochKeys(ssl, ssl->dtls13PeerEpoch, DECRYPT_SIDE_ONLY);
  7720. if (ret != 0)
  7721. return ret;
  7722. }
  7723. #endif /* WOLFSSL_DTLS13 */
  7724. if (ssl->keys.keyUpdateRespond) {
  7725. #ifdef WOLFSSL_DTLS13
  7726. /* we already sent a keyUpdate (either in response to a previous
  7727. KeyUpdate or initiated by the application) and we are waiting for the
  7728. ack. We can't send a new KeyUpdate right away but to honor the RFC we
  7729. should send another KeyUpdate after the one in-flight is acked. We
  7730. don't do that as it looks redundant, it will make the code more
  7731. complex and I don't see a good use case for that. */
  7732. if (ssl->options.dtls && ssl->dtls13WaitKeyUpdateAck) {
  7733. ssl->keys.keyUpdateRespond = 0;
  7734. return 0;
  7735. }
  7736. #endif /* WOLFSSL_DTLS13 */
  7737. return SendTls13KeyUpdate(ssl);
  7738. }
  7739. WOLFSSL_LEAVE("DoTls13KeyUpdate", ret);
  7740. WOLFSSL_END(WC_FUNC_KEY_UPDATE_DO);
  7741. return 0;
  7742. }
  7743. #ifdef WOLFSSL_EARLY_DATA
  7744. #ifndef NO_WOLFSSL_CLIENT
  7745. /* Send the TLS v1.3 EndOfEarlyData message to indicate that there will be no
  7746. * more early application data.
  7747. * The encryption key now changes to the pre-calculated handshake key.
  7748. *
  7749. * ssl The SSL/TLS object.
  7750. * returns 0 on success and otherwise failure.
  7751. */
  7752. static int SendTls13EndOfEarlyData(WOLFSSL* ssl)
  7753. {
  7754. byte* output;
  7755. int ret;
  7756. int sendSz;
  7757. word32 length;
  7758. word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  7759. WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_SEND);
  7760. WOLFSSL_ENTER("SendTls13EndOfEarlyData");
  7761. length = 0;
  7762. sendSz = idx + length + MAX_MSG_EXTRA;
  7763. ssl->options.buildingMsg = 1;
  7764. /* Check buffers are big enough and grow if needed. */
  7765. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  7766. return ret;
  7767. /* Get position in output buffer to write new message to. */
  7768. output = ssl->buffers.outputBuffer.buffer +
  7769. ssl->buffers.outputBuffer.length;
  7770. /* Put the record and handshake headers on. */
  7771. AddTls13Headers(output, length, end_of_early_data, ssl);
  7772. /* This message is always encrypted. */
  7773. sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
  7774. idx - RECORD_HEADER_SZ, handshake, 1, 0, 0);
  7775. if (sendSz < 0)
  7776. return sendSz;
  7777. ssl->buffers.outputBuffer.length += sendSz;
  7778. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  7779. return ret;
  7780. ssl->options.buildingMsg = 0;
  7781. if (!ssl->options.groupMessages)
  7782. ret = SendBuffered(ssl);
  7783. WOLFSSL_LEAVE("SendTls13EndOfEarlyData", ret);
  7784. WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_SEND);
  7785. return ret;
  7786. }
  7787. #endif /* !NO_WOLFSSL_CLIENT */
  7788. #ifndef NO_WOLFSSL_SERVER
  7789. /* handle processing of TLS 1.3 end_of_early_data (5) */
  7790. /* Parse the TLS v1.3 EndOfEarlyData message that indicates that there will be
  7791. * no more early application data.
  7792. * The decryption key now changes to the pre-calculated handshake key.
  7793. *
  7794. * ssl The SSL/TLS object.
  7795. * returns 0 on success and otherwise failure.
  7796. */
  7797. static int DoTls13EndOfEarlyData(WOLFSSL* ssl, const byte* input,
  7798. word32* inOutIdx, word32 size)
  7799. {
  7800. int ret;
  7801. word32 begin = *inOutIdx;
  7802. (void)input;
  7803. WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_DO);
  7804. WOLFSSL_ENTER("DoTls13EndOfEarlyData");
  7805. if ((*inOutIdx - begin) != size)
  7806. return BUFFER_ERROR;
  7807. if (ssl->earlyData == no_early_data) {
  7808. WOLFSSL_MSG("EndOfEarlyData received unexpectedly");
  7809. SendAlert(ssl, alert_fatal, unexpected_message);
  7810. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  7811. return OUT_OF_ORDER_E;
  7812. }
  7813. ssl->earlyData = done_early_data;
  7814. /* Always encrypted. */
  7815. *inOutIdx += ssl->keys.padSz;
  7816. ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY);
  7817. WOLFSSL_LEAVE("DoTls13EndOfEarlyData", ret);
  7818. WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_DO);
  7819. return ret;
  7820. }
  7821. #endif /* !NO_WOLFSSL_SERVER */
  7822. #endif /* WOLFSSL_EARLY_DATA */
  7823. #ifndef NO_WOLFSSL_CLIENT
  7824. /* Handle a New Session Ticket handshake message.
  7825. * Message contains the information required to perform resumption.
  7826. *
  7827. * ssl The SSL/TLS object.
  7828. * input The message buffer.
  7829. * inOutIdx On entry, the index into the message buffer of Finished.
  7830. * On exit, the index of byte after the Finished message and padding.
  7831. * size The length of the current handshake message.
  7832. * returns 0 on success, otherwise failure.
  7833. */
  7834. static int DoTls13NewSessionTicket(WOLFSSL* ssl, const byte* input,
  7835. word32* inOutIdx, word32 size)
  7836. {
  7837. #ifdef HAVE_SESSION_TICKET
  7838. int ret;
  7839. word32 begin = *inOutIdx;
  7840. word32 lifetime;
  7841. word32 ageAdd;
  7842. word16 length;
  7843. word32 now;
  7844. const byte* nonce;
  7845. byte nonceLength;
  7846. WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_DO);
  7847. WOLFSSL_ENTER("DoTls13NewSessionTicket");
  7848. /* Lifetime hint. */
  7849. if ((*inOutIdx - begin) + SESSION_HINT_SZ > size)
  7850. return BUFFER_ERROR;
  7851. ato32(input + *inOutIdx, &lifetime);
  7852. *inOutIdx += SESSION_HINT_SZ;
  7853. if (lifetime > MAX_LIFETIME) {
  7854. WOLFSSL_ERROR_VERBOSE(SERVER_HINT_ERROR);
  7855. return SERVER_HINT_ERROR;
  7856. }
  7857. /* Age add. */
  7858. if ((*inOutIdx - begin) + SESSION_ADD_SZ > size)
  7859. return BUFFER_ERROR;
  7860. ato32(input + *inOutIdx, &ageAdd);
  7861. *inOutIdx += SESSION_ADD_SZ;
  7862. /* Ticket nonce. */
  7863. if ((*inOutIdx - begin) + 1 > size)
  7864. return BUFFER_ERROR;
  7865. nonceLength = input[*inOutIdx];
  7866. if (nonceLength > MAX_TICKET_NONCE_SZ) {
  7867. WOLFSSL_MSG("Nonce length not supported");
  7868. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  7869. return INVALID_PARAMETER;
  7870. }
  7871. *inOutIdx += 1;
  7872. if ((*inOutIdx - begin) + nonceLength > size)
  7873. return BUFFER_ERROR;
  7874. nonce = input + *inOutIdx;
  7875. *inOutIdx += nonceLength;
  7876. /* Ticket length. */
  7877. if ((*inOutIdx - begin) + LENGTH_SZ > size)
  7878. return BUFFER_ERROR;
  7879. ato16(input + *inOutIdx, &length);
  7880. *inOutIdx += LENGTH_SZ;
  7881. if ((*inOutIdx - begin) + length > size)
  7882. return BUFFER_ERROR;
  7883. if ((ret = SetTicket(ssl, input + *inOutIdx, length)) != 0)
  7884. return ret;
  7885. *inOutIdx += length;
  7886. now = TimeNowInMilliseconds();
  7887. if (now == (word32)GETTIME_ERROR)
  7888. return now;
  7889. /* Copy in ticket data (server identity). */
  7890. ssl->timeout = lifetime;
  7891. ssl->session->timeout = lifetime;
  7892. ssl->session->cipherSuite0 = ssl->options.cipherSuite0;
  7893. ssl->session->cipherSuite = ssl->options.cipherSuite;
  7894. ssl->session->ticketSeen = now;
  7895. ssl->session->ticketAdd = ageAdd;
  7896. #ifdef WOLFSSL_EARLY_DATA
  7897. ssl->session->maxEarlyDataSz = ssl->options.maxEarlyDataSz;
  7898. #endif
  7899. ssl->session->ticketNonce.len = nonceLength;
  7900. if (nonceLength > 0)
  7901. XMEMCPY(&ssl->session->ticketNonce.data, nonce, nonceLength);
  7902. ssl->session->namedGroup = ssl->namedGroup;
  7903. if ((*inOutIdx - begin) + EXTS_SZ > size)
  7904. return BUFFER_ERROR;
  7905. ato16(input + *inOutIdx, &length);
  7906. *inOutIdx += EXTS_SZ;
  7907. if ((*inOutIdx - begin) + length != size)
  7908. return BUFFER_ERROR;
  7909. #ifdef WOLFSSL_EARLY_DATA
  7910. ret = TLSX_Parse(ssl, (byte *)input + (*inOutIdx), length, session_ticket,
  7911. NULL);
  7912. if (ret != 0)
  7913. return ret;
  7914. #endif
  7915. *inOutIdx += length;
  7916. #ifndef NO_SESSION_CACHE
  7917. AddSession(ssl);
  7918. #endif
  7919. /* Always encrypted. */
  7920. *inOutIdx += ssl->keys.padSz;
  7921. ssl->expect_session_ticket = 0;
  7922. #else
  7923. (void)ssl;
  7924. (void)input;
  7925. WOLFSSL_ENTER("DoTls13NewSessionTicket");
  7926. *inOutIdx += size + ssl->keys.padSz;
  7927. #endif /* HAVE_SESSION_TICKET */
  7928. WOLFSSL_LEAVE("DoTls13NewSessionTicket", 0);
  7929. WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_DO);
  7930. return 0;
  7931. }
  7932. #endif /* NO_WOLFSSL_CLIENT */
  7933. #ifndef NO_WOLFSSL_SERVER
  7934. #ifdef HAVE_SESSION_TICKET
  7935. #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
  7936. /* Offset of the MAC size in the finished message. */
  7937. #define FINISHED_MSG_SIZE_OFFSET 3
  7938. /* Calculate the resumption secret which includes the unseen client finished
  7939. * message.
  7940. *
  7941. * ssl The SSL/TLS object.
  7942. * returns 0 on success, otherwise failure.
  7943. */
  7944. static int ExpectedResumptionSecret(WOLFSSL* ssl)
  7945. {
  7946. int ret;
  7947. word32 finishedSz = 0;
  7948. byte mac[WC_MAX_DIGEST_SIZE];
  7949. Digest digest;
  7950. static byte header[] = { 0x14, 0x00, 0x00, 0x00 };
  7951. /* Copy the running hash so we can restore it after. */
  7952. switch (ssl->specs.mac_algorithm) {
  7953. #ifndef NO_SHA256
  7954. case sha256_mac:
  7955. ret = wc_Sha256Copy(&ssl->hsHashes->hashSha256, &digest.sha256);
  7956. if (ret != 0)
  7957. return ret;
  7958. break;
  7959. #endif
  7960. #ifdef WOLFSSL_SHA384
  7961. case sha384_mac:
  7962. ret = wc_Sha384Copy(&ssl->hsHashes->hashSha384, &digest.sha384);
  7963. if (ret != 0)
  7964. return ret;
  7965. break;
  7966. #endif
  7967. #ifdef WOLFSSL_TLS13_SHA512
  7968. case sha512_mac:
  7969. ret = wc_Sha512Copy(&ssl->hsHashes->hashSha512, &digest.sha512);
  7970. if (ret != 0)
  7971. return ret;
  7972. break;
  7973. #endif
  7974. }
  7975. /* Generate the Client's Finished message and hash it. */
  7976. ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret, mac,
  7977. &finishedSz);
  7978. if (ret != 0)
  7979. return ret;
  7980. header[FINISHED_MSG_SIZE_OFFSET] = finishedSz;
  7981. #ifdef WOLFSSL_EARLY_DATA
  7982. if (ssl->earlyData != no_early_data) {
  7983. static byte endOfEarlyData[] = { 0x05, 0x00, 0x00, 0x00 };
  7984. ret = HashRaw(ssl, endOfEarlyData, sizeof(endOfEarlyData));
  7985. if (ret != 0)
  7986. return ret;
  7987. }
  7988. #endif
  7989. if ((ret = HashRaw(ssl, header, sizeof(header))) != 0)
  7990. return ret;
  7991. if ((ret = HashRaw(ssl, mac, finishedSz)) != 0)
  7992. return ret;
  7993. if ((ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret)) != 0)
  7994. return ret;
  7995. /* Restore the hash inline with currently seen messages. */
  7996. switch (ssl->specs.mac_algorithm) {
  7997. #ifndef NO_SHA256
  7998. case sha256_mac:
  7999. wc_Sha256Free(&ssl->hsHashes->hashSha256);
  8000. ret = wc_Sha256Copy(&digest.sha256, &ssl->hsHashes->hashSha256);
  8001. wc_Sha256Free(&digest.sha256);
  8002. if (ret != 0)
  8003. return ret;
  8004. break;
  8005. #endif
  8006. #ifdef WOLFSSL_SHA384
  8007. case sha384_mac:
  8008. wc_Sha384Free(&ssl->hsHashes->hashSha384);
  8009. ret = wc_Sha384Copy(&digest.sha384, &ssl->hsHashes->hashSha384);
  8010. wc_Sha384Free(&digest.sha384);
  8011. if (ret != 0)
  8012. return ret;
  8013. break;
  8014. #endif
  8015. #ifdef WOLFSSL_TLS13_SHA512
  8016. case sha512_mac:
  8017. wc_Sha512Free(&ssl->hsHashes->hashSha512);
  8018. ret = wc_Sha512Copy(&digest.sha512, &ssl->hsHashes->hashSha512);
  8019. wc_Sha512Free(&digest.sha512);
  8020. if (ret != 0)
  8021. return ret;
  8022. break;
  8023. #endif
  8024. }
  8025. return ret;
  8026. }
  8027. #endif
  8028. /* Send New Session Ticket handshake message.
  8029. * Message contains the information required to perform resumption.
  8030. *
  8031. * ssl The SSL/TLS object.
  8032. * returns 0 on success, otherwise failure.
  8033. */
  8034. static int SendTls13NewSessionTicket(WOLFSSL* ssl)
  8035. {
  8036. byte* output;
  8037. int ret;
  8038. int sendSz;
  8039. word16 extSz;
  8040. word32 length;
  8041. word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  8042. WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_SEND);
  8043. WOLFSSL_ENTER("SendTls13NewSessionTicket");
  8044. #ifdef WOLFSSL_DTLS13
  8045. if (ssl->options.dtls)
  8046. idx = Dtls13GetRlHeaderLength(1) + DTLS_HANDSHAKE_HEADER_SZ;
  8047. #endif /* WOLFSSL_DTLS13 */
  8048. #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
  8049. if (!ssl->msgsReceived.got_finished) {
  8050. if ((ret = ExpectedResumptionSecret(ssl)) != 0)
  8051. return ret;
  8052. }
  8053. #endif
  8054. /* Start ticket nonce at 0 and go up to 255. */
  8055. if (ssl->session->ticketNonce.len == 0) {
  8056. ssl->session->ticketNonce.len = DEF_TICKET_NONCE_SZ;
  8057. ssl->session->ticketNonce.data[0] = 0;
  8058. }
  8059. else
  8060. ssl->session->ticketNonce.data[0]++;
  8061. if (!ssl->options.noTicketTls13) {
  8062. if ((ret = CreateTicket(ssl)) != 0)
  8063. return ret;
  8064. }
  8065. #ifdef WOLFSSL_EARLY_DATA
  8066. ssl->session->maxEarlyDataSz = ssl->options.maxEarlyDataSz;
  8067. if (ssl->session->maxEarlyDataSz > 0)
  8068. TLSX_EarlyData_Use(ssl, ssl->session->maxEarlyDataSz);
  8069. extSz = 0;
  8070. ret = TLSX_GetResponseSize(ssl, session_ticket, &extSz);
  8071. if (ret != 0)
  8072. return ret;
  8073. #else
  8074. extSz = EXTS_SZ;
  8075. #endif
  8076. /* Lifetime | Age Add | Ticket | Extensions */
  8077. length = SESSION_HINT_SZ + SESSION_ADD_SZ + LENGTH_SZ +
  8078. ssl->session->ticketLen + extSz;
  8079. /* Nonce */
  8080. length += TICKET_NONCE_LEN_SZ + DEF_TICKET_NONCE_SZ;
  8081. sendSz = idx + length + MAX_MSG_EXTRA;
  8082. /* Check buffers are big enough and grow if needed. */
  8083. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  8084. return ret;
  8085. /* Get position in output buffer to write new message to. */
  8086. output = ssl->buffers.outputBuffer.buffer +
  8087. ssl->buffers.outputBuffer.length;
  8088. /* Put the record and handshake headers on. */
  8089. AddTls13Headers(output, length, session_ticket, ssl);
  8090. /* Lifetime hint */
  8091. c32toa(ssl->ctx->ticketHint, output + idx);
  8092. idx += SESSION_HINT_SZ;
  8093. /* Age add - obfuscator */
  8094. c32toa(ssl->session->ticketAdd, output + idx);
  8095. idx += SESSION_ADD_SZ;
  8096. output[idx++] = ssl->session->ticketNonce.len;
  8097. output[idx++] = ssl->session->ticketNonce.data[0];
  8098. /* length */
  8099. c16toa(ssl->session->ticketLen, output + idx);
  8100. idx += LENGTH_SZ;
  8101. /* ticket */
  8102. XMEMCPY(output + idx, ssl->session->ticket, ssl->session->ticketLen);
  8103. idx += ssl->session->ticketLen;
  8104. #ifdef WOLFSSL_EARLY_DATA
  8105. extSz = 0;
  8106. ret = TLSX_WriteResponse(ssl, output + idx, session_ticket, &extSz);
  8107. if (ret != 0)
  8108. return ret;
  8109. idx += extSz;
  8110. #else
  8111. /* No extension support - empty extensions. */
  8112. c16toa(0, output + idx);
  8113. idx += EXTS_SZ;
  8114. #endif
  8115. ssl->options.haveSessionId = 1;
  8116. #ifndef NO_SESSION_CACHE
  8117. AddSession(ssl);
  8118. #endif
  8119. #ifdef WOLFSSL_DTLS13
  8120. if (ssl->options.dtls)
  8121. return Dtls13HandshakeSend(ssl, output, sendSz, idx, session_ticket, 0);
  8122. #endif /* WOLFSSL_DTLS13 */
  8123. /* This message is always encrypted. */
  8124. sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
  8125. idx - RECORD_HEADER_SZ, handshake, 0, 0, 0);
  8126. if (sendSz < 0)
  8127. return sendSz;
  8128. ssl->buffers.outputBuffer.length += sendSz;
  8129. /* Always send as this is either directly after server's Finished or only
  8130. * message after client's Finished.
  8131. */
  8132. ret = SendBuffered(ssl);
  8133. WOLFSSL_LEAVE("SendTls13NewSessionTicket", 0);
  8134. WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_SEND);
  8135. return ret;
  8136. }
  8137. #endif /* HAVE_SESSION_TICKET */
  8138. #endif /* NO_WOLFSSL_SERVER */
  8139. /* Make sure no duplicates, no fast forward, or other problems
  8140. *
  8141. * ssl The SSL/TLS object.
  8142. * type Type of handshake message received.
  8143. * returns 0 on success, otherwise failure.
  8144. */
  8145. static int SanityCheckTls13MsgReceived(WOLFSSL* ssl, byte type)
  8146. {
  8147. /* verify not a duplicate, mark received, check state */
  8148. switch (type) {
  8149. #ifndef NO_WOLFSSL_SERVER
  8150. case client_hello:
  8151. #ifndef NO_WOLFSSL_CLIENT
  8152. /* Only valid when received on SERVER side. */
  8153. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  8154. WOLFSSL_MSG("ClientHello received by client");
  8155. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8156. return SIDE_ERROR;
  8157. }
  8158. #endif
  8159. /* Check state. */
  8160. if (ssl->options.clientState >= CLIENT_HELLO_COMPLETE) {
  8161. WOLFSSL_MSG("ClientHello received out of order");
  8162. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8163. return OUT_OF_ORDER_E;
  8164. }
  8165. /* Check previously seen. */
  8166. /* Initial and after HelloRetryRequest - no more than 2. */
  8167. if (ssl->msgsReceived.got_client_hello == 2) {
  8168. WOLFSSL_MSG("Too many ClientHello received");
  8169. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8170. return DUPLICATE_MSG_E;
  8171. }
  8172. /* Second only after HelloRetryRequest seen. */
  8173. if (ssl->msgsReceived.got_client_hello == 1 &&
  8174. ssl->options.serverState !=
  8175. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  8176. WOLFSSL_MSG("Duplicate ClientHello received");
  8177. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8178. return DUPLICATE_MSG_E;
  8179. }
  8180. ssl->msgsReceived.got_client_hello++;
  8181. break;
  8182. #endif
  8183. #ifndef NO_WOLFSSL_CLIENT
  8184. case server_hello:
  8185. #ifndef NO_WOLFSSL_SERVER
  8186. /* Only valid when received on CLIENT side. */
  8187. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8188. WOLFSSL_MSG("ServerHello received by server");
  8189. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8190. return SIDE_ERROR;
  8191. }
  8192. #endif
  8193. /* Check state. */
  8194. if (ssl->options.serverState >= SERVER_HELLO_COMPLETE) {
  8195. WOLFSSL_MSG("ServerHello received out of order");
  8196. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8197. return OUT_OF_ORDER_E;
  8198. }
  8199. /* Check previously seen. */
  8200. /* Only once after ClientHello.
  8201. * HelloRetryRequest has ServerHello type but count fixed up later
  8202. * - see DoTls13ServerHello().
  8203. */
  8204. if (ssl->msgsReceived.got_server_hello) {
  8205. WOLFSSL_MSG("Duplicate ServerHello received");
  8206. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8207. return DUPLICATE_MSG_E;
  8208. }
  8209. ssl->msgsReceived.got_server_hello = 1;
  8210. break;
  8211. #endif
  8212. #ifndef NO_WOLFSSL_CLIENT
  8213. case session_ticket:
  8214. #ifndef NO_WOLFSSL_SERVER
  8215. /* Only valid when received on CLIENT side. */
  8216. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8217. WOLFSSL_MSG("NewSessionTicket received by server");
  8218. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8219. return SIDE_ERROR;
  8220. }
  8221. #endif
  8222. /* Check state. */
  8223. #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
  8224. /* Only allowed after server's Finished message. */
  8225. if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
  8226. WOLFSSL_MSG("NewSessionTicket received out of order");
  8227. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8228. return OUT_OF_ORDER_E;
  8229. }
  8230. #else
  8231. /* Only allowed after client's Finished message. */
  8232. if (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
  8233. WOLFSSL_MSG("NewSessionTicket received out of order");
  8234. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8235. return OUT_OF_ORDER_E;
  8236. }
  8237. #endif
  8238. /* Many SessionTickets can be sent. */
  8239. ssl->msgsReceived.got_session_ticket = 1;
  8240. break;
  8241. #endif
  8242. #ifndef NO_WOLFSSL_SERVER
  8243. #ifdef WOLFSSL_EARLY_DATA
  8244. case end_of_early_data:
  8245. #ifndef NO_WOLFSSL_CLIENT
  8246. /* Only valid when received on SERVER side. */
  8247. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  8248. WOLFSSL_MSG("EndOfEarlyData received by client");
  8249. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8250. return SIDE_ERROR;
  8251. }
  8252. #endif
  8253. /* Check state. */
  8254. /* Only after server's Finished and before client's Finished. */
  8255. if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
  8256. WOLFSSL_MSG("EndOfEarlyData received out of order");
  8257. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8258. return OUT_OF_ORDER_E;
  8259. }
  8260. if (ssl->options.clientState >= CLIENT_FINISHED_COMPLETE) {
  8261. WOLFSSL_MSG("EndOfEarlyData received out of order");
  8262. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8263. return OUT_OF_ORDER_E;
  8264. }
  8265. /* Check previously seen. */
  8266. if (ssl->msgsReceived.got_end_of_early_data) {
  8267. WOLFSSL_MSG("Too many EndOfEarlyData received");
  8268. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8269. return DUPLICATE_MSG_E;
  8270. }
  8271. ssl->msgsReceived.got_end_of_early_data = 1;
  8272. break;
  8273. #endif
  8274. #endif
  8275. #ifndef NO_WOLFSSL_CLIENT
  8276. case encrypted_extensions:
  8277. #ifndef NO_WOLFSSL_SERVER
  8278. /* Only valid when received on CLIENT side. */
  8279. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8280. WOLFSSL_MSG("EncryptedExtensions received by server");
  8281. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8282. return SIDE_ERROR;
  8283. }
  8284. #endif
  8285. /* Check state. */
  8286. /* Must be received directly after ServerHello.
  8287. * DoTls13EncryptedExtensions() changes state to:
  8288. * SERVER_ENCRYPTED_EXTENSIONS_COMPLETE.
  8289. */
  8290. if (ssl->options.serverState != SERVER_HELLO_COMPLETE) {
  8291. WOLFSSL_MSG("EncryptedExtensions received out of order");
  8292. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8293. return OUT_OF_ORDER_E;
  8294. }
  8295. /* Check previously seen. */
  8296. if (ssl->msgsReceived.got_encrypted_extensions) {
  8297. WOLFSSL_MSG("Duplicate EncryptedExtensions received");
  8298. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8299. return DUPLICATE_MSG_E;
  8300. }
  8301. ssl->msgsReceived.got_encrypted_extensions = 1;
  8302. break;
  8303. #endif
  8304. case certificate:
  8305. /* Valid on both sides. */
  8306. #ifndef NO_WOLFSSL_CLIENT
  8307. /* Check state. */
  8308. /* On client, seen after EncryptedExtension and CertificateRequest
  8309. * (if sent) and before CertificateVerify and Finished.
  8310. * DoTls13Certificate() sets serverState to SERVER_CERT_COMPLETE.
  8311. */
  8312. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  8313. ssl->options.serverState !=
  8314. SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
  8315. WOLFSSL_MSG("Certificate received out of order - Client");
  8316. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8317. return OUT_OF_ORDER_E;
  8318. }
  8319. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  8320. /* Server's authenticating with PSK must not send this. */
  8321. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  8322. ssl->options.serverState == SERVER_CERT_COMPLETE &&
  8323. ssl->options.pskNegotiated) {
  8324. WOLFSSL_MSG("Certificate received while using PSK");
  8325. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8326. return SANITY_MSG_E;
  8327. }
  8328. #endif
  8329. #endif
  8330. #ifndef NO_WOLFSSL_SERVER
  8331. /* Check state. */
  8332. /* On Server, valid after ClientHello received and ServerFinished
  8333. * sent. */
  8334. if (ssl->options.side == WOLFSSL_SERVER_END &&
  8335. ssl->options.clientState != CLIENT_HELLO_COMPLETE &&
  8336. ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
  8337. WOLFSSL_MSG("Certificate received out of order - Server");
  8338. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8339. return OUT_OF_ORDER_E;
  8340. }
  8341. #endif
  8342. /* Check previously seen. */
  8343. if (ssl->msgsReceived.got_certificate) {
  8344. WOLFSSL_MSG("Duplicate Certificate received");
  8345. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8346. return DUPLICATE_MSG_E;
  8347. }
  8348. ssl->msgsReceived.got_certificate = 1;
  8349. break;
  8350. #ifndef NO_WOLFSSL_CLIENT
  8351. case certificate_request:
  8352. #ifndef NO_WOLFSSL_SERVER
  8353. /* Only valid when received on CLIENT side. */
  8354. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8355. WOLFSSL_MSG("CertificateRequest received by server");
  8356. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8357. return SIDE_ERROR;
  8358. }
  8359. #endif
  8360. /* Check state. */
  8361. #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
  8362. /* Only valid when sent after EncryptedExtensions and before
  8363. * Certificate. */
  8364. if (ssl->options.serverState !=
  8365. SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
  8366. WOLFSSL_MSG("CertificateRequest received out of order");
  8367. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8368. return OUT_OF_ORDER_E;
  8369. }
  8370. #else
  8371. /* Valid when sent after EncryptedExtensions and before Certificate
  8372. * and after both client and server have sent Finished (Post
  8373. * Handshake Authentication). */
  8374. if (ssl->options.serverState !=
  8375. SERVER_ENCRYPTED_EXTENSIONS_COMPLETE &&
  8376. (ssl->options.serverState < SERVER_FINISHED_COMPLETE ||
  8377. ssl->options.clientState != CLIENT_FINISHED_COMPLETE)) {
  8378. WOLFSSL_MSG("CertificateRequest received out of order");
  8379. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8380. return OUT_OF_ORDER_E;
  8381. }
  8382. #endif
  8383. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  8384. /* Server's authenticating with PSK must not send this. */
  8385. if (ssl->options.pskNegotiated) {
  8386. WOLFSSL_MSG("CertificateRequest received while using PSK");
  8387. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8388. return SANITY_MSG_E;
  8389. }
  8390. #endif
  8391. /* Check previously seen. */
  8392. #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
  8393. /* Only once during handshake. */
  8394. if (ssl->msgsReceived.got_certificate_request) {
  8395. WOLFSSL_MSG("Duplicate CertificateRequest received");
  8396. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8397. return DUPLICATE_MSG_E;
  8398. }
  8399. #else
  8400. /* Only once during handshake. */
  8401. if (ssl->msgsReceived.got_certificate_request &&
  8402. ssl->options.clientState != CLIENT_FINISHED_COMPLETE) {
  8403. WOLFSSL_MSG("Duplicate CertificateRequest received");
  8404. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8405. return DUPLICATE_MSG_E;
  8406. }
  8407. #endif
  8408. ssl->msgsReceived.got_certificate_request = 1;
  8409. break;
  8410. #endif
  8411. case certificate_verify:
  8412. /* Valid on both sides. */
  8413. #ifndef NO_WOLFSSL_CLIENT
  8414. /* Check state on client.
  8415. * Valid only directly after a Certificate message. */
  8416. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  8417. if (ssl->options.serverState != SERVER_CERT_COMPLETE) {
  8418. WOLFSSL_MSG("No Cert before CertVerify");
  8419. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8420. return OUT_OF_ORDER_E;
  8421. }
  8422. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  8423. /* Server's authenticating with PSK must not send this. */
  8424. if (ssl->options.pskNegotiated) {
  8425. WOLFSSL_MSG("CertificateVerify received while using PSK");
  8426. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8427. return SANITY_MSG_E;
  8428. }
  8429. #endif
  8430. }
  8431. #endif
  8432. #ifndef NO_WOLFSSL_SERVER
  8433. /* Check state on server. */
  8434. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8435. /* Server must have sent Finished message. */
  8436. if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
  8437. WOLFSSL_MSG("CertificateVerify received out of order");
  8438. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8439. return OUT_OF_ORDER_E;
  8440. }
  8441. /* Valid only directly after a Certificate message. */
  8442. if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  8443. WOLFSSL_MSG("CertificateVerify before ClientHello done");
  8444. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8445. return OUT_OF_ORDER_E;
  8446. }
  8447. if (!ssl->msgsReceived.got_certificate) {
  8448. WOLFSSL_MSG("No Cert before CertificateVerify");
  8449. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8450. return OUT_OF_ORDER_E;
  8451. }
  8452. }
  8453. #endif
  8454. /* Check previously seen. */
  8455. if (ssl->msgsReceived.got_certificate_verify) {
  8456. WOLFSSL_MSG("Duplicate CertificateVerify received");
  8457. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8458. return DUPLICATE_MSG_E;
  8459. }
  8460. ssl->msgsReceived.got_certificate_verify = 1;
  8461. break;
  8462. case finished:
  8463. /* Valid on both sides. */
  8464. #ifndef NO_WOLFSSL_CLIENT
  8465. /* Check state on client. */
  8466. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  8467. /* After sending ClientHello */
  8468. if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  8469. WOLFSSL_MSG("Finished received out of order - clientState");
  8470. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8471. return OUT_OF_ORDER_E;
  8472. }
  8473. /* Must have seen certificate and verify from server except when
  8474. * using PSK. */
  8475. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  8476. if (ssl->options.pskNegotiated) {
  8477. if (ssl->options.serverState !=
  8478. SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
  8479. WOLFSSL_MSG("Finished received out of order - PSK");
  8480. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8481. return OUT_OF_ORDER_E;
  8482. }
  8483. }
  8484. else
  8485. #endif
  8486. if (ssl->options.serverState != SERVER_CERT_VERIFY_COMPLETE) {
  8487. WOLFSSL_MSG("Finished received out of order - serverState");
  8488. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8489. return OUT_OF_ORDER_E;
  8490. }
  8491. }
  8492. #endif
  8493. #ifndef NO_WOLFSSL_SERVER
  8494. /* Check state on server. */
  8495. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8496. if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
  8497. WOLFSSL_MSG("Finished received out of order - serverState");
  8498. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8499. return OUT_OF_ORDER_E;
  8500. }
  8501. if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  8502. WOLFSSL_MSG("Finished received out of order - clientState");
  8503. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8504. return OUT_OF_ORDER_E;
  8505. }
  8506. #ifdef WOLFSSL_EARLY_DATA
  8507. if (ssl->earlyData == process_early_data &&
  8508. /* early data may be lost when using DTLS */
  8509. !ssl->options.dtls
  8510. /* QUIC does not use EndOfEarlyData records */
  8511. && !WOLFSSL_IS_QUIC(ssl)) {
  8512. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8513. return OUT_OF_ORDER_E;
  8514. }
  8515. #endif
  8516. }
  8517. #endif
  8518. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  8519. if (!ssl->options.pskNegotiated)
  8520. #endif
  8521. {
  8522. /* Must have received a Certificate message from client if
  8523. * verifying the peer. Empty certificate message indicates
  8524. * no certificate available.
  8525. */
  8526. if (ssl->options.verifyPeer &&
  8527. !ssl->msgsReceived.got_certificate) {
  8528. WOLFSSL_MSG("Finished received out of order - "
  8529. "missing Certificate message");
  8530. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8531. return OUT_OF_ORDER_E;
  8532. }
  8533. /* Mutual authentication on server requires a certificate from
  8534. * peer. Verify peer set on client side requires a certificate
  8535. * from peer as not doing PSK.
  8536. */
  8537. if ((ssl->options.mutualAuth ||
  8538. (ssl->options.side == WOLFSSL_CLIENT_END &&
  8539. ssl->options.verifyPeer)) && !ssl->options.havePeerCert) {
  8540. WOLFSSL_MSG("Finished received out of order - "
  8541. "no valid certificate");
  8542. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8543. return OUT_OF_ORDER_E;
  8544. }
  8545. /* Must have received a valid CertificateVerify if verifying
  8546. * peer and got a peer certificate.
  8547. */
  8548. if ((ssl->options.mutualAuth || ssl->options.verifyPeer) &&
  8549. ssl->options.havePeerCert && !ssl->options.havePeerVerify) {
  8550. WOLFSSL_MSG("Finished received out of order - "
  8551. "Certificate message but no CertificateVerify");
  8552. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8553. return OUT_OF_ORDER_E;
  8554. }
  8555. }
  8556. /* Check previously seen. */
  8557. if (ssl->msgsReceived.got_finished) {
  8558. WOLFSSL_MSG("Duplicate Finished received");
  8559. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8560. return DUPLICATE_MSG_E;
  8561. }
  8562. ssl->msgsReceived.got_finished = 1;
  8563. break;
  8564. case key_update:
  8565. /* Valid on both sides. */
  8566. /* Check state.
  8567. * Client and server must have received finished message from other
  8568. * side.
  8569. */
  8570. if (!ssl->msgsReceived.got_finished) {
  8571. WOLFSSL_MSG("No KeyUpdate before Finished");
  8572. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8573. return OUT_OF_ORDER_E;
  8574. }
  8575. /* Multiple KeyUpdates can be sent. */
  8576. break;
  8577. #if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
  8578. case hello_verify_request:
  8579. if (!ssl->options.dtls) {
  8580. WOLFSSL_MSG("HelloVerifyRequest when not in DTLS");
  8581. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8582. return OUT_OF_ORDER_E;
  8583. }
  8584. if (ssl->msgsReceived.got_hello_verify_request) {
  8585. WOLFSSL_MSG("Duplicate HelloVerifyRequest received");
  8586. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8587. return DUPLICATE_MSG_E;
  8588. }
  8589. ssl->msgsReceived.got_hello_verify_request = 1;
  8590. if (ssl->msgsReceived.got_hello_retry_request) {
  8591. WOLFSSL_MSG(
  8592. "Both HelloVerifyRequest and HelloRetryRequest received");
  8593. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  8594. return DUPLICATE_MSG_E;
  8595. }
  8596. if (ssl->options.serverState >=
  8597. SERVER_HELLO_RETRY_REQUEST_COMPLETE ||
  8598. ssl->options.connectState != CLIENT_HELLO_SENT) {
  8599. WOLFSSL_MSG("HelloVerifyRequest received out of order");
  8600. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8601. return OUT_OF_ORDER_E;
  8602. }
  8603. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8604. WOLFSSL_MSG("HelloVerifyRequest recevied on the server");
  8605. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  8606. return SIDE_ERROR;
  8607. }
  8608. if (!ssl->options.downgrade ||
  8609. ssl->options.minDowngrade < DTLSv1_2_MINOR) {
  8610. WOLFSSL_MSG(
  8611. "HelloVerifyRequest recevied but not DTLSv1.2 allowed");
  8612. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  8613. return VERSION_ERROR;
  8614. }
  8615. break;
  8616. #endif /* WOLFSSL_DTLS13 && !WOLFSSL_NO_TLS12*/
  8617. default:
  8618. WOLFSSL_MSG("Unknown message type");
  8619. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8620. return SANITY_MSG_E;
  8621. }
  8622. return 0;
  8623. }
  8624. /* Handle a type of handshake message that has been received.
  8625. *
  8626. * ssl The SSL/TLS object.
  8627. * input The message buffer.
  8628. * inOutIdx On entry, the index into the buffer of the current message.
  8629. * On exit, the index into the buffer of the next message.
  8630. * size The length of the current handshake message.
  8631. * totalSz Length of remaining data in the message buffer.
  8632. * returns 0 on success and otherwise failure.
  8633. */
  8634. int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  8635. byte type, word32 size, word32 totalSz)
  8636. {
  8637. int ret = 0;
  8638. word32 inIdx = *inOutIdx;
  8639. (void)totalSz;
  8640. WOLFSSL_ENTER("DoTls13HandShakeMsgType");
  8641. /* make sure we can read the message */
  8642. if (*inOutIdx + size > totalSz)
  8643. return INCOMPLETE_DATA;
  8644. /* sanity check msg received */
  8645. if ((ret = SanityCheckTls13MsgReceived(ssl, type)) != 0) {
  8646. WOLFSSL_MSG("Sanity Check on handshake message type received failed");
  8647. SendAlert(ssl, alert_fatal, unexpected_message);
  8648. return ret;
  8649. }
  8650. #ifdef WOLFSSL_CALLBACKS
  8651. /* add name later, add on record and handshake header part back on */
  8652. if (ssl->toInfoOn) {
  8653. int add = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  8654. AddPacketInfo(ssl, 0, handshake, input + *inOutIdx - add,
  8655. size + add, READ_PROTO, ssl->heap);
  8656. AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
  8657. }
  8658. #endif
  8659. if (ssl->options.handShakeState == HANDSHAKE_DONE &&
  8660. type != session_ticket && type != certificate_request &&
  8661. type != certificate && type != key_update && type != finished) {
  8662. WOLFSSL_MSG("HandShake message after handshake complete");
  8663. SendAlert(ssl, alert_fatal, unexpected_message);
  8664. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8665. return OUT_OF_ORDER_E;
  8666. }
  8667. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  8668. ssl->options.serverState == NULL_STATE &&
  8669. type != server_hello && type != hello_retry_request
  8670. #if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
  8671. && (!ssl->options.dtls || type != hello_verify_request)
  8672. #endif /* defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12) */
  8673. ) {
  8674. WOLFSSL_MSG("First server message not server hello");
  8675. SendAlert(ssl, alert_fatal, unexpected_message);
  8676. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8677. return OUT_OF_ORDER_E;
  8678. }
  8679. if (ssl->options.side == WOLFSSL_SERVER_END &&
  8680. ssl->options.clientState == NULL_STATE && type != client_hello) {
  8681. WOLFSSL_MSG("First client message not client hello");
  8682. SendAlert(ssl, alert_fatal, unexpected_message);
  8683. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  8684. return OUT_OF_ORDER_E;
  8685. }
  8686. /* above checks handshake state */
  8687. switch (type) {
  8688. #ifndef NO_WOLFSSL_CLIENT
  8689. /* Messages only received by client. */
  8690. case server_hello:
  8691. WOLFSSL_MSG("processing server hello");
  8692. ret = DoTls13ServerHello(ssl, input, inOutIdx, size, &type);
  8693. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  8694. ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  8695. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  8696. if (ssl->options.resuming || !IsAtLeastTLSv1_2(ssl) ||
  8697. IsAtLeastTLSv1_3(ssl->version)) {
  8698. ssl->options.cacheMessages = 0;
  8699. if ((ssl->hsHashes != NULL) && (ssl->hsHashes->messages != NULL)) {
  8700. ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length);
  8701. XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
  8702. ssl->hsHashes->messages = NULL;
  8703. }
  8704. }
  8705. #endif
  8706. break;
  8707. case encrypted_extensions:
  8708. WOLFSSL_MSG("processing encrypted extensions");
  8709. ret = DoTls13EncryptedExtensions(ssl, input, inOutIdx, size);
  8710. break;
  8711. #ifndef NO_CERTS
  8712. case certificate_request:
  8713. WOLFSSL_MSG("processing certificate request");
  8714. ret = DoTls13CertificateRequest(ssl, input, inOutIdx, size);
  8715. break;
  8716. #endif
  8717. case session_ticket:
  8718. WOLFSSL_MSG("processing new session ticket");
  8719. ret = DoTls13NewSessionTicket(ssl, input, inOutIdx, size);
  8720. break;
  8721. #endif /* !NO_WOLFSSL_CLIENT */
  8722. #ifndef NO_WOLFSSL_SERVER
  8723. /* Messages only received by server. */
  8724. case client_hello:
  8725. WOLFSSL_MSG("processing client hello");
  8726. ret = DoTls13ClientHello(ssl, input, inOutIdx, size);
  8727. break;
  8728. #ifdef WOLFSSL_EARLY_DATA
  8729. case end_of_early_data:
  8730. WOLFSSL_MSG("processing end of early data");
  8731. ret = DoTls13EndOfEarlyData(ssl, input, inOutIdx, size);
  8732. break;
  8733. #endif
  8734. #endif /* !NO_WOLFSSL_SERVER */
  8735. /* Messages received by both client and server. */
  8736. #if !defined(NO_CERTS) && (!defined(NO_WOLFSSL_CLIENT) || \
  8737. !defined(WOLFSSL_NO_CLIENT_AUTH))
  8738. case certificate:
  8739. WOLFSSL_MSG("processing certificate");
  8740. ret = DoTls13Certificate(ssl, input, inOutIdx, size);
  8741. break;
  8742. #endif
  8743. #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  8744. defined(HAVE_ED448) || defined(HAVE_PQC)
  8745. case certificate_verify:
  8746. WOLFSSL_MSG("processing certificate verify");
  8747. ret = DoTls13CertificateVerify(ssl, input, inOutIdx, size);
  8748. break;
  8749. #endif
  8750. case finished:
  8751. WOLFSSL_MSG("processing finished");
  8752. ret = DoTls13Finished(ssl, input, inOutIdx, size, totalSz, NO_SNIFF);
  8753. break;
  8754. case key_update:
  8755. WOLFSSL_MSG("processing key update");
  8756. ret = DoTls13KeyUpdate(ssl, input, inOutIdx, size);
  8757. break;
  8758. #if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
  8759. case hello_verify_request:
  8760. WOLFSSL_MSG("processing hello verify request");
  8761. ret = DoHelloVerifyRequest(ssl, input, inOutIdx, size);
  8762. break;
  8763. #endif
  8764. default:
  8765. WOLFSSL_MSG("Unknown handshake message type");
  8766. ret = UNKNOWN_HANDSHAKE_TYPE;
  8767. break;
  8768. }
  8769. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_ASYNC_IO)
  8770. /* if async, offset index so this msg will be processed again */
  8771. /* NOTE: check this now before other calls can overwrite ret */
  8772. if ((ret == WC_PENDING_E || ret == OCSP_WANT_READ) && *inOutIdx > 0) {
  8773. /* DTLS always stores a message in a buffer when async is enable, so we
  8774. * don't need to adjust for the extra bytes here (*inOutIdx is always
  8775. * == 0) */
  8776. *inOutIdx -= HANDSHAKE_HEADER_SZ;
  8777. }
  8778. #endif
  8779. /* reset error */
  8780. if (ret == 0 && ssl->error == WC_PENDING_E)
  8781. ssl->error = 0;
  8782. if (ret == 0 && type != client_hello && type != session_ticket &&
  8783. type != key_update) {
  8784. ret = HashInput(ssl, input + inIdx, size);
  8785. }
  8786. if (ret == BUFFER_ERROR || ret == MISSING_HANDSHAKE_DATA)
  8787. SendAlert(ssl, alert_fatal, decode_error);
  8788. else if (ret == EXT_NOT_ALLOWED || ret == PEER_KEY_ERROR ||
  8789. ret == ECC_PEERKEY_ERROR || ret == BAD_KEY_SHARE_DATA ||
  8790. ret == PSK_KEY_ERROR || ret == INVALID_PARAMETER) {
  8791. SendAlert(ssl, alert_fatal, illegal_parameter);
  8792. }
  8793. if (ret == 0 && ssl->options.tls1_3) {
  8794. /* Need to hash input message before deriving secrets. */
  8795. #ifndef NO_WOLFSSL_CLIENT
  8796. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  8797. if (type == server_hello) {
  8798. if ((ret = DeriveEarlySecret(ssl)) != 0)
  8799. return ret;
  8800. if ((ret = DeriveHandshakeSecret(ssl)) != 0)
  8801. return ret;
  8802. if ((ret = DeriveTls13Keys(ssl, handshake_key,
  8803. ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0) {
  8804. return ret;
  8805. }
  8806. #ifdef WOLFSSL_EARLY_DATA
  8807. if (ssl->earlyData != no_early_data) {
  8808. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  8809. return ret;
  8810. }
  8811. else
  8812. #endif
  8813. if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0)
  8814. return ret;
  8815. #ifdef WOLFSSL_DTLS13
  8816. if (ssl->options.dtls) {
  8817. w64wrapper epochHandshake;
  8818. epochHandshake = w64From32(0, DTLS13_EPOCH_HANDSHAKE);
  8819. ssl->dtls13Epoch = epochHandshake;
  8820. ssl->dtls13PeerEpoch = epochHandshake;
  8821. ret = Dtls13NewEpoch(
  8822. ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE);
  8823. if (ret != 0)
  8824. return ret;
  8825. ret = Dtls13SetEpochKeys(
  8826. ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE);
  8827. if (ret != 0)
  8828. return ret;
  8829. }
  8830. #endif /* WOLFSSL_DTLS13 */
  8831. }
  8832. if (type == finished) {
  8833. if ((ret = DeriveMasterSecret(ssl)) != 0)
  8834. return ret;
  8835. /* Last use of preMasterSecret - zeroize as soon as possible. */
  8836. ForceZero(ssl->arrays->preMasterSecret,
  8837. ssl->arrays->preMasterSz);
  8838. #ifdef WOLFSSL_EARLY_DATA
  8839. #ifdef WOLFSSL_QUIC
  8840. if (WOLFSSL_IS_QUIC(ssl) && ssl->earlyData != no_early_data) {
  8841. /* QUIC never sends/receives EndOfEarlyData, but having
  8842. * early data means the last encrpytion keys had not been
  8843. * set yet. */
  8844. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  8845. return ret;
  8846. }
  8847. #endif
  8848. if ((ret = DeriveTls13Keys(ssl, traffic_key,
  8849. ENCRYPT_AND_DECRYPT_SIDE,
  8850. ssl->earlyData == no_early_data)) != 0) {
  8851. return ret;
  8852. }
  8853. #else
  8854. if ((ret = DeriveTls13Keys(ssl, traffic_key,
  8855. ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0) {
  8856. return ret;
  8857. }
  8858. #endif
  8859. }
  8860. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  8861. if (type == certificate_request &&
  8862. ssl->options.handShakeState == HANDSHAKE_DONE) {
  8863. /* reset handshake states */
  8864. ssl->options.clientState = CLIENT_HELLO_COMPLETE;
  8865. ssl->options.connectState = FIRST_REPLY_DONE;
  8866. ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
  8867. ssl->options.processReply = 0; /* doProcessInit */
  8868. /*
  8869. DTLSv1.3 note: We can't reset serverState to
  8870. SERVER_FINISHED_COMPLETE with the goal that this connect
  8871. blocks until the cert/cert_verify/finished flight gets ACKed
  8872. by the server. The problem is that we will invoke
  8873. ProcessReplyEx() in that case, but we came here from
  8874. ProcessReplyEx() and it is not re-entrant safe (the input
  8875. buffer would still have the certificate_request message). */
  8876. if (wolfSSL_connect_TLSv13(ssl) != WOLFSSL_SUCCESS) {
  8877. ret = ssl->error;
  8878. if (ret != WC_PENDING_E)
  8879. ret = POST_HAND_AUTH_ERROR;
  8880. }
  8881. }
  8882. #endif
  8883. }
  8884. #endif /* NO_WOLFSSL_CLIENT */
  8885. #ifndef NO_WOLFSSL_SERVER
  8886. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  8887. if (ssl->options.side == WOLFSSL_SERVER_END && type == finished) {
  8888. ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret);
  8889. if (ret != 0)
  8890. return ret;
  8891. }
  8892. #endif
  8893. #endif /* NO_WOLFSSL_SERVER */
  8894. }
  8895. WOLFSSL_LEAVE("DoTls13HandShakeMsgType()", ret);
  8896. return ret;
  8897. }
  8898. /* Handle a handshake message that has been received.
  8899. *
  8900. * ssl The SSL/TLS object.
  8901. * input The message buffer.
  8902. * inOutIdx On entry, the index into the buffer of the current message.
  8903. * On exit, the index into the buffer of the next message.
  8904. * totalSz Length of remaining data in the message buffer.
  8905. * returns 0 on success and otherwise failure.
  8906. */
  8907. int DoTls13HandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  8908. word32 totalSz)
  8909. {
  8910. int ret = 0;
  8911. word32 inputLength;
  8912. byte type;
  8913. word32 size = 0;
  8914. WOLFSSL_ENTER("DoTls13HandShakeMsg()");
  8915. if (ssl->arrays == NULL) {
  8916. if (GetHandshakeHeader(ssl, input, inOutIdx, &type, &size,
  8917. totalSz) != 0) {
  8918. SendAlert(ssl, alert_fatal, unexpected_message);
  8919. WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
  8920. return PARSE_ERROR;
  8921. }
  8922. return DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
  8923. totalSz);
  8924. }
  8925. inputLength = ssl->buffers.inputBuffer.length - *inOutIdx - ssl->keys.padSz;
  8926. /* If there is a pending fragmented handshake message,
  8927. * pending message size will be non-zero. */
  8928. if (ssl->arrays->pendingMsgSz == 0) {
  8929. if (GetHandshakeHeader(ssl, input, inOutIdx, &type, &size,
  8930. totalSz) != 0) {
  8931. WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
  8932. return PARSE_ERROR;
  8933. }
  8934. /* Cap the maximum size of a handshake message to something reasonable.
  8935. * By default is the maximum size of a certificate message assuming
  8936. * nine 2048-bit RSA certificates in the chain. */
  8937. if (size > MAX_HANDSHAKE_SZ) {
  8938. WOLFSSL_MSG("Handshake message too large");
  8939. WOLFSSL_ERROR_VERBOSE(HANDSHAKE_SIZE_ERROR);
  8940. return HANDSHAKE_SIZE_ERROR;
  8941. }
  8942. /* size is the size of the certificate message payload */
  8943. if (inputLength - HANDSHAKE_HEADER_SZ < size) {
  8944. ssl->arrays->pendingMsgType = type;
  8945. ssl->arrays->pendingMsgSz = size + HANDSHAKE_HEADER_SZ;
  8946. ssl->arrays->pendingMsg = (byte*)XMALLOC(size + HANDSHAKE_HEADER_SZ,
  8947. ssl->heap,
  8948. DYNAMIC_TYPE_ARRAYS);
  8949. if (ssl->arrays->pendingMsg == NULL)
  8950. return MEMORY_E;
  8951. XMEMCPY(ssl->arrays->pendingMsg,
  8952. input + *inOutIdx - HANDSHAKE_HEADER_SZ,
  8953. inputLength);
  8954. ssl->arrays->pendingMsgOffset = inputLength;
  8955. *inOutIdx += inputLength + ssl->keys.padSz - HANDSHAKE_HEADER_SZ;
  8956. return 0;
  8957. }
  8958. ret = DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
  8959. totalSz);
  8960. }
  8961. else {
  8962. if (inputLength + ssl->arrays->pendingMsgOffset >
  8963. ssl->arrays->pendingMsgSz) {
  8964. inputLength = ssl->arrays->pendingMsgSz -
  8965. ssl->arrays->pendingMsgOffset;
  8966. }
  8967. XMEMCPY(ssl->arrays->pendingMsg + ssl->arrays->pendingMsgOffset,
  8968. input + *inOutIdx, inputLength);
  8969. ssl->arrays->pendingMsgOffset += inputLength;
  8970. *inOutIdx += inputLength + ssl->keys.padSz;
  8971. if (ssl->arrays->pendingMsgOffset == ssl->arrays->pendingMsgSz)
  8972. {
  8973. word32 idx = 0;
  8974. ret = DoTls13HandShakeMsgType(ssl,
  8975. ssl->arrays->pendingMsg + HANDSHAKE_HEADER_SZ,
  8976. &idx, ssl->arrays->pendingMsgType,
  8977. ssl->arrays->pendingMsgSz - HANDSHAKE_HEADER_SZ,
  8978. ssl->arrays->pendingMsgSz);
  8979. #ifdef WOLFSSL_ASYNC_CRYPT
  8980. if (ret == WC_PENDING_E) {
  8981. /* setup to process fragment again */
  8982. ssl->arrays->pendingMsgOffset -= inputLength;
  8983. *inOutIdx -= inputLength + ssl->keys.padSz;
  8984. }
  8985. else
  8986. #endif
  8987. {
  8988. XFREE(ssl->arrays->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
  8989. ssl->arrays->pendingMsg = NULL;
  8990. ssl->arrays->pendingMsgSz = 0;
  8991. }
  8992. }
  8993. }
  8994. WOLFSSL_LEAVE("DoTls13HandShakeMsg()", ret);
  8995. return ret;
  8996. }
  8997. #ifndef NO_WOLFSSL_CLIENT
  8998. /* The client connecting to the server.
  8999. * The protocol version is expecting to be TLS v1.3.
  9000. * If the server downgrades, and older versions of the protocol are compiled
  9001. * in, the client will fallback to wolfSSL_connect().
  9002. * Please see note at top of README if you get an error from connect.
  9003. *
  9004. * ssl The SSL/TLS object.
  9005. * returns WOLFSSL_SUCCESS on successful handshake, WOLFSSL_FATAL_ERROR when
  9006. * unrecoverable error occurs and 0 otherwise.
  9007. * For more error information use wolfSSL_get_error().
  9008. */
  9009. int wolfSSL_connect_TLSv13(WOLFSSL* ssl)
  9010. {
  9011. int advanceState;
  9012. int ret = 0;
  9013. WOLFSSL_ENTER("wolfSSL_connect_TLSv13()");
  9014. #ifdef HAVE_ERRNO_H
  9015. errno = 0;
  9016. #endif
  9017. if (ssl->options.side != WOLFSSL_CLIENT_END) {
  9018. ssl->error = SIDE_ERROR;
  9019. WOLFSSL_ERROR(ssl->error);
  9020. return WOLFSSL_FATAL_ERROR;
  9021. }
  9022. #ifdef WOLFSSL_WOLFSENTRY_HOOKS
  9023. if ((ssl->ConnectFilter != NULL) &&
  9024. (ssl->options.connectState == CONNECT_BEGIN))
  9025. {
  9026. wolfSSL_netfilter_decision_t res;
  9027. if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) ==
  9028. WOLFSSL_SUCCESS) &&
  9029. (res == WOLFSSL_NETFILTER_REJECT)) {
  9030. ssl->error = SOCKET_FILTERED_E;
  9031. WOLFSSL_ERROR(ssl->error);
  9032. return WOLFSSL_FATAL_ERROR;
  9033. }
  9034. }
  9035. #endif /* WOLFSSL_WOLFSENTRY_HOOKS */
  9036. /* fragOffset is non-zero when sending fragments. On the last
  9037. * fragment, fragOffset is zero again, and the state can be
  9038. * advanced. Also, only advance from states in which we send data */
  9039. advanceState = (ssl->options.connectState == CONNECT_BEGIN ||
  9040. ssl->options.connectState == HELLO_AGAIN ||
  9041. (ssl->options.connectState >= FIRST_REPLY_DONE &&
  9042. ssl->options.connectState <= FIRST_REPLY_FOURTH));
  9043. #ifdef WOLFSSL_DTLS13
  9044. if (ssl->options.dtls)
  9045. advanceState = advanceState && !ssl->dtls13SendingFragments
  9046. && !ssl->dtls13SendingAckOrRtx;
  9047. #endif /* WOLFSSL_DTLS13 */
  9048. if (ssl->buffers.outputBuffer.length > 0
  9049. #ifdef WOLFSSL_ASYNC_CRYPT
  9050. /* do not send buffered or advance state if last error was an
  9051. async pending operation */
  9052. && ssl->error != WC_PENDING_E
  9053. #endif
  9054. ) {
  9055. if ((ssl->error = SendBuffered(ssl)) == 0) {
  9056. if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
  9057. if (advanceState) {
  9058. #ifdef WOLFSSL_DTLS13
  9059. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version) &&
  9060. ssl->options.connectState == FIRST_REPLY_FOURTH) {
  9061. /* WAIT_FINISHED_ACK is a state added afterwards, but it
  9062. can't follow FIRST_REPLY_FOURTH in the enum order. Indeed
  9063. the value of the enum ConnectState is stored in
  9064. serialized session. This would make importing serialized
  9065. session from other wolfSSL version incompatible */
  9066. ssl->options.connectState = WAIT_FINISHED_ACK;
  9067. }
  9068. else
  9069. #endif /* WOLFSSL_DTLS13 */
  9070. {
  9071. ssl->options.connectState++;
  9072. }
  9073. WOLFSSL_MSG("connect state: "
  9074. "Advanced from last buffered fragment send");
  9075. #ifdef WOLFSSL_ASYNC_IO
  9076. FreeAsyncCtx(ssl, 0);
  9077. #endif
  9078. }
  9079. }
  9080. else {
  9081. WOLFSSL_MSG("connect state: "
  9082. "Not advanced, more fragments to send");
  9083. }
  9084. #ifdef WOLFSSL_DTLS13
  9085. if (ssl->options.dtls)
  9086. ssl->dtls13SendingAckOrRtx =0;
  9087. #endif /* WOLFSSL_DTLS13 */
  9088. }
  9089. else {
  9090. ssl->error = ret;
  9091. WOLFSSL_ERROR(ssl->error);
  9092. return WOLFSSL_FATAL_ERROR;
  9093. }
  9094. }
  9095. ret = RetrySendAlert(ssl);
  9096. if (ret != 0) {
  9097. ssl->error = ret;
  9098. WOLFSSL_ERROR(ssl->error);
  9099. return WOLFSSL_FATAL_ERROR;
  9100. }
  9101. #ifdef WOLFSSL_DTLS13
  9102. if (ssl->options.dtls && ssl->dtls13SendingFragments) {
  9103. if ((ssl->error = Dtls13FragmentsContinue(ssl)) != 0) {
  9104. WOLFSSL_ERROR(ssl->error);
  9105. return WOLFSSL_FATAL_ERROR;
  9106. }
  9107. /* we sent all the fragments. Advance state. */
  9108. ssl->options.connectState++;
  9109. }
  9110. #endif /* WOLFSSL_DTLS13 */
  9111. switch (ssl->options.connectState) {
  9112. case CONNECT_BEGIN:
  9113. /* Always send client hello first. */
  9114. if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
  9115. WOLFSSL_ERROR(ssl->error);
  9116. return WOLFSSL_FATAL_ERROR;
  9117. }
  9118. ssl->options.connectState = CLIENT_HELLO_SENT;
  9119. WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT");
  9120. #ifdef WOLFSSL_EARLY_DATA
  9121. if (ssl->earlyData != no_early_data) {
  9122. #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
  9123. if (!ssl->options.dtls && ssl->options.tls13MiddleBoxCompat) {
  9124. if ((ssl->error = SendChangeCipher(ssl)) != 0) {
  9125. WOLFSSL_ERROR(ssl->error);
  9126. return WOLFSSL_FATAL_ERROR;
  9127. }
  9128. ssl->options.sentChangeCipher = 1;
  9129. }
  9130. #endif
  9131. ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
  9132. return WOLFSSL_SUCCESS;
  9133. }
  9134. #endif
  9135. FALL_THROUGH;
  9136. case CLIENT_HELLO_SENT:
  9137. /* Get the response/s from the server. */
  9138. while (ssl->options.serverState <
  9139. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  9140. if ((ssl->error = ProcessReply(ssl)) < 0) {
  9141. WOLFSSL_ERROR(ssl->error);
  9142. return WOLFSSL_FATAL_ERROR;
  9143. }
  9144. #ifdef WOLFSSL_DTLS13
  9145. if (ssl->options.dtls) {
  9146. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  9147. WOLFSSL_ERROR(ssl->error);
  9148. return WOLFSSL_FATAL_ERROR;
  9149. }
  9150. }
  9151. #endif /* WOLFSSL_DTLS13 */
  9152. }
  9153. if (!ssl->options.tls1_3) {
  9154. #ifndef WOLFSSL_NO_TLS12
  9155. if (ssl->options.downgrade)
  9156. return wolfSSL_connect(ssl);
  9157. #endif
  9158. WOLFSSL_MSG("Client using higher version, fatal error");
  9159. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  9160. return VERSION_ERROR;
  9161. }
  9162. ssl->options.connectState = HELLO_AGAIN;
  9163. WOLFSSL_MSG("connect state: HELLO_AGAIN");
  9164. FALL_THROUGH;
  9165. case HELLO_AGAIN:
  9166. if (ssl->options.certOnly)
  9167. return WOLFSSL_SUCCESS;
  9168. if (ssl->options.serverState ==
  9169. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  9170. #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
  9171. if (!ssl->options.dtls && !ssl->options.sentChangeCipher
  9172. && ssl->options.tls13MiddleBoxCompat) {
  9173. if ((ssl->error = SendChangeCipher(ssl)) != 0) {
  9174. WOLFSSL_ERROR(ssl->error);
  9175. return WOLFSSL_FATAL_ERROR;
  9176. }
  9177. ssl->options.sentChangeCipher = 1;
  9178. }
  9179. #endif
  9180. /* Try again with different security parameters. */
  9181. if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
  9182. WOLFSSL_ERROR(ssl->error);
  9183. return WOLFSSL_FATAL_ERROR;
  9184. }
  9185. }
  9186. ssl->options.connectState = HELLO_AGAIN_REPLY;
  9187. WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY");
  9188. FALL_THROUGH;
  9189. case HELLO_AGAIN_REPLY:
  9190. /* Get the response/s from the server. */
  9191. while (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
  9192. if ((ssl->error = ProcessReply(ssl)) < 0) {
  9193. WOLFSSL_ERROR(ssl->error);
  9194. return WOLFSSL_FATAL_ERROR;
  9195. }
  9196. #ifdef WOLFSSL_DTLS13
  9197. if (ssl->options.dtls) {
  9198. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  9199. WOLFSSL_ERROR(ssl->error);
  9200. return WOLFSSL_FATAL_ERROR;
  9201. }
  9202. }
  9203. #endif /* WOLFSSL_DTLS13 */
  9204. }
  9205. ssl->options.connectState = FIRST_REPLY_DONE;
  9206. WOLFSSL_MSG("connect state: FIRST_REPLY_DONE");
  9207. FALL_THROUGH;
  9208. case FIRST_REPLY_DONE:
  9209. #ifdef WOLFSSL_EARLY_DATA
  9210. if (!ssl->options.dtls && ssl->earlyData != no_early_data
  9211. && !WOLFSSL_IS_QUIC(ssl)) {
  9212. if ((ssl->error = SendTls13EndOfEarlyData(ssl)) != 0) {
  9213. WOLFSSL_ERROR(ssl->error);
  9214. return WOLFSSL_FATAL_ERROR;
  9215. }
  9216. WOLFSSL_MSG("sent: end_of_early_data");
  9217. }
  9218. #endif
  9219. ssl->options.connectState = FIRST_REPLY_FIRST;
  9220. WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST");
  9221. FALL_THROUGH;
  9222. case FIRST_REPLY_FIRST:
  9223. #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
  9224. if (!ssl->options.sentChangeCipher && !ssl->options.dtls
  9225. && ssl->options.tls13MiddleBoxCompat) {
  9226. if ((ssl->error = SendChangeCipher(ssl)) != 0) {
  9227. WOLFSSL_ERROR(ssl->error);
  9228. return WOLFSSL_FATAL_ERROR;
  9229. }
  9230. ssl->options.sentChangeCipher = 1;
  9231. }
  9232. #endif
  9233. ssl->options.connectState = FIRST_REPLY_SECOND;
  9234. WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
  9235. FALL_THROUGH;
  9236. case FIRST_REPLY_SECOND:
  9237. /* CLIENT: check peer authentication. */
  9238. if (!ssl->options.peerAuthGood) {
  9239. WOLFSSL_MSG("Server authentication did not happen");
  9240. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  9241. return WOLFSSL_FATAL_ERROR;
  9242. }
  9243. #ifndef NO_CERTS
  9244. if (!ssl->options.resuming && ssl->options.sendVerify) {
  9245. ssl->error = SendTls13Certificate(ssl);
  9246. if (ssl->error != 0) {
  9247. #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
  9248. ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
  9249. #endif
  9250. WOLFSSL_ERROR(ssl->error);
  9251. return WOLFSSL_FATAL_ERROR;
  9252. }
  9253. WOLFSSL_MSG("sent: certificate");
  9254. }
  9255. #endif
  9256. ssl->options.connectState = FIRST_REPLY_THIRD;
  9257. WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
  9258. FALL_THROUGH;
  9259. case FIRST_REPLY_THIRD:
  9260. #if (!defined(NO_CERTS) && (!defined(NO_RSA) || defined(HAVE_ECC) || \
  9261. defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  9262. defined(HAVE_PQC))) && (!defined(NO_WOLFSSL_SERVER) || \
  9263. !defined(WOLFSSL_NO_CLIENT_AUTH))
  9264. if (!ssl->options.resuming && ssl->options.sendVerify) {
  9265. ssl->error = SendTls13CertificateVerify(ssl);
  9266. if (ssl->error != 0) {
  9267. #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
  9268. ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
  9269. #endif
  9270. WOLFSSL_ERROR(ssl->error);
  9271. return WOLFSSL_FATAL_ERROR;
  9272. }
  9273. WOLFSSL_MSG("sent: certificate verify");
  9274. }
  9275. #endif
  9276. ssl->options.connectState = FIRST_REPLY_FOURTH;
  9277. WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
  9278. FALL_THROUGH;
  9279. case FIRST_REPLY_FOURTH:
  9280. if ((ssl->error = SendTls13Finished(ssl)) != 0) {
  9281. #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
  9282. ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
  9283. #endif
  9284. WOLFSSL_ERROR(ssl->error);
  9285. return WOLFSSL_FATAL_ERROR;
  9286. }
  9287. WOLFSSL_MSG("sent: finished");
  9288. #ifdef WOLFSSL_DTLS13
  9289. ssl->options.connectState = WAIT_FINISHED_ACK;
  9290. WOLFSSL_MSG("connect state: WAIT_FINISHED_ACK");
  9291. FALL_THROUGH;
  9292. case WAIT_FINISHED_ACK:
  9293. if (ssl->options.dtls) {
  9294. while (ssl->options.serverState != SERVER_FINISHED_ACKED) {
  9295. if ((ssl->error = ProcessReply(ssl)) < 0) {
  9296. WOLFSSL_ERROR(ssl->error);
  9297. return WOLFSSL_FATAL_ERROR;
  9298. }
  9299. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  9300. WOLFSSL_ERROR(ssl->error);
  9301. return WOLFSSL_FATAL_ERROR;
  9302. }
  9303. }
  9304. }
  9305. #endif /* WOLFSSL_DTLS13 */
  9306. ssl->options.connectState = FINISHED_DONE;
  9307. WOLFSSL_MSG("connect state: FINISHED_DONE");
  9308. FALL_THROUGH;
  9309. case FINISHED_DONE:
  9310. #ifndef NO_HANDSHAKE_DONE_CB
  9311. if (ssl->hsDoneCb != NULL) {
  9312. int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
  9313. if (cbret < 0) {
  9314. ssl->error = cbret;
  9315. WOLFSSL_ERROR_VERBOSE(ssl->error);
  9316. WOLFSSL_MSG("HandShake Done Cb don't continue error");
  9317. return WOLFSSL_FATAL_ERROR;
  9318. }
  9319. }
  9320. #endif /* NO_HANDSHAKE_DONE_CB */
  9321. if (!ssl->options.keepResources) {
  9322. FreeHandshakeResources(ssl);
  9323. }
  9324. #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
  9325. /* Free the remaining async context if not using it for crypto */
  9326. FreeAsyncCtx(ssl, 1);
  9327. #endif
  9328. ssl->error = 0; /* clear the error */
  9329. WOLFSSL_LEAVE("wolfSSL_connect_TLSv13()", WOLFSSL_SUCCESS);
  9330. return WOLFSSL_SUCCESS;
  9331. default:
  9332. WOLFSSL_MSG("Unknown connect state ERROR");
  9333. return WOLFSSL_FATAL_ERROR; /* unknown connect state */
  9334. }
  9335. }
  9336. #endif
  9337. #if defined(WOLFSSL_SEND_HRR_COOKIE)
  9338. /* Send a cookie with the HelloRetryRequest to avoid storing state.
  9339. *
  9340. * ssl SSL/TLS object.
  9341. * secret Secret to use when generating integrity check for cookie.
  9342. * A value of NULL indicates to generate a new random secret.
  9343. * secretSz Size of secret data in bytes.
  9344. * Use a value of 0 to indicate use of default size.
  9345. * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3, SIDE_ERROR when
  9346. * called on a client; WOLFSSL_SUCCESS on success and otherwise failure.
  9347. */
  9348. int wolfSSL_send_hrr_cookie(WOLFSSL* ssl, const unsigned char* secret,
  9349. unsigned int secretSz)
  9350. {
  9351. int ret;
  9352. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9353. return BAD_FUNC_ARG;
  9354. #ifndef NO_WOLFSSL_SERVER
  9355. if (ssl->options.side == WOLFSSL_CLIENT_END)
  9356. return SIDE_ERROR;
  9357. if (secretSz == 0) {
  9358. #if !defined(NO_SHA) && defined(NO_SHA256)
  9359. secretSz = WC_SHA_DIGEST_SIZE;
  9360. #endif /* NO_SHA */
  9361. #ifndef NO_SHA256
  9362. secretSz = WC_SHA256_DIGEST_SIZE;
  9363. #endif /* NO_SHA256 */
  9364. }
  9365. if (secretSz != ssl->buffers.tls13CookieSecret.length) {
  9366. byte* newSecret;
  9367. if (ssl->buffers.tls13CookieSecret.buffer != NULL) {
  9368. ForceZero(ssl->buffers.tls13CookieSecret.buffer,
  9369. ssl->buffers.tls13CookieSecret.length);
  9370. XFREE(ssl->buffers.tls13CookieSecret.buffer,
  9371. ssl->heap, DYNAMIC_TYPE_COOKIE_PWD);
  9372. }
  9373. newSecret = (byte*)XMALLOC(secretSz, ssl->heap,
  9374. DYNAMIC_TYPE_COOKIE_PWD);
  9375. if (newSecret == NULL) {
  9376. ssl->buffers.tls13CookieSecret.buffer = NULL;
  9377. ssl->buffers.tls13CookieSecret.length = 0;
  9378. WOLFSSL_MSG("couldn't allocate new cookie secret");
  9379. return MEMORY_ERROR;
  9380. }
  9381. ssl->buffers.tls13CookieSecret.buffer = newSecret;
  9382. ssl->buffers.tls13CookieSecret.length = secretSz;
  9383. #ifdef WOLFSSL_CHECK_MEM_ZERO
  9384. wc_MemZero_Add("wolfSSL_send_hrr_cookie secret",
  9385. ssl->buffers.tls13CookieSecret.buffer,
  9386. ssl->buffers.tls13CookieSecret.length);
  9387. #endif
  9388. }
  9389. /* If the supplied secret is NULL, randomly generate a new secret. */
  9390. if (secret == NULL) {
  9391. ret = wc_RNG_GenerateBlock(ssl->rng,
  9392. ssl->buffers.tls13CookieSecret.buffer, secretSz);
  9393. if (ret < 0)
  9394. return ret;
  9395. }
  9396. else
  9397. XMEMCPY(ssl->buffers.tls13CookieSecret.buffer, secret, secretSz);
  9398. ssl->options.sendCookie = 1;
  9399. ret = WOLFSSL_SUCCESS;
  9400. #else
  9401. (void)secret;
  9402. (void)secretSz;
  9403. ret = SIDE_ERROR;
  9404. #endif
  9405. return ret;
  9406. }
  9407. #endif
  9408. #ifdef HAVE_SUPPORTED_CURVES
  9409. /* Create a key share entry from group.
  9410. * Generates a key pair.
  9411. *
  9412. * ssl The SSL/TLS object.
  9413. * group The named group.
  9414. * returns 0 on success, otherwise failure.
  9415. * for async can return WC_PENDING_E and should be called again
  9416. */
  9417. int wolfSSL_UseKeyShare(WOLFSSL* ssl, word16 group)
  9418. {
  9419. int ret;
  9420. if (ssl == NULL)
  9421. return BAD_FUNC_ARG;
  9422. #ifdef WOLFSSL_ASYNC_CRYPT
  9423. ret = wolfSSL_AsyncPop(ssl, NULL);
  9424. if (ret != WC_NOT_PENDING_E) {
  9425. /* Check for error */
  9426. if (ret < 0)
  9427. return ret;
  9428. }
  9429. #endif
  9430. #ifdef HAVE_PQC
  9431. if (group >= WOLFSSL_PQC_MIN &&
  9432. group <= WOLFSSL_PQC_MAX) {
  9433. if (ssl->ctx != NULL && ssl->ctx->method != NULL &&
  9434. ssl->ctx->method->version.minor != TLSv1_3_MINOR) {
  9435. return BAD_FUNC_ARG;
  9436. }
  9437. if (ssl->options.side == WOLFSSL_SERVER_END) {
  9438. /* If I am the server of a KEM connection, do not do keygen because I'm
  9439. * going to encapsulate with the client's public key. Note that I might
  9440. * be the client and ssl->option.side has not been properly set yet. In
  9441. * that case the KeyGen operation will be deferred to connection time. */
  9442. return WOLFSSL_SUCCESS;
  9443. }
  9444. }
  9445. #endif
  9446. #if defined(NO_TLS)
  9447. (void)ret;
  9448. (void)group;
  9449. #else
  9450. ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL);
  9451. if (ret != 0)
  9452. return ret;
  9453. #endif /* NO_TLS */
  9454. return WOLFSSL_SUCCESS;
  9455. }
  9456. /* Send no key share entries - use HelloRetryRequest to negotiate shared group.
  9457. *
  9458. * ssl The SSL/TLS object.
  9459. * returns 0 on success, otherwise failure.
  9460. */
  9461. int wolfSSL_NoKeyShares(WOLFSSL* ssl)
  9462. {
  9463. int ret;
  9464. if (ssl == NULL)
  9465. return BAD_FUNC_ARG;
  9466. if (ssl->options.side == WOLFSSL_SERVER_END)
  9467. return SIDE_ERROR;
  9468. #if defined(NO_TLS)
  9469. (void)ret;
  9470. #else
  9471. ret = TLSX_KeyShare_Empty(ssl);
  9472. if (ret != 0)
  9473. return ret;
  9474. #endif /* NO_TLS */
  9475. return WOLFSSL_SUCCESS;
  9476. }
  9477. #endif
  9478. /* Do not send a ticket after TLS v1.3 handshake for resumption.
  9479. *
  9480. * ctx The SSL/TLS CTX object.
  9481. * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
  9482. */
  9483. int wolfSSL_CTX_no_ticket_TLSv13(WOLFSSL_CTX* ctx)
  9484. {
  9485. if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
  9486. return BAD_FUNC_ARG;
  9487. if (ctx->method->side == WOLFSSL_CLIENT_END)
  9488. return SIDE_ERROR;
  9489. #ifdef HAVE_SESSION_TICKET
  9490. ctx->noTicketTls13 = 1;
  9491. #endif
  9492. return 0;
  9493. }
  9494. /* Do not send a ticket after TLS v1.3 handshake for resumption.
  9495. *
  9496. * ssl The SSL/TLS object.
  9497. * returns BAD_FUNC_ARG when ssl is NULL, not using TLS v1.3, or called on
  9498. * a client and 0 on success.
  9499. */
  9500. int wolfSSL_no_ticket_TLSv13(WOLFSSL* ssl)
  9501. {
  9502. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9503. return BAD_FUNC_ARG;
  9504. if (ssl->options.side == WOLFSSL_CLIENT_END)
  9505. return SIDE_ERROR;
  9506. #ifdef HAVE_SESSION_TICKET
  9507. ssl->options.noTicketTls13 = 1;
  9508. #endif
  9509. return 0;
  9510. }
  9511. /* Disallow (EC)DHE key exchange when using pre-shared keys.
  9512. *
  9513. * ctx The SSL/TLS CTX object.
  9514. * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
  9515. */
  9516. int wolfSSL_CTX_no_dhe_psk(WOLFSSL_CTX* ctx)
  9517. {
  9518. if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
  9519. return BAD_FUNC_ARG;
  9520. ctx->noPskDheKe = 1;
  9521. return 0;
  9522. }
  9523. /* Disallow (EC)DHE key exchange when using pre-shared keys.
  9524. *
  9525. * ssl The SSL/TLS object.
  9526. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3 and 0 on
  9527. * success.
  9528. */
  9529. int wolfSSL_no_dhe_psk(WOLFSSL* ssl)
  9530. {
  9531. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9532. return BAD_FUNC_ARG;
  9533. ssl->options.noPskDheKe = 1;
  9534. return 0;
  9535. }
  9536. /* Update the keys for encryption and decryption.
  9537. * If using non-blocking I/O and WOLFSSL_ERROR_WANT_WRITE is returned then
  9538. * calling wolfSSL_write() will have the message sent when ready.
  9539. *
  9540. * ssl The SSL/TLS object.
  9541. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
  9542. * WOLFSSL_ERROR_WANT_WRITE when non-blocking I/O is not ready to write,
  9543. * WOLFSSL_SUCCESS on success and otherwise failure.
  9544. */
  9545. int wolfSSL_update_keys(WOLFSSL* ssl)
  9546. {
  9547. int ret;
  9548. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9549. return BAD_FUNC_ARG;
  9550. #ifdef WOLFSSL_DTLS13
  9551. /* we are already waiting for the ack of a sent key update message. We can't
  9552. send another one before receiving its ack. Either wolfSSL_update_keys()
  9553. was invoked multiple times over a short period of time or we replied to a
  9554. KeyUpdate with update request. We'll just ignore sending this
  9555. KeyUpdate. */
  9556. /* TODO: add WOLFSSL_ERROR_ALREADY_IN_PROGRESS type of error here */
  9557. if (ssl->options.dtls && ssl->dtls13WaitKeyUpdateAck)
  9558. return WOLFSSL_SUCCESS;
  9559. #endif /* WOLFSSL_DTLS13 */
  9560. ret = SendTls13KeyUpdate(ssl);
  9561. if (ret == WANT_WRITE)
  9562. ret = WOLFSSL_ERROR_WANT_WRITE;
  9563. else if (ret == 0)
  9564. ret = WOLFSSL_SUCCESS;
  9565. return ret;
  9566. }
  9567. /* Whether a response is waiting for key update request.
  9568. *
  9569. * ssl The SSL/TLS object.
  9570. * required 0 when no key update response required.
  9571. * 1 when no key update response required.
  9572. * return 0 on success.
  9573. * return BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3
  9574. */
  9575. int wolfSSL_key_update_response(WOLFSSL* ssl, int* required)
  9576. {
  9577. if (required == NULL || ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9578. return BAD_FUNC_ARG;
  9579. *required = ssl->keys.updateResponseReq;
  9580. return 0;
  9581. }
  9582. #if !defined(NO_CERTS) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  9583. /* Allow post-handshake authentication in TLS v1.3 connections.
  9584. *
  9585. * ctx The SSL/TLS CTX object.
  9586. * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a client and
  9587. * 0 on success.
  9588. */
  9589. int wolfSSL_CTX_allow_post_handshake_auth(WOLFSSL_CTX* ctx)
  9590. {
  9591. if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
  9592. return BAD_FUNC_ARG;
  9593. if (ctx->method->side == WOLFSSL_SERVER_END)
  9594. return SIDE_ERROR;
  9595. ctx->postHandshakeAuth = 1;
  9596. return 0;
  9597. }
  9598. /* Allow post-handshake authentication in TLS v1.3 connection.
  9599. *
  9600. * ssl The SSL/TLS object.
  9601. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
  9602. * SIDE_ERROR when not a client and 0 on success.
  9603. */
  9604. int wolfSSL_allow_post_handshake_auth(WOLFSSL* ssl)
  9605. {
  9606. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9607. return BAD_FUNC_ARG;
  9608. if (ssl->options.side == WOLFSSL_SERVER_END)
  9609. return SIDE_ERROR;
  9610. ssl->options.postHandshakeAuth = 1;
  9611. return 0;
  9612. }
  9613. /* Request a certificate of the client.
  9614. * Can be called any time after handshake completion.
  9615. * A maximum of 256 requests can be sent on a connection.
  9616. *
  9617. * ssl SSL/TLS object.
  9618. */
  9619. int wolfSSL_request_certificate(WOLFSSL* ssl)
  9620. {
  9621. int ret;
  9622. #ifndef NO_WOLFSSL_SERVER
  9623. CertReqCtx* certReqCtx;
  9624. #endif
  9625. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9626. return BAD_FUNC_ARG;
  9627. #ifndef NO_WOLFSSL_SERVER
  9628. if (ssl->options.side == WOLFSSL_CLIENT_END)
  9629. return SIDE_ERROR;
  9630. if (ssl->options.handShakeState != HANDSHAKE_DONE)
  9631. return NOT_READY_ERROR;
  9632. if (!ssl->options.postHandshakeAuth)
  9633. return POST_HAND_AUTH_ERROR;
  9634. certReqCtx = (CertReqCtx*)XMALLOC(sizeof(CertReqCtx), ssl->heap,
  9635. DYNAMIC_TYPE_TMP_BUFFER);
  9636. if (certReqCtx == NULL)
  9637. return MEMORY_E;
  9638. XMEMSET(certReqCtx, 0, sizeof(CertReqCtx));
  9639. certReqCtx->next = ssl->certReqCtx;
  9640. certReqCtx->len = 1;
  9641. if (certReqCtx->next != NULL)
  9642. certReqCtx->ctx = certReqCtx->next->ctx + 1;
  9643. ssl->certReqCtx = certReqCtx;
  9644. ssl->msgsReceived.got_certificate = 0;
  9645. ssl->msgsReceived.got_certificate_verify = 0;
  9646. ssl->msgsReceived.got_finished = 0;
  9647. ret = SendTls13CertificateRequest(ssl, &certReqCtx->ctx, certReqCtx->len);
  9648. if (ret == WANT_WRITE)
  9649. ret = WOLFSSL_ERROR_WANT_WRITE;
  9650. else if (ret == 0)
  9651. ret = WOLFSSL_SUCCESS;
  9652. #else
  9653. ret = SIDE_ERROR;
  9654. #endif
  9655. return ret;
  9656. }
  9657. #endif /* !NO_CERTS && WOLFSSL_POST_HANDSHAKE_AUTH */
  9658. #if !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  9659. /* Get the preferred key exchange group.
  9660. *
  9661. * ssl The SSL/TLS object.
  9662. * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3,
  9663. * SIDE_ERROR when not a client, NOT_READY_ERROR when handshake not complete
  9664. * and group number on success.
  9665. */
  9666. int wolfSSL_preferred_group(WOLFSSL* ssl)
  9667. {
  9668. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  9669. return BAD_FUNC_ARG;
  9670. #ifndef NO_WOLFSSL_CLIENT
  9671. if (ssl->options.side == WOLFSSL_SERVER_END)
  9672. return SIDE_ERROR;
  9673. if (ssl->options.handShakeState != HANDSHAKE_DONE)
  9674. return NOT_READY_ERROR;
  9675. #ifdef HAVE_SUPPORTED_CURVES
  9676. /* Return supported groups only. */
  9677. return TLSX_SupportedCurve_Preferred(ssl, 1);
  9678. #else
  9679. return 0;
  9680. #endif
  9681. #else
  9682. return SIDE_ERROR;
  9683. #endif
  9684. }
  9685. #endif
  9686. #if defined(HAVE_SUPPORTED_CURVES)
  9687. /* Sets the key exchange groups in rank order on a context.
  9688. *
  9689. * ctx SSL/TLS context object.
  9690. * groups Array of groups.
  9691. * count Number of groups in array.
  9692. * returns BAD_FUNC_ARG when ctx or groups is NULL, not using TLS v1.3 or
  9693. * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success.
  9694. */
  9695. int wolfSSL_CTX_set_groups(WOLFSSL_CTX* ctx, int* groups, int count)
  9696. {
  9697. int ret, i;
  9698. WOLFSSL_ENTER("wolfSSL_CTX_set_groups");
  9699. if (ctx == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT)
  9700. return BAD_FUNC_ARG;
  9701. if (!IsAtLeastTLSv1_3(ctx->method->version))
  9702. return BAD_FUNC_ARG;
  9703. ctx->numGroups = 0;
  9704. #if !defined(NO_TLS)
  9705. TLSX_Remove(&ctx->extensions, TLSX_SUPPORTED_GROUPS, ctx->heap);
  9706. #endif /* !NO_TLS */
  9707. for (i = 0; i < count; i++) {
  9708. /* Call to wolfSSL_CTX_UseSupportedCurve also checks if input groups
  9709. * are valid */
  9710. if ((ret = wolfSSL_CTX_UseSupportedCurve(ctx, (word16)groups[i]))
  9711. != WOLFSSL_SUCCESS) {
  9712. #if !defined(NO_TLS)
  9713. TLSX_Remove(&ctx->extensions, TLSX_SUPPORTED_GROUPS, ctx->heap);
  9714. #endif /* !NO_TLS */
  9715. return ret;
  9716. }
  9717. ctx->group[i] = (word16)groups[i];
  9718. }
  9719. ctx->numGroups = (byte)count;
  9720. return WOLFSSL_SUCCESS;
  9721. }
  9722. /* Sets the key exchange groups in rank order.
  9723. *
  9724. * ssl SSL/TLS object.
  9725. * groups Array of groups.
  9726. * count Number of groups in array.
  9727. * returns BAD_FUNC_ARG when ssl or groups is NULL, not using TLS v1.3 or
  9728. * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success.
  9729. */
  9730. int wolfSSL_set_groups(WOLFSSL* ssl, int* groups, int count)
  9731. {
  9732. int ret, i;
  9733. WOLFSSL_ENTER("wolfSSL_set_groups");
  9734. if (ssl == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT)
  9735. return BAD_FUNC_ARG;
  9736. if (!IsAtLeastTLSv1_3(ssl->version))
  9737. return BAD_FUNC_ARG;
  9738. ssl->numGroups = 0;
  9739. #if !defined(NO_TLS)
  9740. TLSX_Remove(&ssl->extensions, TLSX_SUPPORTED_GROUPS, ssl->heap);
  9741. #endif /* !NO_TLS */
  9742. for (i = 0; i < count; i++) {
  9743. /* Call to wolfSSL_UseSupportedCurve also checks if input groups
  9744. * are valid */
  9745. if ((ret = wolfSSL_UseSupportedCurve(ssl, (word16)groups[i]))
  9746. != WOLFSSL_SUCCESS) {
  9747. #if !defined(NO_TLS)
  9748. TLSX_Remove(&ssl->extensions, TLSX_SUPPORTED_GROUPS, ssl->heap);
  9749. #endif /* !NO_TLS */
  9750. return ret;
  9751. }
  9752. ssl->group[i] = (word16)groups[i];
  9753. }
  9754. ssl->numGroups = (byte)count;
  9755. return WOLFSSL_SUCCESS;
  9756. }
  9757. #endif /* HAVE_SUPPORTED_CURVES */
  9758. #ifndef NO_PSK
  9759. /* Set the PSK callback, that is passed the cipher suite, for a client to use
  9760. * against context object.
  9761. *
  9762. * @param [in, out] ctx SSL/TLS context object.
  9763. * @param [in] cb Client PSK callback passed a cipher suite.
  9764. */
  9765. void wolfSSL_CTX_set_psk_client_cs_callback(WOLFSSL_CTX* ctx,
  9766. wc_psk_client_cs_callback cb)
  9767. {
  9768. WOLFSSL_ENTER("SSL_CTX_set_psk_client_cs_callback");
  9769. if (ctx == NULL)
  9770. return;
  9771. ctx->havePSK = 1;
  9772. ctx->client_psk_cs_cb = cb;
  9773. }
  9774. /* Set the PSK callback, that is passed the cipher suite, for a client to use
  9775. * against SSL object.
  9776. *
  9777. * @param [in, out] ssl SSL/TLS object.
  9778. * @param [in] cb Client PSK callback passed a cipher suite.
  9779. */
  9780. void wolfSSL_set_psk_client_cs_callback(WOLFSSL* ssl,
  9781. wc_psk_client_cs_callback cb)
  9782. {
  9783. byte haveRSA = 1;
  9784. int keySz = 0;
  9785. WOLFSSL_ENTER("SSL_set_psk_client_cs_callback");
  9786. if (ssl == NULL)
  9787. return;
  9788. ssl->options.havePSK = 1;
  9789. ssl->options.client_psk_cs_cb = cb;
  9790. #ifdef NO_RSA
  9791. haveRSA = 0;
  9792. #endif
  9793. #ifndef NO_CERTS
  9794. keySz = ssl->buffers.keySz;
  9795. #endif
  9796. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
  9797. ssl->options.haveDH, ssl->options.haveECDSAsig,
  9798. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  9799. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  9800. ssl->options.haveAnon, TRUE, ssl->options.side);
  9801. }
  9802. /* Set the PSK callback that returns the cipher suite for a client to use
  9803. * against context object.
  9804. *
  9805. * @param [in, out] ctx SSL/TLS context object.
  9806. * @param [in] cb Client PSK callback returning cipher suite.
  9807. */
  9808. void wolfSSL_CTX_set_psk_client_tls13_callback(WOLFSSL_CTX* ctx,
  9809. wc_psk_client_tls13_callback cb)
  9810. {
  9811. WOLFSSL_ENTER("SSL_CTX_set_psk_client_tls13_callback");
  9812. if (ctx == NULL)
  9813. return;
  9814. ctx->havePSK = 1;
  9815. ctx->client_psk_tls13_cb = cb;
  9816. }
  9817. /* Set the PSK callback that returns the cipher suite for a client to use
  9818. * against SSL object.
  9819. *
  9820. * @param [in, out] ssl SSL/TLS object.
  9821. * @param [in] cb Client PSK callback returning cipher suite.
  9822. */
  9823. void wolfSSL_set_psk_client_tls13_callback(WOLFSSL* ssl,
  9824. wc_psk_client_tls13_callback cb)
  9825. {
  9826. byte haveRSA = 1;
  9827. int keySz = 0;
  9828. WOLFSSL_ENTER("SSL_set_psk_client_tls13_callback");
  9829. if (ssl == NULL)
  9830. return;
  9831. ssl->options.havePSK = 1;
  9832. ssl->options.client_psk_tls13_cb = cb;
  9833. #ifdef NO_RSA
  9834. haveRSA = 0;
  9835. #endif
  9836. #ifndef NO_CERTS
  9837. keySz = ssl->buffers.keySz;
  9838. #endif
  9839. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
  9840. ssl->options.haveDH, ssl->options.haveECDSAsig,
  9841. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  9842. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  9843. ssl->options.haveAnon, TRUE, ssl->options.side);
  9844. }
  9845. /* Set the PSK callback that returns the cipher suite for a server to use
  9846. * against context object.
  9847. *
  9848. * @param [in, out] ctx SSL/TLS context object.
  9849. * @param [in] cb Server PSK callback returning cipher suite.
  9850. */
  9851. void wolfSSL_CTX_set_psk_server_tls13_callback(WOLFSSL_CTX* ctx,
  9852. wc_psk_server_tls13_callback cb)
  9853. {
  9854. WOLFSSL_ENTER("SSL_CTX_set_psk_server_tls13_callback");
  9855. if (ctx == NULL)
  9856. return;
  9857. ctx->havePSK = 1;
  9858. ctx->server_psk_tls13_cb = cb;
  9859. }
  9860. /* Set the PSK callback that returns the cipher suite for a server to use
  9861. * against SSL object.
  9862. *
  9863. * @param [in, out] ssl SSL/TLS object.
  9864. * @param [in] cb Server PSK callback returning cipher suite.
  9865. */
  9866. void wolfSSL_set_psk_server_tls13_callback(WOLFSSL* ssl,
  9867. wc_psk_server_tls13_callback cb)
  9868. {
  9869. byte haveRSA = 1;
  9870. int keySz = 0;
  9871. WOLFSSL_ENTER("SSL_set_psk_server_tls13_callback");
  9872. if (ssl == NULL)
  9873. return;
  9874. ssl->options.havePSK = 1;
  9875. ssl->options.server_psk_tls13_cb = cb;
  9876. #ifdef NO_RSA
  9877. haveRSA = 0;
  9878. #endif
  9879. #ifndef NO_CERTS
  9880. keySz = ssl->buffers.keySz;
  9881. #endif
  9882. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
  9883. ssl->options.haveDH, ssl->options.haveECDSAsig,
  9884. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  9885. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  9886. ssl->options.haveAnon, TRUE, ssl->options.side);
  9887. }
  9888. /* Get name of first supported cipher suite that uses the hash indicated.
  9889. *
  9890. * @param [in] ssl SSL/TLS object.
  9891. * @param [in] hash Name of hash algorithm. e.g. "SHA256", "SHA384"
  9892. * @return Name of cipher suite.
  9893. * @return NULL on failure.
  9894. */
  9895. const char* wolfSSL_get_cipher_name_by_hash(WOLFSSL* ssl, const char* hash)
  9896. {
  9897. const char* name = NULL;
  9898. byte mac = no_mac;
  9899. int i;
  9900. if (XSTRCMP(hash, "SHA256") == 0) {
  9901. mac = sha256_mac;
  9902. }
  9903. else if (XSTRCMP(hash, "SHA384") == 0) {
  9904. mac = sha384_mac;
  9905. }
  9906. if (mac != no_mac) {
  9907. for (i = 0; i < ssl->suites->suiteSz; i += 2) {
  9908. if (SuiteMac(ssl->suites->suites + i) == mac) {
  9909. name = GetCipherNameInternal(ssl->suites->suites[i + 0],
  9910. ssl->suites->suites[i + 1]);
  9911. break;
  9912. }
  9913. }
  9914. }
  9915. return name;
  9916. }
  9917. #endif /* !NO_PSK */
  9918. #ifndef NO_WOLFSSL_SERVER
  9919. /* The server accepting a connection from a client.
  9920. * The protocol version is expecting to be TLS v1.3.
  9921. * If the client downgrades, and older versions of the protocol are compiled
  9922. * in, the server will fallback to wolfSSL_accept().
  9923. * Please see note at top of README if you get an error from accept.
  9924. *
  9925. * ssl The SSL/TLS object.
  9926. * returns WOLFSSL_SUCCESS on successful handshake, WOLFSSL_FATAL_ERROR when
  9927. * unrecoverable error occurs and 0 otherwise.
  9928. * For more error information use wolfSSL_get_error().
  9929. */
  9930. int wolfSSL_accept_TLSv13(WOLFSSL* ssl)
  9931. {
  9932. #if !defined(NO_CERTS) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  9933. word16 havePSK = 0;
  9934. #endif
  9935. int advanceState;
  9936. int ret = 0;
  9937. WOLFSSL_ENTER("SSL_accept_TLSv13()");
  9938. #ifdef HAVE_ERRNO_H
  9939. errno = 0;
  9940. #endif
  9941. #if !defined(NO_CERTS) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  9942. havePSK = ssl->options.havePSK;
  9943. #endif
  9944. if (ssl->options.side != WOLFSSL_SERVER_END) {
  9945. ssl->error = SIDE_ERROR;
  9946. WOLFSSL_ERROR(ssl->error);
  9947. return WOLFSSL_FATAL_ERROR;
  9948. }
  9949. #ifdef WOLFSSL_WOLFSENTRY_HOOKS
  9950. if ((ssl->AcceptFilter != NULL) &&
  9951. ((ssl->options.acceptState == TLS13_ACCEPT_BEGIN)
  9952. #ifdef HAVE_SECURE_RENEGOTIATION
  9953. || (ssl->options.acceptState == TLS13_ACCEPT_BEGIN_RENEG)
  9954. #endif
  9955. ))
  9956. {
  9957. wolfSSL_netfilter_decision_t res;
  9958. if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) ==
  9959. WOLFSSL_SUCCESS) &&
  9960. (res == WOLFSSL_NETFILTER_REJECT)) {
  9961. ssl->error = SOCKET_FILTERED_E;
  9962. WOLFSSL_ERROR(ssl->error);
  9963. return WOLFSSL_FATAL_ERROR;
  9964. }
  9965. }
  9966. #endif /* WOLFSSL_WOLFSENTRY_HOOKS */
  9967. #ifndef NO_CERTS
  9968. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  9969. if (!havePSK)
  9970. #endif
  9971. {
  9972. #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \
  9973. defined(WOLFSSL_NGINX) || defined (WOLFSSL_HAPROXY)
  9974. if (ssl->ctx->certSetupCb != NULL) {
  9975. WOLFSSL_MSG("CertSetupCb set. server cert and "
  9976. "key not checked");
  9977. }
  9978. else
  9979. #endif
  9980. {
  9981. if (!ssl->buffers.certificate ||
  9982. !ssl->buffers.certificate->buffer) {
  9983. WOLFSSL_MSG("accept error: server cert required");
  9984. ssl->error = NO_PRIVATE_KEY;
  9985. WOLFSSL_ERROR(ssl->error);
  9986. return WOLFSSL_FATAL_ERROR;
  9987. }
  9988. if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
  9989. /* allow no private key if using existing key */
  9990. #ifdef WOLF_PRIVATE_KEY_ID
  9991. if (ssl->devId != INVALID_DEVID
  9992. #ifdef HAVE_PK_CALLBACKS
  9993. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  9994. #endif
  9995. ) {
  9996. WOLFSSL_MSG("Allowing no server private key (external)");
  9997. }
  9998. else
  9999. #endif
  10000. {
  10001. WOLFSSL_MSG("accept error: server key required");
  10002. ssl->error = NO_PRIVATE_KEY;
  10003. WOLFSSL_ERROR(ssl->error);
  10004. return WOLFSSL_FATAL_ERROR;
  10005. }
  10006. }
  10007. }
  10008. }
  10009. #endif /* NO_CERTS */
  10010. if (ssl->buffers.outputBuffer.length > 0
  10011. #ifdef WOLFSSL_ASYNC_CRYPT
  10012. /* do not send buffered or advance state if last error was an
  10013. async pending operation */
  10014. && ssl->error != WC_PENDING_E
  10015. #endif
  10016. ) {
  10017. /* fragOffset is non-zero when sending fragments. On the last
  10018. * fragment, fragOffset is zero again, and the state can be
  10019. * advanced. */
  10020. advanceState =
  10021. (ssl->options.acceptState == TLS13_ACCEPT_CLIENT_HELLO_DONE ||
  10022. ssl->options.acceptState ==
  10023. TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE ||
  10024. ssl->options.acceptState == TLS13_ACCEPT_SECOND_REPLY_DONE ||
  10025. ssl->options.acceptState == TLS13_SERVER_HELLO_SENT ||
  10026. ssl->options.acceptState == TLS13_ACCEPT_THIRD_REPLY_DONE ||
  10027. ssl->options.acceptState == TLS13_SERVER_EXTENSIONS_SENT ||
  10028. ssl->options.acceptState == TLS13_CERT_REQ_SENT ||
  10029. ssl->options.acceptState == TLS13_CERT_SENT ||
  10030. ssl->options.acceptState == TLS13_CERT_VERIFY_SENT ||
  10031. ssl->options.acceptState == TLS13_ACCEPT_FINISHED_SENT ||
  10032. ssl->options.acceptState == TLS13_ACCEPT_FINISHED_DONE);
  10033. #ifdef WOLFSSL_DTLS13
  10034. if (ssl->options.dtls)
  10035. advanceState = advanceState && !ssl->dtls13SendingFragments
  10036. && !ssl->dtls13SendingAckOrRtx;
  10037. #endif /* WOLFSSL_DTLS13 */
  10038. if ((ssl->error = SendBuffered(ssl)) == 0) {
  10039. if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
  10040. if (advanceState) {
  10041. ssl->options.acceptState++;
  10042. WOLFSSL_MSG("accept state: "
  10043. "Advanced from last buffered fragment send");
  10044. #ifdef WOLFSSL_ASYNC_IO
  10045. FreeAsyncCtx(ssl, 0);
  10046. #endif
  10047. }
  10048. }
  10049. else {
  10050. WOLFSSL_MSG("accept state: "
  10051. "Not advanced, more fragments to send");
  10052. }
  10053. #ifdef WOLFSSL_DTLS13
  10054. if (ssl->options.dtls)
  10055. ssl->dtls13SendingAckOrRtx = 0;
  10056. #endif /* WOLFSSL_DTLS13 */
  10057. }
  10058. else {
  10059. ssl->error = ret;
  10060. WOLFSSL_ERROR(ssl->error);
  10061. return WOLFSSL_FATAL_ERROR;
  10062. }
  10063. }
  10064. ret = RetrySendAlert(ssl);
  10065. if (ret != 0) {
  10066. ssl->error = ret;
  10067. WOLFSSL_ERROR(ssl->error);
  10068. return WOLFSSL_FATAL_ERROR;
  10069. }
  10070. #ifdef WOLFSSL_DTLS13
  10071. if (ssl->options.dtls && ssl->dtls13SendingFragments) {
  10072. if ((ssl->error = Dtls13FragmentsContinue(ssl)) != 0) {
  10073. WOLFSSL_ERROR(ssl->error);
  10074. return WOLFSSL_FATAL_ERROR;
  10075. }
  10076. /* we sent all the fragments. Advance state. */
  10077. ssl->options.acceptState++;
  10078. }
  10079. #endif /* WOLFSSL_DTLS13 */
  10080. switch (ssl->options.acceptState) {
  10081. #ifdef HAVE_SECURE_RENEGOTIATION
  10082. case TLS13_ACCEPT_BEGIN_RENEG:
  10083. #endif
  10084. case TLS13_ACCEPT_BEGIN :
  10085. /* get client_hello */
  10086. while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  10087. if ((ssl->error = ProcessReply(ssl)) < 0) {
  10088. WOLFSSL_ERROR(ssl->error);
  10089. return WOLFSSL_FATAL_ERROR;
  10090. }
  10091. #ifdef WOLFSSL_DTLS13
  10092. if (ssl->options.dtls) {
  10093. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  10094. WOLFSSL_ERROR(ssl->error);
  10095. return WOLFSSL_FATAL_ERROR;
  10096. }
  10097. }
  10098. #endif /* WOLFSSL_DTLS13 */
  10099. }
  10100. ssl->options.acceptState = TLS13_ACCEPT_CLIENT_HELLO_DONE;
  10101. WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
  10102. if (!IsAtLeastTLSv1_3(ssl->version))
  10103. return wolfSSL_accept(ssl);
  10104. FALL_THROUGH;
  10105. case TLS13_ACCEPT_CLIENT_HELLO_DONE :
  10106. if (ssl->options.serverState ==
  10107. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  10108. if ((ssl->error = SendTls13ServerHello(ssl,
  10109. hello_retry_request)) != 0) {
  10110. WOLFSSL_ERROR(ssl->error);
  10111. return WOLFSSL_FATAL_ERROR;
  10112. }
  10113. #ifdef WOLFSSL_DTLS13
  10114. if (ssl->options.dtls && wolfSSL_dtls_get_using_nonblock(ssl)) {
  10115. /* Reset the state so that we can statelessly await the
  10116. * ClientHello that contains the cookie. Return a WANT_READ
  10117. * to the user so that we don't drop UDP messages in the
  10118. * network callbacks. */
  10119. /* Reset DTLS window */
  10120. w64Zero(&ssl->dtls13Epochs[0].nextSeqNumber);
  10121. w64Zero(&ssl->dtls13Epochs[0].nextPeerSeqNumber);
  10122. XMEMSET(ssl->dtls13Epochs[0].window, 0,
  10123. sizeof(ssl->dtls13Epochs[0].window));
  10124. ssl->keys.dtls_expected_peer_handshake_number = 0;
  10125. ssl->keys.dtls_handshake_number = 0;
  10126. ssl->msgsReceived.got_client_hello = 0;
  10127. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10128. /* Remove cookie so that it will get computed again */
  10129. TLSX_Remove(&ssl->extensions, TLSX_COOKIE, ssl->heap);
  10130. #endif
  10131. /* Reset states */
  10132. ssl->options.serverState = NULL_STATE;
  10133. ssl->options.clientState = NULL_STATE;
  10134. ssl->options.connectState = CONNECT_BEGIN;
  10135. ssl->options.acceptState = ACCEPT_BEGIN;
  10136. ssl->options.handShakeState = NULL_STATE;
  10137. ssl->error = WANT_READ;
  10138. WOLFSSL_ERROR(ssl->error);
  10139. return WOLFSSL_FATAL_ERROR;
  10140. }
  10141. #endif /* WOLFSSL_DTLS13 */
  10142. }
  10143. ssl->options.acceptState = TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE;
  10144. WOLFSSL_MSG("accept state ACCEPT_HELLO_RETRY_REQUEST_DONE");
  10145. FALL_THROUGH;
  10146. case TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE :
  10147. #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
  10148. if (!ssl->options.dtls && ssl->options.tls13MiddleBoxCompat
  10149. && ssl->options.serverState ==
  10150. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  10151. if ((ssl->error = SendChangeCipher(ssl)) != 0) {
  10152. WOLFSSL_ERROR(ssl->error);
  10153. return WOLFSSL_FATAL_ERROR;
  10154. }
  10155. ssl->options.sentChangeCipher = 1;
  10156. ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
  10157. }
  10158. #endif
  10159. ssl->options.acceptState = TLS13_ACCEPT_FIRST_REPLY_DONE;
  10160. WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
  10161. FALL_THROUGH;
  10162. case TLS13_ACCEPT_FIRST_REPLY_DONE :
  10163. if (ssl->options.serverState ==
  10164. SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
  10165. ssl->options.clientState = CLIENT_HELLO_RETRY;
  10166. while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  10167. if ((ssl->error = ProcessReply(ssl)) < 0) {
  10168. WOLFSSL_ERROR(ssl->error);
  10169. return WOLFSSL_FATAL_ERROR;
  10170. }
  10171. #ifdef WOLFSSL_DTLS13
  10172. if (ssl->options.dtls) {
  10173. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  10174. WOLFSSL_ERROR(ssl->error);
  10175. return WOLFSSL_FATAL_ERROR;
  10176. }
  10177. }
  10178. #endif /* WOLFSSL_DTLS13 */
  10179. }
  10180. }
  10181. #ifdef WOLFSSL_DTLS
  10182. if (ssl->chGoodCb != NULL) {
  10183. int cbret = ssl->chGoodCb(ssl, ssl->chGoodCtx);
  10184. if (cbret < 0) {
  10185. ssl->error = cbret;
  10186. WOLFSSL_MSG("ClientHello Good Cb don't continue error");
  10187. return WOLFSSL_FATAL_ERROR;
  10188. }
  10189. }
  10190. #endif
  10191. ssl->options.acceptState = TLS13_ACCEPT_SECOND_REPLY_DONE;
  10192. WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE");
  10193. FALL_THROUGH;
  10194. case TLS13_ACCEPT_SECOND_REPLY_DONE :
  10195. if ((ssl->error = SendTls13ServerHello(ssl, server_hello)) != 0) {
  10196. WOLFSSL_ERROR(ssl->error);
  10197. return WOLFSSL_FATAL_ERROR;
  10198. }
  10199. ssl->options.acceptState = TLS13_SERVER_HELLO_SENT;
  10200. WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
  10201. FALL_THROUGH;
  10202. case TLS13_SERVER_HELLO_SENT :
  10203. #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
  10204. if (!ssl->options.dtls && ssl->options.tls13MiddleBoxCompat
  10205. && !ssl->options.sentChangeCipher && !ssl->options.dtls) {
  10206. if ((ssl->error = SendChangeCipher(ssl)) != 0) {
  10207. WOLFSSL_ERROR(ssl->error);
  10208. return WOLFSSL_FATAL_ERROR;
  10209. }
  10210. ssl->options.sentChangeCipher = 1;
  10211. }
  10212. #endif
  10213. ssl->options.acceptState = TLS13_ACCEPT_THIRD_REPLY_DONE;
  10214. WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
  10215. FALL_THROUGH;
  10216. case TLS13_ACCEPT_THIRD_REPLY_DONE :
  10217. #ifdef HAVE_SUPPORTED_CURVES
  10218. if (!ssl->options.noPskDheKe) {
  10219. ssl->error = TLSX_KeyShare_DeriveSecret(ssl);
  10220. if (ssl->error != 0)
  10221. return WOLFSSL_FATAL_ERROR;
  10222. }
  10223. #endif
  10224. if ((ssl->error = SendTls13EncryptedExtensions(ssl)) != 0) {
  10225. WOLFSSL_ERROR(ssl->error);
  10226. return WOLFSSL_FATAL_ERROR;
  10227. }
  10228. ssl->options.acceptState = TLS13_SERVER_EXTENSIONS_SENT;
  10229. WOLFSSL_MSG("accept state SERVER_EXTENSIONS_SENT");
  10230. FALL_THROUGH;
  10231. case TLS13_SERVER_EXTENSIONS_SENT :
  10232. #ifndef NO_CERTS
  10233. if (!ssl->options.resuming) {
  10234. if (ssl->options.verifyPeer
  10235. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10236. && !ssl->options.verifyPostHandshake
  10237. #endif
  10238. ) {
  10239. ssl->error = SendTls13CertificateRequest(ssl, NULL, 0);
  10240. if (ssl->error != 0) {
  10241. WOLFSSL_ERROR(ssl->error);
  10242. return WOLFSSL_FATAL_ERROR;
  10243. }
  10244. }
  10245. else {
  10246. /* SERVER: Peer auth good if not verifying client. */
  10247. ssl->options.peerAuthGood = 1;
  10248. }
  10249. }
  10250. #endif
  10251. ssl->options.acceptState = TLS13_CERT_REQ_SENT;
  10252. WOLFSSL_MSG("accept state CERT_REQ_SENT");
  10253. FALL_THROUGH;
  10254. case TLS13_CERT_REQ_SENT :
  10255. #ifndef NO_CERTS
  10256. if (!ssl->options.resuming && ssl->options.sendVerify) {
  10257. if ((ssl->error = SendTls13Certificate(ssl)) != 0) {
  10258. WOLFSSL_ERROR(ssl->error);
  10259. return WOLFSSL_FATAL_ERROR;
  10260. }
  10261. }
  10262. #endif
  10263. ssl->options.acceptState = TLS13_CERT_SENT;
  10264. WOLFSSL_MSG("accept state CERT_SENT");
  10265. FALL_THROUGH;
  10266. case TLS13_CERT_SENT :
  10267. #if !defined(NO_CERTS) && (!defined(NO_RSA) || defined(HAVE_ECC) || \
  10268. defined(HAVE_ED25519) || defined(HAVE_ED448) || defined(HAVE_PQC))
  10269. if (!ssl->options.resuming && ssl->options.sendVerify) {
  10270. if ((ssl->error = SendTls13CertificateVerify(ssl)) != 0) {
  10271. WOLFSSL_ERROR(ssl->error);
  10272. return WOLFSSL_FATAL_ERROR;
  10273. }
  10274. }
  10275. #endif
  10276. ssl->options.acceptState = TLS13_CERT_VERIFY_SENT;
  10277. WOLFSSL_MSG("accept state CERT_VERIFY_SENT");
  10278. FALL_THROUGH;
  10279. case TLS13_CERT_VERIFY_SENT :
  10280. if ((ssl->error = SendTls13Finished(ssl)) != 0) {
  10281. WOLFSSL_ERROR(ssl->error);
  10282. return WOLFSSL_FATAL_ERROR;
  10283. }
  10284. ssl->options.acceptState = TLS13_ACCEPT_FINISHED_SENT;
  10285. WOLFSSL_MSG("accept state ACCEPT_FINISHED_SENT");
  10286. #ifdef WOLFSSL_EARLY_DATA
  10287. if (ssl->earlyData != no_early_data) {
  10288. ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
  10289. return WOLFSSL_SUCCESS;
  10290. }
  10291. #endif
  10292. FALL_THROUGH;
  10293. case TLS13_ACCEPT_FINISHED_SENT :
  10294. #ifdef HAVE_SESSION_TICKET
  10295. #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
  10296. if (!ssl->options.verifyPeer && !ssl->options.noTicketTls13 &&
  10297. ssl->ctx->ticketEncCb != NULL) {
  10298. if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
  10299. WOLFSSL_ERROR(ssl->error);
  10300. return WOLFSSL_FATAL_ERROR;
  10301. }
  10302. ssl->options.ticketsSent = 1;
  10303. }
  10304. #endif
  10305. #endif /* HAVE_SESSION_TICKET */
  10306. ssl->options.acceptState = TLS13_PRE_TICKET_SENT;
  10307. WOLFSSL_MSG("accept state TICKET_SENT");
  10308. FALL_THROUGH;
  10309. case TLS13_PRE_TICKET_SENT :
  10310. while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
  10311. if ( (ssl->error = ProcessReply(ssl)) < 0) {
  10312. WOLFSSL_ERROR(ssl->error);
  10313. return WOLFSSL_FATAL_ERROR;
  10314. }
  10315. #ifdef WOLFSSL_DTLS13
  10316. if (ssl->options.dtls) {
  10317. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  10318. WOLFSSL_ERROR(ssl->error);
  10319. return WOLFSSL_FATAL_ERROR;
  10320. }
  10321. }
  10322. #endif /* WOLFSSL_DTLS13 */
  10323. }
  10324. ssl->options.acceptState = TLS13_ACCEPT_FINISHED_DONE;
  10325. WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
  10326. FALL_THROUGH;
  10327. case TLS13_ACCEPT_FINISHED_DONE :
  10328. /* SERVER: When not resuming and verifying peer but no certificate
  10329. * received and not failing when not received then peer auth good.
  10330. */
  10331. if (!ssl->options.resuming && ssl->options.verifyPeer &&
  10332. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10333. !ssl->options.verifyPostHandshake &&
  10334. #endif
  10335. !ssl->options.havePeerCert && !ssl->options.failNoCert) {
  10336. ssl->options.peerAuthGood = 1;
  10337. }
  10338. /* SERVER: check peer authentication. */
  10339. if (!ssl->options.peerAuthGood) {
  10340. WOLFSSL_MSG("Client authentication did not happen");
  10341. return WOLFSSL_FATAL_ERROR;
  10342. }
  10343. #ifdef HAVE_SESSION_TICKET
  10344. while (ssl->options.ticketsSent < ssl->options.maxTicketTls13) {
  10345. if (!ssl->options.noTicketTls13 && ssl->ctx->ticketEncCb
  10346. != NULL) {
  10347. if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
  10348. WOLFSSL_ERROR(ssl->error);
  10349. return WOLFSSL_FATAL_ERROR;
  10350. }
  10351. }
  10352. ssl->options.ticketsSent++;
  10353. /* only one session ticket is sent on session resumption */
  10354. if (ssl->options.resuming) {
  10355. break;
  10356. }
  10357. }
  10358. #endif /* HAVE_SESSION_TICKET */
  10359. ssl->options.acceptState = TLS13_TICKET_SENT;
  10360. WOLFSSL_MSG("accept state TICKET_SENT");
  10361. FALL_THROUGH;
  10362. case TLS13_TICKET_SENT :
  10363. #ifndef NO_HANDSHAKE_DONE_CB
  10364. if (ssl->hsDoneCb) {
  10365. int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
  10366. if (cbret < 0) {
  10367. ssl->error = cbret;
  10368. WOLFSSL_MSG("HandShake Done Cb don't continue error");
  10369. return WOLFSSL_FATAL_ERROR;
  10370. }
  10371. }
  10372. #endif /* NO_HANDSHAKE_DONE_CB */
  10373. if (!ssl->options.keepResources) {
  10374. FreeHandshakeResources(ssl);
  10375. }
  10376. #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
  10377. /* Free the remaining async context if not using it for crypto */
  10378. FreeAsyncCtx(ssl, 1);
  10379. #endif
  10380. ssl->error = 0; /* clear the error */
  10381. WOLFSSL_LEAVE("SSL_accept()", WOLFSSL_SUCCESS);
  10382. return WOLFSSL_SUCCESS;
  10383. default :
  10384. WOLFSSL_MSG("Unknown accept state ERROR");
  10385. return WOLFSSL_FATAL_ERROR;
  10386. }
  10387. }
  10388. #endif
  10389. #if !defined(NO_WOLFSSL_SERVER) && defined(HAVE_SESSION_TICKET)
  10390. /* Server sends a session ticket to the peer.
  10391. *
  10392. * RFC 8446, section 4.6.1, para 1.
  10393. *
  10394. * ssl The SSL/TLS object.
  10395. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
  10396. * SIDE_ERROR when not a server,
  10397. * NOT_READY_ERROR when handshake not complete,
  10398. * WOLFSSL_FATAL_ERROR when creating or sending message fails, and
  10399. * WOLFSSL_SUCCESS on success.
  10400. */
  10401. int wolfSSL_send_SessionTicket(WOLFSSL* ssl)
  10402. {
  10403. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  10404. return BAD_FUNC_ARG;
  10405. if (ssl->options.side == WOLFSSL_CLIENT_END)
  10406. return SIDE_ERROR;
  10407. if (ssl->options.handShakeState != HANDSHAKE_DONE)
  10408. return NOT_READY_ERROR;
  10409. if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
  10410. WOLFSSL_ERROR(ssl->error);
  10411. return WOLFSSL_FATAL_ERROR;
  10412. }
  10413. ssl->options.ticketsSent++;
  10414. return WOLFSSL_SUCCESS;
  10415. }
  10416. #endif
  10417. #ifdef WOLFSSL_EARLY_DATA
  10418. /* Sets the maximum amount of early data that can be seen by server when using
  10419. * session tickets for resumption.
  10420. * A value of zero indicates no early data is to be sent by client using session
  10421. * tickets.
  10422. *
  10423. * ctx The SSL/TLS CTX object.
  10424. * sz Maximum size of the early data.
  10425. * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
  10426. * 0 on success.
  10427. */
  10428. int wolfSSL_CTX_set_max_early_data(WOLFSSL_CTX* ctx, unsigned int sz)
  10429. {
  10430. if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
  10431. return BAD_FUNC_ARG;
  10432. if (ctx->method->side == WOLFSSL_CLIENT_END)
  10433. return SIDE_ERROR;
  10434. ctx->maxEarlyDataSz = sz;
  10435. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_ERROR_CODE_OPENSSL)
  10436. /* 1 on success in OpenSSL*/
  10437. return WOLFSSL_SUCCESS;
  10438. #else
  10439. return 0;
  10440. #endif
  10441. }
  10442. /* Sets the maximum amount of early data that can be seen by server when using
  10443. * session tickets for resumption.
  10444. * A value of zero indicates no early data is to be sent by client using session
  10445. * tickets.
  10446. *
  10447. * ssl The SSL/TLS object.
  10448. * sz Maximum size of the early data.
  10449. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
  10450. * SIDE_ERROR when not a server and 0 on success.
  10451. */
  10452. int wolfSSL_set_max_early_data(WOLFSSL* ssl, unsigned int sz)
  10453. {
  10454. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  10455. return BAD_FUNC_ARG;
  10456. if (ssl->options.side == WOLFSSL_CLIENT_END)
  10457. return SIDE_ERROR;
  10458. ssl->options.maxEarlyDataSz = sz;
  10459. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_ERROR_CODE_OPENSSL)
  10460. /* 1 on success in OpenSSL*/
  10461. return WOLFSSL_SUCCESS;
  10462. #else
  10463. return 0;
  10464. #endif
  10465. }
  10466. /* Gets the maximum amount of early data that can be seen by server when using
  10467. * session tickets for resumption.
  10468. * A value of zero indicates no early data is to be sent by client using session
  10469. * tickets.
  10470. *
  10471. * ctx The SSL/TLS CTX object.
  10472. * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
  10473. * returns the maximum amount of early data to be set
  10474. */
  10475. int wolfSSL_CTX_get_max_early_data(WOLFSSL_CTX* ctx)
  10476. {
  10477. if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
  10478. return BAD_FUNC_ARG;
  10479. if (ctx->method->side == WOLFSSL_CLIENT_END)
  10480. return SIDE_ERROR;
  10481. return ctx->maxEarlyDataSz;
  10482. }
  10483. /* Gets the maximum amount of early data that can be seen by server when using
  10484. * session tickets for resumption.
  10485. * A value of zero indicates no early data is to be sent by client using session
  10486. * tickets.
  10487. *
  10488. * ssl The SSL/TLS object.
  10489. * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
  10490. * SIDE_ERROR when not a server and
  10491. * returns the maximum amount of early data to be set
  10492. */
  10493. int wolfSSL_get_max_early_data(WOLFSSL* ssl)
  10494. {
  10495. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  10496. return BAD_FUNC_ARG;
  10497. if (ssl->options.side == WOLFSSL_CLIENT_END)
  10498. return SIDE_ERROR;
  10499. return ssl->options.maxEarlyDataSz;
  10500. }
  10501. /* Write early data to the server.
  10502. *
  10503. * ssl The SSL/TLS object.
  10504. * data Early data to write
  10505. * sz The size of the early data in bytes.
  10506. * outSz The number of early data bytes written.
  10507. * returns BAD_FUNC_ARG when: ssl, data or outSz is NULL; sz is negative;
  10508. * or not using TLS v1.3. SIDE ERROR when not a server. Otherwise the number of
  10509. * early data bytes written.
  10510. */
  10511. int wolfSSL_write_early_data(WOLFSSL* ssl, const void* data, int sz, int* outSz)
  10512. {
  10513. int ret = 0;
  10514. WOLFSSL_ENTER("SSL_write_early_data()");
  10515. if (ssl == NULL || data == NULL || sz < 0 || outSz == NULL)
  10516. return BAD_FUNC_ARG;
  10517. if (!IsAtLeastTLSv1_3(ssl->version))
  10518. return BAD_FUNC_ARG;
  10519. #ifndef NO_WOLFSSL_CLIENT
  10520. if (ssl->options.side == WOLFSSL_SERVER_END)
  10521. return SIDE_ERROR;
  10522. if (ssl->options.handShakeState == NULL_STATE) {
  10523. if (ssl->error != WC_PENDING_E)
  10524. ssl->earlyData = expecting_early_data;
  10525. ret = wolfSSL_connect_TLSv13(ssl);
  10526. if (ret != WOLFSSL_SUCCESS)
  10527. return WOLFSSL_FATAL_ERROR;
  10528. /* on client side, status is set to rejected */
  10529. /* until sever accepts the early data extension. */
  10530. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_REJECTED;
  10531. }
  10532. if (ssl->options.handShakeState == CLIENT_HELLO_COMPLETE) {
  10533. #ifdef OPENSSL_EXTRA
  10534. /* when processed early data exceeds max size */
  10535. if (ssl->session->maxEarlyDataSz > 0 &&
  10536. (ssl->earlyDataSz + sz > ssl->session->maxEarlyDataSz)) {
  10537. ssl->error = TOO_MUCH_EARLY_DATA;
  10538. return WOLFSSL_FATAL_ERROR;
  10539. }
  10540. #endif
  10541. ret = SendData(ssl, data, sz);
  10542. if (ret > 0) {
  10543. *outSz = ret;
  10544. /* store amount of processed early data from client */
  10545. ssl->earlyDataSz += ret;
  10546. }
  10547. }
  10548. #else
  10549. return SIDE_ERROR;
  10550. #endif
  10551. WOLFSSL_LEAVE("SSL_write_early_data()", ret);
  10552. if (ret < 0)
  10553. ret = WOLFSSL_FATAL_ERROR;
  10554. return ret;
  10555. }
  10556. /* Read the any early data from the client.
  10557. *
  10558. * ssl The SSL/TLS object.
  10559. * data Buffer to put the early data into.
  10560. * sz The size of the buffer in bytes.
  10561. * outSz The number of early data bytes read.
  10562. * returns BAD_FUNC_ARG when: ssl, data or outSz is NULL; sz is negative;
  10563. * or not using TLS v1.3. SIDE ERROR when not a server. Otherwise the number of
  10564. * early data bytes read.
  10565. */
  10566. int wolfSSL_read_early_data(WOLFSSL* ssl, void* data, int sz, int* outSz)
  10567. {
  10568. int ret = 0;
  10569. WOLFSSL_ENTER("wolfSSL_read_early_data()");
  10570. if (ssl == NULL || data == NULL || sz < 0 || outSz == NULL)
  10571. return BAD_FUNC_ARG;
  10572. if (!IsAtLeastTLSv1_3(ssl->version))
  10573. return BAD_FUNC_ARG;
  10574. #ifndef NO_WOLFSSL_SERVER
  10575. if (ssl->options.side == WOLFSSL_CLIENT_END)
  10576. return SIDE_ERROR;
  10577. if (ssl->options.handShakeState == NULL_STATE) {
  10578. if (ssl->error != WC_PENDING_E)
  10579. ssl->earlyData = expecting_early_data;
  10580. ret = wolfSSL_accept_TLSv13(ssl);
  10581. if (ret <= 0)
  10582. return WOLFSSL_FATAL_ERROR;
  10583. }
  10584. if (ssl->options.handShakeState == SERVER_FINISHED_COMPLETE) {
  10585. ret = ReceiveData(ssl, (byte*)data, sz, FALSE);
  10586. if (ret > 0)
  10587. *outSz = ret;
  10588. if (ssl->error == ZERO_RETURN) {
  10589. ssl->error = WOLFSSL_ERROR_NONE;
  10590. #ifdef WOLFSSL_DTLS13
  10591. if (ssl->options.dtls) {
  10592. ret = Dtls13DoScheduledWork(ssl);
  10593. if (ret < 0) {
  10594. ssl->error = ret;
  10595. WOLFSSL_ERROR(ssl->error);
  10596. return WOLFSSL_FATAL_ERROR;
  10597. }
  10598. }
  10599. #endif /* WOLFSSL_DTLS13 */
  10600. }
  10601. }
  10602. else
  10603. ret = 0;
  10604. #else
  10605. return SIDE_ERROR;
  10606. #endif
  10607. WOLFSSL_LEAVE("wolfSSL_read_early_data()", ret);
  10608. if (ret < 0)
  10609. ret = WOLFSSL_FATAL_ERROR;
  10610. return ret;
  10611. }
  10612. /* Returns early data status
  10613. *
  10614. * ssl The SSL/TLS object.
  10615. * returns WOLFSSL_EARLY_DATA_ACCEPTED if the data was accepted
  10616. * WOLFSSL_EARLY_DATA_REJECTED if the data was rejected
  10617. * WOLFSSL_EARLY_DATA_NOT_SENT if no early data was sent
  10618. */
  10619. int wolfSSL_get_early_data_status(const WOLFSSL* ssl)
  10620. {
  10621. if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
  10622. return BAD_FUNC_ARG;
  10623. return ssl->earlyDataStatus;
  10624. }
  10625. #endif
  10626. #ifdef HAVE_SECRET_CALLBACK
  10627. int wolfSSL_set_tls13_secret_cb(WOLFSSL* ssl, Tls13SecretCb cb, void* ctx)
  10628. {
  10629. WOLFSSL_ENTER("wolfSSL_set_tls13_secret_cb");
  10630. if (ssl == NULL)
  10631. return WOLFSSL_FATAL_ERROR;
  10632. ssl->tls13SecretCb = cb;
  10633. ssl->tls13SecretCtx = ctx;
  10634. return WOLFSSL_SUCCESS;
  10635. }
  10636. #endif
  10637. #undef ERROR_OUT
  10638. #endif /* !WOLFCRYPT_ONLY */
  10639. #endif /* WOLFSSL_TLS13 */