tls.c 474 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475
  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. !defined(WOLFSSL_KEYLOG_EXPORT_WARNED)
  96. #ifndef _MSC_VER
  97. #warning The SHOW_SECRETS and WOLFSSL_SSLKEYLOGFILE options should only be used for debugging and never in a production environment
  98. #else
  99. #pragma message("Warning: The SHOW_SECRETS and WOLFSSL_SSLKEYLOGFILE options should only be used for debugging and never in a production environment")
  100. #endif
  101. #endif
  102. #ifndef WOLFSSL_NO_TLS12
  103. #ifdef WOLFSSL_SHA384
  104. #define HSHASH_SZ WC_SHA384_DIGEST_SIZE
  105. #else
  106. #define HSHASH_SZ FINISHED_SZ
  107. #endif
  108. int BuildTlsHandshakeHash(WOLFSSL* ssl, byte* hash, word32* hashLen)
  109. {
  110. int ret = 0;
  111. word32 hashSz = FINISHED_SZ;
  112. if (ssl == NULL || hash == NULL || hashLen == NULL || *hashLen < HSHASH_SZ)
  113. return BAD_FUNC_ARG;
  114. /* for constant timing perform these even if error */
  115. #ifndef NO_OLD_TLS
  116. ret |= wc_Md5GetHash(&ssl->hsHashes->hashMd5, hash);
  117. ret |= wc_ShaGetHash(&ssl->hsHashes->hashSha, &hash[WC_MD5_DIGEST_SIZE]);
  118. #endif
  119. if (IsAtLeastTLSv1_2(ssl)) {
  120. #ifndef NO_SHA256
  121. if (ssl->specs.mac_algorithm <= sha256_mac ||
  122. ssl->specs.mac_algorithm == blake2b_mac) {
  123. ret |= wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
  124. hashSz = WC_SHA256_DIGEST_SIZE;
  125. }
  126. #endif
  127. #ifdef WOLFSSL_SHA384
  128. if (ssl->specs.mac_algorithm == sha384_mac) {
  129. ret |= wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
  130. hashSz = WC_SHA384_DIGEST_SIZE;
  131. }
  132. #endif
  133. #ifdef WOLFSSL_SM3
  134. if (ssl->specs.mac_algorithm == sm3_mac) {
  135. ret |= wc_Sm3GetHash(&ssl->hsHashes->hashSm3, hash);
  136. hashSz = WC_SM3_DIGEST_SIZE;
  137. }
  138. #endif
  139. }
  140. *hashLen = hashSz;
  141. #ifdef WOLFSSL_CHECK_MEM_ZERO
  142. wc_MemZero_Add("TLS handshake hash", hash, hashSz);
  143. #endif
  144. if (ret != 0) {
  145. ret = BUILD_MSG_ERROR;
  146. WOLFSSL_ERROR_VERBOSE(ret);
  147. }
  148. return ret;
  149. }
  150. int BuildTlsFinished(WOLFSSL* ssl, Hashes* hashes, const byte* sender)
  151. {
  152. int ret;
  153. const byte* side = NULL;
  154. word32 hashSz = HSHASH_SZ;
  155. #if !defined(WOLFSSL_ASYNC_CRYPT) || defined(WC_ASYNC_NO_HASH)
  156. byte handshake_hash[HSHASH_SZ];
  157. #else
  158. WC_DECLARE_VAR(handshake_hash, byte, HSHASH_SZ, ssl->heap);
  159. WC_ALLOC_VAR(handshake_hash, byte, HSHASH_SZ, ssl->heap);
  160. if (handshake_hash == NULL)
  161. return MEMORY_E;
  162. #endif
  163. XMEMSET(handshake_hash, 0, HSHASH_SZ);
  164. ret = BuildTlsHandshakeHash(ssl, handshake_hash, &hashSz);
  165. if (ret == 0) {
  166. if (XSTRNCMP((const char*)sender, (const char*)kTlsClientStr,
  167. SIZEOF_SENDER) == 0) {
  168. side = kTlsClientFinStr;
  169. }
  170. else if (XSTRNCMP((const char*)sender, (const char*)kTlsServerStr,
  171. SIZEOF_SENDER) == 0) {
  172. side = kTlsServerFinStr;
  173. }
  174. else {
  175. ret = BAD_FUNC_ARG;
  176. WOLFSSL_MSG("Unexpected sender value");
  177. }
  178. }
  179. if (ret == 0) {
  180. #ifdef WOLFSSL_HAVE_PRF
  181. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  182. if (ssl->ctx->TlsFinishedCb) {
  183. void* ctx = wolfSSL_GetTlsFinishedCtx(ssl);
  184. ret = ssl->ctx->TlsFinishedCb(ssl, side, handshake_hash, hashSz,
  185. (byte*)hashes, ctx);
  186. }
  187. if (!ssl->ctx->TlsFinishedCb || ret == PROTOCOLCB_UNAVAILABLE)
  188. #endif
  189. {
  190. PRIVATE_KEY_UNLOCK();
  191. ret = wc_PRF_TLS((byte*)hashes, TLS_FINISHED_SZ,
  192. ssl->arrays->masterSecret, SECRET_LEN, side,
  193. FINISHED_LABEL_SZ, handshake_hash, hashSz,
  194. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  195. ssl->heap, ssl->devId);
  196. PRIVATE_KEY_LOCK();
  197. }
  198. ForceZero(handshake_hash, hashSz);
  199. #else
  200. /* Pseudo random function must be enabled in the configuration. */
  201. ret = PRF_MISSING;
  202. WOLFSSL_ERROR_VERBOSE(ret);
  203. WOLFSSL_MSG("Pseudo-random function is not enabled");
  204. (void)side;
  205. (void)hashes;
  206. #endif
  207. }
  208. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  209. WC_FREE_VAR(handshake_hash, ssl->heap);
  210. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  211. wc_MemZero_Check(handshake_hash, HSHASH_SZ);
  212. #endif
  213. return ret;
  214. }
  215. #endif /* !WOLFSSL_NO_TLS12 */
  216. #ifndef NO_OLD_TLS
  217. #ifdef WOLFSSL_ALLOW_TLSV10
  218. ProtocolVersion MakeTLSv1(void)
  219. {
  220. ProtocolVersion pv;
  221. pv.major = SSLv3_MAJOR;
  222. pv.minor = TLSv1_MINOR;
  223. return pv;
  224. }
  225. #endif /* WOLFSSL_ALLOW_TLSV10 */
  226. ProtocolVersion MakeTLSv1_1(void)
  227. {
  228. ProtocolVersion pv;
  229. pv.major = SSLv3_MAJOR;
  230. pv.minor = TLSv1_1_MINOR;
  231. return pv;
  232. }
  233. #endif /* !NO_OLD_TLS */
  234. #ifndef WOLFSSL_NO_TLS12
  235. ProtocolVersion MakeTLSv1_2(void)
  236. {
  237. ProtocolVersion pv;
  238. pv.major = SSLv3_MAJOR;
  239. pv.minor = TLSv1_2_MINOR;
  240. return pv;
  241. }
  242. #endif /* !WOLFSSL_NO_TLS12 */
  243. #ifdef WOLFSSL_TLS13
  244. /* The TLS v1.3 protocol version.
  245. *
  246. * returns the protocol version data for TLS v1.3.
  247. */
  248. ProtocolVersion MakeTLSv1_3(void)
  249. {
  250. ProtocolVersion pv;
  251. pv.major = SSLv3_MAJOR;
  252. pv.minor = TLSv1_3_MINOR;
  253. return pv;
  254. }
  255. #endif
  256. #ifndef WOLFSSL_NO_TLS12
  257. #ifdef HAVE_EXTENDED_MASTER
  258. static const byte ext_master_label[EXT_MASTER_LABEL_SZ + 1] =
  259. "extended master secret";
  260. #endif
  261. static const byte master_label[MASTER_LABEL_SZ + 1] = "master secret";
  262. static const byte key_label [KEY_LABEL_SZ + 1] = "key expansion";
  263. static int _DeriveTlsKeys(byte* key_dig, word32 key_dig_len,
  264. const byte* ms, word32 msLen,
  265. const byte* sr, const byte* cr,
  266. int tls1_2, int hash_type,
  267. void* heap, int devId)
  268. {
  269. int ret;
  270. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  271. WC_DECLARE_VAR(seed, byte, SEED_LEN, heap);
  272. WC_ALLOC_VAR(seed, byte, SEED_LEN, heap);
  273. if (seed == NULL)
  274. return MEMORY_E;
  275. #else
  276. byte seed[SEED_LEN];
  277. #endif
  278. XMEMCPY(seed, sr, RAN_LEN);
  279. XMEMCPY(seed + RAN_LEN, cr, RAN_LEN);
  280. #ifdef WOLFSSL_HAVE_PRF
  281. PRIVATE_KEY_UNLOCK();
  282. ret = wc_PRF_TLS(key_dig, key_dig_len, ms, msLen, key_label, KEY_LABEL_SZ,
  283. seed, SEED_LEN, tls1_2, hash_type, heap, devId);
  284. PRIVATE_KEY_LOCK();
  285. #else
  286. /* Pseudo random function must be enabled in the configuration. */
  287. ret = PRF_MISSING;
  288. WOLFSSL_ERROR_VERBOSE(ret);
  289. WOLFSSL_MSG("Pseudo-random function is not enabled");
  290. (void)key_dig;
  291. (void)key_dig_len;
  292. (void)ms;
  293. (void)msLen;
  294. (void)tls1_2;
  295. (void)hash_type;
  296. (void)heap;
  297. (void)devId;
  298. (void)key_label;
  299. (void)master_label;
  300. #ifdef HAVE_EXTENDED_MASTER
  301. (void)ext_master_label;
  302. #endif
  303. #endif
  304. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  305. WC_FREE_VAR(seed, heap);
  306. #endif
  307. return ret;
  308. }
  309. /* External facing wrapper so user can call as well, 0 on success */
  310. int wolfSSL_DeriveTlsKeys(byte* key_dig, word32 key_dig_len,
  311. const byte* ms, word32 msLen,
  312. const byte* sr, const byte* cr,
  313. int tls1_2, int hash_type)
  314. {
  315. return _DeriveTlsKeys(key_dig, key_dig_len, ms, msLen, sr, cr, tls1_2,
  316. hash_type, NULL, INVALID_DEVID);
  317. }
  318. int DeriveTlsKeys(WOLFSSL* ssl)
  319. {
  320. int ret;
  321. int key_dig_len = 2 * ssl->specs.hash_size +
  322. 2 * ssl->specs.key_size +
  323. 2 * ssl->specs.iv_size;
  324. #ifdef WOLFSSL_SMALL_STACK
  325. byte* key_dig;
  326. #else
  327. byte key_dig[MAX_PRF_DIG];
  328. #endif
  329. #ifdef WOLFSSL_SMALL_STACK
  330. key_dig = (byte*)XMALLOC(MAX_PRF_DIG, ssl->heap, DYNAMIC_TYPE_DIGEST);
  331. if (key_dig == NULL) {
  332. return MEMORY_E;
  333. }
  334. #endif
  335. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  336. ret = PROTOCOLCB_UNAVAILABLE;
  337. if (ssl->ctx->GenSessionKeyCb) {
  338. void* ctx = wolfSSL_GetGenSessionKeyCtx(ssl);
  339. ret = ssl->ctx->GenSessionKeyCb(ssl, ctx);
  340. }
  341. if (!ssl->ctx->GenSessionKeyCb || ret == PROTOCOLCB_UNAVAILABLE)
  342. #endif
  343. ret = _DeriveTlsKeys(key_dig, key_dig_len,
  344. ssl->arrays->masterSecret, SECRET_LEN,
  345. ssl->arrays->serverRandom, ssl->arrays->clientRandom,
  346. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  347. ssl->heap, ssl->devId);
  348. if (ret == 0)
  349. ret = StoreKeys(ssl, key_dig, PROVISION_CLIENT_SERVER);
  350. #ifdef WOLFSSL_SMALL_STACK
  351. XFREE(key_dig, ssl->heap, DYNAMIC_TYPE_DIGEST);
  352. #endif
  353. return ret;
  354. }
  355. static int _MakeTlsMasterSecret(byte* ms, word32 msLen,
  356. const byte* pms, word32 pmsLen,
  357. const byte* cr, const byte* sr,
  358. int tls1_2, int hash_type,
  359. void* heap, int devId)
  360. {
  361. int ret;
  362. #if !defined(WOLFSSL_ASYNC_CRYPT) || defined(WC_ASYNC_NO_HASH)
  363. byte seed[SEED_LEN];
  364. #else
  365. WC_DECLARE_VAR(seed, byte, SEED_LEN, heap);
  366. WC_ALLOC_VAR(seed, byte, SEED_LEN, heap);
  367. if (seed == NULL)
  368. return MEMORY_E;
  369. #endif
  370. XMEMCPY(seed, cr, RAN_LEN);
  371. XMEMCPY(seed + RAN_LEN, sr, RAN_LEN);
  372. #ifdef WOLFSSL_HAVE_PRF
  373. PRIVATE_KEY_UNLOCK();
  374. ret = wc_PRF_TLS(ms, msLen, pms, pmsLen, master_label, MASTER_LABEL_SZ,
  375. seed, SEED_LEN, tls1_2, hash_type, heap, devId);
  376. PRIVATE_KEY_LOCK();
  377. #else
  378. /* Pseudo random function must be enabled in the configuration. */
  379. ret = PRF_MISSING;
  380. WOLFSSL_MSG("Pseudo-random function is not enabled");
  381. (void)ms;
  382. (void)msLen;
  383. (void)pms;
  384. (void)pmsLen;
  385. (void)tls1_2;
  386. (void)hash_type;
  387. (void)heap;
  388. (void)devId;
  389. #endif
  390. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  391. WC_FREE_VAR(seed, heap);
  392. #endif
  393. return ret;
  394. }
  395. /* External facing wrapper so user can call as well, 0 on success */
  396. int wolfSSL_MakeTlsMasterSecret(byte* ms, word32 msLen,
  397. const byte* pms, word32 pmsLen,
  398. const byte* cr, const byte* sr,
  399. int tls1_2, int hash_type)
  400. {
  401. return _MakeTlsMasterSecret(ms, msLen, pms, pmsLen, cr, sr, tls1_2,
  402. hash_type, NULL, INVALID_DEVID);
  403. }
  404. #ifdef HAVE_EXTENDED_MASTER
  405. static int _MakeTlsExtendedMasterSecret(byte* ms, word32 msLen,
  406. const byte* pms, word32 pmsLen,
  407. const byte* sHash, word32 sHashLen,
  408. int tls1_2, int hash_type,
  409. void* heap, int devId)
  410. {
  411. int ret;
  412. #ifdef WOLFSSL_HAVE_PRF
  413. PRIVATE_KEY_UNLOCK();
  414. ret = wc_PRF_TLS(ms, msLen, pms, pmsLen, ext_master_label, EXT_MASTER_LABEL_SZ,
  415. sHash, sHashLen, tls1_2, hash_type, heap, devId);
  416. PRIVATE_KEY_LOCK();
  417. #else
  418. /* Pseudo random function must be enabled in the configuration. */
  419. ret = PRF_MISSING;
  420. WOLFSSL_MSG("Pseudo-random function is not enabled");
  421. (void)ms;
  422. (void)msLen;
  423. (void)pms;
  424. (void)pmsLen;
  425. (void)sHash;
  426. (void)sHashLen;
  427. (void)tls1_2;
  428. (void)hash_type;
  429. (void)heap;
  430. (void)devId;
  431. #endif
  432. return ret;
  433. }
  434. /* External facing wrapper so user can call as well, 0 on success */
  435. int wolfSSL_MakeTlsExtendedMasterSecret(byte* ms, word32 msLen,
  436. const byte* pms, word32 pmsLen,
  437. const byte* sHash, word32 sHashLen,
  438. int tls1_2, int hash_type)
  439. {
  440. return _MakeTlsExtendedMasterSecret(ms, msLen, pms, pmsLen, sHash, sHashLen,
  441. tls1_2, hash_type, NULL, INVALID_DEVID);
  442. }
  443. #endif /* HAVE_EXTENDED_MASTER */
  444. int MakeTlsMasterSecret(WOLFSSL* ssl)
  445. {
  446. int ret;
  447. #if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  448. /* If this is called from a sniffer session with keylog file support, obtain
  449. * the master secret from the callback */
  450. if (ssl->snifferSecretCb != NULL) {
  451. ret = ssl->snifferSecretCb(ssl->arrays->clientRandom,
  452. SNIFFER_SECRET_TLS12_MASTER_SECRET,
  453. ssl->arrays->masterSecret);
  454. if (ret != 0) {
  455. return ret;
  456. }
  457. ret = DeriveTlsKeys(ssl);
  458. return ret;
  459. }
  460. #endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
  461. #ifdef HAVE_EXTENDED_MASTER
  462. if (ssl->options.haveEMS) {
  463. word32 hashSz = HSHASH_SZ;
  464. #ifdef WOLFSSL_SMALL_STACK
  465. byte* handshake_hash = (byte*)XMALLOC(HSHASH_SZ, ssl->heap,
  466. DYNAMIC_TYPE_DIGEST);
  467. if (handshake_hash == NULL)
  468. return MEMORY_E;
  469. #else
  470. byte handshake_hash[HSHASH_SZ];
  471. #endif
  472. XMEMSET(handshake_hash, 0, HSHASH_SZ);
  473. ret = BuildTlsHandshakeHash(ssl, handshake_hash, &hashSz);
  474. if (ret == 0) {
  475. ret = _MakeTlsExtendedMasterSecret(
  476. ssl->arrays->masterSecret, SECRET_LEN,
  477. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz,
  478. handshake_hash, hashSz,
  479. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  480. ssl->heap, ssl->devId);
  481. ForceZero(handshake_hash, hashSz);
  482. }
  483. #ifdef WOLFSSL_SMALL_STACK
  484. XFREE(handshake_hash, ssl->heap, DYNAMIC_TYPE_DIGEST);
  485. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  486. wc_MemZero_Check(handshake_hash, HSHASH_SZ);
  487. #endif
  488. }
  489. else
  490. #endif /* HAVE_EXTENDED_MASTER */
  491. {
  492. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  493. ret = PROTOCOLCB_UNAVAILABLE;
  494. if (ssl->ctx->GenMasterCb) {
  495. void* ctx = wolfSSL_GetGenMasterSecretCtx(ssl);
  496. ret = ssl->ctx->GenMasterCb(ssl, ctx);
  497. }
  498. if (!ssl->ctx->GenMasterCb || ret == PROTOCOLCB_UNAVAILABLE)
  499. #endif
  500. {
  501. ret = _MakeTlsMasterSecret(ssl->arrays->masterSecret,
  502. SECRET_LEN, ssl->arrays->preMasterSecret,
  503. ssl->arrays->preMasterSz, ssl->arrays->clientRandom,
  504. ssl->arrays->serverRandom, IsAtLeastTLSv1_2(ssl),
  505. ssl->specs.mac_algorithm, ssl->heap, ssl->devId);
  506. }
  507. }
  508. #ifdef HAVE_SECRET_CALLBACK
  509. if (ret == 0 && ssl->tlsSecretCb != NULL) {
  510. ret = ssl->tlsSecretCb(ssl, ssl->arrays->masterSecret,
  511. SECRET_LEN, ssl->tlsSecretCtx);
  512. }
  513. #endif /* HAVE_SECRET_CALLBACK */
  514. if (ret == 0) {
  515. ret = DeriveTlsKeys(ssl);
  516. }
  517. return ret;
  518. }
  519. /* Used by EAP-TLS and EAP-TTLS to derive keying material from
  520. * the master_secret. */
  521. int wolfSSL_make_eap_keys(WOLFSSL* ssl, void* msk, unsigned int len,
  522. const char* label)
  523. {
  524. int ret;
  525. #ifdef WOLFSSL_SMALL_STACK
  526. byte* seed;
  527. #else
  528. byte seed[SEED_LEN];
  529. #endif
  530. #ifdef WOLFSSL_SMALL_STACK
  531. seed = (byte*)XMALLOC(SEED_LEN, ssl->heap, DYNAMIC_TYPE_SEED);
  532. if (seed == NULL)
  533. return MEMORY_E;
  534. #endif
  535. /*
  536. * As per RFC-5281, the order of the client and server randoms is reversed
  537. * from that used by the TLS protocol to derive keys.
  538. */
  539. XMEMCPY(seed, ssl->arrays->clientRandom, RAN_LEN);
  540. XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
  541. #ifdef WOLFSSL_HAVE_PRF
  542. PRIVATE_KEY_UNLOCK();
  543. ret = wc_PRF_TLS((byte*)msk, len, ssl->arrays->masterSecret, SECRET_LEN,
  544. (const byte *)label, (word32)XSTRLEN(label), seed, SEED_LEN,
  545. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  546. ssl->heap, ssl->devId);
  547. PRIVATE_KEY_LOCK();
  548. #else
  549. /* Pseudo random function must be enabled in the configuration. */
  550. ret = PRF_MISSING;
  551. WOLFSSL_MSG("Pseudo-random function is not enabled");
  552. (void)msk;
  553. (void)len;
  554. (void)label;
  555. #endif
  556. #ifdef WOLFSSL_SMALL_STACK
  557. XFREE(seed, ssl->heap, DYNAMIC_TYPE_SEED);
  558. #endif
  559. return ret;
  560. }
  561. /* return HMAC digest type in wolfSSL format */
  562. int wolfSSL_GetHmacType(WOLFSSL* ssl)
  563. {
  564. if (ssl == NULL)
  565. return BAD_FUNC_ARG;
  566. return wolfSSL_GetHmacType_ex(&ssl->specs);
  567. }
  568. int wolfSSL_SetTlsHmacInner(WOLFSSL* ssl, byte* inner, word32 sz, int content,
  569. int verify)
  570. {
  571. if (ssl == NULL || inner == NULL)
  572. return BAD_FUNC_ARG;
  573. XMEMSET(inner, 0, WOLFSSL_TLS_HMAC_INNER_SZ);
  574. WriteSEQ(ssl, verify, inner);
  575. inner[SEQ_SZ] = (byte)content;
  576. inner[SEQ_SZ + ENUM_LEN] = ssl->version.major;
  577. inner[SEQ_SZ + ENUM_LEN + ENUM_LEN] = ssl->version.minor;
  578. c16toa((word16)sz, inner + SEQ_SZ + ENUM_LEN + VERSION_SZ);
  579. return 0;
  580. }
  581. #ifndef WOLFSSL_AEAD_ONLY
  582. #if !defined(WOLFSSL_NO_HASH_RAW) && !defined(HAVE_FIPS) && \
  583. !defined(HAVE_SELFTEST)
  584. /* Update the hash in the HMAC.
  585. *
  586. * hmac HMAC object.
  587. * data Data to be hashed.
  588. * sz Size of data to hash.
  589. * returns 0 on success, otherwise failure.
  590. */
  591. static int Hmac_HashUpdate(Hmac* hmac, const byte* data, word32 sz)
  592. {
  593. int ret = BAD_FUNC_ARG;
  594. switch (hmac->macType) {
  595. #ifndef NO_SHA
  596. case WC_SHA:
  597. ret = wc_ShaUpdate(&hmac->hash.sha, data, sz);
  598. break;
  599. #endif /* !NO_SHA */
  600. #ifndef NO_SHA256
  601. case WC_SHA256:
  602. ret = wc_Sha256Update(&hmac->hash.sha256, data, sz);
  603. break;
  604. #endif /* !NO_SHA256 */
  605. #ifdef WOLFSSL_SHA384
  606. case WC_SHA384:
  607. ret = wc_Sha384Update(&hmac->hash.sha384, data, sz);
  608. break;
  609. #endif /* WOLFSSL_SHA384 */
  610. #ifdef WOLFSSL_SHA512
  611. case WC_SHA512:
  612. ret = wc_Sha512Update(&hmac->hash.sha512, data, sz);
  613. break;
  614. #endif /* WOLFSSL_SHA512 */
  615. #ifdef WOLFSSL_SM3
  616. case WC_SM3:
  617. ret = wc_Sm3Update(&hmac->hash.sm3, data, sz);
  618. break;
  619. #endif /* WOLFSSL_SM3 */
  620. default:
  621. break;
  622. }
  623. return ret;
  624. }
  625. /* Finalize the hash but don't put the EOC, padding or length in.
  626. *
  627. * hmac HMAC object.
  628. * hash Hash result.
  629. * returns 0 on success, otherwise failure.
  630. */
  631. static int Hmac_HashFinalRaw(Hmac* hmac, unsigned char* hash)
  632. {
  633. int ret = BAD_FUNC_ARG;
  634. switch (hmac->macType) {
  635. #ifndef NO_SHA
  636. case WC_SHA:
  637. ret = wc_ShaFinalRaw(&hmac->hash.sha, hash);
  638. break;
  639. #endif /* !NO_SHA */
  640. #ifndef NO_SHA256
  641. case WC_SHA256:
  642. ret = wc_Sha256FinalRaw(&hmac->hash.sha256, hash);
  643. break;
  644. #endif /* !NO_SHA256 */
  645. #ifdef WOLFSSL_SHA384
  646. case WC_SHA384:
  647. ret = wc_Sha384FinalRaw(&hmac->hash.sha384, hash);
  648. break;
  649. #endif /* WOLFSSL_SHA384 */
  650. #ifdef WOLFSSL_SHA512
  651. case WC_SHA512:
  652. ret = wc_Sha512FinalRaw(&hmac->hash.sha512, hash);
  653. break;
  654. #endif /* WOLFSSL_SHA512 */
  655. #ifdef WOLFSSL_SM3
  656. case WC_SM3:
  657. ret = wc_Sm3FinalRaw(&hmac->hash.sm3, hash);
  658. break;
  659. #endif /* WOLFSSL_SM3 */
  660. default:
  661. break;
  662. }
  663. return ret;
  664. }
  665. /* Finalize the HMAC by performing outer hash.
  666. *
  667. * hmac HMAC object.
  668. * mac MAC result.
  669. * returns 0 on success, otherwise failure.
  670. */
  671. static int Hmac_OuterHash(Hmac* hmac, unsigned char* mac)
  672. {
  673. int ret = BAD_FUNC_ARG;
  674. wc_HashAlg hash;
  675. enum wc_HashType hashType = (enum wc_HashType)hmac->macType;
  676. int digestSz = wc_HashGetDigestSize(hashType);
  677. int blockSz = wc_HashGetBlockSize(hashType);
  678. if ((digestSz >= 0) && (blockSz >= 0)) {
  679. ret = wc_HashInit(&hash, hashType);
  680. }
  681. if (ret == 0) {
  682. ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->opad,
  683. blockSz);
  684. if (ret == 0)
  685. ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->innerHash,
  686. digestSz);
  687. if (ret == 0)
  688. ret = wc_HashFinal(&hash, hashType, mac);
  689. wc_HashFree(&hash, hashType);
  690. }
  691. return ret;
  692. }
  693. /* Calculate the HMAC of the header + message data.
  694. * Constant time implementation using wc_Sha*FinalRaw().
  695. *
  696. * hmac HMAC object.
  697. * digest MAC result.
  698. * in Message data.
  699. * sz Size of the message data.
  700. * header Constructed record header with length of handshake data.
  701. * returns 0 on success, otherwise failure.
  702. */
  703. static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in,
  704. word32 sz, int macLen, byte* header)
  705. {
  706. byte lenBytes[8];
  707. int i, j;
  708. unsigned int k;
  709. int blockBits, blockMask;
  710. int lastBlockLen, extraLen, eocIndex;
  711. int blocks, safeBlocks, lenBlock, eocBlock;
  712. unsigned int maxLen;
  713. int blockSz, padSz;
  714. int ret;
  715. word32 realLen;
  716. byte extraBlock;
  717. switch (hmac->macType) {
  718. #ifndef NO_SHA
  719. case WC_SHA:
  720. blockSz = WC_SHA_BLOCK_SIZE;
  721. blockBits = 6;
  722. padSz = WC_SHA_BLOCK_SIZE - WC_SHA_PAD_SIZE + 1;
  723. break;
  724. #endif /* !NO_SHA */
  725. #ifndef NO_SHA256
  726. case WC_SHA256:
  727. blockSz = WC_SHA256_BLOCK_SIZE;
  728. blockBits = 6;
  729. padSz = WC_SHA256_BLOCK_SIZE - WC_SHA256_PAD_SIZE + 1;
  730. break;
  731. #endif /* !NO_SHA256 */
  732. #ifdef WOLFSSL_SHA384
  733. case WC_SHA384:
  734. blockSz = WC_SHA384_BLOCK_SIZE;
  735. blockBits = 7;
  736. padSz = WC_SHA384_BLOCK_SIZE - WC_SHA384_PAD_SIZE + 1;
  737. break;
  738. #endif /* WOLFSSL_SHA384 */
  739. #ifdef WOLFSSL_SHA512
  740. case WC_SHA512:
  741. blockSz = WC_SHA512_BLOCK_SIZE;
  742. blockBits = 7;
  743. padSz = WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE + 1;
  744. break;
  745. #endif /* WOLFSSL_SHA512 */
  746. #ifdef WOLFSSL_SM3
  747. case WC_SM3:
  748. blockSz = WC_SM3_BLOCK_SIZE;
  749. blockBits = 6;
  750. padSz = WC_SM3_BLOCK_SIZE - WC_SM3_PAD_SIZE + 1;
  751. break;
  752. #endif /* WOLFSSL_SM3 */
  753. default:
  754. return BAD_FUNC_ARG;
  755. }
  756. blockMask = blockSz - 1;
  757. /* Size of data to HMAC if padding length byte is zero. */
  758. maxLen = WOLFSSL_TLS_HMAC_INNER_SZ + sz - 1 - macLen;
  759. /* Complete data (including padding) has block for EOC and/or length. */
  760. extraBlock = ctSetLTE((maxLen + padSz) & blockMask, padSz);
  761. /* Total number of blocks for data including padding. */
  762. blocks = ((maxLen + blockSz - 1) >> blockBits) + extraBlock;
  763. /* Up to last 6 blocks can be hashed safely. */
  764. safeBlocks = blocks - 6;
  765. /* Length of message data. */
  766. realLen = maxLen - in[sz - 1];
  767. /* Number of message bytes in last block. */
  768. lastBlockLen = realLen & blockMask;
  769. /* Number of padding bytes in last block. */
  770. extraLen = ((blockSz * 2 - padSz - lastBlockLen) & blockMask) + 1;
  771. /* Number of blocks to create for hash. */
  772. lenBlock = (realLen + extraLen) >> blockBits;
  773. /* Block containing EOC byte. */
  774. eocBlock = realLen >> blockBits;
  775. /* Index of EOC byte in block. */
  776. eocIndex = realLen & blockMask;
  777. /* Add length of hmac's ipad to total length. */
  778. realLen += blockSz;
  779. /* Length as bits - 8 bytes bigendian. */
  780. c32toa(realLen >> ((sizeof(word32) * 8) - 3), lenBytes);
  781. c32toa(realLen << 3, lenBytes + sizeof(word32));
  782. ret = Hmac_HashUpdate(hmac, (unsigned char*)hmac->ipad, blockSz);
  783. if (ret != 0)
  784. return ret;
  785. XMEMSET(hmac->innerHash, 0, macLen);
  786. if (safeBlocks > 0) {
  787. ret = Hmac_HashUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ);
  788. if (ret != 0)
  789. return ret;
  790. ret = Hmac_HashUpdate(hmac, in, safeBlocks * blockSz -
  791. WOLFSSL_TLS_HMAC_INNER_SZ);
  792. if (ret != 0)
  793. return ret;
  794. }
  795. else
  796. safeBlocks = 0;
  797. XMEMSET(digest, 0, macLen);
  798. k = safeBlocks * blockSz;
  799. for (i = safeBlocks; i < blocks; i++) {
  800. unsigned char hashBlock[WC_MAX_BLOCK_SIZE];
  801. unsigned char isEocBlock = ctMaskEq(i, eocBlock);
  802. unsigned char isOutBlock = ctMaskEq(i, lenBlock);
  803. for (j = 0; j < blockSz; j++) {
  804. unsigned char atEoc = ctMaskEq(j, eocIndex) & isEocBlock;
  805. unsigned char pastEoc = ctMaskGT(j, eocIndex) & isEocBlock;
  806. unsigned char b = 0;
  807. if (k < WOLFSSL_TLS_HMAC_INNER_SZ)
  808. b = header[k];
  809. else if (k < maxLen)
  810. b = in[k - WOLFSSL_TLS_HMAC_INNER_SZ];
  811. k++;
  812. b = ctMaskSel(atEoc, 0x80, b);
  813. b &= (unsigned char)~(word32)pastEoc;
  814. b &= ((unsigned char)~(word32)isOutBlock) | isEocBlock;
  815. if (j >= blockSz - 8) {
  816. b = ctMaskSel(isOutBlock, lenBytes[j - (blockSz - 8)], b);
  817. }
  818. hashBlock[j] = b;
  819. }
  820. ret = Hmac_HashUpdate(hmac, hashBlock, blockSz);
  821. if (ret != 0)
  822. return ret;
  823. ret = Hmac_HashFinalRaw(hmac, hashBlock);
  824. if (ret != 0)
  825. return ret;
  826. for (j = 0; j < macLen; j++)
  827. ((unsigned char*)hmac->innerHash)[j] |= hashBlock[j] & isOutBlock;
  828. }
  829. ret = Hmac_OuterHash(hmac, digest);
  830. return ret;
  831. }
  832. #endif
  833. #if defined(WOLFSSL_NO_HASH_RAW) || defined(HAVE_FIPS) || \
  834. defined(HAVE_SELFTEST) || defined(HAVE_BLAKE2)
  835. /* Calculate the HMAC of the header + message data.
  836. * Constant time implementation using normal hashing operations.
  837. * Update-Final need to be constant time.
  838. *
  839. * hmac HMAC object.
  840. * digest MAC result.
  841. * in Message data.
  842. * sz Size of the message data.
  843. * header Constructed record header with length of handshake data.
  844. * returns 0 on success, otherwise failure.
  845. */
  846. static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in,
  847. word32 sz, byte* header)
  848. {
  849. byte dummy[WC_MAX_BLOCK_SIZE] = {0};
  850. int ret = 0;
  851. word32 msgSz, blockSz, macSz, padSz, maxSz, realSz;
  852. word32 offset = 0;
  853. int msgBlocks, blocks, blockBits;
  854. int i;
  855. switch (hmac->macType) {
  856. #ifndef NO_SHA
  857. case WC_SHA:
  858. blockSz = WC_SHA_BLOCK_SIZE;
  859. blockBits = 6;
  860. macSz = WC_SHA_DIGEST_SIZE;
  861. padSz = WC_SHA_BLOCK_SIZE - WC_SHA_PAD_SIZE + 1;
  862. break;
  863. #endif /* !NO_SHA */
  864. #ifndef NO_SHA256
  865. case WC_SHA256:
  866. blockSz = WC_SHA256_BLOCK_SIZE;
  867. blockBits = 6;
  868. macSz = WC_SHA256_DIGEST_SIZE;
  869. padSz = WC_SHA256_BLOCK_SIZE - WC_SHA256_PAD_SIZE + 1;
  870. break;
  871. #endif /* !NO_SHA256 */
  872. #ifdef WOLFSSL_SHA384
  873. case WC_SHA384:
  874. blockSz = WC_SHA384_BLOCK_SIZE;
  875. blockBits = 7;
  876. macSz = WC_SHA384_DIGEST_SIZE;
  877. padSz = WC_SHA384_BLOCK_SIZE - WC_SHA384_PAD_SIZE + 1;
  878. break;
  879. #endif /* WOLFSSL_SHA384 */
  880. #ifdef WOLFSSL_SHA512
  881. case WC_SHA512:
  882. blockSz = WC_SHA512_BLOCK_SIZE;
  883. blockBits = 7;
  884. macSz = WC_SHA512_DIGEST_SIZE;
  885. padSz = WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE + 1;
  886. break;
  887. #endif /* WOLFSSL_SHA512 */
  888. #ifdef HAVE_BLAKE2
  889. case WC_HASH_TYPE_BLAKE2B:
  890. blockSz = BLAKE2B_BLOCKBYTES;
  891. blockBits = 7;
  892. macSz = BLAKE2B_256;
  893. padSz = 0;
  894. break;
  895. #endif /* HAVE_BLAKE2 */
  896. #ifdef WOLFSSL_SM3
  897. case WC_SM3:
  898. blockSz = WC_SM3_BLOCK_SIZE;
  899. blockBits = 6;
  900. macSz = WC_SM3_DIGEST_SIZE;
  901. padSz = WC_SM3_BLOCK_SIZE - WC_SM3_PAD_SIZE + 1;
  902. break;
  903. #endif
  904. default:
  905. WOLFSSL_MSG("ERROR: Hmac_UpdateFinal failed, no hmac->macType");
  906. return BAD_FUNC_ARG;
  907. }
  908. msgSz = sz - (1 + in[sz - 1] + macSz);
  909. /* Make negative result 0 */
  910. msgSz &= ~(0 - (msgSz >> 31));
  911. realSz = WOLFSSL_TLS_HMAC_INNER_SZ + msgSz;
  912. maxSz = WOLFSSL_TLS_HMAC_INNER_SZ + (sz - 1) - macSz;
  913. /* Make negative result 0 */
  914. maxSz &= ~(0 - (maxSz >> 31));
  915. /* Calculate #blocks processed in HMAC for max and real data. */
  916. blocks = maxSz >> blockBits;
  917. blocks += ((maxSz + padSz) % blockSz) < padSz;
  918. msgBlocks = realSz >> blockBits;
  919. /* #Extra blocks to process. */
  920. blocks -= msgBlocks + ((((realSz + padSz) % blockSz) < padSz) ? 1 : 0);
  921. /* Calculate whole blocks. */
  922. msgBlocks--;
  923. ret = wc_HmacUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ);
  924. if (ret == 0) {
  925. /* Fill the rest of the block with any available data. */
  926. word32 currSz = ctMaskLT(msgSz, blockSz) & msgSz;
  927. currSz |= ctMaskGTE(msgSz, blockSz) & blockSz;
  928. currSz -= WOLFSSL_TLS_HMAC_INNER_SZ;
  929. currSz &= ~(0 - (currSz >> 31));
  930. ret = wc_HmacUpdate(hmac, in, currSz);
  931. offset = currSz;
  932. }
  933. if (ret == 0) {
  934. /* Do the hash operations on a block basis. */
  935. for (i = 0; i < msgBlocks; i++, offset += blockSz) {
  936. ret = wc_HmacUpdate(hmac, in + offset, blockSz);
  937. if (ret != 0)
  938. break;
  939. }
  940. }
  941. if (ret == 0)
  942. ret = wc_HmacUpdate(hmac, in + offset, msgSz - offset);
  943. if (ret == 0)
  944. ret = wc_HmacFinal(hmac, digest);
  945. if (ret == 0) {
  946. /* Do the dummy hash operations. Do at least one. */
  947. for (i = 0; i < blocks + 1; i++) {
  948. ret = wc_HmacUpdate(hmac, dummy, blockSz);
  949. if (ret != 0)
  950. break;
  951. }
  952. }
  953. return ret;
  954. }
  955. #endif
  956. int TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, int padSz,
  957. int content, int verify, int epochOrder)
  958. {
  959. Hmac hmac;
  960. byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
  961. int ret = 0;
  962. const byte* macSecret = NULL;
  963. word32 hashSz = 0;
  964. if (ssl == NULL)
  965. return BAD_FUNC_ARG;
  966. #ifdef HAVE_TRUNCATED_HMAC
  967. hashSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  968. : ssl->specs.hash_size;
  969. #else
  970. hashSz = ssl->specs.hash_size;
  971. #endif
  972. #ifdef HAVE_FUZZER
  973. /* Fuzz "in" buffer with sz to be used in HMAC algorithm */
  974. if (ssl->fuzzerCb) {
  975. if (verify && padSz >= 0) {
  976. ssl->fuzzerCb(ssl, in, sz + hashSz + padSz + 1, FUZZ_HMAC,
  977. ssl->fuzzerCtx);
  978. }
  979. else {
  980. ssl->fuzzerCb(ssl, in, sz, FUZZ_HMAC, ssl->fuzzerCtx);
  981. }
  982. }
  983. #endif
  984. if (!ssl->options.dtls)
  985. wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, verify);
  986. else
  987. wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, epochOrder);
  988. ret = wc_HmacInit(&hmac, ssl->heap, ssl->devId);
  989. if (ret != 0)
  990. return ret;
  991. #ifdef WOLFSSL_DTLS
  992. if (ssl->options.dtls)
  993. macSecret = wolfSSL_GetDtlsMacSecret(ssl, verify, epochOrder);
  994. else
  995. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  996. #else
  997. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  998. #endif
  999. ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
  1000. macSecret,
  1001. ssl->specs.hash_size);
  1002. if (ret == 0) {
  1003. /* Constant time verification required. */
  1004. if (verify && padSz >= 0) {
  1005. #if !defined(WOLFSSL_NO_HASH_RAW) && !defined(HAVE_FIPS) && \
  1006. !defined(HAVE_SELFTEST)
  1007. #ifdef HAVE_BLAKE2
  1008. if (wolfSSL_GetHmacType(ssl) == WC_HASH_TYPE_BLAKE2B) {
  1009. ret = Hmac_UpdateFinal(&hmac, digest, in,
  1010. sz + hashSz + padSz + 1, myInner);
  1011. }
  1012. else
  1013. #endif
  1014. {
  1015. ret = Hmac_UpdateFinal_CT(&hmac, digest, in,
  1016. sz + hashSz + padSz + 1, hashSz, myInner);
  1017. }
  1018. #else
  1019. ret = Hmac_UpdateFinal(&hmac, digest, in, sz + hashSz + padSz + 1,
  1020. myInner);
  1021. #endif
  1022. }
  1023. else {
  1024. ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
  1025. if (ret == 0)
  1026. ret = wc_HmacUpdate(&hmac, in, sz); /* content */
  1027. if (ret == 0)
  1028. ret = wc_HmacFinal(&hmac, digest);
  1029. }
  1030. }
  1031. wc_HmacFree(&hmac);
  1032. return ret;
  1033. }
  1034. #endif /* WOLFSSL_AEAD_ONLY */
  1035. #endif /* !WOLFSSL_NO_TLS12 */
  1036. int wolfSSL_GetHmacType_ex(CipherSpecs* specs)
  1037. {
  1038. if (specs == NULL)
  1039. return BAD_FUNC_ARG;
  1040. switch (specs->mac_algorithm) {
  1041. #ifndef NO_MD5
  1042. case md5_mac:
  1043. {
  1044. return WC_MD5;
  1045. }
  1046. #endif
  1047. #ifndef NO_SHA256
  1048. case sha256_mac:
  1049. {
  1050. return WC_SHA256;
  1051. }
  1052. #endif
  1053. #ifdef WOLFSSL_SHA384
  1054. case sha384_mac:
  1055. {
  1056. return WC_SHA384;
  1057. }
  1058. #endif
  1059. #ifdef WOLFSSL_SM3
  1060. case sm3_mac:
  1061. {
  1062. return WC_SM3;
  1063. }
  1064. #endif
  1065. #ifndef NO_SHA
  1066. case sha_mac:
  1067. {
  1068. return WC_SHA;
  1069. }
  1070. #endif
  1071. #ifdef HAVE_BLAKE2
  1072. case blake2b_mac:
  1073. {
  1074. return BLAKE2B_ID;
  1075. }
  1076. #endif
  1077. default:
  1078. {
  1079. return WOLFSSL_FATAL_ERROR;
  1080. }
  1081. }
  1082. }
  1083. #ifdef HAVE_TLS_EXTENSIONS
  1084. /**
  1085. * The TLSX semaphore is used to calculate the size of the extensions to be sent
  1086. * from one peer to another.
  1087. */
  1088. /** Supports up to 72 flags. Increase as needed. */
  1089. #define SEMAPHORE_SIZE 9
  1090. /**
  1091. * Converts the extension type (id) to an index in the semaphore.
  1092. *
  1093. * Official reference for TLS extension types:
  1094. * http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xml
  1095. *
  1096. * Motivation:
  1097. * Previously, we used the extension type itself as the index of that
  1098. * extension in the semaphore as the extension types were declared
  1099. * sequentially, but maintain a semaphore as big as the number of available
  1100. * extensions is no longer an option since the release of renegotiation_info.
  1101. *
  1102. * How to update:
  1103. * Assign extension types that extrapolate the number of available semaphores
  1104. * to the first available index going backwards in the semaphore array.
  1105. * When adding a new extension type that don't extrapolate the number of
  1106. * available semaphores, check for a possible collision with with a
  1107. * 'remapped' extension type.
  1108. *
  1109. * Update TLSX_Parse for duplicate detection if more added above 62.
  1110. */
  1111. static WC_INLINE word16 TLSX_ToSemaphore(word16 type)
  1112. {
  1113. switch (type) {
  1114. case TLSX_RENEGOTIATION_INFO: /* 0xFF01 */
  1115. return 63;
  1116. #ifdef WOLFSSL_QUIC
  1117. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT: /* 0xffa5 */
  1118. return 64;
  1119. #endif
  1120. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1121. case TLSX_ECH: /* 0xfe0d */
  1122. return 65;
  1123. #endif
  1124. #ifdef WOLFSSL_DUAL_ALG_CERTS
  1125. case TLSX_CKS:
  1126. return 66;
  1127. #endif
  1128. default:
  1129. if (type > 62) {
  1130. /* This message SHOULD only happens during the adding of
  1131. new TLS extensions in which its IANA number overflows
  1132. the current semaphore's range, or if its number already
  1133. is assigned to be used by another extension.
  1134. Use this check value for the new extension and decrement
  1135. the check value by one. */
  1136. WOLFSSL_MSG("### TLSX semaphore collision or overflow detected!");
  1137. }
  1138. }
  1139. return type;
  1140. }
  1141. /** Checks if a specific light (tls extension) is not set in the semaphore. */
  1142. #define IS_OFF(semaphore, light) \
  1143. (!(((semaphore)[(light) / 8] & (byte) (0x01 << ((light) % 8)))))
  1144. /** Turn on a specific light (tls extension) in the semaphore. */
  1145. /* the semaphore marks the extensions already written to the message */
  1146. #define TURN_ON(semaphore, light) \
  1147. ((semaphore)[(light) / 8] |= (byte) (0x01 << ((light) % 8)))
  1148. /** Turn off a specific light (tls extension) in the semaphore. */
  1149. #define TURN_OFF(semaphore, light) \
  1150. ((semaphore)[(light) / 8] &= (byte) ~(0x01 << ((light) % 8)))
  1151. /** Creates a new extension. */
  1152. static TLSX* TLSX_New(TLSX_Type type, const void* data, void* heap)
  1153. {
  1154. TLSX* extension = (TLSX*)XMALLOC(sizeof(TLSX), heap, DYNAMIC_TYPE_TLSX);
  1155. (void)heap;
  1156. if (extension) {
  1157. extension->type = type;
  1158. extension->data = (void*)data;
  1159. extension->resp = 0;
  1160. extension->next = NULL;
  1161. }
  1162. return extension;
  1163. }
  1164. /**
  1165. * Creates a new extension and appends it to the provided list.
  1166. * Checks for duplicate extensions, keeps the newest.
  1167. */
  1168. int TLSX_Append(TLSX** list, TLSX_Type type, const void* data, void* heap)
  1169. {
  1170. TLSX* extension = TLSX_New(type, data, heap);
  1171. TLSX* cur;
  1172. TLSX** prevNext = list;
  1173. if (extension == NULL)
  1174. return MEMORY_E;
  1175. for (cur = *list; cur != NULL;) {
  1176. if (cur->type == type) {
  1177. *prevNext = cur->next;
  1178. cur->next = NULL;
  1179. TLSX_FreeAll(cur, heap);
  1180. cur = *prevNext;
  1181. }
  1182. else {
  1183. prevNext = &cur->next;
  1184. cur = cur->next;
  1185. }
  1186. }
  1187. /* Append the extension to the list */
  1188. *prevNext = extension;
  1189. return 0;
  1190. }
  1191. /**
  1192. * Creates a new extension and pushes it to the provided list.
  1193. * Checks for duplicate extensions, keeps the newest.
  1194. */
  1195. int TLSX_Push(TLSX** list, TLSX_Type type, const void* data, void* heap)
  1196. {
  1197. TLSX* extension = TLSX_New(type, data, heap);
  1198. if (extension == NULL)
  1199. return MEMORY_E;
  1200. /* pushes the new extension on the list. */
  1201. extension->next = *list;
  1202. *list = extension;
  1203. /* remove duplicate extensions, there should be only one of each type. */
  1204. do {
  1205. if (extension->next && extension->next->type == type) {
  1206. TLSX *next = extension->next;
  1207. extension->next = next->next;
  1208. next->next = NULL;
  1209. TLSX_FreeAll(next, heap);
  1210. /* there is no way to occur more than
  1211. * two extensions of the same type.
  1212. */
  1213. break;
  1214. }
  1215. } while ((extension = extension->next));
  1216. return 0;
  1217. }
  1218. #ifndef NO_WOLFSSL_CLIENT
  1219. int TLSX_CheckUnsupportedExtension(WOLFSSL* ssl, TLSX_Type type);
  1220. int TLSX_CheckUnsupportedExtension(WOLFSSL* ssl, TLSX_Type type)
  1221. {
  1222. TLSX *extension = TLSX_Find(ssl->extensions, type);
  1223. if (!extension)
  1224. extension = TLSX_Find(ssl->ctx->extensions, type);
  1225. return extension == NULL;
  1226. }
  1227. int TLSX_HandleUnsupportedExtension(WOLFSSL* ssl);
  1228. int TLSX_HandleUnsupportedExtension(WOLFSSL* ssl)
  1229. {
  1230. SendAlert(ssl, alert_fatal, unsupported_extension);
  1231. WOLFSSL_ERROR_VERBOSE(UNSUPPORTED_EXTENSION);
  1232. return UNSUPPORTED_EXTENSION;
  1233. }
  1234. #else
  1235. #define TLSX_CheckUnsupportedExtension(ssl, type) 0
  1236. #define TLSX_HandleUnsupportedExtension(ssl) 0
  1237. #endif
  1238. #if !defined(NO_WOLFSSL_SERVER) || defined(WOLFSSL_TLS13)
  1239. void TLSX_SetResponse(WOLFSSL* ssl, TLSX_Type type);
  1240. /** Mark an extension to be sent back to the client. */
  1241. void TLSX_SetResponse(WOLFSSL* ssl, TLSX_Type type)
  1242. {
  1243. TLSX *extension = TLSX_Find(ssl->extensions, type);
  1244. if (extension)
  1245. extension->resp = 1;
  1246. }
  1247. #endif
  1248. /******************************************************************************/
  1249. /* Application-Layer Protocol Negotiation */
  1250. /******************************************************************************/
  1251. #ifdef HAVE_ALPN
  1252. /** Creates a new ALPN object, providing protocol name to use. */
  1253. static ALPN* TLSX_ALPN_New(char *protocol_name, word16 protocol_nameSz,
  1254. void* heap)
  1255. {
  1256. ALPN *alpn;
  1257. WOLFSSL_ENTER("TLSX_ALPN_New");
  1258. if (protocol_name == NULL ||
  1259. protocol_nameSz > WOLFSSL_MAX_ALPN_PROTO_NAME_LEN) {
  1260. WOLFSSL_MSG("Invalid arguments");
  1261. return NULL;
  1262. }
  1263. alpn = (ALPN*)XMALLOC(sizeof(ALPN), heap, DYNAMIC_TYPE_TLSX);
  1264. if (alpn == NULL) {
  1265. WOLFSSL_MSG("Memory failure");
  1266. return NULL;
  1267. }
  1268. alpn->next = NULL;
  1269. alpn->negotiated = 0;
  1270. alpn->options = 0;
  1271. alpn->protocol_name = (char*)XMALLOC(protocol_nameSz + 1,
  1272. heap, DYNAMIC_TYPE_TLSX);
  1273. if (alpn->protocol_name == NULL) {
  1274. WOLFSSL_MSG("Memory failure");
  1275. XFREE(alpn, heap, DYNAMIC_TYPE_TLSX);
  1276. return NULL;
  1277. }
  1278. XMEMCPY(alpn->protocol_name, protocol_name, protocol_nameSz);
  1279. alpn->protocol_name[protocol_nameSz] = 0;
  1280. (void)heap;
  1281. return alpn;
  1282. }
  1283. /** Releases an ALPN object. */
  1284. static void TLSX_ALPN_Free(ALPN *alpn, void* heap)
  1285. {
  1286. (void)heap;
  1287. if (alpn == NULL)
  1288. return;
  1289. XFREE(alpn->protocol_name, heap, DYNAMIC_TYPE_TLSX);
  1290. XFREE(alpn, heap, DYNAMIC_TYPE_TLSX);
  1291. }
  1292. /** Releases all ALPN objects in the provided list. */
  1293. static void TLSX_ALPN_FreeAll(ALPN *list, void* heap)
  1294. {
  1295. ALPN* alpn;
  1296. while ((alpn = list)) {
  1297. list = alpn->next;
  1298. TLSX_ALPN_Free(alpn, heap);
  1299. }
  1300. }
  1301. /** Tells the buffered size of the ALPN objects in a list. */
  1302. static word16 TLSX_ALPN_GetSize(ALPN *list)
  1303. {
  1304. ALPN* alpn;
  1305. word16 length = OPAQUE16_LEN; /* list length */
  1306. while ((alpn = list)) {
  1307. list = alpn->next;
  1308. length++; /* protocol name length is on one byte */
  1309. length += (word16)XSTRLEN(alpn->protocol_name);
  1310. }
  1311. return length;
  1312. }
  1313. /** Writes the ALPN objects of a list in a buffer. */
  1314. static word16 TLSX_ALPN_Write(ALPN *list, byte *output)
  1315. {
  1316. ALPN* alpn;
  1317. word16 length = 0;
  1318. word16 offset = OPAQUE16_LEN; /* list length offset */
  1319. while ((alpn = list)) {
  1320. list = alpn->next;
  1321. length = (word16)XSTRLEN(alpn->protocol_name);
  1322. /* protocol name length */
  1323. output[offset++] = (byte)length;
  1324. /* protocol name value */
  1325. XMEMCPY(output + offset, alpn->protocol_name, length);
  1326. offset += length;
  1327. }
  1328. /* writing list length */
  1329. c16toa(offset - OPAQUE16_LEN, output);
  1330. return offset;
  1331. }
  1332. /** Finds a protocol name in the provided ALPN list */
  1333. static ALPN* TLSX_ALPN_Find(ALPN *list, char *protocol_name, word16 size)
  1334. {
  1335. ALPN *alpn;
  1336. if (list == NULL || protocol_name == NULL)
  1337. return NULL;
  1338. alpn = list;
  1339. while (alpn != NULL && (
  1340. (word16)XSTRLEN(alpn->protocol_name) != size ||
  1341. XSTRNCMP(alpn->protocol_name, protocol_name, size)))
  1342. alpn = alpn->next;
  1343. return alpn;
  1344. }
  1345. /** Set the ALPN matching client and server requirements */
  1346. static int TLSX_SetALPN(TLSX** extensions, const void* data, word16 size,
  1347. void* heap)
  1348. {
  1349. ALPN *alpn;
  1350. int ret;
  1351. if (extensions == NULL || data == NULL)
  1352. return BAD_FUNC_ARG;
  1353. alpn = TLSX_ALPN_New((char *)data, size, heap);
  1354. if (alpn == NULL) {
  1355. WOLFSSL_MSG("Memory failure");
  1356. return MEMORY_E;
  1357. }
  1358. alpn->negotiated = 1;
  1359. ret = TLSX_Push(extensions, TLSX_APPLICATION_LAYER_PROTOCOL, (void*)alpn,
  1360. heap);
  1361. if (ret != 0) {
  1362. TLSX_ALPN_Free(alpn, heap);
  1363. return ret;
  1364. }
  1365. return WOLFSSL_SUCCESS;
  1366. }
  1367. static int ALPN_find_match(WOLFSSL *ssl, TLSX **pextension,
  1368. const byte **psel, byte *psel_len,
  1369. const byte *alpn_val, word16 alpn_val_len)
  1370. {
  1371. TLSX *extension;
  1372. ALPN *alpn, *list;
  1373. const byte *sel = NULL, *s;
  1374. byte sel_len = 0, wlen;
  1375. extension = TLSX_Find(ssl->extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1376. if (extension == NULL)
  1377. extension = TLSX_Find(ssl->ctx->extensions,
  1378. TLSX_APPLICATION_LAYER_PROTOCOL);
  1379. /* No ALPN configured here */
  1380. if (extension == NULL || extension->data == NULL) {
  1381. *pextension = NULL;
  1382. *psel = NULL;
  1383. *psel_len = 0;
  1384. return 0;
  1385. }
  1386. list = (ALPN*)extension->data;
  1387. for (s = alpn_val;
  1388. (s - alpn_val) < alpn_val_len;
  1389. s += wlen) {
  1390. wlen = *s++; /* bounds already checked on save */
  1391. alpn = TLSX_ALPN_Find(list, (char*)s, wlen);
  1392. if (alpn != NULL) {
  1393. WOLFSSL_MSG("ALPN protocol match");
  1394. sel = s,
  1395. sel_len = wlen;
  1396. break;
  1397. }
  1398. }
  1399. if (sel == NULL) {
  1400. WOLFSSL_MSG("No ALPN protocol match");
  1401. /* do nothing if no protocol match between client and server and option
  1402. is set to continue (like OpenSSL) */
  1403. if (list->options & WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) {
  1404. WOLFSSL_MSG("Continue on mismatch");
  1405. }
  1406. else {
  1407. SendAlert(ssl, alert_fatal, no_application_protocol);
  1408. WOLFSSL_ERROR_VERBOSE(UNKNOWN_ALPN_PROTOCOL_NAME_E);
  1409. return UNKNOWN_ALPN_PROTOCOL_NAME_E;
  1410. }
  1411. }
  1412. *pextension = extension;
  1413. *psel = sel;
  1414. *psel_len = sel_len;
  1415. return 0;
  1416. }
  1417. int ALPN_Select(WOLFSSL *ssl)
  1418. {
  1419. TLSX *extension;
  1420. const byte *sel = NULL;
  1421. byte sel_len = 0;
  1422. int r = 0;
  1423. WOLFSSL_ENTER("ALPN_Select");
  1424. if (ssl->alpn_peer_requested == NULL)
  1425. return 0;
  1426. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  1427. if (ssl->alpnSelect != NULL && ssl->options.side == WOLFSSL_SERVER_END) {
  1428. r = ssl->alpnSelect(ssl, &sel, &sel_len, ssl->alpn_peer_requested,
  1429. ssl->alpn_peer_requested_length, ssl->alpnSelectArg);
  1430. switch (r) {
  1431. case SSL_TLSEXT_ERR_OK:
  1432. WOLFSSL_MSG("ALPN protocol match");
  1433. break;
  1434. case SSL_TLSEXT_ERR_NOACK:
  1435. WOLFSSL_MSG("ALPN cb no match but not fatal");
  1436. sel = NULL;
  1437. sel_len = 0;
  1438. break;
  1439. case SSL_TLSEXT_ERR_ALERT_FATAL:
  1440. default:
  1441. WOLFSSL_MSG("ALPN cb no match and fatal");
  1442. SendAlert(ssl, alert_fatal, no_application_protocol);
  1443. WOLFSSL_ERROR_VERBOSE(UNKNOWN_ALPN_PROTOCOL_NAME_E);
  1444. return UNKNOWN_ALPN_PROTOCOL_NAME_E;
  1445. }
  1446. }
  1447. else
  1448. #endif
  1449. {
  1450. r = ALPN_find_match(ssl, &extension, &sel, &sel_len,
  1451. ssl->alpn_peer_requested,
  1452. ssl->alpn_peer_requested_length);
  1453. if (r != 0)
  1454. return r;
  1455. }
  1456. if (sel != NULL) {
  1457. /* set the matching negotiated protocol */
  1458. r = TLSX_SetALPN(&ssl->extensions, sel, sel_len, ssl->heap);
  1459. if (r != WOLFSSL_SUCCESS) {
  1460. WOLFSSL_MSG("TLSX_SetALPN failed");
  1461. return BUFFER_ERROR;
  1462. }
  1463. /* reply to ALPN extension sent from peer */
  1464. #ifndef NO_WOLFSSL_SERVER
  1465. TLSX_SetResponse(ssl, TLSX_APPLICATION_LAYER_PROTOCOL);
  1466. #endif
  1467. }
  1468. return 0;
  1469. }
  1470. /** Parses a buffer of ALPN extensions and set the first one matching
  1471. * client and server requirements */
  1472. static int TLSX_ALPN_ParseAndSet(WOLFSSL *ssl, const byte *input, word16 length,
  1473. byte isRequest)
  1474. {
  1475. word16 size = 0, offset = 0, wlen;
  1476. int r = BUFFER_ERROR;
  1477. const byte *s;
  1478. if (OPAQUE16_LEN > length)
  1479. return BUFFER_ERROR;
  1480. ato16(input, &size);
  1481. offset += OPAQUE16_LEN;
  1482. /* validating alpn list length */
  1483. if (size == 0 || length != OPAQUE16_LEN + size)
  1484. return BUFFER_ERROR;
  1485. /* validating length of entries before accepting */
  1486. for (s = input + offset; (s - input) < size; s += wlen) {
  1487. wlen = *s++;
  1488. if (wlen == 0 || (s + wlen - input) > length)
  1489. return BUFFER_ERROR;
  1490. }
  1491. if (isRequest) {
  1492. /* keep the list sent by peer, if this is from a request. We
  1493. * use it later in ALPN_Select() for evaluation. */
  1494. if (ssl->alpn_peer_requested != NULL) {
  1495. XFREE(ssl->alpn_peer_requested, ssl->heap, DYNAMIC_TYPE_ALPN);
  1496. ssl->alpn_peer_requested_length = 0;
  1497. }
  1498. ssl->alpn_peer_requested = (byte *)XMALLOC(size, ssl->heap,
  1499. DYNAMIC_TYPE_ALPN);
  1500. if (ssl->alpn_peer_requested == NULL) {
  1501. return MEMORY_ERROR;
  1502. }
  1503. ssl->alpn_peer_requested_length = size;
  1504. XMEMCPY(ssl->alpn_peer_requested, (char*)input + offset, size);
  1505. }
  1506. else {
  1507. /* a response, we should find the value in our config */
  1508. const byte *sel = NULL;
  1509. byte sel_len = 0;
  1510. TLSX *extension = NULL;
  1511. r = ALPN_find_match(ssl, &extension, &sel, &sel_len, input + offset, size);
  1512. if (r != 0)
  1513. return r;
  1514. if (sel != NULL) {
  1515. /* set the matching negotiated protocol */
  1516. r = TLSX_SetALPN(&ssl->extensions, sel, sel_len, ssl->heap);
  1517. if (r != WOLFSSL_SUCCESS) {
  1518. WOLFSSL_MSG("TLSX_SetALPN failed");
  1519. return BUFFER_ERROR;
  1520. }
  1521. }
  1522. /* If we had nothing configured, the response is unexpected */
  1523. else if (extension == NULL) {
  1524. r = TLSX_HandleUnsupportedExtension(ssl);
  1525. if (r != 0)
  1526. return r;
  1527. }
  1528. }
  1529. return 0;
  1530. }
  1531. /** Add a protocol name to the list of accepted usable ones */
  1532. int TLSX_UseALPN(TLSX** extensions, const void* data, word16 size, byte options,
  1533. void* heap)
  1534. {
  1535. ALPN *alpn;
  1536. TLSX *extension;
  1537. int ret;
  1538. if (extensions == NULL || data == NULL)
  1539. return BAD_FUNC_ARG;
  1540. alpn = TLSX_ALPN_New((char *)data, size, heap);
  1541. if (alpn == NULL) {
  1542. WOLFSSL_MSG("Memory failure");
  1543. return MEMORY_E;
  1544. }
  1545. /* Set Options of ALPN */
  1546. alpn->options = options;
  1547. extension = TLSX_Find(*extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1548. if (extension == NULL) {
  1549. ret = TLSX_Push(extensions, TLSX_APPLICATION_LAYER_PROTOCOL,
  1550. (void*)alpn, heap);
  1551. if (ret != 0) {
  1552. TLSX_ALPN_Free(alpn, heap);
  1553. return ret;
  1554. }
  1555. }
  1556. else {
  1557. /* push new ALPN object to extension data. */
  1558. alpn->next = (ALPN*)extension->data;
  1559. extension->data = (void*)alpn;
  1560. }
  1561. return WOLFSSL_SUCCESS;
  1562. }
  1563. /** Get the protocol name set by the server */
  1564. int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz)
  1565. {
  1566. TLSX *extension;
  1567. ALPN *alpn;
  1568. if (extensions == NULL || data == NULL || dataSz == NULL)
  1569. return BAD_FUNC_ARG;
  1570. *data = NULL;
  1571. *dataSz = 0;
  1572. extension = TLSX_Find(extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1573. if (extension == NULL) {
  1574. WOLFSSL_MSG("TLS extension not found");
  1575. WOLFSSL_ERROR_VERBOSE(WOLFSSL_ALPN_NOT_FOUND);
  1576. return WOLFSSL_ALPN_NOT_FOUND;
  1577. }
  1578. alpn = (ALPN *)extension->data;
  1579. if (alpn == NULL) {
  1580. WOLFSSL_MSG("ALPN extension not found");
  1581. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1582. return WOLFSSL_FATAL_ERROR;
  1583. }
  1584. if (alpn->negotiated != 1) {
  1585. /* consider as an error */
  1586. if (alpn->options & WOLFSSL_ALPN_FAILED_ON_MISMATCH) {
  1587. WOLFSSL_MSG("No protocol match with peer -> Failed");
  1588. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1589. return WOLFSSL_FATAL_ERROR;
  1590. }
  1591. /* continue without negotiated protocol */
  1592. WOLFSSL_MSG("No protocol match with peer -> Continue");
  1593. WOLFSSL_ERROR_VERBOSE(WOLFSSL_ALPN_NOT_FOUND);
  1594. return WOLFSSL_ALPN_NOT_FOUND;
  1595. }
  1596. if (alpn->next != NULL) {
  1597. WOLFSSL_MSG("Only one protocol name must be accepted");
  1598. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1599. return WOLFSSL_FATAL_ERROR;
  1600. }
  1601. *data = alpn->protocol_name;
  1602. *dataSz = (word16)XSTRLEN((char*)*data);
  1603. return WOLFSSL_SUCCESS;
  1604. }
  1605. #define ALPN_FREE_ALL TLSX_ALPN_FreeAll
  1606. #define ALPN_GET_SIZE TLSX_ALPN_GetSize
  1607. #define ALPN_WRITE TLSX_ALPN_Write
  1608. #define ALPN_PARSE TLSX_ALPN_ParseAndSet
  1609. #else /* HAVE_ALPN */
  1610. #define ALPN_FREE_ALL(list, heap) WC_DO_NOTHING
  1611. #define ALPN_GET_SIZE(list) 0
  1612. #define ALPN_WRITE(a, b) 0
  1613. #define ALPN_PARSE(a, b, c, d) 0
  1614. #endif /* HAVE_ALPN */
  1615. /******************************************************************************/
  1616. /* Server Name Indication */
  1617. /******************************************************************************/
  1618. #ifdef HAVE_SNI
  1619. /** Creates a new SNI object. */
  1620. static SNI* TLSX_SNI_New(byte type, const void* data, word16 size, void* heap)
  1621. {
  1622. SNI* sni = (SNI*)XMALLOC(sizeof(SNI), heap, DYNAMIC_TYPE_TLSX);
  1623. (void)heap;
  1624. if (sni) {
  1625. sni->type = type;
  1626. sni->next = NULL;
  1627. #ifndef NO_WOLFSSL_SERVER
  1628. sni->options = 0;
  1629. sni->status = WOLFSSL_SNI_NO_MATCH;
  1630. #endif
  1631. switch (sni->type) {
  1632. case WOLFSSL_SNI_HOST_NAME:
  1633. sni->data.host_name = (char*)XMALLOC(size + 1, heap,
  1634. DYNAMIC_TYPE_TLSX);
  1635. if (sni->data.host_name) {
  1636. XSTRNCPY(sni->data.host_name, (const char*)data, size);
  1637. sni->data.host_name[size] = '\0';
  1638. } else {
  1639. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1640. sni = NULL;
  1641. }
  1642. break;
  1643. default: /* invalid type */
  1644. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1645. sni = NULL;
  1646. }
  1647. }
  1648. return sni;
  1649. }
  1650. /** Releases a SNI object. */
  1651. static void TLSX_SNI_Free(SNI* sni, void* heap)
  1652. {
  1653. if (sni) {
  1654. switch (sni->type) {
  1655. case WOLFSSL_SNI_HOST_NAME:
  1656. XFREE(sni->data.host_name, heap, DYNAMIC_TYPE_TLSX);
  1657. break;
  1658. }
  1659. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1660. }
  1661. (void)heap;
  1662. }
  1663. /** Releases all SNI objects in the provided list. */
  1664. static void TLSX_SNI_FreeAll(SNI* list, void* heap)
  1665. {
  1666. SNI* sni;
  1667. while ((sni = list)) {
  1668. list = sni->next;
  1669. TLSX_SNI_Free(sni, heap);
  1670. }
  1671. }
  1672. /** Tells the buffered size of the SNI objects in a list. */
  1673. static word16 TLSX_SNI_GetSize(SNI* list)
  1674. {
  1675. SNI* sni;
  1676. word16 length = OPAQUE16_LEN; /* list length */
  1677. while ((sni = list)) {
  1678. list = sni->next;
  1679. length += ENUM_LEN + OPAQUE16_LEN; /* sni type + sni length */
  1680. switch (sni->type) {
  1681. case WOLFSSL_SNI_HOST_NAME:
  1682. length += (word16)XSTRLEN((char*)sni->data.host_name);
  1683. break;
  1684. }
  1685. }
  1686. return length;
  1687. }
  1688. /** Writes the SNI objects of a list in a buffer. */
  1689. static word16 TLSX_SNI_Write(SNI* list, byte* output)
  1690. {
  1691. SNI* sni;
  1692. word16 length = 0;
  1693. word16 offset = OPAQUE16_LEN; /* list length offset */
  1694. while ((sni = list)) {
  1695. list = sni->next;
  1696. output[offset++] = sni->type; /* sni type */
  1697. switch (sni->type) {
  1698. case WOLFSSL_SNI_HOST_NAME:
  1699. length = (word16)XSTRLEN((char*)sni->data.host_name);
  1700. c16toa(length, output + offset); /* sni length */
  1701. offset += OPAQUE16_LEN;
  1702. XMEMCPY(output + offset, sni->data.host_name, length);
  1703. offset += length;
  1704. break;
  1705. }
  1706. }
  1707. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  1708. return offset;
  1709. }
  1710. /** Finds a SNI object in the provided list. */
  1711. static SNI* TLSX_SNI_Find(SNI *list, byte type)
  1712. {
  1713. SNI* sni = list;
  1714. while (sni && sni->type != type)
  1715. sni = sni->next;
  1716. return sni;
  1717. }
  1718. #if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
  1719. /** Sets the status of a SNI object. */
  1720. static void TLSX_SNI_SetStatus(TLSX* extensions, byte type, byte status)
  1721. {
  1722. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1723. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1724. if (sni)
  1725. sni->status = status;
  1726. }
  1727. #endif
  1728. /** Gets the status of a SNI object. */
  1729. byte TLSX_SNI_Status(TLSX* extensions, byte type)
  1730. {
  1731. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1732. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1733. if (sni)
  1734. return sni->status;
  1735. return 0;
  1736. }
  1737. /** Parses a buffer of SNI extensions. */
  1738. static int TLSX_SNI_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  1739. byte isRequest)
  1740. {
  1741. #ifndef NO_WOLFSSL_SERVER
  1742. word16 size = 0;
  1743. word16 offset = 0;
  1744. int cacheOnly = 0;
  1745. SNI *sni = NULL;
  1746. byte type;
  1747. byte matched;
  1748. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1749. WOLFSSL_ECH* ech = NULL;
  1750. WOLFSSL_EchConfig* workingConfig;
  1751. TLSX* echX;
  1752. #endif
  1753. #endif /* !NO_WOLFSSL_SERVER */
  1754. TLSX *extension = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  1755. if (!extension)
  1756. extension = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  1757. if (!isRequest) {
  1758. #ifndef NO_WOLFSSL_CLIENT
  1759. if (!extension || !extension->data)
  1760. return TLSX_HandleUnsupportedExtension(ssl);
  1761. if (length > 0)
  1762. return BUFFER_ERROR; /* SNI response MUST be empty. */
  1763. /* This call enables wolfSSL_SNI_GetRequest() to be called in the
  1764. * client side to fetch the used SNI. It will only work if the SNI
  1765. * was set at the SSL object level. Right now we only support one
  1766. * name type, WOLFSSL_SNI_HOST_NAME, but in the future, the
  1767. * inclusion of other name types will turn this method inaccurate,
  1768. * as the extension response doesn't contains information of which
  1769. * name was accepted.
  1770. */
  1771. TLSX_SNI_SetStatus(ssl->extensions, WOLFSSL_SNI_HOST_NAME,
  1772. WOLFSSL_SNI_REAL_MATCH);
  1773. return 0;
  1774. #endif
  1775. }
  1776. #ifndef NO_WOLFSSL_SERVER
  1777. if (!extension || !extension->data) {
  1778. /* This will keep SNI even though TLSX_UseSNI has not been called.
  1779. * Enable it so that the received sni is available to functions
  1780. * that use a custom callback when SNI is received.
  1781. */
  1782. #ifdef WOLFSSL_ALWAYS_KEEP_SNI
  1783. cacheOnly = 1;
  1784. #endif
  1785. if (ssl->ctx->sniRecvCb) {
  1786. cacheOnly = 1;
  1787. }
  1788. if (cacheOnly) {
  1789. WOLFSSL_MSG("Forcing SSL object to store SNI parameter");
  1790. }
  1791. else {
  1792. /* Skipping, SNI not enabled at server side. */
  1793. return 0;
  1794. }
  1795. }
  1796. if (OPAQUE16_LEN > length)
  1797. return BUFFER_ERROR;
  1798. ato16(input, &size);
  1799. offset += OPAQUE16_LEN;
  1800. /* validating sni list length */
  1801. if (length != OPAQUE16_LEN + size || size == 0)
  1802. return BUFFER_ERROR;
  1803. /* SNI was badly specified and only one type is now recognized and allowed.
  1804. * Only one SNI value per type (RFC6066), so, no loop. */
  1805. type = input[offset++];
  1806. if (type != WOLFSSL_SNI_HOST_NAME)
  1807. return BUFFER_ERROR;
  1808. if (offset + OPAQUE16_LEN > length)
  1809. return BUFFER_ERROR;
  1810. ato16(input + offset, &size);
  1811. offset += OPAQUE16_LEN;
  1812. if (offset + size != length || size == 0)
  1813. return BUFFER_ERROR;
  1814. if (!cacheOnly && !(sni = TLSX_SNI_Find((SNI*)extension->data, type)))
  1815. return 0; /* not using this type of SNI. */
  1816. #ifdef WOLFSSL_TLS13
  1817. /* Don't process the second ClientHello SNI extension if there
  1818. * was problems with the first.
  1819. */
  1820. if (!cacheOnly && sni->status != 0)
  1821. return 0;
  1822. #endif
  1823. matched = cacheOnly || (XSTRLEN(sni->data.host_name) == size &&
  1824. XSTRNCMP(sni->data.host_name, (const char*)input + offset, size) == 0);
  1825. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1826. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  1827. if (echX != NULL)
  1828. ech = (WOLFSSL_ECH*)(echX->data);
  1829. if (!matched && ech != NULL) {
  1830. workingConfig = ech->echConfig;
  1831. while (workingConfig != NULL) {
  1832. matched = XSTRLEN(workingConfig->publicName) == size &&
  1833. XSTRNCMP(workingConfig->publicName,
  1834. (const char*)input + offset, size) == 0;
  1835. if (matched)
  1836. break;
  1837. workingConfig = workingConfig->next;
  1838. }
  1839. }
  1840. #endif
  1841. if (matched || sni->options & WOLFSSL_SNI_ANSWER_ON_MISMATCH) {
  1842. int matchStat;
  1843. int r = TLSX_UseSNI(&ssl->extensions, type, input + offset, size,
  1844. ssl->heap);
  1845. if (r != WOLFSSL_SUCCESS)
  1846. return r; /* throws error. */
  1847. if (cacheOnly) {
  1848. WOLFSSL_MSG("Forcing storage of SNI, Fake match");
  1849. matchStat = WOLFSSL_SNI_FORCE_KEEP;
  1850. }
  1851. else if (matched) {
  1852. WOLFSSL_MSG("SNI did match!");
  1853. matchStat = WOLFSSL_SNI_REAL_MATCH;
  1854. }
  1855. else {
  1856. WOLFSSL_MSG("fake SNI match from ANSWER_ON_MISMATCH");
  1857. matchStat = WOLFSSL_SNI_FAKE_MATCH;
  1858. }
  1859. TLSX_SNI_SetStatus(ssl->extensions, type, (byte)matchStat);
  1860. if (!cacheOnly)
  1861. TLSX_SetResponse(ssl, TLSX_SERVER_NAME);
  1862. }
  1863. else if (!(sni->options & WOLFSSL_SNI_CONTINUE_ON_MISMATCH)) {
  1864. SendAlert(ssl, alert_fatal, unrecognized_name);
  1865. WOLFSSL_ERROR_VERBOSE(UNKNOWN_SNI_HOST_NAME_E);
  1866. return UNKNOWN_SNI_HOST_NAME_E;
  1867. }
  1868. #else
  1869. (void)input;
  1870. #endif /* !NO_WOLFSSL_SERVER */
  1871. #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER)
  1872. (void)length;
  1873. #endif
  1874. return 0;
  1875. }
  1876. static int TLSX_SNI_VerifyParse(WOLFSSL* ssl, byte isRequest)
  1877. {
  1878. (void)ssl;
  1879. if (isRequest) {
  1880. #ifndef NO_WOLFSSL_SERVER
  1881. TLSX* ctx_ext = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  1882. TLSX* ssl_ext = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  1883. SNI* ctx_sni = ctx_ext ? (SNI*)ctx_ext->data : NULL;
  1884. SNI* ssl_sni = ssl_ext ? (SNI*)ssl_ext->data : NULL;
  1885. SNI* sni = NULL;
  1886. for (; ctx_sni; ctx_sni = ctx_sni->next) {
  1887. if (ctx_sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) {
  1888. sni = TLSX_SNI_Find(ssl_sni, ctx_sni->type);
  1889. if (sni) {
  1890. if (sni->status != WOLFSSL_SNI_NO_MATCH)
  1891. continue;
  1892. /* if ssl level overrides ctx level, it is ok. */
  1893. if ((sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) == 0)
  1894. continue;
  1895. }
  1896. SendAlert(ssl, alert_fatal, handshake_failure);
  1897. WOLFSSL_ERROR_VERBOSE(SNI_ABSENT_ERROR);
  1898. return SNI_ABSENT_ERROR;
  1899. }
  1900. }
  1901. for (; ssl_sni; ssl_sni = ssl_sni->next) {
  1902. if (ssl_sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) {
  1903. if (ssl_sni->status != WOLFSSL_SNI_NO_MATCH)
  1904. continue;
  1905. SendAlert(ssl, alert_fatal, handshake_failure);
  1906. WOLFSSL_ERROR_VERBOSE(SNI_ABSENT_ERROR);
  1907. return SNI_ABSENT_ERROR;
  1908. }
  1909. }
  1910. #endif /* NO_WOLFSSL_SERVER */
  1911. }
  1912. return 0;
  1913. }
  1914. int TLSX_UseSNI(TLSX** extensions, byte type, const void* data, word16 size,
  1915. void* heap)
  1916. {
  1917. TLSX* extension;
  1918. SNI* sni = NULL;
  1919. if (extensions == NULL || data == NULL)
  1920. return BAD_FUNC_ARG;
  1921. if ((sni = TLSX_SNI_New(type, data, size, heap)) == NULL)
  1922. return MEMORY_E;
  1923. extension = TLSX_Find(*extensions, TLSX_SERVER_NAME);
  1924. if (!extension) {
  1925. int ret = TLSX_Push(extensions, TLSX_SERVER_NAME, (void*)sni, heap);
  1926. if (ret != 0) {
  1927. TLSX_SNI_Free(sni, heap);
  1928. return ret;
  1929. }
  1930. }
  1931. else {
  1932. /* push new SNI object to extension data. */
  1933. sni->next = (SNI*)extension->data;
  1934. extension->data = (void*)sni;
  1935. /* remove duplicate SNI, there should be only one of each type. */
  1936. do {
  1937. if (sni->next && sni->next->type == type) {
  1938. SNI* next = sni->next;
  1939. sni->next = next->next;
  1940. TLSX_SNI_Free(next, heap);
  1941. /* there is no way to occur more than
  1942. * two SNIs of the same type.
  1943. */
  1944. break;
  1945. }
  1946. } while ((sni = sni->next));
  1947. }
  1948. return WOLFSSL_SUCCESS;
  1949. }
  1950. #ifndef NO_WOLFSSL_SERVER
  1951. /** Tells the SNI requested by the client. */
  1952. word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type, void** data)
  1953. {
  1954. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1955. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1956. if (sni && sni->status != WOLFSSL_SNI_NO_MATCH) {
  1957. switch (sni->type) {
  1958. case WOLFSSL_SNI_HOST_NAME:
  1959. if (data) {
  1960. *data = sni->data.host_name;
  1961. return (word16)XSTRLEN((char*)*data);
  1962. }
  1963. }
  1964. }
  1965. return 0;
  1966. }
  1967. /** Sets the options for a SNI object. */
  1968. void TLSX_SNI_SetOptions(TLSX* extensions, byte type, byte options)
  1969. {
  1970. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1971. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1972. if (sni)
  1973. sni->options = options;
  1974. }
  1975. /** Retrieves a SNI request from a client hello buffer. */
  1976. int TLSX_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz,
  1977. byte type, byte* sni, word32* inOutSz)
  1978. {
  1979. word32 offset = 0;
  1980. word32 len32 = 0;
  1981. word16 len16 = 0;
  1982. if (helloSz < RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + CLIENT_HELLO_FIRST)
  1983. return INCOMPLETE_DATA;
  1984. /* TLS record header */
  1985. if ((enum ContentType) clientHello[offset++] != handshake) {
  1986. /* checking for SSLv2.0 client hello according to: */
  1987. /* http://tools.ietf.org/html/rfc4346#appendix-E.1 */
  1988. if ((enum HandShakeType) clientHello[++offset] == client_hello) {
  1989. offset += ENUM_LEN + VERSION_SZ; /* skip version */
  1990. ato16(clientHello + offset, &len16);
  1991. offset += OPAQUE16_LEN;
  1992. if (len16 % 3) /* cipher_spec_length must be multiple of 3 */
  1993. return BUFFER_ERROR;
  1994. ato16(clientHello + offset, &len16);
  1995. /* Returning SNI_UNSUPPORTED do not increment offset here */
  1996. if (len16 != 0) /* session_id_length must be 0 */
  1997. return BUFFER_ERROR;
  1998. WOLFSSL_ERROR_VERBOSE(SNI_UNSUPPORTED);
  1999. return SNI_UNSUPPORTED;
  2000. }
  2001. return BUFFER_ERROR;
  2002. }
  2003. if (clientHello[offset++] != SSLv3_MAJOR)
  2004. return BUFFER_ERROR;
  2005. if (clientHello[offset++] < TLSv1_MINOR) {
  2006. WOLFSSL_ERROR_VERBOSE(SNI_UNSUPPORTED);
  2007. return SNI_UNSUPPORTED;
  2008. }
  2009. ato16(clientHello + offset, &len16);
  2010. offset += OPAQUE16_LEN;
  2011. if (offset + len16 > helloSz)
  2012. return INCOMPLETE_DATA;
  2013. /* Handshake header */
  2014. if ((enum HandShakeType) clientHello[offset] != client_hello)
  2015. return BUFFER_ERROR;
  2016. c24to32(clientHello + offset + 1, &len32);
  2017. offset += HANDSHAKE_HEADER_SZ;
  2018. if (offset + len32 > helloSz)
  2019. return BUFFER_ERROR;
  2020. /* client hello */
  2021. offset += VERSION_SZ + RAN_LEN; /* version, random */
  2022. if (helloSz < offset + clientHello[offset])
  2023. return BUFFER_ERROR;
  2024. offset += ENUM_LEN + clientHello[offset]; /* skip session id */
  2025. /* cypher suites */
  2026. if (helloSz < offset + OPAQUE16_LEN)
  2027. return BUFFER_ERROR;
  2028. ato16(clientHello + offset, &len16);
  2029. offset += OPAQUE16_LEN;
  2030. if (helloSz < offset + len16)
  2031. return BUFFER_ERROR;
  2032. offset += len16; /* skip cypher suites */
  2033. /* compression methods */
  2034. if (helloSz < offset + 1)
  2035. return BUFFER_ERROR;
  2036. if (helloSz < offset + clientHello[offset])
  2037. return BUFFER_ERROR;
  2038. offset += ENUM_LEN + clientHello[offset]; /* skip compression methods */
  2039. /* extensions */
  2040. if (helloSz < offset + OPAQUE16_LEN)
  2041. return 0; /* no extensions in client hello. */
  2042. ato16(clientHello + offset, &len16);
  2043. offset += OPAQUE16_LEN;
  2044. if (helloSz < offset + len16)
  2045. return BUFFER_ERROR;
  2046. while (len16 >= OPAQUE16_LEN + OPAQUE16_LEN) {
  2047. word16 extType;
  2048. word16 extLen;
  2049. ato16(clientHello + offset, &extType);
  2050. offset += OPAQUE16_LEN;
  2051. ato16(clientHello + offset, &extLen);
  2052. offset += OPAQUE16_LEN;
  2053. if (helloSz < offset + extLen)
  2054. return BUFFER_ERROR;
  2055. if (extType != TLSX_SERVER_NAME) {
  2056. offset += extLen; /* skip extension */
  2057. } else {
  2058. word16 listLen;
  2059. ato16(clientHello + offset, &listLen);
  2060. offset += OPAQUE16_LEN;
  2061. if (helloSz < offset + listLen)
  2062. return BUFFER_ERROR;
  2063. while (listLen > ENUM_LEN + OPAQUE16_LEN) {
  2064. byte sniType = clientHello[offset++];
  2065. word16 sniLen;
  2066. ato16(clientHello + offset, &sniLen);
  2067. offset += OPAQUE16_LEN;
  2068. if (helloSz < offset + sniLen)
  2069. return BUFFER_ERROR;
  2070. if (sniType != type) {
  2071. offset += sniLen;
  2072. listLen -= min(ENUM_LEN + OPAQUE16_LEN + sniLen, listLen);
  2073. continue;
  2074. }
  2075. *inOutSz = min(sniLen, *inOutSz);
  2076. XMEMCPY(sni, clientHello + offset, *inOutSz);
  2077. return WOLFSSL_SUCCESS;
  2078. }
  2079. }
  2080. len16 -= min(2 * OPAQUE16_LEN + extLen, len16);
  2081. }
  2082. return len16 ? BUFFER_ERROR : 0;
  2083. }
  2084. #endif
  2085. #define SNI_FREE_ALL TLSX_SNI_FreeAll
  2086. #define SNI_GET_SIZE TLSX_SNI_GetSize
  2087. #define SNI_WRITE TLSX_SNI_Write
  2088. #define SNI_PARSE TLSX_SNI_Parse
  2089. #define SNI_VERIFY_PARSE TLSX_SNI_VerifyParse
  2090. #else
  2091. #define SNI_FREE_ALL(list, heap) WC_DO_NOTHING
  2092. #define SNI_GET_SIZE(list) 0
  2093. #define SNI_WRITE(a, b) 0
  2094. #define SNI_PARSE(a, b, c, d) 0
  2095. #define SNI_VERIFY_PARSE(a, b) 0
  2096. #endif /* HAVE_SNI */
  2097. /******************************************************************************/
  2098. /* Trusted CA Key Indication */
  2099. /******************************************************************************/
  2100. #ifdef HAVE_TRUSTED_CA
  2101. /** Creates a new TCA object. */
  2102. static TCA* TLSX_TCA_New(byte type, const byte* id, word16 idSz, void* heap)
  2103. {
  2104. TCA* tca = (TCA*)XMALLOC(sizeof(TCA), heap, DYNAMIC_TYPE_TLSX);
  2105. if (tca) {
  2106. XMEMSET(tca, 0, sizeof(TCA));
  2107. tca->type = type;
  2108. switch (type) {
  2109. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2110. break;
  2111. #ifndef NO_SHA
  2112. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2113. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2114. if (idSz == WC_SHA_DIGEST_SIZE &&
  2115. (tca->id =
  2116. (byte*)XMALLOC(idSz, heap, DYNAMIC_TYPE_TLSX))) {
  2117. XMEMCPY(tca->id, id, idSz);
  2118. tca->idSz = idSz;
  2119. }
  2120. else {
  2121. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2122. tca = NULL;
  2123. }
  2124. break;
  2125. #endif
  2126. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2127. if (idSz > 0 &&
  2128. (tca->id =
  2129. (byte*)XMALLOC(idSz, heap, DYNAMIC_TYPE_TLSX))) {
  2130. XMEMCPY(tca->id, id, idSz);
  2131. tca->idSz = idSz;
  2132. }
  2133. else {
  2134. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2135. tca = NULL;
  2136. }
  2137. break;
  2138. default: /* invalid type */
  2139. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2140. tca = NULL;
  2141. }
  2142. }
  2143. (void)heap;
  2144. return tca;
  2145. }
  2146. /** Releases a TCA object. */
  2147. static void TLSX_TCA_Free(TCA* tca, void* heap)
  2148. {
  2149. (void)heap;
  2150. if (tca) {
  2151. if (tca->id)
  2152. XFREE(tca->id, heap, DYNAMIC_TYPE_TLSX);
  2153. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2154. }
  2155. }
  2156. /** Releases all TCA objects in the provided list. */
  2157. static void TLSX_TCA_FreeAll(TCA* list, void* heap)
  2158. {
  2159. TCA* tca;
  2160. while ((tca = list)) {
  2161. list = tca->next;
  2162. TLSX_TCA_Free(tca, heap);
  2163. }
  2164. }
  2165. /** Tells the buffered size of the TCA objects in a list. */
  2166. static word16 TLSX_TCA_GetSize(TCA* list)
  2167. {
  2168. TCA* tca;
  2169. word16 length = OPAQUE16_LEN; /* list length */
  2170. while ((tca = list)) {
  2171. list = tca->next;
  2172. length += ENUM_LEN; /* tca type */
  2173. switch (tca->type) {
  2174. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2175. break;
  2176. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2177. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2178. length += tca->idSz;
  2179. break;
  2180. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2181. length += OPAQUE16_LEN + tca->idSz;
  2182. break;
  2183. }
  2184. }
  2185. return length;
  2186. }
  2187. /** Writes the TCA objects of a list in a buffer. */
  2188. static word16 TLSX_TCA_Write(TCA* list, byte* output)
  2189. {
  2190. TCA* tca;
  2191. word16 offset = OPAQUE16_LEN; /* list length offset */
  2192. while ((tca = list)) {
  2193. list = tca->next;
  2194. output[offset++] = tca->type; /* tca type */
  2195. switch (tca->type) {
  2196. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2197. break;
  2198. #ifndef NO_SHA
  2199. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2200. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2201. if (tca->id != NULL) {
  2202. XMEMCPY(output + offset, tca->id, tca->idSz);
  2203. offset += tca->idSz;
  2204. }
  2205. else {
  2206. /* ID missing. Set to an empty string. */
  2207. c16toa(0, output + offset);
  2208. offset += OPAQUE16_LEN;
  2209. }
  2210. break;
  2211. #endif
  2212. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2213. if (tca->id != NULL) {
  2214. c16toa(tca->idSz, output + offset); /* tca length */
  2215. offset += OPAQUE16_LEN;
  2216. XMEMCPY(output + offset, tca->id, tca->idSz);
  2217. offset += tca->idSz;
  2218. }
  2219. else {
  2220. /* ID missing. Set to an empty string. */
  2221. c16toa(0, output + offset);
  2222. offset += OPAQUE16_LEN;
  2223. }
  2224. break;
  2225. default:
  2226. /* ID unknown. Set to an empty string. */
  2227. c16toa(0, output + offset);
  2228. offset += OPAQUE16_LEN;
  2229. }
  2230. }
  2231. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  2232. return offset;
  2233. }
  2234. #ifndef NO_WOLFSSL_SERVER
  2235. static TCA* TLSX_TCA_Find(TCA *list, byte type, const byte* id, word16 idSz)
  2236. {
  2237. TCA* tca = list;
  2238. while (tca && tca->type != type && type != WOLFSSL_TRUSTED_CA_PRE_AGREED &&
  2239. idSz != tca->idSz && !XMEMCMP(id, tca->id, idSz))
  2240. tca = tca->next;
  2241. return tca;
  2242. }
  2243. #endif /* NO_WOLFSSL_SERVER */
  2244. /** Parses a buffer of TCA extensions. */
  2245. static int TLSX_TCA_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2246. byte isRequest)
  2247. {
  2248. #ifndef NO_WOLFSSL_SERVER
  2249. word16 size = 0;
  2250. word16 offset = 0;
  2251. #endif
  2252. TLSX *extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS);
  2253. if (!extension)
  2254. extension = TLSX_Find(ssl->ctx->extensions, TLSX_TRUSTED_CA_KEYS);
  2255. if (!isRequest) {
  2256. #ifndef NO_WOLFSSL_CLIENT
  2257. if (!extension || !extension->data)
  2258. return TLSX_HandleUnsupportedExtension(ssl);
  2259. if (length > 0)
  2260. return BUFFER_ERROR; /* TCA response MUST be empty. */
  2261. /* Set the flag that we're good for keys */
  2262. TLSX_SetResponse(ssl, TLSX_TRUSTED_CA_KEYS);
  2263. return 0;
  2264. #endif
  2265. }
  2266. #ifndef NO_WOLFSSL_SERVER
  2267. if (!extension || !extension->data) {
  2268. /* Skipping, TCA not enabled at server side. */
  2269. return 0;
  2270. }
  2271. if (OPAQUE16_LEN > length)
  2272. return BUFFER_ERROR;
  2273. ato16(input, &size);
  2274. offset += OPAQUE16_LEN;
  2275. /* validating tca list length */
  2276. if (length != OPAQUE16_LEN + size)
  2277. return BUFFER_ERROR;
  2278. for (size = 0; offset < length; offset += size) {
  2279. TCA *tca = NULL;
  2280. byte type;
  2281. const byte* id = NULL;
  2282. word16 idSz = 0;
  2283. if (offset + ENUM_LEN > length)
  2284. return BUFFER_ERROR;
  2285. type = input[offset++];
  2286. switch (type) {
  2287. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2288. break;
  2289. #ifndef NO_SHA
  2290. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2291. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2292. if (offset + WC_SHA_DIGEST_SIZE > length)
  2293. return BUFFER_ERROR;
  2294. idSz = WC_SHA_DIGEST_SIZE;
  2295. id = input + offset;
  2296. offset += idSz;
  2297. break;
  2298. #endif
  2299. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2300. if (offset + OPAQUE16_LEN > length)
  2301. return BUFFER_ERROR;
  2302. ato16(input + offset, &idSz);
  2303. offset += OPAQUE16_LEN;
  2304. if ((offset > length) || (idSz > length - offset))
  2305. return BUFFER_ERROR;
  2306. id = input + offset;
  2307. offset += idSz;
  2308. break;
  2309. default:
  2310. WOLFSSL_ERROR_VERBOSE(TCA_INVALID_ID_TYPE);
  2311. return TCA_INVALID_ID_TYPE;
  2312. }
  2313. /* Find the type/ID in the TCA list. */
  2314. tca = TLSX_TCA_Find((TCA*)extension->data, type, id, idSz);
  2315. if (tca != NULL) {
  2316. /* Found it. Set the response flag and break out of the loop. */
  2317. TLSX_SetResponse(ssl, TLSX_TRUSTED_CA_KEYS);
  2318. break;
  2319. }
  2320. }
  2321. #else
  2322. (void)input;
  2323. #endif
  2324. return 0;
  2325. }
  2326. /* Checks to see if the server sent a response for the TCA. */
  2327. static int TLSX_TCA_VerifyParse(WOLFSSL* ssl, byte isRequest)
  2328. {
  2329. (void)ssl;
  2330. if (!isRequest) {
  2331. #ifndef NO_WOLFSSL_CLIENT
  2332. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS);
  2333. if (extension && !extension->resp) {
  2334. SendAlert(ssl, alert_fatal, handshake_failure);
  2335. WOLFSSL_ERROR_VERBOSE(TCA_ABSENT_ERROR);
  2336. return TCA_ABSENT_ERROR;
  2337. }
  2338. #endif /* NO_WOLFSSL_CLIENT */
  2339. }
  2340. return 0;
  2341. }
  2342. int TLSX_UseTrustedCA(TLSX** extensions, byte type,
  2343. const byte* id, word16 idSz, void* heap)
  2344. {
  2345. TLSX* extension;
  2346. TCA* tca = NULL;
  2347. if (extensions == NULL)
  2348. return BAD_FUNC_ARG;
  2349. if ((tca = TLSX_TCA_New(type, id, idSz, heap)) == NULL)
  2350. return MEMORY_E;
  2351. extension = TLSX_Find(*extensions, TLSX_TRUSTED_CA_KEYS);
  2352. if (!extension) {
  2353. int ret = TLSX_Push(extensions, TLSX_TRUSTED_CA_KEYS, (void*)tca, heap);
  2354. if (ret != 0) {
  2355. TLSX_TCA_Free(tca, heap);
  2356. return ret;
  2357. }
  2358. }
  2359. else {
  2360. /* push new TCA object to extension data. */
  2361. tca->next = (TCA*)extension->data;
  2362. extension->data = (void*)tca;
  2363. }
  2364. return WOLFSSL_SUCCESS;
  2365. }
  2366. #define TCA_FREE_ALL TLSX_TCA_FreeAll
  2367. #define TCA_GET_SIZE TLSX_TCA_GetSize
  2368. #define TCA_WRITE TLSX_TCA_Write
  2369. #define TCA_PARSE TLSX_TCA_Parse
  2370. #define TCA_VERIFY_PARSE TLSX_TCA_VerifyParse
  2371. #else /* HAVE_TRUSTED_CA */
  2372. #define TCA_FREE_ALL(list, heap) WC_DO_NOTHING
  2373. #define TCA_GET_SIZE(list) 0
  2374. #define TCA_WRITE(a, b) 0
  2375. #define TCA_PARSE(a, b, c, d) 0
  2376. #define TCA_VERIFY_PARSE(a, b) 0
  2377. #endif /* HAVE_TRUSTED_CA */
  2378. /******************************************************************************/
  2379. /* Max Fragment Length Negotiation */
  2380. /******************************************************************************/
  2381. #ifdef HAVE_MAX_FRAGMENT
  2382. static word16 TLSX_MFL_Write(byte* data, byte* output)
  2383. {
  2384. output[0] = data[0];
  2385. return ENUM_LEN;
  2386. }
  2387. static int TLSX_MFL_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2388. byte isRequest)
  2389. {
  2390. if (length != ENUM_LEN)
  2391. return BUFFER_ERROR;
  2392. #ifdef WOLFSSL_OLD_UNSUPPORTED_EXTENSION
  2393. (void) isRequest;
  2394. #else
  2395. if (!isRequest)
  2396. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_MAX_FRAGMENT_LENGTH))
  2397. return TLSX_HandleUnsupportedExtension(ssl);
  2398. #endif
  2399. switch (*input) {
  2400. case WOLFSSL_MFL_2_8 : ssl->max_fragment = 256; break;
  2401. case WOLFSSL_MFL_2_9 : ssl->max_fragment = 512; break;
  2402. case WOLFSSL_MFL_2_10: ssl->max_fragment = 1024; break;
  2403. case WOLFSSL_MFL_2_11: ssl->max_fragment = 2048; break;
  2404. case WOLFSSL_MFL_2_12: ssl->max_fragment = 4096; break;
  2405. case WOLFSSL_MFL_2_13: ssl->max_fragment = 8192; break;
  2406. default:
  2407. SendAlert(ssl, alert_fatal, illegal_parameter);
  2408. WOLFSSL_ERROR_VERBOSE(UNKNOWN_MAX_FRAG_LEN_E);
  2409. return UNKNOWN_MAX_FRAG_LEN_E;
  2410. }
  2411. #ifndef NO_WOLFSSL_SERVER
  2412. if (isRequest) {
  2413. int ret = TLSX_UseMaxFragment(&ssl->extensions, *input, ssl->heap);
  2414. if (ret != WOLFSSL_SUCCESS)
  2415. return ret; /* throw error */
  2416. TLSX_SetResponse(ssl, TLSX_MAX_FRAGMENT_LENGTH);
  2417. }
  2418. #endif
  2419. return 0;
  2420. }
  2421. int TLSX_UseMaxFragment(TLSX** extensions, byte mfl, void* heap)
  2422. {
  2423. byte* data = NULL;
  2424. int ret = 0;
  2425. if (extensions == NULL || mfl < WOLFSSL_MFL_MIN || mfl > WOLFSSL_MFL_MAX)
  2426. return BAD_FUNC_ARG;
  2427. data = (byte*)XMALLOC(ENUM_LEN, heap, DYNAMIC_TYPE_TLSX);
  2428. if (data == NULL)
  2429. return MEMORY_E;
  2430. data[0] = mfl;
  2431. ret = TLSX_Push(extensions, TLSX_MAX_FRAGMENT_LENGTH, data, heap);
  2432. if (ret != 0) {
  2433. XFREE(data, heap, DYNAMIC_TYPE_TLSX);
  2434. return ret;
  2435. }
  2436. return WOLFSSL_SUCCESS;
  2437. }
  2438. #define MFL_FREE_ALL(data, heap) XFREE(data, (heap), DYNAMIC_TYPE_TLSX)
  2439. #define MFL_GET_SIZE(data) ENUM_LEN
  2440. #define MFL_WRITE TLSX_MFL_Write
  2441. #define MFL_PARSE TLSX_MFL_Parse
  2442. #else
  2443. #define MFL_FREE_ALL(a, b) WC_DO_NOTHING
  2444. #define MFL_GET_SIZE(a) 0
  2445. #define MFL_WRITE(a, b) 0
  2446. #define MFL_PARSE(a, b, c, d) 0
  2447. #endif /* HAVE_MAX_FRAGMENT */
  2448. /******************************************************************************/
  2449. /* Truncated HMAC */
  2450. /******************************************************************************/
  2451. #ifdef HAVE_TRUNCATED_HMAC
  2452. static int TLSX_THM_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2453. byte isRequest)
  2454. {
  2455. if (length != 0 || input == NULL)
  2456. return BUFFER_ERROR;
  2457. if (!isRequest) {
  2458. #ifndef WOLFSSL_OLD_UNSUPPORTED_EXTENSION
  2459. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_TRUNCATED_HMAC))
  2460. return TLSX_HandleUnsupportedExtension(ssl);
  2461. #endif
  2462. }
  2463. else {
  2464. #ifndef NO_WOLFSSL_SERVER
  2465. int ret = TLSX_UseTruncatedHMAC(&ssl->extensions, ssl->heap);
  2466. if (ret != WOLFSSL_SUCCESS)
  2467. return ret; /* throw error */
  2468. TLSX_SetResponse(ssl, TLSX_TRUNCATED_HMAC);
  2469. #endif
  2470. }
  2471. ssl->truncated_hmac = 1;
  2472. return 0;
  2473. }
  2474. int TLSX_UseTruncatedHMAC(TLSX** extensions, void* heap)
  2475. {
  2476. int ret = 0;
  2477. if (extensions == NULL)
  2478. return BAD_FUNC_ARG;
  2479. ret = TLSX_Push(extensions, TLSX_TRUNCATED_HMAC, NULL, heap);
  2480. if (ret != 0)
  2481. return ret;
  2482. return WOLFSSL_SUCCESS;
  2483. }
  2484. #define THM_PARSE TLSX_THM_Parse
  2485. #else
  2486. #define THM_PARSE(a, b, c, d) 0
  2487. #endif /* HAVE_TRUNCATED_HMAC */
  2488. /******************************************************************************/
  2489. /* Certificate Status Request */
  2490. /******************************************************************************/
  2491. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  2492. static void TLSX_CSR_Free(CertificateStatusRequest* csr, void* heap)
  2493. {
  2494. switch (csr->status_type) {
  2495. case WOLFSSL_CSR_OCSP:
  2496. FreeOcspRequest(&csr->request.ocsp);
  2497. break;
  2498. }
  2499. #ifdef WOLFSSL_TLS13
  2500. if (csr->response.buffer != NULL) {
  2501. XFREE(csr->response.buffer, csr->ssl->heap,
  2502. DYNAMIC_TYPE_TMP_BUFFER);
  2503. }
  2504. #endif
  2505. XFREE(csr, heap, DYNAMIC_TYPE_TLSX);
  2506. (void)heap;
  2507. }
  2508. static word16 TLSX_CSR_GetSize(CertificateStatusRequest* csr, byte isRequest)
  2509. {
  2510. word16 size = 0;
  2511. /* shut up compiler warnings */
  2512. (void) csr; (void) isRequest;
  2513. #ifndef NO_WOLFSSL_CLIENT
  2514. if (isRequest) {
  2515. switch (csr->status_type) {
  2516. case WOLFSSL_CSR_OCSP:
  2517. size += ENUM_LEN + 2 * OPAQUE16_LEN;
  2518. if (csr->request.ocsp.nonceSz)
  2519. size += OCSP_NONCE_EXT_SZ;
  2520. break;
  2521. }
  2522. }
  2523. #endif
  2524. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  2525. if (!isRequest && csr->ssl->options.tls1_3)
  2526. return OPAQUE8_LEN + OPAQUE24_LEN + csr->response.length;
  2527. #endif
  2528. return size;
  2529. }
  2530. static int TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output,
  2531. byte isRequest)
  2532. {
  2533. /* shut up compiler warnings */
  2534. (void) csr; (void) output; (void) isRequest;
  2535. #ifndef NO_WOLFSSL_CLIENT
  2536. if (isRequest) {
  2537. int ret = 0;
  2538. word16 offset = 0;
  2539. word16 length = 0;
  2540. /* type */
  2541. output[offset++] = csr->status_type;
  2542. switch (csr->status_type) {
  2543. case WOLFSSL_CSR_OCSP:
  2544. /* responder id list */
  2545. c16toa(0, output + offset);
  2546. offset += OPAQUE16_LEN;
  2547. /* request extensions */
  2548. if (csr->request.ocsp.nonceSz) {
  2549. ret = (int)EncodeOcspRequestExtensions(&csr->request.ocsp,
  2550. output + offset + OPAQUE16_LEN,
  2551. OCSP_NONCE_EXT_SZ);
  2552. if (ret > 0) {
  2553. length = (word16)ret;
  2554. }
  2555. else {
  2556. return ret;
  2557. }
  2558. }
  2559. c16toa(length, output + offset);
  2560. offset += OPAQUE16_LEN + length;
  2561. break;
  2562. }
  2563. return (int)offset;
  2564. }
  2565. #endif
  2566. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  2567. if (!isRequest && csr->ssl->options.tls1_3) {
  2568. word16 offset = 0;
  2569. output[offset++] = csr->status_type;
  2570. c32to24(csr->response.length, output + offset);
  2571. offset += OPAQUE24_LEN;
  2572. XMEMCPY(output + offset, csr->response.buffer, csr->response.length);
  2573. offset += csr->response.length;
  2574. return offset;
  2575. }
  2576. #endif
  2577. return 0;
  2578. }
  2579. static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2580. byte isRequest)
  2581. {
  2582. int ret;
  2583. #if !defined(NO_WOLFSSL_SERVER)
  2584. byte status_type;
  2585. word16 size = 0;
  2586. #if defined(WOLFSSL_TLS13)
  2587. DecodedCert* cert;
  2588. #endif
  2589. #endif
  2590. #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) \
  2591. && defined(WOLFSSL_TLS13)
  2592. OcspRequest* request;
  2593. TLSX* extension;
  2594. CertificateStatusRequest* csr;
  2595. #endif
  2596. #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_TLS13) \
  2597. || !defined(NO_WOLFSSL_SERVER)
  2598. word32 offset = 0;
  2599. #endif
  2600. #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_TLS13)
  2601. word32 resp_length = 0;
  2602. #endif
  2603. /* shut up compiler warnings */
  2604. (void) ssl; (void) input;
  2605. if (!isRequest) {
  2606. #ifndef NO_WOLFSSL_CLIENT
  2607. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2608. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2609. if (!csr) {
  2610. /* look at context level */
  2611. extension = TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST);
  2612. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2613. if (!csr) /* unexpected extension */
  2614. return TLSX_HandleUnsupportedExtension(ssl);
  2615. /* enable extension at ssl level */
  2616. ret = TLSX_UseCertificateStatusRequest(&ssl->extensions,
  2617. csr->status_type, csr->options, ssl,
  2618. ssl->heap, ssl->devId);
  2619. if (ret != WOLFSSL_SUCCESS)
  2620. return ret == 0 ? -1 : ret;
  2621. switch (csr->status_type) {
  2622. case WOLFSSL_CSR_OCSP:
  2623. /* propagate nonce */
  2624. if (csr->request.ocsp.nonceSz) {
  2625. request =
  2626. (OcspRequest*)TLSX_CSR_GetRequest(ssl->extensions);
  2627. if (request) {
  2628. XMEMCPY(request->nonce, csr->request.ocsp.nonce,
  2629. csr->request.ocsp.nonceSz);
  2630. request->nonceSz = csr->request.ocsp.nonceSz;
  2631. }
  2632. }
  2633. break;
  2634. }
  2635. }
  2636. ssl->status_request = 1;
  2637. #ifdef WOLFSSL_TLS13
  2638. if (ssl->options.tls1_3) {
  2639. /* Get the new extension potentially created above. */
  2640. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2641. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2642. if (csr == NULL)
  2643. return MEMORY_ERROR;
  2644. ret = 0;
  2645. if (OPAQUE8_LEN + OPAQUE24_LEN > length)
  2646. ret = BUFFER_ERROR;
  2647. if (ret == 0 && input[offset++] != WOLFSSL_CSR_OCSP) {
  2648. ret = BAD_CERTIFICATE_STATUS_ERROR;
  2649. WOLFSSL_ERROR_VERBOSE(ret);
  2650. }
  2651. if (ret == 0) {
  2652. c24to32(input + offset, &resp_length);
  2653. offset += OPAQUE24_LEN;
  2654. if (offset + resp_length != length)
  2655. ret = BUFFER_ERROR;
  2656. }
  2657. if (ret == 0) {
  2658. csr->response.buffer = (byte*)XMALLOC(resp_length, ssl->heap,
  2659. DYNAMIC_TYPE_TMP_BUFFER);
  2660. if (csr->response.buffer == NULL)
  2661. ret = MEMORY_ERROR;
  2662. }
  2663. if (ret == 0) {
  2664. XMEMCPY(csr->response.buffer, input + offset, resp_length);
  2665. csr->response.length = resp_length;
  2666. }
  2667. return ret;
  2668. }
  2669. else
  2670. #endif
  2671. {
  2672. /* extension_data MUST be empty. */
  2673. return length ? BUFFER_ERROR : 0;
  2674. }
  2675. #endif
  2676. }
  2677. else {
  2678. #ifndef NO_WOLFSSL_SERVER
  2679. if (length == 0)
  2680. return 0;
  2681. status_type = input[offset++];
  2682. switch (status_type) {
  2683. case WOLFSSL_CSR_OCSP: {
  2684. /* skip responder_id_list */
  2685. if ((int)(length - offset) < OPAQUE16_LEN)
  2686. return BUFFER_ERROR;
  2687. ato16(input + offset, &size);
  2688. offset += OPAQUE16_LEN + size;
  2689. /* skip request_extensions */
  2690. if ((int)(length - offset) < OPAQUE16_LEN)
  2691. return BUFFER_ERROR;
  2692. ato16(input + offset, &size);
  2693. offset += OPAQUE16_LEN + size;
  2694. if (offset > length)
  2695. return BUFFER_ERROR;
  2696. /* is able to send OCSP response? */
  2697. if (SSL_CM(ssl) == NULL || !SSL_CM(ssl)->ocspStaplingEnabled)
  2698. return 0;
  2699. }
  2700. break;
  2701. /* unknown status type */
  2702. default:
  2703. return 0;
  2704. }
  2705. /* if using status_request and already sending it, skip this one */
  2706. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2707. if (ssl->status_request_v2)
  2708. return 0;
  2709. #endif
  2710. /* accept the first good status_type and return */
  2711. ret = TLSX_UseCertificateStatusRequest(&ssl->extensions, status_type,
  2712. 0, ssl, ssl->heap, ssl->devId);
  2713. if (ret != WOLFSSL_SUCCESS)
  2714. return ret == 0 ? -1 : ret; /* throw error */
  2715. #if defined(WOLFSSL_TLS13)
  2716. if (ssl->options.tls1_3) {
  2717. if (ssl->buffers.certificate == NULL) {
  2718. WOLFSSL_MSG("Certificate buffer not set!");
  2719. return BUFFER_ERROR;
  2720. }
  2721. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
  2722. DYNAMIC_TYPE_DCERT);
  2723. if (cert == NULL) {
  2724. return MEMORY_E;
  2725. }
  2726. InitDecodedCert(cert, ssl->buffers.certificate->buffer,
  2727. ssl->buffers.certificate->length, ssl->heap);
  2728. ret = ParseCert(cert, CERT_TYPE, 1, SSL_CM(ssl));
  2729. if (ret != 0) {
  2730. FreeDecodedCert(cert);
  2731. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2732. /* Let's not error out the connection if we can't verify our
  2733. * cert */
  2734. if (ret == ASN_SELF_SIGNED_E || ret == ASN_NO_SIGNER_E)
  2735. ret = 0;
  2736. return ret;
  2737. }
  2738. ret = TLSX_CSR_InitRequest(ssl->extensions, cert, ssl->heap);
  2739. if (ret != 0 ) {
  2740. FreeDecodedCert(cert);
  2741. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2742. return ret;
  2743. }
  2744. FreeDecodedCert(cert);
  2745. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2746. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2747. csr = extension ?
  2748. (CertificateStatusRequest*)extension->data : NULL;
  2749. if (csr == NULL)
  2750. return MEMORY_ERROR;
  2751. request = &csr->request.ocsp;
  2752. ret = CreateOcspResponse(ssl, &request, &csr->response);
  2753. if (ret != 0)
  2754. return ret;
  2755. if (csr->response.buffer)
  2756. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST);
  2757. }
  2758. else
  2759. #endif
  2760. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST);
  2761. ssl->status_request = status_type;
  2762. #endif
  2763. }
  2764. return 0;
  2765. }
  2766. int TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert, void* heap)
  2767. {
  2768. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST);
  2769. CertificateStatusRequest* csr = extension ?
  2770. (CertificateStatusRequest*)extension->data : NULL;
  2771. int ret = 0;
  2772. if (csr) {
  2773. switch (csr->status_type) {
  2774. case WOLFSSL_CSR_OCSP: {
  2775. byte nonce[MAX_OCSP_NONCE_SZ];
  2776. int nonceSz = csr->request.ocsp.nonceSz;
  2777. /* preserve nonce */
  2778. XMEMCPY(nonce, csr->request.ocsp.nonce, nonceSz);
  2779. if ((ret = InitOcspRequest(&csr->request.ocsp, cert, 0, heap))
  2780. != 0)
  2781. return ret;
  2782. /* restore nonce */
  2783. XMEMCPY(csr->request.ocsp.nonce, nonce, nonceSz);
  2784. csr->request.ocsp.nonceSz = nonceSz;
  2785. }
  2786. break;
  2787. }
  2788. }
  2789. return ret;
  2790. }
  2791. void* TLSX_CSR_GetRequest(TLSX* extensions)
  2792. {
  2793. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST);
  2794. CertificateStatusRequest* csr = extension ?
  2795. (CertificateStatusRequest*)extension->data : NULL;
  2796. if (csr) {
  2797. switch (csr->status_type) {
  2798. case WOLFSSL_CSR_OCSP:
  2799. return &csr->request.ocsp;
  2800. }
  2801. }
  2802. return NULL;
  2803. }
  2804. int TLSX_CSR_ForceRequest(WOLFSSL* ssl)
  2805. {
  2806. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2807. CertificateStatusRequest* csr = extension ?
  2808. (CertificateStatusRequest*)extension->data : NULL;
  2809. if (csr) {
  2810. switch (csr->status_type) {
  2811. case WOLFSSL_CSR_OCSP:
  2812. if (SSL_CM(ssl)->ocspEnabled) {
  2813. csr->request.ocsp.ssl = ssl;
  2814. return CheckOcspRequest(SSL_CM(ssl)->ocsp,
  2815. &csr->request.ocsp, NULL, NULL);
  2816. }
  2817. else {
  2818. WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL);
  2819. return OCSP_LOOKUP_FAIL;
  2820. }
  2821. }
  2822. }
  2823. return 0;
  2824. }
  2825. int TLSX_UseCertificateStatusRequest(TLSX** extensions, byte status_type,
  2826. byte options, WOLFSSL* ssl, void* heap,
  2827. int devId)
  2828. {
  2829. CertificateStatusRequest* csr = NULL;
  2830. int ret = 0;
  2831. if (!extensions || status_type != WOLFSSL_CSR_OCSP)
  2832. return BAD_FUNC_ARG;
  2833. csr = (CertificateStatusRequest*)
  2834. XMALLOC(sizeof(CertificateStatusRequest), heap, DYNAMIC_TYPE_TLSX);
  2835. if (!csr)
  2836. return MEMORY_E;
  2837. ForceZero(csr, sizeof(CertificateStatusRequest));
  2838. csr->status_type = status_type;
  2839. csr->options = options;
  2840. csr->ssl = ssl;
  2841. switch (csr->status_type) {
  2842. case WOLFSSL_CSR_OCSP:
  2843. if (options & WOLFSSL_CSR_OCSP_USE_NONCE) {
  2844. WC_RNG rng;
  2845. #ifndef HAVE_FIPS
  2846. ret = wc_InitRng_ex(&rng, heap, devId);
  2847. #else
  2848. ret = wc_InitRng(&rng);
  2849. (void)devId;
  2850. #endif
  2851. if (ret == 0) {
  2852. if (wc_RNG_GenerateBlock(&rng, csr->request.ocsp.nonce,
  2853. MAX_OCSP_NONCE_SZ) == 0)
  2854. csr->request.ocsp.nonceSz = MAX_OCSP_NONCE_SZ;
  2855. wc_FreeRng(&rng);
  2856. }
  2857. }
  2858. break;
  2859. }
  2860. if ((ret = TLSX_Push(extensions, TLSX_STATUS_REQUEST, csr, heap)) != 0) {
  2861. XFREE(csr, heap, DYNAMIC_TYPE_TLSX);
  2862. return ret;
  2863. }
  2864. return WOLFSSL_SUCCESS;
  2865. }
  2866. #define CSR_FREE_ALL TLSX_CSR_Free
  2867. #define CSR_GET_SIZE TLSX_CSR_GetSize
  2868. #define CSR_WRITE TLSX_CSR_Write
  2869. #define CSR_PARSE TLSX_CSR_Parse
  2870. #else
  2871. #define CSR_FREE_ALL(data, heap) WC_DO_NOTHING
  2872. #define CSR_GET_SIZE(a, b) 0
  2873. #define CSR_WRITE(a, b, c) 0
  2874. #define CSR_PARSE(a, b, c, d) 0
  2875. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
  2876. /******************************************************************************/
  2877. /* Certificate Status Request v2 */
  2878. /******************************************************************************/
  2879. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2880. static void TLSX_CSR2_FreeAll(CertificateStatusRequestItemV2* csr2, void* heap)
  2881. {
  2882. CertificateStatusRequestItemV2* next;
  2883. for (; csr2; csr2 = next) {
  2884. next = csr2->next;
  2885. switch (csr2->status_type) {
  2886. case WOLFSSL_CSR2_OCSP:
  2887. case WOLFSSL_CSR2_OCSP_MULTI:
  2888. while(csr2->requests--)
  2889. FreeOcspRequest(&csr2->request.ocsp[csr2->requests]);
  2890. break;
  2891. }
  2892. XFREE(csr2, heap, DYNAMIC_TYPE_TLSX);
  2893. }
  2894. (void)heap;
  2895. }
  2896. static word16 TLSX_CSR2_GetSize(CertificateStatusRequestItemV2* csr2,
  2897. byte isRequest)
  2898. {
  2899. word16 size = 0;
  2900. /* shut up compiler warnings */
  2901. (void) csr2; (void) isRequest;
  2902. #ifndef NO_WOLFSSL_CLIENT
  2903. if (isRequest) {
  2904. CertificateStatusRequestItemV2* next;
  2905. for (size = OPAQUE16_LEN; csr2; csr2 = next) {
  2906. next = csr2->next;
  2907. switch (csr2->status_type) {
  2908. case WOLFSSL_CSR2_OCSP:
  2909. case WOLFSSL_CSR2_OCSP_MULTI:
  2910. size += ENUM_LEN + 3 * OPAQUE16_LEN;
  2911. if (csr2->request.ocsp[0].nonceSz)
  2912. size += OCSP_NONCE_EXT_SZ;
  2913. break;
  2914. }
  2915. }
  2916. }
  2917. #endif
  2918. return size;
  2919. }
  2920. static int TLSX_CSR2_Write(CertificateStatusRequestItemV2* csr2,
  2921. byte* output, byte isRequest)
  2922. {
  2923. /* shut up compiler warnings */
  2924. (void) csr2; (void) output; (void) isRequest;
  2925. #ifndef NO_WOLFSSL_CLIENT
  2926. if (isRequest) {
  2927. int ret = 0;
  2928. word16 offset;
  2929. word16 length;
  2930. for (offset = OPAQUE16_LEN; csr2 != NULL; csr2 = csr2->next) {
  2931. /* status_type */
  2932. output[offset++] = csr2->status_type;
  2933. /* request */
  2934. switch (csr2->status_type) {
  2935. case WOLFSSL_CSR2_OCSP:
  2936. case WOLFSSL_CSR2_OCSP_MULTI:
  2937. /* request_length */
  2938. length = 2 * OPAQUE16_LEN;
  2939. if (csr2->request.ocsp[0].nonceSz)
  2940. length += OCSP_NONCE_EXT_SZ;
  2941. c16toa(length, output + offset);
  2942. offset += OPAQUE16_LEN;
  2943. /* responder id list */
  2944. c16toa(0, output + offset);
  2945. offset += OPAQUE16_LEN;
  2946. /* request extensions */
  2947. length = 0;
  2948. if (csr2->request.ocsp[0].nonceSz) {
  2949. ret = (int)EncodeOcspRequestExtensions(
  2950. &csr2->request.ocsp[0],
  2951. output + offset + OPAQUE16_LEN,
  2952. OCSP_NONCE_EXT_SZ);
  2953. if (ret > 0) {
  2954. length = (word16)ret;
  2955. }
  2956. else {
  2957. return ret;
  2958. }
  2959. }
  2960. c16toa(length, output + offset);
  2961. offset += OPAQUE16_LEN + length;
  2962. break;
  2963. }
  2964. }
  2965. /* list size */
  2966. c16toa(offset - OPAQUE16_LEN, output);
  2967. return (int)offset;
  2968. }
  2969. #endif
  2970. return 0;
  2971. }
  2972. static int TLSX_CSR2_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2973. byte isRequest)
  2974. {
  2975. int ret;
  2976. /* shut up compiler warnings */
  2977. (void) ssl; (void) input;
  2978. if (!isRequest) {
  2979. #ifndef NO_WOLFSSL_CLIENT
  2980. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST_V2);
  2981. CertificateStatusRequestItemV2* csr2 = extension ?
  2982. (CertificateStatusRequestItemV2*)extension->data : NULL;
  2983. if (!csr2) {
  2984. /* look at context level */
  2985. extension = TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST_V2);
  2986. csr2 = extension ?
  2987. (CertificateStatusRequestItemV2*)extension->data : NULL;
  2988. if (!csr2) /* unexpected extension */
  2989. return TLSX_HandleUnsupportedExtension(ssl);
  2990. /* enable extension at ssl level */
  2991. for (; csr2; csr2 = csr2->next) {
  2992. ret = TLSX_UseCertificateStatusRequestV2(&ssl->extensions,
  2993. csr2->status_type, csr2->options, ssl->heap,
  2994. ssl->devId);
  2995. if (ret != WOLFSSL_SUCCESS)
  2996. return ret;
  2997. switch (csr2->status_type) {
  2998. case WOLFSSL_CSR2_OCSP:
  2999. /* followed by */
  3000. case WOLFSSL_CSR2_OCSP_MULTI:
  3001. /* propagate nonce */
  3002. if (csr2->request.ocsp[0].nonceSz) {
  3003. OcspRequest* request =
  3004. (OcspRequest*)TLSX_CSR2_GetRequest(ssl->extensions,
  3005. csr2->status_type, 0);
  3006. if (request) {
  3007. XMEMCPY(request->nonce,
  3008. csr2->request.ocsp[0].nonce,
  3009. csr2->request.ocsp[0].nonceSz);
  3010. request->nonceSz =
  3011. csr2->request.ocsp[0].nonceSz;
  3012. }
  3013. }
  3014. break;
  3015. }
  3016. }
  3017. }
  3018. ssl->status_request_v2 = 1;
  3019. return length ? BUFFER_ERROR : 0; /* extension_data MUST be empty. */
  3020. #endif
  3021. }
  3022. else {
  3023. #ifndef NO_WOLFSSL_SERVER
  3024. byte status_type;
  3025. word16 request_length;
  3026. word16 offset = 0;
  3027. word16 size = 0;
  3028. /* list size */
  3029. if (offset + OPAQUE16_LEN >= length) {
  3030. return BUFFER_E;
  3031. }
  3032. ato16(input + offset, &request_length);
  3033. offset += OPAQUE16_LEN;
  3034. if (length - OPAQUE16_LEN != request_length)
  3035. return BUFFER_ERROR;
  3036. while (length > offset) {
  3037. if ((int)(length - offset) < ENUM_LEN + OPAQUE16_LEN)
  3038. return BUFFER_ERROR;
  3039. status_type = input[offset++];
  3040. ato16(input + offset, &request_length);
  3041. offset += OPAQUE16_LEN;
  3042. if (length - offset < request_length)
  3043. return BUFFER_ERROR;
  3044. switch (status_type) {
  3045. case WOLFSSL_CSR2_OCSP:
  3046. case WOLFSSL_CSR2_OCSP_MULTI:
  3047. /* skip responder_id_list */
  3048. if ((int)(length - offset) < OPAQUE16_LEN)
  3049. return BUFFER_ERROR;
  3050. ato16(input + offset, &size);
  3051. if (length - offset < size)
  3052. return BUFFER_ERROR;
  3053. offset += OPAQUE16_LEN + size;
  3054. /* skip request_extensions */
  3055. if ((int)(length - offset) < OPAQUE16_LEN)
  3056. return BUFFER_ERROR;
  3057. ato16(input + offset, &size);
  3058. if (length - offset < size)
  3059. return BUFFER_ERROR;
  3060. offset += OPAQUE16_LEN + size;
  3061. if (offset > length)
  3062. return BUFFER_ERROR;
  3063. /* is able to send OCSP response? */
  3064. if (SSL_CM(ssl) == NULL
  3065. || !SSL_CM(ssl)->ocspStaplingEnabled)
  3066. continue;
  3067. break;
  3068. default:
  3069. /* unknown status type, skipping! */
  3070. offset += request_length;
  3071. continue;
  3072. }
  3073. /* if using status_request and already sending it, remove it
  3074. * and prefer to use the v2 version */
  3075. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  3076. if (ssl->status_request) {
  3077. ssl->status_request = 0;
  3078. TLSX_Remove(&ssl->extensions, TLSX_STATUS_REQUEST, ssl->heap);
  3079. }
  3080. #endif
  3081. /* TLS 1.3 servers MUST NOT act upon presence or information in
  3082. * this extension (RFC 8448 Section 4.4.2.1).
  3083. */
  3084. if (!IsAtLeastTLSv1_3(ssl->version)) {
  3085. /* accept the first good status_type and return */
  3086. ret = TLSX_UseCertificateStatusRequestV2(&ssl->extensions,
  3087. status_type, 0, ssl->heap, ssl->devId);
  3088. if (ret != WOLFSSL_SUCCESS)
  3089. return ret; /* throw error */
  3090. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST_V2);
  3091. ssl->status_request_v2 = status_type;
  3092. }
  3093. return 0;
  3094. }
  3095. #endif
  3096. }
  3097. return 0;
  3098. }
  3099. int TLSX_CSR2_InitRequests(TLSX* extensions, DecodedCert* cert, byte isPeer,
  3100. void* heap)
  3101. {
  3102. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2);
  3103. CertificateStatusRequestItemV2* csr2 = extension ?
  3104. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3105. int ret = 0;
  3106. for (; csr2; csr2 = csr2->next) {
  3107. switch (csr2->status_type) {
  3108. case WOLFSSL_CSR2_OCSP:
  3109. if (!isPeer || csr2->requests != 0)
  3110. break;
  3111. FALL_THROUGH; /* followed by */
  3112. case WOLFSSL_CSR2_OCSP_MULTI: {
  3113. if (csr2->requests < 1 + MAX_CHAIN_DEPTH) {
  3114. byte nonce[MAX_OCSP_NONCE_SZ];
  3115. int nonceSz = csr2->request.ocsp[0].nonceSz;
  3116. /* preserve nonce, replicating nonce of ocsp[0] */
  3117. XMEMCPY(nonce, csr2->request.ocsp[0].nonce, nonceSz);
  3118. if ((ret = InitOcspRequest(
  3119. &csr2->request.ocsp[csr2->requests], cert,
  3120. 0, heap)) != 0)
  3121. return ret;
  3122. /* restore nonce */
  3123. XMEMCPY(csr2->request.ocsp[csr2->requests].nonce,
  3124. nonce, nonceSz);
  3125. csr2->request.ocsp[csr2->requests].nonceSz = nonceSz;
  3126. csr2->requests++;
  3127. }
  3128. }
  3129. break;
  3130. }
  3131. }
  3132. (void)cert;
  3133. return ret;
  3134. }
  3135. void* TLSX_CSR2_GetRequest(TLSX* extensions, byte status_type, byte idx)
  3136. {
  3137. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2);
  3138. CertificateStatusRequestItemV2* csr2 = extension ?
  3139. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3140. for (; csr2; csr2 = csr2->next) {
  3141. if (csr2->status_type == status_type) {
  3142. switch (csr2->status_type) {
  3143. case WOLFSSL_CSR2_OCSP:
  3144. /* followed by */
  3145. case WOLFSSL_CSR2_OCSP_MULTI:
  3146. /* requests are initialized in the reverse order */
  3147. return idx < csr2->requests
  3148. ? &csr2->request.ocsp[csr2->requests - idx - 1]
  3149. : NULL;
  3150. }
  3151. }
  3152. }
  3153. return NULL;
  3154. }
  3155. int TLSX_CSR2_ForceRequest(WOLFSSL* ssl)
  3156. {
  3157. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST_V2);
  3158. CertificateStatusRequestItemV2* csr2 = extension ?
  3159. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3160. /* forces only the first one */
  3161. if (csr2) {
  3162. switch (csr2->status_type) {
  3163. case WOLFSSL_CSR2_OCSP:
  3164. /* followed by */
  3165. case WOLFSSL_CSR2_OCSP_MULTI:
  3166. if (SSL_CM(ssl)->ocspEnabled) {
  3167. csr2->request.ocsp[0].ssl = ssl;
  3168. return CheckOcspRequest(SSL_CM(ssl)->ocsp,
  3169. &csr2->request.ocsp[0], NULL, NULL);
  3170. }
  3171. else {
  3172. WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL);
  3173. return OCSP_LOOKUP_FAIL;
  3174. }
  3175. }
  3176. }
  3177. return 0;
  3178. }
  3179. int TLSX_UseCertificateStatusRequestV2(TLSX** extensions, byte status_type,
  3180. byte options, void* heap, int devId)
  3181. {
  3182. TLSX* extension = NULL;
  3183. CertificateStatusRequestItemV2* csr2 = NULL;
  3184. int ret = 0;
  3185. if (!extensions)
  3186. return BAD_FUNC_ARG;
  3187. if (status_type != WOLFSSL_CSR2_OCSP
  3188. && status_type != WOLFSSL_CSR2_OCSP_MULTI)
  3189. return BAD_FUNC_ARG;
  3190. csr2 = (CertificateStatusRequestItemV2*)
  3191. XMALLOC(sizeof(CertificateStatusRequestItemV2), heap, DYNAMIC_TYPE_TLSX);
  3192. if (!csr2)
  3193. return MEMORY_E;
  3194. ForceZero(csr2, sizeof(CertificateStatusRequestItemV2));
  3195. csr2->status_type = status_type;
  3196. csr2->options = options;
  3197. csr2->next = NULL;
  3198. switch (csr2->status_type) {
  3199. case WOLFSSL_CSR2_OCSP:
  3200. case WOLFSSL_CSR2_OCSP_MULTI:
  3201. if (options & WOLFSSL_CSR2_OCSP_USE_NONCE) {
  3202. WC_RNG rng;
  3203. #ifndef HAVE_FIPS
  3204. ret = wc_InitRng_ex(&rng, heap, devId);
  3205. #else
  3206. ret = wc_InitRng(&rng);
  3207. (void)devId;
  3208. #endif
  3209. if (ret == 0) {
  3210. if (wc_RNG_GenerateBlock(&rng, csr2->request.ocsp[0].nonce,
  3211. MAX_OCSP_NONCE_SZ) == 0)
  3212. csr2->request.ocsp[0].nonceSz = MAX_OCSP_NONCE_SZ;
  3213. wc_FreeRng(&rng);
  3214. }
  3215. }
  3216. break;
  3217. }
  3218. /* append new item */
  3219. if ((extension = TLSX_Find(*extensions, TLSX_STATUS_REQUEST_V2))) {
  3220. CertificateStatusRequestItemV2* last =
  3221. (CertificateStatusRequestItemV2*)extension->data;
  3222. for (; last->next; last = last->next);
  3223. last->next = csr2;
  3224. }
  3225. else if ((ret = TLSX_Push(extensions, TLSX_STATUS_REQUEST_V2, csr2,heap))) {
  3226. XFREE(csr2, heap, DYNAMIC_TYPE_TLSX);
  3227. return ret;
  3228. }
  3229. return WOLFSSL_SUCCESS;
  3230. }
  3231. #define CSR2_FREE_ALL TLSX_CSR2_FreeAll
  3232. #define CSR2_GET_SIZE TLSX_CSR2_GetSize
  3233. #define CSR2_WRITE TLSX_CSR2_Write
  3234. #define CSR2_PARSE TLSX_CSR2_Parse
  3235. #else
  3236. #define CSR2_FREE_ALL(data, heap) WC_DO_NOTHING
  3237. #define CSR2_GET_SIZE(a, b) 0
  3238. #define CSR2_WRITE(a, b, c) 0
  3239. #define CSR2_PARSE(a, b, c, d) 0
  3240. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  3241. /******************************************************************************/
  3242. /* Supported Elliptic Curves */
  3243. /******************************************************************************/
  3244. #ifdef HAVE_SUPPORTED_CURVES
  3245. #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) \
  3246. && !defined(HAVE_FFDHE) && !defined(HAVE_PQC)
  3247. #error Elliptic Curves Extension requires Elliptic Curve Cryptography or liboqs groups. \
  3248. Use --enable-ecc and/or --enable-liboqs in the configure script or \
  3249. define HAVE_ECC. Alternatively use FFDHE for DH cipher suites.
  3250. #endif
  3251. static int TLSX_SupportedCurve_New(SupportedCurve** curve, word16 name,
  3252. void* heap)
  3253. {
  3254. if (curve == NULL)
  3255. return BAD_FUNC_ARG;
  3256. (void)heap;
  3257. *curve = (SupportedCurve*)XMALLOC(sizeof(SupportedCurve), heap,
  3258. DYNAMIC_TYPE_TLSX);
  3259. if (*curve == NULL)
  3260. return MEMORY_E;
  3261. (*curve)->name = name;
  3262. (*curve)->next = NULL;
  3263. return 0;
  3264. }
  3265. static int TLSX_PointFormat_New(PointFormat** point, byte format, void* heap)
  3266. {
  3267. if (point == NULL)
  3268. return BAD_FUNC_ARG;
  3269. (void)heap;
  3270. *point = (PointFormat*)XMALLOC(sizeof(PointFormat), heap,
  3271. DYNAMIC_TYPE_TLSX);
  3272. if (*point == NULL)
  3273. return MEMORY_E;
  3274. (*point)->format = format;
  3275. (*point)->next = NULL;
  3276. return 0;
  3277. }
  3278. static void TLSX_SupportedCurve_FreeAll(SupportedCurve* list, void* heap)
  3279. {
  3280. SupportedCurve* curve;
  3281. while ((curve = list)) {
  3282. list = curve->next;
  3283. XFREE(curve, heap, DYNAMIC_TYPE_TLSX);
  3284. }
  3285. (void)heap;
  3286. }
  3287. static void TLSX_PointFormat_FreeAll(PointFormat* list, void* heap)
  3288. {
  3289. PointFormat* point;
  3290. while ((point = list)) {
  3291. list = point->next;
  3292. XFREE(point, heap, DYNAMIC_TYPE_TLSX);
  3293. }
  3294. (void)heap;
  3295. }
  3296. static int TLSX_SupportedCurve_Append(SupportedCurve* list, word16 name,
  3297. void* heap)
  3298. {
  3299. int ret = BAD_FUNC_ARG;
  3300. while (list) {
  3301. if (list->name == name) {
  3302. ret = 0; /* curve already in use */
  3303. break;
  3304. }
  3305. if (list->next == NULL) {
  3306. ret = TLSX_SupportedCurve_New(&list->next, name, heap);
  3307. break;
  3308. }
  3309. list = list->next;
  3310. }
  3311. return ret;
  3312. }
  3313. static int TLSX_PointFormat_Append(PointFormat* list, byte format, void* heap)
  3314. {
  3315. int ret = BAD_FUNC_ARG;
  3316. while (list) {
  3317. if (list->format == format) {
  3318. ret = 0; /* format already in use */
  3319. break;
  3320. }
  3321. if (list->next == NULL) {
  3322. ret = TLSX_PointFormat_New(&list->next, format, heap);
  3323. break;
  3324. }
  3325. list = list->next;
  3326. }
  3327. return ret;
  3328. }
  3329. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  3330. #if defined(HAVE_FFDHE) && (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3331. defined(HAVE_CURVE448))
  3332. static void TLSX_SupportedCurve_ValidateRequest(const WOLFSSL* ssl,
  3333. const byte* semaphore)
  3334. {
  3335. /* If all pre-defined parameter types for key exchange are supported then
  3336. * always send SupportedGroups extension.
  3337. */
  3338. (void)ssl;
  3339. (void)semaphore;
  3340. }
  3341. #else
  3342. static void TLSX_SupportedCurve_ValidateRequest(WOLFSSL* ssl, byte* semaphore)
  3343. {
  3344. word16 i;
  3345. const Suites* suites = WOLFSSL_SUITES(ssl);
  3346. for (i = 0; i < suites->suiteSz; i += 2) {
  3347. if (suites->suites[i] == TLS13_BYTE)
  3348. return;
  3349. #ifdef BUILD_TLS_SM4_GCM_SM3
  3350. if ((suites->suites[i] == CIPHER_BYTE) &&
  3351. (suites->suites[i+1] == TLS_SM4_GCM_SM3))
  3352. return;
  3353. #endif
  3354. #ifdef BUILD_TLS_SM4_CCM_SM3
  3355. if ((suites->suites[i] == CIPHER_BYTE) &&
  3356. (suites->suites[i+1] == TLS_SM4_CCM_SM3))
  3357. return;
  3358. #endif
  3359. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3360. if ((suites->suites[i] == SM_BYTE) &&
  3361. (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3362. return;
  3363. #endif
  3364. if ((suites->suites[i] == ECC_BYTE) ||
  3365. (suites->suites[i] == ECDHE_PSK_BYTE) ||
  3366. (suites->suites[i] == CHACHA_BYTE)) {
  3367. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3368. defined(HAVE_CURVE448)
  3369. return;
  3370. #endif
  3371. }
  3372. #ifdef HAVE_FFDHE
  3373. else {
  3374. return;
  3375. }
  3376. #endif
  3377. }
  3378. /* turns semaphore on to avoid sending this extension. */
  3379. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_GROUPS));
  3380. }
  3381. #endif
  3382. /* Only send PointFormats if TLSv13, ECC or CHACHA cipher suite present.
  3383. */
  3384. static void TLSX_PointFormat_ValidateRequest(WOLFSSL* ssl, byte* semaphore)
  3385. {
  3386. #ifdef HAVE_FFDHE
  3387. (void)ssl;
  3388. (void)semaphore;
  3389. #else
  3390. word16 i;
  3391. const Suites* suites = WOLFSSL_SUITES(ssl);
  3392. if (suites == NULL)
  3393. return;
  3394. for (i = 0; i < suites->suiteSz; i += 2) {
  3395. if (suites->suites[i] == TLS13_BYTE)
  3396. return;
  3397. #ifdef BUILD_TLS_SM4_GCM_SM3
  3398. if ((suites->suites[i] == CIPHER_BYTE) &&
  3399. (suites->suites[i+1] == TLS_SM4_GCM_SM3))
  3400. return;
  3401. #endif
  3402. #ifdef BUILD_TLS_SM4_CCM_SM3
  3403. if ((suites->suites[i] == CIPHER_BYTE) &&
  3404. (suites->suites[i+1] == TLS_SM4_CCM_SM3))
  3405. return;
  3406. #endif
  3407. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3408. if ((suites->suites[i] == SM_BYTE) &&
  3409. (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3410. return;
  3411. #endif
  3412. if ((suites->suites[i] == ECC_BYTE) ||
  3413. (suites->suites[i] == ECDHE_PSK_BYTE) ||
  3414. (suites->suites[i] == CHACHA_BYTE)) {
  3415. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3416. defined(HAVE_CURVE448)
  3417. return;
  3418. #endif
  3419. }
  3420. }
  3421. /* turns semaphore on to avoid sending this extension. */
  3422. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  3423. #endif
  3424. }
  3425. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  3426. #ifndef NO_WOLFSSL_SERVER
  3427. static void TLSX_PointFormat_ValidateResponse(WOLFSSL* ssl, byte* semaphore)
  3428. {
  3429. #if defined(HAVE_FFDHE) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3430. defined(HAVE_CURVE448)
  3431. (void)semaphore;
  3432. #endif
  3433. if (ssl->options.cipherSuite0 == TLS13_BYTE)
  3434. return;
  3435. #ifdef BUILD_TLS_SM4_GCM_SM3
  3436. if ((ssl->options.cipherSuite0 == CIPHER_BYTE) &&
  3437. (ssl->options.cipherSuite == TLS_SM4_GCM_SM3))
  3438. return;
  3439. #endif
  3440. #ifdef BUILD_TLS_SM4_CCM_SM3
  3441. if ((ssl->options.cipherSuite0 == CIPHER_BYTE) &&
  3442. (ssl->options.cipherSuite == TLS_SM4_CCM_SM3))
  3443. return;
  3444. #endif
  3445. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3446. if ((ssl->options.cipherSuite0 == SM_BYTE) &&
  3447. (ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3448. return;
  3449. #endif
  3450. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  3451. if (ssl->options.cipherSuite0 == ECC_BYTE ||
  3452. ssl->options.cipherSuite0 == ECDHE_PSK_BYTE ||
  3453. ssl->options.cipherSuite0 == CHACHA_BYTE) {
  3454. return;
  3455. }
  3456. #endif
  3457. /* turns semaphore on to avoid sending this extension. */
  3458. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  3459. }
  3460. #endif /* !NO_WOLFSSL_SERVER */
  3461. #if !defined(NO_WOLFSSL_CLIENT) || defined(WOLFSSL_TLS13)
  3462. static word16 TLSX_SupportedCurve_GetSize(SupportedCurve* list)
  3463. {
  3464. SupportedCurve* curve;
  3465. word16 length = OPAQUE16_LEN; /* list length */
  3466. while ((curve = list)) {
  3467. list = curve->next;
  3468. length += OPAQUE16_LEN; /* curve length */
  3469. }
  3470. return length;
  3471. }
  3472. #endif
  3473. static word16 TLSX_PointFormat_GetSize(PointFormat* list)
  3474. {
  3475. PointFormat* point;
  3476. word16 length = ENUM_LEN; /* list length */
  3477. while ((point = list)) {
  3478. list = point->next;
  3479. length += ENUM_LEN; /* format length */
  3480. }
  3481. return length;
  3482. }
  3483. #if !defined(NO_WOLFSSL_CLIENT) || defined(WOLFSSL_TLS13)
  3484. static word16 TLSX_SupportedCurve_Write(SupportedCurve* list, byte* output)
  3485. {
  3486. word16 offset = OPAQUE16_LEN;
  3487. while (list) {
  3488. c16toa(list->name, output + offset);
  3489. offset += OPAQUE16_LEN;
  3490. list = list->next;
  3491. }
  3492. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  3493. return offset;
  3494. }
  3495. #endif
  3496. static word16 TLSX_PointFormat_Write(PointFormat* list, byte* output)
  3497. {
  3498. word16 offset = ENUM_LEN;
  3499. while (list) {
  3500. output[offset++] = list->format;
  3501. list = list->next;
  3502. }
  3503. output[0] = (byte)(offset - ENUM_LEN);
  3504. return offset;
  3505. }
  3506. #if !defined(NO_WOLFSSL_SERVER) || (defined(WOLFSSL_TLS13) && \
  3507. !defined(WOLFSSL_NO_SERVER_GROUPS_EXT))
  3508. int TLSX_SupportedCurve_Parse(const WOLFSSL* ssl, const byte* input,
  3509. word16 length, byte isRequest, TLSX** extensions)
  3510. {
  3511. word16 offset;
  3512. word16 name;
  3513. int ret;
  3514. if(!isRequest && !IsAtLeastTLSv1_3(ssl->version)) {
  3515. #ifdef WOLFSSL_ALLOW_SERVER_SC_EXT
  3516. return 0;
  3517. #else
  3518. return BUFFER_ERROR; /* servers doesn't send this extension. */
  3519. #endif
  3520. }
  3521. if (OPAQUE16_LEN > length || length % OPAQUE16_LEN)
  3522. return BUFFER_ERROR;
  3523. ato16(input, &offset);
  3524. /* validating curve list length */
  3525. if (length != OPAQUE16_LEN + offset)
  3526. return BUFFER_ERROR;
  3527. offset = OPAQUE16_LEN;
  3528. if (offset == length)
  3529. return 0;
  3530. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3531. if (!isRequest) {
  3532. TLSX* extension;
  3533. SupportedCurve* curve;
  3534. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  3535. if (extension != NULL) {
  3536. /* Replace client list with server list of supported groups. */
  3537. curve = (SupportedCurve*)extension->data;
  3538. extension->data = NULL;
  3539. TLSX_SupportedCurve_FreeAll(curve, ssl->heap);
  3540. ato16(input + offset, &name);
  3541. offset += OPAQUE16_LEN;
  3542. ret = TLSX_SupportedCurve_New(&curve, name, ssl->heap);
  3543. if (ret != 0)
  3544. return ret; /* throw error */
  3545. extension->data = (void*)curve;
  3546. }
  3547. }
  3548. #endif
  3549. for (; offset < length; offset += OPAQUE16_LEN) {
  3550. ato16(input + offset, &name);
  3551. ret = TLSX_UseSupportedCurve(extensions, name, ssl->heap);
  3552. /* If it is BAD_FUNC_ARG then it is a group we do not support, but
  3553. * that is fine. */
  3554. if (ret != WOLFSSL_SUCCESS && ret != BAD_FUNC_ARG) {
  3555. return ret;
  3556. }
  3557. }
  3558. return 0;
  3559. }
  3560. #endif
  3561. #if !defined(NO_WOLFSSL_SERVER)
  3562. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3563. /* Checks the priority of the groups on the server and set the supported groups
  3564. * response if there is a group not advertised by the client that is preferred.
  3565. *
  3566. * ssl SSL/TLS object.
  3567. * returns 0 on success, otherwise an error.
  3568. */
  3569. int TLSX_SupportedCurve_CheckPriority(WOLFSSL* ssl)
  3570. {
  3571. int ret;
  3572. TLSX* extension;
  3573. TLSX* priority = NULL;
  3574. TLSX* ext = NULL;
  3575. word16 name;
  3576. SupportedCurve* curve;
  3577. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3578. /* May be doing PSK with no key exchange. */
  3579. if (extension == NULL)
  3580. return 0;
  3581. ret = TLSX_PopulateSupportedGroups(ssl, &priority);
  3582. if (ret != WOLFSSL_SUCCESS) {
  3583. TLSX_FreeAll(priority, ssl->heap);
  3584. return ret;
  3585. }
  3586. ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS);
  3587. if (ext == NULL) {
  3588. WOLFSSL_MSG("Could not find supported groups extension");
  3589. TLSX_FreeAll(priority, ssl->heap);
  3590. return 0;
  3591. }
  3592. curve = (SupportedCurve*)ext->data;
  3593. name = curve->name;
  3594. curve = (SupportedCurve*)extension->data;
  3595. while (curve != NULL) {
  3596. if (curve->name == name)
  3597. break;
  3598. curve = curve->next;
  3599. }
  3600. if (curve == NULL) {
  3601. /* Couldn't find the preferred group in client list. */
  3602. extension->resp = 1;
  3603. /* Send server list back and free client list. */
  3604. curve = (SupportedCurve*)extension->data;
  3605. extension->data = ext->data;
  3606. ext->data = curve;
  3607. }
  3608. TLSX_FreeAll(priority, ssl->heap);
  3609. return 0;
  3610. }
  3611. #endif /* WOLFSSL_TLS13 && !WOLFSSL_NO_SERVER_GROUPS_EXT */
  3612. #if defined(HAVE_FFDHE) && !defined(WOLFSSL_NO_TLS12)
  3613. #ifdef HAVE_PUBLIC_FFDHE
  3614. static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup,
  3615. SupportedCurve* serverGroup)
  3616. {
  3617. int ret = 0;
  3618. SupportedCurve* group;
  3619. const DhParams* params = NULL;
  3620. for (; serverGroup != NULL; serverGroup = serverGroup->next) {
  3621. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name))
  3622. continue;
  3623. for (group = clientGroup; group != NULL; group = group->next) {
  3624. if (serverGroup->name != group->name)
  3625. continue;
  3626. switch (serverGroup->name) {
  3627. #ifdef HAVE_FFDHE_2048
  3628. case WOLFSSL_FFDHE_2048:
  3629. params = wc_Dh_ffdhe2048_Get();
  3630. break;
  3631. #endif
  3632. #ifdef HAVE_FFDHE_3072
  3633. case WOLFSSL_FFDHE_3072:
  3634. params = wc_Dh_ffdhe3072_Get();
  3635. break;
  3636. #endif
  3637. #ifdef HAVE_FFDHE_4096
  3638. case WOLFSSL_FFDHE_4096:
  3639. params = wc_Dh_ffdhe4096_Get();
  3640. break;
  3641. #endif
  3642. #ifdef HAVE_FFDHE_6144
  3643. case WOLFSSL_FFDHE_6144:
  3644. params = wc_Dh_ffdhe6144_Get();
  3645. break;
  3646. #endif
  3647. #ifdef HAVE_FFDHE_8192
  3648. case WOLFSSL_FFDHE_8192:
  3649. params = wc_Dh_ffdhe8192_Get();
  3650. break;
  3651. #endif
  3652. default:
  3653. break;
  3654. }
  3655. if (params == NULL) {
  3656. ret = BAD_FUNC_ARG;
  3657. break;
  3658. }
  3659. if (params->p_len >= ssl->options.minDhKeySz &&
  3660. params->p_len <= ssl->options.maxDhKeySz) {
  3661. break;
  3662. }
  3663. }
  3664. if (ret != 0)
  3665. break;
  3666. if ((group != NULL) && (serverGroup->name == group->name))
  3667. break;
  3668. }
  3669. if ((ret == 0) && (serverGroup != NULL) && (params != NULL)) {
  3670. ssl->buffers.serverDH_P.buffer = (unsigned char *)params->p;
  3671. ssl->buffers.serverDH_P.length = params->p_len;
  3672. ssl->buffers.serverDH_G.buffer = (unsigned char *)params->g;
  3673. ssl->buffers.serverDH_G.length = params->g_len;
  3674. ssl->namedGroup = serverGroup->name;
  3675. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  3676. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  3677. ssl->options.dhDoKeyTest = 0;
  3678. #endif
  3679. ssl->options.haveDH = 1;
  3680. }
  3681. return ret;
  3682. }
  3683. #else
  3684. static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup,
  3685. SupportedCurve* serverGroup)
  3686. {
  3687. int ret = 0;
  3688. SupportedCurve* group;
  3689. word32 p_len;
  3690. for (; serverGroup != NULL; serverGroup = serverGroup->next) {
  3691. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name))
  3692. continue;
  3693. for (group = clientGroup; group != NULL; group = group->next) {
  3694. if (serverGroup->name != group->name)
  3695. continue;
  3696. wc_DhGetNamedKeyParamSize(serverGroup->name, &p_len, NULL, NULL);
  3697. if (p_len == 0) {
  3698. ret = BAD_FUNC_ARG;
  3699. break;
  3700. }
  3701. if (p_len >= ssl->options.minDhKeySz &&
  3702. p_len <= ssl->options.maxDhKeySz) {
  3703. break;
  3704. }
  3705. }
  3706. if (ret != 0)
  3707. break;
  3708. if ((group != NULL) && (serverGroup->name == group->name))
  3709. break;
  3710. }
  3711. if ((ret == 0) && (serverGroup != NULL)) {
  3712. word32 pSz, gSz;
  3713. ssl->buffers.serverDH_P.buffer = NULL;
  3714. ssl->buffers.serverDH_G.buffer = NULL;
  3715. ret = wc_DhGetNamedKeyParamSize(serverGroup->name, &pSz, &gSz, NULL);
  3716. if (ret == 0) {
  3717. ssl->buffers.serverDH_P.buffer =
  3718. (byte*)XMALLOC(pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  3719. if (ssl->buffers.serverDH_P.buffer == NULL)
  3720. ret = MEMORY_E;
  3721. else
  3722. ssl->buffers.serverDH_P.length = pSz;
  3723. }
  3724. if (ret == 0) {
  3725. ssl->buffers.serverDH_G.buffer =
  3726. (byte*)XMALLOC(gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  3727. if (ssl->buffers.serverDH_G.buffer == NULL) {
  3728. ret = MEMORY_E;
  3729. } else
  3730. ssl->buffers.serverDH_G.length = gSz;
  3731. }
  3732. if (ret == 0) {
  3733. ret = wc_DhCopyNamedKey(serverGroup->name,
  3734. ssl->buffers.serverDH_P.buffer, &pSz,
  3735. ssl->buffers.serverDH_G.buffer, &gSz,
  3736. NULL, NULL);
  3737. }
  3738. if (ret == 0) {
  3739. ssl->buffers.weOwnDH = 1;
  3740. ssl->namedGroup = serverGroup->name;
  3741. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  3742. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  3743. ssl->options.dhDoKeyTest = 0;
  3744. #endif
  3745. ssl->options.haveDH = 1;
  3746. }
  3747. else {
  3748. if (ssl->buffers.serverDH_P.buffer != NULL) {
  3749. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  3750. DYNAMIC_TYPE_PUBLIC_KEY);
  3751. ssl->buffers.serverDH_P.length = 0;
  3752. ssl->buffers.serverDH_P.buffer = NULL;
  3753. }
  3754. if (ssl->buffers.serverDH_G.buffer != NULL) {
  3755. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  3756. DYNAMIC_TYPE_PUBLIC_KEY);
  3757. ssl->buffers.serverDH_G.length = 0;
  3758. ssl->buffers.serverDH_G.buffer = NULL;
  3759. }
  3760. }
  3761. }
  3762. return ret;
  3763. }
  3764. #endif
  3765. /* Set the highest priority common FFDHE group on the server as compared to
  3766. * client extensions.
  3767. *
  3768. * ssl SSL/TLS object.
  3769. * returns 0 on success, otherwise an error.
  3770. */
  3771. int TLSX_SupportedFFDHE_Set(WOLFSSL* ssl)
  3772. {
  3773. int ret;
  3774. TLSX* priority = NULL;
  3775. TLSX* ext = NULL;
  3776. TLSX* extension;
  3777. SupportedCurve* clientGroup;
  3778. SupportedCurve* group;
  3779. int found = 0;
  3780. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3781. /* May be doing PSK with no key exchange. */
  3782. if (extension == NULL)
  3783. return 0;
  3784. clientGroup = (SupportedCurve*)extension->data;
  3785. for (group = clientGroup; group != NULL; group = group->next) {
  3786. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(group->name)) {
  3787. found = 1;
  3788. break;
  3789. }
  3790. }
  3791. if (!found)
  3792. return 0;
  3793. if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
  3794. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  3795. DYNAMIC_TYPE_PUBLIC_KEY);
  3796. }
  3797. if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
  3798. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  3799. DYNAMIC_TYPE_PUBLIC_KEY);
  3800. }
  3801. ssl->buffers.serverDH_P.buffer = NULL;
  3802. ssl->buffers.serverDH_G.buffer = NULL;
  3803. ssl->buffers.weOwnDH = 0;
  3804. ssl->options.haveDH = 0;
  3805. ret = TLSX_PopulateSupportedGroups(ssl, &priority);
  3806. if (ret == WOLFSSL_SUCCESS) {
  3807. SupportedCurve* serverGroup;
  3808. ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS);
  3809. serverGroup = (SupportedCurve*)ext->data;
  3810. ret = tlsx_ffdhe_find_group(ssl, clientGroup, serverGroup);
  3811. }
  3812. TLSX_FreeAll(priority, ssl->heap);
  3813. return ret;
  3814. }
  3815. #endif /* HAVE_FFDHE && !WOLFSSL_NO_TLS12 */
  3816. #endif /* !NO_WOLFSSL_SERVER */
  3817. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3818. /* Return the preferred group.
  3819. *
  3820. * ssl SSL/TLS object.
  3821. * checkSupported Whether to check for the first supported group.
  3822. * returns BAD_FUNC_ARG if no group found, otherwise the group.
  3823. */
  3824. int TLSX_SupportedCurve_Preferred(WOLFSSL* ssl, int checkSupported)
  3825. {
  3826. TLSX* extension;
  3827. SupportedCurve* curve;
  3828. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3829. if (extension == NULL)
  3830. return BAD_FUNC_ARG;
  3831. curve = (SupportedCurve*)extension->data;
  3832. while (curve != NULL) {
  3833. if (!checkSupported || TLSX_KeyShare_IsSupported(curve->name))
  3834. return curve->name;
  3835. curve = curve->next;
  3836. }
  3837. return BAD_FUNC_ARG;
  3838. }
  3839. #endif /* HAVE_SUPPORTED_CURVES */
  3840. #ifndef NO_WOLFSSL_SERVER
  3841. static int TLSX_PointFormat_Parse(WOLFSSL* ssl, const byte* input,
  3842. word16 length, byte isRequest)
  3843. {
  3844. int ret;
  3845. /* validating formats list length */
  3846. if (ENUM_LEN > length || length != (word16)ENUM_LEN + input[0])
  3847. return BUFFER_ERROR;
  3848. if (isRequest) {
  3849. /* adding uncompressed point format to response */
  3850. ret = TLSX_UsePointFormat(&ssl->extensions, WOLFSSL_EC_PF_UNCOMPRESSED,
  3851. ssl->heap);
  3852. if (ret != WOLFSSL_SUCCESS)
  3853. return ret; /* throw error */
  3854. TLSX_SetResponse(ssl, TLSX_EC_POINT_FORMATS);
  3855. }
  3856. return 0;
  3857. }
  3858. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  3859. int TLSX_ValidateSupportedCurves(const WOLFSSL* ssl, byte first, byte second,
  3860. word32* ecdhCurveOID) {
  3861. TLSX* extension = NULL;
  3862. SupportedCurve* curve = NULL;
  3863. word32 oid = 0;
  3864. word32 defOid = 0;
  3865. word32 defSz = 80; /* Maximum known curve size is 66. */
  3866. word32 nextOid = 0;
  3867. word32 nextSz = 80; /* Maximum known curve size is 66. */
  3868. word32 currOid = ssl->ecdhCurveOID;
  3869. int ephmSuite = 0;
  3870. word16 octets = 0; /* according to 'ecc_set_type ecc_sets[];' */
  3871. int key = 0; /* validate key */
  3872. (void)oid;
  3873. if (first == CHACHA_BYTE) {
  3874. switch (second) {
  3875. case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
  3876. case TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3877. case TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3878. case TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256:
  3879. return 1; /* no suite restriction */
  3880. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
  3881. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256:
  3882. case TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3883. break;
  3884. }
  3885. }
  3886. if (first == ECC_BYTE || first == ECDHE_PSK_BYTE || first == CHACHA_BYTE)
  3887. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3888. if (!extension)
  3889. return 1; /* no suite restriction */
  3890. for (curve = (SupportedCurve*)extension->data;
  3891. curve && !key;
  3892. curve = curve->next) {
  3893. #ifdef OPENSSL_EXTRA
  3894. /* skip if name is not in supported ECC range
  3895. * or disabled by user */
  3896. if (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. /* In TLS 1.2 the server never sends supported curve extension, but in TLS 1.3
  4270. * the server can send supported groups extension to indicate what it will
  4271. * support for later connections. */
  4272. #if !defined(NO_WOLFSSL_CLIENT) || defined(WOLFSSL_TLS13)
  4273. #define EC_GET_SIZE TLSX_SupportedCurve_GetSize
  4274. #define EC_WRITE TLSX_SupportedCurve_Write
  4275. #else
  4276. #define EC_GET_SIZE(list) 0
  4277. #define EC_WRITE(a, b) 0
  4278. #endif
  4279. #if !defined(NO_WOLFSSL_SERVER) || (defined(WOLFSSL_TLS13) && \
  4280. !defined(WOLFSSL_NO_SERVER_GROUPS_EXT))
  4281. #define EC_PARSE TLSX_SupportedCurve_Parse
  4282. #else
  4283. #define EC_PARSE(a, b, c, d, e) 0
  4284. #endif
  4285. #define PF_FREE_ALL TLSX_PointFormat_FreeAll
  4286. #define PF_VALIDATE_REQUEST TLSX_PointFormat_ValidateRequest
  4287. #define PF_VALIDATE_RESPONSE TLSX_PointFormat_ValidateResponse
  4288. #define PF_GET_SIZE TLSX_PointFormat_GetSize
  4289. #define PF_WRITE TLSX_PointFormat_Write
  4290. #ifndef NO_WOLFSSL_SERVER
  4291. #define PF_PARSE TLSX_PointFormat_Parse
  4292. #else
  4293. #define PF_PARSE(a, b, c, d) 0
  4294. #endif
  4295. #else
  4296. #define EC_FREE_ALL(list, heap) WC_DO_NOTHING
  4297. #define EC_GET_SIZE(list) 0
  4298. #define EC_WRITE(a, b) 0
  4299. #define EC_PARSE(a, b, c, d, e) 0
  4300. #define EC_VALIDATE_REQUEST(a, b) WC_DO_NOTHING
  4301. #define PF_FREE_ALL(list, heap) WC_DO_NOTHING
  4302. #define PF_GET_SIZE(list) 0
  4303. #define PF_WRITE(a, b) 0
  4304. #define PF_PARSE(a, b, c, d) 0
  4305. #define PF_VALIDATE_REQUEST(a, b) WC_DO_NOTHING
  4306. #define PF_VALIDATE_RESPONSE(a, b) WC_DO_NOTHING
  4307. #endif /* HAVE_SUPPORTED_CURVES */
  4308. /******************************************************************************/
  4309. /* Renegotiation Indication */
  4310. /******************************************************************************/
  4311. #if defined(HAVE_SECURE_RENEGOTIATION) \
  4312. || defined(HAVE_SERVER_RENEGOTIATION_INFO)
  4313. static byte TLSX_SecureRenegotiation_GetSize(SecureRenegotiation* data,
  4314. int isRequest)
  4315. {
  4316. byte length = OPAQUE8_LEN; /* empty info length */
  4317. /* data will be NULL for HAVE_SERVER_RENEGOTIATION_INFO only */
  4318. if (data && data->enabled && data->verifySet) {
  4319. /* client sends client_verify_data only */
  4320. length += TLS_FINISHED_SZ;
  4321. /* server also sends server_verify_data */
  4322. if (!isRequest)
  4323. length += TLS_FINISHED_SZ;
  4324. }
  4325. return length;
  4326. }
  4327. static word16 TLSX_SecureRenegotiation_Write(SecureRenegotiation* data,
  4328. byte* output, int isRequest)
  4329. {
  4330. word16 offset = OPAQUE8_LEN; /* RenegotiationInfo length */
  4331. if (data && data->enabled && data->verifySet) {
  4332. /* client sends client_verify_data only */
  4333. XMEMCPY(output + offset, data->client_verify_data, TLS_FINISHED_SZ);
  4334. offset += TLS_FINISHED_SZ;
  4335. /* server also sends server_verify_data */
  4336. if (!isRequest) {
  4337. XMEMCPY(output + offset, data->server_verify_data, TLS_FINISHED_SZ);
  4338. offset += TLS_FINISHED_SZ;
  4339. }
  4340. }
  4341. output[0] = (byte)(offset - 1); /* info length - self */
  4342. return offset;
  4343. }
  4344. static int TLSX_SecureRenegotiation_Parse(WOLFSSL* ssl, const byte* input,
  4345. word16 length, byte isRequest)
  4346. {
  4347. int ret = SECURE_RENEGOTIATION_E;
  4348. if (length >= OPAQUE8_LEN) {
  4349. if (isRequest) {
  4350. #ifndef NO_WOLFSSL_SERVER
  4351. if (ssl->secure_renegotiation == NULL) {
  4352. ret = wolfSSL_UseSecureRenegotiation(ssl);
  4353. if (ret == WOLFSSL_SUCCESS)
  4354. ret = 0;
  4355. }
  4356. if (ret != 0 && ret != SECURE_RENEGOTIATION_E) {
  4357. }
  4358. else if (ssl->secure_renegotiation == NULL) {
  4359. }
  4360. else if (!ssl->secure_renegotiation->enabled) {
  4361. if (*input == 0) {
  4362. input++; /* get past size */
  4363. ssl->secure_renegotiation->enabled = 1;
  4364. TLSX_SetResponse(ssl, TLSX_RENEGOTIATION_INFO);
  4365. ret = 0;
  4366. }
  4367. else {
  4368. /* already in error state */
  4369. WOLFSSL_MSG("SCR client verify data present");
  4370. }
  4371. }
  4372. else if (*input == TLS_FINISHED_SZ) {
  4373. if (length < TLS_FINISHED_SZ + 1) {
  4374. WOLFSSL_MSG("SCR malformed buffer");
  4375. ret = BUFFER_E;
  4376. }
  4377. else {
  4378. input++; /* get past size */
  4379. /* validate client verify data */
  4380. if (XMEMCMP(input,
  4381. ssl->secure_renegotiation->client_verify_data,
  4382. TLS_FINISHED_SZ) == 0) {
  4383. WOLFSSL_MSG("SCR client verify data match");
  4384. TLSX_SetResponse(ssl, TLSX_RENEGOTIATION_INFO);
  4385. ret = 0; /* verified */
  4386. }
  4387. else {
  4388. /* already in error state */
  4389. WOLFSSL_MSG("SCR client verify data Failure");
  4390. }
  4391. }
  4392. }
  4393. #endif
  4394. }
  4395. else if (ssl->secure_renegotiation != NULL) {
  4396. #ifndef NO_WOLFSSL_CLIENT
  4397. if (!ssl->secure_renegotiation->enabled) {
  4398. if (*input == 0) {
  4399. ssl->secure_renegotiation->enabled = 1;
  4400. ret = 0;
  4401. }
  4402. }
  4403. else if (*input == 2 * TLS_FINISHED_SZ &&
  4404. length == 2 * TLS_FINISHED_SZ + OPAQUE8_LEN) {
  4405. input++; /* get past size */
  4406. /* validate client and server verify data */
  4407. if (XMEMCMP(input,
  4408. ssl->secure_renegotiation->client_verify_data,
  4409. TLS_FINISHED_SZ) == 0 &&
  4410. XMEMCMP(input + TLS_FINISHED_SZ,
  4411. ssl->secure_renegotiation->server_verify_data,
  4412. TLS_FINISHED_SZ) == 0) {
  4413. WOLFSSL_MSG("SCR client and server verify data match");
  4414. ret = 0; /* verified */
  4415. }
  4416. else {
  4417. /* already in error state */
  4418. WOLFSSL_MSG("SCR client and server verify data Failure");
  4419. }
  4420. }
  4421. #endif
  4422. }
  4423. }
  4424. if (ret != 0) {
  4425. WOLFSSL_ERROR_VERBOSE(ret);
  4426. SendAlert(ssl, alert_fatal, handshake_failure);
  4427. }
  4428. return ret;
  4429. }
  4430. int TLSX_UseSecureRenegotiation(TLSX** extensions, void* heap)
  4431. {
  4432. int ret = 0;
  4433. SecureRenegotiation* data;
  4434. data = (SecureRenegotiation*)XMALLOC(sizeof(SecureRenegotiation), heap,
  4435. DYNAMIC_TYPE_TLSX);
  4436. if (data == NULL)
  4437. return MEMORY_E;
  4438. XMEMSET(data, 0, sizeof(SecureRenegotiation));
  4439. ret = TLSX_Push(extensions, TLSX_RENEGOTIATION_INFO, data, heap);
  4440. if (ret != 0) {
  4441. XFREE(data, heap, DYNAMIC_TYPE_TLSX);
  4442. return ret;
  4443. }
  4444. return WOLFSSL_SUCCESS;
  4445. }
  4446. #ifdef HAVE_SERVER_RENEGOTIATION_INFO
  4447. int TLSX_AddEmptyRenegotiationInfo(TLSX** extensions, void* heap)
  4448. {
  4449. int ret;
  4450. /* send empty renegotiation_info extension */
  4451. TLSX* ext = TLSX_Find(*extensions, TLSX_RENEGOTIATION_INFO);
  4452. if (ext == NULL) {
  4453. ret = TLSX_UseSecureRenegotiation(extensions, heap);
  4454. if (ret != WOLFSSL_SUCCESS)
  4455. return ret;
  4456. ext = TLSX_Find(*extensions, TLSX_RENEGOTIATION_INFO);
  4457. }
  4458. if (ext)
  4459. ext->resp = 1;
  4460. return WOLFSSL_SUCCESS;
  4461. }
  4462. #endif /* HAVE_SERVER_RENEGOTIATION_INFO */
  4463. #define SCR_FREE_ALL(data, heap) XFREE(data, (heap), DYNAMIC_TYPE_TLSX)
  4464. #define SCR_GET_SIZE TLSX_SecureRenegotiation_GetSize
  4465. #define SCR_WRITE TLSX_SecureRenegotiation_Write
  4466. #define SCR_PARSE TLSX_SecureRenegotiation_Parse
  4467. #else
  4468. #define SCR_FREE_ALL(a, heap) WC_DO_NOTHING
  4469. #define SCR_GET_SIZE(a, b) 0
  4470. #define SCR_WRITE(a, b, c) 0
  4471. #define SCR_PARSE(a, b, c, d) 0
  4472. #endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
  4473. /******************************************************************************/
  4474. /* Session Tickets */
  4475. /******************************************************************************/
  4476. #ifdef HAVE_SESSION_TICKET
  4477. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  4478. static void TLSX_SessionTicket_ValidateRequest(WOLFSSL* ssl)
  4479. {
  4480. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_SESSION_TICKET);
  4481. SessionTicket* ticket = extension ?
  4482. (SessionTicket*)extension->data : NULL;
  4483. if (ticket) {
  4484. /* TODO validate ticket timeout here! */
  4485. if (ticket->lifetime == 0xfffffff) {
  4486. /* send empty ticket on timeout */
  4487. TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4488. }
  4489. }
  4490. }
  4491. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  4492. static word16 TLSX_SessionTicket_GetSize(SessionTicket* ticket, int isRequest)
  4493. {
  4494. (void)isRequest;
  4495. return ticket ? ticket->size : 0;
  4496. }
  4497. static word16 TLSX_SessionTicket_Write(SessionTicket* ticket, byte* output,
  4498. int isRequest)
  4499. {
  4500. word16 offset = 0; /* empty ticket */
  4501. if (isRequest && ticket) {
  4502. XMEMCPY(output + offset, ticket->data, ticket->size);
  4503. offset += ticket->size;
  4504. }
  4505. return offset;
  4506. }
  4507. static int TLSX_SessionTicket_Parse(WOLFSSL* ssl, const byte* input,
  4508. word16 length, byte isRequest)
  4509. {
  4510. int ret = 0;
  4511. (void) input; /* avoid unused parameter if NO_WOLFSSL_SERVER defined */
  4512. if (!isRequest) {
  4513. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_SESSION_TICKET))
  4514. return TLSX_HandleUnsupportedExtension(ssl);
  4515. if (length != 0)
  4516. return BUFFER_ERROR;
  4517. #ifndef NO_WOLFSSL_CLIENT
  4518. ssl->expect_session_ticket = 1;
  4519. #endif
  4520. }
  4521. #ifndef NO_WOLFSSL_SERVER
  4522. else {
  4523. /* server side */
  4524. if (ssl->ctx->ticketEncCb == NULL) {
  4525. WOLFSSL_MSG("Client sent session ticket, server has no callback");
  4526. return 0;
  4527. }
  4528. #ifdef HAVE_SECURE_RENEGOTIATION
  4529. if (IsSCR(ssl)) {
  4530. WOLFSSL_MSG("Client sent session ticket during SCR. Ignoring.");
  4531. return 0;
  4532. }
  4533. #endif
  4534. if (length > SESSION_TICKET_LEN) {
  4535. ret = BAD_TICKET_MSG_SZ;
  4536. WOLFSSL_ERROR_VERBOSE(ret);
  4537. } else if (IsAtLeastTLSv1_3(ssl->version)) {
  4538. WOLFSSL_MSG("Process client ticket rejected, TLS 1.3 no support");
  4539. ssl->options.rejectTicket = 1;
  4540. ret = 0; /* not fatal */
  4541. } else if (ssl->options.noTicketTls12) {
  4542. /* ignore ticket request */
  4543. } else if (length == 0) {
  4544. /* blank ticket */
  4545. ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4546. if (ret == WOLFSSL_SUCCESS) {
  4547. ret = 0;
  4548. /* send blank ticket */
  4549. TLSX_SetResponse(ssl, TLSX_SESSION_TICKET);
  4550. ssl->options.createTicket = 1; /* will send ticket msg */
  4551. ssl->options.useTicket = 1;
  4552. ssl->options.resuming = 0; /* no standard resumption */
  4553. ssl->arrays->sessionIDSz = 0; /* no echo on blank ticket */
  4554. }
  4555. } else {
  4556. /* got actual ticket from client */
  4557. ret = DoClientTicket(ssl, input, length);
  4558. if (ret == WOLFSSL_TICKET_RET_OK) { /* use ticket to resume */
  4559. WOLFSSL_MSG("Using existing client ticket");
  4560. ssl->options.useTicket = 1;
  4561. ssl->options.resuming = 1;
  4562. /* SERVER: ticket is peer auth. */
  4563. ssl->options.peerAuthGood = 1;
  4564. } else if (ret == WOLFSSL_TICKET_RET_CREATE) {
  4565. WOLFSSL_MSG("Using existing client ticket, creating new one");
  4566. ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4567. if (ret == WOLFSSL_SUCCESS) {
  4568. ret = 0;
  4569. TLSX_SetResponse(ssl, TLSX_SESSION_TICKET);
  4570. /* send blank ticket */
  4571. ssl->options.createTicket = 1; /* will send ticket msg */
  4572. ssl->options.useTicket = 1;
  4573. ssl->options.resuming = 1;
  4574. /* SERVER: ticket is peer auth. */
  4575. ssl->options.peerAuthGood = 1;
  4576. }
  4577. } else if (ret == WOLFSSL_TICKET_RET_REJECT) {
  4578. WOLFSSL_MSG("Process client ticket rejected, not using");
  4579. ssl->options.rejectTicket = 1;
  4580. ret = 0; /* not fatal */
  4581. } else if (ret == VERSION_ERROR) {
  4582. WOLFSSL_MSG("Process client ticket rejected, bad TLS version");
  4583. ssl->options.rejectTicket = 1;
  4584. ret = 0; /* not fatal */
  4585. } else if (ret == WOLFSSL_TICKET_RET_FATAL) {
  4586. WOLFSSL_MSG("Process client ticket fatal error, not using");
  4587. } else if (ret < 0) {
  4588. WOLFSSL_MSG("Process client ticket unknown error, not using");
  4589. }
  4590. }
  4591. }
  4592. #endif /* NO_WOLFSSL_SERVER */
  4593. #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER)
  4594. (void)ssl;
  4595. #endif
  4596. return ret;
  4597. }
  4598. WOLFSSL_LOCAL SessionTicket* TLSX_SessionTicket_Create(word32 lifetime,
  4599. byte* data, word16 size, void* heap)
  4600. {
  4601. SessionTicket* ticket = (SessionTicket*)XMALLOC(sizeof(SessionTicket),
  4602. heap, DYNAMIC_TYPE_TLSX);
  4603. if (ticket) {
  4604. ticket->data = (byte*)XMALLOC(size, heap, DYNAMIC_TYPE_TLSX);
  4605. if (ticket->data == NULL) {
  4606. XFREE(ticket, heap, DYNAMIC_TYPE_TLSX);
  4607. return NULL;
  4608. }
  4609. XMEMCPY(ticket->data, data, size);
  4610. ticket->size = size;
  4611. ticket->lifetime = lifetime;
  4612. }
  4613. (void)heap;
  4614. return ticket;
  4615. }
  4616. WOLFSSL_LOCAL void TLSX_SessionTicket_Free(SessionTicket* ticket, void* heap)
  4617. {
  4618. if (ticket) {
  4619. XFREE(ticket->data, heap, DYNAMIC_TYPE_TLSX);
  4620. XFREE(ticket, heap, DYNAMIC_TYPE_TLSX);
  4621. }
  4622. (void)heap;
  4623. }
  4624. int TLSX_UseSessionTicket(TLSX** extensions, SessionTicket* ticket, void* heap)
  4625. {
  4626. int ret = 0;
  4627. if (extensions == NULL)
  4628. return BAD_FUNC_ARG;
  4629. /* If the ticket is NULL, the client will request a new ticket from the
  4630. server. Otherwise, the client will use it in the next client hello. */
  4631. if ((ret = TLSX_Push(extensions, TLSX_SESSION_TICKET, (void*)ticket, heap))
  4632. != 0)
  4633. return ret;
  4634. return WOLFSSL_SUCCESS;
  4635. }
  4636. #define WOLF_STK_VALIDATE_REQUEST TLSX_SessionTicket_ValidateRequest
  4637. #define WOLF_STK_GET_SIZE TLSX_SessionTicket_GetSize
  4638. #define WOLF_STK_WRITE TLSX_SessionTicket_Write
  4639. #define WOLF_STK_PARSE TLSX_SessionTicket_Parse
  4640. #define WOLF_STK_FREE(stk, heap) TLSX_SessionTicket_Free((SessionTicket*)(stk),(heap))
  4641. #else
  4642. #define WOLF_STK_FREE(a, b) WC_DO_NOTHING
  4643. #define WOLF_STK_VALIDATE_REQUEST(a) WC_DO_NOTHING
  4644. #define WOLF_STK_GET_SIZE(a, b) 0
  4645. #define WOLF_STK_WRITE(a, b, c) 0
  4646. #define WOLF_STK_PARSE(a, b, c, d) 0
  4647. #endif /* HAVE_SESSION_TICKET */
  4648. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  4649. /******************************************************************************/
  4650. /* Encrypt-then-MAC */
  4651. /******************************************************************************/
  4652. #ifndef WOLFSSL_NO_TLS12
  4653. static int TLSX_EncryptThenMac_Use(WOLFSSL* ssl);
  4654. /**
  4655. * Get the size of the Encrypt-Then-MAC extension.
  4656. *
  4657. * msgType Type of message to put extension into.
  4658. * pSz Size of extension data.
  4659. * return SANITY_MSG_E when the message is not allowed to have extension and
  4660. * 0 otherwise.
  4661. */
  4662. static int TLSX_EncryptThenMac_GetSize(byte msgType, word16* pSz)
  4663. {
  4664. (void)pSz;
  4665. if (msgType != client_hello && msgType != server_hello) {
  4666. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4667. return SANITY_MSG_E;
  4668. }
  4669. /* Empty extension */
  4670. return 0;
  4671. }
  4672. /**
  4673. * Write the Encrypt-Then-MAC extension.
  4674. *
  4675. * data Unused
  4676. * output Extension data buffer. Unused.
  4677. * msgType Type of message to put extension into.
  4678. * pSz Size of extension data.
  4679. * return SANITY_MSG_E when the message is not allowed to have extension and
  4680. * 0 otherwise.
  4681. */
  4682. static int TLSX_EncryptThenMac_Write(void* data, byte* output, byte msgType,
  4683. word16* pSz)
  4684. {
  4685. (void)data;
  4686. (void)output;
  4687. (void)pSz;
  4688. if (msgType != client_hello && msgType != server_hello) {
  4689. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4690. return SANITY_MSG_E;
  4691. }
  4692. /* Empty extension */
  4693. return 0;
  4694. }
  4695. /**
  4696. * Parse the Encrypt-Then-MAC extension.
  4697. *
  4698. * ssl SSL object
  4699. * input Extension data buffer.
  4700. * length Length of this extension's data.
  4701. * msgType Type of message to extension appeared in.
  4702. * return SANITY_MSG_E when the message is not allowed to have extension,
  4703. * BUFFER_ERROR when the extension's data is invalid,
  4704. * MEMORY_E when unable to allocate memory and
  4705. * 0 otherwise.
  4706. */
  4707. static int TLSX_EncryptThenMac_Parse(WOLFSSL* ssl, const byte* input,
  4708. word16 length, byte msgType)
  4709. {
  4710. int ret;
  4711. (void)input;
  4712. if (msgType != client_hello && msgType != server_hello) {
  4713. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4714. return SANITY_MSG_E;
  4715. }
  4716. /* Empty extension */
  4717. if (length != 0)
  4718. return BUFFER_ERROR;
  4719. if (msgType == client_hello) {
  4720. /* Check the user hasn't disallowed use of Encrypt-Then-Mac. */
  4721. if (!ssl->options.disallowEncThenMac) {
  4722. ssl->options.encThenMac = 1;
  4723. /* Set the extension reply. */
  4724. ret = TLSX_EncryptThenMac_Use(ssl);
  4725. if (ret != 0)
  4726. return ret;
  4727. }
  4728. return 0;
  4729. }
  4730. /* Server Hello */
  4731. if (ssl->options.disallowEncThenMac) {
  4732. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4733. return SANITY_MSG_E;
  4734. }
  4735. ssl->options.encThenMac = 1;
  4736. return 0;
  4737. }
  4738. /**
  4739. * Add the Encrypt-Then-MAC extension to list.
  4740. *
  4741. * ssl SSL object
  4742. * return MEMORY_E when unable to allocate memory and 0 otherwise.
  4743. */
  4744. static int TLSX_EncryptThenMac_Use(WOLFSSL* ssl)
  4745. {
  4746. int ret = 0;
  4747. TLSX* extension;
  4748. /* Find the Encrypt-Then-Mac extension if it exists. */
  4749. extension = TLSX_Find(ssl->extensions, TLSX_ENCRYPT_THEN_MAC);
  4750. if (extension == NULL) {
  4751. /* Push new Encrypt-Then-Mac extension. */
  4752. ret = TLSX_Push(&ssl->extensions, TLSX_ENCRYPT_THEN_MAC, NULL,
  4753. ssl->heap);
  4754. if (ret != 0)
  4755. return ret;
  4756. }
  4757. return 0;
  4758. }
  4759. /**
  4760. * Set the Encrypt-Then-MAC extension as one to respond too.
  4761. *
  4762. * ssl SSL object
  4763. * return EXT_MISSING when EncryptThenMac extension not in list.
  4764. */
  4765. int TLSX_EncryptThenMac_Respond(WOLFSSL* ssl)
  4766. {
  4767. TLSX* extension;
  4768. extension = TLSX_Find(ssl->extensions, TLSX_ENCRYPT_THEN_MAC);
  4769. if (extension == NULL)
  4770. return EXT_MISSING;
  4771. extension->resp = 1;
  4772. return 0;
  4773. }
  4774. #define ETM_GET_SIZE TLSX_EncryptThenMac_GetSize
  4775. #define ETM_WRITE TLSX_EncryptThenMac_Write
  4776. #define ETM_PARSE TLSX_EncryptThenMac_Parse
  4777. #else
  4778. #define ETM_GET_SIZE(a, b) 0
  4779. #define ETM_WRITE(a, b, c, d) 0
  4780. #define ETM_PARSE(a, b, c, d) 0
  4781. #endif /* !WOLFSSL_NO_TLS12 */
  4782. #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */
  4783. #ifdef WOLFSSL_SRTP
  4784. /******************************************************************************/
  4785. /* DTLS SRTP (Secure Real-time Transport Protocol) */
  4786. /******************************************************************************/
  4787. /* Only support single SRTP profile */
  4788. typedef struct TlsxSrtp {
  4789. word16 profileCount;
  4790. word16 ids; /* selected bits */
  4791. } TlsxSrtp;
  4792. static int TLSX_UseSRTP_GetSize(TlsxSrtp *srtp)
  4793. {
  4794. /* SRTP Profile Len (2)
  4795. * SRTP Profiles (2)
  4796. * MKI (master key id) Length */
  4797. return (OPAQUE16_LEN + (srtp->profileCount * OPAQUE16_LEN) + 1);
  4798. }
  4799. static TlsxSrtp* TLSX_UseSRTP_New(word16 ids, void* heap)
  4800. {
  4801. TlsxSrtp* srtp;
  4802. int i;
  4803. srtp = (TlsxSrtp*)XMALLOC(sizeof(TlsxSrtp), heap, DYNAMIC_TYPE_TLSX);
  4804. if (srtp == NULL) {
  4805. WOLFSSL_MSG("TLSX SRTP Memory failure");
  4806. return NULL;
  4807. }
  4808. /* count and test each bit set */
  4809. srtp->profileCount = 0;
  4810. for (i=0; i<16; i++) {
  4811. if (ids & (1 << i)) {
  4812. srtp->profileCount++;
  4813. }
  4814. }
  4815. srtp->ids = ids;
  4816. return srtp;
  4817. }
  4818. static void TLSX_UseSRTP_Free(TlsxSrtp *srtp, void* heap)
  4819. {
  4820. if (srtp != NULL) {
  4821. XFREE(srtp, heap, DYNAMIC_TYPE_TLSX);
  4822. }
  4823. (void)heap;
  4824. }
  4825. static int TLSX_UseSRTP_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  4826. byte isRequest)
  4827. {
  4828. int ret = BAD_FUNC_ARG;
  4829. word16 profile_len = 0;
  4830. word16 profile_value = 0;
  4831. word16 offset = 0;
  4832. #ifndef NO_WOLFSSL_SERVER
  4833. int i;
  4834. TlsxSrtp* srtp = NULL;
  4835. #endif
  4836. if (length < OPAQUE16_LEN) {
  4837. return BUFFER_ERROR;
  4838. }
  4839. /* reset selected DTLS SRTP profile ID */
  4840. ssl->dtlsSrtpId = 0;
  4841. /* total length, not include itself */
  4842. ato16(input, &profile_len);
  4843. offset += OPAQUE16_LEN;
  4844. if (!isRequest) {
  4845. #ifndef NO_WOLFSSL_CLIENT
  4846. if (length < offset + OPAQUE16_LEN)
  4847. return BUFFER_ERROR;
  4848. ato16(input + offset, &profile_value);
  4849. /* check that the profile received was in the ones we support */
  4850. if (profile_value < 16 &&
  4851. (ssl->dtlsSrtpProfiles & (1 << profile_value))) {
  4852. ssl->dtlsSrtpId = profile_value;
  4853. ret = 0; /* success */
  4854. }
  4855. #endif
  4856. }
  4857. #ifndef NO_WOLFSSL_SERVER
  4858. else {
  4859. /* parse remainder one profile at a time, looking for match in CTX */
  4860. ret = 0;
  4861. for (i=offset; i<length; i+=OPAQUE16_LEN) {
  4862. if (length < (i + OPAQUE16_LEN)) {
  4863. WOLFSSL_MSG("Unexpected length when parsing SRTP profile");
  4864. ret = BUFFER_ERROR;
  4865. break;
  4866. }
  4867. ato16(input+i, &profile_value);
  4868. /* find first match */
  4869. if (profile_value < 16 &&
  4870. ssl->dtlsSrtpProfiles & (1 << profile_value)) {
  4871. ssl->dtlsSrtpId = profile_value;
  4872. /* make sure we respond with selected SRTP id selected */
  4873. srtp = TLSX_UseSRTP_New((1 << profile_value), ssl->heap);
  4874. if (srtp != NULL) {
  4875. ret = TLSX_Push(&ssl->extensions, TLSX_USE_SRTP,
  4876. (void*)srtp, ssl->heap);
  4877. if (ret == 0) {
  4878. TLSX_SetResponse(ssl, TLSX_USE_SRTP);
  4879. /* successfully set extension */
  4880. }
  4881. }
  4882. else {
  4883. ret = MEMORY_E;
  4884. }
  4885. break;
  4886. }
  4887. }
  4888. }
  4889. if (ret == 0 && ssl->dtlsSrtpId == 0) {
  4890. WOLFSSL_MSG("TLSX_UseSRTP_Parse profile not found!");
  4891. /* not fatal */
  4892. }
  4893. else if (ret != 0) {
  4894. ssl->dtlsSrtpId = 0;
  4895. TLSX_UseSRTP_Free(srtp, ssl->heap);
  4896. }
  4897. #endif
  4898. (void)profile_len;
  4899. return ret;
  4900. }
  4901. static word16 TLSX_UseSRTP_Write(TlsxSrtp* srtp, byte* output)
  4902. {
  4903. word16 offset = 0;
  4904. int i, j;
  4905. c16toa(srtp->profileCount * 2, output + offset);
  4906. offset += OPAQUE16_LEN;
  4907. j = 0;
  4908. for (i = 0; i < srtp->profileCount; i++) {
  4909. for (; j < 16; j++) {
  4910. if (srtp->ids & (1 << j)) {
  4911. c16toa(j, output + offset);
  4912. offset += OPAQUE16_LEN;
  4913. }
  4914. }
  4915. }
  4916. output[offset++] = 0x00; /* MKI Length */
  4917. return offset;
  4918. }
  4919. static int TLSX_UseSRTP(TLSX** extensions, word16 profiles, void* heap)
  4920. {
  4921. int ret = 0;
  4922. TLSX* extension;
  4923. if (extensions == NULL) {
  4924. return BAD_FUNC_ARG;
  4925. }
  4926. extension = TLSX_Find(*extensions, TLSX_USE_SRTP);
  4927. if (extension == NULL) {
  4928. TlsxSrtp* srtp = TLSX_UseSRTP_New(profiles, heap);
  4929. if (srtp == NULL) {
  4930. return MEMORY_E;
  4931. }
  4932. ret = TLSX_Push(extensions, TLSX_USE_SRTP, (void*)srtp, heap);
  4933. if (ret != 0) {
  4934. TLSX_UseSRTP_Free(srtp, heap);
  4935. }
  4936. }
  4937. return ret;
  4938. }
  4939. #ifndef NO_WOLFSSL_SERVER
  4940. #define SRTP_FREE TLSX_UseSRTP_Free
  4941. #define SRTP_PARSE TLSX_UseSRTP_Parse
  4942. #define SRTP_WRITE TLSX_UseSRTP_Write
  4943. #define SRTP_GET_SIZE TLSX_UseSRTP_GetSize
  4944. #else
  4945. #define SRTP_FREE(a, b) WC_DO_NOTHING
  4946. #define SRTP_PARSE(a, b, c, d) 0
  4947. #define SRTP_WRITE(a, b) 0
  4948. #define SRTP_GET_SIZE(a) 0
  4949. #endif
  4950. #endif /* WOLFSSL_SRTP */
  4951. /******************************************************************************/
  4952. /* Supported Versions */
  4953. /******************************************************************************/
  4954. #ifdef WOLFSSL_TLS13
  4955. static WC_INLINE int versionIsGreater(byte isDtls, byte a, byte b)
  4956. {
  4957. (void)isDtls;
  4958. #ifdef WOLFSSL_DTLS
  4959. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4960. if (isDtls)
  4961. return a < b;
  4962. #endif /* WOLFSSL_DTLS */
  4963. return a > b;
  4964. }
  4965. static WC_INLINE int versionIsLesser(byte isDtls, byte a, byte b)
  4966. {
  4967. (void)isDtls;
  4968. #ifdef WOLFSSL_DTLS
  4969. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4970. if (isDtls)
  4971. return a > b;
  4972. #endif /* WOLFSSL_DTLS */
  4973. return a < b;
  4974. }
  4975. static WC_INLINE int versionIsAtLeast(byte isDtls, byte a, byte b)
  4976. {
  4977. (void)isDtls;
  4978. #ifdef WOLFSSL_DTLS
  4979. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4980. if (isDtls)
  4981. return a <= b;
  4982. #endif /* WOLFSSL_DTLS */
  4983. return a >= b;
  4984. }
  4985. static WC_INLINE int versionIsLessEqual(byte isDtls, byte a, byte b)
  4986. {
  4987. (void)isDtls;
  4988. #ifdef WOLFSSL_DTLS
  4989. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4990. if (isDtls)
  4991. return a >= b;
  4992. #endif /* WOLFSSL_DTLS */
  4993. return a <= b;
  4994. }
  4995. /* Return the size of the SupportedVersions extension's data.
  4996. *
  4997. * data The SSL/TLS object.
  4998. * msgType The type of the message this extension is being written into.
  4999. * returns the length of data that will be in the extension.
  5000. */
  5001. static int TLSX_SupportedVersions_GetSize(void* data, byte msgType, word16* pSz)
  5002. {
  5003. WOLFSSL* ssl = (WOLFSSL*)data;
  5004. byte tls13Minor, tls12Minor, tls11Minor, isDtls;
  5005. isDtls = !!ssl->options.dtls;
  5006. tls13Minor = (byte)(isDtls ? DTLSv1_3_MINOR : TLSv1_3_MINOR);
  5007. tls12Minor = (byte)(isDtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR);
  5008. tls11Minor = (byte)(isDtls ? DTLS_MINOR : TLSv1_1_MINOR);
  5009. /* unused on some configuration */
  5010. (void)tls12Minor;
  5011. (void)tls13Minor;
  5012. (void)tls11Minor;
  5013. if (msgType == client_hello) {
  5014. /* TLS v1.2 and TLS v1.3 */
  5015. int cnt = 0;
  5016. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13Minor)
  5017. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5018. defined(WOLFSSL_WPAS_SMALL)
  5019. && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0
  5020. #endif
  5021. ) {
  5022. cnt++;
  5023. }
  5024. if (ssl->options.downgrade) {
  5025. #ifndef WOLFSSL_NO_TLS12
  5026. if (versionIsLessEqual(
  5027. isDtls, ssl->options.minDowngrade, tls12Minor)
  5028. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5029. defined(WOLFSSL_WPAS_SMALL)
  5030. && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0
  5031. #endif
  5032. ) {
  5033. cnt++;
  5034. }
  5035. #endif
  5036. #ifndef NO_OLD_TLS
  5037. if (versionIsLessEqual(
  5038. isDtls, ssl->options.minDowngrade, tls11Minor)
  5039. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5040. defined(WOLFSSL_WPAS_SMALL)
  5041. && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0
  5042. #endif
  5043. ) {
  5044. cnt++;
  5045. }
  5046. #ifdef WOLFSSL_ALLOW_TLSV10
  5047. if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR)
  5048. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5049. defined(WOLFSSL_WPAS_SMALL)
  5050. && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0
  5051. #endif
  5052. ) {
  5053. cnt++;
  5054. }
  5055. #endif
  5056. #endif
  5057. }
  5058. *pSz += (word16)(OPAQUE8_LEN + cnt * OPAQUE16_LEN);
  5059. }
  5060. else if (msgType == server_hello || msgType == hello_retry_request) {
  5061. *pSz += OPAQUE16_LEN;
  5062. }
  5063. else {
  5064. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5065. return SANITY_MSG_E;
  5066. }
  5067. return 0;
  5068. }
  5069. /* Writes the SupportedVersions extension into the buffer.
  5070. *
  5071. * data The SSL/TLS object.
  5072. * output The buffer to write the extension into.
  5073. * msgType The type of the message this extension is being written into.
  5074. * returns the length of data that was written.
  5075. */
  5076. static int TLSX_SupportedVersions_Write(void* data, byte* output,
  5077. byte msgType, word16* pSz)
  5078. {
  5079. WOLFSSL* ssl = (WOLFSSL*)data;
  5080. byte tls13minor, tls12minor, tls11minor, isDtls = 0;
  5081. tls13minor = (byte)TLSv1_3_MINOR;
  5082. tls12minor = (byte)TLSv1_2_MINOR;
  5083. tls11minor = (byte)TLSv1_1_MINOR;
  5084. /* unused in some configuration */
  5085. (void)tls11minor;
  5086. (void)tls12minor;
  5087. #ifdef WOLFSSL_DTLS13
  5088. if (ssl->options.dtls) {
  5089. tls13minor = (byte)DTLSv1_3_MINOR;
  5090. #ifndef WOLFSSL_NO_TLS12
  5091. tls12minor = (byte)DTLSv1_2_MINOR;
  5092. #endif
  5093. #ifndef NO_OLD_TLS
  5094. tls11minor = (byte)DTLS_MINOR;
  5095. #endif
  5096. isDtls = 1;
  5097. }
  5098. #endif /* WOLFSSL_DTLS13 */
  5099. if (msgType == client_hello) {
  5100. byte major = ssl->ctx->method->version.major;
  5101. byte* cnt = output++;
  5102. *cnt = 0;
  5103. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13minor)
  5104. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5105. defined(WOLFSSL_WPAS_SMALL)
  5106. && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0
  5107. #endif
  5108. ) {
  5109. *cnt += OPAQUE16_LEN;
  5110. #ifdef WOLFSSL_TLS13_DRAFT
  5111. /* The TLS draft major number. */
  5112. *(output++) = TLS_DRAFT_MAJOR;
  5113. /* Version of draft supported. */
  5114. *(output++) = TLS_DRAFT_MINOR;
  5115. #else
  5116. *(output++) = major;
  5117. *(output++) = tls13minor;
  5118. #endif
  5119. }
  5120. if (ssl->options.downgrade) {
  5121. #ifndef WOLFSSL_NO_TLS12
  5122. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls12minor)
  5123. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5124. defined(WOLFSSL_WPAS_SMALL)
  5125. && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0
  5126. #endif
  5127. ) {
  5128. *cnt += OPAQUE16_LEN;
  5129. *(output++) = major;
  5130. *(output++) = tls12minor;
  5131. }
  5132. #endif
  5133. #ifndef NO_OLD_TLS
  5134. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls11minor)
  5135. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5136. defined(WOLFSSL_WPAS_SMALL)
  5137. && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0
  5138. #endif
  5139. ) {
  5140. *cnt += OPAQUE16_LEN;
  5141. *(output++) = major;
  5142. *(output++) = tls11minor;
  5143. }
  5144. #ifdef WOLFSSL_ALLOW_TLSV10
  5145. if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR)
  5146. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5147. defined(WOLFSSL_WPAS_SMALL)
  5148. && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0
  5149. #endif
  5150. ) {
  5151. *cnt += OPAQUE16_LEN;
  5152. *(output++) = major;
  5153. *(output++) = (byte)TLSv1_MINOR;
  5154. }
  5155. #endif
  5156. #endif
  5157. }
  5158. *pSz += (word16)(OPAQUE8_LEN + *cnt);
  5159. }
  5160. else if (msgType == server_hello || msgType == hello_retry_request) {
  5161. output[0] = ssl->version.major;
  5162. output[1] = ssl->version.minor;
  5163. *pSz += OPAQUE16_LEN;
  5164. }
  5165. else {
  5166. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5167. return SANITY_MSG_E;
  5168. }
  5169. return 0;
  5170. }
  5171. /* Parse the SupportedVersions extension.
  5172. *
  5173. * ssl The SSL/TLS object.
  5174. * input The buffer with the extension data.
  5175. * length The length of the extension data.
  5176. * msgType The type of the message this extension is being parsed from.
  5177. * pv The output ProtocolVersion for the negotiated version
  5178. * opts The output options structure. Can be NULL.
  5179. * exts The output extensions list. Can be NULL.
  5180. * returns 0 on success, otherwise failure.
  5181. */
  5182. int TLSX_SupportedVersions_Parse(const WOLFSSL* ssl, const byte* input,
  5183. word16 length, byte msgType, ProtocolVersion* pv, Options* opts,
  5184. TLSX** exts)
  5185. {
  5186. /* The client's greatest minor version that we support */
  5187. byte clientGreatestMinor = SSLv3_MINOR;
  5188. int ret;
  5189. byte major, minor;
  5190. byte tls13minor, tls12minor;
  5191. byte isDtls;
  5192. tls13minor = TLSv1_3_MINOR;
  5193. tls12minor = TLSv1_2_MINOR;
  5194. isDtls = ssl->options.dtls == 1;
  5195. #ifdef WOLFSSL_DTLS13
  5196. if (ssl->options.dtls) {
  5197. tls13minor = DTLSv1_3_MINOR;
  5198. tls12minor = DTLSv1_2_MINOR;
  5199. clientGreatestMinor = DTLS_MINOR;
  5200. }
  5201. #endif /* WOLFSSL_DTLS13 */
  5202. if (msgType == client_hello) {
  5203. int i;
  5204. int len;
  5205. int set = 0;
  5206. /* Must contain a length and at least one version. */
  5207. if (length < OPAQUE8_LEN + OPAQUE16_LEN || (length & 1) != 1)
  5208. return BUFFER_ERROR;
  5209. len = *input;
  5210. /* Protocol version array must fill rest of data. */
  5211. if (length != (word16)OPAQUE8_LEN + len)
  5212. return BUFFER_ERROR;
  5213. input++;
  5214. /* Find first match. */
  5215. for (i = 0; i < len; i += OPAQUE16_LEN) {
  5216. major = input[i];
  5217. minor = input[i + OPAQUE8_LEN];
  5218. #ifdef WOLFSSL_TLS13_DRAFT
  5219. if (major == TLS_DRAFT_MAJOR && minor == TLS_DRAFT_MINOR) {
  5220. major = SSLv3_MAJOR;
  5221. minor = TLSv1_3_MINOR;
  5222. }
  5223. #else
  5224. if (major == TLS_DRAFT_MAJOR)
  5225. continue;
  5226. #endif
  5227. if (major != ssl->ctx->method->version.major)
  5228. continue;
  5229. /* No upgrade allowed. */
  5230. if (versionIsGreater(isDtls, minor, ssl->version.minor))
  5231. continue;
  5232. /* Check downgrade. */
  5233. if (versionIsLesser(isDtls, minor, ssl->version.minor)) {
  5234. if (!ssl->options.downgrade)
  5235. continue;
  5236. if (versionIsLesser(isDtls, minor, ssl->options.minDowngrade))
  5237. continue;
  5238. }
  5239. if (versionIsGreater(isDtls, minor, clientGreatestMinor))
  5240. clientGreatestMinor = minor;
  5241. set = 1;
  5242. }
  5243. if (!set) {
  5244. /* No common supported version was negotiated */
  5245. SendAlert((WOLFSSL*)ssl, alert_fatal,
  5246. wolfssl_alert_protocol_version);
  5247. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5248. return VERSION_ERROR;
  5249. }
  5250. pv->minor = clientGreatestMinor;
  5251. if (versionIsAtLeast(isDtls, clientGreatestMinor, tls13minor)) {
  5252. if (opts != NULL)
  5253. opts->tls1_3 = 1;
  5254. /* TLS v1.3 requires supported version extension */
  5255. if (exts != NULL &&
  5256. TLSX_Find(*exts, TLSX_SUPPORTED_VERSIONS) == NULL) {
  5257. ret = TLSX_Push(exts,
  5258. TLSX_SUPPORTED_VERSIONS, ssl, ssl->heap);
  5259. if (ret != 0) {
  5260. return ret;
  5261. }
  5262. /* *exts should be pointing to the TLSX_SUPPORTED_VERSIONS
  5263. * ext in the list since it was pushed. */
  5264. (*exts)->resp = 1;
  5265. }
  5266. }
  5267. }
  5268. else if (msgType == server_hello || msgType == hello_retry_request) {
  5269. /* Must contain one version. */
  5270. if (length != OPAQUE16_LEN)
  5271. return BUFFER_ERROR;
  5272. major = input[0];
  5273. minor = input[OPAQUE8_LEN];
  5274. if (major != ssl->ctx->method->version.major) {
  5275. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5276. return VERSION_ERROR;
  5277. }
  5278. /* Can't downgrade with this extension below TLS v1.3. */
  5279. if (versionIsLesser(isDtls, minor, tls13minor)) {
  5280. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5281. return VERSION_ERROR;
  5282. }
  5283. /* Version is TLS v1.2 to handle downgrading from TLS v1.3+. */
  5284. if (ssl->options.downgrade && ssl->version.minor == tls12minor) {
  5285. /* Set minor version back to TLS v1.3+ */
  5286. pv->minor = ssl->ctx->method->version.minor;
  5287. }
  5288. /* No upgrade allowed. */
  5289. if (versionIsLesser(isDtls, ssl->version.minor, minor)) {
  5290. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5291. return VERSION_ERROR;
  5292. }
  5293. /* Check downgrade. */
  5294. if (versionIsGreater(isDtls, ssl->version.minor, minor)) {
  5295. if (!ssl->options.downgrade) {
  5296. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5297. return VERSION_ERROR;
  5298. }
  5299. if (versionIsLesser(
  5300. isDtls, minor, ssl->options.minDowngrade)) {
  5301. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5302. return VERSION_ERROR;
  5303. }
  5304. /* Downgrade the version. */
  5305. pv->minor = minor;
  5306. }
  5307. }
  5308. else {
  5309. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5310. return SANITY_MSG_E;
  5311. }
  5312. return 0;
  5313. }
  5314. /* Sets a new SupportedVersions extension into the extension list.
  5315. *
  5316. * extensions The list of extensions.
  5317. * data The extensions specific data.
  5318. * heap The heap used for allocation.
  5319. * returns 0 on success, otherwise failure.
  5320. */
  5321. static int TLSX_SetSupportedVersions(TLSX** extensions, const void* data,
  5322. void* heap)
  5323. {
  5324. if (extensions == NULL || data == NULL)
  5325. return BAD_FUNC_ARG;
  5326. return TLSX_Push(extensions, TLSX_SUPPORTED_VERSIONS, data, heap);
  5327. }
  5328. #define SV_GET_SIZE TLSX_SupportedVersions_GetSize
  5329. #define SV_WRITE TLSX_SupportedVersions_Write
  5330. #define SV_PARSE TLSX_SupportedVersions_Parse
  5331. #else
  5332. #define SV_GET_SIZE(a, b, c) 0
  5333. #define SV_WRITE(a, b, c, d) 0
  5334. #define SV_PARSE(a, b, c, d, e, f, g) 0
  5335. #endif /* WOLFSSL_TLS13 */
  5336. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  5337. /******************************************************************************/
  5338. /* Cookie */
  5339. /******************************************************************************/
  5340. /* Free the cookie data.
  5341. *
  5342. * cookie Cookie data.
  5343. * heap The heap used for allocation.
  5344. */
  5345. static void TLSX_Cookie_FreeAll(Cookie* cookie, void* heap)
  5346. {
  5347. (void)heap;
  5348. if (cookie != NULL)
  5349. XFREE(cookie, heap, DYNAMIC_TYPE_TLSX);
  5350. }
  5351. /* Get the size of the encoded Cookie extension.
  5352. * In messages: ClientHello and HelloRetryRequest.
  5353. *
  5354. * cookie The cookie to write.
  5355. * msgType The type of the message this extension is being written into.
  5356. * returns the number of bytes of the encoded Cookie extension.
  5357. */
  5358. static int TLSX_Cookie_GetSize(Cookie* cookie, byte msgType, word16* pSz)
  5359. {
  5360. if (msgType == client_hello || msgType == hello_retry_request) {
  5361. *pSz += OPAQUE16_LEN + cookie->len;
  5362. }
  5363. else {
  5364. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5365. return SANITY_MSG_E;
  5366. }
  5367. return 0;
  5368. }
  5369. /* Writes the Cookie extension into the output buffer.
  5370. * Assumes that the the output buffer is big enough to hold data.
  5371. * In messages: ClientHello and HelloRetryRequest.
  5372. *
  5373. * cookie The cookie to write.
  5374. * output The buffer to write into.
  5375. * msgType The type of the message this extension is being written into.
  5376. * returns the number of bytes written into the buffer.
  5377. */
  5378. static int TLSX_Cookie_Write(Cookie* cookie, byte* output, byte msgType,
  5379. word16* pSz)
  5380. {
  5381. if (msgType == client_hello || msgType == hello_retry_request) {
  5382. c16toa(cookie->len, output);
  5383. output += OPAQUE16_LEN;
  5384. XMEMCPY(output, cookie->data, cookie->len);
  5385. *pSz += OPAQUE16_LEN + cookie->len;
  5386. }
  5387. else {
  5388. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5389. return SANITY_MSG_E;
  5390. }
  5391. return 0;
  5392. }
  5393. /* Parse the Cookie extension.
  5394. * In messages: ClientHello and HelloRetryRequest.
  5395. *
  5396. * ssl The SSL/TLS object.
  5397. * input The extension data.
  5398. * length The length of the extension data.
  5399. * msgType The type of the message this extension is being parsed from.
  5400. * returns 0 on success and other values indicate failure.
  5401. */
  5402. static int TLSX_Cookie_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  5403. byte msgType)
  5404. {
  5405. word16 len;
  5406. word16 idx = 0;
  5407. TLSX* extension;
  5408. Cookie* cookie;
  5409. if (msgType != client_hello && msgType != hello_retry_request) {
  5410. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5411. return SANITY_MSG_E;
  5412. }
  5413. /* Message contains length and Cookie which must be at least one byte
  5414. * in length.
  5415. */
  5416. if (length < OPAQUE16_LEN + 1)
  5417. return BUFFER_E;
  5418. ato16(input + idx, &len);
  5419. idx += OPAQUE16_LEN;
  5420. if (length - idx != len)
  5421. return BUFFER_E;
  5422. if (msgType == hello_retry_request)
  5423. return TLSX_Cookie_Use(ssl, input + idx, len, NULL, 0, 1,
  5424. &ssl->extensions);
  5425. /* client_hello */
  5426. extension = TLSX_Find(ssl->extensions, TLSX_COOKIE);
  5427. if (extension == NULL) {
  5428. #ifdef WOLFSSL_DTLS13
  5429. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version))
  5430. /* Allow a cookie extension with DTLS 1.3 because it is possible
  5431. * that a different SSL instance sent the cookie but we are now
  5432. * receiving it. */
  5433. return TLSX_Cookie_Use(ssl, input + idx, len, NULL, 0, 0,
  5434. &ssl->extensions);
  5435. else
  5436. #endif
  5437. {
  5438. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  5439. return HRR_COOKIE_ERROR;
  5440. }
  5441. }
  5442. cookie = (Cookie*)extension->data;
  5443. if (cookie->len != len || XMEMCMP(cookie->data, input + idx, len) != 0) {
  5444. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  5445. return HRR_COOKIE_ERROR;
  5446. }
  5447. /* Request seen. */
  5448. extension->resp = 0;
  5449. return 0;
  5450. }
  5451. /* Use the data to create a new Cookie object in the extensions.
  5452. *
  5453. * ssl SSL/TLS object.
  5454. * data Cookie data.
  5455. * len Length of cookie data in bytes.
  5456. * mac MAC data.
  5457. * macSz Length of MAC data in bytes.
  5458. * resp Indicates the extension will go into a response (HelloRetryRequest).
  5459. * returns 0 on success and other values indicate failure.
  5460. */
  5461. int TLSX_Cookie_Use(const WOLFSSL* ssl, const byte* data, word16 len, byte* mac,
  5462. byte macSz, int resp, TLSX** exts)
  5463. {
  5464. int ret = 0;
  5465. TLSX* extension;
  5466. Cookie* cookie;
  5467. /* Find the cookie extension if it exists. */
  5468. extension = TLSX_Find(*exts, TLSX_COOKIE);
  5469. if (extension == NULL) {
  5470. /* Push new cookie extension. */
  5471. ret = TLSX_Push(exts, TLSX_COOKIE, NULL, ssl->heap);
  5472. if (ret != 0)
  5473. return ret;
  5474. extension = TLSX_Find(*exts, TLSX_COOKIE);
  5475. if (extension == NULL)
  5476. return MEMORY_E;
  5477. }
  5478. cookie = (Cookie*)XMALLOC(sizeof(Cookie) + len + macSz, ssl->heap,
  5479. DYNAMIC_TYPE_TLSX);
  5480. if (cookie == NULL)
  5481. return MEMORY_E;
  5482. cookie->len = len + macSz;
  5483. XMEMCPY(cookie->data, data, len);
  5484. if (mac != NULL)
  5485. XMEMCPY(cookie->data + len, mac, macSz);
  5486. if (extension->data != NULL)
  5487. XFREE(extension->data, ssl->heap, DYNAMIC_TYPE_TLSX);
  5488. extension->data = (void*)cookie;
  5489. extension->resp = (byte)resp;
  5490. return 0;
  5491. }
  5492. #define CKE_FREE_ALL TLSX_Cookie_FreeAll
  5493. #define CKE_GET_SIZE TLSX_Cookie_GetSize
  5494. #define CKE_WRITE TLSX_Cookie_Write
  5495. #define CKE_PARSE TLSX_Cookie_Parse
  5496. #else
  5497. #define CKE_FREE_ALL(a, b) 0
  5498. #define CKE_GET_SIZE(a, b, c) 0
  5499. #define CKE_WRITE(a, b, c, d) 0
  5500. #define CKE_PARSE(a, b, c, d) 0
  5501. #endif
  5502. #if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && \
  5503. !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA)
  5504. /* Currently only settable through compatibility API */
  5505. /******************************************************************************/
  5506. /* Certificate Authorities */
  5507. /******************************************************************************/
  5508. static word16 TLSX_CA_Names_GetSize(void* data)
  5509. {
  5510. WOLFSSL* ssl = (WOLFSSL*)data;
  5511. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  5512. word16 size = 0;
  5513. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5514. /* To add support use a different member like ssl->ca_names and
  5515. * add accessor functions:
  5516. * - *_set0_CA_list
  5517. * - *_get0_CA_list */
  5518. WOLFSSL_MSG("We don't currently support sending the client's list.");
  5519. return 0;
  5520. }
  5521. /* Length of names */
  5522. size += OPAQUE16_LEN;
  5523. for (names = SSL_CA_NAMES(ssl); names != NULL; names = names->next) {
  5524. byte seq[MAX_SEQ_SZ];
  5525. WOLFSSL_X509_NAME* name = names->data.name;
  5526. if (name != NULL) {
  5527. /* 16-bit length | SEQ | Len | DER of name */
  5528. size += (word16)(OPAQUE16_LEN + SetSequence(name->rawLen, seq) +
  5529. name->rawLen);
  5530. }
  5531. }
  5532. return size;
  5533. }
  5534. static word16 TLSX_CA_Names_Write(void* data, byte* output)
  5535. {
  5536. WOLFSSL* ssl = (WOLFSSL*)data;
  5537. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  5538. byte* len;
  5539. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5540. /* To add support use a different member like ssl->ca_names and
  5541. * add accessor functions:
  5542. * - *_set0_CA_list
  5543. * - *_get0_CA_list */
  5544. WOLFSSL_MSG("We don't currently support sending the client's list.");
  5545. return 0;
  5546. }
  5547. /* Reserve space for the length value */
  5548. len = output;
  5549. output += OPAQUE16_LEN;
  5550. for (names = SSL_CA_NAMES(ssl); names != NULL; names = names->next) {
  5551. byte seq[MAX_SEQ_SZ];
  5552. WOLFSSL_X509_NAME* name = names->data.name;
  5553. if (name != NULL) {
  5554. c16toa((word16)name->rawLen +
  5555. (word16)SetSequence(name->rawLen, seq), output);
  5556. output += OPAQUE16_LEN;
  5557. output += SetSequence(name->rawLen, output);
  5558. XMEMCPY(output, name->raw, name->rawLen);
  5559. output += name->rawLen;
  5560. }
  5561. }
  5562. /* Write the total length */
  5563. c16toa((word16)(output - len - OPAQUE16_LEN), len);
  5564. return (word16)(output - len);
  5565. }
  5566. static int TLSX_CA_Names_Parse(WOLFSSL *ssl, const byte* input,
  5567. word16 length, byte isRequest)
  5568. {
  5569. word16 extLen;
  5570. (void)isRequest;
  5571. if (ssl->options.side == WOLFSSL_SERVER_END) {
  5572. /* To add support use a different member like ssl->ca_names and
  5573. * add accessor functions:
  5574. * - *_set0_CA_list
  5575. * - *_get0_CA_list */
  5576. WOLFSSL_MSG("We don't currently support parsing the client's list.");
  5577. return 0;
  5578. }
  5579. if (ssl->client_ca_names != ssl->ctx->client_ca_names)
  5580. wolfSSL_sk_X509_NAME_pop_free(ssl->client_ca_names, NULL);
  5581. ssl->client_ca_names = wolfSSL_sk_X509_NAME_new(NULL);
  5582. if (ssl->client_ca_names == NULL)
  5583. return MEMORY_ERROR;
  5584. if (length < OPAQUE16_LEN)
  5585. return BUFFER_ERROR;
  5586. ato16(input, &extLen);
  5587. input += OPAQUE16_LEN;
  5588. length -= OPAQUE16_LEN;
  5589. if (extLen != length)
  5590. return BUFFER_ERROR;
  5591. while (length) {
  5592. word32 idx = 0;
  5593. WOLFSSL_X509_NAME* name = NULL;
  5594. int ret = 0;
  5595. int didInit = FALSE;
  5596. /* Use a DecodedCert struct to get access to GetName to
  5597. * parse DN name */
  5598. #ifdef WOLFSSL_SMALL_STACK
  5599. DecodedCert *cert = (DecodedCert *)XMALLOC(
  5600. sizeof(*cert), ssl->heap, DYNAMIC_TYPE_DCERT);
  5601. if (cert == NULL)
  5602. return MEMORY_ERROR;
  5603. #else
  5604. DecodedCert cert[1];
  5605. #endif
  5606. if (length < OPAQUE16_LEN) {
  5607. ret = BUFFER_ERROR;
  5608. }
  5609. if (ret == 0) {
  5610. ato16(input, &extLen);
  5611. idx += OPAQUE16_LEN;
  5612. if (idx + extLen > length)
  5613. ret = BUFFER_ERROR;
  5614. }
  5615. if (ret == 0) {
  5616. InitDecodedCert(cert, input + idx, extLen, ssl->heap);
  5617. didInit = TRUE;
  5618. idx += extLen;
  5619. ret = GetName(cert, SUBJECT, extLen);
  5620. }
  5621. if (ret == 0 && (name = wolfSSL_X509_NAME_new()) == NULL)
  5622. ret = MEMORY_ERROR;
  5623. if (ret == 0) {
  5624. CopyDecodedName(name, cert, SUBJECT);
  5625. if (wolfSSL_sk_X509_NAME_push(ssl->client_ca_names, name)
  5626. == WOLFSSL_FAILURE)
  5627. ret = MEMORY_ERROR;
  5628. }
  5629. if (didInit)
  5630. FreeDecodedCert(cert);
  5631. #ifdef WOLFSSL_SMALL_STACK
  5632. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  5633. #endif
  5634. if (ret != 0)
  5635. return ret;
  5636. input += idx;
  5637. length -= (word16)idx;
  5638. }
  5639. return 0;
  5640. }
  5641. #define CAN_GET_SIZE TLSX_CA_Names_GetSize
  5642. #define CAN_WRITE TLSX_CA_Names_Write
  5643. #define CAN_PARSE TLSX_CA_Names_Parse
  5644. #else
  5645. #define CAN_GET_SIZE(...) 0
  5646. #define CAN_WRITE(...) 0
  5647. #define CAN_PARSE(...) 0
  5648. #endif
  5649. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  5650. /******************************************************************************/
  5651. /* Signature Algorithms */
  5652. /******************************************************************************/
  5653. /* Return the size of the SignatureAlgorithms extension's data.
  5654. *
  5655. * data Unused
  5656. * returns the length of data that will be in the extension.
  5657. */
  5658. static word16 TLSX_SignatureAlgorithms_GetSize(void* data)
  5659. {
  5660. SignatureAlgorithms* sa = (SignatureAlgorithms*)data;
  5661. if (sa->hashSigAlgoSz == 0)
  5662. return OPAQUE16_LEN + WOLFSSL_SUITES(sa->ssl)->hashSigAlgoSz;
  5663. else
  5664. return OPAQUE16_LEN + sa->hashSigAlgoSz;
  5665. }
  5666. /* Creates a bit string of supported hash algorithms with RSA PSS.
  5667. * The bit string is used when determining which signature algorithm to use
  5668. * when creating the CertificateVerify message.
  5669. * Note: Valid data has an even length as each signature algorithm is two bytes.
  5670. *
  5671. * ssl The SSL/TLS object.
  5672. * input The buffer with the list of supported signature algorithms.
  5673. * length The length of the list in bytes.
  5674. * returns 0 on success, BUFFER_ERROR when the length is not even.
  5675. */
  5676. static int TLSX_SignatureAlgorithms_MapPss(WOLFSSL *ssl, const byte* input,
  5677. word16 length)
  5678. {
  5679. word16 i;
  5680. if ((length & 1) == 1)
  5681. return BUFFER_ERROR;
  5682. ssl->pssAlgo = 0;
  5683. for (i = 0; i < length; i += 2) {
  5684. if (input[i] == rsa_pss_sa_algo && input[i + 1] <= sha512_mac)
  5685. ssl->pssAlgo |= 1 << input[i + 1];
  5686. #ifdef WOLFSSL_TLS13
  5687. if (input[i] == rsa_pss_sa_algo && input[i + 1] >= pss_sha256 &&
  5688. input[i + 1] <= pss_sha512) {
  5689. ssl->pssAlgo |= 1 << input[i + 1];
  5690. }
  5691. #endif
  5692. }
  5693. return 0;
  5694. }
  5695. /* Writes the SignatureAlgorithms extension into the buffer.
  5696. *
  5697. * data Unused
  5698. * output The buffer to write the extension into.
  5699. * returns the length of data that was written.
  5700. */
  5701. static word16 TLSX_SignatureAlgorithms_Write(void* data, byte* output)
  5702. {
  5703. SignatureAlgorithms* sa = (SignatureAlgorithms*)data;
  5704. const Suites* suites = WOLFSSL_SUITES(sa->ssl);
  5705. word16 hashSigAlgoSz;
  5706. if (sa->hashSigAlgoSz == 0) {
  5707. c16toa(suites->hashSigAlgoSz, output);
  5708. XMEMCPY(output + OPAQUE16_LEN, suites->hashSigAlgo,
  5709. suites->hashSigAlgoSz);
  5710. hashSigAlgoSz = suites->hashSigAlgoSz;
  5711. }
  5712. else {
  5713. c16toa(sa->hashSigAlgoSz, output);
  5714. XMEMCPY(output + OPAQUE16_LEN, sa->hashSigAlgo,
  5715. sa->hashSigAlgoSz);
  5716. hashSigAlgoSz = sa->hashSigAlgoSz;
  5717. }
  5718. #ifndef NO_RSA
  5719. TLSX_SignatureAlgorithms_MapPss(sa->ssl, output + OPAQUE16_LEN,
  5720. hashSigAlgoSz);
  5721. #endif
  5722. return OPAQUE16_LEN + hashSigAlgoSz;
  5723. }
  5724. /* Parse the SignatureAlgorithms extension.
  5725. *
  5726. * ssl The SSL/TLS object.
  5727. * input The buffer with the extension data.
  5728. * length The length of the extension data.
  5729. * returns 0 on success, otherwise failure.
  5730. */
  5731. static int TLSX_SignatureAlgorithms_Parse(WOLFSSL *ssl, const byte* input,
  5732. word16 length, byte isRequest, Suites* suites)
  5733. {
  5734. word16 len;
  5735. if (!isRequest)
  5736. return BUFFER_ERROR;
  5737. /* Must contain a length and at least algorithm. */
  5738. if (length < OPAQUE16_LEN + OPAQUE16_LEN || (length & 1) != 0)
  5739. return BUFFER_ERROR;
  5740. ato16(input, &len);
  5741. input += OPAQUE16_LEN;
  5742. /* Algorithm array must fill rest of data. */
  5743. if (length != OPAQUE16_LEN + len)
  5744. return BUFFER_ERROR;
  5745. /* Sig Algo list size must be even. */
  5746. if (suites->hashSigAlgoSz % 2 != 0)
  5747. return BUFFER_ERROR;
  5748. /* truncate hashSigAlgo list if too long */
  5749. suites->hashSigAlgoSz = len;
  5750. if (suites->hashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  5751. WOLFSSL_MSG("TLSX SigAlgo list exceeds max, truncating");
  5752. suites->hashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  5753. }
  5754. XMEMCPY(suites->hashSigAlgo, input, suites->hashSigAlgoSz);
  5755. return TLSX_SignatureAlgorithms_MapPss(ssl, input, len);
  5756. }
  5757. /* Sets a new SignatureAlgorithms extension into the extension list.
  5758. *
  5759. * extensions The list of extensions.
  5760. * data The extensions specific data.
  5761. * heap The heap used for allocation.
  5762. * returns 0 on success, otherwise failure.
  5763. */
  5764. static int TLSX_SetSignatureAlgorithms(TLSX** extensions, WOLFSSL* ssl,
  5765. void* heap)
  5766. {
  5767. SignatureAlgorithms* sa;
  5768. int ret;
  5769. if (extensions == NULL)
  5770. return BAD_FUNC_ARG;
  5771. /* Already present */
  5772. if (TLSX_Find(*extensions, TLSX_SIGNATURE_ALGORITHMS) != NULL)
  5773. return 0;
  5774. sa = TLSX_SignatureAlgorithms_New(ssl, 0, heap);
  5775. if (sa == NULL)
  5776. return MEMORY_ERROR;
  5777. ret = TLSX_Push(extensions, TLSX_SIGNATURE_ALGORITHMS, sa, heap);
  5778. if (ret != 0)
  5779. TLSX_SignatureAlgorithms_FreeAll(sa, heap);
  5780. return ret;
  5781. }
  5782. SignatureAlgorithms* TLSX_SignatureAlgorithms_New(WOLFSSL* ssl,
  5783. word16 hashSigAlgoSz, void* heap)
  5784. {
  5785. SignatureAlgorithms* sa;
  5786. (void)heap;
  5787. sa = (SignatureAlgorithms*)XMALLOC(sizeof(*sa) + hashSigAlgoSz, heap,
  5788. DYNAMIC_TYPE_TLSX);
  5789. if (sa != NULL) {
  5790. XMEMSET(sa, 0, sizeof(*sa) + hashSigAlgoSz);
  5791. sa->ssl = ssl;
  5792. sa->hashSigAlgoSz = hashSigAlgoSz;
  5793. }
  5794. return sa;
  5795. }
  5796. void TLSX_SignatureAlgorithms_FreeAll(SignatureAlgorithms* sa,
  5797. void* heap)
  5798. {
  5799. XFREE(sa, heap, DYNAMIC_TYPE_TLSX);
  5800. (void)heap;
  5801. }
  5802. #define SA_GET_SIZE TLSX_SignatureAlgorithms_GetSize
  5803. #define SA_WRITE TLSX_SignatureAlgorithms_Write
  5804. #define SA_PARSE TLSX_SignatureAlgorithms_Parse
  5805. #define SA_FREE_ALL TLSX_SignatureAlgorithms_FreeAll
  5806. #endif
  5807. /******************************************************************************/
  5808. /* Signature Algorithms Certificate */
  5809. /******************************************************************************/
  5810. #if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  5811. /* Return the size of the SignatureAlgorithms extension's data.
  5812. *
  5813. * data Unused
  5814. * returns the length of data that will be in the extension.
  5815. */
  5816. static word16 TLSX_SignatureAlgorithmsCert_GetSize(void* data)
  5817. {
  5818. WOLFSSL* ssl = (WOLFSSL*)data;
  5819. return OPAQUE16_LEN + ssl->certHashSigAlgoSz;
  5820. }
  5821. /* Writes the SignatureAlgorithmsCert extension into the buffer.
  5822. *
  5823. * data Unused
  5824. * output The buffer to write the extension into.
  5825. * returns the length of data that was written.
  5826. */
  5827. static word16 TLSX_SignatureAlgorithmsCert_Write(void* data, byte* output)
  5828. {
  5829. WOLFSSL* ssl = (WOLFSSL*)data;
  5830. c16toa(ssl->certHashSigAlgoSz, output);
  5831. XMEMCPY(output + OPAQUE16_LEN, ssl->certHashSigAlgo,
  5832. ssl->certHashSigAlgoSz);
  5833. return OPAQUE16_LEN + ssl->certHashSigAlgoSz;
  5834. }
  5835. /* Parse the SignatureAlgorithmsCert extension.
  5836. *
  5837. * ssl The SSL/TLS object.
  5838. * input The buffer with the extension data.
  5839. * length The length of the extension data.
  5840. * returns 0 on success, otherwise failure.
  5841. */
  5842. static int TLSX_SignatureAlgorithmsCert_Parse(WOLFSSL *ssl, const byte* input,
  5843. word16 length, byte isRequest)
  5844. {
  5845. word16 len;
  5846. if (!isRequest)
  5847. return BUFFER_ERROR;
  5848. /* Must contain a length and at least algorithm. */
  5849. if (length < OPAQUE16_LEN + OPAQUE16_LEN || (length & 1) != 0)
  5850. return BUFFER_ERROR;
  5851. ato16(input, &len);
  5852. input += OPAQUE16_LEN;
  5853. /* Algorithm array must fill rest of data. */
  5854. if (length != OPAQUE16_LEN + len)
  5855. return BUFFER_ERROR;
  5856. /* truncate hashSigAlgo list if too long */
  5857. ssl->certHashSigAlgoSz = len;
  5858. if (ssl->certHashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  5859. WOLFSSL_MSG("TLSX SigAlgo list exceeds max, truncating");
  5860. ssl->certHashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  5861. }
  5862. XMEMCPY(ssl->certHashSigAlgo, input, ssl->certHashSigAlgoSz);
  5863. return 0;
  5864. }
  5865. /* Sets a new SignatureAlgorithmsCert extension into the extension list.
  5866. *
  5867. * extensions The list of extensions.
  5868. * data The extensions specific data.
  5869. * heap The heap used for allocation.
  5870. * returns 0 on success, otherwise failure.
  5871. */
  5872. static int TLSX_SetSignatureAlgorithmsCert(TLSX** extensions,
  5873. const WOLFSSL* data, void* heap)
  5874. {
  5875. if (extensions == NULL)
  5876. return BAD_FUNC_ARG;
  5877. return TLSX_Push(extensions, TLSX_SIGNATURE_ALGORITHMS_CERT, data, heap);
  5878. }
  5879. #define SAC_GET_SIZE TLSX_SignatureAlgorithmsCert_GetSize
  5880. #define SAC_WRITE TLSX_SignatureAlgorithmsCert_Write
  5881. #define SAC_PARSE TLSX_SignatureAlgorithmsCert_Parse
  5882. #endif /* WOLFSSL_TLS13 */
  5883. /******************************************************************************/
  5884. /* Key Share */
  5885. /******************************************************************************/
  5886. #if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
  5887. /* Create a key share entry using named Diffie-Hellman parameters group.
  5888. * Generates a key pair.
  5889. *
  5890. * ssl The SSL/TLS object.
  5891. * kse The key share entry object.
  5892. * returns 0 on success, otherwise failure.
  5893. */
  5894. static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse)
  5895. {
  5896. int ret = 0;
  5897. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  5898. word32 pSz = 0, pvtSz = 0;
  5899. DhKey* dhKey = (DhKey*)kse->key;
  5900. /* Pick the parameters from the named group. */
  5901. #ifdef HAVE_PUBLIC_FFDHE
  5902. const DhParams* params = NULL;
  5903. switch (kse->group) {
  5904. #ifdef HAVE_FFDHE_2048
  5905. case WOLFSSL_FFDHE_2048:
  5906. params = wc_Dh_ffdhe2048_Get();
  5907. pvtSz = 29;
  5908. break;
  5909. #endif
  5910. #ifdef HAVE_FFDHE_3072
  5911. case WOLFSSL_FFDHE_3072:
  5912. params = wc_Dh_ffdhe3072_Get();
  5913. pvtSz = 34;
  5914. break;
  5915. #endif
  5916. #ifdef HAVE_FFDHE_4096
  5917. case WOLFSSL_FFDHE_4096:
  5918. params = wc_Dh_ffdhe4096_Get();
  5919. pvtSz = 39;
  5920. break;
  5921. #endif
  5922. #ifdef HAVE_FFDHE_6144
  5923. case WOLFSSL_FFDHE_6144:
  5924. params = wc_Dh_ffdhe6144_Get();
  5925. pvtSz = 46;
  5926. break;
  5927. #endif
  5928. #ifdef HAVE_FFDHE_8192
  5929. case WOLFSSL_FFDHE_8192:
  5930. params = wc_Dh_ffdhe8192_Get();
  5931. pvtSz = 52;
  5932. break;
  5933. #endif
  5934. default:
  5935. break;
  5936. }
  5937. if (params == NULL)
  5938. return BAD_FUNC_ARG;
  5939. pSz = params->p_len;
  5940. #else
  5941. pvtSz = wc_DhGetNamedKeyMinSize(kse->group);
  5942. if (pvtSz == 0) {
  5943. return BAD_FUNC_ARG;
  5944. }
  5945. ret = wc_DhGetNamedKeyParamSize(kse->group, &pSz, NULL, NULL);
  5946. if (ret != 0) {
  5947. return BAD_FUNC_ARG;
  5948. }
  5949. #endif
  5950. /* Trigger Key Generation */
  5951. if (kse->pubKey == NULL || kse->privKey == NULL) {
  5952. if (kse->key == NULL) {
  5953. kse->key = (DhKey*)XMALLOC(sizeof(DhKey), ssl->heap,
  5954. DYNAMIC_TYPE_DH);
  5955. if (kse->key == NULL)
  5956. return MEMORY_E;
  5957. /* Setup Key */
  5958. ret = wc_InitDhKey_ex((DhKey*)kse->key, ssl->heap, ssl->devId);
  5959. if (ret == 0) {
  5960. dhKey = (DhKey*)kse->key;
  5961. #ifdef HAVE_PUBLIC_FFDHE
  5962. ret = wc_DhSetKey(dhKey, params->p, params->p_len, params->g,
  5963. params->g_len);
  5964. #else
  5965. ret = wc_DhSetNamedKey(dhKey, kse->group);
  5966. #endif
  5967. }
  5968. }
  5969. /* Allocate space for the private and public key */
  5970. if (ret == 0 && kse->pubKey == NULL) {
  5971. kse->pubKey = (byte*)XMALLOC(pSz, ssl->heap,
  5972. DYNAMIC_TYPE_PUBLIC_KEY);
  5973. if (kse->pubKey == NULL)
  5974. ret = MEMORY_E;
  5975. }
  5976. if (ret == 0 && kse->privKey == NULL) {
  5977. kse->privKey = (byte*)XMALLOC(pvtSz, ssl->heap,
  5978. DYNAMIC_TYPE_PRIVATE_KEY);
  5979. if (kse->privKey == NULL)
  5980. ret = MEMORY_E;
  5981. }
  5982. if (ret == 0) {
  5983. #if defined(WOLFSSL_STATIC_EPHEMERAL) && defined(WOLFSSL_DH_EXTRA)
  5984. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_DH, kse->key);
  5985. kse->pubKeyLen = pSz;
  5986. kse->keyLen = pvtSz;
  5987. if (ret == 0) {
  5988. ret = wc_DhExportKeyPair(dhKey,
  5989. (byte*)kse->privKey, &kse->keyLen, /* private */
  5990. kse->pubKey, &kse->pubKeyLen /* public */
  5991. );
  5992. }
  5993. else
  5994. #endif
  5995. {
  5996. /* Generate a new key pair */
  5997. /* For async this is called once and when event is done, the
  5998. * provided buffers will be populated.
  5999. * Final processing is zero pad below. */
  6000. kse->pubKeyLen = pSz;
  6001. kse->keyLen = pvtSz;
  6002. ret = DhGenKeyPair(ssl, dhKey,
  6003. (byte*)kse->privKey, &kse->keyLen, /* private */
  6004. kse->pubKey, &kse->pubKeyLen /* public */
  6005. );
  6006. #ifdef WOLFSSL_ASYNC_CRYPT
  6007. if (ret == WC_PENDING_E) {
  6008. return ret;
  6009. }
  6010. #endif
  6011. }
  6012. }
  6013. }
  6014. if (ret == 0) {
  6015. if (pSz != kse->pubKeyLen) {
  6016. /* Zero pad the front of the public key to match prime "p" size */
  6017. XMEMMOVE(kse->pubKey + pSz - kse->pubKeyLen, kse->pubKey,
  6018. kse->pubKeyLen);
  6019. XMEMSET(kse->pubKey, 0, pSz - kse->pubKeyLen);
  6020. kse->pubKeyLen = pSz;
  6021. }
  6022. if (pvtSz != kse->keyLen) {
  6023. /* Zero pad the front of the private key */
  6024. XMEMMOVE(kse->privKey + pvtSz - kse->keyLen, kse->privKey,
  6025. kse->keyLen);
  6026. XMEMSET(kse->privKey, 0, pvtSz - kse->keyLen);
  6027. kse->keyLen = pvtSz;
  6028. }
  6029. #ifdef WOLFSSL_DEBUG_TLS
  6030. WOLFSSL_MSG("Public DH Key");
  6031. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6032. #endif
  6033. }
  6034. /* Always release the DH key to free up memory.
  6035. * The DhKey will be setup again in TLSX_KeyShare_ProcessDh */
  6036. if (dhKey != NULL)
  6037. wc_FreeDhKey(dhKey);
  6038. if (kse->key != NULL) {
  6039. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_DH);
  6040. kse->key = NULL;
  6041. }
  6042. if (ret != 0) {
  6043. /* Cleanup on error, otherwise data owned by key share entry */
  6044. if (kse->privKey != NULL) {
  6045. XFREE(kse->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6046. kse->privKey = NULL;
  6047. }
  6048. if (kse->pubKey != NULL) {
  6049. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6050. kse->pubKey = NULL;
  6051. }
  6052. }
  6053. #else
  6054. (void)ssl;
  6055. (void)kse;
  6056. ret = NOT_COMPILED_IN;
  6057. WOLFSSL_ERROR_VERBOSE(ret);
  6058. #endif
  6059. return ret;
  6060. }
  6061. /* Create a key share entry using X25519 parameters group.
  6062. * Generates a key pair.
  6063. *
  6064. * ssl The SSL/TLS object.
  6065. * kse The key share entry object.
  6066. * returns 0 on success, otherwise failure.
  6067. */
  6068. static int TLSX_KeyShare_GenX25519Key(WOLFSSL *ssl, KeyShareEntry* kse)
  6069. {
  6070. int ret = 0;
  6071. #ifdef HAVE_CURVE25519
  6072. curve25519_key* key = (curve25519_key*)kse->key;
  6073. if (kse->key == NULL) {
  6074. /* Allocate a Curve25519 key to hold private key. */
  6075. kse->key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), ssl->heap,
  6076. DYNAMIC_TYPE_PRIVATE_KEY);
  6077. if (kse->key == NULL) {
  6078. WOLFSSL_MSG("GenX25519Key memory error");
  6079. return MEMORY_E;
  6080. }
  6081. /* Make an Curve25519 key. */
  6082. ret = wc_curve25519_init_ex((curve25519_key*)kse->key, ssl->heap,
  6083. INVALID_DEVID);
  6084. if (ret == 0) {
  6085. /* setting "key" means okay to call wc_curve25519_free */
  6086. key = (curve25519_key*)kse->key;
  6087. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6088. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE25519, kse->key);
  6089. if (ret != 0)
  6090. #endif
  6091. {
  6092. ret = wc_curve25519_make_key(ssl->rng, CURVE25519_KEYSIZE, key);
  6093. }
  6094. }
  6095. }
  6096. if (ret == 0 && kse->pubKey == NULL) {
  6097. /* Allocate space for the public key. */
  6098. kse->pubKey = (byte*)XMALLOC(CURVE25519_KEYSIZE, ssl->heap,
  6099. DYNAMIC_TYPE_PUBLIC_KEY);
  6100. if (kse->pubKey == NULL) {
  6101. WOLFSSL_MSG("GenX25519Key pub memory error");
  6102. ret = MEMORY_E;
  6103. }
  6104. }
  6105. if (ret == 0) {
  6106. /* Export Curve25519 public key. */
  6107. kse->pubKeyLen = CURVE25519_KEYSIZE;
  6108. if (wc_curve25519_export_public_ex(key, kse->pubKey, &kse->pubKeyLen,
  6109. EC25519_LITTLE_ENDIAN) != 0) {
  6110. ret = ECC_EXPORT_ERROR;
  6111. WOLFSSL_ERROR_VERBOSE(ret);
  6112. }
  6113. kse->pubKeyLen = CURVE25519_KEYSIZE; /* always CURVE25519_KEYSIZE */
  6114. }
  6115. #ifdef WOLFSSL_DEBUG_TLS
  6116. if (ret == 0) {
  6117. WOLFSSL_MSG("Public Curve25519 Key");
  6118. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6119. }
  6120. #endif
  6121. if (ret != 0) {
  6122. /* Data owned by key share entry otherwise. */
  6123. if (kse->pubKey != NULL) {
  6124. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6125. kse->pubKey = NULL;
  6126. }
  6127. if (key != NULL)
  6128. wc_curve25519_free(key);
  6129. if (kse->key != NULL) {
  6130. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6131. kse->key = NULL;
  6132. }
  6133. }
  6134. #else
  6135. (void)ssl;
  6136. (void)kse;
  6137. ret = NOT_COMPILED_IN;
  6138. WOLFSSL_ERROR_VERBOSE(ret);
  6139. #endif /* HAVE_CURVE25519 */
  6140. return ret;
  6141. }
  6142. /* Create a key share entry using X448 parameters group.
  6143. * Generates a key pair.
  6144. *
  6145. * ssl The SSL/TLS object.
  6146. * kse The key share entry object.
  6147. * returns 0 on success, otherwise failure.
  6148. */
  6149. static int TLSX_KeyShare_GenX448Key(WOLFSSL *ssl, KeyShareEntry* kse)
  6150. {
  6151. int ret = 0;
  6152. #ifdef HAVE_CURVE448
  6153. curve448_key* key = (curve448_key*)kse->key;
  6154. if (kse->key == NULL) {
  6155. /* Allocate a Curve448 key to hold private key. */
  6156. kse->key = (curve448_key*)XMALLOC(sizeof(curve448_key), ssl->heap,
  6157. DYNAMIC_TYPE_PRIVATE_KEY);
  6158. if (kse->key == NULL) {
  6159. WOLFSSL_MSG("GenX448Key memory error");
  6160. return MEMORY_E;
  6161. }
  6162. /* Make an Curve448 key. */
  6163. ret = wc_curve448_init((curve448_key*)kse->key);
  6164. if (ret == 0) {
  6165. key = (curve448_key*)kse->key;
  6166. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6167. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE448, kse->key);
  6168. if (ret != 0)
  6169. #endif
  6170. {
  6171. ret = wc_curve448_make_key(ssl->rng, CURVE448_KEY_SIZE, key);
  6172. }
  6173. }
  6174. }
  6175. if (ret == 0 && kse->pubKey == NULL) {
  6176. /* Allocate space for the public key. */
  6177. kse->pubKey = (byte*)XMALLOC(CURVE448_KEY_SIZE, ssl->heap,
  6178. DYNAMIC_TYPE_PUBLIC_KEY);
  6179. if (kse->pubKey == NULL) {
  6180. WOLFSSL_MSG("GenX448Key pub memory error");
  6181. ret = MEMORY_E;
  6182. }
  6183. }
  6184. if (ret == 0) {
  6185. /* Export Curve448 public key. */
  6186. kse->pubKeyLen = CURVE448_KEY_SIZE;
  6187. if (wc_curve448_export_public_ex(key, kse->pubKey, &kse->pubKeyLen,
  6188. EC448_LITTLE_ENDIAN) != 0) {
  6189. ret = ECC_EXPORT_ERROR;
  6190. }
  6191. kse->pubKeyLen = CURVE448_KEY_SIZE; /* always CURVE448_KEY_SIZE */
  6192. }
  6193. #ifdef WOLFSSL_DEBUG_TLS
  6194. if (ret == 0) {
  6195. WOLFSSL_MSG("Public Curve448 Key");
  6196. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6197. }
  6198. #endif
  6199. if (ret != 0) {
  6200. /* Data owned by key share entry otherwise. */
  6201. if (kse->pubKey != NULL) {
  6202. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6203. kse->pubKey = NULL;
  6204. }
  6205. if (key != NULL)
  6206. wc_curve448_free(key);
  6207. if (kse->key != NULL) {
  6208. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6209. kse->key = NULL;
  6210. }
  6211. }
  6212. #else
  6213. (void)ssl;
  6214. (void)kse;
  6215. ret = NOT_COMPILED_IN;
  6216. WOLFSSL_ERROR_VERBOSE(ret);
  6217. #endif /* HAVE_CURVE448 */
  6218. return ret;
  6219. }
  6220. /* Create a key share entry using named elliptic curve parameters group.
  6221. * Generates a key pair.
  6222. *
  6223. * ssl The SSL/TLS object.
  6224. * kse The key share entry object.
  6225. * returns 0 on success, otherwise failure.
  6226. */
  6227. static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse)
  6228. {
  6229. int ret = 0;
  6230. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  6231. word32 keySize = 0;
  6232. word16 curveId = (word16) ECC_CURVE_INVALID;
  6233. ecc_key* eccKey = (ecc_key*)kse->key;
  6234. /* TODO: [TLS13] Get key sizes using wc_ecc_get_curve_size_from_id. */
  6235. /* Translate named group to a curve id. */
  6236. switch (kse->group) {
  6237. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  6238. #ifndef NO_ECC_SECP
  6239. case WOLFSSL_ECC_SECP256R1:
  6240. curveId = ECC_SECP256R1;
  6241. keySize = 32;
  6242. break;
  6243. #endif /* !NO_ECC_SECP */
  6244. #ifdef WOLFSSL_SM2
  6245. case WOLFSSL_ECC_SM2P256V1:
  6246. curveId = ECC_SM2P256V1;
  6247. keySize = 32;
  6248. break;
  6249. #endif /* !NO_ECC_SECP */
  6250. #endif
  6251. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  6252. #ifndef NO_ECC_SECP
  6253. case WOLFSSL_ECC_SECP384R1:
  6254. curveId = ECC_SECP384R1;
  6255. keySize = 48;
  6256. break;
  6257. #endif /* !NO_ECC_SECP */
  6258. #endif
  6259. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  6260. #ifndef NO_ECC_SECP
  6261. case WOLFSSL_ECC_SECP521R1:
  6262. curveId = ECC_SECP521R1;
  6263. keySize = 66;
  6264. break;
  6265. #endif /* !NO_ECC_SECP */
  6266. #endif
  6267. default:
  6268. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  6269. return BAD_FUNC_ARG;
  6270. }
  6271. if (kse->key == NULL) {
  6272. /* Allocate an ECC key to hold private key. */
  6273. kse->key = (byte*)XMALLOC(sizeof(ecc_key), ssl->heap, DYNAMIC_TYPE_ECC);
  6274. if (kse->key == NULL) {
  6275. WOLFSSL_MSG_EX("Failed to allocate %d bytes, ssl->heap: %p",
  6276. (int)sizeof(ecc_key), (wc_ptr_t)ssl->heap);
  6277. WOLFSSL_MSG("EccTempKey Memory error!");
  6278. return MEMORY_E;
  6279. }
  6280. /* Initialize an ECC key struct for the ephemeral key */
  6281. ret = wc_ecc_init_ex((ecc_key*)kse->key, ssl->heap, ssl->devId);
  6282. if (ret == 0) {
  6283. kse->keyLen = keySize;
  6284. kse->pubKeyLen = keySize * 2 + 1;
  6285. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  6286. ret = tsip_Tls13GenEccKeyPair(ssl, kse);
  6287. if (ret != CRYPTOCB_UNAVAILABLE) {
  6288. return ret;
  6289. }
  6290. #endif
  6291. /* setting eccKey means okay to call wc_ecc_free */
  6292. eccKey = (ecc_key*)kse->key;
  6293. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6294. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_ECDH, kse->key);
  6295. if (ret != 0)
  6296. #endif
  6297. {
  6298. /* set curve info for EccMakeKey "peer" info */
  6299. ret = wc_ecc_set_curve(eccKey, kse->keyLen, curveId);
  6300. if (ret == 0) {
  6301. #ifdef WOLFSSL_ASYNC_CRYPT
  6302. /* Detect when private key generation is done */
  6303. if (ssl->error == WC_PENDING_E &&
  6304. eccKey->type == ECC_PRIVATEKEY) {
  6305. ret = 0; /* ECC Key Generation is done */
  6306. }
  6307. else
  6308. #endif
  6309. {
  6310. /* Generate ephemeral ECC key */
  6311. /* For async this is called once and when event is done, the
  6312. * provided buffers in key be populated.
  6313. * Final processing is x963 key export below. */
  6314. ret = EccMakeKey(ssl, eccKey, eccKey);
  6315. }
  6316. }
  6317. #ifdef WOLFSSL_ASYNC_CRYPT
  6318. if (ret == WC_PENDING_E)
  6319. return ret;
  6320. #endif
  6321. }
  6322. }
  6323. }
  6324. if (ret == 0 && kse->pubKey == NULL) {
  6325. /* Allocate space for the public key */
  6326. kse->pubKey = (byte*)XMALLOC(kse->pubKeyLen, ssl->heap,
  6327. DYNAMIC_TYPE_PUBLIC_KEY);
  6328. if (kse->pubKey == NULL) {
  6329. WOLFSSL_MSG("Key data Memory error");
  6330. ret = MEMORY_E;
  6331. }
  6332. }
  6333. if (ret == 0) {
  6334. XMEMSET(kse->pubKey, 0, kse->pubKeyLen);
  6335. /* Export public key. */
  6336. PRIVATE_KEY_UNLOCK();
  6337. if (wc_ecc_export_x963(eccKey, kse->pubKey, &kse->pubKeyLen) != 0) {
  6338. ret = ECC_EXPORT_ERROR;
  6339. WOLFSSL_ERROR_VERBOSE(ret);
  6340. }
  6341. PRIVATE_KEY_LOCK();
  6342. }
  6343. #ifdef WOLFSSL_DEBUG_TLS
  6344. if (ret == 0) {
  6345. WOLFSSL_MSG("Public ECC Key");
  6346. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6347. }
  6348. #endif
  6349. if (ret != 0) {
  6350. /* Cleanup on error, otherwise data owned by key share entry */
  6351. if (kse->pubKey != NULL) {
  6352. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6353. kse->pubKey = NULL;
  6354. }
  6355. if (eccKey != NULL)
  6356. wc_ecc_free(eccKey);
  6357. if (kse->key != NULL) {
  6358. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6359. kse->key = NULL;
  6360. }
  6361. }
  6362. #else
  6363. (void)ssl;
  6364. (void)kse;
  6365. ret = NOT_COMPILED_IN;
  6366. WOLFSSL_ERROR_VERBOSE(ret);
  6367. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  6368. return ret;
  6369. }
  6370. #ifdef HAVE_PQC
  6371. static int kyber_id2type(int id, int *type)
  6372. {
  6373. int ret = 0;
  6374. switch (id) {
  6375. #ifdef WOLFSSL_KYBER512
  6376. case WOLFSSL_KYBER_LEVEL1:
  6377. *type = KYBER512;
  6378. break;
  6379. #endif
  6380. #ifdef WOLFSSL_KYBER768
  6381. case WOLFSSL_KYBER_LEVEL3:
  6382. *type = KYBER768;
  6383. break;
  6384. #endif
  6385. #ifdef WOLFSSL_KYBER1024
  6386. case WOLFSSL_KYBER_LEVEL5:
  6387. *type = KYBER1024;
  6388. break;
  6389. #endif
  6390. default:
  6391. ret = NOT_COMPILED_IN;
  6392. break;
  6393. }
  6394. return ret;
  6395. }
  6396. typedef struct PqcHybridMapping {
  6397. int hybrid;
  6398. int ecc;
  6399. int pqc;
  6400. } PqcHybridMapping;
  6401. static const PqcHybridMapping pqc_hybrid_mapping[] = {
  6402. {.hybrid = WOLFSSL_P256_KYBER_LEVEL1, .ecc = WOLFSSL_ECC_SECP256R1,
  6403. .pqc = WOLFSSL_KYBER_LEVEL1},
  6404. {.hybrid = WOLFSSL_P384_KYBER_LEVEL3, .ecc = WOLFSSL_ECC_SECP384R1,
  6405. .pqc = WOLFSSL_KYBER_LEVEL3},
  6406. {.hybrid = WOLFSSL_P521_KYBER_LEVEL5, .ecc = WOLFSSL_ECC_SECP521R1,
  6407. .pqc = WOLFSSL_KYBER_LEVEL5},
  6408. {.hybrid = 0, .ecc = 0, .pqc = 0}
  6409. };
  6410. /* This will map an ecc-pqs hybrid group into its ecc group and pqc kem group.
  6411. * If it cannot find a mapping then *pqc is set to group. ecc is optional. */
  6412. static void findEccPqc(int *ecc, int *pqc, int group)
  6413. {
  6414. int i;
  6415. if (pqc == NULL) {
  6416. return;
  6417. }
  6418. *pqc = 0;
  6419. if (ecc != NULL) {
  6420. *ecc = 0;
  6421. }
  6422. for (i = 0; pqc_hybrid_mapping[i].hybrid != 0; i++) {
  6423. if (pqc_hybrid_mapping[i].hybrid == group) {
  6424. *pqc = pqc_hybrid_mapping[i].pqc;
  6425. if (ecc != NULL) {
  6426. *ecc = pqc_hybrid_mapping[i].ecc;
  6427. }
  6428. break;
  6429. }
  6430. }
  6431. if (*pqc == 0) {
  6432. /* It is not a hybrid, so maybe its simple. */
  6433. *pqc = group;
  6434. }
  6435. }
  6436. /* Create a key share entry using liboqs parameters group.
  6437. * Generates a key pair.
  6438. *
  6439. * ssl The SSL/TLS object.
  6440. * kse The key share entry object.
  6441. * returns 0 on success, otherwise failure.
  6442. */
  6443. static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse)
  6444. {
  6445. int ret = 0;
  6446. int type = 0;
  6447. KyberKey kem[1];
  6448. byte* pubKey = NULL;
  6449. byte* privKey = NULL;
  6450. KeyShareEntry *ecc_kse = NULL;
  6451. int oqs_group = 0;
  6452. int ecc_group = 0;
  6453. word32 privSz = 0;
  6454. word32 pubSz = 0;
  6455. /* This gets called twice. Once during parsing of the key share and once
  6456. * during the population of the extension. No need to do work the second
  6457. * time. Just return success if its already been done. */
  6458. if (kse->pubKey != NULL) {
  6459. return ret;
  6460. }
  6461. findEccPqc(&ecc_group, &oqs_group, kse->group);
  6462. ret = kyber_id2type(oqs_group, &type);
  6463. if (ret == NOT_COMPILED_IN) {
  6464. WOLFSSL_MSG("Invalid Kyber algorithm specified.");
  6465. ret = BAD_FUNC_ARG;
  6466. }
  6467. if (ret == 0) {
  6468. ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId);
  6469. if (ret != 0) {
  6470. WOLFSSL_MSG("Failed to initialize Kyber Key.");
  6471. }
  6472. }
  6473. if (ret == 0) {
  6474. ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap,
  6475. DYNAMIC_TYPE_TLSX);
  6476. if (ecc_kse == NULL) {
  6477. WOLFSSL_MSG("ecc_kse memory allocation failure");
  6478. ret = MEMORY_ERROR;
  6479. }
  6480. }
  6481. if (ret == 0) {
  6482. XMEMSET(ecc_kse, 0, sizeof(*ecc_kse));
  6483. ret = wc_KyberKey_PrivateKeySize(kem, &privSz);
  6484. }
  6485. if (ret == 0) {
  6486. ret = wc_KyberKey_PublicKeySize(kem, &pubSz);
  6487. }
  6488. if (ret == 0 && ecc_group != 0) {
  6489. ecc_kse->group = ecc_group;
  6490. ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse);
  6491. /* If fail, no error message, TLSX_KeyShare_GenEccKey will do it. */
  6492. }
  6493. if (ret == 0) {
  6494. pubKey = (byte*)XMALLOC(ecc_kse->pubKeyLen + pubSz, ssl->heap,
  6495. DYNAMIC_TYPE_PUBLIC_KEY);
  6496. if (pubKey == NULL) {
  6497. WOLFSSL_MSG("pubkey memory allocation failure");
  6498. ret = MEMORY_ERROR;
  6499. }
  6500. }
  6501. if (ret == 0) {
  6502. privKey = (byte*)XMALLOC(privSz, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6503. if (privKey == NULL) {
  6504. WOLFSSL_MSG("privkey memory allocation failure");
  6505. ret = MEMORY_ERROR;
  6506. }
  6507. }
  6508. if (ret == 0) {
  6509. ret = wc_KyberKey_MakeKey(kem, ssl->rng);
  6510. if (ret != 0) {
  6511. WOLFSSL_MSG("Kyber keygen failure");
  6512. }
  6513. }
  6514. if (ret == 0) {
  6515. ret = wc_KyberKey_EncodePublicKey(kem, pubKey + ecc_kse->pubKeyLen,
  6516. pubSz);
  6517. }
  6518. if (ret == 0) {
  6519. ret = wc_KyberKey_EncodePrivateKey(kem, privKey, privSz);
  6520. }
  6521. if (ret == 0) {
  6522. if (ecc_kse->pubKeyLen > 0)
  6523. XMEMCPY(pubKey, ecc_kse->pubKey, ecc_kse->pubKeyLen);
  6524. kse->pubKey = pubKey;
  6525. kse->pubKeyLen = ecc_kse->pubKeyLen + pubSz;
  6526. pubKey = NULL;
  6527. /* Note we are saving the OQS private key and ECC private key
  6528. * separately. That's because the ECC private key is not simply a
  6529. * buffer. Its is an ecc_key struct. Typically do not need the private
  6530. * key size, but will need to zero it out upon freeing. */
  6531. kse->privKey = privKey;
  6532. privKey = NULL;
  6533. kse->privKeyLen = privSz;
  6534. kse->key = ecc_kse->key;
  6535. ecc_kse->key = NULL;
  6536. }
  6537. #ifdef WOLFSSL_DEBUG_TLS
  6538. WOLFSSL_MSG("Public Kyber Key");
  6539. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen );
  6540. #endif
  6541. wc_KyberKey_Free(kem);
  6542. TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap);
  6543. if (pubKey != NULL)
  6544. XFREE(pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6545. if (privKey != NULL)
  6546. XFREE(privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6547. return ret;
  6548. }
  6549. #endif /* HAVE_PQC */
  6550. /* Generate a secret/key using the key share entry.
  6551. *
  6552. * ssl The SSL/TLS object.
  6553. * kse The key share entry holding peer data.
  6554. */
  6555. int TLSX_KeyShare_GenKey(WOLFSSL *ssl, KeyShareEntry *kse)
  6556. {
  6557. int ret;
  6558. /* Named FFDHE groups have a bit set to identify them. */
  6559. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(kse->group))
  6560. ret = TLSX_KeyShare_GenDhKey(ssl, kse);
  6561. else if (kse->group == WOLFSSL_ECC_X25519)
  6562. ret = TLSX_KeyShare_GenX25519Key(ssl, kse);
  6563. else if (kse->group == WOLFSSL_ECC_X448)
  6564. ret = TLSX_KeyShare_GenX448Key(ssl, kse);
  6565. #ifdef HAVE_PQC
  6566. else if (WOLFSSL_NAMED_GROUP_IS_PQC(kse->group))
  6567. ret = TLSX_KeyShare_GenPqcKey(ssl, kse);
  6568. #endif
  6569. else
  6570. ret = TLSX_KeyShare_GenEccKey(ssl, kse);
  6571. #ifdef WOLFSSL_ASYNC_CRYPT
  6572. kse->lastRet = ret;
  6573. #endif
  6574. return ret;
  6575. }
  6576. /* Free the key share dynamic data.
  6577. *
  6578. * list The linked list of key share entry objects.
  6579. * heap The heap used for allocation.
  6580. */
  6581. static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap)
  6582. {
  6583. KeyShareEntry* current;
  6584. while ((current = list) != NULL) {
  6585. list = current->next;
  6586. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(current->group)) {
  6587. #ifndef NO_DH
  6588. wc_FreeDhKey((DhKey*)current->key);
  6589. #endif
  6590. }
  6591. else if (current->group == WOLFSSL_ECC_X25519) {
  6592. #ifdef HAVE_CURVE25519
  6593. wc_curve25519_free((curve25519_key*)current->key);
  6594. #endif
  6595. }
  6596. else if (current->group == WOLFSSL_ECC_X448) {
  6597. #ifdef HAVE_CURVE448
  6598. wc_curve448_free((curve448_key*)current->key);
  6599. #endif
  6600. }
  6601. #ifdef HAVE_PQC
  6602. else if (WOLFSSL_NAMED_GROUP_IS_PQC(current->group)) {
  6603. if (current->key != NULL) {
  6604. ForceZero((byte*)current->key, current->keyLen);
  6605. }
  6606. if (current->pubKey != NULL) {
  6607. XFREE(current->pubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6608. current->pubKey = NULL;
  6609. }
  6610. if (current->privKey != NULL) {
  6611. ForceZero(current->privKey, current->privKeyLen);
  6612. XFREE(current->privKey, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6613. current->privKey = NULL;
  6614. }
  6615. }
  6616. #endif
  6617. else {
  6618. #ifdef HAVE_ECC
  6619. wc_ecc_free((ecc_key*)current->key);
  6620. #endif
  6621. }
  6622. XFREE(current->key, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6623. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  6624. XFREE(current->privKey, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6625. #endif
  6626. XFREE(current->pubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6627. XFREE(current->ke, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6628. XFREE(current, heap, DYNAMIC_TYPE_TLSX);
  6629. }
  6630. (void)heap;
  6631. }
  6632. /* Get the size of the encoded key share extension.
  6633. *
  6634. * list The linked list of key share extensions.
  6635. * msgType The type of the message this extension is being written into.
  6636. * returns the number of bytes of the encoded key share extension.
  6637. */
  6638. static word16 TLSX_KeyShare_GetSize(KeyShareEntry* list, byte msgType)
  6639. {
  6640. word16 len = 0;
  6641. byte isRequest = (msgType == client_hello);
  6642. KeyShareEntry* current;
  6643. /* The named group the server wants to use. */
  6644. if (msgType == hello_retry_request)
  6645. return OPAQUE16_LEN;
  6646. /* List of key exchange groups. */
  6647. if (isRequest)
  6648. len += OPAQUE16_LEN;
  6649. while ((current = list) != NULL) {
  6650. list = current->next;
  6651. if (!isRequest && current->pubKey == NULL)
  6652. continue;
  6653. len += (word16)(KE_GROUP_LEN + OPAQUE16_LEN + current->pubKeyLen);
  6654. }
  6655. return len;
  6656. }
  6657. /* Writes the key share extension into the output buffer.
  6658. * Assumes that the the output buffer is big enough to hold data.
  6659. *
  6660. * list The linked list of key share entries.
  6661. * output The buffer to write into.
  6662. * msgType The type of the message this extension is being written into.
  6663. * returns the number of bytes written into the buffer.
  6664. */
  6665. static word16 TLSX_KeyShare_Write(KeyShareEntry* list, byte* output,
  6666. byte msgType)
  6667. {
  6668. word16 i = 0;
  6669. byte isRequest = (msgType == client_hello);
  6670. KeyShareEntry* current;
  6671. if (msgType == hello_retry_request) {
  6672. c16toa(list->group, output);
  6673. return OPAQUE16_LEN;
  6674. }
  6675. /* ClientHello has a list but ServerHello is only the chosen. */
  6676. if (isRequest)
  6677. i += OPAQUE16_LEN;
  6678. /* Write out all in the list. */
  6679. while ((current = list) != NULL) {
  6680. list = current->next;
  6681. if (!isRequest && current->pubKey == NULL)
  6682. continue;
  6683. c16toa(current->group, &output[i]);
  6684. i += KE_GROUP_LEN;
  6685. c16toa((word16)(current->pubKeyLen), &output[i]);
  6686. i += OPAQUE16_LEN;
  6687. XMEMCPY(&output[i], current->pubKey, current->pubKeyLen);
  6688. i += (word16)current->pubKeyLen;
  6689. }
  6690. /* Write the length of the list if required. */
  6691. if (isRequest)
  6692. c16toa(i - OPAQUE16_LEN, output);
  6693. return i;
  6694. }
  6695. /* Process the DH key share extension on the client side.
  6696. *
  6697. * ssl The SSL/TLS object.
  6698. * keyShareEntry The key share entry object to use to calculate shared secret.
  6699. * returns 0 on success and other values indicate failure.
  6700. */
  6701. static int TLSX_KeyShare_ProcessDh(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6702. {
  6703. int ret = 0;
  6704. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  6705. word32 pSz = 0;
  6706. DhKey* dhKey = (DhKey*)keyShareEntry->key;
  6707. #ifdef HAVE_PUBLIC_FFDHE
  6708. const DhParams* params = NULL;
  6709. switch (keyShareEntry->group) {
  6710. #ifdef HAVE_FFDHE_2048
  6711. case WOLFSSL_FFDHE_2048:
  6712. params = wc_Dh_ffdhe2048_Get();
  6713. break;
  6714. #endif
  6715. #ifdef HAVE_FFDHE_3072
  6716. case WOLFSSL_FFDHE_3072:
  6717. params = wc_Dh_ffdhe3072_Get();
  6718. break;
  6719. #endif
  6720. #ifdef HAVE_FFDHE_4096
  6721. case WOLFSSL_FFDHE_4096:
  6722. params = wc_Dh_ffdhe4096_Get();
  6723. break;
  6724. #endif
  6725. #ifdef HAVE_FFDHE_6144
  6726. case WOLFSSL_FFDHE_6144:
  6727. params = wc_Dh_ffdhe6144_Get();
  6728. break;
  6729. #endif
  6730. #ifdef HAVE_FFDHE_8192
  6731. case WOLFSSL_FFDHE_8192:
  6732. params = wc_Dh_ffdhe8192_Get();
  6733. break;
  6734. #endif
  6735. default:
  6736. break;
  6737. }
  6738. if (params == NULL) {
  6739. WOLFSSL_ERROR_VERBOSE(PEER_KEY_ERROR);
  6740. return PEER_KEY_ERROR;
  6741. }
  6742. pSz = params->p_len;
  6743. #else
  6744. ret = wc_DhGetNamedKeyParamSize(keyShareEntry->group, &pSz, NULL, NULL);
  6745. if (ret != 0 || pSz == 0) {
  6746. WOLFSSL_ERROR_VERBOSE(PEER_KEY_ERROR);
  6747. return PEER_KEY_ERROR;
  6748. }
  6749. #endif
  6750. /* if DhKey is not setup, do it now */
  6751. if (keyShareEntry->key == NULL) {
  6752. keyShareEntry->key = (DhKey*)XMALLOC(sizeof(DhKey), ssl->heap,
  6753. DYNAMIC_TYPE_DH);
  6754. if (keyShareEntry->key == NULL)
  6755. return MEMORY_E;
  6756. /* Setup Key */
  6757. ret = wc_InitDhKey_ex((DhKey*)keyShareEntry->key, ssl->heap, ssl->devId);
  6758. if (ret == 0) {
  6759. dhKey = (DhKey*)keyShareEntry->key;
  6760. /* Set key */
  6761. #ifdef HAVE_PUBLIC_FFDHE
  6762. ret = wc_DhSetKey(dhKey, params->p, params->p_len, params->g,
  6763. params->g_len);
  6764. #else
  6765. ret = wc_DhSetNamedKey(dhKey, keyShareEntry->group);
  6766. #endif
  6767. }
  6768. }
  6769. if (ret == 0
  6770. #ifdef WOLFSSL_ASYNC_CRYPT
  6771. && keyShareEntry->lastRet == 0 /* don't enter here if WC_PENDING_E */
  6772. #endif
  6773. ) {
  6774. #ifdef WOLFSSL_DEBUG_TLS
  6775. WOLFSSL_MSG("Peer DH Key");
  6776. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6777. #endif
  6778. ssl->options.dhKeySz = (word16)pSz;
  6779. /* Derive secret from private key and peer's public key. */
  6780. ret = DhAgree(ssl, dhKey,
  6781. (const byte*)keyShareEntry->privKey, keyShareEntry->keyLen, /* our private */
  6782. keyShareEntry->ke, keyShareEntry->keLen, /* peer's public key */
  6783. ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz, /* secret */
  6784. NULL, 0
  6785. );
  6786. #ifdef WOLFSSL_ASYNC_CRYPT
  6787. if (ret == WC_PENDING_E) {
  6788. return ret;
  6789. }
  6790. #endif
  6791. }
  6792. /* RFC 8446 Section 7.4.1:
  6793. * ... left-padded with zeros up to the size of the prime. ...
  6794. */
  6795. if (ret == 0 && (word32)ssl->options.dhKeySz > ssl->arrays->preMasterSz) {
  6796. word32 diff = (word32)ssl->options.dhKeySz - ssl->arrays->preMasterSz;
  6797. XMEMMOVE(ssl->arrays->preMasterSecret + diff,
  6798. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  6799. XMEMSET(ssl->arrays->preMasterSecret, 0, diff);
  6800. ssl->arrays->preMasterSz = ssl->options.dhKeySz;
  6801. }
  6802. /* done with key share, release resources */
  6803. if (dhKey)
  6804. wc_FreeDhKey(dhKey);
  6805. if (keyShareEntry->key) {
  6806. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_DH);
  6807. keyShareEntry->key = NULL;
  6808. }
  6809. if (keyShareEntry->privKey != NULL) {
  6810. XFREE(keyShareEntry->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6811. keyShareEntry->privKey = NULL;
  6812. }
  6813. if (keyShareEntry->pubKey != NULL) {
  6814. XFREE(keyShareEntry->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6815. keyShareEntry->pubKey = NULL;
  6816. }
  6817. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6818. keyShareEntry->ke = NULL;
  6819. #else
  6820. (void)ssl;
  6821. (void)keyShareEntry;
  6822. ret = PEER_KEY_ERROR;
  6823. WOLFSSL_ERROR_VERBOSE(ret);
  6824. #endif
  6825. return ret;
  6826. }
  6827. /* Process the X25519 key share extension on the client side.
  6828. *
  6829. * ssl The SSL/TLS object.
  6830. * keyShareEntry The key share entry object to use to calculate shared secret.
  6831. * returns 0 on success and other values indicate failure.
  6832. */
  6833. static int TLSX_KeyShare_ProcessX25519(WOLFSSL* ssl,
  6834. KeyShareEntry* keyShareEntry)
  6835. {
  6836. int ret;
  6837. #ifdef HAVE_CURVE25519
  6838. curve25519_key* key = (curve25519_key*)keyShareEntry->key;
  6839. curve25519_key* peerX25519Key;
  6840. #ifdef HAVE_ECC
  6841. if (ssl->peerEccKey != NULL) {
  6842. wc_ecc_free(ssl->peerEccKey);
  6843. ssl->peerEccKey = NULL;
  6844. ssl->peerEccKeyPresent = 0;
  6845. }
  6846. #endif
  6847. peerX25519Key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), ssl->heap,
  6848. DYNAMIC_TYPE_TLSX);
  6849. if (peerX25519Key == NULL) {
  6850. WOLFSSL_MSG("PeerEccKey Memory error");
  6851. return MEMORY_ERROR;
  6852. }
  6853. ret = wc_curve25519_init(peerX25519Key);
  6854. if (ret != 0) {
  6855. XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6856. return ret;
  6857. }
  6858. #ifdef WOLFSSL_DEBUG_TLS
  6859. WOLFSSL_MSG("Peer Curve25519 Key");
  6860. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6861. #endif
  6862. if (wc_curve25519_check_public(keyShareEntry->ke, keyShareEntry->keLen,
  6863. EC25519_LITTLE_ENDIAN) != 0) {
  6864. ret = ECC_PEERKEY_ERROR;
  6865. WOLFSSL_ERROR_VERBOSE(ret);
  6866. }
  6867. if (ret == 0) {
  6868. if (wc_curve25519_import_public_ex(keyShareEntry->ke,
  6869. keyShareEntry->keLen, peerX25519Key,
  6870. EC25519_LITTLE_ENDIAN) != 0) {
  6871. ret = ECC_PEERKEY_ERROR;
  6872. WOLFSSL_ERROR_VERBOSE(ret);
  6873. }
  6874. }
  6875. if (ret == 0) {
  6876. ssl->ecdhCurveOID = ECC_X25519_OID;
  6877. ret = wc_curve25519_shared_secret_ex(key, peerX25519Key,
  6878. ssl->arrays->preMasterSecret,
  6879. &ssl->arrays->preMasterSz,
  6880. EC25519_LITTLE_ENDIAN);
  6881. }
  6882. wc_curve25519_free(peerX25519Key);
  6883. XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6884. wc_curve25519_free((curve25519_key*)keyShareEntry->key);
  6885. if (keyShareEntry->key != NULL) {
  6886. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6887. keyShareEntry->key = NULL;
  6888. }
  6889. #else
  6890. (void)ssl;
  6891. (void)keyShareEntry;
  6892. ret = PEER_KEY_ERROR;
  6893. WOLFSSL_ERROR_VERBOSE(ret);
  6894. #endif /* HAVE_CURVE25519 */
  6895. return ret;
  6896. }
  6897. /* Process the X448 key share extension on the client side.
  6898. *
  6899. * ssl The SSL/TLS object.
  6900. * keyShareEntry The key share entry object to use to calculate shared secret.
  6901. * returns 0 on success and other values indicate failure.
  6902. */
  6903. static int TLSX_KeyShare_ProcessX448(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6904. {
  6905. int ret;
  6906. #ifdef HAVE_CURVE448
  6907. curve448_key* key = (curve448_key*)keyShareEntry->key;
  6908. curve448_key* peerX448Key;
  6909. #ifdef HAVE_ECC
  6910. if (ssl->peerEccKey != NULL) {
  6911. wc_ecc_free(ssl->peerEccKey);
  6912. ssl->peerEccKey = NULL;
  6913. ssl->peerEccKeyPresent = 0;
  6914. }
  6915. #endif
  6916. peerX448Key = (curve448_key*)XMALLOC(sizeof(curve448_key), ssl->heap,
  6917. DYNAMIC_TYPE_TLSX);
  6918. if (peerX448Key == NULL) {
  6919. WOLFSSL_MSG("PeerEccKey Memory error");
  6920. return MEMORY_ERROR;
  6921. }
  6922. ret = wc_curve448_init(peerX448Key);
  6923. if (ret != 0) {
  6924. XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6925. return ret;
  6926. }
  6927. #ifdef WOLFSSL_DEBUG_TLS
  6928. WOLFSSL_MSG("Peer Curve448 Key");
  6929. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6930. #endif
  6931. if (wc_curve448_check_public(keyShareEntry->ke, keyShareEntry->keLen,
  6932. EC448_LITTLE_ENDIAN) != 0) {
  6933. ret = ECC_PEERKEY_ERROR;
  6934. WOLFSSL_ERROR_VERBOSE(ret);
  6935. }
  6936. if (ret == 0) {
  6937. if (wc_curve448_import_public_ex(keyShareEntry->ke,
  6938. keyShareEntry->keLen, peerX448Key,
  6939. EC448_LITTLE_ENDIAN) != 0) {
  6940. ret = ECC_PEERKEY_ERROR;
  6941. WOLFSSL_ERROR_VERBOSE(ret);
  6942. }
  6943. }
  6944. if (ret == 0) {
  6945. ssl->ecdhCurveOID = ECC_X448_OID;
  6946. ret = wc_curve448_shared_secret_ex(key, peerX448Key,
  6947. ssl->arrays->preMasterSecret,
  6948. &ssl->arrays->preMasterSz,
  6949. EC448_LITTLE_ENDIAN);
  6950. }
  6951. wc_curve448_free(peerX448Key);
  6952. XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6953. wc_curve448_free((curve448_key*)keyShareEntry->key);
  6954. if (keyShareEntry->key != NULL) {
  6955. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6956. keyShareEntry->key = NULL;
  6957. }
  6958. #else
  6959. (void)ssl;
  6960. (void)keyShareEntry;
  6961. ret = PEER_KEY_ERROR;
  6962. WOLFSSL_ERROR_VERBOSE(ret);
  6963. #endif /* HAVE_CURVE448 */
  6964. return ret;
  6965. }
  6966. /* Process the ECC key share extension on the client side.
  6967. *
  6968. * ssl The SSL/TLS object.
  6969. * keyShareEntry The key share entry object to use to calculate shared secret.
  6970. * returns 0 on success and other values indicate failure.
  6971. */
  6972. static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6973. {
  6974. int ret = 0;
  6975. #ifdef HAVE_ECC
  6976. int curveId = ECC_CURVE_INVALID;
  6977. ecc_key* eccKey = (ecc_key*)keyShareEntry->key;
  6978. /* find supported curve */
  6979. switch (keyShareEntry->group) {
  6980. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  6981. #ifndef NO_ECC_SECP
  6982. case WOLFSSL_ECC_SECP256R1:
  6983. curveId = ECC_SECP256R1;
  6984. break;
  6985. #endif /* !NO_ECC_SECP */
  6986. #ifdef WOLFSSL_SM2
  6987. case WOLFSSL_ECC_SM2P256V1:
  6988. curveId = ECC_SM2P256V1;
  6989. break;
  6990. #endif
  6991. #endif
  6992. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  6993. #ifndef NO_ECC_SECP
  6994. case WOLFSSL_ECC_SECP384R1:
  6995. curveId = ECC_SECP384R1;
  6996. break;
  6997. #endif /* !NO_ECC_SECP */
  6998. #endif
  6999. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  7000. #ifndef NO_ECC_SECP
  7001. case WOLFSSL_ECC_SECP521R1:
  7002. curveId = ECC_SECP521R1;
  7003. break;
  7004. #endif /* !NO_ECC_SECP */
  7005. #endif
  7006. #if defined(HAVE_X448) && ECC_MIN_KEY_SZ <= 448
  7007. case WOLFSSL_ECC_X448:
  7008. curveId = ECC_X448;
  7009. break;
  7010. #endif
  7011. default:
  7012. /* unsupported curve */
  7013. WOLFSSL_ERROR_VERBOSE(ECC_PEERKEY_ERROR);
  7014. return ECC_PEERKEY_ERROR;
  7015. }
  7016. #ifdef WOLFSSL_ASYNC_CRYPT
  7017. if (keyShareEntry->lastRet == 0) /* don't enter here if WC_PENDING_E */
  7018. #endif
  7019. {
  7020. #ifdef WOLFSSL_DEBUG_TLS
  7021. WOLFSSL_MSG("Peer ECC Key");
  7022. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  7023. #endif
  7024. if (ssl->peerEccKey != NULL) {
  7025. wc_ecc_free(ssl->peerEccKey);
  7026. XFREE(ssl->peerEccKey, ssl->heap, DYNAMIC_TYPE_ECC);
  7027. ssl->peerEccKeyPresent = 0;
  7028. }
  7029. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  7030. ret = tsip_Tls13GenSharedSecret(ssl, keyShareEntry);
  7031. if (ret != CRYPTOCB_UNAVAILABLE) {
  7032. return ret;
  7033. }
  7034. ret = 0;
  7035. #endif
  7036. ssl->peerEccKey = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
  7037. DYNAMIC_TYPE_ECC);
  7038. if (ssl->peerEccKey == NULL) {
  7039. WOLFSSL_MSG("PeerEccKey Memory error");
  7040. ret = MEMORY_ERROR;
  7041. }
  7042. if (ret == 0) {
  7043. ret = wc_ecc_init_ex(ssl->peerEccKey, ssl->heap, ssl->devId);
  7044. }
  7045. /* Point is validated by import function. */
  7046. if (ret == 0) {
  7047. ret = wc_ecc_import_x963_ex(keyShareEntry->ke, keyShareEntry->keLen,
  7048. ssl->peerEccKey, curveId);
  7049. if (ret != 0) {
  7050. ret = ECC_PEERKEY_ERROR;
  7051. WOLFSSL_ERROR_VERBOSE(ret);
  7052. }
  7053. }
  7054. if (ret == 0) {
  7055. ssl->ecdhCurveOID = ssl->peerEccKey->dp->oidSum;
  7056. ssl->peerEccKeyPresent = 1;
  7057. }
  7058. }
  7059. if (ret == 0 && eccKey == NULL)
  7060. ret = BAD_FUNC_ARG;
  7061. if (ret == 0) {
  7062. ret = EccSharedSecret(ssl, eccKey, ssl->peerEccKey,
  7063. keyShareEntry->ke, &keyShareEntry->keLen,
  7064. ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz,
  7065. ssl->options.side
  7066. );
  7067. #ifdef WOLFSSL_ASYNC_CRYPT
  7068. if (ret == WC_PENDING_E)
  7069. return ret;
  7070. #endif
  7071. }
  7072. /* done with key share, release resources */
  7073. if (ssl->peerEccKey != NULL
  7074. #ifdef HAVE_PK_CALLBACKS
  7075. && ssl->ctx->EccSharedSecretCb == NULL
  7076. #endif
  7077. ) {
  7078. wc_ecc_free(ssl->peerEccKey);
  7079. XFREE(ssl->peerEccKey, ssl->heap, DYNAMIC_TYPE_ECC);
  7080. ssl->peerEccKey = NULL;
  7081. ssl->peerEccKeyPresent = 0;
  7082. }
  7083. if (keyShareEntry->key) {
  7084. wc_ecc_free((ecc_key*)keyShareEntry->key);
  7085. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_ECC);
  7086. keyShareEntry->key = NULL;
  7087. }
  7088. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7089. keyShareEntry->ke = NULL;
  7090. #else
  7091. (void)ssl;
  7092. (void)keyShareEntry;
  7093. ret = PEER_KEY_ERROR;
  7094. WOLFSSL_ERROR_VERBOSE(ret);
  7095. #endif /* HAVE_ECC */
  7096. return ret;
  7097. }
  7098. #ifdef HAVE_PQC
  7099. /* Process the Kyber key share extension on the client side.
  7100. *
  7101. * ssl The SSL/TLS object.
  7102. * keyShareEntry The key share entry object to use to calculate shared secret.
  7103. * returns 0 on success and other values indicate failure.
  7104. */
  7105. static int TLSX_KeyShare_ProcessPqc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  7106. {
  7107. int ret = 0;
  7108. int type;
  7109. KyberKey kem[1];
  7110. byte* sharedSecret = NULL;
  7111. word32 sharedSecretLen = 0;
  7112. int oqs_group = 0;
  7113. int ecc_group = 0;
  7114. ecc_key eccpubkey;
  7115. word32 outlen = 0;
  7116. word32 privSz = 0;
  7117. word32 ctSz = 0;
  7118. word32 ssSz = 0;
  7119. if (keyShareEntry->ke == NULL) {
  7120. WOLFSSL_MSG("Invalid OQS algorithm specified.");
  7121. return BAD_FUNC_ARG;
  7122. }
  7123. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7124. /* I am the server, the shared secret has already been generated and
  7125. * is in keyShareEntry->ke; copy it to the pre-master secret
  7126. * pre-allocated buffer. */
  7127. if (keyShareEntry->keLen > ENCRYPT_LEN) {
  7128. WOLFSSL_MSG("shared secret is too long.");
  7129. return LENGTH_ERROR;
  7130. }
  7131. XMEMCPY(ssl->arrays->preMasterSecret, keyShareEntry->ke,
  7132. keyShareEntry->keLen);
  7133. ssl->arrays->preMasterSz = keyShareEntry->keLen;
  7134. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_SECRET);
  7135. keyShareEntry->ke = NULL;
  7136. keyShareEntry->keLen = 0;
  7137. return 0;
  7138. }
  7139. /* I am the client, the ciphertext is in keyShareEntry->ke */
  7140. findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group);
  7141. ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId);
  7142. if (ret != 0) {
  7143. WOLFSSL_MSG("Memory allocation error.");
  7144. return MEMORY_E;
  7145. }
  7146. ret = kyber_id2type(oqs_group, &type);
  7147. if (ret != 0) {
  7148. wc_ecc_free(&eccpubkey);
  7149. WOLFSSL_MSG("Invalid OQS algorithm specified.");
  7150. return BAD_FUNC_ARG;
  7151. }
  7152. ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId);
  7153. if (ret != 0) {
  7154. wc_ecc_free(&eccpubkey);
  7155. WOLFSSL_MSG("Error creating Kyber KEM");
  7156. return MEMORY_E;
  7157. }
  7158. if (ret == 0) {
  7159. ret = wc_KyberKey_SharedSecretSize(kem, &ssSz);
  7160. }
  7161. if (ret == 0) {
  7162. sharedSecretLen = ssSz;
  7163. switch (ecc_group) {
  7164. case WOLFSSL_ECC_SECP256R1:
  7165. sharedSecretLen += 32;
  7166. outlen = 32;
  7167. break;
  7168. case WOLFSSL_ECC_SECP384R1:
  7169. sharedSecretLen += 48;
  7170. outlen = 48;
  7171. break;
  7172. case WOLFSSL_ECC_SECP521R1:
  7173. sharedSecretLen += 66;
  7174. outlen = 66;
  7175. break;
  7176. default:
  7177. break;
  7178. }
  7179. }
  7180. if (ret == 0) {
  7181. sharedSecret = (byte*)XMALLOC(sharedSecretLen, ssl->heap,
  7182. DYNAMIC_TYPE_TLSX);
  7183. if (sharedSecret == NULL) {
  7184. WOLFSSL_MSG("Memory allocation error.");
  7185. ret = MEMORY_E;
  7186. }
  7187. }
  7188. if (ret == 0) {
  7189. ret = wc_KyberKey_CipherTextSize(kem, &ctSz);
  7190. }
  7191. if (ret == 0) {
  7192. ret = wc_KyberKey_PrivateKeySize(kem, &privSz);
  7193. }
  7194. if (ret == 0) {
  7195. ret = wc_KyberKey_DecodePrivateKey(kem, keyShareEntry->privKey, privSz);
  7196. }
  7197. if (ret == 0) {
  7198. ret = wc_KyberKey_Decapsulate(kem, sharedSecret + outlen,
  7199. keyShareEntry->ke + keyShareEntry->keLen - ctSz, ctSz);
  7200. if (ret != 0) {
  7201. WOLFSSL_MSG("wc_KyberKey decapsulation failure.");
  7202. ret = BAD_FUNC_ARG;
  7203. }
  7204. }
  7205. if (ecc_group != 0) {
  7206. if (ret == 0) {
  7207. /* Point is validated by import function. */
  7208. ret = wc_ecc_import_x963(keyShareEntry->ke,
  7209. keyShareEntry->keLen - ctSz,
  7210. &eccpubkey);
  7211. if (ret != 0) {
  7212. WOLFSSL_MSG("ECC Public key import error.");
  7213. }
  7214. }
  7215. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  7216. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  7217. !defined(HAVE_SELFTEST)
  7218. if (ret == 0) {
  7219. ret = wc_ecc_set_rng(keyShareEntry->key, ssl->rng);
  7220. if (ret != 0) {
  7221. WOLFSSL_MSG("Failure to set the ECC private key RNG.");
  7222. }
  7223. }
  7224. #endif
  7225. if (ret == 0) {
  7226. PRIVATE_KEY_UNLOCK();
  7227. ret = wc_ecc_shared_secret(keyShareEntry->key, &eccpubkey,
  7228. sharedSecret, &outlen);
  7229. PRIVATE_KEY_LOCK();
  7230. if (outlen != sharedSecretLen - ssSz) {
  7231. WOLFSSL_MSG("ECC shared secret derivation error.");
  7232. ret = BAD_FUNC_ARG;
  7233. }
  7234. }
  7235. }
  7236. if ((ret == 0) && (sharedSecretLen > ENCRYPT_LEN)) {
  7237. WOLFSSL_MSG("shared secret is too long.");
  7238. ret = LENGTH_ERROR;
  7239. }
  7240. if (ret == 0) {
  7241. /* Copy the shared secret to the pre-master secret pre-allocated
  7242. * buffer. */
  7243. XMEMCPY(ssl->arrays->preMasterSecret, sharedSecret, sharedSecretLen);
  7244. ssl->arrays->preMasterSz = (word32) sharedSecretLen;
  7245. }
  7246. if (sharedSecret != NULL) {
  7247. XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  7248. }
  7249. wc_ecc_free(&eccpubkey);
  7250. wc_KyberKey_Free(kem);
  7251. return ret;
  7252. }
  7253. #endif /* HAVE_PQC */
  7254. /* Process the key share extension on the client side.
  7255. *
  7256. * ssl The SSL/TLS object.
  7257. * keyShareEntry The key share entry object to use to calculate shared secret.
  7258. * returns 0 on success and other values indicate failure.
  7259. */
  7260. static int TLSX_KeyShare_Process(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  7261. {
  7262. int ret;
  7263. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  7264. ssl->session->namedGroup = keyShareEntry->group;
  7265. #endif
  7266. /* reset the pre master secret size */
  7267. if (ssl->arrays->preMasterSz == 0)
  7268. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  7269. /* Use Key Share Data from server. */
  7270. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(keyShareEntry->group))
  7271. ret = TLSX_KeyShare_ProcessDh(ssl, keyShareEntry);
  7272. else if (keyShareEntry->group == WOLFSSL_ECC_X25519)
  7273. ret = TLSX_KeyShare_ProcessX25519(ssl, keyShareEntry);
  7274. else if (keyShareEntry->group == WOLFSSL_ECC_X448)
  7275. ret = TLSX_KeyShare_ProcessX448(ssl, keyShareEntry);
  7276. #ifdef HAVE_PQC
  7277. else if (WOLFSSL_NAMED_GROUP_IS_PQC(keyShareEntry->group))
  7278. ret = TLSX_KeyShare_ProcessPqc(ssl, keyShareEntry);
  7279. #endif
  7280. else
  7281. ret = TLSX_KeyShare_ProcessEcc(ssl, keyShareEntry);
  7282. #ifdef WOLFSSL_DEBUG_TLS
  7283. if (ret == 0) {
  7284. WOLFSSL_MSG("KE Secret");
  7285. WOLFSSL_BUFFER(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  7286. }
  7287. #endif
  7288. #ifdef WOLFSSL_ASYNC_CRYPT
  7289. keyShareEntry->lastRet = ret;
  7290. #endif
  7291. return ret;
  7292. }
  7293. /* Parse an entry of the KeyShare extension.
  7294. *
  7295. * ssl The SSL/TLS object.
  7296. * input The extension data.
  7297. * length The length of the extension data.
  7298. * kse The new key share entry object.
  7299. * returns a positive number to indicate amount of data parsed and a negative
  7300. * number on error.
  7301. */
  7302. static int TLSX_KeyShareEntry_Parse(const WOLFSSL* ssl, const byte* input,
  7303. word16 length, KeyShareEntry **kse, TLSX** extensions)
  7304. {
  7305. int ret;
  7306. word16 group;
  7307. word16 keLen;
  7308. int offset = 0;
  7309. byte* ke;
  7310. if (length < OPAQUE16_LEN + OPAQUE16_LEN)
  7311. return BUFFER_ERROR;
  7312. /* Named group */
  7313. ato16(&input[offset], &group);
  7314. offset += OPAQUE16_LEN;
  7315. /* Key exchange data - public key. */
  7316. ato16(&input[offset], &keLen);
  7317. offset += OPAQUE16_LEN;
  7318. if (keLen == 0)
  7319. return INVALID_PARAMETER;
  7320. if (keLen > length - offset)
  7321. return BUFFER_ERROR;
  7322. #ifdef HAVE_PQC
  7323. if (WOLFSSL_NAMED_GROUP_IS_PQC(group) &&
  7324. ssl->options.side == WOLFSSL_SERVER_END) {
  7325. /* For KEMs, the public key is not stored. Casting away const because
  7326. * we know for KEMs, it will be read-only.*/
  7327. ke = (byte *)&input[offset];
  7328. } else
  7329. #endif
  7330. {
  7331. /* Store a copy in the key share object. */
  7332. ke = (byte*)XMALLOC(keLen, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7333. if (ke == NULL)
  7334. return MEMORY_E;
  7335. XMEMCPY(ke, &input[offset], keLen);
  7336. }
  7337. /* Populate a key share object in the extension. */
  7338. ret = TLSX_KeyShare_Use(ssl, group, keLen, ke, kse, extensions);
  7339. if (ret != 0) {
  7340. if (ke != &input[offset]) {
  7341. XFREE(ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7342. }
  7343. return ret;
  7344. }
  7345. /* Total length of the parsed data. */
  7346. return offset + keLen;
  7347. }
  7348. /* Searches the groups sent for the specified named group.
  7349. *
  7350. * ssl SSL/TLS object.
  7351. * name Group name to match.
  7352. * returns 1 when the extension has the group name and 0 otherwise.
  7353. */
  7354. static int TLSX_KeyShare_Find(WOLFSSL* ssl, word16 group)
  7355. {
  7356. TLSX* extension;
  7357. KeyShareEntry* list;
  7358. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  7359. if (extension == NULL) {
  7360. extension = TLSX_Find(ssl->ctx->extensions, TLSX_KEY_SHARE);
  7361. if (extension == NULL)
  7362. return 0;
  7363. }
  7364. list = (KeyShareEntry*)extension->data;
  7365. while (list != NULL) {
  7366. if (list->group == group)
  7367. return 1;
  7368. list = list->next;
  7369. }
  7370. return 0;
  7371. }
  7372. /* Searches the supported groups extension for the specified named group.
  7373. *
  7374. * ssl The SSL/TLS object.
  7375. * name The group name to match.
  7376. * returns 1 when the extension has the group name and 0 otherwise.
  7377. */
  7378. static int TLSX_SupportedGroups_Find(const WOLFSSL* ssl, word16 name,
  7379. TLSX* extensions)
  7380. {
  7381. #ifdef HAVE_SUPPORTED_CURVES
  7382. TLSX* extension;
  7383. SupportedCurve* curve = NULL;
  7384. if ((extension = TLSX_Find(extensions, TLSX_SUPPORTED_GROUPS)) == NULL) {
  7385. if ((extension = TLSX_Find(ssl->ctx->extensions,
  7386. TLSX_SUPPORTED_GROUPS)) == NULL) {
  7387. return 0;
  7388. }
  7389. }
  7390. for (curve = (SupportedCurve*)extension->data; curve; curve = curve->next) {
  7391. if (curve->name == name)
  7392. return 1;
  7393. }
  7394. #endif
  7395. (void)ssl;
  7396. (void)name;
  7397. return 0;
  7398. }
  7399. int TLSX_KeyShare_Parse_ClientHello(const WOLFSSL* ssl,
  7400. const byte* input, word16 length, TLSX** extensions)
  7401. {
  7402. int ret;
  7403. int offset = 0;
  7404. word16 len;
  7405. TLSX* extension;
  7406. /* Add a KeyShare extension if it doesn't exist even if peer sent no
  7407. * entries. The presence of this extension signals that the peer can be
  7408. * negotiated with. */
  7409. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7410. if (extension == NULL) {
  7411. /* Push new KeyShare extension. */
  7412. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7413. if (ret != 0)
  7414. return ret;
  7415. }
  7416. if (length < OPAQUE16_LEN)
  7417. return BUFFER_ERROR;
  7418. /* ClientHello contains zero or more key share entries. */
  7419. ato16(input, &len);
  7420. if (len != length - OPAQUE16_LEN)
  7421. return BUFFER_ERROR;
  7422. offset += OPAQUE16_LEN;
  7423. while (offset < (int)length) {
  7424. ret = TLSX_KeyShareEntry_Parse(ssl, &input[offset],
  7425. length - (word16)offset, NULL, extensions);
  7426. if (ret < 0)
  7427. return ret;
  7428. offset += ret;
  7429. }
  7430. return 0;
  7431. }
  7432. /* Parse the KeyShare extension.
  7433. * Different formats in different messages.
  7434. *
  7435. * ssl The SSL/TLS object.
  7436. * input The extension data.
  7437. * length The length of the extension data.
  7438. * msgType The type of the message this extension is being parsed from.
  7439. * returns 0 on success and other values indicate failure.
  7440. */
  7441. int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  7442. byte msgType)
  7443. {
  7444. int ret = 0;
  7445. KeyShareEntry *keyShareEntry = NULL;
  7446. word16 group;
  7447. if (msgType == client_hello) {
  7448. ret = TLSX_KeyShare_Parse_ClientHello(ssl, input, length,
  7449. &ssl->extensions);
  7450. }
  7451. else if (msgType == server_hello) {
  7452. int len;
  7453. if (length < OPAQUE16_LEN)
  7454. return BUFFER_ERROR;
  7455. /* The data is the named group the server wants to use. */
  7456. ato16(input, &group);
  7457. /* Check the selected group was supported by ClientHello extensions. */
  7458. if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) {
  7459. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7460. return BAD_KEY_SHARE_DATA;
  7461. }
  7462. /* Check if the group was sent. */
  7463. if (!TLSX_KeyShare_Find(ssl, group)) {
  7464. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7465. return BAD_KEY_SHARE_DATA;
  7466. }
  7467. /* ServerHello contains one key share entry. */
  7468. len = TLSX_KeyShareEntry_Parse(ssl, input, length, &keyShareEntry,
  7469. &ssl->extensions);
  7470. if (len != (int)length)
  7471. return BUFFER_ERROR;
  7472. /* Not in list sent if there isn't a private key. */
  7473. if (keyShareEntry == NULL || (keyShareEntry->key == NULL
  7474. #if !defined(NO_DH) || defined(HAVE_PQC)
  7475. && keyShareEntry->privKey == NULL
  7476. #endif
  7477. )) {
  7478. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7479. return BAD_KEY_SHARE_DATA;
  7480. }
  7481. /* Process the entry to calculate the secret. */
  7482. ret = TLSX_KeyShare_Process(ssl, keyShareEntry);
  7483. if (ret == 0)
  7484. ssl->session->namedGroup = ssl->namedGroup = group;
  7485. }
  7486. else if (msgType == hello_retry_request) {
  7487. if (length != OPAQUE16_LEN)
  7488. return BUFFER_ERROR;
  7489. /* The data is the named group the server wants to use. */
  7490. ato16(input, &group);
  7491. #ifdef WOLFSSL_ASYNC_CRYPT
  7492. /* only perform find and clear TLSX if not returning from async */
  7493. if (ssl->error != WC_PENDING_E)
  7494. #endif
  7495. {
  7496. /* Check the selected group was supported by ClientHello extensions. */
  7497. if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) {
  7498. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7499. return BAD_KEY_SHARE_DATA;
  7500. }
  7501. /* Check if the group was sent. */
  7502. if (TLSX_KeyShare_Find(ssl, group)) {
  7503. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7504. return BAD_KEY_SHARE_DATA;
  7505. }
  7506. /* Clear out unusable key shares. */
  7507. ret = TLSX_KeyShare_Empty(ssl);
  7508. if (ret != 0)
  7509. return ret;
  7510. }
  7511. ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL, &ssl->extensions);
  7512. if (ret == 0)
  7513. ssl->session->namedGroup = ssl->namedGroup = group;
  7514. }
  7515. else {
  7516. /* Not a message type that is allowed to have this extension. */
  7517. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  7518. return SANITY_MSG_E;
  7519. }
  7520. return ret;
  7521. }
  7522. /* Create a new key share entry and put it into the list.
  7523. *
  7524. * list The linked list of key share entries.
  7525. * group The named group.
  7526. * heap The memory to allocate with.
  7527. * keyShareEntry The new key share entry object.
  7528. * returns 0 on success and other values indicate failure.
  7529. */
  7530. static int TLSX_KeyShare_New(KeyShareEntry** list, int group, void *heap,
  7531. KeyShareEntry** keyShareEntry)
  7532. {
  7533. KeyShareEntry* kse;
  7534. KeyShareEntry** next;
  7535. kse = (KeyShareEntry*)XMALLOC(sizeof(KeyShareEntry), heap,
  7536. DYNAMIC_TYPE_TLSX);
  7537. if (kse == NULL)
  7538. return MEMORY_E;
  7539. XMEMSET(kse, 0, sizeof(*kse));
  7540. kse->group = (word16)group;
  7541. /* Add it to the back and maintain the links. */
  7542. while (*list != NULL) {
  7543. /* Assign to temporary to work around compiler bug found by customer. */
  7544. next = &((*list)->next);
  7545. list = next;
  7546. }
  7547. *list = kse;
  7548. *keyShareEntry = kse;
  7549. (void)heap;
  7550. return 0;
  7551. }
  7552. #ifdef HAVE_PQC
  7553. static int server_generate_pqc_ciphertext(WOLFSSL* ssl,
  7554. KeyShareEntry* keyShareEntry, byte* data, word16 len)
  7555. {
  7556. /* I am the server. The data parameter is the client's public key. I need
  7557. * to generate the public information (AKA ciphertext) and shared secret
  7558. * here. Note the "public information" is equivalent to a the public key in
  7559. * key exchange parlance. That's why it is being assigned to pubKey.
  7560. */
  7561. int type;
  7562. KyberKey kem[1];
  7563. byte* sharedSecret = NULL;
  7564. byte* ciphertext = NULL;
  7565. int ret = 0;
  7566. int oqs_group = 0;
  7567. int ecc_group = 0;
  7568. KeyShareEntry *ecc_kse = NULL;
  7569. ecc_key eccpubkey;
  7570. word32 outlen = 0;
  7571. word32 pubSz = 0;
  7572. word32 ctSz = 0;
  7573. word32 ssSz = 0;
  7574. findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group);
  7575. ret = kyber_id2type(oqs_group, &type);
  7576. if (ret != 0) {
  7577. WOLFSSL_MSG("Invalid Kyber algorithm specified.");
  7578. return BAD_FUNC_ARG;
  7579. }
  7580. ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId);
  7581. if (ret != 0) {
  7582. WOLFSSL_MSG("Could not do ECC public key initialization.");
  7583. return MEMORY_E;
  7584. }
  7585. ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId);
  7586. if (ret != 0) {
  7587. wc_ecc_free(&eccpubkey);
  7588. WOLFSSL_MSG("Error creating Kyber KEM");
  7589. return MEMORY_E;
  7590. }
  7591. if (ret == 0) {
  7592. ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap,
  7593. DYNAMIC_TYPE_TLSX);
  7594. if (ecc_kse == NULL) {
  7595. WOLFSSL_MSG("ecc_kse memory allocation failure");
  7596. ret = MEMORY_ERROR;
  7597. }
  7598. }
  7599. if (ret == 0) {
  7600. XMEMSET(ecc_kse, 0, sizeof(*ecc_kse));
  7601. }
  7602. if (ret == 0 && ecc_group != 0) {
  7603. ecc_kse->group = ecc_group;
  7604. ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse);
  7605. /* No message, TLSX_KeyShare_GenEccKey() will do it. */
  7606. }
  7607. if (ret == 0) {
  7608. ret = wc_KyberKey_PublicKeySize(kem, &pubSz);
  7609. }
  7610. if (ret == 0) {
  7611. ret = wc_KyberKey_CipherTextSize(kem, &ctSz);
  7612. }
  7613. if (ret == 0) {
  7614. ret = wc_KyberKey_SharedSecretSize(kem, &ssSz);
  7615. }
  7616. if (ret == 0 && len != pubSz + ecc_kse->pubKeyLen) {
  7617. WOLFSSL_MSG("Invalid public key.");
  7618. ret = BAD_FUNC_ARG;
  7619. }
  7620. if (ret == 0) {
  7621. sharedSecret = (byte*)XMALLOC(ecc_kse->keyLen + ssSz, ssl->heap,
  7622. DYNAMIC_TYPE_SECRET);
  7623. ciphertext = (byte*)XMALLOC(ecc_kse->pubKeyLen + ctSz, ssl->heap,
  7624. DYNAMIC_TYPE_TLSX);
  7625. if (sharedSecret == NULL || ciphertext == NULL) {
  7626. WOLFSSL_MSG("Ciphertext/shared secret memory allocation failure.");
  7627. ret = MEMORY_E;
  7628. }
  7629. }
  7630. if (ecc_group != 0) {
  7631. if (ret == 0) {
  7632. /* Point is validated by import function. */
  7633. ret = wc_ecc_import_x963(data, len - pubSz, &eccpubkey);
  7634. if (ret != 0) {
  7635. WOLFSSL_MSG("Bad ECC public key.");
  7636. }
  7637. }
  7638. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  7639. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  7640. !defined(HAVE_SELFTEST)
  7641. if (ret == 0) {
  7642. ret = wc_ecc_set_rng(ecc_kse->key, ssl->rng);
  7643. }
  7644. #endif
  7645. if (ret == 0) {
  7646. outlen = ecc_kse->keyLen;
  7647. PRIVATE_KEY_UNLOCK();
  7648. ret = wc_ecc_shared_secret(ecc_kse->key, &eccpubkey,
  7649. sharedSecret,
  7650. &outlen);
  7651. PRIVATE_KEY_LOCK();
  7652. if (outlen != ecc_kse->keyLen) {
  7653. WOLFSSL_MSG("Data length mismatch.");
  7654. ret = BAD_FUNC_ARG;
  7655. }
  7656. }
  7657. }
  7658. if (ret == 0) {
  7659. ret = wc_KyberKey_DecodePublicKey(kem, data + ecc_kse->pubKeyLen,
  7660. pubSz);
  7661. }
  7662. if (ret == 0) {
  7663. ret = wc_KyberKey_Encapsulate(kem, ciphertext + ecc_kse->pubKeyLen,
  7664. sharedSecret + outlen, ssl->rng);
  7665. if (ret != 0) {
  7666. WOLFSSL_MSG("wc_KyberKey encapsulation failure.");
  7667. }
  7668. }
  7669. if (ret == 0) {
  7670. if (keyShareEntry->ke != NULL) {
  7671. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7672. }
  7673. keyShareEntry->ke = sharedSecret;
  7674. keyShareEntry->keLen = outlen + ssSz;
  7675. sharedSecret = NULL;
  7676. if (ecc_kse->pubKeyLen > 0)
  7677. XMEMCPY(ciphertext, ecc_kse->pubKey, ecc_kse->pubKeyLen);
  7678. keyShareEntry->pubKey = ciphertext;
  7679. keyShareEntry->pubKeyLen = (word32)(ecc_kse->pubKeyLen + ctSz);
  7680. ciphertext = NULL;
  7681. /* Set namedGroup so wolfSSL_get_curve_name() can function properly on
  7682. * the server side. */
  7683. ssl->namedGroup = keyShareEntry->group;
  7684. }
  7685. TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap);
  7686. if (sharedSecret != NULL)
  7687. XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  7688. if (ciphertext != NULL)
  7689. XFREE(ciphertext, ssl->heap, DYNAMIC_TYPE_TLSX);
  7690. wc_ecc_free(&eccpubkey);
  7691. wc_KyberKey_Free(kem);
  7692. return ret;
  7693. }
  7694. #endif /* HAVE_PQC */
  7695. /* Use the data to create a new key share object in the extensions.
  7696. *
  7697. * ssl The SSL/TLS object.
  7698. * group The named group.
  7699. * len The length of the public key data.
  7700. * data The public key data.
  7701. * kse The new key share entry object.
  7702. * returns 0 on success and other values indicate failure.
  7703. */
  7704. int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group, word16 len, byte* data,
  7705. KeyShareEntry **kse, TLSX** extensions)
  7706. {
  7707. int ret = 0;
  7708. TLSX* extension;
  7709. KeyShareEntry* keyShareEntry = NULL;
  7710. /* Find the KeyShare extension if it exists. */
  7711. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7712. if (extension == NULL) {
  7713. /* Push new KeyShare extension. */
  7714. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7715. if (ret != 0)
  7716. return ret;
  7717. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7718. if (extension == NULL)
  7719. return MEMORY_E;
  7720. }
  7721. extension->resp = 0;
  7722. /* Try to find the key share entry with this group. */
  7723. keyShareEntry = (KeyShareEntry*)extension->data;
  7724. while (keyShareEntry != NULL) {
  7725. if (keyShareEntry->group == group)
  7726. break;
  7727. keyShareEntry = keyShareEntry->next;
  7728. }
  7729. /* Create a new key share entry if not found. */
  7730. if (keyShareEntry == NULL) {
  7731. ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, group,
  7732. ssl->heap, &keyShareEntry);
  7733. if (ret != 0)
  7734. return ret;
  7735. }
  7736. #ifdef HAVE_PQC
  7737. if (WOLFSSL_NAMED_GROUP_IS_PQC(group) &&
  7738. ssl->options.side == WOLFSSL_SERVER_END) {
  7739. ret = server_generate_pqc_ciphertext((WOLFSSL*)ssl, keyShareEntry, data,
  7740. len);
  7741. if (ret != 0)
  7742. return ret;
  7743. }
  7744. else
  7745. #endif
  7746. if (data != NULL) {
  7747. if (keyShareEntry->ke != NULL) {
  7748. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7749. }
  7750. keyShareEntry->ke = data;
  7751. keyShareEntry->keLen = len;
  7752. }
  7753. else {
  7754. /* Generate a key pair. Casting to non-const since changes inside are
  7755. * minimal but would require an extensive redesign to refactor. Also
  7756. * this path shouldn't be taken when parsing a ClientHello in stateless
  7757. * mode. */
  7758. ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, keyShareEntry);
  7759. if (ret != 0)
  7760. return ret;
  7761. }
  7762. if (kse != NULL)
  7763. *kse = keyShareEntry;
  7764. return 0;
  7765. }
  7766. /* Set an empty Key Share extension.
  7767. *
  7768. * ssl The SSL/TLS object.
  7769. * returns 0 on success and other values indicate failure.
  7770. */
  7771. int TLSX_KeyShare_Empty(WOLFSSL* ssl)
  7772. {
  7773. int ret = 0;
  7774. TLSX* extension;
  7775. /* Find the KeyShare extension if it exists. */
  7776. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  7777. if (extension == NULL) {
  7778. /* Push new KeyShare extension. */
  7779. ret = TLSX_Push(&ssl->extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7780. }
  7781. else if (extension->data != NULL) {
  7782. TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap);
  7783. extension->data = NULL;
  7784. }
  7785. return ret;
  7786. }
  7787. /* Returns whether this group is supported.
  7788. *
  7789. * namedGroup The named group to check.
  7790. * returns 1 when supported or 0 otherwise.
  7791. */
  7792. static int TLSX_KeyShare_IsSupported(int namedGroup)
  7793. {
  7794. switch (namedGroup) {
  7795. #ifdef HAVE_FFDHE_2048
  7796. case WOLFSSL_FFDHE_2048:
  7797. break;
  7798. #endif
  7799. #ifdef HAVE_FFDHE_3072
  7800. case WOLFSSL_FFDHE_3072:
  7801. break;
  7802. #endif
  7803. #ifdef HAVE_FFDHE_4096
  7804. case WOLFSSL_FFDHE_4096:
  7805. break;
  7806. #endif
  7807. #ifdef HAVE_FFDHE_6144
  7808. case WOLFSSL_FFDHE_6144:
  7809. break;
  7810. #endif
  7811. #ifdef HAVE_FFDHE_8192
  7812. case WOLFSSL_FFDHE_8192:
  7813. break;
  7814. #endif
  7815. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  7816. #ifdef HAVE_ECC_KOBLITZ
  7817. case WOLFSSL_ECC_SECP256K1:
  7818. break;
  7819. #endif
  7820. #ifndef NO_ECC_SECP
  7821. case WOLFSSL_ECC_SECP256R1:
  7822. break;
  7823. #endif /* !NO_ECC_SECP */
  7824. #ifdef HAVE_ECC_BRAINPOOL
  7825. case WOLFSSL_ECC_BRAINPOOLP256R1:
  7826. break;
  7827. #endif
  7828. #ifdef WOLFSSL_SM2
  7829. case WOLFSSL_ECC_SM2P256V1:
  7830. break;
  7831. #endif /* WOLFSSL_SM2 */
  7832. #endif
  7833. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  7834. case WOLFSSL_ECC_X25519:
  7835. break;
  7836. #endif
  7837. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  7838. case WOLFSSL_ECC_X448:
  7839. break;
  7840. #endif
  7841. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  7842. #ifndef NO_ECC_SECP
  7843. case WOLFSSL_ECC_SECP384R1:
  7844. break;
  7845. #endif /* !NO_ECC_SECP */
  7846. #ifdef HAVE_ECC_BRAINPOOL
  7847. case WOLFSSL_ECC_BRAINPOOLP384R1:
  7848. break;
  7849. #endif
  7850. #endif
  7851. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  7852. #ifndef NO_ECC_SECP
  7853. case WOLFSSL_ECC_SECP521R1:
  7854. break;
  7855. #endif /* !NO_ECC_SECP */
  7856. #endif
  7857. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  7858. #ifdef HAVE_ECC_KOBLITZ
  7859. case WOLFSSL_ECC_SECP160K1:
  7860. break;
  7861. #endif
  7862. #ifndef NO_ECC_SECP
  7863. case WOLFSSL_ECC_SECP160R1:
  7864. break;
  7865. #endif
  7866. #ifdef HAVE_ECC_SECPR2
  7867. case WOLFSSL_ECC_SECP160R2:
  7868. break;
  7869. #endif
  7870. #endif
  7871. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  7872. #ifdef HAVE_ECC_KOBLITZ
  7873. case WOLFSSL_ECC_SECP192K1:
  7874. break;
  7875. #endif
  7876. #ifndef NO_ECC_SECP
  7877. case WOLFSSL_ECC_SECP192R1:
  7878. break;
  7879. #endif
  7880. #endif
  7881. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  7882. #ifdef HAVE_ECC_KOBLITZ
  7883. case WOLFSSL_ECC_SECP224K1:
  7884. break;
  7885. #endif
  7886. #ifndef NO_ECC_SECP
  7887. case WOLFSSL_ECC_SECP224R1:
  7888. break;
  7889. #endif
  7890. #endif
  7891. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  7892. #ifdef HAVE_ECC_BRAINPOOL
  7893. case WOLFSSL_ECC_BRAINPOOLP512R1:
  7894. break;
  7895. #endif
  7896. #endif
  7897. #ifdef HAVE_PQC
  7898. #ifdef WOLFSSL_WC_KYBER
  7899. #ifdef WOLFSSL_KYBER512
  7900. case WOLFSSL_KYBER_LEVEL1:
  7901. #endif
  7902. #ifdef WOLFSSL_KYBER768
  7903. case WOLFSSL_KYBER_LEVEL3:
  7904. #endif
  7905. #ifdef WOLFSSL_KYBER1024
  7906. case WOLFSSL_KYBER_LEVEL5:
  7907. #endif
  7908. break;
  7909. #elif defined(HAVE_LIBOQS)
  7910. case WOLFSSL_KYBER_LEVEL1:
  7911. case WOLFSSL_KYBER_LEVEL3:
  7912. case WOLFSSL_KYBER_LEVEL5:
  7913. case WOLFSSL_P256_KYBER_LEVEL1:
  7914. case WOLFSSL_P384_KYBER_LEVEL3:
  7915. case WOLFSSL_P521_KYBER_LEVEL5:
  7916. {
  7917. int ret;
  7918. int id;
  7919. findEccPqc(NULL, &namedGroup, namedGroup);
  7920. ret = kyber_id2type(namedGroup, &id);
  7921. if (ret == NOT_COMPILED_IN) {
  7922. return 0;
  7923. }
  7924. if (! ext_kyber_enabled(id)) {
  7925. return 0;
  7926. }
  7927. break;
  7928. }
  7929. #elif defined(HAVE_PQM4)
  7930. case WOLFSSL_KYBER_LEVEL1:
  7931. break;
  7932. #endif
  7933. #endif /* HAVE_PQC */
  7934. default:
  7935. return 0;
  7936. }
  7937. return 1;
  7938. }
  7939. static const word16 preferredGroup[] = {
  7940. #if defined(HAVE_ECC) && (!defined(NO_ECC256) || \
  7941. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 256
  7942. WOLFSSL_ECC_SECP256R1,
  7943. #if !defined(HAVE_FIPS) && defined(WOLFSSL_SM2)
  7944. WOLFSSL_ECC_SM2P256V1,
  7945. #endif
  7946. #endif
  7947. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  7948. WOLFSSL_ECC_X25519,
  7949. #endif
  7950. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  7951. WOLFSSL_ECC_X448,
  7952. #endif
  7953. #if defined(HAVE_ECC) && (!defined(NO_ECC384) || \
  7954. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 384
  7955. WOLFSSL_ECC_SECP384R1,
  7956. #endif
  7957. #if defined(HAVE_ECC) && (!defined(NO_ECC521) || \
  7958. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 521
  7959. WOLFSSL_ECC_SECP521R1,
  7960. #endif
  7961. #if defined(HAVE_FFDHE_2048)
  7962. WOLFSSL_FFDHE_2048,
  7963. #endif
  7964. #if defined(HAVE_FFDHE_3072)
  7965. WOLFSSL_FFDHE_3072,
  7966. #endif
  7967. #if defined(HAVE_FFDHE_4096)
  7968. WOLFSSL_FFDHE_4096,
  7969. #endif
  7970. #if defined(HAVE_FFDHE_6144)
  7971. WOLFSSL_FFDHE_6144,
  7972. #endif
  7973. #if defined(HAVE_FFDHE_8192)
  7974. WOLFSSL_FFDHE_8192,
  7975. #endif
  7976. #ifdef WOLFSSL_WC_KYBER
  7977. #ifdef WOLFSSL_KYBER512
  7978. WOLFSSL_KYBER_LEVEL1,
  7979. #endif
  7980. #ifdef WOLFSSL_KYBER768
  7981. WOLFSSL_KYBER_LEVEL3,
  7982. #endif
  7983. #ifdef WOLFSSL_KYBER1024
  7984. WOLFSSL_KYBER_LEVEL5,
  7985. #endif
  7986. #elif defined(HAVE_LIBOQS)
  7987. /* These require a runtime call to TLSX_KeyShare_IsSupported to use */
  7988. WOLFSSL_KYBER_LEVEL1,
  7989. WOLFSSL_KYBER_LEVEL3,
  7990. WOLFSSL_KYBER_LEVEL5,
  7991. WOLFSSL_P256_KYBER_LEVEL1,
  7992. WOLFSSL_P384_KYBER_LEVEL3,
  7993. WOLFSSL_P521_KYBER_LEVEL5,
  7994. #elif defined(HAVE_PQM4)
  7995. WOLFSSL_KYBER_LEVEL1,
  7996. #endif
  7997. WOLFSSL_NAMED_GROUP_INVALID
  7998. };
  7999. #define PREFERRED_GROUP_SZ \
  8000. ((sizeof(preferredGroup)/sizeof(*preferredGroup)) - 1)
  8001. /* -1 for the invalid group */
  8002. /* Examines the application specified group ranking and returns the rank of the
  8003. * group.
  8004. * If no group ranking set then all groups are rank 0 (highest).
  8005. *
  8006. * ssl The SSL/TLS object.
  8007. * group The group to check ranking for.
  8008. * returns ranking from 0 to MAX_GROUP_COUNT-1 or -1 when group not in list.
  8009. */
  8010. static int TLSX_KeyShare_GroupRank(const WOLFSSL* ssl, int group)
  8011. {
  8012. byte i;
  8013. const word16* groups;
  8014. byte numGroups;
  8015. if (ssl->numGroups == 0) {
  8016. groups = preferredGroup;
  8017. numGroups = PREFERRED_GROUP_SZ;
  8018. }
  8019. else {
  8020. groups = ssl->group;
  8021. numGroups = ssl->numGroups;
  8022. }
  8023. #ifdef HAVE_LIBOQS
  8024. if (!TLSX_KeyShare_IsSupported(group))
  8025. return -1;
  8026. #endif
  8027. for (i = 0; i < numGroups; i++)
  8028. if (groups[i] == (word16)group)
  8029. return i;
  8030. return -1;
  8031. }
  8032. /* Set a key share that is supported by the client into extensions.
  8033. *
  8034. * ssl The SSL/TLS object.
  8035. * returns BAD_KEY_SHARE_DATA if no supported group has a key share,
  8036. * 0 if a supported group has a key share and other values indicate an error.
  8037. */
  8038. int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl, TLSX** extensions)
  8039. {
  8040. int ret;
  8041. #ifdef HAVE_SUPPORTED_CURVES
  8042. TLSX* extension;
  8043. SupportedCurve* curve = NULL;
  8044. SupportedCurve* preferredCurve = NULL;
  8045. KeyShareEntry* kse = NULL;
  8046. int preferredRank = WOLFSSL_MAX_GROUP_COUNT;
  8047. int rank;
  8048. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  8049. if (extension != NULL)
  8050. curve = (SupportedCurve*)extension->data;
  8051. /* Use server's preference order. */
  8052. for (; curve != NULL; curve = curve->next) {
  8053. if (!TLSX_KeyShare_IsSupported(curve->name))
  8054. continue;
  8055. if (wolfSSL_curve_is_disabled(ssl, curve->name))
  8056. continue;
  8057. rank = TLSX_KeyShare_GroupRank(ssl, curve->name);
  8058. if (rank == -1)
  8059. continue;
  8060. if (rank < preferredRank) {
  8061. preferredCurve = curve;
  8062. preferredRank = rank;
  8063. }
  8064. }
  8065. curve = preferredCurve;
  8066. if (curve == NULL) {
  8067. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  8068. return BAD_KEY_SHARE_DATA;
  8069. }
  8070. #ifdef WOLFSSL_ASYNC_CRYPT
  8071. /* Check the old key share data list. */
  8072. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  8073. if (extension != NULL) {
  8074. kse = (KeyShareEntry*)extension->data;
  8075. /* We should not be computing keys if we are only going to advertise
  8076. * our choice here. */
  8077. if (kse != NULL && kse->lastRet == WC_PENDING_E) {
  8078. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  8079. return BAD_KEY_SHARE_DATA;
  8080. }
  8081. }
  8082. #endif
  8083. /* Push new KeyShare extension. This will also free the old one */
  8084. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  8085. if (ret != 0)
  8086. return ret;
  8087. /* Extension got pushed to head */
  8088. extension = *extensions;
  8089. /* Push the selected curve */
  8090. ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, curve->name,
  8091. ssl->heap, &kse);
  8092. if (ret != 0)
  8093. return ret;
  8094. /* Set extension to be in response. */
  8095. extension->resp = 1;
  8096. #else
  8097. (void)ssl;
  8098. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  8099. ret = NOT_COMPILED_IN;
  8100. #endif
  8101. return ret;
  8102. }
  8103. #ifdef WOLFSSL_DUAL_ALG_CERTS
  8104. /* Writes the CKS objects of a list in a buffer. */
  8105. static word16 CKS_WRITE(WOLFSSL* ssl, byte* output)
  8106. {
  8107. XMEMCPY(output, ssl->sigSpec, ssl->sigSpecSz);
  8108. return ssl->sigSpecSz;
  8109. }
  8110. static int TLSX_UseCKS(TLSX** extensions, WOLFSSL* ssl, void* heap)
  8111. {
  8112. int ret = 0;
  8113. TLSX* extension;
  8114. if (extensions == NULL) {
  8115. return BAD_FUNC_ARG;
  8116. }
  8117. extension = TLSX_Find(*extensions, TLSX_CKS);
  8118. /* If it is already present, do nothing. */
  8119. if (extension == NULL) {
  8120. /* The data required is in the ssl struct, so push it in. */
  8121. ret = TLSX_Push(extensions, TLSX_CKS, (void*)ssl, heap);
  8122. }
  8123. return ret;
  8124. }
  8125. int TLSX_CKS_Set(WOLFSSL* ssl, TLSX** extensions)
  8126. {
  8127. int ret;
  8128. TLSX* extension;
  8129. /* Push new KeyShare extension. This will also free the old one */
  8130. ret = TLSX_Push(extensions, TLSX_CKS, NULL, ssl->heap);
  8131. if (ret != 0)
  8132. return ret;
  8133. /* Extension got pushed to head */
  8134. extension = *extensions;
  8135. /* Need ssl->sigSpecSz during extension length calculation. */
  8136. extension->data = ssl;
  8137. /* Set extension to be in response. */
  8138. extension->resp = 1;
  8139. return ret;
  8140. }
  8141. int TLSX_CKS_Parse(WOLFSSL* ssl, byte* input, word16 length,
  8142. TLSX** extensions)
  8143. {
  8144. (void) extensions;
  8145. int ret;
  8146. int i, j;
  8147. /* Validating the input. */
  8148. if (length == 0)
  8149. return BUFFER_ERROR;
  8150. for (i = 0; i < length; i++) {
  8151. switch (input[i])
  8152. {
  8153. case WOLFSSL_CKS_SIGSPEC_NATIVE:
  8154. case WOLFSSL_CKS_SIGSPEC_ALTERNATIVE:
  8155. case WOLFSSL_CKS_SIGSPEC_BOTH:
  8156. /* These are all valid values; do nothing */
  8157. break;
  8158. case WOLFSSL_CKS_SIGSPEC_EXTERNAL:
  8159. default:
  8160. /* All other values (including external) are not. */
  8161. return BAD_FUNC_ARG;
  8162. }
  8163. }
  8164. /* Extension data is valid, but if we are the server and we don't have an
  8165. * alt private key, do not respond with CKS extension. */
  8166. if (wolfSSL_is_server(ssl) && ssl->buffers.altKey == NULL) {
  8167. ssl->sigSpec = NULL;
  8168. ssl->sigSpecSz = 0;
  8169. return 0;
  8170. }
  8171. /* Copy as the lifetime of input seems to be ephemeral. */
  8172. ssl->peerSigSpec = (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_TLSX);
  8173. if (ssl->peerSigSpec == NULL) {
  8174. return BUFFER_ERROR;
  8175. }
  8176. XMEMCPY(ssl->peerSigSpec, input, length);
  8177. ssl->peerSigSpecSz = length;
  8178. /* If there is no preference set, use theirs... */
  8179. if (ssl->sigSpec == NULL) {
  8180. ret = wolfSSL_UseCKS(ssl, ssl->peerSigSpec, 1);
  8181. if (ret == WOLFSSL_SUCCESS) {
  8182. ret = TLSX_UseCKS(&ssl->extensions, ssl, ssl->heap);
  8183. TLSX_SetResponse(ssl, TLSX_CKS);
  8184. }
  8185. return ret;
  8186. }
  8187. /* ...otherwise, prioritize our preference. */
  8188. for (i = 0; i < ssl->sigSpecSz; i++) {
  8189. for (j = 0; j < length; j++) {
  8190. if (ssl->sigSpec[i] == input[j]) {
  8191. /* Got the match, set to this one. */
  8192. ret = wolfSSL_UseCKS(ssl, &ssl->sigSpec[i], 1);
  8193. if (ret == WOLFSSL_SUCCESS) {
  8194. ret = TLSX_UseCKS(&ssl->extensions, ssl, ssl->heap);
  8195. TLSX_SetResponse(ssl, TLSX_CKS);
  8196. }
  8197. return ret;
  8198. }
  8199. }
  8200. }
  8201. /* No match found. Cannot continue. */
  8202. return MATCH_SUITE_ERROR;
  8203. }
  8204. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  8205. /* Server side KSE processing */
  8206. int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions,
  8207. byte cipherSuite0, byte cipherSuite, KeyShareEntry** kse, byte* searched)
  8208. {
  8209. TLSX* extension;
  8210. KeyShareEntry* clientKSE = NULL;
  8211. KeyShareEntry* list = NULL;
  8212. KeyShareEntry* preferredKSE = NULL;
  8213. int preferredRank = WOLFSSL_MAX_GROUP_COUNT;
  8214. int rank;
  8215. (void)cipherSuite0;
  8216. (void)cipherSuite;
  8217. if (ssl == NULL || ssl->options.side != WOLFSSL_SERVER_END)
  8218. return BAD_FUNC_ARG;
  8219. *searched = 0;
  8220. /* Find the KeyShare extension if it exists. */
  8221. extension = TLSX_Find(extensions, TLSX_KEY_SHARE);
  8222. if (extension != NULL)
  8223. list = (KeyShareEntry*)extension->data;
  8224. if (extension && extension->resp == 1) {
  8225. /* Outside of the async case this path should not be taken. */
  8226. int ret = INCOMPLETE_DATA;
  8227. #ifdef WOLFSSL_ASYNC_CRYPT
  8228. /* in async case make sure key generation is finalized */
  8229. KeyShareEntry* serverKSE = (KeyShareEntry*)extension->data;
  8230. if (serverKSE && serverKSE->lastRet == WC_PENDING_E) {
  8231. if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
  8232. *searched = 1;
  8233. ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE);
  8234. }
  8235. #endif
  8236. return ret;
  8237. }
  8238. /* Use server's preference order. */
  8239. for (clientKSE = list; clientKSE != NULL; clientKSE = clientKSE->next) {
  8240. if (clientKSE->ke == NULL)
  8241. continue;
  8242. #ifdef WOLFSSL_SM2
  8243. if ((cipherSuite0 == CIPHER_BYTE) &&
  8244. ((cipherSuite == TLS_SM4_GCM_SM3) ||
  8245. (cipherSuite == TLS_SM4_CCM_SM3))) {
  8246. if (clientKSE->group != WOLFSSL_ECC_SM2P256V1) {
  8247. continue;
  8248. }
  8249. }
  8250. else if (clientKSE->group == WOLFSSL_ECC_SM2P256V1) {
  8251. continue;
  8252. }
  8253. #endif
  8254. /* Check consistency now - extensions in any order. */
  8255. if (!TLSX_SupportedGroups_Find(ssl, clientKSE->group, extensions))
  8256. continue;
  8257. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(clientKSE->group)) {
  8258. /* Check max value supported. */
  8259. if (clientKSE->group > WOLFSSL_ECC_MAX) {
  8260. #ifdef HAVE_PQC
  8261. if (!WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group))
  8262. #endif
  8263. continue;
  8264. }
  8265. if (wolfSSL_curve_is_disabled(ssl, clientKSE->group))
  8266. continue;
  8267. }
  8268. if (!TLSX_KeyShare_IsSupported(clientKSE->group))
  8269. continue;
  8270. rank = TLSX_KeyShare_GroupRank(ssl, clientKSE->group);
  8271. if (rank == -1)
  8272. continue;
  8273. if (rank < preferredRank) {
  8274. preferredKSE = clientKSE;
  8275. preferredRank = rank;
  8276. }
  8277. }
  8278. *kse = preferredKSE;
  8279. *searched = 1;
  8280. return 0;
  8281. }
  8282. /* Server side KSE processing */
  8283. int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE)
  8284. {
  8285. int ret;
  8286. TLSX* extension;
  8287. KeyShareEntry* serverKSE;
  8288. KeyShareEntry* list = NULL;
  8289. if (ssl == NULL || ssl->options.side != WOLFSSL_SERVER_END)
  8290. return BAD_FUNC_ARG;
  8291. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  8292. if (extension == NULL)
  8293. return BAD_STATE_E;
  8294. if (clientKSE == NULL) {
  8295. #ifdef WOLFSSL_ASYNC_CRYPT
  8296. /* Not necessarily an error. The key may have already been setup. */
  8297. if (extension != NULL && extension->resp == 1) {
  8298. serverKSE = (KeyShareEntry*)extension->data;
  8299. if (serverKSE != NULL) {
  8300. /* in async case make sure key generation is finalized */
  8301. if (serverKSE->lastRet == WC_PENDING_E)
  8302. return TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE);
  8303. else if (serverKSE->lastRet == 0)
  8304. return 0;
  8305. }
  8306. }
  8307. #endif
  8308. return BAD_FUNC_ARG;
  8309. }
  8310. /* Generate a new key pair except in the case of OQS KEM because we
  8311. * are going to encapsulate and that does not require us to generate a
  8312. * key pair.
  8313. */
  8314. ret = TLSX_KeyShare_New(&list, clientKSE->group, ssl->heap, &serverKSE);
  8315. if (ret != 0)
  8316. return ret;
  8317. if (clientKSE->key == NULL) {
  8318. #ifdef HAVE_PQC
  8319. if (WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group)) {
  8320. /* Going to need the public key (AKA ciphertext). */
  8321. serverKSE->pubKey = clientKSE->pubKey;
  8322. clientKSE->pubKey = NULL;
  8323. serverKSE->pubKeyLen = clientKSE->pubKeyLen;
  8324. clientKSE->pubKeyLen = 0;
  8325. }
  8326. else
  8327. #endif
  8328. {
  8329. ret = TLSX_KeyShare_GenKey(ssl, serverKSE);
  8330. }
  8331. /* for async do setup of serverKSE below, but return WC_PENDING_E */
  8332. if (ret != 0
  8333. #ifdef WOLFSSL_ASYNC_CRYPT
  8334. && ret != WC_PENDING_E
  8335. #endif
  8336. ) {
  8337. TLSX_KeyShare_FreeAll(list, ssl->heap);
  8338. return ret;
  8339. }
  8340. }
  8341. else {
  8342. /* transfer buffers to serverKSE */
  8343. serverKSE->key = clientKSE->key;
  8344. clientKSE->key = NULL;
  8345. serverKSE->keyLen = clientKSE->keyLen;
  8346. serverKSE->pubKey = clientKSE->pubKey;
  8347. clientKSE->pubKey = NULL;
  8348. serverKSE->pubKeyLen = clientKSE->pubKeyLen;
  8349. #ifndef NO_DH
  8350. serverKSE->privKey = clientKSE->privKey;
  8351. clientKSE->privKey = NULL;
  8352. #endif
  8353. }
  8354. serverKSE->ke = clientKSE->ke;
  8355. serverKSE->keLen = clientKSE->keLen;
  8356. clientKSE->ke = NULL;
  8357. clientKSE->keLen = 0;
  8358. ssl->namedGroup = serverKSE->group;
  8359. TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap);
  8360. extension->data = (void *)serverKSE;
  8361. extension->resp = 1;
  8362. return ret;
  8363. }
  8364. /* Ensure there is a key pair that can be used for key exchange.
  8365. *
  8366. * ssl The SSL/TLS object.
  8367. * doHelloRetry If set to non-zero will do hello_retry
  8368. * returns 0 on success and other values indicate failure.
  8369. */
  8370. int TLSX_KeyShare_Establish(WOLFSSL *ssl, int* doHelloRetry)
  8371. {
  8372. int ret;
  8373. KeyShareEntry* clientKSE = NULL;
  8374. byte searched = 0;
  8375. *doHelloRetry = 0;
  8376. ret = TLSX_KeyShare_Choose(ssl, ssl->extensions, ssl->cipher.cipherSuite0,
  8377. ssl->cipher.cipherSuite, &clientKSE, &searched);
  8378. if (ret != 0 || !searched)
  8379. return ret;
  8380. /* No supported group found - send HelloRetryRequest. */
  8381. if (clientKSE == NULL) {
  8382. /* Set KEY_SHARE_ERROR to indicate HelloRetryRequest required. */
  8383. *doHelloRetry = 1;
  8384. return TLSX_KeyShare_SetSupported(ssl, &ssl->extensions);
  8385. }
  8386. return TLSX_KeyShare_Setup(ssl, clientKSE);
  8387. }
  8388. /* Derive the shared secret of the key exchange.
  8389. *
  8390. * ssl The SSL/TLS object.
  8391. * returns 0 on success and other values indicate failure.
  8392. */
  8393. int TLSX_KeyShare_DeriveSecret(WOLFSSL *ssl)
  8394. {
  8395. int ret;
  8396. TLSX* extension;
  8397. KeyShareEntry* list = NULL;
  8398. #ifdef WOLFSSL_ASYNC_CRYPT
  8399. ret = wolfSSL_AsyncPop(ssl, NULL);
  8400. /* Check for error */
  8401. if (ret != WC_NO_PENDING_E && ret < 0) {
  8402. return ret;
  8403. }
  8404. #endif
  8405. /* Find the KeyShare extension if it exists. */
  8406. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  8407. if (extension != NULL)
  8408. list = (KeyShareEntry*)extension->data;
  8409. if (list == NULL)
  8410. return KEY_SHARE_ERROR;
  8411. /* Calculate secret. */
  8412. ret = TLSX_KeyShare_Process(ssl, list);
  8413. return ret;
  8414. }
  8415. #define KS_FREE_ALL TLSX_KeyShare_FreeAll
  8416. #define KS_GET_SIZE TLSX_KeyShare_GetSize
  8417. #define KS_WRITE TLSX_KeyShare_Write
  8418. #define KS_PARSE TLSX_KeyShare_Parse
  8419. #else
  8420. #define KS_FREE_ALL(a, b) WC_DO_NOTHING
  8421. #define KS_GET_SIZE(a, b) 0
  8422. #define KS_WRITE(a, b, c) 0
  8423. #define KS_PARSE(a, b, c, d) 0
  8424. #endif /* WOLFSSL_TLS13 */
  8425. /******************************************************************************/
  8426. /* Pre-Shared Key */
  8427. /******************************************************************************/
  8428. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  8429. /* Free the pre-shared key dynamic data.
  8430. *
  8431. * list The linked list of key share entry objects.
  8432. * heap The heap used for allocation.
  8433. */
  8434. static void TLSX_PreSharedKey_FreeAll(PreSharedKey* list, void* heap)
  8435. {
  8436. PreSharedKey* current;
  8437. while ((current = list) != NULL) {
  8438. list = current->next;
  8439. XFREE(current->identity, heap, DYNAMIC_TYPE_TLSX);
  8440. XFREE(current, heap, DYNAMIC_TYPE_TLSX);
  8441. }
  8442. (void)heap;
  8443. }
  8444. /* Get the size of the encoded pre shared key extension.
  8445. *
  8446. * list The linked list of pre-shared key extensions.
  8447. * msgType The type of the message this extension is being written into.
  8448. * returns the number of bytes of the encoded pre-shared key extension or
  8449. * SANITY_MSG_E to indicate invalid message type.
  8450. */
  8451. static int TLSX_PreSharedKey_GetSize(PreSharedKey* list, byte msgType,
  8452. word16* pSz)
  8453. {
  8454. if (msgType == client_hello) {
  8455. /* Length of identities + Length of binders. */
  8456. word16 len = OPAQUE16_LEN + OPAQUE16_LEN;
  8457. while (list != NULL) {
  8458. /* Each entry has: identity, ticket age and binder. */
  8459. len += OPAQUE16_LEN + list->identityLen + OPAQUE32_LEN +
  8460. OPAQUE8_LEN + (word16)list->binderLen;
  8461. list = list->next;
  8462. }
  8463. *pSz += len;
  8464. return 0;
  8465. }
  8466. if (msgType == server_hello) {
  8467. *pSz += OPAQUE16_LEN;
  8468. return 0;
  8469. }
  8470. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8471. return SANITY_MSG_E;
  8472. }
  8473. /* The number of bytes to be written for the binders.
  8474. *
  8475. * list The linked list of pre-shared key extensions.
  8476. * msgType The type of the message this extension is being written into.
  8477. * returns the number of bytes of the encoded pre-shared key extension or
  8478. * SANITY_MSG_E to indicate invalid message type.
  8479. */
  8480. int TLSX_PreSharedKey_GetSizeBinders(PreSharedKey* list, byte msgType,
  8481. word16* pSz)
  8482. {
  8483. word16 len;
  8484. if (msgType != client_hello) {
  8485. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8486. return SANITY_MSG_E;
  8487. }
  8488. /* Length of all binders. */
  8489. len = OPAQUE16_LEN;
  8490. while (list != NULL) {
  8491. len += OPAQUE8_LEN + (word16)list->binderLen;
  8492. list = list->next;
  8493. }
  8494. *pSz = len;
  8495. return 0;
  8496. }
  8497. /* Writes the pre-shared key extension into the output buffer - binders only.
  8498. * Assumes that the the output buffer is big enough to hold data.
  8499. *
  8500. * list The linked list of key share entries.
  8501. * output The buffer to write into.
  8502. * msgType The type of the message this extension is being written into.
  8503. * returns the number of bytes written into the buffer.
  8504. */
  8505. int TLSX_PreSharedKey_WriteBinders(PreSharedKey* list, byte* output,
  8506. byte msgType, word16* pSz)
  8507. {
  8508. PreSharedKey* current = list;
  8509. word16 idx = 0;
  8510. word16 lenIdx;
  8511. word16 len;
  8512. if (msgType != client_hello) {
  8513. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8514. return SANITY_MSG_E;
  8515. }
  8516. /* Skip length of all binders. */
  8517. lenIdx = idx;
  8518. idx += OPAQUE16_LEN;
  8519. while (current != NULL) {
  8520. /* Binder data length. */
  8521. output[idx++] = (byte)current->binderLen;
  8522. /* Binder data. */
  8523. XMEMCPY(output + idx, current->binder, current->binderLen);
  8524. idx += (word16)current->binderLen;
  8525. current = current->next;
  8526. }
  8527. /* Length of the binders. */
  8528. len = idx - lenIdx - OPAQUE16_LEN;
  8529. c16toa(len, output + lenIdx);
  8530. *pSz = idx;
  8531. return 0;
  8532. }
  8533. /* Writes the pre-shared key extension into the output buffer.
  8534. * Assumes that the the output buffer is big enough to hold data.
  8535. *
  8536. * list The linked list of key share entries.
  8537. * output The buffer to write into.
  8538. * msgType The type of the message this extension is being written into.
  8539. * returns the number of bytes written into the buffer.
  8540. */
  8541. static int TLSX_PreSharedKey_Write(PreSharedKey* list, byte* output,
  8542. byte msgType, word16* pSz)
  8543. {
  8544. if (msgType == client_hello) {
  8545. PreSharedKey* current = list;
  8546. word16 idx = 0;
  8547. word16 lenIdx;
  8548. word16 len;
  8549. int ret;
  8550. /* Write identities only. Binders after HMACing over this. */
  8551. lenIdx = idx;
  8552. idx += OPAQUE16_LEN;
  8553. while (current != NULL) {
  8554. /* Identity length */
  8555. c16toa(current->identityLen, output + idx);
  8556. idx += OPAQUE16_LEN;
  8557. /* Identity data */
  8558. XMEMCPY(output + idx, current->identity, current->identityLen);
  8559. idx += current->identityLen;
  8560. /* Obfuscated ticket age. */
  8561. c32toa(current->ticketAge, output + idx);
  8562. idx += OPAQUE32_LEN;
  8563. current = current->next;
  8564. }
  8565. /* Length of the identities. */
  8566. len = idx - lenIdx - OPAQUE16_LEN;
  8567. c16toa(len, output + lenIdx);
  8568. /* Don't include binders here.
  8569. * The binders are based on the hash of all the ClientHello data up to
  8570. * and include the identities written above.
  8571. */
  8572. ret = TLSX_PreSharedKey_GetSizeBinders(list, msgType, &len);
  8573. if (ret < 0)
  8574. return ret;
  8575. *pSz += idx + len;
  8576. }
  8577. else if (msgType == server_hello) {
  8578. word16 i;
  8579. /* Find the index of the chosen identity. */
  8580. for (i=0; list != NULL && !list->chosen; i++)
  8581. list = list->next;
  8582. if (list == NULL) {
  8583. WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR);
  8584. return BUILD_MSG_ERROR;
  8585. }
  8586. /* The index of the identity chosen by the server from the list supplied
  8587. * by the client.
  8588. */
  8589. c16toa(i, output);
  8590. *pSz += OPAQUE16_LEN;
  8591. }
  8592. else {
  8593. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8594. return SANITY_MSG_E;
  8595. }
  8596. return 0;
  8597. }
  8598. int TLSX_PreSharedKey_Parse_ClientHello(TLSX** extensions, const byte* input,
  8599. word16 length, void* heap)
  8600. {
  8601. int ret;
  8602. word16 len;
  8603. word16 idx = 0;
  8604. TLSX* extension;
  8605. PreSharedKey* list;
  8606. TLSX_Remove(extensions, TLSX_PRE_SHARED_KEY, heap);
  8607. /* Length of identities and of binders. */
  8608. if ((int)(length - idx) < OPAQUE16_LEN + OPAQUE16_LEN)
  8609. return BUFFER_E;
  8610. /* Length of identities. */
  8611. ato16(input + idx, &len);
  8612. idx += OPAQUE16_LEN;
  8613. if (len < MIN_PSK_ID_LEN || length - idx < len)
  8614. return BUFFER_E;
  8615. /* Create a pre-shared key object for each identity. */
  8616. while (len > 0) {
  8617. const byte* identity;
  8618. word16 identityLen;
  8619. word32 age;
  8620. if (len < OPAQUE16_LEN)
  8621. return BUFFER_E;
  8622. /* Length of identity. */
  8623. ato16(input + idx, &identityLen);
  8624. idx += OPAQUE16_LEN;
  8625. if (len < OPAQUE16_LEN + identityLen + OPAQUE32_LEN ||
  8626. identityLen > MAX_PSK_ID_LEN)
  8627. return BUFFER_E;
  8628. /* Cache identity pointer. */
  8629. identity = input + idx;
  8630. idx += identityLen;
  8631. /* Ticket age. */
  8632. ato32(input + idx, &age);
  8633. idx += OPAQUE32_LEN;
  8634. ret = TLSX_PreSharedKey_Use(extensions, identity, identityLen, age, no_mac,
  8635. 0, 0, 1, NULL, heap);
  8636. if (ret != 0)
  8637. return ret;
  8638. /* Done with this identity. */
  8639. len -= OPAQUE16_LEN + identityLen + OPAQUE32_LEN;
  8640. }
  8641. /* Find the list of identities sent to server. */
  8642. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8643. if (extension == NULL)
  8644. return PSK_KEY_ERROR;
  8645. list = (PreSharedKey*)extension->data;
  8646. /* Length of binders. */
  8647. if (idx + OPAQUE16_LEN > length)
  8648. return BUFFER_E;
  8649. ato16(input + idx, &len);
  8650. idx += OPAQUE16_LEN;
  8651. if (len < MIN_PSK_BINDERS_LEN || length - idx < len)
  8652. return BUFFER_E;
  8653. /* Set binder for each identity. */
  8654. while (list != NULL && len > 0) {
  8655. /* Length of binder */
  8656. list->binderLen = input[idx++];
  8657. if (list->binderLen < WC_SHA256_DIGEST_SIZE ||
  8658. list->binderLen > WC_MAX_DIGEST_SIZE)
  8659. return BUFFER_E;
  8660. if (len < OPAQUE8_LEN + list->binderLen)
  8661. return BUFFER_E;
  8662. /* Copy binder into static buffer. */
  8663. XMEMCPY(list->binder, input + idx, list->binderLen);
  8664. idx += (word16)list->binderLen;
  8665. /* Done with binder entry. */
  8666. len -= OPAQUE8_LEN + (word16)list->binderLen;
  8667. /* Next identity. */
  8668. list = list->next;
  8669. }
  8670. if (list != NULL || len != 0)
  8671. return BUFFER_E;
  8672. return 0;
  8673. }
  8674. /* Parse the pre-shared key extension.
  8675. * Different formats in different messages.
  8676. *
  8677. * ssl The SSL/TLS object.
  8678. * input The extension data.
  8679. * length The length of the extension data.
  8680. * msgType The type of the message this extension is being parsed from.
  8681. * returns 0 on success and other values indicate failure.
  8682. */
  8683. static int TLSX_PreSharedKey_Parse(WOLFSSL* ssl, const byte* input,
  8684. word16 length, byte msgType)
  8685. {
  8686. if (msgType == client_hello) {
  8687. return TLSX_PreSharedKey_Parse_ClientHello(&ssl->extensions, input,
  8688. length, ssl->heap);
  8689. }
  8690. if (msgType == server_hello) {
  8691. word16 idx;
  8692. PreSharedKey* list;
  8693. TLSX* extension;
  8694. /* Index of identity chosen by server. */
  8695. if (length != OPAQUE16_LEN)
  8696. return BUFFER_E;
  8697. ato16(input, &idx);
  8698. #ifdef WOLFSSL_EARLY_DATA
  8699. ssl->options.pskIdIndex = idx + 1;
  8700. #endif
  8701. /* Find the list of identities sent to server. */
  8702. extension = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  8703. if (extension == NULL)
  8704. return PSK_KEY_ERROR;
  8705. list = (PreSharedKey*)extension->data;
  8706. /* Mark the identity as chosen. */
  8707. for (; list != NULL && idx > 0; idx--)
  8708. list = list->next;
  8709. if (list == NULL) {
  8710. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8711. return PSK_KEY_ERROR;
  8712. }
  8713. list->chosen = 1;
  8714. #ifdef HAVE_SESSION_TICKET
  8715. if (list->resumption) {
  8716. /* Check that the session's details are the same as the server's. */
  8717. if (ssl->options.cipherSuite0 != ssl->session->cipherSuite0 ||
  8718. ssl->options.cipherSuite != ssl->session->cipherSuite ||
  8719. ssl->session->version.major != ssl->ctx->method->version.major ||
  8720. ssl->session->version.minor != ssl->ctx->method->version.minor) {
  8721. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8722. return PSK_KEY_ERROR;
  8723. }
  8724. }
  8725. #endif
  8726. return 0;
  8727. }
  8728. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8729. return SANITY_MSG_E;
  8730. }
  8731. /* Create a new pre-shared key and put it into the list.
  8732. *
  8733. * list The linked list of pre-shared key.
  8734. * identity The identity.
  8735. * len The length of the identity data.
  8736. * heap The memory to allocate with.
  8737. * preSharedKey The new pre-shared key object.
  8738. * returns 0 on success and other values indicate failure.
  8739. */
  8740. static int TLSX_PreSharedKey_New(PreSharedKey** list, const byte* identity,
  8741. word16 len, void *heap,
  8742. PreSharedKey** preSharedKey)
  8743. {
  8744. PreSharedKey* psk;
  8745. PreSharedKey** next;
  8746. psk = (PreSharedKey*)XMALLOC(sizeof(PreSharedKey), heap, DYNAMIC_TYPE_TLSX);
  8747. if (psk == NULL)
  8748. return MEMORY_E;
  8749. XMEMSET(psk, 0, sizeof(*psk));
  8750. /* Make a copy of the identity data. */
  8751. psk->identity = (byte*)XMALLOC(len + NULL_TERM_LEN, heap,
  8752. DYNAMIC_TYPE_TLSX);
  8753. if (psk->identity == NULL) {
  8754. XFREE(psk, heap, DYNAMIC_TYPE_TLSX);
  8755. return MEMORY_E;
  8756. }
  8757. XMEMCPY(psk->identity, identity, len);
  8758. psk->identityLen = len;
  8759. /* Use a NULL terminator in case it is a C string */
  8760. psk->identity[psk->identityLen] = '\0';
  8761. /* Add it to the end and maintain the links. */
  8762. while (*list != NULL) {
  8763. /* Assign to temporary to work around compiler bug found by customer. */
  8764. next = &((*list)->next);
  8765. list = next;
  8766. }
  8767. *list = psk;
  8768. *preSharedKey = psk;
  8769. (void)heap;
  8770. return 0;
  8771. }
  8772. static WC_INLINE byte GetHmacLength(int hmac)
  8773. {
  8774. switch (hmac) {
  8775. #ifndef NO_SHA256
  8776. case sha256_mac:
  8777. return WC_SHA256_DIGEST_SIZE;
  8778. #endif
  8779. #ifdef WOLFSSL_SHA384
  8780. case sha384_mac:
  8781. return WC_SHA384_DIGEST_SIZE;
  8782. #endif
  8783. #ifdef WOLFSSL_SHA512
  8784. case sha512_mac:
  8785. return WC_SHA512_DIGEST_SIZE;
  8786. #endif
  8787. #ifdef WOLFSSL_SM3
  8788. case sm3_mac:
  8789. return WC_SM3_DIGEST_SIZE;
  8790. #endif
  8791. default:
  8792. break;
  8793. }
  8794. return 0;
  8795. }
  8796. /* Use the data to create a new pre-shared key object in the extensions.
  8797. *
  8798. * ssl The SSL/TLS object.
  8799. * identity The identity.
  8800. * len The length of the identity data.
  8801. * age The age of the identity.
  8802. * hmac The HMAC algorithm.
  8803. * cipherSuite0 The first byte of the cipher suite to use.
  8804. * cipherSuite The second byte of the cipher suite to use.
  8805. * resumption The PSK is for resumption of a session.
  8806. * preSharedKey The new pre-shared key object.
  8807. * returns 0 on success and other values indicate failure.
  8808. */
  8809. int TLSX_PreSharedKey_Use(TLSX** extensions, const byte* identity, word16 len,
  8810. word32 age, byte hmac, byte cipherSuite0,
  8811. byte cipherSuite, byte resumption,
  8812. PreSharedKey **preSharedKey, void* heap)
  8813. {
  8814. int ret = 0;
  8815. TLSX* extension;
  8816. PreSharedKey* psk = NULL;
  8817. /* Find the pre-shared key extension if it exists. */
  8818. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8819. if (extension == NULL) {
  8820. /* Push new pre-shared key extension. */
  8821. ret = TLSX_Push(extensions, TLSX_PRE_SHARED_KEY, NULL, heap);
  8822. if (ret != 0)
  8823. return ret;
  8824. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8825. if (extension == NULL)
  8826. return MEMORY_E;
  8827. }
  8828. /* Try to find the pre-shared key with this identity. */
  8829. psk = (PreSharedKey*)extension->data;
  8830. while (psk != NULL) {
  8831. if ((psk->identityLen == len) &&
  8832. (XMEMCMP(psk->identity, identity, len) == 0)) {
  8833. break;
  8834. }
  8835. psk = psk->next;
  8836. }
  8837. /* Create a new pre-shared key object if not found. */
  8838. if (psk == NULL) {
  8839. ret = TLSX_PreSharedKey_New((PreSharedKey**)&extension->data, identity,
  8840. len, heap, &psk);
  8841. if (ret != 0)
  8842. return ret;
  8843. }
  8844. /* Update/set age and HMAC algorithm. */
  8845. psk->ticketAge = age;
  8846. psk->hmac = hmac;
  8847. psk->cipherSuite0 = cipherSuite0;
  8848. psk->cipherSuite = cipherSuite;
  8849. psk->resumption = resumption;
  8850. psk->binderLen = GetHmacLength(psk->hmac);
  8851. if (preSharedKey != NULL)
  8852. *preSharedKey = psk;
  8853. return 0;
  8854. }
  8855. #define PSK_FREE_ALL TLSX_PreSharedKey_FreeAll
  8856. #define PSK_GET_SIZE TLSX_PreSharedKey_GetSize
  8857. #define PSK_WRITE TLSX_PreSharedKey_Write
  8858. #define PSK_PARSE TLSX_PreSharedKey_Parse
  8859. #else
  8860. #define PSK_FREE_ALL(a, b) WC_DO_NOTHING
  8861. #define PSK_GET_SIZE(a, b, c) 0
  8862. #define PSK_WRITE(a, b, c, d) 0
  8863. #define PSK_PARSE(a, b, c, d) 0
  8864. #endif
  8865. /******************************************************************************/
  8866. /* PSK Key Exchange Modes */
  8867. /******************************************************************************/
  8868. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  8869. /* Get the size of the encoded PSK KE modes extension.
  8870. * Only in ClientHello.
  8871. *
  8872. * modes The PSK KE mode bit string.
  8873. * msgType The type of the message this extension is being written into.
  8874. * returns the number of bytes of the encoded PSK KE mode extension.
  8875. */
  8876. static int TLSX_PskKeModes_GetSize(byte modes, byte msgType, word16* pSz)
  8877. {
  8878. if (msgType == client_hello) {
  8879. /* Format: Len | Modes* */
  8880. word16 len = OPAQUE8_LEN;
  8881. /* Check whether each possible mode is to be written. */
  8882. if (modes & (1 << PSK_KE))
  8883. len += OPAQUE8_LEN;
  8884. if (modes & (1 << PSK_DHE_KE))
  8885. len += OPAQUE8_LEN;
  8886. *pSz += len;
  8887. return 0;
  8888. }
  8889. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8890. return SANITY_MSG_E;
  8891. }
  8892. /* Writes the PSK KE modes extension into the output buffer.
  8893. * Assumes that the the output buffer is big enough to hold data.
  8894. * Only in ClientHello.
  8895. *
  8896. * modes The PSK KE mode bit string.
  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_PskKeModes_Write(byte modes, byte* output, byte msgType,
  8902. word16* pSz)
  8903. {
  8904. if (msgType == client_hello) {
  8905. /* Format: Len | Modes* */
  8906. word16 idx = OPAQUE8_LEN;
  8907. /* Write out each possible mode. */
  8908. if (modes & (1 << PSK_KE))
  8909. output[idx++] = PSK_KE;
  8910. if (modes & (1 << PSK_DHE_KE))
  8911. output[idx++] = PSK_DHE_KE;
  8912. /* Write out length of mode list. */
  8913. output[0] = (byte)(idx - OPAQUE8_LEN);
  8914. *pSz += idx;
  8915. return 0;
  8916. }
  8917. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8918. return SANITY_MSG_E;
  8919. }
  8920. int TLSX_PskKeyModes_Parse_Modes(const byte* input, word16 length, byte msgType,
  8921. byte* modes)
  8922. {
  8923. if (msgType == client_hello) {
  8924. /* Format: Len | Modes* */
  8925. int idx = 0;
  8926. word16 len;
  8927. *modes = 0;
  8928. /* Ensure length byte exists. */
  8929. if (length < OPAQUE8_LEN)
  8930. return BUFFER_E;
  8931. /* Get length of mode list and ensure that is the only data. */
  8932. len = input[0];
  8933. if (length - OPAQUE8_LEN != len)
  8934. return BUFFER_E;
  8935. idx = OPAQUE8_LEN;
  8936. /* Set a bit for each recognized modes. */
  8937. while (len > 0) {
  8938. /* Ignore unrecognized modes. */
  8939. if (input[idx] <= PSK_DHE_KE)
  8940. *modes |= 1 << input[idx];
  8941. idx++;
  8942. len--;
  8943. }
  8944. return 0;
  8945. }
  8946. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8947. return SANITY_MSG_E;
  8948. }
  8949. /* Parse the PSK KE modes extension.
  8950. * Only in ClientHello.
  8951. *
  8952. * ssl The SSL/TLS object.
  8953. * input The extension data.
  8954. * length The length of the extension data.
  8955. * msgType The type of the message this extension is being parsed from.
  8956. * returns 0 on success and other values indicate failure.
  8957. */
  8958. static int TLSX_PskKeModes_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  8959. byte msgType)
  8960. {
  8961. int ret;
  8962. byte modes;
  8963. ret = TLSX_PskKeyModes_Parse_Modes(input, length, msgType, &modes);
  8964. if (ret == 0)
  8965. ret = TLSX_PskKeyModes_Use(ssl, modes);
  8966. if (ret != 0) {
  8967. WOLFSSL_ERROR_VERBOSE(ret);
  8968. }
  8969. return ret;
  8970. }
  8971. /* Use the data to create a new PSK Key Exchange Modes object in the extensions.
  8972. *
  8973. * ssl The SSL/TLS object.
  8974. * modes The PSK key exchange modes.
  8975. * returns 0 on success and other values indicate failure.
  8976. */
  8977. int TLSX_PskKeyModes_Use(WOLFSSL* ssl, byte modes)
  8978. {
  8979. int ret = 0;
  8980. TLSX* extension;
  8981. /* Find the PSK key exchange modes extension if it exists. */
  8982. extension = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  8983. if (extension == NULL) {
  8984. /* Push new PSK key exchange modes extension. */
  8985. ret = TLSX_Push(&ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES, NULL,
  8986. ssl->heap);
  8987. if (ret != 0)
  8988. return ret;
  8989. extension = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  8990. if (extension == NULL)
  8991. return MEMORY_E;
  8992. }
  8993. extension->val = modes;
  8994. return 0;
  8995. }
  8996. #define PKM_GET_SIZE TLSX_PskKeModes_GetSize
  8997. #define PKM_WRITE TLSX_PskKeModes_Write
  8998. #define PKM_PARSE TLSX_PskKeModes_Parse
  8999. #else
  9000. #define PKM_GET_SIZE(a, b, c) 0
  9001. #define PKM_WRITE(a, b, c, d) 0
  9002. #define PKM_PARSE(a, b, c, d) 0
  9003. #endif
  9004. /******************************************************************************/
  9005. /* Post-Handshake Authentication */
  9006. /******************************************************************************/
  9007. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  9008. /* Get the size of the encoded Post-Handshake Authentication extension.
  9009. * Only in ClientHello.
  9010. *
  9011. * msgType The type of the message this extension is being written into.
  9012. * returns the number of bytes of the encoded Post-Handshake Authentication
  9013. * extension.
  9014. */
  9015. static int TLSX_PostHandAuth_GetSize(byte msgType, word16* pSz)
  9016. {
  9017. if (msgType == client_hello) {
  9018. *pSz += 0;
  9019. return 0;
  9020. }
  9021. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9022. return SANITY_MSG_E;
  9023. }
  9024. /* Writes the Post-Handshake Authentication extension into the output buffer.
  9025. * Assumes that the the output buffer is big enough to hold data.
  9026. * Only in ClientHello.
  9027. *
  9028. * output The buffer to write into.
  9029. * msgType The type of the message this extension is being written into.
  9030. * returns the number of bytes written into the buffer.
  9031. */
  9032. static int TLSX_PostHandAuth_Write(byte* output, byte msgType, word16* pSz)
  9033. {
  9034. (void)output;
  9035. if (msgType == client_hello) {
  9036. *pSz += 0;
  9037. return 0;
  9038. }
  9039. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9040. return SANITY_MSG_E;
  9041. }
  9042. /* Parse the Post-Handshake Authentication extension.
  9043. * Only in ClientHello.
  9044. *
  9045. * ssl The SSL/TLS object.
  9046. * input The extension data.
  9047. * length The length of the extension data.
  9048. * msgType The type of the message this extension is being parsed from.
  9049. * returns 0 on success and other values indicate failure.
  9050. */
  9051. static int TLSX_PostHandAuth_Parse(WOLFSSL* ssl, const byte* input,
  9052. word16 length, byte msgType)
  9053. {
  9054. (void)input;
  9055. if (msgType == client_hello) {
  9056. /* Ensure extension is empty. */
  9057. if (length != 0)
  9058. return BUFFER_E;
  9059. ssl->options.postHandshakeAuth = 1;
  9060. return 0;
  9061. }
  9062. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9063. return SANITY_MSG_E;
  9064. }
  9065. /* Create a new Post-handshake authentication object in the extensions.
  9066. *
  9067. * ssl The SSL/TLS object.
  9068. * returns 0 on success and other values indicate failure.
  9069. */
  9070. static int TLSX_PostHandAuth_Use(WOLFSSL* ssl)
  9071. {
  9072. int ret = 0;
  9073. TLSX* extension;
  9074. /* Find the PSK key exchange modes extension if it exists. */
  9075. extension = TLSX_Find(ssl->extensions, TLSX_POST_HANDSHAKE_AUTH);
  9076. if (extension == NULL) {
  9077. /* Push new Post-handshake Authentication extension. */
  9078. ret = TLSX_Push(&ssl->extensions, TLSX_POST_HANDSHAKE_AUTH, NULL,
  9079. ssl->heap);
  9080. if (ret != 0)
  9081. return ret;
  9082. }
  9083. return 0;
  9084. }
  9085. #define PHA_GET_SIZE TLSX_PostHandAuth_GetSize
  9086. #define PHA_WRITE TLSX_PostHandAuth_Write
  9087. #define PHA_PARSE TLSX_PostHandAuth_Parse
  9088. #else
  9089. #define PHA_GET_SIZE(a, b) 0
  9090. #define PHA_WRITE(a, b, c) 0
  9091. #define PHA_PARSE(a, b, c, d) 0
  9092. #endif
  9093. /******************************************************************************/
  9094. /* Early Data Indication */
  9095. /******************************************************************************/
  9096. #ifdef WOLFSSL_EARLY_DATA
  9097. /* Get the size of the encoded Early Data Indication extension.
  9098. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  9099. *
  9100. * msgType The type of the message this extension is being written into.
  9101. * returns the number of bytes of the encoded Early Data Indication extension.
  9102. */
  9103. static int TLSX_EarlyData_GetSize(byte msgType, word16* pSz)
  9104. {
  9105. int ret = 0;
  9106. if (msgType == client_hello || msgType == encrypted_extensions)
  9107. *pSz += 0;
  9108. else if (msgType == session_ticket)
  9109. *pSz += OPAQUE32_LEN;
  9110. else {
  9111. ret = SANITY_MSG_E;
  9112. WOLFSSL_ERROR_VERBOSE(ret);
  9113. }
  9114. return ret;
  9115. }
  9116. /* Writes the Early Data Indicator extension into the output buffer.
  9117. * Assumes that the the output buffer is big enough to hold data.
  9118. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  9119. *
  9120. * maxSz The maximum early data size.
  9121. * output The buffer to write into.
  9122. * msgType The type of the message this extension is being written into.
  9123. * returns the number of bytes written into the buffer.
  9124. */
  9125. static int TLSX_EarlyData_Write(word32 maxSz, byte* output, byte msgType,
  9126. word16* pSz)
  9127. {
  9128. if (msgType == client_hello || msgType == encrypted_extensions)
  9129. return 0;
  9130. else if (msgType == session_ticket) {
  9131. c32toa(maxSz, output);
  9132. *pSz += OPAQUE32_LEN;
  9133. return 0;
  9134. }
  9135. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9136. return SANITY_MSG_E;
  9137. }
  9138. /* Parse the Early Data Indicator extension.
  9139. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  9140. *
  9141. * ssl The SSL/TLS object.
  9142. * input The extension data.
  9143. * length The length of the extension data.
  9144. * msgType The type of the message this extension is being parsed from.
  9145. * returns 0 on success and other values indicate failure.
  9146. */
  9147. static int TLSX_EarlyData_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  9148. byte msgType)
  9149. {
  9150. WOLFSSL_ENTER("TLSX_EarlyData_Parse");
  9151. if (msgType == client_hello) {
  9152. if (length != 0)
  9153. return BUFFER_E;
  9154. if (ssl->earlyData == expecting_early_data) {
  9155. if (ssl->options.maxEarlyDataSz != 0)
  9156. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_ACCEPTED;
  9157. else
  9158. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_REJECTED;
  9159. return TLSX_EarlyData_Use(ssl, 0, 0);
  9160. }
  9161. ssl->earlyData = early_data_ext;
  9162. return 0;
  9163. }
  9164. if (msgType == encrypted_extensions) {
  9165. if (length != 0)
  9166. return BUFFER_E;
  9167. /* Ensure the index of PSK identity chosen by server is 0.
  9168. * Index is plus one to handle 'not set' value of 0.
  9169. */
  9170. if (ssl->options.pskIdIndex != 1) {
  9171. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  9172. return PSK_KEY_ERROR;
  9173. }
  9174. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  9175. /* the extension from server comes in */
  9176. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_ACCEPTED;
  9177. }
  9178. return TLSX_EarlyData_Use(ssl, 1, 1);
  9179. }
  9180. if (msgType == session_ticket) {
  9181. word32 maxSz;
  9182. if (length != OPAQUE32_LEN)
  9183. return BUFFER_E;
  9184. ato32(input, &maxSz);
  9185. ssl->session->maxEarlyDataSz = maxSz;
  9186. return 0;
  9187. }
  9188. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9189. return SANITY_MSG_E;
  9190. }
  9191. /* Use the data to create a new Early Data object in the extensions.
  9192. *
  9193. * ssl The SSL/TLS object.
  9194. * maxSz The maximum early data size.
  9195. * is_response if this extension is part of a response
  9196. * returns 0 on success and other values indicate failure.
  9197. */
  9198. int TLSX_EarlyData_Use(WOLFSSL* ssl, word32 maxSz, int is_response)
  9199. {
  9200. int ret = 0;
  9201. TLSX* extension;
  9202. /* Find the early data extension if it exists. */
  9203. extension = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  9204. if (extension == NULL) {
  9205. /* Push new early data extension. */
  9206. ret = TLSX_Push(&ssl->extensions, TLSX_EARLY_DATA, NULL, ssl->heap);
  9207. if (ret != 0)
  9208. return ret;
  9209. extension = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  9210. if (extension == NULL)
  9211. return MEMORY_E;
  9212. }
  9213. extension->resp = is_response;
  9214. /* In QUIC, earlydata size is either 0 or 0xffffffff.
  9215. * Override any size between, possibly left from our initial value */
  9216. extension->val = (WOLFSSL_IS_QUIC(ssl) && is_response && maxSz > 0) ?
  9217. WOLFSSL_MAX_32BIT : maxSz;
  9218. return 0;
  9219. }
  9220. #define EDI_GET_SIZE TLSX_EarlyData_GetSize
  9221. #define EDI_WRITE TLSX_EarlyData_Write
  9222. #define EDI_PARSE TLSX_EarlyData_Parse
  9223. #else
  9224. #define EDI_GET_SIZE(a, b) 0
  9225. #define EDI_WRITE(a, b, c, d) 0
  9226. #define EDI_PARSE(a, b, c, d) 0
  9227. #endif
  9228. /******************************************************************************/
  9229. /* QUIC transport parameter extension */
  9230. /******************************************************************************/
  9231. #ifdef WOLFSSL_QUIC
  9232. static word16 TLSX_QuicTP_GetSize(TLSX* extension)
  9233. {
  9234. const QuicTransportParam *tp = (QuicTransportParam*)extension->data;
  9235. return tp ? tp->len : 0;
  9236. }
  9237. int TLSX_QuicTP_Use(WOLFSSL* ssl, TLSX_Type ext_type, int is_response)
  9238. {
  9239. int ret = 0;
  9240. TLSX* extension;
  9241. WOLFSSL_ENTER("TLSX_QuicTP_Use");
  9242. if (ssl->quic.transport_local == NULL) {
  9243. /* RFC9000, ch 7.3: "An endpoint MUST treat the absence of [...]
  9244. * from either endpoint [...] as a connection error of type
  9245. * TRANSPORT_PARAMETER_ERROR."
  9246. */
  9247. ret = QUIC_TP_MISSING_E;
  9248. goto cleanup;
  9249. }
  9250. extension = TLSX_Find(ssl->extensions, ext_type);
  9251. if (extension == NULL) {
  9252. ret = TLSX_Push(&ssl->extensions, ext_type, NULL, ssl->heap);
  9253. if (ret != 0)
  9254. goto cleanup;
  9255. extension = TLSX_Find(ssl->extensions, ext_type);
  9256. if (extension == NULL) {
  9257. ret = MEMORY_E;
  9258. goto cleanup;
  9259. }
  9260. }
  9261. if (extension->data) {
  9262. QuicTransportParam_free((QuicTransportParam*)extension->data, ssl->heap);
  9263. extension->data = NULL;
  9264. }
  9265. extension->resp = is_response;
  9266. extension->data = (void*)QuicTransportParam_dup(ssl->quic.transport_local, ssl->heap);
  9267. if (!extension->data) {
  9268. ret = MEMORY_E;
  9269. goto cleanup;
  9270. }
  9271. cleanup:
  9272. WOLFSSL_LEAVE("TLSX_QuicTP_Use", ret);
  9273. return ret;
  9274. }
  9275. static word16 TLSX_QuicTP_Write(QuicTransportParam *tp, byte* output)
  9276. {
  9277. word16 len = 0;
  9278. WOLFSSL_ENTER("TLSX_QuicTP_Write");
  9279. if (tp && tp->len) {
  9280. XMEMCPY(output, tp->data, tp->len);
  9281. len = tp->len;
  9282. }
  9283. WOLFSSL_LEAVE("TLSX_QuicTP_Write", len);
  9284. return len;
  9285. }
  9286. static int TLSX_QuicTP_Parse(WOLFSSL *ssl, const byte *input, size_t len, int ext_type, int msgType)
  9287. {
  9288. const QuicTransportParam *tp, **ptp;
  9289. (void)msgType;
  9290. tp = QuicTransportParam_new(input, len, ssl->heap);
  9291. if (!tp) {
  9292. return MEMORY_E;
  9293. }
  9294. ptp = (ext_type == TLSX_KEY_QUIC_TP_PARAMS_DRAFT) ?
  9295. &ssl->quic.transport_peer_draft : &ssl->quic.transport_peer;
  9296. if (*ptp) {
  9297. QTP_FREE(*ptp, ssl->heap);
  9298. }
  9299. *ptp = tp;
  9300. return 0;
  9301. }
  9302. #define QTP_GET_SIZE TLSX_QuicTP_GetSize
  9303. #define QTP_USE TLSX_QuicTP_Use
  9304. #define QTP_WRITE TLSX_QuicTP_Write
  9305. #define QTP_PARSE TLSX_QuicTP_Parse
  9306. #endif /* WOLFSSL_QUIC */
  9307. #if defined(WOLFSSL_DTLS_CID)
  9308. #define CID_GET_SIZE TLSX_ConnectionID_GetSize
  9309. #define CID_WRITE TLSX_ConnectionID_Write
  9310. #define CID_PARSE TLSX_ConnectionID_Parse
  9311. #define CID_FREE TLSX_ConnectionID_Free
  9312. #else
  9313. #define CID_GET_SIZE(a) 0
  9314. #define CID_WRITE(a, b) 0
  9315. #define CID_PARSE(a, b, c, d) 0
  9316. #define CID_FREE(a, b) 0
  9317. #endif /* defined(WOLFSSL_DTLS_CID) */
  9318. #if defined(HAVE_RPK)
  9319. /******************************************************************************/
  9320. /* Client_Certificate_Type extension */
  9321. /******************************************************************************/
  9322. /* return 1 if specified type is included in the given list, otherwise 0 */
  9323. static int IsCertTypeListed(byte type, byte cnt, const byte* list)
  9324. {
  9325. int ret = 0;
  9326. int i;
  9327. if (cnt == 0 || list == NULL)
  9328. return ret;
  9329. if (cnt > 0 && cnt <= MAX_CLIENT_CERT_TYPE_CNT) {
  9330. for (i = 0; i < cnt; i++) {
  9331. if (list[i] == type)
  9332. return 1;
  9333. }
  9334. }
  9335. return 0;
  9336. }
  9337. /* Search both arrays from above to find a common value between the two given
  9338. * arrays(a and b). return 1 if it finds a common value, otherwise return 0.
  9339. */
  9340. static int GetCommonItem(const byte* a, byte aLen, const byte* b, byte bLen,
  9341. byte* type)
  9342. {
  9343. int i, j;
  9344. if (a == NULL || b == NULL)
  9345. return 0;
  9346. for (i = 0; i < aLen; i++) {
  9347. for (j = 0; j < bLen; j++) {
  9348. if (a[i] == b[j]) {
  9349. *type = a[i];
  9350. return 1;
  9351. }
  9352. }
  9353. }
  9354. return 0;
  9355. }
  9356. /* Creates a "client certificate type" extension if necessary.
  9357. * Returns 0 if no error occurred, negative value otherwise.
  9358. * A return of 0, it does not indicae that the extension was created.
  9359. */
  9360. static int TLSX_ClientCertificateType_Use(WOLFSSL* ssl, byte isServer)
  9361. {
  9362. int ret = 0;
  9363. if (ssl == NULL)
  9364. return BAD_FUNC_ARG;
  9365. if (isServer) {
  9366. /* [in server side]
  9367. */
  9368. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_RPK,
  9369. ssl->options.rpkConfig.preferred_ClientCertTypeCnt,
  9370. ssl->options.rpkConfig.preferred_ClientCertTypes)) {
  9371. WOLFSSL_MSG("Adding Client Certificate Type extension");
  9372. ret = TLSX_Push(&ssl->extensions, TLSX_CLIENT_CERTIFICATE_TYPE, ssl,
  9373. ssl->heap);
  9374. if (ret == 0) {
  9375. TLSX_SetResponse(ssl, TLSX_CLIENT_CERTIFICATE_TYPE);
  9376. }
  9377. }
  9378. }
  9379. else {
  9380. /* [in client side]
  9381. * This extension MUST be omitted from the ClientHello unless the RPK
  9382. * certificate is preferred by the user and actually loaded.
  9383. */
  9384. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_RPK,
  9385. ssl->options.rpkConfig.preferred_ClientCertTypeCnt,
  9386. ssl->options.rpkConfig.preferred_ClientCertTypes)) {
  9387. if (ssl->options.rpkState.isRPKLoaded) {
  9388. ssl->options.rpkState.sending_ClientCertTypeCnt = 1;
  9389. ssl->options.rpkState.sending_ClientCertTypes[0] =
  9390. WOLFSSL_CERT_TYPE_RPK;
  9391. /* Push new client_certificate_type extension. */
  9392. WOLFSSL_MSG("Adding Client Certificate Type extension");
  9393. ret = TLSX_Push(&ssl->extensions, TLSX_CLIENT_CERTIFICATE_TYPE,
  9394. ssl, ssl->heap);
  9395. }
  9396. else {
  9397. WOLFSSL_MSG("Willing to use RPK cert but not loaded it");
  9398. }
  9399. }
  9400. else {
  9401. WOLFSSL_MSG("No will to use RPK cert");
  9402. }
  9403. }
  9404. return ret;
  9405. }
  9406. /* Parse a "client certificate type" extension received from peer.
  9407. * returns 0 on success and other values indicate failure.
  9408. */
  9409. static int TLSX_ClientCertificateType_Parse(WOLFSSL* ssl, const byte* input,
  9410. word16 length, byte msgType)
  9411. {
  9412. byte typeCnt;
  9413. int idx = 0;
  9414. int ret = 0;
  9415. int i;
  9416. int populate = 0;
  9417. byte cmnType;
  9418. if (msgType == client_hello) {
  9419. /* [parse ClientHello in server end]
  9420. * case 1) if peer verify is disabled, this extension must be omitted
  9421. * from ServerHello.
  9422. * case 2) if user have not set his preference, find X509 in parsed
  9423. * result, then populate "Client Certificate Type" extension.
  9424. * case 3) if user have not set his preference and X509 isn't included
  9425. * in parsed result, send "unsupported certificate" alert.
  9426. * case 4) if user have set his preference, find a common cert type
  9427. * in users preference and received cert types.
  9428. * case 5) if user have set his preference, but no common cert type
  9429. * found.
  9430. */
  9431. /* case 1 */
  9432. if (ssl->options.verifyNone) {
  9433. return ret;
  9434. }
  9435. /* parse extension */
  9436. if (length < OPAQUE8_LEN)
  9437. return BUFFER_E;
  9438. typeCnt = input[idx];
  9439. if (typeCnt > MAX_CLIENT_CERT_TYPE_CNT)
  9440. return BUFFER_E;
  9441. if ((typeCnt + 1) * OPAQUE8_LEN != length){
  9442. return BUFFER_E;
  9443. }
  9444. ssl->options.rpkState.received_ClientCertTypeCnt = input[idx];
  9445. idx += OPAQUE8_LEN;
  9446. for (i = 0; i < typeCnt; i++) {
  9447. ssl->options.rpkState.received_ClientCertTypes[i] = input[idx];
  9448. idx += OPAQUE8_LEN;
  9449. }
  9450. if (ssl->options.rpkConfig.preferred_ClientCertTypeCnt == 0) {
  9451. /* case 2 */
  9452. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_X509,
  9453. ssl->options.rpkState.received_ClientCertTypeCnt,
  9454. ssl->options.rpkState.received_ClientCertTypes)) {
  9455. ssl->options.rpkState.sending_ClientCertTypeCnt = 1;
  9456. ssl->options.rpkState.sending_ClientCertTypes[0] =
  9457. WOLFSSL_CERT_TYPE_X509;
  9458. populate = 1;
  9459. }
  9460. /* case 3 */
  9461. else {
  9462. WOLFSSL_MSG("No common cert type found in client_certificate_type ext");
  9463. SendAlert(ssl, alert_fatal, unsupported_certificate);
  9464. return UNSUPPORTED_CERTIFICATE;
  9465. }
  9466. }
  9467. else if (ssl->options.rpkConfig.preferred_ClientCertTypeCnt > 0) {
  9468. /* case 4 */
  9469. if (GetCommonItem(
  9470. ssl->options.rpkConfig.preferred_ClientCertTypes,
  9471. ssl->options.rpkConfig.preferred_ClientCertTypeCnt,
  9472. ssl->options.rpkState.received_ClientCertTypes,
  9473. ssl->options.rpkState.received_ClientCertTypeCnt,
  9474. &cmnType)) {
  9475. ssl->options.rpkState.sending_ClientCertTypeCnt = 1;
  9476. ssl->options.rpkState.sending_ClientCertTypes[0] = cmnType;
  9477. populate = 1;
  9478. }
  9479. /* case 5 */
  9480. else {
  9481. WOLFSSL_MSG("No common cert type found in client_certificate_type ext");
  9482. SendAlert(ssl, alert_fatal, unsupported_certificate);
  9483. return UNSUPPORTED_CERTIFICATE;
  9484. }
  9485. }
  9486. /* populate client_certificate_type extension */
  9487. if (populate) {
  9488. WOLFSSL_MSG("Adding Client Certificate Type extension");
  9489. ret = TLSX_Push(&ssl->extensions, TLSX_CLIENT_CERTIFICATE_TYPE, ssl,
  9490. ssl->heap);
  9491. if (ret == 0) {
  9492. TLSX_SetResponse(ssl, TLSX_CLIENT_CERTIFICATE_TYPE);
  9493. }
  9494. }
  9495. }
  9496. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9497. /* parse it in client side */
  9498. if (length == 1) {
  9499. ssl->options.rpkState.received_ClientCertTypeCnt = 1;
  9500. ssl->options.rpkState.received_ClientCertTypes[0] = *input;
  9501. }
  9502. else {
  9503. return BUFFER_E;
  9504. }
  9505. }
  9506. return ret;
  9507. }
  9508. /* Write out the "client certificate type" extension data into the given buffer.
  9509. * return the size wrote in the buffer on success, negative value on error.
  9510. */
  9511. static word16 TLSX_ClientCertificateType_Write(void* data, byte* output,
  9512. byte msgType)
  9513. {
  9514. WOLFSSL* ssl = (WOLFSSL*)data;
  9515. word16 idx = 0;
  9516. byte cnt = 0;
  9517. int i;
  9518. /* skip to write extension if count is zero */
  9519. cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;
  9520. if (cnt == 0)
  9521. return 0;
  9522. if (msgType == client_hello) {
  9523. /* client side */
  9524. *(output + idx) = cnt;
  9525. idx += OPAQUE8_LEN;
  9526. for (i = 0; i < cnt; i++) {
  9527. *(output + idx) = ssl->options.rpkState.sending_ClientCertTypes[i];
  9528. idx += OPAQUE8_LEN;
  9529. }
  9530. return idx;
  9531. }
  9532. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9533. /* sever side */
  9534. if (cnt == 1) {
  9535. *(output + idx) = ssl->options.rpkState.sending_ClientCertTypes[0];
  9536. idx += OPAQUE8_LEN;
  9537. }
  9538. }
  9539. return idx;
  9540. }
  9541. /* Calculate then return the size of the "client certificate type" extension
  9542. * data.
  9543. * return the extension data size on success, negative value on error.
  9544. */
  9545. static int TLSX_ClientCertificateType_GetSize(WOLFSSL* ssl, byte msgType)
  9546. {
  9547. int ret = 0;
  9548. byte cnt;
  9549. if (ssl == NULL)
  9550. return BAD_FUNC_ARG;
  9551. if (msgType == client_hello) {
  9552. /* client side */
  9553. cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;
  9554. ret = (int)(OPAQUE8_LEN + cnt * OPAQUE8_LEN);
  9555. }
  9556. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9557. /* server side */
  9558. cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;/* must be one */
  9559. if (cnt != 1)
  9560. return SANITY_MSG_E;
  9561. ret = OPAQUE8_LEN;
  9562. }
  9563. else {
  9564. return SANITY_MSG_E;
  9565. }
  9566. return ret;
  9567. }
  9568. #define CCT_GET_SIZE TLSX_ClientCertificateType_GetSize
  9569. #define CCT_WRITE TLSX_ClientCertificateType_Write
  9570. #define CCT_PARSE TLSX_ClientCertificateType_Parse
  9571. #else
  9572. #define CCT_GET_SIZE(a) 0
  9573. #define CCT_WRITE(a, b) 0
  9574. #define CCT_PARSE(a, b, c, d) 0
  9575. #endif /* HAVE_RPK */
  9576. #if defined(HAVE_RPK)
  9577. /******************************************************************************/
  9578. /* Server_Certificate_Type extension */
  9579. /******************************************************************************/
  9580. /* Creates a "server certificate type" extension if necessary.
  9581. * Returns 0 if no error occurred, negative value otherwise.
  9582. * A return of 0, it does not indicae that the extension was created.
  9583. */
  9584. static int TLSX_ServerCertificateType_Use(WOLFSSL* ssl, byte isServer)
  9585. {
  9586. int ret = 0;
  9587. byte ctype;
  9588. if (ssl == NULL)
  9589. return BAD_FUNC_ARG;
  9590. if (isServer) {
  9591. /* [in server side] */
  9592. /* find common cert type to both end */
  9593. if (GetCommonItem(
  9594. ssl->options.rpkConfig.preferred_ServerCertTypes,
  9595. ssl->options.rpkConfig.preferred_ServerCertTypeCnt,
  9596. ssl->options.rpkState.received_ServerCertTypes,
  9597. ssl->options.rpkState.received_ServerCertTypeCnt,
  9598. &ctype)) {
  9599. ssl->options.rpkState.sending_ServerCertTypeCnt = 1;
  9600. ssl->options.rpkState.sending_ServerCertTypes[0] = ctype;
  9601. /* Push new server_certificate_type extension. */
  9602. WOLFSSL_MSG("Adding Server Certificate Type extension");
  9603. ret = TLSX_Push(&ssl->extensions, TLSX_SERVER_CERTIFICATE_TYPE, ssl,
  9604. ssl->heap);
  9605. if (ret == 0) {
  9606. TLSX_SetResponse(ssl, TLSX_SERVER_CERTIFICATE_TYPE);
  9607. }
  9608. }
  9609. else {
  9610. /* no common cert type found */
  9611. WOLFSSL_MSG("No common cert type found in server_certificate_type ext");
  9612. SendAlert(ssl, alert_fatal, unsupported_certificate);
  9613. ret = UNSUPPORTED_CERTIFICATE;
  9614. }
  9615. }
  9616. else {
  9617. /* [in client side] */
  9618. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_RPK,
  9619. ssl->options.rpkConfig.preferred_ServerCertTypeCnt,
  9620. ssl->options.rpkConfig.preferred_ServerCertTypes)) {
  9621. ssl->options.rpkState.sending_ServerCertTypeCnt =
  9622. ssl->options.rpkConfig.preferred_ServerCertTypeCnt;
  9623. XMEMCPY(ssl->options.rpkState.sending_ServerCertTypes,
  9624. ssl->options.rpkConfig.preferred_ServerCertTypes,
  9625. ssl->options.rpkConfig.preferred_ServerCertTypeCnt);
  9626. /* Push new server_certificate_type extension. */
  9627. WOLFSSL_MSG("Adding Server Certificate Type extension");
  9628. ret = TLSX_Push(&ssl->extensions, TLSX_SERVER_CERTIFICATE_TYPE, ssl,
  9629. ssl->heap);
  9630. }
  9631. else {
  9632. WOLFSSL_MSG("No will to accept RPK cert");
  9633. }
  9634. }
  9635. return ret;
  9636. }
  9637. /* Parse a "server certificate type" extension received from peer.
  9638. * returns 0 on success and other values indicate failure.
  9639. */
  9640. static int TLSX_ServerCertificateType_Parse(WOLFSSL* ssl, const byte* input,
  9641. word16 length, byte msgType)
  9642. {
  9643. byte typeCnt;
  9644. int idx = 0;
  9645. int ret = 0;
  9646. int i;
  9647. if (msgType == client_hello) {
  9648. /* in server side */
  9649. if (length < OPAQUE8_LEN)
  9650. return BUFFER_E;
  9651. typeCnt = input[idx];
  9652. if (typeCnt > MAX_SERVER_CERT_TYPE_CNT)
  9653. return BUFFER_E;
  9654. if ((typeCnt + 1) * OPAQUE8_LEN != length){
  9655. return BUFFER_E;
  9656. }
  9657. ssl->options.rpkState.received_ServerCertTypeCnt = input[idx];
  9658. idx += OPAQUE8_LEN;
  9659. for (i = 0; i < typeCnt; i++) {
  9660. ssl->options.rpkState.received_ServerCertTypes[i] = input[idx];
  9661. idx += OPAQUE8_LEN;
  9662. }
  9663. ret = TLSX_ServerCertificateType_Use(ssl, 1);
  9664. if (ret == 0) {
  9665. TLSX_SetResponse(ssl, TLSX_SERVER_CERTIFICATE_TYPE);
  9666. }
  9667. }
  9668. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9669. /* in client side */
  9670. if (length != 1) /* length slould be 1 */
  9671. return BUFFER_E;
  9672. ssl->options.rpkState.received_ServerCertTypeCnt = 1;
  9673. ssl->options.rpkState.received_ServerCertTypes[0] = *input;
  9674. }
  9675. return 0;
  9676. }
  9677. /* Write out the "server certificate type" extension data into the given buffer.
  9678. * return the size wrote in the buffer on success, negative value on error.
  9679. */
  9680. static word16 TLSX_ServerCertificateType_Write(void* data, byte* output,
  9681. byte msgType)
  9682. {
  9683. WOLFSSL* ssl = (WOLFSSL*)data;
  9684. word16 idx = 0;
  9685. int cnt = 0;
  9686. int i;
  9687. /* skip to write extension if count is zero */
  9688. cnt = ssl->options.rpkState.sending_ServerCertTypeCnt;
  9689. if (cnt == 0)
  9690. return 0;
  9691. if (msgType == client_hello) {
  9692. /* in client side */
  9693. *(output + idx) = cnt;
  9694. idx += OPAQUE8_LEN;
  9695. for (i = 0; i < cnt; i++) {
  9696. *(output + idx) = ssl->options.rpkState.sending_ServerCertTypes[i];
  9697. idx += OPAQUE8_LEN;
  9698. }
  9699. }
  9700. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9701. /* in server side */
  9702. /* ensure cnt is one */
  9703. if (cnt != 1)
  9704. return 0;
  9705. *(output + idx) = ssl->options.rpkState.sending_ServerCertTypes[0];
  9706. idx += OPAQUE8_LEN;
  9707. }
  9708. return idx;
  9709. }
  9710. /* Calculate then return the size of the "server certificate type" extension
  9711. * data.
  9712. * return the extension data size on success, negative value on error.
  9713. */
  9714. static int TLSX_ServerCertificateType_GetSize(WOLFSSL* ssl, byte msgType)
  9715. {
  9716. int ret = 0;
  9717. int cnt;
  9718. if (ssl == NULL)
  9719. return BAD_FUNC_ARG;
  9720. if (msgType == client_hello) {
  9721. /* in clent side */
  9722. cnt = ssl->options.rpkState.sending_ServerCertTypeCnt;
  9723. if (cnt > 0) {
  9724. ret = (int)(OPAQUE8_LEN + cnt * OPAQUE8_LEN);
  9725. }
  9726. }
  9727. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9728. /* in server side */
  9729. ret = (int)OPAQUE8_LEN;
  9730. }
  9731. else {
  9732. return SANITY_MSG_E;
  9733. }
  9734. return ret;
  9735. }
  9736. #define SCT_GET_SIZE TLSX_ServerCertificateType_GetSize
  9737. #define SCT_WRITE TLSX_ServerCertificateType_Write
  9738. #define SCT_PARSE TLSX_ServerCertificateType_Parse
  9739. #else
  9740. #define SCT_GET_SIZE(a) 0
  9741. #define SCT_WRITE(a, b) 0
  9742. #define SCT_PARSE(a, b, c, d) 0
  9743. #endif /* HAVE_RPK */
  9744. /******************************************************************************/
  9745. /* TLS Extensions Framework */
  9746. /******************************************************************************/
  9747. /** Finds an extension in the provided list. */
  9748. TLSX* TLSX_Find(TLSX* list, TLSX_Type type)
  9749. {
  9750. TLSX* extension = list;
  9751. while (extension && extension->type != type)
  9752. extension = extension->next;
  9753. return extension;
  9754. }
  9755. /** Remove an extension. */
  9756. void TLSX_Remove(TLSX** list, TLSX_Type type, void* heap)
  9757. {
  9758. TLSX* extension;
  9759. TLSX** next;
  9760. if (list == NULL)
  9761. return;
  9762. extension = *list;
  9763. next = list;
  9764. while (extension && extension->type != type) {
  9765. next = &extension->next;
  9766. extension = extension->next;
  9767. }
  9768. if (extension) {
  9769. *next = extension->next;
  9770. extension->next = NULL;
  9771. TLSX_FreeAll(extension, heap);
  9772. }
  9773. }
  9774. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  9775. #define GREASE_ECH_SIZE 160
  9776. #define MAX_PUBLIC_NAME_SZ 256
  9777. #define TLS_INFO_CONST_STRING "tls ech"
  9778. #define TLS_INFO_CONST_STRING_SZ 7
  9779. /* return status after setting up ech to write a grease ech */
  9780. static int TLSX_GreaseECH_Use(TLSX** extensions, void* heap, WC_RNG* rng)
  9781. {
  9782. int ret = 0;
  9783. WOLFSSL_ECH* ech;
  9784. if (extensions == NULL)
  9785. return BAD_FUNC_ARG;
  9786. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9787. DYNAMIC_TYPE_TMP_BUFFER);
  9788. if (ech == NULL)
  9789. return MEMORY_E;
  9790. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9791. ech->state = ECH_WRITE_GREASE;
  9792. /* 0 for outer */
  9793. ech->type = ECH_TYPE_OUTER;
  9794. /* kemId */
  9795. ech->kemId = DHKEM_X25519_HKDF_SHA256;
  9796. /* cipherSuite kdf */
  9797. ech->cipherSuite.kdfId = HKDF_SHA256;
  9798. /* cipherSuite aead */
  9799. ech->cipherSuite.aeadId = HPKE_AES_128_GCM;
  9800. /* random configId */
  9801. ret = wc_RNG_GenerateByte(rng, &(ech->configId));
  9802. /* curve25519 encLen */
  9803. ech->encLen = DHKEM_X25519_ENC_LEN;
  9804. if (ret == 0)
  9805. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9806. if (ret != 0) {
  9807. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9808. }
  9809. return ret;
  9810. }
  9811. /* return status after setting up ech to write real ech */
  9812. static int TLSX_ECH_Use(WOLFSSL_EchConfig* echConfig, TLSX** extensions,
  9813. void* heap, WC_RNG* rng)
  9814. {
  9815. int ret = 0;
  9816. int suiteIndex;
  9817. WOLFSSL_ECH* ech;
  9818. if (extensions == NULL)
  9819. return BAD_FUNC_ARG;
  9820. /* find a supported cipher suite */
  9821. suiteIndex = EchConfigGetSupportedCipherSuite(echConfig);
  9822. if (suiteIndex < 0)
  9823. return suiteIndex;
  9824. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9825. DYNAMIC_TYPE_TMP_BUFFER);
  9826. if (ech == NULL)
  9827. return MEMORY_E;
  9828. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9829. ech->state = ECH_WRITE_REAL;
  9830. ech->echConfig = echConfig;
  9831. /* 0 for outer */
  9832. ech->type = ECH_TYPE_OUTER;
  9833. /* kemId */
  9834. ech->kemId = echConfig->kemId;
  9835. /* cipherSuite kdf */
  9836. ech->cipherSuite.kdfId = echConfig->cipherSuites[suiteIndex].kdfId;
  9837. /* cipherSuite aead */
  9838. ech->cipherSuite.aeadId = echConfig->cipherSuites[suiteIndex].aeadId;
  9839. /* configId */
  9840. ech->configId = echConfig->configId;
  9841. /* encLen */
  9842. switch (echConfig->kemId)
  9843. {
  9844. case DHKEM_P256_HKDF_SHA256:
  9845. ech->encLen = DHKEM_P256_ENC_LEN;
  9846. break;
  9847. case DHKEM_P384_HKDF_SHA384:
  9848. ech->encLen = DHKEM_P384_ENC_LEN;
  9849. break;
  9850. case DHKEM_P521_HKDF_SHA512:
  9851. ech->encLen = DHKEM_P521_ENC_LEN;
  9852. break;
  9853. case DHKEM_X25519_HKDF_SHA256:
  9854. ech->encLen = DHKEM_X25519_ENC_LEN;
  9855. break;
  9856. case DHKEM_X448_HKDF_SHA512:
  9857. ech->encLen = DHKEM_X448_ENC_LEN;
  9858. break;
  9859. }
  9860. /* setup hpke */
  9861. ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER);
  9862. if (ech->hpke == NULL) {
  9863. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9864. return MEMORY_E;
  9865. }
  9866. ret = wc_HpkeInit(ech->hpke, ech->kemId, ech->cipherSuite.kdfId,
  9867. ech->cipherSuite.aeadId, heap);
  9868. /* setup the ephemeralKey */
  9869. if (ret == 0)
  9870. ret = wc_HpkeGenerateKeyPair(ech->hpke, &ech->ephemeralKey, rng);
  9871. if (ret == 0)
  9872. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9873. if (ret != 0) {
  9874. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9875. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9876. }
  9877. return ret;
  9878. }
  9879. /* return status after setting up ech to read and decrypt */
  9880. static int TLSX_ServerECH_Use(TLSX** extensions, void* heap,
  9881. WOLFSSL_EchConfig* configs)
  9882. {
  9883. int ret;
  9884. WOLFSSL_ECH* ech;
  9885. TLSX* echX;
  9886. if (extensions == NULL)
  9887. return BAD_FUNC_ARG;
  9888. /* if we already have ech don't override it */
  9889. echX = TLSX_Find(*extensions, TLSX_ECH);
  9890. if (echX != NULL)
  9891. return 0;
  9892. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9893. DYNAMIC_TYPE_TMP_BUFFER);
  9894. if (ech == NULL)
  9895. return MEMORY_E;
  9896. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9897. ech->state = ECH_WRITE_NONE;
  9898. /* 0 for outer */
  9899. ech->type = ECH_TYPE_OUTER;
  9900. ech->echConfig = configs;
  9901. /* setup the rest of the settings when we receive ech from the client */
  9902. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9903. if (ret != 0)
  9904. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9905. return ret;
  9906. }
  9907. /* return length after writing the ech */
  9908. static int TLSX_ECH_Write(WOLFSSL_ECH* ech, byte* writeBuf, word16* offset)
  9909. {
  9910. int ret = 0;
  9911. int rngRet = -1;
  9912. word32 configsLen = 0;
  9913. void* ephemeralKey = NULL;
  9914. byte* writeBuf_p = writeBuf;
  9915. #ifdef WOLFSSL_SMALL_STACK
  9916. Hpke* hpke = NULL;
  9917. WC_RNG* rng = NULL;
  9918. #else
  9919. Hpke hpke[1];
  9920. WC_RNG rng[1];
  9921. #endif
  9922. WOLFSSL_MSG("TLSX_ECH_Write");
  9923. if (ech->state == ECH_WRITE_NONE || ech->state == ECH_PARSED_INTERNAL)
  9924. return 0;
  9925. if (ech->state == ECH_WRITE_RETRY_CONFIGS) {
  9926. /* get size then write */
  9927. ret = GetEchConfigsEx(ech->echConfig, NULL, &configsLen);
  9928. if (ret != LENGTH_ONLY_E)
  9929. return ret;
  9930. ret = GetEchConfigsEx(ech->echConfig, writeBuf, &configsLen);
  9931. if (ret != WOLFSSL_SUCCESS)
  9932. return ret;
  9933. *offset += configsLen;
  9934. return 0;
  9935. }
  9936. #ifdef WOLFSSL_SMALL_STACK
  9937. hpke = (Hpke*)XMALLOC(sizeof(Hpke), NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9938. if (hpke == NULL)
  9939. return MEMORY_E;
  9940. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  9941. if (rng == NULL) {
  9942. XFREE(hpke, NULL, DYNAMIC_TYPE_RNG);
  9943. return MEMORY_E;
  9944. }
  9945. #endif
  9946. /* type */
  9947. *writeBuf_p = ech->type;
  9948. writeBuf_p += sizeof(ech->type);
  9949. /* outer has body, inner does not */
  9950. if (ech->type == ECH_TYPE_OUTER) {
  9951. /* kdfId */
  9952. c16toa(ech->cipherSuite.kdfId, writeBuf_p);
  9953. writeBuf_p += sizeof(ech->cipherSuite.kdfId);
  9954. /* aeadId */
  9955. c16toa(ech->cipherSuite.aeadId, writeBuf_p);
  9956. writeBuf_p += sizeof(ech->cipherSuite.aeadId);
  9957. /* configId */
  9958. *writeBuf_p = ech->configId;
  9959. writeBuf_p += sizeof(ech->configId);
  9960. /* encLen */
  9961. c16toa(ech->encLen, writeBuf_p);
  9962. writeBuf_p += 2;
  9963. if (ech->state == ECH_WRITE_GREASE) {
  9964. /* hpke init */
  9965. ret = wc_HpkeInit(hpke, ech->kemId, ech->cipherSuite.kdfId,
  9966. ech->cipherSuite.aeadId, NULL);
  9967. if (ret == 0)
  9968. rngRet = ret = wc_InitRng(rng);
  9969. /* create the ephemeralKey */
  9970. if (ret == 0)
  9971. ret = wc_HpkeGenerateKeyPair(hpke, &ephemeralKey, rng);
  9972. /* enc */
  9973. if (ret == 0) {
  9974. ret = wc_HpkeSerializePublicKey(hpke, ephemeralKey, writeBuf_p,
  9975. &ech->encLen);
  9976. writeBuf_p += ech->encLen;
  9977. }
  9978. if (ret == 0) {
  9979. /* innerClientHelloLen */
  9980. c16toa(GREASE_ECH_SIZE + ((writeBuf_p + 2 - writeBuf) % 32),
  9981. writeBuf_p);
  9982. writeBuf_p += 2;
  9983. /* innerClientHello */
  9984. ret = wc_RNG_GenerateBlock(rng, writeBuf_p, GREASE_ECH_SIZE +
  9985. ((writeBuf_p - writeBuf) % 32));
  9986. writeBuf_p += GREASE_ECH_SIZE + ((writeBuf_p - writeBuf) % 32);
  9987. }
  9988. if (rngRet == 0)
  9989. wc_FreeRng(rng);
  9990. if (ephemeralKey != NULL)
  9991. wc_HpkeFreeKey(hpke, hpke->kem, ephemeralKey, hpke->heap);
  9992. }
  9993. else {
  9994. /* write enc to writeBuf_p */
  9995. ret = wc_HpkeSerializePublicKey(ech->hpke, ech->ephemeralKey,
  9996. writeBuf_p, &ech->encLen);
  9997. writeBuf_p += ech->encLen;
  9998. /* innerClientHelloLen */
  9999. c16toa(ech->innerClientHelloLen, writeBuf_p);
  10000. writeBuf_p += 2;
  10001. /* set payload offset for when we finalize */
  10002. ech->outerClientPayload = writeBuf_p;
  10003. /* write zeros for payload */
  10004. XMEMSET(writeBuf_p, 0, ech->innerClientHelloLen);
  10005. writeBuf_p += ech->innerClientHelloLen;
  10006. }
  10007. }
  10008. #ifdef WOLFSSL_SMALL_STACK
  10009. XFREE(hpke, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10010. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  10011. #endif
  10012. if (ret == 0)
  10013. *offset += (writeBuf_p - writeBuf);
  10014. return ret;
  10015. }
  10016. /* return the size needed for the ech extension */
  10017. static int TLSX_ECH_GetSize(WOLFSSL_ECH* ech)
  10018. {
  10019. int ret;
  10020. word32 size;
  10021. if (ech->state == ECH_WRITE_GREASE) {
  10022. size = sizeof(ech->type) + sizeof(ech->cipherSuite) +
  10023. sizeof(ech->configId) + sizeof(word16) + ech->encLen +
  10024. sizeof(word16);
  10025. size += GREASE_ECH_SIZE + (size % 32);
  10026. }
  10027. else if (ech->state == ECH_WRITE_NONE ||
  10028. ech->state == ECH_PARSED_INTERNAL) {
  10029. size = 0;
  10030. }
  10031. else if (ech->state == ECH_WRITE_RETRY_CONFIGS) {
  10032. /* get the size of the raw configs */
  10033. ret = GetEchConfigsEx(ech->echConfig, NULL, &size);
  10034. if (ret != LENGTH_ONLY_E)
  10035. return ret;
  10036. }
  10037. else if (ech->type == ECH_TYPE_INNER)
  10038. {
  10039. size = sizeof(ech->type);
  10040. }
  10041. else
  10042. {
  10043. size = sizeof(ech->type) + sizeof(ech->cipherSuite) +
  10044. sizeof(ech->configId) + sizeof(word16) + ech->encLen +
  10045. sizeof(word16) + ech->innerClientHelloLen;
  10046. }
  10047. return (int)size;
  10048. }
  10049. /* return status after attempting to open the hpke encrypted ech extension, if
  10050. * successful the inner client hello will be stored in
  10051. * ech->innerClientHelloLen */
  10052. static int TLSX_ExtractEch(WOLFSSL_ECH* ech, WOLFSSL_EchConfig* echConfig,
  10053. byte* aad, word32 aadLen, void* heap)
  10054. {
  10055. int ret = 0;
  10056. int expectedEncLen;
  10057. int i;
  10058. word32 rawConfigLen = 0;
  10059. byte* info = NULL;
  10060. word32 infoLen = 0;
  10061. if (ech == NULL || echConfig == NULL || aad == NULL)
  10062. return BAD_FUNC_ARG;
  10063. /* verify the kem and key len */
  10064. switch (echConfig->kemId)
  10065. {
  10066. case DHKEM_P256_HKDF_SHA256:
  10067. expectedEncLen = DHKEM_P256_ENC_LEN;
  10068. break;
  10069. case DHKEM_P384_HKDF_SHA384:
  10070. expectedEncLen = DHKEM_P384_ENC_LEN;
  10071. break;
  10072. case DHKEM_P521_HKDF_SHA512:
  10073. expectedEncLen = DHKEM_P521_ENC_LEN;
  10074. break;
  10075. case DHKEM_X25519_HKDF_SHA256:
  10076. expectedEncLen = DHKEM_X25519_ENC_LEN;
  10077. break;
  10078. case DHKEM_X448_HKDF_SHA512:
  10079. expectedEncLen = DHKEM_X448_ENC_LEN;
  10080. break;
  10081. default:
  10082. expectedEncLen = 0;
  10083. break;
  10084. }
  10085. if (expectedEncLen != ech->encLen)
  10086. return BAD_FUNC_ARG;
  10087. /* verify the cipher suite */
  10088. for (i = 0; i < echConfig->numCipherSuites; i++) {
  10089. if (echConfig->cipherSuites[i].kdfId == ech->cipherSuite.kdfId &&
  10090. echConfig->cipherSuites[i].aeadId == ech->cipherSuite.aeadId) {
  10091. break;
  10092. }
  10093. }
  10094. if (i >= echConfig->numCipherSuites) {
  10095. return BAD_FUNC_ARG;
  10096. }
  10097. ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER);
  10098. if (ech->hpke == NULL)
  10099. return MEMORY_E;
  10100. ret = wc_HpkeInit(ech->hpke, echConfig->kemId, ech->cipherSuite.kdfId,
  10101. ech->cipherSuite.aeadId, heap);
  10102. /* get the rawConfigLen */
  10103. if (ret == 0)
  10104. ret = GetEchConfig(echConfig, NULL, &rawConfigLen);
  10105. if (ret == LENGTH_ONLY_E)
  10106. ret = 0;
  10107. /* create info */
  10108. if (ret == 0) {
  10109. infoLen = TLS_INFO_CONST_STRING_SZ + 1 + rawConfigLen;
  10110. info = (byte*)XMALLOC(infoLen, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10111. if (info == NULL)
  10112. ret = MEMORY_E;
  10113. else {
  10114. XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING,
  10115. TLS_INFO_CONST_STRING_SZ + 1);
  10116. ret = GetEchConfig(echConfig, info +
  10117. TLS_INFO_CONST_STRING_SZ + 1, &rawConfigLen);
  10118. }
  10119. }
  10120. /* decrypt the ech payload */
  10121. if (ret == 0)
  10122. ret = wc_HpkeOpenBase(ech->hpke, echConfig->receiverPrivkey, ech->enc,
  10123. ech->encLen, info, infoLen, aad, aadLen, ech->outerClientPayload,
  10124. ech->innerClientHelloLen,
  10125. ech->innerClientHello + HANDSHAKE_HEADER_SZ);
  10126. if (ret != 0) {
  10127. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10128. ech->hpke = NULL;
  10129. }
  10130. if (info != NULL)
  10131. XFREE(info, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10132. return ret;
  10133. }
  10134. /* parse the ech extension, if internal update ech->state and return, if
  10135. * external attempt to extract the inner client_hello, return the status */
  10136. static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size,
  10137. byte msgType)
  10138. {
  10139. int ret = 0;
  10140. int i;
  10141. TLSX* echX;
  10142. WOLFSSL_ECH* ech;
  10143. WOLFSSL_EchConfig* echConfig;
  10144. byte* aadCopy;
  10145. byte* readBuf_p = (byte*)readBuf;
  10146. WOLFSSL_MSG("TLSX_ECH_Parse");
  10147. if (size == 0)
  10148. return BAD_FUNC_ARG;
  10149. if (msgType == encrypted_extensions) {
  10150. ret = wolfSSL_SetEchConfigs(ssl, readBuf, size);
  10151. if (ret == WOLFSSL_SUCCESS)
  10152. ret = 0;
  10153. }
  10154. else if (msgType == client_hello && ssl->ctx->echConfigs != NULL) {
  10155. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  10156. if (echX == NULL)
  10157. return BAD_FUNC_ARG;
  10158. ech = (WOLFSSL_ECH*)echX->data;
  10159. /* read the ech parameters before the payload */
  10160. ech->type = *readBuf_p;
  10161. readBuf_p++;
  10162. if (ech->type == ECH_TYPE_INNER) {
  10163. ech->state = ECH_PARSED_INTERNAL;
  10164. return 0;
  10165. }
  10166. /* technically the payload would only be 1 byte at this length */
  10167. if (size < 11 + ech->encLen)
  10168. return BAD_FUNC_ARG;
  10169. ato16(readBuf_p, &ech->cipherSuite.kdfId);
  10170. readBuf_p += 2;
  10171. ato16(readBuf_p, &ech->cipherSuite.aeadId);
  10172. readBuf_p += 2;
  10173. ech->configId = *readBuf_p;
  10174. readBuf_p++;
  10175. ato16(readBuf_p, &ech->encLen);
  10176. readBuf_p += 2;
  10177. if (ech->encLen > HPKE_Npk_MAX)
  10178. return BAD_FUNC_ARG;
  10179. XMEMCPY(ech->enc, readBuf_p, ech->encLen);
  10180. readBuf_p += ech->encLen;
  10181. ato16(readBuf_p, &ech->innerClientHelloLen);
  10182. ech->innerClientHelloLen -= AES_BLOCK_SIZE;
  10183. readBuf_p += 2;
  10184. ech->outerClientPayload = readBuf_p;
  10185. /* make a copy of the aad */
  10186. aadCopy = (byte*)XMALLOC(ech->aadLen, ssl->heap,
  10187. DYNAMIC_TYPE_TMP_BUFFER);
  10188. if (aadCopy == NULL)
  10189. return MEMORY_E;
  10190. XMEMCPY(aadCopy, ech->aad, ech->aadLen);
  10191. /* set the ech payload of the copy to zeros */
  10192. XMEMSET(aadCopy + (readBuf_p - ech->aad), 0,
  10193. ech->innerClientHelloLen + AES_BLOCK_SIZE);
  10194. /* allocate the inner payload buffer */
  10195. ech->innerClientHello =
  10196. (byte*)XMALLOC(ech->innerClientHelloLen + HANDSHAKE_HEADER_SZ,
  10197. ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10198. if (ech->innerClientHello == NULL) {
  10199. XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10200. return MEMORY_E;
  10201. }
  10202. /* first check if the config id matches */
  10203. echConfig = ssl->ctx->echConfigs;
  10204. while (echConfig != NULL) {
  10205. /* decrypt with this config */
  10206. if (echConfig->configId == ech->configId) {
  10207. ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen,
  10208. ssl->heap);
  10209. break;
  10210. }
  10211. echConfig = echConfig->next;
  10212. }
  10213. /* try to decrypt with all configs */
  10214. if (echConfig == NULL || ret != 0) {
  10215. echConfig = ssl->ctx->echConfigs;
  10216. while (echConfig != NULL) {
  10217. ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen,
  10218. ssl->heap);
  10219. if (ret== 0)
  10220. break;
  10221. echConfig = echConfig->next;
  10222. }
  10223. }
  10224. /* if we failed to extract */
  10225. if (ret != 0) {
  10226. XFREE(ech->innerClientHello, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10227. ech->innerClientHello = NULL;
  10228. ech->state = ECH_WRITE_RETRY_CONFIGS;
  10229. }
  10230. else {
  10231. i = 0;
  10232. /* decrement until before the padding */
  10233. while (ech->innerClientHello[ech->innerClientHelloLen +
  10234. HANDSHAKE_HEADER_SZ - i - 1] != ECH_TYPE_INNER) {
  10235. i++;
  10236. }
  10237. /* subtract the length of the padding from the length */
  10238. ech->innerClientHelloLen -= i;
  10239. }
  10240. XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10241. return 0;
  10242. }
  10243. return ret;
  10244. }
  10245. /* free the ech struct and the dynamic buffer it uses */
  10246. static void TLSX_ECH_Free(WOLFSSL_ECH* ech, void* heap)
  10247. {
  10248. if (ech->innerClientHello != NULL)
  10249. XFREE(ech->innerClientHello, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10250. if (ech->ephemeralKey != NULL)
  10251. wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, ech->ephemeralKey,
  10252. ech->hpke->heap);
  10253. if (ech->hpke != NULL)
  10254. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10255. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10256. (void)heap;
  10257. }
  10258. /* encrypt the client hello and store it in ech->outerClientPayload, return
  10259. * status */
  10260. int TLSX_FinalizeEch(WOLFSSL_ECH* ech, byte* aad, word32 aadLen)
  10261. {
  10262. int ret;
  10263. void* receiverPubkey = NULL;
  10264. byte* info;
  10265. int infoLen;
  10266. byte* aadCopy;
  10267. /* import the server public key */
  10268. ret = wc_HpkeDeserializePublicKey(ech->hpke, &receiverPubkey,
  10269. ech->echConfig->receiverPubkey, ech->encLen);
  10270. if (ret == 0) {
  10271. /* create info */
  10272. infoLen = TLS_INFO_CONST_STRING_SZ + 1 + ech->echConfig->rawLen;
  10273. info = (byte*)XMALLOC(infoLen, ech->hpke->heap,
  10274. DYNAMIC_TYPE_TMP_BUFFER);
  10275. if (info == NULL)
  10276. ret = MEMORY_E;
  10277. if (ret == 0) {
  10278. /* puts the null byte in for me */
  10279. XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING, TLS_INFO_CONST_STRING_SZ
  10280. + 1);
  10281. XMEMCPY(info + TLS_INFO_CONST_STRING_SZ + 1, ech->echConfig->raw,
  10282. ech->echConfig->rawLen);
  10283. /* make a copy of the aad since we overwrite it */
  10284. aadCopy = (byte*)XMALLOC(aadLen, ech->hpke->heap,
  10285. DYNAMIC_TYPE_TMP_BUFFER);
  10286. if (aadCopy == NULL) {
  10287. XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10288. ret = MEMORY_E;
  10289. }
  10290. }
  10291. if (ret == 0) {
  10292. XMEMCPY(aadCopy, aad, aadLen);
  10293. /* seal the payload */
  10294. ret = wc_HpkeSealBase(ech->hpke, ech->ephemeralKey, receiverPubkey,
  10295. info, infoLen, aadCopy, aadLen, ech->innerClientHello,
  10296. ech->innerClientHelloLen - ech->hpke->Nt,
  10297. ech->outerClientPayload);
  10298. XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10299. XFREE(aadCopy, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10300. }
  10301. }
  10302. if (receiverPubkey != NULL)
  10303. wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, receiverPubkey,
  10304. ech->hpke->heap);
  10305. return ret;
  10306. }
  10307. #define GREASE_ECH_USE TLSX_GreaseECH_Use
  10308. #define ECH_USE TLSX_ECH_Use
  10309. #define SERVER_ECH_USE TLSX_ServerECH_Use
  10310. #define ECH_WRITE TLSX_ECH_Write
  10311. #define ECH_GET_SIZE TLSX_ECH_GetSize
  10312. #define ECH_PARSE TLSX_ECH_Parse
  10313. #define ECH_FREE TLSX_ECH_Free
  10314. #endif
  10315. /** Releases all extensions in the provided list. */
  10316. void TLSX_FreeAll(TLSX* list, void* heap)
  10317. {
  10318. TLSX* extension;
  10319. while ((extension = list)) {
  10320. list = extension->next;
  10321. switch (extension->type) {
  10322. #if defined(HAVE_RPK)
  10323. case TLSX_CLIENT_CERTIFICATE_TYPE:
  10324. WOLFSSL_MSG("Client Certificate Type extension free");
  10325. /* nothing to do */
  10326. break;
  10327. case TLSX_SERVER_CERTIFICATE_TYPE:
  10328. WOLFSSL_MSG("Server Certificate Type extension free");
  10329. /* nothing to do */
  10330. break;
  10331. #endif
  10332. #ifdef HAVE_SNI
  10333. case TLSX_SERVER_NAME:
  10334. WOLFSSL_MSG("SNI extension free");
  10335. SNI_FREE_ALL((SNI*)extension->data, heap);
  10336. break;
  10337. #endif
  10338. case TLSX_TRUSTED_CA_KEYS:
  10339. WOLFSSL_MSG("Trusted CA Indication extension free");
  10340. TCA_FREE_ALL((TCA*)extension->data, heap);
  10341. break;
  10342. case TLSX_MAX_FRAGMENT_LENGTH:
  10343. WOLFSSL_MSG("Max Fragment Length extension free");
  10344. MFL_FREE_ALL(extension->data, heap);
  10345. break;
  10346. case TLSX_EXTENDED_MASTER_SECRET:
  10347. WOLFSSL_MSG("Extended Master Secret free");
  10348. /* Nothing to do. */
  10349. break;
  10350. case TLSX_TRUNCATED_HMAC:
  10351. WOLFSSL_MSG("Truncated HMAC extension free");
  10352. /* Nothing to do. */
  10353. break;
  10354. case TLSX_SUPPORTED_GROUPS:
  10355. WOLFSSL_MSG("Supported Groups extension free");
  10356. EC_FREE_ALL((SupportedCurve*)extension->data, heap);
  10357. break;
  10358. case TLSX_EC_POINT_FORMATS:
  10359. WOLFSSL_MSG("Point Formats extension free");
  10360. PF_FREE_ALL((PointFormat*)extension->data, heap);
  10361. break;
  10362. case TLSX_STATUS_REQUEST:
  10363. WOLFSSL_MSG("Certificate Status Request extension free");
  10364. CSR_FREE_ALL((CertificateStatusRequest*)extension->data, heap);
  10365. break;
  10366. case TLSX_STATUS_REQUEST_V2:
  10367. WOLFSSL_MSG("Certificate Status Request v2 extension free");
  10368. CSR2_FREE_ALL((CertificateStatusRequestItemV2*)extension->data,
  10369. heap);
  10370. break;
  10371. case TLSX_RENEGOTIATION_INFO:
  10372. WOLFSSL_MSG("Secure Renegotiation extension free");
  10373. SCR_FREE_ALL(extension->data, heap);
  10374. break;
  10375. case TLSX_SESSION_TICKET:
  10376. WOLFSSL_MSG("Session Ticket extension free");
  10377. WOLF_STK_FREE(extension->data, heap);
  10378. break;
  10379. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10380. WOLFSSL_MSG("ALPN extension free");
  10381. ALPN_FREE_ALL((ALPN*)extension->data, heap);
  10382. break;
  10383. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10384. case TLSX_SIGNATURE_ALGORITHMS:
  10385. WOLFSSL_MSG("Signature Algorithms extension to free");
  10386. SA_FREE_ALL((SignatureAlgorithms*)extension->data, heap);
  10387. break;
  10388. #endif
  10389. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10390. case TLSX_ENCRYPT_THEN_MAC:
  10391. WOLFSSL_MSG("Encrypt-Then-Mac extension free");
  10392. break;
  10393. #endif
  10394. #ifdef WOLFSSL_TLS13
  10395. case TLSX_SUPPORTED_VERSIONS:
  10396. WOLFSSL_MSG("Supported Versions extension free");
  10397. break;
  10398. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10399. case TLSX_COOKIE:
  10400. WOLFSSL_MSG("Cookie extension free");
  10401. CKE_FREE_ALL((Cookie*)extension->data, heap);
  10402. break;
  10403. #endif
  10404. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10405. case TLSX_PRE_SHARED_KEY:
  10406. WOLFSSL_MSG("Pre-Shared Key extension free");
  10407. PSK_FREE_ALL((PreSharedKey*)extension->data, heap);
  10408. break;
  10409. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10410. WOLFSSL_MSG("PSK Key Exchange Modes extension free");
  10411. break;
  10412. #endif
  10413. #ifdef WOLFSSL_EARLY_DATA
  10414. case TLSX_EARLY_DATA:
  10415. WOLFSSL_MSG("Early Data extension free");
  10416. break;
  10417. #endif
  10418. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10419. case TLSX_POST_HANDSHAKE_AUTH:
  10420. WOLFSSL_MSG("Post-Handshake Authentication extension free");
  10421. break;
  10422. #endif
  10423. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10424. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10425. WOLFSSL_MSG("Signature Algorithms extension free");
  10426. break;
  10427. #endif
  10428. case TLSX_KEY_SHARE:
  10429. WOLFSSL_MSG("Key Share extension free");
  10430. KS_FREE_ALL((KeyShareEntry*)extension->data, heap);
  10431. break;
  10432. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10433. case TLSX_CERTIFICATE_AUTHORITIES:
  10434. WOLFSSL_MSG("Certificate Authorities extension free");
  10435. break;
  10436. #endif
  10437. #endif
  10438. #ifdef WOLFSSL_SRTP
  10439. case TLSX_USE_SRTP:
  10440. WOLFSSL_MSG("SRTP extension free");
  10441. SRTP_FREE((TlsxSrtp*)extension->data, heap);
  10442. break;
  10443. #endif
  10444. #ifdef WOLFSSL_QUIC
  10445. case TLSX_KEY_QUIC_TP_PARAMS:
  10446. FALL_THROUGH;
  10447. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10448. WOLFSSL_MSG("QUIC transport parameter free");
  10449. QTP_FREE((QuicTransportParam*)extension->data, heap);
  10450. break;
  10451. #endif
  10452. #ifdef WOLFSSL_DTLS_CID
  10453. case TLSX_CONNECTION_ID:
  10454. WOLFSSL_MSG("Connection ID extension free");
  10455. CID_FREE((byte*)extension->data, heap);
  10456. break;
  10457. #endif /* WOLFSSL_DTLS_CID */
  10458. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10459. case TLSX_ECH:
  10460. WOLFSSL_MSG("ECH extension free");
  10461. ECH_FREE((WOLFSSL_ECH*)extension->data, heap);
  10462. break;
  10463. #endif
  10464. #ifdef WOLFSSL_DUAL_ALG_CERTS
  10465. case TLSX_CKS:
  10466. WOLFSSL_MSG("CKS extension free");
  10467. /* nothing to do */
  10468. break;
  10469. #endif
  10470. default:
  10471. break;
  10472. }
  10473. XFREE(extension, heap, DYNAMIC_TYPE_TLSX);
  10474. }
  10475. (void)heap;
  10476. }
  10477. /** Checks if the tls extensions are supported based on the protocol version. */
  10478. int TLSX_SupportExtensions(WOLFSSL* ssl) {
  10479. return ssl && (IsTLS(ssl) || ssl->version.major == DTLS_MAJOR);
  10480. }
  10481. /** Tells the buffered size of the extensions in a list. */
  10482. static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType,
  10483. word16* pLength)
  10484. {
  10485. int ret = 0;
  10486. TLSX* extension;
  10487. word16 length = 0;
  10488. byte isRequest = (msgType == client_hello ||
  10489. msgType == certificate_request);
  10490. while ((extension = list)) {
  10491. list = extension->next;
  10492. /* only extensions marked as response are sent back to the client. */
  10493. if (!isRequest && !extension->resp)
  10494. continue; /* skip! */
  10495. /* ssl level extensions are expected to override ctx level ones. */
  10496. if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type)))
  10497. continue; /* skip! */
  10498. /* extension type + extension data length. */
  10499. length += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN;
  10500. switch (extension->type) {
  10501. #ifdef WOLFSSL_DUAL_ALG_CERTS
  10502. case TLSX_CKS:
  10503. length += ((WOLFSSL*)extension->data)->sigSpecSz ;
  10504. break;
  10505. #endif
  10506. #ifdef HAVE_SNI
  10507. case TLSX_SERVER_NAME:
  10508. /* SNI only sends the name on the request. */
  10509. if (isRequest)
  10510. length += SNI_GET_SIZE((SNI*)extension->data);
  10511. break;
  10512. #endif
  10513. case TLSX_TRUSTED_CA_KEYS:
  10514. /* TCA only sends the list on the request. */
  10515. if (isRequest)
  10516. length += TCA_GET_SIZE((TCA*)extension->data);
  10517. break;
  10518. case TLSX_MAX_FRAGMENT_LENGTH:
  10519. length += MFL_GET_SIZE(extension->data);
  10520. break;
  10521. case TLSX_EXTENDED_MASTER_SECRET:
  10522. case TLSX_TRUNCATED_HMAC:
  10523. /* always empty. */
  10524. break;
  10525. case TLSX_SUPPORTED_GROUPS:
  10526. length += EC_GET_SIZE((SupportedCurve*)extension->data);
  10527. break;
  10528. case TLSX_EC_POINT_FORMATS:
  10529. length += PF_GET_SIZE((PointFormat*)extension->data);
  10530. break;
  10531. case TLSX_STATUS_REQUEST:
  10532. length += CSR_GET_SIZE(
  10533. (CertificateStatusRequest*)extension->data, isRequest);
  10534. break;
  10535. case TLSX_STATUS_REQUEST_V2:
  10536. length += CSR2_GET_SIZE(
  10537. (CertificateStatusRequestItemV2*)extension->data,
  10538. isRequest);
  10539. break;
  10540. case TLSX_RENEGOTIATION_INFO:
  10541. length += SCR_GET_SIZE((SecureRenegotiation*)extension->data,
  10542. isRequest);
  10543. break;
  10544. case TLSX_SESSION_TICKET:
  10545. length += WOLF_STK_GET_SIZE((SessionTicket*)extension->data,
  10546. isRequest);
  10547. break;
  10548. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10549. length += ALPN_GET_SIZE((ALPN*)extension->data);
  10550. break;
  10551. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10552. case TLSX_SIGNATURE_ALGORITHMS:
  10553. length += SA_GET_SIZE(extension->data);
  10554. break;
  10555. #endif
  10556. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10557. case TLSX_ENCRYPT_THEN_MAC:
  10558. ret = ETM_GET_SIZE(msgType, &length);
  10559. break;
  10560. #endif /* HAVE_ENCRYPT_THEN_MAC */
  10561. #ifdef WOLFSSL_TLS13
  10562. case TLSX_SUPPORTED_VERSIONS:
  10563. ret = SV_GET_SIZE(extension->data, msgType, &length);
  10564. break;
  10565. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10566. case TLSX_COOKIE:
  10567. ret = CKE_GET_SIZE((Cookie*)extension->data, msgType, &length);
  10568. break;
  10569. #endif
  10570. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10571. case TLSX_PRE_SHARED_KEY:
  10572. ret = PSK_GET_SIZE((PreSharedKey*)extension->data, msgType,
  10573. &length);
  10574. break;
  10575. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10576. ret = PKM_GET_SIZE((byte)extension->val, msgType, &length);
  10577. break;
  10578. #endif
  10579. #ifdef WOLFSSL_EARLY_DATA
  10580. case TLSX_EARLY_DATA:
  10581. ret = EDI_GET_SIZE(msgType, &length);
  10582. break;
  10583. #endif
  10584. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10585. case TLSX_POST_HANDSHAKE_AUTH:
  10586. ret = PHA_GET_SIZE(msgType, &length);
  10587. break;
  10588. #endif
  10589. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10590. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10591. length += SAC_GET_SIZE(extension->data);
  10592. break;
  10593. #endif
  10594. case TLSX_KEY_SHARE:
  10595. length += KS_GET_SIZE((KeyShareEntry*)extension->data, msgType);
  10596. break;
  10597. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10598. case TLSX_CERTIFICATE_AUTHORITIES:
  10599. length += CAN_GET_SIZE(extension->data);
  10600. break;
  10601. #endif
  10602. #endif
  10603. #ifdef WOLFSSL_SRTP
  10604. case TLSX_USE_SRTP:
  10605. length += SRTP_GET_SIZE((TlsxSrtp*)extension->data);
  10606. break;
  10607. #endif
  10608. #ifdef HAVE_RPK
  10609. case TLSX_CLIENT_CERTIFICATE_TYPE:
  10610. length += CCT_GET_SIZE((WOLFSSL*)extension->data, msgType);
  10611. break;
  10612. case TLSX_SERVER_CERTIFICATE_TYPE:
  10613. length += SCT_GET_SIZE((WOLFSSL*)extension->data, msgType);
  10614. break;
  10615. #endif /* HAVE_RPK */
  10616. #ifdef WOLFSSL_QUIC
  10617. case TLSX_KEY_QUIC_TP_PARAMS:
  10618. FALL_THROUGH; /* followed by */
  10619. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10620. length += QTP_GET_SIZE(extension);
  10621. break;
  10622. #endif
  10623. #ifdef WOLFSSL_DTLS_CID
  10624. case TLSX_CONNECTION_ID:
  10625. length += CID_GET_SIZE((byte*)extension->data);
  10626. break;
  10627. #endif /* WOLFSSL_DTLS_CID */
  10628. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10629. case TLSX_ECH:
  10630. length += ECH_GET_SIZE((WOLFSSL_ECH*)extension->data);
  10631. break;
  10632. #endif
  10633. default:
  10634. break;
  10635. }
  10636. /* marks the extension as processed so ctx level */
  10637. /* extensions don't overlap with ssl level ones. */
  10638. TURN_ON(semaphore, TLSX_ToSemaphore(extension->type));
  10639. }
  10640. *pLength += length;
  10641. return ret;
  10642. }
  10643. /** Writes the extensions of a list in a buffer. */
  10644. static int TLSX_Write(TLSX* list, byte* output, byte* semaphore,
  10645. byte msgType, word16* pOffset)
  10646. {
  10647. int ret = 0;
  10648. TLSX* extension;
  10649. word16 offset = 0;
  10650. word16 length_offset = 0;
  10651. byte isRequest = (msgType == client_hello ||
  10652. msgType == certificate_request);
  10653. while ((extension = list)) {
  10654. list = extension->next;
  10655. /* only extensions marked as response are written in a response. */
  10656. if (!isRequest && !extension->resp)
  10657. continue; /* skip! */
  10658. /* ssl level extensions are expected to override ctx level ones. */
  10659. if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type)))
  10660. continue; /* skip! */
  10661. /* writes extension type. */
  10662. c16toa(extension->type, output + offset);
  10663. offset += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN;
  10664. length_offset = offset;
  10665. /* extension data should be written internally. */
  10666. switch (extension->type) {
  10667. #ifdef WOLFSSL_DUAL_ALG_CERTS
  10668. case TLSX_CKS:
  10669. WOLFSSL_MSG("CKS extension to write");
  10670. offset += CKS_WRITE(((WOLFSSL*)extension->data),
  10671. output + offset);
  10672. break;
  10673. #endif
  10674. #ifdef HAVE_SNI
  10675. case TLSX_SERVER_NAME:
  10676. if (isRequest) {
  10677. WOLFSSL_MSG("SNI extension to write");
  10678. offset += SNI_WRITE((SNI*)extension->data, output + offset);
  10679. }
  10680. break;
  10681. #endif
  10682. case TLSX_TRUSTED_CA_KEYS:
  10683. WOLFSSL_MSG("Trusted CA Indication extension to write");
  10684. if (isRequest) {
  10685. offset += TCA_WRITE((TCA*)extension->data, output + offset);
  10686. }
  10687. break;
  10688. case TLSX_MAX_FRAGMENT_LENGTH:
  10689. WOLFSSL_MSG("Max Fragment Length extension to write");
  10690. offset += MFL_WRITE((byte*)extension->data, output + offset);
  10691. break;
  10692. case TLSX_EXTENDED_MASTER_SECRET:
  10693. WOLFSSL_MSG("Extended Master Secret");
  10694. /* always empty. */
  10695. break;
  10696. case TLSX_TRUNCATED_HMAC:
  10697. WOLFSSL_MSG("Truncated HMAC extension to write");
  10698. /* always empty. */
  10699. break;
  10700. case TLSX_SUPPORTED_GROUPS:
  10701. WOLFSSL_MSG("Supported Groups extension to write");
  10702. offset += EC_WRITE((SupportedCurve*)extension->data,
  10703. output + offset);
  10704. break;
  10705. case TLSX_EC_POINT_FORMATS:
  10706. WOLFSSL_MSG("Point Formats extension to write");
  10707. offset += PF_WRITE((PointFormat*)extension->data,
  10708. output + offset);
  10709. break;
  10710. case TLSX_STATUS_REQUEST:
  10711. WOLFSSL_MSG("Certificate Status Request extension to write");
  10712. ret = CSR_WRITE((CertificateStatusRequest*)extension->data,
  10713. output + offset, isRequest);
  10714. if (ret > 0) {
  10715. offset += (word16)ret;
  10716. ret = 0;
  10717. }
  10718. break;
  10719. case TLSX_STATUS_REQUEST_V2:
  10720. WOLFSSL_MSG("Certificate Status Request v2 extension to write");
  10721. ret = CSR2_WRITE(
  10722. (CertificateStatusRequestItemV2*)extension->data,
  10723. output + offset, isRequest);
  10724. if (ret > 0) {
  10725. offset += (word16)ret;
  10726. ret = 0;
  10727. }
  10728. break;
  10729. case TLSX_RENEGOTIATION_INFO:
  10730. WOLFSSL_MSG("Secure Renegotiation extension to write");
  10731. offset += SCR_WRITE((SecureRenegotiation*)extension->data,
  10732. output + offset, isRequest);
  10733. break;
  10734. case TLSX_SESSION_TICKET:
  10735. WOLFSSL_MSG("Session Ticket extension to write");
  10736. offset += WOLF_STK_WRITE((SessionTicket*)extension->data,
  10737. output + offset, isRequest);
  10738. break;
  10739. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10740. WOLFSSL_MSG("ALPN extension to write");
  10741. offset += ALPN_WRITE((ALPN*)extension->data, output + offset);
  10742. break;
  10743. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10744. case TLSX_SIGNATURE_ALGORITHMS:
  10745. WOLFSSL_MSG("Signature Algorithms extension to write");
  10746. offset += SA_WRITE(extension->data, output + offset);
  10747. break;
  10748. #endif
  10749. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10750. case TLSX_ENCRYPT_THEN_MAC:
  10751. WOLFSSL_MSG("Encrypt-Then-Mac extension to write");
  10752. ret = ETM_WRITE(extension->data, output, msgType, &offset);
  10753. break;
  10754. #endif /* HAVE_ENCRYPT_THEN_MAC */
  10755. #ifdef WOLFSSL_TLS13
  10756. case TLSX_SUPPORTED_VERSIONS:
  10757. WOLFSSL_MSG("Supported Versions extension to write");
  10758. ret = SV_WRITE(extension->data, output + offset, msgType, &offset);
  10759. break;
  10760. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10761. case TLSX_COOKIE:
  10762. WOLFSSL_MSG("Cookie extension to write");
  10763. ret = CKE_WRITE((Cookie*)extension->data, output + offset,
  10764. msgType, &offset);
  10765. break;
  10766. #endif
  10767. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10768. case TLSX_PRE_SHARED_KEY:
  10769. WOLFSSL_MSG("Pre-Shared Key extension to write");
  10770. ret = PSK_WRITE((PreSharedKey*)extension->data, output + offset,
  10771. msgType, &offset);
  10772. break;
  10773. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10774. WOLFSSL_MSG("PSK Key Exchange Modes extension to write");
  10775. ret = PKM_WRITE((byte)extension->val, output + offset, msgType,
  10776. &offset);
  10777. break;
  10778. #endif
  10779. #ifdef WOLFSSL_EARLY_DATA
  10780. case TLSX_EARLY_DATA:
  10781. WOLFSSL_MSG("Early Data extension to write");
  10782. ret = EDI_WRITE(extension->val, output + offset, msgType,
  10783. &offset);
  10784. break;
  10785. #endif
  10786. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10787. case TLSX_POST_HANDSHAKE_AUTH:
  10788. WOLFSSL_MSG("Post-Handshake Authentication extension to write");
  10789. ret = PHA_WRITE(output + offset, msgType, &offset);
  10790. break;
  10791. #endif
  10792. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10793. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10794. WOLFSSL_MSG("Signature Algorithms extension to write");
  10795. offset += SAC_WRITE(extension->data, output + offset);
  10796. break;
  10797. #endif
  10798. case TLSX_KEY_SHARE:
  10799. WOLFSSL_MSG("Key Share extension to write");
  10800. offset += KS_WRITE((KeyShareEntry*)extension->data,
  10801. output + offset, msgType);
  10802. break;
  10803. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10804. case TLSX_CERTIFICATE_AUTHORITIES:
  10805. WOLFSSL_MSG("Certificate Authorities extension to write");
  10806. offset += CAN_WRITE(extension->data, output + offset);
  10807. break;
  10808. #endif
  10809. #endif
  10810. #ifdef WOLFSSL_SRTP
  10811. case TLSX_USE_SRTP:
  10812. WOLFSSL_MSG("SRTP extension to write");
  10813. offset += SRTP_WRITE((TlsxSrtp*)extension->data, output+offset);
  10814. break;
  10815. #endif
  10816. #ifdef HAVE_RPK
  10817. case TLSX_CLIENT_CERTIFICATE_TYPE:
  10818. WOLFSSL_MSG("Client Certificate Type extension to write");
  10819. offset += CCT_WRITE(extension->data, output + offset, msgType);
  10820. break;
  10821. case TLSX_SERVER_CERTIFICATE_TYPE:
  10822. WOLFSSL_MSG("Server Certificate Type extension to write");
  10823. offset += SCT_WRITE(extension->data, output + offset, msgType);
  10824. break;
  10825. #endif /* HAVE_RPK */
  10826. #ifdef WOLFSSL_QUIC
  10827. case TLSX_KEY_QUIC_TP_PARAMS:
  10828. FALL_THROUGH;
  10829. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10830. WOLFSSL_MSG("QUIC transport parameter to write");
  10831. offset += QTP_WRITE((QuicTransportParam*)extension->data,
  10832. output + offset);
  10833. break;
  10834. #endif
  10835. #ifdef WOLFSSL_DTLS_CID
  10836. case TLSX_CONNECTION_ID:
  10837. WOLFSSL_MSG("Connection ID extension to write");
  10838. offset += CID_WRITE((byte*)extension->data, output+offset);
  10839. break;
  10840. #endif /* WOLFSSL_DTLS_CID */
  10841. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10842. case TLSX_ECH:
  10843. WOLFSSL_MSG("ECH extension to write");
  10844. ret = ECH_WRITE((WOLFSSL_ECH*)extension->data,
  10845. output + offset, &offset);
  10846. break;
  10847. #endif
  10848. default:
  10849. break;
  10850. }
  10851. /* writes extension data length. */
  10852. c16toa(offset - length_offset, output + length_offset - OPAQUE16_LEN);
  10853. /* marks the extension as processed so ctx level */
  10854. /* extensions don't overlap with ssl level ones. */
  10855. TURN_ON(semaphore, TLSX_ToSemaphore(extension->type));
  10856. /* if we encountered an error propagate it */
  10857. if (ret != 0)
  10858. break;
  10859. }
  10860. *pOffset += offset;
  10861. return ret;
  10862. }
  10863. #ifdef HAVE_SUPPORTED_CURVES
  10864. /* Populates the default supported groups / curves */
  10865. static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions)
  10866. {
  10867. int ret = WOLFSSL_SUCCESS;
  10868. #ifdef WOLFSSL_TLS13
  10869. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10870. if (ssl->options.resuming && ssl->session->namedGroup != 0) {
  10871. return TLSX_UseSupportedCurve(extensions, ssl->session->namedGroup,
  10872. ssl->heap);
  10873. }
  10874. #endif
  10875. if (ssl->numGroups != 0) {
  10876. int i;
  10877. for (i = 0; i < ssl->numGroups; i++) {
  10878. ret = TLSX_UseSupportedCurve(extensions, ssl->group[i], ssl->heap);
  10879. if (ret != WOLFSSL_SUCCESS)
  10880. return ret;
  10881. }
  10882. return WOLFSSL_SUCCESS;
  10883. }
  10884. #endif /* WOLFSSL_TLS13 */
  10885. #if defined(HAVE_ECC)
  10886. /* list in order by strength, since not all servers choose by strength */
  10887. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  10888. #ifndef NO_ECC_SECP
  10889. ret = TLSX_UseSupportedCurve(extensions,
  10890. WOLFSSL_ECC_SECP521R1, ssl->heap);
  10891. if (ret != WOLFSSL_SUCCESS) return ret;
  10892. #endif
  10893. #endif
  10894. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  10895. #ifdef HAVE_ECC_BRAINPOOL
  10896. ret = TLSX_UseSupportedCurve(extensions,
  10897. WOLFSSL_ECC_BRAINPOOLP512R1, ssl->heap);
  10898. if (ret != WOLFSSL_SUCCESS) return ret;
  10899. #endif
  10900. #endif
  10901. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  10902. #ifndef NO_ECC_SECP
  10903. ret = TLSX_UseSupportedCurve(extensions,
  10904. WOLFSSL_ECC_SECP384R1, ssl->heap);
  10905. if (ret != WOLFSSL_SUCCESS) return ret;
  10906. #endif
  10907. #ifdef HAVE_ECC_BRAINPOOL
  10908. ret = TLSX_UseSupportedCurve(extensions,
  10909. WOLFSSL_ECC_BRAINPOOLP384R1, ssl->heap);
  10910. if (ret != WOLFSSL_SUCCESS) return ret;
  10911. #endif
  10912. #endif
  10913. #endif /* HAVE_ECC */
  10914. #ifndef HAVE_FIPS
  10915. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  10916. ret = TLSX_UseSupportedCurve(extensions,
  10917. WOLFSSL_ECC_X448, ssl->heap);
  10918. if (ret != WOLFSSL_SUCCESS) return ret;
  10919. #endif
  10920. #endif /* HAVE_FIPS */
  10921. #if defined(HAVE_ECC) && defined(HAVE_SUPPORTED_CURVES)
  10922. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  10923. #ifndef NO_ECC_SECP
  10924. ret = TLSX_UseSupportedCurve(extensions,
  10925. WOLFSSL_ECC_SECP256R1, ssl->heap);
  10926. if (ret != WOLFSSL_SUCCESS) return ret;
  10927. #endif
  10928. #ifdef HAVE_ECC_KOBLITZ
  10929. ret = TLSX_UseSupportedCurve(extensions,
  10930. WOLFSSL_ECC_SECP256K1, ssl->heap);
  10931. if (ret != WOLFSSL_SUCCESS) return ret;
  10932. #endif
  10933. #ifdef HAVE_ECC_BRAINPOOL
  10934. ret = TLSX_UseSupportedCurve(extensions,
  10935. WOLFSSL_ECC_BRAINPOOLP256R1, ssl->heap);
  10936. if (ret != WOLFSSL_SUCCESS) return ret;
  10937. #endif
  10938. #ifdef WOLFSSL_SM2
  10939. ret = TLSX_UseSupportedCurve(extensions,
  10940. WOLFSSL_ECC_SM2P256V1, ssl->heap);
  10941. if (ret != WOLFSSL_SUCCESS) return ret;
  10942. #endif
  10943. #endif
  10944. #endif /* HAVE_ECC */
  10945. #ifndef HAVE_FIPS
  10946. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  10947. ret = TLSX_UseSupportedCurve(extensions,
  10948. WOLFSSL_ECC_X25519, ssl->heap);
  10949. if (ret != WOLFSSL_SUCCESS) return ret;
  10950. #endif
  10951. #endif /* HAVE_FIPS */
  10952. #if defined(HAVE_ECC) && defined(HAVE_SUPPORTED_CURVES)
  10953. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  10954. #ifndef NO_ECC_SECP
  10955. ret = TLSX_UseSupportedCurve(extensions,
  10956. WOLFSSL_ECC_SECP224R1, ssl->heap);
  10957. if (ret != WOLFSSL_SUCCESS) return ret;
  10958. #endif
  10959. #ifdef HAVE_ECC_KOBLITZ
  10960. ret = TLSX_UseSupportedCurve(extensions,
  10961. WOLFSSL_ECC_SECP224K1, ssl->heap);
  10962. if (ret != WOLFSSL_SUCCESS) return ret;
  10963. #endif
  10964. #endif
  10965. #ifndef HAVE_FIPS
  10966. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  10967. #ifndef NO_ECC_SECP
  10968. ret = TLSX_UseSupportedCurve(extensions,
  10969. WOLFSSL_ECC_SECP192R1, ssl->heap);
  10970. if (ret != WOLFSSL_SUCCESS) return ret;
  10971. #endif
  10972. #ifdef HAVE_ECC_KOBLITZ
  10973. ret = TLSX_UseSupportedCurve(extensions,
  10974. WOLFSSL_ECC_SECP192K1, ssl->heap);
  10975. if (ret != WOLFSSL_SUCCESS) return ret;
  10976. #endif
  10977. #endif
  10978. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  10979. #ifndef NO_ECC_SECP
  10980. ret = TLSX_UseSupportedCurve(extensions,
  10981. WOLFSSL_ECC_SECP160R1, ssl->heap);
  10982. if (ret != WOLFSSL_SUCCESS) return ret;
  10983. #endif
  10984. #ifdef HAVE_ECC_SECPR2
  10985. ret = TLSX_UseSupportedCurve(extensions,
  10986. WOLFSSL_ECC_SECP160R2, ssl->heap);
  10987. if (ret != WOLFSSL_SUCCESS) return ret;
  10988. #endif
  10989. #ifdef HAVE_ECC_KOBLITZ
  10990. ret = TLSX_UseSupportedCurve(extensions,
  10991. WOLFSSL_ECC_SECP160K1, ssl->heap);
  10992. if (ret != WOLFSSL_SUCCESS) return ret;
  10993. #endif
  10994. #endif
  10995. #endif /* HAVE_FIPS */
  10996. #endif /* HAVE_ECC */
  10997. #ifndef NO_DH
  10998. /* Add FFDHE supported groups. */
  10999. #ifdef HAVE_FFDHE_8192
  11000. if (8192/8 >= ssl->options.minDhKeySz &&
  11001. 8192/8 <= ssl->options.maxDhKeySz) {
  11002. ret = TLSX_UseSupportedCurve(extensions,
  11003. WOLFSSL_FFDHE_8192, ssl->heap);
  11004. if (ret != WOLFSSL_SUCCESS)
  11005. return ret;
  11006. }
  11007. #endif
  11008. #ifdef HAVE_FFDHE_6144
  11009. if (6144/8 >= ssl->options.minDhKeySz &&
  11010. 6144/8 <= ssl->options.maxDhKeySz) {
  11011. ret = TLSX_UseSupportedCurve(extensions,
  11012. WOLFSSL_FFDHE_6144, ssl->heap);
  11013. if (ret != WOLFSSL_SUCCESS)
  11014. return ret;
  11015. }
  11016. #endif
  11017. #ifdef HAVE_FFDHE_4096
  11018. if (4096/8 >= ssl->options.minDhKeySz &&
  11019. 4096/8 <= ssl->options.maxDhKeySz) {
  11020. ret = TLSX_UseSupportedCurve(extensions,
  11021. WOLFSSL_FFDHE_4096, ssl->heap);
  11022. if (ret != WOLFSSL_SUCCESS)
  11023. return ret;
  11024. }
  11025. #endif
  11026. #ifdef HAVE_FFDHE_3072
  11027. if (3072/8 >= ssl->options.minDhKeySz &&
  11028. 3072/8 <= ssl->options.maxDhKeySz) {
  11029. ret = TLSX_UseSupportedCurve(extensions,
  11030. WOLFSSL_FFDHE_3072, ssl->heap);
  11031. if (ret != WOLFSSL_SUCCESS)
  11032. return ret;
  11033. }
  11034. #endif
  11035. #ifdef HAVE_FFDHE_2048
  11036. if (2048/8 >= ssl->options.minDhKeySz &&
  11037. 2048/8 <= ssl->options.maxDhKeySz) {
  11038. ret = TLSX_UseSupportedCurve(extensions,
  11039. WOLFSSL_FFDHE_2048, ssl->heap);
  11040. if (ret != WOLFSSL_SUCCESS)
  11041. return ret;
  11042. }
  11043. #endif
  11044. #endif
  11045. #ifdef HAVE_PQC
  11046. #ifdef WOLFSSL_WC_KYBER
  11047. #ifdef WOLFSSL_KYBER512
  11048. if (ret == WOLFSSL_SUCCESS)
  11049. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1,
  11050. ssl->heap);
  11051. #endif
  11052. #ifdef WOLFSSL_KYBER768
  11053. if (ret == WOLFSSL_SUCCESS)
  11054. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3,
  11055. ssl->heap);
  11056. #endif
  11057. #ifdef WOLFSSL_KYBER768
  11058. if (ret == WOLFSSL_SUCCESS)
  11059. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5,
  11060. ssl->heap);
  11061. #endif
  11062. #elif defined(HAVE_LIBOQS)
  11063. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap);
  11064. if (ret == WOLFSSL_SUCCESS)
  11065. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3,
  11066. ssl->heap);
  11067. if (ret == WOLFSSL_SUCCESS)
  11068. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5,
  11069. ssl->heap);
  11070. if (ret == WOLFSSL_SUCCESS)
  11071. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_KYBER_LEVEL1,
  11072. ssl->heap);
  11073. if (ret == WOLFSSL_SUCCESS)
  11074. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_KYBER_LEVEL3,
  11075. ssl->heap);
  11076. if (ret == WOLFSSL_SUCCESS)
  11077. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_KYBER_LEVEL5,
  11078. ssl->heap);
  11079. #elif defined(HAVE_PQM4)
  11080. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap);
  11081. #endif /* HAVE_LIBOQS */
  11082. #endif /* HAVE_PQC */
  11083. (void)ssl;
  11084. (void)extensions;
  11085. return ret;
  11086. }
  11087. #endif /* HAVE_SUPPORTED_CURVES */
  11088. int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer)
  11089. {
  11090. int ret = 0;
  11091. byte* public_key = NULL;
  11092. word16 public_key_len = 0;
  11093. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  11094. int usingPSK = 0;
  11095. #endif
  11096. #if defined(HAVE_SUPPORTED_CURVES) && defined(WOLFSSL_TLS13)
  11097. TLSX* extension = NULL;
  11098. word16 namedGroup = WOLFSSL_NAMED_GROUP_INVALID;
  11099. #endif
  11100. /* server will add extension depending on what is parsed from client */
  11101. if (!isServer) {
  11102. #if defined(HAVE_RPK)
  11103. ret = TLSX_ClientCertificateType_Use(ssl, isServer);
  11104. if (ret != 0)
  11105. return ret;
  11106. ret = TLSX_ServerCertificateType_Use(ssl, isServer);
  11107. if (ret != 0)
  11108. return ret;
  11109. #endif /* HAVE_RPK */
  11110. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  11111. if (!ssl->options.disallowEncThenMac) {
  11112. ret = TLSX_EncryptThenMac_Use(ssl);
  11113. if (ret != 0)
  11114. return ret;
  11115. }
  11116. #endif
  11117. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  11118. defined(HAVE_CURVE448)) && defined(HAVE_SUPPORTED_CURVES)
  11119. if (!ssl->options.userCurves && !ssl->ctx->userCurves) {
  11120. if (TLSX_Find(ssl->ctx->extensions,
  11121. TLSX_SUPPORTED_GROUPS) == NULL) {
  11122. ret = TLSX_PopulateSupportedGroups(ssl, &ssl->extensions);
  11123. if (ret != WOLFSSL_SUCCESS)
  11124. return ret;
  11125. }
  11126. }
  11127. if ((!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade) &&
  11128. TLSX_Find(ssl->ctx->extensions, TLSX_EC_POINT_FORMATS) == NULL &&
  11129. TLSX_Find(ssl->extensions, TLSX_EC_POINT_FORMATS) == NULL) {
  11130. ret = TLSX_UsePointFormat(&ssl->extensions,
  11131. WOLFSSL_EC_PF_UNCOMPRESSED, ssl->heap);
  11132. if (ret != WOLFSSL_SUCCESS)
  11133. return ret;
  11134. }
  11135. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && HAVE_SUPPORTED_CURVES */
  11136. #ifdef WOLFSSL_SRTP
  11137. if (ssl->options.dtls && ssl->dtlsSrtpProfiles != 0) {
  11138. WOLFSSL_MSG("Adding DTLS SRTP extension");
  11139. if ((ret = TLSX_UseSRTP(&ssl->extensions, ssl->dtlsSrtpProfiles,
  11140. ssl->heap)) != 0) {
  11141. return ret;
  11142. }
  11143. }
  11144. #endif
  11145. #ifdef WOLFSSL_DUAL_ALG_CERTS
  11146. if ((IsAtLeastTLSv1_3(ssl->version)) && (ssl->sigSpec != NULL)) {
  11147. WOLFSSL_MSG("Adding CKS extension");
  11148. if ((ret = TLSX_UseCKS(&ssl->extensions, ssl, ssl->heap)) != 0) {
  11149. return ret;
  11150. }
  11151. }
  11152. #endif
  11153. } /* is not server */
  11154. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11155. WOLFSSL_MSG("Adding signature algorithms extension");
  11156. if ((ret = TLSX_SetSignatureAlgorithms(&ssl->extensions, ssl, ssl->heap))
  11157. != 0) {
  11158. return ret;
  11159. }
  11160. #else
  11161. ret = 0;
  11162. #endif
  11163. #ifdef WOLFSSL_TLS13
  11164. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11165. if (isServer && IsAtLeastTLSv1_3(ssl->version)) {
  11166. if (SSL_CA_NAMES(ssl) != NULL) {
  11167. WOLFSSL_MSG("Adding certificate authorities extension");
  11168. if ((ret = TLSX_Push(&ssl->extensions,
  11169. TLSX_CERTIFICATE_AUTHORITIES, ssl, ssl->heap)) != 0) {
  11170. return ret;
  11171. }
  11172. }
  11173. }
  11174. #endif
  11175. if (!isServer && IsAtLeastTLSv1_3(ssl->version)) {
  11176. /* Add mandatory TLS v1.3 extension: supported version */
  11177. WOLFSSL_MSG("Adding supported versions extension");
  11178. if ((ret = TLSX_SetSupportedVersions(&ssl->extensions, ssl,
  11179. ssl->heap)) != 0) {
  11180. return ret;
  11181. }
  11182. #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && \
  11183. !defined(HAVE_CURVE448) && defined(HAVE_SUPPORTED_CURVES)
  11184. if (TLSX_Find(ssl->ctx->extensions, TLSX_SUPPORTED_GROUPS) == NULL) {
  11185. /* Put in DH groups for TLS 1.3 only. */
  11186. ret = TLSX_PopulateSupportedGroups(ssl, &ssl->extensions);
  11187. if (ret != WOLFSSL_SUCCESS)
  11188. return ret;
  11189. /* ret value will be overwritten in !NO_PSK case */
  11190. #ifdef NO_PSK
  11191. ret = 0;
  11192. #endif
  11193. }
  11194. #endif /* !(HAVE_ECC || CURVE25519 || CURVE448) && HAVE_SUPPORTED_CURVES */
  11195. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11196. if (ssl->certHashSigAlgoSz > 0) {
  11197. WOLFSSL_MSG("Adding signature algorithms cert extension");
  11198. if ((ret = TLSX_SetSignatureAlgorithmsCert(&ssl->extensions,
  11199. ssl, ssl->heap)) != 0) {
  11200. return ret;
  11201. }
  11202. }
  11203. #endif
  11204. #if defined(HAVE_SUPPORTED_CURVES)
  11205. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  11206. if (extension == NULL) {
  11207. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11208. if (ssl->options.resuming && ssl->session->namedGroup != 0)
  11209. namedGroup = ssl->session->namedGroup;
  11210. else
  11211. #endif
  11212. if (ssl->numGroups > 0) {
  11213. int set = 0;
  11214. int i, j;
  11215. /* try to find the highest element in ssl->group[]
  11216. * that is contained in preferredGroup[].
  11217. */
  11218. namedGroup = preferredGroup[0];
  11219. for (i = 0; i < ssl->numGroups && !set; i++) {
  11220. for (j = 0; preferredGroup[j] != WOLFSSL_NAMED_GROUP_INVALID; j++) {
  11221. if (preferredGroup[j] == ssl->group[i]
  11222. #ifdef HAVE_LIBOQS
  11223. && TLSX_KeyShare_IsSupported(preferredGroup[j])
  11224. #endif
  11225. ) {
  11226. namedGroup = ssl->group[i];
  11227. set = 1;
  11228. break;
  11229. }
  11230. }
  11231. }
  11232. if (!set)
  11233. namedGroup = WOLFSSL_NAMED_GROUP_INVALID;
  11234. }
  11235. else {
  11236. /* Choose the most preferred group. */
  11237. namedGroup = preferredGroup[0];
  11238. #ifdef HAVE_LIBOQS
  11239. if (!TLSX_KeyShare_IsSupported(namedGroup)) {
  11240. int i = 1;
  11241. for (;preferredGroup[i] != WOLFSSL_NAMED_GROUP_INVALID;
  11242. i++) {
  11243. if (TLSX_KeyShare_IsSupported(preferredGroup[i]))
  11244. break;
  11245. }
  11246. namedGroup = preferredGroup[i];
  11247. }
  11248. #endif
  11249. }
  11250. }
  11251. else {
  11252. KeyShareEntry* kse = (KeyShareEntry*)extension->data;
  11253. if (kse)
  11254. namedGroup = kse->group;
  11255. }
  11256. if (namedGroup != WOLFSSL_NAMED_GROUP_INVALID) {
  11257. ret = TLSX_KeyShare_Use(ssl, namedGroup, 0, NULL, NULL,
  11258. &ssl->extensions);
  11259. if (ret != 0)
  11260. return ret;
  11261. }
  11262. #endif /* HAVE_SUPPORTED_CURVES */
  11263. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11264. TLSX_Remove(&ssl->extensions, TLSX_PRE_SHARED_KEY, ssl->heap);
  11265. #endif
  11266. #if defined(HAVE_SESSION_TICKET)
  11267. if (ssl->options.resuming && ssl->session->ticketLen > 0) {
  11268. WOLFSSL_SESSION* sess = ssl->session;
  11269. #ifdef WOLFSSL_32BIT_MILLI_TIME
  11270. word32 now, milli;
  11271. #else
  11272. word64 now, milli;
  11273. #endif
  11274. if (sess->ticketLen > MAX_PSK_ID_LEN) {
  11275. WOLFSSL_MSG("Session ticket length for PSK ext is too large");
  11276. return BUFFER_ERROR;
  11277. }
  11278. /* Determine the MAC algorithm for the cipher suite used. */
  11279. ssl->options.cipherSuite0 = sess->cipherSuite0;
  11280. ssl->options.cipherSuite = sess->cipherSuite;
  11281. ret = SetCipherSpecs(ssl);
  11282. if (ret != 0)
  11283. return ret;
  11284. now = TimeNowInMilliseconds();
  11285. if (now == 0)
  11286. return GETTIME_ERROR;
  11287. #ifdef WOLFSSL_32BIT_MILLI_TIME
  11288. if (now < sess->ticketSeen)
  11289. milli = (0xFFFFFFFFU - sess->ticketSeen) + 1 + now;
  11290. else
  11291. milli = now - sess->ticketSeen;
  11292. milli += sess->ticketAdd;
  11293. /* Pre-shared key is mandatory extension for resumption. */
  11294. ret = TLSX_PreSharedKey_Use(&ssl->extensions, sess->ticket,
  11295. sess->ticketLen, milli, ssl->specs.mac_algorithm,
  11296. ssl->options.cipherSuite0, ssl->options.cipherSuite, 1,
  11297. NULL, ssl->heap);
  11298. #else
  11299. milli = now - sess->ticketSeen + sess->ticketAdd;
  11300. /* Pre-shared key is mandatory extension for resumption. */
  11301. ret = TLSX_PreSharedKey_Use(&ssl->extensions, sess->ticket,
  11302. sess->ticketLen, (word32)milli, ssl->specs.mac_algorithm,
  11303. ssl->options.cipherSuite0, ssl->options.cipherSuite, 1,
  11304. NULL, ssl->heap);
  11305. #endif
  11306. if (ret != 0)
  11307. return ret;
  11308. usingPSK = 1;
  11309. }
  11310. #endif
  11311. #ifndef NO_PSK
  11312. #ifndef WOLFSSL_PSK_ONE_ID
  11313. if (ssl->options.client_psk_cs_cb != NULL) {
  11314. int i;
  11315. const Suites* suites = WOLFSSL_SUITES(ssl);
  11316. for (i = 0; i < suites->suiteSz; i += 2) {
  11317. byte cipherSuite0 = suites->suites[i + 0];
  11318. byte cipherSuite = suites->suites[i + 1];
  11319. unsigned int keySz;
  11320. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11321. int cnt = 0;
  11322. #endif
  11323. #ifdef HAVE_NULL_CIPHER
  11324. if (cipherSuite0 == ECC_BYTE ||
  11325. cipherSuite0 == ECDHE_PSK_BYTE) {
  11326. if (cipherSuite != TLS_SHA256_SHA256 &&
  11327. cipherSuite != TLS_SHA384_SHA384) {
  11328. continue;
  11329. }
  11330. }
  11331. else
  11332. #endif
  11333. #if (defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)) && \
  11334. defined(WOLFSSL_SM3)
  11335. if (cipherSuite0 == CIPHER_BYTE) {
  11336. if ((cipherSuite != TLS_SM4_GCM_SM3) &&
  11337. (cipherSuite != TLS_SM4_CCM_SM3)) {
  11338. continue;
  11339. }
  11340. }
  11341. else
  11342. #endif
  11343. if (cipherSuite0 != TLS13_BYTE)
  11344. continue;
  11345. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11346. do {
  11347. ssl->arrays->client_identity[0] = cnt;
  11348. #endif
  11349. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  11350. keySz = ssl->options.client_psk_cs_cb(
  11351. ssl, ssl->arrays->server_hint,
  11352. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  11353. ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
  11354. GetCipherNameInternal(cipherSuite0, cipherSuite));
  11355. if (keySz > 0) {
  11356. ssl->arrays->psk_keySz = keySz;
  11357. ret = TLSX_PreSharedKey_Use(&ssl->extensions,
  11358. (byte*)ssl->arrays->client_identity,
  11359. (word16)XSTRLEN(ssl->arrays->client_identity),
  11360. 0, SuiteMac(WOLFSSL_SUITES(ssl)->suites + i),
  11361. cipherSuite0, cipherSuite, 0, NULL, ssl->heap);
  11362. if (ret != 0)
  11363. return ret;
  11364. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11365. cnt++;
  11366. #endif
  11367. }
  11368. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11369. }
  11370. while (keySz > 0);
  11371. #endif
  11372. }
  11373. usingPSK = 1;
  11374. }
  11375. else
  11376. #endif
  11377. if (ssl->options.client_psk_cb != NULL ||
  11378. ssl->options.client_psk_tls13_cb != NULL) {
  11379. /* Default cipher suite. */
  11380. byte cipherSuite0 = TLS13_BYTE;
  11381. byte cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
  11382. int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
  11383. const char* cipherName = NULL;
  11384. if (ssl->options.client_psk_tls13_cb != NULL) {
  11385. ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(
  11386. ssl, ssl->arrays->server_hint,
  11387. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  11388. ssl->arrays->psk_key, MAX_PSK_KEY_LEN, &cipherName);
  11389. if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
  11390. &cipherSuite, &cipherSuiteFlags) != 0) {
  11391. return PSK_KEY_ERROR;
  11392. }
  11393. }
  11394. else {
  11395. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  11396. ssl->arrays->server_hint, ssl->arrays->client_identity,
  11397. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  11398. }
  11399. if (
  11400. #ifdef OPENSSL_EXTRA
  11401. /* OpenSSL treats a PSK key length of 0
  11402. * to indicate no PSK available.
  11403. */
  11404. ssl->arrays->psk_keySz == 0 ||
  11405. #endif
  11406. (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN &&
  11407. (int)ssl->arrays->psk_keySz != USE_HW_PSK)) {
  11408. #ifndef OPENSSL_EXTRA
  11409. ret = PSK_KEY_ERROR;
  11410. #endif
  11411. }
  11412. else {
  11413. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  11414. ssl->options.cipherSuite0 = cipherSuite0;
  11415. ssl->options.cipherSuite = cipherSuite;
  11416. (void)cipherSuiteFlags;
  11417. ret = SetCipherSpecs(ssl);
  11418. if (ret == 0) {
  11419. ret = TLSX_PreSharedKey_Use(
  11420. &ssl->extensions,
  11421. (byte*)ssl->arrays->client_identity,
  11422. (word16)XSTRLEN(ssl->arrays->client_identity),
  11423. 0, ssl->specs.mac_algorithm,
  11424. cipherSuite0, cipherSuite, 0,
  11425. NULL, ssl->heap);
  11426. }
  11427. if (ret == 0)
  11428. usingPSK = 1;
  11429. }
  11430. if (ret != 0)
  11431. return ret;
  11432. }
  11433. #endif /* !NO_PSK */
  11434. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11435. /* Some servers do not generate session tickets unless
  11436. * the extension is seen in a non-resume client hello.
  11437. * We used to send it only if we were otherwise using PSK.
  11438. * Now always send it. Define NO_TLSX_PSKKEM_PLAIN_ANNOUNCE
  11439. * to revert to the old behaviour. */
  11440. #ifdef NO_TLSX_PSKKEM_PLAIN_ANNOUNCE
  11441. if (usingPSK)
  11442. #endif
  11443. {
  11444. byte modes = 0;
  11445. (void)usingPSK;
  11446. /* Pre-shared key modes: mandatory extension for resumption. */
  11447. #ifdef HAVE_SUPPORTED_CURVES
  11448. if (!ssl->options.onlyPskDheKe)
  11449. #endif
  11450. {
  11451. modes = 1 << PSK_KE;
  11452. }
  11453. #if !defined(NO_DH) || defined(HAVE_ECC) || \
  11454. defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  11455. if (!ssl->options.noPskDheKe) {
  11456. modes |= 1 << PSK_DHE_KE;
  11457. }
  11458. #endif
  11459. ret = TLSX_PskKeyModes_Use(ssl, modes);
  11460. if (ret != 0)
  11461. return ret;
  11462. }
  11463. #endif
  11464. #if defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  11465. if (!isServer && ssl->options.postHandshakeAuth) {
  11466. ret = TLSX_PostHandAuth_Use(ssl);
  11467. if (ret != 0)
  11468. return ret;
  11469. }
  11470. #endif
  11471. #if defined(HAVE_ECH)
  11472. /* GREASE ECH */
  11473. if (ssl->echConfigs == NULL) {
  11474. ret = GREASE_ECH_USE(&(ssl->extensions), ssl->heap, ssl->rng);
  11475. }
  11476. else if (ssl->echConfigs != NULL) {
  11477. ret = ECH_USE(ssl->echConfigs, &(ssl->extensions), ssl->heap,
  11478. ssl->rng);
  11479. }
  11480. #endif
  11481. }
  11482. #if defined(HAVE_ECH)
  11483. else if (IsAtLeastTLSv1_3(ssl->version)) {
  11484. if (ssl->ctx->echConfigs != NULL) {
  11485. ret = SERVER_ECH_USE(&(ssl->extensions), ssl->heap,
  11486. ssl->ctx->echConfigs);
  11487. if (ret == 0)
  11488. TLSX_SetResponse(ssl, TLSX_ECH);
  11489. }
  11490. }
  11491. #endif
  11492. #endif
  11493. (void)isServer;
  11494. (void)public_key;
  11495. (void)public_key_len;
  11496. (void)ssl;
  11497. return ret;
  11498. }
  11499. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  11500. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11501. /* because the size of ech depends on the size of other extensions we need to
  11502. * get the size with ech special and process ech last, return status */
  11503. static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType,
  11504. word16* pLength)
  11505. {
  11506. int ret = 0;
  11507. TLSX* echX = NULL;
  11508. TLSX* serverNameX = NULL;
  11509. TLSX** extensions = NULL;
  11510. #ifdef WOLFSSL_SMALL_STACK
  11511. char* tmpServerName = NULL;
  11512. #else
  11513. char tmpServerName[MAX_PUBLIC_NAME_SZ];
  11514. #endif
  11515. /* calculate the rest of the extensions length with inner ech */
  11516. if (ssl->extensions)
  11517. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  11518. if (echX == NULL && ssl->ctx && ssl->ctx->extensions)
  11519. echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH);
  11520. /* if type is outer change sni to public name */
  11521. if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) {
  11522. if (ssl->extensions) {
  11523. serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  11524. if (serverNameX != NULL)
  11525. extensions = &ssl->extensions;
  11526. }
  11527. if (serverNameX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11528. serverNameX = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  11529. extensions = &ssl->ctx->extensions;
  11530. }
  11531. /* store the inner server name */
  11532. if (serverNameX != NULL) {
  11533. char* hostName = ((SNI*)serverNameX->data)->data.host_name;
  11534. word32 hostNameSz = (word32)XSTRLEN(hostName) + 1;
  11535. #ifdef WOLFSSL_SMALL_STACK
  11536. tmpServerName = (char*)XMALLOC(hostNameSz, ssl->heap,
  11537. DYNAMIC_TYPE_TMP_BUFFER);
  11538. if (tmpServerName == NULL)
  11539. return MEMORY_E;
  11540. #else
  11541. /* truncate if too long */
  11542. if (hostNameSz > MAX_PUBLIC_NAME_SZ)
  11543. hostNameSz = MAX_PUBLIC_NAME_SZ;
  11544. #endif
  11545. XMEMCPY(tmpServerName, hostName, hostNameSz);
  11546. }
  11547. /* remove the inner server name */
  11548. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11549. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11550. ((WOLFSSL_ECH*)echX->data)->echConfig->publicName,
  11551. XSTRLEN(((WOLFSSL_ECH*)echX->data)->echConfig->publicName),
  11552. ssl->heap);
  11553. /* set the public name as the server name */
  11554. if (ret == WOLFSSL_SUCCESS)
  11555. ret = 0;
  11556. }
  11557. if (ret == 0 && ssl->extensions)
  11558. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, pLength);
  11559. if (ret == 0 && ssl->ctx && ssl->ctx->extensions)
  11560. ret = TLSX_GetSize(ssl->ctx->extensions, semaphore, msgType, pLength);
  11561. if (serverNameX != NULL) {
  11562. /* remove the public name SNI */
  11563. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11564. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11565. tmpServerName, XSTRLEN(tmpServerName), ssl->heap);
  11566. /* restore the inner server name */
  11567. if (ret == WOLFSSL_SUCCESS)
  11568. ret = 0;
  11569. }
  11570. #ifdef WOLFSSL_SMALL_STACK
  11571. XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11572. #endif
  11573. return ret;
  11574. }
  11575. #endif
  11576. /** Tells the buffered size of extensions to be sent into the client hello. */
  11577. int TLSX_GetRequestSize(WOLFSSL* ssl, byte msgType, word32* pLength)
  11578. {
  11579. int ret = 0;
  11580. word16 length = 0;
  11581. byte semaphore[SEMAPHORE_SIZE] = {0};
  11582. if (!TLSX_SupportExtensions(ssl))
  11583. return 0;
  11584. if (msgType == client_hello) {
  11585. EC_VALIDATE_REQUEST(ssl, semaphore);
  11586. PF_VALIDATE_REQUEST(ssl, semaphore);
  11587. WOLF_STK_VALIDATE_REQUEST(ssl);
  11588. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11589. if (WOLFSSL_SUITES(ssl)->hashSigAlgoSz == 0)
  11590. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11591. #endif
  11592. #if defined(WOLFSSL_TLS13)
  11593. if (!IsAtLeastTLSv1_2(ssl)) {
  11594. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11595. }
  11596. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11597. if (!IsAtLeastTLSv1_3(ssl->version)) {
  11598. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11599. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11600. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11601. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PSK_KEY_EXCHANGE_MODES));
  11602. #endif
  11603. #ifdef WOLFSSL_EARLY_DATA
  11604. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11605. #endif
  11606. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11607. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11608. #endif
  11609. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  11610. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_POST_HANDSHAKE_AUTH));
  11611. #endif
  11612. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11613. TURN_ON(semaphore,
  11614. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11615. #endif
  11616. }
  11617. #endif
  11618. #endif /* WOLFSSL_TLS13 */
  11619. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  11620. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  11621. if (!SSL_CM(ssl)->ocspStaplingEnabled) {
  11622. /* mark already sent, so it won't send it */
  11623. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11624. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11625. }
  11626. #endif
  11627. }
  11628. #ifdef WOLFSSL_TLS13
  11629. #ifndef NO_CERTS
  11630. else if (msgType == certificate_request) {
  11631. /* Don't send out any extension except those that are turned off. */
  11632. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11633. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11634. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11635. #endif
  11636. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11637. if (SSL_CA_NAMES(ssl) != NULL)
  11638. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11639. #endif
  11640. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, OID_FILTERS
  11641. * TLSX_STATUS_REQUEST
  11642. */
  11643. }
  11644. #endif
  11645. #if defined(HAVE_ECH)
  11646. if (ssl->options.useEch == 1 && msgType == client_hello) {
  11647. ret = TLSX_GetSizeWithEch(ssl, semaphore, msgType, &length);
  11648. if (ret != 0)
  11649. return ret;
  11650. }
  11651. else
  11652. #endif /* HAVE_ECH */
  11653. #endif /* WOLFSSL_TLS13 */
  11654. {
  11655. if (ssl->extensions) {
  11656. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, &length);
  11657. if (ret != 0)
  11658. return ret;
  11659. }
  11660. if (ssl->ctx && ssl->ctx->extensions) {
  11661. ret = TLSX_GetSize(ssl->ctx->extensions, semaphore, msgType,
  11662. &length);
  11663. if (ret != 0)
  11664. return ret;
  11665. }
  11666. }
  11667. #ifdef HAVE_EXTENDED_MASTER
  11668. if (msgType == client_hello && ssl->options.haveEMS &&
  11669. (!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade)) {
  11670. length += HELLO_EXT_SZ;
  11671. }
  11672. #endif
  11673. if (length)
  11674. length += OPAQUE16_LEN; /* for total length storage. */
  11675. *pLength += length;
  11676. return ret;
  11677. }
  11678. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11679. /* return status after writing the extensions with ech written last */
  11680. static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore,
  11681. byte msgType, word16* pOffset)
  11682. {
  11683. int ret = 0;
  11684. TLSX* echX = NULL;
  11685. TLSX* serverNameX = NULL;
  11686. TLSX** extensions = NULL;
  11687. #ifdef WOLFSSL_SMALL_STACK
  11688. char* tmpServerName = NULL;
  11689. #else
  11690. char tmpServerName[MAX_PUBLIC_NAME_SZ];
  11691. #endif
  11692. /* get the echX from either extensions or ctx */
  11693. if (ssl->extensions)
  11694. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  11695. if (echX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11696. /* if not NULL the semaphore will stop it from being counted */
  11697. if (echX == NULL)
  11698. echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH);
  11699. }
  11700. /* if type is outer change sni to public name */
  11701. if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) {
  11702. if (ssl->extensions) {
  11703. serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  11704. if (serverNameX != NULL)
  11705. extensions = &ssl->extensions;
  11706. }
  11707. if (serverNameX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11708. serverNameX = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  11709. extensions = &ssl->ctx->extensions;
  11710. }
  11711. /* store the inner server name */
  11712. if (serverNameX != NULL) {
  11713. char* hostName = ((SNI*)serverNameX->data)->data.host_name;
  11714. word32 hostNameSz = (word32)XSTRLEN(hostName) + 1;
  11715. #ifdef WOLFSSL_SMALL_STACK
  11716. tmpServerName = (char*)XMALLOC(hostNameSz, ssl->heap,
  11717. DYNAMIC_TYPE_TMP_BUFFER);
  11718. if (tmpServerName == NULL)
  11719. return MEMORY_E;
  11720. #else
  11721. /* truncate if too long */
  11722. if (hostNameSz > MAX_PUBLIC_NAME_SZ)
  11723. hostNameSz = MAX_PUBLIC_NAME_SZ;
  11724. #endif
  11725. XMEMCPY(tmpServerName, hostName, hostNameSz);
  11726. }
  11727. /* remove the inner server name */
  11728. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11729. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11730. ((WOLFSSL_ECH*)echX->data)->echConfig->publicName,
  11731. XSTRLEN(((WOLFSSL_ECH*)echX->data)->echConfig->publicName),
  11732. ssl->heap);
  11733. /* set the public name as the server name */
  11734. if (ret == WOLFSSL_SUCCESS)
  11735. ret = 0;
  11736. }
  11737. if (echX != NULL) {
  11738. /* turn ech on so it doesn't write, then write it last */
  11739. TURN_ON(semaphore, TLSX_ToSemaphore(echX->type));
  11740. }
  11741. if (ret == 0 && ssl->extensions) {
  11742. ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore,
  11743. msgType, pOffset);
  11744. }
  11745. if (ret == 0 && ssl->ctx && ssl->ctx->extensions) {
  11746. ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore,
  11747. msgType, pOffset);
  11748. }
  11749. if (echX != NULL) {
  11750. /* turn off and write it last */
  11751. TURN_OFF(semaphore, TLSX_ToSemaphore(echX->type));
  11752. }
  11753. if (ret == 0 && ssl->extensions) {
  11754. ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore,
  11755. msgType, pOffset);
  11756. }
  11757. if (ret == 0 && ssl->ctx && ssl->ctx->extensions) {
  11758. ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore,
  11759. msgType, pOffset);
  11760. }
  11761. if (serverNameX != NULL) {
  11762. /* remove the public name SNI */
  11763. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11764. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME, tmpServerName,
  11765. XSTRLEN(tmpServerName), ssl->heap);
  11766. /* restore the inner server name */
  11767. if (ret == WOLFSSL_SUCCESS)
  11768. ret = 0;
  11769. }
  11770. #ifdef WOLFSSL_SMALL_STACK
  11771. XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11772. #endif
  11773. return ret;
  11774. }
  11775. #endif
  11776. /** Writes the extensions to be sent into the client hello. */
  11777. int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word32* pOffset)
  11778. {
  11779. int ret = 0;
  11780. word16 offset = 0;
  11781. byte semaphore[SEMAPHORE_SIZE] = {0};
  11782. if (!TLSX_SupportExtensions(ssl) || output == NULL)
  11783. return 0;
  11784. offset += OPAQUE16_LEN; /* extensions length */
  11785. if (msgType == client_hello) {
  11786. EC_VALIDATE_REQUEST(ssl, semaphore);
  11787. PF_VALIDATE_REQUEST(ssl, semaphore);
  11788. WOLF_STK_VALIDATE_REQUEST(ssl);
  11789. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11790. if (WOLFSSL_SUITES(ssl)->hashSigAlgoSz == 0)
  11791. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11792. #endif
  11793. #ifdef WOLFSSL_TLS13
  11794. if (!IsAtLeastTLSv1_2(ssl)) {
  11795. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11796. }
  11797. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11798. if (!IsAtLeastTLSv1_3(ssl->version)) {
  11799. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11800. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11801. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PSK_KEY_EXCHANGE_MODES));
  11802. #endif
  11803. #ifdef WOLFSSL_EARLY_DATA
  11804. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11805. #endif
  11806. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11807. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11808. #endif
  11809. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  11810. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_POST_HANDSHAKE_AUTH));
  11811. #endif
  11812. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11813. TURN_ON(semaphore,
  11814. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11815. #endif
  11816. #ifdef WOLFSSL_DUAL_ALG_CERTS
  11817. TURN_ON(semaphore,
  11818. TLSX_ToSemaphore(TLSX_CKS));
  11819. #endif
  11820. }
  11821. #endif
  11822. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11823. /* Must write Pre-shared Key extension at the end in TLS v1.3.
  11824. * Must not write out Pre-shared Key extension in earlier versions of
  11825. * protocol.
  11826. */
  11827. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11828. #endif
  11829. #endif /* WOLFSSL_TLS13 */
  11830. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  11831. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  11832. /* mark already sent, so it won't send it */
  11833. if (!SSL_CM(ssl)->ocspStaplingEnabled) {
  11834. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11835. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11836. }
  11837. #endif
  11838. }
  11839. #ifdef WOLFSSL_TLS13
  11840. #ifndef NO_CERTS
  11841. else if (msgType == certificate_request) {
  11842. /* Don't send out any extension except those that are turned off. */
  11843. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11844. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11845. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11846. #endif
  11847. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11848. if (SSL_CA_NAMES(ssl) != NULL) {
  11849. TURN_OFF(semaphore,
  11850. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11851. }
  11852. #endif
  11853. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, TLSX_OID_FILTERS
  11854. * TLSX_STATUS_REQUEST
  11855. */
  11856. }
  11857. #endif
  11858. #endif
  11859. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11860. if (ssl->options.useEch == 1 && msgType == client_hello) {
  11861. ret = TLSX_WriteWithEch(ssl, output, semaphore,
  11862. msgType, &offset);
  11863. if (ret != 0)
  11864. return ret;
  11865. }
  11866. else
  11867. #endif
  11868. {
  11869. if (ssl->extensions) {
  11870. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11871. msgType, &offset);
  11872. if (ret != 0)
  11873. return ret;
  11874. }
  11875. if (ssl->ctx && ssl->ctx->extensions) {
  11876. ret = TLSX_Write(ssl->ctx->extensions, output + offset, semaphore,
  11877. msgType, &offset);
  11878. if (ret != 0)
  11879. return ret;
  11880. }
  11881. }
  11882. #ifdef HAVE_EXTENDED_MASTER
  11883. if (msgType == client_hello && ssl->options.haveEMS &&
  11884. (!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade)) {
  11885. WOLFSSL_MSG("EMS extension to write");
  11886. c16toa(HELLO_EXT_EXTMS, output + offset);
  11887. offset += HELLO_EXT_TYPE_SZ;
  11888. c16toa(0, output + offset);
  11889. offset += HELLO_EXT_SZ_SZ;
  11890. }
  11891. #endif
  11892. #ifdef WOLFSSL_TLS13
  11893. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11894. if (msgType == client_hello && IsAtLeastTLSv1_3(ssl->version)) {
  11895. /* Write out what we can of Pre-shared key extension. */
  11896. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11897. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11898. client_hello, &offset);
  11899. if (ret != 0)
  11900. return ret;
  11901. }
  11902. #endif
  11903. #endif
  11904. if (offset > OPAQUE16_LEN || msgType != client_hello)
  11905. c16toa(offset - OPAQUE16_LEN, output); /* extensions length */
  11906. *pOffset += offset;
  11907. return ret;
  11908. }
  11909. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  11910. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_SERVER)
  11911. /** Tells the buffered size of extensions to be sent into the server hello. */
  11912. int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength)
  11913. {
  11914. int ret = 0;
  11915. word16 length = 0;
  11916. byte semaphore[SEMAPHORE_SIZE] = {0};
  11917. switch (msgType) {
  11918. #ifndef NO_WOLFSSL_SERVER
  11919. case server_hello:
  11920. PF_VALIDATE_RESPONSE(ssl, semaphore);
  11921. #ifdef WOLFSSL_TLS13
  11922. if (IsAtLeastTLSv1_3(ssl->version)) {
  11923. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11924. TURN_OFF(semaphore,
  11925. TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11926. #if defined(HAVE_SUPPORTED_CURVES)
  11927. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11928. if (!ssl->options.noPskDheKe)
  11929. #endif
  11930. {
  11931. /* Expect KeyShare extension in ServerHello. */
  11932. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11933. }
  11934. #endif
  11935. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11936. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11937. #endif
  11938. #ifdef WOLFSSL_DTLS_CID
  11939. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11940. #endif
  11941. }
  11942. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11943. else {
  11944. #ifdef HAVE_SUPPORTED_CURVES
  11945. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11946. #endif
  11947. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11948. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11949. #endif
  11950. }
  11951. #endif
  11952. #endif /* WOLFSSL_TLS13 */
  11953. break;
  11954. #ifdef WOLFSSL_TLS13
  11955. case hello_retry_request:
  11956. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11957. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11958. #ifdef HAVE_SUPPORTED_CURVES
  11959. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11960. if (!ssl->options.noPskDheKe)
  11961. #endif
  11962. {
  11963. /* Expect KeyShare extension in HelloRetryRequest. */
  11964. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11965. }
  11966. #endif
  11967. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11968. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11969. #endif
  11970. break;
  11971. #endif
  11972. #ifdef WOLFSSL_TLS13
  11973. case encrypted_extensions:
  11974. /* Send out all extension except those that are turned on. */
  11975. #ifdef HAVE_ECC
  11976. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  11977. #endif
  11978. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11979. #ifdef HAVE_SESSION_TICKET
  11980. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SESSION_TICKET));
  11981. #endif
  11982. #ifdef HAVE_SUPPORTED_CURVES
  11983. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11984. #endif
  11985. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11986. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11987. #endif
  11988. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  11989. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11990. #endif
  11991. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  11992. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11993. #endif
  11994. #if defined(HAVE_SERVER_RENEGOTIATION_INFO)
  11995. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_RENEGOTIATION_INFO));
  11996. #endif
  11997. #ifdef WOLFSSL_DTLS_CID
  11998. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11999. #endif /* WOLFSSL_DTLS_CID */
  12000. break;
  12001. #ifdef WOLFSSL_EARLY_DATA
  12002. case session_ticket:
  12003. if (ssl->options.tls1_3) {
  12004. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12005. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  12006. }
  12007. break;
  12008. #endif
  12009. #endif
  12010. #endif
  12011. #ifdef WOLFSSL_TLS13
  12012. #ifndef NO_CERTS
  12013. case certificate:
  12014. /* Don't send out any extension except those that are turned off. */
  12015. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12016. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  12017. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP,
  12018. * TLSX_SERVER_CERTIFICATE_TYPE
  12019. */
  12020. break;
  12021. #endif
  12022. #endif
  12023. }
  12024. #ifdef HAVE_EXTENDED_MASTER
  12025. if (ssl->options.haveEMS && msgType == server_hello &&
  12026. !IsAtLeastTLSv1_3(ssl->version)) {
  12027. length += HELLO_EXT_SZ;
  12028. }
  12029. #endif
  12030. if (TLSX_SupportExtensions(ssl)) {
  12031. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, &length);
  12032. if (ret != 0)
  12033. return ret;
  12034. }
  12035. /* All the response data is set at the ssl object only, so no ctx here. */
  12036. if (length || msgType != server_hello)
  12037. length += OPAQUE16_LEN; /* for total length storage. */
  12038. *pLength += length;
  12039. return ret;
  12040. }
  12041. /** Writes the server hello extensions into a buffer. */
  12042. int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset)
  12043. {
  12044. int ret = 0;
  12045. word16 offset = 0;
  12046. if (TLSX_SupportExtensions(ssl) && output) {
  12047. byte semaphore[SEMAPHORE_SIZE] = {0};
  12048. switch (msgType) {
  12049. #ifndef NO_WOLFSSL_SERVER
  12050. case server_hello:
  12051. PF_VALIDATE_RESPONSE(ssl, semaphore);
  12052. #ifdef WOLFSSL_TLS13
  12053. if (IsAtLeastTLSv1_3(ssl->version)) {
  12054. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12055. TURN_OFF(semaphore,
  12056. TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  12057. #ifdef HAVE_SUPPORTED_CURVES
  12058. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12059. if (!ssl->options.noPskDheKe)
  12060. #endif
  12061. {
  12062. /* Write out KeyShare in ServerHello. */
  12063. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  12064. }
  12065. #endif
  12066. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12067. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  12068. #endif
  12069. #ifdef WOLFSSL_DTLS_CID
  12070. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  12071. #endif /* WOLFSSL_DTLS_CID */
  12072. }
  12073. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  12074. else {
  12075. #ifdef HAVE_SUPPORTED_CURVES
  12076. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  12077. #endif
  12078. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12079. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  12080. #endif
  12081. }
  12082. #endif
  12083. #endif
  12084. break;
  12085. #ifdef WOLFSSL_TLS13
  12086. case hello_retry_request:
  12087. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12088. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  12089. #ifdef HAVE_SUPPORTED_CURVES
  12090. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12091. if (!ssl->options.noPskDheKe)
  12092. #endif
  12093. {
  12094. /* Write out KeyShare in HelloRetryRequest. */
  12095. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  12096. }
  12097. #endif
  12098. /* Cookie is written below as last extension. */
  12099. break;
  12100. #endif
  12101. #ifdef WOLFSSL_TLS13
  12102. case encrypted_extensions:
  12103. /* Send out all extension except those that are turned on. */
  12104. #ifdef HAVE_ECC
  12105. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  12106. #endif
  12107. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  12108. #ifdef HAVE_SESSION_TICKET
  12109. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SESSION_TICKET));
  12110. #endif
  12111. #ifdef HAVE_SUPPORTED_CURVES
  12112. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  12113. #endif
  12114. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12115. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  12116. #endif
  12117. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  12118. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  12119. #endif
  12120. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  12121. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  12122. #endif
  12123. #if defined(HAVE_SERVER_RENEGOTIATION_INFO)
  12124. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_RENEGOTIATION_INFO));
  12125. #endif
  12126. #ifdef WOLFSSL_DTLS_CID
  12127. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  12128. #endif /* WOLFSSL_DTLS_CID */
  12129. break;
  12130. #ifdef WOLFSSL_EARLY_DATA
  12131. case session_ticket:
  12132. if (ssl->options.tls1_3) {
  12133. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12134. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  12135. }
  12136. break;
  12137. #endif
  12138. #endif
  12139. #endif
  12140. #ifdef WOLFSSL_TLS13
  12141. #ifndef NO_CERTS
  12142. case certificate:
  12143. /* Don't send out any extension except those that are turned
  12144. * off. */
  12145. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12146. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  12147. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP,
  12148. * TLSX_SERVER_CERTIFICATE_TYPE
  12149. */
  12150. break;
  12151. #endif
  12152. #endif
  12153. default:
  12154. break;
  12155. }
  12156. offset += OPAQUE16_LEN; /* extensions length */
  12157. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  12158. msgType, &offset);
  12159. if (ret != 0)
  12160. return ret;
  12161. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  12162. if (msgType == hello_retry_request) {
  12163. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12164. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  12165. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  12166. msgType, &offset);
  12167. if (ret != 0)
  12168. return ret;
  12169. }
  12170. #endif
  12171. #ifdef HAVE_EXTENDED_MASTER
  12172. if (ssl->options.haveEMS && msgType == server_hello &&
  12173. !IsAtLeastTLSv1_3(ssl->version)) {
  12174. WOLFSSL_MSG("EMS extension to write");
  12175. c16toa(HELLO_EXT_EXTMS, output + offset);
  12176. offset += HELLO_EXT_TYPE_SZ;
  12177. c16toa(0, output + offset);
  12178. offset += HELLO_EXT_SZ_SZ;
  12179. }
  12180. #endif
  12181. if (offset > OPAQUE16_LEN || msgType != server_hello)
  12182. c16toa(offset - OPAQUE16_LEN, output); /* extensions length */
  12183. }
  12184. if (pOffset)
  12185. *pOffset += offset;
  12186. return ret;
  12187. }
  12188. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_SERVER */
  12189. #ifdef WOLFSSL_TLS13
  12190. int TLSX_ParseVersion(WOLFSSL* ssl, const byte* input, word16 length,
  12191. byte msgType, int* found)
  12192. {
  12193. int ret = 0;
  12194. int offset = 0;
  12195. *found = 0;
  12196. while (offset < (int)length) {
  12197. word16 type;
  12198. word16 size;
  12199. if (offset + (2 * OPAQUE16_LEN) > length) {
  12200. ret = BUFFER_ERROR;
  12201. break;
  12202. }
  12203. ato16(input + offset, &type);
  12204. offset += HELLO_EXT_TYPE_SZ;
  12205. ato16(input + offset, &size);
  12206. offset += OPAQUE16_LEN;
  12207. if (offset + size > length) {
  12208. ret = BUFFER_ERROR;
  12209. break;
  12210. }
  12211. if (type == TLSX_SUPPORTED_VERSIONS) {
  12212. *found = 1;
  12213. WOLFSSL_MSG("Supported Versions extension received");
  12214. ret = SV_PARSE(ssl, input + offset, size, msgType, &ssl->version,
  12215. &ssl->options, &ssl->extensions);
  12216. break;
  12217. }
  12218. offset += size;
  12219. }
  12220. return ret;
  12221. }
  12222. #endif
  12223. /** Parses a buffer of TLS extensions. */
  12224. int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType,
  12225. Suites *suites)
  12226. {
  12227. int ret = 0;
  12228. word16 offset = 0;
  12229. byte isRequest = (msgType == client_hello ||
  12230. msgType == certificate_request);
  12231. #ifdef HAVE_EXTENDED_MASTER
  12232. byte pendingEMS = 0;
  12233. #endif
  12234. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  12235. int pskDone = 0;
  12236. #endif
  12237. byte seenType[SEMAPHORE_SIZE]; /* Seen known extensions. */
  12238. if (!ssl || !input || (isRequest && !suites))
  12239. return BAD_FUNC_ARG;
  12240. /* No known extensions seen yet. */
  12241. XMEMSET(seenType, 0, sizeof(seenType));
  12242. while (ret == 0 && offset < length) {
  12243. word16 type;
  12244. word16 size;
  12245. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  12246. if (msgType == client_hello && pskDone) {
  12247. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  12248. return PSK_KEY_ERROR;
  12249. }
  12250. #endif
  12251. if (length - offset < HELLO_EXT_TYPE_SZ + OPAQUE16_LEN)
  12252. return BUFFER_ERROR;
  12253. ato16(input + offset, &type);
  12254. offset += HELLO_EXT_TYPE_SZ;
  12255. ato16(input + offset, &size);
  12256. offset += OPAQUE16_LEN;
  12257. /* Check we have a bit for extension type. */
  12258. if ((type <= 62) || (type == TLSX_RENEGOTIATION_INFO)
  12259. #ifdef WOLFSSL_QUIC
  12260. || (type == TLSX_KEY_QUIC_TP_PARAMS_DRAFT)
  12261. #endif
  12262. )
  12263. {
  12264. /* Detect duplicate recognized extensions. */
  12265. if (IS_OFF(seenType, TLSX_ToSemaphore(type))) {
  12266. TURN_ON(seenType, TLSX_ToSemaphore(type));
  12267. }
  12268. else {
  12269. return DUPLICATE_TLS_EXT_E;
  12270. }
  12271. }
  12272. if (length - offset < size)
  12273. return BUFFER_ERROR;
  12274. switch (type) {
  12275. #ifdef HAVE_SNI
  12276. case TLSX_SERVER_NAME:
  12277. WOLFSSL_MSG("SNI extension received");
  12278. #ifdef WOLFSSL_DEBUG_TLS
  12279. WOLFSSL_BUFFER(input + offset, size);
  12280. #endif
  12281. #ifdef WOLFSSL_TLS13
  12282. if (IsAtLeastTLSv1_3(ssl->version)) {
  12283. if (msgType != client_hello &&
  12284. msgType != encrypted_extensions)
  12285. return EXT_NOT_ALLOWED;
  12286. }
  12287. else
  12288. #endif
  12289. {
  12290. if (msgType != client_hello &&
  12291. msgType != server_hello)
  12292. return EXT_NOT_ALLOWED;
  12293. }
  12294. ret = SNI_PARSE(ssl, input + offset, size, isRequest);
  12295. break;
  12296. #endif
  12297. case TLSX_TRUSTED_CA_KEYS:
  12298. WOLFSSL_MSG("Trusted CA extension received");
  12299. #ifdef WOLFSSL_DEBUG_TLS
  12300. WOLFSSL_BUFFER(input + offset, size);
  12301. #endif
  12302. #ifdef WOLFSSL_TLS13
  12303. /* RFC 8446 4.2.4 states trusted_ca_keys is not used
  12304. in TLS 1.3. */
  12305. if (IsAtLeastTLSv1_3(ssl->version)) {
  12306. return EXT_NOT_ALLOWED;
  12307. }
  12308. else
  12309. #endif
  12310. {
  12311. if (msgType != client_hello &&
  12312. msgType != server_hello)
  12313. return EXT_NOT_ALLOWED;
  12314. }
  12315. ret = TCA_PARSE(ssl, input + offset, size, isRequest);
  12316. break;
  12317. case TLSX_MAX_FRAGMENT_LENGTH:
  12318. WOLFSSL_MSG("Max Fragment Length extension received");
  12319. #ifdef WOLFSSL_DEBUG_TLS
  12320. WOLFSSL_BUFFER(input + offset, size);
  12321. #endif
  12322. #ifdef WOLFSSL_TLS13
  12323. if (IsAtLeastTLSv1_3(ssl->version)) {
  12324. if (msgType != client_hello &&
  12325. msgType != encrypted_extensions) {
  12326. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12327. return EXT_NOT_ALLOWED;
  12328. }
  12329. }
  12330. else
  12331. #endif
  12332. {
  12333. if (msgType != client_hello &&
  12334. msgType != server_hello) {
  12335. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12336. return EXT_NOT_ALLOWED;
  12337. }
  12338. }
  12339. ret = MFL_PARSE(ssl, input + offset, size, isRequest);
  12340. break;
  12341. case TLSX_TRUNCATED_HMAC:
  12342. WOLFSSL_MSG("Truncated HMAC extension received");
  12343. #ifdef WOLFSSL_DEBUG_TLS
  12344. WOLFSSL_BUFFER(input + offset, size);
  12345. #endif
  12346. #ifdef WOLFSSL_TLS13
  12347. if (IsAtLeastTLSv1_3(ssl->version))
  12348. break;
  12349. #endif
  12350. if (msgType != client_hello)
  12351. return EXT_NOT_ALLOWED;
  12352. ret = THM_PARSE(ssl, input + offset, size, isRequest);
  12353. break;
  12354. case TLSX_SUPPORTED_GROUPS:
  12355. WOLFSSL_MSG("Supported Groups extension received");
  12356. #ifdef WOLFSSL_DEBUG_TLS
  12357. WOLFSSL_BUFFER(input + offset, size);
  12358. #endif
  12359. #ifdef WOLFSSL_TLS13
  12360. if (IsAtLeastTLSv1_3(ssl->version)) {
  12361. if (msgType != client_hello &&
  12362. msgType != encrypted_extensions) {
  12363. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12364. return EXT_NOT_ALLOWED;
  12365. }
  12366. }
  12367. else
  12368. #endif
  12369. {
  12370. if (msgType != client_hello) {
  12371. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12372. return EXT_NOT_ALLOWED;
  12373. }
  12374. }
  12375. ret = EC_PARSE(ssl, input + offset, size, isRequest,
  12376. &ssl->extensions);
  12377. break;
  12378. #ifdef WOLFSSL_DUAL_ALG_CERTS
  12379. case TLSX_CKS:
  12380. WOLFSSL_MSG("CKS extension received");
  12381. if (!IsAtLeastTLSv1_3(ssl->version) ||
  12382. (msgType != client_hello &&
  12383. msgType != encrypted_extensions)) {
  12384. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12385. return EXT_NOT_ALLOWED;
  12386. }
  12387. ret = TLSX_CKS_Parse(ssl, (byte *)(input + offset), size,
  12388. &ssl->extensions);
  12389. break;
  12390. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  12391. case TLSX_EC_POINT_FORMATS:
  12392. WOLFSSL_MSG("Point Formats extension received");
  12393. #ifdef WOLFSSL_DEBUG_TLS
  12394. WOLFSSL_BUFFER(input + offset, size);
  12395. #endif
  12396. #ifdef WOLFSSL_TLS13
  12397. if (IsAtLeastTLSv1_3(ssl->version))
  12398. break;
  12399. #endif
  12400. if (msgType != client_hello &&
  12401. msgType != server_hello) {
  12402. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12403. return EXT_NOT_ALLOWED;
  12404. }
  12405. ret = PF_PARSE(ssl, input + offset, size, isRequest);
  12406. break;
  12407. case TLSX_STATUS_REQUEST:
  12408. WOLFSSL_MSG("Certificate Status Request extension received");
  12409. #ifdef WOLFSSL_DEBUG_TLS
  12410. WOLFSSL_BUFFER(input + offset, size);
  12411. #endif
  12412. #ifdef WOLFSSL_TLS13
  12413. if (IsAtLeastTLSv1_3(ssl->version)) {
  12414. if (msgType != client_hello &&
  12415. msgType != certificate_request &&
  12416. msgType != certificate)
  12417. return EXT_NOT_ALLOWED;
  12418. }
  12419. else
  12420. #endif
  12421. {
  12422. if (msgType != client_hello &&
  12423. msgType != server_hello)
  12424. return EXT_NOT_ALLOWED;
  12425. }
  12426. ret = CSR_PARSE(ssl, input + offset, size, isRequest);
  12427. break;
  12428. case TLSX_STATUS_REQUEST_V2:
  12429. WOLFSSL_MSG("Certificate Status Request v2 extension received");
  12430. #ifdef WOLFSSL_DEBUG_TLS
  12431. WOLFSSL_BUFFER(input + offset, size);
  12432. #endif
  12433. #if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  12434. if (IsAtLeastTLSv1_3(ssl->version)) {
  12435. if (msgType != client_hello &&
  12436. msgType != certificate_request &&
  12437. msgType != certificate)
  12438. return EXT_NOT_ALLOWED;
  12439. }
  12440. else
  12441. #endif
  12442. {
  12443. if (msgType != client_hello &&
  12444. msgType != server_hello)
  12445. return EXT_NOT_ALLOWED;
  12446. }
  12447. ret = CSR2_PARSE(ssl, input + offset, size, isRequest);
  12448. break;
  12449. #ifdef HAVE_EXTENDED_MASTER
  12450. case HELLO_EXT_EXTMS:
  12451. WOLFSSL_MSG("Extended Master Secret extension received");
  12452. #ifdef WOLFSSL_DEBUG_TLS
  12453. WOLFSSL_BUFFER(input + offset, size);
  12454. #endif
  12455. #if defined(WOLFSSL_TLS13)
  12456. if (IsAtLeastTLSv1_3(ssl->version))
  12457. break;
  12458. #endif
  12459. if (msgType != client_hello &&
  12460. msgType != server_hello)
  12461. return EXT_NOT_ALLOWED;
  12462. if (size != 0)
  12463. return BUFFER_ERROR;
  12464. #ifndef NO_WOLFSSL_SERVER
  12465. if (isRequest)
  12466. ssl->options.haveEMS = 1;
  12467. #endif
  12468. pendingEMS = 1;
  12469. break;
  12470. #endif
  12471. case TLSX_RENEGOTIATION_INFO:
  12472. WOLFSSL_MSG("Secure Renegotiation extension received");
  12473. #ifdef WOLFSSL_DEBUG_TLS
  12474. WOLFSSL_BUFFER(input + offset, size);
  12475. #endif
  12476. #ifdef WOLFSSL_TLS13
  12477. if (IsAtLeastTLSv1_3(ssl->version))
  12478. break;
  12479. #endif
  12480. if (msgType != client_hello &&
  12481. msgType != server_hello)
  12482. return EXT_NOT_ALLOWED;
  12483. ret = SCR_PARSE(ssl, input + offset, size, isRequest);
  12484. break;
  12485. case TLSX_SESSION_TICKET:
  12486. WOLFSSL_MSG("Session Ticket extension received");
  12487. #ifdef WOLFSSL_DEBUG_TLS
  12488. WOLFSSL_BUFFER(input + offset, size);
  12489. #endif
  12490. #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)
  12491. if (IsAtLeastTLSv1_3(ssl->version)) {
  12492. if (msgType != client_hello)
  12493. return EXT_NOT_ALLOWED;
  12494. }
  12495. else
  12496. #endif
  12497. {
  12498. if (msgType != client_hello &&
  12499. msgType != server_hello)
  12500. return EXT_NOT_ALLOWED;
  12501. }
  12502. ret = WOLF_STK_PARSE(ssl, input + offset, size, isRequest);
  12503. break;
  12504. case TLSX_APPLICATION_LAYER_PROTOCOL:
  12505. WOLFSSL_MSG("ALPN extension received");
  12506. #ifdef WOLFSSL_DEBUG_TLS
  12507. WOLFSSL_BUFFER(input + offset, size);
  12508. #endif
  12509. #if defined(WOLFSSL_TLS13) && defined(HAVE_ALPN)
  12510. if (IsAtLeastTLSv1_3(ssl->version)) {
  12511. if (msgType != client_hello &&
  12512. msgType != encrypted_extensions)
  12513. return EXT_NOT_ALLOWED;
  12514. }
  12515. else
  12516. #endif
  12517. {
  12518. if (msgType != client_hello &&
  12519. msgType != server_hello)
  12520. return EXT_NOT_ALLOWED;
  12521. }
  12522. ret = ALPN_PARSE(ssl, input + offset, size, isRequest);
  12523. break;
  12524. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  12525. case TLSX_SIGNATURE_ALGORITHMS:
  12526. WOLFSSL_MSG("Signature Algorithms extension received");
  12527. #ifdef WOLFSSL_DEBUG_TLS
  12528. WOLFSSL_BUFFER(input + offset, size);
  12529. #endif
  12530. if (!IsAtLeastTLSv1_2(ssl))
  12531. break;
  12532. #ifdef WOLFSSL_TLS13
  12533. if (IsAtLeastTLSv1_3(ssl->version)) {
  12534. if (msgType != client_hello &&
  12535. msgType != certificate_request)
  12536. return EXT_NOT_ALLOWED;
  12537. }
  12538. else
  12539. #endif
  12540. {
  12541. if (msgType != client_hello)
  12542. return EXT_NOT_ALLOWED;
  12543. }
  12544. ret = SA_PARSE(ssl, input + offset, size, isRequest, suites);
  12545. break;
  12546. #endif
  12547. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  12548. case TLSX_ENCRYPT_THEN_MAC:
  12549. WOLFSSL_MSG("Encrypt-Then-Mac extension received");
  12550. /* Ignore for TLS 1.3+ */
  12551. if (IsAtLeastTLSv1_3(ssl->version))
  12552. break;
  12553. if (msgType != client_hello &&
  12554. msgType != server_hello)
  12555. return EXT_NOT_ALLOWED;
  12556. ret = ETM_PARSE(ssl, input + offset, size, msgType);
  12557. break;
  12558. #endif /* HAVE_ENCRYPT_THEN_MAC */
  12559. #ifdef WOLFSSL_TLS13
  12560. case TLSX_SUPPORTED_VERSIONS:
  12561. WOLFSSL_MSG("Skipping Supported Versions - already processed");
  12562. #ifdef WOLFSSL_DEBUG_TLS
  12563. WOLFSSL_BUFFER(input + offset, size);
  12564. #endif
  12565. if (msgType != client_hello &&
  12566. msgType != server_hello &&
  12567. msgType != hello_retry_request)
  12568. return EXT_NOT_ALLOWED;
  12569. break;
  12570. #ifdef WOLFSSL_SEND_HRR_COOKIE
  12571. case TLSX_COOKIE:
  12572. WOLFSSL_MSG("Cookie extension received");
  12573. #ifdef WOLFSSL_DEBUG_TLS
  12574. WOLFSSL_BUFFER(input + offset, size);
  12575. #endif
  12576. if (!IsAtLeastTLSv1_3(ssl->version))
  12577. break;
  12578. if (msgType != client_hello &&
  12579. msgType != hello_retry_request) {
  12580. return EXT_NOT_ALLOWED;
  12581. }
  12582. ret = CKE_PARSE(ssl, input + offset, size, msgType);
  12583. break;
  12584. #endif
  12585. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12586. case TLSX_PRE_SHARED_KEY:
  12587. WOLFSSL_MSG("Pre-Shared Key extension received");
  12588. #ifdef WOLFSSL_DEBUG_TLS
  12589. WOLFSSL_BUFFER(input + offset, size);
  12590. #endif
  12591. if (!IsAtLeastTLSv1_3(ssl->version))
  12592. break;
  12593. if (msgType != client_hello &&
  12594. msgType != server_hello) {
  12595. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12596. return EXT_NOT_ALLOWED;
  12597. }
  12598. ret = PSK_PARSE(ssl, input + offset, size, msgType);
  12599. pskDone = 1;
  12600. break;
  12601. case TLSX_PSK_KEY_EXCHANGE_MODES:
  12602. WOLFSSL_MSG("PSK Key Exchange Modes extension received");
  12603. #ifdef WOLFSSL_DEBUG_TLS
  12604. WOLFSSL_BUFFER(input + offset, size);
  12605. #endif
  12606. if (!IsAtLeastTLSv1_3(ssl->version))
  12607. break;
  12608. if (msgType != client_hello) {
  12609. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12610. return EXT_NOT_ALLOWED;
  12611. }
  12612. ret = PKM_PARSE(ssl, input + offset, size, msgType);
  12613. break;
  12614. #endif
  12615. #ifdef WOLFSSL_EARLY_DATA
  12616. case TLSX_EARLY_DATA:
  12617. WOLFSSL_MSG("Early Data extension received");
  12618. #ifdef WOLFSSL_DEBUG_TLS
  12619. WOLFSSL_BUFFER(input + offset, size);
  12620. #endif
  12621. if (!IsAtLeastTLSv1_3(ssl->version))
  12622. break;
  12623. if (msgType != client_hello && msgType != session_ticket &&
  12624. msgType != encrypted_extensions) {
  12625. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12626. return EXT_NOT_ALLOWED;
  12627. }
  12628. ret = EDI_PARSE(ssl, input + offset, size, msgType);
  12629. break;
  12630. #endif
  12631. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  12632. case TLSX_POST_HANDSHAKE_AUTH:
  12633. WOLFSSL_MSG("Post Handshake Authentication extension received");
  12634. #ifdef WOLFSSL_DEBUG_TLS
  12635. WOLFSSL_BUFFER(input + offset, size);
  12636. #endif
  12637. if (!IsAtLeastTLSv1_3(ssl->version))
  12638. break;
  12639. if (msgType != client_hello) {
  12640. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12641. return EXT_NOT_ALLOWED;
  12642. }
  12643. ret = PHA_PARSE(ssl, input + offset, size, msgType);
  12644. break;
  12645. #endif
  12646. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  12647. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  12648. WOLFSSL_MSG("Signature Algorithms extension received");
  12649. #ifdef WOLFSSL_DEBUG_TLS
  12650. WOLFSSL_BUFFER(input + offset, size);
  12651. #endif
  12652. if (!IsAtLeastTLSv1_3(ssl->version))
  12653. break;
  12654. if (msgType != client_hello &&
  12655. msgType != certificate_request) {
  12656. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12657. return EXT_NOT_ALLOWED;
  12658. }
  12659. ret = SAC_PARSE(ssl, input + offset, size, isRequest);
  12660. break;
  12661. #endif
  12662. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  12663. case TLSX_CERTIFICATE_AUTHORITIES:
  12664. WOLFSSL_MSG("Certificate Authorities extension received");
  12665. #ifdef WOLFSSL_DEBUG_TLS
  12666. WOLFSSL_BUFFER(input + offset, size);
  12667. #endif
  12668. if (!IsAtLeastTLSv1_3(ssl->version))
  12669. break;
  12670. if (msgType != client_hello &&
  12671. msgType != certificate_request) {
  12672. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12673. return EXT_NOT_ALLOWED;
  12674. }
  12675. ret = CAN_PARSE(ssl, input + offset, size, isRequest);
  12676. break;
  12677. #endif
  12678. case TLSX_KEY_SHARE:
  12679. WOLFSSL_MSG("Key Share extension received");
  12680. #ifdef WOLFSSL_DEBUG_TLS
  12681. WOLFSSL_BUFFER(input + offset, size);
  12682. #endif
  12683. #ifdef HAVE_SUPPORTED_CURVES
  12684. if (!IsAtLeastTLSv1_3(ssl->version))
  12685. break;
  12686. if (msgType != client_hello && msgType != server_hello &&
  12687. msgType != hello_retry_request) {
  12688. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12689. return EXT_NOT_ALLOWED;
  12690. }
  12691. #endif
  12692. ret = KS_PARSE(ssl, input + offset, size, msgType);
  12693. break;
  12694. #endif
  12695. #ifdef WOLFSSL_SRTP
  12696. case TLSX_USE_SRTP:
  12697. WOLFSSL_MSG("Use SRTP extension received");
  12698. ret = SRTP_PARSE(ssl, input + offset, size, isRequest);
  12699. break;
  12700. #endif
  12701. #ifdef WOLFSSL_QUIC
  12702. case TLSX_KEY_QUIC_TP_PARAMS:
  12703. FALL_THROUGH;
  12704. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  12705. WOLFSSL_MSG("QUIC transport parameter received");
  12706. #ifdef WOLFSSL_DEBUG_TLS
  12707. WOLFSSL_BUFFER(input + offset, size);
  12708. #endif
  12709. if (IsAtLeastTLSv1_3(ssl->version) &&
  12710. msgType != client_hello &&
  12711. msgType != server_hello &&
  12712. msgType != encrypted_extensions) {
  12713. return EXT_NOT_ALLOWED;
  12714. }
  12715. else if (!IsAtLeastTLSv1_3(ssl->version) &&
  12716. msgType == encrypted_extensions) {
  12717. return EXT_NOT_ALLOWED;
  12718. }
  12719. else if (WOLFSSL_IS_QUIC(ssl)) {
  12720. ret = QTP_PARSE(ssl, input + offset, size, type, msgType);
  12721. }
  12722. else {
  12723. WOLFSSL_MSG("QUIC transport param TLS extension type, but no QUIC");
  12724. return EXT_NOT_ALLOWED; /* be safe, this should not happen */
  12725. }
  12726. break;
  12727. #endif /* WOLFSSL_QUIC */
  12728. #if defined(WOLFSSL_DTLS_CID)
  12729. case TLSX_CONNECTION_ID:
  12730. /* connection ID not supported in DTLSv1.2 */
  12731. if (!IsAtLeastTLSv1_3(ssl->version))
  12732. break;
  12733. if (msgType != client_hello && msgType != server_hello)
  12734. return EXT_NOT_ALLOWED;
  12735. WOLFSSL_MSG("ConnectionID extension received");
  12736. ret = CID_PARSE(ssl, input + offset, size, isRequest);
  12737. break;
  12738. #endif /* defined(WOLFSSL_DTLS_CID) */
  12739. #if defined(HAVE_RPK)
  12740. case TLSX_CLIENT_CERTIFICATE_TYPE:
  12741. WOLFSSL_MSG("Client Certificate Type extension received");
  12742. ret = CCT_PARSE(ssl, input + offset, size, msgType);
  12743. break;
  12744. case TLSX_SERVER_CERTIFICATE_TYPE:
  12745. WOLFSSL_MSG("Server Certificate Type extension received");
  12746. ret = SCT_PARSE(ssl, input + offset, size, msgType);
  12747. break;
  12748. #endif /* HAVE_RPK */
  12749. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  12750. case TLSX_ECH:
  12751. WOLFSSL_MSG("ECH extension received");
  12752. ret = ECH_PARSE(ssl, input + offset, size, msgType);
  12753. break;
  12754. #endif
  12755. default:
  12756. WOLFSSL_MSG("Unknown TLS extension type");
  12757. }
  12758. /* offset should be updated here! */
  12759. offset += size;
  12760. }
  12761. #ifdef HAVE_EXTENDED_MASTER
  12762. if (IsAtLeastTLSv1_3(ssl->version) &&
  12763. (msgType == hello_retry_request || msgType == hello_verify_request)) {
  12764. /* Don't change EMS status until server_hello received.
  12765. * Second ClientHello must have same extensions.
  12766. */
  12767. }
  12768. else if (!isRequest && ssl->options.haveEMS && !pendingEMS)
  12769. ssl->options.haveEMS = 0;
  12770. #endif
  12771. #if defined(WOLFSSL_TLS13) && !defined(NO_PSK)
  12772. if (IsAtLeastTLSv1_3(ssl->version) && msgType == server_hello &&
  12773. IS_OFF(seenType, TLSX_ToSemaphore(TLSX_KEY_SHARE))) {
  12774. ssl->options.noPskDheKe = 1;
  12775. }
  12776. #endif
  12777. if (ret == 0)
  12778. ret = SNI_VERIFY_PARSE(ssl, isRequest);
  12779. if (ret == 0)
  12780. ret = TCA_VERIFY_PARSE(ssl, isRequest);
  12781. return ret;
  12782. }
  12783. /* undefining semaphore macros */
  12784. #undef IS_OFF
  12785. #undef TURN_ON
  12786. #undef SEMAPHORE_SIZE
  12787. #endif /* HAVE_TLS_EXTENSIONS */
  12788. #ifndef NO_WOLFSSL_CLIENT
  12789. WOLFSSL_METHOD* wolfTLS_client_method(void)
  12790. {
  12791. return wolfTLS_client_method_ex(NULL);
  12792. }
  12793. WOLFSSL_METHOD* wolfTLS_client_method_ex(void* heap)
  12794. {
  12795. WOLFSSL_METHOD* method =
  12796. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12797. heap, DYNAMIC_TYPE_METHOD);
  12798. (void)heap;
  12799. WOLFSSL_ENTER("TLS_client_method_ex");
  12800. if (method) {
  12801. #if defined(WOLFSSL_TLS13)
  12802. InitSSL_Method(method, MakeTLSv1_3());
  12803. #elif !defined(WOLFSSL_NO_TLS12)
  12804. InitSSL_Method(method, MakeTLSv1_2());
  12805. #elif !defined(NO_OLD_TLS)
  12806. InitSSL_Method(method, MakeTLSv1_1());
  12807. #elif defined(WOLFSSL_ALLOW_TLSV10)
  12808. InitSSL_Method(method, MakeTLSv1());
  12809. #else
  12810. #error No TLS version enabled!
  12811. #endif
  12812. method->downgrade = 1;
  12813. method->side = WOLFSSL_CLIENT_END;
  12814. }
  12815. return method;
  12816. }
  12817. #ifndef NO_OLD_TLS
  12818. #ifdef WOLFSSL_ALLOW_TLSV10
  12819. WOLFSSL_METHOD* wolfTLSv1_client_method(void)
  12820. {
  12821. return wolfTLSv1_client_method_ex(NULL);
  12822. }
  12823. WOLFSSL_METHOD* wolfTLSv1_client_method_ex(void* heap)
  12824. {
  12825. WOLFSSL_METHOD* method =
  12826. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12827. heap, DYNAMIC_TYPE_METHOD);
  12828. (void)heap;
  12829. WOLFSSL_ENTER("TLSv1_client_method_ex");
  12830. if (method)
  12831. InitSSL_Method(method, MakeTLSv1());
  12832. return method;
  12833. }
  12834. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12835. WOLFSSL_METHOD* wolfTLSv1_1_client_method(void)
  12836. {
  12837. return wolfTLSv1_1_client_method_ex(NULL);
  12838. }
  12839. WOLFSSL_METHOD* wolfTLSv1_1_client_method_ex(void* heap)
  12840. {
  12841. WOLFSSL_METHOD* method =
  12842. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12843. heap, DYNAMIC_TYPE_METHOD);
  12844. (void)heap;
  12845. WOLFSSL_ENTER("TLSv1_1_client_method_ex");
  12846. if (method)
  12847. InitSSL_Method(method, MakeTLSv1_1());
  12848. return method;
  12849. }
  12850. #endif /* !NO_OLD_TLS */
  12851. #ifndef WOLFSSL_NO_TLS12
  12852. WOLFSSL_ABI
  12853. WOLFSSL_METHOD* wolfTLSv1_2_client_method(void)
  12854. {
  12855. return wolfTLSv1_2_client_method_ex(NULL);
  12856. }
  12857. WOLFSSL_METHOD* wolfTLSv1_2_client_method_ex(void* heap)
  12858. {
  12859. WOLFSSL_METHOD* method =
  12860. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12861. heap, DYNAMIC_TYPE_METHOD);
  12862. (void)heap;
  12863. WOLFSSL_ENTER("TLSv1_2_client_method_ex");
  12864. if (method)
  12865. InitSSL_Method(method, MakeTLSv1_2());
  12866. return method;
  12867. }
  12868. #endif /* WOLFSSL_NO_TLS12 */
  12869. #ifdef WOLFSSL_TLS13
  12870. /* The TLS v1.3 client method data.
  12871. *
  12872. * returns the method data for a TLS v1.3 client.
  12873. */
  12874. WOLFSSL_ABI
  12875. WOLFSSL_METHOD* wolfTLSv1_3_client_method(void)
  12876. {
  12877. return wolfTLSv1_3_client_method_ex(NULL);
  12878. }
  12879. /* The TLS v1.3 client method data.
  12880. *
  12881. * heap The heap used for allocation.
  12882. * returns the method data for a TLS v1.3 client.
  12883. */
  12884. WOLFSSL_METHOD* wolfTLSv1_3_client_method_ex(void* heap)
  12885. {
  12886. WOLFSSL_METHOD* method = (WOLFSSL_METHOD*)
  12887. XMALLOC(sizeof(WOLFSSL_METHOD), heap,
  12888. DYNAMIC_TYPE_METHOD);
  12889. (void)heap;
  12890. WOLFSSL_ENTER("TLSv1_3_client_method_ex");
  12891. if (method)
  12892. InitSSL_Method(method, MakeTLSv1_3());
  12893. return method;
  12894. }
  12895. #endif /* WOLFSSL_TLS13 */
  12896. #ifdef WOLFSSL_DTLS
  12897. WOLFSSL_METHOD* wolfDTLS_client_method(void)
  12898. {
  12899. return wolfDTLS_client_method_ex(NULL);
  12900. }
  12901. WOLFSSL_METHOD* wolfDTLS_client_method_ex(void* heap)
  12902. {
  12903. WOLFSSL_METHOD* method =
  12904. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12905. heap, DYNAMIC_TYPE_METHOD);
  12906. (void)heap;
  12907. WOLFSSL_ENTER("DTLS_client_method_ex");
  12908. if (method) {
  12909. #if defined(WOLFSSL_DTLS13)
  12910. InitSSL_Method(method, MakeDTLSv1_3());
  12911. #elif !defined(WOLFSSL_NO_TLS12)
  12912. InitSSL_Method(method, MakeDTLSv1_2());
  12913. #elif !defined(NO_OLD_TLS)
  12914. InitSSL_Method(method, MakeDTLSv1());
  12915. #else
  12916. #error No DTLS version enabled!
  12917. #endif
  12918. method->downgrade = 1;
  12919. method->side = WOLFSSL_CLIENT_END;
  12920. }
  12921. return method;
  12922. }
  12923. #ifndef NO_OLD_TLS
  12924. WOLFSSL_METHOD* wolfDTLSv1_client_method(void)
  12925. {
  12926. return wolfDTLSv1_client_method_ex(NULL);
  12927. }
  12928. WOLFSSL_METHOD* wolfDTLSv1_client_method_ex(void* heap)
  12929. {
  12930. WOLFSSL_METHOD* method =
  12931. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12932. heap, DYNAMIC_TYPE_METHOD);
  12933. (void)heap;
  12934. WOLFSSL_ENTER("DTLSv1_client_method_ex");
  12935. if (method)
  12936. InitSSL_Method(method, MakeDTLSv1());
  12937. return method;
  12938. }
  12939. #endif /* NO_OLD_TLS */
  12940. #ifndef WOLFSSL_NO_TLS12
  12941. WOLFSSL_METHOD* wolfDTLSv1_2_client_method(void)
  12942. {
  12943. return wolfDTLSv1_2_client_method_ex(NULL);
  12944. }
  12945. WOLFSSL_METHOD* wolfDTLSv1_2_client_method_ex(void* heap)
  12946. {
  12947. WOLFSSL_METHOD* method =
  12948. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12949. heap, DYNAMIC_TYPE_METHOD);
  12950. (void)heap;
  12951. WOLFSSL_ENTER("DTLSv1_2_client_method_ex");
  12952. if (method)
  12953. InitSSL_Method(method, MakeDTLSv1_2());
  12954. (void)heap;
  12955. return method;
  12956. }
  12957. #endif /* !WOLFSSL_NO_TLS12 */
  12958. #endif /* WOLFSSL_DTLS */
  12959. #endif /* NO_WOLFSSL_CLIENT */
  12960. /* EITHER SIDE METHODS */
  12961. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
  12962. #ifndef NO_OLD_TLS
  12963. #ifdef WOLFSSL_ALLOW_TLSV10
  12964. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12965. *
  12966. * Returns a pointer to a WOLFSSL_METHOD struct
  12967. */
  12968. WOLFSSL_METHOD* wolfTLSv1_method(void)
  12969. {
  12970. return wolfTLSv1_method_ex(NULL);
  12971. }
  12972. WOLFSSL_METHOD* wolfTLSv1_method_ex(void* heap)
  12973. {
  12974. WOLFSSL_METHOD* m;
  12975. WOLFSSL_ENTER("TLSv1_method");
  12976. #ifndef NO_WOLFSSL_CLIENT
  12977. m = wolfTLSv1_client_method_ex(heap);
  12978. #else
  12979. m = wolfTLSv1_server_method_ex(heap);
  12980. #endif
  12981. if (m != NULL) {
  12982. m->side = WOLFSSL_NEITHER_END;
  12983. }
  12984. return m;
  12985. }
  12986. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12987. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12988. *
  12989. * Returns a pointer to a WOLFSSL_METHOD struct
  12990. */
  12991. WOLFSSL_METHOD* wolfTLSv1_1_method(void)
  12992. {
  12993. return wolfTLSv1_1_method_ex(NULL);
  12994. }
  12995. WOLFSSL_METHOD* wolfTLSv1_1_method_ex(void* heap)
  12996. {
  12997. WOLFSSL_METHOD* m;
  12998. WOLFSSL_ENTER("TLSv1_1_method");
  12999. #ifndef NO_WOLFSSL_CLIENT
  13000. m = wolfTLSv1_1_client_method_ex(heap);
  13001. #else
  13002. m = wolfTLSv1_1_server_method_ex(heap);
  13003. #endif
  13004. if (m != NULL) {
  13005. m->side = WOLFSSL_NEITHER_END;
  13006. }
  13007. return m;
  13008. }
  13009. #endif /* !NO_OLD_TLS */
  13010. #ifndef WOLFSSL_NO_TLS12
  13011. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  13012. *
  13013. * Returns a pointer to a WOLFSSL_METHOD struct
  13014. */
  13015. WOLFSSL_METHOD* wolfTLSv1_2_method(void)
  13016. {
  13017. return wolfTLSv1_2_method_ex(NULL);
  13018. }
  13019. WOLFSSL_METHOD* wolfTLSv1_2_method_ex(void* heap)
  13020. {
  13021. WOLFSSL_METHOD* m;
  13022. WOLFSSL_ENTER("TLSv1_2_method");
  13023. #ifndef NO_WOLFSSL_CLIENT
  13024. m = wolfTLSv1_2_client_method_ex(heap);
  13025. #else
  13026. m = wolfTLSv1_2_server_method_ex(heap);
  13027. #endif
  13028. if (m != NULL) {
  13029. m->side = WOLFSSL_NEITHER_END;
  13030. }
  13031. return m;
  13032. }
  13033. #endif /* !WOLFSSL_NO_TLS12 */
  13034. #ifdef WOLFSSL_TLS13
  13035. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  13036. *
  13037. * Returns a pointer to a WOLFSSL_METHOD struct
  13038. */
  13039. WOLFSSL_METHOD* wolfTLSv1_3_method(void)
  13040. {
  13041. return wolfTLSv1_3_method_ex(NULL);
  13042. }
  13043. WOLFSSL_METHOD* wolfTLSv1_3_method_ex(void* heap)
  13044. {
  13045. WOLFSSL_METHOD* m;
  13046. WOLFSSL_ENTER("TLSv1_3_method");
  13047. #ifndef NO_WOLFSSL_CLIENT
  13048. m = wolfTLSv1_3_client_method_ex(heap);
  13049. #else
  13050. m = wolfTLSv1_3_server_method_ex(heap);
  13051. #endif
  13052. if (m != NULL) {
  13053. m->side = WOLFSSL_NEITHER_END;
  13054. }
  13055. return m;
  13056. }
  13057. #endif /* WOLFSSL_TLS13 */
  13058. #ifdef WOLFSSL_DTLS
  13059. WOLFSSL_METHOD* wolfDTLS_method(void)
  13060. {
  13061. return wolfDTLS_method_ex(NULL);
  13062. }
  13063. WOLFSSL_METHOD* wolfDTLS_method_ex(void* heap)
  13064. {
  13065. WOLFSSL_METHOD* m;
  13066. WOLFSSL_ENTER("DTLS_method_ex");
  13067. #ifndef NO_WOLFSSL_CLIENT
  13068. m = wolfDTLS_client_method_ex(heap);
  13069. #else
  13070. m = wolfDTLS_server_method_ex(heap);
  13071. #endif
  13072. if (m != NULL) {
  13073. m->side = WOLFSSL_NEITHER_END;
  13074. }
  13075. return m;
  13076. }
  13077. #ifndef NO_OLD_TLS
  13078. WOLFSSL_METHOD* wolfDTLSv1_method(void)
  13079. {
  13080. return wolfDTLSv1_method_ex(NULL);
  13081. }
  13082. WOLFSSL_METHOD* wolfDTLSv1_method_ex(void* heap)
  13083. {
  13084. WOLFSSL_METHOD* m;
  13085. WOLFSSL_ENTER("DTLSv1_method_ex");
  13086. #ifndef NO_WOLFSSL_CLIENT
  13087. m = wolfDTLSv1_client_method_ex(heap);
  13088. #else
  13089. m = wolfDTLSv1_server_method_ex(heap);
  13090. #endif
  13091. if (m != NULL) {
  13092. m->side = WOLFSSL_NEITHER_END;
  13093. }
  13094. return m;
  13095. }
  13096. #endif /* !NO_OLD_TLS */
  13097. #ifndef WOLFSSL_NO_TLS12
  13098. WOLFSSL_METHOD* wolfDTLSv1_2_method(void)
  13099. {
  13100. return wolfDTLSv1_2_method_ex(NULL);
  13101. }
  13102. WOLFSSL_METHOD* wolfDTLSv1_2_method_ex(void* heap)
  13103. {
  13104. WOLFSSL_METHOD* m;
  13105. WOLFSSL_ENTER("DTLSv1_2_method");
  13106. #ifndef NO_WOLFSSL_CLIENT
  13107. m = wolfDTLSv1_2_client_method_ex(heap);
  13108. #else
  13109. m = wolfDTLSv1_2_server_method_ex(heap);
  13110. #endif
  13111. if (m != NULL) {
  13112. m->side = WOLFSSL_NEITHER_END;
  13113. }
  13114. return m;
  13115. }
  13116. #endif /* !WOLFSSL_NO_TLS12 */
  13117. #endif /* WOLFSSL_DTLS */
  13118. #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
  13119. #ifndef NO_WOLFSSL_SERVER
  13120. WOLFSSL_METHOD* wolfTLS_server_method(void)
  13121. {
  13122. return wolfTLS_server_method_ex(NULL);
  13123. }
  13124. WOLFSSL_METHOD* wolfTLS_server_method_ex(void* heap)
  13125. {
  13126. WOLFSSL_METHOD* method =
  13127. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13128. heap, DYNAMIC_TYPE_METHOD);
  13129. (void)heap;
  13130. WOLFSSL_ENTER("TLS_server_method_ex");
  13131. if (method) {
  13132. #if defined(WOLFSSL_TLS13)
  13133. InitSSL_Method(method, MakeTLSv1_3());
  13134. #elif !defined(WOLFSSL_NO_TLS12)
  13135. InitSSL_Method(method, MakeTLSv1_2());
  13136. #elif !defined(NO_OLD_TLS)
  13137. InitSSL_Method(method, MakeTLSv1_1());
  13138. #elif defined(WOLFSSL_ALLOW_TLSV10)
  13139. InitSSL_Method(method, MakeTLSv1());
  13140. #else
  13141. #error No TLS version enabled!
  13142. #endif
  13143. method->downgrade = 1;
  13144. method->side = WOLFSSL_SERVER_END;
  13145. }
  13146. return method;
  13147. }
  13148. #ifndef NO_OLD_TLS
  13149. #ifdef WOLFSSL_ALLOW_TLSV10
  13150. WOLFSSL_METHOD* wolfTLSv1_server_method(void)
  13151. {
  13152. return wolfTLSv1_server_method_ex(NULL);
  13153. }
  13154. WOLFSSL_METHOD* wolfTLSv1_server_method_ex(void* heap)
  13155. {
  13156. WOLFSSL_METHOD* method =
  13157. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13158. heap, DYNAMIC_TYPE_METHOD);
  13159. (void)heap;
  13160. WOLFSSL_ENTER("TLSv1_server_method_ex");
  13161. if (method) {
  13162. InitSSL_Method(method, MakeTLSv1());
  13163. method->side = WOLFSSL_SERVER_END;
  13164. }
  13165. return method;
  13166. }
  13167. #endif /* WOLFSSL_ALLOW_TLSV10 */
  13168. WOLFSSL_METHOD* wolfTLSv1_1_server_method(void)
  13169. {
  13170. return wolfTLSv1_1_server_method_ex(NULL);
  13171. }
  13172. WOLFSSL_METHOD* wolfTLSv1_1_server_method_ex(void* heap)
  13173. {
  13174. WOLFSSL_METHOD* method =
  13175. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13176. heap, DYNAMIC_TYPE_METHOD);
  13177. (void)heap;
  13178. WOLFSSL_ENTER("TLSv1_1_server_method_ex");
  13179. if (method) {
  13180. InitSSL_Method(method, MakeTLSv1_1());
  13181. method->side = WOLFSSL_SERVER_END;
  13182. }
  13183. return method;
  13184. }
  13185. #endif /* !NO_OLD_TLS */
  13186. #ifndef WOLFSSL_NO_TLS12
  13187. WOLFSSL_ABI
  13188. WOLFSSL_METHOD* wolfTLSv1_2_server_method(void)
  13189. {
  13190. return wolfTLSv1_2_server_method_ex(NULL);
  13191. }
  13192. WOLFSSL_METHOD* wolfTLSv1_2_server_method_ex(void* heap)
  13193. {
  13194. WOLFSSL_METHOD* method =
  13195. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13196. heap, DYNAMIC_TYPE_METHOD);
  13197. (void)heap;
  13198. WOLFSSL_ENTER("TLSv1_2_server_method_ex");
  13199. if (method) {
  13200. InitSSL_Method(method, MakeTLSv1_2());
  13201. method->side = WOLFSSL_SERVER_END;
  13202. }
  13203. return method;
  13204. }
  13205. #endif /* !WOLFSSL_NO_TLS12 */
  13206. #ifdef WOLFSSL_TLS13
  13207. /* The TLS v1.3 server method data.
  13208. *
  13209. * returns the method data for a TLS v1.3 server.
  13210. */
  13211. WOLFSSL_ABI
  13212. WOLFSSL_METHOD* wolfTLSv1_3_server_method(void)
  13213. {
  13214. return wolfTLSv1_3_server_method_ex(NULL);
  13215. }
  13216. /* The TLS v1.3 server method data.
  13217. *
  13218. * heap The heap used for allocation.
  13219. * returns the method data for a TLS v1.3 server.
  13220. */
  13221. WOLFSSL_METHOD* wolfTLSv1_3_server_method_ex(void* heap)
  13222. {
  13223. WOLFSSL_METHOD* method =
  13224. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13225. heap, DYNAMIC_TYPE_METHOD);
  13226. (void)heap;
  13227. WOLFSSL_ENTER("TLSv1_3_server_method_ex");
  13228. if (method) {
  13229. InitSSL_Method(method, MakeTLSv1_3());
  13230. method->side = WOLFSSL_SERVER_END;
  13231. }
  13232. return method;
  13233. }
  13234. #endif /* WOLFSSL_TLS13 */
  13235. #ifdef WOLFSSL_DTLS
  13236. WOLFSSL_METHOD* wolfDTLS_server_method(void)
  13237. {
  13238. return wolfDTLS_server_method_ex(NULL);
  13239. }
  13240. WOLFSSL_METHOD* wolfDTLS_server_method_ex(void* heap)
  13241. {
  13242. WOLFSSL_METHOD* method =
  13243. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13244. heap, DYNAMIC_TYPE_METHOD);
  13245. (void)heap;
  13246. WOLFSSL_ENTER("DTLS_server_method_ex");
  13247. if (method) {
  13248. #if defined(WOLFSSL_DTLS13)
  13249. InitSSL_Method(method, MakeDTLSv1_3());
  13250. #elif !defined(WOLFSSL_NO_TLS12)
  13251. InitSSL_Method(method, MakeDTLSv1_2());
  13252. #elif !defined(NO_OLD_TLS)
  13253. InitSSL_Method(method, MakeDTLSv1());
  13254. #else
  13255. #error No DTLS version enabled!
  13256. #endif
  13257. method->downgrade = 1;
  13258. method->side = WOLFSSL_SERVER_END;
  13259. }
  13260. return method;
  13261. }
  13262. #ifndef NO_OLD_TLS
  13263. WOLFSSL_METHOD* wolfDTLSv1_server_method(void)
  13264. {
  13265. return wolfDTLSv1_server_method_ex(NULL);
  13266. }
  13267. WOLFSSL_METHOD* wolfDTLSv1_server_method_ex(void* heap)
  13268. {
  13269. WOLFSSL_METHOD* method =
  13270. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13271. heap, DYNAMIC_TYPE_METHOD);
  13272. (void)heap;
  13273. WOLFSSL_ENTER("DTLSv1_server_method_ex");
  13274. if (method) {
  13275. InitSSL_Method(method, MakeDTLSv1());
  13276. method->side = WOLFSSL_SERVER_END;
  13277. }
  13278. return method;
  13279. }
  13280. #endif /* !NO_OLD_TLS */
  13281. #ifndef WOLFSSL_NO_TLS12
  13282. WOLFSSL_METHOD* wolfDTLSv1_2_server_method(void)
  13283. {
  13284. return wolfDTLSv1_2_server_method_ex(NULL);
  13285. }
  13286. WOLFSSL_METHOD* wolfDTLSv1_2_server_method_ex(void* heap)
  13287. {
  13288. WOLFSSL_METHOD* method =
  13289. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13290. heap, DYNAMIC_TYPE_METHOD);
  13291. WOLFSSL_ENTER("DTLSv1_2_server_method_ex");
  13292. (void)heap;
  13293. if (method) {
  13294. InitSSL_Method(method, MakeDTLSv1_2());
  13295. method->side = WOLFSSL_SERVER_END;
  13296. }
  13297. (void)heap;
  13298. return method;
  13299. }
  13300. #endif /* !WOLFSSL_NO_TLS12 */
  13301. #endif /* WOLFSSL_DTLS */
  13302. #endif /* NO_WOLFSSL_SERVER */
  13303. #endif /* NO_TLS */
  13304. #endif /* WOLFCRYPT_ONLY */