tls13.c 326 KB

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