tls13.c 235 KB

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