tls13.c 269 KB

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