tls.c 465 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248
  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. #if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  443. /* If this is called from a sniffer session with keylog file support, obtain
  444. * the master secret from the callback */
  445. if (ssl->snifferSecretCb != NULL) {
  446. ret = ssl->snifferSecretCb(ssl->arrays->clientRandom,
  447. SNIFFER_SECRET_TLS12_MASTER_SECRET,
  448. ssl->arrays->masterSecret);
  449. if (ret != 0) {
  450. return ret;
  451. }
  452. ret = DeriveTlsKeys(ssl);
  453. return ret;
  454. }
  455. #endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
  456. #ifdef HAVE_EXTENDED_MASTER
  457. if (ssl->options.haveEMS) {
  458. word32 hashSz = HSHASH_SZ;
  459. #ifdef WOLFSSL_SMALL_STACK
  460. byte* handshake_hash = (byte*)XMALLOC(HSHASH_SZ, ssl->heap,
  461. DYNAMIC_TYPE_DIGEST);
  462. if (handshake_hash == NULL)
  463. return MEMORY_E;
  464. #else
  465. byte handshake_hash[HSHASH_SZ];
  466. #endif
  467. ret = BuildTlsHandshakeHash(ssl, handshake_hash, &hashSz);
  468. if (ret == 0) {
  469. ret = _MakeTlsExtendedMasterSecret(
  470. ssl->arrays->masterSecret, SECRET_LEN,
  471. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz,
  472. handshake_hash, hashSz,
  473. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  474. ssl->heap, ssl->devId);
  475. ForceZero(handshake_hash, hashSz);
  476. }
  477. #ifdef WOLFSSL_SMALL_STACK
  478. XFREE(handshake_hash, ssl->heap, DYNAMIC_TYPE_DIGEST);
  479. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  480. wc_MemZero_Check(handshake_hash, HSHASH_SZ);
  481. #endif
  482. }
  483. else
  484. #endif /* HAVE_EXTENDED_MASTER */
  485. {
  486. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  487. ret = PROTOCOLCB_UNAVAILABLE;
  488. if (ssl->ctx->GenMasterCb) {
  489. void* ctx = wolfSSL_GetGenMasterSecretCtx(ssl);
  490. ret = ssl->ctx->GenMasterCb(ssl, ctx);
  491. }
  492. if (!ssl->ctx->GenMasterCb || ret == PROTOCOLCB_UNAVAILABLE)
  493. #endif
  494. {
  495. ret = _MakeTlsMasterSecret(ssl->arrays->masterSecret,
  496. SECRET_LEN, ssl->arrays->preMasterSecret,
  497. ssl->arrays->preMasterSz, ssl->arrays->clientRandom,
  498. ssl->arrays->serverRandom, IsAtLeastTLSv1_2(ssl),
  499. ssl->specs.mac_algorithm, ssl->heap, ssl->devId);
  500. }
  501. }
  502. if (ret == 0) {
  503. #ifdef SHOW_SECRETS
  504. /* Wireshark Pre-Master-Secret Format:
  505. * CLIENT_RANDOM <clientrandom> <mastersecret>
  506. */
  507. const char* CLIENT_RANDOM_LABEL = "CLIENT_RANDOM";
  508. int i, pmsPos = 0;
  509. char pmsBuf[13 + 1 + 64 + 1 + 96 + 1 + 1];
  510. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%s ",
  511. CLIENT_RANDOM_LABEL);
  512. pmsPos += XSTRLEN(CLIENT_RANDOM_LABEL) + 1;
  513. for (i = 0; i < RAN_LEN; i++) {
  514. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
  515. ssl->arrays->clientRandom[i]);
  516. pmsPos += 2;
  517. }
  518. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, " ");
  519. pmsPos += 1;
  520. for (i = 0; i < SECRET_LEN; i++) {
  521. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
  522. ssl->arrays->masterSecret[i]);
  523. pmsPos += 2;
  524. }
  525. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "\n");
  526. pmsPos += 1;
  527. /* print master secret */
  528. puts(pmsBuf);
  529. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE)
  530. {
  531. FILE* f = XFOPEN(WOLFSSL_SSLKEYLOGFILE_OUTPUT, "a");
  532. if (f != XBADFILE) {
  533. XFWRITE(pmsBuf, 1, pmsPos, f);
  534. XFCLOSE(f);
  535. }
  536. }
  537. #endif
  538. #endif /* SHOW_SECRETS */
  539. ret = DeriveTlsKeys(ssl);
  540. }
  541. return ret;
  542. }
  543. /* Used by EAP-TLS and EAP-TTLS to derive keying material from
  544. * the master_secret. */
  545. int wolfSSL_make_eap_keys(WOLFSSL* ssl, void* msk, unsigned int len,
  546. const char* label)
  547. {
  548. int ret;
  549. #ifdef WOLFSSL_SMALL_STACK
  550. byte* seed;
  551. #else
  552. byte seed[SEED_LEN];
  553. #endif
  554. #ifdef WOLFSSL_SMALL_STACK
  555. seed = (byte*)XMALLOC(SEED_LEN, ssl->heap, DYNAMIC_TYPE_SEED);
  556. if (seed == NULL)
  557. return MEMORY_E;
  558. #endif
  559. /*
  560. * As per RFC-5281, the order of the client and server randoms is reversed
  561. * from that used by the TLS protocol to derive keys.
  562. */
  563. XMEMCPY(seed, ssl->arrays->clientRandom, RAN_LEN);
  564. XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
  565. #ifdef WOLFSSL_HAVE_PRF
  566. PRIVATE_KEY_UNLOCK();
  567. ret = wc_PRF_TLS((byte*)msk, len, ssl->arrays->masterSecret, SECRET_LEN,
  568. (const byte *)label, (word32)XSTRLEN(label), seed, SEED_LEN,
  569. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  570. ssl->heap, ssl->devId);
  571. PRIVATE_KEY_LOCK();
  572. #else
  573. /* Pseudo random function must be enabled in the configuration. */
  574. ret = PRF_MISSING;
  575. WOLFSSL_MSG("Pseudo-random function is not enabled");
  576. (void)msk;
  577. (void)len;
  578. (void)label;
  579. #endif
  580. #ifdef WOLFSSL_SMALL_STACK
  581. XFREE(seed, ssl->heap, DYNAMIC_TYPE_SEED);
  582. #endif
  583. return ret;
  584. }
  585. int wolfSSL_GetHmacType_ex(CipherSpecs* specs)
  586. {
  587. if (specs == NULL)
  588. return BAD_FUNC_ARG;
  589. switch (specs->mac_algorithm) {
  590. #ifndef NO_MD5
  591. case md5_mac:
  592. {
  593. return WC_MD5;
  594. }
  595. #endif
  596. #ifndef NO_SHA256
  597. case sha256_mac:
  598. {
  599. return WC_SHA256;
  600. }
  601. #endif
  602. #ifdef WOLFSSL_SHA384
  603. case sha384_mac:
  604. {
  605. return WC_SHA384;
  606. }
  607. #endif
  608. #ifdef WOLFSSL_SM3
  609. case sm3_mac:
  610. {
  611. return WC_SM3;
  612. }
  613. #endif
  614. #ifndef NO_SHA
  615. case sha_mac:
  616. {
  617. return WC_SHA;
  618. }
  619. #endif
  620. #ifdef HAVE_BLAKE2
  621. case blake2b_mac:
  622. {
  623. return BLAKE2B_ID;
  624. }
  625. #endif
  626. default:
  627. {
  628. return WOLFSSL_FATAL_ERROR;
  629. }
  630. }
  631. }
  632. /* return HMAC digest type in wolfSSL format */
  633. int wolfSSL_GetHmacType(WOLFSSL* ssl)
  634. {
  635. if (ssl == NULL)
  636. return BAD_FUNC_ARG;
  637. return wolfSSL_GetHmacType_ex(&ssl->specs);
  638. }
  639. int wolfSSL_SetTlsHmacInner(WOLFSSL* ssl, byte* inner, word32 sz, int content,
  640. int verify)
  641. {
  642. if (ssl == NULL || inner == NULL)
  643. return BAD_FUNC_ARG;
  644. XMEMSET(inner, 0, WOLFSSL_TLS_HMAC_INNER_SZ);
  645. WriteSEQ(ssl, verify, inner);
  646. inner[SEQ_SZ] = (byte)content;
  647. inner[SEQ_SZ + ENUM_LEN] = ssl->version.major;
  648. inner[SEQ_SZ + ENUM_LEN + ENUM_LEN] = ssl->version.minor;
  649. c16toa((word16)sz, inner + SEQ_SZ + ENUM_LEN + VERSION_SZ);
  650. return 0;
  651. }
  652. #ifndef WOLFSSL_AEAD_ONLY
  653. #if !defined(WOLFSSL_NO_HASH_RAW) && !defined(HAVE_FIPS) && \
  654. !defined(HAVE_SELFTEST)
  655. /* Update the hash in the HMAC.
  656. *
  657. * hmac HMAC object.
  658. * data Data to be hashed.
  659. * sz Size of data to hash.
  660. * returns 0 on success, otherwise failure.
  661. */
  662. static int Hmac_HashUpdate(Hmac* hmac, const byte* data, word32 sz)
  663. {
  664. int ret = BAD_FUNC_ARG;
  665. switch (hmac->macType) {
  666. #ifndef NO_SHA
  667. case WC_SHA:
  668. ret = wc_ShaUpdate(&hmac->hash.sha, data, sz);
  669. break;
  670. #endif /* !NO_SHA */
  671. #ifndef NO_SHA256
  672. case WC_SHA256:
  673. ret = wc_Sha256Update(&hmac->hash.sha256, data, sz);
  674. break;
  675. #endif /* !NO_SHA256 */
  676. #ifdef WOLFSSL_SHA384
  677. case WC_SHA384:
  678. ret = wc_Sha384Update(&hmac->hash.sha384, data, sz);
  679. break;
  680. #endif /* WOLFSSL_SHA384 */
  681. #ifdef WOLFSSL_SHA512
  682. case WC_SHA512:
  683. ret = wc_Sha512Update(&hmac->hash.sha512, data, sz);
  684. break;
  685. #endif /* WOLFSSL_SHA512 */
  686. #ifdef WOLFSSL_SM3
  687. case WC_SM3:
  688. ret = wc_Sm3Update(&hmac->hash.sm3, data, sz);
  689. break;
  690. #endif /* WOLFSSL_SM3 */
  691. default:
  692. break;
  693. }
  694. return ret;
  695. }
  696. /* Finalize the hash but don't put the EOC, padding or length in.
  697. *
  698. * hmac HMAC object.
  699. * hash Hash result.
  700. * returns 0 on success, otherwise failure.
  701. */
  702. static int Hmac_HashFinalRaw(Hmac* hmac, unsigned char* hash)
  703. {
  704. int ret = BAD_FUNC_ARG;
  705. switch (hmac->macType) {
  706. #ifndef NO_SHA
  707. case WC_SHA:
  708. ret = wc_ShaFinalRaw(&hmac->hash.sha, hash);
  709. break;
  710. #endif /* !NO_SHA */
  711. #ifndef NO_SHA256
  712. case WC_SHA256:
  713. ret = wc_Sha256FinalRaw(&hmac->hash.sha256, hash);
  714. break;
  715. #endif /* !NO_SHA256 */
  716. #ifdef WOLFSSL_SHA384
  717. case WC_SHA384:
  718. ret = wc_Sha384FinalRaw(&hmac->hash.sha384, hash);
  719. break;
  720. #endif /* WOLFSSL_SHA384 */
  721. #ifdef WOLFSSL_SHA512
  722. case WC_SHA512:
  723. ret = wc_Sha512FinalRaw(&hmac->hash.sha512, hash);
  724. break;
  725. #endif /* WOLFSSL_SHA512 */
  726. #ifdef WOLFSSL_SM3
  727. case WC_SM3:
  728. ret = wc_Sm3FinalRaw(&hmac->hash.sm3, hash);
  729. break;
  730. #endif /* WOLFSSL_SM3 */
  731. default:
  732. break;
  733. }
  734. return ret;
  735. }
  736. /* Finalize the HMAC by performing outer hash.
  737. *
  738. * hmac HMAC object.
  739. * mac MAC result.
  740. * returns 0 on success, otherwise failure.
  741. */
  742. static int Hmac_OuterHash(Hmac* hmac, unsigned char* mac)
  743. {
  744. int ret = BAD_FUNC_ARG;
  745. wc_HashAlg hash;
  746. enum wc_HashType hashType = (enum wc_HashType)hmac->macType;
  747. int digestSz = wc_HashGetDigestSize(hashType);
  748. int blockSz = wc_HashGetBlockSize(hashType);
  749. if ((digestSz >= 0) && (blockSz >= 0)) {
  750. ret = wc_HashInit(&hash, hashType);
  751. }
  752. if (ret == 0) {
  753. ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->opad,
  754. blockSz);
  755. if (ret == 0)
  756. ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->innerHash,
  757. digestSz);
  758. if (ret == 0)
  759. ret = wc_HashFinal(&hash, hashType, mac);
  760. wc_HashFree(&hash, hashType);
  761. }
  762. return ret;
  763. }
  764. /* Calculate the HMAC of the header + message data.
  765. * Constant time implementation using wc_Sha*FinalRaw().
  766. *
  767. * hmac HMAC object.
  768. * digest MAC result.
  769. * in Message data.
  770. * sz Size of the message data.
  771. * header Constructed record header with length of handshake data.
  772. * returns 0 on success, otherwise failure.
  773. */
  774. static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in,
  775. word32 sz, int macLen, byte* header)
  776. {
  777. byte lenBytes[8];
  778. int i, j;
  779. unsigned int k;
  780. int blockBits, blockMask;
  781. int lastBlockLen, extraLen, eocIndex;
  782. int blocks, safeBlocks, lenBlock, eocBlock;
  783. unsigned int maxLen;
  784. int blockSz, padSz;
  785. int ret;
  786. word32 realLen;
  787. byte extraBlock;
  788. switch (hmac->macType) {
  789. #ifndef NO_SHA
  790. case WC_SHA:
  791. blockSz = WC_SHA_BLOCK_SIZE;
  792. blockBits = 6;
  793. padSz = WC_SHA_BLOCK_SIZE - WC_SHA_PAD_SIZE + 1;
  794. break;
  795. #endif /* !NO_SHA */
  796. #ifndef NO_SHA256
  797. case WC_SHA256:
  798. blockSz = WC_SHA256_BLOCK_SIZE;
  799. blockBits = 6;
  800. padSz = WC_SHA256_BLOCK_SIZE - WC_SHA256_PAD_SIZE + 1;
  801. break;
  802. #endif /* !NO_SHA256 */
  803. #ifdef WOLFSSL_SHA384
  804. case WC_SHA384:
  805. blockSz = WC_SHA384_BLOCK_SIZE;
  806. blockBits = 7;
  807. padSz = WC_SHA384_BLOCK_SIZE - WC_SHA384_PAD_SIZE + 1;
  808. break;
  809. #endif /* WOLFSSL_SHA384 */
  810. #ifdef WOLFSSL_SHA512
  811. case WC_SHA512:
  812. blockSz = WC_SHA512_BLOCK_SIZE;
  813. blockBits = 7;
  814. padSz = WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE + 1;
  815. break;
  816. #endif /* WOLFSSL_SHA512 */
  817. #ifdef WOLFSSL_SM3
  818. case WC_SM3:
  819. blockSz = WC_SM3_BLOCK_SIZE;
  820. blockBits = 6;
  821. padSz = WC_SM3_BLOCK_SIZE - WC_SM3_PAD_SIZE + 1;
  822. break;
  823. #endif /* WOLFSSL_SM3 */
  824. default:
  825. return BAD_FUNC_ARG;
  826. }
  827. blockMask = blockSz - 1;
  828. /* Size of data to HMAC if padding length byte is zero. */
  829. maxLen = WOLFSSL_TLS_HMAC_INNER_SZ + sz - 1 - macLen;
  830. /* Complete data (including padding) has block for EOC and/or length. */
  831. extraBlock = ctSetLTE((maxLen + padSz) & blockMask, padSz);
  832. /* Total number of blocks for data including padding. */
  833. blocks = ((maxLen + blockSz - 1) >> blockBits) + extraBlock;
  834. /* Up to last 6 blocks can be hashed safely. */
  835. safeBlocks = blocks - 6;
  836. /* Length of message data. */
  837. realLen = maxLen - in[sz - 1];
  838. /* Number of message bytes in last block. */
  839. lastBlockLen = realLen & blockMask;
  840. /* Number of padding bytes in last block. */
  841. extraLen = ((blockSz * 2 - padSz - lastBlockLen) & blockMask) + 1;
  842. /* Number of blocks to create for hash. */
  843. lenBlock = (realLen + extraLen) >> blockBits;
  844. /* Block containing EOC byte. */
  845. eocBlock = realLen >> blockBits;
  846. /* Index of EOC byte in block. */
  847. eocIndex = realLen & blockMask;
  848. /* Add length of hmac's ipad to total length. */
  849. realLen += blockSz;
  850. /* Length as bits - 8 bytes bigendian. */
  851. c32toa(realLen >> ((sizeof(word32) * 8) - 3), lenBytes);
  852. c32toa(realLen << 3, lenBytes + sizeof(word32));
  853. ret = Hmac_HashUpdate(hmac, (unsigned char*)hmac->ipad, blockSz);
  854. if (ret != 0)
  855. return ret;
  856. XMEMSET(hmac->innerHash, 0, macLen);
  857. if (safeBlocks > 0) {
  858. ret = Hmac_HashUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ);
  859. if (ret != 0)
  860. return ret;
  861. ret = Hmac_HashUpdate(hmac, in, safeBlocks * blockSz -
  862. WOLFSSL_TLS_HMAC_INNER_SZ);
  863. if (ret != 0)
  864. return ret;
  865. }
  866. else
  867. safeBlocks = 0;
  868. XMEMSET(digest, 0, macLen);
  869. k = safeBlocks * blockSz;
  870. for (i = safeBlocks; i < blocks; i++) {
  871. unsigned char hashBlock[WC_MAX_BLOCK_SIZE];
  872. unsigned char isEocBlock = ctMaskEq(i, eocBlock);
  873. unsigned char isOutBlock = ctMaskEq(i, lenBlock);
  874. for (j = 0; j < blockSz; j++) {
  875. unsigned char atEoc = ctMaskEq(j, eocIndex) & isEocBlock;
  876. unsigned char pastEoc = ctMaskGT(j, eocIndex) & isEocBlock;
  877. unsigned char b = 0;
  878. if (k < WOLFSSL_TLS_HMAC_INNER_SZ)
  879. b = header[k];
  880. else if (k < maxLen)
  881. b = in[k - WOLFSSL_TLS_HMAC_INNER_SZ];
  882. k++;
  883. b = ctMaskSel(atEoc, 0x80, b);
  884. b &= (unsigned char)~(word32)pastEoc;
  885. b &= ((unsigned char)~(word32)isOutBlock) | isEocBlock;
  886. if (j >= blockSz - 8) {
  887. b = ctMaskSel(isOutBlock, lenBytes[j - (blockSz - 8)], b);
  888. }
  889. hashBlock[j] = b;
  890. }
  891. ret = Hmac_HashUpdate(hmac, hashBlock, blockSz);
  892. if (ret != 0)
  893. return ret;
  894. ret = Hmac_HashFinalRaw(hmac, hashBlock);
  895. if (ret != 0)
  896. return ret;
  897. for (j = 0; j < macLen; j++)
  898. ((unsigned char*)hmac->innerHash)[j] |= hashBlock[j] & isOutBlock;
  899. }
  900. ret = Hmac_OuterHash(hmac, digest);
  901. return ret;
  902. }
  903. #endif
  904. #if defined(WOLFSSL_NO_HASH_RAW) || defined(HAVE_FIPS) || \
  905. defined(HAVE_SELFTEST) || defined(HAVE_BLAKE2)
  906. /* Calculate the HMAC of the header + message data.
  907. * Constant time implementation using normal hashing operations.
  908. * Update-Final need to be constant time.
  909. *
  910. * hmac HMAC object.
  911. * digest MAC result.
  912. * in Message data.
  913. * sz Size of the message data.
  914. * header Constructed record header with length of handshake data.
  915. * returns 0 on success, otherwise failure.
  916. */
  917. static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in,
  918. word32 sz, byte* header)
  919. {
  920. byte dummy[WC_MAX_BLOCK_SIZE] = {0};
  921. int ret = 0;
  922. word32 msgSz, blockSz, macSz, padSz, maxSz, realSz;
  923. word32 offset = 0;
  924. int msgBlocks, blocks, blockBits;
  925. int i;
  926. switch (hmac->macType) {
  927. #ifndef NO_SHA
  928. case WC_SHA:
  929. blockSz = WC_SHA_BLOCK_SIZE;
  930. blockBits = 6;
  931. macSz = WC_SHA_DIGEST_SIZE;
  932. padSz = WC_SHA_BLOCK_SIZE - WC_SHA_PAD_SIZE + 1;
  933. break;
  934. #endif /* !NO_SHA */
  935. #ifndef NO_SHA256
  936. case WC_SHA256:
  937. blockSz = WC_SHA256_BLOCK_SIZE;
  938. blockBits = 6;
  939. macSz = WC_SHA256_DIGEST_SIZE;
  940. padSz = WC_SHA256_BLOCK_SIZE - WC_SHA256_PAD_SIZE + 1;
  941. break;
  942. #endif /* !NO_SHA256 */
  943. #ifdef WOLFSSL_SHA384
  944. case WC_SHA384:
  945. blockSz = WC_SHA384_BLOCK_SIZE;
  946. blockBits = 7;
  947. macSz = WC_SHA384_DIGEST_SIZE;
  948. padSz = WC_SHA384_BLOCK_SIZE - WC_SHA384_PAD_SIZE + 1;
  949. break;
  950. #endif /* WOLFSSL_SHA384 */
  951. #ifdef WOLFSSL_SHA512
  952. case WC_SHA512:
  953. blockSz = WC_SHA512_BLOCK_SIZE;
  954. blockBits = 7;
  955. macSz = WC_SHA512_DIGEST_SIZE;
  956. padSz = WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE + 1;
  957. break;
  958. #endif /* WOLFSSL_SHA512 */
  959. #ifdef HAVE_BLAKE2
  960. case WC_HASH_TYPE_BLAKE2B:
  961. blockSz = BLAKE2B_BLOCKBYTES;
  962. blockBits = 7;
  963. macSz = BLAKE2B_256;
  964. padSz = 0;
  965. break;
  966. #endif /* HAVE_BLAKE2 */
  967. #ifdef WOLFSSL_SM3
  968. case WC_SM3:
  969. blockSz = WC_SM3_BLOCK_SIZE;
  970. blockBits = 6;
  971. macSz = WC_SM3_DIGEST_SIZE;
  972. padSz = WC_SM3_BLOCK_SIZE - WC_SM3_PAD_SIZE + 1;
  973. break;
  974. #endif
  975. default:
  976. WOLFSSL_MSG("ERROR: Hmac_UpdateFinal failed, no hmac->macType");
  977. return BAD_FUNC_ARG;
  978. }
  979. msgSz = sz - (1 + in[sz - 1] + macSz);
  980. /* Make negative result 0 */
  981. msgSz &= ~(0 - (msgSz >> 31));
  982. realSz = WOLFSSL_TLS_HMAC_INNER_SZ + msgSz;
  983. maxSz = WOLFSSL_TLS_HMAC_INNER_SZ + (sz - 1) - macSz;
  984. /* Calculate #blocks processed in HMAC for max and real data. */
  985. blocks = maxSz >> blockBits;
  986. blocks += ((maxSz + padSz) % blockSz) < padSz;
  987. msgBlocks = realSz >> blockBits;
  988. /* #Extra blocks to process. */
  989. blocks -= msgBlocks + ((((realSz + padSz) % blockSz) < padSz) ? 1 : 0);
  990. /* Calculate whole blocks. */
  991. msgBlocks--;
  992. ret = wc_HmacUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ);
  993. if (ret == 0) {
  994. /* Fill the rest of the block with any available data. */
  995. word32 currSz = ctMaskLT(msgSz, blockSz) & msgSz;
  996. currSz |= ctMaskGTE(msgSz, blockSz) & blockSz;
  997. currSz -= WOLFSSL_TLS_HMAC_INNER_SZ;
  998. currSz &= ~(0 - (currSz >> 31));
  999. ret = wc_HmacUpdate(hmac, in, currSz);
  1000. offset = currSz;
  1001. }
  1002. if (ret == 0) {
  1003. /* Do the hash operations on a block basis. */
  1004. for (i = 0; i < msgBlocks; i++, offset += blockSz) {
  1005. ret = wc_HmacUpdate(hmac, in + offset, blockSz);
  1006. if (ret != 0)
  1007. break;
  1008. }
  1009. }
  1010. if (ret == 0)
  1011. ret = wc_HmacUpdate(hmac, in + offset, msgSz - offset);
  1012. if (ret == 0)
  1013. ret = wc_HmacFinal(hmac, digest);
  1014. if (ret == 0) {
  1015. /* Do the dummy hash operations. Do at least one. */
  1016. for (i = 0; i < blocks + 1; i++) {
  1017. ret = wc_HmacUpdate(hmac, dummy, blockSz);
  1018. if (ret != 0)
  1019. break;
  1020. }
  1021. }
  1022. return ret;
  1023. }
  1024. #endif
  1025. int TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, int padSz,
  1026. int content, int verify, int epochOrder)
  1027. {
  1028. Hmac hmac;
  1029. byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
  1030. int ret = 0;
  1031. const byte* macSecret = NULL;
  1032. word32 hashSz = 0;
  1033. if (ssl == NULL)
  1034. return BAD_FUNC_ARG;
  1035. #ifdef HAVE_TRUNCATED_HMAC
  1036. hashSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  1037. : ssl->specs.hash_size;
  1038. #else
  1039. hashSz = ssl->specs.hash_size;
  1040. #endif
  1041. #ifdef HAVE_FUZZER
  1042. /* Fuzz "in" buffer with sz to be used in HMAC algorithm */
  1043. if (ssl->fuzzerCb) {
  1044. if (verify && padSz >= 0) {
  1045. ssl->fuzzerCb(ssl, in, sz + hashSz + padSz + 1, FUZZ_HMAC,
  1046. ssl->fuzzerCtx);
  1047. }
  1048. else {
  1049. ssl->fuzzerCb(ssl, in, sz, FUZZ_HMAC, ssl->fuzzerCtx);
  1050. }
  1051. }
  1052. #endif
  1053. if (!ssl->options.dtls)
  1054. wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, verify);
  1055. else
  1056. wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, epochOrder);
  1057. ret = wc_HmacInit(&hmac, ssl->heap, ssl->devId);
  1058. if (ret != 0)
  1059. return ret;
  1060. #ifdef WOLFSSL_DTLS
  1061. if (ssl->options.dtls)
  1062. macSecret = wolfSSL_GetDtlsMacSecret(ssl, verify, epochOrder);
  1063. else
  1064. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  1065. #else
  1066. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  1067. #endif
  1068. ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
  1069. macSecret,
  1070. ssl->specs.hash_size);
  1071. if (ret == 0) {
  1072. /* Constant time verification required. */
  1073. if (verify && padSz >= 0) {
  1074. #if !defined(WOLFSSL_NO_HASH_RAW) && !defined(HAVE_FIPS) && \
  1075. !defined(HAVE_SELFTEST)
  1076. #ifdef HAVE_BLAKE2
  1077. if (wolfSSL_GetHmacType(ssl) == WC_HASH_TYPE_BLAKE2B) {
  1078. ret = Hmac_UpdateFinal(&hmac, digest, in,
  1079. sz + hashSz + padSz + 1, myInner);
  1080. }
  1081. else
  1082. #endif
  1083. {
  1084. ret = Hmac_UpdateFinal_CT(&hmac, digest, in,
  1085. sz + hashSz + padSz + 1, hashSz, myInner);
  1086. }
  1087. #else
  1088. ret = Hmac_UpdateFinal(&hmac, digest, in, sz + hashSz + padSz + 1,
  1089. myInner);
  1090. #endif
  1091. }
  1092. else {
  1093. ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
  1094. if (ret == 0)
  1095. ret = wc_HmacUpdate(&hmac, in, sz); /* content */
  1096. if (ret == 0)
  1097. ret = wc_HmacFinal(&hmac, digest);
  1098. }
  1099. }
  1100. wc_HmacFree(&hmac);
  1101. return ret;
  1102. }
  1103. #endif /* WOLFSSL_AEAD_ONLY */
  1104. #endif /* !WOLFSSL_NO_TLS12 */
  1105. #ifdef HAVE_TLS_EXTENSIONS
  1106. /**
  1107. * The TLSX semaphore is used to calculate the size of the extensions to be sent
  1108. * from one peer to another.
  1109. */
  1110. /** Supports up to 72 flags. Increase as needed. */
  1111. #define SEMAPHORE_SIZE 9
  1112. /**
  1113. * Converts the extension type (id) to an index in the semaphore.
  1114. *
  1115. * Official reference for TLS extension types:
  1116. * http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xml
  1117. *
  1118. * Motivation:
  1119. * Previously, we used the extension type itself as the index of that
  1120. * extension in the semaphore as the extension types were declared
  1121. * sequentially, but maintain a semaphore as big as the number of available
  1122. * extensions is no longer an option since the release of renegotiation_info.
  1123. *
  1124. * How to update:
  1125. * Assign extension types that extrapolate the number of available semaphores
  1126. * to the first available index going backwards in the semaphore array.
  1127. * When adding a new extension type that don't extrapolate the number of
  1128. * available semaphores, check for a possible collision with with a
  1129. * 'remapped' extension type.
  1130. *
  1131. * Update TLSX_Parse for duplicate detection if more added above 62.
  1132. */
  1133. static WC_INLINE word16 TLSX_ToSemaphore(word16 type)
  1134. {
  1135. switch (type) {
  1136. case TLSX_RENEGOTIATION_INFO: /* 0xFF01 */
  1137. return 63;
  1138. #ifdef WOLFSSL_QUIC
  1139. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT: /* 0xffa5 */
  1140. return 64;
  1141. #endif
  1142. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1143. case TLSX_ECH: /* 0xfe0d */
  1144. return 65;
  1145. #endif
  1146. default:
  1147. if (type > 62) {
  1148. /* This message SHOULD only happens during the adding of
  1149. new TLS extensions in which its IANA number overflows
  1150. the current semaphore's range, or if its number already
  1151. is assigned to be used by another extension.
  1152. Use this check value for the new extension and decrement
  1153. the check value by one. */
  1154. WOLFSSL_MSG("### TLSX semaphore collision or overflow detected!");
  1155. }
  1156. }
  1157. return type;
  1158. }
  1159. /** Checks if a specific light (tls extension) is not set in the semaphore. */
  1160. #define IS_OFF(semaphore, light) \
  1161. (!(((semaphore)[(light) / 8] & (byte) (0x01 << ((light) % 8)))))
  1162. /** Turn on a specific light (tls extension) in the semaphore. */
  1163. /* the semaphore marks the extensions already written to the message */
  1164. #define TURN_ON(semaphore, light) \
  1165. ((semaphore)[(light) / 8] |= (byte) (0x01 << ((light) % 8)))
  1166. /** Turn off a specific light (tls extension) in the semaphore. */
  1167. #define TURN_OFF(semaphore, light) \
  1168. ((semaphore)[(light) / 8] &= (byte) ~(0x01 << ((light) % 8)))
  1169. /** Creates a new extension. */
  1170. static TLSX* TLSX_New(TLSX_Type type, const void* data, void* heap)
  1171. {
  1172. TLSX* extension = (TLSX*)XMALLOC(sizeof(TLSX), heap, DYNAMIC_TYPE_TLSX);
  1173. (void)heap;
  1174. if (extension) {
  1175. extension->type = type;
  1176. extension->data = (void*)data;
  1177. extension->resp = 0;
  1178. extension->next = NULL;
  1179. }
  1180. return extension;
  1181. }
  1182. /**
  1183. * Creates a new extension and appends it to the provided list.
  1184. * Checks for duplicate extensions, keeps the newest.
  1185. */
  1186. int TLSX_Append(TLSX** list, TLSX_Type type, const void* data, void* heap)
  1187. {
  1188. TLSX* extension = TLSX_New(type, data, heap);
  1189. TLSX* cur;
  1190. TLSX** prevNext = list;
  1191. if (extension == NULL)
  1192. return MEMORY_E;
  1193. for (cur = *list; cur != NULL;) {
  1194. if (cur->type == type) {
  1195. *prevNext = cur->next;
  1196. cur->next = NULL;
  1197. TLSX_FreeAll(cur, heap);
  1198. cur = *prevNext;
  1199. }
  1200. else {
  1201. prevNext = &cur->next;
  1202. cur = cur->next;
  1203. }
  1204. }
  1205. /* Append the extension to the list */
  1206. *prevNext = extension;
  1207. return 0;
  1208. }
  1209. /**
  1210. * Creates a new extension and pushes it to the provided list.
  1211. * Checks for duplicate extensions, keeps the newest.
  1212. */
  1213. int TLSX_Push(TLSX** list, TLSX_Type type, const void* data, void* heap)
  1214. {
  1215. TLSX* extension = TLSX_New(type, data, heap);
  1216. if (extension == NULL)
  1217. return MEMORY_E;
  1218. /* pushes the new extension on the list. */
  1219. extension->next = *list;
  1220. *list = extension;
  1221. /* remove duplicate extensions, there should be only one of each type. */
  1222. do {
  1223. if (extension->next && extension->next->type == type) {
  1224. TLSX *next = extension->next;
  1225. extension->next = next->next;
  1226. next->next = NULL;
  1227. TLSX_FreeAll(next, heap);
  1228. /* there is no way to occur more than
  1229. * two extensions of the same type.
  1230. */
  1231. break;
  1232. }
  1233. } while ((extension = extension->next));
  1234. return 0;
  1235. }
  1236. #ifndef NO_WOLFSSL_CLIENT
  1237. int TLSX_CheckUnsupportedExtension(WOLFSSL* ssl, TLSX_Type type);
  1238. int TLSX_CheckUnsupportedExtension(WOLFSSL* ssl, TLSX_Type type)
  1239. {
  1240. TLSX *extension = TLSX_Find(ssl->extensions, type);
  1241. if (!extension)
  1242. extension = TLSX_Find(ssl->ctx->extensions, type);
  1243. return extension == NULL;
  1244. }
  1245. int TLSX_HandleUnsupportedExtension(WOLFSSL* ssl);
  1246. int TLSX_HandleUnsupportedExtension(WOLFSSL* ssl)
  1247. {
  1248. SendAlert(ssl, alert_fatal, unsupported_extension);
  1249. WOLFSSL_ERROR_VERBOSE(UNSUPPORTED_EXTENSION);
  1250. return UNSUPPORTED_EXTENSION;
  1251. }
  1252. #else
  1253. #define TLSX_CheckUnsupportedExtension(ssl, type) 0
  1254. #define TLSX_HandleUnsupportedExtension(ssl) 0
  1255. #endif
  1256. #if !defined(NO_WOLFSSL_SERVER) || defined(WOLFSSL_TLS13)
  1257. void TLSX_SetResponse(WOLFSSL* ssl, TLSX_Type type);
  1258. /** Mark an extension to be sent back to the client. */
  1259. void TLSX_SetResponse(WOLFSSL* ssl, TLSX_Type type)
  1260. {
  1261. TLSX *extension = TLSX_Find(ssl->extensions, type);
  1262. if (extension)
  1263. extension->resp = 1;
  1264. }
  1265. #endif
  1266. /******************************************************************************/
  1267. /* Application-Layer Protocol Negotiation */
  1268. /******************************************************************************/
  1269. #ifdef HAVE_ALPN
  1270. /** Creates a new ALPN object, providing protocol name to use. */
  1271. static ALPN* TLSX_ALPN_New(char *protocol_name, word16 protocol_nameSz,
  1272. void* heap)
  1273. {
  1274. ALPN *alpn;
  1275. WOLFSSL_ENTER("TLSX_ALPN_New");
  1276. if (protocol_name == NULL ||
  1277. protocol_nameSz > WOLFSSL_MAX_ALPN_PROTO_NAME_LEN) {
  1278. WOLFSSL_MSG("Invalid arguments");
  1279. return NULL;
  1280. }
  1281. alpn = (ALPN*)XMALLOC(sizeof(ALPN), heap, DYNAMIC_TYPE_TLSX);
  1282. if (alpn == NULL) {
  1283. WOLFSSL_MSG("Memory failure");
  1284. return NULL;
  1285. }
  1286. alpn->next = NULL;
  1287. alpn->negotiated = 0;
  1288. alpn->options = 0;
  1289. alpn->protocol_name = (char*)XMALLOC(protocol_nameSz + 1,
  1290. heap, DYNAMIC_TYPE_TLSX);
  1291. if (alpn->protocol_name == NULL) {
  1292. WOLFSSL_MSG("Memory failure");
  1293. XFREE(alpn, heap, DYNAMIC_TYPE_TLSX);
  1294. return NULL;
  1295. }
  1296. XMEMCPY(alpn->protocol_name, protocol_name, protocol_nameSz);
  1297. alpn->protocol_name[protocol_nameSz] = 0;
  1298. (void)heap;
  1299. return alpn;
  1300. }
  1301. /** Releases an ALPN object. */
  1302. static void TLSX_ALPN_Free(ALPN *alpn, void* heap)
  1303. {
  1304. (void)heap;
  1305. if (alpn == NULL)
  1306. return;
  1307. XFREE(alpn->protocol_name, heap, DYNAMIC_TYPE_TLSX);
  1308. XFREE(alpn, heap, DYNAMIC_TYPE_TLSX);
  1309. }
  1310. /** Releases all ALPN objects in the provided list. */
  1311. static void TLSX_ALPN_FreeAll(ALPN *list, void* heap)
  1312. {
  1313. ALPN* alpn;
  1314. while ((alpn = list)) {
  1315. list = alpn->next;
  1316. TLSX_ALPN_Free(alpn, heap);
  1317. }
  1318. }
  1319. /** Tells the buffered size of the ALPN objects in a list. */
  1320. static word16 TLSX_ALPN_GetSize(ALPN *list)
  1321. {
  1322. ALPN* alpn;
  1323. word16 length = OPAQUE16_LEN; /* list length */
  1324. while ((alpn = list)) {
  1325. list = alpn->next;
  1326. length++; /* protocol name length is on one byte */
  1327. length += (word16)XSTRLEN(alpn->protocol_name);
  1328. }
  1329. return length;
  1330. }
  1331. /** Writes the ALPN objects of a list in a buffer. */
  1332. static word16 TLSX_ALPN_Write(ALPN *list, byte *output)
  1333. {
  1334. ALPN* alpn;
  1335. word16 length = 0;
  1336. word16 offset = OPAQUE16_LEN; /* list length offset */
  1337. while ((alpn = list)) {
  1338. list = alpn->next;
  1339. length = (word16)XSTRLEN(alpn->protocol_name);
  1340. /* protocol name length */
  1341. output[offset++] = (byte)length;
  1342. /* protocol name value */
  1343. XMEMCPY(output + offset, alpn->protocol_name, length);
  1344. offset += length;
  1345. }
  1346. /* writing list length */
  1347. c16toa(offset - OPAQUE16_LEN, output);
  1348. return offset;
  1349. }
  1350. /** Finds a protocol name in the provided ALPN list */
  1351. static ALPN* TLSX_ALPN_Find(ALPN *list, char *protocol_name, word16 size)
  1352. {
  1353. ALPN *alpn;
  1354. if (list == NULL || protocol_name == NULL)
  1355. return NULL;
  1356. alpn = list;
  1357. while (alpn != NULL && (
  1358. (word16)XSTRLEN(alpn->protocol_name) != size ||
  1359. XSTRNCMP(alpn->protocol_name, protocol_name, size)))
  1360. alpn = alpn->next;
  1361. return alpn;
  1362. }
  1363. /** Set the ALPN matching client and server requirements */
  1364. static int TLSX_SetALPN(TLSX** extensions, const void* data, word16 size,
  1365. void* heap)
  1366. {
  1367. ALPN *alpn;
  1368. int ret;
  1369. if (extensions == NULL || data == NULL)
  1370. return BAD_FUNC_ARG;
  1371. alpn = TLSX_ALPN_New((char *)data, size, heap);
  1372. if (alpn == NULL) {
  1373. WOLFSSL_MSG("Memory failure");
  1374. return MEMORY_E;
  1375. }
  1376. alpn->negotiated = 1;
  1377. ret = TLSX_Push(extensions, TLSX_APPLICATION_LAYER_PROTOCOL, (void*)alpn,
  1378. heap);
  1379. if (ret != 0) {
  1380. TLSX_ALPN_Free(alpn, heap);
  1381. return ret;
  1382. }
  1383. return WOLFSSL_SUCCESS;
  1384. }
  1385. static int ALPN_find_match(WOLFSSL *ssl, TLSX **pextension,
  1386. const byte **psel, byte *psel_len,
  1387. const byte *alpn_val, word16 alpn_val_len)
  1388. {
  1389. TLSX *extension;
  1390. ALPN *alpn, *list;
  1391. const byte *sel = NULL, *s;
  1392. byte sel_len = 0, wlen;
  1393. extension = TLSX_Find(ssl->extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1394. if (extension == NULL)
  1395. extension = TLSX_Find(ssl->ctx->extensions,
  1396. TLSX_APPLICATION_LAYER_PROTOCOL);
  1397. /* No ALPN configured here */
  1398. if (extension == NULL || extension->data == NULL) {
  1399. *pextension = NULL;
  1400. *psel = NULL;
  1401. *psel_len = 0;
  1402. return 0;
  1403. }
  1404. list = (ALPN*)extension->data;
  1405. for (s = alpn_val;
  1406. (s - alpn_val) < alpn_val_len;
  1407. s += wlen) {
  1408. wlen = *s++; /* bounds already checked on save */
  1409. alpn = TLSX_ALPN_Find(list, (char*)s, wlen);
  1410. if (alpn != NULL) {
  1411. WOLFSSL_MSG("ALPN protocol match");
  1412. sel = s,
  1413. sel_len = wlen;
  1414. break;
  1415. }
  1416. }
  1417. if (sel == NULL) {
  1418. WOLFSSL_MSG("No ALPN protocol match");
  1419. /* do nothing if no protocol match between client and server and option
  1420. is set to continue (like OpenSSL) */
  1421. if (list->options & WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) {
  1422. WOLFSSL_MSG("Continue on mismatch");
  1423. }
  1424. else {
  1425. SendAlert(ssl, alert_fatal, no_application_protocol);
  1426. WOLFSSL_ERROR_VERBOSE(UNKNOWN_ALPN_PROTOCOL_NAME_E);
  1427. return UNKNOWN_ALPN_PROTOCOL_NAME_E;
  1428. }
  1429. }
  1430. *pextension = extension;
  1431. *psel = sel;
  1432. *psel_len = sel_len;
  1433. return 0;
  1434. }
  1435. int ALPN_Select(WOLFSSL *ssl)
  1436. {
  1437. TLSX *extension;
  1438. const byte *sel = NULL;
  1439. byte sel_len = 0;
  1440. int r = 0;
  1441. WOLFSSL_ENTER("ALPN_Select");
  1442. if (ssl->alpn_peer_requested == NULL)
  1443. return 0;
  1444. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  1445. if (ssl->alpnSelect != NULL && ssl->options.side == WOLFSSL_SERVER_END) {
  1446. r = ssl->alpnSelect(ssl, &sel, &sel_len, ssl->alpn_peer_requested,
  1447. ssl->alpn_peer_requested_length, ssl->alpnSelectArg);
  1448. switch (r) {
  1449. case SSL_TLSEXT_ERR_OK:
  1450. WOLFSSL_MSG("ALPN protocol match");
  1451. break;
  1452. case SSL_TLSEXT_ERR_NOACK:
  1453. WOLFSSL_MSG("ALPN cb no match but not fatal");
  1454. sel = NULL;
  1455. sel_len = 0;
  1456. break;
  1457. case SSL_TLSEXT_ERR_ALERT_FATAL:
  1458. default:
  1459. WOLFSSL_MSG("ALPN cb no match and fatal");
  1460. SendAlert(ssl, alert_fatal, no_application_protocol);
  1461. WOLFSSL_ERROR_VERBOSE(UNKNOWN_ALPN_PROTOCOL_NAME_E);
  1462. return UNKNOWN_ALPN_PROTOCOL_NAME_E;
  1463. }
  1464. }
  1465. else
  1466. #endif
  1467. {
  1468. r = ALPN_find_match(ssl, &extension, &sel, &sel_len,
  1469. ssl->alpn_peer_requested,
  1470. ssl->alpn_peer_requested_length);
  1471. if (r != 0)
  1472. return r;
  1473. }
  1474. if (sel != NULL) {
  1475. /* set the matching negotiated protocol */
  1476. r = TLSX_SetALPN(&ssl->extensions, sel, sel_len, ssl->heap);
  1477. if (r != WOLFSSL_SUCCESS) {
  1478. WOLFSSL_MSG("TLSX_SetALPN failed");
  1479. return BUFFER_ERROR;
  1480. }
  1481. /* reply to ALPN extension sent from peer */
  1482. #ifndef NO_WOLFSSL_SERVER
  1483. TLSX_SetResponse(ssl, TLSX_APPLICATION_LAYER_PROTOCOL);
  1484. #endif
  1485. }
  1486. return 0;
  1487. }
  1488. /** Parses a buffer of ALPN extensions and set the first one matching
  1489. * client and server requirements */
  1490. static int TLSX_ALPN_ParseAndSet(WOLFSSL *ssl, const byte *input, word16 length,
  1491. byte isRequest)
  1492. {
  1493. word16 size = 0, offset = 0, wlen;
  1494. int r = BUFFER_ERROR;
  1495. const byte *s;
  1496. if (OPAQUE16_LEN > length)
  1497. return BUFFER_ERROR;
  1498. ato16(input, &size);
  1499. offset += OPAQUE16_LEN;
  1500. /* validating alpn list length */
  1501. if (size == 0 || length != OPAQUE16_LEN + size)
  1502. return BUFFER_ERROR;
  1503. /* validating length of entries before accepting */
  1504. for (s = input + offset; (s - input) < size; s += wlen) {
  1505. wlen = *s++;
  1506. if (wlen == 0 || (s + wlen - input) > length)
  1507. return BUFFER_ERROR;
  1508. }
  1509. if (isRequest) {
  1510. /* keep the list sent by peer, if this is from a request. We
  1511. * use it later in ALPN_Select() for evaluation. */
  1512. if (ssl->alpn_peer_requested != NULL) {
  1513. XFREE(ssl->alpn_peer_requested, ssl->heap, DYNAMIC_TYPE_ALPN);
  1514. ssl->alpn_peer_requested_length = 0;
  1515. }
  1516. ssl->alpn_peer_requested = (byte *)XMALLOC(size, ssl->heap,
  1517. DYNAMIC_TYPE_ALPN);
  1518. if (ssl->alpn_peer_requested == NULL) {
  1519. return MEMORY_ERROR;
  1520. }
  1521. ssl->alpn_peer_requested_length = size;
  1522. XMEMCPY(ssl->alpn_peer_requested, (char*)input + offset, size);
  1523. }
  1524. else {
  1525. /* a response, we should find the value in our config */
  1526. const byte *sel = NULL;
  1527. byte sel_len = 0;
  1528. TLSX *extension = NULL;
  1529. r = ALPN_find_match(ssl, &extension, &sel, &sel_len, input + offset, size);
  1530. if (r != 0)
  1531. return r;
  1532. if (sel != NULL) {
  1533. /* set the matching negotiated protocol */
  1534. r = TLSX_SetALPN(&ssl->extensions, sel, sel_len, ssl->heap);
  1535. if (r != WOLFSSL_SUCCESS) {
  1536. WOLFSSL_MSG("TLSX_SetALPN failed");
  1537. return BUFFER_ERROR;
  1538. }
  1539. }
  1540. /* If we had nothing configured, the response is unexpected */
  1541. else if (extension == NULL) {
  1542. r = TLSX_HandleUnsupportedExtension(ssl);
  1543. if (r != 0)
  1544. return r;
  1545. }
  1546. }
  1547. return 0;
  1548. }
  1549. /** Add a protocol name to the list of accepted usable ones */
  1550. int TLSX_UseALPN(TLSX** extensions, const void* data, word16 size, byte options,
  1551. void* heap)
  1552. {
  1553. ALPN *alpn;
  1554. TLSX *extension;
  1555. int ret;
  1556. if (extensions == NULL || data == NULL)
  1557. return BAD_FUNC_ARG;
  1558. alpn = TLSX_ALPN_New((char *)data, size, heap);
  1559. if (alpn == NULL) {
  1560. WOLFSSL_MSG("Memory failure");
  1561. return MEMORY_E;
  1562. }
  1563. /* Set Options of ALPN */
  1564. alpn->options = options;
  1565. extension = TLSX_Find(*extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1566. if (extension == NULL) {
  1567. ret = TLSX_Push(extensions, TLSX_APPLICATION_LAYER_PROTOCOL,
  1568. (void*)alpn, heap);
  1569. if (ret != 0) {
  1570. TLSX_ALPN_Free(alpn, heap);
  1571. return ret;
  1572. }
  1573. }
  1574. else {
  1575. /* push new ALPN object to extension data. */
  1576. alpn->next = (ALPN*)extension->data;
  1577. extension->data = (void*)alpn;
  1578. }
  1579. return WOLFSSL_SUCCESS;
  1580. }
  1581. /** Get the protocol name set by the server */
  1582. int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz)
  1583. {
  1584. TLSX *extension;
  1585. ALPN *alpn;
  1586. if (extensions == NULL || data == NULL || dataSz == NULL)
  1587. return BAD_FUNC_ARG;
  1588. *data = NULL;
  1589. *dataSz = 0;
  1590. extension = TLSX_Find(extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1591. if (extension == NULL) {
  1592. WOLFSSL_MSG("TLS extension not found");
  1593. WOLFSSL_ERROR_VERBOSE(WOLFSSL_ALPN_NOT_FOUND);
  1594. return WOLFSSL_ALPN_NOT_FOUND;
  1595. }
  1596. alpn = (ALPN *)extension->data;
  1597. if (alpn == NULL) {
  1598. WOLFSSL_MSG("ALPN extension not found");
  1599. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1600. return WOLFSSL_FATAL_ERROR;
  1601. }
  1602. if (alpn->negotiated != 1) {
  1603. /* consider as an error */
  1604. if (alpn->options & WOLFSSL_ALPN_FAILED_ON_MISMATCH) {
  1605. WOLFSSL_MSG("No protocol match with peer -> Failed");
  1606. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1607. return WOLFSSL_FATAL_ERROR;
  1608. }
  1609. /* continue without negotiated protocol */
  1610. WOLFSSL_MSG("No protocol match with peer -> Continue");
  1611. WOLFSSL_ERROR_VERBOSE(WOLFSSL_ALPN_NOT_FOUND);
  1612. return WOLFSSL_ALPN_NOT_FOUND;
  1613. }
  1614. if (alpn->next != NULL) {
  1615. WOLFSSL_MSG("Only one protocol name must be accepted");
  1616. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1617. return WOLFSSL_FATAL_ERROR;
  1618. }
  1619. *data = alpn->protocol_name;
  1620. *dataSz = (word16)XSTRLEN((char*)*data);
  1621. return WOLFSSL_SUCCESS;
  1622. }
  1623. #define ALPN_FREE_ALL TLSX_ALPN_FreeAll
  1624. #define ALPN_GET_SIZE TLSX_ALPN_GetSize
  1625. #define ALPN_WRITE TLSX_ALPN_Write
  1626. #define ALPN_PARSE TLSX_ALPN_ParseAndSet
  1627. #else /* HAVE_ALPN */
  1628. #define ALPN_FREE_ALL(list, heap) WC_DO_NOTHING
  1629. #define ALPN_GET_SIZE(list) 0
  1630. #define ALPN_WRITE(a, b) 0
  1631. #define ALPN_PARSE(a, b, c, d) 0
  1632. #endif /* HAVE_ALPN */
  1633. /******************************************************************************/
  1634. /* Server Name Indication */
  1635. /******************************************************************************/
  1636. #ifdef HAVE_SNI
  1637. /** Creates a new SNI object. */
  1638. static SNI* TLSX_SNI_New(byte type, const void* data, word16 size, void* heap)
  1639. {
  1640. SNI* sni = (SNI*)XMALLOC(sizeof(SNI), heap, DYNAMIC_TYPE_TLSX);
  1641. (void)heap;
  1642. if (sni) {
  1643. sni->type = type;
  1644. sni->next = NULL;
  1645. #ifndef NO_WOLFSSL_SERVER
  1646. sni->options = 0;
  1647. sni->status = WOLFSSL_SNI_NO_MATCH;
  1648. #endif
  1649. switch (sni->type) {
  1650. case WOLFSSL_SNI_HOST_NAME:
  1651. sni->data.host_name = (char*)XMALLOC(size + 1, heap,
  1652. DYNAMIC_TYPE_TLSX);
  1653. if (sni->data.host_name) {
  1654. XSTRNCPY(sni->data.host_name, (const char*)data, size);
  1655. sni->data.host_name[size] = '\0';
  1656. } else {
  1657. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1658. sni = NULL;
  1659. }
  1660. break;
  1661. default: /* invalid type */
  1662. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1663. sni = NULL;
  1664. }
  1665. }
  1666. return sni;
  1667. }
  1668. /** Releases a SNI object. */
  1669. static void TLSX_SNI_Free(SNI* sni, void* heap)
  1670. {
  1671. if (sni) {
  1672. switch (sni->type) {
  1673. case WOLFSSL_SNI_HOST_NAME:
  1674. XFREE(sni->data.host_name, heap, DYNAMIC_TYPE_TLSX);
  1675. break;
  1676. }
  1677. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1678. }
  1679. (void)heap;
  1680. }
  1681. /** Releases all SNI objects in the provided list. */
  1682. static void TLSX_SNI_FreeAll(SNI* list, void* heap)
  1683. {
  1684. SNI* sni;
  1685. while ((sni = list)) {
  1686. list = sni->next;
  1687. TLSX_SNI_Free(sni, heap);
  1688. }
  1689. }
  1690. /** Tells the buffered size of the SNI objects in a list. */
  1691. static word16 TLSX_SNI_GetSize(SNI* list)
  1692. {
  1693. SNI* sni;
  1694. word16 length = OPAQUE16_LEN; /* list length */
  1695. while ((sni = list)) {
  1696. list = sni->next;
  1697. length += ENUM_LEN + OPAQUE16_LEN; /* sni type + sni length */
  1698. switch (sni->type) {
  1699. case WOLFSSL_SNI_HOST_NAME:
  1700. length += (word16)XSTRLEN((char*)sni->data.host_name);
  1701. break;
  1702. }
  1703. }
  1704. return length;
  1705. }
  1706. /** Writes the SNI objects of a list in a buffer. */
  1707. static word16 TLSX_SNI_Write(SNI* list, byte* output)
  1708. {
  1709. SNI* sni;
  1710. word16 length = 0;
  1711. word16 offset = OPAQUE16_LEN; /* list length offset */
  1712. while ((sni = list)) {
  1713. list = sni->next;
  1714. output[offset++] = sni->type; /* sni type */
  1715. switch (sni->type) {
  1716. case WOLFSSL_SNI_HOST_NAME:
  1717. length = (word16)XSTRLEN((char*)sni->data.host_name);
  1718. c16toa(length, output + offset); /* sni length */
  1719. offset += OPAQUE16_LEN;
  1720. XMEMCPY(output + offset, sni->data.host_name, length);
  1721. offset += length;
  1722. break;
  1723. }
  1724. }
  1725. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  1726. return offset;
  1727. }
  1728. /** Finds a SNI object in the provided list. */
  1729. static SNI* TLSX_SNI_Find(SNI *list, byte type)
  1730. {
  1731. SNI* sni = list;
  1732. while (sni && sni->type != type)
  1733. sni = sni->next;
  1734. return sni;
  1735. }
  1736. #if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
  1737. /** Sets the status of a SNI object. */
  1738. static void TLSX_SNI_SetStatus(TLSX* extensions, byte type, byte status)
  1739. {
  1740. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1741. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1742. if (sni)
  1743. sni->status = status;
  1744. }
  1745. #endif
  1746. /** Gets the status of a SNI object. */
  1747. byte TLSX_SNI_Status(TLSX* extensions, byte type)
  1748. {
  1749. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1750. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1751. if (sni)
  1752. return sni->status;
  1753. return 0;
  1754. }
  1755. /** Parses a buffer of SNI extensions. */
  1756. static int TLSX_SNI_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  1757. byte isRequest)
  1758. {
  1759. #ifndef NO_WOLFSSL_SERVER
  1760. word16 size = 0;
  1761. word16 offset = 0;
  1762. int cacheOnly = 0;
  1763. SNI *sni = NULL;
  1764. byte type;
  1765. byte matched;
  1766. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1767. WOLFSSL_ECH* ech = NULL;
  1768. WOLFSSL_EchConfig* workingConfig;
  1769. TLSX* echX;
  1770. #endif
  1771. #endif /* !NO_WOLFSSL_SERVER */
  1772. TLSX *extension = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  1773. if (!extension)
  1774. extension = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  1775. if (!isRequest) {
  1776. #ifndef NO_WOLFSSL_CLIENT
  1777. if (!extension || !extension->data)
  1778. return TLSX_HandleUnsupportedExtension(ssl);
  1779. if (length > 0)
  1780. return BUFFER_ERROR; /* SNI response MUST be empty. */
  1781. /* This call enables wolfSSL_SNI_GetRequest() to be called in the
  1782. * client side to fetch the used SNI. It will only work if the SNI
  1783. * was set at the SSL object level. Right now we only support one
  1784. * name type, WOLFSSL_SNI_HOST_NAME, but in the future, the
  1785. * inclusion of other name types will turn this method inaccurate,
  1786. * as the extension response doesn't contains information of which
  1787. * name was accepted.
  1788. */
  1789. TLSX_SNI_SetStatus(ssl->extensions, WOLFSSL_SNI_HOST_NAME,
  1790. WOLFSSL_SNI_REAL_MATCH);
  1791. return 0;
  1792. #endif
  1793. }
  1794. #ifndef NO_WOLFSSL_SERVER
  1795. if (!extension || !extension->data) {
  1796. /* This will keep SNI even though TLSX_UseSNI has not been called.
  1797. * Enable it so that the received sni is available to functions
  1798. * that use a custom callback when SNI is received.
  1799. */
  1800. #ifdef WOLFSSL_ALWAYS_KEEP_SNI
  1801. cacheOnly = 1;
  1802. #endif
  1803. if (ssl->ctx->sniRecvCb) {
  1804. cacheOnly = 1;
  1805. }
  1806. if (cacheOnly) {
  1807. WOLFSSL_MSG("Forcing SSL object to store SNI parameter");
  1808. }
  1809. else {
  1810. /* Skipping, SNI not enabled at server side. */
  1811. return 0;
  1812. }
  1813. }
  1814. if (OPAQUE16_LEN > length)
  1815. return BUFFER_ERROR;
  1816. ato16(input, &size);
  1817. offset += OPAQUE16_LEN;
  1818. /* validating sni list length */
  1819. if (length != OPAQUE16_LEN + size || size == 0)
  1820. return BUFFER_ERROR;
  1821. /* SNI was badly specified and only one type is now recognized and allowed.
  1822. * Only one SNI value per type (RFC6066), so, no loop. */
  1823. type = input[offset++];
  1824. if (type != WOLFSSL_SNI_HOST_NAME)
  1825. return BUFFER_ERROR;
  1826. if (offset + OPAQUE16_LEN > length)
  1827. return BUFFER_ERROR;
  1828. ato16(input + offset, &size);
  1829. offset += OPAQUE16_LEN;
  1830. if (offset + size != length || size == 0)
  1831. return BUFFER_ERROR;
  1832. if (!cacheOnly && !(sni = TLSX_SNI_Find((SNI*)extension->data, type)))
  1833. return 0; /* not using this type of SNI. */
  1834. #ifdef WOLFSSL_TLS13
  1835. /* Don't process the second ClientHello SNI extension if there
  1836. * was problems with the first.
  1837. */
  1838. if (!cacheOnly && sni->status != 0)
  1839. return 0;
  1840. #endif
  1841. matched = cacheOnly || (XSTRLEN(sni->data.host_name) == size &&
  1842. XSTRNCMP(sni->data.host_name, (const char*)input + offset, size) == 0);
  1843. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1844. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  1845. if (echX != NULL)
  1846. ech = (WOLFSSL_ECH*)(echX->data);
  1847. if (!matched && ech != NULL) {
  1848. workingConfig = ech->echConfig;
  1849. while (workingConfig != NULL) {
  1850. matched = XSTRLEN(workingConfig->publicName) == size &&
  1851. XSTRNCMP(workingConfig->publicName,
  1852. (const char*)input + offset, size) == 0;
  1853. if (matched)
  1854. break;
  1855. workingConfig = workingConfig->next;
  1856. }
  1857. }
  1858. #endif
  1859. if (matched || sni->options & WOLFSSL_SNI_ANSWER_ON_MISMATCH) {
  1860. int matchStat;
  1861. int r = TLSX_UseSNI(&ssl->extensions, type, input + offset, size,
  1862. ssl->heap);
  1863. if (r != WOLFSSL_SUCCESS)
  1864. return r; /* throws error. */
  1865. if (cacheOnly) {
  1866. WOLFSSL_MSG("Forcing storage of SNI, Fake match");
  1867. matchStat = WOLFSSL_SNI_FORCE_KEEP;
  1868. }
  1869. else if (matched) {
  1870. WOLFSSL_MSG("SNI did match!");
  1871. matchStat = WOLFSSL_SNI_REAL_MATCH;
  1872. }
  1873. else {
  1874. WOLFSSL_MSG("fake SNI match from ANSWER_ON_MISMATCH");
  1875. matchStat = WOLFSSL_SNI_FAKE_MATCH;
  1876. }
  1877. TLSX_SNI_SetStatus(ssl->extensions, type, (byte)matchStat);
  1878. if (!cacheOnly)
  1879. TLSX_SetResponse(ssl, TLSX_SERVER_NAME);
  1880. }
  1881. else if (!(sni->options & WOLFSSL_SNI_CONTINUE_ON_MISMATCH)) {
  1882. SendAlert(ssl, alert_fatal, unrecognized_name);
  1883. WOLFSSL_ERROR_VERBOSE(UNKNOWN_SNI_HOST_NAME_E);
  1884. return UNKNOWN_SNI_HOST_NAME_E;
  1885. }
  1886. #else
  1887. (void)input;
  1888. #endif /* !NO_WOLFSSL_SERVER */
  1889. #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER)
  1890. (void)length;
  1891. #endif
  1892. return 0;
  1893. }
  1894. static int TLSX_SNI_VerifyParse(WOLFSSL* ssl, byte isRequest)
  1895. {
  1896. (void)ssl;
  1897. if (isRequest) {
  1898. #ifndef NO_WOLFSSL_SERVER
  1899. TLSX* ctx_ext = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  1900. TLSX* ssl_ext = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  1901. SNI* ctx_sni = ctx_ext ? (SNI*)ctx_ext->data : NULL;
  1902. SNI* ssl_sni = ssl_ext ? (SNI*)ssl_ext->data : NULL;
  1903. SNI* sni = NULL;
  1904. for (; ctx_sni; ctx_sni = ctx_sni->next) {
  1905. if (ctx_sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) {
  1906. sni = TLSX_SNI_Find(ssl_sni, ctx_sni->type);
  1907. if (sni) {
  1908. if (sni->status != WOLFSSL_SNI_NO_MATCH)
  1909. continue;
  1910. /* if ssl level overrides ctx level, it is ok. */
  1911. if ((sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) == 0)
  1912. continue;
  1913. }
  1914. SendAlert(ssl, alert_fatal, handshake_failure);
  1915. WOLFSSL_ERROR_VERBOSE(SNI_ABSENT_ERROR);
  1916. return SNI_ABSENT_ERROR;
  1917. }
  1918. }
  1919. for (; ssl_sni; ssl_sni = ssl_sni->next) {
  1920. if (ssl_sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) {
  1921. if (ssl_sni->status != WOLFSSL_SNI_NO_MATCH)
  1922. continue;
  1923. SendAlert(ssl, alert_fatal, handshake_failure);
  1924. WOLFSSL_ERROR_VERBOSE(SNI_ABSENT_ERROR);
  1925. return SNI_ABSENT_ERROR;
  1926. }
  1927. }
  1928. #endif /* NO_WOLFSSL_SERVER */
  1929. }
  1930. return 0;
  1931. }
  1932. int TLSX_UseSNI(TLSX** extensions, byte type, const void* data, word16 size,
  1933. void* heap)
  1934. {
  1935. TLSX* extension;
  1936. SNI* sni = NULL;
  1937. if (extensions == NULL || data == NULL)
  1938. return BAD_FUNC_ARG;
  1939. if ((sni = TLSX_SNI_New(type, data, size, heap)) == NULL)
  1940. return MEMORY_E;
  1941. extension = TLSX_Find(*extensions, TLSX_SERVER_NAME);
  1942. if (!extension) {
  1943. int ret = TLSX_Push(extensions, TLSX_SERVER_NAME, (void*)sni, heap);
  1944. if (ret != 0) {
  1945. TLSX_SNI_Free(sni, heap);
  1946. return ret;
  1947. }
  1948. }
  1949. else {
  1950. /* push new SNI object to extension data. */
  1951. sni->next = (SNI*)extension->data;
  1952. extension->data = (void*)sni;
  1953. /* remove duplicate SNI, there should be only one of each type. */
  1954. do {
  1955. if (sni->next && sni->next->type == type) {
  1956. SNI* next = sni->next;
  1957. sni->next = next->next;
  1958. TLSX_SNI_Free(next, heap);
  1959. /* there is no way to occur more than
  1960. * two SNIs of the same type.
  1961. */
  1962. break;
  1963. }
  1964. } while ((sni = sni->next));
  1965. }
  1966. return WOLFSSL_SUCCESS;
  1967. }
  1968. #ifndef NO_WOLFSSL_SERVER
  1969. /** Tells the SNI requested by the client. */
  1970. word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type, void** data)
  1971. {
  1972. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1973. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1974. if (sni && sni->status != WOLFSSL_SNI_NO_MATCH) {
  1975. switch (sni->type) {
  1976. case WOLFSSL_SNI_HOST_NAME:
  1977. if (data) {
  1978. *data = sni->data.host_name;
  1979. return (word16)XSTRLEN((char*)*data);
  1980. }
  1981. }
  1982. }
  1983. return 0;
  1984. }
  1985. /** Sets the options for a SNI object. */
  1986. void TLSX_SNI_SetOptions(TLSX* extensions, byte type, byte options)
  1987. {
  1988. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1989. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1990. if (sni)
  1991. sni->options = options;
  1992. }
  1993. /** Retrieves a SNI request from a client hello buffer. */
  1994. int TLSX_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz,
  1995. byte type, byte* sni, word32* inOutSz)
  1996. {
  1997. word32 offset = 0;
  1998. word32 len32 = 0;
  1999. word16 len16 = 0;
  2000. if (helloSz < RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + CLIENT_HELLO_FIRST)
  2001. return INCOMPLETE_DATA;
  2002. /* TLS record header */
  2003. if ((enum ContentType) clientHello[offset++] != handshake) {
  2004. /* checking for SSLv2.0 client hello according to: */
  2005. /* http://tools.ietf.org/html/rfc4346#appendix-E.1 */
  2006. if ((enum HandShakeType) clientHello[++offset] == client_hello) {
  2007. offset += ENUM_LEN + VERSION_SZ; /* skip version */
  2008. ato16(clientHello + offset, &len16);
  2009. offset += OPAQUE16_LEN;
  2010. if (len16 % 3) /* cipher_spec_length must be multiple of 3 */
  2011. return BUFFER_ERROR;
  2012. ato16(clientHello + offset, &len16);
  2013. /* Returning SNI_UNSUPPORTED do not increment offset here */
  2014. if (len16 != 0) /* session_id_length must be 0 */
  2015. return BUFFER_ERROR;
  2016. WOLFSSL_ERROR_VERBOSE(SNI_UNSUPPORTED);
  2017. return SNI_UNSUPPORTED;
  2018. }
  2019. return BUFFER_ERROR;
  2020. }
  2021. if (clientHello[offset++] != SSLv3_MAJOR)
  2022. return BUFFER_ERROR;
  2023. if (clientHello[offset++] < TLSv1_MINOR) {
  2024. WOLFSSL_ERROR_VERBOSE(SNI_UNSUPPORTED);
  2025. return SNI_UNSUPPORTED;
  2026. }
  2027. ato16(clientHello + offset, &len16);
  2028. offset += OPAQUE16_LEN;
  2029. if (offset + len16 > helloSz)
  2030. return INCOMPLETE_DATA;
  2031. /* Handshake header */
  2032. if ((enum HandShakeType) clientHello[offset] != client_hello)
  2033. return BUFFER_ERROR;
  2034. c24to32(clientHello + offset + 1, &len32);
  2035. offset += HANDSHAKE_HEADER_SZ;
  2036. if (offset + len32 > helloSz)
  2037. return BUFFER_ERROR;
  2038. /* client hello */
  2039. offset += VERSION_SZ + RAN_LEN; /* version, random */
  2040. if (helloSz < offset + clientHello[offset])
  2041. return BUFFER_ERROR;
  2042. offset += ENUM_LEN + clientHello[offset]; /* skip session id */
  2043. /* cypher suites */
  2044. if (helloSz < offset + OPAQUE16_LEN)
  2045. return BUFFER_ERROR;
  2046. ato16(clientHello + offset, &len16);
  2047. offset += OPAQUE16_LEN;
  2048. if (helloSz < offset + len16)
  2049. return BUFFER_ERROR;
  2050. offset += len16; /* skip cypher suites */
  2051. /* compression methods */
  2052. if (helloSz < offset + 1)
  2053. return BUFFER_ERROR;
  2054. if (helloSz < offset + clientHello[offset])
  2055. return BUFFER_ERROR;
  2056. offset += ENUM_LEN + clientHello[offset]; /* skip compression methods */
  2057. /* extensions */
  2058. if (helloSz < offset + OPAQUE16_LEN)
  2059. return 0; /* no extensions in client hello. */
  2060. ato16(clientHello + offset, &len16);
  2061. offset += OPAQUE16_LEN;
  2062. if (helloSz < offset + len16)
  2063. return BUFFER_ERROR;
  2064. while (len16 >= OPAQUE16_LEN + OPAQUE16_LEN) {
  2065. word16 extType;
  2066. word16 extLen;
  2067. ato16(clientHello + offset, &extType);
  2068. offset += OPAQUE16_LEN;
  2069. ato16(clientHello + offset, &extLen);
  2070. offset += OPAQUE16_LEN;
  2071. if (helloSz < offset + extLen)
  2072. return BUFFER_ERROR;
  2073. if (extType != TLSX_SERVER_NAME) {
  2074. offset += extLen; /* skip extension */
  2075. } else {
  2076. word16 listLen;
  2077. ato16(clientHello + offset, &listLen);
  2078. offset += OPAQUE16_LEN;
  2079. if (helloSz < offset + listLen)
  2080. return BUFFER_ERROR;
  2081. while (listLen > ENUM_LEN + OPAQUE16_LEN) {
  2082. byte sniType = clientHello[offset++];
  2083. word16 sniLen;
  2084. ato16(clientHello + offset, &sniLen);
  2085. offset += OPAQUE16_LEN;
  2086. if (helloSz < offset + sniLen)
  2087. return BUFFER_ERROR;
  2088. if (sniType != type) {
  2089. offset += sniLen;
  2090. listLen -= min(ENUM_LEN + OPAQUE16_LEN + sniLen, listLen);
  2091. continue;
  2092. }
  2093. *inOutSz = min(sniLen, *inOutSz);
  2094. XMEMCPY(sni, clientHello + offset, *inOutSz);
  2095. return WOLFSSL_SUCCESS;
  2096. }
  2097. }
  2098. len16 -= min(2 * OPAQUE16_LEN + extLen, len16);
  2099. }
  2100. return len16 ? BUFFER_ERROR : 0;
  2101. }
  2102. #endif
  2103. #define SNI_FREE_ALL TLSX_SNI_FreeAll
  2104. #define SNI_GET_SIZE TLSX_SNI_GetSize
  2105. #define SNI_WRITE TLSX_SNI_Write
  2106. #define SNI_PARSE TLSX_SNI_Parse
  2107. #define SNI_VERIFY_PARSE TLSX_SNI_VerifyParse
  2108. #else
  2109. #define SNI_FREE_ALL(list, heap) WC_DO_NOTHING
  2110. #define SNI_GET_SIZE(list) 0
  2111. #define SNI_WRITE(a, b) 0
  2112. #define SNI_PARSE(a, b, c, d) 0
  2113. #define SNI_VERIFY_PARSE(a, b) 0
  2114. #endif /* HAVE_SNI */
  2115. /******************************************************************************/
  2116. /* Trusted CA Key Indication */
  2117. /******************************************************************************/
  2118. #ifdef HAVE_TRUSTED_CA
  2119. /** Creates a new TCA object. */
  2120. static TCA* TLSX_TCA_New(byte type, const byte* id, word16 idSz, void* heap)
  2121. {
  2122. TCA* tca = (TCA*)XMALLOC(sizeof(TCA), heap, DYNAMIC_TYPE_TLSX);
  2123. if (tca) {
  2124. XMEMSET(tca, 0, sizeof(TCA));
  2125. tca->type = type;
  2126. switch (type) {
  2127. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2128. break;
  2129. #ifndef NO_SHA
  2130. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2131. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2132. if (idSz == WC_SHA_DIGEST_SIZE &&
  2133. (tca->id =
  2134. (byte*)XMALLOC(idSz, heap, DYNAMIC_TYPE_TLSX))) {
  2135. XMEMCPY(tca->id, id, idSz);
  2136. tca->idSz = idSz;
  2137. }
  2138. else {
  2139. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2140. tca = NULL;
  2141. }
  2142. break;
  2143. #endif
  2144. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2145. if (idSz > 0 &&
  2146. (tca->id =
  2147. (byte*)XMALLOC(idSz, heap, DYNAMIC_TYPE_TLSX))) {
  2148. XMEMCPY(tca->id, id, idSz);
  2149. tca->idSz = idSz;
  2150. }
  2151. else {
  2152. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2153. tca = NULL;
  2154. }
  2155. break;
  2156. default: /* invalid type */
  2157. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2158. tca = NULL;
  2159. }
  2160. }
  2161. (void)heap;
  2162. return tca;
  2163. }
  2164. /** Releases a TCA object. */
  2165. static void TLSX_TCA_Free(TCA* tca, void* heap)
  2166. {
  2167. (void)heap;
  2168. if (tca) {
  2169. if (tca->id)
  2170. XFREE(tca->id, heap, DYNAMIC_TYPE_TLSX);
  2171. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2172. }
  2173. }
  2174. /** Releases all TCA objects in the provided list. */
  2175. static void TLSX_TCA_FreeAll(TCA* list, void* heap)
  2176. {
  2177. TCA* tca;
  2178. while ((tca = list)) {
  2179. list = tca->next;
  2180. TLSX_TCA_Free(tca, heap);
  2181. }
  2182. }
  2183. /** Tells the buffered size of the TCA objects in a list. */
  2184. static word16 TLSX_TCA_GetSize(TCA* list)
  2185. {
  2186. TCA* tca;
  2187. word16 length = OPAQUE16_LEN; /* list length */
  2188. while ((tca = list)) {
  2189. list = tca->next;
  2190. length += ENUM_LEN; /* tca type */
  2191. switch (tca->type) {
  2192. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2193. break;
  2194. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2195. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2196. length += tca->idSz;
  2197. break;
  2198. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2199. length += OPAQUE16_LEN + tca->idSz;
  2200. break;
  2201. }
  2202. }
  2203. return length;
  2204. }
  2205. /** Writes the TCA objects of a list in a buffer. */
  2206. static word16 TLSX_TCA_Write(TCA* list, byte* output)
  2207. {
  2208. TCA* tca;
  2209. word16 offset = OPAQUE16_LEN; /* list length offset */
  2210. while ((tca = list)) {
  2211. list = tca->next;
  2212. output[offset++] = tca->type; /* tca type */
  2213. switch (tca->type) {
  2214. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2215. break;
  2216. #ifndef NO_SHA
  2217. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2218. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2219. if (tca->id != NULL) {
  2220. XMEMCPY(output + offset, tca->id, tca->idSz);
  2221. offset += tca->idSz;
  2222. }
  2223. else {
  2224. /* ID missing. Set to an empty string. */
  2225. c16toa(0, output + offset);
  2226. offset += OPAQUE16_LEN;
  2227. }
  2228. break;
  2229. #endif
  2230. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2231. if (tca->id != NULL) {
  2232. c16toa(tca->idSz, output + offset); /* tca length */
  2233. offset += OPAQUE16_LEN;
  2234. XMEMCPY(output + offset, tca->id, tca->idSz);
  2235. offset += tca->idSz;
  2236. }
  2237. else {
  2238. /* ID missing. Set to an empty string. */
  2239. c16toa(0, output + offset);
  2240. offset += OPAQUE16_LEN;
  2241. }
  2242. break;
  2243. default:
  2244. /* ID unknown. Set to an empty string. */
  2245. c16toa(0, output + offset);
  2246. offset += OPAQUE16_LEN;
  2247. }
  2248. }
  2249. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  2250. return offset;
  2251. }
  2252. #ifndef NO_WOLFSSL_SERVER
  2253. static TCA* TLSX_TCA_Find(TCA *list, byte type, const byte* id, word16 idSz)
  2254. {
  2255. TCA* tca = list;
  2256. while (tca && tca->type != type && type != WOLFSSL_TRUSTED_CA_PRE_AGREED &&
  2257. idSz != tca->idSz && !XMEMCMP(id, tca->id, idSz))
  2258. tca = tca->next;
  2259. return tca;
  2260. }
  2261. #endif /* NO_WOLFSSL_SERVER */
  2262. /** Parses a buffer of TCA extensions. */
  2263. static int TLSX_TCA_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2264. byte isRequest)
  2265. {
  2266. #ifndef NO_WOLFSSL_SERVER
  2267. word16 size = 0;
  2268. word16 offset = 0;
  2269. #endif
  2270. TLSX *extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS);
  2271. if (!extension)
  2272. extension = TLSX_Find(ssl->ctx->extensions, TLSX_TRUSTED_CA_KEYS);
  2273. if (!isRequest) {
  2274. #ifndef NO_WOLFSSL_CLIENT
  2275. if (!extension || !extension->data)
  2276. return TLSX_HandleUnsupportedExtension(ssl);
  2277. if (length > 0)
  2278. return BUFFER_ERROR; /* TCA response MUST be empty. */
  2279. /* Set the flag that we're good for keys */
  2280. TLSX_SetResponse(ssl, TLSX_TRUSTED_CA_KEYS);
  2281. return 0;
  2282. #endif
  2283. }
  2284. #ifndef NO_WOLFSSL_SERVER
  2285. if (!extension || !extension->data) {
  2286. /* Skipping, TCA not enabled at server side. */
  2287. return 0;
  2288. }
  2289. if (OPAQUE16_LEN > length)
  2290. return BUFFER_ERROR;
  2291. ato16(input, &size);
  2292. offset += OPAQUE16_LEN;
  2293. /* validating tca list length */
  2294. if (length != OPAQUE16_LEN + size)
  2295. return BUFFER_ERROR;
  2296. for (size = 0; offset < length; offset += size) {
  2297. TCA *tca = NULL;
  2298. byte type;
  2299. const byte* id = NULL;
  2300. word16 idSz = 0;
  2301. if (offset + ENUM_LEN > length)
  2302. return BUFFER_ERROR;
  2303. type = input[offset++];
  2304. switch (type) {
  2305. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2306. break;
  2307. #ifndef NO_SHA
  2308. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2309. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2310. if (offset + WC_SHA_DIGEST_SIZE > length)
  2311. return BUFFER_ERROR;
  2312. idSz = WC_SHA_DIGEST_SIZE;
  2313. id = input + offset;
  2314. offset += idSz;
  2315. break;
  2316. #endif
  2317. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2318. if (offset + OPAQUE16_LEN > length)
  2319. return BUFFER_ERROR;
  2320. ato16(input + offset, &idSz);
  2321. offset += OPAQUE16_LEN;
  2322. if ((offset > length) || (idSz > length - offset))
  2323. return BUFFER_ERROR;
  2324. id = input + offset;
  2325. offset += idSz;
  2326. break;
  2327. default:
  2328. WOLFSSL_ERROR_VERBOSE(TCA_INVALID_ID_TYPE);
  2329. return TCA_INVALID_ID_TYPE;
  2330. }
  2331. /* Find the type/ID in the TCA list. */
  2332. tca = TLSX_TCA_Find((TCA*)extension->data, type, id, idSz);
  2333. if (tca != NULL) {
  2334. /* Found it. Set the response flag and break out of the loop. */
  2335. TLSX_SetResponse(ssl, TLSX_TRUSTED_CA_KEYS);
  2336. break;
  2337. }
  2338. }
  2339. #else
  2340. (void)input;
  2341. #endif
  2342. return 0;
  2343. }
  2344. /* Checks to see if the server sent a response for the TCA. */
  2345. static int TLSX_TCA_VerifyParse(WOLFSSL* ssl, byte isRequest)
  2346. {
  2347. (void)ssl;
  2348. if (!isRequest) {
  2349. #ifndef NO_WOLFSSL_CLIENT
  2350. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS);
  2351. if (extension && !extension->resp) {
  2352. SendAlert(ssl, alert_fatal, handshake_failure);
  2353. WOLFSSL_ERROR_VERBOSE(TCA_ABSENT_ERROR);
  2354. return TCA_ABSENT_ERROR;
  2355. }
  2356. #endif /* NO_WOLFSSL_CLIENT */
  2357. }
  2358. return 0;
  2359. }
  2360. int TLSX_UseTrustedCA(TLSX** extensions, byte type,
  2361. const byte* id, word16 idSz, void* heap)
  2362. {
  2363. TLSX* extension;
  2364. TCA* tca = NULL;
  2365. if (extensions == NULL)
  2366. return BAD_FUNC_ARG;
  2367. if ((tca = TLSX_TCA_New(type, id, idSz, heap)) == NULL)
  2368. return MEMORY_E;
  2369. extension = TLSX_Find(*extensions, TLSX_TRUSTED_CA_KEYS);
  2370. if (!extension) {
  2371. int ret = TLSX_Push(extensions, TLSX_TRUSTED_CA_KEYS, (void*)tca, heap);
  2372. if (ret != 0) {
  2373. TLSX_TCA_Free(tca, heap);
  2374. return ret;
  2375. }
  2376. }
  2377. else {
  2378. /* push new TCA object to extension data. */
  2379. tca->next = (TCA*)extension->data;
  2380. extension->data = (void*)tca;
  2381. }
  2382. return WOLFSSL_SUCCESS;
  2383. }
  2384. #define TCA_FREE_ALL TLSX_TCA_FreeAll
  2385. #define TCA_GET_SIZE TLSX_TCA_GetSize
  2386. #define TCA_WRITE TLSX_TCA_Write
  2387. #define TCA_PARSE TLSX_TCA_Parse
  2388. #define TCA_VERIFY_PARSE TLSX_TCA_VerifyParse
  2389. #else /* HAVE_TRUSTED_CA */
  2390. #define TCA_FREE_ALL(list, heap) WC_DO_NOTHING
  2391. #define TCA_GET_SIZE(list) 0
  2392. #define TCA_WRITE(a, b) 0
  2393. #define TCA_PARSE(a, b, c, d) 0
  2394. #define TCA_VERIFY_PARSE(a, b) 0
  2395. #endif /* HAVE_TRUSTED_CA */
  2396. /******************************************************************************/
  2397. /* Max Fragment Length Negotiation */
  2398. /******************************************************************************/
  2399. #ifdef HAVE_MAX_FRAGMENT
  2400. static word16 TLSX_MFL_Write(byte* data, byte* output)
  2401. {
  2402. output[0] = data[0];
  2403. return ENUM_LEN;
  2404. }
  2405. static int TLSX_MFL_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2406. byte isRequest)
  2407. {
  2408. if (length != ENUM_LEN)
  2409. return BUFFER_ERROR;
  2410. #ifdef WOLFSSL_OLD_UNSUPPORTED_EXTENSION
  2411. (void) isRequest;
  2412. #else
  2413. if (!isRequest)
  2414. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_MAX_FRAGMENT_LENGTH))
  2415. return TLSX_HandleUnsupportedExtension(ssl);
  2416. #endif
  2417. switch (*input) {
  2418. case WOLFSSL_MFL_2_8 : ssl->max_fragment = 256; break;
  2419. case WOLFSSL_MFL_2_9 : ssl->max_fragment = 512; break;
  2420. case WOLFSSL_MFL_2_10: ssl->max_fragment = 1024; break;
  2421. case WOLFSSL_MFL_2_11: ssl->max_fragment = 2048; break;
  2422. case WOLFSSL_MFL_2_12: ssl->max_fragment = 4096; break;
  2423. case WOLFSSL_MFL_2_13: ssl->max_fragment = 8192; break;
  2424. default:
  2425. SendAlert(ssl, alert_fatal, illegal_parameter);
  2426. WOLFSSL_ERROR_VERBOSE(UNKNOWN_MAX_FRAG_LEN_E);
  2427. return UNKNOWN_MAX_FRAG_LEN_E;
  2428. }
  2429. #ifndef NO_WOLFSSL_SERVER
  2430. if (isRequest) {
  2431. int ret = TLSX_UseMaxFragment(&ssl->extensions, *input, ssl->heap);
  2432. if (ret != WOLFSSL_SUCCESS)
  2433. return ret; /* throw error */
  2434. TLSX_SetResponse(ssl, TLSX_MAX_FRAGMENT_LENGTH);
  2435. }
  2436. #endif
  2437. return 0;
  2438. }
  2439. int TLSX_UseMaxFragment(TLSX** extensions, byte mfl, void* heap)
  2440. {
  2441. byte* data = NULL;
  2442. int ret = 0;
  2443. if (extensions == NULL || mfl < WOLFSSL_MFL_MIN || mfl > WOLFSSL_MFL_MAX)
  2444. return BAD_FUNC_ARG;
  2445. data = (byte*)XMALLOC(ENUM_LEN, heap, DYNAMIC_TYPE_TLSX);
  2446. if (data == NULL)
  2447. return MEMORY_E;
  2448. data[0] = mfl;
  2449. ret = TLSX_Push(extensions, TLSX_MAX_FRAGMENT_LENGTH, data, heap);
  2450. if (ret != 0) {
  2451. XFREE(data, heap, DYNAMIC_TYPE_TLSX);
  2452. return ret;
  2453. }
  2454. return WOLFSSL_SUCCESS;
  2455. }
  2456. #define MFL_FREE_ALL(data, heap) XFREE(data, (heap), DYNAMIC_TYPE_TLSX)
  2457. #define MFL_GET_SIZE(data) ENUM_LEN
  2458. #define MFL_WRITE TLSX_MFL_Write
  2459. #define MFL_PARSE TLSX_MFL_Parse
  2460. #else
  2461. #define MFL_FREE_ALL(a, b) WC_DO_NOTHING
  2462. #define MFL_GET_SIZE(a) 0
  2463. #define MFL_WRITE(a, b) 0
  2464. #define MFL_PARSE(a, b, c, d) 0
  2465. #endif /* HAVE_MAX_FRAGMENT */
  2466. /******************************************************************************/
  2467. /* Truncated HMAC */
  2468. /******************************************************************************/
  2469. #ifdef HAVE_TRUNCATED_HMAC
  2470. static int TLSX_THM_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2471. byte isRequest)
  2472. {
  2473. if (length != 0 || input == NULL)
  2474. return BUFFER_ERROR;
  2475. if (!isRequest) {
  2476. #ifndef WOLFSSL_OLD_UNSUPPORTED_EXTENSION
  2477. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_TRUNCATED_HMAC))
  2478. return TLSX_HandleUnsupportedExtension(ssl);
  2479. #endif
  2480. }
  2481. else {
  2482. #ifndef NO_WOLFSSL_SERVER
  2483. int ret = TLSX_UseTruncatedHMAC(&ssl->extensions, ssl->heap);
  2484. if (ret != WOLFSSL_SUCCESS)
  2485. return ret; /* throw error */
  2486. TLSX_SetResponse(ssl, TLSX_TRUNCATED_HMAC);
  2487. #endif
  2488. }
  2489. ssl->truncated_hmac = 1;
  2490. return 0;
  2491. }
  2492. int TLSX_UseTruncatedHMAC(TLSX** extensions, void* heap)
  2493. {
  2494. int ret = 0;
  2495. if (extensions == NULL)
  2496. return BAD_FUNC_ARG;
  2497. ret = TLSX_Push(extensions, TLSX_TRUNCATED_HMAC, NULL, heap);
  2498. if (ret != 0)
  2499. return ret;
  2500. return WOLFSSL_SUCCESS;
  2501. }
  2502. #define THM_PARSE TLSX_THM_Parse
  2503. #else
  2504. #define THM_PARSE(a, b, c, d) 0
  2505. #endif /* HAVE_TRUNCATED_HMAC */
  2506. /******************************************************************************/
  2507. /* Certificate Status Request */
  2508. /******************************************************************************/
  2509. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  2510. static void TLSX_CSR_Free(CertificateStatusRequest* csr, void* heap)
  2511. {
  2512. switch (csr->status_type) {
  2513. case WOLFSSL_CSR_OCSP:
  2514. FreeOcspRequest(&csr->request.ocsp);
  2515. break;
  2516. }
  2517. #ifdef WOLFSSL_TLS13
  2518. if (csr->response.buffer != NULL) {
  2519. XFREE(csr->response.buffer, csr->ssl->heap,
  2520. DYNAMIC_TYPE_TMP_BUFFER);
  2521. }
  2522. #endif
  2523. XFREE(csr, heap, DYNAMIC_TYPE_TLSX);
  2524. (void)heap;
  2525. }
  2526. static word16 TLSX_CSR_GetSize(CertificateStatusRequest* csr, byte isRequest)
  2527. {
  2528. word16 size = 0;
  2529. /* shut up compiler warnings */
  2530. (void) csr; (void) isRequest;
  2531. #ifndef NO_WOLFSSL_CLIENT
  2532. if (isRequest) {
  2533. switch (csr->status_type) {
  2534. case WOLFSSL_CSR_OCSP:
  2535. size += ENUM_LEN + 2 * OPAQUE16_LEN;
  2536. if (csr->request.ocsp.nonceSz)
  2537. size += OCSP_NONCE_EXT_SZ;
  2538. break;
  2539. }
  2540. }
  2541. #endif
  2542. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  2543. if (!isRequest && csr->ssl->options.tls1_3)
  2544. return OPAQUE8_LEN + OPAQUE24_LEN + csr->response.length;
  2545. #endif
  2546. return size;
  2547. }
  2548. static word16 TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output,
  2549. byte isRequest)
  2550. {
  2551. /* shut up compiler warnings */
  2552. (void) csr; (void) output; (void) isRequest;
  2553. #ifndef NO_WOLFSSL_CLIENT
  2554. if (isRequest) {
  2555. word16 offset = 0;
  2556. word16 length = 0;
  2557. /* type */
  2558. output[offset++] = csr->status_type;
  2559. switch (csr->status_type) {
  2560. case WOLFSSL_CSR_OCSP:
  2561. /* responder id list */
  2562. c16toa(0, output + offset);
  2563. offset += OPAQUE16_LEN;
  2564. /* request extensions */
  2565. if (csr->request.ocsp.nonceSz)
  2566. length = (word16)EncodeOcspRequestExtensions(
  2567. &csr->request.ocsp,
  2568. output + offset + OPAQUE16_LEN,
  2569. OCSP_NONCE_EXT_SZ);
  2570. c16toa(length, output + offset);
  2571. offset += OPAQUE16_LEN + length;
  2572. break;
  2573. }
  2574. return offset;
  2575. }
  2576. #endif
  2577. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  2578. if (!isRequest && csr->ssl->options.tls1_3) {
  2579. word16 offset = 0;
  2580. output[offset++] = csr->status_type;
  2581. c32to24(csr->response.length, output + offset);
  2582. offset += OPAQUE24_LEN;
  2583. XMEMCPY(output + offset, csr->response.buffer, csr->response.length);
  2584. offset += csr->response.length;
  2585. return offset;
  2586. }
  2587. #endif
  2588. return 0;
  2589. }
  2590. static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2591. byte isRequest)
  2592. {
  2593. int ret;
  2594. #if !defined(NO_WOLFSSL_SERVER)
  2595. byte status_type;
  2596. word16 size = 0;
  2597. #if defined(WOLFSSL_TLS13)
  2598. DecodedCert* cert;
  2599. #endif
  2600. #endif
  2601. #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) \
  2602. && defined(WOLFSSL_TLS13)
  2603. OcspRequest* request;
  2604. TLSX* extension;
  2605. CertificateStatusRequest* csr;
  2606. #endif
  2607. #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_TLS13) \
  2608. || !defined(NO_WOLFSSL_SERVER)
  2609. word32 offset = 0;
  2610. #endif
  2611. #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_TLS13)
  2612. word32 resp_length = 0;
  2613. #endif
  2614. /* shut up compiler warnings */
  2615. (void) ssl; (void) input;
  2616. if (!isRequest) {
  2617. #ifndef NO_WOLFSSL_CLIENT
  2618. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2619. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2620. if (!csr) {
  2621. /* look at context level */
  2622. extension = TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST);
  2623. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2624. if (!csr) /* unexpected extension */
  2625. return TLSX_HandleUnsupportedExtension(ssl);
  2626. /* enable extension at ssl level */
  2627. ret = TLSX_UseCertificateStatusRequest(&ssl->extensions,
  2628. csr->status_type, csr->options, ssl,
  2629. ssl->heap, ssl->devId);
  2630. if (ret != WOLFSSL_SUCCESS)
  2631. return ret == 0 ? -1 : ret;
  2632. switch (csr->status_type) {
  2633. case WOLFSSL_CSR_OCSP:
  2634. /* propagate nonce */
  2635. if (csr->request.ocsp.nonceSz) {
  2636. request =
  2637. (OcspRequest*)TLSX_CSR_GetRequest(ssl->extensions);
  2638. if (request) {
  2639. XMEMCPY(request->nonce, csr->request.ocsp.nonce,
  2640. csr->request.ocsp.nonceSz);
  2641. request->nonceSz = csr->request.ocsp.nonceSz;
  2642. }
  2643. }
  2644. break;
  2645. }
  2646. }
  2647. ssl->status_request = 1;
  2648. #ifdef WOLFSSL_TLS13
  2649. if (ssl->options.tls1_3) {
  2650. /* Get the new extension potentially created above. */
  2651. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2652. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2653. if (csr == NULL)
  2654. return MEMORY_ERROR;
  2655. ret = 0;
  2656. if (OPAQUE8_LEN + OPAQUE24_LEN > length)
  2657. ret = BUFFER_ERROR;
  2658. if (ret == 0 && input[offset++] != WOLFSSL_CSR_OCSP) {
  2659. ret = BAD_CERTIFICATE_STATUS_ERROR;
  2660. WOLFSSL_ERROR_VERBOSE(ret);
  2661. }
  2662. if (ret == 0) {
  2663. c24to32(input + offset, &resp_length);
  2664. offset += OPAQUE24_LEN;
  2665. if (offset + resp_length != length)
  2666. ret = BUFFER_ERROR;
  2667. }
  2668. if (ret == 0) {
  2669. csr->response.buffer = (byte*)XMALLOC(resp_length, ssl->heap,
  2670. DYNAMIC_TYPE_TMP_BUFFER);
  2671. if (csr->response.buffer == NULL)
  2672. ret = MEMORY_ERROR;
  2673. }
  2674. if (ret == 0) {
  2675. XMEMCPY(csr->response.buffer, input + offset, resp_length);
  2676. csr->response.length = resp_length;
  2677. }
  2678. return ret;
  2679. }
  2680. else
  2681. #endif
  2682. {
  2683. /* extension_data MUST be empty. */
  2684. return length ? BUFFER_ERROR : 0;
  2685. }
  2686. #endif
  2687. }
  2688. else {
  2689. #ifndef NO_WOLFSSL_SERVER
  2690. if (length == 0)
  2691. return 0;
  2692. status_type = input[offset++];
  2693. switch (status_type) {
  2694. case WOLFSSL_CSR_OCSP: {
  2695. /* skip responder_id_list */
  2696. if ((int)(length - offset) < OPAQUE16_LEN)
  2697. return BUFFER_ERROR;
  2698. ato16(input + offset, &size);
  2699. offset += OPAQUE16_LEN + size;
  2700. /* skip request_extensions */
  2701. if ((int)(length - offset) < OPAQUE16_LEN)
  2702. return BUFFER_ERROR;
  2703. ato16(input + offset, &size);
  2704. offset += OPAQUE16_LEN + size;
  2705. if (offset > length)
  2706. return BUFFER_ERROR;
  2707. /* is able to send OCSP response? */
  2708. if (SSL_CM(ssl) == NULL || !SSL_CM(ssl)->ocspStaplingEnabled)
  2709. return 0;
  2710. }
  2711. break;
  2712. /* unknown status type */
  2713. default:
  2714. return 0;
  2715. }
  2716. /* if using status_request and already sending it, skip this one */
  2717. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2718. if (ssl->status_request_v2)
  2719. return 0;
  2720. #endif
  2721. /* accept the first good status_type and return */
  2722. ret = TLSX_UseCertificateStatusRequest(&ssl->extensions, status_type,
  2723. 0, ssl, ssl->heap, ssl->devId);
  2724. if (ret != WOLFSSL_SUCCESS)
  2725. return ret == 0 ? -1 : ret; /* throw error */
  2726. #if defined(WOLFSSL_TLS13)
  2727. if (ssl->options.tls1_3) {
  2728. if (ssl->buffers.certificate == NULL) {
  2729. WOLFSSL_MSG("Certificate buffer not set!");
  2730. return BUFFER_ERROR;
  2731. }
  2732. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
  2733. DYNAMIC_TYPE_DCERT);
  2734. if (cert == NULL) {
  2735. return MEMORY_E;
  2736. }
  2737. InitDecodedCert(cert, ssl->buffers.certificate->buffer,
  2738. ssl->buffers.certificate->length, ssl->heap);
  2739. ret = ParseCert(cert, CERT_TYPE, 1, SSL_CM(ssl));
  2740. if (ret != 0 ) {
  2741. FreeDecodedCert(cert);
  2742. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2743. return ret;
  2744. }
  2745. ret = TLSX_CSR_InitRequest(ssl->extensions, cert, ssl->heap);
  2746. if (ret != 0 ) {
  2747. FreeDecodedCert(cert);
  2748. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2749. return ret;
  2750. }
  2751. FreeDecodedCert(cert);
  2752. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2753. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2754. csr = extension ?
  2755. (CertificateStatusRequest*)extension->data : NULL;
  2756. if (csr == NULL)
  2757. return MEMORY_ERROR;
  2758. request = &csr->request.ocsp;
  2759. ret = CreateOcspResponse(ssl, &request, &csr->response);
  2760. if (ret != 0)
  2761. return ret;
  2762. if (csr->response.buffer)
  2763. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST);
  2764. }
  2765. else
  2766. #endif
  2767. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST);
  2768. ssl->status_request = status_type;
  2769. #endif
  2770. }
  2771. return 0;
  2772. }
  2773. int TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert, void* heap)
  2774. {
  2775. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST);
  2776. CertificateStatusRequest* csr = extension ?
  2777. (CertificateStatusRequest*)extension->data : NULL;
  2778. int ret = 0;
  2779. if (csr) {
  2780. switch (csr->status_type) {
  2781. case WOLFSSL_CSR_OCSP: {
  2782. byte nonce[MAX_OCSP_NONCE_SZ];
  2783. int nonceSz = csr->request.ocsp.nonceSz;
  2784. /* preserve nonce */
  2785. XMEMCPY(nonce, csr->request.ocsp.nonce, nonceSz);
  2786. if ((ret = InitOcspRequest(&csr->request.ocsp, cert, 0, heap))
  2787. != 0)
  2788. return ret;
  2789. /* restore nonce */
  2790. XMEMCPY(csr->request.ocsp.nonce, nonce, nonceSz);
  2791. csr->request.ocsp.nonceSz = nonceSz;
  2792. }
  2793. break;
  2794. }
  2795. }
  2796. return ret;
  2797. }
  2798. void* TLSX_CSR_GetRequest(TLSX* extensions)
  2799. {
  2800. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST);
  2801. CertificateStatusRequest* csr = extension ?
  2802. (CertificateStatusRequest*)extension->data : NULL;
  2803. if (csr) {
  2804. switch (csr->status_type) {
  2805. case WOLFSSL_CSR_OCSP:
  2806. return &csr->request.ocsp;
  2807. }
  2808. }
  2809. return NULL;
  2810. }
  2811. int TLSX_CSR_ForceRequest(WOLFSSL* ssl)
  2812. {
  2813. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2814. CertificateStatusRequest* csr = extension ?
  2815. (CertificateStatusRequest*)extension->data : NULL;
  2816. if (csr) {
  2817. switch (csr->status_type) {
  2818. case WOLFSSL_CSR_OCSP:
  2819. if (SSL_CM(ssl)->ocspEnabled) {
  2820. csr->request.ocsp.ssl = ssl;
  2821. return CheckOcspRequest(SSL_CM(ssl)->ocsp,
  2822. &csr->request.ocsp, NULL, NULL);
  2823. }
  2824. else {
  2825. WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL);
  2826. return OCSP_LOOKUP_FAIL;
  2827. }
  2828. }
  2829. }
  2830. return 0;
  2831. }
  2832. int TLSX_UseCertificateStatusRequest(TLSX** extensions, byte status_type,
  2833. byte options, WOLFSSL* ssl, void* heap,
  2834. int devId)
  2835. {
  2836. CertificateStatusRequest* csr = NULL;
  2837. int ret = 0;
  2838. if (!extensions || status_type != WOLFSSL_CSR_OCSP)
  2839. return BAD_FUNC_ARG;
  2840. csr = (CertificateStatusRequest*)
  2841. XMALLOC(sizeof(CertificateStatusRequest), heap, DYNAMIC_TYPE_TLSX);
  2842. if (!csr)
  2843. return MEMORY_E;
  2844. ForceZero(csr, sizeof(CertificateStatusRequest));
  2845. csr->status_type = status_type;
  2846. csr->options = options;
  2847. csr->ssl = ssl;
  2848. switch (csr->status_type) {
  2849. case WOLFSSL_CSR_OCSP:
  2850. if (options & WOLFSSL_CSR_OCSP_USE_NONCE) {
  2851. WC_RNG rng;
  2852. #ifndef HAVE_FIPS
  2853. ret = wc_InitRng_ex(&rng, heap, devId);
  2854. #else
  2855. ret = wc_InitRng(&rng);
  2856. (void)devId;
  2857. #endif
  2858. if (ret == 0) {
  2859. if (wc_RNG_GenerateBlock(&rng, csr->request.ocsp.nonce,
  2860. MAX_OCSP_NONCE_SZ) == 0)
  2861. csr->request.ocsp.nonceSz = MAX_OCSP_NONCE_SZ;
  2862. wc_FreeRng(&rng);
  2863. }
  2864. }
  2865. break;
  2866. }
  2867. if ((ret = TLSX_Push(extensions, TLSX_STATUS_REQUEST, csr, heap)) != 0) {
  2868. XFREE(csr, heap, DYNAMIC_TYPE_TLSX);
  2869. return ret;
  2870. }
  2871. return WOLFSSL_SUCCESS;
  2872. }
  2873. #define CSR_FREE_ALL TLSX_CSR_Free
  2874. #define CSR_GET_SIZE TLSX_CSR_GetSize
  2875. #define CSR_WRITE TLSX_CSR_Write
  2876. #define CSR_PARSE TLSX_CSR_Parse
  2877. #else
  2878. #define CSR_FREE_ALL(data, heap) WC_DO_NOTHING
  2879. #define CSR_GET_SIZE(a, b) 0
  2880. #define CSR_WRITE(a, b, c) 0
  2881. #define CSR_PARSE(a, b, c, d) 0
  2882. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
  2883. /******************************************************************************/
  2884. /* Certificate Status Request v2 */
  2885. /******************************************************************************/
  2886. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2887. static void TLSX_CSR2_FreeAll(CertificateStatusRequestItemV2* csr2, void* heap)
  2888. {
  2889. CertificateStatusRequestItemV2* next;
  2890. for (; csr2; csr2 = next) {
  2891. next = csr2->next;
  2892. switch (csr2->status_type) {
  2893. case WOLFSSL_CSR2_OCSP:
  2894. case WOLFSSL_CSR2_OCSP_MULTI:
  2895. while(csr2->requests--)
  2896. FreeOcspRequest(&csr2->request.ocsp[csr2->requests]);
  2897. break;
  2898. }
  2899. XFREE(csr2, heap, DYNAMIC_TYPE_TLSX);
  2900. }
  2901. (void)heap;
  2902. }
  2903. static word16 TLSX_CSR2_GetSize(CertificateStatusRequestItemV2* csr2,
  2904. byte isRequest)
  2905. {
  2906. word16 size = 0;
  2907. /* shut up compiler warnings */
  2908. (void) csr2; (void) isRequest;
  2909. #ifndef NO_WOLFSSL_CLIENT
  2910. if (isRequest) {
  2911. CertificateStatusRequestItemV2* next;
  2912. for (size = OPAQUE16_LEN; csr2; csr2 = next) {
  2913. next = csr2->next;
  2914. switch (csr2->status_type) {
  2915. case WOLFSSL_CSR2_OCSP:
  2916. case WOLFSSL_CSR2_OCSP_MULTI:
  2917. size += ENUM_LEN + 3 * OPAQUE16_LEN;
  2918. if (csr2->request.ocsp[0].nonceSz)
  2919. size += OCSP_NONCE_EXT_SZ;
  2920. break;
  2921. }
  2922. }
  2923. }
  2924. #endif
  2925. return size;
  2926. }
  2927. static word16 TLSX_CSR2_Write(CertificateStatusRequestItemV2* csr2,
  2928. byte* output, byte isRequest)
  2929. {
  2930. /* shut up compiler warnings */
  2931. (void) csr2; (void) output; (void) isRequest;
  2932. #ifndef NO_WOLFSSL_CLIENT
  2933. if (isRequest) {
  2934. word16 offset;
  2935. word16 length;
  2936. for (offset = OPAQUE16_LEN; csr2 != NULL; csr2 = csr2->next) {
  2937. /* status_type */
  2938. output[offset++] = csr2->status_type;
  2939. /* request */
  2940. switch (csr2->status_type) {
  2941. case WOLFSSL_CSR2_OCSP:
  2942. case WOLFSSL_CSR2_OCSP_MULTI:
  2943. /* request_length */
  2944. length = 2 * OPAQUE16_LEN;
  2945. if (csr2->request.ocsp[0].nonceSz)
  2946. length += OCSP_NONCE_EXT_SZ;
  2947. c16toa(length, output + offset);
  2948. offset += OPAQUE16_LEN;
  2949. /* responder id list */
  2950. c16toa(0, output + offset);
  2951. offset += OPAQUE16_LEN;
  2952. /* request extensions */
  2953. length = 0;
  2954. if (csr2->request.ocsp[0].nonceSz)
  2955. length = (word16)EncodeOcspRequestExtensions(
  2956. &csr2->request.ocsp[0],
  2957. output + offset + OPAQUE16_LEN,
  2958. OCSP_NONCE_EXT_SZ);
  2959. c16toa(length, output + offset);
  2960. offset += OPAQUE16_LEN + length;
  2961. break;
  2962. }
  2963. }
  2964. /* list size */
  2965. c16toa(offset - OPAQUE16_LEN, output);
  2966. return offset;
  2967. }
  2968. #endif
  2969. return 0;
  2970. }
  2971. static int TLSX_CSR2_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2972. byte isRequest)
  2973. {
  2974. int ret;
  2975. /* shut up compiler warnings */
  2976. (void) ssl; (void) input;
  2977. if (!isRequest) {
  2978. #ifndef NO_WOLFSSL_CLIENT
  2979. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST_V2);
  2980. CertificateStatusRequestItemV2* csr2 = extension ?
  2981. (CertificateStatusRequestItemV2*)extension->data : NULL;
  2982. if (!csr2) {
  2983. /* look at context level */
  2984. extension = TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST_V2);
  2985. csr2 = extension ?
  2986. (CertificateStatusRequestItemV2*)extension->data : NULL;
  2987. if (!csr2) /* unexpected extension */
  2988. return TLSX_HandleUnsupportedExtension(ssl);
  2989. /* enable extension at ssl level */
  2990. for (; csr2; csr2 = csr2->next) {
  2991. ret = TLSX_UseCertificateStatusRequestV2(&ssl->extensions,
  2992. csr2->status_type, csr2->options, ssl->heap,
  2993. ssl->devId);
  2994. if (ret != WOLFSSL_SUCCESS)
  2995. return ret;
  2996. switch (csr2->status_type) {
  2997. case WOLFSSL_CSR2_OCSP:
  2998. /* followed by */
  2999. case WOLFSSL_CSR2_OCSP_MULTI:
  3000. /* propagate nonce */
  3001. if (csr2->request.ocsp[0].nonceSz) {
  3002. OcspRequest* request =
  3003. (OcspRequest*)TLSX_CSR2_GetRequest(ssl->extensions,
  3004. csr2->status_type, 0);
  3005. if (request) {
  3006. XMEMCPY(request->nonce,
  3007. csr2->request.ocsp[0].nonce,
  3008. csr2->request.ocsp[0].nonceSz);
  3009. request->nonceSz =
  3010. csr2->request.ocsp[0].nonceSz;
  3011. }
  3012. }
  3013. break;
  3014. }
  3015. }
  3016. }
  3017. ssl->status_request_v2 = 1;
  3018. return length ? BUFFER_ERROR : 0; /* extension_data MUST be empty. */
  3019. #endif
  3020. }
  3021. else {
  3022. #ifndef NO_WOLFSSL_SERVER
  3023. byte status_type;
  3024. word16 request_length;
  3025. word16 offset = 0;
  3026. word16 size = 0;
  3027. /* list size */
  3028. if (offset + OPAQUE16_LEN >= length) {
  3029. return BUFFER_E;
  3030. }
  3031. ato16(input + offset, &request_length);
  3032. offset += OPAQUE16_LEN;
  3033. if (length - OPAQUE16_LEN != request_length)
  3034. return BUFFER_ERROR;
  3035. while (length > offset) {
  3036. if ((int)(length - offset) < ENUM_LEN + OPAQUE16_LEN)
  3037. return BUFFER_ERROR;
  3038. status_type = input[offset++];
  3039. ato16(input + offset, &request_length);
  3040. offset += OPAQUE16_LEN;
  3041. if (length - offset < request_length)
  3042. return BUFFER_ERROR;
  3043. switch (status_type) {
  3044. case WOLFSSL_CSR2_OCSP:
  3045. case WOLFSSL_CSR2_OCSP_MULTI:
  3046. /* skip responder_id_list */
  3047. if ((int)(length - offset) < OPAQUE16_LEN)
  3048. return BUFFER_ERROR;
  3049. ato16(input + offset, &size);
  3050. if (length - offset < size)
  3051. return BUFFER_ERROR;
  3052. offset += OPAQUE16_LEN + size;
  3053. /* skip request_extensions */
  3054. if ((int)(length - offset) < OPAQUE16_LEN)
  3055. return BUFFER_ERROR;
  3056. ato16(input + offset, &size);
  3057. if (length - offset < size)
  3058. return BUFFER_ERROR;
  3059. offset += OPAQUE16_LEN + size;
  3060. if (offset > length)
  3061. return BUFFER_ERROR;
  3062. /* is able to send OCSP response? */
  3063. if (SSL_CM(ssl) == NULL
  3064. || !SSL_CM(ssl)->ocspStaplingEnabled)
  3065. continue;
  3066. break;
  3067. default:
  3068. /* unknown status type, skipping! */
  3069. offset += request_length;
  3070. continue;
  3071. }
  3072. /* if using status_request and already sending it, remove it
  3073. * and prefer to use the v2 version */
  3074. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  3075. if (ssl->status_request) {
  3076. ssl->status_request = 0;
  3077. TLSX_Remove(&ssl->extensions, TLSX_STATUS_REQUEST, ssl->heap);
  3078. }
  3079. #endif
  3080. /* TLS 1.3 servers MUST NOT act upon presence or information in
  3081. * this extension (RFC 8448 Section 4.4.2.1).
  3082. */
  3083. if (!IsAtLeastTLSv1_3(ssl->version)) {
  3084. /* accept the first good status_type and return */
  3085. ret = TLSX_UseCertificateStatusRequestV2(&ssl->extensions,
  3086. status_type, 0, ssl->heap, ssl->devId);
  3087. if (ret != WOLFSSL_SUCCESS)
  3088. return ret; /* throw error */
  3089. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST_V2);
  3090. ssl->status_request_v2 = status_type;
  3091. }
  3092. return 0;
  3093. }
  3094. #endif
  3095. }
  3096. return 0;
  3097. }
  3098. int TLSX_CSR2_InitRequests(TLSX* extensions, DecodedCert* cert, byte isPeer,
  3099. void* heap)
  3100. {
  3101. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2);
  3102. CertificateStatusRequestItemV2* csr2 = extension ?
  3103. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3104. int ret = 0;
  3105. for (; csr2; csr2 = csr2->next) {
  3106. switch (csr2->status_type) {
  3107. case WOLFSSL_CSR2_OCSP:
  3108. if (!isPeer || csr2->requests != 0)
  3109. break;
  3110. FALL_THROUGH; /* followed by */
  3111. case WOLFSSL_CSR2_OCSP_MULTI: {
  3112. if (csr2->requests < 1 + MAX_CHAIN_DEPTH) {
  3113. byte nonce[MAX_OCSP_NONCE_SZ];
  3114. int nonceSz = csr2->request.ocsp[0].nonceSz;
  3115. /* preserve nonce, replicating nonce of ocsp[0] */
  3116. XMEMCPY(nonce, csr2->request.ocsp[0].nonce, nonceSz);
  3117. if ((ret = InitOcspRequest(
  3118. &csr2->request.ocsp[csr2->requests], cert,
  3119. 0, heap)) != 0)
  3120. return ret;
  3121. /* restore nonce */
  3122. XMEMCPY(csr2->request.ocsp[csr2->requests].nonce,
  3123. nonce, nonceSz);
  3124. csr2->request.ocsp[csr2->requests].nonceSz = nonceSz;
  3125. csr2->requests++;
  3126. }
  3127. }
  3128. break;
  3129. }
  3130. }
  3131. (void)cert;
  3132. return ret;
  3133. }
  3134. void* TLSX_CSR2_GetRequest(TLSX* extensions, byte status_type, byte idx)
  3135. {
  3136. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2);
  3137. CertificateStatusRequestItemV2* csr2 = extension ?
  3138. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3139. for (; csr2; csr2 = csr2->next) {
  3140. if (csr2->status_type == status_type) {
  3141. switch (csr2->status_type) {
  3142. case WOLFSSL_CSR2_OCSP:
  3143. /* followed by */
  3144. case WOLFSSL_CSR2_OCSP_MULTI:
  3145. /* requests are initialized in the reverse order */
  3146. return idx < csr2->requests
  3147. ? &csr2->request.ocsp[csr2->requests - idx - 1]
  3148. : NULL;
  3149. }
  3150. }
  3151. }
  3152. return NULL;
  3153. }
  3154. int TLSX_CSR2_ForceRequest(WOLFSSL* ssl)
  3155. {
  3156. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST_V2);
  3157. CertificateStatusRequestItemV2* csr2 = extension ?
  3158. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3159. /* forces only the first one */
  3160. if (csr2) {
  3161. switch (csr2->status_type) {
  3162. case WOLFSSL_CSR2_OCSP:
  3163. /* followed by */
  3164. case WOLFSSL_CSR2_OCSP_MULTI:
  3165. if (SSL_CM(ssl)->ocspEnabled) {
  3166. csr2->request.ocsp[0].ssl = ssl;
  3167. return CheckOcspRequest(SSL_CM(ssl)->ocsp,
  3168. &csr2->request.ocsp[0], NULL, NULL);
  3169. }
  3170. else {
  3171. WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL);
  3172. return OCSP_LOOKUP_FAIL;
  3173. }
  3174. }
  3175. }
  3176. return 0;
  3177. }
  3178. int TLSX_UseCertificateStatusRequestV2(TLSX** extensions, byte status_type,
  3179. byte options, void* heap, int devId)
  3180. {
  3181. TLSX* extension = NULL;
  3182. CertificateStatusRequestItemV2* csr2 = NULL;
  3183. int ret = 0;
  3184. if (!extensions)
  3185. return BAD_FUNC_ARG;
  3186. if (status_type != WOLFSSL_CSR2_OCSP
  3187. && status_type != WOLFSSL_CSR2_OCSP_MULTI)
  3188. return BAD_FUNC_ARG;
  3189. csr2 = (CertificateStatusRequestItemV2*)
  3190. XMALLOC(sizeof(CertificateStatusRequestItemV2), heap, DYNAMIC_TYPE_TLSX);
  3191. if (!csr2)
  3192. return MEMORY_E;
  3193. ForceZero(csr2, sizeof(CertificateStatusRequestItemV2));
  3194. csr2->status_type = status_type;
  3195. csr2->options = options;
  3196. csr2->next = NULL;
  3197. switch (csr2->status_type) {
  3198. case WOLFSSL_CSR2_OCSP:
  3199. case WOLFSSL_CSR2_OCSP_MULTI:
  3200. if (options & WOLFSSL_CSR2_OCSP_USE_NONCE) {
  3201. WC_RNG rng;
  3202. #ifndef HAVE_FIPS
  3203. ret = wc_InitRng_ex(&rng, heap, devId);
  3204. #else
  3205. ret = wc_InitRng(&rng);
  3206. (void)devId;
  3207. #endif
  3208. if (ret == 0) {
  3209. if (wc_RNG_GenerateBlock(&rng, csr2->request.ocsp[0].nonce,
  3210. MAX_OCSP_NONCE_SZ) == 0)
  3211. csr2->request.ocsp[0].nonceSz = MAX_OCSP_NONCE_SZ;
  3212. wc_FreeRng(&rng);
  3213. }
  3214. }
  3215. break;
  3216. }
  3217. /* append new item */
  3218. if ((extension = TLSX_Find(*extensions, TLSX_STATUS_REQUEST_V2))) {
  3219. CertificateStatusRequestItemV2* last =
  3220. (CertificateStatusRequestItemV2*)extension->data;
  3221. for (; last->next; last = last->next);
  3222. last->next = csr2;
  3223. }
  3224. else if ((ret = TLSX_Push(extensions, TLSX_STATUS_REQUEST_V2, csr2,heap))) {
  3225. XFREE(csr2, heap, DYNAMIC_TYPE_TLSX);
  3226. return ret;
  3227. }
  3228. return WOLFSSL_SUCCESS;
  3229. }
  3230. #define CSR2_FREE_ALL TLSX_CSR2_FreeAll
  3231. #define CSR2_GET_SIZE TLSX_CSR2_GetSize
  3232. #define CSR2_WRITE TLSX_CSR2_Write
  3233. #define CSR2_PARSE TLSX_CSR2_Parse
  3234. #else
  3235. #define CSR2_FREE_ALL(data, heap) WC_DO_NOTHING
  3236. #define CSR2_GET_SIZE(a, b) 0
  3237. #define CSR2_WRITE(a, b, c) 0
  3238. #define CSR2_PARSE(a, b, c, d) 0
  3239. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  3240. /******************************************************************************/
  3241. /* Supported Elliptic Curves */
  3242. /******************************************************************************/
  3243. #ifdef HAVE_SUPPORTED_CURVES
  3244. #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) \
  3245. && !defined(HAVE_FFDHE) && !defined(HAVE_PQC)
  3246. #error Elliptic Curves Extension requires Elliptic Curve Cryptography or liboqs groups. \
  3247. Use --enable-ecc and/or --enable-liboqs in the configure script or \
  3248. define HAVE_ECC. Alternatively use FFDHE for DH cipher suites.
  3249. #endif
  3250. static int TLSX_SupportedCurve_New(SupportedCurve** curve, word16 name,
  3251. void* heap)
  3252. {
  3253. if (curve == NULL)
  3254. return BAD_FUNC_ARG;
  3255. (void)heap;
  3256. *curve = (SupportedCurve*)XMALLOC(sizeof(SupportedCurve), heap,
  3257. DYNAMIC_TYPE_TLSX);
  3258. if (*curve == NULL)
  3259. return MEMORY_E;
  3260. (*curve)->name = name;
  3261. (*curve)->next = NULL;
  3262. return 0;
  3263. }
  3264. static int TLSX_PointFormat_New(PointFormat** point, byte format, void* heap)
  3265. {
  3266. if (point == NULL)
  3267. return BAD_FUNC_ARG;
  3268. (void)heap;
  3269. *point = (PointFormat*)XMALLOC(sizeof(PointFormat), heap,
  3270. DYNAMIC_TYPE_TLSX);
  3271. if (*point == NULL)
  3272. return MEMORY_E;
  3273. (*point)->format = format;
  3274. (*point)->next = NULL;
  3275. return 0;
  3276. }
  3277. static void TLSX_SupportedCurve_FreeAll(SupportedCurve* list, void* heap)
  3278. {
  3279. SupportedCurve* curve;
  3280. while ((curve = list)) {
  3281. list = curve->next;
  3282. XFREE(curve, heap, DYNAMIC_TYPE_TLSX);
  3283. }
  3284. (void)heap;
  3285. }
  3286. static void TLSX_PointFormat_FreeAll(PointFormat* list, void* heap)
  3287. {
  3288. PointFormat* point;
  3289. while ((point = list)) {
  3290. list = point->next;
  3291. XFREE(point, heap, DYNAMIC_TYPE_TLSX);
  3292. }
  3293. (void)heap;
  3294. }
  3295. static int TLSX_SupportedCurve_Append(SupportedCurve* list, word16 name,
  3296. void* heap)
  3297. {
  3298. int ret = BAD_FUNC_ARG;
  3299. while (list) {
  3300. if (list->name == name) {
  3301. ret = 0; /* curve already in use */
  3302. break;
  3303. }
  3304. if (list->next == NULL) {
  3305. ret = TLSX_SupportedCurve_New(&list->next, name, heap);
  3306. break;
  3307. }
  3308. list = list->next;
  3309. }
  3310. return ret;
  3311. }
  3312. static int TLSX_PointFormat_Append(PointFormat* list, byte format, void* heap)
  3313. {
  3314. int ret = BAD_FUNC_ARG;
  3315. while (list) {
  3316. if (list->format == format) {
  3317. ret = 0; /* format already in use */
  3318. break;
  3319. }
  3320. if (list->next == NULL) {
  3321. ret = TLSX_PointFormat_New(&list->next, format, heap);
  3322. break;
  3323. }
  3324. list = list->next;
  3325. }
  3326. return ret;
  3327. }
  3328. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  3329. #if defined(HAVE_FFDHE) && (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3330. defined(HAVE_CURVE448))
  3331. static void TLSX_SupportedCurve_ValidateRequest(const WOLFSSL* ssl,
  3332. const byte* semaphore)
  3333. {
  3334. /* If all pre-defined parameter types for key exchange are supported then
  3335. * always send SupportedGroups extension.
  3336. */
  3337. (void)ssl;
  3338. (void)semaphore;
  3339. }
  3340. #else
  3341. static void TLSX_SupportedCurve_ValidateRequest(WOLFSSL* ssl, byte* semaphore)
  3342. {
  3343. word16 i;
  3344. const Suites* suites = WOLFSSL_SUITES(ssl);
  3345. for (i = 0; i < suites->suiteSz; i += 2) {
  3346. if (suites->suites[i] == TLS13_BYTE)
  3347. return;
  3348. #ifdef BUILD_TLS_SM4_GCM_SM3
  3349. if ((suites->suites[i] == CIPHER_BYTE) &&
  3350. (suites->suites[i+1] == TLS_SM4_GCM_SM3))
  3351. return;
  3352. #endif
  3353. #ifdef BUILD_TLS_SM4_CCM_SM3
  3354. if ((suites->suites[i] == CIPHER_BYTE) &&
  3355. (suites->suites[i+1] == TLS_SM4_CCM_SM3))
  3356. return;
  3357. #endif
  3358. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3359. if ((suites->suites[i] == SM_BYTE) &&
  3360. (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3361. return;
  3362. #endif
  3363. if ((suites->suites[i] == ECC_BYTE) ||
  3364. (suites->suites[i] == ECDHE_PSK_BYTE) ||
  3365. (suites->suites[i] == CHACHA_BYTE)) {
  3366. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3367. defined(HAVE_CURVE448)
  3368. return;
  3369. #endif
  3370. }
  3371. #ifdef HAVE_FFDHE
  3372. else {
  3373. return;
  3374. }
  3375. #endif
  3376. }
  3377. /* turns semaphore on to avoid sending this extension. */
  3378. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_GROUPS));
  3379. }
  3380. #endif
  3381. /* Only send PointFormats if TLSv13, ECC or CHACHA cipher suite present.
  3382. */
  3383. static void TLSX_PointFormat_ValidateRequest(WOLFSSL* ssl, byte* semaphore)
  3384. {
  3385. #ifdef HAVE_FFDHE
  3386. (void)ssl;
  3387. (void)semaphore;
  3388. #else
  3389. word16 i;
  3390. const Suites* suites = WOLFSSL_SUITES(ssl);
  3391. if (suites == NULL)
  3392. return;
  3393. for (i = 0; i < suites->suiteSz; i += 2) {
  3394. if (suites->suites[i] == TLS13_BYTE)
  3395. return;
  3396. #ifdef BUILD_TLS_SM4_GCM_SM3
  3397. if ((suites->suites[i] == CIPHER_BYTE) &&
  3398. (suites->suites[i+1] == TLS_SM4_GCM_SM3))
  3399. return;
  3400. #endif
  3401. #ifdef BUILD_TLS_SM4_CCM_SM3
  3402. if ((suites->suites[i] == CIPHER_BYTE) &&
  3403. (suites->suites[i+1] == TLS_SM4_CCM_SM3))
  3404. return;
  3405. #endif
  3406. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3407. if ((suites->suites[i] == SM_BYTE) &&
  3408. (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3409. return;
  3410. #endif
  3411. if ((suites->suites[i] == ECC_BYTE) ||
  3412. (suites->suites[i] == ECDHE_PSK_BYTE) ||
  3413. (suites->suites[i] == CHACHA_BYTE)) {
  3414. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3415. defined(HAVE_CURVE448)
  3416. return;
  3417. #endif
  3418. }
  3419. }
  3420. /* turns semaphore on to avoid sending this extension. */
  3421. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  3422. #endif
  3423. }
  3424. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  3425. #ifndef NO_WOLFSSL_SERVER
  3426. static void TLSX_PointFormat_ValidateResponse(WOLFSSL* ssl, byte* semaphore)
  3427. {
  3428. #if defined(HAVE_FFDHE) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3429. defined(HAVE_CURVE448)
  3430. (void)semaphore;
  3431. #endif
  3432. if (ssl->options.cipherSuite0 == TLS13_BYTE)
  3433. return;
  3434. #ifdef BUILD_TLS_SM4_GCM_SM3
  3435. if ((ssl->options.cipherSuite0 == CIPHER_BYTE) &&
  3436. (ssl->options.cipherSuite == TLS_SM4_GCM_SM3))
  3437. return;
  3438. #endif
  3439. #ifdef BUILD_TLS_SM4_CCM_SM3
  3440. if ((ssl->options.cipherSuite0 == CIPHER_BYTE) &&
  3441. (ssl->options.cipherSuite == TLS_SM4_CCM_SM3))
  3442. return;
  3443. #endif
  3444. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3445. if ((ssl->options.cipherSuite0 == SM_BYTE) &&
  3446. (ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3447. return;
  3448. #endif
  3449. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  3450. if (ssl->options.cipherSuite0 == ECC_BYTE ||
  3451. ssl->options.cipherSuite0 == ECDHE_PSK_BYTE ||
  3452. ssl->options.cipherSuite0 == CHACHA_BYTE) {
  3453. return;
  3454. }
  3455. #endif
  3456. /* turns semaphore on to avoid sending this extension. */
  3457. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  3458. }
  3459. #endif /* !NO_WOLFSSL_SERVER */
  3460. #ifndef NO_WOLFSSL_CLIENT
  3461. static word16 TLSX_SupportedCurve_GetSize(SupportedCurve* list)
  3462. {
  3463. SupportedCurve* curve;
  3464. word16 length = OPAQUE16_LEN; /* list length */
  3465. while ((curve = list)) {
  3466. list = curve->next;
  3467. length += OPAQUE16_LEN; /* curve length */
  3468. }
  3469. return length;
  3470. }
  3471. #endif
  3472. static word16 TLSX_PointFormat_GetSize(PointFormat* list)
  3473. {
  3474. PointFormat* point;
  3475. word16 length = ENUM_LEN; /* list length */
  3476. while ((point = list)) {
  3477. list = point->next;
  3478. length += ENUM_LEN; /* format length */
  3479. }
  3480. return length;
  3481. }
  3482. #ifndef NO_WOLFSSL_CLIENT
  3483. static word16 TLSX_SupportedCurve_Write(SupportedCurve* list, byte* output)
  3484. {
  3485. word16 offset = OPAQUE16_LEN;
  3486. while (list) {
  3487. c16toa(list->name, output + offset);
  3488. offset += OPAQUE16_LEN;
  3489. list = list->next;
  3490. }
  3491. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  3492. return offset;
  3493. }
  3494. #endif
  3495. static word16 TLSX_PointFormat_Write(PointFormat* list, byte* output)
  3496. {
  3497. word16 offset = ENUM_LEN;
  3498. while (list) {
  3499. output[offset++] = list->format;
  3500. list = list->next;
  3501. }
  3502. output[0] = (byte)(offset - ENUM_LEN);
  3503. return offset;
  3504. }
  3505. #if !defined(NO_WOLFSSL_SERVER) || (defined(WOLFSSL_TLS13) && \
  3506. !defined(WOLFSSL_NO_SERVER_GROUPS_EXT))
  3507. int TLSX_SupportedCurve_Parse(const WOLFSSL* ssl, const byte* input,
  3508. word16 length, byte isRequest, TLSX** extensions)
  3509. {
  3510. word16 offset;
  3511. word16 name;
  3512. int ret;
  3513. if(!isRequest && !IsAtLeastTLSv1_3(ssl->version)) {
  3514. #ifdef WOLFSSL_ALLOW_SERVER_SC_EXT
  3515. return 0;
  3516. #else
  3517. return BUFFER_ERROR; /* servers doesn't send this extension. */
  3518. #endif
  3519. }
  3520. if (OPAQUE16_LEN > length || length % OPAQUE16_LEN)
  3521. return BUFFER_ERROR;
  3522. ato16(input, &offset);
  3523. /* validating curve list length */
  3524. if (length != OPAQUE16_LEN + offset)
  3525. return BUFFER_ERROR;
  3526. offset = OPAQUE16_LEN;
  3527. if (offset == length)
  3528. return 0;
  3529. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3530. if (!isRequest) {
  3531. TLSX* extension;
  3532. SupportedCurve* curve;
  3533. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  3534. if (extension != NULL) {
  3535. /* Replace client list with server list of supported groups. */
  3536. curve = (SupportedCurve*)extension->data;
  3537. extension->data = NULL;
  3538. TLSX_SupportedCurve_FreeAll(curve, ssl->heap);
  3539. ato16(input + offset, &name);
  3540. offset += OPAQUE16_LEN;
  3541. ret = TLSX_SupportedCurve_New(&curve, name, ssl->heap);
  3542. if (ret != 0)
  3543. return ret; /* throw error */
  3544. extension->data = (void*)curve;
  3545. }
  3546. }
  3547. #endif
  3548. for (; offset < length; offset += OPAQUE16_LEN) {
  3549. ato16(input + offset, &name);
  3550. ret = TLSX_UseSupportedCurve(extensions, name, ssl->heap);
  3551. /* If it is BAD_FUNC_ARG then it is a group we do not support, but
  3552. * that is fine. */
  3553. if (ret != WOLFSSL_SUCCESS && ret != BAD_FUNC_ARG) {
  3554. return ret;
  3555. }
  3556. }
  3557. return 0;
  3558. }
  3559. #endif
  3560. #if !defined(NO_WOLFSSL_SERVER)
  3561. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3562. /* Checks the priority of the groups on the server and set the supported groups
  3563. * response if there is a group not advertised by the client that is preferred.
  3564. *
  3565. * ssl SSL/TLS object.
  3566. * returns 0 on success, otherwise an error.
  3567. */
  3568. int TLSX_SupportedCurve_CheckPriority(WOLFSSL* ssl)
  3569. {
  3570. int ret;
  3571. TLSX* extension;
  3572. TLSX* priority = NULL;
  3573. TLSX* ext = NULL;
  3574. word16 name;
  3575. SupportedCurve* curve;
  3576. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3577. /* May be doing PSK with no key exchange. */
  3578. if (extension == NULL)
  3579. return 0;
  3580. ret = TLSX_PopulateSupportedGroups(ssl, &priority);
  3581. if (ret != WOLFSSL_SUCCESS) {
  3582. TLSX_FreeAll(priority, ssl->heap);
  3583. return ret;
  3584. }
  3585. ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS);
  3586. if (ext == NULL) {
  3587. WOLFSSL_MSG("Could not find supported groups extension");
  3588. TLSX_FreeAll(priority, ssl->heap);
  3589. return 0;
  3590. }
  3591. curve = (SupportedCurve*)ext->data;
  3592. name = curve->name;
  3593. curve = (SupportedCurve*)extension->data;
  3594. while (curve != NULL) {
  3595. if (curve->name == name)
  3596. break;
  3597. curve = curve->next;
  3598. }
  3599. if (curve == NULL) {
  3600. /* Couldn't find the preferred group in client list. */
  3601. extension->resp = 1;
  3602. /* Send server list back and free client list. */
  3603. curve = (SupportedCurve*)extension->data;
  3604. extension->data = ext->data;
  3605. ext->data = curve;
  3606. }
  3607. TLSX_FreeAll(priority, ssl->heap);
  3608. return 0;
  3609. }
  3610. #endif /* WOLFSSL_TLS13 && !WOLFSSL_NO_SERVER_GROUPS_EXT */
  3611. #if defined(HAVE_FFDHE) && !defined(WOLFSSL_NO_TLS12)
  3612. #ifdef HAVE_PUBLIC_FFDHE
  3613. static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup,
  3614. SupportedCurve* serverGroup)
  3615. {
  3616. int ret = 0;
  3617. SupportedCurve* group;
  3618. const DhParams* params = NULL;
  3619. for (; serverGroup != NULL; serverGroup = serverGroup->next) {
  3620. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name))
  3621. continue;
  3622. for (group = clientGroup; group != NULL; group = group->next) {
  3623. if (serverGroup->name != group->name)
  3624. continue;
  3625. switch (serverGroup->name) {
  3626. #ifdef HAVE_FFDHE_2048
  3627. case WOLFSSL_FFDHE_2048:
  3628. params = wc_Dh_ffdhe2048_Get();
  3629. break;
  3630. #endif
  3631. #ifdef HAVE_FFDHE_3072
  3632. case WOLFSSL_FFDHE_3072:
  3633. params = wc_Dh_ffdhe3072_Get();
  3634. break;
  3635. #endif
  3636. #ifdef HAVE_FFDHE_4096
  3637. case WOLFSSL_FFDHE_4096:
  3638. params = wc_Dh_ffdhe4096_Get();
  3639. break;
  3640. #endif
  3641. #ifdef HAVE_FFDHE_6144
  3642. case WOLFSSL_FFDHE_6144:
  3643. params = wc_Dh_ffdhe6144_Get();
  3644. break;
  3645. #endif
  3646. #ifdef HAVE_FFDHE_8192
  3647. case WOLFSSL_FFDHE_8192:
  3648. params = wc_Dh_ffdhe8192_Get();
  3649. break;
  3650. #endif
  3651. default:
  3652. break;
  3653. }
  3654. if (params == NULL) {
  3655. ret = BAD_FUNC_ARG;
  3656. break;
  3657. }
  3658. if (params->p_len >= ssl->options.minDhKeySz &&
  3659. params->p_len <= ssl->options.maxDhKeySz) {
  3660. break;
  3661. }
  3662. }
  3663. if (ret != 0)
  3664. break;
  3665. if ((group != NULL) && (serverGroup->name == group->name))
  3666. break;
  3667. }
  3668. if ((ret == 0) && (serverGroup != NULL) && (params != NULL)) {
  3669. ssl->buffers.serverDH_P.buffer = (unsigned char *)params->p;
  3670. ssl->buffers.serverDH_P.length = params->p_len;
  3671. ssl->buffers.serverDH_G.buffer = (unsigned char *)params->g;
  3672. ssl->buffers.serverDH_G.length = params->g_len;
  3673. ssl->namedGroup = serverGroup->name;
  3674. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  3675. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  3676. ssl->options.dhDoKeyTest = 0;
  3677. #endif
  3678. ssl->options.haveDH = 1;
  3679. }
  3680. return ret;
  3681. }
  3682. #else
  3683. static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup,
  3684. SupportedCurve* serverGroup)
  3685. {
  3686. int ret = 0;
  3687. SupportedCurve* group;
  3688. word32 p_len;
  3689. for (; serverGroup != NULL; serverGroup = serverGroup->next) {
  3690. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name))
  3691. continue;
  3692. for (group = clientGroup; group != NULL; group = group->next) {
  3693. if (serverGroup->name != group->name)
  3694. continue;
  3695. wc_DhGetNamedKeyParamSize(serverGroup->name, &p_len, NULL, NULL);
  3696. if (p_len == 0) {
  3697. ret = BAD_FUNC_ARG;
  3698. break;
  3699. }
  3700. if (p_len >= ssl->options.minDhKeySz &&
  3701. p_len <= ssl->options.maxDhKeySz) {
  3702. break;
  3703. }
  3704. }
  3705. if (ret != 0)
  3706. break;
  3707. if ((group != NULL) && (serverGroup->name == group->name))
  3708. break;
  3709. }
  3710. if ((ret == 0) && (serverGroup != NULL)) {
  3711. word32 pSz, gSz;
  3712. ssl->buffers.serverDH_P.buffer = NULL;
  3713. ssl->buffers.serverDH_G.buffer = NULL;
  3714. ret = wc_DhGetNamedKeyParamSize(serverGroup->name, &pSz, &gSz, NULL);
  3715. if (ret == 0) {
  3716. ssl->buffers.serverDH_P.buffer =
  3717. (byte*)XMALLOC(pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  3718. if (ssl->buffers.serverDH_P.buffer == NULL)
  3719. ret = MEMORY_E;
  3720. else
  3721. ssl->buffers.serverDH_P.length = pSz;
  3722. }
  3723. if (ret == 0) {
  3724. ssl->buffers.serverDH_G.buffer =
  3725. (byte*)XMALLOC(gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  3726. if (ssl->buffers.serverDH_G.buffer == NULL) {
  3727. ret = MEMORY_E;
  3728. } else
  3729. ssl->buffers.serverDH_G.length = gSz;
  3730. }
  3731. if (ret == 0) {
  3732. ret = wc_DhCopyNamedKey(serverGroup->name,
  3733. ssl->buffers.serverDH_P.buffer, &pSz,
  3734. ssl->buffers.serverDH_G.buffer, &gSz,
  3735. NULL, NULL);
  3736. }
  3737. if (ret == 0) {
  3738. ssl->buffers.weOwnDH = 1;
  3739. ssl->namedGroup = serverGroup->name;
  3740. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  3741. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  3742. ssl->options.dhDoKeyTest = 0;
  3743. #endif
  3744. ssl->options.haveDH = 1;
  3745. }
  3746. else {
  3747. if (ssl->buffers.serverDH_P.buffer != NULL) {
  3748. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  3749. DYNAMIC_TYPE_PUBLIC_KEY);
  3750. ssl->buffers.serverDH_P.length = 0;
  3751. ssl->buffers.serverDH_P.buffer = NULL;
  3752. }
  3753. if (ssl->buffers.serverDH_G.buffer != NULL) {
  3754. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  3755. DYNAMIC_TYPE_PUBLIC_KEY);
  3756. ssl->buffers.serverDH_G.length = 0;
  3757. ssl->buffers.serverDH_G.buffer = NULL;
  3758. }
  3759. }
  3760. }
  3761. return ret;
  3762. }
  3763. #endif
  3764. /* Set the highest priority common FFDHE group on the server as compared to
  3765. * client extensions.
  3766. *
  3767. * ssl SSL/TLS object.
  3768. * returns 0 on success, otherwise an error.
  3769. */
  3770. int TLSX_SupportedFFDHE_Set(WOLFSSL* ssl)
  3771. {
  3772. int ret;
  3773. TLSX* priority = NULL;
  3774. TLSX* ext = NULL;
  3775. TLSX* extension;
  3776. SupportedCurve* clientGroup;
  3777. SupportedCurve* group;
  3778. int found = 0;
  3779. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3780. /* May be doing PSK with no key exchange. */
  3781. if (extension == NULL)
  3782. return 0;
  3783. clientGroup = (SupportedCurve*)extension->data;
  3784. for (group = clientGroup; group != NULL; group = group->next) {
  3785. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(group->name)) {
  3786. found = 1;
  3787. break;
  3788. }
  3789. }
  3790. if (!found)
  3791. return 0;
  3792. if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
  3793. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  3794. DYNAMIC_TYPE_PUBLIC_KEY);
  3795. }
  3796. if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
  3797. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  3798. DYNAMIC_TYPE_PUBLIC_KEY);
  3799. }
  3800. ssl->buffers.serverDH_P.buffer = NULL;
  3801. ssl->buffers.serverDH_G.buffer = NULL;
  3802. ssl->buffers.weOwnDH = 0;
  3803. ssl->options.haveDH = 0;
  3804. ret = TLSX_PopulateSupportedGroups(ssl, &priority);
  3805. if (ret == WOLFSSL_SUCCESS) {
  3806. SupportedCurve* serverGroup;
  3807. ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS);
  3808. serverGroup = (SupportedCurve*)ext->data;
  3809. ret = tlsx_ffdhe_find_group(ssl, clientGroup, serverGroup);
  3810. }
  3811. TLSX_FreeAll(priority, ssl->heap);
  3812. return ret;
  3813. }
  3814. #endif /* HAVE_FFDHE && !WOLFSSL_NO_TLS12 */
  3815. #endif /* !NO_WOLFSSL_SERVER */
  3816. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3817. /* Return the preferred group.
  3818. *
  3819. * ssl SSL/TLS object.
  3820. * checkSupported Whether to check for the first supported group.
  3821. * returns BAD_FUNC_ARG if no group found, otherwise the group.
  3822. */
  3823. int TLSX_SupportedCurve_Preferred(WOLFSSL* ssl, int checkSupported)
  3824. {
  3825. TLSX* extension;
  3826. SupportedCurve* curve;
  3827. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3828. if (extension == NULL)
  3829. return BAD_FUNC_ARG;
  3830. curve = (SupportedCurve*)extension->data;
  3831. while (curve != NULL) {
  3832. if (!checkSupported || TLSX_KeyShare_IsSupported(curve->name))
  3833. return curve->name;
  3834. curve = curve->next;
  3835. }
  3836. return BAD_FUNC_ARG;
  3837. }
  3838. #endif /* HAVE_SUPPORTED_CURVES */
  3839. #ifndef NO_WOLFSSL_SERVER
  3840. static int TLSX_PointFormat_Parse(WOLFSSL* ssl, const byte* input,
  3841. word16 length, byte isRequest)
  3842. {
  3843. int ret;
  3844. /* validating formats list length */
  3845. if (ENUM_LEN > length || length != (word16)ENUM_LEN + input[0])
  3846. return BUFFER_ERROR;
  3847. if (isRequest) {
  3848. /* adding uncompressed point format to response */
  3849. ret = TLSX_UsePointFormat(&ssl->extensions, WOLFSSL_EC_PF_UNCOMPRESSED,
  3850. ssl->heap);
  3851. if (ret != WOLFSSL_SUCCESS)
  3852. return ret; /* throw error */
  3853. TLSX_SetResponse(ssl, TLSX_EC_POINT_FORMATS);
  3854. }
  3855. return 0;
  3856. }
  3857. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  3858. int TLSX_ValidateSupportedCurves(const WOLFSSL* ssl, byte first, byte second,
  3859. word32* ecdhCurveOID) {
  3860. TLSX* extension = NULL;
  3861. SupportedCurve* curve = NULL;
  3862. word32 oid = 0;
  3863. word32 defOid = 0;
  3864. word32 defSz = 80; /* Maximum known curve size is 66. */
  3865. word32 nextOid = 0;
  3866. word32 nextSz = 80; /* Maximum known curve size is 66. */
  3867. word32 currOid = ssl->ecdhCurveOID;
  3868. int ephmSuite = 0;
  3869. word16 octets = 0; /* according to 'ecc_set_type ecc_sets[];' */
  3870. int key = 0; /* validate key */
  3871. (void)oid;
  3872. if (first == CHACHA_BYTE) {
  3873. switch (second) {
  3874. case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
  3875. case TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3876. case TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3877. case TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256:
  3878. return 1; /* no suite restriction */
  3879. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
  3880. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256:
  3881. case TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3882. break;
  3883. }
  3884. }
  3885. if (first == ECC_BYTE || first == ECDHE_PSK_BYTE || first == CHACHA_BYTE)
  3886. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3887. if (!extension)
  3888. return 1; /* no suite restriction */
  3889. for (curve = (SupportedCurve*)extension->data;
  3890. curve && !key;
  3891. curve = curve->next) {
  3892. #ifdef OPENSSL_EXTRA
  3893. /* skip if name is not in supported ECC range
  3894. * or disabled by user */
  3895. if (curve->name > WOLFSSL_ECC_MAX ||
  3896. wolfSSL_curve_is_disabled(ssl, curve->name))
  3897. continue;
  3898. #endif
  3899. /* find supported curve */
  3900. switch (curve->name) {
  3901. #ifdef HAVE_ECC
  3902. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  3903. #ifndef NO_ECC_SECP
  3904. case WOLFSSL_ECC_SECP160R1:
  3905. oid = ECC_SECP160R1_OID;
  3906. octets = 20;
  3907. break;
  3908. #endif /* !NO_ECC_SECP */
  3909. #ifdef HAVE_ECC_SECPR2
  3910. case WOLFSSL_ECC_SECP160R2:
  3911. oid = ECC_SECP160R2_OID;
  3912. octets = 20;
  3913. break;
  3914. #endif /* HAVE_ECC_SECPR2 */
  3915. #ifdef HAVE_ECC_KOBLITZ
  3916. case WOLFSSL_ECC_SECP160K1:
  3917. oid = ECC_SECP160K1_OID;
  3918. octets = 20;
  3919. break;
  3920. #endif /* HAVE_ECC_KOBLITZ */
  3921. #endif
  3922. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  3923. #ifndef NO_ECC_SECP
  3924. case WOLFSSL_ECC_SECP192R1:
  3925. oid = ECC_SECP192R1_OID;
  3926. octets = 24;
  3927. break;
  3928. #endif /* !NO_ECC_SECP */
  3929. #ifdef HAVE_ECC_KOBLITZ
  3930. case WOLFSSL_ECC_SECP192K1:
  3931. oid = ECC_SECP192K1_OID;
  3932. octets = 24;
  3933. break;
  3934. #endif /* HAVE_ECC_KOBLITZ */
  3935. #endif
  3936. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  3937. #ifndef NO_ECC_SECP
  3938. case WOLFSSL_ECC_SECP224R1:
  3939. oid = ECC_SECP224R1_OID;
  3940. octets = 28;
  3941. break;
  3942. #endif /* !NO_ECC_SECP */
  3943. #ifdef HAVE_ECC_KOBLITZ
  3944. case WOLFSSL_ECC_SECP224K1:
  3945. oid = ECC_SECP224K1_OID;
  3946. octets = 28;
  3947. break;
  3948. #endif /* HAVE_ECC_KOBLITZ */
  3949. #endif
  3950. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  3951. #ifndef NO_ECC_SECP
  3952. case WOLFSSL_ECC_SECP256R1:
  3953. oid = ECC_SECP256R1_OID;
  3954. octets = 32;
  3955. break;
  3956. #endif /* !NO_ECC_SECP */
  3957. #endif /* !NO_ECC256 || HAVE_ALL_CURVES */
  3958. #endif
  3959. #if (defined(HAVE_CURVE25519) || defined(HAVE_ED25519)) && ECC_MIN_KEY_SZ <= 256
  3960. case WOLFSSL_ECC_X25519:
  3961. oid = ECC_X25519_OID;
  3962. octets = 32;
  3963. break;
  3964. #endif /* HAVE_CURVE25519 */
  3965. #ifdef HAVE_ECC
  3966. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  3967. #ifdef HAVE_ECC_KOBLITZ
  3968. case WOLFSSL_ECC_SECP256K1:
  3969. oid = ECC_SECP256K1_OID;
  3970. octets = 32;
  3971. break;
  3972. #endif /* HAVE_ECC_KOBLITZ */
  3973. #ifdef HAVE_ECC_BRAINPOOL
  3974. case WOLFSSL_ECC_BRAINPOOLP256R1:
  3975. oid = ECC_BRAINPOOLP256R1_OID;
  3976. octets = 32;
  3977. break;
  3978. #endif /* HAVE_ECC_BRAINPOOL */
  3979. #ifdef WOLFSSL_SM2
  3980. case WOLFSSL_ECC_SM2P256V1:
  3981. oid = ECC_SM2P256V1_OID;
  3982. octets = 32;
  3983. break;
  3984. #endif /* WOLFSSL_SM2 */
  3985. #endif
  3986. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  3987. #ifndef NO_ECC_SECP
  3988. case WOLFSSL_ECC_SECP384R1:
  3989. oid = ECC_SECP384R1_OID;
  3990. octets = 48;
  3991. break;
  3992. #endif /* !NO_ECC_SECP */
  3993. #ifdef HAVE_ECC_BRAINPOOL
  3994. case WOLFSSL_ECC_BRAINPOOLP384R1:
  3995. oid = ECC_BRAINPOOLP384R1_OID;
  3996. octets = 48;
  3997. break;
  3998. #endif /* HAVE_ECC_BRAINPOOL */
  3999. #endif
  4000. #endif
  4001. #if (defined(HAVE_CURVE448) || defined(HAVE_ED448)) && ECC_MIN_KEY_SZ <= 448
  4002. case WOLFSSL_ECC_X448:
  4003. oid = ECC_X448_OID;
  4004. octets = 57;
  4005. break;
  4006. #endif /* HAVE_CURVE448 */
  4007. #ifdef HAVE_ECC
  4008. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  4009. #ifdef HAVE_ECC_BRAINPOOL
  4010. case WOLFSSL_ECC_BRAINPOOLP512R1:
  4011. oid = ECC_BRAINPOOLP512R1_OID;
  4012. octets = 64;
  4013. break;
  4014. #endif /* HAVE_ECC_BRAINPOOL */
  4015. #endif
  4016. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  4017. #ifndef NO_ECC_SECP
  4018. case WOLFSSL_ECC_SECP521R1:
  4019. oid = ECC_SECP521R1_OID;
  4020. octets = 66;
  4021. break;
  4022. #endif /* !NO_ECC_SECP */
  4023. #endif
  4024. #endif
  4025. default: continue; /* unsupported curve */
  4026. }
  4027. #ifdef HAVE_ECC
  4028. /* Set default Oid */
  4029. if (defOid == 0 && ssl->eccTempKeySz <= octets && defSz > octets) {
  4030. defOid = oid;
  4031. defSz = octets;
  4032. }
  4033. /* The eccTempKeySz is the preferred ephemeral key size */
  4034. if (currOid == 0 && ssl->eccTempKeySz == octets)
  4035. currOid = oid;
  4036. if ((nextOid == 0 || nextSz > octets) && ssl->eccTempKeySz <= octets) {
  4037. nextOid = oid;
  4038. nextSz = octets;
  4039. }
  4040. #else
  4041. if (defOid == 0 && defSz > octets) {
  4042. defOid = oid;
  4043. defSz = octets;
  4044. }
  4045. if (currOid == 0)
  4046. currOid = oid;
  4047. if (nextOid == 0 || nextSz > octets) {
  4048. nextOid = oid;
  4049. nextSz = octets;
  4050. }
  4051. #endif
  4052. if (first == ECC_BYTE) {
  4053. switch (second) {
  4054. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  4055. /* ECDHE_ECDSA */
  4056. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
  4057. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
  4058. case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
  4059. case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
  4060. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
  4061. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
  4062. case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
  4063. case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
  4064. case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
  4065. case TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
  4066. key |= ssl->ecdhCurveOID == oid;
  4067. ephmSuite = 1;
  4068. break;
  4069. #ifdef WOLFSSL_STATIC_DH
  4070. /* ECDH_ECDSA */
  4071. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
  4072. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
  4073. case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
  4074. case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
  4075. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
  4076. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
  4077. case TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
  4078. case TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
  4079. if (oid == ECC_X25519_OID && defOid == oid) {
  4080. defOid = 0;
  4081. defSz = 80;
  4082. }
  4083. if (oid == ECC_X448_OID && defOid == oid) {
  4084. defOid = 0;
  4085. defSz = 80;
  4086. }
  4087. key |= ssl->pkCurveOID == oid;
  4088. break;
  4089. #endif /* WOLFSSL_STATIC_DH */
  4090. #endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  4091. #ifndef NO_RSA
  4092. /* ECDHE_RSA */
  4093. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
  4094. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
  4095. case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
  4096. case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
  4097. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
  4098. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
  4099. case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
  4100. case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
  4101. key |= ssl->ecdhCurveOID == oid;
  4102. ephmSuite = 1;
  4103. break;
  4104. #if defined(HAVE_ECC) && defined(WOLFSSL_STATIC_DH)
  4105. /* ECDH_RSA */
  4106. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
  4107. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
  4108. case TLS_ECDH_RSA_WITH_RC4_128_SHA:
  4109. case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
  4110. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
  4111. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
  4112. case TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
  4113. case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
  4114. if (oid == ECC_X25519_OID && defOid == oid) {
  4115. defOid = 0;
  4116. defSz = 80;
  4117. }
  4118. if (oid == ECC_X448_OID && defOid == oid) {
  4119. defOid = 0;
  4120. defSz = 80;
  4121. }
  4122. key |= ssl->pkCurveOID == oid;
  4123. break;
  4124. #endif /* HAVE_ECC && WOLFSSL_STATIC_DH */
  4125. #endif
  4126. default:
  4127. if (oid == ECC_X25519_OID && defOid == oid) {
  4128. defOid = 0;
  4129. defSz = 80;
  4130. }
  4131. if (oid == ECC_X448_OID && defOid == oid) {
  4132. defOid = 0;
  4133. defSz = 80;
  4134. }
  4135. key = 1;
  4136. break;
  4137. }
  4138. }
  4139. /* ChaCha20-Poly1305 ECC cipher suites */
  4140. if (first == CHACHA_BYTE) {
  4141. switch (second) {
  4142. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  4143. /* ECDHE_ECDSA */
  4144. case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 :
  4145. case TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  4146. key |= ssl->ecdhCurveOID == oid;
  4147. ephmSuite = 1;
  4148. break;
  4149. #endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  4150. #ifndef NO_RSA
  4151. /* ECDHE_RSA */
  4152. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 :
  4153. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  4154. key |= ssl->ecdhCurveOID == oid;
  4155. ephmSuite = 1;
  4156. break;
  4157. #endif
  4158. default:
  4159. key = 1;
  4160. break;
  4161. }
  4162. }
  4163. }
  4164. *ecdhCurveOID = ssl->ecdhCurveOID;
  4165. /* Choose the default if it is at the required strength. */
  4166. #ifdef HAVE_ECC
  4167. if (*ecdhCurveOID == 0 && defSz == ssl->eccTempKeySz)
  4168. #else
  4169. if (*ecdhCurveOID == 0)
  4170. #endif
  4171. {
  4172. key = 1;
  4173. *ecdhCurveOID = defOid;
  4174. }
  4175. /* Choose any curve at the required strength. */
  4176. if (*ecdhCurveOID == 0) {
  4177. key = 1;
  4178. *ecdhCurveOID = currOid;
  4179. }
  4180. /* Choose the default if it is at the next highest strength. */
  4181. if (*ecdhCurveOID == 0 && defSz == nextSz)
  4182. *ecdhCurveOID = defOid;
  4183. /* Choose any curve at the next highest strength. */
  4184. if (*ecdhCurveOID == 0)
  4185. *ecdhCurveOID = nextOid;
  4186. /* No curve and ephemeral ECC suite requires a matching curve. */
  4187. if (*ecdhCurveOID == 0 && ephmSuite)
  4188. key = 0;
  4189. return key;
  4190. }
  4191. #endif
  4192. #endif /* NO_WOLFSSL_SERVER */
  4193. int TLSX_SupportedCurve_Copy(TLSX* src, TLSX** dst, void* heap)
  4194. {
  4195. TLSX* extension;
  4196. int ret;
  4197. extension = TLSX_Find(src, TLSX_SUPPORTED_GROUPS);
  4198. if (extension != NULL) {
  4199. SupportedCurve* curve;
  4200. for (curve = (SupportedCurve*)extension->data; curve != NULL;
  4201. curve = curve->next) {
  4202. ret = TLSX_UseSupportedCurve(dst, curve->name, heap);
  4203. if (ret != WOLFSSL_SUCCESS)
  4204. return MEMORY_E;
  4205. }
  4206. }
  4207. return 0;
  4208. }
  4209. int TLSX_UseSupportedCurve(TLSX** extensions, word16 name, void* heap)
  4210. {
  4211. TLSX* extension = NULL;
  4212. SupportedCurve* curve = NULL;
  4213. int ret;
  4214. if (extensions == NULL) {
  4215. return BAD_FUNC_ARG;
  4216. }
  4217. #ifdef WOLFSSL_TLS13
  4218. if (! TLSX_KeyShare_IsSupported(name)) {
  4219. return BAD_FUNC_ARG;
  4220. }
  4221. #endif
  4222. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  4223. if (!extension) {
  4224. ret = TLSX_SupportedCurve_New(&curve, name, heap);
  4225. if (ret != 0)
  4226. return ret;
  4227. ret = TLSX_Push(extensions, TLSX_SUPPORTED_GROUPS, curve, heap);
  4228. if (ret != 0) {
  4229. XFREE(curve, heap, DYNAMIC_TYPE_TLSX);
  4230. return ret;
  4231. }
  4232. }
  4233. else {
  4234. ret = TLSX_SupportedCurve_Append((SupportedCurve*)extension->data, name,
  4235. heap);
  4236. if (ret != 0)
  4237. return ret;
  4238. }
  4239. return WOLFSSL_SUCCESS;
  4240. }
  4241. int TLSX_UsePointFormat(TLSX** extensions, byte format, void* heap)
  4242. {
  4243. TLSX* extension = NULL;
  4244. PointFormat* point = NULL;
  4245. int ret = 0;
  4246. if (extensions == NULL)
  4247. return BAD_FUNC_ARG;
  4248. extension = TLSX_Find(*extensions, TLSX_EC_POINT_FORMATS);
  4249. if (!extension) {
  4250. ret = TLSX_PointFormat_New(&point, format, heap);
  4251. if (ret != 0)
  4252. return ret;
  4253. ret = TLSX_Push(extensions, TLSX_EC_POINT_FORMATS, point, heap);
  4254. if (ret != 0) {
  4255. XFREE(point, heap, DYNAMIC_TYPE_TLSX);
  4256. return ret;
  4257. }
  4258. }
  4259. else {
  4260. ret = TLSX_PointFormat_Append((PointFormat*)extension->data, format,
  4261. heap);
  4262. if (ret != 0)
  4263. return ret;
  4264. }
  4265. return WOLFSSL_SUCCESS;
  4266. }
  4267. #define EC_FREE_ALL TLSX_SupportedCurve_FreeAll
  4268. #define EC_VALIDATE_REQUEST TLSX_SupportedCurve_ValidateRequest
  4269. #ifndef NO_WOLFSSL_CLIENT
  4270. #define EC_GET_SIZE TLSX_SupportedCurve_GetSize
  4271. #define EC_WRITE TLSX_SupportedCurve_Write
  4272. #else
  4273. #define EC_GET_SIZE(list) 0
  4274. #define EC_WRITE(a, b) 0
  4275. #endif
  4276. #if !defined(NO_WOLFSSL_SERVER) || (defined(WOLFSSL_TLS13) && \
  4277. !defined(WOLFSSL_NO_SERVER_GROUPS_EXT))
  4278. #define EC_PARSE TLSX_SupportedCurve_Parse
  4279. #else
  4280. #define EC_PARSE(a, b, c, d, e) 0
  4281. #endif
  4282. #define PF_FREE_ALL TLSX_PointFormat_FreeAll
  4283. #define PF_VALIDATE_REQUEST TLSX_PointFormat_ValidateRequest
  4284. #define PF_VALIDATE_RESPONSE TLSX_PointFormat_ValidateResponse
  4285. #define PF_GET_SIZE TLSX_PointFormat_GetSize
  4286. #define PF_WRITE TLSX_PointFormat_Write
  4287. #ifndef NO_WOLFSSL_SERVER
  4288. #define PF_PARSE TLSX_PointFormat_Parse
  4289. #else
  4290. #define PF_PARSE(a, b, c, d) 0
  4291. #endif
  4292. #else
  4293. #define EC_FREE_ALL(list, heap) WC_DO_NOTHING
  4294. #define EC_GET_SIZE(list) 0
  4295. #define EC_WRITE(a, b) 0
  4296. #define EC_PARSE(a, b, c, d, e) 0
  4297. #define EC_VALIDATE_REQUEST(a, b) WC_DO_NOTHING
  4298. #define PF_FREE_ALL(list, heap) WC_DO_NOTHING
  4299. #define PF_GET_SIZE(list) 0
  4300. #define PF_WRITE(a, b) 0
  4301. #define PF_PARSE(a, b, c, d) 0
  4302. #define PF_VALIDATE_REQUEST(a, b) WC_DO_NOTHING
  4303. #define PF_VALIDATE_RESPONSE(a, b) WC_DO_NOTHING
  4304. #endif /* HAVE_SUPPORTED_CURVES */
  4305. /******************************************************************************/
  4306. /* Renegotiation Indication */
  4307. /******************************************************************************/
  4308. #if defined(HAVE_SECURE_RENEGOTIATION) \
  4309. || defined(HAVE_SERVER_RENEGOTIATION_INFO)
  4310. static byte TLSX_SecureRenegotiation_GetSize(SecureRenegotiation* data,
  4311. int isRequest)
  4312. {
  4313. byte length = OPAQUE8_LEN; /* empty info length */
  4314. /* data will be NULL for HAVE_SERVER_RENEGOTIATION_INFO only */
  4315. if (data && data->enabled && data->verifySet) {
  4316. /* client sends client_verify_data only */
  4317. length += TLS_FINISHED_SZ;
  4318. /* server also sends server_verify_data */
  4319. if (!isRequest)
  4320. length += TLS_FINISHED_SZ;
  4321. }
  4322. return length;
  4323. }
  4324. static word16 TLSX_SecureRenegotiation_Write(SecureRenegotiation* data,
  4325. byte* output, int isRequest)
  4326. {
  4327. word16 offset = OPAQUE8_LEN; /* RenegotiationInfo length */
  4328. if (data && data->enabled && data->verifySet) {
  4329. /* client sends client_verify_data only */
  4330. XMEMCPY(output + offset, data->client_verify_data, TLS_FINISHED_SZ);
  4331. offset += TLS_FINISHED_SZ;
  4332. /* server also sends server_verify_data */
  4333. if (!isRequest) {
  4334. XMEMCPY(output + offset, data->server_verify_data, TLS_FINISHED_SZ);
  4335. offset += TLS_FINISHED_SZ;
  4336. }
  4337. }
  4338. output[0] = (byte)(offset - 1); /* info length - self */
  4339. return offset;
  4340. }
  4341. static int TLSX_SecureRenegotiation_Parse(WOLFSSL* ssl, const byte* input,
  4342. word16 length, byte isRequest)
  4343. {
  4344. int ret = SECURE_RENEGOTIATION_E;
  4345. if (length >= OPAQUE8_LEN) {
  4346. if (isRequest) {
  4347. #ifndef NO_WOLFSSL_SERVER
  4348. if (ssl->secure_renegotiation == NULL) {
  4349. ret = wolfSSL_UseSecureRenegotiation(ssl);
  4350. if (ret == WOLFSSL_SUCCESS)
  4351. ret = 0;
  4352. }
  4353. if (ret != 0 && ret != SECURE_RENEGOTIATION_E) {
  4354. }
  4355. else if (ssl->secure_renegotiation == NULL) {
  4356. }
  4357. else if (!ssl->secure_renegotiation->enabled) {
  4358. if (*input == 0) {
  4359. input++; /* get past size */
  4360. ssl->secure_renegotiation->enabled = 1;
  4361. TLSX_SetResponse(ssl, TLSX_RENEGOTIATION_INFO);
  4362. ret = 0;
  4363. }
  4364. else {
  4365. /* already in error state */
  4366. WOLFSSL_MSG("SCR client verify data present");
  4367. }
  4368. }
  4369. else if (*input == TLS_FINISHED_SZ) {
  4370. if (length < TLS_FINISHED_SZ + 1) {
  4371. WOLFSSL_MSG("SCR malformed buffer");
  4372. ret = BUFFER_E;
  4373. }
  4374. else {
  4375. input++; /* get past size */
  4376. /* validate client verify data */
  4377. if (XMEMCMP(input,
  4378. ssl->secure_renegotiation->client_verify_data,
  4379. TLS_FINISHED_SZ) == 0) {
  4380. WOLFSSL_MSG("SCR client verify data match");
  4381. TLSX_SetResponse(ssl, TLSX_RENEGOTIATION_INFO);
  4382. ret = 0; /* verified */
  4383. }
  4384. else {
  4385. /* already in error state */
  4386. WOLFSSL_MSG("SCR client verify data Failure");
  4387. }
  4388. }
  4389. }
  4390. #endif
  4391. }
  4392. else if (ssl->secure_renegotiation != NULL) {
  4393. #ifndef NO_WOLFSSL_CLIENT
  4394. if (!ssl->secure_renegotiation->enabled) {
  4395. if (*input == 0) {
  4396. ssl->secure_renegotiation->enabled = 1;
  4397. ret = 0;
  4398. }
  4399. }
  4400. else if (*input == 2 * TLS_FINISHED_SZ &&
  4401. length == 2 * TLS_FINISHED_SZ + OPAQUE8_LEN) {
  4402. input++; /* get past size */
  4403. /* validate client and server verify data */
  4404. if (XMEMCMP(input,
  4405. ssl->secure_renegotiation->client_verify_data,
  4406. TLS_FINISHED_SZ) == 0 &&
  4407. XMEMCMP(input + TLS_FINISHED_SZ,
  4408. ssl->secure_renegotiation->server_verify_data,
  4409. TLS_FINISHED_SZ) == 0) {
  4410. WOLFSSL_MSG("SCR client and server verify data match");
  4411. ret = 0; /* verified */
  4412. }
  4413. else {
  4414. /* already in error state */
  4415. WOLFSSL_MSG("SCR client and server verify data Failure");
  4416. }
  4417. }
  4418. #endif
  4419. }
  4420. }
  4421. if (ret != 0) {
  4422. WOLFSSL_ERROR_VERBOSE(ret);
  4423. SendAlert(ssl, alert_fatal, handshake_failure);
  4424. }
  4425. return ret;
  4426. }
  4427. int TLSX_UseSecureRenegotiation(TLSX** extensions, void* heap)
  4428. {
  4429. int ret = 0;
  4430. SecureRenegotiation* data;
  4431. data = (SecureRenegotiation*)XMALLOC(sizeof(SecureRenegotiation), heap,
  4432. DYNAMIC_TYPE_TLSX);
  4433. if (data == NULL)
  4434. return MEMORY_E;
  4435. XMEMSET(data, 0, sizeof(SecureRenegotiation));
  4436. ret = TLSX_Push(extensions, TLSX_RENEGOTIATION_INFO, data, heap);
  4437. if (ret != 0) {
  4438. XFREE(data, heap, DYNAMIC_TYPE_TLSX);
  4439. return ret;
  4440. }
  4441. return WOLFSSL_SUCCESS;
  4442. }
  4443. #ifdef HAVE_SERVER_RENEGOTIATION_INFO
  4444. int TLSX_AddEmptyRenegotiationInfo(TLSX** extensions, void* heap)
  4445. {
  4446. int ret;
  4447. /* send empty renegotiation_info extension */
  4448. TLSX* ext = TLSX_Find(*extensions, TLSX_RENEGOTIATION_INFO);
  4449. if (ext == NULL) {
  4450. ret = TLSX_UseSecureRenegotiation(extensions, heap);
  4451. if (ret != WOLFSSL_SUCCESS)
  4452. return ret;
  4453. ext = TLSX_Find(*extensions, TLSX_RENEGOTIATION_INFO);
  4454. }
  4455. if (ext)
  4456. ext->resp = 1;
  4457. return WOLFSSL_SUCCESS;
  4458. }
  4459. #endif /* HAVE_SERVER_RENEGOTIATION_INFO */
  4460. #define SCR_FREE_ALL(data, heap) XFREE(data, (heap), DYNAMIC_TYPE_TLSX)
  4461. #define SCR_GET_SIZE TLSX_SecureRenegotiation_GetSize
  4462. #define SCR_WRITE TLSX_SecureRenegotiation_Write
  4463. #define SCR_PARSE TLSX_SecureRenegotiation_Parse
  4464. #else
  4465. #define SCR_FREE_ALL(a, heap) WC_DO_NOTHING
  4466. #define SCR_GET_SIZE(a, b) 0
  4467. #define SCR_WRITE(a, b, c) 0
  4468. #define SCR_PARSE(a, b, c, d) 0
  4469. #endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
  4470. /******************************************************************************/
  4471. /* Session Tickets */
  4472. /******************************************************************************/
  4473. #ifdef HAVE_SESSION_TICKET
  4474. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  4475. static void TLSX_SessionTicket_ValidateRequest(WOLFSSL* ssl)
  4476. {
  4477. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_SESSION_TICKET);
  4478. SessionTicket* ticket = extension ?
  4479. (SessionTicket*)extension->data : NULL;
  4480. if (ticket) {
  4481. /* TODO validate ticket timeout here! */
  4482. if (ticket->lifetime == 0xfffffff) {
  4483. /* send empty ticket on timeout */
  4484. TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4485. }
  4486. }
  4487. }
  4488. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  4489. static word16 TLSX_SessionTicket_GetSize(SessionTicket* ticket, int isRequest)
  4490. {
  4491. (void)isRequest;
  4492. return ticket ? ticket->size : 0;
  4493. }
  4494. static word16 TLSX_SessionTicket_Write(SessionTicket* ticket, byte* output,
  4495. int isRequest)
  4496. {
  4497. word16 offset = 0; /* empty ticket */
  4498. if (isRequest && ticket) {
  4499. XMEMCPY(output + offset, ticket->data, ticket->size);
  4500. offset += ticket->size;
  4501. }
  4502. return offset;
  4503. }
  4504. static int TLSX_SessionTicket_Parse(WOLFSSL* ssl, const byte* input,
  4505. word16 length, byte isRequest)
  4506. {
  4507. int ret = 0;
  4508. (void) input; /* avoid unused parameter if NO_WOLFSSL_SERVER defined */
  4509. if (!isRequest) {
  4510. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_SESSION_TICKET))
  4511. return TLSX_HandleUnsupportedExtension(ssl);
  4512. if (length != 0)
  4513. return BUFFER_ERROR;
  4514. #ifndef NO_WOLFSSL_CLIENT
  4515. ssl->expect_session_ticket = 1;
  4516. #endif
  4517. }
  4518. #ifndef NO_WOLFSSL_SERVER
  4519. else {
  4520. /* server side */
  4521. if (ssl->ctx->ticketEncCb == NULL) {
  4522. WOLFSSL_MSG("Client sent session ticket, server has no callback");
  4523. return 0;
  4524. }
  4525. #ifdef HAVE_SECURE_RENEGOTIATION
  4526. if (IsSCR(ssl)) {
  4527. WOLFSSL_MSG("Client sent session ticket during SCR. Ignoring.");
  4528. return 0;
  4529. }
  4530. #endif
  4531. if (length > SESSION_TICKET_LEN) {
  4532. ret = BAD_TICKET_MSG_SZ;
  4533. WOLFSSL_ERROR_VERBOSE(ret);
  4534. } else if (IsAtLeastTLSv1_3(ssl->version)) {
  4535. WOLFSSL_MSG("Process client ticket rejected, TLS 1.3 no support");
  4536. ssl->options.rejectTicket = 1;
  4537. ret = 0; /* not fatal */
  4538. } else if (ssl->options.noTicketTls12) {
  4539. /* ignore ticket request */
  4540. } else if (length == 0) {
  4541. /* blank ticket */
  4542. ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4543. if (ret == WOLFSSL_SUCCESS) {
  4544. ret = 0;
  4545. /* send blank ticket */
  4546. TLSX_SetResponse(ssl, TLSX_SESSION_TICKET);
  4547. ssl->options.createTicket = 1; /* will send ticket msg */
  4548. ssl->options.useTicket = 1;
  4549. ssl->options.resuming = 0; /* no standard resumption */
  4550. ssl->arrays->sessionIDSz = 0; /* no echo on blank ticket */
  4551. }
  4552. } else {
  4553. /* got actual ticket from client */
  4554. ret = DoClientTicket(ssl, input, length);
  4555. if (ret == WOLFSSL_TICKET_RET_OK) { /* use ticket to resume */
  4556. WOLFSSL_MSG("Using existing client ticket");
  4557. ssl->options.useTicket = 1;
  4558. ssl->options.resuming = 1;
  4559. /* SERVER: ticket is peer auth. */
  4560. ssl->options.peerAuthGood = 1;
  4561. } else if (ret == WOLFSSL_TICKET_RET_CREATE) {
  4562. WOLFSSL_MSG("Using existing client ticket, creating new one");
  4563. ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4564. if (ret == WOLFSSL_SUCCESS) {
  4565. ret = 0;
  4566. TLSX_SetResponse(ssl, TLSX_SESSION_TICKET);
  4567. /* send blank ticket */
  4568. ssl->options.createTicket = 1; /* will send ticket msg */
  4569. ssl->options.useTicket = 1;
  4570. ssl->options.resuming = 1;
  4571. /* SERVER: ticket is peer auth. */
  4572. ssl->options.peerAuthGood = 1;
  4573. }
  4574. } else if (ret == WOLFSSL_TICKET_RET_REJECT) {
  4575. WOLFSSL_MSG("Process client ticket rejected, not using");
  4576. ssl->options.rejectTicket = 1;
  4577. ret = 0; /* not fatal */
  4578. } else if (ret == VERSION_ERROR) {
  4579. WOLFSSL_MSG("Process client ticket rejected, bad TLS version");
  4580. ssl->options.rejectTicket = 1;
  4581. ret = 0; /* not fatal */
  4582. } else if (ret == WOLFSSL_TICKET_RET_FATAL) {
  4583. WOLFSSL_MSG("Process client ticket fatal error, not using");
  4584. } else if (ret < 0) {
  4585. WOLFSSL_MSG("Process client ticket unknown error, not using");
  4586. }
  4587. }
  4588. }
  4589. #endif /* NO_WOLFSSL_SERVER */
  4590. #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER)
  4591. (void)ssl;
  4592. #endif
  4593. return ret;
  4594. }
  4595. WOLFSSL_LOCAL SessionTicket* TLSX_SessionTicket_Create(word32 lifetime,
  4596. byte* data, word16 size, void* heap)
  4597. {
  4598. SessionTicket* ticket = (SessionTicket*)XMALLOC(sizeof(SessionTicket),
  4599. heap, DYNAMIC_TYPE_TLSX);
  4600. if (ticket) {
  4601. ticket->data = (byte*)XMALLOC(size, heap, DYNAMIC_TYPE_TLSX);
  4602. if (ticket->data == NULL) {
  4603. XFREE(ticket, heap, DYNAMIC_TYPE_TLSX);
  4604. return NULL;
  4605. }
  4606. XMEMCPY(ticket->data, data, size);
  4607. ticket->size = size;
  4608. ticket->lifetime = lifetime;
  4609. }
  4610. (void)heap;
  4611. return ticket;
  4612. }
  4613. WOLFSSL_LOCAL void TLSX_SessionTicket_Free(SessionTicket* ticket, void* heap)
  4614. {
  4615. if (ticket) {
  4616. XFREE(ticket->data, heap, DYNAMIC_TYPE_TLSX);
  4617. XFREE(ticket, heap, DYNAMIC_TYPE_TLSX);
  4618. }
  4619. (void)heap;
  4620. }
  4621. int TLSX_UseSessionTicket(TLSX** extensions, SessionTicket* ticket, void* heap)
  4622. {
  4623. int ret = 0;
  4624. if (extensions == NULL)
  4625. return BAD_FUNC_ARG;
  4626. /* If the ticket is NULL, the client will request a new ticket from the
  4627. server. Otherwise, the client will use it in the next client hello. */
  4628. if ((ret = TLSX_Push(extensions, TLSX_SESSION_TICKET, (void*)ticket, heap))
  4629. != 0)
  4630. return ret;
  4631. return WOLFSSL_SUCCESS;
  4632. }
  4633. #define WOLF_STK_VALIDATE_REQUEST TLSX_SessionTicket_ValidateRequest
  4634. #define WOLF_STK_GET_SIZE TLSX_SessionTicket_GetSize
  4635. #define WOLF_STK_WRITE TLSX_SessionTicket_Write
  4636. #define WOLF_STK_PARSE TLSX_SessionTicket_Parse
  4637. #define WOLF_STK_FREE(stk, heap) TLSX_SessionTicket_Free((SessionTicket*)(stk),(heap))
  4638. #else
  4639. #define WOLF_STK_FREE(a, b) WC_DO_NOTHING
  4640. #define WOLF_STK_VALIDATE_REQUEST(a) WC_DO_NOTHING
  4641. #define WOLF_STK_GET_SIZE(a, b) 0
  4642. #define WOLF_STK_WRITE(a, b, c) 0
  4643. #define WOLF_STK_PARSE(a, b, c, d) 0
  4644. #endif /* HAVE_SESSION_TICKET */
  4645. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  4646. /******************************************************************************/
  4647. /* Encrypt-then-MAC */
  4648. /******************************************************************************/
  4649. #ifndef WOLFSSL_NO_TLS12
  4650. static int TLSX_EncryptThenMac_Use(WOLFSSL* ssl);
  4651. /**
  4652. * Get the size of the Encrypt-Then-MAC extension.
  4653. *
  4654. * msgType Type of message to put extension into.
  4655. * pSz Size of extension data.
  4656. * return SANITY_MSG_E when the message is not allowed to have extension and
  4657. * 0 otherwise.
  4658. */
  4659. static int TLSX_EncryptThenMac_GetSize(byte msgType, word16* pSz)
  4660. {
  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. * Write the Encrypt-Then-MAC extension.
  4671. *
  4672. * data Unused
  4673. * output Extension data buffer. Unused.
  4674. * msgType Type of message to put extension into.
  4675. * pSz Size of extension data.
  4676. * return SANITY_MSG_E when the message is not allowed to have extension and
  4677. * 0 otherwise.
  4678. */
  4679. static int TLSX_EncryptThenMac_Write(void* data, byte* output, byte msgType,
  4680. word16* pSz)
  4681. {
  4682. (void)data;
  4683. (void)output;
  4684. (void)pSz;
  4685. if (msgType != client_hello && msgType != server_hello) {
  4686. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4687. return SANITY_MSG_E;
  4688. }
  4689. /* Empty extension */
  4690. return 0;
  4691. }
  4692. /**
  4693. * Parse the Encrypt-Then-MAC extension.
  4694. *
  4695. * ssl SSL object
  4696. * input Extension data buffer.
  4697. * length Length of this extension's data.
  4698. * msgType Type of message to extension appeared in.
  4699. * return SANITY_MSG_E when the message is not allowed to have extension,
  4700. * BUFFER_ERROR when the extension's data is invalid,
  4701. * MEMORY_E when unable to allocate memory and
  4702. * 0 otherwise.
  4703. */
  4704. static int TLSX_EncryptThenMac_Parse(WOLFSSL* ssl, const byte* input,
  4705. word16 length, byte msgType)
  4706. {
  4707. int ret;
  4708. (void)input;
  4709. if (msgType != client_hello && msgType != server_hello) {
  4710. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4711. return SANITY_MSG_E;
  4712. }
  4713. /* Empty extension */
  4714. if (length != 0)
  4715. return BUFFER_ERROR;
  4716. if (msgType == client_hello) {
  4717. /* Check the user hasn't disallowed use of Encrypt-Then-Mac. */
  4718. if (!ssl->options.disallowEncThenMac) {
  4719. ssl->options.encThenMac = 1;
  4720. /* Set the extension reply. */
  4721. ret = TLSX_EncryptThenMac_Use(ssl);
  4722. if (ret != 0)
  4723. return ret;
  4724. }
  4725. return 0;
  4726. }
  4727. /* Server Hello */
  4728. if (ssl->options.disallowEncThenMac) {
  4729. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4730. return SANITY_MSG_E;
  4731. }
  4732. ssl->options.encThenMac = 1;
  4733. return 0;
  4734. }
  4735. /**
  4736. * Add the Encrypt-Then-MAC extension to list.
  4737. *
  4738. * ssl SSL object
  4739. * return MEMORY_E when unable to allocate memory and 0 otherwise.
  4740. */
  4741. static int TLSX_EncryptThenMac_Use(WOLFSSL* ssl)
  4742. {
  4743. int ret = 0;
  4744. TLSX* extension;
  4745. /* Find the Encrypt-Then-Mac extension if it exists. */
  4746. extension = TLSX_Find(ssl->extensions, TLSX_ENCRYPT_THEN_MAC);
  4747. if (extension == NULL) {
  4748. /* Push new Encrypt-Then-Mac extension. */
  4749. ret = TLSX_Push(&ssl->extensions, TLSX_ENCRYPT_THEN_MAC, NULL,
  4750. ssl->heap);
  4751. if (ret != 0)
  4752. return ret;
  4753. }
  4754. return 0;
  4755. }
  4756. /**
  4757. * Set the Encrypt-Then-MAC extension as one to respond too.
  4758. *
  4759. * ssl SSL object
  4760. * return EXT_MISSING when EncryptThenMac extension not in list.
  4761. */
  4762. int TLSX_EncryptThenMac_Respond(WOLFSSL* ssl)
  4763. {
  4764. TLSX* extension;
  4765. extension = TLSX_Find(ssl->extensions, TLSX_ENCRYPT_THEN_MAC);
  4766. if (extension == NULL)
  4767. return EXT_MISSING;
  4768. extension->resp = 1;
  4769. return 0;
  4770. }
  4771. #define ETM_GET_SIZE TLSX_EncryptThenMac_GetSize
  4772. #define ETM_WRITE TLSX_EncryptThenMac_Write
  4773. #define ETM_PARSE TLSX_EncryptThenMac_Parse
  4774. #else
  4775. #define ETM_GET_SIZE(a, b) 0
  4776. #define ETM_WRITE(a, b, c, d) 0
  4777. #define ETM_PARSE(a, b, c, d) 0
  4778. #endif /* !WOLFSSL_NO_TLS12 */
  4779. #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */
  4780. #ifdef WOLFSSL_SRTP
  4781. /******************************************************************************/
  4782. /* DTLS SRTP (Secure Real-time Transport Protocol) */
  4783. /******************************************************************************/
  4784. /* Only support single SRTP profile */
  4785. typedef struct TlsxSrtp {
  4786. word16 profileCount;
  4787. word16 ids; /* selected bits */
  4788. } TlsxSrtp;
  4789. static int TLSX_UseSRTP_GetSize(TlsxSrtp *srtp)
  4790. {
  4791. /* SRTP Profile Len (2)
  4792. * SRTP Profiles (2)
  4793. * MKI (master key id) Length */
  4794. return (OPAQUE16_LEN + (srtp->profileCount * OPAQUE16_LEN) + 1);
  4795. }
  4796. static TlsxSrtp* TLSX_UseSRTP_New(word16 ids, void* heap)
  4797. {
  4798. TlsxSrtp* srtp;
  4799. int i;
  4800. srtp = (TlsxSrtp*)XMALLOC(sizeof(TlsxSrtp), heap, DYNAMIC_TYPE_TLSX);
  4801. if (srtp == NULL) {
  4802. WOLFSSL_MSG("TLSX SRTP Memory failure");
  4803. return NULL;
  4804. }
  4805. /* count and test each bit set */
  4806. srtp->profileCount = 0;
  4807. for (i=0; i<16; i++) {
  4808. if (ids & (1 << i)) {
  4809. srtp->profileCount++;
  4810. }
  4811. }
  4812. srtp->ids = ids;
  4813. return srtp;
  4814. }
  4815. static void TLSX_UseSRTP_Free(TlsxSrtp *srtp, void* heap)
  4816. {
  4817. if (srtp != NULL) {
  4818. XFREE(srtp, heap, DYNAMIC_TYPE_TLSX);
  4819. }
  4820. (void)heap;
  4821. }
  4822. static int TLSX_UseSRTP_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  4823. byte isRequest)
  4824. {
  4825. int ret = BAD_FUNC_ARG;
  4826. word16 profile_len = 0;
  4827. word16 profile_value = 0;
  4828. word16 offset = 0;
  4829. #ifndef NO_WOLFSSL_SERVER
  4830. int i;
  4831. TlsxSrtp* srtp = NULL;
  4832. #endif
  4833. if (length < OPAQUE16_LEN) {
  4834. return BUFFER_ERROR;
  4835. }
  4836. /* reset selected DTLS SRTP profile ID */
  4837. ssl->dtlsSrtpId = 0;
  4838. /* total length, not include itself */
  4839. ato16(input, &profile_len);
  4840. offset += OPAQUE16_LEN;
  4841. if (!isRequest) {
  4842. #ifndef NO_WOLFSSL_CLIENT
  4843. if (length < offset + OPAQUE16_LEN)
  4844. return BUFFER_ERROR;
  4845. ato16(input + offset, &profile_value);
  4846. /* check that the profile received was in the ones we support */
  4847. if (profile_value < 16 &&
  4848. (ssl->dtlsSrtpProfiles & (1 << profile_value))) {
  4849. ssl->dtlsSrtpId = profile_value;
  4850. ret = 0; /* success */
  4851. }
  4852. #endif
  4853. }
  4854. #ifndef NO_WOLFSSL_SERVER
  4855. else {
  4856. /* parse remainder one profile at a time, looking for match in CTX */
  4857. ret = 0;
  4858. for (i=offset; i<length; i+=OPAQUE16_LEN) {
  4859. ato16(input+i, &profile_value);
  4860. /* find first match */
  4861. if (profile_value < 16 &&
  4862. ssl->dtlsSrtpProfiles & (1 << profile_value)) {
  4863. ssl->dtlsSrtpId = profile_value;
  4864. /* make sure we respond with selected SRTP id selected */
  4865. srtp = TLSX_UseSRTP_New((1 << profile_value), ssl->heap);
  4866. if (srtp != NULL) {
  4867. ret = TLSX_Push(&ssl->extensions, TLSX_USE_SRTP,
  4868. (void*)srtp, ssl->heap);
  4869. if (ret == 0) {
  4870. TLSX_SetResponse(ssl, TLSX_USE_SRTP);
  4871. /* successfully set extension */
  4872. }
  4873. }
  4874. else {
  4875. ret = MEMORY_E;
  4876. }
  4877. break;
  4878. }
  4879. }
  4880. }
  4881. if (ret == 0 && ssl->dtlsSrtpId == 0) {
  4882. WOLFSSL_MSG("TLSX_UseSRTP_Parse profile not found!");
  4883. /* not fatal */
  4884. }
  4885. else if (ret != 0) {
  4886. ssl->dtlsSrtpId = 0;
  4887. TLSX_UseSRTP_Free(srtp, ssl->heap);
  4888. }
  4889. #endif
  4890. (void)profile_len;
  4891. return ret;
  4892. }
  4893. static word16 TLSX_UseSRTP_Write(TlsxSrtp* srtp, byte* output)
  4894. {
  4895. word16 offset = 0;
  4896. int i, j;
  4897. c16toa(srtp->profileCount * 2, output + offset);
  4898. offset += OPAQUE16_LEN;
  4899. j = 0;
  4900. for (i = 0; i < srtp->profileCount; i++) {
  4901. for (; j < 16; j++) {
  4902. if (srtp->ids & (1 << j)) {
  4903. c16toa(j, output + offset);
  4904. offset += OPAQUE16_LEN;
  4905. }
  4906. }
  4907. }
  4908. output[offset++] = 0x00; /* MKI Length */
  4909. return offset;
  4910. }
  4911. static int TLSX_UseSRTP(TLSX** extensions, word16 profiles, void* heap)
  4912. {
  4913. int ret = 0;
  4914. TLSX* extension;
  4915. if (extensions == NULL) {
  4916. return BAD_FUNC_ARG;
  4917. }
  4918. extension = TLSX_Find(*extensions, TLSX_USE_SRTP);
  4919. if (extension == NULL) {
  4920. TlsxSrtp* srtp = TLSX_UseSRTP_New(profiles, heap);
  4921. if (srtp == NULL) {
  4922. return MEMORY_E;
  4923. }
  4924. ret = TLSX_Push(extensions, TLSX_USE_SRTP, (void*)srtp, heap);
  4925. if (ret != 0) {
  4926. TLSX_UseSRTP_Free(srtp, heap);
  4927. }
  4928. }
  4929. return ret;
  4930. }
  4931. #ifndef NO_WOLFSSL_SERVER
  4932. #define SRTP_FREE TLSX_UseSRTP_Free
  4933. #define SRTP_PARSE TLSX_UseSRTP_Parse
  4934. #define SRTP_WRITE TLSX_UseSRTP_Write
  4935. #define SRTP_GET_SIZE TLSX_UseSRTP_GetSize
  4936. #else
  4937. #define SRTP_FREE(a, b) WC_DO_NOTHING
  4938. #define SRTP_PARSE(a, b, c, d) 0
  4939. #define SRTP_WRITE(a, b) 0
  4940. #define SRTP_GET_SIZE(a) 0
  4941. #endif
  4942. #endif /* WOLFSSL_SRTP */
  4943. /******************************************************************************/
  4944. /* Supported Versions */
  4945. /******************************************************************************/
  4946. #ifdef WOLFSSL_TLS13
  4947. static WC_INLINE int versionIsGreater(byte isDtls, byte a, byte b)
  4948. {
  4949. (void)isDtls;
  4950. #ifdef WOLFSSL_DTLS
  4951. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4952. if (isDtls)
  4953. return a < b;
  4954. #endif /* WOLFSSL_DTLS */
  4955. return a > b;
  4956. }
  4957. static WC_INLINE int versionIsLesser(byte isDtls, byte a, byte b)
  4958. {
  4959. (void)isDtls;
  4960. #ifdef WOLFSSL_DTLS
  4961. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4962. if (isDtls)
  4963. return a > b;
  4964. #endif /* WOLFSSL_DTLS */
  4965. return a < b;
  4966. }
  4967. static WC_INLINE int versionIsAtLeast(byte isDtls, byte a, byte b)
  4968. {
  4969. (void)isDtls;
  4970. #ifdef WOLFSSL_DTLS
  4971. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4972. if (isDtls)
  4973. return a <= b;
  4974. #endif /* WOLFSSL_DTLS */
  4975. return a >= b;
  4976. }
  4977. static WC_INLINE int versionIsLessEqual(byte isDtls, byte a, byte b)
  4978. {
  4979. (void)isDtls;
  4980. #ifdef WOLFSSL_DTLS
  4981. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4982. if (isDtls)
  4983. return a >= b;
  4984. #endif /* WOLFSSL_DTLS */
  4985. return a <= b;
  4986. }
  4987. /* Return the size of the SupportedVersions extension's data.
  4988. *
  4989. * data The SSL/TLS object.
  4990. * msgType The type of the message this extension is being written into.
  4991. * returns the length of data that will be in the extension.
  4992. */
  4993. static int TLSX_SupportedVersions_GetSize(void* data, byte msgType, word16* pSz)
  4994. {
  4995. WOLFSSL* ssl = (WOLFSSL*)data;
  4996. byte tls13Minor, tls12Minor, tls11Minor, isDtls;
  4997. isDtls = !!ssl->options.dtls;
  4998. tls13Minor = (byte)(isDtls ? DTLSv1_3_MINOR : TLSv1_3_MINOR);
  4999. tls12Minor = (byte)(isDtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR);
  5000. tls11Minor = (byte)(isDtls ? DTLS_MINOR : TLSv1_1_MINOR);
  5001. /* unused on some configuration */
  5002. (void)tls12Minor;
  5003. (void)tls13Minor;
  5004. (void)tls11Minor;
  5005. if (msgType == client_hello) {
  5006. /* TLS v1.2 and TLS v1.3 */
  5007. int cnt = 0;
  5008. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13Minor)
  5009. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5010. defined(WOLFSSL_WPAS_SMALL)
  5011. && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0
  5012. #endif
  5013. ) {
  5014. cnt++;
  5015. }
  5016. if (ssl->options.downgrade) {
  5017. #ifndef WOLFSSL_NO_TLS12
  5018. if (versionIsLessEqual(
  5019. isDtls, ssl->options.minDowngrade, tls12Minor)
  5020. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5021. defined(WOLFSSL_WPAS_SMALL)
  5022. && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0
  5023. #endif
  5024. ) {
  5025. cnt++;
  5026. }
  5027. #endif
  5028. #ifndef NO_OLD_TLS
  5029. if (versionIsLessEqual(
  5030. isDtls, ssl->options.minDowngrade, tls11Minor)
  5031. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5032. defined(WOLFSSL_WPAS_SMALL)
  5033. && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0
  5034. #endif
  5035. ) {
  5036. cnt++;
  5037. }
  5038. #ifdef WOLFSSL_ALLOW_TLSV10
  5039. if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR)
  5040. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5041. defined(WOLFSSL_WPAS_SMALL)
  5042. && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0
  5043. #endif
  5044. ) {
  5045. cnt++;
  5046. }
  5047. #endif
  5048. #endif
  5049. }
  5050. *pSz += (word16)(OPAQUE8_LEN + cnt * OPAQUE16_LEN);
  5051. }
  5052. else if (msgType == server_hello || msgType == hello_retry_request) {
  5053. *pSz += OPAQUE16_LEN;
  5054. }
  5055. else {
  5056. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5057. return SANITY_MSG_E;
  5058. }
  5059. return 0;
  5060. }
  5061. /* Writes the SupportedVersions extension into the buffer.
  5062. *
  5063. * data The SSL/TLS object.
  5064. * output The buffer to write the extension into.
  5065. * msgType The type of the message this extension is being written into.
  5066. * returns the length of data that was written.
  5067. */
  5068. static int TLSX_SupportedVersions_Write(void* data, byte* output,
  5069. byte msgType, word16* pSz)
  5070. {
  5071. WOLFSSL* ssl = (WOLFSSL*)data;
  5072. byte tls13minor, tls12minor, tls11minor, isDtls = 0;
  5073. tls13minor = (byte)TLSv1_3_MINOR;
  5074. tls12minor = (byte)TLSv1_2_MINOR;
  5075. tls11minor = (byte)TLSv1_1_MINOR;
  5076. /* unused in some configuration */
  5077. (void)tls11minor;
  5078. (void)tls12minor;
  5079. #ifdef WOLFSSL_DTLS13
  5080. if (ssl->options.dtls) {
  5081. tls13minor = (byte)DTLSv1_3_MINOR;
  5082. tls12minor = (byte)DTLSv1_2_MINOR;
  5083. tls11minor = (byte)DTLS_MINOR;
  5084. isDtls = 1;
  5085. }
  5086. #endif /* WOLFSSL_DTLS13 */
  5087. if (msgType == client_hello) {
  5088. byte major = ssl->ctx->method->version.major;
  5089. byte* cnt = output++;
  5090. *cnt = 0;
  5091. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13minor)
  5092. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5093. defined(WOLFSSL_WPAS_SMALL)
  5094. && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0
  5095. #endif
  5096. ) {
  5097. *cnt += OPAQUE16_LEN;
  5098. #ifdef WOLFSSL_TLS13_DRAFT
  5099. /* The TLS draft major number. */
  5100. *(output++) = TLS_DRAFT_MAJOR;
  5101. /* Version of draft supported. */
  5102. *(output++) = TLS_DRAFT_MINOR;
  5103. #else
  5104. *(output++) = major;
  5105. *(output++) = tls13minor;
  5106. #endif
  5107. }
  5108. if (ssl->options.downgrade) {
  5109. #ifndef WOLFSSL_NO_TLS12
  5110. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls12minor)
  5111. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5112. defined(WOLFSSL_WPAS_SMALL)
  5113. && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0
  5114. #endif
  5115. ) {
  5116. *cnt += OPAQUE16_LEN;
  5117. *(output++) = major;
  5118. *(output++) = tls12minor;
  5119. }
  5120. #endif
  5121. #ifndef NO_OLD_TLS
  5122. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls11minor)
  5123. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5124. defined(WOLFSSL_WPAS_SMALL)
  5125. && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0
  5126. #endif
  5127. ) {
  5128. *cnt += OPAQUE16_LEN;
  5129. *(output++) = major;
  5130. *(output++) = tls11minor;
  5131. }
  5132. #ifdef WOLFSSL_ALLOW_TLSV10
  5133. if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR)
  5134. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5135. defined(WOLFSSL_WPAS_SMALL)
  5136. && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0
  5137. #endif
  5138. ) {
  5139. *cnt += OPAQUE16_LEN;
  5140. *(output++) = major;
  5141. *(output++) = (byte)TLSv1_MINOR;
  5142. }
  5143. #endif
  5144. #endif
  5145. }
  5146. *pSz += (word16)(OPAQUE8_LEN + *cnt);
  5147. }
  5148. else if (msgType == server_hello || msgType == hello_retry_request) {
  5149. output[0] = ssl->version.major;
  5150. output[1] = ssl->version.minor;
  5151. *pSz += OPAQUE16_LEN;
  5152. }
  5153. else {
  5154. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5155. return SANITY_MSG_E;
  5156. }
  5157. return 0;
  5158. }
  5159. /* Parse the SupportedVersions extension.
  5160. *
  5161. * ssl The SSL/TLS object.
  5162. * input The buffer with the extension data.
  5163. * length The length of the extension data.
  5164. * msgType The type of the message this extension is being parsed from.
  5165. * pv The output ProtocolVersion for the negotiated version
  5166. * opts The output options structure. Can be NULL.
  5167. * exts The output extensions list. Can be NULL.
  5168. * returns 0 on success, otherwise failure.
  5169. */
  5170. int TLSX_SupportedVersions_Parse(const WOLFSSL* ssl, const byte* input,
  5171. word16 length, byte msgType, ProtocolVersion* pv, Options* opts,
  5172. TLSX** exts)
  5173. {
  5174. /* The client's greatest minor version that we support */
  5175. byte clientGreatestMinor = SSLv3_MINOR;
  5176. int ret;
  5177. byte major, minor;
  5178. byte tls13minor, tls12minor;
  5179. byte isDtls;
  5180. tls13minor = TLSv1_3_MINOR;
  5181. tls12minor = TLSv1_2_MINOR;
  5182. isDtls = ssl->options.dtls == 1;
  5183. #ifdef WOLFSSL_DTLS13
  5184. if (ssl->options.dtls) {
  5185. tls13minor = DTLSv1_3_MINOR;
  5186. tls12minor = DTLSv1_2_MINOR;
  5187. clientGreatestMinor = DTLS_MINOR;
  5188. }
  5189. #endif /* WOLFSSL_DTLS13 */
  5190. if (msgType == client_hello) {
  5191. int i;
  5192. int len;
  5193. int set = 0;
  5194. /* Must contain a length and at least one version. */
  5195. if (length < OPAQUE8_LEN + OPAQUE16_LEN || (length & 1) != 1)
  5196. return BUFFER_ERROR;
  5197. len = *input;
  5198. /* Protocol version array must fill rest of data. */
  5199. if (length != (word16)OPAQUE8_LEN + len)
  5200. return BUFFER_ERROR;
  5201. input++;
  5202. /* Find first match. */
  5203. for (i = 0; i < len; i += OPAQUE16_LEN) {
  5204. major = input[i];
  5205. minor = input[i + OPAQUE8_LEN];
  5206. #ifdef WOLFSSL_TLS13_DRAFT
  5207. if (major == TLS_DRAFT_MAJOR && minor == TLS_DRAFT_MINOR) {
  5208. major = SSLv3_MAJOR;
  5209. minor = TLSv1_3_MINOR;
  5210. }
  5211. #else
  5212. if (major == TLS_DRAFT_MAJOR)
  5213. continue;
  5214. #endif
  5215. if (major != ssl->ctx->method->version.major)
  5216. continue;
  5217. /* No upgrade allowed. */
  5218. if (versionIsGreater(isDtls, minor, ssl->version.minor))
  5219. continue;
  5220. /* Check downgrade. */
  5221. if (versionIsLesser(isDtls, minor, ssl->version.minor)) {
  5222. if (!ssl->options.downgrade)
  5223. continue;
  5224. if (versionIsLesser(isDtls, minor, ssl->options.minDowngrade))
  5225. continue;
  5226. }
  5227. if (versionIsGreater(isDtls, minor, clientGreatestMinor))
  5228. clientGreatestMinor = minor;
  5229. set = 1;
  5230. }
  5231. if (!set) {
  5232. /* No common supported version was negotiated */
  5233. SendAlert((WOLFSSL*)ssl, alert_fatal,
  5234. wolfssl_alert_protocol_version);
  5235. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5236. return VERSION_ERROR;
  5237. }
  5238. pv->minor = clientGreatestMinor;
  5239. if (versionIsAtLeast(isDtls, clientGreatestMinor, tls13minor)) {
  5240. if (opts != NULL)
  5241. opts->tls1_3 = 1;
  5242. /* TLS v1.3 requires supported version extension */
  5243. if (exts != NULL &&
  5244. TLSX_Find(*exts, TLSX_SUPPORTED_VERSIONS) == NULL) {
  5245. ret = TLSX_Push(exts,
  5246. TLSX_SUPPORTED_VERSIONS, ssl, ssl->heap);
  5247. if (ret != 0) {
  5248. return ret;
  5249. }
  5250. /* *exts should be pointing to the TLSX_SUPPORTED_VERSIONS
  5251. * ext in the list since it was pushed. */
  5252. (*exts)->resp = 1;
  5253. }
  5254. }
  5255. }
  5256. else if (msgType == server_hello || msgType == hello_retry_request) {
  5257. /* Must contain one version. */
  5258. if (length != OPAQUE16_LEN)
  5259. return BUFFER_ERROR;
  5260. major = input[0];
  5261. minor = input[OPAQUE8_LEN];
  5262. if (major != ssl->ctx->method->version.major) {
  5263. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5264. return VERSION_ERROR;
  5265. }
  5266. /* Can't downgrade with this extension below TLS v1.3. */
  5267. if (versionIsLesser(isDtls, minor, tls13minor)) {
  5268. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5269. return VERSION_ERROR;
  5270. }
  5271. /* Version is TLS v1.2 to handle downgrading from TLS v1.3+. */
  5272. if (ssl->options.downgrade && ssl->version.minor == tls12minor) {
  5273. /* Set minor version back to TLS v1.3+ */
  5274. pv->minor = ssl->ctx->method->version.minor;
  5275. }
  5276. /* No upgrade allowed. */
  5277. if (versionIsLesser(isDtls, ssl->version.minor, minor)) {
  5278. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5279. return VERSION_ERROR;
  5280. }
  5281. /* Check downgrade. */
  5282. if (versionIsGreater(isDtls, ssl->version.minor, minor)) {
  5283. if (!ssl->options.downgrade) {
  5284. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5285. return VERSION_ERROR;
  5286. }
  5287. if (versionIsLesser(
  5288. isDtls, minor, ssl->options.minDowngrade)) {
  5289. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5290. return VERSION_ERROR;
  5291. }
  5292. /* Downgrade the version. */
  5293. pv->minor = minor;
  5294. }
  5295. }
  5296. else {
  5297. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5298. return SANITY_MSG_E;
  5299. }
  5300. return 0;
  5301. }
  5302. /* Sets a new SupportedVersions extension into the extension list.
  5303. *
  5304. * extensions The list of extensions.
  5305. * data The extensions specific data.
  5306. * heap The heap used for allocation.
  5307. * returns 0 on success, otherwise failure.
  5308. */
  5309. static int TLSX_SetSupportedVersions(TLSX** extensions, const void* data,
  5310. void* heap)
  5311. {
  5312. if (extensions == NULL || data == NULL)
  5313. return BAD_FUNC_ARG;
  5314. return TLSX_Push(extensions, TLSX_SUPPORTED_VERSIONS, data, heap);
  5315. }
  5316. #define SV_GET_SIZE TLSX_SupportedVersions_GetSize
  5317. #define SV_WRITE TLSX_SupportedVersions_Write
  5318. #define SV_PARSE TLSX_SupportedVersions_Parse
  5319. #else
  5320. #define SV_GET_SIZE(a, b, c) 0
  5321. #define SV_WRITE(a, b, c, d) 0
  5322. #define SV_PARSE(a, b, c, d, e, f, g) 0
  5323. #endif /* WOLFSSL_TLS13 */
  5324. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  5325. /******************************************************************************/
  5326. /* Cookie */
  5327. /******************************************************************************/
  5328. /* Free the cookie data.
  5329. *
  5330. * cookie Cookie data.
  5331. * heap The heap used for allocation.
  5332. */
  5333. static void TLSX_Cookie_FreeAll(Cookie* cookie, void* heap)
  5334. {
  5335. (void)heap;
  5336. if (cookie != NULL)
  5337. XFREE(cookie, heap, DYNAMIC_TYPE_TLSX);
  5338. }
  5339. /* Get the size of the encoded Cookie extension.
  5340. * In messages: ClientHello and HelloRetryRequest.
  5341. *
  5342. * cookie The cookie to write.
  5343. * msgType The type of the message this extension is being written into.
  5344. * returns the number of bytes of the encoded Cookie extension.
  5345. */
  5346. static int TLSX_Cookie_GetSize(Cookie* cookie, byte msgType, word16* pSz)
  5347. {
  5348. if (msgType == client_hello || msgType == hello_retry_request) {
  5349. *pSz += OPAQUE16_LEN + cookie->len;
  5350. }
  5351. else {
  5352. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5353. return SANITY_MSG_E;
  5354. }
  5355. return 0;
  5356. }
  5357. /* Writes the Cookie extension into the output buffer.
  5358. * Assumes that the the output buffer is big enough to hold data.
  5359. * In messages: ClientHello and HelloRetryRequest.
  5360. *
  5361. * cookie The cookie to write.
  5362. * output The buffer to write into.
  5363. * msgType The type of the message this extension is being written into.
  5364. * returns the number of bytes written into the buffer.
  5365. */
  5366. static int TLSX_Cookie_Write(Cookie* cookie, byte* output, byte msgType,
  5367. word16* pSz)
  5368. {
  5369. if (msgType == client_hello || msgType == hello_retry_request) {
  5370. c16toa(cookie->len, output);
  5371. output += OPAQUE16_LEN;
  5372. XMEMCPY(output, cookie->data, cookie->len);
  5373. *pSz += OPAQUE16_LEN + cookie->len;
  5374. }
  5375. else {
  5376. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5377. return SANITY_MSG_E;
  5378. }
  5379. return 0;
  5380. }
  5381. /* Parse the Cookie extension.
  5382. * In messages: ClientHello and HelloRetryRequest.
  5383. *
  5384. * ssl The SSL/TLS object.
  5385. * input The extension data.
  5386. * length The length of the extension data.
  5387. * msgType The type of the message this extension is being parsed from.
  5388. * returns 0 on success and other values indicate failure.
  5389. */
  5390. static int TLSX_Cookie_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  5391. byte msgType)
  5392. {
  5393. word16 len;
  5394. word16 idx = 0;
  5395. TLSX* extension;
  5396. Cookie* cookie;
  5397. if (msgType != client_hello && msgType != hello_retry_request) {
  5398. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5399. return SANITY_MSG_E;
  5400. }
  5401. /* Message contains length and Cookie which must be at least one byte
  5402. * in length.
  5403. */
  5404. if (length < OPAQUE16_LEN + 1)
  5405. return BUFFER_E;
  5406. ato16(input + idx, &len);
  5407. idx += OPAQUE16_LEN;
  5408. if (length - idx != len)
  5409. return BUFFER_E;
  5410. if (msgType == hello_retry_request)
  5411. return TLSX_Cookie_Use(ssl, input + idx, len, NULL, 0, 0,
  5412. &ssl->extensions);
  5413. /* client_hello */
  5414. extension = TLSX_Find(ssl->extensions, TLSX_COOKIE);
  5415. if (extension == NULL) {
  5416. #ifdef WOLFSSL_DTLS13
  5417. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version))
  5418. /* Allow a cookie extension with DTLS 1.3 because it is possible
  5419. * that a different SSL instance sent the cookie but we are now
  5420. * receiving it. */
  5421. return TLSX_Cookie_Use(ssl, input + idx, len, NULL, 0, 0,
  5422. &ssl->extensions);
  5423. else
  5424. #endif
  5425. {
  5426. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  5427. return HRR_COOKIE_ERROR;
  5428. }
  5429. }
  5430. cookie = (Cookie*)extension->data;
  5431. if (cookie->len != len || XMEMCMP(cookie->data, input + idx, len) != 0) {
  5432. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  5433. return HRR_COOKIE_ERROR;
  5434. }
  5435. /* Request seen. */
  5436. extension->resp = 0;
  5437. return 0;
  5438. }
  5439. /* Use the data to create a new Cookie object in the extensions.
  5440. *
  5441. * ssl SSL/TLS object.
  5442. * data Cookie data.
  5443. * len Length of cookie data in bytes.
  5444. * mac MAC data.
  5445. * macSz Length of MAC data in bytes.
  5446. * resp Indicates the extension will go into a response (HelloRetryRequest).
  5447. * returns 0 on success and other values indicate failure.
  5448. */
  5449. int TLSX_Cookie_Use(const WOLFSSL* ssl, const byte* data, word16 len, byte* mac,
  5450. byte macSz, int resp, TLSX** exts)
  5451. {
  5452. int ret = 0;
  5453. TLSX* extension;
  5454. Cookie* cookie;
  5455. /* Find the cookie extension if it exists. */
  5456. extension = TLSX_Find(*exts, TLSX_COOKIE);
  5457. if (extension == NULL) {
  5458. /* Push new cookie extension. */
  5459. ret = TLSX_Push(exts, TLSX_COOKIE, NULL, ssl->heap);
  5460. if (ret != 0)
  5461. return ret;
  5462. extension = TLSX_Find(*exts, TLSX_COOKIE);
  5463. if (extension == NULL)
  5464. return MEMORY_E;
  5465. }
  5466. cookie = (Cookie*)XMALLOC(sizeof(Cookie) + len + macSz, ssl->heap,
  5467. DYNAMIC_TYPE_TLSX);
  5468. if (cookie == NULL)
  5469. return MEMORY_E;
  5470. cookie->len = len + macSz;
  5471. XMEMCPY(cookie->data, data, len);
  5472. if (mac != NULL)
  5473. XMEMCPY(cookie->data + len, mac, macSz);
  5474. if (extension->data != NULL)
  5475. XFREE(extension->data, ssl->heap, DYNAMIC_TYPE_TLSX);
  5476. extension->data = (void*)cookie;
  5477. extension->resp = (byte)resp;
  5478. return 0;
  5479. }
  5480. #define CKE_FREE_ALL TLSX_Cookie_FreeAll
  5481. #define CKE_GET_SIZE TLSX_Cookie_GetSize
  5482. #define CKE_WRITE TLSX_Cookie_Write
  5483. #define CKE_PARSE TLSX_Cookie_Parse
  5484. #else
  5485. #define CKE_FREE_ALL(a, b) 0
  5486. #define CKE_GET_SIZE(a, b, c) 0
  5487. #define CKE_WRITE(a, b, c, d) 0
  5488. #define CKE_PARSE(a, b, c, d) 0
  5489. #endif
  5490. #if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && \
  5491. !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA)
  5492. /* Currently only settable through compatibility API */
  5493. /******************************************************************************/
  5494. /* Certificate Authorities */
  5495. /******************************************************************************/
  5496. static word16 TLSX_CA_Names_GetSize(void* data)
  5497. {
  5498. WOLFSSL* ssl = (WOLFSSL*)data;
  5499. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  5500. word16 size = 0;
  5501. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5502. /* To add support use a different member like ssl->ca_names and
  5503. * add accessor functions:
  5504. * - *_set0_CA_list
  5505. * - *_get0_CA_list */
  5506. WOLFSSL_MSG("We don't currently support sending the client's list.");
  5507. return 0;
  5508. }
  5509. /* Length of names */
  5510. size += OPAQUE16_LEN;
  5511. for (names = SSL_CA_NAMES(ssl); names != NULL; names = names->next) {
  5512. byte seq[MAX_SEQ_SZ];
  5513. WOLFSSL_X509_NAME* name = names->data.name;
  5514. if (name != NULL) {
  5515. /* 16-bit length | SEQ | Len | DER of name */
  5516. size += (word16)(OPAQUE16_LEN + SetSequence(name->rawLen, seq) +
  5517. name->rawLen);
  5518. }
  5519. }
  5520. return size;
  5521. }
  5522. static word16 TLSX_CA_Names_Write(void* data, byte* output)
  5523. {
  5524. WOLFSSL* ssl = (WOLFSSL*)data;
  5525. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  5526. byte* len;
  5527. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5528. /* To add support use a different member like ssl->ca_names and
  5529. * add accessor functions:
  5530. * - *_set0_CA_list
  5531. * - *_get0_CA_list */
  5532. WOLFSSL_MSG("We don't currently support sending the client's list.");
  5533. return 0;
  5534. }
  5535. /* Reserve space for the length value */
  5536. len = output;
  5537. output += OPAQUE16_LEN;
  5538. for (names = SSL_CA_NAMES(ssl); names != NULL; names = names->next) {
  5539. byte seq[MAX_SEQ_SZ];
  5540. WOLFSSL_X509_NAME* name = names->data.name;
  5541. if (name != NULL) {
  5542. c16toa((word16)name->rawLen +
  5543. (word16)SetSequence(name->rawLen, seq), output);
  5544. output += OPAQUE16_LEN;
  5545. output += SetSequence(name->rawLen, output);
  5546. XMEMCPY(output, name->raw, name->rawLen);
  5547. output += name->rawLen;
  5548. }
  5549. }
  5550. /* Write the total length */
  5551. c16toa((word16)(output - len - OPAQUE16_LEN), len);
  5552. return (word16)(output - len);
  5553. }
  5554. static int TLSX_CA_Names_Parse(WOLFSSL *ssl, const byte* input,
  5555. word16 length, byte isRequest)
  5556. {
  5557. word16 extLen;
  5558. (void)isRequest;
  5559. if (ssl->options.side == WOLFSSL_SERVER_END) {
  5560. /* To add support use a different member like ssl->ca_names and
  5561. * add accessor functions:
  5562. * - *_set0_CA_list
  5563. * - *_get0_CA_list */
  5564. WOLFSSL_MSG("We don't currently support parsing the client's list.");
  5565. return 0;
  5566. }
  5567. if (ssl->client_ca_names != ssl->ctx->client_ca_names)
  5568. wolfSSL_sk_X509_NAME_pop_free(ssl->client_ca_names, NULL);
  5569. ssl->client_ca_names = wolfSSL_sk_X509_NAME_new(NULL);
  5570. if (ssl->client_ca_names == NULL)
  5571. return MEMORY_ERROR;
  5572. if (length < OPAQUE16_LEN)
  5573. return BUFFER_ERROR;
  5574. ato16(input, &extLen);
  5575. input += OPAQUE16_LEN;
  5576. length -= OPAQUE16_LEN;
  5577. if (extLen != length)
  5578. return BUFFER_ERROR;
  5579. while (length) {
  5580. word32 idx = 0;
  5581. WOLFSSL_X509_NAME* name = NULL;
  5582. int ret = 0;
  5583. int didInit = FALSE;
  5584. /* Use a DecodedCert struct to get access to GetName to
  5585. * parse DN name */
  5586. #ifdef WOLFSSL_SMALL_STACK
  5587. DecodedCert *cert = (DecodedCert *)XMALLOC(
  5588. sizeof(*cert), ssl->heap, DYNAMIC_TYPE_DCERT);
  5589. if (cert == NULL)
  5590. return MEMORY_ERROR;
  5591. #else
  5592. DecodedCert cert[1];
  5593. #endif
  5594. if (length < OPAQUE16_LEN)
  5595. return BUFFER_ERROR;
  5596. ato16(input, &extLen);
  5597. idx += OPAQUE16_LEN;
  5598. if (idx + extLen > length)
  5599. ret = BUFFER_ERROR;
  5600. if (ret == 0) {
  5601. InitDecodedCert(cert, input + idx, extLen, ssl->heap);
  5602. didInit = TRUE;
  5603. idx += extLen;
  5604. ret = GetName(cert, SUBJECT, extLen);
  5605. }
  5606. if (ret == 0 && (name = wolfSSL_X509_NAME_new()) == NULL)
  5607. ret = MEMORY_ERROR;
  5608. if (ret == 0) {
  5609. CopyDecodedName(name, cert, SUBJECT);
  5610. if (wolfSSL_sk_X509_NAME_push(ssl->client_ca_names, name)
  5611. == WOLFSSL_FAILURE)
  5612. ret = MEMORY_ERROR;
  5613. }
  5614. if (didInit)
  5615. FreeDecodedCert(cert);
  5616. #ifdef WOLFSSL_SMALL_STACK
  5617. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  5618. #endif
  5619. if (ret != 0)
  5620. return ret;
  5621. input += idx;
  5622. length -= (word16)idx;
  5623. }
  5624. return 0;
  5625. }
  5626. #define CAN_GET_SIZE TLSX_CA_Names_GetSize
  5627. #define CAN_WRITE TLSX_CA_Names_Write
  5628. #define CAN_PARSE TLSX_CA_Names_Parse
  5629. #else
  5630. #define CAN_GET_SIZE(...) 0
  5631. #define CAN_WRITE(...) 0
  5632. #define CAN_PARSE(...) 0
  5633. #endif
  5634. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  5635. /******************************************************************************/
  5636. /* Signature Algorithms */
  5637. /******************************************************************************/
  5638. /* Return the size of the SignatureAlgorithms extension's data.
  5639. *
  5640. * data Unused
  5641. * returns the length of data that will be in the extension.
  5642. */
  5643. static word16 TLSX_SignatureAlgorithms_GetSize(void* data)
  5644. {
  5645. SignatureAlgorithms* sa = (SignatureAlgorithms*)data;
  5646. if (sa->hashSigAlgoSz == 0)
  5647. return OPAQUE16_LEN + WOLFSSL_SUITES(sa->ssl)->hashSigAlgoSz;
  5648. else
  5649. return OPAQUE16_LEN + sa->hashSigAlgoSz;
  5650. }
  5651. /* Creates a bit string of supported hash algorithms with RSA PSS.
  5652. * The bit string is used when determining which signature algorithm to use
  5653. * when creating the CertificateVerify message.
  5654. * Note: Valid data has an even length as each signature algorithm is two bytes.
  5655. *
  5656. * ssl The SSL/TLS object.
  5657. * input The buffer with the list of supported signature algorithms.
  5658. * length The length of the list in bytes.
  5659. * returns 0 on success, BUFFER_ERROR when the length is not even.
  5660. */
  5661. static int TLSX_SignatureAlgorithms_MapPss(WOLFSSL *ssl, const byte* input,
  5662. word16 length)
  5663. {
  5664. word16 i;
  5665. if ((length & 1) == 1)
  5666. return BUFFER_ERROR;
  5667. ssl->pssAlgo = 0;
  5668. for (i = 0; i < length; i += 2) {
  5669. if (input[i] == rsa_pss_sa_algo && input[i + 1] <= sha512_mac)
  5670. ssl->pssAlgo |= 1 << input[i + 1];
  5671. #ifdef WOLFSSL_TLS13
  5672. if (input[i] == rsa_pss_sa_algo && input[i + 1] >= pss_sha256 &&
  5673. input[i + 1] <= pss_sha512) {
  5674. ssl->pssAlgo |= 1 << input[i + 1];
  5675. }
  5676. #endif
  5677. }
  5678. return 0;
  5679. }
  5680. /* Writes the SignatureAlgorithms extension into the buffer.
  5681. *
  5682. * data Unused
  5683. * output The buffer to write the extension into.
  5684. * returns the length of data that was written.
  5685. */
  5686. static word16 TLSX_SignatureAlgorithms_Write(void* data, byte* output)
  5687. {
  5688. SignatureAlgorithms* sa = (SignatureAlgorithms*)data;
  5689. const Suites* suites = WOLFSSL_SUITES(sa->ssl);
  5690. word16 hashSigAlgoSz;
  5691. if (sa->hashSigAlgoSz == 0) {
  5692. c16toa(suites->hashSigAlgoSz, output);
  5693. XMEMCPY(output + OPAQUE16_LEN, suites->hashSigAlgo,
  5694. suites->hashSigAlgoSz);
  5695. hashSigAlgoSz = suites->hashSigAlgoSz;
  5696. }
  5697. else {
  5698. c16toa(sa->hashSigAlgoSz, output);
  5699. XMEMCPY(output + OPAQUE16_LEN, sa->hashSigAlgo,
  5700. sa->hashSigAlgoSz);
  5701. hashSigAlgoSz = sa->hashSigAlgoSz;
  5702. }
  5703. #ifndef NO_RSA
  5704. TLSX_SignatureAlgorithms_MapPss(sa->ssl, output + OPAQUE16_LEN,
  5705. hashSigAlgoSz);
  5706. #endif
  5707. return OPAQUE16_LEN + hashSigAlgoSz;
  5708. }
  5709. /* Parse the SignatureAlgorithms extension.
  5710. *
  5711. * ssl The SSL/TLS object.
  5712. * input The buffer with the extension data.
  5713. * length The length of the extension data.
  5714. * returns 0 on success, otherwise failure.
  5715. */
  5716. static int TLSX_SignatureAlgorithms_Parse(WOLFSSL *ssl, const byte* input,
  5717. word16 length, byte isRequest, Suites* suites)
  5718. {
  5719. word16 len;
  5720. if (!isRequest)
  5721. return BUFFER_ERROR;
  5722. /* Must contain a length and at least algorithm. */
  5723. if (length < OPAQUE16_LEN + OPAQUE16_LEN || (length & 1) != 0)
  5724. return BUFFER_ERROR;
  5725. ato16(input, &len);
  5726. input += OPAQUE16_LEN;
  5727. /* Algorithm array must fill rest of data. */
  5728. if (length != OPAQUE16_LEN + len)
  5729. return BUFFER_ERROR;
  5730. /* Sig Algo list size must be even. */
  5731. if (suites->hashSigAlgoSz % 2 != 0)
  5732. return BUFFER_ERROR;
  5733. /* truncate hashSigAlgo list if too long */
  5734. suites->hashSigAlgoSz = len;
  5735. if (suites->hashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  5736. WOLFSSL_MSG("TLSX SigAlgo list exceeds max, truncating");
  5737. suites->hashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  5738. }
  5739. XMEMCPY(suites->hashSigAlgo, input, suites->hashSigAlgoSz);
  5740. return TLSX_SignatureAlgorithms_MapPss(ssl, input, len);
  5741. }
  5742. /* Sets a new SignatureAlgorithms extension into the extension list.
  5743. *
  5744. * extensions The list of extensions.
  5745. * data The extensions specific data.
  5746. * heap The heap used for allocation.
  5747. * returns 0 on success, otherwise failure.
  5748. */
  5749. static int TLSX_SetSignatureAlgorithms(TLSX** extensions, WOLFSSL* ssl,
  5750. void* heap)
  5751. {
  5752. SignatureAlgorithms* sa;
  5753. int ret;
  5754. if (extensions == NULL)
  5755. return BAD_FUNC_ARG;
  5756. /* Already present */
  5757. if (TLSX_Find(*extensions, TLSX_SIGNATURE_ALGORITHMS) != NULL)
  5758. return 0;
  5759. sa = TLSX_SignatureAlgorithms_New(ssl, 0, heap);
  5760. if (sa == NULL)
  5761. return MEMORY_ERROR;
  5762. ret = TLSX_Push(extensions, TLSX_SIGNATURE_ALGORITHMS, sa, heap);
  5763. if (ret != 0)
  5764. TLSX_SignatureAlgorithms_FreeAll(sa, heap);
  5765. return ret;
  5766. }
  5767. SignatureAlgorithms* TLSX_SignatureAlgorithms_New(WOLFSSL* ssl,
  5768. word16 hashSigAlgoSz, void* heap)
  5769. {
  5770. SignatureAlgorithms* sa;
  5771. (void)heap;
  5772. sa = (SignatureAlgorithms*)XMALLOC(sizeof(*sa) + hashSigAlgoSz, heap,
  5773. DYNAMIC_TYPE_TLSX);
  5774. if (sa != NULL) {
  5775. XMEMSET(sa, 0, sizeof(*sa) + hashSigAlgoSz);
  5776. sa->ssl = ssl;
  5777. sa->hashSigAlgoSz = hashSigAlgoSz;
  5778. }
  5779. return sa;
  5780. }
  5781. void TLSX_SignatureAlgorithms_FreeAll(SignatureAlgorithms* sa,
  5782. void* heap)
  5783. {
  5784. XFREE(sa, heap, DYNAMIC_TYPE_TLSX);
  5785. (void)heap;
  5786. }
  5787. #define SA_GET_SIZE TLSX_SignatureAlgorithms_GetSize
  5788. #define SA_WRITE TLSX_SignatureAlgorithms_Write
  5789. #define SA_PARSE TLSX_SignatureAlgorithms_Parse
  5790. #define SA_FREE_ALL TLSX_SignatureAlgorithms_FreeAll
  5791. #endif
  5792. /******************************************************************************/
  5793. /* Signature Algorithms Certificate */
  5794. /******************************************************************************/
  5795. #if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  5796. /* Return the size of the SignatureAlgorithms extension's data.
  5797. *
  5798. * data Unused
  5799. * returns the length of data that will be in the extension.
  5800. */
  5801. static word16 TLSX_SignatureAlgorithmsCert_GetSize(void* data)
  5802. {
  5803. WOLFSSL* ssl = (WOLFSSL*)data;
  5804. return OPAQUE16_LEN + ssl->certHashSigAlgoSz;
  5805. }
  5806. /* Writes the SignatureAlgorithmsCert extension into the buffer.
  5807. *
  5808. * data Unused
  5809. * output The buffer to write the extension into.
  5810. * returns the length of data that was written.
  5811. */
  5812. static word16 TLSX_SignatureAlgorithmsCert_Write(void* data, byte* output)
  5813. {
  5814. WOLFSSL* ssl = (WOLFSSL*)data;
  5815. c16toa(ssl->certHashSigAlgoSz, output);
  5816. XMEMCPY(output + OPAQUE16_LEN, ssl->certHashSigAlgo,
  5817. ssl->certHashSigAlgoSz);
  5818. return OPAQUE16_LEN + ssl->certHashSigAlgoSz;
  5819. }
  5820. /* Parse the SignatureAlgorithmsCert extension.
  5821. *
  5822. * ssl The SSL/TLS object.
  5823. * input The buffer with the extension data.
  5824. * length The length of the extension data.
  5825. * returns 0 on success, otherwise failure.
  5826. */
  5827. static int TLSX_SignatureAlgorithmsCert_Parse(WOLFSSL *ssl, const byte* input,
  5828. word16 length, byte isRequest)
  5829. {
  5830. word16 len;
  5831. if (!isRequest)
  5832. return BUFFER_ERROR;
  5833. /* Must contain a length and at least algorithm. */
  5834. if (length < OPAQUE16_LEN + OPAQUE16_LEN || (length & 1) != 0)
  5835. return BUFFER_ERROR;
  5836. ato16(input, &len);
  5837. input += OPAQUE16_LEN;
  5838. /* Algorithm array must fill rest of data. */
  5839. if (length != OPAQUE16_LEN + len)
  5840. return BUFFER_ERROR;
  5841. /* truncate hashSigAlgo list if too long */
  5842. ssl->certHashSigAlgoSz = len;
  5843. if (ssl->certHashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  5844. WOLFSSL_MSG("TLSX SigAlgo list exceeds max, truncating");
  5845. ssl->certHashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  5846. }
  5847. XMEMCPY(ssl->certHashSigAlgo, input, ssl->certHashSigAlgoSz);
  5848. return 0;
  5849. }
  5850. /* Sets a new SignatureAlgorithmsCert extension into the extension list.
  5851. *
  5852. * extensions The list of extensions.
  5853. * data The extensions specific data.
  5854. * heap The heap used for allocation.
  5855. * returns 0 on success, otherwise failure.
  5856. */
  5857. static int TLSX_SetSignatureAlgorithmsCert(TLSX** extensions,
  5858. const WOLFSSL* data, void* heap)
  5859. {
  5860. if (extensions == NULL)
  5861. return BAD_FUNC_ARG;
  5862. return TLSX_Push(extensions, TLSX_SIGNATURE_ALGORITHMS_CERT, data, heap);
  5863. }
  5864. #define SAC_GET_SIZE TLSX_SignatureAlgorithmsCert_GetSize
  5865. #define SAC_WRITE TLSX_SignatureAlgorithmsCert_Write
  5866. #define SAC_PARSE TLSX_SignatureAlgorithmsCert_Parse
  5867. #endif /* WOLFSSL_TLS13 */
  5868. /******************************************************************************/
  5869. /* Key Share */
  5870. /******************************************************************************/
  5871. #if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
  5872. /* Create a key share entry using named Diffie-Hellman parameters group.
  5873. * Generates a key pair.
  5874. *
  5875. * ssl The SSL/TLS object.
  5876. * kse The key share entry object.
  5877. * returns 0 on success, otherwise failure.
  5878. */
  5879. static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse)
  5880. {
  5881. int ret = 0;
  5882. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  5883. word32 pSz = 0, pvtSz = 0;
  5884. DhKey* dhKey = (DhKey*)kse->key;
  5885. /* Pick the parameters from the named group. */
  5886. #ifdef HAVE_PUBLIC_FFDHE
  5887. const DhParams* params = NULL;
  5888. switch (kse->group) {
  5889. #ifdef HAVE_FFDHE_2048
  5890. case WOLFSSL_FFDHE_2048:
  5891. params = wc_Dh_ffdhe2048_Get();
  5892. pvtSz = 29;
  5893. break;
  5894. #endif
  5895. #ifdef HAVE_FFDHE_3072
  5896. case WOLFSSL_FFDHE_3072:
  5897. params = wc_Dh_ffdhe3072_Get();
  5898. pvtSz = 34;
  5899. break;
  5900. #endif
  5901. #ifdef HAVE_FFDHE_4096
  5902. case WOLFSSL_FFDHE_4096:
  5903. params = wc_Dh_ffdhe4096_Get();
  5904. pvtSz = 39;
  5905. break;
  5906. #endif
  5907. #ifdef HAVE_FFDHE_6144
  5908. case WOLFSSL_FFDHE_6144:
  5909. params = wc_Dh_ffdhe6144_Get();
  5910. pvtSz = 46;
  5911. break;
  5912. #endif
  5913. #ifdef HAVE_FFDHE_8192
  5914. case WOLFSSL_FFDHE_8192:
  5915. params = wc_Dh_ffdhe8192_Get();
  5916. pvtSz = 52;
  5917. break;
  5918. #endif
  5919. default:
  5920. break;
  5921. }
  5922. if (params == NULL)
  5923. return BAD_FUNC_ARG;
  5924. pSz = params->p_len;
  5925. #else
  5926. pvtSz = wc_DhGetNamedKeyMinSize(kse->group);
  5927. if (pvtSz == 0) {
  5928. return BAD_FUNC_ARG;
  5929. }
  5930. ret = wc_DhGetNamedKeyParamSize(kse->group, &pSz, NULL, NULL);
  5931. if (ret != 0) {
  5932. return BAD_FUNC_ARG;
  5933. }
  5934. #endif
  5935. /* Trigger Key Generation */
  5936. if (kse->pubKey == NULL || kse->privKey == NULL) {
  5937. if (kse->key == NULL) {
  5938. kse->key = (DhKey*)XMALLOC(sizeof(DhKey), ssl->heap,
  5939. DYNAMIC_TYPE_DH);
  5940. if (kse->key == NULL)
  5941. return MEMORY_E;
  5942. /* Setup Key */
  5943. ret = wc_InitDhKey_ex((DhKey*)kse->key, ssl->heap, ssl->devId);
  5944. if (ret == 0) {
  5945. dhKey = (DhKey*)kse->key;
  5946. #ifdef HAVE_PUBLIC_FFDHE
  5947. ret = wc_DhSetKey(dhKey, params->p, params->p_len, params->g,
  5948. params->g_len);
  5949. #else
  5950. ret = wc_DhSetNamedKey(dhKey, kse->group);
  5951. #endif
  5952. }
  5953. }
  5954. /* Allocate space for the private and public key */
  5955. if (ret == 0 && kse->pubKey == NULL) {
  5956. kse->pubKey = (byte*)XMALLOC(pSz, ssl->heap,
  5957. DYNAMIC_TYPE_PUBLIC_KEY);
  5958. if (kse->pubKey == NULL)
  5959. ret = MEMORY_E;
  5960. }
  5961. if (ret == 0 && kse->privKey == NULL) {
  5962. kse->privKey = (byte*)XMALLOC(pvtSz, ssl->heap,
  5963. DYNAMIC_TYPE_PRIVATE_KEY);
  5964. if (kse->privKey == NULL)
  5965. ret = MEMORY_E;
  5966. }
  5967. if (ret == 0) {
  5968. #if defined(WOLFSSL_STATIC_EPHEMERAL) && defined(WOLFSSL_DH_EXTRA)
  5969. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_DH, kse->key);
  5970. kse->pubKeyLen = pSz;
  5971. kse->keyLen = pvtSz;
  5972. if (ret == 0) {
  5973. ret = wc_DhExportKeyPair(dhKey,
  5974. (byte*)kse->privKey, &kse->keyLen, /* private */
  5975. kse->pubKey, &kse->pubKeyLen /* public */
  5976. );
  5977. }
  5978. else
  5979. #endif
  5980. {
  5981. /* Generate a new key pair */
  5982. /* For async this is called once and when event is done, the
  5983. * provided buffers will be populated.
  5984. * Final processing is zero pad below. */
  5985. kse->pubKeyLen = pSz;
  5986. kse->keyLen = pvtSz;
  5987. ret = DhGenKeyPair(ssl, dhKey,
  5988. (byte*)kse->privKey, &kse->keyLen, /* private */
  5989. kse->pubKey, &kse->pubKeyLen /* public */
  5990. );
  5991. #ifdef WOLFSSL_ASYNC_CRYPT
  5992. if (ret == WC_PENDING_E) {
  5993. return ret;
  5994. }
  5995. #endif
  5996. }
  5997. }
  5998. }
  5999. if (ret == 0) {
  6000. if (pSz != kse->pubKeyLen) {
  6001. /* Zero pad the front of the public key to match prime "p" size */
  6002. XMEMMOVE(kse->pubKey + pSz - kse->pubKeyLen, kse->pubKey,
  6003. kse->pubKeyLen);
  6004. XMEMSET(kse->pubKey, 0, pSz - kse->pubKeyLen);
  6005. kse->pubKeyLen = pSz;
  6006. }
  6007. if (pvtSz != kse->keyLen) {
  6008. /* Zero pad the front of the private key */
  6009. XMEMMOVE(kse->privKey + pvtSz - kse->keyLen, kse->privKey,
  6010. kse->keyLen);
  6011. XMEMSET(kse->privKey, 0, pvtSz - kse->keyLen);
  6012. kse->keyLen = pvtSz;
  6013. }
  6014. #ifdef WOLFSSL_DEBUG_TLS
  6015. WOLFSSL_MSG("Public DH Key");
  6016. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6017. #endif
  6018. }
  6019. /* Always release the DH key to free up memory.
  6020. * The DhKey will be setup again in TLSX_KeyShare_ProcessDh */
  6021. if (dhKey != NULL)
  6022. wc_FreeDhKey(dhKey);
  6023. if (kse->key != NULL) {
  6024. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_DH);
  6025. kse->key = NULL;
  6026. }
  6027. if (ret != 0) {
  6028. /* Cleanup on error, otherwise data owned by key share entry */
  6029. if (kse->privKey != NULL) {
  6030. XFREE(kse->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6031. kse->privKey = NULL;
  6032. }
  6033. if (kse->pubKey != NULL) {
  6034. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6035. kse->pubKey = NULL;
  6036. }
  6037. }
  6038. #else
  6039. (void)ssl;
  6040. (void)kse;
  6041. ret = NOT_COMPILED_IN;
  6042. WOLFSSL_ERROR_VERBOSE(ret);
  6043. #endif
  6044. return ret;
  6045. }
  6046. /* Create a key share entry using X25519 parameters group.
  6047. * Generates a key pair.
  6048. *
  6049. * ssl The SSL/TLS object.
  6050. * kse The key share entry object.
  6051. * returns 0 on success, otherwise failure.
  6052. */
  6053. static int TLSX_KeyShare_GenX25519Key(WOLFSSL *ssl, KeyShareEntry* kse)
  6054. {
  6055. int ret = 0;
  6056. #ifdef HAVE_CURVE25519
  6057. curve25519_key* key = (curve25519_key*)kse->key;
  6058. if (kse->key == NULL) {
  6059. /* Allocate a Curve25519 key to hold private key. */
  6060. kse->key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), ssl->heap,
  6061. DYNAMIC_TYPE_PRIVATE_KEY);
  6062. if (kse->key == NULL) {
  6063. WOLFSSL_MSG("GenX25519Key memory error");
  6064. return MEMORY_E;
  6065. }
  6066. /* Make an Curve25519 key. */
  6067. ret = wc_curve25519_init_ex((curve25519_key*)kse->key, ssl->heap,
  6068. INVALID_DEVID);
  6069. if (ret == 0) {
  6070. /* setting "key" means okay to call wc_curve25519_free */
  6071. key = (curve25519_key*)kse->key;
  6072. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6073. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE25519, kse->key);
  6074. if (ret != 0)
  6075. #endif
  6076. {
  6077. ret = wc_curve25519_make_key(ssl->rng, CURVE25519_KEYSIZE, key);
  6078. }
  6079. }
  6080. }
  6081. if (ret == 0 && kse->pubKey == NULL) {
  6082. /* Allocate space for the public key. */
  6083. kse->pubKey = (byte*)XMALLOC(CURVE25519_KEYSIZE, ssl->heap,
  6084. DYNAMIC_TYPE_PUBLIC_KEY);
  6085. if (kse->pubKey == NULL) {
  6086. WOLFSSL_MSG("GenX25519Key pub memory error");
  6087. ret = MEMORY_E;
  6088. }
  6089. }
  6090. if (ret == 0) {
  6091. /* Export Curve25519 public key. */
  6092. kse->pubKeyLen = CURVE25519_KEYSIZE;
  6093. if (wc_curve25519_export_public_ex(key, kse->pubKey, &kse->pubKeyLen,
  6094. EC25519_LITTLE_ENDIAN) != 0) {
  6095. ret = ECC_EXPORT_ERROR;
  6096. WOLFSSL_ERROR_VERBOSE(ret);
  6097. }
  6098. kse->pubKeyLen = CURVE25519_KEYSIZE; /* always CURVE25519_KEYSIZE */
  6099. }
  6100. #ifdef WOLFSSL_DEBUG_TLS
  6101. if (ret == 0) {
  6102. WOLFSSL_MSG("Public Curve25519 Key");
  6103. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6104. }
  6105. #endif
  6106. if (ret != 0) {
  6107. /* Data owned by key share entry otherwise. */
  6108. if (kse->pubKey != NULL) {
  6109. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6110. kse->pubKey = NULL;
  6111. }
  6112. if (key != NULL)
  6113. wc_curve25519_free(key);
  6114. if (kse->key != NULL) {
  6115. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6116. kse->key = NULL;
  6117. }
  6118. }
  6119. #else
  6120. (void)ssl;
  6121. (void)kse;
  6122. ret = NOT_COMPILED_IN;
  6123. WOLFSSL_ERROR_VERBOSE(ret);
  6124. #endif /* HAVE_CURVE25519 */
  6125. return ret;
  6126. }
  6127. /* Create a key share entry using X448 parameters group.
  6128. * Generates a key pair.
  6129. *
  6130. * ssl The SSL/TLS object.
  6131. * kse The key share entry object.
  6132. * returns 0 on success, otherwise failure.
  6133. */
  6134. static int TLSX_KeyShare_GenX448Key(WOLFSSL *ssl, KeyShareEntry* kse)
  6135. {
  6136. int ret = 0;
  6137. #ifdef HAVE_CURVE448
  6138. curve448_key* key = (curve448_key*)kse->key;
  6139. if (kse->key == NULL) {
  6140. /* Allocate a Curve448 key to hold private key. */
  6141. kse->key = (curve448_key*)XMALLOC(sizeof(curve448_key), ssl->heap,
  6142. DYNAMIC_TYPE_PRIVATE_KEY);
  6143. if (kse->key == NULL) {
  6144. WOLFSSL_MSG("GenX448Key memory error");
  6145. return MEMORY_E;
  6146. }
  6147. /* Make an Curve448 key. */
  6148. ret = wc_curve448_init((curve448_key*)kse->key);
  6149. if (ret == 0) {
  6150. key = (curve448_key*)kse->key;
  6151. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6152. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE448, kse->key);
  6153. if (ret != 0)
  6154. #endif
  6155. {
  6156. ret = wc_curve448_make_key(ssl->rng, CURVE448_KEY_SIZE, key);
  6157. }
  6158. }
  6159. }
  6160. if (ret == 0 && kse->pubKey == NULL) {
  6161. /* Allocate space for the public key. */
  6162. kse->pubKey = (byte*)XMALLOC(CURVE448_KEY_SIZE, ssl->heap,
  6163. DYNAMIC_TYPE_PUBLIC_KEY);
  6164. if (kse->pubKey == NULL) {
  6165. WOLFSSL_MSG("GenX448Key pub memory error");
  6166. ret = MEMORY_E;
  6167. }
  6168. }
  6169. if (ret == 0) {
  6170. /* Export Curve448 public key. */
  6171. kse->pubKeyLen = CURVE448_KEY_SIZE;
  6172. if (wc_curve448_export_public_ex(key, kse->pubKey, &kse->pubKeyLen,
  6173. EC448_LITTLE_ENDIAN) != 0) {
  6174. ret = ECC_EXPORT_ERROR;
  6175. }
  6176. kse->pubKeyLen = CURVE448_KEY_SIZE; /* always CURVE448_KEY_SIZE */
  6177. }
  6178. #ifdef WOLFSSL_DEBUG_TLS
  6179. if (ret == 0) {
  6180. WOLFSSL_MSG("Public Curve448 Key");
  6181. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6182. }
  6183. #endif
  6184. if (ret != 0) {
  6185. /* Data owned by key share entry otherwise. */
  6186. if (kse->pubKey != NULL) {
  6187. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6188. kse->pubKey = NULL;
  6189. }
  6190. if (key != NULL)
  6191. wc_curve448_free(key);
  6192. if (kse->key != NULL) {
  6193. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6194. kse->key = NULL;
  6195. }
  6196. }
  6197. #else
  6198. (void)ssl;
  6199. (void)kse;
  6200. ret = NOT_COMPILED_IN;
  6201. WOLFSSL_ERROR_VERBOSE(ret);
  6202. #endif /* HAVE_CURVE448 */
  6203. return ret;
  6204. }
  6205. /* Create a key share entry using named elliptic curve parameters group.
  6206. * Generates a key pair.
  6207. *
  6208. * ssl The SSL/TLS object.
  6209. * kse The key share entry object.
  6210. * returns 0 on success, otherwise failure.
  6211. */
  6212. static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse)
  6213. {
  6214. int ret = 0;
  6215. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  6216. word32 keySize = 0;
  6217. word16 curveId = (word16) ECC_CURVE_INVALID;
  6218. ecc_key* eccKey = (ecc_key*)kse->key;
  6219. /* TODO: [TLS13] Get key sizes using wc_ecc_get_curve_size_from_id. */
  6220. /* Translate named group to a curve id. */
  6221. switch (kse->group) {
  6222. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  6223. #ifndef NO_ECC_SECP
  6224. case WOLFSSL_ECC_SECP256R1:
  6225. curveId = ECC_SECP256R1;
  6226. keySize = 32;
  6227. break;
  6228. #endif /* !NO_ECC_SECP */
  6229. #ifdef WOLFSSL_SM2
  6230. case WOLFSSL_ECC_SM2P256V1:
  6231. curveId = ECC_SM2P256V1;
  6232. keySize = 32;
  6233. break;
  6234. #endif /* !NO_ECC_SECP */
  6235. #endif
  6236. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  6237. #ifndef NO_ECC_SECP
  6238. case WOLFSSL_ECC_SECP384R1:
  6239. curveId = ECC_SECP384R1;
  6240. keySize = 48;
  6241. break;
  6242. #endif /* !NO_ECC_SECP */
  6243. #endif
  6244. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  6245. #ifndef NO_ECC_SECP
  6246. case WOLFSSL_ECC_SECP521R1:
  6247. curveId = ECC_SECP521R1;
  6248. keySize = 66;
  6249. break;
  6250. #endif /* !NO_ECC_SECP */
  6251. #endif
  6252. default:
  6253. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  6254. return BAD_FUNC_ARG;
  6255. }
  6256. if (kse->key == NULL) {
  6257. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  6258. ret = tsip_Tls13GenEccKeyPair(ssl, kse);
  6259. if (ret != CRYPTOCB_UNAVAILABLE) {
  6260. return ret;
  6261. }
  6262. #endif
  6263. /* Allocate an ECC key to hold private key. */
  6264. kse->key = (byte*)XMALLOC(sizeof(ecc_key), ssl->heap, DYNAMIC_TYPE_ECC);
  6265. if (kse->key == NULL) {
  6266. WOLFSSL_MSG("EccTempKey Memory error");
  6267. return MEMORY_E;
  6268. }
  6269. /* Initialize an ECC key struct for the ephemeral key */
  6270. ret = wc_ecc_init_ex((ecc_key*)kse->key, ssl->heap, ssl->devId);
  6271. if (ret == 0) {
  6272. kse->keyLen = keySize;
  6273. kse->pubKeyLen = keySize * 2 + 1;
  6274. /* setting eccKey means okay to call wc_ecc_free */
  6275. eccKey = (ecc_key*)kse->key;
  6276. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6277. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_ECDH, kse->key);
  6278. if (ret != 0)
  6279. #endif
  6280. {
  6281. /* set curve info for EccMakeKey "peer" info */
  6282. ret = wc_ecc_set_curve(eccKey, kse->keyLen, curveId);
  6283. if (ret == 0) {
  6284. #ifdef WOLFSSL_ASYNC_CRYPT
  6285. /* Detect when private key generation is done */
  6286. if (ssl->error == WC_PENDING_E &&
  6287. eccKey->type == ECC_PRIVATEKEY) {
  6288. ret = 0; /* ECC Key Generation is done */
  6289. }
  6290. else
  6291. #endif
  6292. {
  6293. /* Generate ephemeral ECC key */
  6294. /* For async this is called once and when event is done, the
  6295. * provided buffers in key be populated.
  6296. * Final processing is x963 key export below. */
  6297. ret = EccMakeKey(ssl, eccKey, eccKey);
  6298. }
  6299. }
  6300. #ifdef WOLFSSL_ASYNC_CRYPT
  6301. if (ret == WC_PENDING_E)
  6302. return ret;
  6303. #endif
  6304. }
  6305. }
  6306. }
  6307. if (ret == 0 && kse->pubKey == NULL) {
  6308. /* Allocate space for the public key */
  6309. kse->pubKey = (byte*)XMALLOC(kse->pubKeyLen, ssl->heap,
  6310. DYNAMIC_TYPE_PUBLIC_KEY);
  6311. if (kse->pubKey == NULL) {
  6312. WOLFSSL_MSG("Key data Memory error");
  6313. ret = MEMORY_E;
  6314. }
  6315. }
  6316. if (ret == 0) {
  6317. XMEMSET(kse->pubKey, 0, kse->pubKeyLen);
  6318. /* Export public key. */
  6319. PRIVATE_KEY_UNLOCK();
  6320. if (wc_ecc_export_x963(eccKey, kse->pubKey, &kse->pubKeyLen) != 0) {
  6321. ret = ECC_EXPORT_ERROR;
  6322. WOLFSSL_ERROR_VERBOSE(ret);
  6323. }
  6324. PRIVATE_KEY_LOCK();
  6325. }
  6326. #ifdef WOLFSSL_DEBUG_TLS
  6327. if (ret == 0) {
  6328. WOLFSSL_MSG("Public ECC Key");
  6329. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6330. }
  6331. #endif
  6332. if (ret != 0) {
  6333. /* Cleanup on error, otherwise data owned by key share entry */
  6334. if (kse->pubKey != NULL) {
  6335. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6336. kse->pubKey = NULL;
  6337. }
  6338. if (eccKey != NULL)
  6339. wc_ecc_free(eccKey);
  6340. if (kse->key != NULL) {
  6341. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6342. kse->key = NULL;
  6343. }
  6344. }
  6345. #else
  6346. (void)ssl;
  6347. (void)kse;
  6348. ret = NOT_COMPILED_IN;
  6349. WOLFSSL_ERROR_VERBOSE(ret);
  6350. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  6351. return ret;
  6352. }
  6353. #ifdef HAVE_PQC
  6354. static int kyber_id2type(int id, int *type)
  6355. {
  6356. int ret = 0;
  6357. switch (id) {
  6358. #ifdef WOLFSSL_KYBER512
  6359. case WOLFSSL_KYBER_LEVEL1:
  6360. *type = KYBER512;
  6361. break;
  6362. #endif
  6363. #ifdef WOLFSSL_KYBER768
  6364. case WOLFSSL_KYBER_LEVEL3:
  6365. *type = KYBER768;
  6366. break;
  6367. #endif
  6368. #ifdef WOLFSSL_KYBER1024
  6369. case WOLFSSL_KYBER_LEVEL5:
  6370. *type = KYBER1024;
  6371. break;
  6372. #endif
  6373. default:
  6374. ret = NOT_COMPILED_IN;
  6375. break;
  6376. }
  6377. return ret;
  6378. }
  6379. typedef struct PqcHybridMapping {
  6380. int hybrid;
  6381. int ecc;
  6382. int pqc;
  6383. } PqcHybridMapping;
  6384. static const PqcHybridMapping pqc_hybrid_mapping[] = {
  6385. {.hybrid = WOLFSSL_P256_KYBER_LEVEL1, .ecc = WOLFSSL_ECC_SECP256R1,
  6386. .pqc = WOLFSSL_KYBER_LEVEL1},
  6387. {.hybrid = WOLFSSL_P384_KYBER_LEVEL3, .ecc = WOLFSSL_ECC_SECP384R1,
  6388. .pqc = WOLFSSL_KYBER_LEVEL3},
  6389. {.hybrid = WOLFSSL_P521_KYBER_LEVEL5, .ecc = WOLFSSL_ECC_SECP521R1,
  6390. .pqc = WOLFSSL_KYBER_LEVEL5},
  6391. {.hybrid = 0, .ecc = 0, .pqc = 0}
  6392. };
  6393. /* This will map an ecc-pqs hybrid group into its ecc group and pqc kem group.
  6394. * If it cannot find a mapping then *pqc is set to group. ecc is optional. */
  6395. static void findEccPqc(int *ecc, int *pqc, int group)
  6396. {
  6397. int i;
  6398. if (pqc == NULL) {
  6399. return;
  6400. }
  6401. *pqc = 0;
  6402. if (ecc != NULL) {
  6403. *ecc = 0;
  6404. }
  6405. for (i = 0; pqc_hybrid_mapping[i].hybrid != 0; i++) {
  6406. if (pqc_hybrid_mapping[i].hybrid == group) {
  6407. *pqc = pqc_hybrid_mapping[i].pqc;
  6408. if (ecc != NULL) {
  6409. *ecc = pqc_hybrid_mapping[i].ecc;
  6410. }
  6411. break;
  6412. }
  6413. }
  6414. if (*pqc == 0) {
  6415. /* It is not a hybrid, so maybe its simple. */
  6416. *pqc = group;
  6417. }
  6418. }
  6419. /* Create a key share entry using liboqs parameters group.
  6420. * Generates a key pair.
  6421. *
  6422. * ssl The SSL/TLS object.
  6423. * kse The key share entry object.
  6424. * returns 0 on success, otherwise failure.
  6425. */
  6426. static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse)
  6427. {
  6428. int ret = 0;
  6429. int type = 0;
  6430. KyberKey kem[1];
  6431. byte* pubKey = NULL;
  6432. byte* privKey = NULL;
  6433. KeyShareEntry *ecc_kse = NULL;
  6434. int oqs_group = 0;
  6435. int ecc_group = 0;
  6436. word32 privSz = 0;
  6437. word32 pubSz = 0;
  6438. findEccPqc(&ecc_group, &oqs_group, kse->group);
  6439. ret = kyber_id2type(oqs_group, &type);
  6440. if (ret == NOT_COMPILED_IN) {
  6441. WOLFSSL_MSG("Invalid Kyber algorithm specified.");
  6442. ret = BAD_FUNC_ARG;
  6443. }
  6444. if (ret == 0) {
  6445. ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId);
  6446. if (ret != 0) {
  6447. WOLFSSL_MSG("Failed to initialize Kyber Key.");
  6448. }
  6449. }
  6450. if (ret == 0) {
  6451. ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap,
  6452. DYNAMIC_TYPE_TLSX);
  6453. if (ecc_kse == NULL) {
  6454. WOLFSSL_MSG("ecc_kse memory allocation failure");
  6455. ret = MEMORY_ERROR;
  6456. }
  6457. }
  6458. if (ret == 0) {
  6459. XMEMSET(ecc_kse, 0, sizeof(*ecc_kse));
  6460. ret = wc_KyberKey_PrivateKeySize(kem, &privSz);
  6461. }
  6462. if (ret == 0) {
  6463. ret = wc_KyberKey_PublicKeySize(kem, &pubSz);
  6464. }
  6465. if (ret == 0 && ecc_group != 0) {
  6466. ecc_kse->group = ecc_group;
  6467. ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse);
  6468. /* If fail, no error message, TLSX_KeyShare_GenEccKey will do it. */
  6469. }
  6470. if (ret == 0) {
  6471. pubKey = (byte*)XMALLOC(ecc_kse->pubKeyLen + pubSz, ssl->heap,
  6472. DYNAMIC_TYPE_PUBLIC_KEY);
  6473. if (pubKey == NULL) {
  6474. WOLFSSL_MSG("pubkey memory allocation failure");
  6475. ret = MEMORY_ERROR;
  6476. }
  6477. }
  6478. if (ret == 0) {
  6479. privKey = (byte*)XMALLOC(privSz, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6480. if (privKey == NULL) {
  6481. WOLFSSL_MSG("privkey memory allocation failure");
  6482. ret = MEMORY_ERROR;
  6483. }
  6484. }
  6485. if (ret == 0) {
  6486. ret = wc_KyberKey_MakeKey(kem, ssl->rng);
  6487. if (ret != 0) {
  6488. WOLFSSL_MSG("Kyber keygen failure");
  6489. }
  6490. }
  6491. if (ret == 0) {
  6492. ret = wc_KyberKey_EncodePublicKey(kem, pubKey + ecc_kse->pubKeyLen,
  6493. pubSz);
  6494. }
  6495. if (ret == 0) {
  6496. ret = wc_KyberKey_EncodePrivateKey(kem, privKey, privSz);
  6497. }
  6498. if (ret == 0) {
  6499. XMEMCPY(pubKey, ecc_kse->pubKey, ecc_kse->pubKeyLen);
  6500. kse->pubKey = pubKey;
  6501. kse->pubKeyLen = ecc_kse->pubKeyLen + pubSz;
  6502. pubKey = NULL;
  6503. /* Note we are saving the OQS private key and ECC private key
  6504. * separately. That's because the ECC private key is not simply a
  6505. * buffer. Its is an ecc_key struct.
  6506. */
  6507. kse->privKey = privKey;
  6508. privKey = NULL;
  6509. kse->key = ecc_kse->key;
  6510. ecc_kse->key = NULL;
  6511. }
  6512. #ifdef WOLFSSL_DEBUG_TLS
  6513. WOLFSSL_MSG("Public Kyber Key");
  6514. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen );
  6515. #endif
  6516. wc_KyberKey_Free(kem);
  6517. TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap);
  6518. if (pubKey != NULL)
  6519. XFREE(pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6520. if (privKey != NULL)
  6521. XFREE(privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6522. return ret;
  6523. }
  6524. #endif /* HAVE_PQC */
  6525. /* Generate a secret/key using the key share entry.
  6526. *
  6527. * ssl The SSL/TLS object.
  6528. * kse The key share entry holding peer data.
  6529. */
  6530. int TLSX_KeyShare_GenKey(WOLFSSL *ssl, KeyShareEntry *kse)
  6531. {
  6532. int ret;
  6533. /* Named FFDHE groups have a bit set to identify them. */
  6534. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(kse->group))
  6535. ret = TLSX_KeyShare_GenDhKey(ssl, kse);
  6536. else if (kse->group == WOLFSSL_ECC_X25519)
  6537. ret = TLSX_KeyShare_GenX25519Key(ssl, kse);
  6538. else if (kse->group == WOLFSSL_ECC_X448)
  6539. ret = TLSX_KeyShare_GenX448Key(ssl, kse);
  6540. #ifdef HAVE_PQC
  6541. else if (WOLFSSL_NAMED_GROUP_IS_PQC(kse->group))
  6542. ret = TLSX_KeyShare_GenPqcKey(ssl, kse);
  6543. #endif
  6544. else
  6545. ret = TLSX_KeyShare_GenEccKey(ssl, kse);
  6546. #ifdef WOLFSSL_ASYNC_CRYPT
  6547. kse->lastRet = ret;
  6548. #endif
  6549. return ret;
  6550. }
  6551. /* Free the key share dynamic data.
  6552. *
  6553. * list The linked list of key share entry objects.
  6554. * heap The heap used for allocation.
  6555. */
  6556. static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap)
  6557. {
  6558. KeyShareEntry* current;
  6559. while ((current = list) != NULL) {
  6560. list = current->next;
  6561. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(current->group)) {
  6562. #ifndef NO_DH
  6563. wc_FreeDhKey((DhKey*)current->key);
  6564. #endif
  6565. }
  6566. else if (current->group == WOLFSSL_ECC_X25519) {
  6567. #ifdef HAVE_CURVE25519
  6568. wc_curve25519_free((curve25519_key*)current->key);
  6569. #endif
  6570. }
  6571. else if (current->group == WOLFSSL_ECC_X448) {
  6572. #ifdef HAVE_CURVE448
  6573. wc_curve448_free((curve448_key*)current->key);
  6574. #endif
  6575. }
  6576. #ifdef HAVE_PQC
  6577. else if (WOLFSSL_NAMED_GROUP_IS_PQC(current->group) &&
  6578. current->key != NULL) {
  6579. ForceZero((byte*)current->key, current->keyLen);
  6580. }
  6581. #endif
  6582. else {
  6583. #ifdef HAVE_ECC
  6584. wc_ecc_free((ecc_key*)current->key);
  6585. #endif
  6586. }
  6587. XFREE(current->key, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6588. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  6589. XFREE(current->privKey, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6590. #endif
  6591. XFREE(current->pubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6592. XFREE(current->ke, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6593. XFREE(current, heap, DYNAMIC_TYPE_TLSX);
  6594. }
  6595. (void)heap;
  6596. }
  6597. /* Get the size of the encoded key share extension.
  6598. *
  6599. * list The linked list of key share extensions.
  6600. * msgType The type of the message this extension is being written into.
  6601. * returns the number of bytes of the encoded key share extension.
  6602. */
  6603. static word16 TLSX_KeyShare_GetSize(KeyShareEntry* list, byte msgType)
  6604. {
  6605. word16 len = 0;
  6606. byte isRequest = (msgType == client_hello);
  6607. KeyShareEntry* current;
  6608. /* The named group the server wants to use. */
  6609. if (msgType == hello_retry_request)
  6610. return OPAQUE16_LEN;
  6611. /* List of key exchange groups. */
  6612. if (isRequest)
  6613. len += OPAQUE16_LEN;
  6614. while ((current = list) != NULL) {
  6615. list = current->next;
  6616. if (!isRequest && current->pubKey == NULL)
  6617. continue;
  6618. len += (word16)(KE_GROUP_LEN + OPAQUE16_LEN + current->pubKeyLen);
  6619. }
  6620. return len;
  6621. }
  6622. /* Writes the key share extension into the output buffer.
  6623. * Assumes that the the output buffer is big enough to hold data.
  6624. *
  6625. * list The linked list of key share entries.
  6626. * output The buffer to write into.
  6627. * msgType The type of the message this extension is being written into.
  6628. * returns the number of bytes written into the buffer.
  6629. */
  6630. static word16 TLSX_KeyShare_Write(KeyShareEntry* list, byte* output,
  6631. byte msgType)
  6632. {
  6633. word16 i = 0;
  6634. byte isRequest = (msgType == client_hello);
  6635. KeyShareEntry* current;
  6636. if (msgType == hello_retry_request) {
  6637. c16toa(list->group, output);
  6638. return OPAQUE16_LEN;
  6639. }
  6640. /* ClientHello has a list but ServerHello is only the chosen. */
  6641. if (isRequest)
  6642. i += OPAQUE16_LEN;
  6643. /* Write out all in the list. */
  6644. while ((current = list) != NULL) {
  6645. list = current->next;
  6646. if (!isRequest && current->pubKey == NULL)
  6647. continue;
  6648. c16toa(current->group, &output[i]);
  6649. i += KE_GROUP_LEN;
  6650. c16toa((word16)(current->pubKeyLen), &output[i]);
  6651. i += OPAQUE16_LEN;
  6652. XMEMCPY(&output[i], current->pubKey, current->pubKeyLen);
  6653. i += (word16)current->pubKeyLen;
  6654. }
  6655. /* Write the length of the list if required. */
  6656. if (isRequest)
  6657. c16toa(i - OPAQUE16_LEN, output);
  6658. return i;
  6659. }
  6660. /* Process the DH key share extension on the client side.
  6661. *
  6662. * ssl The SSL/TLS object.
  6663. * keyShareEntry The key share entry object to use to calculate shared secret.
  6664. * returns 0 on success and other values indicate failure.
  6665. */
  6666. static int TLSX_KeyShare_ProcessDh(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6667. {
  6668. int ret = 0;
  6669. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  6670. word32 pSz = 0;
  6671. DhKey* dhKey = (DhKey*)keyShareEntry->key;
  6672. #ifdef HAVE_PUBLIC_FFDHE
  6673. const DhParams* params = NULL;
  6674. switch (keyShareEntry->group) {
  6675. #ifdef HAVE_FFDHE_2048
  6676. case WOLFSSL_FFDHE_2048:
  6677. params = wc_Dh_ffdhe2048_Get();
  6678. break;
  6679. #endif
  6680. #ifdef HAVE_FFDHE_3072
  6681. case WOLFSSL_FFDHE_3072:
  6682. params = wc_Dh_ffdhe3072_Get();
  6683. break;
  6684. #endif
  6685. #ifdef HAVE_FFDHE_4096
  6686. case WOLFSSL_FFDHE_4096:
  6687. params = wc_Dh_ffdhe4096_Get();
  6688. break;
  6689. #endif
  6690. #ifdef HAVE_FFDHE_6144
  6691. case WOLFSSL_FFDHE_6144:
  6692. params = wc_Dh_ffdhe6144_Get();
  6693. break;
  6694. #endif
  6695. #ifdef HAVE_FFDHE_8192
  6696. case WOLFSSL_FFDHE_8192:
  6697. params = wc_Dh_ffdhe8192_Get();
  6698. break;
  6699. #endif
  6700. default:
  6701. break;
  6702. }
  6703. if (params == NULL) {
  6704. WOLFSSL_ERROR_VERBOSE(PEER_KEY_ERROR);
  6705. return PEER_KEY_ERROR;
  6706. }
  6707. pSz = params->p_len;
  6708. #else
  6709. ret = wc_DhGetNamedKeyParamSize(keyShareEntry->group, &pSz, NULL, NULL);
  6710. if (ret != 0 || pSz == 0) {
  6711. WOLFSSL_ERROR_VERBOSE(PEER_KEY_ERROR);
  6712. return PEER_KEY_ERROR;
  6713. }
  6714. #endif
  6715. /* if DhKey is not setup, do it now */
  6716. if (keyShareEntry->key == NULL) {
  6717. keyShareEntry->key = (DhKey*)XMALLOC(sizeof(DhKey), ssl->heap,
  6718. DYNAMIC_TYPE_DH);
  6719. if (keyShareEntry->key == NULL)
  6720. return MEMORY_E;
  6721. /* Setup Key */
  6722. ret = wc_InitDhKey_ex((DhKey*)keyShareEntry->key, ssl->heap, ssl->devId);
  6723. if (ret == 0) {
  6724. dhKey = (DhKey*)keyShareEntry->key;
  6725. /* Set key */
  6726. #ifdef HAVE_PUBLIC_FFDHE
  6727. ret = wc_DhSetKey(dhKey, params->p, params->p_len, params->g,
  6728. params->g_len);
  6729. #else
  6730. ret = wc_DhSetNamedKey(dhKey, keyShareEntry->group);
  6731. #endif
  6732. }
  6733. }
  6734. if (ret == 0
  6735. #ifdef WOLFSSL_ASYNC_CRYPT
  6736. && keyShareEntry->lastRet == 0 /* don't enter here if WC_PENDING_E */
  6737. #endif
  6738. ) {
  6739. #ifdef WOLFSSL_DEBUG_TLS
  6740. WOLFSSL_MSG("Peer DH Key");
  6741. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6742. #endif
  6743. ssl->options.dhKeySz = (word16)pSz;
  6744. /* Derive secret from private key and peer's public key. */
  6745. ret = DhAgree(ssl, dhKey,
  6746. (const byte*)keyShareEntry->privKey, keyShareEntry->keyLen, /* our private */
  6747. keyShareEntry->ke, keyShareEntry->keLen, /* peer's public key */
  6748. ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz, /* secret */
  6749. NULL, 0
  6750. );
  6751. #ifdef WOLFSSL_ASYNC_CRYPT
  6752. if (ret == WC_PENDING_E) {
  6753. return ret;
  6754. }
  6755. #endif
  6756. }
  6757. /* RFC 8446 Section 7.4.1:
  6758. * ... left-padded with zeros up to the size of the prime. ...
  6759. */
  6760. if (ret == 0 && (word32)ssl->options.dhKeySz > ssl->arrays->preMasterSz) {
  6761. word32 diff = (word32)ssl->options.dhKeySz - ssl->arrays->preMasterSz;
  6762. XMEMMOVE(ssl->arrays->preMasterSecret + diff,
  6763. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  6764. XMEMSET(ssl->arrays->preMasterSecret, 0, diff);
  6765. ssl->arrays->preMasterSz = ssl->options.dhKeySz;
  6766. }
  6767. /* done with key share, release resources */
  6768. if (dhKey)
  6769. wc_FreeDhKey(dhKey);
  6770. if (keyShareEntry->key) {
  6771. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_DH);
  6772. keyShareEntry->key = NULL;
  6773. }
  6774. if (keyShareEntry->privKey != NULL) {
  6775. XFREE(keyShareEntry->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6776. keyShareEntry->privKey = NULL;
  6777. }
  6778. if (keyShareEntry->pubKey != NULL) {
  6779. XFREE(keyShareEntry->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6780. keyShareEntry->pubKey = NULL;
  6781. }
  6782. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6783. keyShareEntry->ke = NULL;
  6784. #else
  6785. (void)ssl;
  6786. (void)keyShareEntry;
  6787. ret = PEER_KEY_ERROR;
  6788. WOLFSSL_ERROR_VERBOSE(ret);
  6789. #endif
  6790. return ret;
  6791. }
  6792. /* Process the X25519 key share extension on the client side.
  6793. *
  6794. * ssl The SSL/TLS object.
  6795. * keyShareEntry The key share entry object to use to calculate shared secret.
  6796. * returns 0 on success and other values indicate failure.
  6797. */
  6798. static int TLSX_KeyShare_ProcessX25519(WOLFSSL* ssl,
  6799. KeyShareEntry* keyShareEntry)
  6800. {
  6801. int ret;
  6802. #ifdef HAVE_CURVE25519
  6803. curve25519_key* key = (curve25519_key*)keyShareEntry->key;
  6804. curve25519_key* peerX25519Key;
  6805. #ifdef HAVE_ECC
  6806. if (ssl->peerEccKey != NULL) {
  6807. wc_ecc_free(ssl->peerEccKey);
  6808. ssl->peerEccKey = NULL;
  6809. ssl->peerEccKeyPresent = 0;
  6810. }
  6811. #endif
  6812. peerX25519Key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), ssl->heap,
  6813. DYNAMIC_TYPE_TLSX);
  6814. if (peerX25519Key == NULL) {
  6815. WOLFSSL_MSG("PeerEccKey Memory error");
  6816. return MEMORY_ERROR;
  6817. }
  6818. ret = wc_curve25519_init(peerX25519Key);
  6819. if (ret != 0) {
  6820. XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6821. return ret;
  6822. }
  6823. #ifdef WOLFSSL_DEBUG_TLS
  6824. WOLFSSL_MSG("Peer Curve25519 Key");
  6825. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6826. #endif
  6827. if (wc_curve25519_check_public(keyShareEntry->ke, keyShareEntry->keLen,
  6828. EC25519_LITTLE_ENDIAN) != 0) {
  6829. ret = ECC_PEERKEY_ERROR;
  6830. WOLFSSL_ERROR_VERBOSE(ret);
  6831. }
  6832. if (ret == 0) {
  6833. if (wc_curve25519_import_public_ex(keyShareEntry->ke,
  6834. keyShareEntry->keLen, peerX25519Key,
  6835. EC25519_LITTLE_ENDIAN) != 0) {
  6836. ret = ECC_PEERKEY_ERROR;
  6837. WOLFSSL_ERROR_VERBOSE(ret);
  6838. }
  6839. }
  6840. if (ret == 0) {
  6841. ssl->ecdhCurveOID = ECC_X25519_OID;
  6842. ret = wc_curve25519_shared_secret_ex(key, peerX25519Key,
  6843. ssl->arrays->preMasterSecret,
  6844. &ssl->arrays->preMasterSz,
  6845. EC25519_LITTLE_ENDIAN);
  6846. }
  6847. wc_curve25519_free(peerX25519Key);
  6848. XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6849. wc_curve25519_free((curve25519_key*)keyShareEntry->key);
  6850. if (keyShareEntry->key != NULL) {
  6851. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6852. keyShareEntry->key = NULL;
  6853. }
  6854. #else
  6855. (void)ssl;
  6856. (void)keyShareEntry;
  6857. ret = PEER_KEY_ERROR;
  6858. WOLFSSL_ERROR_VERBOSE(ret);
  6859. #endif /* HAVE_CURVE25519 */
  6860. return ret;
  6861. }
  6862. /* Process the X448 key share extension on the client side.
  6863. *
  6864. * ssl The SSL/TLS object.
  6865. * keyShareEntry The key share entry object to use to calculate shared secret.
  6866. * returns 0 on success and other values indicate failure.
  6867. */
  6868. static int TLSX_KeyShare_ProcessX448(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6869. {
  6870. int ret;
  6871. #ifdef HAVE_CURVE448
  6872. curve448_key* key = (curve448_key*)keyShareEntry->key;
  6873. curve448_key* peerX448Key;
  6874. #ifdef HAVE_ECC
  6875. if (ssl->peerEccKey != NULL) {
  6876. wc_ecc_free(ssl->peerEccKey);
  6877. ssl->peerEccKey = NULL;
  6878. ssl->peerEccKeyPresent = 0;
  6879. }
  6880. #endif
  6881. peerX448Key = (curve448_key*)XMALLOC(sizeof(curve448_key), ssl->heap,
  6882. DYNAMIC_TYPE_TLSX);
  6883. if (peerX448Key == NULL) {
  6884. WOLFSSL_MSG("PeerEccKey Memory error");
  6885. return MEMORY_ERROR;
  6886. }
  6887. ret = wc_curve448_init(peerX448Key);
  6888. if (ret != 0) {
  6889. XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6890. return ret;
  6891. }
  6892. #ifdef WOLFSSL_DEBUG_TLS
  6893. WOLFSSL_MSG("Peer Curve448 Key");
  6894. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6895. #endif
  6896. if (wc_curve448_check_public(keyShareEntry->ke, keyShareEntry->keLen,
  6897. EC448_LITTLE_ENDIAN) != 0) {
  6898. ret = ECC_PEERKEY_ERROR;
  6899. WOLFSSL_ERROR_VERBOSE(ret);
  6900. }
  6901. if (ret == 0) {
  6902. if (wc_curve448_import_public_ex(keyShareEntry->ke,
  6903. keyShareEntry->keLen, peerX448Key,
  6904. EC448_LITTLE_ENDIAN) != 0) {
  6905. ret = ECC_PEERKEY_ERROR;
  6906. WOLFSSL_ERROR_VERBOSE(ret);
  6907. }
  6908. }
  6909. if (ret == 0) {
  6910. ssl->ecdhCurveOID = ECC_X448_OID;
  6911. ret = wc_curve448_shared_secret_ex(key, peerX448Key,
  6912. ssl->arrays->preMasterSecret,
  6913. &ssl->arrays->preMasterSz,
  6914. EC448_LITTLE_ENDIAN);
  6915. }
  6916. wc_curve448_free(peerX448Key);
  6917. XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6918. wc_curve448_free((curve448_key*)keyShareEntry->key);
  6919. if (keyShareEntry->key != NULL) {
  6920. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6921. keyShareEntry->key = NULL;
  6922. }
  6923. #else
  6924. (void)ssl;
  6925. (void)keyShareEntry;
  6926. ret = PEER_KEY_ERROR;
  6927. WOLFSSL_ERROR_VERBOSE(ret);
  6928. #endif /* HAVE_CURVE448 */
  6929. return ret;
  6930. }
  6931. /* Process the ECC key share extension on the client side.
  6932. *
  6933. * ssl The SSL/TLS object.
  6934. * keyShareEntry The key share entry object to use to calculate shared secret.
  6935. * returns 0 on success and other values indicate failure.
  6936. */
  6937. static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6938. {
  6939. int ret = 0;
  6940. #ifdef HAVE_ECC
  6941. int curveId = ECC_CURVE_INVALID;
  6942. ecc_key* eccKey = (ecc_key*)keyShareEntry->key;
  6943. /* find supported curve */
  6944. switch (keyShareEntry->group) {
  6945. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  6946. #ifndef NO_ECC_SECP
  6947. case WOLFSSL_ECC_SECP256R1:
  6948. curveId = ECC_SECP256R1;
  6949. break;
  6950. #endif /* !NO_ECC_SECP */
  6951. #ifdef WOLFSSL_SM2
  6952. case WOLFSSL_ECC_SM2P256V1:
  6953. curveId = ECC_SM2P256V1;
  6954. break;
  6955. #endif
  6956. #endif
  6957. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  6958. #ifndef NO_ECC_SECP
  6959. case WOLFSSL_ECC_SECP384R1:
  6960. curveId = ECC_SECP384R1;
  6961. break;
  6962. #endif /* !NO_ECC_SECP */
  6963. #endif
  6964. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  6965. #ifndef NO_ECC_SECP
  6966. case WOLFSSL_ECC_SECP521R1:
  6967. curveId = ECC_SECP521R1;
  6968. break;
  6969. #endif /* !NO_ECC_SECP */
  6970. #endif
  6971. #if defined(HAVE_X448) && ECC_MIN_KEY_SZ <= 448
  6972. case WOLFSSL_ECC_X448:
  6973. curveId = ECC_X448;
  6974. break;
  6975. #endif
  6976. default:
  6977. /* unsupported curve */
  6978. WOLFSSL_ERROR_VERBOSE(ECC_PEERKEY_ERROR);
  6979. return ECC_PEERKEY_ERROR;
  6980. }
  6981. #ifdef WOLFSSL_ASYNC_CRYPT
  6982. if (keyShareEntry->lastRet == 0) /* don't enter here if WC_PENDING_E */
  6983. #endif
  6984. {
  6985. #ifdef WOLFSSL_DEBUG_TLS
  6986. WOLFSSL_MSG("Peer ECC Key");
  6987. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6988. #endif
  6989. if (ssl->peerEccKey != NULL) {
  6990. wc_ecc_free(ssl->peerEccKey);
  6991. XFREE(ssl->peerEccKey, ssl->heap, DYNAMIC_TYPE_ECC);
  6992. ssl->peerEccKeyPresent = 0;
  6993. }
  6994. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  6995. ret = tsip_Tls13GenSharedSecret(ssl, keyShareEntry);
  6996. if (ret != CRYPTOCB_UNAVAILABLE) {
  6997. return ret;
  6998. }
  6999. ret = 0;
  7000. #endif
  7001. ssl->peerEccKey = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
  7002. DYNAMIC_TYPE_ECC);
  7003. if (ssl->peerEccKey == NULL) {
  7004. WOLFSSL_MSG("PeerEccKey Memory error");
  7005. ret = MEMORY_ERROR;
  7006. }
  7007. if (ret == 0) {
  7008. ret = wc_ecc_init_ex(ssl->peerEccKey, ssl->heap, ssl->devId);
  7009. }
  7010. /* Point is validated by import function. */
  7011. if (ret == 0) {
  7012. ret = wc_ecc_import_x963_ex(keyShareEntry->ke, keyShareEntry->keLen,
  7013. ssl->peerEccKey, curveId);
  7014. if (ret != 0) {
  7015. ret = ECC_PEERKEY_ERROR;
  7016. WOLFSSL_ERROR_VERBOSE(ret);
  7017. }
  7018. }
  7019. if (ret == 0) {
  7020. ssl->ecdhCurveOID = ssl->peerEccKey->dp->oidSum;
  7021. ssl->peerEccKeyPresent = 1;
  7022. }
  7023. }
  7024. if (ret == 0 && eccKey == NULL)
  7025. ret = BAD_FUNC_ARG;
  7026. if (ret == 0) {
  7027. ret = EccSharedSecret(ssl, eccKey, ssl->peerEccKey,
  7028. keyShareEntry->ke, &keyShareEntry->keLen,
  7029. ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz,
  7030. ssl->options.side
  7031. );
  7032. #ifdef WOLFSSL_ASYNC_CRYPT
  7033. if (ret == WC_PENDING_E)
  7034. return ret;
  7035. #endif
  7036. }
  7037. /* done with key share, release resources */
  7038. if (ssl->peerEccKey != NULL
  7039. #ifdef HAVE_PK_CALLBACKS
  7040. && ssl->ctx->EccSharedSecretCb == NULL
  7041. #endif
  7042. ) {
  7043. wc_ecc_free(ssl->peerEccKey);
  7044. XFREE(ssl->peerEccKey, ssl->heap, DYNAMIC_TYPE_ECC);
  7045. ssl->peerEccKey = NULL;
  7046. ssl->peerEccKeyPresent = 0;
  7047. }
  7048. if (keyShareEntry->key) {
  7049. wc_ecc_free((ecc_key*)keyShareEntry->key);
  7050. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_ECC);
  7051. keyShareEntry->key = NULL;
  7052. }
  7053. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7054. keyShareEntry->ke = NULL;
  7055. #else
  7056. (void)ssl;
  7057. (void)keyShareEntry;
  7058. ret = PEER_KEY_ERROR;
  7059. WOLFSSL_ERROR_VERBOSE(ret);
  7060. #endif /* HAVE_ECC */
  7061. return ret;
  7062. }
  7063. #ifdef HAVE_PQC
  7064. /* Process the Kyber key share extension on the client side.
  7065. *
  7066. * ssl The SSL/TLS object.
  7067. * keyShareEntry The key share entry object to use to calculate shared secret.
  7068. * returns 0 on success and other values indicate failure.
  7069. */
  7070. static int TLSX_KeyShare_ProcessPqc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  7071. {
  7072. int ret = 0;
  7073. int type;
  7074. KyberKey kem[1];
  7075. byte* sharedSecret = NULL;
  7076. word32 sharedSecretLen = 0;
  7077. int oqs_group = 0;
  7078. int ecc_group = 0;
  7079. ecc_key eccpubkey;
  7080. word32 outlen = 0;
  7081. word32 privSz = 0;
  7082. word32 ctSz = 0;
  7083. word32 ssSz = 0;
  7084. if (keyShareEntry->ke == NULL) {
  7085. WOLFSSL_MSG("Invalid OQS algorithm specified.");
  7086. return BAD_FUNC_ARG;
  7087. }
  7088. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7089. /* I am the server, the shared secret has already been generated and
  7090. * is in keyShareEntry->ke; copy it to the pre-master secret
  7091. * pre-allocated buffer. */
  7092. if (keyShareEntry->keLen > ENCRYPT_LEN) {
  7093. WOLFSSL_MSG("shared secret is too long.");
  7094. return LENGTH_ERROR;
  7095. }
  7096. XMEMCPY(ssl->arrays->preMasterSecret, keyShareEntry->ke,
  7097. keyShareEntry->keLen);
  7098. ssl->arrays->preMasterSz = keyShareEntry->keLen;
  7099. XFREE(keyShareEntry->ke, sl->heap, DYNAMIC_TYPE_SECRET)
  7100. keyShareEntry->ke = NULL;
  7101. keyShareEntry->keLen = 0;
  7102. return 0;
  7103. }
  7104. /* I am the client, the ciphertext is in keyShareEntry->ke */
  7105. findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group);
  7106. ret = kyber_id2type(oqs_group, &type);
  7107. if (ret != 0) {
  7108. WOLFSSL_MSG("Invalid OQS algorithm specified.");
  7109. ret = BAD_FUNC_ARG;
  7110. }
  7111. if (ret == 0) {
  7112. ret = wc_KyberKey_Init(type, kem, ssl->heap, INVALID_DEVID);
  7113. if (ret != 0) {
  7114. WOLFSSL_MSG("Error creating Kyber KEM");
  7115. }
  7116. }
  7117. if (ret == 0) {
  7118. ret = wc_KyberKey_SharedSecretSize(kem, &ssSz);
  7119. }
  7120. if (ret == 0) {
  7121. sharedSecretLen = ssSz;
  7122. switch (ecc_group) {
  7123. case WOLFSSL_ECC_SECP256R1:
  7124. sharedSecretLen += 32;
  7125. outlen = 32;
  7126. break;
  7127. case WOLFSSL_ECC_SECP384R1:
  7128. sharedSecretLen += 48;
  7129. outlen = 48;
  7130. break;
  7131. case WOLFSSL_ECC_SECP521R1:
  7132. sharedSecretLen += 66;
  7133. outlen = 66;
  7134. break;
  7135. default:
  7136. break;
  7137. }
  7138. ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId);
  7139. if (ret != 0) {
  7140. WOLFSSL_MSG("Memory allocation error.");
  7141. ret = MEMORY_E;
  7142. }
  7143. }
  7144. if (ret == 0) {
  7145. sharedSecret = (byte*)XMALLOC(sharedSecretLen, ssl->heap,
  7146. DYNAMIC_TYPE_TLSX);
  7147. if (sharedSecret == NULL) {
  7148. WOLFSSL_MSG("Memory allocation error.");
  7149. ret = MEMORY_E;
  7150. }
  7151. }
  7152. if (ret == 0) {
  7153. ret = wc_KyberKey_CipherTextSize(kem, &ctSz);
  7154. }
  7155. if (ret == 0) {
  7156. ret = wc_KyberKey_PrivateKeySize(kem, &privSz);
  7157. }
  7158. if (ret == 0) {
  7159. ret = wc_KyberKey_DecodePrivateKey(kem, keyShareEntry->privKey, privSz);
  7160. }
  7161. if (ret == 0) {
  7162. ret = wc_KyberKey_Decapsulate(kem, sharedSecret + outlen,
  7163. keyShareEntry->ke + keyShareEntry->keLen - ctSz, ctSz);
  7164. if (ret != 0) {
  7165. WOLFSSL_MSG("wc_KyberKey decapsulation failure.");
  7166. ret = BAD_FUNC_ARG;
  7167. }
  7168. }
  7169. if (ecc_group != 0) {
  7170. if (ret == 0) {
  7171. /* Point is validated by import function. */
  7172. ret = wc_ecc_import_x963(keyShareEntry->ke,
  7173. keyShareEntry->keLen - ctSz,
  7174. &eccpubkey);
  7175. if (ret != 0) {
  7176. WOLFSSL_MSG("ECC Public key import error.");
  7177. }
  7178. }
  7179. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  7180. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  7181. !defined(HAVE_SELFTEST)
  7182. if (ret == 0) {
  7183. ret = wc_ecc_set_rng(keyShareEntry->key, ssl->rng);
  7184. if (ret != 0) {
  7185. WOLFSSL_MSG("Failure to set the ECC private key RNG.");
  7186. }
  7187. }
  7188. #endif
  7189. if (ret == 0) {
  7190. PRIVATE_KEY_UNLOCK();
  7191. ret = wc_ecc_shared_secret(keyShareEntry->key, &eccpubkey,
  7192. sharedSecret, &outlen);
  7193. PRIVATE_KEY_LOCK();
  7194. if (outlen != sharedSecretLen - ssSz) {
  7195. WOLFSSL_MSG("ECC shared secret derivation error.");
  7196. ret = BAD_FUNC_ARG;
  7197. }
  7198. }
  7199. }
  7200. if ((ret == 0) && (sharedSecretLen > ENCRYPT_LEN)) {
  7201. WOLFSSL_MSG("shared secret is too long.");
  7202. ret = LENGTH_ERROR;
  7203. }
  7204. if (ret == 0) {
  7205. /* Copy the shared secret to the pre-master secret pre-allocated
  7206. * buffer. */
  7207. XMEMCPY(ssl->arrays->preMasterSecret, sharedSecret, sharedSecretLen);
  7208. ssl->arrays->preMasterSz = (word32) sharedSecretLen;
  7209. }
  7210. if (sharedSecret != NULL) {
  7211. XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  7212. }
  7213. wc_ecc_free(&eccpubkey);
  7214. wc_KyberKey_Free(kem);
  7215. return ret;
  7216. }
  7217. #endif /* HAVE_PQC */
  7218. /* Process the key share extension on the client side.
  7219. *
  7220. * ssl The SSL/TLS object.
  7221. * keyShareEntry The key share entry object to use to calculate shared secret.
  7222. * returns 0 on success and other values indicate failure.
  7223. */
  7224. static int TLSX_KeyShare_Process(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  7225. {
  7226. int ret;
  7227. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  7228. ssl->session->namedGroup = keyShareEntry->group;
  7229. #endif
  7230. /* reset the pre master secret size */
  7231. if (ssl->arrays->preMasterSz == 0)
  7232. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  7233. /* Use Key Share Data from server. */
  7234. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(keyShareEntry->group))
  7235. ret = TLSX_KeyShare_ProcessDh(ssl, keyShareEntry);
  7236. else if (keyShareEntry->group == WOLFSSL_ECC_X25519)
  7237. ret = TLSX_KeyShare_ProcessX25519(ssl, keyShareEntry);
  7238. else if (keyShareEntry->group == WOLFSSL_ECC_X448)
  7239. ret = TLSX_KeyShare_ProcessX448(ssl, keyShareEntry);
  7240. #ifdef HAVE_PQC
  7241. else if (WOLFSSL_NAMED_GROUP_IS_PQC(keyShareEntry->group))
  7242. ret = TLSX_KeyShare_ProcessPqc(ssl, keyShareEntry);
  7243. #endif
  7244. else
  7245. ret = TLSX_KeyShare_ProcessEcc(ssl, keyShareEntry);
  7246. #ifdef WOLFSSL_DEBUG_TLS
  7247. if (ret == 0) {
  7248. WOLFSSL_MSG("KE Secret");
  7249. WOLFSSL_BUFFER(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  7250. }
  7251. #endif
  7252. #ifdef WOLFSSL_ASYNC_CRYPT
  7253. keyShareEntry->lastRet = ret;
  7254. #endif
  7255. return ret;
  7256. }
  7257. /* Parse an entry of the KeyShare extension.
  7258. *
  7259. * ssl The SSL/TLS object.
  7260. * input The extension data.
  7261. * length The length of the extension data.
  7262. * kse The new key share entry object.
  7263. * returns a positive number to indicate amount of data parsed and a negative
  7264. * number on error.
  7265. */
  7266. static int TLSX_KeyShareEntry_Parse(const WOLFSSL* ssl, const byte* input,
  7267. word16 length, KeyShareEntry **kse, TLSX** extensions)
  7268. {
  7269. int ret;
  7270. word16 group;
  7271. word16 keLen;
  7272. int offset = 0;
  7273. byte* ke;
  7274. if (length < OPAQUE16_LEN + OPAQUE16_LEN)
  7275. return BUFFER_ERROR;
  7276. /* Named group */
  7277. ato16(&input[offset], &group);
  7278. offset += OPAQUE16_LEN;
  7279. /* Key exchange data - public key. */
  7280. ato16(&input[offset], &keLen);
  7281. offset += OPAQUE16_LEN;
  7282. if (keLen == 0)
  7283. return INVALID_PARAMETER;
  7284. if (keLen > length - offset)
  7285. return BUFFER_ERROR;
  7286. #ifdef HAVE_PQC
  7287. if (WOLFSSL_NAMED_GROUP_IS_PQC(group) &&
  7288. ssl->options.side == WOLFSSL_SERVER_END) {
  7289. /* For KEMs, the public key is not stored. Casting away const because
  7290. * we know for KEMs, it will be read-only.*/
  7291. ke = (byte *)&input[offset];
  7292. } else
  7293. #endif
  7294. {
  7295. /* Store a copy in the key share object. */
  7296. ke = (byte*)XMALLOC(keLen, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7297. if (ke == NULL)
  7298. return MEMORY_E;
  7299. XMEMCPY(ke, &input[offset], keLen);
  7300. }
  7301. /* Populate a key share object in the extension. */
  7302. ret = TLSX_KeyShare_Use(ssl, group, keLen, ke, kse, extensions);
  7303. if (ret != 0) {
  7304. if (ke != &input[offset]) {
  7305. XFREE(ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7306. }
  7307. return ret;
  7308. }
  7309. /* Total length of the parsed data. */
  7310. return offset + keLen;
  7311. }
  7312. /* Searches the groups sent for the specified named group.
  7313. *
  7314. * ssl SSL/TLS object.
  7315. * name Group name to match.
  7316. * returns 1 when the extension has the group name and 0 otherwise.
  7317. */
  7318. static int TLSX_KeyShare_Find(WOLFSSL* ssl, word16 group)
  7319. {
  7320. TLSX* extension;
  7321. KeyShareEntry* list;
  7322. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  7323. if (extension == NULL) {
  7324. extension = TLSX_Find(ssl->ctx->extensions, TLSX_KEY_SHARE);
  7325. if (extension == NULL)
  7326. return 0;
  7327. }
  7328. list = (KeyShareEntry*)extension->data;
  7329. while (list != NULL) {
  7330. if (list->group == group)
  7331. return 1;
  7332. list = list->next;
  7333. }
  7334. return 0;
  7335. }
  7336. /* Searches the supported groups extension for the specified named group.
  7337. *
  7338. * ssl The SSL/TLS object.
  7339. * name The group name to match.
  7340. * returns 1 when the extension has the group name and 0 otherwise.
  7341. */
  7342. static int TLSX_SupportedGroups_Find(const WOLFSSL* ssl, word16 name,
  7343. TLSX* extensions)
  7344. {
  7345. #ifdef HAVE_SUPPORTED_CURVES
  7346. TLSX* extension;
  7347. SupportedCurve* curve = NULL;
  7348. if ((extension = TLSX_Find(extensions,
  7349. TLSX_SUPPORTED_GROUPS)) == NULL) {
  7350. if ((extension = TLSX_Find(ssl->ctx->extensions,
  7351. TLSX_SUPPORTED_GROUPS)) == NULL) {
  7352. return 0;
  7353. }
  7354. }
  7355. for (curve = (SupportedCurve*)extension->data; curve; curve = curve->next) {
  7356. if (curve->name == name)
  7357. return 1;
  7358. }
  7359. #endif
  7360. (void)ssl;
  7361. (void)name;
  7362. return 0;
  7363. }
  7364. int TLSX_KeyShare_Parse_ClientHello(const WOLFSSL* ssl,
  7365. const byte* input, word16 length, TLSX** extensions)
  7366. {
  7367. int ret;
  7368. int offset = 0;
  7369. word16 len;
  7370. TLSX* extension;
  7371. /* Add a KeyShare extension if it doesn't exist even if peer sent no
  7372. * entries. The presence of this extension signals that the peer can be
  7373. * negotiated with. */
  7374. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7375. if (extension == NULL) {
  7376. /* Push new KeyShare extension. */
  7377. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7378. if (ret != 0)
  7379. return ret;
  7380. }
  7381. if (length < OPAQUE16_LEN)
  7382. return BUFFER_ERROR;
  7383. /* ClientHello contains zero or more key share entries. */
  7384. ato16(input, &len);
  7385. if (len != length - OPAQUE16_LEN)
  7386. return BUFFER_ERROR;
  7387. offset += OPAQUE16_LEN;
  7388. while (offset < (int)length) {
  7389. ret = TLSX_KeyShareEntry_Parse(ssl, &input[offset],
  7390. length - (word16)offset, NULL, extensions);
  7391. if (ret < 0)
  7392. return ret;
  7393. offset += ret;
  7394. }
  7395. return 0;
  7396. }
  7397. /* Parse the KeyShare extension.
  7398. * Different formats in different messages.
  7399. *
  7400. * ssl The SSL/TLS object.
  7401. * input The extension data.
  7402. * length The length of the extension data.
  7403. * msgType The type of the message this extension is being parsed from.
  7404. * returns 0 on success and other values indicate failure.
  7405. */
  7406. int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  7407. byte msgType)
  7408. {
  7409. int ret;
  7410. KeyShareEntry *keyShareEntry = NULL;
  7411. word16 group;
  7412. if (msgType == client_hello) {
  7413. ret = TLSX_KeyShare_Parse_ClientHello(ssl, input, length,
  7414. &ssl->extensions);
  7415. }
  7416. else if (msgType == server_hello) {
  7417. int len;
  7418. if (length < OPAQUE16_LEN)
  7419. return BUFFER_ERROR;
  7420. /* The data is the named group the server wants to use. */
  7421. ato16(input, &group);
  7422. /* Check the selected group was supported by ClientHello extensions. */
  7423. if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) {
  7424. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7425. return BAD_KEY_SHARE_DATA;
  7426. }
  7427. /* Check if the group was sent. */
  7428. if (!TLSX_KeyShare_Find(ssl, group)) {
  7429. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7430. return BAD_KEY_SHARE_DATA;
  7431. }
  7432. /* ServerHello contains one key share entry. */
  7433. len = TLSX_KeyShareEntry_Parse(ssl, input, length, &keyShareEntry,
  7434. &ssl->extensions);
  7435. if (len != (int)length)
  7436. return BUFFER_ERROR;
  7437. /* Not in list sent if there isn't a private key. */
  7438. if (keyShareEntry == NULL || (keyShareEntry->key == NULL
  7439. #if !defined(NO_DH) || defined(HAVE_PQC)
  7440. && keyShareEntry->privKey == NULL
  7441. #endif
  7442. )) {
  7443. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7444. return BAD_KEY_SHARE_DATA;
  7445. }
  7446. /* Process the entry to calculate the secret. */
  7447. ret = TLSX_KeyShare_Process(ssl, keyShareEntry);
  7448. if (ret == 0)
  7449. ssl->session->namedGroup = ssl->namedGroup = group;
  7450. }
  7451. else if (msgType == hello_retry_request) {
  7452. if (length != OPAQUE16_LEN)
  7453. return BUFFER_ERROR;
  7454. /* The data is the named group the server wants to use. */
  7455. ato16(input, &group);
  7456. #ifdef WOLFSSL_ASYNC_CRYPT
  7457. /* only perform find and clear TLSX if not returning from async */
  7458. if (ssl->error != WC_PENDING_E)
  7459. #endif
  7460. {
  7461. /* Check the selected group was supported by ClientHello extensions. */
  7462. if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) {
  7463. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7464. return BAD_KEY_SHARE_DATA;
  7465. }
  7466. /* Check if the group was sent. */
  7467. if (TLSX_KeyShare_Find(ssl, group)) {
  7468. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7469. return BAD_KEY_SHARE_DATA;
  7470. }
  7471. /* Clear out unusable key shares. */
  7472. ret = TLSX_KeyShare_Empty(ssl);
  7473. if (ret != 0)
  7474. return ret;
  7475. }
  7476. #ifdef HAVE_PQC
  7477. /* For post-quantum groups, do this in TLSX_PopulateExtensions(). */
  7478. if (!WOLFSSL_NAMED_GROUP_IS_PQC(group))
  7479. #endif
  7480. ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL, &ssl->extensions);
  7481. if (ret == 0)
  7482. ssl->session->namedGroup = ssl->namedGroup = group;
  7483. }
  7484. else {
  7485. /* Not a message type that is allowed to have this extension. */
  7486. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  7487. return SANITY_MSG_E;
  7488. }
  7489. return ret;
  7490. }
  7491. /* Create a new key share entry and put it into the list.
  7492. *
  7493. * list The linked list of key share entries.
  7494. * group The named group.
  7495. * heap The memory to allocate with.
  7496. * keyShareEntry The new key share entry object.
  7497. * returns 0 on success and other values indicate failure.
  7498. */
  7499. static int TLSX_KeyShare_New(KeyShareEntry** list, int group, void *heap,
  7500. KeyShareEntry** keyShareEntry)
  7501. {
  7502. KeyShareEntry* kse;
  7503. KeyShareEntry** next;
  7504. kse = (KeyShareEntry*)XMALLOC(sizeof(KeyShareEntry), heap,
  7505. DYNAMIC_TYPE_TLSX);
  7506. if (kse == NULL)
  7507. return MEMORY_E;
  7508. XMEMSET(kse, 0, sizeof(*kse));
  7509. kse->group = (word16)group;
  7510. /* Add it to the back and maintain the links. */
  7511. while (*list != NULL) {
  7512. /* Assign to temporary to work around compiler bug found by customer. */
  7513. next = &((*list)->next);
  7514. list = next;
  7515. }
  7516. *list = kse;
  7517. *keyShareEntry = kse;
  7518. (void)heap;
  7519. return 0;
  7520. }
  7521. #ifdef HAVE_PQC
  7522. static int server_generate_pqc_ciphertext(WOLFSSL* ssl,
  7523. KeyShareEntry* keyShareEntry, byte* data, word16 len)
  7524. {
  7525. /* I am the server. The data parameter is the client's public key. I need
  7526. * to generate the public information (AKA ciphertext) and shared secret
  7527. * here. Note the "public information" is equivalent to a the public key in
  7528. * key exchange parlance. That's why it is being assigned to pubKey.
  7529. */
  7530. int type;
  7531. KyberKey kem[1];
  7532. byte* sharedSecret = NULL;
  7533. byte* ciphertext = NULL;
  7534. int ret = 0;
  7535. int oqs_group = 0;
  7536. int ecc_group = 0;
  7537. KeyShareEntry *ecc_kse = NULL;
  7538. ecc_key eccpubkey;
  7539. word32 outlen = 0;
  7540. word32 pubSz = 0;
  7541. word32 ctSz = 0;
  7542. word32 ssSz = 0;
  7543. findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group);
  7544. ret = kyber_id2type(oqs_group, &type);
  7545. if (ret != 0) {
  7546. WOLFSSL_MSG("Invalid Kyber algorithm specified.");
  7547. ret = BAD_FUNC_ARG;
  7548. }
  7549. if (ret == 0) {
  7550. ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId);
  7551. if (ret != 0) {
  7552. WOLFSSL_MSG("Could not do ECC public key initialization.");
  7553. ret = MEMORY_E;
  7554. }
  7555. }
  7556. if (ret == 0) {
  7557. ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap,
  7558. DYNAMIC_TYPE_TLSX);
  7559. if (ecc_kse == NULL) {
  7560. WOLFSSL_MSG("ecc_kse memory allocation failure");
  7561. ret = MEMORY_ERROR;
  7562. }
  7563. }
  7564. if (ret == 0) {
  7565. XMEMSET(ecc_kse, 0, sizeof(*ecc_kse));
  7566. }
  7567. if (ret == 0 && ecc_group != 0) {
  7568. ecc_kse->group = ecc_group;
  7569. ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse);
  7570. if (ret != 0) {
  7571. /* No message, TLSX_KeyShare_GenEccKey() will do it. */
  7572. return ret;
  7573. }
  7574. ret = 0;
  7575. }
  7576. if (ret == 0) {
  7577. ret = wc_KyberKey_Init(type, kem, ssl->heap, INVALID_DEVID);
  7578. if (ret != 0) {
  7579. WOLFSSL_MSG("Error creating Kyber KEM");
  7580. }
  7581. }
  7582. if (ret == 0) {
  7583. ret = wc_KyberKey_PublicKeySize(kem, &pubSz);
  7584. }
  7585. if (ret == 0) {
  7586. ret = wc_KyberKey_CipherTextSize(kem, &ctSz);
  7587. }
  7588. if (ret == 0) {
  7589. ret = wc_KyberKey_SharedSecretSize(kem, &ssSz);
  7590. }
  7591. if (ret == 0 && len != pubSz + ecc_kse->pubKeyLen) {
  7592. WOLFSSL_MSG("Invalid public key.");
  7593. ret = BAD_FUNC_ARG;
  7594. }
  7595. if (ret == 0) {
  7596. sharedSecret = (byte*)XMALLOC(ecc_kse->keyLen + ssSz, ssl->heap,
  7597. DYNAMIC_TYPE_TLSX);
  7598. ciphertext = (byte*)XMALLOC(ecc_kse->pubKeyLen + ctSz, ssl->heap,
  7599. DYNAMIC_TYPE_TLSX);
  7600. if (sharedSecret == NULL || ciphertext == NULL) {
  7601. WOLFSSL_MSG("Ciphertext/shared secret memory allocation failure.");
  7602. ret = MEMORY_E;
  7603. }
  7604. }
  7605. if (ecc_group != 0) {
  7606. if (ret == 0) {
  7607. /* Point is validated by import function. */
  7608. ret = wc_ecc_import_x963(data, len - pubSz, &eccpubkey);
  7609. if (ret != 0) {
  7610. WOLFSSL_MSG("Bad ECC public key.");
  7611. }
  7612. }
  7613. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  7614. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  7615. !defined(HAVE_SELFTEST)
  7616. if (ret == 0) {
  7617. ret = wc_ecc_set_rng(ecc_kse->key, ssl->rng);
  7618. }
  7619. #endif
  7620. if (ret == 0) {
  7621. outlen = ecc_kse->keyLen;
  7622. PRIVATE_KEY_UNLOCK();
  7623. ret = wc_ecc_shared_secret(ecc_kse->key, &eccpubkey,
  7624. sharedSecret,
  7625. &outlen);
  7626. PRIVATE_KEY_LOCK();
  7627. if (outlen != ecc_kse->keyLen) {
  7628. WOLFSSL_MSG("Data length mismatch.");
  7629. ret = BAD_FUNC_ARG;
  7630. }
  7631. }
  7632. }
  7633. if (ret == 0) {
  7634. ret = wc_KyberKey_DecodePublicKey(kem, data + ecc_kse->pubKeyLen,
  7635. pubSz);
  7636. }
  7637. if (ret == 0) {
  7638. ret = wc_KyberKey_Encapsulate(kem, ciphertext + ecc_kse->pubKeyLen,
  7639. sharedSecret + outlen, ssl->rng);
  7640. if (ret != 0) {
  7641. WOLFSSL_MSG("wc_KyberKey encapsulation failure.");
  7642. }
  7643. }
  7644. if (ret == 0) {
  7645. if (keyShareEntry->ke != NULL) {
  7646. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7647. }
  7648. keyShareEntry->ke = sharedSecret;
  7649. keyShareEntry->keLen = outlen + ssSz;
  7650. sharedSecret = NULL;
  7651. XMEMCPY(ciphertext, ecc_kse->pubKey, ecc_kse->pubKeyLen);
  7652. keyShareEntry->pubKey = ciphertext;
  7653. keyShareEntry->pubKeyLen = (word32)(ecc_kse->pubKeyLen + ctSz);
  7654. ciphertext = NULL;
  7655. /* Set namedGroup so wolfSSL_get_curve_name() can function properly on
  7656. * the server side. */
  7657. ssl->namedGroup = keyShareEntry->group;
  7658. }
  7659. TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap);
  7660. if (sharedSecret != NULL)
  7661. XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_TLSX);
  7662. if (ciphertext != NULL)
  7663. XFREE(ciphertext, ssl->heap, DYNAMIC_TYPE_TLSX);
  7664. wc_ecc_free(&eccpubkey);
  7665. wc_KyberKey_Free(kem);
  7666. return ret;
  7667. }
  7668. #endif /* HAVE_PQC */
  7669. /* Use the data to create a new key share object in the extensions.
  7670. *
  7671. * ssl The SSL/TLS object.
  7672. * group The named group.
  7673. * len The length of the public key data.
  7674. * data The public key data.
  7675. * kse The new key share entry object.
  7676. * returns 0 on success and other values indicate failure.
  7677. */
  7678. int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group, word16 len, byte* data,
  7679. KeyShareEntry **kse, TLSX** extensions)
  7680. {
  7681. int ret = 0;
  7682. TLSX* extension;
  7683. KeyShareEntry* keyShareEntry = NULL;
  7684. /* Find the KeyShare extension if it exists. */
  7685. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7686. if (extension == NULL) {
  7687. /* Push new KeyShare extension. */
  7688. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7689. if (ret != 0)
  7690. return ret;
  7691. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7692. if (extension == NULL)
  7693. return MEMORY_E;
  7694. }
  7695. extension->resp = 0;
  7696. /* Try to find the key share entry with this group. */
  7697. keyShareEntry = (KeyShareEntry*)extension->data;
  7698. while (keyShareEntry != NULL) {
  7699. if (keyShareEntry->group == group)
  7700. break;
  7701. keyShareEntry = keyShareEntry->next;
  7702. }
  7703. /* Create a new key share entry if not found. */
  7704. if (keyShareEntry == NULL) {
  7705. ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, group,
  7706. ssl->heap, &keyShareEntry);
  7707. if (ret != 0)
  7708. return ret;
  7709. }
  7710. #ifdef HAVE_PQC
  7711. if (WOLFSSL_NAMED_GROUP_IS_PQC(group) &&
  7712. ssl->options.side == WOLFSSL_SERVER_END) {
  7713. ret = server_generate_pqc_ciphertext((WOLFSSL*)ssl, keyShareEntry, data,
  7714. len);
  7715. if (ret != 0)
  7716. return ret;
  7717. }
  7718. else
  7719. #endif
  7720. if (data != NULL) {
  7721. if (keyShareEntry->ke != NULL) {
  7722. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7723. }
  7724. keyShareEntry->ke = data;
  7725. keyShareEntry->keLen = len;
  7726. }
  7727. else {
  7728. /* Generate a key pair. Casting to non-const since changes inside are
  7729. * minimal but would require an extensive redesign to refactor. Also
  7730. * this path shouldn't be taken when parsing a ClientHello in stateless
  7731. * mode. */
  7732. ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, keyShareEntry);
  7733. if (ret != 0)
  7734. return ret;
  7735. }
  7736. if (kse != NULL)
  7737. *kse = keyShareEntry;
  7738. return 0;
  7739. }
  7740. /* Set an empty Key Share extension.
  7741. *
  7742. * ssl The SSL/TLS object.
  7743. * returns 0 on success and other values indicate failure.
  7744. */
  7745. int TLSX_KeyShare_Empty(WOLFSSL* ssl)
  7746. {
  7747. int ret = 0;
  7748. TLSX* extension;
  7749. /* Find the KeyShare extension if it exists. */
  7750. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  7751. if (extension == NULL) {
  7752. /* Push new KeyShare extension. */
  7753. ret = TLSX_Push(&ssl->extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7754. }
  7755. else if (extension->data != NULL) {
  7756. TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap);
  7757. extension->data = NULL;
  7758. }
  7759. return ret;
  7760. }
  7761. /* Returns whether this group is supported.
  7762. *
  7763. * namedGroup The named group to check.
  7764. * returns 1 when supported or 0 otherwise.
  7765. */
  7766. static int TLSX_KeyShare_IsSupported(int namedGroup)
  7767. {
  7768. switch (namedGroup) {
  7769. #ifdef HAVE_FFDHE_2048
  7770. case WOLFSSL_FFDHE_2048:
  7771. break;
  7772. #endif
  7773. #ifdef HAVE_FFDHE_3072
  7774. case WOLFSSL_FFDHE_3072:
  7775. break;
  7776. #endif
  7777. #ifdef HAVE_FFDHE_4096
  7778. case WOLFSSL_FFDHE_4096:
  7779. break;
  7780. #endif
  7781. #ifdef HAVE_FFDHE_6144
  7782. case WOLFSSL_FFDHE_6144:
  7783. break;
  7784. #endif
  7785. #ifdef HAVE_FFDHE_8192
  7786. case WOLFSSL_FFDHE_8192:
  7787. break;
  7788. #endif
  7789. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  7790. #ifdef HAVE_ECC_KOBLITZ
  7791. case WOLFSSL_ECC_SECP256K1:
  7792. break;
  7793. #endif
  7794. #ifndef NO_ECC_SECP
  7795. case WOLFSSL_ECC_SECP256R1:
  7796. break;
  7797. #endif /* !NO_ECC_SECP */
  7798. #ifdef HAVE_ECC_BRAINPOOL
  7799. case WOLFSSL_ECC_BRAINPOOLP256R1:
  7800. break;
  7801. #endif
  7802. #ifdef WOLFSSL_SM2
  7803. case WOLFSSL_ECC_SM2P256V1:
  7804. break;
  7805. #endif /* WOLFSSL_SM2 */
  7806. #endif
  7807. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  7808. case WOLFSSL_ECC_X25519:
  7809. break;
  7810. #endif
  7811. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  7812. case WOLFSSL_ECC_X448:
  7813. break;
  7814. #endif
  7815. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  7816. #ifndef NO_ECC_SECP
  7817. case WOLFSSL_ECC_SECP384R1:
  7818. break;
  7819. #endif /* !NO_ECC_SECP */
  7820. #ifdef HAVE_ECC_BRAINPOOL
  7821. case WOLFSSL_ECC_BRAINPOOLP384R1:
  7822. break;
  7823. #endif
  7824. #endif
  7825. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  7826. #ifndef NO_ECC_SECP
  7827. case WOLFSSL_ECC_SECP521R1:
  7828. break;
  7829. #endif /* !NO_ECC_SECP */
  7830. #endif
  7831. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  7832. #ifdef HAVE_ECC_KOBLITZ
  7833. case WOLFSSL_ECC_SECP160K1:
  7834. break;
  7835. #endif
  7836. #ifndef NO_ECC_SECP
  7837. case WOLFSSL_ECC_SECP160R1:
  7838. break;
  7839. #endif
  7840. #ifdef HAVE_ECC_SECPR2
  7841. case WOLFSSL_ECC_SECP160R2:
  7842. break;
  7843. #endif
  7844. #endif
  7845. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  7846. #ifdef HAVE_ECC_KOBLITZ
  7847. case WOLFSSL_ECC_SECP192K1:
  7848. break;
  7849. #endif
  7850. #ifndef NO_ECC_SECP
  7851. case WOLFSSL_ECC_SECP192R1:
  7852. break;
  7853. #endif
  7854. #endif
  7855. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  7856. #ifdef HAVE_ECC_KOBLITZ
  7857. case WOLFSSL_ECC_SECP224K1:
  7858. break;
  7859. #endif
  7860. #ifndef NO_ECC_SECP
  7861. case WOLFSSL_ECC_SECP224R1:
  7862. break;
  7863. #endif
  7864. #endif
  7865. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  7866. #ifdef HAVE_ECC_BRAINPOOL
  7867. case WOLFSSL_ECC_BRAINPOOLP512R1:
  7868. break;
  7869. #endif
  7870. #endif
  7871. #ifdef HAVE_PQC
  7872. #ifdef WOLFSSL_WC_KYBER
  7873. #ifdef WOLFSSL_KYBER512
  7874. case WOLFSSL_KYBER_LEVEL1:
  7875. #endif
  7876. #ifdef WOLFSSL_KYBER768
  7877. case WOLFSSL_KYBER_LEVEL3:
  7878. #endif
  7879. #ifdef WOLFSSL_KYBER1024
  7880. case WOLFSSL_KYBER_LEVEL5:
  7881. #endif
  7882. break;
  7883. #elif defined(HAVE_LIBOQS)
  7884. case WOLFSSL_KYBER_LEVEL1:
  7885. case WOLFSSL_KYBER_LEVEL3:
  7886. case WOLFSSL_KYBER_LEVEL5:
  7887. case WOLFSSL_P256_KYBER_LEVEL1:
  7888. case WOLFSSL_P384_KYBER_LEVEL3:
  7889. case WOLFSSL_P521_KYBER_LEVEL5:
  7890. {
  7891. int ret;
  7892. int id;
  7893. findEccPqc(NULL, &namedGroup, namedGroup);
  7894. ret = kyber_id2type(namedGroup, &id);
  7895. if (ret == NOT_COMPILED_IN) {
  7896. return 0;
  7897. }
  7898. if (! ext_kyber_enabled(id)) {
  7899. return 0;
  7900. }
  7901. break;
  7902. }
  7903. #elif defined(HAVE_PQM4)
  7904. case WOLFSSL_KYBER_LEVEL1:
  7905. break;
  7906. #endif
  7907. #endif /* HAVE_PQC */
  7908. default:
  7909. return 0;
  7910. }
  7911. return 1;
  7912. }
  7913. static const word16 preferredGroup[] = {
  7914. #if defined(HAVE_ECC) && (!defined(NO_ECC256) || \
  7915. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 256
  7916. WOLFSSL_ECC_SECP256R1,
  7917. #if !defined(HAVE_FIPS) && defined(WOLFSSL_SM2)
  7918. WOLFSSL_ECC_SM2P256V1,
  7919. #endif
  7920. #endif
  7921. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  7922. WOLFSSL_ECC_X25519,
  7923. #endif
  7924. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  7925. WOLFSSL_ECC_X448,
  7926. #endif
  7927. #if defined(HAVE_ECC) && (!defined(NO_ECC384) || \
  7928. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 384
  7929. WOLFSSL_ECC_SECP384R1,
  7930. #endif
  7931. #if defined(HAVE_ECC) && (!defined(NO_ECC521) || \
  7932. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 521
  7933. WOLFSSL_ECC_SECP521R1,
  7934. #endif
  7935. #if defined(HAVE_FFDHE_2048)
  7936. WOLFSSL_FFDHE_2048,
  7937. #endif
  7938. #if defined(HAVE_FFDHE_3072)
  7939. WOLFSSL_FFDHE_3072,
  7940. #endif
  7941. #if defined(HAVE_FFDHE_4096)
  7942. WOLFSSL_FFDHE_4096,
  7943. #endif
  7944. #if defined(HAVE_FFDHE_6144)
  7945. WOLFSSL_FFDHE_6144,
  7946. #endif
  7947. #if defined(HAVE_FFDHE_8192)
  7948. WOLFSSL_FFDHE_8192,
  7949. #endif
  7950. #ifdef WOLFSSL_WC_KYBER
  7951. #ifdef WOLFSSL_KYBER512
  7952. WOLFSSL_KYBER_LEVEL1,
  7953. #endif
  7954. #ifdef WOLFSSL_KYBER768
  7955. WOLFSSL_KYBER_LEVEL3,
  7956. #endif
  7957. #ifdef WOLFSSL_KYBER1024
  7958. WOLFSSL_KYBER_LEVEL5,
  7959. #endif
  7960. #elif defined(HAVE_LIBOQS)
  7961. /* These require a runtime call to TLSX_KeyShare_IsSupported to use */
  7962. WOLFSSL_KYBER_LEVEL1,
  7963. WOLFSSL_KYBER_LEVEL3,
  7964. WOLFSSL_KYBER_LEVEL5,
  7965. WOLFSSL_P256_KYBER_LEVEL1,
  7966. WOLFSSL_P384_KYBER_LEVEL3,
  7967. WOLFSSL_P521_KYBER_LEVEL5,
  7968. #elif defined(HAVE_PQM4)
  7969. WOLFSSL_KYBER_LEVEL1,
  7970. #endif
  7971. WOLFSSL_NAMED_GROUP_INVALID
  7972. };
  7973. #define PREFERRED_GROUP_SZ \
  7974. ((sizeof(preferredGroup)/sizeof(*preferredGroup)) - 1)
  7975. /* -1 for the invalid group */
  7976. /* Examines the application specified group ranking and returns the rank of the
  7977. * group.
  7978. * If no group ranking set then all groups are rank 0 (highest).
  7979. *
  7980. * ssl The SSL/TLS object.
  7981. * group The group to check ranking for.
  7982. * returns ranking from 0 to MAX_GROUP_COUNT-1 or -1 when group not in list.
  7983. */
  7984. static int TLSX_KeyShare_GroupRank(const WOLFSSL* ssl, int group)
  7985. {
  7986. byte i;
  7987. const word16* groups;
  7988. byte numGroups;
  7989. if (ssl->numGroups == 0) {
  7990. groups = preferredGroup;
  7991. numGroups = PREFERRED_GROUP_SZ;
  7992. }
  7993. else {
  7994. groups = ssl->group;
  7995. numGroups = ssl->numGroups;
  7996. }
  7997. #ifdef HAVE_LIBOQS
  7998. if (!TLSX_KeyShare_IsSupported(group))
  7999. return -1;
  8000. #endif
  8001. for (i = 0; i < numGroups; i++)
  8002. if (groups[i] == (word16)group)
  8003. return i;
  8004. return -1;
  8005. }
  8006. /* Set a key share that is supported by the client into extensions.
  8007. *
  8008. * ssl The SSL/TLS object.
  8009. * returns BAD_KEY_SHARE_DATA if no supported group has a key share,
  8010. * 0 if a supported group has a key share and other values indicate an error.
  8011. */
  8012. int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl, TLSX** extensions)
  8013. {
  8014. int ret;
  8015. #ifdef HAVE_SUPPORTED_CURVES
  8016. TLSX* extension;
  8017. SupportedCurve* curve = NULL;
  8018. SupportedCurve* preferredCurve = NULL;
  8019. KeyShareEntry* kse = NULL;
  8020. int preferredRank = WOLFSSL_MAX_GROUP_COUNT;
  8021. int rank;
  8022. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  8023. if (extension != NULL)
  8024. curve = (SupportedCurve*)extension->data;
  8025. /* Use server's preference order. */
  8026. for (; curve != NULL; curve = curve->next) {
  8027. if (!TLSX_KeyShare_IsSupported(curve->name))
  8028. continue;
  8029. if (wolfSSL_curve_is_disabled(ssl, curve->name))
  8030. continue;
  8031. rank = TLSX_KeyShare_GroupRank(ssl, curve->name);
  8032. if (rank == -1)
  8033. continue;
  8034. if (rank < preferredRank) {
  8035. preferredCurve = curve;
  8036. preferredRank = rank;
  8037. }
  8038. }
  8039. curve = preferredCurve;
  8040. if (curve == NULL) {
  8041. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  8042. return BAD_KEY_SHARE_DATA;
  8043. }
  8044. #ifdef WOLFSSL_ASYNC_CRYPT
  8045. /* Check the old key share data list. */
  8046. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  8047. if (extension != NULL) {
  8048. kse = (KeyShareEntry*)extension->data;
  8049. /* We should not be computing keys if we are only going to advertise
  8050. * our choice here. */
  8051. if (kse != NULL && kse->lastRet == WC_PENDING_E) {
  8052. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  8053. return BAD_KEY_SHARE_DATA;
  8054. }
  8055. }
  8056. #endif
  8057. /* Push new KeyShare extension. This will also free the old one */
  8058. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  8059. if (ret != 0)
  8060. return ret;
  8061. /* Extension got pushed to head */
  8062. extension = *extensions;
  8063. /* Push the selected curve */
  8064. ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, curve->name,
  8065. ssl->heap, &kse);
  8066. if (ret != 0)
  8067. return ret;
  8068. /* Set extension to be in response. */
  8069. extension->resp = 1;
  8070. #else
  8071. (void)ssl;
  8072. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  8073. ret = NOT_COMPILED_IN;
  8074. #endif
  8075. return ret;
  8076. }
  8077. /* Server side KSE processing */
  8078. int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions,
  8079. byte cipherSuite0, byte cipherSuite, KeyShareEntry** kse, byte* searched)
  8080. {
  8081. TLSX* extension;
  8082. KeyShareEntry* clientKSE = NULL;
  8083. KeyShareEntry* list = NULL;
  8084. KeyShareEntry* preferredKSE = NULL;
  8085. int preferredRank = WOLFSSL_MAX_GROUP_COUNT;
  8086. int rank;
  8087. (void)cipherSuite0;
  8088. (void)cipherSuite;
  8089. if (ssl == NULL || ssl->options.side != WOLFSSL_SERVER_END)
  8090. return BAD_FUNC_ARG;
  8091. *searched = 0;
  8092. /* Find the KeyShare extension if it exists. */
  8093. extension = TLSX_Find(extensions, TLSX_KEY_SHARE);
  8094. if (extension != NULL)
  8095. list = (KeyShareEntry*)extension->data;
  8096. if (extension && extension->resp == 1) {
  8097. /* Outside of the async case this path should not be taken. */
  8098. int ret = INCOMPLETE_DATA;
  8099. #ifdef WOLFSSL_ASYNC_CRYPT
  8100. /* in async case make sure key generation is finalized */
  8101. KeyShareEntry* serverKSE = (KeyShareEntry*)extension->data;
  8102. if (serverKSE && serverKSE->lastRet == WC_PENDING_E) {
  8103. if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
  8104. *searched = 1;
  8105. ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE);
  8106. }
  8107. #endif
  8108. return ret;
  8109. }
  8110. /* Use server's preference order. */
  8111. for (clientKSE = list; clientKSE != NULL; clientKSE = clientKSE->next) {
  8112. if (clientKSE->ke == NULL)
  8113. continue;
  8114. #ifdef WOLFSSL_SM2
  8115. if ((cipherSuite0 == CIPHER_BYTE) &&
  8116. ((cipherSuite == TLS_SM4_GCM_SM3) ||
  8117. (cipherSuite == TLS_SM4_CCM_SM3))) {
  8118. if (clientKSE->group != WOLFSSL_ECC_SM2P256V1) {
  8119. continue;
  8120. }
  8121. }
  8122. else if (clientKSE->group == WOLFSSL_ECC_SM2P256V1) {
  8123. continue;
  8124. }
  8125. #endif
  8126. /* Check consistency now - extensions in any order. */
  8127. if (!TLSX_SupportedGroups_Find(ssl, clientKSE->group, extensions))
  8128. continue;
  8129. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(clientKSE->group)) {
  8130. /* Check max value supported. */
  8131. if (clientKSE->group > WOLFSSL_ECC_MAX) {
  8132. #ifdef HAVE_PQC
  8133. if (!WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group))
  8134. #endif
  8135. continue;
  8136. }
  8137. if (wolfSSL_curve_is_disabled(ssl, clientKSE->group))
  8138. continue;
  8139. }
  8140. if (!TLSX_KeyShare_IsSupported(clientKSE->group))
  8141. continue;
  8142. rank = TLSX_KeyShare_GroupRank(ssl, clientKSE->group);
  8143. if (rank == -1)
  8144. continue;
  8145. if (rank < preferredRank) {
  8146. preferredKSE = clientKSE;
  8147. preferredRank = rank;
  8148. }
  8149. }
  8150. *kse = preferredKSE;
  8151. *searched = 1;
  8152. return 0;
  8153. }
  8154. /* Server side KSE processing */
  8155. int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE)
  8156. {
  8157. int ret;
  8158. TLSX* extension;
  8159. KeyShareEntry* serverKSE;
  8160. KeyShareEntry* list = NULL;
  8161. if (ssl == NULL || ssl->options.side != WOLFSSL_SERVER_END)
  8162. return BAD_FUNC_ARG;
  8163. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  8164. if (extension == NULL)
  8165. return BAD_STATE_E;
  8166. if (clientKSE == NULL) {
  8167. #ifdef WOLFSSL_ASYNC_CRYPT
  8168. /* Not necessarily an error. The key may have already been setup. */
  8169. if (extension != NULL && extension->resp == 1) {
  8170. serverKSE = (KeyShareEntry*)extension->data;
  8171. if (serverKSE != NULL) {
  8172. /* in async case make sure key generation is finalized */
  8173. if (serverKSE->lastRet == WC_PENDING_E)
  8174. return TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE);
  8175. else if (serverKSE->lastRet == 0)
  8176. return 0;
  8177. }
  8178. }
  8179. #endif
  8180. return BAD_FUNC_ARG;
  8181. }
  8182. /* Generate a new key pair except in the case of OQS KEM because we
  8183. * are going to encapsulate and that does not require us to generate a
  8184. * key pair.
  8185. */
  8186. ret = TLSX_KeyShare_New(&list, clientKSE->group, ssl->heap, &serverKSE);
  8187. if (ret != 0)
  8188. return ret;
  8189. if (clientKSE->key == NULL) {
  8190. #ifdef HAVE_PQC
  8191. if (WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group)) {
  8192. /* Going to need the public key (AKA ciphertext). */
  8193. serverKSE->pubKey = clientKSE->pubKey;
  8194. clientKSE->pubKey = NULL;
  8195. serverKSE->pubKeyLen = clientKSE->pubKeyLen;
  8196. clientKSE->pubKeyLen = 0;
  8197. }
  8198. else
  8199. #endif
  8200. {
  8201. ret = TLSX_KeyShare_GenKey(ssl, serverKSE);
  8202. }
  8203. /* for async do setup of serverKSE below, but return WC_PENDING_E */
  8204. if (ret != 0
  8205. #ifdef WOLFSSL_ASYNC_CRYPT
  8206. && ret != WC_PENDING_E
  8207. #endif
  8208. ) {
  8209. TLSX_KeyShare_FreeAll(list, ssl->heap);
  8210. return ret;
  8211. }
  8212. }
  8213. else {
  8214. /* transfer buffers to serverKSE */
  8215. serverKSE->key = clientKSE->key;
  8216. clientKSE->key = NULL;
  8217. serverKSE->keyLen = clientKSE->keyLen;
  8218. serverKSE->pubKey = clientKSE->pubKey;
  8219. clientKSE->pubKey = NULL;
  8220. serverKSE->pubKeyLen = clientKSE->pubKeyLen;
  8221. #ifndef NO_DH
  8222. serverKSE->privKey = clientKSE->privKey;
  8223. clientKSE->privKey = NULL;
  8224. #endif
  8225. }
  8226. serverKSE->ke = clientKSE->ke;
  8227. serverKSE->keLen = clientKSE->keLen;
  8228. clientKSE->ke = NULL;
  8229. clientKSE->keLen = 0;
  8230. TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap);
  8231. extension->data = (void *)serverKSE;
  8232. extension->resp = 1;
  8233. return ret;
  8234. }
  8235. /* Ensure there is a key pair that can be used for key exchange.
  8236. *
  8237. * ssl The SSL/TLS object.
  8238. * doHelloRetry If set to non-zero will do hello_retry
  8239. * returns 0 on success and other values indicate failure.
  8240. */
  8241. int TLSX_KeyShare_Establish(WOLFSSL *ssl, int* doHelloRetry)
  8242. {
  8243. int ret;
  8244. KeyShareEntry* clientKSE = NULL;
  8245. byte searched = 0;
  8246. *doHelloRetry = 0;
  8247. ret = TLSX_KeyShare_Choose(ssl, ssl->extensions, ssl->cipher.cipherSuite0,
  8248. ssl->cipher.cipherSuite, &clientKSE, &searched);
  8249. if (ret != 0 || !searched)
  8250. return ret;
  8251. /* No supported group found - send HelloRetryRequest. */
  8252. if (clientKSE == NULL) {
  8253. /* Set KEY_SHARE_ERROR to indicate HelloRetryRequest required. */
  8254. *doHelloRetry = 1;
  8255. return TLSX_KeyShare_SetSupported(ssl, &ssl->extensions);
  8256. }
  8257. return TLSX_KeyShare_Setup(ssl, clientKSE);
  8258. }
  8259. /* Derive the shared secret of the key exchange.
  8260. *
  8261. * ssl The SSL/TLS object.
  8262. * returns 0 on success and other values indicate failure.
  8263. */
  8264. int TLSX_KeyShare_DeriveSecret(WOLFSSL *ssl)
  8265. {
  8266. int ret;
  8267. TLSX* extension;
  8268. KeyShareEntry* list = NULL;
  8269. #ifdef WOLFSSL_ASYNC_CRYPT
  8270. ret = wolfSSL_AsyncPop(ssl, NULL);
  8271. /* Check for error */
  8272. if (ret != WC_NO_PENDING_E && ret < 0) {
  8273. return ret;
  8274. }
  8275. #endif
  8276. /* Find the KeyShare extension if it exists. */
  8277. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  8278. if (extension != NULL)
  8279. list = (KeyShareEntry*)extension->data;
  8280. if (list == NULL)
  8281. return KEY_SHARE_ERROR;
  8282. /* Calculate secret. */
  8283. ret = TLSX_KeyShare_Process(ssl, list);
  8284. return ret;
  8285. }
  8286. #define KS_FREE_ALL TLSX_KeyShare_FreeAll
  8287. #define KS_GET_SIZE TLSX_KeyShare_GetSize
  8288. #define KS_WRITE TLSX_KeyShare_Write
  8289. #define KS_PARSE TLSX_KeyShare_Parse
  8290. #else
  8291. #define KS_FREE_ALL(a, b) WC_DO_NOTHING
  8292. #define KS_GET_SIZE(a, b) 0
  8293. #define KS_WRITE(a, b, c) 0
  8294. #define KS_PARSE(a, b, c, d) 0
  8295. #endif /* WOLFSSL_TLS13 */
  8296. /******************************************************************************/
  8297. /* Pre-Shared Key */
  8298. /******************************************************************************/
  8299. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  8300. /* Free the pre-shared key dynamic data.
  8301. *
  8302. * list The linked list of key share entry objects.
  8303. * heap The heap used for allocation.
  8304. */
  8305. static void TLSX_PreSharedKey_FreeAll(PreSharedKey* list, void* heap)
  8306. {
  8307. PreSharedKey* current;
  8308. while ((current = list) != NULL) {
  8309. list = current->next;
  8310. XFREE(current->identity, heap, DYNAMIC_TYPE_TLSX);
  8311. XFREE(current, heap, DYNAMIC_TYPE_TLSX);
  8312. }
  8313. (void)heap;
  8314. }
  8315. /* Get the size of the encoded pre shared key extension.
  8316. *
  8317. * list The linked list of pre-shared key extensions.
  8318. * msgType The type of the message this extension is being written into.
  8319. * returns the number of bytes of the encoded pre-shared key extension or
  8320. * SANITY_MSG_E to indicate invalid message type.
  8321. */
  8322. static int TLSX_PreSharedKey_GetSize(PreSharedKey* list, byte msgType,
  8323. word16* pSz)
  8324. {
  8325. if (msgType == client_hello) {
  8326. /* Length of identities + Length of binders. */
  8327. word16 len = OPAQUE16_LEN + OPAQUE16_LEN;
  8328. while (list != NULL) {
  8329. /* Each entry has: identity, ticket age and binder. */
  8330. len += OPAQUE16_LEN + list->identityLen + OPAQUE32_LEN +
  8331. OPAQUE8_LEN + (word16)list->binderLen;
  8332. list = list->next;
  8333. }
  8334. *pSz += len;
  8335. return 0;
  8336. }
  8337. if (msgType == server_hello) {
  8338. *pSz += OPAQUE16_LEN;
  8339. return 0;
  8340. }
  8341. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8342. return SANITY_MSG_E;
  8343. }
  8344. /* The number of bytes to be written for the binders.
  8345. *
  8346. * list The linked list of pre-shared key extensions.
  8347. * msgType The type of the message this extension is being written into.
  8348. * returns the number of bytes of the encoded pre-shared key extension or
  8349. * SANITY_MSG_E to indicate invalid message type.
  8350. */
  8351. int TLSX_PreSharedKey_GetSizeBinders(PreSharedKey* list, byte msgType,
  8352. word16* pSz)
  8353. {
  8354. word16 len;
  8355. if (msgType != client_hello) {
  8356. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8357. return SANITY_MSG_E;
  8358. }
  8359. /* Length of all binders. */
  8360. len = OPAQUE16_LEN;
  8361. while (list != NULL) {
  8362. len += OPAQUE8_LEN + (word16)list->binderLen;
  8363. list = list->next;
  8364. }
  8365. *pSz = len;
  8366. return 0;
  8367. }
  8368. /* Writes the pre-shared key extension into the output buffer - binders only.
  8369. * Assumes that the the output buffer is big enough to hold data.
  8370. *
  8371. * list The linked list of key share entries.
  8372. * output The buffer to write into.
  8373. * msgType The type of the message this extension is being written into.
  8374. * returns the number of bytes written into the buffer.
  8375. */
  8376. int TLSX_PreSharedKey_WriteBinders(PreSharedKey* list, byte* output,
  8377. byte msgType, word16* pSz)
  8378. {
  8379. PreSharedKey* current = list;
  8380. word16 idx = 0;
  8381. word16 lenIdx;
  8382. word16 len;
  8383. if (msgType != client_hello) {
  8384. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8385. return SANITY_MSG_E;
  8386. }
  8387. /* Skip length of all binders. */
  8388. lenIdx = idx;
  8389. idx += OPAQUE16_LEN;
  8390. while (current != NULL) {
  8391. /* Binder data length. */
  8392. output[idx++] = (byte)current->binderLen;
  8393. /* Binder data. */
  8394. XMEMCPY(output + idx, current->binder, current->binderLen);
  8395. idx += (word16)current->binderLen;
  8396. current = current->next;
  8397. }
  8398. /* Length of the binders. */
  8399. len = idx - lenIdx - OPAQUE16_LEN;
  8400. c16toa(len, output + lenIdx);
  8401. *pSz = idx;
  8402. return 0;
  8403. }
  8404. /* Writes the pre-shared key extension into the output buffer.
  8405. * Assumes that the the output buffer is big enough to hold data.
  8406. *
  8407. * list The linked list of key share entries.
  8408. * output The buffer to write into.
  8409. * msgType The type of the message this extension is being written into.
  8410. * returns the number of bytes written into the buffer.
  8411. */
  8412. static int TLSX_PreSharedKey_Write(PreSharedKey* list, byte* output,
  8413. byte msgType, word16* pSz)
  8414. {
  8415. if (msgType == client_hello) {
  8416. PreSharedKey* current = list;
  8417. word16 idx = 0;
  8418. word16 lenIdx;
  8419. word16 len;
  8420. int ret;
  8421. /* Write identities only. Binders after HMACing over this. */
  8422. lenIdx = idx;
  8423. idx += OPAQUE16_LEN;
  8424. while (current != NULL) {
  8425. /* Identity length */
  8426. c16toa(current->identityLen, output + idx);
  8427. idx += OPAQUE16_LEN;
  8428. /* Identity data */
  8429. XMEMCPY(output + idx, current->identity, current->identityLen);
  8430. idx += current->identityLen;
  8431. /* Obfuscated ticket age. */
  8432. c32toa(current->ticketAge, output + idx);
  8433. idx += OPAQUE32_LEN;
  8434. current = current->next;
  8435. }
  8436. /* Length of the identities. */
  8437. len = idx - lenIdx - OPAQUE16_LEN;
  8438. c16toa(len, output + lenIdx);
  8439. /* Don't include binders here.
  8440. * The binders are based on the hash of all the ClientHello data up to
  8441. * and include the identities written above.
  8442. */
  8443. ret = TLSX_PreSharedKey_GetSizeBinders(list, msgType, &len);
  8444. if (ret < 0)
  8445. return ret;
  8446. *pSz += idx + len;
  8447. }
  8448. else if (msgType == server_hello) {
  8449. word16 i;
  8450. /* Find the index of the chosen identity. */
  8451. for (i=0; list != NULL && !list->chosen; i++)
  8452. list = list->next;
  8453. if (list == NULL) {
  8454. WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR);
  8455. return BUILD_MSG_ERROR;
  8456. }
  8457. /* The index of the identity chosen by the server from the list supplied
  8458. * by the client.
  8459. */
  8460. c16toa(i, output);
  8461. *pSz += OPAQUE16_LEN;
  8462. }
  8463. else {
  8464. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8465. return SANITY_MSG_E;
  8466. }
  8467. return 0;
  8468. }
  8469. int TLSX_PreSharedKey_Parse_ClientHello(TLSX** extensions, const byte* input,
  8470. word16 length, void* heap)
  8471. {
  8472. int ret;
  8473. word16 len;
  8474. word16 idx = 0;
  8475. TLSX* extension;
  8476. PreSharedKey* list;
  8477. TLSX_Remove(extensions, TLSX_PRE_SHARED_KEY, heap);
  8478. /* Length of identities and of binders. */
  8479. if ((int)(length - idx) < OPAQUE16_LEN + OPAQUE16_LEN)
  8480. return BUFFER_E;
  8481. /* Length of identities. */
  8482. ato16(input + idx, &len);
  8483. idx += OPAQUE16_LEN;
  8484. if (len < MIN_PSK_ID_LEN || length - idx < len)
  8485. return BUFFER_E;
  8486. /* Create a pre-shared key object for each identity. */
  8487. while (len > 0) {
  8488. const byte* identity;
  8489. word16 identityLen;
  8490. word32 age;
  8491. if (len < OPAQUE16_LEN)
  8492. return BUFFER_E;
  8493. /* Length of identity. */
  8494. ato16(input + idx, &identityLen);
  8495. idx += OPAQUE16_LEN;
  8496. if (len < OPAQUE16_LEN + identityLen + OPAQUE32_LEN ||
  8497. identityLen > MAX_PSK_ID_LEN)
  8498. return BUFFER_E;
  8499. /* Cache identity pointer. */
  8500. identity = input + idx;
  8501. idx += identityLen;
  8502. /* Ticket age. */
  8503. ato32(input + idx, &age);
  8504. idx += OPAQUE32_LEN;
  8505. ret = TLSX_PreSharedKey_Use(extensions, identity, identityLen, age, no_mac,
  8506. 0, 0, 1, NULL, heap);
  8507. if (ret != 0)
  8508. return ret;
  8509. /* Done with this identity. */
  8510. len -= OPAQUE16_LEN + identityLen + OPAQUE32_LEN;
  8511. }
  8512. /* Find the list of identities sent to server. */
  8513. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8514. if (extension == NULL)
  8515. return PSK_KEY_ERROR;
  8516. list = (PreSharedKey*)extension->data;
  8517. /* Length of binders. */
  8518. if (idx + OPAQUE16_LEN > length)
  8519. return BUFFER_E;
  8520. ato16(input + idx, &len);
  8521. idx += OPAQUE16_LEN;
  8522. if (len < MIN_PSK_BINDERS_LEN || length - idx < len)
  8523. return BUFFER_E;
  8524. /* Set binder for each identity. */
  8525. while (list != NULL && len > 0) {
  8526. /* Length of binder */
  8527. list->binderLen = input[idx++];
  8528. if (list->binderLen < WC_SHA256_DIGEST_SIZE ||
  8529. list->binderLen > WC_MAX_DIGEST_SIZE)
  8530. return BUFFER_E;
  8531. if (len < OPAQUE8_LEN + list->binderLen)
  8532. return BUFFER_E;
  8533. /* Copy binder into static buffer. */
  8534. XMEMCPY(list->binder, input + idx, list->binderLen);
  8535. idx += (word16)list->binderLen;
  8536. /* Done with binder entry. */
  8537. len -= OPAQUE8_LEN + (word16)list->binderLen;
  8538. /* Next identity. */
  8539. list = list->next;
  8540. }
  8541. if (list != NULL || len != 0)
  8542. return BUFFER_E;
  8543. return 0;
  8544. }
  8545. /* Parse the pre-shared key extension.
  8546. * Different formats in different messages.
  8547. *
  8548. * ssl The SSL/TLS object.
  8549. * input The extension data.
  8550. * length The length of the extension data.
  8551. * msgType The type of the message this extension is being parsed from.
  8552. * returns 0 on success and other values indicate failure.
  8553. */
  8554. static int TLSX_PreSharedKey_Parse(WOLFSSL* ssl, const byte* input,
  8555. word16 length, byte msgType)
  8556. {
  8557. if (msgType == client_hello) {
  8558. return TLSX_PreSharedKey_Parse_ClientHello(&ssl->extensions, input,
  8559. length, ssl->heap);
  8560. }
  8561. if (msgType == server_hello) {
  8562. word16 idx;
  8563. PreSharedKey* list;
  8564. TLSX* extension;
  8565. /* Index of identity chosen by server. */
  8566. if (length != OPAQUE16_LEN)
  8567. return BUFFER_E;
  8568. ato16(input, &idx);
  8569. #ifdef WOLFSSL_EARLY_DATA
  8570. ssl->options.pskIdIndex = idx + 1;
  8571. #endif
  8572. /* Find the list of identities sent to server. */
  8573. extension = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  8574. if (extension == NULL)
  8575. return PSK_KEY_ERROR;
  8576. list = (PreSharedKey*)extension->data;
  8577. /* Mark the identity as chosen. */
  8578. for (; list != NULL && idx > 0; idx--)
  8579. list = list->next;
  8580. if (list == NULL) {
  8581. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8582. return PSK_KEY_ERROR;
  8583. }
  8584. list->chosen = 1;
  8585. #ifdef HAVE_SESSION_TICKET
  8586. if (list->resumption) {
  8587. /* Check that the session's details are the same as the server's. */
  8588. if (ssl->options.cipherSuite0 != ssl->session->cipherSuite0 ||
  8589. ssl->options.cipherSuite != ssl->session->cipherSuite ||
  8590. ssl->session->version.major != ssl->ctx->method->version.major ||
  8591. ssl->session->version.minor != ssl->ctx->method->version.minor) {
  8592. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8593. return PSK_KEY_ERROR;
  8594. }
  8595. }
  8596. #endif
  8597. return 0;
  8598. }
  8599. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8600. return SANITY_MSG_E;
  8601. }
  8602. /* Create a new pre-shared key and put it into the list.
  8603. *
  8604. * list The linked list of pre-shared key.
  8605. * identity The identity.
  8606. * len The length of the identity data.
  8607. * heap The memory to allocate with.
  8608. * preSharedKey The new pre-shared key object.
  8609. * returns 0 on success and other values indicate failure.
  8610. */
  8611. static int TLSX_PreSharedKey_New(PreSharedKey** list, const byte* identity,
  8612. word16 len, void *heap,
  8613. PreSharedKey** preSharedKey)
  8614. {
  8615. PreSharedKey* psk;
  8616. PreSharedKey** next;
  8617. psk = (PreSharedKey*)XMALLOC(sizeof(PreSharedKey), heap, DYNAMIC_TYPE_TLSX);
  8618. if (psk == NULL)
  8619. return MEMORY_E;
  8620. XMEMSET(psk, 0, sizeof(*psk));
  8621. /* Make a copy of the identity data. */
  8622. psk->identity = (byte*)XMALLOC(len + NULL_TERM_LEN, heap,
  8623. DYNAMIC_TYPE_TLSX);
  8624. if (psk->identity == NULL) {
  8625. XFREE(psk, heap, DYNAMIC_TYPE_TLSX);
  8626. return MEMORY_E;
  8627. }
  8628. XMEMCPY(psk->identity, identity, len);
  8629. psk->identityLen = len;
  8630. /* Use a NULL terminator in case it is a C string */
  8631. psk->identity[psk->identityLen] = '\0';
  8632. /* Add it to the end and maintain the links. */
  8633. while (*list != NULL) {
  8634. /* Assign to temporary to work around compiler bug found by customer. */
  8635. next = &((*list)->next);
  8636. list = next;
  8637. }
  8638. *list = psk;
  8639. *preSharedKey = psk;
  8640. (void)heap;
  8641. return 0;
  8642. }
  8643. static WC_INLINE byte GetHmacLength(int hmac)
  8644. {
  8645. switch (hmac) {
  8646. #ifndef NO_SHA256
  8647. case sha256_mac:
  8648. return WC_SHA256_DIGEST_SIZE;
  8649. #endif
  8650. #ifdef WOLFSSL_SHA384
  8651. case sha384_mac:
  8652. return WC_SHA384_DIGEST_SIZE;
  8653. #endif
  8654. #ifdef WOLFSSL_SHA512
  8655. case sha512_mac:
  8656. return WC_SHA512_DIGEST_SIZE;
  8657. #endif
  8658. #ifdef WOLFSSL_SM3
  8659. case sm3_mac:
  8660. return WC_SM3_DIGEST_SIZE;
  8661. #endif
  8662. }
  8663. return 0;
  8664. }
  8665. /* Use the data to create a new pre-shared key object in the extensions.
  8666. *
  8667. * ssl The SSL/TLS object.
  8668. * identity The identity.
  8669. * len The length of the identity data.
  8670. * age The age of the identity.
  8671. * hmac The HMAC algorithm.
  8672. * cipherSuite0 The first byte of the cipher suite to use.
  8673. * cipherSuite The second byte of the cipher suite to use.
  8674. * resumption The PSK is for resumption of a session.
  8675. * preSharedKey The new pre-shared key object.
  8676. * returns 0 on success and other values indicate failure.
  8677. */
  8678. int TLSX_PreSharedKey_Use(TLSX** extensions, const byte* identity, word16 len,
  8679. word32 age, byte hmac, byte cipherSuite0,
  8680. byte cipherSuite, byte resumption,
  8681. PreSharedKey **preSharedKey, void* heap)
  8682. {
  8683. int ret = 0;
  8684. TLSX* extension;
  8685. PreSharedKey* psk = NULL;
  8686. /* Find the pre-shared key extension if it exists. */
  8687. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8688. if (extension == NULL) {
  8689. /* Push new pre-shared key extension. */
  8690. ret = TLSX_Push(extensions, TLSX_PRE_SHARED_KEY, NULL, heap);
  8691. if (ret != 0)
  8692. return ret;
  8693. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8694. if (extension == NULL)
  8695. return MEMORY_E;
  8696. }
  8697. /* Try to find the pre-shared key with this identity. */
  8698. psk = (PreSharedKey*)extension->data;
  8699. while (psk != NULL) {
  8700. if ((psk->identityLen == len) &&
  8701. (XMEMCMP(psk->identity, identity, len) == 0)) {
  8702. break;
  8703. }
  8704. psk = psk->next;
  8705. }
  8706. /* Create a new pre-shared key object if not found. */
  8707. if (psk == NULL) {
  8708. ret = TLSX_PreSharedKey_New((PreSharedKey**)&extension->data, identity,
  8709. len, heap, &psk);
  8710. if (ret != 0)
  8711. return ret;
  8712. }
  8713. /* Update/set age and HMAC algorithm. */
  8714. psk->ticketAge = age;
  8715. psk->hmac = hmac;
  8716. psk->cipherSuite0 = cipherSuite0;
  8717. psk->cipherSuite = cipherSuite;
  8718. psk->resumption = resumption;
  8719. psk->binderLen = GetHmacLength(psk->hmac);
  8720. if (preSharedKey != NULL)
  8721. *preSharedKey = psk;
  8722. return 0;
  8723. }
  8724. #define PSK_FREE_ALL TLSX_PreSharedKey_FreeAll
  8725. #define PSK_GET_SIZE TLSX_PreSharedKey_GetSize
  8726. #define PSK_WRITE TLSX_PreSharedKey_Write
  8727. #define PSK_PARSE TLSX_PreSharedKey_Parse
  8728. #else
  8729. #define PSK_FREE_ALL(a, b) WC_DO_NOTHING
  8730. #define PSK_GET_SIZE(a, b, c) 0
  8731. #define PSK_WRITE(a, b, c, d) 0
  8732. #define PSK_PARSE(a, b, c, d) 0
  8733. #endif
  8734. /******************************************************************************/
  8735. /* PSK Key Exchange Modes */
  8736. /******************************************************************************/
  8737. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  8738. /* Get the size of the encoded PSK KE modes extension.
  8739. * Only in ClientHello.
  8740. *
  8741. * modes The PSK KE mode bit string.
  8742. * msgType The type of the message this extension is being written into.
  8743. * returns the number of bytes of the encoded PSK KE mode extension.
  8744. */
  8745. static int TLSX_PskKeModes_GetSize(byte modes, byte msgType, word16* pSz)
  8746. {
  8747. if (msgType == client_hello) {
  8748. /* Format: Len | Modes* */
  8749. word16 len = OPAQUE8_LEN;
  8750. /* Check whether each possible mode is to be written. */
  8751. if (modes & (1 << PSK_KE))
  8752. len += OPAQUE8_LEN;
  8753. if (modes & (1 << PSK_DHE_KE))
  8754. len += OPAQUE8_LEN;
  8755. *pSz += len;
  8756. return 0;
  8757. }
  8758. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8759. return SANITY_MSG_E;
  8760. }
  8761. /* Writes the PSK KE modes extension into the output buffer.
  8762. * Assumes that the the output buffer is big enough to hold data.
  8763. * Only in ClientHello.
  8764. *
  8765. * modes The PSK KE mode bit string.
  8766. * output The buffer to write into.
  8767. * msgType The type of the message this extension is being written into.
  8768. * returns the number of bytes written into the buffer.
  8769. */
  8770. static int TLSX_PskKeModes_Write(byte modes, byte* output, byte msgType,
  8771. word16* pSz)
  8772. {
  8773. if (msgType == client_hello) {
  8774. /* Format: Len | Modes* */
  8775. word16 idx = OPAQUE8_LEN;
  8776. /* Write out each possible mode. */
  8777. if (modes & (1 << PSK_KE))
  8778. output[idx++] = PSK_KE;
  8779. if (modes & (1 << PSK_DHE_KE))
  8780. output[idx++] = PSK_DHE_KE;
  8781. /* Write out length of mode list. */
  8782. output[0] = (byte)(idx - OPAQUE8_LEN);
  8783. *pSz += idx;
  8784. return 0;
  8785. }
  8786. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8787. return SANITY_MSG_E;
  8788. }
  8789. int TLSX_PskKeyModes_Parse_Modes(const byte* input, word16 length, byte msgType,
  8790. byte* modes)
  8791. {
  8792. if (msgType == client_hello) {
  8793. /* Format: Len | Modes* */
  8794. int idx = 0;
  8795. word16 len;
  8796. *modes = 0;
  8797. /* Ensure length byte exists. */
  8798. if (length < OPAQUE8_LEN)
  8799. return BUFFER_E;
  8800. /* Get length of mode list and ensure that is the only data. */
  8801. len = input[0];
  8802. if (length - OPAQUE8_LEN != len)
  8803. return BUFFER_E;
  8804. idx = OPAQUE8_LEN;
  8805. /* Set a bit for each recognized modes. */
  8806. while (len > 0) {
  8807. /* Ignore unrecognized modes. */
  8808. if (input[idx] <= PSK_DHE_KE)
  8809. *modes |= 1 << input[idx];
  8810. idx++;
  8811. len--;
  8812. }
  8813. return 0;
  8814. }
  8815. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8816. return SANITY_MSG_E;
  8817. }
  8818. /* Parse the PSK KE modes extension.
  8819. * Only in ClientHello.
  8820. *
  8821. * ssl The SSL/TLS object.
  8822. * input The extension data.
  8823. * length The length of the extension data.
  8824. * msgType The type of the message this extension is being parsed from.
  8825. * returns 0 on success and other values indicate failure.
  8826. */
  8827. static int TLSX_PskKeModes_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  8828. byte msgType)
  8829. {
  8830. int ret;
  8831. byte modes;
  8832. ret = TLSX_PskKeyModes_Parse_Modes(input, length, msgType, &modes);
  8833. if (ret == 0)
  8834. ret = TLSX_PskKeyModes_Use(ssl, modes);
  8835. if (ret != 0) {
  8836. WOLFSSL_ERROR_VERBOSE(ret);
  8837. }
  8838. return ret;
  8839. }
  8840. /* Use the data to create a new PSK Key Exchange Modes object in the extensions.
  8841. *
  8842. * ssl The SSL/TLS object.
  8843. * modes The PSK key exchange modes.
  8844. * returns 0 on success and other values indicate failure.
  8845. */
  8846. int TLSX_PskKeyModes_Use(WOLFSSL* ssl, byte modes)
  8847. {
  8848. int ret = 0;
  8849. TLSX* extension;
  8850. /* Find the PSK key exchange modes extension if it exists. */
  8851. extension = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  8852. if (extension == NULL) {
  8853. /* Push new PSK key exchange modes extension. */
  8854. ret = TLSX_Push(&ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES, NULL,
  8855. ssl->heap);
  8856. if (ret != 0)
  8857. return ret;
  8858. extension = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  8859. if (extension == NULL)
  8860. return MEMORY_E;
  8861. }
  8862. extension->val = modes;
  8863. return 0;
  8864. }
  8865. #define PKM_GET_SIZE TLSX_PskKeModes_GetSize
  8866. #define PKM_WRITE TLSX_PskKeModes_Write
  8867. #define PKM_PARSE TLSX_PskKeModes_Parse
  8868. #else
  8869. #define PKM_GET_SIZE(a, b, c) 0
  8870. #define PKM_WRITE(a, b, c, d) 0
  8871. #define PKM_PARSE(a, b, c, d) 0
  8872. #endif
  8873. /******************************************************************************/
  8874. /* Post-Handshake Authentication */
  8875. /******************************************************************************/
  8876. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  8877. /* Get the size of the encoded Post-Handshake Authentication extension.
  8878. * Only in ClientHello.
  8879. *
  8880. * msgType The type of the message this extension is being written into.
  8881. * returns the number of bytes of the encoded Post-Handshake Authentication
  8882. * extension.
  8883. */
  8884. static int TLSX_PostHandAuth_GetSize(byte msgType, word16* pSz)
  8885. {
  8886. if (msgType == client_hello) {
  8887. *pSz += 0;
  8888. return 0;
  8889. }
  8890. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8891. return SANITY_MSG_E;
  8892. }
  8893. /* Writes the Post-Handshake Authentication extension into the output buffer.
  8894. * Assumes that the the output buffer is big enough to hold data.
  8895. * Only in ClientHello.
  8896. *
  8897. * output The buffer to write into.
  8898. * msgType The type of the message this extension is being written into.
  8899. * returns the number of bytes written into the buffer.
  8900. */
  8901. static int TLSX_PostHandAuth_Write(byte* output, byte msgType, word16* pSz)
  8902. {
  8903. (void)output;
  8904. if (msgType == client_hello) {
  8905. *pSz += 0;
  8906. return 0;
  8907. }
  8908. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8909. return SANITY_MSG_E;
  8910. }
  8911. /* Parse the Post-Handshake Authentication extension.
  8912. * Only in ClientHello.
  8913. *
  8914. * ssl The SSL/TLS object.
  8915. * input The extension data.
  8916. * length The length of the extension data.
  8917. * msgType The type of the message this extension is being parsed from.
  8918. * returns 0 on success and other values indicate failure.
  8919. */
  8920. static int TLSX_PostHandAuth_Parse(WOLFSSL* ssl, const byte* input,
  8921. word16 length, byte msgType)
  8922. {
  8923. (void)input;
  8924. if (msgType == client_hello) {
  8925. /* Ensure extension is empty. */
  8926. if (length != 0)
  8927. return BUFFER_E;
  8928. ssl->options.postHandshakeAuth = 1;
  8929. return 0;
  8930. }
  8931. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8932. return SANITY_MSG_E;
  8933. }
  8934. /* Create a new Post-handshake authentication object in the extensions.
  8935. *
  8936. * ssl The SSL/TLS object.
  8937. * returns 0 on success and other values indicate failure.
  8938. */
  8939. static int TLSX_PostHandAuth_Use(WOLFSSL* ssl)
  8940. {
  8941. int ret = 0;
  8942. TLSX* extension;
  8943. /* Find the PSK key exchange modes extension if it exists. */
  8944. extension = TLSX_Find(ssl->extensions, TLSX_POST_HANDSHAKE_AUTH);
  8945. if (extension == NULL) {
  8946. /* Push new Post-handshake Authentication extension. */
  8947. ret = TLSX_Push(&ssl->extensions, TLSX_POST_HANDSHAKE_AUTH, NULL,
  8948. ssl->heap);
  8949. if (ret != 0)
  8950. return ret;
  8951. }
  8952. return 0;
  8953. }
  8954. #define PHA_GET_SIZE TLSX_PostHandAuth_GetSize
  8955. #define PHA_WRITE TLSX_PostHandAuth_Write
  8956. #define PHA_PARSE TLSX_PostHandAuth_Parse
  8957. #else
  8958. #define PHA_GET_SIZE(a, b) 0
  8959. #define PHA_WRITE(a, b, c) 0
  8960. #define PHA_PARSE(a, b, c, d) 0
  8961. #endif
  8962. /******************************************************************************/
  8963. /* Early Data Indication */
  8964. /******************************************************************************/
  8965. #ifdef WOLFSSL_EARLY_DATA
  8966. /* Get the size of the encoded Early Data Indication extension.
  8967. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  8968. *
  8969. * msgType The type of the message this extension is being written into.
  8970. * returns the number of bytes of the encoded Early Data Indication extension.
  8971. */
  8972. static int TLSX_EarlyData_GetSize(byte msgType, word16* pSz)
  8973. {
  8974. int ret = 0;
  8975. if (msgType == client_hello || msgType == encrypted_extensions)
  8976. *pSz += 0;
  8977. else if (msgType == session_ticket)
  8978. *pSz += OPAQUE32_LEN;
  8979. else {
  8980. ret = SANITY_MSG_E;
  8981. WOLFSSL_ERROR_VERBOSE(ret);
  8982. }
  8983. return ret;
  8984. }
  8985. /* Writes the Early Data Indicator extension into the output buffer.
  8986. * Assumes that the the output buffer is big enough to hold data.
  8987. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  8988. *
  8989. * maxSz The maximum early data size.
  8990. * output The buffer to write into.
  8991. * msgType The type of the message this extension is being written into.
  8992. * returns the number of bytes written into the buffer.
  8993. */
  8994. static int TLSX_EarlyData_Write(word32 maxSz, byte* output, byte msgType,
  8995. word16* pSz)
  8996. {
  8997. if (msgType == client_hello || msgType == encrypted_extensions)
  8998. return 0;
  8999. else if (msgType == session_ticket) {
  9000. c32toa(maxSz, output);
  9001. *pSz += OPAQUE32_LEN;
  9002. return 0;
  9003. }
  9004. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9005. return SANITY_MSG_E;
  9006. }
  9007. /* Parse the Early Data Indicator extension.
  9008. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  9009. *
  9010. * ssl The SSL/TLS object.
  9011. * input The extension data.
  9012. * length The length of the extension data.
  9013. * msgType The type of the message this extension is being parsed from.
  9014. * returns 0 on success and other values indicate failure.
  9015. */
  9016. static int TLSX_EarlyData_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  9017. byte msgType)
  9018. {
  9019. WOLFSSL_ENTER("TLSX_EarlyData_Parse");
  9020. if (msgType == client_hello) {
  9021. if (length != 0)
  9022. return BUFFER_E;
  9023. if (ssl->earlyData == expecting_early_data) {
  9024. if (ssl->options.maxEarlyDataSz != 0)
  9025. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_ACCEPTED;
  9026. else
  9027. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_REJECTED;
  9028. return TLSX_EarlyData_Use(ssl, 0, 0);
  9029. }
  9030. ssl->earlyData = early_data_ext;
  9031. return 0;
  9032. }
  9033. if (msgType == encrypted_extensions) {
  9034. if (length != 0)
  9035. return BUFFER_E;
  9036. /* Ensure the index of PSK identity chosen by server is 0.
  9037. * Index is plus one to handle 'not set' value of 0.
  9038. */
  9039. if (ssl->options.pskIdIndex != 1) {
  9040. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  9041. return PSK_KEY_ERROR;
  9042. }
  9043. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  9044. /* the extension from server comes in */
  9045. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_ACCEPTED;
  9046. }
  9047. return TLSX_EarlyData_Use(ssl, 1, 1);
  9048. }
  9049. if (msgType == session_ticket) {
  9050. word32 maxSz;
  9051. if (length != OPAQUE32_LEN)
  9052. return BUFFER_E;
  9053. ato32(input, &maxSz);
  9054. ssl->session->maxEarlyDataSz = maxSz;
  9055. return 0;
  9056. }
  9057. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9058. return SANITY_MSG_E;
  9059. }
  9060. /* Use the data to create a new Early Data object in the extensions.
  9061. *
  9062. * ssl The SSL/TLS object.
  9063. * maxSz The maximum early data size.
  9064. * is_response if this extension is part of a response
  9065. * returns 0 on success and other values indicate failure.
  9066. */
  9067. int TLSX_EarlyData_Use(WOLFSSL* ssl, word32 maxSz, int is_response)
  9068. {
  9069. int ret = 0;
  9070. TLSX* extension;
  9071. /* Find the early data extension if it exists. */
  9072. extension = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  9073. if (extension == NULL) {
  9074. /* Push new early data extension. */
  9075. ret = TLSX_Push(&ssl->extensions, TLSX_EARLY_DATA, NULL, ssl->heap);
  9076. if (ret != 0)
  9077. return ret;
  9078. extension = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  9079. if (extension == NULL)
  9080. return MEMORY_E;
  9081. }
  9082. extension->resp = is_response;
  9083. /* In QUIC, earlydata size is either 0 or 0xffffffff.
  9084. * Override any size between, possibly left from our initial value */
  9085. extension->val = (WOLFSSL_IS_QUIC(ssl) && is_response && maxSz > 0) ?
  9086. WOLFSSL_MAX_32BIT : maxSz;
  9087. return 0;
  9088. }
  9089. #define EDI_GET_SIZE TLSX_EarlyData_GetSize
  9090. #define EDI_WRITE TLSX_EarlyData_Write
  9091. #define EDI_PARSE TLSX_EarlyData_Parse
  9092. #else
  9093. #define EDI_GET_SIZE(a, b) 0
  9094. #define EDI_WRITE(a, b, c, d) 0
  9095. #define EDI_PARSE(a, b, c, d) 0
  9096. #endif
  9097. /******************************************************************************/
  9098. /* QUIC transport parameter extension */
  9099. /******************************************************************************/
  9100. #ifdef WOLFSSL_QUIC
  9101. static word16 TLSX_QuicTP_GetSize(TLSX* extension)
  9102. {
  9103. const QuicTransportParam *tp = (QuicTransportParam*)extension->data;
  9104. return tp ? tp->len : 0;
  9105. }
  9106. int TLSX_QuicTP_Use(WOLFSSL* ssl, TLSX_Type ext_type, int is_response)
  9107. {
  9108. int ret = 0;
  9109. TLSX* extension;
  9110. WOLFSSL_ENTER("TLSX_QuicTP_Use");
  9111. if (ssl->quic.transport_local == NULL) {
  9112. /* RFC9000, ch 7.3: "An endpoint MUST treat the absence of [...]
  9113. * from either endpoint [...] as a connection error of type
  9114. * TRANSPORT_PARAMETER_ERROR."
  9115. */
  9116. ret = QUIC_TP_MISSING_E;
  9117. goto cleanup;
  9118. }
  9119. extension = TLSX_Find(ssl->extensions, ext_type);
  9120. if (extension == NULL) {
  9121. ret = TLSX_Push(&ssl->extensions, ext_type, NULL, ssl->heap);
  9122. if (ret != 0)
  9123. goto cleanup;
  9124. extension = TLSX_Find(ssl->extensions, ext_type);
  9125. if (extension == NULL) {
  9126. ret = MEMORY_E;
  9127. goto cleanup;
  9128. }
  9129. }
  9130. if (extension->data) {
  9131. QuicTransportParam_free((QuicTransportParam*)extension->data, ssl->heap);
  9132. extension->data = NULL;
  9133. }
  9134. extension->resp = is_response;
  9135. extension->data = (void*)QuicTransportParam_dup(ssl->quic.transport_local, ssl->heap);
  9136. if (!extension->data) {
  9137. ret = MEMORY_E;
  9138. goto cleanup;
  9139. }
  9140. cleanup:
  9141. WOLFSSL_LEAVE("TLSX_QuicTP_Use", ret);
  9142. return ret;
  9143. }
  9144. static word16 TLSX_QuicTP_Write(QuicTransportParam *tp, byte* output)
  9145. {
  9146. word16 len = 0;
  9147. WOLFSSL_ENTER("TLSX_QuicTP_Write");
  9148. if (tp && tp->len) {
  9149. XMEMCPY(output, tp->data, tp->len);
  9150. len = tp->len;
  9151. }
  9152. WOLFSSL_LEAVE("TLSX_QuicTP_Write", len);
  9153. return len;
  9154. }
  9155. static int TLSX_QuicTP_Parse(WOLFSSL *ssl, const byte *input, size_t len, int ext_type, int msgType)
  9156. {
  9157. const QuicTransportParam *tp, **ptp;
  9158. (void)msgType;
  9159. tp = QuicTransportParam_new(input, len, ssl->heap);
  9160. if (!tp) {
  9161. return MEMORY_E;
  9162. }
  9163. ptp = (ext_type == TLSX_KEY_QUIC_TP_PARAMS_DRAFT) ?
  9164. &ssl->quic.transport_peer_draft : &ssl->quic.transport_peer;
  9165. if (*ptp) {
  9166. QTP_FREE(*ptp, ssl->heap);
  9167. }
  9168. *ptp = tp;
  9169. return 0;
  9170. }
  9171. #define QTP_GET_SIZE TLSX_QuicTP_GetSize
  9172. #define QTP_USE TLSX_QuicTP_Use
  9173. #define QTP_WRITE TLSX_QuicTP_Write
  9174. #define QTP_PARSE TLSX_QuicTP_Parse
  9175. #endif /* WOLFSSL_QUIC */
  9176. #if defined(WOLFSSL_DTLS_CID)
  9177. #define CID_GET_SIZE TLSX_ConnectionID_GetSize
  9178. #define CID_WRITE TLSX_ConnectionID_Write
  9179. #define CID_PARSE TLSX_ConnectionID_Parse
  9180. #define CID_FREE TLSX_ConnectionID_Free
  9181. #else
  9182. #define CID_GET_SIZE(a) 0
  9183. #define CID_WRITE(a, b) 0
  9184. #define CID_PARSE(a, b, c, d) 0
  9185. #define CID_FREE(a, b) 0
  9186. #endif /* defined(WOLFSSL_DTLS_CID) */
  9187. #if defined(HAVE_RPK)
  9188. /******************************************************************************/
  9189. /* Client_Certificate_Type extension */
  9190. /******************************************************************************/
  9191. /* return 1 if specified type is included in the given list, otherwise 0 */
  9192. static int IsCertTypeListed(byte type, byte cnt, const byte* list)
  9193. {
  9194. int ret = 0;
  9195. int i;
  9196. if (cnt == 0 || list == NULL)
  9197. return ret;
  9198. if (cnt > 0 && cnt <= MAX_CLIENT_CERT_TYPE_CNT) {
  9199. for (i = 0; i < cnt; i++) {
  9200. if (list[i] == type)
  9201. return 1;
  9202. }
  9203. }
  9204. return 0;
  9205. }
  9206. /* Search both arrays from above to find a common value between the two given
  9207. * arrays(a and b). return 1 if it finds a common value, otherwise return 0.
  9208. */
  9209. static int GetCommonItem(const byte* a, byte aLen, const byte* b, byte bLen,
  9210. byte* type)
  9211. {
  9212. int i, j;
  9213. if (a == NULL || b == NULL)
  9214. return 0;
  9215. for (i = 0; i < aLen; i++) {
  9216. for (j = 0; j < bLen; j++) {
  9217. if (a[i] == b[j]) {
  9218. *type = a[i];
  9219. return 1;
  9220. }
  9221. }
  9222. }
  9223. return 0;
  9224. }
  9225. /* Creates a "client certificate type" extension if necessary.
  9226. * Returns 0 if no error occurred, negative value otherwise.
  9227. * A return of 0, it does not indicae that the extension was created.
  9228. */
  9229. static int TLSX_ClientCertificateType_Use(WOLFSSL* ssl, byte isServer)
  9230. {
  9231. int ret = 0;
  9232. if (ssl == NULL)
  9233. return BAD_FUNC_ARG;
  9234. if (isServer) {
  9235. /* [in server side]
  9236. */
  9237. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_RPK,
  9238. ssl->options.rpkConfig.preferred_ClientCertTypeCnt,
  9239. ssl->options.rpkConfig.preferred_ClientCertTypes)) {
  9240. WOLFSSL_MSG("Adding Client Certificate Type extension");
  9241. ret = TLSX_Push(&ssl->extensions, TLSX_CLIENT_CERTIFICATE_TYPE, ssl,
  9242. ssl->heap);
  9243. if (ret == 0) {
  9244. TLSX_SetResponse(ssl, TLSX_CLIENT_CERTIFICATE_TYPE);
  9245. }
  9246. }
  9247. }
  9248. else {
  9249. /* [in client side]
  9250. * This extension MUST be omitted from the ClientHello unless the RPK
  9251. * certificate is preferred by the user and actually loaded.
  9252. */
  9253. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_RPK,
  9254. ssl->options.rpkConfig.preferred_ClientCertTypeCnt,
  9255. ssl->options.rpkConfig.preferred_ClientCertTypes)) {
  9256. if (ssl->options.rpkState.isRPKLoaded) {
  9257. ssl->options.rpkState.sending_ClientCertTypeCnt = 1;
  9258. ssl->options.rpkState.sending_ClientCertTypes[0] =
  9259. WOLFSSL_CERT_TYPE_RPK;
  9260. /* Push new client_certificate_type extension. */
  9261. WOLFSSL_MSG("Adding Client Certificate Type extension");
  9262. ret = TLSX_Push(&ssl->extensions, TLSX_CLIENT_CERTIFICATE_TYPE,
  9263. ssl, ssl->heap);
  9264. }
  9265. else {
  9266. WOLFSSL_MSG("Willing to use RPK cert but not loaded it");
  9267. }
  9268. }
  9269. else {
  9270. WOLFSSL_MSG("No will to use RPK cert");
  9271. }
  9272. }
  9273. return ret;
  9274. }
  9275. /* Parse a "client certificate type" extension received from peer.
  9276. * returns 0 on success and other values indicate failure.
  9277. */
  9278. static int TLSX_ClientCertificateType_Parse(WOLFSSL* ssl, const byte* input,
  9279. word16 length, byte msgType)
  9280. {
  9281. byte typeCnt;
  9282. int idx = 0;
  9283. int ret = 0;
  9284. int i;
  9285. int populate = 0;
  9286. byte cmnType;
  9287. if (msgType == client_hello) {
  9288. /* [parse ClientHello in server end]
  9289. * case 1) if peer verify is disabled, this extension must be omitted
  9290. * from ServerHello.
  9291. * case 2) if user have not set his preference, find X509 in parsed
  9292. * result, then populate "Client Certificate Type" extension.
  9293. * case 3) if user have not set his preference and X509 isn't included
  9294. * in parsed result, send "unsupported certificate" alert.
  9295. * case 4) if user have set his preference, find a common cert type
  9296. * in users preference and received cert types.
  9297. * case 5) if user have set his preference, but no common cert type
  9298. * found.
  9299. */
  9300. /* case 1 */
  9301. if (ssl->options.verifyNone) {
  9302. return ret;
  9303. }
  9304. /* parse extension */
  9305. if (length < OPAQUE8_LEN)
  9306. return BUFFER_E;
  9307. typeCnt = input[idx];
  9308. if (typeCnt > MAX_CLIENT_CERT_TYPE_CNT)
  9309. return BUFFER_E;
  9310. if ((typeCnt + 1) * OPAQUE8_LEN != length){
  9311. return BUFFER_E;
  9312. }
  9313. ssl->options.rpkState.received_ClientCertTypeCnt = input[idx];
  9314. idx += OPAQUE8_LEN;
  9315. for (i = 0; i < typeCnt; i++) {
  9316. ssl->options.rpkState.received_ClientCertTypes[i] = input[idx];
  9317. idx += OPAQUE8_LEN;
  9318. }
  9319. if (ssl->options.rpkConfig.preferred_ClientCertTypeCnt == 0) {
  9320. /* case 2 */
  9321. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_X509,
  9322. ssl->options.rpkState.received_ClientCertTypeCnt,
  9323. ssl->options.rpkState.received_ClientCertTypes)) {
  9324. ssl->options.rpkState.sending_ClientCertTypeCnt = 1;
  9325. ssl->options.rpkState.sending_ClientCertTypes[0] =
  9326. WOLFSSL_CERT_TYPE_X509;
  9327. populate = 1;
  9328. }
  9329. /* case 3 */
  9330. else {
  9331. WOLFSSL_MSG("No common cert type found in client_certificate_type ext");
  9332. SendAlert(ssl, alert_fatal, unsupported_certificate);
  9333. return UNSUPPORTED_CERTIFICATE;
  9334. }
  9335. }
  9336. else if (ssl->options.rpkConfig.preferred_ClientCertTypeCnt > 0) {
  9337. /* case 4 */
  9338. if (GetCommonItem(
  9339. ssl->options.rpkConfig.preferred_ClientCertTypes,
  9340. ssl->options.rpkConfig.preferred_ClientCertTypeCnt,
  9341. ssl->options.rpkState.received_ClientCertTypes,
  9342. ssl->options.rpkState.received_ClientCertTypeCnt,
  9343. &cmnType)) {
  9344. ssl->options.rpkState.sending_ClientCertTypeCnt = 1;
  9345. ssl->options.rpkState.sending_ClientCertTypes[0] = cmnType;
  9346. populate = 1;
  9347. }
  9348. /* case 5 */
  9349. else {
  9350. WOLFSSL_MSG("No common cert type found in client_certificate_type ext");
  9351. SendAlert(ssl, alert_fatal, unsupported_certificate);
  9352. return UNSUPPORTED_CERTIFICATE;
  9353. }
  9354. }
  9355. /* populate client_certificate_type extension */
  9356. if (populate) {
  9357. WOLFSSL_MSG("Adding Client Certificate Type extension");
  9358. ret = TLSX_Push(&ssl->extensions, TLSX_CLIENT_CERTIFICATE_TYPE, ssl,
  9359. ssl->heap);
  9360. if (ret == 0) {
  9361. TLSX_SetResponse(ssl, TLSX_CLIENT_CERTIFICATE_TYPE);
  9362. }
  9363. }
  9364. }
  9365. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9366. /* parse it in client side */
  9367. if (length == 1) {
  9368. ssl->options.rpkState.received_ClientCertTypeCnt = 1;
  9369. ssl->options.rpkState.received_ClientCertTypes[0] = *input;
  9370. }
  9371. else {
  9372. return BUFFER_E;
  9373. }
  9374. }
  9375. return ret;
  9376. }
  9377. /* Write out the "client certificate type" extension data into the given buffer.
  9378. * return the size wrote in the buffer on success, negative value on error.
  9379. */
  9380. static word16 TLSX_ClientCertificateType_Write(void* data, byte* output,
  9381. byte msgType)
  9382. {
  9383. WOLFSSL* ssl = (WOLFSSL*)data;
  9384. word16 idx = 0;
  9385. byte cnt = 0;
  9386. int i;
  9387. /* skip to write extension if count is zero */
  9388. cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;
  9389. if (cnt == 0)
  9390. return 0;
  9391. if (msgType == client_hello) {
  9392. /* client side */
  9393. *(output + idx) = cnt;
  9394. idx += OPAQUE8_LEN;
  9395. for (i = 0; i < cnt; i++) {
  9396. *(output + idx) = ssl->options.rpkState.sending_ClientCertTypes[i];
  9397. idx += OPAQUE8_LEN;
  9398. }
  9399. return idx;
  9400. }
  9401. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9402. /* sever side */
  9403. if (cnt == 1) {
  9404. *(output + idx) = ssl->options.rpkState.sending_ClientCertTypes[0];
  9405. idx += OPAQUE8_LEN;
  9406. }
  9407. }
  9408. return idx;
  9409. }
  9410. /* Calculate then return the size of the "client certificate type" extension
  9411. * data.
  9412. * return the extension data size on success, negative value on error.
  9413. */
  9414. static int TLSX_ClientCertificateType_GetSize(WOLFSSL* ssl, byte msgType)
  9415. {
  9416. int ret = 0;
  9417. byte cnt;
  9418. if (ssl == NULL)
  9419. return BAD_FUNC_ARG;
  9420. if (msgType == client_hello) {
  9421. /* client side */
  9422. cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;
  9423. ret = (int)(OPAQUE8_LEN + cnt * OPAQUE8_LEN);
  9424. }
  9425. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9426. /* sever side */
  9427. cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;/* must be one */
  9428. ret = OPAQUE8_LEN;
  9429. }
  9430. else {
  9431. return SANITY_MSG_E;
  9432. }
  9433. return ret;
  9434. }
  9435. #define CCT_GET_SIZE TLSX_ClientCertificateType_GetSize
  9436. #define CCT_WRITE TLSX_ClientCertificateType_Write
  9437. #define CCT_PARSE TLSX_ClientCertificateType_Parse
  9438. #else
  9439. #define CCT_GET_SIZE(a) 0
  9440. #define CCT_WRITE(a, b) 0
  9441. #define CCT_PARSE(a, b, c, d) 0
  9442. #endif /* HAVE_RPK */
  9443. #if defined(HAVE_RPK)
  9444. /******************************************************************************/
  9445. /* Server_Certificate_Type extension */
  9446. /******************************************************************************/
  9447. /* Creates a "server certificate type" extension if necessary.
  9448. * Returns 0 if no error occurred, negative value otherwise.
  9449. * A return of 0, it does not indicae that the extension was created.
  9450. */
  9451. static int TLSX_ServerCertificateType_Use(WOLFSSL* ssl, byte isServer)
  9452. {
  9453. int ret = 0;
  9454. byte ctype;
  9455. if (ssl == NULL)
  9456. return BAD_FUNC_ARG;
  9457. if (isServer) {
  9458. /* [in server side] */
  9459. /* find common cert type to both end */
  9460. if (GetCommonItem(
  9461. ssl->options.rpkConfig.preferred_ServerCertTypes,
  9462. ssl->options.rpkConfig.preferred_ServerCertTypeCnt,
  9463. ssl->options.rpkState.received_ServerCertTypes,
  9464. ssl->options.rpkState.received_ServerCertTypeCnt,
  9465. &ctype)) {
  9466. ssl->options.rpkState.sending_ServerCertTypeCnt = 1;
  9467. ssl->options.rpkState.sending_ServerCertTypes[0] = ctype;
  9468. /* Push new server_certificate_type extension. */
  9469. WOLFSSL_MSG("Adding Server Certificate Type extension");
  9470. ret = TLSX_Push(&ssl->extensions, TLSX_SERVER_CERTIFICATE_TYPE, ssl,
  9471. ssl->heap);
  9472. if (ret == 0) {
  9473. TLSX_SetResponse(ssl, TLSX_SERVER_CERTIFICATE_TYPE);
  9474. }
  9475. }
  9476. else {
  9477. /* no common cert type found */
  9478. WOLFSSL_MSG("No common cert type found in server_certificate_type ext");
  9479. SendAlert(ssl, alert_fatal, unsupported_certificate);
  9480. ret = UNSUPPORTED_CERTIFICATE;
  9481. }
  9482. }
  9483. else {
  9484. /* [in client side] */
  9485. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_RPK,
  9486. ssl->options.rpkConfig.preferred_ServerCertTypeCnt,
  9487. ssl->options.rpkConfig.preferred_ServerCertTypes)) {
  9488. ssl->options.rpkState.sending_ServerCertTypeCnt =
  9489. ssl->options.rpkConfig.preferred_ServerCertTypeCnt;
  9490. XMEMCPY(ssl->options.rpkState.sending_ServerCertTypes,
  9491. ssl->options.rpkConfig.preferred_ServerCertTypes,
  9492. ssl->options.rpkConfig.preferred_ServerCertTypeCnt);
  9493. /* Push new server_certificate_type extension. */
  9494. WOLFSSL_MSG("Adding Server Certificate Type extension");
  9495. ret = TLSX_Push(&ssl->extensions, TLSX_SERVER_CERTIFICATE_TYPE, ssl,
  9496. ssl->heap);
  9497. }
  9498. else {
  9499. WOLFSSL_MSG("No will to accept RPK cert");
  9500. }
  9501. }
  9502. return ret;
  9503. }
  9504. /* Parse a "server certificate type" extension received from peer.
  9505. * returns 0 on success and other values indicate failure.
  9506. */
  9507. static int TLSX_ServerCertificateType_Parse(WOLFSSL* ssl, const byte* input,
  9508. word16 length, byte msgType)
  9509. {
  9510. byte typeCnt;
  9511. int idx = 0;
  9512. int ret = 0;
  9513. int i;
  9514. if (msgType == client_hello) {
  9515. /* in server side */
  9516. if (length < OPAQUE8_LEN)
  9517. return BUFFER_E;
  9518. typeCnt = input[idx];
  9519. if (typeCnt > MAX_SERVER_CERT_TYPE_CNT)
  9520. return BUFFER_E;
  9521. if ((typeCnt + 1) * OPAQUE8_LEN != length){
  9522. return BUFFER_E;
  9523. }
  9524. ssl->options.rpkState.received_ServerCertTypeCnt = input[idx];
  9525. idx += OPAQUE8_LEN;
  9526. for (i = 0; i < typeCnt; i++) {
  9527. ssl->options.rpkState.received_ServerCertTypes[i] = input[idx];
  9528. idx += OPAQUE8_LEN;
  9529. }
  9530. ret = TLSX_ServerCertificateType_Use(ssl, 1);
  9531. if (ret == 0) {
  9532. TLSX_SetResponse(ssl, TLSX_SERVER_CERTIFICATE_TYPE);
  9533. }
  9534. }
  9535. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9536. /* in client side */
  9537. if (length != 1) /* length slould be 1 */
  9538. return BUFFER_E;
  9539. ssl->options.rpkState.received_ServerCertTypeCnt = 1;
  9540. ssl->options.rpkState.received_ServerCertTypes[0] = *input;
  9541. }
  9542. return 0;
  9543. }
  9544. /* Write out the "server certificate type" extension data into the given buffer.
  9545. * return the size wrote in the buffer on success, negative value on error.
  9546. */
  9547. static word16 TLSX_ServerCertificateType_Write(void* data, byte* output,
  9548. byte msgType)
  9549. {
  9550. WOLFSSL* ssl = (WOLFSSL*)data;
  9551. word16 idx = 0;
  9552. int cnt = 0;
  9553. int i;
  9554. /* skip to write extension if count is zero */
  9555. cnt = ssl->options.rpkState.sending_ServerCertTypeCnt;
  9556. if (cnt == 0)
  9557. return 0;
  9558. if (msgType == client_hello) {
  9559. /* in client side */
  9560. *(output + idx) = cnt;
  9561. idx += OPAQUE8_LEN;
  9562. for (i = 0; i < cnt; i++) {
  9563. *(output + idx) = ssl->options.rpkState.sending_ServerCertTypes[i];
  9564. idx += OPAQUE8_LEN;
  9565. }
  9566. }
  9567. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9568. /* in server side */
  9569. /* ensure cnt is one */
  9570. if (cnt != 1)
  9571. return 0;
  9572. *(output + idx) = ssl->options.rpkState.sending_ServerCertTypes[0];
  9573. idx += OPAQUE8_LEN;
  9574. }
  9575. return idx;
  9576. }
  9577. /* Calculate then return the size of the "server certificate type" extension
  9578. * data.
  9579. * return the extension data size on success, negative value on error.
  9580. */
  9581. static int TLSX_ServerCertificateType_GetSize(WOLFSSL* ssl, byte msgType)
  9582. {
  9583. int ret = 0;
  9584. int cnt;
  9585. if (ssl == NULL)
  9586. return BAD_FUNC_ARG;
  9587. if (msgType == client_hello) {
  9588. /* in clent side */
  9589. cnt = ssl->options.rpkState.sending_ServerCertTypeCnt;
  9590. if (cnt > 0) {
  9591. ret = (int)(OPAQUE8_LEN + cnt * OPAQUE8_LEN);
  9592. }
  9593. }
  9594. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9595. /* in server side */
  9596. ret = (int)OPAQUE8_LEN;
  9597. }
  9598. else {
  9599. return SANITY_MSG_E;
  9600. }
  9601. return ret;
  9602. }
  9603. #define SCT_GET_SIZE TLSX_ServerCertificateType_GetSize
  9604. #define SCT_WRITE TLSX_ServerCertificateType_Write
  9605. #define SCT_PARSE TLSX_ServerCertificateType_Parse
  9606. #else
  9607. #define SCT_GET_SIZE(a) 0
  9608. #define SCT_WRITE(a, b) 0
  9609. #define SCT_PARSE(a, b, c, d) 0
  9610. #endif /* HAVE_RPK */
  9611. /******************************************************************************/
  9612. /* TLS Extensions Framework */
  9613. /******************************************************************************/
  9614. /** Finds an extension in the provided list. */
  9615. TLSX* TLSX_Find(TLSX* list, TLSX_Type type)
  9616. {
  9617. TLSX* extension = list;
  9618. while (extension && extension->type != type)
  9619. extension = extension->next;
  9620. return extension;
  9621. }
  9622. /** Remove an extension. */
  9623. void TLSX_Remove(TLSX** list, TLSX_Type type, void* heap)
  9624. {
  9625. TLSX* extension;
  9626. TLSX** next;
  9627. if (list == NULL)
  9628. return;
  9629. extension = *list;
  9630. next = list;
  9631. while (extension && extension->type != type) {
  9632. next = &extension->next;
  9633. extension = extension->next;
  9634. }
  9635. if (extension) {
  9636. *next = extension->next;
  9637. extension->next = NULL;
  9638. TLSX_FreeAll(extension, heap);
  9639. }
  9640. }
  9641. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  9642. #define GREASE_ECH_SIZE 160
  9643. #define MAX_PUBLIC_NAME_SZ 256
  9644. #define TLS_INFO_CONST_STRING "tls ech"
  9645. #define TLS_INFO_CONST_STRING_SZ 7
  9646. /* return status after setting up ech to write a grease ech */
  9647. static int TLSX_GreaseECH_Use(TLSX** extensions, void* heap, WC_RNG* rng)
  9648. {
  9649. int ret = 0;
  9650. WOLFSSL_ECH* ech;
  9651. if (extensions == NULL)
  9652. return BAD_FUNC_ARG;
  9653. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9654. DYNAMIC_TYPE_TMP_BUFFER);
  9655. if (ech == NULL)
  9656. return MEMORY_E;
  9657. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9658. ech->state = ECH_WRITE_GREASE;
  9659. /* 0 for outer */
  9660. ech->type = ECH_TYPE_OUTER;
  9661. /* kemId */
  9662. ech->kemId = DHKEM_X25519_HKDF_SHA256;
  9663. /* cipherSuite kdf */
  9664. ech->cipherSuite.kdfId = HKDF_SHA256;
  9665. /* cipherSuite aead */
  9666. ech->cipherSuite.aeadId = HPKE_AES_128_GCM;
  9667. /* random configId */
  9668. ret = wc_RNG_GenerateByte(rng, &(ech->configId));
  9669. /* curve25519 encLen */
  9670. ech->encLen = DHKEM_X25519_ENC_LEN;
  9671. if (ret == 0)
  9672. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9673. if (ret != 0) {
  9674. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9675. }
  9676. return ret;
  9677. }
  9678. /* return status after setting up ech to write real ech */
  9679. static int TLSX_ECH_Use(WOLFSSL_EchConfig* echConfig, TLSX** extensions,
  9680. void* heap, WC_RNG* rng)
  9681. {
  9682. int ret = 0;
  9683. int suiteIndex;
  9684. WOLFSSL_ECH* ech;
  9685. if (extensions == NULL)
  9686. return BAD_FUNC_ARG;
  9687. /* find a supported cipher suite */
  9688. suiteIndex = EchConfigGetSupportedCipherSuite(echConfig);
  9689. if (suiteIndex < 0)
  9690. return suiteIndex;
  9691. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9692. DYNAMIC_TYPE_TMP_BUFFER);
  9693. if (ech == NULL)
  9694. return MEMORY_E;
  9695. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9696. ech->state = ECH_WRITE_REAL;
  9697. ech->echConfig = echConfig;
  9698. /* 0 for outer */
  9699. ech->type = ECH_TYPE_OUTER;
  9700. /* kemId */
  9701. ech->kemId = echConfig->kemId;
  9702. /* cipherSuite kdf */
  9703. ech->cipherSuite.kdfId = echConfig->cipherSuites[suiteIndex].kdfId;
  9704. /* cipherSuite aead */
  9705. ech->cipherSuite.aeadId = echConfig->cipherSuites[suiteIndex].aeadId;
  9706. /* configId */
  9707. ech->configId = echConfig->configId;
  9708. /* encLen */
  9709. switch (echConfig->kemId)
  9710. {
  9711. case DHKEM_P256_HKDF_SHA256:
  9712. ech->encLen = DHKEM_P256_ENC_LEN;
  9713. break;
  9714. case DHKEM_P384_HKDF_SHA384:
  9715. ech->encLen = DHKEM_P384_ENC_LEN;
  9716. break;
  9717. case DHKEM_P521_HKDF_SHA512:
  9718. ech->encLen = DHKEM_P521_ENC_LEN;
  9719. break;
  9720. case DHKEM_X25519_HKDF_SHA256:
  9721. ech->encLen = DHKEM_X25519_ENC_LEN;
  9722. break;
  9723. case DHKEM_X448_HKDF_SHA512:
  9724. ech->encLen = DHKEM_X448_ENC_LEN;
  9725. break;
  9726. }
  9727. /* setup hpke */
  9728. ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER);
  9729. if (ech->hpke == NULL) {
  9730. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9731. return MEMORY_E;
  9732. }
  9733. ret = wc_HpkeInit(ech->hpke, ech->kemId, ech->cipherSuite.kdfId,
  9734. ech->cipherSuite.aeadId, heap);
  9735. /* setup the ephemeralKey */
  9736. if (ret == 0)
  9737. ret = wc_HpkeGenerateKeyPair(ech->hpke, &ech->ephemeralKey, rng);
  9738. if (ret == 0)
  9739. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9740. if (ret != 0) {
  9741. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9742. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9743. }
  9744. return ret;
  9745. }
  9746. /* return status after setting up ech to read and decrypt */
  9747. static int TLSX_ServerECH_Use(TLSX** extensions, void* heap,
  9748. WOLFSSL_EchConfig* configs)
  9749. {
  9750. int ret;
  9751. WOLFSSL_ECH* ech;
  9752. TLSX* echX;
  9753. if (extensions == NULL)
  9754. return BAD_FUNC_ARG;
  9755. /* if we already have ech don't override it */
  9756. echX = TLSX_Find(*extensions, TLSX_ECH);
  9757. if (echX != NULL)
  9758. return 0;
  9759. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9760. DYNAMIC_TYPE_TMP_BUFFER);
  9761. if (ech == NULL)
  9762. return MEMORY_E;
  9763. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9764. ech->state = ECH_WRITE_NONE;
  9765. /* 0 for outer */
  9766. ech->type = ECH_TYPE_OUTER;
  9767. ech->echConfig = configs;
  9768. /* setup the rest of the settings when we receive ech from the client */
  9769. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9770. if (ret != 0)
  9771. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9772. return ret;
  9773. }
  9774. /* return length after writing the ech */
  9775. static int TLSX_ECH_Write(WOLFSSL_ECH* ech, byte* writeBuf, word16* offset)
  9776. {
  9777. int ret = 0;
  9778. int rngRet = -1;
  9779. word32 configsLen = 0;
  9780. void* ephemeralKey = NULL;
  9781. byte* writeBuf_p = writeBuf;
  9782. #ifdef WOLFSSL_SMALL_STACK
  9783. Hpke* hpke = NULL;
  9784. WC_RNG* rng = NULL;
  9785. #else
  9786. Hpke hpke[1];
  9787. WC_RNG rng[1];
  9788. #endif
  9789. WOLFSSL_MSG("TLSX_ECH_Write");
  9790. if (ech->state == ECH_WRITE_NONE || ech->state == ECH_PARSED_INTERNAL)
  9791. return 0;
  9792. if (ech->state == ECH_WRITE_RETRY_CONFIGS) {
  9793. /* get size then write */
  9794. ret = GetEchConfigsEx(ech->echConfig, NULL, &configsLen);
  9795. if (ret != LENGTH_ONLY_E)
  9796. return ret;
  9797. ret = GetEchConfigsEx(ech->echConfig, writeBuf, &configsLen);
  9798. if (ret != WOLFSSL_SUCCESS)
  9799. return ret;
  9800. *offset += configsLen;
  9801. return 0;
  9802. }
  9803. #ifdef WOLFSSL_SMALL_STACK
  9804. hpke = (Hpke*)XMALLOC(sizeof(Hpke), NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9805. if (hpke == NULL)
  9806. return MEMORY_E;
  9807. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  9808. if (rng == NULL) {
  9809. XFREE(hpke, NULL, DYNAMIC_TYPE_RNG);
  9810. return MEMORY_E;
  9811. }
  9812. #endif
  9813. /* type */
  9814. *writeBuf_p = ech->type;
  9815. writeBuf_p += sizeof(ech->type);
  9816. /* outer has body, inner does not */
  9817. if (ech->type == ECH_TYPE_OUTER) {
  9818. /* kdfId */
  9819. c16toa(ech->cipherSuite.kdfId, writeBuf_p);
  9820. writeBuf_p += sizeof(ech->cipherSuite.kdfId);
  9821. /* aeadId */
  9822. c16toa(ech->cipherSuite.aeadId, writeBuf_p);
  9823. writeBuf_p += sizeof(ech->cipherSuite.aeadId);
  9824. /* configId */
  9825. *writeBuf_p = ech->configId;
  9826. writeBuf_p += sizeof(ech->configId);
  9827. /* encLen */
  9828. c16toa(ech->encLen, writeBuf_p);
  9829. writeBuf_p += 2;
  9830. if (ech->state == ECH_WRITE_GREASE) {
  9831. /* hpke init */
  9832. ret = wc_HpkeInit(hpke, ech->kemId, ech->cipherSuite.kdfId,
  9833. ech->cipherSuite.aeadId, NULL);
  9834. if (ret == 0)
  9835. rngRet = ret = wc_InitRng(rng);
  9836. /* create the ephemeralKey */
  9837. if (ret == 0)
  9838. ret = wc_HpkeGenerateKeyPair(hpke, &ephemeralKey, rng);
  9839. /* enc */
  9840. if (ret == 0) {
  9841. ret = wc_HpkeSerializePublicKey(hpke, ephemeralKey, writeBuf_p,
  9842. &ech->encLen);
  9843. writeBuf_p += ech->encLen;
  9844. }
  9845. if (ret == 0) {
  9846. /* innerClientHelloLen */
  9847. c16toa(GREASE_ECH_SIZE + ((writeBuf_p + 2 - writeBuf) % 32),
  9848. writeBuf_p);
  9849. writeBuf_p += 2;
  9850. /* innerClientHello */
  9851. ret = wc_RNG_GenerateBlock(rng, writeBuf_p, GREASE_ECH_SIZE +
  9852. ((writeBuf_p - writeBuf) % 32));
  9853. writeBuf_p += GREASE_ECH_SIZE + ((writeBuf_p - writeBuf) % 32);
  9854. }
  9855. if (rngRet == 0)
  9856. wc_FreeRng(rng);
  9857. if (ephemeralKey != NULL)
  9858. wc_HpkeFreeKey(hpke, hpke->kem, ephemeralKey, hpke->heap);
  9859. }
  9860. else {
  9861. /* write enc to writeBuf_p */
  9862. ret = wc_HpkeSerializePublicKey(ech->hpke, ech->ephemeralKey,
  9863. writeBuf_p, &ech->encLen);
  9864. writeBuf_p += ech->encLen;
  9865. /* innerClientHelloLen */
  9866. c16toa(ech->innerClientHelloLen, writeBuf_p);
  9867. writeBuf_p += 2;
  9868. /* set payload offset for when we finalize */
  9869. ech->outerClientPayload = writeBuf_p;
  9870. /* write zeros for payload */
  9871. XMEMSET(writeBuf_p, 0, ech->innerClientHelloLen);
  9872. writeBuf_p += ech->innerClientHelloLen;
  9873. }
  9874. }
  9875. #ifdef WOLFSSL_SMALL_STACK
  9876. XFREE(hpke, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9877. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  9878. #endif
  9879. if (ret == 0)
  9880. *offset += (writeBuf_p - writeBuf);
  9881. return ret;
  9882. }
  9883. /* return the size needed for the ech extension */
  9884. static int TLSX_ECH_GetSize(WOLFSSL_ECH* ech)
  9885. {
  9886. int ret;
  9887. word32 size;
  9888. if (ech->state == ECH_WRITE_GREASE) {
  9889. size = sizeof(ech->type) + sizeof(ech->cipherSuite) +
  9890. sizeof(ech->configId) + sizeof(word16) + ech->encLen +
  9891. sizeof(word16);
  9892. size += GREASE_ECH_SIZE + (size % 32);
  9893. }
  9894. else if (ech->state == ECH_WRITE_NONE ||
  9895. ech->state == ECH_PARSED_INTERNAL) {
  9896. size = 0;
  9897. }
  9898. else if (ech->state == ECH_WRITE_RETRY_CONFIGS) {
  9899. /* get the size of the raw configs */
  9900. ret = GetEchConfigsEx(ech->echConfig, NULL, &size);
  9901. if (ret != LENGTH_ONLY_E)
  9902. return ret;
  9903. }
  9904. else if (ech->type == ECH_TYPE_INNER)
  9905. {
  9906. size = sizeof(ech->type);
  9907. }
  9908. else
  9909. {
  9910. size = sizeof(ech->type) + sizeof(ech->cipherSuite) +
  9911. sizeof(ech->configId) + sizeof(word16) + ech->encLen +
  9912. sizeof(word16) + ech->innerClientHelloLen;
  9913. }
  9914. return (int)size;
  9915. }
  9916. /* return status after attempting to open the hpke encrypted ech extension, if
  9917. * successful the inner client hello will be stored in
  9918. * ech->innerClientHelloLen */
  9919. static int TLSX_ExtractEch(WOLFSSL_ECH* ech, WOLFSSL_EchConfig* echConfig,
  9920. byte* aad, word32 aadLen, void* heap)
  9921. {
  9922. int ret = 0;
  9923. int expectedEncLen;
  9924. int i;
  9925. word32 rawConfigLen = 0;
  9926. byte* info = NULL;
  9927. word32 infoLen = 0;
  9928. if (ech == NULL || echConfig == NULL || aad == NULL)
  9929. return BAD_FUNC_ARG;
  9930. /* verify the kem and key len */
  9931. switch (echConfig->kemId)
  9932. {
  9933. case DHKEM_P256_HKDF_SHA256:
  9934. expectedEncLen = DHKEM_P256_ENC_LEN;
  9935. break;
  9936. case DHKEM_P384_HKDF_SHA384:
  9937. expectedEncLen = DHKEM_P384_ENC_LEN;
  9938. break;
  9939. case DHKEM_P521_HKDF_SHA512:
  9940. expectedEncLen = DHKEM_P521_ENC_LEN;
  9941. break;
  9942. case DHKEM_X25519_HKDF_SHA256:
  9943. expectedEncLen = DHKEM_X25519_ENC_LEN;
  9944. break;
  9945. case DHKEM_X448_HKDF_SHA512:
  9946. expectedEncLen = DHKEM_X448_ENC_LEN;
  9947. break;
  9948. default:
  9949. expectedEncLen = 0;
  9950. break;
  9951. }
  9952. if (expectedEncLen != ech->encLen)
  9953. return BAD_FUNC_ARG;
  9954. /* verify the cipher suite */
  9955. for (i = 0; i < echConfig->numCipherSuites; i++) {
  9956. if (echConfig->cipherSuites[i].kdfId == ech->cipherSuite.kdfId &&
  9957. echConfig->cipherSuites[i].aeadId == ech->cipherSuite.aeadId) {
  9958. break;
  9959. }
  9960. }
  9961. if (i >= echConfig->numCipherSuites) {
  9962. return BAD_FUNC_ARG;
  9963. }
  9964. ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER);
  9965. if (ech->hpke == NULL)
  9966. return MEMORY_E;
  9967. ret = wc_HpkeInit(ech->hpke, echConfig->kemId, ech->cipherSuite.kdfId,
  9968. ech->cipherSuite.aeadId, heap);
  9969. /* get the rawConfigLen */
  9970. if (ret == 0)
  9971. ret = GetEchConfig(echConfig, NULL, &rawConfigLen);
  9972. if (ret == LENGTH_ONLY_E)
  9973. ret = 0;
  9974. /* create info */
  9975. if (ret == 0) {
  9976. infoLen = TLS_INFO_CONST_STRING_SZ + 1 + rawConfigLen;
  9977. info = (byte*)XMALLOC(infoLen, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9978. if (info == NULL)
  9979. ret = MEMORY_E;
  9980. else {
  9981. XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING,
  9982. TLS_INFO_CONST_STRING_SZ + 1);
  9983. ret = GetEchConfig(echConfig, info +
  9984. TLS_INFO_CONST_STRING_SZ + 1, &rawConfigLen);
  9985. }
  9986. }
  9987. /* decrypt the ech payload */
  9988. if (ret == 0)
  9989. ret = wc_HpkeOpenBase(ech->hpke, echConfig->receiverPrivkey, ech->enc,
  9990. ech->encLen, info, infoLen, aad, aadLen, ech->outerClientPayload,
  9991. ech->innerClientHelloLen,
  9992. ech->innerClientHello + HANDSHAKE_HEADER_SZ);
  9993. if (ret != 0) {
  9994. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9995. ech->hpke = NULL;
  9996. }
  9997. if (info != NULL)
  9998. XFREE(info, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9999. return ret;
  10000. }
  10001. /* parse the ech extension, if internal update ech->state and return, if
  10002. * external attempt to extract the inner client_hello, return the status */
  10003. static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size,
  10004. byte msgType)
  10005. {
  10006. int ret = 0;
  10007. int i;
  10008. TLSX* echX;
  10009. WOLFSSL_ECH* ech;
  10010. WOLFSSL_EchConfig* echConfig;
  10011. byte* aadCopy;
  10012. byte* readBuf_p = (byte*)readBuf;
  10013. WOLFSSL_MSG("TLSX_ECH_Parse");
  10014. if (size == 0)
  10015. return BAD_FUNC_ARG;
  10016. if (msgType == encrypted_extensions) {
  10017. ret = wolfSSL_SetEchConfigs(ssl, readBuf, size);
  10018. if (ret == WOLFSSL_SUCCESS)
  10019. ret = 0;
  10020. }
  10021. else if (msgType == client_hello && ssl->ctx->echConfigs != NULL) {
  10022. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  10023. if (echX == NULL)
  10024. return BAD_FUNC_ARG;
  10025. ech = (WOLFSSL_ECH*)echX->data;
  10026. /* read the ech parameters before the payload */
  10027. ech->type = *readBuf_p;
  10028. readBuf_p++;
  10029. if (ech->type == ECH_TYPE_INNER) {
  10030. ech->state = ECH_PARSED_INTERNAL;
  10031. return 0;
  10032. }
  10033. /* technically the payload would only be 1 byte at this length */
  10034. if (size < 11 + ech->encLen)
  10035. return BAD_FUNC_ARG;
  10036. ato16(readBuf_p, &ech->cipherSuite.kdfId);
  10037. readBuf_p += 2;
  10038. ato16(readBuf_p, &ech->cipherSuite.aeadId);
  10039. readBuf_p += 2;
  10040. ech->configId = *readBuf_p;
  10041. readBuf_p++;
  10042. ato16(readBuf_p, &ech->encLen);
  10043. readBuf_p += 2;
  10044. if (ech->encLen > HPKE_Npk_MAX)
  10045. return BAD_FUNC_ARG;
  10046. XMEMCPY(ech->enc, readBuf_p, ech->encLen);
  10047. readBuf_p += ech->encLen;
  10048. ato16(readBuf_p, &ech->innerClientHelloLen);
  10049. ech->innerClientHelloLen -= AES_BLOCK_SIZE;
  10050. readBuf_p += 2;
  10051. ech->outerClientPayload = readBuf_p;
  10052. /* make a copy of the aad */
  10053. aadCopy = (byte*)XMALLOC(ech->aadLen, ssl->heap,
  10054. DYNAMIC_TYPE_TMP_BUFFER);
  10055. if (aadCopy == NULL)
  10056. return MEMORY_E;
  10057. XMEMCPY(aadCopy, ech->aad, ech->aadLen);
  10058. /* set the ech payload of the copy to zeros */
  10059. XMEMSET(aadCopy + (readBuf_p - ech->aad), 0,
  10060. ech->innerClientHelloLen + AES_BLOCK_SIZE);
  10061. /* allocate the inner payload buffer */
  10062. ech->innerClientHello =
  10063. (byte*)XMALLOC(ech->innerClientHelloLen + HANDSHAKE_HEADER_SZ,
  10064. ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10065. if (ech->innerClientHello == NULL) {
  10066. XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10067. return MEMORY_E;
  10068. }
  10069. /* first check if the config id matches */
  10070. echConfig = ssl->ctx->echConfigs;
  10071. while (echConfig != NULL) {
  10072. /* decrypt with this config */
  10073. if (echConfig->configId == ech->configId) {
  10074. ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen,
  10075. ssl->heap);
  10076. break;
  10077. }
  10078. echConfig = echConfig->next;
  10079. }
  10080. /* try to decrypt with all configs */
  10081. if (echConfig == NULL || ret != 0) {
  10082. echConfig = ssl->ctx->echConfigs;
  10083. while (echConfig != NULL) {
  10084. ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen,
  10085. ssl->heap);
  10086. if (ret== 0)
  10087. break;
  10088. echConfig = echConfig->next;
  10089. }
  10090. }
  10091. /* if we failed to extract */
  10092. if (ret != 0) {
  10093. XFREE(ech->innerClientHello, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10094. ech->innerClientHello = NULL;
  10095. ech->state = ECH_WRITE_RETRY_CONFIGS;
  10096. }
  10097. else {
  10098. i = 0;
  10099. /* decrement until before the padding */
  10100. while (ech->innerClientHello[ech->innerClientHelloLen +
  10101. HANDSHAKE_HEADER_SZ - i - 1] != ECH_TYPE_INNER) {
  10102. i++;
  10103. }
  10104. /* subtract the length of the padding from the length */
  10105. ech->innerClientHelloLen -= i;
  10106. }
  10107. XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10108. return 0;
  10109. }
  10110. return ret;
  10111. }
  10112. /* free the ech struct and the dynamic buffer it uses */
  10113. static void TLSX_ECH_Free(WOLFSSL_ECH* ech, void* heap)
  10114. {
  10115. if (ech->innerClientHello != NULL)
  10116. XFREE(ech->innerClientHello, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10117. if (ech->ephemeralKey != NULL)
  10118. wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, ech->ephemeralKey,
  10119. ech->hpke->heap);
  10120. if (ech->hpke != NULL)
  10121. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10122. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10123. (void)heap;
  10124. }
  10125. /* encrypt the client hello and store it in ech->outerClientPayload, return
  10126. * status */
  10127. int TLSX_FinalizeEch(WOLFSSL_ECH* ech, byte* aad, word32 aadLen)
  10128. {
  10129. int ret;
  10130. void* receiverPubkey = NULL;
  10131. byte* info;
  10132. int infoLen;
  10133. byte* aadCopy;
  10134. /* import the server public key */
  10135. ret = wc_HpkeDeserializePublicKey(ech->hpke, &receiverPubkey,
  10136. ech->echConfig->receiverPubkey, ech->encLen);
  10137. if (ret == 0) {
  10138. /* create info */
  10139. infoLen = TLS_INFO_CONST_STRING_SZ + 1 + ech->echConfig->rawLen;
  10140. info = (byte*)XMALLOC(infoLen, ech->hpke->heap,
  10141. DYNAMIC_TYPE_TMP_BUFFER);
  10142. if (info == NULL)
  10143. ret = MEMORY_E;
  10144. if (ret == 0) {
  10145. /* puts the null byte in for me */
  10146. XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING, TLS_INFO_CONST_STRING_SZ
  10147. + 1);
  10148. XMEMCPY(info + TLS_INFO_CONST_STRING_SZ + 1, ech->echConfig->raw,
  10149. ech->echConfig->rawLen);
  10150. /* make a copy of the aad since we overwrite it */
  10151. aadCopy = (byte*)XMALLOC(aadLen, ech->hpke->heap,
  10152. DYNAMIC_TYPE_TMP_BUFFER);
  10153. if (aadCopy == NULL) {
  10154. XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10155. ret = MEMORY_E;
  10156. }
  10157. }
  10158. if (ret == 0) {
  10159. XMEMCPY(aadCopy, aad, aadLen);
  10160. /* seal the payload */
  10161. ret = wc_HpkeSealBase(ech->hpke, ech->ephemeralKey, receiverPubkey,
  10162. info, infoLen, aadCopy, aadLen, ech->innerClientHello,
  10163. ech->innerClientHelloLen - ech->hpke->Nt,
  10164. ech->outerClientPayload);
  10165. XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10166. XFREE(aadCopy, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10167. }
  10168. }
  10169. if (receiverPubkey != NULL)
  10170. wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, receiverPubkey,
  10171. ech->hpke->heap);
  10172. return ret;
  10173. }
  10174. #define GREASE_ECH_USE TLSX_GreaseECH_Use
  10175. #define ECH_USE TLSX_ECH_Use
  10176. #define SERVER_ECH_USE TLSX_ServerECH_Use
  10177. #define ECH_WRITE TLSX_ECH_Write
  10178. #define ECH_GET_SIZE TLSX_ECH_GetSize
  10179. #define ECH_PARSE TLSX_ECH_Parse
  10180. #define ECH_FREE TLSX_ECH_Free
  10181. #endif
  10182. /** Releases all extensions in the provided list. */
  10183. void TLSX_FreeAll(TLSX* list, void* heap)
  10184. {
  10185. TLSX* extension;
  10186. while ((extension = list)) {
  10187. list = extension->next;
  10188. switch (extension->type) {
  10189. #if defined(HAVE_RPK)
  10190. case TLSX_CLIENT_CERTIFICATE_TYPE:
  10191. case TLSX_SERVER_CERTIFICATE_TYPE:
  10192. /* nothing to do */
  10193. break;
  10194. #endif
  10195. #ifdef HAVE_SNI
  10196. case TLSX_SERVER_NAME:
  10197. SNI_FREE_ALL((SNI*)extension->data, heap);
  10198. break;
  10199. #endif
  10200. case TLSX_TRUSTED_CA_KEYS:
  10201. TCA_FREE_ALL((TCA*)extension->data, heap);
  10202. break;
  10203. case TLSX_MAX_FRAGMENT_LENGTH:
  10204. MFL_FREE_ALL(extension->data, heap);
  10205. break;
  10206. case TLSX_EXTENDED_MASTER_SECRET:
  10207. case TLSX_TRUNCATED_HMAC:
  10208. /* Nothing to do. */
  10209. break;
  10210. case TLSX_SUPPORTED_GROUPS:
  10211. EC_FREE_ALL((SupportedCurve*)extension->data, heap);
  10212. break;
  10213. case TLSX_EC_POINT_FORMATS:
  10214. PF_FREE_ALL((PointFormat*)extension->data, heap);
  10215. break;
  10216. case TLSX_STATUS_REQUEST:
  10217. CSR_FREE_ALL((CertificateStatusRequest*)extension->data, heap);
  10218. break;
  10219. case TLSX_STATUS_REQUEST_V2:
  10220. CSR2_FREE_ALL((CertificateStatusRequestItemV2*)extension->data,
  10221. heap);
  10222. break;
  10223. case TLSX_RENEGOTIATION_INFO:
  10224. SCR_FREE_ALL(extension->data, heap);
  10225. break;
  10226. case TLSX_SESSION_TICKET:
  10227. WOLF_STK_FREE(extension->data, heap);
  10228. break;
  10229. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10230. ALPN_FREE_ALL((ALPN*)extension->data, heap);
  10231. break;
  10232. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10233. case TLSX_SIGNATURE_ALGORITHMS:
  10234. SA_FREE_ALL((SignatureAlgorithms*)extension->data, heap);
  10235. break;
  10236. #endif
  10237. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10238. case TLSX_ENCRYPT_THEN_MAC:
  10239. break;
  10240. #endif
  10241. #ifdef WOLFSSL_TLS13
  10242. case TLSX_SUPPORTED_VERSIONS:
  10243. break;
  10244. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10245. case TLSX_COOKIE:
  10246. CKE_FREE_ALL((Cookie*)extension->data, heap);
  10247. break;
  10248. #endif
  10249. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10250. case TLSX_PRE_SHARED_KEY:
  10251. PSK_FREE_ALL((PreSharedKey*)extension->data, heap);
  10252. break;
  10253. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10254. break;
  10255. #endif
  10256. #ifdef WOLFSSL_EARLY_DATA
  10257. case TLSX_EARLY_DATA:
  10258. break;
  10259. #endif
  10260. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10261. case TLSX_POST_HANDSHAKE_AUTH:
  10262. break;
  10263. #endif
  10264. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10265. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10266. break;
  10267. #endif
  10268. case TLSX_KEY_SHARE:
  10269. KS_FREE_ALL((KeyShareEntry*)extension->data, heap);
  10270. break;
  10271. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10272. case TLSX_CERTIFICATE_AUTHORITIES:
  10273. break;
  10274. #endif
  10275. #endif
  10276. #ifdef WOLFSSL_SRTP
  10277. case TLSX_USE_SRTP:
  10278. SRTP_FREE((TlsxSrtp*)extension->data, heap);
  10279. break;
  10280. #endif
  10281. #ifdef WOLFSSL_QUIC
  10282. case TLSX_KEY_QUIC_TP_PARAMS:
  10283. FALL_THROUGH;
  10284. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10285. QTP_FREE((QuicTransportParam*)extension->data, heap);
  10286. break;
  10287. #endif
  10288. #ifdef WOLFSSL_DTLS_CID
  10289. case TLSX_CONNECTION_ID:
  10290. CID_FREE((byte*)extension->data, heap);
  10291. break;
  10292. #endif /* WOLFSSL_DTLS_CID */
  10293. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10294. case TLSX_ECH:
  10295. ECH_FREE((WOLFSSL_ECH*)extension->data, heap);
  10296. break;
  10297. #endif
  10298. default:
  10299. break;
  10300. }
  10301. XFREE(extension, heap, DYNAMIC_TYPE_TLSX);
  10302. }
  10303. (void)heap;
  10304. }
  10305. /** Checks if the tls extensions are supported based on the protocol version. */
  10306. int TLSX_SupportExtensions(WOLFSSL* ssl) {
  10307. return ssl && (IsTLS(ssl) || ssl->version.major == DTLS_MAJOR);
  10308. }
  10309. /** Tells the buffered size of the extensions in a list. */
  10310. static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType,
  10311. word16* pLength)
  10312. {
  10313. int ret = 0;
  10314. TLSX* extension;
  10315. word16 length = 0;
  10316. byte isRequest = (msgType == client_hello ||
  10317. msgType == certificate_request);
  10318. while ((extension = list)) {
  10319. list = extension->next;
  10320. /* only extensions marked as response are sent back to the client. */
  10321. if (!isRequest && !extension->resp)
  10322. continue; /* skip! */
  10323. /* ssl level extensions are expected to override ctx level ones. */
  10324. if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type)))
  10325. continue; /* skip! */
  10326. /* extension type + extension data length. */
  10327. length += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN;
  10328. switch (extension->type) {
  10329. #ifdef HAVE_SNI
  10330. case TLSX_SERVER_NAME:
  10331. /* SNI only sends the name on the request. */
  10332. if (isRequest)
  10333. length += SNI_GET_SIZE((SNI*)extension->data);
  10334. break;
  10335. #endif
  10336. case TLSX_TRUSTED_CA_KEYS:
  10337. /* TCA only sends the list on the request. */
  10338. if (isRequest)
  10339. length += TCA_GET_SIZE((TCA*)extension->data);
  10340. break;
  10341. case TLSX_MAX_FRAGMENT_LENGTH:
  10342. length += MFL_GET_SIZE(extension->data);
  10343. break;
  10344. case TLSX_EXTENDED_MASTER_SECRET:
  10345. case TLSX_TRUNCATED_HMAC:
  10346. /* always empty. */
  10347. break;
  10348. case TLSX_SUPPORTED_GROUPS:
  10349. length += EC_GET_SIZE((SupportedCurve*)extension->data);
  10350. break;
  10351. case TLSX_EC_POINT_FORMATS:
  10352. length += PF_GET_SIZE((PointFormat*)extension->data);
  10353. break;
  10354. case TLSX_STATUS_REQUEST:
  10355. length += CSR_GET_SIZE(
  10356. (CertificateStatusRequest*)extension->data, isRequest);
  10357. break;
  10358. case TLSX_STATUS_REQUEST_V2:
  10359. length += CSR2_GET_SIZE(
  10360. (CertificateStatusRequestItemV2*)extension->data,
  10361. isRequest);
  10362. break;
  10363. case TLSX_RENEGOTIATION_INFO:
  10364. length += SCR_GET_SIZE((SecureRenegotiation*)extension->data,
  10365. isRequest);
  10366. break;
  10367. case TLSX_SESSION_TICKET:
  10368. length += WOLF_STK_GET_SIZE((SessionTicket*)extension->data,
  10369. isRequest);
  10370. break;
  10371. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10372. length += ALPN_GET_SIZE((ALPN*)extension->data);
  10373. break;
  10374. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10375. case TLSX_SIGNATURE_ALGORITHMS:
  10376. length += SA_GET_SIZE(extension->data);
  10377. break;
  10378. #endif
  10379. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10380. case TLSX_ENCRYPT_THEN_MAC:
  10381. ret = ETM_GET_SIZE(msgType, &length);
  10382. break;
  10383. #endif /* HAVE_ENCRYPT_THEN_MAC */
  10384. #ifdef WOLFSSL_TLS13
  10385. case TLSX_SUPPORTED_VERSIONS:
  10386. ret = SV_GET_SIZE(extension->data, msgType, &length);
  10387. break;
  10388. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10389. case TLSX_COOKIE:
  10390. ret = CKE_GET_SIZE((Cookie*)extension->data, msgType, &length);
  10391. break;
  10392. #endif
  10393. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10394. case TLSX_PRE_SHARED_KEY:
  10395. ret = PSK_GET_SIZE((PreSharedKey*)extension->data, msgType,
  10396. &length);
  10397. break;
  10398. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10399. ret = PKM_GET_SIZE((byte)extension->val, msgType, &length);
  10400. break;
  10401. #endif
  10402. #ifdef WOLFSSL_EARLY_DATA
  10403. case TLSX_EARLY_DATA:
  10404. ret = EDI_GET_SIZE(msgType, &length);
  10405. break;
  10406. #endif
  10407. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10408. case TLSX_POST_HANDSHAKE_AUTH:
  10409. ret = PHA_GET_SIZE(msgType, &length);
  10410. break;
  10411. #endif
  10412. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10413. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10414. length += SAC_GET_SIZE(extension->data);
  10415. break;
  10416. #endif
  10417. case TLSX_KEY_SHARE:
  10418. length += KS_GET_SIZE((KeyShareEntry*)extension->data, msgType);
  10419. break;
  10420. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10421. case TLSX_CERTIFICATE_AUTHORITIES:
  10422. length += CAN_GET_SIZE(extension->data);
  10423. break;
  10424. #endif
  10425. #endif
  10426. #ifdef WOLFSSL_SRTP
  10427. case TLSX_USE_SRTP:
  10428. length += SRTP_GET_SIZE((TlsxSrtp*)extension->data);
  10429. break;
  10430. #endif
  10431. #ifdef HAVE_RPK
  10432. case TLSX_CLIENT_CERTIFICATE_TYPE:
  10433. length += CCT_GET_SIZE((WOLFSSL*)extension->data, msgType);
  10434. break;
  10435. case TLSX_SERVER_CERTIFICATE_TYPE:
  10436. length += SCT_GET_SIZE((WOLFSSL*)extension->data, msgType);
  10437. break;
  10438. #endif /* HAVE_RPK */
  10439. #ifdef WOLFSSL_QUIC
  10440. case TLSX_KEY_QUIC_TP_PARAMS:
  10441. FALL_THROUGH; /* followed by */
  10442. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10443. length += QTP_GET_SIZE(extension);
  10444. break;
  10445. #endif
  10446. #ifdef WOLFSSL_DTLS_CID
  10447. case TLSX_CONNECTION_ID:
  10448. length += CID_GET_SIZE((byte*)extension->data);
  10449. break;
  10450. #endif /* WOLFSSL_DTLS_CID */
  10451. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10452. case TLSX_ECH:
  10453. length += ECH_GET_SIZE((WOLFSSL_ECH*)extension->data);
  10454. break;
  10455. #endif
  10456. default:
  10457. break;
  10458. }
  10459. /* marks the extension as processed so ctx level */
  10460. /* extensions don't overlap with ssl level ones. */
  10461. TURN_ON(semaphore, TLSX_ToSemaphore(extension->type));
  10462. }
  10463. *pLength += length;
  10464. return ret;
  10465. }
  10466. /** Writes the extensions of a list in a buffer. */
  10467. static int TLSX_Write(TLSX* list, byte* output, byte* semaphore,
  10468. byte msgType, word16* pOffset)
  10469. {
  10470. int ret = 0;
  10471. TLSX* extension;
  10472. word16 offset = 0;
  10473. word16 length_offset = 0;
  10474. byte isRequest = (msgType == client_hello ||
  10475. msgType == certificate_request);
  10476. while ((extension = list)) {
  10477. list = extension->next;
  10478. /* only extensions marked as response are written in a response. */
  10479. if (!isRequest && !extension->resp)
  10480. continue; /* skip! */
  10481. /* ssl level extensions are expected to override ctx level ones. */
  10482. if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type)))
  10483. continue; /* skip! */
  10484. /* writes extension type. */
  10485. c16toa(extension->type, output + offset);
  10486. offset += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN;
  10487. length_offset = offset;
  10488. /* extension data should be written internally. */
  10489. switch (extension->type) {
  10490. #ifdef HAVE_SNI
  10491. case TLSX_SERVER_NAME:
  10492. if (isRequest) {
  10493. WOLFSSL_MSG("SNI extension to write");
  10494. offset += SNI_WRITE((SNI*)extension->data, output + offset);
  10495. }
  10496. break;
  10497. #endif
  10498. case TLSX_TRUSTED_CA_KEYS:
  10499. WOLFSSL_MSG("Trusted CA Indication extension to write");
  10500. if (isRequest) {
  10501. offset += TCA_WRITE((TCA*)extension->data, output + offset);
  10502. }
  10503. break;
  10504. case TLSX_MAX_FRAGMENT_LENGTH:
  10505. WOLFSSL_MSG("Max Fragment Length extension to write");
  10506. offset += MFL_WRITE((byte*)extension->data, output + offset);
  10507. break;
  10508. case TLSX_EXTENDED_MASTER_SECRET:
  10509. WOLFSSL_MSG("Extended Master Secret");
  10510. /* always empty. */
  10511. break;
  10512. case TLSX_TRUNCATED_HMAC:
  10513. WOLFSSL_MSG("Truncated HMAC extension to write");
  10514. /* always empty. */
  10515. break;
  10516. case TLSX_SUPPORTED_GROUPS:
  10517. WOLFSSL_MSG("Supported Groups extension to write");
  10518. offset += EC_WRITE((SupportedCurve*)extension->data,
  10519. output + offset);
  10520. break;
  10521. case TLSX_EC_POINT_FORMATS:
  10522. WOLFSSL_MSG("Point Formats extension to write");
  10523. offset += PF_WRITE((PointFormat*)extension->data,
  10524. output + offset);
  10525. break;
  10526. case TLSX_STATUS_REQUEST:
  10527. WOLFSSL_MSG("Certificate Status Request extension to write");
  10528. offset += CSR_WRITE((CertificateStatusRequest*)extension->data,
  10529. output + offset, isRequest);
  10530. break;
  10531. case TLSX_STATUS_REQUEST_V2:
  10532. WOLFSSL_MSG("Certificate Status Request v2 extension to write");
  10533. offset += CSR2_WRITE(
  10534. (CertificateStatusRequestItemV2*)extension->data,
  10535. output + offset, isRequest);
  10536. break;
  10537. case TLSX_RENEGOTIATION_INFO:
  10538. WOLFSSL_MSG("Secure Renegotiation extension to write");
  10539. offset += SCR_WRITE((SecureRenegotiation*)extension->data,
  10540. output + offset, isRequest);
  10541. break;
  10542. case TLSX_SESSION_TICKET:
  10543. WOLFSSL_MSG("Session Ticket extension to write");
  10544. offset += WOLF_STK_WRITE((SessionTicket*)extension->data,
  10545. output + offset, isRequest);
  10546. break;
  10547. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10548. WOLFSSL_MSG("ALPN extension to write");
  10549. offset += ALPN_WRITE((ALPN*)extension->data, output + offset);
  10550. break;
  10551. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10552. case TLSX_SIGNATURE_ALGORITHMS:
  10553. WOLFSSL_MSG("Signature Algorithms extension to write");
  10554. offset += SA_WRITE(extension->data, output + offset);
  10555. break;
  10556. #endif
  10557. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10558. case TLSX_ENCRYPT_THEN_MAC:
  10559. WOLFSSL_MSG("Encrypt-Then-Mac extension to write");
  10560. ret = ETM_WRITE(extension->data, output, msgType, &offset);
  10561. break;
  10562. #endif /* HAVE_ENCRYPT_THEN_MAC */
  10563. #ifdef WOLFSSL_TLS13
  10564. case TLSX_SUPPORTED_VERSIONS:
  10565. WOLFSSL_MSG("Supported Versions extension to write");
  10566. ret = SV_WRITE(extension->data, output + offset, msgType, &offset);
  10567. break;
  10568. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10569. case TLSX_COOKIE:
  10570. WOLFSSL_MSG("Cookie extension to write");
  10571. ret = CKE_WRITE((Cookie*)extension->data, output + offset,
  10572. msgType, &offset);
  10573. break;
  10574. #endif
  10575. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10576. case TLSX_PRE_SHARED_KEY:
  10577. WOLFSSL_MSG("Pre-Shared Key extension to write");
  10578. ret = PSK_WRITE((PreSharedKey*)extension->data, output + offset,
  10579. msgType, &offset);
  10580. break;
  10581. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10582. WOLFSSL_MSG("PSK Key Exchange Modes extension to write");
  10583. ret = PKM_WRITE((byte)extension->val, output + offset, msgType,
  10584. &offset);
  10585. break;
  10586. #endif
  10587. #ifdef WOLFSSL_EARLY_DATA
  10588. case TLSX_EARLY_DATA:
  10589. WOLFSSL_MSG("Early Data extension to write");
  10590. ret = EDI_WRITE(extension->val, output + offset, msgType,
  10591. &offset);
  10592. break;
  10593. #endif
  10594. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10595. case TLSX_POST_HANDSHAKE_AUTH:
  10596. WOLFSSL_MSG("Post-Handshake Authentication extension to write");
  10597. ret = PHA_WRITE(output + offset, msgType, &offset);
  10598. break;
  10599. #endif
  10600. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10601. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10602. WOLFSSL_MSG("Signature Algorithms extension to write");
  10603. offset += SAC_WRITE(extension->data, output + offset);
  10604. break;
  10605. #endif
  10606. case TLSX_KEY_SHARE:
  10607. WOLFSSL_MSG("Key Share extension to write");
  10608. offset += KS_WRITE((KeyShareEntry*)extension->data,
  10609. output + offset, msgType);
  10610. break;
  10611. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10612. case TLSX_CERTIFICATE_AUTHORITIES:
  10613. WOLFSSL_MSG("Certificate Authorities extension to write");
  10614. offset += CAN_WRITE(extension->data, output + offset);
  10615. break;
  10616. #endif
  10617. #endif
  10618. #ifdef WOLFSSL_SRTP
  10619. case TLSX_USE_SRTP:
  10620. offset += SRTP_WRITE((TlsxSrtp*)extension->data, output+offset);
  10621. break;
  10622. #endif
  10623. #ifdef HAVE_RPK
  10624. case TLSX_CLIENT_CERTIFICATE_TYPE:
  10625. WOLFSSL_MSG("Client Certificate Type extension to write");
  10626. offset += CCT_WRITE(extension->data, output + offset, msgType);
  10627. break;
  10628. case TLSX_SERVER_CERTIFICATE_TYPE:
  10629. WOLFSSL_MSG("Server Certificate Type extension to write");
  10630. offset += SCT_WRITE(extension->data, output + offset, msgType);
  10631. break;
  10632. #endif /* HAVE_RPK */
  10633. #ifdef WOLFSSL_QUIC
  10634. case TLSX_KEY_QUIC_TP_PARAMS:
  10635. FALL_THROUGH;
  10636. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10637. WOLFSSL_MSG("QUIC transport parameter to write");
  10638. offset += QTP_WRITE((QuicTransportParam*)extension->data,
  10639. output + offset);
  10640. break;
  10641. #endif
  10642. #ifdef WOLFSSL_DTLS_CID
  10643. case TLSX_CONNECTION_ID:
  10644. offset += CID_WRITE((byte*)extension->data, output+offset);
  10645. break;
  10646. #endif /* WOLFSSL_DTLS_CID */
  10647. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10648. case TLSX_ECH:
  10649. ret = ECH_WRITE((WOLFSSL_ECH*)extension->data,
  10650. output + offset, &offset);
  10651. break;
  10652. #endif
  10653. default:
  10654. break;
  10655. }
  10656. /* writes extension data length. */
  10657. c16toa(offset - length_offset, output + length_offset - OPAQUE16_LEN);
  10658. /* marks the extension as processed so ctx level */
  10659. /* extensions don't overlap with ssl level ones. */
  10660. TURN_ON(semaphore, TLSX_ToSemaphore(extension->type));
  10661. /* if we encountered an error propagate it */
  10662. if (ret != 0)
  10663. break;
  10664. }
  10665. *pOffset += offset;
  10666. return ret;
  10667. }
  10668. #ifdef HAVE_SUPPORTED_CURVES
  10669. /* Populates the default supported groups / curves */
  10670. static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions)
  10671. {
  10672. int ret = WOLFSSL_SUCCESS;
  10673. #ifdef WOLFSSL_TLS13
  10674. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10675. if (ssl->options.resuming && ssl->session->namedGroup != 0) {
  10676. return TLSX_UseSupportedCurve(extensions, ssl->session->namedGroup,
  10677. ssl->heap);
  10678. }
  10679. #endif
  10680. if (ssl->numGroups != 0) {
  10681. int i;
  10682. for (i = 0; i < ssl->numGroups; i++) {
  10683. ret = TLSX_UseSupportedCurve(extensions, ssl->group[i], ssl->heap);
  10684. if (ret != WOLFSSL_SUCCESS)
  10685. return ret;
  10686. }
  10687. return WOLFSSL_SUCCESS;
  10688. }
  10689. #endif /* WOLFSSL_TLS13 */
  10690. #if defined(HAVE_ECC)
  10691. /* list in order by strength, since not all servers choose by strength */
  10692. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  10693. #ifndef NO_ECC_SECP
  10694. ret = TLSX_UseSupportedCurve(extensions,
  10695. WOLFSSL_ECC_SECP521R1, ssl->heap);
  10696. if (ret != WOLFSSL_SUCCESS) return ret;
  10697. #endif
  10698. #endif
  10699. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  10700. #ifdef HAVE_ECC_BRAINPOOL
  10701. ret = TLSX_UseSupportedCurve(extensions,
  10702. WOLFSSL_ECC_BRAINPOOLP512R1, ssl->heap);
  10703. if (ret != WOLFSSL_SUCCESS) return ret;
  10704. #endif
  10705. #endif
  10706. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  10707. #ifndef NO_ECC_SECP
  10708. ret = TLSX_UseSupportedCurve(extensions,
  10709. WOLFSSL_ECC_SECP384R1, ssl->heap);
  10710. if (ret != WOLFSSL_SUCCESS) return ret;
  10711. #endif
  10712. #ifdef HAVE_ECC_BRAINPOOL
  10713. ret = TLSX_UseSupportedCurve(extensions,
  10714. WOLFSSL_ECC_BRAINPOOLP384R1, ssl->heap);
  10715. if (ret != WOLFSSL_SUCCESS) return ret;
  10716. #endif
  10717. #endif
  10718. #endif /* HAVE_ECC */
  10719. #ifndef HAVE_FIPS
  10720. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  10721. ret = TLSX_UseSupportedCurve(extensions,
  10722. WOLFSSL_ECC_X448, ssl->heap);
  10723. if (ret != WOLFSSL_SUCCESS) return ret;
  10724. #endif
  10725. #endif /* HAVE_FIPS */
  10726. #if defined(HAVE_ECC) && defined(HAVE_SUPPORTED_CURVES)
  10727. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  10728. #ifndef NO_ECC_SECP
  10729. ret = TLSX_UseSupportedCurve(extensions,
  10730. WOLFSSL_ECC_SECP256R1, ssl->heap);
  10731. if (ret != WOLFSSL_SUCCESS) return ret;
  10732. #endif
  10733. #ifdef HAVE_ECC_KOBLITZ
  10734. ret = TLSX_UseSupportedCurve(extensions,
  10735. WOLFSSL_ECC_SECP256K1, ssl->heap);
  10736. if (ret != WOLFSSL_SUCCESS) return ret;
  10737. #endif
  10738. #ifdef HAVE_ECC_BRAINPOOL
  10739. ret = TLSX_UseSupportedCurve(extensions,
  10740. WOLFSSL_ECC_BRAINPOOLP256R1, ssl->heap);
  10741. if (ret != WOLFSSL_SUCCESS) return ret;
  10742. #endif
  10743. #ifdef WOLFSSL_SM2
  10744. ret = TLSX_UseSupportedCurve(extensions,
  10745. WOLFSSL_ECC_SM2P256V1, ssl->heap);
  10746. if (ret != WOLFSSL_SUCCESS) return ret;
  10747. #endif
  10748. #endif
  10749. #endif /* HAVE_ECC */
  10750. #ifndef HAVE_FIPS
  10751. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  10752. ret = TLSX_UseSupportedCurve(extensions,
  10753. WOLFSSL_ECC_X25519, ssl->heap);
  10754. if (ret != WOLFSSL_SUCCESS) return ret;
  10755. #endif
  10756. #endif /* HAVE_FIPS */
  10757. #if defined(HAVE_ECC) && defined(HAVE_SUPPORTED_CURVES)
  10758. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  10759. #ifndef NO_ECC_SECP
  10760. ret = TLSX_UseSupportedCurve(extensions,
  10761. WOLFSSL_ECC_SECP224R1, ssl->heap);
  10762. if (ret != WOLFSSL_SUCCESS) return ret;
  10763. #endif
  10764. #ifdef HAVE_ECC_KOBLITZ
  10765. ret = TLSX_UseSupportedCurve(extensions,
  10766. WOLFSSL_ECC_SECP224K1, ssl->heap);
  10767. if (ret != WOLFSSL_SUCCESS) return ret;
  10768. #endif
  10769. #endif
  10770. #ifndef HAVE_FIPS
  10771. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  10772. #ifndef NO_ECC_SECP
  10773. ret = TLSX_UseSupportedCurve(extensions,
  10774. WOLFSSL_ECC_SECP192R1, ssl->heap);
  10775. if (ret != WOLFSSL_SUCCESS) return ret;
  10776. #endif
  10777. #ifdef HAVE_ECC_KOBLITZ
  10778. ret = TLSX_UseSupportedCurve(extensions,
  10779. WOLFSSL_ECC_SECP192K1, ssl->heap);
  10780. if (ret != WOLFSSL_SUCCESS) return ret;
  10781. #endif
  10782. #endif
  10783. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  10784. #ifndef NO_ECC_SECP
  10785. ret = TLSX_UseSupportedCurve(extensions,
  10786. WOLFSSL_ECC_SECP160R1, ssl->heap);
  10787. if (ret != WOLFSSL_SUCCESS) return ret;
  10788. #endif
  10789. #ifdef HAVE_ECC_SECPR2
  10790. ret = TLSX_UseSupportedCurve(extensions,
  10791. WOLFSSL_ECC_SECP160R2, ssl->heap);
  10792. if (ret != WOLFSSL_SUCCESS) return ret;
  10793. #endif
  10794. #ifdef HAVE_ECC_KOBLITZ
  10795. ret = TLSX_UseSupportedCurve(extensions,
  10796. WOLFSSL_ECC_SECP160K1, ssl->heap);
  10797. if (ret != WOLFSSL_SUCCESS) return ret;
  10798. #endif
  10799. #endif
  10800. #endif /* HAVE_FIPS */
  10801. #endif /* HAVE_ECC */
  10802. #ifndef NO_DH
  10803. /* Add FFDHE supported groups. */
  10804. #ifdef HAVE_FFDHE_8192
  10805. if (8192/8 >= ssl->options.minDhKeySz &&
  10806. 8192/8 <= ssl->options.maxDhKeySz) {
  10807. ret = TLSX_UseSupportedCurve(extensions,
  10808. WOLFSSL_FFDHE_8192, ssl->heap);
  10809. if (ret != WOLFSSL_SUCCESS)
  10810. return ret;
  10811. }
  10812. #endif
  10813. #ifdef HAVE_FFDHE_6144
  10814. if (6144/8 >= ssl->options.minDhKeySz &&
  10815. 6144/8 <= ssl->options.maxDhKeySz) {
  10816. ret = TLSX_UseSupportedCurve(extensions,
  10817. WOLFSSL_FFDHE_6144, ssl->heap);
  10818. if (ret != WOLFSSL_SUCCESS)
  10819. return ret;
  10820. }
  10821. #endif
  10822. #ifdef HAVE_FFDHE_4096
  10823. if (4096/8 >= ssl->options.minDhKeySz &&
  10824. 4096/8 <= ssl->options.maxDhKeySz) {
  10825. ret = TLSX_UseSupportedCurve(extensions,
  10826. WOLFSSL_FFDHE_4096, ssl->heap);
  10827. if (ret != WOLFSSL_SUCCESS)
  10828. return ret;
  10829. }
  10830. #endif
  10831. #ifdef HAVE_FFDHE_3072
  10832. if (3072/8 >= ssl->options.minDhKeySz &&
  10833. 3072/8 <= ssl->options.maxDhKeySz) {
  10834. ret = TLSX_UseSupportedCurve(extensions,
  10835. WOLFSSL_FFDHE_3072, ssl->heap);
  10836. if (ret != WOLFSSL_SUCCESS)
  10837. return ret;
  10838. }
  10839. #endif
  10840. #ifdef HAVE_FFDHE_2048
  10841. if (2048/8 >= ssl->options.minDhKeySz &&
  10842. 2048/8 <= ssl->options.maxDhKeySz) {
  10843. ret = TLSX_UseSupportedCurve(extensions,
  10844. WOLFSSL_FFDHE_2048, ssl->heap);
  10845. if (ret != WOLFSSL_SUCCESS)
  10846. return ret;
  10847. }
  10848. #endif
  10849. #endif
  10850. #ifdef HAVE_PQC
  10851. #ifdef WOLFSSL_WC_KYBER
  10852. #ifdef WOLFSSL_KYBER512
  10853. if (ret == WOLFSSL_SUCCESS)
  10854. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1,
  10855. ssl->heap);
  10856. #endif
  10857. #ifdef WOLFSSL_KYBER768
  10858. if (ret == WOLFSSL_SUCCESS)
  10859. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3,
  10860. ssl->heap);
  10861. #endif
  10862. #ifdef WOLFSSL_KYBER768
  10863. if (ret == WOLFSSL_SUCCESS)
  10864. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5,
  10865. ssl->heap);
  10866. #endif
  10867. #elif defined(HAVE_LIBOQS)
  10868. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap);
  10869. if (ret == WOLFSSL_SUCCESS)
  10870. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3,
  10871. ssl->heap);
  10872. if (ret == WOLFSSL_SUCCESS)
  10873. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5,
  10874. ssl->heap);
  10875. if (ret == WOLFSSL_SUCCESS)
  10876. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_KYBER_LEVEL1,
  10877. ssl->heap);
  10878. if (ret == WOLFSSL_SUCCESS)
  10879. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_KYBER_LEVEL3,
  10880. ssl->heap);
  10881. if (ret == WOLFSSL_SUCCESS)
  10882. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_KYBER_LEVEL5,
  10883. ssl->heap);
  10884. #elif defined(HAVE_PQM4)
  10885. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap);
  10886. #endif /* HAVE_LIBOQS */
  10887. #endif /* HAVE_PQC */
  10888. (void)ssl;
  10889. (void)extensions;
  10890. return ret;
  10891. }
  10892. #endif /* HAVE_SUPPORTED_CURVES */
  10893. int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer)
  10894. {
  10895. int ret = 0;
  10896. byte* public_key = NULL;
  10897. word16 public_key_len = 0;
  10898. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  10899. int usingPSK = 0;
  10900. #endif
  10901. #if defined(HAVE_SUPPORTED_CURVES) && defined(WOLFSSL_TLS13)
  10902. TLSX* extension = NULL;
  10903. word16 namedGroup = WOLFSSL_NAMED_GROUP_INVALID;
  10904. #endif
  10905. /* server will add extension depending on what is parsed from client */
  10906. if (!isServer) {
  10907. #if defined(HAVE_RPK)
  10908. ret = TLSX_ClientCertificateType_Use(ssl, isServer);
  10909. if (ret != 0)
  10910. return ret;
  10911. ret = TLSX_ServerCertificateType_Use(ssl, isServer);
  10912. if (ret != 0)
  10913. return ret;
  10914. #endif /* HAVE_RPK */
  10915. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10916. if (!ssl->options.disallowEncThenMac) {
  10917. ret = TLSX_EncryptThenMac_Use(ssl);
  10918. if (ret != 0)
  10919. return ret;
  10920. }
  10921. #endif
  10922. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  10923. defined(HAVE_CURVE448)) && defined(HAVE_SUPPORTED_CURVES)
  10924. if (!ssl->options.userCurves && !ssl->ctx->userCurves) {
  10925. if (TLSX_Find(ssl->ctx->extensions,
  10926. TLSX_SUPPORTED_GROUPS) == NULL) {
  10927. ret = TLSX_PopulateSupportedGroups(ssl, &ssl->extensions);
  10928. if (ret != WOLFSSL_SUCCESS)
  10929. return ret;
  10930. }
  10931. }
  10932. if ((!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade) &&
  10933. TLSX_Find(ssl->ctx->extensions, TLSX_EC_POINT_FORMATS) == NULL &&
  10934. TLSX_Find(ssl->extensions, TLSX_EC_POINT_FORMATS) == NULL) {
  10935. ret = TLSX_UsePointFormat(&ssl->extensions,
  10936. WOLFSSL_EC_PF_UNCOMPRESSED, ssl->heap);
  10937. if (ret != WOLFSSL_SUCCESS)
  10938. return ret;
  10939. }
  10940. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && HAVE_SUPPORTED_CURVES */
  10941. #ifdef WOLFSSL_SRTP
  10942. if (ssl->options.dtls && ssl->dtlsSrtpProfiles != 0) {
  10943. WOLFSSL_MSG("Adding DTLS SRTP extension");
  10944. if ((ret = TLSX_UseSRTP(&ssl->extensions, ssl->dtlsSrtpProfiles,
  10945. ssl->heap)) != 0) {
  10946. return ret;
  10947. }
  10948. }
  10949. #endif
  10950. } /* is not server */
  10951. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10952. WOLFSSL_MSG("Adding signature algorithms extension");
  10953. if ((ret = TLSX_SetSignatureAlgorithms(&ssl->extensions, ssl, ssl->heap))
  10954. != 0) {
  10955. return ret;
  10956. }
  10957. #else
  10958. ret = 0;
  10959. #endif
  10960. #ifdef WOLFSSL_TLS13
  10961. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10962. if (isServer && IsAtLeastTLSv1_3(ssl->version)) {
  10963. if (SSL_CA_NAMES(ssl) != NULL) {
  10964. WOLFSSL_MSG("Adding certificate authorities extension");
  10965. if ((ret = TLSX_Push(&ssl->extensions,
  10966. TLSX_CERTIFICATE_AUTHORITIES, ssl, ssl->heap)) != 0) {
  10967. return ret;
  10968. }
  10969. }
  10970. }
  10971. #endif
  10972. if (!isServer && IsAtLeastTLSv1_3(ssl->version)) {
  10973. /* Add mandatory TLS v1.3 extension: supported version */
  10974. WOLFSSL_MSG("Adding supported versions extension");
  10975. if ((ret = TLSX_SetSupportedVersions(&ssl->extensions, ssl,
  10976. ssl->heap)) != 0) {
  10977. return ret;
  10978. }
  10979. #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && \
  10980. !defined(HAVE_CURVE448) && defined(HAVE_SUPPORTED_CURVES)
  10981. if (TLSX_Find(ssl->ctx->extensions, TLSX_SUPPORTED_GROUPS) == NULL) {
  10982. /* Put in DH groups for TLS 1.3 only. */
  10983. ret = TLSX_PopulateSupportedGroups(ssl, &ssl->extensions);
  10984. if (ret != WOLFSSL_SUCCESS)
  10985. return ret;
  10986. /* ret value will be overwritten in !NO_PSK case */
  10987. #ifdef NO_PSK
  10988. ret = 0;
  10989. #endif
  10990. }
  10991. #endif /* !(HAVE_ECC || CURVE25519 || CURVE448) && HAVE_SUPPORTED_CURVES */
  10992. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10993. if (ssl->certHashSigAlgoSz > 0) {
  10994. WOLFSSL_MSG("Adding signature algorithms cert extension");
  10995. if ((ret = TLSX_SetSignatureAlgorithmsCert(&ssl->extensions,
  10996. ssl, ssl->heap)) != 0) {
  10997. return ret;
  10998. }
  10999. }
  11000. #endif
  11001. #if defined(HAVE_SUPPORTED_CURVES)
  11002. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  11003. if (extension == NULL) {
  11004. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11005. if (ssl->options.resuming && ssl->session->namedGroup != 0)
  11006. namedGroup = ssl->session->namedGroup;
  11007. else
  11008. #endif
  11009. if (ssl->numGroups > 0) {
  11010. int set = 0;
  11011. int i, j;
  11012. /* try to find the highest element in ssl->group[]
  11013. * that is contained in preferredGroup[].
  11014. */
  11015. namedGroup = preferredGroup[0];
  11016. for (i = 0; i < ssl->numGroups && !set; i++) {
  11017. for (j = 0; preferredGroup[j] != WOLFSSL_NAMED_GROUP_INVALID; j++) {
  11018. if (preferredGroup[j] == ssl->group[i]
  11019. #ifdef HAVE_LIBOQS
  11020. && TLSX_KeyShare_IsSupported(preferredGroup[j])
  11021. #endif
  11022. ) {
  11023. namedGroup = ssl->group[i];
  11024. set = 1;
  11025. break;
  11026. }
  11027. }
  11028. }
  11029. if (!set)
  11030. namedGroup = WOLFSSL_NAMED_GROUP_INVALID;
  11031. }
  11032. else {
  11033. /* Choose the most preferred group. */
  11034. namedGroup = preferredGroup[0];
  11035. #ifdef HAVE_LIBOQS
  11036. if (!TLSX_KeyShare_IsSupported(namedGroup)) {
  11037. int i = 1;
  11038. for (;preferredGroup[i] != WOLFSSL_NAMED_GROUP_INVALID;
  11039. i++) {
  11040. if (TLSX_KeyShare_IsSupported(preferredGroup[i]))
  11041. break;
  11042. }
  11043. namedGroup = preferredGroup[i];
  11044. }
  11045. #endif
  11046. }
  11047. }
  11048. else {
  11049. KeyShareEntry* kse = (KeyShareEntry*)extension->data;
  11050. if (kse)
  11051. namedGroup = kse->group;
  11052. }
  11053. if (namedGroup != WOLFSSL_NAMED_GROUP_INVALID) {
  11054. #ifdef HAVE_PQC
  11055. /* For KEMs, the key share has already been generated, but not
  11056. * if we are resuming. */
  11057. if (!WOLFSSL_NAMED_GROUP_IS_PQC(namedGroup)
  11058. #ifdef HAVE_SESSION_TICKET
  11059. || ssl->options.resuming
  11060. #endif /* HAVE_SESSION_TICKET */
  11061. )
  11062. #endif /* HAVE_PQC */
  11063. {
  11064. ret = TLSX_KeyShare_Use(ssl, namedGroup, 0, NULL, NULL,
  11065. &ssl->extensions);
  11066. }
  11067. if (ret != 0)
  11068. return ret;
  11069. }
  11070. #endif /* HAVE_SUPPORTED_CURVES */
  11071. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11072. TLSX_Remove(&ssl->extensions, TLSX_PRE_SHARED_KEY, ssl->heap);
  11073. #endif
  11074. #if defined(HAVE_SESSION_TICKET)
  11075. if (ssl->options.resuming && ssl->session->ticketLen > 0) {
  11076. WOLFSSL_SESSION* sess = ssl->session;
  11077. #ifdef WOLFSSL_32BIT_MILLI_TIME
  11078. word32 now, milli;
  11079. #else
  11080. word64 now, milli;
  11081. #endif
  11082. if (sess->ticketLen > MAX_PSK_ID_LEN) {
  11083. WOLFSSL_MSG("Session ticket length for PSK ext is too large");
  11084. return BUFFER_ERROR;
  11085. }
  11086. /* Determine the MAC algorithm for the cipher suite used. */
  11087. ssl->options.cipherSuite0 = sess->cipherSuite0;
  11088. ssl->options.cipherSuite = sess->cipherSuite;
  11089. ret = SetCipherSpecs(ssl);
  11090. if (ret != 0)
  11091. return ret;
  11092. now = TimeNowInMilliseconds();
  11093. if (now == 0)
  11094. return GETTIME_ERROR;
  11095. #ifdef WOLFSSL_32BIT_MILLI_TIME
  11096. if (now < sess->ticketSeen)
  11097. milli = (0xFFFFFFFFU - sess->ticketSeen) + 1 + now;
  11098. else
  11099. milli = now - sess->ticketSeen;
  11100. milli += sess->ticketAdd;
  11101. /* Pre-shared key is mandatory extension for resumption. */
  11102. ret = TLSX_PreSharedKey_Use(&ssl->extensions, sess->ticket,
  11103. sess->ticketLen, milli, ssl->specs.mac_algorithm,
  11104. ssl->options.cipherSuite0, ssl->options.cipherSuite, 1,
  11105. NULL, ssl->heap);
  11106. #else
  11107. milli = now - sess->ticketSeen + sess->ticketAdd;
  11108. /* Pre-shared key is mandatory extension for resumption. */
  11109. ret = TLSX_PreSharedKey_Use(&ssl->extensions, sess->ticket,
  11110. sess->ticketLen, (word32)milli, ssl->specs.mac_algorithm,
  11111. ssl->options.cipherSuite0, ssl->options.cipherSuite, 1,
  11112. NULL, ssl->heap);
  11113. #endif
  11114. if (ret != 0)
  11115. return ret;
  11116. usingPSK = 1;
  11117. }
  11118. #endif
  11119. #ifndef NO_PSK
  11120. #ifndef WOLFSSL_PSK_ONE_ID
  11121. if (ssl->options.client_psk_cs_cb != NULL) {
  11122. int i;
  11123. const Suites* suites = WOLFSSL_SUITES(ssl);
  11124. for (i = 0; i < suites->suiteSz; i += 2) {
  11125. byte cipherSuite0 = suites->suites[i + 0];
  11126. byte cipherSuite = suites->suites[i + 1];
  11127. unsigned int keySz;
  11128. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11129. int cnt = 0;
  11130. #endif
  11131. #ifdef HAVE_NULL_CIPHER
  11132. if (cipherSuite0 == ECC_BYTE ||
  11133. cipherSuite0 == ECDHE_PSK_BYTE) {
  11134. if (cipherSuite != TLS_SHA256_SHA256 &&
  11135. cipherSuite != TLS_SHA384_SHA384) {
  11136. continue;
  11137. }
  11138. }
  11139. else
  11140. #endif
  11141. #if (defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)) && \
  11142. defined(WOLFSSL_SM3)
  11143. if (cipherSuite0 == CIPHER_BYTE) {
  11144. if ((cipherSuite != TLS_SM4_GCM_SM3) &&
  11145. (cipherSuite != TLS_SM4_CCM_SM3)) {
  11146. continue;
  11147. }
  11148. }
  11149. else
  11150. #endif
  11151. if (cipherSuite0 != TLS13_BYTE)
  11152. continue;
  11153. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11154. do {
  11155. ssl->arrays->client_identity[0] = cnt;
  11156. #endif
  11157. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  11158. keySz = ssl->options.client_psk_cs_cb(
  11159. ssl, ssl->arrays->server_hint,
  11160. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  11161. ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
  11162. GetCipherNameInternal(cipherSuite0, cipherSuite));
  11163. if (keySz > 0) {
  11164. ssl->arrays->psk_keySz = keySz;
  11165. ret = TLSX_PreSharedKey_Use(&ssl->extensions,
  11166. (byte*)ssl->arrays->client_identity,
  11167. (word16)XSTRLEN(ssl->arrays->client_identity),
  11168. 0, SuiteMac(WOLFSSL_SUITES(ssl)->suites + i),
  11169. cipherSuite0, cipherSuite, 0, NULL, ssl->heap);
  11170. if (ret != 0)
  11171. return ret;
  11172. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11173. cnt++;
  11174. #endif
  11175. }
  11176. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11177. }
  11178. while (keySz > 0);
  11179. #endif
  11180. }
  11181. usingPSK = 1;
  11182. }
  11183. else
  11184. #endif
  11185. if (ssl->options.client_psk_cb != NULL ||
  11186. ssl->options.client_psk_tls13_cb != NULL) {
  11187. /* Default cipher suite. */
  11188. byte cipherSuite0 = TLS13_BYTE;
  11189. byte cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
  11190. int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
  11191. const char* cipherName = NULL;
  11192. if (ssl->options.client_psk_tls13_cb != NULL) {
  11193. ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(
  11194. ssl, ssl->arrays->server_hint,
  11195. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  11196. ssl->arrays->psk_key, MAX_PSK_KEY_LEN, &cipherName);
  11197. if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
  11198. &cipherSuite, &cipherSuiteFlags) != 0) {
  11199. return PSK_KEY_ERROR;
  11200. }
  11201. }
  11202. else {
  11203. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  11204. ssl->arrays->server_hint, ssl->arrays->client_identity,
  11205. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  11206. }
  11207. #if defined(OPENSSL_EXTRA)
  11208. /* OpenSSL treats 0 as a PSK key length of 0
  11209. * and meaning no PSK available.
  11210. */
  11211. if (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  11212. return PSK_KEY_ERROR;
  11213. }
  11214. if (ssl->arrays->psk_keySz > 0) {
  11215. #else
  11216. if (ssl->arrays->psk_keySz == 0 ||
  11217. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  11218. return PSK_KEY_ERROR;
  11219. }
  11220. #endif
  11221. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  11222. ssl->options.cipherSuite0 = cipherSuite0;
  11223. ssl->options.cipherSuite = cipherSuite;
  11224. (void)cipherSuiteFlags;
  11225. ret = SetCipherSpecs(ssl);
  11226. if (ret != 0)
  11227. return ret;
  11228. ret = TLSX_PreSharedKey_Use(&ssl->extensions,
  11229. (byte*)ssl->arrays->client_identity,
  11230. (word16)XSTRLEN(ssl->arrays->client_identity),
  11231. 0, ssl->specs.mac_algorithm,
  11232. cipherSuite0, cipherSuite, 0,
  11233. NULL, ssl->heap);
  11234. if (ret != 0)
  11235. return ret;
  11236. usingPSK = 1;
  11237. #if defined(OPENSSL_EXTRA)
  11238. }
  11239. #endif
  11240. }
  11241. #endif /* !NO_PSK */
  11242. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11243. /* Some servers do not generate session tickets unless
  11244. * the extension is seen in a non-resume client hello.
  11245. * We used to send it only if we were otherwise using PSK.
  11246. * Now always send it. Define NO_TLSX_PSKKEM_PLAIN_ANNOUNCE
  11247. * to revert to the old behaviour. */
  11248. #ifdef NO_TLSX_PSKKEM_PLAIN_ANNOUNCE
  11249. if (usingPSK)
  11250. #endif
  11251. {
  11252. byte modes = 0;
  11253. (void)usingPSK;
  11254. /* Pre-shared key modes: mandatory extension for resumption. */
  11255. #ifdef HAVE_SUPPORTED_CURVES
  11256. if (!ssl->options.onlyPskDheKe)
  11257. #endif
  11258. {
  11259. modes = 1 << PSK_KE;
  11260. }
  11261. #if !defined(NO_DH) || defined(HAVE_ECC) || \
  11262. defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  11263. if (!ssl->options.noPskDheKe) {
  11264. modes |= 1 << PSK_DHE_KE;
  11265. }
  11266. #endif
  11267. ret = TLSX_PskKeyModes_Use(ssl, modes);
  11268. if (ret != 0)
  11269. return ret;
  11270. }
  11271. #endif
  11272. #if defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  11273. if (!isServer && ssl->options.postHandshakeAuth) {
  11274. ret = TLSX_PostHandAuth_Use(ssl);
  11275. if (ret != 0)
  11276. return ret;
  11277. }
  11278. #endif
  11279. #if defined(HAVE_ECH)
  11280. /* GREASE ECH */
  11281. if (ssl->echConfigs == NULL) {
  11282. ret = GREASE_ECH_USE(&(ssl->extensions), ssl->heap, ssl->rng);
  11283. }
  11284. else if (ssl->echConfigs != NULL) {
  11285. ret = ECH_USE(ssl->echConfigs, &(ssl->extensions), ssl->heap,
  11286. ssl->rng);
  11287. }
  11288. #endif
  11289. }
  11290. #if defined(HAVE_ECH)
  11291. else if (IsAtLeastTLSv1_3(ssl->version)) {
  11292. if (ssl->ctx->echConfigs != NULL) {
  11293. ret = SERVER_ECH_USE(&(ssl->extensions), ssl->heap,
  11294. ssl->ctx->echConfigs);
  11295. if (ret == 0)
  11296. TLSX_SetResponse(ssl, TLSX_ECH);
  11297. }
  11298. }
  11299. #endif
  11300. #endif
  11301. (void)isServer;
  11302. (void)public_key;
  11303. (void)public_key_len;
  11304. (void)ssl;
  11305. return ret;
  11306. }
  11307. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  11308. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11309. /* because the size of ech depends on the size of other extensions we need to
  11310. * get the size with ech special and process ech last, return status */
  11311. static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType,
  11312. word16* pLength)
  11313. {
  11314. int ret = 0;
  11315. TLSX* echX = NULL;
  11316. TLSX* serverNameX = NULL;
  11317. TLSX** extensions = NULL;
  11318. #ifdef WOLFSSL_SMALL_STACK
  11319. char* tmpServerName = NULL;
  11320. #else
  11321. char tmpServerName[MAX_PUBLIC_NAME_SZ];
  11322. #endif
  11323. /* calculate the rest of the extensions length with inner ech */
  11324. if (ssl->extensions)
  11325. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  11326. if (echX == NULL && ssl->ctx && ssl->ctx->extensions)
  11327. echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH);
  11328. /* if type is outer change sni to public name */
  11329. if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) {
  11330. if (ssl->extensions) {
  11331. serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  11332. if (serverNameX != NULL)
  11333. extensions = &ssl->extensions;
  11334. }
  11335. if (serverNameX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11336. serverNameX = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  11337. extensions = &ssl->ctx->extensions;
  11338. }
  11339. /* store the inner server name */
  11340. if (serverNameX != NULL) {
  11341. char* hostName = ((SNI*)serverNameX->data)->data.host_name;
  11342. word32 hostNameSz = (word32)XSTRLEN(hostName) + 1;
  11343. #ifdef WOLFSSL_SMALL_STACK
  11344. tmpServerName = (char*)XMALLOC(hostNameSz, ssl->heap,
  11345. DYNAMIC_TYPE_TMP_BUFFER);
  11346. if (tmpServerName == NULL)
  11347. return MEMORY_E;
  11348. #else
  11349. /* truncate if too long */
  11350. if (hostNameSz > MAX_PUBLIC_NAME_SZ)
  11351. hostNameSz = MAX_PUBLIC_NAME_SZ;
  11352. #endif
  11353. XMEMCPY(tmpServerName, hostName, hostNameSz);
  11354. }
  11355. /* remove the inner server name */
  11356. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11357. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11358. ((WOLFSSL_ECH*)echX->data)->echConfig->publicName,
  11359. XSTRLEN(((WOLFSSL_ECH*)echX->data)->echConfig->publicName),
  11360. ssl->heap);
  11361. /* set the public name as the server name */
  11362. if (ret == WOLFSSL_SUCCESS)
  11363. ret = 0;
  11364. }
  11365. if (ret == 0 && ssl->extensions)
  11366. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, pLength);
  11367. if (ret == 0 && ssl->ctx && ssl->ctx->extensions)
  11368. ret = TLSX_GetSize(ssl->ctx->extensions, semaphore, msgType, pLength);
  11369. if (serverNameX != NULL) {
  11370. /* remove the public name SNI */
  11371. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11372. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11373. tmpServerName, XSTRLEN(tmpServerName), ssl->heap);
  11374. /* restore the inner server name */
  11375. if (ret == WOLFSSL_SUCCESS)
  11376. ret = 0;
  11377. }
  11378. #ifdef WOLFSSL_SMALL_STACK
  11379. XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11380. #endif
  11381. return ret;
  11382. }
  11383. #endif
  11384. /** Tells the buffered size of extensions to be sent into the client hello. */
  11385. int TLSX_GetRequestSize(WOLFSSL* ssl, byte msgType, word16* pLength)
  11386. {
  11387. int ret = 0;
  11388. word16 length = 0;
  11389. byte semaphore[SEMAPHORE_SIZE] = {0};
  11390. if (!TLSX_SupportExtensions(ssl))
  11391. return 0;
  11392. if (msgType == client_hello) {
  11393. EC_VALIDATE_REQUEST(ssl, semaphore);
  11394. PF_VALIDATE_REQUEST(ssl, semaphore);
  11395. WOLF_STK_VALIDATE_REQUEST(ssl);
  11396. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11397. if (WOLFSSL_SUITES(ssl)->hashSigAlgoSz == 0)
  11398. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11399. #endif
  11400. #if defined(WOLFSSL_TLS13)
  11401. if (!IsAtLeastTLSv1_2(ssl)) {
  11402. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11403. }
  11404. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11405. if (!IsAtLeastTLSv1_3(ssl->version)) {
  11406. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11407. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11408. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11409. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PSK_KEY_EXCHANGE_MODES));
  11410. #endif
  11411. #ifdef WOLFSSL_EARLY_DATA
  11412. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11413. #endif
  11414. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11415. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11416. #endif
  11417. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  11418. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_POST_HANDSHAKE_AUTH));
  11419. #endif
  11420. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11421. TURN_ON(semaphore,
  11422. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11423. #endif
  11424. }
  11425. #endif
  11426. #endif /* WOLFSSL_TLS13 */
  11427. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  11428. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  11429. if (!SSL_CM(ssl)->ocspStaplingEnabled) {
  11430. /* mark already sent, so it won't send it */
  11431. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11432. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11433. }
  11434. #endif
  11435. }
  11436. #ifdef WOLFSSL_TLS13
  11437. #ifndef NO_CERTS
  11438. else if (msgType == certificate_request) {
  11439. /* Don't send out any extension except those that are turned off. */
  11440. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11441. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11442. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11443. #endif
  11444. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11445. if (SSL_CA_NAMES(ssl) != NULL)
  11446. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11447. #endif
  11448. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, OID_FILTERS
  11449. * TLSX_STATUS_REQUEST
  11450. */
  11451. }
  11452. #endif
  11453. #if defined(HAVE_ECH)
  11454. if (ssl->options.useEch == 1 && msgType == client_hello) {
  11455. ret = TLSX_GetSizeWithEch(ssl, semaphore, msgType, &length);
  11456. if (ret != 0)
  11457. return ret;
  11458. }
  11459. else
  11460. #endif /* HAVE_ECH */
  11461. #endif /* WOLFSSL_TLS13 */
  11462. {
  11463. if (ssl->extensions) {
  11464. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, &length);
  11465. if (ret != 0)
  11466. return ret;
  11467. }
  11468. if (ssl->ctx && ssl->ctx->extensions) {
  11469. ret = TLSX_GetSize(ssl->ctx->extensions, semaphore, msgType,
  11470. &length);
  11471. if (ret != 0)
  11472. return ret;
  11473. }
  11474. }
  11475. #ifdef HAVE_EXTENDED_MASTER
  11476. if (msgType == client_hello && ssl->options.haveEMS &&
  11477. (!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade)) {
  11478. length += HELLO_EXT_SZ;
  11479. }
  11480. #endif
  11481. if (length)
  11482. length += OPAQUE16_LEN; /* for total length storage. */
  11483. *pLength += length;
  11484. return ret;
  11485. }
  11486. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11487. /* return status after writing the extensions with ech written last */
  11488. static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore,
  11489. byte msgType, word16* pOffset)
  11490. {
  11491. int ret = 0;
  11492. TLSX* echX = NULL;
  11493. TLSX* serverNameX = NULL;
  11494. TLSX** extensions = NULL;
  11495. #ifdef WOLFSSL_SMALL_STACK
  11496. char* tmpServerName = NULL;
  11497. #else
  11498. char tmpServerName[MAX_PUBLIC_NAME_SZ];
  11499. #endif
  11500. /* get the echX from either extensions or ctx */
  11501. if (ssl->extensions)
  11502. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  11503. if (echX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11504. /* if not NULL the semaphore will stop it from being counted */
  11505. if (echX == NULL)
  11506. echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH);
  11507. }
  11508. /* if type is outer change sni to public name */
  11509. if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) {
  11510. if (ssl->extensions) {
  11511. serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  11512. if (serverNameX != NULL)
  11513. extensions = &ssl->extensions;
  11514. }
  11515. if (serverNameX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11516. serverNameX = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  11517. extensions = &ssl->ctx->extensions;
  11518. }
  11519. /* store the inner server name */
  11520. if (serverNameX != NULL) {
  11521. char* hostName = ((SNI*)serverNameX->data)->data.host_name;
  11522. word32 hostNameSz = (word32)XSTRLEN(hostName) + 1;
  11523. #ifdef WOLFSSL_SMALL_STACK
  11524. tmpServerName = (char*)XMALLOC(hostNameSz, ssl->heap,
  11525. DYNAMIC_TYPE_TMP_BUFFER);
  11526. if (tmpServerName == NULL)
  11527. return MEMORY_E;
  11528. #else
  11529. /* truncate if too long */
  11530. if (hostNameSz > MAX_PUBLIC_NAME_SZ)
  11531. hostNameSz = MAX_PUBLIC_NAME_SZ;
  11532. #endif
  11533. XMEMCPY(tmpServerName, hostName, hostNameSz);
  11534. }
  11535. /* remove the inner server name */
  11536. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11537. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11538. ((WOLFSSL_ECH*)echX->data)->echConfig->publicName,
  11539. XSTRLEN(((WOLFSSL_ECH*)echX->data)->echConfig->publicName),
  11540. ssl->heap);
  11541. /* set the public name as the server name */
  11542. if (ret == WOLFSSL_SUCCESS)
  11543. ret = 0;
  11544. }
  11545. if (echX != NULL) {
  11546. /* turn ech on so it doesn't write, then write it last */
  11547. TURN_ON(semaphore, TLSX_ToSemaphore(echX->type));
  11548. }
  11549. if (ret == 0 && ssl->extensions) {
  11550. ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore,
  11551. msgType, pOffset);
  11552. }
  11553. if (ret == 0 && ssl->ctx && ssl->ctx->extensions) {
  11554. ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore,
  11555. msgType, pOffset);
  11556. }
  11557. if (echX != NULL) {
  11558. /* turn off and write it last */
  11559. TURN_OFF(semaphore, TLSX_ToSemaphore(echX->type));
  11560. }
  11561. if (ret == 0 && ssl->extensions) {
  11562. ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore,
  11563. msgType, pOffset);
  11564. }
  11565. if (ret == 0 && ssl->ctx && ssl->ctx->extensions) {
  11566. ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore,
  11567. msgType, pOffset);
  11568. }
  11569. if (serverNameX != NULL) {
  11570. /* remove the public name SNI */
  11571. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11572. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME, tmpServerName,
  11573. XSTRLEN(tmpServerName), ssl->heap);
  11574. /* restore the inner server name */
  11575. if (ret == WOLFSSL_SUCCESS)
  11576. ret = 0;
  11577. }
  11578. #ifdef WOLFSSL_SMALL_STACK
  11579. XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11580. #endif
  11581. return ret;
  11582. }
  11583. #endif
  11584. /** Writes the extensions to be sent into the client hello. */
  11585. int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word16* pOffset)
  11586. {
  11587. int ret = 0;
  11588. word16 offset = 0;
  11589. byte semaphore[SEMAPHORE_SIZE] = {0};
  11590. if (!TLSX_SupportExtensions(ssl) || output == NULL)
  11591. return 0;
  11592. offset += OPAQUE16_LEN; /* extensions length */
  11593. if (msgType == client_hello) {
  11594. EC_VALIDATE_REQUEST(ssl, semaphore);
  11595. PF_VALIDATE_REQUEST(ssl, semaphore);
  11596. WOLF_STK_VALIDATE_REQUEST(ssl);
  11597. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11598. if (WOLFSSL_SUITES(ssl)->hashSigAlgoSz == 0)
  11599. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11600. #endif
  11601. #ifdef WOLFSSL_TLS13
  11602. if (!IsAtLeastTLSv1_2(ssl)) {
  11603. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11604. }
  11605. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11606. if (!IsAtLeastTLSv1_3(ssl->version)) {
  11607. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11608. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11609. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PSK_KEY_EXCHANGE_MODES));
  11610. #endif
  11611. #ifdef WOLFSSL_EARLY_DATA
  11612. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11613. #endif
  11614. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11615. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11616. #endif
  11617. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  11618. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_POST_HANDSHAKE_AUTH));
  11619. #endif
  11620. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11621. TURN_ON(semaphore,
  11622. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11623. #endif
  11624. }
  11625. #endif
  11626. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11627. /* Must write Pre-shared Key extension at the end in TLS v1.3.
  11628. * Must not write out Pre-shared Key extension in earlier versions of
  11629. * protocol.
  11630. */
  11631. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11632. #endif
  11633. #endif /* WOLFSSL_TLS13 */
  11634. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  11635. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  11636. /* mark already sent, so it won't send it */
  11637. if (!SSL_CM(ssl)->ocspStaplingEnabled) {
  11638. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11639. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11640. }
  11641. #endif
  11642. }
  11643. #ifdef WOLFSSL_TLS13
  11644. #ifndef NO_CERTS
  11645. else if (msgType == certificate_request) {
  11646. /* Don't send out any extension except those that are turned off. */
  11647. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11648. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11649. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11650. #endif
  11651. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11652. if (SSL_CA_NAMES(ssl) != NULL) {
  11653. TURN_OFF(semaphore,
  11654. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11655. }
  11656. #endif
  11657. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, TLSX_OID_FILTERS
  11658. * TLSX_STATUS_REQUEST
  11659. */
  11660. }
  11661. #endif
  11662. #endif
  11663. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11664. if (ssl->options.useEch == 1 && msgType == client_hello) {
  11665. ret = TLSX_WriteWithEch(ssl, output, semaphore,
  11666. msgType, &offset);
  11667. if (ret != 0)
  11668. return ret;
  11669. }
  11670. else
  11671. #endif
  11672. {
  11673. if (ssl->extensions) {
  11674. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11675. msgType, &offset);
  11676. if (ret != 0)
  11677. return ret;
  11678. }
  11679. if (ssl->ctx && ssl->ctx->extensions) {
  11680. ret = TLSX_Write(ssl->ctx->extensions, output + offset, semaphore,
  11681. msgType, &offset);
  11682. if (ret != 0)
  11683. return ret;
  11684. }
  11685. }
  11686. #ifdef HAVE_EXTENDED_MASTER
  11687. if (msgType == client_hello && ssl->options.haveEMS &&
  11688. (!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade)) {
  11689. WOLFSSL_MSG("EMS extension to write");
  11690. c16toa(HELLO_EXT_EXTMS, output + offset);
  11691. offset += HELLO_EXT_TYPE_SZ;
  11692. c16toa(0, output + offset);
  11693. offset += HELLO_EXT_SZ_SZ;
  11694. }
  11695. #endif
  11696. #ifdef WOLFSSL_TLS13
  11697. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11698. if (msgType == client_hello && IsAtLeastTLSv1_3(ssl->version)) {
  11699. /* Write out what we can of Pre-shared key extension. */
  11700. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11701. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11702. client_hello, &offset);
  11703. if (ret != 0)
  11704. return ret;
  11705. }
  11706. #endif
  11707. #endif
  11708. if (offset > OPAQUE16_LEN || msgType != client_hello)
  11709. c16toa(offset - OPAQUE16_LEN, output); /* extensions length */
  11710. *pOffset += offset;
  11711. return ret;
  11712. }
  11713. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  11714. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_SERVER)
  11715. /** Tells the buffered size of extensions to be sent into the server hello. */
  11716. int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength)
  11717. {
  11718. int ret = 0;
  11719. word16 length = 0;
  11720. byte semaphore[SEMAPHORE_SIZE] = {0};
  11721. switch (msgType) {
  11722. #ifndef NO_WOLFSSL_SERVER
  11723. case server_hello:
  11724. PF_VALIDATE_RESPONSE(ssl, semaphore);
  11725. #ifdef WOLFSSL_TLS13
  11726. if (IsAtLeastTLSv1_3(ssl->version)) {
  11727. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11728. TURN_OFF(semaphore,
  11729. TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11730. #if defined(HAVE_SUPPORTED_CURVES)
  11731. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11732. if (!ssl->options.noPskDheKe)
  11733. #endif
  11734. {
  11735. /* Expect KeyShare extension in ServerHello. */
  11736. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11737. }
  11738. #endif
  11739. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11740. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11741. #endif
  11742. #ifdef WOLFSSL_DTLS_CID
  11743. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11744. #endif
  11745. }
  11746. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11747. else {
  11748. #ifdef HAVE_SUPPORTED_CURVES
  11749. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11750. #endif
  11751. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11752. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11753. #endif
  11754. }
  11755. #endif
  11756. #endif /* WOLFSSL_TLS13 */
  11757. break;
  11758. #ifdef WOLFSSL_TLS13
  11759. case hello_retry_request:
  11760. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11761. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11762. #ifdef HAVE_SUPPORTED_CURVES
  11763. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11764. if (!ssl->options.noPskDheKe)
  11765. #endif
  11766. {
  11767. /* Expect KeyShare extension in HelloRetryRequest. */
  11768. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11769. }
  11770. #endif
  11771. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11772. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11773. #endif
  11774. break;
  11775. #endif
  11776. #ifdef WOLFSSL_TLS13
  11777. case encrypted_extensions:
  11778. /* Send out all extension except those that are turned on. */
  11779. #ifdef HAVE_ECC
  11780. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  11781. #endif
  11782. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11783. #ifdef HAVE_SESSION_TICKET
  11784. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SESSION_TICKET));
  11785. #endif
  11786. #ifdef HAVE_SUPPORTED_CURVES
  11787. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11788. #endif
  11789. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11790. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11791. #endif
  11792. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  11793. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11794. #endif
  11795. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  11796. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11797. #endif
  11798. #if defined(HAVE_SERVER_RENEGOTIATION_INFO)
  11799. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_RENEGOTIATION_INFO));
  11800. #endif
  11801. #ifdef WOLFSSL_DTLS_CID
  11802. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11803. #endif /* WOLFSSL_DTLS_CID */
  11804. break;
  11805. #ifdef WOLFSSL_EARLY_DATA
  11806. case session_ticket:
  11807. if (ssl->options.tls1_3) {
  11808. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11809. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11810. }
  11811. break;
  11812. #endif
  11813. #endif
  11814. #endif
  11815. #ifdef WOLFSSL_TLS13
  11816. #ifndef NO_CERTS
  11817. case certificate:
  11818. /* Don't send out any extension except those that are turned off. */
  11819. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11820. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11821. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP,
  11822. * TLSX_SERVER_CERTIFICATE_TYPE
  11823. */
  11824. break;
  11825. #endif
  11826. #endif
  11827. }
  11828. #ifdef HAVE_EXTENDED_MASTER
  11829. if (ssl->options.haveEMS && msgType == server_hello &&
  11830. !IsAtLeastTLSv1_3(ssl->version)) {
  11831. length += HELLO_EXT_SZ;
  11832. }
  11833. #endif
  11834. if (TLSX_SupportExtensions(ssl)) {
  11835. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, &length);
  11836. if (ret != 0)
  11837. return ret;
  11838. }
  11839. /* All the response data is set at the ssl object only, so no ctx here. */
  11840. if (length || msgType != server_hello)
  11841. length += OPAQUE16_LEN; /* for total length storage. */
  11842. *pLength += length;
  11843. return ret;
  11844. }
  11845. /** Writes the server hello extensions into a buffer. */
  11846. int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset)
  11847. {
  11848. int ret = 0;
  11849. word16 offset = 0;
  11850. if (TLSX_SupportExtensions(ssl) && output) {
  11851. byte semaphore[SEMAPHORE_SIZE] = {0};
  11852. switch (msgType) {
  11853. #ifndef NO_WOLFSSL_SERVER
  11854. case server_hello:
  11855. PF_VALIDATE_RESPONSE(ssl, semaphore);
  11856. #ifdef WOLFSSL_TLS13
  11857. if (IsAtLeastTLSv1_3(ssl->version)) {
  11858. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11859. TURN_OFF(semaphore,
  11860. TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11861. #ifdef HAVE_SUPPORTED_CURVES
  11862. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11863. if (!ssl->options.noPskDheKe)
  11864. #endif
  11865. {
  11866. /* Write out KeyShare in ServerHello. */
  11867. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11868. }
  11869. #endif
  11870. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11871. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11872. #endif
  11873. #ifdef WOLFSSL_DTLS_CID
  11874. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11875. #endif /* WOLFSSL_DTLS_CID */
  11876. }
  11877. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11878. else {
  11879. #ifdef HAVE_SUPPORTED_CURVES
  11880. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11881. #endif
  11882. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11883. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11884. #endif
  11885. }
  11886. #endif
  11887. #endif
  11888. break;
  11889. #ifdef WOLFSSL_TLS13
  11890. case hello_retry_request:
  11891. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11892. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11893. #ifdef HAVE_SUPPORTED_CURVES
  11894. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11895. if (!ssl->options.noPskDheKe)
  11896. #endif
  11897. {
  11898. /* Write out KeyShare in HelloRetryRequest. */
  11899. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11900. }
  11901. #endif
  11902. /* Cookie is written below as last extension. */
  11903. break;
  11904. #endif
  11905. #ifdef WOLFSSL_TLS13
  11906. case encrypted_extensions:
  11907. /* Send out all extension except those that are turned on. */
  11908. #ifdef HAVE_ECC
  11909. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  11910. #endif
  11911. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11912. #ifdef HAVE_SESSION_TICKET
  11913. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SESSION_TICKET));
  11914. #endif
  11915. #ifdef HAVE_SUPPORTED_CURVES
  11916. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11917. #endif
  11918. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11919. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11920. #endif
  11921. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  11922. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11923. #endif
  11924. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  11925. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11926. #endif
  11927. #if defined(HAVE_SERVER_RENEGOTIATION_INFO)
  11928. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_RENEGOTIATION_INFO));
  11929. #endif
  11930. #ifdef WOLFSSL_DTLS_CID
  11931. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11932. #endif /* WOLFSSL_DTLS_CID */
  11933. break;
  11934. #ifdef WOLFSSL_EARLY_DATA
  11935. case session_ticket:
  11936. if (ssl->options.tls1_3) {
  11937. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11938. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11939. }
  11940. break;
  11941. #endif
  11942. #endif
  11943. #endif
  11944. #ifdef WOLFSSL_TLS13
  11945. #ifndef NO_CERTS
  11946. case certificate:
  11947. /* Don't send out any extension except those that are turned
  11948. * off. */
  11949. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11950. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11951. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP,
  11952. * TLSX_SERVER_CERTIFICATE_TYPE
  11953. */
  11954. break;
  11955. #endif
  11956. #endif
  11957. default:
  11958. break;
  11959. }
  11960. offset += OPAQUE16_LEN; /* extensions length */
  11961. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11962. msgType, &offset);
  11963. if (ret != 0)
  11964. return ret;
  11965. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  11966. if (msgType == hello_retry_request) {
  11967. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11968. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11969. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11970. msgType, &offset);
  11971. if (ret != 0)
  11972. return ret;
  11973. }
  11974. #endif
  11975. #ifdef HAVE_EXTENDED_MASTER
  11976. if (ssl->options.haveEMS && msgType == server_hello &&
  11977. !IsAtLeastTLSv1_3(ssl->version)) {
  11978. WOLFSSL_MSG("EMS extension to write");
  11979. c16toa(HELLO_EXT_EXTMS, output + offset);
  11980. offset += HELLO_EXT_TYPE_SZ;
  11981. c16toa(0, output + offset);
  11982. offset += HELLO_EXT_SZ_SZ;
  11983. }
  11984. #endif
  11985. if (offset > OPAQUE16_LEN || msgType != server_hello)
  11986. c16toa(offset - OPAQUE16_LEN, output); /* extensions length */
  11987. }
  11988. if (pOffset)
  11989. *pOffset += offset;
  11990. return ret;
  11991. }
  11992. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_SERVER */
  11993. #ifdef WOLFSSL_TLS13
  11994. int TLSX_ParseVersion(WOLFSSL* ssl, const byte* input, word16 length,
  11995. byte msgType, int* found)
  11996. {
  11997. int ret = 0;
  11998. int offset = 0;
  11999. *found = 0;
  12000. while (offset < (int)length) {
  12001. word16 type;
  12002. word16 size;
  12003. if (offset + (2 * OPAQUE16_LEN) > length) {
  12004. ret = BUFFER_ERROR;
  12005. break;
  12006. }
  12007. ato16(input + offset, &type);
  12008. offset += HELLO_EXT_TYPE_SZ;
  12009. ato16(input + offset, &size);
  12010. offset += OPAQUE16_LEN;
  12011. if (offset + size > length) {
  12012. ret = BUFFER_ERROR;
  12013. break;
  12014. }
  12015. if (type == TLSX_SUPPORTED_VERSIONS) {
  12016. *found = 1;
  12017. WOLFSSL_MSG("Supported Versions extension received");
  12018. ret = SV_PARSE(ssl, input + offset, size, msgType, &ssl->version,
  12019. &ssl->options, &ssl->extensions);
  12020. break;
  12021. }
  12022. offset += size;
  12023. }
  12024. return ret;
  12025. }
  12026. #endif
  12027. /** Parses a buffer of TLS extensions. */
  12028. int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType,
  12029. Suites *suites)
  12030. {
  12031. int ret = 0;
  12032. word16 offset = 0;
  12033. byte isRequest = (msgType == client_hello ||
  12034. msgType == certificate_request);
  12035. #ifdef HAVE_EXTENDED_MASTER
  12036. byte pendingEMS = 0;
  12037. #endif
  12038. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  12039. int pskDone = 0;
  12040. #endif
  12041. byte seenType[SEMAPHORE_SIZE]; /* Seen known extensions. */
  12042. if (!ssl || !input || (isRequest && !suites))
  12043. return BAD_FUNC_ARG;
  12044. /* No known extensions seen yet. */
  12045. XMEMSET(seenType, 0, sizeof(seenType));
  12046. while (ret == 0 && offset < length) {
  12047. word16 type;
  12048. word16 size;
  12049. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  12050. if (msgType == client_hello && pskDone) {
  12051. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  12052. return PSK_KEY_ERROR;
  12053. }
  12054. #endif
  12055. if (length - offset < HELLO_EXT_TYPE_SZ + OPAQUE16_LEN)
  12056. return BUFFER_ERROR;
  12057. ato16(input + offset, &type);
  12058. offset += HELLO_EXT_TYPE_SZ;
  12059. ato16(input + offset, &size);
  12060. offset += OPAQUE16_LEN;
  12061. /* Check we have a bit for extension type. */
  12062. if ((type <= 62) || (type == TLSX_RENEGOTIATION_INFO)
  12063. #ifdef WOLFSSL_QUIC
  12064. || (type == TLSX_KEY_QUIC_TP_PARAMS_DRAFT)
  12065. #endif
  12066. )
  12067. {
  12068. /* Detect duplicate recognized extensions. */
  12069. if (IS_OFF(seenType, TLSX_ToSemaphore(type))) {
  12070. TURN_ON(seenType, TLSX_ToSemaphore(type));
  12071. }
  12072. else {
  12073. return DUPLICATE_TLS_EXT_E;
  12074. }
  12075. }
  12076. if (length - offset < size)
  12077. return BUFFER_ERROR;
  12078. switch (type) {
  12079. #ifdef HAVE_SNI
  12080. case TLSX_SERVER_NAME:
  12081. WOLFSSL_MSG("SNI extension received");
  12082. #ifdef WOLFSSL_DEBUG_TLS
  12083. WOLFSSL_BUFFER(input + offset, size);
  12084. #endif
  12085. #ifdef WOLFSSL_TLS13
  12086. if (IsAtLeastTLSv1_3(ssl->version)) {
  12087. if (msgType != client_hello &&
  12088. msgType != encrypted_extensions)
  12089. return EXT_NOT_ALLOWED;
  12090. }
  12091. else
  12092. #endif
  12093. {
  12094. if (msgType != client_hello &&
  12095. msgType != server_hello)
  12096. return EXT_NOT_ALLOWED;
  12097. }
  12098. ret = SNI_PARSE(ssl, input + offset, size, isRequest);
  12099. break;
  12100. #endif
  12101. case TLSX_TRUSTED_CA_KEYS:
  12102. WOLFSSL_MSG("Trusted CA extension received");
  12103. #ifdef WOLFSSL_DEBUG_TLS
  12104. WOLFSSL_BUFFER(input + offset, size);
  12105. #endif
  12106. #ifdef WOLFSSL_TLS13
  12107. /* RFC 8446 4.2.4 states trusted_ca_keys is not used
  12108. in TLS 1.3. */
  12109. if (IsAtLeastTLSv1_3(ssl->version)) {
  12110. return EXT_NOT_ALLOWED;
  12111. }
  12112. else
  12113. #endif
  12114. {
  12115. if (msgType != client_hello &&
  12116. msgType != server_hello)
  12117. return EXT_NOT_ALLOWED;
  12118. }
  12119. ret = TCA_PARSE(ssl, input + offset, size, isRequest);
  12120. break;
  12121. case TLSX_MAX_FRAGMENT_LENGTH:
  12122. WOLFSSL_MSG("Max Fragment Length extension received");
  12123. #ifdef WOLFSSL_DEBUG_TLS
  12124. WOLFSSL_BUFFER(input + offset, size);
  12125. #endif
  12126. #ifdef WOLFSSL_TLS13
  12127. if (IsAtLeastTLSv1_3(ssl->version)) {
  12128. if (msgType != client_hello &&
  12129. msgType != encrypted_extensions) {
  12130. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12131. return EXT_NOT_ALLOWED;
  12132. }
  12133. }
  12134. else
  12135. #endif
  12136. {
  12137. if (msgType != client_hello &&
  12138. msgType != server_hello) {
  12139. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12140. return EXT_NOT_ALLOWED;
  12141. }
  12142. }
  12143. ret = MFL_PARSE(ssl, input + offset, size, isRequest);
  12144. break;
  12145. case TLSX_TRUNCATED_HMAC:
  12146. WOLFSSL_MSG("Truncated HMAC extension received");
  12147. #ifdef WOLFSSL_DEBUG_TLS
  12148. WOLFSSL_BUFFER(input + offset, size);
  12149. #endif
  12150. #ifdef WOLFSSL_TLS13
  12151. if (IsAtLeastTLSv1_3(ssl->version))
  12152. break;
  12153. #endif
  12154. if (msgType != client_hello)
  12155. return EXT_NOT_ALLOWED;
  12156. ret = THM_PARSE(ssl, input + offset, size, isRequest);
  12157. break;
  12158. case TLSX_SUPPORTED_GROUPS:
  12159. WOLFSSL_MSG("Supported Groups extension received");
  12160. #ifdef WOLFSSL_DEBUG_TLS
  12161. WOLFSSL_BUFFER(input + offset, size);
  12162. #endif
  12163. #ifdef WOLFSSL_TLS13
  12164. if (IsAtLeastTLSv1_3(ssl->version)) {
  12165. if (msgType != client_hello &&
  12166. msgType != encrypted_extensions) {
  12167. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12168. return EXT_NOT_ALLOWED;
  12169. }
  12170. }
  12171. else
  12172. #endif
  12173. {
  12174. if (msgType != client_hello) {
  12175. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12176. return EXT_NOT_ALLOWED;
  12177. }
  12178. }
  12179. ret = EC_PARSE(ssl, input + offset, size, isRequest,
  12180. &ssl->extensions);
  12181. break;
  12182. case TLSX_EC_POINT_FORMATS:
  12183. WOLFSSL_MSG("Point Formats extension received");
  12184. #ifdef WOLFSSL_DEBUG_TLS
  12185. WOLFSSL_BUFFER(input + offset, size);
  12186. #endif
  12187. #ifdef WOLFSSL_TLS13
  12188. if (IsAtLeastTLSv1_3(ssl->version))
  12189. break;
  12190. #endif
  12191. if (msgType != client_hello &&
  12192. msgType != server_hello) {
  12193. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12194. return EXT_NOT_ALLOWED;
  12195. }
  12196. ret = PF_PARSE(ssl, input + offset, size, isRequest);
  12197. break;
  12198. case TLSX_STATUS_REQUEST:
  12199. WOLFSSL_MSG("Certificate Status Request extension received");
  12200. #ifdef WOLFSSL_DEBUG_TLS
  12201. WOLFSSL_BUFFER(input + offset, size);
  12202. #endif
  12203. #ifdef WOLFSSL_TLS13
  12204. if (IsAtLeastTLSv1_3(ssl->version)) {
  12205. if (msgType != client_hello &&
  12206. msgType != certificate_request &&
  12207. msgType != certificate)
  12208. return EXT_NOT_ALLOWED;
  12209. }
  12210. else
  12211. #endif
  12212. {
  12213. if (msgType != client_hello &&
  12214. msgType != server_hello)
  12215. return EXT_NOT_ALLOWED;
  12216. }
  12217. ret = CSR_PARSE(ssl, input + offset, size, isRequest);
  12218. break;
  12219. case TLSX_STATUS_REQUEST_V2:
  12220. WOLFSSL_MSG("Certificate Status Request v2 extension received");
  12221. #ifdef WOLFSSL_DEBUG_TLS
  12222. WOLFSSL_BUFFER(input + offset, size);
  12223. #endif
  12224. #if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  12225. if (IsAtLeastTLSv1_3(ssl->version)) {
  12226. if (msgType != client_hello &&
  12227. msgType != certificate_request &&
  12228. msgType != certificate)
  12229. return EXT_NOT_ALLOWED;
  12230. }
  12231. else
  12232. #endif
  12233. {
  12234. if (msgType != client_hello &&
  12235. msgType != server_hello)
  12236. return EXT_NOT_ALLOWED;
  12237. }
  12238. ret = CSR2_PARSE(ssl, input + offset, size, isRequest);
  12239. break;
  12240. #ifdef HAVE_EXTENDED_MASTER
  12241. case HELLO_EXT_EXTMS:
  12242. WOLFSSL_MSG("Extended Master Secret extension received");
  12243. #ifdef WOLFSSL_DEBUG_TLS
  12244. WOLFSSL_BUFFER(input + offset, size);
  12245. #endif
  12246. #if defined(WOLFSSL_TLS13)
  12247. if (IsAtLeastTLSv1_3(ssl->version))
  12248. break;
  12249. #endif
  12250. if (msgType != client_hello &&
  12251. msgType != server_hello)
  12252. return EXT_NOT_ALLOWED;
  12253. if (size != 0)
  12254. return BUFFER_ERROR;
  12255. #ifndef NO_WOLFSSL_SERVER
  12256. if (isRequest)
  12257. ssl->options.haveEMS = 1;
  12258. #endif
  12259. pendingEMS = 1;
  12260. break;
  12261. #endif
  12262. case TLSX_RENEGOTIATION_INFO:
  12263. WOLFSSL_MSG("Secure Renegotiation extension received");
  12264. #ifdef WOLFSSL_DEBUG_TLS
  12265. WOLFSSL_BUFFER(input + offset, size);
  12266. #endif
  12267. #ifdef WOLFSSL_TLS13
  12268. if (IsAtLeastTLSv1_3(ssl->version))
  12269. break;
  12270. #endif
  12271. if (msgType != client_hello &&
  12272. msgType != server_hello)
  12273. return EXT_NOT_ALLOWED;
  12274. ret = SCR_PARSE(ssl, input + offset, size, isRequest);
  12275. break;
  12276. case TLSX_SESSION_TICKET:
  12277. WOLFSSL_MSG("Session Ticket extension received");
  12278. #ifdef WOLFSSL_DEBUG_TLS
  12279. WOLFSSL_BUFFER(input + offset, size);
  12280. #endif
  12281. #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)
  12282. if (IsAtLeastTLSv1_3(ssl->version)) {
  12283. if (msgType != client_hello)
  12284. return EXT_NOT_ALLOWED;
  12285. }
  12286. else
  12287. #endif
  12288. {
  12289. if (msgType != client_hello &&
  12290. msgType != server_hello)
  12291. return EXT_NOT_ALLOWED;
  12292. }
  12293. ret = WOLF_STK_PARSE(ssl, input + offset, size, isRequest);
  12294. break;
  12295. case TLSX_APPLICATION_LAYER_PROTOCOL:
  12296. WOLFSSL_MSG("ALPN extension received");
  12297. #ifdef WOLFSSL_DEBUG_TLS
  12298. WOLFSSL_BUFFER(input + offset, size);
  12299. #endif
  12300. #if defined(WOLFSSL_TLS13) && defined(HAVE_ALPN)
  12301. if (IsAtLeastTLSv1_3(ssl->version)) {
  12302. if (msgType != client_hello &&
  12303. msgType != encrypted_extensions)
  12304. return EXT_NOT_ALLOWED;
  12305. }
  12306. else
  12307. #endif
  12308. {
  12309. if (msgType != client_hello &&
  12310. msgType != server_hello)
  12311. return EXT_NOT_ALLOWED;
  12312. }
  12313. ret = ALPN_PARSE(ssl, input + offset, size, isRequest);
  12314. break;
  12315. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  12316. case TLSX_SIGNATURE_ALGORITHMS:
  12317. WOLFSSL_MSG("Signature Algorithms extension received");
  12318. #ifdef WOLFSSL_DEBUG_TLS
  12319. WOLFSSL_BUFFER(input + offset, size);
  12320. #endif
  12321. if (!IsAtLeastTLSv1_2(ssl))
  12322. break;
  12323. #ifdef WOLFSSL_TLS13
  12324. if (IsAtLeastTLSv1_3(ssl->version)) {
  12325. if (msgType != client_hello &&
  12326. msgType != certificate_request)
  12327. return EXT_NOT_ALLOWED;
  12328. }
  12329. else
  12330. #endif
  12331. {
  12332. if (msgType != client_hello)
  12333. return EXT_NOT_ALLOWED;
  12334. }
  12335. ret = SA_PARSE(ssl, input + offset, size, isRequest, suites);
  12336. break;
  12337. #endif
  12338. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  12339. case TLSX_ENCRYPT_THEN_MAC:
  12340. WOLFSSL_MSG("Encrypt-Then-Mac extension received");
  12341. /* Ignore for TLS 1.3+ */
  12342. if (IsAtLeastTLSv1_3(ssl->version))
  12343. break;
  12344. if (msgType != client_hello &&
  12345. msgType != server_hello)
  12346. return EXT_NOT_ALLOWED;
  12347. ret = ETM_PARSE(ssl, input + offset, size, msgType);
  12348. break;
  12349. #endif /* HAVE_ENCRYPT_THEN_MAC */
  12350. #ifdef WOLFSSL_TLS13
  12351. case TLSX_SUPPORTED_VERSIONS:
  12352. WOLFSSL_MSG("Skipping Supported Versions - already processed");
  12353. #ifdef WOLFSSL_DEBUG_TLS
  12354. WOLFSSL_BUFFER(input + offset, size);
  12355. #endif
  12356. if (msgType != client_hello &&
  12357. msgType != server_hello &&
  12358. msgType != hello_retry_request)
  12359. return EXT_NOT_ALLOWED;
  12360. break;
  12361. #ifdef WOLFSSL_SEND_HRR_COOKIE
  12362. case TLSX_COOKIE:
  12363. WOLFSSL_MSG("Cookie extension received");
  12364. #ifdef WOLFSSL_DEBUG_TLS
  12365. WOLFSSL_BUFFER(input + offset, size);
  12366. #endif
  12367. if (!IsAtLeastTLSv1_3(ssl->version))
  12368. break;
  12369. if (msgType != client_hello &&
  12370. msgType != hello_retry_request) {
  12371. return EXT_NOT_ALLOWED;
  12372. }
  12373. ret = CKE_PARSE(ssl, input + offset, size, msgType);
  12374. break;
  12375. #endif
  12376. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12377. case TLSX_PRE_SHARED_KEY:
  12378. WOLFSSL_MSG("Pre-Shared Key extension received");
  12379. #ifdef WOLFSSL_DEBUG_TLS
  12380. WOLFSSL_BUFFER(input + offset, size);
  12381. #endif
  12382. if (!IsAtLeastTLSv1_3(ssl->version))
  12383. break;
  12384. if (msgType != client_hello &&
  12385. msgType != server_hello) {
  12386. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12387. return EXT_NOT_ALLOWED;
  12388. }
  12389. ret = PSK_PARSE(ssl, input + offset, size, msgType);
  12390. pskDone = 1;
  12391. break;
  12392. case TLSX_PSK_KEY_EXCHANGE_MODES:
  12393. WOLFSSL_MSG("PSK Key Exchange Modes extension received");
  12394. #ifdef WOLFSSL_DEBUG_TLS
  12395. WOLFSSL_BUFFER(input + offset, size);
  12396. #endif
  12397. if (!IsAtLeastTLSv1_3(ssl->version))
  12398. break;
  12399. if (msgType != client_hello) {
  12400. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12401. return EXT_NOT_ALLOWED;
  12402. }
  12403. ret = PKM_PARSE(ssl, input + offset, size, msgType);
  12404. break;
  12405. #endif
  12406. #ifdef WOLFSSL_EARLY_DATA
  12407. case TLSX_EARLY_DATA:
  12408. WOLFSSL_MSG("Early Data extension received");
  12409. #ifdef WOLFSSL_DEBUG_TLS
  12410. WOLFSSL_BUFFER(input + offset, size);
  12411. #endif
  12412. if (!IsAtLeastTLSv1_3(ssl->version))
  12413. break;
  12414. if (msgType != client_hello && msgType != session_ticket &&
  12415. msgType != encrypted_extensions) {
  12416. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12417. return EXT_NOT_ALLOWED;
  12418. }
  12419. ret = EDI_PARSE(ssl, input + offset, size, msgType);
  12420. break;
  12421. #endif
  12422. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  12423. case TLSX_POST_HANDSHAKE_AUTH:
  12424. WOLFSSL_MSG("Post Handshake Authentication extension received");
  12425. #ifdef WOLFSSL_DEBUG_TLS
  12426. WOLFSSL_BUFFER(input + offset, size);
  12427. #endif
  12428. if (!IsAtLeastTLSv1_3(ssl->version))
  12429. break;
  12430. if (msgType != client_hello) {
  12431. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12432. return EXT_NOT_ALLOWED;
  12433. }
  12434. ret = PHA_PARSE(ssl, input + offset, size, msgType);
  12435. break;
  12436. #endif
  12437. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  12438. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  12439. WOLFSSL_MSG("Signature Algorithms extension received");
  12440. #ifdef WOLFSSL_DEBUG_TLS
  12441. WOLFSSL_BUFFER(input + offset, size);
  12442. #endif
  12443. if (!IsAtLeastTLSv1_3(ssl->version))
  12444. break;
  12445. if (msgType != client_hello &&
  12446. msgType != certificate_request) {
  12447. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12448. return EXT_NOT_ALLOWED;
  12449. }
  12450. ret = SAC_PARSE(ssl, input + offset, size, isRequest);
  12451. break;
  12452. #endif
  12453. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  12454. case TLSX_CERTIFICATE_AUTHORITIES:
  12455. WOLFSSL_MSG("Certificate Authorities extension received");
  12456. #ifdef WOLFSSL_DEBUG_TLS
  12457. WOLFSSL_BUFFER(input + offset, size);
  12458. #endif
  12459. if (!IsAtLeastTLSv1_3(ssl->version))
  12460. break;
  12461. if (msgType != client_hello &&
  12462. msgType != certificate_request) {
  12463. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12464. return EXT_NOT_ALLOWED;
  12465. }
  12466. ret = CAN_PARSE(ssl, input + offset, size, isRequest);
  12467. break;
  12468. #endif
  12469. case TLSX_KEY_SHARE:
  12470. WOLFSSL_MSG("Key Share extension received");
  12471. #ifdef WOLFSSL_DEBUG_TLS
  12472. WOLFSSL_BUFFER(input + offset, size);
  12473. #endif
  12474. #ifdef HAVE_SUPPORTED_CURVES
  12475. if (!IsAtLeastTLSv1_3(ssl->version))
  12476. break;
  12477. if (msgType != client_hello && msgType != server_hello &&
  12478. msgType != hello_retry_request) {
  12479. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12480. return EXT_NOT_ALLOWED;
  12481. }
  12482. #endif
  12483. ret = KS_PARSE(ssl, input + offset, size, msgType);
  12484. break;
  12485. #endif
  12486. #ifdef WOLFSSL_SRTP
  12487. case TLSX_USE_SRTP:
  12488. WOLFSSL_MSG("Use SRTP extension received");
  12489. ret = SRTP_PARSE(ssl, input + offset, size, isRequest);
  12490. break;
  12491. #endif
  12492. #ifdef WOLFSSL_QUIC
  12493. case TLSX_KEY_QUIC_TP_PARAMS:
  12494. FALL_THROUGH;
  12495. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  12496. WOLFSSL_MSG("QUIC transport parameter received");
  12497. #ifdef WOLFSSL_DEBUG_TLS
  12498. WOLFSSL_BUFFER(input + offset, size);
  12499. #endif
  12500. if (IsAtLeastTLSv1_3(ssl->version) &&
  12501. msgType != client_hello &&
  12502. msgType != server_hello &&
  12503. msgType != encrypted_extensions) {
  12504. return EXT_NOT_ALLOWED;
  12505. }
  12506. else if (!IsAtLeastTLSv1_3(ssl->version) &&
  12507. msgType == encrypted_extensions) {
  12508. return EXT_NOT_ALLOWED;
  12509. }
  12510. else if (WOLFSSL_IS_QUIC(ssl)) {
  12511. ret = QTP_PARSE(ssl, input + offset, size, type, msgType);
  12512. }
  12513. else {
  12514. WOLFSSL_MSG("QUIC transport param TLS extension type, but no QUIC");
  12515. return EXT_NOT_ALLOWED; /* be safe, this should not happen */
  12516. }
  12517. break;
  12518. #endif /* WOLFSSL_QUIC */
  12519. #if defined(WOLFSSL_DTLS_CID)
  12520. case TLSX_CONNECTION_ID:
  12521. /* connection ID not supported in DTLSv1.2 */
  12522. if (!IsAtLeastTLSv1_3(ssl->version))
  12523. break;
  12524. if (msgType != client_hello && msgType != server_hello)
  12525. return EXT_NOT_ALLOWED;
  12526. WOLFSSL_MSG("ConnectionID extension received");
  12527. ret = CID_PARSE(ssl, input + offset, size, isRequest);
  12528. break;
  12529. #endif /* defined(WOLFSSL_DTLS_CID) */
  12530. #if defined(HAVE_RPK)
  12531. case TLSX_CLIENT_CERTIFICATE_TYPE:
  12532. WOLFSSL_MSG("Client Certificate Type extension received");
  12533. ret = CCT_PARSE(ssl, input + offset, size, msgType);
  12534. break;
  12535. case TLSX_SERVER_CERTIFICATE_TYPE:
  12536. WOLFSSL_MSG("Server Certificate Type extension received");
  12537. ret = SCT_PARSE(ssl, input + offset, size, msgType);
  12538. break;
  12539. #endif /* HAVE_RPK */
  12540. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  12541. case TLSX_ECH:
  12542. ret = ECH_PARSE(ssl, input + offset, size, msgType);
  12543. break;
  12544. #endif
  12545. default:
  12546. WOLFSSL_MSG("Unknown TLS extension type");
  12547. }
  12548. /* offset should be updated here! */
  12549. offset += size;
  12550. }
  12551. #ifdef HAVE_EXTENDED_MASTER
  12552. if (IsAtLeastTLSv1_3(ssl->version) && msgType == hello_retry_request) {
  12553. /* Don't change EMS status until server_hello received.
  12554. * Second ClientHello must have same extensions.
  12555. */
  12556. }
  12557. else if (!isRequest && ssl->options.haveEMS && !pendingEMS)
  12558. ssl->options.haveEMS = 0;
  12559. #endif
  12560. if (ret == 0)
  12561. ret = SNI_VERIFY_PARSE(ssl, isRequest);
  12562. if (ret == 0)
  12563. ret = TCA_VERIFY_PARSE(ssl, isRequest);
  12564. return ret;
  12565. }
  12566. /* undefining semaphore macros */
  12567. #undef IS_OFF
  12568. #undef TURN_ON
  12569. #undef SEMAPHORE_SIZE
  12570. #endif /* HAVE_TLS_EXTENSIONS */
  12571. #ifndef NO_WOLFSSL_CLIENT
  12572. WOLFSSL_METHOD* wolfTLS_client_method(void)
  12573. {
  12574. return wolfTLS_client_method_ex(NULL);
  12575. }
  12576. WOLFSSL_METHOD* wolfTLS_client_method_ex(void* heap)
  12577. {
  12578. WOLFSSL_METHOD* method =
  12579. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12580. heap, DYNAMIC_TYPE_METHOD);
  12581. (void)heap;
  12582. WOLFSSL_ENTER("TLS_client_method_ex");
  12583. if (method) {
  12584. #if defined(WOLFSSL_TLS13)
  12585. InitSSL_Method(method, MakeTLSv1_3());
  12586. #elif !defined(WOLFSSL_NO_TLS12)
  12587. InitSSL_Method(method, MakeTLSv1_2());
  12588. #elif !defined(NO_OLD_TLS)
  12589. InitSSL_Method(method, MakeTLSv1_1());
  12590. #elif defined(WOLFSSL_ALLOW_TLSV10)
  12591. InitSSL_Method(method, MakeTLSv1());
  12592. #else
  12593. #error No TLS version enabled!
  12594. #endif
  12595. method->downgrade = 1;
  12596. method->side = WOLFSSL_CLIENT_END;
  12597. }
  12598. return method;
  12599. }
  12600. #ifndef NO_OLD_TLS
  12601. #ifdef WOLFSSL_ALLOW_TLSV10
  12602. WOLFSSL_METHOD* wolfTLSv1_client_method(void)
  12603. {
  12604. return wolfTLSv1_client_method_ex(NULL);
  12605. }
  12606. WOLFSSL_METHOD* wolfTLSv1_client_method_ex(void* heap)
  12607. {
  12608. WOLFSSL_METHOD* method =
  12609. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12610. heap, DYNAMIC_TYPE_METHOD);
  12611. (void)heap;
  12612. WOLFSSL_ENTER("TLSv1_client_method_ex");
  12613. if (method)
  12614. InitSSL_Method(method, MakeTLSv1());
  12615. return method;
  12616. }
  12617. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12618. WOLFSSL_METHOD* wolfTLSv1_1_client_method(void)
  12619. {
  12620. return wolfTLSv1_1_client_method_ex(NULL);
  12621. }
  12622. WOLFSSL_METHOD* wolfTLSv1_1_client_method_ex(void* heap)
  12623. {
  12624. WOLFSSL_METHOD* method =
  12625. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12626. heap, DYNAMIC_TYPE_METHOD);
  12627. (void)heap;
  12628. WOLFSSL_ENTER("TLSv1_1_client_method_ex");
  12629. if (method)
  12630. InitSSL_Method(method, MakeTLSv1_1());
  12631. return method;
  12632. }
  12633. #endif /* !NO_OLD_TLS */
  12634. #ifndef WOLFSSL_NO_TLS12
  12635. WOLFSSL_ABI
  12636. WOLFSSL_METHOD* wolfTLSv1_2_client_method(void)
  12637. {
  12638. return wolfTLSv1_2_client_method_ex(NULL);
  12639. }
  12640. WOLFSSL_METHOD* wolfTLSv1_2_client_method_ex(void* heap)
  12641. {
  12642. WOLFSSL_METHOD* method =
  12643. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12644. heap, DYNAMIC_TYPE_METHOD);
  12645. (void)heap;
  12646. WOLFSSL_ENTER("TLSv1_2_client_method_ex");
  12647. if (method)
  12648. InitSSL_Method(method, MakeTLSv1_2());
  12649. return method;
  12650. }
  12651. #endif /* WOLFSSL_NO_TLS12 */
  12652. #ifdef WOLFSSL_TLS13
  12653. /* The TLS v1.3 client method data.
  12654. *
  12655. * returns the method data for a TLS v1.3 client.
  12656. */
  12657. WOLFSSL_ABI
  12658. WOLFSSL_METHOD* wolfTLSv1_3_client_method(void)
  12659. {
  12660. return wolfTLSv1_3_client_method_ex(NULL);
  12661. }
  12662. /* The TLS v1.3 client method data.
  12663. *
  12664. * heap The heap used for allocation.
  12665. * returns the method data for a TLS v1.3 client.
  12666. */
  12667. WOLFSSL_METHOD* wolfTLSv1_3_client_method_ex(void* heap)
  12668. {
  12669. WOLFSSL_METHOD* method = (WOLFSSL_METHOD*)
  12670. XMALLOC(sizeof(WOLFSSL_METHOD), heap,
  12671. DYNAMIC_TYPE_METHOD);
  12672. (void)heap;
  12673. WOLFSSL_ENTER("TLSv1_3_client_method_ex");
  12674. if (method)
  12675. InitSSL_Method(method, MakeTLSv1_3());
  12676. return method;
  12677. }
  12678. #endif /* WOLFSSL_TLS13 */
  12679. #ifdef WOLFSSL_DTLS
  12680. WOLFSSL_METHOD* wolfDTLS_client_method(void)
  12681. {
  12682. return wolfDTLS_client_method_ex(NULL);
  12683. }
  12684. WOLFSSL_METHOD* wolfDTLS_client_method_ex(void* heap)
  12685. {
  12686. WOLFSSL_METHOD* method =
  12687. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12688. heap, DYNAMIC_TYPE_METHOD);
  12689. (void)heap;
  12690. WOLFSSL_ENTER("DTLS_client_method_ex");
  12691. if (method) {
  12692. #if defined(WOLFSSL_DTLS13)
  12693. InitSSL_Method(method, MakeDTLSv1_3());
  12694. #elif !defined(WOLFSSL_NO_TLS12)
  12695. InitSSL_Method(method, MakeDTLSv1_2());
  12696. #elif !defined(NO_OLD_TLS)
  12697. InitSSL_Method(method, MakeDTLSv1());
  12698. #else
  12699. #error No DTLS version enabled!
  12700. #endif
  12701. method->downgrade = 1;
  12702. method->side = WOLFSSL_CLIENT_END;
  12703. }
  12704. return method;
  12705. }
  12706. #ifndef NO_OLD_TLS
  12707. WOLFSSL_METHOD* wolfDTLSv1_client_method(void)
  12708. {
  12709. return wolfDTLSv1_client_method_ex(NULL);
  12710. }
  12711. WOLFSSL_METHOD* wolfDTLSv1_client_method_ex(void* heap)
  12712. {
  12713. WOLFSSL_METHOD* method =
  12714. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12715. heap, DYNAMIC_TYPE_METHOD);
  12716. (void)heap;
  12717. WOLFSSL_ENTER("DTLSv1_client_method_ex");
  12718. if (method)
  12719. InitSSL_Method(method, MakeDTLSv1());
  12720. return method;
  12721. }
  12722. #endif /* NO_OLD_TLS */
  12723. #ifndef WOLFSSL_NO_TLS12
  12724. WOLFSSL_METHOD* wolfDTLSv1_2_client_method(void)
  12725. {
  12726. return wolfDTLSv1_2_client_method_ex(NULL);
  12727. }
  12728. WOLFSSL_METHOD* wolfDTLSv1_2_client_method_ex(void* heap)
  12729. {
  12730. WOLFSSL_METHOD* method =
  12731. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12732. heap, DYNAMIC_TYPE_METHOD);
  12733. (void)heap;
  12734. WOLFSSL_ENTER("DTLSv1_2_client_method_ex");
  12735. if (method)
  12736. InitSSL_Method(method, MakeDTLSv1_2());
  12737. (void)heap;
  12738. return method;
  12739. }
  12740. #endif /* !WOLFSSL_NO_TLS12 */
  12741. #endif /* WOLFSSL_DTLS */
  12742. #endif /* NO_WOLFSSL_CLIENT */
  12743. /* EITHER SIDE METHODS */
  12744. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
  12745. #ifndef NO_OLD_TLS
  12746. #ifdef WOLFSSL_ALLOW_TLSV10
  12747. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12748. *
  12749. * Returns a pointer to a WOLFSSL_METHOD struct
  12750. */
  12751. WOLFSSL_METHOD* wolfTLSv1_method(void)
  12752. {
  12753. return wolfTLSv1_method_ex(NULL);
  12754. }
  12755. WOLFSSL_METHOD* wolfTLSv1_method_ex(void* heap)
  12756. {
  12757. WOLFSSL_METHOD* m;
  12758. WOLFSSL_ENTER("TLSv1_method");
  12759. #ifndef NO_WOLFSSL_CLIENT
  12760. m = wolfTLSv1_client_method_ex(heap);
  12761. #else
  12762. m = wolfTLSv1_server_method_ex(heap);
  12763. #endif
  12764. if (m != NULL) {
  12765. m->side = WOLFSSL_NEITHER_END;
  12766. }
  12767. return m;
  12768. }
  12769. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12770. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12771. *
  12772. * Returns a pointer to a WOLFSSL_METHOD struct
  12773. */
  12774. WOLFSSL_METHOD* wolfTLSv1_1_method(void)
  12775. {
  12776. return wolfTLSv1_1_method_ex(NULL);
  12777. }
  12778. WOLFSSL_METHOD* wolfTLSv1_1_method_ex(void* heap)
  12779. {
  12780. WOLFSSL_METHOD* m;
  12781. WOLFSSL_ENTER("TLSv1_1_method");
  12782. #ifndef NO_WOLFSSL_CLIENT
  12783. m = wolfTLSv1_1_client_method_ex(heap);
  12784. #else
  12785. m = wolfTLSv1_1_server_method_ex(heap);
  12786. #endif
  12787. if (m != NULL) {
  12788. m->side = WOLFSSL_NEITHER_END;
  12789. }
  12790. return m;
  12791. }
  12792. #endif /* !NO_OLD_TLS */
  12793. #ifndef WOLFSSL_NO_TLS12
  12794. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12795. *
  12796. * Returns a pointer to a WOLFSSL_METHOD struct
  12797. */
  12798. WOLFSSL_METHOD* wolfTLSv1_2_method(void)
  12799. {
  12800. return wolfTLSv1_2_method_ex(NULL);
  12801. }
  12802. WOLFSSL_METHOD* wolfTLSv1_2_method_ex(void* heap)
  12803. {
  12804. WOLFSSL_METHOD* m;
  12805. WOLFSSL_ENTER("TLSv1_2_method");
  12806. #ifndef NO_WOLFSSL_CLIENT
  12807. m = wolfTLSv1_2_client_method_ex(heap);
  12808. #else
  12809. m = wolfTLSv1_2_server_method_ex(heap);
  12810. #endif
  12811. if (m != NULL) {
  12812. m->side = WOLFSSL_NEITHER_END;
  12813. }
  12814. return m;
  12815. }
  12816. #endif /* !WOLFSSL_NO_TLS12 */
  12817. #ifdef WOLFSSL_TLS13
  12818. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12819. *
  12820. * Returns a pointer to a WOLFSSL_METHOD struct
  12821. */
  12822. WOLFSSL_METHOD* wolfTLSv1_3_method(void)
  12823. {
  12824. return wolfTLSv1_3_method_ex(NULL);
  12825. }
  12826. WOLFSSL_METHOD* wolfTLSv1_3_method_ex(void* heap)
  12827. {
  12828. WOLFSSL_METHOD* m;
  12829. WOLFSSL_ENTER("TLSv1_3_method");
  12830. #ifndef NO_WOLFSSL_CLIENT
  12831. m = wolfTLSv1_3_client_method_ex(heap);
  12832. #else
  12833. m = wolfTLSv1_3_server_method_ex(heap);
  12834. #endif
  12835. if (m != NULL) {
  12836. m->side = WOLFSSL_NEITHER_END;
  12837. }
  12838. return m;
  12839. }
  12840. #endif /* WOLFSSL_TLS13 */
  12841. #ifdef WOLFSSL_DTLS
  12842. WOLFSSL_METHOD* wolfDTLS_method(void)
  12843. {
  12844. return wolfDTLS_method_ex(NULL);
  12845. }
  12846. WOLFSSL_METHOD* wolfDTLS_method_ex(void* heap)
  12847. {
  12848. WOLFSSL_METHOD* m;
  12849. WOLFSSL_ENTER("DTLS_method_ex");
  12850. #ifndef NO_WOLFSSL_CLIENT
  12851. m = wolfDTLS_client_method_ex(heap);
  12852. #else
  12853. m = wolfDTLS_server_method_ex(heap);
  12854. #endif
  12855. if (m != NULL) {
  12856. m->side = WOLFSSL_NEITHER_END;
  12857. }
  12858. return m;
  12859. }
  12860. #ifndef NO_OLD_TLS
  12861. WOLFSSL_METHOD* wolfDTLSv1_method(void)
  12862. {
  12863. return wolfDTLSv1_method_ex(NULL);
  12864. }
  12865. WOLFSSL_METHOD* wolfDTLSv1_method_ex(void* heap)
  12866. {
  12867. WOLFSSL_METHOD* m;
  12868. WOLFSSL_ENTER("DTLSv1_method_ex");
  12869. #ifndef NO_WOLFSSL_CLIENT
  12870. m = wolfDTLSv1_client_method_ex(heap);
  12871. #else
  12872. m = wolfDTLSv1_server_method_ex(heap);
  12873. #endif
  12874. if (m != NULL) {
  12875. m->side = WOLFSSL_NEITHER_END;
  12876. }
  12877. return m;
  12878. }
  12879. #endif /* !NO_OLD_TLS */
  12880. #ifndef WOLFSSL_NO_TLS12
  12881. WOLFSSL_METHOD* wolfDTLSv1_2_method(void)
  12882. {
  12883. return wolfDTLSv1_2_method_ex(NULL);
  12884. }
  12885. WOLFSSL_METHOD* wolfDTLSv1_2_method_ex(void* heap)
  12886. {
  12887. WOLFSSL_METHOD* m;
  12888. WOLFSSL_ENTER("DTLSv1_2_method");
  12889. #ifndef NO_WOLFSSL_CLIENT
  12890. m = wolfDTLSv1_2_client_method_ex(heap);
  12891. #else
  12892. m = wolfDTLSv1_2_server_method_ex(heap);
  12893. #endif
  12894. if (m != NULL) {
  12895. m->side = WOLFSSL_NEITHER_END;
  12896. }
  12897. return m;
  12898. }
  12899. #endif /* !WOLFSSL_NO_TLS12 */
  12900. #endif /* WOLFSSL_DTLS */
  12901. #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
  12902. #ifndef NO_WOLFSSL_SERVER
  12903. WOLFSSL_METHOD* wolfTLS_server_method(void)
  12904. {
  12905. return wolfTLS_server_method_ex(NULL);
  12906. }
  12907. WOLFSSL_METHOD* wolfTLS_server_method_ex(void* heap)
  12908. {
  12909. WOLFSSL_METHOD* method =
  12910. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12911. heap, DYNAMIC_TYPE_METHOD);
  12912. (void)heap;
  12913. WOLFSSL_ENTER("TLS_server_method_ex");
  12914. if (method) {
  12915. #if defined(WOLFSSL_TLS13)
  12916. InitSSL_Method(method, MakeTLSv1_3());
  12917. #elif !defined(WOLFSSL_NO_TLS12)
  12918. InitSSL_Method(method, MakeTLSv1_2());
  12919. #elif !defined(NO_OLD_TLS)
  12920. InitSSL_Method(method, MakeTLSv1_1());
  12921. #elif defined(WOLFSSL_ALLOW_TLSV10)
  12922. InitSSL_Method(method, MakeTLSv1());
  12923. #else
  12924. #error No TLS version enabled!
  12925. #endif
  12926. method->downgrade = 1;
  12927. method->side = WOLFSSL_SERVER_END;
  12928. }
  12929. return method;
  12930. }
  12931. #ifndef NO_OLD_TLS
  12932. #ifdef WOLFSSL_ALLOW_TLSV10
  12933. WOLFSSL_METHOD* wolfTLSv1_server_method(void)
  12934. {
  12935. return wolfTLSv1_server_method_ex(NULL);
  12936. }
  12937. WOLFSSL_METHOD* wolfTLSv1_server_method_ex(void* heap)
  12938. {
  12939. WOLFSSL_METHOD* method =
  12940. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12941. heap, DYNAMIC_TYPE_METHOD);
  12942. (void)heap;
  12943. WOLFSSL_ENTER("TLSv1_server_method_ex");
  12944. if (method) {
  12945. InitSSL_Method(method, MakeTLSv1());
  12946. method->side = WOLFSSL_SERVER_END;
  12947. }
  12948. return method;
  12949. }
  12950. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12951. WOLFSSL_METHOD* wolfTLSv1_1_server_method(void)
  12952. {
  12953. return wolfTLSv1_1_server_method_ex(NULL);
  12954. }
  12955. WOLFSSL_METHOD* wolfTLSv1_1_server_method_ex(void* heap)
  12956. {
  12957. WOLFSSL_METHOD* method =
  12958. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12959. heap, DYNAMIC_TYPE_METHOD);
  12960. (void)heap;
  12961. WOLFSSL_ENTER("TLSv1_1_server_method_ex");
  12962. if (method) {
  12963. InitSSL_Method(method, MakeTLSv1_1());
  12964. method->side = WOLFSSL_SERVER_END;
  12965. }
  12966. return method;
  12967. }
  12968. #endif /* !NO_OLD_TLS */
  12969. #ifndef WOLFSSL_NO_TLS12
  12970. WOLFSSL_ABI
  12971. WOLFSSL_METHOD* wolfTLSv1_2_server_method(void)
  12972. {
  12973. return wolfTLSv1_2_server_method_ex(NULL);
  12974. }
  12975. WOLFSSL_METHOD* wolfTLSv1_2_server_method_ex(void* heap)
  12976. {
  12977. WOLFSSL_METHOD* method =
  12978. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12979. heap, DYNAMIC_TYPE_METHOD);
  12980. (void)heap;
  12981. WOLFSSL_ENTER("TLSv1_2_server_method_ex");
  12982. if (method) {
  12983. InitSSL_Method(method, MakeTLSv1_2());
  12984. method->side = WOLFSSL_SERVER_END;
  12985. }
  12986. return method;
  12987. }
  12988. #endif /* !WOLFSSL_NO_TLS12 */
  12989. #ifdef WOLFSSL_TLS13
  12990. /* The TLS v1.3 server method data.
  12991. *
  12992. * returns the method data for a TLS v1.3 server.
  12993. */
  12994. WOLFSSL_ABI
  12995. WOLFSSL_METHOD* wolfTLSv1_3_server_method(void)
  12996. {
  12997. return wolfTLSv1_3_server_method_ex(NULL);
  12998. }
  12999. /* The TLS v1.3 server method data.
  13000. *
  13001. * heap The heap used for allocation.
  13002. * returns the method data for a TLS v1.3 server.
  13003. */
  13004. WOLFSSL_METHOD* wolfTLSv1_3_server_method_ex(void* heap)
  13005. {
  13006. WOLFSSL_METHOD* method =
  13007. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13008. heap, DYNAMIC_TYPE_METHOD);
  13009. (void)heap;
  13010. WOLFSSL_ENTER("TLSv1_3_server_method_ex");
  13011. if (method) {
  13012. InitSSL_Method(method, MakeTLSv1_3());
  13013. method->side = WOLFSSL_SERVER_END;
  13014. }
  13015. return method;
  13016. }
  13017. #endif /* WOLFSSL_TLS13 */
  13018. #ifdef WOLFSSL_DTLS
  13019. WOLFSSL_METHOD* wolfDTLS_server_method(void)
  13020. {
  13021. return wolfDTLS_server_method_ex(NULL);
  13022. }
  13023. WOLFSSL_METHOD* wolfDTLS_server_method_ex(void* heap)
  13024. {
  13025. WOLFSSL_METHOD* method =
  13026. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13027. heap, DYNAMIC_TYPE_METHOD);
  13028. (void)heap;
  13029. WOLFSSL_ENTER("DTLS_server_method_ex");
  13030. if (method) {
  13031. #if defined(WOLFSSL_DTLS13)
  13032. InitSSL_Method(method, MakeDTLSv1_3());
  13033. #elif !defined(WOLFSSL_NO_TLS12)
  13034. InitSSL_Method(method, MakeDTLSv1_2());
  13035. #elif !defined(NO_OLD_TLS)
  13036. InitSSL_Method(method, MakeDTLSv1());
  13037. #else
  13038. #error No DTLS version enabled!
  13039. #endif
  13040. method->downgrade = 1;
  13041. method->side = WOLFSSL_SERVER_END;
  13042. }
  13043. return method;
  13044. }
  13045. #ifndef NO_OLD_TLS
  13046. WOLFSSL_METHOD* wolfDTLSv1_server_method(void)
  13047. {
  13048. return wolfDTLSv1_server_method_ex(NULL);
  13049. }
  13050. WOLFSSL_METHOD* wolfDTLSv1_server_method_ex(void* heap)
  13051. {
  13052. WOLFSSL_METHOD* method =
  13053. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13054. heap, DYNAMIC_TYPE_METHOD);
  13055. (void)heap;
  13056. WOLFSSL_ENTER("DTLSv1_server_method_ex");
  13057. if (method) {
  13058. InitSSL_Method(method, MakeDTLSv1());
  13059. method->side = WOLFSSL_SERVER_END;
  13060. }
  13061. return method;
  13062. }
  13063. #endif /* !NO_OLD_TLS */
  13064. #ifndef WOLFSSL_NO_TLS12
  13065. WOLFSSL_METHOD* wolfDTLSv1_2_server_method(void)
  13066. {
  13067. return wolfDTLSv1_2_server_method_ex(NULL);
  13068. }
  13069. WOLFSSL_METHOD* wolfDTLSv1_2_server_method_ex(void* heap)
  13070. {
  13071. WOLFSSL_METHOD* method =
  13072. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13073. heap, DYNAMIC_TYPE_METHOD);
  13074. WOLFSSL_ENTER("DTLSv1_2_server_method_ex");
  13075. (void)heap;
  13076. if (method) {
  13077. InitSSL_Method(method, MakeDTLSv1_2());
  13078. method->side = WOLFSSL_SERVER_END;
  13079. }
  13080. (void)heap;
  13081. return method;
  13082. }
  13083. #endif /* !WOLFSSL_NO_TLS12 */
  13084. #endif /* WOLFSSL_DTLS */
  13085. #endif /* NO_WOLFSSL_SERVER */
  13086. #endif /* NO_TLS */
  13087. #endif /* WOLFCRYPT_ONLY */