tls.c 474 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468
  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. if (handshake_hash == NULL)
  160. return MEMORY_E;
  161. #endif
  162. XMEMSET(handshake_hash, 0, HSHASH_SZ);
  163. ret = BuildTlsHandshakeHash(ssl, handshake_hash, &hashSz);
  164. if (ret == 0) {
  165. if (XSTRNCMP((const char*)sender, (const char*)kTlsClientStr,
  166. SIZEOF_SENDER) == 0) {
  167. side = kTlsClientFinStr;
  168. }
  169. else if (XSTRNCMP((const char*)sender, (const char*)kTlsServerStr,
  170. SIZEOF_SENDER) == 0) {
  171. side = kTlsServerFinStr;
  172. }
  173. else {
  174. ret = BAD_FUNC_ARG;
  175. WOLFSSL_MSG("Unexpected sender value");
  176. }
  177. }
  178. if (ret == 0) {
  179. #ifdef WOLFSSL_HAVE_PRF
  180. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  181. if (ssl->ctx->TlsFinishedCb) {
  182. void* ctx = wolfSSL_GetTlsFinishedCtx(ssl);
  183. ret = ssl->ctx->TlsFinishedCb(ssl, side, handshake_hash, hashSz,
  184. (byte*)hashes, ctx);
  185. }
  186. if (!ssl->ctx->TlsFinishedCb || ret == PROTOCOLCB_UNAVAILABLE)
  187. #endif
  188. {
  189. PRIVATE_KEY_UNLOCK();
  190. ret = wc_PRF_TLS((byte*)hashes, TLS_FINISHED_SZ,
  191. ssl->arrays->masterSecret, SECRET_LEN, side,
  192. FINISHED_LABEL_SZ, handshake_hash, hashSz,
  193. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  194. ssl->heap, ssl->devId);
  195. PRIVATE_KEY_LOCK();
  196. }
  197. ForceZero(handshake_hash, hashSz);
  198. #else
  199. /* Pseudo random function must be enabled in the configuration. */
  200. ret = PRF_MISSING;
  201. WOLFSSL_ERROR_VERBOSE(ret);
  202. WOLFSSL_MSG("Pseudo-random function is not enabled");
  203. (void)side;
  204. (void)hashes;
  205. #endif
  206. }
  207. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  208. WC_FREE_VAR(handshake_hash, ssl->heap);
  209. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  210. wc_MemZero_Check(handshake_hash, HSHASH_SZ);
  211. #endif
  212. return ret;
  213. }
  214. #endif /* !WOLFSSL_NO_TLS12 */
  215. #ifndef NO_OLD_TLS
  216. #ifdef WOLFSSL_ALLOW_TLSV10
  217. ProtocolVersion MakeTLSv1(void)
  218. {
  219. ProtocolVersion pv;
  220. pv.major = SSLv3_MAJOR;
  221. pv.minor = TLSv1_MINOR;
  222. return pv;
  223. }
  224. #endif /* WOLFSSL_ALLOW_TLSV10 */
  225. ProtocolVersion MakeTLSv1_1(void)
  226. {
  227. ProtocolVersion pv;
  228. pv.major = SSLv3_MAJOR;
  229. pv.minor = TLSv1_1_MINOR;
  230. return pv;
  231. }
  232. #endif /* !NO_OLD_TLS */
  233. #ifndef WOLFSSL_NO_TLS12
  234. ProtocolVersion MakeTLSv1_2(void)
  235. {
  236. ProtocolVersion pv;
  237. pv.major = SSLv3_MAJOR;
  238. pv.minor = TLSv1_2_MINOR;
  239. return pv;
  240. }
  241. #endif /* !WOLFSSL_NO_TLS12 */
  242. #ifdef WOLFSSL_TLS13
  243. /* The TLS v1.3 protocol version.
  244. *
  245. * returns the protocol version data for TLS v1.3.
  246. */
  247. ProtocolVersion MakeTLSv1_3(void)
  248. {
  249. ProtocolVersion pv;
  250. pv.major = SSLv3_MAJOR;
  251. pv.minor = TLSv1_3_MINOR;
  252. return pv;
  253. }
  254. #endif
  255. #ifndef WOLFSSL_NO_TLS12
  256. #ifdef HAVE_EXTENDED_MASTER
  257. static const byte ext_master_label[EXT_MASTER_LABEL_SZ + 1] =
  258. "extended master secret";
  259. #endif
  260. static const byte master_label[MASTER_LABEL_SZ + 1] = "master secret";
  261. static const byte key_label [KEY_LABEL_SZ + 1] = "key expansion";
  262. static int _DeriveTlsKeys(byte* key_dig, word32 key_dig_len,
  263. const byte* ms, word32 msLen,
  264. const byte* sr, const byte* cr,
  265. int tls1_2, int hash_type,
  266. void* heap, int devId)
  267. {
  268. int ret;
  269. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  270. WC_DECLARE_VAR(seed, byte, SEED_LEN, heap);
  271. if (seed == NULL)
  272. return MEMORY_E;
  273. #else
  274. byte seed[SEED_LEN];
  275. #endif
  276. XMEMCPY(seed, sr, RAN_LEN);
  277. XMEMCPY(seed + RAN_LEN, cr, RAN_LEN);
  278. #ifdef WOLFSSL_HAVE_PRF
  279. PRIVATE_KEY_UNLOCK();
  280. ret = wc_PRF_TLS(key_dig, key_dig_len, ms, msLen, key_label, KEY_LABEL_SZ,
  281. seed, SEED_LEN, tls1_2, hash_type, heap, devId);
  282. PRIVATE_KEY_LOCK();
  283. #else
  284. /* Pseudo random function must be enabled in the configuration. */
  285. ret = PRF_MISSING;
  286. WOLFSSL_ERROR_VERBOSE(ret);
  287. WOLFSSL_MSG("Pseudo-random function is not enabled");
  288. (void)key_dig;
  289. (void)key_dig_len;
  290. (void)ms;
  291. (void)msLen;
  292. (void)tls1_2;
  293. (void)hash_type;
  294. (void)heap;
  295. (void)devId;
  296. (void)key_label;
  297. (void)master_label;
  298. #ifdef HAVE_EXTENDED_MASTER
  299. (void)ext_master_label;
  300. #endif
  301. #endif
  302. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  303. WC_FREE_VAR(seed, heap);
  304. #endif
  305. return ret;
  306. }
  307. /* External facing wrapper so user can call as well, 0 on success */
  308. int wolfSSL_DeriveTlsKeys(byte* key_dig, word32 key_dig_len,
  309. const byte* ms, word32 msLen,
  310. const byte* sr, const byte* cr,
  311. int tls1_2, int hash_type)
  312. {
  313. return _DeriveTlsKeys(key_dig, key_dig_len, ms, msLen, sr, cr, tls1_2,
  314. hash_type, NULL, INVALID_DEVID);
  315. }
  316. int DeriveTlsKeys(WOLFSSL* ssl)
  317. {
  318. int ret;
  319. int key_dig_len = 2 * ssl->specs.hash_size +
  320. 2 * ssl->specs.key_size +
  321. 2 * ssl->specs.iv_size;
  322. #ifdef WOLFSSL_SMALL_STACK
  323. byte* key_dig;
  324. #else
  325. byte key_dig[MAX_PRF_DIG];
  326. #endif
  327. #ifdef WOLFSSL_SMALL_STACK
  328. key_dig = (byte*)XMALLOC(MAX_PRF_DIG, ssl->heap, DYNAMIC_TYPE_DIGEST);
  329. if (key_dig == NULL) {
  330. return MEMORY_E;
  331. }
  332. #endif
  333. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  334. ret = PROTOCOLCB_UNAVAILABLE;
  335. if (ssl->ctx->GenSessionKeyCb) {
  336. void* ctx = wolfSSL_GetGenSessionKeyCtx(ssl);
  337. ret = ssl->ctx->GenSessionKeyCb(ssl, ctx);
  338. }
  339. if (!ssl->ctx->GenSessionKeyCb || ret == PROTOCOLCB_UNAVAILABLE)
  340. #endif
  341. ret = _DeriveTlsKeys(key_dig, key_dig_len,
  342. ssl->arrays->masterSecret, SECRET_LEN,
  343. ssl->arrays->serverRandom, ssl->arrays->clientRandom,
  344. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  345. ssl->heap, ssl->devId);
  346. if (ret == 0)
  347. ret = StoreKeys(ssl, key_dig, PROVISION_CLIENT_SERVER);
  348. #ifdef WOLFSSL_SMALL_STACK
  349. XFREE(key_dig, ssl->heap, DYNAMIC_TYPE_DIGEST);
  350. #endif
  351. return ret;
  352. }
  353. static int _MakeTlsMasterSecret(byte* ms, word32 msLen,
  354. const byte* pms, word32 pmsLen,
  355. const byte* cr, const byte* sr,
  356. int tls1_2, int hash_type,
  357. void* heap, int devId)
  358. {
  359. int ret;
  360. #if !defined(WOLFSSL_ASYNC_CRYPT) || defined(WC_ASYNC_NO_HASH)
  361. byte seed[SEED_LEN];
  362. #else
  363. WC_DECLARE_VAR(seed, byte, SEED_LEN, heap);
  364. if (seed == NULL)
  365. return MEMORY_E;
  366. #endif
  367. XMEMCPY(seed, cr, RAN_LEN);
  368. XMEMCPY(seed + RAN_LEN, sr, RAN_LEN);
  369. #ifdef WOLFSSL_HAVE_PRF
  370. PRIVATE_KEY_UNLOCK();
  371. ret = wc_PRF_TLS(ms, msLen, pms, pmsLen, master_label, MASTER_LABEL_SZ,
  372. seed, SEED_LEN, tls1_2, hash_type, heap, devId);
  373. PRIVATE_KEY_LOCK();
  374. #else
  375. /* Pseudo random function must be enabled in the configuration. */
  376. ret = PRF_MISSING;
  377. WOLFSSL_MSG("Pseudo-random function is not enabled");
  378. (void)ms;
  379. (void)msLen;
  380. (void)pms;
  381. (void)pmsLen;
  382. (void)tls1_2;
  383. (void)hash_type;
  384. (void)heap;
  385. (void)devId;
  386. #endif
  387. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  388. WC_FREE_VAR(seed, heap);
  389. #endif
  390. return ret;
  391. }
  392. /* External facing wrapper so user can call as well, 0 on success */
  393. int wolfSSL_MakeTlsMasterSecret(byte* ms, word32 msLen,
  394. const byte* pms, word32 pmsLen,
  395. const byte* cr, const byte* sr,
  396. int tls1_2, int hash_type)
  397. {
  398. return _MakeTlsMasterSecret(ms, msLen, pms, pmsLen, cr, sr, tls1_2,
  399. hash_type, NULL, INVALID_DEVID);
  400. }
  401. #ifdef HAVE_EXTENDED_MASTER
  402. static int _MakeTlsExtendedMasterSecret(byte* ms, word32 msLen,
  403. const byte* pms, word32 pmsLen,
  404. const byte* sHash, word32 sHashLen,
  405. int tls1_2, int hash_type,
  406. void* heap, int devId)
  407. {
  408. int ret;
  409. #ifdef WOLFSSL_HAVE_PRF
  410. PRIVATE_KEY_UNLOCK();
  411. ret = wc_PRF_TLS(ms, msLen, pms, pmsLen, ext_master_label, EXT_MASTER_LABEL_SZ,
  412. sHash, sHashLen, tls1_2, hash_type, heap, devId);
  413. PRIVATE_KEY_LOCK();
  414. #else
  415. /* Pseudo random function must be enabled in the configuration. */
  416. ret = PRF_MISSING;
  417. WOLFSSL_MSG("Pseudo-random function is not enabled");
  418. (void)ms;
  419. (void)msLen;
  420. (void)pms;
  421. (void)pmsLen;
  422. (void)sHash;
  423. (void)sHashLen;
  424. (void)tls1_2;
  425. (void)hash_type;
  426. (void)heap;
  427. (void)devId;
  428. #endif
  429. return ret;
  430. }
  431. /* External facing wrapper so user can call as well, 0 on success */
  432. int wolfSSL_MakeTlsExtendedMasterSecret(byte* ms, word32 msLen,
  433. const byte* pms, word32 pmsLen,
  434. const byte* sHash, word32 sHashLen,
  435. int tls1_2, int hash_type)
  436. {
  437. return _MakeTlsExtendedMasterSecret(ms, msLen, pms, pmsLen, sHash, sHashLen,
  438. tls1_2, hash_type, NULL, INVALID_DEVID);
  439. }
  440. #endif /* HAVE_EXTENDED_MASTER */
  441. int MakeTlsMasterSecret(WOLFSSL* ssl)
  442. {
  443. int ret;
  444. #if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  445. /* If this is called from a sniffer session with keylog file support, obtain
  446. * the master secret from the callback */
  447. if (ssl->snifferSecretCb != NULL) {
  448. ret = ssl->snifferSecretCb(ssl->arrays->clientRandom,
  449. SNIFFER_SECRET_TLS12_MASTER_SECRET,
  450. ssl->arrays->masterSecret);
  451. if (ret != 0) {
  452. return ret;
  453. }
  454. ret = DeriveTlsKeys(ssl);
  455. return ret;
  456. }
  457. #endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
  458. #ifdef HAVE_EXTENDED_MASTER
  459. if (ssl->options.haveEMS) {
  460. word32 hashSz = HSHASH_SZ;
  461. #ifdef WOLFSSL_SMALL_STACK
  462. byte* handshake_hash = (byte*)XMALLOC(HSHASH_SZ, ssl->heap,
  463. DYNAMIC_TYPE_DIGEST);
  464. if (handshake_hash == NULL)
  465. return MEMORY_E;
  466. #else
  467. byte handshake_hash[HSHASH_SZ];
  468. #endif
  469. XMEMSET(handshake_hash, 0, HSHASH_SZ);
  470. ret = BuildTlsHandshakeHash(ssl, handshake_hash, &hashSz);
  471. if (ret == 0) {
  472. ret = _MakeTlsExtendedMasterSecret(
  473. ssl->arrays->masterSecret, SECRET_LEN,
  474. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz,
  475. handshake_hash, hashSz,
  476. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  477. ssl->heap, ssl->devId);
  478. ForceZero(handshake_hash, hashSz);
  479. }
  480. #ifdef WOLFSSL_SMALL_STACK
  481. XFREE(handshake_hash, ssl->heap, DYNAMIC_TYPE_DIGEST);
  482. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  483. wc_MemZero_Check(handshake_hash, HSHASH_SZ);
  484. #endif
  485. }
  486. else
  487. #endif /* HAVE_EXTENDED_MASTER */
  488. {
  489. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  490. ret = PROTOCOLCB_UNAVAILABLE;
  491. if (ssl->ctx->GenMasterCb) {
  492. void* ctx = wolfSSL_GetGenMasterSecretCtx(ssl);
  493. ret = ssl->ctx->GenMasterCb(ssl, ctx);
  494. }
  495. if (!ssl->ctx->GenMasterCb || ret == PROTOCOLCB_UNAVAILABLE)
  496. #endif
  497. {
  498. ret = _MakeTlsMasterSecret(ssl->arrays->masterSecret,
  499. SECRET_LEN, ssl->arrays->preMasterSecret,
  500. ssl->arrays->preMasterSz, ssl->arrays->clientRandom,
  501. ssl->arrays->serverRandom, IsAtLeastTLSv1_2(ssl),
  502. ssl->specs.mac_algorithm, ssl->heap, ssl->devId);
  503. }
  504. }
  505. if (ret == 0) {
  506. #ifdef SHOW_SECRETS
  507. /* Wireshark Pre-Master-Secret Format:
  508. * CLIENT_RANDOM <clientrandom> <mastersecret>
  509. */
  510. const char* CLIENT_RANDOM_LABEL = "CLIENT_RANDOM";
  511. int i, pmsPos = 0;
  512. char pmsBuf[13 + 1 + 64 + 1 + 96 + 1 + 1];
  513. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%s ",
  514. CLIENT_RANDOM_LABEL);
  515. pmsPos += XSTRLEN(CLIENT_RANDOM_LABEL) + 1;
  516. for (i = 0; i < RAN_LEN; i++) {
  517. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
  518. ssl->arrays->clientRandom[i]);
  519. pmsPos += 2;
  520. }
  521. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, " ");
  522. pmsPos += 1;
  523. for (i = 0; i < SECRET_LEN; i++) {
  524. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
  525. ssl->arrays->masterSecret[i]);
  526. pmsPos += 2;
  527. }
  528. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "\n");
  529. pmsPos += 1;
  530. /* print master secret */
  531. puts(pmsBuf);
  532. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE)
  533. {
  534. FILE* f = XFOPEN(WOLFSSL_SSLKEYLOGFILE_OUTPUT, "a");
  535. if (f != XBADFILE) {
  536. XFWRITE(pmsBuf, 1, pmsPos, f);
  537. XFCLOSE(f);
  538. }
  539. }
  540. #endif
  541. #endif /* SHOW_SECRETS */
  542. ret = DeriveTlsKeys(ssl);
  543. }
  544. return ret;
  545. }
  546. /* Used by EAP-TLS and EAP-TTLS to derive keying material from
  547. * the master_secret. */
  548. int wolfSSL_make_eap_keys(WOLFSSL* ssl, void* msk, unsigned int len,
  549. const char* label)
  550. {
  551. int ret;
  552. #ifdef WOLFSSL_SMALL_STACK
  553. byte* seed;
  554. #else
  555. byte seed[SEED_LEN];
  556. #endif
  557. #ifdef WOLFSSL_SMALL_STACK
  558. seed = (byte*)XMALLOC(SEED_LEN, ssl->heap, DYNAMIC_TYPE_SEED);
  559. if (seed == NULL)
  560. return MEMORY_E;
  561. #endif
  562. /*
  563. * As per RFC-5281, the order of the client and server randoms is reversed
  564. * from that used by the TLS protocol to derive keys.
  565. */
  566. XMEMCPY(seed, ssl->arrays->clientRandom, RAN_LEN);
  567. XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
  568. #ifdef WOLFSSL_HAVE_PRF
  569. PRIVATE_KEY_UNLOCK();
  570. ret = wc_PRF_TLS((byte*)msk, len, ssl->arrays->masterSecret, SECRET_LEN,
  571. (const byte *)label, (word32)XSTRLEN(label), seed, SEED_LEN,
  572. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  573. ssl->heap, ssl->devId);
  574. PRIVATE_KEY_LOCK();
  575. #else
  576. /* Pseudo random function must be enabled in the configuration. */
  577. ret = PRF_MISSING;
  578. WOLFSSL_MSG("Pseudo-random function is not enabled");
  579. (void)msk;
  580. (void)len;
  581. (void)label;
  582. #endif
  583. #ifdef WOLFSSL_SMALL_STACK
  584. XFREE(seed, ssl->heap, DYNAMIC_TYPE_SEED);
  585. #endif
  586. return ret;
  587. }
  588. /* return HMAC digest type in wolfSSL format */
  589. int wolfSSL_GetHmacType(WOLFSSL* ssl)
  590. {
  591. if (ssl == NULL)
  592. return BAD_FUNC_ARG;
  593. return wolfSSL_GetHmacType_ex(&ssl->specs);
  594. }
  595. int wolfSSL_SetTlsHmacInner(WOLFSSL* ssl, byte* inner, word32 sz, int content,
  596. int verify)
  597. {
  598. if (ssl == NULL || inner == NULL)
  599. return BAD_FUNC_ARG;
  600. XMEMSET(inner, 0, WOLFSSL_TLS_HMAC_INNER_SZ);
  601. WriteSEQ(ssl, verify, inner);
  602. inner[SEQ_SZ] = (byte)content;
  603. inner[SEQ_SZ + ENUM_LEN] = ssl->version.major;
  604. inner[SEQ_SZ + ENUM_LEN + ENUM_LEN] = ssl->version.minor;
  605. c16toa((word16)sz, inner + SEQ_SZ + ENUM_LEN + VERSION_SZ);
  606. return 0;
  607. }
  608. #ifndef WOLFSSL_AEAD_ONLY
  609. #if !defined(WOLFSSL_NO_HASH_RAW) && !defined(HAVE_FIPS) && \
  610. !defined(HAVE_SELFTEST)
  611. /* Update the hash in the HMAC.
  612. *
  613. * hmac HMAC object.
  614. * data Data to be hashed.
  615. * sz Size of data to hash.
  616. * returns 0 on success, otherwise failure.
  617. */
  618. static int Hmac_HashUpdate(Hmac* hmac, const byte* data, word32 sz)
  619. {
  620. int ret = BAD_FUNC_ARG;
  621. switch (hmac->macType) {
  622. #ifndef NO_SHA
  623. case WC_SHA:
  624. ret = wc_ShaUpdate(&hmac->hash.sha, data, sz);
  625. break;
  626. #endif /* !NO_SHA */
  627. #ifndef NO_SHA256
  628. case WC_SHA256:
  629. ret = wc_Sha256Update(&hmac->hash.sha256, data, sz);
  630. break;
  631. #endif /* !NO_SHA256 */
  632. #ifdef WOLFSSL_SHA384
  633. case WC_SHA384:
  634. ret = wc_Sha384Update(&hmac->hash.sha384, data, sz);
  635. break;
  636. #endif /* WOLFSSL_SHA384 */
  637. #ifdef WOLFSSL_SHA512
  638. case WC_SHA512:
  639. ret = wc_Sha512Update(&hmac->hash.sha512, data, sz);
  640. break;
  641. #endif /* WOLFSSL_SHA512 */
  642. #ifdef WOLFSSL_SM3
  643. case WC_SM3:
  644. ret = wc_Sm3Update(&hmac->hash.sm3, data, sz);
  645. break;
  646. #endif /* WOLFSSL_SM3 */
  647. default:
  648. break;
  649. }
  650. return ret;
  651. }
  652. /* Finalize the hash but don't put the EOC, padding or length in.
  653. *
  654. * hmac HMAC object.
  655. * hash Hash result.
  656. * returns 0 on success, otherwise failure.
  657. */
  658. static int Hmac_HashFinalRaw(Hmac* hmac, unsigned char* hash)
  659. {
  660. int ret = BAD_FUNC_ARG;
  661. switch (hmac->macType) {
  662. #ifndef NO_SHA
  663. case WC_SHA:
  664. ret = wc_ShaFinalRaw(&hmac->hash.sha, hash);
  665. break;
  666. #endif /* !NO_SHA */
  667. #ifndef NO_SHA256
  668. case WC_SHA256:
  669. ret = wc_Sha256FinalRaw(&hmac->hash.sha256, hash);
  670. break;
  671. #endif /* !NO_SHA256 */
  672. #ifdef WOLFSSL_SHA384
  673. case WC_SHA384:
  674. ret = wc_Sha384FinalRaw(&hmac->hash.sha384, hash);
  675. break;
  676. #endif /* WOLFSSL_SHA384 */
  677. #ifdef WOLFSSL_SHA512
  678. case WC_SHA512:
  679. ret = wc_Sha512FinalRaw(&hmac->hash.sha512, hash);
  680. break;
  681. #endif /* WOLFSSL_SHA512 */
  682. #ifdef WOLFSSL_SM3
  683. case WC_SM3:
  684. ret = wc_Sm3FinalRaw(&hmac->hash.sm3, hash);
  685. break;
  686. #endif /* WOLFSSL_SM3 */
  687. default:
  688. break;
  689. }
  690. return ret;
  691. }
  692. /* Finalize the HMAC by performing outer hash.
  693. *
  694. * hmac HMAC object.
  695. * mac MAC result.
  696. * returns 0 on success, otherwise failure.
  697. */
  698. static int Hmac_OuterHash(Hmac* hmac, unsigned char* mac)
  699. {
  700. int ret = BAD_FUNC_ARG;
  701. wc_HashAlg hash;
  702. enum wc_HashType hashType = (enum wc_HashType)hmac->macType;
  703. int digestSz = wc_HashGetDigestSize(hashType);
  704. int blockSz = wc_HashGetBlockSize(hashType);
  705. if ((digestSz >= 0) && (blockSz >= 0)) {
  706. ret = wc_HashInit(&hash, hashType);
  707. }
  708. if (ret == 0) {
  709. ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->opad,
  710. blockSz);
  711. if (ret == 0)
  712. ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->innerHash,
  713. digestSz);
  714. if (ret == 0)
  715. ret = wc_HashFinal(&hash, hashType, mac);
  716. wc_HashFree(&hash, hashType);
  717. }
  718. return ret;
  719. }
  720. /* Calculate the HMAC of the header + message data.
  721. * Constant time implementation using wc_Sha*FinalRaw().
  722. *
  723. * hmac HMAC object.
  724. * digest MAC result.
  725. * in Message data.
  726. * sz Size of the message data.
  727. * header Constructed record header with length of handshake data.
  728. * returns 0 on success, otherwise failure.
  729. */
  730. static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in,
  731. word32 sz, int macLen, byte* header)
  732. {
  733. byte lenBytes[8];
  734. int i, j;
  735. unsigned int k;
  736. int blockBits, blockMask;
  737. int lastBlockLen, extraLen, eocIndex;
  738. int blocks, safeBlocks, lenBlock, eocBlock;
  739. unsigned int maxLen;
  740. int blockSz, padSz;
  741. int ret;
  742. word32 realLen;
  743. byte extraBlock;
  744. switch (hmac->macType) {
  745. #ifndef NO_SHA
  746. case WC_SHA:
  747. blockSz = WC_SHA_BLOCK_SIZE;
  748. blockBits = 6;
  749. padSz = WC_SHA_BLOCK_SIZE - WC_SHA_PAD_SIZE + 1;
  750. break;
  751. #endif /* !NO_SHA */
  752. #ifndef NO_SHA256
  753. case WC_SHA256:
  754. blockSz = WC_SHA256_BLOCK_SIZE;
  755. blockBits = 6;
  756. padSz = WC_SHA256_BLOCK_SIZE - WC_SHA256_PAD_SIZE + 1;
  757. break;
  758. #endif /* !NO_SHA256 */
  759. #ifdef WOLFSSL_SHA384
  760. case WC_SHA384:
  761. blockSz = WC_SHA384_BLOCK_SIZE;
  762. blockBits = 7;
  763. padSz = WC_SHA384_BLOCK_SIZE - WC_SHA384_PAD_SIZE + 1;
  764. break;
  765. #endif /* WOLFSSL_SHA384 */
  766. #ifdef WOLFSSL_SHA512
  767. case WC_SHA512:
  768. blockSz = WC_SHA512_BLOCK_SIZE;
  769. blockBits = 7;
  770. padSz = WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE + 1;
  771. break;
  772. #endif /* WOLFSSL_SHA512 */
  773. #ifdef WOLFSSL_SM3
  774. case WC_SM3:
  775. blockSz = WC_SM3_BLOCK_SIZE;
  776. blockBits = 6;
  777. padSz = WC_SM3_BLOCK_SIZE - WC_SM3_PAD_SIZE + 1;
  778. break;
  779. #endif /* WOLFSSL_SM3 */
  780. default:
  781. return BAD_FUNC_ARG;
  782. }
  783. blockMask = blockSz - 1;
  784. /* Size of data to HMAC if padding length byte is zero. */
  785. maxLen = WOLFSSL_TLS_HMAC_INNER_SZ + sz - 1 - macLen;
  786. /* Complete data (including padding) has block for EOC and/or length. */
  787. extraBlock = ctSetLTE((maxLen + padSz) & blockMask, padSz);
  788. /* Total number of blocks for data including padding. */
  789. blocks = ((maxLen + blockSz - 1) >> blockBits) + extraBlock;
  790. /* Up to last 6 blocks can be hashed safely. */
  791. safeBlocks = blocks - 6;
  792. /* Length of message data. */
  793. realLen = maxLen - in[sz - 1];
  794. /* Number of message bytes in last block. */
  795. lastBlockLen = realLen & blockMask;
  796. /* Number of padding bytes in last block. */
  797. extraLen = ((blockSz * 2 - padSz - lastBlockLen) & blockMask) + 1;
  798. /* Number of blocks to create for hash. */
  799. lenBlock = (realLen + extraLen) >> blockBits;
  800. /* Block containing EOC byte. */
  801. eocBlock = realLen >> blockBits;
  802. /* Index of EOC byte in block. */
  803. eocIndex = realLen & blockMask;
  804. /* Add length of hmac's ipad to total length. */
  805. realLen += blockSz;
  806. /* Length as bits - 8 bytes bigendian. */
  807. c32toa(realLen >> ((sizeof(word32) * 8) - 3), lenBytes);
  808. c32toa(realLen << 3, lenBytes + sizeof(word32));
  809. ret = Hmac_HashUpdate(hmac, (unsigned char*)hmac->ipad, blockSz);
  810. if (ret != 0)
  811. return ret;
  812. XMEMSET(hmac->innerHash, 0, macLen);
  813. if (safeBlocks > 0) {
  814. ret = Hmac_HashUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ);
  815. if (ret != 0)
  816. return ret;
  817. ret = Hmac_HashUpdate(hmac, in, safeBlocks * blockSz -
  818. WOLFSSL_TLS_HMAC_INNER_SZ);
  819. if (ret != 0)
  820. return ret;
  821. }
  822. else
  823. safeBlocks = 0;
  824. XMEMSET(digest, 0, macLen);
  825. k = safeBlocks * blockSz;
  826. for (i = safeBlocks; i < blocks; i++) {
  827. unsigned char hashBlock[WC_MAX_BLOCK_SIZE];
  828. unsigned char isEocBlock = ctMaskEq(i, eocBlock);
  829. unsigned char isOutBlock = ctMaskEq(i, lenBlock);
  830. for (j = 0; j < blockSz; j++) {
  831. unsigned char atEoc = ctMaskEq(j, eocIndex) & isEocBlock;
  832. unsigned char pastEoc = ctMaskGT(j, eocIndex) & isEocBlock;
  833. unsigned char b = 0;
  834. if (k < WOLFSSL_TLS_HMAC_INNER_SZ)
  835. b = header[k];
  836. else if (k < maxLen)
  837. b = in[k - WOLFSSL_TLS_HMAC_INNER_SZ];
  838. k++;
  839. b = ctMaskSel(atEoc, 0x80, b);
  840. b &= (unsigned char)~(word32)pastEoc;
  841. b &= ((unsigned char)~(word32)isOutBlock) | isEocBlock;
  842. if (j >= blockSz - 8) {
  843. b = ctMaskSel(isOutBlock, lenBytes[j - (blockSz - 8)], b);
  844. }
  845. hashBlock[j] = b;
  846. }
  847. ret = Hmac_HashUpdate(hmac, hashBlock, blockSz);
  848. if (ret != 0)
  849. return ret;
  850. ret = Hmac_HashFinalRaw(hmac, hashBlock);
  851. if (ret != 0)
  852. return ret;
  853. for (j = 0; j < macLen; j++)
  854. ((unsigned char*)hmac->innerHash)[j] |= hashBlock[j] & isOutBlock;
  855. }
  856. ret = Hmac_OuterHash(hmac, digest);
  857. return ret;
  858. }
  859. #endif
  860. #if defined(WOLFSSL_NO_HASH_RAW) || defined(HAVE_FIPS) || \
  861. defined(HAVE_SELFTEST) || defined(HAVE_BLAKE2)
  862. /* Calculate the HMAC of the header + message data.
  863. * Constant time implementation using normal hashing operations.
  864. * Update-Final need to be constant time.
  865. *
  866. * hmac HMAC object.
  867. * digest MAC result.
  868. * in Message data.
  869. * sz Size of the message data.
  870. * header Constructed record header with length of handshake data.
  871. * returns 0 on success, otherwise failure.
  872. */
  873. static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in,
  874. word32 sz, byte* header)
  875. {
  876. byte dummy[WC_MAX_BLOCK_SIZE] = {0};
  877. int ret = 0;
  878. word32 msgSz, blockSz, macSz, padSz, maxSz, realSz;
  879. word32 offset = 0;
  880. int msgBlocks, blocks, blockBits;
  881. int i;
  882. switch (hmac->macType) {
  883. #ifndef NO_SHA
  884. case WC_SHA:
  885. blockSz = WC_SHA_BLOCK_SIZE;
  886. blockBits = 6;
  887. macSz = WC_SHA_DIGEST_SIZE;
  888. padSz = WC_SHA_BLOCK_SIZE - WC_SHA_PAD_SIZE + 1;
  889. break;
  890. #endif /* !NO_SHA */
  891. #ifndef NO_SHA256
  892. case WC_SHA256:
  893. blockSz = WC_SHA256_BLOCK_SIZE;
  894. blockBits = 6;
  895. macSz = WC_SHA256_DIGEST_SIZE;
  896. padSz = WC_SHA256_BLOCK_SIZE - WC_SHA256_PAD_SIZE + 1;
  897. break;
  898. #endif /* !NO_SHA256 */
  899. #ifdef WOLFSSL_SHA384
  900. case WC_SHA384:
  901. blockSz = WC_SHA384_BLOCK_SIZE;
  902. blockBits = 7;
  903. macSz = WC_SHA384_DIGEST_SIZE;
  904. padSz = WC_SHA384_BLOCK_SIZE - WC_SHA384_PAD_SIZE + 1;
  905. break;
  906. #endif /* WOLFSSL_SHA384 */
  907. #ifdef WOLFSSL_SHA512
  908. case WC_SHA512:
  909. blockSz = WC_SHA512_BLOCK_SIZE;
  910. blockBits = 7;
  911. macSz = WC_SHA512_DIGEST_SIZE;
  912. padSz = WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE + 1;
  913. break;
  914. #endif /* WOLFSSL_SHA512 */
  915. #ifdef HAVE_BLAKE2
  916. case WC_HASH_TYPE_BLAKE2B:
  917. blockSz = BLAKE2B_BLOCKBYTES;
  918. blockBits = 7;
  919. macSz = BLAKE2B_256;
  920. padSz = 0;
  921. break;
  922. #endif /* HAVE_BLAKE2 */
  923. #ifdef WOLFSSL_SM3
  924. case WC_SM3:
  925. blockSz = WC_SM3_BLOCK_SIZE;
  926. blockBits = 6;
  927. macSz = WC_SM3_DIGEST_SIZE;
  928. padSz = WC_SM3_BLOCK_SIZE - WC_SM3_PAD_SIZE + 1;
  929. break;
  930. #endif
  931. default:
  932. WOLFSSL_MSG("ERROR: Hmac_UpdateFinal failed, no hmac->macType");
  933. return BAD_FUNC_ARG;
  934. }
  935. msgSz = sz - (1 + in[sz - 1] + macSz);
  936. /* Make negative result 0 */
  937. msgSz &= ~(0 - (msgSz >> 31));
  938. realSz = WOLFSSL_TLS_HMAC_INNER_SZ + msgSz;
  939. maxSz = WOLFSSL_TLS_HMAC_INNER_SZ + (sz - 1) - macSz;
  940. /* Make negative result 0 */
  941. maxSz &= ~(0 - (maxSz >> 31));
  942. /* Calculate #blocks processed in HMAC for max and real data. */
  943. blocks = maxSz >> blockBits;
  944. blocks += ((maxSz + padSz) % blockSz) < padSz;
  945. msgBlocks = realSz >> blockBits;
  946. /* #Extra blocks to process. */
  947. blocks -= msgBlocks + ((((realSz + padSz) % blockSz) < padSz) ? 1 : 0);
  948. /* Calculate whole blocks. */
  949. msgBlocks--;
  950. ret = wc_HmacUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ);
  951. if (ret == 0) {
  952. /* Fill the rest of the block with any available data. */
  953. word32 currSz = ctMaskLT(msgSz, blockSz) & msgSz;
  954. currSz |= ctMaskGTE(msgSz, blockSz) & blockSz;
  955. currSz -= WOLFSSL_TLS_HMAC_INNER_SZ;
  956. currSz &= ~(0 - (currSz >> 31));
  957. ret = wc_HmacUpdate(hmac, in, currSz);
  958. offset = currSz;
  959. }
  960. if (ret == 0) {
  961. /* Do the hash operations on a block basis. */
  962. for (i = 0; i < msgBlocks; i++, offset += blockSz) {
  963. ret = wc_HmacUpdate(hmac, in + offset, blockSz);
  964. if (ret != 0)
  965. break;
  966. }
  967. }
  968. if (ret == 0)
  969. ret = wc_HmacUpdate(hmac, in + offset, msgSz - offset);
  970. if (ret == 0)
  971. ret = wc_HmacFinal(hmac, digest);
  972. if (ret == 0) {
  973. /* Do the dummy hash operations. Do at least one. */
  974. for (i = 0; i < blocks + 1; i++) {
  975. ret = wc_HmacUpdate(hmac, dummy, blockSz);
  976. if (ret != 0)
  977. break;
  978. }
  979. }
  980. return ret;
  981. }
  982. #endif
  983. int TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, int padSz,
  984. int content, int verify, int epochOrder)
  985. {
  986. Hmac hmac;
  987. byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
  988. int ret = 0;
  989. const byte* macSecret = NULL;
  990. word32 hashSz = 0;
  991. if (ssl == NULL)
  992. return BAD_FUNC_ARG;
  993. #ifdef HAVE_TRUNCATED_HMAC
  994. hashSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  995. : ssl->specs.hash_size;
  996. #else
  997. hashSz = ssl->specs.hash_size;
  998. #endif
  999. #ifdef HAVE_FUZZER
  1000. /* Fuzz "in" buffer with sz to be used in HMAC algorithm */
  1001. if (ssl->fuzzerCb) {
  1002. if (verify && padSz >= 0) {
  1003. ssl->fuzzerCb(ssl, in, sz + hashSz + padSz + 1, FUZZ_HMAC,
  1004. ssl->fuzzerCtx);
  1005. }
  1006. else {
  1007. ssl->fuzzerCb(ssl, in, sz, FUZZ_HMAC, ssl->fuzzerCtx);
  1008. }
  1009. }
  1010. #endif
  1011. if (!ssl->options.dtls)
  1012. wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, verify);
  1013. else
  1014. wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, epochOrder);
  1015. ret = wc_HmacInit(&hmac, ssl->heap, ssl->devId);
  1016. if (ret != 0)
  1017. return ret;
  1018. #ifdef WOLFSSL_DTLS
  1019. if (ssl->options.dtls)
  1020. macSecret = wolfSSL_GetDtlsMacSecret(ssl, verify, epochOrder);
  1021. else
  1022. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  1023. #else
  1024. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  1025. #endif
  1026. ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
  1027. macSecret,
  1028. ssl->specs.hash_size);
  1029. if (ret == 0) {
  1030. /* Constant time verification required. */
  1031. if (verify && padSz >= 0) {
  1032. #if !defined(WOLFSSL_NO_HASH_RAW) && !defined(HAVE_FIPS) && \
  1033. !defined(HAVE_SELFTEST)
  1034. #ifdef HAVE_BLAKE2
  1035. if (wolfSSL_GetHmacType(ssl) == WC_HASH_TYPE_BLAKE2B) {
  1036. ret = Hmac_UpdateFinal(&hmac, digest, in,
  1037. sz + hashSz + padSz + 1, myInner);
  1038. }
  1039. else
  1040. #endif
  1041. {
  1042. ret = Hmac_UpdateFinal_CT(&hmac, digest, in,
  1043. sz + hashSz + padSz + 1, hashSz, myInner);
  1044. }
  1045. #else
  1046. ret = Hmac_UpdateFinal(&hmac, digest, in, sz + hashSz + padSz + 1,
  1047. myInner);
  1048. #endif
  1049. }
  1050. else {
  1051. ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
  1052. if (ret == 0)
  1053. ret = wc_HmacUpdate(&hmac, in, sz); /* content */
  1054. if (ret == 0)
  1055. ret = wc_HmacFinal(&hmac, digest);
  1056. }
  1057. }
  1058. wc_HmacFree(&hmac);
  1059. return ret;
  1060. }
  1061. #endif /* WOLFSSL_AEAD_ONLY */
  1062. #endif /* !WOLFSSL_NO_TLS12 */
  1063. int wolfSSL_GetHmacType_ex(CipherSpecs* specs)
  1064. {
  1065. if (specs == NULL)
  1066. return BAD_FUNC_ARG;
  1067. switch (specs->mac_algorithm) {
  1068. #ifndef NO_MD5
  1069. case md5_mac:
  1070. {
  1071. return WC_MD5;
  1072. }
  1073. #endif
  1074. #ifndef NO_SHA256
  1075. case sha256_mac:
  1076. {
  1077. return WC_SHA256;
  1078. }
  1079. #endif
  1080. #ifdef WOLFSSL_SHA384
  1081. case sha384_mac:
  1082. {
  1083. return WC_SHA384;
  1084. }
  1085. #endif
  1086. #ifdef WOLFSSL_SM3
  1087. case sm3_mac:
  1088. {
  1089. return WC_SM3;
  1090. }
  1091. #endif
  1092. #ifndef NO_SHA
  1093. case sha_mac:
  1094. {
  1095. return WC_SHA;
  1096. }
  1097. #endif
  1098. #ifdef HAVE_BLAKE2
  1099. case blake2b_mac:
  1100. {
  1101. return BLAKE2B_ID;
  1102. }
  1103. #endif
  1104. default:
  1105. {
  1106. return WOLFSSL_FATAL_ERROR;
  1107. }
  1108. }
  1109. }
  1110. #ifdef HAVE_TLS_EXTENSIONS
  1111. /**
  1112. * The TLSX semaphore is used to calculate the size of the extensions to be sent
  1113. * from one peer to another.
  1114. */
  1115. /** Supports up to 72 flags. Increase as needed. */
  1116. #define SEMAPHORE_SIZE 9
  1117. /**
  1118. * Converts the extension type (id) to an index in the semaphore.
  1119. *
  1120. * Official reference for TLS extension types:
  1121. * http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xml
  1122. *
  1123. * Motivation:
  1124. * Previously, we used the extension type itself as the index of that
  1125. * extension in the semaphore as the extension types were declared
  1126. * sequentially, but maintain a semaphore as big as the number of available
  1127. * extensions is no longer an option since the release of renegotiation_info.
  1128. *
  1129. * How to update:
  1130. * Assign extension types that extrapolate the number of available semaphores
  1131. * to the first available index going backwards in the semaphore array.
  1132. * When adding a new extension type that don't extrapolate the number of
  1133. * available semaphores, check for a possible collision with with a
  1134. * 'remapped' extension type.
  1135. *
  1136. * Update TLSX_Parse for duplicate detection if more added above 62.
  1137. */
  1138. static WC_INLINE word16 TLSX_ToSemaphore(word16 type)
  1139. {
  1140. switch (type) {
  1141. case TLSX_RENEGOTIATION_INFO: /* 0xFF01 */
  1142. return 63;
  1143. #ifdef WOLFSSL_QUIC
  1144. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT: /* 0xffa5 */
  1145. return 64;
  1146. #endif
  1147. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1148. case TLSX_ECH: /* 0xfe0d */
  1149. return 65;
  1150. #endif
  1151. #ifdef WOLFSSL_DUAL_ALG_CERTS
  1152. case TLSX_CKS:
  1153. return 66;
  1154. #endif
  1155. default:
  1156. if (type > 62) {
  1157. /* This message SHOULD only happens during the adding of
  1158. new TLS extensions in which its IANA number overflows
  1159. the current semaphore's range, or if its number already
  1160. is assigned to be used by another extension.
  1161. Use this check value for the new extension and decrement
  1162. the check value by one. */
  1163. WOLFSSL_MSG("### TLSX semaphore collision or overflow detected!");
  1164. }
  1165. }
  1166. return type;
  1167. }
  1168. /** Checks if a specific light (tls extension) is not set in the semaphore. */
  1169. #define IS_OFF(semaphore, light) \
  1170. (!(((semaphore)[(light) / 8] & (byte) (0x01 << ((light) % 8)))))
  1171. /** Turn on a specific light (tls extension) in the semaphore. */
  1172. /* the semaphore marks the extensions already written to the message */
  1173. #define TURN_ON(semaphore, light) \
  1174. ((semaphore)[(light) / 8] |= (byte) (0x01 << ((light) % 8)))
  1175. /** Turn off a specific light (tls extension) in the semaphore. */
  1176. #define TURN_OFF(semaphore, light) \
  1177. ((semaphore)[(light) / 8] &= (byte) ~(0x01 << ((light) % 8)))
  1178. /** Creates a new extension. */
  1179. static TLSX* TLSX_New(TLSX_Type type, const void* data, void* heap)
  1180. {
  1181. TLSX* extension = (TLSX*)XMALLOC(sizeof(TLSX), heap, DYNAMIC_TYPE_TLSX);
  1182. (void)heap;
  1183. if (extension) {
  1184. extension->type = type;
  1185. extension->data = (void*)data;
  1186. extension->resp = 0;
  1187. extension->next = NULL;
  1188. }
  1189. return extension;
  1190. }
  1191. /**
  1192. * Creates a new extension and appends it to the provided list.
  1193. * Checks for duplicate extensions, keeps the newest.
  1194. */
  1195. int TLSX_Append(TLSX** list, TLSX_Type type, const void* data, void* heap)
  1196. {
  1197. TLSX* extension = TLSX_New(type, data, heap);
  1198. TLSX* cur;
  1199. TLSX** prevNext = list;
  1200. if (extension == NULL)
  1201. return MEMORY_E;
  1202. for (cur = *list; cur != NULL;) {
  1203. if (cur->type == type) {
  1204. *prevNext = cur->next;
  1205. cur->next = NULL;
  1206. TLSX_FreeAll(cur, heap);
  1207. cur = *prevNext;
  1208. }
  1209. else {
  1210. prevNext = &cur->next;
  1211. cur = cur->next;
  1212. }
  1213. }
  1214. /* Append the extension to the list */
  1215. *prevNext = extension;
  1216. return 0;
  1217. }
  1218. /**
  1219. * Creates a new extension and pushes it to the provided list.
  1220. * Checks for duplicate extensions, keeps the newest.
  1221. */
  1222. int TLSX_Push(TLSX** list, TLSX_Type type, const void* data, void* heap)
  1223. {
  1224. TLSX* extension = TLSX_New(type, data, heap);
  1225. if (extension == NULL)
  1226. return MEMORY_E;
  1227. /* pushes the new extension on the list. */
  1228. extension->next = *list;
  1229. *list = extension;
  1230. /* remove duplicate extensions, there should be only one of each type. */
  1231. do {
  1232. if (extension->next && extension->next->type == type) {
  1233. TLSX *next = extension->next;
  1234. extension->next = next->next;
  1235. next->next = NULL;
  1236. TLSX_FreeAll(next, heap);
  1237. /* there is no way to occur more than
  1238. * two extensions of the same type.
  1239. */
  1240. break;
  1241. }
  1242. } while ((extension = extension->next));
  1243. return 0;
  1244. }
  1245. #ifndef NO_WOLFSSL_CLIENT
  1246. int TLSX_CheckUnsupportedExtension(WOLFSSL* ssl, TLSX_Type type);
  1247. int TLSX_CheckUnsupportedExtension(WOLFSSL* ssl, TLSX_Type type)
  1248. {
  1249. TLSX *extension = TLSX_Find(ssl->extensions, type);
  1250. if (!extension)
  1251. extension = TLSX_Find(ssl->ctx->extensions, type);
  1252. return extension == NULL;
  1253. }
  1254. int TLSX_HandleUnsupportedExtension(WOLFSSL* ssl);
  1255. int TLSX_HandleUnsupportedExtension(WOLFSSL* ssl)
  1256. {
  1257. SendAlert(ssl, alert_fatal, unsupported_extension);
  1258. WOLFSSL_ERROR_VERBOSE(UNSUPPORTED_EXTENSION);
  1259. return UNSUPPORTED_EXTENSION;
  1260. }
  1261. #else
  1262. #define TLSX_CheckUnsupportedExtension(ssl, type) 0
  1263. #define TLSX_HandleUnsupportedExtension(ssl) 0
  1264. #endif
  1265. #if !defined(NO_WOLFSSL_SERVER) || defined(WOLFSSL_TLS13)
  1266. void TLSX_SetResponse(WOLFSSL* ssl, TLSX_Type type);
  1267. /** Mark an extension to be sent back to the client. */
  1268. void TLSX_SetResponse(WOLFSSL* ssl, TLSX_Type type)
  1269. {
  1270. TLSX *extension = TLSX_Find(ssl->extensions, type);
  1271. if (extension)
  1272. extension->resp = 1;
  1273. }
  1274. #endif
  1275. /******************************************************************************/
  1276. /* Application-Layer Protocol Negotiation */
  1277. /******************************************************************************/
  1278. #ifdef HAVE_ALPN
  1279. /** Creates a new ALPN object, providing protocol name to use. */
  1280. static ALPN* TLSX_ALPN_New(char *protocol_name, word16 protocol_nameSz,
  1281. void* heap)
  1282. {
  1283. ALPN *alpn;
  1284. WOLFSSL_ENTER("TLSX_ALPN_New");
  1285. if (protocol_name == NULL ||
  1286. protocol_nameSz > WOLFSSL_MAX_ALPN_PROTO_NAME_LEN) {
  1287. WOLFSSL_MSG("Invalid arguments");
  1288. return NULL;
  1289. }
  1290. alpn = (ALPN*)XMALLOC(sizeof(ALPN), heap, DYNAMIC_TYPE_TLSX);
  1291. if (alpn == NULL) {
  1292. WOLFSSL_MSG("Memory failure");
  1293. return NULL;
  1294. }
  1295. alpn->next = NULL;
  1296. alpn->negotiated = 0;
  1297. alpn->options = 0;
  1298. alpn->protocol_name = (char*)XMALLOC(protocol_nameSz + 1,
  1299. heap, DYNAMIC_TYPE_TLSX);
  1300. if (alpn->protocol_name == NULL) {
  1301. WOLFSSL_MSG("Memory failure");
  1302. XFREE(alpn, heap, DYNAMIC_TYPE_TLSX);
  1303. return NULL;
  1304. }
  1305. XMEMCPY(alpn->protocol_name, protocol_name, protocol_nameSz);
  1306. alpn->protocol_name[protocol_nameSz] = 0;
  1307. (void)heap;
  1308. return alpn;
  1309. }
  1310. /** Releases an ALPN object. */
  1311. static void TLSX_ALPN_Free(ALPN *alpn, void* heap)
  1312. {
  1313. (void)heap;
  1314. if (alpn == NULL)
  1315. return;
  1316. XFREE(alpn->protocol_name, heap, DYNAMIC_TYPE_TLSX);
  1317. XFREE(alpn, heap, DYNAMIC_TYPE_TLSX);
  1318. }
  1319. /** Releases all ALPN objects in the provided list. */
  1320. static void TLSX_ALPN_FreeAll(ALPN *list, void* heap)
  1321. {
  1322. ALPN* alpn;
  1323. while ((alpn = list)) {
  1324. list = alpn->next;
  1325. TLSX_ALPN_Free(alpn, heap);
  1326. }
  1327. }
  1328. /** Tells the buffered size of the ALPN objects in a list. */
  1329. static word16 TLSX_ALPN_GetSize(ALPN *list)
  1330. {
  1331. ALPN* alpn;
  1332. word16 length = OPAQUE16_LEN; /* list length */
  1333. while ((alpn = list)) {
  1334. list = alpn->next;
  1335. length++; /* protocol name length is on one byte */
  1336. length += (word16)XSTRLEN(alpn->protocol_name);
  1337. }
  1338. return length;
  1339. }
  1340. /** Writes the ALPN objects of a list in a buffer. */
  1341. static word16 TLSX_ALPN_Write(ALPN *list, byte *output)
  1342. {
  1343. ALPN* alpn;
  1344. word16 length = 0;
  1345. word16 offset = OPAQUE16_LEN; /* list length offset */
  1346. while ((alpn = list)) {
  1347. list = alpn->next;
  1348. length = (word16)XSTRLEN(alpn->protocol_name);
  1349. /* protocol name length */
  1350. output[offset++] = (byte)length;
  1351. /* protocol name value */
  1352. XMEMCPY(output + offset, alpn->protocol_name, length);
  1353. offset += length;
  1354. }
  1355. /* writing list length */
  1356. c16toa(offset - OPAQUE16_LEN, output);
  1357. return offset;
  1358. }
  1359. /** Finds a protocol name in the provided ALPN list */
  1360. static ALPN* TLSX_ALPN_Find(ALPN *list, char *protocol_name, word16 size)
  1361. {
  1362. ALPN *alpn;
  1363. if (list == NULL || protocol_name == NULL)
  1364. return NULL;
  1365. alpn = list;
  1366. while (alpn != NULL && (
  1367. (word16)XSTRLEN(alpn->protocol_name) != size ||
  1368. XSTRNCMP(alpn->protocol_name, protocol_name, size)))
  1369. alpn = alpn->next;
  1370. return alpn;
  1371. }
  1372. /** Set the ALPN matching client and server requirements */
  1373. static int TLSX_SetALPN(TLSX** extensions, const void* data, word16 size,
  1374. void* heap)
  1375. {
  1376. ALPN *alpn;
  1377. int ret;
  1378. if (extensions == NULL || data == NULL)
  1379. return BAD_FUNC_ARG;
  1380. alpn = TLSX_ALPN_New((char *)data, size, heap);
  1381. if (alpn == NULL) {
  1382. WOLFSSL_MSG("Memory failure");
  1383. return MEMORY_E;
  1384. }
  1385. alpn->negotiated = 1;
  1386. ret = TLSX_Push(extensions, TLSX_APPLICATION_LAYER_PROTOCOL, (void*)alpn,
  1387. heap);
  1388. if (ret != 0) {
  1389. TLSX_ALPN_Free(alpn, heap);
  1390. return ret;
  1391. }
  1392. return WOLFSSL_SUCCESS;
  1393. }
  1394. static int ALPN_find_match(WOLFSSL *ssl, TLSX **pextension,
  1395. const byte **psel, byte *psel_len,
  1396. const byte *alpn_val, word16 alpn_val_len)
  1397. {
  1398. TLSX *extension;
  1399. ALPN *alpn, *list;
  1400. const byte *sel = NULL, *s;
  1401. byte sel_len = 0, wlen;
  1402. extension = TLSX_Find(ssl->extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1403. if (extension == NULL)
  1404. extension = TLSX_Find(ssl->ctx->extensions,
  1405. TLSX_APPLICATION_LAYER_PROTOCOL);
  1406. /* No ALPN configured here */
  1407. if (extension == NULL || extension->data == NULL) {
  1408. *pextension = NULL;
  1409. *psel = NULL;
  1410. *psel_len = 0;
  1411. return 0;
  1412. }
  1413. list = (ALPN*)extension->data;
  1414. for (s = alpn_val;
  1415. (s - alpn_val) < alpn_val_len;
  1416. s += wlen) {
  1417. wlen = *s++; /* bounds already checked on save */
  1418. alpn = TLSX_ALPN_Find(list, (char*)s, wlen);
  1419. if (alpn != NULL) {
  1420. WOLFSSL_MSG("ALPN protocol match");
  1421. sel = s,
  1422. sel_len = wlen;
  1423. break;
  1424. }
  1425. }
  1426. if (sel == NULL) {
  1427. WOLFSSL_MSG("No ALPN protocol match");
  1428. /* do nothing if no protocol match between client and server and option
  1429. is set to continue (like OpenSSL) */
  1430. if (list->options & WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) {
  1431. WOLFSSL_MSG("Continue on mismatch");
  1432. }
  1433. else {
  1434. SendAlert(ssl, alert_fatal, no_application_protocol);
  1435. WOLFSSL_ERROR_VERBOSE(UNKNOWN_ALPN_PROTOCOL_NAME_E);
  1436. return UNKNOWN_ALPN_PROTOCOL_NAME_E;
  1437. }
  1438. }
  1439. *pextension = extension;
  1440. *psel = sel;
  1441. *psel_len = sel_len;
  1442. return 0;
  1443. }
  1444. int ALPN_Select(WOLFSSL *ssl)
  1445. {
  1446. TLSX *extension;
  1447. const byte *sel = NULL;
  1448. byte sel_len = 0;
  1449. int r = 0;
  1450. WOLFSSL_ENTER("ALPN_Select");
  1451. if (ssl->alpn_peer_requested == NULL)
  1452. return 0;
  1453. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  1454. if (ssl->alpnSelect != NULL && ssl->options.side == WOLFSSL_SERVER_END) {
  1455. r = ssl->alpnSelect(ssl, &sel, &sel_len, ssl->alpn_peer_requested,
  1456. ssl->alpn_peer_requested_length, ssl->alpnSelectArg);
  1457. switch (r) {
  1458. case SSL_TLSEXT_ERR_OK:
  1459. WOLFSSL_MSG("ALPN protocol match");
  1460. break;
  1461. case SSL_TLSEXT_ERR_NOACK:
  1462. WOLFSSL_MSG("ALPN cb no match but not fatal");
  1463. sel = NULL;
  1464. sel_len = 0;
  1465. break;
  1466. case SSL_TLSEXT_ERR_ALERT_FATAL:
  1467. default:
  1468. WOLFSSL_MSG("ALPN cb no match and fatal");
  1469. SendAlert(ssl, alert_fatal, no_application_protocol);
  1470. WOLFSSL_ERROR_VERBOSE(UNKNOWN_ALPN_PROTOCOL_NAME_E);
  1471. return UNKNOWN_ALPN_PROTOCOL_NAME_E;
  1472. }
  1473. }
  1474. else
  1475. #endif
  1476. {
  1477. r = ALPN_find_match(ssl, &extension, &sel, &sel_len,
  1478. ssl->alpn_peer_requested,
  1479. ssl->alpn_peer_requested_length);
  1480. if (r != 0)
  1481. return r;
  1482. }
  1483. if (sel != NULL) {
  1484. /* set the matching negotiated protocol */
  1485. r = TLSX_SetALPN(&ssl->extensions, sel, sel_len, ssl->heap);
  1486. if (r != WOLFSSL_SUCCESS) {
  1487. WOLFSSL_MSG("TLSX_SetALPN failed");
  1488. return BUFFER_ERROR;
  1489. }
  1490. /* reply to ALPN extension sent from peer */
  1491. #ifndef NO_WOLFSSL_SERVER
  1492. TLSX_SetResponse(ssl, TLSX_APPLICATION_LAYER_PROTOCOL);
  1493. #endif
  1494. }
  1495. return 0;
  1496. }
  1497. /** Parses a buffer of ALPN extensions and set the first one matching
  1498. * client and server requirements */
  1499. static int TLSX_ALPN_ParseAndSet(WOLFSSL *ssl, const byte *input, word16 length,
  1500. byte isRequest)
  1501. {
  1502. word16 size = 0, offset = 0, wlen;
  1503. int r = BUFFER_ERROR;
  1504. const byte *s;
  1505. if (OPAQUE16_LEN > length)
  1506. return BUFFER_ERROR;
  1507. ato16(input, &size);
  1508. offset += OPAQUE16_LEN;
  1509. /* validating alpn list length */
  1510. if (size == 0 || length != OPAQUE16_LEN + size)
  1511. return BUFFER_ERROR;
  1512. /* validating length of entries before accepting */
  1513. for (s = input + offset; (s - input) < size; s += wlen) {
  1514. wlen = *s++;
  1515. if (wlen == 0 || (s + wlen - input) > length)
  1516. return BUFFER_ERROR;
  1517. }
  1518. if (isRequest) {
  1519. /* keep the list sent by peer, if this is from a request. We
  1520. * use it later in ALPN_Select() for evaluation. */
  1521. if (ssl->alpn_peer_requested != NULL) {
  1522. XFREE(ssl->alpn_peer_requested, ssl->heap, DYNAMIC_TYPE_ALPN);
  1523. ssl->alpn_peer_requested_length = 0;
  1524. }
  1525. ssl->alpn_peer_requested = (byte *)XMALLOC(size, ssl->heap,
  1526. DYNAMIC_TYPE_ALPN);
  1527. if (ssl->alpn_peer_requested == NULL) {
  1528. return MEMORY_ERROR;
  1529. }
  1530. ssl->alpn_peer_requested_length = size;
  1531. XMEMCPY(ssl->alpn_peer_requested, (char*)input + offset, size);
  1532. }
  1533. else {
  1534. /* a response, we should find the value in our config */
  1535. const byte *sel = NULL;
  1536. byte sel_len = 0;
  1537. TLSX *extension = NULL;
  1538. r = ALPN_find_match(ssl, &extension, &sel, &sel_len, input + offset, size);
  1539. if (r != 0)
  1540. return r;
  1541. if (sel != NULL) {
  1542. /* set the matching negotiated protocol */
  1543. r = TLSX_SetALPN(&ssl->extensions, sel, sel_len, ssl->heap);
  1544. if (r != WOLFSSL_SUCCESS) {
  1545. WOLFSSL_MSG("TLSX_SetALPN failed");
  1546. return BUFFER_ERROR;
  1547. }
  1548. }
  1549. /* If we had nothing configured, the response is unexpected */
  1550. else if (extension == NULL) {
  1551. r = TLSX_HandleUnsupportedExtension(ssl);
  1552. if (r != 0)
  1553. return r;
  1554. }
  1555. }
  1556. return 0;
  1557. }
  1558. /** Add a protocol name to the list of accepted usable ones */
  1559. int TLSX_UseALPN(TLSX** extensions, const void* data, word16 size, byte options,
  1560. void* heap)
  1561. {
  1562. ALPN *alpn;
  1563. TLSX *extension;
  1564. int ret;
  1565. if (extensions == NULL || data == NULL)
  1566. return BAD_FUNC_ARG;
  1567. alpn = TLSX_ALPN_New((char *)data, size, heap);
  1568. if (alpn == NULL) {
  1569. WOLFSSL_MSG("Memory failure");
  1570. return MEMORY_E;
  1571. }
  1572. /* Set Options of ALPN */
  1573. alpn->options = options;
  1574. extension = TLSX_Find(*extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1575. if (extension == NULL) {
  1576. ret = TLSX_Push(extensions, TLSX_APPLICATION_LAYER_PROTOCOL,
  1577. (void*)alpn, heap);
  1578. if (ret != 0) {
  1579. TLSX_ALPN_Free(alpn, heap);
  1580. return ret;
  1581. }
  1582. }
  1583. else {
  1584. /* push new ALPN object to extension data. */
  1585. alpn->next = (ALPN*)extension->data;
  1586. extension->data = (void*)alpn;
  1587. }
  1588. return WOLFSSL_SUCCESS;
  1589. }
  1590. /** Get the protocol name set by the server */
  1591. int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz)
  1592. {
  1593. TLSX *extension;
  1594. ALPN *alpn;
  1595. if (extensions == NULL || data == NULL || dataSz == NULL)
  1596. return BAD_FUNC_ARG;
  1597. *data = NULL;
  1598. *dataSz = 0;
  1599. extension = TLSX_Find(extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1600. if (extension == NULL) {
  1601. WOLFSSL_MSG("TLS extension not found");
  1602. WOLFSSL_ERROR_VERBOSE(WOLFSSL_ALPN_NOT_FOUND);
  1603. return WOLFSSL_ALPN_NOT_FOUND;
  1604. }
  1605. alpn = (ALPN *)extension->data;
  1606. if (alpn == NULL) {
  1607. WOLFSSL_MSG("ALPN extension not found");
  1608. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1609. return WOLFSSL_FATAL_ERROR;
  1610. }
  1611. if (alpn->negotiated != 1) {
  1612. /* consider as an error */
  1613. if (alpn->options & WOLFSSL_ALPN_FAILED_ON_MISMATCH) {
  1614. WOLFSSL_MSG("No protocol match with peer -> Failed");
  1615. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1616. return WOLFSSL_FATAL_ERROR;
  1617. }
  1618. /* continue without negotiated protocol */
  1619. WOLFSSL_MSG("No protocol match with peer -> Continue");
  1620. WOLFSSL_ERROR_VERBOSE(WOLFSSL_ALPN_NOT_FOUND);
  1621. return WOLFSSL_ALPN_NOT_FOUND;
  1622. }
  1623. if (alpn->next != NULL) {
  1624. WOLFSSL_MSG("Only one protocol name must be accepted");
  1625. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1626. return WOLFSSL_FATAL_ERROR;
  1627. }
  1628. *data = alpn->protocol_name;
  1629. *dataSz = (word16)XSTRLEN((char*)*data);
  1630. return WOLFSSL_SUCCESS;
  1631. }
  1632. #define ALPN_FREE_ALL TLSX_ALPN_FreeAll
  1633. #define ALPN_GET_SIZE TLSX_ALPN_GetSize
  1634. #define ALPN_WRITE TLSX_ALPN_Write
  1635. #define ALPN_PARSE TLSX_ALPN_ParseAndSet
  1636. #else /* HAVE_ALPN */
  1637. #define ALPN_FREE_ALL(list, heap) WC_DO_NOTHING
  1638. #define ALPN_GET_SIZE(list) 0
  1639. #define ALPN_WRITE(a, b) 0
  1640. #define ALPN_PARSE(a, b, c, d) 0
  1641. #endif /* HAVE_ALPN */
  1642. /******************************************************************************/
  1643. /* Server Name Indication */
  1644. /******************************************************************************/
  1645. #ifdef HAVE_SNI
  1646. /** Creates a new SNI object. */
  1647. static SNI* TLSX_SNI_New(byte type, const void* data, word16 size, void* heap)
  1648. {
  1649. SNI* sni = (SNI*)XMALLOC(sizeof(SNI), heap, DYNAMIC_TYPE_TLSX);
  1650. (void)heap;
  1651. if (sni) {
  1652. sni->type = type;
  1653. sni->next = NULL;
  1654. #ifndef NO_WOLFSSL_SERVER
  1655. sni->options = 0;
  1656. sni->status = WOLFSSL_SNI_NO_MATCH;
  1657. #endif
  1658. switch (sni->type) {
  1659. case WOLFSSL_SNI_HOST_NAME:
  1660. sni->data.host_name = (char*)XMALLOC(size + 1, heap,
  1661. DYNAMIC_TYPE_TLSX);
  1662. if (sni->data.host_name) {
  1663. XSTRNCPY(sni->data.host_name, (const char*)data, size);
  1664. sni->data.host_name[size] = '\0';
  1665. } else {
  1666. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1667. sni = NULL;
  1668. }
  1669. break;
  1670. default: /* invalid type */
  1671. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1672. sni = NULL;
  1673. }
  1674. }
  1675. return sni;
  1676. }
  1677. /** Releases a SNI object. */
  1678. static void TLSX_SNI_Free(SNI* sni, void* heap)
  1679. {
  1680. if (sni) {
  1681. switch (sni->type) {
  1682. case WOLFSSL_SNI_HOST_NAME:
  1683. XFREE(sni->data.host_name, heap, DYNAMIC_TYPE_TLSX);
  1684. break;
  1685. }
  1686. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1687. }
  1688. (void)heap;
  1689. }
  1690. /** Releases all SNI objects in the provided list. */
  1691. static void TLSX_SNI_FreeAll(SNI* list, void* heap)
  1692. {
  1693. SNI* sni;
  1694. while ((sni = list)) {
  1695. list = sni->next;
  1696. TLSX_SNI_Free(sni, heap);
  1697. }
  1698. }
  1699. /** Tells the buffered size of the SNI objects in a list. */
  1700. static word16 TLSX_SNI_GetSize(SNI* list)
  1701. {
  1702. SNI* sni;
  1703. word16 length = OPAQUE16_LEN; /* list length */
  1704. while ((sni = list)) {
  1705. list = sni->next;
  1706. length += ENUM_LEN + OPAQUE16_LEN; /* sni type + sni length */
  1707. switch (sni->type) {
  1708. case WOLFSSL_SNI_HOST_NAME:
  1709. length += (word16)XSTRLEN((char*)sni->data.host_name);
  1710. break;
  1711. }
  1712. }
  1713. return length;
  1714. }
  1715. /** Writes the SNI objects of a list in a buffer. */
  1716. static word16 TLSX_SNI_Write(SNI* list, byte* output)
  1717. {
  1718. SNI* sni;
  1719. word16 length = 0;
  1720. word16 offset = OPAQUE16_LEN; /* list length offset */
  1721. while ((sni = list)) {
  1722. list = sni->next;
  1723. output[offset++] = sni->type; /* sni type */
  1724. switch (sni->type) {
  1725. case WOLFSSL_SNI_HOST_NAME:
  1726. length = (word16)XSTRLEN((char*)sni->data.host_name);
  1727. c16toa(length, output + offset); /* sni length */
  1728. offset += OPAQUE16_LEN;
  1729. XMEMCPY(output + offset, sni->data.host_name, length);
  1730. offset += length;
  1731. break;
  1732. }
  1733. }
  1734. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  1735. return offset;
  1736. }
  1737. /** Finds a SNI object in the provided list. */
  1738. static SNI* TLSX_SNI_Find(SNI *list, byte type)
  1739. {
  1740. SNI* sni = list;
  1741. while (sni && sni->type != type)
  1742. sni = sni->next;
  1743. return sni;
  1744. }
  1745. #if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
  1746. /** Sets the status of a SNI object. */
  1747. static void TLSX_SNI_SetStatus(TLSX* extensions, byte type, byte status)
  1748. {
  1749. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1750. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1751. if (sni)
  1752. sni->status = status;
  1753. }
  1754. #endif
  1755. /** Gets the status of a SNI object. */
  1756. byte TLSX_SNI_Status(TLSX* extensions, byte type)
  1757. {
  1758. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1759. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1760. if (sni)
  1761. return sni->status;
  1762. return 0;
  1763. }
  1764. /** Parses a buffer of SNI extensions. */
  1765. static int TLSX_SNI_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  1766. byte isRequest)
  1767. {
  1768. #ifndef NO_WOLFSSL_SERVER
  1769. word16 size = 0;
  1770. word16 offset = 0;
  1771. int cacheOnly = 0;
  1772. SNI *sni = NULL;
  1773. byte type;
  1774. byte matched;
  1775. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1776. WOLFSSL_ECH* ech = NULL;
  1777. WOLFSSL_EchConfig* workingConfig;
  1778. TLSX* echX;
  1779. #endif
  1780. #endif /* !NO_WOLFSSL_SERVER */
  1781. TLSX *extension = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  1782. if (!extension)
  1783. extension = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  1784. if (!isRequest) {
  1785. #ifndef NO_WOLFSSL_CLIENT
  1786. if (!extension || !extension->data)
  1787. return TLSX_HandleUnsupportedExtension(ssl);
  1788. if (length > 0)
  1789. return BUFFER_ERROR; /* SNI response MUST be empty. */
  1790. /* This call enables wolfSSL_SNI_GetRequest() to be called in the
  1791. * client side to fetch the used SNI. It will only work if the SNI
  1792. * was set at the SSL object level. Right now we only support one
  1793. * name type, WOLFSSL_SNI_HOST_NAME, but in the future, the
  1794. * inclusion of other name types will turn this method inaccurate,
  1795. * as the extension response doesn't contains information of which
  1796. * name was accepted.
  1797. */
  1798. TLSX_SNI_SetStatus(ssl->extensions, WOLFSSL_SNI_HOST_NAME,
  1799. WOLFSSL_SNI_REAL_MATCH);
  1800. return 0;
  1801. #endif
  1802. }
  1803. #ifndef NO_WOLFSSL_SERVER
  1804. if (!extension || !extension->data) {
  1805. /* This will keep SNI even though TLSX_UseSNI has not been called.
  1806. * Enable it so that the received sni is available to functions
  1807. * that use a custom callback when SNI is received.
  1808. */
  1809. #ifdef WOLFSSL_ALWAYS_KEEP_SNI
  1810. cacheOnly = 1;
  1811. #endif
  1812. if (ssl->ctx->sniRecvCb) {
  1813. cacheOnly = 1;
  1814. }
  1815. if (cacheOnly) {
  1816. WOLFSSL_MSG("Forcing SSL object to store SNI parameter");
  1817. }
  1818. else {
  1819. /* Skipping, SNI not enabled at server side. */
  1820. return 0;
  1821. }
  1822. }
  1823. if (OPAQUE16_LEN > length)
  1824. return BUFFER_ERROR;
  1825. ato16(input, &size);
  1826. offset += OPAQUE16_LEN;
  1827. /* validating sni list length */
  1828. if (length != OPAQUE16_LEN + size || size == 0)
  1829. return BUFFER_ERROR;
  1830. /* SNI was badly specified and only one type is now recognized and allowed.
  1831. * Only one SNI value per type (RFC6066), so, no loop. */
  1832. type = input[offset++];
  1833. if (type != WOLFSSL_SNI_HOST_NAME)
  1834. return BUFFER_ERROR;
  1835. if (offset + OPAQUE16_LEN > length)
  1836. return BUFFER_ERROR;
  1837. ato16(input + offset, &size);
  1838. offset += OPAQUE16_LEN;
  1839. if (offset + size != length || size == 0)
  1840. return BUFFER_ERROR;
  1841. if (!cacheOnly && !(sni = TLSX_SNI_Find((SNI*)extension->data, type)))
  1842. return 0; /* not using this type of SNI. */
  1843. #ifdef WOLFSSL_TLS13
  1844. /* Don't process the second ClientHello SNI extension if there
  1845. * was problems with the first.
  1846. */
  1847. if (!cacheOnly && sni->status != 0)
  1848. return 0;
  1849. #endif
  1850. matched = cacheOnly || (XSTRLEN(sni->data.host_name) == size &&
  1851. XSTRNCMP(sni->data.host_name, (const char*)input + offset, size) == 0);
  1852. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1853. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  1854. if (echX != NULL)
  1855. ech = (WOLFSSL_ECH*)(echX->data);
  1856. if (!matched && ech != NULL) {
  1857. workingConfig = ech->echConfig;
  1858. while (workingConfig != NULL) {
  1859. matched = XSTRLEN(workingConfig->publicName) == size &&
  1860. XSTRNCMP(workingConfig->publicName,
  1861. (const char*)input + offset, size) == 0;
  1862. if (matched)
  1863. break;
  1864. workingConfig = workingConfig->next;
  1865. }
  1866. }
  1867. #endif
  1868. if (matched || sni->options & WOLFSSL_SNI_ANSWER_ON_MISMATCH) {
  1869. int matchStat;
  1870. int r = TLSX_UseSNI(&ssl->extensions, type, input + offset, size,
  1871. ssl->heap);
  1872. if (r != WOLFSSL_SUCCESS)
  1873. return r; /* throws error. */
  1874. if (cacheOnly) {
  1875. WOLFSSL_MSG("Forcing storage of SNI, Fake match");
  1876. matchStat = WOLFSSL_SNI_FORCE_KEEP;
  1877. }
  1878. else if (matched) {
  1879. WOLFSSL_MSG("SNI did match!");
  1880. matchStat = WOLFSSL_SNI_REAL_MATCH;
  1881. }
  1882. else {
  1883. WOLFSSL_MSG("fake SNI match from ANSWER_ON_MISMATCH");
  1884. matchStat = WOLFSSL_SNI_FAKE_MATCH;
  1885. }
  1886. TLSX_SNI_SetStatus(ssl->extensions, type, (byte)matchStat);
  1887. if (!cacheOnly)
  1888. TLSX_SetResponse(ssl, TLSX_SERVER_NAME);
  1889. }
  1890. else if (!(sni->options & WOLFSSL_SNI_CONTINUE_ON_MISMATCH)) {
  1891. SendAlert(ssl, alert_fatal, unrecognized_name);
  1892. WOLFSSL_ERROR_VERBOSE(UNKNOWN_SNI_HOST_NAME_E);
  1893. return UNKNOWN_SNI_HOST_NAME_E;
  1894. }
  1895. #else
  1896. (void)input;
  1897. #endif /* !NO_WOLFSSL_SERVER */
  1898. #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER)
  1899. (void)length;
  1900. #endif
  1901. return 0;
  1902. }
  1903. static int TLSX_SNI_VerifyParse(WOLFSSL* ssl, byte isRequest)
  1904. {
  1905. (void)ssl;
  1906. if (isRequest) {
  1907. #ifndef NO_WOLFSSL_SERVER
  1908. TLSX* ctx_ext = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  1909. TLSX* ssl_ext = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  1910. SNI* ctx_sni = ctx_ext ? (SNI*)ctx_ext->data : NULL;
  1911. SNI* ssl_sni = ssl_ext ? (SNI*)ssl_ext->data : NULL;
  1912. SNI* sni = NULL;
  1913. for (; ctx_sni; ctx_sni = ctx_sni->next) {
  1914. if (ctx_sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) {
  1915. sni = TLSX_SNI_Find(ssl_sni, ctx_sni->type);
  1916. if (sni) {
  1917. if (sni->status != WOLFSSL_SNI_NO_MATCH)
  1918. continue;
  1919. /* if ssl level overrides ctx level, it is ok. */
  1920. if ((sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) == 0)
  1921. continue;
  1922. }
  1923. SendAlert(ssl, alert_fatal, handshake_failure);
  1924. WOLFSSL_ERROR_VERBOSE(SNI_ABSENT_ERROR);
  1925. return SNI_ABSENT_ERROR;
  1926. }
  1927. }
  1928. for (; ssl_sni; ssl_sni = ssl_sni->next) {
  1929. if (ssl_sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) {
  1930. if (ssl_sni->status != WOLFSSL_SNI_NO_MATCH)
  1931. continue;
  1932. SendAlert(ssl, alert_fatal, handshake_failure);
  1933. WOLFSSL_ERROR_VERBOSE(SNI_ABSENT_ERROR);
  1934. return SNI_ABSENT_ERROR;
  1935. }
  1936. }
  1937. #endif /* NO_WOLFSSL_SERVER */
  1938. }
  1939. return 0;
  1940. }
  1941. int TLSX_UseSNI(TLSX** extensions, byte type, const void* data, word16 size,
  1942. void* heap)
  1943. {
  1944. TLSX* extension;
  1945. SNI* sni = NULL;
  1946. if (extensions == NULL || data == NULL)
  1947. return BAD_FUNC_ARG;
  1948. if ((sni = TLSX_SNI_New(type, data, size, heap)) == NULL)
  1949. return MEMORY_E;
  1950. extension = TLSX_Find(*extensions, TLSX_SERVER_NAME);
  1951. if (!extension) {
  1952. int ret = TLSX_Push(extensions, TLSX_SERVER_NAME, (void*)sni, heap);
  1953. if (ret != 0) {
  1954. TLSX_SNI_Free(sni, heap);
  1955. return ret;
  1956. }
  1957. }
  1958. else {
  1959. /* push new SNI object to extension data. */
  1960. sni->next = (SNI*)extension->data;
  1961. extension->data = (void*)sni;
  1962. /* remove duplicate SNI, there should be only one of each type. */
  1963. do {
  1964. if (sni->next && sni->next->type == type) {
  1965. SNI* next = sni->next;
  1966. sni->next = next->next;
  1967. TLSX_SNI_Free(next, heap);
  1968. /* there is no way to occur more than
  1969. * two SNIs of the same type.
  1970. */
  1971. break;
  1972. }
  1973. } while ((sni = sni->next));
  1974. }
  1975. return WOLFSSL_SUCCESS;
  1976. }
  1977. #ifndef NO_WOLFSSL_SERVER
  1978. /** Tells the SNI requested by the client. */
  1979. word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type, void** data)
  1980. {
  1981. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1982. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1983. if (sni && sni->status != WOLFSSL_SNI_NO_MATCH) {
  1984. switch (sni->type) {
  1985. case WOLFSSL_SNI_HOST_NAME:
  1986. if (data) {
  1987. *data = sni->data.host_name;
  1988. return (word16)XSTRLEN((char*)*data);
  1989. }
  1990. }
  1991. }
  1992. return 0;
  1993. }
  1994. /** Sets the options for a SNI object. */
  1995. void TLSX_SNI_SetOptions(TLSX* extensions, byte type, byte options)
  1996. {
  1997. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1998. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1999. if (sni)
  2000. sni->options = options;
  2001. }
  2002. /** Retrieves a SNI request from a client hello buffer. */
  2003. int TLSX_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz,
  2004. byte type, byte* sni, word32* inOutSz)
  2005. {
  2006. word32 offset = 0;
  2007. word32 len32 = 0;
  2008. word16 len16 = 0;
  2009. if (helloSz < RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + CLIENT_HELLO_FIRST)
  2010. return INCOMPLETE_DATA;
  2011. /* TLS record header */
  2012. if ((enum ContentType) clientHello[offset++] != handshake) {
  2013. /* checking for SSLv2.0 client hello according to: */
  2014. /* http://tools.ietf.org/html/rfc4346#appendix-E.1 */
  2015. if ((enum HandShakeType) clientHello[++offset] == client_hello) {
  2016. offset += ENUM_LEN + VERSION_SZ; /* skip version */
  2017. ato16(clientHello + offset, &len16);
  2018. offset += OPAQUE16_LEN;
  2019. if (len16 % 3) /* cipher_spec_length must be multiple of 3 */
  2020. return BUFFER_ERROR;
  2021. ato16(clientHello + offset, &len16);
  2022. /* Returning SNI_UNSUPPORTED do not increment offset here */
  2023. if (len16 != 0) /* session_id_length must be 0 */
  2024. return BUFFER_ERROR;
  2025. WOLFSSL_ERROR_VERBOSE(SNI_UNSUPPORTED);
  2026. return SNI_UNSUPPORTED;
  2027. }
  2028. return BUFFER_ERROR;
  2029. }
  2030. if (clientHello[offset++] != SSLv3_MAJOR)
  2031. return BUFFER_ERROR;
  2032. if (clientHello[offset++] < TLSv1_MINOR) {
  2033. WOLFSSL_ERROR_VERBOSE(SNI_UNSUPPORTED);
  2034. return SNI_UNSUPPORTED;
  2035. }
  2036. ato16(clientHello + offset, &len16);
  2037. offset += OPAQUE16_LEN;
  2038. if (offset + len16 > helloSz)
  2039. return INCOMPLETE_DATA;
  2040. /* Handshake header */
  2041. if ((enum HandShakeType) clientHello[offset] != client_hello)
  2042. return BUFFER_ERROR;
  2043. c24to32(clientHello + offset + 1, &len32);
  2044. offset += HANDSHAKE_HEADER_SZ;
  2045. if (offset + len32 > helloSz)
  2046. return BUFFER_ERROR;
  2047. /* client hello */
  2048. offset += VERSION_SZ + RAN_LEN; /* version, random */
  2049. if (helloSz < offset + clientHello[offset])
  2050. return BUFFER_ERROR;
  2051. offset += ENUM_LEN + clientHello[offset]; /* skip session id */
  2052. /* cypher suites */
  2053. if (helloSz < offset + OPAQUE16_LEN)
  2054. return BUFFER_ERROR;
  2055. ato16(clientHello + offset, &len16);
  2056. offset += OPAQUE16_LEN;
  2057. if (helloSz < offset + len16)
  2058. return BUFFER_ERROR;
  2059. offset += len16; /* skip cypher suites */
  2060. /* compression methods */
  2061. if (helloSz < offset + 1)
  2062. return BUFFER_ERROR;
  2063. if (helloSz < offset + clientHello[offset])
  2064. return BUFFER_ERROR;
  2065. offset += ENUM_LEN + clientHello[offset]; /* skip compression methods */
  2066. /* extensions */
  2067. if (helloSz < offset + OPAQUE16_LEN)
  2068. return 0; /* no extensions in client hello. */
  2069. ato16(clientHello + offset, &len16);
  2070. offset += OPAQUE16_LEN;
  2071. if (helloSz < offset + len16)
  2072. return BUFFER_ERROR;
  2073. while (len16 >= OPAQUE16_LEN + OPAQUE16_LEN) {
  2074. word16 extType;
  2075. word16 extLen;
  2076. ato16(clientHello + offset, &extType);
  2077. offset += OPAQUE16_LEN;
  2078. ato16(clientHello + offset, &extLen);
  2079. offset += OPAQUE16_LEN;
  2080. if (helloSz < offset + extLen)
  2081. return BUFFER_ERROR;
  2082. if (extType != TLSX_SERVER_NAME) {
  2083. offset += extLen; /* skip extension */
  2084. } else {
  2085. word16 listLen;
  2086. ato16(clientHello + offset, &listLen);
  2087. offset += OPAQUE16_LEN;
  2088. if (helloSz < offset + listLen)
  2089. return BUFFER_ERROR;
  2090. while (listLen > ENUM_LEN + OPAQUE16_LEN) {
  2091. byte sniType = clientHello[offset++];
  2092. word16 sniLen;
  2093. ato16(clientHello + offset, &sniLen);
  2094. offset += OPAQUE16_LEN;
  2095. if (helloSz < offset + sniLen)
  2096. return BUFFER_ERROR;
  2097. if (sniType != type) {
  2098. offset += sniLen;
  2099. listLen -= min(ENUM_LEN + OPAQUE16_LEN + sniLen, listLen);
  2100. continue;
  2101. }
  2102. *inOutSz = min(sniLen, *inOutSz);
  2103. XMEMCPY(sni, clientHello + offset, *inOutSz);
  2104. return WOLFSSL_SUCCESS;
  2105. }
  2106. }
  2107. len16 -= min(2 * OPAQUE16_LEN + extLen, len16);
  2108. }
  2109. return len16 ? BUFFER_ERROR : 0;
  2110. }
  2111. #endif
  2112. #define SNI_FREE_ALL TLSX_SNI_FreeAll
  2113. #define SNI_GET_SIZE TLSX_SNI_GetSize
  2114. #define SNI_WRITE TLSX_SNI_Write
  2115. #define SNI_PARSE TLSX_SNI_Parse
  2116. #define SNI_VERIFY_PARSE TLSX_SNI_VerifyParse
  2117. #else
  2118. #define SNI_FREE_ALL(list, heap) WC_DO_NOTHING
  2119. #define SNI_GET_SIZE(list) 0
  2120. #define SNI_WRITE(a, b) 0
  2121. #define SNI_PARSE(a, b, c, d) 0
  2122. #define SNI_VERIFY_PARSE(a, b) 0
  2123. #endif /* HAVE_SNI */
  2124. /******************************************************************************/
  2125. /* Trusted CA Key Indication */
  2126. /******************************************************************************/
  2127. #ifdef HAVE_TRUSTED_CA
  2128. /** Creates a new TCA object. */
  2129. static TCA* TLSX_TCA_New(byte type, const byte* id, word16 idSz, void* heap)
  2130. {
  2131. TCA* tca = (TCA*)XMALLOC(sizeof(TCA), heap, DYNAMIC_TYPE_TLSX);
  2132. if (tca) {
  2133. XMEMSET(tca, 0, sizeof(TCA));
  2134. tca->type = type;
  2135. switch (type) {
  2136. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2137. break;
  2138. #ifndef NO_SHA
  2139. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2140. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2141. if (idSz == WC_SHA_DIGEST_SIZE &&
  2142. (tca->id =
  2143. (byte*)XMALLOC(idSz, heap, DYNAMIC_TYPE_TLSX))) {
  2144. XMEMCPY(tca->id, id, idSz);
  2145. tca->idSz = idSz;
  2146. }
  2147. else {
  2148. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2149. tca = NULL;
  2150. }
  2151. break;
  2152. #endif
  2153. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2154. if (idSz > 0 &&
  2155. (tca->id =
  2156. (byte*)XMALLOC(idSz, heap, DYNAMIC_TYPE_TLSX))) {
  2157. XMEMCPY(tca->id, id, idSz);
  2158. tca->idSz = idSz;
  2159. }
  2160. else {
  2161. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2162. tca = NULL;
  2163. }
  2164. break;
  2165. default: /* invalid type */
  2166. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2167. tca = NULL;
  2168. }
  2169. }
  2170. (void)heap;
  2171. return tca;
  2172. }
  2173. /** Releases a TCA object. */
  2174. static void TLSX_TCA_Free(TCA* tca, void* heap)
  2175. {
  2176. (void)heap;
  2177. if (tca) {
  2178. if (tca->id)
  2179. XFREE(tca->id, heap, DYNAMIC_TYPE_TLSX);
  2180. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2181. }
  2182. }
  2183. /** Releases all TCA objects in the provided list. */
  2184. static void TLSX_TCA_FreeAll(TCA* list, void* heap)
  2185. {
  2186. TCA* tca;
  2187. while ((tca = list)) {
  2188. list = tca->next;
  2189. TLSX_TCA_Free(tca, heap);
  2190. }
  2191. }
  2192. /** Tells the buffered size of the TCA objects in a list. */
  2193. static word16 TLSX_TCA_GetSize(TCA* list)
  2194. {
  2195. TCA* tca;
  2196. word16 length = OPAQUE16_LEN; /* list length */
  2197. while ((tca = list)) {
  2198. list = tca->next;
  2199. length += ENUM_LEN; /* tca type */
  2200. switch (tca->type) {
  2201. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2202. break;
  2203. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2204. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2205. length += tca->idSz;
  2206. break;
  2207. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2208. length += OPAQUE16_LEN + tca->idSz;
  2209. break;
  2210. }
  2211. }
  2212. return length;
  2213. }
  2214. /** Writes the TCA objects of a list in a buffer. */
  2215. static word16 TLSX_TCA_Write(TCA* list, byte* output)
  2216. {
  2217. TCA* tca;
  2218. word16 offset = OPAQUE16_LEN; /* list length offset */
  2219. while ((tca = list)) {
  2220. list = tca->next;
  2221. output[offset++] = tca->type; /* tca type */
  2222. switch (tca->type) {
  2223. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2224. break;
  2225. #ifndef NO_SHA
  2226. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2227. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2228. if (tca->id != NULL) {
  2229. XMEMCPY(output + offset, tca->id, tca->idSz);
  2230. offset += tca->idSz;
  2231. }
  2232. else {
  2233. /* ID missing. Set to an empty string. */
  2234. c16toa(0, output + offset);
  2235. offset += OPAQUE16_LEN;
  2236. }
  2237. break;
  2238. #endif
  2239. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2240. if (tca->id != NULL) {
  2241. c16toa(tca->idSz, output + offset); /* tca length */
  2242. offset += OPAQUE16_LEN;
  2243. XMEMCPY(output + offset, tca->id, tca->idSz);
  2244. offset += tca->idSz;
  2245. }
  2246. else {
  2247. /* ID missing. Set to an empty string. */
  2248. c16toa(0, output + offset);
  2249. offset += OPAQUE16_LEN;
  2250. }
  2251. break;
  2252. default:
  2253. /* ID unknown. Set to an empty string. */
  2254. c16toa(0, output + offset);
  2255. offset += OPAQUE16_LEN;
  2256. }
  2257. }
  2258. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  2259. return offset;
  2260. }
  2261. #ifndef NO_WOLFSSL_SERVER
  2262. static TCA* TLSX_TCA_Find(TCA *list, byte type, const byte* id, word16 idSz)
  2263. {
  2264. TCA* tca = list;
  2265. while (tca && tca->type != type && type != WOLFSSL_TRUSTED_CA_PRE_AGREED &&
  2266. idSz != tca->idSz && !XMEMCMP(id, tca->id, idSz))
  2267. tca = tca->next;
  2268. return tca;
  2269. }
  2270. #endif /* NO_WOLFSSL_SERVER */
  2271. /** Parses a buffer of TCA extensions. */
  2272. static int TLSX_TCA_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2273. byte isRequest)
  2274. {
  2275. #ifndef NO_WOLFSSL_SERVER
  2276. word16 size = 0;
  2277. word16 offset = 0;
  2278. #endif
  2279. TLSX *extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS);
  2280. if (!extension)
  2281. extension = TLSX_Find(ssl->ctx->extensions, TLSX_TRUSTED_CA_KEYS);
  2282. if (!isRequest) {
  2283. #ifndef NO_WOLFSSL_CLIENT
  2284. if (!extension || !extension->data)
  2285. return TLSX_HandleUnsupportedExtension(ssl);
  2286. if (length > 0)
  2287. return BUFFER_ERROR; /* TCA response MUST be empty. */
  2288. /* Set the flag that we're good for keys */
  2289. TLSX_SetResponse(ssl, TLSX_TRUSTED_CA_KEYS);
  2290. return 0;
  2291. #endif
  2292. }
  2293. #ifndef NO_WOLFSSL_SERVER
  2294. if (!extension || !extension->data) {
  2295. /* Skipping, TCA not enabled at server side. */
  2296. return 0;
  2297. }
  2298. if (OPAQUE16_LEN > length)
  2299. return BUFFER_ERROR;
  2300. ato16(input, &size);
  2301. offset += OPAQUE16_LEN;
  2302. /* validating tca list length */
  2303. if (length != OPAQUE16_LEN + size)
  2304. return BUFFER_ERROR;
  2305. for (size = 0; offset < length; offset += size) {
  2306. TCA *tca = NULL;
  2307. byte type;
  2308. const byte* id = NULL;
  2309. word16 idSz = 0;
  2310. if (offset + ENUM_LEN > length)
  2311. return BUFFER_ERROR;
  2312. type = input[offset++];
  2313. switch (type) {
  2314. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2315. break;
  2316. #ifndef NO_SHA
  2317. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2318. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2319. if (offset + WC_SHA_DIGEST_SIZE > length)
  2320. return BUFFER_ERROR;
  2321. idSz = WC_SHA_DIGEST_SIZE;
  2322. id = input + offset;
  2323. offset += idSz;
  2324. break;
  2325. #endif
  2326. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2327. if (offset + OPAQUE16_LEN > length)
  2328. return BUFFER_ERROR;
  2329. ato16(input + offset, &idSz);
  2330. offset += OPAQUE16_LEN;
  2331. if ((offset > length) || (idSz > length - offset))
  2332. return BUFFER_ERROR;
  2333. id = input + offset;
  2334. offset += idSz;
  2335. break;
  2336. default:
  2337. WOLFSSL_ERROR_VERBOSE(TCA_INVALID_ID_TYPE);
  2338. return TCA_INVALID_ID_TYPE;
  2339. }
  2340. /* Find the type/ID in the TCA list. */
  2341. tca = TLSX_TCA_Find((TCA*)extension->data, type, id, idSz);
  2342. if (tca != NULL) {
  2343. /* Found it. Set the response flag and break out of the loop. */
  2344. TLSX_SetResponse(ssl, TLSX_TRUSTED_CA_KEYS);
  2345. break;
  2346. }
  2347. }
  2348. #else
  2349. (void)input;
  2350. #endif
  2351. return 0;
  2352. }
  2353. /* Checks to see if the server sent a response for the TCA. */
  2354. static int TLSX_TCA_VerifyParse(WOLFSSL* ssl, byte isRequest)
  2355. {
  2356. (void)ssl;
  2357. if (!isRequest) {
  2358. #ifndef NO_WOLFSSL_CLIENT
  2359. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS);
  2360. if (extension && !extension->resp) {
  2361. SendAlert(ssl, alert_fatal, handshake_failure);
  2362. WOLFSSL_ERROR_VERBOSE(TCA_ABSENT_ERROR);
  2363. return TCA_ABSENT_ERROR;
  2364. }
  2365. #endif /* NO_WOLFSSL_CLIENT */
  2366. }
  2367. return 0;
  2368. }
  2369. int TLSX_UseTrustedCA(TLSX** extensions, byte type,
  2370. const byte* id, word16 idSz, void* heap)
  2371. {
  2372. TLSX* extension;
  2373. TCA* tca = NULL;
  2374. if (extensions == NULL)
  2375. return BAD_FUNC_ARG;
  2376. if ((tca = TLSX_TCA_New(type, id, idSz, heap)) == NULL)
  2377. return MEMORY_E;
  2378. extension = TLSX_Find(*extensions, TLSX_TRUSTED_CA_KEYS);
  2379. if (!extension) {
  2380. int ret = TLSX_Push(extensions, TLSX_TRUSTED_CA_KEYS, (void*)tca, heap);
  2381. if (ret != 0) {
  2382. TLSX_TCA_Free(tca, heap);
  2383. return ret;
  2384. }
  2385. }
  2386. else {
  2387. /* push new TCA object to extension data. */
  2388. tca->next = (TCA*)extension->data;
  2389. extension->data = (void*)tca;
  2390. }
  2391. return WOLFSSL_SUCCESS;
  2392. }
  2393. #define TCA_FREE_ALL TLSX_TCA_FreeAll
  2394. #define TCA_GET_SIZE TLSX_TCA_GetSize
  2395. #define TCA_WRITE TLSX_TCA_Write
  2396. #define TCA_PARSE TLSX_TCA_Parse
  2397. #define TCA_VERIFY_PARSE TLSX_TCA_VerifyParse
  2398. #else /* HAVE_TRUSTED_CA */
  2399. #define TCA_FREE_ALL(list, heap) WC_DO_NOTHING
  2400. #define TCA_GET_SIZE(list) 0
  2401. #define TCA_WRITE(a, b) 0
  2402. #define TCA_PARSE(a, b, c, d) 0
  2403. #define TCA_VERIFY_PARSE(a, b) 0
  2404. #endif /* HAVE_TRUSTED_CA */
  2405. /******************************************************************************/
  2406. /* Max Fragment Length Negotiation */
  2407. /******************************************************************************/
  2408. #ifdef HAVE_MAX_FRAGMENT
  2409. static word16 TLSX_MFL_Write(byte* data, byte* output)
  2410. {
  2411. output[0] = data[0];
  2412. return ENUM_LEN;
  2413. }
  2414. static int TLSX_MFL_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2415. byte isRequest)
  2416. {
  2417. if (length != ENUM_LEN)
  2418. return BUFFER_ERROR;
  2419. #ifdef WOLFSSL_OLD_UNSUPPORTED_EXTENSION
  2420. (void) isRequest;
  2421. #else
  2422. if (!isRequest)
  2423. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_MAX_FRAGMENT_LENGTH))
  2424. return TLSX_HandleUnsupportedExtension(ssl);
  2425. #endif
  2426. switch (*input) {
  2427. case WOLFSSL_MFL_2_8 : ssl->max_fragment = 256; break;
  2428. case WOLFSSL_MFL_2_9 : ssl->max_fragment = 512; break;
  2429. case WOLFSSL_MFL_2_10: ssl->max_fragment = 1024; break;
  2430. case WOLFSSL_MFL_2_11: ssl->max_fragment = 2048; break;
  2431. case WOLFSSL_MFL_2_12: ssl->max_fragment = 4096; break;
  2432. case WOLFSSL_MFL_2_13: ssl->max_fragment = 8192; break;
  2433. default:
  2434. SendAlert(ssl, alert_fatal, illegal_parameter);
  2435. WOLFSSL_ERROR_VERBOSE(UNKNOWN_MAX_FRAG_LEN_E);
  2436. return UNKNOWN_MAX_FRAG_LEN_E;
  2437. }
  2438. #ifndef NO_WOLFSSL_SERVER
  2439. if (isRequest) {
  2440. int ret = TLSX_UseMaxFragment(&ssl->extensions, *input, ssl->heap);
  2441. if (ret != WOLFSSL_SUCCESS)
  2442. return ret; /* throw error */
  2443. TLSX_SetResponse(ssl, TLSX_MAX_FRAGMENT_LENGTH);
  2444. }
  2445. #endif
  2446. return 0;
  2447. }
  2448. int TLSX_UseMaxFragment(TLSX** extensions, byte mfl, void* heap)
  2449. {
  2450. byte* data = NULL;
  2451. int ret = 0;
  2452. if (extensions == NULL || mfl < WOLFSSL_MFL_MIN || mfl > WOLFSSL_MFL_MAX)
  2453. return BAD_FUNC_ARG;
  2454. data = (byte*)XMALLOC(ENUM_LEN, heap, DYNAMIC_TYPE_TLSX);
  2455. if (data == NULL)
  2456. return MEMORY_E;
  2457. data[0] = mfl;
  2458. ret = TLSX_Push(extensions, TLSX_MAX_FRAGMENT_LENGTH, data, heap);
  2459. if (ret != 0) {
  2460. XFREE(data, heap, DYNAMIC_TYPE_TLSX);
  2461. return ret;
  2462. }
  2463. return WOLFSSL_SUCCESS;
  2464. }
  2465. #define MFL_FREE_ALL(data, heap) XFREE(data, (heap), DYNAMIC_TYPE_TLSX)
  2466. #define MFL_GET_SIZE(data) ENUM_LEN
  2467. #define MFL_WRITE TLSX_MFL_Write
  2468. #define MFL_PARSE TLSX_MFL_Parse
  2469. #else
  2470. #define MFL_FREE_ALL(a, b) WC_DO_NOTHING
  2471. #define MFL_GET_SIZE(a) 0
  2472. #define MFL_WRITE(a, b) 0
  2473. #define MFL_PARSE(a, b, c, d) 0
  2474. #endif /* HAVE_MAX_FRAGMENT */
  2475. /******************************************************************************/
  2476. /* Truncated HMAC */
  2477. /******************************************************************************/
  2478. #ifdef HAVE_TRUNCATED_HMAC
  2479. static int TLSX_THM_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2480. byte isRequest)
  2481. {
  2482. if (length != 0 || input == NULL)
  2483. return BUFFER_ERROR;
  2484. if (!isRequest) {
  2485. #ifndef WOLFSSL_OLD_UNSUPPORTED_EXTENSION
  2486. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_TRUNCATED_HMAC))
  2487. return TLSX_HandleUnsupportedExtension(ssl);
  2488. #endif
  2489. }
  2490. else {
  2491. #ifndef NO_WOLFSSL_SERVER
  2492. int ret = TLSX_UseTruncatedHMAC(&ssl->extensions, ssl->heap);
  2493. if (ret != WOLFSSL_SUCCESS)
  2494. return ret; /* throw error */
  2495. TLSX_SetResponse(ssl, TLSX_TRUNCATED_HMAC);
  2496. #endif
  2497. }
  2498. ssl->truncated_hmac = 1;
  2499. return 0;
  2500. }
  2501. int TLSX_UseTruncatedHMAC(TLSX** extensions, void* heap)
  2502. {
  2503. int ret = 0;
  2504. if (extensions == NULL)
  2505. return BAD_FUNC_ARG;
  2506. ret = TLSX_Push(extensions, TLSX_TRUNCATED_HMAC, NULL, heap);
  2507. if (ret != 0)
  2508. return ret;
  2509. return WOLFSSL_SUCCESS;
  2510. }
  2511. #define THM_PARSE TLSX_THM_Parse
  2512. #else
  2513. #define THM_PARSE(a, b, c, d) 0
  2514. #endif /* HAVE_TRUNCATED_HMAC */
  2515. /******************************************************************************/
  2516. /* Certificate Status Request */
  2517. /******************************************************************************/
  2518. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  2519. static void TLSX_CSR_Free(CertificateStatusRequest* csr, void* heap)
  2520. {
  2521. switch (csr->status_type) {
  2522. case WOLFSSL_CSR_OCSP:
  2523. FreeOcspRequest(&csr->request.ocsp);
  2524. break;
  2525. }
  2526. #ifdef WOLFSSL_TLS13
  2527. if (csr->response.buffer != NULL) {
  2528. XFREE(csr->response.buffer, csr->ssl->heap,
  2529. DYNAMIC_TYPE_TMP_BUFFER);
  2530. }
  2531. #endif
  2532. XFREE(csr, heap, DYNAMIC_TYPE_TLSX);
  2533. (void)heap;
  2534. }
  2535. static word16 TLSX_CSR_GetSize(CertificateStatusRequest* csr, byte isRequest)
  2536. {
  2537. word16 size = 0;
  2538. /* shut up compiler warnings */
  2539. (void) csr; (void) isRequest;
  2540. #ifndef NO_WOLFSSL_CLIENT
  2541. if (isRequest) {
  2542. switch (csr->status_type) {
  2543. case WOLFSSL_CSR_OCSP:
  2544. size += ENUM_LEN + 2 * OPAQUE16_LEN;
  2545. if (csr->request.ocsp.nonceSz)
  2546. size += OCSP_NONCE_EXT_SZ;
  2547. break;
  2548. }
  2549. }
  2550. #endif
  2551. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  2552. if (!isRequest && csr->ssl->options.tls1_3)
  2553. return OPAQUE8_LEN + OPAQUE24_LEN + csr->response.length;
  2554. #endif
  2555. return size;
  2556. }
  2557. static word16 TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output,
  2558. byte isRequest)
  2559. {
  2560. /* shut up compiler warnings */
  2561. (void) csr; (void) output; (void) isRequest;
  2562. #ifndef NO_WOLFSSL_CLIENT
  2563. if (isRequest) {
  2564. word16 offset = 0;
  2565. word16 length = 0;
  2566. /* type */
  2567. output[offset++] = csr->status_type;
  2568. switch (csr->status_type) {
  2569. case WOLFSSL_CSR_OCSP:
  2570. /* responder id list */
  2571. c16toa(0, output + offset);
  2572. offset += OPAQUE16_LEN;
  2573. /* request extensions */
  2574. if (csr->request.ocsp.nonceSz)
  2575. length = (word16)EncodeOcspRequestExtensions(
  2576. &csr->request.ocsp,
  2577. output + offset + OPAQUE16_LEN,
  2578. OCSP_NONCE_EXT_SZ);
  2579. c16toa(length, output + offset);
  2580. offset += OPAQUE16_LEN + length;
  2581. break;
  2582. }
  2583. return offset;
  2584. }
  2585. #endif
  2586. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  2587. if (!isRequest && csr->ssl->options.tls1_3) {
  2588. word16 offset = 0;
  2589. output[offset++] = csr->status_type;
  2590. c32to24(csr->response.length, output + offset);
  2591. offset += OPAQUE24_LEN;
  2592. XMEMCPY(output + offset, csr->response.buffer, csr->response.length);
  2593. offset += csr->response.length;
  2594. return offset;
  2595. }
  2596. #endif
  2597. return 0;
  2598. }
  2599. static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2600. byte isRequest)
  2601. {
  2602. int ret;
  2603. #if !defined(NO_WOLFSSL_SERVER)
  2604. byte status_type;
  2605. word16 size = 0;
  2606. #if defined(WOLFSSL_TLS13)
  2607. DecodedCert* cert;
  2608. #endif
  2609. #endif
  2610. #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) \
  2611. && defined(WOLFSSL_TLS13)
  2612. OcspRequest* request;
  2613. TLSX* extension;
  2614. CertificateStatusRequest* csr;
  2615. #endif
  2616. #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_TLS13) \
  2617. || !defined(NO_WOLFSSL_SERVER)
  2618. word32 offset = 0;
  2619. #endif
  2620. #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_TLS13)
  2621. word32 resp_length = 0;
  2622. #endif
  2623. /* shut up compiler warnings */
  2624. (void) ssl; (void) input;
  2625. if (!isRequest) {
  2626. #ifndef NO_WOLFSSL_CLIENT
  2627. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2628. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2629. if (!csr) {
  2630. /* look at context level */
  2631. extension = TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST);
  2632. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2633. if (!csr) /* unexpected extension */
  2634. return TLSX_HandleUnsupportedExtension(ssl);
  2635. /* enable extension at ssl level */
  2636. ret = TLSX_UseCertificateStatusRequest(&ssl->extensions,
  2637. csr->status_type, csr->options, ssl,
  2638. ssl->heap, ssl->devId);
  2639. if (ret != WOLFSSL_SUCCESS)
  2640. return ret == 0 ? -1 : ret;
  2641. switch (csr->status_type) {
  2642. case WOLFSSL_CSR_OCSP:
  2643. /* propagate nonce */
  2644. if (csr->request.ocsp.nonceSz) {
  2645. request =
  2646. (OcspRequest*)TLSX_CSR_GetRequest(ssl->extensions);
  2647. if (request) {
  2648. XMEMCPY(request->nonce, csr->request.ocsp.nonce,
  2649. csr->request.ocsp.nonceSz);
  2650. request->nonceSz = csr->request.ocsp.nonceSz;
  2651. }
  2652. }
  2653. break;
  2654. }
  2655. }
  2656. ssl->status_request = 1;
  2657. #ifdef WOLFSSL_TLS13
  2658. if (ssl->options.tls1_3) {
  2659. /* Get the new extension potentially created above. */
  2660. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2661. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2662. if (csr == NULL)
  2663. return MEMORY_ERROR;
  2664. ret = 0;
  2665. if (OPAQUE8_LEN + OPAQUE24_LEN > length)
  2666. ret = BUFFER_ERROR;
  2667. if (ret == 0 && input[offset++] != WOLFSSL_CSR_OCSP) {
  2668. ret = BAD_CERTIFICATE_STATUS_ERROR;
  2669. WOLFSSL_ERROR_VERBOSE(ret);
  2670. }
  2671. if (ret == 0) {
  2672. c24to32(input + offset, &resp_length);
  2673. offset += OPAQUE24_LEN;
  2674. if (offset + resp_length != length)
  2675. ret = BUFFER_ERROR;
  2676. }
  2677. if (ret == 0) {
  2678. csr->response.buffer = (byte*)XMALLOC(resp_length, ssl->heap,
  2679. DYNAMIC_TYPE_TMP_BUFFER);
  2680. if (csr->response.buffer == NULL)
  2681. ret = MEMORY_ERROR;
  2682. }
  2683. if (ret == 0) {
  2684. XMEMCPY(csr->response.buffer, input + offset, resp_length);
  2685. csr->response.length = resp_length;
  2686. }
  2687. return ret;
  2688. }
  2689. else
  2690. #endif
  2691. {
  2692. /* extension_data MUST be empty. */
  2693. return length ? BUFFER_ERROR : 0;
  2694. }
  2695. #endif
  2696. }
  2697. else {
  2698. #ifndef NO_WOLFSSL_SERVER
  2699. if (length == 0)
  2700. return 0;
  2701. status_type = input[offset++];
  2702. switch (status_type) {
  2703. case WOLFSSL_CSR_OCSP: {
  2704. /* skip responder_id_list */
  2705. if ((int)(length - offset) < OPAQUE16_LEN)
  2706. return BUFFER_ERROR;
  2707. ato16(input + offset, &size);
  2708. offset += OPAQUE16_LEN + size;
  2709. /* skip request_extensions */
  2710. if ((int)(length - offset) < OPAQUE16_LEN)
  2711. return BUFFER_ERROR;
  2712. ato16(input + offset, &size);
  2713. offset += OPAQUE16_LEN + size;
  2714. if (offset > length)
  2715. return BUFFER_ERROR;
  2716. /* is able to send OCSP response? */
  2717. if (SSL_CM(ssl) == NULL || !SSL_CM(ssl)->ocspStaplingEnabled)
  2718. return 0;
  2719. }
  2720. break;
  2721. /* unknown status type */
  2722. default:
  2723. return 0;
  2724. }
  2725. /* if using status_request and already sending it, skip this one */
  2726. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2727. if (ssl->status_request_v2)
  2728. return 0;
  2729. #endif
  2730. /* accept the first good status_type and return */
  2731. ret = TLSX_UseCertificateStatusRequest(&ssl->extensions, status_type,
  2732. 0, ssl, ssl->heap, ssl->devId);
  2733. if (ret != WOLFSSL_SUCCESS)
  2734. return ret == 0 ? -1 : ret; /* throw error */
  2735. #if defined(WOLFSSL_TLS13)
  2736. if (ssl->options.tls1_3) {
  2737. if (ssl->buffers.certificate == NULL) {
  2738. WOLFSSL_MSG("Certificate buffer not set!");
  2739. return BUFFER_ERROR;
  2740. }
  2741. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
  2742. DYNAMIC_TYPE_DCERT);
  2743. if (cert == NULL) {
  2744. return MEMORY_E;
  2745. }
  2746. InitDecodedCert(cert, ssl->buffers.certificate->buffer,
  2747. ssl->buffers.certificate->length, ssl->heap);
  2748. ret = ParseCert(cert, CERT_TYPE, 1, SSL_CM(ssl));
  2749. if (ret != 0) {
  2750. FreeDecodedCert(cert);
  2751. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2752. /* Let's not error out the connection if we can't verify our
  2753. * cert */
  2754. if (ret == ASN_SELF_SIGNED_E || ret == ASN_NO_SIGNER_E)
  2755. ret = 0;
  2756. return ret;
  2757. }
  2758. ret = TLSX_CSR_InitRequest(ssl->extensions, cert, ssl->heap);
  2759. if (ret != 0 ) {
  2760. FreeDecodedCert(cert);
  2761. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2762. return ret;
  2763. }
  2764. FreeDecodedCert(cert);
  2765. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2766. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2767. csr = extension ?
  2768. (CertificateStatusRequest*)extension->data : NULL;
  2769. if (csr == NULL)
  2770. return MEMORY_ERROR;
  2771. request = &csr->request.ocsp;
  2772. ret = CreateOcspResponse(ssl, &request, &csr->response);
  2773. if (ret != 0)
  2774. return ret;
  2775. if (csr->response.buffer)
  2776. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST);
  2777. }
  2778. else
  2779. #endif
  2780. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST);
  2781. ssl->status_request = status_type;
  2782. #endif
  2783. }
  2784. return 0;
  2785. }
  2786. int TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert, void* heap)
  2787. {
  2788. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST);
  2789. CertificateStatusRequest* csr = extension ?
  2790. (CertificateStatusRequest*)extension->data : NULL;
  2791. int ret = 0;
  2792. if (csr) {
  2793. switch (csr->status_type) {
  2794. case WOLFSSL_CSR_OCSP: {
  2795. byte nonce[MAX_OCSP_NONCE_SZ];
  2796. int nonceSz = csr->request.ocsp.nonceSz;
  2797. /* preserve nonce */
  2798. XMEMCPY(nonce, csr->request.ocsp.nonce, nonceSz);
  2799. if ((ret = InitOcspRequest(&csr->request.ocsp, cert, 0, heap))
  2800. != 0)
  2801. return ret;
  2802. /* restore nonce */
  2803. XMEMCPY(csr->request.ocsp.nonce, nonce, nonceSz);
  2804. csr->request.ocsp.nonceSz = nonceSz;
  2805. }
  2806. break;
  2807. }
  2808. }
  2809. return ret;
  2810. }
  2811. void* TLSX_CSR_GetRequest(TLSX* extensions)
  2812. {
  2813. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST);
  2814. CertificateStatusRequest* csr = extension ?
  2815. (CertificateStatusRequest*)extension->data : NULL;
  2816. if (csr) {
  2817. switch (csr->status_type) {
  2818. case WOLFSSL_CSR_OCSP:
  2819. return &csr->request.ocsp;
  2820. }
  2821. }
  2822. return NULL;
  2823. }
  2824. int TLSX_CSR_ForceRequest(WOLFSSL* ssl)
  2825. {
  2826. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2827. CertificateStatusRequest* csr = extension ?
  2828. (CertificateStatusRequest*)extension->data : NULL;
  2829. if (csr) {
  2830. switch (csr->status_type) {
  2831. case WOLFSSL_CSR_OCSP:
  2832. if (SSL_CM(ssl)->ocspEnabled) {
  2833. csr->request.ocsp.ssl = ssl;
  2834. return CheckOcspRequest(SSL_CM(ssl)->ocsp,
  2835. &csr->request.ocsp, NULL, NULL);
  2836. }
  2837. else {
  2838. WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL);
  2839. return OCSP_LOOKUP_FAIL;
  2840. }
  2841. }
  2842. }
  2843. return 0;
  2844. }
  2845. int TLSX_UseCertificateStatusRequest(TLSX** extensions, byte status_type,
  2846. byte options, WOLFSSL* ssl, void* heap,
  2847. int devId)
  2848. {
  2849. CertificateStatusRequest* csr = NULL;
  2850. int ret = 0;
  2851. if (!extensions || status_type != WOLFSSL_CSR_OCSP)
  2852. return BAD_FUNC_ARG;
  2853. csr = (CertificateStatusRequest*)
  2854. XMALLOC(sizeof(CertificateStatusRequest), heap, DYNAMIC_TYPE_TLSX);
  2855. if (!csr)
  2856. return MEMORY_E;
  2857. ForceZero(csr, sizeof(CertificateStatusRequest));
  2858. csr->status_type = status_type;
  2859. csr->options = options;
  2860. csr->ssl = ssl;
  2861. switch (csr->status_type) {
  2862. case WOLFSSL_CSR_OCSP:
  2863. if (options & WOLFSSL_CSR_OCSP_USE_NONCE) {
  2864. WC_RNG rng;
  2865. #ifndef HAVE_FIPS
  2866. ret = wc_InitRng_ex(&rng, heap, devId);
  2867. #else
  2868. ret = wc_InitRng(&rng);
  2869. (void)devId;
  2870. #endif
  2871. if (ret == 0) {
  2872. if (wc_RNG_GenerateBlock(&rng, csr->request.ocsp.nonce,
  2873. MAX_OCSP_NONCE_SZ) == 0)
  2874. csr->request.ocsp.nonceSz = MAX_OCSP_NONCE_SZ;
  2875. wc_FreeRng(&rng);
  2876. }
  2877. }
  2878. break;
  2879. }
  2880. if ((ret = TLSX_Push(extensions, TLSX_STATUS_REQUEST, csr, heap)) != 0) {
  2881. XFREE(csr, heap, DYNAMIC_TYPE_TLSX);
  2882. return ret;
  2883. }
  2884. return WOLFSSL_SUCCESS;
  2885. }
  2886. #define CSR_FREE_ALL TLSX_CSR_Free
  2887. #define CSR_GET_SIZE TLSX_CSR_GetSize
  2888. #define CSR_WRITE TLSX_CSR_Write
  2889. #define CSR_PARSE TLSX_CSR_Parse
  2890. #else
  2891. #define CSR_FREE_ALL(data, heap) WC_DO_NOTHING
  2892. #define CSR_GET_SIZE(a, b) 0
  2893. #define CSR_WRITE(a, b, c) 0
  2894. #define CSR_PARSE(a, b, c, d) 0
  2895. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
  2896. /******************************************************************************/
  2897. /* Certificate Status Request v2 */
  2898. /******************************************************************************/
  2899. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2900. static void TLSX_CSR2_FreeAll(CertificateStatusRequestItemV2* csr2, void* heap)
  2901. {
  2902. CertificateStatusRequestItemV2* next;
  2903. for (; csr2; csr2 = next) {
  2904. next = csr2->next;
  2905. switch (csr2->status_type) {
  2906. case WOLFSSL_CSR2_OCSP:
  2907. case WOLFSSL_CSR2_OCSP_MULTI:
  2908. while(csr2->requests--)
  2909. FreeOcspRequest(&csr2->request.ocsp[csr2->requests]);
  2910. break;
  2911. }
  2912. XFREE(csr2, heap, DYNAMIC_TYPE_TLSX);
  2913. }
  2914. (void)heap;
  2915. }
  2916. static word16 TLSX_CSR2_GetSize(CertificateStatusRequestItemV2* csr2,
  2917. byte isRequest)
  2918. {
  2919. word16 size = 0;
  2920. /* shut up compiler warnings */
  2921. (void) csr2; (void) isRequest;
  2922. #ifndef NO_WOLFSSL_CLIENT
  2923. if (isRequest) {
  2924. CertificateStatusRequestItemV2* next;
  2925. for (size = OPAQUE16_LEN; csr2; csr2 = next) {
  2926. next = csr2->next;
  2927. switch (csr2->status_type) {
  2928. case WOLFSSL_CSR2_OCSP:
  2929. case WOLFSSL_CSR2_OCSP_MULTI:
  2930. size += ENUM_LEN + 3 * OPAQUE16_LEN;
  2931. if (csr2->request.ocsp[0].nonceSz)
  2932. size += OCSP_NONCE_EXT_SZ;
  2933. break;
  2934. }
  2935. }
  2936. }
  2937. #endif
  2938. return size;
  2939. }
  2940. static word16 TLSX_CSR2_Write(CertificateStatusRequestItemV2* csr2,
  2941. byte* output, byte isRequest)
  2942. {
  2943. /* shut up compiler warnings */
  2944. (void) csr2; (void) output; (void) isRequest;
  2945. #ifndef NO_WOLFSSL_CLIENT
  2946. if (isRequest) {
  2947. word16 offset;
  2948. word16 length;
  2949. for (offset = OPAQUE16_LEN; csr2 != NULL; csr2 = csr2->next) {
  2950. /* status_type */
  2951. output[offset++] = csr2->status_type;
  2952. /* request */
  2953. switch (csr2->status_type) {
  2954. case WOLFSSL_CSR2_OCSP:
  2955. case WOLFSSL_CSR2_OCSP_MULTI:
  2956. /* request_length */
  2957. length = 2 * OPAQUE16_LEN;
  2958. if (csr2->request.ocsp[0].nonceSz)
  2959. length += OCSP_NONCE_EXT_SZ;
  2960. c16toa(length, output + offset);
  2961. offset += OPAQUE16_LEN;
  2962. /* responder id list */
  2963. c16toa(0, output + offset);
  2964. offset += OPAQUE16_LEN;
  2965. /* request extensions */
  2966. length = 0;
  2967. if (csr2->request.ocsp[0].nonceSz)
  2968. length = (word16)EncodeOcspRequestExtensions(
  2969. &csr2->request.ocsp[0],
  2970. output + offset + OPAQUE16_LEN,
  2971. OCSP_NONCE_EXT_SZ);
  2972. c16toa(length, output + offset);
  2973. offset += OPAQUE16_LEN + length;
  2974. break;
  2975. }
  2976. }
  2977. /* list size */
  2978. c16toa(offset - OPAQUE16_LEN, output);
  2979. return offset;
  2980. }
  2981. #endif
  2982. return 0;
  2983. }
  2984. static int TLSX_CSR2_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2985. byte isRequest)
  2986. {
  2987. int ret;
  2988. /* shut up compiler warnings */
  2989. (void) ssl; (void) input;
  2990. if (!isRequest) {
  2991. #ifndef NO_WOLFSSL_CLIENT
  2992. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST_V2);
  2993. CertificateStatusRequestItemV2* csr2 = extension ?
  2994. (CertificateStatusRequestItemV2*)extension->data : NULL;
  2995. if (!csr2) {
  2996. /* look at context level */
  2997. extension = TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST_V2);
  2998. csr2 = extension ?
  2999. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3000. if (!csr2) /* unexpected extension */
  3001. return TLSX_HandleUnsupportedExtension(ssl);
  3002. /* enable extension at ssl level */
  3003. for (; csr2; csr2 = csr2->next) {
  3004. ret = TLSX_UseCertificateStatusRequestV2(&ssl->extensions,
  3005. csr2->status_type, csr2->options, ssl->heap,
  3006. ssl->devId);
  3007. if (ret != WOLFSSL_SUCCESS)
  3008. return ret;
  3009. switch (csr2->status_type) {
  3010. case WOLFSSL_CSR2_OCSP:
  3011. /* followed by */
  3012. case WOLFSSL_CSR2_OCSP_MULTI:
  3013. /* propagate nonce */
  3014. if (csr2->request.ocsp[0].nonceSz) {
  3015. OcspRequest* request =
  3016. (OcspRequest*)TLSX_CSR2_GetRequest(ssl->extensions,
  3017. csr2->status_type, 0);
  3018. if (request) {
  3019. XMEMCPY(request->nonce,
  3020. csr2->request.ocsp[0].nonce,
  3021. csr2->request.ocsp[0].nonceSz);
  3022. request->nonceSz =
  3023. csr2->request.ocsp[0].nonceSz;
  3024. }
  3025. }
  3026. break;
  3027. }
  3028. }
  3029. }
  3030. ssl->status_request_v2 = 1;
  3031. return length ? BUFFER_ERROR : 0; /* extension_data MUST be empty. */
  3032. #endif
  3033. }
  3034. else {
  3035. #ifndef NO_WOLFSSL_SERVER
  3036. byte status_type;
  3037. word16 request_length;
  3038. word16 offset = 0;
  3039. word16 size = 0;
  3040. /* list size */
  3041. if (offset + OPAQUE16_LEN >= length) {
  3042. return BUFFER_E;
  3043. }
  3044. ato16(input + offset, &request_length);
  3045. offset += OPAQUE16_LEN;
  3046. if (length - OPAQUE16_LEN != request_length)
  3047. return BUFFER_ERROR;
  3048. while (length > offset) {
  3049. if ((int)(length - offset) < ENUM_LEN + OPAQUE16_LEN)
  3050. return BUFFER_ERROR;
  3051. status_type = input[offset++];
  3052. ato16(input + offset, &request_length);
  3053. offset += OPAQUE16_LEN;
  3054. if (length - offset < request_length)
  3055. return BUFFER_ERROR;
  3056. switch (status_type) {
  3057. case WOLFSSL_CSR2_OCSP:
  3058. case WOLFSSL_CSR2_OCSP_MULTI:
  3059. /* skip responder_id_list */
  3060. if ((int)(length - offset) < OPAQUE16_LEN)
  3061. return BUFFER_ERROR;
  3062. ato16(input + offset, &size);
  3063. if (length - offset < size)
  3064. return BUFFER_ERROR;
  3065. offset += OPAQUE16_LEN + size;
  3066. /* skip request_extensions */
  3067. if ((int)(length - offset) < OPAQUE16_LEN)
  3068. return BUFFER_ERROR;
  3069. ato16(input + offset, &size);
  3070. if (length - offset < size)
  3071. return BUFFER_ERROR;
  3072. offset += OPAQUE16_LEN + size;
  3073. if (offset > length)
  3074. return BUFFER_ERROR;
  3075. /* is able to send OCSP response? */
  3076. if (SSL_CM(ssl) == NULL
  3077. || !SSL_CM(ssl)->ocspStaplingEnabled)
  3078. continue;
  3079. break;
  3080. default:
  3081. /* unknown status type, skipping! */
  3082. offset += request_length;
  3083. continue;
  3084. }
  3085. /* if using status_request and already sending it, remove it
  3086. * and prefer to use the v2 version */
  3087. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  3088. if (ssl->status_request) {
  3089. ssl->status_request = 0;
  3090. TLSX_Remove(&ssl->extensions, TLSX_STATUS_REQUEST, ssl->heap);
  3091. }
  3092. #endif
  3093. /* TLS 1.3 servers MUST NOT act upon presence or information in
  3094. * this extension (RFC 8448 Section 4.4.2.1).
  3095. */
  3096. if (!IsAtLeastTLSv1_3(ssl->version)) {
  3097. /* accept the first good status_type and return */
  3098. ret = TLSX_UseCertificateStatusRequestV2(&ssl->extensions,
  3099. status_type, 0, ssl->heap, ssl->devId);
  3100. if (ret != WOLFSSL_SUCCESS)
  3101. return ret; /* throw error */
  3102. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST_V2);
  3103. ssl->status_request_v2 = status_type;
  3104. }
  3105. return 0;
  3106. }
  3107. #endif
  3108. }
  3109. return 0;
  3110. }
  3111. int TLSX_CSR2_InitRequests(TLSX* extensions, DecodedCert* cert, byte isPeer,
  3112. void* heap)
  3113. {
  3114. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2);
  3115. CertificateStatusRequestItemV2* csr2 = extension ?
  3116. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3117. int ret = 0;
  3118. for (; csr2; csr2 = csr2->next) {
  3119. switch (csr2->status_type) {
  3120. case WOLFSSL_CSR2_OCSP:
  3121. if (!isPeer || csr2->requests != 0)
  3122. break;
  3123. FALL_THROUGH; /* followed by */
  3124. case WOLFSSL_CSR2_OCSP_MULTI: {
  3125. if (csr2->requests < 1 + MAX_CHAIN_DEPTH) {
  3126. byte nonce[MAX_OCSP_NONCE_SZ];
  3127. int nonceSz = csr2->request.ocsp[0].nonceSz;
  3128. /* preserve nonce, replicating nonce of ocsp[0] */
  3129. XMEMCPY(nonce, csr2->request.ocsp[0].nonce, nonceSz);
  3130. if ((ret = InitOcspRequest(
  3131. &csr2->request.ocsp[csr2->requests], cert,
  3132. 0, heap)) != 0)
  3133. return ret;
  3134. /* restore nonce */
  3135. XMEMCPY(csr2->request.ocsp[csr2->requests].nonce,
  3136. nonce, nonceSz);
  3137. csr2->request.ocsp[csr2->requests].nonceSz = nonceSz;
  3138. csr2->requests++;
  3139. }
  3140. }
  3141. break;
  3142. }
  3143. }
  3144. (void)cert;
  3145. return ret;
  3146. }
  3147. void* TLSX_CSR2_GetRequest(TLSX* extensions, byte status_type, byte idx)
  3148. {
  3149. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2);
  3150. CertificateStatusRequestItemV2* csr2 = extension ?
  3151. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3152. for (; csr2; csr2 = csr2->next) {
  3153. if (csr2->status_type == status_type) {
  3154. switch (csr2->status_type) {
  3155. case WOLFSSL_CSR2_OCSP:
  3156. /* followed by */
  3157. case WOLFSSL_CSR2_OCSP_MULTI:
  3158. /* requests are initialized in the reverse order */
  3159. return idx < csr2->requests
  3160. ? &csr2->request.ocsp[csr2->requests - idx - 1]
  3161. : NULL;
  3162. }
  3163. }
  3164. }
  3165. return NULL;
  3166. }
  3167. int TLSX_CSR2_ForceRequest(WOLFSSL* ssl)
  3168. {
  3169. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST_V2);
  3170. CertificateStatusRequestItemV2* csr2 = extension ?
  3171. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3172. /* forces only the first one */
  3173. if (csr2) {
  3174. switch (csr2->status_type) {
  3175. case WOLFSSL_CSR2_OCSP:
  3176. /* followed by */
  3177. case WOLFSSL_CSR2_OCSP_MULTI:
  3178. if (SSL_CM(ssl)->ocspEnabled) {
  3179. csr2->request.ocsp[0].ssl = ssl;
  3180. return CheckOcspRequest(SSL_CM(ssl)->ocsp,
  3181. &csr2->request.ocsp[0], NULL, NULL);
  3182. }
  3183. else {
  3184. WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL);
  3185. return OCSP_LOOKUP_FAIL;
  3186. }
  3187. }
  3188. }
  3189. return 0;
  3190. }
  3191. int TLSX_UseCertificateStatusRequestV2(TLSX** extensions, byte status_type,
  3192. byte options, void* heap, int devId)
  3193. {
  3194. TLSX* extension = NULL;
  3195. CertificateStatusRequestItemV2* csr2 = NULL;
  3196. int ret = 0;
  3197. if (!extensions)
  3198. return BAD_FUNC_ARG;
  3199. if (status_type != WOLFSSL_CSR2_OCSP
  3200. && status_type != WOLFSSL_CSR2_OCSP_MULTI)
  3201. return BAD_FUNC_ARG;
  3202. csr2 = (CertificateStatusRequestItemV2*)
  3203. XMALLOC(sizeof(CertificateStatusRequestItemV2), heap, DYNAMIC_TYPE_TLSX);
  3204. if (!csr2)
  3205. return MEMORY_E;
  3206. ForceZero(csr2, sizeof(CertificateStatusRequestItemV2));
  3207. csr2->status_type = status_type;
  3208. csr2->options = options;
  3209. csr2->next = NULL;
  3210. switch (csr2->status_type) {
  3211. case WOLFSSL_CSR2_OCSP:
  3212. case WOLFSSL_CSR2_OCSP_MULTI:
  3213. if (options & WOLFSSL_CSR2_OCSP_USE_NONCE) {
  3214. WC_RNG rng;
  3215. #ifndef HAVE_FIPS
  3216. ret = wc_InitRng_ex(&rng, heap, devId);
  3217. #else
  3218. ret = wc_InitRng(&rng);
  3219. (void)devId;
  3220. #endif
  3221. if (ret == 0) {
  3222. if (wc_RNG_GenerateBlock(&rng, csr2->request.ocsp[0].nonce,
  3223. MAX_OCSP_NONCE_SZ) == 0)
  3224. csr2->request.ocsp[0].nonceSz = MAX_OCSP_NONCE_SZ;
  3225. wc_FreeRng(&rng);
  3226. }
  3227. }
  3228. break;
  3229. }
  3230. /* append new item */
  3231. if ((extension = TLSX_Find(*extensions, TLSX_STATUS_REQUEST_V2))) {
  3232. CertificateStatusRequestItemV2* last =
  3233. (CertificateStatusRequestItemV2*)extension->data;
  3234. for (; last->next; last = last->next);
  3235. last->next = csr2;
  3236. }
  3237. else if ((ret = TLSX_Push(extensions, TLSX_STATUS_REQUEST_V2, csr2,heap))) {
  3238. XFREE(csr2, heap, DYNAMIC_TYPE_TLSX);
  3239. return ret;
  3240. }
  3241. return WOLFSSL_SUCCESS;
  3242. }
  3243. #define CSR2_FREE_ALL TLSX_CSR2_FreeAll
  3244. #define CSR2_GET_SIZE TLSX_CSR2_GetSize
  3245. #define CSR2_WRITE TLSX_CSR2_Write
  3246. #define CSR2_PARSE TLSX_CSR2_Parse
  3247. #else
  3248. #define CSR2_FREE_ALL(data, heap) WC_DO_NOTHING
  3249. #define CSR2_GET_SIZE(a, b) 0
  3250. #define CSR2_WRITE(a, b, c) 0
  3251. #define CSR2_PARSE(a, b, c, d) 0
  3252. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  3253. /******************************************************************************/
  3254. /* Supported Elliptic Curves */
  3255. /******************************************************************************/
  3256. #ifdef HAVE_SUPPORTED_CURVES
  3257. #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) \
  3258. && !defined(HAVE_FFDHE) && !defined(HAVE_PQC)
  3259. #error Elliptic Curves Extension requires Elliptic Curve Cryptography or liboqs groups. \
  3260. Use --enable-ecc and/or --enable-liboqs in the configure script or \
  3261. define HAVE_ECC. Alternatively use FFDHE for DH cipher suites.
  3262. #endif
  3263. static int TLSX_SupportedCurve_New(SupportedCurve** curve, word16 name,
  3264. void* heap)
  3265. {
  3266. if (curve == NULL)
  3267. return BAD_FUNC_ARG;
  3268. (void)heap;
  3269. *curve = (SupportedCurve*)XMALLOC(sizeof(SupportedCurve), heap,
  3270. DYNAMIC_TYPE_TLSX);
  3271. if (*curve == NULL)
  3272. return MEMORY_E;
  3273. (*curve)->name = name;
  3274. (*curve)->next = NULL;
  3275. return 0;
  3276. }
  3277. static int TLSX_PointFormat_New(PointFormat** point, byte format, void* heap)
  3278. {
  3279. if (point == NULL)
  3280. return BAD_FUNC_ARG;
  3281. (void)heap;
  3282. *point = (PointFormat*)XMALLOC(sizeof(PointFormat), heap,
  3283. DYNAMIC_TYPE_TLSX);
  3284. if (*point == NULL)
  3285. return MEMORY_E;
  3286. (*point)->format = format;
  3287. (*point)->next = NULL;
  3288. return 0;
  3289. }
  3290. static void TLSX_SupportedCurve_FreeAll(SupportedCurve* list, void* heap)
  3291. {
  3292. SupportedCurve* curve;
  3293. while ((curve = list)) {
  3294. list = curve->next;
  3295. XFREE(curve, heap, DYNAMIC_TYPE_TLSX);
  3296. }
  3297. (void)heap;
  3298. }
  3299. static void TLSX_PointFormat_FreeAll(PointFormat* list, void* heap)
  3300. {
  3301. PointFormat* point;
  3302. while ((point = list)) {
  3303. list = point->next;
  3304. XFREE(point, heap, DYNAMIC_TYPE_TLSX);
  3305. }
  3306. (void)heap;
  3307. }
  3308. static int TLSX_SupportedCurve_Append(SupportedCurve* list, word16 name,
  3309. void* heap)
  3310. {
  3311. int ret = BAD_FUNC_ARG;
  3312. while (list) {
  3313. if (list->name == name) {
  3314. ret = 0; /* curve already in use */
  3315. break;
  3316. }
  3317. if (list->next == NULL) {
  3318. ret = TLSX_SupportedCurve_New(&list->next, name, heap);
  3319. break;
  3320. }
  3321. list = list->next;
  3322. }
  3323. return ret;
  3324. }
  3325. static int TLSX_PointFormat_Append(PointFormat* list, byte format, void* heap)
  3326. {
  3327. int ret = BAD_FUNC_ARG;
  3328. while (list) {
  3329. if (list->format == format) {
  3330. ret = 0; /* format already in use */
  3331. break;
  3332. }
  3333. if (list->next == NULL) {
  3334. ret = TLSX_PointFormat_New(&list->next, format, heap);
  3335. break;
  3336. }
  3337. list = list->next;
  3338. }
  3339. return ret;
  3340. }
  3341. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  3342. #if defined(HAVE_FFDHE) && (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3343. defined(HAVE_CURVE448))
  3344. static void TLSX_SupportedCurve_ValidateRequest(const WOLFSSL* ssl,
  3345. const byte* semaphore)
  3346. {
  3347. /* If all pre-defined parameter types for key exchange are supported then
  3348. * always send SupportedGroups extension.
  3349. */
  3350. (void)ssl;
  3351. (void)semaphore;
  3352. }
  3353. #else
  3354. static void TLSX_SupportedCurve_ValidateRequest(WOLFSSL* ssl, byte* semaphore)
  3355. {
  3356. word16 i;
  3357. const Suites* suites = WOLFSSL_SUITES(ssl);
  3358. for (i = 0; i < suites->suiteSz; i += 2) {
  3359. if (suites->suites[i] == TLS13_BYTE)
  3360. return;
  3361. #ifdef BUILD_TLS_SM4_GCM_SM3
  3362. if ((suites->suites[i] == CIPHER_BYTE) &&
  3363. (suites->suites[i+1] == TLS_SM4_GCM_SM3))
  3364. return;
  3365. #endif
  3366. #ifdef BUILD_TLS_SM4_CCM_SM3
  3367. if ((suites->suites[i] == CIPHER_BYTE) &&
  3368. (suites->suites[i+1] == TLS_SM4_CCM_SM3))
  3369. return;
  3370. #endif
  3371. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3372. if ((suites->suites[i] == SM_BYTE) &&
  3373. (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3374. return;
  3375. #endif
  3376. if ((suites->suites[i] == ECC_BYTE) ||
  3377. (suites->suites[i] == ECDHE_PSK_BYTE) ||
  3378. (suites->suites[i] == CHACHA_BYTE)) {
  3379. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3380. defined(HAVE_CURVE448)
  3381. return;
  3382. #endif
  3383. }
  3384. #ifdef HAVE_FFDHE
  3385. else {
  3386. return;
  3387. }
  3388. #endif
  3389. }
  3390. /* turns semaphore on to avoid sending this extension. */
  3391. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_GROUPS));
  3392. }
  3393. #endif
  3394. /* Only send PointFormats if TLSv13, ECC or CHACHA cipher suite present.
  3395. */
  3396. static void TLSX_PointFormat_ValidateRequest(WOLFSSL* ssl, byte* semaphore)
  3397. {
  3398. #ifdef HAVE_FFDHE
  3399. (void)ssl;
  3400. (void)semaphore;
  3401. #else
  3402. word16 i;
  3403. const Suites* suites = WOLFSSL_SUITES(ssl);
  3404. if (suites == NULL)
  3405. return;
  3406. for (i = 0; i < suites->suiteSz; i += 2) {
  3407. if (suites->suites[i] == TLS13_BYTE)
  3408. return;
  3409. #ifdef BUILD_TLS_SM4_GCM_SM3
  3410. if ((suites->suites[i] == CIPHER_BYTE) &&
  3411. (suites->suites[i+1] == TLS_SM4_GCM_SM3))
  3412. return;
  3413. #endif
  3414. #ifdef BUILD_TLS_SM4_CCM_SM3
  3415. if ((suites->suites[i] == CIPHER_BYTE) &&
  3416. (suites->suites[i+1] == TLS_SM4_CCM_SM3))
  3417. return;
  3418. #endif
  3419. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3420. if ((suites->suites[i] == SM_BYTE) &&
  3421. (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3422. return;
  3423. #endif
  3424. if ((suites->suites[i] == ECC_BYTE) ||
  3425. (suites->suites[i] == ECDHE_PSK_BYTE) ||
  3426. (suites->suites[i] == CHACHA_BYTE)) {
  3427. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3428. defined(HAVE_CURVE448)
  3429. return;
  3430. #endif
  3431. }
  3432. }
  3433. /* turns semaphore on to avoid sending this extension. */
  3434. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  3435. #endif
  3436. }
  3437. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  3438. #ifndef NO_WOLFSSL_SERVER
  3439. static void TLSX_PointFormat_ValidateResponse(WOLFSSL* ssl, byte* semaphore)
  3440. {
  3441. #if defined(HAVE_FFDHE) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3442. defined(HAVE_CURVE448)
  3443. (void)semaphore;
  3444. #endif
  3445. if (ssl->options.cipherSuite0 == TLS13_BYTE)
  3446. return;
  3447. #ifdef BUILD_TLS_SM4_GCM_SM3
  3448. if ((ssl->options.cipherSuite0 == CIPHER_BYTE) &&
  3449. (ssl->options.cipherSuite == TLS_SM4_GCM_SM3))
  3450. return;
  3451. #endif
  3452. #ifdef BUILD_TLS_SM4_CCM_SM3
  3453. if ((ssl->options.cipherSuite0 == CIPHER_BYTE) &&
  3454. (ssl->options.cipherSuite == TLS_SM4_CCM_SM3))
  3455. return;
  3456. #endif
  3457. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3458. if ((ssl->options.cipherSuite0 == SM_BYTE) &&
  3459. (ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3460. return;
  3461. #endif
  3462. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  3463. if (ssl->options.cipherSuite0 == ECC_BYTE ||
  3464. ssl->options.cipherSuite0 == ECDHE_PSK_BYTE ||
  3465. ssl->options.cipherSuite0 == CHACHA_BYTE) {
  3466. return;
  3467. }
  3468. #endif
  3469. /* turns semaphore on to avoid sending this extension. */
  3470. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  3471. }
  3472. #endif /* !NO_WOLFSSL_SERVER */
  3473. #if !defined(NO_WOLFSSL_CLIENT) || defined(WOLFSSL_TLS13)
  3474. static word16 TLSX_SupportedCurve_GetSize(SupportedCurve* list)
  3475. {
  3476. SupportedCurve* curve;
  3477. word16 length = OPAQUE16_LEN; /* list length */
  3478. while ((curve = list)) {
  3479. list = curve->next;
  3480. length += OPAQUE16_LEN; /* curve length */
  3481. }
  3482. return length;
  3483. }
  3484. #endif
  3485. static word16 TLSX_PointFormat_GetSize(PointFormat* list)
  3486. {
  3487. PointFormat* point;
  3488. word16 length = ENUM_LEN; /* list length */
  3489. while ((point = list)) {
  3490. list = point->next;
  3491. length += ENUM_LEN; /* format length */
  3492. }
  3493. return length;
  3494. }
  3495. #if !defined(NO_WOLFSSL_CLIENT) || defined(WOLFSSL_TLS13)
  3496. static word16 TLSX_SupportedCurve_Write(SupportedCurve* list, byte* output)
  3497. {
  3498. word16 offset = OPAQUE16_LEN;
  3499. while (list) {
  3500. c16toa(list->name, output + offset);
  3501. offset += OPAQUE16_LEN;
  3502. list = list->next;
  3503. }
  3504. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  3505. return offset;
  3506. }
  3507. #endif
  3508. static word16 TLSX_PointFormat_Write(PointFormat* list, byte* output)
  3509. {
  3510. word16 offset = ENUM_LEN;
  3511. while (list) {
  3512. output[offset++] = list->format;
  3513. list = list->next;
  3514. }
  3515. output[0] = (byte)(offset - ENUM_LEN);
  3516. return offset;
  3517. }
  3518. #if !defined(NO_WOLFSSL_SERVER) || (defined(WOLFSSL_TLS13) && \
  3519. !defined(WOLFSSL_NO_SERVER_GROUPS_EXT))
  3520. int TLSX_SupportedCurve_Parse(const WOLFSSL* ssl, const byte* input,
  3521. word16 length, byte isRequest, TLSX** extensions)
  3522. {
  3523. word16 offset;
  3524. word16 name;
  3525. int ret;
  3526. if(!isRequest && !IsAtLeastTLSv1_3(ssl->version)) {
  3527. #ifdef WOLFSSL_ALLOW_SERVER_SC_EXT
  3528. return 0;
  3529. #else
  3530. return BUFFER_ERROR; /* servers doesn't send this extension. */
  3531. #endif
  3532. }
  3533. if (OPAQUE16_LEN > length || length % OPAQUE16_LEN)
  3534. return BUFFER_ERROR;
  3535. ato16(input, &offset);
  3536. /* validating curve list length */
  3537. if (length != OPAQUE16_LEN + offset)
  3538. return BUFFER_ERROR;
  3539. offset = OPAQUE16_LEN;
  3540. if (offset == length)
  3541. return 0;
  3542. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3543. if (!isRequest) {
  3544. TLSX* extension;
  3545. SupportedCurve* curve;
  3546. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  3547. if (extension != NULL) {
  3548. /* Replace client list with server list of supported groups. */
  3549. curve = (SupportedCurve*)extension->data;
  3550. extension->data = NULL;
  3551. TLSX_SupportedCurve_FreeAll(curve, ssl->heap);
  3552. ato16(input + offset, &name);
  3553. offset += OPAQUE16_LEN;
  3554. ret = TLSX_SupportedCurve_New(&curve, name, ssl->heap);
  3555. if (ret != 0)
  3556. return ret; /* throw error */
  3557. extension->data = (void*)curve;
  3558. }
  3559. }
  3560. #endif
  3561. for (; offset < length; offset += OPAQUE16_LEN) {
  3562. ato16(input + offset, &name);
  3563. ret = TLSX_UseSupportedCurve(extensions, name, ssl->heap);
  3564. /* If it is BAD_FUNC_ARG then it is a group we do not support, but
  3565. * that is fine. */
  3566. if (ret != WOLFSSL_SUCCESS && ret != BAD_FUNC_ARG) {
  3567. return ret;
  3568. }
  3569. }
  3570. return 0;
  3571. }
  3572. #endif
  3573. #if !defined(NO_WOLFSSL_SERVER)
  3574. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3575. /* Checks the priority of the groups on the server and set the supported groups
  3576. * response if there is a group not advertised by the client that is preferred.
  3577. *
  3578. * ssl SSL/TLS object.
  3579. * returns 0 on success, otherwise an error.
  3580. */
  3581. int TLSX_SupportedCurve_CheckPriority(WOLFSSL* ssl)
  3582. {
  3583. int ret;
  3584. TLSX* extension;
  3585. TLSX* priority = NULL;
  3586. TLSX* ext = NULL;
  3587. word16 name;
  3588. SupportedCurve* curve;
  3589. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3590. /* May be doing PSK with no key exchange. */
  3591. if (extension == NULL)
  3592. return 0;
  3593. ret = TLSX_PopulateSupportedGroups(ssl, &priority);
  3594. if (ret != WOLFSSL_SUCCESS) {
  3595. TLSX_FreeAll(priority, ssl->heap);
  3596. return ret;
  3597. }
  3598. ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS);
  3599. if (ext == NULL) {
  3600. WOLFSSL_MSG("Could not find supported groups extension");
  3601. TLSX_FreeAll(priority, ssl->heap);
  3602. return 0;
  3603. }
  3604. curve = (SupportedCurve*)ext->data;
  3605. name = curve->name;
  3606. curve = (SupportedCurve*)extension->data;
  3607. while (curve != NULL) {
  3608. if (curve->name == name)
  3609. break;
  3610. curve = curve->next;
  3611. }
  3612. if (curve == NULL) {
  3613. /* Couldn't find the preferred group in client list. */
  3614. extension->resp = 1;
  3615. /* Send server list back and free client list. */
  3616. curve = (SupportedCurve*)extension->data;
  3617. extension->data = ext->data;
  3618. ext->data = curve;
  3619. }
  3620. TLSX_FreeAll(priority, ssl->heap);
  3621. return 0;
  3622. }
  3623. #endif /* WOLFSSL_TLS13 && !WOLFSSL_NO_SERVER_GROUPS_EXT */
  3624. #if defined(HAVE_FFDHE) && !defined(WOLFSSL_NO_TLS12)
  3625. #ifdef HAVE_PUBLIC_FFDHE
  3626. static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup,
  3627. SupportedCurve* serverGroup)
  3628. {
  3629. int ret = 0;
  3630. SupportedCurve* group;
  3631. const DhParams* params = NULL;
  3632. for (; serverGroup != NULL; serverGroup = serverGroup->next) {
  3633. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name))
  3634. continue;
  3635. for (group = clientGroup; group != NULL; group = group->next) {
  3636. if (serverGroup->name != group->name)
  3637. continue;
  3638. switch (serverGroup->name) {
  3639. #ifdef HAVE_FFDHE_2048
  3640. case WOLFSSL_FFDHE_2048:
  3641. params = wc_Dh_ffdhe2048_Get();
  3642. break;
  3643. #endif
  3644. #ifdef HAVE_FFDHE_3072
  3645. case WOLFSSL_FFDHE_3072:
  3646. params = wc_Dh_ffdhe3072_Get();
  3647. break;
  3648. #endif
  3649. #ifdef HAVE_FFDHE_4096
  3650. case WOLFSSL_FFDHE_4096:
  3651. params = wc_Dh_ffdhe4096_Get();
  3652. break;
  3653. #endif
  3654. #ifdef HAVE_FFDHE_6144
  3655. case WOLFSSL_FFDHE_6144:
  3656. params = wc_Dh_ffdhe6144_Get();
  3657. break;
  3658. #endif
  3659. #ifdef HAVE_FFDHE_8192
  3660. case WOLFSSL_FFDHE_8192:
  3661. params = wc_Dh_ffdhe8192_Get();
  3662. break;
  3663. #endif
  3664. default:
  3665. break;
  3666. }
  3667. if (params == NULL) {
  3668. ret = BAD_FUNC_ARG;
  3669. break;
  3670. }
  3671. if (params->p_len >= ssl->options.minDhKeySz &&
  3672. params->p_len <= ssl->options.maxDhKeySz) {
  3673. break;
  3674. }
  3675. }
  3676. if (ret != 0)
  3677. break;
  3678. if ((group != NULL) && (serverGroup->name == group->name))
  3679. break;
  3680. }
  3681. if ((ret == 0) && (serverGroup != NULL) && (params != NULL)) {
  3682. ssl->buffers.serverDH_P.buffer = (unsigned char *)params->p;
  3683. ssl->buffers.serverDH_P.length = params->p_len;
  3684. ssl->buffers.serverDH_G.buffer = (unsigned char *)params->g;
  3685. ssl->buffers.serverDH_G.length = params->g_len;
  3686. ssl->namedGroup = serverGroup->name;
  3687. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  3688. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  3689. ssl->options.dhDoKeyTest = 0;
  3690. #endif
  3691. ssl->options.haveDH = 1;
  3692. }
  3693. return ret;
  3694. }
  3695. #else
  3696. static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup,
  3697. SupportedCurve* serverGroup)
  3698. {
  3699. int ret = 0;
  3700. SupportedCurve* group;
  3701. word32 p_len;
  3702. for (; serverGroup != NULL; serverGroup = serverGroup->next) {
  3703. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name))
  3704. continue;
  3705. for (group = clientGroup; group != NULL; group = group->next) {
  3706. if (serverGroup->name != group->name)
  3707. continue;
  3708. wc_DhGetNamedKeyParamSize(serverGroup->name, &p_len, NULL, NULL);
  3709. if (p_len == 0) {
  3710. ret = BAD_FUNC_ARG;
  3711. break;
  3712. }
  3713. if (p_len >= ssl->options.minDhKeySz &&
  3714. p_len <= ssl->options.maxDhKeySz) {
  3715. break;
  3716. }
  3717. }
  3718. if (ret != 0)
  3719. break;
  3720. if ((group != NULL) && (serverGroup->name == group->name))
  3721. break;
  3722. }
  3723. if ((ret == 0) && (serverGroup != NULL)) {
  3724. word32 pSz, gSz;
  3725. ssl->buffers.serverDH_P.buffer = NULL;
  3726. ssl->buffers.serverDH_G.buffer = NULL;
  3727. ret = wc_DhGetNamedKeyParamSize(serverGroup->name, &pSz, &gSz, NULL);
  3728. if (ret == 0) {
  3729. ssl->buffers.serverDH_P.buffer =
  3730. (byte*)XMALLOC(pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  3731. if (ssl->buffers.serverDH_P.buffer == NULL)
  3732. ret = MEMORY_E;
  3733. else
  3734. ssl->buffers.serverDH_P.length = pSz;
  3735. }
  3736. if (ret == 0) {
  3737. ssl->buffers.serverDH_G.buffer =
  3738. (byte*)XMALLOC(gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  3739. if (ssl->buffers.serverDH_G.buffer == NULL) {
  3740. ret = MEMORY_E;
  3741. } else
  3742. ssl->buffers.serverDH_G.length = gSz;
  3743. }
  3744. if (ret == 0) {
  3745. ret = wc_DhCopyNamedKey(serverGroup->name,
  3746. ssl->buffers.serverDH_P.buffer, &pSz,
  3747. ssl->buffers.serverDH_G.buffer, &gSz,
  3748. NULL, NULL);
  3749. }
  3750. if (ret == 0) {
  3751. ssl->buffers.weOwnDH = 1;
  3752. ssl->namedGroup = serverGroup->name;
  3753. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  3754. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  3755. ssl->options.dhDoKeyTest = 0;
  3756. #endif
  3757. ssl->options.haveDH = 1;
  3758. }
  3759. else {
  3760. if (ssl->buffers.serverDH_P.buffer != NULL) {
  3761. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  3762. DYNAMIC_TYPE_PUBLIC_KEY);
  3763. ssl->buffers.serverDH_P.length = 0;
  3764. ssl->buffers.serverDH_P.buffer = NULL;
  3765. }
  3766. if (ssl->buffers.serverDH_G.buffer != NULL) {
  3767. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  3768. DYNAMIC_TYPE_PUBLIC_KEY);
  3769. ssl->buffers.serverDH_G.length = 0;
  3770. ssl->buffers.serverDH_G.buffer = NULL;
  3771. }
  3772. }
  3773. }
  3774. return ret;
  3775. }
  3776. #endif
  3777. /* Set the highest priority common FFDHE group on the server as compared to
  3778. * client extensions.
  3779. *
  3780. * ssl SSL/TLS object.
  3781. * returns 0 on success, otherwise an error.
  3782. */
  3783. int TLSX_SupportedFFDHE_Set(WOLFSSL* ssl)
  3784. {
  3785. int ret;
  3786. TLSX* priority = NULL;
  3787. TLSX* ext = NULL;
  3788. TLSX* extension;
  3789. SupportedCurve* clientGroup;
  3790. SupportedCurve* group;
  3791. int found = 0;
  3792. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3793. /* May be doing PSK with no key exchange. */
  3794. if (extension == NULL)
  3795. return 0;
  3796. clientGroup = (SupportedCurve*)extension->data;
  3797. for (group = clientGroup; group != NULL; group = group->next) {
  3798. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(group->name)) {
  3799. found = 1;
  3800. break;
  3801. }
  3802. }
  3803. if (!found)
  3804. return 0;
  3805. if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
  3806. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  3807. DYNAMIC_TYPE_PUBLIC_KEY);
  3808. }
  3809. if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
  3810. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  3811. DYNAMIC_TYPE_PUBLIC_KEY);
  3812. }
  3813. ssl->buffers.serverDH_P.buffer = NULL;
  3814. ssl->buffers.serverDH_G.buffer = NULL;
  3815. ssl->buffers.weOwnDH = 0;
  3816. ssl->options.haveDH = 0;
  3817. ret = TLSX_PopulateSupportedGroups(ssl, &priority);
  3818. if (ret == WOLFSSL_SUCCESS) {
  3819. SupportedCurve* serverGroup;
  3820. ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS);
  3821. serverGroup = (SupportedCurve*)ext->data;
  3822. ret = tlsx_ffdhe_find_group(ssl, clientGroup, serverGroup);
  3823. }
  3824. TLSX_FreeAll(priority, ssl->heap);
  3825. return ret;
  3826. }
  3827. #endif /* HAVE_FFDHE && !WOLFSSL_NO_TLS12 */
  3828. #endif /* !NO_WOLFSSL_SERVER */
  3829. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3830. /* Return the preferred group.
  3831. *
  3832. * ssl SSL/TLS object.
  3833. * checkSupported Whether to check for the first supported group.
  3834. * returns BAD_FUNC_ARG if no group found, otherwise the group.
  3835. */
  3836. int TLSX_SupportedCurve_Preferred(WOLFSSL* ssl, int checkSupported)
  3837. {
  3838. TLSX* extension;
  3839. SupportedCurve* curve;
  3840. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3841. if (extension == NULL)
  3842. return BAD_FUNC_ARG;
  3843. curve = (SupportedCurve*)extension->data;
  3844. while (curve != NULL) {
  3845. if (!checkSupported || TLSX_KeyShare_IsSupported(curve->name))
  3846. return curve->name;
  3847. curve = curve->next;
  3848. }
  3849. return BAD_FUNC_ARG;
  3850. }
  3851. #endif /* HAVE_SUPPORTED_CURVES */
  3852. #ifndef NO_WOLFSSL_SERVER
  3853. static int TLSX_PointFormat_Parse(WOLFSSL* ssl, const byte* input,
  3854. word16 length, byte isRequest)
  3855. {
  3856. int ret;
  3857. /* validating formats list length */
  3858. if (ENUM_LEN > length || length != (word16)ENUM_LEN + input[0])
  3859. return BUFFER_ERROR;
  3860. if (isRequest) {
  3861. /* adding uncompressed point format to response */
  3862. ret = TLSX_UsePointFormat(&ssl->extensions, WOLFSSL_EC_PF_UNCOMPRESSED,
  3863. ssl->heap);
  3864. if (ret != WOLFSSL_SUCCESS)
  3865. return ret; /* throw error */
  3866. TLSX_SetResponse(ssl, TLSX_EC_POINT_FORMATS);
  3867. }
  3868. return 0;
  3869. }
  3870. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  3871. int TLSX_ValidateSupportedCurves(const WOLFSSL* ssl, byte first, byte second,
  3872. word32* ecdhCurveOID) {
  3873. TLSX* extension = NULL;
  3874. SupportedCurve* curve = NULL;
  3875. word32 oid = 0;
  3876. word32 defOid = 0;
  3877. word32 defSz = 80; /* Maximum known curve size is 66. */
  3878. word32 nextOid = 0;
  3879. word32 nextSz = 80; /* Maximum known curve size is 66. */
  3880. word32 currOid = ssl->ecdhCurveOID;
  3881. int ephmSuite = 0;
  3882. word16 octets = 0; /* according to 'ecc_set_type ecc_sets[];' */
  3883. int key = 0; /* validate key */
  3884. (void)oid;
  3885. if (first == CHACHA_BYTE) {
  3886. switch (second) {
  3887. case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
  3888. case TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3889. case TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3890. case TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256:
  3891. return 1; /* no suite restriction */
  3892. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
  3893. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256:
  3894. case TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3895. break;
  3896. }
  3897. }
  3898. if (first == ECC_BYTE || first == ECDHE_PSK_BYTE || first == CHACHA_BYTE)
  3899. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3900. if (!extension)
  3901. return 1; /* no suite restriction */
  3902. for (curve = (SupportedCurve*)extension->data;
  3903. curve && !key;
  3904. curve = curve->next) {
  3905. #ifdef OPENSSL_EXTRA
  3906. /* skip if name is not in supported ECC range
  3907. * or disabled by user */
  3908. if (wolfSSL_curve_is_disabled(ssl, curve->name))
  3909. continue;
  3910. #endif
  3911. /* find supported curve */
  3912. switch (curve->name) {
  3913. #ifdef HAVE_ECC
  3914. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  3915. #ifndef NO_ECC_SECP
  3916. case WOLFSSL_ECC_SECP160R1:
  3917. oid = ECC_SECP160R1_OID;
  3918. octets = 20;
  3919. break;
  3920. #endif /* !NO_ECC_SECP */
  3921. #ifdef HAVE_ECC_SECPR2
  3922. case WOLFSSL_ECC_SECP160R2:
  3923. oid = ECC_SECP160R2_OID;
  3924. octets = 20;
  3925. break;
  3926. #endif /* HAVE_ECC_SECPR2 */
  3927. #ifdef HAVE_ECC_KOBLITZ
  3928. case WOLFSSL_ECC_SECP160K1:
  3929. oid = ECC_SECP160K1_OID;
  3930. octets = 20;
  3931. break;
  3932. #endif /* HAVE_ECC_KOBLITZ */
  3933. #endif
  3934. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  3935. #ifndef NO_ECC_SECP
  3936. case WOLFSSL_ECC_SECP192R1:
  3937. oid = ECC_SECP192R1_OID;
  3938. octets = 24;
  3939. break;
  3940. #endif /* !NO_ECC_SECP */
  3941. #ifdef HAVE_ECC_KOBLITZ
  3942. case WOLFSSL_ECC_SECP192K1:
  3943. oid = ECC_SECP192K1_OID;
  3944. octets = 24;
  3945. break;
  3946. #endif /* HAVE_ECC_KOBLITZ */
  3947. #endif
  3948. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  3949. #ifndef NO_ECC_SECP
  3950. case WOLFSSL_ECC_SECP224R1:
  3951. oid = ECC_SECP224R1_OID;
  3952. octets = 28;
  3953. break;
  3954. #endif /* !NO_ECC_SECP */
  3955. #ifdef HAVE_ECC_KOBLITZ
  3956. case WOLFSSL_ECC_SECP224K1:
  3957. oid = ECC_SECP224K1_OID;
  3958. octets = 28;
  3959. break;
  3960. #endif /* HAVE_ECC_KOBLITZ */
  3961. #endif
  3962. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  3963. #ifndef NO_ECC_SECP
  3964. case WOLFSSL_ECC_SECP256R1:
  3965. oid = ECC_SECP256R1_OID;
  3966. octets = 32;
  3967. break;
  3968. #endif /* !NO_ECC_SECP */
  3969. #endif /* !NO_ECC256 || HAVE_ALL_CURVES */
  3970. #endif
  3971. #if (defined(HAVE_CURVE25519) || defined(HAVE_ED25519)) && ECC_MIN_KEY_SZ <= 256
  3972. case WOLFSSL_ECC_X25519:
  3973. oid = ECC_X25519_OID;
  3974. octets = 32;
  3975. break;
  3976. #endif /* HAVE_CURVE25519 */
  3977. #ifdef HAVE_ECC
  3978. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  3979. #ifdef HAVE_ECC_KOBLITZ
  3980. case WOLFSSL_ECC_SECP256K1:
  3981. oid = ECC_SECP256K1_OID;
  3982. octets = 32;
  3983. break;
  3984. #endif /* HAVE_ECC_KOBLITZ */
  3985. #ifdef HAVE_ECC_BRAINPOOL
  3986. case WOLFSSL_ECC_BRAINPOOLP256R1:
  3987. oid = ECC_BRAINPOOLP256R1_OID;
  3988. octets = 32;
  3989. break;
  3990. #endif /* HAVE_ECC_BRAINPOOL */
  3991. #ifdef WOLFSSL_SM2
  3992. case WOLFSSL_ECC_SM2P256V1:
  3993. oid = ECC_SM2P256V1_OID;
  3994. octets = 32;
  3995. break;
  3996. #endif /* WOLFSSL_SM2 */
  3997. #endif
  3998. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  3999. #ifndef NO_ECC_SECP
  4000. case WOLFSSL_ECC_SECP384R1:
  4001. oid = ECC_SECP384R1_OID;
  4002. octets = 48;
  4003. break;
  4004. #endif /* !NO_ECC_SECP */
  4005. #ifdef HAVE_ECC_BRAINPOOL
  4006. case WOLFSSL_ECC_BRAINPOOLP384R1:
  4007. oid = ECC_BRAINPOOLP384R1_OID;
  4008. octets = 48;
  4009. break;
  4010. #endif /* HAVE_ECC_BRAINPOOL */
  4011. #endif
  4012. #endif
  4013. #if (defined(HAVE_CURVE448) || defined(HAVE_ED448)) && ECC_MIN_KEY_SZ <= 448
  4014. case WOLFSSL_ECC_X448:
  4015. oid = ECC_X448_OID;
  4016. octets = 57;
  4017. break;
  4018. #endif /* HAVE_CURVE448 */
  4019. #ifdef HAVE_ECC
  4020. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  4021. #ifdef HAVE_ECC_BRAINPOOL
  4022. case WOLFSSL_ECC_BRAINPOOLP512R1:
  4023. oid = ECC_BRAINPOOLP512R1_OID;
  4024. octets = 64;
  4025. break;
  4026. #endif /* HAVE_ECC_BRAINPOOL */
  4027. #endif
  4028. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  4029. #ifndef NO_ECC_SECP
  4030. case WOLFSSL_ECC_SECP521R1:
  4031. oid = ECC_SECP521R1_OID;
  4032. octets = 66;
  4033. break;
  4034. #endif /* !NO_ECC_SECP */
  4035. #endif
  4036. #endif
  4037. default: continue; /* unsupported curve */
  4038. }
  4039. #ifdef HAVE_ECC
  4040. /* Set default Oid */
  4041. if (defOid == 0 && ssl->eccTempKeySz <= octets && defSz > octets) {
  4042. defOid = oid;
  4043. defSz = octets;
  4044. }
  4045. /* The eccTempKeySz is the preferred ephemeral key size */
  4046. if (currOid == 0 && ssl->eccTempKeySz == octets)
  4047. currOid = oid;
  4048. if ((nextOid == 0 || nextSz > octets) && ssl->eccTempKeySz <= octets) {
  4049. nextOid = oid;
  4050. nextSz = octets;
  4051. }
  4052. #else
  4053. if (defOid == 0 && defSz > octets) {
  4054. defOid = oid;
  4055. defSz = octets;
  4056. }
  4057. if (currOid == 0)
  4058. currOid = oid;
  4059. if (nextOid == 0 || nextSz > octets) {
  4060. nextOid = oid;
  4061. nextSz = octets;
  4062. }
  4063. #endif
  4064. if (first == ECC_BYTE) {
  4065. switch (second) {
  4066. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  4067. /* ECDHE_ECDSA */
  4068. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
  4069. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
  4070. case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
  4071. case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
  4072. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
  4073. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
  4074. case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
  4075. case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
  4076. case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
  4077. case TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
  4078. key |= ssl->ecdhCurveOID == oid;
  4079. ephmSuite = 1;
  4080. break;
  4081. #ifdef WOLFSSL_STATIC_DH
  4082. /* ECDH_ECDSA */
  4083. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
  4084. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
  4085. case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
  4086. case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
  4087. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
  4088. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
  4089. case TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
  4090. case TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
  4091. if (oid == ECC_X25519_OID && defOid == oid) {
  4092. defOid = 0;
  4093. defSz = 80;
  4094. }
  4095. if (oid == ECC_X448_OID && defOid == oid) {
  4096. defOid = 0;
  4097. defSz = 80;
  4098. }
  4099. key |= ssl->pkCurveOID == oid;
  4100. break;
  4101. #endif /* WOLFSSL_STATIC_DH */
  4102. #endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  4103. #ifndef NO_RSA
  4104. /* ECDHE_RSA */
  4105. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
  4106. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
  4107. case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
  4108. case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
  4109. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
  4110. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
  4111. case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
  4112. case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
  4113. key |= ssl->ecdhCurveOID == oid;
  4114. ephmSuite = 1;
  4115. break;
  4116. #if defined(HAVE_ECC) && defined(WOLFSSL_STATIC_DH)
  4117. /* ECDH_RSA */
  4118. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
  4119. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
  4120. case TLS_ECDH_RSA_WITH_RC4_128_SHA:
  4121. case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
  4122. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
  4123. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
  4124. case TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
  4125. case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
  4126. if (oid == ECC_X25519_OID && defOid == oid) {
  4127. defOid = 0;
  4128. defSz = 80;
  4129. }
  4130. if (oid == ECC_X448_OID && defOid == oid) {
  4131. defOid = 0;
  4132. defSz = 80;
  4133. }
  4134. key |= ssl->pkCurveOID == oid;
  4135. break;
  4136. #endif /* HAVE_ECC && WOLFSSL_STATIC_DH */
  4137. #endif
  4138. default:
  4139. if (oid == ECC_X25519_OID && defOid == oid) {
  4140. defOid = 0;
  4141. defSz = 80;
  4142. }
  4143. if (oid == ECC_X448_OID && defOid == oid) {
  4144. defOid = 0;
  4145. defSz = 80;
  4146. }
  4147. key = 1;
  4148. break;
  4149. }
  4150. }
  4151. /* ChaCha20-Poly1305 ECC cipher suites */
  4152. if (first == CHACHA_BYTE) {
  4153. switch (second) {
  4154. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  4155. /* ECDHE_ECDSA */
  4156. case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 :
  4157. case TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  4158. key |= ssl->ecdhCurveOID == oid;
  4159. ephmSuite = 1;
  4160. break;
  4161. #endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  4162. #ifndef NO_RSA
  4163. /* ECDHE_RSA */
  4164. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 :
  4165. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  4166. key |= ssl->ecdhCurveOID == oid;
  4167. ephmSuite = 1;
  4168. break;
  4169. #endif
  4170. default:
  4171. key = 1;
  4172. break;
  4173. }
  4174. }
  4175. }
  4176. *ecdhCurveOID = ssl->ecdhCurveOID;
  4177. /* Choose the default if it is at the required strength. */
  4178. #ifdef HAVE_ECC
  4179. if (*ecdhCurveOID == 0 && defSz == ssl->eccTempKeySz)
  4180. #else
  4181. if (*ecdhCurveOID == 0)
  4182. #endif
  4183. {
  4184. key = 1;
  4185. *ecdhCurveOID = defOid;
  4186. }
  4187. /* Choose any curve at the required strength. */
  4188. if (*ecdhCurveOID == 0) {
  4189. key = 1;
  4190. *ecdhCurveOID = currOid;
  4191. }
  4192. /* Choose the default if it is at the next highest strength. */
  4193. if (*ecdhCurveOID == 0 && defSz == nextSz)
  4194. *ecdhCurveOID = defOid;
  4195. /* Choose any curve at the next highest strength. */
  4196. if (*ecdhCurveOID == 0)
  4197. *ecdhCurveOID = nextOid;
  4198. /* No curve and ephemeral ECC suite requires a matching curve. */
  4199. if (*ecdhCurveOID == 0 && ephmSuite)
  4200. key = 0;
  4201. return key;
  4202. }
  4203. #endif
  4204. #endif /* NO_WOLFSSL_SERVER */
  4205. int TLSX_SupportedCurve_Copy(TLSX* src, TLSX** dst, void* heap)
  4206. {
  4207. TLSX* extension;
  4208. int ret;
  4209. extension = TLSX_Find(src, TLSX_SUPPORTED_GROUPS);
  4210. if (extension != NULL) {
  4211. SupportedCurve* curve;
  4212. for (curve = (SupportedCurve*)extension->data; curve != NULL;
  4213. curve = curve->next) {
  4214. ret = TLSX_UseSupportedCurve(dst, curve->name, heap);
  4215. if (ret != WOLFSSL_SUCCESS)
  4216. return MEMORY_E;
  4217. }
  4218. }
  4219. return 0;
  4220. }
  4221. int TLSX_UseSupportedCurve(TLSX** extensions, word16 name, void* heap)
  4222. {
  4223. TLSX* extension = NULL;
  4224. SupportedCurve* curve = NULL;
  4225. int ret;
  4226. if (extensions == NULL) {
  4227. return BAD_FUNC_ARG;
  4228. }
  4229. #ifdef WOLFSSL_TLS13
  4230. if (! TLSX_KeyShare_IsSupported(name)) {
  4231. return BAD_FUNC_ARG;
  4232. }
  4233. #endif
  4234. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  4235. if (!extension) {
  4236. ret = TLSX_SupportedCurve_New(&curve, name, heap);
  4237. if (ret != 0)
  4238. return ret;
  4239. ret = TLSX_Push(extensions, TLSX_SUPPORTED_GROUPS, curve, heap);
  4240. if (ret != 0) {
  4241. XFREE(curve, heap, DYNAMIC_TYPE_TLSX);
  4242. return ret;
  4243. }
  4244. }
  4245. else {
  4246. ret = TLSX_SupportedCurve_Append((SupportedCurve*)extension->data, name,
  4247. heap);
  4248. if (ret != 0)
  4249. return ret;
  4250. }
  4251. return WOLFSSL_SUCCESS;
  4252. }
  4253. int TLSX_UsePointFormat(TLSX** extensions, byte format, void* heap)
  4254. {
  4255. TLSX* extension = NULL;
  4256. PointFormat* point = NULL;
  4257. int ret = 0;
  4258. if (extensions == NULL)
  4259. return BAD_FUNC_ARG;
  4260. extension = TLSX_Find(*extensions, TLSX_EC_POINT_FORMATS);
  4261. if (!extension) {
  4262. ret = TLSX_PointFormat_New(&point, format, heap);
  4263. if (ret != 0)
  4264. return ret;
  4265. ret = TLSX_Push(extensions, TLSX_EC_POINT_FORMATS, point, heap);
  4266. if (ret != 0) {
  4267. XFREE(point, heap, DYNAMIC_TYPE_TLSX);
  4268. return ret;
  4269. }
  4270. }
  4271. else {
  4272. ret = TLSX_PointFormat_Append((PointFormat*)extension->data, format,
  4273. heap);
  4274. if (ret != 0)
  4275. return ret;
  4276. }
  4277. return WOLFSSL_SUCCESS;
  4278. }
  4279. #define EC_FREE_ALL TLSX_SupportedCurve_FreeAll
  4280. #define EC_VALIDATE_REQUEST TLSX_SupportedCurve_ValidateRequest
  4281. /* In TLS 1.2 the server never sends supported curve extension, but in TLS 1.3
  4282. * the server can send supported groups extension to indicate what it will
  4283. * support for later connections. */
  4284. #if !defined(NO_WOLFSSL_CLIENT) || defined(WOLFSSL_TLS13)
  4285. #define EC_GET_SIZE TLSX_SupportedCurve_GetSize
  4286. #define EC_WRITE TLSX_SupportedCurve_Write
  4287. #else
  4288. #define EC_GET_SIZE(list) 0
  4289. #define EC_WRITE(a, b) 0
  4290. #endif
  4291. #if !defined(NO_WOLFSSL_SERVER) || (defined(WOLFSSL_TLS13) && \
  4292. !defined(WOLFSSL_NO_SERVER_GROUPS_EXT))
  4293. #define EC_PARSE TLSX_SupportedCurve_Parse
  4294. #else
  4295. #define EC_PARSE(a, b, c, d, e) 0
  4296. #endif
  4297. #define PF_FREE_ALL TLSX_PointFormat_FreeAll
  4298. #define PF_VALIDATE_REQUEST TLSX_PointFormat_ValidateRequest
  4299. #define PF_VALIDATE_RESPONSE TLSX_PointFormat_ValidateResponse
  4300. #define PF_GET_SIZE TLSX_PointFormat_GetSize
  4301. #define PF_WRITE TLSX_PointFormat_Write
  4302. #ifndef NO_WOLFSSL_SERVER
  4303. #define PF_PARSE TLSX_PointFormat_Parse
  4304. #else
  4305. #define PF_PARSE(a, b, c, d) 0
  4306. #endif
  4307. #else
  4308. #define EC_FREE_ALL(list, heap) WC_DO_NOTHING
  4309. #define EC_GET_SIZE(list) 0
  4310. #define EC_WRITE(a, b) 0
  4311. #define EC_PARSE(a, b, c, d, e) 0
  4312. #define EC_VALIDATE_REQUEST(a, b) WC_DO_NOTHING
  4313. #define PF_FREE_ALL(list, heap) WC_DO_NOTHING
  4314. #define PF_GET_SIZE(list) 0
  4315. #define PF_WRITE(a, b) 0
  4316. #define PF_PARSE(a, b, c, d) 0
  4317. #define PF_VALIDATE_REQUEST(a, b) WC_DO_NOTHING
  4318. #define PF_VALIDATE_RESPONSE(a, b) WC_DO_NOTHING
  4319. #endif /* HAVE_SUPPORTED_CURVES */
  4320. /******************************************************************************/
  4321. /* Renegotiation Indication */
  4322. /******************************************************************************/
  4323. #if defined(HAVE_SECURE_RENEGOTIATION) \
  4324. || defined(HAVE_SERVER_RENEGOTIATION_INFO)
  4325. static byte TLSX_SecureRenegotiation_GetSize(SecureRenegotiation* data,
  4326. int isRequest)
  4327. {
  4328. byte length = OPAQUE8_LEN; /* empty info length */
  4329. /* data will be NULL for HAVE_SERVER_RENEGOTIATION_INFO only */
  4330. if (data && data->enabled && data->verifySet) {
  4331. /* client sends client_verify_data only */
  4332. length += TLS_FINISHED_SZ;
  4333. /* server also sends server_verify_data */
  4334. if (!isRequest)
  4335. length += TLS_FINISHED_SZ;
  4336. }
  4337. return length;
  4338. }
  4339. static word16 TLSX_SecureRenegotiation_Write(SecureRenegotiation* data,
  4340. byte* output, int isRequest)
  4341. {
  4342. word16 offset = OPAQUE8_LEN; /* RenegotiationInfo length */
  4343. if (data && data->enabled && data->verifySet) {
  4344. /* client sends client_verify_data only */
  4345. XMEMCPY(output + offset, data->client_verify_data, TLS_FINISHED_SZ);
  4346. offset += TLS_FINISHED_SZ;
  4347. /* server also sends server_verify_data */
  4348. if (!isRequest) {
  4349. XMEMCPY(output + offset, data->server_verify_data, TLS_FINISHED_SZ);
  4350. offset += TLS_FINISHED_SZ;
  4351. }
  4352. }
  4353. output[0] = (byte)(offset - 1); /* info length - self */
  4354. return offset;
  4355. }
  4356. static int TLSX_SecureRenegotiation_Parse(WOLFSSL* ssl, const byte* input,
  4357. word16 length, byte isRequest)
  4358. {
  4359. int ret = SECURE_RENEGOTIATION_E;
  4360. if (length >= OPAQUE8_LEN) {
  4361. if (isRequest) {
  4362. #ifndef NO_WOLFSSL_SERVER
  4363. if (ssl->secure_renegotiation == NULL) {
  4364. ret = wolfSSL_UseSecureRenegotiation(ssl);
  4365. if (ret == WOLFSSL_SUCCESS)
  4366. ret = 0;
  4367. }
  4368. if (ret != 0 && ret != SECURE_RENEGOTIATION_E) {
  4369. }
  4370. else if (ssl->secure_renegotiation == NULL) {
  4371. }
  4372. else if (!ssl->secure_renegotiation->enabled) {
  4373. if (*input == 0) {
  4374. input++; /* get past size */
  4375. ssl->secure_renegotiation->enabled = 1;
  4376. TLSX_SetResponse(ssl, TLSX_RENEGOTIATION_INFO);
  4377. ret = 0;
  4378. }
  4379. else {
  4380. /* already in error state */
  4381. WOLFSSL_MSG("SCR client verify data present");
  4382. }
  4383. }
  4384. else if (*input == TLS_FINISHED_SZ) {
  4385. if (length < TLS_FINISHED_SZ + 1) {
  4386. WOLFSSL_MSG("SCR malformed buffer");
  4387. ret = BUFFER_E;
  4388. }
  4389. else {
  4390. input++; /* get past size */
  4391. /* validate client verify data */
  4392. if (XMEMCMP(input,
  4393. ssl->secure_renegotiation->client_verify_data,
  4394. TLS_FINISHED_SZ) == 0) {
  4395. WOLFSSL_MSG("SCR client verify data match");
  4396. TLSX_SetResponse(ssl, TLSX_RENEGOTIATION_INFO);
  4397. ret = 0; /* verified */
  4398. }
  4399. else {
  4400. /* already in error state */
  4401. WOLFSSL_MSG("SCR client verify data Failure");
  4402. }
  4403. }
  4404. }
  4405. #endif
  4406. }
  4407. else if (ssl->secure_renegotiation != NULL) {
  4408. #ifndef NO_WOLFSSL_CLIENT
  4409. if (!ssl->secure_renegotiation->enabled) {
  4410. if (*input == 0) {
  4411. ssl->secure_renegotiation->enabled = 1;
  4412. ret = 0;
  4413. }
  4414. }
  4415. else if (*input == 2 * TLS_FINISHED_SZ &&
  4416. length == 2 * TLS_FINISHED_SZ + OPAQUE8_LEN) {
  4417. input++; /* get past size */
  4418. /* validate client and server verify data */
  4419. if (XMEMCMP(input,
  4420. ssl->secure_renegotiation->client_verify_data,
  4421. TLS_FINISHED_SZ) == 0 &&
  4422. XMEMCMP(input + TLS_FINISHED_SZ,
  4423. ssl->secure_renegotiation->server_verify_data,
  4424. TLS_FINISHED_SZ) == 0) {
  4425. WOLFSSL_MSG("SCR client and server verify data match");
  4426. ret = 0; /* verified */
  4427. }
  4428. else {
  4429. /* already in error state */
  4430. WOLFSSL_MSG("SCR client and server verify data Failure");
  4431. }
  4432. }
  4433. #endif
  4434. }
  4435. }
  4436. if (ret != 0) {
  4437. WOLFSSL_ERROR_VERBOSE(ret);
  4438. SendAlert(ssl, alert_fatal, handshake_failure);
  4439. }
  4440. return ret;
  4441. }
  4442. int TLSX_UseSecureRenegotiation(TLSX** extensions, void* heap)
  4443. {
  4444. int ret = 0;
  4445. SecureRenegotiation* data;
  4446. data = (SecureRenegotiation*)XMALLOC(sizeof(SecureRenegotiation), heap,
  4447. DYNAMIC_TYPE_TLSX);
  4448. if (data == NULL)
  4449. return MEMORY_E;
  4450. XMEMSET(data, 0, sizeof(SecureRenegotiation));
  4451. ret = TLSX_Push(extensions, TLSX_RENEGOTIATION_INFO, data, heap);
  4452. if (ret != 0) {
  4453. XFREE(data, heap, DYNAMIC_TYPE_TLSX);
  4454. return ret;
  4455. }
  4456. return WOLFSSL_SUCCESS;
  4457. }
  4458. #ifdef HAVE_SERVER_RENEGOTIATION_INFO
  4459. int TLSX_AddEmptyRenegotiationInfo(TLSX** extensions, void* heap)
  4460. {
  4461. int ret;
  4462. /* send empty renegotiation_info extension */
  4463. TLSX* ext = TLSX_Find(*extensions, TLSX_RENEGOTIATION_INFO);
  4464. if (ext == NULL) {
  4465. ret = TLSX_UseSecureRenegotiation(extensions, heap);
  4466. if (ret != WOLFSSL_SUCCESS)
  4467. return ret;
  4468. ext = TLSX_Find(*extensions, TLSX_RENEGOTIATION_INFO);
  4469. }
  4470. if (ext)
  4471. ext->resp = 1;
  4472. return WOLFSSL_SUCCESS;
  4473. }
  4474. #endif /* HAVE_SERVER_RENEGOTIATION_INFO */
  4475. #define SCR_FREE_ALL(data, heap) XFREE(data, (heap), DYNAMIC_TYPE_TLSX)
  4476. #define SCR_GET_SIZE TLSX_SecureRenegotiation_GetSize
  4477. #define SCR_WRITE TLSX_SecureRenegotiation_Write
  4478. #define SCR_PARSE TLSX_SecureRenegotiation_Parse
  4479. #else
  4480. #define SCR_FREE_ALL(a, heap) WC_DO_NOTHING
  4481. #define SCR_GET_SIZE(a, b) 0
  4482. #define SCR_WRITE(a, b, c) 0
  4483. #define SCR_PARSE(a, b, c, d) 0
  4484. #endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
  4485. /******************************************************************************/
  4486. /* Session Tickets */
  4487. /******************************************************************************/
  4488. #ifdef HAVE_SESSION_TICKET
  4489. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  4490. static void TLSX_SessionTicket_ValidateRequest(WOLFSSL* ssl)
  4491. {
  4492. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_SESSION_TICKET);
  4493. SessionTicket* ticket = extension ?
  4494. (SessionTicket*)extension->data : NULL;
  4495. if (ticket) {
  4496. /* TODO validate ticket timeout here! */
  4497. if (ticket->lifetime == 0xfffffff) {
  4498. /* send empty ticket on timeout */
  4499. TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4500. }
  4501. }
  4502. }
  4503. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  4504. static word16 TLSX_SessionTicket_GetSize(SessionTicket* ticket, int isRequest)
  4505. {
  4506. (void)isRequest;
  4507. return ticket ? ticket->size : 0;
  4508. }
  4509. static word16 TLSX_SessionTicket_Write(SessionTicket* ticket, byte* output,
  4510. int isRequest)
  4511. {
  4512. word16 offset = 0; /* empty ticket */
  4513. if (isRequest && ticket) {
  4514. XMEMCPY(output + offset, ticket->data, ticket->size);
  4515. offset += ticket->size;
  4516. }
  4517. return offset;
  4518. }
  4519. static int TLSX_SessionTicket_Parse(WOLFSSL* ssl, const byte* input,
  4520. word16 length, byte isRequest)
  4521. {
  4522. int ret = 0;
  4523. (void) input; /* avoid unused parameter if NO_WOLFSSL_SERVER defined */
  4524. if (!isRequest) {
  4525. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_SESSION_TICKET))
  4526. return TLSX_HandleUnsupportedExtension(ssl);
  4527. if (length != 0)
  4528. return BUFFER_ERROR;
  4529. #ifndef NO_WOLFSSL_CLIENT
  4530. ssl->expect_session_ticket = 1;
  4531. #endif
  4532. }
  4533. #ifndef NO_WOLFSSL_SERVER
  4534. else {
  4535. /* server side */
  4536. if (ssl->ctx->ticketEncCb == NULL) {
  4537. WOLFSSL_MSG("Client sent session ticket, server has no callback");
  4538. return 0;
  4539. }
  4540. #ifdef HAVE_SECURE_RENEGOTIATION
  4541. if (IsSCR(ssl)) {
  4542. WOLFSSL_MSG("Client sent session ticket during SCR. Ignoring.");
  4543. return 0;
  4544. }
  4545. #endif
  4546. if (length > SESSION_TICKET_LEN) {
  4547. ret = BAD_TICKET_MSG_SZ;
  4548. WOLFSSL_ERROR_VERBOSE(ret);
  4549. } else if (IsAtLeastTLSv1_3(ssl->version)) {
  4550. WOLFSSL_MSG("Process client ticket rejected, TLS 1.3 no support");
  4551. ssl->options.rejectTicket = 1;
  4552. ret = 0; /* not fatal */
  4553. } else if (ssl->options.noTicketTls12) {
  4554. /* ignore ticket request */
  4555. } else if (length == 0) {
  4556. /* blank ticket */
  4557. ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4558. if (ret == WOLFSSL_SUCCESS) {
  4559. ret = 0;
  4560. /* send blank ticket */
  4561. TLSX_SetResponse(ssl, TLSX_SESSION_TICKET);
  4562. ssl->options.createTicket = 1; /* will send ticket msg */
  4563. ssl->options.useTicket = 1;
  4564. ssl->options.resuming = 0; /* no standard resumption */
  4565. ssl->arrays->sessionIDSz = 0; /* no echo on blank ticket */
  4566. }
  4567. } else {
  4568. /* got actual ticket from client */
  4569. ret = DoClientTicket(ssl, input, length);
  4570. if (ret == WOLFSSL_TICKET_RET_OK) { /* use ticket to resume */
  4571. WOLFSSL_MSG("Using existing client ticket");
  4572. ssl->options.useTicket = 1;
  4573. ssl->options.resuming = 1;
  4574. /* SERVER: ticket is peer auth. */
  4575. ssl->options.peerAuthGood = 1;
  4576. } else if (ret == WOLFSSL_TICKET_RET_CREATE) {
  4577. WOLFSSL_MSG("Using existing client ticket, creating new one");
  4578. ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4579. if (ret == WOLFSSL_SUCCESS) {
  4580. ret = 0;
  4581. TLSX_SetResponse(ssl, TLSX_SESSION_TICKET);
  4582. /* send blank ticket */
  4583. ssl->options.createTicket = 1; /* will send ticket msg */
  4584. ssl->options.useTicket = 1;
  4585. ssl->options.resuming = 1;
  4586. /* SERVER: ticket is peer auth. */
  4587. ssl->options.peerAuthGood = 1;
  4588. }
  4589. } else if (ret == WOLFSSL_TICKET_RET_REJECT) {
  4590. WOLFSSL_MSG("Process client ticket rejected, not using");
  4591. ssl->options.rejectTicket = 1;
  4592. ret = 0; /* not fatal */
  4593. } else if (ret == VERSION_ERROR) {
  4594. WOLFSSL_MSG("Process client ticket rejected, bad TLS version");
  4595. ssl->options.rejectTicket = 1;
  4596. ret = 0; /* not fatal */
  4597. } else if (ret == WOLFSSL_TICKET_RET_FATAL) {
  4598. WOLFSSL_MSG("Process client ticket fatal error, not using");
  4599. } else if (ret < 0) {
  4600. WOLFSSL_MSG("Process client ticket unknown error, not using");
  4601. }
  4602. }
  4603. }
  4604. #endif /* NO_WOLFSSL_SERVER */
  4605. #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER)
  4606. (void)ssl;
  4607. #endif
  4608. return ret;
  4609. }
  4610. WOLFSSL_LOCAL SessionTicket* TLSX_SessionTicket_Create(word32 lifetime,
  4611. byte* data, word16 size, void* heap)
  4612. {
  4613. SessionTicket* ticket = (SessionTicket*)XMALLOC(sizeof(SessionTicket),
  4614. heap, DYNAMIC_TYPE_TLSX);
  4615. if (ticket) {
  4616. ticket->data = (byte*)XMALLOC(size, heap, DYNAMIC_TYPE_TLSX);
  4617. if (ticket->data == NULL) {
  4618. XFREE(ticket, heap, DYNAMIC_TYPE_TLSX);
  4619. return NULL;
  4620. }
  4621. XMEMCPY(ticket->data, data, size);
  4622. ticket->size = size;
  4623. ticket->lifetime = lifetime;
  4624. }
  4625. (void)heap;
  4626. return ticket;
  4627. }
  4628. WOLFSSL_LOCAL void TLSX_SessionTicket_Free(SessionTicket* ticket, void* heap)
  4629. {
  4630. if (ticket) {
  4631. XFREE(ticket->data, heap, DYNAMIC_TYPE_TLSX);
  4632. XFREE(ticket, heap, DYNAMIC_TYPE_TLSX);
  4633. }
  4634. (void)heap;
  4635. }
  4636. int TLSX_UseSessionTicket(TLSX** extensions, SessionTicket* ticket, void* heap)
  4637. {
  4638. int ret = 0;
  4639. if (extensions == NULL)
  4640. return BAD_FUNC_ARG;
  4641. /* If the ticket is NULL, the client will request a new ticket from the
  4642. server. Otherwise, the client will use it in the next client hello. */
  4643. if ((ret = TLSX_Push(extensions, TLSX_SESSION_TICKET, (void*)ticket, heap))
  4644. != 0)
  4645. return ret;
  4646. return WOLFSSL_SUCCESS;
  4647. }
  4648. #define WOLF_STK_VALIDATE_REQUEST TLSX_SessionTicket_ValidateRequest
  4649. #define WOLF_STK_GET_SIZE TLSX_SessionTicket_GetSize
  4650. #define WOLF_STK_WRITE TLSX_SessionTicket_Write
  4651. #define WOLF_STK_PARSE TLSX_SessionTicket_Parse
  4652. #define WOLF_STK_FREE(stk, heap) TLSX_SessionTicket_Free((SessionTicket*)(stk),(heap))
  4653. #else
  4654. #define WOLF_STK_FREE(a, b) WC_DO_NOTHING
  4655. #define WOLF_STK_VALIDATE_REQUEST(a) WC_DO_NOTHING
  4656. #define WOLF_STK_GET_SIZE(a, b) 0
  4657. #define WOLF_STK_WRITE(a, b, c) 0
  4658. #define WOLF_STK_PARSE(a, b, c, d) 0
  4659. #endif /* HAVE_SESSION_TICKET */
  4660. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  4661. /******************************************************************************/
  4662. /* Encrypt-then-MAC */
  4663. /******************************************************************************/
  4664. #ifndef WOLFSSL_NO_TLS12
  4665. static int TLSX_EncryptThenMac_Use(WOLFSSL* ssl);
  4666. /**
  4667. * Get the size of the Encrypt-Then-MAC extension.
  4668. *
  4669. * msgType Type of message to put extension into.
  4670. * pSz Size of extension data.
  4671. * return SANITY_MSG_E when the message is not allowed to have extension and
  4672. * 0 otherwise.
  4673. */
  4674. static int TLSX_EncryptThenMac_GetSize(byte msgType, word16* pSz)
  4675. {
  4676. (void)pSz;
  4677. if (msgType != client_hello && msgType != server_hello) {
  4678. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4679. return SANITY_MSG_E;
  4680. }
  4681. /* Empty extension */
  4682. return 0;
  4683. }
  4684. /**
  4685. * Write the Encrypt-Then-MAC extension.
  4686. *
  4687. * data Unused
  4688. * output Extension data buffer. Unused.
  4689. * msgType Type of message to put extension into.
  4690. * pSz Size of extension data.
  4691. * return SANITY_MSG_E when the message is not allowed to have extension and
  4692. * 0 otherwise.
  4693. */
  4694. static int TLSX_EncryptThenMac_Write(void* data, byte* output, byte msgType,
  4695. word16* pSz)
  4696. {
  4697. (void)data;
  4698. (void)output;
  4699. (void)pSz;
  4700. if (msgType != client_hello && msgType != server_hello) {
  4701. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4702. return SANITY_MSG_E;
  4703. }
  4704. /* Empty extension */
  4705. return 0;
  4706. }
  4707. /**
  4708. * Parse the Encrypt-Then-MAC extension.
  4709. *
  4710. * ssl SSL object
  4711. * input Extension data buffer.
  4712. * length Length of this extension's data.
  4713. * msgType Type of message to extension appeared in.
  4714. * return SANITY_MSG_E when the message is not allowed to have extension,
  4715. * BUFFER_ERROR when the extension's data is invalid,
  4716. * MEMORY_E when unable to allocate memory and
  4717. * 0 otherwise.
  4718. */
  4719. static int TLSX_EncryptThenMac_Parse(WOLFSSL* ssl, const byte* input,
  4720. word16 length, byte msgType)
  4721. {
  4722. int ret;
  4723. (void)input;
  4724. if (msgType != client_hello && msgType != server_hello) {
  4725. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4726. return SANITY_MSG_E;
  4727. }
  4728. /* Empty extension */
  4729. if (length != 0)
  4730. return BUFFER_ERROR;
  4731. if (msgType == client_hello) {
  4732. /* Check the user hasn't disallowed use of Encrypt-Then-Mac. */
  4733. if (!ssl->options.disallowEncThenMac) {
  4734. ssl->options.encThenMac = 1;
  4735. /* Set the extension reply. */
  4736. ret = TLSX_EncryptThenMac_Use(ssl);
  4737. if (ret != 0)
  4738. return ret;
  4739. }
  4740. return 0;
  4741. }
  4742. /* Server Hello */
  4743. if (ssl->options.disallowEncThenMac) {
  4744. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4745. return SANITY_MSG_E;
  4746. }
  4747. ssl->options.encThenMac = 1;
  4748. return 0;
  4749. }
  4750. /**
  4751. * Add the Encrypt-Then-MAC extension to list.
  4752. *
  4753. * ssl SSL object
  4754. * return MEMORY_E when unable to allocate memory and 0 otherwise.
  4755. */
  4756. static int TLSX_EncryptThenMac_Use(WOLFSSL* ssl)
  4757. {
  4758. int ret = 0;
  4759. TLSX* extension;
  4760. /* Find the Encrypt-Then-Mac extension if it exists. */
  4761. extension = TLSX_Find(ssl->extensions, TLSX_ENCRYPT_THEN_MAC);
  4762. if (extension == NULL) {
  4763. /* Push new Encrypt-Then-Mac extension. */
  4764. ret = TLSX_Push(&ssl->extensions, TLSX_ENCRYPT_THEN_MAC, NULL,
  4765. ssl->heap);
  4766. if (ret != 0)
  4767. return ret;
  4768. }
  4769. return 0;
  4770. }
  4771. /**
  4772. * Set the Encrypt-Then-MAC extension as one to respond too.
  4773. *
  4774. * ssl SSL object
  4775. * return EXT_MISSING when EncryptThenMac extension not in list.
  4776. */
  4777. int TLSX_EncryptThenMac_Respond(WOLFSSL* ssl)
  4778. {
  4779. TLSX* extension;
  4780. extension = TLSX_Find(ssl->extensions, TLSX_ENCRYPT_THEN_MAC);
  4781. if (extension == NULL)
  4782. return EXT_MISSING;
  4783. extension->resp = 1;
  4784. return 0;
  4785. }
  4786. #define ETM_GET_SIZE TLSX_EncryptThenMac_GetSize
  4787. #define ETM_WRITE TLSX_EncryptThenMac_Write
  4788. #define ETM_PARSE TLSX_EncryptThenMac_Parse
  4789. #else
  4790. #define ETM_GET_SIZE(a, b) 0
  4791. #define ETM_WRITE(a, b, c, d) 0
  4792. #define ETM_PARSE(a, b, c, d) 0
  4793. #endif /* !WOLFSSL_NO_TLS12 */
  4794. #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */
  4795. #ifdef WOLFSSL_SRTP
  4796. /******************************************************************************/
  4797. /* DTLS SRTP (Secure Real-time Transport Protocol) */
  4798. /******************************************************************************/
  4799. /* Only support single SRTP profile */
  4800. typedef struct TlsxSrtp {
  4801. word16 profileCount;
  4802. word16 ids; /* selected bits */
  4803. } TlsxSrtp;
  4804. static int TLSX_UseSRTP_GetSize(TlsxSrtp *srtp)
  4805. {
  4806. /* SRTP Profile Len (2)
  4807. * SRTP Profiles (2)
  4808. * MKI (master key id) Length */
  4809. return (OPAQUE16_LEN + (srtp->profileCount * OPAQUE16_LEN) + 1);
  4810. }
  4811. static TlsxSrtp* TLSX_UseSRTP_New(word16 ids, void* heap)
  4812. {
  4813. TlsxSrtp* srtp;
  4814. int i;
  4815. srtp = (TlsxSrtp*)XMALLOC(sizeof(TlsxSrtp), heap, DYNAMIC_TYPE_TLSX);
  4816. if (srtp == NULL) {
  4817. WOLFSSL_MSG("TLSX SRTP Memory failure");
  4818. return NULL;
  4819. }
  4820. /* count and test each bit set */
  4821. srtp->profileCount = 0;
  4822. for (i=0; i<16; i++) {
  4823. if (ids & (1 << i)) {
  4824. srtp->profileCount++;
  4825. }
  4826. }
  4827. srtp->ids = ids;
  4828. return srtp;
  4829. }
  4830. static void TLSX_UseSRTP_Free(TlsxSrtp *srtp, void* heap)
  4831. {
  4832. if (srtp != NULL) {
  4833. XFREE(srtp, heap, DYNAMIC_TYPE_TLSX);
  4834. }
  4835. (void)heap;
  4836. }
  4837. static int TLSX_UseSRTP_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  4838. byte isRequest)
  4839. {
  4840. int ret = BAD_FUNC_ARG;
  4841. word16 profile_len = 0;
  4842. word16 profile_value = 0;
  4843. word16 offset = 0;
  4844. #ifndef NO_WOLFSSL_SERVER
  4845. int i;
  4846. TlsxSrtp* srtp = NULL;
  4847. #endif
  4848. if (length < OPAQUE16_LEN) {
  4849. return BUFFER_ERROR;
  4850. }
  4851. /* reset selected DTLS SRTP profile ID */
  4852. ssl->dtlsSrtpId = 0;
  4853. /* total length, not include itself */
  4854. ato16(input, &profile_len);
  4855. offset += OPAQUE16_LEN;
  4856. if (!isRequest) {
  4857. #ifndef NO_WOLFSSL_CLIENT
  4858. if (length < offset + OPAQUE16_LEN)
  4859. return BUFFER_ERROR;
  4860. ato16(input + offset, &profile_value);
  4861. /* check that the profile received was in the ones we support */
  4862. if (profile_value < 16 &&
  4863. (ssl->dtlsSrtpProfiles & (1 << profile_value))) {
  4864. ssl->dtlsSrtpId = profile_value;
  4865. ret = 0; /* success */
  4866. }
  4867. #endif
  4868. }
  4869. #ifndef NO_WOLFSSL_SERVER
  4870. else {
  4871. /* parse remainder one profile at a time, looking for match in CTX */
  4872. ret = 0;
  4873. for (i=offset; i<length; i+=OPAQUE16_LEN) {
  4874. if (length < (i + OPAQUE16_LEN)) {
  4875. WOLFSSL_MSG("Unexpected length when parsing SRTP profile");
  4876. ret = BUFFER_ERROR;
  4877. break;
  4878. }
  4879. ato16(input+i, &profile_value);
  4880. /* find first match */
  4881. if (profile_value < 16 &&
  4882. ssl->dtlsSrtpProfiles & (1 << profile_value)) {
  4883. ssl->dtlsSrtpId = profile_value;
  4884. /* make sure we respond with selected SRTP id selected */
  4885. srtp = TLSX_UseSRTP_New((1 << profile_value), ssl->heap);
  4886. if (srtp != NULL) {
  4887. ret = TLSX_Push(&ssl->extensions, TLSX_USE_SRTP,
  4888. (void*)srtp, ssl->heap);
  4889. if (ret == 0) {
  4890. TLSX_SetResponse(ssl, TLSX_USE_SRTP);
  4891. /* successfully set extension */
  4892. }
  4893. }
  4894. else {
  4895. ret = MEMORY_E;
  4896. }
  4897. break;
  4898. }
  4899. }
  4900. }
  4901. if (ret == 0 && ssl->dtlsSrtpId == 0) {
  4902. WOLFSSL_MSG("TLSX_UseSRTP_Parse profile not found!");
  4903. /* not fatal */
  4904. }
  4905. else if (ret != 0) {
  4906. ssl->dtlsSrtpId = 0;
  4907. TLSX_UseSRTP_Free(srtp, ssl->heap);
  4908. }
  4909. #endif
  4910. (void)profile_len;
  4911. return ret;
  4912. }
  4913. static word16 TLSX_UseSRTP_Write(TlsxSrtp* srtp, byte* output)
  4914. {
  4915. word16 offset = 0;
  4916. int i, j;
  4917. c16toa(srtp->profileCount * 2, output + offset);
  4918. offset += OPAQUE16_LEN;
  4919. j = 0;
  4920. for (i = 0; i < srtp->profileCount; i++) {
  4921. for (; j < 16; j++) {
  4922. if (srtp->ids & (1 << j)) {
  4923. c16toa(j, output + offset);
  4924. offset += OPAQUE16_LEN;
  4925. }
  4926. }
  4927. }
  4928. output[offset++] = 0x00; /* MKI Length */
  4929. return offset;
  4930. }
  4931. static int TLSX_UseSRTP(TLSX** extensions, word16 profiles, void* heap)
  4932. {
  4933. int ret = 0;
  4934. TLSX* extension;
  4935. if (extensions == NULL) {
  4936. return BAD_FUNC_ARG;
  4937. }
  4938. extension = TLSX_Find(*extensions, TLSX_USE_SRTP);
  4939. if (extension == NULL) {
  4940. TlsxSrtp* srtp = TLSX_UseSRTP_New(profiles, heap);
  4941. if (srtp == NULL) {
  4942. return MEMORY_E;
  4943. }
  4944. ret = TLSX_Push(extensions, TLSX_USE_SRTP, (void*)srtp, heap);
  4945. if (ret != 0) {
  4946. TLSX_UseSRTP_Free(srtp, heap);
  4947. }
  4948. }
  4949. return ret;
  4950. }
  4951. #ifndef NO_WOLFSSL_SERVER
  4952. #define SRTP_FREE TLSX_UseSRTP_Free
  4953. #define SRTP_PARSE TLSX_UseSRTP_Parse
  4954. #define SRTP_WRITE TLSX_UseSRTP_Write
  4955. #define SRTP_GET_SIZE TLSX_UseSRTP_GetSize
  4956. #else
  4957. #define SRTP_FREE(a, b) WC_DO_NOTHING
  4958. #define SRTP_PARSE(a, b, c, d) 0
  4959. #define SRTP_WRITE(a, b) 0
  4960. #define SRTP_GET_SIZE(a) 0
  4961. #endif
  4962. #endif /* WOLFSSL_SRTP */
  4963. /******************************************************************************/
  4964. /* Supported Versions */
  4965. /******************************************************************************/
  4966. #ifdef WOLFSSL_TLS13
  4967. static WC_INLINE int versionIsGreater(byte isDtls, byte a, byte b)
  4968. {
  4969. (void)isDtls;
  4970. #ifdef WOLFSSL_DTLS
  4971. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4972. if (isDtls)
  4973. return a < b;
  4974. #endif /* WOLFSSL_DTLS */
  4975. return a > b;
  4976. }
  4977. static WC_INLINE int versionIsLesser(byte isDtls, byte a, byte b)
  4978. {
  4979. (void)isDtls;
  4980. #ifdef WOLFSSL_DTLS
  4981. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4982. if (isDtls)
  4983. return a > b;
  4984. #endif /* WOLFSSL_DTLS */
  4985. return a < b;
  4986. }
  4987. static WC_INLINE int versionIsAtLeast(byte isDtls, byte a, byte b)
  4988. {
  4989. (void)isDtls;
  4990. #ifdef WOLFSSL_DTLS
  4991. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4992. if (isDtls)
  4993. return a <= b;
  4994. #endif /* WOLFSSL_DTLS */
  4995. return a >= b;
  4996. }
  4997. static WC_INLINE int versionIsLessEqual(byte isDtls, byte a, byte b)
  4998. {
  4999. (void)isDtls;
  5000. #ifdef WOLFSSL_DTLS
  5001. /* DTLS version increases backwards (-1,-2,-3,etc) */
  5002. if (isDtls)
  5003. return a >= b;
  5004. #endif /* WOLFSSL_DTLS */
  5005. return a <= b;
  5006. }
  5007. /* Return the size of the SupportedVersions extension's data.
  5008. *
  5009. * data The SSL/TLS object.
  5010. * msgType The type of the message this extension is being written into.
  5011. * returns the length of data that will be in the extension.
  5012. */
  5013. static int TLSX_SupportedVersions_GetSize(void* data, byte msgType, word16* pSz)
  5014. {
  5015. WOLFSSL* ssl = (WOLFSSL*)data;
  5016. byte tls13Minor, tls12Minor, tls11Minor, isDtls;
  5017. isDtls = !!ssl->options.dtls;
  5018. tls13Minor = (byte)(isDtls ? DTLSv1_3_MINOR : TLSv1_3_MINOR);
  5019. tls12Minor = (byte)(isDtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR);
  5020. tls11Minor = (byte)(isDtls ? DTLS_MINOR : TLSv1_1_MINOR);
  5021. /* unused on some configuration */
  5022. (void)tls12Minor;
  5023. (void)tls13Minor;
  5024. (void)tls11Minor;
  5025. if (msgType == client_hello) {
  5026. /* TLS v1.2 and TLS v1.3 */
  5027. int cnt = 0;
  5028. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13Minor)
  5029. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5030. defined(WOLFSSL_WPAS_SMALL)
  5031. && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0
  5032. #endif
  5033. ) {
  5034. cnt++;
  5035. }
  5036. if (ssl->options.downgrade) {
  5037. #ifndef WOLFSSL_NO_TLS12
  5038. if (versionIsLessEqual(
  5039. isDtls, ssl->options.minDowngrade, tls12Minor)
  5040. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5041. defined(WOLFSSL_WPAS_SMALL)
  5042. && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0
  5043. #endif
  5044. ) {
  5045. cnt++;
  5046. }
  5047. #endif
  5048. #ifndef NO_OLD_TLS
  5049. if (versionIsLessEqual(
  5050. isDtls, ssl->options.minDowngrade, tls11Minor)
  5051. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5052. defined(WOLFSSL_WPAS_SMALL)
  5053. && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0
  5054. #endif
  5055. ) {
  5056. cnt++;
  5057. }
  5058. #ifdef WOLFSSL_ALLOW_TLSV10
  5059. if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR)
  5060. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5061. defined(WOLFSSL_WPAS_SMALL)
  5062. && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0
  5063. #endif
  5064. ) {
  5065. cnt++;
  5066. }
  5067. #endif
  5068. #endif
  5069. }
  5070. *pSz += (word16)(OPAQUE8_LEN + cnt * OPAQUE16_LEN);
  5071. }
  5072. else if (msgType == server_hello || msgType == hello_retry_request) {
  5073. *pSz += OPAQUE16_LEN;
  5074. }
  5075. else {
  5076. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5077. return SANITY_MSG_E;
  5078. }
  5079. return 0;
  5080. }
  5081. /* Writes the SupportedVersions extension into the buffer.
  5082. *
  5083. * data The SSL/TLS object.
  5084. * output The buffer to write the extension into.
  5085. * msgType The type of the message this extension is being written into.
  5086. * returns the length of data that was written.
  5087. */
  5088. static int TLSX_SupportedVersions_Write(void* data, byte* output,
  5089. byte msgType, word16* pSz)
  5090. {
  5091. WOLFSSL* ssl = (WOLFSSL*)data;
  5092. byte tls13minor, tls12minor, tls11minor, isDtls = 0;
  5093. tls13minor = (byte)TLSv1_3_MINOR;
  5094. tls12minor = (byte)TLSv1_2_MINOR;
  5095. tls11minor = (byte)TLSv1_1_MINOR;
  5096. /* unused in some configuration */
  5097. (void)tls11minor;
  5098. (void)tls12minor;
  5099. #ifdef WOLFSSL_DTLS13
  5100. if (ssl->options.dtls) {
  5101. tls13minor = (byte)DTLSv1_3_MINOR;
  5102. tls12minor = (byte)DTLSv1_2_MINOR;
  5103. tls11minor = (byte)DTLS_MINOR;
  5104. isDtls = 1;
  5105. }
  5106. #endif /* WOLFSSL_DTLS13 */
  5107. if (msgType == client_hello) {
  5108. byte major = ssl->ctx->method->version.major;
  5109. byte* cnt = output++;
  5110. *cnt = 0;
  5111. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13minor)
  5112. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5113. defined(WOLFSSL_WPAS_SMALL)
  5114. && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0
  5115. #endif
  5116. ) {
  5117. *cnt += OPAQUE16_LEN;
  5118. #ifdef WOLFSSL_TLS13_DRAFT
  5119. /* The TLS draft major number. */
  5120. *(output++) = TLS_DRAFT_MAJOR;
  5121. /* Version of draft supported. */
  5122. *(output++) = TLS_DRAFT_MINOR;
  5123. #else
  5124. *(output++) = major;
  5125. *(output++) = tls13minor;
  5126. #endif
  5127. }
  5128. if (ssl->options.downgrade) {
  5129. #ifndef WOLFSSL_NO_TLS12
  5130. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls12minor)
  5131. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5132. defined(WOLFSSL_WPAS_SMALL)
  5133. && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0
  5134. #endif
  5135. ) {
  5136. *cnt += OPAQUE16_LEN;
  5137. *(output++) = major;
  5138. *(output++) = tls12minor;
  5139. }
  5140. #endif
  5141. #ifndef NO_OLD_TLS
  5142. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls11minor)
  5143. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5144. defined(WOLFSSL_WPAS_SMALL)
  5145. && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0
  5146. #endif
  5147. ) {
  5148. *cnt += OPAQUE16_LEN;
  5149. *(output++) = major;
  5150. *(output++) = tls11minor;
  5151. }
  5152. #ifdef WOLFSSL_ALLOW_TLSV10
  5153. if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR)
  5154. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5155. defined(WOLFSSL_WPAS_SMALL)
  5156. && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0
  5157. #endif
  5158. ) {
  5159. *cnt += OPAQUE16_LEN;
  5160. *(output++) = major;
  5161. *(output++) = (byte)TLSv1_MINOR;
  5162. }
  5163. #endif
  5164. #endif
  5165. }
  5166. *pSz += (word16)(OPAQUE8_LEN + *cnt);
  5167. }
  5168. else if (msgType == server_hello || msgType == hello_retry_request) {
  5169. output[0] = ssl->version.major;
  5170. output[1] = ssl->version.minor;
  5171. *pSz += OPAQUE16_LEN;
  5172. }
  5173. else {
  5174. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5175. return SANITY_MSG_E;
  5176. }
  5177. return 0;
  5178. }
  5179. /* Parse the SupportedVersions extension.
  5180. *
  5181. * ssl The SSL/TLS object.
  5182. * input The buffer with the extension data.
  5183. * length The length of the extension data.
  5184. * msgType The type of the message this extension is being parsed from.
  5185. * pv The output ProtocolVersion for the negotiated version
  5186. * opts The output options structure. Can be NULL.
  5187. * exts The output extensions list. Can be NULL.
  5188. * returns 0 on success, otherwise failure.
  5189. */
  5190. int TLSX_SupportedVersions_Parse(const WOLFSSL* ssl, const byte* input,
  5191. word16 length, byte msgType, ProtocolVersion* pv, Options* opts,
  5192. TLSX** exts)
  5193. {
  5194. /* The client's greatest minor version that we support */
  5195. byte clientGreatestMinor = SSLv3_MINOR;
  5196. int ret;
  5197. byte major, minor;
  5198. byte tls13minor, tls12minor;
  5199. byte isDtls;
  5200. tls13minor = TLSv1_3_MINOR;
  5201. tls12minor = TLSv1_2_MINOR;
  5202. isDtls = ssl->options.dtls == 1;
  5203. #ifdef WOLFSSL_DTLS13
  5204. if (ssl->options.dtls) {
  5205. tls13minor = DTLSv1_3_MINOR;
  5206. tls12minor = DTLSv1_2_MINOR;
  5207. clientGreatestMinor = DTLS_MINOR;
  5208. }
  5209. #endif /* WOLFSSL_DTLS13 */
  5210. if (msgType == client_hello) {
  5211. int i;
  5212. int len;
  5213. int set = 0;
  5214. /* Must contain a length and at least one version. */
  5215. if (length < OPAQUE8_LEN + OPAQUE16_LEN || (length & 1) != 1)
  5216. return BUFFER_ERROR;
  5217. len = *input;
  5218. /* Protocol version array must fill rest of data. */
  5219. if (length != (word16)OPAQUE8_LEN + len)
  5220. return BUFFER_ERROR;
  5221. input++;
  5222. /* Find first match. */
  5223. for (i = 0; i < len; i += OPAQUE16_LEN) {
  5224. major = input[i];
  5225. minor = input[i + OPAQUE8_LEN];
  5226. #ifdef WOLFSSL_TLS13_DRAFT
  5227. if (major == TLS_DRAFT_MAJOR && minor == TLS_DRAFT_MINOR) {
  5228. major = SSLv3_MAJOR;
  5229. minor = TLSv1_3_MINOR;
  5230. }
  5231. #else
  5232. if (major == TLS_DRAFT_MAJOR)
  5233. continue;
  5234. #endif
  5235. if (major != ssl->ctx->method->version.major)
  5236. continue;
  5237. /* No upgrade allowed. */
  5238. if (versionIsGreater(isDtls, minor, ssl->version.minor))
  5239. continue;
  5240. /* Check downgrade. */
  5241. if (versionIsLesser(isDtls, minor, ssl->version.minor)) {
  5242. if (!ssl->options.downgrade)
  5243. continue;
  5244. if (versionIsLesser(isDtls, minor, ssl->options.minDowngrade))
  5245. continue;
  5246. }
  5247. if (versionIsGreater(isDtls, minor, clientGreatestMinor))
  5248. clientGreatestMinor = minor;
  5249. set = 1;
  5250. }
  5251. if (!set) {
  5252. /* No common supported version was negotiated */
  5253. SendAlert((WOLFSSL*)ssl, alert_fatal,
  5254. wolfssl_alert_protocol_version);
  5255. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5256. return VERSION_ERROR;
  5257. }
  5258. pv->minor = clientGreatestMinor;
  5259. if (versionIsAtLeast(isDtls, clientGreatestMinor, tls13minor)) {
  5260. if (opts != NULL)
  5261. opts->tls1_3 = 1;
  5262. /* TLS v1.3 requires supported version extension */
  5263. if (exts != NULL &&
  5264. TLSX_Find(*exts, TLSX_SUPPORTED_VERSIONS) == NULL) {
  5265. ret = TLSX_Push(exts,
  5266. TLSX_SUPPORTED_VERSIONS, ssl, ssl->heap);
  5267. if (ret != 0) {
  5268. return ret;
  5269. }
  5270. /* *exts should be pointing to the TLSX_SUPPORTED_VERSIONS
  5271. * ext in the list since it was pushed. */
  5272. (*exts)->resp = 1;
  5273. }
  5274. }
  5275. }
  5276. else if (msgType == server_hello || msgType == hello_retry_request) {
  5277. /* Must contain one version. */
  5278. if (length != OPAQUE16_LEN)
  5279. return BUFFER_ERROR;
  5280. major = input[0];
  5281. minor = input[OPAQUE8_LEN];
  5282. if (major != ssl->ctx->method->version.major) {
  5283. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5284. return VERSION_ERROR;
  5285. }
  5286. /* Can't downgrade with this extension below TLS v1.3. */
  5287. if (versionIsLesser(isDtls, minor, tls13minor)) {
  5288. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5289. return VERSION_ERROR;
  5290. }
  5291. /* Version is TLS v1.2 to handle downgrading from TLS v1.3+. */
  5292. if (ssl->options.downgrade && ssl->version.minor == tls12minor) {
  5293. /* Set minor version back to TLS v1.3+ */
  5294. pv->minor = ssl->ctx->method->version.minor;
  5295. }
  5296. /* No upgrade allowed. */
  5297. if (versionIsLesser(isDtls, ssl->version.minor, minor)) {
  5298. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5299. return VERSION_ERROR;
  5300. }
  5301. /* Check downgrade. */
  5302. if (versionIsGreater(isDtls, ssl->version.minor, minor)) {
  5303. if (!ssl->options.downgrade) {
  5304. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5305. return VERSION_ERROR;
  5306. }
  5307. if (versionIsLesser(
  5308. isDtls, minor, ssl->options.minDowngrade)) {
  5309. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5310. return VERSION_ERROR;
  5311. }
  5312. /* Downgrade the version. */
  5313. pv->minor = minor;
  5314. }
  5315. }
  5316. else {
  5317. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5318. return SANITY_MSG_E;
  5319. }
  5320. return 0;
  5321. }
  5322. /* Sets a new SupportedVersions extension into the extension list.
  5323. *
  5324. * extensions The list of extensions.
  5325. * data The extensions specific data.
  5326. * heap The heap used for allocation.
  5327. * returns 0 on success, otherwise failure.
  5328. */
  5329. static int TLSX_SetSupportedVersions(TLSX** extensions, const void* data,
  5330. void* heap)
  5331. {
  5332. if (extensions == NULL || data == NULL)
  5333. return BAD_FUNC_ARG;
  5334. return TLSX_Push(extensions, TLSX_SUPPORTED_VERSIONS, data, heap);
  5335. }
  5336. #define SV_GET_SIZE TLSX_SupportedVersions_GetSize
  5337. #define SV_WRITE TLSX_SupportedVersions_Write
  5338. #define SV_PARSE TLSX_SupportedVersions_Parse
  5339. #else
  5340. #define SV_GET_SIZE(a, b, c) 0
  5341. #define SV_WRITE(a, b, c, d) 0
  5342. #define SV_PARSE(a, b, c, d, e, f, g) 0
  5343. #endif /* WOLFSSL_TLS13 */
  5344. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  5345. /******************************************************************************/
  5346. /* Cookie */
  5347. /******************************************************************************/
  5348. /* Free the cookie data.
  5349. *
  5350. * cookie Cookie data.
  5351. * heap The heap used for allocation.
  5352. */
  5353. static void TLSX_Cookie_FreeAll(Cookie* cookie, void* heap)
  5354. {
  5355. (void)heap;
  5356. if (cookie != NULL)
  5357. XFREE(cookie, heap, DYNAMIC_TYPE_TLSX);
  5358. }
  5359. /* Get the size of the encoded Cookie extension.
  5360. * In messages: ClientHello and HelloRetryRequest.
  5361. *
  5362. * cookie The cookie to write.
  5363. * msgType The type of the message this extension is being written into.
  5364. * returns the number of bytes of the encoded Cookie extension.
  5365. */
  5366. static int TLSX_Cookie_GetSize(Cookie* cookie, byte msgType, word16* pSz)
  5367. {
  5368. if (msgType == client_hello || msgType == hello_retry_request) {
  5369. *pSz += OPAQUE16_LEN + cookie->len;
  5370. }
  5371. else {
  5372. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5373. return SANITY_MSG_E;
  5374. }
  5375. return 0;
  5376. }
  5377. /* Writes the Cookie extension into the output buffer.
  5378. * Assumes that the the output buffer is big enough to hold data.
  5379. * In messages: ClientHello and HelloRetryRequest.
  5380. *
  5381. * cookie The cookie to write.
  5382. * output The buffer to write into.
  5383. * msgType The type of the message this extension is being written into.
  5384. * returns the number of bytes written into the buffer.
  5385. */
  5386. static int TLSX_Cookie_Write(Cookie* cookie, byte* output, byte msgType,
  5387. word16* pSz)
  5388. {
  5389. if (msgType == client_hello || msgType == hello_retry_request) {
  5390. c16toa(cookie->len, output);
  5391. output += OPAQUE16_LEN;
  5392. XMEMCPY(output, cookie->data, cookie->len);
  5393. *pSz += OPAQUE16_LEN + cookie->len;
  5394. }
  5395. else {
  5396. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5397. return SANITY_MSG_E;
  5398. }
  5399. return 0;
  5400. }
  5401. /* Parse the Cookie extension.
  5402. * In messages: ClientHello and HelloRetryRequest.
  5403. *
  5404. * ssl The SSL/TLS object.
  5405. * input The extension data.
  5406. * length The length of the extension data.
  5407. * msgType The type of the message this extension is being parsed from.
  5408. * returns 0 on success and other values indicate failure.
  5409. */
  5410. static int TLSX_Cookie_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  5411. byte msgType)
  5412. {
  5413. word16 len;
  5414. word16 idx = 0;
  5415. TLSX* extension;
  5416. Cookie* cookie;
  5417. if (msgType != client_hello && msgType != hello_retry_request) {
  5418. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5419. return SANITY_MSG_E;
  5420. }
  5421. /* Message contains length and Cookie which must be at least one byte
  5422. * in length.
  5423. */
  5424. if (length < OPAQUE16_LEN + 1)
  5425. return BUFFER_E;
  5426. ato16(input + idx, &len);
  5427. idx += OPAQUE16_LEN;
  5428. if (length - idx != len)
  5429. return BUFFER_E;
  5430. if (msgType == hello_retry_request)
  5431. return TLSX_Cookie_Use(ssl, input + idx, len, NULL, 0, 1,
  5432. &ssl->extensions);
  5433. /* client_hello */
  5434. extension = TLSX_Find(ssl->extensions, TLSX_COOKIE);
  5435. if (extension == NULL) {
  5436. #ifdef WOLFSSL_DTLS13
  5437. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version))
  5438. /* Allow a cookie extension with DTLS 1.3 because it is possible
  5439. * that a different SSL instance sent the cookie but we are now
  5440. * receiving it. */
  5441. return TLSX_Cookie_Use(ssl, input + idx, len, NULL, 0, 0,
  5442. &ssl->extensions);
  5443. else
  5444. #endif
  5445. {
  5446. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  5447. return HRR_COOKIE_ERROR;
  5448. }
  5449. }
  5450. cookie = (Cookie*)extension->data;
  5451. if (cookie->len != len || XMEMCMP(cookie->data, input + idx, len) != 0) {
  5452. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  5453. return HRR_COOKIE_ERROR;
  5454. }
  5455. /* Request seen. */
  5456. extension->resp = 0;
  5457. return 0;
  5458. }
  5459. /* Use the data to create a new Cookie object in the extensions.
  5460. *
  5461. * ssl SSL/TLS object.
  5462. * data Cookie data.
  5463. * len Length of cookie data in bytes.
  5464. * mac MAC data.
  5465. * macSz Length of MAC data in bytes.
  5466. * resp Indicates the extension will go into a response (HelloRetryRequest).
  5467. * returns 0 on success and other values indicate failure.
  5468. */
  5469. int TLSX_Cookie_Use(const WOLFSSL* ssl, const byte* data, word16 len, byte* mac,
  5470. byte macSz, int resp, TLSX** exts)
  5471. {
  5472. int ret = 0;
  5473. TLSX* extension;
  5474. Cookie* cookie;
  5475. /* Find the cookie extension if it exists. */
  5476. extension = TLSX_Find(*exts, TLSX_COOKIE);
  5477. if (extension == NULL) {
  5478. /* Push new cookie extension. */
  5479. ret = TLSX_Push(exts, TLSX_COOKIE, NULL, ssl->heap);
  5480. if (ret != 0)
  5481. return ret;
  5482. extension = TLSX_Find(*exts, TLSX_COOKIE);
  5483. if (extension == NULL)
  5484. return MEMORY_E;
  5485. }
  5486. cookie = (Cookie*)XMALLOC(sizeof(Cookie) + len + macSz, ssl->heap,
  5487. DYNAMIC_TYPE_TLSX);
  5488. if (cookie == NULL)
  5489. return MEMORY_E;
  5490. cookie->len = len + macSz;
  5491. XMEMCPY(cookie->data, data, len);
  5492. if (mac != NULL)
  5493. XMEMCPY(cookie->data + len, mac, macSz);
  5494. if (extension->data != NULL)
  5495. XFREE(extension->data, ssl->heap, DYNAMIC_TYPE_TLSX);
  5496. extension->data = (void*)cookie;
  5497. extension->resp = (byte)resp;
  5498. return 0;
  5499. }
  5500. #define CKE_FREE_ALL TLSX_Cookie_FreeAll
  5501. #define CKE_GET_SIZE TLSX_Cookie_GetSize
  5502. #define CKE_WRITE TLSX_Cookie_Write
  5503. #define CKE_PARSE TLSX_Cookie_Parse
  5504. #else
  5505. #define CKE_FREE_ALL(a, b) 0
  5506. #define CKE_GET_SIZE(a, b, c) 0
  5507. #define CKE_WRITE(a, b, c, d) 0
  5508. #define CKE_PARSE(a, b, c, d) 0
  5509. #endif
  5510. #if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && \
  5511. !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA)
  5512. /* Currently only settable through compatibility API */
  5513. /******************************************************************************/
  5514. /* Certificate Authorities */
  5515. /******************************************************************************/
  5516. static word16 TLSX_CA_Names_GetSize(void* data)
  5517. {
  5518. WOLFSSL* ssl = (WOLFSSL*)data;
  5519. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  5520. word16 size = 0;
  5521. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5522. /* To add support use a different member like ssl->ca_names and
  5523. * add accessor functions:
  5524. * - *_set0_CA_list
  5525. * - *_get0_CA_list */
  5526. WOLFSSL_MSG("We don't currently support sending the client's list.");
  5527. return 0;
  5528. }
  5529. /* Length of names */
  5530. size += OPAQUE16_LEN;
  5531. for (names = SSL_CA_NAMES(ssl); names != NULL; names = names->next) {
  5532. byte seq[MAX_SEQ_SZ];
  5533. WOLFSSL_X509_NAME* name = names->data.name;
  5534. if (name != NULL) {
  5535. /* 16-bit length | SEQ | Len | DER of name */
  5536. size += (word16)(OPAQUE16_LEN + SetSequence(name->rawLen, seq) +
  5537. name->rawLen);
  5538. }
  5539. }
  5540. return size;
  5541. }
  5542. static word16 TLSX_CA_Names_Write(void* data, byte* output)
  5543. {
  5544. WOLFSSL* ssl = (WOLFSSL*)data;
  5545. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  5546. byte* len;
  5547. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5548. /* To add support use a different member like ssl->ca_names and
  5549. * add accessor functions:
  5550. * - *_set0_CA_list
  5551. * - *_get0_CA_list */
  5552. WOLFSSL_MSG("We don't currently support sending the client's list.");
  5553. return 0;
  5554. }
  5555. /* Reserve space for the length value */
  5556. len = output;
  5557. output += OPAQUE16_LEN;
  5558. for (names = SSL_CA_NAMES(ssl); names != NULL; names = names->next) {
  5559. byte seq[MAX_SEQ_SZ];
  5560. WOLFSSL_X509_NAME* name = names->data.name;
  5561. if (name != NULL) {
  5562. c16toa((word16)name->rawLen +
  5563. (word16)SetSequence(name->rawLen, seq), output);
  5564. output += OPAQUE16_LEN;
  5565. output += SetSequence(name->rawLen, output);
  5566. XMEMCPY(output, name->raw, name->rawLen);
  5567. output += name->rawLen;
  5568. }
  5569. }
  5570. /* Write the total length */
  5571. c16toa((word16)(output - len - OPAQUE16_LEN), len);
  5572. return (word16)(output - len);
  5573. }
  5574. static int TLSX_CA_Names_Parse(WOLFSSL *ssl, const byte* input,
  5575. word16 length, byte isRequest)
  5576. {
  5577. word16 extLen;
  5578. (void)isRequest;
  5579. if (ssl->options.side == WOLFSSL_SERVER_END) {
  5580. /* To add support use a different member like ssl->ca_names and
  5581. * add accessor functions:
  5582. * - *_set0_CA_list
  5583. * - *_get0_CA_list */
  5584. WOLFSSL_MSG("We don't currently support parsing the client's list.");
  5585. return 0;
  5586. }
  5587. if (ssl->client_ca_names != ssl->ctx->client_ca_names)
  5588. wolfSSL_sk_X509_NAME_pop_free(ssl->client_ca_names, NULL);
  5589. ssl->client_ca_names = wolfSSL_sk_X509_NAME_new(NULL);
  5590. if (ssl->client_ca_names == NULL)
  5591. return MEMORY_ERROR;
  5592. if (length < OPAQUE16_LEN)
  5593. return BUFFER_ERROR;
  5594. ato16(input, &extLen);
  5595. input += OPAQUE16_LEN;
  5596. length -= OPAQUE16_LEN;
  5597. if (extLen != length)
  5598. return BUFFER_ERROR;
  5599. while (length) {
  5600. word32 idx = 0;
  5601. WOLFSSL_X509_NAME* name = NULL;
  5602. int ret = 0;
  5603. int didInit = FALSE;
  5604. /* Use a DecodedCert struct to get access to GetName to
  5605. * parse DN name */
  5606. #ifdef WOLFSSL_SMALL_STACK
  5607. DecodedCert *cert = (DecodedCert *)XMALLOC(
  5608. sizeof(*cert), ssl->heap, DYNAMIC_TYPE_DCERT);
  5609. if (cert == NULL)
  5610. return MEMORY_ERROR;
  5611. #else
  5612. DecodedCert cert[1];
  5613. #endif
  5614. if (length < OPAQUE16_LEN) {
  5615. ret = BUFFER_ERROR;
  5616. }
  5617. if (ret == 0) {
  5618. ato16(input, &extLen);
  5619. idx += OPAQUE16_LEN;
  5620. if (idx + extLen > length)
  5621. ret = BUFFER_ERROR;
  5622. }
  5623. if (ret == 0) {
  5624. InitDecodedCert(cert, input + idx, extLen, ssl->heap);
  5625. didInit = TRUE;
  5626. idx += extLen;
  5627. ret = GetName(cert, SUBJECT, extLen);
  5628. }
  5629. if (ret == 0 && (name = wolfSSL_X509_NAME_new()) == NULL)
  5630. ret = MEMORY_ERROR;
  5631. if (ret == 0) {
  5632. CopyDecodedName(name, cert, SUBJECT);
  5633. if (wolfSSL_sk_X509_NAME_push(ssl->client_ca_names, name)
  5634. == WOLFSSL_FAILURE)
  5635. ret = MEMORY_ERROR;
  5636. }
  5637. if (didInit)
  5638. FreeDecodedCert(cert);
  5639. #ifdef WOLFSSL_SMALL_STACK
  5640. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  5641. #endif
  5642. if (ret != 0)
  5643. return ret;
  5644. input += idx;
  5645. length -= (word16)idx;
  5646. }
  5647. return 0;
  5648. }
  5649. #define CAN_GET_SIZE TLSX_CA_Names_GetSize
  5650. #define CAN_WRITE TLSX_CA_Names_Write
  5651. #define CAN_PARSE TLSX_CA_Names_Parse
  5652. #else
  5653. #define CAN_GET_SIZE(...) 0
  5654. #define CAN_WRITE(...) 0
  5655. #define CAN_PARSE(...) 0
  5656. #endif
  5657. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  5658. /******************************************************************************/
  5659. /* Signature Algorithms */
  5660. /******************************************************************************/
  5661. /* Return the size of the SignatureAlgorithms extension's data.
  5662. *
  5663. * data Unused
  5664. * returns the length of data that will be in the extension.
  5665. */
  5666. static word16 TLSX_SignatureAlgorithms_GetSize(void* data)
  5667. {
  5668. SignatureAlgorithms* sa = (SignatureAlgorithms*)data;
  5669. if (sa->hashSigAlgoSz == 0)
  5670. return OPAQUE16_LEN + WOLFSSL_SUITES(sa->ssl)->hashSigAlgoSz;
  5671. else
  5672. return OPAQUE16_LEN + sa->hashSigAlgoSz;
  5673. }
  5674. /* Creates a bit string of supported hash algorithms with RSA PSS.
  5675. * The bit string is used when determining which signature algorithm to use
  5676. * when creating the CertificateVerify message.
  5677. * Note: Valid data has an even length as each signature algorithm is two bytes.
  5678. *
  5679. * ssl The SSL/TLS object.
  5680. * input The buffer with the list of supported signature algorithms.
  5681. * length The length of the list in bytes.
  5682. * returns 0 on success, BUFFER_ERROR when the length is not even.
  5683. */
  5684. static int TLSX_SignatureAlgorithms_MapPss(WOLFSSL *ssl, const byte* input,
  5685. word16 length)
  5686. {
  5687. word16 i;
  5688. if ((length & 1) == 1)
  5689. return BUFFER_ERROR;
  5690. ssl->pssAlgo = 0;
  5691. for (i = 0; i < length; i += 2) {
  5692. if (input[i] == rsa_pss_sa_algo && input[i + 1] <= sha512_mac)
  5693. ssl->pssAlgo |= 1 << input[i + 1];
  5694. #ifdef WOLFSSL_TLS13
  5695. if (input[i] == rsa_pss_sa_algo && input[i + 1] >= pss_sha256 &&
  5696. input[i + 1] <= pss_sha512) {
  5697. ssl->pssAlgo |= 1 << input[i + 1];
  5698. }
  5699. #endif
  5700. }
  5701. return 0;
  5702. }
  5703. /* Writes the SignatureAlgorithms extension into the buffer.
  5704. *
  5705. * data Unused
  5706. * output The buffer to write the extension into.
  5707. * returns the length of data that was written.
  5708. */
  5709. static word16 TLSX_SignatureAlgorithms_Write(void* data, byte* output)
  5710. {
  5711. SignatureAlgorithms* sa = (SignatureAlgorithms*)data;
  5712. const Suites* suites = WOLFSSL_SUITES(sa->ssl);
  5713. word16 hashSigAlgoSz;
  5714. if (sa->hashSigAlgoSz == 0) {
  5715. c16toa(suites->hashSigAlgoSz, output);
  5716. XMEMCPY(output + OPAQUE16_LEN, suites->hashSigAlgo,
  5717. suites->hashSigAlgoSz);
  5718. hashSigAlgoSz = suites->hashSigAlgoSz;
  5719. }
  5720. else {
  5721. c16toa(sa->hashSigAlgoSz, output);
  5722. XMEMCPY(output + OPAQUE16_LEN, sa->hashSigAlgo,
  5723. sa->hashSigAlgoSz);
  5724. hashSigAlgoSz = sa->hashSigAlgoSz;
  5725. }
  5726. #ifndef NO_RSA
  5727. TLSX_SignatureAlgorithms_MapPss(sa->ssl, output + OPAQUE16_LEN,
  5728. hashSigAlgoSz);
  5729. #endif
  5730. return OPAQUE16_LEN + hashSigAlgoSz;
  5731. }
  5732. /* Parse the SignatureAlgorithms extension.
  5733. *
  5734. * ssl The SSL/TLS object.
  5735. * input The buffer with the extension data.
  5736. * length The length of the extension data.
  5737. * returns 0 on success, otherwise failure.
  5738. */
  5739. static int TLSX_SignatureAlgorithms_Parse(WOLFSSL *ssl, const byte* input,
  5740. word16 length, byte isRequest, Suites* suites)
  5741. {
  5742. word16 len;
  5743. if (!isRequest)
  5744. return BUFFER_ERROR;
  5745. /* Must contain a length and at least algorithm. */
  5746. if (length < OPAQUE16_LEN + OPAQUE16_LEN || (length & 1) != 0)
  5747. return BUFFER_ERROR;
  5748. ato16(input, &len);
  5749. input += OPAQUE16_LEN;
  5750. /* Algorithm array must fill rest of data. */
  5751. if (length != OPAQUE16_LEN + len)
  5752. return BUFFER_ERROR;
  5753. /* Sig Algo list size must be even. */
  5754. if (suites->hashSigAlgoSz % 2 != 0)
  5755. return BUFFER_ERROR;
  5756. /* truncate hashSigAlgo list if too long */
  5757. suites->hashSigAlgoSz = len;
  5758. if (suites->hashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  5759. WOLFSSL_MSG("TLSX SigAlgo list exceeds max, truncating");
  5760. suites->hashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  5761. }
  5762. XMEMCPY(suites->hashSigAlgo, input, suites->hashSigAlgoSz);
  5763. return TLSX_SignatureAlgorithms_MapPss(ssl, input, len);
  5764. }
  5765. /* Sets a new SignatureAlgorithms extension into the extension list.
  5766. *
  5767. * extensions The list of extensions.
  5768. * data The extensions specific data.
  5769. * heap The heap used for allocation.
  5770. * returns 0 on success, otherwise failure.
  5771. */
  5772. static int TLSX_SetSignatureAlgorithms(TLSX** extensions, WOLFSSL* ssl,
  5773. void* heap)
  5774. {
  5775. SignatureAlgorithms* sa;
  5776. int ret;
  5777. if (extensions == NULL)
  5778. return BAD_FUNC_ARG;
  5779. /* Already present */
  5780. if (TLSX_Find(*extensions, TLSX_SIGNATURE_ALGORITHMS) != NULL)
  5781. return 0;
  5782. sa = TLSX_SignatureAlgorithms_New(ssl, 0, heap);
  5783. if (sa == NULL)
  5784. return MEMORY_ERROR;
  5785. ret = TLSX_Push(extensions, TLSX_SIGNATURE_ALGORITHMS, sa, heap);
  5786. if (ret != 0)
  5787. TLSX_SignatureAlgorithms_FreeAll(sa, heap);
  5788. return ret;
  5789. }
  5790. SignatureAlgorithms* TLSX_SignatureAlgorithms_New(WOLFSSL* ssl,
  5791. word16 hashSigAlgoSz, void* heap)
  5792. {
  5793. SignatureAlgorithms* sa;
  5794. (void)heap;
  5795. sa = (SignatureAlgorithms*)XMALLOC(sizeof(*sa) + hashSigAlgoSz, heap,
  5796. DYNAMIC_TYPE_TLSX);
  5797. if (sa != NULL) {
  5798. XMEMSET(sa, 0, sizeof(*sa) + hashSigAlgoSz);
  5799. sa->ssl = ssl;
  5800. sa->hashSigAlgoSz = hashSigAlgoSz;
  5801. }
  5802. return sa;
  5803. }
  5804. void TLSX_SignatureAlgorithms_FreeAll(SignatureAlgorithms* sa,
  5805. void* heap)
  5806. {
  5807. XFREE(sa, heap, DYNAMIC_TYPE_TLSX);
  5808. (void)heap;
  5809. }
  5810. #define SA_GET_SIZE TLSX_SignatureAlgorithms_GetSize
  5811. #define SA_WRITE TLSX_SignatureAlgorithms_Write
  5812. #define SA_PARSE TLSX_SignatureAlgorithms_Parse
  5813. #define SA_FREE_ALL TLSX_SignatureAlgorithms_FreeAll
  5814. #endif
  5815. /******************************************************************************/
  5816. /* Signature Algorithms Certificate */
  5817. /******************************************************************************/
  5818. #if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  5819. /* Return the size of the SignatureAlgorithms extension's data.
  5820. *
  5821. * data Unused
  5822. * returns the length of data that will be in the extension.
  5823. */
  5824. static word16 TLSX_SignatureAlgorithmsCert_GetSize(void* data)
  5825. {
  5826. WOLFSSL* ssl = (WOLFSSL*)data;
  5827. return OPAQUE16_LEN + ssl->certHashSigAlgoSz;
  5828. }
  5829. /* Writes the SignatureAlgorithmsCert extension into the buffer.
  5830. *
  5831. * data Unused
  5832. * output The buffer to write the extension into.
  5833. * returns the length of data that was written.
  5834. */
  5835. static word16 TLSX_SignatureAlgorithmsCert_Write(void* data, byte* output)
  5836. {
  5837. WOLFSSL* ssl = (WOLFSSL*)data;
  5838. c16toa(ssl->certHashSigAlgoSz, output);
  5839. XMEMCPY(output + OPAQUE16_LEN, ssl->certHashSigAlgo,
  5840. ssl->certHashSigAlgoSz);
  5841. return OPAQUE16_LEN + ssl->certHashSigAlgoSz;
  5842. }
  5843. /* Parse the SignatureAlgorithmsCert extension.
  5844. *
  5845. * ssl The SSL/TLS object.
  5846. * input The buffer with the extension data.
  5847. * length The length of the extension data.
  5848. * returns 0 on success, otherwise failure.
  5849. */
  5850. static int TLSX_SignatureAlgorithmsCert_Parse(WOLFSSL *ssl, const byte* input,
  5851. word16 length, byte isRequest)
  5852. {
  5853. word16 len;
  5854. if (!isRequest)
  5855. return BUFFER_ERROR;
  5856. /* Must contain a length and at least algorithm. */
  5857. if (length < OPAQUE16_LEN + OPAQUE16_LEN || (length & 1) != 0)
  5858. return BUFFER_ERROR;
  5859. ato16(input, &len);
  5860. input += OPAQUE16_LEN;
  5861. /* Algorithm array must fill rest of data. */
  5862. if (length != OPAQUE16_LEN + len)
  5863. return BUFFER_ERROR;
  5864. /* truncate hashSigAlgo list if too long */
  5865. ssl->certHashSigAlgoSz = len;
  5866. if (ssl->certHashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  5867. WOLFSSL_MSG("TLSX SigAlgo list exceeds max, truncating");
  5868. ssl->certHashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  5869. }
  5870. XMEMCPY(ssl->certHashSigAlgo, input, ssl->certHashSigAlgoSz);
  5871. return 0;
  5872. }
  5873. /* Sets a new SignatureAlgorithmsCert extension into the extension list.
  5874. *
  5875. * extensions The list of extensions.
  5876. * data The extensions specific data.
  5877. * heap The heap used for allocation.
  5878. * returns 0 on success, otherwise failure.
  5879. */
  5880. static int TLSX_SetSignatureAlgorithmsCert(TLSX** extensions,
  5881. const WOLFSSL* data, void* heap)
  5882. {
  5883. if (extensions == NULL)
  5884. return BAD_FUNC_ARG;
  5885. return TLSX_Push(extensions, TLSX_SIGNATURE_ALGORITHMS_CERT, data, heap);
  5886. }
  5887. #define SAC_GET_SIZE TLSX_SignatureAlgorithmsCert_GetSize
  5888. #define SAC_WRITE TLSX_SignatureAlgorithmsCert_Write
  5889. #define SAC_PARSE TLSX_SignatureAlgorithmsCert_Parse
  5890. #endif /* WOLFSSL_TLS13 */
  5891. /******************************************************************************/
  5892. /* Key Share */
  5893. /******************************************************************************/
  5894. #if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
  5895. /* Create a key share entry using named Diffie-Hellman parameters group.
  5896. * Generates a key pair.
  5897. *
  5898. * ssl The SSL/TLS object.
  5899. * kse The key share entry object.
  5900. * returns 0 on success, otherwise failure.
  5901. */
  5902. static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse)
  5903. {
  5904. int ret = 0;
  5905. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  5906. word32 pSz = 0, pvtSz = 0;
  5907. DhKey* dhKey = (DhKey*)kse->key;
  5908. /* Pick the parameters from the named group. */
  5909. #ifdef HAVE_PUBLIC_FFDHE
  5910. const DhParams* params = NULL;
  5911. switch (kse->group) {
  5912. #ifdef HAVE_FFDHE_2048
  5913. case WOLFSSL_FFDHE_2048:
  5914. params = wc_Dh_ffdhe2048_Get();
  5915. pvtSz = 29;
  5916. break;
  5917. #endif
  5918. #ifdef HAVE_FFDHE_3072
  5919. case WOLFSSL_FFDHE_3072:
  5920. params = wc_Dh_ffdhe3072_Get();
  5921. pvtSz = 34;
  5922. break;
  5923. #endif
  5924. #ifdef HAVE_FFDHE_4096
  5925. case WOLFSSL_FFDHE_4096:
  5926. params = wc_Dh_ffdhe4096_Get();
  5927. pvtSz = 39;
  5928. break;
  5929. #endif
  5930. #ifdef HAVE_FFDHE_6144
  5931. case WOLFSSL_FFDHE_6144:
  5932. params = wc_Dh_ffdhe6144_Get();
  5933. pvtSz = 46;
  5934. break;
  5935. #endif
  5936. #ifdef HAVE_FFDHE_8192
  5937. case WOLFSSL_FFDHE_8192:
  5938. params = wc_Dh_ffdhe8192_Get();
  5939. pvtSz = 52;
  5940. break;
  5941. #endif
  5942. default:
  5943. break;
  5944. }
  5945. if (params == NULL)
  5946. return BAD_FUNC_ARG;
  5947. pSz = params->p_len;
  5948. #else
  5949. pvtSz = wc_DhGetNamedKeyMinSize(kse->group);
  5950. if (pvtSz == 0) {
  5951. return BAD_FUNC_ARG;
  5952. }
  5953. ret = wc_DhGetNamedKeyParamSize(kse->group, &pSz, NULL, NULL);
  5954. if (ret != 0) {
  5955. return BAD_FUNC_ARG;
  5956. }
  5957. #endif
  5958. /* Trigger Key Generation */
  5959. if (kse->pubKey == NULL || kse->privKey == NULL) {
  5960. if (kse->key == NULL) {
  5961. kse->key = (DhKey*)XMALLOC(sizeof(DhKey), ssl->heap,
  5962. DYNAMIC_TYPE_DH);
  5963. if (kse->key == NULL)
  5964. return MEMORY_E;
  5965. /* Setup Key */
  5966. ret = wc_InitDhKey_ex((DhKey*)kse->key, ssl->heap, ssl->devId);
  5967. if (ret == 0) {
  5968. dhKey = (DhKey*)kse->key;
  5969. #ifdef HAVE_PUBLIC_FFDHE
  5970. ret = wc_DhSetKey(dhKey, params->p, params->p_len, params->g,
  5971. params->g_len);
  5972. #else
  5973. ret = wc_DhSetNamedKey(dhKey, kse->group);
  5974. #endif
  5975. }
  5976. }
  5977. /* Allocate space for the private and public key */
  5978. if (ret == 0 && kse->pubKey == NULL) {
  5979. kse->pubKey = (byte*)XMALLOC(pSz, ssl->heap,
  5980. DYNAMIC_TYPE_PUBLIC_KEY);
  5981. if (kse->pubKey == NULL)
  5982. ret = MEMORY_E;
  5983. }
  5984. if (ret == 0 && kse->privKey == NULL) {
  5985. kse->privKey = (byte*)XMALLOC(pvtSz, ssl->heap,
  5986. DYNAMIC_TYPE_PRIVATE_KEY);
  5987. if (kse->privKey == NULL)
  5988. ret = MEMORY_E;
  5989. }
  5990. if (ret == 0) {
  5991. #if defined(WOLFSSL_STATIC_EPHEMERAL) && defined(WOLFSSL_DH_EXTRA)
  5992. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_DH, kse->key);
  5993. kse->pubKeyLen = pSz;
  5994. kse->keyLen = pvtSz;
  5995. if (ret == 0) {
  5996. ret = wc_DhExportKeyPair(dhKey,
  5997. (byte*)kse->privKey, &kse->keyLen, /* private */
  5998. kse->pubKey, &kse->pubKeyLen /* public */
  5999. );
  6000. }
  6001. else
  6002. #endif
  6003. {
  6004. /* Generate a new key pair */
  6005. /* For async this is called once and when event is done, the
  6006. * provided buffers will be populated.
  6007. * Final processing is zero pad below. */
  6008. kse->pubKeyLen = pSz;
  6009. kse->keyLen = pvtSz;
  6010. ret = DhGenKeyPair(ssl, dhKey,
  6011. (byte*)kse->privKey, &kse->keyLen, /* private */
  6012. kse->pubKey, &kse->pubKeyLen /* public */
  6013. );
  6014. #ifdef WOLFSSL_ASYNC_CRYPT
  6015. if (ret == WC_PENDING_E) {
  6016. return ret;
  6017. }
  6018. #endif
  6019. }
  6020. }
  6021. }
  6022. if (ret == 0) {
  6023. if (pSz != kse->pubKeyLen) {
  6024. /* Zero pad the front of the public key to match prime "p" size */
  6025. XMEMMOVE(kse->pubKey + pSz - kse->pubKeyLen, kse->pubKey,
  6026. kse->pubKeyLen);
  6027. XMEMSET(kse->pubKey, 0, pSz - kse->pubKeyLen);
  6028. kse->pubKeyLen = pSz;
  6029. }
  6030. if (pvtSz != kse->keyLen) {
  6031. /* Zero pad the front of the private key */
  6032. XMEMMOVE(kse->privKey + pvtSz - kse->keyLen, kse->privKey,
  6033. kse->keyLen);
  6034. XMEMSET(kse->privKey, 0, pvtSz - kse->keyLen);
  6035. kse->keyLen = pvtSz;
  6036. }
  6037. #ifdef WOLFSSL_DEBUG_TLS
  6038. WOLFSSL_MSG("Public DH Key");
  6039. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6040. #endif
  6041. }
  6042. /* Always release the DH key to free up memory.
  6043. * The DhKey will be setup again in TLSX_KeyShare_ProcessDh */
  6044. if (dhKey != NULL)
  6045. wc_FreeDhKey(dhKey);
  6046. if (kse->key != NULL) {
  6047. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_DH);
  6048. kse->key = NULL;
  6049. }
  6050. if (ret != 0) {
  6051. /* Cleanup on error, otherwise data owned by key share entry */
  6052. if (kse->privKey != NULL) {
  6053. XFREE(kse->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6054. kse->privKey = NULL;
  6055. }
  6056. if (kse->pubKey != NULL) {
  6057. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6058. kse->pubKey = NULL;
  6059. }
  6060. }
  6061. #else
  6062. (void)ssl;
  6063. (void)kse;
  6064. ret = NOT_COMPILED_IN;
  6065. WOLFSSL_ERROR_VERBOSE(ret);
  6066. #endif
  6067. return ret;
  6068. }
  6069. /* Create a key share entry using X25519 parameters group.
  6070. * Generates a key pair.
  6071. *
  6072. * ssl The SSL/TLS object.
  6073. * kse The key share entry object.
  6074. * returns 0 on success, otherwise failure.
  6075. */
  6076. static int TLSX_KeyShare_GenX25519Key(WOLFSSL *ssl, KeyShareEntry* kse)
  6077. {
  6078. int ret = 0;
  6079. #ifdef HAVE_CURVE25519
  6080. curve25519_key* key = (curve25519_key*)kse->key;
  6081. if (kse->key == NULL) {
  6082. /* Allocate a Curve25519 key to hold private key. */
  6083. kse->key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), ssl->heap,
  6084. DYNAMIC_TYPE_PRIVATE_KEY);
  6085. if (kse->key == NULL) {
  6086. WOLFSSL_MSG("GenX25519Key memory error");
  6087. return MEMORY_E;
  6088. }
  6089. /* Make an Curve25519 key. */
  6090. ret = wc_curve25519_init_ex((curve25519_key*)kse->key, ssl->heap,
  6091. INVALID_DEVID);
  6092. if (ret == 0) {
  6093. /* setting "key" means okay to call wc_curve25519_free */
  6094. key = (curve25519_key*)kse->key;
  6095. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6096. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE25519, kse->key);
  6097. if (ret != 0)
  6098. #endif
  6099. {
  6100. ret = wc_curve25519_make_key(ssl->rng, CURVE25519_KEYSIZE, key);
  6101. }
  6102. }
  6103. }
  6104. if (ret == 0 && kse->pubKey == NULL) {
  6105. /* Allocate space for the public key. */
  6106. kse->pubKey = (byte*)XMALLOC(CURVE25519_KEYSIZE, ssl->heap,
  6107. DYNAMIC_TYPE_PUBLIC_KEY);
  6108. if (kse->pubKey == NULL) {
  6109. WOLFSSL_MSG("GenX25519Key pub memory error");
  6110. ret = MEMORY_E;
  6111. }
  6112. }
  6113. if (ret == 0) {
  6114. /* Export Curve25519 public key. */
  6115. kse->pubKeyLen = CURVE25519_KEYSIZE;
  6116. if (wc_curve25519_export_public_ex(key, kse->pubKey, &kse->pubKeyLen,
  6117. EC25519_LITTLE_ENDIAN) != 0) {
  6118. ret = ECC_EXPORT_ERROR;
  6119. WOLFSSL_ERROR_VERBOSE(ret);
  6120. }
  6121. kse->pubKeyLen = CURVE25519_KEYSIZE; /* always CURVE25519_KEYSIZE */
  6122. }
  6123. #ifdef WOLFSSL_DEBUG_TLS
  6124. if (ret == 0) {
  6125. WOLFSSL_MSG("Public Curve25519 Key");
  6126. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6127. }
  6128. #endif
  6129. if (ret != 0) {
  6130. /* Data owned by key share entry otherwise. */
  6131. if (kse->pubKey != NULL) {
  6132. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6133. kse->pubKey = NULL;
  6134. }
  6135. if (key != NULL)
  6136. wc_curve25519_free(key);
  6137. if (kse->key != NULL) {
  6138. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6139. kse->key = NULL;
  6140. }
  6141. }
  6142. #else
  6143. (void)ssl;
  6144. (void)kse;
  6145. ret = NOT_COMPILED_IN;
  6146. WOLFSSL_ERROR_VERBOSE(ret);
  6147. #endif /* HAVE_CURVE25519 */
  6148. return ret;
  6149. }
  6150. /* Create a key share entry using X448 parameters group.
  6151. * Generates a key pair.
  6152. *
  6153. * ssl The SSL/TLS object.
  6154. * kse The key share entry object.
  6155. * returns 0 on success, otherwise failure.
  6156. */
  6157. static int TLSX_KeyShare_GenX448Key(WOLFSSL *ssl, KeyShareEntry* kse)
  6158. {
  6159. int ret = 0;
  6160. #ifdef HAVE_CURVE448
  6161. curve448_key* key = (curve448_key*)kse->key;
  6162. if (kse->key == NULL) {
  6163. /* Allocate a Curve448 key to hold private key. */
  6164. kse->key = (curve448_key*)XMALLOC(sizeof(curve448_key), ssl->heap,
  6165. DYNAMIC_TYPE_PRIVATE_KEY);
  6166. if (kse->key == NULL) {
  6167. WOLFSSL_MSG("GenX448Key memory error");
  6168. return MEMORY_E;
  6169. }
  6170. /* Make an Curve448 key. */
  6171. ret = wc_curve448_init((curve448_key*)kse->key);
  6172. if (ret == 0) {
  6173. key = (curve448_key*)kse->key;
  6174. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6175. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE448, kse->key);
  6176. if (ret != 0)
  6177. #endif
  6178. {
  6179. ret = wc_curve448_make_key(ssl->rng, CURVE448_KEY_SIZE, key);
  6180. }
  6181. }
  6182. }
  6183. if (ret == 0 && kse->pubKey == NULL) {
  6184. /* Allocate space for the public key. */
  6185. kse->pubKey = (byte*)XMALLOC(CURVE448_KEY_SIZE, ssl->heap,
  6186. DYNAMIC_TYPE_PUBLIC_KEY);
  6187. if (kse->pubKey == NULL) {
  6188. WOLFSSL_MSG("GenX448Key pub memory error");
  6189. ret = MEMORY_E;
  6190. }
  6191. }
  6192. if (ret == 0) {
  6193. /* Export Curve448 public key. */
  6194. kse->pubKeyLen = CURVE448_KEY_SIZE;
  6195. if (wc_curve448_export_public_ex(key, kse->pubKey, &kse->pubKeyLen,
  6196. EC448_LITTLE_ENDIAN) != 0) {
  6197. ret = ECC_EXPORT_ERROR;
  6198. }
  6199. kse->pubKeyLen = CURVE448_KEY_SIZE; /* always CURVE448_KEY_SIZE */
  6200. }
  6201. #ifdef WOLFSSL_DEBUG_TLS
  6202. if (ret == 0) {
  6203. WOLFSSL_MSG("Public Curve448 Key");
  6204. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6205. }
  6206. #endif
  6207. if (ret != 0) {
  6208. /* Data owned by key share entry otherwise. */
  6209. if (kse->pubKey != NULL) {
  6210. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6211. kse->pubKey = NULL;
  6212. }
  6213. if (key != NULL)
  6214. wc_curve448_free(key);
  6215. if (kse->key != NULL) {
  6216. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6217. kse->key = NULL;
  6218. }
  6219. }
  6220. #else
  6221. (void)ssl;
  6222. (void)kse;
  6223. ret = NOT_COMPILED_IN;
  6224. WOLFSSL_ERROR_VERBOSE(ret);
  6225. #endif /* HAVE_CURVE448 */
  6226. return ret;
  6227. }
  6228. /* Create a key share entry using named elliptic curve parameters group.
  6229. * Generates a key pair.
  6230. *
  6231. * ssl The SSL/TLS object.
  6232. * kse The key share entry object.
  6233. * returns 0 on success, otherwise failure.
  6234. */
  6235. static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse)
  6236. {
  6237. int ret = 0;
  6238. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  6239. word32 keySize = 0;
  6240. word16 curveId = (word16) ECC_CURVE_INVALID;
  6241. ecc_key* eccKey = (ecc_key*)kse->key;
  6242. /* TODO: [TLS13] Get key sizes using wc_ecc_get_curve_size_from_id. */
  6243. /* Translate named group to a curve id. */
  6244. switch (kse->group) {
  6245. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  6246. #ifndef NO_ECC_SECP
  6247. case WOLFSSL_ECC_SECP256R1:
  6248. curveId = ECC_SECP256R1;
  6249. keySize = 32;
  6250. break;
  6251. #endif /* !NO_ECC_SECP */
  6252. #ifdef WOLFSSL_SM2
  6253. case WOLFSSL_ECC_SM2P256V1:
  6254. curveId = ECC_SM2P256V1;
  6255. keySize = 32;
  6256. break;
  6257. #endif /* !NO_ECC_SECP */
  6258. #endif
  6259. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  6260. #ifndef NO_ECC_SECP
  6261. case WOLFSSL_ECC_SECP384R1:
  6262. curveId = ECC_SECP384R1;
  6263. keySize = 48;
  6264. break;
  6265. #endif /* !NO_ECC_SECP */
  6266. #endif
  6267. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  6268. #ifndef NO_ECC_SECP
  6269. case WOLFSSL_ECC_SECP521R1:
  6270. curveId = ECC_SECP521R1;
  6271. keySize = 66;
  6272. break;
  6273. #endif /* !NO_ECC_SECP */
  6274. #endif
  6275. default:
  6276. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  6277. return BAD_FUNC_ARG;
  6278. }
  6279. if (kse->key == NULL) {
  6280. /* Allocate an ECC key to hold private key. */
  6281. kse->key = (byte*)XMALLOC(sizeof(ecc_key), ssl->heap, DYNAMIC_TYPE_ECC);
  6282. if (kse->key == NULL) {
  6283. WOLFSSL_MSG("EccTempKey Memory error");
  6284. return MEMORY_E;
  6285. }
  6286. /* Initialize an ECC key struct for the ephemeral key */
  6287. ret = wc_ecc_init_ex((ecc_key*)kse->key, ssl->heap, ssl->devId);
  6288. if (ret == 0) {
  6289. kse->keyLen = keySize;
  6290. kse->pubKeyLen = keySize * 2 + 1;
  6291. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  6292. ret = tsip_Tls13GenEccKeyPair(ssl, kse);
  6293. if (ret != CRYPTOCB_UNAVAILABLE) {
  6294. return ret;
  6295. }
  6296. #endif
  6297. /* setting eccKey means okay to call wc_ecc_free */
  6298. eccKey = (ecc_key*)kse->key;
  6299. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6300. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_ECDH, kse->key);
  6301. if (ret != 0)
  6302. #endif
  6303. {
  6304. /* set curve info for EccMakeKey "peer" info */
  6305. ret = wc_ecc_set_curve(eccKey, kse->keyLen, curveId);
  6306. if (ret == 0) {
  6307. #ifdef WOLFSSL_ASYNC_CRYPT
  6308. /* Detect when private key generation is done */
  6309. if (ssl->error == WC_PENDING_E &&
  6310. eccKey->type == ECC_PRIVATEKEY) {
  6311. ret = 0; /* ECC Key Generation is done */
  6312. }
  6313. else
  6314. #endif
  6315. {
  6316. /* Generate ephemeral ECC key */
  6317. /* For async this is called once and when event is done, the
  6318. * provided buffers in key be populated.
  6319. * Final processing is x963 key export below. */
  6320. ret = EccMakeKey(ssl, eccKey, eccKey);
  6321. }
  6322. }
  6323. #ifdef WOLFSSL_ASYNC_CRYPT
  6324. if (ret == WC_PENDING_E)
  6325. return ret;
  6326. #endif
  6327. }
  6328. }
  6329. }
  6330. if (ret == 0 && kse->pubKey == NULL) {
  6331. /* Allocate space for the public key */
  6332. kse->pubKey = (byte*)XMALLOC(kse->pubKeyLen, ssl->heap,
  6333. DYNAMIC_TYPE_PUBLIC_KEY);
  6334. if (kse->pubKey == NULL) {
  6335. WOLFSSL_MSG("Key data Memory error");
  6336. ret = MEMORY_E;
  6337. }
  6338. }
  6339. if (ret == 0) {
  6340. XMEMSET(kse->pubKey, 0, kse->pubKeyLen);
  6341. /* Export public key. */
  6342. PRIVATE_KEY_UNLOCK();
  6343. if (wc_ecc_export_x963(eccKey, kse->pubKey, &kse->pubKeyLen) != 0) {
  6344. ret = ECC_EXPORT_ERROR;
  6345. WOLFSSL_ERROR_VERBOSE(ret);
  6346. }
  6347. PRIVATE_KEY_LOCK();
  6348. }
  6349. #ifdef WOLFSSL_DEBUG_TLS
  6350. if (ret == 0) {
  6351. WOLFSSL_MSG("Public ECC Key");
  6352. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6353. }
  6354. #endif
  6355. if (ret != 0) {
  6356. /* Cleanup on error, otherwise data owned by key share entry */
  6357. if (kse->pubKey != NULL) {
  6358. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6359. kse->pubKey = NULL;
  6360. }
  6361. if (eccKey != NULL)
  6362. wc_ecc_free(eccKey);
  6363. if (kse->key != NULL) {
  6364. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6365. kse->key = NULL;
  6366. }
  6367. }
  6368. #else
  6369. (void)ssl;
  6370. (void)kse;
  6371. ret = NOT_COMPILED_IN;
  6372. WOLFSSL_ERROR_VERBOSE(ret);
  6373. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  6374. return ret;
  6375. }
  6376. #ifdef HAVE_PQC
  6377. static int kyber_id2type(int id, int *type)
  6378. {
  6379. int ret = 0;
  6380. switch (id) {
  6381. #ifdef WOLFSSL_KYBER512
  6382. case WOLFSSL_KYBER_LEVEL1:
  6383. *type = KYBER512;
  6384. break;
  6385. #endif
  6386. #ifdef WOLFSSL_KYBER768
  6387. case WOLFSSL_KYBER_LEVEL3:
  6388. *type = KYBER768;
  6389. break;
  6390. #endif
  6391. #ifdef WOLFSSL_KYBER1024
  6392. case WOLFSSL_KYBER_LEVEL5:
  6393. *type = KYBER1024;
  6394. break;
  6395. #endif
  6396. default:
  6397. ret = NOT_COMPILED_IN;
  6398. break;
  6399. }
  6400. return ret;
  6401. }
  6402. typedef struct PqcHybridMapping {
  6403. int hybrid;
  6404. int ecc;
  6405. int pqc;
  6406. } PqcHybridMapping;
  6407. static const PqcHybridMapping pqc_hybrid_mapping[] = {
  6408. {.hybrid = WOLFSSL_P256_KYBER_LEVEL1, .ecc = WOLFSSL_ECC_SECP256R1,
  6409. .pqc = WOLFSSL_KYBER_LEVEL1},
  6410. {.hybrid = WOLFSSL_P384_KYBER_LEVEL3, .ecc = WOLFSSL_ECC_SECP384R1,
  6411. .pqc = WOLFSSL_KYBER_LEVEL3},
  6412. {.hybrid = WOLFSSL_P521_KYBER_LEVEL5, .ecc = WOLFSSL_ECC_SECP521R1,
  6413. .pqc = WOLFSSL_KYBER_LEVEL5},
  6414. {.hybrid = 0, .ecc = 0, .pqc = 0}
  6415. };
  6416. /* This will map an ecc-pqs hybrid group into its ecc group and pqc kem group.
  6417. * If it cannot find a mapping then *pqc is set to group. ecc is optional. */
  6418. static void findEccPqc(int *ecc, int *pqc, int group)
  6419. {
  6420. int i;
  6421. if (pqc == NULL) {
  6422. return;
  6423. }
  6424. *pqc = 0;
  6425. if (ecc != NULL) {
  6426. *ecc = 0;
  6427. }
  6428. for (i = 0; pqc_hybrid_mapping[i].hybrid != 0; i++) {
  6429. if (pqc_hybrid_mapping[i].hybrid == group) {
  6430. *pqc = pqc_hybrid_mapping[i].pqc;
  6431. if (ecc != NULL) {
  6432. *ecc = pqc_hybrid_mapping[i].ecc;
  6433. }
  6434. break;
  6435. }
  6436. }
  6437. if (*pqc == 0) {
  6438. /* It is not a hybrid, so maybe its simple. */
  6439. *pqc = group;
  6440. }
  6441. }
  6442. /* Create a key share entry using liboqs parameters group.
  6443. * Generates a key pair.
  6444. *
  6445. * ssl The SSL/TLS object.
  6446. * kse The key share entry object.
  6447. * returns 0 on success, otherwise failure.
  6448. */
  6449. static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse)
  6450. {
  6451. int ret = 0;
  6452. int type = 0;
  6453. KyberKey kem[1];
  6454. byte* pubKey = NULL;
  6455. byte* privKey = NULL;
  6456. KeyShareEntry *ecc_kse = NULL;
  6457. int oqs_group = 0;
  6458. int ecc_group = 0;
  6459. word32 privSz = 0;
  6460. word32 pubSz = 0;
  6461. /* This gets called twice. Once during parsing of the key share and once
  6462. * during the population of the extension. No need to do work the second
  6463. * time. Just return success if its already been done. */
  6464. if (kse->pubKey != NULL) {
  6465. return ret;
  6466. }
  6467. findEccPqc(&ecc_group, &oqs_group, kse->group);
  6468. ret = kyber_id2type(oqs_group, &type);
  6469. if (ret == NOT_COMPILED_IN) {
  6470. WOLFSSL_MSG("Invalid Kyber algorithm specified.");
  6471. ret = BAD_FUNC_ARG;
  6472. }
  6473. if (ret == 0) {
  6474. ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId);
  6475. if (ret != 0) {
  6476. WOLFSSL_MSG("Failed to initialize Kyber Key.");
  6477. }
  6478. }
  6479. if (ret == 0) {
  6480. ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap,
  6481. DYNAMIC_TYPE_TLSX);
  6482. if (ecc_kse == NULL) {
  6483. WOLFSSL_MSG("ecc_kse memory allocation failure");
  6484. ret = MEMORY_ERROR;
  6485. }
  6486. }
  6487. if (ret == 0) {
  6488. XMEMSET(ecc_kse, 0, sizeof(*ecc_kse));
  6489. ret = wc_KyberKey_PrivateKeySize(kem, &privSz);
  6490. }
  6491. if (ret == 0) {
  6492. ret = wc_KyberKey_PublicKeySize(kem, &pubSz);
  6493. }
  6494. if (ret == 0 && ecc_group != 0) {
  6495. ecc_kse->group = ecc_group;
  6496. ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse);
  6497. /* If fail, no error message, TLSX_KeyShare_GenEccKey will do it. */
  6498. }
  6499. if (ret == 0) {
  6500. pubKey = (byte*)XMALLOC(ecc_kse->pubKeyLen + pubSz, ssl->heap,
  6501. DYNAMIC_TYPE_PUBLIC_KEY);
  6502. if (pubKey == NULL) {
  6503. WOLFSSL_MSG("pubkey memory allocation failure");
  6504. ret = MEMORY_ERROR;
  6505. }
  6506. }
  6507. if (ret == 0) {
  6508. privKey = (byte*)XMALLOC(privSz, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6509. if (privKey == NULL) {
  6510. WOLFSSL_MSG("privkey memory allocation failure");
  6511. ret = MEMORY_ERROR;
  6512. }
  6513. }
  6514. if (ret == 0) {
  6515. ret = wc_KyberKey_MakeKey(kem, ssl->rng);
  6516. if (ret != 0) {
  6517. WOLFSSL_MSG("Kyber keygen failure");
  6518. }
  6519. }
  6520. if (ret == 0) {
  6521. ret = wc_KyberKey_EncodePublicKey(kem, pubKey + ecc_kse->pubKeyLen,
  6522. pubSz);
  6523. }
  6524. if (ret == 0) {
  6525. ret = wc_KyberKey_EncodePrivateKey(kem, privKey, privSz);
  6526. }
  6527. if (ret == 0) {
  6528. if (ecc_kse->pubKeyLen > 0)
  6529. XMEMCPY(pubKey, ecc_kse->pubKey, ecc_kse->pubKeyLen);
  6530. kse->pubKey = pubKey;
  6531. kse->pubKeyLen = ecc_kse->pubKeyLen + pubSz;
  6532. pubKey = NULL;
  6533. /* Note we are saving the OQS private key and ECC private key
  6534. * separately. That's because the ECC private key is not simply a
  6535. * buffer. Its is an ecc_key struct. Typically do not need the private
  6536. * key size, but will need to zero it out upon freeing. */
  6537. kse->privKey = privKey;
  6538. privKey = NULL;
  6539. kse->privKeyLen = privSz;
  6540. kse->key = ecc_kse->key;
  6541. ecc_kse->key = NULL;
  6542. }
  6543. #ifdef WOLFSSL_DEBUG_TLS
  6544. WOLFSSL_MSG("Public Kyber Key");
  6545. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen );
  6546. #endif
  6547. wc_KyberKey_Free(kem);
  6548. TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap);
  6549. if (pubKey != NULL)
  6550. XFREE(pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6551. if (privKey != NULL)
  6552. XFREE(privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6553. return ret;
  6554. }
  6555. #endif /* HAVE_PQC */
  6556. /* Generate a secret/key using the key share entry.
  6557. *
  6558. * ssl The SSL/TLS object.
  6559. * kse The key share entry holding peer data.
  6560. */
  6561. int TLSX_KeyShare_GenKey(WOLFSSL *ssl, KeyShareEntry *kse)
  6562. {
  6563. int ret;
  6564. /* Named FFDHE groups have a bit set to identify them. */
  6565. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(kse->group))
  6566. ret = TLSX_KeyShare_GenDhKey(ssl, kse);
  6567. else if (kse->group == WOLFSSL_ECC_X25519)
  6568. ret = TLSX_KeyShare_GenX25519Key(ssl, kse);
  6569. else if (kse->group == WOLFSSL_ECC_X448)
  6570. ret = TLSX_KeyShare_GenX448Key(ssl, kse);
  6571. #ifdef HAVE_PQC
  6572. else if (WOLFSSL_NAMED_GROUP_IS_PQC(kse->group))
  6573. ret = TLSX_KeyShare_GenPqcKey(ssl, kse);
  6574. #endif
  6575. else
  6576. ret = TLSX_KeyShare_GenEccKey(ssl, kse);
  6577. #ifdef WOLFSSL_ASYNC_CRYPT
  6578. kse->lastRet = ret;
  6579. #endif
  6580. return ret;
  6581. }
  6582. /* Free the key share dynamic data.
  6583. *
  6584. * list The linked list of key share entry objects.
  6585. * heap The heap used for allocation.
  6586. */
  6587. static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap)
  6588. {
  6589. KeyShareEntry* current;
  6590. while ((current = list) != NULL) {
  6591. list = current->next;
  6592. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(current->group)) {
  6593. #ifndef NO_DH
  6594. wc_FreeDhKey((DhKey*)current->key);
  6595. #endif
  6596. }
  6597. else if (current->group == WOLFSSL_ECC_X25519) {
  6598. #ifdef HAVE_CURVE25519
  6599. wc_curve25519_free((curve25519_key*)current->key);
  6600. #endif
  6601. }
  6602. else if (current->group == WOLFSSL_ECC_X448) {
  6603. #ifdef HAVE_CURVE448
  6604. wc_curve448_free((curve448_key*)current->key);
  6605. #endif
  6606. }
  6607. #ifdef HAVE_PQC
  6608. else if (WOLFSSL_NAMED_GROUP_IS_PQC(current->group)) {
  6609. if (current->key != NULL) {
  6610. ForceZero((byte*)current->key, current->keyLen);
  6611. }
  6612. if (current->pubKey != NULL) {
  6613. XFREE(current->pubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6614. current->pubKey = NULL;
  6615. }
  6616. if (current->privKey != NULL) {
  6617. ForceZero(current->privKey, current->privKeyLen);
  6618. XFREE(current->privKey, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6619. current->privKey = NULL;
  6620. }
  6621. }
  6622. #endif
  6623. else {
  6624. #ifdef HAVE_ECC
  6625. wc_ecc_free((ecc_key*)current->key);
  6626. #endif
  6627. }
  6628. XFREE(current->key, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6629. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  6630. XFREE(current->privKey, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6631. #endif
  6632. XFREE(current->pubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6633. XFREE(current->ke, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6634. XFREE(current, heap, DYNAMIC_TYPE_TLSX);
  6635. }
  6636. (void)heap;
  6637. }
  6638. /* Get the size of the encoded key share extension.
  6639. *
  6640. * list The linked list of key share extensions.
  6641. * msgType The type of the message this extension is being written into.
  6642. * returns the number of bytes of the encoded key share extension.
  6643. */
  6644. static word16 TLSX_KeyShare_GetSize(KeyShareEntry* list, byte msgType)
  6645. {
  6646. word16 len = 0;
  6647. byte isRequest = (msgType == client_hello);
  6648. KeyShareEntry* current;
  6649. /* The named group the server wants to use. */
  6650. if (msgType == hello_retry_request)
  6651. return OPAQUE16_LEN;
  6652. /* List of key exchange groups. */
  6653. if (isRequest)
  6654. len += OPAQUE16_LEN;
  6655. while ((current = list) != NULL) {
  6656. list = current->next;
  6657. if (!isRequest && current->pubKey == NULL)
  6658. continue;
  6659. len += (word16)(KE_GROUP_LEN + OPAQUE16_LEN + current->pubKeyLen);
  6660. }
  6661. return len;
  6662. }
  6663. /* Writes the key share extension into the output buffer.
  6664. * Assumes that the the output buffer is big enough to hold data.
  6665. *
  6666. * list The linked list of key share entries.
  6667. * output The buffer to write into.
  6668. * msgType The type of the message this extension is being written into.
  6669. * returns the number of bytes written into the buffer.
  6670. */
  6671. static word16 TLSX_KeyShare_Write(KeyShareEntry* list, byte* output,
  6672. byte msgType)
  6673. {
  6674. word16 i = 0;
  6675. byte isRequest = (msgType == client_hello);
  6676. KeyShareEntry* current;
  6677. if (msgType == hello_retry_request) {
  6678. c16toa(list->group, output);
  6679. return OPAQUE16_LEN;
  6680. }
  6681. /* ClientHello has a list but ServerHello is only the chosen. */
  6682. if (isRequest)
  6683. i += OPAQUE16_LEN;
  6684. /* Write out all in the list. */
  6685. while ((current = list) != NULL) {
  6686. list = current->next;
  6687. if (!isRequest && current->pubKey == NULL)
  6688. continue;
  6689. c16toa(current->group, &output[i]);
  6690. i += KE_GROUP_LEN;
  6691. c16toa((word16)(current->pubKeyLen), &output[i]);
  6692. i += OPAQUE16_LEN;
  6693. XMEMCPY(&output[i], current->pubKey, current->pubKeyLen);
  6694. i += (word16)current->pubKeyLen;
  6695. }
  6696. /* Write the length of the list if required. */
  6697. if (isRequest)
  6698. c16toa(i - OPAQUE16_LEN, output);
  6699. return i;
  6700. }
  6701. /* Process the DH key share extension on the client side.
  6702. *
  6703. * ssl The SSL/TLS object.
  6704. * keyShareEntry The key share entry object to use to calculate shared secret.
  6705. * returns 0 on success and other values indicate failure.
  6706. */
  6707. static int TLSX_KeyShare_ProcessDh(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6708. {
  6709. int ret = 0;
  6710. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  6711. word32 pSz = 0;
  6712. DhKey* dhKey = (DhKey*)keyShareEntry->key;
  6713. #ifdef HAVE_PUBLIC_FFDHE
  6714. const DhParams* params = NULL;
  6715. switch (keyShareEntry->group) {
  6716. #ifdef HAVE_FFDHE_2048
  6717. case WOLFSSL_FFDHE_2048:
  6718. params = wc_Dh_ffdhe2048_Get();
  6719. break;
  6720. #endif
  6721. #ifdef HAVE_FFDHE_3072
  6722. case WOLFSSL_FFDHE_3072:
  6723. params = wc_Dh_ffdhe3072_Get();
  6724. break;
  6725. #endif
  6726. #ifdef HAVE_FFDHE_4096
  6727. case WOLFSSL_FFDHE_4096:
  6728. params = wc_Dh_ffdhe4096_Get();
  6729. break;
  6730. #endif
  6731. #ifdef HAVE_FFDHE_6144
  6732. case WOLFSSL_FFDHE_6144:
  6733. params = wc_Dh_ffdhe6144_Get();
  6734. break;
  6735. #endif
  6736. #ifdef HAVE_FFDHE_8192
  6737. case WOLFSSL_FFDHE_8192:
  6738. params = wc_Dh_ffdhe8192_Get();
  6739. break;
  6740. #endif
  6741. default:
  6742. break;
  6743. }
  6744. if (params == NULL) {
  6745. WOLFSSL_ERROR_VERBOSE(PEER_KEY_ERROR);
  6746. return PEER_KEY_ERROR;
  6747. }
  6748. pSz = params->p_len;
  6749. #else
  6750. ret = wc_DhGetNamedKeyParamSize(keyShareEntry->group, &pSz, NULL, NULL);
  6751. if (ret != 0 || pSz == 0) {
  6752. WOLFSSL_ERROR_VERBOSE(PEER_KEY_ERROR);
  6753. return PEER_KEY_ERROR;
  6754. }
  6755. #endif
  6756. /* if DhKey is not setup, do it now */
  6757. if (keyShareEntry->key == NULL) {
  6758. keyShareEntry->key = (DhKey*)XMALLOC(sizeof(DhKey), ssl->heap,
  6759. DYNAMIC_TYPE_DH);
  6760. if (keyShareEntry->key == NULL)
  6761. return MEMORY_E;
  6762. /* Setup Key */
  6763. ret = wc_InitDhKey_ex((DhKey*)keyShareEntry->key, ssl->heap, ssl->devId);
  6764. if (ret == 0) {
  6765. dhKey = (DhKey*)keyShareEntry->key;
  6766. /* Set key */
  6767. #ifdef HAVE_PUBLIC_FFDHE
  6768. ret = wc_DhSetKey(dhKey, params->p, params->p_len, params->g,
  6769. params->g_len);
  6770. #else
  6771. ret = wc_DhSetNamedKey(dhKey, keyShareEntry->group);
  6772. #endif
  6773. }
  6774. }
  6775. if (ret == 0
  6776. #ifdef WOLFSSL_ASYNC_CRYPT
  6777. && keyShareEntry->lastRet == 0 /* don't enter here if WC_PENDING_E */
  6778. #endif
  6779. ) {
  6780. #ifdef WOLFSSL_DEBUG_TLS
  6781. WOLFSSL_MSG("Peer DH Key");
  6782. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6783. #endif
  6784. ssl->options.dhKeySz = (word16)pSz;
  6785. /* Derive secret from private key and peer's public key. */
  6786. ret = DhAgree(ssl, dhKey,
  6787. (const byte*)keyShareEntry->privKey, keyShareEntry->keyLen, /* our private */
  6788. keyShareEntry->ke, keyShareEntry->keLen, /* peer's public key */
  6789. ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz, /* secret */
  6790. NULL, 0
  6791. );
  6792. #ifdef WOLFSSL_ASYNC_CRYPT
  6793. if (ret == WC_PENDING_E) {
  6794. return ret;
  6795. }
  6796. #endif
  6797. }
  6798. /* RFC 8446 Section 7.4.1:
  6799. * ... left-padded with zeros up to the size of the prime. ...
  6800. */
  6801. if (ret == 0 && (word32)ssl->options.dhKeySz > ssl->arrays->preMasterSz) {
  6802. word32 diff = (word32)ssl->options.dhKeySz - ssl->arrays->preMasterSz;
  6803. XMEMMOVE(ssl->arrays->preMasterSecret + diff,
  6804. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  6805. XMEMSET(ssl->arrays->preMasterSecret, 0, diff);
  6806. ssl->arrays->preMasterSz = ssl->options.dhKeySz;
  6807. }
  6808. /* done with key share, release resources */
  6809. if (dhKey)
  6810. wc_FreeDhKey(dhKey);
  6811. if (keyShareEntry->key) {
  6812. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_DH);
  6813. keyShareEntry->key = NULL;
  6814. }
  6815. if (keyShareEntry->privKey != NULL) {
  6816. XFREE(keyShareEntry->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6817. keyShareEntry->privKey = NULL;
  6818. }
  6819. if (keyShareEntry->pubKey != NULL) {
  6820. XFREE(keyShareEntry->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6821. keyShareEntry->pubKey = NULL;
  6822. }
  6823. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6824. keyShareEntry->ke = NULL;
  6825. #else
  6826. (void)ssl;
  6827. (void)keyShareEntry;
  6828. ret = PEER_KEY_ERROR;
  6829. WOLFSSL_ERROR_VERBOSE(ret);
  6830. #endif
  6831. return ret;
  6832. }
  6833. /* Process the X25519 key share extension on the client side.
  6834. *
  6835. * ssl The SSL/TLS object.
  6836. * keyShareEntry The key share entry object to use to calculate shared secret.
  6837. * returns 0 on success and other values indicate failure.
  6838. */
  6839. static int TLSX_KeyShare_ProcessX25519(WOLFSSL* ssl,
  6840. KeyShareEntry* keyShareEntry)
  6841. {
  6842. int ret;
  6843. #ifdef HAVE_CURVE25519
  6844. curve25519_key* key = (curve25519_key*)keyShareEntry->key;
  6845. curve25519_key* peerX25519Key;
  6846. #ifdef HAVE_ECC
  6847. if (ssl->peerEccKey != NULL) {
  6848. wc_ecc_free(ssl->peerEccKey);
  6849. ssl->peerEccKey = NULL;
  6850. ssl->peerEccKeyPresent = 0;
  6851. }
  6852. #endif
  6853. peerX25519Key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), ssl->heap,
  6854. DYNAMIC_TYPE_TLSX);
  6855. if (peerX25519Key == NULL) {
  6856. WOLFSSL_MSG("PeerEccKey Memory error");
  6857. return MEMORY_ERROR;
  6858. }
  6859. ret = wc_curve25519_init(peerX25519Key);
  6860. if (ret != 0) {
  6861. XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6862. return ret;
  6863. }
  6864. #ifdef WOLFSSL_DEBUG_TLS
  6865. WOLFSSL_MSG("Peer Curve25519 Key");
  6866. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6867. #endif
  6868. if (wc_curve25519_check_public(keyShareEntry->ke, keyShareEntry->keLen,
  6869. EC25519_LITTLE_ENDIAN) != 0) {
  6870. ret = ECC_PEERKEY_ERROR;
  6871. WOLFSSL_ERROR_VERBOSE(ret);
  6872. }
  6873. if (ret == 0) {
  6874. if (wc_curve25519_import_public_ex(keyShareEntry->ke,
  6875. keyShareEntry->keLen, peerX25519Key,
  6876. EC25519_LITTLE_ENDIAN) != 0) {
  6877. ret = ECC_PEERKEY_ERROR;
  6878. WOLFSSL_ERROR_VERBOSE(ret);
  6879. }
  6880. }
  6881. if (ret == 0) {
  6882. ssl->ecdhCurveOID = ECC_X25519_OID;
  6883. ret = wc_curve25519_shared_secret_ex(key, peerX25519Key,
  6884. ssl->arrays->preMasterSecret,
  6885. &ssl->arrays->preMasterSz,
  6886. EC25519_LITTLE_ENDIAN);
  6887. }
  6888. wc_curve25519_free(peerX25519Key);
  6889. XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6890. wc_curve25519_free((curve25519_key*)keyShareEntry->key);
  6891. if (keyShareEntry->key != NULL) {
  6892. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6893. keyShareEntry->key = NULL;
  6894. }
  6895. #else
  6896. (void)ssl;
  6897. (void)keyShareEntry;
  6898. ret = PEER_KEY_ERROR;
  6899. WOLFSSL_ERROR_VERBOSE(ret);
  6900. #endif /* HAVE_CURVE25519 */
  6901. return ret;
  6902. }
  6903. /* Process the X448 key share extension on the client side.
  6904. *
  6905. * ssl The SSL/TLS object.
  6906. * keyShareEntry The key share entry object to use to calculate shared secret.
  6907. * returns 0 on success and other values indicate failure.
  6908. */
  6909. static int TLSX_KeyShare_ProcessX448(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6910. {
  6911. int ret;
  6912. #ifdef HAVE_CURVE448
  6913. curve448_key* key = (curve448_key*)keyShareEntry->key;
  6914. curve448_key* peerX448Key;
  6915. #ifdef HAVE_ECC
  6916. if (ssl->peerEccKey != NULL) {
  6917. wc_ecc_free(ssl->peerEccKey);
  6918. ssl->peerEccKey = NULL;
  6919. ssl->peerEccKeyPresent = 0;
  6920. }
  6921. #endif
  6922. peerX448Key = (curve448_key*)XMALLOC(sizeof(curve448_key), ssl->heap,
  6923. DYNAMIC_TYPE_TLSX);
  6924. if (peerX448Key == NULL) {
  6925. WOLFSSL_MSG("PeerEccKey Memory error");
  6926. return MEMORY_ERROR;
  6927. }
  6928. ret = wc_curve448_init(peerX448Key);
  6929. if (ret != 0) {
  6930. XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6931. return ret;
  6932. }
  6933. #ifdef WOLFSSL_DEBUG_TLS
  6934. WOLFSSL_MSG("Peer Curve448 Key");
  6935. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6936. #endif
  6937. if (wc_curve448_check_public(keyShareEntry->ke, keyShareEntry->keLen,
  6938. EC448_LITTLE_ENDIAN) != 0) {
  6939. ret = ECC_PEERKEY_ERROR;
  6940. WOLFSSL_ERROR_VERBOSE(ret);
  6941. }
  6942. if (ret == 0) {
  6943. if (wc_curve448_import_public_ex(keyShareEntry->ke,
  6944. keyShareEntry->keLen, peerX448Key,
  6945. EC448_LITTLE_ENDIAN) != 0) {
  6946. ret = ECC_PEERKEY_ERROR;
  6947. WOLFSSL_ERROR_VERBOSE(ret);
  6948. }
  6949. }
  6950. if (ret == 0) {
  6951. ssl->ecdhCurveOID = ECC_X448_OID;
  6952. ret = wc_curve448_shared_secret_ex(key, peerX448Key,
  6953. ssl->arrays->preMasterSecret,
  6954. &ssl->arrays->preMasterSz,
  6955. EC448_LITTLE_ENDIAN);
  6956. }
  6957. wc_curve448_free(peerX448Key);
  6958. XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6959. wc_curve448_free((curve448_key*)keyShareEntry->key);
  6960. if (keyShareEntry->key != NULL) {
  6961. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6962. keyShareEntry->key = NULL;
  6963. }
  6964. #else
  6965. (void)ssl;
  6966. (void)keyShareEntry;
  6967. ret = PEER_KEY_ERROR;
  6968. WOLFSSL_ERROR_VERBOSE(ret);
  6969. #endif /* HAVE_CURVE448 */
  6970. return ret;
  6971. }
  6972. /* Process the ECC key share extension on the client side.
  6973. *
  6974. * ssl The SSL/TLS object.
  6975. * keyShareEntry The key share entry object to use to calculate shared secret.
  6976. * returns 0 on success and other values indicate failure.
  6977. */
  6978. static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6979. {
  6980. int ret = 0;
  6981. #ifdef HAVE_ECC
  6982. int curveId = ECC_CURVE_INVALID;
  6983. ecc_key* eccKey = (ecc_key*)keyShareEntry->key;
  6984. /* find supported curve */
  6985. switch (keyShareEntry->group) {
  6986. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  6987. #ifndef NO_ECC_SECP
  6988. case WOLFSSL_ECC_SECP256R1:
  6989. curveId = ECC_SECP256R1;
  6990. break;
  6991. #endif /* !NO_ECC_SECP */
  6992. #ifdef WOLFSSL_SM2
  6993. case WOLFSSL_ECC_SM2P256V1:
  6994. curveId = ECC_SM2P256V1;
  6995. break;
  6996. #endif
  6997. #endif
  6998. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  6999. #ifndef NO_ECC_SECP
  7000. case WOLFSSL_ECC_SECP384R1:
  7001. curveId = ECC_SECP384R1;
  7002. break;
  7003. #endif /* !NO_ECC_SECP */
  7004. #endif
  7005. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  7006. #ifndef NO_ECC_SECP
  7007. case WOLFSSL_ECC_SECP521R1:
  7008. curveId = ECC_SECP521R1;
  7009. break;
  7010. #endif /* !NO_ECC_SECP */
  7011. #endif
  7012. #if defined(HAVE_X448) && ECC_MIN_KEY_SZ <= 448
  7013. case WOLFSSL_ECC_X448:
  7014. curveId = ECC_X448;
  7015. break;
  7016. #endif
  7017. default:
  7018. /* unsupported curve */
  7019. WOLFSSL_ERROR_VERBOSE(ECC_PEERKEY_ERROR);
  7020. return ECC_PEERKEY_ERROR;
  7021. }
  7022. #ifdef WOLFSSL_ASYNC_CRYPT
  7023. if (keyShareEntry->lastRet == 0) /* don't enter here if WC_PENDING_E */
  7024. #endif
  7025. {
  7026. #ifdef WOLFSSL_DEBUG_TLS
  7027. WOLFSSL_MSG("Peer ECC Key");
  7028. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  7029. #endif
  7030. if (ssl->peerEccKey != NULL) {
  7031. wc_ecc_free(ssl->peerEccKey);
  7032. XFREE(ssl->peerEccKey, ssl->heap, DYNAMIC_TYPE_ECC);
  7033. ssl->peerEccKeyPresent = 0;
  7034. }
  7035. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  7036. ret = tsip_Tls13GenSharedSecret(ssl, keyShareEntry);
  7037. if (ret != CRYPTOCB_UNAVAILABLE) {
  7038. return ret;
  7039. }
  7040. ret = 0;
  7041. #endif
  7042. ssl->peerEccKey = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
  7043. DYNAMIC_TYPE_ECC);
  7044. if (ssl->peerEccKey == NULL) {
  7045. WOLFSSL_MSG("PeerEccKey Memory error");
  7046. ret = MEMORY_ERROR;
  7047. }
  7048. if (ret == 0) {
  7049. ret = wc_ecc_init_ex(ssl->peerEccKey, ssl->heap, ssl->devId);
  7050. }
  7051. /* Point is validated by import function. */
  7052. if (ret == 0) {
  7053. ret = wc_ecc_import_x963_ex(keyShareEntry->ke, keyShareEntry->keLen,
  7054. ssl->peerEccKey, curveId);
  7055. if (ret != 0) {
  7056. ret = ECC_PEERKEY_ERROR;
  7057. WOLFSSL_ERROR_VERBOSE(ret);
  7058. }
  7059. }
  7060. if (ret == 0) {
  7061. ssl->ecdhCurveOID = ssl->peerEccKey->dp->oidSum;
  7062. ssl->peerEccKeyPresent = 1;
  7063. }
  7064. }
  7065. if (ret == 0 && eccKey == NULL)
  7066. ret = BAD_FUNC_ARG;
  7067. if (ret == 0) {
  7068. ret = EccSharedSecret(ssl, eccKey, ssl->peerEccKey,
  7069. keyShareEntry->ke, &keyShareEntry->keLen,
  7070. ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz,
  7071. ssl->options.side
  7072. );
  7073. #ifdef WOLFSSL_ASYNC_CRYPT
  7074. if (ret == WC_PENDING_E)
  7075. return ret;
  7076. #endif
  7077. }
  7078. /* done with key share, release resources */
  7079. if (ssl->peerEccKey != NULL
  7080. #ifdef HAVE_PK_CALLBACKS
  7081. && ssl->ctx->EccSharedSecretCb == NULL
  7082. #endif
  7083. ) {
  7084. wc_ecc_free(ssl->peerEccKey);
  7085. XFREE(ssl->peerEccKey, ssl->heap, DYNAMIC_TYPE_ECC);
  7086. ssl->peerEccKey = NULL;
  7087. ssl->peerEccKeyPresent = 0;
  7088. }
  7089. if (keyShareEntry->key) {
  7090. wc_ecc_free((ecc_key*)keyShareEntry->key);
  7091. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_ECC);
  7092. keyShareEntry->key = NULL;
  7093. }
  7094. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7095. keyShareEntry->ke = NULL;
  7096. #else
  7097. (void)ssl;
  7098. (void)keyShareEntry;
  7099. ret = PEER_KEY_ERROR;
  7100. WOLFSSL_ERROR_VERBOSE(ret);
  7101. #endif /* HAVE_ECC */
  7102. return ret;
  7103. }
  7104. #ifdef HAVE_PQC
  7105. /* Process the Kyber key share extension on the client side.
  7106. *
  7107. * ssl The SSL/TLS object.
  7108. * keyShareEntry The key share entry object to use to calculate shared secret.
  7109. * returns 0 on success and other values indicate failure.
  7110. */
  7111. static int TLSX_KeyShare_ProcessPqc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  7112. {
  7113. int ret = 0;
  7114. int type;
  7115. KyberKey kem[1];
  7116. byte* sharedSecret = NULL;
  7117. word32 sharedSecretLen = 0;
  7118. int oqs_group = 0;
  7119. int ecc_group = 0;
  7120. ecc_key eccpubkey;
  7121. word32 outlen = 0;
  7122. word32 privSz = 0;
  7123. word32 ctSz = 0;
  7124. word32 ssSz = 0;
  7125. if (keyShareEntry->ke == NULL) {
  7126. WOLFSSL_MSG("Invalid OQS algorithm specified.");
  7127. return BAD_FUNC_ARG;
  7128. }
  7129. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7130. /* I am the server, the shared secret has already been generated and
  7131. * is in keyShareEntry->ke; copy it to the pre-master secret
  7132. * pre-allocated buffer. */
  7133. if (keyShareEntry->keLen > ENCRYPT_LEN) {
  7134. WOLFSSL_MSG("shared secret is too long.");
  7135. return LENGTH_ERROR;
  7136. }
  7137. XMEMCPY(ssl->arrays->preMasterSecret, keyShareEntry->ke,
  7138. keyShareEntry->keLen);
  7139. ssl->arrays->preMasterSz = keyShareEntry->keLen;
  7140. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_SECRET)
  7141. keyShareEntry->ke = NULL;
  7142. keyShareEntry->keLen = 0;
  7143. return 0;
  7144. }
  7145. /* I am the client, the ciphertext is in keyShareEntry->ke */
  7146. findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group);
  7147. ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId);
  7148. if (ret != 0) {
  7149. WOLFSSL_MSG("Memory allocation error.");
  7150. return MEMORY_E;
  7151. }
  7152. ret = kyber_id2type(oqs_group, &type);
  7153. if (ret != 0) {
  7154. wc_ecc_free(&eccpubkey);
  7155. WOLFSSL_MSG("Invalid OQS algorithm specified.");
  7156. return BAD_FUNC_ARG;
  7157. }
  7158. ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId);
  7159. if (ret != 0) {
  7160. wc_ecc_free(&eccpubkey);
  7161. WOLFSSL_MSG("Error creating Kyber KEM");
  7162. return MEMORY_E;
  7163. }
  7164. if (ret == 0) {
  7165. ret = wc_KyberKey_SharedSecretSize(kem, &ssSz);
  7166. }
  7167. if (ret == 0) {
  7168. sharedSecretLen = ssSz;
  7169. switch (ecc_group) {
  7170. case WOLFSSL_ECC_SECP256R1:
  7171. sharedSecretLen += 32;
  7172. outlen = 32;
  7173. break;
  7174. case WOLFSSL_ECC_SECP384R1:
  7175. sharedSecretLen += 48;
  7176. outlen = 48;
  7177. break;
  7178. case WOLFSSL_ECC_SECP521R1:
  7179. sharedSecretLen += 66;
  7180. outlen = 66;
  7181. break;
  7182. default:
  7183. break;
  7184. }
  7185. }
  7186. if (ret == 0) {
  7187. sharedSecret = (byte*)XMALLOC(sharedSecretLen, ssl->heap,
  7188. DYNAMIC_TYPE_TLSX);
  7189. if (sharedSecret == NULL) {
  7190. WOLFSSL_MSG("Memory allocation error.");
  7191. ret = MEMORY_E;
  7192. }
  7193. }
  7194. if (ret == 0) {
  7195. ret = wc_KyberKey_CipherTextSize(kem, &ctSz);
  7196. }
  7197. if (ret == 0) {
  7198. ret = wc_KyberKey_PrivateKeySize(kem, &privSz);
  7199. }
  7200. if (ret == 0) {
  7201. ret = wc_KyberKey_DecodePrivateKey(kem, keyShareEntry->privKey, privSz);
  7202. }
  7203. if (ret == 0) {
  7204. ret = wc_KyberKey_Decapsulate(kem, sharedSecret + outlen,
  7205. keyShareEntry->ke + keyShareEntry->keLen - ctSz, ctSz);
  7206. if (ret != 0) {
  7207. WOLFSSL_MSG("wc_KyberKey decapsulation failure.");
  7208. ret = BAD_FUNC_ARG;
  7209. }
  7210. }
  7211. if (ecc_group != 0) {
  7212. if (ret == 0) {
  7213. /* Point is validated by import function. */
  7214. ret = wc_ecc_import_x963(keyShareEntry->ke,
  7215. keyShareEntry->keLen - ctSz,
  7216. &eccpubkey);
  7217. if (ret != 0) {
  7218. WOLFSSL_MSG("ECC Public key import error.");
  7219. }
  7220. }
  7221. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  7222. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  7223. !defined(HAVE_SELFTEST)
  7224. if (ret == 0) {
  7225. ret = wc_ecc_set_rng(keyShareEntry->key, ssl->rng);
  7226. if (ret != 0) {
  7227. WOLFSSL_MSG("Failure to set the ECC private key RNG.");
  7228. }
  7229. }
  7230. #endif
  7231. if (ret == 0) {
  7232. PRIVATE_KEY_UNLOCK();
  7233. ret = wc_ecc_shared_secret(keyShareEntry->key, &eccpubkey,
  7234. sharedSecret, &outlen);
  7235. PRIVATE_KEY_LOCK();
  7236. if (outlen != sharedSecretLen - ssSz) {
  7237. WOLFSSL_MSG("ECC shared secret derivation error.");
  7238. ret = BAD_FUNC_ARG;
  7239. }
  7240. }
  7241. }
  7242. if ((ret == 0) && (sharedSecretLen > ENCRYPT_LEN)) {
  7243. WOLFSSL_MSG("shared secret is too long.");
  7244. ret = LENGTH_ERROR;
  7245. }
  7246. if (ret == 0) {
  7247. /* Copy the shared secret to the pre-master secret pre-allocated
  7248. * buffer. */
  7249. XMEMCPY(ssl->arrays->preMasterSecret, sharedSecret, sharedSecretLen);
  7250. ssl->arrays->preMasterSz = (word32) sharedSecretLen;
  7251. }
  7252. if (sharedSecret != NULL) {
  7253. XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  7254. }
  7255. wc_ecc_free(&eccpubkey);
  7256. wc_KyberKey_Free(kem);
  7257. return ret;
  7258. }
  7259. #endif /* HAVE_PQC */
  7260. /* Process the key share extension on the client side.
  7261. *
  7262. * ssl The SSL/TLS object.
  7263. * keyShareEntry The key share entry object to use to calculate shared secret.
  7264. * returns 0 on success and other values indicate failure.
  7265. */
  7266. static int TLSX_KeyShare_Process(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  7267. {
  7268. int ret;
  7269. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  7270. ssl->session->namedGroup = keyShareEntry->group;
  7271. #endif
  7272. /* reset the pre master secret size */
  7273. if (ssl->arrays->preMasterSz == 0)
  7274. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  7275. /* Use Key Share Data from server. */
  7276. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(keyShareEntry->group))
  7277. ret = TLSX_KeyShare_ProcessDh(ssl, keyShareEntry);
  7278. else if (keyShareEntry->group == WOLFSSL_ECC_X25519)
  7279. ret = TLSX_KeyShare_ProcessX25519(ssl, keyShareEntry);
  7280. else if (keyShareEntry->group == WOLFSSL_ECC_X448)
  7281. ret = TLSX_KeyShare_ProcessX448(ssl, keyShareEntry);
  7282. #ifdef HAVE_PQC
  7283. else if (WOLFSSL_NAMED_GROUP_IS_PQC(keyShareEntry->group))
  7284. ret = TLSX_KeyShare_ProcessPqc(ssl, keyShareEntry);
  7285. #endif
  7286. else
  7287. ret = TLSX_KeyShare_ProcessEcc(ssl, keyShareEntry);
  7288. #ifdef WOLFSSL_DEBUG_TLS
  7289. if (ret == 0) {
  7290. WOLFSSL_MSG("KE Secret");
  7291. WOLFSSL_BUFFER(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  7292. }
  7293. #endif
  7294. #ifdef WOLFSSL_ASYNC_CRYPT
  7295. keyShareEntry->lastRet = ret;
  7296. #endif
  7297. return ret;
  7298. }
  7299. /* Parse an entry of the KeyShare extension.
  7300. *
  7301. * ssl The SSL/TLS object.
  7302. * input The extension data.
  7303. * length The length of the extension data.
  7304. * kse The new key share entry object.
  7305. * returns a positive number to indicate amount of data parsed and a negative
  7306. * number on error.
  7307. */
  7308. static int TLSX_KeyShareEntry_Parse(const WOLFSSL* ssl, const byte* input,
  7309. word16 length, KeyShareEntry **kse, TLSX** extensions)
  7310. {
  7311. int ret;
  7312. word16 group;
  7313. word16 keLen;
  7314. int offset = 0;
  7315. byte* ke;
  7316. if (length < OPAQUE16_LEN + OPAQUE16_LEN)
  7317. return BUFFER_ERROR;
  7318. /* Named group */
  7319. ato16(&input[offset], &group);
  7320. offset += OPAQUE16_LEN;
  7321. /* Key exchange data - public key. */
  7322. ato16(&input[offset], &keLen);
  7323. offset += OPAQUE16_LEN;
  7324. if (keLen == 0)
  7325. return INVALID_PARAMETER;
  7326. if (keLen > length - offset)
  7327. return BUFFER_ERROR;
  7328. #ifdef HAVE_PQC
  7329. if (WOLFSSL_NAMED_GROUP_IS_PQC(group) &&
  7330. ssl->options.side == WOLFSSL_SERVER_END) {
  7331. /* For KEMs, the public key is not stored. Casting away const because
  7332. * we know for KEMs, it will be read-only.*/
  7333. ke = (byte *)&input[offset];
  7334. } else
  7335. #endif
  7336. {
  7337. /* Store a copy in the key share object. */
  7338. ke = (byte*)XMALLOC(keLen, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7339. if (ke == NULL)
  7340. return MEMORY_E;
  7341. XMEMCPY(ke, &input[offset], keLen);
  7342. }
  7343. /* Populate a key share object in the extension. */
  7344. ret = TLSX_KeyShare_Use(ssl, group, keLen, ke, kse, extensions);
  7345. if (ret != 0) {
  7346. if (ke != &input[offset]) {
  7347. XFREE(ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7348. }
  7349. return ret;
  7350. }
  7351. /* Total length of the parsed data. */
  7352. return offset + keLen;
  7353. }
  7354. /* Searches the groups sent for the specified named group.
  7355. *
  7356. * ssl SSL/TLS object.
  7357. * name Group name to match.
  7358. * returns 1 when the extension has the group name and 0 otherwise.
  7359. */
  7360. static int TLSX_KeyShare_Find(WOLFSSL* ssl, word16 group)
  7361. {
  7362. TLSX* extension;
  7363. KeyShareEntry* list;
  7364. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  7365. if (extension == NULL) {
  7366. extension = TLSX_Find(ssl->ctx->extensions, TLSX_KEY_SHARE);
  7367. if (extension == NULL)
  7368. return 0;
  7369. }
  7370. list = (KeyShareEntry*)extension->data;
  7371. while (list != NULL) {
  7372. if (list->group == group)
  7373. return 1;
  7374. list = list->next;
  7375. }
  7376. return 0;
  7377. }
  7378. /* Searches the supported groups extension for the specified named group.
  7379. *
  7380. * ssl The SSL/TLS object.
  7381. * name The group name to match.
  7382. * returns 1 when the extension has the group name and 0 otherwise.
  7383. */
  7384. static int TLSX_SupportedGroups_Find(const WOLFSSL* ssl, word16 name,
  7385. TLSX* extensions)
  7386. {
  7387. #ifdef HAVE_SUPPORTED_CURVES
  7388. TLSX* extension;
  7389. SupportedCurve* curve = NULL;
  7390. if ((extension = TLSX_Find(extensions, TLSX_SUPPORTED_GROUPS)) == NULL) {
  7391. if ((extension = TLSX_Find(ssl->ctx->extensions,
  7392. TLSX_SUPPORTED_GROUPS)) == NULL) {
  7393. return 0;
  7394. }
  7395. }
  7396. for (curve = (SupportedCurve*)extension->data; curve; curve = curve->next) {
  7397. if (curve->name == name)
  7398. return 1;
  7399. }
  7400. #endif
  7401. (void)ssl;
  7402. (void)name;
  7403. return 0;
  7404. }
  7405. int TLSX_KeyShare_Parse_ClientHello(const WOLFSSL* ssl,
  7406. const byte* input, word16 length, TLSX** extensions)
  7407. {
  7408. int ret;
  7409. int offset = 0;
  7410. word16 len;
  7411. TLSX* extension;
  7412. /* Add a KeyShare extension if it doesn't exist even if peer sent no
  7413. * entries. The presence of this extension signals that the peer can be
  7414. * negotiated with. */
  7415. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7416. if (extension == NULL) {
  7417. /* Push new KeyShare extension. */
  7418. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7419. if (ret != 0)
  7420. return ret;
  7421. }
  7422. if (length < OPAQUE16_LEN)
  7423. return BUFFER_ERROR;
  7424. /* ClientHello contains zero or more key share entries. */
  7425. ato16(input, &len);
  7426. if (len != length - OPAQUE16_LEN)
  7427. return BUFFER_ERROR;
  7428. offset += OPAQUE16_LEN;
  7429. while (offset < (int)length) {
  7430. ret = TLSX_KeyShareEntry_Parse(ssl, &input[offset],
  7431. length - (word16)offset, NULL, extensions);
  7432. if (ret < 0)
  7433. return ret;
  7434. offset += ret;
  7435. }
  7436. return 0;
  7437. }
  7438. /* Parse the KeyShare extension.
  7439. * Different formats in different messages.
  7440. *
  7441. * ssl The SSL/TLS object.
  7442. * input The extension data.
  7443. * length The length of the extension data.
  7444. * msgType The type of the message this extension is being parsed from.
  7445. * returns 0 on success and other values indicate failure.
  7446. */
  7447. int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  7448. byte msgType)
  7449. {
  7450. int ret = 0;
  7451. KeyShareEntry *keyShareEntry = NULL;
  7452. word16 group;
  7453. if (msgType == client_hello) {
  7454. ret = TLSX_KeyShare_Parse_ClientHello(ssl, input, length,
  7455. &ssl->extensions);
  7456. }
  7457. else if (msgType == server_hello) {
  7458. int len;
  7459. if (length < OPAQUE16_LEN)
  7460. return BUFFER_ERROR;
  7461. /* The data is the named group the server wants to use. */
  7462. ato16(input, &group);
  7463. /* Check the selected group was supported by ClientHello extensions. */
  7464. if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) {
  7465. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7466. return BAD_KEY_SHARE_DATA;
  7467. }
  7468. /* Check if the group was sent. */
  7469. if (!TLSX_KeyShare_Find(ssl, group)) {
  7470. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7471. return BAD_KEY_SHARE_DATA;
  7472. }
  7473. /* ServerHello contains one key share entry. */
  7474. len = TLSX_KeyShareEntry_Parse(ssl, input, length, &keyShareEntry,
  7475. &ssl->extensions);
  7476. if (len != (int)length)
  7477. return BUFFER_ERROR;
  7478. /* Not in list sent if there isn't a private key. */
  7479. if (keyShareEntry == NULL || (keyShareEntry->key == NULL
  7480. #if !defined(NO_DH) || defined(HAVE_PQC)
  7481. && keyShareEntry->privKey == NULL
  7482. #endif
  7483. )) {
  7484. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7485. return BAD_KEY_SHARE_DATA;
  7486. }
  7487. /* Process the entry to calculate the secret. */
  7488. ret = TLSX_KeyShare_Process(ssl, keyShareEntry);
  7489. if (ret == 0)
  7490. ssl->session->namedGroup = ssl->namedGroup = group;
  7491. }
  7492. else if (msgType == hello_retry_request) {
  7493. if (length != OPAQUE16_LEN)
  7494. return BUFFER_ERROR;
  7495. /* The data is the named group the server wants to use. */
  7496. ato16(input, &group);
  7497. #ifdef WOLFSSL_ASYNC_CRYPT
  7498. /* only perform find and clear TLSX if not returning from async */
  7499. if (ssl->error != WC_PENDING_E)
  7500. #endif
  7501. {
  7502. /* Check the selected group was supported by ClientHello extensions. */
  7503. if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) {
  7504. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7505. return BAD_KEY_SHARE_DATA;
  7506. }
  7507. /* Check if the group was sent. */
  7508. if (TLSX_KeyShare_Find(ssl, group)) {
  7509. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7510. return BAD_KEY_SHARE_DATA;
  7511. }
  7512. /* Clear out unusable key shares. */
  7513. ret = TLSX_KeyShare_Empty(ssl);
  7514. if (ret != 0)
  7515. return ret;
  7516. }
  7517. ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL, &ssl->extensions);
  7518. if (ret == 0)
  7519. ssl->session->namedGroup = ssl->namedGroup = group;
  7520. }
  7521. else {
  7522. /* Not a message type that is allowed to have this extension. */
  7523. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  7524. return SANITY_MSG_E;
  7525. }
  7526. return ret;
  7527. }
  7528. /* Create a new key share entry and put it into the list.
  7529. *
  7530. * list The linked list of key share entries.
  7531. * group The named group.
  7532. * heap The memory to allocate with.
  7533. * keyShareEntry The new key share entry object.
  7534. * returns 0 on success and other values indicate failure.
  7535. */
  7536. static int TLSX_KeyShare_New(KeyShareEntry** list, int group, void *heap,
  7537. KeyShareEntry** keyShareEntry)
  7538. {
  7539. KeyShareEntry* kse;
  7540. KeyShareEntry** next;
  7541. kse = (KeyShareEntry*)XMALLOC(sizeof(KeyShareEntry), heap,
  7542. DYNAMIC_TYPE_TLSX);
  7543. if (kse == NULL)
  7544. return MEMORY_E;
  7545. XMEMSET(kse, 0, sizeof(*kse));
  7546. kse->group = (word16)group;
  7547. /* Add it to the back and maintain the links. */
  7548. while (*list != NULL) {
  7549. /* Assign to temporary to work around compiler bug found by customer. */
  7550. next = &((*list)->next);
  7551. list = next;
  7552. }
  7553. *list = kse;
  7554. *keyShareEntry = kse;
  7555. (void)heap;
  7556. return 0;
  7557. }
  7558. #ifdef HAVE_PQC
  7559. static int server_generate_pqc_ciphertext(WOLFSSL* ssl,
  7560. KeyShareEntry* keyShareEntry, byte* data, word16 len)
  7561. {
  7562. /* I am the server. The data parameter is the client's public key. I need
  7563. * to generate the public information (AKA ciphertext) and shared secret
  7564. * here. Note the "public information" is equivalent to a the public key in
  7565. * key exchange parlance. That's why it is being assigned to pubKey.
  7566. */
  7567. int type;
  7568. KyberKey kem[1];
  7569. byte* sharedSecret = NULL;
  7570. byte* ciphertext = NULL;
  7571. int ret = 0;
  7572. int oqs_group = 0;
  7573. int ecc_group = 0;
  7574. KeyShareEntry *ecc_kse = NULL;
  7575. ecc_key eccpubkey;
  7576. word32 outlen = 0;
  7577. word32 pubSz = 0;
  7578. word32 ctSz = 0;
  7579. word32 ssSz = 0;
  7580. findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group);
  7581. ret = kyber_id2type(oqs_group, &type);
  7582. if (ret != 0) {
  7583. WOLFSSL_MSG("Invalid Kyber algorithm specified.");
  7584. return BAD_FUNC_ARG;
  7585. }
  7586. ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId);
  7587. if (ret != 0) {
  7588. WOLFSSL_MSG("Could not do ECC public key initialization.");
  7589. return MEMORY_E;
  7590. }
  7591. ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId);
  7592. if (ret != 0) {
  7593. wc_ecc_free(&eccpubkey);
  7594. WOLFSSL_MSG("Error creating Kyber KEM");
  7595. return MEMORY_E;
  7596. }
  7597. if (ret == 0) {
  7598. ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap,
  7599. DYNAMIC_TYPE_TLSX);
  7600. if (ecc_kse == NULL) {
  7601. WOLFSSL_MSG("ecc_kse memory allocation failure");
  7602. ret = MEMORY_ERROR;
  7603. }
  7604. }
  7605. if (ret == 0) {
  7606. XMEMSET(ecc_kse, 0, sizeof(*ecc_kse));
  7607. }
  7608. if (ret == 0 && ecc_group != 0) {
  7609. ecc_kse->group = ecc_group;
  7610. ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse);
  7611. /* No message, TLSX_KeyShare_GenEccKey() will do it. */
  7612. }
  7613. if (ret == 0) {
  7614. ret = wc_KyberKey_PublicKeySize(kem, &pubSz);
  7615. }
  7616. if (ret == 0) {
  7617. ret = wc_KyberKey_CipherTextSize(kem, &ctSz);
  7618. }
  7619. if (ret == 0) {
  7620. ret = wc_KyberKey_SharedSecretSize(kem, &ssSz);
  7621. }
  7622. if (ret == 0 && len != pubSz + ecc_kse->pubKeyLen) {
  7623. WOLFSSL_MSG("Invalid public key.");
  7624. ret = BAD_FUNC_ARG;
  7625. }
  7626. if (ret == 0) {
  7627. sharedSecret = (byte*)XMALLOC(ecc_kse->keyLen + ssSz, ssl->heap,
  7628. DYNAMIC_TYPE_SECRET);
  7629. ciphertext = (byte*)XMALLOC(ecc_kse->pubKeyLen + ctSz, ssl->heap,
  7630. DYNAMIC_TYPE_TLSX);
  7631. if (sharedSecret == NULL || ciphertext == NULL) {
  7632. WOLFSSL_MSG("Ciphertext/shared secret memory allocation failure.");
  7633. ret = MEMORY_E;
  7634. }
  7635. }
  7636. if (ecc_group != 0) {
  7637. if (ret == 0) {
  7638. /* Point is validated by import function. */
  7639. ret = wc_ecc_import_x963(data, len - pubSz, &eccpubkey);
  7640. if (ret != 0) {
  7641. WOLFSSL_MSG("Bad ECC public key.");
  7642. }
  7643. }
  7644. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  7645. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  7646. !defined(HAVE_SELFTEST)
  7647. if (ret == 0) {
  7648. ret = wc_ecc_set_rng(ecc_kse->key, ssl->rng);
  7649. }
  7650. #endif
  7651. if (ret == 0) {
  7652. outlen = ecc_kse->keyLen;
  7653. PRIVATE_KEY_UNLOCK();
  7654. ret = wc_ecc_shared_secret(ecc_kse->key, &eccpubkey,
  7655. sharedSecret,
  7656. &outlen);
  7657. PRIVATE_KEY_LOCK();
  7658. if (outlen != ecc_kse->keyLen) {
  7659. WOLFSSL_MSG("Data length mismatch.");
  7660. ret = BAD_FUNC_ARG;
  7661. }
  7662. }
  7663. }
  7664. if (ret == 0) {
  7665. ret = wc_KyberKey_DecodePublicKey(kem, data + ecc_kse->pubKeyLen,
  7666. pubSz);
  7667. }
  7668. if (ret == 0) {
  7669. ret = wc_KyberKey_Encapsulate(kem, ciphertext + ecc_kse->pubKeyLen,
  7670. sharedSecret + outlen, ssl->rng);
  7671. if (ret != 0) {
  7672. WOLFSSL_MSG("wc_KyberKey encapsulation failure.");
  7673. }
  7674. }
  7675. if (ret == 0) {
  7676. if (keyShareEntry->ke != NULL) {
  7677. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7678. }
  7679. keyShareEntry->ke = sharedSecret;
  7680. keyShareEntry->keLen = outlen + ssSz;
  7681. sharedSecret = NULL;
  7682. if (ecc_kse->pubKeyLen > 0)
  7683. XMEMCPY(ciphertext, ecc_kse->pubKey, ecc_kse->pubKeyLen);
  7684. keyShareEntry->pubKey = ciphertext;
  7685. keyShareEntry->pubKeyLen = (word32)(ecc_kse->pubKeyLen + ctSz);
  7686. ciphertext = NULL;
  7687. /* Set namedGroup so wolfSSL_get_curve_name() can function properly on
  7688. * the server side. */
  7689. ssl->namedGroup = keyShareEntry->group;
  7690. }
  7691. TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap);
  7692. if (sharedSecret != NULL)
  7693. XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  7694. if (ciphertext != NULL)
  7695. XFREE(ciphertext, ssl->heap, DYNAMIC_TYPE_TLSX);
  7696. wc_ecc_free(&eccpubkey);
  7697. wc_KyberKey_Free(kem);
  7698. return ret;
  7699. }
  7700. #endif /* HAVE_PQC */
  7701. /* Use the data to create a new key share object in the extensions.
  7702. *
  7703. * ssl The SSL/TLS object.
  7704. * group The named group.
  7705. * len The length of the public key data.
  7706. * data The public key data.
  7707. * kse The new key share entry object.
  7708. * returns 0 on success and other values indicate failure.
  7709. */
  7710. int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group, word16 len, byte* data,
  7711. KeyShareEntry **kse, TLSX** extensions)
  7712. {
  7713. int ret = 0;
  7714. TLSX* extension;
  7715. KeyShareEntry* keyShareEntry = NULL;
  7716. /* Find the KeyShare extension if it exists. */
  7717. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7718. if (extension == NULL) {
  7719. /* Push new KeyShare extension. */
  7720. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7721. if (ret != 0)
  7722. return ret;
  7723. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7724. if (extension == NULL)
  7725. return MEMORY_E;
  7726. }
  7727. extension->resp = 0;
  7728. /* Try to find the key share entry with this group. */
  7729. keyShareEntry = (KeyShareEntry*)extension->data;
  7730. while (keyShareEntry != NULL) {
  7731. if (keyShareEntry->group == group)
  7732. break;
  7733. keyShareEntry = keyShareEntry->next;
  7734. }
  7735. /* Create a new key share entry if not found. */
  7736. if (keyShareEntry == NULL) {
  7737. ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, group,
  7738. ssl->heap, &keyShareEntry);
  7739. if (ret != 0)
  7740. return ret;
  7741. }
  7742. #ifdef HAVE_PQC
  7743. if (WOLFSSL_NAMED_GROUP_IS_PQC(group) &&
  7744. ssl->options.side == WOLFSSL_SERVER_END) {
  7745. ret = server_generate_pqc_ciphertext((WOLFSSL*)ssl, keyShareEntry, data,
  7746. len);
  7747. if (ret != 0)
  7748. return ret;
  7749. }
  7750. else
  7751. #endif
  7752. if (data != NULL) {
  7753. if (keyShareEntry->ke != NULL) {
  7754. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7755. }
  7756. keyShareEntry->ke = data;
  7757. keyShareEntry->keLen = len;
  7758. }
  7759. else {
  7760. /* Generate a key pair. Casting to non-const since changes inside are
  7761. * minimal but would require an extensive redesign to refactor. Also
  7762. * this path shouldn't be taken when parsing a ClientHello in stateless
  7763. * mode. */
  7764. ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, keyShareEntry);
  7765. if (ret != 0)
  7766. return ret;
  7767. }
  7768. if (kse != NULL)
  7769. *kse = keyShareEntry;
  7770. return 0;
  7771. }
  7772. /* Set an empty Key Share extension.
  7773. *
  7774. * ssl The SSL/TLS object.
  7775. * returns 0 on success and other values indicate failure.
  7776. */
  7777. int TLSX_KeyShare_Empty(WOLFSSL* ssl)
  7778. {
  7779. int ret = 0;
  7780. TLSX* extension;
  7781. /* Find the KeyShare extension if it exists. */
  7782. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  7783. if (extension == NULL) {
  7784. /* Push new KeyShare extension. */
  7785. ret = TLSX_Push(&ssl->extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7786. }
  7787. else if (extension->data != NULL) {
  7788. TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap);
  7789. extension->data = NULL;
  7790. }
  7791. return ret;
  7792. }
  7793. /* Returns whether this group is supported.
  7794. *
  7795. * namedGroup The named group to check.
  7796. * returns 1 when supported or 0 otherwise.
  7797. */
  7798. static int TLSX_KeyShare_IsSupported(int namedGroup)
  7799. {
  7800. switch (namedGroup) {
  7801. #ifdef HAVE_FFDHE_2048
  7802. case WOLFSSL_FFDHE_2048:
  7803. break;
  7804. #endif
  7805. #ifdef HAVE_FFDHE_3072
  7806. case WOLFSSL_FFDHE_3072:
  7807. break;
  7808. #endif
  7809. #ifdef HAVE_FFDHE_4096
  7810. case WOLFSSL_FFDHE_4096:
  7811. break;
  7812. #endif
  7813. #ifdef HAVE_FFDHE_6144
  7814. case WOLFSSL_FFDHE_6144:
  7815. break;
  7816. #endif
  7817. #ifdef HAVE_FFDHE_8192
  7818. case WOLFSSL_FFDHE_8192:
  7819. break;
  7820. #endif
  7821. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  7822. #ifdef HAVE_ECC_KOBLITZ
  7823. case WOLFSSL_ECC_SECP256K1:
  7824. break;
  7825. #endif
  7826. #ifndef NO_ECC_SECP
  7827. case WOLFSSL_ECC_SECP256R1:
  7828. break;
  7829. #endif /* !NO_ECC_SECP */
  7830. #ifdef HAVE_ECC_BRAINPOOL
  7831. case WOLFSSL_ECC_BRAINPOOLP256R1:
  7832. break;
  7833. #endif
  7834. #ifdef WOLFSSL_SM2
  7835. case WOLFSSL_ECC_SM2P256V1:
  7836. break;
  7837. #endif /* WOLFSSL_SM2 */
  7838. #endif
  7839. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  7840. case WOLFSSL_ECC_X25519:
  7841. break;
  7842. #endif
  7843. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  7844. case WOLFSSL_ECC_X448:
  7845. break;
  7846. #endif
  7847. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  7848. #ifndef NO_ECC_SECP
  7849. case WOLFSSL_ECC_SECP384R1:
  7850. break;
  7851. #endif /* !NO_ECC_SECP */
  7852. #ifdef HAVE_ECC_BRAINPOOL
  7853. case WOLFSSL_ECC_BRAINPOOLP384R1:
  7854. break;
  7855. #endif
  7856. #endif
  7857. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  7858. #ifndef NO_ECC_SECP
  7859. case WOLFSSL_ECC_SECP521R1:
  7860. break;
  7861. #endif /* !NO_ECC_SECP */
  7862. #endif
  7863. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  7864. #ifdef HAVE_ECC_KOBLITZ
  7865. case WOLFSSL_ECC_SECP160K1:
  7866. break;
  7867. #endif
  7868. #ifndef NO_ECC_SECP
  7869. case WOLFSSL_ECC_SECP160R1:
  7870. break;
  7871. #endif
  7872. #ifdef HAVE_ECC_SECPR2
  7873. case WOLFSSL_ECC_SECP160R2:
  7874. break;
  7875. #endif
  7876. #endif
  7877. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  7878. #ifdef HAVE_ECC_KOBLITZ
  7879. case WOLFSSL_ECC_SECP192K1:
  7880. break;
  7881. #endif
  7882. #ifndef NO_ECC_SECP
  7883. case WOLFSSL_ECC_SECP192R1:
  7884. break;
  7885. #endif
  7886. #endif
  7887. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  7888. #ifdef HAVE_ECC_KOBLITZ
  7889. case WOLFSSL_ECC_SECP224K1:
  7890. break;
  7891. #endif
  7892. #ifndef NO_ECC_SECP
  7893. case WOLFSSL_ECC_SECP224R1:
  7894. break;
  7895. #endif
  7896. #endif
  7897. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  7898. #ifdef HAVE_ECC_BRAINPOOL
  7899. case WOLFSSL_ECC_BRAINPOOLP512R1:
  7900. break;
  7901. #endif
  7902. #endif
  7903. #ifdef HAVE_PQC
  7904. #ifdef WOLFSSL_WC_KYBER
  7905. #ifdef WOLFSSL_KYBER512
  7906. case WOLFSSL_KYBER_LEVEL1:
  7907. #endif
  7908. #ifdef WOLFSSL_KYBER768
  7909. case WOLFSSL_KYBER_LEVEL3:
  7910. #endif
  7911. #ifdef WOLFSSL_KYBER1024
  7912. case WOLFSSL_KYBER_LEVEL5:
  7913. #endif
  7914. break;
  7915. #elif defined(HAVE_LIBOQS)
  7916. case WOLFSSL_KYBER_LEVEL1:
  7917. case WOLFSSL_KYBER_LEVEL3:
  7918. case WOLFSSL_KYBER_LEVEL5:
  7919. case WOLFSSL_P256_KYBER_LEVEL1:
  7920. case WOLFSSL_P384_KYBER_LEVEL3:
  7921. case WOLFSSL_P521_KYBER_LEVEL5:
  7922. {
  7923. int ret;
  7924. int id;
  7925. findEccPqc(NULL, &namedGroup, namedGroup);
  7926. ret = kyber_id2type(namedGroup, &id);
  7927. if (ret == NOT_COMPILED_IN) {
  7928. return 0;
  7929. }
  7930. if (! ext_kyber_enabled(id)) {
  7931. return 0;
  7932. }
  7933. break;
  7934. }
  7935. #elif defined(HAVE_PQM4)
  7936. case WOLFSSL_KYBER_LEVEL1:
  7937. break;
  7938. #endif
  7939. #endif /* HAVE_PQC */
  7940. default:
  7941. return 0;
  7942. }
  7943. return 1;
  7944. }
  7945. static const word16 preferredGroup[] = {
  7946. #if defined(HAVE_ECC) && (!defined(NO_ECC256) || \
  7947. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 256
  7948. WOLFSSL_ECC_SECP256R1,
  7949. #if !defined(HAVE_FIPS) && defined(WOLFSSL_SM2)
  7950. WOLFSSL_ECC_SM2P256V1,
  7951. #endif
  7952. #endif
  7953. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  7954. WOLFSSL_ECC_X25519,
  7955. #endif
  7956. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  7957. WOLFSSL_ECC_X448,
  7958. #endif
  7959. #if defined(HAVE_ECC) && (!defined(NO_ECC384) || \
  7960. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 384
  7961. WOLFSSL_ECC_SECP384R1,
  7962. #endif
  7963. #if defined(HAVE_ECC) && (!defined(NO_ECC521) || \
  7964. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 521
  7965. WOLFSSL_ECC_SECP521R1,
  7966. #endif
  7967. #if defined(HAVE_FFDHE_2048)
  7968. WOLFSSL_FFDHE_2048,
  7969. #endif
  7970. #if defined(HAVE_FFDHE_3072)
  7971. WOLFSSL_FFDHE_3072,
  7972. #endif
  7973. #if defined(HAVE_FFDHE_4096)
  7974. WOLFSSL_FFDHE_4096,
  7975. #endif
  7976. #if defined(HAVE_FFDHE_6144)
  7977. WOLFSSL_FFDHE_6144,
  7978. #endif
  7979. #if defined(HAVE_FFDHE_8192)
  7980. WOLFSSL_FFDHE_8192,
  7981. #endif
  7982. #ifdef WOLFSSL_WC_KYBER
  7983. #ifdef WOLFSSL_KYBER512
  7984. WOLFSSL_KYBER_LEVEL1,
  7985. #endif
  7986. #ifdef WOLFSSL_KYBER768
  7987. WOLFSSL_KYBER_LEVEL3,
  7988. #endif
  7989. #ifdef WOLFSSL_KYBER1024
  7990. WOLFSSL_KYBER_LEVEL5,
  7991. #endif
  7992. #elif defined(HAVE_LIBOQS)
  7993. /* These require a runtime call to TLSX_KeyShare_IsSupported to use */
  7994. WOLFSSL_KYBER_LEVEL1,
  7995. WOLFSSL_KYBER_LEVEL3,
  7996. WOLFSSL_KYBER_LEVEL5,
  7997. WOLFSSL_P256_KYBER_LEVEL1,
  7998. WOLFSSL_P384_KYBER_LEVEL3,
  7999. WOLFSSL_P521_KYBER_LEVEL5,
  8000. #elif defined(HAVE_PQM4)
  8001. WOLFSSL_KYBER_LEVEL1,
  8002. #endif
  8003. WOLFSSL_NAMED_GROUP_INVALID
  8004. };
  8005. #define PREFERRED_GROUP_SZ \
  8006. ((sizeof(preferredGroup)/sizeof(*preferredGroup)) - 1)
  8007. /* -1 for the invalid group */
  8008. /* Examines the application specified group ranking and returns the rank of the
  8009. * group.
  8010. * If no group ranking set then all groups are rank 0 (highest).
  8011. *
  8012. * ssl The SSL/TLS object.
  8013. * group The group to check ranking for.
  8014. * returns ranking from 0 to MAX_GROUP_COUNT-1 or -1 when group not in list.
  8015. */
  8016. static int TLSX_KeyShare_GroupRank(const WOLFSSL* ssl, int group)
  8017. {
  8018. byte i;
  8019. const word16* groups;
  8020. byte numGroups;
  8021. if (ssl->numGroups == 0) {
  8022. groups = preferredGroup;
  8023. numGroups = PREFERRED_GROUP_SZ;
  8024. }
  8025. else {
  8026. groups = ssl->group;
  8027. numGroups = ssl->numGroups;
  8028. }
  8029. #ifdef HAVE_LIBOQS
  8030. if (!TLSX_KeyShare_IsSupported(group))
  8031. return -1;
  8032. #endif
  8033. for (i = 0; i < numGroups; i++)
  8034. if (groups[i] == (word16)group)
  8035. return i;
  8036. return -1;
  8037. }
  8038. /* Set a key share that is supported by the client into extensions.
  8039. *
  8040. * ssl The SSL/TLS object.
  8041. * returns BAD_KEY_SHARE_DATA if no supported group has a key share,
  8042. * 0 if a supported group has a key share and other values indicate an error.
  8043. */
  8044. int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl, TLSX** extensions)
  8045. {
  8046. int ret;
  8047. #ifdef HAVE_SUPPORTED_CURVES
  8048. TLSX* extension;
  8049. SupportedCurve* curve = NULL;
  8050. SupportedCurve* preferredCurve = NULL;
  8051. KeyShareEntry* kse = NULL;
  8052. int preferredRank = WOLFSSL_MAX_GROUP_COUNT;
  8053. int rank;
  8054. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  8055. if (extension != NULL)
  8056. curve = (SupportedCurve*)extension->data;
  8057. /* Use server's preference order. */
  8058. for (; curve != NULL; curve = curve->next) {
  8059. if (!TLSX_KeyShare_IsSupported(curve->name))
  8060. continue;
  8061. if (wolfSSL_curve_is_disabled(ssl, curve->name))
  8062. continue;
  8063. rank = TLSX_KeyShare_GroupRank(ssl, curve->name);
  8064. if (rank == -1)
  8065. continue;
  8066. if (rank < preferredRank) {
  8067. preferredCurve = curve;
  8068. preferredRank = rank;
  8069. }
  8070. }
  8071. curve = preferredCurve;
  8072. if (curve == NULL) {
  8073. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  8074. return BAD_KEY_SHARE_DATA;
  8075. }
  8076. #ifdef WOLFSSL_ASYNC_CRYPT
  8077. /* Check the old key share data list. */
  8078. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  8079. if (extension != NULL) {
  8080. kse = (KeyShareEntry*)extension->data;
  8081. /* We should not be computing keys if we are only going to advertise
  8082. * our choice here. */
  8083. if (kse != NULL && kse->lastRet == WC_PENDING_E) {
  8084. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  8085. return BAD_KEY_SHARE_DATA;
  8086. }
  8087. }
  8088. #endif
  8089. /* Push new KeyShare extension. This will also free the old one */
  8090. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  8091. if (ret != 0)
  8092. return ret;
  8093. /* Extension got pushed to head */
  8094. extension = *extensions;
  8095. /* Push the selected curve */
  8096. ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, curve->name,
  8097. ssl->heap, &kse);
  8098. if (ret != 0)
  8099. return ret;
  8100. /* Set extension to be in response. */
  8101. extension->resp = 1;
  8102. #else
  8103. (void)ssl;
  8104. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  8105. ret = NOT_COMPILED_IN;
  8106. #endif
  8107. return ret;
  8108. }
  8109. #ifdef WOLFSSL_DUAL_ALG_CERTS
  8110. /* Writes the CKS objects of a list in a buffer. */
  8111. static word16 CKS_WRITE(WOLFSSL* ssl, byte* output)
  8112. {
  8113. XMEMCPY(output, ssl->sigSpec, ssl->sigSpecSz);
  8114. return ssl->sigSpecSz;
  8115. }
  8116. static int TLSX_UseCKS(TLSX** extensions, WOLFSSL* ssl, void* heap)
  8117. {
  8118. int ret = 0;
  8119. TLSX* extension;
  8120. if (extensions == NULL) {
  8121. return BAD_FUNC_ARG;
  8122. }
  8123. extension = TLSX_Find(*extensions, TLSX_CKS);
  8124. /* If it is already present, do nothing. */
  8125. if (extension == NULL) {
  8126. /* The data required is in the ssl struct, so push it in. */
  8127. ret = TLSX_Push(extensions, TLSX_CKS, (void*)ssl, heap);
  8128. }
  8129. return ret;
  8130. }
  8131. int TLSX_CKS_Set(WOLFSSL* ssl, TLSX** extensions)
  8132. {
  8133. int ret;
  8134. TLSX* extension;
  8135. /* Push new KeyShare extension. This will also free the old one */
  8136. ret = TLSX_Push(extensions, TLSX_CKS, NULL, ssl->heap);
  8137. if (ret != 0)
  8138. return ret;
  8139. /* Extension got pushed to head */
  8140. extension = *extensions;
  8141. /* Need ssl->sigSpecSz during extension length calculation. */
  8142. extension->data = ssl;
  8143. /* Set extension to be in response. */
  8144. extension->resp = 1;
  8145. return ret;
  8146. }
  8147. int TLSX_CKS_Parse(WOLFSSL* ssl, byte* input, word16 length,
  8148. TLSX** extensions)
  8149. {
  8150. (void) extensions;
  8151. int ret;
  8152. int i, j;
  8153. /* Validating the input. */
  8154. if (length == 0)
  8155. return BUFFER_ERROR;
  8156. for (i = 0; i < length; i++) {
  8157. switch (input[i])
  8158. {
  8159. case WOLFSSL_CKS_SIGSPEC_NATIVE:
  8160. case WOLFSSL_CKS_SIGSPEC_ALTERNATIVE:
  8161. case WOLFSSL_CKS_SIGSPEC_BOTH:
  8162. /* These are all valid values; do nothing */
  8163. break;
  8164. case WOLFSSL_CKS_SIGSPEC_EXTERNAL:
  8165. default:
  8166. /* All other values (including external) are not. */
  8167. return WOLFSSL_NOT_IMPLEMENTED;
  8168. }
  8169. }
  8170. /* Extension data is valid, but if we are the server and we don't have an
  8171. * alt private key, do not respond with CKS extension. */
  8172. if (wolfSSL_is_server(ssl) && ssl->buffers.altKey == NULL) {
  8173. ssl->sigSpec = NULL;
  8174. ssl->sigSpecSz = 0;
  8175. return 0;
  8176. }
  8177. /* Copy as the lifetime of input seems to be ephemeral. */
  8178. ssl->peerSigSpec = (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_TLSX);
  8179. if (ssl->peerSigSpec == NULL) {
  8180. return BUFFER_ERROR;
  8181. }
  8182. XMEMCPY(ssl->peerSigSpec, input, length);
  8183. ssl->peerSigSpecSz = length;
  8184. /* If there is no preference set, use theirs... */
  8185. if (ssl->sigSpec == NULL) {
  8186. ret = wolfSSL_UseCKS(ssl, ssl->peerSigSpec, 1);
  8187. if (ret == WOLFSSL_SUCCESS) {
  8188. ret = TLSX_UseCKS(&ssl->extensions, ssl, ssl->heap);
  8189. TLSX_SetResponse(ssl, TLSX_CKS);
  8190. }
  8191. return ret;
  8192. }
  8193. /* ...otherwise, prioritize our preference. */
  8194. for (i = 0; i < ssl->sigSpecSz; i++) {
  8195. for (j = 0; j < length; j++) {
  8196. if (ssl->sigSpec[i] == input[j]) {
  8197. /* Got the match, set to this one. */
  8198. ret = wolfSSL_UseCKS(ssl, &ssl->peerSigSpec[i], 1);
  8199. if (ret == WOLFSSL_SUCCESS) {
  8200. ret = TLSX_UseCKS(&ssl->extensions, ssl, ssl->heap);
  8201. TLSX_SetResponse(ssl, TLSX_CKS);
  8202. }
  8203. return ret;
  8204. }
  8205. }
  8206. }
  8207. /* No match found. Cannot continue. */
  8208. return MATCH_SUITE_ERROR;
  8209. }
  8210. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  8211. /* Server side KSE processing */
  8212. int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions,
  8213. byte cipherSuite0, byte cipherSuite, KeyShareEntry** kse, byte* searched)
  8214. {
  8215. TLSX* extension;
  8216. KeyShareEntry* clientKSE = NULL;
  8217. KeyShareEntry* list = NULL;
  8218. KeyShareEntry* preferredKSE = NULL;
  8219. int preferredRank = WOLFSSL_MAX_GROUP_COUNT;
  8220. int rank;
  8221. (void)cipherSuite0;
  8222. (void)cipherSuite;
  8223. if (ssl == NULL || ssl->options.side != WOLFSSL_SERVER_END)
  8224. return BAD_FUNC_ARG;
  8225. *searched = 0;
  8226. /* Find the KeyShare extension if it exists. */
  8227. extension = TLSX_Find(extensions, TLSX_KEY_SHARE);
  8228. if (extension != NULL)
  8229. list = (KeyShareEntry*)extension->data;
  8230. if (extension && extension->resp == 1) {
  8231. /* Outside of the async case this path should not be taken. */
  8232. int ret = INCOMPLETE_DATA;
  8233. #ifdef WOLFSSL_ASYNC_CRYPT
  8234. /* in async case make sure key generation is finalized */
  8235. KeyShareEntry* serverKSE = (KeyShareEntry*)extension->data;
  8236. if (serverKSE && serverKSE->lastRet == WC_PENDING_E) {
  8237. if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
  8238. *searched = 1;
  8239. ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE);
  8240. }
  8241. #endif
  8242. return ret;
  8243. }
  8244. /* Use server's preference order. */
  8245. for (clientKSE = list; clientKSE != NULL; clientKSE = clientKSE->next) {
  8246. if (clientKSE->ke == NULL)
  8247. continue;
  8248. #ifdef WOLFSSL_SM2
  8249. if ((cipherSuite0 == CIPHER_BYTE) &&
  8250. ((cipherSuite == TLS_SM4_GCM_SM3) ||
  8251. (cipherSuite == TLS_SM4_CCM_SM3))) {
  8252. if (clientKSE->group != WOLFSSL_ECC_SM2P256V1) {
  8253. continue;
  8254. }
  8255. }
  8256. else if (clientKSE->group == WOLFSSL_ECC_SM2P256V1) {
  8257. continue;
  8258. }
  8259. #endif
  8260. /* Check consistency now - extensions in any order. */
  8261. if (!TLSX_SupportedGroups_Find(ssl, clientKSE->group, extensions))
  8262. continue;
  8263. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(clientKSE->group)) {
  8264. /* Check max value supported. */
  8265. if (clientKSE->group > WOLFSSL_ECC_MAX) {
  8266. #ifdef HAVE_PQC
  8267. if (!WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group))
  8268. #endif
  8269. continue;
  8270. }
  8271. if (wolfSSL_curve_is_disabled(ssl, clientKSE->group))
  8272. continue;
  8273. }
  8274. if (!TLSX_KeyShare_IsSupported(clientKSE->group))
  8275. continue;
  8276. rank = TLSX_KeyShare_GroupRank(ssl, clientKSE->group);
  8277. if (rank == -1)
  8278. continue;
  8279. if (rank < preferredRank) {
  8280. preferredKSE = clientKSE;
  8281. preferredRank = rank;
  8282. }
  8283. }
  8284. *kse = preferredKSE;
  8285. *searched = 1;
  8286. return 0;
  8287. }
  8288. /* Server side KSE processing */
  8289. int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE)
  8290. {
  8291. int ret;
  8292. TLSX* extension;
  8293. KeyShareEntry* serverKSE;
  8294. KeyShareEntry* list = NULL;
  8295. if (ssl == NULL || ssl->options.side != WOLFSSL_SERVER_END)
  8296. return BAD_FUNC_ARG;
  8297. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  8298. if (extension == NULL)
  8299. return BAD_STATE_E;
  8300. if (clientKSE == NULL) {
  8301. #ifdef WOLFSSL_ASYNC_CRYPT
  8302. /* Not necessarily an error. The key may have already been setup. */
  8303. if (extension != NULL && extension->resp == 1) {
  8304. serverKSE = (KeyShareEntry*)extension->data;
  8305. if (serverKSE != NULL) {
  8306. /* in async case make sure key generation is finalized */
  8307. if (serverKSE->lastRet == WC_PENDING_E)
  8308. return TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE);
  8309. else if (serverKSE->lastRet == 0)
  8310. return 0;
  8311. }
  8312. }
  8313. #endif
  8314. return BAD_FUNC_ARG;
  8315. }
  8316. /* Generate a new key pair except in the case of OQS KEM because we
  8317. * are going to encapsulate and that does not require us to generate a
  8318. * key pair.
  8319. */
  8320. ret = TLSX_KeyShare_New(&list, clientKSE->group, ssl->heap, &serverKSE);
  8321. if (ret != 0)
  8322. return ret;
  8323. if (clientKSE->key == NULL) {
  8324. #ifdef HAVE_PQC
  8325. if (WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group)) {
  8326. /* Going to need the public key (AKA ciphertext). */
  8327. serverKSE->pubKey = clientKSE->pubKey;
  8328. clientKSE->pubKey = NULL;
  8329. serverKSE->pubKeyLen = clientKSE->pubKeyLen;
  8330. clientKSE->pubKeyLen = 0;
  8331. }
  8332. else
  8333. #endif
  8334. {
  8335. ret = TLSX_KeyShare_GenKey(ssl, serverKSE);
  8336. }
  8337. /* for async do setup of serverKSE below, but return WC_PENDING_E */
  8338. if (ret != 0
  8339. #ifdef WOLFSSL_ASYNC_CRYPT
  8340. && ret != WC_PENDING_E
  8341. #endif
  8342. ) {
  8343. TLSX_KeyShare_FreeAll(list, ssl->heap);
  8344. return ret;
  8345. }
  8346. }
  8347. else {
  8348. /* transfer buffers to serverKSE */
  8349. serverKSE->key = clientKSE->key;
  8350. clientKSE->key = NULL;
  8351. serverKSE->keyLen = clientKSE->keyLen;
  8352. serverKSE->pubKey = clientKSE->pubKey;
  8353. clientKSE->pubKey = NULL;
  8354. serverKSE->pubKeyLen = clientKSE->pubKeyLen;
  8355. #ifndef NO_DH
  8356. serverKSE->privKey = clientKSE->privKey;
  8357. clientKSE->privKey = NULL;
  8358. #endif
  8359. }
  8360. serverKSE->ke = clientKSE->ke;
  8361. serverKSE->keLen = clientKSE->keLen;
  8362. clientKSE->ke = NULL;
  8363. clientKSE->keLen = 0;
  8364. ssl->namedGroup = serverKSE->group;
  8365. TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap);
  8366. extension->data = (void *)serverKSE;
  8367. extension->resp = 1;
  8368. return ret;
  8369. }
  8370. /* Ensure there is a key pair that can be used for key exchange.
  8371. *
  8372. * ssl The SSL/TLS object.
  8373. * doHelloRetry If set to non-zero will do hello_retry
  8374. * returns 0 on success and other values indicate failure.
  8375. */
  8376. int TLSX_KeyShare_Establish(WOLFSSL *ssl, int* doHelloRetry)
  8377. {
  8378. int ret;
  8379. KeyShareEntry* clientKSE = NULL;
  8380. byte searched = 0;
  8381. *doHelloRetry = 0;
  8382. ret = TLSX_KeyShare_Choose(ssl, ssl->extensions, ssl->cipher.cipherSuite0,
  8383. ssl->cipher.cipherSuite, &clientKSE, &searched);
  8384. if (ret != 0 || !searched)
  8385. return ret;
  8386. /* No supported group found - send HelloRetryRequest. */
  8387. if (clientKSE == NULL) {
  8388. /* Set KEY_SHARE_ERROR to indicate HelloRetryRequest required. */
  8389. *doHelloRetry = 1;
  8390. return TLSX_KeyShare_SetSupported(ssl, &ssl->extensions);
  8391. }
  8392. return TLSX_KeyShare_Setup(ssl, clientKSE);
  8393. }
  8394. /* Derive the shared secret of the key exchange.
  8395. *
  8396. * ssl The SSL/TLS object.
  8397. * returns 0 on success and other values indicate failure.
  8398. */
  8399. int TLSX_KeyShare_DeriveSecret(WOLFSSL *ssl)
  8400. {
  8401. int ret;
  8402. TLSX* extension;
  8403. KeyShareEntry* list = NULL;
  8404. #ifdef WOLFSSL_ASYNC_CRYPT
  8405. ret = wolfSSL_AsyncPop(ssl, NULL);
  8406. /* Check for error */
  8407. if (ret != WC_NO_PENDING_E && ret < 0) {
  8408. return ret;
  8409. }
  8410. #endif
  8411. /* Find the KeyShare extension if it exists. */
  8412. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  8413. if (extension != NULL)
  8414. list = (KeyShareEntry*)extension->data;
  8415. if (list == NULL)
  8416. return KEY_SHARE_ERROR;
  8417. /* Calculate secret. */
  8418. ret = TLSX_KeyShare_Process(ssl, list);
  8419. return ret;
  8420. }
  8421. #define KS_FREE_ALL TLSX_KeyShare_FreeAll
  8422. #define KS_GET_SIZE TLSX_KeyShare_GetSize
  8423. #define KS_WRITE TLSX_KeyShare_Write
  8424. #define KS_PARSE TLSX_KeyShare_Parse
  8425. #else
  8426. #define KS_FREE_ALL(a, b) WC_DO_NOTHING
  8427. #define KS_GET_SIZE(a, b) 0
  8428. #define KS_WRITE(a, b, c) 0
  8429. #define KS_PARSE(a, b, c, d) 0
  8430. #endif /* WOLFSSL_TLS13 */
  8431. /******************************************************************************/
  8432. /* Pre-Shared Key */
  8433. /******************************************************************************/
  8434. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  8435. /* Free the pre-shared key dynamic data.
  8436. *
  8437. * list The linked list of key share entry objects.
  8438. * heap The heap used for allocation.
  8439. */
  8440. static void TLSX_PreSharedKey_FreeAll(PreSharedKey* list, void* heap)
  8441. {
  8442. PreSharedKey* current;
  8443. while ((current = list) != NULL) {
  8444. list = current->next;
  8445. XFREE(current->identity, heap, DYNAMIC_TYPE_TLSX);
  8446. XFREE(current, heap, DYNAMIC_TYPE_TLSX);
  8447. }
  8448. (void)heap;
  8449. }
  8450. /* Get the size of the encoded pre shared key extension.
  8451. *
  8452. * list The linked list of pre-shared key extensions.
  8453. * msgType The type of the message this extension is being written into.
  8454. * returns the number of bytes of the encoded pre-shared key extension or
  8455. * SANITY_MSG_E to indicate invalid message type.
  8456. */
  8457. static int TLSX_PreSharedKey_GetSize(PreSharedKey* list, byte msgType,
  8458. word16* pSz)
  8459. {
  8460. if (msgType == client_hello) {
  8461. /* Length of identities + Length of binders. */
  8462. word16 len = OPAQUE16_LEN + OPAQUE16_LEN;
  8463. while (list != NULL) {
  8464. /* Each entry has: identity, ticket age and binder. */
  8465. len += OPAQUE16_LEN + list->identityLen + OPAQUE32_LEN +
  8466. OPAQUE8_LEN + (word16)list->binderLen;
  8467. list = list->next;
  8468. }
  8469. *pSz += len;
  8470. return 0;
  8471. }
  8472. if (msgType == server_hello) {
  8473. *pSz += OPAQUE16_LEN;
  8474. return 0;
  8475. }
  8476. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8477. return SANITY_MSG_E;
  8478. }
  8479. /* The number of bytes to be written for the binders.
  8480. *
  8481. * list The linked list of pre-shared key extensions.
  8482. * msgType The type of the message this extension is being written into.
  8483. * returns the number of bytes of the encoded pre-shared key extension or
  8484. * SANITY_MSG_E to indicate invalid message type.
  8485. */
  8486. int TLSX_PreSharedKey_GetSizeBinders(PreSharedKey* list, byte msgType,
  8487. word16* pSz)
  8488. {
  8489. word16 len;
  8490. if (msgType != client_hello) {
  8491. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8492. return SANITY_MSG_E;
  8493. }
  8494. /* Length of all binders. */
  8495. len = OPAQUE16_LEN;
  8496. while (list != NULL) {
  8497. len += OPAQUE8_LEN + (word16)list->binderLen;
  8498. list = list->next;
  8499. }
  8500. *pSz = len;
  8501. return 0;
  8502. }
  8503. /* Writes the pre-shared key extension into the output buffer - binders only.
  8504. * Assumes that the the output buffer is big enough to hold data.
  8505. *
  8506. * list The linked list of key share entries.
  8507. * output The buffer to write into.
  8508. * msgType The type of the message this extension is being written into.
  8509. * returns the number of bytes written into the buffer.
  8510. */
  8511. int TLSX_PreSharedKey_WriteBinders(PreSharedKey* list, byte* output,
  8512. byte msgType, word16* pSz)
  8513. {
  8514. PreSharedKey* current = list;
  8515. word16 idx = 0;
  8516. word16 lenIdx;
  8517. word16 len;
  8518. if (msgType != client_hello) {
  8519. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8520. return SANITY_MSG_E;
  8521. }
  8522. /* Skip length of all binders. */
  8523. lenIdx = idx;
  8524. idx += OPAQUE16_LEN;
  8525. while (current != NULL) {
  8526. /* Binder data length. */
  8527. output[idx++] = (byte)current->binderLen;
  8528. /* Binder data. */
  8529. XMEMCPY(output + idx, current->binder, current->binderLen);
  8530. idx += (word16)current->binderLen;
  8531. current = current->next;
  8532. }
  8533. /* Length of the binders. */
  8534. len = idx - lenIdx - OPAQUE16_LEN;
  8535. c16toa(len, output + lenIdx);
  8536. *pSz = idx;
  8537. return 0;
  8538. }
  8539. /* Writes the pre-shared key extension into the output buffer.
  8540. * Assumes that the the output buffer is big enough to hold data.
  8541. *
  8542. * list The linked list of key share entries.
  8543. * output The buffer to write into.
  8544. * msgType The type of the message this extension is being written into.
  8545. * returns the number of bytes written into the buffer.
  8546. */
  8547. static int TLSX_PreSharedKey_Write(PreSharedKey* list, byte* output,
  8548. byte msgType, word16* pSz)
  8549. {
  8550. if (msgType == client_hello) {
  8551. PreSharedKey* current = list;
  8552. word16 idx = 0;
  8553. word16 lenIdx;
  8554. word16 len;
  8555. int ret;
  8556. /* Write identities only. Binders after HMACing over this. */
  8557. lenIdx = idx;
  8558. idx += OPAQUE16_LEN;
  8559. while (current != NULL) {
  8560. /* Identity length */
  8561. c16toa(current->identityLen, output + idx);
  8562. idx += OPAQUE16_LEN;
  8563. /* Identity data */
  8564. XMEMCPY(output + idx, current->identity, current->identityLen);
  8565. idx += current->identityLen;
  8566. /* Obfuscated ticket age. */
  8567. c32toa(current->ticketAge, output + idx);
  8568. idx += OPAQUE32_LEN;
  8569. current = current->next;
  8570. }
  8571. /* Length of the identities. */
  8572. len = idx - lenIdx - OPAQUE16_LEN;
  8573. c16toa(len, output + lenIdx);
  8574. /* Don't include binders here.
  8575. * The binders are based on the hash of all the ClientHello data up to
  8576. * and include the identities written above.
  8577. */
  8578. ret = TLSX_PreSharedKey_GetSizeBinders(list, msgType, &len);
  8579. if (ret < 0)
  8580. return ret;
  8581. *pSz += idx + len;
  8582. }
  8583. else if (msgType == server_hello) {
  8584. word16 i;
  8585. /* Find the index of the chosen identity. */
  8586. for (i=0; list != NULL && !list->chosen; i++)
  8587. list = list->next;
  8588. if (list == NULL) {
  8589. WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR);
  8590. return BUILD_MSG_ERROR;
  8591. }
  8592. /* The index of the identity chosen by the server from the list supplied
  8593. * by the client.
  8594. */
  8595. c16toa(i, output);
  8596. *pSz += OPAQUE16_LEN;
  8597. }
  8598. else {
  8599. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8600. return SANITY_MSG_E;
  8601. }
  8602. return 0;
  8603. }
  8604. int TLSX_PreSharedKey_Parse_ClientHello(TLSX** extensions, const byte* input,
  8605. word16 length, void* heap)
  8606. {
  8607. int ret;
  8608. word16 len;
  8609. word16 idx = 0;
  8610. TLSX* extension;
  8611. PreSharedKey* list;
  8612. TLSX_Remove(extensions, TLSX_PRE_SHARED_KEY, heap);
  8613. /* Length of identities and of binders. */
  8614. if ((int)(length - idx) < OPAQUE16_LEN + OPAQUE16_LEN)
  8615. return BUFFER_E;
  8616. /* Length of identities. */
  8617. ato16(input + idx, &len);
  8618. idx += OPAQUE16_LEN;
  8619. if (len < MIN_PSK_ID_LEN || length - idx < len)
  8620. return BUFFER_E;
  8621. /* Create a pre-shared key object for each identity. */
  8622. while (len > 0) {
  8623. const byte* identity;
  8624. word16 identityLen;
  8625. word32 age;
  8626. if (len < OPAQUE16_LEN)
  8627. return BUFFER_E;
  8628. /* Length of identity. */
  8629. ato16(input + idx, &identityLen);
  8630. idx += OPAQUE16_LEN;
  8631. if (len < OPAQUE16_LEN + identityLen + OPAQUE32_LEN ||
  8632. identityLen > MAX_PSK_ID_LEN)
  8633. return BUFFER_E;
  8634. /* Cache identity pointer. */
  8635. identity = input + idx;
  8636. idx += identityLen;
  8637. /* Ticket age. */
  8638. ato32(input + idx, &age);
  8639. idx += OPAQUE32_LEN;
  8640. ret = TLSX_PreSharedKey_Use(extensions, identity, identityLen, age, no_mac,
  8641. 0, 0, 1, NULL, heap);
  8642. if (ret != 0)
  8643. return ret;
  8644. /* Done with this identity. */
  8645. len -= OPAQUE16_LEN + identityLen + OPAQUE32_LEN;
  8646. }
  8647. /* Find the list of identities sent to server. */
  8648. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8649. if (extension == NULL)
  8650. return PSK_KEY_ERROR;
  8651. list = (PreSharedKey*)extension->data;
  8652. /* Length of binders. */
  8653. if (idx + OPAQUE16_LEN > length)
  8654. return BUFFER_E;
  8655. ato16(input + idx, &len);
  8656. idx += OPAQUE16_LEN;
  8657. if (len < MIN_PSK_BINDERS_LEN || length - idx < len)
  8658. return BUFFER_E;
  8659. /* Set binder for each identity. */
  8660. while (list != NULL && len > 0) {
  8661. /* Length of binder */
  8662. list->binderLen = input[idx++];
  8663. if (list->binderLen < WC_SHA256_DIGEST_SIZE ||
  8664. list->binderLen > WC_MAX_DIGEST_SIZE)
  8665. return BUFFER_E;
  8666. if (len < OPAQUE8_LEN + list->binderLen)
  8667. return BUFFER_E;
  8668. /* Copy binder into static buffer. */
  8669. XMEMCPY(list->binder, input + idx, list->binderLen);
  8670. idx += (word16)list->binderLen;
  8671. /* Done with binder entry. */
  8672. len -= OPAQUE8_LEN + (word16)list->binderLen;
  8673. /* Next identity. */
  8674. list = list->next;
  8675. }
  8676. if (list != NULL || len != 0)
  8677. return BUFFER_E;
  8678. return 0;
  8679. }
  8680. /* Parse the pre-shared key extension.
  8681. * Different formats in different messages.
  8682. *
  8683. * ssl The SSL/TLS object.
  8684. * input The extension data.
  8685. * length The length of the extension data.
  8686. * msgType The type of the message this extension is being parsed from.
  8687. * returns 0 on success and other values indicate failure.
  8688. */
  8689. static int TLSX_PreSharedKey_Parse(WOLFSSL* ssl, const byte* input,
  8690. word16 length, byte msgType)
  8691. {
  8692. if (msgType == client_hello) {
  8693. return TLSX_PreSharedKey_Parse_ClientHello(&ssl->extensions, input,
  8694. length, ssl->heap);
  8695. }
  8696. if (msgType == server_hello) {
  8697. word16 idx;
  8698. PreSharedKey* list;
  8699. TLSX* extension;
  8700. /* Index of identity chosen by server. */
  8701. if (length != OPAQUE16_LEN)
  8702. return BUFFER_E;
  8703. ato16(input, &idx);
  8704. #ifdef WOLFSSL_EARLY_DATA
  8705. ssl->options.pskIdIndex = idx + 1;
  8706. #endif
  8707. /* Find the list of identities sent to server. */
  8708. extension = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  8709. if (extension == NULL)
  8710. return PSK_KEY_ERROR;
  8711. list = (PreSharedKey*)extension->data;
  8712. /* Mark the identity as chosen. */
  8713. for (; list != NULL && idx > 0; idx--)
  8714. list = list->next;
  8715. if (list == NULL) {
  8716. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8717. return PSK_KEY_ERROR;
  8718. }
  8719. list->chosen = 1;
  8720. #ifdef HAVE_SESSION_TICKET
  8721. if (list->resumption) {
  8722. /* Check that the session's details are the same as the server's. */
  8723. if (ssl->options.cipherSuite0 != ssl->session->cipherSuite0 ||
  8724. ssl->options.cipherSuite != ssl->session->cipherSuite ||
  8725. ssl->session->version.major != ssl->ctx->method->version.major ||
  8726. ssl->session->version.minor != ssl->ctx->method->version.minor) {
  8727. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8728. return PSK_KEY_ERROR;
  8729. }
  8730. }
  8731. #endif
  8732. return 0;
  8733. }
  8734. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8735. return SANITY_MSG_E;
  8736. }
  8737. /* Create a new pre-shared key and put it into the list.
  8738. *
  8739. * list The linked list of pre-shared key.
  8740. * identity The identity.
  8741. * len The length of the identity data.
  8742. * heap The memory to allocate with.
  8743. * preSharedKey The new pre-shared key object.
  8744. * returns 0 on success and other values indicate failure.
  8745. */
  8746. static int TLSX_PreSharedKey_New(PreSharedKey** list, const byte* identity,
  8747. word16 len, void *heap,
  8748. PreSharedKey** preSharedKey)
  8749. {
  8750. PreSharedKey* psk;
  8751. PreSharedKey** next;
  8752. psk = (PreSharedKey*)XMALLOC(sizeof(PreSharedKey), heap, DYNAMIC_TYPE_TLSX);
  8753. if (psk == NULL)
  8754. return MEMORY_E;
  8755. XMEMSET(psk, 0, sizeof(*psk));
  8756. /* Make a copy of the identity data. */
  8757. psk->identity = (byte*)XMALLOC(len + NULL_TERM_LEN, heap,
  8758. DYNAMIC_TYPE_TLSX);
  8759. if (psk->identity == NULL) {
  8760. XFREE(psk, heap, DYNAMIC_TYPE_TLSX);
  8761. return MEMORY_E;
  8762. }
  8763. XMEMCPY(psk->identity, identity, len);
  8764. psk->identityLen = len;
  8765. /* Use a NULL terminator in case it is a C string */
  8766. psk->identity[psk->identityLen] = '\0';
  8767. /* Add it to the end and maintain the links. */
  8768. while (*list != NULL) {
  8769. /* Assign to temporary to work around compiler bug found by customer. */
  8770. next = &((*list)->next);
  8771. list = next;
  8772. }
  8773. *list = psk;
  8774. *preSharedKey = psk;
  8775. (void)heap;
  8776. return 0;
  8777. }
  8778. static WC_INLINE byte GetHmacLength(int hmac)
  8779. {
  8780. switch (hmac) {
  8781. #ifndef NO_SHA256
  8782. case sha256_mac:
  8783. return WC_SHA256_DIGEST_SIZE;
  8784. #endif
  8785. #ifdef WOLFSSL_SHA384
  8786. case sha384_mac:
  8787. return WC_SHA384_DIGEST_SIZE;
  8788. #endif
  8789. #ifdef WOLFSSL_SHA512
  8790. case sha512_mac:
  8791. return WC_SHA512_DIGEST_SIZE;
  8792. #endif
  8793. #ifdef WOLFSSL_SM3
  8794. case sm3_mac:
  8795. return WC_SM3_DIGEST_SIZE;
  8796. #endif
  8797. default:
  8798. break;
  8799. }
  8800. return 0;
  8801. }
  8802. /* Use the data to create a new pre-shared key object in the extensions.
  8803. *
  8804. * ssl The SSL/TLS object.
  8805. * identity The identity.
  8806. * len The length of the identity data.
  8807. * age The age of the identity.
  8808. * hmac The HMAC algorithm.
  8809. * cipherSuite0 The first byte of the cipher suite to use.
  8810. * cipherSuite The second byte of the cipher suite to use.
  8811. * resumption The PSK is for resumption of a session.
  8812. * preSharedKey The new pre-shared key object.
  8813. * returns 0 on success and other values indicate failure.
  8814. */
  8815. int TLSX_PreSharedKey_Use(TLSX** extensions, const byte* identity, word16 len,
  8816. word32 age, byte hmac, byte cipherSuite0,
  8817. byte cipherSuite, byte resumption,
  8818. PreSharedKey **preSharedKey, void* heap)
  8819. {
  8820. int ret = 0;
  8821. TLSX* extension;
  8822. PreSharedKey* psk = NULL;
  8823. /* Find the pre-shared key extension if it exists. */
  8824. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8825. if (extension == NULL) {
  8826. /* Push new pre-shared key extension. */
  8827. ret = TLSX_Push(extensions, TLSX_PRE_SHARED_KEY, NULL, heap);
  8828. if (ret != 0)
  8829. return ret;
  8830. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8831. if (extension == NULL)
  8832. return MEMORY_E;
  8833. }
  8834. /* Try to find the pre-shared key with this identity. */
  8835. psk = (PreSharedKey*)extension->data;
  8836. while (psk != NULL) {
  8837. if ((psk->identityLen == len) &&
  8838. (XMEMCMP(psk->identity, identity, len) == 0)) {
  8839. break;
  8840. }
  8841. psk = psk->next;
  8842. }
  8843. /* Create a new pre-shared key object if not found. */
  8844. if (psk == NULL) {
  8845. ret = TLSX_PreSharedKey_New((PreSharedKey**)&extension->data, identity,
  8846. len, heap, &psk);
  8847. if (ret != 0)
  8848. return ret;
  8849. }
  8850. /* Update/set age and HMAC algorithm. */
  8851. psk->ticketAge = age;
  8852. psk->hmac = hmac;
  8853. psk->cipherSuite0 = cipherSuite0;
  8854. psk->cipherSuite = cipherSuite;
  8855. psk->resumption = resumption;
  8856. psk->binderLen = GetHmacLength(psk->hmac);
  8857. if (preSharedKey != NULL)
  8858. *preSharedKey = psk;
  8859. return 0;
  8860. }
  8861. #define PSK_FREE_ALL TLSX_PreSharedKey_FreeAll
  8862. #define PSK_GET_SIZE TLSX_PreSharedKey_GetSize
  8863. #define PSK_WRITE TLSX_PreSharedKey_Write
  8864. #define PSK_PARSE TLSX_PreSharedKey_Parse
  8865. #else
  8866. #define PSK_FREE_ALL(a, b) WC_DO_NOTHING
  8867. #define PSK_GET_SIZE(a, b, c) 0
  8868. #define PSK_WRITE(a, b, c, d) 0
  8869. #define PSK_PARSE(a, b, c, d) 0
  8870. #endif
  8871. /******************************************************************************/
  8872. /* PSK Key Exchange Modes */
  8873. /******************************************************************************/
  8874. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  8875. /* Get the size of the encoded PSK KE modes extension.
  8876. * Only in ClientHello.
  8877. *
  8878. * modes The PSK KE mode bit string.
  8879. * msgType The type of the message this extension is being written into.
  8880. * returns the number of bytes of the encoded PSK KE mode extension.
  8881. */
  8882. static int TLSX_PskKeModes_GetSize(byte modes, byte msgType, word16* pSz)
  8883. {
  8884. if (msgType == client_hello) {
  8885. /* Format: Len | Modes* */
  8886. word16 len = OPAQUE8_LEN;
  8887. /* Check whether each possible mode is to be written. */
  8888. if (modes & (1 << PSK_KE))
  8889. len += OPAQUE8_LEN;
  8890. if (modes & (1 << PSK_DHE_KE))
  8891. len += OPAQUE8_LEN;
  8892. *pSz += len;
  8893. return 0;
  8894. }
  8895. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8896. return SANITY_MSG_E;
  8897. }
  8898. /* Writes the PSK KE modes extension into the output buffer.
  8899. * Assumes that the the output buffer is big enough to hold data.
  8900. * Only in ClientHello.
  8901. *
  8902. * modes The PSK KE mode bit string.
  8903. * output The buffer to write into.
  8904. * msgType The type of the message this extension is being written into.
  8905. * returns the number of bytes written into the buffer.
  8906. */
  8907. static int TLSX_PskKeModes_Write(byte modes, byte* output, byte msgType,
  8908. word16* pSz)
  8909. {
  8910. if (msgType == client_hello) {
  8911. /* Format: Len | Modes* */
  8912. word16 idx = OPAQUE8_LEN;
  8913. /* Write out each possible mode. */
  8914. if (modes & (1 << PSK_KE))
  8915. output[idx++] = PSK_KE;
  8916. if (modes & (1 << PSK_DHE_KE))
  8917. output[idx++] = PSK_DHE_KE;
  8918. /* Write out length of mode list. */
  8919. output[0] = (byte)(idx - OPAQUE8_LEN);
  8920. *pSz += idx;
  8921. return 0;
  8922. }
  8923. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8924. return SANITY_MSG_E;
  8925. }
  8926. int TLSX_PskKeyModes_Parse_Modes(const byte* input, word16 length, byte msgType,
  8927. byte* modes)
  8928. {
  8929. if (msgType == client_hello) {
  8930. /* Format: Len | Modes* */
  8931. int idx = 0;
  8932. word16 len;
  8933. *modes = 0;
  8934. /* Ensure length byte exists. */
  8935. if (length < OPAQUE8_LEN)
  8936. return BUFFER_E;
  8937. /* Get length of mode list and ensure that is the only data. */
  8938. len = input[0];
  8939. if (length - OPAQUE8_LEN != len)
  8940. return BUFFER_E;
  8941. idx = OPAQUE8_LEN;
  8942. /* Set a bit for each recognized modes. */
  8943. while (len > 0) {
  8944. /* Ignore unrecognized modes. */
  8945. if (input[idx] <= PSK_DHE_KE)
  8946. *modes |= 1 << input[idx];
  8947. idx++;
  8948. len--;
  8949. }
  8950. return 0;
  8951. }
  8952. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8953. return SANITY_MSG_E;
  8954. }
  8955. /* Parse the PSK KE modes extension.
  8956. * Only in ClientHello.
  8957. *
  8958. * ssl The SSL/TLS object.
  8959. * input The extension data.
  8960. * length The length of the extension data.
  8961. * msgType The type of the message this extension is being parsed from.
  8962. * returns 0 on success and other values indicate failure.
  8963. */
  8964. static int TLSX_PskKeModes_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  8965. byte msgType)
  8966. {
  8967. int ret;
  8968. byte modes;
  8969. ret = TLSX_PskKeyModes_Parse_Modes(input, length, msgType, &modes);
  8970. if (ret == 0)
  8971. ret = TLSX_PskKeyModes_Use(ssl, modes);
  8972. if (ret != 0) {
  8973. WOLFSSL_ERROR_VERBOSE(ret);
  8974. }
  8975. return ret;
  8976. }
  8977. /* Use the data to create a new PSK Key Exchange Modes object in the extensions.
  8978. *
  8979. * ssl The SSL/TLS object.
  8980. * modes The PSK key exchange modes.
  8981. * returns 0 on success and other values indicate failure.
  8982. */
  8983. int TLSX_PskKeyModes_Use(WOLFSSL* ssl, byte modes)
  8984. {
  8985. int ret = 0;
  8986. TLSX* extension;
  8987. /* Find the PSK key exchange modes extension if it exists. */
  8988. extension = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  8989. if (extension == NULL) {
  8990. /* Push new PSK key exchange modes extension. */
  8991. ret = TLSX_Push(&ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES, NULL,
  8992. ssl->heap);
  8993. if (ret != 0)
  8994. return ret;
  8995. extension = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  8996. if (extension == NULL)
  8997. return MEMORY_E;
  8998. }
  8999. extension->val = modes;
  9000. return 0;
  9001. }
  9002. #define PKM_GET_SIZE TLSX_PskKeModes_GetSize
  9003. #define PKM_WRITE TLSX_PskKeModes_Write
  9004. #define PKM_PARSE TLSX_PskKeModes_Parse
  9005. #else
  9006. #define PKM_GET_SIZE(a, b, c) 0
  9007. #define PKM_WRITE(a, b, c, d) 0
  9008. #define PKM_PARSE(a, b, c, d) 0
  9009. #endif
  9010. /******************************************************************************/
  9011. /* Post-Handshake Authentication */
  9012. /******************************************************************************/
  9013. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  9014. /* Get the size of the encoded Post-Handshake Authentication extension.
  9015. * Only in ClientHello.
  9016. *
  9017. * msgType The type of the message this extension is being written into.
  9018. * returns the number of bytes of the encoded Post-Handshake Authentication
  9019. * extension.
  9020. */
  9021. static int TLSX_PostHandAuth_GetSize(byte msgType, word16* pSz)
  9022. {
  9023. if (msgType == client_hello) {
  9024. *pSz += 0;
  9025. return 0;
  9026. }
  9027. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9028. return SANITY_MSG_E;
  9029. }
  9030. /* Writes the Post-Handshake Authentication extension into the output buffer.
  9031. * Assumes that the the output buffer is big enough to hold data.
  9032. * Only in ClientHello.
  9033. *
  9034. * output The buffer to write into.
  9035. * msgType The type of the message this extension is being written into.
  9036. * returns the number of bytes written into the buffer.
  9037. */
  9038. static int TLSX_PostHandAuth_Write(byte* output, byte msgType, word16* pSz)
  9039. {
  9040. (void)output;
  9041. if (msgType == client_hello) {
  9042. *pSz += 0;
  9043. return 0;
  9044. }
  9045. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9046. return SANITY_MSG_E;
  9047. }
  9048. /* Parse the Post-Handshake Authentication extension.
  9049. * Only in ClientHello.
  9050. *
  9051. * ssl The SSL/TLS object.
  9052. * input The extension data.
  9053. * length The length of the extension data.
  9054. * msgType The type of the message this extension is being parsed from.
  9055. * returns 0 on success and other values indicate failure.
  9056. */
  9057. static int TLSX_PostHandAuth_Parse(WOLFSSL* ssl, const byte* input,
  9058. word16 length, byte msgType)
  9059. {
  9060. (void)input;
  9061. if (msgType == client_hello) {
  9062. /* Ensure extension is empty. */
  9063. if (length != 0)
  9064. return BUFFER_E;
  9065. ssl->options.postHandshakeAuth = 1;
  9066. return 0;
  9067. }
  9068. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9069. return SANITY_MSG_E;
  9070. }
  9071. /* Create a new Post-handshake authentication object in the extensions.
  9072. *
  9073. * ssl The SSL/TLS object.
  9074. * returns 0 on success and other values indicate failure.
  9075. */
  9076. static int TLSX_PostHandAuth_Use(WOLFSSL* ssl)
  9077. {
  9078. int ret = 0;
  9079. TLSX* extension;
  9080. /* Find the PSK key exchange modes extension if it exists. */
  9081. extension = TLSX_Find(ssl->extensions, TLSX_POST_HANDSHAKE_AUTH);
  9082. if (extension == NULL) {
  9083. /* Push new Post-handshake Authentication extension. */
  9084. ret = TLSX_Push(&ssl->extensions, TLSX_POST_HANDSHAKE_AUTH, NULL,
  9085. ssl->heap);
  9086. if (ret != 0)
  9087. return ret;
  9088. }
  9089. return 0;
  9090. }
  9091. #define PHA_GET_SIZE TLSX_PostHandAuth_GetSize
  9092. #define PHA_WRITE TLSX_PostHandAuth_Write
  9093. #define PHA_PARSE TLSX_PostHandAuth_Parse
  9094. #else
  9095. #define PHA_GET_SIZE(a, b) 0
  9096. #define PHA_WRITE(a, b, c) 0
  9097. #define PHA_PARSE(a, b, c, d) 0
  9098. #endif
  9099. /******************************************************************************/
  9100. /* Early Data Indication */
  9101. /******************************************************************************/
  9102. #ifdef WOLFSSL_EARLY_DATA
  9103. /* Get the size of the encoded Early Data Indication extension.
  9104. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  9105. *
  9106. * msgType The type of the message this extension is being written into.
  9107. * returns the number of bytes of the encoded Early Data Indication extension.
  9108. */
  9109. static int TLSX_EarlyData_GetSize(byte msgType, word16* pSz)
  9110. {
  9111. int ret = 0;
  9112. if (msgType == client_hello || msgType == encrypted_extensions)
  9113. *pSz += 0;
  9114. else if (msgType == session_ticket)
  9115. *pSz += OPAQUE32_LEN;
  9116. else {
  9117. ret = SANITY_MSG_E;
  9118. WOLFSSL_ERROR_VERBOSE(ret);
  9119. }
  9120. return ret;
  9121. }
  9122. /* Writes the Early Data Indicator extension into the output buffer.
  9123. * Assumes that the the output buffer is big enough to hold data.
  9124. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  9125. *
  9126. * maxSz The maximum early data size.
  9127. * output The buffer to write into.
  9128. * msgType The type of the message this extension is being written into.
  9129. * returns the number of bytes written into the buffer.
  9130. */
  9131. static int TLSX_EarlyData_Write(word32 maxSz, byte* output, byte msgType,
  9132. word16* pSz)
  9133. {
  9134. if (msgType == client_hello || msgType == encrypted_extensions)
  9135. return 0;
  9136. else if (msgType == session_ticket) {
  9137. c32toa(maxSz, output);
  9138. *pSz += OPAQUE32_LEN;
  9139. return 0;
  9140. }
  9141. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9142. return SANITY_MSG_E;
  9143. }
  9144. /* Parse the Early Data Indicator extension.
  9145. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  9146. *
  9147. * ssl The SSL/TLS object.
  9148. * input The extension data.
  9149. * length The length of the extension data.
  9150. * msgType The type of the message this extension is being parsed from.
  9151. * returns 0 on success and other values indicate failure.
  9152. */
  9153. static int TLSX_EarlyData_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  9154. byte msgType)
  9155. {
  9156. WOLFSSL_ENTER("TLSX_EarlyData_Parse");
  9157. if (msgType == client_hello) {
  9158. if (length != 0)
  9159. return BUFFER_E;
  9160. if (ssl->earlyData == expecting_early_data) {
  9161. if (ssl->options.maxEarlyDataSz != 0)
  9162. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_ACCEPTED;
  9163. else
  9164. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_REJECTED;
  9165. return TLSX_EarlyData_Use(ssl, 0, 0);
  9166. }
  9167. ssl->earlyData = early_data_ext;
  9168. return 0;
  9169. }
  9170. if (msgType == encrypted_extensions) {
  9171. if (length != 0)
  9172. return BUFFER_E;
  9173. /* Ensure the index of PSK identity chosen by server is 0.
  9174. * Index is plus one to handle 'not set' value of 0.
  9175. */
  9176. if (ssl->options.pskIdIndex != 1) {
  9177. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  9178. return PSK_KEY_ERROR;
  9179. }
  9180. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  9181. /* the extension from server comes in */
  9182. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_ACCEPTED;
  9183. }
  9184. return TLSX_EarlyData_Use(ssl, 1, 1);
  9185. }
  9186. if (msgType == session_ticket) {
  9187. word32 maxSz;
  9188. if (length != OPAQUE32_LEN)
  9189. return BUFFER_E;
  9190. ato32(input, &maxSz);
  9191. ssl->session->maxEarlyDataSz = maxSz;
  9192. return 0;
  9193. }
  9194. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9195. return SANITY_MSG_E;
  9196. }
  9197. /* Use the data to create a new Early Data object in the extensions.
  9198. *
  9199. * ssl The SSL/TLS object.
  9200. * maxSz The maximum early data size.
  9201. * is_response if this extension is part of a response
  9202. * returns 0 on success and other values indicate failure.
  9203. */
  9204. int TLSX_EarlyData_Use(WOLFSSL* ssl, word32 maxSz, int is_response)
  9205. {
  9206. int ret = 0;
  9207. TLSX* extension;
  9208. /* Find the early data extension if it exists. */
  9209. extension = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  9210. if (extension == NULL) {
  9211. /* Push new early data extension. */
  9212. ret = TLSX_Push(&ssl->extensions, TLSX_EARLY_DATA, NULL, ssl->heap);
  9213. if (ret != 0)
  9214. return ret;
  9215. extension = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  9216. if (extension == NULL)
  9217. return MEMORY_E;
  9218. }
  9219. extension->resp = is_response;
  9220. /* In QUIC, earlydata size is either 0 or 0xffffffff.
  9221. * Override any size between, possibly left from our initial value */
  9222. extension->val = (WOLFSSL_IS_QUIC(ssl) && is_response && maxSz > 0) ?
  9223. WOLFSSL_MAX_32BIT : maxSz;
  9224. return 0;
  9225. }
  9226. #define EDI_GET_SIZE TLSX_EarlyData_GetSize
  9227. #define EDI_WRITE TLSX_EarlyData_Write
  9228. #define EDI_PARSE TLSX_EarlyData_Parse
  9229. #else
  9230. #define EDI_GET_SIZE(a, b) 0
  9231. #define EDI_WRITE(a, b, c, d) 0
  9232. #define EDI_PARSE(a, b, c, d) 0
  9233. #endif
  9234. /******************************************************************************/
  9235. /* QUIC transport parameter extension */
  9236. /******************************************************************************/
  9237. #ifdef WOLFSSL_QUIC
  9238. static word16 TLSX_QuicTP_GetSize(TLSX* extension)
  9239. {
  9240. const QuicTransportParam *tp = (QuicTransportParam*)extension->data;
  9241. return tp ? tp->len : 0;
  9242. }
  9243. int TLSX_QuicTP_Use(WOLFSSL* ssl, TLSX_Type ext_type, int is_response)
  9244. {
  9245. int ret = 0;
  9246. TLSX* extension;
  9247. WOLFSSL_ENTER("TLSX_QuicTP_Use");
  9248. if (ssl->quic.transport_local == NULL) {
  9249. /* RFC9000, ch 7.3: "An endpoint MUST treat the absence of [...]
  9250. * from either endpoint [...] as a connection error of type
  9251. * TRANSPORT_PARAMETER_ERROR."
  9252. */
  9253. ret = QUIC_TP_MISSING_E;
  9254. goto cleanup;
  9255. }
  9256. extension = TLSX_Find(ssl->extensions, ext_type);
  9257. if (extension == NULL) {
  9258. ret = TLSX_Push(&ssl->extensions, ext_type, NULL, ssl->heap);
  9259. if (ret != 0)
  9260. goto cleanup;
  9261. extension = TLSX_Find(ssl->extensions, ext_type);
  9262. if (extension == NULL) {
  9263. ret = MEMORY_E;
  9264. goto cleanup;
  9265. }
  9266. }
  9267. if (extension->data) {
  9268. QuicTransportParam_free((QuicTransportParam*)extension->data, ssl->heap);
  9269. extension->data = NULL;
  9270. }
  9271. extension->resp = is_response;
  9272. extension->data = (void*)QuicTransportParam_dup(ssl->quic.transport_local, ssl->heap);
  9273. if (!extension->data) {
  9274. ret = MEMORY_E;
  9275. goto cleanup;
  9276. }
  9277. cleanup:
  9278. WOLFSSL_LEAVE("TLSX_QuicTP_Use", ret);
  9279. return ret;
  9280. }
  9281. static word16 TLSX_QuicTP_Write(QuicTransportParam *tp, byte* output)
  9282. {
  9283. word16 len = 0;
  9284. WOLFSSL_ENTER("TLSX_QuicTP_Write");
  9285. if (tp && tp->len) {
  9286. XMEMCPY(output, tp->data, tp->len);
  9287. len = tp->len;
  9288. }
  9289. WOLFSSL_LEAVE("TLSX_QuicTP_Write", len);
  9290. return len;
  9291. }
  9292. static int TLSX_QuicTP_Parse(WOLFSSL *ssl, const byte *input, size_t len, int ext_type, int msgType)
  9293. {
  9294. const QuicTransportParam *tp, **ptp;
  9295. (void)msgType;
  9296. tp = QuicTransportParam_new(input, len, ssl->heap);
  9297. if (!tp) {
  9298. return MEMORY_E;
  9299. }
  9300. ptp = (ext_type == TLSX_KEY_QUIC_TP_PARAMS_DRAFT) ?
  9301. &ssl->quic.transport_peer_draft : &ssl->quic.transport_peer;
  9302. if (*ptp) {
  9303. QTP_FREE(*ptp, ssl->heap);
  9304. }
  9305. *ptp = tp;
  9306. return 0;
  9307. }
  9308. #define QTP_GET_SIZE TLSX_QuicTP_GetSize
  9309. #define QTP_USE TLSX_QuicTP_Use
  9310. #define QTP_WRITE TLSX_QuicTP_Write
  9311. #define QTP_PARSE TLSX_QuicTP_Parse
  9312. #endif /* WOLFSSL_QUIC */
  9313. #if defined(WOLFSSL_DTLS_CID)
  9314. #define CID_GET_SIZE TLSX_ConnectionID_GetSize
  9315. #define CID_WRITE TLSX_ConnectionID_Write
  9316. #define CID_PARSE TLSX_ConnectionID_Parse
  9317. #define CID_FREE TLSX_ConnectionID_Free
  9318. #else
  9319. #define CID_GET_SIZE(a) 0
  9320. #define CID_WRITE(a, b) 0
  9321. #define CID_PARSE(a, b, c, d) 0
  9322. #define CID_FREE(a, b) 0
  9323. #endif /* defined(WOLFSSL_DTLS_CID) */
  9324. #if defined(HAVE_RPK)
  9325. /******************************************************************************/
  9326. /* Client_Certificate_Type extension */
  9327. /******************************************************************************/
  9328. /* return 1 if specified type is included in the given list, otherwise 0 */
  9329. static int IsCertTypeListed(byte type, byte cnt, const byte* list)
  9330. {
  9331. int ret = 0;
  9332. int i;
  9333. if (cnt == 0 || list == NULL)
  9334. return ret;
  9335. if (cnt > 0 && cnt <= MAX_CLIENT_CERT_TYPE_CNT) {
  9336. for (i = 0; i < cnt; i++) {
  9337. if (list[i] == type)
  9338. return 1;
  9339. }
  9340. }
  9341. return 0;
  9342. }
  9343. /* Search both arrays from above to find a common value between the two given
  9344. * arrays(a and b). return 1 if it finds a common value, otherwise return 0.
  9345. */
  9346. static int GetCommonItem(const byte* a, byte aLen, const byte* b, byte bLen,
  9347. byte* type)
  9348. {
  9349. int i, j;
  9350. if (a == NULL || b == NULL)
  9351. return 0;
  9352. for (i = 0; i < aLen; i++) {
  9353. for (j = 0; j < bLen; j++) {
  9354. if (a[i] == b[j]) {
  9355. *type = a[i];
  9356. return 1;
  9357. }
  9358. }
  9359. }
  9360. return 0;
  9361. }
  9362. /* Creates a "client certificate type" extension if necessary.
  9363. * Returns 0 if no error occurred, negative value otherwise.
  9364. * A return of 0, it does not indicae that the extension was created.
  9365. */
  9366. static int TLSX_ClientCertificateType_Use(WOLFSSL* ssl, byte isServer)
  9367. {
  9368. int ret = 0;
  9369. if (ssl == NULL)
  9370. return BAD_FUNC_ARG;
  9371. if (isServer) {
  9372. /* [in server side]
  9373. */
  9374. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_RPK,
  9375. ssl->options.rpkConfig.preferred_ClientCertTypeCnt,
  9376. ssl->options.rpkConfig.preferred_ClientCertTypes)) {
  9377. WOLFSSL_MSG("Adding Client Certificate Type extension");
  9378. ret = TLSX_Push(&ssl->extensions, TLSX_CLIENT_CERTIFICATE_TYPE, ssl,
  9379. ssl->heap);
  9380. if (ret == 0) {
  9381. TLSX_SetResponse(ssl, TLSX_CLIENT_CERTIFICATE_TYPE);
  9382. }
  9383. }
  9384. }
  9385. else {
  9386. /* [in client side]
  9387. * This extension MUST be omitted from the ClientHello unless the RPK
  9388. * certificate is preferred by the user and actually loaded.
  9389. */
  9390. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_RPK,
  9391. ssl->options.rpkConfig.preferred_ClientCertTypeCnt,
  9392. ssl->options.rpkConfig.preferred_ClientCertTypes)) {
  9393. if (ssl->options.rpkState.isRPKLoaded) {
  9394. ssl->options.rpkState.sending_ClientCertTypeCnt = 1;
  9395. ssl->options.rpkState.sending_ClientCertTypes[0] =
  9396. WOLFSSL_CERT_TYPE_RPK;
  9397. /* Push new client_certificate_type extension. */
  9398. WOLFSSL_MSG("Adding Client Certificate Type extension");
  9399. ret = TLSX_Push(&ssl->extensions, TLSX_CLIENT_CERTIFICATE_TYPE,
  9400. ssl, ssl->heap);
  9401. }
  9402. else {
  9403. WOLFSSL_MSG("Willing to use RPK cert but not loaded it");
  9404. }
  9405. }
  9406. else {
  9407. WOLFSSL_MSG("No will to use RPK cert");
  9408. }
  9409. }
  9410. return ret;
  9411. }
  9412. /* Parse a "client certificate type" extension received from peer.
  9413. * returns 0 on success and other values indicate failure.
  9414. */
  9415. static int TLSX_ClientCertificateType_Parse(WOLFSSL* ssl, const byte* input,
  9416. word16 length, byte msgType)
  9417. {
  9418. byte typeCnt;
  9419. int idx = 0;
  9420. int ret = 0;
  9421. int i;
  9422. int populate = 0;
  9423. byte cmnType;
  9424. if (msgType == client_hello) {
  9425. /* [parse ClientHello in server end]
  9426. * case 1) if peer verify is disabled, this extension must be omitted
  9427. * from ServerHello.
  9428. * case 2) if user have not set his preference, find X509 in parsed
  9429. * result, then populate "Client Certificate Type" extension.
  9430. * case 3) if user have not set his preference and X509 isn't included
  9431. * in parsed result, send "unsupported certificate" alert.
  9432. * case 4) if user have set his preference, find a common cert type
  9433. * in users preference and received cert types.
  9434. * case 5) if user have set his preference, but no common cert type
  9435. * found.
  9436. */
  9437. /* case 1 */
  9438. if (ssl->options.verifyNone) {
  9439. return ret;
  9440. }
  9441. /* parse extension */
  9442. if (length < OPAQUE8_LEN)
  9443. return BUFFER_E;
  9444. typeCnt = input[idx];
  9445. if (typeCnt > MAX_CLIENT_CERT_TYPE_CNT)
  9446. return BUFFER_E;
  9447. if ((typeCnt + 1) * OPAQUE8_LEN != length){
  9448. return BUFFER_E;
  9449. }
  9450. ssl->options.rpkState.received_ClientCertTypeCnt = input[idx];
  9451. idx += OPAQUE8_LEN;
  9452. for (i = 0; i < typeCnt; i++) {
  9453. ssl->options.rpkState.received_ClientCertTypes[i] = input[idx];
  9454. idx += OPAQUE8_LEN;
  9455. }
  9456. if (ssl->options.rpkConfig.preferred_ClientCertTypeCnt == 0) {
  9457. /* case 2 */
  9458. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_X509,
  9459. ssl->options.rpkState.received_ClientCertTypeCnt,
  9460. ssl->options.rpkState.received_ClientCertTypes)) {
  9461. ssl->options.rpkState.sending_ClientCertTypeCnt = 1;
  9462. ssl->options.rpkState.sending_ClientCertTypes[0] =
  9463. WOLFSSL_CERT_TYPE_X509;
  9464. populate = 1;
  9465. }
  9466. /* case 3 */
  9467. else {
  9468. WOLFSSL_MSG("No common cert type found in client_certificate_type ext");
  9469. SendAlert(ssl, alert_fatal, unsupported_certificate);
  9470. return UNSUPPORTED_CERTIFICATE;
  9471. }
  9472. }
  9473. else if (ssl->options.rpkConfig.preferred_ClientCertTypeCnt > 0) {
  9474. /* case 4 */
  9475. if (GetCommonItem(
  9476. ssl->options.rpkConfig.preferred_ClientCertTypes,
  9477. ssl->options.rpkConfig.preferred_ClientCertTypeCnt,
  9478. ssl->options.rpkState.received_ClientCertTypes,
  9479. ssl->options.rpkState.received_ClientCertTypeCnt,
  9480. &cmnType)) {
  9481. ssl->options.rpkState.sending_ClientCertTypeCnt = 1;
  9482. ssl->options.rpkState.sending_ClientCertTypes[0] = cmnType;
  9483. populate = 1;
  9484. }
  9485. /* case 5 */
  9486. else {
  9487. WOLFSSL_MSG("No common cert type found in client_certificate_type ext");
  9488. SendAlert(ssl, alert_fatal, unsupported_certificate);
  9489. return UNSUPPORTED_CERTIFICATE;
  9490. }
  9491. }
  9492. /* populate client_certificate_type extension */
  9493. if (populate) {
  9494. WOLFSSL_MSG("Adding Client Certificate Type extension");
  9495. ret = TLSX_Push(&ssl->extensions, TLSX_CLIENT_CERTIFICATE_TYPE, ssl,
  9496. ssl->heap);
  9497. if (ret == 0) {
  9498. TLSX_SetResponse(ssl, TLSX_CLIENT_CERTIFICATE_TYPE);
  9499. }
  9500. }
  9501. }
  9502. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9503. /* parse it in client side */
  9504. if (length == 1) {
  9505. ssl->options.rpkState.received_ClientCertTypeCnt = 1;
  9506. ssl->options.rpkState.received_ClientCertTypes[0] = *input;
  9507. }
  9508. else {
  9509. return BUFFER_E;
  9510. }
  9511. }
  9512. return ret;
  9513. }
  9514. /* Write out the "client certificate type" extension data into the given buffer.
  9515. * return the size wrote in the buffer on success, negative value on error.
  9516. */
  9517. static word16 TLSX_ClientCertificateType_Write(void* data, byte* output,
  9518. byte msgType)
  9519. {
  9520. WOLFSSL* ssl = (WOLFSSL*)data;
  9521. word16 idx = 0;
  9522. byte cnt = 0;
  9523. int i;
  9524. /* skip to write extension if count is zero */
  9525. cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;
  9526. if (cnt == 0)
  9527. return 0;
  9528. if (msgType == client_hello) {
  9529. /* client side */
  9530. *(output + idx) = cnt;
  9531. idx += OPAQUE8_LEN;
  9532. for (i = 0; i < cnt; i++) {
  9533. *(output + idx) = ssl->options.rpkState.sending_ClientCertTypes[i];
  9534. idx += OPAQUE8_LEN;
  9535. }
  9536. return idx;
  9537. }
  9538. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9539. /* sever side */
  9540. if (cnt == 1) {
  9541. *(output + idx) = ssl->options.rpkState.sending_ClientCertTypes[0];
  9542. idx += OPAQUE8_LEN;
  9543. }
  9544. }
  9545. return idx;
  9546. }
  9547. /* Calculate then return the size of the "client certificate type" extension
  9548. * data.
  9549. * return the extension data size on success, negative value on error.
  9550. */
  9551. static int TLSX_ClientCertificateType_GetSize(WOLFSSL* ssl, byte msgType)
  9552. {
  9553. int ret = 0;
  9554. byte cnt;
  9555. if (ssl == NULL)
  9556. return BAD_FUNC_ARG;
  9557. if (msgType == client_hello) {
  9558. /* client side */
  9559. cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;
  9560. ret = (int)(OPAQUE8_LEN + cnt * OPAQUE8_LEN);
  9561. }
  9562. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9563. /* sever side */
  9564. cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;/* must be one */
  9565. ret = OPAQUE8_LEN;
  9566. }
  9567. else {
  9568. return SANITY_MSG_E;
  9569. }
  9570. return ret;
  9571. }
  9572. #define CCT_GET_SIZE TLSX_ClientCertificateType_GetSize
  9573. #define CCT_WRITE TLSX_ClientCertificateType_Write
  9574. #define CCT_PARSE TLSX_ClientCertificateType_Parse
  9575. #else
  9576. #define CCT_GET_SIZE(a) 0
  9577. #define CCT_WRITE(a, b) 0
  9578. #define CCT_PARSE(a, b, c, d) 0
  9579. #endif /* HAVE_RPK */
  9580. #if defined(HAVE_RPK)
  9581. /******************************************************************************/
  9582. /* Server_Certificate_Type extension */
  9583. /******************************************************************************/
  9584. /* Creates a "server certificate type" extension if necessary.
  9585. * Returns 0 if no error occurred, negative value otherwise.
  9586. * A return of 0, it does not indicae that the extension was created.
  9587. */
  9588. static int TLSX_ServerCertificateType_Use(WOLFSSL* ssl, byte isServer)
  9589. {
  9590. int ret = 0;
  9591. byte ctype;
  9592. if (ssl == NULL)
  9593. return BAD_FUNC_ARG;
  9594. if (isServer) {
  9595. /* [in server side] */
  9596. /* find common cert type to both end */
  9597. if (GetCommonItem(
  9598. ssl->options.rpkConfig.preferred_ServerCertTypes,
  9599. ssl->options.rpkConfig.preferred_ServerCertTypeCnt,
  9600. ssl->options.rpkState.received_ServerCertTypes,
  9601. ssl->options.rpkState.received_ServerCertTypeCnt,
  9602. &ctype)) {
  9603. ssl->options.rpkState.sending_ServerCertTypeCnt = 1;
  9604. ssl->options.rpkState.sending_ServerCertTypes[0] = ctype;
  9605. /* Push new server_certificate_type extension. */
  9606. WOLFSSL_MSG("Adding Server Certificate Type extension");
  9607. ret = TLSX_Push(&ssl->extensions, TLSX_SERVER_CERTIFICATE_TYPE, ssl,
  9608. ssl->heap);
  9609. if (ret == 0) {
  9610. TLSX_SetResponse(ssl, TLSX_SERVER_CERTIFICATE_TYPE);
  9611. }
  9612. }
  9613. else {
  9614. /* no common cert type found */
  9615. WOLFSSL_MSG("No common cert type found in server_certificate_type ext");
  9616. SendAlert(ssl, alert_fatal, unsupported_certificate);
  9617. ret = UNSUPPORTED_CERTIFICATE;
  9618. }
  9619. }
  9620. else {
  9621. /* [in client side] */
  9622. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_RPK,
  9623. ssl->options.rpkConfig.preferred_ServerCertTypeCnt,
  9624. ssl->options.rpkConfig.preferred_ServerCertTypes)) {
  9625. ssl->options.rpkState.sending_ServerCertTypeCnt =
  9626. ssl->options.rpkConfig.preferred_ServerCertTypeCnt;
  9627. XMEMCPY(ssl->options.rpkState.sending_ServerCertTypes,
  9628. ssl->options.rpkConfig.preferred_ServerCertTypes,
  9629. ssl->options.rpkConfig.preferred_ServerCertTypeCnt);
  9630. /* Push new server_certificate_type extension. */
  9631. WOLFSSL_MSG("Adding Server Certificate Type extension");
  9632. ret = TLSX_Push(&ssl->extensions, TLSX_SERVER_CERTIFICATE_TYPE, ssl,
  9633. ssl->heap);
  9634. }
  9635. else {
  9636. WOLFSSL_MSG("No will to accept RPK cert");
  9637. }
  9638. }
  9639. return ret;
  9640. }
  9641. /* Parse a "server certificate type" extension received from peer.
  9642. * returns 0 on success and other values indicate failure.
  9643. */
  9644. static int TLSX_ServerCertificateType_Parse(WOLFSSL* ssl, const byte* input,
  9645. word16 length, byte msgType)
  9646. {
  9647. byte typeCnt;
  9648. int idx = 0;
  9649. int ret = 0;
  9650. int i;
  9651. if (msgType == client_hello) {
  9652. /* in server side */
  9653. if (length < OPAQUE8_LEN)
  9654. return BUFFER_E;
  9655. typeCnt = input[idx];
  9656. if (typeCnt > MAX_SERVER_CERT_TYPE_CNT)
  9657. return BUFFER_E;
  9658. if ((typeCnt + 1) * OPAQUE8_LEN != length){
  9659. return BUFFER_E;
  9660. }
  9661. ssl->options.rpkState.received_ServerCertTypeCnt = input[idx];
  9662. idx += OPAQUE8_LEN;
  9663. for (i = 0; i < typeCnt; i++) {
  9664. ssl->options.rpkState.received_ServerCertTypes[i] = input[idx];
  9665. idx += OPAQUE8_LEN;
  9666. }
  9667. ret = TLSX_ServerCertificateType_Use(ssl, 1);
  9668. if (ret == 0) {
  9669. TLSX_SetResponse(ssl, TLSX_SERVER_CERTIFICATE_TYPE);
  9670. }
  9671. }
  9672. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9673. /* in client side */
  9674. if (length != 1) /* length slould be 1 */
  9675. return BUFFER_E;
  9676. ssl->options.rpkState.received_ServerCertTypeCnt = 1;
  9677. ssl->options.rpkState.received_ServerCertTypes[0] = *input;
  9678. }
  9679. return 0;
  9680. }
  9681. /* Write out the "server certificate type" extension data into the given buffer.
  9682. * return the size wrote in the buffer on success, negative value on error.
  9683. */
  9684. static word16 TLSX_ServerCertificateType_Write(void* data, byte* output,
  9685. byte msgType)
  9686. {
  9687. WOLFSSL* ssl = (WOLFSSL*)data;
  9688. word16 idx = 0;
  9689. int cnt = 0;
  9690. int i;
  9691. /* skip to write extension if count is zero */
  9692. cnt = ssl->options.rpkState.sending_ServerCertTypeCnt;
  9693. if (cnt == 0)
  9694. return 0;
  9695. if (msgType == client_hello) {
  9696. /* in client side */
  9697. *(output + idx) = cnt;
  9698. idx += OPAQUE8_LEN;
  9699. for (i = 0; i < cnt; i++) {
  9700. *(output + idx) = ssl->options.rpkState.sending_ServerCertTypes[i];
  9701. idx += OPAQUE8_LEN;
  9702. }
  9703. }
  9704. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9705. /* in server side */
  9706. /* ensure cnt is one */
  9707. if (cnt != 1)
  9708. return 0;
  9709. *(output + idx) = ssl->options.rpkState.sending_ServerCertTypes[0];
  9710. idx += OPAQUE8_LEN;
  9711. }
  9712. return idx;
  9713. }
  9714. /* Calculate then return the size of the "server certificate type" extension
  9715. * data.
  9716. * return the extension data size on success, negative value on error.
  9717. */
  9718. static int TLSX_ServerCertificateType_GetSize(WOLFSSL* ssl, byte msgType)
  9719. {
  9720. int ret = 0;
  9721. int cnt;
  9722. if (ssl == NULL)
  9723. return BAD_FUNC_ARG;
  9724. if (msgType == client_hello) {
  9725. /* in clent side */
  9726. cnt = ssl->options.rpkState.sending_ServerCertTypeCnt;
  9727. if (cnt > 0) {
  9728. ret = (int)(OPAQUE8_LEN + cnt * OPAQUE8_LEN);
  9729. }
  9730. }
  9731. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9732. /* in server side */
  9733. ret = (int)OPAQUE8_LEN;
  9734. }
  9735. else {
  9736. return SANITY_MSG_E;
  9737. }
  9738. return ret;
  9739. }
  9740. #define SCT_GET_SIZE TLSX_ServerCertificateType_GetSize
  9741. #define SCT_WRITE TLSX_ServerCertificateType_Write
  9742. #define SCT_PARSE TLSX_ServerCertificateType_Parse
  9743. #else
  9744. #define SCT_GET_SIZE(a) 0
  9745. #define SCT_WRITE(a, b) 0
  9746. #define SCT_PARSE(a, b, c, d) 0
  9747. #endif /* HAVE_RPK */
  9748. /******************************************************************************/
  9749. /* TLS Extensions Framework */
  9750. /******************************************************************************/
  9751. /** Finds an extension in the provided list. */
  9752. TLSX* TLSX_Find(TLSX* list, TLSX_Type type)
  9753. {
  9754. TLSX* extension = list;
  9755. while (extension && extension->type != type)
  9756. extension = extension->next;
  9757. return extension;
  9758. }
  9759. /** Remove an extension. */
  9760. void TLSX_Remove(TLSX** list, TLSX_Type type, void* heap)
  9761. {
  9762. TLSX* extension;
  9763. TLSX** next;
  9764. if (list == NULL)
  9765. return;
  9766. extension = *list;
  9767. next = list;
  9768. while (extension && extension->type != type) {
  9769. next = &extension->next;
  9770. extension = extension->next;
  9771. }
  9772. if (extension) {
  9773. *next = extension->next;
  9774. extension->next = NULL;
  9775. TLSX_FreeAll(extension, heap);
  9776. }
  9777. }
  9778. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  9779. #define GREASE_ECH_SIZE 160
  9780. #define MAX_PUBLIC_NAME_SZ 256
  9781. #define TLS_INFO_CONST_STRING "tls ech"
  9782. #define TLS_INFO_CONST_STRING_SZ 7
  9783. /* return status after setting up ech to write a grease ech */
  9784. static int TLSX_GreaseECH_Use(TLSX** extensions, void* heap, WC_RNG* rng)
  9785. {
  9786. int ret = 0;
  9787. WOLFSSL_ECH* ech;
  9788. if (extensions == NULL)
  9789. return BAD_FUNC_ARG;
  9790. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9791. DYNAMIC_TYPE_TMP_BUFFER);
  9792. if (ech == NULL)
  9793. return MEMORY_E;
  9794. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9795. ech->state = ECH_WRITE_GREASE;
  9796. /* 0 for outer */
  9797. ech->type = ECH_TYPE_OUTER;
  9798. /* kemId */
  9799. ech->kemId = DHKEM_X25519_HKDF_SHA256;
  9800. /* cipherSuite kdf */
  9801. ech->cipherSuite.kdfId = HKDF_SHA256;
  9802. /* cipherSuite aead */
  9803. ech->cipherSuite.aeadId = HPKE_AES_128_GCM;
  9804. /* random configId */
  9805. ret = wc_RNG_GenerateByte(rng, &(ech->configId));
  9806. /* curve25519 encLen */
  9807. ech->encLen = DHKEM_X25519_ENC_LEN;
  9808. if (ret == 0)
  9809. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9810. if (ret != 0) {
  9811. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9812. }
  9813. return ret;
  9814. }
  9815. /* return status after setting up ech to write real ech */
  9816. static int TLSX_ECH_Use(WOLFSSL_EchConfig* echConfig, TLSX** extensions,
  9817. void* heap, WC_RNG* rng)
  9818. {
  9819. int ret = 0;
  9820. int suiteIndex;
  9821. WOLFSSL_ECH* ech;
  9822. if (extensions == NULL)
  9823. return BAD_FUNC_ARG;
  9824. /* find a supported cipher suite */
  9825. suiteIndex = EchConfigGetSupportedCipherSuite(echConfig);
  9826. if (suiteIndex < 0)
  9827. return suiteIndex;
  9828. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9829. DYNAMIC_TYPE_TMP_BUFFER);
  9830. if (ech == NULL)
  9831. return MEMORY_E;
  9832. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9833. ech->state = ECH_WRITE_REAL;
  9834. ech->echConfig = echConfig;
  9835. /* 0 for outer */
  9836. ech->type = ECH_TYPE_OUTER;
  9837. /* kemId */
  9838. ech->kemId = echConfig->kemId;
  9839. /* cipherSuite kdf */
  9840. ech->cipherSuite.kdfId = echConfig->cipherSuites[suiteIndex].kdfId;
  9841. /* cipherSuite aead */
  9842. ech->cipherSuite.aeadId = echConfig->cipherSuites[suiteIndex].aeadId;
  9843. /* configId */
  9844. ech->configId = echConfig->configId;
  9845. /* encLen */
  9846. switch (echConfig->kemId)
  9847. {
  9848. case DHKEM_P256_HKDF_SHA256:
  9849. ech->encLen = DHKEM_P256_ENC_LEN;
  9850. break;
  9851. case DHKEM_P384_HKDF_SHA384:
  9852. ech->encLen = DHKEM_P384_ENC_LEN;
  9853. break;
  9854. case DHKEM_P521_HKDF_SHA512:
  9855. ech->encLen = DHKEM_P521_ENC_LEN;
  9856. break;
  9857. case DHKEM_X25519_HKDF_SHA256:
  9858. ech->encLen = DHKEM_X25519_ENC_LEN;
  9859. break;
  9860. case DHKEM_X448_HKDF_SHA512:
  9861. ech->encLen = DHKEM_X448_ENC_LEN;
  9862. break;
  9863. }
  9864. /* setup hpke */
  9865. ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER);
  9866. if (ech->hpke == NULL) {
  9867. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9868. return MEMORY_E;
  9869. }
  9870. ret = wc_HpkeInit(ech->hpke, ech->kemId, ech->cipherSuite.kdfId,
  9871. ech->cipherSuite.aeadId, heap);
  9872. /* setup the ephemeralKey */
  9873. if (ret == 0)
  9874. ret = wc_HpkeGenerateKeyPair(ech->hpke, &ech->ephemeralKey, rng);
  9875. if (ret == 0)
  9876. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9877. if (ret != 0) {
  9878. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9879. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9880. }
  9881. return ret;
  9882. }
  9883. /* return status after setting up ech to read and decrypt */
  9884. static int TLSX_ServerECH_Use(TLSX** extensions, void* heap,
  9885. WOLFSSL_EchConfig* configs)
  9886. {
  9887. int ret;
  9888. WOLFSSL_ECH* ech;
  9889. TLSX* echX;
  9890. if (extensions == NULL)
  9891. return BAD_FUNC_ARG;
  9892. /* if we already have ech don't override it */
  9893. echX = TLSX_Find(*extensions, TLSX_ECH);
  9894. if (echX != NULL)
  9895. return 0;
  9896. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9897. DYNAMIC_TYPE_TMP_BUFFER);
  9898. if (ech == NULL)
  9899. return MEMORY_E;
  9900. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9901. ech->state = ECH_WRITE_NONE;
  9902. /* 0 for outer */
  9903. ech->type = ECH_TYPE_OUTER;
  9904. ech->echConfig = configs;
  9905. /* setup the rest of the settings when we receive ech from the client */
  9906. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9907. if (ret != 0)
  9908. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9909. return ret;
  9910. }
  9911. /* return length after writing the ech */
  9912. static int TLSX_ECH_Write(WOLFSSL_ECH* ech, byte* writeBuf, word16* offset)
  9913. {
  9914. int ret = 0;
  9915. int rngRet = -1;
  9916. word32 configsLen = 0;
  9917. void* ephemeralKey = NULL;
  9918. byte* writeBuf_p = writeBuf;
  9919. #ifdef WOLFSSL_SMALL_STACK
  9920. Hpke* hpke = NULL;
  9921. WC_RNG* rng = NULL;
  9922. #else
  9923. Hpke hpke[1];
  9924. WC_RNG rng[1];
  9925. #endif
  9926. WOLFSSL_MSG("TLSX_ECH_Write");
  9927. if (ech->state == ECH_WRITE_NONE || ech->state == ECH_PARSED_INTERNAL)
  9928. return 0;
  9929. if (ech->state == ECH_WRITE_RETRY_CONFIGS) {
  9930. /* get size then write */
  9931. ret = GetEchConfigsEx(ech->echConfig, NULL, &configsLen);
  9932. if (ret != LENGTH_ONLY_E)
  9933. return ret;
  9934. ret = GetEchConfigsEx(ech->echConfig, writeBuf, &configsLen);
  9935. if (ret != WOLFSSL_SUCCESS)
  9936. return ret;
  9937. *offset += configsLen;
  9938. return 0;
  9939. }
  9940. #ifdef WOLFSSL_SMALL_STACK
  9941. hpke = (Hpke*)XMALLOC(sizeof(Hpke), NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9942. if (hpke == NULL)
  9943. return MEMORY_E;
  9944. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  9945. if (rng == NULL) {
  9946. XFREE(hpke, NULL, DYNAMIC_TYPE_RNG);
  9947. return MEMORY_E;
  9948. }
  9949. #endif
  9950. /* type */
  9951. *writeBuf_p = ech->type;
  9952. writeBuf_p += sizeof(ech->type);
  9953. /* outer has body, inner does not */
  9954. if (ech->type == ECH_TYPE_OUTER) {
  9955. /* kdfId */
  9956. c16toa(ech->cipherSuite.kdfId, writeBuf_p);
  9957. writeBuf_p += sizeof(ech->cipherSuite.kdfId);
  9958. /* aeadId */
  9959. c16toa(ech->cipherSuite.aeadId, writeBuf_p);
  9960. writeBuf_p += sizeof(ech->cipherSuite.aeadId);
  9961. /* configId */
  9962. *writeBuf_p = ech->configId;
  9963. writeBuf_p += sizeof(ech->configId);
  9964. /* encLen */
  9965. c16toa(ech->encLen, writeBuf_p);
  9966. writeBuf_p += 2;
  9967. if (ech->state == ECH_WRITE_GREASE) {
  9968. /* hpke init */
  9969. ret = wc_HpkeInit(hpke, ech->kemId, ech->cipherSuite.kdfId,
  9970. ech->cipherSuite.aeadId, NULL);
  9971. if (ret == 0)
  9972. rngRet = ret = wc_InitRng(rng);
  9973. /* create the ephemeralKey */
  9974. if (ret == 0)
  9975. ret = wc_HpkeGenerateKeyPair(hpke, &ephemeralKey, rng);
  9976. /* enc */
  9977. if (ret == 0) {
  9978. ret = wc_HpkeSerializePublicKey(hpke, ephemeralKey, writeBuf_p,
  9979. &ech->encLen);
  9980. writeBuf_p += ech->encLen;
  9981. }
  9982. if (ret == 0) {
  9983. /* innerClientHelloLen */
  9984. c16toa(GREASE_ECH_SIZE + ((writeBuf_p + 2 - writeBuf) % 32),
  9985. writeBuf_p);
  9986. writeBuf_p += 2;
  9987. /* innerClientHello */
  9988. ret = wc_RNG_GenerateBlock(rng, writeBuf_p, GREASE_ECH_SIZE +
  9989. ((writeBuf_p - writeBuf) % 32));
  9990. writeBuf_p += GREASE_ECH_SIZE + ((writeBuf_p - writeBuf) % 32);
  9991. }
  9992. if (rngRet == 0)
  9993. wc_FreeRng(rng);
  9994. if (ephemeralKey != NULL)
  9995. wc_HpkeFreeKey(hpke, hpke->kem, ephemeralKey, hpke->heap);
  9996. }
  9997. else {
  9998. /* write enc to writeBuf_p */
  9999. ret = wc_HpkeSerializePublicKey(ech->hpke, ech->ephemeralKey,
  10000. writeBuf_p, &ech->encLen);
  10001. writeBuf_p += ech->encLen;
  10002. /* innerClientHelloLen */
  10003. c16toa(ech->innerClientHelloLen, writeBuf_p);
  10004. writeBuf_p += 2;
  10005. /* set payload offset for when we finalize */
  10006. ech->outerClientPayload = writeBuf_p;
  10007. /* write zeros for payload */
  10008. XMEMSET(writeBuf_p, 0, ech->innerClientHelloLen);
  10009. writeBuf_p += ech->innerClientHelloLen;
  10010. }
  10011. }
  10012. #ifdef WOLFSSL_SMALL_STACK
  10013. XFREE(hpke, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10014. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  10015. #endif
  10016. if (ret == 0)
  10017. *offset += (writeBuf_p - writeBuf);
  10018. return ret;
  10019. }
  10020. /* return the size needed for the ech extension */
  10021. static int TLSX_ECH_GetSize(WOLFSSL_ECH* ech)
  10022. {
  10023. int ret;
  10024. word32 size;
  10025. if (ech->state == ECH_WRITE_GREASE) {
  10026. size = sizeof(ech->type) + sizeof(ech->cipherSuite) +
  10027. sizeof(ech->configId) + sizeof(word16) + ech->encLen +
  10028. sizeof(word16);
  10029. size += GREASE_ECH_SIZE + (size % 32);
  10030. }
  10031. else if (ech->state == ECH_WRITE_NONE ||
  10032. ech->state == ECH_PARSED_INTERNAL) {
  10033. size = 0;
  10034. }
  10035. else if (ech->state == ECH_WRITE_RETRY_CONFIGS) {
  10036. /* get the size of the raw configs */
  10037. ret = GetEchConfigsEx(ech->echConfig, NULL, &size);
  10038. if (ret != LENGTH_ONLY_E)
  10039. return ret;
  10040. }
  10041. else if (ech->type == ECH_TYPE_INNER)
  10042. {
  10043. size = sizeof(ech->type);
  10044. }
  10045. else
  10046. {
  10047. size = sizeof(ech->type) + sizeof(ech->cipherSuite) +
  10048. sizeof(ech->configId) + sizeof(word16) + ech->encLen +
  10049. sizeof(word16) + ech->innerClientHelloLen;
  10050. }
  10051. return (int)size;
  10052. }
  10053. /* return status after attempting to open the hpke encrypted ech extension, if
  10054. * successful the inner client hello will be stored in
  10055. * ech->innerClientHelloLen */
  10056. static int TLSX_ExtractEch(WOLFSSL_ECH* ech, WOLFSSL_EchConfig* echConfig,
  10057. byte* aad, word32 aadLen, void* heap)
  10058. {
  10059. int ret = 0;
  10060. int expectedEncLen;
  10061. int i;
  10062. word32 rawConfigLen = 0;
  10063. byte* info = NULL;
  10064. word32 infoLen = 0;
  10065. if (ech == NULL || echConfig == NULL || aad == NULL)
  10066. return BAD_FUNC_ARG;
  10067. /* verify the kem and key len */
  10068. switch (echConfig->kemId)
  10069. {
  10070. case DHKEM_P256_HKDF_SHA256:
  10071. expectedEncLen = DHKEM_P256_ENC_LEN;
  10072. break;
  10073. case DHKEM_P384_HKDF_SHA384:
  10074. expectedEncLen = DHKEM_P384_ENC_LEN;
  10075. break;
  10076. case DHKEM_P521_HKDF_SHA512:
  10077. expectedEncLen = DHKEM_P521_ENC_LEN;
  10078. break;
  10079. case DHKEM_X25519_HKDF_SHA256:
  10080. expectedEncLen = DHKEM_X25519_ENC_LEN;
  10081. break;
  10082. case DHKEM_X448_HKDF_SHA512:
  10083. expectedEncLen = DHKEM_X448_ENC_LEN;
  10084. break;
  10085. default:
  10086. expectedEncLen = 0;
  10087. break;
  10088. }
  10089. if (expectedEncLen != ech->encLen)
  10090. return BAD_FUNC_ARG;
  10091. /* verify the cipher suite */
  10092. for (i = 0; i < echConfig->numCipherSuites; i++) {
  10093. if (echConfig->cipherSuites[i].kdfId == ech->cipherSuite.kdfId &&
  10094. echConfig->cipherSuites[i].aeadId == ech->cipherSuite.aeadId) {
  10095. break;
  10096. }
  10097. }
  10098. if (i >= echConfig->numCipherSuites) {
  10099. return BAD_FUNC_ARG;
  10100. }
  10101. ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER);
  10102. if (ech->hpke == NULL)
  10103. return MEMORY_E;
  10104. ret = wc_HpkeInit(ech->hpke, echConfig->kemId, ech->cipherSuite.kdfId,
  10105. ech->cipherSuite.aeadId, heap);
  10106. /* get the rawConfigLen */
  10107. if (ret == 0)
  10108. ret = GetEchConfig(echConfig, NULL, &rawConfigLen);
  10109. if (ret == LENGTH_ONLY_E)
  10110. ret = 0;
  10111. /* create info */
  10112. if (ret == 0) {
  10113. infoLen = TLS_INFO_CONST_STRING_SZ + 1 + rawConfigLen;
  10114. info = (byte*)XMALLOC(infoLen, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10115. if (info == NULL)
  10116. ret = MEMORY_E;
  10117. else {
  10118. XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING,
  10119. TLS_INFO_CONST_STRING_SZ + 1);
  10120. ret = GetEchConfig(echConfig, info +
  10121. TLS_INFO_CONST_STRING_SZ + 1, &rawConfigLen);
  10122. }
  10123. }
  10124. /* decrypt the ech payload */
  10125. if (ret == 0)
  10126. ret = wc_HpkeOpenBase(ech->hpke, echConfig->receiverPrivkey, ech->enc,
  10127. ech->encLen, info, infoLen, aad, aadLen, ech->outerClientPayload,
  10128. ech->innerClientHelloLen,
  10129. ech->innerClientHello + HANDSHAKE_HEADER_SZ);
  10130. if (ret != 0) {
  10131. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10132. ech->hpke = NULL;
  10133. }
  10134. if (info != NULL)
  10135. XFREE(info, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10136. return ret;
  10137. }
  10138. /* parse the ech extension, if internal update ech->state and return, if
  10139. * external attempt to extract the inner client_hello, return the status */
  10140. static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size,
  10141. byte msgType)
  10142. {
  10143. int ret = 0;
  10144. int i;
  10145. TLSX* echX;
  10146. WOLFSSL_ECH* ech;
  10147. WOLFSSL_EchConfig* echConfig;
  10148. byte* aadCopy;
  10149. byte* readBuf_p = (byte*)readBuf;
  10150. WOLFSSL_MSG("TLSX_ECH_Parse");
  10151. if (size == 0)
  10152. return BAD_FUNC_ARG;
  10153. if (msgType == encrypted_extensions) {
  10154. ret = wolfSSL_SetEchConfigs(ssl, readBuf, size);
  10155. if (ret == WOLFSSL_SUCCESS)
  10156. ret = 0;
  10157. }
  10158. else if (msgType == client_hello && ssl->ctx->echConfigs != NULL) {
  10159. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  10160. if (echX == NULL)
  10161. return BAD_FUNC_ARG;
  10162. ech = (WOLFSSL_ECH*)echX->data;
  10163. /* read the ech parameters before the payload */
  10164. ech->type = *readBuf_p;
  10165. readBuf_p++;
  10166. if (ech->type == ECH_TYPE_INNER) {
  10167. ech->state = ECH_PARSED_INTERNAL;
  10168. return 0;
  10169. }
  10170. /* technically the payload would only be 1 byte at this length */
  10171. if (size < 11 + ech->encLen)
  10172. return BAD_FUNC_ARG;
  10173. ato16(readBuf_p, &ech->cipherSuite.kdfId);
  10174. readBuf_p += 2;
  10175. ato16(readBuf_p, &ech->cipherSuite.aeadId);
  10176. readBuf_p += 2;
  10177. ech->configId = *readBuf_p;
  10178. readBuf_p++;
  10179. ato16(readBuf_p, &ech->encLen);
  10180. readBuf_p += 2;
  10181. if (ech->encLen > HPKE_Npk_MAX)
  10182. return BAD_FUNC_ARG;
  10183. XMEMCPY(ech->enc, readBuf_p, ech->encLen);
  10184. readBuf_p += ech->encLen;
  10185. ato16(readBuf_p, &ech->innerClientHelloLen);
  10186. ech->innerClientHelloLen -= AES_BLOCK_SIZE;
  10187. readBuf_p += 2;
  10188. ech->outerClientPayload = readBuf_p;
  10189. /* make a copy of the aad */
  10190. aadCopy = (byte*)XMALLOC(ech->aadLen, ssl->heap,
  10191. DYNAMIC_TYPE_TMP_BUFFER);
  10192. if (aadCopy == NULL)
  10193. return MEMORY_E;
  10194. XMEMCPY(aadCopy, ech->aad, ech->aadLen);
  10195. /* set the ech payload of the copy to zeros */
  10196. XMEMSET(aadCopy + (readBuf_p - ech->aad), 0,
  10197. ech->innerClientHelloLen + AES_BLOCK_SIZE);
  10198. /* allocate the inner payload buffer */
  10199. ech->innerClientHello =
  10200. (byte*)XMALLOC(ech->innerClientHelloLen + HANDSHAKE_HEADER_SZ,
  10201. ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10202. if (ech->innerClientHello == NULL) {
  10203. XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10204. return MEMORY_E;
  10205. }
  10206. /* first check if the config id matches */
  10207. echConfig = ssl->ctx->echConfigs;
  10208. while (echConfig != NULL) {
  10209. /* decrypt with this config */
  10210. if (echConfig->configId == ech->configId) {
  10211. ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen,
  10212. ssl->heap);
  10213. break;
  10214. }
  10215. echConfig = echConfig->next;
  10216. }
  10217. /* try to decrypt with all configs */
  10218. if (echConfig == NULL || ret != 0) {
  10219. echConfig = ssl->ctx->echConfigs;
  10220. while (echConfig != NULL) {
  10221. ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen,
  10222. ssl->heap);
  10223. if (ret== 0)
  10224. break;
  10225. echConfig = echConfig->next;
  10226. }
  10227. }
  10228. /* if we failed to extract */
  10229. if (ret != 0) {
  10230. XFREE(ech->innerClientHello, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10231. ech->innerClientHello = NULL;
  10232. ech->state = ECH_WRITE_RETRY_CONFIGS;
  10233. }
  10234. else {
  10235. i = 0;
  10236. /* decrement until before the padding */
  10237. while (ech->innerClientHello[ech->innerClientHelloLen +
  10238. HANDSHAKE_HEADER_SZ - i - 1] != ECH_TYPE_INNER) {
  10239. i++;
  10240. }
  10241. /* subtract the length of the padding from the length */
  10242. ech->innerClientHelloLen -= i;
  10243. }
  10244. XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10245. return 0;
  10246. }
  10247. return ret;
  10248. }
  10249. /* free the ech struct and the dynamic buffer it uses */
  10250. static void TLSX_ECH_Free(WOLFSSL_ECH* ech, void* heap)
  10251. {
  10252. if (ech->innerClientHello != NULL)
  10253. XFREE(ech->innerClientHello, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10254. if (ech->ephemeralKey != NULL)
  10255. wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, ech->ephemeralKey,
  10256. ech->hpke->heap);
  10257. if (ech->hpke != NULL)
  10258. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10259. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10260. (void)heap;
  10261. }
  10262. /* encrypt the client hello and store it in ech->outerClientPayload, return
  10263. * status */
  10264. int TLSX_FinalizeEch(WOLFSSL_ECH* ech, byte* aad, word32 aadLen)
  10265. {
  10266. int ret;
  10267. void* receiverPubkey = NULL;
  10268. byte* info;
  10269. int infoLen;
  10270. byte* aadCopy;
  10271. /* import the server public key */
  10272. ret = wc_HpkeDeserializePublicKey(ech->hpke, &receiverPubkey,
  10273. ech->echConfig->receiverPubkey, ech->encLen);
  10274. if (ret == 0) {
  10275. /* create info */
  10276. infoLen = TLS_INFO_CONST_STRING_SZ + 1 + ech->echConfig->rawLen;
  10277. info = (byte*)XMALLOC(infoLen, ech->hpke->heap,
  10278. DYNAMIC_TYPE_TMP_BUFFER);
  10279. if (info == NULL)
  10280. ret = MEMORY_E;
  10281. if (ret == 0) {
  10282. /* puts the null byte in for me */
  10283. XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING, TLS_INFO_CONST_STRING_SZ
  10284. + 1);
  10285. XMEMCPY(info + TLS_INFO_CONST_STRING_SZ + 1, ech->echConfig->raw,
  10286. ech->echConfig->rawLen);
  10287. /* make a copy of the aad since we overwrite it */
  10288. aadCopy = (byte*)XMALLOC(aadLen, ech->hpke->heap,
  10289. DYNAMIC_TYPE_TMP_BUFFER);
  10290. if (aadCopy == NULL) {
  10291. XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10292. ret = MEMORY_E;
  10293. }
  10294. }
  10295. if (ret == 0) {
  10296. XMEMCPY(aadCopy, aad, aadLen);
  10297. /* seal the payload */
  10298. ret = wc_HpkeSealBase(ech->hpke, ech->ephemeralKey, receiverPubkey,
  10299. info, infoLen, aadCopy, aadLen, ech->innerClientHello,
  10300. ech->innerClientHelloLen - ech->hpke->Nt,
  10301. ech->outerClientPayload);
  10302. XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10303. XFREE(aadCopy, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10304. }
  10305. }
  10306. if (receiverPubkey != NULL)
  10307. wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, receiverPubkey,
  10308. ech->hpke->heap);
  10309. return ret;
  10310. }
  10311. #define GREASE_ECH_USE TLSX_GreaseECH_Use
  10312. #define ECH_USE TLSX_ECH_Use
  10313. #define SERVER_ECH_USE TLSX_ServerECH_Use
  10314. #define ECH_WRITE TLSX_ECH_Write
  10315. #define ECH_GET_SIZE TLSX_ECH_GetSize
  10316. #define ECH_PARSE TLSX_ECH_Parse
  10317. #define ECH_FREE TLSX_ECH_Free
  10318. #endif
  10319. /** Releases all extensions in the provided list. */
  10320. void TLSX_FreeAll(TLSX* list, void* heap)
  10321. {
  10322. TLSX* extension;
  10323. while ((extension = list)) {
  10324. list = extension->next;
  10325. switch (extension->type) {
  10326. #if defined(HAVE_RPK)
  10327. case TLSX_CLIENT_CERTIFICATE_TYPE:
  10328. WOLFSSL_MSG("Client Certificate Type extension free");
  10329. /* nothing to do */
  10330. break;
  10331. case TLSX_SERVER_CERTIFICATE_TYPE:
  10332. WOLFSSL_MSG("Server Certificate Type extension free");
  10333. /* nothing to do */
  10334. break;
  10335. #endif
  10336. #ifdef HAVE_SNI
  10337. case TLSX_SERVER_NAME:
  10338. WOLFSSL_MSG("SNI extension free");
  10339. SNI_FREE_ALL((SNI*)extension->data, heap);
  10340. break;
  10341. #endif
  10342. case TLSX_TRUSTED_CA_KEYS:
  10343. WOLFSSL_MSG("Trusted CA Indication extension free");
  10344. TCA_FREE_ALL((TCA*)extension->data, heap);
  10345. break;
  10346. case TLSX_MAX_FRAGMENT_LENGTH:
  10347. WOLFSSL_MSG("Max Fragment Length extension free");
  10348. MFL_FREE_ALL(extension->data, heap);
  10349. break;
  10350. case TLSX_EXTENDED_MASTER_SECRET:
  10351. WOLFSSL_MSG("Extended Master Secret free");
  10352. /* Nothing to do. */
  10353. break;
  10354. case TLSX_TRUNCATED_HMAC:
  10355. WOLFSSL_MSG("Truncated HMAC extension free");
  10356. /* Nothing to do. */
  10357. break;
  10358. case TLSX_SUPPORTED_GROUPS:
  10359. WOLFSSL_MSG("Supported Groups extension free");
  10360. EC_FREE_ALL((SupportedCurve*)extension->data, heap);
  10361. break;
  10362. case TLSX_EC_POINT_FORMATS:
  10363. WOLFSSL_MSG("Point Formats extension free");
  10364. PF_FREE_ALL((PointFormat*)extension->data, heap);
  10365. break;
  10366. case TLSX_STATUS_REQUEST:
  10367. WOLFSSL_MSG("Certificate Status Request extension free");
  10368. CSR_FREE_ALL((CertificateStatusRequest*)extension->data, heap);
  10369. break;
  10370. case TLSX_STATUS_REQUEST_V2:
  10371. WOLFSSL_MSG("Certificate Status Request v2 extension free");
  10372. CSR2_FREE_ALL((CertificateStatusRequestItemV2*)extension->data,
  10373. heap);
  10374. break;
  10375. case TLSX_RENEGOTIATION_INFO:
  10376. WOLFSSL_MSG("Secure Renegotiation extension free");
  10377. SCR_FREE_ALL(extension->data, heap);
  10378. break;
  10379. case TLSX_SESSION_TICKET:
  10380. WOLFSSL_MSG("Session Ticket extension free");
  10381. WOLF_STK_FREE(extension->data, heap);
  10382. break;
  10383. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10384. WOLFSSL_MSG("ALPN extension free");
  10385. ALPN_FREE_ALL((ALPN*)extension->data, heap);
  10386. break;
  10387. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10388. case TLSX_SIGNATURE_ALGORITHMS:
  10389. WOLFSSL_MSG("Signature Algorithms extension to free");
  10390. SA_FREE_ALL((SignatureAlgorithms*)extension->data, heap);
  10391. break;
  10392. #endif
  10393. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10394. case TLSX_ENCRYPT_THEN_MAC:
  10395. WOLFSSL_MSG("Encrypt-Then-Mac extension free");
  10396. break;
  10397. #endif
  10398. #ifdef WOLFSSL_TLS13
  10399. case TLSX_SUPPORTED_VERSIONS:
  10400. WOLFSSL_MSG("Supported Versions extension free");
  10401. break;
  10402. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10403. case TLSX_COOKIE:
  10404. WOLFSSL_MSG("Cookie extension free");
  10405. CKE_FREE_ALL((Cookie*)extension->data, heap);
  10406. break;
  10407. #endif
  10408. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10409. case TLSX_PRE_SHARED_KEY:
  10410. WOLFSSL_MSG("Pre-Shared Key extension free");
  10411. PSK_FREE_ALL((PreSharedKey*)extension->data, heap);
  10412. break;
  10413. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10414. WOLFSSL_MSG("PSK Key Exchange Modes extension free");
  10415. break;
  10416. #endif
  10417. #ifdef WOLFSSL_EARLY_DATA
  10418. case TLSX_EARLY_DATA:
  10419. WOLFSSL_MSG("Early Data extension free");
  10420. break;
  10421. #endif
  10422. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10423. case TLSX_POST_HANDSHAKE_AUTH:
  10424. WOLFSSL_MSG("Post-Handshake Authentication extension free");
  10425. break;
  10426. #endif
  10427. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10428. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10429. WOLFSSL_MSG("Signature Algorithms extension free");
  10430. break;
  10431. #endif
  10432. case TLSX_KEY_SHARE:
  10433. WOLFSSL_MSG("Key Share extension free");
  10434. KS_FREE_ALL((KeyShareEntry*)extension->data, heap);
  10435. break;
  10436. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10437. case TLSX_CERTIFICATE_AUTHORITIES:
  10438. WOLFSSL_MSG("Certificate Authorities extension free");
  10439. break;
  10440. #endif
  10441. #endif
  10442. #ifdef WOLFSSL_SRTP
  10443. case TLSX_USE_SRTP:
  10444. WOLFSSL_MSG("SRTP extension free");
  10445. SRTP_FREE((TlsxSrtp*)extension->data, heap);
  10446. break;
  10447. #endif
  10448. #ifdef WOLFSSL_QUIC
  10449. case TLSX_KEY_QUIC_TP_PARAMS:
  10450. FALL_THROUGH;
  10451. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10452. WOLFSSL_MSG("QUIC transport parameter free");
  10453. QTP_FREE((QuicTransportParam*)extension->data, heap);
  10454. break;
  10455. #endif
  10456. #ifdef WOLFSSL_DTLS_CID
  10457. case TLSX_CONNECTION_ID:
  10458. WOLFSSL_MSG("Connection ID extension free");
  10459. CID_FREE((byte*)extension->data, heap);
  10460. break;
  10461. #endif /* WOLFSSL_DTLS_CID */
  10462. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10463. case TLSX_ECH:
  10464. WOLFSSL_MSG("ECH extension free");
  10465. ECH_FREE((WOLFSSL_ECH*)extension->data, heap);
  10466. break;
  10467. #endif
  10468. #ifdef WOLFSSL_DUAL_ALG_CERTS
  10469. case TLSX_CKS:
  10470. WOLFSSL_MSG("CKS extension free");
  10471. /* nothing to do */
  10472. break;
  10473. #endif
  10474. default:
  10475. break;
  10476. }
  10477. XFREE(extension, heap, DYNAMIC_TYPE_TLSX);
  10478. }
  10479. (void)heap;
  10480. }
  10481. /** Checks if the tls extensions are supported based on the protocol version. */
  10482. int TLSX_SupportExtensions(WOLFSSL* ssl) {
  10483. return ssl && (IsTLS(ssl) || ssl->version.major == DTLS_MAJOR);
  10484. }
  10485. /** Tells the buffered size of the extensions in a list. */
  10486. static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType,
  10487. word16* pLength)
  10488. {
  10489. int ret = 0;
  10490. TLSX* extension;
  10491. word16 length = 0;
  10492. byte isRequest = (msgType == client_hello ||
  10493. msgType == certificate_request);
  10494. while ((extension = list)) {
  10495. list = extension->next;
  10496. /* only extensions marked as response are sent back to the client. */
  10497. if (!isRequest && !extension->resp)
  10498. continue; /* skip! */
  10499. /* ssl level extensions are expected to override ctx level ones. */
  10500. if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type)))
  10501. continue; /* skip! */
  10502. /* extension type + extension data length. */
  10503. length += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN;
  10504. switch (extension->type) {
  10505. #ifdef WOLFSSL_DUAL_ALG_CERTS
  10506. case TLSX_CKS:
  10507. length += ((WOLFSSL*)extension->data)->sigSpecSz ;
  10508. break;
  10509. #endif
  10510. #ifdef HAVE_SNI
  10511. case TLSX_SERVER_NAME:
  10512. /* SNI only sends the name on the request. */
  10513. if (isRequest)
  10514. length += SNI_GET_SIZE((SNI*)extension->data);
  10515. break;
  10516. #endif
  10517. case TLSX_TRUSTED_CA_KEYS:
  10518. /* TCA only sends the list on the request. */
  10519. if (isRequest)
  10520. length += TCA_GET_SIZE((TCA*)extension->data);
  10521. break;
  10522. case TLSX_MAX_FRAGMENT_LENGTH:
  10523. length += MFL_GET_SIZE(extension->data);
  10524. break;
  10525. case TLSX_EXTENDED_MASTER_SECRET:
  10526. case TLSX_TRUNCATED_HMAC:
  10527. /* always empty. */
  10528. break;
  10529. case TLSX_SUPPORTED_GROUPS:
  10530. length += EC_GET_SIZE((SupportedCurve*)extension->data);
  10531. break;
  10532. case TLSX_EC_POINT_FORMATS:
  10533. length += PF_GET_SIZE((PointFormat*)extension->data);
  10534. break;
  10535. case TLSX_STATUS_REQUEST:
  10536. length += CSR_GET_SIZE(
  10537. (CertificateStatusRequest*)extension->data, isRequest);
  10538. break;
  10539. case TLSX_STATUS_REQUEST_V2:
  10540. length += CSR2_GET_SIZE(
  10541. (CertificateStatusRequestItemV2*)extension->data,
  10542. isRequest);
  10543. break;
  10544. case TLSX_RENEGOTIATION_INFO:
  10545. length += SCR_GET_SIZE((SecureRenegotiation*)extension->data,
  10546. isRequest);
  10547. break;
  10548. case TLSX_SESSION_TICKET:
  10549. length += WOLF_STK_GET_SIZE((SessionTicket*)extension->data,
  10550. isRequest);
  10551. break;
  10552. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10553. length += ALPN_GET_SIZE((ALPN*)extension->data);
  10554. break;
  10555. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10556. case TLSX_SIGNATURE_ALGORITHMS:
  10557. length += SA_GET_SIZE(extension->data);
  10558. break;
  10559. #endif
  10560. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10561. case TLSX_ENCRYPT_THEN_MAC:
  10562. ret = ETM_GET_SIZE(msgType, &length);
  10563. break;
  10564. #endif /* HAVE_ENCRYPT_THEN_MAC */
  10565. #ifdef WOLFSSL_TLS13
  10566. case TLSX_SUPPORTED_VERSIONS:
  10567. ret = SV_GET_SIZE(extension->data, msgType, &length);
  10568. break;
  10569. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10570. case TLSX_COOKIE:
  10571. ret = CKE_GET_SIZE((Cookie*)extension->data, msgType, &length);
  10572. break;
  10573. #endif
  10574. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10575. case TLSX_PRE_SHARED_KEY:
  10576. ret = PSK_GET_SIZE((PreSharedKey*)extension->data, msgType,
  10577. &length);
  10578. break;
  10579. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10580. ret = PKM_GET_SIZE((byte)extension->val, msgType, &length);
  10581. break;
  10582. #endif
  10583. #ifdef WOLFSSL_EARLY_DATA
  10584. case TLSX_EARLY_DATA:
  10585. ret = EDI_GET_SIZE(msgType, &length);
  10586. break;
  10587. #endif
  10588. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10589. case TLSX_POST_HANDSHAKE_AUTH:
  10590. ret = PHA_GET_SIZE(msgType, &length);
  10591. break;
  10592. #endif
  10593. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10594. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10595. length += SAC_GET_SIZE(extension->data);
  10596. break;
  10597. #endif
  10598. case TLSX_KEY_SHARE:
  10599. length += KS_GET_SIZE((KeyShareEntry*)extension->data, msgType);
  10600. break;
  10601. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10602. case TLSX_CERTIFICATE_AUTHORITIES:
  10603. length += CAN_GET_SIZE(extension->data);
  10604. break;
  10605. #endif
  10606. #endif
  10607. #ifdef WOLFSSL_SRTP
  10608. case TLSX_USE_SRTP:
  10609. length += SRTP_GET_SIZE((TlsxSrtp*)extension->data);
  10610. break;
  10611. #endif
  10612. #ifdef HAVE_RPK
  10613. case TLSX_CLIENT_CERTIFICATE_TYPE:
  10614. length += CCT_GET_SIZE((WOLFSSL*)extension->data, msgType);
  10615. break;
  10616. case TLSX_SERVER_CERTIFICATE_TYPE:
  10617. length += SCT_GET_SIZE((WOLFSSL*)extension->data, msgType);
  10618. break;
  10619. #endif /* HAVE_RPK */
  10620. #ifdef WOLFSSL_QUIC
  10621. case TLSX_KEY_QUIC_TP_PARAMS:
  10622. FALL_THROUGH; /* followed by */
  10623. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10624. length += QTP_GET_SIZE(extension);
  10625. break;
  10626. #endif
  10627. #ifdef WOLFSSL_DTLS_CID
  10628. case TLSX_CONNECTION_ID:
  10629. length += CID_GET_SIZE((byte*)extension->data);
  10630. break;
  10631. #endif /* WOLFSSL_DTLS_CID */
  10632. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10633. case TLSX_ECH:
  10634. length += ECH_GET_SIZE((WOLFSSL_ECH*)extension->data);
  10635. break;
  10636. #endif
  10637. default:
  10638. break;
  10639. }
  10640. /* marks the extension as processed so ctx level */
  10641. /* extensions don't overlap with ssl level ones. */
  10642. TURN_ON(semaphore, TLSX_ToSemaphore(extension->type));
  10643. }
  10644. *pLength += length;
  10645. return ret;
  10646. }
  10647. /** Writes the extensions of a list in a buffer. */
  10648. static int TLSX_Write(TLSX* list, byte* output, byte* semaphore,
  10649. byte msgType, word16* pOffset)
  10650. {
  10651. int ret = 0;
  10652. TLSX* extension;
  10653. word16 offset = 0;
  10654. word16 length_offset = 0;
  10655. byte isRequest = (msgType == client_hello ||
  10656. msgType == certificate_request);
  10657. while ((extension = list)) {
  10658. list = extension->next;
  10659. /* only extensions marked as response are written in a response. */
  10660. if (!isRequest && !extension->resp)
  10661. continue; /* skip! */
  10662. /* ssl level extensions are expected to override ctx level ones. */
  10663. if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type)))
  10664. continue; /* skip! */
  10665. /* writes extension type. */
  10666. c16toa(extension->type, output + offset);
  10667. offset += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN;
  10668. length_offset = offset;
  10669. /* extension data should be written internally. */
  10670. switch (extension->type) {
  10671. #ifdef WOLFSSL_DUAL_ALG_CERTS
  10672. case TLSX_CKS:
  10673. WOLFSSL_MSG("CKS extension to write");
  10674. offset += CKS_WRITE(((WOLFSSL*)extension->data),
  10675. output + offset);
  10676. break;
  10677. #endif
  10678. #ifdef HAVE_SNI
  10679. case TLSX_SERVER_NAME:
  10680. if (isRequest) {
  10681. WOLFSSL_MSG("SNI extension to write");
  10682. offset += SNI_WRITE((SNI*)extension->data, output + offset);
  10683. }
  10684. break;
  10685. #endif
  10686. case TLSX_TRUSTED_CA_KEYS:
  10687. WOLFSSL_MSG("Trusted CA Indication extension to write");
  10688. if (isRequest) {
  10689. offset += TCA_WRITE((TCA*)extension->data, output + offset);
  10690. }
  10691. break;
  10692. case TLSX_MAX_FRAGMENT_LENGTH:
  10693. WOLFSSL_MSG("Max Fragment Length extension to write");
  10694. offset += MFL_WRITE((byte*)extension->data, output + offset);
  10695. break;
  10696. case TLSX_EXTENDED_MASTER_SECRET:
  10697. WOLFSSL_MSG("Extended Master Secret");
  10698. /* always empty. */
  10699. break;
  10700. case TLSX_TRUNCATED_HMAC:
  10701. WOLFSSL_MSG("Truncated HMAC extension to write");
  10702. /* always empty. */
  10703. break;
  10704. case TLSX_SUPPORTED_GROUPS:
  10705. WOLFSSL_MSG("Supported Groups extension to write");
  10706. offset += EC_WRITE((SupportedCurve*)extension->data,
  10707. output + offset);
  10708. break;
  10709. case TLSX_EC_POINT_FORMATS:
  10710. WOLFSSL_MSG("Point Formats extension to write");
  10711. offset += PF_WRITE((PointFormat*)extension->data,
  10712. output + offset);
  10713. break;
  10714. case TLSX_STATUS_REQUEST:
  10715. WOLFSSL_MSG("Certificate Status Request extension to write");
  10716. offset += CSR_WRITE((CertificateStatusRequest*)extension->data,
  10717. output + offset, isRequest);
  10718. break;
  10719. case TLSX_STATUS_REQUEST_V2:
  10720. WOLFSSL_MSG("Certificate Status Request v2 extension to write");
  10721. offset += CSR2_WRITE(
  10722. (CertificateStatusRequestItemV2*)extension->data,
  10723. output + offset, isRequest);
  10724. break;
  10725. case TLSX_RENEGOTIATION_INFO:
  10726. WOLFSSL_MSG("Secure Renegotiation extension to write");
  10727. offset += SCR_WRITE((SecureRenegotiation*)extension->data,
  10728. output + offset, isRequest);
  10729. break;
  10730. case TLSX_SESSION_TICKET:
  10731. WOLFSSL_MSG("Session Ticket extension to write");
  10732. offset += WOLF_STK_WRITE((SessionTicket*)extension->data,
  10733. output + offset, isRequest);
  10734. break;
  10735. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10736. WOLFSSL_MSG("ALPN extension to write");
  10737. offset += ALPN_WRITE((ALPN*)extension->data, output + offset);
  10738. break;
  10739. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10740. case TLSX_SIGNATURE_ALGORITHMS:
  10741. WOLFSSL_MSG("Signature Algorithms extension to write");
  10742. offset += SA_WRITE(extension->data, output + offset);
  10743. break;
  10744. #endif
  10745. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10746. case TLSX_ENCRYPT_THEN_MAC:
  10747. WOLFSSL_MSG("Encrypt-Then-Mac extension to write");
  10748. ret = ETM_WRITE(extension->data, output, msgType, &offset);
  10749. break;
  10750. #endif /* HAVE_ENCRYPT_THEN_MAC */
  10751. #ifdef WOLFSSL_TLS13
  10752. case TLSX_SUPPORTED_VERSIONS:
  10753. WOLFSSL_MSG("Supported Versions extension to write");
  10754. ret = SV_WRITE(extension->data, output + offset, msgType, &offset);
  10755. break;
  10756. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10757. case TLSX_COOKIE:
  10758. WOLFSSL_MSG("Cookie extension to write");
  10759. ret = CKE_WRITE((Cookie*)extension->data, output + offset,
  10760. msgType, &offset);
  10761. break;
  10762. #endif
  10763. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10764. case TLSX_PRE_SHARED_KEY:
  10765. WOLFSSL_MSG("Pre-Shared Key extension to write");
  10766. ret = PSK_WRITE((PreSharedKey*)extension->data, output + offset,
  10767. msgType, &offset);
  10768. break;
  10769. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10770. WOLFSSL_MSG("PSK Key Exchange Modes extension to write");
  10771. ret = PKM_WRITE((byte)extension->val, output + offset, msgType,
  10772. &offset);
  10773. break;
  10774. #endif
  10775. #ifdef WOLFSSL_EARLY_DATA
  10776. case TLSX_EARLY_DATA:
  10777. WOLFSSL_MSG("Early Data extension to write");
  10778. ret = EDI_WRITE(extension->val, output + offset, msgType,
  10779. &offset);
  10780. break;
  10781. #endif
  10782. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10783. case TLSX_POST_HANDSHAKE_AUTH:
  10784. WOLFSSL_MSG("Post-Handshake Authentication extension to write");
  10785. ret = PHA_WRITE(output + offset, msgType, &offset);
  10786. break;
  10787. #endif
  10788. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10789. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10790. WOLFSSL_MSG("Signature Algorithms extension to write");
  10791. offset += SAC_WRITE(extension->data, output + offset);
  10792. break;
  10793. #endif
  10794. case TLSX_KEY_SHARE:
  10795. WOLFSSL_MSG("Key Share extension to write");
  10796. offset += KS_WRITE((KeyShareEntry*)extension->data,
  10797. output + offset, msgType);
  10798. break;
  10799. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10800. case TLSX_CERTIFICATE_AUTHORITIES:
  10801. WOLFSSL_MSG("Certificate Authorities extension to write");
  10802. offset += CAN_WRITE(extension->data, output + offset);
  10803. break;
  10804. #endif
  10805. #endif
  10806. #ifdef WOLFSSL_SRTP
  10807. case TLSX_USE_SRTP:
  10808. WOLFSSL_MSG("SRTP extension to write");
  10809. offset += SRTP_WRITE((TlsxSrtp*)extension->data, output+offset);
  10810. break;
  10811. #endif
  10812. #ifdef HAVE_RPK
  10813. case TLSX_CLIENT_CERTIFICATE_TYPE:
  10814. WOLFSSL_MSG("Client Certificate Type extension to write");
  10815. offset += CCT_WRITE(extension->data, output + offset, msgType);
  10816. break;
  10817. case TLSX_SERVER_CERTIFICATE_TYPE:
  10818. WOLFSSL_MSG("Server Certificate Type extension to write");
  10819. offset += SCT_WRITE(extension->data, output + offset, msgType);
  10820. break;
  10821. #endif /* HAVE_RPK */
  10822. #ifdef WOLFSSL_QUIC
  10823. case TLSX_KEY_QUIC_TP_PARAMS:
  10824. FALL_THROUGH;
  10825. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10826. WOLFSSL_MSG("QUIC transport parameter to write");
  10827. offset += QTP_WRITE((QuicTransportParam*)extension->data,
  10828. output + offset);
  10829. break;
  10830. #endif
  10831. #ifdef WOLFSSL_DTLS_CID
  10832. case TLSX_CONNECTION_ID:
  10833. WOLFSSL_MSG("Connection ID extension to write");
  10834. offset += CID_WRITE((byte*)extension->data, output+offset);
  10835. break;
  10836. #endif /* WOLFSSL_DTLS_CID */
  10837. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10838. case TLSX_ECH:
  10839. WOLFSSL_MSG("ECH extension to write");
  10840. ret = ECH_WRITE((WOLFSSL_ECH*)extension->data,
  10841. output + offset, &offset);
  10842. break;
  10843. #endif
  10844. default:
  10845. break;
  10846. }
  10847. /* writes extension data length. */
  10848. c16toa(offset - length_offset, output + length_offset - OPAQUE16_LEN);
  10849. /* marks the extension as processed so ctx level */
  10850. /* extensions don't overlap with ssl level ones. */
  10851. TURN_ON(semaphore, TLSX_ToSemaphore(extension->type));
  10852. /* if we encountered an error propagate it */
  10853. if (ret != 0)
  10854. break;
  10855. }
  10856. *pOffset += offset;
  10857. return ret;
  10858. }
  10859. #ifdef HAVE_SUPPORTED_CURVES
  10860. /* Populates the default supported groups / curves */
  10861. static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions)
  10862. {
  10863. int ret = WOLFSSL_SUCCESS;
  10864. #ifdef WOLFSSL_TLS13
  10865. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10866. if (ssl->options.resuming && ssl->session->namedGroup != 0) {
  10867. return TLSX_UseSupportedCurve(extensions, ssl->session->namedGroup,
  10868. ssl->heap);
  10869. }
  10870. #endif
  10871. if (ssl->numGroups != 0) {
  10872. int i;
  10873. for (i = 0; i < ssl->numGroups; i++) {
  10874. ret = TLSX_UseSupportedCurve(extensions, ssl->group[i], ssl->heap);
  10875. if (ret != WOLFSSL_SUCCESS)
  10876. return ret;
  10877. }
  10878. return WOLFSSL_SUCCESS;
  10879. }
  10880. #endif /* WOLFSSL_TLS13 */
  10881. #if defined(HAVE_ECC)
  10882. /* list in order by strength, since not all servers choose by strength */
  10883. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  10884. #ifndef NO_ECC_SECP
  10885. ret = TLSX_UseSupportedCurve(extensions,
  10886. WOLFSSL_ECC_SECP521R1, ssl->heap);
  10887. if (ret != WOLFSSL_SUCCESS) return ret;
  10888. #endif
  10889. #endif
  10890. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  10891. #ifdef HAVE_ECC_BRAINPOOL
  10892. ret = TLSX_UseSupportedCurve(extensions,
  10893. WOLFSSL_ECC_BRAINPOOLP512R1, ssl->heap);
  10894. if (ret != WOLFSSL_SUCCESS) return ret;
  10895. #endif
  10896. #endif
  10897. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  10898. #ifndef NO_ECC_SECP
  10899. ret = TLSX_UseSupportedCurve(extensions,
  10900. WOLFSSL_ECC_SECP384R1, ssl->heap);
  10901. if (ret != WOLFSSL_SUCCESS) return ret;
  10902. #endif
  10903. #ifdef HAVE_ECC_BRAINPOOL
  10904. ret = TLSX_UseSupportedCurve(extensions,
  10905. WOLFSSL_ECC_BRAINPOOLP384R1, ssl->heap);
  10906. if (ret != WOLFSSL_SUCCESS) return ret;
  10907. #endif
  10908. #endif
  10909. #endif /* HAVE_ECC */
  10910. #ifndef HAVE_FIPS
  10911. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  10912. ret = TLSX_UseSupportedCurve(extensions,
  10913. WOLFSSL_ECC_X448, ssl->heap);
  10914. if (ret != WOLFSSL_SUCCESS) return ret;
  10915. #endif
  10916. #endif /* HAVE_FIPS */
  10917. #if defined(HAVE_ECC) && defined(HAVE_SUPPORTED_CURVES)
  10918. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  10919. #ifndef NO_ECC_SECP
  10920. ret = TLSX_UseSupportedCurve(extensions,
  10921. WOLFSSL_ECC_SECP256R1, ssl->heap);
  10922. if (ret != WOLFSSL_SUCCESS) return ret;
  10923. #endif
  10924. #ifdef HAVE_ECC_KOBLITZ
  10925. ret = TLSX_UseSupportedCurve(extensions,
  10926. WOLFSSL_ECC_SECP256K1, ssl->heap);
  10927. if (ret != WOLFSSL_SUCCESS) return ret;
  10928. #endif
  10929. #ifdef HAVE_ECC_BRAINPOOL
  10930. ret = TLSX_UseSupportedCurve(extensions,
  10931. WOLFSSL_ECC_BRAINPOOLP256R1, ssl->heap);
  10932. if (ret != WOLFSSL_SUCCESS) return ret;
  10933. #endif
  10934. #ifdef WOLFSSL_SM2
  10935. ret = TLSX_UseSupportedCurve(extensions,
  10936. WOLFSSL_ECC_SM2P256V1, ssl->heap);
  10937. if (ret != WOLFSSL_SUCCESS) return ret;
  10938. #endif
  10939. #endif
  10940. #endif /* HAVE_ECC */
  10941. #ifndef HAVE_FIPS
  10942. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  10943. ret = TLSX_UseSupportedCurve(extensions,
  10944. WOLFSSL_ECC_X25519, ssl->heap);
  10945. if (ret != WOLFSSL_SUCCESS) return ret;
  10946. #endif
  10947. #endif /* HAVE_FIPS */
  10948. #if defined(HAVE_ECC) && defined(HAVE_SUPPORTED_CURVES)
  10949. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  10950. #ifndef NO_ECC_SECP
  10951. ret = TLSX_UseSupportedCurve(extensions,
  10952. WOLFSSL_ECC_SECP224R1, ssl->heap);
  10953. if (ret != WOLFSSL_SUCCESS) return ret;
  10954. #endif
  10955. #ifdef HAVE_ECC_KOBLITZ
  10956. ret = TLSX_UseSupportedCurve(extensions,
  10957. WOLFSSL_ECC_SECP224K1, ssl->heap);
  10958. if (ret != WOLFSSL_SUCCESS) return ret;
  10959. #endif
  10960. #endif
  10961. #ifndef HAVE_FIPS
  10962. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  10963. #ifndef NO_ECC_SECP
  10964. ret = TLSX_UseSupportedCurve(extensions,
  10965. WOLFSSL_ECC_SECP192R1, ssl->heap);
  10966. if (ret != WOLFSSL_SUCCESS) return ret;
  10967. #endif
  10968. #ifdef HAVE_ECC_KOBLITZ
  10969. ret = TLSX_UseSupportedCurve(extensions,
  10970. WOLFSSL_ECC_SECP192K1, ssl->heap);
  10971. if (ret != WOLFSSL_SUCCESS) return ret;
  10972. #endif
  10973. #endif
  10974. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  10975. #ifndef NO_ECC_SECP
  10976. ret = TLSX_UseSupportedCurve(extensions,
  10977. WOLFSSL_ECC_SECP160R1, ssl->heap);
  10978. if (ret != WOLFSSL_SUCCESS) return ret;
  10979. #endif
  10980. #ifdef HAVE_ECC_SECPR2
  10981. ret = TLSX_UseSupportedCurve(extensions,
  10982. WOLFSSL_ECC_SECP160R2, ssl->heap);
  10983. if (ret != WOLFSSL_SUCCESS) return ret;
  10984. #endif
  10985. #ifdef HAVE_ECC_KOBLITZ
  10986. ret = TLSX_UseSupportedCurve(extensions,
  10987. WOLFSSL_ECC_SECP160K1, ssl->heap);
  10988. if (ret != WOLFSSL_SUCCESS) return ret;
  10989. #endif
  10990. #endif
  10991. #endif /* HAVE_FIPS */
  10992. #endif /* HAVE_ECC */
  10993. #ifndef NO_DH
  10994. /* Add FFDHE supported groups. */
  10995. #ifdef HAVE_FFDHE_8192
  10996. if (8192/8 >= ssl->options.minDhKeySz &&
  10997. 8192/8 <= ssl->options.maxDhKeySz) {
  10998. ret = TLSX_UseSupportedCurve(extensions,
  10999. WOLFSSL_FFDHE_8192, ssl->heap);
  11000. if (ret != WOLFSSL_SUCCESS)
  11001. return ret;
  11002. }
  11003. #endif
  11004. #ifdef HAVE_FFDHE_6144
  11005. if (6144/8 >= ssl->options.minDhKeySz &&
  11006. 6144/8 <= ssl->options.maxDhKeySz) {
  11007. ret = TLSX_UseSupportedCurve(extensions,
  11008. WOLFSSL_FFDHE_6144, ssl->heap);
  11009. if (ret != WOLFSSL_SUCCESS)
  11010. return ret;
  11011. }
  11012. #endif
  11013. #ifdef HAVE_FFDHE_4096
  11014. if (4096/8 >= ssl->options.minDhKeySz &&
  11015. 4096/8 <= ssl->options.maxDhKeySz) {
  11016. ret = TLSX_UseSupportedCurve(extensions,
  11017. WOLFSSL_FFDHE_4096, ssl->heap);
  11018. if (ret != WOLFSSL_SUCCESS)
  11019. return ret;
  11020. }
  11021. #endif
  11022. #ifdef HAVE_FFDHE_3072
  11023. if (3072/8 >= ssl->options.minDhKeySz &&
  11024. 3072/8 <= ssl->options.maxDhKeySz) {
  11025. ret = TLSX_UseSupportedCurve(extensions,
  11026. WOLFSSL_FFDHE_3072, ssl->heap);
  11027. if (ret != WOLFSSL_SUCCESS)
  11028. return ret;
  11029. }
  11030. #endif
  11031. #ifdef HAVE_FFDHE_2048
  11032. if (2048/8 >= ssl->options.minDhKeySz &&
  11033. 2048/8 <= ssl->options.maxDhKeySz) {
  11034. ret = TLSX_UseSupportedCurve(extensions,
  11035. WOLFSSL_FFDHE_2048, ssl->heap);
  11036. if (ret != WOLFSSL_SUCCESS)
  11037. return ret;
  11038. }
  11039. #endif
  11040. #endif
  11041. #ifdef HAVE_PQC
  11042. #ifdef WOLFSSL_WC_KYBER
  11043. #ifdef WOLFSSL_KYBER512
  11044. if (ret == WOLFSSL_SUCCESS)
  11045. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1,
  11046. ssl->heap);
  11047. #endif
  11048. #ifdef WOLFSSL_KYBER768
  11049. if (ret == WOLFSSL_SUCCESS)
  11050. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3,
  11051. ssl->heap);
  11052. #endif
  11053. #ifdef WOLFSSL_KYBER768
  11054. if (ret == WOLFSSL_SUCCESS)
  11055. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5,
  11056. ssl->heap);
  11057. #endif
  11058. #elif defined(HAVE_LIBOQS)
  11059. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap);
  11060. if (ret == WOLFSSL_SUCCESS)
  11061. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3,
  11062. ssl->heap);
  11063. if (ret == WOLFSSL_SUCCESS)
  11064. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5,
  11065. ssl->heap);
  11066. if (ret == WOLFSSL_SUCCESS)
  11067. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_KYBER_LEVEL1,
  11068. ssl->heap);
  11069. if (ret == WOLFSSL_SUCCESS)
  11070. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_KYBER_LEVEL3,
  11071. ssl->heap);
  11072. if (ret == WOLFSSL_SUCCESS)
  11073. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_KYBER_LEVEL5,
  11074. ssl->heap);
  11075. #elif defined(HAVE_PQM4)
  11076. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap);
  11077. #endif /* HAVE_LIBOQS */
  11078. #endif /* HAVE_PQC */
  11079. (void)ssl;
  11080. (void)extensions;
  11081. return ret;
  11082. }
  11083. #endif /* HAVE_SUPPORTED_CURVES */
  11084. int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer)
  11085. {
  11086. int ret = 0;
  11087. byte* public_key = NULL;
  11088. word16 public_key_len = 0;
  11089. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  11090. int usingPSK = 0;
  11091. #endif
  11092. #if defined(HAVE_SUPPORTED_CURVES) && defined(WOLFSSL_TLS13)
  11093. TLSX* extension = NULL;
  11094. word16 namedGroup = WOLFSSL_NAMED_GROUP_INVALID;
  11095. #endif
  11096. /* server will add extension depending on what is parsed from client */
  11097. if (!isServer) {
  11098. #if defined(HAVE_RPK)
  11099. ret = TLSX_ClientCertificateType_Use(ssl, isServer);
  11100. if (ret != 0)
  11101. return ret;
  11102. ret = TLSX_ServerCertificateType_Use(ssl, isServer);
  11103. if (ret != 0)
  11104. return ret;
  11105. #endif /* HAVE_RPK */
  11106. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  11107. if (!ssl->options.disallowEncThenMac) {
  11108. ret = TLSX_EncryptThenMac_Use(ssl);
  11109. if (ret != 0)
  11110. return ret;
  11111. }
  11112. #endif
  11113. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  11114. defined(HAVE_CURVE448)) && defined(HAVE_SUPPORTED_CURVES)
  11115. if (!ssl->options.userCurves && !ssl->ctx->userCurves) {
  11116. if (TLSX_Find(ssl->ctx->extensions,
  11117. TLSX_SUPPORTED_GROUPS) == NULL) {
  11118. ret = TLSX_PopulateSupportedGroups(ssl, &ssl->extensions);
  11119. if (ret != WOLFSSL_SUCCESS)
  11120. return ret;
  11121. }
  11122. }
  11123. if ((!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade) &&
  11124. TLSX_Find(ssl->ctx->extensions, TLSX_EC_POINT_FORMATS) == NULL &&
  11125. TLSX_Find(ssl->extensions, TLSX_EC_POINT_FORMATS) == NULL) {
  11126. ret = TLSX_UsePointFormat(&ssl->extensions,
  11127. WOLFSSL_EC_PF_UNCOMPRESSED, ssl->heap);
  11128. if (ret != WOLFSSL_SUCCESS)
  11129. return ret;
  11130. }
  11131. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && HAVE_SUPPORTED_CURVES */
  11132. #ifdef WOLFSSL_SRTP
  11133. if (ssl->options.dtls && ssl->dtlsSrtpProfiles != 0) {
  11134. WOLFSSL_MSG("Adding DTLS SRTP extension");
  11135. if ((ret = TLSX_UseSRTP(&ssl->extensions, ssl->dtlsSrtpProfiles,
  11136. ssl->heap)) != 0) {
  11137. return ret;
  11138. }
  11139. }
  11140. #endif
  11141. #ifdef WOLFSSL_DUAL_ALG_CERTS
  11142. if ((IsAtLeastTLSv1_3(ssl->version)) && (ssl->sigSpec != NULL)) {
  11143. WOLFSSL_MSG("Adding CKS extension");
  11144. if ((ret = TLSX_UseCKS(&ssl->extensions, ssl, ssl->heap)) != 0) {
  11145. return ret;
  11146. }
  11147. }
  11148. #endif
  11149. } /* is not server */
  11150. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11151. WOLFSSL_MSG("Adding signature algorithms extension");
  11152. if ((ret = TLSX_SetSignatureAlgorithms(&ssl->extensions, ssl, ssl->heap))
  11153. != 0) {
  11154. return ret;
  11155. }
  11156. #else
  11157. ret = 0;
  11158. #endif
  11159. #ifdef WOLFSSL_TLS13
  11160. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11161. if (isServer && IsAtLeastTLSv1_3(ssl->version)) {
  11162. if (SSL_CA_NAMES(ssl) != NULL) {
  11163. WOLFSSL_MSG("Adding certificate authorities extension");
  11164. if ((ret = TLSX_Push(&ssl->extensions,
  11165. TLSX_CERTIFICATE_AUTHORITIES, ssl, ssl->heap)) != 0) {
  11166. return ret;
  11167. }
  11168. }
  11169. }
  11170. #endif
  11171. if (!isServer && IsAtLeastTLSv1_3(ssl->version)) {
  11172. /* Add mandatory TLS v1.3 extension: supported version */
  11173. WOLFSSL_MSG("Adding supported versions extension");
  11174. if ((ret = TLSX_SetSupportedVersions(&ssl->extensions, ssl,
  11175. ssl->heap)) != 0) {
  11176. return ret;
  11177. }
  11178. #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && \
  11179. !defined(HAVE_CURVE448) && defined(HAVE_SUPPORTED_CURVES)
  11180. if (TLSX_Find(ssl->ctx->extensions, TLSX_SUPPORTED_GROUPS) == NULL) {
  11181. /* Put in DH groups for TLS 1.3 only. */
  11182. ret = TLSX_PopulateSupportedGroups(ssl, &ssl->extensions);
  11183. if (ret != WOLFSSL_SUCCESS)
  11184. return ret;
  11185. /* ret value will be overwritten in !NO_PSK case */
  11186. #ifdef NO_PSK
  11187. ret = 0;
  11188. #endif
  11189. }
  11190. #endif /* !(HAVE_ECC || CURVE25519 || CURVE448) && HAVE_SUPPORTED_CURVES */
  11191. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11192. if (ssl->certHashSigAlgoSz > 0) {
  11193. WOLFSSL_MSG("Adding signature algorithms cert extension");
  11194. if ((ret = TLSX_SetSignatureAlgorithmsCert(&ssl->extensions,
  11195. ssl, ssl->heap)) != 0) {
  11196. return ret;
  11197. }
  11198. }
  11199. #endif
  11200. #if defined(HAVE_SUPPORTED_CURVES)
  11201. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  11202. if (extension == NULL) {
  11203. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11204. if (ssl->options.resuming && ssl->session->namedGroup != 0)
  11205. namedGroup = ssl->session->namedGroup;
  11206. else
  11207. #endif
  11208. if (ssl->numGroups > 0) {
  11209. int set = 0;
  11210. int i, j;
  11211. /* try to find the highest element in ssl->group[]
  11212. * that is contained in preferredGroup[].
  11213. */
  11214. namedGroup = preferredGroup[0];
  11215. for (i = 0; i < ssl->numGroups && !set; i++) {
  11216. for (j = 0; preferredGroup[j] != WOLFSSL_NAMED_GROUP_INVALID; j++) {
  11217. if (preferredGroup[j] == ssl->group[i]
  11218. #ifdef HAVE_LIBOQS
  11219. && TLSX_KeyShare_IsSupported(preferredGroup[j])
  11220. #endif
  11221. ) {
  11222. namedGroup = ssl->group[i];
  11223. set = 1;
  11224. break;
  11225. }
  11226. }
  11227. }
  11228. if (!set)
  11229. namedGroup = WOLFSSL_NAMED_GROUP_INVALID;
  11230. }
  11231. else {
  11232. /* Choose the most preferred group. */
  11233. namedGroup = preferredGroup[0];
  11234. #ifdef HAVE_LIBOQS
  11235. if (!TLSX_KeyShare_IsSupported(namedGroup)) {
  11236. int i = 1;
  11237. for (;preferredGroup[i] != WOLFSSL_NAMED_GROUP_INVALID;
  11238. i++) {
  11239. if (TLSX_KeyShare_IsSupported(preferredGroup[i]))
  11240. break;
  11241. }
  11242. namedGroup = preferredGroup[i];
  11243. }
  11244. #endif
  11245. }
  11246. }
  11247. else {
  11248. KeyShareEntry* kse = (KeyShareEntry*)extension->data;
  11249. if (kse)
  11250. namedGroup = kse->group;
  11251. }
  11252. if (namedGroup != WOLFSSL_NAMED_GROUP_INVALID) {
  11253. ret = TLSX_KeyShare_Use(ssl, namedGroup, 0, NULL, NULL,
  11254. &ssl->extensions);
  11255. if (ret != 0)
  11256. return ret;
  11257. }
  11258. #endif /* HAVE_SUPPORTED_CURVES */
  11259. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11260. TLSX_Remove(&ssl->extensions, TLSX_PRE_SHARED_KEY, ssl->heap);
  11261. #endif
  11262. #if defined(HAVE_SESSION_TICKET)
  11263. if (ssl->options.resuming && ssl->session->ticketLen > 0) {
  11264. WOLFSSL_SESSION* sess = ssl->session;
  11265. #ifdef WOLFSSL_32BIT_MILLI_TIME
  11266. word32 now, milli;
  11267. #else
  11268. word64 now, milli;
  11269. #endif
  11270. if (sess->ticketLen > MAX_PSK_ID_LEN) {
  11271. WOLFSSL_MSG("Session ticket length for PSK ext is too large");
  11272. return BUFFER_ERROR;
  11273. }
  11274. /* Determine the MAC algorithm for the cipher suite used. */
  11275. ssl->options.cipherSuite0 = sess->cipherSuite0;
  11276. ssl->options.cipherSuite = sess->cipherSuite;
  11277. ret = SetCipherSpecs(ssl);
  11278. if (ret != 0)
  11279. return ret;
  11280. now = TimeNowInMilliseconds();
  11281. if (now == 0)
  11282. return GETTIME_ERROR;
  11283. #ifdef WOLFSSL_32BIT_MILLI_TIME
  11284. if (now < sess->ticketSeen)
  11285. milli = (0xFFFFFFFFU - sess->ticketSeen) + 1 + now;
  11286. else
  11287. milli = now - sess->ticketSeen;
  11288. milli += sess->ticketAdd;
  11289. /* Pre-shared key is mandatory extension for resumption. */
  11290. ret = TLSX_PreSharedKey_Use(&ssl->extensions, sess->ticket,
  11291. sess->ticketLen, milli, ssl->specs.mac_algorithm,
  11292. ssl->options.cipherSuite0, ssl->options.cipherSuite, 1,
  11293. NULL, ssl->heap);
  11294. #else
  11295. milli = now - sess->ticketSeen + sess->ticketAdd;
  11296. /* Pre-shared key is mandatory extension for resumption. */
  11297. ret = TLSX_PreSharedKey_Use(&ssl->extensions, sess->ticket,
  11298. sess->ticketLen, (word32)milli, ssl->specs.mac_algorithm,
  11299. ssl->options.cipherSuite0, ssl->options.cipherSuite, 1,
  11300. NULL, ssl->heap);
  11301. #endif
  11302. if (ret != 0)
  11303. return ret;
  11304. usingPSK = 1;
  11305. }
  11306. #endif
  11307. #ifndef NO_PSK
  11308. #ifndef WOLFSSL_PSK_ONE_ID
  11309. if (ssl->options.client_psk_cs_cb != NULL) {
  11310. int i;
  11311. const Suites* suites = WOLFSSL_SUITES(ssl);
  11312. for (i = 0; i < suites->suiteSz; i += 2) {
  11313. byte cipherSuite0 = suites->suites[i + 0];
  11314. byte cipherSuite = suites->suites[i + 1];
  11315. unsigned int keySz;
  11316. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11317. int cnt = 0;
  11318. #endif
  11319. #ifdef HAVE_NULL_CIPHER
  11320. if (cipherSuite0 == ECC_BYTE ||
  11321. cipherSuite0 == ECDHE_PSK_BYTE) {
  11322. if (cipherSuite != TLS_SHA256_SHA256 &&
  11323. cipherSuite != TLS_SHA384_SHA384) {
  11324. continue;
  11325. }
  11326. }
  11327. else
  11328. #endif
  11329. #if (defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)) && \
  11330. defined(WOLFSSL_SM3)
  11331. if (cipherSuite0 == CIPHER_BYTE) {
  11332. if ((cipherSuite != TLS_SM4_GCM_SM3) &&
  11333. (cipherSuite != TLS_SM4_CCM_SM3)) {
  11334. continue;
  11335. }
  11336. }
  11337. else
  11338. #endif
  11339. if (cipherSuite0 != TLS13_BYTE)
  11340. continue;
  11341. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11342. do {
  11343. ssl->arrays->client_identity[0] = cnt;
  11344. #endif
  11345. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  11346. keySz = ssl->options.client_psk_cs_cb(
  11347. ssl, ssl->arrays->server_hint,
  11348. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  11349. ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
  11350. GetCipherNameInternal(cipherSuite0, cipherSuite));
  11351. if (keySz > 0) {
  11352. ssl->arrays->psk_keySz = keySz;
  11353. ret = TLSX_PreSharedKey_Use(&ssl->extensions,
  11354. (byte*)ssl->arrays->client_identity,
  11355. (word16)XSTRLEN(ssl->arrays->client_identity),
  11356. 0, SuiteMac(WOLFSSL_SUITES(ssl)->suites + i),
  11357. cipherSuite0, cipherSuite, 0, NULL, ssl->heap);
  11358. if (ret != 0)
  11359. return ret;
  11360. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11361. cnt++;
  11362. #endif
  11363. }
  11364. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11365. }
  11366. while (keySz > 0);
  11367. #endif
  11368. }
  11369. usingPSK = 1;
  11370. }
  11371. else
  11372. #endif
  11373. if (ssl->options.client_psk_cb != NULL ||
  11374. ssl->options.client_psk_tls13_cb != NULL) {
  11375. /* Default cipher suite. */
  11376. byte cipherSuite0 = TLS13_BYTE;
  11377. byte cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
  11378. int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
  11379. const char* cipherName = NULL;
  11380. if (ssl->options.client_psk_tls13_cb != NULL) {
  11381. ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(
  11382. ssl, ssl->arrays->server_hint,
  11383. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  11384. ssl->arrays->psk_key, MAX_PSK_KEY_LEN, &cipherName);
  11385. if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
  11386. &cipherSuite, &cipherSuiteFlags) != 0) {
  11387. return PSK_KEY_ERROR;
  11388. }
  11389. }
  11390. else {
  11391. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  11392. ssl->arrays->server_hint, ssl->arrays->client_identity,
  11393. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  11394. }
  11395. #if defined(OPENSSL_EXTRA)
  11396. /* OpenSSL treats 0 as a PSK key length of 0
  11397. * and meaning no PSK available.
  11398. */
  11399. if (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  11400. return PSK_KEY_ERROR;
  11401. }
  11402. if (ssl->arrays->psk_keySz > 0) {
  11403. #else
  11404. if (ssl->arrays->psk_keySz == 0 ||
  11405. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  11406. return PSK_KEY_ERROR;
  11407. }
  11408. #endif
  11409. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  11410. ssl->options.cipherSuite0 = cipherSuite0;
  11411. ssl->options.cipherSuite = cipherSuite;
  11412. (void)cipherSuiteFlags;
  11413. ret = SetCipherSpecs(ssl);
  11414. if (ret != 0)
  11415. return ret;
  11416. ret = TLSX_PreSharedKey_Use(&ssl->extensions,
  11417. (byte*)ssl->arrays->client_identity,
  11418. (word16)XSTRLEN(ssl->arrays->client_identity),
  11419. 0, ssl->specs.mac_algorithm,
  11420. cipherSuite0, cipherSuite, 0,
  11421. NULL, ssl->heap);
  11422. if (ret != 0)
  11423. return ret;
  11424. usingPSK = 1;
  11425. #if defined(OPENSSL_EXTRA)
  11426. }
  11427. #endif
  11428. }
  11429. #endif /* !NO_PSK */
  11430. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11431. /* Some servers do not generate session tickets unless
  11432. * the extension is seen in a non-resume client hello.
  11433. * We used to send it only if we were otherwise using PSK.
  11434. * Now always send it. Define NO_TLSX_PSKKEM_PLAIN_ANNOUNCE
  11435. * to revert to the old behaviour. */
  11436. #ifdef NO_TLSX_PSKKEM_PLAIN_ANNOUNCE
  11437. if (usingPSK)
  11438. #endif
  11439. {
  11440. byte modes = 0;
  11441. (void)usingPSK;
  11442. /* Pre-shared key modes: mandatory extension for resumption. */
  11443. #ifdef HAVE_SUPPORTED_CURVES
  11444. if (!ssl->options.onlyPskDheKe)
  11445. #endif
  11446. {
  11447. modes = 1 << PSK_KE;
  11448. }
  11449. #if !defined(NO_DH) || defined(HAVE_ECC) || \
  11450. defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  11451. if (!ssl->options.noPskDheKe) {
  11452. modes |= 1 << PSK_DHE_KE;
  11453. }
  11454. #endif
  11455. ret = TLSX_PskKeyModes_Use(ssl, modes);
  11456. if (ret != 0)
  11457. return ret;
  11458. }
  11459. #endif
  11460. #if defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  11461. if (!isServer && ssl->options.postHandshakeAuth) {
  11462. ret = TLSX_PostHandAuth_Use(ssl);
  11463. if (ret != 0)
  11464. return ret;
  11465. }
  11466. #endif
  11467. #if defined(HAVE_ECH)
  11468. /* GREASE ECH */
  11469. if (ssl->echConfigs == NULL) {
  11470. ret = GREASE_ECH_USE(&(ssl->extensions), ssl->heap, ssl->rng);
  11471. }
  11472. else if (ssl->echConfigs != NULL) {
  11473. ret = ECH_USE(ssl->echConfigs, &(ssl->extensions), ssl->heap,
  11474. ssl->rng);
  11475. }
  11476. #endif
  11477. }
  11478. #if defined(HAVE_ECH)
  11479. else if (IsAtLeastTLSv1_3(ssl->version)) {
  11480. if (ssl->ctx->echConfigs != NULL) {
  11481. ret = SERVER_ECH_USE(&(ssl->extensions), ssl->heap,
  11482. ssl->ctx->echConfigs);
  11483. if (ret == 0)
  11484. TLSX_SetResponse(ssl, TLSX_ECH);
  11485. }
  11486. }
  11487. #endif
  11488. #endif
  11489. (void)isServer;
  11490. (void)public_key;
  11491. (void)public_key_len;
  11492. (void)ssl;
  11493. return ret;
  11494. }
  11495. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  11496. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11497. /* because the size of ech depends on the size of other extensions we need to
  11498. * get the size with ech special and process ech last, return status */
  11499. static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType,
  11500. word16* pLength)
  11501. {
  11502. int ret = 0;
  11503. TLSX* echX = NULL;
  11504. TLSX* serverNameX = NULL;
  11505. TLSX** extensions = NULL;
  11506. #ifdef WOLFSSL_SMALL_STACK
  11507. char* tmpServerName = NULL;
  11508. #else
  11509. char tmpServerName[MAX_PUBLIC_NAME_SZ];
  11510. #endif
  11511. /* calculate the rest of the extensions length with inner ech */
  11512. if (ssl->extensions)
  11513. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  11514. if (echX == NULL && ssl->ctx && ssl->ctx->extensions)
  11515. echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH);
  11516. /* if type is outer change sni to public name */
  11517. if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) {
  11518. if (ssl->extensions) {
  11519. serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  11520. if (serverNameX != NULL)
  11521. extensions = &ssl->extensions;
  11522. }
  11523. if (serverNameX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11524. serverNameX = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  11525. extensions = &ssl->ctx->extensions;
  11526. }
  11527. /* store the inner server name */
  11528. if (serverNameX != NULL) {
  11529. char* hostName = ((SNI*)serverNameX->data)->data.host_name;
  11530. word32 hostNameSz = (word32)XSTRLEN(hostName) + 1;
  11531. #ifdef WOLFSSL_SMALL_STACK
  11532. tmpServerName = (char*)XMALLOC(hostNameSz, ssl->heap,
  11533. DYNAMIC_TYPE_TMP_BUFFER);
  11534. if (tmpServerName == NULL)
  11535. return MEMORY_E;
  11536. #else
  11537. /* truncate if too long */
  11538. if (hostNameSz > MAX_PUBLIC_NAME_SZ)
  11539. hostNameSz = MAX_PUBLIC_NAME_SZ;
  11540. #endif
  11541. XMEMCPY(tmpServerName, hostName, hostNameSz);
  11542. }
  11543. /* remove the inner server name */
  11544. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11545. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11546. ((WOLFSSL_ECH*)echX->data)->echConfig->publicName,
  11547. XSTRLEN(((WOLFSSL_ECH*)echX->data)->echConfig->publicName),
  11548. ssl->heap);
  11549. /* set the public name as the server name */
  11550. if (ret == WOLFSSL_SUCCESS)
  11551. ret = 0;
  11552. }
  11553. if (ret == 0 && ssl->extensions)
  11554. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, pLength);
  11555. if (ret == 0 && ssl->ctx && ssl->ctx->extensions)
  11556. ret = TLSX_GetSize(ssl->ctx->extensions, semaphore, msgType, pLength);
  11557. if (serverNameX != NULL) {
  11558. /* remove the public name SNI */
  11559. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11560. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11561. tmpServerName, XSTRLEN(tmpServerName), ssl->heap);
  11562. /* restore the inner server name */
  11563. if (ret == WOLFSSL_SUCCESS)
  11564. ret = 0;
  11565. }
  11566. #ifdef WOLFSSL_SMALL_STACK
  11567. XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11568. #endif
  11569. return ret;
  11570. }
  11571. #endif
  11572. /** Tells the buffered size of extensions to be sent into the client hello. */
  11573. int TLSX_GetRequestSize(WOLFSSL* ssl, byte msgType, word16* pLength)
  11574. {
  11575. int ret = 0;
  11576. word16 length = 0;
  11577. byte semaphore[SEMAPHORE_SIZE] = {0};
  11578. if (!TLSX_SupportExtensions(ssl))
  11579. return 0;
  11580. if (msgType == client_hello) {
  11581. EC_VALIDATE_REQUEST(ssl, semaphore);
  11582. PF_VALIDATE_REQUEST(ssl, semaphore);
  11583. WOLF_STK_VALIDATE_REQUEST(ssl);
  11584. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11585. if (WOLFSSL_SUITES(ssl)->hashSigAlgoSz == 0)
  11586. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11587. #endif
  11588. #if defined(WOLFSSL_TLS13)
  11589. if (!IsAtLeastTLSv1_2(ssl)) {
  11590. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11591. }
  11592. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11593. if (!IsAtLeastTLSv1_3(ssl->version)) {
  11594. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11595. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11596. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11597. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PSK_KEY_EXCHANGE_MODES));
  11598. #endif
  11599. #ifdef WOLFSSL_EARLY_DATA
  11600. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11601. #endif
  11602. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11603. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11604. #endif
  11605. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  11606. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_POST_HANDSHAKE_AUTH));
  11607. #endif
  11608. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11609. TURN_ON(semaphore,
  11610. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11611. #endif
  11612. }
  11613. #endif
  11614. #endif /* WOLFSSL_TLS13 */
  11615. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  11616. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  11617. if (!SSL_CM(ssl)->ocspStaplingEnabled) {
  11618. /* mark already sent, so it won't send it */
  11619. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11620. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11621. }
  11622. #endif
  11623. }
  11624. #ifdef WOLFSSL_TLS13
  11625. #ifndef NO_CERTS
  11626. else if (msgType == certificate_request) {
  11627. /* Don't send out any extension except those that are turned off. */
  11628. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11629. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11630. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11631. #endif
  11632. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11633. if (SSL_CA_NAMES(ssl) != NULL)
  11634. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11635. #endif
  11636. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, OID_FILTERS
  11637. * TLSX_STATUS_REQUEST
  11638. */
  11639. }
  11640. #endif
  11641. #if defined(HAVE_ECH)
  11642. if (ssl->options.useEch == 1 && msgType == client_hello) {
  11643. ret = TLSX_GetSizeWithEch(ssl, semaphore, msgType, &length);
  11644. if (ret != 0)
  11645. return ret;
  11646. }
  11647. else
  11648. #endif /* HAVE_ECH */
  11649. #endif /* WOLFSSL_TLS13 */
  11650. {
  11651. if (ssl->extensions) {
  11652. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, &length);
  11653. if (ret != 0)
  11654. return ret;
  11655. }
  11656. if (ssl->ctx && ssl->ctx->extensions) {
  11657. ret = TLSX_GetSize(ssl->ctx->extensions, semaphore, msgType,
  11658. &length);
  11659. if (ret != 0)
  11660. return ret;
  11661. }
  11662. }
  11663. #ifdef HAVE_EXTENDED_MASTER
  11664. if (msgType == client_hello && ssl->options.haveEMS &&
  11665. (!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade)) {
  11666. length += HELLO_EXT_SZ;
  11667. }
  11668. #endif
  11669. if (length)
  11670. length += OPAQUE16_LEN; /* for total length storage. */
  11671. *pLength += length;
  11672. return ret;
  11673. }
  11674. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11675. /* return status after writing the extensions with ech written last */
  11676. static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore,
  11677. byte msgType, word16* pOffset)
  11678. {
  11679. int ret = 0;
  11680. TLSX* echX = NULL;
  11681. TLSX* serverNameX = NULL;
  11682. TLSX** extensions = NULL;
  11683. #ifdef WOLFSSL_SMALL_STACK
  11684. char* tmpServerName = NULL;
  11685. #else
  11686. char tmpServerName[MAX_PUBLIC_NAME_SZ];
  11687. #endif
  11688. /* get the echX from either extensions or ctx */
  11689. if (ssl->extensions)
  11690. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  11691. if (echX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11692. /* if not NULL the semaphore will stop it from being counted */
  11693. if (echX == NULL)
  11694. echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH);
  11695. }
  11696. /* if type is outer change sni to public name */
  11697. if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) {
  11698. if (ssl->extensions) {
  11699. serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  11700. if (serverNameX != NULL)
  11701. extensions = &ssl->extensions;
  11702. }
  11703. if (serverNameX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11704. serverNameX = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  11705. extensions = &ssl->ctx->extensions;
  11706. }
  11707. /* store the inner server name */
  11708. if (serverNameX != NULL) {
  11709. char* hostName = ((SNI*)serverNameX->data)->data.host_name;
  11710. word32 hostNameSz = (word32)XSTRLEN(hostName) + 1;
  11711. #ifdef WOLFSSL_SMALL_STACK
  11712. tmpServerName = (char*)XMALLOC(hostNameSz, ssl->heap,
  11713. DYNAMIC_TYPE_TMP_BUFFER);
  11714. if (tmpServerName == NULL)
  11715. return MEMORY_E;
  11716. #else
  11717. /* truncate if too long */
  11718. if (hostNameSz > MAX_PUBLIC_NAME_SZ)
  11719. hostNameSz = MAX_PUBLIC_NAME_SZ;
  11720. #endif
  11721. XMEMCPY(tmpServerName, hostName, hostNameSz);
  11722. }
  11723. /* remove the inner server name */
  11724. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11725. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11726. ((WOLFSSL_ECH*)echX->data)->echConfig->publicName,
  11727. XSTRLEN(((WOLFSSL_ECH*)echX->data)->echConfig->publicName),
  11728. ssl->heap);
  11729. /* set the public name as the server name */
  11730. if (ret == WOLFSSL_SUCCESS)
  11731. ret = 0;
  11732. }
  11733. if (echX != NULL) {
  11734. /* turn ech on so it doesn't write, then write it last */
  11735. TURN_ON(semaphore, TLSX_ToSemaphore(echX->type));
  11736. }
  11737. if (ret == 0 && ssl->extensions) {
  11738. ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore,
  11739. msgType, pOffset);
  11740. }
  11741. if (ret == 0 && ssl->ctx && ssl->ctx->extensions) {
  11742. ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore,
  11743. msgType, pOffset);
  11744. }
  11745. if (echX != NULL) {
  11746. /* turn off and write it last */
  11747. TURN_OFF(semaphore, TLSX_ToSemaphore(echX->type));
  11748. }
  11749. if (ret == 0 && ssl->extensions) {
  11750. ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore,
  11751. msgType, pOffset);
  11752. }
  11753. if (ret == 0 && ssl->ctx && ssl->ctx->extensions) {
  11754. ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore,
  11755. msgType, pOffset);
  11756. }
  11757. if (serverNameX != NULL) {
  11758. /* remove the public name SNI */
  11759. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11760. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME, tmpServerName,
  11761. XSTRLEN(tmpServerName), ssl->heap);
  11762. /* restore the inner server name */
  11763. if (ret == WOLFSSL_SUCCESS)
  11764. ret = 0;
  11765. }
  11766. #ifdef WOLFSSL_SMALL_STACK
  11767. XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11768. #endif
  11769. return ret;
  11770. }
  11771. #endif
  11772. /** Writes the extensions to be sent into the client hello. */
  11773. int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word16* pOffset)
  11774. {
  11775. int ret = 0;
  11776. word16 offset = 0;
  11777. byte semaphore[SEMAPHORE_SIZE] = {0};
  11778. if (!TLSX_SupportExtensions(ssl) || output == NULL)
  11779. return 0;
  11780. offset += OPAQUE16_LEN; /* extensions length */
  11781. if (msgType == client_hello) {
  11782. EC_VALIDATE_REQUEST(ssl, semaphore);
  11783. PF_VALIDATE_REQUEST(ssl, semaphore);
  11784. WOLF_STK_VALIDATE_REQUEST(ssl);
  11785. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11786. if (WOLFSSL_SUITES(ssl)->hashSigAlgoSz == 0)
  11787. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11788. #endif
  11789. #ifdef WOLFSSL_TLS13
  11790. if (!IsAtLeastTLSv1_2(ssl)) {
  11791. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11792. }
  11793. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11794. if (!IsAtLeastTLSv1_3(ssl->version)) {
  11795. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11796. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11797. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PSK_KEY_EXCHANGE_MODES));
  11798. #endif
  11799. #ifdef WOLFSSL_EARLY_DATA
  11800. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11801. #endif
  11802. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11803. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11804. #endif
  11805. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  11806. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_POST_HANDSHAKE_AUTH));
  11807. #endif
  11808. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11809. TURN_ON(semaphore,
  11810. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11811. #endif
  11812. #ifdef WOLFSSL_DUAL_ALG_CERTS
  11813. TURN_ON(semaphore,
  11814. TLSX_ToSemaphore(TLSX_CKS));
  11815. #endif
  11816. }
  11817. #endif
  11818. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11819. /* Must write Pre-shared Key extension at the end in TLS v1.3.
  11820. * Must not write out Pre-shared Key extension in earlier versions of
  11821. * protocol.
  11822. */
  11823. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11824. #endif
  11825. #endif /* WOLFSSL_TLS13 */
  11826. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  11827. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  11828. /* mark already sent, so it won't send it */
  11829. if (!SSL_CM(ssl)->ocspStaplingEnabled) {
  11830. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11831. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11832. }
  11833. #endif
  11834. }
  11835. #ifdef WOLFSSL_TLS13
  11836. #ifndef NO_CERTS
  11837. else if (msgType == certificate_request) {
  11838. /* Don't send out any extension except those that are turned off. */
  11839. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11840. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11841. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11842. #endif
  11843. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11844. if (SSL_CA_NAMES(ssl) != NULL) {
  11845. TURN_OFF(semaphore,
  11846. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11847. }
  11848. #endif
  11849. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, TLSX_OID_FILTERS
  11850. * TLSX_STATUS_REQUEST
  11851. */
  11852. }
  11853. #endif
  11854. #endif
  11855. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11856. if (ssl->options.useEch == 1 && msgType == client_hello) {
  11857. ret = TLSX_WriteWithEch(ssl, output, semaphore,
  11858. msgType, &offset);
  11859. if (ret != 0)
  11860. return ret;
  11861. }
  11862. else
  11863. #endif
  11864. {
  11865. if (ssl->extensions) {
  11866. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11867. msgType, &offset);
  11868. if (ret != 0)
  11869. return ret;
  11870. }
  11871. if (ssl->ctx && ssl->ctx->extensions) {
  11872. ret = TLSX_Write(ssl->ctx->extensions, output + offset, semaphore,
  11873. msgType, &offset);
  11874. if (ret != 0)
  11875. return ret;
  11876. }
  11877. }
  11878. #ifdef HAVE_EXTENDED_MASTER
  11879. if (msgType == client_hello && ssl->options.haveEMS &&
  11880. (!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade)) {
  11881. WOLFSSL_MSG("EMS extension to write");
  11882. c16toa(HELLO_EXT_EXTMS, output + offset);
  11883. offset += HELLO_EXT_TYPE_SZ;
  11884. c16toa(0, output + offset);
  11885. offset += HELLO_EXT_SZ_SZ;
  11886. }
  11887. #endif
  11888. #ifdef WOLFSSL_TLS13
  11889. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11890. if (msgType == client_hello && IsAtLeastTLSv1_3(ssl->version)) {
  11891. /* Write out what we can of Pre-shared key extension. */
  11892. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11893. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11894. client_hello, &offset);
  11895. if (ret != 0)
  11896. return ret;
  11897. }
  11898. #endif
  11899. #endif
  11900. if (offset > OPAQUE16_LEN || msgType != client_hello)
  11901. c16toa(offset - OPAQUE16_LEN, output); /* extensions length */
  11902. *pOffset += offset;
  11903. return ret;
  11904. }
  11905. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  11906. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_SERVER)
  11907. /** Tells the buffered size of extensions to be sent into the server hello. */
  11908. int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength)
  11909. {
  11910. int ret = 0;
  11911. word16 length = 0;
  11912. byte semaphore[SEMAPHORE_SIZE] = {0};
  11913. switch (msgType) {
  11914. #ifndef NO_WOLFSSL_SERVER
  11915. case server_hello:
  11916. PF_VALIDATE_RESPONSE(ssl, semaphore);
  11917. #ifdef WOLFSSL_TLS13
  11918. if (IsAtLeastTLSv1_3(ssl->version)) {
  11919. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11920. TURN_OFF(semaphore,
  11921. TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11922. #if defined(HAVE_SUPPORTED_CURVES)
  11923. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11924. if (!ssl->options.noPskDheKe)
  11925. #endif
  11926. {
  11927. /* Expect KeyShare extension in ServerHello. */
  11928. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11929. }
  11930. #endif
  11931. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11932. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11933. #endif
  11934. #ifdef WOLFSSL_DTLS_CID
  11935. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11936. #endif
  11937. }
  11938. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11939. else {
  11940. #ifdef HAVE_SUPPORTED_CURVES
  11941. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11942. #endif
  11943. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11944. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11945. #endif
  11946. }
  11947. #endif
  11948. #endif /* WOLFSSL_TLS13 */
  11949. break;
  11950. #ifdef WOLFSSL_TLS13
  11951. case hello_retry_request:
  11952. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11953. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11954. #ifdef HAVE_SUPPORTED_CURVES
  11955. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11956. if (!ssl->options.noPskDheKe)
  11957. #endif
  11958. {
  11959. /* Expect KeyShare extension in HelloRetryRequest. */
  11960. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11961. }
  11962. #endif
  11963. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11964. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11965. #endif
  11966. break;
  11967. #endif
  11968. #ifdef WOLFSSL_TLS13
  11969. case encrypted_extensions:
  11970. /* Send out all extension except those that are turned on. */
  11971. #ifdef HAVE_ECC
  11972. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  11973. #endif
  11974. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11975. #ifdef HAVE_SESSION_TICKET
  11976. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SESSION_TICKET));
  11977. #endif
  11978. #ifdef HAVE_SUPPORTED_CURVES
  11979. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11980. #endif
  11981. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11982. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11983. #endif
  11984. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  11985. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11986. #endif
  11987. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  11988. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11989. #endif
  11990. #if defined(HAVE_SERVER_RENEGOTIATION_INFO)
  11991. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_RENEGOTIATION_INFO));
  11992. #endif
  11993. #ifdef WOLFSSL_DTLS_CID
  11994. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11995. #endif /* WOLFSSL_DTLS_CID */
  11996. break;
  11997. #ifdef WOLFSSL_EARLY_DATA
  11998. case session_ticket:
  11999. if (ssl->options.tls1_3) {
  12000. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12001. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  12002. }
  12003. break;
  12004. #endif
  12005. #endif
  12006. #endif
  12007. #ifdef WOLFSSL_TLS13
  12008. #ifndef NO_CERTS
  12009. case certificate:
  12010. /* Don't send out any extension except those that are turned off. */
  12011. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12012. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  12013. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP,
  12014. * TLSX_SERVER_CERTIFICATE_TYPE
  12015. */
  12016. break;
  12017. #endif
  12018. #endif
  12019. }
  12020. #ifdef HAVE_EXTENDED_MASTER
  12021. if (ssl->options.haveEMS && msgType == server_hello &&
  12022. !IsAtLeastTLSv1_3(ssl->version)) {
  12023. length += HELLO_EXT_SZ;
  12024. }
  12025. #endif
  12026. if (TLSX_SupportExtensions(ssl)) {
  12027. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, &length);
  12028. if (ret != 0)
  12029. return ret;
  12030. }
  12031. /* All the response data is set at the ssl object only, so no ctx here. */
  12032. if (length || msgType != server_hello)
  12033. length += OPAQUE16_LEN; /* for total length storage. */
  12034. *pLength += length;
  12035. return ret;
  12036. }
  12037. /** Writes the server hello extensions into a buffer. */
  12038. int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset)
  12039. {
  12040. int ret = 0;
  12041. word16 offset = 0;
  12042. if (TLSX_SupportExtensions(ssl) && output) {
  12043. byte semaphore[SEMAPHORE_SIZE] = {0};
  12044. switch (msgType) {
  12045. #ifndef NO_WOLFSSL_SERVER
  12046. case server_hello:
  12047. PF_VALIDATE_RESPONSE(ssl, semaphore);
  12048. #ifdef WOLFSSL_TLS13
  12049. if (IsAtLeastTLSv1_3(ssl->version)) {
  12050. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12051. TURN_OFF(semaphore,
  12052. TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  12053. #ifdef HAVE_SUPPORTED_CURVES
  12054. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12055. if (!ssl->options.noPskDheKe)
  12056. #endif
  12057. {
  12058. /* Write out KeyShare in ServerHello. */
  12059. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  12060. }
  12061. #endif
  12062. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12063. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  12064. #endif
  12065. #ifdef WOLFSSL_DTLS_CID
  12066. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  12067. #endif /* WOLFSSL_DTLS_CID */
  12068. }
  12069. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  12070. else {
  12071. #ifdef HAVE_SUPPORTED_CURVES
  12072. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  12073. #endif
  12074. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12075. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  12076. #endif
  12077. }
  12078. #endif
  12079. #endif
  12080. break;
  12081. #ifdef WOLFSSL_TLS13
  12082. case hello_retry_request:
  12083. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12084. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  12085. #ifdef HAVE_SUPPORTED_CURVES
  12086. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12087. if (!ssl->options.noPskDheKe)
  12088. #endif
  12089. {
  12090. /* Write out KeyShare in HelloRetryRequest. */
  12091. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  12092. }
  12093. #endif
  12094. /* Cookie is written below as last extension. */
  12095. break;
  12096. #endif
  12097. #ifdef WOLFSSL_TLS13
  12098. case encrypted_extensions:
  12099. /* Send out all extension except those that are turned on. */
  12100. #ifdef HAVE_ECC
  12101. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  12102. #endif
  12103. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  12104. #ifdef HAVE_SESSION_TICKET
  12105. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SESSION_TICKET));
  12106. #endif
  12107. #ifdef HAVE_SUPPORTED_CURVES
  12108. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  12109. #endif
  12110. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12111. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  12112. #endif
  12113. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  12114. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  12115. #endif
  12116. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  12117. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  12118. #endif
  12119. #if defined(HAVE_SERVER_RENEGOTIATION_INFO)
  12120. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_RENEGOTIATION_INFO));
  12121. #endif
  12122. #ifdef WOLFSSL_DTLS_CID
  12123. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  12124. #endif /* WOLFSSL_DTLS_CID */
  12125. break;
  12126. #ifdef WOLFSSL_EARLY_DATA
  12127. case session_ticket:
  12128. if (ssl->options.tls1_3) {
  12129. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12130. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  12131. }
  12132. break;
  12133. #endif
  12134. #endif
  12135. #endif
  12136. #ifdef WOLFSSL_TLS13
  12137. #ifndef NO_CERTS
  12138. case certificate:
  12139. /* Don't send out any extension except those that are turned
  12140. * off. */
  12141. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12142. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  12143. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP,
  12144. * TLSX_SERVER_CERTIFICATE_TYPE
  12145. */
  12146. break;
  12147. #endif
  12148. #endif
  12149. default:
  12150. break;
  12151. }
  12152. offset += OPAQUE16_LEN; /* extensions length */
  12153. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  12154. msgType, &offset);
  12155. if (ret != 0)
  12156. return ret;
  12157. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  12158. if (msgType == hello_retry_request) {
  12159. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12160. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  12161. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  12162. msgType, &offset);
  12163. if (ret != 0)
  12164. return ret;
  12165. }
  12166. #endif
  12167. #ifdef HAVE_EXTENDED_MASTER
  12168. if (ssl->options.haveEMS && msgType == server_hello &&
  12169. !IsAtLeastTLSv1_3(ssl->version)) {
  12170. WOLFSSL_MSG("EMS extension to write");
  12171. c16toa(HELLO_EXT_EXTMS, output + offset);
  12172. offset += HELLO_EXT_TYPE_SZ;
  12173. c16toa(0, output + offset);
  12174. offset += HELLO_EXT_SZ_SZ;
  12175. }
  12176. #endif
  12177. if (offset > OPAQUE16_LEN || msgType != server_hello)
  12178. c16toa(offset - OPAQUE16_LEN, output); /* extensions length */
  12179. }
  12180. if (pOffset)
  12181. *pOffset += offset;
  12182. return ret;
  12183. }
  12184. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_SERVER */
  12185. #ifdef WOLFSSL_TLS13
  12186. int TLSX_ParseVersion(WOLFSSL* ssl, const byte* input, word16 length,
  12187. byte msgType, int* found)
  12188. {
  12189. int ret = 0;
  12190. int offset = 0;
  12191. *found = 0;
  12192. while (offset < (int)length) {
  12193. word16 type;
  12194. word16 size;
  12195. if (offset + (2 * OPAQUE16_LEN) > length) {
  12196. ret = BUFFER_ERROR;
  12197. break;
  12198. }
  12199. ato16(input + offset, &type);
  12200. offset += HELLO_EXT_TYPE_SZ;
  12201. ato16(input + offset, &size);
  12202. offset += OPAQUE16_LEN;
  12203. if (offset + size > length) {
  12204. ret = BUFFER_ERROR;
  12205. break;
  12206. }
  12207. if (type == TLSX_SUPPORTED_VERSIONS) {
  12208. *found = 1;
  12209. WOLFSSL_MSG("Supported Versions extension received");
  12210. ret = SV_PARSE(ssl, input + offset, size, msgType, &ssl->version,
  12211. &ssl->options, &ssl->extensions);
  12212. break;
  12213. }
  12214. offset += size;
  12215. }
  12216. return ret;
  12217. }
  12218. #endif
  12219. /** Parses a buffer of TLS extensions. */
  12220. int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType,
  12221. Suites *suites)
  12222. {
  12223. int ret = 0;
  12224. word16 offset = 0;
  12225. byte isRequest = (msgType == client_hello ||
  12226. msgType == certificate_request);
  12227. #ifdef HAVE_EXTENDED_MASTER
  12228. byte pendingEMS = 0;
  12229. #endif
  12230. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  12231. int pskDone = 0;
  12232. #endif
  12233. byte seenType[SEMAPHORE_SIZE]; /* Seen known extensions. */
  12234. if (!ssl || !input || (isRequest && !suites))
  12235. return BAD_FUNC_ARG;
  12236. /* No known extensions seen yet. */
  12237. XMEMSET(seenType, 0, sizeof(seenType));
  12238. while (ret == 0 && offset < length) {
  12239. word16 type;
  12240. word16 size;
  12241. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  12242. if (msgType == client_hello && pskDone) {
  12243. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  12244. return PSK_KEY_ERROR;
  12245. }
  12246. #endif
  12247. if (length - offset < HELLO_EXT_TYPE_SZ + OPAQUE16_LEN)
  12248. return BUFFER_ERROR;
  12249. ato16(input + offset, &type);
  12250. offset += HELLO_EXT_TYPE_SZ;
  12251. ato16(input + offset, &size);
  12252. offset += OPAQUE16_LEN;
  12253. /* Check we have a bit for extension type. */
  12254. if ((type <= 62) || (type == TLSX_RENEGOTIATION_INFO)
  12255. #ifdef WOLFSSL_QUIC
  12256. || (type == TLSX_KEY_QUIC_TP_PARAMS_DRAFT)
  12257. #endif
  12258. )
  12259. {
  12260. /* Detect duplicate recognized extensions. */
  12261. if (IS_OFF(seenType, TLSX_ToSemaphore(type))) {
  12262. TURN_ON(seenType, TLSX_ToSemaphore(type));
  12263. }
  12264. else {
  12265. return DUPLICATE_TLS_EXT_E;
  12266. }
  12267. }
  12268. if (length - offset < size)
  12269. return BUFFER_ERROR;
  12270. switch (type) {
  12271. #ifdef HAVE_SNI
  12272. case TLSX_SERVER_NAME:
  12273. WOLFSSL_MSG("SNI extension received");
  12274. #ifdef WOLFSSL_DEBUG_TLS
  12275. WOLFSSL_BUFFER(input + offset, size);
  12276. #endif
  12277. #ifdef WOLFSSL_TLS13
  12278. if (IsAtLeastTLSv1_3(ssl->version)) {
  12279. if (msgType != client_hello &&
  12280. msgType != encrypted_extensions)
  12281. return EXT_NOT_ALLOWED;
  12282. }
  12283. else
  12284. #endif
  12285. {
  12286. if (msgType != client_hello &&
  12287. msgType != server_hello)
  12288. return EXT_NOT_ALLOWED;
  12289. }
  12290. ret = SNI_PARSE(ssl, input + offset, size, isRequest);
  12291. break;
  12292. #endif
  12293. case TLSX_TRUSTED_CA_KEYS:
  12294. WOLFSSL_MSG("Trusted CA extension received");
  12295. #ifdef WOLFSSL_DEBUG_TLS
  12296. WOLFSSL_BUFFER(input + offset, size);
  12297. #endif
  12298. #ifdef WOLFSSL_TLS13
  12299. /* RFC 8446 4.2.4 states trusted_ca_keys is not used
  12300. in TLS 1.3. */
  12301. if (IsAtLeastTLSv1_3(ssl->version)) {
  12302. return EXT_NOT_ALLOWED;
  12303. }
  12304. else
  12305. #endif
  12306. {
  12307. if (msgType != client_hello &&
  12308. msgType != server_hello)
  12309. return EXT_NOT_ALLOWED;
  12310. }
  12311. ret = TCA_PARSE(ssl, input + offset, size, isRequest);
  12312. break;
  12313. case TLSX_MAX_FRAGMENT_LENGTH:
  12314. WOLFSSL_MSG("Max Fragment Length extension received");
  12315. #ifdef WOLFSSL_DEBUG_TLS
  12316. WOLFSSL_BUFFER(input + offset, size);
  12317. #endif
  12318. #ifdef WOLFSSL_TLS13
  12319. if (IsAtLeastTLSv1_3(ssl->version)) {
  12320. if (msgType != client_hello &&
  12321. msgType != encrypted_extensions) {
  12322. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12323. return EXT_NOT_ALLOWED;
  12324. }
  12325. }
  12326. else
  12327. #endif
  12328. {
  12329. if (msgType != client_hello &&
  12330. msgType != server_hello) {
  12331. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12332. return EXT_NOT_ALLOWED;
  12333. }
  12334. }
  12335. ret = MFL_PARSE(ssl, input + offset, size, isRequest);
  12336. break;
  12337. case TLSX_TRUNCATED_HMAC:
  12338. WOLFSSL_MSG("Truncated HMAC extension received");
  12339. #ifdef WOLFSSL_DEBUG_TLS
  12340. WOLFSSL_BUFFER(input + offset, size);
  12341. #endif
  12342. #ifdef WOLFSSL_TLS13
  12343. if (IsAtLeastTLSv1_3(ssl->version))
  12344. break;
  12345. #endif
  12346. if (msgType != client_hello)
  12347. return EXT_NOT_ALLOWED;
  12348. ret = THM_PARSE(ssl, input + offset, size, isRequest);
  12349. break;
  12350. case TLSX_SUPPORTED_GROUPS:
  12351. WOLFSSL_MSG("Supported Groups extension received");
  12352. #ifdef WOLFSSL_DEBUG_TLS
  12353. WOLFSSL_BUFFER(input + offset, size);
  12354. #endif
  12355. #ifdef WOLFSSL_TLS13
  12356. if (IsAtLeastTLSv1_3(ssl->version)) {
  12357. if (msgType != client_hello &&
  12358. msgType != encrypted_extensions) {
  12359. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12360. return EXT_NOT_ALLOWED;
  12361. }
  12362. }
  12363. else
  12364. #endif
  12365. {
  12366. if (msgType != client_hello) {
  12367. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12368. return EXT_NOT_ALLOWED;
  12369. }
  12370. }
  12371. ret = EC_PARSE(ssl, input + offset, size, isRequest,
  12372. &ssl->extensions);
  12373. break;
  12374. #ifdef WOLFSSL_DUAL_ALG_CERTS
  12375. case TLSX_CKS:
  12376. WOLFSSL_MSG("CKS extension received");
  12377. if (!IsAtLeastTLSv1_3(ssl->version) ||
  12378. (msgType != client_hello &&
  12379. msgType != encrypted_extensions)) {
  12380. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12381. return EXT_NOT_ALLOWED;
  12382. }
  12383. ret = TLSX_CKS_Parse(ssl, (byte *)(input + offset), size,
  12384. &ssl->extensions);
  12385. break;
  12386. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  12387. case TLSX_EC_POINT_FORMATS:
  12388. WOLFSSL_MSG("Point Formats extension received");
  12389. #ifdef WOLFSSL_DEBUG_TLS
  12390. WOLFSSL_BUFFER(input + offset, size);
  12391. #endif
  12392. #ifdef WOLFSSL_TLS13
  12393. if (IsAtLeastTLSv1_3(ssl->version))
  12394. break;
  12395. #endif
  12396. if (msgType != client_hello &&
  12397. msgType != server_hello) {
  12398. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12399. return EXT_NOT_ALLOWED;
  12400. }
  12401. ret = PF_PARSE(ssl, input + offset, size, isRequest);
  12402. break;
  12403. case TLSX_STATUS_REQUEST:
  12404. WOLFSSL_MSG("Certificate Status Request extension received");
  12405. #ifdef WOLFSSL_DEBUG_TLS
  12406. WOLFSSL_BUFFER(input + offset, size);
  12407. #endif
  12408. #ifdef WOLFSSL_TLS13
  12409. if (IsAtLeastTLSv1_3(ssl->version)) {
  12410. if (msgType != client_hello &&
  12411. msgType != certificate_request &&
  12412. msgType != certificate)
  12413. return EXT_NOT_ALLOWED;
  12414. }
  12415. else
  12416. #endif
  12417. {
  12418. if (msgType != client_hello &&
  12419. msgType != server_hello)
  12420. return EXT_NOT_ALLOWED;
  12421. }
  12422. ret = CSR_PARSE(ssl, input + offset, size, isRequest);
  12423. break;
  12424. case TLSX_STATUS_REQUEST_V2:
  12425. WOLFSSL_MSG("Certificate Status Request v2 extension received");
  12426. #ifdef WOLFSSL_DEBUG_TLS
  12427. WOLFSSL_BUFFER(input + offset, size);
  12428. #endif
  12429. #if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  12430. if (IsAtLeastTLSv1_3(ssl->version)) {
  12431. if (msgType != client_hello &&
  12432. msgType != certificate_request &&
  12433. msgType != certificate)
  12434. return EXT_NOT_ALLOWED;
  12435. }
  12436. else
  12437. #endif
  12438. {
  12439. if (msgType != client_hello &&
  12440. msgType != server_hello)
  12441. return EXT_NOT_ALLOWED;
  12442. }
  12443. ret = CSR2_PARSE(ssl, input + offset, size, isRequest);
  12444. break;
  12445. #ifdef HAVE_EXTENDED_MASTER
  12446. case HELLO_EXT_EXTMS:
  12447. WOLFSSL_MSG("Extended Master Secret extension received");
  12448. #ifdef WOLFSSL_DEBUG_TLS
  12449. WOLFSSL_BUFFER(input + offset, size);
  12450. #endif
  12451. #if defined(WOLFSSL_TLS13)
  12452. if (IsAtLeastTLSv1_3(ssl->version))
  12453. break;
  12454. #endif
  12455. if (msgType != client_hello &&
  12456. msgType != server_hello)
  12457. return EXT_NOT_ALLOWED;
  12458. if (size != 0)
  12459. return BUFFER_ERROR;
  12460. #ifndef NO_WOLFSSL_SERVER
  12461. if (isRequest)
  12462. ssl->options.haveEMS = 1;
  12463. #endif
  12464. pendingEMS = 1;
  12465. break;
  12466. #endif
  12467. case TLSX_RENEGOTIATION_INFO:
  12468. WOLFSSL_MSG("Secure Renegotiation extension received");
  12469. #ifdef WOLFSSL_DEBUG_TLS
  12470. WOLFSSL_BUFFER(input + offset, size);
  12471. #endif
  12472. #ifdef WOLFSSL_TLS13
  12473. if (IsAtLeastTLSv1_3(ssl->version))
  12474. break;
  12475. #endif
  12476. if (msgType != client_hello &&
  12477. msgType != server_hello)
  12478. return EXT_NOT_ALLOWED;
  12479. ret = SCR_PARSE(ssl, input + offset, size, isRequest);
  12480. break;
  12481. case TLSX_SESSION_TICKET:
  12482. WOLFSSL_MSG("Session Ticket extension received");
  12483. #ifdef WOLFSSL_DEBUG_TLS
  12484. WOLFSSL_BUFFER(input + offset, size);
  12485. #endif
  12486. #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)
  12487. if (IsAtLeastTLSv1_3(ssl->version)) {
  12488. if (msgType != client_hello)
  12489. return EXT_NOT_ALLOWED;
  12490. }
  12491. else
  12492. #endif
  12493. {
  12494. if (msgType != client_hello &&
  12495. msgType != server_hello)
  12496. return EXT_NOT_ALLOWED;
  12497. }
  12498. ret = WOLF_STK_PARSE(ssl, input + offset, size, isRequest);
  12499. break;
  12500. case TLSX_APPLICATION_LAYER_PROTOCOL:
  12501. WOLFSSL_MSG("ALPN extension received");
  12502. #ifdef WOLFSSL_DEBUG_TLS
  12503. WOLFSSL_BUFFER(input + offset, size);
  12504. #endif
  12505. #if defined(WOLFSSL_TLS13) && defined(HAVE_ALPN)
  12506. if (IsAtLeastTLSv1_3(ssl->version)) {
  12507. if (msgType != client_hello &&
  12508. msgType != encrypted_extensions)
  12509. return EXT_NOT_ALLOWED;
  12510. }
  12511. else
  12512. #endif
  12513. {
  12514. if (msgType != client_hello &&
  12515. msgType != server_hello)
  12516. return EXT_NOT_ALLOWED;
  12517. }
  12518. ret = ALPN_PARSE(ssl, input + offset, size, isRequest);
  12519. break;
  12520. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  12521. case TLSX_SIGNATURE_ALGORITHMS:
  12522. WOLFSSL_MSG("Signature Algorithms extension received");
  12523. #ifdef WOLFSSL_DEBUG_TLS
  12524. WOLFSSL_BUFFER(input + offset, size);
  12525. #endif
  12526. if (!IsAtLeastTLSv1_2(ssl))
  12527. break;
  12528. #ifdef WOLFSSL_TLS13
  12529. if (IsAtLeastTLSv1_3(ssl->version)) {
  12530. if (msgType != client_hello &&
  12531. msgType != certificate_request)
  12532. return EXT_NOT_ALLOWED;
  12533. }
  12534. else
  12535. #endif
  12536. {
  12537. if (msgType != client_hello)
  12538. return EXT_NOT_ALLOWED;
  12539. }
  12540. ret = SA_PARSE(ssl, input + offset, size, isRequest, suites);
  12541. break;
  12542. #endif
  12543. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  12544. case TLSX_ENCRYPT_THEN_MAC:
  12545. WOLFSSL_MSG("Encrypt-Then-Mac extension received");
  12546. /* Ignore for TLS 1.3+ */
  12547. if (IsAtLeastTLSv1_3(ssl->version))
  12548. break;
  12549. if (msgType != client_hello &&
  12550. msgType != server_hello)
  12551. return EXT_NOT_ALLOWED;
  12552. ret = ETM_PARSE(ssl, input + offset, size, msgType);
  12553. break;
  12554. #endif /* HAVE_ENCRYPT_THEN_MAC */
  12555. #ifdef WOLFSSL_TLS13
  12556. case TLSX_SUPPORTED_VERSIONS:
  12557. WOLFSSL_MSG("Skipping Supported Versions - already processed");
  12558. #ifdef WOLFSSL_DEBUG_TLS
  12559. WOLFSSL_BUFFER(input + offset, size);
  12560. #endif
  12561. if (msgType != client_hello &&
  12562. msgType != server_hello &&
  12563. msgType != hello_retry_request)
  12564. return EXT_NOT_ALLOWED;
  12565. break;
  12566. #ifdef WOLFSSL_SEND_HRR_COOKIE
  12567. case TLSX_COOKIE:
  12568. WOLFSSL_MSG("Cookie extension received");
  12569. #ifdef WOLFSSL_DEBUG_TLS
  12570. WOLFSSL_BUFFER(input + offset, size);
  12571. #endif
  12572. if (!IsAtLeastTLSv1_3(ssl->version))
  12573. break;
  12574. if (msgType != client_hello &&
  12575. msgType != hello_retry_request) {
  12576. return EXT_NOT_ALLOWED;
  12577. }
  12578. ret = CKE_PARSE(ssl, input + offset, size, msgType);
  12579. break;
  12580. #endif
  12581. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12582. case TLSX_PRE_SHARED_KEY:
  12583. WOLFSSL_MSG("Pre-Shared Key extension received");
  12584. #ifdef WOLFSSL_DEBUG_TLS
  12585. WOLFSSL_BUFFER(input + offset, size);
  12586. #endif
  12587. if (!IsAtLeastTLSv1_3(ssl->version))
  12588. break;
  12589. if (msgType != client_hello &&
  12590. msgType != server_hello) {
  12591. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12592. return EXT_NOT_ALLOWED;
  12593. }
  12594. ret = PSK_PARSE(ssl, input + offset, size, msgType);
  12595. pskDone = 1;
  12596. break;
  12597. case TLSX_PSK_KEY_EXCHANGE_MODES:
  12598. WOLFSSL_MSG("PSK Key Exchange Modes extension received");
  12599. #ifdef WOLFSSL_DEBUG_TLS
  12600. WOLFSSL_BUFFER(input + offset, size);
  12601. #endif
  12602. if (!IsAtLeastTLSv1_3(ssl->version))
  12603. break;
  12604. if (msgType != client_hello) {
  12605. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12606. return EXT_NOT_ALLOWED;
  12607. }
  12608. ret = PKM_PARSE(ssl, input + offset, size, msgType);
  12609. break;
  12610. #endif
  12611. #ifdef WOLFSSL_EARLY_DATA
  12612. case TLSX_EARLY_DATA:
  12613. WOLFSSL_MSG("Early Data extension received");
  12614. #ifdef WOLFSSL_DEBUG_TLS
  12615. WOLFSSL_BUFFER(input + offset, size);
  12616. #endif
  12617. if (!IsAtLeastTLSv1_3(ssl->version))
  12618. break;
  12619. if (msgType != client_hello && msgType != session_ticket &&
  12620. msgType != encrypted_extensions) {
  12621. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12622. return EXT_NOT_ALLOWED;
  12623. }
  12624. ret = EDI_PARSE(ssl, input + offset, size, msgType);
  12625. break;
  12626. #endif
  12627. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  12628. case TLSX_POST_HANDSHAKE_AUTH:
  12629. WOLFSSL_MSG("Post Handshake Authentication extension received");
  12630. #ifdef WOLFSSL_DEBUG_TLS
  12631. WOLFSSL_BUFFER(input + offset, size);
  12632. #endif
  12633. if (!IsAtLeastTLSv1_3(ssl->version))
  12634. break;
  12635. if (msgType != client_hello) {
  12636. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12637. return EXT_NOT_ALLOWED;
  12638. }
  12639. ret = PHA_PARSE(ssl, input + offset, size, msgType);
  12640. break;
  12641. #endif
  12642. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  12643. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  12644. WOLFSSL_MSG("Signature Algorithms extension received");
  12645. #ifdef WOLFSSL_DEBUG_TLS
  12646. WOLFSSL_BUFFER(input + offset, size);
  12647. #endif
  12648. if (!IsAtLeastTLSv1_3(ssl->version))
  12649. break;
  12650. if (msgType != client_hello &&
  12651. msgType != certificate_request) {
  12652. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12653. return EXT_NOT_ALLOWED;
  12654. }
  12655. ret = SAC_PARSE(ssl, input + offset, size, isRequest);
  12656. break;
  12657. #endif
  12658. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  12659. case TLSX_CERTIFICATE_AUTHORITIES:
  12660. WOLFSSL_MSG("Certificate Authorities extension received");
  12661. #ifdef WOLFSSL_DEBUG_TLS
  12662. WOLFSSL_BUFFER(input + offset, size);
  12663. #endif
  12664. if (!IsAtLeastTLSv1_3(ssl->version))
  12665. break;
  12666. if (msgType != client_hello &&
  12667. msgType != certificate_request) {
  12668. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12669. return EXT_NOT_ALLOWED;
  12670. }
  12671. ret = CAN_PARSE(ssl, input + offset, size, isRequest);
  12672. break;
  12673. #endif
  12674. case TLSX_KEY_SHARE:
  12675. WOLFSSL_MSG("Key Share extension received");
  12676. #ifdef WOLFSSL_DEBUG_TLS
  12677. WOLFSSL_BUFFER(input + offset, size);
  12678. #endif
  12679. #ifdef HAVE_SUPPORTED_CURVES
  12680. if (!IsAtLeastTLSv1_3(ssl->version))
  12681. break;
  12682. if (msgType != client_hello && msgType != server_hello &&
  12683. msgType != hello_retry_request) {
  12684. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12685. return EXT_NOT_ALLOWED;
  12686. }
  12687. #endif
  12688. ret = KS_PARSE(ssl, input + offset, size, msgType);
  12689. break;
  12690. #endif
  12691. #ifdef WOLFSSL_SRTP
  12692. case TLSX_USE_SRTP:
  12693. WOLFSSL_MSG("Use SRTP extension received");
  12694. ret = SRTP_PARSE(ssl, input + offset, size, isRequest);
  12695. break;
  12696. #endif
  12697. #ifdef WOLFSSL_QUIC
  12698. case TLSX_KEY_QUIC_TP_PARAMS:
  12699. FALL_THROUGH;
  12700. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  12701. WOLFSSL_MSG("QUIC transport parameter received");
  12702. #ifdef WOLFSSL_DEBUG_TLS
  12703. WOLFSSL_BUFFER(input + offset, size);
  12704. #endif
  12705. if (IsAtLeastTLSv1_3(ssl->version) &&
  12706. msgType != client_hello &&
  12707. msgType != server_hello &&
  12708. msgType != encrypted_extensions) {
  12709. return EXT_NOT_ALLOWED;
  12710. }
  12711. else if (!IsAtLeastTLSv1_3(ssl->version) &&
  12712. msgType == encrypted_extensions) {
  12713. return EXT_NOT_ALLOWED;
  12714. }
  12715. else if (WOLFSSL_IS_QUIC(ssl)) {
  12716. ret = QTP_PARSE(ssl, input + offset, size, type, msgType);
  12717. }
  12718. else {
  12719. WOLFSSL_MSG("QUIC transport param TLS extension type, but no QUIC");
  12720. return EXT_NOT_ALLOWED; /* be safe, this should not happen */
  12721. }
  12722. break;
  12723. #endif /* WOLFSSL_QUIC */
  12724. #if defined(WOLFSSL_DTLS_CID)
  12725. case TLSX_CONNECTION_ID:
  12726. /* connection ID not supported in DTLSv1.2 */
  12727. if (!IsAtLeastTLSv1_3(ssl->version))
  12728. break;
  12729. if (msgType != client_hello && msgType != server_hello)
  12730. return EXT_NOT_ALLOWED;
  12731. WOLFSSL_MSG("ConnectionID extension received");
  12732. ret = CID_PARSE(ssl, input + offset, size, isRequest);
  12733. break;
  12734. #endif /* defined(WOLFSSL_DTLS_CID) */
  12735. #if defined(HAVE_RPK)
  12736. case TLSX_CLIENT_CERTIFICATE_TYPE:
  12737. WOLFSSL_MSG("Client Certificate Type extension received");
  12738. ret = CCT_PARSE(ssl, input + offset, size, msgType);
  12739. break;
  12740. case TLSX_SERVER_CERTIFICATE_TYPE:
  12741. WOLFSSL_MSG("Server Certificate Type extension received");
  12742. ret = SCT_PARSE(ssl, input + offset, size, msgType);
  12743. break;
  12744. #endif /* HAVE_RPK */
  12745. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  12746. case TLSX_ECH:
  12747. WOLFSSL_MSG("ECH extension received");
  12748. ret = ECH_PARSE(ssl, input + offset, size, msgType);
  12749. break;
  12750. #endif
  12751. default:
  12752. WOLFSSL_MSG("Unknown TLS extension type");
  12753. }
  12754. /* offset should be updated here! */
  12755. offset += size;
  12756. }
  12757. #ifdef HAVE_EXTENDED_MASTER
  12758. if (IsAtLeastTLSv1_3(ssl->version) && msgType == hello_retry_request) {
  12759. /* Don't change EMS status until server_hello received.
  12760. * Second ClientHello must have same extensions.
  12761. */
  12762. }
  12763. else if (!isRequest && ssl->options.haveEMS && !pendingEMS)
  12764. ssl->options.haveEMS = 0;
  12765. #endif
  12766. if (ret == 0)
  12767. ret = SNI_VERIFY_PARSE(ssl, isRequest);
  12768. if (ret == 0)
  12769. ret = TCA_VERIFY_PARSE(ssl, isRequest);
  12770. return ret;
  12771. }
  12772. /* undefining semaphore macros */
  12773. #undef IS_OFF
  12774. #undef TURN_ON
  12775. #undef SEMAPHORE_SIZE
  12776. #endif /* HAVE_TLS_EXTENSIONS */
  12777. #ifndef NO_WOLFSSL_CLIENT
  12778. WOLFSSL_METHOD* wolfTLS_client_method(void)
  12779. {
  12780. return wolfTLS_client_method_ex(NULL);
  12781. }
  12782. WOLFSSL_METHOD* wolfTLS_client_method_ex(void* heap)
  12783. {
  12784. WOLFSSL_METHOD* method =
  12785. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12786. heap, DYNAMIC_TYPE_METHOD);
  12787. (void)heap;
  12788. WOLFSSL_ENTER("TLS_client_method_ex");
  12789. if (method) {
  12790. #if defined(WOLFSSL_TLS13)
  12791. InitSSL_Method(method, MakeTLSv1_3());
  12792. #elif !defined(WOLFSSL_NO_TLS12)
  12793. InitSSL_Method(method, MakeTLSv1_2());
  12794. #elif !defined(NO_OLD_TLS)
  12795. InitSSL_Method(method, MakeTLSv1_1());
  12796. #elif defined(WOLFSSL_ALLOW_TLSV10)
  12797. InitSSL_Method(method, MakeTLSv1());
  12798. #else
  12799. #error No TLS version enabled!
  12800. #endif
  12801. method->downgrade = 1;
  12802. method->side = WOLFSSL_CLIENT_END;
  12803. }
  12804. return method;
  12805. }
  12806. #ifndef NO_OLD_TLS
  12807. #ifdef WOLFSSL_ALLOW_TLSV10
  12808. WOLFSSL_METHOD* wolfTLSv1_client_method(void)
  12809. {
  12810. return wolfTLSv1_client_method_ex(NULL);
  12811. }
  12812. WOLFSSL_METHOD* wolfTLSv1_client_method_ex(void* heap)
  12813. {
  12814. WOLFSSL_METHOD* method =
  12815. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12816. heap, DYNAMIC_TYPE_METHOD);
  12817. (void)heap;
  12818. WOLFSSL_ENTER("TLSv1_client_method_ex");
  12819. if (method)
  12820. InitSSL_Method(method, MakeTLSv1());
  12821. return method;
  12822. }
  12823. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12824. WOLFSSL_METHOD* wolfTLSv1_1_client_method(void)
  12825. {
  12826. return wolfTLSv1_1_client_method_ex(NULL);
  12827. }
  12828. WOLFSSL_METHOD* wolfTLSv1_1_client_method_ex(void* heap)
  12829. {
  12830. WOLFSSL_METHOD* method =
  12831. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12832. heap, DYNAMIC_TYPE_METHOD);
  12833. (void)heap;
  12834. WOLFSSL_ENTER("TLSv1_1_client_method_ex");
  12835. if (method)
  12836. InitSSL_Method(method, MakeTLSv1_1());
  12837. return method;
  12838. }
  12839. #endif /* !NO_OLD_TLS */
  12840. #ifndef WOLFSSL_NO_TLS12
  12841. WOLFSSL_ABI
  12842. WOLFSSL_METHOD* wolfTLSv1_2_client_method(void)
  12843. {
  12844. return wolfTLSv1_2_client_method_ex(NULL);
  12845. }
  12846. WOLFSSL_METHOD* wolfTLSv1_2_client_method_ex(void* heap)
  12847. {
  12848. WOLFSSL_METHOD* method =
  12849. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12850. heap, DYNAMIC_TYPE_METHOD);
  12851. (void)heap;
  12852. WOLFSSL_ENTER("TLSv1_2_client_method_ex");
  12853. if (method)
  12854. InitSSL_Method(method, MakeTLSv1_2());
  12855. return method;
  12856. }
  12857. #endif /* WOLFSSL_NO_TLS12 */
  12858. #ifdef WOLFSSL_TLS13
  12859. /* The TLS v1.3 client method data.
  12860. *
  12861. * returns the method data for a TLS v1.3 client.
  12862. */
  12863. WOLFSSL_ABI
  12864. WOLFSSL_METHOD* wolfTLSv1_3_client_method(void)
  12865. {
  12866. return wolfTLSv1_3_client_method_ex(NULL);
  12867. }
  12868. /* The TLS v1.3 client method data.
  12869. *
  12870. * heap The heap used for allocation.
  12871. * returns the method data for a TLS v1.3 client.
  12872. */
  12873. WOLFSSL_METHOD* wolfTLSv1_3_client_method_ex(void* heap)
  12874. {
  12875. WOLFSSL_METHOD* method = (WOLFSSL_METHOD*)
  12876. XMALLOC(sizeof(WOLFSSL_METHOD), heap,
  12877. DYNAMIC_TYPE_METHOD);
  12878. (void)heap;
  12879. WOLFSSL_ENTER("TLSv1_3_client_method_ex");
  12880. if (method)
  12881. InitSSL_Method(method, MakeTLSv1_3());
  12882. return method;
  12883. }
  12884. #endif /* WOLFSSL_TLS13 */
  12885. #ifdef WOLFSSL_DTLS
  12886. WOLFSSL_METHOD* wolfDTLS_client_method(void)
  12887. {
  12888. return wolfDTLS_client_method_ex(NULL);
  12889. }
  12890. WOLFSSL_METHOD* wolfDTLS_client_method_ex(void* heap)
  12891. {
  12892. WOLFSSL_METHOD* method =
  12893. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12894. heap, DYNAMIC_TYPE_METHOD);
  12895. (void)heap;
  12896. WOLFSSL_ENTER("DTLS_client_method_ex");
  12897. if (method) {
  12898. #if defined(WOLFSSL_DTLS13)
  12899. InitSSL_Method(method, MakeDTLSv1_3());
  12900. #elif !defined(WOLFSSL_NO_TLS12)
  12901. InitSSL_Method(method, MakeDTLSv1_2());
  12902. #elif !defined(NO_OLD_TLS)
  12903. InitSSL_Method(method, MakeDTLSv1());
  12904. #else
  12905. #error No DTLS version enabled!
  12906. #endif
  12907. method->downgrade = 1;
  12908. method->side = WOLFSSL_CLIENT_END;
  12909. }
  12910. return method;
  12911. }
  12912. #ifndef NO_OLD_TLS
  12913. WOLFSSL_METHOD* wolfDTLSv1_client_method(void)
  12914. {
  12915. return wolfDTLSv1_client_method_ex(NULL);
  12916. }
  12917. WOLFSSL_METHOD* wolfDTLSv1_client_method_ex(void* heap)
  12918. {
  12919. WOLFSSL_METHOD* method =
  12920. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12921. heap, DYNAMIC_TYPE_METHOD);
  12922. (void)heap;
  12923. WOLFSSL_ENTER("DTLSv1_client_method_ex");
  12924. if (method)
  12925. InitSSL_Method(method, MakeDTLSv1());
  12926. return method;
  12927. }
  12928. #endif /* NO_OLD_TLS */
  12929. #ifndef WOLFSSL_NO_TLS12
  12930. WOLFSSL_METHOD* wolfDTLSv1_2_client_method(void)
  12931. {
  12932. return wolfDTLSv1_2_client_method_ex(NULL);
  12933. }
  12934. WOLFSSL_METHOD* wolfDTLSv1_2_client_method_ex(void* heap)
  12935. {
  12936. WOLFSSL_METHOD* method =
  12937. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12938. heap, DYNAMIC_TYPE_METHOD);
  12939. (void)heap;
  12940. WOLFSSL_ENTER("DTLSv1_2_client_method_ex");
  12941. if (method)
  12942. InitSSL_Method(method, MakeDTLSv1_2());
  12943. (void)heap;
  12944. return method;
  12945. }
  12946. #endif /* !WOLFSSL_NO_TLS12 */
  12947. #endif /* WOLFSSL_DTLS */
  12948. #endif /* NO_WOLFSSL_CLIENT */
  12949. /* EITHER SIDE METHODS */
  12950. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
  12951. #ifndef NO_OLD_TLS
  12952. #ifdef WOLFSSL_ALLOW_TLSV10
  12953. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12954. *
  12955. * Returns a pointer to a WOLFSSL_METHOD struct
  12956. */
  12957. WOLFSSL_METHOD* wolfTLSv1_method(void)
  12958. {
  12959. return wolfTLSv1_method_ex(NULL);
  12960. }
  12961. WOLFSSL_METHOD* wolfTLSv1_method_ex(void* heap)
  12962. {
  12963. WOLFSSL_METHOD* m;
  12964. WOLFSSL_ENTER("TLSv1_method");
  12965. #ifndef NO_WOLFSSL_CLIENT
  12966. m = wolfTLSv1_client_method_ex(heap);
  12967. #else
  12968. m = wolfTLSv1_server_method_ex(heap);
  12969. #endif
  12970. if (m != NULL) {
  12971. m->side = WOLFSSL_NEITHER_END;
  12972. }
  12973. return m;
  12974. }
  12975. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12976. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12977. *
  12978. * Returns a pointer to a WOLFSSL_METHOD struct
  12979. */
  12980. WOLFSSL_METHOD* wolfTLSv1_1_method(void)
  12981. {
  12982. return wolfTLSv1_1_method_ex(NULL);
  12983. }
  12984. WOLFSSL_METHOD* wolfTLSv1_1_method_ex(void* heap)
  12985. {
  12986. WOLFSSL_METHOD* m;
  12987. WOLFSSL_ENTER("TLSv1_1_method");
  12988. #ifndef NO_WOLFSSL_CLIENT
  12989. m = wolfTLSv1_1_client_method_ex(heap);
  12990. #else
  12991. m = wolfTLSv1_1_server_method_ex(heap);
  12992. #endif
  12993. if (m != NULL) {
  12994. m->side = WOLFSSL_NEITHER_END;
  12995. }
  12996. return m;
  12997. }
  12998. #endif /* !NO_OLD_TLS */
  12999. #ifndef WOLFSSL_NO_TLS12
  13000. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  13001. *
  13002. * Returns a pointer to a WOLFSSL_METHOD struct
  13003. */
  13004. WOLFSSL_METHOD* wolfTLSv1_2_method(void)
  13005. {
  13006. return wolfTLSv1_2_method_ex(NULL);
  13007. }
  13008. WOLFSSL_METHOD* wolfTLSv1_2_method_ex(void* heap)
  13009. {
  13010. WOLFSSL_METHOD* m;
  13011. WOLFSSL_ENTER("TLSv1_2_method");
  13012. #ifndef NO_WOLFSSL_CLIENT
  13013. m = wolfTLSv1_2_client_method_ex(heap);
  13014. #else
  13015. m = wolfTLSv1_2_server_method_ex(heap);
  13016. #endif
  13017. if (m != NULL) {
  13018. m->side = WOLFSSL_NEITHER_END;
  13019. }
  13020. return m;
  13021. }
  13022. #endif /* !WOLFSSL_NO_TLS12 */
  13023. #ifdef WOLFSSL_TLS13
  13024. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  13025. *
  13026. * Returns a pointer to a WOLFSSL_METHOD struct
  13027. */
  13028. WOLFSSL_METHOD* wolfTLSv1_3_method(void)
  13029. {
  13030. return wolfTLSv1_3_method_ex(NULL);
  13031. }
  13032. WOLFSSL_METHOD* wolfTLSv1_3_method_ex(void* heap)
  13033. {
  13034. WOLFSSL_METHOD* m;
  13035. WOLFSSL_ENTER("TLSv1_3_method");
  13036. #ifndef NO_WOLFSSL_CLIENT
  13037. m = wolfTLSv1_3_client_method_ex(heap);
  13038. #else
  13039. m = wolfTLSv1_3_server_method_ex(heap);
  13040. #endif
  13041. if (m != NULL) {
  13042. m->side = WOLFSSL_NEITHER_END;
  13043. }
  13044. return m;
  13045. }
  13046. #endif /* WOLFSSL_TLS13 */
  13047. #ifdef WOLFSSL_DTLS
  13048. WOLFSSL_METHOD* wolfDTLS_method(void)
  13049. {
  13050. return wolfDTLS_method_ex(NULL);
  13051. }
  13052. WOLFSSL_METHOD* wolfDTLS_method_ex(void* heap)
  13053. {
  13054. WOLFSSL_METHOD* m;
  13055. WOLFSSL_ENTER("DTLS_method_ex");
  13056. #ifndef NO_WOLFSSL_CLIENT
  13057. m = wolfDTLS_client_method_ex(heap);
  13058. #else
  13059. m = wolfDTLS_server_method_ex(heap);
  13060. #endif
  13061. if (m != NULL) {
  13062. m->side = WOLFSSL_NEITHER_END;
  13063. }
  13064. return m;
  13065. }
  13066. #ifndef NO_OLD_TLS
  13067. WOLFSSL_METHOD* wolfDTLSv1_method(void)
  13068. {
  13069. return wolfDTLSv1_method_ex(NULL);
  13070. }
  13071. WOLFSSL_METHOD* wolfDTLSv1_method_ex(void* heap)
  13072. {
  13073. WOLFSSL_METHOD* m;
  13074. WOLFSSL_ENTER("DTLSv1_method_ex");
  13075. #ifndef NO_WOLFSSL_CLIENT
  13076. m = wolfDTLSv1_client_method_ex(heap);
  13077. #else
  13078. m = wolfDTLSv1_server_method_ex(heap);
  13079. #endif
  13080. if (m != NULL) {
  13081. m->side = WOLFSSL_NEITHER_END;
  13082. }
  13083. return m;
  13084. }
  13085. #endif /* !NO_OLD_TLS */
  13086. #ifndef WOLFSSL_NO_TLS12
  13087. WOLFSSL_METHOD* wolfDTLSv1_2_method(void)
  13088. {
  13089. return wolfDTLSv1_2_method_ex(NULL);
  13090. }
  13091. WOLFSSL_METHOD* wolfDTLSv1_2_method_ex(void* heap)
  13092. {
  13093. WOLFSSL_METHOD* m;
  13094. WOLFSSL_ENTER("DTLSv1_2_method");
  13095. #ifndef NO_WOLFSSL_CLIENT
  13096. m = wolfDTLSv1_2_client_method_ex(heap);
  13097. #else
  13098. m = wolfDTLSv1_2_server_method_ex(heap);
  13099. #endif
  13100. if (m != NULL) {
  13101. m->side = WOLFSSL_NEITHER_END;
  13102. }
  13103. return m;
  13104. }
  13105. #endif /* !WOLFSSL_NO_TLS12 */
  13106. #endif /* WOLFSSL_DTLS */
  13107. #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
  13108. #ifndef NO_WOLFSSL_SERVER
  13109. WOLFSSL_METHOD* wolfTLS_server_method(void)
  13110. {
  13111. return wolfTLS_server_method_ex(NULL);
  13112. }
  13113. WOLFSSL_METHOD* wolfTLS_server_method_ex(void* heap)
  13114. {
  13115. WOLFSSL_METHOD* method =
  13116. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13117. heap, DYNAMIC_TYPE_METHOD);
  13118. (void)heap;
  13119. WOLFSSL_ENTER("TLS_server_method_ex");
  13120. if (method) {
  13121. #if defined(WOLFSSL_TLS13)
  13122. InitSSL_Method(method, MakeTLSv1_3());
  13123. #elif !defined(WOLFSSL_NO_TLS12)
  13124. InitSSL_Method(method, MakeTLSv1_2());
  13125. #elif !defined(NO_OLD_TLS)
  13126. InitSSL_Method(method, MakeTLSv1_1());
  13127. #elif defined(WOLFSSL_ALLOW_TLSV10)
  13128. InitSSL_Method(method, MakeTLSv1());
  13129. #else
  13130. #error No TLS version enabled!
  13131. #endif
  13132. method->downgrade = 1;
  13133. method->side = WOLFSSL_SERVER_END;
  13134. }
  13135. return method;
  13136. }
  13137. #ifndef NO_OLD_TLS
  13138. #ifdef WOLFSSL_ALLOW_TLSV10
  13139. WOLFSSL_METHOD* wolfTLSv1_server_method(void)
  13140. {
  13141. return wolfTLSv1_server_method_ex(NULL);
  13142. }
  13143. WOLFSSL_METHOD* wolfTLSv1_server_method_ex(void* heap)
  13144. {
  13145. WOLFSSL_METHOD* method =
  13146. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13147. heap, DYNAMIC_TYPE_METHOD);
  13148. (void)heap;
  13149. WOLFSSL_ENTER("TLSv1_server_method_ex");
  13150. if (method) {
  13151. InitSSL_Method(method, MakeTLSv1());
  13152. method->side = WOLFSSL_SERVER_END;
  13153. }
  13154. return method;
  13155. }
  13156. #endif /* WOLFSSL_ALLOW_TLSV10 */
  13157. WOLFSSL_METHOD* wolfTLSv1_1_server_method(void)
  13158. {
  13159. return wolfTLSv1_1_server_method_ex(NULL);
  13160. }
  13161. WOLFSSL_METHOD* wolfTLSv1_1_server_method_ex(void* heap)
  13162. {
  13163. WOLFSSL_METHOD* method =
  13164. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13165. heap, DYNAMIC_TYPE_METHOD);
  13166. (void)heap;
  13167. WOLFSSL_ENTER("TLSv1_1_server_method_ex");
  13168. if (method) {
  13169. InitSSL_Method(method, MakeTLSv1_1());
  13170. method->side = WOLFSSL_SERVER_END;
  13171. }
  13172. return method;
  13173. }
  13174. #endif /* !NO_OLD_TLS */
  13175. #ifndef WOLFSSL_NO_TLS12
  13176. WOLFSSL_ABI
  13177. WOLFSSL_METHOD* wolfTLSv1_2_server_method(void)
  13178. {
  13179. return wolfTLSv1_2_server_method_ex(NULL);
  13180. }
  13181. WOLFSSL_METHOD* wolfTLSv1_2_server_method_ex(void* heap)
  13182. {
  13183. WOLFSSL_METHOD* method =
  13184. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13185. heap, DYNAMIC_TYPE_METHOD);
  13186. (void)heap;
  13187. WOLFSSL_ENTER("TLSv1_2_server_method_ex");
  13188. if (method) {
  13189. InitSSL_Method(method, MakeTLSv1_2());
  13190. method->side = WOLFSSL_SERVER_END;
  13191. }
  13192. return method;
  13193. }
  13194. #endif /* !WOLFSSL_NO_TLS12 */
  13195. #ifdef WOLFSSL_TLS13
  13196. /* The TLS v1.3 server method data.
  13197. *
  13198. * returns the method data for a TLS v1.3 server.
  13199. */
  13200. WOLFSSL_ABI
  13201. WOLFSSL_METHOD* wolfTLSv1_3_server_method(void)
  13202. {
  13203. return wolfTLSv1_3_server_method_ex(NULL);
  13204. }
  13205. /* The TLS v1.3 server method data.
  13206. *
  13207. * heap The heap used for allocation.
  13208. * returns the method data for a TLS v1.3 server.
  13209. */
  13210. WOLFSSL_METHOD* wolfTLSv1_3_server_method_ex(void* heap)
  13211. {
  13212. WOLFSSL_METHOD* method =
  13213. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13214. heap, DYNAMIC_TYPE_METHOD);
  13215. (void)heap;
  13216. WOLFSSL_ENTER("TLSv1_3_server_method_ex");
  13217. if (method) {
  13218. InitSSL_Method(method, MakeTLSv1_3());
  13219. method->side = WOLFSSL_SERVER_END;
  13220. }
  13221. return method;
  13222. }
  13223. #endif /* WOLFSSL_TLS13 */
  13224. #ifdef WOLFSSL_DTLS
  13225. WOLFSSL_METHOD* wolfDTLS_server_method(void)
  13226. {
  13227. return wolfDTLS_server_method_ex(NULL);
  13228. }
  13229. WOLFSSL_METHOD* wolfDTLS_server_method_ex(void* heap)
  13230. {
  13231. WOLFSSL_METHOD* method =
  13232. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13233. heap, DYNAMIC_TYPE_METHOD);
  13234. (void)heap;
  13235. WOLFSSL_ENTER("DTLS_server_method_ex");
  13236. if (method) {
  13237. #if defined(WOLFSSL_DTLS13)
  13238. InitSSL_Method(method, MakeDTLSv1_3());
  13239. #elif !defined(WOLFSSL_NO_TLS12)
  13240. InitSSL_Method(method, MakeDTLSv1_2());
  13241. #elif !defined(NO_OLD_TLS)
  13242. InitSSL_Method(method, MakeDTLSv1());
  13243. #else
  13244. #error No DTLS version enabled!
  13245. #endif
  13246. method->downgrade = 1;
  13247. method->side = WOLFSSL_SERVER_END;
  13248. }
  13249. return method;
  13250. }
  13251. #ifndef NO_OLD_TLS
  13252. WOLFSSL_METHOD* wolfDTLSv1_server_method(void)
  13253. {
  13254. return wolfDTLSv1_server_method_ex(NULL);
  13255. }
  13256. WOLFSSL_METHOD* wolfDTLSv1_server_method_ex(void* heap)
  13257. {
  13258. WOLFSSL_METHOD* method =
  13259. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13260. heap, DYNAMIC_TYPE_METHOD);
  13261. (void)heap;
  13262. WOLFSSL_ENTER("DTLSv1_server_method_ex");
  13263. if (method) {
  13264. InitSSL_Method(method, MakeDTLSv1());
  13265. method->side = WOLFSSL_SERVER_END;
  13266. }
  13267. return method;
  13268. }
  13269. #endif /* !NO_OLD_TLS */
  13270. #ifndef WOLFSSL_NO_TLS12
  13271. WOLFSSL_METHOD* wolfDTLSv1_2_server_method(void)
  13272. {
  13273. return wolfDTLSv1_2_server_method_ex(NULL);
  13274. }
  13275. WOLFSSL_METHOD* wolfDTLSv1_2_server_method_ex(void* heap)
  13276. {
  13277. WOLFSSL_METHOD* method =
  13278. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13279. heap, DYNAMIC_TYPE_METHOD);
  13280. WOLFSSL_ENTER("DTLSv1_2_server_method_ex");
  13281. (void)heap;
  13282. if (method) {
  13283. InitSSL_Method(method, MakeDTLSv1_2());
  13284. method->side = WOLFSSL_SERVER_END;
  13285. }
  13286. (void)heap;
  13287. return method;
  13288. }
  13289. #endif /* !WOLFSSL_NO_TLS12 */
  13290. #endif /* WOLFSSL_DTLS */
  13291. #endif /* NO_WOLFSSL_SERVER */
  13292. #endif /* NO_TLS */
  13293. #endif /* WOLFCRYPT_ONLY */