tls13.c 389 KB

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