tls.c 468 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288
  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. ret = BuildTlsHandshakeHash(ssl, handshake_hash, &hashSz);
  163. if (ret == 0) {
  164. if (XSTRNCMP((const char*)sender, (const char*)kTlsClientStr,
  165. SIZEOF_SENDER) == 0) {
  166. side = kTlsClientFinStr;
  167. }
  168. else if (XSTRNCMP((const char*)sender, (const char*)kTlsServerStr,
  169. SIZEOF_SENDER) == 0) {
  170. side = kTlsServerFinStr;
  171. }
  172. else {
  173. ret = BAD_FUNC_ARG;
  174. WOLFSSL_MSG("Unexpected sender value");
  175. }
  176. }
  177. if (ret == 0) {
  178. #ifdef WOLFSSL_HAVE_PRF
  179. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  180. if (ssl->ctx->TlsFinishedCb) {
  181. void* ctx = wolfSSL_GetTlsFinishedCtx(ssl);
  182. ret = ssl->ctx->TlsFinishedCb(ssl, side, handshake_hash, hashSz,
  183. (byte*)hashes, ctx);
  184. }
  185. if (!ssl->ctx->TlsFinishedCb || ret == PROTOCOLCB_UNAVAILABLE)
  186. #endif
  187. {
  188. PRIVATE_KEY_UNLOCK();
  189. ret = wc_PRF_TLS((byte*)hashes, TLS_FINISHED_SZ,
  190. ssl->arrays->masterSecret, SECRET_LEN, side,
  191. FINISHED_LABEL_SZ, handshake_hash, hashSz,
  192. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  193. ssl->heap, ssl->devId);
  194. PRIVATE_KEY_LOCK();
  195. }
  196. ForceZero(handshake_hash, hashSz);
  197. #else
  198. /* Pseudo random function must be enabled in the configuration. */
  199. ret = PRF_MISSING;
  200. WOLFSSL_ERROR_VERBOSE(ret);
  201. WOLFSSL_MSG("Pseudo-random function is not enabled");
  202. (void)side;
  203. (void)hashes;
  204. #endif
  205. }
  206. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  207. WC_FREE_VAR(handshake_hash, ssl->heap);
  208. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  209. wc_MemZero_Check(handshake_hash, HSHASH_SZ);
  210. #endif
  211. return ret;
  212. }
  213. #endif /* !WOLFSSL_NO_TLS12 */
  214. #ifndef NO_OLD_TLS
  215. #ifdef WOLFSSL_ALLOW_TLSV10
  216. ProtocolVersion MakeTLSv1(void)
  217. {
  218. ProtocolVersion pv;
  219. pv.major = SSLv3_MAJOR;
  220. pv.minor = TLSv1_MINOR;
  221. return pv;
  222. }
  223. #endif /* WOLFSSL_ALLOW_TLSV10 */
  224. ProtocolVersion MakeTLSv1_1(void)
  225. {
  226. ProtocolVersion pv;
  227. pv.major = SSLv3_MAJOR;
  228. pv.minor = TLSv1_1_MINOR;
  229. return pv;
  230. }
  231. #endif /* !NO_OLD_TLS */
  232. #ifndef WOLFSSL_NO_TLS12
  233. ProtocolVersion MakeTLSv1_2(void)
  234. {
  235. ProtocolVersion pv;
  236. pv.major = SSLv3_MAJOR;
  237. pv.minor = TLSv1_2_MINOR;
  238. return pv;
  239. }
  240. #endif /* !WOLFSSL_NO_TLS12 */
  241. #ifdef WOLFSSL_TLS13
  242. /* The TLS v1.3 protocol version.
  243. *
  244. * returns the protocol version data for TLS v1.3.
  245. */
  246. ProtocolVersion MakeTLSv1_3(void)
  247. {
  248. ProtocolVersion pv;
  249. pv.major = SSLv3_MAJOR;
  250. pv.minor = TLSv1_3_MINOR;
  251. return pv;
  252. }
  253. #endif
  254. #ifndef WOLFSSL_NO_TLS12
  255. #ifdef HAVE_EXTENDED_MASTER
  256. static const byte ext_master_label[EXT_MASTER_LABEL_SZ + 1] =
  257. "extended master secret";
  258. #endif
  259. static const byte master_label[MASTER_LABEL_SZ + 1] = "master secret";
  260. static const byte key_label [KEY_LABEL_SZ + 1] = "key expansion";
  261. static int _DeriveTlsKeys(byte* key_dig, word32 key_dig_len,
  262. const byte* ms, word32 msLen,
  263. const byte* sr, const byte* cr,
  264. int tls1_2, int hash_type,
  265. void* heap, int devId)
  266. {
  267. int ret;
  268. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  269. WC_DECLARE_VAR(seed, byte, SEED_LEN, heap);
  270. if (seed == NULL)
  271. return MEMORY_E;
  272. #else
  273. byte seed[SEED_LEN];
  274. #endif
  275. XMEMCPY(seed, sr, RAN_LEN);
  276. XMEMCPY(seed + RAN_LEN, cr, RAN_LEN);
  277. #ifdef WOLFSSL_HAVE_PRF
  278. PRIVATE_KEY_UNLOCK();
  279. ret = wc_PRF_TLS(key_dig, key_dig_len, ms, msLen, key_label, KEY_LABEL_SZ,
  280. seed, SEED_LEN, tls1_2, hash_type, heap, devId);
  281. PRIVATE_KEY_LOCK();
  282. #else
  283. /* Pseudo random function must be enabled in the configuration. */
  284. ret = PRF_MISSING;
  285. WOLFSSL_ERROR_VERBOSE(ret);
  286. WOLFSSL_MSG("Pseudo-random function is not enabled");
  287. (void)key_dig;
  288. (void)key_dig_len;
  289. (void)ms;
  290. (void)msLen;
  291. (void)tls1_2;
  292. (void)hash_type;
  293. (void)heap;
  294. (void)devId;
  295. (void)key_label;
  296. (void)master_label;
  297. #ifdef HAVE_EXTENDED_MASTER
  298. (void)ext_master_label;
  299. #endif
  300. #endif
  301. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  302. WC_FREE_VAR(seed, heap);
  303. #endif
  304. return ret;
  305. }
  306. /* External facing wrapper so user can call as well, 0 on success */
  307. int wolfSSL_DeriveTlsKeys(byte* key_dig, word32 key_dig_len,
  308. const byte* ms, word32 msLen,
  309. const byte* sr, const byte* cr,
  310. int tls1_2, int hash_type)
  311. {
  312. return _DeriveTlsKeys(key_dig, key_dig_len, ms, msLen, sr, cr, tls1_2,
  313. hash_type, NULL, INVALID_DEVID);
  314. }
  315. int DeriveTlsKeys(WOLFSSL* ssl)
  316. {
  317. int ret;
  318. int key_dig_len = 2 * ssl->specs.hash_size +
  319. 2 * ssl->specs.key_size +
  320. 2 * ssl->specs.iv_size;
  321. #ifdef WOLFSSL_SMALL_STACK
  322. byte* key_dig;
  323. #else
  324. byte key_dig[MAX_PRF_DIG];
  325. #endif
  326. #ifdef WOLFSSL_SMALL_STACK
  327. key_dig = (byte*)XMALLOC(MAX_PRF_DIG, ssl->heap, DYNAMIC_TYPE_DIGEST);
  328. if (key_dig == NULL) {
  329. return MEMORY_E;
  330. }
  331. #endif
  332. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  333. ret = PROTOCOLCB_UNAVAILABLE;
  334. if (ssl->ctx->GenSessionKeyCb) {
  335. void* ctx = wolfSSL_GetGenSessionKeyCtx(ssl);
  336. ret = ssl->ctx->GenSessionKeyCb(ssl, ctx);
  337. }
  338. if (!ssl->ctx->GenSessionKeyCb || ret == PROTOCOLCB_UNAVAILABLE)
  339. #endif
  340. ret = _DeriveTlsKeys(key_dig, key_dig_len,
  341. ssl->arrays->masterSecret, SECRET_LEN,
  342. ssl->arrays->serverRandom, ssl->arrays->clientRandom,
  343. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  344. ssl->heap, ssl->devId);
  345. if (ret == 0)
  346. ret = StoreKeys(ssl, key_dig, PROVISION_CLIENT_SERVER);
  347. #ifdef WOLFSSL_SMALL_STACK
  348. XFREE(key_dig, ssl->heap, DYNAMIC_TYPE_DIGEST);
  349. #endif
  350. return ret;
  351. }
  352. static int _MakeTlsMasterSecret(byte* ms, word32 msLen,
  353. const byte* pms, word32 pmsLen,
  354. const byte* cr, const byte* sr,
  355. int tls1_2, int hash_type,
  356. void* heap, int devId)
  357. {
  358. int ret;
  359. #if !defined(WOLFSSL_ASYNC_CRYPT) || defined(WC_ASYNC_NO_HASH)
  360. byte seed[SEED_LEN];
  361. #else
  362. WC_DECLARE_VAR(seed, byte, SEED_LEN, heap);
  363. if (seed == NULL)
  364. return MEMORY_E;
  365. #endif
  366. XMEMCPY(seed, cr, RAN_LEN);
  367. XMEMCPY(seed + RAN_LEN, sr, RAN_LEN);
  368. #ifdef WOLFSSL_HAVE_PRF
  369. PRIVATE_KEY_UNLOCK();
  370. ret = wc_PRF_TLS(ms, msLen, pms, pmsLen, master_label, MASTER_LABEL_SZ,
  371. seed, SEED_LEN, tls1_2, hash_type, heap, devId);
  372. PRIVATE_KEY_LOCK();
  373. #else
  374. /* Pseudo random function must be enabled in the configuration. */
  375. ret = PRF_MISSING;
  376. WOLFSSL_MSG("Pseudo-random function is not enabled");
  377. (void)ms;
  378. (void)msLen;
  379. (void)pms;
  380. (void)pmsLen;
  381. (void)tls1_2;
  382. (void)hash_type;
  383. (void)heap;
  384. (void)devId;
  385. #endif
  386. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  387. WC_FREE_VAR(seed, heap);
  388. #endif
  389. return ret;
  390. }
  391. /* External facing wrapper so user can call as well, 0 on success */
  392. int wolfSSL_MakeTlsMasterSecret(byte* ms, word32 msLen,
  393. const byte* pms, word32 pmsLen,
  394. const byte* cr, const byte* sr,
  395. int tls1_2, int hash_type)
  396. {
  397. return _MakeTlsMasterSecret(ms, msLen, pms, pmsLen, cr, sr, tls1_2,
  398. hash_type, NULL, INVALID_DEVID);
  399. }
  400. #ifdef HAVE_EXTENDED_MASTER
  401. static int _MakeTlsExtendedMasterSecret(byte* ms, word32 msLen,
  402. const byte* pms, word32 pmsLen,
  403. const byte* sHash, word32 sHashLen,
  404. int tls1_2, int hash_type,
  405. void* heap, int devId)
  406. {
  407. int ret;
  408. #ifdef WOLFSSL_HAVE_PRF
  409. PRIVATE_KEY_UNLOCK();
  410. ret = wc_PRF_TLS(ms, msLen, pms, pmsLen, ext_master_label, EXT_MASTER_LABEL_SZ,
  411. sHash, sHashLen, tls1_2, hash_type, heap, devId);
  412. PRIVATE_KEY_LOCK();
  413. #else
  414. /* Pseudo random function must be enabled in the configuration. */
  415. ret = PRF_MISSING;
  416. WOLFSSL_MSG("Pseudo-random function is not enabled");
  417. (void)ms;
  418. (void)msLen;
  419. (void)pms;
  420. (void)pmsLen;
  421. (void)sHash;
  422. (void)sHashLen;
  423. (void)tls1_2;
  424. (void)hash_type;
  425. (void)heap;
  426. (void)devId;
  427. #endif
  428. return ret;
  429. }
  430. /* External facing wrapper so user can call as well, 0 on success */
  431. int wolfSSL_MakeTlsExtendedMasterSecret(byte* ms, word32 msLen,
  432. const byte* pms, word32 pmsLen,
  433. const byte* sHash, word32 sHashLen,
  434. int tls1_2, int hash_type)
  435. {
  436. return _MakeTlsExtendedMasterSecret(ms, msLen, pms, pmsLen, sHash, sHashLen,
  437. tls1_2, hash_type, NULL, INVALID_DEVID);
  438. }
  439. #endif /* HAVE_EXTENDED_MASTER */
  440. int MakeTlsMasterSecret(WOLFSSL* ssl)
  441. {
  442. int ret;
  443. #if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  444. /* If this is called from a sniffer session with keylog file support, obtain
  445. * the master secret from the callback */
  446. if (ssl->snifferSecretCb != NULL) {
  447. ret = ssl->snifferSecretCb(ssl->arrays->clientRandom,
  448. SNIFFER_SECRET_TLS12_MASTER_SECRET,
  449. ssl->arrays->masterSecret);
  450. if (ret != 0) {
  451. return ret;
  452. }
  453. ret = DeriveTlsKeys(ssl);
  454. return ret;
  455. }
  456. #endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
  457. #ifdef HAVE_EXTENDED_MASTER
  458. if (ssl->options.haveEMS) {
  459. word32 hashSz = HSHASH_SZ;
  460. #ifdef WOLFSSL_SMALL_STACK
  461. byte* handshake_hash = (byte*)XMALLOC(HSHASH_SZ, ssl->heap,
  462. DYNAMIC_TYPE_DIGEST);
  463. if (handshake_hash == NULL)
  464. return MEMORY_E;
  465. #else
  466. byte handshake_hash[HSHASH_SZ];
  467. #endif
  468. ret = BuildTlsHandshakeHash(ssl, handshake_hash, &hashSz);
  469. if (ret == 0) {
  470. ret = _MakeTlsExtendedMasterSecret(
  471. ssl->arrays->masterSecret, SECRET_LEN,
  472. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz,
  473. handshake_hash, hashSz,
  474. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  475. ssl->heap, ssl->devId);
  476. ForceZero(handshake_hash, hashSz);
  477. }
  478. #ifdef WOLFSSL_SMALL_STACK
  479. XFREE(handshake_hash, ssl->heap, DYNAMIC_TYPE_DIGEST);
  480. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  481. wc_MemZero_Check(handshake_hash, HSHASH_SZ);
  482. #endif
  483. }
  484. else
  485. #endif /* HAVE_EXTENDED_MASTER */
  486. {
  487. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  488. ret = PROTOCOLCB_UNAVAILABLE;
  489. if (ssl->ctx->GenMasterCb) {
  490. void* ctx = wolfSSL_GetGenMasterSecretCtx(ssl);
  491. ret = ssl->ctx->GenMasterCb(ssl, ctx);
  492. }
  493. if (!ssl->ctx->GenMasterCb || ret == PROTOCOLCB_UNAVAILABLE)
  494. #endif
  495. {
  496. ret = _MakeTlsMasterSecret(ssl->arrays->masterSecret,
  497. SECRET_LEN, ssl->arrays->preMasterSecret,
  498. ssl->arrays->preMasterSz, ssl->arrays->clientRandom,
  499. ssl->arrays->serverRandom, IsAtLeastTLSv1_2(ssl),
  500. ssl->specs.mac_algorithm, ssl->heap, ssl->devId);
  501. }
  502. }
  503. if (ret == 0) {
  504. #ifdef SHOW_SECRETS
  505. /* Wireshark Pre-Master-Secret Format:
  506. * CLIENT_RANDOM <clientrandom> <mastersecret>
  507. */
  508. const char* CLIENT_RANDOM_LABEL = "CLIENT_RANDOM";
  509. int i, pmsPos = 0;
  510. char pmsBuf[13 + 1 + 64 + 1 + 96 + 1 + 1];
  511. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%s ",
  512. CLIENT_RANDOM_LABEL);
  513. pmsPos += XSTRLEN(CLIENT_RANDOM_LABEL) + 1;
  514. for (i = 0; i < RAN_LEN; i++) {
  515. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
  516. ssl->arrays->clientRandom[i]);
  517. pmsPos += 2;
  518. }
  519. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, " ");
  520. pmsPos += 1;
  521. for (i = 0; i < SECRET_LEN; i++) {
  522. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
  523. ssl->arrays->masterSecret[i]);
  524. pmsPos += 2;
  525. }
  526. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "\n");
  527. pmsPos += 1;
  528. /* print master secret */
  529. puts(pmsBuf);
  530. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE)
  531. {
  532. FILE* f = XFOPEN(WOLFSSL_SSLKEYLOGFILE_OUTPUT, "a");
  533. if (f != XBADFILE) {
  534. XFWRITE(pmsBuf, 1, pmsPos, f);
  535. XFCLOSE(f);
  536. }
  537. }
  538. #endif
  539. #endif /* SHOW_SECRETS */
  540. ret = DeriveTlsKeys(ssl);
  541. }
  542. return ret;
  543. }
  544. /* Used by EAP-TLS and EAP-TTLS to derive keying material from
  545. * the master_secret. */
  546. int wolfSSL_make_eap_keys(WOLFSSL* ssl, void* msk, unsigned int len,
  547. const char* label)
  548. {
  549. int ret;
  550. #ifdef WOLFSSL_SMALL_STACK
  551. byte* seed;
  552. #else
  553. byte seed[SEED_LEN];
  554. #endif
  555. #ifdef WOLFSSL_SMALL_STACK
  556. seed = (byte*)XMALLOC(SEED_LEN, ssl->heap, DYNAMIC_TYPE_SEED);
  557. if (seed == NULL)
  558. return MEMORY_E;
  559. #endif
  560. /*
  561. * As per RFC-5281, the order of the client and server randoms is reversed
  562. * from that used by the TLS protocol to derive keys.
  563. */
  564. XMEMCPY(seed, ssl->arrays->clientRandom, RAN_LEN);
  565. XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
  566. #ifdef WOLFSSL_HAVE_PRF
  567. PRIVATE_KEY_UNLOCK();
  568. ret = wc_PRF_TLS((byte*)msk, len, ssl->arrays->masterSecret, SECRET_LEN,
  569. (const byte *)label, (word32)XSTRLEN(label), seed, SEED_LEN,
  570. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  571. ssl->heap, ssl->devId);
  572. PRIVATE_KEY_LOCK();
  573. #else
  574. /* Pseudo random function must be enabled in the configuration. */
  575. ret = PRF_MISSING;
  576. WOLFSSL_MSG("Pseudo-random function is not enabled");
  577. (void)msk;
  578. (void)len;
  579. (void)label;
  580. #endif
  581. #ifdef WOLFSSL_SMALL_STACK
  582. XFREE(seed, ssl->heap, DYNAMIC_TYPE_SEED);
  583. #endif
  584. return ret;
  585. }
  586. /* return HMAC digest type in wolfSSL format */
  587. int wolfSSL_GetHmacType(WOLFSSL* ssl)
  588. {
  589. if (ssl == NULL)
  590. return BAD_FUNC_ARG;
  591. return wolfSSL_GetHmacType_ex(&ssl->specs);
  592. }
  593. int wolfSSL_SetTlsHmacInner(WOLFSSL* ssl, byte* inner, word32 sz, int content,
  594. int verify)
  595. {
  596. if (ssl == NULL || inner == NULL)
  597. return BAD_FUNC_ARG;
  598. XMEMSET(inner, 0, WOLFSSL_TLS_HMAC_INNER_SZ);
  599. WriteSEQ(ssl, verify, inner);
  600. inner[SEQ_SZ] = (byte)content;
  601. inner[SEQ_SZ + ENUM_LEN] = ssl->version.major;
  602. inner[SEQ_SZ + ENUM_LEN + ENUM_LEN] = ssl->version.minor;
  603. c16toa((word16)sz, inner + SEQ_SZ + ENUM_LEN + VERSION_SZ);
  604. return 0;
  605. }
  606. #ifndef WOLFSSL_AEAD_ONLY
  607. #if !defined(WOLFSSL_NO_HASH_RAW) && !defined(HAVE_FIPS) && \
  608. !defined(HAVE_SELFTEST)
  609. /* Update the hash in the HMAC.
  610. *
  611. * hmac HMAC object.
  612. * data Data to be hashed.
  613. * sz Size of data to hash.
  614. * returns 0 on success, otherwise failure.
  615. */
  616. static int Hmac_HashUpdate(Hmac* hmac, const byte* data, word32 sz)
  617. {
  618. int ret = BAD_FUNC_ARG;
  619. switch (hmac->macType) {
  620. #ifndef NO_SHA
  621. case WC_SHA:
  622. ret = wc_ShaUpdate(&hmac->hash.sha, data, sz);
  623. break;
  624. #endif /* !NO_SHA */
  625. #ifndef NO_SHA256
  626. case WC_SHA256:
  627. ret = wc_Sha256Update(&hmac->hash.sha256, data, sz);
  628. break;
  629. #endif /* !NO_SHA256 */
  630. #ifdef WOLFSSL_SHA384
  631. case WC_SHA384:
  632. ret = wc_Sha384Update(&hmac->hash.sha384, data, sz);
  633. break;
  634. #endif /* WOLFSSL_SHA384 */
  635. #ifdef WOLFSSL_SHA512
  636. case WC_SHA512:
  637. ret = wc_Sha512Update(&hmac->hash.sha512, data, sz);
  638. break;
  639. #endif /* WOLFSSL_SHA512 */
  640. #ifdef WOLFSSL_SM3
  641. case WC_SM3:
  642. ret = wc_Sm3Update(&hmac->hash.sm3, data, sz);
  643. break;
  644. #endif /* WOLFSSL_SM3 */
  645. default:
  646. break;
  647. }
  648. return ret;
  649. }
  650. /* Finalize the hash but don't put the EOC, padding or length in.
  651. *
  652. * hmac HMAC object.
  653. * hash Hash result.
  654. * returns 0 on success, otherwise failure.
  655. */
  656. static int Hmac_HashFinalRaw(Hmac* hmac, unsigned char* hash)
  657. {
  658. int ret = BAD_FUNC_ARG;
  659. switch (hmac->macType) {
  660. #ifndef NO_SHA
  661. case WC_SHA:
  662. ret = wc_ShaFinalRaw(&hmac->hash.sha, hash);
  663. break;
  664. #endif /* !NO_SHA */
  665. #ifndef NO_SHA256
  666. case WC_SHA256:
  667. ret = wc_Sha256FinalRaw(&hmac->hash.sha256, hash);
  668. break;
  669. #endif /* !NO_SHA256 */
  670. #ifdef WOLFSSL_SHA384
  671. case WC_SHA384:
  672. ret = wc_Sha384FinalRaw(&hmac->hash.sha384, hash);
  673. break;
  674. #endif /* WOLFSSL_SHA384 */
  675. #ifdef WOLFSSL_SHA512
  676. case WC_SHA512:
  677. ret = wc_Sha512FinalRaw(&hmac->hash.sha512, hash);
  678. break;
  679. #endif /* WOLFSSL_SHA512 */
  680. #ifdef WOLFSSL_SM3
  681. case WC_SM3:
  682. ret = wc_Sm3FinalRaw(&hmac->hash.sm3, hash);
  683. break;
  684. #endif /* WOLFSSL_SM3 */
  685. default:
  686. break;
  687. }
  688. return ret;
  689. }
  690. /* Finalize the HMAC by performing outer hash.
  691. *
  692. * hmac HMAC object.
  693. * mac MAC result.
  694. * returns 0 on success, otherwise failure.
  695. */
  696. static int Hmac_OuterHash(Hmac* hmac, unsigned char* mac)
  697. {
  698. int ret = BAD_FUNC_ARG;
  699. wc_HashAlg hash;
  700. enum wc_HashType hashType = (enum wc_HashType)hmac->macType;
  701. int digestSz = wc_HashGetDigestSize(hashType);
  702. int blockSz = wc_HashGetBlockSize(hashType);
  703. if ((digestSz >= 0) && (blockSz >= 0)) {
  704. ret = wc_HashInit(&hash, hashType);
  705. }
  706. if (ret == 0) {
  707. ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->opad,
  708. blockSz);
  709. if (ret == 0)
  710. ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->innerHash,
  711. digestSz);
  712. if (ret == 0)
  713. ret = wc_HashFinal(&hash, hashType, mac);
  714. wc_HashFree(&hash, hashType);
  715. }
  716. return ret;
  717. }
  718. /* Calculate the HMAC of the header + message data.
  719. * Constant time implementation using wc_Sha*FinalRaw().
  720. *
  721. * hmac HMAC object.
  722. * digest MAC result.
  723. * in Message data.
  724. * sz Size of the message data.
  725. * header Constructed record header with length of handshake data.
  726. * returns 0 on success, otherwise failure.
  727. */
  728. static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in,
  729. word32 sz, int macLen, byte* header)
  730. {
  731. byte lenBytes[8];
  732. int i, j;
  733. unsigned int k;
  734. int blockBits, blockMask;
  735. int lastBlockLen, extraLen, eocIndex;
  736. int blocks, safeBlocks, lenBlock, eocBlock;
  737. unsigned int maxLen;
  738. int blockSz, padSz;
  739. int ret;
  740. word32 realLen;
  741. byte extraBlock;
  742. switch (hmac->macType) {
  743. #ifndef NO_SHA
  744. case WC_SHA:
  745. blockSz = WC_SHA_BLOCK_SIZE;
  746. blockBits = 6;
  747. padSz = WC_SHA_BLOCK_SIZE - WC_SHA_PAD_SIZE + 1;
  748. break;
  749. #endif /* !NO_SHA */
  750. #ifndef NO_SHA256
  751. case WC_SHA256:
  752. blockSz = WC_SHA256_BLOCK_SIZE;
  753. blockBits = 6;
  754. padSz = WC_SHA256_BLOCK_SIZE - WC_SHA256_PAD_SIZE + 1;
  755. break;
  756. #endif /* !NO_SHA256 */
  757. #ifdef WOLFSSL_SHA384
  758. case WC_SHA384:
  759. blockSz = WC_SHA384_BLOCK_SIZE;
  760. blockBits = 7;
  761. padSz = WC_SHA384_BLOCK_SIZE - WC_SHA384_PAD_SIZE + 1;
  762. break;
  763. #endif /* WOLFSSL_SHA384 */
  764. #ifdef WOLFSSL_SHA512
  765. case WC_SHA512:
  766. blockSz = WC_SHA512_BLOCK_SIZE;
  767. blockBits = 7;
  768. padSz = WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE + 1;
  769. break;
  770. #endif /* WOLFSSL_SHA512 */
  771. #ifdef WOLFSSL_SM3
  772. case WC_SM3:
  773. blockSz = WC_SM3_BLOCK_SIZE;
  774. blockBits = 6;
  775. padSz = WC_SM3_BLOCK_SIZE - WC_SM3_PAD_SIZE + 1;
  776. break;
  777. #endif /* WOLFSSL_SM3 */
  778. default:
  779. return BAD_FUNC_ARG;
  780. }
  781. blockMask = blockSz - 1;
  782. /* Size of data to HMAC if padding length byte is zero. */
  783. maxLen = WOLFSSL_TLS_HMAC_INNER_SZ + sz - 1 - macLen;
  784. /* Complete data (including padding) has block for EOC and/or length. */
  785. extraBlock = ctSetLTE((maxLen + padSz) & blockMask, padSz);
  786. /* Total number of blocks for data including padding. */
  787. blocks = ((maxLen + blockSz - 1) >> blockBits) + extraBlock;
  788. /* Up to last 6 blocks can be hashed safely. */
  789. safeBlocks = blocks - 6;
  790. /* Length of message data. */
  791. realLen = maxLen - in[sz - 1];
  792. /* Number of message bytes in last block. */
  793. lastBlockLen = realLen & blockMask;
  794. /* Number of padding bytes in last block. */
  795. extraLen = ((blockSz * 2 - padSz - lastBlockLen) & blockMask) + 1;
  796. /* Number of blocks to create for hash. */
  797. lenBlock = (realLen + extraLen) >> blockBits;
  798. /* Block containing EOC byte. */
  799. eocBlock = realLen >> blockBits;
  800. /* Index of EOC byte in block. */
  801. eocIndex = realLen & blockMask;
  802. /* Add length of hmac's ipad to total length. */
  803. realLen += blockSz;
  804. /* Length as bits - 8 bytes bigendian. */
  805. c32toa(realLen >> ((sizeof(word32) * 8) - 3), lenBytes);
  806. c32toa(realLen << 3, lenBytes + sizeof(word32));
  807. ret = Hmac_HashUpdate(hmac, (unsigned char*)hmac->ipad, blockSz);
  808. if (ret != 0)
  809. return ret;
  810. XMEMSET(hmac->innerHash, 0, macLen);
  811. if (safeBlocks > 0) {
  812. ret = Hmac_HashUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ);
  813. if (ret != 0)
  814. return ret;
  815. ret = Hmac_HashUpdate(hmac, in, safeBlocks * blockSz -
  816. WOLFSSL_TLS_HMAC_INNER_SZ);
  817. if (ret != 0)
  818. return ret;
  819. }
  820. else
  821. safeBlocks = 0;
  822. XMEMSET(digest, 0, macLen);
  823. k = safeBlocks * blockSz;
  824. for (i = safeBlocks; i < blocks; i++) {
  825. unsigned char hashBlock[WC_MAX_BLOCK_SIZE];
  826. unsigned char isEocBlock = ctMaskEq(i, eocBlock);
  827. unsigned char isOutBlock = ctMaskEq(i, lenBlock);
  828. for (j = 0; j < blockSz; j++) {
  829. unsigned char atEoc = ctMaskEq(j, eocIndex) & isEocBlock;
  830. unsigned char pastEoc = ctMaskGT(j, eocIndex) & isEocBlock;
  831. unsigned char b = 0;
  832. if (k < WOLFSSL_TLS_HMAC_INNER_SZ)
  833. b = header[k];
  834. else if (k < maxLen)
  835. b = in[k - WOLFSSL_TLS_HMAC_INNER_SZ];
  836. k++;
  837. b = ctMaskSel(atEoc, 0x80, b);
  838. b &= (unsigned char)~(word32)pastEoc;
  839. b &= ((unsigned char)~(word32)isOutBlock) | isEocBlock;
  840. if (j >= blockSz - 8) {
  841. b = ctMaskSel(isOutBlock, lenBytes[j - (blockSz - 8)], b);
  842. }
  843. hashBlock[j] = b;
  844. }
  845. ret = Hmac_HashUpdate(hmac, hashBlock, blockSz);
  846. if (ret != 0)
  847. return ret;
  848. ret = Hmac_HashFinalRaw(hmac, hashBlock);
  849. if (ret != 0)
  850. return ret;
  851. for (j = 0; j < macLen; j++)
  852. ((unsigned char*)hmac->innerHash)[j] |= hashBlock[j] & isOutBlock;
  853. }
  854. ret = Hmac_OuterHash(hmac, digest);
  855. return ret;
  856. }
  857. #endif
  858. #if defined(WOLFSSL_NO_HASH_RAW) || defined(HAVE_FIPS) || \
  859. defined(HAVE_SELFTEST) || defined(HAVE_BLAKE2)
  860. /* Calculate the HMAC of the header + message data.
  861. * Constant time implementation using normal hashing operations.
  862. * Update-Final need to be constant time.
  863. *
  864. * hmac HMAC object.
  865. * digest MAC result.
  866. * in Message data.
  867. * sz Size of the message data.
  868. * header Constructed record header with length of handshake data.
  869. * returns 0 on success, otherwise failure.
  870. */
  871. static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in,
  872. word32 sz, byte* header)
  873. {
  874. byte dummy[WC_MAX_BLOCK_SIZE] = {0};
  875. int ret = 0;
  876. word32 msgSz, blockSz, macSz, padSz, maxSz, realSz;
  877. word32 offset = 0;
  878. int msgBlocks, blocks, blockBits;
  879. int i;
  880. switch (hmac->macType) {
  881. #ifndef NO_SHA
  882. case WC_SHA:
  883. blockSz = WC_SHA_BLOCK_SIZE;
  884. blockBits = 6;
  885. macSz = WC_SHA_DIGEST_SIZE;
  886. padSz = WC_SHA_BLOCK_SIZE - WC_SHA_PAD_SIZE + 1;
  887. break;
  888. #endif /* !NO_SHA */
  889. #ifndef NO_SHA256
  890. case WC_SHA256:
  891. blockSz = WC_SHA256_BLOCK_SIZE;
  892. blockBits = 6;
  893. macSz = WC_SHA256_DIGEST_SIZE;
  894. padSz = WC_SHA256_BLOCK_SIZE - WC_SHA256_PAD_SIZE + 1;
  895. break;
  896. #endif /* !NO_SHA256 */
  897. #ifdef WOLFSSL_SHA384
  898. case WC_SHA384:
  899. blockSz = WC_SHA384_BLOCK_SIZE;
  900. blockBits = 7;
  901. macSz = WC_SHA384_DIGEST_SIZE;
  902. padSz = WC_SHA384_BLOCK_SIZE - WC_SHA384_PAD_SIZE + 1;
  903. break;
  904. #endif /* WOLFSSL_SHA384 */
  905. #ifdef WOLFSSL_SHA512
  906. case WC_SHA512:
  907. blockSz = WC_SHA512_BLOCK_SIZE;
  908. blockBits = 7;
  909. macSz = WC_SHA512_DIGEST_SIZE;
  910. padSz = WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE + 1;
  911. break;
  912. #endif /* WOLFSSL_SHA512 */
  913. #ifdef HAVE_BLAKE2
  914. case WC_HASH_TYPE_BLAKE2B:
  915. blockSz = BLAKE2B_BLOCKBYTES;
  916. blockBits = 7;
  917. macSz = BLAKE2B_256;
  918. padSz = 0;
  919. break;
  920. #endif /* HAVE_BLAKE2 */
  921. #ifdef WOLFSSL_SM3
  922. case WC_SM3:
  923. blockSz = WC_SM3_BLOCK_SIZE;
  924. blockBits = 6;
  925. macSz = WC_SM3_DIGEST_SIZE;
  926. padSz = WC_SM3_BLOCK_SIZE - WC_SM3_PAD_SIZE + 1;
  927. break;
  928. #endif
  929. default:
  930. WOLFSSL_MSG("ERROR: Hmac_UpdateFinal failed, no hmac->macType");
  931. return BAD_FUNC_ARG;
  932. }
  933. msgSz = sz - (1 + in[sz - 1] + macSz);
  934. /* Make negative result 0 */
  935. msgSz &= ~(0 - (msgSz >> 31));
  936. realSz = WOLFSSL_TLS_HMAC_INNER_SZ + msgSz;
  937. maxSz = WOLFSSL_TLS_HMAC_INNER_SZ + (sz - 1) - macSz;
  938. /* Make negative result 0 */
  939. maxSz &= ~(0 - (maxSz >> 31));
  940. /* Calculate #blocks processed in HMAC for max and real data. */
  941. blocks = maxSz >> blockBits;
  942. blocks += ((maxSz + padSz) % blockSz) < padSz;
  943. msgBlocks = realSz >> blockBits;
  944. /* #Extra blocks to process. */
  945. blocks -= msgBlocks + ((((realSz + padSz) % blockSz) < padSz) ? 1 : 0);
  946. /* Calculate whole blocks. */
  947. msgBlocks--;
  948. ret = wc_HmacUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ);
  949. if (ret == 0) {
  950. /* Fill the rest of the block with any available data. */
  951. word32 currSz = ctMaskLT(msgSz, blockSz) & msgSz;
  952. currSz |= ctMaskGTE(msgSz, blockSz) & blockSz;
  953. currSz -= WOLFSSL_TLS_HMAC_INNER_SZ;
  954. currSz &= ~(0 - (currSz >> 31));
  955. ret = wc_HmacUpdate(hmac, in, currSz);
  956. offset = currSz;
  957. }
  958. if (ret == 0) {
  959. /* Do the hash operations on a block basis. */
  960. for (i = 0; i < msgBlocks; i++, offset += blockSz) {
  961. ret = wc_HmacUpdate(hmac, in + offset, blockSz);
  962. if (ret != 0)
  963. break;
  964. }
  965. }
  966. if (ret == 0)
  967. ret = wc_HmacUpdate(hmac, in + offset, msgSz - offset);
  968. if (ret == 0)
  969. ret = wc_HmacFinal(hmac, digest);
  970. if (ret == 0) {
  971. /* Do the dummy hash operations. Do at least one. */
  972. for (i = 0; i < blocks + 1; i++) {
  973. ret = wc_HmacUpdate(hmac, dummy, blockSz);
  974. if (ret != 0)
  975. break;
  976. }
  977. }
  978. return ret;
  979. }
  980. #endif
  981. int TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, int padSz,
  982. int content, int verify, int epochOrder)
  983. {
  984. Hmac hmac;
  985. byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
  986. int ret = 0;
  987. const byte* macSecret = NULL;
  988. word32 hashSz = 0;
  989. if (ssl == NULL)
  990. return BAD_FUNC_ARG;
  991. #ifdef HAVE_TRUNCATED_HMAC
  992. hashSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  993. : ssl->specs.hash_size;
  994. #else
  995. hashSz = ssl->specs.hash_size;
  996. #endif
  997. #ifdef HAVE_FUZZER
  998. /* Fuzz "in" buffer with sz to be used in HMAC algorithm */
  999. if (ssl->fuzzerCb) {
  1000. if (verify && padSz >= 0) {
  1001. ssl->fuzzerCb(ssl, in, sz + hashSz + padSz + 1, FUZZ_HMAC,
  1002. ssl->fuzzerCtx);
  1003. }
  1004. else {
  1005. ssl->fuzzerCb(ssl, in, sz, FUZZ_HMAC, ssl->fuzzerCtx);
  1006. }
  1007. }
  1008. #endif
  1009. if (!ssl->options.dtls)
  1010. wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, verify);
  1011. else
  1012. wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, epochOrder);
  1013. ret = wc_HmacInit(&hmac, ssl->heap, ssl->devId);
  1014. if (ret != 0)
  1015. return ret;
  1016. #ifdef WOLFSSL_DTLS
  1017. if (ssl->options.dtls)
  1018. macSecret = wolfSSL_GetDtlsMacSecret(ssl, verify, epochOrder);
  1019. else
  1020. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  1021. #else
  1022. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  1023. #endif
  1024. ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
  1025. macSecret,
  1026. ssl->specs.hash_size);
  1027. if (ret == 0) {
  1028. /* Constant time verification required. */
  1029. if (verify && padSz >= 0) {
  1030. #if !defined(WOLFSSL_NO_HASH_RAW) && !defined(HAVE_FIPS) && \
  1031. !defined(HAVE_SELFTEST)
  1032. #ifdef HAVE_BLAKE2
  1033. if (wolfSSL_GetHmacType(ssl) == WC_HASH_TYPE_BLAKE2B) {
  1034. ret = Hmac_UpdateFinal(&hmac, digest, in,
  1035. sz + hashSz + padSz + 1, myInner);
  1036. }
  1037. else
  1038. #endif
  1039. {
  1040. ret = Hmac_UpdateFinal_CT(&hmac, digest, in,
  1041. sz + hashSz + padSz + 1, hashSz, myInner);
  1042. }
  1043. #else
  1044. ret = Hmac_UpdateFinal(&hmac, digest, in, sz + hashSz + padSz + 1,
  1045. myInner);
  1046. #endif
  1047. }
  1048. else {
  1049. ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
  1050. if (ret == 0)
  1051. ret = wc_HmacUpdate(&hmac, in, sz); /* content */
  1052. if (ret == 0)
  1053. ret = wc_HmacFinal(&hmac, digest);
  1054. }
  1055. }
  1056. wc_HmacFree(&hmac);
  1057. return ret;
  1058. }
  1059. #endif /* WOLFSSL_AEAD_ONLY */
  1060. #endif /* !WOLFSSL_NO_TLS12 */
  1061. int wolfSSL_GetHmacType_ex(CipherSpecs* specs)
  1062. {
  1063. if (specs == NULL)
  1064. return BAD_FUNC_ARG;
  1065. switch (specs->mac_algorithm) {
  1066. #ifndef NO_MD5
  1067. case md5_mac:
  1068. {
  1069. return WC_MD5;
  1070. }
  1071. #endif
  1072. #ifndef NO_SHA256
  1073. case sha256_mac:
  1074. {
  1075. return WC_SHA256;
  1076. }
  1077. #endif
  1078. #ifdef WOLFSSL_SHA384
  1079. case sha384_mac:
  1080. {
  1081. return WC_SHA384;
  1082. }
  1083. #endif
  1084. #ifdef WOLFSSL_SM3
  1085. case sm3_mac:
  1086. {
  1087. return WC_SM3;
  1088. }
  1089. #endif
  1090. #ifndef NO_SHA
  1091. case sha_mac:
  1092. {
  1093. return WC_SHA;
  1094. }
  1095. #endif
  1096. #ifdef HAVE_BLAKE2
  1097. case blake2b_mac:
  1098. {
  1099. return BLAKE2B_ID;
  1100. }
  1101. #endif
  1102. default:
  1103. {
  1104. return WOLFSSL_FATAL_ERROR;
  1105. }
  1106. }
  1107. }
  1108. #ifdef HAVE_TLS_EXTENSIONS
  1109. /**
  1110. * The TLSX semaphore is used to calculate the size of the extensions to be sent
  1111. * from one peer to another.
  1112. */
  1113. /** Supports up to 72 flags. Increase as needed. */
  1114. #define SEMAPHORE_SIZE 9
  1115. /**
  1116. * Converts the extension type (id) to an index in the semaphore.
  1117. *
  1118. * Official reference for TLS extension types:
  1119. * http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xml
  1120. *
  1121. * Motivation:
  1122. * Previously, we used the extension type itself as the index of that
  1123. * extension in the semaphore as the extension types were declared
  1124. * sequentially, but maintain a semaphore as big as the number of available
  1125. * extensions is no longer an option since the release of renegotiation_info.
  1126. *
  1127. * How to update:
  1128. * Assign extension types that extrapolate the number of available semaphores
  1129. * to the first available index going backwards in the semaphore array.
  1130. * When adding a new extension type that don't extrapolate the number of
  1131. * available semaphores, check for a possible collision with with a
  1132. * 'remapped' extension type.
  1133. *
  1134. * Update TLSX_Parse for duplicate detection if more added above 62.
  1135. */
  1136. static WC_INLINE word16 TLSX_ToSemaphore(word16 type)
  1137. {
  1138. switch (type) {
  1139. case TLSX_RENEGOTIATION_INFO: /* 0xFF01 */
  1140. return 63;
  1141. #ifdef WOLFSSL_QUIC
  1142. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT: /* 0xffa5 */
  1143. return 64;
  1144. #endif
  1145. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1146. case TLSX_ECH: /* 0xfe0d */
  1147. return 65;
  1148. #endif
  1149. default:
  1150. if (type > 62) {
  1151. /* This message SHOULD only happens during the adding of
  1152. new TLS extensions in which its IANA number overflows
  1153. the current semaphore's range, or if its number already
  1154. is assigned to be used by another extension.
  1155. Use this check value for the new extension and decrement
  1156. the check value by one. */
  1157. WOLFSSL_MSG("### TLSX semaphore collision or overflow detected!");
  1158. }
  1159. }
  1160. return type;
  1161. }
  1162. /** Checks if a specific light (tls extension) is not set in the semaphore. */
  1163. #define IS_OFF(semaphore, light) \
  1164. (!(((semaphore)[(light) / 8] & (byte) (0x01 << ((light) % 8)))))
  1165. /** Turn on a specific light (tls extension) in the semaphore. */
  1166. /* the semaphore marks the extensions already written to the message */
  1167. #define TURN_ON(semaphore, light) \
  1168. ((semaphore)[(light) / 8] |= (byte) (0x01 << ((light) % 8)))
  1169. /** Turn off a specific light (tls extension) in the semaphore. */
  1170. #define TURN_OFF(semaphore, light) \
  1171. ((semaphore)[(light) / 8] &= (byte) ~(0x01 << ((light) % 8)))
  1172. /** Creates a new extension. */
  1173. static TLSX* TLSX_New(TLSX_Type type, const void* data, void* heap)
  1174. {
  1175. TLSX* extension = (TLSX*)XMALLOC(sizeof(TLSX), heap, DYNAMIC_TYPE_TLSX);
  1176. (void)heap;
  1177. if (extension) {
  1178. extension->type = type;
  1179. extension->data = (void*)data;
  1180. extension->resp = 0;
  1181. extension->next = NULL;
  1182. }
  1183. return extension;
  1184. }
  1185. /**
  1186. * Creates a new extension and appends it to the provided list.
  1187. * Checks for duplicate extensions, keeps the newest.
  1188. */
  1189. int TLSX_Append(TLSX** list, TLSX_Type type, const void* data, void* heap)
  1190. {
  1191. TLSX* extension = TLSX_New(type, data, heap);
  1192. TLSX* cur;
  1193. TLSX** prevNext = list;
  1194. if (extension == NULL)
  1195. return MEMORY_E;
  1196. for (cur = *list; cur != NULL;) {
  1197. if (cur->type == type) {
  1198. *prevNext = cur->next;
  1199. cur->next = NULL;
  1200. TLSX_FreeAll(cur, heap);
  1201. cur = *prevNext;
  1202. }
  1203. else {
  1204. prevNext = &cur->next;
  1205. cur = cur->next;
  1206. }
  1207. }
  1208. /* Append the extension to the list */
  1209. *prevNext = extension;
  1210. return 0;
  1211. }
  1212. /**
  1213. * Creates a new extension and pushes it to the provided list.
  1214. * Checks for duplicate extensions, keeps the newest.
  1215. */
  1216. int TLSX_Push(TLSX** list, TLSX_Type type, const void* data, void* heap)
  1217. {
  1218. TLSX* extension = TLSX_New(type, data, heap);
  1219. if (extension == NULL)
  1220. return MEMORY_E;
  1221. /* pushes the new extension on the list. */
  1222. extension->next = *list;
  1223. *list = extension;
  1224. /* remove duplicate extensions, there should be only one of each type. */
  1225. do {
  1226. if (extension->next && extension->next->type == type) {
  1227. TLSX *next = extension->next;
  1228. extension->next = next->next;
  1229. next->next = NULL;
  1230. TLSX_FreeAll(next, heap);
  1231. /* there is no way to occur more than
  1232. * two extensions of the same type.
  1233. */
  1234. break;
  1235. }
  1236. } while ((extension = extension->next));
  1237. return 0;
  1238. }
  1239. #ifndef NO_WOLFSSL_CLIENT
  1240. int TLSX_CheckUnsupportedExtension(WOLFSSL* ssl, TLSX_Type type);
  1241. int TLSX_CheckUnsupportedExtension(WOLFSSL* ssl, TLSX_Type type)
  1242. {
  1243. TLSX *extension = TLSX_Find(ssl->extensions, type);
  1244. if (!extension)
  1245. extension = TLSX_Find(ssl->ctx->extensions, type);
  1246. return extension == NULL;
  1247. }
  1248. int TLSX_HandleUnsupportedExtension(WOLFSSL* ssl);
  1249. int TLSX_HandleUnsupportedExtension(WOLFSSL* ssl)
  1250. {
  1251. SendAlert(ssl, alert_fatal, unsupported_extension);
  1252. WOLFSSL_ERROR_VERBOSE(UNSUPPORTED_EXTENSION);
  1253. return UNSUPPORTED_EXTENSION;
  1254. }
  1255. #else
  1256. #define TLSX_CheckUnsupportedExtension(ssl, type) 0
  1257. #define TLSX_HandleUnsupportedExtension(ssl) 0
  1258. #endif
  1259. #if !defined(NO_WOLFSSL_SERVER) || defined(WOLFSSL_TLS13)
  1260. void TLSX_SetResponse(WOLFSSL* ssl, TLSX_Type type);
  1261. /** Mark an extension to be sent back to the client. */
  1262. void TLSX_SetResponse(WOLFSSL* ssl, TLSX_Type type)
  1263. {
  1264. TLSX *extension = TLSX_Find(ssl->extensions, type);
  1265. if (extension)
  1266. extension->resp = 1;
  1267. }
  1268. #endif
  1269. /******************************************************************************/
  1270. /* Application-Layer Protocol Negotiation */
  1271. /******************************************************************************/
  1272. #ifdef HAVE_ALPN
  1273. /** Creates a new ALPN object, providing protocol name to use. */
  1274. static ALPN* TLSX_ALPN_New(char *protocol_name, word16 protocol_nameSz,
  1275. void* heap)
  1276. {
  1277. ALPN *alpn;
  1278. WOLFSSL_ENTER("TLSX_ALPN_New");
  1279. if (protocol_name == NULL ||
  1280. protocol_nameSz > WOLFSSL_MAX_ALPN_PROTO_NAME_LEN) {
  1281. WOLFSSL_MSG("Invalid arguments");
  1282. return NULL;
  1283. }
  1284. alpn = (ALPN*)XMALLOC(sizeof(ALPN), heap, DYNAMIC_TYPE_TLSX);
  1285. if (alpn == NULL) {
  1286. WOLFSSL_MSG("Memory failure");
  1287. return NULL;
  1288. }
  1289. alpn->next = NULL;
  1290. alpn->negotiated = 0;
  1291. alpn->options = 0;
  1292. alpn->protocol_name = (char*)XMALLOC(protocol_nameSz + 1,
  1293. heap, DYNAMIC_TYPE_TLSX);
  1294. if (alpn->protocol_name == NULL) {
  1295. WOLFSSL_MSG("Memory failure");
  1296. XFREE(alpn, heap, DYNAMIC_TYPE_TLSX);
  1297. return NULL;
  1298. }
  1299. XMEMCPY(alpn->protocol_name, protocol_name, protocol_nameSz);
  1300. alpn->protocol_name[protocol_nameSz] = 0;
  1301. (void)heap;
  1302. return alpn;
  1303. }
  1304. /** Releases an ALPN object. */
  1305. static void TLSX_ALPN_Free(ALPN *alpn, void* heap)
  1306. {
  1307. (void)heap;
  1308. if (alpn == NULL)
  1309. return;
  1310. XFREE(alpn->protocol_name, heap, DYNAMIC_TYPE_TLSX);
  1311. XFREE(alpn, heap, DYNAMIC_TYPE_TLSX);
  1312. }
  1313. /** Releases all ALPN objects in the provided list. */
  1314. static void TLSX_ALPN_FreeAll(ALPN *list, void* heap)
  1315. {
  1316. ALPN* alpn;
  1317. while ((alpn = list)) {
  1318. list = alpn->next;
  1319. TLSX_ALPN_Free(alpn, heap);
  1320. }
  1321. }
  1322. /** Tells the buffered size of the ALPN objects in a list. */
  1323. static word16 TLSX_ALPN_GetSize(ALPN *list)
  1324. {
  1325. ALPN* alpn;
  1326. word16 length = OPAQUE16_LEN; /* list length */
  1327. while ((alpn = list)) {
  1328. list = alpn->next;
  1329. length++; /* protocol name length is on one byte */
  1330. length += (word16)XSTRLEN(alpn->protocol_name);
  1331. }
  1332. return length;
  1333. }
  1334. /** Writes the ALPN objects of a list in a buffer. */
  1335. static word16 TLSX_ALPN_Write(ALPN *list, byte *output)
  1336. {
  1337. ALPN* alpn;
  1338. word16 length = 0;
  1339. word16 offset = OPAQUE16_LEN; /* list length offset */
  1340. while ((alpn = list)) {
  1341. list = alpn->next;
  1342. length = (word16)XSTRLEN(alpn->protocol_name);
  1343. /* protocol name length */
  1344. output[offset++] = (byte)length;
  1345. /* protocol name value */
  1346. XMEMCPY(output + offset, alpn->protocol_name, length);
  1347. offset += length;
  1348. }
  1349. /* writing list length */
  1350. c16toa(offset - OPAQUE16_LEN, output);
  1351. return offset;
  1352. }
  1353. /** Finds a protocol name in the provided ALPN list */
  1354. static ALPN* TLSX_ALPN_Find(ALPN *list, char *protocol_name, word16 size)
  1355. {
  1356. ALPN *alpn;
  1357. if (list == NULL || protocol_name == NULL)
  1358. return NULL;
  1359. alpn = list;
  1360. while (alpn != NULL && (
  1361. (word16)XSTRLEN(alpn->protocol_name) != size ||
  1362. XSTRNCMP(alpn->protocol_name, protocol_name, size)))
  1363. alpn = alpn->next;
  1364. return alpn;
  1365. }
  1366. /** Set the ALPN matching client and server requirements */
  1367. static int TLSX_SetALPN(TLSX** extensions, const void* data, word16 size,
  1368. void* heap)
  1369. {
  1370. ALPN *alpn;
  1371. int ret;
  1372. if (extensions == NULL || data == NULL)
  1373. return BAD_FUNC_ARG;
  1374. alpn = TLSX_ALPN_New((char *)data, size, heap);
  1375. if (alpn == NULL) {
  1376. WOLFSSL_MSG("Memory failure");
  1377. return MEMORY_E;
  1378. }
  1379. alpn->negotiated = 1;
  1380. ret = TLSX_Push(extensions, TLSX_APPLICATION_LAYER_PROTOCOL, (void*)alpn,
  1381. heap);
  1382. if (ret != 0) {
  1383. TLSX_ALPN_Free(alpn, heap);
  1384. return ret;
  1385. }
  1386. return WOLFSSL_SUCCESS;
  1387. }
  1388. static int ALPN_find_match(WOLFSSL *ssl, TLSX **pextension,
  1389. const byte **psel, byte *psel_len,
  1390. const byte *alpn_val, word16 alpn_val_len)
  1391. {
  1392. TLSX *extension;
  1393. ALPN *alpn, *list;
  1394. const byte *sel = NULL, *s;
  1395. byte sel_len = 0, wlen;
  1396. extension = TLSX_Find(ssl->extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1397. if (extension == NULL)
  1398. extension = TLSX_Find(ssl->ctx->extensions,
  1399. TLSX_APPLICATION_LAYER_PROTOCOL);
  1400. /* No ALPN configured here */
  1401. if (extension == NULL || extension->data == NULL) {
  1402. *pextension = NULL;
  1403. *psel = NULL;
  1404. *psel_len = 0;
  1405. return 0;
  1406. }
  1407. list = (ALPN*)extension->data;
  1408. for (s = alpn_val;
  1409. (s - alpn_val) < alpn_val_len;
  1410. s += wlen) {
  1411. wlen = *s++; /* bounds already checked on save */
  1412. alpn = TLSX_ALPN_Find(list, (char*)s, wlen);
  1413. if (alpn != NULL) {
  1414. WOLFSSL_MSG("ALPN protocol match");
  1415. sel = s,
  1416. sel_len = wlen;
  1417. break;
  1418. }
  1419. }
  1420. if (sel == NULL) {
  1421. WOLFSSL_MSG("No ALPN protocol match");
  1422. /* do nothing if no protocol match between client and server and option
  1423. is set to continue (like OpenSSL) */
  1424. if (list->options & WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) {
  1425. WOLFSSL_MSG("Continue on mismatch");
  1426. }
  1427. else {
  1428. SendAlert(ssl, alert_fatal, no_application_protocol);
  1429. WOLFSSL_ERROR_VERBOSE(UNKNOWN_ALPN_PROTOCOL_NAME_E);
  1430. return UNKNOWN_ALPN_PROTOCOL_NAME_E;
  1431. }
  1432. }
  1433. *pextension = extension;
  1434. *psel = sel;
  1435. *psel_len = sel_len;
  1436. return 0;
  1437. }
  1438. int ALPN_Select(WOLFSSL *ssl)
  1439. {
  1440. TLSX *extension;
  1441. const byte *sel = NULL;
  1442. byte sel_len = 0;
  1443. int r = 0;
  1444. WOLFSSL_ENTER("ALPN_Select");
  1445. if (ssl->alpn_peer_requested == NULL)
  1446. return 0;
  1447. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  1448. if (ssl->alpnSelect != NULL && ssl->options.side == WOLFSSL_SERVER_END) {
  1449. r = ssl->alpnSelect(ssl, &sel, &sel_len, ssl->alpn_peer_requested,
  1450. ssl->alpn_peer_requested_length, ssl->alpnSelectArg);
  1451. switch (r) {
  1452. case SSL_TLSEXT_ERR_OK:
  1453. WOLFSSL_MSG("ALPN protocol match");
  1454. break;
  1455. case SSL_TLSEXT_ERR_NOACK:
  1456. WOLFSSL_MSG("ALPN cb no match but not fatal");
  1457. sel = NULL;
  1458. sel_len = 0;
  1459. break;
  1460. case SSL_TLSEXT_ERR_ALERT_FATAL:
  1461. default:
  1462. WOLFSSL_MSG("ALPN cb no match and fatal");
  1463. SendAlert(ssl, alert_fatal, no_application_protocol);
  1464. WOLFSSL_ERROR_VERBOSE(UNKNOWN_ALPN_PROTOCOL_NAME_E);
  1465. return UNKNOWN_ALPN_PROTOCOL_NAME_E;
  1466. }
  1467. }
  1468. else
  1469. #endif
  1470. {
  1471. r = ALPN_find_match(ssl, &extension, &sel, &sel_len,
  1472. ssl->alpn_peer_requested,
  1473. ssl->alpn_peer_requested_length);
  1474. if (r != 0)
  1475. return r;
  1476. }
  1477. if (sel != NULL) {
  1478. /* set the matching negotiated protocol */
  1479. r = TLSX_SetALPN(&ssl->extensions, sel, sel_len, ssl->heap);
  1480. if (r != WOLFSSL_SUCCESS) {
  1481. WOLFSSL_MSG("TLSX_SetALPN failed");
  1482. return BUFFER_ERROR;
  1483. }
  1484. /* reply to ALPN extension sent from peer */
  1485. #ifndef NO_WOLFSSL_SERVER
  1486. TLSX_SetResponse(ssl, TLSX_APPLICATION_LAYER_PROTOCOL);
  1487. #endif
  1488. }
  1489. return 0;
  1490. }
  1491. /** Parses a buffer of ALPN extensions and set the first one matching
  1492. * client and server requirements */
  1493. static int TLSX_ALPN_ParseAndSet(WOLFSSL *ssl, const byte *input, word16 length,
  1494. byte isRequest)
  1495. {
  1496. word16 size = 0, offset = 0, wlen;
  1497. int r = BUFFER_ERROR;
  1498. const byte *s;
  1499. if (OPAQUE16_LEN > length)
  1500. return BUFFER_ERROR;
  1501. ato16(input, &size);
  1502. offset += OPAQUE16_LEN;
  1503. /* validating alpn list length */
  1504. if (size == 0 || length != OPAQUE16_LEN + size)
  1505. return BUFFER_ERROR;
  1506. /* validating length of entries before accepting */
  1507. for (s = input + offset; (s - input) < size; s += wlen) {
  1508. wlen = *s++;
  1509. if (wlen == 0 || (s + wlen - input) > length)
  1510. return BUFFER_ERROR;
  1511. }
  1512. if (isRequest) {
  1513. /* keep the list sent by peer, if this is from a request. We
  1514. * use it later in ALPN_Select() for evaluation. */
  1515. if (ssl->alpn_peer_requested != NULL) {
  1516. XFREE(ssl->alpn_peer_requested, ssl->heap, DYNAMIC_TYPE_ALPN);
  1517. ssl->alpn_peer_requested_length = 0;
  1518. }
  1519. ssl->alpn_peer_requested = (byte *)XMALLOC(size, ssl->heap,
  1520. DYNAMIC_TYPE_ALPN);
  1521. if (ssl->alpn_peer_requested == NULL) {
  1522. return MEMORY_ERROR;
  1523. }
  1524. ssl->alpn_peer_requested_length = size;
  1525. XMEMCPY(ssl->alpn_peer_requested, (char*)input + offset, size);
  1526. }
  1527. else {
  1528. /* a response, we should find the value in our config */
  1529. const byte *sel = NULL;
  1530. byte sel_len = 0;
  1531. TLSX *extension = NULL;
  1532. r = ALPN_find_match(ssl, &extension, &sel, &sel_len, input + offset, size);
  1533. if (r != 0)
  1534. return r;
  1535. if (sel != NULL) {
  1536. /* set the matching negotiated protocol */
  1537. r = TLSX_SetALPN(&ssl->extensions, sel, sel_len, ssl->heap);
  1538. if (r != WOLFSSL_SUCCESS) {
  1539. WOLFSSL_MSG("TLSX_SetALPN failed");
  1540. return BUFFER_ERROR;
  1541. }
  1542. }
  1543. /* If we had nothing configured, the response is unexpected */
  1544. else if (extension == NULL) {
  1545. r = TLSX_HandleUnsupportedExtension(ssl);
  1546. if (r != 0)
  1547. return r;
  1548. }
  1549. }
  1550. return 0;
  1551. }
  1552. /** Add a protocol name to the list of accepted usable ones */
  1553. int TLSX_UseALPN(TLSX** extensions, const void* data, word16 size, byte options,
  1554. void* heap)
  1555. {
  1556. ALPN *alpn;
  1557. TLSX *extension;
  1558. int ret;
  1559. if (extensions == NULL || data == NULL)
  1560. return BAD_FUNC_ARG;
  1561. alpn = TLSX_ALPN_New((char *)data, size, heap);
  1562. if (alpn == NULL) {
  1563. WOLFSSL_MSG("Memory failure");
  1564. return MEMORY_E;
  1565. }
  1566. /* Set Options of ALPN */
  1567. alpn->options = options;
  1568. extension = TLSX_Find(*extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1569. if (extension == NULL) {
  1570. ret = TLSX_Push(extensions, TLSX_APPLICATION_LAYER_PROTOCOL,
  1571. (void*)alpn, heap);
  1572. if (ret != 0) {
  1573. TLSX_ALPN_Free(alpn, heap);
  1574. return ret;
  1575. }
  1576. }
  1577. else {
  1578. /* push new ALPN object to extension data. */
  1579. alpn->next = (ALPN*)extension->data;
  1580. extension->data = (void*)alpn;
  1581. }
  1582. return WOLFSSL_SUCCESS;
  1583. }
  1584. /** Get the protocol name set by the server */
  1585. int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz)
  1586. {
  1587. TLSX *extension;
  1588. ALPN *alpn;
  1589. if (extensions == NULL || data == NULL || dataSz == NULL)
  1590. return BAD_FUNC_ARG;
  1591. *data = NULL;
  1592. *dataSz = 0;
  1593. extension = TLSX_Find(extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1594. if (extension == NULL) {
  1595. WOLFSSL_MSG("TLS extension not found");
  1596. WOLFSSL_ERROR_VERBOSE(WOLFSSL_ALPN_NOT_FOUND);
  1597. return WOLFSSL_ALPN_NOT_FOUND;
  1598. }
  1599. alpn = (ALPN *)extension->data;
  1600. if (alpn == NULL) {
  1601. WOLFSSL_MSG("ALPN extension not found");
  1602. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1603. return WOLFSSL_FATAL_ERROR;
  1604. }
  1605. if (alpn->negotiated != 1) {
  1606. /* consider as an error */
  1607. if (alpn->options & WOLFSSL_ALPN_FAILED_ON_MISMATCH) {
  1608. WOLFSSL_MSG("No protocol match with peer -> Failed");
  1609. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1610. return WOLFSSL_FATAL_ERROR;
  1611. }
  1612. /* continue without negotiated protocol */
  1613. WOLFSSL_MSG("No protocol match with peer -> Continue");
  1614. WOLFSSL_ERROR_VERBOSE(WOLFSSL_ALPN_NOT_FOUND);
  1615. return WOLFSSL_ALPN_NOT_FOUND;
  1616. }
  1617. if (alpn->next != NULL) {
  1618. WOLFSSL_MSG("Only one protocol name must be accepted");
  1619. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1620. return WOLFSSL_FATAL_ERROR;
  1621. }
  1622. *data = alpn->protocol_name;
  1623. *dataSz = (word16)XSTRLEN((char*)*data);
  1624. return WOLFSSL_SUCCESS;
  1625. }
  1626. #define ALPN_FREE_ALL TLSX_ALPN_FreeAll
  1627. #define ALPN_GET_SIZE TLSX_ALPN_GetSize
  1628. #define ALPN_WRITE TLSX_ALPN_Write
  1629. #define ALPN_PARSE TLSX_ALPN_ParseAndSet
  1630. #else /* HAVE_ALPN */
  1631. #define ALPN_FREE_ALL(list, heap) WC_DO_NOTHING
  1632. #define ALPN_GET_SIZE(list) 0
  1633. #define ALPN_WRITE(a, b) 0
  1634. #define ALPN_PARSE(a, b, c, d) 0
  1635. #endif /* HAVE_ALPN */
  1636. /******************************************************************************/
  1637. /* Server Name Indication */
  1638. /******************************************************************************/
  1639. #ifdef HAVE_SNI
  1640. /** Creates a new SNI object. */
  1641. static SNI* TLSX_SNI_New(byte type, const void* data, word16 size, void* heap)
  1642. {
  1643. SNI* sni = (SNI*)XMALLOC(sizeof(SNI), heap, DYNAMIC_TYPE_TLSX);
  1644. (void)heap;
  1645. if (sni) {
  1646. sni->type = type;
  1647. sni->next = NULL;
  1648. #ifndef NO_WOLFSSL_SERVER
  1649. sni->options = 0;
  1650. sni->status = WOLFSSL_SNI_NO_MATCH;
  1651. #endif
  1652. switch (sni->type) {
  1653. case WOLFSSL_SNI_HOST_NAME:
  1654. sni->data.host_name = (char*)XMALLOC(size + 1, heap,
  1655. DYNAMIC_TYPE_TLSX);
  1656. if (sni->data.host_name) {
  1657. XSTRNCPY(sni->data.host_name, (const char*)data, size);
  1658. sni->data.host_name[size] = '\0';
  1659. } else {
  1660. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1661. sni = NULL;
  1662. }
  1663. break;
  1664. default: /* invalid type */
  1665. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1666. sni = NULL;
  1667. }
  1668. }
  1669. return sni;
  1670. }
  1671. /** Releases a SNI object. */
  1672. static void TLSX_SNI_Free(SNI* sni, void* heap)
  1673. {
  1674. if (sni) {
  1675. switch (sni->type) {
  1676. case WOLFSSL_SNI_HOST_NAME:
  1677. XFREE(sni->data.host_name, heap, DYNAMIC_TYPE_TLSX);
  1678. break;
  1679. }
  1680. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1681. }
  1682. (void)heap;
  1683. }
  1684. /** Releases all SNI objects in the provided list. */
  1685. static void TLSX_SNI_FreeAll(SNI* list, void* heap)
  1686. {
  1687. SNI* sni;
  1688. while ((sni = list)) {
  1689. list = sni->next;
  1690. TLSX_SNI_Free(sni, heap);
  1691. }
  1692. }
  1693. /** Tells the buffered size of the SNI objects in a list. */
  1694. static word16 TLSX_SNI_GetSize(SNI* list)
  1695. {
  1696. SNI* sni;
  1697. word16 length = OPAQUE16_LEN; /* list length */
  1698. while ((sni = list)) {
  1699. list = sni->next;
  1700. length += ENUM_LEN + OPAQUE16_LEN; /* sni type + sni length */
  1701. switch (sni->type) {
  1702. case WOLFSSL_SNI_HOST_NAME:
  1703. length += (word16)XSTRLEN((char*)sni->data.host_name);
  1704. break;
  1705. }
  1706. }
  1707. return length;
  1708. }
  1709. /** Writes the SNI objects of a list in a buffer. */
  1710. static word16 TLSX_SNI_Write(SNI* list, byte* output)
  1711. {
  1712. SNI* sni;
  1713. word16 length = 0;
  1714. word16 offset = OPAQUE16_LEN; /* list length offset */
  1715. while ((sni = list)) {
  1716. list = sni->next;
  1717. output[offset++] = sni->type; /* sni type */
  1718. switch (sni->type) {
  1719. case WOLFSSL_SNI_HOST_NAME:
  1720. length = (word16)XSTRLEN((char*)sni->data.host_name);
  1721. c16toa(length, output + offset); /* sni length */
  1722. offset += OPAQUE16_LEN;
  1723. XMEMCPY(output + offset, sni->data.host_name, length);
  1724. offset += length;
  1725. break;
  1726. }
  1727. }
  1728. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  1729. return offset;
  1730. }
  1731. /** Finds a SNI object in the provided list. */
  1732. static SNI* TLSX_SNI_Find(SNI *list, byte type)
  1733. {
  1734. SNI* sni = list;
  1735. while (sni && sni->type != type)
  1736. sni = sni->next;
  1737. return sni;
  1738. }
  1739. #if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
  1740. /** Sets the status of a SNI object. */
  1741. static void TLSX_SNI_SetStatus(TLSX* extensions, byte type, byte status)
  1742. {
  1743. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1744. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1745. if (sni)
  1746. sni->status = status;
  1747. }
  1748. #endif
  1749. /** Gets the status of a SNI object. */
  1750. byte TLSX_SNI_Status(TLSX* extensions, byte type)
  1751. {
  1752. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1753. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1754. if (sni)
  1755. return sni->status;
  1756. return 0;
  1757. }
  1758. /** Parses a buffer of SNI extensions. */
  1759. static int TLSX_SNI_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  1760. byte isRequest)
  1761. {
  1762. #ifndef NO_WOLFSSL_SERVER
  1763. word16 size = 0;
  1764. word16 offset = 0;
  1765. int cacheOnly = 0;
  1766. SNI *sni = NULL;
  1767. byte type;
  1768. byte matched;
  1769. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1770. WOLFSSL_ECH* ech = NULL;
  1771. WOLFSSL_EchConfig* workingConfig;
  1772. TLSX* echX;
  1773. #endif
  1774. #endif /* !NO_WOLFSSL_SERVER */
  1775. TLSX *extension = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  1776. if (!extension)
  1777. extension = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  1778. if (!isRequest) {
  1779. #ifndef NO_WOLFSSL_CLIENT
  1780. if (!extension || !extension->data)
  1781. return TLSX_HandleUnsupportedExtension(ssl);
  1782. if (length > 0)
  1783. return BUFFER_ERROR; /* SNI response MUST be empty. */
  1784. /* This call enables wolfSSL_SNI_GetRequest() to be called in the
  1785. * client side to fetch the used SNI. It will only work if the SNI
  1786. * was set at the SSL object level. Right now we only support one
  1787. * name type, WOLFSSL_SNI_HOST_NAME, but in the future, the
  1788. * inclusion of other name types will turn this method inaccurate,
  1789. * as the extension response doesn't contains information of which
  1790. * name was accepted.
  1791. */
  1792. TLSX_SNI_SetStatus(ssl->extensions, WOLFSSL_SNI_HOST_NAME,
  1793. WOLFSSL_SNI_REAL_MATCH);
  1794. return 0;
  1795. #endif
  1796. }
  1797. #ifndef NO_WOLFSSL_SERVER
  1798. if (!extension || !extension->data) {
  1799. /* This will keep SNI even though TLSX_UseSNI has not been called.
  1800. * Enable it so that the received sni is available to functions
  1801. * that use a custom callback when SNI is received.
  1802. */
  1803. #ifdef WOLFSSL_ALWAYS_KEEP_SNI
  1804. cacheOnly = 1;
  1805. #endif
  1806. if (ssl->ctx->sniRecvCb) {
  1807. cacheOnly = 1;
  1808. }
  1809. if (cacheOnly) {
  1810. WOLFSSL_MSG("Forcing SSL object to store SNI parameter");
  1811. }
  1812. else {
  1813. /* Skipping, SNI not enabled at server side. */
  1814. return 0;
  1815. }
  1816. }
  1817. if (OPAQUE16_LEN > length)
  1818. return BUFFER_ERROR;
  1819. ato16(input, &size);
  1820. offset += OPAQUE16_LEN;
  1821. /* validating sni list length */
  1822. if (length != OPAQUE16_LEN + size || size == 0)
  1823. return BUFFER_ERROR;
  1824. /* SNI was badly specified and only one type is now recognized and allowed.
  1825. * Only one SNI value per type (RFC6066), so, no loop. */
  1826. type = input[offset++];
  1827. if (type != WOLFSSL_SNI_HOST_NAME)
  1828. return BUFFER_ERROR;
  1829. if (offset + OPAQUE16_LEN > length)
  1830. return BUFFER_ERROR;
  1831. ato16(input + offset, &size);
  1832. offset += OPAQUE16_LEN;
  1833. if (offset + size != length || size == 0)
  1834. return BUFFER_ERROR;
  1835. if (!cacheOnly && !(sni = TLSX_SNI_Find((SNI*)extension->data, type)))
  1836. return 0; /* not using this type of SNI. */
  1837. #ifdef WOLFSSL_TLS13
  1838. /* Don't process the second ClientHello SNI extension if there
  1839. * was problems with the first.
  1840. */
  1841. if (!cacheOnly && sni->status != 0)
  1842. return 0;
  1843. #endif
  1844. matched = cacheOnly || (XSTRLEN(sni->data.host_name) == size &&
  1845. XSTRNCMP(sni->data.host_name, (const char*)input + offset, size) == 0);
  1846. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1847. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  1848. if (echX != NULL)
  1849. ech = (WOLFSSL_ECH*)(echX->data);
  1850. if (!matched && ech != NULL) {
  1851. workingConfig = ech->echConfig;
  1852. while (workingConfig != NULL) {
  1853. matched = XSTRLEN(workingConfig->publicName) == size &&
  1854. XSTRNCMP(workingConfig->publicName,
  1855. (const char*)input + offset, size) == 0;
  1856. if (matched)
  1857. break;
  1858. workingConfig = workingConfig->next;
  1859. }
  1860. }
  1861. #endif
  1862. if (matched || sni->options & WOLFSSL_SNI_ANSWER_ON_MISMATCH) {
  1863. int matchStat;
  1864. int r = TLSX_UseSNI(&ssl->extensions, type, input + offset, size,
  1865. ssl->heap);
  1866. if (r != WOLFSSL_SUCCESS)
  1867. return r; /* throws error. */
  1868. if (cacheOnly) {
  1869. WOLFSSL_MSG("Forcing storage of SNI, Fake match");
  1870. matchStat = WOLFSSL_SNI_FORCE_KEEP;
  1871. }
  1872. else if (matched) {
  1873. WOLFSSL_MSG("SNI did match!");
  1874. matchStat = WOLFSSL_SNI_REAL_MATCH;
  1875. }
  1876. else {
  1877. WOLFSSL_MSG("fake SNI match from ANSWER_ON_MISMATCH");
  1878. matchStat = WOLFSSL_SNI_FAKE_MATCH;
  1879. }
  1880. TLSX_SNI_SetStatus(ssl->extensions, type, (byte)matchStat);
  1881. if (!cacheOnly)
  1882. TLSX_SetResponse(ssl, TLSX_SERVER_NAME);
  1883. }
  1884. else if (!(sni->options & WOLFSSL_SNI_CONTINUE_ON_MISMATCH)) {
  1885. SendAlert(ssl, alert_fatal, unrecognized_name);
  1886. WOLFSSL_ERROR_VERBOSE(UNKNOWN_SNI_HOST_NAME_E);
  1887. return UNKNOWN_SNI_HOST_NAME_E;
  1888. }
  1889. #else
  1890. (void)input;
  1891. #endif /* !NO_WOLFSSL_SERVER */
  1892. #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER)
  1893. (void)length;
  1894. #endif
  1895. return 0;
  1896. }
  1897. static int TLSX_SNI_VerifyParse(WOLFSSL* ssl, byte isRequest)
  1898. {
  1899. (void)ssl;
  1900. if (isRequest) {
  1901. #ifndef NO_WOLFSSL_SERVER
  1902. TLSX* ctx_ext = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  1903. TLSX* ssl_ext = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  1904. SNI* ctx_sni = ctx_ext ? (SNI*)ctx_ext->data : NULL;
  1905. SNI* ssl_sni = ssl_ext ? (SNI*)ssl_ext->data : NULL;
  1906. SNI* sni = NULL;
  1907. for (; ctx_sni; ctx_sni = ctx_sni->next) {
  1908. if (ctx_sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) {
  1909. sni = TLSX_SNI_Find(ssl_sni, ctx_sni->type);
  1910. if (sni) {
  1911. if (sni->status != WOLFSSL_SNI_NO_MATCH)
  1912. continue;
  1913. /* if ssl level overrides ctx level, it is ok. */
  1914. if ((sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) == 0)
  1915. continue;
  1916. }
  1917. SendAlert(ssl, alert_fatal, handshake_failure);
  1918. WOLFSSL_ERROR_VERBOSE(SNI_ABSENT_ERROR);
  1919. return SNI_ABSENT_ERROR;
  1920. }
  1921. }
  1922. for (; ssl_sni; ssl_sni = ssl_sni->next) {
  1923. if (ssl_sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) {
  1924. if (ssl_sni->status != WOLFSSL_SNI_NO_MATCH)
  1925. continue;
  1926. SendAlert(ssl, alert_fatal, handshake_failure);
  1927. WOLFSSL_ERROR_VERBOSE(SNI_ABSENT_ERROR);
  1928. return SNI_ABSENT_ERROR;
  1929. }
  1930. }
  1931. #endif /* NO_WOLFSSL_SERVER */
  1932. }
  1933. return 0;
  1934. }
  1935. int TLSX_UseSNI(TLSX** extensions, byte type, const void* data, word16 size,
  1936. void* heap)
  1937. {
  1938. TLSX* extension;
  1939. SNI* sni = NULL;
  1940. if (extensions == NULL || data == NULL)
  1941. return BAD_FUNC_ARG;
  1942. if ((sni = TLSX_SNI_New(type, data, size, heap)) == NULL)
  1943. return MEMORY_E;
  1944. extension = TLSX_Find(*extensions, TLSX_SERVER_NAME);
  1945. if (!extension) {
  1946. int ret = TLSX_Push(extensions, TLSX_SERVER_NAME, (void*)sni, heap);
  1947. if (ret != 0) {
  1948. TLSX_SNI_Free(sni, heap);
  1949. return ret;
  1950. }
  1951. }
  1952. else {
  1953. /* push new SNI object to extension data. */
  1954. sni->next = (SNI*)extension->data;
  1955. extension->data = (void*)sni;
  1956. /* remove duplicate SNI, there should be only one of each type. */
  1957. do {
  1958. if (sni->next && sni->next->type == type) {
  1959. SNI* next = sni->next;
  1960. sni->next = next->next;
  1961. TLSX_SNI_Free(next, heap);
  1962. /* there is no way to occur more than
  1963. * two SNIs of the same type.
  1964. */
  1965. break;
  1966. }
  1967. } while ((sni = sni->next));
  1968. }
  1969. return WOLFSSL_SUCCESS;
  1970. }
  1971. #ifndef NO_WOLFSSL_SERVER
  1972. /** Tells the SNI requested by the client. */
  1973. word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type, void** data)
  1974. {
  1975. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1976. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1977. if (sni && sni->status != WOLFSSL_SNI_NO_MATCH) {
  1978. switch (sni->type) {
  1979. case WOLFSSL_SNI_HOST_NAME:
  1980. if (data) {
  1981. *data = sni->data.host_name;
  1982. return (word16)XSTRLEN((char*)*data);
  1983. }
  1984. }
  1985. }
  1986. return 0;
  1987. }
  1988. /** Sets the options for a SNI object. */
  1989. void TLSX_SNI_SetOptions(TLSX* extensions, byte type, byte options)
  1990. {
  1991. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1992. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1993. if (sni)
  1994. sni->options = options;
  1995. }
  1996. /** Retrieves a SNI request from a client hello buffer. */
  1997. int TLSX_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz,
  1998. byte type, byte* sni, word32* inOutSz)
  1999. {
  2000. word32 offset = 0;
  2001. word32 len32 = 0;
  2002. word16 len16 = 0;
  2003. if (helloSz < RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + CLIENT_HELLO_FIRST)
  2004. return INCOMPLETE_DATA;
  2005. /* TLS record header */
  2006. if ((enum ContentType) clientHello[offset++] != handshake) {
  2007. /* checking for SSLv2.0 client hello according to: */
  2008. /* http://tools.ietf.org/html/rfc4346#appendix-E.1 */
  2009. if ((enum HandShakeType) clientHello[++offset] == client_hello) {
  2010. offset += ENUM_LEN + VERSION_SZ; /* skip version */
  2011. ato16(clientHello + offset, &len16);
  2012. offset += OPAQUE16_LEN;
  2013. if (len16 % 3) /* cipher_spec_length must be multiple of 3 */
  2014. return BUFFER_ERROR;
  2015. ato16(clientHello + offset, &len16);
  2016. /* Returning SNI_UNSUPPORTED do not increment offset here */
  2017. if (len16 != 0) /* session_id_length must be 0 */
  2018. return BUFFER_ERROR;
  2019. WOLFSSL_ERROR_VERBOSE(SNI_UNSUPPORTED);
  2020. return SNI_UNSUPPORTED;
  2021. }
  2022. return BUFFER_ERROR;
  2023. }
  2024. if (clientHello[offset++] != SSLv3_MAJOR)
  2025. return BUFFER_ERROR;
  2026. if (clientHello[offset++] < TLSv1_MINOR) {
  2027. WOLFSSL_ERROR_VERBOSE(SNI_UNSUPPORTED);
  2028. return SNI_UNSUPPORTED;
  2029. }
  2030. ato16(clientHello + offset, &len16);
  2031. offset += OPAQUE16_LEN;
  2032. if (offset + len16 > helloSz)
  2033. return INCOMPLETE_DATA;
  2034. /* Handshake header */
  2035. if ((enum HandShakeType) clientHello[offset] != client_hello)
  2036. return BUFFER_ERROR;
  2037. c24to32(clientHello + offset + 1, &len32);
  2038. offset += HANDSHAKE_HEADER_SZ;
  2039. if (offset + len32 > helloSz)
  2040. return BUFFER_ERROR;
  2041. /* client hello */
  2042. offset += VERSION_SZ + RAN_LEN; /* version, random */
  2043. if (helloSz < offset + clientHello[offset])
  2044. return BUFFER_ERROR;
  2045. offset += ENUM_LEN + clientHello[offset]; /* skip session id */
  2046. /* cypher suites */
  2047. if (helloSz < offset + OPAQUE16_LEN)
  2048. return BUFFER_ERROR;
  2049. ato16(clientHello + offset, &len16);
  2050. offset += OPAQUE16_LEN;
  2051. if (helloSz < offset + len16)
  2052. return BUFFER_ERROR;
  2053. offset += len16; /* skip cypher suites */
  2054. /* compression methods */
  2055. if (helloSz < offset + 1)
  2056. return BUFFER_ERROR;
  2057. if (helloSz < offset + clientHello[offset])
  2058. return BUFFER_ERROR;
  2059. offset += ENUM_LEN + clientHello[offset]; /* skip compression methods */
  2060. /* extensions */
  2061. if (helloSz < offset + OPAQUE16_LEN)
  2062. return 0; /* no extensions in client hello. */
  2063. ato16(clientHello + offset, &len16);
  2064. offset += OPAQUE16_LEN;
  2065. if (helloSz < offset + len16)
  2066. return BUFFER_ERROR;
  2067. while (len16 >= OPAQUE16_LEN + OPAQUE16_LEN) {
  2068. word16 extType;
  2069. word16 extLen;
  2070. ato16(clientHello + offset, &extType);
  2071. offset += OPAQUE16_LEN;
  2072. ato16(clientHello + offset, &extLen);
  2073. offset += OPAQUE16_LEN;
  2074. if (helloSz < offset + extLen)
  2075. return BUFFER_ERROR;
  2076. if (extType != TLSX_SERVER_NAME) {
  2077. offset += extLen; /* skip extension */
  2078. } else {
  2079. word16 listLen;
  2080. ato16(clientHello + offset, &listLen);
  2081. offset += OPAQUE16_LEN;
  2082. if (helloSz < offset + listLen)
  2083. return BUFFER_ERROR;
  2084. while (listLen > ENUM_LEN + OPAQUE16_LEN) {
  2085. byte sniType = clientHello[offset++];
  2086. word16 sniLen;
  2087. ato16(clientHello + offset, &sniLen);
  2088. offset += OPAQUE16_LEN;
  2089. if (helloSz < offset + sniLen)
  2090. return BUFFER_ERROR;
  2091. if (sniType != type) {
  2092. offset += sniLen;
  2093. listLen -= min(ENUM_LEN + OPAQUE16_LEN + sniLen, listLen);
  2094. continue;
  2095. }
  2096. *inOutSz = min(sniLen, *inOutSz);
  2097. XMEMCPY(sni, clientHello + offset, *inOutSz);
  2098. return WOLFSSL_SUCCESS;
  2099. }
  2100. }
  2101. len16 -= min(2 * OPAQUE16_LEN + extLen, len16);
  2102. }
  2103. return len16 ? BUFFER_ERROR : 0;
  2104. }
  2105. #endif
  2106. #define SNI_FREE_ALL TLSX_SNI_FreeAll
  2107. #define SNI_GET_SIZE TLSX_SNI_GetSize
  2108. #define SNI_WRITE TLSX_SNI_Write
  2109. #define SNI_PARSE TLSX_SNI_Parse
  2110. #define SNI_VERIFY_PARSE TLSX_SNI_VerifyParse
  2111. #else
  2112. #define SNI_FREE_ALL(list, heap) WC_DO_NOTHING
  2113. #define SNI_GET_SIZE(list) 0
  2114. #define SNI_WRITE(a, b) 0
  2115. #define SNI_PARSE(a, b, c, d) 0
  2116. #define SNI_VERIFY_PARSE(a, b) 0
  2117. #endif /* HAVE_SNI */
  2118. /******************************************************************************/
  2119. /* Trusted CA Key Indication */
  2120. /******************************************************************************/
  2121. #ifdef HAVE_TRUSTED_CA
  2122. /** Creates a new TCA object. */
  2123. static TCA* TLSX_TCA_New(byte type, const byte* id, word16 idSz, void* heap)
  2124. {
  2125. TCA* tca = (TCA*)XMALLOC(sizeof(TCA), heap, DYNAMIC_TYPE_TLSX);
  2126. if (tca) {
  2127. XMEMSET(tca, 0, sizeof(TCA));
  2128. tca->type = type;
  2129. switch (type) {
  2130. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2131. break;
  2132. #ifndef NO_SHA
  2133. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2134. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2135. if (idSz == WC_SHA_DIGEST_SIZE &&
  2136. (tca->id =
  2137. (byte*)XMALLOC(idSz, heap, DYNAMIC_TYPE_TLSX))) {
  2138. XMEMCPY(tca->id, id, idSz);
  2139. tca->idSz = idSz;
  2140. }
  2141. else {
  2142. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2143. tca = NULL;
  2144. }
  2145. break;
  2146. #endif
  2147. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2148. if (idSz > 0 &&
  2149. (tca->id =
  2150. (byte*)XMALLOC(idSz, heap, DYNAMIC_TYPE_TLSX))) {
  2151. XMEMCPY(tca->id, id, idSz);
  2152. tca->idSz = idSz;
  2153. }
  2154. else {
  2155. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2156. tca = NULL;
  2157. }
  2158. break;
  2159. default: /* invalid type */
  2160. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2161. tca = NULL;
  2162. }
  2163. }
  2164. (void)heap;
  2165. return tca;
  2166. }
  2167. /** Releases a TCA object. */
  2168. static void TLSX_TCA_Free(TCA* tca, void* heap)
  2169. {
  2170. (void)heap;
  2171. if (tca) {
  2172. if (tca->id)
  2173. XFREE(tca->id, heap, DYNAMIC_TYPE_TLSX);
  2174. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2175. }
  2176. }
  2177. /** Releases all TCA objects in the provided list. */
  2178. static void TLSX_TCA_FreeAll(TCA* list, void* heap)
  2179. {
  2180. TCA* tca;
  2181. while ((tca = list)) {
  2182. list = tca->next;
  2183. TLSX_TCA_Free(tca, heap);
  2184. }
  2185. }
  2186. /** Tells the buffered size of the TCA objects in a list. */
  2187. static word16 TLSX_TCA_GetSize(TCA* list)
  2188. {
  2189. TCA* tca;
  2190. word16 length = OPAQUE16_LEN; /* list length */
  2191. while ((tca = list)) {
  2192. list = tca->next;
  2193. length += ENUM_LEN; /* tca type */
  2194. switch (tca->type) {
  2195. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2196. break;
  2197. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2198. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2199. length += tca->idSz;
  2200. break;
  2201. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2202. length += OPAQUE16_LEN + tca->idSz;
  2203. break;
  2204. }
  2205. }
  2206. return length;
  2207. }
  2208. /** Writes the TCA objects of a list in a buffer. */
  2209. static word16 TLSX_TCA_Write(TCA* list, byte* output)
  2210. {
  2211. TCA* tca;
  2212. word16 offset = OPAQUE16_LEN; /* list length offset */
  2213. while ((tca = list)) {
  2214. list = tca->next;
  2215. output[offset++] = tca->type; /* tca type */
  2216. switch (tca->type) {
  2217. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2218. break;
  2219. #ifndef NO_SHA
  2220. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2221. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2222. if (tca->id != NULL) {
  2223. XMEMCPY(output + offset, tca->id, tca->idSz);
  2224. offset += tca->idSz;
  2225. }
  2226. else {
  2227. /* ID missing. Set to an empty string. */
  2228. c16toa(0, output + offset);
  2229. offset += OPAQUE16_LEN;
  2230. }
  2231. break;
  2232. #endif
  2233. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2234. if (tca->id != NULL) {
  2235. c16toa(tca->idSz, output + offset); /* tca length */
  2236. offset += OPAQUE16_LEN;
  2237. XMEMCPY(output + offset, tca->id, tca->idSz);
  2238. offset += tca->idSz;
  2239. }
  2240. else {
  2241. /* ID missing. Set to an empty string. */
  2242. c16toa(0, output + offset);
  2243. offset += OPAQUE16_LEN;
  2244. }
  2245. break;
  2246. default:
  2247. /* ID unknown. Set to an empty string. */
  2248. c16toa(0, output + offset);
  2249. offset += OPAQUE16_LEN;
  2250. }
  2251. }
  2252. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  2253. return offset;
  2254. }
  2255. #ifndef NO_WOLFSSL_SERVER
  2256. static TCA* TLSX_TCA_Find(TCA *list, byte type, const byte* id, word16 idSz)
  2257. {
  2258. TCA* tca = list;
  2259. while (tca && tca->type != type && type != WOLFSSL_TRUSTED_CA_PRE_AGREED &&
  2260. idSz != tca->idSz && !XMEMCMP(id, tca->id, idSz))
  2261. tca = tca->next;
  2262. return tca;
  2263. }
  2264. #endif /* NO_WOLFSSL_SERVER */
  2265. /** Parses a buffer of TCA extensions. */
  2266. static int TLSX_TCA_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2267. byte isRequest)
  2268. {
  2269. #ifndef NO_WOLFSSL_SERVER
  2270. word16 size = 0;
  2271. word16 offset = 0;
  2272. #endif
  2273. TLSX *extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS);
  2274. if (!extension)
  2275. extension = TLSX_Find(ssl->ctx->extensions, TLSX_TRUSTED_CA_KEYS);
  2276. if (!isRequest) {
  2277. #ifndef NO_WOLFSSL_CLIENT
  2278. if (!extension || !extension->data)
  2279. return TLSX_HandleUnsupportedExtension(ssl);
  2280. if (length > 0)
  2281. return BUFFER_ERROR; /* TCA response MUST be empty. */
  2282. /* Set the flag that we're good for keys */
  2283. TLSX_SetResponse(ssl, TLSX_TRUSTED_CA_KEYS);
  2284. return 0;
  2285. #endif
  2286. }
  2287. #ifndef NO_WOLFSSL_SERVER
  2288. if (!extension || !extension->data) {
  2289. /* Skipping, TCA not enabled at server side. */
  2290. return 0;
  2291. }
  2292. if (OPAQUE16_LEN > length)
  2293. return BUFFER_ERROR;
  2294. ato16(input, &size);
  2295. offset += OPAQUE16_LEN;
  2296. /* validating tca list length */
  2297. if (length != OPAQUE16_LEN + size)
  2298. return BUFFER_ERROR;
  2299. for (size = 0; offset < length; offset += size) {
  2300. TCA *tca = NULL;
  2301. byte type;
  2302. const byte* id = NULL;
  2303. word16 idSz = 0;
  2304. if (offset + ENUM_LEN > length)
  2305. return BUFFER_ERROR;
  2306. type = input[offset++];
  2307. switch (type) {
  2308. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2309. break;
  2310. #ifndef NO_SHA
  2311. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2312. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2313. if (offset + WC_SHA_DIGEST_SIZE > length)
  2314. return BUFFER_ERROR;
  2315. idSz = WC_SHA_DIGEST_SIZE;
  2316. id = input + offset;
  2317. offset += idSz;
  2318. break;
  2319. #endif
  2320. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2321. if (offset + OPAQUE16_LEN > length)
  2322. return BUFFER_ERROR;
  2323. ato16(input + offset, &idSz);
  2324. offset += OPAQUE16_LEN;
  2325. if ((offset > length) || (idSz > length - offset))
  2326. return BUFFER_ERROR;
  2327. id = input + offset;
  2328. offset += idSz;
  2329. break;
  2330. default:
  2331. WOLFSSL_ERROR_VERBOSE(TCA_INVALID_ID_TYPE);
  2332. return TCA_INVALID_ID_TYPE;
  2333. }
  2334. /* Find the type/ID in the TCA list. */
  2335. tca = TLSX_TCA_Find((TCA*)extension->data, type, id, idSz);
  2336. if (tca != NULL) {
  2337. /* Found it. Set the response flag and break out of the loop. */
  2338. TLSX_SetResponse(ssl, TLSX_TRUSTED_CA_KEYS);
  2339. break;
  2340. }
  2341. }
  2342. #else
  2343. (void)input;
  2344. #endif
  2345. return 0;
  2346. }
  2347. /* Checks to see if the server sent a response for the TCA. */
  2348. static int TLSX_TCA_VerifyParse(WOLFSSL* ssl, byte isRequest)
  2349. {
  2350. (void)ssl;
  2351. if (!isRequest) {
  2352. #ifndef NO_WOLFSSL_CLIENT
  2353. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS);
  2354. if (extension && !extension->resp) {
  2355. SendAlert(ssl, alert_fatal, handshake_failure);
  2356. WOLFSSL_ERROR_VERBOSE(TCA_ABSENT_ERROR);
  2357. return TCA_ABSENT_ERROR;
  2358. }
  2359. #endif /* NO_WOLFSSL_CLIENT */
  2360. }
  2361. return 0;
  2362. }
  2363. int TLSX_UseTrustedCA(TLSX** extensions, byte type,
  2364. const byte* id, word16 idSz, void* heap)
  2365. {
  2366. TLSX* extension;
  2367. TCA* tca = NULL;
  2368. if (extensions == NULL)
  2369. return BAD_FUNC_ARG;
  2370. if ((tca = TLSX_TCA_New(type, id, idSz, heap)) == NULL)
  2371. return MEMORY_E;
  2372. extension = TLSX_Find(*extensions, TLSX_TRUSTED_CA_KEYS);
  2373. if (!extension) {
  2374. int ret = TLSX_Push(extensions, TLSX_TRUSTED_CA_KEYS, (void*)tca, heap);
  2375. if (ret != 0) {
  2376. TLSX_TCA_Free(tca, heap);
  2377. return ret;
  2378. }
  2379. }
  2380. else {
  2381. /* push new TCA object to extension data. */
  2382. tca->next = (TCA*)extension->data;
  2383. extension->data = (void*)tca;
  2384. }
  2385. return WOLFSSL_SUCCESS;
  2386. }
  2387. #define TCA_FREE_ALL TLSX_TCA_FreeAll
  2388. #define TCA_GET_SIZE TLSX_TCA_GetSize
  2389. #define TCA_WRITE TLSX_TCA_Write
  2390. #define TCA_PARSE TLSX_TCA_Parse
  2391. #define TCA_VERIFY_PARSE TLSX_TCA_VerifyParse
  2392. #else /* HAVE_TRUSTED_CA */
  2393. #define TCA_FREE_ALL(list, heap) WC_DO_NOTHING
  2394. #define TCA_GET_SIZE(list) 0
  2395. #define TCA_WRITE(a, b) 0
  2396. #define TCA_PARSE(a, b, c, d) 0
  2397. #define TCA_VERIFY_PARSE(a, b) 0
  2398. #endif /* HAVE_TRUSTED_CA */
  2399. /******************************************************************************/
  2400. /* Max Fragment Length Negotiation */
  2401. /******************************************************************************/
  2402. #ifdef HAVE_MAX_FRAGMENT
  2403. static word16 TLSX_MFL_Write(byte* data, byte* output)
  2404. {
  2405. output[0] = data[0];
  2406. return ENUM_LEN;
  2407. }
  2408. static int TLSX_MFL_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2409. byte isRequest)
  2410. {
  2411. if (length != ENUM_LEN)
  2412. return BUFFER_ERROR;
  2413. #ifdef WOLFSSL_OLD_UNSUPPORTED_EXTENSION
  2414. (void) isRequest;
  2415. #else
  2416. if (!isRequest)
  2417. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_MAX_FRAGMENT_LENGTH))
  2418. return TLSX_HandleUnsupportedExtension(ssl);
  2419. #endif
  2420. switch (*input) {
  2421. case WOLFSSL_MFL_2_8 : ssl->max_fragment = 256; break;
  2422. case WOLFSSL_MFL_2_9 : ssl->max_fragment = 512; break;
  2423. case WOLFSSL_MFL_2_10: ssl->max_fragment = 1024; break;
  2424. case WOLFSSL_MFL_2_11: ssl->max_fragment = 2048; break;
  2425. case WOLFSSL_MFL_2_12: ssl->max_fragment = 4096; break;
  2426. case WOLFSSL_MFL_2_13: ssl->max_fragment = 8192; break;
  2427. default:
  2428. SendAlert(ssl, alert_fatal, illegal_parameter);
  2429. WOLFSSL_ERROR_VERBOSE(UNKNOWN_MAX_FRAG_LEN_E);
  2430. return UNKNOWN_MAX_FRAG_LEN_E;
  2431. }
  2432. #ifndef NO_WOLFSSL_SERVER
  2433. if (isRequest) {
  2434. int ret = TLSX_UseMaxFragment(&ssl->extensions, *input, ssl->heap);
  2435. if (ret != WOLFSSL_SUCCESS)
  2436. return ret; /* throw error */
  2437. TLSX_SetResponse(ssl, TLSX_MAX_FRAGMENT_LENGTH);
  2438. }
  2439. #endif
  2440. return 0;
  2441. }
  2442. int TLSX_UseMaxFragment(TLSX** extensions, byte mfl, void* heap)
  2443. {
  2444. byte* data = NULL;
  2445. int ret = 0;
  2446. if (extensions == NULL || mfl < WOLFSSL_MFL_MIN || mfl > WOLFSSL_MFL_MAX)
  2447. return BAD_FUNC_ARG;
  2448. data = (byte*)XMALLOC(ENUM_LEN, heap, DYNAMIC_TYPE_TLSX);
  2449. if (data == NULL)
  2450. return MEMORY_E;
  2451. data[0] = mfl;
  2452. ret = TLSX_Push(extensions, TLSX_MAX_FRAGMENT_LENGTH, data, heap);
  2453. if (ret != 0) {
  2454. XFREE(data, heap, DYNAMIC_TYPE_TLSX);
  2455. return ret;
  2456. }
  2457. return WOLFSSL_SUCCESS;
  2458. }
  2459. #define MFL_FREE_ALL(data, heap) XFREE(data, (heap), DYNAMIC_TYPE_TLSX)
  2460. #define MFL_GET_SIZE(data) ENUM_LEN
  2461. #define MFL_WRITE TLSX_MFL_Write
  2462. #define MFL_PARSE TLSX_MFL_Parse
  2463. #else
  2464. #define MFL_FREE_ALL(a, b) WC_DO_NOTHING
  2465. #define MFL_GET_SIZE(a) 0
  2466. #define MFL_WRITE(a, b) 0
  2467. #define MFL_PARSE(a, b, c, d) 0
  2468. #endif /* HAVE_MAX_FRAGMENT */
  2469. /******************************************************************************/
  2470. /* Truncated HMAC */
  2471. /******************************************************************************/
  2472. #ifdef HAVE_TRUNCATED_HMAC
  2473. static int TLSX_THM_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2474. byte isRequest)
  2475. {
  2476. if (length != 0 || input == NULL)
  2477. return BUFFER_ERROR;
  2478. if (!isRequest) {
  2479. #ifndef WOLFSSL_OLD_UNSUPPORTED_EXTENSION
  2480. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_TRUNCATED_HMAC))
  2481. return TLSX_HandleUnsupportedExtension(ssl);
  2482. #endif
  2483. }
  2484. else {
  2485. #ifndef NO_WOLFSSL_SERVER
  2486. int ret = TLSX_UseTruncatedHMAC(&ssl->extensions, ssl->heap);
  2487. if (ret != WOLFSSL_SUCCESS)
  2488. return ret; /* throw error */
  2489. TLSX_SetResponse(ssl, TLSX_TRUNCATED_HMAC);
  2490. #endif
  2491. }
  2492. ssl->truncated_hmac = 1;
  2493. return 0;
  2494. }
  2495. int TLSX_UseTruncatedHMAC(TLSX** extensions, void* heap)
  2496. {
  2497. int ret = 0;
  2498. if (extensions == NULL)
  2499. return BAD_FUNC_ARG;
  2500. ret = TLSX_Push(extensions, TLSX_TRUNCATED_HMAC, NULL, heap);
  2501. if (ret != 0)
  2502. return ret;
  2503. return WOLFSSL_SUCCESS;
  2504. }
  2505. #define THM_PARSE TLSX_THM_Parse
  2506. #else
  2507. #define THM_PARSE(a, b, c, d) 0
  2508. #endif /* HAVE_TRUNCATED_HMAC */
  2509. /******************************************************************************/
  2510. /* Certificate Status Request */
  2511. /******************************************************************************/
  2512. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  2513. static void TLSX_CSR_Free(CertificateStatusRequest* csr, void* heap)
  2514. {
  2515. switch (csr->status_type) {
  2516. case WOLFSSL_CSR_OCSP:
  2517. FreeOcspRequest(&csr->request.ocsp);
  2518. break;
  2519. }
  2520. #ifdef WOLFSSL_TLS13
  2521. if (csr->response.buffer != NULL) {
  2522. XFREE(csr->response.buffer, csr->ssl->heap,
  2523. DYNAMIC_TYPE_TMP_BUFFER);
  2524. }
  2525. #endif
  2526. XFREE(csr, heap, DYNAMIC_TYPE_TLSX);
  2527. (void)heap;
  2528. }
  2529. static word16 TLSX_CSR_GetSize(CertificateStatusRequest* csr, byte isRequest)
  2530. {
  2531. word16 size = 0;
  2532. /* shut up compiler warnings */
  2533. (void) csr; (void) isRequest;
  2534. #ifndef NO_WOLFSSL_CLIENT
  2535. if (isRequest) {
  2536. switch (csr->status_type) {
  2537. case WOLFSSL_CSR_OCSP:
  2538. size += ENUM_LEN + 2 * OPAQUE16_LEN;
  2539. if (csr->request.ocsp.nonceSz)
  2540. size += OCSP_NONCE_EXT_SZ;
  2541. break;
  2542. }
  2543. }
  2544. #endif
  2545. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  2546. if (!isRequest && csr->ssl->options.tls1_3)
  2547. return OPAQUE8_LEN + OPAQUE24_LEN + csr->response.length;
  2548. #endif
  2549. return size;
  2550. }
  2551. static word16 TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output,
  2552. byte isRequest)
  2553. {
  2554. /* shut up compiler warnings */
  2555. (void) csr; (void) output; (void) isRequest;
  2556. #ifndef NO_WOLFSSL_CLIENT
  2557. if (isRequest) {
  2558. word16 offset = 0;
  2559. word16 length = 0;
  2560. /* type */
  2561. output[offset++] = csr->status_type;
  2562. switch (csr->status_type) {
  2563. case WOLFSSL_CSR_OCSP:
  2564. /* responder id list */
  2565. c16toa(0, output + offset);
  2566. offset += OPAQUE16_LEN;
  2567. /* request extensions */
  2568. if (csr->request.ocsp.nonceSz)
  2569. length = (word16)EncodeOcspRequestExtensions(
  2570. &csr->request.ocsp,
  2571. output + offset + OPAQUE16_LEN,
  2572. OCSP_NONCE_EXT_SZ);
  2573. c16toa(length, output + offset);
  2574. offset += OPAQUE16_LEN + length;
  2575. break;
  2576. }
  2577. return offset;
  2578. }
  2579. #endif
  2580. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  2581. if (!isRequest && csr->ssl->options.tls1_3) {
  2582. word16 offset = 0;
  2583. output[offset++] = csr->status_type;
  2584. c32to24(csr->response.length, output + offset);
  2585. offset += OPAQUE24_LEN;
  2586. XMEMCPY(output + offset, csr->response.buffer, csr->response.length);
  2587. offset += csr->response.length;
  2588. return offset;
  2589. }
  2590. #endif
  2591. return 0;
  2592. }
  2593. static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2594. byte isRequest)
  2595. {
  2596. int ret;
  2597. #if !defined(NO_WOLFSSL_SERVER)
  2598. byte status_type;
  2599. word16 size = 0;
  2600. #if defined(WOLFSSL_TLS13)
  2601. DecodedCert* cert;
  2602. #endif
  2603. #endif
  2604. #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) \
  2605. && defined(WOLFSSL_TLS13)
  2606. OcspRequest* request;
  2607. TLSX* extension;
  2608. CertificateStatusRequest* csr;
  2609. #endif
  2610. #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_TLS13) \
  2611. || !defined(NO_WOLFSSL_SERVER)
  2612. word32 offset = 0;
  2613. #endif
  2614. #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_TLS13)
  2615. word32 resp_length = 0;
  2616. #endif
  2617. /* shut up compiler warnings */
  2618. (void) ssl; (void) input;
  2619. if (!isRequest) {
  2620. #ifndef NO_WOLFSSL_CLIENT
  2621. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2622. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2623. if (!csr) {
  2624. /* look at context level */
  2625. extension = TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST);
  2626. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2627. if (!csr) /* unexpected extension */
  2628. return TLSX_HandleUnsupportedExtension(ssl);
  2629. /* enable extension at ssl level */
  2630. ret = TLSX_UseCertificateStatusRequest(&ssl->extensions,
  2631. csr->status_type, csr->options, ssl,
  2632. ssl->heap, ssl->devId);
  2633. if (ret != WOLFSSL_SUCCESS)
  2634. return ret == 0 ? -1 : ret;
  2635. switch (csr->status_type) {
  2636. case WOLFSSL_CSR_OCSP:
  2637. /* propagate nonce */
  2638. if (csr->request.ocsp.nonceSz) {
  2639. request =
  2640. (OcspRequest*)TLSX_CSR_GetRequest(ssl->extensions);
  2641. if (request) {
  2642. XMEMCPY(request->nonce, csr->request.ocsp.nonce,
  2643. csr->request.ocsp.nonceSz);
  2644. request->nonceSz = csr->request.ocsp.nonceSz;
  2645. }
  2646. }
  2647. break;
  2648. }
  2649. }
  2650. ssl->status_request = 1;
  2651. #ifdef WOLFSSL_TLS13
  2652. if (ssl->options.tls1_3) {
  2653. /* Get the new extension potentially created above. */
  2654. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2655. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2656. if (csr == NULL)
  2657. return MEMORY_ERROR;
  2658. ret = 0;
  2659. if (OPAQUE8_LEN + OPAQUE24_LEN > length)
  2660. ret = BUFFER_ERROR;
  2661. if (ret == 0 && input[offset++] != WOLFSSL_CSR_OCSP) {
  2662. ret = BAD_CERTIFICATE_STATUS_ERROR;
  2663. WOLFSSL_ERROR_VERBOSE(ret);
  2664. }
  2665. if (ret == 0) {
  2666. c24to32(input + offset, &resp_length);
  2667. offset += OPAQUE24_LEN;
  2668. if (offset + resp_length != length)
  2669. ret = BUFFER_ERROR;
  2670. }
  2671. if (ret == 0) {
  2672. csr->response.buffer = (byte*)XMALLOC(resp_length, ssl->heap,
  2673. DYNAMIC_TYPE_TMP_BUFFER);
  2674. if (csr->response.buffer == NULL)
  2675. ret = MEMORY_ERROR;
  2676. }
  2677. if (ret == 0) {
  2678. XMEMCPY(csr->response.buffer, input + offset, resp_length);
  2679. csr->response.length = resp_length;
  2680. }
  2681. return ret;
  2682. }
  2683. else
  2684. #endif
  2685. {
  2686. /* extension_data MUST be empty. */
  2687. return length ? BUFFER_ERROR : 0;
  2688. }
  2689. #endif
  2690. }
  2691. else {
  2692. #ifndef NO_WOLFSSL_SERVER
  2693. if (length == 0)
  2694. return 0;
  2695. status_type = input[offset++];
  2696. switch (status_type) {
  2697. case WOLFSSL_CSR_OCSP: {
  2698. /* skip responder_id_list */
  2699. if ((int)(length - offset) < OPAQUE16_LEN)
  2700. return BUFFER_ERROR;
  2701. ato16(input + offset, &size);
  2702. offset += OPAQUE16_LEN + size;
  2703. /* skip request_extensions */
  2704. if ((int)(length - offset) < OPAQUE16_LEN)
  2705. return BUFFER_ERROR;
  2706. ato16(input + offset, &size);
  2707. offset += OPAQUE16_LEN + size;
  2708. if (offset > length)
  2709. return BUFFER_ERROR;
  2710. /* is able to send OCSP response? */
  2711. if (SSL_CM(ssl) == NULL || !SSL_CM(ssl)->ocspStaplingEnabled)
  2712. return 0;
  2713. }
  2714. break;
  2715. /* unknown status type */
  2716. default:
  2717. return 0;
  2718. }
  2719. /* if using status_request and already sending it, skip this one */
  2720. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2721. if (ssl->status_request_v2)
  2722. return 0;
  2723. #endif
  2724. /* accept the first good status_type and return */
  2725. ret = TLSX_UseCertificateStatusRequest(&ssl->extensions, status_type,
  2726. 0, ssl, ssl->heap, ssl->devId);
  2727. if (ret != WOLFSSL_SUCCESS)
  2728. return ret == 0 ? -1 : ret; /* throw error */
  2729. #if defined(WOLFSSL_TLS13)
  2730. if (ssl->options.tls1_3) {
  2731. if (ssl->buffers.certificate == NULL) {
  2732. WOLFSSL_MSG("Certificate buffer not set!");
  2733. return BUFFER_ERROR;
  2734. }
  2735. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
  2736. DYNAMIC_TYPE_DCERT);
  2737. if (cert == NULL) {
  2738. return MEMORY_E;
  2739. }
  2740. InitDecodedCert(cert, ssl->buffers.certificate->buffer,
  2741. ssl->buffers.certificate->length, ssl->heap);
  2742. ret = ParseCert(cert, CERT_TYPE, 1, SSL_CM(ssl));
  2743. if (ret != 0) {
  2744. FreeDecodedCert(cert);
  2745. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2746. /* Let's not error out the connection if we can't verify our
  2747. * cert */
  2748. if (ret == ASN_SELF_SIGNED_E || ret == ASN_NO_SIGNER_E)
  2749. ret = 0;
  2750. return ret;
  2751. }
  2752. ret = TLSX_CSR_InitRequest(ssl->extensions, cert, ssl->heap);
  2753. if (ret != 0 ) {
  2754. FreeDecodedCert(cert);
  2755. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2756. return ret;
  2757. }
  2758. FreeDecodedCert(cert);
  2759. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2760. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2761. csr = extension ?
  2762. (CertificateStatusRequest*)extension->data : NULL;
  2763. if (csr == NULL)
  2764. return MEMORY_ERROR;
  2765. request = &csr->request.ocsp;
  2766. ret = CreateOcspResponse(ssl, &request, &csr->response);
  2767. if (ret != 0)
  2768. return ret;
  2769. if (csr->response.buffer)
  2770. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST);
  2771. }
  2772. else
  2773. #endif
  2774. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST);
  2775. ssl->status_request = status_type;
  2776. #endif
  2777. }
  2778. return 0;
  2779. }
  2780. int TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert, void* heap)
  2781. {
  2782. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST);
  2783. CertificateStatusRequest* csr = extension ?
  2784. (CertificateStatusRequest*)extension->data : NULL;
  2785. int ret = 0;
  2786. if (csr) {
  2787. switch (csr->status_type) {
  2788. case WOLFSSL_CSR_OCSP: {
  2789. byte nonce[MAX_OCSP_NONCE_SZ];
  2790. int nonceSz = csr->request.ocsp.nonceSz;
  2791. /* preserve nonce */
  2792. XMEMCPY(nonce, csr->request.ocsp.nonce, nonceSz);
  2793. if ((ret = InitOcspRequest(&csr->request.ocsp, cert, 0, heap))
  2794. != 0)
  2795. return ret;
  2796. /* restore nonce */
  2797. XMEMCPY(csr->request.ocsp.nonce, nonce, nonceSz);
  2798. csr->request.ocsp.nonceSz = nonceSz;
  2799. }
  2800. break;
  2801. }
  2802. }
  2803. return ret;
  2804. }
  2805. void* TLSX_CSR_GetRequest(TLSX* extensions)
  2806. {
  2807. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST);
  2808. CertificateStatusRequest* csr = extension ?
  2809. (CertificateStatusRequest*)extension->data : NULL;
  2810. if (csr) {
  2811. switch (csr->status_type) {
  2812. case WOLFSSL_CSR_OCSP:
  2813. return &csr->request.ocsp;
  2814. }
  2815. }
  2816. return NULL;
  2817. }
  2818. int TLSX_CSR_ForceRequest(WOLFSSL* ssl)
  2819. {
  2820. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2821. CertificateStatusRequest* csr = extension ?
  2822. (CertificateStatusRequest*)extension->data : NULL;
  2823. if (csr) {
  2824. switch (csr->status_type) {
  2825. case WOLFSSL_CSR_OCSP:
  2826. if (SSL_CM(ssl)->ocspEnabled) {
  2827. csr->request.ocsp.ssl = ssl;
  2828. return CheckOcspRequest(SSL_CM(ssl)->ocsp,
  2829. &csr->request.ocsp, NULL, NULL);
  2830. }
  2831. else {
  2832. WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL);
  2833. return OCSP_LOOKUP_FAIL;
  2834. }
  2835. }
  2836. }
  2837. return 0;
  2838. }
  2839. int TLSX_UseCertificateStatusRequest(TLSX** extensions, byte status_type,
  2840. byte options, WOLFSSL* ssl, void* heap,
  2841. int devId)
  2842. {
  2843. CertificateStatusRequest* csr = NULL;
  2844. int ret = 0;
  2845. if (!extensions || status_type != WOLFSSL_CSR_OCSP)
  2846. return BAD_FUNC_ARG;
  2847. csr = (CertificateStatusRequest*)
  2848. XMALLOC(sizeof(CertificateStatusRequest), heap, DYNAMIC_TYPE_TLSX);
  2849. if (!csr)
  2850. return MEMORY_E;
  2851. ForceZero(csr, sizeof(CertificateStatusRequest));
  2852. csr->status_type = status_type;
  2853. csr->options = options;
  2854. csr->ssl = ssl;
  2855. switch (csr->status_type) {
  2856. case WOLFSSL_CSR_OCSP:
  2857. if (options & WOLFSSL_CSR_OCSP_USE_NONCE) {
  2858. WC_RNG rng;
  2859. #ifndef HAVE_FIPS
  2860. ret = wc_InitRng_ex(&rng, heap, devId);
  2861. #else
  2862. ret = wc_InitRng(&rng);
  2863. (void)devId;
  2864. #endif
  2865. if (ret == 0) {
  2866. if (wc_RNG_GenerateBlock(&rng, csr->request.ocsp.nonce,
  2867. MAX_OCSP_NONCE_SZ) == 0)
  2868. csr->request.ocsp.nonceSz = MAX_OCSP_NONCE_SZ;
  2869. wc_FreeRng(&rng);
  2870. }
  2871. }
  2872. break;
  2873. }
  2874. if ((ret = TLSX_Push(extensions, TLSX_STATUS_REQUEST, csr, heap)) != 0) {
  2875. XFREE(csr, heap, DYNAMIC_TYPE_TLSX);
  2876. return ret;
  2877. }
  2878. return WOLFSSL_SUCCESS;
  2879. }
  2880. #define CSR_FREE_ALL TLSX_CSR_Free
  2881. #define CSR_GET_SIZE TLSX_CSR_GetSize
  2882. #define CSR_WRITE TLSX_CSR_Write
  2883. #define CSR_PARSE TLSX_CSR_Parse
  2884. #else
  2885. #define CSR_FREE_ALL(data, heap) WC_DO_NOTHING
  2886. #define CSR_GET_SIZE(a, b) 0
  2887. #define CSR_WRITE(a, b, c) 0
  2888. #define CSR_PARSE(a, b, c, d) 0
  2889. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
  2890. /******************************************************************************/
  2891. /* Certificate Status Request v2 */
  2892. /******************************************************************************/
  2893. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2894. static void TLSX_CSR2_FreeAll(CertificateStatusRequestItemV2* csr2, void* heap)
  2895. {
  2896. CertificateStatusRequestItemV2* next;
  2897. for (; csr2; csr2 = next) {
  2898. next = csr2->next;
  2899. switch (csr2->status_type) {
  2900. case WOLFSSL_CSR2_OCSP:
  2901. case WOLFSSL_CSR2_OCSP_MULTI:
  2902. while(csr2->requests--)
  2903. FreeOcspRequest(&csr2->request.ocsp[csr2->requests]);
  2904. break;
  2905. }
  2906. XFREE(csr2, heap, DYNAMIC_TYPE_TLSX);
  2907. }
  2908. (void)heap;
  2909. }
  2910. static word16 TLSX_CSR2_GetSize(CertificateStatusRequestItemV2* csr2,
  2911. byte isRequest)
  2912. {
  2913. word16 size = 0;
  2914. /* shut up compiler warnings */
  2915. (void) csr2; (void) isRequest;
  2916. #ifndef NO_WOLFSSL_CLIENT
  2917. if (isRequest) {
  2918. CertificateStatusRequestItemV2* next;
  2919. for (size = OPAQUE16_LEN; csr2; csr2 = next) {
  2920. next = csr2->next;
  2921. switch (csr2->status_type) {
  2922. case WOLFSSL_CSR2_OCSP:
  2923. case WOLFSSL_CSR2_OCSP_MULTI:
  2924. size += ENUM_LEN + 3 * OPAQUE16_LEN;
  2925. if (csr2->request.ocsp[0].nonceSz)
  2926. size += OCSP_NONCE_EXT_SZ;
  2927. break;
  2928. }
  2929. }
  2930. }
  2931. #endif
  2932. return size;
  2933. }
  2934. static word16 TLSX_CSR2_Write(CertificateStatusRequestItemV2* csr2,
  2935. byte* output, byte isRequest)
  2936. {
  2937. /* shut up compiler warnings */
  2938. (void) csr2; (void) output; (void) isRequest;
  2939. #ifndef NO_WOLFSSL_CLIENT
  2940. if (isRequest) {
  2941. word16 offset;
  2942. word16 length;
  2943. for (offset = OPAQUE16_LEN; csr2 != NULL; csr2 = csr2->next) {
  2944. /* status_type */
  2945. output[offset++] = csr2->status_type;
  2946. /* request */
  2947. switch (csr2->status_type) {
  2948. case WOLFSSL_CSR2_OCSP:
  2949. case WOLFSSL_CSR2_OCSP_MULTI:
  2950. /* request_length */
  2951. length = 2 * OPAQUE16_LEN;
  2952. if (csr2->request.ocsp[0].nonceSz)
  2953. length += OCSP_NONCE_EXT_SZ;
  2954. c16toa(length, output + offset);
  2955. offset += OPAQUE16_LEN;
  2956. /* responder id list */
  2957. c16toa(0, output + offset);
  2958. offset += OPAQUE16_LEN;
  2959. /* request extensions */
  2960. length = 0;
  2961. if (csr2->request.ocsp[0].nonceSz)
  2962. length = (word16)EncodeOcspRequestExtensions(
  2963. &csr2->request.ocsp[0],
  2964. output + offset + OPAQUE16_LEN,
  2965. OCSP_NONCE_EXT_SZ);
  2966. c16toa(length, output + offset);
  2967. offset += OPAQUE16_LEN + length;
  2968. break;
  2969. }
  2970. }
  2971. /* list size */
  2972. c16toa(offset - OPAQUE16_LEN, output);
  2973. return offset;
  2974. }
  2975. #endif
  2976. return 0;
  2977. }
  2978. static int TLSX_CSR2_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2979. byte isRequest)
  2980. {
  2981. int ret;
  2982. /* shut up compiler warnings */
  2983. (void) ssl; (void) input;
  2984. if (!isRequest) {
  2985. #ifndef NO_WOLFSSL_CLIENT
  2986. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST_V2);
  2987. CertificateStatusRequestItemV2* csr2 = extension ?
  2988. (CertificateStatusRequestItemV2*)extension->data : NULL;
  2989. if (!csr2) {
  2990. /* look at context level */
  2991. extension = TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST_V2);
  2992. csr2 = extension ?
  2993. (CertificateStatusRequestItemV2*)extension->data : NULL;
  2994. if (!csr2) /* unexpected extension */
  2995. return TLSX_HandleUnsupportedExtension(ssl);
  2996. /* enable extension at ssl level */
  2997. for (; csr2; csr2 = csr2->next) {
  2998. ret = TLSX_UseCertificateStatusRequestV2(&ssl->extensions,
  2999. csr2->status_type, csr2->options, ssl->heap,
  3000. ssl->devId);
  3001. if (ret != WOLFSSL_SUCCESS)
  3002. return ret;
  3003. switch (csr2->status_type) {
  3004. case WOLFSSL_CSR2_OCSP:
  3005. /* followed by */
  3006. case WOLFSSL_CSR2_OCSP_MULTI:
  3007. /* propagate nonce */
  3008. if (csr2->request.ocsp[0].nonceSz) {
  3009. OcspRequest* request =
  3010. (OcspRequest*)TLSX_CSR2_GetRequest(ssl->extensions,
  3011. csr2->status_type, 0);
  3012. if (request) {
  3013. XMEMCPY(request->nonce,
  3014. csr2->request.ocsp[0].nonce,
  3015. csr2->request.ocsp[0].nonceSz);
  3016. request->nonceSz =
  3017. csr2->request.ocsp[0].nonceSz;
  3018. }
  3019. }
  3020. break;
  3021. }
  3022. }
  3023. }
  3024. ssl->status_request_v2 = 1;
  3025. return length ? BUFFER_ERROR : 0; /* extension_data MUST be empty. */
  3026. #endif
  3027. }
  3028. else {
  3029. #ifndef NO_WOLFSSL_SERVER
  3030. byte status_type;
  3031. word16 request_length;
  3032. word16 offset = 0;
  3033. word16 size = 0;
  3034. /* list size */
  3035. if (offset + OPAQUE16_LEN >= length) {
  3036. return BUFFER_E;
  3037. }
  3038. ato16(input + offset, &request_length);
  3039. offset += OPAQUE16_LEN;
  3040. if (length - OPAQUE16_LEN != request_length)
  3041. return BUFFER_ERROR;
  3042. while (length > offset) {
  3043. if ((int)(length - offset) < ENUM_LEN + OPAQUE16_LEN)
  3044. return BUFFER_ERROR;
  3045. status_type = input[offset++];
  3046. ato16(input + offset, &request_length);
  3047. offset += OPAQUE16_LEN;
  3048. if (length - offset < request_length)
  3049. return BUFFER_ERROR;
  3050. switch (status_type) {
  3051. case WOLFSSL_CSR2_OCSP:
  3052. case WOLFSSL_CSR2_OCSP_MULTI:
  3053. /* skip responder_id_list */
  3054. if ((int)(length - offset) < OPAQUE16_LEN)
  3055. return BUFFER_ERROR;
  3056. ato16(input + offset, &size);
  3057. if (length - offset < size)
  3058. return BUFFER_ERROR;
  3059. offset += OPAQUE16_LEN + size;
  3060. /* skip request_extensions */
  3061. if ((int)(length - offset) < OPAQUE16_LEN)
  3062. return BUFFER_ERROR;
  3063. ato16(input + offset, &size);
  3064. if (length - offset < size)
  3065. return BUFFER_ERROR;
  3066. offset += OPAQUE16_LEN + size;
  3067. if (offset > length)
  3068. return BUFFER_ERROR;
  3069. /* is able to send OCSP response? */
  3070. if (SSL_CM(ssl) == NULL
  3071. || !SSL_CM(ssl)->ocspStaplingEnabled)
  3072. continue;
  3073. break;
  3074. default:
  3075. /* unknown status type, skipping! */
  3076. offset += request_length;
  3077. continue;
  3078. }
  3079. /* if using status_request and already sending it, remove it
  3080. * and prefer to use the v2 version */
  3081. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  3082. if (ssl->status_request) {
  3083. ssl->status_request = 0;
  3084. TLSX_Remove(&ssl->extensions, TLSX_STATUS_REQUEST, ssl->heap);
  3085. }
  3086. #endif
  3087. /* TLS 1.3 servers MUST NOT act upon presence or information in
  3088. * this extension (RFC 8448 Section 4.4.2.1).
  3089. */
  3090. if (!IsAtLeastTLSv1_3(ssl->version)) {
  3091. /* accept the first good status_type and return */
  3092. ret = TLSX_UseCertificateStatusRequestV2(&ssl->extensions,
  3093. status_type, 0, ssl->heap, ssl->devId);
  3094. if (ret != WOLFSSL_SUCCESS)
  3095. return ret; /* throw error */
  3096. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST_V2);
  3097. ssl->status_request_v2 = status_type;
  3098. }
  3099. return 0;
  3100. }
  3101. #endif
  3102. }
  3103. return 0;
  3104. }
  3105. int TLSX_CSR2_InitRequests(TLSX* extensions, DecodedCert* cert, byte isPeer,
  3106. void* heap)
  3107. {
  3108. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2);
  3109. CertificateStatusRequestItemV2* csr2 = extension ?
  3110. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3111. int ret = 0;
  3112. for (; csr2; csr2 = csr2->next) {
  3113. switch (csr2->status_type) {
  3114. case WOLFSSL_CSR2_OCSP:
  3115. if (!isPeer || csr2->requests != 0)
  3116. break;
  3117. FALL_THROUGH; /* followed by */
  3118. case WOLFSSL_CSR2_OCSP_MULTI: {
  3119. if (csr2->requests < 1 + MAX_CHAIN_DEPTH) {
  3120. byte nonce[MAX_OCSP_NONCE_SZ];
  3121. int nonceSz = csr2->request.ocsp[0].nonceSz;
  3122. /* preserve nonce, replicating nonce of ocsp[0] */
  3123. XMEMCPY(nonce, csr2->request.ocsp[0].nonce, nonceSz);
  3124. if ((ret = InitOcspRequest(
  3125. &csr2->request.ocsp[csr2->requests], cert,
  3126. 0, heap)) != 0)
  3127. return ret;
  3128. /* restore nonce */
  3129. XMEMCPY(csr2->request.ocsp[csr2->requests].nonce,
  3130. nonce, nonceSz);
  3131. csr2->request.ocsp[csr2->requests].nonceSz = nonceSz;
  3132. csr2->requests++;
  3133. }
  3134. }
  3135. break;
  3136. }
  3137. }
  3138. (void)cert;
  3139. return ret;
  3140. }
  3141. void* TLSX_CSR2_GetRequest(TLSX* extensions, byte status_type, byte idx)
  3142. {
  3143. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2);
  3144. CertificateStatusRequestItemV2* csr2 = extension ?
  3145. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3146. for (; csr2; csr2 = csr2->next) {
  3147. if (csr2->status_type == status_type) {
  3148. switch (csr2->status_type) {
  3149. case WOLFSSL_CSR2_OCSP:
  3150. /* followed by */
  3151. case WOLFSSL_CSR2_OCSP_MULTI:
  3152. /* requests are initialized in the reverse order */
  3153. return idx < csr2->requests
  3154. ? &csr2->request.ocsp[csr2->requests - idx - 1]
  3155. : NULL;
  3156. }
  3157. }
  3158. }
  3159. return NULL;
  3160. }
  3161. int TLSX_CSR2_ForceRequest(WOLFSSL* ssl)
  3162. {
  3163. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST_V2);
  3164. CertificateStatusRequestItemV2* csr2 = extension ?
  3165. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3166. /* forces only the first one */
  3167. if (csr2) {
  3168. switch (csr2->status_type) {
  3169. case WOLFSSL_CSR2_OCSP:
  3170. /* followed by */
  3171. case WOLFSSL_CSR2_OCSP_MULTI:
  3172. if (SSL_CM(ssl)->ocspEnabled) {
  3173. csr2->request.ocsp[0].ssl = ssl;
  3174. return CheckOcspRequest(SSL_CM(ssl)->ocsp,
  3175. &csr2->request.ocsp[0], NULL, NULL);
  3176. }
  3177. else {
  3178. WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL);
  3179. return OCSP_LOOKUP_FAIL;
  3180. }
  3181. }
  3182. }
  3183. return 0;
  3184. }
  3185. int TLSX_UseCertificateStatusRequestV2(TLSX** extensions, byte status_type,
  3186. byte options, void* heap, int devId)
  3187. {
  3188. TLSX* extension = NULL;
  3189. CertificateStatusRequestItemV2* csr2 = NULL;
  3190. int ret = 0;
  3191. if (!extensions)
  3192. return BAD_FUNC_ARG;
  3193. if (status_type != WOLFSSL_CSR2_OCSP
  3194. && status_type != WOLFSSL_CSR2_OCSP_MULTI)
  3195. return BAD_FUNC_ARG;
  3196. csr2 = (CertificateStatusRequestItemV2*)
  3197. XMALLOC(sizeof(CertificateStatusRequestItemV2), heap, DYNAMIC_TYPE_TLSX);
  3198. if (!csr2)
  3199. return MEMORY_E;
  3200. ForceZero(csr2, sizeof(CertificateStatusRequestItemV2));
  3201. csr2->status_type = status_type;
  3202. csr2->options = options;
  3203. csr2->next = NULL;
  3204. switch (csr2->status_type) {
  3205. case WOLFSSL_CSR2_OCSP:
  3206. case WOLFSSL_CSR2_OCSP_MULTI:
  3207. if (options & WOLFSSL_CSR2_OCSP_USE_NONCE) {
  3208. WC_RNG rng;
  3209. #ifndef HAVE_FIPS
  3210. ret = wc_InitRng_ex(&rng, heap, devId);
  3211. #else
  3212. ret = wc_InitRng(&rng);
  3213. (void)devId;
  3214. #endif
  3215. if (ret == 0) {
  3216. if (wc_RNG_GenerateBlock(&rng, csr2->request.ocsp[0].nonce,
  3217. MAX_OCSP_NONCE_SZ) == 0)
  3218. csr2->request.ocsp[0].nonceSz = MAX_OCSP_NONCE_SZ;
  3219. wc_FreeRng(&rng);
  3220. }
  3221. }
  3222. break;
  3223. }
  3224. /* append new item */
  3225. if ((extension = TLSX_Find(*extensions, TLSX_STATUS_REQUEST_V2))) {
  3226. CertificateStatusRequestItemV2* last =
  3227. (CertificateStatusRequestItemV2*)extension->data;
  3228. for (; last->next; last = last->next);
  3229. last->next = csr2;
  3230. }
  3231. else if ((ret = TLSX_Push(extensions, TLSX_STATUS_REQUEST_V2, csr2,heap))) {
  3232. XFREE(csr2, heap, DYNAMIC_TYPE_TLSX);
  3233. return ret;
  3234. }
  3235. return WOLFSSL_SUCCESS;
  3236. }
  3237. #define CSR2_FREE_ALL TLSX_CSR2_FreeAll
  3238. #define CSR2_GET_SIZE TLSX_CSR2_GetSize
  3239. #define CSR2_WRITE TLSX_CSR2_Write
  3240. #define CSR2_PARSE TLSX_CSR2_Parse
  3241. #else
  3242. #define CSR2_FREE_ALL(data, heap) WC_DO_NOTHING
  3243. #define CSR2_GET_SIZE(a, b) 0
  3244. #define CSR2_WRITE(a, b, c) 0
  3245. #define CSR2_PARSE(a, b, c, d) 0
  3246. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  3247. /******************************************************************************/
  3248. /* Supported Elliptic Curves */
  3249. /******************************************************************************/
  3250. #ifdef HAVE_SUPPORTED_CURVES
  3251. #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) \
  3252. && !defined(HAVE_FFDHE) && !defined(HAVE_PQC)
  3253. #error Elliptic Curves Extension requires Elliptic Curve Cryptography or liboqs groups. \
  3254. Use --enable-ecc and/or --enable-liboqs in the configure script or \
  3255. define HAVE_ECC. Alternatively use FFDHE for DH cipher suites.
  3256. #endif
  3257. static int TLSX_SupportedCurve_New(SupportedCurve** curve, word16 name,
  3258. void* heap)
  3259. {
  3260. if (curve == NULL)
  3261. return BAD_FUNC_ARG;
  3262. (void)heap;
  3263. *curve = (SupportedCurve*)XMALLOC(sizeof(SupportedCurve), heap,
  3264. DYNAMIC_TYPE_TLSX);
  3265. if (*curve == NULL)
  3266. return MEMORY_E;
  3267. (*curve)->name = name;
  3268. (*curve)->next = NULL;
  3269. return 0;
  3270. }
  3271. static int TLSX_PointFormat_New(PointFormat** point, byte format, void* heap)
  3272. {
  3273. if (point == NULL)
  3274. return BAD_FUNC_ARG;
  3275. (void)heap;
  3276. *point = (PointFormat*)XMALLOC(sizeof(PointFormat), heap,
  3277. DYNAMIC_TYPE_TLSX);
  3278. if (*point == NULL)
  3279. return MEMORY_E;
  3280. (*point)->format = format;
  3281. (*point)->next = NULL;
  3282. return 0;
  3283. }
  3284. static void TLSX_SupportedCurve_FreeAll(SupportedCurve* list, void* heap)
  3285. {
  3286. SupportedCurve* curve;
  3287. while ((curve = list)) {
  3288. list = curve->next;
  3289. XFREE(curve, heap, DYNAMIC_TYPE_TLSX);
  3290. }
  3291. (void)heap;
  3292. }
  3293. static void TLSX_PointFormat_FreeAll(PointFormat* list, void* heap)
  3294. {
  3295. PointFormat* point;
  3296. while ((point = list)) {
  3297. list = point->next;
  3298. XFREE(point, heap, DYNAMIC_TYPE_TLSX);
  3299. }
  3300. (void)heap;
  3301. }
  3302. static int TLSX_SupportedCurve_Append(SupportedCurve* list, word16 name,
  3303. void* heap)
  3304. {
  3305. int ret = BAD_FUNC_ARG;
  3306. while (list) {
  3307. if (list->name == name) {
  3308. ret = 0; /* curve already in use */
  3309. break;
  3310. }
  3311. if (list->next == NULL) {
  3312. ret = TLSX_SupportedCurve_New(&list->next, name, heap);
  3313. break;
  3314. }
  3315. list = list->next;
  3316. }
  3317. return ret;
  3318. }
  3319. static int TLSX_PointFormat_Append(PointFormat* list, byte format, void* heap)
  3320. {
  3321. int ret = BAD_FUNC_ARG;
  3322. while (list) {
  3323. if (list->format == format) {
  3324. ret = 0; /* format already in use */
  3325. break;
  3326. }
  3327. if (list->next == NULL) {
  3328. ret = TLSX_PointFormat_New(&list->next, format, heap);
  3329. break;
  3330. }
  3331. list = list->next;
  3332. }
  3333. return ret;
  3334. }
  3335. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  3336. #if defined(HAVE_FFDHE) && (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3337. defined(HAVE_CURVE448))
  3338. static void TLSX_SupportedCurve_ValidateRequest(const WOLFSSL* ssl,
  3339. const byte* semaphore)
  3340. {
  3341. /* If all pre-defined parameter types for key exchange are supported then
  3342. * always send SupportedGroups extension.
  3343. */
  3344. (void)ssl;
  3345. (void)semaphore;
  3346. }
  3347. #else
  3348. static void TLSX_SupportedCurve_ValidateRequest(WOLFSSL* ssl, byte* semaphore)
  3349. {
  3350. word16 i;
  3351. const Suites* suites = WOLFSSL_SUITES(ssl);
  3352. for (i = 0; i < suites->suiteSz; i += 2) {
  3353. if (suites->suites[i] == TLS13_BYTE)
  3354. return;
  3355. #ifdef BUILD_TLS_SM4_GCM_SM3
  3356. if ((suites->suites[i] == CIPHER_BYTE) &&
  3357. (suites->suites[i+1] == TLS_SM4_GCM_SM3))
  3358. return;
  3359. #endif
  3360. #ifdef BUILD_TLS_SM4_CCM_SM3
  3361. if ((suites->suites[i] == CIPHER_BYTE) &&
  3362. (suites->suites[i+1] == TLS_SM4_CCM_SM3))
  3363. return;
  3364. #endif
  3365. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3366. if ((suites->suites[i] == SM_BYTE) &&
  3367. (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3368. return;
  3369. #endif
  3370. if ((suites->suites[i] == ECC_BYTE) ||
  3371. (suites->suites[i] == ECDHE_PSK_BYTE) ||
  3372. (suites->suites[i] == CHACHA_BYTE)) {
  3373. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3374. defined(HAVE_CURVE448)
  3375. return;
  3376. #endif
  3377. }
  3378. #ifdef HAVE_FFDHE
  3379. else {
  3380. return;
  3381. }
  3382. #endif
  3383. }
  3384. /* turns semaphore on to avoid sending this extension. */
  3385. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_GROUPS));
  3386. }
  3387. #endif
  3388. /* Only send PointFormats if TLSv13, ECC or CHACHA cipher suite present.
  3389. */
  3390. static void TLSX_PointFormat_ValidateRequest(WOLFSSL* ssl, byte* semaphore)
  3391. {
  3392. #ifdef HAVE_FFDHE
  3393. (void)ssl;
  3394. (void)semaphore;
  3395. #else
  3396. word16 i;
  3397. const Suites* suites = WOLFSSL_SUITES(ssl);
  3398. if (suites == NULL)
  3399. return;
  3400. for (i = 0; i < suites->suiteSz; i += 2) {
  3401. if (suites->suites[i] == TLS13_BYTE)
  3402. return;
  3403. #ifdef BUILD_TLS_SM4_GCM_SM3
  3404. if ((suites->suites[i] == CIPHER_BYTE) &&
  3405. (suites->suites[i+1] == TLS_SM4_GCM_SM3))
  3406. return;
  3407. #endif
  3408. #ifdef BUILD_TLS_SM4_CCM_SM3
  3409. if ((suites->suites[i] == CIPHER_BYTE) &&
  3410. (suites->suites[i+1] == TLS_SM4_CCM_SM3))
  3411. return;
  3412. #endif
  3413. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3414. if ((suites->suites[i] == SM_BYTE) &&
  3415. (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3416. return;
  3417. #endif
  3418. if ((suites->suites[i] == ECC_BYTE) ||
  3419. (suites->suites[i] == ECDHE_PSK_BYTE) ||
  3420. (suites->suites[i] == CHACHA_BYTE)) {
  3421. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3422. defined(HAVE_CURVE448)
  3423. return;
  3424. #endif
  3425. }
  3426. }
  3427. /* turns semaphore on to avoid sending this extension. */
  3428. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  3429. #endif
  3430. }
  3431. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  3432. #ifndef NO_WOLFSSL_SERVER
  3433. static void TLSX_PointFormat_ValidateResponse(WOLFSSL* ssl, byte* semaphore)
  3434. {
  3435. #if defined(HAVE_FFDHE) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3436. defined(HAVE_CURVE448)
  3437. (void)semaphore;
  3438. #endif
  3439. if (ssl->options.cipherSuite0 == TLS13_BYTE)
  3440. return;
  3441. #ifdef BUILD_TLS_SM4_GCM_SM3
  3442. if ((ssl->options.cipherSuite0 == CIPHER_BYTE) &&
  3443. (ssl->options.cipherSuite == TLS_SM4_GCM_SM3))
  3444. return;
  3445. #endif
  3446. #ifdef BUILD_TLS_SM4_CCM_SM3
  3447. if ((ssl->options.cipherSuite0 == CIPHER_BYTE) &&
  3448. (ssl->options.cipherSuite == TLS_SM4_CCM_SM3))
  3449. return;
  3450. #endif
  3451. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3452. if ((ssl->options.cipherSuite0 == SM_BYTE) &&
  3453. (ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3454. return;
  3455. #endif
  3456. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  3457. if (ssl->options.cipherSuite0 == ECC_BYTE ||
  3458. ssl->options.cipherSuite0 == ECDHE_PSK_BYTE ||
  3459. ssl->options.cipherSuite0 == CHACHA_BYTE) {
  3460. return;
  3461. }
  3462. #endif
  3463. /* turns semaphore on to avoid sending this extension. */
  3464. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  3465. }
  3466. #endif /* !NO_WOLFSSL_SERVER */
  3467. #if !defined(NO_WOLFSSL_CLIENT) || defined(WOLFSSL_TLS13)
  3468. static word16 TLSX_SupportedCurve_GetSize(SupportedCurve* list)
  3469. {
  3470. SupportedCurve* curve;
  3471. word16 length = OPAQUE16_LEN; /* list length */
  3472. while ((curve = list)) {
  3473. list = curve->next;
  3474. length += OPAQUE16_LEN; /* curve length */
  3475. }
  3476. return length;
  3477. }
  3478. #endif
  3479. static word16 TLSX_PointFormat_GetSize(PointFormat* list)
  3480. {
  3481. PointFormat* point;
  3482. word16 length = ENUM_LEN; /* list length */
  3483. while ((point = list)) {
  3484. list = point->next;
  3485. length += ENUM_LEN; /* format length */
  3486. }
  3487. return length;
  3488. }
  3489. #if !defined(NO_WOLFSSL_CLIENT) || defined(WOLFSSL_TLS13)
  3490. static word16 TLSX_SupportedCurve_Write(SupportedCurve* list, byte* output)
  3491. {
  3492. word16 offset = OPAQUE16_LEN;
  3493. while (list) {
  3494. c16toa(list->name, output + offset);
  3495. offset += OPAQUE16_LEN;
  3496. list = list->next;
  3497. }
  3498. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  3499. return offset;
  3500. }
  3501. #endif
  3502. static word16 TLSX_PointFormat_Write(PointFormat* list, byte* output)
  3503. {
  3504. word16 offset = ENUM_LEN;
  3505. while (list) {
  3506. output[offset++] = list->format;
  3507. list = list->next;
  3508. }
  3509. output[0] = (byte)(offset - ENUM_LEN);
  3510. return offset;
  3511. }
  3512. #if !defined(NO_WOLFSSL_SERVER) || (defined(WOLFSSL_TLS13) && \
  3513. !defined(WOLFSSL_NO_SERVER_GROUPS_EXT))
  3514. int TLSX_SupportedCurve_Parse(const WOLFSSL* ssl, const byte* input,
  3515. word16 length, byte isRequest, TLSX** extensions)
  3516. {
  3517. word16 offset;
  3518. word16 name;
  3519. int ret;
  3520. if(!isRequest && !IsAtLeastTLSv1_3(ssl->version)) {
  3521. #ifdef WOLFSSL_ALLOW_SERVER_SC_EXT
  3522. return 0;
  3523. #else
  3524. return BUFFER_ERROR; /* servers doesn't send this extension. */
  3525. #endif
  3526. }
  3527. if (OPAQUE16_LEN > length || length % OPAQUE16_LEN)
  3528. return BUFFER_ERROR;
  3529. ato16(input, &offset);
  3530. /* validating curve list length */
  3531. if (length != OPAQUE16_LEN + offset)
  3532. return BUFFER_ERROR;
  3533. offset = OPAQUE16_LEN;
  3534. if (offset == length)
  3535. return 0;
  3536. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3537. if (!isRequest) {
  3538. TLSX* extension;
  3539. SupportedCurve* curve;
  3540. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  3541. if (extension != NULL) {
  3542. /* Replace client list with server list of supported groups. */
  3543. curve = (SupportedCurve*)extension->data;
  3544. extension->data = NULL;
  3545. TLSX_SupportedCurve_FreeAll(curve, ssl->heap);
  3546. ato16(input + offset, &name);
  3547. offset += OPAQUE16_LEN;
  3548. ret = TLSX_SupportedCurve_New(&curve, name, ssl->heap);
  3549. if (ret != 0)
  3550. return ret; /* throw error */
  3551. extension->data = (void*)curve;
  3552. }
  3553. }
  3554. #endif
  3555. for (; offset < length; offset += OPAQUE16_LEN) {
  3556. ato16(input + offset, &name);
  3557. ret = TLSX_UseSupportedCurve(extensions, name, ssl->heap);
  3558. /* If it is BAD_FUNC_ARG then it is a group we do not support, but
  3559. * that is fine. */
  3560. if (ret != WOLFSSL_SUCCESS && ret != BAD_FUNC_ARG) {
  3561. return ret;
  3562. }
  3563. }
  3564. return 0;
  3565. }
  3566. #endif
  3567. #if !defined(NO_WOLFSSL_SERVER)
  3568. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3569. /* Checks the priority of the groups on the server and set the supported groups
  3570. * response if there is a group not advertised by the client that is preferred.
  3571. *
  3572. * ssl SSL/TLS object.
  3573. * returns 0 on success, otherwise an error.
  3574. */
  3575. int TLSX_SupportedCurve_CheckPriority(WOLFSSL* ssl)
  3576. {
  3577. int ret;
  3578. TLSX* extension;
  3579. TLSX* priority = NULL;
  3580. TLSX* ext = NULL;
  3581. word16 name;
  3582. SupportedCurve* curve;
  3583. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3584. /* May be doing PSK with no key exchange. */
  3585. if (extension == NULL)
  3586. return 0;
  3587. ret = TLSX_PopulateSupportedGroups(ssl, &priority);
  3588. if (ret != WOLFSSL_SUCCESS) {
  3589. TLSX_FreeAll(priority, ssl->heap);
  3590. return ret;
  3591. }
  3592. ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS);
  3593. if (ext == NULL) {
  3594. WOLFSSL_MSG("Could not find supported groups extension");
  3595. TLSX_FreeAll(priority, ssl->heap);
  3596. return 0;
  3597. }
  3598. curve = (SupportedCurve*)ext->data;
  3599. name = curve->name;
  3600. curve = (SupportedCurve*)extension->data;
  3601. while (curve != NULL) {
  3602. if (curve->name == name)
  3603. break;
  3604. curve = curve->next;
  3605. }
  3606. if (curve == NULL) {
  3607. /* Couldn't find the preferred group in client list. */
  3608. extension->resp = 1;
  3609. /* Send server list back and free client list. */
  3610. curve = (SupportedCurve*)extension->data;
  3611. extension->data = ext->data;
  3612. ext->data = curve;
  3613. }
  3614. TLSX_FreeAll(priority, ssl->heap);
  3615. return 0;
  3616. }
  3617. #endif /* WOLFSSL_TLS13 && !WOLFSSL_NO_SERVER_GROUPS_EXT */
  3618. #if defined(HAVE_FFDHE) && !defined(WOLFSSL_NO_TLS12)
  3619. #ifdef HAVE_PUBLIC_FFDHE
  3620. static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup,
  3621. SupportedCurve* serverGroup)
  3622. {
  3623. int ret = 0;
  3624. SupportedCurve* group;
  3625. const DhParams* params = NULL;
  3626. for (; serverGroup != NULL; serverGroup = serverGroup->next) {
  3627. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name))
  3628. continue;
  3629. for (group = clientGroup; group != NULL; group = group->next) {
  3630. if (serverGroup->name != group->name)
  3631. continue;
  3632. switch (serverGroup->name) {
  3633. #ifdef HAVE_FFDHE_2048
  3634. case WOLFSSL_FFDHE_2048:
  3635. params = wc_Dh_ffdhe2048_Get();
  3636. break;
  3637. #endif
  3638. #ifdef HAVE_FFDHE_3072
  3639. case WOLFSSL_FFDHE_3072:
  3640. params = wc_Dh_ffdhe3072_Get();
  3641. break;
  3642. #endif
  3643. #ifdef HAVE_FFDHE_4096
  3644. case WOLFSSL_FFDHE_4096:
  3645. params = wc_Dh_ffdhe4096_Get();
  3646. break;
  3647. #endif
  3648. #ifdef HAVE_FFDHE_6144
  3649. case WOLFSSL_FFDHE_6144:
  3650. params = wc_Dh_ffdhe6144_Get();
  3651. break;
  3652. #endif
  3653. #ifdef HAVE_FFDHE_8192
  3654. case WOLFSSL_FFDHE_8192:
  3655. params = wc_Dh_ffdhe8192_Get();
  3656. break;
  3657. #endif
  3658. default:
  3659. break;
  3660. }
  3661. if (params == NULL) {
  3662. ret = BAD_FUNC_ARG;
  3663. break;
  3664. }
  3665. if (params->p_len >= ssl->options.minDhKeySz &&
  3666. params->p_len <= ssl->options.maxDhKeySz) {
  3667. break;
  3668. }
  3669. }
  3670. if (ret != 0)
  3671. break;
  3672. if ((group != NULL) && (serverGroup->name == group->name))
  3673. break;
  3674. }
  3675. if ((ret == 0) && (serverGroup != NULL) && (params != NULL)) {
  3676. ssl->buffers.serverDH_P.buffer = (unsigned char *)params->p;
  3677. ssl->buffers.serverDH_P.length = params->p_len;
  3678. ssl->buffers.serverDH_G.buffer = (unsigned char *)params->g;
  3679. ssl->buffers.serverDH_G.length = params->g_len;
  3680. ssl->namedGroup = serverGroup->name;
  3681. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  3682. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  3683. ssl->options.dhDoKeyTest = 0;
  3684. #endif
  3685. ssl->options.haveDH = 1;
  3686. }
  3687. return ret;
  3688. }
  3689. #else
  3690. static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup,
  3691. SupportedCurve* serverGroup)
  3692. {
  3693. int ret = 0;
  3694. SupportedCurve* group;
  3695. word32 p_len;
  3696. for (; serverGroup != NULL; serverGroup = serverGroup->next) {
  3697. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name))
  3698. continue;
  3699. for (group = clientGroup; group != NULL; group = group->next) {
  3700. if (serverGroup->name != group->name)
  3701. continue;
  3702. wc_DhGetNamedKeyParamSize(serverGroup->name, &p_len, NULL, NULL);
  3703. if (p_len == 0) {
  3704. ret = BAD_FUNC_ARG;
  3705. break;
  3706. }
  3707. if (p_len >= ssl->options.minDhKeySz &&
  3708. p_len <= ssl->options.maxDhKeySz) {
  3709. break;
  3710. }
  3711. }
  3712. if (ret != 0)
  3713. break;
  3714. if ((group != NULL) && (serverGroup->name == group->name))
  3715. break;
  3716. }
  3717. if ((ret == 0) && (serverGroup != NULL)) {
  3718. word32 pSz, gSz;
  3719. ssl->buffers.serverDH_P.buffer = NULL;
  3720. ssl->buffers.serverDH_G.buffer = NULL;
  3721. ret = wc_DhGetNamedKeyParamSize(serverGroup->name, &pSz, &gSz, NULL);
  3722. if (ret == 0) {
  3723. ssl->buffers.serverDH_P.buffer =
  3724. (byte*)XMALLOC(pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  3725. if (ssl->buffers.serverDH_P.buffer == NULL)
  3726. ret = MEMORY_E;
  3727. else
  3728. ssl->buffers.serverDH_P.length = pSz;
  3729. }
  3730. if (ret == 0) {
  3731. ssl->buffers.serverDH_G.buffer =
  3732. (byte*)XMALLOC(gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  3733. if (ssl->buffers.serverDH_G.buffer == NULL) {
  3734. ret = MEMORY_E;
  3735. } else
  3736. ssl->buffers.serverDH_G.length = gSz;
  3737. }
  3738. if (ret == 0) {
  3739. ret = wc_DhCopyNamedKey(serverGroup->name,
  3740. ssl->buffers.serverDH_P.buffer, &pSz,
  3741. ssl->buffers.serverDH_G.buffer, &gSz,
  3742. NULL, NULL);
  3743. }
  3744. if (ret == 0) {
  3745. ssl->buffers.weOwnDH = 1;
  3746. ssl->namedGroup = serverGroup->name;
  3747. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  3748. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  3749. ssl->options.dhDoKeyTest = 0;
  3750. #endif
  3751. ssl->options.haveDH = 1;
  3752. }
  3753. else {
  3754. if (ssl->buffers.serverDH_P.buffer != NULL) {
  3755. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  3756. DYNAMIC_TYPE_PUBLIC_KEY);
  3757. ssl->buffers.serverDH_P.length = 0;
  3758. ssl->buffers.serverDH_P.buffer = NULL;
  3759. }
  3760. if (ssl->buffers.serverDH_G.buffer != NULL) {
  3761. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  3762. DYNAMIC_TYPE_PUBLIC_KEY);
  3763. ssl->buffers.serverDH_G.length = 0;
  3764. ssl->buffers.serverDH_G.buffer = NULL;
  3765. }
  3766. }
  3767. }
  3768. return ret;
  3769. }
  3770. #endif
  3771. /* Set the highest priority common FFDHE group on the server as compared to
  3772. * client extensions.
  3773. *
  3774. * ssl SSL/TLS object.
  3775. * returns 0 on success, otherwise an error.
  3776. */
  3777. int TLSX_SupportedFFDHE_Set(WOLFSSL* ssl)
  3778. {
  3779. int ret;
  3780. TLSX* priority = NULL;
  3781. TLSX* ext = NULL;
  3782. TLSX* extension;
  3783. SupportedCurve* clientGroup;
  3784. SupportedCurve* group;
  3785. int found = 0;
  3786. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3787. /* May be doing PSK with no key exchange. */
  3788. if (extension == NULL)
  3789. return 0;
  3790. clientGroup = (SupportedCurve*)extension->data;
  3791. for (group = clientGroup; group != NULL; group = group->next) {
  3792. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(group->name)) {
  3793. found = 1;
  3794. break;
  3795. }
  3796. }
  3797. if (!found)
  3798. return 0;
  3799. if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
  3800. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  3801. DYNAMIC_TYPE_PUBLIC_KEY);
  3802. }
  3803. if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
  3804. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  3805. DYNAMIC_TYPE_PUBLIC_KEY);
  3806. }
  3807. ssl->buffers.serverDH_P.buffer = NULL;
  3808. ssl->buffers.serverDH_G.buffer = NULL;
  3809. ssl->buffers.weOwnDH = 0;
  3810. ssl->options.haveDH = 0;
  3811. ret = TLSX_PopulateSupportedGroups(ssl, &priority);
  3812. if (ret == WOLFSSL_SUCCESS) {
  3813. SupportedCurve* serverGroup;
  3814. ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS);
  3815. serverGroup = (SupportedCurve*)ext->data;
  3816. ret = tlsx_ffdhe_find_group(ssl, clientGroup, serverGroup);
  3817. }
  3818. TLSX_FreeAll(priority, ssl->heap);
  3819. return ret;
  3820. }
  3821. #endif /* HAVE_FFDHE && !WOLFSSL_NO_TLS12 */
  3822. #endif /* !NO_WOLFSSL_SERVER */
  3823. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3824. /* Return the preferred group.
  3825. *
  3826. * ssl SSL/TLS object.
  3827. * checkSupported Whether to check for the first supported group.
  3828. * returns BAD_FUNC_ARG if no group found, otherwise the group.
  3829. */
  3830. int TLSX_SupportedCurve_Preferred(WOLFSSL* ssl, int checkSupported)
  3831. {
  3832. TLSX* extension;
  3833. SupportedCurve* curve;
  3834. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3835. if (extension == NULL)
  3836. return BAD_FUNC_ARG;
  3837. curve = (SupportedCurve*)extension->data;
  3838. while (curve != NULL) {
  3839. if (!checkSupported || TLSX_KeyShare_IsSupported(curve->name))
  3840. return curve->name;
  3841. curve = curve->next;
  3842. }
  3843. return BAD_FUNC_ARG;
  3844. }
  3845. #endif /* HAVE_SUPPORTED_CURVES */
  3846. #ifndef NO_WOLFSSL_SERVER
  3847. static int TLSX_PointFormat_Parse(WOLFSSL* ssl, const byte* input,
  3848. word16 length, byte isRequest)
  3849. {
  3850. int ret;
  3851. /* validating formats list length */
  3852. if (ENUM_LEN > length || length != (word16)ENUM_LEN + input[0])
  3853. return BUFFER_ERROR;
  3854. if (isRequest) {
  3855. /* adding uncompressed point format to response */
  3856. ret = TLSX_UsePointFormat(&ssl->extensions, WOLFSSL_EC_PF_UNCOMPRESSED,
  3857. ssl->heap);
  3858. if (ret != WOLFSSL_SUCCESS)
  3859. return ret; /* throw error */
  3860. TLSX_SetResponse(ssl, TLSX_EC_POINT_FORMATS);
  3861. }
  3862. return 0;
  3863. }
  3864. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  3865. int TLSX_ValidateSupportedCurves(const WOLFSSL* ssl, byte first, byte second,
  3866. word32* ecdhCurveOID) {
  3867. TLSX* extension = NULL;
  3868. SupportedCurve* curve = NULL;
  3869. word32 oid = 0;
  3870. word32 defOid = 0;
  3871. word32 defSz = 80; /* Maximum known curve size is 66. */
  3872. word32 nextOid = 0;
  3873. word32 nextSz = 80; /* Maximum known curve size is 66. */
  3874. word32 currOid = ssl->ecdhCurveOID;
  3875. int ephmSuite = 0;
  3876. word16 octets = 0; /* according to 'ecc_set_type ecc_sets[];' */
  3877. int key = 0; /* validate key */
  3878. (void)oid;
  3879. if (first == CHACHA_BYTE) {
  3880. switch (second) {
  3881. case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
  3882. case TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3883. case TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3884. case TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256:
  3885. return 1; /* no suite restriction */
  3886. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
  3887. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256:
  3888. case TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3889. break;
  3890. }
  3891. }
  3892. if (first == ECC_BYTE || first == ECDHE_PSK_BYTE || first == CHACHA_BYTE)
  3893. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3894. if (!extension)
  3895. return 1; /* no suite restriction */
  3896. for (curve = (SupportedCurve*)extension->data;
  3897. curve && !key;
  3898. curve = curve->next) {
  3899. #ifdef OPENSSL_EXTRA
  3900. /* skip if name is not in supported ECC range
  3901. * or disabled by user */
  3902. if (wolfSSL_curve_is_disabled(ssl, curve->name))
  3903. continue;
  3904. #endif
  3905. /* find supported curve */
  3906. switch (curve->name) {
  3907. #ifdef HAVE_ECC
  3908. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  3909. #ifndef NO_ECC_SECP
  3910. case WOLFSSL_ECC_SECP160R1:
  3911. oid = ECC_SECP160R1_OID;
  3912. octets = 20;
  3913. break;
  3914. #endif /* !NO_ECC_SECP */
  3915. #ifdef HAVE_ECC_SECPR2
  3916. case WOLFSSL_ECC_SECP160R2:
  3917. oid = ECC_SECP160R2_OID;
  3918. octets = 20;
  3919. break;
  3920. #endif /* HAVE_ECC_SECPR2 */
  3921. #ifdef HAVE_ECC_KOBLITZ
  3922. case WOLFSSL_ECC_SECP160K1:
  3923. oid = ECC_SECP160K1_OID;
  3924. octets = 20;
  3925. break;
  3926. #endif /* HAVE_ECC_KOBLITZ */
  3927. #endif
  3928. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  3929. #ifndef NO_ECC_SECP
  3930. case WOLFSSL_ECC_SECP192R1:
  3931. oid = ECC_SECP192R1_OID;
  3932. octets = 24;
  3933. break;
  3934. #endif /* !NO_ECC_SECP */
  3935. #ifdef HAVE_ECC_KOBLITZ
  3936. case WOLFSSL_ECC_SECP192K1:
  3937. oid = ECC_SECP192K1_OID;
  3938. octets = 24;
  3939. break;
  3940. #endif /* HAVE_ECC_KOBLITZ */
  3941. #endif
  3942. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  3943. #ifndef NO_ECC_SECP
  3944. case WOLFSSL_ECC_SECP224R1:
  3945. oid = ECC_SECP224R1_OID;
  3946. octets = 28;
  3947. break;
  3948. #endif /* !NO_ECC_SECP */
  3949. #ifdef HAVE_ECC_KOBLITZ
  3950. case WOLFSSL_ECC_SECP224K1:
  3951. oid = ECC_SECP224K1_OID;
  3952. octets = 28;
  3953. break;
  3954. #endif /* HAVE_ECC_KOBLITZ */
  3955. #endif
  3956. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  3957. #ifndef NO_ECC_SECP
  3958. case WOLFSSL_ECC_SECP256R1:
  3959. oid = ECC_SECP256R1_OID;
  3960. octets = 32;
  3961. break;
  3962. #endif /* !NO_ECC_SECP */
  3963. #endif /* !NO_ECC256 || HAVE_ALL_CURVES */
  3964. #endif
  3965. #if (defined(HAVE_CURVE25519) || defined(HAVE_ED25519)) && ECC_MIN_KEY_SZ <= 256
  3966. case WOLFSSL_ECC_X25519:
  3967. oid = ECC_X25519_OID;
  3968. octets = 32;
  3969. break;
  3970. #endif /* HAVE_CURVE25519 */
  3971. #ifdef HAVE_ECC
  3972. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  3973. #ifdef HAVE_ECC_KOBLITZ
  3974. case WOLFSSL_ECC_SECP256K1:
  3975. oid = ECC_SECP256K1_OID;
  3976. octets = 32;
  3977. break;
  3978. #endif /* HAVE_ECC_KOBLITZ */
  3979. #ifdef HAVE_ECC_BRAINPOOL
  3980. case WOLFSSL_ECC_BRAINPOOLP256R1:
  3981. oid = ECC_BRAINPOOLP256R1_OID;
  3982. octets = 32;
  3983. break;
  3984. #endif /* HAVE_ECC_BRAINPOOL */
  3985. #ifdef WOLFSSL_SM2
  3986. case WOLFSSL_ECC_SM2P256V1:
  3987. oid = ECC_SM2P256V1_OID;
  3988. octets = 32;
  3989. break;
  3990. #endif /* WOLFSSL_SM2 */
  3991. #endif
  3992. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  3993. #ifndef NO_ECC_SECP
  3994. case WOLFSSL_ECC_SECP384R1:
  3995. oid = ECC_SECP384R1_OID;
  3996. octets = 48;
  3997. break;
  3998. #endif /* !NO_ECC_SECP */
  3999. #ifdef HAVE_ECC_BRAINPOOL
  4000. case WOLFSSL_ECC_BRAINPOOLP384R1:
  4001. oid = ECC_BRAINPOOLP384R1_OID;
  4002. octets = 48;
  4003. break;
  4004. #endif /* HAVE_ECC_BRAINPOOL */
  4005. #endif
  4006. #endif
  4007. #if (defined(HAVE_CURVE448) || defined(HAVE_ED448)) && ECC_MIN_KEY_SZ <= 448
  4008. case WOLFSSL_ECC_X448:
  4009. oid = ECC_X448_OID;
  4010. octets = 57;
  4011. break;
  4012. #endif /* HAVE_CURVE448 */
  4013. #ifdef HAVE_ECC
  4014. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  4015. #ifdef HAVE_ECC_BRAINPOOL
  4016. case WOLFSSL_ECC_BRAINPOOLP512R1:
  4017. oid = ECC_BRAINPOOLP512R1_OID;
  4018. octets = 64;
  4019. break;
  4020. #endif /* HAVE_ECC_BRAINPOOL */
  4021. #endif
  4022. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  4023. #ifndef NO_ECC_SECP
  4024. case WOLFSSL_ECC_SECP521R1:
  4025. oid = ECC_SECP521R1_OID;
  4026. octets = 66;
  4027. break;
  4028. #endif /* !NO_ECC_SECP */
  4029. #endif
  4030. #endif
  4031. default: continue; /* unsupported curve */
  4032. }
  4033. #ifdef HAVE_ECC
  4034. /* Set default Oid */
  4035. if (defOid == 0 && ssl->eccTempKeySz <= octets && defSz > octets) {
  4036. defOid = oid;
  4037. defSz = octets;
  4038. }
  4039. /* The eccTempKeySz is the preferred ephemeral key size */
  4040. if (currOid == 0 && ssl->eccTempKeySz == octets)
  4041. currOid = oid;
  4042. if ((nextOid == 0 || nextSz > octets) && ssl->eccTempKeySz <= octets) {
  4043. nextOid = oid;
  4044. nextSz = octets;
  4045. }
  4046. #else
  4047. if (defOid == 0 && defSz > octets) {
  4048. defOid = oid;
  4049. defSz = octets;
  4050. }
  4051. if (currOid == 0)
  4052. currOid = oid;
  4053. if (nextOid == 0 || nextSz > octets) {
  4054. nextOid = oid;
  4055. nextSz = octets;
  4056. }
  4057. #endif
  4058. if (first == ECC_BYTE) {
  4059. switch (second) {
  4060. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  4061. /* ECDHE_ECDSA */
  4062. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
  4063. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
  4064. case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
  4065. case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
  4066. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
  4067. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
  4068. case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
  4069. case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
  4070. case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
  4071. case TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
  4072. key |= ssl->ecdhCurveOID == oid;
  4073. ephmSuite = 1;
  4074. break;
  4075. #ifdef WOLFSSL_STATIC_DH
  4076. /* ECDH_ECDSA */
  4077. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
  4078. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
  4079. case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
  4080. case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
  4081. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
  4082. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
  4083. case TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
  4084. case TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
  4085. if (oid == ECC_X25519_OID && defOid == oid) {
  4086. defOid = 0;
  4087. defSz = 80;
  4088. }
  4089. if (oid == ECC_X448_OID && defOid == oid) {
  4090. defOid = 0;
  4091. defSz = 80;
  4092. }
  4093. key |= ssl->pkCurveOID == oid;
  4094. break;
  4095. #endif /* WOLFSSL_STATIC_DH */
  4096. #endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  4097. #ifndef NO_RSA
  4098. /* ECDHE_RSA */
  4099. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
  4100. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
  4101. case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
  4102. case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
  4103. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
  4104. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
  4105. case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
  4106. case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
  4107. key |= ssl->ecdhCurveOID == oid;
  4108. ephmSuite = 1;
  4109. break;
  4110. #if defined(HAVE_ECC) && defined(WOLFSSL_STATIC_DH)
  4111. /* ECDH_RSA */
  4112. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
  4113. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
  4114. case TLS_ECDH_RSA_WITH_RC4_128_SHA:
  4115. case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
  4116. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
  4117. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
  4118. case TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
  4119. case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
  4120. if (oid == ECC_X25519_OID && defOid == oid) {
  4121. defOid = 0;
  4122. defSz = 80;
  4123. }
  4124. if (oid == ECC_X448_OID && defOid == oid) {
  4125. defOid = 0;
  4126. defSz = 80;
  4127. }
  4128. key |= ssl->pkCurveOID == oid;
  4129. break;
  4130. #endif /* HAVE_ECC && WOLFSSL_STATIC_DH */
  4131. #endif
  4132. default:
  4133. if (oid == ECC_X25519_OID && defOid == oid) {
  4134. defOid = 0;
  4135. defSz = 80;
  4136. }
  4137. if (oid == ECC_X448_OID && defOid == oid) {
  4138. defOid = 0;
  4139. defSz = 80;
  4140. }
  4141. key = 1;
  4142. break;
  4143. }
  4144. }
  4145. /* ChaCha20-Poly1305 ECC cipher suites */
  4146. if (first == CHACHA_BYTE) {
  4147. switch (second) {
  4148. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  4149. /* ECDHE_ECDSA */
  4150. case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 :
  4151. case TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  4152. key |= ssl->ecdhCurveOID == oid;
  4153. ephmSuite = 1;
  4154. break;
  4155. #endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  4156. #ifndef NO_RSA
  4157. /* ECDHE_RSA */
  4158. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 :
  4159. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  4160. key |= ssl->ecdhCurveOID == oid;
  4161. ephmSuite = 1;
  4162. break;
  4163. #endif
  4164. default:
  4165. key = 1;
  4166. break;
  4167. }
  4168. }
  4169. }
  4170. *ecdhCurveOID = ssl->ecdhCurveOID;
  4171. /* Choose the default if it is at the required strength. */
  4172. #ifdef HAVE_ECC
  4173. if (*ecdhCurveOID == 0 && defSz == ssl->eccTempKeySz)
  4174. #else
  4175. if (*ecdhCurveOID == 0)
  4176. #endif
  4177. {
  4178. key = 1;
  4179. *ecdhCurveOID = defOid;
  4180. }
  4181. /* Choose any curve at the required strength. */
  4182. if (*ecdhCurveOID == 0) {
  4183. key = 1;
  4184. *ecdhCurveOID = currOid;
  4185. }
  4186. /* Choose the default if it is at the next highest strength. */
  4187. if (*ecdhCurveOID == 0 && defSz == nextSz)
  4188. *ecdhCurveOID = defOid;
  4189. /* Choose any curve at the next highest strength. */
  4190. if (*ecdhCurveOID == 0)
  4191. *ecdhCurveOID = nextOid;
  4192. /* No curve and ephemeral ECC suite requires a matching curve. */
  4193. if (*ecdhCurveOID == 0 && ephmSuite)
  4194. key = 0;
  4195. return key;
  4196. }
  4197. #endif
  4198. #endif /* NO_WOLFSSL_SERVER */
  4199. int TLSX_SupportedCurve_Copy(TLSX* src, TLSX** dst, void* heap)
  4200. {
  4201. TLSX* extension;
  4202. int ret;
  4203. extension = TLSX_Find(src, TLSX_SUPPORTED_GROUPS);
  4204. if (extension != NULL) {
  4205. SupportedCurve* curve;
  4206. for (curve = (SupportedCurve*)extension->data; curve != NULL;
  4207. curve = curve->next) {
  4208. ret = TLSX_UseSupportedCurve(dst, curve->name, heap);
  4209. if (ret != WOLFSSL_SUCCESS)
  4210. return MEMORY_E;
  4211. }
  4212. }
  4213. return 0;
  4214. }
  4215. int TLSX_UseSupportedCurve(TLSX** extensions, word16 name, void* heap)
  4216. {
  4217. TLSX* extension = NULL;
  4218. SupportedCurve* curve = NULL;
  4219. int ret;
  4220. if (extensions == NULL) {
  4221. return BAD_FUNC_ARG;
  4222. }
  4223. #ifdef WOLFSSL_TLS13
  4224. if (! TLSX_KeyShare_IsSupported(name)) {
  4225. return BAD_FUNC_ARG;
  4226. }
  4227. #endif
  4228. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  4229. if (!extension) {
  4230. ret = TLSX_SupportedCurve_New(&curve, name, heap);
  4231. if (ret != 0)
  4232. return ret;
  4233. ret = TLSX_Push(extensions, TLSX_SUPPORTED_GROUPS, curve, heap);
  4234. if (ret != 0) {
  4235. XFREE(curve, heap, DYNAMIC_TYPE_TLSX);
  4236. return ret;
  4237. }
  4238. }
  4239. else {
  4240. ret = TLSX_SupportedCurve_Append((SupportedCurve*)extension->data, name,
  4241. heap);
  4242. if (ret != 0)
  4243. return ret;
  4244. }
  4245. return WOLFSSL_SUCCESS;
  4246. }
  4247. int TLSX_UsePointFormat(TLSX** extensions, byte format, void* heap)
  4248. {
  4249. TLSX* extension = NULL;
  4250. PointFormat* point = NULL;
  4251. int ret = 0;
  4252. if (extensions == NULL)
  4253. return BAD_FUNC_ARG;
  4254. extension = TLSX_Find(*extensions, TLSX_EC_POINT_FORMATS);
  4255. if (!extension) {
  4256. ret = TLSX_PointFormat_New(&point, format, heap);
  4257. if (ret != 0)
  4258. return ret;
  4259. ret = TLSX_Push(extensions, TLSX_EC_POINT_FORMATS, point, heap);
  4260. if (ret != 0) {
  4261. XFREE(point, heap, DYNAMIC_TYPE_TLSX);
  4262. return ret;
  4263. }
  4264. }
  4265. else {
  4266. ret = TLSX_PointFormat_Append((PointFormat*)extension->data, format,
  4267. heap);
  4268. if (ret != 0)
  4269. return ret;
  4270. }
  4271. return WOLFSSL_SUCCESS;
  4272. }
  4273. #define EC_FREE_ALL TLSX_SupportedCurve_FreeAll
  4274. #define EC_VALIDATE_REQUEST TLSX_SupportedCurve_ValidateRequest
  4275. /* In TLS 1.2 the server never sends supported curve extension, but in TLS 1.3
  4276. * the server can send supported groups extension to indicate what it will
  4277. * support for later connections. */
  4278. #if !defined(NO_WOLFSSL_CLIENT) || defined(WOLFSSL_TLS13)
  4279. #define EC_GET_SIZE TLSX_SupportedCurve_GetSize
  4280. #define EC_WRITE TLSX_SupportedCurve_Write
  4281. #else
  4282. #define EC_GET_SIZE(list) 0
  4283. #define EC_WRITE(a, b) 0
  4284. #endif
  4285. #if !defined(NO_WOLFSSL_SERVER) || (defined(WOLFSSL_TLS13) && \
  4286. !defined(WOLFSSL_NO_SERVER_GROUPS_EXT))
  4287. #define EC_PARSE TLSX_SupportedCurve_Parse
  4288. #else
  4289. #define EC_PARSE(a, b, c, d, e) 0
  4290. #endif
  4291. #define PF_FREE_ALL TLSX_PointFormat_FreeAll
  4292. #define PF_VALIDATE_REQUEST TLSX_PointFormat_ValidateRequest
  4293. #define PF_VALIDATE_RESPONSE TLSX_PointFormat_ValidateResponse
  4294. #define PF_GET_SIZE TLSX_PointFormat_GetSize
  4295. #define PF_WRITE TLSX_PointFormat_Write
  4296. #ifndef NO_WOLFSSL_SERVER
  4297. #define PF_PARSE TLSX_PointFormat_Parse
  4298. #else
  4299. #define PF_PARSE(a, b, c, d) 0
  4300. #endif
  4301. #else
  4302. #define EC_FREE_ALL(list, heap) WC_DO_NOTHING
  4303. #define EC_GET_SIZE(list) 0
  4304. #define EC_WRITE(a, b) 0
  4305. #define EC_PARSE(a, b, c, d, e) 0
  4306. #define EC_VALIDATE_REQUEST(a, b) WC_DO_NOTHING
  4307. #define PF_FREE_ALL(list, heap) WC_DO_NOTHING
  4308. #define PF_GET_SIZE(list) 0
  4309. #define PF_WRITE(a, b) 0
  4310. #define PF_PARSE(a, b, c, d) 0
  4311. #define PF_VALIDATE_REQUEST(a, b) WC_DO_NOTHING
  4312. #define PF_VALIDATE_RESPONSE(a, b) WC_DO_NOTHING
  4313. #endif /* HAVE_SUPPORTED_CURVES */
  4314. /******************************************************************************/
  4315. /* Renegotiation Indication */
  4316. /******************************************************************************/
  4317. #if defined(HAVE_SECURE_RENEGOTIATION) \
  4318. || defined(HAVE_SERVER_RENEGOTIATION_INFO)
  4319. static byte TLSX_SecureRenegotiation_GetSize(SecureRenegotiation* data,
  4320. int isRequest)
  4321. {
  4322. byte length = OPAQUE8_LEN; /* empty info length */
  4323. /* data will be NULL for HAVE_SERVER_RENEGOTIATION_INFO only */
  4324. if (data && data->enabled && data->verifySet) {
  4325. /* client sends client_verify_data only */
  4326. length += TLS_FINISHED_SZ;
  4327. /* server also sends server_verify_data */
  4328. if (!isRequest)
  4329. length += TLS_FINISHED_SZ;
  4330. }
  4331. return length;
  4332. }
  4333. static word16 TLSX_SecureRenegotiation_Write(SecureRenegotiation* data,
  4334. byte* output, int isRequest)
  4335. {
  4336. word16 offset = OPAQUE8_LEN; /* RenegotiationInfo length */
  4337. if (data && data->enabled && data->verifySet) {
  4338. /* client sends client_verify_data only */
  4339. XMEMCPY(output + offset, data->client_verify_data, TLS_FINISHED_SZ);
  4340. offset += TLS_FINISHED_SZ;
  4341. /* server also sends server_verify_data */
  4342. if (!isRequest) {
  4343. XMEMCPY(output + offset, data->server_verify_data, TLS_FINISHED_SZ);
  4344. offset += TLS_FINISHED_SZ;
  4345. }
  4346. }
  4347. output[0] = (byte)(offset - 1); /* info length - self */
  4348. return offset;
  4349. }
  4350. static int TLSX_SecureRenegotiation_Parse(WOLFSSL* ssl, const byte* input,
  4351. word16 length, byte isRequest)
  4352. {
  4353. int ret = SECURE_RENEGOTIATION_E;
  4354. if (length >= OPAQUE8_LEN) {
  4355. if (isRequest) {
  4356. #ifndef NO_WOLFSSL_SERVER
  4357. if (ssl->secure_renegotiation == NULL) {
  4358. ret = wolfSSL_UseSecureRenegotiation(ssl);
  4359. if (ret == WOLFSSL_SUCCESS)
  4360. ret = 0;
  4361. }
  4362. if (ret != 0 && ret != SECURE_RENEGOTIATION_E) {
  4363. }
  4364. else if (ssl->secure_renegotiation == NULL) {
  4365. }
  4366. else if (!ssl->secure_renegotiation->enabled) {
  4367. if (*input == 0) {
  4368. input++; /* get past size */
  4369. ssl->secure_renegotiation->enabled = 1;
  4370. TLSX_SetResponse(ssl, TLSX_RENEGOTIATION_INFO);
  4371. ret = 0;
  4372. }
  4373. else {
  4374. /* already in error state */
  4375. WOLFSSL_MSG("SCR client verify data present");
  4376. }
  4377. }
  4378. else if (*input == TLS_FINISHED_SZ) {
  4379. if (length < TLS_FINISHED_SZ + 1) {
  4380. WOLFSSL_MSG("SCR malformed buffer");
  4381. ret = BUFFER_E;
  4382. }
  4383. else {
  4384. input++; /* get past size */
  4385. /* validate client verify data */
  4386. if (XMEMCMP(input,
  4387. ssl->secure_renegotiation->client_verify_data,
  4388. TLS_FINISHED_SZ) == 0) {
  4389. WOLFSSL_MSG("SCR client verify data match");
  4390. TLSX_SetResponse(ssl, TLSX_RENEGOTIATION_INFO);
  4391. ret = 0; /* verified */
  4392. }
  4393. else {
  4394. /* already in error state */
  4395. WOLFSSL_MSG("SCR client verify data Failure");
  4396. }
  4397. }
  4398. }
  4399. #endif
  4400. }
  4401. else if (ssl->secure_renegotiation != NULL) {
  4402. #ifndef NO_WOLFSSL_CLIENT
  4403. if (!ssl->secure_renegotiation->enabled) {
  4404. if (*input == 0) {
  4405. ssl->secure_renegotiation->enabled = 1;
  4406. ret = 0;
  4407. }
  4408. }
  4409. else if (*input == 2 * TLS_FINISHED_SZ &&
  4410. length == 2 * TLS_FINISHED_SZ + OPAQUE8_LEN) {
  4411. input++; /* get past size */
  4412. /* validate client and server verify data */
  4413. if (XMEMCMP(input,
  4414. ssl->secure_renegotiation->client_verify_data,
  4415. TLS_FINISHED_SZ) == 0 &&
  4416. XMEMCMP(input + TLS_FINISHED_SZ,
  4417. ssl->secure_renegotiation->server_verify_data,
  4418. TLS_FINISHED_SZ) == 0) {
  4419. WOLFSSL_MSG("SCR client and server verify data match");
  4420. ret = 0; /* verified */
  4421. }
  4422. else {
  4423. /* already in error state */
  4424. WOLFSSL_MSG("SCR client and server verify data Failure");
  4425. }
  4426. }
  4427. #endif
  4428. }
  4429. }
  4430. if (ret != 0) {
  4431. WOLFSSL_ERROR_VERBOSE(ret);
  4432. SendAlert(ssl, alert_fatal, handshake_failure);
  4433. }
  4434. return ret;
  4435. }
  4436. int TLSX_UseSecureRenegotiation(TLSX** extensions, void* heap)
  4437. {
  4438. int ret = 0;
  4439. SecureRenegotiation* data;
  4440. data = (SecureRenegotiation*)XMALLOC(sizeof(SecureRenegotiation), heap,
  4441. DYNAMIC_TYPE_TLSX);
  4442. if (data == NULL)
  4443. return MEMORY_E;
  4444. XMEMSET(data, 0, sizeof(SecureRenegotiation));
  4445. ret = TLSX_Push(extensions, TLSX_RENEGOTIATION_INFO, data, heap);
  4446. if (ret != 0) {
  4447. XFREE(data, heap, DYNAMIC_TYPE_TLSX);
  4448. return ret;
  4449. }
  4450. return WOLFSSL_SUCCESS;
  4451. }
  4452. #ifdef HAVE_SERVER_RENEGOTIATION_INFO
  4453. int TLSX_AddEmptyRenegotiationInfo(TLSX** extensions, void* heap)
  4454. {
  4455. int ret;
  4456. /* send empty renegotiation_info extension */
  4457. TLSX* ext = TLSX_Find(*extensions, TLSX_RENEGOTIATION_INFO);
  4458. if (ext == NULL) {
  4459. ret = TLSX_UseSecureRenegotiation(extensions, heap);
  4460. if (ret != WOLFSSL_SUCCESS)
  4461. return ret;
  4462. ext = TLSX_Find(*extensions, TLSX_RENEGOTIATION_INFO);
  4463. }
  4464. if (ext)
  4465. ext->resp = 1;
  4466. return WOLFSSL_SUCCESS;
  4467. }
  4468. #endif /* HAVE_SERVER_RENEGOTIATION_INFO */
  4469. #define SCR_FREE_ALL(data, heap) XFREE(data, (heap), DYNAMIC_TYPE_TLSX)
  4470. #define SCR_GET_SIZE TLSX_SecureRenegotiation_GetSize
  4471. #define SCR_WRITE TLSX_SecureRenegotiation_Write
  4472. #define SCR_PARSE TLSX_SecureRenegotiation_Parse
  4473. #else
  4474. #define SCR_FREE_ALL(a, heap) WC_DO_NOTHING
  4475. #define SCR_GET_SIZE(a, b) 0
  4476. #define SCR_WRITE(a, b, c) 0
  4477. #define SCR_PARSE(a, b, c, d) 0
  4478. #endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
  4479. /******************************************************************************/
  4480. /* Session Tickets */
  4481. /******************************************************************************/
  4482. #ifdef HAVE_SESSION_TICKET
  4483. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  4484. static void TLSX_SessionTicket_ValidateRequest(WOLFSSL* ssl)
  4485. {
  4486. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_SESSION_TICKET);
  4487. SessionTicket* ticket = extension ?
  4488. (SessionTicket*)extension->data : NULL;
  4489. if (ticket) {
  4490. /* TODO validate ticket timeout here! */
  4491. if (ticket->lifetime == 0xfffffff) {
  4492. /* send empty ticket on timeout */
  4493. TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4494. }
  4495. }
  4496. }
  4497. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  4498. static word16 TLSX_SessionTicket_GetSize(SessionTicket* ticket, int isRequest)
  4499. {
  4500. (void)isRequest;
  4501. return ticket ? ticket->size : 0;
  4502. }
  4503. static word16 TLSX_SessionTicket_Write(SessionTicket* ticket, byte* output,
  4504. int isRequest)
  4505. {
  4506. word16 offset = 0; /* empty ticket */
  4507. if (isRequest && ticket) {
  4508. XMEMCPY(output + offset, ticket->data, ticket->size);
  4509. offset += ticket->size;
  4510. }
  4511. return offset;
  4512. }
  4513. static int TLSX_SessionTicket_Parse(WOLFSSL* ssl, const byte* input,
  4514. word16 length, byte isRequest)
  4515. {
  4516. int ret = 0;
  4517. (void) input; /* avoid unused parameter if NO_WOLFSSL_SERVER defined */
  4518. if (!isRequest) {
  4519. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_SESSION_TICKET))
  4520. return TLSX_HandleUnsupportedExtension(ssl);
  4521. if (length != 0)
  4522. return BUFFER_ERROR;
  4523. #ifndef NO_WOLFSSL_CLIENT
  4524. ssl->expect_session_ticket = 1;
  4525. #endif
  4526. }
  4527. #ifndef NO_WOLFSSL_SERVER
  4528. else {
  4529. /* server side */
  4530. if (ssl->ctx->ticketEncCb == NULL) {
  4531. WOLFSSL_MSG("Client sent session ticket, server has no callback");
  4532. return 0;
  4533. }
  4534. #ifdef HAVE_SECURE_RENEGOTIATION
  4535. if (IsSCR(ssl)) {
  4536. WOLFSSL_MSG("Client sent session ticket during SCR. Ignoring.");
  4537. return 0;
  4538. }
  4539. #endif
  4540. if (length > SESSION_TICKET_LEN) {
  4541. ret = BAD_TICKET_MSG_SZ;
  4542. WOLFSSL_ERROR_VERBOSE(ret);
  4543. } else if (IsAtLeastTLSv1_3(ssl->version)) {
  4544. WOLFSSL_MSG("Process client ticket rejected, TLS 1.3 no support");
  4545. ssl->options.rejectTicket = 1;
  4546. ret = 0; /* not fatal */
  4547. } else if (ssl->options.noTicketTls12) {
  4548. /* ignore ticket request */
  4549. } else if (length == 0) {
  4550. /* blank ticket */
  4551. ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4552. if (ret == WOLFSSL_SUCCESS) {
  4553. ret = 0;
  4554. /* send blank ticket */
  4555. TLSX_SetResponse(ssl, TLSX_SESSION_TICKET);
  4556. ssl->options.createTicket = 1; /* will send ticket msg */
  4557. ssl->options.useTicket = 1;
  4558. ssl->options.resuming = 0; /* no standard resumption */
  4559. ssl->arrays->sessionIDSz = 0; /* no echo on blank ticket */
  4560. }
  4561. } else {
  4562. /* got actual ticket from client */
  4563. ret = DoClientTicket(ssl, input, length);
  4564. if (ret == WOLFSSL_TICKET_RET_OK) { /* use ticket to resume */
  4565. WOLFSSL_MSG("Using existing client ticket");
  4566. ssl->options.useTicket = 1;
  4567. ssl->options.resuming = 1;
  4568. /* SERVER: ticket is peer auth. */
  4569. ssl->options.peerAuthGood = 1;
  4570. } else if (ret == WOLFSSL_TICKET_RET_CREATE) {
  4571. WOLFSSL_MSG("Using existing client ticket, creating new one");
  4572. ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4573. if (ret == WOLFSSL_SUCCESS) {
  4574. ret = 0;
  4575. TLSX_SetResponse(ssl, TLSX_SESSION_TICKET);
  4576. /* send blank ticket */
  4577. ssl->options.createTicket = 1; /* will send ticket msg */
  4578. ssl->options.useTicket = 1;
  4579. ssl->options.resuming = 1;
  4580. /* SERVER: ticket is peer auth. */
  4581. ssl->options.peerAuthGood = 1;
  4582. }
  4583. } else if (ret == WOLFSSL_TICKET_RET_REJECT) {
  4584. WOLFSSL_MSG("Process client ticket rejected, not using");
  4585. ssl->options.rejectTicket = 1;
  4586. ret = 0; /* not fatal */
  4587. } else if (ret == VERSION_ERROR) {
  4588. WOLFSSL_MSG("Process client ticket rejected, bad TLS version");
  4589. ssl->options.rejectTicket = 1;
  4590. ret = 0; /* not fatal */
  4591. } else if (ret == WOLFSSL_TICKET_RET_FATAL) {
  4592. WOLFSSL_MSG("Process client ticket fatal error, not using");
  4593. } else if (ret < 0) {
  4594. WOLFSSL_MSG("Process client ticket unknown error, not using");
  4595. }
  4596. }
  4597. }
  4598. #endif /* NO_WOLFSSL_SERVER */
  4599. #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER)
  4600. (void)ssl;
  4601. #endif
  4602. return ret;
  4603. }
  4604. WOLFSSL_LOCAL SessionTicket* TLSX_SessionTicket_Create(word32 lifetime,
  4605. byte* data, word16 size, void* heap)
  4606. {
  4607. SessionTicket* ticket = (SessionTicket*)XMALLOC(sizeof(SessionTicket),
  4608. heap, DYNAMIC_TYPE_TLSX);
  4609. if (ticket) {
  4610. ticket->data = (byte*)XMALLOC(size, heap, DYNAMIC_TYPE_TLSX);
  4611. if (ticket->data == NULL) {
  4612. XFREE(ticket, heap, DYNAMIC_TYPE_TLSX);
  4613. return NULL;
  4614. }
  4615. XMEMCPY(ticket->data, data, size);
  4616. ticket->size = size;
  4617. ticket->lifetime = lifetime;
  4618. }
  4619. (void)heap;
  4620. return ticket;
  4621. }
  4622. WOLFSSL_LOCAL void TLSX_SessionTicket_Free(SessionTicket* ticket, void* heap)
  4623. {
  4624. if (ticket) {
  4625. XFREE(ticket->data, heap, DYNAMIC_TYPE_TLSX);
  4626. XFREE(ticket, heap, DYNAMIC_TYPE_TLSX);
  4627. }
  4628. (void)heap;
  4629. }
  4630. int TLSX_UseSessionTicket(TLSX** extensions, SessionTicket* ticket, void* heap)
  4631. {
  4632. int ret = 0;
  4633. if (extensions == NULL)
  4634. return BAD_FUNC_ARG;
  4635. /* If the ticket is NULL, the client will request a new ticket from the
  4636. server. Otherwise, the client will use it in the next client hello. */
  4637. if ((ret = TLSX_Push(extensions, TLSX_SESSION_TICKET, (void*)ticket, heap))
  4638. != 0)
  4639. return ret;
  4640. return WOLFSSL_SUCCESS;
  4641. }
  4642. #define WOLF_STK_VALIDATE_REQUEST TLSX_SessionTicket_ValidateRequest
  4643. #define WOLF_STK_GET_SIZE TLSX_SessionTicket_GetSize
  4644. #define WOLF_STK_WRITE TLSX_SessionTicket_Write
  4645. #define WOLF_STK_PARSE TLSX_SessionTicket_Parse
  4646. #define WOLF_STK_FREE(stk, heap) TLSX_SessionTicket_Free((SessionTicket*)(stk),(heap))
  4647. #else
  4648. #define WOLF_STK_FREE(a, b) WC_DO_NOTHING
  4649. #define WOLF_STK_VALIDATE_REQUEST(a) WC_DO_NOTHING
  4650. #define WOLF_STK_GET_SIZE(a, b) 0
  4651. #define WOLF_STK_WRITE(a, b, c) 0
  4652. #define WOLF_STK_PARSE(a, b, c, d) 0
  4653. #endif /* HAVE_SESSION_TICKET */
  4654. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  4655. /******************************************************************************/
  4656. /* Encrypt-then-MAC */
  4657. /******************************************************************************/
  4658. #ifndef WOLFSSL_NO_TLS12
  4659. static int TLSX_EncryptThenMac_Use(WOLFSSL* ssl);
  4660. /**
  4661. * Get the size of the Encrypt-Then-MAC extension.
  4662. *
  4663. * msgType Type of message to put extension into.
  4664. * pSz Size of extension data.
  4665. * return SANITY_MSG_E when the message is not allowed to have extension and
  4666. * 0 otherwise.
  4667. */
  4668. static int TLSX_EncryptThenMac_GetSize(byte msgType, word16* pSz)
  4669. {
  4670. (void)pSz;
  4671. if (msgType != client_hello && msgType != server_hello) {
  4672. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4673. return SANITY_MSG_E;
  4674. }
  4675. /* Empty extension */
  4676. return 0;
  4677. }
  4678. /**
  4679. * Write the Encrypt-Then-MAC extension.
  4680. *
  4681. * data Unused
  4682. * output Extension data buffer. Unused.
  4683. * msgType Type of message to put extension into.
  4684. * pSz Size of extension data.
  4685. * return SANITY_MSG_E when the message is not allowed to have extension and
  4686. * 0 otherwise.
  4687. */
  4688. static int TLSX_EncryptThenMac_Write(void* data, byte* output, byte msgType,
  4689. word16* pSz)
  4690. {
  4691. (void)data;
  4692. (void)output;
  4693. (void)pSz;
  4694. if (msgType != client_hello && msgType != server_hello) {
  4695. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4696. return SANITY_MSG_E;
  4697. }
  4698. /* Empty extension */
  4699. return 0;
  4700. }
  4701. /**
  4702. * Parse the Encrypt-Then-MAC extension.
  4703. *
  4704. * ssl SSL object
  4705. * input Extension data buffer.
  4706. * length Length of this extension's data.
  4707. * msgType Type of message to extension appeared in.
  4708. * return SANITY_MSG_E when the message is not allowed to have extension,
  4709. * BUFFER_ERROR when the extension's data is invalid,
  4710. * MEMORY_E when unable to allocate memory and
  4711. * 0 otherwise.
  4712. */
  4713. static int TLSX_EncryptThenMac_Parse(WOLFSSL* ssl, const byte* input,
  4714. word16 length, byte msgType)
  4715. {
  4716. int ret;
  4717. (void)input;
  4718. if (msgType != client_hello && msgType != server_hello) {
  4719. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4720. return SANITY_MSG_E;
  4721. }
  4722. /* Empty extension */
  4723. if (length != 0)
  4724. return BUFFER_ERROR;
  4725. if (msgType == client_hello) {
  4726. /* Check the user hasn't disallowed use of Encrypt-Then-Mac. */
  4727. if (!ssl->options.disallowEncThenMac) {
  4728. ssl->options.encThenMac = 1;
  4729. /* Set the extension reply. */
  4730. ret = TLSX_EncryptThenMac_Use(ssl);
  4731. if (ret != 0)
  4732. return ret;
  4733. }
  4734. return 0;
  4735. }
  4736. /* Server Hello */
  4737. if (ssl->options.disallowEncThenMac) {
  4738. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4739. return SANITY_MSG_E;
  4740. }
  4741. ssl->options.encThenMac = 1;
  4742. return 0;
  4743. }
  4744. /**
  4745. * Add the Encrypt-Then-MAC extension to list.
  4746. *
  4747. * ssl SSL object
  4748. * return MEMORY_E when unable to allocate memory and 0 otherwise.
  4749. */
  4750. static int TLSX_EncryptThenMac_Use(WOLFSSL* ssl)
  4751. {
  4752. int ret = 0;
  4753. TLSX* extension;
  4754. /* Find the Encrypt-Then-Mac extension if it exists. */
  4755. extension = TLSX_Find(ssl->extensions, TLSX_ENCRYPT_THEN_MAC);
  4756. if (extension == NULL) {
  4757. /* Push new Encrypt-Then-Mac extension. */
  4758. ret = TLSX_Push(&ssl->extensions, TLSX_ENCRYPT_THEN_MAC, NULL,
  4759. ssl->heap);
  4760. if (ret != 0)
  4761. return ret;
  4762. }
  4763. return 0;
  4764. }
  4765. /**
  4766. * Set the Encrypt-Then-MAC extension as one to respond too.
  4767. *
  4768. * ssl SSL object
  4769. * return EXT_MISSING when EncryptThenMac extension not in list.
  4770. */
  4771. int TLSX_EncryptThenMac_Respond(WOLFSSL* ssl)
  4772. {
  4773. TLSX* extension;
  4774. extension = TLSX_Find(ssl->extensions, TLSX_ENCRYPT_THEN_MAC);
  4775. if (extension == NULL)
  4776. return EXT_MISSING;
  4777. extension->resp = 1;
  4778. return 0;
  4779. }
  4780. #define ETM_GET_SIZE TLSX_EncryptThenMac_GetSize
  4781. #define ETM_WRITE TLSX_EncryptThenMac_Write
  4782. #define ETM_PARSE TLSX_EncryptThenMac_Parse
  4783. #else
  4784. #define ETM_GET_SIZE(a, b) 0
  4785. #define ETM_WRITE(a, b, c, d) 0
  4786. #define ETM_PARSE(a, b, c, d) 0
  4787. #endif /* !WOLFSSL_NO_TLS12 */
  4788. #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */
  4789. #ifdef WOLFSSL_SRTP
  4790. /******************************************************************************/
  4791. /* DTLS SRTP (Secure Real-time Transport Protocol) */
  4792. /******************************************************************************/
  4793. /* Only support single SRTP profile */
  4794. typedef struct TlsxSrtp {
  4795. word16 profileCount;
  4796. word16 ids; /* selected bits */
  4797. } TlsxSrtp;
  4798. static int TLSX_UseSRTP_GetSize(TlsxSrtp *srtp)
  4799. {
  4800. /* SRTP Profile Len (2)
  4801. * SRTP Profiles (2)
  4802. * MKI (master key id) Length */
  4803. return (OPAQUE16_LEN + (srtp->profileCount * OPAQUE16_LEN) + 1);
  4804. }
  4805. static TlsxSrtp* TLSX_UseSRTP_New(word16 ids, void* heap)
  4806. {
  4807. TlsxSrtp* srtp;
  4808. int i;
  4809. srtp = (TlsxSrtp*)XMALLOC(sizeof(TlsxSrtp), heap, DYNAMIC_TYPE_TLSX);
  4810. if (srtp == NULL) {
  4811. WOLFSSL_MSG("TLSX SRTP Memory failure");
  4812. return NULL;
  4813. }
  4814. /* count and test each bit set */
  4815. srtp->profileCount = 0;
  4816. for (i=0; i<16; i++) {
  4817. if (ids & (1 << i)) {
  4818. srtp->profileCount++;
  4819. }
  4820. }
  4821. srtp->ids = ids;
  4822. return srtp;
  4823. }
  4824. static void TLSX_UseSRTP_Free(TlsxSrtp *srtp, void* heap)
  4825. {
  4826. if (srtp != NULL) {
  4827. XFREE(srtp, heap, DYNAMIC_TYPE_TLSX);
  4828. }
  4829. (void)heap;
  4830. }
  4831. static int TLSX_UseSRTP_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  4832. byte isRequest)
  4833. {
  4834. int ret = BAD_FUNC_ARG;
  4835. word16 profile_len = 0;
  4836. word16 profile_value = 0;
  4837. word16 offset = 0;
  4838. #ifndef NO_WOLFSSL_SERVER
  4839. int i;
  4840. TlsxSrtp* srtp = NULL;
  4841. #endif
  4842. if (length < OPAQUE16_LEN) {
  4843. return BUFFER_ERROR;
  4844. }
  4845. /* reset selected DTLS SRTP profile ID */
  4846. ssl->dtlsSrtpId = 0;
  4847. /* total length, not include itself */
  4848. ato16(input, &profile_len);
  4849. offset += OPAQUE16_LEN;
  4850. if (!isRequest) {
  4851. #ifndef NO_WOLFSSL_CLIENT
  4852. if (length < offset + OPAQUE16_LEN)
  4853. return BUFFER_ERROR;
  4854. ato16(input + offset, &profile_value);
  4855. /* check that the profile received was in the ones we support */
  4856. if (profile_value < 16 &&
  4857. (ssl->dtlsSrtpProfiles & (1 << profile_value))) {
  4858. ssl->dtlsSrtpId = profile_value;
  4859. ret = 0; /* success */
  4860. }
  4861. #endif
  4862. }
  4863. #ifndef NO_WOLFSSL_SERVER
  4864. else {
  4865. /* parse remainder one profile at a time, looking for match in CTX */
  4866. ret = 0;
  4867. for (i=offset; i<length; i+=OPAQUE16_LEN) {
  4868. if (length < (i + OPAQUE16_LEN)) {
  4869. WOLFSSL_MSG("Unexpected length when parsing SRTP profile");
  4870. ret = BUFFER_ERROR;
  4871. break;
  4872. }
  4873. ato16(input+i, &profile_value);
  4874. /* find first match */
  4875. if (profile_value < 16 &&
  4876. ssl->dtlsSrtpProfiles & (1 << profile_value)) {
  4877. ssl->dtlsSrtpId = profile_value;
  4878. /* make sure we respond with selected SRTP id selected */
  4879. srtp = TLSX_UseSRTP_New((1 << profile_value), ssl->heap);
  4880. if (srtp != NULL) {
  4881. ret = TLSX_Push(&ssl->extensions, TLSX_USE_SRTP,
  4882. (void*)srtp, ssl->heap);
  4883. if (ret == 0) {
  4884. TLSX_SetResponse(ssl, TLSX_USE_SRTP);
  4885. /* successfully set extension */
  4886. }
  4887. }
  4888. else {
  4889. ret = MEMORY_E;
  4890. }
  4891. break;
  4892. }
  4893. }
  4894. }
  4895. if (ret == 0 && ssl->dtlsSrtpId == 0) {
  4896. WOLFSSL_MSG("TLSX_UseSRTP_Parse profile not found!");
  4897. /* not fatal */
  4898. }
  4899. else if (ret != 0) {
  4900. ssl->dtlsSrtpId = 0;
  4901. TLSX_UseSRTP_Free(srtp, ssl->heap);
  4902. }
  4903. #endif
  4904. (void)profile_len;
  4905. return ret;
  4906. }
  4907. static word16 TLSX_UseSRTP_Write(TlsxSrtp* srtp, byte* output)
  4908. {
  4909. word16 offset = 0;
  4910. int i, j;
  4911. c16toa(srtp->profileCount * 2, output + offset);
  4912. offset += OPAQUE16_LEN;
  4913. j = 0;
  4914. for (i = 0; i < srtp->profileCount; i++) {
  4915. for (; j < 16; j++) {
  4916. if (srtp->ids & (1 << j)) {
  4917. c16toa(j, output + offset);
  4918. offset += OPAQUE16_LEN;
  4919. }
  4920. }
  4921. }
  4922. output[offset++] = 0x00; /* MKI Length */
  4923. return offset;
  4924. }
  4925. static int TLSX_UseSRTP(TLSX** extensions, word16 profiles, void* heap)
  4926. {
  4927. int ret = 0;
  4928. TLSX* extension;
  4929. if (extensions == NULL) {
  4930. return BAD_FUNC_ARG;
  4931. }
  4932. extension = TLSX_Find(*extensions, TLSX_USE_SRTP);
  4933. if (extension == NULL) {
  4934. TlsxSrtp* srtp = TLSX_UseSRTP_New(profiles, heap);
  4935. if (srtp == NULL) {
  4936. return MEMORY_E;
  4937. }
  4938. ret = TLSX_Push(extensions, TLSX_USE_SRTP, (void*)srtp, heap);
  4939. if (ret != 0) {
  4940. TLSX_UseSRTP_Free(srtp, heap);
  4941. }
  4942. }
  4943. return ret;
  4944. }
  4945. #ifndef NO_WOLFSSL_SERVER
  4946. #define SRTP_FREE TLSX_UseSRTP_Free
  4947. #define SRTP_PARSE TLSX_UseSRTP_Parse
  4948. #define SRTP_WRITE TLSX_UseSRTP_Write
  4949. #define SRTP_GET_SIZE TLSX_UseSRTP_GetSize
  4950. #else
  4951. #define SRTP_FREE(a, b) WC_DO_NOTHING
  4952. #define SRTP_PARSE(a, b, c, d) 0
  4953. #define SRTP_WRITE(a, b) 0
  4954. #define SRTP_GET_SIZE(a) 0
  4955. #endif
  4956. #endif /* WOLFSSL_SRTP */
  4957. /******************************************************************************/
  4958. /* Supported Versions */
  4959. /******************************************************************************/
  4960. #ifdef WOLFSSL_TLS13
  4961. static WC_INLINE int versionIsGreater(byte isDtls, byte a, byte b)
  4962. {
  4963. (void)isDtls;
  4964. #ifdef WOLFSSL_DTLS
  4965. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4966. if (isDtls)
  4967. return a < b;
  4968. #endif /* WOLFSSL_DTLS */
  4969. return a > b;
  4970. }
  4971. static WC_INLINE int versionIsLesser(byte isDtls, byte a, byte b)
  4972. {
  4973. (void)isDtls;
  4974. #ifdef WOLFSSL_DTLS
  4975. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4976. if (isDtls)
  4977. return a > b;
  4978. #endif /* WOLFSSL_DTLS */
  4979. return a < b;
  4980. }
  4981. static WC_INLINE int versionIsAtLeast(byte isDtls, byte a, byte b)
  4982. {
  4983. (void)isDtls;
  4984. #ifdef WOLFSSL_DTLS
  4985. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4986. if (isDtls)
  4987. return a <= b;
  4988. #endif /* WOLFSSL_DTLS */
  4989. return a >= b;
  4990. }
  4991. static WC_INLINE int versionIsLessEqual(byte isDtls, byte a, byte b)
  4992. {
  4993. (void)isDtls;
  4994. #ifdef WOLFSSL_DTLS
  4995. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4996. if (isDtls)
  4997. return a >= b;
  4998. #endif /* WOLFSSL_DTLS */
  4999. return a <= b;
  5000. }
  5001. /* Return the size of the SupportedVersions extension's data.
  5002. *
  5003. * data The SSL/TLS object.
  5004. * msgType The type of the message this extension is being written into.
  5005. * returns the length of data that will be in the extension.
  5006. */
  5007. static int TLSX_SupportedVersions_GetSize(void* data, byte msgType, word16* pSz)
  5008. {
  5009. WOLFSSL* ssl = (WOLFSSL*)data;
  5010. byte tls13Minor, tls12Minor, tls11Minor, isDtls;
  5011. isDtls = !!ssl->options.dtls;
  5012. tls13Minor = (byte)(isDtls ? DTLSv1_3_MINOR : TLSv1_3_MINOR);
  5013. tls12Minor = (byte)(isDtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR);
  5014. tls11Minor = (byte)(isDtls ? DTLS_MINOR : TLSv1_1_MINOR);
  5015. /* unused on some configuration */
  5016. (void)tls12Minor;
  5017. (void)tls13Minor;
  5018. (void)tls11Minor;
  5019. if (msgType == client_hello) {
  5020. /* TLS v1.2 and TLS v1.3 */
  5021. int cnt = 0;
  5022. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13Minor)
  5023. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5024. defined(WOLFSSL_WPAS_SMALL)
  5025. && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0
  5026. #endif
  5027. ) {
  5028. cnt++;
  5029. }
  5030. if (ssl->options.downgrade) {
  5031. #ifndef WOLFSSL_NO_TLS12
  5032. if (versionIsLessEqual(
  5033. isDtls, ssl->options.minDowngrade, tls12Minor)
  5034. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5035. defined(WOLFSSL_WPAS_SMALL)
  5036. && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0
  5037. #endif
  5038. ) {
  5039. cnt++;
  5040. }
  5041. #endif
  5042. #ifndef NO_OLD_TLS
  5043. if (versionIsLessEqual(
  5044. isDtls, ssl->options.minDowngrade, tls11Minor)
  5045. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5046. defined(WOLFSSL_WPAS_SMALL)
  5047. && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0
  5048. #endif
  5049. ) {
  5050. cnt++;
  5051. }
  5052. #ifdef WOLFSSL_ALLOW_TLSV10
  5053. if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR)
  5054. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5055. defined(WOLFSSL_WPAS_SMALL)
  5056. && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0
  5057. #endif
  5058. ) {
  5059. cnt++;
  5060. }
  5061. #endif
  5062. #endif
  5063. }
  5064. *pSz += (word16)(OPAQUE8_LEN + cnt * OPAQUE16_LEN);
  5065. }
  5066. else if (msgType == server_hello || msgType == hello_retry_request) {
  5067. *pSz += OPAQUE16_LEN;
  5068. }
  5069. else {
  5070. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5071. return SANITY_MSG_E;
  5072. }
  5073. return 0;
  5074. }
  5075. /* Writes the SupportedVersions extension into the buffer.
  5076. *
  5077. * data The SSL/TLS object.
  5078. * output The buffer to write the extension into.
  5079. * msgType The type of the message this extension is being written into.
  5080. * returns the length of data that was written.
  5081. */
  5082. static int TLSX_SupportedVersions_Write(void* data, byte* output,
  5083. byte msgType, word16* pSz)
  5084. {
  5085. WOLFSSL* ssl = (WOLFSSL*)data;
  5086. byte tls13minor, tls12minor, tls11minor, isDtls = 0;
  5087. tls13minor = (byte)TLSv1_3_MINOR;
  5088. tls12minor = (byte)TLSv1_2_MINOR;
  5089. tls11minor = (byte)TLSv1_1_MINOR;
  5090. /* unused in some configuration */
  5091. (void)tls11minor;
  5092. (void)tls12minor;
  5093. #ifdef WOLFSSL_DTLS13
  5094. if (ssl->options.dtls) {
  5095. tls13minor = (byte)DTLSv1_3_MINOR;
  5096. tls12minor = (byte)DTLSv1_2_MINOR;
  5097. tls11minor = (byte)DTLS_MINOR;
  5098. isDtls = 1;
  5099. }
  5100. #endif /* WOLFSSL_DTLS13 */
  5101. if (msgType == client_hello) {
  5102. byte major = ssl->ctx->method->version.major;
  5103. byte* cnt = output++;
  5104. *cnt = 0;
  5105. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13minor)
  5106. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5107. defined(WOLFSSL_WPAS_SMALL)
  5108. && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0
  5109. #endif
  5110. ) {
  5111. *cnt += OPAQUE16_LEN;
  5112. #ifdef WOLFSSL_TLS13_DRAFT
  5113. /* The TLS draft major number. */
  5114. *(output++) = TLS_DRAFT_MAJOR;
  5115. /* Version of draft supported. */
  5116. *(output++) = TLS_DRAFT_MINOR;
  5117. #else
  5118. *(output++) = major;
  5119. *(output++) = tls13minor;
  5120. #endif
  5121. }
  5122. if (ssl->options.downgrade) {
  5123. #ifndef WOLFSSL_NO_TLS12
  5124. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls12minor)
  5125. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5126. defined(WOLFSSL_WPAS_SMALL)
  5127. && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0
  5128. #endif
  5129. ) {
  5130. *cnt += OPAQUE16_LEN;
  5131. *(output++) = major;
  5132. *(output++) = tls12minor;
  5133. }
  5134. #endif
  5135. #ifndef NO_OLD_TLS
  5136. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls11minor)
  5137. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5138. defined(WOLFSSL_WPAS_SMALL)
  5139. && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0
  5140. #endif
  5141. ) {
  5142. *cnt += OPAQUE16_LEN;
  5143. *(output++) = major;
  5144. *(output++) = tls11minor;
  5145. }
  5146. #ifdef WOLFSSL_ALLOW_TLSV10
  5147. if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR)
  5148. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5149. defined(WOLFSSL_WPAS_SMALL)
  5150. && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0
  5151. #endif
  5152. ) {
  5153. *cnt += OPAQUE16_LEN;
  5154. *(output++) = major;
  5155. *(output++) = (byte)TLSv1_MINOR;
  5156. }
  5157. #endif
  5158. #endif
  5159. }
  5160. *pSz += (word16)(OPAQUE8_LEN + *cnt);
  5161. }
  5162. else if (msgType == server_hello || msgType == hello_retry_request) {
  5163. output[0] = ssl->version.major;
  5164. output[1] = ssl->version.minor;
  5165. *pSz += OPAQUE16_LEN;
  5166. }
  5167. else {
  5168. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5169. return SANITY_MSG_E;
  5170. }
  5171. return 0;
  5172. }
  5173. /* Parse the SupportedVersions extension.
  5174. *
  5175. * ssl The SSL/TLS object.
  5176. * input The buffer with the extension data.
  5177. * length The length of the extension data.
  5178. * msgType The type of the message this extension is being parsed from.
  5179. * pv The output ProtocolVersion for the negotiated version
  5180. * opts The output options structure. Can be NULL.
  5181. * exts The output extensions list. Can be NULL.
  5182. * returns 0 on success, otherwise failure.
  5183. */
  5184. int TLSX_SupportedVersions_Parse(const WOLFSSL* ssl, const byte* input,
  5185. word16 length, byte msgType, ProtocolVersion* pv, Options* opts,
  5186. TLSX** exts)
  5187. {
  5188. /* The client's greatest minor version that we support */
  5189. byte clientGreatestMinor = SSLv3_MINOR;
  5190. int ret;
  5191. byte major, minor;
  5192. byte tls13minor, tls12minor;
  5193. byte isDtls;
  5194. tls13minor = TLSv1_3_MINOR;
  5195. tls12minor = TLSv1_2_MINOR;
  5196. isDtls = ssl->options.dtls == 1;
  5197. #ifdef WOLFSSL_DTLS13
  5198. if (ssl->options.dtls) {
  5199. tls13minor = DTLSv1_3_MINOR;
  5200. tls12minor = DTLSv1_2_MINOR;
  5201. clientGreatestMinor = DTLS_MINOR;
  5202. }
  5203. #endif /* WOLFSSL_DTLS13 */
  5204. if (msgType == client_hello) {
  5205. int i;
  5206. int len;
  5207. int set = 0;
  5208. /* Must contain a length and at least one version. */
  5209. if (length < OPAQUE8_LEN + OPAQUE16_LEN || (length & 1) != 1)
  5210. return BUFFER_ERROR;
  5211. len = *input;
  5212. /* Protocol version array must fill rest of data. */
  5213. if (length != (word16)OPAQUE8_LEN + len)
  5214. return BUFFER_ERROR;
  5215. input++;
  5216. /* Find first match. */
  5217. for (i = 0; i < len; i += OPAQUE16_LEN) {
  5218. major = input[i];
  5219. minor = input[i + OPAQUE8_LEN];
  5220. #ifdef WOLFSSL_TLS13_DRAFT
  5221. if (major == TLS_DRAFT_MAJOR && minor == TLS_DRAFT_MINOR) {
  5222. major = SSLv3_MAJOR;
  5223. minor = TLSv1_3_MINOR;
  5224. }
  5225. #else
  5226. if (major == TLS_DRAFT_MAJOR)
  5227. continue;
  5228. #endif
  5229. if (major != ssl->ctx->method->version.major)
  5230. continue;
  5231. /* No upgrade allowed. */
  5232. if (versionIsGreater(isDtls, minor, ssl->version.minor))
  5233. continue;
  5234. /* Check downgrade. */
  5235. if (versionIsLesser(isDtls, minor, ssl->version.minor)) {
  5236. if (!ssl->options.downgrade)
  5237. continue;
  5238. if (versionIsLesser(isDtls, minor, ssl->options.minDowngrade))
  5239. continue;
  5240. }
  5241. if (versionIsGreater(isDtls, minor, clientGreatestMinor))
  5242. clientGreatestMinor = minor;
  5243. set = 1;
  5244. }
  5245. if (!set) {
  5246. /* No common supported version was negotiated */
  5247. SendAlert((WOLFSSL*)ssl, alert_fatal,
  5248. wolfssl_alert_protocol_version);
  5249. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5250. return VERSION_ERROR;
  5251. }
  5252. pv->minor = clientGreatestMinor;
  5253. if (versionIsAtLeast(isDtls, clientGreatestMinor, tls13minor)) {
  5254. if (opts != NULL)
  5255. opts->tls1_3 = 1;
  5256. /* TLS v1.3 requires supported version extension */
  5257. if (exts != NULL &&
  5258. TLSX_Find(*exts, TLSX_SUPPORTED_VERSIONS) == NULL) {
  5259. ret = TLSX_Push(exts,
  5260. TLSX_SUPPORTED_VERSIONS, ssl, ssl->heap);
  5261. if (ret != 0) {
  5262. return ret;
  5263. }
  5264. /* *exts should be pointing to the TLSX_SUPPORTED_VERSIONS
  5265. * ext in the list since it was pushed. */
  5266. (*exts)->resp = 1;
  5267. }
  5268. }
  5269. }
  5270. else if (msgType == server_hello || msgType == hello_retry_request) {
  5271. /* Must contain one version. */
  5272. if (length != OPAQUE16_LEN)
  5273. return BUFFER_ERROR;
  5274. major = input[0];
  5275. minor = input[OPAQUE8_LEN];
  5276. if (major != ssl->ctx->method->version.major) {
  5277. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5278. return VERSION_ERROR;
  5279. }
  5280. /* Can't downgrade with this extension below TLS v1.3. */
  5281. if (versionIsLesser(isDtls, minor, tls13minor)) {
  5282. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5283. return VERSION_ERROR;
  5284. }
  5285. /* Version is TLS v1.2 to handle downgrading from TLS v1.3+. */
  5286. if (ssl->options.downgrade && ssl->version.minor == tls12minor) {
  5287. /* Set minor version back to TLS v1.3+ */
  5288. pv->minor = ssl->ctx->method->version.minor;
  5289. }
  5290. /* No upgrade allowed. */
  5291. if (versionIsLesser(isDtls, ssl->version.minor, minor)) {
  5292. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5293. return VERSION_ERROR;
  5294. }
  5295. /* Check downgrade. */
  5296. if (versionIsGreater(isDtls, ssl->version.minor, minor)) {
  5297. if (!ssl->options.downgrade) {
  5298. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5299. return VERSION_ERROR;
  5300. }
  5301. if (versionIsLesser(
  5302. isDtls, minor, ssl->options.minDowngrade)) {
  5303. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5304. return VERSION_ERROR;
  5305. }
  5306. /* Downgrade the version. */
  5307. pv->minor = minor;
  5308. }
  5309. }
  5310. else {
  5311. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5312. return SANITY_MSG_E;
  5313. }
  5314. return 0;
  5315. }
  5316. /* Sets a new SupportedVersions extension into the extension list.
  5317. *
  5318. * extensions The list of extensions.
  5319. * data The extensions specific data.
  5320. * heap The heap used for allocation.
  5321. * returns 0 on success, otherwise failure.
  5322. */
  5323. static int TLSX_SetSupportedVersions(TLSX** extensions, const void* data,
  5324. void* heap)
  5325. {
  5326. if (extensions == NULL || data == NULL)
  5327. return BAD_FUNC_ARG;
  5328. return TLSX_Push(extensions, TLSX_SUPPORTED_VERSIONS, data, heap);
  5329. }
  5330. #define SV_GET_SIZE TLSX_SupportedVersions_GetSize
  5331. #define SV_WRITE TLSX_SupportedVersions_Write
  5332. #define SV_PARSE TLSX_SupportedVersions_Parse
  5333. #else
  5334. #define SV_GET_SIZE(a, b, c) 0
  5335. #define SV_WRITE(a, b, c, d) 0
  5336. #define SV_PARSE(a, b, c, d, e, f, g) 0
  5337. #endif /* WOLFSSL_TLS13 */
  5338. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  5339. /******************************************************************************/
  5340. /* Cookie */
  5341. /******************************************************************************/
  5342. /* Free the cookie data.
  5343. *
  5344. * cookie Cookie data.
  5345. * heap The heap used for allocation.
  5346. */
  5347. static void TLSX_Cookie_FreeAll(Cookie* cookie, void* heap)
  5348. {
  5349. (void)heap;
  5350. if (cookie != NULL)
  5351. XFREE(cookie, heap, DYNAMIC_TYPE_TLSX);
  5352. }
  5353. /* Get the size of the encoded Cookie extension.
  5354. * In messages: ClientHello and HelloRetryRequest.
  5355. *
  5356. * cookie The cookie to write.
  5357. * msgType The type of the message this extension is being written into.
  5358. * returns the number of bytes of the encoded Cookie extension.
  5359. */
  5360. static int TLSX_Cookie_GetSize(Cookie* cookie, byte msgType, word16* pSz)
  5361. {
  5362. if (msgType == client_hello || msgType == hello_retry_request) {
  5363. *pSz += OPAQUE16_LEN + cookie->len;
  5364. }
  5365. else {
  5366. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5367. return SANITY_MSG_E;
  5368. }
  5369. return 0;
  5370. }
  5371. /* Writes the Cookie extension into the output buffer.
  5372. * Assumes that the the output buffer is big enough to hold data.
  5373. * In messages: ClientHello and HelloRetryRequest.
  5374. *
  5375. * cookie The cookie to write.
  5376. * output The buffer to write into.
  5377. * msgType The type of the message this extension is being written into.
  5378. * returns the number of bytes written into the buffer.
  5379. */
  5380. static int TLSX_Cookie_Write(Cookie* cookie, byte* output, byte msgType,
  5381. word16* pSz)
  5382. {
  5383. if (msgType == client_hello || msgType == hello_retry_request) {
  5384. c16toa(cookie->len, output);
  5385. output += OPAQUE16_LEN;
  5386. XMEMCPY(output, cookie->data, cookie->len);
  5387. *pSz += OPAQUE16_LEN + cookie->len;
  5388. }
  5389. else {
  5390. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5391. return SANITY_MSG_E;
  5392. }
  5393. return 0;
  5394. }
  5395. /* Parse the Cookie extension.
  5396. * In messages: ClientHello and HelloRetryRequest.
  5397. *
  5398. * ssl The SSL/TLS object.
  5399. * input The extension data.
  5400. * length The length of the extension data.
  5401. * msgType The type of the message this extension is being parsed from.
  5402. * returns 0 on success and other values indicate failure.
  5403. */
  5404. static int TLSX_Cookie_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  5405. byte msgType)
  5406. {
  5407. word16 len;
  5408. word16 idx = 0;
  5409. TLSX* extension;
  5410. Cookie* cookie;
  5411. if (msgType != client_hello && msgType != hello_retry_request) {
  5412. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5413. return SANITY_MSG_E;
  5414. }
  5415. /* Message contains length and Cookie which must be at least one byte
  5416. * in length.
  5417. */
  5418. if (length < OPAQUE16_LEN + 1)
  5419. return BUFFER_E;
  5420. ato16(input + idx, &len);
  5421. idx += OPAQUE16_LEN;
  5422. if (length - idx != len)
  5423. return BUFFER_E;
  5424. if (msgType == hello_retry_request)
  5425. return TLSX_Cookie_Use(ssl, input + idx, len, NULL, 0, 0,
  5426. &ssl->extensions);
  5427. /* client_hello */
  5428. extension = TLSX_Find(ssl->extensions, TLSX_COOKIE);
  5429. if (extension == NULL) {
  5430. #ifdef WOLFSSL_DTLS13
  5431. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version))
  5432. /* Allow a cookie extension with DTLS 1.3 because it is possible
  5433. * that a different SSL instance sent the cookie but we are now
  5434. * receiving it. */
  5435. return TLSX_Cookie_Use(ssl, input + idx, len, NULL, 0, 0,
  5436. &ssl->extensions);
  5437. else
  5438. #endif
  5439. {
  5440. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  5441. return HRR_COOKIE_ERROR;
  5442. }
  5443. }
  5444. cookie = (Cookie*)extension->data;
  5445. if (cookie->len != len || XMEMCMP(cookie->data, input + idx, len) != 0) {
  5446. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  5447. return HRR_COOKIE_ERROR;
  5448. }
  5449. /* Request seen. */
  5450. extension->resp = 0;
  5451. return 0;
  5452. }
  5453. /* Use the data to create a new Cookie object in the extensions.
  5454. *
  5455. * ssl SSL/TLS object.
  5456. * data Cookie data.
  5457. * len Length of cookie data in bytes.
  5458. * mac MAC data.
  5459. * macSz Length of MAC data in bytes.
  5460. * resp Indicates the extension will go into a response (HelloRetryRequest).
  5461. * returns 0 on success and other values indicate failure.
  5462. */
  5463. int TLSX_Cookie_Use(const WOLFSSL* ssl, const byte* data, word16 len, byte* mac,
  5464. byte macSz, int resp, TLSX** exts)
  5465. {
  5466. int ret = 0;
  5467. TLSX* extension;
  5468. Cookie* cookie;
  5469. /* Find the cookie extension if it exists. */
  5470. extension = TLSX_Find(*exts, TLSX_COOKIE);
  5471. if (extension == NULL) {
  5472. /* Push new cookie extension. */
  5473. ret = TLSX_Push(exts, TLSX_COOKIE, NULL, ssl->heap);
  5474. if (ret != 0)
  5475. return ret;
  5476. extension = TLSX_Find(*exts, TLSX_COOKIE);
  5477. if (extension == NULL)
  5478. return MEMORY_E;
  5479. }
  5480. cookie = (Cookie*)XMALLOC(sizeof(Cookie) + len + macSz, ssl->heap,
  5481. DYNAMIC_TYPE_TLSX);
  5482. if (cookie == NULL)
  5483. return MEMORY_E;
  5484. cookie->len = len + macSz;
  5485. XMEMCPY(cookie->data, data, len);
  5486. if (mac != NULL)
  5487. XMEMCPY(cookie->data + len, mac, macSz);
  5488. if (extension->data != NULL)
  5489. XFREE(extension->data, ssl->heap, DYNAMIC_TYPE_TLSX);
  5490. extension->data = (void*)cookie;
  5491. extension->resp = (byte)resp;
  5492. return 0;
  5493. }
  5494. #define CKE_FREE_ALL TLSX_Cookie_FreeAll
  5495. #define CKE_GET_SIZE TLSX_Cookie_GetSize
  5496. #define CKE_WRITE TLSX_Cookie_Write
  5497. #define CKE_PARSE TLSX_Cookie_Parse
  5498. #else
  5499. #define CKE_FREE_ALL(a, b) 0
  5500. #define CKE_GET_SIZE(a, b, c) 0
  5501. #define CKE_WRITE(a, b, c, d) 0
  5502. #define CKE_PARSE(a, b, c, d) 0
  5503. #endif
  5504. #if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && \
  5505. !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA)
  5506. /* Currently only settable through compatibility API */
  5507. /******************************************************************************/
  5508. /* Certificate Authorities */
  5509. /******************************************************************************/
  5510. static word16 TLSX_CA_Names_GetSize(void* data)
  5511. {
  5512. WOLFSSL* ssl = (WOLFSSL*)data;
  5513. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  5514. word16 size = 0;
  5515. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5516. /* To add support use a different member like ssl->ca_names and
  5517. * add accessor functions:
  5518. * - *_set0_CA_list
  5519. * - *_get0_CA_list */
  5520. WOLFSSL_MSG("We don't currently support sending the client's list.");
  5521. return 0;
  5522. }
  5523. /* Length of names */
  5524. size += OPAQUE16_LEN;
  5525. for (names = SSL_CA_NAMES(ssl); names != NULL; names = names->next) {
  5526. byte seq[MAX_SEQ_SZ];
  5527. WOLFSSL_X509_NAME* name = names->data.name;
  5528. if (name != NULL) {
  5529. /* 16-bit length | SEQ | Len | DER of name */
  5530. size += (word16)(OPAQUE16_LEN + SetSequence(name->rawLen, seq) +
  5531. name->rawLen);
  5532. }
  5533. }
  5534. return size;
  5535. }
  5536. static word16 TLSX_CA_Names_Write(void* data, byte* output)
  5537. {
  5538. WOLFSSL* ssl = (WOLFSSL*)data;
  5539. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  5540. byte* len;
  5541. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5542. /* To add support use a different member like ssl->ca_names and
  5543. * add accessor functions:
  5544. * - *_set0_CA_list
  5545. * - *_get0_CA_list */
  5546. WOLFSSL_MSG("We don't currently support sending the client's list.");
  5547. return 0;
  5548. }
  5549. /* Reserve space for the length value */
  5550. len = output;
  5551. output += OPAQUE16_LEN;
  5552. for (names = SSL_CA_NAMES(ssl); names != NULL; names = names->next) {
  5553. byte seq[MAX_SEQ_SZ];
  5554. WOLFSSL_X509_NAME* name = names->data.name;
  5555. if (name != NULL) {
  5556. c16toa((word16)name->rawLen +
  5557. (word16)SetSequence(name->rawLen, seq), output);
  5558. output += OPAQUE16_LEN;
  5559. output += SetSequence(name->rawLen, output);
  5560. XMEMCPY(output, name->raw, name->rawLen);
  5561. output += name->rawLen;
  5562. }
  5563. }
  5564. /* Write the total length */
  5565. c16toa((word16)(output - len - OPAQUE16_LEN), len);
  5566. return (word16)(output - len);
  5567. }
  5568. static int TLSX_CA_Names_Parse(WOLFSSL *ssl, const byte* input,
  5569. word16 length, byte isRequest)
  5570. {
  5571. word16 extLen;
  5572. (void)isRequest;
  5573. if (ssl->options.side == WOLFSSL_SERVER_END) {
  5574. /* To add support use a different member like ssl->ca_names and
  5575. * add accessor functions:
  5576. * - *_set0_CA_list
  5577. * - *_get0_CA_list */
  5578. WOLFSSL_MSG("We don't currently support parsing the client's list.");
  5579. return 0;
  5580. }
  5581. if (ssl->client_ca_names != ssl->ctx->client_ca_names)
  5582. wolfSSL_sk_X509_NAME_pop_free(ssl->client_ca_names, NULL);
  5583. ssl->client_ca_names = wolfSSL_sk_X509_NAME_new(NULL);
  5584. if (ssl->client_ca_names == NULL)
  5585. return MEMORY_ERROR;
  5586. if (length < OPAQUE16_LEN)
  5587. return BUFFER_ERROR;
  5588. ato16(input, &extLen);
  5589. input += OPAQUE16_LEN;
  5590. length -= OPAQUE16_LEN;
  5591. if (extLen != length)
  5592. return BUFFER_ERROR;
  5593. while (length) {
  5594. word32 idx = 0;
  5595. WOLFSSL_X509_NAME* name = NULL;
  5596. int ret = 0;
  5597. int didInit = FALSE;
  5598. /* Use a DecodedCert struct to get access to GetName to
  5599. * parse DN name */
  5600. #ifdef WOLFSSL_SMALL_STACK
  5601. DecodedCert *cert = (DecodedCert *)XMALLOC(
  5602. sizeof(*cert), ssl->heap, DYNAMIC_TYPE_DCERT);
  5603. if (cert == NULL)
  5604. return MEMORY_ERROR;
  5605. #else
  5606. DecodedCert cert[1];
  5607. #endif
  5608. if (length < OPAQUE16_LEN) {
  5609. ret = BUFFER_ERROR;
  5610. }
  5611. if (ret == 0) {
  5612. ato16(input, &extLen);
  5613. idx += OPAQUE16_LEN;
  5614. if (idx + extLen > length)
  5615. ret = BUFFER_ERROR;
  5616. }
  5617. if (ret == 0) {
  5618. InitDecodedCert(cert, input + idx, extLen, ssl->heap);
  5619. didInit = TRUE;
  5620. idx += extLen;
  5621. ret = GetName(cert, SUBJECT, extLen);
  5622. }
  5623. if (ret == 0 && (name = wolfSSL_X509_NAME_new()) == NULL)
  5624. ret = MEMORY_ERROR;
  5625. if (ret == 0) {
  5626. CopyDecodedName(name, cert, SUBJECT);
  5627. if (wolfSSL_sk_X509_NAME_push(ssl->client_ca_names, name)
  5628. == WOLFSSL_FAILURE)
  5629. ret = MEMORY_ERROR;
  5630. }
  5631. if (didInit)
  5632. FreeDecodedCert(cert);
  5633. #ifdef WOLFSSL_SMALL_STACK
  5634. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  5635. #endif
  5636. if (ret != 0)
  5637. return ret;
  5638. input += idx;
  5639. length -= (word16)idx;
  5640. }
  5641. return 0;
  5642. }
  5643. #define CAN_GET_SIZE TLSX_CA_Names_GetSize
  5644. #define CAN_WRITE TLSX_CA_Names_Write
  5645. #define CAN_PARSE TLSX_CA_Names_Parse
  5646. #else
  5647. #define CAN_GET_SIZE(...) 0
  5648. #define CAN_WRITE(...) 0
  5649. #define CAN_PARSE(...) 0
  5650. #endif
  5651. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  5652. /******************************************************************************/
  5653. /* Signature Algorithms */
  5654. /******************************************************************************/
  5655. /* Return the size of the SignatureAlgorithms extension's data.
  5656. *
  5657. * data Unused
  5658. * returns the length of data that will be in the extension.
  5659. */
  5660. static word16 TLSX_SignatureAlgorithms_GetSize(void* data)
  5661. {
  5662. SignatureAlgorithms* sa = (SignatureAlgorithms*)data;
  5663. if (sa->hashSigAlgoSz == 0)
  5664. return OPAQUE16_LEN + WOLFSSL_SUITES(sa->ssl)->hashSigAlgoSz;
  5665. else
  5666. return OPAQUE16_LEN + sa->hashSigAlgoSz;
  5667. }
  5668. /* Creates a bit string of supported hash algorithms with RSA PSS.
  5669. * The bit string is used when determining which signature algorithm to use
  5670. * when creating the CertificateVerify message.
  5671. * Note: Valid data has an even length as each signature algorithm is two bytes.
  5672. *
  5673. * ssl The SSL/TLS object.
  5674. * input The buffer with the list of supported signature algorithms.
  5675. * length The length of the list in bytes.
  5676. * returns 0 on success, BUFFER_ERROR when the length is not even.
  5677. */
  5678. static int TLSX_SignatureAlgorithms_MapPss(WOLFSSL *ssl, const byte* input,
  5679. word16 length)
  5680. {
  5681. word16 i;
  5682. if ((length & 1) == 1)
  5683. return BUFFER_ERROR;
  5684. ssl->pssAlgo = 0;
  5685. for (i = 0; i < length; i += 2) {
  5686. if (input[i] == rsa_pss_sa_algo && input[i + 1] <= sha512_mac)
  5687. ssl->pssAlgo |= 1 << input[i + 1];
  5688. #ifdef WOLFSSL_TLS13
  5689. if (input[i] == rsa_pss_sa_algo && input[i + 1] >= pss_sha256 &&
  5690. input[i + 1] <= pss_sha512) {
  5691. ssl->pssAlgo |= 1 << input[i + 1];
  5692. }
  5693. #endif
  5694. }
  5695. return 0;
  5696. }
  5697. /* Writes the SignatureAlgorithms extension into the buffer.
  5698. *
  5699. * data Unused
  5700. * output The buffer to write the extension into.
  5701. * returns the length of data that was written.
  5702. */
  5703. static word16 TLSX_SignatureAlgorithms_Write(void* data, byte* output)
  5704. {
  5705. SignatureAlgorithms* sa = (SignatureAlgorithms*)data;
  5706. const Suites* suites = WOLFSSL_SUITES(sa->ssl);
  5707. word16 hashSigAlgoSz;
  5708. if (sa->hashSigAlgoSz == 0) {
  5709. c16toa(suites->hashSigAlgoSz, output);
  5710. XMEMCPY(output + OPAQUE16_LEN, suites->hashSigAlgo,
  5711. suites->hashSigAlgoSz);
  5712. hashSigAlgoSz = suites->hashSigAlgoSz;
  5713. }
  5714. else {
  5715. c16toa(sa->hashSigAlgoSz, output);
  5716. XMEMCPY(output + OPAQUE16_LEN, sa->hashSigAlgo,
  5717. sa->hashSigAlgoSz);
  5718. hashSigAlgoSz = sa->hashSigAlgoSz;
  5719. }
  5720. #ifndef NO_RSA
  5721. TLSX_SignatureAlgorithms_MapPss(sa->ssl, output + OPAQUE16_LEN,
  5722. hashSigAlgoSz);
  5723. #endif
  5724. return OPAQUE16_LEN + hashSigAlgoSz;
  5725. }
  5726. /* Parse the SignatureAlgorithms extension.
  5727. *
  5728. * ssl The SSL/TLS object.
  5729. * input The buffer with the extension data.
  5730. * length The length of the extension data.
  5731. * returns 0 on success, otherwise failure.
  5732. */
  5733. static int TLSX_SignatureAlgorithms_Parse(WOLFSSL *ssl, const byte* input,
  5734. word16 length, byte isRequest, Suites* suites)
  5735. {
  5736. word16 len;
  5737. if (!isRequest)
  5738. return BUFFER_ERROR;
  5739. /* Must contain a length and at least algorithm. */
  5740. if (length < OPAQUE16_LEN + OPAQUE16_LEN || (length & 1) != 0)
  5741. return BUFFER_ERROR;
  5742. ato16(input, &len);
  5743. input += OPAQUE16_LEN;
  5744. /* Algorithm array must fill rest of data. */
  5745. if (length != OPAQUE16_LEN + len)
  5746. return BUFFER_ERROR;
  5747. /* Sig Algo list size must be even. */
  5748. if (suites->hashSigAlgoSz % 2 != 0)
  5749. return BUFFER_ERROR;
  5750. /* truncate hashSigAlgo list if too long */
  5751. suites->hashSigAlgoSz = len;
  5752. if (suites->hashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  5753. WOLFSSL_MSG("TLSX SigAlgo list exceeds max, truncating");
  5754. suites->hashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  5755. }
  5756. XMEMCPY(suites->hashSigAlgo, input, suites->hashSigAlgoSz);
  5757. return TLSX_SignatureAlgorithms_MapPss(ssl, input, len);
  5758. }
  5759. /* Sets a new SignatureAlgorithms extension into the extension list.
  5760. *
  5761. * extensions The list of extensions.
  5762. * data The extensions specific data.
  5763. * heap The heap used for allocation.
  5764. * returns 0 on success, otherwise failure.
  5765. */
  5766. static int TLSX_SetSignatureAlgorithms(TLSX** extensions, WOLFSSL* ssl,
  5767. void* heap)
  5768. {
  5769. SignatureAlgorithms* sa;
  5770. int ret;
  5771. if (extensions == NULL)
  5772. return BAD_FUNC_ARG;
  5773. /* Already present */
  5774. if (TLSX_Find(*extensions, TLSX_SIGNATURE_ALGORITHMS) != NULL)
  5775. return 0;
  5776. sa = TLSX_SignatureAlgorithms_New(ssl, 0, heap);
  5777. if (sa == NULL)
  5778. return MEMORY_ERROR;
  5779. ret = TLSX_Push(extensions, TLSX_SIGNATURE_ALGORITHMS, sa, heap);
  5780. if (ret != 0)
  5781. TLSX_SignatureAlgorithms_FreeAll(sa, heap);
  5782. return ret;
  5783. }
  5784. SignatureAlgorithms* TLSX_SignatureAlgorithms_New(WOLFSSL* ssl,
  5785. word16 hashSigAlgoSz, void* heap)
  5786. {
  5787. SignatureAlgorithms* sa;
  5788. (void)heap;
  5789. sa = (SignatureAlgorithms*)XMALLOC(sizeof(*sa) + hashSigAlgoSz, heap,
  5790. DYNAMIC_TYPE_TLSX);
  5791. if (sa != NULL) {
  5792. XMEMSET(sa, 0, sizeof(*sa) + hashSigAlgoSz);
  5793. sa->ssl = ssl;
  5794. sa->hashSigAlgoSz = hashSigAlgoSz;
  5795. }
  5796. return sa;
  5797. }
  5798. void TLSX_SignatureAlgorithms_FreeAll(SignatureAlgorithms* sa,
  5799. void* heap)
  5800. {
  5801. XFREE(sa, heap, DYNAMIC_TYPE_TLSX);
  5802. (void)heap;
  5803. }
  5804. #define SA_GET_SIZE TLSX_SignatureAlgorithms_GetSize
  5805. #define SA_WRITE TLSX_SignatureAlgorithms_Write
  5806. #define SA_PARSE TLSX_SignatureAlgorithms_Parse
  5807. #define SA_FREE_ALL TLSX_SignatureAlgorithms_FreeAll
  5808. #endif
  5809. /******************************************************************************/
  5810. /* Signature Algorithms Certificate */
  5811. /******************************************************************************/
  5812. #if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  5813. /* Return the size of the SignatureAlgorithms extension's data.
  5814. *
  5815. * data Unused
  5816. * returns the length of data that will be in the extension.
  5817. */
  5818. static word16 TLSX_SignatureAlgorithmsCert_GetSize(void* data)
  5819. {
  5820. WOLFSSL* ssl = (WOLFSSL*)data;
  5821. return OPAQUE16_LEN + ssl->certHashSigAlgoSz;
  5822. }
  5823. /* Writes the SignatureAlgorithmsCert extension into the buffer.
  5824. *
  5825. * data Unused
  5826. * output The buffer to write the extension into.
  5827. * returns the length of data that was written.
  5828. */
  5829. static word16 TLSX_SignatureAlgorithmsCert_Write(void* data, byte* output)
  5830. {
  5831. WOLFSSL* ssl = (WOLFSSL*)data;
  5832. c16toa(ssl->certHashSigAlgoSz, output);
  5833. XMEMCPY(output + OPAQUE16_LEN, ssl->certHashSigAlgo,
  5834. ssl->certHashSigAlgoSz);
  5835. return OPAQUE16_LEN + ssl->certHashSigAlgoSz;
  5836. }
  5837. /* Parse the SignatureAlgorithmsCert extension.
  5838. *
  5839. * ssl The SSL/TLS object.
  5840. * input The buffer with the extension data.
  5841. * length The length of the extension data.
  5842. * returns 0 on success, otherwise failure.
  5843. */
  5844. static int TLSX_SignatureAlgorithmsCert_Parse(WOLFSSL *ssl, const byte* input,
  5845. word16 length, byte isRequest)
  5846. {
  5847. word16 len;
  5848. if (!isRequest)
  5849. return BUFFER_ERROR;
  5850. /* Must contain a length and at least algorithm. */
  5851. if (length < OPAQUE16_LEN + OPAQUE16_LEN || (length & 1) != 0)
  5852. return BUFFER_ERROR;
  5853. ato16(input, &len);
  5854. input += OPAQUE16_LEN;
  5855. /* Algorithm array must fill rest of data. */
  5856. if (length != OPAQUE16_LEN + len)
  5857. return BUFFER_ERROR;
  5858. /* truncate hashSigAlgo list if too long */
  5859. ssl->certHashSigAlgoSz = len;
  5860. if (ssl->certHashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  5861. WOLFSSL_MSG("TLSX SigAlgo list exceeds max, truncating");
  5862. ssl->certHashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  5863. }
  5864. XMEMCPY(ssl->certHashSigAlgo, input, ssl->certHashSigAlgoSz);
  5865. return 0;
  5866. }
  5867. /* Sets a new SignatureAlgorithmsCert extension into the extension list.
  5868. *
  5869. * extensions The list of extensions.
  5870. * data The extensions specific data.
  5871. * heap The heap used for allocation.
  5872. * returns 0 on success, otherwise failure.
  5873. */
  5874. static int TLSX_SetSignatureAlgorithmsCert(TLSX** extensions,
  5875. const WOLFSSL* data, void* heap)
  5876. {
  5877. if (extensions == NULL)
  5878. return BAD_FUNC_ARG;
  5879. return TLSX_Push(extensions, TLSX_SIGNATURE_ALGORITHMS_CERT, data, heap);
  5880. }
  5881. #define SAC_GET_SIZE TLSX_SignatureAlgorithmsCert_GetSize
  5882. #define SAC_WRITE TLSX_SignatureAlgorithmsCert_Write
  5883. #define SAC_PARSE TLSX_SignatureAlgorithmsCert_Parse
  5884. #endif /* WOLFSSL_TLS13 */
  5885. /******************************************************************************/
  5886. /* Key Share */
  5887. /******************************************************************************/
  5888. #if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
  5889. /* Create a key share entry using named Diffie-Hellman parameters group.
  5890. * Generates a key pair.
  5891. *
  5892. * ssl The SSL/TLS object.
  5893. * kse The key share entry object.
  5894. * returns 0 on success, otherwise failure.
  5895. */
  5896. static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse)
  5897. {
  5898. int ret = 0;
  5899. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  5900. word32 pSz = 0, pvtSz = 0;
  5901. DhKey* dhKey = (DhKey*)kse->key;
  5902. /* Pick the parameters from the named group. */
  5903. #ifdef HAVE_PUBLIC_FFDHE
  5904. const DhParams* params = NULL;
  5905. switch (kse->group) {
  5906. #ifdef HAVE_FFDHE_2048
  5907. case WOLFSSL_FFDHE_2048:
  5908. params = wc_Dh_ffdhe2048_Get();
  5909. pvtSz = 29;
  5910. break;
  5911. #endif
  5912. #ifdef HAVE_FFDHE_3072
  5913. case WOLFSSL_FFDHE_3072:
  5914. params = wc_Dh_ffdhe3072_Get();
  5915. pvtSz = 34;
  5916. break;
  5917. #endif
  5918. #ifdef HAVE_FFDHE_4096
  5919. case WOLFSSL_FFDHE_4096:
  5920. params = wc_Dh_ffdhe4096_Get();
  5921. pvtSz = 39;
  5922. break;
  5923. #endif
  5924. #ifdef HAVE_FFDHE_6144
  5925. case WOLFSSL_FFDHE_6144:
  5926. params = wc_Dh_ffdhe6144_Get();
  5927. pvtSz = 46;
  5928. break;
  5929. #endif
  5930. #ifdef HAVE_FFDHE_8192
  5931. case WOLFSSL_FFDHE_8192:
  5932. params = wc_Dh_ffdhe8192_Get();
  5933. pvtSz = 52;
  5934. break;
  5935. #endif
  5936. default:
  5937. break;
  5938. }
  5939. if (params == NULL)
  5940. return BAD_FUNC_ARG;
  5941. pSz = params->p_len;
  5942. #else
  5943. pvtSz = wc_DhGetNamedKeyMinSize(kse->group);
  5944. if (pvtSz == 0) {
  5945. return BAD_FUNC_ARG;
  5946. }
  5947. ret = wc_DhGetNamedKeyParamSize(kse->group, &pSz, NULL, NULL);
  5948. if (ret != 0) {
  5949. return BAD_FUNC_ARG;
  5950. }
  5951. #endif
  5952. /* Trigger Key Generation */
  5953. if (kse->pubKey == NULL || kse->privKey == NULL) {
  5954. if (kse->key == NULL) {
  5955. kse->key = (DhKey*)XMALLOC(sizeof(DhKey), ssl->heap,
  5956. DYNAMIC_TYPE_DH);
  5957. if (kse->key == NULL)
  5958. return MEMORY_E;
  5959. /* Setup Key */
  5960. ret = wc_InitDhKey_ex((DhKey*)kse->key, ssl->heap, ssl->devId);
  5961. if (ret == 0) {
  5962. dhKey = (DhKey*)kse->key;
  5963. #ifdef HAVE_PUBLIC_FFDHE
  5964. ret = wc_DhSetKey(dhKey, params->p, params->p_len, params->g,
  5965. params->g_len);
  5966. #else
  5967. ret = wc_DhSetNamedKey(dhKey, kse->group);
  5968. #endif
  5969. }
  5970. }
  5971. /* Allocate space for the private and public key */
  5972. if (ret == 0 && kse->pubKey == NULL) {
  5973. kse->pubKey = (byte*)XMALLOC(pSz, ssl->heap,
  5974. DYNAMIC_TYPE_PUBLIC_KEY);
  5975. if (kse->pubKey == NULL)
  5976. ret = MEMORY_E;
  5977. }
  5978. if (ret == 0 && kse->privKey == NULL) {
  5979. kse->privKey = (byte*)XMALLOC(pvtSz, ssl->heap,
  5980. DYNAMIC_TYPE_PRIVATE_KEY);
  5981. if (kse->privKey == NULL)
  5982. ret = MEMORY_E;
  5983. }
  5984. if (ret == 0) {
  5985. #if defined(WOLFSSL_STATIC_EPHEMERAL) && defined(WOLFSSL_DH_EXTRA)
  5986. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_DH, kse->key);
  5987. kse->pubKeyLen = pSz;
  5988. kse->keyLen = pvtSz;
  5989. if (ret == 0) {
  5990. ret = wc_DhExportKeyPair(dhKey,
  5991. (byte*)kse->privKey, &kse->keyLen, /* private */
  5992. kse->pubKey, &kse->pubKeyLen /* public */
  5993. );
  5994. }
  5995. else
  5996. #endif
  5997. {
  5998. /* Generate a new key pair */
  5999. /* For async this is called once and when event is done, the
  6000. * provided buffers will be populated.
  6001. * Final processing is zero pad below. */
  6002. kse->pubKeyLen = pSz;
  6003. kse->keyLen = pvtSz;
  6004. ret = DhGenKeyPair(ssl, dhKey,
  6005. (byte*)kse->privKey, &kse->keyLen, /* private */
  6006. kse->pubKey, &kse->pubKeyLen /* public */
  6007. );
  6008. #ifdef WOLFSSL_ASYNC_CRYPT
  6009. if (ret == WC_PENDING_E) {
  6010. return ret;
  6011. }
  6012. #endif
  6013. }
  6014. }
  6015. }
  6016. if (ret == 0) {
  6017. if (pSz != kse->pubKeyLen) {
  6018. /* Zero pad the front of the public key to match prime "p" size */
  6019. XMEMMOVE(kse->pubKey + pSz - kse->pubKeyLen, kse->pubKey,
  6020. kse->pubKeyLen);
  6021. XMEMSET(kse->pubKey, 0, pSz - kse->pubKeyLen);
  6022. kse->pubKeyLen = pSz;
  6023. }
  6024. if (pvtSz != kse->keyLen) {
  6025. /* Zero pad the front of the private key */
  6026. XMEMMOVE(kse->privKey + pvtSz - kse->keyLen, kse->privKey,
  6027. kse->keyLen);
  6028. XMEMSET(kse->privKey, 0, pvtSz - kse->keyLen);
  6029. kse->keyLen = pvtSz;
  6030. }
  6031. #ifdef WOLFSSL_DEBUG_TLS
  6032. WOLFSSL_MSG("Public DH Key");
  6033. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6034. #endif
  6035. }
  6036. /* Always release the DH key to free up memory.
  6037. * The DhKey will be setup again in TLSX_KeyShare_ProcessDh */
  6038. if (dhKey != NULL)
  6039. wc_FreeDhKey(dhKey);
  6040. if (kse->key != NULL) {
  6041. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_DH);
  6042. kse->key = NULL;
  6043. }
  6044. if (ret != 0) {
  6045. /* Cleanup on error, otherwise data owned by key share entry */
  6046. if (kse->privKey != NULL) {
  6047. XFREE(kse->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6048. kse->privKey = NULL;
  6049. }
  6050. if (kse->pubKey != NULL) {
  6051. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6052. kse->pubKey = NULL;
  6053. }
  6054. }
  6055. #else
  6056. (void)ssl;
  6057. (void)kse;
  6058. ret = NOT_COMPILED_IN;
  6059. WOLFSSL_ERROR_VERBOSE(ret);
  6060. #endif
  6061. return ret;
  6062. }
  6063. /* Create a key share entry using X25519 parameters group.
  6064. * Generates a key pair.
  6065. *
  6066. * ssl The SSL/TLS object.
  6067. * kse The key share entry object.
  6068. * returns 0 on success, otherwise failure.
  6069. */
  6070. static int TLSX_KeyShare_GenX25519Key(WOLFSSL *ssl, KeyShareEntry* kse)
  6071. {
  6072. int ret = 0;
  6073. #ifdef HAVE_CURVE25519
  6074. curve25519_key* key = (curve25519_key*)kse->key;
  6075. if (kse->key == NULL) {
  6076. /* Allocate a Curve25519 key to hold private key. */
  6077. kse->key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), ssl->heap,
  6078. DYNAMIC_TYPE_PRIVATE_KEY);
  6079. if (kse->key == NULL) {
  6080. WOLFSSL_MSG("GenX25519Key memory error");
  6081. return MEMORY_E;
  6082. }
  6083. /* Make an Curve25519 key. */
  6084. ret = wc_curve25519_init_ex((curve25519_key*)kse->key, ssl->heap,
  6085. INVALID_DEVID);
  6086. if (ret == 0) {
  6087. /* setting "key" means okay to call wc_curve25519_free */
  6088. key = (curve25519_key*)kse->key;
  6089. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6090. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE25519, kse->key);
  6091. if (ret != 0)
  6092. #endif
  6093. {
  6094. ret = wc_curve25519_make_key(ssl->rng, CURVE25519_KEYSIZE, key);
  6095. }
  6096. }
  6097. }
  6098. if (ret == 0 && kse->pubKey == NULL) {
  6099. /* Allocate space for the public key. */
  6100. kse->pubKey = (byte*)XMALLOC(CURVE25519_KEYSIZE, ssl->heap,
  6101. DYNAMIC_TYPE_PUBLIC_KEY);
  6102. if (kse->pubKey == NULL) {
  6103. WOLFSSL_MSG("GenX25519Key pub memory error");
  6104. ret = MEMORY_E;
  6105. }
  6106. }
  6107. if (ret == 0) {
  6108. /* Export Curve25519 public key. */
  6109. kse->pubKeyLen = CURVE25519_KEYSIZE;
  6110. if (wc_curve25519_export_public_ex(key, kse->pubKey, &kse->pubKeyLen,
  6111. EC25519_LITTLE_ENDIAN) != 0) {
  6112. ret = ECC_EXPORT_ERROR;
  6113. WOLFSSL_ERROR_VERBOSE(ret);
  6114. }
  6115. kse->pubKeyLen = CURVE25519_KEYSIZE; /* always CURVE25519_KEYSIZE */
  6116. }
  6117. #ifdef WOLFSSL_DEBUG_TLS
  6118. if (ret == 0) {
  6119. WOLFSSL_MSG("Public Curve25519 Key");
  6120. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6121. }
  6122. #endif
  6123. if (ret != 0) {
  6124. /* Data owned by key share entry otherwise. */
  6125. if (kse->pubKey != NULL) {
  6126. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6127. kse->pubKey = NULL;
  6128. }
  6129. if (key != NULL)
  6130. wc_curve25519_free(key);
  6131. if (kse->key != NULL) {
  6132. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6133. kse->key = NULL;
  6134. }
  6135. }
  6136. #else
  6137. (void)ssl;
  6138. (void)kse;
  6139. ret = NOT_COMPILED_IN;
  6140. WOLFSSL_ERROR_VERBOSE(ret);
  6141. #endif /* HAVE_CURVE25519 */
  6142. return ret;
  6143. }
  6144. /* Create a key share entry using X448 parameters group.
  6145. * Generates a key pair.
  6146. *
  6147. * ssl The SSL/TLS object.
  6148. * kse The key share entry object.
  6149. * returns 0 on success, otherwise failure.
  6150. */
  6151. static int TLSX_KeyShare_GenX448Key(WOLFSSL *ssl, KeyShareEntry* kse)
  6152. {
  6153. int ret = 0;
  6154. #ifdef HAVE_CURVE448
  6155. curve448_key* key = (curve448_key*)kse->key;
  6156. if (kse->key == NULL) {
  6157. /* Allocate a Curve448 key to hold private key. */
  6158. kse->key = (curve448_key*)XMALLOC(sizeof(curve448_key), ssl->heap,
  6159. DYNAMIC_TYPE_PRIVATE_KEY);
  6160. if (kse->key == NULL) {
  6161. WOLFSSL_MSG("GenX448Key memory error");
  6162. return MEMORY_E;
  6163. }
  6164. /* Make an Curve448 key. */
  6165. ret = wc_curve448_init((curve448_key*)kse->key);
  6166. if (ret == 0) {
  6167. key = (curve448_key*)kse->key;
  6168. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6169. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE448, kse->key);
  6170. if (ret != 0)
  6171. #endif
  6172. {
  6173. ret = wc_curve448_make_key(ssl->rng, CURVE448_KEY_SIZE, key);
  6174. }
  6175. }
  6176. }
  6177. if (ret == 0 && kse->pubKey == NULL) {
  6178. /* Allocate space for the public key. */
  6179. kse->pubKey = (byte*)XMALLOC(CURVE448_KEY_SIZE, ssl->heap,
  6180. DYNAMIC_TYPE_PUBLIC_KEY);
  6181. if (kse->pubKey == NULL) {
  6182. WOLFSSL_MSG("GenX448Key pub memory error");
  6183. ret = MEMORY_E;
  6184. }
  6185. }
  6186. if (ret == 0) {
  6187. /* Export Curve448 public key. */
  6188. kse->pubKeyLen = CURVE448_KEY_SIZE;
  6189. if (wc_curve448_export_public_ex(key, kse->pubKey, &kse->pubKeyLen,
  6190. EC448_LITTLE_ENDIAN) != 0) {
  6191. ret = ECC_EXPORT_ERROR;
  6192. }
  6193. kse->pubKeyLen = CURVE448_KEY_SIZE; /* always CURVE448_KEY_SIZE */
  6194. }
  6195. #ifdef WOLFSSL_DEBUG_TLS
  6196. if (ret == 0) {
  6197. WOLFSSL_MSG("Public Curve448 Key");
  6198. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6199. }
  6200. #endif
  6201. if (ret != 0) {
  6202. /* Data owned by key share entry otherwise. */
  6203. if (kse->pubKey != NULL) {
  6204. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6205. kse->pubKey = NULL;
  6206. }
  6207. if (key != NULL)
  6208. wc_curve448_free(key);
  6209. if (kse->key != NULL) {
  6210. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6211. kse->key = NULL;
  6212. }
  6213. }
  6214. #else
  6215. (void)ssl;
  6216. (void)kse;
  6217. ret = NOT_COMPILED_IN;
  6218. WOLFSSL_ERROR_VERBOSE(ret);
  6219. #endif /* HAVE_CURVE448 */
  6220. return ret;
  6221. }
  6222. /* Create a key share entry using named elliptic curve parameters group.
  6223. * Generates a key pair.
  6224. *
  6225. * ssl The SSL/TLS object.
  6226. * kse The key share entry object.
  6227. * returns 0 on success, otherwise failure.
  6228. */
  6229. static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse)
  6230. {
  6231. int ret = 0;
  6232. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  6233. word32 keySize = 0;
  6234. word16 curveId = (word16) ECC_CURVE_INVALID;
  6235. ecc_key* eccKey = (ecc_key*)kse->key;
  6236. /* TODO: [TLS13] Get key sizes using wc_ecc_get_curve_size_from_id. */
  6237. /* Translate named group to a curve id. */
  6238. switch (kse->group) {
  6239. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  6240. #ifndef NO_ECC_SECP
  6241. case WOLFSSL_ECC_SECP256R1:
  6242. curveId = ECC_SECP256R1;
  6243. keySize = 32;
  6244. break;
  6245. #endif /* !NO_ECC_SECP */
  6246. #ifdef WOLFSSL_SM2
  6247. case WOLFSSL_ECC_SM2P256V1:
  6248. curveId = ECC_SM2P256V1;
  6249. keySize = 32;
  6250. break;
  6251. #endif /* !NO_ECC_SECP */
  6252. #endif
  6253. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  6254. #ifndef NO_ECC_SECP
  6255. case WOLFSSL_ECC_SECP384R1:
  6256. curveId = ECC_SECP384R1;
  6257. keySize = 48;
  6258. break;
  6259. #endif /* !NO_ECC_SECP */
  6260. #endif
  6261. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  6262. #ifndef NO_ECC_SECP
  6263. case WOLFSSL_ECC_SECP521R1:
  6264. curveId = ECC_SECP521R1;
  6265. keySize = 66;
  6266. break;
  6267. #endif /* !NO_ECC_SECP */
  6268. #endif
  6269. default:
  6270. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  6271. return BAD_FUNC_ARG;
  6272. }
  6273. if (kse->key == NULL) {
  6274. /* Allocate an ECC key to hold private key. */
  6275. kse->key = (byte*)XMALLOC(sizeof(ecc_key), ssl->heap, DYNAMIC_TYPE_ECC);
  6276. if (kse->key == NULL) {
  6277. WOLFSSL_MSG("EccTempKey Memory error");
  6278. return MEMORY_E;
  6279. }
  6280. /* Initialize an ECC key struct for the ephemeral key */
  6281. ret = wc_ecc_init_ex((ecc_key*)kse->key, ssl->heap, ssl->devId);
  6282. if (ret == 0) {
  6283. kse->keyLen = keySize;
  6284. kse->pubKeyLen = keySize * 2 + 1;
  6285. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  6286. ret = tsip_Tls13GenEccKeyPair(ssl, kse);
  6287. if (ret != CRYPTOCB_UNAVAILABLE) {
  6288. return ret;
  6289. }
  6290. #endif
  6291. /* setting eccKey means okay to call wc_ecc_free */
  6292. eccKey = (ecc_key*)kse->key;
  6293. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6294. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_ECDH, kse->key);
  6295. if (ret != 0)
  6296. #endif
  6297. {
  6298. /* set curve info for EccMakeKey "peer" info */
  6299. ret = wc_ecc_set_curve(eccKey, kse->keyLen, curveId);
  6300. if (ret == 0) {
  6301. #ifdef WOLFSSL_ASYNC_CRYPT
  6302. /* Detect when private key generation is done */
  6303. if (ssl->error == WC_PENDING_E &&
  6304. eccKey->type == ECC_PRIVATEKEY) {
  6305. ret = 0; /* ECC Key Generation is done */
  6306. }
  6307. else
  6308. #endif
  6309. {
  6310. /* Generate ephemeral ECC key */
  6311. /* For async this is called once and when event is done, the
  6312. * provided buffers in key be populated.
  6313. * Final processing is x963 key export below. */
  6314. ret = EccMakeKey(ssl, eccKey, eccKey);
  6315. }
  6316. }
  6317. #ifdef WOLFSSL_ASYNC_CRYPT
  6318. if (ret == WC_PENDING_E)
  6319. return ret;
  6320. #endif
  6321. }
  6322. }
  6323. }
  6324. if (ret == 0 && kse->pubKey == NULL) {
  6325. /* Allocate space for the public key */
  6326. kse->pubKey = (byte*)XMALLOC(kse->pubKeyLen, ssl->heap,
  6327. DYNAMIC_TYPE_PUBLIC_KEY);
  6328. if (kse->pubKey == NULL) {
  6329. WOLFSSL_MSG("Key data Memory error");
  6330. ret = MEMORY_E;
  6331. }
  6332. }
  6333. if (ret == 0) {
  6334. XMEMSET(kse->pubKey, 0, kse->pubKeyLen);
  6335. /* Export public key. */
  6336. PRIVATE_KEY_UNLOCK();
  6337. if (wc_ecc_export_x963(eccKey, kse->pubKey, &kse->pubKeyLen) != 0) {
  6338. ret = ECC_EXPORT_ERROR;
  6339. WOLFSSL_ERROR_VERBOSE(ret);
  6340. }
  6341. PRIVATE_KEY_LOCK();
  6342. }
  6343. #ifdef WOLFSSL_DEBUG_TLS
  6344. if (ret == 0) {
  6345. WOLFSSL_MSG("Public ECC Key");
  6346. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6347. }
  6348. #endif
  6349. if (ret != 0) {
  6350. /* Cleanup on error, otherwise data owned by key share entry */
  6351. if (kse->pubKey != NULL) {
  6352. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6353. kse->pubKey = NULL;
  6354. }
  6355. if (eccKey != NULL)
  6356. wc_ecc_free(eccKey);
  6357. if (kse->key != NULL) {
  6358. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6359. kse->key = NULL;
  6360. }
  6361. }
  6362. #else
  6363. (void)ssl;
  6364. (void)kse;
  6365. ret = NOT_COMPILED_IN;
  6366. WOLFSSL_ERROR_VERBOSE(ret);
  6367. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  6368. return ret;
  6369. }
  6370. #ifdef HAVE_PQC
  6371. static int kyber_id2type(int id, int *type)
  6372. {
  6373. int ret = 0;
  6374. switch (id) {
  6375. #ifdef WOLFSSL_KYBER512
  6376. case WOLFSSL_KYBER_LEVEL1:
  6377. *type = KYBER512;
  6378. break;
  6379. #endif
  6380. #ifdef WOLFSSL_KYBER768
  6381. case WOLFSSL_KYBER_LEVEL3:
  6382. *type = KYBER768;
  6383. break;
  6384. #endif
  6385. #ifdef WOLFSSL_KYBER1024
  6386. case WOLFSSL_KYBER_LEVEL5:
  6387. *type = KYBER1024;
  6388. break;
  6389. #endif
  6390. default:
  6391. ret = NOT_COMPILED_IN;
  6392. break;
  6393. }
  6394. return ret;
  6395. }
  6396. typedef struct PqcHybridMapping {
  6397. int hybrid;
  6398. int ecc;
  6399. int pqc;
  6400. } PqcHybridMapping;
  6401. static const PqcHybridMapping pqc_hybrid_mapping[] = {
  6402. {.hybrid = WOLFSSL_P256_KYBER_LEVEL1, .ecc = WOLFSSL_ECC_SECP256R1,
  6403. .pqc = WOLFSSL_KYBER_LEVEL1},
  6404. {.hybrid = WOLFSSL_P384_KYBER_LEVEL3, .ecc = WOLFSSL_ECC_SECP384R1,
  6405. .pqc = WOLFSSL_KYBER_LEVEL3},
  6406. {.hybrid = WOLFSSL_P521_KYBER_LEVEL5, .ecc = WOLFSSL_ECC_SECP521R1,
  6407. .pqc = WOLFSSL_KYBER_LEVEL5},
  6408. {.hybrid = 0, .ecc = 0, .pqc = 0}
  6409. };
  6410. /* This will map an ecc-pqs hybrid group into its ecc group and pqc kem group.
  6411. * If it cannot find a mapping then *pqc is set to group. ecc is optional. */
  6412. static void findEccPqc(int *ecc, int *pqc, int group)
  6413. {
  6414. int i;
  6415. if (pqc == NULL) {
  6416. return;
  6417. }
  6418. *pqc = 0;
  6419. if (ecc != NULL) {
  6420. *ecc = 0;
  6421. }
  6422. for (i = 0; pqc_hybrid_mapping[i].hybrid != 0; i++) {
  6423. if (pqc_hybrid_mapping[i].hybrid == group) {
  6424. *pqc = pqc_hybrid_mapping[i].pqc;
  6425. if (ecc != NULL) {
  6426. *ecc = pqc_hybrid_mapping[i].ecc;
  6427. }
  6428. break;
  6429. }
  6430. }
  6431. if (*pqc == 0) {
  6432. /* It is not a hybrid, so maybe its simple. */
  6433. *pqc = group;
  6434. }
  6435. }
  6436. /* Create a key share entry using liboqs parameters group.
  6437. * Generates a key pair.
  6438. *
  6439. * ssl The SSL/TLS object.
  6440. * kse The key share entry object.
  6441. * returns 0 on success, otherwise failure.
  6442. */
  6443. static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse)
  6444. {
  6445. int ret = 0;
  6446. int type = 0;
  6447. KyberKey kem[1];
  6448. byte* pubKey = NULL;
  6449. byte* privKey = NULL;
  6450. KeyShareEntry *ecc_kse = NULL;
  6451. int oqs_group = 0;
  6452. int ecc_group = 0;
  6453. word32 privSz = 0;
  6454. word32 pubSz = 0;
  6455. findEccPqc(&ecc_group, &oqs_group, kse->group);
  6456. ret = kyber_id2type(oqs_group, &type);
  6457. if (ret == NOT_COMPILED_IN) {
  6458. WOLFSSL_MSG("Invalid Kyber algorithm specified.");
  6459. ret = BAD_FUNC_ARG;
  6460. }
  6461. if (ret == 0) {
  6462. ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId);
  6463. if (ret != 0) {
  6464. WOLFSSL_MSG("Failed to initialize Kyber Key.");
  6465. }
  6466. }
  6467. if (ret == 0) {
  6468. ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap,
  6469. DYNAMIC_TYPE_TLSX);
  6470. if (ecc_kse == NULL) {
  6471. WOLFSSL_MSG("ecc_kse memory allocation failure");
  6472. ret = MEMORY_ERROR;
  6473. }
  6474. }
  6475. if (ret == 0) {
  6476. XMEMSET(ecc_kse, 0, sizeof(*ecc_kse));
  6477. ret = wc_KyberKey_PrivateKeySize(kem, &privSz);
  6478. }
  6479. if (ret == 0) {
  6480. ret = wc_KyberKey_PublicKeySize(kem, &pubSz);
  6481. }
  6482. if (ret == 0 && ecc_group != 0) {
  6483. ecc_kse->group = ecc_group;
  6484. ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse);
  6485. /* If fail, no error message, TLSX_KeyShare_GenEccKey will do it. */
  6486. }
  6487. if (ret == 0) {
  6488. pubKey = (byte*)XMALLOC(ecc_kse->pubKeyLen + pubSz, ssl->heap,
  6489. DYNAMIC_TYPE_PUBLIC_KEY);
  6490. if (pubKey == NULL) {
  6491. WOLFSSL_MSG("pubkey memory allocation failure");
  6492. ret = MEMORY_ERROR;
  6493. }
  6494. }
  6495. if (ret == 0) {
  6496. privKey = (byte*)XMALLOC(privSz, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6497. if (privKey == NULL) {
  6498. WOLFSSL_MSG("privkey memory allocation failure");
  6499. ret = MEMORY_ERROR;
  6500. }
  6501. }
  6502. if (ret == 0) {
  6503. ret = wc_KyberKey_MakeKey(kem, ssl->rng);
  6504. if (ret != 0) {
  6505. WOLFSSL_MSG("Kyber keygen failure");
  6506. }
  6507. }
  6508. if (ret == 0) {
  6509. ret = wc_KyberKey_EncodePublicKey(kem, pubKey + ecc_kse->pubKeyLen,
  6510. pubSz);
  6511. }
  6512. if (ret == 0) {
  6513. ret = wc_KyberKey_EncodePrivateKey(kem, privKey, privSz);
  6514. }
  6515. if (ret == 0) {
  6516. XMEMCPY(pubKey, ecc_kse->pubKey, ecc_kse->pubKeyLen);
  6517. kse->pubKey = pubKey;
  6518. kse->pubKeyLen = ecc_kse->pubKeyLen + pubSz;
  6519. pubKey = NULL;
  6520. /* Note we are saving the OQS private key and ECC private key
  6521. * separately. That's because the ECC private key is not simply a
  6522. * buffer. Its is an ecc_key struct.
  6523. */
  6524. kse->privKey = privKey;
  6525. privKey = NULL;
  6526. kse->key = ecc_kse->key;
  6527. ecc_kse->key = NULL;
  6528. }
  6529. #ifdef WOLFSSL_DEBUG_TLS
  6530. WOLFSSL_MSG("Public Kyber Key");
  6531. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen );
  6532. #endif
  6533. wc_KyberKey_Free(kem);
  6534. TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap);
  6535. if (pubKey != NULL)
  6536. XFREE(pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6537. if (privKey != NULL)
  6538. XFREE(privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6539. return ret;
  6540. }
  6541. #endif /* HAVE_PQC */
  6542. /* Generate a secret/key using the key share entry.
  6543. *
  6544. * ssl The SSL/TLS object.
  6545. * kse The key share entry holding peer data.
  6546. */
  6547. int TLSX_KeyShare_GenKey(WOLFSSL *ssl, KeyShareEntry *kse)
  6548. {
  6549. int ret;
  6550. /* Named FFDHE groups have a bit set to identify them. */
  6551. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(kse->group))
  6552. ret = TLSX_KeyShare_GenDhKey(ssl, kse);
  6553. else if (kse->group == WOLFSSL_ECC_X25519)
  6554. ret = TLSX_KeyShare_GenX25519Key(ssl, kse);
  6555. else if (kse->group == WOLFSSL_ECC_X448)
  6556. ret = TLSX_KeyShare_GenX448Key(ssl, kse);
  6557. #ifdef HAVE_PQC
  6558. else if (WOLFSSL_NAMED_GROUP_IS_PQC(kse->group))
  6559. ret = TLSX_KeyShare_GenPqcKey(ssl, kse);
  6560. #endif
  6561. else
  6562. ret = TLSX_KeyShare_GenEccKey(ssl, kse);
  6563. #ifdef WOLFSSL_ASYNC_CRYPT
  6564. kse->lastRet = ret;
  6565. #endif
  6566. return ret;
  6567. }
  6568. /* Free the key share dynamic data.
  6569. *
  6570. * list The linked list of key share entry objects.
  6571. * heap The heap used for allocation.
  6572. */
  6573. static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap)
  6574. {
  6575. KeyShareEntry* current;
  6576. while ((current = list) != NULL) {
  6577. list = current->next;
  6578. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(current->group)) {
  6579. #ifndef NO_DH
  6580. wc_FreeDhKey((DhKey*)current->key);
  6581. #endif
  6582. }
  6583. else if (current->group == WOLFSSL_ECC_X25519) {
  6584. #ifdef HAVE_CURVE25519
  6585. wc_curve25519_free((curve25519_key*)current->key);
  6586. #endif
  6587. }
  6588. else if (current->group == WOLFSSL_ECC_X448) {
  6589. #ifdef HAVE_CURVE448
  6590. wc_curve448_free((curve448_key*)current->key);
  6591. #endif
  6592. }
  6593. #ifdef HAVE_PQC
  6594. else if (WOLFSSL_NAMED_GROUP_IS_PQC(current->group) &&
  6595. current->key != NULL) {
  6596. ForceZero((byte*)current->key, current->keyLen);
  6597. }
  6598. #endif
  6599. else {
  6600. #ifdef HAVE_ECC
  6601. wc_ecc_free((ecc_key*)current->key);
  6602. #endif
  6603. }
  6604. XFREE(current->key, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6605. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  6606. XFREE(current->privKey, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6607. #endif
  6608. XFREE(current->pubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6609. XFREE(current->ke, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6610. XFREE(current, heap, DYNAMIC_TYPE_TLSX);
  6611. }
  6612. (void)heap;
  6613. }
  6614. /* Get the size of the encoded key share extension.
  6615. *
  6616. * list The linked list of key share extensions.
  6617. * msgType The type of the message this extension is being written into.
  6618. * returns the number of bytes of the encoded key share extension.
  6619. */
  6620. static word16 TLSX_KeyShare_GetSize(KeyShareEntry* list, byte msgType)
  6621. {
  6622. word16 len = 0;
  6623. byte isRequest = (msgType == client_hello);
  6624. KeyShareEntry* current;
  6625. /* The named group the server wants to use. */
  6626. if (msgType == hello_retry_request)
  6627. return OPAQUE16_LEN;
  6628. /* List of key exchange groups. */
  6629. if (isRequest)
  6630. len += OPAQUE16_LEN;
  6631. while ((current = list) != NULL) {
  6632. list = current->next;
  6633. if (!isRequest && current->pubKey == NULL)
  6634. continue;
  6635. len += (word16)(KE_GROUP_LEN + OPAQUE16_LEN + current->pubKeyLen);
  6636. }
  6637. return len;
  6638. }
  6639. /* Writes the key share extension into the output buffer.
  6640. * Assumes that the the output buffer is big enough to hold data.
  6641. *
  6642. * list The linked list of key share entries.
  6643. * output The buffer to write into.
  6644. * msgType The type of the message this extension is being written into.
  6645. * returns the number of bytes written into the buffer.
  6646. */
  6647. static word16 TLSX_KeyShare_Write(KeyShareEntry* list, byte* output,
  6648. byte msgType)
  6649. {
  6650. word16 i = 0;
  6651. byte isRequest = (msgType == client_hello);
  6652. KeyShareEntry* current;
  6653. if (msgType == hello_retry_request) {
  6654. c16toa(list->group, output);
  6655. return OPAQUE16_LEN;
  6656. }
  6657. /* ClientHello has a list but ServerHello is only the chosen. */
  6658. if (isRequest)
  6659. i += OPAQUE16_LEN;
  6660. /* Write out all in the list. */
  6661. while ((current = list) != NULL) {
  6662. list = current->next;
  6663. if (!isRequest && current->pubKey == NULL)
  6664. continue;
  6665. c16toa(current->group, &output[i]);
  6666. i += KE_GROUP_LEN;
  6667. c16toa((word16)(current->pubKeyLen), &output[i]);
  6668. i += OPAQUE16_LEN;
  6669. XMEMCPY(&output[i], current->pubKey, current->pubKeyLen);
  6670. i += (word16)current->pubKeyLen;
  6671. }
  6672. /* Write the length of the list if required. */
  6673. if (isRequest)
  6674. c16toa(i - OPAQUE16_LEN, output);
  6675. return i;
  6676. }
  6677. /* Process the DH key share extension on the client side.
  6678. *
  6679. * ssl The SSL/TLS object.
  6680. * keyShareEntry The key share entry object to use to calculate shared secret.
  6681. * returns 0 on success and other values indicate failure.
  6682. */
  6683. static int TLSX_KeyShare_ProcessDh(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6684. {
  6685. int ret = 0;
  6686. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  6687. word32 pSz = 0;
  6688. DhKey* dhKey = (DhKey*)keyShareEntry->key;
  6689. #ifdef HAVE_PUBLIC_FFDHE
  6690. const DhParams* params = NULL;
  6691. switch (keyShareEntry->group) {
  6692. #ifdef HAVE_FFDHE_2048
  6693. case WOLFSSL_FFDHE_2048:
  6694. params = wc_Dh_ffdhe2048_Get();
  6695. break;
  6696. #endif
  6697. #ifdef HAVE_FFDHE_3072
  6698. case WOLFSSL_FFDHE_3072:
  6699. params = wc_Dh_ffdhe3072_Get();
  6700. break;
  6701. #endif
  6702. #ifdef HAVE_FFDHE_4096
  6703. case WOLFSSL_FFDHE_4096:
  6704. params = wc_Dh_ffdhe4096_Get();
  6705. break;
  6706. #endif
  6707. #ifdef HAVE_FFDHE_6144
  6708. case WOLFSSL_FFDHE_6144:
  6709. params = wc_Dh_ffdhe6144_Get();
  6710. break;
  6711. #endif
  6712. #ifdef HAVE_FFDHE_8192
  6713. case WOLFSSL_FFDHE_8192:
  6714. params = wc_Dh_ffdhe8192_Get();
  6715. break;
  6716. #endif
  6717. default:
  6718. break;
  6719. }
  6720. if (params == NULL) {
  6721. WOLFSSL_ERROR_VERBOSE(PEER_KEY_ERROR);
  6722. return PEER_KEY_ERROR;
  6723. }
  6724. pSz = params->p_len;
  6725. #else
  6726. ret = wc_DhGetNamedKeyParamSize(keyShareEntry->group, &pSz, NULL, NULL);
  6727. if (ret != 0 || pSz == 0) {
  6728. WOLFSSL_ERROR_VERBOSE(PEER_KEY_ERROR);
  6729. return PEER_KEY_ERROR;
  6730. }
  6731. #endif
  6732. /* if DhKey is not setup, do it now */
  6733. if (keyShareEntry->key == NULL) {
  6734. keyShareEntry->key = (DhKey*)XMALLOC(sizeof(DhKey), ssl->heap,
  6735. DYNAMIC_TYPE_DH);
  6736. if (keyShareEntry->key == NULL)
  6737. return MEMORY_E;
  6738. /* Setup Key */
  6739. ret = wc_InitDhKey_ex((DhKey*)keyShareEntry->key, ssl->heap, ssl->devId);
  6740. if (ret == 0) {
  6741. dhKey = (DhKey*)keyShareEntry->key;
  6742. /* Set key */
  6743. #ifdef HAVE_PUBLIC_FFDHE
  6744. ret = wc_DhSetKey(dhKey, params->p, params->p_len, params->g,
  6745. params->g_len);
  6746. #else
  6747. ret = wc_DhSetNamedKey(dhKey, keyShareEntry->group);
  6748. #endif
  6749. }
  6750. }
  6751. if (ret == 0
  6752. #ifdef WOLFSSL_ASYNC_CRYPT
  6753. && keyShareEntry->lastRet == 0 /* don't enter here if WC_PENDING_E */
  6754. #endif
  6755. ) {
  6756. #ifdef WOLFSSL_DEBUG_TLS
  6757. WOLFSSL_MSG("Peer DH Key");
  6758. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6759. #endif
  6760. ssl->options.dhKeySz = (word16)pSz;
  6761. /* Derive secret from private key and peer's public key. */
  6762. ret = DhAgree(ssl, dhKey,
  6763. (const byte*)keyShareEntry->privKey, keyShareEntry->keyLen, /* our private */
  6764. keyShareEntry->ke, keyShareEntry->keLen, /* peer's public key */
  6765. ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz, /* secret */
  6766. NULL, 0
  6767. );
  6768. #ifdef WOLFSSL_ASYNC_CRYPT
  6769. if (ret == WC_PENDING_E) {
  6770. return ret;
  6771. }
  6772. #endif
  6773. }
  6774. /* RFC 8446 Section 7.4.1:
  6775. * ... left-padded with zeros up to the size of the prime. ...
  6776. */
  6777. if (ret == 0 && (word32)ssl->options.dhKeySz > ssl->arrays->preMasterSz) {
  6778. word32 diff = (word32)ssl->options.dhKeySz - ssl->arrays->preMasterSz;
  6779. XMEMMOVE(ssl->arrays->preMasterSecret + diff,
  6780. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  6781. XMEMSET(ssl->arrays->preMasterSecret, 0, diff);
  6782. ssl->arrays->preMasterSz = ssl->options.dhKeySz;
  6783. }
  6784. /* done with key share, release resources */
  6785. if (dhKey)
  6786. wc_FreeDhKey(dhKey);
  6787. if (keyShareEntry->key) {
  6788. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_DH);
  6789. keyShareEntry->key = NULL;
  6790. }
  6791. if (keyShareEntry->privKey != NULL) {
  6792. XFREE(keyShareEntry->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6793. keyShareEntry->privKey = NULL;
  6794. }
  6795. if (keyShareEntry->pubKey != NULL) {
  6796. XFREE(keyShareEntry->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6797. keyShareEntry->pubKey = NULL;
  6798. }
  6799. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6800. keyShareEntry->ke = NULL;
  6801. #else
  6802. (void)ssl;
  6803. (void)keyShareEntry;
  6804. ret = PEER_KEY_ERROR;
  6805. WOLFSSL_ERROR_VERBOSE(ret);
  6806. #endif
  6807. return ret;
  6808. }
  6809. /* Process the X25519 key share extension on the client side.
  6810. *
  6811. * ssl The SSL/TLS object.
  6812. * keyShareEntry The key share entry object to use to calculate shared secret.
  6813. * returns 0 on success and other values indicate failure.
  6814. */
  6815. static int TLSX_KeyShare_ProcessX25519(WOLFSSL* ssl,
  6816. KeyShareEntry* keyShareEntry)
  6817. {
  6818. int ret;
  6819. #ifdef HAVE_CURVE25519
  6820. curve25519_key* key = (curve25519_key*)keyShareEntry->key;
  6821. curve25519_key* peerX25519Key;
  6822. #ifdef HAVE_ECC
  6823. if (ssl->peerEccKey != NULL) {
  6824. wc_ecc_free(ssl->peerEccKey);
  6825. ssl->peerEccKey = NULL;
  6826. ssl->peerEccKeyPresent = 0;
  6827. }
  6828. #endif
  6829. peerX25519Key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), ssl->heap,
  6830. DYNAMIC_TYPE_TLSX);
  6831. if (peerX25519Key == NULL) {
  6832. WOLFSSL_MSG("PeerEccKey Memory error");
  6833. return MEMORY_ERROR;
  6834. }
  6835. ret = wc_curve25519_init(peerX25519Key);
  6836. if (ret != 0) {
  6837. XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6838. return ret;
  6839. }
  6840. #ifdef WOLFSSL_DEBUG_TLS
  6841. WOLFSSL_MSG("Peer Curve25519 Key");
  6842. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6843. #endif
  6844. if (wc_curve25519_check_public(keyShareEntry->ke, keyShareEntry->keLen,
  6845. EC25519_LITTLE_ENDIAN) != 0) {
  6846. ret = ECC_PEERKEY_ERROR;
  6847. WOLFSSL_ERROR_VERBOSE(ret);
  6848. }
  6849. if (ret == 0) {
  6850. if (wc_curve25519_import_public_ex(keyShareEntry->ke,
  6851. keyShareEntry->keLen, peerX25519Key,
  6852. EC25519_LITTLE_ENDIAN) != 0) {
  6853. ret = ECC_PEERKEY_ERROR;
  6854. WOLFSSL_ERROR_VERBOSE(ret);
  6855. }
  6856. }
  6857. if (ret == 0) {
  6858. ssl->ecdhCurveOID = ECC_X25519_OID;
  6859. ret = wc_curve25519_shared_secret_ex(key, peerX25519Key,
  6860. ssl->arrays->preMasterSecret,
  6861. &ssl->arrays->preMasterSz,
  6862. EC25519_LITTLE_ENDIAN);
  6863. }
  6864. wc_curve25519_free(peerX25519Key);
  6865. XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6866. wc_curve25519_free((curve25519_key*)keyShareEntry->key);
  6867. if (keyShareEntry->key != NULL) {
  6868. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6869. keyShareEntry->key = NULL;
  6870. }
  6871. #else
  6872. (void)ssl;
  6873. (void)keyShareEntry;
  6874. ret = PEER_KEY_ERROR;
  6875. WOLFSSL_ERROR_VERBOSE(ret);
  6876. #endif /* HAVE_CURVE25519 */
  6877. return ret;
  6878. }
  6879. /* Process the X448 key share extension on the client side.
  6880. *
  6881. * ssl The SSL/TLS object.
  6882. * keyShareEntry The key share entry object to use to calculate shared secret.
  6883. * returns 0 on success and other values indicate failure.
  6884. */
  6885. static int TLSX_KeyShare_ProcessX448(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6886. {
  6887. int ret;
  6888. #ifdef HAVE_CURVE448
  6889. curve448_key* key = (curve448_key*)keyShareEntry->key;
  6890. curve448_key* peerX448Key;
  6891. #ifdef HAVE_ECC
  6892. if (ssl->peerEccKey != NULL) {
  6893. wc_ecc_free(ssl->peerEccKey);
  6894. ssl->peerEccKey = NULL;
  6895. ssl->peerEccKeyPresent = 0;
  6896. }
  6897. #endif
  6898. peerX448Key = (curve448_key*)XMALLOC(sizeof(curve448_key), ssl->heap,
  6899. DYNAMIC_TYPE_TLSX);
  6900. if (peerX448Key == NULL) {
  6901. WOLFSSL_MSG("PeerEccKey Memory error");
  6902. return MEMORY_ERROR;
  6903. }
  6904. ret = wc_curve448_init(peerX448Key);
  6905. if (ret != 0) {
  6906. XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6907. return ret;
  6908. }
  6909. #ifdef WOLFSSL_DEBUG_TLS
  6910. WOLFSSL_MSG("Peer Curve448 Key");
  6911. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6912. #endif
  6913. if (wc_curve448_check_public(keyShareEntry->ke, keyShareEntry->keLen,
  6914. EC448_LITTLE_ENDIAN) != 0) {
  6915. ret = ECC_PEERKEY_ERROR;
  6916. WOLFSSL_ERROR_VERBOSE(ret);
  6917. }
  6918. if (ret == 0) {
  6919. if (wc_curve448_import_public_ex(keyShareEntry->ke,
  6920. keyShareEntry->keLen, peerX448Key,
  6921. EC448_LITTLE_ENDIAN) != 0) {
  6922. ret = ECC_PEERKEY_ERROR;
  6923. WOLFSSL_ERROR_VERBOSE(ret);
  6924. }
  6925. }
  6926. if (ret == 0) {
  6927. ssl->ecdhCurveOID = ECC_X448_OID;
  6928. ret = wc_curve448_shared_secret_ex(key, peerX448Key,
  6929. ssl->arrays->preMasterSecret,
  6930. &ssl->arrays->preMasterSz,
  6931. EC448_LITTLE_ENDIAN);
  6932. }
  6933. wc_curve448_free(peerX448Key);
  6934. XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6935. wc_curve448_free((curve448_key*)keyShareEntry->key);
  6936. if (keyShareEntry->key != NULL) {
  6937. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6938. keyShareEntry->key = NULL;
  6939. }
  6940. #else
  6941. (void)ssl;
  6942. (void)keyShareEntry;
  6943. ret = PEER_KEY_ERROR;
  6944. WOLFSSL_ERROR_VERBOSE(ret);
  6945. #endif /* HAVE_CURVE448 */
  6946. return ret;
  6947. }
  6948. /* Process the ECC key share extension on the client side.
  6949. *
  6950. * ssl The SSL/TLS object.
  6951. * keyShareEntry The key share entry object to use to calculate shared secret.
  6952. * returns 0 on success and other values indicate failure.
  6953. */
  6954. static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6955. {
  6956. int ret = 0;
  6957. #ifdef HAVE_ECC
  6958. int curveId = ECC_CURVE_INVALID;
  6959. ecc_key* eccKey = (ecc_key*)keyShareEntry->key;
  6960. /* find supported curve */
  6961. switch (keyShareEntry->group) {
  6962. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  6963. #ifndef NO_ECC_SECP
  6964. case WOLFSSL_ECC_SECP256R1:
  6965. curveId = ECC_SECP256R1;
  6966. break;
  6967. #endif /* !NO_ECC_SECP */
  6968. #ifdef WOLFSSL_SM2
  6969. case WOLFSSL_ECC_SM2P256V1:
  6970. curveId = ECC_SM2P256V1;
  6971. break;
  6972. #endif
  6973. #endif
  6974. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  6975. #ifndef NO_ECC_SECP
  6976. case WOLFSSL_ECC_SECP384R1:
  6977. curveId = ECC_SECP384R1;
  6978. break;
  6979. #endif /* !NO_ECC_SECP */
  6980. #endif
  6981. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  6982. #ifndef NO_ECC_SECP
  6983. case WOLFSSL_ECC_SECP521R1:
  6984. curveId = ECC_SECP521R1;
  6985. break;
  6986. #endif /* !NO_ECC_SECP */
  6987. #endif
  6988. #if defined(HAVE_X448) && ECC_MIN_KEY_SZ <= 448
  6989. case WOLFSSL_ECC_X448:
  6990. curveId = ECC_X448;
  6991. break;
  6992. #endif
  6993. default:
  6994. /* unsupported curve */
  6995. WOLFSSL_ERROR_VERBOSE(ECC_PEERKEY_ERROR);
  6996. return ECC_PEERKEY_ERROR;
  6997. }
  6998. #ifdef WOLFSSL_ASYNC_CRYPT
  6999. if (keyShareEntry->lastRet == 0) /* don't enter here if WC_PENDING_E */
  7000. #endif
  7001. {
  7002. #ifdef WOLFSSL_DEBUG_TLS
  7003. WOLFSSL_MSG("Peer ECC Key");
  7004. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  7005. #endif
  7006. if (ssl->peerEccKey != NULL) {
  7007. wc_ecc_free(ssl->peerEccKey);
  7008. XFREE(ssl->peerEccKey, ssl->heap, DYNAMIC_TYPE_ECC);
  7009. ssl->peerEccKeyPresent = 0;
  7010. }
  7011. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  7012. ret = tsip_Tls13GenSharedSecret(ssl, keyShareEntry);
  7013. if (ret != CRYPTOCB_UNAVAILABLE) {
  7014. return ret;
  7015. }
  7016. ret = 0;
  7017. #endif
  7018. ssl->peerEccKey = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
  7019. DYNAMIC_TYPE_ECC);
  7020. if (ssl->peerEccKey == NULL) {
  7021. WOLFSSL_MSG("PeerEccKey Memory error");
  7022. ret = MEMORY_ERROR;
  7023. }
  7024. if (ret == 0) {
  7025. ret = wc_ecc_init_ex(ssl->peerEccKey, ssl->heap, ssl->devId);
  7026. }
  7027. /* Point is validated by import function. */
  7028. if (ret == 0) {
  7029. ret = wc_ecc_import_x963_ex(keyShareEntry->ke, keyShareEntry->keLen,
  7030. ssl->peerEccKey, curveId);
  7031. if (ret != 0) {
  7032. ret = ECC_PEERKEY_ERROR;
  7033. WOLFSSL_ERROR_VERBOSE(ret);
  7034. }
  7035. }
  7036. if (ret == 0) {
  7037. ssl->ecdhCurveOID = ssl->peerEccKey->dp->oidSum;
  7038. ssl->peerEccKeyPresent = 1;
  7039. }
  7040. }
  7041. if (ret == 0 && eccKey == NULL)
  7042. ret = BAD_FUNC_ARG;
  7043. if (ret == 0) {
  7044. ret = EccSharedSecret(ssl, eccKey, ssl->peerEccKey,
  7045. keyShareEntry->ke, &keyShareEntry->keLen,
  7046. ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz,
  7047. ssl->options.side
  7048. );
  7049. #ifdef WOLFSSL_ASYNC_CRYPT
  7050. if (ret == WC_PENDING_E)
  7051. return ret;
  7052. #endif
  7053. }
  7054. /* done with key share, release resources */
  7055. if (ssl->peerEccKey != NULL
  7056. #ifdef HAVE_PK_CALLBACKS
  7057. && ssl->ctx->EccSharedSecretCb == NULL
  7058. #endif
  7059. ) {
  7060. wc_ecc_free(ssl->peerEccKey);
  7061. XFREE(ssl->peerEccKey, ssl->heap, DYNAMIC_TYPE_ECC);
  7062. ssl->peerEccKey = NULL;
  7063. ssl->peerEccKeyPresent = 0;
  7064. }
  7065. if (keyShareEntry->key) {
  7066. wc_ecc_free((ecc_key*)keyShareEntry->key);
  7067. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_ECC);
  7068. keyShareEntry->key = NULL;
  7069. }
  7070. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7071. keyShareEntry->ke = NULL;
  7072. #else
  7073. (void)ssl;
  7074. (void)keyShareEntry;
  7075. ret = PEER_KEY_ERROR;
  7076. WOLFSSL_ERROR_VERBOSE(ret);
  7077. #endif /* HAVE_ECC */
  7078. return ret;
  7079. }
  7080. #ifdef HAVE_PQC
  7081. /* Process the Kyber key share extension on the client side.
  7082. *
  7083. * ssl The SSL/TLS object.
  7084. * keyShareEntry The key share entry object to use to calculate shared secret.
  7085. * returns 0 on success and other values indicate failure.
  7086. */
  7087. static int TLSX_KeyShare_ProcessPqc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  7088. {
  7089. int ret = 0;
  7090. int type;
  7091. KyberKey kem[1];
  7092. byte* sharedSecret = NULL;
  7093. word32 sharedSecretLen = 0;
  7094. int oqs_group = 0;
  7095. int ecc_group = 0;
  7096. ecc_key eccpubkey;
  7097. word32 outlen = 0;
  7098. word32 privSz = 0;
  7099. word32 ctSz = 0;
  7100. word32 ssSz = 0;
  7101. if (keyShareEntry->ke == NULL) {
  7102. WOLFSSL_MSG("Invalid OQS algorithm specified.");
  7103. return BAD_FUNC_ARG;
  7104. }
  7105. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7106. /* I am the server, the shared secret has already been generated and
  7107. * is in keyShareEntry->ke; copy it to the pre-master secret
  7108. * pre-allocated buffer. */
  7109. if (keyShareEntry->keLen > ENCRYPT_LEN) {
  7110. WOLFSSL_MSG("shared secret is too long.");
  7111. return LENGTH_ERROR;
  7112. }
  7113. XMEMCPY(ssl->arrays->preMasterSecret, keyShareEntry->ke,
  7114. keyShareEntry->keLen);
  7115. ssl->arrays->preMasterSz = keyShareEntry->keLen;
  7116. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_SECRET)
  7117. keyShareEntry->ke = NULL;
  7118. keyShareEntry->keLen = 0;
  7119. return 0;
  7120. }
  7121. /* I am the client, the ciphertext is in keyShareEntry->ke */
  7122. findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group);
  7123. ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId);
  7124. if (ret != 0) {
  7125. WOLFSSL_MSG("Memory allocation error.");
  7126. return MEMORY_E;
  7127. }
  7128. ret = kyber_id2type(oqs_group, &type);
  7129. if (ret != 0) {
  7130. wc_ecc_free(&eccpubkey);
  7131. WOLFSSL_MSG("Invalid OQS algorithm specified.");
  7132. return BAD_FUNC_ARG;
  7133. }
  7134. ret = wc_KyberKey_Init(type, kem, ssl->heap, INVALID_DEVID);
  7135. if (ret != 0) {
  7136. wc_ecc_free(&eccpubkey);
  7137. WOLFSSL_MSG("Error creating Kyber KEM");
  7138. return MEMORY_E;
  7139. }
  7140. if (ret == 0) {
  7141. ret = wc_KyberKey_SharedSecretSize(kem, &ssSz);
  7142. }
  7143. if (ret == 0) {
  7144. sharedSecretLen = ssSz;
  7145. switch (ecc_group) {
  7146. case WOLFSSL_ECC_SECP256R1:
  7147. sharedSecretLen += 32;
  7148. outlen = 32;
  7149. break;
  7150. case WOLFSSL_ECC_SECP384R1:
  7151. sharedSecretLen += 48;
  7152. outlen = 48;
  7153. break;
  7154. case WOLFSSL_ECC_SECP521R1:
  7155. sharedSecretLen += 66;
  7156. outlen = 66;
  7157. break;
  7158. default:
  7159. break;
  7160. }
  7161. }
  7162. if (ret == 0) {
  7163. sharedSecret = (byte*)XMALLOC(sharedSecretLen, ssl->heap,
  7164. DYNAMIC_TYPE_TLSX);
  7165. if (sharedSecret == NULL) {
  7166. WOLFSSL_MSG("Memory allocation error.");
  7167. ret = MEMORY_E;
  7168. }
  7169. }
  7170. if (ret == 0) {
  7171. ret = wc_KyberKey_CipherTextSize(kem, &ctSz);
  7172. }
  7173. if (ret == 0) {
  7174. ret = wc_KyberKey_PrivateKeySize(kem, &privSz);
  7175. }
  7176. if (ret == 0) {
  7177. ret = wc_KyberKey_DecodePrivateKey(kem, keyShareEntry->privKey, privSz);
  7178. }
  7179. if (ret == 0) {
  7180. ret = wc_KyberKey_Decapsulate(kem, sharedSecret + outlen,
  7181. keyShareEntry->ke + keyShareEntry->keLen - ctSz, ctSz);
  7182. if (ret != 0) {
  7183. WOLFSSL_MSG("wc_KyberKey decapsulation failure.");
  7184. ret = BAD_FUNC_ARG;
  7185. }
  7186. }
  7187. if (ecc_group != 0) {
  7188. if (ret == 0) {
  7189. /* Point is validated by import function. */
  7190. ret = wc_ecc_import_x963(keyShareEntry->ke,
  7191. keyShareEntry->keLen - ctSz,
  7192. &eccpubkey);
  7193. if (ret != 0) {
  7194. WOLFSSL_MSG("ECC Public key import error.");
  7195. }
  7196. }
  7197. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  7198. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  7199. !defined(HAVE_SELFTEST)
  7200. if (ret == 0) {
  7201. ret = wc_ecc_set_rng(keyShareEntry->key, ssl->rng);
  7202. if (ret != 0) {
  7203. WOLFSSL_MSG("Failure to set the ECC private key RNG.");
  7204. }
  7205. }
  7206. #endif
  7207. if (ret == 0) {
  7208. PRIVATE_KEY_UNLOCK();
  7209. ret = wc_ecc_shared_secret(keyShareEntry->key, &eccpubkey,
  7210. sharedSecret, &outlen);
  7211. PRIVATE_KEY_LOCK();
  7212. if (outlen != sharedSecretLen - ssSz) {
  7213. WOLFSSL_MSG("ECC shared secret derivation error.");
  7214. ret = BAD_FUNC_ARG;
  7215. }
  7216. }
  7217. }
  7218. if ((ret == 0) && (sharedSecretLen > ENCRYPT_LEN)) {
  7219. WOLFSSL_MSG("shared secret is too long.");
  7220. ret = LENGTH_ERROR;
  7221. }
  7222. if (ret == 0) {
  7223. /* Copy the shared secret to the pre-master secret pre-allocated
  7224. * buffer. */
  7225. XMEMCPY(ssl->arrays->preMasterSecret, sharedSecret, sharedSecretLen);
  7226. ssl->arrays->preMasterSz = (word32) sharedSecretLen;
  7227. }
  7228. if (sharedSecret != NULL) {
  7229. XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  7230. }
  7231. wc_ecc_free(&eccpubkey);
  7232. wc_KyberKey_Free(kem);
  7233. return ret;
  7234. }
  7235. #endif /* HAVE_PQC */
  7236. /* Process the key share extension on the client side.
  7237. *
  7238. * ssl The SSL/TLS object.
  7239. * keyShareEntry The key share entry object to use to calculate shared secret.
  7240. * returns 0 on success and other values indicate failure.
  7241. */
  7242. static int TLSX_KeyShare_Process(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  7243. {
  7244. int ret;
  7245. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  7246. ssl->session->namedGroup = keyShareEntry->group;
  7247. #endif
  7248. /* reset the pre master secret size */
  7249. if (ssl->arrays->preMasterSz == 0)
  7250. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  7251. /* Use Key Share Data from server. */
  7252. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(keyShareEntry->group))
  7253. ret = TLSX_KeyShare_ProcessDh(ssl, keyShareEntry);
  7254. else if (keyShareEntry->group == WOLFSSL_ECC_X25519)
  7255. ret = TLSX_KeyShare_ProcessX25519(ssl, keyShareEntry);
  7256. else if (keyShareEntry->group == WOLFSSL_ECC_X448)
  7257. ret = TLSX_KeyShare_ProcessX448(ssl, keyShareEntry);
  7258. #ifdef HAVE_PQC
  7259. else if (WOLFSSL_NAMED_GROUP_IS_PQC(keyShareEntry->group))
  7260. ret = TLSX_KeyShare_ProcessPqc(ssl, keyShareEntry);
  7261. #endif
  7262. else
  7263. ret = TLSX_KeyShare_ProcessEcc(ssl, keyShareEntry);
  7264. #ifdef WOLFSSL_DEBUG_TLS
  7265. if (ret == 0) {
  7266. WOLFSSL_MSG("KE Secret");
  7267. WOLFSSL_BUFFER(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  7268. }
  7269. #endif
  7270. #ifdef WOLFSSL_ASYNC_CRYPT
  7271. keyShareEntry->lastRet = ret;
  7272. #endif
  7273. return ret;
  7274. }
  7275. /* Parse an entry of the KeyShare extension.
  7276. *
  7277. * ssl The SSL/TLS object.
  7278. * input The extension data.
  7279. * length The length of the extension data.
  7280. * kse The new key share entry object.
  7281. * returns a positive number to indicate amount of data parsed and a negative
  7282. * number on error.
  7283. */
  7284. static int TLSX_KeyShareEntry_Parse(const WOLFSSL* ssl, const byte* input,
  7285. word16 length, KeyShareEntry **kse, TLSX** extensions)
  7286. {
  7287. int ret;
  7288. word16 group;
  7289. word16 keLen;
  7290. int offset = 0;
  7291. byte* ke;
  7292. if (length < OPAQUE16_LEN + OPAQUE16_LEN)
  7293. return BUFFER_ERROR;
  7294. /* Named group */
  7295. ato16(&input[offset], &group);
  7296. offset += OPAQUE16_LEN;
  7297. /* Key exchange data - public key. */
  7298. ato16(&input[offset], &keLen);
  7299. offset += OPAQUE16_LEN;
  7300. if (keLen == 0)
  7301. return INVALID_PARAMETER;
  7302. if (keLen > length - offset)
  7303. return BUFFER_ERROR;
  7304. #ifdef HAVE_PQC
  7305. if (WOLFSSL_NAMED_GROUP_IS_PQC(group) &&
  7306. ssl->options.side == WOLFSSL_SERVER_END) {
  7307. /* For KEMs, the public key is not stored. Casting away const because
  7308. * we know for KEMs, it will be read-only.*/
  7309. ke = (byte *)&input[offset];
  7310. } else
  7311. #endif
  7312. {
  7313. /* Store a copy in the key share object. */
  7314. ke = (byte*)XMALLOC(keLen, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7315. if (ke == NULL)
  7316. return MEMORY_E;
  7317. XMEMCPY(ke, &input[offset], keLen);
  7318. }
  7319. /* Populate a key share object in the extension. */
  7320. ret = TLSX_KeyShare_Use(ssl, group, keLen, ke, kse, extensions);
  7321. if (ret != 0) {
  7322. if (ke != &input[offset]) {
  7323. XFREE(ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7324. }
  7325. return ret;
  7326. }
  7327. /* Total length of the parsed data. */
  7328. return offset + keLen;
  7329. }
  7330. /* Searches the groups sent for the specified named group.
  7331. *
  7332. * ssl SSL/TLS object.
  7333. * name Group name to match.
  7334. * returns 1 when the extension has the group name and 0 otherwise.
  7335. */
  7336. static int TLSX_KeyShare_Find(WOLFSSL* ssl, word16 group)
  7337. {
  7338. TLSX* extension;
  7339. KeyShareEntry* list;
  7340. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  7341. if (extension == NULL) {
  7342. extension = TLSX_Find(ssl->ctx->extensions, TLSX_KEY_SHARE);
  7343. if (extension == NULL)
  7344. return 0;
  7345. }
  7346. list = (KeyShareEntry*)extension->data;
  7347. while (list != NULL) {
  7348. if (list->group == group)
  7349. return 1;
  7350. list = list->next;
  7351. }
  7352. return 0;
  7353. }
  7354. /* Searches the supported groups extension for the specified named group.
  7355. *
  7356. * ssl The SSL/TLS object.
  7357. * name The group name to match.
  7358. * returns 1 when the extension has the group name and 0 otherwise.
  7359. */
  7360. static int TLSX_SupportedGroups_Find(const WOLFSSL* ssl, word16 name,
  7361. TLSX* extensions)
  7362. {
  7363. #ifdef HAVE_SUPPORTED_CURVES
  7364. TLSX* extension;
  7365. SupportedCurve* curve = NULL;
  7366. if ((extension = TLSX_Find(extensions, TLSX_SUPPORTED_GROUPS)) == NULL) {
  7367. if ((extension = TLSX_Find(ssl->ctx->extensions,
  7368. TLSX_SUPPORTED_GROUPS)) == NULL) {
  7369. return 0;
  7370. }
  7371. }
  7372. for (curve = (SupportedCurve*)extension->data; curve; curve = curve->next) {
  7373. if (curve->name == name)
  7374. return 1;
  7375. }
  7376. #endif
  7377. (void)ssl;
  7378. (void)name;
  7379. return 0;
  7380. }
  7381. int TLSX_KeyShare_Parse_ClientHello(const WOLFSSL* ssl,
  7382. const byte* input, word16 length, TLSX** extensions)
  7383. {
  7384. int ret;
  7385. int offset = 0;
  7386. word16 len;
  7387. TLSX* extension;
  7388. /* Add a KeyShare extension if it doesn't exist even if peer sent no
  7389. * entries. The presence of this extension signals that the peer can be
  7390. * negotiated with. */
  7391. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7392. if (extension == NULL) {
  7393. /* Push new KeyShare extension. */
  7394. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7395. if (ret != 0)
  7396. return ret;
  7397. }
  7398. if (length < OPAQUE16_LEN)
  7399. return BUFFER_ERROR;
  7400. /* ClientHello contains zero or more key share entries. */
  7401. ato16(input, &len);
  7402. if (len != length - OPAQUE16_LEN)
  7403. return BUFFER_ERROR;
  7404. offset += OPAQUE16_LEN;
  7405. while (offset < (int)length) {
  7406. ret = TLSX_KeyShareEntry_Parse(ssl, &input[offset],
  7407. length - (word16)offset, NULL, extensions);
  7408. if (ret < 0)
  7409. return ret;
  7410. offset += ret;
  7411. }
  7412. return 0;
  7413. }
  7414. /* Parse the KeyShare extension.
  7415. * Different formats in different messages.
  7416. *
  7417. * ssl The SSL/TLS object.
  7418. * input The extension data.
  7419. * length The length of the extension data.
  7420. * msgType The type of the message this extension is being parsed from.
  7421. * returns 0 on success and other values indicate failure.
  7422. */
  7423. int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  7424. byte msgType)
  7425. {
  7426. int ret = 0;
  7427. KeyShareEntry *keyShareEntry = NULL;
  7428. word16 group;
  7429. if (msgType == client_hello) {
  7430. ret = TLSX_KeyShare_Parse_ClientHello(ssl, input, length,
  7431. &ssl->extensions);
  7432. }
  7433. else if (msgType == server_hello) {
  7434. int len;
  7435. if (length < OPAQUE16_LEN)
  7436. return BUFFER_ERROR;
  7437. /* The data is the named group the server wants to use. */
  7438. ato16(input, &group);
  7439. /* Check the selected group was supported by ClientHello extensions. */
  7440. if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) {
  7441. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7442. return BAD_KEY_SHARE_DATA;
  7443. }
  7444. /* Check if the group was sent. */
  7445. if (!TLSX_KeyShare_Find(ssl, group)) {
  7446. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7447. return BAD_KEY_SHARE_DATA;
  7448. }
  7449. /* ServerHello contains one key share entry. */
  7450. len = TLSX_KeyShareEntry_Parse(ssl, input, length, &keyShareEntry,
  7451. &ssl->extensions);
  7452. if (len != (int)length)
  7453. return BUFFER_ERROR;
  7454. /* Not in list sent if there isn't a private key. */
  7455. if (keyShareEntry == NULL || (keyShareEntry->key == NULL
  7456. #if !defined(NO_DH) || defined(HAVE_PQC)
  7457. && keyShareEntry->privKey == NULL
  7458. #endif
  7459. )) {
  7460. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7461. return BAD_KEY_SHARE_DATA;
  7462. }
  7463. /* Process the entry to calculate the secret. */
  7464. ret = TLSX_KeyShare_Process(ssl, keyShareEntry);
  7465. if (ret == 0)
  7466. ssl->session->namedGroup = ssl->namedGroup = group;
  7467. }
  7468. else if (msgType == hello_retry_request) {
  7469. if (length != OPAQUE16_LEN)
  7470. return BUFFER_ERROR;
  7471. /* The data is the named group the server wants to use. */
  7472. ato16(input, &group);
  7473. #ifdef WOLFSSL_ASYNC_CRYPT
  7474. /* only perform find and clear TLSX if not returning from async */
  7475. if (ssl->error != WC_PENDING_E)
  7476. #endif
  7477. {
  7478. /* Check the selected group was supported by ClientHello extensions. */
  7479. if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) {
  7480. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7481. return BAD_KEY_SHARE_DATA;
  7482. }
  7483. /* Check if the group was sent. */
  7484. if (TLSX_KeyShare_Find(ssl, group)) {
  7485. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7486. return BAD_KEY_SHARE_DATA;
  7487. }
  7488. /* Clear out unusable key shares. */
  7489. ret = TLSX_KeyShare_Empty(ssl);
  7490. if (ret != 0)
  7491. return ret;
  7492. }
  7493. ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL, &ssl->extensions);
  7494. if (ret == 0)
  7495. ssl->session->namedGroup = ssl->namedGroup = group;
  7496. }
  7497. else {
  7498. /* Not a message type that is allowed to have this extension. */
  7499. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  7500. return SANITY_MSG_E;
  7501. }
  7502. return ret;
  7503. }
  7504. /* Create a new key share entry and put it into the list.
  7505. *
  7506. * list The linked list of key share entries.
  7507. * group The named group.
  7508. * heap The memory to allocate with.
  7509. * keyShareEntry The new key share entry object.
  7510. * returns 0 on success and other values indicate failure.
  7511. */
  7512. static int TLSX_KeyShare_New(KeyShareEntry** list, int group, void *heap,
  7513. KeyShareEntry** keyShareEntry)
  7514. {
  7515. KeyShareEntry* kse;
  7516. KeyShareEntry** next;
  7517. kse = (KeyShareEntry*)XMALLOC(sizeof(KeyShareEntry), heap,
  7518. DYNAMIC_TYPE_TLSX);
  7519. if (kse == NULL)
  7520. return MEMORY_E;
  7521. XMEMSET(kse, 0, sizeof(*kse));
  7522. kse->group = (word16)group;
  7523. /* Add it to the back and maintain the links. */
  7524. while (*list != NULL) {
  7525. /* Assign to temporary to work around compiler bug found by customer. */
  7526. next = &((*list)->next);
  7527. list = next;
  7528. }
  7529. *list = kse;
  7530. *keyShareEntry = kse;
  7531. (void)heap;
  7532. return 0;
  7533. }
  7534. #ifdef HAVE_PQC
  7535. static int server_generate_pqc_ciphertext(WOLFSSL* ssl,
  7536. KeyShareEntry* keyShareEntry, byte* data, word16 len)
  7537. {
  7538. /* I am the server. The data parameter is the client's public key. I need
  7539. * to generate the public information (AKA ciphertext) and shared secret
  7540. * here. Note the "public information" is equivalent to a the public key in
  7541. * key exchange parlance. That's why it is being assigned to pubKey.
  7542. */
  7543. int type;
  7544. KyberKey kem[1];
  7545. byte* sharedSecret = NULL;
  7546. byte* ciphertext = NULL;
  7547. int ret = 0;
  7548. int oqs_group = 0;
  7549. int ecc_group = 0;
  7550. KeyShareEntry *ecc_kse = NULL;
  7551. ecc_key eccpubkey;
  7552. word32 outlen = 0;
  7553. word32 pubSz = 0;
  7554. word32 ctSz = 0;
  7555. word32 ssSz = 0;
  7556. findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group);
  7557. ret = kyber_id2type(oqs_group, &type);
  7558. if (ret != 0) {
  7559. WOLFSSL_MSG("Invalid Kyber algorithm specified.");
  7560. return BAD_FUNC_ARG;
  7561. }
  7562. ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId);
  7563. if (ret != 0) {
  7564. WOLFSSL_MSG("Could not do ECC public key initialization.");
  7565. return MEMORY_E;
  7566. }
  7567. ret = wc_KyberKey_Init(type, kem, ssl->heap, INVALID_DEVID);
  7568. if (ret != 0) {
  7569. wc_ecc_free(&eccpubkey);
  7570. WOLFSSL_MSG("Error creating Kyber KEM");
  7571. return MEMORY_E;
  7572. }
  7573. if (ret == 0) {
  7574. ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap,
  7575. DYNAMIC_TYPE_TLSX);
  7576. if (ecc_kse == NULL) {
  7577. WOLFSSL_MSG("ecc_kse memory allocation failure");
  7578. ret = MEMORY_ERROR;
  7579. }
  7580. }
  7581. if (ret == 0) {
  7582. XMEMSET(ecc_kse, 0, sizeof(*ecc_kse));
  7583. }
  7584. if (ret == 0 && ecc_group != 0) {
  7585. ecc_kse->group = ecc_group;
  7586. ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse);
  7587. /* No message, TLSX_KeyShare_GenEccKey() will do it. */
  7588. }
  7589. if (ret == 0) {
  7590. ret = wc_KyberKey_PublicKeySize(kem, &pubSz);
  7591. }
  7592. if (ret == 0) {
  7593. ret = wc_KyberKey_CipherTextSize(kem, &ctSz);
  7594. }
  7595. if (ret == 0) {
  7596. ret = wc_KyberKey_SharedSecretSize(kem, &ssSz);
  7597. }
  7598. if (ret == 0 && len != pubSz + ecc_kse->pubKeyLen) {
  7599. WOLFSSL_MSG("Invalid public key.");
  7600. ret = BAD_FUNC_ARG;
  7601. }
  7602. if (ret == 0) {
  7603. sharedSecret = (byte*)XMALLOC(ecc_kse->keyLen + ssSz, ssl->heap,
  7604. DYNAMIC_TYPE_SECRET);
  7605. ciphertext = (byte*)XMALLOC(ecc_kse->pubKeyLen + ctSz, ssl->heap,
  7606. DYNAMIC_TYPE_TLSX);
  7607. if (sharedSecret == NULL || ciphertext == NULL) {
  7608. WOLFSSL_MSG("Ciphertext/shared secret memory allocation failure.");
  7609. ret = MEMORY_E;
  7610. }
  7611. }
  7612. if (ecc_group != 0) {
  7613. if (ret == 0) {
  7614. /* Point is validated by import function. */
  7615. ret = wc_ecc_import_x963(data, len - pubSz, &eccpubkey);
  7616. if (ret != 0) {
  7617. WOLFSSL_MSG("Bad ECC public key.");
  7618. }
  7619. }
  7620. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  7621. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  7622. !defined(HAVE_SELFTEST)
  7623. if (ret == 0) {
  7624. ret = wc_ecc_set_rng(ecc_kse->key, ssl->rng);
  7625. }
  7626. #endif
  7627. if (ret == 0) {
  7628. outlen = ecc_kse->keyLen;
  7629. PRIVATE_KEY_UNLOCK();
  7630. ret = wc_ecc_shared_secret(ecc_kse->key, &eccpubkey,
  7631. sharedSecret,
  7632. &outlen);
  7633. PRIVATE_KEY_LOCK();
  7634. if (outlen != ecc_kse->keyLen) {
  7635. WOLFSSL_MSG("Data length mismatch.");
  7636. ret = BAD_FUNC_ARG;
  7637. }
  7638. }
  7639. }
  7640. if (ret == 0) {
  7641. ret = wc_KyberKey_DecodePublicKey(kem, data + ecc_kse->pubKeyLen,
  7642. pubSz);
  7643. }
  7644. if (ret == 0) {
  7645. ret = wc_KyberKey_Encapsulate(kem, ciphertext + ecc_kse->pubKeyLen,
  7646. sharedSecret + outlen, ssl->rng);
  7647. if (ret != 0) {
  7648. WOLFSSL_MSG("wc_KyberKey encapsulation failure.");
  7649. }
  7650. }
  7651. if (ret == 0) {
  7652. if (keyShareEntry->ke != NULL) {
  7653. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7654. }
  7655. keyShareEntry->ke = sharedSecret;
  7656. keyShareEntry->keLen = outlen + ssSz;
  7657. sharedSecret = NULL;
  7658. XMEMCPY(ciphertext, ecc_kse->pubKey, ecc_kse->pubKeyLen);
  7659. keyShareEntry->pubKey = ciphertext;
  7660. keyShareEntry->pubKeyLen = (word32)(ecc_kse->pubKeyLen + ctSz);
  7661. ciphertext = NULL;
  7662. /* Set namedGroup so wolfSSL_get_curve_name() can function properly on
  7663. * the server side. */
  7664. ssl->namedGroup = keyShareEntry->group;
  7665. }
  7666. TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap);
  7667. if (sharedSecret != NULL)
  7668. XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  7669. if (ciphertext != NULL)
  7670. XFREE(ciphertext, ssl->heap, DYNAMIC_TYPE_TLSX);
  7671. wc_ecc_free(&eccpubkey);
  7672. wc_KyberKey_Free(kem);
  7673. return ret;
  7674. }
  7675. #endif /* HAVE_PQC */
  7676. /* Use the data to create a new key share object in the extensions.
  7677. *
  7678. * ssl The SSL/TLS object.
  7679. * group The named group.
  7680. * len The length of the public key data.
  7681. * data The public key data.
  7682. * kse The new key share entry object.
  7683. * returns 0 on success and other values indicate failure.
  7684. */
  7685. int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group, word16 len, byte* data,
  7686. KeyShareEntry **kse, TLSX** extensions)
  7687. {
  7688. int ret = 0;
  7689. TLSX* extension;
  7690. KeyShareEntry* keyShareEntry = NULL;
  7691. /* Find the KeyShare extension if it exists. */
  7692. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7693. if (extension == NULL) {
  7694. /* Push new KeyShare extension. */
  7695. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7696. if (ret != 0)
  7697. return ret;
  7698. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7699. if (extension == NULL)
  7700. return MEMORY_E;
  7701. }
  7702. extension->resp = 0;
  7703. /* Try to find the key share entry with this group. */
  7704. keyShareEntry = (KeyShareEntry*)extension->data;
  7705. while (keyShareEntry != NULL) {
  7706. if (keyShareEntry->group == group)
  7707. break;
  7708. keyShareEntry = keyShareEntry->next;
  7709. }
  7710. /* Create a new key share entry if not found. */
  7711. if (keyShareEntry == NULL) {
  7712. ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, group,
  7713. ssl->heap, &keyShareEntry);
  7714. if (ret != 0)
  7715. return ret;
  7716. }
  7717. #ifdef HAVE_PQC
  7718. if (WOLFSSL_NAMED_GROUP_IS_PQC(group) &&
  7719. ssl->options.side == WOLFSSL_SERVER_END) {
  7720. ret = server_generate_pqc_ciphertext((WOLFSSL*)ssl, keyShareEntry, data,
  7721. len);
  7722. if (ret != 0)
  7723. return ret;
  7724. }
  7725. else
  7726. #endif
  7727. if (data != NULL) {
  7728. if (keyShareEntry->ke != NULL) {
  7729. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7730. }
  7731. keyShareEntry->ke = data;
  7732. keyShareEntry->keLen = len;
  7733. }
  7734. else {
  7735. /* Generate a key pair. Casting to non-const since changes inside are
  7736. * minimal but would require an extensive redesign to refactor. Also
  7737. * this path shouldn't be taken when parsing a ClientHello in stateless
  7738. * mode. */
  7739. ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, keyShareEntry);
  7740. if (ret != 0)
  7741. return ret;
  7742. }
  7743. if (kse != NULL)
  7744. *kse = keyShareEntry;
  7745. return 0;
  7746. }
  7747. /* Set an empty Key Share extension.
  7748. *
  7749. * ssl The SSL/TLS object.
  7750. * returns 0 on success and other values indicate failure.
  7751. */
  7752. int TLSX_KeyShare_Empty(WOLFSSL* ssl)
  7753. {
  7754. int ret = 0;
  7755. TLSX* extension;
  7756. /* Find the KeyShare extension if it exists. */
  7757. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  7758. if (extension == NULL) {
  7759. /* Push new KeyShare extension. */
  7760. ret = TLSX_Push(&ssl->extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7761. }
  7762. else if (extension->data != NULL) {
  7763. TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap);
  7764. extension->data = NULL;
  7765. }
  7766. return ret;
  7767. }
  7768. /* Returns whether this group is supported.
  7769. *
  7770. * namedGroup The named group to check.
  7771. * returns 1 when supported or 0 otherwise.
  7772. */
  7773. static int TLSX_KeyShare_IsSupported(int namedGroup)
  7774. {
  7775. switch (namedGroup) {
  7776. #ifdef HAVE_FFDHE_2048
  7777. case WOLFSSL_FFDHE_2048:
  7778. break;
  7779. #endif
  7780. #ifdef HAVE_FFDHE_3072
  7781. case WOLFSSL_FFDHE_3072:
  7782. break;
  7783. #endif
  7784. #ifdef HAVE_FFDHE_4096
  7785. case WOLFSSL_FFDHE_4096:
  7786. break;
  7787. #endif
  7788. #ifdef HAVE_FFDHE_6144
  7789. case WOLFSSL_FFDHE_6144:
  7790. break;
  7791. #endif
  7792. #ifdef HAVE_FFDHE_8192
  7793. case WOLFSSL_FFDHE_8192:
  7794. break;
  7795. #endif
  7796. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  7797. #ifdef HAVE_ECC_KOBLITZ
  7798. case WOLFSSL_ECC_SECP256K1:
  7799. break;
  7800. #endif
  7801. #ifndef NO_ECC_SECP
  7802. case WOLFSSL_ECC_SECP256R1:
  7803. break;
  7804. #endif /* !NO_ECC_SECP */
  7805. #ifdef HAVE_ECC_BRAINPOOL
  7806. case WOLFSSL_ECC_BRAINPOOLP256R1:
  7807. break;
  7808. #endif
  7809. #ifdef WOLFSSL_SM2
  7810. case WOLFSSL_ECC_SM2P256V1:
  7811. break;
  7812. #endif /* WOLFSSL_SM2 */
  7813. #endif
  7814. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  7815. case WOLFSSL_ECC_X25519:
  7816. break;
  7817. #endif
  7818. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  7819. case WOLFSSL_ECC_X448:
  7820. break;
  7821. #endif
  7822. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  7823. #ifndef NO_ECC_SECP
  7824. case WOLFSSL_ECC_SECP384R1:
  7825. break;
  7826. #endif /* !NO_ECC_SECP */
  7827. #ifdef HAVE_ECC_BRAINPOOL
  7828. case WOLFSSL_ECC_BRAINPOOLP384R1:
  7829. break;
  7830. #endif
  7831. #endif
  7832. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  7833. #ifndef NO_ECC_SECP
  7834. case WOLFSSL_ECC_SECP521R1:
  7835. break;
  7836. #endif /* !NO_ECC_SECP */
  7837. #endif
  7838. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  7839. #ifdef HAVE_ECC_KOBLITZ
  7840. case WOLFSSL_ECC_SECP160K1:
  7841. break;
  7842. #endif
  7843. #ifndef NO_ECC_SECP
  7844. case WOLFSSL_ECC_SECP160R1:
  7845. break;
  7846. #endif
  7847. #ifdef HAVE_ECC_SECPR2
  7848. case WOLFSSL_ECC_SECP160R2:
  7849. break;
  7850. #endif
  7851. #endif
  7852. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  7853. #ifdef HAVE_ECC_KOBLITZ
  7854. case WOLFSSL_ECC_SECP192K1:
  7855. break;
  7856. #endif
  7857. #ifndef NO_ECC_SECP
  7858. case WOLFSSL_ECC_SECP192R1:
  7859. break;
  7860. #endif
  7861. #endif
  7862. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  7863. #ifdef HAVE_ECC_KOBLITZ
  7864. case WOLFSSL_ECC_SECP224K1:
  7865. break;
  7866. #endif
  7867. #ifndef NO_ECC_SECP
  7868. case WOLFSSL_ECC_SECP224R1:
  7869. break;
  7870. #endif
  7871. #endif
  7872. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  7873. #ifdef HAVE_ECC_BRAINPOOL
  7874. case WOLFSSL_ECC_BRAINPOOLP512R1:
  7875. break;
  7876. #endif
  7877. #endif
  7878. #ifdef HAVE_PQC
  7879. #ifdef WOLFSSL_WC_KYBER
  7880. #ifdef WOLFSSL_KYBER512
  7881. case WOLFSSL_KYBER_LEVEL1:
  7882. #endif
  7883. #ifdef WOLFSSL_KYBER768
  7884. case WOLFSSL_KYBER_LEVEL3:
  7885. #endif
  7886. #ifdef WOLFSSL_KYBER1024
  7887. case WOLFSSL_KYBER_LEVEL5:
  7888. #endif
  7889. break;
  7890. #elif defined(HAVE_LIBOQS)
  7891. case WOLFSSL_KYBER_LEVEL1:
  7892. case WOLFSSL_KYBER_LEVEL3:
  7893. case WOLFSSL_KYBER_LEVEL5:
  7894. case WOLFSSL_P256_KYBER_LEVEL1:
  7895. case WOLFSSL_P384_KYBER_LEVEL3:
  7896. case WOLFSSL_P521_KYBER_LEVEL5:
  7897. {
  7898. int ret;
  7899. int id;
  7900. findEccPqc(NULL, &namedGroup, namedGroup);
  7901. ret = kyber_id2type(namedGroup, &id);
  7902. if (ret == NOT_COMPILED_IN) {
  7903. return 0;
  7904. }
  7905. if (! ext_kyber_enabled(id)) {
  7906. return 0;
  7907. }
  7908. break;
  7909. }
  7910. #elif defined(HAVE_PQM4)
  7911. case WOLFSSL_KYBER_LEVEL1:
  7912. break;
  7913. #endif
  7914. #endif /* HAVE_PQC */
  7915. default:
  7916. return 0;
  7917. }
  7918. return 1;
  7919. }
  7920. static const word16 preferredGroup[] = {
  7921. #if defined(HAVE_ECC) && (!defined(NO_ECC256) || \
  7922. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 256
  7923. WOLFSSL_ECC_SECP256R1,
  7924. #if !defined(HAVE_FIPS) && defined(WOLFSSL_SM2)
  7925. WOLFSSL_ECC_SM2P256V1,
  7926. #endif
  7927. #endif
  7928. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  7929. WOLFSSL_ECC_X25519,
  7930. #endif
  7931. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  7932. WOLFSSL_ECC_X448,
  7933. #endif
  7934. #if defined(HAVE_ECC) && (!defined(NO_ECC384) || \
  7935. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 384
  7936. WOLFSSL_ECC_SECP384R1,
  7937. #endif
  7938. #if defined(HAVE_ECC) && (!defined(NO_ECC521) || \
  7939. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 521
  7940. WOLFSSL_ECC_SECP521R1,
  7941. #endif
  7942. #if defined(HAVE_FFDHE_2048)
  7943. WOLFSSL_FFDHE_2048,
  7944. #endif
  7945. #if defined(HAVE_FFDHE_3072)
  7946. WOLFSSL_FFDHE_3072,
  7947. #endif
  7948. #if defined(HAVE_FFDHE_4096)
  7949. WOLFSSL_FFDHE_4096,
  7950. #endif
  7951. #if defined(HAVE_FFDHE_6144)
  7952. WOLFSSL_FFDHE_6144,
  7953. #endif
  7954. #if defined(HAVE_FFDHE_8192)
  7955. WOLFSSL_FFDHE_8192,
  7956. #endif
  7957. #ifdef WOLFSSL_WC_KYBER
  7958. #ifdef WOLFSSL_KYBER512
  7959. WOLFSSL_KYBER_LEVEL1,
  7960. #endif
  7961. #ifdef WOLFSSL_KYBER768
  7962. WOLFSSL_KYBER_LEVEL3,
  7963. #endif
  7964. #ifdef WOLFSSL_KYBER1024
  7965. WOLFSSL_KYBER_LEVEL5,
  7966. #endif
  7967. #elif defined(HAVE_LIBOQS)
  7968. /* These require a runtime call to TLSX_KeyShare_IsSupported to use */
  7969. WOLFSSL_KYBER_LEVEL1,
  7970. WOLFSSL_KYBER_LEVEL3,
  7971. WOLFSSL_KYBER_LEVEL5,
  7972. WOLFSSL_P256_KYBER_LEVEL1,
  7973. WOLFSSL_P384_KYBER_LEVEL3,
  7974. WOLFSSL_P521_KYBER_LEVEL5,
  7975. #elif defined(HAVE_PQM4)
  7976. WOLFSSL_KYBER_LEVEL1,
  7977. #endif
  7978. WOLFSSL_NAMED_GROUP_INVALID
  7979. };
  7980. #define PREFERRED_GROUP_SZ \
  7981. ((sizeof(preferredGroup)/sizeof(*preferredGroup)) - 1)
  7982. /* -1 for the invalid group */
  7983. /* Examines the application specified group ranking and returns the rank of the
  7984. * group.
  7985. * If no group ranking set then all groups are rank 0 (highest).
  7986. *
  7987. * ssl The SSL/TLS object.
  7988. * group The group to check ranking for.
  7989. * returns ranking from 0 to MAX_GROUP_COUNT-1 or -1 when group not in list.
  7990. */
  7991. static int TLSX_KeyShare_GroupRank(const WOLFSSL* ssl, int group)
  7992. {
  7993. byte i;
  7994. const word16* groups;
  7995. byte numGroups;
  7996. if (ssl->numGroups == 0) {
  7997. groups = preferredGroup;
  7998. numGroups = PREFERRED_GROUP_SZ;
  7999. }
  8000. else {
  8001. groups = ssl->group;
  8002. numGroups = ssl->numGroups;
  8003. }
  8004. #ifdef HAVE_LIBOQS
  8005. if (!TLSX_KeyShare_IsSupported(group))
  8006. return -1;
  8007. #endif
  8008. for (i = 0; i < numGroups; i++)
  8009. if (groups[i] == (word16)group)
  8010. return i;
  8011. return -1;
  8012. }
  8013. /* Set a key share that is supported by the client into extensions.
  8014. *
  8015. * ssl The SSL/TLS object.
  8016. * returns BAD_KEY_SHARE_DATA if no supported group has a key share,
  8017. * 0 if a supported group has a key share and other values indicate an error.
  8018. */
  8019. int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl, TLSX** extensions)
  8020. {
  8021. int ret;
  8022. #ifdef HAVE_SUPPORTED_CURVES
  8023. TLSX* extension;
  8024. SupportedCurve* curve = NULL;
  8025. SupportedCurve* preferredCurve = NULL;
  8026. KeyShareEntry* kse = NULL;
  8027. int preferredRank = WOLFSSL_MAX_GROUP_COUNT;
  8028. int rank;
  8029. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  8030. if (extension != NULL)
  8031. curve = (SupportedCurve*)extension->data;
  8032. /* Use server's preference order. */
  8033. for (; curve != NULL; curve = curve->next) {
  8034. if (!TLSX_KeyShare_IsSupported(curve->name))
  8035. continue;
  8036. if (wolfSSL_curve_is_disabled(ssl, curve->name))
  8037. continue;
  8038. rank = TLSX_KeyShare_GroupRank(ssl, curve->name);
  8039. if (rank == -1)
  8040. continue;
  8041. if (rank < preferredRank) {
  8042. preferredCurve = curve;
  8043. preferredRank = rank;
  8044. }
  8045. }
  8046. curve = preferredCurve;
  8047. if (curve == NULL) {
  8048. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  8049. return BAD_KEY_SHARE_DATA;
  8050. }
  8051. #ifdef WOLFSSL_ASYNC_CRYPT
  8052. /* Check the old key share data list. */
  8053. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  8054. if (extension != NULL) {
  8055. kse = (KeyShareEntry*)extension->data;
  8056. /* We should not be computing keys if we are only going to advertise
  8057. * our choice here. */
  8058. if (kse != NULL && kse->lastRet == WC_PENDING_E) {
  8059. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  8060. return BAD_KEY_SHARE_DATA;
  8061. }
  8062. }
  8063. #endif
  8064. /* Push new KeyShare extension. This will also free the old one */
  8065. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  8066. if (ret != 0)
  8067. return ret;
  8068. /* Extension got pushed to head */
  8069. extension = *extensions;
  8070. /* Push the selected curve */
  8071. ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, curve->name,
  8072. ssl->heap, &kse);
  8073. if (ret != 0)
  8074. return ret;
  8075. /* Set extension to be in response. */
  8076. extension->resp = 1;
  8077. #else
  8078. (void)ssl;
  8079. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  8080. ret = NOT_COMPILED_IN;
  8081. #endif
  8082. return ret;
  8083. }
  8084. /* Server side KSE processing */
  8085. int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions,
  8086. byte cipherSuite0, byte cipherSuite, KeyShareEntry** kse, byte* searched)
  8087. {
  8088. TLSX* extension;
  8089. KeyShareEntry* clientKSE = NULL;
  8090. KeyShareEntry* list = NULL;
  8091. KeyShareEntry* preferredKSE = NULL;
  8092. int preferredRank = WOLFSSL_MAX_GROUP_COUNT;
  8093. int rank;
  8094. (void)cipherSuite0;
  8095. (void)cipherSuite;
  8096. if (ssl == NULL || ssl->options.side != WOLFSSL_SERVER_END)
  8097. return BAD_FUNC_ARG;
  8098. *searched = 0;
  8099. /* Find the KeyShare extension if it exists. */
  8100. extension = TLSX_Find(extensions, TLSX_KEY_SHARE);
  8101. if (extension != NULL)
  8102. list = (KeyShareEntry*)extension->data;
  8103. if (extension && extension->resp == 1) {
  8104. /* Outside of the async case this path should not be taken. */
  8105. int ret = INCOMPLETE_DATA;
  8106. #ifdef WOLFSSL_ASYNC_CRYPT
  8107. /* in async case make sure key generation is finalized */
  8108. KeyShareEntry* serverKSE = (KeyShareEntry*)extension->data;
  8109. if (serverKSE && serverKSE->lastRet == WC_PENDING_E) {
  8110. if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
  8111. *searched = 1;
  8112. ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE);
  8113. }
  8114. #endif
  8115. return ret;
  8116. }
  8117. /* Use server's preference order. */
  8118. for (clientKSE = list; clientKSE != NULL; clientKSE = clientKSE->next) {
  8119. if (clientKSE->ke == NULL)
  8120. continue;
  8121. #ifdef WOLFSSL_SM2
  8122. if ((cipherSuite0 == CIPHER_BYTE) &&
  8123. ((cipherSuite == TLS_SM4_GCM_SM3) ||
  8124. (cipherSuite == TLS_SM4_CCM_SM3))) {
  8125. if (clientKSE->group != WOLFSSL_ECC_SM2P256V1) {
  8126. continue;
  8127. }
  8128. }
  8129. else if (clientKSE->group == WOLFSSL_ECC_SM2P256V1) {
  8130. continue;
  8131. }
  8132. #endif
  8133. /* Check consistency now - extensions in any order. */
  8134. if (!TLSX_SupportedGroups_Find(ssl, clientKSE->group, extensions))
  8135. continue;
  8136. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(clientKSE->group)) {
  8137. /* Check max value supported. */
  8138. if (clientKSE->group > WOLFSSL_ECC_MAX) {
  8139. #ifdef HAVE_PQC
  8140. if (!WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group))
  8141. #endif
  8142. continue;
  8143. }
  8144. if (wolfSSL_curve_is_disabled(ssl, clientKSE->group))
  8145. continue;
  8146. }
  8147. if (!TLSX_KeyShare_IsSupported(clientKSE->group))
  8148. continue;
  8149. rank = TLSX_KeyShare_GroupRank(ssl, clientKSE->group);
  8150. if (rank == -1)
  8151. continue;
  8152. if (rank < preferredRank) {
  8153. preferredKSE = clientKSE;
  8154. preferredRank = rank;
  8155. }
  8156. }
  8157. *kse = preferredKSE;
  8158. *searched = 1;
  8159. return 0;
  8160. }
  8161. /* Server side KSE processing */
  8162. int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE)
  8163. {
  8164. int ret;
  8165. TLSX* extension;
  8166. KeyShareEntry* serverKSE;
  8167. KeyShareEntry* list = NULL;
  8168. if (ssl == NULL || ssl->options.side != WOLFSSL_SERVER_END)
  8169. return BAD_FUNC_ARG;
  8170. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  8171. if (extension == NULL)
  8172. return BAD_STATE_E;
  8173. if (clientKSE == NULL) {
  8174. #ifdef WOLFSSL_ASYNC_CRYPT
  8175. /* Not necessarily an error. The key may have already been setup. */
  8176. if (extension != NULL && extension->resp == 1) {
  8177. serverKSE = (KeyShareEntry*)extension->data;
  8178. if (serverKSE != NULL) {
  8179. /* in async case make sure key generation is finalized */
  8180. if (serverKSE->lastRet == WC_PENDING_E)
  8181. return TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE);
  8182. else if (serverKSE->lastRet == 0)
  8183. return 0;
  8184. }
  8185. }
  8186. #endif
  8187. return BAD_FUNC_ARG;
  8188. }
  8189. /* Generate a new key pair except in the case of OQS KEM because we
  8190. * are going to encapsulate and that does not require us to generate a
  8191. * key pair.
  8192. */
  8193. ret = TLSX_KeyShare_New(&list, clientKSE->group, ssl->heap, &serverKSE);
  8194. if (ret != 0)
  8195. return ret;
  8196. if (clientKSE->key == NULL) {
  8197. #ifdef HAVE_PQC
  8198. if (WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group)) {
  8199. /* Going to need the public key (AKA ciphertext). */
  8200. serverKSE->pubKey = clientKSE->pubKey;
  8201. clientKSE->pubKey = NULL;
  8202. serverKSE->pubKeyLen = clientKSE->pubKeyLen;
  8203. clientKSE->pubKeyLen = 0;
  8204. }
  8205. else
  8206. #endif
  8207. {
  8208. ret = TLSX_KeyShare_GenKey(ssl, serverKSE);
  8209. }
  8210. /* for async do setup of serverKSE below, but return WC_PENDING_E */
  8211. if (ret != 0
  8212. #ifdef WOLFSSL_ASYNC_CRYPT
  8213. && ret != WC_PENDING_E
  8214. #endif
  8215. ) {
  8216. TLSX_KeyShare_FreeAll(list, ssl->heap);
  8217. return ret;
  8218. }
  8219. }
  8220. else {
  8221. /* transfer buffers to serverKSE */
  8222. serverKSE->key = clientKSE->key;
  8223. clientKSE->key = NULL;
  8224. serverKSE->keyLen = clientKSE->keyLen;
  8225. serverKSE->pubKey = clientKSE->pubKey;
  8226. clientKSE->pubKey = NULL;
  8227. serverKSE->pubKeyLen = clientKSE->pubKeyLen;
  8228. #ifndef NO_DH
  8229. serverKSE->privKey = clientKSE->privKey;
  8230. clientKSE->privKey = NULL;
  8231. #endif
  8232. }
  8233. serverKSE->ke = clientKSE->ke;
  8234. serverKSE->keLen = clientKSE->keLen;
  8235. clientKSE->ke = NULL;
  8236. clientKSE->keLen = 0;
  8237. ssl->namedGroup = serverKSE->group;
  8238. TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap);
  8239. extension->data = (void *)serverKSE;
  8240. extension->resp = 1;
  8241. return ret;
  8242. }
  8243. /* Ensure there is a key pair that can be used for key exchange.
  8244. *
  8245. * ssl The SSL/TLS object.
  8246. * doHelloRetry If set to non-zero will do hello_retry
  8247. * returns 0 on success and other values indicate failure.
  8248. */
  8249. int TLSX_KeyShare_Establish(WOLFSSL *ssl, int* doHelloRetry)
  8250. {
  8251. int ret;
  8252. KeyShareEntry* clientKSE = NULL;
  8253. byte searched = 0;
  8254. *doHelloRetry = 0;
  8255. ret = TLSX_KeyShare_Choose(ssl, ssl->extensions, ssl->cipher.cipherSuite0,
  8256. ssl->cipher.cipherSuite, &clientKSE, &searched);
  8257. if (ret != 0 || !searched)
  8258. return ret;
  8259. /* No supported group found - send HelloRetryRequest. */
  8260. if (clientKSE == NULL) {
  8261. /* Set KEY_SHARE_ERROR to indicate HelloRetryRequest required. */
  8262. *doHelloRetry = 1;
  8263. return TLSX_KeyShare_SetSupported(ssl, &ssl->extensions);
  8264. }
  8265. return TLSX_KeyShare_Setup(ssl, clientKSE);
  8266. }
  8267. /* Derive the shared secret of the key exchange.
  8268. *
  8269. * ssl The SSL/TLS object.
  8270. * returns 0 on success and other values indicate failure.
  8271. */
  8272. int TLSX_KeyShare_DeriveSecret(WOLFSSL *ssl)
  8273. {
  8274. int ret;
  8275. TLSX* extension;
  8276. KeyShareEntry* list = NULL;
  8277. #ifdef WOLFSSL_ASYNC_CRYPT
  8278. ret = wolfSSL_AsyncPop(ssl, NULL);
  8279. /* Check for error */
  8280. if (ret != WC_NO_PENDING_E && ret < 0) {
  8281. return ret;
  8282. }
  8283. #endif
  8284. /* Find the KeyShare extension if it exists. */
  8285. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  8286. if (extension != NULL)
  8287. list = (KeyShareEntry*)extension->data;
  8288. if (list == NULL)
  8289. return KEY_SHARE_ERROR;
  8290. /* Calculate secret. */
  8291. ret = TLSX_KeyShare_Process(ssl, list);
  8292. return ret;
  8293. }
  8294. #define KS_FREE_ALL TLSX_KeyShare_FreeAll
  8295. #define KS_GET_SIZE TLSX_KeyShare_GetSize
  8296. #define KS_WRITE TLSX_KeyShare_Write
  8297. #define KS_PARSE TLSX_KeyShare_Parse
  8298. #else
  8299. #define KS_FREE_ALL(a, b) WC_DO_NOTHING
  8300. #define KS_GET_SIZE(a, b) 0
  8301. #define KS_WRITE(a, b, c) 0
  8302. #define KS_PARSE(a, b, c, d) 0
  8303. #endif /* WOLFSSL_TLS13 */
  8304. /******************************************************************************/
  8305. /* Pre-Shared Key */
  8306. /******************************************************************************/
  8307. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  8308. /* Free the pre-shared key dynamic data.
  8309. *
  8310. * list The linked list of key share entry objects.
  8311. * heap The heap used for allocation.
  8312. */
  8313. static void TLSX_PreSharedKey_FreeAll(PreSharedKey* list, void* heap)
  8314. {
  8315. PreSharedKey* current;
  8316. while ((current = list) != NULL) {
  8317. list = current->next;
  8318. XFREE(current->identity, heap, DYNAMIC_TYPE_TLSX);
  8319. XFREE(current, heap, DYNAMIC_TYPE_TLSX);
  8320. }
  8321. (void)heap;
  8322. }
  8323. /* Get the size of the encoded pre shared key extension.
  8324. *
  8325. * list The linked list of pre-shared key extensions.
  8326. * msgType The type of the message this extension is being written into.
  8327. * returns the number of bytes of the encoded pre-shared key extension or
  8328. * SANITY_MSG_E to indicate invalid message type.
  8329. */
  8330. static int TLSX_PreSharedKey_GetSize(PreSharedKey* list, byte msgType,
  8331. word16* pSz)
  8332. {
  8333. if (msgType == client_hello) {
  8334. /* Length of identities + Length of binders. */
  8335. word16 len = OPAQUE16_LEN + OPAQUE16_LEN;
  8336. while (list != NULL) {
  8337. /* Each entry has: identity, ticket age and binder. */
  8338. len += OPAQUE16_LEN + list->identityLen + OPAQUE32_LEN +
  8339. OPAQUE8_LEN + (word16)list->binderLen;
  8340. list = list->next;
  8341. }
  8342. *pSz += len;
  8343. return 0;
  8344. }
  8345. if (msgType == server_hello) {
  8346. *pSz += OPAQUE16_LEN;
  8347. return 0;
  8348. }
  8349. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8350. return SANITY_MSG_E;
  8351. }
  8352. /* The number of bytes to be written for the binders.
  8353. *
  8354. * list The linked list of pre-shared key extensions.
  8355. * msgType The type of the message this extension is being written into.
  8356. * returns the number of bytes of the encoded pre-shared key extension or
  8357. * SANITY_MSG_E to indicate invalid message type.
  8358. */
  8359. int TLSX_PreSharedKey_GetSizeBinders(PreSharedKey* list, byte msgType,
  8360. word16* pSz)
  8361. {
  8362. word16 len;
  8363. if (msgType != client_hello) {
  8364. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8365. return SANITY_MSG_E;
  8366. }
  8367. /* Length of all binders. */
  8368. len = OPAQUE16_LEN;
  8369. while (list != NULL) {
  8370. len += OPAQUE8_LEN + (word16)list->binderLen;
  8371. list = list->next;
  8372. }
  8373. *pSz = len;
  8374. return 0;
  8375. }
  8376. /* Writes the pre-shared key extension into the output buffer - binders only.
  8377. * Assumes that the the output buffer is big enough to hold data.
  8378. *
  8379. * list The linked list of key share entries.
  8380. * output The buffer to write into.
  8381. * msgType The type of the message this extension is being written into.
  8382. * returns the number of bytes written into the buffer.
  8383. */
  8384. int TLSX_PreSharedKey_WriteBinders(PreSharedKey* list, byte* output,
  8385. byte msgType, word16* pSz)
  8386. {
  8387. PreSharedKey* current = list;
  8388. word16 idx = 0;
  8389. word16 lenIdx;
  8390. word16 len;
  8391. if (msgType != client_hello) {
  8392. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8393. return SANITY_MSG_E;
  8394. }
  8395. /* Skip length of all binders. */
  8396. lenIdx = idx;
  8397. idx += OPAQUE16_LEN;
  8398. while (current != NULL) {
  8399. /* Binder data length. */
  8400. output[idx++] = (byte)current->binderLen;
  8401. /* Binder data. */
  8402. XMEMCPY(output + idx, current->binder, current->binderLen);
  8403. idx += (word16)current->binderLen;
  8404. current = current->next;
  8405. }
  8406. /* Length of the binders. */
  8407. len = idx - lenIdx - OPAQUE16_LEN;
  8408. c16toa(len, output + lenIdx);
  8409. *pSz = idx;
  8410. return 0;
  8411. }
  8412. /* Writes the pre-shared key extension into the output buffer.
  8413. * Assumes that the the output buffer is big enough to hold data.
  8414. *
  8415. * list The linked list of key share entries.
  8416. * output The buffer to write into.
  8417. * msgType The type of the message this extension is being written into.
  8418. * returns the number of bytes written into the buffer.
  8419. */
  8420. static int TLSX_PreSharedKey_Write(PreSharedKey* list, byte* output,
  8421. byte msgType, word16* pSz)
  8422. {
  8423. if (msgType == client_hello) {
  8424. PreSharedKey* current = list;
  8425. word16 idx = 0;
  8426. word16 lenIdx;
  8427. word16 len;
  8428. int ret;
  8429. /* Write identities only. Binders after HMACing over this. */
  8430. lenIdx = idx;
  8431. idx += OPAQUE16_LEN;
  8432. while (current != NULL) {
  8433. /* Identity length */
  8434. c16toa(current->identityLen, output + idx);
  8435. idx += OPAQUE16_LEN;
  8436. /* Identity data */
  8437. XMEMCPY(output + idx, current->identity, current->identityLen);
  8438. idx += current->identityLen;
  8439. /* Obfuscated ticket age. */
  8440. c32toa(current->ticketAge, output + idx);
  8441. idx += OPAQUE32_LEN;
  8442. current = current->next;
  8443. }
  8444. /* Length of the identities. */
  8445. len = idx - lenIdx - OPAQUE16_LEN;
  8446. c16toa(len, output + lenIdx);
  8447. /* Don't include binders here.
  8448. * The binders are based on the hash of all the ClientHello data up to
  8449. * and include the identities written above.
  8450. */
  8451. ret = TLSX_PreSharedKey_GetSizeBinders(list, msgType, &len);
  8452. if (ret < 0)
  8453. return ret;
  8454. *pSz += idx + len;
  8455. }
  8456. else if (msgType == server_hello) {
  8457. word16 i;
  8458. /* Find the index of the chosen identity. */
  8459. for (i=0; list != NULL && !list->chosen; i++)
  8460. list = list->next;
  8461. if (list == NULL) {
  8462. WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR);
  8463. return BUILD_MSG_ERROR;
  8464. }
  8465. /* The index of the identity chosen by the server from the list supplied
  8466. * by the client.
  8467. */
  8468. c16toa(i, output);
  8469. *pSz += OPAQUE16_LEN;
  8470. }
  8471. else {
  8472. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8473. return SANITY_MSG_E;
  8474. }
  8475. return 0;
  8476. }
  8477. int TLSX_PreSharedKey_Parse_ClientHello(TLSX** extensions, const byte* input,
  8478. word16 length, void* heap)
  8479. {
  8480. int ret;
  8481. word16 len;
  8482. word16 idx = 0;
  8483. TLSX* extension;
  8484. PreSharedKey* list;
  8485. TLSX_Remove(extensions, TLSX_PRE_SHARED_KEY, heap);
  8486. /* Length of identities and of binders. */
  8487. if ((int)(length - idx) < OPAQUE16_LEN + OPAQUE16_LEN)
  8488. return BUFFER_E;
  8489. /* Length of identities. */
  8490. ato16(input + idx, &len);
  8491. idx += OPAQUE16_LEN;
  8492. if (len < MIN_PSK_ID_LEN || length - idx < len)
  8493. return BUFFER_E;
  8494. /* Create a pre-shared key object for each identity. */
  8495. while (len > 0) {
  8496. const byte* identity;
  8497. word16 identityLen;
  8498. word32 age;
  8499. if (len < OPAQUE16_LEN)
  8500. return BUFFER_E;
  8501. /* Length of identity. */
  8502. ato16(input + idx, &identityLen);
  8503. idx += OPAQUE16_LEN;
  8504. if (len < OPAQUE16_LEN + identityLen + OPAQUE32_LEN ||
  8505. identityLen > MAX_PSK_ID_LEN)
  8506. return BUFFER_E;
  8507. /* Cache identity pointer. */
  8508. identity = input + idx;
  8509. idx += identityLen;
  8510. /* Ticket age. */
  8511. ato32(input + idx, &age);
  8512. idx += OPAQUE32_LEN;
  8513. ret = TLSX_PreSharedKey_Use(extensions, identity, identityLen, age, no_mac,
  8514. 0, 0, 1, NULL, heap);
  8515. if (ret != 0)
  8516. return ret;
  8517. /* Done with this identity. */
  8518. len -= OPAQUE16_LEN + identityLen + OPAQUE32_LEN;
  8519. }
  8520. /* Find the list of identities sent to server. */
  8521. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8522. if (extension == NULL)
  8523. return PSK_KEY_ERROR;
  8524. list = (PreSharedKey*)extension->data;
  8525. /* Length of binders. */
  8526. if (idx + OPAQUE16_LEN > length)
  8527. return BUFFER_E;
  8528. ato16(input + idx, &len);
  8529. idx += OPAQUE16_LEN;
  8530. if (len < MIN_PSK_BINDERS_LEN || length - idx < len)
  8531. return BUFFER_E;
  8532. /* Set binder for each identity. */
  8533. while (list != NULL && len > 0) {
  8534. /* Length of binder */
  8535. list->binderLen = input[idx++];
  8536. if (list->binderLen < WC_SHA256_DIGEST_SIZE ||
  8537. list->binderLen > WC_MAX_DIGEST_SIZE)
  8538. return BUFFER_E;
  8539. if (len < OPAQUE8_LEN + list->binderLen)
  8540. return BUFFER_E;
  8541. /* Copy binder into static buffer. */
  8542. XMEMCPY(list->binder, input + idx, list->binderLen);
  8543. idx += (word16)list->binderLen;
  8544. /* Done with binder entry. */
  8545. len -= OPAQUE8_LEN + (word16)list->binderLen;
  8546. /* Next identity. */
  8547. list = list->next;
  8548. }
  8549. if (list != NULL || len != 0)
  8550. return BUFFER_E;
  8551. return 0;
  8552. }
  8553. /* Parse the pre-shared key extension.
  8554. * Different formats in different messages.
  8555. *
  8556. * ssl The SSL/TLS object.
  8557. * input The extension data.
  8558. * length The length of the extension data.
  8559. * msgType The type of the message this extension is being parsed from.
  8560. * returns 0 on success and other values indicate failure.
  8561. */
  8562. static int TLSX_PreSharedKey_Parse(WOLFSSL* ssl, const byte* input,
  8563. word16 length, byte msgType)
  8564. {
  8565. if (msgType == client_hello) {
  8566. return TLSX_PreSharedKey_Parse_ClientHello(&ssl->extensions, input,
  8567. length, ssl->heap);
  8568. }
  8569. if (msgType == server_hello) {
  8570. word16 idx;
  8571. PreSharedKey* list;
  8572. TLSX* extension;
  8573. /* Index of identity chosen by server. */
  8574. if (length != OPAQUE16_LEN)
  8575. return BUFFER_E;
  8576. ato16(input, &idx);
  8577. #ifdef WOLFSSL_EARLY_DATA
  8578. ssl->options.pskIdIndex = idx + 1;
  8579. #endif
  8580. /* Find the list of identities sent to server. */
  8581. extension = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  8582. if (extension == NULL)
  8583. return PSK_KEY_ERROR;
  8584. list = (PreSharedKey*)extension->data;
  8585. /* Mark the identity as chosen. */
  8586. for (; list != NULL && idx > 0; idx--)
  8587. list = list->next;
  8588. if (list == NULL) {
  8589. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8590. return PSK_KEY_ERROR;
  8591. }
  8592. list->chosen = 1;
  8593. #ifdef HAVE_SESSION_TICKET
  8594. if (list->resumption) {
  8595. /* Check that the session's details are the same as the server's. */
  8596. if (ssl->options.cipherSuite0 != ssl->session->cipherSuite0 ||
  8597. ssl->options.cipherSuite != ssl->session->cipherSuite ||
  8598. ssl->session->version.major != ssl->ctx->method->version.major ||
  8599. ssl->session->version.minor != ssl->ctx->method->version.minor) {
  8600. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8601. return PSK_KEY_ERROR;
  8602. }
  8603. }
  8604. #endif
  8605. return 0;
  8606. }
  8607. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8608. return SANITY_MSG_E;
  8609. }
  8610. /* Create a new pre-shared key and put it into the list.
  8611. *
  8612. * list The linked list of pre-shared key.
  8613. * identity The identity.
  8614. * len The length of the identity data.
  8615. * heap The memory to allocate with.
  8616. * preSharedKey The new pre-shared key object.
  8617. * returns 0 on success and other values indicate failure.
  8618. */
  8619. static int TLSX_PreSharedKey_New(PreSharedKey** list, const byte* identity,
  8620. word16 len, void *heap,
  8621. PreSharedKey** preSharedKey)
  8622. {
  8623. PreSharedKey* psk;
  8624. PreSharedKey** next;
  8625. psk = (PreSharedKey*)XMALLOC(sizeof(PreSharedKey), heap, DYNAMIC_TYPE_TLSX);
  8626. if (psk == NULL)
  8627. return MEMORY_E;
  8628. XMEMSET(psk, 0, sizeof(*psk));
  8629. /* Make a copy of the identity data. */
  8630. psk->identity = (byte*)XMALLOC(len + NULL_TERM_LEN, heap,
  8631. DYNAMIC_TYPE_TLSX);
  8632. if (psk->identity == NULL) {
  8633. XFREE(psk, heap, DYNAMIC_TYPE_TLSX);
  8634. return MEMORY_E;
  8635. }
  8636. XMEMCPY(psk->identity, identity, len);
  8637. psk->identityLen = len;
  8638. /* Use a NULL terminator in case it is a C string */
  8639. psk->identity[psk->identityLen] = '\0';
  8640. /* Add it to the end and maintain the links. */
  8641. while (*list != NULL) {
  8642. /* Assign to temporary to work around compiler bug found by customer. */
  8643. next = &((*list)->next);
  8644. list = next;
  8645. }
  8646. *list = psk;
  8647. *preSharedKey = psk;
  8648. (void)heap;
  8649. return 0;
  8650. }
  8651. static WC_INLINE byte GetHmacLength(int hmac)
  8652. {
  8653. switch (hmac) {
  8654. #ifndef NO_SHA256
  8655. case sha256_mac:
  8656. return WC_SHA256_DIGEST_SIZE;
  8657. #endif
  8658. #ifdef WOLFSSL_SHA384
  8659. case sha384_mac:
  8660. return WC_SHA384_DIGEST_SIZE;
  8661. #endif
  8662. #ifdef WOLFSSL_SHA512
  8663. case sha512_mac:
  8664. return WC_SHA512_DIGEST_SIZE;
  8665. #endif
  8666. #ifdef WOLFSSL_SM3
  8667. case sm3_mac:
  8668. return WC_SM3_DIGEST_SIZE;
  8669. #endif
  8670. default:
  8671. break;
  8672. }
  8673. return 0;
  8674. }
  8675. /* Use the data to create a new pre-shared key object in the extensions.
  8676. *
  8677. * ssl The SSL/TLS object.
  8678. * identity The identity.
  8679. * len The length of the identity data.
  8680. * age The age of the identity.
  8681. * hmac The HMAC algorithm.
  8682. * cipherSuite0 The first byte of the cipher suite to use.
  8683. * cipherSuite The second byte of the cipher suite to use.
  8684. * resumption The PSK is for resumption of a session.
  8685. * preSharedKey The new pre-shared key object.
  8686. * returns 0 on success and other values indicate failure.
  8687. */
  8688. int TLSX_PreSharedKey_Use(TLSX** extensions, const byte* identity, word16 len,
  8689. word32 age, byte hmac, byte cipherSuite0,
  8690. byte cipherSuite, byte resumption,
  8691. PreSharedKey **preSharedKey, void* heap)
  8692. {
  8693. int ret = 0;
  8694. TLSX* extension;
  8695. PreSharedKey* psk = NULL;
  8696. /* Find the pre-shared key extension if it exists. */
  8697. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8698. if (extension == NULL) {
  8699. /* Push new pre-shared key extension. */
  8700. ret = TLSX_Push(extensions, TLSX_PRE_SHARED_KEY, NULL, heap);
  8701. if (ret != 0)
  8702. return ret;
  8703. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8704. if (extension == NULL)
  8705. return MEMORY_E;
  8706. }
  8707. /* Try to find the pre-shared key with this identity. */
  8708. psk = (PreSharedKey*)extension->data;
  8709. while (psk != NULL) {
  8710. if ((psk->identityLen == len) &&
  8711. (XMEMCMP(psk->identity, identity, len) == 0)) {
  8712. break;
  8713. }
  8714. psk = psk->next;
  8715. }
  8716. /* Create a new pre-shared key object if not found. */
  8717. if (psk == NULL) {
  8718. ret = TLSX_PreSharedKey_New((PreSharedKey**)&extension->data, identity,
  8719. len, heap, &psk);
  8720. if (ret != 0)
  8721. return ret;
  8722. }
  8723. /* Update/set age and HMAC algorithm. */
  8724. psk->ticketAge = age;
  8725. psk->hmac = hmac;
  8726. psk->cipherSuite0 = cipherSuite0;
  8727. psk->cipherSuite = cipherSuite;
  8728. psk->resumption = resumption;
  8729. psk->binderLen = GetHmacLength(psk->hmac);
  8730. if (preSharedKey != NULL)
  8731. *preSharedKey = psk;
  8732. return 0;
  8733. }
  8734. #define PSK_FREE_ALL TLSX_PreSharedKey_FreeAll
  8735. #define PSK_GET_SIZE TLSX_PreSharedKey_GetSize
  8736. #define PSK_WRITE TLSX_PreSharedKey_Write
  8737. #define PSK_PARSE TLSX_PreSharedKey_Parse
  8738. #else
  8739. #define PSK_FREE_ALL(a, b) WC_DO_NOTHING
  8740. #define PSK_GET_SIZE(a, b, c) 0
  8741. #define PSK_WRITE(a, b, c, d) 0
  8742. #define PSK_PARSE(a, b, c, d) 0
  8743. #endif
  8744. /******************************************************************************/
  8745. /* PSK Key Exchange Modes */
  8746. /******************************************************************************/
  8747. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  8748. /* Get the size of the encoded PSK KE modes extension.
  8749. * Only in ClientHello.
  8750. *
  8751. * modes The PSK KE mode bit string.
  8752. * msgType The type of the message this extension is being written into.
  8753. * returns the number of bytes of the encoded PSK KE mode extension.
  8754. */
  8755. static int TLSX_PskKeModes_GetSize(byte modes, byte msgType, word16* pSz)
  8756. {
  8757. if (msgType == client_hello) {
  8758. /* Format: Len | Modes* */
  8759. word16 len = OPAQUE8_LEN;
  8760. /* Check whether each possible mode is to be written. */
  8761. if (modes & (1 << PSK_KE))
  8762. len += OPAQUE8_LEN;
  8763. if (modes & (1 << PSK_DHE_KE))
  8764. len += OPAQUE8_LEN;
  8765. *pSz += len;
  8766. return 0;
  8767. }
  8768. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8769. return SANITY_MSG_E;
  8770. }
  8771. /* Writes the PSK KE modes extension into the output buffer.
  8772. * Assumes that the the output buffer is big enough to hold data.
  8773. * Only in ClientHello.
  8774. *
  8775. * modes The PSK KE mode bit string.
  8776. * output The buffer to write into.
  8777. * msgType The type of the message this extension is being written into.
  8778. * returns the number of bytes written into the buffer.
  8779. */
  8780. static int TLSX_PskKeModes_Write(byte modes, byte* output, byte msgType,
  8781. word16* pSz)
  8782. {
  8783. if (msgType == client_hello) {
  8784. /* Format: Len | Modes* */
  8785. word16 idx = OPAQUE8_LEN;
  8786. /* Write out each possible mode. */
  8787. if (modes & (1 << PSK_KE))
  8788. output[idx++] = PSK_KE;
  8789. if (modes & (1 << PSK_DHE_KE))
  8790. output[idx++] = PSK_DHE_KE;
  8791. /* Write out length of mode list. */
  8792. output[0] = (byte)(idx - OPAQUE8_LEN);
  8793. *pSz += idx;
  8794. return 0;
  8795. }
  8796. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8797. return SANITY_MSG_E;
  8798. }
  8799. int TLSX_PskKeyModes_Parse_Modes(const byte* input, word16 length, byte msgType,
  8800. byte* modes)
  8801. {
  8802. if (msgType == client_hello) {
  8803. /* Format: Len | Modes* */
  8804. int idx = 0;
  8805. word16 len;
  8806. *modes = 0;
  8807. /* Ensure length byte exists. */
  8808. if (length < OPAQUE8_LEN)
  8809. return BUFFER_E;
  8810. /* Get length of mode list and ensure that is the only data. */
  8811. len = input[0];
  8812. if (length - OPAQUE8_LEN != len)
  8813. return BUFFER_E;
  8814. idx = OPAQUE8_LEN;
  8815. /* Set a bit for each recognized modes. */
  8816. while (len > 0) {
  8817. /* Ignore unrecognized modes. */
  8818. if (input[idx] <= PSK_DHE_KE)
  8819. *modes |= 1 << input[idx];
  8820. idx++;
  8821. len--;
  8822. }
  8823. return 0;
  8824. }
  8825. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8826. return SANITY_MSG_E;
  8827. }
  8828. /* Parse the PSK KE modes extension.
  8829. * Only in ClientHello.
  8830. *
  8831. * ssl The SSL/TLS object.
  8832. * input The extension data.
  8833. * length The length of the extension data.
  8834. * msgType The type of the message this extension is being parsed from.
  8835. * returns 0 on success and other values indicate failure.
  8836. */
  8837. static int TLSX_PskKeModes_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  8838. byte msgType)
  8839. {
  8840. int ret;
  8841. byte modes;
  8842. ret = TLSX_PskKeyModes_Parse_Modes(input, length, msgType, &modes);
  8843. if (ret == 0)
  8844. ret = TLSX_PskKeyModes_Use(ssl, modes);
  8845. if (ret != 0) {
  8846. WOLFSSL_ERROR_VERBOSE(ret);
  8847. }
  8848. return ret;
  8849. }
  8850. /* Use the data to create a new PSK Key Exchange Modes object in the extensions.
  8851. *
  8852. * ssl The SSL/TLS object.
  8853. * modes The PSK key exchange modes.
  8854. * returns 0 on success and other values indicate failure.
  8855. */
  8856. int TLSX_PskKeyModes_Use(WOLFSSL* ssl, byte modes)
  8857. {
  8858. int ret = 0;
  8859. TLSX* extension;
  8860. /* Find the PSK key exchange modes extension if it exists. */
  8861. extension = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  8862. if (extension == NULL) {
  8863. /* Push new PSK key exchange modes extension. */
  8864. ret = TLSX_Push(&ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES, NULL,
  8865. ssl->heap);
  8866. if (ret != 0)
  8867. return ret;
  8868. extension = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  8869. if (extension == NULL)
  8870. return MEMORY_E;
  8871. }
  8872. extension->val = modes;
  8873. return 0;
  8874. }
  8875. #define PKM_GET_SIZE TLSX_PskKeModes_GetSize
  8876. #define PKM_WRITE TLSX_PskKeModes_Write
  8877. #define PKM_PARSE TLSX_PskKeModes_Parse
  8878. #else
  8879. #define PKM_GET_SIZE(a, b, c) 0
  8880. #define PKM_WRITE(a, b, c, d) 0
  8881. #define PKM_PARSE(a, b, c, d) 0
  8882. #endif
  8883. /******************************************************************************/
  8884. /* Post-Handshake Authentication */
  8885. /******************************************************************************/
  8886. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  8887. /* Get the size of the encoded Post-Handshake Authentication extension.
  8888. * Only in ClientHello.
  8889. *
  8890. * msgType The type of the message this extension is being written into.
  8891. * returns the number of bytes of the encoded Post-Handshake Authentication
  8892. * extension.
  8893. */
  8894. static int TLSX_PostHandAuth_GetSize(byte msgType, word16* pSz)
  8895. {
  8896. if (msgType == client_hello) {
  8897. *pSz += 0;
  8898. return 0;
  8899. }
  8900. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8901. return SANITY_MSG_E;
  8902. }
  8903. /* Writes the Post-Handshake Authentication extension into the output buffer.
  8904. * Assumes that the the output buffer is big enough to hold data.
  8905. * Only in ClientHello.
  8906. *
  8907. * output The buffer to write into.
  8908. * msgType The type of the message this extension is being written into.
  8909. * returns the number of bytes written into the buffer.
  8910. */
  8911. static int TLSX_PostHandAuth_Write(byte* output, byte msgType, word16* pSz)
  8912. {
  8913. (void)output;
  8914. if (msgType == client_hello) {
  8915. *pSz += 0;
  8916. return 0;
  8917. }
  8918. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8919. return SANITY_MSG_E;
  8920. }
  8921. /* Parse the Post-Handshake Authentication extension.
  8922. * Only in ClientHello.
  8923. *
  8924. * ssl The SSL/TLS object.
  8925. * input The extension data.
  8926. * length The length of the extension data.
  8927. * msgType The type of the message this extension is being parsed from.
  8928. * returns 0 on success and other values indicate failure.
  8929. */
  8930. static int TLSX_PostHandAuth_Parse(WOLFSSL* ssl, const byte* input,
  8931. word16 length, byte msgType)
  8932. {
  8933. (void)input;
  8934. if (msgType == client_hello) {
  8935. /* Ensure extension is empty. */
  8936. if (length != 0)
  8937. return BUFFER_E;
  8938. ssl->options.postHandshakeAuth = 1;
  8939. return 0;
  8940. }
  8941. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8942. return SANITY_MSG_E;
  8943. }
  8944. /* Create a new Post-handshake authentication object in the extensions.
  8945. *
  8946. * ssl The SSL/TLS object.
  8947. * returns 0 on success and other values indicate failure.
  8948. */
  8949. static int TLSX_PostHandAuth_Use(WOLFSSL* ssl)
  8950. {
  8951. int ret = 0;
  8952. TLSX* extension;
  8953. /* Find the PSK key exchange modes extension if it exists. */
  8954. extension = TLSX_Find(ssl->extensions, TLSX_POST_HANDSHAKE_AUTH);
  8955. if (extension == NULL) {
  8956. /* Push new Post-handshake Authentication extension. */
  8957. ret = TLSX_Push(&ssl->extensions, TLSX_POST_HANDSHAKE_AUTH, NULL,
  8958. ssl->heap);
  8959. if (ret != 0)
  8960. return ret;
  8961. }
  8962. return 0;
  8963. }
  8964. #define PHA_GET_SIZE TLSX_PostHandAuth_GetSize
  8965. #define PHA_WRITE TLSX_PostHandAuth_Write
  8966. #define PHA_PARSE TLSX_PostHandAuth_Parse
  8967. #else
  8968. #define PHA_GET_SIZE(a, b) 0
  8969. #define PHA_WRITE(a, b, c) 0
  8970. #define PHA_PARSE(a, b, c, d) 0
  8971. #endif
  8972. /******************************************************************************/
  8973. /* Early Data Indication */
  8974. /******************************************************************************/
  8975. #ifdef WOLFSSL_EARLY_DATA
  8976. /* Get the size of the encoded Early Data Indication extension.
  8977. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  8978. *
  8979. * msgType The type of the message this extension is being written into.
  8980. * returns the number of bytes of the encoded Early Data Indication extension.
  8981. */
  8982. static int TLSX_EarlyData_GetSize(byte msgType, word16* pSz)
  8983. {
  8984. int ret = 0;
  8985. if (msgType == client_hello || msgType == encrypted_extensions)
  8986. *pSz += 0;
  8987. else if (msgType == session_ticket)
  8988. *pSz += OPAQUE32_LEN;
  8989. else {
  8990. ret = SANITY_MSG_E;
  8991. WOLFSSL_ERROR_VERBOSE(ret);
  8992. }
  8993. return ret;
  8994. }
  8995. /* Writes the Early Data Indicator extension into the output buffer.
  8996. * Assumes that the the output buffer is big enough to hold data.
  8997. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  8998. *
  8999. * maxSz The maximum early data size.
  9000. * output The buffer to write into.
  9001. * msgType The type of the message this extension is being written into.
  9002. * returns the number of bytes written into the buffer.
  9003. */
  9004. static int TLSX_EarlyData_Write(word32 maxSz, byte* output, byte msgType,
  9005. word16* pSz)
  9006. {
  9007. if (msgType == client_hello || msgType == encrypted_extensions)
  9008. return 0;
  9009. else if (msgType == session_ticket) {
  9010. c32toa(maxSz, output);
  9011. *pSz += OPAQUE32_LEN;
  9012. return 0;
  9013. }
  9014. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9015. return SANITY_MSG_E;
  9016. }
  9017. /* Parse the Early Data Indicator extension.
  9018. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  9019. *
  9020. * ssl The SSL/TLS object.
  9021. * input The extension data.
  9022. * length The length of the extension data.
  9023. * msgType The type of the message this extension is being parsed from.
  9024. * returns 0 on success and other values indicate failure.
  9025. */
  9026. static int TLSX_EarlyData_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  9027. byte msgType)
  9028. {
  9029. WOLFSSL_ENTER("TLSX_EarlyData_Parse");
  9030. if (msgType == client_hello) {
  9031. if (length != 0)
  9032. return BUFFER_E;
  9033. if (ssl->earlyData == expecting_early_data) {
  9034. if (ssl->options.maxEarlyDataSz != 0)
  9035. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_ACCEPTED;
  9036. else
  9037. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_REJECTED;
  9038. return TLSX_EarlyData_Use(ssl, 0, 0);
  9039. }
  9040. ssl->earlyData = early_data_ext;
  9041. return 0;
  9042. }
  9043. if (msgType == encrypted_extensions) {
  9044. if (length != 0)
  9045. return BUFFER_E;
  9046. /* Ensure the index of PSK identity chosen by server is 0.
  9047. * Index is plus one to handle 'not set' value of 0.
  9048. */
  9049. if (ssl->options.pskIdIndex != 1) {
  9050. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  9051. return PSK_KEY_ERROR;
  9052. }
  9053. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  9054. /* the extension from server comes in */
  9055. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_ACCEPTED;
  9056. }
  9057. return TLSX_EarlyData_Use(ssl, 1, 1);
  9058. }
  9059. if (msgType == session_ticket) {
  9060. word32 maxSz;
  9061. if (length != OPAQUE32_LEN)
  9062. return BUFFER_E;
  9063. ato32(input, &maxSz);
  9064. ssl->session->maxEarlyDataSz = maxSz;
  9065. return 0;
  9066. }
  9067. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9068. return SANITY_MSG_E;
  9069. }
  9070. /* Use the data to create a new Early Data object in the extensions.
  9071. *
  9072. * ssl The SSL/TLS object.
  9073. * maxSz The maximum early data size.
  9074. * is_response if this extension is part of a response
  9075. * returns 0 on success and other values indicate failure.
  9076. */
  9077. int TLSX_EarlyData_Use(WOLFSSL* ssl, word32 maxSz, int is_response)
  9078. {
  9079. int ret = 0;
  9080. TLSX* extension;
  9081. /* Find the early data extension if it exists. */
  9082. extension = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  9083. if (extension == NULL) {
  9084. /* Push new early data extension. */
  9085. ret = TLSX_Push(&ssl->extensions, TLSX_EARLY_DATA, NULL, ssl->heap);
  9086. if (ret != 0)
  9087. return ret;
  9088. extension = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  9089. if (extension == NULL)
  9090. return MEMORY_E;
  9091. }
  9092. extension->resp = is_response;
  9093. /* In QUIC, earlydata size is either 0 or 0xffffffff.
  9094. * Override any size between, possibly left from our initial value */
  9095. extension->val = (WOLFSSL_IS_QUIC(ssl) && is_response && maxSz > 0) ?
  9096. WOLFSSL_MAX_32BIT : maxSz;
  9097. return 0;
  9098. }
  9099. #define EDI_GET_SIZE TLSX_EarlyData_GetSize
  9100. #define EDI_WRITE TLSX_EarlyData_Write
  9101. #define EDI_PARSE TLSX_EarlyData_Parse
  9102. #else
  9103. #define EDI_GET_SIZE(a, b) 0
  9104. #define EDI_WRITE(a, b, c, d) 0
  9105. #define EDI_PARSE(a, b, c, d) 0
  9106. #endif
  9107. /******************************************************************************/
  9108. /* QUIC transport parameter extension */
  9109. /******************************************************************************/
  9110. #ifdef WOLFSSL_QUIC
  9111. static word16 TLSX_QuicTP_GetSize(TLSX* extension)
  9112. {
  9113. const QuicTransportParam *tp = (QuicTransportParam*)extension->data;
  9114. return tp ? tp->len : 0;
  9115. }
  9116. int TLSX_QuicTP_Use(WOLFSSL* ssl, TLSX_Type ext_type, int is_response)
  9117. {
  9118. int ret = 0;
  9119. TLSX* extension;
  9120. WOLFSSL_ENTER("TLSX_QuicTP_Use");
  9121. if (ssl->quic.transport_local == NULL) {
  9122. /* RFC9000, ch 7.3: "An endpoint MUST treat the absence of [...]
  9123. * from either endpoint [...] as a connection error of type
  9124. * TRANSPORT_PARAMETER_ERROR."
  9125. */
  9126. ret = QUIC_TP_MISSING_E;
  9127. goto cleanup;
  9128. }
  9129. extension = TLSX_Find(ssl->extensions, ext_type);
  9130. if (extension == NULL) {
  9131. ret = TLSX_Push(&ssl->extensions, ext_type, NULL, ssl->heap);
  9132. if (ret != 0)
  9133. goto cleanup;
  9134. extension = TLSX_Find(ssl->extensions, ext_type);
  9135. if (extension == NULL) {
  9136. ret = MEMORY_E;
  9137. goto cleanup;
  9138. }
  9139. }
  9140. if (extension->data) {
  9141. QuicTransportParam_free((QuicTransportParam*)extension->data, ssl->heap);
  9142. extension->data = NULL;
  9143. }
  9144. extension->resp = is_response;
  9145. extension->data = (void*)QuicTransportParam_dup(ssl->quic.transport_local, ssl->heap);
  9146. if (!extension->data) {
  9147. ret = MEMORY_E;
  9148. goto cleanup;
  9149. }
  9150. cleanup:
  9151. WOLFSSL_LEAVE("TLSX_QuicTP_Use", ret);
  9152. return ret;
  9153. }
  9154. static word16 TLSX_QuicTP_Write(QuicTransportParam *tp, byte* output)
  9155. {
  9156. word16 len = 0;
  9157. WOLFSSL_ENTER("TLSX_QuicTP_Write");
  9158. if (tp && tp->len) {
  9159. XMEMCPY(output, tp->data, tp->len);
  9160. len = tp->len;
  9161. }
  9162. WOLFSSL_LEAVE("TLSX_QuicTP_Write", len);
  9163. return len;
  9164. }
  9165. static int TLSX_QuicTP_Parse(WOLFSSL *ssl, const byte *input, size_t len, int ext_type, int msgType)
  9166. {
  9167. const QuicTransportParam *tp, **ptp;
  9168. (void)msgType;
  9169. tp = QuicTransportParam_new(input, len, ssl->heap);
  9170. if (!tp) {
  9171. return MEMORY_E;
  9172. }
  9173. ptp = (ext_type == TLSX_KEY_QUIC_TP_PARAMS_DRAFT) ?
  9174. &ssl->quic.transport_peer_draft : &ssl->quic.transport_peer;
  9175. if (*ptp) {
  9176. QTP_FREE(*ptp, ssl->heap);
  9177. }
  9178. *ptp = tp;
  9179. return 0;
  9180. }
  9181. #define QTP_GET_SIZE TLSX_QuicTP_GetSize
  9182. #define QTP_USE TLSX_QuicTP_Use
  9183. #define QTP_WRITE TLSX_QuicTP_Write
  9184. #define QTP_PARSE TLSX_QuicTP_Parse
  9185. #endif /* WOLFSSL_QUIC */
  9186. #if defined(WOLFSSL_DTLS_CID)
  9187. #define CID_GET_SIZE TLSX_ConnectionID_GetSize
  9188. #define CID_WRITE TLSX_ConnectionID_Write
  9189. #define CID_PARSE TLSX_ConnectionID_Parse
  9190. #define CID_FREE TLSX_ConnectionID_Free
  9191. #else
  9192. #define CID_GET_SIZE(a) 0
  9193. #define CID_WRITE(a, b) 0
  9194. #define CID_PARSE(a, b, c, d) 0
  9195. #define CID_FREE(a, b) 0
  9196. #endif /* defined(WOLFSSL_DTLS_CID) */
  9197. #if defined(HAVE_RPK)
  9198. /******************************************************************************/
  9199. /* Client_Certificate_Type extension */
  9200. /******************************************************************************/
  9201. /* return 1 if specified type is included in the given list, otherwise 0 */
  9202. static int IsCertTypeListed(byte type, byte cnt, const byte* list)
  9203. {
  9204. int ret = 0;
  9205. int i;
  9206. if (cnt == 0 || list == NULL)
  9207. return ret;
  9208. if (cnt > 0 && cnt <= MAX_CLIENT_CERT_TYPE_CNT) {
  9209. for (i = 0; i < cnt; i++) {
  9210. if (list[i] == type)
  9211. return 1;
  9212. }
  9213. }
  9214. return 0;
  9215. }
  9216. /* Search both arrays from above to find a common value between the two given
  9217. * arrays(a and b). return 1 if it finds a common value, otherwise return 0.
  9218. */
  9219. static int GetCommonItem(const byte* a, byte aLen, const byte* b, byte bLen,
  9220. byte* type)
  9221. {
  9222. int i, j;
  9223. if (a == NULL || b == NULL)
  9224. return 0;
  9225. for (i = 0; i < aLen; i++) {
  9226. for (j = 0; j < bLen; j++) {
  9227. if (a[i] == b[j]) {
  9228. *type = a[i];
  9229. return 1;
  9230. }
  9231. }
  9232. }
  9233. return 0;
  9234. }
  9235. /* Creates a "client certificate type" extension if necessary.
  9236. * Returns 0 if no error occurred, negative value otherwise.
  9237. * A return of 0, it does not indicae that the extension was created.
  9238. */
  9239. static int TLSX_ClientCertificateType_Use(WOLFSSL* ssl, byte isServer)
  9240. {
  9241. int ret = 0;
  9242. if (ssl == NULL)
  9243. return BAD_FUNC_ARG;
  9244. if (isServer) {
  9245. /* [in server side]
  9246. */
  9247. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_RPK,
  9248. ssl->options.rpkConfig.preferred_ClientCertTypeCnt,
  9249. ssl->options.rpkConfig.preferred_ClientCertTypes)) {
  9250. WOLFSSL_MSG("Adding Client Certificate Type extension");
  9251. ret = TLSX_Push(&ssl->extensions, TLSX_CLIENT_CERTIFICATE_TYPE, ssl,
  9252. ssl->heap);
  9253. if (ret == 0) {
  9254. TLSX_SetResponse(ssl, TLSX_CLIENT_CERTIFICATE_TYPE);
  9255. }
  9256. }
  9257. }
  9258. else {
  9259. /* [in client side]
  9260. * This extension MUST be omitted from the ClientHello unless the RPK
  9261. * certificate is preferred by the user and actually loaded.
  9262. */
  9263. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_RPK,
  9264. ssl->options.rpkConfig.preferred_ClientCertTypeCnt,
  9265. ssl->options.rpkConfig.preferred_ClientCertTypes)) {
  9266. if (ssl->options.rpkState.isRPKLoaded) {
  9267. ssl->options.rpkState.sending_ClientCertTypeCnt = 1;
  9268. ssl->options.rpkState.sending_ClientCertTypes[0] =
  9269. WOLFSSL_CERT_TYPE_RPK;
  9270. /* Push new client_certificate_type extension. */
  9271. WOLFSSL_MSG("Adding Client Certificate Type extension");
  9272. ret = TLSX_Push(&ssl->extensions, TLSX_CLIENT_CERTIFICATE_TYPE,
  9273. ssl, ssl->heap);
  9274. }
  9275. else {
  9276. WOLFSSL_MSG("Willing to use RPK cert but not loaded it");
  9277. }
  9278. }
  9279. else {
  9280. WOLFSSL_MSG("No will to use RPK cert");
  9281. }
  9282. }
  9283. return ret;
  9284. }
  9285. /* Parse a "client certificate type" extension received from peer.
  9286. * returns 0 on success and other values indicate failure.
  9287. */
  9288. static int TLSX_ClientCertificateType_Parse(WOLFSSL* ssl, const byte* input,
  9289. word16 length, byte msgType)
  9290. {
  9291. byte typeCnt;
  9292. int idx = 0;
  9293. int ret = 0;
  9294. int i;
  9295. int populate = 0;
  9296. byte cmnType;
  9297. if (msgType == client_hello) {
  9298. /* [parse ClientHello in server end]
  9299. * case 1) if peer verify is disabled, this extension must be omitted
  9300. * from ServerHello.
  9301. * case 2) if user have not set his preference, find X509 in parsed
  9302. * result, then populate "Client Certificate Type" extension.
  9303. * case 3) if user have not set his preference and X509 isn't included
  9304. * in parsed result, send "unsupported certificate" alert.
  9305. * case 4) if user have set his preference, find a common cert type
  9306. * in users preference and received cert types.
  9307. * case 5) if user have set his preference, but no common cert type
  9308. * found.
  9309. */
  9310. /* case 1 */
  9311. if (ssl->options.verifyNone) {
  9312. return ret;
  9313. }
  9314. /* parse extension */
  9315. if (length < OPAQUE8_LEN)
  9316. return BUFFER_E;
  9317. typeCnt = input[idx];
  9318. if (typeCnt > MAX_CLIENT_CERT_TYPE_CNT)
  9319. return BUFFER_E;
  9320. if ((typeCnt + 1) * OPAQUE8_LEN != length){
  9321. return BUFFER_E;
  9322. }
  9323. ssl->options.rpkState.received_ClientCertTypeCnt = input[idx];
  9324. idx += OPAQUE8_LEN;
  9325. for (i = 0; i < typeCnt; i++) {
  9326. ssl->options.rpkState.received_ClientCertTypes[i] = input[idx];
  9327. idx += OPAQUE8_LEN;
  9328. }
  9329. if (ssl->options.rpkConfig.preferred_ClientCertTypeCnt == 0) {
  9330. /* case 2 */
  9331. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_X509,
  9332. ssl->options.rpkState.received_ClientCertTypeCnt,
  9333. ssl->options.rpkState.received_ClientCertTypes)) {
  9334. ssl->options.rpkState.sending_ClientCertTypeCnt = 1;
  9335. ssl->options.rpkState.sending_ClientCertTypes[0] =
  9336. WOLFSSL_CERT_TYPE_X509;
  9337. populate = 1;
  9338. }
  9339. /* case 3 */
  9340. else {
  9341. WOLFSSL_MSG("No common cert type found in client_certificate_type ext");
  9342. SendAlert(ssl, alert_fatal, unsupported_certificate);
  9343. return UNSUPPORTED_CERTIFICATE;
  9344. }
  9345. }
  9346. else if (ssl->options.rpkConfig.preferred_ClientCertTypeCnt > 0) {
  9347. /* case 4 */
  9348. if (GetCommonItem(
  9349. ssl->options.rpkConfig.preferred_ClientCertTypes,
  9350. ssl->options.rpkConfig.preferred_ClientCertTypeCnt,
  9351. ssl->options.rpkState.received_ClientCertTypes,
  9352. ssl->options.rpkState.received_ClientCertTypeCnt,
  9353. &cmnType)) {
  9354. ssl->options.rpkState.sending_ClientCertTypeCnt = 1;
  9355. ssl->options.rpkState.sending_ClientCertTypes[0] = cmnType;
  9356. populate = 1;
  9357. }
  9358. /* case 5 */
  9359. else {
  9360. WOLFSSL_MSG("No common cert type found in client_certificate_type ext");
  9361. SendAlert(ssl, alert_fatal, unsupported_certificate);
  9362. return UNSUPPORTED_CERTIFICATE;
  9363. }
  9364. }
  9365. /* populate client_certificate_type extension */
  9366. if (populate) {
  9367. WOLFSSL_MSG("Adding Client Certificate Type extension");
  9368. ret = TLSX_Push(&ssl->extensions, TLSX_CLIENT_CERTIFICATE_TYPE, ssl,
  9369. ssl->heap);
  9370. if (ret == 0) {
  9371. TLSX_SetResponse(ssl, TLSX_CLIENT_CERTIFICATE_TYPE);
  9372. }
  9373. }
  9374. }
  9375. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9376. /* parse it in client side */
  9377. if (length == 1) {
  9378. ssl->options.rpkState.received_ClientCertTypeCnt = 1;
  9379. ssl->options.rpkState.received_ClientCertTypes[0] = *input;
  9380. }
  9381. else {
  9382. return BUFFER_E;
  9383. }
  9384. }
  9385. return ret;
  9386. }
  9387. /* Write out the "client certificate type" extension data into the given buffer.
  9388. * return the size wrote in the buffer on success, negative value on error.
  9389. */
  9390. static word16 TLSX_ClientCertificateType_Write(void* data, byte* output,
  9391. byte msgType)
  9392. {
  9393. WOLFSSL* ssl = (WOLFSSL*)data;
  9394. word16 idx = 0;
  9395. byte cnt = 0;
  9396. int i;
  9397. /* skip to write extension if count is zero */
  9398. cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;
  9399. if (cnt == 0)
  9400. return 0;
  9401. if (msgType == client_hello) {
  9402. /* client side */
  9403. *(output + idx) = cnt;
  9404. idx += OPAQUE8_LEN;
  9405. for (i = 0; i < cnt; i++) {
  9406. *(output + idx) = ssl->options.rpkState.sending_ClientCertTypes[i];
  9407. idx += OPAQUE8_LEN;
  9408. }
  9409. return idx;
  9410. }
  9411. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9412. /* sever side */
  9413. if (cnt == 1) {
  9414. *(output + idx) = ssl->options.rpkState.sending_ClientCertTypes[0];
  9415. idx += OPAQUE8_LEN;
  9416. }
  9417. }
  9418. return idx;
  9419. }
  9420. /* Calculate then return the size of the "client certificate type" extension
  9421. * data.
  9422. * return the extension data size on success, negative value on error.
  9423. */
  9424. static int TLSX_ClientCertificateType_GetSize(WOLFSSL* ssl, byte msgType)
  9425. {
  9426. int ret = 0;
  9427. byte cnt;
  9428. if (ssl == NULL)
  9429. return BAD_FUNC_ARG;
  9430. if (msgType == client_hello) {
  9431. /* client side */
  9432. cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;
  9433. ret = (int)(OPAQUE8_LEN + cnt * OPAQUE8_LEN);
  9434. }
  9435. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9436. /* sever side */
  9437. cnt = ssl->options.rpkState.sending_ClientCertTypeCnt;/* must be one */
  9438. ret = OPAQUE8_LEN;
  9439. }
  9440. else {
  9441. return SANITY_MSG_E;
  9442. }
  9443. return ret;
  9444. }
  9445. #define CCT_GET_SIZE TLSX_ClientCertificateType_GetSize
  9446. #define CCT_WRITE TLSX_ClientCertificateType_Write
  9447. #define CCT_PARSE TLSX_ClientCertificateType_Parse
  9448. #else
  9449. #define CCT_GET_SIZE(a) 0
  9450. #define CCT_WRITE(a, b) 0
  9451. #define CCT_PARSE(a, b, c, d) 0
  9452. #endif /* HAVE_RPK */
  9453. #if defined(HAVE_RPK)
  9454. /******************************************************************************/
  9455. /* Server_Certificate_Type extension */
  9456. /******************************************************************************/
  9457. /* Creates a "server certificate type" extension if necessary.
  9458. * Returns 0 if no error occurred, negative value otherwise.
  9459. * A return of 0, it does not indicae that the extension was created.
  9460. */
  9461. static int TLSX_ServerCertificateType_Use(WOLFSSL* ssl, byte isServer)
  9462. {
  9463. int ret = 0;
  9464. byte ctype;
  9465. if (ssl == NULL)
  9466. return BAD_FUNC_ARG;
  9467. if (isServer) {
  9468. /* [in server side] */
  9469. /* find common cert type to both end */
  9470. if (GetCommonItem(
  9471. ssl->options.rpkConfig.preferred_ServerCertTypes,
  9472. ssl->options.rpkConfig.preferred_ServerCertTypeCnt,
  9473. ssl->options.rpkState.received_ServerCertTypes,
  9474. ssl->options.rpkState.received_ServerCertTypeCnt,
  9475. &ctype)) {
  9476. ssl->options.rpkState.sending_ServerCertTypeCnt = 1;
  9477. ssl->options.rpkState.sending_ServerCertTypes[0] = ctype;
  9478. /* Push new server_certificate_type extension. */
  9479. WOLFSSL_MSG("Adding Server Certificate Type extension");
  9480. ret = TLSX_Push(&ssl->extensions, TLSX_SERVER_CERTIFICATE_TYPE, ssl,
  9481. ssl->heap);
  9482. if (ret == 0) {
  9483. TLSX_SetResponse(ssl, TLSX_SERVER_CERTIFICATE_TYPE);
  9484. }
  9485. }
  9486. else {
  9487. /* no common cert type found */
  9488. WOLFSSL_MSG("No common cert type found in server_certificate_type ext");
  9489. SendAlert(ssl, alert_fatal, unsupported_certificate);
  9490. ret = UNSUPPORTED_CERTIFICATE;
  9491. }
  9492. }
  9493. else {
  9494. /* [in client side] */
  9495. if (IsCertTypeListed(WOLFSSL_CERT_TYPE_RPK,
  9496. ssl->options.rpkConfig.preferred_ServerCertTypeCnt,
  9497. ssl->options.rpkConfig.preferred_ServerCertTypes)) {
  9498. ssl->options.rpkState.sending_ServerCertTypeCnt =
  9499. ssl->options.rpkConfig.preferred_ServerCertTypeCnt;
  9500. XMEMCPY(ssl->options.rpkState.sending_ServerCertTypes,
  9501. ssl->options.rpkConfig.preferred_ServerCertTypes,
  9502. ssl->options.rpkConfig.preferred_ServerCertTypeCnt);
  9503. /* Push new server_certificate_type extension. */
  9504. WOLFSSL_MSG("Adding Server Certificate Type extension");
  9505. ret = TLSX_Push(&ssl->extensions, TLSX_SERVER_CERTIFICATE_TYPE, ssl,
  9506. ssl->heap);
  9507. }
  9508. else {
  9509. WOLFSSL_MSG("No will to accept RPK cert");
  9510. }
  9511. }
  9512. return ret;
  9513. }
  9514. /* Parse a "server certificate type" extension received from peer.
  9515. * returns 0 on success and other values indicate failure.
  9516. */
  9517. static int TLSX_ServerCertificateType_Parse(WOLFSSL* ssl, const byte* input,
  9518. word16 length, byte msgType)
  9519. {
  9520. byte typeCnt;
  9521. int idx = 0;
  9522. int ret = 0;
  9523. int i;
  9524. if (msgType == client_hello) {
  9525. /* in server side */
  9526. if (length < OPAQUE8_LEN)
  9527. return BUFFER_E;
  9528. typeCnt = input[idx];
  9529. if (typeCnt > MAX_SERVER_CERT_TYPE_CNT)
  9530. return BUFFER_E;
  9531. if ((typeCnt + 1) * OPAQUE8_LEN != length){
  9532. return BUFFER_E;
  9533. }
  9534. ssl->options.rpkState.received_ServerCertTypeCnt = input[idx];
  9535. idx += OPAQUE8_LEN;
  9536. for (i = 0; i < typeCnt; i++) {
  9537. ssl->options.rpkState.received_ServerCertTypes[i] = input[idx];
  9538. idx += OPAQUE8_LEN;
  9539. }
  9540. ret = TLSX_ServerCertificateType_Use(ssl, 1);
  9541. if (ret == 0) {
  9542. TLSX_SetResponse(ssl, TLSX_SERVER_CERTIFICATE_TYPE);
  9543. }
  9544. }
  9545. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9546. /* in client side */
  9547. if (length != 1) /* length slould be 1 */
  9548. return BUFFER_E;
  9549. ssl->options.rpkState.received_ServerCertTypeCnt = 1;
  9550. ssl->options.rpkState.received_ServerCertTypes[0] = *input;
  9551. }
  9552. return 0;
  9553. }
  9554. /* Write out the "server certificate type" extension data into the given buffer.
  9555. * return the size wrote in the buffer on success, negative value on error.
  9556. */
  9557. static word16 TLSX_ServerCertificateType_Write(void* data, byte* output,
  9558. byte msgType)
  9559. {
  9560. WOLFSSL* ssl = (WOLFSSL*)data;
  9561. word16 idx = 0;
  9562. int cnt = 0;
  9563. int i;
  9564. /* skip to write extension if count is zero */
  9565. cnt = ssl->options.rpkState.sending_ServerCertTypeCnt;
  9566. if (cnt == 0)
  9567. return 0;
  9568. if (msgType == client_hello) {
  9569. /* in client side */
  9570. *(output + idx) = cnt;
  9571. idx += OPAQUE8_LEN;
  9572. for (i = 0; i < cnt; i++) {
  9573. *(output + idx) = ssl->options.rpkState.sending_ServerCertTypes[i];
  9574. idx += OPAQUE8_LEN;
  9575. }
  9576. }
  9577. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9578. /* in server side */
  9579. /* ensure cnt is one */
  9580. if (cnt != 1)
  9581. return 0;
  9582. *(output + idx) = ssl->options.rpkState.sending_ServerCertTypes[0];
  9583. idx += OPAQUE8_LEN;
  9584. }
  9585. return idx;
  9586. }
  9587. /* Calculate then return the size of the "server certificate type" extension
  9588. * data.
  9589. * return the extension data size on success, negative value on error.
  9590. */
  9591. static int TLSX_ServerCertificateType_GetSize(WOLFSSL* ssl, byte msgType)
  9592. {
  9593. int ret = 0;
  9594. int cnt;
  9595. if (ssl == NULL)
  9596. return BAD_FUNC_ARG;
  9597. if (msgType == client_hello) {
  9598. /* in clent side */
  9599. cnt = ssl->options.rpkState.sending_ServerCertTypeCnt;
  9600. if (cnt > 0) {
  9601. ret = (int)(OPAQUE8_LEN + cnt * OPAQUE8_LEN);
  9602. }
  9603. }
  9604. else if (msgType == server_hello || msgType == encrypted_extensions) {
  9605. /* in server side */
  9606. ret = (int)OPAQUE8_LEN;
  9607. }
  9608. else {
  9609. return SANITY_MSG_E;
  9610. }
  9611. return ret;
  9612. }
  9613. #define SCT_GET_SIZE TLSX_ServerCertificateType_GetSize
  9614. #define SCT_WRITE TLSX_ServerCertificateType_Write
  9615. #define SCT_PARSE TLSX_ServerCertificateType_Parse
  9616. #else
  9617. #define SCT_GET_SIZE(a) 0
  9618. #define SCT_WRITE(a, b) 0
  9619. #define SCT_PARSE(a, b, c, d) 0
  9620. #endif /* HAVE_RPK */
  9621. /******************************************************************************/
  9622. /* TLS Extensions Framework */
  9623. /******************************************************************************/
  9624. /** Finds an extension in the provided list. */
  9625. TLSX* TLSX_Find(TLSX* list, TLSX_Type type)
  9626. {
  9627. TLSX* extension = list;
  9628. while (extension && extension->type != type)
  9629. extension = extension->next;
  9630. return extension;
  9631. }
  9632. /** Remove an extension. */
  9633. void TLSX_Remove(TLSX** list, TLSX_Type type, void* heap)
  9634. {
  9635. TLSX* extension;
  9636. TLSX** next;
  9637. if (list == NULL)
  9638. return;
  9639. extension = *list;
  9640. next = list;
  9641. while (extension && extension->type != type) {
  9642. next = &extension->next;
  9643. extension = extension->next;
  9644. }
  9645. if (extension) {
  9646. *next = extension->next;
  9647. extension->next = NULL;
  9648. TLSX_FreeAll(extension, heap);
  9649. }
  9650. }
  9651. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  9652. #define GREASE_ECH_SIZE 160
  9653. #define MAX_PUBLIC_NAME_SZ 256
  9654. #define TLS_INFO_CONST_STRING "tls ech"
  9655. #define TLS_INFO_CONST_STRING_SZ 7
  9656. /* return status after setting up ech to write a grease ech */
  9657. static int TLSX_GreaseECH_Use(TLSX** extensions, void* heap, WC_RNG* rng)
  9658. {
  9659. int ret = 0;
  9660. WOLFSSL_ECH* ech;
  9661. if (extensions == NULL)
  9662. return BAD_FUNC_ARG;
  9663. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9664. DYNAMIC_TYPE_TMP_BUFFER);
  9665. if (ech == NULL)
  9666. return MEMORY_E;
  9667. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9668. ech->state = ECH_WRITE_GREASE;
  9669. /* 0 for outer */
  9670. ech->type = ECH_TYPE_OUTER;
  9671. /* kemId */
  9672. ech->kemId = DHKEM_X25519_HKDF_SHA256;
  9673. /* cipherSuite kdf */
  9674. ech->cipherSuite.kdfId = HKDF_SHA256;
  9675. /* cipherSuite aead */
  9676. ech->cipherSuite.aeadId = HPKE_AES_128_GCM;
  9677. /* random configId */
  9678. ret = wc_RNG_GenerateByte(rng, &(ech->configId));
  9679. /* curve25519 encLen */
  9680. ech->encLen = DHKEM_X25519_ENC_LEN;
  9681. if (ret == 0)
  9682. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9683. if (ret != 0) {
  9684. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9685. }
  9686. return ret;
  9687. }
  9688. /* return status after setting up ech to write real ech */
  9689. static int TLSX_ECH_Use(WOLFSSL_EchConfig* echConfig, TLSX** extensions,
  9690. void* heap, WC_RNG* rng)
  9691. {
  9692. int ret = 0;
  9693. int suiteIndex;
  9694. WOLFSSL_ECH* ech;
  9695. if (extensions == NULL)
  9696. return BAD_FUNC_ARG;
  9697. /* find a supported cipher suite */
  9698. suiteIndex = EchConfigGetSupportedCipherSuite(echConfig);
  9699. if (suiteIndex < 0)
  9700. return suiteIndex;
  9701. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9702. DYNAMIC_TYPE_TMP_BUFFER);
  9703. if (ech == NULL)
  9704. return MEMORY_E;
  9705. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9706. ech->state = ECH_WRITE_REAL;
  9707. ech->echConfig = echConfig;
  9708. /* 0 for outer */
  9709. ech->type = ECH_TYPE_OUTER;
  9710. /* kemId */
  9711. ech->kemId = echConfig->kemId;
  9712. /* cipherSuite kdf */
  9713. ech->cipherSuite.kdfId = echConfig->cipherSuites[suiteIndex].kdfId;
  9714. /* cipherSuite aead */
  9715. ech->cipherSuite.aeadId = echConfig->cipherSuites[suiteIndex].aeadId;
  9716. /* configId */
  9717. ech->configId = echConfig->configId;
  9718. /* encLen */
  9719. switch (echConfig->kemId)
  9720. {
  9721. case DHKEM_P256_HKDF_SHA256:
  9722. ech->encLen = DHKEM_P256_ENC_LEN;
  9723. break;
  9724. case DHKEM_P384_HKDF_SHA384:
  9725. ech->encLen = DHKEM_P384_ENC_LEN;
  9726. break;
  9727. case DHKEM_P521_HKDF_SHA512:
  9728. ech->encLen = DHKEM_P521_ENC_LEN;
  9729. break;
  9730. case DHKEM_X25519_HKDF_SHA256:
  9731. ech->encLen = DHKEM_X25519_ENC_LEN;
  9732. break;
  9733. case DHKEM_X448_HKDF_SHA512:
  9734. ech->encLen = DHKEM_X448_ENC_LEN;
  9735. break;
  9736. }
  9737. /* setup hpke */
  9738. ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER);
  9739. if (ech->hpke == NULL) {
  9740. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9741. return MEMORY_E;
  9742. }
  9743. ret = wc_HpkeInit(ech->hpke, ech->kemId, ech->cipherSuite.kdfId,
  9744. ech->cipherSuite.aeadId, heap);
  9745. /* setup the ephemeralKey */
  9746. if (ret == 0)
  9747. ret = wc_HpkeGenerateKeyPair(ech->hpke, &ech->ephemeralKey, rng);
  9748. if (ret == 0)
  9749. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9750. if (ret != 0) {
  9751. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9752. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9753. }
  9754. return ret;
  9755. }
  9756. /* return status after setting up ech to read and decrypt */
  9757. static int TLSX_ServerECH_Use(TLSX** extensions, void* heap,
  9758. WOLFSSL_EchConfig* configs)
  9759. {
  9760. int ret;
  9761. WOLFSSL_ECH* ech;
  9762. TLSX* echX;
  9763. if (extensions == NULL)
  9764. return BAD_FUNC_ARG;
  9765. /* if we already have ech don't override it */
  9766. echX = TLSX_Find(*extensions, TLSX_ECH);
  9767. if (echX != NULL)
  9768. return 0;
  9769. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9770. DYNAMIC_TYPE_TMP_BUFFER);
  9771. if (ech == NULL)
  9772. return MEMORY_E;
  9773. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9774. ech->state = ECH_WRITE_NONE;
  9775. /* 0 for outer */
  9776. ech->type = ECH_TYPE_OUTER;
  9777. ech->echConfig = configs;
  9778. /* setup the rest of the settings when we receive ech from the client */
  9779. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9780. if (ret != 0)
  9781. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9782. return ret;
  9783. }
  9784. /* return length after writing the ech */
  9785. static int TLSX_ECH_Write(WOLFSSL_ECH* ech, byte* writeBuf, word16* offset)
  9786. {
  9787. int ret = 0;
  9788. int rngRet = -1;
  9789. word32 configsLen = 0;
  9790. void* ephemeralKey = NULL;
  9791. byte* writeBuf_p = writeBuf;
  9792. #ifdef WOLFSSL_SMALL_STACK
  9793. Hpke* hpke = NULL;
  9794. WC_RNG* rng = NULL;
  9795. #else
  9796. Hpke hpke[1];
  9797. WC_RNG rng[1];
  9798. #endif
  9799. WOLFSSL_MSG("TLSX_ECH_Write");
  9800. if (ech->state == ECH_WRITE_NONE || ech->state == ECH_PARSED_INTERNAL)
  9801. return 0;
  9802. if (ech->state == ECH_WRITE_RETRY_CONFIGS) {
  9803. /* get size then write */
  9804. ret = GetEchConfigsEx(ech->echConfig, NULL, &configsLen);
  9805. if (ret != LENGTH_ONLY_E)
  9806. return ret;
  9807. ret = GetEchConfigsEx(ech->echConfig, writeBuf, &configsLen);
  9808. if (ret != WOLFSSL_SUCCESS)
  9809. return ret;
  9810. *offset += configsLen;
  9811. return 0;
  9812. }
  9813. #ifdef WOLFSSL_SMALL_STACK
  9814. hpke = (Hpke*)XMALLOC(sizeof(Hpke), NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9815. if (hpke == NULL)
  9816. return MEMORY_E;
  9817. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  9818. if (rng == NULL) {
  9819. XFREE(hpke, NULL, DYNAMIC_TYPE_RNG);
  9820. return MEMORY_E;
  9821. }
  9822. #endif
  9823. /* type */
  9824. *writeBuf_p = ech->type;
  9825. writeBuf_p += sizeof(ech->type);
  9826. /* outer has body, inner does not */
  9827. if (ech->type == ECH_TYPE_OUTER) {
  9828. /* kdfId */
  9829. c16toa(ech->cipherSuite.kdfId, writeBuf_p);
  9830. writeBuf_p += sizeof(ech->cipherSuite.kdfId);
  9831. /* aeadId */
  9832. c16toa(ech->cipherSuite.aeadId, writeBuf_p);
  9833. writeBuf_p += sizeof(ech->cipherSuite.aeadId);
  9834. /* configId */
  9835. *writeBuf_p = ech->configId;
  9836. writeBuf_p += sizeof(ech->configId);
  9837. /* encLen */
  9838. c16toa(ech->encLen, writeBuf_p);
  9839. writeBuf_p += 2;
  9840. if (ech->state == ECH_WRITE_GREASE) {
  9841. /* hpke init */
  9842. ret = wc_HpkeInit(hpke, ech->kemId, ech->cipherSuite.kdfId,
  9843. ech->cipherSuite.aeadId, NULL);
  9844. if (ret == 0)
  9845. rngRet = ret = wc_InitRng(rng);
  9846. /* create the ephemeralKey */
  9847. if (ret == 0)
  9848. ret = wc_HpkeGenerateKeyPair(hpke, &ephemeralKey, rng);
  9849. /* enc */
  9850. if (ret == 0) {
  9851. ret = wc_HpkeSerializePublicKey(hpke, ephemeralKey, writeBuf_p,
  9852. &ech->encLen);
  9853. writeBuf_p += ech->encLen;
  9854. }
  9855. if (ret == 0) {
  9856. /* innerClientHelloLen */
  9857. c16toa(GREASE_ECH_SIZE + ((writeBuf_p + 2 - writeBuf) % 32),
  9858. writeBuf_p);
  9859. writeBuf_p += 2;
  9860. /* innerClientHello */
  9861. ret = wc_RNG_GenerateBlock(rng, writeBuf_p, GREASE_ECH_SIZE +
  9862. ((writeBuf_p - writeBuf) % 32));
  9863. writeBuf_p += GREASE_ECH_SIZE + ((writeBuf_p - writeBuf) % 32);
  9864. }
  9865. if (rngRet == 0)
  9866. wc_FreeRng(rng);
  9867. if (ephemeralKey != NULL)
  9868. wc_HpkeFreeKey(hpke, hpke->kem, ephemeralKey, hpke->heap);
  9869. }
  9870. else {
  9871. /* write enc to writeBuf_p */
  9872. ret = wc_HpkeSerializePublicKey(ech->hpke, ech->ephemeralKey,
  9873. writeBuf_p, &ech->encLen);
  9874. writeBuf_p += ech->encLen;
  9875. /* innerClientHelloLen */
  9876. c16toa(ech->innerClientHelloLen, writeBuf_p);
  9877. writeBuf_p += 2;
  9878. /* set payload offset for when we finalize */
  9879. ech->outerClientPayload = writeBuf_p;
  9880. /* write zeros for payload */
  9881. XMEMSET(writeBuf_p, 0, ech->innerClientHelloLen);
  9882. writeBuf_p += ech->innerClientHelloLen;
  9883. }
  9884. }
  9885. #ifdef WOLFSSL_SMALL_STACK
  9886. XFREE(hpke, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9887. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  9888. #endif
  9889. if (ret == 0)
  9890. *offset += (writeBuf_p - writeBuf);
  9891. return ret;
  9892. }
  9893. /* return the size needed for the ech extension */
  9894. static int TLSX_ECH_GetSize(WOLFSSL_ECH* ech)
  9895. {
  9896. int ret;
  9897. word32 size;
  9898. if (ech->state == ECH_WRITE_GREASE) {
  9899. size = sizeof(ech->type) + sizeof(ech->cipherSuite) +
  9900. sizeof(ech->configId) + sizeof(word16) + ech->encLen +
  9901. sizeof(word16);
  9902. size += GREASE_ECH_SIZE + (size % 32);
  9903. }
  9904. else if (ech->state == ECH_WRITE_NONE ||
  9905. ech->state == ECH_PARSED_INTERNAL) {
  9906. size = 0;
  9907. }
  9908. else if (ech->state == ECH_WRITE_RETRY_CONFIGS) {
  9909. /* get the size of the raw configs */
  9910. ret = GetEchConfigsEx(ech->echConfig, NULL, &size);
  9911. if (ret != LENGTH_ONLY_E)
  9912. return ret;
  9913. }
  9914. else if (ech->type == ECH_TYPE_INNER)
  9915. {
  9916. size = sizeof(ech->type);
  9917. }
  9918. else
  9919. {
  9920. size = sizeof(ech->type) + sizeof(ech->cipherSuite) +
  9921. sizeof(ech->configId) + sizeof(word16) + ech->encLen +
  9922. sizeof(word16) + ech->innerClientHelloLen;
  9923. }
  9924. return (int)size;
  9925. }
  9926. /* return status after attempting to open the hpke encrypted ech extension, if
  9927. * successful the inner client hello will be stored in
  9928. * ech->innerClientHelloLen */
  9929. static int TLSX_ExtractEch(WOLFSSL_ECH* ech, WOLFSSL_EchConfig* echConfig,
  9930. byte* aad, word32 aadLen, void* heap)
  9931. {
  9932. int ret = 0;
  9933. int expectedEncLen;
  9934. int i;
  9935. word32 rawConfigLen = 0;
  9936. byte* info = NULL;
  9937. word32 infoLen = 0;
  9938. if (ech == NULL || echConfig == NULL || aad == NULL)
  9939. return BAD_FUNC_ARG;
  9940. /* verify the kem and key len */
  9941. switch (echConfig->kemId)
  9942. {
  9943. case DHKEM_P256_HKDF_SHA256:
  9944. expectedEncLen = DHKEM_P256_ENC_LEN;
  9945. break;
  9946. case DHKEM_P384_HKDF_SHA384:
  9947. expectedEncLen = DHKEM_P384_ENC_LEN;
  9948. break;
  9949. case DHKEM_P521_HKDF_SHA512:
  9950. expectedEncLen = DHKEM_P521_ENC_LEN;
  9951. break;
  9952. case DHKEM_X25519_HKDF_SHA256:
  9953. expectedEncLen = DHKEM_X25519_ENC_LEN;
  9954. break;
  9955. case DHKEM_X448_HKDF_SHA512:
  9956. expectedEncLen = DHKEM_X448_ENC_LEN;
  9957. break;
  9958. default:
  9959. expectedEncLen = 0;
  9960. break;
  9961. }
  9962. if (expectedEncLen != ech->encLen)
  9963. return BAD_FUNC_ARG;
  9964. /* verify the cipher suite */
  9965. for (i = 0; i < echConfig->numCipherSuites; i++) {
  9966. if (echConfig->cipherSuites[i].kdfId == ech->cipherSuite.kdfId &&
  9967. echConfig->cipherSuites[i].aeadId == ech->cipherSuite.aeadId) {
  9968. break;
  9969. }
  9970. }
  9971. if (i >= echConfig->numCipherSuites) {
  9972. return BAD_FUNC_ARG;
  9973. }
  9974. ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER);
  9975. if (ech->hpke == NULL)
  9976. return MEMORY_E;
  9977. ret = wc_HpkeInit(ech->hpke, echConfig->kemId, ech->cipherSuite.kdfId,
  9978. ech->cipherSuite.aeadId, heap);
  9979. /* get the rawConfigLen */
  9980. if (ret == 0)
  9981. ret = GetEchConfig(echConfig, NULL, &rawConfigLen);
  9982. if (ret == LENGTH_ONLY_E)
  9983. ret = 0;
  9984. /* create info */
  9985. if (ret == 0) {
  9986. infoLen = TLS_INFO_CONST_STRING_SZ + 1 + rawConfigLen;
  9987. info = (byte*)XMALLOC(infoLen, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9988. if (info == NULL)
  9989. ret = MEMORY_E;
  9990. else {
  9991. XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING,
  9992. TLS_INFO_CONST_STRING_SZ + 1);
  9993. ret = GetEchConfig(echConfig, info +
  9994. TLS_INFO_CONST_STRING_SZ + 1, &rawConfigLen);
  9995. }
  9996. }
  9997. /* decrypt the ech payload */
  9998. if (ret == 0)
  9999. ret = wc_HpkeOpenBase(ech->hpke, echConfig->receiverPrivkey, ech->enc,
  10000. ech->encLen, info, infoLen, aad, aadLen, ech->outerClientPayload,
  10001. ech->innerClientHelloLen,
  10002. ech->innerClientHello + HANDSHAKE_HEADER_SZ);
  10003. if (ret != 0) {
  10004. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10005. ech->hpke = NULL;
  10006. }
  10007. if (info != NULL)
  10008. XFREE(info, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10009. return ret;
  10010. }
  10011. /* parse the ech extension, if internal update ech->state and return, if
  10012. * external attempt to extract the inner client_hello, return the status */
  10013. static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size,
  10014. byte msgType)
  10015. {
  10016. int ret = 0;
  10017. int i;
  10018. TLSX* echX;
  10019. WOLFSSL_ECH* ech;
  10020. WOLFSSL_EchConfig* echConfig;
  10021. byte* aadCopy;
  10022. byte* readBuf_p = (byte*)readBuf;
  10023. WOLFSSL_MSG("TLSX_ECH_Parse");
  10024. if (size == 0)
  10025. return BAD_FUNC_ARG;
  10026. if (msgType == encrypted_extensions) {
  10027. ret = wolfSSL_SetEchConfigs(ssl, readBuf, size);
  10028. if (ret == WOLFSSL_SUCCESS)
  10029. ret = 0;
  10030. }
  10031. else if (msgType == client_hello && ssl->ctx->echConfigs != NULL) {
  10032. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  10033. if (echX == NULL)
  10034. return BAD_FUNC_ARG;
  10035. ech = (WOLFSSL_ECH*)echX->data;
  10036. /* read the ech parameters before the payload */
  10037. ech->type = *readBuf_p;
  10038. readBuf_p++;
  10039. if (ech->type == ECH_TYPE_INNER) {
  10040. ech->state = ECH_PARSED_INTERNAL;
  10041. return 0;
  10042. }
  10043. /* technically the payload would only be 1 byte at this length */
  10044. if (size < 11 + ech->encLen)
  10045. return BAD_FUNC_ARG;
  10046. ato16(readBuf_p, &ech->cipherSuite.kdfId);
  10047. readBuf_p += 2;
  10048. ato16(readBuf_p, &ech->cipherSuite.aeadId);
  10049. readBuf_p += 2;
  10050. ech->configId = *readBuf_p;
  10051. readBuf_p++;
  10052. ato16(readBuf_p, &ech->encLen);
  10053. readBuf_p += 2;
  10054. if (ech->encLen > HPKE_Npk_MAX)
  10055. return BAD_FUNC_ARG;
  10056. XMEMCPY(ech->enc, readBuf_p, ech->encLen);
  10057. readBuf_p += ech->encLen;
  10058. ato16(readBuf_p, &ech->innerClientHelloLen);
  10059. ech->innerClientHelloLen -= AES_BLOCK_SIZE;
  10060. readBuf_p += 2;
  10061. ech->outerClientPayload = readBuf_p;
  10062. /* make a copy of the aad */
  10063. aadCopy = (byte*)XMALLOC(ech->aadLen, ssl->heap,
  10064. DYNAMIC_TYPE_TMP_BUFFER);
  10065. if (aadCopy == NULL)
  10066. return MEMORY_E;
  10067. XMEMCPY(aadCopy, ech->aad, ech->aadLen);
  10068. /* set the ech payload of the copy to zeros */
  10069. XMEMSET(aadCopy + (readBuf_p - ech->aad), 0,
  10070. ech->innerClientHelloLen + AES_BLOCK_SIZE);
  10071. /* allocate the inner payload buffer */
  10072. ech->innerClientHello =
  10073. (byte*)XMALLOC(ech->innerClientHelloLen + HANDSHAKE_HEADER_SZ,
  10074. ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10075. if (ech->innerClientHello == NULL) {
  10076. XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10077. return MEMORY_E;
  10078. }
  10079. /* first check if the config id matches */
  10080. echConfig = ssl->ctx->echConfigs;
  10081. while (echConfig != NULL) {
  10082. /* decrypt with this config */
  10083. if (echConfig->configId == ech->configId) {
  10084. ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen,
  10085. ssl->heap);
  10086. break;
  10087. }
  10088. echConfig = echConfig->next;
  10089. }
  10090. /* try to decrypt with all configs */
  10091. if (echConfig == NULL || ret != 0) {
  10092. echConfig = ssl->ctx->echConfigs;
  10093. while (echConfig != NULL) {
  10094. ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen,
  10095. ssl->heap);
  10096. if (ret== 0)
  10097. break;
  10098. echConfig = echConfig->next;
  10099. }
  10100. }
  10101. /* if we failed to extract */
  10102. if (ret != 0) {
  10103. XFREE(ech->innerClientHello, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10104. ech->innerClientHello = NULL;
  10105. ech->state = ECH_WRITE_RETRY_CONFIGS;
  10106. }
  10107. else {
  10108. i = 0;
  10109. /* decrement until before the padding */
  10110. while (ech->innerClientHello[ech->innerClientHelloLen +
  10111. HANDSHAKE_HEADER_SZ - i - 1] != ECH_TYPE_INNER) {
  10112. i++;
  10113. }
  10114. /* subtract the length of the padding from the length */
  10115. ech->innerClientHelloLen -= i;
  10116. }
  10117. XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10118. return 0;
  10119. }
  10120. return ret;
  10121. }
  10122. /* free the ech struct and the dynamic buffer it uses */
  10123. static void TLSX_ECH_Free(WOLFSSL_ECH* ech, void* heap)
  10124. {
  10125. if (ech->innerClientHello != NULL)
  10126. XFREE(ech->innerClientHello, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10127. if (ech->ephemeralKey != NULL)
  10128. wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, ech->ephemeralKey,
  10129. ech->hpke->heap);
  10130. if (ech->hpke != NULL)
  10131. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10132. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10133. (void)heap;
  10134. }
  10135. /* encrypt the client hello and store it in ech->outerClientPayload, return
  10136. * status */
  10137. int TLSX_FinalizeEch(WOLFSSL_ECH* ech, byte* aad, word32 aadLen)
  10138. {
  10139. int ret;
  10140. void* receiverPubkey = NULL;
  10141. byte* info;
  10142. int infoLen;
  10143. byte* aadCopy;
  10144. /* import the server public key */
  10145. ret = wc_HpkeDeserializePublicKey(ech->hpke, &receiverPubkey,
  10146. ech->echConfig->receiverPubkey, ech->encLen);
  10147. if (ret == 0) {
  10148. /* create info */
  10149. infoLen = TLS_INFO_CONST_STRING_SZ + 1 + ech->echConfig->rawLen;
  10150. info = (byte*)XMALLOC(infoLen, ech->hpke->heap,
  10151. DYNAMIC_TYPE_TMP_BUFFER);
  10152. if (info == NULL)
  10153. ret = MEMORY_E;
  10154. if (ret == 0) {
  10155. /* puts the null byte in for me */
  10156. XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING, TLS_INFO_CONST_STRING_SZ
  10157. + 1);
  10158. XMEMCPY(info + TLS_INFO_CONST_STRING_SZ + 1, ech->echConfig->raw,
  10159. ech->echConfig->rawLen);
  10160. /* make a copy of the aad since we overwrite it */
  10161. aadCopy = (byte*)XMALLOC(aadLen, ech->hpke->heap,
  10162. DYNAMIC_TYPE_TMP_BUFFER);
  10163. if (aadCopy == NULL) {
  10164. XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10165. ret = MEMORY_E;
  10166. }
  10167. }
  10168. if (ret == 0) {
  10169. XMEMCPY(aadCopy, aad, aadLen);
  10170. /* seal the payload */
  10171. ret = wc_HpkeSealBase(ech->hpke, ech->ephemeralKey, receiverPubkey,
  10172. info, infoLen, aadCopy, aadLen, ech->innerClientHello,
  10173. ech->innerClientHelloLen - ech->hpke->Nt,
  10174. ech->outerClientPayload);
  10175. XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10176. XFREE(aadCopy, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10177. }
  10178. }
  10179. if (receiverPubkey != NULL)
  10180. wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, receiverPubkey,
  10181. ech->hpke->heap);
  10182. return ret;
  10183. }
  10184. #define GREASE_ECH_USE TLSX_GreaseECH_Use
  10185. #define ECH_USE TLSX_ECH_Use
  10186. #define SERVER_ECH_USE TLSX_ServerECH_Use
  10187. #define ECH_WRITE TLSX_ECH_Write
  10188. #define ECH_GET_SIZE TLSX_ECH_GetSize
  10189. #define ECH_PARSE TLSX_ECH_Parse
  10190. #define ECH_FREE TLSX_ECH_Free
  10191. #endif
  10192. /** Releases all extensions in the provided list. */
  10193. void TLSX_FreeAll(TLSX* list, void* heap)
  10194. {
  10195. TLSX* extension;
  10196. while ((extension = list)) {
  10197. list = extension->next;
  10198. switch (extension->type) {
  10199. #if defined(HAVE_RPK)
  10200. case TLSX_CLIENT_CERTIFICATE_TYPE:
  10201. WOLFSSL_MSG("Client Certificate Type extension free");
  10202. /* nothing to do */
  10203. break;
  10204. case TLSX_SERVER_CERTIFICATE_TYPE:
  10205. WOLFSSL_MSG("Server Certificate Type extension free");
  10206. /* nothing to do */
  10207. break;
  10208. #endif
  10209. #ifdef HAVE_SNI
  10210. case TLSX_SERVER_NAME:
  10211. WOLFSSL_MSG("SNI extension free");
  10212. SNI_FREE_ALL((SNI*)extension->data, heap);
  10213. break;
  10214. #endif
  10215. case TLSX_TRUSTED_CA_KEYS:
  10216. WOLFSSL_MSG("Trusted CA Indication extension free");
  10217. TCA_FREE_ALL((TCA*)extension->data, heap);
  10218. break;
  10219. case TLSX_MAX_FRAGMENT_LENGTH:
  10220. WOLFSSL_MSG("Max Fragment Length extension free");
  10221. MFL_FREE_ALL(extension->data, heap);
  10222. break;
  10223. case TLSX_EXTENDED_MASTER_SECRET:
  10224. WOLFSSL_MSG("Extended Master Secret free");
  10225. /* Nothing to do. */
  10226. break;
  10227. case TLSX_TRUNCATED_HMAC:
  10228. WOLFSSL_MSG("Truncated HMAC extension free");
  10229. /* Nothing to do. */
  10230. break;
  10231. case TLSX_SUPPORTED_GROUPS:
  10232. WOLFSSL_MSG("Supported Groups extension free");
  10233. EC_FREE_ALL((SupportedCurve*)extension->data, heap);
  10234. break;
  10235. case TLSX_EC_POINT_FORMATS:
  10236. WOLFSSL_MSG("Point Formats extension free");
  10237. PF_FREE_ALL((PointFormat*)extension->data, heap);
  10238. break;
  10239. case TLSX_STATUS_REQUEST:
  10240. WOLFSSL_MSG("Certificate Status Request extension free");
  10241. CSR_FREE_ALL((CertificateStatusRequest*)extension->data, heap);
  10242. break;
  10243. case TLSX_STATUS_REQUEST_V2:
  10244. WOLFSSL_MSG("Certificate Status Request v2 extension free");
  10245. CSR2_FREE_ALL((CertificateStatusRequestItemV2*)extension->data,
  10246. heap);
  10247. break;
  10248. case TLSX_RENEGOTIATION_INFO:
  10249. WOLFSSL_MSG("Secure Renegotiation extension free");
  10250. SCR_FREE_ALL(extension->data, heap);
  10251. break;
  10252. case TLSX_SESSION_TICKET:
  10253. WOLFSSL_MSG("Session Ticket extension free");
  10254. WOLF_STK_FREE(extension->data, heap);
  10255. break;
  10256. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10257. WOLFSSL_MSG("ALPN extension free");
  10258. ALPN_FREE_ALL((ALPN*)extension->data, heap);
  10259. break;
  10260. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10261. case TLSX_SIGNATURE_ALGORITHMS:
  10262. WOLFSSL_MSG("Signature Algorithms extension to free");
  10263. SA_FREE_ALL((SignatureAlgorithms*)extension->data, heap);
  10264. break;
  10265. #endif
  10266. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10267. case TLSX_ENCRYPT_THEN_MAC:
  10268. WOLFSSL_MSG("Encrypt-Then-Mac extension free");
  10269. break;
  10270. #endif
  10271. #ifdef WOLFSSL_TLS13
  10272. case TLSX_SUPPORTED_VERSIONS:
  10273. WOLFSSL_MSG("Supported Versions extension free");
  10274. break;
  10275. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10276. case TLSX_COOKIE:
  10277. WOLFSSL_MSG("Cookie extension free");
  10278. CKE_FREE_ALL((Cookie*)extension->data, heap);
  10279. break;
  10280. #endif
  10281. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10282. case TLSX_PRE_SHARED_KEY:
  10283. WOLFSSL_MSG("Pre-Shared Key extension free");
  10284. PSK_FREE_ALL((PreSharedKey*)extension->data, heap);
  10285. break;
  10286. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10287. WOLFSSL_MSG("PSK Key Exchange Modes extension free");
  10288. break;
  10289. #endif
  10290. #ifdef WOLFSSL_EARLY_DATA
  10291. case TLSX_EARLY_DATA:
  10292. WOLFSSL_MSG("Early Data extension free");
  10293. break;
  10294. #endif
  10295. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10296. case TLSX_POST_HANDSHAKE_AUTH:
  10297. WOLFSSL_MSG("Post-Handshake Authentication extension free");
  10298. break;
  10299. #endif
  10300. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10301. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10302. WOLFSSL_MSG("Signature Algorithms extension free");
  10303. break;
  10304. #endif
  10305. case TLSX_KEY_SHARE:
  10306. WOLFSSL_MSG("Key Share extension free");
  10307. KS_FREE_ALL((KeyShareEntry*)extension->data, heap);
  10308. break;
  10309. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10310. case TLSX_CERTIFICATE_AUTHORITIES:
  10311. WOLFSSL_MSG("Certificate Authorities extension free");
  10312. break;
  10313. #endif
  10314. #endif
  10315. #ifdef WOLFSSL_SRTP
  10316. case TLSX_USE_SRTP:
  10317. WOLFSSL_MSG("SRTP extension free");
  10318. SRTP_FREE((TlsxSrtp*)extension->data, heap);
  10319. break;
  10320. #endif
  10321. #ifdef WOLFSSL_QUIC
  10322. case TLSX_KEY_QUIC_TP_PARAMS:
  10323. FALL_THROUGH;
  10324. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10325. WOLFSSL_MSG("QUIC transport parameter free");
  10326. QTP_FREE((QuicTransportParam*)extension->data, heap);
  10327. break;
  10328. #endif
  10329. #ifdef WOLFSSL_DTLS_CID
  10330. case TLSX_CONNECTION_ID:
  10331. WOLFSSL_MSG("Connection ID extension free");
  10332. CID_FREE((byte*)extension->data, heap);
  10333. break;
  10334. #endif /* WOLFSSL_DTLS_CID */
  10335. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10336. case TLSX_ECH:
  10337. WOLFSSL_MSG("ECH extension free");
  10338. ECH_FREE((WOLFSSL_ECH*)extension->data, heap);
  10339. break;
  10340. #endif
  10341. default:
  10342. break;
  10343. }
  10344. XFREE(extension, heap, DYNAMIC_TYPE_TLSX);
  10345. }
  10346. (void)heap;
  10347. }
  10348. /** Checks if the tls extensions are supported based on the protocol version. */
  10349. int TLSX_SupportExtensions(WOLFSSL* ssl) {
  10350. return ssl && (IsTLS(ssl) || ssl->version.major == DTLS_MAJOR);
  10351. }
  10352. /** Tells the buffered size of the extensions in a list. */
  10353. static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType,
  10354. word16* pLength)
  10355. {
  10356. int ret = 0;
  10357. TLSX* extension;
  10358. word16 length = 0;
  10359. byte isRequest = (msgType == client_hello ||
  10360. msgType == certificate_request);
  10361. while ((extension = list)) {
  10362. list = extension->next;
  10363. /* only extensions marked as response are sent back to the client. */
  10364. if (!isRequest && !extension->resp)
  10365. continue; /* skip! */
  10366. /* ssl level extensions are expected to override ctx level ones. */
  10367. if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type)))
  10368. continue; /* skip! */
  10369. /* extension type + extension data length. */
  10370. length += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN;
  10371. switch (extension->type) {
  10372. #ifdef HAVE_SNI
  10373. case TLSX_SERVER_NAME:
  10374. /* SNI only sends the name on the request. */
  10375. if (isRequest)
  10376. length += SNI_GET_SIZE((SNI*)extension->data);
  10377. break;
  10378. #endif
  10379. case TLSX_TRUSTED_CA_KEYS:
  10380. /* TCA only sends the list on the request. */
  10381. if (isRequest)
  10382. length += TCA_GET_SIZE((TCA*)extension->data);
  10383. break;
  10384. case TLSX_MAX_FRAGMENT_LENGTH:
  10385. length += MFL_GET_SIZE(extension->data);
  10386. break;
  10387. case TLSX_EXTENDED_MASTER_SECRET:
  10388. case TLSX_TRUNCATED_HMAC:
  10389. /* always empty. */
  10390. break;
  10391. case TLSX_SUPPORTED_GROUPS:
  10392. length += EC_GET_SIZE((SupportedCurve*)extension->data);
  10393. break;
  10394. case TLSX_EC_POINT_FORMATS:
  10395. length += PF_GET_SIZE((PointFormat*)extension->data);
  10396. break;
  10397. case TLSX_STATUS_REQUEST:
  10398. length += CSR_GET_SIZE(
  10399. (CertificateStatusRequest*)extension->data, isRequest);
  10400. break;
  10401. case TLSX_STATUS_REQUEST_V2:
  10402. length += CSR2_GET_SIZE(
  10403. (CertificateStatusRequestItemV2*)extension->data,
  10404. isRequest);
  10405. break;
  10406. case TLSX_RENEGOTIATION_INFO:
  10407. length += SCR_GET_SIZE((SecureRenegotiation*)extension->data,
  10408. isRequest);
  10409. break;
  10410. case TLSX_SESSION_TICKET:
  10411. length += WOLF_STK_GET_SIZE((SessionTicket*)extension->data,
  10412. isRequest);
  10413. break;
  10414. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10415. length += ALPN_GET_SIZE((ALPN*)extension->data);
  10416. break;
  10417. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10418. case TLSX_SIGNATURE_ALGORITHMS:
  10419. length += SA_GET_SIZE(extension->data);
  10420. break;
  10421. #endif
  10422. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10423. case TLSX_ENCRYPT_THEN_MAC:
  10424. ret = ETM_GET_SIZE(msgType, &length);
  10425. break;
  10426. #endif /* HAVE_ENCRYPT_THEN_MAC */
  10427. #ifdef WOLFSSL_TLS13
  10428. case TLSX_SUPPORTED_VERSIONS:
  10429. ret = SV_GET_SIZE(extension->data, msgType, &length);
  10430. break;
  10431. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10432. case TLSX_COOKIE:
  10433. ret = CKE_GET_SIZE((Cookie*)extension->data, msgType, &length);
  10434. break;
  10435. #endif
  10436. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10437. case TLSX_PRE_SHARED_KEY:
  10438. ret = PSK_GET_SIZE((PreSharedKey*)extension->data, msgType,
  10439. &length);
  10440. break;
  10441. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10442. ret = PKM_GET_SIZE((byte)extension->val, msgType, &length);
  10443. break;
  10444. #endif
  10445. #ifdef WOLFSSL_EARLY_DATA
  10446. case TLSX_EARLY_DATA:
  10447. ret = EDI_GET_SIZE(msgType, &length);
  10448. break;
  10449. #endif
  10450. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10451. case TLSX_POST_HANDSHAKE_AUTH:
  10452. ret = PHA_GET_SIZE(msgType, &length);
  10453. break;
  10454. #endif
  10455. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10456. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10457. length += SAC_GET_SIZE(extension->data);
  10458. break;
  10459. #endif
  10460. case TLSX_KEY_SHARE:
  10461. length += KS_GET_SIZE((KeyShareEntry*)extension->data, msgType);
  10462. break;
  10463. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10464. case TLSX_CERTIFICATE_AUTHORITIES:
  10465. length += CAN_GET_SIZE(extension->data);
  10466. break;
  10467. #endif
  10468. #endif
  10469. #ifdef WOLFSSL_SRTP
  10470. case TLSX_USE_SRTP:
  10471. length += SRTP_GET_SIZE((TlsxSrtp*)extension->data);
  10472. break;
  10473. #endif
  10474. #ifdef HAVE_RPK
  10475. case TLSX_CLIENT_CERTIFICATE_TYPE:
  10476. length += CCT_GET_SIZE((WOLFSSL*)extension->data, msgType);
  10477. break;
  10478. case TLSX_SERVER_CERTIFICATE_TYPE:
  10479. length += SCT_GET_SIZE((WOLFSSL*)extension->data, msgType);
  10480. break;
  10481. #endif /* HAVE_RPK */
  10482. #ifdef WOLFSSL_QUIC
  10483. case TLSX_KEY_QUIC_TP_PARAMS:
  10484. FALL_THROUGH; /* followed by */
  10485. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10486. length += QTP_GET_SIZE(extension);
  10487. break;
  10488. #endif
  10489. #ifdef WOLFSSL_DTLS_CID
  10490. case TLSX_CONNECTION_ID:
  10491. length += CID_GET_SIZE((byte*)extension->data);
  10492. break;
  10493. #endif /* WOLFSSL_DTLS_CID */
  10494. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10495. case TLSX_ECH:
  10496. length += ECH_GET_SIZE((WOLFSSL_ECH*)extension->data);
  10497. break;
  10498. #endif
  10499. default:
  10500. break;
  10501. }
  10502. /* marks the extension as processed so ctx level */
  10503. /* extensions don't overlap with ssl level ones. */
  10504. TURN_ON(semaphore, TLSX_ToSemaphore(extension->type));
  10505. }
  10506. *pLength += length;
  10507. return ret;
  10508. }
  10509. /** Writes the extensions of a list in a buffer. */
  10510. static int TLSX_Write(TLSX* list, byte* output, byte* semaphore,
  10511. byte msgType, word16* pOffset)
  10512. {
  10513. int ret = 0;
  10514. TLSX* extension;
  10515. word16 offset = 0;
  10516. word16 length_offset = 0;
  10517. byte isRequest = (msgType == client_hello ||
  10518. msgType == certificate_request);
  10519. while ((extension = list)) {
  10520. list = extension->next;
  10521. /* only extensions marked as response are written in a response. */
  10522. if (!isRequest && !extension->resp)
  10523. continue; /* skip! */
  10524. /* ssl level extensions are expected to override ctx level ones. */
  10525. if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type)))
  10526. continue; /* skip! */
  10527. /* writes extension type. */
  10528. c16toa(extension->type, output + offset);
  10529. offset += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN;
  10530. length_offset = offset;
  10531. /* extension data should be written internally. */
  10532. switch (extension->type) {
  10533. #ifdef HAVE_SNI
  10534. case TLSX_SERVER_NAME:
  10535. if (isRequest) {
  10536. WOLFSSL_MSG("SNI extension to write");
  10537. offset += SNI_WRITE((SNI*)extension->data, output + offset);
  10538. }
  10539. break;
  10540. #endif
  10541. case TLSX_TRUSTED_CA_KEYS:
  10542. WOLFSSL_MSG("Trusted CA Indication extension to write");
  10543. if (isRequest) {
  10544. offset += TCA_WRITE((TCA*)extension->data, output + offset);
  10545. }
  10546. break;
  10547. case TLSX_MAX_FRAGMENT_LENGTH:
  10548. WOLFSSL_MSG("Max Fragment Length extension to write");
  10549. offset += MFL_WRITE((byte*)extension->data, output + offset);
  10550. break;
  10551. case TLSX_EXTENDED_MASTER_SECRET:
  10552. WOLFSSL_MSG("Extended Master Secret");
  10553. /* always empty. */
  10554. break;
  10555. case TLSX_TRUNCATED_HMAC:
  10556. WOLFSSL_MSG("Truncated HMAC extension to write");
  10557. /* always empty. */
  10558. break;
  10559. case TLSX_SUPPORTED_GROUPS:
  10560. WOLFSSL_MSG("Supported Groups extension to write");
  10561. offset += EC_WRITE((SupportedCurve*)extension->data,
  10562. output + offset);
  10563. break;
  10564. case TLSX_EC_POINT_FORMATS:
  10565. WOLFSSL_MSG("Point Formats extension to write");
  10566. offset += PF_WRITE((PointFormat*)extension->data,
  10567. output + offset);
  10568. break;
  10569. case TLSX_STATUS_REQUEST:
  10570. WOLFSSL_MSG("Certificate Status Request extension to write");
  10571. offset += CSR_WRITE((CertificateStatusRequest*)extension->data,
  10572. output + offset, isRequest);
  10573. break;
  10574. case TLSX_STATUS_REQUEST_V2:
  10575. WOLFSSL_MSG("Certificate Status Request v2 extension to write");
  10576. offset += CSR2_WRITE(
  10577. (CertificateStatusRequestItemV2*)extension->data,
  10578. output + offset, isRequest);
  10579. break;
  10580. case TLSX_RENEGOTIATION_INFO:
  10581. WOLFSSL_MSG("Secure Renegotiation extension to write");
  10582. offset += SCR_WRITE((SecureRenegotiation*)extension->data,
  10583. output + offset, isRequest);
  10584. break;
  10585. case TLSX_SESSION_TICKET:
  10586. WOLFSSL_MSG("Session Ticket extension to write");
  10587. offset += WOLF_STK_WRITE((SessionTicket*)extension->data,
  10588. output + offset, isRequest);
  10589. break;
  10590. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10591. WOLFSSL_MSG("ALPN extension to write");
  10592. offset += ALPN_WRITE((ALPN*)extension->data, output + offset);
  10593. break;
  10594. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10595. case TLSX_SIGNATURE_ALGORITHMS:
  10596. WOLFSSL_MSG("Signature Algorithms extension to write");
  10597. offset += SA_WRITE(extension->data, output + offset);
  10598. break;
  10599. #endif
  10600. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10601. case TLSX_ENCRYPT_THEN_MAC:
  10602. WOLFSSL_MSG("Encrypt-Then-Mac extension to write");
  10603. ret = ETM_WRITE(extension->data, output, msgType, &offset);
  10604. break;
  10605. #endif /* HAVE_ENCRYPT_THEN_MAC */
  10606. #ifdef WOLFSSL_TLS13
  10607. case TLSX_SUPPORTED_VERSIONS:
  10608. WOLFSSL_MSG("Supported Versions extension to write");
  10609. ret = SV_WRITE(extension->data, output + offset, msgType, &offset);
  10610. break;
  10611. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10612. case TLSX_COOKIE:
  10613. WOLFSSL_MSG("Cookie extension to write");
  10614. ret = CKE_WRITE((Cookie*)extension->data, output + offset,
  10615. msgType, &offset);
  10616. break;
  10617. #endif
  10618. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10619. case TLSX_PRE_SHARED_KEY:
  10620. WOLFSSL_MSG("Pre-Shared Key extension to write");
  10621. ret = PSK_WRITE((PreSharedKey*)extension->data, output + offset,
  10622. msgType, &offset);
  10623. break;
  10624. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10625. WOLFSSL_MSG("PSK Key Exchange Modes extension to write");
  10626. ret = PKM_WRITE((byte)extension->val, output + offset, msgType,
  10627. &offset);
  10628. break;
  10629. #endif
  10630. #ifdef WOLFSSL_EARLY_DATA
  10631. case TLSX_EARLY_DATA:
  10632. WOLFSSL_MSG("Early Data extension to write");
  10633. ret = EDI_WRITE(extension->val, output + offset, msgType,
  10634. &offset);
  10635. break;
  10636. #endif
  10637. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10638. case TLSX_POST_HANDSHAKE_AUTH:
  10639. WOLFSSL_MSG("Post-Handshake Authentication extension to write");
  10640. ret = PHA_WRITE(output + offset, msgType, &offset);
  10641. break;
  10642. #endif
  10643. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10644. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10645. WOLFSSL_MSG("Signature Algorithms extension to write");
  10646. offset += SAC_WRITE(extension->data, output + offset);
  10647. break;
  10648. #endif
  10649. case TLSX_KEY_SHARE:
  10650. WOLFSSL_MSG("Key Share extension to write");
  10651. offset += KS_WRITE((KeyShareEntry*)extension->data,
  10652. output + offset, msgType);
  10653. break;
  10654. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10655. case TLSX_CERTIFICATE_AUTHORITIES:
  10656. WOLFSSL_MSG("Certificate Authorities extension to write");
  10657. offset += CAN_WRITE(extension->data, output + offset);
  10658. break;
  10659. #endif
  10660. #endif
  10661. #ifdef WOLFSSL_SRTP
  10662. case TLSX_USE_SRTP:
  10663. WOLFSSL_MSG("SRTP extension to write");
  10664. offset += SRTP_WRITE((TlsxSrtp*)extension->data, output+offset);
  10665. break;
  10666. #endif
  10667. #ifdef HAVE_RPK
  10668. case TLSX_CLIENT_CERTIFICATE_TYPE:
  10669. WOLFSSL_MSG("Client Certificate Type extension to write");
  10670. offset += CCT_WRITE(extension->data, output + offset, msgType);
  10671. break;
  10672. case TLSX_SERVER_CERTIFICATE_TYPE:
  10673. WOLFSSL_MSG("Server Certificate Type extension to write");
  10674. offset += SCT_WRITE(extension->data, output + offset, msgType);
  10675. break;
  10676. #endif /* HAVE_RPK */
  10677. #ifdef WOLFSSL_QUIC
  10678. case TLSX_KEY_QUIC_TP_PARAMS:
  10679. FALL_THROUGH;
  10680. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10681. WOLFSSL_MSG("QUIC transport parameter to write");
  10682. offset += QTP_WRITE((QuicTransportParam*)extension->data,
  10683. output + offset);
  10684. break;
  10685. #endif
  10686. #ifdef WOLFSSL_DTLS_CID
  10687. case TLSX_CONNECTION_ID:
  10688. WOLFSSL_MSG("Connection ID extension to write");
  10689. offset += CID_WRITE((byte*)extension->data, output+offset);
  10690. break;
  10691. #endif /* WOLFSSL_DTLS_CID */
  10692. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10693. case TLSX_ECH:
  10694. WOLFSSL_MSG("ECH extension to write");
  10695. ret = ECH_WRITE((WOLFSSL_ECH*)extension->data,
  10696. output + offset, &offset);
  10697. break;
  10698. #endif
  10699. default:
  10700. break;
  10701. }
  10702. /* writes extension data length. */
  10703. c16toa(offset - length_offset, output + length_offset - OPAQUE16_LEN);
  10704. /* marks the extension as processed so ctx level */
  10705. /* extensions don't overlap with ssl level ones. */
  10706. TURN_ON(semaphore, TLSX_ToSemaphore(extension->type));
  10707. /* if we encountered an error propagate it */
  10708. if (ret != 0)
  10709. break;
  10710. }
  10711. *pOffset += offset;
  10712. return ret;
  10713. }
  10714. #ifdef HAVE_SUPPORTED_CURVES
  10715. /* Populates the default supported groups / curves */
  10716. static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions)
  10717. {
  10718. int ret = WOLFSSL_SUCCESS;
  10719. #ifdef WOLFSSL_TLS13
  10720. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10721. if (ssl->options.resuming && ssl->session->namedGroup != 0) {
  10722. return TLSX_UseSupportedCurve(extensions, ssl->session->namedGroup,
  10723. ssl->heap);
  10724. }
  10725. #endif
  10726. if (ssl->numGroups != 0) {
  10727. int i;
  10728. for (i = 0; i < ssl->numGroups; i++) {
  10729. ret = TLSX_UseSupportedCurve(extensions, ssl->group[i], ssl->heap);
  10730. if (ret != WOLFSSL_SUCCESS)
  10731. return ret;
  10732. }
  10733. return WOLFSSL_SUCCESS;
  10734. }
  10735. #endif /* WOLFSSL_TLS13 */
  10736. #if defined(HAVE_ECC)
  10737. /* list in order by strength, since not all servers choose by strength */
  10738. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  10739. #ifndef NO_ECC_SECP
  10740. ret = TLSX_UseSupportedCurve(extensions,
  10741. WOLFSSL_ECC_SECP521R1, ssl->heap);
  10742. if (ret != WOLFSSL_SUCCESS) return ret;
  10743. #endif
  10744. #endif
  10745. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  10746. #ifdef HAVE_ECC_BRAINPOOL
  10747. ret = TLSX_UseSupportedCurve(extensions,
  10748. WOLFSSL_ECC_BRAINPOOLP512R1, ssl->heap);
  10749. if (ret != WOLFSSL_SUCCESS) return ret;
  10750. #endif
  10751. #endif
  10752. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  10753. #ifndef NO_ECC_SECP
  10754. ret = TLSX_UseSupportedCurve(extensions,
  10755. WOLFSSL_ECC_SECP384R1, ssl->heap);
  10756. if (ret != WOLFSSL_SUCCESS) return ret;
  10757. #endif
  10758. #ifdef HAVE_ECC_BRAINPOOL
  10759. ret = TLSX_UseSupportedCurve(extensions,
  10760. WOLFSSL_ECC_BRAINPOOLP384R1, ssl->heap);
  10761. if (ret != WOLFSSL_SUCCESS) return ret;
  10762. #endif
  10763. #endif
  10764. #endif /* HAVE_ECC */
  10765. #ifndef HAVE_FIPS
  10766. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  10767. ret = TLSX_UseSupportedCurve(extensions,
  10768. WOLFSSL_ECC_X448, ssl->heap);
  10769. if (ret != WOLFSSL_SUCCESS) return ret;
  10770. #endif
  10771. #endif /* HAVE_FIPS */
  10772. #if defined(HAVE_ECC) && defined(HAVE_SUPPORTED_CURVES)
  10773. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  10774. #ifndef NO_ECC_SECP
  10775. ret = TLSX_UseSupportedCurve(extensions,
  10776. WOLFSSL_ECC_SECP256R1, ssl->heap);
  10777. if (ret != WOLFSSL_SUCCESS) return ret;
  10778. #endif
  10779. #ifdef HAVE_ECC_KOBLITZ
  10780. ret = TLSX_UseSupportedCurve(extensions,
  10781. WOLFSSL_ECC_SECP256K1, ssl->heap);
  10782. if (ret != WOLFSSL_SUCCESS) return ret;
  10783. #endif
  10784. #ifdef HAVE_ECC_BRAINPOOL
  10785. ret = TLSX_UseSupportedCurve(extensions,
  10786. WOLFSSL_ECC_BRAINPOOLP256R1, ssl->heap);
  10787. if (ret != WOLFSSL_SUCCESS) return ret;
  10788. #endif
  10789. #ifdef WOLFSSL_SM2
  10790. ret = TLSX_UseSupportedCurve(extensions,
  10791. WOLFSSL_ECC_SM2P256V1, ssl->heap);
  10792. if (ret != WOLFSSL_SUCCESS) return ret;
  10793. #endif
  10794. #endif
  10795. #endif /* HAVE_ECC */
  10796. #ifndef HAVE_FIPS
  10797. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  10798. ret = TLSX_UseSupportedCurve(extensions,
  10799. WOLFSSL_ECC_X25519, ssl->heap);
  10800. if (ret != WOLFSSL_SUCCESS) return ret;
  10801. #endif
  10802. #endif /* HAVE_FIPS */
  10803. #if defined(HAVE_ECC) && defined(HAVE_SUPPORTED_CURVES)
  10804. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  10805. #ifndef NO_ECC_SECP
  10806. ret = TLSX_UseSupportedCurve(extensions,
  10807. WOLFSSL_ECC_SECP224R1, ssl->heap);
  10808. if (ret != WOLFSSL_SUCCESS) return ret;
  10809. #endif
  10810. #ifdef HAVE_ECC_KOBLITZ
  10811. ret = TLSX_UseSupportedCurve(extensions,
  10812. WOLFSSL_ECC_SECP224K1, ssl->heap);
  10813. if (ret != WOLFSSL_SUCCESS) return ret;
  10814. #endif
  10815. #endif
  10816. #ifndef HAVE_FIPS
  10817. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  10818. #ifndef NO_ECC_SECP
  10819. ret = TLSX_UseSupportedCurve(extensions,
  10820. WOLFSSL_ECC_SECP192R1, ssl->heap);
  10821. if (ret != WOLFSSL_SUCCESS) return ret;
  10822. #endif
  10823. #ifdef HAVE_ECC_KOBLITZ
  10824. ret = TLSX_UseSupportedCurve(extensions,
  10825. WOLFSSL_ECC_SECP192K1, ssl->heap);
  10826. if (ret != WOLFSSL_SUCCESS) return ret;
  10827. #endif
  10828. #endif
  10829. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  10830. #ifndef NO_ECC_SECP
  10831. ret = TLSX_UseSupportedCurve(extensions,
  10832. WOLFSSL_ECC_SECP160R1, ssl->heap);
  10833. if (ret != WOLFSSL_SUCCESS) return ret;
  10834. #endif
  10835. #ifdef HAVE_ECC_SECPR2
  10836. ret = TLSX_UseSupportedCurve(extensions,
  10837. WOLFSSL_ECC_SECP160R2, ssl->heap);
  10838. if (ret != WOLFSSL_SUCCESS) return ret;
  10839. #endif
  10840. #ifdef HAVE_ECC_KOBLITZ
  10841. ret = TLSX_UseSupportedCurve(extensions,
  10842. WOLFSSL_ECC_SECP160K1, ssl->heap);
  10843. if (ret != WOLFSSL_SUCCESS) return ret;
  10844. #endif
  10845. #endif
  10846. #endif /* HAVE_FIPS */
  10847. #endif /* HAVE_ECC */
  10848. #ifndef NO_DH
  10849. /* Add FFDHE supported groups. */
  10850. #ifdef HAVE_FFDHE_8192
  10851. if (8192/8 >= ssl->options.minDhKeySz &&
  10852. 8192/8 <= ssl->options.maxDhKeySz) {
  10853. ret = TLSX_UseSupportedCurve(extensions,
  10854. WOLFSSL_FFDHE_8192, ssl->heap);
  10855. if (ret != WOLFSSL_SUCCESS)
  10856. return ret;
  10857. }
  10858. #endif
  10859. #ifdef HAVE_FFDHE_6144
  10860. if (6144/8 >= ssl->options.minDhKeySz &&
  10861. 6144/8 <= ssl->options.maxDhKeySz) {
  10862. ret = TLSX_UseSupportedCurve(extensions,
  10863. WOLFSSL_FFDHE_6144, ssl->heap);
  10864. if (ret != WOLFSSL_SUCCESS)
  10865. return ret;
  10866. }
  10867. #endif
  10868. #ifdef HAVE_FFDHE_4096
  10869. if (4096/8 >= ssl->options.minDhKeySz &&
  10870. 4096/8 <= ssl->options.maxDhKeySz) {
  10871. ret = TLSX_UseSupportedCurve(extensions,
  10872. WOLFSSL_FFDHE_4096, ssl->heap);
  10873. if (ret != WOLFSSL_SUCCESS)
  10874. return ret;
  10875. }
  10876. #endif
  10877. #ifdef HAVE_FFDHE_3072
  10878. if (3072/8 >= ssl->options.minDhKeySz &&
  10879. 3072/8 <= ssl->options.maxDhKeySz) {
  10880. ret = TLSX_UseSupportedCurve(extensions,
  10881. WOLFSSL_FFDHE_3072, ssl->heap);
  10882. if (ret != WOLFSSL_SUCCESS)
  10883. return ret;
  10884. }
  10885. #endif
  10886. #ifdef HAVE_FFDHE_2048
  10887. if (2048/8 >= ssl->options.minDhKeySz &&
  10888. 2048/8 <= ssl->options.maxDhKeySz) {
  10889. ret = TLSX_UseSupportedCurve(extensions,
  10890. WOLFSSL_FFDHE_2048, ssl->heap);
  10891. if (ret != WOLFSSL_SUCCESS)
  10892. return ret;
  10893. }
  10894. #endif
  10895. #endif
  10896. #ifdef HAVE_PQC
  10897. #ifdef WOLFSSL_WC_KYBER
  10898. #ifdef WOLFSSL_KYBER512
  10899. if (ret == WOLFSSL_SUCCESS)
  10900. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1,
  10901. ssl->heap);
  10902. #endif
  10903. #ifdef WOLFSSL_KYBER768
  10904. if (ret == WOLFSSL_SUCCESS)
  10905. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3,
  10906. ssl->heap);
  10907. #endif
  10908. #ifdef WOLFSSL_KYBER768
  10909. if (ret == WOLFSSL_SUCCESS)
  10910. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5,
  10911. ssl->heap);
  10912. #endif
  10913. #elif defined(HAVE_LIBOQS)
  10914. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap);
  10915. if (ret == WOLFSSL_SUCCESS)
  10916. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3,
  10917. ssl->heap);
  10918. if (ret == WOLFSSL_SUCCESS)
  10919. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5,
  10920. ssl->heap);
  10921. if (ret == WOLFSSL_SUCCESS)
  10922. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_KYBER_LEVEL1,
  10923. ssl->heap);
  10924. if (ret == WOLFSSL_SUCCESS)
  10925. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_KYBER_LEVEL3,
  10926. ssl->heap);
  10927. if (ret == WOLFSSL_SUCCESS)
  10928. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_KYBER_LEVEL5,
  10929. ssl->heap);
  10930. #elif defined(HAVE_PQM4)
  10931. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap);
  10932. #endif /* HAVE_LIBOQS */
  10933. #endif /* HAVE_PQC */
  10934. (void)ssl;
  10935. (void)extensions;
  10936. return ret;
  10937. }
  10938. #endif /* HAVE_SUPPORTED_CURVES */
  10939. int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer)
  10940. {
  10941. int ret = 0;
  10942. byte* public_key = NULL;
  10943. word16 public_key_len = 0;
  10944. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  10945. int usingPSK = 0;
  10946. #endif
  10947. #if defined(HAVE_SUPPORTED_CURVES) && defined(WOLFSSL_TLS13)
  10948. TLSX* extension = NULL;
  10949. word16 namedGroup = WOLFSSL_NAMED_GROUP_INVALID;
  10950. #endif
  10951. /* server will add extension depending on what is parsed from client */
  10952. if (!isServer) {
  10953. #if defined(HAVE_RPK)
  10954. ret = TLSX_ClientCertificateType_Use(ssl, isServer);
  10955. if (ret != 0)
  10956. return ret;
  10957. ret = TLSX_ServerCertificateType_Use(ssl, isServer);
  10958. if (ret != 0)
  10959. return ret;
  10960. #endif /* HAVE_RPK */
  10961. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10962. if (!ssl->options.disallowEncThenMac) {
  10963. ret = TLSX_EncryptThenMac_Use(ssl);
  10964. if (ret != 0)
  10965. return ret;
  10966. }
  10967. #endif
  10968. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  10969. defined(HAVE_CURVE448)) && defined(HAVE_SUPPORTED_CURVES)
  10970. if (!ssl->options.userCurves && !ssl->ctx->userCurves) {
  10971. if (TLSX_Find(ssl->ctx->extensions,
  10972. TLSX_SUPPORTED_GROUPS) == NULL) {
  10973. ret = TLSX_PopulateSupportedGroups(ssl, &ssl->extensions);
  10974. if (ret != WOLFSSL_SUCCESS)
  10975. return ret;
  10976. }
  10977. }
  10978. if ((!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade) &&
  10979. TLSX_Find(ssl->ctx->extensions, TLSX_EC_POINT_FORMATS) == NULL &&
  10980. TLSX_Find(ssl->extensions, TLSX_EC_POINT_FORMATS) == NULL) {
  10981. ret = TLSX_UsePointFormat(&ssl->extensions,
  10982. WOLFSSL_EC_PF_UNCOMPRESSED, ssl->heap);
  10983. if (ret != WOLFSSL_SUCCESS)
  10984. return ret;
  10985. }
  10986. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && HAVE_SUPPORTED_CURVES */
  10987. #ifdef WOLFSSL_SRTP
  10988. if (ssl->options.dtls && ssl->dtlsSrtpProfiles != 0) {
  10989. WOLFSSL_MSG("Adding DTLS SRTP extension");
  10990. if ((ret = TLSX_UseSRTP(&ssl->extensions, ssl->dtlsSrtpProfiles,
  10991. ssl->heap)) != 0) {
  10992. return ret;
  10993. }
  10994. }
  10995. #endif
  10996. } /* is not server */
  10997. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10998. WOLFSSL_MSG("Adding signature algorithms extension");
  10999. if ((ret = TLSX_SetSignatureAlgorithms(&ssl->extensions, ssl, ssl->heap))
  11000. != 0) {
  11001. return ret;
  11002. }
  11003. #else
  11004. ret = 0;
  11005. #endif
  11006. #ifdef WOLFSSL_TLS13
  11007. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11008. if (isServer && IsAtLeastTLSv1_3(ssl->version)) {
  11009. if (SSL_CA_NAMES(ssl) != NULL) {
  11010. WOLFSSL_MSG("Adding certificate authorities extension");
  11011. if ((ret = TLSX_Push(&ssl->extensions,
  11012. TLSX_CERTIFICATE_AUTHORITIES, ssl, ssl->heap)) != 0) {
  11013. return ret;
  11014. }
  11015. }
  11016. }
  11017. #endif
  11018. if (!isServer && IsAtLeastTLSv1_3(ssl->version)) {
  11019. /* Add mandatory TLS v1.3 extension: supported version */
  11020. WOLFSSL_MSG("Adding supported versions extension");
  11021. if ((ret = TLSX_SetSupportedVersions(&ssl->extensions, ssl,
  11022. ssl->heap)) != 0) {
  11023. return ret;
  11024. }
  11025. #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && \
  11026. !defined(HAVE_CURVE448) && defined(HAVE_SUPPORTED_CURVES)
  11027. if (TLSX_Find(ssl->ctx->extensions, TLSX_SUPPORTED_GROUPS) == NULL) {
  11028. /* Put in DH groups for TLS 1.3 only. */
  11029. ret = TLSX_PopulateSupportedGroups(ssl, &ssl->extensions);
  11030. if (ret != WOLFSSL_SUCCESS)
  11031. return ret;
  11032. /* ret value will be overwritten in !NO_PSK case */
  11033. #ifdef NO_PSK
  11034. ret = 0;
  11035. #endif
  11036. }
  11037. #endif /* !(HAVE_ECC || CURVE25519 || CURVE448) && HAVE_SUPPORTED_CURVES */
  11038. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11039. if (ssl->certHashSigAlgoSz > 0) {
  11040. WOLFSSL_MSG("Adding signature algorithms cert extension");
  11041. if ((ret = TLSX_SetSignatureAlgorithmsCert(&ssl->extensions,
  11042. ssl, ssl->heap)) != 0) {
  11043. return ret;
  11044. }
  11045. }
  11046. #endif
  11047. #if defined(HAVE_SUPPORTED_CURVES)
  11048. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  11049. if (extension == NULL) {
  11050. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11051. if (ssl->options.resuming && ssl->session->namedGroup != 0)
  11052. namedGroup = ssl->session->namedGroup;
  11053. else
  11054. #endif
  11055. if (ssl->numGroups > 0) {
  11056. int set = 0;
  11057. int i, j;
  11058. /* try to find the highest element in ssl->group[]
  11059. * that is contained in preferredGroup[].
  11060. */
  11061. namedGroup = preferredGroup[0];
  11062. for (i = 0; i < ssl->numGroups && !set; i++) {
  11063. for (j = 0; preferredGroup[j] != WOLFSSL_NAMED_GROUP_INVALID; j++) {
  11064. if (preferredGroup[j] == ssl->group[i]
  11065. #ifdef HAVE_LIBOQS
  11066. && TLSX_KeyShare_IsSupported(preferredGroup[j])
  11067. #endif
  11068. ) {
  11069. namedGroup = ssl->group[i];
  11070. set = 1;
  11071. break;
  11072. }
  11073. }
  11074. }
  11075. if (!set)
  11076. namedGroup = WOLFSSL_NAMED_GROUP_INVALID;
  11077. }
  11078. else {
  11079. /* Choose the most preferred group. */
  11080. namedGroup = preferredGroup[0];
  11081. #ifdef HAVE_LIBOQS
  11082. if (!TLSX_KeyShare_IsSupported(namedGroup)) {
  11083. int i = 1;
  11084. for (;preferredGroup[i] != WOLFSSL_NAMED_GROUP_INVALID;
  11085. i++) {
  11086. if (TLSX_KeyShare_IsSupported(preferredGroup[i]))
  11087. break;
  11088. }
  11089. namedGroup = preferredGroup[i];
  11090. }
  11091. #endif
  11092. }
  11093. }
  11094. else {
  11095. KeyShareEntry* kse = (KeyShareEntry*)extension->data;
  11096. if (kse)
  11097. namedGroup = kse->group;
  11098. }
  11099. if (namedGroup != WOLFSSL_NAMED_GROUP_INVALID) {
  11100. ret = TLSX_KeyShare_Use(ssl, namedGroup, 0, NULL, NULL,
  11101. &ssl->extensions);
  11102. if (ret != 0)
  11103. return ret;
  11104. }
  11105. #endif /* HAVE_SUPPORTED_CURVES */
  11106. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11107. TLSX_Remove(&ssl->extensions, TLSX_PRE_SHARED_KEY, ssl->heap);
  11108. #endif
  11109. #if defined(HAVE_SESSION_TICKET)
  11110. if (ssl->options.resuming && ssl->session->ticketLen > 0) {
  11111. WOLFSSL_SESSION* sess = ssl->session;
  11112. #ifdef WOLFSSL_32BIT_MILLI_TIME
  11113. word32 now, milli;
  11114. #else
  11115. word64 now, milli;
  11116. #endif
  11117. if (sess->ticketLen > MAX_PSK_ID_LEN) {
  11118. WOLFSSL_MSG("Session ticket length for PSK ext is too large");
  11119. return BUFFER_ERROR;
  11120. }
  11121. /* Determine the MAC algorithm for the cipher suite used. */
  11122. ssl->options.cipherSuite0 = sess->cipherSuite0;
  11123. ssl->options.cipherSuite = sess->cipherSuite;
  11124. ret = SetCipherSpecs(ssl);
  11125. if (ret != 0)
  11126. return ret;
  11127. now = TimeNowInMilliseconds();
  11128. if (now == 0)
  11129. return GETTIME_ERROR;
  11130. #ifdef WOLFSSL_32BIT_MILLI_TIME
  11131. if (now < sess->ticketSeen)
  11132. milli = (0xFFFFFFFFU - sess->ticketSeen) + 1 + now;
  11133. else
  11134. milli = now - sess->ticketSeen;
  11135. milli += sess->ticketAdd;
  11136. /* Pre-shared key is mandatory extension for resumption. */
  11137. ret = TLSX_PreSharedKey_Use(&ssl->extensions, sess->ticket,
  11138. sess->ticketLen, milli, ssl->specs.mac_algorithm,
  11139. ssl->options.cipherSuite0, ssl->options.cipherSuite, 1,
  11140. NULL, ssl->heap);
  11141. #else
  11142. milli = now - sess->ticketSeen + sess->ticketAdd;
  11143. /* Pre-shared key is mandatory extension for resumption. */
  11144. ret = TLSX_PreSharedKey_Use(&ssl->extensions, sess->ticket,
  11145. sess->ticketLen, (word32)milli, ssl->specs.mac_algorithm,
  11146. ssl->options.cipherSuite0, ssl->options.cipherSuite, 1,
  11147. NULL, ssl->heap);
  11148. #endif
  11149. if (ret != 0)
  11150. return ret;
  11151. usingPSK = 1;
  11152. }
  11153. #endif
  11154. #ifndef NO_PSK
  11155. #ifndef WOLFSSL_PSK_ONE_ID
  11156. if (ssl->options.client_psk_cs_cb != NULL) {
  11157. int i;
  11158. const Suites* suites = WOLFSSL_SUITES(ssl);
  11159. for (i = 0; i < suites->suiteSz; i += 2) {
  11160. byte cipherSuite0 = suites->suites[i + 0];
  11161. byte cipherSuite = suites->suites[i + 1];
  11162. unsigned int keySz;
  11163. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11164. int cnt = 0;
  11165. #endif
  11166. #ifdef HAVE_NULL_CIPHER
  11167. if (cipherSuite0 == ECC_BYTE ||
  11168. cipherSuite0 == ECDHE_PSK_BYTE) {
  11169. if (cipherSuite != TLS_SHA256_SHA256 &&
  11170. cipherSuite != TLS_SHA384_SHA384) {
  11171. continue;
  11172. }
  11173. }
  11174. else
  11175. #endif
  11176. #if (defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)) && \
  11177. defined(WOLFSSL_SM3)
  11178. if (cipherSuite0 == CIPHER_BYTE) {
  11179. if ((cipherSuite != TLS_SM4_GCM_SM3) &&
  11180. (cipherSuite != TLS_SM4_CCM_SM3)) {
  11181. continue;
  11182. }
  11183. }
  11184. else
  11185. #endif
  11186. if (cipherSuite0 != TLS13_BYTE)
  11187. continue;
  11188. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11189. do {
  11190. ssl->arrays->client_identity[0] = cnt;
  11191. #endif
  11192. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  11193. keySz = ssl->options.client_psk_cs_cb(
  11194. ssl, ssl->arrays->server_hint,
  11195. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  11196. ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
  11197. GetCipherNameInternal(cipherSuite0, cipherSuite));
  11198. if (keySz > 0) {
  11199. ssl->arrays->psk_keySz = keySz;
  11200. ret = TLSX_PreSharedKey_Use(&ssl->extensions,
  11201. (byte*)ssl->arrays->client_identity,
  11202. (word16)XSTRLEN(ssl->arrays->client_identity),
  11203. 0, SuiteMac(WOLFSSL_SUITES(ssl)->suites + i),
  11204. cipherSuite0, cipherSuite, 0, NULL, ssl->heap);
  11205. if (ret != 0)
  11206. return ret;
  11207. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11208. cnt++;
  11209. #endif
  11210. }
  11211. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  11212. }
  11213. while (keySz > 0);
  11214. #endif
  11215. }
  11216. usingPSK = 1;
  11217. }
  11218. else
  11219. #endif
  11220. if (ssl->options.client_psk_cb != NULL ||
  11221. ssl->options.client_psk_tls13_cb != NULL) {
  11222. /* Default cipher suite. */
  11223. byte cipherSuite0 = TLS13_BYTE;
  11224. byte cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
  11225. int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
  11226. const char* cipherName = NULL;
  11227. if (ssl->options.client_psk_tls13_cb != NULL) {
  11228. ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(
  11229. ssl, ssl->arrays->server_hint,
  11230. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  11231. ssl->arrays->psk_key, MAX_PSK_KEY_LEN, &cipherName);
  11232. if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
  11233. &cipherSuite, &cipherSuiteFlags) != 0) {
  11234. return PSK_KEY_ERROR;
  11235. }
  11236. }
  11237. else {
  11238. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  11239. ssl->arrays->server_hint, ssl->arrays->client_identity,
  11240. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  11241. }
  11242. #if defined(OPENSSL_EXTRA)
  11243. /* OpenSSL treats 0 as a PSK key length of 0
  11244. * and meaning no PSK available.
  11245. */
  11246. if (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  11247. return PSK_KEY_ERROR;
  11248. }
  11249. if (ssl->arrays->psk_keySz > 0) {
  11250. #else
  11251. if (ssl->arrays->psk_keySz == 0 ||
  11252. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  11253. return PSK_KEY_ERROR;
  11254. }
  11255. #endif
  11256. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  11257. ssl->options.cipherSuite0 = cipherSuite0;
  11258. ssl->options.cipherSuite = cipherSuite;
  11259. (void)cipherSuiteFlags;
  11260. ret = SetCipherSpecs(ssl);
  11261. if (ret != 0)
  11262. return ret;
  11263. ret = TLSX_PreSharedKey_Use(&ssl->extensions,
  11264. (byte*)ssl->arrays->client_identity,
  11265. (word16)XSTRLEN(ssl->arrays->client_identity),
  11266. 0, ssl->specs.mac_algorithm,
  11267. cipherSuite0, cipherSuite, 0,
  11268. NULL, ssl->heap);
  11269. if (ret != 0)
  11270. return ret;
  11271. usingPSK = 1;
  11272. #if defined(OPENSSL_EXTRA)
  11273. }
  11274. #endif
  11275. }
  11276. #endif /* !NO_PSK */
  11277. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11278. /* Some servers do not generate session tickets unless
  11279. * the extension is seen in a non-resume client hello.
  11280. * We used to send it only if we were otherwise using PSK.
  11281. * Now always send it. Define NO_TLSX_PSKKEM_PLAIN_ANNOUNCE
  11282. * to revert to the old behaviour. */
  11283. #ifdef NO_TLSX_PSKKEM_PLAIN_ANNOUNCE
  11284. if (usingPSK)
  11285. #endif
  11286. {
  11287. byte modes = 0;
  11288. (void)usingPSK;
  11289. /* Pre-shared key modes: mandatory extension for resumption. */
  11290. #ifdef HAVE_SUPPORTED_CURVES
  11291. if (!ssl->options.onlyPskDheKe)
  11292. #endif
  11293. {
  11294. modes = 1 << PSK_KE;
  11295. }
  11296. #if !defined(NO_DH) || defined(HAVE_ECC) || \
  11297. defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  11298. if (!ssl->options.noPskDheKe) {
  11299. modes |= 1 << PSK_DHE_KE;
  11300. }
  11301. #endif
  11302. ret = TLSX_PskKeyModes_Use(ssl, modes);
  11303. if (ret != 0)
  11304. return ret;
  11305. }
  11306. #endif
  11307. #if defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  11308. if (!isServer && ssl->options.postHandshakeAuth) {
  11309. ret = TLSX_PostHandAuth_Use(ssl);
  11310. if (ret != 0)
  11311. return ret;
  11312. }
  11313. #endif
  11314. #if defined(HAVE_ECH)
  11315. /* GREASE ECH */
  11316. if (ssl->echConfigs == NULL) {
  11317. ret = GREASE_ECH_USE(&(ssl->extensions), ssl->heap, ssl->rng);
  11318. }
  11319. else if (ssl->echConfigs != NULL) {
  11320. ret = ECH_USE(ssl->echConfigs, &(ssl->extensions), ssl->heap,
  11321. ssl->rng);
  11322. }
  11323. #endif
  11324. }
  11325. #if defined(HAVE_ECH)
  11326. else if (IsAtLeastTLSv1_3(ssl->version)) {
  11327. if (ssl->ctx->echConfigs != NULL) {
  11328. ret = SERVER_ECH_USE(&(ssl->extensions), ssl->heap,
  11329. ssl->ctx->echConfigs);
  11330. if (ret == 0)
  11331. TLSX_SetResponse(ssl, TLSX_ECH);
  11332. }
  11333. }
  11334. #endif
  11335. #endif
  11336. (void)isServer;
  11337. (void)public_key;
  11338. (void)public_key_len;
  11339. (void)ssl;
  11340. return ret;
  11341. }
  11342. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  11343. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11344. /* because the size of ech depends on the size of other extensions we need to
  11345. * get the size with ech special and process ech last, return status */
  11346. static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType,
  11347. word16* pLength)
  11348. {
  11349. int ret = 0;
  11350. TLSX* echX = NULL;
  11351. TLSX* serverNameX = NULL;
  11352. TLSX** extensions = NULL;
  11353. #ifdef WOLFSSL_SMALL_STACK
  11354. char* tmpServerName = NULL;
  11355. #else
  11356. char tmpServerName[MAX_PUBLIC_NAME_SZ];
  11357. #endif
  11358. /* calculate the rest of the extensions length with inner ech */
  11359. if (ssl->extensions)
  11360. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  11361. if (echX == NULL && ssl->ctx && ssl->ctx->extensions)
  11362. echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH);
  11363. /* if type is outer change sni to public name */
  11364. if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) {
  11365. if (ssl->extensions) {
  11366. serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  11367. if (serverNameX != NULL)
  11368. extensions = &ssl->extensions;
  11369. }
  11370. if (serverNameX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11371. serverNameX = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  11372. extensions = &ssl->ctx->extensions;
  11373. }
  11374. /* store the inner server name */
  11375. if (serverNameX != NULL) {
  11376. char* hostName = ((SNI*)serverNameX->data)->data.host_name;
  11377. word32 hostNameSz = (word32)XSTRLEN(hostName) + 1;
  11378. #ifdef WOLFSSL_SMALL_STACK
  11379. tmpServerName = (char*)XMALLOC(hostNameSz, ssl->heap,
  11380. DYNAMIC_TYPE_TMP_BUFFER);
  11381. if (tmpServerName == NULL)
  11382. return MEMORY_E;
  11383. #else
  11384. /* truncate if too long */
  11385. if (hostNameSz > MAX_PUBLIC_NAME_SZ)
  11386. hostNameSz = MAX_PUBLIC_NAME_SZ;
  11387. #endif
  11388. XMEMCPY(tmpServerName, hostName, hostNameSz);
  11389. }
  11390. /* remove the inner server name */
  11391. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11392. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11393. ((WOLFSSL_ECH*)echX->data)->echConfig->publicName,
  11394. XSTRLEN(((WOLFSSL_ECH*)echX->data)->echConfig->publicName),
  11395. ssl->heap);
  11396. /* set the public name as the server name */
  11397. if (ret == WOLFSSL_SUCCESS)
  11398. ret = 0;
  11399. }
  11400. if (ret == 0 && ssl->extensions)
  11401. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, pLength);
  11402. if (ret == 0 && ssl->ctx && ssl->ctx->extensions)
  11403. ret = TLSX_GetSize(ssl->ctx->extensions, semaphore, msgType, pLength);
  11404. if (serverNameX != NULL) {
  11405. /* remove the public name SNI */
  11406. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11407. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11408. tmpServerName, XSTRLEN(tmpServerName), ssl->heap);
  11409. /* restore the inner server name */
  11410. if (ret == WOLFSSL_SUCCESS)
  11411. ret = 0;
  11412. }
  11413. #ifdef WOLFSSL_SMALL_STACK
  11414. XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11415. #endif
  11416. return ret;
  11417. }
  11418. #endif
  11419. /** Tells the buffered size of extensions to be sent into the client hello. */
  11420. int TLSX_GetRequestSize(WOLFSSL* ssl, byte msgType, word16* pLength)
  11421. {
  11422. int ret = 0;
  11423. word16 length = 0;
  11424. byte semaphore[SEMAPHORE_SIZE] = {0};
  11425. if (!TLSX_SupportExtensions(ssl))
  11426. return 0;
  11427. if (msgType == client_hello) {
  11428. EC_VALIDATE_REQUEST(ssl, semaphore);
  11429. PF_VALIDATE_REQUEST(ssl, semaphore);
  11430. WOLF_STK_VALIDATE_REQUEST(ssl);
  11431. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11432. if (WOLFSSL_SUITES(ssl)->hashSigAlgoSz == 0)
  11433. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11434. #endif
  11435. #if defined(WOLFSSL_TLS13)
  11436. if (!IsAtLeastTLSv1_2(ssl)) {
  11437. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11438. }
  11439. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11440. if (!IsAtLeastTLSv1_3(ssl->version)) {
  11441. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11442. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11443. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11444. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PSK_KEY_EXCHANGE_MODES));
  11445. #endif
  11446. #ifdef WOLFSSL_EARLY_DATA
  11447. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11448. #endif
  11449. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11450. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11451. #endif
  11452. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  11453. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_POST_HANDSHAKE_AUTH));
  11454. #endif
  11455. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11456. TURN_ON(semaphore,
  11457. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11458. #endif
  11459. }
  11460. #endif
  11461. #endif /* WOLFSSL_TLS13 */
  11462. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  11463. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  11464. if (!SSL_CM(ssl)->ocspStaplingEnabled) {
  11465. /* mark already sent, so it won't send it */
  11466. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11467. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11468. }
  11469. #endif
  11470. }
  11471. #ifdef WOLFSSL_TLS13
  11472. #ifndef NO_CERTS
  11473. else if (msgType == certificate_request) {
  11474. /* Don't send out any extension except those that are turned off. */
  11475. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11476. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11477. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11478. #endif
  11479. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11480. if (SSL_CA_NAMES(ssl) != NULL)
  11481. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11482. #endif
  11483. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, OID_FILTERS
  11484. * TLSX_STATUS_REQUEST
  11485. */
  11486. }
  11487. #endif
  11488. #if defined(HAVE_ECH)
  11489. if (ssl->options.useEch == 1 && msgType == client_hello) {
  11490. ret = TLSX_GetSizeWithEch(ssl, semaphore, msgType, &length);
  11491. if (ret != 0)
  11492. return ret;
  11493. }
  11494. else
  11495. #endif /* HAVE_ECH */
  11496. #endif /* WOLFSSL_TLS13 */
  11497. {
  11498. if (ssl->extensions) {
  11499. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, &length);
  11500. if (ret != 0)
  11501. return ret;
  11502. }
  11503. if (ssl->ctx && ssl->ctx->extensions) {
  11504. ret = TLSX_GetSize(ssl->ctx->extensions, semaphore, msgType,
  11505. &length);
  11506. if (ret != 0)
  11507. return ret;
  11508. }
  11509. }
  11510. #ifdef HAVE_EXTENDED_MASTER
  11511. if (msgType == client_hello && ssl->options.haveEMS &&
  11512. (!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade)) {
  11513. length += HELLO_EXT_SZ;
  11514. }
  11515. #endif
  11516. if (length)
  11517. length += OPAQUE16_LEN; /* for total length storage. */
  11518. *pLength += length;
  11519. return ret;
  11520. }
  11521. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11522. /* return status after writing the extensions with ech written last */
  11523. static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore,
  11524. byte msgType, word16* pOffset)
  11525. {
  11526. int ret = 0;
  11527. TLSX* echX = NULL;
  11528. TLSX* serverNameX = NULL;
  11529. TLSX** extensions = NULL;
  11530. #ifdef WOLFSSL_SMALL_STACK
  11531. char* tmpServerName = NULL;
  11532. #else
  11533. char tmpServerName[MAX_PUBLIC_NAME_SZ];
  11534. #endif
  11535. /* get the echX from either extensions or ctx */
  11536. if (ssl->extensions)
  11537. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  11538. if (echX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11539. /* if not NULL the semaphore will stop it from being counted */
  11540. if (echX == NULL)
  11541. echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH);
  11542. }
  11543. /* if type is outer change sni to public name */
  11544. if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) {
  11545. if (ssl->extensions) {
  11546. serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  11547. if (serverNameX != NULL)
  11548. extensions = &ssl->extensions;
  11549. }
  11550. if (serverNameX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11551. serverNameX = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  11552. extensions = &ssl->ctx->extensions;
  11553. }
  11554. /* store the inner server name */
  11555. if (serverNameX != NULL) {
  11556. char* hostName = ((SNI*)serverNameX->data)->data.host_name;
  11557. word32 hostNameSz = (word32)XSTRLEN(hostName) + 1;
  11558. #ifdef WOLFSSL_SMALL_STACK
  11559. tmpServerName = (char*)XMALLOC(hostNameSz, ssl->heap,
  11560. DYNAMIC_TYPE_TMP_BUFFER);
  11561. if (tmpServerName == NULL)
  11562. return MEMORY_E;
  11563. #else
  11564. /* truncate if too long */
  11565. if (hostNameSz > MAX_PUBLIC_NAME_SZ)
  11566. hostNameSz = MAX_PUBLIC_NAME_SZ;
  11567. #endif
  11568. XMEMCPY(tmpServerName, hostName, hostNameSz);
  11569. }
  11570. /* remove the inner server name */
  11571. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11572. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11573. ((WOLFSSL_ECH*)echX->data)->echConfig->publicName,
  11574. XSTRLEN(((WOLFSSL_ECH*)echX->data)->echConfig->publicName),
  11575. ssl->heap);
  11576. /* set the public name as the server name */
  11577. if (ret == WOLFSSL_SUCCESS)
  11578. ret = 0;
  11579. }
  11580. if (echX != NULL) {
  11581. /* turn ech on so it doesn't write, then write it last */
  11582. TURN_ON(semaphore, TLSX_ToSemaphore(echX->type));
  11583. }
  11584. if (ret == 0 && ssl->extensions) {
  11585. ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore,
  11586. msgType, pOffset);
  11587. }
  11588. if (ret == 0 && ssl->ctx && ssl->ctx->extensions) {
  11589. ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore,
  11590. msgType, pOffset);
  11591. }
  11592. if (echX != NULL) {
  11593. /* turn off and write it last */
  11594. TURN_OFF(semaphore, TLSX_ToSemaphore(echX->type));
  11595. }
  11596. if (ret == 0 && ssl->extensions) {
  11597. ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore,
  11598. msgType, pOffset);
  11599. }
  11600. if (ret == 0 && ssl->ctx && ssl->ctx->extensions) {
  11601. ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore,
  11602. msgType, pOffset);
  11603. }
  11604. if (serverNameX != NULL) {
  11605. /* remove the public name SNI */
  11606. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11607. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME, tmpServerName,
  11608. XSTRLEN(tmpServerName), ssl->heap);
  11609. /* restore the inner server name */
  11610. if (ret == WOLFSSL_SUCCESS)
  11611. ret = 0;
  11612. }
  11613. #ifdef WOLFSSL_SMALL_STACK
  11614. XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11615. #endif
  11616. return ret;
  11617. }
  11618. #endif
  11619. /** Writes the extensions to be sent into the client hello. */
  11620. int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word16* pOffset)
  11621. {
  11622. int ret = 0;
  11623. word16 offset = 0;
  11624. byte semaphore[SEMAPHORE_SIZE] = {0};
  11625. if (!TLSX_SupportExtensions(ssl) || output == NULL)
  11626. return 0;
  11627. offset += OPAQUE16_LEN; /* extensions length */
  11628. if (msgType == client_hello) {
  11629. EC_VALIDATE_REQUEST(ssl, semaphore);
  11630. PF_VALIDATE_REQUEST(ssl, semaphore);
  11631. WOLF_STK_VALIDATE_REQUEST(ssl);
  11632. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11633. if (WOLFSSL_SUITES(ssl)->hashSigAlgoSz == 0)
  11634. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11635. #endif
  11636. #ifdef WOLFSSL_TLS13
  11637. if (!IsAtLeastTLSv1_2(ssl)) {
  11638. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11639. }
  11640. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11641. if (!IsAtLeastTLSv1_3(ssl->version)) {
  11642. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11643. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11644. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PSK_KEY_EXCHANGE_MODES));
  11645. #endif
  11646. #ifdef WOLFSSL_EARLY_DATA
  11647. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11648. #endif
  11649. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11650. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11651. #endif
  11652. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  11653. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_POST_HANDSHAKE_AUTH));
  11654. #endif
  11655. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11656. TURN_ON(semaphore,
  11657. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11658. #endif
  11659. }
  11660. #endif
  11661. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11662. /* Must write Pre-shared Key extension at the end in TLS v1.3.
  11663. * Must not write out Pre-shared Key extension in earlier versions of
  11664. * protocol.
  11665. */
  11666. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11667. #endif
  11668. #endif /* WOLFSSL_TLS13 */
  11669. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  11670. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  11671. /* mark already sent, so it won't send it */
  11672. if (!SSL_CM(ssl)->ocspStaplingEnabled) {
  11673. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11674. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11675. }
  11676. #endif
  11677. }
  11678. #ifdef WOLFSSL_TLS13
  11679. #ifndef NO_CERTS
  11680. else if (msgType == certificate_request) {
  11681. /* Don't send out any extension except those that are turned off. */
  11682. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11683. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11684. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11685. #endif
  11686. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11687. if (SSL_CA_NAMES(ssl) != NULL) {
  11688. TURN_OFF(semaphore,
  11689. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11690. }
  11691. #endif
  11692. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, TLSX_OID_FILTERS
  11693. * TLSX_STATUS_REQUEST
  11694. */
  11695. }
  11696. #endif
  11697. #endif
  11698. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11699. if (ssl->options.useEch == 1 && msgType == client_hello) {
  11700. ret = TLSX_WriteWithEch(ssl, output, semaphore,
  11701. msgType, &offset);
  11702. if (ret != 0)
  11703. return ret;
  11704. }
  11705. else
  11706. #endif
  11707. {
  11708. if (ssl->extensions) {
  11709. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11710. msgType, &offset);
  11711. if (ret != 0)
  11712. return ret;
  11713. }
  11714. if (ssl->ctx && ssl->ctx->extensions) {
  11715. ret = TLSX_Write(ssl->ctx->extensions, output + offset, semaphore,
  11716. msgType, &offset);
  11717. if (ret != 0)
  11718. return ret;
  11719. }
  11720. }
  11721. #ifdef HAVE_EXTENDED_MASTER
  11722. if (msgType == client_hello && ssl->options.haveEMS &&
  11723. (!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade)) {
  11724. WOLFSSL_MSG("EMS extension to write");
  11725. c16toa(HELLO_EXT_EXTMS, output + offset);
  11726. offset += HELLO_EXT_TYPE_SZ;
  11727. c16toa(0, output + offset);
  11728. offset += HELLO_EXT_SZ_SZ;
  11729. }
  11730. #endif
  11731. #ifdef WOLFSSL_TLS13
  11732. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11733. if (msgType == client_hello && IsAtLeastTLSv1_3(ssl->version)) {
  11734. /* Write out what we can of Pre-shared key extension. */
  11735. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11736. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11737. client_hello, &offset);
  11738. if (ret != 0)
  11739. return ret;
  11740. }
  11741. #endif
  11742. #endif
  11743. if (offset > OPAQUE16_LEN || msgType != client_hello)
  11744. c16toa(offset - OPAQUE16_LEN, output); /* extensions length */
  11745. *pOffset += offset;
  11746. return ret;
  11747. }
  11748. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  11749. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_SERVER)
  11750. /** Tells the buffered size of extensions to be sent into the server hello. */
  11751. int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength)
  11752. {
  11753. int ret = 0;
  11754. word16 length = 0;
  11755. byte semaphore[SEMAPHORE_SIZE] = {0};
  11756. switch (msgType) {
  11757. #ifndef NO_WOLFSSL_SERVER
  11758. case server_hello:
  11759. PF_VALIDATE_RESPONSE(ssl, semaphore);
  11760. #ifdef WOLFSSL_TLS13
  11761. if (IsAtLeastTLSv1_3(ssl->version)) {
  11762. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11763. TURN_OFF(semaphore,
  11764. TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11765. #if defined(HAVE_SUPPORTED_CURVES)
  11766. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11767. if (!ssl->options.noPskDheKe)
  11768. #endif
  11769. {
  11770. /* Expect KeyShare extension in ServerHello. */
  11771. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11772. }
  11773. #endif
  11774. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11775. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11776. #endif
  11777. #ifdef WOLFSSL_DTLS_CID
  11778. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11779. #endif
  11780. }
  11781. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11782. else {
  11783. #ifdef HAVE_SUPPORTED_CURVES
  11784. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11785. #endif
  11786. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11787. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11788. #endif
  11789. }
  11790. #endif
  11791. #endif /* WOLFSSL_TLS13 */
  11792. break;
  11793. #ifdef WOLFSSL_TLS13
  11794. case hello_retry_request:
  11795. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11796. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11797. #ifdef HAVE_SUPPORTED_CURVES
  11798. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11799. if (!ssl->options.noPskDheKe)
  11800. #endif
  11801. {
  11802. /* Expect KeyShare extension in HelloRetryRequest. */
  11803. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11804. }
  11805. #endif
  11806. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11807. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11808. #endif
  11809. break;
  11810. #endif
  11811. #ifdef WOLFSSL_TLS13
  11812. case encrypted_extensions:
  11813. /* Send out all extension except those that are turned on. */
  11814. #ifdef HAVE_ECC
  11815. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  11816. #endif
  11817. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11818. #ifdef HAVE_SESSION_TICKET
  11819. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SESSION_TICKET));
  11820. #endif
  11821. #ifdef HAVE_SUPPORTED_CURVES
  11822. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11823. #endif
  11824. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11825. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11826. #endif
  11827. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  11828. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11829. #endif
  11830. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  11831. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11832. #endif
  11833. #if defined(HAVE_SERVER_RENEGOTIATION_INFO)
  11834. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_RENEGOTIATION_INFO));
  11835. #endif
  11836. #ifdef WOLFSSL_DTLS_CID
  11837. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11838. #endif /* WOLFSSL_DTLS_CID */
  11839. break;
  11840. #ifdef WOLFSSL_EARLY_DATA
  11841. case session_ticket:
  11842. if (ssl->options.tls1_3) {
  11843. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11844. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11845. }
  11846. break;
  11847. #endif
  11848. #endif
  11849. #endif
  11850. #ifdef WOLFSSL_TLS13
  11851. #ifndef NO_CERTS
  11852. case certificate:
  11853. /* Don't send out any extension except those that are turned off. */
  11854. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11855. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11856. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP,
  11857. * TLSX_SERVER_CERTIFICATE_TYPE
  11858. */
  11859. break;
  11860. #endif
  11861. #endif
  11862. }
  11863. #ifdef HAVE_EXTENDED_MASTER
  11864. if (ssl->options.haveEMS && msgType == server_hello &&
  11865. !IsAtLeastTLSv1_3(ssl->version)) {
  11866. length += HELLO_EXT_SZ;
  11867. }
  11868. #endif
  11869. if (TLSX_SupportExtensions(ssl)) {
  11870. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, &length);
  11871. if (ret != 0)
  11872. return ret;
  11873. }
  11874. /* All the response data is set at the ssl object only, so no ctx here. */
  11875. if (length || msgType != server_hello)
  11876. length += OPAQUE16_LEN; /* for total length storage. */
  11877. *pLength += length;
  11878. return ret;
  11879. }
  11880. /** Writes the server hello extensions into a buffer. */
  11881. int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset)
  11882. {
  11883. int ret = 0;
  11884. word16 offset = 0;
  11885. if (TLSX_SupportExtensions(ssl) && output) {
  11886. byte semaphore[SEMAPHORE_SIZE] = {0};
  11887. switch (msgType) {
  11888. #ifndef NO_WOLFSSL_SERVER
  11889. case server_hello:
  11890. PF_VALIDATE_RESPONSE(ssl, semaphore);
  11891. #ifdef WOLFSSL_TLS13
  11892. if (IsAtLeastTLSv1_3(ssl->version)) {
  11893. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11894. TURN_OFF(semaphore,
  11895. TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11896. #ifdef HAVE_SUPPORTED_CURVES
  11897. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11898. if (!ssl->options.noPskDheKe)
  11899. #endif
  11900. {
  11901. /* Write out KeyShare in ServerHello. */
  11902. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11903. }
  11904. #endif
  11905. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11906. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11907. #endif
  11908. #ifdef WOLFSSL_DTLS_CID
  11909. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11910. #endif /* WOLFSSL_DTLS_CID */
  11911. }
  11912. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11913. else {
  11914. #ifdef HAVE_SUPPORTED_CURVES
  11915. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11916. #endif
  11917. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11918. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11919. #endif
  11920. }
  11921. #endif
  11922. #endif
  11923. break;
  11924. #ifdef WOLFSSL_TLS13
  11925. case hello_retry_request:
  11926. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11927. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11928. #ifdef HAVE_SUPPORTED_CURVES
  11929. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11930. if (!ssl->options.noPskDheKe)
  11931. #endif
  11932. {
  11933. /* Write out KeyShare in HelloRetryRequest. */
  11934. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11935. }
  11936. #endif
  11937. /* Cookie is written below as last extension. */
  11938. break;
  11939. #endif
  11940. #ifdef WOLFSSL_TLS13
  11941. case encrypted_extensions:
  11942. /* Send out all extension except those that are turned on. */
  11943. #ifdef HAVE_ECC
  11944. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  11945. #endif
  11946. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11947. #ifdef HAVE_SESSION_TICKET
  11948. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SESSION_TICKET));
  11949. #endif
  11950. #ifdef HAVE_SUPPORTED_CURVES
  11951. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11952. #endif
  11953. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11954. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11955. #endif
  11956. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  11957. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11958. #endif
  11959. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  11960. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11961. #endif
  11962. #if defined(HAVE_SERVER_RENEGOTIATION_INFO)
  11963. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_RENEGOTIATION_INFO));
  11964. #endif
  11965. #ifdef WOLFSSL_DTLS_CID
  11966. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11967. #endif /* WOLFSSL_DTLS_CID */
  11968. break;
  11969. #ifdef WOLFSSL_EARLY_DATA
  11970. case session_ticket:
  11971. if (ssl->options.tls1_3) {
  11972. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11973. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11974. }
  11975. break;
  11976. #endif
  11977. #endif
  11978. #endif
  11979. #ifdef WOLFSSL_TLS13
  11980. #ifndef NO_CERTS
  11981. case certificate:
  11982. /* Don't send out any extension except those that are turned
  11983. * off. */
  11984. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11985. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11986. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP,
  11987. * TLSX_SERVER_CERTIFICATE_TYPE
  11988. */
  11989. break;
  11990. #endif
  11991. #endif
  11992. default:
  11993. break;
  11994. }
  11995. offset += OPAQUE16_LEN; /* extensions length */
  11996. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11997. msgType, &offset);
  11998. if (ret != 0)
  11999. return ret;
  12000. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  12001. if (msgType == hello_retry_request) {
  12002. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  12003. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  12004. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  12005. msgType, &offset);
  12006. if (ret != 0)
  12007. return ret;
  12008. }
  12009. #endif
  12010. #ifdef HAVE_EXTENDED_MASTER
  12011. if (ssl->options.haveEMS && msgType == server_hello &&
  12012. !IsAtLeastTLSv1_3(ssl->version)) {
  12013. WOLFSSL_MSG("EMS extension to write");
  12014. c16toa(HELLO_EXT_EXTMS, output + offset);
  12015. offset += HELLO_EXT_TYPE_SZ;
  12016. c16toa(0, output + offset);
  12017. offset += HELLO_EXT_SZ_SZ;
  12018. }
  12019. #endif
  12020. if (offset > OPAQUE16_LEN || msgType != server_hello)
  12021. c16toa(offset - OPAQUE16_LEN, output); /* extensions length */
  12022. }
  12023. if (pOffset)
  12024. *pOffset += offset;
  12025. return ret;
  12026. }
  12027. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_SERVER */
  12028. #ifdef WOLFSSL_TLS13
  12029. int TLSX_ParseVersion(WOLFSSL* ssl, const byte* input, word16 length,
  12030. byte msgType, int* found)
  12031. {
  12032. int ret = 0;
  12033. int offset = 0;
  12034. *found = 0;
  12035. while (offset < (int)length) {
  12036. word16 type;
  12037. word16 size;
  12038. if (offset + (2 * OPAQUE16_LEN) > length) {
  12039. ret = BUFFER_ERROR;
  12040. break;
  12041. }
  12042. ato16(input + offset, &type);
  12043. offset += HELLO_EXT_TYPE_SZ;
  12044. ato16(input + offset, &size);
  12045. offset += OPAQUE16_LEN;
  12046. if (offset + size > length) {
  12047. ret = BUFFER_ERROR;
  12048. break;
  12049. }
  12050. if (type == TLSX_SUPPORTED_VERSIONS) {
  12051. *found = 1;
  12052. WOLFSSL_MSG("Supported Versions extension received");
  12053. ret = SV_PARSE(ssl, input + offset, size, msgType, &ssl->version,
  12054. &ssl->options, &ssl->extensions);
  12055. break;
  12056. }
  12057. offset += size;
  12058. }
  12059. return ret;
  12060. }
  12061. #endif
  12062. /** Parses a buffer of TLS extensions. */
  12063. int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType,
  12064. Suites *suites)
  12065. {
  12066. int ret = 0;
  12067. word16 offset = 0;
  12068. byte isRequest = (msgType == client_hello ||
  12069. msgType == certificate_request);
  12070. #ifdef HAVE_EXTENDED_MASTER
  12071. byte pendingEMS = 0;
  12072. #endif
  12073. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  12074. int pskDone = 0;
  12075. #endif
  12076. byte seenType[SEMAPHORE_SIZE]; /* Seen known extensions. */
  12077. if (!ssl || !input || (isRequest && !suites))
  12078. return BAD_FUNC_ARG;
  12079. /* No known extensions seen yet. */
  12080. XMEMSET(seenType, 0, sizeof(seenType));
  12081. while (ret == 0 && offset < length) {
  12082. word16 type;
  12083. word16 size;
  12084. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  12085. if (msgType == client_hello && pskDone) {
  12086. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  12087. return PSK_KEY_ERROR;
  12088. }
  12089. #endif
  12090. if (length - offset < HELLO_EXT_TYPE_SZ + OPAQUE16_LEN)
  12091. return BUFFER_ERROR;
  12092. ato16(input + offset, &type);
  12093. offset += HELLO_EXT_TYPE_SZ;
  12094. ato16(input + offset, &size);
  12095. offset += OPAQUE16_LEN;
  12096. /* Check we have a bit for extension type. */
  12097. if ((type <= 62) || (type == TLSX_RENEGOTIATION_INFO)
  12098. #ifdef WOLFSSL_QUIC
  12099. || (type == TLSX_KEY_QUIC_TP_PARAMS_DRAFT)
  12100. #endif
  12101. )
  12102. {
  12103. /* Detect duplicate recognized extensions. */
  12104. if (IS_OFF(seenType, TLSX_ToSemaphore(type))) {
  12105. TURN_ON(seenType, TLSX_ToSemaphore(type));
  12106. }
  12107. else {
  12108. return DUPLICATE_TLS_EXT_E;
  12109. }
  12110. }
  12111. if (length - offset < size)
  12112. return BUFFER_ERROR;
  12113. switch (type) {
  12114. #ifdef HAVE_SNI
  12115. case TLSX_SERVER_NAME:
  12116. WOLFSSL_MSG("SNI extension received");
  12117. #ifdef WOLFSSL_DEBUG_TLS
  12118. WOLFSSL_BUFFER(input + offset, size);
  12119. #endif
  12120. #ifdef WOLFSSL_TLS13
  12121. if (IsAtLeastTLSv1_3(ssl->version)) {
  12122. if (msgType != client_hello &&
  12123. msgType != encrypted_extensions)
  12124. return EXT_NOT_ALLOWED;
  12125. }
  12126. else
  12127. #endif
  12128. {
  12129. if (msgType != client_hello &&
  12130. msgType != server_hello)
  12131. return EXT_NOT_ALLOWED;
  12132. }
  12133. ret = SNI_PARSE(ssl, input + offset, size, isRequest);
  12134. break;
  12135. #endif
  12136. case TLSX_TRUSTED_CA_KEYS:
  12137. WOLFSSL_MSG("Trusted CA extension received");
  12138. #ifdef WOLFSSL_DEBUG_TLS
  12139. WOLFSSL_BUFFER(input + offset, size);
  12140. #endif
  12141. #ifdef WOLFSSL_TLS13
  12142. /* RFC 8446 4.2.4 states trusted_ca_keys is not used
  12143. in TLS 1.3. */
  12144. if (IsAtLeastTLSv1_3(ssl->version)) {
  12145. return EXT_NOT_ALLOWED;
  12146. }
  12147. else
  12148. #endif
  12149. {
  12150. if (msgType != client_hello &&
  12151. msgType != server_hello)
  12152. return EXT_NOT_ALLOWED;
  12153. }
  12154. ret = TCA_PARSE(ssl, input + offset, size, isRequest);
  12155. break;
  12156. case TLSX_MAX_FRAGMENT_LENGTH:
  12157. WOLFSSL_MSG("Max Fragment Length extension received");
  12158. #ifdef WOLFSSL_DEBUG_TLS
  12159. WOLFSSL_BUFFER(input + offset, size);
  12160. #endif
  12161. #ifdef WOLFSSL_TLS13
  12162. if (IsAtLeastTLSv1_3(ssl->version)) {
  12163. if (msgType != client_hello &&
  12164. msgType != encrypted_extensions) {
  12165. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12166. return EXT_NOT_ALLOWED;
  12167. }
  12168. }
  12169. else
  12170. #endif
  12171. {
  12172. if (msgType != client_hello &&
  12173. msgType != server_hello) {
  12174. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12175. return EXT_NOT_ALLOWED;
  12176. }
  12177. }
  12178. ret = MFL_PARSE(ssl, input + offset, size, isRequest);
  12179. break;
  12180. case TLSX_TRUNCATED_HMAC:
  12181. WOLFSSL_MSG("Truncated HMAC extension received");
  12182. #ifdef WOLFSSL_DEBUG_TLS
  12183. WOLFSSL_BUFFER(input + offset, size);
  12184. #endif
  12185. #ifdef WOLFSSL_TLS13
  12186. if (IsAtLeastTLSv1_3(ssl->version))
  12187. break;
  12188. #endif
  12189. if (msgType != client_hello)
  12190. return EXT_NOT_ALLOWED;
  12191. ret = THM_PARSE(ssl, input + offset, size, isRequest);
  12192. break;
  12193. case TLSX_SUPPORTED_GROUPS:
  12194. WOLFSSL_MSG("Supported Groups extension received");
  12195. #ifdef WOLFSSL_DEBUG_TLS
  12196. WOLFSSL_BUFFER(input + offset, size);
  12197. #endif
  12198. #ifdef WOLFSSL_TLS13
  12199. if (IsAtLeastTLSv1_3(ssl->version)) {
  12200. if (msgType != client_hello &&
  12201. msgType != encrypted_extensions) {
  12202. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12203. return EXT_NOT_ALLOWED;
  12204. }
  12205. }
  12206. else
  12207. #endif
  12208. {
  12209. if (msgType != client_hello) {
  12210. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12211. return EXT_NOT_ALLOWED;
  12212. }
  12213. }
  12214. ret = EC_PARSE(ssl, input + offset, size, isRequest,
  12215. &ssl->extensions);
  12216. break;
  12217. case TLSX_EC_POINT_FORMATS:
  12218. WOLFSSL_MSG("Point Formats extension received");
  12219. #ifdef WOLFSSL_DEBUG_TLS
  12220. WOLFSSL_BUFFER(input + offset, size);
  12221. #endif
  12222. #ifdef WOLFSSL_TLS13
  12223. if (IsAtLeastTLSv1_3(ssl->version))
  12224. break;
  12225. #endif
  12226. if (msgType != client_hello &&
  12227. msgType != server_hello) {
  12228. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12229. return EXT_NOT_ALLOWED;
  12230. }
  12231. ret = PF_PARSE(ssl, input + offset, size, isRequest);
  12232. break;
  12233. case TLSX_STATUS_REQUEST:
  12234. WOLFSSL_MSG("Certificate Status Request extension received");
  12235. #ifdef WOLFSSL_DEBUG_TLS
  12236. WOLFSSL_BUFFER(input + offset, size);
  12237. #endif
  12238. #ifdef WOLFSSL_TLS13
  12239. if (IsAtLeastTLSv1_3(ssl->version)) {
  12240. if (msgType != client_hello &&
  12241. msgType != certificate_request &&
  12242. msgType != certificate)
  12243. return EXT_NOT_ALLOWED;
  12244. }
  12245. else
  12246. #endif
  12247. {
  12248. if (msgType != client_hello &&
  12249. msgType != server_hello)
  12250. return EXT_NOT_ALLOWED;
  12251. }
  12252. ret = CSR_PARSE(ssl, input + offset, size, isRequest);
  12253. break;
  12254. case TLSX_STATUS_REQUEST_V2:
  12255. WOLFSSL_MSG("Certificate Status Request v2 extension received");
  12256. #ifdef WOLFSSL_DEBUG_TLS
  12257. WOLFSSL_BUFFER(input + offset, size);
  12258. #endif
  12259. #if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  12260. if (IsAtLeastTLSv1_3(ssl->version)) {
  12261. if (msgType != client_hello &&
  12262. msgType != certificate_request &&
  12263. msgType != certificate)
  12264. return EXT_NOT_ALLOWED;
  12265. }
  12266. else
  12267. #endif
  12268. {
  12269. if (msgType != client_hello &&
  12270. msgType != server_hello)
  12271. return EXT_NOT_ALLOWED;
  12272. }
  12273. ret = CSR2_PARSE(ssl, input + offset, size, isRequest);
  12274. break;
  12275. #ifdef HAVE_EXTENDED_MASTER
  12276. case HELLO_EXT_EXTMS:
  12277. WOLFSSL_MSG("Extended Master Secret extension received");
  12278. #ifdef WOLFSSL_DEBUG_TLS
  12279. WOLFSSL_BUFFER(input + offset, size);
  12280. #endif
  12281. #if defined(WOLFSSL_TLS13)
  12282. if (IsAtLeastTLSv1_3(ssl->version))
  12283. break;
  12284. #endif
  12285. if (msgType != client_hello &&
  12286. msgType != server_hello)
  12287. return EXT_NOT_ALLOWED;
  12288. if (size != 0)
  12289. return BUFFER_ERROR;
  12290. #ifndef NO_WOLFSSL_SERVER
  12291. if (isRequest)
  12292. ssl->options.haveEMS = 1;
  12293. #endif
  12294. pendingEMS = 1;
  12295. break;
  12296. #endif
  12297. case TLSX_RENEGOTIATION_INFO:
  12298. WOLFSSL_MSG("Secure Renegotiation extension received");
  12299. #ifdef WOLFSSL_DEBUG_TLS
  12300. WOLFSSL_BUFFER(input + offset, size);
  12301. #endif
  12302. #ifdef WOLFSSL_TLS13
  12303. if (IsAtLeastTLSv1_3(ssl->version))
  12304. break;
  12305. #endif
  12306. if (msgType != client_hello &&
  12307. msgType != server_hello)
  12308. return EXT_NOT_ALLOWED;
  12309. ret = SCR_PARSE(ssl, input + offset, size, isRequest);
  12310. break;
  12311. case TLSX_SESSION_TICKET:
  12312. WOLFSSL_MSG("Session Ticket extension received");
  12313. #ifdef WOLFSSL_DEBUG_TLS
  12314. WOLFSSL_BUFFER(input + offset, size);
  12315. #endif
  12316. #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)
  12317. if (IsAtLeastTLSv1_3(ssl->version)) {
  12318. if (msgType != client_hello)
  12319. return EXT_NOT_ALLOWED;
  12320. }
  12321. else
  12322. #endif
  12323. {
  12324. if (msgType != client_hello &&
  12325. msgType != server_hello)
  12326. return EXT_NOT_ALLOWED;
  12327. }
  12328. ret = WOLF_STK_PARSE(ssl, input + offset, size, isRequest);
  12329. break;
  12330. case TLSX_APPLICATION_LAYER_PROTOCOL:
  12331. WOLFSSL_MSG("ALPN extension received");
  12332. #ifdef WOLFSSL_DEBUG_TLS
  12333. WOLFSSL_BUFFER(input + offset, size);
  12334. #endif
  12335. #if defined(WOLFSSL_TLS13) && defined(HAVE_ALPN)
  12336. if (IsAtLeastTLSv1_3(ssl->version)) {
  12337. if (msgType != client_hello &&
  12338. msgType != encrypted_extensions)
  12339. return EXT_NOT_ALLOWED;
  12340. }
  12341. else
  12342. #endif
  12343. {
  12344. if (msgType != client_hello &&
  12345. msgType != server_hello)
  12346. return EXT_NOT_ALLOWED;
  12347. }
  12348. ret = ALPN_PARSE(ssl, input + offset, size, isRequest);
  12349. break;
  12350. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  12351. case TLSX_SIGNATURE_ALGORITHMS:
  12352. WOLFSSL_MSG("Signature Algorithms extension received");
  12353. #ifdef WOLFSSL_DEBUG_TLS
  12354. WOLFSSL_BUFFER(input + offset, size);
  12355. #endif
  12356. if (!IsAtLeastTLSv1_2(ssl))
  12357. break;
  12358. #ifdef WOLFSSL_TLS13
  12359. if (IsAtLeastTLSv1_3(ssl->version)) {
  12360. if (msgType != client_hello &&
  12361. msgType != certificate_request)
  12362. return EXT_NOT_ALLOWED;
  12363. }
  12364. else
  12365. #endif
  12366. {
  12367. if (msgType != client_hello)
  12368. return EXT_NOT_ALLOWED;
  12369. }
  12370. ret = SA_PARSE(ssl, input + offset, size, isRequest, suites);
  12371. break;
  12372. #endif
  12373. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  12374. case TLSX_ENCRYPT_THEN_MAC:
  12375. WOLFSSL_MSG("Encrypt-Then-Mac extension received");
  12376. /* Ignore for TLS 1.3+ */
  12377. if (IsAtLeastTLSv1_3(ssl->version))
  12378. break;
  12379. if (msgType != client_hello &&
  12380. msgType != server_hello)
  12381. return EXT_NOT_ALLOWED;
  12382. ret = ETM_PARSE(ssl, input + offset, size, msgType);
  12383. break;
  12384. #endif /* HAVE_ENCRYPT_THEN_MAC */
  12385. #ifdef WOLFSSL_TLS13
  12386. case TLSX_SUPPORTED_VERSIONS:
  12387. WOLFSSL_MSG("Skipping Supported Versions - already processed");
  12388. #ifdef WOLFSSL_DEBUG_TLS
  12389. WOLFSSL_BUFFER(input + offset, size);
  12390. #endif
  12391. if (msgType != client_hello &&
  12392. msgType != server_hello &&
  12393. msgType != hello_retry_request)
  12394. return EXT_NOT_ALLOWED;
  12395. break;
  12396. #ifdef WOLFSSL_SEND_HRR_COOKIE
  12397. case TLSX_COOKIE:
  12398. WOLFSSL_MSG("Cookie extension received");
  12399. #ifdef WOLFSSL_DEBUG_TLS
  12400. WOLFSSL_BUFFER(input + offset, size);
  12401. #endif
  12402. if (!IsAtLeastTLSv1_3(ssl->version))
  12403. break;
  12404. if (msgType != client_hello &&
  12405. msgType != hello_retry_request) {
  12406. return EXT_NOT_ALLOWED;
  12407. }
  12408. ret = CKE_PARSE(ssl, input + offset, size, msgType);
  12409. break;
  12410. #endif
  12411. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  12412. case TLSX_PRE_SHARED_KEY:
  12413. WOLFSSL_MSG("Pre-Shared Key extension received");
  12414. #ifdef WOLFSSL_DEBUG_TLS
  12415. WOLFSSL_BUFFER(input + offset, size);
  12416. #endif
  12417. if (!IsAtLeastTLSv1_3(ssl->version))
  12418. break;
  12419. if (msgType != client_hello &&
  12420. msgType != server_hello) {
  12421. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12422. return EXT_NOT_ALLOWED;
  12423. }
  12424. ret = PSK_PARSE(ssl, input + offset, size, msgType);
  12425. pskDone = 1;
  12426. break;
  12427. case TLSX_PSK_KEY_EXCHANGE_MODES:
  12428. WOLFSSL_MSG("PSK Key Exchange Modes extension received");
  12429. #ifdef WOLFSSL_DEBUG_TLS
  12430. WOLFSSL_BUFFER(input + offset, size);
  12431. #endif
  12432. if (!IsAtLeastTLSv1_3(ssl->version))
  12433. break;
  12434. if (msgType != client_hello) {
  12435. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12436. return EXT_NOT_ALLOWED;
  12437. }
  12438. ret = PKM_PARSE(ssl, input + offset, size, msgType);
  12439. break;
  12440. #endif
  12441. #ifdef WOLFSSL_EARLY_DATA
  12442. case TLSX_EARLY_DATA:
  12443. WOLFSSL_MSG("Early Data extension received");
  12444. #ifdef WOLFSSL_DEBUG_TLS
  12445. WOLFSSL_BUFFER(input + offset, size);
  12446. #endif
  12447. if (!IsAtLeastTLSv1_3(ssl->version))
  12448. break;
  12449. if (msgType != client_hello && msgType != session_ticket &&
  12450. msgType != encrypted_extensions) {
  12451. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12452. return EXT_NOT_ALLOWED;
  12453. }
  12454. ret = EDI_PARSE(ssl, input + offset, size, msgType);
  12455. break;
  12456. #endif
  12457. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  12458. case TLSX_POST_HANDSHAKE_AUTH:
  12459. WOLFSSL_MSG("Post Handshake Authentication extension received");
  12460. #ifdef WOLFSSL_DEBUG_TLS
  12461. WOLFSSL_BUFFER(input + offset, size);
  12462. #endif
  12463. if (!IsAtLeastTLSv1_3(ssl->version))
  12464. break;
  12465. if (msgType != client_hello) {
  12466. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12467. return EXT_NOT_ALLOWED;
  12468. }
  12469. ret = PHA_PARSE(ssl, input + offset, size, msgType);
  12470. break;
  12471. #endif
  12472. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  12473. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  12474. WOLFSSL_MSG("Signature Algorithms extension received");
  12475. #ifdef WOLFSSL_DEBUG_TLS
  12476. WOLFSSL_BUFFER(input + offset, size);
  12477. #endif
  12478. if (!IsAtLeastTLSv1_3(ssl->version))
  12479. break;
  12480. if (msgType != client_hello &&
  12481. msgType != certificate_request) {
  12482. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12483. return EXT_NOT_ALLOWED;
  12484. }
  12485. ret = SAC_PARSE(ssl, input + offset, size, isRequest);
  12486. break;
  12487. #endif
  12488. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  12489. case TLSX_CERTIFICATE_AUTHORITIES:
  12490. WOLFSSL_MSG("Certificate Authorities extension received");
  12491. #ifdef WOLFSSL_DEBUG_TLS
  12492. WOLFSSL_BUFFER(input + offset, size);
  12493. #endif
  12494. if (!IsAtLeastTLSv1_3(ssl->version))
  12495. break;
  12496. if (msgType != client_hello &&
  12497. msgType != certificate_request) {
  12498. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12499. return EXT_NOT_ALLOWED;
  12500. }
  12501. ret = CAN_PARSE(ssl, input + offset, size, isRequest);
  12502. break;
  12503. #endif
  12504. case TLSX_KEY_SHARE:
  12505. WOLFSSL_MSG("Key Share extension received");
  12506. #ifdef WOLFSSL_DEBUG_TLS
  12507. WOLFSSL_BUFFER(input + offset, size);
  12508. #endif
  12509. #ifdef HAVE_SUPPORTED_CURVES
  12510. if (!IsAtLeastTLSv1_3(ssl->version))
  12511. break;
  12512. if (msgType != client_hello && msgType != server_hello &&
  12513. msgType != hello_retry_request) {
  12514. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  12515. return EXT_NOT_ALLOWED;
  12516. }
  12517. #endif
  12518. ret = KS_PARSE(ssl, input + offset, size, msgType);
  12519. break;
  12520. #endif
  12521. #ifdef WOLFSSL_SRTP
  12522. case TLSX_USE_SRTP:
  12523. WOLFSSL_MSG("Use SRTP extension received");
  12524. ret = SRTP_PARSE(ssl, input + offset, size, isRequest);
  12525. break;
  12526. #endif
  12527. #ifdef WOLFSSL_QUIC
  12528. case TLSX_KEY_QUIC_TP_PARAMS:
  12529. FALL_THROUGH;
  12530. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  12531. WOLFSSL_MSG("QUIC transport parameter received");
  12532. #ifdef WOLFSSL_DEBUG_TLS
  12533. WOLFSSL_BUFFER(input + offset, size);
  12534. #endif
  12535. if (IsAtLeastTLSv1_3(ssl->version) &&
  12536. msgType != client_hello &&
  12537. msgType != server_hello &&
  12538. msgType != encrypted_extensions) {
  12539. return EXT_NOT_ALLOWED;
  12540. }
  12541. else if (!IsAtLeastTLSv1_3(ssl->version) &&
  12542. msgType == encrypted_extensions) {
  12543. return EXT_NOT_ALLOWED;
  12544. }
  12545. else if (WOLFSSL_IS_QUIC(ssl)) {
  12546. ret = QTP_PARSE(ssl, input + offset, size, type, msgType);
  12547. }
  12548. else {
  12549. WOLFSSL_MSG("QUIC transport param TLS extension type, but no QUIC");
  12550. return EXT_NOT_ALLOWED; /* be safe, this should not happen */
  12551. }
  12552. break;
  12553. #endif /* WOLFSSL_QUIC */
  12554. #if defined(WOLFSSL_DTLS_CID)
  12555. case TLSX_CONNECTION_ID:
  12556. /* connection ID not supported in DTLSv1.2 */
  12557. if (!IsAtLeastTLSv1_3(ssl->version))
  12558. break;
  12559. if (msgType != client_hello && msgType != server_hello)
  12560. return EXT_NOT_ALLOWED;
  12561. WOLFSSL_MSG("ConnectionID extension received");
  12562. ret = CID_PARSE(ssl, input + offset, size, isRequest);
  12563. break;
  12564. #endif /* defined(WOLFSSL_DTLS_CID) */
  12565. #if defined(HAVE_RPK)
  12566. case TLSX_CLIENT_CERTIFICATE_TYPE:
  12567. WOLFSSL_MSG("Client Certificate Type extension received");
  12568. ret = CCT_PARSE(ssl, input + offset, size, msgType);
  12569. break;
  12570. case TLSX_SERVER_CERTIFICATE_TYPE:
  12571. WOLFSSL_MSG("Server Certificate Type extension received");
  12572. ret = SCT_PARSE(ssl, input + offset, size, msgType);
  12573. break;
  12574. #endif /* HAVE_RPK */
  12575. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  12576. case TLSX_ECH:
  12577. WOLFSSL_MSG("ECH extension received");
  12578. ret = ECH_PARSE(ssl, input + offset, size, msgType);
  12579. break;
  12580. #endif
  12581. default:
  12582. WOLFSSL_MSG("Unknown TLS extension type");
  12583. }
  12584. /* offset should be updated here! */
  12585. offset += size;
  12586. }
  12587. #ifdef HAVE_EXTENDED_MASTER
  12588. if (IsAtLeastTLSv1_3(ssl->version) && msgType == hello_retry_request) {
  12589. /* Don't change EMS status until server_hello received.
  12590. * Second ClientHello must have same extensions.
  12591. */
  12592. }
  12593. else if (!isRequest && ssl->options.haveEMS && !pendingEMS)
  12594. ssl->options.haveEMS = 0;
  12595. #endif
  12596. if (ret == 0)
  12597. ret = SNI_VERIFY_PARSE(ssl, isRequest);
  12598. if (ret == 0)
  12599. ret = TCA_VERIFY_PARSE(ssl, isRequest);
  12600. return ret;
  12601. }
  12602. /* undefining semaphore macros */
  12603. #undef IS_OFF
  12604. #undef TURN_ON
  12605. #undef SEMAPHORE_SIZE
  12606. #endif /* HAVE_TLS_EXTENSIONS */
  12607. #ifndef NO_WOLFSSL_CLIENT
  12608. WOLFSSL_METHOD* wolfTLS_client_method(void)
  12609. {
  12610. return wolfTLS_client_method_ex(NULL);
  12611. }
  12612. WOLFSSL_METHOD* wolfTLS_client_method_ex(void* heap)
  12613. {
  12614. WOLFSSL_METHOD* method =
  12615. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12616. heap, DYNAMIC_TYPE_METHOD);
  12617. (void)heap;
  12618. WOLFSSL_ENTER("TLS_client_method_ex");
  12619. if (method) {
  12620. #if defined(WOLFSSL_TLS13)
  12621. InitSSL_Method(method, MakeTLSv1_3());
  12622. #elif !defined(WOLFSSL_NO_TLS12)
  12623. InitSSL_Method(method, MakeTLSv1_2());
  12624. #elif !defined(NO_OLD_TLS)
  12625. InitSSL_Method(method, MakeTLSv1_1());
  12626. #elif defined(WOLFSSL_ALLOW_TLSV10)
  12627. InitSSL_Method(method, MakeTLSv1());
  12628. #else
  12629. #error No TLS version enabled!
  12630. #endif
  12631. method->downgrade = 1;
  12632. method->side = WOLFSSL_CLIENT_END;
  12633. }
  12634. return method;
  12635. }
  12636. #ifndef NO_OLD_TLS
  12637. #ifdef WOLFSSL_ALLOW_TLSV10
  12638. WOLFSSL_METHOD* wolfTLSv1_client_method(void)
  12639. {
  12640. return wolfTLSv1_client_method_ex(NULL);
  12641. }
  12642. WOLFSSL_METHOD* wolfTLSv1_client_method_ex(void* heap)
  12643. {
  12644. WOLFSSL_METHOD* method =
  12645. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12646. heap, DYNAMIC_TYPE_METHOD);
  12647. (void)heap;
  12648. WOLFSSL_ENTER("TLSv1_client_method_ex");
  12649. if (method)
  12650. InitSSL_Method(method, MakeTLSv1());
  12651. return method;
  12652. }
  12653. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12654. WOLFSSL_METHOD* wolfTLSv1_1_client_method(void)
  12655. {
  12656. return wolfTLSv1_1_client_method_ex(NULL);
  12657. }
  12658. WOLFSSL_METHOD* wolfTLSv1_1_client_method_ex(void* heap)
  12659. {
  12660. WOLFSSL_METHOD* method =
  12661. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12662. heap, DYNAMIC_TYPE_METHOD);
  12663. (void)heap;
  12664. WOLFSSL_ENTER("TLSv1_1_client_method_ex");
  12665. if (method)
  12666. InitSSL_Method(method, MakeTLSv1_1());
  12667. return method;
  12668. }
  12669. #endif /* !NO_OLD_TLS */
  12670. #ifndef WOLFSSL_NO_TLS12
  12671. WOLFSSL_ABI
  12672. WOLFSSL_METHOD* wolfTLSv1_2_client_method(void)
  12673. {
  12674. return wolfTLSv1_2_client_method_ex(NULL);
  12675. }
  12676. WOLFSSL_METHOD* wolfTLSv1_2_client_method_ex(void* heap)
  12677. {
  12678. WOLFSSL_METHOD* method =
  12679. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12680. heap, DYNAMIC_TYPE_METHOD);
  12681. (void)heap;
  12682. WOLFSSL_ENTER("TLSv1_2_client_method_ex");
  12683. if (method)
  12684. InitSSL_Method(method, MakeTLSv1_2());
  12685. return method;
  12686. }
  12687. #endif /* WOLFSSL_NO_TLS12 */
  12688. #ifdef WOLFSSL_TLS13
  12689. /* The TLS v1.3 client method data.
  12690. *
  12691. * returns the method data for a TLS v1.3 client.
  12692. */
  12693. WOLFSSL_ABI
  12694. WOLFSSL_METHOD* wolfTLSv1_3_client_method(void)
  12695. {
  12696. return wolfTLSv1_3_client_method_ex(NULL);
  12697. }
  12698. /* The TLS v1.3 client method data.
  12699. *
  12700. * heap The heap used for allocation.
  12701. * returns the method data for a TLS v1.3 client.
  12702. */
  12703. WOLFSSL_METHOD* wolfTLSv1_3_client_method_ex(void* heap)
  12704. {
  12705. WOLFSSL_METHOD* method = (WOLFSSL_METHOD*)
  12706. XMALLOC(sizeof(WOLFSSL_METHOD), heap,
  12707. DYNAMIC_TYPE_METHOD);
  12708. (void)heap;
  12709. WOLFSSL_ENTER("TLSv1_3_client_method_ex");
  12710. if (method)
  12711. InitSSL_Method(method, MakeTLSv1_3());
  12712. return method;
  12713. }
  12714. #endif /* WOLFSSL_TLS13 */
  12715. #ifdef WOLFSSL_DTLS
  12716. WOLFSSL_METHOD* wolfDTLS_client_method(void)
  12717. {
  12718. return wolfDTLS_client_method_ex(NULL);
  12719. }
  12720. WOLFSSL_METHOD* wolfDTLS_client_method_ex(void* heap)
  12721. {
  12722. WOLFSSL_METHOD* method =
  12723. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12724. heap, DYNAMIC_TYPE_METHOD);
  12725. (void)heap;
  12726. WOLFSSL_ENTER("DTLS_client_method_ex");
  12727. if (method) {
  12728. #if defined(WOLFSSL_DTLS13)
  12729. InitSSL_Method(method, MakeDTLSv1_3());
  12730. #elif !defined(WOLFSSL_NO_TLS12)
  12731. InitSSL_Method(method, MakeDTLSv1_2());
  12732. #elif !defined(NO_OLD_TLS)
  12733. InitSSL_Method(method, MakeDTLSv1());
  12734. #else
  12735. #error No DTLS version enabled!
  12736. #endif
  12737. method->downgrade = 1;
  12738. method->side = WOLFSSL_CLIENT_END;
  12739. }
  12740. return method;
  12741. }
  12742. #ifndef NO_OLD_TLS
  12743. WOLFSSL_METHOD* wolfDTLSv1_client_method(void)
  12744. {
  12745. return wolfDTLSv1_client_method_ex(NULL);
  12746. }
  12747. WOLFSSL_METHOD* wolfDTLSv1_client_method_ex(void* heap)
  12748. {
  12749. WOLFSSL_METHOD* method =
  12750. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12751. heap, DYNAMIC_TYPE_METHOD);
  12752. (void)heap;
  12753. WOLFSSL_ENTER("DTLSv1_client_method_ex");
  12754. if (method)
  12755. InitSSL_Method(method, MakeDTLSv1());
  12756. return method;
  12757. }
  12758. #endif /* NO_OLD_TLS */
  12759. #ifndef WOLFSSL_NO_TLS12
  12760. WOLFSSL_METHOD* wolfDTLSv1_2_client_method(void)
  12761. {
  12762. return wolfDTLSv1_2_client_method_ex(NULL);
  12763. }
  12764. WOLFSSL_METHOD* wolfDTLSv1_2_client_method_ex(void* heap)
  12765. {
  12766. WOLFSSL_METHOD* method =
  12767. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12768. heap, DYNAMIC_TYPE_METHOD);
  12769. (void)heap;
  12770. WOLFSSL_ENTER("DTLSv1_2_client_method_ex");
  12771. if (method)
  12772. InitSSL_Method(method, MakeDTLSv1_2());
  12773. (void)heap;
  12774. return method;
  12775. }
  12776. #endif /* !WOLFSSL_NO_TLS12 */
  12777. #endif /* WOLFSSL_DTLS */
  12778. #endif /* NO_WOLFSSL_CLIENT */
  12779. /* EITHER SIDE METHODS */
  12780. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
  12781. #ifndef NO_OLD_TLS
  12782. #ifdef WOLFSSL_ALLOW_TLSV10
  12783. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12784. *
  12785. * Returns a pointer to a WOLFSSL_METHOD struct
  12786. */
  12787. WOLFSSL_METHOD* wolfTLSv1_method(void)
  12788. {
  12789. return wolfTLSv1_method_ex(NULL);
  12790. }
  12791. WOLFSSL_METHOD* wolfTLSv1_method_ex(void* heap)
  12792. {
  12793. WOLFSSL_METHOD* m;
  12794. WOLFSSL_ENTER("TLSv1_method");
  12795. #ifndef NO_WOLFSSL_CLIENT
  12796. m = wolfTLSv1_client_method_ex(heap);
  12797. #else
  12798. m = wolfTLSv1_server_method_ex(heap);
  12799. #endif
  12800. if (m != NULL) {
  12801. m->side = WOLFSSL_NEITHER_END;
  12802. }
  12803. return m;
  12804. }
  12805. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12806. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12807. *
  12808. * Returns a pointer to a WOLFSSL_METHOD struct
  12809. */
  12810. WOLFSSL_METHOD* wolfTLSv1_1_method(void)
  12811. {
  12812. return wolfTLSv1_1_method_ex(NULL);
  12813. }
  12814. WOLFSSL_METHOD* wolfTLSv1_1_method_ex(void* heap)
  12815. {
  12816. WOLFSSL_METHOD* m;
  12817. WOLFSSL_ENTER("TLSv1_1_method");
  12818. #ifndef NO_WOLFSSL_CLIENT
  12819. m = wolfTLSv1_1_client_method_ex(heap);
  12820. #else
  12821. m = wolfTLSv1_1_server_method_ex(heap);
  12822. #endif
  12823. if (m != NULL) {
  12824. m->side = WOLFSSL_NEITHER_END;
  12825. }
  12826. return m;
  12827. }
  12828. #endif /* !NO_OLD_TLS */
  12829. #ifndef WOLFSSL_NO_TLS12
  12830. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12831. *
  12832. * Returns a pointer to a WOLFSSL_METHOD struct
  12833. */
  12834. WOLFSSL_METHOD* wolfTLSv1_2_method(void)
  12835. {
  12836. return wolfTLSv1_2_method_ex(NULL);
  12837. }
  12838. WOLFSSL_METHOD* wolfTLSv1_2_method_ex(void* heap)
  12839. {
  12840. WOLFSSL_METHOD* m;
  12841. WOLFSSL_ENTER("TLSv1_2_method");
  12842. #ifndef NO_WOLFSSL_CLIENT
  12843. m = wolfTLSv1_2_client_method_ex(heap);
  12844. #else
  12845. m = wolfTLSv1_2_server_method_ex(heap);
  12846. #endif
  12847. if (m != NULL) {
  12848. m->side = WOLFSSL_NEITHER_END;
  12849. }
  12850. return m;
  12851. }
  12852. #endif /* !WOLFSSL_NO_TLS12 */
  12853. #ifdef WOLFSSL_TLS13
  12854. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12855. *
  12856. * Returns a pointer to a WOLFSSL_METHOD struct
  12857. */
  12858. WOLFSSL_METHOD* wolfTLSv1_3_method(void)
  12859. {
  12860. return wolfTLSv1_3_method_ex(NULL);
  12861. }
  12862. WOLFSSL_METHOD* wolfTLSv1_3_method_ex(void* heap)
  12863. {
  12864. WOLFSSL_METHOD* m;
  12865. WOLFSSL_ENTER("TLSv1_3_method");
  12866. #ifndef NO_WOLFSSL_CLIENT
  12867. m = wolfTLSv1_3_client_method_ex(heap);
  12868. #else
  12869. m = wolfTLSv1_3_server_method_ex(heap);
  12870. #endif
  12871. if (m != NULL) {
  12872. m->side = WOLFSSL_NEITHER_END;
  12873. }
  12874. return m;
  12875. }
  12876. #endif /* WOLFSSL_TLS13 */
  12877. #ifdef WOLFSSL_DTLS
  12878. WOLFSSL_METHOD* wolfDTLS_method(void)
  12879. {
  12880. return wolfDTLS_method_ex(NULL);
  12881. }
  12882. WOLFSSL_METHOD* wolfDTLS_method_ex(void* heap)
  12883. {
  12884. WOLFSSL_METHOD* m;
  12885. WOLFSSL_ENTER("DTLS_method_ex");
  12886. #ifndef NO_WOLFSSL_CLIENT
  12887. m = wolfDTLS_client_method_ex(heap);
  12888. #else
  12889. m = wolfDTLS_server_method_ex(heap);
  12890. #endif
  12891. if (m != NULL) {
  12892. m->side = WOLFSSL_NEITHER_END;
  12893. }
  12894. return m;
  12895. }
  12896. #ifndef NO_OLD_TLS
  12897. WOLFSSL_METHOD* wolfDTLSv1_method(void)
  12898. {
  12899. return wolfDTLSv1_method_ex(NULL);
  12900. }
  12901. WOLFSSL_METHOD* wolfDTLSv1_method_ex(void* heap)
  12902. {
  12903. WOLFSSL_METHOD* m;
  12904. WOLFSSL_ENTER("DTLSv1_method_ex");
  12905. #ifndef NO_WOLFSSL_CLIENT
  12906. m = wolfDTLSv1_client_method_ex(heap);
  12907. #else
  12908. m = wolfDTLSv1_server_method_ex(heap);
  12909. #endif
  12910. if (m != NULL) {
  12911. m->side = WOLFSSL_NEITHER_END;
  12912. }
  12913. return m;
  12914. }
  12915. #endif /* !NO_OLD_TLS */
  12916. #ifndef WOLFSSL_NO_TLS12
  12917. WOLFSSL_METHOD* wolfDTLSv1_2_method(void)
  12918. {
  12919. return wolfDTLSv1_2_method_ex(NULL);
  12920. }
  12921. WOLFSSL_METHOD* wolfDTLSv1_2_method_ex(void* heap)
  12922. {
  12923. WOLFSSL_METHOD* m;
  12924. WOLFSSL_ENTER("DTLSv1_2_method");
  12925. #ifndef NO_WOLFSSL_CLIENT
  12926. m = wolfDTLSv1_2_client_method_ex(heap);
  12927. #else
  12928. m = wolfDTLSv1_2_server_method_ex(heap);
  12929. #endif
  12930. if (m != NULL) {
  12931. m->side = WOLFSSL_NEITHER_END;
  12932. }
  12933. return m;
  12934. }
  12935. #endif /* !WOLFSSL_NO_TLS12 */
  12936. #endif /* WOLFSSL_DTLS */
  12937. #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
  12938. #ifndef NO_WOLFSSL_SERVER
  12939. WOLFSSL_METHOD* wolfTLS_server_method(void)
  12940. {
  12941. return wolfTLS_server_method_ex(NULL);
  12942. }
  12943. WOLFSSL_METHOD* wolfTLS_server_method_ex(void* heap)
  12944. {
  12945. WOLFSSL_METHOD* method =
  12946. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12947. heap, DYNAMIC_TYPE_METHOD);
  12948. (void)heap;
  12949. WOLFSSL_ENTER("TLS_server_method_ex");
  12950. if (method) {
  12951. #if defined(WOLFSSL_TLS13)
  12952. InitSSL_Method(method, MakeTLSv1_3());
  12953. #elif !defined(WOLFSSL_NO_TLS12)
  12954. InitSSL_Method(method, MakeTLSv1_2());
  12955. #elif !defined(NO_OLD_TLS)
  12956. InitSSL_Method(method, MakeTLSv1_1());
  12957. #elif defined(WOLFSSL_ALLOW_TLSV10)
  12958. InitSSL_Method(method, MakeTLSv1());
  12959. #else
  12960. #error No TLS version enabled!
  12961. #endif
  12962. method->downgrade = 1;
  12963. method->side = WOLFSSL_SERVER_END;
  12964. }
  12965. return method;
  12966. }
  12967. #ifndef NO_OLD_TLS
  12968. #ifdef WOLFSSL_ALLOW_TLSV10
  12969. WOLFSSL_METHOD* wolfTLSv1_server_method(void)
  12970. {
  12971. return wolfTLSv1_server_method_ex(NULL);
  12972. }
  12973. WOLFSSL_METHOD* wolfTLSv1_server_method_ex(void* heap)
  12974. {
  12975. WOLFSSL_METHOD* method =
  12976. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12977. heap, DYNAMIC_TYPE_METHOD);
  12978. (void)heap;
  12979. WOLFSSL_ENTER("TLSv1_server_method_ex");
  12980. if (method) {
  12981. InitSSL_Method(method, MakeTLSv1());
  12982. method->side = WOLFSSL_SERVER_END;
  12983. }
  12984. return method;
  12985. }
  12986. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12987. WOLFSSL_METHOD* wolfTLSv1_1_server_method(void)
  12988. {
  12989. return wolfTLSv1_1_server_method_ex(NULL);
  12990. }
  12991. WOLFSSL_METHOD* wolfTLSv1_1_server_method_ex(void* heap)
  12992. {
  12993. WOLFSSL_METHOD* method =
  12994. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12995. heap, DYNAMIC_TYPE_METHOD);
  12996. (void)heap;
  12997. WOLFSSL_ENTER("TLSv1_1_server_method_ex");
  12998. if (method) {
  12999. InitSSL_Method(method, MakeTLSv1_1());
  13000. method->side = WOLFSSL_SERVER_END;
  13001. }
  13002. return method;
  13003. }
  13004. #endif /* !NO_OLD_TLS */
  13005. #ifndef WOLFSSL_NO_TLS12
  13006. WOLFSSL_ABI
  13007. WOLFSSL_METHOD* wolfTLSv1_2_server_method(void)
  13008. {
  13009. return wolfTLSv1_2_server_method_ex(NULL);
  13010. }
  13011. WOLFSSL_METHOD* wolfTLSv1_2_server_method_ex(void* heap)
  13012. {
  13013. WOLFSSL_METHOD* method =
  13014. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13015. heap, DYNAMIC_TYPE_METHOD);
  13016. (void)heap;
  13017. WOLFSSL_ENTER("TLSv1_2_server_method_ex");
  13018. if (method) {
  13019. InitSSL_Method(method, MakeTLSv1_2());
  13020. method->side = WOLFSSL_SERVER_END;
  13021. }
  13022. return method;
  13023. }
  13024. #endif /* !WOLFSSL_NO_TLS12 */
  13025. #ifdef WOLFSSL_TLS13
  13026. /* The TLS v1.3 server method data.
  13027. *
  13028. * returns the method data for a TLS v1.3 server.
  13029. */
  13030. WOLFSSL_ABI
  13031. WOLFSSL_METHOD* wolfTLSv1_3_server_method(void)
  13032. {
  13033. return wolfTLSv1_3_server_method_ex(NULL);
  13034. }
  13035. /* The TLS v1.3 server method data.
  13036. *
  13037. * heap The heap used for allocation.
  13038. * returns the method data for a TLS v1.3 server.
  13039. */
  13040. WOLFSSL_METHOD* wolfTLSv1_3_server_method_ex(void* heap)
  13041. {
  13042. WOLFSSL_METHOD* method =
  13043. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13044. heap, DYNAMIC_TYPE_METHOD);
  13045. (void)heap;
  13046. WOLFSSL_ENTER("TLSv1_3_server_method_ex");
  13047. if (method) {
  13048. InitSSL_Method(method, MakeTLSv1_3());
  13049. method->side = WOLFSSL_SERVER_END;
  13050. }
  13051. return method;
  13052. }
  13053. #endif /* WOLFSSL_TLS13 */
  13054. #ifdef WOLFSSL_DTLS
  13055. WOLFSSL_METHOD* wolfDTLS_server_method(void)
  13056. {
  13057. return wolfDTLS_server_method_ex(NULL);
  13058. }
  13059. WOLFSSL_METHOD* wolfDTLS_server_method_ex(void* heap)
  13060. {
  13061. WOLFSSL_METHOD* method =
  13062. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13063. heap, DYNAMIC_TYPE_METHOD);
  13064. (void)heap;
  13065. WOLFSSL_ENTER("DTLS_server_method_ex");
  13066. if (method) {
  13067. #if defined(WOLFSSL_DTLS13)
  13068. InitSSL_Method(method, MakeDTLSv1_3());
  13069. #elif !defined(WOLFSSL_NO_TLS12)
  13070. InitSSL_Method(method, MakeDTLSv1_2());
  13071. #elif !defined(NO_OLD_TLS)
  13072. InitSSL_Method(method, MakeDTLSv1());
  13073. #else
  13074. #error No DTLS version enabled!
  13075. #endif
  13076. method->downgrade = 1;
  13077. method->side = WOLFSSL_SERVER_END;
  13078. }
  13079. return method;
  13080. }
  13081. #ifndef NO_OLD_TLS
  13082. WOLFSSL_METHOD* wolfDTLSv1_server_method(void)
  13083. {
  13084. return wolfDTLSv1_server_method_ex(NULL);
  13085. }
  13086. WOLFSSL_METHOD* wolfDTLSv1_server_method_ex(void* heap)
  13087. {
  13088. WOLFSSL_METHOD* method =
  13089. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13090. heap, DYNAMIC_TYPE_METHOD);
  13091. (void)heap;
  13092. WOLFSSL_ENTER("DTLSv1_server_method_ex");
  13093. if (method) {
  13094. InitSSL_Method(method, MakeDTLSv1());
  13095. method->side = WOLFSSL_SERVER_END;
  13096. }
  13097. return method;
  13098. }
  13099. #endif /* !NO_OLD_TLS */
  13100. #ifndef WOLFSSL_NO_TLS12
  13101. WOLFSSL_METHOD* wolfDTLSv1_2_server_method(void)
  13102. {
  13103. return wolfDTLSv1_2_server_method_ex(NULL);
  13104. }
  13105. WOLFSSL_METHOD* wolfDTLSv1_2_server_method_ex(void* heap)
  13106. {
  13107. WOLFSSL_METHOD* method =
  13108. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  13109. heap, DYNAMIC_TYPE_METHOD);
  13110. WOLFSSL_ENTER("DTLSv1_2_server_method_ex");
  13111. (void)heap;
  13112. if (method) {
  13113. InitSSL_Method(method, MakeDTLSv1_2());
  13114. method->side = WOLFSSL_SERVER_END;
  13115. }
  13116. (void)heap;
  13117. return method;
  13118. }
  13119. #endif /* !WOLFSSL_NO_TLS12 */
  13120. #endif /* WOLFSSL_DTLS */
  13121. #endif /* NO_WOLFSSL_SERVER */
  13122. #endif /* NO_TLS */
  13123. #endif /* WOLFCRYPT_ONLY */