tls.c 446 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656
  1. /* tls.c
  2. *
  3. * Copyright (C) 2006-2023 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. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #ifndef WOLFCRYPT_ONLY
  26. #include <wolfssl/ssl.h>
  27. #include <wolfssl/internal.h>
  28. #include <wolfssl/error-ssl.h>
  29. #include <wolfssl/wolfcrypt/hash.h>
  30. #include <wolfssl/wolfcrypt/hmac.h>
  31. #include <wolfssl/wolfcrypt/kdf.h>
  32. #ifdef NO_INLINE
  33. #include <wolfssl/wolfcrypt/misc.h>
  34. #else
  35. #define WOLFSSL_MISC_INCLUDED
  36. #include <wolfcrypt/src/misc.c>
  37. #endif
  38. #ifdef HAVE_CURVE25519
  39. #include <wolfssl/wolfcrypt/curve25519.h>
  40. #endif
  41. #ifdef HAVE_CURVE448
  42. #include <wolfssl/wolfcrypt/curve448.h>
  43. #endif
  44. #ifdef HAVE_PQC
  45. #include <wolfssl/wolfcrypt/kyber.h>
  46. #ifdef WOLFSSL_WC_KYBER
  47. #include <wolfssl/wolfcrypt/wc_kyber.h>
  48. #elif defined(HAVE_LIBOQS) || defined(HAVE_PQM4)
  49. #include <wolfssl/wolfcrypt/ext_kyber.h>
  50. #endif
  51. #endif
  52. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  53. #include <wolfssl/wolfcrypt/port/Renesas/renesas-tsip-crypt.h>
  54. #endif
  55. #include <wolfssl/wolfcrypt/hpke.h>
  56. #ifndef NO_TLS
  57. #if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
  58. static int TLSX_KeyShare_IsSupported(int namedGroup);
  59. static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap);
  60. #endif
  61. #ifdef HAVE_SUPPORTED_CURVES
  62. static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions);
  63. #endif
  64. /* Digest enable checks */
  65. #ifdef NO_OLD_TLS /* TLS 1.2 only */
  66. #if defined(NO_SHA256) && !defined(WOLFSSL_SHA384) && \
  67. !defined(WOLFSSL_SHA512)
  68. #error Must have SHA256, SHA384 or SHA512 enabled for TLS 1.2
  69. #endif
  70. #else /* TLS 1.1 or older */
  71. #if defined(NO_MD5) && defined(NO_SHA)
  72. #error Must have SHA1 and MD5 enabled for old TLS
  73. #endif
  74. #endif
  75. #ifdef WOLFSSL_TLS13
  76. #if !defined(NO_DH) && \
  77. !defined(HAVE_FFDHE_2048) && !defined(HAVE_FFDHE_3072) && \
  78. !defined(HAVE_FFDHE_4096) && !defined(HAVE_FFDHE_6144) && \
  79. !defined(HAVE_FFDHE_8192)
  80. #error Please configure your TLS 1.3 DH key size using either: HAVE_FFDHE_2048, HAVE_FFDHE_3072, HAVE_FFDHE_4096, HAVE_FFDHE_6144 or HAVE_FFDHE_8192
  81. #endif
  82. #if !defined(NO_RSA) && !defined(WC_RSA_PSS)
  83. #error The build option WC_RSA_PSS is required for TLS 1.3 with RSA
  84. #endif
  85. #ifndef HAVE_TLS_EXTENSIONS
  86. #ifndef _MSC_VER
  87. #error "The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3"
  88. #else
  89. #pragma message("Error: The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3")
  90. #endif
  91. #endif
  92. #endif
  93. /* Warn if secrets logging is enabled */
  94. #if defined(SHOW_SECRETS) || defined(WOLFSSL_SSLKEYLOGFILE)
  95. #ifndef _MSC_VER
  96. #warning The SHOW_SECRETS and WOLFSSL_SSLKEYLOGFILE options should only be used for debugging and never in a production environment
  97. #else
  98. #pragma message("Warning: The SHOW_SECRETS and WOLFSSL_SSLKEYLOGFILE options should only be used for debugging and never in a production environment")
  99. #endif
  100. #endif
  101. #ifndef WOLFSSL_NO_TLS12
  102. #ifdef WOLFSSL_SHA384
  103. #define HSHASH_SZ WC_SHA384_DIGEST_SIZE
  104. #else
  105. #define HSHASH_SZ FINISHED_SZ
  106. #endif
  107. int BuildTlsHandshakeHash(WOLFSSL* ssl, byte* hash, word32* hashLen)
  108. {
  109. int ret = 0;
  110. word32 hashSz = FINISHED_SZ;
  111. if (ssl == NULL || hash == NULL || hashLen == NULL || *hashLen < HSHASH_SZ)
  112. return BAD_FUNC_ARG;
  113. /* for constant timing perform these even if error */
  114. #ifndef NO_OLD_TLS
  115. ret |= wc_Md5GetHash(&ssl->hsHashes->hashMd5, hash);
  116. ret |= wc_ShaGetHash(&ssl->hsHashes->hashSha, &hash[WC_MD5_DIGEST_SIZE]);
  117. #endif
  118. if (IsAtLeastTLSv1_2(ssl)) {
  119. #ifndef NO_SHA256
  120. if (ssl->specs.mac_algorithm <= sha256_mac ||
  121. ssl->specs.mac_algorithm == blake2b_mac) {
  122. ret |= wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
  123. hashSz = WC_SHA256_DIGEST_SIZE;
  124. }
  125. #endif
  126. #ifdef WOLFSSL_SHA384
  127. if (ssl->specs.mac_algorithm == sha384_mac) {
  128. ret |= wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
  129. hashSz = WC_SHA384_DIGEST_SIZE;
  130. }
  131. #endif
  132. #ifdef WOLFSSL_SM3
  133. if (ssl->specs.mac_algorithm == sm3_mac) {
  134. ret |= wc_Sm3GetHash(&ssl->hsHashes->hashSm3, hash);
  135. hashSz = WC_SM3_DIGEST_SIZE;
  136. }
  137. #endif
  138. }
  139. *hashLen = hashSz;
  140. #ifdef WOLFSSL_CHECK_MEM_ZERO
  141. wc_MemZero_Add("TLS handshake hash", hash, hashSz);
  142. #endif
  143. if (ret != 0) {
  144. ret = BUILD_MSG_ERROR;
  145. WOLFSSL_ERROR_VERBOSE(ret);
  146. }
  147. return ret;
  148. }
  149. int BuildTlsFinished(WOLFSSL* ssl, Hashes* hashes, const byte* sender)
  150. {
  151. int ret;
  152. const byte* side = NULL;
  153. word32 hashSz = HSHASH_SZ;
  154. #if !defined(WOLFSSL_ASYNC_CRYPT) || defined(WC_ASYNC_NO_HASH)
  155. byte handshake_hash[HSHASH_SZ];
  156. #else
  157. WC_DECLARE_VAR(handshake_hash, byte, HSHASH_SZ, ssl->heap);
  158. if (handshake_hash == NULL)
  159. return MEMORY_E;
  160. #endif
  161. ret = BuildTlsHandshakeHash(ssl, handshake_hash, &hashSz);
  162. if (ret == 0) {
  163. if (XSTRNCMP((const char*)sender, (const char*)kTlsClientStr,
  164. SIZEOF_SENDER) == 0) {
  165. side = kTlsClientFinStr;
  166. }
  167. else if (XSTRNCMP((const char*)sender, (const char*)kTlsServerStr,
  168. SIZEOF_SENDER) == 0) {
  169. side = kTlsServerFinStr;
  170. }
  171. else {
  172. ret = BAD_FUNC_ARG;
  173. WOLFSSL_MSG("Unexpected sender value");
  174. }
  175. }
  176. if (ret == 0) {
  177. #ifdef WOLFSSL_HAVE_PRF
  178. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  179. if (ssl->ctx->TlsFinishedCb) {
  180. void* ctx = wolfSSL_GetTlsFinishedCtx(ssl);
  181. ret = ssl->ctx->TlsFinishedCb(ssl, side, handshake_hash, hashSz,
  182. (byte*)hashes, ctx);
  183. }
  184. if (!ssl->ctx->TlsFinishedCb || ret == PROTOCOLCB_UNAVAILABLE)
  185. #endif
  186. {
  187. PRIVATE_KEY_UNLOCK();
  188. ret = wc_PRF_TLS((byte*)hashes, TLS_FINISHED_SZ,
  189. ssl->arrays->masterSecret, SECRET_LEN, side,
  190. FINISHED_LABEL_SZ, handshake_hash, hashSz,
  191. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  192. ssl->heap, ssl->devId);
  193. PRIVATE_KEY_LOCK();
  194. }
  195. ForceZero(handshake_hash, hashSz);
  196. #else
  197. /* Pseudo random function must be enabled in the configuration. */
  198. ret = PRF_MISSING;
  199. WOLFSSL_ERROR_VERBOSE(ret);
  200. WOLFSSL_MSG("Pseudo-random function is not enabled");
  201. (void)side;
  202. (void)hashes;
  203. #endif
  204. }
  205. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  206. WC_FREE_VAR(handshake_hash, ssl->heap);
  207. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  208. wc_MemZero_Check(handshake_hash, HSHASH_SZ);
  209. #endif
  210. return ret;
  211. }
  212. #endif /* !WOLFSSL_NO_TLS12 */
  213. #ifndef NO_OLD_TLS
  214. #ifdef WOLFSSL_ALLOW_TLSV10
  215. ProtocolVersion MakeTLSv1(void)
  216. {
  217. ProtocolVersion pv;
  218. pv.major = SSLv3_MAJOR;
  219. pv.minor = TLSv1_MINOR;
  220. return pv;
  221. }
  222. #endif /* WOLFSSL_ALLOW_TLSV10 */
  223. ProtocolVersion MakeTLSv1_1(void)
  224. {
  225. ProtocolVersion pv;
  226. pv.major = SSLv3_MAJOR;
  227. pv.minor = TLSv1_1_MINOR;
  228. return pv;
  229. }
  230. #endif /* !NO_OLD_TLS */
  231. #ifndef WOLFSSL_NO_TLS12
  232. ProtocolVersion MakeTLSv1_2(void)
  233. {
  234. ProtocolVersion pv;
  235. pv.major = SSLv3_MAJOR;
  236. pv.minor = TLSv1_2_MINOR;
  237. return pv;
  238. }
  239. #endif /* !WOLFSSL_NO_TLS12 */
  240. #ifdef WOLFSSL_TLS13
  241. /* The TLS v1.3 protocol version.
  242. *
  243. * returns the protocol version data for TLS v1.3.
  244. */
  245. ProtocolVersion MakeTLSv1_3(void)
  246. {
  247. ProtocolVersion pv;
  248. pv.major = SSLv3_MAJOR;
  249. pv.minor = TLSv1_3_MINOR;
  250. return pv;
  251. }
  252. #endif
  253. #ifndef WOLFSSL_NO_TLS12
  254. #ifdef HAVE_EXTENDED_MASTER
  255. static const byte ext_master_label[EXT_MASTER_LABEL_SZ + 1] =
  256. "extended master secret";
  257. #endif
  258. static const byte master_label[MASTER_LABEL_SZ + 1] = "master secret";
  259. static const byte key_label [KEY_LABEL_SZ + 1] = "key expansion";
  260. static int _DeriveTlsKeys(byte* key_dig, word32 key_dig_len,
  261. const byte* ms, word32 msLen,
  262. const byte* sr, const byte* cr,
  263. int tls1_2, int hash_type,
  264. void* heap, int devId)
  265. {
  266. int ret;
  267. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  268. WC_DECLARE_VAR(seed, byte, SEED_LEN, heap);
  269. if (seed == NULL)
  270. return MEMORY_E;
  271. #else
  272. byte seed[SEED_LEN];
  273. #endif
  274. XMEMCPY(seed, sr, RAN_LEN);
  275. XMEMCPY(seed + RAN_LEN, cr, RAN_LEN);
  276. #ifdef WOLFSSL_HAVE_PRF
  277. PRIVATE_KEY_UNLOCK();
  278. ret = wc_PRF_TLS(key_dig, key_dig_len, ms, msLen, key_label, KEY_LABEL_SZ,
  279. seed, SEED_LEN, tls1_2, hash_type, heap, devId);
  280. PRIVATE_KEY_LOCK();
  281. #else
  282. /* Pseudo random function must be enabled in the configuration. */
  283. ret = PRF_MISSING;
  284. WOLFSSL_ERROR_VERBOSE(ret);
  285. WOLFSSL_MSG("Pseudo-random function is not enabled");
  286. (void)key_dig;
  287. (void)key_dig_len;
  288. (void)ms;
  289. (void)msLen;
  290. (void)tls1_2;
  291. (void)hash_type;
  292. (void)heap;
  293. (void)devId;
  294. (void)key_label;
  295. (void)master_label;
  296. #ifdef HAVE_EXTENDED_MASTER
  297. (void)ext_master_label;
  298. #endif
  299. #endif
  300. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  301. WC_FREE_VAR(seed, heap);
  302. #endif
  303. return ret;
  304. }
  305. /* External facing wrapper so user can call as well, 0 on success */
  306. int wolfSSL_DeriveTlsKeys(byte* key_dig, word32 key_dig_len,
  307. const byte* ms, word32 msLen,
  308. const byte* sr, const byte* cr,
  309. int tls1_2, int hash_type)
  310. {
  311. return _DeriveTlsKeys(key_dig, key_dig_len, ms, msLen, sr, cr, tls1_2,
  312. hash_type, NULL, INVALID_DEVID);
  313. }
  314. int DeriveTlsKeys(WOLFSSL* ssl)
  315. {
  316. int ret;
  317. int key_dig_len = 2 * ssl->specs.hash_size +
  318. 2 * ssl->specs.key_size +
  319. 2 * ssl->specs.iv_size;
  320. #ifdef WOLFSSL_SMALL_STACK
  321. byte* key_dig;
  322. #else
  323. byte key_dig[MAX_PRF_DIG];
  324. #endif
  325. #ifdef WOLFSSL_SMALL_STACK
  326. key_dig = (byte*)XMALLOC(MAX_PRF_DIG, ssl->heap, DYNAMIC_TYPE_DIGEST);
  327. if (key_dig == NULL) {
  328. return MEMORY_E;
  329. }
  330. #endif
  331. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  332. ret = PROTOCOLCB_UNAVAILABLE;
  333. if (ssl->ctx->GenSessionKeyCb) {
  334. void* ctx = wolfSSL_GetGenSessionKeyCtx(ssl);
  335. ret = ssl->ctx->GenSessionKeyCb(ssl, ctx);
  336. }
  337. if (!ssl->ctx->GenSessionKeyCb || ret == PROTOCOLCB_UNAVAILABLE)
  338. #endif
  339. ret = _DeriveTlsKeys(key_dig, key_dig_len,
  340. ssl->arrays->masterSecret, SECRET_LEN,
  341. ssl->arrays->serverRandom, ssl->arrays->clientRandom,
  342. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  343. ssl->heap, ssl->devId);
  344. if (ret == 0)
  345. ret = StoreKeys(ssl, key_dig, PROVISION_CLIENT_SERVER);
  346. #ifdef WOLFSSL_SMALL_STACK
  347. XFREE(key_dig, ssl->heap, DYNAMIC_TYPE_DIGEST);
  348. #endif
  349. return ret;
  350. }
  351. static int _MakeTlsMasterSecret(byte* ms, word32 msLen,
  352. const byte* pms, word32 pmsLen,
  353. const byte* cr, const byte* sr,
  354. int tls1_2, int hash_type,
  355. void* heap, int devId)
  356. {
  357. int ret;
  358. #if !defined(WOLFSSL_ASYNC_CRYPT) || defined(WC_ASYNC_NO_HASH)
  359. byte seed[SEED_LEN];
  360. #else
  361. WC_DECLARE_VAR(seed, byte, SEED_LEN, heap);
  362. if (seed == NULL)
  363. return MEMORY_E;
  364. #endif
  365. XMEMCPY(seed, cr, RAN_LEN);
  366. XMEMCPY(seed + RAN_LEN, sr, RAN_LEN);
  367. #ifdef WOLFSSL_HAVE_PRF
  368. PRIVATE_KEY_UNLOCK();
  369. ret = wc_PRF_TLS(ms, msLen, pms, pmsLen, master_label, MASTER_LABEL_SZ,
  370. seed, SEED_LEN, tls1_2, hash_type, heap, devId);
  371. PRIVATE_KEY_LOCK();
  372. #else
  373. /* Pseudo random function must be enabled in the configuration. */
  374. ret = PRF_MISSING;
  375. WOLFSSL_MSG("Pseudo-random function is not enabled");
  376. (void)ms;
  377. (void)msLen;
  378. (void)pms;
  379. (void)pmsLen;
  380. (void)tls1_2;
  381. (void)hash_type;
  382. (void)heap;
  383. (void)devId;
  384. #endif
  385. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  386. WC_FREE_VAR(seed, heap);
  387. #endif
  388. return ret;
  389. }
  390. /* External facing wrapper so user can call as well, 0 on success */
  391. int wolfSSL_MakeTlsMasterSecret(byte* ms, word32 msLen,
  392. const byte* pms, word32 pmsLen,
  393. const byte* cr, const byte* sr,
  394. int tls1_2, int hash_type)
  395. {
  396. return _MakeTlsMasterSecret(ms, msLen, pms, pmsLen, cr, sr, tls1_2,
  397. hash_type, NULL, INVALID_DEVID);
  398. }
  399. #ifdef HAVE_EXTENDED_MASTER
  400. static int _MakeTlsExtendedMasterSecret(byte* ms, word32 msLen,
  401. const byte* pms, word32 pmsLen,
  402. const byte* sHash, word32 sHashLen,
  403. int tls1_2, int hash_type,
  404. void* heap, int devId)
  405. {
  406. int ret;
  407. #ifdef WOLFSSL_HAVE_PRF
  408. PRIVATE_KEY_UNLOCK();
  409. ret = wc_PRF_TLS(ms, msLen, pms, pmsLen, ext_master_label, EXT_MASTER_LABEL_SZ,
  410. sHash, sHashLen, tls1_2, hash_type, heap, devId);
  411. PRIVATE_KEY_LOCK();
  412. #else
  413. /* Pseudo random function must be enabled in the configuration. */
  414. ret = PRF_MISSING;
  415. WOLFSSL_MSG("Pseudo-random function is not enabled");
  416. (void)ms;
  417. (void)msLen;
  418. (void)pms;
  419. (void)pmsLen;
  420. (void)sHash;
  421. (void)sHashLen;
  422. (void)tls1_2;
  423. (void)hash_type;
  424. (void)heap;
  425. (void)devId;
  426. #endif
  427. return ret;
  428. }
  429. /* External facing wrapper so user can call as well, 0 on success */
  430. int wolfSSL_MakeTlsExtendedMasterSecret(byte* ms, word32 msLen,
  431. const byte* pms, word32 pmsLen,
  432. const byte* sHash, word32 sHashLen,
  433. int tls1_2, int hash_type)
  434. {
  435. return _MakeTlsExtendedMasterSecret(ms, msLen, pms, pmsLen, sHash, sHashLen,
  436. tls1_2, hash_type, NULL, INVALID_DEVID);
  437. }
  438. #endif /* HAVE_EXTENDED_MASTER */
  439. int MakeTlsMasterSecret(WOLFSSL* ssl)
  440. {
  441. int ret;
  442. #ifdef HAVE_EXTENDED_MASTER
  443. if (ssl->options.haveEMS) {
  444. word32 hashSz = HSHASH_SZ;
  445. #ifdef WOLFSSL_SMALL_STACK
  446. byte* handshake_hash = (byte*)XMALLOC(HSHASH_SZ, ssl->heap,
  447. DYNAMIC_TYPE_DIGEST);
  448. if (handshake_hash == NULL)
  449. return MEMORY_E;
  450. #else
  451. byte handshake_hash[HSHASH_SZ];
  452. #endif
  453. ret = BuildTlsHandshakeHash(ssl, handshake_hash, &hashSz);
  454. if (ret == 0) {
  455. ret = _MakeTlsExtendedMasterSecret(
  456. ssl->arrays->masterSecret, SECRET_LEN,
  457. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz,
  458. handshake_hash, hashSz,
  459. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  460. ssl->heap, ssl->devId);
  461. ForceZero(handshake_hash, hashSz);
  462. }
  463. #ifdef WOLFSSL_SMALL_STACK
  464. XFREE(handshake_hash, ssl->heap, DYNAMIC_TYPE_DIGEST);
  465. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  466. wc_MemZero_Check(handshake_hash, HSHASH_SZ);
  467. #endif
  468. }
  469. else
  470. #endif /* HAVE_EXTENDED_MASTER */
  471. {
  472. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  473. ret = PROTOCOLCB_UNAVAILABLE;
  474. if (ssl->ctx->GenMasterCb) {
  475. void* ctx = wolfSSL_GetGenMasterSecretCtx(ssl);
  476. ret = ssl->ctx->GenMasterCb(ssl, ctx);
  477. }
  478. if (!ssl->ctx->GenMasterCb || ret == PROTOCOLCB_UNAVAILABLE)
  479. #endif
  480. {
  481. ret = _MakeTlsMasterSecret(ssl->arrays->masterSecret,
  482. SECRET_LEN, ssl->arrays->preMasterSecret,
  483. ssl->arrays->preMasterSz, ssl->arrays->clientRandom,
  484. ssl->arrays->serverRandom, IsAtLeastTLSv1_2(ssl),
  485. ssl->specs.mac_algorithm, ssl->heap, ssl->devId);
  486. }
  487. }
  488. if (ret == 0) {
  489. #ifdef SHOW_SECRETS
  490. /* Wireshark Pre-Master-Secret Format:
  491. * CLIENT_RANDOM <clientrandom> <mastersecret>
  492. */
  493. const char* CLIENT_RANDOM_LABEL = "CLIENT_RANDOM";
  494. int i, pmsPos = 0;
  495. char pmsBuf[13 + 1 + 64 + 1 + 96 + 1 + 1];
  496. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%s ",
  497. CLIENT_RANDOM_LABEL);
  498. pmsPos += XSTRLEN(CLIENT_RANDOM_LABEL) + 1;
  499. for (i = 0; i < RAN_LEN; i++) {
  500. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
  501. ssl->arrays->clientRandom[i]);
  502. pmsPos += 2;
  503. }
  504. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, " ");
  505. pmsPos += 1;
  506. for (i = 0; i < SECRET_LEN; i++) {
  507. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
  508. ssl->arrays->masterSecret[i]);
  509. pmsPos += 2;
  510. }
  511. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "\n");
  512. pmsPos += 1;
  513. /* print master secret */
  514. puts(pmsBuf);
  515. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE)
  516. {
  517. FILE* f = XFOPEN(WOLFSSL_SSLKEYLOGFILE_OUTPUT, "a");
  518. if (f != XBADFILE) {
  519. XFWRITE(pmsBuf, 1, pmsPos, f);
  520. XFCLOSE(f);
  521. }
  522. }
  523. #endif
  524. #endif /* SHOW_SECRETS */
  525. ret = DeriveTlsKeys(ssl);
  526. }
  527. return ret;
  528. }
  529. /* Used by EAP-TLS and EAP-TTLS to derive keying material from
  530. * the master_secret. */
  531. int wolfSSL_make_eap_keys(WOLFSSL* ssl, void* msk, unsigned int len,
  532. const char* label)
  533. {
  534. int ret;
  535. #ifdef WOLFSSL_SMALL_STACK
  536. byte* seed;
  537. #else
  538. byte seed[SEED_LEN];
  539. #endif
  540. #ifdef WOLFSSL_SMALL_STACK
  541. seed = (byte*)XMALLOC(SEED_LEN, ssl->heap, DYNAMIC_TYPE_SEED);
  542. if (seed == NULL)
  543. return MEMORY_E;
  544. #endif
  545. /*
  546. * As per RFC-5281, the order of the client and server randoms is reversed
  547. * from that used by the TLS protocol to derive keys.
  548. */
  549. XMEMCPY(seed, ssl->arrays->clientRandom, RAN_LEN);
  550. XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
  551. #ifdef WOLFSSL_HAVE_PRF
  552. PRIVATE_KEY_UNLOCK();
  553. ret = wc_PRF_TLS((byte*)msk, len, ssl->arrays->masterSecret, SECRET_LEN,
  554. (const byte *)label, (word32)XSTRLEN(label), seed, SEED_LEN,
  555. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  556. ssl->heap, ssl->devId);
  557. PRIVATE_KEY_LOCK();
  558. #else
  559. /* Pseudo random function must be enabled in the configuration. */
  560. ret = PRF_MISSING;
  561. WOLFSSL_MSG("Pseudo-random function is not enabled");
  562. (void)msk;
  563. (void)len;
  564. (void)label;
  565. #endif
  566. #ifdef WOLFSSL_SMALL_STACK
  567. XFREE(seed, ssl->heap, DYNAMIC_TYPE_SEED);
  568. #endif
  569. return ret;
  570. }
  571. int wolfSSL_GetHmacType_ex(CipherSpecs* specs)
  572. {
  573. if (specs == NULL)
  574. return BAD_FUNC_ARG;
  575. switch (specs->mac_algorithm) {
  576. #ifndef NO_MD5
  577. case md5_mac:
  578. {
  579. return WC_MD5;
  580. }
  581. #endif
  582. #ifndef NO_SHA256
  583. case sha256_mac:
  584. {
  585. return WC_SHA256;
  586. }
  587. #endif
  588. #ifdef WOLFSSL_SHA384
  589. case sha384_mac:
  590. {
  591. return WC_SHA384;
  592. }
  593. #endif
  594. #ifdef WOLFSSL_SM3
  595. case sm3_mac:
  596. {
  597. return WC_SM3;
  598. }
  599. #endif
  600. #ifndef NO_SHA
  601. case sha_mac:
  602. {
  603. return WC_SHA;
  604. }
  605. #endif
  606. #ifdef HAVE_BLAKE2
  607. case blake2b_mac:
  608. {
  609. return BLAKE2B_ID;
  610. }
  611. #endif
  612. default:
  613. {
  614. return WOLFSSL_FATAL_ERROR;
  615. }
  616. }
  617. }
  618. /* return HMAC digest type in wolfSSL format */
  619. int wolfSSL_GetHmacType(WOLFSSL* ssl)
  620. {
  621. if (ssl == NULL)
  622. return BAD_FUNC_ARG;
  623. return wolfSSL_GetHmacType_ex(&ssl->specs);
  624. }
  625. int wolfSSL_SetTlsHmacInner(WOLFSSL* ssl, byte* inner, word32 sz, int content,
  626. int verify)
  627. {
  628. if (ssl == NULL || inner == NULL)
  629. return BAD_FUNC_ARG;
  630. XMEMSET(inner, 0, WOLFSSL_TLS_HMAC_INNER_SZ);
  631. WriteSEQ(ssl, verify, inner);
  632. inner[SEQ_SZ] = (byte)content;
  633. inner[SEQ_SZ + ENUM_LEN] = ssl->version.major;
  634. inner[SEQ_SZ + ENUM_LEN + ENUM_LEN] = ssl->version.minor;
  635. c16toa((word16)sz, inner + SEQ_SZ + ENUM_LEN + VERSION_SZ);
  636. return 0;
  637. }
  638. #ifndef WOLFSSL_AEAD_ONLY
  639. #if !defined(WOLFSSL_NO_HASH_RAW) && !defined(HAVE_FIPS) && \
  640. !defined(HAVE_SELFTEST)
  641. /* Update the hash in the HMAC.
  642. *
  643. * hmac HMAC object.
  644. * data Data to be hashed.
  645. * sz Size of data to hash.
  646. * returns 0 on success, otherwise failure.
  647. */
  648. static int Hmac_HashUpdate(Hmac* hmac, const byte* data, word32 sz)
  649. {
  650. int ret = BAD_FUNC_ARG;
  651. switch (hmac->macType) {
  652. #ifndef NO_SHA
  653. case WC_SHA:
  654. ret = wc_ShaUpdate(&hmac->hash.sha, data, sz);
  655. break;
  656. #endif /* !NO_SHA */
  657. #ifndef NO_SHA256
  658. case WC_SHA256:
  659. ret = wc_Sha256Update(&hmac->hash.sha256, data, sz);
  660. break;
  661. #endif /* !NO_SHA256 */
  662. #ifdef WOLFSSL_SHA384
  663. case WC_SHA384:
  664. ret = wc_Sha384Update(&hmac->hash.sha384, data, sz);
  665. break;
  666. #endif /* WOLFSSL_SHA384 */
  667. #ifdef WOLFSSL_SHA512
  668. case WC_SHA512:
  669. ret = wc_Sha512Update(&hmac->hash.sha512, data, sz);
  670. break;
  671. #endif /* WOLFSSL_SHA512 */
  672. #ifdef WOLFSSL_SM3
  673. case WC_SM3:
  674. ret = wc_Sm3Update(&hmac->hash.sm3, data, sz);
  675. break;
  676. #endif /* WOLFSSL_SM3 */
  677. default:
  678. break;
  679. }
  680. return ret;
  681. }
  682. /* Finalize the hash but don't put the EOC, padding or length in.
  683. *
  684. * hmac HMAC object.
  685. * hash Hash result.
  686. * returns 0 on success, otherwise failure.
  687. */
  688. static int Hmac_HashFinalRaw(Hmac* hmac, unsigned char* hash)
  689. {
  690. int ret = BAD_FUNC_ARG;
  691. switch (hmac->macType) {
  692. #ifndef NO_SHA
  693. case WC_SHA:
  694. ret = wc_ShaFinalRaw(&hmac->hash.sha, hash);
  695. break;
  696. #endif /* !NO_SHA */
  697. #ifndef NO_SHA256
  698. case WC_SHA256:
  699. ret = wc_Sha256FinalRaw(&hmac->hash.sha256, hash);
  700. break;
  701. #endif /* !NO_SHA256 */
  702. #ifdef WOLFSSL_SHA384
  703. case WC_SHA384:
  704. ret = wc_Sha384FinalRaw(&hmac->hash.sha384, hash);
  705. break;
  706. #endif /* WOLFSSL_SHA384 */
  707. #ifdef WOLFSSL_SHA512
  708. case WC_SHA512:
  709. ret = wc_Sha512FinalRaw(&hmac->hash.sha512, hash);
  710. break;
  711. #endif /* WOLFSSL_SHA512 */
  712. #ifdef WOLFSSL_SM3
  713. case WC_SM3:
  714. ret = wc_Sm3FinalRaw(&hmac->hash.sm3, hash);
  715. break;
  716. #endif /* WOLFSSL_SM3 */
  717. default:
  718. break;
  719. }
  720. return ret;
  721. }
  722. /* Finalize the HMAC by performing outer hash.
  723. *
  724. * hmac HMAC object.
  725. * mac MAC result.
  726. * returns 0 on success, otherwise failure.
  727. */
  728. static int Hmac_OuterHash(Hmac* hmac, unsigned char* mac)
  729. {
  730. int ret = BAD_FUNC_ARG;
  731. wc_HashAlg hash;
  732. enum wc_HashType hashType = (enum wc_HashType)hmac->macType;
  733. int digestSz = wc_HashGetDigestSize(hashType);
  734. int blockSz = wc_HashGetBlockSize(hashType);
  735. if ((digestSz >= 0) && (blockSz >= 0)) {
  736. ret = wc_HashInit(&hash, hashType);
  737. }
  738. if (ret == 0) {
  739. ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->opad,
  740. blockSz);
  741. if (ret == 0)
  742. ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->innerHash,
  743. digestSz);
  744. if (ret == 0)
  745. ret = wc_HashFinal(&hash, hashType, mac);
  746. wc_HashFree(&hash, hashType);
  747. }
  748. return ret;
  749. }
  750. /* Calculate the HMAC of the header + message data.
  751. * Constant time implementation using wc_Sha*FinalRaw().
  752. *
  753. * hmac HMAC object.
  754. * digest MAC result.
  755. * in Message data.
  756. * sz Size of the message data.
  757. * header Constructed record header with length of handshake data.
  758. * returns 0 on success, otherwise failure.
  759. */
  760. static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in,
  761. word32 sz, int macLen, byte* header)
  762. {
  763. byte lenBytes[8];
  764. int i, j;
  765. unsigned int k;
  766. int blockBits, blockMask;
  767. int lastBlockLen, extraLen, eocIndex;
  768. int blocks, safeBlocks, lenBlock, eocBlock;
  769. unsigned int maxLen;
  770. int blockSz, padSz;
  771. int ret;
  772. word32 realLen;
  773. byte extraBlock;
  774. switch (hmac->macType) {
  775. #ifndef NO_SHA
  776. case WC_SHA:
  777. blockSz = WC_SHA_BLOCK_SIZE;
  778. blockBits = 6;
  779. padSz = WC_SHA_BLOCK_SIZE - WC_SHA_PAD_SIZE + 1;
  780. break;
  781. #endif /* !NO_SHA */
  782. #ifndef NO_SHA256
  783. case WC_SHA256:
  784. blockSz = WC_SHA256_BLOCK_SIZE;
  785. blockBits = 6;
  786. padSz = WC_SHA256_BLOCK_SIZE - WC_SHA256_PAD_SIZE + 1;
  787. break;
  788. #endif /* !NO_SHA256 */
  789. #ifdef WOLFSSL_SHA384
  790. case WC_SHA384:
  791. blockSz = WC_SHA384_BLOCK_SIZE;
  792. blockBits = 7;
  793. padSz = WC_SHA384_BLOCK_SIZE - WC_SHA384_PAD_SIZE + 1;
  794. break;
  795. #endif /* WOLFSSL_SHA384 */
  796. #ifdef WOLFSSL_SHA512
  797. case WC_SHA512:
  798. blockSz = WC_SHA512_BLOCK_SIZE;
  799. blockBits = 7;
  800. padSz = WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE + 1;
  801. break;
  802. #endif /* WOLFSSL_SHA512 */
  803. #ifdef WOLFSSL_SM3
  804. case WC_SM3:
  805. blockSz = WC_SM3_BLOCK_SIZE;
  806. blockBits = 6;
  807. padSz = WC_SM3_BLOCK_SIZE - WC_SM3_PAD_SIZE + 1;
  808. break;
  809. #endif /* WOLFSSL_SM3 */
  810. default:
  811. return BAD_FUNC_ARG;
  812. }
  813. blockMask = blockSz - 1;
  814. /* Size of data to HMAC if padding length byte is zero. */
  815. maxLen = WOLFSSL_TLS_HMAC_INNER_SZ + sz - 1 - macLen;
  816. /* Complete data (including padding) has block for EOC and/or length. */
  817. extraBlock = ctSetLTE((maxLen + padSz) & blockMask, padSz);
  818. /* Total number of blocks for data including padding. */
  819. blocks = ((maxLen + blockSz - 1) >> blockBits) + extraBlock;
  820. /* Up to last 6 blocks can be hashed safely. */
  821. safeBlocks = blocks - 6;
  822. /* Length of message data. */
  823. realLen = maxLen - in[sz - 1];
  824. /* Number of message bytes in last block. */
  825. lastBlockLen = realLen & blockMask;
  826. /* Number of padding bytes in last block. */
  827. extraLen = ((blockSz * 2 - padSz - lastBlockLen) & blockMask) + 1;
  828. /* Number of blocks to create for hash. */
  829. lenBlock = (realLen + extraLen) >> blockBits;
  830. /* Block containing EOC byte. */
  831. eocBlock = realLen >> blockBits;
  832. /* Index of EOC byte in block. */
  833. eocIndex = realLen & blockMask;
  834. /* Add length of hmac's ipad to total length. */
  835. realLen += blockSz;
  836. /* Length as bits - 8 bytes bigendian. */
  837. c32toa(realLen >> ((sizeof(word32) * 8) - 3), lenBytes);
  838. c32toa(realLen << 3, lenBytes + sizeof(word32));
  839. ret = Hmac_HashUpdate(hmac, (unsigned char*)hmac->ipad, blockSz);
  840. if (ret != 0)
  841. return ret;
  842. XMEMSET(hmac->innerHash, 0, macLen);
  843. if (safeBlocks > 0) {
  844. ret = Hmac_HashUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ);
  845. if (ret != 0)
  846. return ret;
  847. ret = Hmac_HashUpdate(hmac, in, safeBlocks * blockSz -
  848. WOLFSSL_TLS_HMAC_INNER_SZ);
  849. if (ret != 0)
  850. return ret;
  851. }
  852. else
  853. safeBlocks = 0;
  854. XMEMSET(digest, 0, macLen);
  855. k = safeBlocks * blockSz;
  856. for (i = safeBlocks; i < blocks; i++) {
  857. unsigned char hashBlock[WC_MAX_BLOCK_SIZE];
  858. unsigned char isEocBlock = ctMaskEq(i, eocBlock);
  859. unsigned char isOutBlock = ctMaskEq(i, lenBlock);
  860. for (j = 0; j < blockSz; j++) {
  861. unsigned char atEoc = ctMaskEq(j, eocIndex) & isEocBlock;
  862. unsigned char pastEoc = ctMaskGT(j, eocIndex) & isEocBlock;
  863. unsigned char b = 0;
  864. if (k < WOLFSSL_TLS_HMAC_INNER_SZ)
  865. b = header[k];
  866. else if (k < maxLen)
  867. b = in[k - WOLFSSL_TLS_HMAC_INNER_SZ];
  868. k++;
  869. b = ctMaskSel(atEoc, 0x80, b);
  870. b &= (unsigned char)~(word32)pastEoc;
  871. b &= ((unsigned char)~(word32)isOutBlock) | isEocBlock;
  872. if (j >= blockSz - 8) {
  873. b = ctMaskSel(isOutBlock, lenBytes[j - (blockSz - 8)], b);
  874. }
  875. hashBlock[j] = b;
  876. }
  877. ret = Hmac_HashUpdate(hmac, hashBlock, blockSz);
  878. if (ret != 0)
  879. return ret;
  880. ret = Hmac_HashFinalRaw(hmac, hashBlock);
  881. if (ret != 0)
  882. return ret;
  883. for (j = 0; j < macLen; j++)
  884. ((unsigned char*)hmac->innerHash)[j] |= hashBlock[j] & isOutBlock;
  885. }
  886. ret = Hmac_OuterHash(hmac, digest);
  887. return ret;
  888. }
  889. #endif
  890. #if defined(WOLFSSL_NO_HASH_RAW) || defined(HAVE_FIPS) || \
  891. defined(HAVE_SELFTEST) || defined(HAVE_BLAKE2)
  892. /* Calculate the HMAC of the header + message data.
  893. * Constant time implementation using normal hashing operations.
  894. * Update-Final need to be constant time.
  895. *
  896. * hmac HMAC object.
  897. * digest MAC result.
  898. * in Message data.
  899. * sz Size of the message data.
  900. * header Constructed record header with length of handshake data.
  901. * returns 0 on success, otherwise failure.
  902. */
  903. static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in,
  904. word32 sz, byte* header)
  905. {
  906. byte dummy[WC_MAX_BLOCK_SIZE] = {0};
  907. int ret;
  908. word32 msgSz, blockSz, macSz, padSz, maxSz, realSz;
  909. word32 offset = 0;
  910. int msgBlocks, blocks, blockBits;
  911. int i;
  912. switch (hmac->macType) {
  913. #ifndef NO_SHA
  914. case WC_SHA:
  915. blockSz = WC_SHA_BLOCK_SIZE;
  916. blockBits = 6;
  917. macSz = WC_SHA_DIGEST_SIZE;
  918. padSz = WC_SHA_BLOCK_SIZE - WC_SHA_PAD_SIZE + 1;
  919. break;
  920. #endif /* !NO_SHA */
  921. #ifndef NO_SHA256
  922. case WC_SHA256:
  923. blockSz = WC_SHA256_BLOCK_SIZE;
  924. blockBits = 6;
  925. macSz = WC_SHA256_DIGEST_SIZE;
  926. padSz = WC_SHA256_BLOCK_SIZE - WC_SHA256_PAD_SIZE + 1;
  927. break;
  928. #endif /* !NO_SHA256 */
  929. #ifdef WOLFSSL_SHA384
  930. case WC_SHA384:
  931. blockSz = WC_SHA384_BLOCK_SIZE;
  932. blockBits = 7;
  933. macSz = WC_SHA384_DIGEST_SIZE;
  934. padSz = WC_SHA384_BLOCK_SIZE - WC_SHA384_PAD_SIZE + 1;
  935. break;
  936. #endif /* WOLFSSL_SHA384 */
  937. #ifdef WOLFSSL_SHA512
  938. case WC_SHA512:
  939. blockSz = WC_SHA512_BLOCK_SIZE;
  940. blockBits = 7;
  941. macSz = WC_SHA512_DIGEST_SIZE;
  942. padSz = WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE + 1;
  943. break;
  944. #endif /* WOLFSSL_SHA512 */
  945. #ifdef HAVE_BLAKE2
  946. case WC_HASH_TYPE_BLAKE2B:
  947. blockSz = BLAKE2B_BLOCKBYTES;
  948. blockBits = 7;
  949. macSz = BLAKE2B_256;
  950. padSz = 0;
  951. break;
  952. #endif /* HAVE_BLAKE2 */
  953. default:
  954. return BAD_FUNC_ARG;
  955. }
  956. msgSz = sz - (1 + in[sz - 1] + macSz);
  957. /* Make negative result 0 */
  958. msgSz &= ~(0 - (msgSz >> 31));
  959. realSz = WOLFSSL_TLS_HMAC_INNER_SZ + msgSz;
  960. maxSz = WOLFSSL_TLS_HMAC_INNER_SZ + (sz - 1) - macSz;
  961. /* Calculate #blocks processed in HMAC for max and real data. */
  962. blocks = maxSz >> blockBits;
  963. blocks += ((maxSz + padSz) % blockSz) < padSz;
  964. msgBlocks = realSz >> blockBits;
  965. /* #Extra blocks to process. */
  966. blocks -= msgBlocks + ((((realSz + padSz) % blockSz) < padSz) ? 1 : 0);
  967. /* Calculate whole blocks. */
  968. msgBlocks--;
  969. ret = wc_HmacUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ);
  970. if (ret == 0) {
  971. /* Fill the rest of the block with any available data. */
  972. word32 currSz = ctMaskLT(msgSz, blockSz) & msgSz;
  973. currSz |= ctMaskGTE(msgSz, blockSz) & blockSz;
  974. currSz -= WOLFSSL_TLS_HMAC_INNER_SZ;
  975. currSz &= ~(0 - (currSz >> 31));
  976. ret = wc_HmacUpdate(hmac, in, currSz);
  977. offset = currSz;
  978. }
  979. if (ret == 0) {
  980. /* Do the hash operations on a block basis. */
  981. for (i = 0; i < msgBlocks; i++, offset += blockSz) {
  982. ret = wc_HmacUpdate(hmac, in + offset, blockSz);
  983. if (ret != 0)
  984. break;
  985. }
  986. }
  987. if (ret == 0)
  988. ret = wc_HmacUpdate(hmac, in + offset, msgSz - offset);
  989. if (ret == 0)
  990. ret = wc_HmacFinal(hmac, digest);
  991. if (ret == 0) {
  992. /* Do the dummy hash operations. Do at least one. */
  993. for (i = 0; i < blocks + 1; i++) {
  994. ret = wc_HmacUpdate(hmac, dummy, blockSz);
  995. if (ret != 0)
  996. break;
  997. }
  998. }
  999. return ret;
  1000. }
  1001. #endif
  1002. int TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, int padSz,
  1003. int content, int verify, int epochOrder)
  1004. {
  1005. Hmac hmac;
  1006. byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
  1007. int ret = 0;
  1008. const byte* macSecret = NULL;
  1009. word32 hashSz = 0;
  1010. if (ssl == NULL)
  1011. return BAD_FUNC_ARG;
  1012. #ifdef HAVE_TRUNCATED_HMAC
  1013. hashSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  1014. : ssl->specs.hash_size;
  1015. #else
  1016. hashSz = ssl->specs.hash_size;
  1017. #endif
  1018. #ifdef HAVE_FUZZER
  1019. /* Fuzz "in" buffer with sz to be used in HMAC algorithm */
  1020. if (ssl->fuzzerCb) {
  1021. if (verify && padSz >= 0) {
  1022. ssl->fuzzerCb(ssl, in, sz + hashSz + padSz + 1, FUZZ_HMAC,
  1023. ssl->fuzzerCtx);
  1024. }
  1025. else {
  1026. ssl->fuzzerCb(ssl, in, sz, FUZZ_HMAC, ssl->fuzzerCtx);
  1027. }
  1028. }
  1029. #endif
  1030. if (!ssl->options.dtls)
  1031. wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, verify);
  1032. else
  1033. wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, epochOrder);
  1034. ret = wc_HmacInit(&hmac, ssl->heap, ssl->devId);
  1035. if (ret != 0)
  1036. return ret;
  1037. #ifdef WOLFSSL_DTLS
  1038. if (ssl->options.dtls)
  1039. macSecret = wolfSSL_GetDtlsMacSecret(ssl, verify, epochOrder);
  1040. else
  1041. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  1042. #else
  1043. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  1044. #endif
  1045. ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
  1046. macSecret,
  1047. ssl->specs.hash_size);
  1048. if (ret == 0) {
  1049. /* Constant time verification required. */
  1050. if (verify && padSz >= 0) {
  1051. #if !defined(WOLFSSL_NO_HASH_RAW) && !defined(HAVE_FIPS) && \
  1052. !defined(HAVE_SELFTEST)
  1053. #ifdef HAVE_BLAKE2
  1054. if (wolfSSL_GetHmacType(ssl) == WC_HASH_TYPE_BLAKE2B) {
  1055. ret = Hmac_UpdateFinal(&hmac, digest, in,
  1056. sz + hashSz + padSz + 1, myInner);
  1057. }
  1058. else
  1059. #endif
  1060. {
  1061. ret = Hmac_UpdateFinal_CT(&hmac, digest, in,
  1062. sz + hashSz + padSz + 1, hashSz, myInner);
  1063. }
  1064. #else
  1065. ret = Hmac_UpdateFinal(&hmac, digest, in, sz + hashSz + padSz + 1,
  1066. myInner);
  1067. #endif
  1068. }
  1069. else {
  1070. ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
  1071. if (ret == 0)
  1072. ret = wc_HmacUpdate(&hmac, in, sz); /* content */
  1073. if (ret == 0)
  1074. ret = wc_HmacFinal(&hmac, digest);
  1075. }
  1076. }
  1077. wc_HmacFree(&hmac);
  1078. return ret;
  1079. }
  1080. #endif /* WOLFSSL_AEAD_ONLY */
  1081. #endif /* !WOLFSSL_NO_TLS12 */
  1082. #ifdef HAVE_TLS_EXTENSIONS
  1083. /**
  1084. * The TLSX semaphore is used to calculate the size of the extensions to be sent
  1085. * from one peer to another.
  1086. */
  1087. /** Supports up to 72 flags. Increase as needed. */
  1088. #define SEMAPHORE_SIZE 9
  1089. /**
  1090. * Converts the extension type (id) to an index in the semaphore.
  1091. *
  1092. * Official reference for TLS extension types:
  1093. * http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xml
  1094. *
  1095. * Motivation:
  1096. * Previously, we used the extension type itself as the index of that
  1097. * extension in the semaphore as the extension types were declared
  1098. * sequentially, but maintain a semaphore as big as the number of available
  1099. * extensions is no longer an option since the release of renegotiation_info.
  1100. *
  1101. * How to update:
  1102. * Assign extension types that extrapolate the number of available semaphores
  1103. * to the first available index going backwards in the semaphore array.
  1104. * When adding a new extension type that don't extrapolate the number of
  1105. * available semaphores, check for a possible collision with with a
  1106. * 'remapped' extension type.
  1107. *
  1108. * Update TLSX_Parse for duplicate detection if more added above 62.
  1109. */
  1110. static WC_INLINE word16 TLSX_ToSemaphore(word16 type)
  1111. {
  1112. switch (type) {
  1113. case TLSX_RENEGOTIATION_INFO: /* 0xFF01 */
  1114. return 63;
  1115. #ifdef WOLFSSL_QUIC
  1116. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT: /* 0xffa5 */
  1117. return 64;
  1118. #endif
  1119. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1120. case TLSX_ECH: /* 0xfe0d */
  1121. return 65;
  1122. #endif
  1123. default:
  1124. if (type > 62) {
  1125. /* This message SHOULD only happens during the adding of
  1126. new TLS extensions in which its IANA number overflows
  1127. the current semaphore's range, or if its number already
  1128. is assigned to be used by another extension.
  1129. Use this check value for the new extension and decrement
  1130. the check value by one. */
  1131. WOLFSSL_MSG("### TLSX semaphore collision or overflow detected!");
  1132. }
  1133. }
  1134. return type;
  1135. }
  1136. /** Checks if a specific light (tls extension) is not set in the semaphore. */
  1137. #define IS_OFF(semaphore, light) \
  1138. (!(((semaphore)[(light) / 8] & (byte) (0x01 << ((light) % 8)))))
  1139. /** Turn on a specific light (tls extension) in the semaphore. */
  1140. /* the semaphore marks the extensions already written to the message */
  1141. #define TURN_ON(semaphore, light) \
  1142. ((semaphore)[(light) / 8] |= (byte) (0x01 << ((light) % 8)))
  1143. /** Turn off a specific light (tls extension) in the semaphore. */
  1144. #define TURN_OFF(semaphore, light) \
  1145. ((semaphore)[(light) / 8] &= (byte) ~(0x01 << ((light) % 8)))
  1146. /** Creates a new extension. */
  1147. static TLSX* TLSX_New(TLSX_Type type, const void* data, void* heap)
  1148. {
  1149. TLSX* extension = (TLSX*)XMALLOC(sizeof(TLSX), heap, DYNAMIC_TYPE_TLSX);
  1150. (void)heap;
  1151. if (extension) {
  1152. extension->type = type;
  1153. extension->data = (void*)data;
  1154. extension->resp = 0;
  1155. extension->next = NULL;
  1156. }
  1157. return extension;
  1158. }
  1159. /**
  1160. * Creates a new extension and appends it to the provided list.
  1161. * Checks for duplicate extensions, keeps the newest.
  1162. */
  1163. int TLSX_Append(TLSX** list, TLSX_Type type, const void* data, void* heap)
  1164. {
  1165. TLSX* extension = TLSX_New(type, data, heap);
  1166. TLSX* cur;
  1167. TLSX** prevNext = list;
  1168. if (extension == NULL)
  1169. return MEMORY_E;
  1170. for (cur = *list; cur != NULL;) {
  1171. if (cur->type == type) {
  1172. *prevNext = cur->next;
  1173. cur->next = NULL;
  1174. TLSX_FreeAll(cur, heap);
  1175. cur = *prevNext;
  1176. }
  1177. else {
  1178. prevNext = &cur->next;
  1179. cur = cur->next;
  1180. }
  1181. }
  1182. /* Append the extension to the list */
  1183. *prevNext = extension;
  1184. return 0;
  1185. }
  1186. /**
  1187. * Creates a new extension and pushes it to the provided list.
  1188. * Checks for duplicate extensions, keeps the newest.
  1189. */
  1190. int TLSX_Push(TLSX** list, TLSX_Type type, const void* data, void* heap)
  1191. {
  1192. TLSX* extension = TLSX_New(type, data, heap);
  1193. if (extension == NULL)
  1194. return MEMORY_E;
  1195. /* pushes the new extension on the list. */
  1196. extension->next = *list;
  1197. *list = extension;
  1198. /* remove duplicate extensions, there should be only one of each type. */
  1199. do {
  1200. if (extension->next && extension->next->type == type) {
  1201. TLSX *next = extension->next;
  1202. extension->next = next->next;
  1203. next->next = NULL;
  1204. TLSX_FreeAll(next, heap);
  1205. /* there is no way to occur more than
  1206. * two extensions of the same type.
  1207. */
  1208. break;
  1209. }
  1210. } while ((extension = extension->next));
  1211. return 0;
  1212. }
  1213. #ifndef NO_WOLFSSL_CLIENT
  1214. int TLSX_CheckUnsupportedExtension(WOLFSSL* ssl, TLSX_Type type);
  1215. int TLSX_CheckUnsupportedExtension(WOLFSSL* ssl, TLSX_Type type)
  1216. {
  1217. TLSX *extension = TLSX_Find(ssl->extensions, type);
  1218. if (!extension)
  1219. extension = TLSX_Find(ssl->ctx->extensions, type);
  1220. return extension == NULL;
  1221. }
  1222. int TLSX_HandleUnsupportedExtension(WOLFSSL* ssl);
  1223. int TLSX_HandleUnsupportedExtension(WOLFSSL* ssl)
  1224. {
  1225. SendAlert(ssl, alert_fatal, unsupported_extension);
  1226. WOLFSSL_ERROR_VERBOSE(UNSUPPORTED_EXTENSION);
  1227. return UNSUPPORTED_EXTENSION;
  1228. }
  1229. #else
  1230. #define TLSX_CheckUnsupportedExtension(ssl, type) 0
  1231. #define TLSX_HandleUnsupportedExtension(ssl) 0
  1232. #endif
  1233. #if !defined(NO_WOLFSSL_SERVER) || defined(WOLFSSL_TLS13)
  1234. void TLSX_SetResponse(WOLFSSL* ssl, TLSX_Type type);
  1235. /** Mark an extension to be sent back to the client. */
  1236. void TLSX_SetResponse(WOLFSSL* ssl, TLSX_Type type)
  1237. {
  1238. TLSX *extension = TLSX_Find(ssl->extensions, type);
  1239. if (extension)
  1240. extension->resp = 1;
  1241. }
  1242. #endif
  1243. /******************************************************************************/
  1244. /* Application-Layer Protocol Negotiation */
  1245. /******************************************************************************/
  1246. #ifdef HAVE_ALPN
  1247. /** Creates a new ALPN object, providing protocol name to use. */
  1248. static ALPN* TLSX_ALPN_New(char *protocol_name, word16 protocol_nameSz,
  1249. void* heap)
  1250. {
  1251. ALPN *alpn;
  1252. WOLFSSL_ENTER("TLSX_ALPN_New");
  1253. if (protocol_name == NULL ||
  1254. protocol_nameSz > WOLFSSL_MAX_ALPN_PROTO_NAME_LEN) {
  1255. WOLFSSL_MSG("Invalid arguments");
  1256. return NULL;
  1257. }
  1258. alpn = (ALPN*)XMALLOC(sizeof(ALPN), heap, DYNAMIC_TYPE_TLSX);
  1259. if (alpn == NULL) {
  1260. WOLFSSL_MSG("Memory failure");
  1261. return NULL;
  1262. }
  1263. alpn->next = NULL;
  1264. alpn->negotiated = 0;
  1265. alpn->options = 0;
  1266. alpn->protocol_name = (char*)XMALLOC(protocol_nameSz + 1,
  1267. heap, DYNAMIC_TYPE_TLSX);
  1268. if (alpn->protocol_name == NULL) {
  1269. WOLFSSL_MSG("Memory failure");
  1270. XFREE(alpn, heap, DYNAMIC_TYPE_TLSX);
  1271. return NULL;
  1272. }
  1273. XMEMCPY(alpn->protocol_name, protocol_name, protocol_nameSz);
  1274. alpn->protocol_name[protocol_nameSz] = 0;
  1275. (void)heap;
  1276. return alpn;
  1277. }
  1278. /** Releases an ALPN object. */
  1279. static void TLSX_ALPN_Free(ALPN *alpn, void* heap)
  1280. {
  1281. (void)heap;
  1282. if (alpn == NULL)
  1283. return;
  1284. XFREE(alpn->protocol_name, heap, DYNAMIC_TYPE_TLSX);
  1285. XFREE(alpn, heap, DYNAMIC_TYPE_TLSX);
  1286. }
  1287. /** Releases all ALPN objects in the provided list. */
  1288. static void TLSX_ALPN_FreeAll(ALPN *list, void* heap)
  1289. {
  1290. ALPN* alpn;
  1291. while ((alpn = list)) {
  1292. list = alpn->next;
  1293. TLSX_ALPN_Free(alpn, heap);
  1294. }
  1295. }
  1296. /** Tells the buffered size of the ALPN objects in a list. */
  1297. static word16 TLSX_ALPN_GetSize(ALPN *list)
  1298. {
  1299. ALPN* alpn;
  1300. word16 length = OPAQUE16_LEN; /* list length */
  1301. while ((alpn = list)) {
  1302. list = alpn->next;
  1303. length++; /* protocol name length is on one byte */
  1304. length += (word16)XSTRLEN(alpn->protocol_name);
  1305. }
  1306. return length;
  1307. }
  1308. /** Writes the ALPN objects of a list in a buffer. */
  1309. static word16 TLSX_ALPN_Write(ALPN *list, byte *output)
  1310. {
  1311. ALPN* alpn;
  1312. word16 length = 0;
  1313. word16 offset = OPAQUE16_LEN; /* list length offset */
  1314. while ((alpn = list)) {
  1315. list = alpn->next;
  1316. length = (word16)XSTRLEN(alpn->protocol_name);
  1317. /* protocol name length */
  1318. output[offset++] = (byte)length;
  1319. /* protocol name value */
  1320. XMEMCPY(output + offset, alpn->protocol_name, length);
  1321. offset += length;
  1322. }
  1323. /* writing list length */
  1324. c16toa(offset - OPAQUE16_LEN, output);
  1325. return offset;
  1326. }
  1327. /** Finds a protocol name in the provided ALPN list */
  1328. static ALPN* TLSX_ALPN_Find(ALPN *list, char *protocol_name, word16 size)
  1329. {
  1330. ALPN *alpn;
  1331. if (list == NULL || protocol_name == NULL)
  1332. return NULL;
  1333. alpn = list;
  1334. while (alpn != NULL && (
  1335. (word16)XSTRLEN(alpn->protocol_name) != size ||
  1336. XSTRNCMP(alpn->protocol_name, protocol_name, size)))
  1337. alpn = alpn->next;
  1338. return alpn;
  1339. }
  1340. /** Set the ALPN matching client and server requirements */
  1341. static int TLSX_SetALPN(TLSX** extensions, const void* data, word16 size,
  1342. void* heap)
  1343. {
  1344. ALPN *alpn;
  1345. int ret;
  1346. if (extensions == NULL || data == NULL)
  1347. return BAD_FUNC_ARG;
  1348. alpn = TLSX_ALPN_New((char *)data, size, heap);
  1349. if (alpn == NULL) {
  1350. WOLFSSL_MSG("Memory failure");
  1351. return MEMORY_E;
  1352. }
  1353. alpn->negotiated = 1;
  1354. ret = TLSX_Push(extensions, TLSX_APPLICATION_LAYER_PROTOCOL, (void*)alpn,
  1355. heap);
  1356. if (ret != 0) {
  1357. TLSX_ALPN_Free(alpn, heap);
  1358. return ret;
  1359. }
  1360. return WOLFSSL_SUCCESS;
  1361. }
  1362. static int ALPN_find_match(WOLFSSL *ssl, TLSX **pextension,
  1363. const byte **psel, byte *psel_len,
  1364. const byte *alpn_val, word16 alpn_val_len)
  1365. {
  1366. TLSX *extension;
  1367. ALPN *alpn, *list;
  1368. const byte *sel = NULL, *s;
  1369. byte sel_len = 0, wlen;
  1370. extension = TLSX_Find(ssl->extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1371. if (extension == NULL)
  1372. extension = TLSX_Find(ssl->ctx->extensions,
  1373. TLSX_APPLICATION_LAYER_PROTOCOL);
  1374. /* No ALPN configured here */
  1375. if (extension == NULL || extension->data == NULL) {
  1376. *pextension = NULL;
  1377. *psel = NULL;
  1378. *psel_len = 0;
  1379. return 0;
  1380. }
  1381. list = (ALPN*)extension->data;
  1382. for (s = alpn_val;
  1383. (s - alpn_val) < alpn_val_len;
  1384. s += wlen) {
  1385. wlen = *s++; /* bounds already checked on save */
  1386. alpn = TLSX_ALPN_Find(list, (char*)s, wlen);
  1387. if (alpn != NULL) {
  1388. WOLFSSL_MSG("ALPN protocol match");
  1389. sel = s,
  1390. sel_len = wlen;
  1391. break;
  1392. }
  1393. }
  1394. if (sel == NULL) {
  1395. WOLFSSL_MSG("No ALPN protocol match");
  1396. /* do nothing if no protocol match between client and server and option
  1397. is set to continue (like OpenSSL) */
  1398. if (list->options & WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) {
  1399. WOLFSSL_MSG("Continue on mismatch");
  1400. }
  1401. else {
  1402. SendAlert(ssl, alert_fatal, no_application_protocol);
  1403. WOLFSSL_ERROR_VERBOSE(UNKNOWN_ALPN_PROTOCOL_NAME_E);
  1404. return UNKNOWN_ALPN_PROTOCOL_NAME_E;
  1405. }
  1406. }
  1407. *pextension = extension;
  1408. *psel = sel;
  1409. *psel_len = sel_len;
  1410. return 0;
  1411. }
  1412. int ALPN_Select(WOLFSSL *ssl)
  1413. {
  1414. TLSX *extension;
  1415. const byte *sel = NULL;
  1416. byte sel_len = 0;
  1417. int r = 0;
  1418. WOLFSSL_ENTER("ALPN_Select");
  1419. if (ssl->alpn_peer_requested == NULL)
  1420. return 0;
  1421. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  1422. if (ssl->alpnSelect != NULL && ssl->options.side == WOLFSSL_SERVER_END) {
  1423. r = ssl->alpnSelect(ssl, &sel, &sel_len, ssl->alpn_peer_requested,
  1424. ssl->alpn_peer_requested_length, ssl->alpnSelectArg);
  1425. switch (r) {
  1426. case SSL_TLSEXT_ERR_OK:
  1427. WOLFSSL_MSG("ALPN protocol match");
  1428. break;
  1429. case SSL_TLSEXT_ERR_NOACK:
  1430. WOLFSSL_MSG("ALPN cb no match but not fatal");
  1431. sel = NULL;
  1432. sel_len = 0;
  1433. break;
  1434. case SSL_TLSEXT_ERR_ALERT_FATAL:
  1435. default:
  1436. WOLFSSL_MSG("ALPN cb no match and fatal");
  1437. SendAlert(ssl, alert_fatal, no_application_protocol);
  1438. WOLFSSL_ERROR_VERBOSE(UNKNOWN_ALPN_PROTOCOL_NAME_E);
  1439. return UNKNOWN_ALPN_PROTOCOL_NAME_E;
  1440. }
  1441. }
  1442. else
  1443. #endif
  1444. {
  1445. r = ALPN_find_match(ssl, &extension, &sel, &sel_len,
  1446. ssl->alpn_peer_requested,
  1447. ssl->alpn_peer_requested_length);
  1448. if (r != 0)
  1449. return r;
  1450. }
  1451. if (sel != NULL) {
  1452. /* set the matching negotiated protocol */
  1453. r = TLSX_SetALPN(&ssl->extensions, sel, sel_len, ssl->heap);
  1454. if (r != WOLFSSL_SUCCESS) {
  1455. WOLFSSL_MSG("TLSX_SetALPN failed");
  1456. return BUFFER_ERROR;
  1457. }
  1458. /* reply to ALPN extension sent from peer */
  1459. #ifndef NO_WOLFSSL_SERVER
  1460. TLSX_SetResponse(ssl, TLSX_APPLICATION_LAYER_PROTOCOL);
  1461. #endif
  1462. }
  1463. return 0;
  1464. }
  1465. /** Parses a buffer of ALPN extensions and set the first one matching
  1466. * client and server requirements */
  1467. static int TLSX_ALPN_ParseAndSet(WOLFSSL *ssl, const byte *input, word16 length,
  1468. byte isRequest)
  1469. {
  1470. word16 size = 0, offset = 0, wlen;
  1471. int r = BUFFER_ERROR;
  1472. const byte *s;
  1473. if (OPAQUE16_LEN > length)
  1474. return BUFFER_ERROR;
  1475. ato16(input, &size);
  1476. offset += OPAQUE16_LEN;
  1477. /* validating alpn list length */
  1478. if (size == 0 || length != OPAQUE16_LEN + size)
  1479. return BUFFER_ERROR;
  1480. /* validating length of entries before accepting */
  1481. for (s = input + offset; (s - input) < size; s += wlen) {
  1482. wlen = *s++;
  1483. if (wlen == 0 || (s + wlen - input) > length)
  1484. return BUFFER_ERROR;
  1485. }
  1486. if (isRequest) {
  1487. /* keep the list sent by peer, if this is from a request. We
  1488. * use it later in ALPN_Select() for evaluation. */
  1489. if (ssl->alpn_peer_requested != NULL) {
  1490. XFREE(ssl->alpn_peer_requested, ssl->heap, DYNAMIC_TYPE_ALPN);
  1491. ssl->alpn_peer_requested_length = 0;
  1492. }
  1493. ssl->alpn_peer_requested = (byte *)XMALLOC(size, ssl->heap,
  1494. DYNAMIC_TYPE_ALPN);
  1495. if (ssl->alpn_peer_requested == NULL) {
  1496. return MEMORY_ERROR;
  1497. }
  1498. ssl->alpn_peer_requested_length = size;
  1499. XMEMCPY(ssl->alpn_peer_requested, (char*)input + offset, size);
  1500. }
  1501. else {
  1502. /* a response, we should find the value in our config */
  1503. const byte *sel = NULL;
  1504. byte sel_len = 0;
  1505. TLSX *extension = NULL;
  1506. r = ALPN_find_match(ssl, &extension, &sel, &sel_len, input + offset, size);
  1507. if (r != 0)
  1508. return r;
  1509. if (sel != NULL) {
  1510. /* set the matching negotiated protocol */
  1511. r = TLSX_SetALPN(&ssl->extensions, sel, sel_len, ssl->heap);
  1512. if (r != WOLFSSL_SUCCESS) {
  1513. WOLFSSL_MSG("TLSX_SetALPN failed");
  1514. return BUFFER_ERROR;
  1515. }
  1516. }
  1517. /* If we had nothing configured, the response is unexpected */
  1518. else if (extension == NULL) {
  1519. r = TLSX_HandleUnsupportedExtension(ssl);
  1520. if (r != 0)
  1521. return r;
  1522. }
  1523. }
  1524. return 0;
  1525. }
  1526. /** Add a protocol name to the list of accepted usable ones */
  1527. int TLSX_UseALPN(TLSX** extensions, const void* data, word16 size, byte options,
  1528. void* heap)
  1529. {
  1530. ALPN *alpn;
  1531. TLSX *extension;
  1532. int ret;
  1533. if (extensions == NULL || data == NULL)
  1534. return BAD_FUNC_ARG;
  1535. alpn = TLSX_ALPN_New((char *)data, size, heap);
  1536. if (alpn == NULL) {
  1537. WOLFSSL_MSG("Memory failure");
  1538. return MEMORY_E;
  1539. }
  1540. /* Set Options of ALPN */
  1541. alpn->options = options;
  1542. extension = TLSX_Find(*extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1543. if (extension == NULL) {
  1544. ret = TLSX_Push(extensions, TLSX_APPLICATION_LAYER_PROTOCOL,
  1545. (void*)alpn, heap);
  1546. if (ret != 0) {
  1547. TLSX_ALPN_Free(alpn, heap);
  1548. return ret;
  1549. }
  1550. }
  1551. else {
  1552. /* push new ALPN object to extension data. */
  1553. alpn->next = (ALPN*)extension->data;
  1554. extension->data = (void*)alpn;
  1555. }
  1556. return WOLFSSL_SUCCESS;
  1557. }
  1558. /** Get the protocol name set by the server */
  1559. int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz)
  1560. {
  1561. TLSX *extension;
  1562. ALPN *alpn;
  1563. if (extensions == NULL || data == NULL || dataSz == NULL)
  1564. return BAD_FUNC_ARG;
  1565. *data = NULL;
  1566. *dataSz = 0;
  1567. extension = TLSX_Find(extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1568. if (extension == NULL) {
  1569. WOLFSSL_MSG("TLS extension not found");
  1570. WOLFSSL_ERROR_VERBOSE(WOLFSSL_ALPN_NOT_FOUND);
  1571. return WOLFSSL_ALPN_NOT_FOUND;
  1572. }
  1573. alpn = (ALPN *)extension->data;
  1574. if (alpn == NULL) {
  1575. WOLFSSL_MSG("ALPN extension not found");
  1576. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1577. return WOLFSSL_FATAL_ERROR;
  1578. }
  1579. if (alpn->negotiated != 1) {
  1580. /* consider as an error */
  1581. if (alpn->options & WOLFSSL_ALPN_FAILED_ON_MISMATCH) {
  1582. WOLFSSL_MSG("No protocol match with peer -> Failed");
  1583. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1584. return WOLFSSL_FATAL_ERROR;
  1585. }
  1586. /* continue without negotiated protocol */
  1587. WOLFSSL_MSG("No protocol match with peer -> Continue");
  1588. WOLFSSL_ERROR_VERBOSE(WOLFSSL_ALPN_NOT_FOUND);
  1589. return WOLFSSL_ALPN_NOT_FOUND;
  1590. }
  1591. if (alpn->next != NULL) {
  1592. WOLFSSL_MSG("Only one protocol name must be accepted");
  1593. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1594. return WOLFSSL_FATAL_ERROR;
  1595. }
  1596. *data = alpn->protocol_name;
  1597. *dataSz = (word16)XSTRLEN((char*)*data);
  1598. return WOLFSSL_SUCCESS;
  1599. }
  1600. #define ALPN_FREE_ALL TLSX_ALPN_FreeAll
  1601. #define ALPN_GET_SIZE TLSX_ALPN_GetSize
  1602. #define ALPN_WRITE TLSX_ALPN_Write
  1603. #define ALPN_PARSE TLSX_ALPN_ParseAndSet
  1604. #else /* HAVE_ALPN */
  1605. #define ALPN_FREE_ALL(list, heap) WC_DO_NOTHING
  1606. #define ALPN_GET_SIZE(list) 0
  1607. #define ALPN_WRITE(a, b) 0
  1608. #define ALPN_PARSE(a, b, c, d) 0
  1609. #endif /* HAVE_ALPN */
  1610. /******************************************************************************/
  1611. /* Server Name Indication */
  1612. /******************************************************************************/
  1613. #ifdef HAVE_SNI
  1614. /** Creates a new SNI object. */
  1615. static SNI* TLSX_SNI_New(byte type, const void* data, word16 size, void* heap)
  1616. {
  1617. SNI* sni = (SNI*)XMALLOC(sizeof(SNI), heap, DYNAMIC_TYPE_TLSX);
  1618. (void)heap;
  1619. if (sni) {
  1620. sni->type = type;
  1621. sni->next = NULL;
  1622. #ifndef NO_WOLFSSL_SERVER
  1623. sni->options = 0;
  1624. sni->status = WOLFSSL_SNI_NO_MATCH;
  1625. #endif
  1626. switch (sni->type) {
  1627. case WOLFSSL_SNI_HOST_NAME:
  1628. sni->data.host_name = (char*)XMALLOC(size + 1, heap,
  1629. DYNAMIC_TYPE_TLSX);
  1630. if (sni->data.host_name) {
  1631. XSTRNCPY(sni->data.host_name, (const char*)data, size);
  1632. sni->data.host_name[size] = '\0';
  1633. } else {
  1634. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1635. sni = NULL;
  1636. }
  1637. break;
  1638. default: /* invalid type */
  1639. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1640. sni = NULL;
  1641. }
  1642. }
  1643. return sni;
  1644. }
  1645. /** Releases a SNI object. */
  1646. static void TLSX_SNI_Free(SNI* sni, void* heap)
  1647. {
  1648. if (sni) {
  1649. switch (sni->type) {
  1650. case WOLFSSL_SNI_HOST_NAME:
  1651. XFREE(sni->data.host_name, heap, DYNAMIC_TYPE_TLSX);
  1652. break;
  1653. }
  1654. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1655. }
  1656. (void)heap;
  1657. }
  1658. /** Releases all SNI objects in the provided list. */
  1659. static void TLSX_SNI_FreeAll(SNI* list, void* heap)
  1660. {
  1661. SNI* sni;
  1662. while ((sni = list)) {
  1663. list = sni->next;
  1664. TLSX_SNI_Free(sni, heap);
  1665. }
  1666. }
  1667. /** Tells the buffered size of the SNI objects in a list. */
  1668. static word16 TLSX_SNI_GetSize(SNI* list)
  1669. {
  1670. SNI* sni;
  1671. word16 length = OPAQUE16_LEN; /* list length */
  1672. while ((sni = list)) {
  1673. list = sni->next;
  1674. length += ENUM_LEN + OPAQUE16_LEN; /* sni type + sni length */
  1675. switch (sni->type) {
  1676. case WOLFSSL_SNI_HOST_NAME:
  1677. length += (word16)XSTRLEN((char*)sni->data.host_name);
  1678. break;
  1679. }
  1680. }
  1681. return length;
  1682. }
  1683. /** Writes the SNI objects of a list in a buffer. */
  1684. static word16 TLSX_SNI_Write(SNI* list, byte* output)
  1685. {
  1686. SNI* sni;
  1687. word16 length = 0;
  1688. word16 offset = OPAQUE16_LEN; /* list length offset */
  1689. while ((sni = list)) {
  1690. list = sni->next;
  1691. output[offset++] = sni->type; /* sni type */
  1692. switch (sni->type) {
  1693. case WOLFSSL_SNI_HOST_NAME:
  1694. length = (word16)XSTRLEN((char*)sni->data.host_name);
  1695. c16toa(length, output + offset); /* sni length */
  1696. offset += OPAQUE16_LEN;
  1697. XMEMCPY(output + offset, sni->data.host_name, length);
  1698. offset += length;
  1699. break;
  1700. }
  1701. }
  1702. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  1703. return offset;
  1704. }
  1705. /** Finds a SNI object in the provided list. */
  1706. static SNI* TLSX_SNI_Find(SNI *list, byte type)
  1707. {
  1708. SNI* sni = list;
  1709. while (sni && sni->type != type)
  1710. sni = sni->next;
  1711. return sni;
  1712. }
  1713. #if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
  1714. /** Sets the status of a SNI object. */
  1715. static void TLSX_SNI_SetStatus(TLSX* extensions, byte type, byte status)
  1716. {
  1717. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1718. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1719. if (sni)
  1720. sni->status = status;
  1721. }
  1722. #endif
  1723. /** Gets the status of a SNI object. */
  1724. byte TLSX_SNI_Status(TLSX* extensions, byte type)
  1725. {
  1726. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1727. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1728. if (sni)
  1729. return sni->status;
  1730. return 0;
  1731. }
  1732. /** Parses a buffer of SNI extensions. */
  1733. static int TLSX_SNI_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  1734. byte isRequest)
  1735. {
  1736. #ifndef NO_WOLFSSL_SERVER
  1737. word16 size = 0;
  1738. word16 offset = 0;
  1739. int cacheOnly = 0;
  1740. SNI *sni = NULL;
  1741. byte type;
  1742. byte matched;
  1743. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1744. WOLFSSL_ECH* ech = NULL;
  1745. WOLFSSL_EchConfig* workingConfig;
  1746. TLSX* echX;
  1747. #endif
  1748. #endif /* !NO_WOLFSSL_SERVER */
  1749. TLSX *extension = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  1750. if (!extension)
  1751. extension = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  1752. if (!isRequest) {
  1753. #ifndef NO_WOLFSSL_CLIENT
  1754. if (!extension || !extension->data)
  1755. return TLSX_HandleUnsupportedExtension(ssl);
  1756. if (length > 0)
  1757. return BUFFER_ERROR; /* SNI response MUST be empty. */
  1758. /* This call enables wolfSSL_SNI_GetRequest() to be called in the
  1759. * client side to fetch the used SNI. It will only work if the SNI
  1760. * was set at the SSL object level. Right now we only support one
  1761. * name type, WOLFSSL_SNI_HOST_NAME, but in the future, the
  1762. * inclusion of other name types will turn this method inaccurate,
  1763. * as the extension response doesn't contains information of which
  1764. * name was accepted.
  1765. */
  1766. TLSX_SNI_SetStatus(ssl->extensions, WOLFSSL_SNI_HOST_NAME,
  1767. WOLFSSL_SNI_REAL_MATCH);
  1768. return 0;
  1769. #endif
  1770. }
  1771. #ifndef NO_WOLFSSL_SERVER
  1772. if (!extension || !extension->data) {
  1773. /* This will keep SNI even though TLSX_UseSNI has not been called.
  1774. * Enable it so that the received sni is available to functions
  1775. * that use a custom callback when SNI is received.
  1776. */
  1777. #ifdef WOLFSSL_ALWAYS_KEEP_SNI
  1778. cacheOnly = 1;
  1779. #endif
  1780. if (ssl->ctx->sniRecvCb) {
  1781. cacheOnly = 1;
  1782. }
  1783. if (cacheOnly) {
  1784. WOLFSSL_MSG("Forcing SSL object to store SNI parameter");
  1785. }
  1786. else {
  1787. /* Skipping, SNI not enabled at server side. */
  1788. return 0;
  1789. }
  1790. }
  1791. if (OPAQUE16_LEN > length)
  1792. return BUFFER_ERROR;
  1793. ato16(input, &size);
  1794. offset += OPAQUE16_LEN;
  1795. /* validating sni list length */
  1796. if (length != OPAQUE16_LEN + size || size == 0)
  1797. return BUFFER_ERROR;
  1798. /* SNI was badly specified and only one type is now recognized and allowed.
  1799. * Only one SNI value per type (RFC6066), so, no loop. */
  1800. type = input[offset++];
  1801. if (type != WOLFSSL_SNI_HOST_NAME)
  1802. return BUFFER_ERROR;
  1803. if (offset + OPAQUE16_LEN > length)
  1804. return BUFFER_ERROR;
  1805. ato16(input + offset, &size);
  1806. offset += OPAQUE16_LEN;
  1807. if (offset + size != length || size == 0)
  1808. return BUFFER_ERROR;
  1809. if (!cacheOnly && !(sni = TLSX_SNI_Find((SNI*)extension->data, type)))
  1810. return 0; /* not using this type of SNI. */
  1811. #ifdef WOLFSSL_TLS13
  1812. /* Don't process the second ClientHello SNI extension if there
  1813. * was problems with the first.
  1814. */
  1815. if (!cacheOnly && sni->status != 0)
  1816. return 0;
  1817. #endif
  1818. matched = cacheOnly || (XSTRLEN(sni->data.host_name) == size &&
  1819. XSTRNCMP(sni->data.host_name, (const char*)input + offset, size) == 0);
  1820. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1821. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  1822. if (echX != NULL)
  1823. ech = (WOLFSSL_ECH*)(echX->data);
  1824. if (!matched && ech != NULL) {
  1825. workingConfig = ech->echConfig;
  1826. while (workingConfig != NULL) {
  1827. matched = XSTRLEN(workingConfig->publicName) == size &&
  1828. XSTRNCMP(workingConfig->publicName,
  1829. (const char*)input + offset, size) == 0;
  1830. if (matched)
  1831. break;
  1832. workingConfig = workingConfig->next;
  1833. }
  1834. }
  1835. #endif
  1836. if (matched || sni->options & WOLFSSL_SNI_ANSWER_ON_MISMATCH) {
  1837. int matchStat;
  1838. int r = TLSX_UseSNI(&ssl->extensions, type, input + offset, size,
  1839. ssl->heap);
  1840. if (r != WOLFSSL_SUCCESS)
  1841. return r; /* throws error. */
  1842. if (cacheOnly) {
  1843. WOLFSSL_MSG("Forcing storage of SNI, Fake match");
  1844. matchStat = WOLFSSL_SNI_FORCE_KEEP;
  1845. }
  1846. else if (matched) {
  1847. WOLFSSL_MSG("SNI did match!");
  1848. matchStat = WOLFSSL_SNI_REAL_MATCH;
  1849. }
  1850. else {
  1851. WOLFSSL_MSG("fake SNI match from ANSWER_ON_MISMATCH");
  1852. matchStat = WOLFSSL_SNI_FAKE_MATCH;
  1853. }
  1854. TLSX_SNI_SetStatus(ssl->extensions, type, (byte)matchStat);
  1855. if (!cacheOnly)
  1856. TLSX_SetResponse(ssl, TLSX_SERVER_NAME);
  1857. }
  1858. else if (!(sni->options & WOLFSSL_SNI_CONTINUE_ON_MISMATCH)) {
  1859. SendAlert(ssl, alert_fatal, unrecognized_name);
  1860. WOLFSSL_ERROR_VERBOSE(UNKNOWN_SNI_HOST_NAME_E);
  1861. return UNKNOWN_SNI_HOST_NAME_E;
  1862. }
  1863. #else
  1864. (void)input;
  1865. #endif /* !NO_WOLFSSL_SERVER */
  1866. #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER)
  1867. (void)length;
  1868. #endif
  1869. return 0;
  1870. }
  1871. static int TLSX_SNI_VerifyParse(WOLFSSL* ssl, byte isRequest)
  1872. {
  1873. (void)ssl;
  1874. if (isRequest) {
  1875. #ifndef NO_WOLFSSL_SERVER
  1876. TLSX* ctx_ext = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  1877. TLSX* ssl_ext = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  1878. SNI* ctx_sni = ctx_ext ? (SNI*)ctx_ext->data : NULL;
  1879. SNI* ssl_sni = ssl_ext ? (SNI*)ssl_ext->data : NULL;
  1880. SNI* sni = NULL;
  1881. for (; ctx_sni; ctx_sni = ctx_sni->next) {
  1882. if (ctx_sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) {
  1883. sni = TLSX_SNI_Find(ssl_sni, ctx_sni->type);
  1884. if (sni) {
  1885. if (sni->status != WOLFSSL_SNI_NO_MATCH)
  1886. continue;
  1887. /* if ssl level overrides ctx level, it is ok. */
  1888. if ((sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) == 0)
  1889. continue;
  1890. }
  1891. SendAlert(ssl, alert_fatal, handshake_failure);
  1892. WOLFSSL_ERROR_VERBOSE(SNI_ABSENT_ERROR);
  1893. return SNI_ABSENT_ERROR;
  1894. }
  1895. }
  1896. for (; ssl_sni; ssl_sni = ssl_sni->next) {
  1897. if (ssl_sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) {
  1898. if (ssl_sni->status != WOLFSSL_SNI_NO_MATCH)
  1899. continue;
  1900. SendAlert(ssl, alert_fatal, handshake_failure);
  1901. WOLFSSL_ERROR_VERBOSE(SNI_ABSENT_ERROR);
  1902. return SNI_ABSENT_ERROR;
  1903. }
  1904. }
  1905. #endif /* NO_WOLFSSL_SERVER */
  1906. }
  1907. return 0;
  1908. }
  1909. int TLSX_UseSNI(TLSX** extensions, byte type, const void* data, word16 size,
  1910. void* heap)
  1911. {
  1912. TLSX* extension;
  1913. SNI* sni = NULL;
  1914. if (extensions == NULL || data == NULL)
  1915. return BAD_FUNC_ARG;
  1916. if ((sni = TLSX_SNI_New(type, data, size, heap)) == NULL)
  1917. return MEMORY_E;
  1918. extension = TLSX_Find(*extensions, TLSX_SERVER_NAME);
  1919. if (!extension) {
  1920. int ret = TLSX_Push(extensions, TLSX_SERVER_NAME, (void*)sni, heap);
  1921. if (ret != 0) {
  1922. TLSX_SNI_Free(sni, heap);
  1923. return ret;
  1924. }
  1925. }
  1926. else {
  1927. /* push new SNI object to extension data. */
  1928. sni->next = (SNI*)extension->data;
  1929. extension->data = (void*)sni;
  1930. /* remove duplicate SNI, there should be only one of each type. */
  1931. do {
  1932. if (sni->next && sni->next->type == type) {
  1933. SNI* next = sni->next;
  1934. sni->next = next->next;
  1935. TLSX_SNI_Free(next, heap);
  1936. /* there is no way to occur more than
  1937. * two SNIs of the same type.
  1938. */
  1939. break;
  1940. }
  1941. } while ((sni = sni->next));
  1942. }
  1943. return WOLFSSL_SUCCESS;
  1944. }
  1945. #ifndef NO_WOLFSSL_SERVER
  1946. /** Tells the SNI requested by the client. */
  1947. word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type, void** data)
  1948. {
  1949. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1950. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1951. if (sni && sni->status != WOLFSSL_SNI_NO_MATCH) {
  1952. switch (sni->type) {
  1953. case WOLFSSL_SNI_HOST_NAME:
  1954. if (data) {
  1955. *data = sni->data.host_name;
  1956. return (word16)XSTRLEN((char*)*data);
  1957. }
  1958. }
  1959. }
  1960. return 0;
  1961. }
  1962. /** Sets the options for a SNI object. */
  1963. void TLSX_SNI_SetOptions(TLSX* extensions, byte type, byte options)
  1964. {
  1965. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1966. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1967. if (sni)
  1968. sni->options = options;
  1969. }
  1970. /** Retrieves a SNI request from a client hello buffer. */
  1971. int TLSX_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz,
  1972. byte type, byte* sni, word32* inOutSz)
  1973. {
  1974. word32 offset = 0;
  1975. word32 len32 = 0;
  1976. word16 len16 = 0;
  1977. if (helloSz < RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + CLIENT_HELLO_FIRST)
  1978. return INCOMPLETE_DATA;
  1979. /* TLS record header */
  1980. if ((enum ContentType) clientHello[offset++] != handshake) {
  1981. /* checking for SSLv2.0 client hello according to: */
  1982. /* http://tools.ietf.org/html/rfc4346#appendix-E.1 */
  1983. if ((enum HandShakeType) clientHello[++offset] == client_hello) {
  1984. offset += ENUM_LEN + VERSION_SZ; /* skip version */
  1985. ato16(clientHello + offset, &len16);
  1986. offset += OPAQUE16_LEN;
  1987. if (len16 % 3) /* cipher_spec_length must be multiple of 3 */
  1988. return BUFFER_ERROR;
  1989. ato16(clientHello + offset, &len16);
  1990. /* Returning SNI_UNSUPPORTED do not increment offset here */
  1991. if (len16 != 0) /* session_id_length must be 0 */
  1992. return BUFFER_ERROR;
  1993. WOLFSSL_ERROR_VERBOSE(SNI_UNSUPPORTED);
  1994. return SNI_UNSUPPORTED;
  1995. }
  1996. return BUFFER_ERROR;
  1997. }
  1998. if (clientHello[offset++] != SSLv3_MAJOR)
  1999. return BUFFER_ERROR;
  2000. if (clientHello[offset++] < TLSv1_MINOR) {
  2001. WOLFSSL_ERROR_VERBOSE(SNI_UNSUPPORTED);
  2002. return SNI_UNSUPPORTED;
  2003. }
  2004. ato16(clientHello + offset, &len16);
  2005. offset += OPAQUE16_LEN;
  2006. if (offset + len16 > helloSz)
  2007. return INCOMPLETE_DATA;
  2008. /* Handshake header */
  2009. if ((enum HandShakeType) clientHello[offset] != client_hello)
  2010. return BUFFER_ERROR;
  2011. c24to32(clientHello + offset + 1, &len32);
  2012. offset += HANDSHAKE_HEADER_SZ;
  2013. if (offset + len32 > helloSz)
  2014. return BUFFER_ERROR;
  2015. /* client hello */
  2016. offset += VERSION_SZ + RAN_LEN; /* version, random */
  2017. if (helloSz < offset + clientHello[offset])
  2018. return BUFFER_ERROR;
  2019. offset += ENUM_LEN + clientHello[offset]; /* skip session id */
  2020. /* cypher suites */
  2021. if (helloSz < offset + OPAQUE16_LEN)
  2022. return BUFFER_ERROR;
  2023. ato16(clientHello + offset, &len16);
  2024. offset += OPAQUE16_LEN;
  2025. if (helloSz < offset + len16)
  2026. return BUFFER_ERROR;
  2027. offset += len16; /* skip cypher suites */
  2028. /* compression methods */
  2029. if (helloSz < offset + 1)
  2030. return BUFFER_ERROR;
  2031. if (helloSz < offset + clientHello[offset])
  2032. return BUFFER_ERROR;
  2033. offset += ENUM_LEN + clientHello[offset]; /* skip compression methods */
  2034. /* extensions */
  2035. if (helloSz < offset + OPAQUE16_LEN)
  2036. return 0; /* no extensions in client hello. */
  2037. ato16(clientHello + offset, &len16);
  2038. offset += OPAQUE16_LEN;
  2039. if (helloSz < offset + len16)
  2040. return BUFFER_ERROR;
  2041. while (len16 >= OPAQUE16_LEN + OPAQUE16_LEN) {
  2042. word16 extType;
  2043. word16 extLen;
  2044. ato16(clientHello + offset, &extType);
  2045. offset += OPAQUE16_LEN;
  2046. ato16(clientHello + offset, &extLen);
  2047. offset += OPAQUE16_LEN;
  2048. if (helloSz < offset + extLen)
  2049. return BUFFER_ERROR;
  2050. if (extType != TLSX_SERVER_NAME) {
  2051. offset += extLen; /* skip extension */
  2052. } else {
  2053. word16 listLen;
  2054. ato16(clientHello + offset, &listLen);
  2055. offset += OPAQUE16_LEN;
  2056. if (helloSz < offset + listLen)
  2057. return BUFFER_ERROR;
  2058. while (listLen > ENUM_LEN + OPAQUE16_LEN) {
  2059. byte sniType = clientHello[offset++];
  2060. word16 sniLen;
  2061. ato16(clientHello + offset, &sniLen);
  2062. offset += OPAQUE16_LEN;
  2063. if (helloSz < offset + sniLen)
  2064. return BUFFER_ERROR;
  2065. if (sniType != type) {
  2066. offset += sniLen;
  2067. listLen -= min(ENUM_LEN + OPAQUE16_LEN + sniLen, listLen);
  2068. continue;
  2069. }
  2070. *inOutSz = min(sniLen, *inOutSz);
  2071. XMEMCPY(sni, clientHello + offset, *inOutSz);
  2072. return WOLFSSL_SUCCESS;
  2073. }
  2074. }
  2075. len16 -= min(2 * OPAQUE16_LEN + extLen, len16);
  2076. }
  2077. return len16 ? BUFFER_ERROR : 0;
  2078. }
  2079. #endif
  2080. #define SNI_FREE_ALL TLSX_SNI_FreeAll
  2081. #define SNI_GET_SIZE TLSX_SNI_GetSize
  2082. #define SNI_WRITE TLSX_SNI_Write
  2083. #define SNI_PARSE TLSX_SNI_Parse
  2084. #define SNI_VERIFY_PARSE TLSX_SNI_VerifyParse
  2085. #else
  2086. #define SNI_FREE_ALL(list, heap) WC_DO_NOTHING
  2087. #define SNI_GET_SIZE(list) 0
  2088. #define SNI_WRITE(a, b) 0
  2089. #define SNI_PARSE(a, b, c, d) 0
  2090. #define SNI_VERIFY_PARSE(a, b) 0
  2091. #endif /* HAVE_SNI */
  2092. /******************************************************************************/
  2093. /* Trusted CA Key Indication */
  2094. /******************************************************************************/
  2095. #ifdef HAVE_TRUSTED_CA
  2096. /** Creates a new TCA object. */
  2097. static TCA* TLSX_TCA_New(byte type, const byte* id, word16 idSz, void* heap)
  2098. {
  2099. TCA* tca = (TCA*)XMALLOC(sizeof(TCA), heap, DYNAMIC_TYPE_TLSX);
  2100. if (tca) {
  2101. XMEMSET(tca, 0, sizeof(TCA));
  2102. tca->type = type;
  2103. switch (type) {
  2104. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2105. break;
  2106. #ifndef NO_SHA
  2107. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2108. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2109. if (idSz == WC_SHA_DIGEST_SIZE &&
  2110. (tca->id =
  2111. (byte*)XMALLOC(idSz, heap, DYNAMIC_TYPE_TLSX))) {
  2112. XMEMCPY(tca->id, id, idSz);
  2113. tca->idSz = idSz;
  2114. }
  2115. else {
  2116. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2117. tca = NULL;
  2118. }
  2119. break;
  2120. #endif
  2121. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2122. if (idSz > 0 &&
  2123. (tca->id =
  2124. (byte*)XMALLOC(idSz, heap, DYNAMIC_TYPE_TLSX))) {
  2125. XMEMCPY(tca->id, id, idSz);
  2126. tca->idSz = idSz;
  2127. }
  2128. else {
  2129. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2130. tca = NULL;
  2131. }
  2132. break;
  2133. default: /* invalid type */
  2134. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2135. tca = NULL;
  2136. }
  2137. }
  2138. (void)heap;
  2139. return tca;
  2140. }
  2141. /** Releases a TCA object. */
  2142. static void TLSX_TCA_Free(TCA* tca, void* heap)
  2143. {
  2144. (void)heap;
  2145. if (tca) {
  2146. if (tca->id)
  2147. XFREE(tca->id, heap, DYNAMIC_TYPE_TLSX);
  2148. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2149. }
  2150. }
  2151. /** Releases all TCA objects in the provided list. */
  2152. static void TLSX_TCA_FreeAll(TCA* list, void* heap)
  2153. {
  2154. TCA* tca;
  2155. while ((tca = list)) {
  2156. list = tca->next;
  2157. TLSX_TCA_Free(tca, heap);
  2158. }
  2159. }
  2160. /** Tells the buffered size of the TCA objects in a list. */
  2161. static word16 TLSX_TCA_GetSize(TCA* list)
  2162. {
  2163. TCA* tca;
  2164. word16 length = OPAQUE16_LEN; /* list length */
  2165. while ((tca = list)) {
  2166. list = tca->next;
  2167. length += ENUM_LEN; /* tca type */
  2168. switch (tca->type) {
  2169. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2170. break;
  2171. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2172. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2173. length += tca->idSz;
  2174. break;
  2175. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2176. length += OPAQUE16_LEN + tca->idSz;
  2177. break;
  2178. }
  2179. }
  2180. return length;
  2181. }
  2182. /** Writes the TCA objects of a list in a buffer. */
  2183. static word16 TLSX_TCA_Write(TCA* list, byte* output)
  2184. {
  2185. TCA* tca;
  2186. word16 offset = OPAQUE16_LEN; /* list length offset */
  2187. while ((tca = list)) {
  2188. list = tca->next;
  2189. output[offset++] = tca->type; /* tca type */
  2190. switch (tca->type) {
  2191. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2192. break;
  2193. #ifndef NO_SHA
  2194. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2195. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2196. if (tca->id != NULL) {
  2197. XMEMCPY(output + offset, tca->id, tca->idSz);
  2198. offset += tca->idSz;
  2199. }
  2200. else {
  2201. /* ID missing. Set to an empty string. */
  2202. c16toa(0, output + offset);
  2203. offset += OPAQUE16_LEN;
  2204. }
  2205. break;
  2206. #endif
  2207. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2208. if (tca->id != NULL) {
  2209. c16toa(tca->idSz, output + offset); /* tca length */
  2210. offset += OPAQUE16_LEN;
  2211. XMEMCPY(output + offset, tca->id, tca->idSz);
  2212. offset += tca->idSz;
  2213. }
  2214. else {
  2215. /* ID missing. Set to an empty string. */
  2216. c16toa(0, output + offset);
  2217. offset += OPAQUE16_LEN;
  2218. }
  2219. break;
  2220. default:
  2221. /* ID unknown. Set to an empty string. */
  2222. c16toa(0, output + offset);
  2223. offset += OPAQUE16_LEN;
  2224. }
  2225. }
  2226. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  2227. return offset;
  2228. }
  2229. #ifndef NO_WOLFSSL_SERVER
  2230. static TCA* TLSX_TCA_Find(TCA *list, byte type, const byte* id, word16 idSz)
  2231. {
  2232. TCA* tca = list;
  2233. while (tca && tca->type != type && type != WOLFSSL_TRUSTED_CA_PRE_AGREED &&
  2234. idSz != tca->idSz && !XMEMCMP(id, tca->id, idSz))
  2235. tca = tca->next;
  2236. return tca;
  2237. }
  2238. #endif /* NO_WOLFSSL_SERVER */
  2239. /** Parses a buffer of TCA extensions. */
  2240. static int TLSX_TCA_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2241. byte isRequest)
  2242. {
  2243. #ifndef NO_WOLFSSL_SERVER
  2244. word16 size = 0;
  2245. word16 offset = 0;
  2246. #endif
  2247. TLSX *extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS);
  2248. if (!extension)
  2249. extension = TLSX_Find(ssl->ctx->extensions, TLSX_TRUSTED_CA_KEYS);
  2250. if (!isRequest) {
  2251. #ifndef NO_WOLFSSL_CLIENT
  2252. if (!extension || !extension->data)
  2253. return TLSX_HandleUnsupportedExtension(ssl);
  2254. if (length > 0)
  2255. return BUFFER_ERROR; /* TCA response MUST be empty. */
  2256. /* Set the flag that we're good for keys */
  2257. TLSX_SetResponse(ssl, TLSX_TRUSTED_CA_KEYS);
  2258. return 0;
  2259. #endif
  2260. }
  2261. #ifndef NO_WOLFSSL_SERVER
  2262. if (!extension || !extension->data) {
  2263. /* Skipping, TCA not enabled at server side. */
  2264. return 0;
  2265. }
  2266. if (OPAQUE16_LEN > length)
  2267. return BUFFER_ERROR;
  2268. ato16(input, &size);
  2269. offset += OPAQUE16_LEN;
  2270. /* validating tca list length */
  2271. if (length != OPAQUE16_LEN + size)
  2272. return BUFFER_ERROR;
  2273. for (size = 0; offset < length; offset += size) {
  2274. TCA *tca = NULL;
  2275. byte type;
  2276. const byte* id = NULL;
  2277. word16 idSz = 0;
  2278. if (offset + ENUM_LEN > length)
  2279. return BUFFER_ERROR;
  2280. type = input[offset++];
  2281. switch (type) {
  2282. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2283. break;
  2284. #ifndef NO_SHA
  2285. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2286. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2287. if (offset + WC_SHA_DIGEST_SIZE > length)
  2288. return BUFFER_ERROR;
  2289. idSz = WC_SHA_DIGEST_SIZE;
  2290. id = input + offset;
  2291. offset += idSz;
  2292. break;
  2293. #endif
  2294. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2295. if (offset + OPAQUE16_LEN > length)
  2296. return BUFFER_ERROR;
  2297. ato16(input + offset, &idSz);
  2298. offset += OPAQUE16_LEN;
  2299. if ((offset > length) || (idSz > length - offset))
  2300. return BUFFER_ERROR;
  2301. id = input + offset;
  2302. offset += idSz;
  2303. break;
  2304. default:
  2305. WOLFSSL_ERROR_VERBOSE(TCA_INVALID_ID_TYPE);
  2306. return TCA_INVALID_ID_TYPE;
  2307. }
  2308. /* Find the type/ID in the TCA list. */
  2309. tca = TLSX_TCA_Find((TCA*)extension->data, type, id, idSz);
  2310. if (tca != NULL) {
  2311. /* Found it. Set the response flag and break out of the loop. */
  2312. TLSX_SetResponse(ssl, TLSX_TRUSTED_CA_KEYS);
  2313. break;
  2314. }
  2315. }
  2316. #else
  2317. (void)input;
  2318. #endif
  2319. return 0;
  2320. }
  2321. /* Checks to see if the server sent a response for the TCA. */
  2322. static int TLSX_TCA_VerifyParse(WOLFSSL* ssl, byte isRequest)
  2323. {
  2324. (void)ssl;
  2325. if (!isRequest) {
  2326. #ifndef NO_WOLFSSL_CLIENT
  2327. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS);
  2328. if (extension && !extension->resp) {
  2329. SendAlert(ssl, alert_fatal, handshake_failure);
  2330. WOLFSSL_ERROR_VERBOSE(TCA_ABSENT_ERROR);
  2331. return TCA_ABSENT_ERROR;
  2332. }
  2333. #endif /* NO_WOLFSSL_CLIENT */
  2334. }
  2335. return 0;
  2336. }
  2337. int TLSX_UseTrustedCA(TLSX** extensions, byte type,
  2338. const byte* id, word16 idSz, void* heap)
  2339. {
  2340. TLSX* extension;
  2341. TCA* tca = NULL;
  2342. if (extensions == NULL)
  2343. return BAD_FUNC_ARG;
  2344. if ((tca = TLSX_TCA_New(type, id, idSz, heap)) == NULL)
  2345. return MEMORY_E;
  2346. extension = TLSX_Find(*extensions, TLSX_TRUSTED_CA_KEYS);
  2347. if (!extension) {
  2348. int ret = TLSX_Push(extensions, TLSX_TRUSTED_CA_KEYS, (void*)tca, heap);
  2349. if (ret != 0) {
  2350. TLSX_TCA_Free(tca, heap);
  2351. return ret;
  2352. }
  2353. }
  2354. else {
  2355. /* push new TCA object to extension data. */
  2356. tca->next = (TCA*)extension->data;
  2357. extension->data = (void*)tca;
  2358. }
  2359. return WOLFSSL_SUCCESS;
  2360. }
  2361. #define TCA_FREE_ALL TLSX_TCA_FreeAll
  2362. #define TCA_GET_SIZE TLSX_TCA_GetSize
  2363. #define TCA_WRITE TLSX_TCA_Write
  2364. #define TCA_PARSE TLSX_TCA_Parse
  2365. #define TCA_VERIFY_PARSE TLSX_TCA_VerifyParse
  2366. #else /* HAVE_TRUSTED_CA */
  2367. #define TCA_FREE_ALL(list, heap) WC_DO_NOTHING
  2368. #define TCA_GET_SIZE(list) 0
  2369. #define TCA_WRITE(a, b) 0
  2370. #define TCA_PARSE(a, b, c, d) 0
  2371. #define TCA_VERIFY_PARSE(a, b) 0
  2372. #endif /* HAVE_TRUSTED_CA */
  2373. /******************************************************************************/
  2374. /* Max Fragment Length Negotiation */
  2375. /******************************************************************************/
  2376. #ifdef HAVE_MAX_FRAGMENT
  2377. static word16 TLSX_MFL_Write(byte* data, byte* output)
  2378. {
  2379. output[0] = data[0];
  2380. return ENUM_LEN;
  2381. }
  2382. static int TLSX_MFL_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2383. byte isRequest)
  2384. {
  2385. if (length != ENUM_LEN)
  2386. return BUFFER_ERROR;
  2387. #ifdef WOLFSSL_OLD_UNSUPPORTED_EXTENSION
  2388. (void) isRequest;
  2389. #else
  2390. if (!isRequest)
  2391. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_MAX_FRAGMENT_LENGTH))
  2392. return TLSX_HandleUnsupportedExtension(ssl);
  2393. #endif
  2394. switch (*input) {
  2395. case WOLFSSL_MFL_2_8 : ssl->max_fragment = 256; break;
  2396. case WOLFSSL_MFL_2_9 : ssl->max_fragment = 512; break;
  2397. case WOLFSSL_MFL_2_10: ssl->max_fragment = 1024; break;
  2398. case WOLFSSL_MFL_2_11: ssl->max_fragment = 2048; break;
  2399. case WOLFSSL_MFL_2_12: ssl->max_fragment = 4096; break;
  2400. case WOLFSSL_MFL_2_13: ssl->max_fragment = 8192; break;
  2401. default:
  2402. SendAlert(ssl, alert_fatal, illegal_parameter);
  2403. WOLFSSL_ERROR_VERBOSE(UNKNOWN_MAX_FRAG_LEN_E);
  2404. return UNKNOWN_MAX_FRAG_LEN_E;
  2405. }
  2406. #ifndef NO_WOLFSSL_SERVER
  2407. if (isRequest) {
  2408. int ret = TLSX_UseMaxFragment(&ssl->extensions, *input, ssl->heap);
  2409. if (ret != WOLFSSL_SUCCESS)
  2410. return ret; /* throw error */
  2411. TLSX_SetResponse(ssl, TLSX_MAX_FRAGMENT_LENGTH);
  2412. }
  2413. #endif
  2414. return 0;
  2415. }
  2416. int TLSX_UseMaxFragment(TLSX** extensions, byte mfl, void* heap)
  2417. {
  2418. byte* data = NULL;
  2419. int ret = 0;
  2420. if (extensions == NULL || mfl < WOLFSSL_MFL_MIN || mfl > WOLFSSL_MFL_MAX)
  2421. return BAD_FUNC_ARG;
  2422. data = (byte*)XMALLOC(ENUM_LEN, heap, DYNAMIC_TYPE_TLSX);
  2423. if (data == NULL)
  2424. return MEMORY_E;
  2425. data[0] = mfl;
  2426. ret = TLSX_Push(extensions, TLSX_MAX_FRAGMENT_LENGTH, data, heap);
  2427. if (ret != 0) {
  2428. XFREE(data, heap, DYNAMIC_TYPE_TLSX);
  2429. return ret;
  2430. }
  2431. return WOLFSSL_SUCCESS;
  2432. }
  2433. #define MFL_FREE_ALL(data, heap) XFREE(data, (heap), DYNAMIC_TYPE_TLSX)
  2434. #define MFL_GET_SIZE(data) ENUM_LEN
  2435. #define MFL_WRITE TLSX_MFL_Write
  2436. #define MFL_PARSE TLSX_MFL_Parse
  2437. #else
  2438. #define MFL_FREE_ALL(a, b) WC_DO_NOTHING
  2439. #define MFL_GET_SIZE(a) 0
  2440. #define MFL_WRITE(a, b) 0
  2441. #define MFL_PARSE(a, b, c, d) 0
  2442. #endif /* HAVE_MAX_FRAGMENT */
  2443. /******************************************************************************/
  2444. /* Truncated HMAC */
  2445. /******************************************************************************/
  2446. #ifdef HAVE_TRUNCATED_HMAC
  2447. static int TLSX_THM_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2448. byte isRequest)
  2449. {
  2450. if (length != 0 || input == NULL)
  2451. return BUFFER_ERROR;
  2452. if (!isRequest) {
  2453. #ifndef WOLFSSL_OLD_UNSUPPORTED_EXTENSION
  2454. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_TRUNCATED_HMAC))
  2455. return TLSX_HandleUnsupportedExtension(ssl);
  2456. #endif
  2457. }
  2458. else {
  2459. #ifndef NO_WOLFSSL_SERVER
  2460. int ret = TLSX_UseTruncatedHMAC(&ssl->extensions, ssl->heap);
  2461. if (ret != WOLFSSL_SUCCESS)
  2462. return ret; /* throw error */
  2463. TLSX_SetResponse(ssl, TLSX_TRUNCATED_HMAC);
  2464. #endif
  2465. }
  2466. ssl->truncated_hmac = 1;
  2467. return 0;
  2468. }
  2469. int TLSX_UseTruncatedHMAC(TLSX** extensions, void* heap)
  2470. {
  2471. int ret = 0;
  2472. if (extensions == NULL)
  2473. return BAD_FUNC_ARG;
  2474. ret = TLSX_Push(extensions, TLSX_TRUNCATED_HMAC, NULL, heap);
  2475. if (ret != 0)
  2476. return ret;
  2477. return WOLFSSL_SUCCESS;
  2478. }
  2479. #define THM_PARSE TLSX_THM_Parse
  2480. #else
  2481. #define THM_PARSE(a, b, c, d) 0
  2482. #endif /* HAVE_TRUNCATED_HMAC */
  2483. /******************************************************************************/
  2484. /* Certificate Status Request */
  2485. /******************************************************************************/
  2486. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  2487. static void TLSX_CSR_Free(CertificateStatusRequest* csr, void* heap)
  2488. {
  2489. switch (csr->status_type) {
  2490. case WOLFSSL_CSR_OCSP:
  2491. FreeOcspRequest(&csr->request.ocsp);
  2492. break;
  2493. }
  2494. #ifdef WOLFSSL_TLS13
  2495. if (csr->response.buffer != NULL) {
  2496. XFREE(csr->response.buffer, csr->ssl->heap,
  2497. DYNAMIC_TYPE_TMP_BUFFER);
  2498. }
  2499. #endif
  2500. XFREE(csr, heap, DYNAMIC_TYPE_TLSX);
  2501. (void)heap;
  2502. }
  2503. static word16 TLSX_CSR_GetSize(CertificateStatusRequest* csr, byte isRequest)
  2504. {
  2505. word16 size = 0;
  2506. /* shut up compiler warnings */
  2507. (void) csr; (void) isRequest;
  2508. #ifndef NO_WOLFSSL_CLIENT
  2509. if (isRequest) {
  2510. switch (csr->status_type) {
  2511. case WOLFSSL_CSR_OCSP:
  2512. size += ENUM_LEN + 2 * OPAQUE16_LEN;
  2513. if (csr->request.ocsp.nonceSz)
  2514. size += OCSP_NONCE_EXT_SZ;
  2515. break;
  2516. }
  2517. }
  2518. #endif
  2519. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  2520. if (!isRequest && csr->ssl->options.tls1_3)
  2521. return OPAQUE8_LEN + OPAQUE24_LEN + csr->response.length;
  2522. #endif
  2523. return size;
  2524. }
  2525. static word16 TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output,
  2526. byte isRequest)
  2527. {
  2528. /* shut up compiler warnings */
  2529. (void) csr; (void) output; (void) isRequest;
  2530. #ifndef NO_WOLFSSL_CLIENT
  2531. if (isRequest) {
  2532. word16 offset = 0;
  2533. word16 length = 0;
  2534. /* type */
  2535. output[offset++] = csr->status_type;
  2536. switch (csr->status_type) {
  2537. case WOLFSSL_CSR_OCSP:
  2538. /* responder id list */
  2539. c16toa(0, output + offset);
  2540. offset += OPAQUE16_LEN;
  2541. /* request extensions */
  2542. if (csr->request.ocsp.nonceSz)
  2543. length = (word16)EncodeOcspRequestExtensions(
  2544. &csr->request.ocsp,
  2545. output + offset + OPAQUE16_LEN,
  2546. OCSP_NONCE_EXT_SZ);
  2547. c16toa(length, output + offset);
  2548. offset += OPAQUE16_LEN + length;
  2549. break;
  2550. }
  2551. return offset;
  2552. }
  2553. #endif
  2554. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  2555. if (!isRequest && csr->ssl->options.tls1_3) {
  2556. word16 offset = 0;
  2557. output[offset++] = csr->status_type;
  2558. c32to24(csr->response.length, output + offset);
  2559. offset += OPAQUE24_LEN;
  2560. XMEMCPY(output + offset, csr->response.buffer, csr->response.length);
  2561. offset += csr->response.length;
  2562. return offset;
  2563. }
  2564. #endif
  2565. return 0;
  2566. }
  2567. static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2568. byte isRequest)
  2569. {
  2570. int ret;
  2571. #if !defined(NO_WOLFSSL_SERVER)
  2572. byte status_type;
  2573. word16 size = 0;
  2574. #if defined(WOLFSSL_TLS13)
  2575. DecodedCert* cert;
  2576. #endif
  2577. #endif
  2578. #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) \
  2579. && defined(WOLFSSL_TLS13)
  2580. OcspRequest* request;
  2581. TLSX* extension;
  2582. CertificateStatusRequest* csr;
  2583. #endif
  2584. #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_TLS13) \
  2585. || !defined(NO_WOLFSSL_SERVER)
  2586. word32 offset = 0;
  2587. #endif
  2588. #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_TLS13)
  2589. word32 resp_length = 0;
  2590. #endif
  2591. /* shut up compiler warnings */
  2592. (void) ssl; (void) input;
  2593. if (!isRequest) {
  2594. #ifndef NO_WOLFSSL_CLIENT
  2595. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2596. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2597. if (!csr) {
  2598. /* look at context level */
  2599. extension = TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST);
  2600. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2601. if (!csr) /* unexpected extension */
  2602. return TLSX_HandleUnsupportedExtension(ssl);
  2603. /* enable extension at ssl level */
  2604. ret = TLSX_UseCertificateStatusRequest(&ssl->extensions,
  2605. csr->status_type, csr->options, ssl,
  2606. ssl->heap, ssl->devId);
  2607. if (ret != WOLFSSL_SUCCESS)
  2608. return ret == 0 ? -1 : ret;
  2609. switch (csr->status_type) {
  2610. case WOLFSSL_CSR_OCSP:
  2611. /* propagate nonce */
  2612. if (csr->request.ocsp.nonceSz) {
  2613. request =
  2614. (OcspRequest*)TLSX_CSR_GetRequest(ssl->extensions);
  2615. if (request) {
  2616. XMEMCPY(request->nonce, csr->request.ocsp.nonce,
  2617. csr->request.ocsp.nonceSz);
  2618. request->nonceSz = csr->request.ocsp.nonceSz;
  2619. }
  2620. }
  2621. break;
  2622. }
  2623. }
  2624. ssl->status_request = 1;
  2625. #ifdef WOLFSSL_TLS13
  2626. if (ssl->options.tls1_3) {
  2627. /* Get the new extension potentially created above. */
  2628. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2629. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2630. if (csr == NULL)
  2631. return MEMORY_ERROR;
  2632. ret = 0;
  2633. if (OPAQUE8_LEN + OPAQUE24_LEN > length)
  2634. ret = BUFFER_ERROR;
  2635. if (ret == 0 && input[offset++] != WOLFSSL_CSR_OCSP) {
  2636. ret = BAD_CERTIFICATE_STATUS_ERROR;
  2637. WOLFSSL_ERROR_VERBOSE(ret);
  2638. }
  2639. if (ret == 0) {
  2640. c24to32(input + offset, &resp_length);
  2641. offset += OPAQUE24_LEN;
  2642. if (offset + resp_length != length)
  2643. ret = BUFFER_ERROR;
  2644. }
  2645. if (ret == 0) {
  2646. csr->response.buffer = (byte*)XMALLOC(resp_length, ssl->heap,
  2647. DYNAMIC_TYPE_TMP_BUFFER);
  2648. if (csr->response.buffer == NULL)
  2649. ret = MEMORY_ERROR;
  2650. }
  2651. if (ret == 0) {
  2652. XMEMCPY(csr->response.buffer, input + offset, resp_length);
  2653. csr->response.length = resp_length;
  2654. }
  2655. return ret;
  2656. }
  2657. else
  2658. #endif
  2659. {
  2660. /* extension_data MUST be empty. */
  2661. return length ? BUFFER_ERROR : 0;
  2662. }
  2663. #endif
  2664. }
  2665. else {
  2666. #ifndef NO_WOLFSSL_SERVER
  2667. if (length == 0)
  2668. return 0;
  2669. status_type = input[offset++];
  2670. switch (status_type) {
  2671. case WOLFSSL_CSR_OCSP: {
  2672. /* skip responder_id_list */
  2673. if ((int)(length - offset) < OPAQUE16_LEN)
  2674. return BUFFER_ERROR;
  2675. ato16(input + offset, &size);
  2676. offset += OPAQUE16_LEN + size;
  2677. /* skip request_extensions */
  2678. if ((int)(length - offset) < OPAQUE16_LEN)
  2679. return BUFFER_ERROR;
  2680. ato16(input + offset, &size);
  2681. offset += OPAQUE16_LEN + size;
  2682. if (offset > length)
  2683. return BUFFER_ERROR;
  2684. /* is able to send OCSP response? */
  2685. if (SSL_CM(ssl) == NULL || !SSL_CM(ssl)->ocspStaplingEnabled)
  2686. return 0;
  2687. }
  2688. break;
  2689. /* unknown status type */
  2690. default:
  2691. return 0;
  2692. }
  2693. /* if using status_request and already sending it, skip this one */
  2694. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2695. if (ssl->status_request_v2)
  2696. return 0;
  2697. #endif
  2698. /* accept the first good status_type and return */
  2699. ret = TLSX_UseCertificateStatusRequest(&ssl->extensions, status_type,
  2700. 0, ssl, ssl->heap, ssl->devId);
  2701. if (ret != WOLFSSL_SUCCESS)
  2702. return ret == 0 ? -1 : ret; /* throw error */
  2703. #if defined(WOLFSSL_TLS13)
  2704. if (ssl->options.tls1_3) {
  2705. if (ssl->buffers.certificate == NULL) {
  2706. WOLFSSL_MSG("Certificate buffer not set!");
  2707. return BUFFER_ERROR;
  2708. }
  2709. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
  2710. DYNAMIC_TYPE_DCERT);
  2711. if (cert == NULL) {
  2712. return MEMORY_E;
  2713. }
  2714. InitDecodedCert(cert, ssl->buffers.certificate->buffer,
  2715. ssl->buffers.certificate->length, ssl->heap);
  2716. ret = ParseCert(cert, CERT_TYPE, 1, SSL_CM(ssl));
  2717. if (ret != 0 ) {
  2718. FreeDecodedCert(cert);
  2719. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2720. return ret;
  2721. }
  2722. ret = TLSX_CSR_InitRequest(ssl->extensions, cert, ssl->heap);
  2723. if (ret != 0 ) {
  2724. FreeDecodedCert(cert);
  2725. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2726. return ret;
  2727. }
  2728. FreeDecodedCert(cert);
  2729. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2730. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2731. csr = extension ?
  2732. (CertificateStatusRequest*)extension->data : NULL;
  2733. if (csr == NULL)
  2734. return MEMORY_ERROR;
  2735. request = &csr->request.ocsp;
  2736. ret = CreateOcspResponse(ssl, &request, &csr->response);
  2737. if (ret != 0)
  2738. return ret;
  2739. if (csr->response.buffer)
  2740. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST);
  2741. }
  2742. else
  2743. #endif
  2744. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST);
  2745. ssl->status_request = status_type;
  2746. #endif
  2747. }
  2748. return 0;
  2749. }
  2750. int TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert, void* heap)
  2751. {
  2752. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST);
  2753. CertificateStatusRequest* csr = extension ?
  2754. (CertificateStatusRequest*)extension->data : NULL;
  2755. int ret = 0;
  2756. if (csr) {
  2757. switch (csr->status_type) {
  2758. case WOLFSSL_CSR_OCSP: {
  2759. byte nonce[MAX_OCSP_NONCE_SZ];
  2760. int nonceSz = csr->request.ocsp.nonceSz;
  2761. /* preserve nonce */
  2762. XMEMCPY(nonce, csr->request.ocsp.nonce, nonceSz);
  2763. if ((ret = InitOcspRequest(&csr->request.ocsp, cert, 0, heap))
  2764. != 0)
  2765. return ret;
  2766. /* restore nonce */
  2767. XMEMCPY(csr->request.ocsp.nonce, nonce, nonceSz);
  2768. csr->request.ocsp.nonceSz = nonceSz;
  2769. }
  2770. break;
  2771. }
  2772. }
  2773. return ret;
  2774. }
  2775. void* TLSX_CSR_GetRequest(TLSX* extensions)
  2776. {
  2777. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST);
  2778. CertificateStatusRequest* csr = extension ?
  2779. (CertificateStatusRequest*)extension->data : NULL;
  2780. if (csr) {
  2781. switch (csr->status_type) {
  2782. case WOLFSSL_CSR_OCSP:
  2783. return &csr->request.ocsp;
  2784. }
  2785. }
  2786. return NULL;
  2787. }
  2788. int TLSX_CSR_ForceRequest(WOLFSSL* ssl)
  2789. {
  2790. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2791. CertificateStatusRequest* csr = extension ?
  2792. (CertificateStatusRequest*)extension->data : NULL;
  2793. if (csr) {
  2794. switch (csr->status_type) {
  2795. case WOLFSSL_CSR_OCSP:
  2796. if (SSL_CM(ssl)->ocspEnabled) {
  2797. csr->request.ocsp.ssl = ssl;
  2798. return CheckOcspRequest(SSL_CM(ssl)->ocsp,
  2799. &csr->request.ocsp, NULL, NULL);
  2800. }
  2801. else {
  2802. WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL);
  2803. return OCSP_LOOKUP_FAIL;
  2804. }
  2805. }
  2806. }
  2807. return 0;
  2808. }
  2809. int TLSX_UseCertificateStatusRequest(TLSX** extensions, byte status_type,
  2810. byte options, WOLFSSL* ssl, void* heap,
  2811. int devId)
  2812. {
  2813. CertificateStatusRequest* csr = NULL;
  2814. int ret = 0;
  2815. if (!extensions || status_type != WOLFSSL_CSR_OCSP)
  2816. return BAD_FUNC_ARG;
  2817. csr = (CertificateStatusRequest*)
  2818. XMALLOC(sizeof(CertificateStatusRequest), heap, DYNAMIC_TYPE_TLSX);
  2819. if (!csr)
  2820. return MEMORY_E;
  2821. ForceZero(csr, sizeof(CertificateStatusRequest));
  2822. csr->status_type = status_type;
  2823. csr->options = options;
  2824. csr->ssl = ssl;
  2825. switch (csr->status_type) {
  2826. case WOLFSSL_CSR_OCSP:
  2827. if (options & WOLFSSL_CSR_OCSP_USE_NONCE) {
  2828. WC_RNG rng;
  2829. #ifndef HAVE_FIPS
  2830. ret = wc_InitRng_ex(&rng, heap, devId);
  2831. #else
  2832. ret = wc_InitRng(&rng);
  2833. (void)devId;
  2834. #endif
  2835. if (ret == 0) {
  2836. if (wc_RNG_GenerateBlock(&rng, csr->request.ocsp.nonce,
  2837. MAX_OCSP_NONCE_SZ) == 0)
  2838. csr->request.ocsp.nonceSz = MAX_OCSP_NONCE_SZ;
  2839. wc_FreeRng(&rng);
  2840. }
  2841. }
  2842. break;
  2843. }
  2844. if ((ret = TLSX_Push(extensions, TLSX_STATUS_REQUEST, csr, heap)) != 0) {
  2845. XFREE(csr, heap, DYNAMIC_TYPE_TLSX);
  2846. return ret;
  2847. }
  2848. return WOLFSSL_SUCCESS;
  2849. }
  2850. #define CSR_FREE_ALL TLSX_CSR_Free
  2851. #define CSR_GET_SIZE TLSX_CSR_GetSize
  2852. #define CSR_WRITE TLSX_CSR_Write
  2853. #define CSR_PARSE TLSX_CSR_Parse
  2854. #else
  2855. #define CSR_FREE_ALL(data, heap) WC_DO_NOTHING
  2856. #define CSR_GET_SIZE(a, b) 0
  2857. #define CSR_WRITE(a, b, c) 0
  2858. #define CSR_PARSE(a, b, c, d) 0
  2859. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
  2860. /******************************************************************************/
  2861. /* Certificate Status Request v2 */
  2862. /******************************************************************************/
  2863. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2864. static void TLSX_CSR2_FreeAll(CertificateStatusRequestItemV2* csr2, void* heap)
  2865. {
  2866. CertificateStatusRequestItemV2* next;
  2867. for (; csr2; csr2 = next) {
  2868. next = csr2->next;
  2869. switch (csr2->status_type) {
  2870. case WOLFSSL_CSR2_OCSP:
  2871. case WOLFSSL_CSR2_OCSP_MULTI:
  2872. while(csr2->requests--)
  2873. FreeOcspRequest(&csr2->request.ocsp[csr2->requests]);
  2874. break;
  2875. }
  2876. XFREE(csr2, heap, DYNAMIC_TYPE_TLSX);
  2877. }
  2878. (void)heap;
  2879. }
  2880. static word16 TLSX_CSR2_GetSize(CertificateStatusRequestItemV2* csr2,
  2881. byte isRequest)
  2882. {
  2883. word16 size = 0;
  2884. /* shut up compiler warnings */
  2885. (void) csr2; (void) isRequest;
  2886. #ifndef NO_WOLFSSL_CLIENT
  2887. if (isRequest) {
  2888. CertificateStatusRequestItemV2* next;
  2889. for (size = OPAQUE16_LEN; csr2; csr2 = next) {
  2890. next = csr2->next;
  2891. switch (csr2->status_type) {
  2892. case WOLFSSL_CSR2_OCSP:
  2893. case WOLFSSL_CSR2_OCSP_MULTI:
  2894. size += ENUM_LEN + 3 * OPAQUE16_LEN;
  2895. if (csr2->request.ocsp[0].nonceSz)
  2896. size += OCSP_NONCE_EXT_SZ;
  2897. break;
  2898. }
  2899. }
  2900. }
  2901. #endif
  2902. return size;
  2903. }
  2904. static word16 TLSX_CSR2_Write(CertificateStatusRequestItemV2* csr2,
  2905. byte* output, byte isRequest)
  2906. {
  2907. /* shut up compiler warnings */
  2908. (void) csr2; (void) output; (void) isRequest;
  2909. #ifndef NO_WOLFSSL_CLIENT
  2910. if (isRequest) {
  2911. word16 offset;
  2912. word16 length;
  2913. for (offset = OPAQUE16_LEN; csr2 != NULL; csr2 = csr2->next) {
  2914. /* status_type */
  2915. output[offset++] = csr2->status_type;
  2916. /* request */
  2917. switch (csr2->status_type) {
  2918. case WOLFSSL_CSR2_OCSP:
  2919. case WOLFSSL_CSR2_OCSP_MULTI:
  2920. /* request_length */
  2921. length = 2 * OPAQUE16_LEN;
  2922. if (csr2->request.ocsp[0].nonceSz)
  2923. length += OCSP_NONCE_EXT_SZ;
  2924. c16toa(length, output + offset);
  2925. offset += OPAQUE16_LEN;
  2926. /* responder id list */
  2927. c16toa(0, output + offset);
  2928. offset += OPAQUE16_LEN;
  2929. /* request extensions */
  2930. length = 0;
  2931. if (csr2->request.ocsp[0].nonceSz)
  2932. length = (word16)EncodeOcspRequestExtensions(
  2933. &csr2->request.ocsp[0],
  2934. output + offset + OPAQUE16_LEN,
  2935. OCSP_NONCE_EXT_SZ);
  2936. c16toa(length, output + offset);
  2937. offset += OPAQUE16_LEN + length;
  2938. break;
  2939. }
  2940. }
  2941. /* list size */
  2942. c16toa(offset - OPAQUE16_LEN, output);
  2943. return offset;
  2944. }
  2945. #endif
  2946. return 0;
  2947. }
  2948. static int TLSX_CSR2_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2949. byte isRequest)
  2950. {
  2951. int ret;
  2952. /* shut up compiler warnings */
  2953. (void) ssl; (void) input;
  2954. if (!isRequest) {
  2955. #ifndef NO_WOLFSSL_CLIENT
  2956. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST_V2);
  2957. CertificateStatusRequestItemV2* csr2 = extension ?
  2958. (CertificateStatusRequestItemV2*)extension->data : NULL;
  2959. if (!csr2) {
  2960. /* look at context level */
  2961. extension = TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST_V2);
  2962. csr2 = extension ?
  2963. (CertificateStatusRequestItemV2*)extension->data : NULL;
  2964. if (!csr2) /* unexpected extension */
  2965. return TLSX_HandleUnsupportedExtension(ssl);
  2966. /* enable extension at ssl level */
  2967. for (; csr2; csr2 = csr2->next) {
  2968. ret = TLSX_UseCertificateStatusRequestV2(&ssl->extensions,
  2969. csr2->status_type, csr2->options, ssl->heap,
  2970. ssl->devId);
  2971. if (ret != WOLFSSL_SUCCESS)
  2972. return ret;
  2973. switch (csr2->status_type) {
  2974. case WOLFSSL_CSR2_OCSP:
  2975. /* followed by */
  2976. case WOLFSSL_CSR2_OCSP_MULTI:
  2977. /* propagate nonce */
  2978. if (csr2->request.ocsp[0].nonceSz) {
  2979. OcspRequest* request =
  2980. (OcspRequest*)TLSX_CSR2_GetRequest(ssl->extensions,
  2981. csr2->status_type, 0);
  2982. if (request) {
  2983. XMEMCPY(request->nonce,
  2984. csr2->request.ocsp[0].nonce,
  2985. csr2->request.ocsp[0].nonceSz);
  2986. request->nonceSz =
  2987. csr2->request.ocsp[0].nonceSz;
  2988. }
  2989. }
  2990. break;
  2991. }
  2992. }
  2993. }
  2994. ssl->status_request_v2 = 1;
  2995. return length ? BUFFER_ERROR : 0; /* extension_data MUST be empty. */
  2996. #endif
  2997. }
  2998. else {
  2999. #ifndef NO_WOLFSSL_SERVER
  3000. byte status_type;
  3001. word16 request_length;
  3002. word16 offset = 0;
  3003. word16 size = 0;
  3004. /* list size */
  3005. if (offset + OPAQUE16_LEN >= length) {
  3006. return BUFFER_E;
  3007. }
  3008. ato16(input + offset, &request_length);
  3009. offset += OPAQUE16_LEN;
  3010. if (length - OPAQUE16_LEN != request_length)
  3011. return BUFFER_ERROR;
  3012. while (length > offset) {
  3013. if ((int)(length - offset) < ENUM_LEN + OPAQUE16_LEN)
  3014. return BUFFER_ERROR;
  3015. status_type = input[offset++];
  3016. ato16(input + offset, &request_length);
  3017. offset += OPAQUE16_LEN;
  3018. if (length - offset < request_length)
  3019. return BUFFER_ERROR;
  3020. switch (status_type) {
  3021. case WOLFSSL_CSR2_OCSP:
  3022. case WOLFSSL_CSR2_OCSP_MULTI:
  3023. /* skip responder_id_list */
  3024. if ((int)(length - offset) < OPAQUE16_LEN)
  3025. return BUFFER_ERROR;
  3026. ato16(input + offset, &size);
  3027. if (length - offset < size)
  3028. return BUFFER_ERROR;
  3029. offset += OPAQUE16_LEN + size;
  3030. /* skip request_extensions */
  3031. if ((int)(length - offset) < OPAQUE16_LEN)
  3032. return BUFFER_ERROR;
  3033. ato16(input + offset, &size);
  3034. if (length - offset < size)
  3035. return BUFFER_ERROR;
  3036. offset += OPAQUE16_LEN + size;
  3037. if (offset > length)
  3038. return BUFFER_ERROR;
  3039. /* is able to send OCSP response? */
  3040. if (SSL_CM(ssl) == NULL
  3041. || !SSL_CM(ssl)->ocspStaplingEnabled)
  3042. continue;
  3043. break;
  3044. default:
  3045. /* unknown status type, skipping! */
  3046. offset += request_length;
  3047. continue;
  3048. }
  3049. /* if using status_request and already sending it, remove it
  3050. * and prefer to use the v2 version */
  3051. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  3052. if (ssl->status_request) {
  3053. ssl->status_request = 0;
  3054. TLSX_Remove(&ssl->extensions, TLSX_STATUS_REQUEST, ssl->heap);
  3055. }
  3056. #endif
  3057. /* TLS 1.3 servers MUST NOT act upon presence or information in
  3058. * this extension (RFC 8448 Section 4.4.2.1).
  3059. */
  3060. if (!IsAtLeastTLSv1_3(ssl->version)) {
  3061. /* accept the first good status_type and return */
  3062. ret = TLSX_UseCertificateStatusRequestV2(&ssl->extensions,
  3063. status_type, 0, ssl->heap, ssl->devId);
  3064. if (ret != WOLFSSL_SUCCESS)
  3065. return ret; /* throw error */
  3066. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST_V2);
  3067. ssl->status_request_v2 = status_type;
  3068. }
  3069. return 0;
  3070. }
  3071. #endif
  3072. }
  3073. return 0;
  3074. }
  3075. int TLSX_CSR2_InitRequests(TLSX* extensions, DecodedCert* cert, byte isPeer,
  3076. void* heap)
  3077. {
  3078. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2);
  3079. CertificateStatusRequestItemV2* csr2 = extension ?
  3080. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3081. int ret = 0;
  3082. for (; csr2; csr2 = csr2->next) {
  3083. switch (csr2->status_type) {
  3084. case WOLFSSL_CSR2_OCSP:
  3085. if (!isPeer || csr2->requests != 0)
  3086. break;
  3087. FALL_THROUGH; /* followed by */
  3088. case WOLFSSL_CSR2_OCSP_MULTI: {
  3089. if (csr2->requests < 1 + MAX_CHAIN_DEPTH) {
  3090. byte nonce[MAX_OCSP_NONCE_SZ];
  3091. int nonceSz = csr2->request.ocsp[0].nonceSz;
  3092. /* preserve nonce, replicating nonce of ocsp[0] */
  3093. XMEMCPY(nonce, csr2->request.ocsp[0].nonce, nonceSz);
  3094. if ((ret = InitOcspRequest(
  3095. &csr2->request.ocsp[csr2->requests], cert,
  3096. 0, heap)) != 0)
  3097. return ret;
  3098. /* restore nonce */
  3099. XMEMCPY(csr2->request.ocsp[csr2->requests].nonce,
  3100. nonce, nonceSz);
  3101. csr2->request.ocsp[csr2->requests].nonceSz = nonceSz;
  3102. csr2->requests++;
  3103. }
  3104. }
  3105. break;
  3106. }
  3107. }
  3108. (void)cert;
  3109. return ret;
  3110. }
  3111. void* TLSX_CSR2_GetRequest(TLSX* extensions, byte status_type, byte idx)
  3112. {
  3113. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2);
  3114. CertificateStatusRequestItemV2* csr2 = extension ?
  3115. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3116. for (; csr2; csr2 = csr2->next) {
  3117. if (csr2->status_type == status_type) {
  3118. switch (csr2->status_type) {
  3119. case WOLFSSL_CSR2_OCSP:
  3120. /* followed by */
  3121. case WOLFSSL_CSR2_OCSP_MULTI:
  3122. /* requests are initialized in the reverse order */
  3123. return idx < csr2->requests
  3124. ? &csr2->request.ocsp[csr2->requests - idx - 1]
  3125. : NULL;
  3126. }
  3127. }
  3128. }
  3129. return NULL;
  3130. }
  3131. int TLSX_CSR2_ForceRequest(WOLFSSL* ssl)
  3132. {
  3133. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST_V2);
  3134. CertificateStatusRequestItemV2* csr2 = extension ?
  3135. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3136. /* forces only the first one */
  3137. if (csr2) {
  3138. switch (csr2->status_type) {
  3139. case WOLFSSL_CSR2_OCSP:
  3140. /* followed by */
  3141. case WOLFSSL_CSR2_OCSP_MULTI:
  3142. if (SSL_CM(ssl)->ocspEnabled) {
  3143. csr2->request.ocsp[0].ssl = ssl;
  3144. return CheckOcspRequest(SSL_CM(ssl)->ocsp,
  3145. &csr2->request.ocsp[0], NULL, NULL);
  3146. }
  3147. else {
  3148. WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL);
  3149. return OCSP_LOOKUP_FAIL;
  3150. }
  3151. }
  3152. }
  3153. return 0;
  3154. }
  3155. int TLSX_UseCertificateStatusRequestV2(TLSX** extensions, byte status_type,
  3156. byte options, void* heap, int devId)
  3157. {
  3158. TLSX* extension = NULL;
  3159. CertificateStatusRequestItemV2* csr2 = NULL;
  3160. int ret = 0;
  3161. if (!extensions)
  3162. return BAD_FUNC_ARG;
  3163. if (status_type != WOLFSSL_CSR2_OCSP
  3164. && status_type != WOLFSSL_CSR2_OCSP_MULTI)
  3165. return BAD_FUNC_ARG;
  3166. csr2 = (CertificateStatusRequestItemV2*)
  3167. XMALLOC(sizeof(CertificateStatusRequestItemV2), heap, DYNAMIC_TYPE_TLSX);
  3168. if (!csr2)
  3169. return MEMORY_E;
  3170. ForceZero(csr2, sizeof(CertificateStatusRequestItemV2));
  3171. csr2->status_type = status_type;
  3172. csr2->options = options;
  3173. csr2->next = NULL;
  3174. switch (csr2->status_type) {
  3175. case WOLFSSL_CSR2_OCSP:
  3176. case WOLFSSL_CSR2_OCSP_MULTI:
  3177. if (options & WOLFSSL_CSR2_OCSP_USE_NONCE) {
  3178. WC_RNG rng;
  3179. #ifndef HAVE_FIPS
  3180. ret = wc_InitRng_ex(&rng, heap, devId);
  3181. #else
  3182. ret = wc_InitRng(&rng);
  3183. (void)devId;
  3184. #endif
  3185. if (ret == 0) {
  3186. if (wc_RNG_GenerateBlock(&rng, csr2->request.ocsp[0].nonce,
  3187. MAX_OCSP_NONCE_SZ) == 0)
  3188. csr2->request.ocsp[0].nonceSz = MAX_OCSP_NONCE_SZ;
  3189. wc_FreeRng(&rng);
  3190. }
  3191. }
  3192. break;
  3193. }
  3194. /* append new item */
  3195. if ((extension = TLSX_Find(*extensions, TLSX_STATUS_REQUEST_V2))) {
  3196. CertificateStatusRequestItemV2* last =
  3197. (CertificateStatusRequestItemV2*)extension->data;
  3198. for (; last->next; last = last->next);
  3199. last->next = csr2;
  3200. }
  3201. else if ((ret = TLSX_Push(extensions, TLSX_STATUS_REQUEST_V2, csr2,heap))) {
  3202. XFREE(csr2, heap, DYNAMIC_TYPE_TLSX);
  3203. return ret;
  3204. }
  3205. return WOLFSSL_SUCCESS;
  3206. }
  3207. #define CSR2_FREE_ALL TLSX_CSR2_FreeAll
  3208. #define CSR2_GET_SIZE TLSX_CSR2_GetSize
  3209. #define CSR2_WRITE TLSX_CSR2_Write
  3210. #define CSR2_PARSE TLSX_CSR2_Parse
  3211. #else
  3212. #define CSR2_FREE_ALL(data, heap) WC_DO_NOTHING
  3213. #define CSR2_GET_SIZE(a, b) 0
  3214. #define CSR2_WRITE(a, b, c) 0
  3215. #define CSR2_PARSE(a, b, c, d) 0
  3216. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  3217. /******************************************************************************/
  3218. /* Supported Elliptic Curves */
  3219. /******************************************************************************/
  3220. #ifdef HAVE_SUPPORTED_CURVES
  3221. #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) \
  3222. && !defined(HAVE_FFDHE) && !defined(HAVE_PQC)
  3223. #error Elliptic Curves Extension requires Elliptic Curve Cryptography or liboqs groups. \
  3224. Use --enable-ecc and/or --enable-liboqs in the configure script or \
  3225. define HAVE_ECC. Alternatively use FFDHE for DH cipher suites.
  3226. #endif
  3227. static int TLSX_SupportedCurve_New(SupportedCurve** curve, word16 name,
  3228. void* heap)
  3229. {
  3230. if (curve == NULL)
  3231. return BAD_FUNC_ARG;
  3232. (void)heap;
  3233. *curve = (SupportedCurve*)XMALLOC(sizeof(SupportedCurve), heap,
  3234. DYNAMIC_TYPE_TLSX);
  3235. if (*curve == NULL)
  3236. return MEMORY_E;
  3237. (*curve)->name = name;
  3238. (*curve)->next = NULL;
  3239. return 0;
  3240. }
  3241. static int TLSX_PointFormat_New(PointFormat** point, byte format, void* heap)
  3242. {
  3243. if (point == NULL)
  3244. return BAD_FUNC_ARG;
  3245. (void)heap;
  3246. *point = (PointFormat*)XMALLOC(sizeof(PointFormat), heap,
  3247. DYNAMIC_TYPE_TLSX);
  3248. if (*point == NULL)
  3249. return MEMORY_E;
  3250. (*point)->format = format;
  3251. (*point)->next = NULL;
  3252. return 0;
  3253. }
  3254. static void TLSX_SupportedCurve_FreeAll(SupportedCurve* list, void* heap)
  3255. {
  3256. SupportedCurve* curve;
  3257. while ((curve = list)) {
  3258. list = curve->next;
  3259. XFREE(curve, heap, DYNAMIC_TYPE_TLSX);
  3260. }
  3261. (void)heap;
  3262. }
  3263. static void TLSX_PointFormat_FreeAll(PointFormat* list, void* heap)
  3264. {
  3265. PointFormat* point;
  3266. while ((point = list)) {
  3267. list = point->next;
  3268. XFREE(point, heap, DYNAMIC_TYPE_TLSX);
  3269. }
  3270. (void)heap;
  3271. }
  3272. static int TLSX_SupportedCurve_Append(SupportedCurve* list, word16 name,
  3273. void* heap)
  3274. {
  3275. int ret = BAD_FUNC_ARG;
  3276. while (list) {
  3277. if (list->name == name) {
  3278. ret = 0; /* curve already in use */
  3279. break;
  3280. }
  3281. if (list->next == NULL) {
  3282. ret = TLSX_SupportedCurve_New(&list->next, name, heap);
  3283. break;
  3284. }
  3285. list = list->next;
  3286. }
  3287. return ret;
  3288. }
  3289. static int TLSX_PointFormat_Append(PointFormat* list, byte format, void* heap)
  3290. {
  3291. int ret = BAD_FUNC_ARG;
  3292. while (list) {
  3293. if (list->format == format) {
  3294. ret = 0; /* format already in use */
  3295. break;
  3296. }
  3297. if (list->next == NULL) {
  3298. ret = TLSX_PointFormat_New(&list->next, format, heap);
  3299. break;
  3300. }
  3301. list = list->next;
  3302. }
  3303. return ret;
  3304. }
  3305. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  3306. #if defined(HAVE_FFDHE) && (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3307. defined(HAVE_CURVE448))
  3308. static void TLSX_SupportedCurve_ValidateRequest(const WOLFSSL* ssl,
  3309. const byte* semaphore)
  3310. {
  3311. /* If all pre-defined parameter types for key exchange are supported then
  3312. * always send SupportedGroups extension.
  3313. */
  3314. (void)ssl;
  3315. (void)semaphore;
  3316. }
  3317. #else
  3318. static void TLSX_SupportedCurve_ValidateRequest(WOLFSSL* ssl, byte* semaphore)
  3319. {
  3320. word16 i;
  3321. const Suites* suites = WOLFSSL_SUITES(ssl);
  3322. for (i = 0; i < suites->suiteSz; i += 2) {
  3323. if (suites->suites[i] == TLS13_BYTE)
  3324. return;
  3325. #ifdef BUILD_TLS_SM4_GCM_SM3
  3326. if ((suites->suites[i] == CIPHER_BYTE) &&
  3327. (suites->suites[i+1] == TLS_SM4_GCM_SM3))
  3328. return;
  3329. #endif
  3330. #ifdef BUILD_TLS_SM4_CCM_SM3
  3331. if ((suites->suites[i] == CIPHER_BYTE) &&
  3332. (suites->suites[i+1] == TLS_SM4_CCM_SM3))
  3333. return;
  3334. #endif
  3335. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3336. if ((suites->suites[i] == SM_BYTE) &&
  3337. (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3338. return;
  3339. #endif
  3340. if ((suites->suites[i] == ECC_BYTE) ||
  3341. (suites->suites[i] == ECDHE_PSK_BYTE) ||
  3342. (suites->suites[i] == CHACHA_BYTE)) {
  3343. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3344. defined(HAVE_CURVE448)
  3345. return;
  3346. #endif
  3347. }
  3348. #ifdef HAVE_FFDHE
  3349. else {
  3350. return;
  3351. }
  3352. #endif
  3353. }
  3354. /* turns semaphore on to avoid sending this extension. */
  3355. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_GROUPS));
  3356. }
  3357. #endif
  3358. /* Only send PointFormats if TLSv13, ECC or CHACHA cipher suite present.
  3359. */
  3360. static void TLSX_PointFormat_ValidateRequest(WOLFSSL* ssl, byte* semaphore)
  3361. {
  3362. #ifdef HAVE_FFDHE
  3363. (void)ssl;
  3364. (void)semaphore;
  3365. #else
  3366. word16 i;
  3367. const Suites* suites = WOLFSSL_SUITES(ssl);
  3368. if (suites == NULL)
  3369. return;
  3370. for (i = 0; i < suites->suiteSz; i += 2) {
  3371. if (suites->suites[i] == TLS13_BYTE)
  3372. return;
  3373. #ifdef BUILD_TLS_SM4_GCM_SM3
  3374. if ((suites->suites[i] == CIPHER_BYTE) &&
  3375. (suites->suites[i+1] == TLS_SM4_GCM_SM3))
  3376. return;
  3377. #endif
  3378. #ifdef BUILD_TLS_SM4_CCM_SM3
  3379. if ((suites->suites[i] == CIPHER_BYTE) &&
  3380. (suites->suites[i+1] == TLS_SM4_CCM_SM3))
  3381. return;
  3382. #endif
  3383. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3384. if ((suites->suites[i] == SM_BYTE) &&
  3385. (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3386. return;
  3387. #endif
  3388. if ((suites->suites[i] == ECC_BYTE) ||
  3389. (suites->suites[i] == ECDHE_PSK_BYTE) ||
  3390. (suites->suites[i] == CHACHA_BYTE)) {
  3391. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3392. defined(HAVE_CURVE448)
  3393. return;
  3394. #endif
  3395. }
  3396. }
  3397. /* turns semaphore on to avoid sending this extension. */
  3398. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  3399. #endif
  3400. }
  3401. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  3402. #ifndef NO_WOLFSSL_SERVER
  3403. static void TLSX_PointFormat_ValidateResponse(WOLFSSL* ssl, byte* semaphore)
  3404. {
  3405. #if defined(HAVE_FFDHE) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3406. defined(HAVE_CURVE448)
  3407. (void)semaphore;
  3408. #endif
  3409. if (ssl->options.cipherSuite0 == TLS13_BYTE)
  3410. return;
  3411. #ifdef BUILD_TLS_SM4_GCM_SM3
  3412. if ((ssl->options.cipherSuite0 == CIPHER_BYTE) &&
  3413. (ssl->options.cipherSuite == TLS_SM4_GCM_SM3))
  3414. return;
  3415. #endif
  3416. #ifdef BUILD_TLS_SM4_CCM_SM3
  3417. if ((ssl->options.cipherSuite0 == CIPHER_BYTE) &&
  3418. (ssl->options.cipherSuite == TLS_SM4_CCM_SM3))
  3419. return;
  3420. #endif
  3421. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3422. if ((ssl->options.cipherSuite0 == SM_BYTE) &&
  3423. (ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3424. return;
  3425. #endif
  3426. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  3427. if (ssl->options.cipherSuite0 == ECC_BYTE ||
  3428. ssl->options.cipherSuite0 == ECDHE_PSK_BYTE ||
  3429. ssl->options.cipherSuite0 == CHACHA_BYTE) {
  3430. return;
  3431. }
  3432. #endif
  3433. /* turns semaphore on to avoid sending this extension. */
  3434. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  3435. }
  3436. #endif /* !NO_WOLFSSL_SERVER */
  3437. #ifndef NO_WOLFSSL_CLIENT
  3438. static word16 TLSX_SupportedCurve_GetSize(SupportedCurve* list)
  3439. {
  3440. SupportedCurve* curve;
  3441. word16 length = OPAQUE16_LEN; /* list length */
  3442. while ((curve = list)) {
  3443. list = curve->next;
  3444. length += OPAQUE16_LEN; /* curve length */
  3445. }
  3446. return length;
  3447. }
  3448. #endif
  3449. static word16 TLSX_PointFormat_GetSize(PointFormat* list)
  3450. {
  3451. PointFormat* point;
  3452. word16 length = ENUM_LEN; /* list length */
  3453. while ((point = list)) {
  3454. list = point->next;
  3455. length += ENUM_LEN; /* format length */
  3456. }
  3457. return length;
  3458. }
  3459. #ifndef NO_WOLFSSL_CLIENT
  3460. static word16 TLSX_SupportedCurve_Write(SupportedCurve* list, byte* output)
  3461. {
  3462. word16 offset = OPAQUE16_LEN;
  3463. while (list) {
  3464. c16toa(list->name, output + offset);
  3465. offset += OPAQUE16_LEN;
  3466. list = list->next;
  3467. }
  3468. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  3469. return offset;
  3470. }
  3471. #endif
  3472. static word16 TLSX_PointFormat_Write(PointFormat* list, byte* output)
  3473. {
  3474. word16 offset = ENUM_LEN;
  3475. while (list) {
  3476. output[offset++] = list->format;
  3477. list = list->next;
  3478. }
  3479. output[0] = (byte)(offset - ENUM_LEN);
  3480. return offset;
  3481. }
  3482. #if !defined(NO_WOLFSSL_SERVER) || (defined(WOLFSSL_TLS13) && \
  3483. !defined(WOLFSSL_NO_SERVER_GROUPS_EXT))
  3484. int TLSX_SupportedCurve_Parse(const WOLFSSL* ssl, const byte* input,
  3485. word16 length, byte isRequest, TLSX** extensions)
  3486. {
  3487. word16 offset;
  3488. word16 name;
  3489. int ret;
  3490. if(!isRequest && !IsAtLeastTLSv1_3(ssl->version)) {
  3491. #ifdef WOLFSSL_ALLOW_SERVER_SC_EXT
  3492. return 0;
  3493. #else
  3494. return BUFFER_ERROR; /* servers doesn't send this extension. */
  3495. #endif
  3496. }
  3497. if (OPAQUE16_LEN > length || length % OPAQUE16_LEN)
  3498. return BUFFER_ERROR;
  3499. ato16(input, &offset);
  3500. /* validating curve list length */
  3501. if (length != OPAQUE16_LEN + offset)
  3502. return BUFFER_ERROR;
  3503. offset = OPAQUE16_LEN;
  3504. if (offset == length)
  3505. return 0;
  3506. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3507. if (!isRequest) {
  3508. TLSX* extension;
  3509. SupportedCurve* curve;
  3510. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  3511. if (extension != NULL) {
  3512. /* Replace client list with server list of supported groups. */
  3513. curve = (SupportedCurve*)extension->data;
  3514. extension->data = NULL;
  3515. TLSX_SupportedCurve_FreeAll(curve, ssl->heap);
  3516. ato16(input + offset, &name);
  3517. offset += OPAQUE16_LEN;
  3518. ret = TLSX_SupportedCurve_New(&curve, name, ssl->heap);
  3519. if (ret != 0)
  3520. return ret; /* throw error */
  3521. extension->data = (void*)curve;
  3522. }
  3523. }
  3524. #endif
  3525. for (; offset < length; offset += OPAQUE16_LEN) {
  3526. ato16(input + offset, &name);
  3527. ret = TLSX_UseSupportedCurve(extensions, name, ssl->heap);
  3528. /* If it is BAD_FUNC_ARG then it is a group we do not support, but
  3529. * that is fine. */
  3530. if (ret != WOLFSSL_SUCCESS && ret != BAD_FUNC_ARG) {
  3531. return ret;
  3532. }
  3533. }
  3534. return 0;
  3535. }
  3536. #endif
  3537. #if !defined(NO_WOLFSSL_SERVER)
  3538. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3539. /* Checks the priority of the groups on the server and set the supported groups
  3540. * response if there is a group not advertised by the client that is preferred.
  3541. *
  3542. * ssl SSL/TLS object.
  3543. * returns 0 on success, otherwise an error.
  3544. */
  3545. int TLSX_SupportedCurve_CheckPriority(WOLFSSL* ssl)
  3546. {
  3547. int ret;
  3548. TLSX* extension;
  3549. TLSX* priority = NULL;
  3550. TLSX* ext = NULL;
  3551. word16 name;
  3552. SupportedCurve* curve;
  3553. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3554. /* May be doing PSK with no key exchange. */
  3555. if (extension == NULL)
  3556. return 0;
  3557. ret = TLSX_PopulateSupportedGroups(ssl, &priority);
  3558. if (ret != WOLFSSL_SUCCESS) {
  3559. TLSX_FreeAll(priority, ssl->heap);
  3560. return ret;
  3561. }
  3562. ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS);
  3563. if (ext == NULL) {
  3564. WOLFSSL_MSG("Could not find supported groups extension");
  3565. TLSX_FreeAll(priority, ssl->heap);
  3566. return 0;
  3567. }
  3568. curve = (SupportedCurve*)ext->data;
  3569. name = curve->name;
  3570. curve = (SupportedCurve*)extension->data;
  3571. while (curve != NULL) {
  3572. if (curve->name == name)
  3573. break;
  3574. curve = curve->next;
  3575. }
  3576. if (curve == NULL) {
  3577. /* Couldn't find the preferred group in client list. */
  3578. extension->resp = 1;
  3579. /* Send server list back and free client list. */
  3580. curve = (SupportedCurve*)extension->data;
  3581. extension->data = ext->data;
  3582. ext->data = curve;
  3583. }
  3584. TLSX_FreeAll(priority, ssl->heap);
  3585. return 0;
  3586. }
  3587. #endif /* WOLFSSL_TLS13 && !WOLFSSL_NO_SERVER_GROUPS_EXT */
  3588. #if defined(HAVE_FFDHE) && !defined(WOLFSSL_NO_TLS12)
  3589. #ifdef HAVE_PUBLIC_FFDHE
  3590. static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup,
  3591. SupportedCurve* serverGroup)
  3592. {
  3593. int ret = 0;
  3594. SupportedCurve* group;
  3595. const DhParams* params = NULL;
  3596. for (; serverGroup != NULL; serverGroup = serverGroup->next) {
  3597. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name))
  3598. continue;
  3599. for (group = clientGroup; group != NULL; group = group->next) {
  3600. if (serverGroup->name != group->name)
  3601. continue;
  3602. switch (serverGroup->name) {
  3603. #ifdef HAVE_FFDHE_2048
  3604. case WOLFSSL_FFDHE_2048:
  3605. params = wc_Dh_ffdhe2048_Get();
  3606. break;
  3607. #endif
  3608. #ifdef HAVE_FFDHE_3072
  3609. case WOLFSSL_FFDHE_3072:
  3610. params = wc_Dh_ffdhe3072_Get();
  3611. break;
  3612. #endif
  3613. #ifdef HAVE_FFDHE_4096
  3614. case WOLFSSL_FFDHE_4096:
  3615. params = wc_Dh_ffdhe4096_Get();
  3616. break;
  3617. #endif
  3618. #ifdef HAVE_FFDHE_6144
  3619. case WOLFSSL_FFDHE_6144:
  3620. params = wc_Dh_ffdhe6144_Get();
  3621. break;
  3622. #endif
  3623. #ifdef HAVE_FFDHE_8192
  3624. case WOLFSSL_FFDHE_8192:
  3625. params = wc_Dh_ffdhe8192_Get();
  3626. break;
  3627. #endif
  3628. default:
  3629. break;
  3630. }
  3631. if (params == NULL) {
  3632. ret = BAD_FUNC_ARG;
  3633. break;
  3634. }
  3635. if (params->p_len >= ssl->options.minDhKeySz &&
  3636. params->p_len <= ssl->options.maxDhKeySz) {
  3637. break;
  3638. }
  3639. }
  3640. if (ret != 0)
  3641. break;
  3642. if ((group != NULL) && (serverGroup->name == group->name))
  3643. break;
  3644. }
  3645. if ((ret == 0) && (serverGroup != NULL) && (params != NULL)) {
  3646. ssl->buffers.serverDH_P.buffer = (unsigned char *)params->p;
  3647. ssl->buffers.serverDH_P.length = params->p_len;
  3648. ssl->buffers.serverDH_G.buffer = (unsigned char *)params->g;
  3649. ssl->buffers.serverDH_G.length = params->g_len;
  3650. ssl->namedGroup = serverGroup->name;
  3651. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  3652. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  3653. ssl->options.dhDoKeyTest = 0;
  3654. #endif
  3655. ssl->options.haveDH = 1;
  3656. }
  3657. return ret;
  3658. }
  3659. #else
  3660. static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup,
  3661. SupportedCurve* serverGroup)
  3662. {
  3663. int ret = 0;
  3664. SupportedCurve* group;
  3665. word32 p_len;
  3666. for (; serverGroup != NULL; serverGroup = serverGroup->next) {
  3667. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name))
  3668. continue;
  3669. for (group = clientGroup; group != NULL; group = group->next) {
  3670. if (serverGroup->name != group->name)
  3671. continue;
  3672. wc_DhGetNamedKeyParamSize(serverGroup->name, &p_len, NULL, NULL);
  3673. if (p_len == 0) {
  3674. ret = BAD_FUNC_ARG;
  3675. break;
  3676. }
  3677. if (p_len >= ssl->options.minDhKeySz &&
  3678. p_len <= ssl->options.maxDhKeySz) {
  3679. break;
  3680. }
  3681. }
  3682. if (ret != 0)
  3683. break;
  3684. if ((group != NULL) && (serverGroup->name == group->name))
  3685. break;
  3686. }
  3687. if ((ret == 0) && (serverGroup != NULL)) {
  3688. word32 pSz, gSz;
  3689. ssl->buffers.serverDH_P.buffer = NULL;
  3690. ssl->buffers.serverDH_G.buffer = NULL;
  3691. ret = wc_DhGetNamedKeyParamSize(serverGroup->name, &pSz, &gSz, NULL);
  3692. if (ret == 0) {
  3693. ssl->buffers.serverDH_P.buffer =
  3694. (byte*)XMALLOC(pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  3695. if (ssl->buffers.serverDH_P.buffer == NULL)
  3696. ret = MEMORY_E;
  3697. else
  3698. ssl->buffers.serverDH_P.length = pSz;
  3699. }
  3700. if (ret == 0) {
  3701. ssl->buffers.serverDH_G.buffer =
  3702. (byte*)XMALLOC(gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  3703. if (ssl->buffers.serverDH_G.buffer == NULL) {
  3704. ret = MEMORY_E;
  3705. } else
  3706. ssl->buffers.serverDH_G.length = gSz;
  3707. }
  3708. if (ret == 0) {
  3709. ret = wc_DhCopyNamedKey(serverGroup->name,
  3710. ssl->buffers.serverDH_P.buffer, &pSz,
  3711. ssl->buffers.serverDH_G.buffer, &gSz,
  3712. NULL, NULL);
  3713. }
  3714. if (ret == 0) {
  3715. ssl->buffers.weOwnDH = 1;
  3716. ssl->namedGroup = serverGroup->name;
  3717. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  3718. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  3719. ssl->options.dhDoKeyTest = 0;
  3720. #endif
  3721. ssl->options.haveDH = 1;
  3722. }
  3723. else {
  3724. if (ssl->buffers.serverDH_P.buffer != NULL) {
  3725. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  3726. DYNAMIC_TYPE_PUBLIC_KEY);
  3727. ssl->buffers.serverDH_P.length = 0;
  3728. ssl->buffers.serverDH_P.buffer = NULL;
  3729. }
  3730. if (ssl->buffers.serverDH_G.buffer != NULL) {
  3731. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  3732. DYNAMIC_TYPE_PUBLIC_KEY);
  3733. ssl->buffers.serverDH_G.length = 0;
  3734. ssl->buffers.serverDH_G.buffer = NULL;
  3735. }
  3736. }
  3737. }
  3738. return ret;
  3739. }
  3740. #endif
  3741. /* Set the highest priority common FFDHE group on the server as compared to
  3742. * client extensions.
  3743. *
  3744. * ssl SSL/TLS object.
  3745. * returns 0 on success, otherwise an error.
  3746. */
  3747. int TLSX_SupportedFFDHE_Set(WOLFSSL* ssl)
  3748. {
  3749. int ret;
  3750. TLSX* priority = NULL;
  3751. TLSX* ext = NULL;
  3752. TLSX* extension;
  3753. SupportedCurve* clientGroup;
  3754. SupportedCurve* group;
  3755. int found = 0;
  3756. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3757. /* May be doing PSK with no key exchange. */
  3758. if (extension == NULL)
  3759. return 0;
  3760. clientGroup = (SupportedCurve*)extension->data;
  3761. for (group = clientGroup; group != NULL; group = group->next) {
  3762. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(group->name)) {
  3763. found = 1;
  3764. break;
  3765. }
  3766. }
  3767. if (!found)
  3768. return 0;
  3769. if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
  3770. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  3771. DYNAMIC_TYPE_PUBLIC_KEY);
  3772. }
  3773. if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
  3774. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  3775. DYNAMIC_TYPE_PUBLIC_KEY);
  3776. }
  3777. ssl->buffers.serverDH_P.buffer = NULL;
  3778. ssl->buffers.serverDH_G.buffer = NULL;
  3779. ssl->buffers.weOwnDH = 0;
  3780. ssl->options.haveDH = 0;
  3781. ret = TLSX_PopulateSupportedGroups(ssl, &priority);
  3782. if (ret == WOLFSSL_SUCCESS) {
  3783. SupportedCurve* serverGroup;
  3784. ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS);
  3785. serverGroup = (SupportedCurve*)ext->data;
  3786. ret = tlsx_ffdhe_find_group(ssl, clientGroup, serverGroup);
  3787. }
  3788. TLSX_FreeAll(priority, ssl->heap);
  3789. return ret;
  3790. }
  3791. #endif /* HAVE_FFDHE && !WOLFSSL_NO_TLS12 */
  3792. #endif /* !NO_WOLFSSL_SERVER */
  3793. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3794. /* Return the preferred group.
  3795. *
  3796. * ssl SSL/TLS object.
  3797. * checkSupported Whether to check for the first supported group.
  3798. * returns BAD_FUNC_ARG if no group found, otherwise the group.
  3799. */
  3800. int TLSX_SupportedCurve_Preferred(WOLFSSL* ssl, int checkSupported)
  3801. {
  3802. TLSX* extension;
  3803. SupportedCurve* curve;
  3804. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3805. if (extension == NULL)
  3806. return BAD_FUNC_ARG;
  3807. curve = (SupportedCurve*)extension->data;
  3808. while (curve != NULL) {
  3809. if (!checkSupported || TLSX_KeyShare_IsSupported(curve->name))
  3810. return curve->name;
  3811. curve = curve->next;
  3812. }
  3813. return BAD_FUNC_ARG;
  3814. }
  3815. #endif /* HAVE_SUPPORTED_CURVES */
  3816. #ifndef NO_WOLFSSL_SERVER
  3817. static int TLSX_PointFormat_Parse(WOLFSSL* ssl, const byte* input,
  3818. word16 length, byte isRequest)
  3819. {
  3820. int ret;
  3821. /* validating formats list length */
  3822. if (ENUM_LEN > length || length != (word16)ENUM_LEN + input[0])
  3823. return BUFFER_ERROR;
  3824. if (isRequest) {
  3825. /* adding uncompressed point format to response */
  3826. ret = TLSX_UsePointFormat(&ssl->extensions, WOLFSSL_EC_PF_UNCOMPRESSED,
  3827. ssl->heap);
  3828. if (ret != WOLFSSL_SUCCESS)
  3829. return ret; /* throw error */
  3830. TLSX_SetResponse(ssl, TLSX_EC_POINT_FORMATS);
  3831. }
  3832. return 0;
  3833. }
  3834. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  3835. int TLSX_ValidateSupportedCurves(const WOLFSSL* ssl, byte first, byte second,
  3836. word32* ecdhCurveOID) {
  3837. TLSX* extension = NULL;
  3838. SupportedCurve* curve = NULL;
  3839. word32 oid = 0;
  3840. word32 defOid = 0;
  3841. word32 defSz = 80; /* Maximum known curve size is 66. */
  3842. word32 nextOid = 0;
  3843. word32 nextSz = 80; /* Maximum known curve size is 66. */
  3844. word32 currOid = ssl->ecdhCurveOID;
  3845. int ephmSuite = 0;
  3846. word16 octets = 0; /* according to 'ecc_set_type ecc_sets[];' */
  3847. int key = 0; /* validate key */
  3848. (void)oid;
  3849. if (first == CHACHA_BYTE) {
  3850. switch (second) {
  3851. case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
  3852. case TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3853. case TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3854. case TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256:
  3855. return 1; /* no suite restriction */
  3856. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
  3857. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256:
  3858. case TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3859. break;
  3860. }
  3861. }
  3862. if (first == ECC_BYTE || first == ECDHE_PSK_BYTE || first == CHACHA_BYTE)
  3863. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3864. if (!extension)
  3865. return 1; /* no suite restriction */
  3866. for (curve = (SupportedCurve*)extension->data;
  3867. curve && !key;
  3868. curve = curve->next) {
  3869. #ifdef OPENSSL_EXTRA
  3870. /* skip if name is not in supported ECC range
  3871. * or disabled by user */
  3872. if (curve->name > WOLFSSL_ECC_MAX ||
  3873. wolfSSL_curve_is_disabled(ssl, curve->name))
  3874. continue;
  3875. #endif
  3876. /* find supported curve */
  3877. switch (curve->name) {
  3878. #ifdef HAVE_ECC
  3879. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  3880. #ifndef NO_ECC_SECP
  3881. case WOLFSSL_ECC_SECP160R1:
  3882. oid = ECC_SECP160R1_OID;
  3883. octets = 20;
  3884. break;
  3885. #endif /* !NO_ECC_SECP */
  3886. #ifdef HAVE_ECC_SECPR2
  3887. case WOLFSSL_ECC_SECP160R2:
  3888. oid = ECC_SECP160R2_OID;
  3889. octets = 20;
  3890. break;
  3891. #endif /* HAVE_ECC_SECPR2 */
  3892. #ifdef HAVE_ECC_KOBLITZ
  3893. case WOLFSSL_ECC_SECP160K1:
  3894. oid = ECC_SECP160K1_OID;
  3895. octets = 20;
  3896. break;
  3897. #endif /* HAVE_ECC_KOBLITZ */
  3898. #endif
  3899. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  3900. #ifndef NO_ECC_SECP
  3901. case WOLFSSL_ECC_SECP192R1:
  3902. oid = ECC_SECP192R1_OID;
  3903. octets = 24;
  3904. break;
  3905. #endif /* !NO_ECC_SECP */
  3906. #ifdef HAVE_ECC_KOBLITZ
  3907. case WOLFSSL_ECC_SECP192K1:
  3908. oid = ECC_SECP192K1_OID;
  3909. octets = 24;
  3910. break;
  3911. #endif /* HAVE_ECC_KOBLITZ */
  3912. #endif
  3913. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  3914. #ifndef NO_ECC_SECP
  3915. case WOLFSSL_ECC_SECP224R1:
  3916. oid = ECC_SECP224R1_OID;
  3917. octets = 28;
  3918. break;
  3919. #endif /* !NO_ECC_SECP */
  3920. #ifdef HAVE_ECC_KOBLITZ
  3921. case WOLFSSL_ECC_SECP224K1:
  3922. oid = ECC_SECP224K1_OID;
  3923. octets = 28;
  3924. break;
  3925. #endif /* HAVE_ECC_KOBLITZ */
  3926. #endif
  3927. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  3928. #ifndef NO_ECC_SECP
  3929. case WOLFSSL_ECC_SECP256R1:
  3930. oid = ECC_SECP256R1_OID;
  3931. octets = 32;
  3932. break;
  3933. #endif /* !NO_ECC_SECP */
  3934. #endif /* !NO_ECC256 || HAVE_ALL_CURVES */
  3935. #endif
  3936. #if (defined(HAVE_CURVE25519) || defined(HAVE_ED25519)) && ECC_MIN_KEY_SZ <= 256
  3937. case WOLFSSL_ECC_X25519:
  3938. oid = ECC_X25519_OID;
  3939. octets = 32;
  3940. break;
  3941. #endif /* HAVE_CURVE25519 */
  3942. #ifdef HAVE_ECC
  3943. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  3944. #ifdef HAVE_ECC_KOBLITZ
  3945. case WOLFSSL_ECC_SECP256K1:
  3946. oid = ECC_SECP256K1_OID;
  3947. octets = 32;
  3948. break;
  3949. #endif /* HAVE_ECC_KOBLITZ */
  3950. #ifdef HAVE_ECC_BRAINPOOL
  3951. case WOLFSSL_ECC_BRAINPOOLP256R1:
  3952. oid = ECC_BRAINPOOLP256R1_OID;
  3953. octets = 32;
  3954. break;
  3955. #endif /* HAVE_ECC_BRAINPOOL */
  3956. #ifdef WOLFSSL_SM2
  3957. case WOLFSSL_ECC_SM2P256V1:
  3958. oid = ECC_SM2P256V1_OID;
  3959. octets = 32;
  3960. break;
  3961. #endif /* WOLFSSL_SM2 */
  3962. #endif
  3963. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  3964. #ifndef NO_ECC_SECP
  3965. case WOLFSSL_ECC_SECP384R1:
  3966. oid = ECC_SECP384R1_OID;
  3967. octets = 48;
  3968. break;
  3969. #endif /* !NO_ECC_SECP */
  3970. #ifdef HAVE_ECC_BRAINPOOL
  3971. case WOLFSSL_ECC_BRAINPOOLP384R1:
  3972. oid = ECC_BRAINPOOLP384R1_OID;
  3973. octets = 48;
  3974. break;
  3975. #endif /* HAVE_ECC_BRAINPOOL */
  3976. #endif
  3977. #endif
  3978. #if (defined(HAVE_CURVE448) || defined(HAVE_ED448)) && ECC_MIN_KEY_SZ <= 448
  3979. case WOLFSSL_ECC_X448:
  3980. oid = ECC_X448_OID;
  3981. octets = 57;
  3982. break;
  3983. #endif /* HAVE_CURVE448 */
  3984. #ifdef HAVE_ECC
  3985. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  3986. #ifdef HAVE_ECC_BRAINPOOL
  3987. case WOLFSSL_ECC_BRAINPOOLP512R1:
  3988. oid = ECC_BRAINPOOLP512R1_OID;
  3989. octets = 64;
  3990. break;
  3991. #endif /* HAVE_ECC_BRAINPOOL */
  3992. #endif
  3993. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  3994. #ifndef NO_ECC_SECP
  3995. case WOLFSSL_ECC_SECP521R1:
  3996. oid = ECC_SECP521R1_OID;
  3997. octets = 66;
  3998. break;
  3999. #endif /* !NO_ECC_SECP */
  4000. #endif
  4001. #endif
  4002. default: continue; /* unsupported curve */
  4003. }
  4004. #ifdef HAVE_ECC
  4005. /* Set default Oid */
  4006. if (defOid == 0 && ssl->eccTempKeySz <= octets && defSz > octets) {
  4007. defOid = oid;
  4008. defSz = octets;
  4009. }
  4010. /* The eccTempKeySz is the preferred ephemeral key size */
  4011. if (currOid == 0 && ssl->eccTempKeySz == octets)
  4012. currOid = oid;
  4013. if ((nextOid == 0 || nextSz > octets) && ssl->eccTempKeySz <= octets) {
  4014. nextOid = oid;
  4015. nextSz = octets;
  4016. }
  4017. #else
  4018. if (defOid == 0 && defSz > octets) {
  4019. defOid = oid;
  4020. defSz = octets;
  4021. }
  4022. if (currOid == 0)
  4023. currOid = oid;
  4024. if (nextOid == 0 || nextSz > octets) {
  4025. nextOid = oid;
  4026. nextSz = octets;
  4027. }
  4028. #endif
  4029. if (first == ECC_BYTE) {
  4030. switch (second) {
  4031. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  4032. /* ECDHE_ECDSA */
  4033. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
  4034. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
  4035. case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
  4036. case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
  4037. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
  4038. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
  4039. case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
  4040. case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
  4041. case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
  4042. case TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
  4043. key |= ssl->ecdhCurveOID == oid;
  4044. ephmSuite = 1;
  4045. break;
  4046. #ifdef WOLFSSL_STATIC_DH
  4047. /* ECDH_ECDSA */
  4048. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
  4049. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
  4050. case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
  4051. case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
  4052. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
  4053. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
  4054. case TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
  4055. case TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
  4056. if (oid == ECC_X25519_OID && defOid == oid) {
  4057. defOid = 0;
  4058. defSz = 80;
  4059. }
  4060. if (oid == ECC_X448_OID && defOid == oid) {
  4061. defOid = 0;
  4062. defSz = 80;
  4063. }
  4064. key |= ssl->pkCurveOID == oid;
  4065. break;
  4066. #endif /* WOLFSSL_STATIC_DH */
  4067. #endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  4068. #ifndef NO_RSA
  4069. /* ECDHE_RSA */
  4070. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
  4071. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
  4072. case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
  4073. case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
  4074. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
  4075. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
  4076. case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
  4077. case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
  4078. key |= ssl->ecdhCurveOID == oid;
  4079. ephmSuite = 1;
  4080. break;
  4081. #if defined(HAVE_ECC) && defined(WOLFSSL_STATIC_DH)
  4082. /* ECDH_RSA */
  4083. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
  4084. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
  4085. case TLS_ECDH_RSA_WITH_RC4_128_SHA:
  4086. case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
  4087. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
  4088. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
  4089. case TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
  4090. case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
  4091. if (oid == ECC_X25519_OID && defOid == oid) {
  4092. defOid = 0;
  4093. defSz = 80;
  4094. }
  4095. if (oid == ECC_X448_OID && defOid == oid) {
  4096. defOid = 0;
  4097. defSz = 80;
  4098. }
  4099. key |= ssl->pkCurveOID == oid;
  4100. break;
  4101. #endif /* HAVE_ECC && WOLFSSL_STATIC_DH */
  4102. #endif
  4103. default:
  4104. if (oid == ECC_X25519_OID && defOid == oid) {
  4105. defOid = 0;
  4106. defSz = 80;
  4107. }
  4108. if (oid == ECC_X448_OID && defOid == oid) {
  4109. defOid = 0;
  4110. defSz = 80;
  4111. }
  4112. key = 1;
  4113. break;
  4114. }
  4115. }
  4116. /* ChaCha20-Poly1305 ECC cipher suites */
  4117. if (first == CHACHA_BYTE) {
  4118. switch (second) {
  4119. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  4120. /* ECDHE_ECDSA */
  4121. case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 :
  4122. case TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  4123. key |= ssl->ecdhCurveOID == oid;
  4124. ephmSuite = 1;
  4125. break;
  4126. #endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  4127. #ifndef NO_RSA
  4128. /* ECDHE_RSA */
  4129. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 :
  4130. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  4131. key |= ssl->ecdhCurveOID == oid;
  4132. ephmSuite = 1;
  4133. break;
  4134. #endif
  4135. default:
  4136. key = 1;
  4137. break;
  4138. }
  4139. }
  4140. }
  4141. *ecdhCurveOID = ssl->ecdhCurveOID;
  4142. /* Choose the default if it is at the required strength. */
  4143. #ifdef HAVE_ECC
  4144. if (*ecdhCurveOID == 0 && defSz == ssl->eccTempKeySz)
  4145. #else
  4146. if (*ecdhCurveOID == 0)
  4147. #endif
  4148. {
  4149. key = 1;
  4150. *ecdhCurveOID = defOid;
  4151. }
  4152. /* Choose any curve at the required strength. */
  4153. if (*ecdhCurveOID == 0) {
  4154. key = 1;
  4155. *ecdhCurveOID = currOid;
  4156. }
  4157. /* Choose the default if it is at the next highest strength. */
  4158. if (*ecdhCurveOID == 0 && defSz == nextSz)
  4159. *ecdhCurveOID = defOid;
  4160. /* Choose any curve at the next highest strength. */
  4161. if (*ecdhCurveOID == 0)
  4162. *ecdhCurveOID = nextOid;
  4163. /* No curve and ephemeral ECC suite requires a matching curve. */
  4164. if (*ecdhCurveOID == 0 && ephmSuite)
  4165. key = 0;
  4166. return key;
  4167. }
  4168. #endif
  4169. #endif /* NO_WOLFSSL_SERVER */
  4170. int TLSX_SupportedCurve_Copy(TLSX* src, TLSX** dst, void* heap)
  4171. {
  4172. TLSX* extension;
  4173. int ret;
  4174. extension = TLSX_Find(src, TLSX_SUPPORTED_GROUPS);
  4175. if (extension != NULL) {
  4176. SupportedCurve* curve;
  4177. for (curve = (SupportedCurve*)extension->data; curve != NULL;
  4178. curve = curve->next) {
  4179. ret = TLSX_UseSupportedCurve(dst, curve->name, heap);
  4180. if (ret != WOLFSSL_SUCCESS)
  4181. return MEMORY_E;
  4182. }
  4183. }
  4184. return 0;
  4185. }
  4186. int TLSX_UseSupportedCurve(TLSX** extensions, word16 name, void* heap)
  4187. {
  4188. TLSX* extension = NULL;
  4189. SupportedCurve* curve = NULL;
  4190. int ret;
  4191. if (extensions == NULL) {
  4192. return BAD_FUNC_ARG;
  4193. }
  4194. #ifdef WOLFSSL_TLS13
  4195. if (! TLSX_KeyShare_IsSupported(name)) {
  4196. return BAD_FUNC_ARG;
  4197. }
  4198. #endif
  4199. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  4200. if (!extension) {
  4201. ret = TLSX_SupportedCurve_New(&curve, name, heap);
  4202. if (ret != 0)
  4203. return ret;
  4204. ret = TLSX_Push(extensions, TLSX_SUPPORTED_GROUPS, curve, heap);
  4205. if (ret != 0) {
  4206. XFREE(curve, heap, DYNAMIC_TYPE_TLSX);
  4207. return ret;
  4208. }
  4209. }
  4210. else {
  4211. ret = TLSX_SupportedCurve_Append((SupportedCurve*)extension->data, name,
  4212. heap);
  4213. if (ret != 0)
  4214. return ret;
  4215. }
  4216. return WOLFSSL_SUCCESS;
  4217. }
  4218. int TLSX_UsePointFormat(TLSX** extensions, byte format, void* heap)
  4219. {
  4220. TLSX* extension = NULL;
  4221. PointFormat* point = NULL;
  4222. int ret = 0;
  4223. if (extensions == NULL)
  4224. return BAD_FUNC_ARG;
  4225. extension = TLSX_Find(*extensions, TLSX_EC_POINT_FORMATS);
  4226. if (!extension) {
  4227. ret = TLSX_PointFormat_New(&point, format, heap);
  4228. if (ret != 0)
  4229. return ret;
  4230. ret = TLSX_Push(extensions, TLSX_EC_POINT_FORMATS, point, heap);
  4231. if (ret != 0) {
  4232. XFREE(point, heap, DYNAMIC_TYPE_TLSX);
  4233. return ret;
  4234. }
  4235. }
  4236. else {
  4237. ret = TLSX_PointFormat_Append((PointFormat*)extension->data, format,
  4238. heap);
  4239. if (ret != 0)
  4240. return ret;
  4241. }
  4242. return WOLFSSL_SUCCESS;
  4243. }
  4244. #define EC_FREE_ALL TLSX_SupportedCurve_FreeAll
  4245. #define EC_VALIDATE_REQUEST TLSX_SupportedCurve_ValidateRequest
  4246. #ifndef NO_WOLFSSL_CLIENT
  4247. #define EC_GET_SIZE TLSX_SupportedCurve_GetSize
  4248. #define EC_WRITE TLSX_SupportedCurve_Write
  4249. #else
  4250. #define EC_GET_SIZE(list) 0
  4251. #define EC_WRITE(a, b) 0
  4252. #endif
  4253. #if !defined(NO_WOLFSSL_SERVER) || (defined(WOLFSSL_TLS13) && \
  4254. !defined(WOLFSSL_NO_SERVER_GROUPS_EXT))
  4255. #define EC_PARSE TLSX_SupportedCurve_Parse
  4256. #else
  4257. #define EC_PARSE(a, b, c, d, e) 0
  4258. #endif
  4259. #define PF_FREE_ALL TLSX_PointFormat_FreeAll
  4260. #define PF_VALIDATE_REQUEST TLSX_PointFormat_ValidateRequest
  4261. #define PF_VALIDATE_RESPONSE TLSX_PointFormat_ValidateResponse
  4262. #define PF_GET_SIZE TLSX_PointFormat_GetSize
  4263. #define PF_WRITE TLSX_PointFormat_Write
  4264. #ifndef NO_WOLFSSL_SERVER
  4265. #define PF_PARSE TLSX_PointFormat_Parse
  4266. #else
  4267. #define PF_PARSE(a, b, c, d) 0
  4268. #endif
  4269. #else
  4270. #define EC_FREE_ALL(list, heap) WC_DO_NOTHING
  4271. #define EC_GET_SIZE(list) 0
  4272. #define EC_WRITE(a, b) 0
  4273. #define EC_PARSE(a, b, c, d, e) 0
  4274. #define EC_VALIDATE_REQUEST(a, b) WC_DO_NOTHING
  4275. #define PF_FREE_ALL(list, heap) WC_DO_NOTHING
  4276. #define PF_GET_SIZE(list) 0
  4277. #define PF_WRITE(a, b) 0
  4278. #define PF_PARSE(a, b, c, d) 0
  4279. #define PF_VALIDATE_REQUEST(a, b) WC_DO_NOTHING
  4280. #define PF_VALIDATE_RESPONSE(a, b) WC_DO_NOTHING
  4281. #endif /* HAVE_SUPPORTED_CURVES */
  4282. /******************************************************************************/
  4283. /* Renegotiation Indication */
  4284. /******************************************************************************/
  4285. #if defined(HAVE_SECURE_RENEGOTIATION) \
  4286. || defined(HAVE_SERVER_RENEGOTIATION_INFO)
  4287. static byte TLSX_SecureRenegotiation_GetSize(SecureRenegotiation* data,
  4288. int isRequest)
  4289. {
  4290. byte length = OPAQUE8_LEN; /* empty info length */
  4291. /* data will be NULL for HAVE_SERVER_RENEGOTIATION_INFO only */
  4292. if (data && data->enabled && data->verifySet) {
  4293. /* client sends client_verify_data only */
  4294. length += TLS_FINISHED_SZ;
  4295. /* server also sends server_verify_data */
  4296. if (!isRequest)
  4297. length += TLS_FINISHED_SZ;
  4298. }
  4299. return length;
  4300. }
  4301. static word16 TLSX_SecureRenegotiation_Write(SecureRenegotiation* data,
  4302. byte* output, int isRequest)
  4303. {
  4304. word16 offset = OPAQUE8_LEN; /* RenegotiationInfo length */
  4305. if (data && data->enabled && data->verifySet) {
  4306. /* client sends client_verify_data only */
  4307. XMEMCPY(output + offset, data->client_verify_data, TLS_FINISHED_SZ);
  4308. offset += TLS_FINISHED_SZ;
  4309. /* server also sends server_verify_data */
  4310. if (!isRequest) {
  4311. XMEMCPY(output + offset, data->server_verify_data, TLS_FINISHED_SZ);
  4312. offset += TLS_FINISHED_SZ;
  4313. }
  4314. }
  4315. output[0] = (byte)(offset - 1); /* info length - self */
  4316. return offset;
  4317. }
  4318. static int TLSX_SecureRenegotiation_Parse(WOLFSSL* ssl, const byte* input,
  4319. word16 length, byte isRequest)
  4320. {
  4321. int ret = SECURE_RENEGOTIATION_E;
  4322. if (length >= OPAQUE8_LEN) {
  4323. if (isRequest) {
  4324. #ifndef NO_WOLFSSL_SERVER
  4325. if (ssl->secure_renegotiation == NULL) {
  4326. ret = wolfSSL_UseSecureRenegotiation(ssl);
  4327. if (ret == WOLFSSL_SUCCESS)
  4328. ret = 0;
  4329. }
  4330. if (ret != 0 && ret != SECURE_RENEGOTIATION_E) {
  4331. }
  4332. else if (ssl->secure_renegotiation == NULL) {
  4333. }
  4334. else if (!ssl->secure_renegotiation->enabled) {
  4335. if (*input == 0) {
  4336. input++; /* get past size */
  4337. ssl->secure_renegotiation->enabled = 1;
  4338. TLSX_SetResponse(ssl, TLSX_RENEGOTIATION_INFO);
  4339. ret = 0;
  4340. }
  4341. else {
  4342. /* already in error state */
  4343. WOLFSSL_MSG("SCR client verify data present");
  4344. }
  4345. }
  4346. else if (*input == TLS_FINISHED_SZ) {
  4347. if (length < TLS_FINISHED_SZ + 1) {
  4348. WOLFSSL_MSG("SCR malformed buffer");
  4349. ret = BUFFER_E;
  4350. }
  4351. else {
  4352. input++; /* get past size */
  4353. /* validate client verify data */
  4354. if (XMEMCMP(input,
  4355. ssl->secure_renegotiation->client_verify_data,
  4356. TLS_FINISHED_SZ) == 0) {
  4357. WOLFSSL_MSG("SCR client verify data match");
  4358. TLSX_SetResponse(ssl, TLSX_RENEGOTIATION_INFO);
  4359. ret = 0; /* verified */
  4360. }
  4361. else {
  4362. /* already in error state */
  4363. WOLFSSL_MSG("SCR client verify data Failure");
  4364. }
  4365. }
  4366. }
  4367. #endif
  4368. }
  4369. else if (ssl->secure_renegotiation != NULL) {
  4370. #ifndef NO_WOLFSSL_CLIENT
  4371. if (!ssl->secure_renegotiation->enabled) {
  4372. if (*input == 0) {
  4373. ssl->secure_renegotiation->enabled = 1;
  4374. ret = 0;
  4375. }
  4376. }
  4377. else if (*input == 2 * TLS_FINISHED_SZ &&
  4378. length == 2 * TLS_FINISHED_SZ + OPAQUE8_LEN) {
  4379. input++; /* get past size */
  4380. /* validate client and server verify data */
  4381. if (XMEMCMP(input,
  4382. ssl->secure_renegotiation->client_verify_data,
  4383. TLS_FINISHED_SZ) == 0 &&
  4384. XMEMCMP(input + TLS_FINISHED_SZ,
  4385. ssl->secure_renegotiation->server_verify_data,
  4386. TLS_FINISHED_SZ) == 0) {
  4387. WOLFSSL_MSG("SCR client and server verify data match");
  4388. ret = 0; /* verified */
  4389. }
  4390. else {
  4391. /* already in error state */
  4392. WOLFSSL_MSG("SCR client and server verify data Failure");
  4393. }
  4394. }
  4395. #endif
  4396. }
  4397. }
  4398. if (ret != 0) {
  4399. WOLFSSL_ERROR_VERBOSE(ret);
  4400. SendAlert(ssl, alert_fatal, handshake_failure);
  4401. }
  4402. return ret;
  4403. }
  4404. int TLSX_UseSecureRenegotiation(TLSX** extensions, void* heap)
  4405. {
  4406. int ret = 0;
  4407. SecureRenegotiation* data;
  4408. data = (SecureRenegotiation*)XMALLOC(sizeof(SecureRenegotiation), heap,
  4409. DYNAMIC_TYPE_TLSX);
  4410. if (data == NULL)
  4411. return MEMORY_E;
  4412. XMEMSET(data, 0, sizeof(SecureRenegotiation));
  4413. ret = TLSX_Push(extensions, TLSX_RENEGOTIATION_INFO, data, heap);
  4414. if (ret != 0) {
  4415. XFREE(data, heap, DYNAMIC_TYPE_TLSX);
  4416. return ret;
  4417. }
  4418. return WOLFSSL_SUCCESS;
  4419. }
  4420. #ifdef HAVE_SERVER_RENEGOTIATION_INFO
  4421. int TLSX_AddEmptyRenegotiationInfo(TLSX** extensions, void* heap)
  4422. {
  4423. int ret;
  4424. /* send empty renegotiation_info extension */
  4425. TLSX* ext = TLSX_Find(*extensions, TLSX_RENEGOTIATION_INFO);
  4426. if (ext == NULL) {
  4427. ret = TLSX_UseSecureRenegotiation(extensions, heap);
  4428. if (ret != WOLFSSL_SUCCESS)
  4429. return ret;
  4430. ext = TLSX_Find(*extensions, TLSX_RENEGOTIATION_INFO);
  4431. }
  4432. if (ext)
  4433. ext->resp = 1;
  4434. return WOLFSSL_SUCCESS;
  4435. }
  4436. #endif /* HAVE_SERVER_RENEGOTIATION_INFO */
  4437. #define SCR_FREE_ALL(data, heap) XFREE(data, (heap), DYNAMIC_TYPE_TLSX)
  4438. #define SCR_GET_SIZE TLSX_SecureRenegotiation_GetSize
  4439. #define SCR_WRITE TLSX_SecureRenegotiation_Write
  4440. #define SCR_PARSE TLSX_SecureRenegotiation_Parse
  4441. #else
  4442. #define SCR_FREE_ALL(a, heap) WC_DO_NOTHING
  4443. #define SCR_GET_SIZE(a, b) 0
  4444. #define SCR_WRITE(a, b, c) 0
  4445. #define SCR_PARSE(a, b, c, d) 0
  4446. #endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
  4447. /******************************************************************************/
  4448. /* Session Tickets */
  4449. /******************************************************************************/
  4450. #ifdef HAVE_SESSION_TICKET
  4451. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  4452. static void TLSX_SessionTicket_ValidateRequest(WOLFSSL* ssl)
  4453. {
  4454. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_SESSION_TICKET);
  4455. SessionTicket* ticket = extension ?
  4456. (SessionTicket*)extension->data : NULL;
  4457. if (ticket) {
  4458. /* TODO validate ticket timeout here! */
  4459. if (ticket->lifetime == 0xfffffff) {
  4460. /* send empty ticket on timeout */
  4461. TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4462. }
  4463. }
  4464. }
  4465. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  4466. static word16 TLSX_SessionTicket_GetSize(SessionTicket* ticket, int isRequest)
  4467. {
  4468. (void)isRequest;
  4469. return ticket ? ticket->size : 0;
  4470. }
  4471. static word16 TLSX_SessionTicket_Write(SessionTicket* ticket, byte* output,
  4472. int isRequest)
  4473. {
  4474. word16 offset = 0; /* empty ticket */
  4475. if (isRequest && ticket) {
  4476. XMEMCPY(output + offset, ticket->data, ticket->size);
  4477. offset += ticket->size;
  4478. }
  4479. return offset;
  4480. }
  4481. static int TLSX_SessionTicket_Parse(WOLFSSL* ssl, const byte* input,
  4482. word16 length, byte isRequest)
  4483. {
  4484. int ret = 0;
  4485. (void) input; /* avoid unused parameter if NO_WOLFSSL_SERVER defined */
  4486. if (!isRequest) {
  4487. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_SESSION_TICKET))
  4488. return TLSX_HandleUnsupportedExtension(ssl);
  4489. if (length != 0)
  4490. return BUFFER_ERROR;
  4491. #ifndef NO_WOLFSSL_CLIENT
  4492. ssl->expect_session_ticket = 1;
  4493. #endif
  4494. }
  4495. #ifndef NO_WOLFSSL_SERVER
  4496. else {
  4497. /* server side */
  4498. if (ssl->ctx->ticketEncCb == NULL) {
  4499. WOLFSSL_MSG("Client sent session ticket, server has no callback");
  4500. return 0;
  4501. }
  4502. #ifdef HAVE_SECURE_RENEGOTIATION
  4503. if (IsSCR(ssl)) {
  4504. WOLFSSL_MSG("Client sent session ticket during SCR. Ignoring.");
  4505. return 0;
  4506. }
  4507. #endif
  4508. if (length > SESSION_TICKET_LEN) {
  4509. ret = BAD_TICKET_MSG_SZ;
  4510. WOLFSSL_ERROR_VERBOSE(ret);
  4511. } else if (IsAtLeastTLSv1_3(ssl->version)) {
  4512. WOLFSSL_MSG("Process client ticket rejected, TLS 1.3 no support");
  4513. ssl->options.rejectTicket = 1;
  4514. ret = 0; /* not fatal */
  4515. } else if (ssl->options.noTicketTls12) {
  4516. /* ignore ticket request */
  4517. } else if (length == 0) {
  4518. /* blank ticket */
  4519. ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4520. if (ret == WOLFSSL_SUCCESS) {
  4521. ret = 0;
  4522. /* send blank ticket */
  4523. TLSX_SetResponse(ssl, TLSX_SESSION_TICKET);
  4524. ssl->options.createTicket = 1; /* will send ticket msg */
  4525. ssl->options.useTicket = 1;
  4526. ssl->options.resuming = 0; /* no standard resumption */
  4527. ssl->arrays->sessionIDSz = 0; /* no echo on blank ticket */
  4528. }
  4529. } else {
  4530. /* got actual ticket from client */
  4531. ret = DoClientTicket(ssl, input, length);
  4532. if (ret == WOLFSSL_TICKET_RET_OK) { /* use ticket to resume */
  4533. WOLFSSL_MSG("Using existing client ticket");
  4534. ssl->options.useTicket = 1;
  4535. ssl->options.resuming = 1;
  4536. /* SERVER: ticket is peer auth. */
  4537. ssl->options.peerAuthGood = 1;
  4538. } else if (ret == WOLFSSL_TICKET_RET_CREATE) {
  4539. WOLFSSL_MSG("Using existing client ticket, creating new one");
  4540. ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4541. if (ret == WOLFSSL_SUCCESS) {
  4542. ret = 0;
  4543. TLSX_SetResponse(ssl, TLSX_SESSION_TICKET);
  4544. /* send blank ticket */
  4545. ssl->options.createTicket = 1; /* will send ticket msg */
  4546. ssl->options.useTicket = 1;
  4547. ssl->options.resuming = 1;
  4548. /* SERVER: ticket is peer auth. */
  4549. ssl->options.peerAuthGood = 1;
  4550. }
  4551. } else if (ret == WOLFSSL_TICKET_RET_REJECT) {
  4552. WOLFSSL_MSG("Process client ticket rejected, not using");
  4553. ssl->options.rejectTicket = 1;
  4554. ret = 0; /* not fatal */
  4555. } else if (ret == VERSION_ERROR) {
  4556. WOLFSSL_MSG("Process client ticket rejected, bad TLS version");
  4557. ssl->options.rejectTicket = 1;
  4558. ret = 0; /* not fatal */
  4559. } else if (ret == WOLFSSL_TICKET_RET_FATAL) {
  4560. WOLFSSL_MSG("Process client ticket fatal error, not using");
  4561. } else if (ret < 0) {
  4562. WOLFSSL_MSG("Process client ticket unknown error, not using");
  4563. }
  4564. }
  4565. }
  4566. #endif /* NO_WOLFSSL_SERVER */
  4567. #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER)
  4568. (void)ssl;
  4569. #endif
  4570. return ret;
  4571. }
  4572. WOLFSSL_LOCAL SessionTicket* TLSX_SessionTicket_Create(word32 lifetime,
  4573. byte* data, word16 size, void* heap)
  4574. {
  4575. SessionTicket* ticket = (SessionTicket*)XMALLOC(sizeof(SessionTicket),
  4576. heap, DYNAMIC_TYPE_TLSX);
  4577. if (ticket) {
  4578. ticket->data = (byte*)XMALLOC(size, heap, DYNAMIC_TYPE_TLSX);
  4579. if (ticket->data == NULL) {
  4580. XFREE(ticket, heap, DYNAMIC_TYPE_TLSX);
  4581. return NULL;
  4582. }
  4583. XMEMCPY(ticket->data, data, size);
  4584. ticket->size = size;
  4585. ticket->lifetime = lifetime;
  4586. }
  4587. (void)heap;
  4588. return ticket;
  4589. }
  4590. WOLFSSL_LOCAL void TLSX_SessionTicket_Free(SessionTicket* ticket, void* heap)
  4591. {
  4592. if (ticket) {
  4593. XFREE(ticket->data, heap, DYNAMIC_TYPE_TLSX);
  4594. XFREE(ticket, heap, DYNAMIC_TYPE_TLSX);
  4595. }
  4596. (void)heap;
  4597. }
  4598. int TLSX_UseSessionTicket(TLSX** extensions, SessionTicket* ticket, void* heap)
  4599. {
  4600. int ret = 0;
  4601. if (extensions == NULL)
  4602. return BAD_FUNC_ARG;
  4603. /* If the ticket is NULL, the client will request a new ticket from the
  4604. server. Otherwise, the client will use it in the next client hello. */
  4605. if ((ret = TLSX_Push(extensions, TLSX_SESSION_TICKET, (void*)ticket, heap))
  4606. != 0)
  4607. return ret;
  4608. return WOLFSSL_SUCCESS;
  4609. }
  4610. #define WOLF_STK_VALIDATE_REQUEST TLSX_SessionTicket_ValidateRequest
  4611. #define WOLF_STK_GET_SIZE TLSX_SessionTicket_GetSize
  4612. #define WOLF_STK_WRITE TLSX_SessionTicket_Write
  4613. #define WOLF_STK_PARSE TLSX_SessionTicket_Parse
  4614. #define WOLF_STK_FREE(stk, heap) TLSX_SessionTicket_Free((SessionTicket*)(stk),(heap))
  4615. #else
  4616. #define WOLF_STK_FREE(a, b) WC_DO_NOTHING
  4617. #define WOLF_STK_VALIDATE_REQUEST(a) WC_DO_NOTHING
  4618. #define WOLF_STK_GET_SIZE(a, b) 0
  4619. #define WOLF_STK_WRITE(a, b, c) 0
  4620. #define WOLF_STK_PARSE(a, b, c, d) 0
  4621. #endif /* HAVE_SESSION_TICKET */
  4622. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  4623. /******************************************************************************/
  4624. /* Encrypt-then-MAC */
  4625. /******************************************************************************/
  4626. #ifndef WOLFSSL_NO_TLS12
  4627. static int TLSX_EncryptThenMac_Use(WOLFSSL* ssl);
  4628. /**
  4629. * Get the size of the Encrypt-Then-MAC extension.
  4630. *
  4631. * msgType Type of message to put extension into.
  4632. * pSz Size of extension data.
  4633. * return SANITY_MSG_E when the message is not allowed to have extension and
  4634. * 0 otherwise.
  4635. */
  4636. static int TLSX_EncryptThenMac_GetSize(byte msgType, word16* pSz)
  4637. {
  4638. (void)pSz;
  4639. if (msgType != client_hello && msgType != server_hello) {
  4640. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4641. return SANITY_MSG_E;
  4642. }
  4643. /* Empty extension */
  4644. return 0;
  4645. }
  4646. /**
  4647. * Write the Encrypt-Then-MAC extension.
  4648. *
  4649. * data Unused
  4650. * output Extension data buffer. Unused.
  4651. * msgType Type of message to put extension into.
  4652. * pSz Size of extension data.
  4653. * return SANITY_MSG_E when the message is not allowed to have extension and
  4654. * 0 otherwise.
  4655. */
  4656. static int TLSX_EncryptThenMac_Write(void* data, byte* output, byte msgType,
  4657. word16* pSz)
  4658. {
  4659. (void)data;
  4660. (void)output;
  4661. (void)pSz;
  4662. if (msgType != client_hello && msgType != server_hello) {
  4663. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4664. return SANITY_MSG_E;
  4665. }
  4666. /* Empty extension */
  4667. return 0;
  4668. }
  4669. /**
  4670. * Parse the Encrypt-Then-MAC extension.
  4671. *
  4672. * ssl SSL object
  4673. * input Extension data buffer.
  4674. * length Length of this extension's data.
  4675. * msgType Type of message to extension appeared in.
  4676. * return SANITY_MSG_E when the message is not allowed to have extension,
  4677. * BUFFER_ERROR when the extension's data is invalid,
  4678. * MEMORY_E when unable to allocate memory and
  4679. * 0 otherwise.
  4680. */
  4681. static int TLSX_EncryptThenMac_Parse(WOLFSSL* ssl, const byte* input,
  4682. word16 length, byte msgType)
  4683. {
  4684. int ret;
  4685. (void)input;
  4686. if (msgType != client_hello && msgType != server_hello) {
  4687. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4688. return SANITY_MSG_E;
  4689. }
  4690. /* Empty extension */
  4691. if (length != 0)
  4692. return BUFFER_ERROR;
  4693. if (msgType == client_hello) {
  4694. /* Check the user hasn't disallowed use of Encrypt-Then-Mac. */
  4695. if (!ssl->options.disallowEncThenMac) {
  4696. ssl->options.encThenMac = 1;
  4697. /* Set the extension reply. */
  4698. ret = TLSX_EncryptThenMac_Use(ssl);
  4699. if (ret != 0)
  4700. return ret;
  4701. }
  4702. return 0;
  4703. }
  4704. /* Server Hello */
  4705. if (ssl->options.disallowEncThenMac) {
  4706. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4707. return SANITY_MSG_E;
  4708. }
  4709. ssl->options.encThenMac = 1;
  4710. return 0;
  4711. }
  4712. /**
  4713. * Add the Encrypt-Then-MAC extension to list.
  4714. *
  4715. * ssl SSL object
  4716. * return MEMORY_E when unable to allocate memory and 0 otherwise.
  4717. */
  4718. static int TLSX_EncryptThenMac_Use(WOLFSSL* ssl)
  4719. {
  4720. int ret = 0;
  4721. TLSX* extension;
  4722. /* Find the Encrypt-Then-Mac extension if it exists. */
  4723. extension = TLSX_Find(ssl->extensions, TLSX_ENCRYPT_THEN_MAC);
  4724. if (extension == NULL) {
  4725. /* Push new Encrypt-Then-Mac extension. */
  4726. ret = TLSX_Push(&ssl->extensions, TLSX_ENCRYPT_THEN_MAC, NULL,
  4727. ssl->heap);
  4728. if (ret != 0)
  4729. return ret;
  4730. }
  4731. return 0;
  4732. }
  4733. /**
  4734. * Set the Encrypt-Then-MAC extension as one to respond too.
  4735. *
  4736. * ssl SSL object
  4737. * return EXT_MISSING when EncryptThenMac extension not in list.
  4738. */
  4739. int TLSX_EncryptThenMac_Respond(WOLFSSL* ssl)
  4740. {
  4741. TLSX* extension;
  4742. extension = TLSX_Find(ssl->extensions, TLSX_ENCRYPT_THEN_MAC);
  4743. if (extension == NULL)
  4744. return EXT_MISSING;
  4745. extension->resp = 1;
  4746. return 0;
  4747. }
  4748. #define ETM_GET_SIZE TLSX_EncryptThenMac_GetSize
  4749. #define ETM_WRITE TLSX_EncryptThenMac_Write
  4750. #define ETM_PARSE TLSX_EncryptThenMac_Parse
  4751. #else
  4752. #define ETM_GET_SIZE(a, b) 0
  4753. #define ETM_WRITE(a, b, c, d) 0
  4754. #define ETM_PARSE(a, b, c, d) 0
  4755. #endif /* !WOLFSSL_NO_TLS12 */
  4756. #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */
  4757. #ifdef WOLFSSL_SRTP
  4758. /******************************************************************************/
  4759. /* DTLS SRTP (Secure Real-time Transport Protocol) */
  4760. /******************************************************************************/
  4761. /* Only support single SRTP profile */
  4762. typedef struct TlsxSrtp {
  4763. word16 profileCount;
  4764. word16 ids; /* selected bits */
  4765. } TlsxSrtp;
  4766. static int TLSX_UseSRTP_GetSize(TlsxSrtp *srtp)
  4767. {
  4768. /* SRTP Profile Len (2)
  4769. * SRTP Profiles (2)
  4770. * MKI (master key id) Length */
  4771. return (OPAQUE16_LEN + (srtp->profileCount * OPAQUE16_LEN) + 1);
  4772. }
  4773. static TlsxSrtp* TLSX_UseSRTP_New(word16 ids, void* heap)
  4774. {
  4775. TlsxSrtp* srtp;
  4776. int i;
  4777. srtp = (TlsxSrtp*)XMALLOC(sizeof(TlsxSrtp), heap, DYNAMIC_TYPE_TLSX);
  4778. if (srtp == NULL) {
  4779. WOLFSSL_MSG("TLSX SRTP Memory failure");
  4780. return NULL;
  4781. }
  4782. /* count and test each bit set */
  4783. srtp->profileCount = 0;
  4784. for (i=0; i<16; i++) {
  4785. if (ids & (1 << i)) {
  4786. srtp->profileCount++;
  4787. }
  4788. }
  4789. srtp->ids = ids;
  4790. return srtp;
  4791. }
  4792. static void TLSX_UseSRTP_Free(TlsxSrtp *srtp, void* heap)
  4793. {
  4794. if (srtp != NULL) {
  4795. XFREE(srtp, heap, DYNAMIC_TYPE_TLSX);
  4796. }
  4797. (void)heap;
  4798. }
  4799. static int TLSX_UseSRTP_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  4800. byte isRequest)
  4801. {
  4802. int ret = BAD_FUNC_ARG;
  4803. word16 profile_len = 0;
  4804. word16 profile_value = 0;
  4805. word16 offset = 0;
  4806. #ifndef NO_WOLFSSL_SERVER
  4807. int i;
  4808. TlsxSrtp* srtp = NULL;
  4809. #endif
  4810. if (length < OPAQUE16_LEN) {
  4811. return BUFFER_ERROR;
  4812. }
  4813. /* reset selected DTLS SRTP profile ID */
  4814. ssl->dtlsSrtpId = 0;
  4815. /* total length, not include itself */
  4816. ato16(input, &profile_len);
  4817. offset += OPAQUE16_LEN;
  4818. if (!isRequest) {
  4819. #ifndef NO_WOLFSSL_CLIENT
  4820. if (length < offset + OPAQUE16_LEN)
  4821. return BUFFER_ERROR;
  4822. ato16(input + offset, &profile_value);
  4823. /* check that the profile received was in the ones we support */
  4824. if (profile_value < 16 &&
  4825. (ssl->dtlsSrtpProfiles & (1 << profile_value))) {
  4826. ssl->dtlsSrtpId = profile_value;
  4827. ret = 0; /* success */
  4828. }
  4829. #endif
  4830. }
  4831. #ifndef NO_WOLFSSL_SERVER
  4832. else {
  4833. /* parse remainder one profile at a time, looking for match in CTX */
  4834. ret = 0;
  4835. for (i=offset; i<length; i+=OPAQUE16_LEN) {
  4836. ato16(input+i, &profile_value);
  4837. /* find first match */
  4838. if (profile_value < 16 &&
  4839. ssl->dtlsSrtpProfiles & (1 << profile_value)) {
  4840. ssl->dtlsSrtpId = profile_value;
  4841. /* make sure we respond with selected SRTP id selected */
  4842. srtp = TLSX_UseSRTP_New((1 << profile_value), ssl->heap);
  4843. if (srtp != NULL) {
  4844. ret = TLSX_Push(&ssl->extensions, TLSX_USE_SRTP,
  4845. (void*)srtp, ssl->heap);
  4846. if (ret == 0) {
  4847. TLSX_SetResponse(ssl, TLSX_USE_SRTP);
  4848. /* successfully set extension */
  4849. }
  4850. }
  4851. else {
  4852. ret = MEMORY_E;
  4853. }
  4854. break;
  4855. }
  4856. }
  4857. }
  4858. if (ret == 0 && ssl->dtlsSrtpId == 0) {
  4859. WOLFSSL_MSG("TLSX_UseSRTP_Parse profile not found!");
  4860. /* not fatal */
  4861. }
  4862. else if (ret != 0) {
  4863. ssl->dtlsSrtpId = 0;
  4864. TLSX_UseSRTP_Free(srtp, ssl->heap);
  4865. }
  4866. #endif
  4867. (void)profile_len;
  4868. return ret;
  4869. }
  4870. static word16 TLSX_UseSRTP_Write(TlsxSrtp* srtp, byte* output)
  4871. {
  4872. word16 offset = 0;
  4873. int i, j;
  4874. c16toa(srtp->profileCount * 2, output + offset);
  4875. offset += OPAQUE16_LEN;
  4876. j = 0;
  4877. for (i = 0; i < srtp->profileCount; i++) {
  4878. for (; j < 16; j++) {
  4879. if (srtp->ids & (1 << j)) {
  4880. c16toa(j, output + offset);
  4881. offset += OPAQUE16_LEN;
  4882. }
  4883. }
  4884. }
  4885. output[offset++] = 0x00; /* MKI Length */
  4886. return offset;
  4887. }
  4888. static int TLSX_UseSRTP(TLSX** extensions, word16 profiles, void* heap)
  4889. {
  4890. int ret = 0;
  4891. TLSX* extension;
  4892. if (extensions == NULL) {
  4893. return BAD_FUNC_ARG;
  4894. }
  4895. extension = TLSX_Find(*extensions, TLSX_USE_SRTP);
  4896. if (extension == NULL) {
  4897. TlsxSrtp* srtp = TLSX_UseSRTP_New(profiles, heap);
  4898. if (srtp == NULL) {
  4899. return MEMORY_E;
  4900. }
  4901. ret = TLSX_Push(extensions, TLSX_USE_SRTP, (void*)srtp, heap);
  4902. if (ret != 0) {
  4903. TLSX_UseSRTP_Free(srtp, heap);
  4904. }
  4905. }
  4906. return ret;
  4907. }
  4908. #ifndef NO_WOLFSSL_SERVER
  4909. #define SRTP_FREE TLSX_UseSRTP_Free
  4910. #define SRTP_PARSE TLSX_UseSRTP_Parse
  4911. #define SRTP_WRITE TLSX_UseSRTP_Write
  4912. #define SRTP_GET_SIZE TLSX_UseSRTP_GetSize
  4913. #else
  4914. #define SRTP_FREE(a, b) WC_DO_NOTHING
  4915. #define SRTP_PARSE(a, b, c, d) 0
  4916. #define SRTP_WRITE(a, b) 0
  4917. #define SRTP_GET_SIZE(a) 0
  4918. #endif
  4919. #endif /* WOLFSSL_SRTP */
  4920. /******************************************************************************/
  4921. /* Supported Versions */
  4922. /******************************************************************************/
  4923. #ifdef WOLFSSL_TLS13
  4924. static WC_INLINE int versionIsGreater(byte isDtls, byte a, byte b)
  4925. {
  4926. (void)isDtls;
  4927. #ifdef WOLFSSL_DTLS
  4928. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4929. if (isDtls)
  4930. return a < b;
  4931. #endif /* WOLFSSL_DTLS */
  4932. return a > b;
  4933. }
  4934. static WC_INLINE int versionIsLesser(byte isDtls, byte a, byte b)
  4935. {
  4936. (void)isDtls;
  4937. #ifdef WOLFSSL_DTLS
  4938. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4939. if (isDtls)
  4940. return a > b;
  4941. #endif /* WOLFSSL_DTLS */
  4942. return a < b;
  4943. }
  4944. static WC_INLINE int versionIsAtLeast(byte isDtls, byte a, byte b)
  4945. {
  4946. (void)isDtls;
  4947. #ifdef WOLFSSL_DTLS
  4948. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4949. if (isDtls)
  4950. return a <= b;
  4951. #endif /* WOLFSSL_DTLS */
  4952. return a >= b;
  4953. }
  4954. static WC_INLINE int versionIsLessEqual(byte isDtls, byte a, byte b)
  4955. {
  4956. (void)isDtls;
  4957. #ifdef WOLFSSL_DTLS
  4958. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4959. if (isDtls)
  4960. return a >= b;
  4961. #endif /* WOLFSSL_DTLS */
  4962. return a <= b;
  4963. }
  4964. /* Return the size of the SupportedVersions extension's data.
  4965. *
  4966. * data The SSL/TLS object.
  4967. * msgType The type of the message this extension is being written into.
  4968. * returns the length of data that will be in the extension.
  4969. */
  4970. static int TLSX_SupportedVersions_GetSize(void* data, byte msgType, word16* pSz)
  4971. {
  4972. WOLFSSL* ssl = (WOLFSSL*)data;
  4973. byte tls13Minor, tls12Minor, tls11Minor, isDtls;
  4974. isDtls = !!ssl->options.dtls;
  4975. tls13Minor = (byte)(isDtls ? DTLSv1_3_MINOR : TLSv1_3_MINOR);
  4976. tls12Minor = (byte)(isDtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR);
  4977. tls11Minor = (byte)(isDtls ? DTLS_MINOR : TLSv1_1_MINOR);
  4978. /* unused on some configuration */
  4979. (void)tls12Minor;
  4980. (void)tls13Minor;
  4981. (void)tls11Minor;
  4982. if (msgType == client_hello) {
  4983. /* TLS v1.2 and TLS v1.3 */
  4984. int cnt = 0;
  4985. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13Minor)
  4986. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  4987. defined(WOLFSSL_WPAS_SMALL)
  4988. && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0
  4989. #endif
  4990. ) {
  4991. cnt++;
  4992. }
  4993. if (ssl->options.downgrade) {
  4994. #ifndef WOLFSSL_NO_TLS12
  4995. if (versionIsLessEqual(
  4996. isDtls, ssl->options.minDowngrade, tls12Minor)
  4997. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  4998. defined(WOLFSSL_WPAS_SMALL)
  4999. && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0
  5000. #endif
  5001. ) {
  5002. cnt++;
  5003. }
  5004. #endif
  5005. #ifndef NO_OLD_TLS
  5006. if (versionIsLessEqual(
  5007. isDtls, ssl->options.minDowngrade, tls11Minor)
  5008. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5009. defined(WOLFSSL_WPAS_SMALL)
  5010. && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0
  5011. #endif
  5012. ) {
  5013. cnt++;
  5014. }
  5015. #ifdef WOLFSSL_ALLOW_TLSV10
  5016. if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR)
  5017. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5018. defined(WOLFSSL_WPAS_SMALL)
  5019. && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0
  5020. #endif
  5021. ) {
  5022. cnt++;
  5023. }
  5024. #endif
  5025. #endif
  5026. }
  5027. *pSz += (word16)(OPAQUE8_LEN + cnt * OPAQUE16_LEN);
  5028. }
  5029. else if (msgType == server_hello || msgType == hello_retry_request) {
  5030. *pSz += OPAQUE16_LEN;
  5031. }
  5032. else {
  5033. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5034. return SANITY_MSG_E;
  5035. }
  5036. return 0;
  5037. }
  5038. /* Writes the SupportedVersions extension into the buffer.
  5039. *
  5040. * data The SSL/TLS object.
  5041. * output The buffer to write the extension into.
  5042. * msgType The type of the message this extension is being written into.
  5043. * returns the length of data that was written.
  5044. */
  5045. static int TLSX_SupportedVersions_Write(void* data, byte* output,
  5046. byte msgType, word16* pSz)
  5047. {
  5048. WOLFSSL* ssl = (WOLFSSL*)data;
  5049. byte tls13minor, tls12minor, tls11minor, isDtls = 0;
  5050. tls13minor = (byte)TLSv1_3_MINOR;
  5051. tls12minor = (byte)TLSv1_2_MINOR;
  5052. tls11minor = (byte)TLSv1_1_MINOR;
  5053. /* unused in some configuration */
  5054. (void)tls11minor;
  5055. (void)tls12minor;
  5056. #ifdef WOLFSSL_DTLS13
  5057. if (ssl->options.dtls) {
  5058. tls13minor = (byte)DTLSv1_3_MINOR;
  5059. tls12minor = (byte)DTLSv1_2_MINOR;
  5060. tls11minor = (byte)DTLS_MINOR;
  5061. isDtls = 1;
  5062. }
  5063. #endif /* WOLFSSL_DTLS13 */
  5064. if (msgType == client_hello) {
  5065. byte major = ssl->ctx->method->version.major;
  5066. byte* cnt = output++;
  5067. *cnt = 0;
  5068. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13minor)
  5069. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5070. defined(WOLFSSL_WPAS_SMALL)
  5071. && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0
  5072. #endif
  5073. ) {
  5074. *cnt += OPAQUE16_LEN;
  5075. #ifdef WOLFSSL_TLS13_DRAFT
  5076. /* The TLS draft major number. */
  5077. *(output++) = TLS_DRAFT_MAJOR;
  5078. /* Version of draft supported. */
  5079. *(output++) = TLS_DRAFT_MINOR;
  5080. #else
  5081. *(output++) = major;
  5082. *(output++) = tls13minor;
  5083. #endif
  5084. }
  5085. if (ssl->options.downgrade) {
  5086. #ifndef WOLFSSL_NO_TLS12
  5087. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls12minor)
  5088. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5089. defined(WOLFSSL_WPAS_SMALL)
  5090. && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0
  5091. #endif
  5092. ) {
  5093. *cnt += OPAQUE16_LEN;
  5094. *(output++) = major;
  5095. *(output++) = tls12minor;
  5096. }
  5097. #endif
  5098. #ifndef NO_OLD_TLS
  5099. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls11minor)
  5100. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5101. defined(WOLFSSL_WPAS_SMALL)
  5102. && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0
  5103. #endif
  5104. ) {
  5105. *cnt += OPAQUE16_LEN;
  5106. *(output++) = major;
  5107. *(output++) = tls11minor;
  5108. }
  5109. #ifdef WOLFSSL_ALLOW_TLSV10
  5110. if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR)
  5111. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5112. defined(WOLFSSL_WPAS_SMALL)
  5113. && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0
  5114. #endif
  5115. ) {
  5116. *cnt += OPAQUE16_LEN;
  5117. *(output++) = major;
  5118. *(output++) = (byte)TLSv1_MINOR;
  5119. }
  5120. #endif
  5121. #endif
  5122. }
  5123. *pSz += (word16)(OPAQUE8_LEN + *cnt);
  5124. }
  5125. else if (msgType == server_hello || msgType == hello_retry_request) {
  5126. output[0] = ssl->version.major;
  5127. output[1] = ssl->version.minor;
  5128. *pSz += OPAQUE16_LEN;
  5129. }
  5130. else {
  5131. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5132. return SANITY_MSG_E;
  5133. }
  5134. return 0;
  5135. }
  5136. /* Parse the SupportedVersions extension.
  5137. *
  5138. * ssl The SSL/TLS object.
  5139. * input The buffer with the extension data.
  5140. * length The length of the extension data.
  5141. * msgType The type of the message this extension is being parsed from.
  5142. * pv The output ProtocolVersion for the negotiated version
  5143. * opts The output options structure. Can be NULL.
  5144. * exts The output extensions list. Can be NULL.
  5145. * returns 0 on success, otherwise failure.
  5146. */
  5147. int TLSX_SupportedVersions_Parse(const WOLFSSL* ssl, const byte* input,
  5148. word16 length, byte msgType, ProtocolVersion* pv, Options* opts,
  5149. TLSX** exts)
  5150. {
  5151. /* The client's greatest minor version that we support */
  5152. byte clientGreatestMinor = SSLv3_MINOR;
  5153. int ret;
  5154. byte major, minor;
  5155. byte tls13minor, tls12minor;
  5156. byte isDtls;
  5157. tls13minor = TLSv1_3_MINOR;
  5158. tls12minor = TLSv1_2_MINOR;
  5159. isDtls = ssl->options.dtls == 1;
  5160. #ifdef WOLFSSL_DTLS13
  5161. if (ssl->options.dtls) {
  5162. tls13minor = DTLSv1_3_MINOR;
  5163. tls12minor = DTLSv1_2_MINOR;
  5164. clientGreatestMinor = DTLS_MINOR;
  5165. }
  5166. #endif /* WOLFSSL_DTLS13 */
  5167. if (msgType == client_hello) {
  5168. int i;
  5169. int len;
  5170. int set = 0;
  5171. /* Must contain a length and at least one version. */
  5172. if (length < OPAQUE8_LEN + OPAQUE16_LEN || (length & 1) != 1)
  5173. return BUFFER_ERROR;
  5174. len = *input;
  5175. /* Protocol version array must fill rest of data. */
  5176. if (length != (word16)OPAQUE8_LEN + len)
  5177. return BUFFER_ERROR;
  5178. input++;
  5179. /* Find first match. */
  5180. for (i = 0; i < len; i += OPAQUE16_LEN) {
  5181. major = input[i];
  5182. minor = input[i + OPAQUE8_LEN];
  5183. #ifdef WOLFSSL_TLS13_DRAFT
  5184. if (major == TLS_DRAFT_MAJOR && minor == TLS_DRAFT_MINOR) {
  5185. major = SSLv3_MAJOR;
  5186. minor = TLSv1_3_MINOR;
  5187. }
  5188. #else
  5189. if (major == TLS_DRAFT_MAJOR)
  5190. continue;
  5191. #endif
  5192. if (major != ssl->ctx->method->version.major)
  5193. continue;
  5194. /* No upgrade allowed. */
  5195. if (versionIsGreater(isDtls, minor, ssl->version.minor))
  5196. continue;
  5197. /* Check downgrade. */
  5198. if (versionIsLesser(isDtls, minor, ssl->version.minor)) {
  5199. if (!ssl->options.downgrade)
  5200. continue;
  5201. if (versionIsLesser(isDtls, minor, ssl->options.minDowngrade))
  5202. continue;
  5203. }
  5204. if (versionIsGreater(isDtls, minor, clientGreatestMinor))
  5205. clientGreatestMinor = minor;
  5206. set = 1;
  5207. }
  5208. if (!set) {
  5209. /* No common supported version was negotiated */
  5210. SendAlert((WOLFSSL*)ssl, alert_fatal,
  5211. wolfssl_alert_protocol_version);
  5212. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5213. return VERSION_ERROR;
  5214. }
  5215. pv->minor = clientGreatestMinor;
  5216. if (versionIsAtLeast(isDtls, clientGreatestMinor, tls13minor)) {
  5217. if (opts != NULL)
  5218. opts->tls1_3 = 1;
  5219. /* TLS v1.3 requires supported version extension */
  5220. if (exts != NULL &&
  5221. TLSX_Find(*exts, TLSX_SUPPORTED_VERSIONS) == NULL) {
  5222. ret = TLSX_Push(exts,
  5223. TLSX_SUPPORTED_VERSIONS, ssl, ssl->heap);
  5224. if (ret != 0) {
  5225. return ret;
  5226. }
  5227. /* *exts should be pointing to the TLSX_SUPPORTED_VERSIONS
  5228. * ext in the list since it was pushed. */
  5229. (*exts)->resp = 1;
  5230. }
  5231. }
  5232. }
  5233. else if (msgType == server_hello || msgType == hello_retry_request) {
  5234. /* Must contain one version. */
  5235. if (length != OPAQUE16_LEN)
  5236. return BUFFER_ERROR;
  5237. major = input[0];
  5238. minor = input[OPAQUE8_LEN];
  5239. if (major != ssl->ctx->method->version.major) {
  5240. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5241. return VERSION_ERROR;
  5242. }
  5243. /* Can't downgrade with this extension below TLS v1.3. */
  5244. if (versionIsLesser(isDtls, minor, tls13minor)) {
  5245. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5246. return VERSION_ERROR;
  5247. }
  5248. /* Version is TLS v1.2 to handle downgrading from TLS v1.3+. */
  5249. if (ssl->options.downgrade && ssl->version.minor == tls12minor) {
  5250. /* Set minor version back to TLS v1.3+ */
  5251. pv->minor = ssl->ctx->method->version.minor;
  5252. }
  5253. /* No upgrade allowed. */
  5254. if (versionIsLesser(isDtls, ssl->version.minor, minor)) {
  5255. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5256. return VERSION_ERROR;
  5257. }
  5258. /* Check downgrade. */
  5259. if (versionIsGreater(isDtls, ssl->version.minor, minor)) {
  5260. if (!ssl->options.downgrade) {
  5261. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5262. return VERSION_ERROR;
  5263. }
  5264. if (versionIsLesser(
  5265. isDtls, minor, ssl->options.minDowngrade)) {
  5266. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5267. return VERSION_ERROR;
  5268. }
  5269. /* Downgrade the version. */
  5270. pv->minor = minor;
  5271. }
  5272. }
  5273. else {
  5274. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5275. return SANITY_MSG_E;
  5276. }
  5277. return 0;
  5278. }
  5279. /* Sets a new SupportedVersions extension into the extension list.
  5280. *
  5281. * extensions The list of extensions.
  5282. * data The extensions specific data.
  5283. * heap The heap used for allocation.
  5284. * returns 0 on success, otherwise failure.
  5285. */
  5286. static int TLSX_SetSupportedVersions(TLSX** extensions, const void* data,
  5287. void* heap)
  5288. {
  5289. if (extensions == NULL || data == NULL)
  5290. return BAD_FUNC_ARG;
  5291. return TLSX_Push(extensions, TLSX_SUPPORTED_VERSIONS, data, heap);
  5292. }
  5293. #define SV_GET_SIZE TLSX_SupportedVersions_GetSize
  5294. #define SV_WRITE TLSX_SupportedVersions_Write
  5295. #define SV_PARSE TLSX_SupportedVersions_Parse
  5296. #else
  5297. #define SV_GET_SIZE(a, b, c) 0
  5298. #define SV_WRITE(a, b, c, d) 0
  5299. #define SV_PARSE(a, b, c, d, e, f, g) 0
  5300. #endif /* WOLFSSL_TLS13 */
  5301. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  5302. /******************************************************************************/
  5303. /* Cookie */
  5304. /******************************************************************************/
  5305. /* Free the cookie data.
  5306. *
  5307. * cookie Cookie data.
  5308. * heap The heap used for allocation.
  5309. */
  5310. static void TLSX_Cookie_FreeAll(Cookie* cookie, void* heap)
  5311. {
  5312. (void)heap;
  5313. if (cookie != NULL)
  5314. XFREE(cookie, heap, DYNAMIC_TYPE_TLSX);
  5315. }
  5316. /* Get the size of the encoded Cookie extension.
  5317. * In messages: ClientHello and HelloRetryRequest.
  5318. *
  5319. * cookie The cookie to write.
  5320. * msgType The type of the message this extension is being written into.
  5321. * returns the number of bytes of the encoded Cookie extension.
  5322. */
  5323. static int TLSX_Cookie_GetSize(Cookie* cookie, byte msgType, word16* pSz)
  5324. {
  5325. if (msgType == client_hello || msgType == hello_retry_request) {
  5326. *pSz += OPAQUE16_LEN + cookie->len;
  5327. }
  5328. else {
  5329. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5330. return SANITY_MSG_E;
  5331. }
  5332. return 0;
  5333. }
  5334. /* Writes the Cookie extension into the output buffer.
  5335. * Assumes that the the output buffer is big enough to hold data.
  5336. * In messages: ClientHello and HelloRetryRequest.
  5337. *
  5338. * cookie The cookie to write.
  5339. * output The buffer to write into.
  5340. * msgType The type of the message this extension is being written into.
  5341. * returns the number of bytes written into the buffer.
  5342. */
  5343. static int TLSX_Cookie_Write(Cookie* cookie, byte* output, byte msgType,
  5344. word16* pSz)
  5345. {
  5346. if (msgType == client_hello || msgType == hello_retry_request) {
  5347. c16toa(cookie->len, output);
  5348. output += OPAQUE16_LEN;
  5349. XMEMCPY(output, cookie->data, cookie->len);
  5350. *pSz += OPAQUE16_LEN + cookie->len;
  5351. }
  5352. else {
  5353. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5354. return SANITY_MSG_E;
  5355. }
  5356. return 0;
  5357. }
  5358. /* Parse the Cookie extension.
  5359. * In messages: ClientHello and HelloRetryRequest.
  5360. *
  5361. * ssl The SSL/TLS object.
  5362. * input The extension data.
  5363. * length The length of the extension data.
  5364. * msgType The type of the message this extension is being parsed from.
  5365. * returns 0 on success and other values indicate failure.
  5366. */
  5367. static int TLSX_Cookie_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  5368. byte msgType)
  5369. {
  5370. word16 len;
  5371. word16 idx = 0;
  5372. TLSX* extension;
  5373. Cookie* cookie;
  5374. if (msgType != client_hello && msgType != hello_retry_request) {
  5375. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5376. return SANITY_MSG_E;
  5377. }
  5378. /* Message contains length and Cookie which must be at least one byte
  5379. * in length.
  5380. */
  5381. if (length < OPAQUE16_LEN + 1)
  5382. return BUFFER_E;
  5383. ato16(input + idx, &len);
  5384. idx += OPAQUE16_LEN;
  5385. if (length - idx != len)
  5386. return BUFFER_E;
  5387. if (msgType == hello_retry_request)
  5388. return TLSX_Cookie_Use(ssl, input + idx, len, NULL, 0, 0,
  5389. &ssl->extensions);
  5390. /* client_hello */
  5391. extension = TLSX_Find(ssl->extensions, TLSX_COOKIE);
  5392. if (extension == NULL) {
  5393. #ifdef WOLFSSL_DTLS13
  5394. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version))
  5395. /* Allow a cookie extension with DTLS 1.3 because it is possible
  5396. * that a different SSL instance sent the cookie but we are now
  5397. * receiving it. */
  5398. return TLSX_Cookie_Use(ssl, input + idx, len, NULL, 0, 0,
  5399. &ssl->extensions);
  5400. else
  5401. #endif
  5402. {
  5403. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  5404. return HRR_COOKIE_ERROR;
  5405. }
  5406. }
  5407. cookie = (Cookie*)extension->data;
  5408. if (cookie->len != len || XMEMCMP(cookie->data, input + idx, len) != 0) {
  5409. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  5410. return HRR_COOKIE_ERROR;
  5411. }
  5412. /* Request seen. */
  5413. extension->resp = 0;
  5414. return 0;
  5415. }
  5416. /* Use the data to create a new Cookie object in the extensions.
  5417. *
  5418. * ssl SSL/TLS object.
  5419. * data Cookie data.
  5420. * len Length of cookie data in bytes.
  5421. * mac MAC data.
  5422. * macSz Length of MAC data in bytes.
  5423. * resp Indicates the extension will go into a response (HelloRetryRequest).
  5424. * returns 0 on success and other values indicate failure.
  5425. */
  5426. int TLSX_Cookie_Use(const WOLFSSL* ssl, const byte* data, word16 len, byte* mac,
  5427. byte macSz, int resp, TLSX** exts)
  5428. {
  5429. int ret = 0;
  5430. TLSX* extension;
  5431. Cookie* cookie;
  5432. /* Find the cookie extension if it exists. */
  5433. extension = TLSX_Find(*exts, TLSX_COOKIE);
  5434. if (extension == NULL) {
  5435. /* Push new cookie extension. */
  5436. ret = TLSX_Push(exts, TLSX_COOKIE, NULL, ssl->heap);
  5437. if (ret != 0)
  5438. return ret;
  5439. extension = TLSX_Find(*exts, TLSX_COOKIE);
  5440. if (extension == NULL)
  5441. return MEMORY_E;
  5442. }
  5443. cookie = (Cookie*)XMALLOC(sizeof(Cookie) + len + macSz, ssl->heap,
  5444. DYNAMIC_TYPE_TLSX);
  5445. if (cookie == NULL)
  5446. return MEMORY_E;
  5447. cookie->len = len + macSz;
  5448. XMEMCPY(cookie->data, data, len);
  5449. if (mac != NULL)
  5450. XMEMCPY(cookie->data + len, mac, macSz);
  5451. if (extension->data != NULL)
  5452. XFREE(extension->data, ssl->heap, DYNAMIC_TYPE_TLSX);
  5453. extension->data = (void*)cookie;
  5454. extension->resp = (byte)resp;
  5455. return 0;
  5456. }
  5457. #define CKE_FREE_ALL TLSX_Cookie_FreeAll
  5458. #define CKE_GET_SIZE TLSX_Cookie_GetSize
  5459. #define CKE_WRITE TLSX_Cookie_Write
  5460. #define CKE_PARSE TLSX_Cookie_Parse
  5461. #else
  5462. #define CKE_FREE_ALL(a, b) 0
  5463. #define CKE_GET_SIZE(a, b, c) 0
  5464. #define CKE_WRITE(a, b, c, d) 0
  5465. #define CKE_PARSE(a, b, c, d) 0
  5466. #endif
  5467. #if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && \
  5468. !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA)
  5469. /* Currently only settable through compatibility API */
  5470. /******************************************************************************/
  5471. /* Certificate Authorities */
  5472. /******************************************************************************/
  5473. static word16 TLSX_CA_Names_GetSize(void* data)
  5474. {
  5475. WOLFSSL* ssl = (WOLFSSL*)data;
  5476. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  5477. word16 size = 0;
  5478. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5479. /* To add support use a different member like ssl->ca_names and
  5480. * add accessor functions:
  5481. * - *_set0_CA_list
  5482. * - *_get0_CA_list */
  5483. WOLFSSL_MSG("We don't currently support sending the client's list.");
  5484. return 0;
  5485. }
  5486. /* Length of names */
  5487. size += OPAQUE16_LEN;
  5488. for (names = SSL_CA_NAMES(ssl); names != NULL; names = names->next) {
  5489. byte seq[MAX_SEQ_SZ];
  5490. WOLFSSL_X509_NAME* name = names->data.name;
  5491. if (name != NULL) {
  5492. /* 16-bit length | SEQ | Len | DER of name */
  5493. size += (word16)(OPAQUE16_LEN + SetSequence(name->rawLen, seq) +
  5494. name->rawLen);
  5495. }
  5496. }
  5497. return size;
  5498. }
  5499. static word16 TLSX_CA_Names_Write(void* data, byte* output)
  5500. {
  5501. WOLFSSL* ssl = (WOLFSSL*)data;
  5502. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  5503. byte* len;
  5504. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5505. /* To add support use a different member like ssl->ca_names and
  5506. * add accessor functions:
  5507. * - *_set0_CA_list
  5508. * - *_get0_CA_list */
  5509. WOLFSSL_MSG("We don't currently support sending the client's list.");
  5510. return 0;
  5511. }
  5512. /* Reserve space for the length value */
  5513. len = output;
  5514. output += OPAQUE16_LEN;
  5515. for (names = SSL_CA_NAMES(ssl); names != NULL; names = names->next) {
  5516. byte seq[MAX_SEQ_SZ];
  5517. WOLFSSL_X509_NAME* name = names->data.name;
  5518. if (name != NULL) {
  5519. c16toa((word16)name->rawLen +
  5520. (word16)SetSequence(name->rawLen, seq), output);
  5521. output += OPAQUE16_LEN;
  5522. output += SetSequence(name->rawLen, output);
  5523. XMEMCPY(output, name->raw, name->rawLen);
  5524. output += name->rawLen;
  5525. }
  5526. }
  5527. /* Write the total length */
  5528. c16toa((word16)(output - len - OPAQUE16_LEN), len);
  5529. return (word16)(output - len);
  5530. }
  5531. static int TLSX_CA_Names_Parse(WOLFSSL *ssl, const byte* input,
  5532. word16 length, byte isRequest)
  5533. {
  5534. word16 extLen;
  5535. (void)isRequest;
  5536. if (ssl->options.side == WOLFSSL_SERVER_END) {
  5537. /* To add support use a different member like ssl->ca_names and
  5538. * add accessor functions:
  5539. * - *_set0_CA_list
  5540. * - *_get0_CA_list */
  5541. WOLFSSL_MSG("We don't currently support parsing the client's list.");
  5542. return 0;
  5543. }
  5544. if (ssl->client_ca_names != ssl->ctx->client_ca_names)
  5545. wolfSSL_sk_X509_NAME_pop_free(ssl->client_ca_names, NULL);
  5546. ssl->client_ca_names = wolfSSL_sk_X509_NAME_new(NULL);
  5547. if (ssl->client_ca_names == NULL)
  5548. return MEMORY_ERROR;
  5549. ato16(input, &extLen);
  5550. input += OPAQUE16_LEN;
  5551. length -= OPAQUE16_LEN;
  5552. if (extLen != length)
  5553. return BUFFER_ERROR;
  5554. while (length) {
  5555. word32 idx = 0;
  5556. WOLFSSL_X509_NAME* name = NULL;
  5557. int ret = 0;
  5558. /* Use a DecodedCert struct to get access to GetName to
  5559. * parse DN name */
  5560. #ifdef WOLFSSL_SMALL_STACK
  5561. DecodedCert *cert = (DecodedCert *)XMALLOC(
  5562. sizeof(*cert), ssl->heap, DYNAMIC_TYPE_DCERT);
  5563. if (cert == NULL)
  5564. return MEMORY_ERROR;
  5565. #else
  5566. DecodedCert cert[1];
  5567. #endif
  5568. ato16(input, &extLen);
  5569. idx += OPAQUE16_LEN;
  5570. if (extLen > length)
  5571. return BUFFER_ERROR;
  5572. InitDecodedCert(cert, input + idx, extLen, ssl->heap);
  5573. idx += extLen;
  5574. ret = GetName(cert, SUBJECT, extLen);
  5575. if (ret == 0 && (name = wolfSSL_X509_NAME_new()) == NULL)
  5576. ret = MEMORY_ERROR;
  5577. if (ret == 0)
  5578. CopyDecodedName(name, cert, SUBJECT);
  5579. if (ret == 0 && wolfSSL_sk_X509_NAME_push(ssl->client_ca_names, name)
  5580. == WOLFSSL_FAILURE)
  5581. ret = MEMORY_ERROR;
  5582. FreeDecodedCert(cert);
  5583. #ifdef WOLFSSL_SMALL_STACK
  5584. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  5585. #endif
  5586. if (ret != 0)
  5587. return ret;
  5588. input += idx;
  5589. length -= (word16)idx;
  5590. }
  5591. return 0;
  5592. }
  5593. #define CAN_GET_SIZE TLSX_CA_Names_GetSize
  5594. #define CAN_WRITE TLSX_CA_Names_Write
  5595. #define CAN_PARSE TLSX_CA_Names_Parse
  5596. #else
  5597. #define CAN_GET_SIZE(...) 0
  5598. #define CAN_WRITE(...) 0
  5599. #define CAN_PARSE(...) 0
  5600. #endif
  5601. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  5602. /******************************************************************************/
  5603. /* Signature Algorithms */
  5604. /******************************************************************************/
  5605. /* Return the size of the SignatureAlgorithms extension's data.
  5606. *
  5607. * data Unused
  5608. * returns the length of data that will be in the extension.
  5609. */
  5610. static word16 TLSX_SignatureAlgorithms_GetSize(void* data)
  5611. {
  5612. SignatureAlgorithms* sa = (SignatureAlgorithms*)data;
  5613. if (sa->hashSigAlgoSz == 0)
  5614. return OPAQUE16_LEN + WOLFSSL_SUITES(sa->ssl)->hashSigAlgoSz;
  5615. else
  5616. return OPAQUE16_LEN + sa->hashSigAlgoSz;
  5617. }
  5618. /* Creates a bit string of supported hash algorithms with RSA PSS.
  5619. * The bit string is used when determining which signature algorithm to use
  5620. * when creating the CertificateVerify message.
  5621. * Note: Valid data has an even length as each signature algorithm is two bytes.
  5622. *
  5623. * ssl The SSL/TLS object.
  5624. * input The buffer with the list of supported signature algorithms.
  5625. * length The length of the list in bytes.
  5626. * returns 0 on success, BUFFER_ERROR when the length is not even.
  5627. */
  5628. static int TLSX_SignatureAlgorithms_MapPss(WOLFSSL *ssl, const byte* input,
  5629. word16 length)
  5630. {
  5631. word16 i;
  5632. if ((length & 1) == 1)
  5633. return BUFFER_ERROR;
  5634. ssl->pssAlgo = 0;
  5635. for (i = 0; i < length; i += 2) {
  5636. if (input[i] == rsa_pss_sa_algo && input[i + 1] <= sha512_mac)
  5637. ssl->pssAlgo |= 1 << input[i + 1];
  5638. #ifdef WOLFSSL_TLS13
  5639. if (input[i] == rsa_pss_sa_algo && input[i + 1] >= pss_sha256 &&
  5640. input[i + 1] <= pss_sha512) {
  5641. ssl->pssAlgo |= 1 << input[i + 1];
  5642. }
  5643. #endif
  5644. }
  5645. return 0;
  5646. }
  5647. /* Writes the SignatureAlgorithms extension into the buffer.
  5648. *
  5649. * data Unused
  5650. * output The buffer to write the extension into.
  5651. * returns the length of data that was written.
  5652. */
  5653. static word16 TLSX_SignatureAlgorithms_Write(void* data, byte* output)
  5654. {
  5655. SignatureAlgorithms* sa = (SignatureAlgorithms*)data;
  5656. const Suites* suites = WOLFSSL_SUITES(sa->ssl);
  5657. word16 hashSigAlgoSz;
  5658. if (sa->hashSigAlgoSz == 0) {
  5659. c16toa(suites->hashSigAlgoSz, output);
  5660. XMEMCPY(output + OPAQUE16_LEN, suites->hashSigAlgo,
  5661. suites->hashSigAlgoSz);
  5662. hashSigAlgoSz = suites->hashSigAlgoSz;
  5663. }
  5664. else {
  5665. c16toa(sa->hashSigAlgoSz, output);
  5666. XMEMCPY(output + OPAQUE16_LEN, sa->hashSigAlgo,
  5667. sa->hashSigAlgoSz);
  5668. hashSigAlgoSz = sa->hashSigAlgoSz;
  5669. }
  5670. #ifndef NO_RSA
  5671. TLSX_SignatureAlgorithms_MapPss(sa->ssl, output + OPAQUE16_LEN,
  5672. hashSigAlgoSz);
  5673. #endif
  5674. return OPAQUE16_LEN + hashSigAlgoSz;
  5675. }
  5676. /* Parse the SignatureAlgorithms extension.
  5677. *
  5678. * ssl The SSL/TLS object.
  5679. * input The buffer with the extension data.
  5680. * length The length of the extension data.
  5681. * returns 0 on success, otherwise failure.
  5682. */
  5683. static int TLSX_SignatureAlgorithms_Parse(WOLFSSL *ssl, const byte* input,
  5684. word16 length, byte isRequest, Suites* suites)
  5685. {
  5686. word16 len;
  5687. if (!isRequest)
  5688. return BUFFER_ERROR;
  5689. /* Must contain a length and at least algorithm. */
  5690. if (length < OPAQUE16_LEN + OPAQUE16_LEN || (length & 1) != 0)
  5691. return BUFFER_ERROR;
  5692. ato16(input, &len);
  5693. input += OPAQUE16_LEN;
  5694. /* Algorithm array must fill rest of data. */
  5695. if (length != OPAQUE16_LEN + len)
  5696. return BUFFER_ERROR;
  5697. /* Sig Algo list size must be even. */
  5698. if (suites->hashSigAlgoSz % 2 != 0)
  5699. return BUFFER_ERROR;
  5700. /* truncate hashSigAlgo list if too long */
  5701. suites->hashSigAlgoSz = len;
  5702. if (suites->hashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  5703. WOLFSSL_MSG("TLSX SigAlgo list exceeds max, truncating");
  5704. suites->hashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  5705. }
  5706. XMEMCPY(suites->hashSigAlgo, input, suites->hashSigAlgoSz);
  5707. return TLSX_SignatureAlgorithms_MapPss(ssl, input, len);
  5708. }
  5709. /* Sets a new SignatureAlgorithms extension into the extension list.
  5710. *
  5711. * extensions The list of extensions.
  5712. * data The extensions specific data.
  5713. * heap The heap used for allocation.
  5714. * returns 0 on success, otherwise failure.
  5715. */
  5716. static int TLSX_SetSignatureAlgorithms(TLSX** extensions, WOLFSSL* ssl,
  5717. void* heap)
  5718. {
  5719. SignatureAlgorithms* sa;
  5720. int ret;
  5721. if (extensions == NULL)
  5722. return BAD_FUNC_ARG;
  5723. /* Already present */
  5724. if (TLSX_Find(*extensions, TLSX_SIGNATURE_ALGORITHMS) != NULL)
  5725. return 0;
  5726. sa = TLSX_SignatureAlgorithms_New(ssl, 0, heap);
  5727. if (sa == NULL)
  5728. return MEMORY_ERROR;
  5729. ret = TLSX_Push(extensions, TLSX_SIGNATURE_ALGORITHMS, sa, heap);
  5730. if (ret != 0)
  5731. TLSX_SignatureAlgorithms_FreeAll(sa, heap);
  5732. return ret;
  5733. }
  5734. SignatureAlgorithms* TLSX_SignatureAlgorithms_New(WOLFSSL* ssl,
  5735. word16 hashSigAlgoSz, void* heap)
  5736. {
  5737. SignatureAlgorithms* sa;
  5738. (void)heap;
  5739. sa = (SignatureAlgorithms*)XMALLOC(sizeof(*sa) + hashSigAlgoSz, heap,
  5740. DYNAMIC_TYPE_TLSX);
  5741. if (sa != NULL) {
  5742. XMEMSET(sa, 0, sizeof(*sa) + hashSigAlgoSz);
  5743. sa->ssl = ssl;
  5744. sa->hashSigAlgoSz = hashSigAlgoSz;
  5745. }
  5746. return sa;
  5747. }
  5748. void TLSX_SignatureAlgorithms_FreeAll(SignatureAlgorithms* sa,
  5749. void* heap)
  5750. {
  5751. XFREE(sa, heap, DYNAMIC_TYPE_TLSX);
  5752. (void)heap;
  5753. }
  5754. #define SA_GET_SIZE TLSX_SignatureAlgorithms_GetSize
  5755. #define SA_WRITE TLSX_SignatureAlgorithms_Write
  5756. #define SA_PARSE TLSX_SignatureAlgorithms_Parse
  5757. #define SA_FREE_ALL TLSX_SignatureAlgorithms_FreeAll
  5758. #endif
  5759. /******************************************************************************/
  5760. /* Signature Algorithms Certificate */
  5761. /******************************************************************************/
  5762. #if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  5763. /* Return the size of the SignatureAlgorithms extension's data.
  5764. *
  5765. * data Unused
  5766. * returns the length of data that will be in the extension.
  5767. */
  5768. static word16 TLSX_SignatureAlgorithmsCert_GetSize(void* data)
  5769. {
  5770. WOLFSSL* ssl = (WOLFSSL*)data;
  5771. return OPAQUE16_LEN + ssl->certHashSigAlgoSz;
  5772. }
  5773. /* Writes the SignatureAlgorithmsCert extension into the buffer.
  5774. *
  5775. * data Unused
  5776. * output The buffer to write the extension into.
  5777. * returns the length of data that was written.
  5778. */
  5779. static word16 TLSX_SignatureAlgorithmsCert_Write(void* data, byte* output)
  5780. {
  5781. WOLFSSL* ssl = (WOLFSSL*)data;
  5782. c16toa(ssl->certHashSigAlgoSz, output);
  5783. XMEMCPY(output + OPAQUE16_LEN, ssl->certHashSigAlgo,
  5784. ssl->certHashSigAlgoSz);
  5785. return OPAQUE16_LEN + ssl->certHashSigAlgoSz;
  5786. }
  5787. /* Parse the SignatureAlgorithmsCert extension.
  5788. *
  5789. * ssl The SSL/TLS object.
  5790. * input The buffer with the extension data.
  5791. * length The length of the extension data.
  5792. * returns 0 on success, otherwise failure.
  5793. */
  5794. static int TLSX_SignatureAlgorithmsCert_Parse(WOLFSSL *ssl, const byte* input,
  5795. word16 length, byte isRequest)
  5796. {
  5797. word16 len;
  5798. if (!isRequest)
  5799. return BUFFER_ERROR;
  5800. /* Must contain a length and at least algorithm. */
  5801. if (length < OPAQUE16_LEN + OPAQUE16_LEN || (length & 1) != 0)
  5802. return BUFFER_ERROR;
  5803. ato16(input, &len);
  5804. input += OPAQUE16_LEN;
  5805. /* Algorithm array must fill rest of data. */
  5806. if (length != OPAQUE16_LEN + len)
  5807. return BUFFER_ERROR;
  5808. /* truncate hashSigAlgo list if too long */
  5809. ssl->certHashSigAlgoSz = len;
  5810. if (ssl->certHashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  5811. WOLFSSL_MSG("TLSX SigAlgo list exceeds max, truncating");
  5812. ssl->certHashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  5813. }
  5814. XMEMCPY(ssl->certHashSigAlgo, input, ssl->certHashSigAlgoSz);
  5815. return 0;
  5816. }
  5817. /* Sets a new SignatureAlgorithmsCert extension into the extension list.
  5818. *
  5819. * extensions The list of extensions.
  5820. * data The extensions specific data.
  5821. * heap The heap used for allocation.
  5822. * returns 0 on success, otherwise failure.
  5823. */
  5824. static int TLSX_SetSignatureAlgorithmsCert(TLSX** extensions,
  5825. const WOLFSSL* data, void* heap)
  5826. {
  5827. if (extensions == NULL)
  5828. return BAD_FUNC_ARG;
  5829. return TLSX_Push(extensions, TLSX_SIGNATURE_ALGORITHMS_CERT, data, heap);
  5830. }
  5831. #define SAC_GET_SIZE TLSX_SignatureAlgorithmsCert_GetSize
  5832. #define SAC_WRITE TLSX_SignatureAlgorithmsCert_Write
  5833. #define SAC_PARSE TLSX_SignatureAlgorithmsCert_Parse
  5834. #endif /* WOLFSSL_TLS13 */
  5835. /******************************************************************************/
  5836. /* Key Share */
  5837. /******************************************************************************/
  5838. #if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
  5839. /* Create a key share entry using named Diffie-Hellman parameters group.
  5840. * Generates a key pair.
  5841. *
  5842. * ssl The SSL/TLS object.
  5843. * kse The key share entry object.
  5844. * returns 0 on success, otherwise failure.
  5845. */
  5846. static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse)
  5847. {
  5848. int ret = 0;
  5849. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  5850. word32 pSz = 0, pvtSz = 0;
  5851. DhKey* dhKey = (DhKey*)kse->key;
  5852. /* Pick the parameters from the named group. */
  5853. #ifdef HAVE_PUBLIC_FFDHE
  5854. const DhParams* params = NULL;
  5855. switch (kse->group) {
  5856. #ifdef HAVE_FFDHE_2048
  5857. case WOLFSSL_FFDHE_2048:
  5858. params = wc_Dh_ffdhe2048_Get();
  5859. pvtSz = 29;
  5860. break;
  5861. #endif
  5862. #ifdef HAVE_FFDHE_3072
  5863. case WOLFSSL_FFDHE_3072:
  5864. params = wc_Dh_ffdhe3072_Get();
  5865. pvtSz = 34;
  5866. break;
  5867. #endif
  5868. #ifdef HAVE_FFDHE_4096
  5869. case WOLFSSL_FFDHE_4096:
  5870. params = wc_Dh_ffdhe4096_Get();
  5871. pvtSz = 39;
  5872. break;
  5873. #endif
  5874. #ifdef HAVE_FFDHE_6144
  5875. case WOLFSSL_FFDHE_6144:
  5876. params = wc_Dh_ffdhe6144_Get();
  5877. pvtSz = 46;
  5878. break;
  5879. #endif
  5880. #ifdef HAVE_FFDHE_8192
  5881. case WOLFSSL_FFDHE_8192:
  5882. params = wc_Dh_ffdhe8192_Get();
  5883. pvtSz = 52;
  5884. break;
  5885. #endif
  5886. default:
  5887. break;
  5888. }
  5889. if (params == NULL)
  5890. return BAD_FUNC_ARG;
  5891. pSz = params->p_len;
  5892. #else
  5893. pvtSz = wc_DhGetNamedKeyMinSize(kse->group);
  5894. if (pvtSz == 0) {
  5895. return BAD_FUNC_ARG;
  5896. }
  5897. ret = wc_DhGetNamedKeyParamSize(kse->group, &pSz, NULL, NULL);
  5898. if (ret != 0) {
  5899. return BAD_FUNC_ARG;
  5900. }
  5901. #endif
  5902. /* Trigger Key Generation */
  5903. if (kse->pubKey == NULL || kse->privKey == NULL) {
  5904. if (kse->key == NULL) {
  5905. kse->key = (DhKey*)XMALLOC(sizeof(DhKey), ssl->heap,
  5906. DYNAMIC_TYPE_DH);
  5907. if (kse->key == NULL)
  5908. return MEMORY_E;
  5909. /* Setup Key */
  5910. ret = wc_InitDhKey_ex((DhKey*)kse->key, ssl->heap, ssl->devId);
  5911. if (ret == 0) {
  5912. dhKey = (DhKey*)kse->key;
  5913. #ifdef HAVE_PUBLIC_FFDHE
  5914. ret = wc_DhSetKey(dhKey, params->p, params->p_len, params->g,
  5915. params->g_len);
  5916. #else
  5917. ret = wc_DhSetNamedKey(dhKey, kse->group);
  5918. #endif
  5919. }
  5920. }
  5921. /* Allocate space for the private and public key */
  5922. if (ret == 0 && kse->pubKey == NULL) {
  5923. kse->pubKey = (byte*)XMALLOC(pSz, ssl->heap,
  5924. DYNAMIC_TYPE_PUBLIC_KEY);
  5925. if (kse->pubKey == NULL)
  5926. ret = MEMORY_E;
  5927. }
  5928. if (ret == 0 && kse->privKey == NULL) {
  5929. kse->privKey = (byte*)XMALLOC(pvtSz, ssl->heap,
  5930. DYNAMIC_TYPE_PRIVATE_KEY);
  5931. if (kse->privKey == NULL)
  5932. ret = MEMORY_E;
  5933. }
  5934. if (ret == 0) {
  5935. #if defined(WOLFSSL_STATIC_EPHEMERAL) && defined(WOLFSSL_DH_EXTRA)
  5936. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_DH, kse->key);
  5937. kse->pubKeyLen = pSz;
  5938. kse->keyLen = pvtSz;
  5939. if (ret == 0) {
  5940. ret = wc_DhExportKeyPair(dhKey,
  5941. (byte*)kse->privKey, &kse->keyLen, /* private */
  5942. kse->pubKey, &kse->pubKeyLen /* public */
  5943. );
  5944. }
  5945. else
  5946. #endif
  5947. {
  5948. /* Generate a new key pair */
  5949. /* For async this is called once and when event is done, the
  5950. * provided buffers will be populated.
  5951. * Final processing is zero pad below. */
  5952. kse->pubKeyLen = pSz;
  5953. kse->keyLen = pvtSz;
  5954. ret = DhGenKeyPair(ssl, dhKey,
  5955. (byte*)kse->privKey, &kse->keyLen, /* private */
  5956. kse->pubKey, &kse->pubKeyLen /* public */
  5957. );
  5958. #ifdef WOLFSSL_ASYNC_CRYPT
  5959. if (ret == WC_PENDING_E) {
  5960. return ret;
  5961. }
  5962. #endif
  5963. }
  5964. }
  5965. }
  5966. if (ret == 0) {
  5967. if (pSz != kse->pubKeyLen) {
  5968. /* Zero pad the front of the public key to match prime "p" size */
  5969. XMEMMOVE(kse->pubKey + pSz - kse->pubKeyLen, kse->pubKey,
  5970. kse->pubKeyLen);
  5971. XMEMSET(kse->pubKey, 0, pSz - kse->pubKeyLen);
  5972. kse->pubKeyLen = pSz;
  5973. }
  5974. if (pvtSz != kse->keyLen) {
  5975. /* Zero pad the front of the private key */
  5976. XMEMMOVE(kse->privKey + pvtSz - kse->keyLen, kse->privKey,
  5977. kse->keyLen);
  5978. XMEMSET(kse->privKey, 0, pvtSz - kse->keyLen);
  5979. kse->keyLen = pvtSz;
  5980. }
  5981. #ifdef WOLFSSL_DEBUG_TLS
  5982. WOLFSSL_MSG("Public DH Key");
  5983. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  5984. #endif
  5985. }
  5986. /* Always release the DH key to free up memory.
  5987. * The DhKey will be setup again in TLSX_KeyShare_ProcessDh */
  5988. if (dhKey != NULL)
  5989. wc_FreeDhKey(dhKey);
  5990. if (kse->key != NULL) {
  5991. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_DH);
  5992. kse->key = NULL;
  5993. }
  5994. if (ret != 0) {
  5995. /* Cleanup on error, otherwise data owned by key share entry */
  5996. if (kse->privKey != NULL) {
  5997. XFREE(kse->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  5998. kse->privKey = NULL;
  5999. }
  6000. if (kse->pubKey != NULL) {
  6001. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6002. kse->pubKey = NULL;
  6003. }
  6004. }
  6005. #else
  6006. (void)ssl;
  6007. (void)kse;
  6008. ret = NOT_COMPILED_IN;
  6009. WOLFSSL_ERROR_VERBOSE(ret);
  6010. #endif
  6011. return ret;
  6012. }
  6013. /* Create a key share entry using X25519 parameters group.
  6014. * Generates a key pair.
  6015. *
  6016. * ssl The SSL/TLS object.
  6017. * kse The key share entry object.
  6018. * returns 0 on success, otherwise failure.
  6019. */
  6020. static int TLSX_KeyShare_GenX25519Key(WOLFSSL *ssl, KeyShareEntry* kse)
  6021. {
  6022. int ret = 0;
  6023. #ifdef HAVE_CURVE25519
  6024. curve25519_key* key = (curve25519_key*)kse->key;
  6025. if (kse->key == NULL) {
  6026. /* Allocate a Curve25519 key to hold private key. */
  6027. kse->key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), ssl->heap,
  6028. DYNAMIC_TYPE_PRIVATE_KEY);
  6029. if (kse->key == NULL) {
  6030. WOLFSSL_MSG("GenX25519Key memory error");
  6031. return MEMORY_E;
  6032. }
  6033. /* Make an Curve25519 key. */
  6034. ret = wc_curve25519_init_ex((curve25519_key*)kse->key, ssl->heap,
  6035. INVALID_DEVID);
  6036. if (ret == 0) {
  6037. /* setting "key" means okay to call wc_curve25519_free */
  6038. key = (curve25519_key*)kse->key;
  6039. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6040. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE25519, kse->key);
  6041. if (ret != 0)
  6042. #endif
  6043. {
  6044. ret = wc_curve25519_make_key(ssl->rng, CURVE25519_KEYSIZE, key);
  6045. }
  6046. }
  6047. }
  6048. if (ret == 0 && kse->pubKey == NULL) {
  6049. /* Allocate space for the public key. */
  6050. kse->pubKey = (byte*)XMALLOC(CURVE25519_KEYSIZE, ssl->heap,
  6051. DYNAMIC_TYPE_PUBLIC_KEY);
  6052. if (kse->pubKey == NULL) {
  6053. WOLFSSL_MSG("GenX25519Key pub memory error");
  6054. ret = MEMORY_E;
  6055. }
  6056. }
  6057. if (ret == 0) {
  6058. /* Export Curve25519 public key. */
  6059. kse->pubKeyLen = CURVE25519_KEYSIZE;
  6060. if (wc_curve25519_export_public_ex(key, kse->pubKey, &kse->pubKeyLen,
  6061. EC25519_LITTLE_ENDIAN) != 0) {
  6062. ret = ECC_EXPORT_ERROR;
  6063. WOLFSSL_ERROR_VERBOSE(ret);
  6064. }
  6065. kse->pubKeyLen = CURVE25519_KEYSIZE; /* always CURVE25519_KEYSIZE */
  6066. }
  6067. #ifdef WOLFSSL_DEBUG_TLS
  6068. if (ret == 0) {
  6069. WOLFSSL_MSG("Public Curve25519 Key");
  6070. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6071. }
  6072. #endif
  6073. if (ret != 0) {
  6074. /* Data owned by key share entry otherwise. */
  6075. if (kse->pubKey != NULL) {
  6076. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6077. kse->pubKey = NULL;
  6078. }
  6079. if (key != NULL)
  6080. wc_curve25519_free(key);
  6081. if (kse->key != NULL) {
  6082. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6083. kse->key = NULL;
  6084. }
  6085. }
  6086. #else
  6087. (void)ssl;
  6088. (void)kse;
  6089. ret = NOT_COMPILED_IN;
  6090. WOLFSSL_ERROR_VERBOSE(ret);
  6091. #endif /* HAVE_CURVE25519 */
  6092. return ret;
  6093. }
  6094. /* Create a key share entry using X448 parameters group.
  6095. * Generates a key pair.
  6096. *
  6097. * ssl The SSL/TLS object.
  6098. * kse The key share entry object.
  6099. * returns 0 on success, otherwise failure.
  6100. */
  6101. static int TLSX_KeyShare_GenX448Key(WOLFSSL *ssl, KeyShareEntry* kse)
  6102. {
  6103. int ret = 0;
  6104. #ifdef HAVE_CURVE448
  6105. curve448_key* key = (curve448_key*)kse->key;
  6106. if (kse->key == NULL) {
  6107. /* Allocate a Curve448 key to hold private key. */
  6108. kse->key = (curve448_key*)XMALLOC(sizeof(curve448_key), ssl->heap,
  6109. DYNAMIC_TYPE_PRIVATE_KEY);
  6110. if (kse->key == NULL) {
  6111. WOLFSSL_MSG("GenX448Key memory error");
  6112. return MEMORY_E;
  6113. }
  6114. /* Make an Curve448 key. */
  6115. ret = wc_curve448_init((curve448_key*)kse->key);
  6116. if (ret == 0) {
  6117. key = (curve448_key*)kse->key;
  6118. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6119. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE448, kse->key);
  6120. if (ret != 0)
  6121. #endif
  6122. {
  6123. ret = wc_curve448_make_key(ssl->rng, CURVE448_KEY_SIZE, key);
  6124. }
  6125. }
  6126. }
  6127. if (ret == 0 && kse->pubKey == NULL) {
  6128. /* Allocate space for the public key. */
  6129. kse->pubKey = (byte*)XMALLOC(CURVE448_KEY_SIZE, ssl->heap,
  6130. DYNAMIC_TYPE_PUBLIC_KEY);
  6131. if (kse->pubKey == NULL) {
  6132. WOLFSSL_MSG("GenX448Key pub memory error");
  6133. ret = MEMORY_E;
  6134. }
  6135. }
  6136. if (ret == 0) {
  6137. /* Export Curve448 public key. */
  6138. kse->pubKeyLen = CURVE448_KEY_SIZE;
  6139. if (wc_curve448_export_public_ex(key, kse->pubKey, &kse->pubKeyLen,
  6140. EC448_LITTLE_ENDIAN) != 0) {
  6141. ret = ECC_EXPORT_ERROR;
  6142. }
  6143. kse->pubKeyLen = CURVE448_KEY_SIZE; /* always CURVE448_KEY_SIZE */
  6144. }
  6145. #ifdef WOLFSSL_DEBUG_TLS
  6146. if (ret == 0) {
  6147. WOLFSSL_MSG("Public Curve448 Key");
  6148. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6149. }
  6150. #endif
  6151. if (ret != 0) {
  6152. /* Data owned by key share entry otherwise. */
  6153. if (kse->pubKey != NULL) {
  6154. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6155. kse->pubKey = NULL;
  6156. }
  6157. if (key != NULL)
  6158. wc_curve448_free(key);
  6159. if (kse->key != NULL) {
  6160. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6161. kse->key = NULL;
  6162. }
  6163. }
  6164. #else
  6165. (void)ssl;
  6166. (void)kse;
  6167. ret = NOT_COMPILED_IN;
  6168. WOLFSSL_ERROR_VERBOSE(ret);
  6169. #endif /* HAVE_CURVE448 */
  6170. return ret;
  6171. }
  6172. /* Create a key share entry using named elliptic curve parameters group.
  6173. * Generates a key pair.
  6174. *
  6175. * ssl The SSL/TLS object.
  6176. * kse The key share entry object.
  6177. * returns 0 on success, otherwise failure.
  6178. */
  6179. static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse)
  6180. {
  6181. int ret = 0;
  6182. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  6183. word32 keySize = 0;
  6184. word16 curveId = (word16) ECC_CURVE_INVALID;
  6185. ecc_key* eccKey = (ecc_key*)kse->key;
  6186. /* TODO: [TLS13] The key sizes should come from wolfcrypt. */
  6187. /* Translate named group to a curve id. */
  6188. switch (kse->group) {
  6189. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  6190. #ifndef NO_ECC_SECP
  6191. case WOLFSSL_ECC_SECP256R1:
  6192. curveId = ECC_SECP256R1;
  6193. keySize = 32;
  6194. break;
  6195. #endif /* !NO_ECC_SECP */
  6196. #ifdef WOLFSSL_SM2
  6197. case WOLFSSL_ECC_SM2P256V1:
  6198. curveId = ECC_SM2P256V1;
  6199. keySize = 32;
  6200. break;
  6201. #endif /* !NO_ECC_SECP */
  6202. #endif
  6203. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  6204. #ifndef NO_ECC_SECP
  6205. case WOLFSSL_ECC_SECP384R1:
  6206. curveId = ECC_SECP384R1;
  6207. keySize = 48;
  6208. break;
  6209. #endif /* !NO_ECC_SECP */
  6210. #endif
  6211. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  6212. #ifndef NO_ECC_SECP
  6213. case WOLFSSL_ECC_SECP521R1:
  6214. curveId = ECC_SECP521R1;
  6215. keySize = 66;
  6216. break;
  6217. #endif /* !NO_ECC_SECP */
  6218. #endif
  6219. default:
  6220. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  6221. return BAD_FUNC_ARG;
  6222. }
  6223. if (kse->key == NULL) {
  6224. kse->keyLen = keySize;
  6225. kse->pubKeyLen = keySize * 2 + 1;
  6226. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  6227. ret = tsip_Tls13GenEccKeyPair(ssl, kse);
  6228. if (ret != CRYPTOCB_UNAVAILABLE) {
  6229. return ret;
  6230. }
  6231. #endif
  6232. /* Allocate an ECC key to hold private key. */
  6233. kse->key = (byte*)XMALLOC(sizeof(ecc_key), ssl->heap, DYNAMIC_TYPE_ECC);
  6234. if (kse->key == NULL) {
  6235. WOLFSSL_MSG("EccTempKey Memory error");
  6236. return MEMORY_E;
  6237. }
  6238. /* Make an ECC key */
  6239. ret = wc_ecc_init_ex((ecc_key*)kse->key, ssl->heap, ssl->devId);
  6240. if (ret == 0) {
  6241. /* setting eccKey means okay to call wc_ecc_free */
  6242. eccKey = (ecc_key*)kse->key;
  6243. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6244. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_ECDH, kse->key);
  6245. if (ret != 0)
  6246. #endif
  6247. {
  6248. /* set curve info for EccMakeKey "peer" info */
  6249. ret = wc_ecc_set_curve(eccKey, kse->keyLen, curveId);
  6250. if (ret == 0) {
  6251. /* Generate ephemeral ECC key */
  6252. /* For async this is called once and when event is done, the
  6253. * provided buffers in key be populated.
  6254. * Final processing is x963 key export below. */
  6255. ret = EccMakeKey(ssl, eccKey, eccKey);
  6256. }
  6257. #ifdef WOLFSSL_ASYNC_CRYPT
  6258. if (ret == WC_PENDING_E)
  6259. return ret;
  6260. #endif
  6261. }
  6262. }
  6263. }
  6264. if (ret == 0 && kse->pubKey == NULL) {
  6265. /* Allocate space for the public key */
  6266. kse->pubKey = (byte*)XMALLOC(kse->pubKeyLen, ssl->heap,
  6267. DYNAMIC_TYPE_PUBLIC_KEY);
  6268. if (kse->pubKey == NULL) {
  6269. WOLFSSL_MSG("Key data Memory error");
  6270. ret = MEMORY_E;
  6271. }
  6272. }
  6273. if (ret == 0) {
  6274. XMEMSET(kse->pubKey, 0, kse->pubKeyLen);
  6275. /* Export public key. */
  6276. PRIVATE_KEY_UNLOCK();
  6277. if (wc_ecc_export_x963(eccKey, kse->pubKey, &kse->pubKeyLen) != 0) {
  6278. ret = ECC_EXPORT_ERROR;
  6279. WOLFSSL_ERROR_VERBOSE(ret);
  6280. }
  6281. PRIVATE_KEY_LOCK();
  6282. }
  6283. #ifdef WOLFSSL_DEBUG_TLS
  6284. if (ret == 0) {
  6285. WOLFSSL_MSG("Public ECC Key");
  6286. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6287. }
  6288. #endif
  6289. if (ret != 0) {
  6290. /* Cleanup on error, otherwise data owned by key share entry */
  6291. if (kse->pubKey != NULL) {
  6292. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6293. kse->pubKey = NULL;
  6294. }
  6295. if (eccKey != NULL)
  6296. wc_ecc_free(eccKey);
  6297. if (kse->key != NULL) {
  6298. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6299. kse->key = NULL;
  6300. }
  6301. }
  6302. #else
  6303. (void)ssl;
  6304. (void)kse;
  6305. ret = NOT_COMPILED_IN;
  6306. WOLFSSL_ERROR_VERBOSE(ret);
  6307. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  6308. return ret;
  6309. }
  6310. #ifdef HAVE_PQC
  6311. static int kyber_id2type(int id, int *type)
  6312. {
  6313. int ret = 0;
  6314. switch (id) {
  6315. #ifdef WOLFSSL_KYBER512
  6316. case WOLFSSL_KYBER_LEVEL1:
  6317. *type = KYBER512;
  6318. break;
  6319. #endif
  6320. #ifdef WOLFSSL_KYBER768
  6321. case WOLFSSL_KYBER_LEVEL3:
  6322. *type = KYBER768;
  6323. break;
  6324. #endif
  6325. #ifdef WOLFSSL_KYBER1024
  6326. case WOLFSSL_KYBER_LEVEL5:
  6327. *type = KYBER1024;
  6328. break;
  6329. #endif
  6330. default:
  6331. ret = NOT_COMPILED_IN;
  6332. break;
  6333. }
  6334. return ret;
  6335. }
  6336. typedef struct PqcHybridMapping {
  6337. int hybrid;
  6338. int ecc;
  6339. int pqc;
  6340. } PqcHybridMapping;
  6341. static const PqcHybridMapping pqc_hybrid_mapping[] = {
  6342. {.hybrid = WOLFSSL_P256_KYBER_LEVEL1, .ecc = WOLFSSL_ECC_SECP256R1,
  6343. .pqc = WOLFSSL_KYBER_LEVEL1},
  6344. {.hybrid = WOLFSSL_P384_KYBER_LEVEL3, .ecc = WOLFSSL_ECC_SECP384R1,
  6345. .pqc = WOLFSSL_KYBER_LEVEL3},
  6346. {.hybrid = WOLFSSL_P521_KYBER_LEVEL5, .ecc = WOLFSSL_ECC_SECP521R1,
  6347. .pqc = WOLFSSL_KYBER_LEVEL5},
  6348. {.hybrid = 0, .ecc = 0, .pqc = 0}
  6349. };
  6350. /* This will map an ecc-pqs hybrid group into its ecc group and pqc kem group.
  6351. * If it cannot find a mapping then *pqc is set to group. ecc is optional. */
  6352. static void findEccPqc(int *ecc, int *pqc, int group)
  6353. {
  6354. int i;
  6355. if (pqc == NULL) {
  6356. return;
  6357. }
  6358. *pqc = 0;
  6359. if (ecc != NULL) {
  6360. *ecc = 0;
  6361. }
  6362. for (i = 0; pqc_hybrid_mapping[i].hybrid != 0; i++) {
  6363. if (pqc_hybrid_mapping[i].hybrid == group) {
  6364. *pqc = pqc_hybrid_mapping[i].pqc;
  6365. if (ecc != NULL) {
  6366. *ecc = pqc_hybrid_mapping[i].ecc;
  6367. }
  6368. break;
  6369. }
  6370. }
  6371. if (*pqc == 0) {
  6372. /* It is not a hybrid, so maybe its simple. */
  6373. *pqc = group;
  6374. }
  6375. }
  6376. /* Create a key share entry using liboqs parameters group.
  6377. * Generates a key pair.
  6378. *
  6379. * ssl The SSL/TLS object.
  6380. * kse The key share entry object.
  6381. * returns 0 on success, otherwise failure.
  6382. */
  6383. static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse)
  6384. {
  6385. int ret = 0;
  6386. int type = 0;
  6387. KyberKey kem[1];
  6388. byte* pubKey = NULL;
  6389. byte* privKey = NULL;
  6390. KeyShareEntry *ecc_kse = NULL;
  6391. int oqs_group = 0;
  6392. int ecc_group = 0;
  6393. word32 privSz = 0;
  6394. word32 pubSz = 0;
  6395. findEccPqc(&ecc_group, &oqs_group, kse->group);
  6396. ret = kyber_id2type(oqs_group, &type);
  6397. if (ret == NOT_COMPILED_IN) {
  6398. WOLFSSL_MSG("Invalid Kyber algorithm specified.");
  6399. ret = BAD_FUNC_ARG;
  6400. }
  6401. if (ret == 0) {
  6402. ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId);
  6403. if (ret != 0) {
  6404. WOLFSSL_MSG("Failed to initialize Kyber Key.");
  6405. }
  6406. }
  6407. if (ret == 0) {
  6408. ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap,
  6409. DYNAMIC_TYPE_TLSX);
  6410. if (ecc_kse == NULL) {
  6411. WOLFSSL_MSG("ecc_kse memory allocation failure");
  6412. ret = MEMORY_ERROR;
  6413. }
  6414. }
  6415. if (ret == 0) {
  6416. XMEMSET(ecc_kse, 0, sizeof(*ecc_kse));
  6417. ret = wc_KyberKey_PrivateKeySize(kem, &privSz);
  6418. }
  6419. if (ret == 0) {
  6420. ret = wc_KyberKey_PublicKeySize(kem, &pubSz);
  6421. }
  6422. if (ret == 0 && ecc_group != 0) {
  6423. ecc_kse->group = ecc_group;
  6424. ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse);
  6425. /* If fail, no error message, TLSX_KeyShare_GenEccKey will do it. */
  6426. }
  6427. if (ret == 0) {
  6428. pubKey = (byte*)XMALLOC(ecc_kse->pubKeyLen + pubSz, ssl->heap,
  6429. DYNAMIC_TYPE_PUBLIC_KEY);
  6430. if (pubKey == NULL) {
  6431. WOLFSSL_MSG("pubkey memory allocation failure");
  6432. ret = MEMORY_ERROR;
  6433. }
  6434. }
  6435. if (ret == 0) {
  6436. privKey = (byte*)XMALLOC(privSz, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6437. if (privKey == NULL) {
  6438. WOLFSSL_MSG("privkey memory allocation failure");
  6439. ret = MEMORY_ERROR;
  6440. }
  6441. }
  6442. if (ret == 0) {
  6443. ret = wc_KyberKey_MakeKey(kem, ssl->rng);
  6444. if (ret != 0) {
  6445. WOLFSSL_MSG("Kyber keygen failure");
  6446. }
  6447. }
  6448. if (ret == 0) {
  6449. ret = wc_KyberKey_EncodePublicKey(kem, pubKey + ecc_kse->pubKeyLen,
  6450. pubSz);
  6451. }
  6452. if (ret == 0) {
  6453. ret = wc_KyberKey_EncodePrivateKey(kem, privKey, privSz);
  6454. }
  6455. if (ret == 0) {
  6456. XMEMCPY(pubKey, ecc_kse->pubKey, ecc_kse->pubKeyLen);
  6457. kse->pubKey = pubKey;
  6458. kse->pubKeyLen = ecc_kse->pubKeyLen + pubSz;
  6459. pubKey = NULL;
  6460. /* Note we are saving the OQS private key and ECC private key
  6461. * separately. That's because the ECC private key is not simply a
  6462. * buffer. Its is an ecc_key struct.
  6463. */
  6464. kse->privKey = privKey;
  6465. privKey = NULL;
  6466. kse->key = ecc_kse->key;
  6467. ecc_kse->key = NULL;
  6468. }
  6469. #ifdef WOLFSSL_DEBUG_TLS
  6470. WOLFSSL_MSG("Public Kyber Key");
  6471. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen );
  6472. #endif
  6473. wc_KyberKey_Free(kem);
  6474. TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap);
  6475. if (pubKey != NULL)
  6476. XFREE(pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6477. if (privKey != NULL)
  6478. XFREE(privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6479. return ret;
  6480. }
  6481. #endif /* HAVE_PQC */
  6482. /* Generate a secret/key using the key share entry.
  6483. *
  6484. * ssl The SSL/TLS object.
  6485. * kse The key share entry holding peer data.
  6486. */
  6487. int TLSX_KeyShare_GenKey(WOLFSSL *ssl, KeyShareEntry *kse)
  6488. {
  6489. int ret;
  6490. /* Named FFDHE groups have a bit set to identify them. */
  6491. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(kse->group))
  6492. ret = TLSX_KeyShare_GenDhKey(ssl, kse);
  6493. else if (kse->group == WOLFSSL_ECC_X25519)
  6494. ret = TLSX_KeyShare_GenX25519Key(ssl, kse);
  6495. else if (kse->group == WOLFSSL_ECC_X448)
  6496. ret = TLSX_KeyShare_GenX448Key(ssl, kse);
  6497. #ifdef HAVE_PQC
  6498. else if (WOLFSSL_NAMED_GROUP_IS_PQC(kse->group))
  6499. ret = TLSX_KeyShare_GenPqcKey(ssl, kse);
  6500. #endif
  6501. else
  6502. ret = TLSX_KeyShare_GenEccKey(ssl, kse);
  6503. #ifdef WOLFSSL_ASYNC_CRYPT
  6504. kse->lastRet = ret;
  6505. #endif
  6506. return ret;
  6507. }
  6508. /* Free the key share dynamic data.
  6509. *
  6510. * list The linked list of key share entry objects.
  6511. * heap The heap used for allocation.
  6512. */
  6513. static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap)
  6514. {
  6515. KeyShareEntry* current;
  6516. while ((current = list) != NULL) {
  6517. list = current->next;
  6518. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(current->group)) {
  6519. #ifndef NO_DH
  6520. wc_FreeDhKey((DhKey*)current->key);
  6521. #endif
  6522. }
  6523. else if (current->group == WOLFSSL_ECC_X25519) {
  6524. #ifdef HAVE_CURVE25519
  6525. wc_curve25519_free((curve25519_key*)current->key);
  6526. #endif
  6527. }
  6528. else if (current->group == WOLFSSL_ECC_X448) {
  6529. #ifdef HAVE_CURVE448
  6530. wc_curve448_free((curve448_key*)current->key);
  6531. #endif
  6532. }
  6533. #ifdef HAVE_PQC
  6534. else if (WOLFSSL_NAMED_GROUP_IS_PQC(current->group) &&
  6535. current->key != NULL) {
  6536. ForceZero((byte*)current->key, current->keyLen);
  6537. }
  6538. #endif
  6539. else {
  6540. #ifdef HAVE_ECC
  6541. wc_ecc_free((ecc_key*)current->key);
  6542. #endif
  6543. }
  6544. XFREE(current->key, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6545. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  6546. XFREE(current->privKey, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6547. #endif
  6548. XFREE(current->pubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6549. XFREE(current->ke, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6550. XFREE(current, heap, DYNAMIC_TYPE_TLSX);
  6551. }
  6552. (void)heap;
  6553. }
  6554. /* Get the size of the encoded key share extension.
  6555. *
  6556. * list The linked list of key share extensions.
  6557. * msgType The type of the message this extension is being written into.
  6558. * returns the number of bytes of the encoded key share extension.
  6559. */
  6560. static word16 TLSX_KeyShare_GetSize(KeyShareEntry* list, byte msgType)
  6561. {
  6562. word16 len = 0;
  6563. byte isRequest = (msgType == client_hello);
  6564. KeyShareEntry* current;
  6565. /* The named group the server wants to use. */
  6566. if (msgType == hello_retry_request)
  6567. return OPAQUE16_LEN;
  6568. /* List of key exchange groups. */
  6569. if (isRequest)
  6570. len += OPAQUE16_LEN;
  6571. while ((current = list) != NULL) {
  6572. list = current->next;
  6573. if (!isRequest && current->pubKey == NULL)
  6574. continue;
  6575. len += (word16)(KE_GROUP_LEN + OPAQUE16_LEN + current->pubKeyLen);
  6576. }
  6577. return len;
  6578. }
  6579. /* Writes the key share extension into the output buffer.
  6580. * Assumes that the the output buffer is big enough to hold data.
  6581. *
  6582. * list The linked list of key share entries.
  6583. * output The buffer to write into.
  6584. * msgType The type of the message this extension is being written into.
  6585. * returns the number of bytes written into the buffer.
  6586. */
  6587. static word16 TLSX_KeyShare_Write(KeyShareEntry* list, byte* output,
  6588. byte msgType)
  6589. {
  6590. word16 i = 0;
  6591. byte isRequest = (msgType == client_hello);
  6592. KeyShareEntry* current;
  6593. if (msgType == hello_retry_request) {
  6594. c16toa(list->group, output);
  6595. return OPAQUE16_LEN;
  6596. }
  6597. /* ClientHello has a list but ServerHello is only the chosen. */
  6598. if (isRequest)
  6599. i += OPAQUE16_LEN;
  6600. /* Write out all in the list. */
  6601. while ((current = list) != NULL) {
  6602. list = current->next;
  6603. if (!isRequest && current->pubKey == NULL)
  6604. continue;
  6605. c16toa(current->group, &output[i]);
  6606. i += KE_GROUP_LEN;
  6607. c16toa((word16)(current->pubKeyLen), &output[i]);
  6608. i += OPAQUE16_LEN;
  6609. XMEMCPY(&output[i], current->pubKey, current->pubKeyLen);
  6610. i += (word16)current->pubKeyLen;
  6611. }
  6612. /* Write the length of the list if required. */
  6613. if (isRequest)
  6614. c16toa(i - OPAQUE16_LEN, output);
  6615. return i;
  6616. }
  6617. /* Process the DH key share extension on the client side.
  6618. *
  6619. * ssl The SSL/TLS object.
  6620. * keyShareEntry The key share entry object to use to calculate shared secret.
  6621. * returns 0 on success and other values indicate failure.
  6622. */
  6623. static int TLSX_KeyShare_ProcessDh(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6624. {
  6625. int ret = 0;
  6626. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  6627. word32 pSz = 0;
  6628. DhKey* dhKey = (DhKey*)keyShareEntry->key;
  6629. #ifdef HAVE_PUBLIC_FFDHE
  6630. const DhParams* params = NULL;
  6631. switch (keyShareEntry->group) {
  6632. #ifdef HAVE_FFDHE_2048
  6633. case WOLFSSL_FFDHE_2048:
  6634. params = wc_Dh_ffdhe2048_Get();
  6635. break;
  6636. #endif
  6637. #ifdef HAVE_FFDHE_3072
  6638. case WOLFSSL_FFDHE_3072:
  6639. params = wc_Dh_ffdhe3072_Get();
  6640. break;
  6641. #endif
  6642. #ifdef HAVE_FFDHE_4096
  6643. case WOLFSSL_FFDHE_4096:
  6644. params = wc_Dh_ffdhe4096_Get();
  6645. break;
  6646. #endif
  6647. #ifdef HAVE_FFDHE_6144
  6648. case WOLFSSL_FFDHE_6144:
  6649. params = wc_Dh_ffdhe6144_Get();
  6650. break;
  6651. #endif
  6652. #ifdef HAVE_FFDHE_8192
  6653. case WOLFSSL_FFDHE_8192:
  6654. params = wc_Dh_ffdhe8192_Get();
  6655. break;
  6656. #endif
  6657. default:
  6658. break;
  6659. }
  6660. if (params == NULL) {
  6661. WOLFSSL_ERROR_VERBOSE(PEER_KEY_ERROR);
  6662. return PEER_KEY_ERROR;
  6663. }
  6664. pSz = params->p_len;
  6665. #else
  6666. ret = wc_DhGetNamedKeyParamSize(keyShareEntry->group, &pSz, NULL, NULL);
  6667. if (ret != 0 || pSz == 0) {
  6668. WOLFSSL_ERROR_VERBOSE(PEER_KEY_ERROR);
  6669. return PEER_KEY_ERROR;
  6670. }
  6671. #endif
  6672. /* if DhKey is not setup, do it now */
  6673. if (keyShareEntry->key == NULL) {
  6674. keyShareEntry->key = (DhKey*)XMALLOC(sizeof(DhKey), ssl->heap,
  6675. DYNAMIC_TYPE_DH);
  6676. if (keyShareEntry->key == NULL)
  6677. return MEMORY_E;
  6678. /* Setup Key */
  6679. ret = wc_InitDhKey_ex((DhKey*)keyShareEntry->key, ssl->heap, ssl->devId);
  6680. if (ret == 0) {
  6681. dhKey = (DhKey*)keyShareEntry->key;
  6682. /* Set key */
  6683. #ifdef HAVE_PUBLIC_FFDHE
  6684. ret = wc_DhSetKey(dhKey, params->p, params->p_len, params->g,
  6685. params->g_len);
  6686. #else
  6687. ret = wc_DhSetNamedKey(dhKey, keyShareEntry->group);
  6688. #endif
  6689. }
  6690. }
  6691. if (ret == 0
  6692. #ifdef WOLFSSL_ASYNC_CRYPT
  6693. && keyShareEntry->lastRet == 0 /* don't enter here if WC_PENDING_E */
  6694. #endif
  6695. ) {
  6696. #ifdef WOLFSSL_DEBUG_TLS
  6697. WOLFSSL_MSG("Peer DH Key");
  6698. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6699. #endif
  6700. ssl->options.dhKeySz = (word16)pSz;
  6701. /* Derive secret from private key and peer's public key. */
  6702. ret = DhAgree(ssl, dhKey,
  6703. (const byte*)keyShareEntry->privKey, keyShareEntry->keyLen, /* our private */
  6704. keyShareEntry->ke, keyShareEntry->keLen, /* peer's public key */
  6705. ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz, /* secret */
  6706. NULL, 0
  6707. );
  6708. #ifdef WOLFSSL_ASYNC_CRYPT
  6709. if (ret == WC_PENDING_E) {
  6710. return ret;
  6711. }
  6712. #endif
  6713. }
  6714. /* RFC 8446 Section 7.4.1:
  6715. * ... left-padded with zeros up to the size of the prime. ...
  6716. */
  6717. if (ret == 0 && (word32)ssl->options.dhKeySz > ssl->arrays->preMasterSz) {
  6718. word32 diff = (word32)ssl->options.dhKeySz - ssl->arrays->preMasterSz;
  6719. XMEMMOVE(ssl->arrays->preMasterSecret + diff,
  6720. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  6721. XMEMSET(ssl->arrays->preMasterSecret, 0, diff);
  6722. ssl->arrays->preMasterSz = ssl->options.dhKeySz;
  6723. }
  6724. /* done with key share, release resources */
  6725. if (dhKey)
  6726. wc_FreeDhKey(dhKey);
  6727. if (keyShareEntry->key) {
  6728. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_DH);
  6729. keyShareEntry->key = NULL;
  6730. }
  6731. if (keyShareEntry->privKey != NULL) {
  6732. XFREE(keyShareEntry->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6733. keyShareEntry->privKey = NULL;
  6734. }
  6735. if (keyShareEntry->pubKey != NULL) {
  6736. XFREE(keyShareEntry->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6737. keyShareEntry->pubKey = NULL;
  6738. }
  6739. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6740. keyShareEntry->ke = NULL;
  6741. #else
  6742. (void)ssl;
  6743. (void)keyShareEntry;
  6744. ret = PEER_KEY_ERROR;
  6745. WOLFSSL_ERROR_VERBOSE(ret);
  6746. #endif
  6747. return ret;
  6748. }
  6749. /* Process the X25519 key share extension on the client side.
  6750. *
  6751. * ssl The SSL/TLS object.
  6752. * keyShareEntry The key share entry object to use to calculate shared secret.
  6753. * returns 0 on success and other values indicate failure.
  6754. */
  6755. static int TLSX_KeyShare_ProcessX25519(WOLFSSL* ssl,
  6756. KeyShareEntry* keyShareEntry)
  6757. {
  6758. int ret;
  6759. #ifdef HAVE_CURVE25519
  6760. curve25519_key* key = (curve25519_key*)keyShareEntry->key;
  6761. curve25519_key* peerX25519Key;
  6762. #ifdef HAVE_ECC
  6763. if (ssl->peerEccKey != NULL) {
  6764. wc_ecc_free(ssl->peerEccKey);
  6765. ssl->peerEccKey = NULL;
  6766. ssl->peerEccKeyPresent = 0;
  6767. }
  6768. #endif
  6769. peerX25519Key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), ssl->heap,
  6770. DYNAMIC_TYPE_TLSX);
  6771. if (peerX25519Key == NULL) {
  6772. WOLFSSL_MSG("PeerEccKey Memory error");
  6773. return MEMORY_ERROR;
  6774. }
  6775. ret = wc_curve25519_init(peerX25519Key);
  6776. if (ret != 0) {
  6777. XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6778. return ret;
  6779. }
  6780. #ifdef WOLFSSL_DEBUG_TLS
  6781. WOLFSSL_MSG("Peer Curve25519 Key");
  6782. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6783. #endif
  6784. if (wc_curve25519_check_public(keyShareEntry->ke, keyShareEntry->keLen,
  6785. EC25519_LITTLE_ENDIAN) != 0) {
  6786. ret = ECC_PEERKEY_ERROR;
  6787. WOLFSSL_ERROR_VERBOSE(ret);
  6788. }
  6789. if (ret == 0) {
  6790. if (wc_curve25519_import_public_ex(keyShareEntry->ke,
  6791. keyShareEntry->keLen, peerX25519Key,
  6792. EC25519_LITTLE_ENDIAN) != 0) {
  6793. ret = ECC_PEERKEY_ERROR;
  6794. WOLFSSL_ERROR_VERBOSE(ret);
  6795. }
  6796. }
  6797. if (ret == 0) {
  6798. ssl->ecdhCurveOID = ECC_X25519_OID;
  6799. ret = wc_curve25519_shared_secret_ex(key, peerX25519Key,
  6800. ssl->arrays->preMasterSecret,
  6801. &ssl->arrays->preMasterSz,
  6802. EC25519_LITTLE_ENDIAN);
  6803. }
  6804. wc_curve25519_free(peerX25519Key);
  6805. XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6806. wc_curve25519_free((curve25519_key*)keyShareEntry->key);
  6807. if (keyShareEntry->key != NULL) {
  6808. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6809. keyShareEntry->key = NULL;
  6810. }
  6811. #else
  6812. (void)ssl;
  6813. (void)keyShareEntry;
  6814. ret = PEER_KEY_ERROR;
  6815. WOLFSSL_ERROR_VERBOSE(ret);
  6816. #endif /* HAVE_CURVE25519 */
  6817. return ret;
  6818. }
  6819. /* Process the X448 key share extension on the client side.
  6820. *
  6821. * ssl The SSL/TLS object.
  6822. * keyShareEntry The key share entry object to use to calculate shared secret.
  6823. * returns 0 on success and other values indicate failure.
  6824. */
  6825. static int TLSX_KeyShare_ProcessX448(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6826. {
  6827. int ret;
  6828. #ifdef HAVE_CURVE448
  6829. curve448_key* key = (curve448_key*)keyShareEntry->key;
  6830. curve448_key* peerX448Key;
  6831. #ifdef HAVE_ECC
  6832. if (ssl->peerEccKey != NULL) {
  6833. wc_ecc_free(ssl->peerEccKey);
  6834. ssl->peerEccKey = NULL;
  6835. ssl->peerEccKeyPresent = 0;
  6836. }
  6837. #endif
  6838. peerX448Key = (curve448_key*)XMALLOC(sizeof(curve448_key), ssl->heap,
  6839. DYNAMIC_TYPE_TLSX);
  6840. if (peerX448Key == NULL) {
  6841. WOLFSSL_MSG("PeerEccKey Memory error");
  6842. return MEMORY_ERROR;
  6843. }
  6844. ret = wc_curve448_init(peerX448Key);
  6845. if (ret != 0) {
  6846. XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6847. return ret;
  6848. }
  6849. #ifdef WOLFSSL_DEBUG_TLS
  6850. WOLFSSL_MSG("Peer Curve448 Key");
  6851. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6852. #endif
  6853. if (wc_curve448_check_public(keyShareEntry->ke, keyShareEntry->keLen,
  6854. EC448_LITTLE_ENDIAN) != 0) {
  6855. ret = ECC_PEERKEY_ERROR;
  6856. WOLFSSL_ERROR_VERBOSE(ret);
  6857. }
  6858. if (ret == 0) {
  6859. if (wc_curve448_import_public_ex(keyShareEntry->ke,
  6860. keyShareEntry->keLen, peerX448Key,
  6861. EC448_LITTLE_ENDIAN) != 0) {
  6862. ret = ECC_PEERKEY_ERROR;
  6863. WOLFSSL_ERROR_VERBOSE(ret);
  6864. }
  6865. }
  6866. if (ret == 0) {
  6867. ssl->ecdhCurveOID = ECC_X448_OID;
  6868. ret = wc_curve448_shared_secret_ex(key, peerX448Key,
  6869. ssl->arrays->preMasterSecret,
  6870. &ssl->arrays->preMasterSz,
  6871. EC448_LITTLE_ENDIAN);
  6872. }
  6873. wc_curve448_free(peerX448Key);
  6874. XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6875. wc_curve448_free((curve448_key*)keyShareEntry->key);
  6876. if (keyShareEntry->key != NULL) {
  6877. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6878. keyShareEntry->key = NULL;
  6879. }
  6880. #else
  6881. (void)ssl;
  6882. (void)keyShareEntry;
  6883. ret = PEER_KEY_ERROR;
  6884. WOLFSSL_ERROR_VERBOSE(ret);
  6885. #endif /* HAVE_CURVE448 */
  6886. return ret;
  6887. }
  6888. /* Process the ECC key share extension on the client side.
  6889. *
  6890. * ssl The SSL/TLS object.
  6891. * keyShareEntry The key share entry object to use to calculate shared secret.
  6892. * returns 0 on success and other values indicate failure.
  6893. */
  6894. static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6895. {
  6896. int ret = 0;
  6897. #ifdef HAVE_ECC
  6898. int curveId = ECC_CURVE_INVALID;
  6899. ecc_key* eccKey = (ecc_key*)keyShareEntry->key;
  6900. /* find supported curve */
  6901. switch (keyShareEntry->group) {
  6902. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  6903. #ifndef NO_ECC_SECP
  6904. case WOLFSSL_ECC_SECP256R1:
  6905. curveId = ECC_SECP256R1;
  6906. break;
  6907. #endif /* !NO_ECC_SECP */
  6908. #ifdef WOLFSSL_SM2
  6909. case WOLFSSL_ECC_SM2P256V1:
  6910. curveId = ECC_SM2P256V1;
  6911. break;
  6912. #endif
  6913. #endif
  6914. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  6915. #ifndef NO_ECC_SECP
  6916. case WOLFSSL_ECC_SECP384R1:
  6917. curveId = ECC_SECP384R1;
  6918. break;
  6919. #endif /* !NO_ECC_SECP */
  6920. #endif
  6921. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  6922. #ifndef NO_ECC_SECP
  6923. case WOLFSSL_ECC_SECP521R1:
  6924. curveId = ECC_SECP521R1;
  6925. break;
  6926. #endif /* !NO_ECC_SECP */
  6927. #endif
  6928. #if defined(HAVE_X448) && ECC_MIN_KEY_SZ <= 448
  6929. case WOLFSSL_ECC_X448:
  6930. curveId = ECC_X448;
  6931. break;
  6932. #endif
  6933. default:
  6934. /* unsupported curve */
  6935. WOLFSSL_ERROR_VERBOSE(ECC_PEERKEY_ERROR);
  6936. return ECC_PEERKEY_ERROR;
  6937. }
  6938. #ifdef WOLFSSL_ASYNC_CRYPT
  6939. if (keyShareEntry->lastRet == 0) /* don't enter here if WC_PENDING_E */
  6940. #endif
  6941. {
  6942. #ifdef WOLFSSL_DEBUG_TLS
  6943. WOLFSSL_MSG("Peer ECC Key");
  6944. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6945. #endif
  6946. if (ssl->peerEccKey != NULL) {
  6947. wc_ecc_free(ssl->peerEccKey);
  6948. XFREE(ssl->peerEccKey, ssl->heap, DYNAMIC_TYPE_ECC);
  6949. ssl->peerEccKeyPresent = 0;
  6950. }
  6951. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  6952. ret = tsip_Tls13GenSharedSecret(ssl, keyShareEntry);
  6953. if (ret != CRYPTOCB_UNAVAILABLE) {
  6954. return ret;
  6955. }
  6956. ret = 0;
  6957. #endif
  6958. ssl->peerEccKey = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
  6959. DYNAMIC_TYPE_ECC);
  6960. if (ssl->peerEccKey == NULL) {
  6961. WOLFSSL_MSG("PeerEccKey Memory error");
  6962. ret = MEMORY_ERROR;
  6963. }
  6964. if (ret == 0) {
  6965. ret = wc_ecc_init_ex(ssl->peerEccKey, ssl->heap, ssl->devId);
  6966. }
  6967. /* Point is validated by import function. */
  6968. if (ret == 0) {
  6969. ret = wc_ecc_import_x963_ex(keyShareEntry->ke, keyShareEntry->keLen,
  6970. ssl->peerEccKey, curveId);
  6971. if (ret != 0) {
  6972. ret = ECC_PEERKEY_ERROR;
  6973. WOLFSSL_ERROR_VERBOSE(ret);
  6974. }
  6975. }
  6976. if (ret == 0) {
  6977. ssl->ecdhCurveOID = ssl->peerEccKey->dp->oidSum;
  6978. ssl->peerEccKeyPresent = 1;
  6979. }
  6980. }
  6981. if (ret == 0 && eccKey == NULL)
  6982. ret = BAD_FUNC_ARG;
  6983. if (ret == 0) {
  6984. ret = EccSharedSecret(ssl, eccKey, ssl->peerEccKey,
  6985. keyShareEntry->ke, &keyShareEntry->keLen,
  6986. ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz,
  6987. ssl->options.side
  6988. );
  6989. #ifdef WOLFSSL_ASYNC_CRYPT
  6990. if (ret == WC_PENDING_E)
  6991. return ret;
  6992. #endif
  6993. }
  6994. /* done with key share, release resources */
  6995. if (ssl->peerEccKey != NULL
  6996. #ifdef HAVE_PK_CALLBACKS
  6997. && ssl->ctx->EccSharedSecretCb == NULL
  6998. #endif
  6999. ) {
  7000. wc_ecc_free(ssl->peerEccKey);
  7001. XFREE(ssl->peerEccKey, ssl->heap, DYNAMIC_TYPE_ECC);
  7002. ssl->peerEccKey = NULL;
  7003. ssl->peerEccKeyPresent = 0;
  7004. }
  7005. if (keyShareEntry->key) {
  7006. wc_ecc_free((ecc_key*)keyShareEntry->key);
  7007. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_ECC);
  7008. keyShareEntry->key = NULL;
  7009. }
  7010. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7011. keyShareEntry->ke = NULL;
  7012. #else
  7013. (void)ssl;
  7014. (void)keyShareEntry;
  7015. ret = PEER_KEY_ERROR;
  7016. WOLFSSL_ERROR_VERBOSE(ret);
  7017. #endif /* HAVE_ECC */
  7018. return ret;
  7019. }
  7020. #ifdef HAVE_PQC
  7021. /* Process the Kyber key share extension on the client side.
  7022. *
  7023. * ssl The SSL/TLS object.
  7024. * keyShareEntry The key share entry object to use to calculate shared secret.
  7025. * returns 0 on success and other values indicate failure.
  7026. */
  7027. static int TLSX_KeyShare_ProcessPqc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  7028. {
  7029. int ret = 0;
  7030. int type;
  7031. KyberKey kem[1];
  7032. byte* sharedSecret = NULL;
  7033. word32 sharedSecretLen = 0;
  7034. int oqs_group = 0;
  7035. int ecc_group = 0;
  7036. ecc_key eccpubkey;
  7037. word32 outlen = 0;
  7038. word32 privSz = 0;
  7039. word32 ctSz = 0;
  7040. word32 ssSz = 0;
  7041. if (keyShareEntry->ke == NULL) {
  7042. WOLFSSL_MSG("Invalid OQS algorithm specified.");
  7043. return BAD_FUNC_ARG;
  7044. }
  7045. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7046. /* I am the server, the shared secret has already been generated and
  7047. * is in keyShareEntry->ke; copy it to the pre-master secret
  7048. * pre-allocated buffer. */
  7049. if (keyShareEntry->keLen > ENCRYPT_LEN) {
  7050. WOLFSSL_MSG("shared secret is too long.");
  7051. return LENGTH_ERROR;
  7052. }
  7053. XMEMCPY(ssl->arrays->preMasterSecret, keyShareEntry->ke,
  7054. keyShareEntry->keLen);
  7055. ssl->arrays->preMasterSz = keyShareEntry->keLen;
  7056. XFREE(keyShareEntry->ke, sl->heap, DYNAMIC_TYPE_SECRET)
  7057. keyShareEntry->ke = NULL;
  7058. keyShareEntry->keLen = 0;
  7059. return 0;
  7060. }
  7061. /* I am the client, the ciphertext is in keyShareEntry->ke */
  7062. findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group);
  7063. ret = kyber_id2type(oqs_group, &type);
  7064. if (ret != 0) {
  7065. WOLFSSL_MSG("Invalid OQS algorithm specified.");
  7066. ret = BAD_FUNC_ARG;
  7067. }
  7068. if (ret == 0) {
  7069. ret = wc_KyberKey_Init(type, kem, ssl->heap, INVALID_DEVID);
  7070. if (ret != 0) {
  7071. WOLFSSL_MSG("Error creating Kyber KEM");
  7072. }
  7073. }
  7074. if (ret == 0) {
  7075. ret = wc_KyberKey_SharedSecretSize(kem, &ssSz);
  7076. }
  7077. if (ret == 0) {
  7078. sharedSecretLen = ssSz;
  7079. switch (ecc_group) {
  7080. case WOLFSSL_ECC_SECP256R1:
  7081. sharedSecretLen += 32;
  7082. outlen = 32;
  7083. break;
  7084. case WOLFSSL_ECC_SECP384R1:
  7085. sharedSecretLen += 48;
  7086. outlen = 48;
  7087. break;
  7088. case WOLFSSL_ECC_SECP521R1:
  7089. sharedSecretLen += 66;
  7090. outlen = 66;
  7091. break;
  7092. default:
  7093. break;
  7094. }
  7095. ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId);
  7096. if (ret != 0) {
  7097. WOLFSSL_MSG("Memory allocation error.");
  7098. ret = MEMORY_E;
  7099. }
  7100. }
  7101. if (ret == 0) {
  7102. sharedSecret = (byte*)XMALLOC(sharedSecretLen, ssl->heap,
  7103. DYNAMIC_TYPE_TLSX);
  7104. if (sharedSecret == NULL) {
  7105. WOLFSSL_MSG("Memory allocation error.");
  7106. ret = MEMORY_E;
  7107. }
  7108. }
  7109. if (ret == 0) {
  7110. ret = wc_KyberKey_CipherTextSize(kem, &ctSz);
  7111. }
  7112. if (ret == 0) {
  7113. ret = wc_KyberKey_PrivateKeySize(kem, &privSz);
  7114. }
  7115. if (ret == 0) {
  7116. ret = wc_KyberKey_DecodePrivateKey(kem, keyShareEntry->privKey, privSz);
  7117. }
  7118. if (ret == 0) {
  7119. ret = wc_KyberKey_Decapsulate(kem, sharedSecret + outlen,
  7120. keyShareEntry->ke + keyShareEntry->keLen - ctSz, ctSz);
  7121. if (ret != 0) {
  7122. WOLFSSL_MSG("wc_KyberKey decapsulation failure.");
  7123. ret = BAD_FUNC_ARG;
  7124. }
  7125. }
  7126. if (ecc_group != 0) {
  7127. if (ret == 0) {
  7128. /* Point is validated by import function. */
  7129. ret = wc_ecc_import_x963(keyShareEntry->ke,
  7130. keyShareEntry->keLen - ctSz,
  7131. &eccpubkey);
  7132. if (ret != 0) {
  7133. WOLFSSL_MSG("ECC Public key import error.");
  7134. }
  7135. }
  7136. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  7137. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  7138. !defined(HAVE_SELFTEST)
  7139. if (ret == 0) {
  7140. ret = wc_ecc_set_rng(keyShareEntry->key, ssl->rng);
  7141. if (ret != 0) {
  7142. WOLFSSL_MSG("Failure to set the ECC private key RNG.");
  7143. }
  7144. }
  7145. #endif
  7146. if (ret == 0) {
  7147. PRIVATE_KEY_UNLOCK();
  7148. ret = wc_ecc_shared_secret(keyShareEntry->key, &eccpubkey,
  7149. sharedSecret, &outlen);
  7150. PRIVATE_KEY_LOCK();
  7151. if (outlen != sharedSecretLen - ssSz) {
  7152. WOLFSSL_MSG("ECC shared secret derivation error.");
  7153. ret = BAD_FUNC_ARG;
  7154. }
  7155. }
  7156. }
  7157. if ((ret == 0) && (sharedSecretLen > ENCRYPT_LEN)) {
  7158. WOLFSSL_MSG("shared secret is too long.");
  7159. ret = LENGTH_ERROR;
  7160. }
  7161. if (ret == 0) {
  7162. /* Copy the shared secret to the pre-master secret pre-allocated
  7163. * buffer. */
  7164. XMEMCPY(ssl->arrays->preMasterSecret, sharedSecret, sharedSecretLen);
  7165. ssl->arrays->preMasterSz = (word32) sharedSecretLen;
  7166. }
  7167. if (sharedSecret != NULL) {
  7168. XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  7169. }
  7170. wc_ecc_free(&eccpubkey);
  7171. wc_KyberKey_Free(kem);
  7172. return ret;
  7173. }
  7174. #endif /* HAVE_PQC */
  7175. /* Process the key share extension on the client side.
  7176. *
  7177. * ssl The SSL/TLS object.
  7178. * keyShareEntry The key share entry object to use to calculate shared secret.
  7179. * returns 0 on success and other values indicate failure.
  7180. */
  7181. static int TLSX_KeyShare_Process(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  7182. {
  7183. int ret;
  7184. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  7185. ssl->session->namedGroup = keyShareEntry->group;
  7186. #endif
  7187. /* reset the pre master secret size */
  7188. if (ssl->arrays->preMasterSz == 0)
  7189. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  7190. /* Use Key Share Data from server. */
  7191. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(keyShareEntry->group))
  7192. ret = TLSX_KeyShare_ProcessDh(ssl, keyShareEntry);
  7193. else if (keyShareEntry->group == WOLFSSL_ECC_X25519)
  7194. ret = TLSX_KeyShare_ProcessX25519(ssl, keyShareEntry);
  7195. else if (keyShareEntry->group == WOLFSSL_ECC_X448)
  7196. ret = TLSX_KeyShare_ProcessX448(ssl, keyShareEntry);
  7197. #ifdef HAVE_PQC
  7198. else if (WOLFSSL_NAMED_GROUP_IS_PQC(keyShareEntry->group))
  7199. ret = TLSX_KeyShare_ProcessPqc(ssl, keyShareEntry);
  7200. #endif
  7201. else
  7202. ret = TLSX_KeyShare_ProcessEcc(ssl, keyShareEntry);
  7203. #ifdef WOLFSSL_DEBUG_TLS
  7204. if (ret == 0) {
  7205. WOLFSSL_MSG("KE Secret");
  7206. WOLFSSL_BUFFER(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  7207. }
  7208. #endif
  7209. #ifdef WOLFSSL_ASYNC_CRYPT
  7210. keyShareEntry->lastRet = ret;
  7211. #endif
  7212. return ret;
  7213. }
  7214. /* Parse an entry of the KeyShare extension.
  7215. *
  7216. * ssl The SSL/TLS object.
  7217. * input The extension data.
  7218. * length The length of the extension data.
  7219. * kse The new key share entry object.
  7220. * returns a positive number to indicate amount of data parsed and a negative
  7221. * number on error.
  7222. */
  7223. static int TLSX_KeyShareEntry_Parse(const WOLFSSL* ssl, const byte* input,
  7224. word16 length, KeyShareEntry **kse, TLSX** extensions)
  7225. {
  7226. int ret;
  7227. word16 group;
  7228. word16 keLen;
  7229. int offset = 0;
  7230. byte* ke;
  7231. if (length < OPAQUE16_LEN + OPAQUE16_LEN)
  7232. return BUFFER_ERROR;
  7233. /* Named group */
  7234. ato16(&input[offset], &group);
  7235. offset += OPAQUE16_LEN;
  7236. /* Key exchange data - public key. */
  7237. ato16(&input[offset], &keLen);
  7238. offset += OPAQUE16_LEN;
  7239. if (keLen == 0)
  7240. return INVALID_PARAMETER;
  7241. if (keLen > length - offset)
  7242. return BUFFER_ERROR;
  7243. #ifdef HAVE_PQC
  7244. if (WOLFSSL_NAMED_GROUP_IS_PQC(group) &&
  7245. ssl->options.side == WOLFSSL_SERVER_END) {
  7246. /* For KEMs, the public key is not stored. Casting away const because
  7247. * we know for KEMs, it will be read-only.*/
  7248. ke = (byte *)&input[offset];
  7249. } else
  7250. #endif
  7251. {
  7252. /* Store a copy in the key share object. */
  7253. ke = (byte*)XMALLOC(keLen, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7254. if (ke == NULL)
  7255. return MEMORY_E;
  7256. XMEMCPY(ke, &input[offset], keLen);
  7257. }
  7258. /* Populate a key share object in the extension. */
  7259. ret = TLSX_KeyShare_Use(ssl, group, keLen, ke, kse, extensions);
  7260. if (ret != 0) {
  7261. if (ke != &input[offset]) {
  7262. XFREE(ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7263. }
  7264. return ret;
  7265. }
  7266. /* Total length of the parsed data. */
  7267. return offset + keLen;
  7268. }
  7269. /* Searches the groups sent for the specified named group.
  7270. *
  7271. * ssl SSL/TLS object.
  7272. * name Group name to match.
  7273. * returns 1 when the extension has the group name and 0 otherwise.
  7274. */
  7275. static int TLSX_KeyShare_Find(WOLFSSL* ssl, word16 group)
  7276. {
  7277. TLSX* extension;
  7278. KeyShareEntry* list;
  7279. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  7280. if (extension == NULL) {
  7281. extension = TLSX_Find(ssl->ctx->extensions, TLSX_KEY_SHARE);
  7282. if (extension == NULL)
  7283. return 0;
  7284. }
  7285. list = (KeyShareEntry*)extension->data;
  7286. while (list != NULL) {
  7287. if (list->group == group)
  7288. return 1;
  7289. list = list->next;
  7290. }
  7291. return 0;
  7292. }
  7293. /* Searches the supported groups extension for the specified named group.
  7294. *
  7295. * ssl The SSL/TLS object.
  7296. * name The group name to match.
  7297. * returns 1 when the extension has the group name and 0 otherwise.
  7298. */
  7299. static int TLSX_SupportedGroups_Find(const WOLFSSL* ssl, word16 name,
  7300. TLSX* extensions)
  7301. {
  7302. #ifdef HAVE_SUPPORTED_CURVES
  7303. TLSX* extension;
  7304. SupportedCurve* curve = NULL;
  7305. if ((extension = TLSX_Find(extensions,
  7306. TLSX_SUPPORTED_GROUPS)) == NULL) {
  7307. if ((extension = TLSX_Find(ssl->ctx->extensions,
  7308. TLSX_SUPPORTED_GROUPS)) == NULL) {
  7309. return 0;
  7310. }
  7311. }
  7312. for (curve = (SupportedCurve*)extension->data; curve; curve = curve->next) {
  7313. if (curve->name == name)
  7314. return 1;
  7315. }
  7316. #endif
  7317. (void)ssl;
  7318. (void)name;
  7319. return 0;
  7320. }
  7321. int TLSX_KeyShare_Parse_ClientHello(const WOLFSSL* ssl,
  7322. const byte* input, word16 length, TLSX** extensions)
  7323. {
  7324. int ret;
  7325. int offset = 0;
  7326. word16 len;
  7327. TLSX* extension;
  7328. /* Add a KeyShare extension if it doesn't exist even if peer sent no
  7329. * entries. The presence of this extension signals that the peer can be
  7330. * negotiated with. */
  7331. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7332. if (extension == NULL) {
  7333. /* Push new KeyShare extension. */
  7334. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7335. if (ret != 0)
  7336. return ret;
  7337. }
  7338. if (length < OPAQUE16_LEN)
  7339. return BUFFER_ERROR;
  7340. /* ClientHello contains zero or more key share entries. */
  7341. ato16(input, &len);
  7342. if (len != length - OPAQUE16_LEN)
  7343. return BUFFER_ERROR;
  7344. offset += OPAQUE16_LEN;
  7345. while (offset < (int)length) {
  7346. ret = TLSX_KeyShareEntry_Parse(ssl, &input[offset],
  7347. length - (word16)offset, NULL, extensions);
  7348. if (ret < 0)
  7349. return ret;
  7350. offset += ret;
  7351. }
  7352. return 0;
  7353. }
  7354. /* Parse the KeyShare extension.
  7355. * Different formats in different messages.
  7356. *
  7357. * ssl The SSL/TLS object.
  7358. * input The extension data.
  7359. * length The length of the extension data.
  7360. * msgType The type of the message this extension is being parsed from.
  7361. * returns 0 on success and other values indicate failure.
  7362. */
  7363. int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  7364. byte msgType)
  7365. {
  7366. int ret;
  7367. KeyShareEntry *keyShareEntry = NULL;
  7368. word16 group;
  7369. if (msgType == client_hello) {
  7370. ret = TLSX_KeyShare_Parse_ClientHello(ssl, input, length,
  7371. &ssl->extensions);
  7372. }
  7373. else if (msgType == server_hello) {
  7374. int len;
  7375. if (length < OPAQUE16_LEN)
  7376. return BUFFER_ERROR;
  7377. /* The data is the named group the server wants to use. */
  7378. ato16(input, &group);
  7379. /* Check the selected group was supported by ClientHello extensions. */
  7380. if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) {
  7381. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7382. return BAD_KEY_SHARE_DATA;
  7383. }
  7384. /* Check if the group was sent. */
  7385. if (!TLSX_KeyShare_Find(ssl, group)) {
  7386. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7387. return BAD_KEY_SHARE_DATA;
  7388. }
  7389. /* ServerHello contains one key share entry. */
  7390. len = TLSX_KeyShareEntry_Parse(ssl, input, length, &keyShareEntry,
  7391. &ssl->extensions);
  7392. if (len != (int)length)
  7393. return BUFFER_ERROR;
  7394. /* Not in list sent if there isn't a private key. */
  7395. if (keyShareEntry == NULL || (keyShareEntry->key == NULL
  7396. #if !defined(NO_DH) || defined(HAVE_PQC)
  7397. && keyShareEntry->privKey == NULL
  7398. #endif
  7399. )) {
  7400. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7401. return BAD_KEY_SHARE_DATA;
  7402. }
  7403. /* Process the entry to calculate the secret. */
  7404. ret = TLSX_KeyShare_Process(ssl, keyShareEntry);
  7405. if (ret == 0)
  7406. ssl->session->namedGroup = ssl->namedGroup = group;
  7407. }
  7408. else if (msgType == hello_retry_request) {
  7409. if (length != OPAQUE16_LEN)
  7410. return BUFFER_ERROR;
  7411. /* The data is the named group the server wants to use. */
  7412. ato16(input, &group);
  7413. #ifdef WOLFSSL_ASYNC_CRYPT
  7414. /* only perform find and clear TLSX if not returning from async */
  7415. if (ssl->error != WC_PENDING_E)
  7416. #endif
  7417. {
  7418. /* Check the selected group was supported by ClientHello extensions. */
  7419. if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) {
  7420. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7421. return BAD_KEY_SHARE_DATA;
  7422. }
  7423. /* Check if the group was sent. */
  7424. if (TLSX_KeyShare_Find(ssl, group)) {
  7425. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7426. return BAD_KEY_SHARE_DATA;
  7427. }
  7428. /* Clear out unusable key shares. */
  7429. ret = TLSX_KeyShare_Empty(ssl);
  7430. if (ret != 0)
  7431. return ret;
  7432. }
  7433. #ifdef HAVE_PQC
  7434. /* For post-quantum groups, do this in TLSX_PopulateExtensions(). */
  7435. if (!WOLFSSL_NAMED_GROUP_IS_PQC(group))
  7436. #endif
  7437. ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL, &ssl->extensions);
  7438. if (ret == 0)
  7439. ssl->session->namedGroup = ssl->namedGroup = group;
  7440. }
  7441. else {
  7442. /* Not a message type that is allowed to have this extension. */
  7443. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  7444. return SANITY_MSG_E;
  7445. }
  7446. return ret;
  7447. }
  7448. /* Create a new key share entry and put it into the list.
  7449. *
  7450. * list The linked list of key share entries.
  7451. * group The named group.
  7452. * heap The memory to allocate with.
  7453. * keyShareEntry The new key share entry object.
  7454. * returns 0 on success and other values indicate failure.
  7455. */
  7456. static int TLSX_KeyShare_New(KeyShareEntry** list, int group, void *heap,
  7457. KeyShareEntry** keyShareEntry)
  7458. {
  7459. KeyShareEntry* kse;
  7460. KeyShareEntry** next;
  7461. kse = (KeyShareEntry*)XMALLOC(sizeof(KeyShareEntry), heap,
  7462. DYNAMIC_TYPE_TLSX);
  7463. if (kse == NULL)
  7464. return MEMORY_E;
  7465. XMEMSET(kse, 0, sizeof(*kse));
  7466. kse->group = (word16)group;
  7467. /* Add it to the back and maintain the links. */
  7468. while (*list != NULL) {
  7469. /* Assign to temporary to work around compiler bug found by customer. */
  7470. next = &((*list)->next);
  7471. list = next;
  7472. }
  7473. *list = kse;
  7474. *keyShareEntry = kse;
  7475. (void)heap;
  7476. return 0;
  7477. }
  7478. #ifdef HAVE_PQC
  7479. static int server_generate_pqc_ciphertext(WOLFSSL* ssl,
  7480. KeyShareEntry* keyShareEntry, byte* data, word16 len)
  7481. {
  7482. /* I am the server. The data parameter is the client's public key. I need
  7483. * to generate the public information (AKA ciphertext) and shared secret
  7484. * here. Note the "public information" is equivalent to a the public key in
  7485. * key exchange parlance. That's why it is being assigned to pubKey.
  7486. */
  7487. int type;
  7488. KyberKey kem[1];
  7489. byte* sharedSecret = NULL;
  7490. byte* ciphertext = NULL;
  7491. int ret = 0;
  7492. int oqs_group = 0;
  7493. int ecc_group = 0;
  7494. KeyShareEntry *ecc_kse = NULL;
  7495. ecc_key eccpubkey;
  7496. word32 outlen = 0;
  7497. word32 pubSz = 0;
  7498. word32 ctSz = 0;
  7499. word32 ssSz = 0;
  7500. findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group);
  7501. ret = kyber_id2type(oqs_group, &type);
  7502. if (ret != 0) {
  7503. WOLFSSL_MSG("Invalid Kyber algorithm specified.");
  7504. ret = BAD_FUNC_ARG;
  7505. }
  7506. if (ret == 0) {
  7507. ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId);
  7508. if (ret != 0) {
  7509. WOLFSSL_MSG("Could not do ECC public key initialization.");
  7510. ret = MEMORY_E;
  7511. }
  7512. }
  7513. if (ret == 0) {
  7514. ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap,
  7515. DYNAMIC_TYPE_TLSX);
  7516. if (ecc_kse == NULL) {
  7517. WOLFSSL_MSG("ecc_kse memory allocation failure");
  7518. ret = MEMORY_ERROR;
  7519. }
  7520. }
  7521. if (ret == 0) {
  7522. XMEMSET(ecc_kse, 0, sizeof(*ecc_kse));
  7523. }
  7524. if (ret == 0 && ecc_group != 0) {
  7525. ecc_kse->group = ecc_group;
  7526. ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse);
  7527. if (ret != 0) {
  7528. /* No message, TLSX_KeyShare_GenEccKey() will do it. */
  7529. return ret;
  7530. }
  7531. ret = 0;
  7532. }
  7533. if (ret == 0) {
  7534. ret = wc_KyberKey_Init(type, kem, ssl->heap, INVALID_DEVID);
  7535. if (ret != 0) {
  7536. WOLFSSL_MSG("Error creating Kyber KEM");
  7537. }
  7538. }
  7539. if (ret == 0) {
  7540. ret = wc_KyberKey_PublicKeySize(kem, &pubSz);
  7541. }
  7542. if (ret == 0) {
  7543. ret = wc_KyberKey_CipherTextSize(kem, &ctSz);
  7544. }
  7545. if (ret == 0) {
  7546. ret = wc_KyberKey_SharedSecretSize(kem, &ssSz);
  7547. }
  7548. if (ret == 0 && len != pubSz + ecc_kse->pubKeyLen) {
  7549. WOLFSSL_MSG("Invalid public key.");
  7550. ret = BAD_FUNC_ARG;
  7551. }
  7552. if (ret == 0) {
  7553. sharedSecret = (byte*)XMALLOC(ecc_kse->keyLen + ssSz, ssl->heap,
  7554. DYNAMIC_TYPE_TLSX);
  7555. ciphertext = (byte*)XMALLOC(ecc_kse->pubKeyLen + ctSz, ssl->heap,
  7556. DYNAMIC_TYPE_TLSX);
  7557. if (sharedSecret == NULL || ciphertext == NULL) {
  7558. WOLFSSL_MSG("Ciphertext/shared secret memory allocation failure.");
  7559. ret = MEMORY_E;
  7560. }
  7561. }
  7562. if (ecc_group != 0) {
  7563. if (ret == 0) {
  7564. /* Point is validated by import function. */
  7565. ret = wc_ecc_import_x963(data, len - pubSz, &eccpubkey);
  7566. if (ret != 0) {
  7567. WOLFSSL_MSG("Bad ECC public key.");
  7568. }
  7569. }
  7570. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  7571. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  7572. !defined(HAVE_SELFTEST)
  7573. if (ret == 0) {
  7574. ret = wc_ecc_set_rng(ecc_kse->key, ssl->rng);
  7575. }
  7576. #endif
  7577. if (ret == 0) {
  7578. outlen = ecc_kse->keyLen;
  7579. PRIVATE_KEY_UNLOCK();
  7580. ret = wc_ecc_shared_secret(ecc_kse->key, &eccpubkey,
  7581. sharedSecret,
  7582. &outlen);
  7583. PRIVATE_KEY_LOCK();
  7584. if (outlen != ecc_kse->keyLen) {
  7585. WOLFSSL_MSG("Data length mismatch.");
  7586. ret = BAD_FUNC_ARG;
  7587. }
  7588. }
  7589. }
  7590. if (ret == 0) {
  7591. ret = wc_KyberKey_DecodePublicKey(kem, data + ecc_kse->pubKeyLen,
  7592. pubSz);
  7593. }
  7594. if (ret == 0) {
  7595. ret = wc_KyberKey_Encapsulate(kem, ciphertext + ecc_kse->pubKeyLen,
  7596. sharedSecret + outlen, ssl->rng);
  7597. if (ret != 0) {
  7598. WOLFSSL_MSG("wc_KyberKey encapsulation failure.");
  7599. }
  7600. }
  7601. if (ret == 0) {
  7602. if (keyShareEntry->ke != NULL) {
  7603. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7604. }
  7605. keyShareEntry->ke = sharedSecret;
  7606. keyShareEntry->keLen = outlen + ssSz;
  7607. sharedSecret = NULL;
  7608. XMEMCPY(ciphertext, ecc_kse->pubKey, ecc_kse->pubKeyLen);
  7609. keyShareEntry->pubKey = ciphertext;
  7610. keyShareEntry->pubKeyLen = (word32)(ecc_kse->pubKeyLen + ctSz);
  7611. ciphertext = NULL;
  7612. }
  7613. TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap);
  7614. if (sharedSecret != NULL)
  7615. XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_TLSX);
  7616. if (ciphertext != NULL)
  7617. XFREE(ciphertext, ssl->heap, DYNAMIC_TYPE_TLSX);
  7618. wc_ecc_free(&eccpubkey);
  7619. wc_KyberKey_Free(kem);
  7620. return ret;
  7621. }
  7622. #endif /* HAVE_PQC */
  7623. /* Use the data to create a new key share object in the extensions.
  7624. *
  7625. * ssl The SSL/TLS object.
  7626. * group The named group.
  7627. * len The length of the public key data.
  7628. * data The public key data.
  7629. * kse The new key share entry object.
  7630. * returns 0 on success and other values indicate failure.
  7631. */
  7632. int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group, word16 len, byte* data,
  7633. KeyShareEntry **kse, TLSX** extensions)
  7634. {
  7635. int ret = 0;
  7636. TLSX* extension;
  7637. KeyShareEntry* keyShareEntry = NULL;
  7638. /* Find the KeyShare extension if it exists. */
  7639. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7640. if (extension == NULL) {
  7641. /* Push new KeyShare extension. */
  7642. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7643. if (ret != 0)
  7644. return ret;
  7645. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7646. if (extension == NULL)
  7647. return MEMORY_E;
  7648. }
  7649. extension->resp = 0;
  7650. /* Try to find the key share entry with this group. */
  7651. keyShareEntry = (KeyShareEntry*)extension->data;
  7652. while (keyShareEntry != NULL) {
  7653. if (keyShareEntry->group == group)
  7654. break;
  7655. keyShareEntry = keyShareEntry->next;
  7656. }
  7657. /* Create a new key share entry if not found. */
  7658. if (keyShareEntry == NULL) {
  7659. ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, group,
  7660. ssl->heap, &keyShareEntry);
  7661. if (ret != 0)
  7662. return ret;
  7663. }
  7664. #ifdef HAVE_PQC
  7665. if (WOLFSSL_NAMED_GROUP_IS_PQC(group) &&
  7666. ssl->options.side == WOLFSSL_SERVER_END) {
  7667. ret = server_generate_pqc_ciphertext((WOLFSSL*)ssl, keyShareEntry, data,
  7668. len);
  7669. if (ret != 0)
  7670. return ret;
  7671. }
  7672. else
  7673. #endif
  7674. if (data != NULL) {
  7675. if (keyShareEntry->ke != NULL) {
  7676. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7677. }
  7678. keyShareEntry->ke = data;
  7679. keyShareEntry->keLen = len;
  7680. }
  7681. else {
  7682. /* Generate a key pair. Casting to non-const since changes inside are
  7683. * minimal but would require an extensive redesign to refactor. Also
  7684. * this path shouldn't be taken when parsing a ClientHello in stateless
  7685. * mode. */
  7686. ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, keyShareEntry);
  7687. if (ret != 0)
  7688. return ret;
  7689. }
  7690. if (kse != NULL)
  7691. *kse = keyShareEntry;
  7692. return 0;
  7693. }
  7694. /* Set an empty Key Share extension.
  7695. *
  7696. * ssl The SSL/TLS object.
  7697. * returns 0 on success and other values indicate failure.
  7698. */
  7699. int TLSX_KeyShare_Empty(WOLFSSL* ssl)
  7700. {
  7701. int ret = 0;
  7702. TLSX* extension;
  7703. /* Find the KeyShare extension if it exists. */
  7704. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  7705. if (extension == NULL) {
  7706. /* Push new KeyShare extension. */
  7707. ret = TLSX_Push(&ssl->extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7708. }
  7709. else if (extension->data != NULL) {
  7710. TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap);
  7711. extension->data = NULL;
  7712. }
  7713. return ret;
  7714. }
  7715. /* Returns whether this group is supported.
  7716. *
  7717. * namedGroup The named group to check.
  7718. * returns 1 when supported or 0 otherwise.
  7719. */
  7720. static int TLSX_KeyShare_IsSupported(int namedGroup)
  7721. {
  7722. switch (namedGroup) {
  7723. #ifdef HAVE_FFDHE_2048
  7724. case WOLFSSL_FFDHE_2048:
  7725. break;
  7726. #endif
  7727. #ifdef HAVE_FFDHE_3072
  7728. case WOLFSSL_FFDHE_3072:
  7729. break;
  7730. #endif
  7731. #ifdef HAVE_FFDHE_4096
  7732. case WOLFSSL_FFDHE_4096:
  7733. break;
  7734. #endif
  7735. #ifdef HAVE_FFDHE_6144
  7736. case WOLFSSL_FFDHE_6144:
  7737. break;
  7738. #endif
  7739. #ifdef HAVE_FFDHE_8192
  7740. case WOLFSSL_FFDHE_8192:
  7741. break;
  7742. #endif
  7743. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  7744. #ifdef HAVE_ECC_KOBLITZ
  7745. case WOLFSSL_ECC_SECP256K1:
  7746. break;
  7747. #endif
  7748. #ifndef NO_ECC_SECP
  7749. case WOLFSSL_ECC_SECP256R1:
  7750. break;
  7751. #endif /* !NO_ECC_SECP */
  7752. #ifdef HAVE_ECC_BRAINPOOL
  7753. case WOLFSSL_ECC_BRAINPOOLP256R1:
  7754. break;
  7755. #endif
  7756. #ifdef WOLFSSL_SM2
  7757. case WOLFSSL_ECC_SM2P256V1:
  7758. break;
  7759. #endif /* WOLFSSL_SM2 */
  7760. #endif
  7761. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  7762. case WOLFSSL_ECC_X25519:
  7763. break;
  7764. #endif
  7765. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  7766. case WOLFSSL_ECC_X448:
  7767. break;
  7768. #endif
  7769. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  7770. #ifndef NO_ECC_SECP
  7771. case WOLFSSL_ECC_SECP384R1:
  7772. break;
  7773. #endif /* !NO_ECC_SECP */
  7774. #ifdef HAVE_ECC_BRAINPOOL
  7775. case WOLFSSL_ECC_BRAINPOOLP384R1:
  7776. break;
  7777. #endif
  7778. #endif
  7779. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  7780. #ifndef NO_ECC_SECP
  7781. case WOLFSSL_ECC_SECP521R1:
  7782. break;
  7783. #endif /* !NO_ECC_SECP */
  7784. #endif
  7785. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  7786. #ifdef HAVE_ECC_KOBLITZ
  7787. case WOLFSSL_ECC_SECP160K1:
  7788. break;
  7789. #endif
  7790. #ifndef NO_ECC_SECP
  7791. case WOLFSSL_ECC_SECP160R1:
  7792. break;
  7793. #endif
  7794. #ifdef HAVE_ECC_SECPR2
  7795. case WOLFSSL_ECC_SECP160R2:
  7796. break;
  7797. #endif
  7798. #endif
  7799. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  7800. #ifdef HAVE_ECC_KOBLITZ
  7801. case WOLFSSL_ECC_SECP192K1:
  7802. break;
  7803. #endif
  7804. #ifndef NO_ECC_SECP
  7805. case WOLFSSL_ECC_SECP192R1:
  7806. break;
  7807. #endif
  7808. #endif
  7809. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  7810. #ifdef HAVE_ECC_KOBLITZ
  7811. case WOLFSSL_ECC_SECP224K1:
  7812. break;
  7813. #endif
  7814. #ifndef NO_ECC_SECP
  7815. case WOLFSSL_ECC_SECP224R1:
  7816. break;
  7817. #endif
  7818. #endif
  7819. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  7820. #ifdef HAVE_ECC_BRAINPOOL
  7821. case WOLFSSL_ECC_BRAINPOOLP512R1:
  7822. break;
  7823. #endif
  7824. #endif
  7825. #ifdef HAVE_PQC
  7826. #ifdef WOLFSSL_WC_KYBER
  7827. #ifdef WOLFSSL_KYBER512
  7828. case WOLFSSL_KYBER_LEVEL1:
  7829. #endif
  7830. #ifdef WOLFSSL_KYBER768
  7831. case WOLFSSL_KYBER_LEVEL3:
  7832. #endif
  7833. #ifdef WOLFSSL_KYBER1024
  7834. case WOLFSSL_KYBER_LEVEL5:
  7835. #endif
  7836. break;
  7837. #elif defined(HAVE_LIBOQS)
  7838. case WOLFSSL_KYBER_LEVEL1:
  7839. case WOLFSSL_KYBER_LEVEL3:
  7840. case WOLFSSL_KYBER_LEVEL5:
  7841. case WOLFSSL_P256_KYBER_LEVEL1:
  7842. case WOLFSSL_P384_KYBER_LEVEL3:
  7843. case WOLFSSL_P521_KYBER_LEVEL5:
  7844. {
  7845. int ret;
  7846. int id;
  7847. findEccPqc(NULL, &namedGroup, namedGroup);
  7848. ret = kyber_id2type(namedGroup, &id);
  7849. if (ret == NOT_COMPILED_IN) {
  7850. return 0;
  7851. }
  7852. if (! ext_kyber_enabled(id)) {
  7853. return 0;
  7854. }
  7855. break;
  7856. }
  7857. #elif defined(HAVE_PQM4)
  7858. case WOLFSSL_KYBER_LEVEL1:
  7859. break;
  7860. #endif
  7861. #endif /* HAVE_PQC */
  7862. default:
  7863. return 0;
  7864. }
  7865. return 1;
  7866. }
  7867. static const word16 preferredGroup[] = {
  7868. #if defined(HAVE_ECC) && (!defined(NO_ECC256) || \
  7869. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 256
  7870. WOLFSSL_ECC_SECP256R1,
  7871. #if !defined(HAVE_FIPS) && defined(WOLFSSL_SM2)
  7872. WOLFSSL_ECC_SM2P256V1,
  7873. #endif
  7874. #endif
  7875. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  7876. WOLFSSL_ECC_X25519,
  7877. #endif
  7878. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  7879. WOLFSSL_ECC_X448,
  7880. #endif
  7881. #if defined(HAVE_ECC) && (!defined(NO_ECC384) || \
  7882. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 384
  7883. WOLFSSL_ECC_SECP384R1,
  7884. #endif
  7885. #if defined(HAVE_ECC) && (!defined(NO_ECC521) || \
  7886. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 521
  7887. WOLFSSL_ECC_SECP521R1,
  7888. #endif
  7889. #if defined(HAVE_FFDHE_2048)
  7890. WOLFSSL_FFDHE_2048,
  7891. #endif
  7892. #if defined(HAVE_FFDHE_3072)
  7893. WOLFSSL_FFDHE_3072,
  7894. #endif
  7895. #if defined(HAVE_FFDHE_4096)
  7896. WOLFSSL_FFDHE_4096,
  7897. #endif
  7898. #if defined(HAVE_FFDHE_6144)
  7899. WOLFSSL_FFDHE_6144,
  7900. #endif
  7901. #if defined(HAVE_FFDHE_8192)
  7902. WOLFSSL_FFDHE_8192,
  7903. #endif
  7904. #ifdef WOLFSSL_WC_KYBER
  7905. #ifdef WOLFSSL_KYBER512
  7906. WOLFSSL_KYBER_LEVEL1,
  7907. #endif
  7908. #ifdef WOLFSSL_KYBER768
  7909. WOLFSSL_KYBER_LEVEL3,
  7910. #endif
  7911. #ifdef WOLFSSL_KYBER1024
  7912. WOLFSSL_KYBER_LEVEL5,
  7913. #endif
  7914. #elif defined(HAVE_LIBOQS)
  7915. /* These require a runtime call to TLSX_KeyShare_IsSupported to use */
  7916. WOLFSSL_KYBER_LEVEL1,
  7917. WOLFSSL_KYBER_LEVEL3,
  7918. WOLFSSL_KYBER_LEVEL5,
  7919. WOLFSSL_P256_KYBER_LEVEL1,
  7920. WOLFSSL_P384_KYBER_LEVEL3,
  7921. WOLFSSL_P521_KYBER_LEVEL5,
  7922. #elif defined(HAVE_PQM4)
  7923. WOLFSSL_KYBER_LEVEL1,
  7924. #endif
  7925. WOLFSSL_NAMED_GROUP_INVALID
  7926. };
  7927. #define PREFERRED_GROUP_SZ \
  7928. ((sizeof(preferredGroup)/sizeof(*preferredGroup)) - 1)
  7929. /* -1 for the invalid group */
  7930. /* Examines the application specified group ranking and returns the rank of the
  7931. * group.
  7932. * If no group ranking set then all groups are rank 0 (highest).
  7933. *
  7934. * ssl The SSL/TLS object.
  7935. * group The group to check ranking for.
  7936. * returns ranking from 0 to MAX_GROUP_COUNT-1 or -1 when group not in list.
  7937. */
  7938. static int TLSX_KeyShare_GroupRank(const WOLFSSL* ssl, int group)
  7939. {
  7940. byte i;
  7941. const word16* groups;
  7942. byte numGroups;
  7943. if (ssl->numGroups == 0) {
  7944. groups = preferredGroup;
  7945. numGroups = PREFERRED_GROUP_SZ;
  7946. }
  7947. else {
  7948. groups = ssl->group;
  7949. numGroups = ssl->numGroups;
  7950. }
  7951. #ifdef HAVE_LIBOQS
  7952. if (!TLSX_KeyShare_IsSupported(group))
  7953. return -1;
  7954. #endif
  7955. for (i = 0; i < numGroups; i++)
  7956. if (groups[i] == (word16)group)
  7957. return i;
  7958. return -1;
  7959. }
  7960. /* Set a key share that is supported by the client into extensions.
  7961. *
  7962. * ssl The SSL/TLS object.
  7963. * returns BAD_KEY_SHARE_DATA if no supported group has a key share,
  7964. * 0 if a supported group has a key share and other values indicate an error.
  7965. */
  7966. int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl, TLSX** extensions)
  7967. {
  7968. int ret;
  7969. #ifdef HAVE_SUPPORTED_CURVES
  7970. TLSX* extension;
  7971. SupportedCurve* curve = NULL;
  7972. SupportedCurve* preferredCurve = NULL;
  7973. KeyShareEntry* kse = NULL;
  7974. int preferredRank = WOLFSSL_MAX_GROUP_COUNT;
  7975. int rank;
  7976. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  7977. if (extension != NULL)
  7978. curve = (SupportedCurve*)extension->data;
  7979. /* Use server's preference order. */
  7980. for (; curve != NULL; curve = curve->next) {
  7981. if (!TLSX_KeyShare_IsSupported(curve->name))
  7982. continue;
  7983. if (wolfSSL_curve_is_disabled(ssl, curve->name))
  7984. continue;
  7985. rank = TLSX_KeyShare_GroupRank(ssl, curve->name);
  7986. if (rank == -1)
  7987. continue;
  7988. if (rank < preferredRank) {
  7989. preferredCurve = curve;
  7990. preferredRank = rank;
  7991. }
  7992. }
  7993. curve = preferredCurve;
  7994. if (curve == NULL) {
  7995. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7996. return BAD_KEY_SHARE_DATA;
  7997. }
  7998. #ifdef WOLFSSL_ASYNC_CRYPT
  7999. /* Check the old key share data list. */
  8000. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  8001. if (extension != NULL) {
  8002. kse = (KeyShareEntry*)extension->data;
  8003. /* We should not be computing keys if we are only going to advertise
  8004. * our choice here. */
  8005. if (kse != NULL && kse->lastRet == WC_PENDING_E) {
  8006. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  8007. return BAD_KEY_SHARE_DATA;
  8008. }
  8009. }
  8010. #endif
  8011. /* Push new KeyShare extension. This will also free the old one */
  8012. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  8013. if (ret != 0)
  8014. return ret;
  8015. /* Extension got pushed to head */
  8016. extension = *extensions;
  8017. /* Push the selected curve */
  8018. ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, curve->name,
  8019. ssl->heap, &kse);
  8020. if (ret != 0)
  8021. return ret;
  8022. /* Set extension to be in response. */
  8023. extension->resp = 1;
  8024. #else
  8025. (void)ssl;
  8026. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  8027. ret = NOT_COMPILED_IN;
  8028. #endif
  8029. return ret;
  8030. }
  8031. /* Server side KSE processing */
  8032. int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions,
  8033. byte cipherSuite0, byte cipherSuite, KeyShareEntry** kse, byte* searched)
  8034. {
  8035. TLSX* extension;
  8036. KeyShareEntry* clientKSE = NULL;
  8037. KeyShareEntry* list = NULL;
  8038. KeyShareEntry* preferredKSE = NULL;
  8039. int preferredRank = WOLFSSL_MAX_GROUP_COUNT;
  8040. int rank;
  8041. (void)cipherSuite0;
  8042. (void)cipherSuite;
  8043. if (ssl == NULL || ssl->options.side != WOLFSSL_SERVER_END)
  8044. return BAD_FUNC_ARG;
  8045. *searched = 0;
  8046. /* Find the KeyShare extension if it exists. */
  8047. extension = TLSX_Find(extensions, TLSX_KEY_SHARE);
  8048. if (extension != NULL)
  8049. list = (KeyShareEntry*)extension->data;
  8050. if (extension && extension->resp == 1) {
  8051. /* Outside of the async case this path should not be taken. */
  8052. int ret = INCOMPLETE_DATA;
  8053. #ifdef WOLFSSL_ASYNC_CRYPT
  8054. /* in async case make sure key generation is finalized */
  8055. KeyShareEntry* serverKSE = (KeyShareEntry*)extension->data;
  8056. if (serverKSE && serverKSE->lastRet == WC_PENDING_E) {
  8057. if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
  8058. *searched = 1;
  8059. ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE);
  8060. }
  8061. #endif
  8062. return ret;
  8063. }
  8064. /* Use server's preference order. */
  8065. for (clientKSE = list; clientKSE != NULL; clientKSE = clientKSE->next) {
  8066. if (clientKSE->ke == NULL)
  8067. continue;
  8068. #ifdef WOLFSSL_SM2
  8069. if ((cipherSuite0 == CIPHER_BYTE) &&
  8070. ((cipherSuite == TLS_SM4_GCM_SM3) ||
  8071. (cipherSuite == TLS_SM4_CCM_SM3))) {
  8072. if (clientKSE->group != WOLFSSL_ECC_SM2P256V1) {
  8073. continue;
  8074. }
  8075. }
  8076. else if (clientKSE->group == WOLFSSL_ECC_SM2P256V1) {
  8077. continue;
  8078. }
  8079. #endif
  8080. /* Check consistency now - extensions in any order. */
  8081. if (!TLSX_SupportedGroups_Find(ssl, clientKSE->group, extensions))
  8082. continue;
  8083. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(clientKSE->group)) {
  8084. /* Check max value supported. */
  8085. if (clientKSE->group > WOLFSSL_ECC_MAX) {
  8086. #ifdef HAVE_PQC
  8087. if (!WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group))
  8088. #endif
  8089. continue;
  8090. }
  8091. if (wolfSSL_curve_is_disabled(ssl, clientKSE->group))
  8092. continue;
  8093. }
  8094. if (!TLSX_KeyShare_IsSupported(clientKSE->group))
  8095. continue;
  8096. rank = TLSX_KeyShare_GroupRank(ssl, clientKSE->group);
  8097. if (rank == -1)
  8098. continue;
  8099. if (rank < preferredRank) {
  8100. preferredKSE = clientKSE;
  8101. preferredRank = rank;
  8102. }
  8103. }
  8104. *kse = preferredKSE;
  8105. *searched = 1;
  8106. return 0;
  8107. }
  8108. /* Server side KSE processing */
  8109. int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE)
  8110. {
  8111. int ret;
  8112. TLSX* extension;
  8113. KeyShareEntry* serverKSE;
  8114. KeyShareEntry* list = NULL;
  8115. if (ssl == NULL || ssl->options.side != WOLFSSL_SERVER_END)
  8116. return BAD_FUNC_ARG;
  8117. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  8118. if (extension == NULL)
  8119. return BAD_STATE_E;
  8120. if (clientKSE == NULL) {
  8121. #ifdef WOLFSSL_ASYNC_CRYPT
  8122. /* Not necessarily an error. The key may have already been setup. */
  8123. if (extension != NULL && extension->resp == 1) {
  8124. serverKSE = (KeyShareEntry*)extension->data;
  8125. if (serverKSE != NULL) {
  8126. /* in async case make sure key generation is finalized */
  8127. if (serverKSE->lastRet == WC_PENDING_E)
  8128. return TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE);
  8129. else if (serverKSE->lastRet == 0)
  8130. return 0;
  8131. }
  8132. }
  8133. #endif
  8134. return BAD_FUNC_ARG;
  8135. }
  8136. /* Generate a new key pair except in the case of OQS KEM because we
  8137. * are going to encapsulate and that does not require us to generate a
  8138. * key pair.
  8139. */
  8140. ret = TLSX_KeyShare_New(&list, clientKSE->group, ssl->heap, &serverKSE);
  8141. if (ret != 0)
  8142. return ret;
  8143. if (clientKSE->key == NULL) {
  8144. #ifdef HAVE_PQC
  8145. if (WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group)) {
  8146. /* Going to need the public key (AKA ciphertext). */
  8147. serverKSE->pubKey = clientKSE->pubKey;
  8148. clientKSE->pubKey = NULL;
  8149. serverKSE->pubKeyLen = clientKSE->pubKeyLen;
  8150. clientKSE->pubKeyLen = 0;
  8151. }
  8152. else
  8153. #endif
  8154. {
  8155. ret = TLSX_KeyShare_GenKey(ssl, serverKSE);
  8156. }
  8157. /* for async do setup of serverKSE below, but return WC_PENDING_E */
  8158. if (ret != 0
  8159. #ifdef WOLFSSL_ASYNC_CRYPT
  8160. && ret != WC_PENDING_E
  8161. #endif
  8162. ) {
  8163. TLSX_KeyShare_FreeAll(list, ssl->heap);
  8164. return ret;
  8165. }
  8166. }
  8167. else {
  8168. /* transfer buffers to serverKSE */
  8169. serverKSE->key = clientKSE->key;
  8170. clientKSE->key = NULL;
  8171. serverKSE->keyLen = clientKSE->keyLen;
  8172. serverKSE->pubKey = clientKSE->pubKey;
  8173. clientKSE->pubKey = NULL;
  8174. serverKSE->pubKeyLen = clientKSE->pubKeyLen;
  8175. #ifndef NO_DH
  8176. serverKSE->privKey = clientKSE->privKey;
  8177. clientKSE->privKey = NULL;
  8178. #endif
  8179. }
  8180. serverKSE->ke = clientKSE->ke;
  8181. serverKSE->keLen = clientKSE->keLen;
  8182. clientKSE->ke = NULL;
  8183. clientKSE->keLen = 0;
  8184. TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap);
  8185. extension->data = (void *)serverKSE;
  8186. extension->resp = 1;
  8187. return ret;
  8188. }
  8189. /* Ensure there is a key pair that can be used for key exchange.
  8190. *
  8191. * ssl The SSL/TLS object.
  8192. * doHelloRetry If set to non-zero will do hello_retry
  8193. * returns 0 on success and other values indicate failure.
  8194. */
  8195. int TLSX_KeyShare_Establish(WOLFSSL *ssl, int* doHelloRetry)
  8196. {
  8197. int ret;
  8198. KeyShareEntry* clientKSE = NULL;
  8199. byte searched = 0;
  8200. *doHelloRetry = 0;
  8201. ret = TLSX_KeyShare_Choose(ssl, ssl->extensions, ssl->cipher.cipherSuite0,
  8202. ssl->cipher.cipherSuite, &clientKSE, &searched);
  8203. if (ret != 0 || !searched)
  8204. return ret;
  8205. /* No supported group found - send HelloRetryRequest. */
  8206. if (clientKSE == NULL) {
  8207. /* Set KEY_SHARE_ERROR to indicate HelloRetryRequest required. */
  8208. *doHelloRetry = 1;
  8209. return TLSX_KeyShare_SetSupported(ssl, &ssl->extensions);
  8210. }
  8211. return TLSX_KeyShare_Setup(ssl, clientKSE);
  8212. }
  8213. /* Derive the shared secret of the key exchange.
  8214. *
  8215. * ssl The SSL/TLS object.
  8216. * returns 0 on success and other values indicate failure.
  8217. */
  8218. int TLSX_KeyShare_DeriveSecret(WOLFSSL *ssl)
  8219. {
  8220. int ret;
  8221. TLSX* extension;
  8222. KeyShareEntry* list = NULL;
  8223. #ifdef WOLFSSL_ASYNC_CRYPT
  8224. ret = wolfSSL_AsyncPop(ssl, NULL);
  8225. /* Check for error */
  8226. if (ret != WC_NOT_PENDING_E && ret < 0) {
  8227. return ret;
  8228. }
  8229. #endif
  8230. /* Find the KeyShare extension if it exists. */
  8231. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  8232. if (extension != NULL)
  8233. list = (KeyShareEntry*)extension->data;
  8234. if (list == NULL)
  8235. return KEY_SHARE_ERROR;
  8236. /* Calculate secret. */
  8237. ret = TLSX_KeyShare_Process(ssl, list);
  8238. return ret;
  8239. }
  8240. #define KS_FREE_ALL TLSX_KeyShare_FreeAll
  8241. #define KS_GET_SIZE TLSX_KeyShare_GetSize
  8242. #define KS_WRITE TLSX_KeyShare_Write
  8243. #define KS_PARSE TLSX_KeyShare_Parse
  8244. #else
  8245. #define KS_FREE_ALL(a, b) WC_DO_NOTHING
  8246. #define KS_GET_SIZE(a, b) 0
  8247. #define KS_WRITE(a, b, c) 0
  8248. #define KS_PARSE(a, b, c, d) 0
  8249. #endif /* WOLFSSL_TLS13 */
  8250. /******************************************************************************/
  8251. /* Pre-Shared Key */
  8252. /******************************************************************************/
  8253. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  8254. /* Free the pre-shared key dynamic data.
  8255. *
  8256. * list The linked list of key share entry objects.
  8257. * heap The heap used for allocation.
  8258. */
  8259. static void TLSX_PreSharedKey_FreeAll(PreSharedKey* list, void* heap)
  8260. {
  8261. PreSharedKey* current;
  8262. while ((current = list) != NULL) {
  8263. list = current->next;
  8264. XFREE(current->identity, heap, DYNAMIC_TYPE_TLSX);
  8265. XFREE(current, heap, DYNAMIC_TYPE_TLSX);
  8266. }
  8267. (void)heap;
  8268. }
  8269. /* Get the size of the encoded pre shared key extension.
  8270. *
  8271. * list The linked list of pre-shared key extensions.
  8272. * msgType The type of the message this extension is being written into.
  8273. * returns the number of bytes of the encoded pre-shared key extension or
  8274. * SANITY_MSG_E to indicate invalid message type.
  8275. */
  8276. static int TLSX_PreSharedKey_GetSize(PreSharedKey* list, byte msgType,
  8277. word16* pSz)
  8278. {
  8279. if (msgType == client_hello) {
  8280. /* Length of identities + Length of binders. */
  8281. word16 len = OPAQUE16_LEN + OPAQUE16_LEN;
  8282. while (list != NULL) {
  8283. /* Each entry has: identity, ticket age and binder. */
  8284. len += OPAQUE16_LEN + list->identityLen + OPAQUE32_LEN +
  8285. OPAQUE8_LEN + (word16)list->binderLen;
  8286. list = list->next;
  8287. }
  8288. *pSz += len;
  8289. return 0;
  8290. }
  8291. if (msgType == server_hello) {
  8292. *pSz += OPAQUE16_LEN;
  8293. return 0;
  8294. }
  8295. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8296. return SANITY_MSG_E;
  8297. }
  8298. /* The number of bytes to be written for the binders.
  8299. *
  8300. * list The linked list of pre-shared key extensions.
  8301. * msgType The type of the message this extension is being written into.
  8302. * returns the number of bytes of the encoded pre-shared key extension or
  8303. * SANITY_MSG_E to indicate invalid message type.
  8304. */
  8305. int TLSX_PreSharedKey_GetSizeBinders(PreSharedKey* list, byte msgType,
  8306. word16* pSz)
  8307. {
  8308. word16 len;
  8309. if (msgType != client_hello) {
  8310. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8311. return SANITY_MSG_E;
  8312. }
  8313. /* Length of all binders. */
  8314. len = OPAQUE16_LEN;
  8315. while (list != NULL) {
  8316. len += OPAQUE8_LEN + (word16)list->binderLen;
  8317. list = list->next;
  8318. }
  8319. *pSz = len;
  8320. return 0;
  8321. }
  8322. /* Writes the pre-shared key extension into the output buffer - binders only.
  8323. * Assumes that the the output buffer is big enough to hold data.
  8324. *
  8325. * list The linked list of key share entries.
  8326. * output The buffer to write into.
  8327. * msgType The type of the message this extension is being written into.
  8328. * returns the number of bytes written into the buffer.
  8329. */
  8330. int TLSX_PreSharedKey_WriteBinders(PreSharedKey* list, byte* output,
  8331. byte msgType, word16* pSz)
  8332. {
  8333. PreSharedKey* current = list;
  8334. word16 idx = 0;
  8335. word16 lenIdx;
  8336. word16 len;
  8337. if (msgType != client_hello) {
  8338. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8339. return SANITY_MSG_E;
  8340. }
  8341. /* Skip length of all binders. */
  8342. lenIdx = idx;
  8343. idx += OPAQUE16_LEN;
  8344. while (current != NULL) {
  8345. /* Binder data length. */
  8346. output[idx++] = (byte)current->binderLen;
  8347. /* Binder data. */
  8348. XMEMCPY(output + idx, current->binder, current->binderLen);
  8349. idx += (word16)current->binderLen;
  8350. current = current->next;
  8351. }
  8352. /* Length of the binders. */
  8353. len = idx - lenIdx - OPAQUE16_LEN;
  8354. c16toa(len, output + lenIdx);
  8355. *pSz = idx;
  8356. return 0;
  8357. }
  8358. /* Writes the pre-shared key extension into the output buffer.
  8359. * Assumes that the the output buffer is big enough to hold data.
  8360. *
  8361. * list The linked list of key share entries.
  8362. * output The buffer to write into.
  8363. * msgType The type of the message this extension is being written into.
  8364. * returns the number of bytes written into the buffer.
  8365. */
  8366. static int TLSX_PreSharedKey_Write(PreSharedKey* list, byte* output,
  8367. byte msgType, word16* pSz)
  8368. {
  8369. if (msgType == client_hello) {
  8370. PreSharedKey* current = list;
  8371. word16 idx = 0;
  8372. word16 lenIdx;
  8373. word16 len;
  8374. int ret;
  8375. /* Write identites only. Binders after HMACing over this. */
  8376. lenIdx = idx;
  8377. idx += OPAQUE16_LEN;
  8378. while (current != NULL) {
  8379. /* Identity length */
  8380. c16toa(current->identityLen, output + idx);
  8381. idx += OPAQUE16_LEN;
  8382. /* Identity data */
  8383. XMEMCPY(output + idx, current->identity, current->identityLen);
  8384. idx += current->identityLen;
  8385. /* Obfuscated ticket age. */
  8386. c32toa(current->ticketAge, output + idx);
  8387. idx += OPAQUE32_LEN;
  8388. current = current->next;
  8389. }
  8390. /* Length of the identites. */
  8391. len = idx - lenIdx - OPAQUE16_LEN;
  8392. c16toa(len, output + lenIdx);
  8393. /* Don't include binders here.
  8394. * The binders are based on the hash of all the ClientHello data up to
  8395. * and include the identities written above.
  8396. */
  8397. ret = TLSX_PreSharedKey_GetSizeBinders(list, msgType, &len);
  8398. if (ret < 0)
  8399. return ret;
  8400. *pSz += idx + len;
  8401. }
  8402. else if (msgType == server_hello) {
  8403. word16 i;
  8404. /* Find the index of the chosen identity. */
  8405. for (i=0; list != NULL && !list->chosen; i++)
  8406. list = list->next;
  8407. if (list == NULL) {
  8408. WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR);
  8409. return BUILD_MSG_ERROR;
  8410. }
  8411. /* The index of the identity chosen by the server from the list supplied
  8412. * by the client.
  8413. */
  8414. c16toa(i, output);
  8415. *pSz += OPAQUE16_LEN;
  8416. }
  8417. else {
  8418. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8419. return SANITY_MSG_E;
  8420. }
  8421. return 0;
  8422. }
  8423. int TLSX_PreSharedKey_Parse_ClientHello(TLSX** extensions, const byte* input,
  8424. word16 length, void* heap)
  8425. {
  8426. int ret;
  8427. word16 len;
  8428. word16 idx = 0;
  8429. TLSX* extension;
  8430. PreSharedKey* list;
  8431. TLSX_Remove(extensions, TLSX_PRE_SHARED_KEY, heap);
  8432. /* Length of identities and of binders. */
  8433. if ((int)(length - idx) < OPAQUE16_LEN + OPAQUE16_LEN)
  8434. return BUFFER_E;
  8435. /* Length of identities. */
  8436. ato16(input + idx, &len);
  8437. idx += OPAQUE16_LEN;
  8438. if (len < MIN_PSK_ID_LEN || length - idx < len)
  8439. return BUFFER_E;
  8440. /* Create a pre-shared key object for each identity. */
  8441. while (len > 0) {
  8442. const byte* identity;
  8443. word16 identityLen;
  8444. word32 age;
  8445. if (len < OPAQUE16_LEN)
  8446. return BUFFER_E;
  8447. /* Length of identity. */
  8448. ato16(input + idx, &identityLen);
  8449. idx += OPAQUE16_LEN;
  8450. if (len < OPAQUE16_LEN + identityLen + OPAQUE32_LEN ||
  8451. identityLen > MAX_PSK_ID_LEN)
  8452. return BUFFER_E;
  8453. /* Cache identity pointer. */
  8454. identity = input + idx;
  8455. idx += identityLen;
  8456. /* Ticket age. */
  8457. ato32(input + idx, &age);
  8458. idx += OPAQUE32_LEN;
  8459. ret = TLSX_PreSharedKey_Use(extensions, identity, identityLen, age, no_mac,
  8460. 0, 0, 1, NULL, heap);
  8461. if (ret != 0)
  8462. return ret;
  8463. /* Done with this identity. */
  8464. len -= OPAQUE16_LEN + identityLen + OPAQUE32_LEN;
  8465. }
  8466. /* Find the list of identities sent to server. */
  8467. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8468. if (extension == NULL)
  8469. return PSK_KEY_ERROR;
  8470. list = (PreSharedKey*)extension->data;
  8471. /* Length of binders. */
  8472. if (idx + OPAQUE16_LEN > length)
  8473. return BUFFER_E;
  8474. ato16(input + idx, &len);
  8475. idx += OPAQUE16_LEN;
  8476. if (len < MIN_PSK_BINDERS_LEN || length - idx < len)
  8477. return BUFFER_E;
  8478. /* Set binder for each identity. */
  8479. while (list != NULL && len > 0) {
  8480. /* Length of binder */
  8481. list->binderLen = input[idx++];
  8482. if (list->binderLen < WC_SHA256_DIGEST_SIZE ||
  8483. list->binderLen > WC_MAX_DIGEST_SIZE)
  8484. return BUFFER_E;
  8485. if (len < OPAQUE8_LEN + list->binderLen)
  8486. return BUFFER_E;
  8487. /* Copy binder into static buffer. */
  8488. XMEMCPY(list->binder, input + idx, list->binderLen);
  8489. idx += (word16)list->binderLen;
  8490. /* Done with binder entry. */
  8491. len -= OPAQUE8_LEN + (word16)list->binderLen;
  8492. /* Next identity. */
  8493. list = list->next;
  8494. }
  8495. if (list != NULL || len != 0)
  8496. return BUFFER_E;
  8497. return 0;
  8498. }
  8499. /* Parse the pre-shared key extension.
  8500. * Different formats in different messages.
  8501. *
  8502. * ssl The SSL/TLS object.
  8503. * input The extension data.
  8504. * length The length of the extension data.
  8505. * msgType The type of the message this extension is being parsed from.
  8506. * returns 0 on success and other values indicate failure.
  8507. */
  8508. static int TLSX_PreSharedKey_Parse(WOLFSSL* ssl, const byte* input,
  8509. word16 length, byte msgType)
  8510. {
  8511. if (msgType == client_hello) {
  8512. return TLSX_PreSharedKey_Parse_ClientHello(&ssl->extensions, input,
  8513. length, ssl->heap);
  8514. }
  8515. if (msgType == server_hello) {
  8516. word16 idx;
  8517. PreSharedKey* list;
  8518. TLSX* extension;
  8519. /* Index of identity chosen by server. */
  8520. if (length != OPAQUE16_LEN)
  8521. return BUFFER_E;
  8522. ato16(input, &idx);
  8523. #ifdef WOLFSSL_EARLY_DATA
  8524. ssl->options.pskIdIndex = idx + 1;
  8525. #endif
  8526. /* Find the list of identities sent to server. */
  8527. extension = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  8528. if (extension == NULL)
  8529. return PSK_KEY_ERROR;
  8530. list = (PreSharedKey*)extension->data;
  8531. /* Mark the identity as chosen. */
  8532. for (; list != NULL && idx > 0; idx--)
  8533. list = list->next;
  8534. if (list == NULL) {
  8535. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8536. return PSK_KEY_ERROR;
  8537. }
  8538. list->chosen = 1;
  8539. #ifdef HAVE_SESSION_TICKET
  8540. if (list->resumption) {
  8541. /* Check that the session's details are the same as the server's. */
  8542. if (ssl->options.cipherSuite0 != ssl->session->cipherSuite0 ||
  8543. ssl->options.cipherSuite != ssl->session->cipherSuite ||
  8544. ssl->session->version.major != ssl->ctx->method->version.major ||
  8545. ssl->session->version.minor != ssl->ctx->method->version.minor) {
  8546. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8547. return PSK_KEY_ERROR;
  8548. }
  8549. }
  8550. #endif
  8551. return 0;
  8552. }
  8553. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8554. return SANITY_MSG_E;
  8555. }
  8556. /* Create a new pre-shared key and put it into the list.
  8557. *
  8558. * list The linked list of pre-shared key.
  8559. * identity The identity.
  8560. * len The length of the identity data.
  8561. * heap The memory to allocate with.
  8562. * preSharedKey The new pre-shared key object.
  8563. * returns 0 on success and other values indicate failure.
  8564. */
  8565. static int TLSX_PreSharedKey_New(PreSharedKey** list, const byte* identity,
  8566. word16 len, void *heap,
  8567. PreSharedKey** preSharedKey)
  8568. {
  8569. PreSharedKey* psk;
  8570. PreSharedKey** next;
  8571. psk = (PreSharedKey*)XMALLOC(sizeof(PreSharedKey), heap, DYNAMIC_TYPE_TLSX);
  8572. if (psk == NULL)
  8573. return MEMORY_E;
  8574. XMEMSET(psk, 0, sizeof(*psk));
  8575. /* Make a copy of the identity data. */
  8576. psk->identity = (byte*)XMALLOC(len + NULL_TERM_LEN, heap,
  8577. DYNAMIC_TYPE_TLSX);
  8578. if (psk->identity == NULL) {
  8579. XFREE(psk, heap, DYNAMIC_TYPE_TLSX);
  8580. return MEMORY_E;
  8581. }
  8582. XMEMCPY(psk->identity, identity, len);
  8583. psk->identityLen = len;
  8584. /* Use a NULL terminator in case it is a C string */
  8585. psk->identity[psk->identityLen] = '\0';
  8586. /* Add it to the end and maintain the links. */
  8587. while (*list != NULL) {
  8588. /* Assign to temporary to work around compiler bug found by customer. */
  8589. next = &((*list)->next);
  8590. list = next;
  8591. }
  8592. *list = psk;
  8593. *preSharedKey = psk;
  8594. (void)heap;
  8595. return 0;
  8596. }
  8597. static WC_INLINE byte GetHmacLength(int hmac)
  8598. {
  8599. switch (hmac) {
  8600. #ifndef NO_SHA256
  8601. case sha256_mac:
  8602. return WC_SHA256_DIGEST_SIZE;
  8603. #endif
  8604. #ifdef WOLFSSL_SHA384
  8605. case sha384_mac:
  8606. return WC_SHA384_DIGEST_SIZE;
  8607. #endif
  8608. #ifdef WOLFSSL_SHA512
  8609. case sha512_mac:
  8610. return WC_SHA512_DIGEST_SIZE;
  8611. #endif
  8612. #ifdef WOLFSSL_SM3
  8613. case sm3_mac:
  8614. return WC_SM3_DIGEST_SIZE;
  8615. #endif
  8616. }
  8617. return 0;
  8618. }
  8619. /* Use the data to create a new pre-shared key object in the extensions.
  8620. *
  8621. * ssl The SSL/TLS object.
  8622. * identity The identity.
  8623. * len The length of the identity data.
  8624. * age The age of the identity.
  8625. * hmac The HMAC algorithm.
  8626. * cipherSuite0 The first byte of the cipher suite to use.
  8627. * cipherSuite The second byte of the cipher suite to use.
  8628. * resumption The PSK is for resumption of a session.
  8629. * preSharedKey The new pre-shared key object.
  8630. * returns 0 on success and other values indicate failure.
  8631. */
  8632. int TLSX_PreSharedKey_Use(TLSX** extensions, const byte* identity, word16 len,
  8633. word32 age, byte hmac, byte cipherSuite0,
  8634. byte cipherSuite, byte resumption,
  8635. PreSharedKey **preSharedKey, void* heap)
  8636. {
  8637. int ret = 0;
  8638. TLSX* extension;
  8639. PreSharedKey* psk = NULL;
  8640. /* Find the pre-shared key extension if it exists. */
  8641. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8642. if (extension == NULL) {
  8643. /* Push new pre-shared key extension. */
  8644. ret = TLSX_Push(extensions, TLSX_PRE_SHARED_KEY, NULL, heap);
  8645. if (ret != 0)
  8646. return ret;
  8647. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8648. if (extension == NULL)
  8649. return MEMORY_E;
  8650. }
  8651. /* Try to find the pre-shared key with this identity. */
  8652. psk = (PreSharedKey*)extension->data;
  8653. while (psk != NULL) {
  8654. if ((psk->identityLen == len) &&
  8655. (XMEMCMP(psk->identity, identity, len) == 0)) {
  8656. break;
  8657. }
  8658. psk = psk->next;
  8659. }
  8660. /* Create a new pre-shared key object if not found. */
  8661. if (psk == NULL) {
  8662. ret = TLSX_PreSharedKey_New((PreSharedKey**)&extension->data, identity,
  8663. len, heap, &psk);
  8664. if (ret != 0)
  8665. return ret;
  8666. }
  8667. /* Update/set age and HMAC algorithm. */
  8668. psk->ticketAge = age;
  8669. psk->hmac = hmac;
  8670. psk->cipherSuite0 = cipherSuite0;
  8671. psk->cipherSuite = cipherSuite;
  8672. psk->resumption = resumption;
  8673. psk->binderLen = GetHmacLength(psk->hmac);
  8674. if (preSharedKey != NULL)
  8675. *preSharedKey = psk;
  8676. return 0;
  8677. }
  8678. #define PSK_FREE_ALL TLSX_PreSharedKey_FreeAll
  8679. #define PSK_GET_SIZE TLSX_PreSharedKey_GetSize
  8680. #define PSK_WRITE TLSX_PreSharedKey_Write
  8681. #define PSK_PARSE TLSX_PreSharedKey_Parse
  8682. #else
  8683. #define PSK_FREE_ALL(a, b) WC_DO_NOTHING
  8684. #define PSK_GET_SIZE(a, b, c) 0
  8685. #define PSK_WRITE(a, b, c, d) 0
  8686. #define PSK_PARSE(a, b, c, d) 0
  8687. #endif
  8688. /******************************************************************************/
  8689. /* PSK Key Exchange Modes */
  8690. /******************************************************************************/
  8691. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  8692. /* Get the size of the encoded PSK KE modes extension.
  8693. * Only in ClientHello.
  8694. *
  8695. * modes The PSK KE mode bit string.
  8696. * msgType The type of the message this extension is being written into.
  8697. * returns the number of bytes of the encoded PSK KE mode extension.
  8698. */
  8699. static int TLSX_PskKeModes_GetSize(byte modes, byte msgType, word16* pSz)
  8700. {
  8701. if (msgType == client_hello) {
  8702. /* Format: Len | Modes* */
  8703. word16 len = OPAQUE8_LEN;
  8704. /* Check whether each possible mode is to be written. */
  8705. if (modes & (1 << PSK_KE))
  8706. len += OPAQUE8_LEN;
  8707. if (modes & (1 << PSK_DHE_KE))
  8708. len += OPAQUE8_LEN;
  8709. *pSz += len;
  8710. return 0;
  8711. }
  8712. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8713. return SANITY_MSG_E;
  8714. }
  8715. /* Writes the PSK KE modes extension into the output buffer.
  8716. * Assumes that the the output buffer is big enough to hold data.
  8717. * Only in ClientHello.
  8718. *
  8719. * modes The PSK KE mode bit string.
  8720. * output The buffer to write into.
  8721. * msgType The type of the message this extension is being written into.
  8722. * returns the number of bytes written into the buffer.
  8723. */
  8724. static int TLSX_PskKeModes_Write(byte modes, byte* output, byte msgType,
  8725. word16* pSz)
  8726. {
  8727. if (msgType == client_hello) {
  8728. /* Format: Len | Modes* */
  8729. word16 idx = OPAQUE8_LEN;
  8730. /* Write out each possible mode. */
  8731. if (modes & (1 << PSK_KE))
  8732. output[idx++] = PSK_KE;
  8733. if (modes & (1 << PSK_DHE_KE))
  8734. output[idx++] = PSK_DHE_KE;
  8735. /* Write out length of mode list. */
  8736. output[0] = (byte)(idx - OPAQUE8_LEN);
  8737. *pSz += idx;
  8738. return 0;
  8739. }
  8740. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8741. return SANITY_MSG_E;
  8742. }
  8743. int TLSX_PskKeyModes_Parse_Modes(const byte* input, word16 length, byte msgType,
  8744. byte* modes)
  8745. {
  8746. if (msgType == client_hello) {
  8747. /* Format: Len | Modes* */
  8748. int idx = 0;
  8749. word16 len;
  8750. *modes = 0;
  8751. /* Ensure length byte exists. */
  8752. if (length < OPAQUE8_LEN)
  8753. return BUFFER_E;
  8754. /* Get length of mode list and ensure that is the only data. */
  8755. len = input[0];
  8756. if (length - OPAQUE8_LEN != len)
  8757. return BUFFER_E;
  8758. idx = OPAQUE8_LEN;
  8759. /* Set a bit for each recognized modes. */
  8760. while (len > 0) {
  8761. /* Ignore unrecognized modes. */
  8762. if (input[idx] <= PSK_DHE_KE)
  8763. *modes |= 1 << input[idx];
  8764. idx++;
  8765. len--;
  8766. }
  8767. return 0;
  8768. }
  8769. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8770. return SANITY_MSG_E;
  8771. }
  8772. /* Parse the PSK KE modes extension.
  8773. * Only in ClientHello.
  8774. *
  8775. * ssl The SSL/TLS object.
  8776. * input The extension data.
  8777. * length The length of the extension data.
  8778. * msgType The type of the message this extension is being parsed from.
  8779. * returns 0 on success and other values indicate failure.
  8780. */
  8781. static int TLSX_PskKeModes_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  8782. byte msgType)
  8783. {
  8784. int ret;
  8785. byte modes;
  8786. ret = TLSX_PskKeyModes_Parse_Modes(input, length, msgType, &modes);
  8787. if (ret == 0)
  8788. ret = TLSX_PskKeyModes_Use(ssl, modes);
  8789. if (ret != 0) {
  8790. WOLFSSL_ERROR_VERBOSE(ret);
  8791. }
  8792. return ret;
  8793. }
  8794. /* Use the data to create a new PSK Key Exchange Modes object in the extensions.
  8795. *
  8796. * ssl The SSL/TLS object.
  8797. * modes The PSK key exchange modes.
  8798. * returns 0 on success and other values indicate failure.
  8799. */
  8800. int TLSX_PskKeyModes_Use(WOLFSSL* ssl, byte modes)
  8801. {
  8802. int ret = 0;
  8803. TLSX* extension;
  8804. /* Find the PSK key exchange modes extension if it exists. */
  8805. extension = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  8806. if (extension == NULL) {
  8807. /* Push new PSK key exchange modes extension. */
  8808. ret = TLSX_Push(&ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES, NULL,
  8809. ssl->heap);
  8810. if (ret != 0)
  8811. return ret;
  8812. extension = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  8813. if (extension == NULL)
  8814. return MEMORY_E;
  8815. }
  8816. extension->val = modes;
  8817. return 0;
  8818. }
  8819. #define PKM_GET_SIZE TLSX_PskKeModes_GetSize
  8820. #define PKM_WRITE TLSX_PskKeModes_Write
  8821. #define PKM_PARSE TLSX_PskKeModes_Parse
  8822. #else
  8823. #define PKM_GET_SIZE(a, b, c) 0
  8824. #define PKM_WRITE(a, b, c, d) 0
  8825. #define PKM_PARSE(a, b, c, d) 0
  8826. #endif
  8827. /******************************************************************************/
  8828. /* Post-Handshake Authentication */
  8829. /******************************************************************************/
  8830. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  8831. /* Get the size of the encoded Post-Handshake Authentication extension.
  8832. * Only in ClientHello.
  8833. *
  8834. * msgType The type of the message this extension is being written into.
  8835. * returns the number of bytes of the encoded Post-Handshake Authentication
  8836. * extension.
  8837. */
  8838. static int TLSX_PostHandAuth_GetSize(byte msgType, word16* pSz)
  8839. {
  8840. if (msgType == client_hello) {
  8841. *pSz += 0;
  8842. return 0;
  8843. }
  8844. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8845. return SANITY_MSG_E;
  8846. }
  8847. /* Writes the Post-Handshake Authentication extension into the output buffer.
  8848. * Assumes that the the output buffer is big enough to hold data.
  8849. * Only in ClientHello.
  8850. *
  8851. * output The buffer to write into.
  8852. * msgType The type of the message this extension is being written into.
  8853. * returns the number of bytes written into the buffer.
  8854. */
  8855. static int TLSX_PostHandAuth_Write(byte* output, byte msgType, word16* pSz)
  8856. {
  8857. (void)output;
  8858. if (msgType == client_hello) {
  8859. *pSz += 0;
  8860. return 0;
  8861. }
  8862. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8863. return SANITY_MSG_E;
  8864. }
  8865. /* Parse the Post-Handshake Authentication extension.
  8866. * Only in ClientHello.
  8867. *
  8868. * ssl The SSL/TLS object.
  8869. * input The extension data.
  8870. * length The length of the extension data.
  8871. * msgType The type of the message this extension is being parsed from.
  8872. * returns 0 on success and other values indicate failure.
  8873. */
  8874. static int TLSX_PostHandAuth_Parse(WOLFSSL* ssl, const byte* input,
  8875. word16 length, byte msgType)
  8876. {
  8877. (void)input;
  8878. if (msgType == client_hello) {
  8879. /* Ensure extension is empty. */
  8880. if (length != 0)
  8881. return BUFFER_E;
  8882. ssl->options.postHandshakeAuth = 1;
  8883. return 0;
  8884. }
  8885. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8886. return SANITY_MSG_E;
  8887. }
  8888. /* Create a new Post-handshake authentication object in the extensions.
  8889. *
  8890. * ssl The SSL/TLS object.
  8891. * returns 0 on success and other values indicate failure.
  8892. */
  8893. static int TLSX_PostHandAuth_Use(WOLFSSL* ssl)
  8894. {
  8895. int ret = 0;
  8896. TLSX* extension;
  8897. /* Find the PSK key exchange modes extension if it exists. */
  8898. extension = TLSX_Find(ssl->extensions, TLSX_POST_HANDSHAKE_AUTH);
  8899. if (extension == NULL) {
  8900. /* Push new Post-handshake Authentication extension. */
  8901. ret = TLSX_Push(&ssl->extensions, TLSX_POST_HANDSHAKE_AUTH, NULL,
  8902. ssl->heap);
  8903. if (ret != 0)
  8904. return ret;
  8905. }
  8906. return 0;
  8907. }
  8908. #define PHA_GET_SIZE TLSX_PostHandAuth_GetSize
  8909. #define PHA_WRITE TLSX_PostHandAuth_Write
  8910. #define PHA_PARSE TLSX_PostHandAuth_Parse
  8911. #else
  8912. #define PHA_GET_SIZE(a, b) 0
  8913. #define PHA_WRITE(a, b, c) 0
  8914. #define PHA_PARSE(a, b, c, d) 0
  8915. #endif
  8916. /******************************************************************************/
  8917. /* Early Data Indication */
  8918. /******************************************************************************/
  8919. #ifdef WOLFSSL_EARLY_DATA
  8920. /* Get the size of the encoded Early Data Indication extension.
  8921. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  8922. *
  8923. * msgType The type of the message this extension is being written into.
  8924. * returns the number of bytes of the encoded Early Data Indication extension.
  8925. */
  8926. static int TLSX_EarlyData_GetSize(byte msgType, word16* pSz)
  8927. {
  8928. int ret = 0;
  8929. if (msgType == client_hello || msgType == encrypted_extensions)
  8930. *pSz += 0;
  8931. else if (msgType == session_ticket)
  8932. *pSz += OPAQUE32_LEN;
  8933. else {
  8934. ret = SANITY_MSG_E;
  8935. WOLFSSL_ERROR_VERBOSE(ret);
  8936. }
  8937. return ret;
  8938. }
  8939. /* Writes the Early Data Indicator extension into the output buffer.
  8940. * Assumes that the the output buffer is big enough to hold data.
  8941. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  8942. *
  8943. * maxSz The maximum early data size.
  8944. * output The buffer to write into.
  8945. * msgType The type of the message this extension is being written into.
  8946. * returns the number of bytes written into the buffer.
  8947. */
  8948. static int TLSX_EarlyData_Write(word32 maxSz, byte* output, byte msgType,
  8949. word16* pSz)
  8950. {
  8951. if (msgType == client_hello || msgType == encrypted_extensions)
  8952. return 0;
  8953. else if (msgType == session_ticket) {
  8954. c32toa(maxSz, output);
  8955. *pSz += OPAQUE32_LEN;
  8956. return 0;
  8957. }
  8958. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8959. return SANITY_MSG_E;
  8960. }
  8961. /* Parse the Early Data Indicator extension.
  8962. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  8963. *
  8964. * ssl The SSL/TLS object.
  8965. * input The extension data.
  8966. * length The length of the extension data.
  8967. * msgType The type of the message this extension is being parsed from.
  8968. * returns 0 on success and other values indicate failure.
  8969. */
  8970. static int TLSX_EarlyData_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  8971. byte msgType)
  8972. {
  8973. WOLFSSL_ENTER("TLSX_EarlyData_Parse");
  8974. if (msgType == client_hello) {
  8975. if (length != 0)
  8976. return BUFFER_E;
  8977. if (ssl->earlyData == expecting_early_data) {
  8978. if (ssl->options.maxEarlyDataSz != 0)
  8979. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_ACCEPTED;
  8980. else
  8981. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_REJECTED;
  8982. return TLSX_EarlyData_Use(ssl, 0, 0);
  8983. }
  8984. ssl->earlyData = early_data_ext;
  8985. return 0;
  8986. }
  8987. if (msgType == encrypted_extensions) {
  8988. if (length != 0)
  8989. return BUFFER_E;
  8990. /* Ensure the index of PSK identity chosen by server is 0.
  8991. * Index is plus one to handle 'not set' value of 0.
  8992. */
  8993. if (ssl->options.pskIdIndex != 1) {
  8994. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8995. return PSK_KEY_ERROR;
  8996. }
  8997. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  8998. /* the extension from server comes in */
  8999. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_ACCEPTED;
  9000. }
  9001. return TLSX_EarlyData_Use(ssl, 1, 1);
  9002. }
  9003. if (msgType == session_ticket) {
  9004. word32 maxSz;
  9005. if (length != OPAQUE32_LEN)
  9006. return BUFFER_E;
  9007. ato32(input, &maxSz);
  9008. ssl->session->maxEarlyDataSz = maxSz;
  9009. return 0;
  9010. }
  9011. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9012. return SANITY_MSG_E;
  9013. }
  9014. /* Use the data to create a new Early Data object in the extensions.
  9015. *
  9016. * ssl The SSL/TLS object.
  9017. * maxSz The maximum early data size.
  9018. * is_response if this extension is part of a response
  9019. * returns 0 on success and other values indicate failure.
  9020. */
  9021. int TLSX_EarlyData_Use(WOLFSSL* ssl, word32 maxSz, int is_response)
  9022. {
  9023. int ret = 0;
  9024. TLSX* extension;
  9025. /* Find the early data extension if it exists. */
  9026. extension = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  9027. if (extension == NULL) {
  9028. /* Push new early data extension. */
  9029. ret = TLSX_Push(&ssl->extensions, TLSX_EARLY_DATA, NULL, ssl->heap);
  9030. if (ret != 0)
  9031. return ret;
  9032. extension = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  9033. if (extension == NULL)
  9034. return MEMORY_E;
  9035. }
  9036. extension->resp = is_response;
  9037. /* In QUIC, earlydata size is either 0 or 0xffffffff.
  9038. * Override any size between, possibly left from our initial value */
  9039. extension->val = (WOLFSSL_IS_QUIC(ssl) && is_response && maxSz > 0) ?
  9040. WOLFSSL_MAX_32BIT : maxSz;
  9041. return 0;
  9042. }
  9043. #define EDI_GET_SIZE TLSX_EarlyData_GetSize
  9044. #define EDI_WRITE TLSX_EarlyData_Write
  9045. #define EDI_PARSE TLSX_EarlyData_Parse
  9046. #else
  9047. #define EDI_GET_SIZE(a, b) 0
  9048. #define EDI_WRITE(a, b, c, d) 0
  9049. #define EDI_PARSE(a, b, c, d) 0
  9050. #endif
  9051. /******************************************************************************/
  9052. /* QUIC transport parameter extension */
  9053. /******************************************************************************/
  9054. #ifdef WOLFSSL_QUIC
  9055. static word16 TLSX_QuicTP_GetSize(TLSX* extension)
  9056. {
  9057. const QuicTransportParam *tp = (QuicTransportParam*)extension->data;
  9058. return tp ? tp->len : 0;
  9059. }
  9060. int TLSX_QuicTP_Use(WOLFSSL* ssl, TLSX_Type ext_type, int is_response)
  9061. {
  9062. int ret = 0;
  9063. TLSX* extension;
  9064. WOLFSSL_ENTER("TLSX_QuicTP_Use");
  9065. if (ssl->quic.transport_local == NULL) {
  9066. /* RFC9000, ch 7.3: "An endpoint MUST treat the absence of [...]
  9067. * from either endpoint [...] as a connection error of type
  9068. * TRANSPORT_PARAMETER_ERROR."
  9069. */
  9070. ret = QUIC_TP_MISSING_E;
  9071. goto cleanup;
  9072. }
  9073. extension = TLSX_Find(ssl->extensions, ext_type);
  9074. if (extension == NULL) {
  9075. ret = TLSX_Push(&ssl->extensions, ext_type, NULL, ssl->heap);
  9076. if (ret != 0)
  9077. goto cleanup;
  9078. extension = TLSX_Find(ssl->extensions, ext_type);
  9079. if (extension == NULL) {
  9080. ret = MEMORY_E;
  9081. goto cleanup;
  9082. }
  9083. }
  9084. if (extension->data) {
  9085. QuicTransportParam_free((QuicTransportParam*)extension->data, ssl->heap);
  9086. extension->data = NULL;
  9087. }
  9088. extension->resp = is_response;
  9089. extension->data = (void*)QuicTransportParam_dup(ssl->quic.transport_local, ssl->heap);
  9090. if (!extension->data) {
  9091. ret = MEMORY_E;
  9092. goto cleanup;
  9093. }
  9094. cleanup:
  9095. WOLFSSL_LEAVE("TLSX_QuicTP_Use", ret);
  9096. return ret;
  9097. }
  9098. static word16 TLSX_QuicTP_Write(QuicTransportParam *tp, byte* output)
  9099. {
  9100. word16 len = 0;
  9101. WOLFSSL_ENTER("TLSX_QuicTP_Write");
  9102. if (tp && tp->len) {
  9103. XMEMCPY(output, tp->data, tp->len);
  9104. len = tp->len;
  9105. }
  9106. WOLFSSL_LEAVE("TLSX_QuicTP_Write", len);
  9107. return len;
  9108. }
  9109. static int TLSX_QuicTP_Parse(WOLFSSL *ssl, const byte *input, size_t len, int ext_type, int msgType)
  9110. {
  9111. const QuicTransportParam *tp, **ptp;
  9112. (void)msgType;
  9113. tp = QuicTransportParam_new(input, len, ssl->heap);
  9114. if (!tp) {
  9115. return MEMORY_E;
  9116. }
  9117. ptp = (ext_type == TLSX_KEY_QUIC_TP_PARAMS_DRAFT) ?
  9118. &ssl->quic.transport_peer_draft : &ssl->quic.transport_peer;
  9119. if (*ptp) {
  9120. QTP_FREE(*ptp, ssl->heap);
  9121. }
  9122. *ptp = tp;
  9123. return 0;
  9124. }
  9125. #define QTP_GET_SIZE TLSX_QuicTP_GetSize
  9126. #define QTP_USE TLSX_QuicTP_Use
  9127. #define QTP_WRITE TLSX_QuicTP_Write
  9128. #define QTP_PARSE TLSX_QuicTP_Parse
  9129. #endif /* WOLFSSL_QUIC */
  9130. #if defined(WOLFSSL_DTLS_CID)
  9131. #define CID_GET_SIZE TLSX_ConnectionID_GetSize
  9132. #define CID_WRITE TLSX_ConnectionID_Write
  9133. #define CID_PARSE TLSX_ConnectionID_Parse
  9134. #define CID_FREE TLSX_ConnectionID_Free
  9135. #else
  9136. #define CID_GET_SIZE(a) 0
  9137. #define CID_WRITE(a, b) 0
  9138. #define CID_PARSE(a, b, c, d) 0
  9139. #define CID_FREE(a, b) 0
  9140. #endif /* defined(WOLFSSL_DTLS_CID) */
  9141. /******************************************************************************/
  9142. /* TLS Extensions Framework */
  9143. /******************************************************************************/
  9144. /** Finds an extension in the provided list. */
  9145. TLSX* TLSX_Find(TLSX* list, TLSX_Type type)
  9146. {
  9147. TLSX* extension = list;
  9148. while (extension && extension->type != type)
  9149. extension = extension->next;
  9150. return extension;
  9151. }
  9152. /** Remove an extension. */
  9153. void TLSX_Remove(TLSX** list, TLSX_Type type, void* heap)
  9154. {
  9155. TLSX* extension;
  9156. TLSX** next;
  9157. if (list == NULL)
  9158. return;
  9159. extension = *list;
  9160. next = list;
  9161. while (extension && extension->type != type) {
  9162. next = &extension->next;
  9163. extension = extension->next;
  9164. }
  9165. if (extension) {
  9166. *next = extension->next;
  9167. extension->next = NULL;
  9168. TLSX_FreeAll(extension, heap);
  9169. }
  9170. }
  9171. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  9172. #define GREASE_ECH_SIZE 160
  9173. #define MAX_PUBLIC_NAME_SZ 256
  9174. #define TLS_INFO_CONST_STRING "tls ech"
  9175. #define TLS_INFO_CONST_STRING_SZ 7
  9176. /* return status after setting up ech to write a grease ech */
  9177. static int TLSX_GreaseECH_Use(TLSX** extensions, void* heap, WC_RNG* rng)
  9178. {
  9179. int ret = 0;
  9180. WOLFSSL_ECH* ech;
  9181. if (extensions == NULL)
  9182. return BAD_FUNC_ARG;
  9183. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9184. DYNAMIC_TYPE_TMP_BUFFER);
  9185. if (ech == NULL)
  9186. return MEMORY_E;
  9187. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9188. ech->state = ECH_WRITE_GREASE;
  9189. /* 0 for outer */
  9190. ech->type = ECH_TYPE_OUTER;
  9191. /* kemId */
  9192. ech->kemId = DHKEM_X25519_HKDF_SHA256;
  9193. /* cipherSuite kdf */
  9194. ech->cipherSuite.kdfId = HKDF_SHA256;
  9195. /* cipherSuite aead */
  9196. ech->cipherSuite.aeadId = HPKE_AES_128_GCM;
  9197. /* random configId */
  9198. ret = wc_RNG_GenerateByte(rng, &(ech->configId));
  9199. /* curve25519 encLen */
  9200. ech->encLen = DHKEM_X25519_ENC_LEN;
  9201. if (ret == 0)
  9202. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9203. if (ret != 0) {
  9204. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9205. }
  9206. return ret;
  9207. }
  9208. /* return status after setting up ech to write real ech */
  9209. static int TLSX_ECH_Use(WOLFSSL_EchConfig* echConfig, TLSX** extensions,
  9210. void* heap, WC_RNG* rng)
  9211. {
  9212. int ret = 0;
  9213. int suiteIndex;
  9214. WOLFSSL_ECH* ech;
  9215. if (extensions == NULL)
  9216. return BAD_FUNC_ARG;
  9217. /* find a supported cipher suite */
  9218. suiteIndex = EchConfigGetSupportedCipherSuite(echConfig);
  9219. if (suiteIndex < 0)
  9220. return suiteIndex;
  9221. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9222. DYNAMIC_TYPE_TMP_BUFFER);
  9223. if (ech == NULL)
  9224. return MEMORY_E;
  9225. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9226. ech->state = ECH_WRITE_REAL;
  9227. ech->echConfig = echConfig;
  9228. /* 0 for outer */
  9229. ech->type = ECH_TYPE_OUTER;
  9230. /* kemId */
  9231. ech->kemId = echConfig->kemId;
  9232. /* cipherSuite kdf */
  9233. ech->cipherSuite.kdfId = echConfig->cipherSuites[suiteIndex].kdfId;
  9234. /* cipherSuite aead */
  9235. ech->cipherSuite.aeadId = echConfig->cipherSuites[suiteIndex].aeadId;
  9236. /* configId */
  9237. ech->configId = echConfig->configId;
  9238. /* encLen */
  9239. switch (echConfig->kemId)
  9240. {
  9241. case DHKEM_P256_HKDF_SHA256:
  9242. ech->encLen = DHKEM_P256_ENC_LEN;
  9243. break;
  9244. case DHKEM_P384_HKDF_SHA384:
  9245. ech->encLen = DHKEM_P384_ENC_LEN;
  9246. break;
  9247. case DHKEM_P521_HKDF_SHA512:
  9248. ech->encLen = DHKEM_P521_ENC_LEN;
  9249. break;
  9250. case DHKEM_X25519_HKDF_SHA256:
  9251. ech->encLen = DHKEM_X25519_ENC_LEN;
  9252. break;
  9253. case DHKEM_X448_HKDF_SHA512:
  9254. ech->encLen = DHKEM_X448_ENC_LEN;
  9255. break;
  9256. }
  9257. /* setup hpke */
  9258. ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER);
  9259. if (ech->hpke == NULL) {
  9260. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9261. return MEMORY_E;
  9262. }
  9263. ret = wc_HpkeInit(ech->hpke, ech->kemId, ech->cipherSuite.kdfId,
  9264. ech->cipherSuite.aeadId, heap);
  9265. /* setup the ephemeralKey */
  9266. if (ret == 0)
  9267. ret = wc_HpkeGenerateKeyPair(ech->hpke, &ech->ephemeralKey, rng);
  9268. if (ret == 0)
  9269. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9270. if (ret != 0) {
  9271. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9272. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9273. }
  9274. return ret;
  9275. }
  9276. /* return status after setting up ech to read and decrypt */
  9277. static int TLSX_ServerECH_Use(TLSX** extensions, void* heap,
  9278. WOLFSSL_EchConfig* configs)
  9279. {
  9280. int ret;
  9281. WOLFSSL_ECH* ech;
  9282. TLSX* echX;
  9283. if (extensions == NULL)
  9284. return BAD_FUNC_ARG;
  9285. /* if we already have ech don't override it */
  9286. echX = TLSX_Find(*extensions, TLSX_ECH);
  9287. if (echX != NULL)
  9288. return 0;
  9289. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9290. DYNAMIC_TYPE_TMP_BUFFER);
  9291. if (ech == NULL)
  9292. return MEMORY_E;
  9293. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9294. ech->state = ECH_WRITE_NONE;
  9295. /* 0 for outer */
  9296. ech->type = ECH_TYPE_OUTER;
  9297. ech->echConfig = configs;
  9298. /* setup the rest of the settings when we receive ech from the client */
  9299. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9300. if (ret != 0)
  9301. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9302. return ret;
  9303. }
  9304. /* return length after writing the ech */
  9305. static int TLSX_ECH_Write(WOLFSSL_ECH* ech, byte* writeBuf, word16* offset)
  9306. {
  9307. int ret = 0;
  9308. int rngRet = -1;
  9309. word32 configsLen = 0;
  9310. void* ephemeralKey = NULL;
  9311. byte* writeBuf_p = writeBuf;
  9312. #ifdef WOLFSSL_SMALL_STACK
  9313. Hpke* hpke = NULL;
  9314. WC_RNG* rng = NULL;
  9315. #else
  9316. Hpke hpke[1];
  9317. WC_RNG rng[1];
  9318. #endif
  9319. WOLFSSL_MSG("TLSX_ECH_Write");
  9320. if (ech->state == ECH_WRITE_NONE || ech->state == ECH_PARSED_INTERNAL)
  9321. return 0;
  9322. if (ech->state == ECH_WRITE_RETRY_CONFIGS) {
  9323. /* get size then write */
  9324. ret = GetEchConfigsEx(ech->echConfig, NULL, &configsLen);
  9325. if (ret != LENGTH_ONLY_E)
  9326. return ret;
  9327. ret = GetEchConfigsEx(ech->echConfig, writeBuf, &configsLen);
  9328. if (ret != WOLFSSL_SUCCESS)
  9329. return ret;
  9330. *offset += configsLen;
  9331. return 0;
  9332. }
  9333. #ifdef WOLFSSL_SMALL_STACK
  9334. hpke = (Hpke*)XMALLOC(sizeof(Hpke), NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9335. if (hpke == NULL)
  9336. return MEMORY_E;
  9337. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  9338. if (rng == NULL) {
  9339. XFREE(hpke, NULL, DYNAMIC_TYPE_RNG);
  9340. return MEMORY_E;
  9341. }
  9342. #endif
  9343. /* type */
  9344. *writeBuf_p = ech->type;
  9345. writeBuf_p += sizeof(ech->type);
  9346. /* outer has body, inner does not */
  9347. if (ech->type == ECH_TYPE_OUTER) {
  9348. /* kdfId */
  9349. c16toa(ech->cipherSuite.kdfId, writeBuf_p);
  9350. writeBuf_p += sizeof(ech->cipherSuite.kdfId);
  9351. /* aeadId */
  9352. c16toa(ech->cipherSuite.aeadId, writeBuf_p);
  9353. writeBuf_p += sizeof(ech->cipherSuite.aeadId);
  9354. /* configId */
  9355. *writeBuf_p = ech->configId;
  9356. writeBuf_p += sizeof(ech->configId);
  9357. /* encLen */
  9358. c16toa(ech->encLen, writeBuf_p);
  9359. writeBuf_p += 2;
  9360. if (ech->state == ECH_WRITE_GREASE) {
  9361. /* hpke init */
  9362. ret = wc_HpkeInit(hpke, ech->kemId, ech->cipherSuite.kdfId,
  9363. ech->cipherSuite.aeadId, NULL);
  9364. if (ret == 0)
  9365. rngRet = ret = wc_InitRng(rng);
  9366. /* create the ephemeralKey */
  9367. if (ret == 0)
  9368. ret = wc_HpkeGenerateKeyPair(hpke, &ephemeralKey, rng);
  9369. /* enc */
  9370. if (ret == 0) {
  9371. ret = wc_HpkeSerializePublicKey(hpke, ephemeralKey, writeBuf_p,
  9372. &ech->encLen);
  9373. writeBuf_p += ech->encLen;
  9374. }
  9375. if (ret == 0) {
  9376. /* innerClientHelloLen */
  9377. c16toa(GREASE_ECH_SIZE + ((writeBuf_p + 2 - writeBuf) % 32),
  9378. writeBuf_p);
  9379. writeBuf_p += 2;
  9380. /* innerClientHello */
  9381. ret = wc_RNG_GenerateBlock(rng, writeBuf_p, GREASE_ECH_SIZE +
  9382. ((writeBuf_p - writeBuf) % 32));
  9383. writeBuf_p += GREASE_ECH_SIZE + ((writeBuf_p - writeBuf) % 32);
  9384. }
  9385. if (rngRet == 0)
  9386. wc_FreeRng(rng);
  9387. if (ephemeralKey != NULL)
  9388. wc_HpkeFreeKey(hpke, hpke->kem, ephemeralKey, hpke->heap);
  9389. }
  9390. else {
  9391. /* write enc to writeBuf_p */
  9392. ret = wc_HpkeSerializePublicKey(ech->hpke, ech->ephemeralKey,
  9393. writeBuf_p, &ech->encLen);
  9394. writeBuf_p += ech->encLen;
  9395. /* innerClientHelloLen */
  9396. c16toa(ech->innerClientHelloLen, writeBuf_p);
  9397. writeBuf_p += 2;
  9398. /* set payload offset for when we finalize */
  9399. ech->outerClientPayload = writeBuf_p;
  9400. /* write zeros for payload */
  9401. XMEMSET(writeBuf_p, 0, ech->innerClientHelloLen);
  9402. writeBuf_p += ech->innerClientHelloLen;
  9403. }
  9404. }
  9405. #ifdef WOLFSSL_SMALL_STACK
  9406. XFREE(hpke, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9407. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  9408. #endif
  9409. if (ret == 0)
  9410. *offset += (writeBuf_p - writeBuf);
  9411. return ret;
  9412. }
  9413. /* return the size needed for the ech extension */
  9414. static int TLSX_ECH_GetSize(WOLFSSL_ECH* ech)
  9415. {
  9416. int ret;
  9417. word32 size;
  9418. if (ech->state == ECH_WRITE_GREASE) {
  9419. size = sizeof(ech->type) + sizeof(ech->cipherSuite) +
  9420. sizeof(ech->configId) + sizeof(word16) + ech->encLen +
  9421. sizeof(word16);
  9422. size += GREASE_ECH_SIZE + (size % 32);
  9423. }
  9424. else if (ech->state == ECH_WRITE_NONE ||
  9425. ech->state == ECH_PARSED_INTERNAL) {
  9426. size = 0;
  9427. }
  9428. else if (ech->state == ECH_WRITE_RETRY_CONFIGS) {
  9429. /* get the size of the raw configs */
  9430. ret = GetEchConfigsEx(ech->echConfig, NULL, &size);
  9431. if (ret != LENGTH_ONLY_E)
  9432. return ret;
  9433. }
  9434. else if (ech->type == ECH_TYPE_INNER)
  9435. {
  9436. size = sizeof(ech->type);
  9437. }
  9438. else
  9439. {
  9440. size = sizeof(ech->type) + sizeof(ech->cipherSuite) +
  9441. sizeof(ech->configId) + sizeof(word16) + ech->encLen +
  9442. sizeof(word16) + ech->innerClientHelloLen;
  9443. }
  9444. return (int)size;
  9445. }
  9446. /* return status after attempting to open the hpke encrypted ech extension, if
  9447. * successful the inner client hello will be stored in
  9448. * ech->innerClientHelloLen */
  9449. static int TLSX_ExtractEch(WOLFSSL_ECH* ech, WOLFSSL_EchConfig* echConfig,
  9450. byte* aad, word32 aadLen, void* heap)
  9451. {
  9452. int ret = 0;
  9453. int expectedEncLen;
  9454. int i;
  9455. word32 rawConfigLen = 0;
  9456. byte* info = NULL;
  9457. word32 infoLen = 0;
  9458. if (ech == NULL || echConfig == NULL || aad == NULL)
  9459. return BAD_FUNC_ARG;
  9460. /* verify the kem and key len */
  9461. switch (echConfig->kemId)
  9462. {
  9463. case DHKEM_P256_HKDF_SHA256:
  9464. expectedEncLen = DHKEM_P256_ENC_LEN;
  9465. break;
  9466. case DHKEM_P384_HKDF_SHA384:
  9467. expectedEncLen = DHKEM_P384_ENC_LEN;
  9468. break;
  9469. case DHKEM_P521_HKDF_SHA512:
  9470. expectedEncLen = DHKEM_P521_ENC_LEN;
  9471. break;
  9472. case DHKEM_X25519_HKDF_SHA256:
  9473. expectedEncLen = DHKEM_X25519_ENC_LEN;
  9474. break;
  9475. case DHKEM_X448_HKDF_SHA512:
  9476. expectedEncLen = DHKEM_X448_ENC_LEN;
  9477. break;
  9478. default:
  9479. expectedEncLen = 0;
  9480. break;
  9481. }
  9482. if (expectedEncLen != ech->encLen)
  9483. return BAD_FUNC_ARG;
  9484. /* verify the cipher suite */
  9485. for (i = 0; i < echConfig->numCipherSuites; i++) {
  9486. if (echConfig->cipherSuites[i].kdfId == ech->cipherSuite.kdfId &&
  9487. echConfig->cipherSuites[i].aeadId == ech->cipherSuite.aeadId) {
  9488. break;
  9489. }
  9490. }
  9491. if (i >= echConfig->numCipherSuites) {
  9492. return BAD_FUNC_ARG;
  9493. }
  9494. ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER);
  9495. if (ech->hpke == NULL)
  9496. return MEMORY_E;
  9497. ret = wc_HpkeInit(ech->hpke, echConfig->kemId, ech->cipherSuite.kdfId,
  9498. ech->cipherSuite.aeadId, heap);
  9499. /* get the rawConfigLen */
  9500. if (ret == 0)
  9501. ret = GetEchConfig(echConfig, NULL, &rawConfigLen);
  9502. if (ret == LENGTH_ONLY_E)
  9503. ret = 0;
  9504. /* create info */
  9505. if (ret == 0) {
  9506. infoLen = TLS_INFO_CONST_STRING_SZ + 1 + rawConfigLen;
  9507. info = (byte*)XMALLOC(infoLen, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9508. if (info == NULL)
  9509. ret = MEMORY_E;
  9510. else {
  9511. XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING,
  9512. TLS_INFO_CONST_STRING_SZ + 1);
  9513. ret = GetEchConfig(echConfig, info +
  9514. TLS_INFO_CONST_STRING_SZ + 1, &rawConfigLen);
  9515. }
  9516. }
  9517. /* decrypt the ech payload */
  9518. if (ret == 0)
  9519. ret = wc_HpkeOpenBase(ech->hpke, echConfig->receiverPrivkey, ech->enc,
  9520. ech->encLen, info, infoLen, aad, aadLen, ech->outerClientPayload,
  9521. ech->innerClientHelloLen,
  9522. ech->innerClientHello + HANDSHAKE_HEADER_SZ);
  9523. if (ret != 0) {
  9524. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9525. ech->hpke = NULL;
  9526. }
  9527. if (info != NULL)
  9528. XFREE(info, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9529. return ret;
  9530. }
  9531. /* parse the ech extension, if internal update ech->state and return, if
  9532. * external attempt to extract the inner client_hello, return the status */
  9533. static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size,
  9534. byte msgType)
  9535. {
  9536. int ret = 0;
  9537. int i;
  9538. TLSX* echX;
  9539. WOLFSSL_ECH* ech;
  9540. WOLFSSL_EchConfig* echConfig;
  9541. byte* aadCopy;
  9542. byte* readBuf_p = (byte*)readBuf;
  9543. WOLFSSL_MSG("TLSX_ECH_Parse");
  9544. if (size == 0)
  9545. return BAD_FUNC_ARG;
  9546. if (msgType == encrypted_extensions) {
  9547. ret = wolfSSL_SetEchConfigs(ssl, readBuf, size);
  9548. if (ret == WOLFSSL_SUCCESS)
  9549. ret = 0;
  9550. }
  9551. else if (msgType == client_hello && ssl->ctx->echConfigs != NULL) {
  9552. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  9553. if (echX == NULL)
  9554. return BAD_FUNC_ARG;
  9555. ech = (WOLFSSL_ECH*)echX->data;
  9556. /* read the ech parameters before the payload */
  9557. ech->type = *readBuf_p;
  9558. readBuf_p++;
  9559. if (ech->type == ECH_TYPE_INNER) {
  9560. ech->state = ECH_PARSED_INTERNAL;
  9561. return 0;
  9562. }
  9563. /* technically the payload would only be 1 byte at this length */
  9564. if (size < 11 + ech->encLen)
  9565. return BAD_FUNC_ARG;
  9566. ato16(readBuf_p, &ech->cipherSuite.kdfId);
  9567. readBuf_p += 2;
  9568. ato16(readBuf_p, &ech->cipherSuite.aeadId);
  9569. readBuf_p += 2;
  9570. ech->configId = *readBuf_p;
  9571. readBuf_p++;
  9572. ato16(readBuf_p, &ech->encLen);
  9573. readBuf_p += 2;
  9574. if (ech->encLen > HPKE_Npk_MAX)
  9575. return BAD_FUNC_ARG;
  9576. XMEMCPY(ech->enc, readBuf_p, ech->encLen);
  9577. readBuf_p += ech->encLen;
  9578. ato16(readBuf_p, &ech->innerClientHelloLen);
  9579. ech->innerClientHelloLen -= AES_BLOCK_SIZE;
  9580. readBuf_p += 2;
  9581. ech->outerClientPayload = readBuf_p;
  9582. /* make a copy of the aad */
  9583. aadCopy = (byte*)XMALLOC(ech->aadLen, ssl->heap,
  9584. DYNAMIC_TYPE_TMP_BUFFER);
  9585. if (aadCopy == NULL)
  9586. return MEMORY_E;
  9587. XMEMCPY(aadCopy, ech->aad, ech->aadLen);
  9588. /* set the ech payload of the copy to zeros */
  9589. XMEMSET(aadCopy + (readBuf_p - ech->aad), 0,
  9590. ech->innerClientHelloLen + AES_BLOCK_SIZE);
  9591. /* allocate the inner payload buffer */
  9592. ech->innerClientHello =
  9593. (byte*)XMALLOC(ech->innerClientHelloLen + HANDSHAKE_HEADER_SZ,
  9594. ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9595. if (ech->innerClientHello == NULL) {
  9596. XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9597. return MEMORY_E;
  9598. }
  9599. /* first check if the config id matches */
  9600. echConfig = ssl->ctx->echConfigs;
  9601. while (echConfig != NULL) {
  9602. /* decrypt with this config */
  9603. if (echConfig->configId == ech->configId) {
  9604. ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen,
  9605. ssl->heap);
  9606. break;
  9607. }
  9608. echConfig = echConfig->next;
  9609. }
  9610. /* try to decrypt with all configs */
  9611. if (echConfig == NULL || ret != 0) {
  9612. echConfig = ssl->ctx->echConfigs;
  9613. while (echConfig != NULL) {
  9614. ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen,
  9615. ssl->heap);
  9616. if (ret== 0)
  9617. break;
  9618. echConfig = echConfig->next;
  9619. }
  9620. }
  9621. /* if we failed to extract */
  9622. if (ret != 0) {
  9623. XFREE(ech->innerClientHello, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9624. ech->innerClientHello = NULL;
  9625. ech->state = ECH_WRITE_RETRY_CONFIGS;
  9626. }
  9627. else {
  9628. i = 0;
  9629. /* decrement until before the padding */
  9630. while (ech->innerClientHello[ech->innerClientHelloLen +
  9631. HANDSHAKE_HEADER_SZ - i - 1] != ECH_TYPE_INNER) {
  9632. i++;
  9633. }
  9634. /* subtract the length of the padding from the length */
  9635. ech->innerClientHelloLen -= i;
  9636. }
  9637. XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9638. return 0;
  9639. }
  9640. return ret;
  9641. }
  9642. /* free the ech struct and the dynamic buffer it uses */
  9643. static void TLSX_ECH_Free(WOLFSSL_ECH* ech, void* heap)
  9644. {
  9645. if (ech->innerClientHello != NULL)
  9646. XFREE(ech->innerClientHello, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9647. if (ech->ephemeralKey != NULL)
  9648. wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, ech->ephemeralKey,
  9649. ech->hpke->heap);
  9650. if (ech->hpke != NULL)
  9651. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9652. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9653. (void)heap;
  9654. }
  9655. /* encrypt the client hello and store it in ech->outerClientPayload, return
  9656. * status */
  9657. int TLSX_FinalizeEch(WOLFSSL_ECH* ech, byte* aad, word32 aadLen)
  9658. {
  9659. int ret;
  9660. void* receiverPubkey = NULL;
  9661. byte* info;
  9662. int infoLen;
  9663. byte* aadCopy;
  9664. /* import the server public key */
  9665. ret = wc_HpkeDeserializePublicKey(ech->hpke, &receiverPubkey,
  9666. ech->echConfig->receiverPubkey, ech->encLen);
  9667. if (ret == 0) {
  9668. /* create info */
  9669. infoLen = TLS_INFO_CONST_STRING_SZ + 1 + ech->echConfig->rawLen;
  9670. info = (byte*)XMALLOC(infoLen, ech->hpke->heap,
  9671. DYNAMIC_TYPE_TMP_BUFFER);
  9672. if (info == NULL)
  9673. ret = MEMORY_E;
  9674. if (ret == 0) {
  9675. /* puts the null byte in for me */
  9676. XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING, TLS_INFO_CONST_STRING_SZ
  9677. + 1);
  9678. XMEMCPY(info + TLS_INFO_CONST_STRING_SZ + 1, ech->echConfig->raw,
  9679. ech->echConfig->rawLen);
  9680. /* make a copy of the aad since we overwrite it */
  9681. aadCopy = (byte*)XMALLOC(aadLen, ech->hpke->heap,
  9682. DYNAMIC_TYPE_TMP_BUFFER);
  9683. if (aadCopy == NULL) {
  9684. XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9685. ret = MEMORY_E;
  9686. }
  9687. }
  9688. if (ret == 0) {
  9689. XMEMCPY(aadCopy, aad, aadLen);
  9690. /* seal the payload */
  9691. ret = wc_HpkeSealBase(ech->hpke, ech->ephemeralKey, receiverPubkey,
  9692. info, infoLen, aadCopy, aadLen, ech->innerClientHello,
  9693. ech->innerClientHelloLen - ech->hpke->Nt,
  9694. ech->outerClientPayload);
  9695. XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9696. XFREE(aadCopy, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9697. }
  9698. }
  9699. if (receiverPubkey != NULL)
  9700. wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, receiverPubkey,
  9701. ech->hpke->heap);
  9702. return ret;
  9703. }
  9704. #define GREASE_ECH_USE TLSX_GreaseECH_Use
  9705. #define ECH_USE TLSX_ECH_Use
  9706. #define SERVER_ECH_USE TLSX_ServerECH_Use
  9707. #define ECH_WRITE TLSX_ECH_Write
  9708. #define ECH_GET_SIZE TLSX_ECH_GetSize
  9709. #define ECH_PARSE TLSX_ECH_Parse
  9710. #define ECH_FREE TLSX_ECH_Free
  9711. #endif
  9712. /** Releases all extensions in the provided list. */
  9713. void TLSX_FreeAll(TLSX* list, void* heap)
  9714. {
  9715. TLSX* extension;
  9716. while ((extension = list)) {
  9717. list = extension->next;
  9718. switch (extension->type) {
  9719. #ifdef HAVE_SNI
  9720. case TLSX_SERVER_NAME:
  9721. SNI_FREE_ALL((SNI*)extension->data, heap);
  9722. break;
  9723. #endif
  9724. case TLSX_TRUSTED_CA_KEYS:
  9725. TCA_FREE_ALL((TCA*)extension->data, heap);
  9726. break;
  9727. case TLSX_MAX_FRAGMENT_LENGTH:
  9728. MFL_FREE_ALL(extension->data, heap);
  9729. break;
  9730. case TLSX_EXTENDED_MASTER_SECRET:
  9731. case TLSX_TRUNCATED_HMAC:
  9732. /* Nothing to do. */
  9733. break;
  9734. case TLSX_SUPPORTED_GROUPS:
  9735. EC_FREE_ALL((SupportedCurve*)extension->data, heap);
  9736. break;
  9737. case TLSX_EC_POINT_FORMATS:
  9738. PF_FREE_ALL((PointFormat*)extension->data, heap);
  9739. break;
  9740. case TLSX_STATUS_REQUEST:
  9741. CSR_FREE_ALL((CertificateStatusRequest*)extension->data, heap);
  9742. break;
  9743. case TLSX_STATUS_REQUEST_V2:
  9744. CSR2_FREE_ALL((CertificateStatusRequestItemV2*)extension->data,
  9745. heap);
  9746. break;
  9747. case TLSX_RENEGOTIATION_INFO:
  9748. SCR_FREE_ALL(extension->data, heap);
  9749. break;
  9750. case TLSX_SESSION_TICKET:
  9751. WOLF_STK_FREE(extension->data, heap);
  9752. break;
  9753. case TLSX_APPLICATION_LAYER_PROTOCOL:
  9754. ALPN_FREE_ALL((ALPN*)extension->data, heap);
  9755. break;
  9756. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  9757. case TLSX_SIGNATURE_ALGORITHMS:
  9758. SA_FREE_ALL((SignatureAlgorithms*)extension->data, heap);
  9759. break;
  9760. #endif
  9761. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  9762. case TLSX_ENCRYPT_THEN_MAC:
  9763. break;
  9764. #endif
  9765. #ifdef WOLFSSL_TLS13
  9766. case TLSX_SUPPORTED_VERSIONS:
  9767. break;
  9768. #ifdef WOLFSSL_SEND_HRR_COOKIE
  9769. case TLSX_COOKIE:
  9770. CKE_FREE_ALL((Cookie*)extension->data, heap);
  9771. break;
  9772. #endif
  9773. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  9774. case TLSX_PRE_SHARED_KEY:
  9775. PSK_FREE_ALL((PreSharedKey*)extension->data, heap);
  9776. break;
  9777. case TLSX_PSK_KEY_EXCHANGE_MODES:
  9778. break;
  9779. #endif
  9780. #ifdef WOLFSSL_EARLY_DATA
  9781. case TLSX_EARLY_DATA:
  9782. break;
  9783. #endif
  9784. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  9785. case TLSX_POST_HANDSHAKE_AUTH:
  9786. break;
  9787. #endif
  9788. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  9789. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  9790. break;
  9791. #endif
  9792. case TLSX_KEY_SHARE:
  9793. KS_FREE_ALL((KeyShareEntry*)extension->data, heap);
  9794. break;
  9795. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  9796. case TLSX_CERTIFICATE_AUTHORITIES:
  9797. break;
  9798. #endif
  9799. #endif
  9800. #ifdef WOLFSSL_SRTP
  9801. case TLSX_USE_SRTP:
  9802. SRTP_FREE((TlsxSrtp*)extension->data, heap);
  9803. break;
  9804. #endif
  9805. #ifdef WOLFSSL_QUIC
  9806. case TLSX_KEY_QUIC_TP_PARAMS:
  9807. FALL_THROUGH;
  9808. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  9809. QTP_FREE((QuicTransportParam*)extension->data, heap);
  9810. break;
  9811. #endif
  9812. #ifdef WOLFSSL_DTLS_CID
  9813. case TLSX_CONNECTION_ID:
  9814. CID_FREE((byte*)extension->data, heap);
  9815. break;
  9816. #endif /* WOLFSSL_DTLS_CID */
  9817. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  9818. case TLSX_ECH:
  9819. ECH_FREE((WOLFSSL_ECH*)extension->data, heap);
  9820. break;
  9821. #endif
  9822. default:
  9823. break;
  9824. }
  9825. XFREE(extension, heap, DYNAMIC_TYPE_TLSX);
  9826. }
  9827. (void)heap;
  9828. }
  9829. /** Checks if the tls extensions are supported based on the protocol version. */
  9830. int TLSX_SupportExtensions(WOLFSSL* ssl) {
  9831. return ssl && (IsTLS(ssl) || ssl->version.major == DTLS_MAJOR);
  9832. }
  9833. /** Tells the buffered size of the extensions in a list. */
  9834. static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType,
  9835. word16* pLength)
  9836. {
  9837. int ret = 0;
  9838. TLSX* extension;
  9839. word16 length = 0;
  9840. byte isRequest = (msgType == client_hello ||
  9841. msgType == certificate_request);
  9842. while ((extension = list)) {
  9843. list = extension->next;
  9844. /* only extensions marked as response are sent back to the client. */
  9845. if (!isRequest && !extension->resp)
  9846. continue; /* skip! */
  9847. /* ssl level extensions are expected to override ctx level ones. */
  9848. if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type)))
  9849. continue; /* skip! */
  9850. /* extension type + extension data length. */
  9851. length += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN;
  9852. switch (extension->type) {
  9853. #ifdef HAVE_SNI
  9854. case TLSX_SERVER_NAME:
  9855. /* SNI only sends the name on the request. */
  9856. if (isRequest)
  9857. length += SNI_GET_SIZE((SNI*)extension->data);
  9858. break;
  9859. #endif
  9860. case TLSX_TRUSTED_CA_KEYS:
  9861. /* TCA only sends the list on the request. */
  9862. if (isRequest)
  9863. length += TCA_GET_SIZE((TCA*)extension->data);
  9864. break;
  9865. case TLSX_MAX_FRAGMENT_LENGTH:
  9866. length += MFL_GET_SIZE(extension->data);
  9867. break;
  9868. case TLSX_EXTENDED_MASTER_SECRET:
  9869. case TLSX_TRUNCATED_HMAC:
  9870. /* always empty. */
  9871. break;
  9872. case TLSX_SUPPORTED_GROUPS:
  9873. length += EC_GET_SIZE((SupportedCurve*)extension->data);
  9874. break;
  9875. case TLSX_EC_POINT_FORMATS:
  9876. length += PF_GET_SIZE((PointFormat*)extension->data);
  9877. break;
  9878. case TLSX_STATUS_REQUEST:
  9879. length += CSR_GET_SIZE(
  9880. (CertificateStatusRequest*)extension->data, isRequest);
  9881. break;
  9882. case TLSX_STATUS_REQUEST_V2:
  9883. length += CSR2_GET_SIZE(
  9884. (CertificateStatusRequestItemV2*)extension->data,
  9885. isRequest);
  9886. break;
  9887. case TLSX_RENEGOTIATION_INFO:
  9888. length += SCR_GET_SIZE((SecureRenegotiation*)extension->data,
  9889. isRequest);
  9890. break;
  9891. case TLSX_SESSION_TICKET:
  9892. length += WOLF_STK_GET_SIZE((SessionTicket*)extension->data,
  9893. isRequest);
  9894. break;
  9895. case TLSX_APPLICATION_LAYER_PROTOCOL:
  9896. length += ALPN_GET_SIZE((ALPN*)extension->data);
  9897. break;
  9898. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  9899. case TLSX_SIGNATURE_ALGORITHMS:
  9900. length += SA_GET_SIZE(extension->data);
  9901. break;
  9902. #endif
  9903. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  9904. case TLSX_ENCRYPT_THEN_MAC:
  9905. ret = ETM_GET_SIZE(msgType, &length);
  9906. break;
  9907. #endif /* HAVE_ENCRYPT_THEN_MAC */
  9908. #ifdef WOLFSSL_TLS13
  9909. case TLSX_SUPPORTED_VERSIONS:
  9910. ret = SV_GET_SIZE(extension->data, msgType, &length);
  9911. break;
  9912. #ifdef WOLFSSL_SEND_HRR_COOKIE
  9913. case TLSX_COOKIE:
  9914. ret = CKE_GET_SIZE((Cookie*)extension->data, msgType, &length);
  9915. break;
  9916. #endif
  9917. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  9918. case TLSX_PRE_SHARED_KEY:
  9919. ret = PSK_GET_SIZE((PreSharedKey*)extension->data, msgType,
  9920. &length);
  9921. break;
  9922. case TLSX_PSK_KEY_EXCHANGE_MODES:
  9923. ret = PKM_GET_SIZE((byte)extension->val, msgType, &length);
  9924. break;
  9925. #endif
  9926. #ifdef WOLFSSL_EARLY_DATA
  9927. case TLSX_EARLY_DATA:
  9928. ret = EDI_GET_SIZE(msgType, &length);
  9929. break;
  9930. #endif
  9931. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  9932. case TLSX_POST_HANDSHAKE_AUTH:
  9933. ret = PHA_GET_SIZE(msgType, &length);
  9934. break;
  9935. #endif
  9936. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  9937. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  9938. length += SAC_GET_SIZE(extension->data);
  9939. break;
  9940. #endif
  9941. case TLSX_KEY_SHARE:
  9942. length += KS_GET_SIZE((KeyShareEntry*)extension->data, msgType);
  9943. break;
  9944. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  9945. case TLSX_CERTIFICATE_AUTHORITIES:
  9946. length += CAN_GET_SIZE(extension->data);
  9947. break;
  9948. #endif
  9949. #endif
  9950. #ifdef WOLFSSL_SRTP
  9951. case TLSX_USE_SRTP:
  9952. length += SRTP_GET_SIZE((TlsxSrtp*)extension->data);
  9953. break;
  9954. #endif
  9955. #ifdef WOLFSSL_QUIC
  9956. case TLSX_KEY_QUIC_TP_PARAMS:
  9957. FALL_THROUGH; /* followed by */
  9958. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  9959. length += QTP_GET_SIZE(extension);
  9960. break;
  9961. #endif
  9962. #ifdef WOLFSSL_DTLS_CID
  9963. case TLSX_CONNECTION_ID:
  9964. length += CID_GET_SIZE((byte*)extension->data);
  9965. break;
  9966. #endif /* WOLFSSL_DTLS_CID */
  9967. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  9968. case TLSX_ECH:
  9969. length += ECH_GET_SIZE((WOLFSSL_ECH*)extension->data);
  9970. break;
  9971. #endif
  9972. default:
  9973. break;
  9974. }
  9975. /* marks the extension as processed so ctx level */
  9976. /* extensions don't overlap with ssl level ones. */
  9977. TURN_ON(semaphore, TLSX_ToSemaphore(extension->type));
  9978. }
  9979. *pLength += length;
  9980. return ret;
  9981. }
  9982. /** Writes the extensions of a list in a buffer. */
  9983. static int TLSX_Write(TLSX* list, byte* output, byte* semaphore,
  9984. byte msgType, word16* pOffset)
  9985. {
  9986. int ret = 0;
  9987. TLSX* extension;
  9988. word16 offset = 0;
  9989. word16 length_offset = 0;
  9990. byte isRequest = (msgType == client_hello ||
  9991. msgType == certificate_request);
  9992. while ((extension = list)) {
  9993. list = extension->next;
  9994. /* only extensions marked as response are written in a response. */
  9995. if (!isRequest && !extension->resp)
  9996. continue; /* skip! */
  9997. /* ssl level extensions are expected to override ctx level ones. */
  9998. if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type)))
  9999. continue; /* skip! */
  10000. /* writes extension type. */
  10001. c16toa(extension->type, output + offset);
  10002. offset += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN;
  10003. length_offset = offset;
  10004. /* extension data should be written internally. */
  10005. switch (extension->type) {
  10006. #ifdef HAVE_SNI
  10007. case TLSX_SERVER_NAME:
  10008. if (isRequest) {
  10009. WOLFSSL_MSG("SNI extension to write");
  10010. offset += SNI_WRITE((SNI*)extension->data, output + offset);
  10011. }
  10012. break;
  10013. #endif
  10014. case TLSX_TRUSTED_CA_KEYS:
  10015. WOLFSSL_MSG("Trusted CA Indication extension to write");
  10016. if (isRequest) {
  10017. offset += TCA_WRITE((TCA*)extension->data, output + offset);
  10018. }
  10019. break;
  10020. case TLSX_MAX_FRAGMENT_LENGTH:
  10021. WOLFSSL_MSG("Max Fragment Length extension to write");
  10022. offset += MFL_WRITE((byte*)extension->data, output + offset);
  10023. break;
  10024. case TLSX_EXTENDED_MASTER_SECRET:
  10025. WOLFSSL_MSG("Extended Master Secret");
  10026. /* always empty. */
  10027. break;
  10028. case TLSX_TRUNCATED_HMAC:
  10029. WOLFSSL_MSG("Truncated HMAC extension to write");
  10030. /* always empty. */
  10031. break;
  10032. case TLSX_SUPPORTED_GROUPS:
  10033. WOLFSSL_MSG("Supported Groups extension to write");
  10034. offset += EC_WRITE((SupportedCurve*)extension->data,
  10035. output + offset);
  10036. break;
  10037. case TLSX_EC_POINT_FORMATS:
  10038. WOLFSSL_MSG("Point Formats extension to write");
  10039. offset += PF_WRITE((PointFormat*)extension->data,
  10040. output + offset);
  10041. break;
  10042. case TLSX_STATUS_REQUEST:
  10043. WOLFSSL_MSG("Certificate Status Request extension to write");
  10044. offset += CSR_WRITE((CertificateStatusRequest*)extension->data,
  10045. output + offset, isRequest);
  10046. break;
  10047. case TLSX_STATUS_REQUEST_V2:
  10048. WOLFSSL_MSG("Certificate Status Request v2 extension to write");
  10049. offset += CSR2_WRITE(
  10050. (CertificateStatusRequestItemV2*)extension->data,
  10051. output + offset, isRequest);
  10052. break;
  10053. case TLSX_RENEGOTIATION_INFO:
  10054. WOLFSSL_MSG("Secure Renegotiation extension to write");
  10055. offset += SCR_WRITE((SecureRenegotiation*)extension->data,
  10056. output + offset, isRequest);
  10057. break;
  10058. case TLSX_SESSION_TICKET:
  10059. WOLFSSL_MSG("Session Ticket extension to write");
  10060. offset += WOLF_STK_WRITE((SessionTicket*)extension->data,
  10061. output + offset, isRequest);
  10062. break;
  10063. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10064. WOLFSSL_MSG("ALPN extension to write");
  10065. offset += ALPN_WRITE((ALPN*)extension->data, output + offset);
  10066. break;
  10067. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10068. case TLSX_SIGNATURE_ALGORITHMS:
  10069. WOLFSSL_MSG("Signature Algorithms extension to write");
  10070. offset += SA_WRITE(extension->data, output + offset);
  10071. break;
  10072. #endif
  10073. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10074. case TLSX_ENCRYPT_THEN_MAC:
  10075. WOLFSSL_MSG("Encrypt-Then-Mac extension to write");
  10076. ret = ETM_WRITE(extension->data, output, msgType, &offset);
  10077. break;
  10078. #endif /* HAVE_ENCRYPT_THEN_MAC */
  10079. #ifdef WOLFSSL_TLS13
  10080. case TLSX_SUPPORTED_VERSIONS:
  10081. WOLFSSL_MSG("Supported Versions extension to write");
  10082. ret = SV_WRITE(extension->data, output + offset, msgType, &offset);
  10083. break;
  10084. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10085. case TLSX_COOKIE:
  10086. WOLFSSL_MSG("Cookie extension to write");
  10087. ret = CKE_WRITE((Cookie*)extension->data, output + offset,
  10088. msgType, &offset);
  10089. break;
  10090. #endif
  10091. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10092. case TLSX_PRE_SHARED_KEY:
  10093. WOLFSSL_MSG("Pre-Shared Key extension to write");
  10094. ret = PSK_WRITE((PreSharedKey*)extension->data, output + offset,
  10095. msgType, &offset);
  10096. break;
  10097. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10098. WOLFSSL_MSG("PSK Key Exchange Modes extension to write");
  10099. ret = PKM_WRITE((byte)extension->val, output + offset, msgType,
  10100. &offset);
  10101. break;
  10102. #endif
  10103. #ifdef WOLFSSL_EARLY_DATA
  10104. case TLSX_EARLY_DATA:
  10105. WOLFSSL_MSG("Early Data extension to write");
  10106. ret = EDI_WRITE(extension->val, output + offset, msgType,
  10107. &offset);
  10108. break;
  10109. #endif
  10110. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10111. case TLSX_POST_HANDSHAKE_AUTH:
  10112. WOLFSSL_MSG("Post-Handshake Authentication extension to write");
  10113. ret = PHA_WRITE(output + offset, msgType, &offset);
  10114. break;
  10115. #endif
  10116. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10117. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10118. WOLFSSL_MSG("Signature Algorithms extension to write");
  10119. offset += SAC_WRITE(extension->data, output + offset);
  10120. break;
  10121. #endif
  10122. case TLSX_KEY_SHARE:
  10123. WOLFSSL_MSG("Key Share extension to write");
  10124. offset += KS_WRITE((KeyShareEntry*)extension->data,
  10125. output + offset, msgType);
  10126. break;
  10127. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10128. case TLSX_CERTIFICATE_AUTHORITIES:
  10129. WOLFSSL_MSG("Certificate Authorities extension to write");
  10130. offset += CAN_WRITE(extension->data, output + offset);
  10131. break;
  10132. #endif
  10133. #endif
  10134. #ifdef WOLFSSL_SRTP
  10135. case TLSX_USE_SRTP:
  10136. offset += SRTP_WRITE((TlsxSrtp*)extension->data, output+offset);
  10137. break;
  10138. #endif
  10139. #ifdef WOLFSSL_QUIC
  10140. case TLSX_KEY_QUIC_TP_PARAMS:
  10141. FALL_THROUGH;
  10142. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10143. WOLFSSL_MSG("QUIC transport parameter to write");
  10144. offset += QTP_WRITE((QuicTransportParam*)extension->data,
  10145. output + offset);
  10146. break;
  10147. #endif
  10148. #ifdef WOLFSSL_DTLS_CID
  10149. case TLSX_CONNECTION_ID:
  10150. offset += CID_WRITE((byte*)extension->data, output+offset);
  10151. break;
  10152. #endif /* WOLFSSL_DTLS_CID */
  10153. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10154. case TLSX_ECH:
  10155. ret = ECH_WRITE((WOLFSSL_ECH*)extension->data,
  10156. output + offset, &offset);
  10157. break;
  10158. #endif
  10159. default:
  10160. break;
  10161. }
  10162. /* writes extension data length. */
  10163. c16toa(offset - length_offset, output + length_offset - OPAQUE16_LEN);
  10164. /* marks the extension as processed so ctx level */
  10165. /* extensions don't overlap with ssl level ones. */
  10166. TURN_ON(semaphore, TLSX_ToSemaphore(extension->type));
  10167. /* if we encountered an error propagate it */
  10168. if (ret != 0)
  10169. break;
  10170. }
  10171. *pOffset += offset;
  10172. return ret;
  10173. }
  10174. #ifdef HAVE_SUPPORTED_CURVES
  10175. /* Populates the default supported groups / curves */
  10176. static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions)
  10177. {
  10178. int ret = WOLFSSL_SUCCESS;
  10179. #ifdef WOLFSSL_TLS13
  10180. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10181. if (ssl->options.resuming && ssl->session->namedGroup != 0) {
  10182. return TLSX_UseSupportedCurve(extensions, ssl->session->namedGroup,
  10183. ssl->heap);
  10184. }
  10185. #endif
  10186. if (ssl->numGroups != 0) {
  10187. int i;
  10188. for (i = 0; i < ssl->numGroups; i++) {
  10189. ret = TLSX_UseSupportedCurve(extensions, ssl->group[i], ssl->heap);
  10190. if (ret != WOLFSSL_SUCCESS)
  10191. return ret;
  10192. }
  10193. return WOLFSSL_SUCCESS;
  10194. }
  10195. #endif /* WOLFSSL_TLS13 */
  10196. #if defined(HAVE_ECC)
  10197. /* list in order by strength, since not all servers choose by strength */
  10198. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  10199. #ifndef NO_ECC_SECP
  10200. ret = TLSX_UseSupportedCurve(extensions,
  10201. WOLFSSL_ECC_SECP521R1, ssl->heap);
  10202. if (ret != WOLFSSL_SUCCESS) return ret;
  10203. #endif
  10204. #endif
  10205. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  10206. #ifdef HAVE_ECC_BRAINPOOL
  10207. ret = TLSX_UseSupportedCurve(extensions,
  10208. WOLFSSL_ECC_BRAINPOOLP512R1, ssl->heap);
  10209. if (ret != WOLFSSL_SUCCESS) return ret;
  10210. #endif
  10211. #endif
  10212. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  10213. #ifndef NO_ECC_SECP
  10214. ret = TLSX_UseSupportedCurve(extensions,
  10215. WOLFSSL_ECC_SECP384R1, ssl->heap);
  10216. if (ret != WOLFSSL_SUCCESS) return ret;
  10217. #endif
  10218. #ifdef HAVE_ECC_BRAINPOOL
  10219. ret = TLSX_UseSupportedCurve(extensions,
  10220. WOLFSSL_ECC_BRAINPOOLP384R1, ssl->heap);
  10221. if (ret != WOLFSSL_SUCCESS) return ret;
  10222. #endif
  10223. #endif
  10224. #endif /* HAVE_ECC */
  10225. #ifndef HAVE_FIPS
  10226. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  10227. ret = TLSX_UseSupportedCurve(extensions,
  10228. WOLFSSL_ECC_X448, ssl->heap);
  10229. if (ret != WOLFSSL_SUCCESS) return ret;
  10230. #endif
  10231. #endif /* HAVE_FIPS */
  10232. #if defined(HAVE_ECC) && defined(HAVE_SUPPORTED_CURVES)
  10233. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  10234. #ifndef NO_ECC_SECP
  10235. ret = TLSX_UseSupportedCurve(extensions,
  10236. WOLFSSL_ECC_SECP256R1, ssl->heap);
  10237. if (ret != WOLFSSL_SUCCESS) return ret;
  10238. #endif
  10239. #ifdef HAVE_ECC_KOBLITZ
  10240. ret = TLSX_UseSupportedCurve(extensions,
  10241. WOLFSSL_ECC_SECP256K1, ssl->heap);
  10242. if (ret != WOLFSSL_SUCCESS) return ret;
  10243. #endif
  10244. #ifdef HAVE_ECC_BRAINPOOL
  10245. ret = TLSX_UseSupportedCurve(extensions,
  10246. WOLFSSL_ECC_BRAINPOOLP256R1, ssl->heap);
  10247. if (ret != WOLFSSL_SUCCESS) return ret;
  10248. #endif
  10249. #ifdef WOLFSSL_SM2
  10250. ret = TLSX_UseSupportedCurve(extensions,
  10251. WOLFSSL_ECC_SM2P256V1, ssl->heap);
  10252. if (ret != WOLFSSL_SUCCESS) return ret;
  10253. #endif
  10254. #endif
  10255. #endif /* HAVE_ECC */
  10256. #ifndef HAVE_FIPS
  10257. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  10258. ret = TLSX_UseSupportedCurve(extensions,
  10259. WOLFSSL_ECC_X25519, ssl->heap);
  10260. if (ret != WOLFSSL_SUCCESS) return ret;
  10261. #endif
  10262. #endif /* HAVE_FIPS */
  10263. #if defined(HAVE_ECC) && defined(HAVE_SUPPORTED_CURVES)
  10264. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  10265. #ifndef NO_ECC_SECP
  10266. ret = TLSX_UseSupportedCurve(extensions,
  10267. WOLFSSL_ECC_SECP224R1, ssl->heap);
  10268. if (ret != WOLFSSL_SUCCESS) return ret;
  10269. #endif
  10270. #ifdef HAVE_ECC_KOBLITZ
  10271. ret = TLSX_UseSupportedCurve(extensions,
  10272. WOLFSSL_ECC_SECP224K1, ssl->heap);
  10273. if (ret != WOLFSSL_SUCCESS) return ret;
  10274. #endif
  10275. #endif
  10276. #ifndef HAVE_FIPS
  10277. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  10278. #ifndef NO_ECC_SECP
  10279. ret = TLSX_UseSupportedCurve(extensions,
  10280. WOLFSSL_ECC_SECP192R1, ssl->heap);
  10281. if (ret != WOLFSSL_SUCCESS) return ret;
  10282. #endif
  10283. #ifdef HAVE_ECC_KOBLITZ
  10284. ret = TLSX_UseSupportedCurve(extensions,
  10285. WOLFSSL_ECC_SECP192K1, ssl->heap);
  10286. if (ret != WOLFSSL_SUCCESS) return ret;
  10287. #endif
  10288. #endif
  10289. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  10290. #ifndef NO_ECC_SECP
  10291. ret = TLSX_UseSupportedCurve(extensions,
  10292. WOLFSSL_ECC_SECP160R1, ssl->heap);
  10293. if (ret != WOLFSSL_SUCCESS) return ret;
  10294. #endif
  10295. #ifdef HAVE_ECC_SECPR2
  10296. ret = TLSX_UseSupportedCurve(extensions,
  10297. WOLFSSL_ECC_SECP160R2, ssl->heap);
  10298. if (ret != WOLFSSL_SUCCESS) return ret;
  10299. #endif
  10300. #ifdef HAVE_ECC_KOBLITZ
  10301. ret = TLSX_UseSupportedCurve(extensions,
  10302. WOLFSSL_ECC_SECP160K1, ssl->heap);
  10303. if (ret != WOLFSSL_SUCCESS) return ret;
  10304. #endif
  10305. #endif
  10306. #endif /* HAVE_FIPS */
  10307. #endif /* HAVE_ECC */
  10308. #ifndef NO_DH
  10309. /* Add FFDHE supported groups. */
  10310. #ifdef HAVE_FFDHE_8192
  10311. if (8192/8 >= ssl->options.minDhKeySz &&
  10312. 8192/8 <= ssl->options.maxDhKeySz) {
  10313. ret = TLSX_UseSupportedCurve(extensions,
  10314. WOLFSSL_FFDHE_8192, ssl->heap);
  10315. if (ret != WOLFSSL_SUCCESS)
  10316. return ret;
  10317. }
  10318. #endif
  10319. #ifdef HAVE_FFDHE_6144
  10320. if (6144/8 >= ssl->options.minDhKeySz &&
  10321. 6144/8 <= ssl->options.maxDhKeySz) {
  10322. ret = TLSX_UseSupportedCurve(extensions,
  10323. WOLFSSL_FFDHE_6144, ssl->heap);
  10324. if (ret != WOLFSSL_SUCCESS)
  10325. return ret;
  10326. }
  10327. #endif
  10328. #ifdef HAVE_FFDHE_4096
  10329. if (4096/8 >= ssl->options.minDhKeySz &&
  10330. 4096/8 <= ssl->options.maxDhKeySz) {
  10331. ret = TLSX_UseSupportedCurve(extensions,
  10332. WOLFSSL_FFDHE_4096, ssl->heap);
  10333. if (ret != WOLFSSL_SUCCESS)
  10334. return ret;
  10335. }
  10336. #endif
  10337. #ifdef HAVE_FFDHE_3072
  10338. if (3072/8 >= ssl->options.minDhKeySz &&
  10339. 3072/8 <= ssl->options.maxDhKeySz) {
  10340. ret = TLSX_UseSupportedCurve(extensions,
  10341. WOLFSSL_FFDHE_3072, ssl->heap);
  10342. if (ret != WOLFSSL_SUCCESS)
  10343. return ret;
  10344. }
  10345. #endif
  10346. #ifdef HAVE_FFDHE_2048
  10347. if (2048/8 >= ssl->options.minDhKeySz &&
  10348. 2048/8 <= ssl->options.maxDhKeySz) {
  10349. ret = TLSX_UseSupportedCurve(extensions,
  10350. WOLFSSL_FFDHE_2048, ssl->heap);
  10351. if (ret != WOLFSSL_SUCCESS)
  10352. return ret;
  10353. }
  10354. #endif
  10355. #endif
  10356. #ifdef HAVE_PQC
  10357. #ifdef WOLFSSL_WC_KYBER
  10358. #ifdef WOLFSSL_KYBER512
  10359. if (ret == WOLFSSL_SUCCESS)
  10360. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1,
  10361. ssl->heap);
  10362. #endif
  10363. #ifdef WOLFSSL_KYBER768
  10364. if (ret == WOLFSSL_SUCCESS)
  10365. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3,
  10366. ssl->heap);
  10367. #endif
  10368. #ifdef WOLFSSL_KYBER768
  10369. if (ret == WOLFSSL_SUCCESS)
  10370. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5,
  10371. ssl->heap);
  10372. #endif
  10373. #elif defined(HAVE_LIBOQS)
  10374. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap);
  10375. if (ret == WOLFSSL_SUCCESS)
  10376. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3,
  10377. ssl->heap);
  10378. if (ret == WOLFSSL_SUCCESS)
  10379. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5,
  10380. ssl->heap);
  10381. if (ret == WOLFSSL_SUCCESS)
  10382. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_KYBER_LEVEL1,
  10383. ssl->heap);
  10384. if (ret == WOLFSSL_SUCCESS)
  10385. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_KYBER_LEVEL3,
  10386. ssl->heap);
  10387. if (ret == WOLFSSL_SUCCESS)
  10388. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_KYBER_LEVEL5,
  10389. ssl->heap);
  10390. #elif defined(HAVE_PQM4)
  10391. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap);
  10392. #endif /* HAVE_LIBOQS */
  10393. #endif /* HAVE_PQC */
  10394. (void)ssl;
  10395. (void)extensions;
  10396. return ret;
  10397. }
  10398. #endif /* HAVE_SUPPORTED_CURVES */
  10399. int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer)
  10400. {
  10401. int ret = 0;
  10402. byte* public_key = NULL;
  10403. word16 public_key_len = 0;
  10404. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  10405. int usingPSK = 0;
  10406. #endif
  10407. #if defined(HAVE_SUPPORTED_CURVES) && defined(WOLFSSL_TLS13)
  10408. TLSX* extension = NULL;
  10409. word16 namedGroup = WOLFSSL_NAMED_GROUP_INVALID;
  10410. #endif
  10411. /* server will add extension depending on what is parsed from client */
  10412. if (!isServer) {
  10413. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10414. if (!ssl->options.disallowEncThenMac) {
  10415. ret = TLSX_EncryptThenMac_Use(ssl);
  10416. if (ret != 0)
  10417. return ret;
  10418. }
  10419. #endif
  10420. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  10421. defined(HAVE_CURVE448)) && defined(HAVE_SUPPORTED_CURVES)
  10422. if (!ssl->options.userCurves && !ssl->ctx->userCurves) {
  10423. if (TLSX_Find(ssl->ctx->extensions,
  10424. TLSX_SUPPORTED_GROUPS) == NULL) {
  10425. ret = TLSX_PopulateSupportedGroups(ssl, &ssl->extensions);
  10426. if (ret != WOLFSSL_SUCCESS)
  10427. return ret;
  10428. }
  10429. }
  10430. if ((!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade) &&
  10431. TLSX_Find(ssl->ctx->extensions, TLSX_EC_POINT_FORMATS) == NULL &&
  10432. TLSX_Find(ssl->extensions, TLSX_EC_POINT_FORMATS) == NULL) {
  10433. ret = TLSX_UsePointFormat(&ssl->extensions,
  10434. WOLFSSL_EC_PF_UNCOMPRESSED, ssl->heap);
  10435. if (ret != WOLFSSL_SUCCESS)
  10436. return ret;
  10437. }
  10438. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && HAVE_SUPPORTED_CURVES */
  10439. #ifdef WOLFSSL_SRTP
  10440. if (ssl->options.dtls && ssl->dtlsSrtpProfiles != 0) {
  10441. WOLFSSL_MSG("Adding DTLS SRTP extension");
  10442. if ((ret = TLSX_UseSRTP(&ssl->extensions, ssl->dtlsSrtpProfiles,
  10443. ssl->heap)) != 0) {
  10444. return ret;
  10445. }
  10446. }
  10447. #endif
  10448. } /* is not server */
  10449. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10450. WOLFSSL_MSG("Adding signature algorithms extension");
  10451. if ((ret = TLSX_SetSignatureAlgorithms(&ssl->extensions, ssl, ssl->heap))
  10452. != 0) {
  10453. return ret;
  10454. }
  10455. #else
  10456. ret = 0;
  10457. #endif
  10458. #ifdef WOLFSSL_TLS13
  10459. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10460. if (isServer && IsAtLeastTLSv1_3(ssl->version)) {
  10461. if (SSL_CA_NAMES(ssl) != NULL) {
  10462. WOLFSSL_MSG("Adding certificate authorities extension");
  10463. if ((ret = TLSX_Push(&ssl->extensions,
  10464. TLSX_CERTIFICATE_AUTHORITIES, ssl, ssl->heap)) != 0) {
  10465. return ret;
  10466. }
  10467. }
  10468. }
  10469. #endif
  10470. if (!isServer && IsAtLeastTLSv1_3(ssl->version)) {
  10471. /* Add mandatory TLS v1.3 extension: supported version */
  10472. WOLFSSL_MSG("Adding supported versions extension");
  10473. if ((ret = TLSX_SetSupportedVersions(&ssl->extensions, ssl,
  10474. ssl->heap)) != 0) {
  10475. return ret;
  10476. }
  10477. #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && \
  10478. !defined(HAVE_CURVE448) && defined(HAVE_SUPPORTED_CURVES)
  10479. if (TLSX_Find(ssl->ctx->extensions, TLSX_SUPPORTED_GROUPS) == NULL) {
  10480. /* Put in DH groups for TLS 1.3 only. */
  10481. ret = TLSX_PopulateSupportedGroups(ssl, &ssl->extensions);
  10482. if (ret != WOLFSSL_SUCCESS)
  10483. return ret;
  10484. /* ret value will be overwritten in !NO_PSK case */
  10485. #ifdef NO_PSK
  10486. ret = 0;
  10487. #endif
  10488. }
  10489. #endif /* !(HAVE_ECC || CURVE25519 || CURVE448) && HAVE_SUPPORTED_CURVES */
  10490. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10491. if (ssl->certHashSigAlgoSz > 0) {
  10492. WOLFSSL_MSG("Adding signature algorithms cert extension");
  10493. if ((ret = TLSX_SetSignatureAlgorithmsCert(&ssl->extensions,
  10494. ssl, ssl->heap)) != 0) {
  10495. return ret;
  10496. }
  10497. }
  10498. #endif
  10499. #if defined(HAVE_SUPPORTED_CURVES)
  10500. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  10501. if (extension == NULL) {
  10502. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10503. if (ssl->options.resuming && ssl->session->namedGroup != 0)
  10504. namedGroup = ssl->session->namedGroup;
  10505. else
  10506. #endif
  10507. if (ssl->numGroups > 0) {
  10508. int set = 0;
  10509. int i, j;
  10510. /* try to find the highest element in ssl->group[]
  10511. * that is contained in preferredGroup[].
  10512. */
  10513. namedGroup = preferredGroup[0];
  10514. for (i = 0; i < ssl->numGroups && !set; i++) {
  10515. for (j = 0; preferredGroup[j] != WOLFSSL_NAMED_GROUP_INVALID; j++) {
  10516. if (preferredGroup[j] == ssl->group[i]
  10517. #ifdef HAVE_LIBOQS
  10518. && TLSX_KeyShare_IsSupported(preferredGroup[j])
  10519. #endif
  10520. ) {
  10521. namedGroup = ssl->group[i];
  10522. set = 1;
  10523. break;
  10524. }
  10525. }
  10526. }
  10527. if (!set)
  10528. namedGroup = WOLFSSL_NAMED_GROUP_INVALID;
  10529. }
  10530. else {
  10531. /* Choose the most preferred group. */
  10532. namedGroup = preferredGroup[0];
  10533. #ifdef HAVE_LIBOQS
  10534. if (!TLSX_KeyShare_IsSupported(namedGroup)) {
  10535. int i = 1;
  10536. for (;preferredGroup[i] != WOLFSSL_NAMED_GROUP_INVALID;
  10537. i++) {
  10538. if (TLSX_KeyShare_IsSupported(preferredGroup[i]))
  10539. break;
  10540. }
  10541. namedGroup = preferredGroup[i];
  10542. }
  10543. #endif
  10544. }
  10545. }
  10546. else {
  10547. KeyShareEntry* kse = (KeyShareEntry*)extension->data;
  10548. if (kse)
  10549. namedGroup = kse->group;
  10550. }
  10551. if (namedGroup != WOLFSSL_NAMED_GROUP_INVALID) {
  10552. #ifdef HAVE_PQC
  10553. /* For KEMs, the key share has already been generated, but not
  10554. * if we are resuming. */
  10555. if (!WOLFSSL_NAMED_GROUP_IS_PQC(namedGroup)
  10556. #ifdef HAVE_SESSION_TICKET
  10557. || ssl->options.resuming
  10558. #endif /* HAVE_SESSION_TICKET */
  10559. )
  10560. #endif /* HAVE_PQC */
  10561. {
  10562. ret = TLSX_KeyShare_Use(ssl, namedGroup, 0, NULL, NULL,
  10563. &ssl->extensions);
  10564. }
  10565. if (ret != 0)
  10566. return ret;
  10567. }
  10568. #endif /* HAVE_SUPPORTED_CURVES */
  10569. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10570. TLSX_Remove(&ssl->extensions, TLSX_PRE_SHARED_KEY, ssl->heap);
  10571. #endif
  10572. #if defined(HAVE_SESSION_TICKET)
  10573. if (ssl->options.resuming && ssl->session->ticketLen > 0) {
  10574. WOLFSSL_SESSION* sess = ssl->session;
  10575. #ifdef WOLFSSL_32BIT_MILLI_TIME
  10576. word32 now, milli;
  10577. #else
  10578. word64 now, milli;
  10579. #endif
  10580. if (sess->ticketLen > MAX_PSK_ID_LEN) {
  10581. WOLFSSL_MSG("Session ticket length for PSK ext is too large");
  10582. return BUFFER_ERROR;
  10583. }
  10584. /* Determine the MAC algorithm for the cipher suite used. */
  10585. ssl->options.cipherSuite0 = sess->cipherSuite0;
  10586. ssl->options.cipherSuite = sess->cipherSuite;
  10587. ret = SetCipherSpecs(ssl);
  10588. if (ret != 0)
  10589. return ret;
  10590. now = TimeNowInMilliseconds();
  10591. if (now == 0)
  10592. return GETTIME_ERROR;
  10593. #ifdef WOLFSSL_32BIT_MILLI_TIME
  10594. if (now < sess->ticketSeen)
  10595. milli = (0xFFFFFFFFU - sess->ticketSeen) + 1 + now;
  10596. else
  10597. milli = now - sess->ticketSeen;
  10598. milli += sess->ticketAdd;
  10599. /* Pre-shared key is mandatory extension for resumption. */
  10600. ret = TLSX_PreSharedKey_Use(&ssl->extensions, sess->ticket,
  10601. sess->ticketLen, milli, ssl->specs.mac_algorithm,
  10602. ssl->options.cipherSuite0, ssl->options.cipherSuite, 1,
  10603. NULL, ssl->heap);
  10604. #else
  10605. milli = now - sess->ticketSeen + sess->ticketAdd;
  10606. /* Pre-shared key is mandatory extension for resumption. */
  10607. ret = TLSX_PreSharedKey_Use(&ssl->extensions, sess->ticket,
  10608. sess->ticketLen, (word32)milli, ssl->specs.mac_algorithm,
  10609. ssl->options.cipherSuite0, ssl->options.cipherSuite, 1,
  10610. NULL, ssl->heap);
  10611. #endif
  10612. if (ret != 0)
  10613. return ret;
  10614. usingPSK = 1;
  10615. }
  10616. #endif
  10617. #ifndef NO_PSK
  10618. #ifndef WOLFSSL_PSK_ONE_ID
  10619. if (ssl->options.client_psk_cs_cb != NULL) {
  10620. int i;
  10621. const Suites* suites = WOLFSSL_SUITES(ssl);
  10622. for (i = 0; i < suites->suiteSz; i += 2) {
  10623. byte cipherSuite0 = suites->suites[i + 0];
  10624. byte cipherSuite = suites->suites[i + 1];
  10625. unsigned int keySz;
  10626. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  10627. int cnt = 0;
  10628. #endif
  10629. #ifdef HAVE_NULL_CIPHER
  10630. if (cipherSuite0 == ECC_BYTE ||
  10631. cipherSuite0 == ECDHE_PSK_BYTE) {
  10632. if (cipherSuite != TLS_SHA256_SHA256 &&
  10633. cipherSuite != TLS_SHA384_SHA384) {
  10634. continue;
  10635. }
  10636. }
  10637. else
  10638. #endif
  10639. #if (defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)) && \
  10640. defined(WOLFSSL_SM3)
  10641. if (cipherSuite0 == CIPHER_BYTE) {
  10642. if ((cipherSuite != TLS_SM4_GCM_SM3) &&
  10643. (cipherSuite != TLS_SM4_CCM_SM3)) {
  10644. continue;
  10645. }
  10646. }
  10647. else
  10648. #endif
  10649. if (cipherSuite0 != TLS13_BYTE)
  10650. continue;
  10651. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  10652. do {
  10653. ssl->arrays->client_identity[0] = cnt;
  10654. #endif
  10655. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  10656. keySz = ssl->options.client_psk_cs_cb(
  10657. ssl, ssl->arrays->server_hint,
  10658. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  10659. ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
  10660. GetCipherNameInternal(cipherSuite0, cipherSuite));
  10661. if (keySz > 0) {
  10662. ssl->arrays->psk_keySz = keySz;
  10663. ret = TLSX_PreSharedKey_Use(&ssl->extensions,
  10664. (byte*)ssl->arrays->client_identity,
  10665. (word16)XSTRLEN(ssl->arrays->client_identity),
  10666. 0, SuiteMac(WOLFSSL_SUITES(ssl)->suites + i),
  10667. cipherSuite0, cipherSuite, 0, NULL, ssl->heap);
  10668. if (ret != 0)
  10669. return ret;
  10670. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  10671. cnt++;
  10672. #endif
  10673. }
  10674. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  10675. }
  10676. while (keySz > 0);
  10677. #endif
  10678. }
  10679. usingPSK = 1;
  10680. }
  10681. else
  10682. #endif
  10683. if (ssl->options.client_psk_cb != NULL ||
  10684. ssl->options.client_psk_tls13_cb != NULL) {
  10685. /* Default cipher suite. */
  10686. byte cipherSuite0 = TLS13_BYTE;
  10687. byte cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
  10688. int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
  10689. const char* cipherName = NULL;
  10690. if (ssl->options.client_psk_tls13_cb != NULL) {
  10691. ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(
  10692. ssl, ssl->arrays->server_hint,
  10693. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  10694. ssl->arrays->psk_key, MAX_PSK_KEY_LEN, &cipherName);
  10695. if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
  10696. &cipherSuite, &cipherSuiteFlags) != 0) {
  10697. return PSK_KEY_ERROR;
  10698. }
  10699. }
  10700. else {
  10701. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  10702. ssl->arrays->server_hint, ssl->arrays->client_identity,
  10703. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  10704. }
  10705. #if defined(OPENSSL_EXTRA)
  10706. /* OpenSSL treats 0 as a PSK key length of 0
  10707. * and meaning no PSK available.
  10708. */
  10709. if (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  10710. return PSK_KEY_ERROR;
  10711. }
  10712. if (ssl->arrays->psk_keySz > 0) {
  10713. #else
  10714. if (ssl->arrays->psk_keySz == 0 ||
  10715. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  10716. return PSK_KEY_ERROR;
  10717. }
  10718. #endif
  10719. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  10720. ssl->options.cipherSuite0 = cipherSuite0;
  10721. ssl->options.cipherSuite = cipherSuite;
  10722. (void)cipherSuiteFlags;
  10723. ret = SetCipherSpecs(ssl);
  10724. if (ret != 0)
  10725. return ret;
  10726. ret = TLSX_PreSharedKey_Use(&ssl->extensions,
  10727. (byte*)ssl->arrays->client_identity,
  10728. (word16)XSTRLEN(ssl->arrays->client_identity),
  10729. 0, ssl->specs.mac_algorithm,
  10730. cipherSuite0, cipherSuite, 0,
  10731. NULL, ssl->heap);
  10732. if (ret != 0)
  10733. return ret;
  10734. usingPSK = 1;
  10735. #if defined(OPENSSL_EXTRA)
  10736. }
  10737. #endif
  10738. }
  10739. #endif /* !NO_PSK */
  10740. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10741. /* Some servers do not generate session tickets unless
  10742. * the extension is seen in a non-resume client hello.
  10743. * We used to send it only if we were otherwise using PSK.
  10744. * Now always send it. Define NO_TLSX_PSKKEM_PLAIN_ANNOUNCE
  10745. * to revert to the old behaviour. */
  10746. #ifdef NO_TLSX_PSKKEM_PLAIN_ANNOUNCE
  10747. if (usingPSK)
  10748. #endif
  10749. {
  10750. byte modes = 0;
  10751. (void)usingPSK;
  10752. /* Pre-shared key modes: mandatory extension for resumption. */
  10753. #ifdef HAVE_SUPPORTED_CURVES
  10754. if (!ssl->options.onlyPskDheKe)
  10755. #endif
  10756. {
  10757. modes = 1 << PSK_KE;
  10758. }
  10759. #if !defined(NO_DH) || defined(HAVE_ECC) || \
  10760. defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  10761. if (!ssl->options.noPskDheKe) {
  10762. modes |= 1 << PSK_DHE_KE;
  10763. }
  10764. #endif
  10765. ret = TLSX_PskKeyModes_Use(ssl, modes);
  10766. if (ret != 0)
  10767. return ret;
  10768. }
  10769. #endif
  10770. #if defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  10771. if (!isServer && ssl->options.postHandshakeAuth) {
  10772. ret = TLSX_PostHandAuth_Use(ssl);
  10773. if (ret != 0)
  10774. return ret;
  10775. }
  10776. #endif
  10777. #if defined(HAVE_ECH)
  10778. /* GREASE ECH */
  10779. if (ssl->echConfigs == NULL) {
  10780. ret = GREASE_ECH_USE(&(ssl->extensions), ssl->heap, ssl->rng);
  10781. }
  10782. else if (ssl->echConfigs != NULL) {
  10783. ret = ECH_USE(ssl->echConfigs, &(ssl->extensions), ssl->heap,
  10784. ssl->rng);
  10785. }
  10786. #endif
  10787. }
  10788. #if defined(HAVE_ECH)
  10789. else if (IsAtLeastTLSv1_3(ssl->version)) {
  10790. if (ssl->ctx->echConfigs != NULL) {
  10791. ret = SERVER_ECH_USE(&(ssl->extensions), ssl->heap,
  10792. ssl->ctx->echConfigs);
  10793. if (ret == 0)
  10794. TLSX_SetResponse(ssl, TLSX_ECH);
  10795. }
  10796. }
  10797. #endif
  10798. #endif
  10799. (void)isServer;
  10800. (void)public_key;
  10801. (void)public_key_len;
  10802. (void)ssl;
  10803. return ret;
  10804. }
  10805. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  10806. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10807. /* because the size of ech depends on the size of other extensions we need to
  10808. * get the size with ech special and process ech last, return status */
  10809. static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType,
  10810. word16* pLength)
  10811. {
  10812. int ret = 0;
  10813. TLSX* echX = NULL;
  10814. TLSX* serverNameX = NULL;
  10815. TLSX** extensions = NULL;
  10816. #ifdef WOLFSSL_SMALL_STACK
  10817. char* tmpServerName = NULL;
  10818. #else
  10819. char tmpServerName[MAX_PUBLIC_NAME_SZ];
  10820. #endif
  10821. /* calculate the rest of the extensions length with inner ech */
  10822. if (ssl->extensions)
  10823. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  10824. if (echX == NULL && ssl->ctx && ssl->ctx->extensions)
  10825. echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH);
  10826. /* if type is outer change sni to public name */
  10827. if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) {
  10828. if (ssl->extensions) {
  10829. serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  10830. if (serverNameX != NULL)
  10831. extensions = &ssl->extensions;
  10832. }
  10833. if (serverNameX == NULL && ssl->ctx && ssl->ctx->extensions) {
  10834. serverNameX = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  10835. extensions = &ssl->ctx->extensions;
  10836. }
  10837. /* store the inner server name */
  10838. if (serverNameX != NULL) {
  10839. char* hostName = ((SNI*)serverNameX->data)->data.host_name;
  10840. word32 hostNameSz = (word32)XSTRLEN(hostName) + 1;
  10841. #ifdef WOLFSSL_SMALL_STACK
  10842. tmpServerName = (char*)XMALLOC(hostNameSz, ssl->heap,
  10843. DYNAMIC_TYPE_TMP_BUFFER);
  10844. if (tmpServerName == NULL)
  10845. return MEMORY_E;
  10846. #else
  10847. /* truncate if too long */
  10848. if (hostNameSz > MAX_PUBLIC_NAME_SZ)
  10849. hostNameSz = MAX_PUBLIC_NAME_SZ;
  10850. #endif
  10851. XMEMCPY(tmpServerName, hostName, hostNameSz);
  10852. }
  10853. /* remove the inner server name */
  10854. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  10855. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  10856. ((WOLFSSL_ECH*)echX->data)->echConfig->publicName,
  10857. XSTRLEN(((WOLFSSL_ECH*)echX->data)->echConfig->publicName),
  10858. ssl->heap);
  10859. /* set the public name as the server name */
  10860. if (ret == WOLFSSL_SUCCESS)
  10861. ret = 0;
  10862. }
  10863. if (ret == 0 && ssl->extensions)
  10864. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, pLength);
  10865. if (ret == 0 && ssl->ctx && ssl->ctx->extensions)
  10866. ret = TLSX_GetSize(ssl->ctx->extensions, semaphore, msgType, pLength);
  10867. if (serverNameX != NULL) {
  10868. /* remove the public name SNI */
  10869. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  10870. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  10871. tmpServerName, XSTRLEN(tmpServerName), ssl->heap);
  10872. /* restore the inner server name */
  10873. if (ret == WOLFSSL_SUCCESS)
  10874. ret = 0;
  10875. }
  10876. #ifdef WOLFSSL_SMALL_STACK
  10877. XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10878. #endif
  10879. return ret;
  10880. }
  10881. #endif
  10882. /** Tells the buffered size of extensions to be sent into the client hello. */
  10883. int TLSX_GetRequestSize(WOLFSSL* ssl, byte msgType, word16* pLength)
  10884. {
  10885. int ret = 0;
  10886. word16 length = 0;
  10887. byte semaphore[SEMAPHORE_SIZE] = {0};
  10888. if (!TLSX_SupportExtensions(ssl))
  10889. return 0;
  10890. if (msgType == client_hello) {
  10891. EC_VALIDATE_REQUEST(ssl, semaphore);
  10892. PF_VALIDATE_REQUEST(ssl, semaphore);
  10893. WOLF_STK_VALIDATE_REQUEST(ssl);
  10894. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10895. if (WOLFSSL_SUITES(ssl)->hashSigAlgoSz == 0)
  10896. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  10897. #endif
  10898. #if defined(WOLFSSL_TLS13)
  10899. if (!IsAtLeastTLSv1_2(ssl)) {
  10900. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  10901. }
  10902. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  10903. if (!IsAtLeastTLSv1_3(ssl->version)) {
  10904. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  10905. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10906. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  10907. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PSK_KEY_EXCHANGE_MODES));
  10908. #endif
  10909. #ifdef WOLFSSL_EARLY_DATA
  10910. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  10911. #endif
  10912. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10913. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  10914. #endif
  10915. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10916. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_POST_HANDSHAKE_AUTH));
  10917. #endif
  10918. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10919. TURN_ON(semaphore,
  10920. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  10921. #endif
  10922. }
  10923. #endif
  10924. #endif /* WOLFSSL_TLS13 */
  10925. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  10926. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  10927. if (!SSL_CM(ssl)->ocspStaplingEnabled) {
  10928. /* mark already sent, so it won't send it */
  10929. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  10930. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  10931. }
  10932. #endif
  10933. }
  10934. #ifdef WOLFSSL_TLS13
  10935. #ifndef NO_CERTS
  10936. else if (msgType == certificate_request) {
  10937. /* Don't send out any extension except those that are turned off. */
  10938. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  10939. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10940. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  10941. #endif
  10942. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10943. if (SSL_CA_NAMES(ssl) != NULL)
  10944. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  10945. #endif
  10946. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, OID_FILTERS
  10947. * TLSX_STATUS_REQUEST
  10948. */
  10949. }
  10950. #endif
  10951. #if defined(HAVE_ECH)
  10952. if (ssl->options.useEch == 1 && msgType == client_hello) {
  10953. ret = TLSX_GetSizeWithEch(ssl, semaphore, msgType, &length);
  10954. if (ret != 0)
  10955. return ret;
  10956. }
  10957. else
  10958. #endif /* HAVE_ECH */
  10959. #endif /* WOLFSSL_TLS13 */
  10960. {
  10961. if (ssl->extensions) {
  10962. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, &length);
  10963. if (ret != 0)
  10964. return ret;
  10965. }
  10966. if (ssl->ctx && ssl->ctx->extensions) {
  10967. ret = TLSX_GetSize(ssl->ctx->extensions, semaphore, msgType,
  10968. &length);
  10969. if (ret != 0)
  10970. return ret;
  10971. }
  10972. }
  10973. #ifdef HAVE_EXTENDED_MASTER
  10974. if (msgType == client_hello && ssl->options.haveEMS &&
  10975. (!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade)) {
  10976. length += HELLO_EXT_SZ;
  10977. }
  10978. #endif
  10979. if (length)
  10980. length += OPAQUE16_LEN; /* for total length storage. */
  10981. *pLength += length;
  10982. return ret;
  10983. }
  10984. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10985. /* return status after writing the extensions with ech written last */
  10986. static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore,
  10987. byte msgType, word16* pOffset)
  10988. {
  10989. int ret = 0;
  10990. TLSX* echX = NULL;
  10991. TLSX* serverNameX = NULL;
  10992. TLSX** extensions = NULL;
  10993. #ifdef WOLFSSL_SMALL_STACK
  10994. char* tmpServerName = NULL;
  10995. #else
  10996. char tmpServerName[MAX_PUBLIC_NAME_SZ];
  10997. #endif
  10998. /* get the echX from either extensions or ctx */
  10999. if (ssl->extensions)
  11000. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  11001. if (echX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11002. /* if not NULL the semaphore will stop it from being counted */
  11003. if (echX == NULL)
  11004. echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH);
  11005. }
  11006. /* if type is outer change sni to public name */
  11007. if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) {
  11008. if (ssl->extensions) {
  11009. serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  11010. if (serverNameX != NULL)
  11011. extensions = &ssl->extensions;
  11012. }
  11013. if (serverNameX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11014. serverNameX = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  11015. extensions = &ssl->ctx->extensions;
  11016. }
  11017. /* store the inner server name */
  11018. if (serverNameX != NULL) {
  11019. char* hostName = ((SNI*)serverNameX->data)->data.host_name;
  11020. word32 hostNameSz = (word32)XSTRLEN(hostName) + 1;
  11021. #ifdef WOLFSSL_SMALL_STACK
  11022. tmpServerName = (char*)XMALLOC(hostNameSz, ssl->heap,
  11023. DYNAMIC_TYPE_TMP_BUFFER);
  11024. if (tmpServerName == NULL)
  11025. return MEMORY_E;
  11026. #else
  11027. /* truncate if too long */
  11028. if (hostNameSz > MAX_PUBLIC_NAME_SZ)
  11029. hostNameSz = MAX_PUBLIC_NAME_SZ;
  11030. #endif
  11031. XMEMCPY(tmpServerName, hostName, hostNameSz);
  11032. }
  11033. /* remove the inner server name */
  11034. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11035. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11036. ((WOLFSSL_ECH*)echX->data)->echConfig->publicName,
  11037. XSTRLEN(((WOLFSSL_ECH*)echX->data)->echConfig->publicName),
  11038. ssl->heap);
  11039. /* set the public name as the server name */
  11040. if (ret == WOLFSSL_SUCCESS)
  11041. ret = 0;
  11042. }
  11043. if (echX != NULL) {
  11044. /* turn ech on so it doesn't write, then write it last */
  11045. TURN_ON(semaphore, TLSX_ToSemaphore(echX->type));
  11046. }
  11047. if (ret == 0 && ssl->extensions) {
  11048. ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore,
  11049. msgType, pOffset);
  11050. }
  11051. if (ret == 0 && ssl->ctx && ssl->ctx->extensions) {
  11052. ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore,
  11053. msgType, pOffset);
  11054. }
  11055. if (echX != NULL) {
  11056. /* turn off and write it last */
  11057. TURN_OFF(semaphore, TLSX_ToSemaphore(echX->type));
  11058. }
  11059. if (ret == 0 && ssl->extensions) {
  11060. ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore,
  11061. msgType, pOffset);
  11062. }
  11063. if (ret == 0 && ssl->ctx && ssl->ctx->extensions) {
  11064. ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore,
  11065. msgType, pOffset);
  11066. }
  11067. if (serverNameX != NULL) {
  11068. /* remove the public name SNI */
  11069. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11070. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME, tmpServerName,
  11071. XSTRLEN(tmpServerName), ssl->heap);
  11072. /* restore the inner server name */
  11073. if (ret == WOLFSSL_SUCCESS)
  11074. ret = 0;
  11075. }
  11076. #ifdef WOLFSSL_SMALL_STACK
  11077. XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11078. #endif
  11079. return ret;
  11080. }
  11081. #endif
  11082. /** Writes the extensions to be sent into the client hello. */
  11083. int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word16* pOffset)
  11084. {
  11085. int ret = 0;
  11086. word16 offset = 0;
  11087. byte semaphore[SEMAPHORE_SIZE] = {0};
  11088. if (!TLSX_SupportExtensions(ssl) || output == NULL)
  11089. return 0;
  11090. offset += OPAQUE16_LEN; /* extensions length */
  11091. if (msgType == client_hello) {
  11092. EC_VALIDATE_REQUEST(ssl, semaphore);
  11093. PF_VALIDATE_REQUEST(ssl, semaphore);
  11094. WOLF_STK_VALIDATE_REQUEST(ssl);
  11095. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11096. if (WOLFSSL_SUITES(ssl)->hashSigAlgoSz == 0)
  11097. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11098. #endif
  11099. #ifdef WOLFSSL_TLS13
  11100. if (!IsAtLeastTLSv1_2(ssl)) {
  11101. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11102. }
  11103. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11104. if (!IsAtLeastTLSv1_3(ssl->version)) {
  11105. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11106. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11107. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PSK_KEY_EXCHANGE_MODES));
  11108. #endif
  11109. #ifdef WOLFSSL_EARLY_DATA
  11110. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11111. #endif
  11112. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11113. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11114. #endif
  11115. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  11116. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_POST_HANDSHAKE_AUTH));
  11117. #endif
  11118. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11119. TURN_ON(semaphore,
  11120. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11121. #endif
  11122. }
  11123. #endif
  11124. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11125. /* Must write Pre-shared Key extension at the end in TLS v1.3.
  11126. * Must not write out Pre-shared Key extension in earlier versions of
  11127. * protocol.
  11128. */
  11129. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11130. #endif
  11131. #endif /* WOLFSSL_TLS13 */
  11132. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  11133. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  11134. /* mark already sent, so it won't send it */
  11135. if (!SSL_CM(ssl)->ocspStaplingEnabled) {
  11136. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11137. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11138. }
  11139. #endif
  11140. }
  11141. #ifdef WOLFSSL_TLS13
  11142. #ifndef NO_CERTS
  11143. else if (msgType == certificate_request) {
  11144. /* Don't send out any extension except those that are turned off. */
  11145. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11146. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11147. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11148. #endif
  11149. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11150. if (SSL_CA_NAMES(ssl) != NULL) {
  11151. TURN_OFF(semaphore,
  11152. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11153. }
  11154. #endif
  11155. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, TLSX_OID_FILTERS
  11156. * TLSX_STATUS_REQUEST
  11157. */
  11158. }
  11159. #endif
  11160. #endif
  11161. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11162. if (ssl->options.useEch == 1 && msgType == client_hello) {
  11163. ret = TLSX_WriteWithEch(ssl, output, semaphore,
  11164. msgType, &offset);
  11165. if (ret != 0)
  11166. return ret;
  11167. }
  11168. else
  11169. #endif
  11170. {
  11171. if (ssl->extensions) {
  11172. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11173. msgType, &offset);
  11174. if (ret != 0)
  11175. return ret;
  11176. }
  11177. if (ssl->ctx && ssl->ctx->extensions) {
  11178. ret = TLSX_Write(ssl->ctx->extensions, output + offset, semaphore,
  11179. msgType, &offset);
  11180. if (ret != 0)
  11181. return ret;
  11182. }
  11183. }
  11184. #ifdef HAVE_EXTENDED_MASTER
  11185. if (msgType == client_hello && ssl->options.haveEMS &&
  11186. (!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade)) {
  11187. WOLFSSL_MSG("EMS extension to write");
  11188. c16toa(HELLO_EXT_EXTMS, output + offset);
  11189. offset += HELLO_EXT_TYPE_SZ;
  11190. c16toa(0, output + offset);
  11191. offset += HELLO_EXT_SZ_SZ;
  11192. }
  11193. #endif
  11194. #ifdef WOLFSSL_TLS13
  11195. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11196. if (msgType == client_hello && IsAtLeastTLSv1_3(ssl->version)) {
  11197. /* Write out what we can of Pre-shared key extension. */
  11198. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11199. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11200. client_hello, &offset);
  11201. if (ret != 0)
  11202. return ret;
  11203. }
  11204. #endif
  11205. #endif
  11206. if (offset > OPAQUE16_LEN || msgType != client_hello)
  11207. c16toa(offset - OPAQUE16_LEN, output); /* extensions length */
  11208. *pOffset += offset;
  11209. return ret;
  11210. }
  11211. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  11212. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_SERVER)
  11213. /** Tells the buffered size of extensions to be sent into the server hello. */
  11214. int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength)
  11215. {
  11216. int ret = 0;
  11217. word16 length = 0;
  11218. byte semaphore[SEMAPHORE_SIZE] = {0};
  11219. switch (msgType) {
  11220. #ifndef NO_WOLFSSL_SERVER
  11221. case server_hello:
  11222. PF_VALIDATE_RESPONSE(ssl, semaphore);
  11223. #ifdef WOLFSSL_TLS13
  11224. if (IsAtLeastTLSv1_3(ssl->version)) {
  11225. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11226. TURN_OFF(semaphore,
  11227. TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11228. #if defined(HAVE_SUPPORTED_CURVES)
  11229. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11230. if (!ssl->options.noPskDheKe)
  11231. #endif
  11232. {
  11233. /* Expect KeyShare extension in ServerHello. */
  11234. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11235. }
  11236. #endif
  11237. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11238. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11239. #endif
  11240. #ifdef WOLFSSL_DTLS_CID
  11241. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11242. #endif
  11243. }
  11244. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11245. else {
  11246. #ifdef HAVE_SUPPORTED_CURVES
  11247. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11248. #endif
  11249. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11250. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11251. #endif
  11252. }
  11253. #endif
  11254. #endif /* WOLFSSL_TLS13 */
  11255. break;
  11256. #ifdef WOLFSSL_TLS13
  11257. case hello_retry_request:
  11258. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11259. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11260. #ifdef HAVE_SUPPORTED_CURVES
  11261. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11262. if (!ssl->options.noPskDheKe)
  11263. #endif
  11264. {
  11265. /* Expect KeyShare extension in HelloRetryRequest. */
  11266. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11267. }
  11268. #endif
  11269. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11270. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11271. #endif
  11272. break;
  11273. #endif
  11274. #ifdef WOLFSSL_TLS13
  11275. case encrypted_extensions:
  11276. /* Send out all extension except those that are turned on. */
  11277. #ifdef HAVE_ECC
  11278. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  11279. #endif
  11280. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11281. #ifdef HAVE_SESSION_TICKET
  11282. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SESSION_TICKET));
  11283. #endif
  11284. #ifdef HAVE_SUPPORTED_CURVES
  11285. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11286. #endif
  11287. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11288. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11289. #endif
  11290. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  11291. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11292. #endif
  11293. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  11294. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11295. #endif
  11296. #if defined(HAVE_SERVER_RENEGOTIATION_INFO)
  11297. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_RENEGOTIATION_INFO));
  11298. #endif
  11299. #ifdef WOLFSSL_DTLS_CID
  11300. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11301. #endif /* WOLFSSL_DTLS_CID */
  11302. break;
  11303. #ifdef WOLFSSL_EARLY_DATA
  11304. case session_ticket:
  11305. if (ssl->options.tls1_3) {
  11306. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11307. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11308. }
  11309. break;
  11310. #endif
  11311. #endif
  11312. #endif
  11313. #ifdef WOLFSSL_TLS13
  11314. #ifndef NO_CERTS
  11315. case certificate:
  11316. /* Don't send out any extension except those that are turned off. */
  11317. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11318. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11319. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP,
  11320. * TLSX_SERVER_CERTIFICATE_TYPE
  11321. */
  11322. break;
  11323. #endif
  11324. #endif
  11325. }
  11326. #ifdef HAVE_EXTENDED_MASTER
  11327. if (ssl->options.haveEMS && msgType == server_hello &&
  11328. !IsAtLeastTLSv1_3(ssl->version)) {
  11329. length += HELLO_EXT_SZ;
  11330. }
  11331. #endif
  11332. if (TLSX_SupportExtensions(ssl)) {
  11333. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, &length);
  11334. if (ret != 0)
  11335. return ret;
  11336. }
  11337. /* All the response data is set at the ssl object only, so no ctx here. */
  11338. if (length || msgType != server_hello)
  11339. length += OPAQUE16_LEN; /* for total length storage. */
  11340. *pLength += length;
  11341. return ret;
  11342. }
  11343. /** Writes the server hello extensions into a buffer. */
  11344. int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset)
  11345. {
  11346. int ret = 0;
  11347. word16 offset = 0;
  11348. if (TLSX_SupportExtensions(ssl) && output) {
  11349. byte semaphore[SEMAPHORE_SIZE] = {0};
  11350. switch (msgType) {
  11351. #ifndef NO_WOLFSSL_SERVER
  11352. case server_hello:
  11353. PF_VALIDATE_RESPONSE(ssl, semaphore);
  11354. #ifdef WOLFSSL_TLS13
  11355. if (IsAtLeastTLSv1_3(ssl->version)) {
  11356. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11357. TURN_OFF(semaphore,
  11358. TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11359. #ifdef HAVE_SUPPORTED_CURVES
  11360. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11361. if (!ssl->options.noPskDheKe)
  11362. #endif
  11363. {
  11364. /* Write out KeyShare in ServerHello. */
  11365. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11366. }
  11367. #endif
  11368. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11369. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11370. #endif
  11371. #ifdef WOLFSSL_DTLS_CID
  11372. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11373. #endif /* WOLFSSL_DTLS_CID */
  11374. }
  11375. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11376. else {
  11377. #ifdef HAVE_SUPPORTED_CURVES
  11378. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11379. #endif
  11380. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11381. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11382. #endif
  11383. }
  11384. #endif
  11385. #endif
  11386. break;
  11387. #ifdef WOLFSSL_TLS13
  11388. case hello_retry_request:
  11389. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11390. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11391. #ifdef HAVE_SUPPORTED_CURVES
  11392. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11393. if (!ssl->options.noPskDheKe)
  11394. #endif
  11395. {
  11396. /* Write out KeyShare in HelloRetryRequest. */
  11397. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11398. }
  11399. #endif
  11400. /* Cookie is written below as last extension. */
  11401. break;
  11402. #endif
  11403. #ifdef WOLFSSL_TLS13
  11404. case encrypted_extensions:
  11405. /* Send out all extension except those that are turned on. */
  11406. #ifdef HAVE_ECC
  11407. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  11408. #endif
  11409. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11410. #ifdef HAVE_SESSION_TICKET
  11411. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SESSION_TICKET));
  11412. #endif
  11413. #ifdef HAVE_SUPPORTED_CURVES
  11414. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11415. #endif
  11416. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11417. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11418. #endif
  11419. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  11420. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11421. #endif
  11422. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  11423. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11424. #endif
  11425. #if defined(HAVE_SERVER_RENEGOTIATION_INFO)
  11426. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_RENEGOTIATION_INFO));
  11427. #endif
  11428. #ifdef WOLFSSL_DTLS_CID
  11429. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11430. #endif /* WOLFSSL_DTLS_CID */
  11431. break;
  11432. #ifdef WOLFSSL_EARLY_DATA
  11433. case session_ticket:
  11434. if (ssl->options.tls1_3) {
  11435. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11436. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11437. }
  11438. break;
  11439. #endif
  11440. #endif
  11441. #endif
  11442. #ifdef WOLFSSL_TLS13
  11443. #ifndef NO_CERTS
  11444. case certificate:
  11445. /* Don't send out any extension except those that are turned
  11446. * off. */
  11447. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11448. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11449. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP,
  11450. * TLSX_SERVER_CERTIFICATE_TYPE
  11451. */
  11452. break;
  11453. #endif
  11454. #endif
  11455. default:
  11456. break;
  11457. }
  11458. offset += OPAQUE16_LEN; /* extensions length */
  11459. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11460. msgType, &offset);
  11461. if (ret != 0)
  11462. return ret;
  11463. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  11464. if (msgType == hello_retry_request) {
  11465. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11466. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11467. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11468. msgType, &offset);
  11469. if (ret != 0)
  11470. return ret;
  11471. }
  11472. #endif
  11473. #ifdef HAVE_EXTENDED_MASTER
  11474. if (ssl->options.haveEMS && msgType == server_hello &&
  11475. !IsAtLeastTLSv1_3(ssl->version)) {
  11476. WOLFSSL_MSG("EMS extension to write");
  11477. c16toa(HELLO_EXT_EXTMS, output + offset);
  11478. offset += HELLO_EXT_TYPE_SZ;
  11479. c16toa(0, output + offset);
  11480. offset += HELLO_EXT_SZ_SZ;
  11481. }
  11482. #endif
  11483. if (offset > OPAQUE16_LEN || msgType != server_hello)
  11484. c16toa(offset - OPAQUE16_LEN, output); /* extensions length */
  11485. }
  11486. if (pOffset)
  11487. *pOffset += offset;
  11488. return ret;
  11489. }
  11490. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_SERVER */
  11491. #ifdef WOLFSSL_TLS13
  11492. int TLSX_ParseVersion(WOLFSSL* ssl, const byte* input, word16 length,
  11493. byte msgType, int* found)
  11494. {
  11495. int ret = 0;
  11496. int offset = 0;
  11497. *found = 0;
  11498. while (offset < (int)length) {
  11499. word16 type;
  11500. word16 size;
  11501. if (offset + (2 * OPAQUE16_LEN) > length) {
  11502. ret = BUFFER_ERROR;
  11503. break;
  11504. }
  11505. ato16(input + offset, &type);
  11506. offset += HELLO_EXT_TYPE_SZ;
  11507. ato16(input + offset, &size);
  11508. offset += OPAQUE16_LEN;
  11509. if (offset + size > length) {
  11510. ret = BUFFER_ERROR;
  11511. break;
  11512. }
  11513. if (type == TLSX_SUPPORTED_VERSIONS) {
  11514. *found = 1;
  11515. WOLFSSL_MSG("Supported Versions extension received");
  11516. ret = SV_PARSE(ssl, input + offset, size, msgType, &ssl->version,
  11517. &ssl->options, &ssl->extensions);
  11518. break;
  11519. }
  11520. offset += size;
  11521. }
  11522. return ret;
  11523. }
  11524. #endif
  11525. /** Parses a buffer of TLS extensions. */
  11526. int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType,
  11527. Suites *suites)
  11528. {
  11529. int ret = 0;
  11530. word16 offset = 0;
  11531. byte isRequest = (msgType == client_hello ||
  11532. msgType == certificate_request);
  11533. #ifdef HAVE_EXTENDED_MASTER
  11534. byte pendingEMS = 0;
  11535. #endif
  11536. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  11537. int pskDone = 0;
  11538. #endif
  11539. byte seenType[SEMAPHORE_SIZE]; /* Seen known extensions. */
  11540. if (!ssl || !input || (isRequest && !suites))
  11541. return BAD_FUNC_ARG;
  11542. /* No known extensions seen yet. */
  11543. XMEMSET(seenType, 0, sizeof(seenType));
  11544. while (ret == 0 && offset < length) {
  11545. word16 type;
  11546. word16 size;
  11547. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  11548. if (msgType == client_hello && pskDone) {
  11549. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  11550. return PSK_KEY_ERROR;
  11551. }
  11552. #endif
  11553. if (length - offset < HELLO_EXT_TYPE_SZ + OPAQUE16_LEN)
  11554. return BUFFER_ERROR;
  11555. ato16(input + offset, &type);
  11556. offset += HELLO_EXT_TYPE_SZ;
  11557. ato16(input + offset, &size);
  11558. offset += OPAQUE16_LEN;
  11559. /* Check we have a bit for extension type. */
  11560. if ((type <= 62) || (type == TLSX_RENEGOTIATION_INFO)
  11561. #ifdef WOLFSSL_QUIC
  11562. || (type == TLSX_KEY_QUIC_TP_PARAMS_DRAFT)
  11563. #endif
  11564. )
  11565. {
  11566. /* Detect duplicate recognized extensions. */
  11567. if (IS_OFF(seenType, TLSX_ToSemaphore(type))) {
  11568. TURN_ON(seenType, TLSX_ToSemaphore(type));
  11569. }
  11570. else {
  11571. return DUPLICATE_TLS_EXT_E;
  11572. }
  11573. }
  11574. if (length - offset < size)
  11575. return BUFFER_ERROR;
  11576. switch (type) {
  11577. #ifdef HAVE_SNI
  11578. case TLSX_SERVER_NAME:
  11579. WOLFSSL_MSG("SNI extension received");
  11580. #ifdef WOLFSSL_DEBUG_TLS
  11581. WOLFSSL_BUFFER(input + offset, size);
  11582. #endif
  11583. #ifdef WOLFSSL_TLS13
  11584. if (IsAtLeastTLSv1_3(ssl->version)) {
  11585. if (msgType != client_hello &&
  11586. msgType != encrypted_extensions)
  11587. return EXT_NOT_ALLOWED;
  11588. }
  11589. else
  11590. #endif
  11591. {
  11592. if (msgType != client_hello &&
  11593. msgType != server_hello)
  11594. return EXT_NOT_ALLOWED;
  11595. }
  11596. ret = SNI_PARSE(ssl, input + offset, size, isRequest);
  11597. break;
  11598. #endif
  11599. case TLSX_TRUSTED_CA_KEYS:
  11600. WOLFSSL_MSG("Trusted CA extension received");
  11601. #ifdef WOLFSSL_DEBUG_TLS
  11602. WOLFSSL_BUFFER(input + offset, size);
  11603. #endif
  11604. #ifdef WOLFSSL_TLS13
  11605. /* RFC 8446 4.2.4 states trusted_ca_keys is not used
  11606. in TLS 1.3. */
  11607. if (IsAtLeastTLSv1_3(ssl->version)) {
  11608. return EXT_NOT_ALLOWED;
  11609. }
  11610. else
  11611. #endif
  11612. {
  11613. if (msgType != client_hello &&
  11614. msgType != server_hello)
  11615. return EXT_NOT_ALLOWED;
  11616. }
  11617. ret = TCA_PARSE(ssl, input + offset, size, isRequest);
  11618. break;
  11619. case TLSX_MAX_FRAGMENT_LENGTH:
  11620. WOLFSSL_MSG("Max Fragment Length extension received");
  11621. #ifdef WOLFSSL_DEBUG_TLS
  11622. WOLFSSL_BUFFER(input + offset, size);
  11623. #endif
  11624. #ifdef WOLFSSL_TLS13
  11625. if (IsAtLeastTLSv1_3(ssl->version)) {
  11626. if (msgType != client_hello &&
  11627. msgType != encrypted_extensions) {
  11628. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11629. return EXT_NOT_ALLOWED;
  11630. }
  11631. }
  11632. else
  11633. #endif
  11634. {
  11635. if (msgType != client_hello &&
  11636. msgType != server_hello) {
  11637. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11638. return EXT_NOT_ALLOWED;
  11639. }
  11640. }
  11641. ret = MFL_PARSE(ssl, input + offset, size, isRequest);
  11642. break;
  11643. case TLSX_TRUNCATED_HMAC:
  11644. WOLFSSL_MSG("Truncated HMAC extension received");
  11645. #ifdef WOLFSSL_DEBUG_TLS
  11646. WOLFSSL_BUFFER(input + offset, size);
  11647. #endif
  11648. #ifdef WOLFSSL_TLS13
  11649. if (IsAtLeastTLSv1_3(ssl->version))
  11650. break;
  11651. #endif
  11652. if (msgType != client_hello)
  11653. return EXT_NOT_ALLOWED;
  11654. ret = THM_PARSE(ssl, input + offset, size, isRequest);
  11655. break;
  11656. case TLSX_SUPPORTED_GROUPS:
  11657. WOLFSSL_MSG("Supported Groups extension received");
  11658. #ifdef WOLFSSL_DEBUG_TLS
  11659. WOLFSSL_BUFFER(input + offset, size);
  11660. #endif
  11661. #ifdef WOLFSSL_TLS13
  11662. if (IsAtLeastTLSv1_3(ssl->version)) {
  11663. if (msgType != client_hello &&
  11664. msgType != encrypted_extensions) {
  11665. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11666. return EXT_NOT_ALLOWED;
  11667. }
  11668. }
  11669. else
  11670. #endif
  11671. {
  11672. if (msgType != client_hello) {
  11673. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11674. return EXT_NOT_ALLOWED;
  11675. }
  11676. }
  11677. ret = EC_PARSE(ssl, input + offset, size, isRequest,
  11678. &ssl->extensions);
  11679. break;
  11680. case TLSX_EC_POINT_FORMATS:
  11681. WOLFSSL_MSG("Point Formats extension received");
  11682. #ifdef WOLFSSL_DEBUG_TLS
  11683. WOLFSSL_BUFFER(input + offset, size);
  11684. #endif
  11685. #ifdef WOLFSSL_TLS13
  11686. if (IsAtLeastTLSv1_3(ssl->version))
  11687. break;
  11688. #endif
  11689. if (msgType != client_hello &&
  11690. msgType != server_hello) {
  11691. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11692. return EXT_NOT_ALLOWED;
  11693. }
  11694. ret = PF_PARSE(ssl, input + offset, size, isRequest);
  11695. break;
  11696. case TLSX_STATUS_REQUEST:
  11697. WOLFSSL_MSG("Certificate Status Request extension received");
  11698. #ifdef WOLFSSL_DEBUG_TLS
  11699. WOLFSSL_BUFFER(input + offset, size);
  11700. #endif
  11701. #ifdef WOLFSSL_TLS13
  11702. if (IsAtLeastTLSv1_3(ssl->version)) {
  11703. if (msgType != client_hello &&
  11704. msgType != certificate_request &&
  11705. msgType != certificate)
  11706. return EXT_NOT_ALLOWED;
  11707. }
  11708. else
  11709. #endif
  11710. {
  11711. if (msgType != client_hello &&
  11712. msgType != server_hello)
  11713. return EXT_NOT_ALLOWED;
  11714. }
  11715. ret = CSR_PARSE(ssl, input + offset, size, isRequest);
  11716. break;
  11717. case TLSX_STATUS_REQUEST_V2:
  11718. WOLFSSL_MSG("Certificate Status Request v2 extension received");
  11719. #ifdef WOLFSSL_DEBUG_TLS
  11720. WOLFSSL_BUFFER(input + offset, size);
  11721. #endif
  11722. #if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  11723. if (IsAtLeastTLSv1_3(ssl->version)) {
  11724. if (msgType != client_hello &&
  11725. msgType != certificate_request &&
  11726. msgType != certificate)
  11727. return EXT_NOT_ALLOWED;
  11728. }
  11729. else
  11730. #endif
  11731. {
  11732. if (msgType != client_hello &&
  11733. msgType != server_hello)
  11734. return EXT_NOT_ALLOWED;
  11735. }
  11736. ret = CSR2_PARSE(ssl, input + offset, size, isRequest);
  11737. break;
  11738. #ifdef HAVE_EXTENDED_MASTER
  11739. case HELLO_EXT_EXTMS:
  11740. WOLFSSL_MSG("Extended Master Secret extension received");
  11741. #ifdef WOLFSSL_DEBUG_TLS
  11742. WOLFSSL_BUFFER(input + offset, size);
  11743. #endif
  11744. #if defined(WOLFSSL_TLS13)
  11745. if (IsAtLeastTLSv1_3(ssl->version))
  11746. break;
  11747. #endif
  11748. if (msgType != client_hello &&
  11749. msgType != server_hello)
  11750. return EXT_NOT_ALLOWED;
  11751. if (size != 0)
  11752. return BUFFER_ERROR;
  11753. #ifndef NO_WOLFSSL_SERVER
  11754. if (isRequest)
  11755. ssl->options.haveEMS = 1;
  11756. #endif
  11757. pendingEMS = 1;
  11758. break;
  11759. #endif
  11760. case TLSX_RENEGOTIATION_INFO:
  11761. WOLFSSL_MSG("Secure Renegotiation extension received");
  11762. #ifdef WOLFSSL_DEBUG_TLS
  11763. WOLFSSL_BUFFER(input + offset, size);
  11764. #endif
  11765. #ifdef WOLFSSL_TLS13
  11766. if (IsAtLeastTLSv1_3(ssl->version))
  11767. break;
  11768. #endif
  11769. if (msgType != client_hello &&
  11770. msgType != server_hello)
  11771. return EXT_NOT_ALLOWED;
  11772. ret = SCR_PARSE(ssl, input + offset, size, isRequest);
  11773. break;
  11774. case TLSX_SESSION_TICKET:
  11775. WOLFSSL_MSG("Session Ticket extension received");
  11776. #ifdef WOLFSSL_DEBUG_TLS
  11777. WOLFSSL_BUFFER(input + offset, size);
  11778. #endif
  11779. #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)
  11780. if (IsAtLeastTLSv1_3(ssl->version)) {
  11781. if (msgType != client_hello)
  11782. return EXT_NOT_ALLOWED;
  11783. }
  11784. else
  11785. #endif
  11786. {
  11787. if (msgType != client_hello &&
  11788. msgType != server_hello)
  11789. return EXT_NOT_ALLOWED;
  11790. }
  11791. ret = WOLF_STK_PARSE(ssl, input + offset, size, isRequest);
  11792. break;
  11793. case TLSX_APPLICATION_LAYER_PROTOCOL:
  11794. WOLFSSL_MSG("ALPN extension received");
  11795. #ifdef WOLFSSL_DEBUG_TLS
  11796. WOLFSSL_BUFFER(input + offset, size);
  11797. #endif
  11798. #if defined(WOLFSSL_TLS13) && defined(HAVE_ALPN)
  11799. if (IsAtLeastTLSv1_3(ssl->version)) {
  11800. if (msgType != client_hello &&
  11801. msgType != encrypted_extensions)
  11802. return EXT_NOT_ALLOWED;
  11803. }
  11804. else
  11805. #endif
  11806. {
  11807. if (msgType != client_hello &&
  11808. msgType != server_hello)
  11809. return EXT_NOT_ALLOWED;
  11810. }
  11811. ret = ALPN_PARSE(ssl, input + offset, size, isRequest);
  11812. break;
  11813. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11814. case TLSX_SIGNATURE_ALGORITHMS:
  11815. WOLFSSL_MSG("Signature Algorithms extension received");
  11816. #ifdef WOLFSSL_DEBUG_TLS
  11817. WOLFSSL_BUFFER(input + offset, size);
  11818. #endif
  11819. if (!IsAtLeastTLSv1_2(ssl))
  11820. break;
  11821. #ifdef WOLFSSL_TLS13
  11822. if (IsAtLeastTLSv1_3(ssl->version)) {
  11823. if (msgType != client_hello &&
  11824. msgType != certificate_request)
  11825. return EXT_NOT_ALLOWED;
  11826. }
  11827. else
  11828. #endif
  11829. {
  11830. if (msgType != client_hello)
  11831. return EXT_NOT_ALLOWED;
  11832. }
  11833. ret = SA_PARSE(ssl, input + offset, size, isRequest, suites);
  11834. break;
  11835. #endif
  11836. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  11837. case TLSX_ENCRYPT_THEN_MAC:
  11838. WOLFSSL_MSG("Encrypt-Then-Mac extension received");
  11839. /* Ignore for TLS 1.3+ */
  11840. if (IsAtLeastTLSv1_3(ssl->version))
  11841. break;
  11842. if (msgType != client_hello &&
  11843. msgType != server_hello)
  11844. return EXT_NOT_ALLOWED;
  11845. ret = ETM_PARSE(ssl, input + offset, size, msgType);
  11846. break;
  11847. #endif /* HAVE_ENCRYPT_THEN_MAC */
  11848. #ifdef WOLFSSL_TLS13
  11849. case TLSX_SUPPORTED_VERSIONS:
  11850. WOLFSSL_MSG("Skipping Supported Versions - already processed");
  11851. #ifdef WOLFSSL_DEBUG_TLS
  11852. WOLFSSL_BUFFER(input + offset, size);
  11853. #endif
  11854. if (msgType != client_hello &&
  11855. msgType != server_hello &&
  11856. msgType != hello_retry_request)
  11857. return EXT_NOT_ALLOWED;
  11858. break;
  11859. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11860. case TLSX_COOKIE:
  11861. WOLFSSL_MSG("Cookie extension received");
  11862. #ifdef WOLFSSL_DEBUG_TLS
  11863. WOLFSSL_BUFFER(input + offset, size);
  11864. #endif
  11865. if (!IsAtLeastTLSv1_3(ssl->version))
  11866. break;
  11867. if (msgType != client_hello &&
  11868. msgType != hello_retry_request) {
  11869. return EXT_NOT_ALLOWED;
  11870. }
  11871. ret = CKE_PARSE(ssl, input + offset, size, msgType);
  11872. break;
  11873. #endif
  11874. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11875. case TLSX_PRE_SHARED_KEY:
  11876. WOLFSSL_MSG("Pre-Shared Key extension received");
  11877. #ifdef WOLFSSL_DEBUG_TLS
  11878. WOLFSSL_BUFFER(input + offset, size);
  11879. #endif
  11880. if (!IsAtLeastTLSv1_3(ssl->version))
  11881. break;
  11882. if (msgType != client_hello &&
  11883. msgType != server_hello) {
  11884. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11885. return EXT_NOT_ALLOWED;
  11886. }
  11887. ret = PSK_PARSE(ssl, input + offset, size, msgType);
  11888. pskDone = 1;
  11889. break;
  11890. case TLSX_PSK_KEY_EXCHANGE_MODES:
  11891. WOLFSSL_MSG("PSK Key Exchange Modes extension received");
  11892. #ifdef WOLFSSL_DEBUG_TLS
  11893. WOLFSSL_BUFFER(input + offset, size);
  11894. #endif
  11895. if (!IsAtLeastTLSv1_3(ssl->version))
  11896. break;
  11897. if (msgType != client_hello) {
  11898. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11899. return EXT_NOT_ALLOWED;
  11900. }
  11901. ret = PKM_PARSE(ssl, input + offset, size, msgType);
  11902. break;
  11903. #endif
  11904. #ifdef WOLFSSL_EARLY_DATA
  11905. case TLSX_EARLY_DATA:
  11906. WOLFSSL_MSG("Early Data extension received");
  11907. #ifdef WOLFSSL_DEBUG_TLS
  11908. WOLFSSL_BUFFER(input + offset, size);
  11909. #endif
  11910. if (!IsAtLeastTLSv1_3(ssl->version))
  11911. break;
  11912. if (msgType != client_hello && msgType != session_ticket &&
  11913. msgType != encrypted_extensions) {
  11914. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11915. return EXT_NOT_ALLOWED;
  11916. }
  11917. ret = EDI_PARSE(ssl, input + offset, size, msgType);
  11918. break;
  11919. #endif
  11920. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  11921. case TLSX_POST_HANDSHAKE_AUTH:
  11922. WOLFSSL_MSG("Post Handshake Authentication extension received");
  11923. #ifdef WOLFSSL_DEBUG_TLS
  11924. WOLFSSL_BUFFER(input + offset, size);
  11925. #endif
  11926. if (!IsAtLeastTLSv1_3(ssl->version))
  11927. break;
  11928. if (msgType != client_hello) {
  11929. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11930. return EXT_NOT_ALLOWED;
  11931. }
  11932. ret = PHA_PARSE(ssl, input + offset, size, msgType);
  11933. break;
  11934. #endif
  11935. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11936. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  11937. WOLFSSL_MSG("Signature Algorithms extension received");
  11938. #ifdef WOLFSSL_DEBUG_TLS
  11939. WOLFSSL_BUFFER(input + offset, size);
  11940. #endif
  11941. if (!IsAtLeastTLSv1_3(ssl->version))
  11942. break;
  11943. if (msgType != client_hello &&
  11944. msgType != certificate_request) {
  11945. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11946. return EXT_NOT_ALLOWED;
  11947. }
  11948. ret = SAC_PARSE(ssl, input + offset, size, isRequest);
  11949. break;
  11950. #endif
  11951. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11952. case TLSX_CERTIFICATE_AUTHORITIES:
  11953. WOLFSSL_MSG("Certificate Authorities extension received");
  11954. #ifdef WOLFSSL_DEBUG_TLS
  11955. WOLFSSL_BUFFER(input + offset, size);
  11956. #endif
  11957. if (!IsAtLeastTLSv1_3(ssl->version))
  11958. break;
  11959. if (msgType != client_hello &&
  11960. msgType != certificate_request) {
  11961. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11962. return EXT_NOT_ALLOWED;
  11963. }
  11964. ret = CAN_PARSE(ssl, input + offset, size, isRequest);
  11965. break;
  11966. #endif
  11967. case TLSX_KEY_SHARE:
  11968. WOLFSSL_MSG("Key Share extension received");
  11969. #ifdef WOLFSSL_DEBUG_TLS
  11970. WOLFSSL_BUFFER(input + offset, size);
  11971. #endif
  11972. #ifdef HAVE_SUPPORTED_CURVES
  11973. if (!IsAtLeastTLSv1_3(ssl->version))
  11974. break;
  11975. if (msgType != client_hello && msgType != server_hello &&
  11976. msgType != hello_retry_request) {
  11977. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11978. return EXT_NOT_ALLOWED;
  11979. }
  11980. #endif
  11981. ret = KS_PARSE(ssl, input + offset, size, msgType);
  11982. break;
  11983. #endif
  11984. #ifdef WOLFSSL_SRTP
  11985. case TLSX_USE_SRTP:
  11986. WOLFSSL_MSG("Use SRTP extension received");
  11987. ret = SRTP_PARSE(ssl, input + offset, size, isRequest);
  11988. break;
  11989. #endif
  11990. #ifdef WOLFSSL_QUIC
  11991. case TLSX_KEY_QUIC_TP_PARAMS:
  11992. FALL_THROUGH;
  11993. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  11994. WOLFSSL_MSG("QUIC transport parameter received");
  11995. #ifdef WOLFSSL_DEBUG_TLS
  11996. WOLFSSL_BUFFER(input + offset, size);
  11997. #endif
  11998. if (IsAtLeastTLSv1_3(ssl->version) &&
  11999. msgType != client_hello &&
  12000. msgType != server_hello &&
  12001. msgType != encrypted_extensions) {
  12002. return EXT_NOT_ALLOWED;
  12003. }
  12004. else if (!IsAtLeastTLSv1_3(ssl->version) &&
  12005. msgType == encrypted_extensions) {
  12006. return EXT_NOT_ALLOWED;
  12007. }
  12008. else if (WOLFSSL_IS_QUIC(ssl)) {
  12009. ret = QTP_PARSE(ssl, input + offset, size, type, msgType);
  12010. }
  12011. else {
  12012. WOLFSSL_MSG("QUIC transport param TLS extension type, but no QUIC");
  12013. return EXT_NOT_ALLOWED; /* be safe, this should not happen */
  12014. }
  12015. break;
  12016. #endif /* WOLFSSL_QUIC */
  12017. #if defined(WOLFSSL_DTLS_CID)
  12018. case TLSX_CONNECTION_ID:
  12019. /* connection ID not supported in DTLSv1.2 */
  12020. if (!IsAtLeastTLSv1_3(ssl->version))
  12021. break;
  12022. if (msgType != client_hello && msgType != server_hello)
  12023. return EXT_NOT_ALLOWED;
  12024. WOLFSSL_MSG("ConnectionID extension received");
  12025. ret = CID_PARSE(ssl, input + offset, size, isRequest);
  12026. break;
  12027. #endif /* defined(WOLFSSL_DTLS_CID) */
  12028. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  12029. case TLSX_ECH:
  12030. ret = ECH_PARSE(ssl, input + offset, size, msgType);
  12031. break;
  12032. #endif
  12033. default:
  12034. WOLFSSL_MSG("Unknown TLS extension type");
  12035. }
  12036. /* offset should be updated here! */
  12037. offset += size;
  12038. }
  12039. #ifdef HAVE_EXTENDED_MASTER
  12040. if (IsAtLeastTLSv1_3(ssl->version) && msgType == hello_retry_request) {
  12041. /* Don't change EMS status until server_hello received.
  12042. * Second ClientHello must have same extensions.
  12043. */
  12044. }
  12045. else if (!isRequest && ssl->options.haveEMS && !pendingEMS)
  12046. ssl->options.haveEMS = 0;
  12047. #endif
  12048. if (ret == 0)
  12049. ret = SNI_VERIFY_PARSE(ssl, isRequest);
  12050. if (ret == 0)
  12051. ret = TCA_VERIFY_PARSE(ssl, isRequest);
  12052. return ret;
  12053. }
  12054. /* undefining semaphore macros */
  12055. #undef IS_OFF
  12056. #undef TURN_ON
  12057. #undef SEMAPHORE_SIZE
  12058. #endif /* HAVE_TLS_EXTENSIONS */
  12059. #ifndef NO_WOLFSSL_CLIENT
  12060. WOLFSSL_METHOD* wolfTLS_client_method(void)
  12061. {
  12062. return wolfTLS_client_method_ex(NULL);
  12063. }
  12064. WOLFSSL_METHOD* wolfTLS_client_method_ex(void* heap)
  12065. {
  12066. WOLFSSL_METHOD* method =
  12067. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12068. heap, DYNAMIC_TYPE_METHOD);
  12069. (void)heap;
  12070. WOLFSSL_ENTER("TLS_client_method_ex");
  12071. if (method) {
  12072. #if defined(WOLFSSL_TLS13)
  12073. InitSSL_Method(method, MakeTLSv1_3());
  12074. #elif !defined(WOLFSSL_NO_TLS12)
  12075. InitSSL_Method(method, MakeTLSv1_2());
  12076. #elif !defined(NO_OLD_TLS)
  12077. InitSSL_Method(method, MakeTLSv1_1());
  12078. #elif defined(WOLFSSL_ALLOW_TLSV10)
  12079. InitSSL_Method(method, MakeTLSv1());
  12080. #else
  12081. #error No TLS version enabled!
  12082. #endif
  12083. method->downgrade = 1;
  12084. method->side = WOLFSSL_CLIENT_END;
  12085. }
  12086. return method;
  12087. }
  12088. #ifndef NO_OLD_TLS
  12089. #ifdef WOLFSSL_ALLOW_TLSV10
  12090. WOLFSSL_METHOD* wolfTLSv1_client_method(void)
  12091. {
  12092. return wolfTLSv1_client_method_ex(NULL);
  12093. }
  12094. WOLFSSL_METHOD* wolfTLSv1_client_method_ex(void* heap)
  12095. {
  12096. WOLFSSL_METHOD* method =
  12097. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12098. heap, DYNAMIC_TYPE_METHOD);
  12099. (void)heap;
  12100. WOLFSSL_ENTER("TLSv1_client_method_ex");
  12101. if (method)
  12102. InitSSL_Method(method, MakeTLSv1());
  12103. return method;
  12104. }
  12105. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12106. WOLFSSL_METHOD* wolfTLSv1_1_client_method(void)
  12107. {
  12108. return wolfTLSv1_1_client_method_ex(NULL);
  12109. }
  12110. WOLFSSL_METHOD* wolfTLSv1_1_client_method_ex(void* heap)
  12111. {
  12112. WOLFSSL_METHOD* method =
  12113. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12114. heap, DYNAMIC_TYPE_METHOD);
  12115. (void)heap;
  12116. WOLFSSL_ENTER("TLSv1_1_client_method_ex");
  12117. if (method)
  12118. InitSSL_Method(method, MakeTLSv1_1());
  12119. return method;
  12120. }
  12121. #endif /* !NO_OLD_TLS */
  12122. #ifndef WOLFSSL_NO_TLS12
  12123. WOLFSSL_ABI
  12124. WOLFSSL_METHOD* wolfTLSv1_2_client_method(void)
  12125. {
  12126. return wolfTLSv1_2_client_method_ex(NULL);
  12127. }
  12128. WOLFSSL_METHOD* wolfTLSv1_2_client_method_ex(void* heap)
  12129. {
  12130. WOLFSSL_METHOD* method =
  12131. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12132. heap, DYNAMIC_TYPE_METHOD);
  12133. (void)heap;
  12134. WOLFSSL_ENTER("TLSv1_2_client_method_ex");
  12135. if (method)
  12136. InitSSL_Method(method, MakeTLSv1_2());
  12137. return method;
  12138. }
  12139. #endif /* WOLFSSL_NO_TLS12 */
  12140. #ifdef WOLFSSL_TLS13
  12141. /* The TLS v1.3 client method data.
  12142. *
  12143. * returns the method data for a TLS v1.3 client.
  12144. */
  12145. WOLFSSL_ABI
  12146. WOLFSSL_METHOD* wolfTLSv1_3_client_method(void)
  12147. {
  12148. return wolfTLSv1_3_client_method_ex(NULL);
  12149. }
  12150. /* The TLS v1.3 client method data.
  12151. *
  12152. * heap The heap used for allocation.
  12153. * returns the method data for a TLS v1.3 client.
  12154. */
  12155. WOLFSSL_METHOD* wolfTLSv1_3_client_method_ex(void* heap)
  12156. {
  12157. WOLFSSL_METHOD* method = (WOLFSSL_METHOD*)
  12158. XMALLOC(sizeof(WOLFSSL_METHOD), heap,
  12159. DYNAMIC_TYPE_METHOD);
  12160. (void)heap;
  12161. WOLFSSL_ENTER("TLSv1_3_client_method_ex");
  12162. if (method)
  12163. InitSSL_Method(method, MakeTLSv1_3());
  12164. return method;
  12165. }
  12166. #endif /* WOLFSSL_TLS13 */
  12167. #ifdef WOLFSSL_DTLS
  12168. WOLFSSL_METHOD* wolfDTLS_client_method(void)
  12169. {
  12170. return wolfDTLS_client_method_ex(NULL);
  12171. }
  12172. WOLFSSL_METHOD* wolfDTLS_client_method_ex(void* heap)
  12173. {
  12174. WOLFSSL_METHOD* method =
  12175. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12176. heap, DYNAMIC_TYPE_METHOD);
  12177. (void)heap;
  12178. WOLFSSL_ENTER("DTLS_client_method_ex");
  12179. if (method) {
  12180. #if defined(WOLFSSL_DTLS13)
  12181. InitSSL_Method(method, MakeDTLSv1_3());
  12182. #elif !defined(WOLFSSL_NO_TLS12)
  12183. InitSSL_Method(method, MakeDTLSv1_2());
  12184. #elif !defined(NO_OLD_TLS)
  12185. InitSSL_Method(method, MakeDTLSv1());
  12186. #else
  12187. #error No DTLS version enabled!
  12188. #endif
  12189. method->downgrade = 1;
  12190. method->side = WOLFSSL_CLIENT_END;
  12191. }
  12192. return method;
  12193. }
  12194. #ifndef NO_OLD_TLS
  12195. WOLFSSL_METHOD* wolfDTLSv1_client_method(void)
  12196. {
  12197. return wolfDTLSv1_client_method_ex(NULL);
  12198. }
  12199. WOLFSSL_METHOD* wolfDTLSv1_client_method_ex(void* heap)
  12200. {
  12201. WOLFSSL_METHOD* method =
  12202. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12203. heap, DYNAMIC_TYPE_METHOD);
  12204. (void)heap;
  12205. WOLFSSL_ENTER("DTLSv1_client_method_ex");
  12206. if (method)
  12207. InitSSL_Method(method, MakeDTLSv1());
  12208. return method;
  12209. }
  12210. #endif /* NO_OLD_TLS */
  12211. #ifndef WOLFSSL_NO_TLS12
  12212. WOLFSSL_METHOD* wolfDTLSv1_2_client_method(void)
  12213. {
  12214. return wolfDTLSv1_2_client_method_ex(NULL);
  12215. }
  12216. WOLFSSL_METHOD* wolfDTLSv1_2_client_method_ex(void* heap)
  12217. {
  12218. WOLFSSL_METHOD* method =
  12219. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12220. heap, DYNAMIC_TYPE_METHOD);
  12221. (void)heap;
  12222. WOLFSSL_ENTER("DTLSv1_2_client_method_ex");
  12223. if (method)
  12224. InitSSL_Method(method, MakeDTLSv1_2());
  12225. (void)heap;
  12226. return method;
  12227. }
  12228. #endif /* !WOLFSSL_NO_TLS12 */
  12229. #endif /* WOLFSSL_DTLS */
  12230. #endif /* NO_WOLFSSL_CLIENT */
  12231. /* EITHER SIDE METHODS */
  12232. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
  12233. #ifndef NO_OLD_TLS
  12234. #ifdef WOLFSSL_ALLOW_TLSV10
  12235. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12236. *
  12237. * Returns a pointer to a WOLFSSL_METHOD struct
  12238. */
  12239. WOLFSSL_METHOD* wolfTLSv1_method(void)
  12240. {
  12241. return wolfTLSv1_method_ex(NULL);
  12242. }
  12243. WOLFSSL_METHOD* wolfTLSv1_method_ex(void* heap)
  12244. {
  12245. WOLFSSL_METHOD* m;
  12246. WOLFSSL_ENTER("TLSv1_method");
  12247. #ifndef NO_WOLFSSL_CLIENT
  12248. m = wolfTLSv1_client_method_ex(heap);
  12249. #else
  12250. m = wolfTLSv1_server_method_ex(heap);
  12251. #endif
  12252. if (m != NULL) {
  12253. m->side = WOLFSSL_NEITHER_END;
  12254. }
  12255. return m;
  12256. }
  12257. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12258. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12259. *
  12260. * Returns a pointer to a WOLFSSL_METHOD struct
  12261. */
  12262. WOLFSSL_METHOD* wolfTLSv1_1_method(void)
  12263. {
  12264. return wolfTLSv1_1_method_ex(NULL);
  12265. }
  12266. WOLFSSL_METHOD* wolfTLSv1_1_method_ex(void* heap)
  12267. {
  12268. WOLFSSL_METHOD* m;
  12269. WOLFSSL_ENTER("TLSv1_1_method");
  12270. #ifndef NO_WOLFSSL_CLIENT
  12271. m = wolfTLSv1_1_client_method_ex(heap);
  12272. #else
  12273. m = wolfTLSv1_1_server_method_ex(heap);
  12274. #endif
  12275. if (m != NULL) {
  12276. m->side = WOLFSSL_NEITHER_END;
  12277. }
  12278. return m;
  12279. }
  12280. #endif /* !NO_OLD_TLS */
  12281. #ifndef WOLFSSL_NO_TLS12
  12282. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12283. *
  12284. * Returns a pointer to a WOLFSSL_METHOD struct
  12285. */
  12286. WOLFSSL_METHOD* wolfTLSv1_2_method(void)
  12287. {
  12288. return wolfTLSv1_2_method_ex(NULL);
  12289. }
  12290. WOLFSSL_METHOD* wolfTLSv1_2_method_ex(void* heap)
  12291. {
  12292. WOLFSSL_METHOD* m;
  12293. WOLFSSL_ENTER("TLSv1_2_method");
  12294. #ifndef NO_WOLFSSL_CLIENT
  12295. m = wolfTLSv1_2_client_method_ex(heap);
  12296. #else
  12297. m = wolfTLSv1_2_server_method_ex(heap);
  12298. #endif
  12299. if (m != NULL) {
  12300. m->side = WOLFSSL_NEITHER_END;
  12301. }
  12302. return m;
  12303. }
  12304. #endif /* !WOLFSSL_NO_TLS12 */
  12305. #ifdef WOLFSSL_TLS13
  12306. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12307. *
  12308. * Returns a pointer to a WOLFSSL_METHOD struct
  12309. */
  12310. WOLFSSL_METHOD* wolfTLSv1_3_method(void)
  12311. {
  12312. return wolfTLSv1_3_method_ex(NULL);
  12313. }
  12314. WOLFSSL_METHOD* wolfTLSv1_3_method_ex(void* heap)
  12315. {
  12316. WOLFSSL_METHOD* m;
  12317. WOLFSSL_ENTER("TLSv1_3_method");
  12318. #ifndef NO_WOLFSSL_CLIENT
  12319. m = wolfTLSv1_3_client_method_ex(heap);
  12320. #else
  12321. m = wolfTLSv1_3_server_method_ex(heap);
  12322. #endif
  12323. if (m != NULL) {
  12324. m->side = WOLFSSL_NEITHER_END;
  12325. }
  12326. return m;
  12327. }
  12328. #endif /* WOLFSSL_TLS13 */
  12329. #ifdef WOLFSSL_DTLS
  12330. WOLFSSL_METHOD* wolfDTLS_method(void)
  12331. {
  12332. return wolfDTLS_method_ex(NULL);
  12333. }
  12334. WOLFSSL_METHOD* wolfDTLS_method_ex(void* heap)
  12335. {
  12336. WOLFSSL_METHOD* m;
  12337. WOLFSSL_ENTER("DTLS_method_ex");
  12338. #ifndef NO_WOLFSSL_CLIENT
  12339. m = wolfDTLS_client_method_ex(heap);
  12340. #else
  12341. m = wolfDTLS_server_method_ex(heap);
  12342. #endif
  12343. if (m != NULL) {
  12344. m->side = WOLFSSL_NEITHER_END;
  12345. }
  12346. return m;
  12347. }
  12348. #ifndef NO_OLD_TLS
  12349. WOLFSSL_METHOD* wolfDTLSv1_method(void)
  12350. {
  12351. return wolfDTLSv1_method_ex(NULL);
  12352. }
  12353. WOLFSSL_METHOD* wolfDTLSv1_method_ex(void* heap)
  12354. {
  12355. WOLFSSL_METHOD* m;
  12356. WOLFSSL_ENTER("DTLSv1_method_ex");
  12357. #ifndef NO_WOLFSSL_CLIENT
  12358. m = wolfDTLSv1_client_method_ex(heap);
  12359. #else
  12360. m = wolfDTLSv1_server_method_ex(heap);
  12361. #endif
  12362. if (m != NULL) {
  12363. m->side = WOLFSSL_NEITHER_END;
  12364. }
  12365. return m;
  12366. }
  12367. #endif /* !NO_OLD_TLS */
  12368. #ifndef WOLFSSL_NO_TLS12
  12369. WOLFSSL_METHOD* wolfDTLSv1_2_method(void)
  12370. {
  12371. return wolfDTLSv1_2_method_ex(NULL);
  12372. }
  12373. WOLFSSL_METHOD* wolfDTLSv1_2_method_ex(void* heap)
  12374. {
  12375. WOLFSSL_METHOD* m;
  12376. WOLFSSL_ENTER("DTLSv1_2_method");
  12377. #ifndef NO_WOLFSSL_CLIENT
  12378. m = wolfDTLSv1_2_client_method_ex(heap);
  12379. #else
  12380. m = wolfDTLSv1_2_server_method_ex(heap);
  12381. #endif
  12382. if (m != NULL) {
  12383. m->side = WOLFSSL_NEITHER_END;
  12384. }
  12385. return m;
  12386. }
  12387. #endif /* !WOLFSSL_NO_TLS12 */
  12388. #endif /* WOLFSSL_DTLS */
  12389. #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
  12390. #ifndef NO_WOLFSSL_SERVER
  12391. WOLFSSL_METHOD* wolfTLS_server_method(void)
  12392. {
  12393. return wolfTLS_server_method_ex(NULL);
  12394. }
  12395. WOLFSSL_METHOD* wolfTLS_server_method_ex(void* heap)
  12396. {
  12397. WOLFSSL_METHOD* method =
  12398. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12399. heap, DYNAMIC_TYPE_METHOD);
  12400. (void)heap;
  12401. WOLFSSL_ENTER("TLS_server_method_ex");
  12402. if (method) {
  12403. #if defined(WOLFSSL_TLS13)
  12404. InitSSL_Method(method, MakeTLSv1_3());
  12405. #elif !defined(WOLFSSL_NO_TLS12)
  12406. InitSSL_Method(method, MakeTLSv1_2());
  12407. #elif !defined(NO_OLD_TLS)
  12408. InitSSL_Method(method, MakeTLSv1_1());
  12409. #elif defined(WOLFSSL_ALLOW_TLSV10)
  12410. InitSSL_Method(method, MakeTLSv1());
  12411. #else
  12412. #error No TLS version enabled!
  12413. #endif
  12414. method->downgrade = 1;
  12415. method->side = WOLFSSL_SERVER_END;
  12416. }
  12417. return method;
  12418. }
  12419. #ifndef NO_OLD_TLS
  12420. #ifdef WOLFSSL_ALLOW_TLSV10
  12421. WOLFSSL_METHOD* wolfTLSv1_server_method(void)
  12422. {
  12423. return wolfTLSv1_server_method_ex(NULL);
  12424. }
  12425. WOLFSSL_METHOD* wolfTLSv1_server_method_ex(void* heap)
  12426. {
  12427. WOLFSSL_METHOD* method =
  12428. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12429. heap, DYNAMIC_TYPE_METHOD);
  12430. (void)heap;
  12431. WOLFSSL_ENTER("TLSv1_server_method_ex");
  12432. if (method) {
  12433. InitSSL_Method(method, MakeTLSv1());
  12434. method->side = WOLFSSL_SERVER_END;
  12435. }
  12436. return method;
  12437. }
  12438. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12439. WOLFSSL_METHOD* wolfTLSv1_1_server_method(void)
  12440. {
  12441. return wolfTLSv1_1_server_method_ex(NULL);
  12442. }
  12443. WOLFSSL_METHOD* wolfTLSv1_1_server_method_ex(void* heap)
  12444. {
  12445. WOLFSSL_METHOD* method =
  12446. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12447. heap, DYNAMIC_TYPE_METHOD);
  12448. (void)heap;
  12449. WOLFSSL_ENTER("TLSv1_1_server_method_ex");
  12450. if (method) {
  12451. InitSSL_Method(method, MakeTLSv1_1());
  12452. method->side = WOLFSSL_SERVER_END;
  12453. }
  12454. return method;
  12455. }
  12456. #endif /* !NO_OLD_TLS */
  12457. #ifndef WOLFSSL_NO_TLS12
  12458. WOLFSSL_ABI
  12459. WOLFSSL_METHOD* wolfTLSv1_2_server_method(void)
  12460. {
  12461. return wolfTLSv1_2_server_method_ex(NULL);
  12462. }
  12463. WOLFSSL_METHOD* wolfTLSv1_2_server_method_ex(void* heap)
  12464. {
  12465. WOLFSSL_METHOD* method =
  12466. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12467. heap, DYNAMIC_TYPE_METHOD);
  12468. (void)heap;
  12469. WOLFSSL_ENTER("TLSv1_2_server_method_ex");
  12470. if (method) {
  12471. InitSSL_Method(method, MakeTLSv1_2());
  12472. method->side = WOLFSSL_SERVER_END;
  12473. }
  12474. return method;
  12475. }
  12476. #endif /* !WOLFSSL_NO_TLS12 */
  12477. #ifdef WOLFSSL_TLS13
  12478. /* The TLS v1.3 server method data.
  12479. *
  12480. * returns the method data for a TLS v1.3 server.
  12481. */
  12482. WOLFSSL_ABI
  12483. WOLFSSL_METHOD* wolfTLSv1_3_server_method(void)
  12484. {
  12485. return wolfTLSv1_3_server_method_ex(NULL);
  12486. }
  12487. /* The TLS v1.3 server method data.
  12488. *
  12489. * heap The heap used for allocation.
  12490. * returns the method data for a TLS v1.3 server.
  12491. */
  12492. WOLFSSL_METHOD* wolfTLSv1_3_server_method_ex(void* heap)
  12493. {
  12494. WOLFSSL_METHOD* method =
  12495. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12496. heap, DYNAMIC_TYPE_METHOD);
  12497. (void)heap;
  12498. WOLFSSL_ENTER("TLSv1_3_server_method_ex");
  12499. if (method) {
  12500. InitSSL_Method(method, MakeTLSv1_3());
  12501. method->side = WOLFSSL_SERVER_END;
  12502. }
  12503. return method;
  12504. }
  12505. #endif /* WOLFSSL_TLS13 */
  12506. #ifdef WOLFSSL_DTLS
  12507. WOLFSSL_METHOD* wolfDTLS_server_method(void)
  12508. {
  12509. return wolfDTLS_server_method_ex(NULL);
  12510. }
  12511. WOLFSSL_METHOD* wolfDTLS_server_method_ex(void* heap)
  12512. {
  12513. WOLFSSL_METHOD* method =
  12514. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12515. heap, DYNAMIC_TYPE_METHOD);
  12516. (void)heap;
  12517. WOLFSSL_ENTER("DTLS_server_method_ex");
  12518. if (method) {
  12519. #if defined(WOLFSSL_DTLS13)
  12520. InitSSL_Method(method, MakeDTLSv1_3());
  12521. #elif !defined(WOLFSSL_NO_TLS12)
  12522. InitSSL_Method(method, MakeDTLSv1_2());
  12523. #elif !defined(NO_OLD_TLS)
  12524. InitSSL_Method(method, MakeDTLSv1());
  12525. #else
  12526. #error No DTLS version enabled!
  12527. #endif
  12528. method->downgrade = 1;
  12529. method->side = WOLFSSL_SERVER_END;
  12530. }
  12531. return method;
  12532. }
  12533. #ifndef NO_OLD_TLS
  12534. WOLFSSL_METHOD* wolfDTLSv1_server_method(void)
  12535. {
  12536. return wolfDTLSv1_server_method_ex(NULL);
  12537. }
  12538. WOLFSSL_METHOD* wolfDTLSv1_server_method_ex(void* heap)
  12539. {
  12540. WOLFSSL_METHOD* method =
  12541. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12542. heap, DYNAMIC_TYPE_METHOD);
  12543. (void)heap;
  12544. WOLFSSL_ENTER("DTLSv1_server_method_ex");
  12545. if (method) {
  12546. InitSSL_Method(method, MakeDTLSv1());
  12547. method->side = WOLFSSL_SERVER_END;
  12548. }
  12549. return method;
  12550. }
  12551. #endif /* !NO_OLD_TLS */
  12552. #ifndef WOLFSSL_NO_TLS12
  12553. WOLFSSL_METHOD* wolfDTLSv1_2_server_method(void)
  12554. {
  12555. return wolfDTLSv1_2_server_method_ex(NULL);
  12556. }
  12557. WOLFSSL_METHOD* wolfDTLSv1_2_server_method_ex(void* heap)
  12558. {
  12559. WOLFSSL_METHOD* method =
  12560. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12561. heap, DYNAMIC_TYPE_METHOD);
  12562. WOLFSSL_ENTER("DTLSv1_2_server_method_ex");
  12563. (void)heap;
  12564. if (method) {
  12565. InitSSL_Method(method, MakeDTLSv1_2());
  12566. method->side = WOLFSSL_SERVER_END;
  12567. }
  12568. (void)heap;
  12569. return method;
  12570. }
  12571. #endif /* !WOLFSSL_NO_TLS12 */
  12572. #endif /* WOLFSSL_DTLS */
  12573. #endif /* NO_WOLFSSL_SERVER */
  12574. #endif /* NO_TLS */
  12575. #endif /* WOLFCRYPT_ONLY */