tls13.c 311 KB

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