tls.c 445 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648
  1. /* tls.c
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #ifndef WOLFCRYPT_ONLY
  26. #include <wolfssl/ssl.h>
  27. #include <wolfssl/internal.h>
  28. #include <wolfssl/error-ssl.h>
  29. #include <wolfssl/wolfcrypt/hash.h>
  30. #include <wolfssl/wolfcrypt/hmac.h>
  31. #include <wolfssl/wolfcrypt/kdf.h>
  32. #ifdef NO_INLINE
  33. #include <wolfssl/wolfcrypt/misc.h>
  34. #else
  35. #define WOLFSSL_MISC_INCLUDED
  36. #include <wolfcrypt/src/misc.c>
  37. #endif
  38. #ifdef HAVE_CURVE25519
  39. #include <wolfssl/wolfcrypt/curve25519.h>
  40. #endif
  41. #ifdef HAVE_CURVE448
  42. #include <wolfssl/wolfcrypt/curve448.h>
  43. #endif
  44. #ifdef HAVE_PQC
  45. #include <wolfssl/wolfcrypt/kyber.h>
  46. #ifdef WOLFSSL_WC_KYBER
  47. #include <wolfssl/wolfcrypt/wc_kyber.h>
  48. #elif defined(HAVE_LIBOQS) || defined(HAVE_PQM4)
  49. #include <wolfssl/wolfcrypt/ext_kyber.h>
  50. #endif
  51. #endif
  52. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  53. #include <wolfssl/wolfcrypt/port/Renesas/renesas-tsip-crypt.h>
  54. #endif
  55. #include <wolfssl/wolfcrypt/hpke.h>
  56. #ifndef NO_TLS
  57. #if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
  58. static int TLSX_KeyShare_IsSupported(int namedGroup);
  59. static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap);
  60. #endif
  61. #ifdef HAVE_SUPPORTED_CURVES
  62. static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions);
  63. #endif
  64. /* Digest enable checks */
  65. #ifdef NO_OLD_TLS /* TLS 1.2 only */
  66. #if defined(NO_SHA256) && !defined(WOLFSSL_SHA384) && \
  67. !defined(WOLFSSL_SHA512)
  68. #error Must have SHA256, SHA384 or SHA512 enabled for TLS 1.2
  69. #endif
  70. #else /* TLS 1.1 or older */
  71. #if defined(NO_MD5) && defined(NO_SHA)
  72. #error Must have SHA1 and MD5 enabled for old TLS
  73. #endif
  74. #endif
  75. #ifdef WOLFSSL_TLS13
  76. #if !defined(NO_DH) && \
  77. !defined(HAVE_FFDHE_2048) && !defined(HAVE_FFDHE_3072) && \
  78. !defined(HAVE_FFDHE_4096) && !defined(HAVE_FFDHE_6144) && \
  79. !defined(HAVE_FFDHE_8192)
  80. #error Please configure your TLS 1.3 DH key size using either: HAVE_FFDHE_2048, HAVE_FFDHE_3072, HAVE_FFDHE_4096, HAVE_FFDHE_6144 or HAVE_FFDHE_8192
  81. #endif
  82. #if !defined(NO_RSA) && !defined(WC_RSA_PSS)
  83. #error The build option WC_RSA_PSS is required for TLS 1.3 with RSA
  84. #endif
  85. #ifndef HAVE_TLS_EXTENSIONS
  86. #ifndef _MSC_VER
  87. #error "The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3"
  88. #else
  89. #pragma message("Error: The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3")
  90. #endif
  91. #endif
  92. #endif
  93. /* Warn if secrets logging is enabled */
  94. #if defined(SHOW_SECRETS) || defined(WOLFSSL_SSLKEYLOGFILE)
  95. #ifndef _MSC_VER
  96. #warning The SHOW_SECRETS and WOLFSSL_SSLKEYLOGFILE options should only be used for debugging and never in a production environment
  97. #else
  98. #pragma message("Warning: The SHOW_SECRETS and WOLFSSL_SSLKEYLOGFILE options should only be used for debugging and never in a production environment")
  99. #endif
  100. #endif
  101. #ifndef WOLFSSL_NO_TLS12
  102. #ifdef WOLFSSL_SHA384
  103. #define HSHASH_SZ WC_SHA384_DIGEST_SIZE
  104. #else
  105. #define HSHASH_SZ FINISHED_SZ
  106. #endif
  107. int BuildTlsHandshakeHash(WOLFSSL* ssl, byte* hash, word32* hashLen)
  108. {
  109. int ret = 0;
  110. word32 hashSz = FINISHED_SZ;
  111. if (ssl == NULL || hash == NULL || hashLen == NULL || *hashLen < HSHASH_SZ)
  112. return BAD_FUNC_ARG;
  113. /* for constant timing perform these even if error */
  114. #ifndef NO_OLD_TLS
  115. ret |= wc_Md5GetHash(&ssl->hsHashes->hashMd5, hash);
  116. ret |= wc_ShaGetHash(&ssl->hsHashes->hashSha, &hash[WC_MD5_DIGEST_SIZE]);
  117. #endif
  118. if (IsAtLeastTLSv1_2(ssl)) {
  119. #ifndef NO_SHA256
  120. if (ssl->specs.mac_algorithm <= sha256_mac ||
  121. ssl->specs.mac_algorithm == blake2b_mac) {
  122. ret |= wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
  123. hashSz = WC_SHA256_DIGEST_SIZE;
  124. }
  125. #endif
  126. #ifdef WOLFSSL_SHA384
  127. if (ssl->specs.mac_algorithm == sha384_mac) {
  128. ret |= wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
  129. hashSz = WC_SHA384_DIGEST_SIZE;
  130. }
  131. #endif
  132. #ifdef WOLFSSL_SM3
  133. if (ssl->specs.mac_algorithm == sm3_mac) {
  134. ret |= wc_Sm3GetHash(&ssl->hsHashes->hashSm3, hash);
  135. hashSz = WC_SM3_DIGEST_SIZE;
  136. }
  137. #endif
  138. }
  139. *hashLen = hashSz;
  140. #ifdef WOLFSSL_CHECK_MEM_ZERO
  141. wc_MemZero_Add("TLS handshake hash", hash, hashSz);
  142. #endif
  143. if (ret != 0) {
  144. ret = BUILD_MSG_ERROR;
  145. WOLFSSL_ERROR_VERBOSE(ret);
  146. }
  147. return ret;
  148. }
  149. int BuildTlsFinished(WOLFSSL* ssl, Hashes* hashes, const byte* sender)
  150. {
  151. int ret;
  152. const byte* side = NULL;
  153. word32 hashSz = HSHASH_SZ;
  154. #if !defined(WOLFSSL_ASYNC_CRYPT) || defined(WC_ASYNC_NO_HASH)
  155. byte handshake_hash[HSHASH_SZ];
  156. #else
  157. WC_DECLARE_VAR(handshake_hash, byte, HSHASH_SZ, ssl->heap);
  158. if (handshake_hash == NULL)
  159. return MEMORY_E;
  160. #endif
  161. ret = BuildTlsHandshakeHash(ssl, handshake_hash, &hashSz);
  162. if (ret == 0) {
  163. if (XSTRNCMP((const char*)sender, (const char*)kTlsClientStr,
  164. SIZEOF_SENDER) == 0) {
  165. side = kTlsClientFinStr;
  166. }
  167. else if (XSTRNCMP((const char*)sender, (const char*)kTlsServerStr,
  168. SIZEOF_SENDER) == 0) {
  169. side = kTlsServerFinStr;
  170. }
  171. else {
  172. ret = BAD_FUNC_ARG;
  173. WOLFSSL_MSG("Unexpected sender value");
  174. }
  175. }
  176. if (ret == 0) {
  177. #ifdef WOLFSSL_HAVE_PRF
  178. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  179. if (ssl->ctx->TlsFinishedCb) {
  180. void* ctx = wolfSSL_GetTlsFinishedCtx(ssl);
  181. ret = ssl->ctx->TlsFinishedCb(ssl, side, handshake_hash, hashSz,
  182. (byte*)hashes, ctx);
  183. }
  184. if (!ssl->ctx->TlsFinishedCb || ret == PROTOCOLCB_UNAVAILABLE)
  185. #endif
  186. {
  187. PRIVATE_KEY_UNLOCK();
  188. ret = wc_PRF_TLS((byte*)hashes, TLS_FINISHED_SZ,
  189. ssl->arrays->masterSecret, SECRET_LEN, side,
  190. FINISHED_LABEL_SZ, handshake_hash, hashSz,
  191. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  192. ssl->heap, ssl->devId);
  193. PRIVATE_KEY_LOCK();
  194. }
  195. ForceZero(handshake_hash, hashSz);
  196. #else
  197. /* Pseudo random function must be enabled in the configuration. */
  198. ret = PRF_MISSING;
  199. WOLFSSL_ERROR_VERBOSE(ret);
  200. WOLFSSL_MSG("Pseudo-random function is not enabled");
  201. (void)side;
  202. (void)hashes;
  203. #endif
  204. }
  205. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  206. WC_FREE_VAR(handshake_hash, ssl->heap);
  207. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  208. wc_MemZero_Check(handshake_hash, HSHASH_SZ);
  209. #endif
  210. return ret;
  211. }
  212. #endif /* !WOLFSSL_NO_TLS12 */
  213. #ifndef NO_OLD_TLS
  214. #ifdef WOLFSSL_ALLOW_TLSV10
  215. ProtocolVersion MakeTLSv1(void)
  216. {
  217. ProtocolVersion pv;
  218. pv.major = SSLv3_MAJOR;
  219. pv.minor = TLSv1_MINOR;
  220. return pv;
  221. }
  222. #endif /* WOLFSSL_ALLOW_TLSV10 */
  223. ProtocolVersion MakeTLSv1_1(void)
  224. {
  225. ProtocolVersion pv;
  226. pv.major = SSLv3_MAJOR;
  227. pv.minor = TLSv1_1_MINOR;
  228. return pv;
  229. }
  230. #endif /* !NO_OLD_TLS */
  231. #ifndef WOLFSSL_NO_TLS12
  232. ProtocolVersion MakeTLSv1_2(void)
  233. {
  234. ProtocolVersion pv;
  235. pv.major = SSLv3_MAJOR;
  236. pv.minor = TLSv1_2_MINOR;
  237. return pv;
  238. }
  239. #endif /* !WOLFSSL_NO_TLS12 */
  240. #ifdef WOLFSSL_TLS13
  241. /* The TLS v1.3 protocol version.
  242. *
  243. * returns the protocol version data for TLS v1.3.
  244. */
  245. ProtocolVersion MakeTLSv1_3(void)
  246. {
  247. ProtocolVersion pv;
  248. pv.major = SSLv3_MAJOR;
  249. pv.minor = TLSv1_3_MINOR;
  250. return pv;
  251. }
  252. #endif
  253. #ifndef WOLFSSL_NO_TLS12
  254. #ifdef HAVE_EXTENDED_MASTER
  255. static const byte ext_master_label[EXT_MASTER_LABEL_SZ + 1] =
  256. "extended master secret";
  257. #endif
  258. static const byte master_label[MASTER_LABEL_SZ + 1] = "master secret";
  259. static const byte key_label [KEY_LABEL_SZ + 1] = "key expansion";
  260. static int _DeriveTlsKeys(byte* key_dig, word32 key_dig_len,
  261. const byte* ms, word32 msLen,
  262. const byte* sr, const byte* cr,
  263. int tls1_2, int hash_type,
  264. void* heap, int devId)
  265. {
  266. int ret;
  267. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  268. WC_DECLARE_VAR(seed, byte, SEED_LEN, heap);
  269. if (seed == NULL)
  270. return MEMORY_E;
  271. #else
  272. byte seed[SEED_LEN];
  273. #endif
  274. XMEMCPY(seed, sr, RAN_LEN);
  275. XMEMCPY(seed + RAN_LEN, cr, RAN_LEN);
  276. #ifdef WOLFSSL_HAVE_PRF
  277. PRIVATE_KEY_UNLOCK();
  278. ret = wc_PRF_TLS(key_dig, key_dig_len, ms, msLen, key_label, KEY_LABEL_SZ,
  279. seed, SEED_LEN, tls1_2, hash_type, heap, devId);
  280. PRIVATE_KEY_LOCK();
  281. #else
  282. /* Pseudo random function must be enabled in the configuration. */
  283. ret = PRF_MISSING;
  284. WOLFSSL_ERROR_VERBOSE(ret);
  285. WOLFSSL_MSG("Pseudo-random function is not enabled");
  286. (void)key_dig;
  287. (void)key_dig_len;
  288. (void)ms;
  289. (void)msLen;
  290. (void)tls1_2;
  291. (void)hash_type;
  292. (void)heap;
  293. (void)devId;
  294. (void)key_label;
  295. (void)master_label;
  296. #ifdef HAVE_EXTENDED_MASTER
  297. (void)ext_master_label;
  298. #endif
  299. #endif
  300. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  301. WC_FREE_VAR(seed, heap);
  302. #endif
  303. return ret;
  304. }
  305. /* External facing wrapper so user can call as well, 0 on success */
  306. int wolfSSL_DeriveTlsKeys(byte* key_dig, word32 key_dig_len,
  307. const byte* ms, word32 msLen,
  308. const byte* sr, const byte* cr,
  309. int tls1_2, int hash_type)
  310. {
  311. return _DeriveTlsKeys(key_dig, key_dig_len, ms, msLen, sr, cr, tls1_2,
  312. hash_type, NULL, INVALID_DEVID);
  313. }
  314. int DeriveTlsKeys(WOLFSSL* ssl)
  315. {
  316. int ret;
  317. int key_dig_len = 2 * ssl->specs.hash_size +
  318. 2 * ssl->specs.key_size +
  319. 2 * ssl->specs.iv_size;
  320. #ifdef WOLFSSL_SMALL_STACK
  321. byte* key_dig;
  322. #else
  323. byte key_dig[MAX_PRF_DIG];
  324. #endif
  325. #ifdef WOLFSSL_SMALL_STACK
  326. key_dig = (byte*)XMALLOC(MAX_PRF_DIG, ssl->heap, DYNAMIC_TYPE_DIGEST);
  327. if (key_dig == NULL) {
  328. return MEMORY_E;
  329. }
  330. #endif
  331. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  332. ret = PROTOCOLCB_UNAVAILABLE;
  333. if (ssl->ctx->GenSessionKeyCb) {
  334. void* ctx = wolfSSL_GetGenSessionKeyCtx(ssl);
  335. ret = ssl->ctx->GenSessionKeyCb(ssl, ctx);
  336. }
  337. if (!ssl->ctx->GenSessionKeyCb || ret == PROTOCOLCB_UNAVAILABLE)
  338. #endif
  339. ret = _DeriveTlsKeys(key_dig, key_dig_len,
  340. ssl->arrays->masterSecret, SECRET_LEN,
  341. ssl->arrays->serverRandom, ssl->arrays->clientRandom,
  342. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  343. ssl->heap, ssl->devId);
  344. if (ret == 0)
  345. ret = StoreKeys(ssl, key_dig, PROVISION_CLIENT_SERVER);
  346. #ifdef WOLFSSL_SMALL_STACK
  347. XFREE(key_dig, ssl->heap, DYNAMIC_TYPE_DIGEST);
  348. #endif
  349. return ret;
  350. }
  351. static int _MakeTlsMasterSecret(byte* ms, word32 msLen,
  352. const byte* pms, word32 pmsLen,
  353. const byte* cr, const byte* sr,
  354. int tls1_2, int hash_type,
  355. void* heap, int devId)
  356. {
  357. int ret;
  358. #if !defined(WOLFSSL_ASYNC_CRYPT) || defined(WC_ASYNC_NO_HASH)
  359. byte seed[SEED_LEN];
  360. #else
  361. WC_DECLARE_VAR(seed, byte, SEED_LEN, heap);
  362. if (seed == NULL)
  363. return MEMORY_E;
  364. #endif
  365. XMEMCPY(seed, cr, RAN_LEN);
  366. XMEMCPY(seed + RAN_LEN, sr, RAN_LEN);
  367. #ifdef WOLFSSL_HAVE_PRF
  368. PRIVATE_KEY_UNLOCK();
  369. ret = wc_PRF_TLS(ms, msLen, pms, pmsLen, master_label, MASTER_LABEL_SZ,
  370. seed, SEED_LEN, tls1_2, hash_type, heap, devId);
  371. PRIVATE_KEY_LOCK();
  372. #else
  373. /* Pseudo random function must be enabled in the configuration. */
  374. ret = PRF_MISSING;
  375. WOLFSSL_MSG("Pseudo-random function is not enabled");
  376. (void)ms;
  377. (void)msLen;
  378. (void)pms;
  379. (void)pmsLen;
  380. (void)tls1_2;
  381. (void)hash_type;
  382. (void)heap;
  383. (void)devId;
  384. #endif
  385. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WC_ASYNC_NO_HASH)
  386. WC_FREE_VAR(seed, heap);
  387. #endif
  388. return ret;
  389. }
  390. /* External facing wrapper so user can call as well, 0 on success */
  391. int wolfSSL_MakeTlsMasterSecret(byte* ms, word32 msLen,
  392. const byte* pms, word32 pmsLen,
  393. const byte* cr, const byte* sr,
  394. int tls1_2, int hash_type)
  395. {
  396. return _MakeTlsMasterSecret(ms, msLen, pms, pmsLen, cr, sr, tls1_2,
  397. hash_type, NULL, INVALID_DEVID);
  398. }
  399. #ifdef HAVE_EXTENDED_MASTER
  400. static int _MakeTlsExtendedMasterSecret(byte* ms, word32 msLen,
  401. const byte* pms, word32 pmsLen,
  402. const byte* sHash, word32 sHashLen,
  403. int tls1_2, int hash_type,
  404. void* heap, int devId)
  405. {
  406. int ret;
  407. #ifdef WOLFSSL_HAVE_PRF
  408. PRIVATE_KEY_UNLOCK();
  409. ret = wc_PRF_TLS(ms, msLen, pms, pmsLen, ext_master_label, EXT_MASTER_LABEL_SZ,
  410. sHash, sHashLen, tls1_2, hash_type, heap, devId);
  411. PRIVATE_KEY_LOCK();
  412. #else
  413. /* Pseudo random function must be enabled in the configuration. */
  414. ret = PRF_MISSING;
  415. WOLFSSL_MSG("Pseudo-random function is not enabled");
  416. (void)ms;
  417. (void)msLen;
  418. (void)pms;
  419. (void)pmsLen;
  420. (void)sHash;
  421. (void)sHashLen;
  422. (void)tls1_2;
  423. (void)hash_type;
  424. (void)heap;
  425. (void)devId;
  426. #endif
  427. return ret;
  428. }
  429. /* External facing wrapper so user can call as well, 0 on success */
  430. int wolfSSL_MakeTlsExtendedMasterSecret(byte* ms, word32 msLen,
  431. const byte* pms, word32 pmsLen,
  432. const byte* sHash, word32 sHashLen,
  433. int tls1_2, int hash_type)
  434. {
  435. return _MakeTlsExtendedMasterSecret(ms, msLen, pms, pmsLen, sHash, sHashLen,
  436. tls1_2, hash_type, NULL, INVALID_DEVID);
  437. }
  438. #endif /* HAVE_EXTENDED_MASTER */
  439. int MakeTlsMasterSecret(WOLFSSL* ssl)
  440. {
  441. int ret;
  442. #ifdef HAVE_EXTENDED_MASTER
  443. if (ssl->options.haveEMS) {
  444. word32 hashSz = HSHASH_SZ;
  445. #ifdef WOLFSSL_SMALL_STACK
  446. byte* handshake_hash = (byte*)XMALLOC(HSHASH_SZ, ssl->heap,
  447. DYNAMIC_TYPE_DIGEST);
  448. if (handshake_hash == NULL)
  449. return MEMORY_E;
  450. #else
  451. byte handshake_hash[HSHASH_SZ];
  452. #endif
  453. ret = BuildTlsHandshakeHash(ssl, handshake_hash, &hashSz);
  454. if (ret == 0) {
  455. ret = _MakeTlsExtendedMasterSecret(
  456. ssl->arrays->masterSecret, SECRET_LEN,
  457. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz,
  458. handshake_hash, hashSz,
  459. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  460. ssl->heap, ssl->devId);
  461. ForceZero(handshake_hash, hashSz);
  462. }
  463. #ifdef WOLFSSL_SMALL_STACK
  464. XFREE(handshake_hash, ssl->heap, DYNAMIC_TYPE_DIGEST);
  465. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  466. wc_MemZero_Check(handshake_hash, HSHASH_SZ);
  467. #endif
  468. }
  469. else
  470. #endif /* HAVE_EXTENDED_MASTER */
  471. {
  472. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  473. ret = PROTOCOLCB_UNAVAILABLE;
  474. if (ssl->ctx->GenMasterCb) {
  475. void* ctx = wolfSSL_GetGenMasterSecretCtx(ssl);
  476. ret = ssl->ctx->GenMasterCb(ssl, ctx);
  477. }
  478. if (!ssl->ctx->GenMasterCb || ret == PROTOCOLCB_UNAVAILABLE)
  479. #endif
  480. {
  481. ret = _MakeTlsMasterSecret(ssl->arrays->masterSecret,
  482. SECRET_LEN, ssl->arrays->preMasterSecret,
  483. ssl->arrays->preMasterSz, ssl->arrays->clientRandom,
  484. ssl->arrays->serverRandom, IsAtLeastTLSv1_2(ssl),
  485. ssl->specs.mac_algorithm, ssl->heap, ssl->devId);
  486. }
  487. }
  488. if (ret == 0) {
  489. #ifdef SHOW_SECRETS
  490. /* Wireshark Pre-Master-Secret Format:
  491. * CLIENT_RANDOM <clientrandom> <mastersecret>
  492. */
  493. const char* CLIENT_RANDOM_LABEL = "CLIENT_RANDOM";
  494. int i, pmsPos = 0;
  495. char pmsBuf[13 + 1 + 64 + 1 + 96 + 1 + 1];
  496. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%s ",
  497. CLIENT_RANDOM_LABEL);
  498. pmsPos += XSTRLEN(CLIENT_RANDOM_LABEL) + 1;
  499. for (i = 0; i < RAN_LEN; i++) {
  500. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
  501. ssl->arrays->clientRandom[i]);
  502. pmsPos += 2;
  503. }
  504. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, " ");
  505. pmsPos += 1;
  506. for (i = 0; i < SECRET_LEN; i++) {
  507. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
  508. ssl->arrays->masterSecret[i]);
  509. pmsPos += 2;
  510. }
  511. XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "\n");
  512. pmsPos += 1;
  513. /* print master secret */
  514. puts(pmsBuf);
  515. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE)
  516. {
  517. FILE* f = XFOPEN(WOLFSSL_SSLKEYLOGFILE_OUTPUT, "a");
  518. if (f != XBADFILE) {
  519. XFWRITE(pmsBuf, 1, pmsPos, f);
  520. XFCLOSE(f);
  521. }
  522. }
  523. #endif
  524. #endif /* SHOW_SECRETS */
  525. ret = DeriveTlsKeys(ssl);
  526. }
  527. return ret;
  528. }
  529. /* Used by EAP-TLS and EAP-TTLS to derive keying material from
  530. * the master_secret. */
  531. int wolfSSL_make_eap_keys(WOLFSSL* ssl, void* msk, unsigned int len,
  532. const char* label)
  533. {
  534. int ret;
  535. #ifdef WOLFSSL_SMALL_STACK
  536. byte* seed;
  537. #else
  538. byte seed[SEED_LEN];
  539. #endif
  540. #ifdef WOLFSSL_SMALL_STACK
  541. seed = (byte*)XMALLOC(SEED_LEN, ssl->heap, DYNAMIC_TYPE_SEED);
  542. if (seed == NULL)
  543. return MEMORY_E;
  544. #endif
  545. /*
  546. * As per RFC-5281, the order of the client and server randoms is reversed
  547. * from that used by the TLS protocol to derive keys.
  548. */
  549. XMEMCPY(seed, ssl->arrays->clientRandom, RAN_LEN);
  550. XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
  551. #ifdef WOLFSSL_HAVE_PRF
  552. PRIVATE_KEY_UNLOCK();
  553. ret = wc_PRF_TLS((byte*)msk, len, ssl->arrays->masterSecret, SECRET_LEN,
  554. (const byte *)label, (word32)XSTRLEN(label), seed, SEED_LEN,
  555. IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm,
  556. ssl->heap, ssl->devId);
  557. PRIVATE_KEY_LOCK();
  558. #else
  559. /* Pseudo random function must be enabled in the configuration. */
  560. ret = PRF_MISSING;
  561. WOLFSSL_MSG("Pseudo-random function is not enabled");
  562. (void)msk;
  563. (void)len;
  564. (void)label;
  565. #endif
  566. #ifdef WOLFSSL_SMALL_STACK
  567. XFREE(seed, ssl->heap, DYNAMIC_TYPE_SEED);
  568. #endif
  569. return ret;
  570. }
  571. int wolfSSL_GetHmacType_ex(CipherSpecs* specs)
  572. {
  573. if (specs == NULL)
  574. return BAD_FUNC_ARG;
  575. switch (specs->mac_algorithm) {
  576. #ifndef NO_MD5
  577. case md5_mac:
  578. {
  579. return WC_MD5;
  580. }
  581. #endif
  582. #ifndef NO_SHA256
  583. case sha256_mac:
  584. {
  585. return WC_SHA256;
  586. }
  587. #endif
  588. #ifdef WOLFSSL_SHA384
  589. case sha384_mac:
  590. {
  591. return WC_SHA384;
  592. }
  593. #endif
  594. #ifdef WOLFSSL_SM3
  595. case sm3_mac:
  596. {
  597. return WC_SM3;
  598. }
  599. #endif
  600. #ifndef NO_SHA
  601. case sha_mac:
  602. {
  603. return WC_SHA;
  604. }
  605. #endif
  606. #ifdef HAVE_BLAKE2
  607. case blake2b_mac:
  608. {
  609. return BLAKE2B_ID;
  610. }
  611. #endif
  612. default:
  613. {
  614. return WOLFSSL_FATAL_ERROR;
  615. }
  616. }
  617. }
  618. /* return HMAC digest type in wolfSSL format */
  619. int wolfSSL_GetHmacType(WOLFSSL* ssl)
  620. {
  621. if (ssl == NULL)
  622. return BAD_FUNC_ARG;
  623. return wolfSSL_GetHmacType_ex(&ssl->specs);
  624. }
  625. int wolfSSL_SetTlsHmacInner(WOLFSSL* ssl, byte* inner, word32 sz, int content,
  626. int verify)
  627. {
  628. if (ssl == NULL || inner == NULL)
  629. return BAD_FUNC_ARG;
  630. XMEMSET(inner, 0, WOLFSSL_TLS_HMAC_INNER_SZ);
  631. WriteSEQ(ssl, verify, inner);
  632. inner[SEQ_SZ] = (byte)content;
  633. inner[SEQ_SZ + ENUM_LEN] = ssl->version.major;
  634. inner[SEQ_SZ + ENUM_LEN + ENUM_LEN] = ssl->version.minor;
  635. c16toa((word16)sz, inner + SEQ_SZ + ENUM_LEN + VERSION_SZ);
  636. return 0;
  637. }
  638. #ifndef WOLFSSL_AEAD_ONLY
  639. #if !defined(WOLFSSL_NO_HASH_RAW) && !defined(HAVE_FIPS) && \
  640. !defined(HAVE_SELFTEST)
  641. /* Update the hash in the HMAC.
  642. *
  643. * hmac HMAC object.
  644. * data Data to be hashed.
  645. * sz Size of data to hash.
  646. * returns 0 on success, otherwise failure.
  647. */
  648. static int Hmac_HashUpdate(Hmac* hmac, const byte* data, word32 sz)
  649. {
  650. int ret = BAD_FUNC_ARG;
  651. switch (hmac->macType) {
  652. #ifndef NO_SHA
  653. case WC_SHA:
  654. ret = wc_ShaUpdate(&hmac->hash.sha, data, sz);
  655. break;
  656. #endif /* !NO_SHA */
  657. #ifndef NO_SHA256
  658. case WC_SHA256:
  659. ret = wc_Sha256Update(&hmac->hash.sha256, data, sz);
  660. break;
  661. #endif /* !NO_SHA256 */
  662. #ifdef WOLFSSL_SHA384
  663. case WC_SHA384:
  664. ret = wc_Sha384Update(&hmac->hash.sha384, data, sz);
  665. break;
  666. #endif /* WOLFSSL_SHA384 */
  667. #ifdef WOLFSSL_SHA512
  668. case WC_SHA512:
  669. ret = wc_Sha512Update(&hmac->hash.sha512, data, sz);
  670. break;
  671. #endif /* WOLFSSL_SHA512 */
  672. #ifdef WOLFSSL_SM3
  673. case WC_SM3:
  674. ret = wc_Sm3Update(&hmac->hash.sm3, data, sz);
  675. break;
  676. #endif /* WOLFSSL_SM3 */
  677. default:
  678. break;
  679. }
  680. return ret;
  681. }
  682. /* Finalize the hash but don't put the EOC, padding or length in.
  683. *
  684. * hmac HMAC object.
  685. * hash Hash result.
  686. * returns 0 on success, otherwise failure.
  687. */
  688. static int Hmac_HashFinalRaw(Hmac* hmac, unsigned char* hash)
  689. {
  690. int ret = BAD_FUNC_ARG;
  691. switch (hmac->macType) {
  692. #ifndef NO_SHA
  693. case WC_SHA:
  694. ret = wc_ShaFinalRaw(&hmac->hash.sha, hash);
  695. break;
  696. #endif /* !NO_SHA */
  697. #ifndef NO_SHA256
  698. case WC_SHA256:
  699. ret = wc_Sha256FinalRaw(&hmac->hash.sha256, hash);
  700. break;
  701. #endif /* !NO_SHA256 */
  702. #ifdef WOLFSSL_SHA384
  703. case WC_SHA384:
  704. ret = wc_Sha384FinalRaw(&hmac->hash.sha384, hash);
  705. break;
  706. #endif /* WOLFSSL_SHA384 */
  707. #ifdef WOLFSSL_SHA512
  708. case WC_SHA512:
  709. ret = wc_Sha512FinalRaw(&hmac->hash.sha512, hash);
  710. break;
  711. #endif /* WOLFSSL_SHA512 */
  712. #ifdef WOLFSSL_SM3
  713. case WC_SM3:
  714. ret = wc_Sm3FinalRaw(&hmac->hash.sm3, hash);
  715. break;
  716. #endif /* WOLFSSL_SM3 */
  717. default:
  718. break;
  719. }
  720. return ret;
  721. }
  722. /* Finalize the HMAC by performing outer hash.
  723. *
  724. * hmac HMAC object.
  725. * mac MAC result.
  726. * returns 0 on success, otherwise failure.
  727. */
  728. static int Hmac_OuterHash(Hmac* hmac, unsigned char* mac)
  729. {
  730. int ret = BAD_FUNC_ARG;
  731. wc_HashAlg hash;
  732. enum wc_HashType hashType = (enum wc_HashType)hmac->macType;
  733. int digestSz = wc_HashGetDigestSize(hashType);
  734. int blockSz = wc_HashGetBlockSize(hashType);
  735. if ((digestSz >= 0) && (blockSz >= 0)) {
  736. ret = wc_HashInit(&hash, hashType);
  737. }
  738. if (ret == 0) {
  739. ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->opad,
  740. blockSz);
  741. if (ret == 0)
  742. ret = wc_HashUpdate(&hash, hashType, (byte*)hmac->innerHash,
  743. digestSz);
  744. if (ret == 0)
  745. ret = wc_HashFinal(&hash, hashType, mac);
  746. wc_HashFree(&hash, hashType);
  747. }
  748. return ret;
  749. }
  750. /* Calculate the HMAC of the header + message data.
  751. * Constant time implementation using wc_Sha*FinalRaw().
  752. *
  753. * hmac HMAC object.
  754. * digest MAC result.
  755. * in Message data.
  756. * sz Size of the message data.
  757. * header Constructed record header with length of handshake data.
  758. * returns 0 on success, otherwise failure.
  759. */
  760. static int Hmac_UpdateFinal_CT(Hmac* hmac, byte* digest, const byte* in,
  761. word32 sz, int macLen, byte* header)
  762. {
  763. byte lenBytes[8];
  764. int i, j;
  765. unsigned int k;
  766. int blockBits, blockMask;
  767. int lastBlockLen, extraLen, eocIndex;
  768. int blocks, safeBlocks, lenBlock, eocBlock;
  769. unsigned int maxLen;
  770. int blockSz, padSz;
  771. int ret;
  772. word32 realLen;
  773. byte extraBlock;
  774. switch (hmac->macType) {
  775. #ifndef NO_SHA
  776. case WC_SHA:
  777. blockSz = WC_SHA_BLOCK_SIZE;
  778. blockBits = 6;
  779. padSz = WC_SHA_BLOCK_SIZE - WC_SHA_PAD_SIZE + 1;
  780. break;
  781. #endif /* !NO_SHA */
  782. #ifndef NO_SHA256
  783. case WC_SHA256:
  784. blockSz = WC_SHA256_BLOCK_SIZE;
  785. blockBits = 6;
  786. padSz = WC_SHA256_BLOCK_SIZE - WC_SHA256_PAD_SIZE + 1;
  787. break;
  788. #endif /* !NO_SHA256 */
  789. #ifdef WOLFSSL_SHA384
  790. case WC_SHA384:
  791. blockSz = WC_SHA384_BLOCK_SIZE;
  792. blockBits = 7;
  793. padSz = WC_SHA384_BLOCK_SIZE - WC_SHA384_PAD_SIZE + 1;
  794. break;
  795. #endif /* WOLFSSL_SHA384 */
  796. #ifdef WOLFSSL_SHA512
  797. case WC_SHA512:
  798. blockSz = WC_SHA512_BLOCK_SIZE;
  799. blockBits = 7;
  800. padSz = WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE + 1;
  801. break;
  802. #endif /* WOLFSSL_SHA512 */
  803. #ifdef WOLFSSL_SM3
  804. case WC_SM3:
  805. blockSz = WC_SM3_BLOCK_SIZE;
  806. blockBits = 6;
  807. padSz = WC_SM3_BLOCK_SIZE - WC_SM3_PAD_SIZE + 1;
  808. break;
  809. #endif /* WOLFSSL_SM3 */
  810. default:
  811. return BAD_FUNC_ARG;
  812. }
  813. blockMask = blockSz - 1;
  814. /* Size of data to HMAC if padding length byte is zero. */
  815. maxLen = WOLFSSL_TLS_HMAC_INNER_SZ + sz - 1 - macLen;
  816. /* Complete data (including padding) has block for EOC and/or length. */
  817. extraBlock = ctSetLTE((maxLen + padSz) & blockMask, padSz);
  818. /* Total number of blocks for data including padding. */
  819. blocks = ((maxLen + blockSz - 1) >> blockBits) + extraBlock;
  820. /* Up to last 6 blocks can be hashed safely. */
  821. safeBlocks = blocks - 6;
  822. /* Length of message data. */
  823. realLen = maxLen - in[sz - 1];
  824. /* Number of message bytes in last block. */
  825. lastBlockLen = realLen & blockMask;
  826. /* Number of padding bytes in last block. */
  827. extraLen = ((blockSz * 2 - padSz - lastBlockLen) & blockMask) + 1;
  828. /* Number of blocks to create for hash. */
  829. lenBlock = (realLen + extraLen) >> blockBits;
  830. /* Block containing EOC byte. */
  831. eocBlock = realLen >> blockBits;
  832. /* Index of EOC byte in block. */
  833. eocIndex = realLen & blockMask;
  834. /* Add length of hmac's ipad to total length. */
  835. realLen += blockSz;
  836. /* Length as bits - 8 bytes bigendian. */
  837. c32toa(realLen >> ((sizeof(word32) * 8) - 3), lenBytes);
  838. c32toa(realLen << 3, lenBytes + sizeof(word32));
  839. ret = Hmac_HashUpdate(hmac, (unsigned char*)hmac->ipad, blockSz);
  840. if (ret != 0)
  841. return ret;
  842. XMEMSET(hmac->innerHash, 0, macLen);
  843. if (safeBlocks > 0) {
  844. ret = Hmac_HashUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ);
  845. if (ret != 0)
  846. return ret;
  847. ret = Hmac_HashUpdate(hmac, in, safeBlocks * blockSz -
  848. WOLFSSL_TLS_HMAC_INNER_SZ);
  849. if (ret != 0)
  850. return ret;
  851. }
  852. else
  853. safeBlocks = 0;
  854. XMEMSET(digest, 0, macLen);
  855. k = safeBlocks * blockSz;
  856. for (i = safeBlocks; i < blocks; i++) {
  857. unsigned char hashBlock[WC_MAX_BLOCK_SIZE];
  858. unsigned char isEocBlock = ctMaskEq(i, eocBlock);
  859. unsigned char isOutBlock = ctMaskEq(i, lenBlock);
  860. for (j = 0; j < blockSz; j++) {
  861. unsigned char atEoc = ctMaskEq(j, eocIndex) & isEocBlock;
  862. unsigned char pastEoc = ctMaskGT(j, eocIndex) & isEocBlock;
  863. unsigned char b = 0;
  864. if (k < WOLFSSL_TLS_HMAC_INNER_SZ)
  865. b = header[k];
  866. else if (k < maxLen)
  867. b = in[k - WOLFSSL_TLS_HMAC_INNER_SZ];
  868. k++;
  869. b = ctMaskSel(atEoc, 0x80, b);
  870. b &= (unsigned char)~(word32)pastEoc;
  871. b &= ((unsigned char)~(word32)isOutBlock) | isEocBlock;
  872. if (j >= blockSz - 8) {
  873. b = ctMaskSel(isOutBlock, lenBytes[j - (blockSz - 8)], b);
  874. }
  875. hashBlock[j] = b;
  876. }
  877. ret = Hmac_HashUpdate(hmac, hashBlock, blockSz);
  878. if (ret != 0)
  879. return ret;
  880. ret = Hmac_HashFinalRaw(hmac, hashBlock);
  881. if (ret != 0)
  882. return ret;
  883. for (j = 0; j < macLen; j++)
  884. ((unsigned char*)hmac->innerHash)[j] |= hashBlock[j] & isOutBlock;
  885. }
  886. ret = Hmac_OuterHash(hmac, digest);
  887. return ret;
  888. }
  889. #endif
  890. #if defined(WOLFSSL_NO_HASH_RAW) || defined(HAVE_FIPS) || \
  891. defined(HAVE_SELFTEST) || defined(HAVE_BLAKE2)
  892. /* Calculate the HMAC of the header + message data.
  893. * Constant time implementation using normal hashing operations.
  894. * Update-Final need to be constant time.
  895. *
  896. * hmac HMAC object.
  897. * digest MAC result.
  898. * in Message data.
  899. * sz Size of the message data.
  900. * header Constructed record header with length of handshake data.
  901. * returns 0 on success, otherwise failure.
  902. */
  903. static int Hmac_UpdateFinal(Hmac* hmac, byte* digest, const byte* in,
  904. word32 sz, byte* header)
  905. {
  906. byte dummy[WC_MAX_BLOCK_SIZE] = {0};
  907. int ret;
  908. word32 msgSz, blockSz, macSz, padSz, maxSz, realSz;
  909. word32 offset = 0;
  910. int msgBlocks, blocks, blockBits;
  911. int i;
  912. switch (hmac->macType) {
  913. #ifndef NO_SHA
  914. case WC_SHA:
  915. blockSz = WC_SHA_BLOCK_SIZE;
  916. blockBits = 6;
  917. macSz = WC_SHA_DIGEST_SIZE;
  918. padSz = WC_SHA_BLOCK_SIZE - WC_SHA_PAD_SIZE + 1;
  919. break;
  920. #endif /* !NO_SHA */
  921. #ifndef NO_SHA256
  922. case WC_SHA256:
  923. blockSz = WC_SHA256_BLOCK_SIZE;
  924. blockBits = 6;
  925. macSz = WC_SHA256_DIGEST_SIZE;
  926. padSz = WC_SHA256_BLOCK_SIZE - WC_SHA256_PAD_SIZE + 1;
  927. break;
  928. #endif /* !NO_SHA256 */
  929. #ifdef WOLFSSL_SHA384
  930. case WC_SHA384:
  931. blockSz = WC_SHA384_BLOCK_SIZE;
  932. blockBits = 7;
  933. macSz = WC_SHA384_DIGEST_SIZE;
  934. padSz = WC_SHA384_BLOCK_SIZE - WC_SHA384_PAD_SIZE + 1;
  935. break;
  936. #endif /* WOLFSSL_SHA384 */
  937. #ifdef WOLFSSL_SHA512
  938. case WC_SHA512:
  939. blockSz = WC_SHA512_BLOCK_SIZE;
  940. blockBits = 7;
  941. macSz = WC_SHA512_DIGEST_SIZE;
  942. padSz = WC_SHA512_BLOCK_SIZE - WC_SHA512_PAD_SIZE + 1;
  943. break;
  944. #endif /* WOLFSSL_SHA512 */
  945. #ifdef HAVE_BLAKE2
  946. case WC_HASH_TYPE_BLAKE2B:
  947. blockSz = BLAKE2B_BLOCKBYTES;
  948. blockBits = 7;
  949. macSz = BLAKE2B_256;
  950. padSz = 0;
  951. break;
  952. #endif /* HAVE_BLAKE2 */
  953. default:
  954. return BAD_FUNC_ARG;
  955. }
  956. msgSz = sz - (1 + in[sz - 1] + macSz);
  957. /* Make negative result 0 */
  958. msgSz &= ~(0 - (msgSz >> 31));
  959. realSz = WOLFSSL_TLS_HMAC_INNER_SZ + msgSz;
  960. maxSz = WOLFSSL_TLS_HMAC_INNER_SZ + (sz - 1) - macSz;
  961. /* Calculate #blocks processed in HMAC for max and real data. */
  962. blocks = maxSz >> blockBits;
  963. blocks += ((maxSz + padSz) % blockSz) < padSz;
  964. msgBlocks = realSz >> blockBits;
  965. /* #Extra blocks to process. */
  966. blocks -= msgBlocks + ((((realSz + padSz) % blockSz) < padSz) ? 1 : 0);
  967. /* Calculate whole blocks. */
  968. msgBlocks--;
  969. ret = wc_HmacUpdate(hmac, header, WOLFSSL_TLS_HMAC_INNER_SZ);
  970. if (ret == 0) {
  971. /* Fill the rest of the block with any available data. */
  972. word32 currSz = ctMaskLT(msgSz, blockSz) & msgSz;
  973. currSz |= ctMaskGTE(msgSz, blockSz) & blockSz;
  974. currSz -= WOLFSSL_TLS_HMAC_INNER_SZ;
  975. currSz &= ~(0 - (currSz >> 31));
  976. ret = wc_HmacUpdate(hmac, in, currSz);
  977. offset = currSz;
  978. }
  979. if (ret == 0) {
  980. /* Do the hash operations on a block basis. */
  981. for (i = 0; i < msgBlocks; i++, offset += blockSz) {
  982. ret = wc_HmacUpdate(hmac, in + offset, blockSz);
  983. if (ret != 0)
  984. break;
  985. }
  986. }
  987. if (ret == 0)
  988. ret = wc_HmacUpdate(hmac, in + offset, msgSz - offset);
  989. if (ret == 0)
  990. ret = wc_HmacFinal(hmac, digest);
  991. if (ret == 0) {
  992. /* Do the dummy hash operations. Do at least one. */
  993. for (i = 0; i < blocks + 1; i++) {
  994. ret = wc_HmacUpdate(hmac, dummy, blockSz);
  995. if (ret != 0)
  996. break;
  997. }
  998. }
  999. return ret;
  1000. }
  1001. #endif
  1002. int TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz, int padSz,
  1003. int content, int verify, int epochOrder)
  1004. {
  1005. Hmac hmac;
  1006. byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
  1007. int ret = 0;
  1008. const byte* macSecret = NULL;
  1009. word32 hashSz = 0;
  1010. if (ssl == NULL)
  1011. return BAD_FUNC_ARG;
  1012. #ifdef HAVE_TRUNCATED_HMAC
  1013. hashSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  1014. : ssl->specs.hash_size;
  1015. #else
  1016. hashSz = ssl->specs.hash_size;
  1017. #endif
  1018. #ifdef HAVE_FUZZER
  1019. /* Fuzz "in" buffer with sz to be used in HMAC algorithm */
  1020. if (ssl->fuzzerCb) {
  1021. if (verify && padSz >= 0) {
  1022. ssl->fuzzerCb(ssl, in, sz + hashSz + padSz + 1, FUZZ_HMAC,
  1023. ssl->fuzzerCtx);
  1024. }
  1025. else {
  1026. ssl->fuzzerCb(ssl, in, sz, FUZZ_HMAC, ssl->fuzzerCtx);
  1027. }
  1028. }
  1029. #endif
  1030. if (!ssl->options.dtls)
  1031. wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, verify);
  1032. else
  1033. wolfSSL_SetTlsHmacInner(ssl, myInner, sz, content, epochOrder);
  1034. ret = wc_HmacInit(&hmac, ssl->heap, ssl->devId);
  1035. if (ret != 0)
  1036. return ret;
  1037. #ifdef WOLFSSL_DTLS
  1038. if (ssl->options.dtls)
  1039. macSecret = wolfSSL_GetDtlsMacSecret(ssl, verify, epochOrder);
  1040. else
  1041. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  1042. #else
  1043. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  1044. #endif
  1045. ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
  1046. macSecret,
  1047. ssl->specs.hash_size);
  1048. if (ret == 0) {
  1049. /* Constant time verification required. */
  1050. if (verify && padSz >= 0) {
  1051. #if !defined(WOLFSSL_NO_HASH_RAW) && !defined(HAVE_FIPS) && \
  1052. !defined(HAVE_SELFTEST)
  1053. #ifdef HAVE_BLAKE2
  1054. if (wolfSSL_GetHmacType(ssl) == WC_HASH_TYPE_BLAKE2B) {
  1055. ret = Hmac_UpdateFinal(&hmac, digest, in,
  1056. sz + hashSz + padSz + 1, myInner);
  1057. }
  1058. else
  1059. #endif
  1060. {
  1061. ret = Hmac_UpdateFinal_CT(&hmac, digest, in,
  1062. sz + hashSz + padSz + 1, hashSz, myInner);
  1063. }
  1064. #else
  1065. ret = Hmac_UpdateFinal(&hmac, digest, in, sz + hashSz + padSz + 1,
  1066. myInner);
  1067. #endif
  1068. }
  1069. else {
  1070. ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
  1071. if (ret == 0)
  1072. ret = wc_HmacUpdate(&hmac, in, sz); /* content */
  1073. if (ret == 0)
  1074. ret = wc_HmacFinal(&hmac, digest);
  1075. }
  1076. }
  1077. wc_HmacFree(&hmac);
  1078. return ret;
  1079. }
  1080. #endif /* WOLFSSL_AEAD_ONLY */
  1081. #endif /* !WOLFSSL_NO_TLS12 */
  1082. #ifdef HAVE_TLS_EXTENSIONS
  1083. /**
  1084. * The TLSX semaphore is used to calculate the size of the extensions to be sent
  1085. * from one peer to another.
  1086. */
  1087. /** Supports up to 72 flags. Increase as needed. */
  1088. #define SEMAPHORE_SIZE 9
  1089. /**
  1090. * Converts the extension type (id) to an index in the semaphore.
  1091. *
  1092. * Official reference for TLS extension types:
  1093. * http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xml
  1094. *
  1095. * Motivation:
  1096. * Previously, we used the extension type itself as the index of that
  1097. * extension in the semaphore as the extension types were declared
  1098. * sequentially, but maintain a semaphore as big as the number of available
  1099. * extensions is no longer an option since the release of renegotiation_info.
  1100. *
  1101. * How to update:
  1102. * Assign extension types that extrapolate the number of available semaphores
  1103. * to the first available index going backwards in the semaphore array.
  1104. * When adding a new extension type that don't extrapolate the number of
  1105. * available semaphores, check for a possible collision with with a
  1106. * 'remapped' extension type.
  1107. *
  1108. * Update TLSX_Parse for duplicate detection if more added above 62.
  1109. */
  1110. static WC_INLINE word16 TLSX_ToSemaphore(word16 type)
  1111. {
  1112. switch (type) {
  1113. case TLSX_RENEGOTIATION_INFO: /* 0xFF01 */
  1114. return 63;
  1115. #ifdef WOLFSSL_QUIC
  1116. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT: /* 0xffa5 */
  1117. return 64;
  1118. #endif
  1119. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1120. case TLSX_ECH: /* 0xfe0d */
  1121. return 65;
  1122. #endif
  1123. default:
  1124. if (type > 62) {
  1125. /* This message SHOULD only happens during the adding of
  1126. new TLS extensions in which its IANA number overflows
  1127. the current semaphore's range, or if its number already
  1128. is assigned to be used by another extension.
  1129. Use this check value for the new extension and decrement
  1130. the check value by one. */
  1131. WOLFSSL_MSG("### TLSX semaphore collision or overflow detected!");
  1132. }
  1133. }
  1134. return type;
  1135. }
  1136. /** Checks if a specific light (tls extension) is not set in the semaphore. */
  1137. #define IS_OFF(semaphore, light) \
  1138. (!(((semaphore)[(light) / 8] & (byte) (0x01 << ((light) % 8)))))
  1139. /** Turn on a specific light (tls extension) in the semaphore. */
  1140. /* the semaphore marks the extensions already written to the message */
  1141. #define TURN_ON(semaphore, light) \
  1142. ((semaphore)[(light) / 8] |= (byte) (0x01 << ((light) % 8)))
  1143. /** Turn off a specific light (tls extension) in the semaphore. */
  1144. #define TURN_OFF(semaphore, light) \
  1145. ((semaphore)[(light) / 8] &= (byte) ~(0x01 << ((light) % 8)))
  1146. /** Creates a new extension. */
  1147. static TLSX* TLSX_New(TLSX_Type type, const void* data, void* heap)
  1148. {
  1149. TLSX* extension = (TLSX*)XMALLOC(sizeof(TLSX), heap, DYNAMIC_TYPE_TLSX);
  1150. (void)heap;
  1151. if (extension) {
  1152. extension->type = type;
  1153. extension->data = (void*)data;
  1154. extension->resp = 0;
  1155. extension->next = NULL;
  1156. }
  1157. return extension;
  1158. }
  1159. /**
  1160. * Creates a new extension and appends it to the provided list.
  1161. * Checks for duplicate extensions, keeps the newest.
  1162. */
  1163. int TLSX_Append(TLSX** list, TLSX_Type type, const void* data, void* heap)
  1164. {
  1165. TLSX* extension = TLSX_New(type, data, heap);
  1166. TLSX* cur;
  1167. TLSX** prevNext = list;
  1168. if (extension == NULL)
  1169. return MEMORY_E;
  1170. for (cur = *list; cur != NULL;) {
  1171. if (cur->type == type) {
  1172. *prevNext = cur->next;
  1173. cur->next = NULL;
  1174. TLSX_FreeAll(cur, heap);
  1175. cur = *prevNext;
  1176. }
  1177. else {
  1178. prevNext = &cur->next;
  1179. cur = cur->next;
  1180. }
  1181. }
  1182. /* Append the extension to the list */
  1183. *prevNext = extension;
  1184. return 0;
  1185. }
  1186. /**
  1187. * Creates a new extension and pushes it to the provided list.
  1188. * Checks for duplicate extensions, keeps the newest.
  1189. */
  1190. int TLSX_Push(TLSX** list, TLSX_Type type, const void* data, void* heap)
  1191. {
  1192. TLSX* extension = TLSX_New(type, data, heap);
  1193. if (extension == NULL)
  1194. return MEMORY_E;
  1195. /* pushes the new extension on the list. */
  1196. extension->next = *list;
  1197. *list = extension;
  1198. /* remove duplicate extensions, there should be only one of each type. */
  1199. do {
  1200. if (extension->next && extension->next->type == type) {
  1201. TLSX *next = extension->next;
  1202. extension->next = next->next;
  1203. next->next = NULL;
  1204. TLSX_FreeAll(next, heap);
  1205. /* there is no way to occur more than
  1206. * two extensions of the same type.
  1207. */
  1208. break;
  1209. }
  1210. } while ((extension = extension->next));
  1211. return 0;
  1212. }
  1213. #ifndef NO_WOLFSSL_CLIENT
  1214. int TLSX_CheckUnsupportedExtension(WOLFSSL* ssl, TLSX_Type type);
  1215. int TLSX_CheckUnsupportedExtension(WOLFSSL* ssl, TLSX_Type type)
  1216. {
  1217. TLSX *extension = TLSX_Find(ssl->extensions, type);
  1218. if (!extension)
  1219. extension = TLSX_Find(ssl->ctx->extensions, type);
  1220. return extension == NULL;
  1221. }
  1222. int TLSX_HandleUnsupportedExtension(WOLFSSL* ssl);
  1223. int TLSX_HandleUnsupportedExtension(WOLFSSL* ssl)
  1224. {
  1225. SendAlert(ssl, alert_fatal, unsupported_extension);
  1226. WOLFSSL_ERROR_VERBOSE(UNSUPPORTED_EXTENSION);
  1227. return UNSUPPORTED_EXTENSION;
  1228. }
  1229. #else
  1230. #define TLSX_CheckUnsupportedExtension(ssl, type) 0
  1231. #define TLSX_HandleUnsupportedExtension(ssl) 0
  1232. #endif
  1233. #if !defined(NO_WOLFSSL_SERVER) || defined(WOLFSSL_TLS13)
  1234. void TLSX_SetResponse(WOLFSSL* ssl, TLSX_Type type);
  1235. /** Mark an extension to be sent back to the client. */
  1236. void TLSX_SetResponse(WOLFSSL* ssl, TLSX_Type type)
  1237. {
  1238. TLSX *extension = TLSX_Find(ssl->extensions, type);
  1239. if (extension)
  1240. extension->resp = 1;
  1241. }
  1242. #endif
  1243. /******************************************************************************/
  1244. /* Application-Layer Protocol Negotiation */
  1245. /******************************************************************************/
  1246. #ifdef HAVE_ALPN
  1247. /** Creates a new ALPN object, providing protocol name to use. */
  1248. static ALPN* TLSX_ALPN_New(char *protocol_name, word16 protocol_nameSz,
  1249. void* heap)
  1250. {
  1251. ALPN *alpn;
  1252. WOLFSSL_ENTER("TLSX_ALPN_New");
  1253. if (protocol_name == NULL ||
  1254. protocol_nameSz > WOLFSSL_MAX_ALPN_PROTO_NAME_LEN) {
  1255. WOLFSSL_MSG("Invalid arguments");
  1256. return NULL;
  1257. }
  1258. alpn = (ALPN*)XMALLOC(sizeof(ALPN), heap, DYNAMIC_TYPE_TLSX);
  1259. if (alpn == NULL) {
  1260. WOLFSSL_MSG("Memory failure");
  1261. return NULL;
  1262. }
  1263. alpn->next = NULL;
  1264. alpn->negotiated = 0;
  1265. alpn->options = 0;
  1266. alpn->protocol_name = (char*)XMALLOC(protocol_nameSz + 1,
  1267. heap, DYNAMIC_TYPE_TLSX);
  1268. if (alpn->protocol_name == NULL) {
  1269. WOLFSSL_MSG("Memory failure");
  1270. XFREE(alpn, heap, DYNAMIC_TYPE_TLSX);
  1271. return NULL;
  1272. }
  1273. XMEMCPY(alpn->protocol_name, protocol_name, protocol_nameSz);
  1274. alpn->protocol_name[protocol_nameSz] = 0;
  1275. (void)heap;
  1276. return alpn;
  1277. }
  1278. /** Releases an ALPN object. */
  1279. static void TLSX_ALPN_Free(ALPN *alpn, void* heap)
  1280. {
  1281. (void)heap;
  1282. if (alpn == NULL)
  1283. return;
  1284. XFREE(alpn->protocol_name, heap, DYNAMIC_TYPE_TLSX);
  1285. XFREE(alpn, heap, DYNAMIC_TYPE_TLSX);
  1286. }
  1287. /** Releases all ALPN objects in the provided list. */
  1288. static void TLSX_ALPN_FreeAll(ALPN *list, void* heap)
  1289. {
  1290. ALPN* alpn;
  1291. while ((alpn = list)) {
  1292. list = alpn->next;
  1293. TLSX_ALPN_Free(alpn, heap);
  1294. }
  1295. }
  1296. /** Tells the buffered size of the ALPN objects in a list. */
  1297. static word16 TLSX_ALPN_GetSize(ALPN *list)
  1298. {
  1299. ALPN* alpn;
  1300. word16 length = OPAQUE16_LEN; /* list length */
  1301. while ((alpn = list)) {
  1302. list = alpn->next;
  1303. length++; /* protocol name length is on one byte */
  1304. length += (word16)XSTRLEN(alpn->protocol_name);
  1305. }
  1306. return length;
  1307. }
  1308. /** Writes the ALPN objects of a list in a buffer. */
  1309. static word16 TLSX_ALPN_Write(ALPN *list, byte *output)
  1310. {
  1311. ALPN* alpn;
  1312. word16 length = 0;
  1313. word16 offset = OPAQUE16_LEN; /* list length offset */
  1314. while ((alpn = list)) {
  1315. list = alpn->next;
  1316. length = (word16)XSTRLEN(alpn->protocol_name);
  1317. /* protocol name length */
  1318. output[offset++] = (byte)length;
  1319. /* protocol name value */
  1320. XMEMCPY(output + offset, alpn->protocol_name, length);
  1321. offset += length;
  1322. }
  1323. /* writing list length */
  1324. c16toa(offset - OPAQUE16_LEN, output);
  1325. return offset;
  1326. }
  1327. /** Finds a protocol name in the provided ALPN list */
  1328. static ALPN* TLSX_ALPN_Find(ALPN *list, char *protocol_name, word16 size)
  1329. {
  1330. ALPN *alpn;
  1331. if (list == NULL || protocol_name == NULL)
  1332. return NULL;
  1333. alpn = list;
  1334. while (alpn != NULL && (
  1335. (word16)XSTRLEN(alpn->protocol_name) != size ||
  1336. XSTRNCMP(alpn->protocol_name, protocol_name, size)))
  1337. alpn = alpn->next;
  1338. return alpn;
  1339. }
  1340. /** Set the ALPN matching client and server requirements */
  1341. static int TLSX_SetALPN(TLSX** extensions, const void* data, word16 size,
  1342. void* heap)
  1343. {
  1344. ALPN *alpn;
  1345. int ret;
  1346. if (extensions == NULL || data == NULL)
  1347. return BAD_FUNC_ARG;
  1348. alpn = TLSX_ALPN_New((char *)data, size, heap);
  1349. if (alpn == NULL) {
  1350. WOLFSSL_MSG("Memory failure");
  1351. return MEMORY_E;
  1352. }
  1353. alpn->negotiated = 1;
  1354. ret = TLSX_Push(extensions, TLSX_APPLICATION_LAYER_PROTOCOL, (void*)alpn,
  1355. heap);
  1356. if (ret != 0) {
  1357. TLSX_ALPN_Free(alpn, heap);
  1358. return ret;
  1359. }
  1360. return WOLFSSL_SUCCESS;
  1361. }
  1362. static int ALPN_find_match(WOLFSSL *ssl, TLSX **pextension,
  1363. const byte **psel, byte *psel_len,
  1364. const byte *alpn_val, word16 alpn_val_len)
  1365. {
  1366. TLSX *extension;
  1367. ALPN *alpn, *list;
  1368. const byte *sel = NULL, *s;
  1369. byte sel_len = 0, wlen;
  1370. extension = TLSX_Find(ssl->extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1371. if (extension == NULL)
  1372. extension = TLSX_Find(ssl->ctx->extensions,
  1373. TLSX_APPLICATION_LAYER_PROTOCOL);
  1374. /* No ALPN configured here */
  1375. if (extension == NULL || extension->data == NULL) {
  1376. *pextension = NULL;
  1377. *psel = NULL;
  1378. *psel_len = 0;
  1379. return 0;
  1380. }
  1381. list = (ALPN*)extension->data;
  1382. for (s = alpn_val;
  1383. (s - alpn_val) < alpn_val_len;
  1384. s += wlen) {
  1385. wlen = *s++; /* bounds already checked on save */
  1386. alpn = TLSX_ALPN_Find(list, (char*)s, wlen);
  1387. if (alpn != NULL) {
  1388. WOLFSSL_MSG("ALPN protocol match");
  1389. sel = s,
  1390. sel_len = wlen;
  1391. break;
  1392. }
  1393. }
  1394. if (sel == NULL) {
  1395. WOLFSSL_MSG("No ALPN protocol match");
  1396. /* do nothing if no protocol match between client and server and option
  1397. is set to continue (like OpenSSL) */
  1398. if (list->options & WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) {
  1399. WOLFSSL_MSG("Continue on mismatch");
  1400. }
  1401. else {
  1402. SendAlert(ssl, alert_fatal, no_application_protocol);
  1403. WOLFSSL_ERROR_VERBOSE(UNKNOWN_ALPN_PROTOCOL_NAME_E);
  1404. return UNKNOWN_ALPN_PROTOCOL_NAME_E;
  1405. }
  1406. }
  1407. *pextension = extension;
  1408. *psel = sel;
  1409. *psel_len = sel_len;
  1410. return 0;
  1411. }
  1412. int ALPN_Select(WOLFSSL *ssl)
  1413. {
  1414. TLSX *extension;
  1415. const byte *sel = NULL;
  1416. byte sel_len = 0;
  1417. int r = 0;
  1418. WOLFSSL_ENTER("ALPN_Select");
  1419. if (ssl->alpn_peer_requested == NULL)
  1420. return 0;
  1421. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  1422. if (ssl->alpnSelect != NULL && ssl->options.side == WOLFSSL_SERVER_END) {
  1423. r = ssl->alpnSelect(ssl, &sel, &sel_len, ssl->alpn_peer_requested,
  1424. ssl->alpn_peer_requested_length, ssl->alpnSelectArg);
  1425. switch (r) {
  1426. case SSL_TLSEXT_ERR_OK:
  1427. WOLFSSL_MSG("ALPN protocol match");
  1428. break;
  1429. case SSL_TLSEXT_ERR_NOACK:
  1430. WOLFSSL_MSG("ALPN cb no match but not fatal");
  1431. sel = NULL;
  1432. sel_len = 0;
  1433. break;
  1434. case SSL_TLSEXT_ERR_ALERT_FATAL:
  1435. default:
  1436. WOLFSSL_MSG("ALPN cb no match and fatal");
  1437. SendAlert(ssl, alert_fatal, no_application_protocol);
  1438. WOLFSSL_ERROR_VERBOSE(UNKNOWN_ALPN_PROTOCOL_NAME_E);
  1439. return UNKNOWN_ALPN_PROTOCOL_NAME_E;
  1440. break;
  1441. }
  1442. }
  1443. else
  1444. #endif
  1445. {
  1446. r = ALPN_find_match(ssl, &extension, &sel, &sel_len,
  1447. ssl->alpn_peer_requested,
  1448. ssl->alpn_peer_requested_length);
  1449. if (r != 0)
  1450. return r;
  1451. }
  1452. if (sel != NULL) {
  1453. /* set the matching negotiated protocol */
  1454. r = TLSX_SetALPN(&ssl->extensions, sel, sel_len, ssl->heap);
  1455. if (r != WOLFSSL_SUCCESS) {
  1456. WOLFSSL_MSG("TLSX_SetALPN failed");
  1457. return BUFFER_ERROR;
  1458. }
  1459. /* reply to ALPN extension sent from peer */
  1460. #ifndef NO_WOLFSSL_SERVER
  1461. TLSX_SetResponse(ssl, TLSX_APPLICATION_LAYER_PROTOCOL);
  1462. #endif
  1463. }
  1464. return 0;
  1465. }
  1466. /** Parses a buffer of ALPN extensions and set the first one matching
  1467. * client and server requirements */
  1468. static int TLSX_ALPN_ParseAndSet(WOLFSSL *ssl, const byte *input, word16 length,
  1469. byte isRequest)
  1470. {
  1471. word16 size = 0, offset = 0, wlen;
  1472. int r = BUFFER_ERROR;
  1473. const byte *s;
  1474. if (OPAQUE16_LEN > length)
  1475. return BUFFER_ERROR;
  1476. ato16(input, &size);
  1477. offset += OPAQUE16_LEN;
  1478. /* validating alpn list length */
  1479. if (size == 0 || length != OPAQUE16_LEN + size)
  1480. return BUFFER_ERROR;
  1481. /* validating length of entries before accepting */
  1482. for (s = input + offset; (s - input) < size; s += wlen) {
  1483. wlen = *s++;
  1484. if (wlen == 0 || (s + wlen - input) > length)
  1485. return BUFFER_ERROR;
  1486. }
  1487. if (isRequest) {
  1488. /* keep the list sent by peer, if this is from a request. We
  1489. * use it later in ALPN_Select() for evaluation. */
  1490. if (ssl->alpn_peer_requested != NULL) {
  1491. XFREE(ssl->alpn_peer_requested, ssl->heap, DYNAMIC_TYPE_ALPN);
  1492. ssl->alpn_peer_requested_length = 0;
  1493. }
  1494. ssl->alpn_peer_requested = (byte *)XMALLOC(size, ssl->heap,
  1495. DYNAMIC_TYPE_ALPN);
  1496. if (ssl->alpn_peer_requested == NULL) {
  1497. return MEMORY_ERROR;
  1498. }
  1499. ssl->alpn_peer_requested_length = size;
  1500. XMEMCPY(ssl->alpn_peer_requested, (char*)input + offset, size);
  1501. }
  1502. else {
  1503. /* a response, we should find the value in our config */
  1504. const byte *sel = NULL;
  1505. byte sel_len = 0;
  1506. TLSX *extension = NULL;
  1507. r = ALPN_find_match(ssl, &extension, &sel, &sel_len, input + offset, size);
  1508. if (r != 0)
  1509. return r;
  1510. if (sel != NULL) {
  1511. /* set the matching negotiated protocol */
  1512. r = TLSX_SetALPN(&ssl->extensions, sel, sel_len, ssl->heap);
  1513. if (r != WOLFSSL_SUCCESS) {
  1514. WOLFSSL_MSG("TLSX_SetALPN failed");
  1515. return BUFFER_ERROR;
  1516. }
  1517. }
  1518. /* If we had nothing configured, the response is unexpected */
  1519. else if (extension == NULL) {
  1520. r = TLSX_HandleUnsupportedExtension(ssl);
  1521. if (r != 0)
  1522. return r;
  1523. }
  1524. }
  1525. return 0;
  1526. }
  1527. /** Add a protocol name to the list of accepted usable ones */
  1528. int TLSX_UseALPN(TLSX** extensions, const void* data, word16 size, byte options,
  1529. void* heap)
  1530. {
  1531. ALPN *alpn;
  1532. TLSX *extension;
  1533. int ret;
  1534. if (extensions == NULL || data == NULL)
  1535. return BAD_FUNC_ARG;
  1536. alpn = TLSX_ALPN_New((char *)data, size, heap);
  1537. if (alpn == NULL) {
  1538. WOLFSSL_MSG("Memory failure");
  1539. return MEMORY_E;
  1540. }
  1541. /* Set Options of ALPN */
  1542. alpn->options = options;
  1543. extension = TLSX_Find(*extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1544. if (extension == NULL) {
  1545. ret = TLSX_Push(extensions, TLSX_APPLICATION_LAYER_PROTOCOL,
  1546. (void*)alpn, heap);
  1547. if (ret != 0) {
  1548. TLSX_ALPN_Free(alpn, heap);
  1549. return ret;
  1550. }
  1551. }
  1552. else {
  1553. /* push new ALPN object to extension data. */
  1554. alpn->next = (ALPN*)extension->data;
  1555. extension->data = (void*)alpn;
  1556. }
  1557. return WOLFSSL_SUCCESS;
  1558. }
  1559. /** Get the protocol name set by the server */
  1560. int TLSX_ALPN_GetRequest(TLSX* extensions, void** data, word16 *dataSz)
  1561. {
  1562. TLSX *extension;
  1563. ALPN *alpn;
  1564. if (extensions == NULL || data == NULL || dataSz == NULL)
  1565. return BAD_FUNC_ARG;
  1566. *data = NULL;
  1567. *dataSz = 0;
  1568. extension = TLSX_Find(extensions, TLSX_APPLICATION_LAYER_PROTOCOL);
  1569. if (extension == NULL) {
  1570. WOLFSSL_MSG("TLS extension not found");
  1571. WOLFSSL_ERROR_VERBOSE(WOLFSSL_ALPN_NOT_FOUND);
  1572. return WOLFSSL_ALPN_NOT_FOUND;
  1573. }
  1574. alpn = (ALPN *)extension->data;
  1575. if (alpn == NULL) {
  1576. WOLFSSL_MSG("ALPN extension not found");
  1577. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1578. return WOLFSSL_FATAL_ERROR;
  1579. }
  1580. if (alpn->negotiated != 1) {
  1581. /* consider as an error */
  1582. if (alpn->options & WOLFSSL_ALPN_FAILED_ON_MISMATCH) {
  1583. WOLFSSL_MSG("No protocol match with peer -> Failed");
  1584. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1585. return WOLFSSL_FATAL_ERROR;
  1586. }
  1587. /* continue without negotiated protocol */
  1588. WOLFSSL_MSG("No protocol match with peer -> Continue");
  1589. WOLFSSL_ERROR_VERBOSE(WOLFSSL_ALPN_NOT_FOUND);
  1590. return WOLFSSL_ALPN_NOT_FOUND;
  1591. }
  1592. if (alpn->next != NULL) {
  1593. WOLFSSL_MSG("Only one protocol name must be accepted");
  1594. WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
  1595. return WOLFSSL_FATAL_ERROR;
  1596. }
  1597. *data = alpn->protocol_name;
  1598. *dataSz = (word16)XSTRLEN((char*)*data);
  1599. return WOLFSSL_SUCCESS;
  1600. }
  1601. #define ALPN_FREE_ALL TLSX_ALPN_FreeAll
  1602. #define ALPN_GET_SIZE TLSX_ALPN_GetSize
  1603. #define ALPN_WRITE TLSX_ALPN_Write
  1604. #define ALPN_PARSE TLSX_ALPN_ParseAndSet
  1605. #else /* HAVE_ALPN */
  1606. #define ALPN_FREE_ALL(list, heap)
  1607. #define ALPN_GET_SIZE(list) 0
  1608. #define ALPN_WRITE(a, b) 0
  1609. #define ALPN_PARSE(a, b, c, d) 0
  1610. #endif /* HAVE_ALPN */
  1611. /******************************************************************************/
  1612. /* Server Name Indication */
  1613. /******************************************************************************/
  1614. #ifdef HAVE_SNI
  1615. /** Creates a new SNI object. */
  1616. static SNI* TLSX_SNI_New(byte type, const void* data, word16 size, void* heap)
  1617. {
  1618. SNI* sni = (SNI*)XMALLOC(sizeof(SNI), heap, DYNAMIC_TYPE_TLSX);
  1619. (void)heap;
  1620. if (sni) {
  1621. sni->type = type;
  1622. sni->next = NULL;
  1623. #ifndef NO_WOLFSSL_SERVER
  1624. sni->options = 0;
  1625. sni->status = WOLFSSL_SNI_NO_MATCH;
  1626. #endif
  1627. switch (sni->type) {
  1628. case WOLFSSL_SNI_HOST_NAME:
  1629. sni->data.host_name = (char*)XMALLOC(size + 1, heap,
  1630. DYNAMIC_TYPE_TLSX);
  1631. if (sni->data.host_name) {
  1632. XSTRNCPY(sni->data.host_name, (const char*)data, size);
  1633. sni->data.host_name[size] = '\0';
  1634. } else {
  1635. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1636. sni = NULL;
  1637. }
  1638. break;
  1639. default: /* invalid type */
  1640. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1641. sni = NULL;
  1642. }
  1643. }
  1644. return sni;
  1645. }
  1646. /** Releases a SNI object. */
  1647. static void TLSX_SNI_Free(SNI* sni, void* heap)
  1648. {
  1649. if (sni) {
  1650. switch (sni->type) {
  1651. case WOLFSSL_SNI_HOST_NAME:
  1652. XFREE(sni->data.host_name, heap, DYNAMIC_TYPE_TLSX);
  1653. break;
  1654. }
  1655. XFREE(sni, heap, DYNAMIC_TYPE_TLSX);
  1656. }
  1657. (void)heap;
  1658. }
  1659. /** Releases all SNI objects in the provided list. */
  1660. static void TLSX_SNI_FreeAll(SNI* list, void* heap)
  1661. {
  1662. SNI* sni;
  1663. while ((sni = list)) {
  1664. list = sni->next;
  1665. TLSX_SNI_Free(sni, heap);
  1666. }
  1667. }
  1668. /** Tells the buffered size of the SNI objects in a list. */
  1669. static word16 TLSX_SNI_GetSize(SNI* list)
  1670. {
  1671. SNI* sni;
  1672. word16 length = OPAQUE16_LEN; /* list length */
  1673. while ((sni = list)) {
  1674. list = sni->next;
  1675. length += ENUM_LEN + OPAQUE16_LEN; /* sni type + sni length */
  1676. switch (sni->type) {
  1677. case WOLFSSL_SNI_HOST_NAME:
  1678. length += (word16)XSTRLEN((char*)sni->data.host_name);
  1679. break;
  1680. }
  1681. }
  1682. return length;
  1683. }
  1684. /** Writes the SNI objects of a list in a buffer. */
  1685. static word16 TLSX_SNI_Write(SNI* list, byte* output)
  1686. {
  1687. SNI* sni;
  1688. word16 length = 0;
  1689. word16 offset = OPAQUE16_LEN; /* list length offset */
  1690. while ((sni = list)) {
  1691. list = sni->next;
  1692. output[offset++] = sni->type; /* sni type */
  1693. switch (sni->type) {
  1694. case WOLFSSL_SNI_HOST_NAME:
  1695. length = (word16)XSTRLEN((char*)sni->data.host_name);
  1696. c16toa(length, output + offset); /* sni length */
  1697. offset += OPAQUE16_LEN;
  1698. XMEMCPY(output + offset, sni->data.host_name, length);
  1699. offset += length;
  1700. break;
  1701. }
  1702. }
  1703. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  1704. return offset;
  1705. }
  1706. /** Finds a SNI object in the provided list. */
  1707. static SNI* TLSX_SNI_Find(SNI *list, byte type)
  1708. {
  1709. SNI* sni = list;
  1710. while (sni && sni->type != type)
  1711. sni = sni->next;
  1712. return sni;
  1713. }
  1714. #if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
  1715. /** Sets the status of a SNI object. */
  1716. static void TLSX_SNI_SetStatus(TLSX* extensions, byte type, byte status)
  1717. {
  1718. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1719. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1720. if (sni)
  1721. sni->status = status;
  1722. }
  1723. #endif
  1724. /** Gets the status of a SNI object. */
  1725. byte TLSX_SNI_Status(TLSX* extensions, byte type)
  1726. {
  1727. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1728. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1729. if (sni)
  1730. return sni->status;
  1731. return 0;
  1732. }
  1733. /** Parses a buffer of SNI extensions. */
  1734. static int TLSX_SNI_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  1735. byte isRequest)
  1736. {
  1737. #ifndef NO_WOLFSSL_SERVER
  1738. word16 size = 0;
  1739. word16 offset = 0;
  1740. int cacheOnly = 0;
  1741. SNI *sni = NULL;
  1742. byte type;
  1743. byte matched;
  1744. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1745. WOLFSSL_ECH* ech = NULL;
  1746. WOLFSSL_EchConfig* workingConfig;
  1747. TLSX* echX;
  1748. #endif
  1749. #endif /* !NO_WOLFSSL_SERVER */
  1750. TLSX *extension = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  1751. if (!extension)
  1752. extension = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  1753. if (!isRequest) {
  1754. #ifndef NO_WOLFSSL_CLIENT
  1755. if (!extension || !extension->data)
  1756. return TLSX_HandleUnsupportedExtension(ssl);
  1757. if (length > 0)
  1758. return BUFFER_ERROR; /* SNI response MUST be empty. */
  1759. /* This call enables wolfSSL_SNI_GetRequest() to be called in the
  1760. * client side to fetch the used SNI. It will only work if the SNI
  1761. * was set at the SSL object level. Right now we only support one
  1762. * name type, WOLFSSL_SNI_HOST_NAME, but in the future, the
  1763. * inclusion of other name types will turn this method inaccurate,
  1764. * as the extension response doesn't contains information of which
  1765. * name was accepted.
  1766. */
  1767. TLSX_SNI_SetStatus(ssl->extensions, WOLFSSL_SNI_HOST_NAME,
  1768. WOLFSSL_SNI_REAL_MATCH);
  1769. return 0;
  1770. #endif
  1771. }
  1772. #ifndef NO_WOLFSSL_SERVER
  1773. if (!extension || !extension->data) {
  1774. /* This will keep SNI even though TLSX_UseSNI has not been called.
  1775. * Enable it so that the received sni is available to functions
  1776. * that use a custom callback when SNI is received.
  1777. */
  1778. #ifdef WOLFSSL_ALWAYS_KEEP_SNI
  1779. cacheOnly = 1;
  1780. #endif
  1781. if (ssl->ctx->sniRecvCb) {
  1782. cacheOnly = 1;
  1783. }
  1784. if (cacheOnly) {
  1785. WOLFSSL_MSG("Forcing SSL object to store SNI parameter");
  1786. }
  1787. else {
  1788. /* Skipping, SNI not enabled at server side. */
  1789. return 0;
  1790. }
  1791. }
  1792. if (OPAQUE16_LEN > length)
  1793. return BUFFER_ERROR;
  1794. ato16(input, &size);
  1795. offset += OPAQUE16_LEN;
  1796. /* validating sni list length */
  1797. if (length != OPAQUE16_LEN + size || size == 0)
  1798. return BUFFER_ERROR;
  1799. /* SNI was badly specified and only one type is now recognized and allowed.
  1800. * Only one SNI value per type (RFC6066), so, no loop. */
  1801. type = input[offset++];
  1802. if (type != WOLFSSL_SNI_HOST_NAME)
  1803. return BUFFER_ERROR;
  1804. if (offset + OPAQUE16_LEN > length)
  1805. return BUFFER_ERROR;
  1806. ato16(input + offset, &size);
  1807. offset += OPAQUE16_LEN;
  1808. if (offset + size != length || size == 0)
  1809. return BUFFER_ERROR;
  1810. if (!cacheOnly && !(sni = TLSX_SNI_Find((SNI*)extension->data, type)))
  1811. return 0; /* not using this type of SNI. */
  1812. #ifdef WOLFSSL_TLS13
  1813. /* Don't process the second ClientHello SNI extension if there
  1814. * was problems with the first.
  1815. */
  1816. if (!cacheOnly && sni->status != 0)
  1817. return 0;
  1818. #endif
  1819. matched = cacheOnly || (XSTRLEN(sni->data.host_name) == size &&
  1820. XSTRNCMP(sni->data.host_name, (const char*)input + offset, size) == 0);
  1821. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  1822. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  1823. if (echX != NULL)
  1824. ech = (WOLFSSL_ECH*)(echX->data);
  1825. if (!matched && ech != NULL) {
  1826. workingConfig = ech->echConfig;
  1827. while (workingConfig != NULL) {
  1828. matched = XSTRLEN(workingConfig->publicName) == size &&
  1829. XSTRNCMP(workingConfig->publicName,
  1830. (const char*)input + offset, size) == 0;
  1831. if (matched)
  1832. break;
  1833. workingConfig = workingConfig->next;
  1834. }
  1835. }
  1836. #endif
  1837. if (matched || sni->options & WOLFSSL_SNI_ANSWER_ON_MISMATCH) {
  1838. int matchStat;
  1839. int r = TLSX_UseSNI(&ssl->extensions, type, input + offset, size,
  1840. ssl->heap);
  1841. if (r != WOLFSSL_SUCCESS)
  1842. return r; /* throws error. */
  1843. if (cacheOnly) {
  1844. WOLFSSL_MSG("Forcing storage of SNI, Fake match");
  1845. matchStat = WOLFSSL_SNI_FORCE_KEEP;
  1846. }
  1847. else if (matched) {
  1848. WOLFSSL_MSG("SNI did match!");
  1849. matchStat = WOLFSSL_SNI_REAL_MATCH;
  1850. }
  1851. else {
  1852. WOLFSSL_MSG("fake SNI match from ANSWER_ON_MISMATCH");
  1853. matchStat = WOLFSSL_SNI_FAKE_MATCH;
  1854. }
  1855. TLSX_SNI_SetStatus(ssl->extensions, type, (byte)matchStat);
  1856. if (!cacheOnly)
  1857. TLSX_SetResponse(ssl, TLSX_SERVER_NAME);
  1858. }
  1859. else if (!(sni->options & WOLFSSL_SNI_CONTINUE_ON_MISMATCH)) {
  1860. SendAlert(ssl, alert_fatal, unrecognized_name);
  1861. WOLFSSL_ERROR_VERBOSE(UNKNOWN_SNI_HOST_NAME_E);
  1862. return UNKNOWN_SNI_HOST_NAME_E;
  1863. }
  1864. #else
  1865. (void)input;
  1866. #endif /* !NO_WOLFSSL_SERVER */
  1867. #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER)
  1868. (void)length;
  1869. #endif
  1870. return 0;
  1871. }
  1872. static int TLSX_SNI_VerifyParse(WOLFSSL* ssl, byte isRequest)
  1873. {
  1874. (void)ssl;
  1875. if (isRequest) {
  1876. #ifndef NO_WOLFSSL_SERVER
  1877. TLSX* ctx_ext = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  1878. TLSX* ssl_ext = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  1879. SNI* ctx_sni = ctx_ext ? (SNI*)ctx_ext->data : NULL;
  1880. SNI* ssl_sni = ssl_ext ? (SNI*)ssl_ext->data : NULL;
  1881. SNI* sni = NULL;
  1882. for (; ctx_sni; ctx_sni = ctx_sni->next) {
  1883. if (ctx_sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) {
  1884. sni = TLSX_SNI_Find(ssl_sni, ctx_sni->type);
  1885. if (sni) {
  1886. if (sni->status != WOLFSSL_SNI_NO_MATCH)
  1887. continue;
  1888. /* if ssl level overrides ctx level, it is ok. */
  1889. if ((sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) == 0)
  1890. continue;
  1891. }
  1892. SendAlert(ssl, alert_fatal, handshake_failure);
  1893. WOLFSSL_ERROR_VERBOSE(SNI_ABSENT_ERROR);
  1894. return SNI_ABSENT_ERROR;
  1895. }
  1896. }
  1897. for (; ssl_sni; ssl_sni = ssl_sni->next) {
  1898. if (ssl_sni->options & WOLFSSL_SNI_ABORT_ON_ABSENCE) {
  1899. if (ssl_sni->status != WOLFSSL_SNI_NO_MATCH)
  1900. continue;
  1901. SendAlert(ssl, alert_fatal, handshake_failure);
  1902. WOLFSSL_ERROR_VERBOSE(SNI_ABSENT_ERROR);
  1903. return SNI_ABSENT_ERROR;
  1904. }
  1905. }
  1906. #endif /* NO_WOLFSSL_SERVER */
  1907. }
  1908. return 0;
  1909. }
  1910. int TLSX_UseSNI(TLSX** extensions, byte type, const void* data, word16 size,
  1911. void* heap)
  1912. {
  1913. TLSX* extension;
  1914. SNI* sni = NULL;
  1915. if (extensions == NULL || data == NULL)
  1916. return BAD_FUNC_ARG;
  1917. if ((sni = TLSX_SNI_New(type, data, size, heap)) == NULL)
  1918. return MEMORY_E;
  1919. extension = TLSX_Find(*extensions, TLSX_SERVER_NAME);
  1920. if (!extension) {
  1921. int ret = TLSX_Push(extensions, TLSX_SERVER_NAME, (void*)sni, heap);
  1922. if (ret != 0) {
  1923. TLSX_SNI_Free(sni, heap);
  1924. return ret;
  1925. }
  1926. }
  1927. else {
  1928. /* push new SNI object to extension data. */
  1929. sni->next = (SNI*)extension->data;
  1930. extension->data = (void*)sni;
  1931. /* remove duplicate SNI, there should be only one of each type. */
  1932. do {
  1933. if (sni->next && sni->next->type == type) {
  1934. SNI* next = sni->next;
  1935. sni->next = next->next;
  1936. TLSX_SNI_Free(next, heap);
  1937. /* there is no way to occur more than
  1938. * two SNIs of the same type.
  1939. */
  1940. break;
  1941. }
  1942. } while ((sni = sni->next));
  1943. }
  1944. return WOLFSSL_SUCCESS;
  1945. }
  1946. #ifndef NO_WOLFSSL_SERVER
  1947. /** Tells the SNI requested by the client. */
  1948. word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type, void** data)
  1949. {
  1950. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1951. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1952. if (sni && sni->status != WOLFSSL_SNI_NO_MATCH) {
  1953. switch (sni->type) {
  1954. case WOLFSSL_SNI_HOST_NAME:
  1955. if (data) {
  1956. *data = sni->data.host_name;
  1957. return (word16)XSTRLEN((char*)*data);
  1958. }
  1959. }
  1960. }
  1961. return 0;
  1962. }
  1963. /** Sets the options for a SNI object. */
  1964. void TLSX_SNI_SetOptions(TLSX* extensions, byte type, byte options)
  1965. {
  1966. TLSX* extension = TLSX_Find(extensions, TLSX_SERVER_NAME);
  1967. SNI* sni = TLSX_SNI_Find(extension ? (SNI*)extension->data : NULL, type);
  1968. if (sni)
  1969. sni->options = options;
  1970. }
  1971. /** Retrieves a SNI request from a client hello buffer. */
  1972. int TLSX_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz,
  1973. byte type, byte* sni, word32* inOutSz)
  1974. {
  1975. word32 offset = 0;
  1976. word32 len32 = 0;
  1977. word16 len16 = 0;
  1978. if (helloSz < RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + CLIENT_HELLO_FIRST)
  1979. return INCOMPLETE_DATA;
  1980. /* TLS record header */
  1981. if ((enum ContentType) clientHello[offset++] != handshake) {
  1982. /* checking for SSLv2.0 client hello according to: */
  1983. /* http://tools.ietf.org/html/rfc4346#appendix-E.1 */
  1984. if ((enum HandShakeType) clientHello[++offset] == client_hello) {
  1985. offset += ENUM_LEN + VERSION_SZ; /* skip version */
  1986. ato16(clientHello + offset, &len16);
  1987. offset += OPAQUE16_LEN;
  1988. if (len16 % 3) /* cipher_spec_length must be multiple of 3 */
  1989. return BUFFER_ERROR;
  1990. ato16(clientHello + offset, &len16);
  1991. /* Returning SNI_UNSUPPORTED do not increment offset here */
  1992. if (len16 != 0) /* session_id_length must be 0 */
  1993. return BUFFER_ERROR;
  1994. WOLFSSL_ERROR_VERBOSE(SNI_UNSUPPORTED);
  1995. return SNI_UNSUPPORTED;
  1996. }
  1997. return BUFFER_ERROR;
  1998. }
  1999. if (clientHello[offset++] != SSLv3_MAJOR)
  2000. return BUFFER_ERROR;
  2001. if (clientHello[offset++] < TLSv1_MINOR) {
  2002. WOLFSSL_ERROR_VERBOSE(SNI_UNSUPPORTED);
  2003. return SNI_UNSUPPORTED;
  2004. }
  2005. ato16(clientHello + offset, &len16);
  2006. offset += OPAQUE16_LEN;
  2007. if (offset + len16 > helloSz)
  2008. return INCOMPLETE_DATA;
  2009. /* Handshake header */
  2010. if ((enum HandShakeType) clientHello[offset] != client_hello)
  2011. return BUFFER_ERROR;
  2012. c24to32(clientHello + offset + 1, &len32);
  2013. offset += HANDSHAKE_HEADER_SZ;
  2014. if (offset + len32 > helloSz)
  2015. return BUFFER_ERROR;
  2016. /* client hello */
  2017. offset += VERSION_SZ + RAN_LEN; /* version, random */
  2018. if (helloSz < offset + clientHello[offset])
  2019. return BUFFER_ERROR;
  2020. offset += ENUM_LEN + clientHello[offset]; /* skip session id */
  2021. /* cypher suites */
  2022. if (helloSz < offset + OPAQUE16_LEN)
  2023. return BUFFER_ERROR;
  2024. ato16(clientHello + offset, &len16);
  2025. offset += OPAQUE16_LEN;
  2026. if (helloSz < offset + len16)
  2027. return BUFFER_ERROR;
  2028. offset += len16; /* skip cypher suites */
  2029. /* compression methods */
  2030. if (helloSz < offset + 1)
  2031. return BUFFER_ERROR;
  2032. if (helloSz < offset + clientHello[offset])
  2033. return BUFFER_ERROR;
  2034. offset += ENUM_LEN + clientHello[offset]; /* skip compression methods */
  2035. /* extensions */
  2036. if (helloSz < offset + OPAQUE16_LEN)
  2037. return 0; /* no extensions in client hello. */
  2038. ato16(clientHello + offset, &len16);
  2039. offset += OPAQUE16_LEN;
  2040. if (helloSz < offset + len16)
  2041. return BUFFER_ERROR;
  2042. while (len16 >= OPAQUE16_LEN + OPAQUE16_LEN) {
  2043. word16 extType;
  2044. word16 extLen;
  2045. ato16(clientHello + offset, &extType);
  2046. offset += OPAQUE16_LEN;
  2047. ato16(clientHello + offset, &extLen);
  2048. offset += OPAQUE16_LEN;
  2049. if (helloSz < offset + extLen)
  2050. return BUFFER_ERROR;
  2051. if (extType != TLSX_SERVER_NAME) {
  2052. offset += extLen; /* skip extension */
  2053. } else {
  2054. word16 listLen;
  2055. ato16(clientHello + offset, &listLen);
  2056. offset += OPAQUE16_LEN;
  2057. if (helloSz < offset + listLen)
  2058. return BUFFER_ERROR;
  2059. while (listLen > ENUM_LEN + OPAQUE16_LEN) {
  2060. byte sniType = clientHello[offset++];
  2061. word16 sniLen;
  2062. ato16(clientHello + offset, &sniLen);
  2063. offset += OPAQUE16_LEN;
  2064. if (helloSz < offset + sniLen)
  2065. return BUFFER_ERROR;
  2066. if (sniType != type) {
  2067. offset += sniLen;
  2068. listLen -= min(ENUM_LEN + OPAQUE16_LEN + sniLen, listLen);
  2069. continue;
  2070. }
  2071. *inOutSz = min(sniLen, *inOutSz);
  2072. XMEMCPY(sni, clientHello + offset, *inOutSz);
  2073. return WOLFSSL_SUCCESS;
  2074. }
  2075. }
  2076. len16 -= min(2 * OPAQUE16_LEN + extLen, len16);
  2077. }
  2078. return len16 ? BUFFER_ERROR : 0;
  2079. }
  2080. #endif
  2081. #define SNI_FREE_ALL TLSX_SNI_FreeAll
  2082. #define SNI_GET_SIZE TLSX_SNI_GetSize
  2083. #define SNI_WRITE TLSX_SNI_Write
  2084. #define SNI_PARSE TLSX_SNI_Parse
  2085. #define SNI_VERIFY_PARSE TLSX_SNI_VerifyParse
  2086. #else
  2087. #define SNI_FREE_ALL(list, heap)
  2088. #define SNI_GET_SIZE(list) 0
  2089. #define SNI_WRITE(a, b) 0
  2090. #define SNI_PARSE(a, b, c, d) 0
  2091. #define SNI_VERIFY_PARSE(a, b) 0
  2092. #endif /* HAVE_SNI */
  2093. /******************************************************************************/
  2094. /* Trusted CA Key Indication */
  2095. /******************************************************************************/
  2096. #ifdef HAVE_TRUSTED_CA
  2097. /** Creates a new TCA object. */
  2098. static TCA* TLSX_TCA_New(byte type, const byte* id, word16 idSz, void* heap)
  2099. {
  2100. TCA* tca = (TCA*)XMALLOC(sizeof(TCA), heap, DYNAMIC_TYPE_TLSX);
  2101. if (tca) {
  2102. XMEMSET(tca, 0, sizeof(TCA));
  2103. tca->type = type;
  2104. switch (type) {
  2105. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2106. break;
  2107. #ifndef NO_SHA
  2108. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2109. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2110. if (idSz == WC_SHA_DIGEST_SIZE &&
  2111. (tca->id =
  2112. (byte*)XMALLOC(idSz, heap, DYNAMIC_TYPE_TLSX))) {
  2113. XMEMCPY(tca->id, id, idSz);
  2114. tca->idSz = idSz;
  2115. }
  2116. else {
  2117. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2118. tca = NULL;
  2119. }
  2120. break;
  2121. #endif
  2122. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2123. if (idSz > 0 &&
  2124. (tca->id =
  2125. (byte*)XMALLOC(idSz, heap, DYNAMIC_TYPE_TLSX))) {
  2126. XMEMCPY(tca->id, id, idSz);
  2127. tca->idSz = idSz;
  2128. }
  2129. else {
  2130. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2131. tca = NULL;
  2132. }
  2133. break;
  2134. default: /* invalid type */
  2135. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2136. tca = NULL;
  2137. }
  2138. }
  2139. (void)heap;
  2140. return tca;
  2141. }
  2142. /** Releases a TCA object. */
  2143. static void TLSX_TCA_Free(TCA* tca, void* heap)
  2144. {
  2145. (void)heap;
  2146. if (tca) {
  2147. if (tca->id)
  2148. XFREE(tca->id, heap, DYNAMIC_TYPE_TLSX);
  2149. XFREE(tca, heap, DYNAMIC_TYPE_TLSX);
  2150. }
  2151. }
  2152. /** Releases all TCA objects in the provided list. */
  2153. static void TLSX_TCA_FreeAll(TCA* list, void* heap)
  2154. {
  2155. TCA* tca;
  2156. while ((tca = list)) {
  2157. list = tca->next;
  2158. TLSX_TCA_Free(tca, heap);
  2159. }
  2160. }
  2161. /** Tells the buffered size of the TCA objects in a list. */
  2162. static word16 TLSX_TCA_GetSize(TCA* list)
  2163. {
  2164. TCA* tca;
  2165. word16 length = OPAQUE16_LEN; /* list length */
  2166. while ((tca = list)) {
  2167. list = tca->next;
  2168. length += ENUM_LEN; /* tca type */
  2169. switch (tca->type) {
  2170. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2171. break;
  2172. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2173. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2174. length += tca->idSz;
  2175. break;
  2176. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2177. length += OPAQUE16_LEN + tca->idSz;
  2178. break;
  2179. }
  2180. }
  2181. return length;
  2182. }
  2183. /** Writes the TCA objects of a list in a buffer. */
  2184. static word16 TLSX_TCA_Write(TCA* list, byte* output)
  2185. {
  2186. TCA* tca;
  2187. word16 offset = OPAQUE16_LEN; /* list length offset */
  2188. while ((tca = list)) {
  2189. list = tca->next;
  2190. output[offset++] = tca->type; /* tca type */
  2191. switch (tca->type) {
  2192. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2193. break;
  2194. #ifndef NO_SHA
  2195. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2196. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2197. if (tca->id != NULL) {
  2198. XMEMCPY(output + offset, tca->id, tca->idSz);
  2199. offset += tca->idSz;
  2200. }
  2201. else {
  2202. /* ID missing. Set to an empty string. */
  2203. c16toa(0, output + offset);
  2204. offset += OPAQUE16_LEN;
  2205. }
  2206. break;
  2207. #endif
  2208. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2209. if (tca->id != NULL) {
  2210. c16toa(tca->idSz, output + offset); /* tca length */
  2211. offset += OPAQUE16_LEN;
  2212. XMEMCPY(output + offset, tca->id, tca->idSz);
  2213. offset += tca->idSz;
  2214. }
  2215. else {
  2216. /* ID missing. Set to an empty string. */
  2217. c16toa(0, output + offset);
  2218. offset += OPAQUE16_LEN;
  2219. }
  2220. break;
  2221. default:
  2222. /* ID unknown. Set to an empty string. */
  2223. c16toa(0, output + offset);
  2224. offset += OPAQUE16_LEN;
  2225. }
  2226. }
  2227. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  2228. return offset;
  2229. }
  2230. #ifndef NO_WOLFSSL_SERVER
  2231. static TCA* TLSX_TCA_Find(TCA *list, byte type, const byte* id, word16 idSz)
  2232. {
  2233. TCA* tca = list;
  2234. while (tca && tca->type != type && type != WOLFSSL_TRUSTED_CA_PRE_AGREED &&
  2235. idSz != tca->idSz && !XMEMCMP(id, tca->id, idSz))
  2236. tca = tca->next;
  2237. return tca;
  2238. }
  2239. #endif /* NO_WOLFSSL_SERVER */
  2240. /** Parses a buffer of TCA extensions. */
  2241. static int TLSX_TCA_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2242. byte isRequest)
  2243. {
  2244. #ifndef NO_WOLFSSL_SERVER
  2245. word16 size = 0;
  2246. word16 offset = 0;
  2247. #endif
  2248. TLSX *extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS);
  2249. if (!extension)
  2250. extension = TLSX_Find(ssl->ctx->extensions, TLSX_TRUSTED_CA_KEYS);
  2251. if (!isRequest) {
  2252. #ifndef NO_WOLFSSL_CLIENT
  2253. if (!extension || !extension->data)
  2254. return TLSX_HandleUnsupportedExtension(ssl);
  2255. if (length > 0)
  2256. return BUFFER_ERROR; /* TCA response MUST be empty. */
  2257. /* Set the flag that we're good for keys */
  2258. TLSX_SetResponse(ssl, TLSX_TRUSTED_CA_KEYS);
  2259. return 0;
  2260. #endif
  2261. }
  2262. #ifndef NO_WOLFSSL_SERVER
  2263. if (!extension || !extension->data) {
  2264. /* Skipping, TCA not enabled at server side. */
  2265. return 0;
  2266. }
  2267. if (OPAQUE16_LEN > length)
  2268. return BUFFER_ERROR;
  2269. ato16(input, &size);
  2270. offset += OPAQUE16_LEN;
  2271. /* validating tca list length */
  2272. if (length != OPAQUE16_LEN + size)
  2273. return BUFFER_ERROR;
  2274. for (size = 0; offset < length; offset += size) {
  2275. TCA *tca = NULL;
  2276. byte type;
  2277. const byte* id = NULL;
  2278. word16 idSz = 0;
  2279. if (offset + ENUM_LEN > length)
  2280. return BUFFER_ERROR;
  2281. type = input[offset++];
  2282. switch (type) {
  2283. case WOLFSSL_TRUSTED_CA_PRE_AGREED:
  2284. break;
  2285. #ifndef NO_SHA
  2286. case WOLFSSL_TRUSTED_CA_KEY_SHA1:
  2287. case WOLFSSL_TRUSTED_CA_CERT_SHA1:
  2288. if (offset + WC_SHA_DIGEST_SIZE > length)
  2289. return BUFFER_ERROR;
  2290. idSz = WC_SHA_DIGEST_SIZE;
  2291. id = input + offset;
  2292. offset += idSz;
  2293. break;
  2294. #endif
  2295. case WOLFSSL_TRUSTED_CA_X509_NAME:
  2296. if (offset + OPAQUE16_LEN > length)
  2297. return BUFFER_ERROR;
  2298. ato16(input + offset, &idSz);
  2299. offset += OPAQUE16_LEN;
  2300. if ((offset > length) || (idSz > length - offset))
  2301. return BUFFER_ERROR;
  2302. id = input + offset;
  2303. offset += idSz;
  2304. break;
  2305. default:
  2306. WOLFSSL_ERROR_VERBOSE(TCA_INVALID_ID_TYPE);
  2307. return TCA_INVALID_ID_TYPE;
  2308. }
  2309. /* Find the type/ID in the TCA list. */
  2310. tca = TLSX_TCA_Find((TCA*)extension->data, type, id, idSz);
  2311. if (tca != NULL) {
  2312. /* Found it. Set the response flag and break out of the loop. */
  2313. TLSX_SetResponse(ssl, TLSX_TRUSTED_CA_KEYS);
  2314. break;
  2315. }
  2316. }
  2317. #else
  2318. (void)input;
  2319. #endif
  2320. return 0;
  2321. }
  2322. /* Checks to see if the server sent a response for the TCA. */
  2323. static int TLSX_TCA_VerifyParse(WOLFSSL* ssl, byte isRequest)
  2324. {
  2325. (void)ssl;
  2326. if (!isRequest) {
  2327. #ifndef NO_WOLFSSL_CLIENT
  2328. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_TRUSTED_CA_KEYS);
  2329. if (extension && !extension->resp) {
  2330. SendAlert(ssl, alert_fatal, handshake_failure);
  2331. WOLFSSL_ERROR_VERBOSE(TCA_ABSENT_ERROR);
  2332. return TCA_ABSENT_ERROR;
  2333. }
  2334. #endif /* NO_WOLFSSL_CLIENT */
  2335. }
  2336. return 0;
  2337. }
  2338. int TLSX_UseTrustedCA(TLSX** extensions, byte type,
  2339. const byte* id, word16 idSz, void* heap)
  2340. {
  2341. TLSX* extension;
  2342. TCA* tca = NULL;
  2343. if (extensions == NULL)
  2344. return BAD_FUNC_ARG;
  2345. if ((tca = TLSX_TCA_New(type, id, idSz, heap)) == NULL)
  2346. return MEMORY_E;
  2347. extension = TLSX_Find(*extensions, TLSX_TRUSTED_CA_KEYS);
  2348. if (!extension) {
  2349. int ret = TLSX_Push(extensions, TLSX_TRUSTED_CA_KEYS, (void*)tca, heap);
  2350. if (ret != 0) {
  2351. TLSX_TCA_Free(tca, heap);
  2352. return ret;
  2353. }
  2354. }
  2355. else {
  2356. /* push new TCA object to extension data. */
  2357. tca->next = (TCA*)extension->data;
  2358. extension->data = (void*)tca;
  2359. }
  2360. return WOLFSSL_SUCCESS;
  2361. }
  2362. #define TCA_FREE_ALL TLSX_TCA_FreeAll
  2363. #define TCA_GET_SIZE TLSX_TCA_GetSize
  2364. #define TCA_WRITE TLSX_TCA_Write
  2365. #define TCA_PARSE TLSX_TCA_Parse
  2366. #define TCA_VERIFY_PARSE TLSX_TCA_VerifyParse
  2367. #else /* HAVE_TRUSTED_CA */
  2368. #define TCA_FREE_ALL(list, heap)
  2369. #define TCA_GET_SIZE(list) 0
  2370. #define TCA_WRITE(a, b) 0
  2371. #define TCA_PARSE(a, b, c, d) 0
  2372. #define TCA_VERIFY_PARSE(a, b) 0
  2373. #endif /* HAVE_TRUSTED_CA */
  2374. /******************************************************************************/
  2375. /* Max Fragment Length Negotiation */
  2376. /******************************************************************************/
  2377. #ifdef HAVE_MAX_FRAGMENT
  2378. static word16 TLSX_MFL_Write(byte* data, byte* output)
  2379. {
  2380. output[0] = data[0];
  2381. return ENUM_LEN;
  2382. }
  2383. static int TLSX_MFL_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2384. byte isRequest)
  2385. {
  2386. if (length != ENUM_LEN)
  2387. return BUFFER_ERROR;
  2388. #ifdef WOLFSSL_OLD_UNSUPPORTED_EXTENSION
  2389. (void) isRequest;
  2390. #else
  2391. if (!isRequest)
  2392. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_MAX_FRAGMENT_LENGTH))
  2393. return TLSX_HandleUnsupportedExtension(ssl);
  2394. #endif
  2395. switch (*input) {
  2396. case WOLFSSL_MFL_2_8 : ssl->max_fragment = 256; break;
  2397. case WOLFSSL_MFL_2_9 : ssl->max_fragment = 512; break;
  2398. case WOLFSSL_MFL_2_10: ssl->max_fragment = 1024; break;
  2399. case WOLFSSL_MFL_2_11: ssl->max_fragment = 2048; break;
  2400. case WOLFSSL_MFL_2_12: ssl->max_fragment = 4096; break;
  2401. case WOLFSSL_MFL_2_13: ssl->max_fragment = 8192; break;
  2402. default:
  2403. SendAlert(ssl, alert_fatal, illegal_parameter);
  2404. WOLFSSL_ERROR_VERBOSE(UNKNOWN_MAX_FRAG_LEN_E);
  2405. return UNKNOWN_MAX_FRAG_LEN_E;
  2406. }
  2407. #ifndef NO_WOLFSSL_SERVER
  2408. if (isRequest) {
  2409. int ret = TLSX_UseMaxFragment(&ssl->extensions, *input, ssl->heap);
  2410. if (ret != WOLFSSL_SUCCESS)
  2411. return ret; /* throw error */
  2412. TLSX_SetResponse(ssl, TLSX_MAX_FRAGMENT_LENGTH);
  2413. }
  2414. #endif
  2415. return 0;
  2416. }
  2417. int TLSX_UseMaxFragment(TLSX** extensions, byte mfl, void* heap)
  2418. {
  2419. byte* data = NULL;
  2420. int ret = 0;
  2421. if (extensions == NULL || mfl < WOLFSSL_MFL_MIN || mfl > WOLFSSL_MFL_MAX)
  2422. return BAD_FUNC_ARG;
  2423. data = (byte*)XMALLOC(ENUM_LEN, heap, DYNAMIC_TYPE_TLSX);
  2424. if (data == NULL)
  2425. return MEMORY_E;
  2426. data[0] = mfl;
  2427. ret = TLSX_Push(extensions, TLSX_MAX_FRAGMENT_LENGTH, data, heap);
  2428. if (ret != 0) {
  2429. XFREE(data, heap, DYNAMIC_TYPE_TLSX);
  2430. return ret;
  2431. }
  2432. return WOLFSSL_SUCCESS;
  2433. }
  2434. #define MFL_FREE_ALL(data, heap) XFREE(data, (heap), DYNAMIC_TYPE_TLSX)
  2435. #define MFL_GET_SIZE(data) ENUM_LEN
  2436. #define MFL_WRITE TLSX_MFL_Write
  2437. #define MFL_PARSE TLSX_MFL_Parse
  2438. #else
  2439. #define MFL_FREE_ALL(a, b)
  2440. #define MFL_GET_SIZE(a) 0
  2441. #define MFL_WRITE(a, b) 0
  2442. #define MFL_PARSE(a, b, c, d) 0
  2443. #endif /* HAVE_MAX_FRAGMENT */
  2444. /******************************************************************************/
  2445. /* Truncated HMAC */
  2446. /******************************************************************************/
  2447. #ifdef HAVE_TRUNCATED_HMAC
  2448. static int TLSX_THM_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2449. byte isRequest)
  2450. {
  2451. if (length != 0 || input == NULL)
  2452. return BUFFER_ERROR;
  2453. if (!isRequest) {
  2454. #ifndef WOLFSSL_OLD_UNSUPPORTED_EXTENSION
  2455. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_TRUNCATED_HMAC))
  2456. return TLSX_HandleUnsupportedExtension(ssl);
  2457. #endif
  2458. }
  2459. else {
  2460. #ifndef NO_WOLFSSL_SERVER
  2461. int ret = TLSX_UseTruncatedHMAC(&ssl->extensions, ssl->heap);
  2462. if (ret != WOLFSSL_SUCCESS)
  2463. return ret; /* throw error */
  2464. TLSX_SetResponse(ssl, TLSX_TRUNCATED_HMAC);
  2465. #endif
  2466. }
  2467. ssl->truncated_hmac = 1;
  2468. return 0;
  2469. }
  2470. int TLSX_UseTruncatedHMAC(TLSX** extensions, void* heap)
  2471. {
  2472. int ret = 0;
  2473. if (extensions == NULL)
  2474. return BAD_FUNC_ARG;
  2475. ret = TLSX_Push(extensions, TLSX_TRUNCATED_HMAC, NULL, heap);
  2476. if (ret != 0)
  2477. return ret;
  2478. return WOLFSSL_SUCCESS;
  2479. }
  2480. #define THM_PARSE TLSX_THM_Parse
  2481. #else
  2482. #define THM_PARSE(a, b, c, d) 0
  2483. #endif /* HAVE_TRUNCATED_HMAC */
  2484. /******************************************************************************/
  2485. /* Certificate Status Request */
  2486. /******************************************************************************/
  2487. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  2488. static void TLSX_CSR_Free(CertificateStatusRequest* csr, void* heap)
  2489. {
  2490. switch (csr->status_type) {
  2491. case WOLFSSL_CSR_OCSP:
  2492. FreeOcspRequest(&csr->request.ocsp);
  2493. break;
  2494. }
  2495. #ifdef WOLFSSL_TLS13
  2496. if (csr->response.buffer != NULL) {
  2497. XFREE(csr->response.buffer, csr->ssl->heap,
  2498. DYNAMIC_TYPE_TMP_BUFFER);
  2499. }
  2500. #endif
  2501. XFREE(csr, heap, DYNAMIC_TYPE_TLSX);
  2502. (void)heap;
  2503. }
  2504. static word16 TLSX_CSR_GetSize(CertificateStatusRequest* csr, byte isRequest)
  2505. {
  2506. word16 size = 0;
  2507. /* shut up compiler warnings */
  2508. (void) csr; (void) isRequest;
  2509. #ifndef NO_WOLFSSL_CLIENT
  2510. if (isRequest) {
  2511. switch (csr->status_type) {
  2512. case WOLFSSL_CSR_OCSP:
  2513. size += ENUM_LEN + 2 * OPAQUE16_LEN;
  2514. if (csr->request.ocsp.nonceSz)
  2515. size += OCSP_NONCE_EXT_SZ;
  2516. break;
  2517. }
  2518. }
  2519. #endif
  2520. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  2521. if (!isRequest && csr->ssl->options.tls1_3)
  2522. return OPAQUE8_LEN + OPAQUE24_LEN + csr->response.length;
  2523. #endif
  2524. return size;
  2525. }
  2526. static word16 TLSX_CSR_Write(CertificateStatusRequest* csr, byte* output,
  2527. byte isRequest)
  2528. {
  2529. /* shut up compiler warnings */
  2530. (void) csr; (void) output; (void) isRequest;
  2531. #ifndef NO_WOLFSSL_CLIENT
  2532. if (isRequest) {
  2533. word16 offset = 0;
  2534. word16 length = 0;
  2535. /* type */
  2536. output[offset++] = csr->status_type;
  2537. switch (csr->status_type) {
  2538. case WOLFSSL_CSR_OCSP:
  2539. /* responder id list */
  2540. c16toa(0, output + offset);
  2541. offset += OPAQUE16_LEN;
  2542. /* request extensions */
  2543. if (csr->request.ocsp.nonceSz)
  2544. length = (word16)EncodeOcspRequestExtensions(
  2545. &csr->request.ocsp,
  2546. output + offset + OPAQUE16_LEN,
  2547. OCSP_NONCE_EXT_SZ);
  2548. c16toa(length, output + offset);
  2549. offset += OPAQUE16_LEN + length;
  2550. break;
  2551. }
  2552. return offset;
  2553. }
  2554. #endif
  2555. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  2556. if (!isRequest && csr->ssl->options.tls1_3) {
  2557. word16 offset = 0;
  2558. output[offset++] = csr->status_type;
  2559. c32to24(csr->response.length, output + offset);
  2560. offset += OPAQUE24_LEN;
  2561. XMEMCPY(output + offset, csr->response.buffer, csr->response.length);
  2562. offset += csr->response.length;
  2563. return offset;
  2564. }
  2565. #endif
  2566. return 0;
  2567. }
  2568. static int TLSX_CSR_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2569. byte isRequest)
  2570. {
  2571. int ret;
  2572. #if !defined(NO_WOLFSSL_SERVER)
  2573. byte status_type;
  2574. word16 size = 0;
  2575. #if defined(WOLFSSL_TLS13)
  2576. DecodedCert* cert;
  2577. #endif
  2578. #endif
  2579. #if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER) \
  2580. && defined(WOLFSSL_TLS13)
  2581. OcspRequest* request;
  2582. TLSX* extension;
  2583. CertificateStatusRequest* csr;
  2584. #endif
  2585. #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_TLS13) \
  2586. || !defined(NO_WOLFSSL_SERVER)
  2587. word32 offset = 0;
  2588. #endif
  2589. #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_TLS13)
  2590. word32 resp_length = 0;
  2591. #endif
  2592. /* shut up compiler warnings */
  2593. (void) ssl; (void) input;
  2594. if (!isRequest) {
  2595. #ifndef NO_WOLFSSL_CLIENT
  2596. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2597. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2598. if (!csr) {
  2599. /* look at context level */
  2600. extension = TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST);
  2601. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2602. if (!csr) /* unexpected extension */
  2603. return TLSX_HandleUnsupportedExtension(ssl);
  2604. /* enable extension at ssl level */
  2605. ret = TLSX_UseCertificateStatusRequest(&ssl->extensions,
  2606. csr->status_type, csr->options, ssl,
  2607. ssl->heap, ssl->devId);
  2608. if (ret != WOLFSSL_SUCCESS)
  2609. return ret == 0 ? -1 : ret;
  2610. switch (csr->status_type) {
  2611. case WOLFSSL_CSR_OCSP:
  2612. /* propagate nonce */
  2613. if (csr->request.ocsp.nonceSz) {
  2614. request =
  2615. (OcspRequest*)TLSX_CSR_GetRequest(ssl->extensions);
  2616. if (request) {
  2617. XMEMCPY(request->nonce, csr->request.ocsp.nonce,
  2618. csr->request.ocsp.nonceSz);
  2619. request->nonceSz = csr->request.ocsp.nonceSz;
  2620. }
  2621. }
  2622. break;
  2623. }
  2624. }
  2625. ssl->status_request = 1;
  2626. #ifdef WOLFSSL_TLS13
  2627. if (ssl->options.tls1_3) {
  2628. /* Get the new extension potentially created above. */
  2629. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2630. csr = extension ? (CertificateStatusRequest*)extension->data : NULL;
  2631. if (csr == NULL)
  2632. return MEMORY_ERROR;
  2633. ret = 0;
  2634. if (OPAQUE8_LEN + OPAQUE24_LEN > length)
  2635. ret = BUFFER_ERROR;
  2636. if (ret == 0 && input[offset++] != WOLFSSL_CSR_OCSP) {
  2637. ret = BAD_CERTIFICATE_STATUS_ERROR;
  2638. WOLFSSL_ERROR_VERBOSE(ret);
  2639. }
  2640. if (ret == 0) {
  2641. c24to32(input + offset, &resp_length);
  2642. offset += OPAQUE24_LEN;
  2643. if (offset + resp_length != length)
  2644. ret = BUFFER_ERROR;
  2645. }
  2646. if (ret == 0) {
  2647. csr->response.buffer = (byte*)XMALLOC(resp_length, ssl->heap,
  2648. DYNAMIC_TYPE_TMP_BUFFER);
  2649. if (csr->response.buffer == NULL)
  2650. ret = MEMORY_ERROR;
  2651. }
  2652. if (ret == 0) {
  2653. XMEMCPY(csr->response.buffer, input + offset, resp_length);
  2654. csr->response.length = resp_length;
  2655. }
  2656. return ret;
  2657. }
  2658. else
  2659. #endif
  2660. {
  2661. /* extension_data MUST be empty. */
  2662. return length ? BUFFER_ERROR : 0;
  2663. }
  2664. #endif
  2665. }
  2666. else {
  2667. #ifndef NO_WOLFSSL_SERVER
  2668. if (length == 0)
  2669. return 0;
  2670. status_type = input[offset++];
  2671. switch (status_type) {
  2672. case WOLFSSL_CSR_OCSP: {
  2673. /* skip responder_id_list */
  2674. if ((int)(length - offset) < OPAQUE16_LEN)
  2675. return BUFFER_ERROR;
  2676. ato16(input + offset, &size);
  2677. offset += OPAQUE16_LEN + size;
  2678. /* skip request_extensions */
  2679. if ((int)(length - offset) < OPAQUE16_LEN)
  2680. return BUFFER_ERROR;
  2681. ato16(input + offset, &size);
  2682. offset += OPAQUE16_LEN + size;
  2683. if (offset > length)
  2684. return BUFFER_ERROR;
  2685. /* is able to send OCSP response? */
  2686. if (SSL_CM(ssl) == NULL || !SSL_CM(ssl)->ocspStaplingEnabled)
  2687. return 0;
  2688. }
  2689. break;
  2690. /* unknown status type */
  2691. default:
  2692. return 0;
  2693. }
  2694. /* if using status_request and already sending it, skip this one */
  2695. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2696. if (ssl->status_request_v2)
  2697. return 0;
  2698. #endif
  2699. /* accept the first good status_type and return */
  2700. ret = TLSX_UseCertificateStatusRequest(&ssl->extensions, status_type,
  2701. 0, ssl, ssl->heap, ssl->devId);
  2702. if (ret != WOLFSSL_SUCCESS)
  2703. return ret == 0 ? -1 : ret; /* throw error */
  2704. #if defined(WOLFSSL_TLS13)
  2705. if (ssl->options.tls1_3) {
  2706. if (ssl->buffers.certificate == NULL) {
  2707. WOLFSSL_MSG("Certificate buffer not set!");
  2708. return BUFFER_ERROR;
  2709. }
  2710. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
  2711. DYNAMIC_TYPE_DCERT);
  2712. if (cert == NULL) {
  2713. return MEMORY_E;
  2714. }
  2715. InitDecodedCert(cert, ssl->buffers.certificate->buffer,
  2716. ssl->buffers.certificate->length, ssl->heap);
  2717. ret = ParseCert(cert, CERT_TYPE, 1, SSL_CM(ssl));
  2718. if (ret != 0 ) {
  2719. FreeDecodedCert(cert);
  2720. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2721. return ret;
  2722. }
  2723. ret = TLSX_CSR_InitRequest(ssl->extensions, cert, ssl->heap);
  2724. if (ret != 0 ) {
  2725. FreeDecodedCert(cert);
  2726. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2727. return ret;
  2728. }
  2729. FreeDecodedCert(cert);
  2730. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  2731. extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2732. csr = extension ?
  2733. (CertificateStatusRequest*)extension->data : NULL;
  2734. if (csr == NULL)
  2735. return MEMORY_ERROR;
  2736. request = &csr->request.ocsp;
  2737. ret = CreateOcspResponse(ssl, &request, &csr->response);
  2738. if (ret != 0)
  2739. return ret;
  2740. if (csr->response.buffer)
  2741. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST);
  2742. }
  2743. else
  2744. #endif
  2745. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST);
  2746. ssl->status_request = status_type;
  2747. #endif
  2748. }
  2749. return 0;
  2750. }
  2751. int TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert, void* heap)
  2752. {
  2753. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST);
  2754. CertificateStatusRequest* csr = extension ?
  2755. (CertificateStatusRequest*)extension->data : NULL;
  2756. int ret = 0;
  2757. if (csr) {
  2758. switch (csr->status_type) {
  2759. case WOLFSSL_CSR_OCSP: {
  2760. byte nonce[MAX_OCSP_NONCE_SZ];
  2761. int nonceSz = csr->request.ocsp.nonceSz;
  2762. /* preserve nonce */
  2763. XMEMCPY(nonce, csr->request.ocsp.nonce, nonceSz);
  2764. if ((ret = InitOcspRequest(&csr->request.ocsp, cert, 0, heap))
  2765. != 0)
  2766. return ret;
  2767. /* restore nonce */
  2768. XMEMCPY(csr->request.ocsp.nonce, nonce, nonceSz);
  2769. csr->request.ocsp.nonceSz = nonceSz;
  2770. }
  2771. break;
  2772. }
  2773. }
  2774. return ret;
  2775. }
  2776. void* TLSX_CSR_GetRequest(TLSX* extensions)
  2777. {
  2778. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST);
  2779. CertificateStatusRequest* csr = extension ?
  2780. (CertificateStatusRequest*)extension->data : NULL;
  2781. if (csr) {
  2782. switch (csr->status_type) {
  2783. case WOLFSSL_CSR_OCSP:
  2784. return &csr->request.ocsp;
  2785. }
  2786. }
  2787. return NULL;
  2788. }
  2789. int TLSX_CSR_ForceRequest(WOLFSSL* ssl)
  2790. {
  2791. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
  2792. CertificateStatusRequest* csr = extension ?
  2793. (CertificateStatusRequest*)extension->data : NULL;
  2794. if (csr) {
  2795. switch (csr->status_type) {
  2796. case WOLFSSL_CSR_OCSP:
  2797. if (SSL_CM(ssl)->ocspEnabled) {
  2798. csr->request.ocsp.ssl = ssl;
  2799. return CheckOcspRequest(SSL_CM(ssl)->ocsp,
  2800. &csr->request.ocsp, NULL, NULL);
  2801. }
  2802. else {
  2803. WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL);
  2804. return OCSP_LOOKUP_FAIL;
  2805. }
  2806. }
  2807. }
  2808. return 0;
  2809. }
  2810. int TLSX_UseCertificateStatusRequest(TLSX** extensions, byte status_type,
  2811. byte options, WOLFSSL* ssl, void* heap,
  2812. int devId)
  2813. {
  2814. CertificateStatusRequest* csr = NULL;
  2815. int ret = 0;
  2816. if (!extensions || status_type != WOLFSSL_CSR_OCSP)
  2817. return BAD_FUNC_ARG;
  2818. csr = (CertificateStatusRequest*)
  2819. XMALLOC(sizeof(CertificateStatusRequest), heap, DYNAMIC_TYPE_TLSX);
  2820. if (!csr)
  2821. return MEMORY_E;
  2822. ForceZero(csr, sizeof(CertificateStatusRequest));
  2823. csr->status_type = status_type;
  2824. csr->options = options;
  2825. csr->ssl = ssl;
  2826. switch (csr->status_type) {
  2827. case WOLFSSL_CSR_OCSP:
  2828. if (options & WOLFSSL_CSR_OCSP_USE_NONCE) {
  2829. WC_RNG rng;
  2830. #ifndef HAVE_FIPS
  2831. ret = wc_InitRng_ex(&rng, heap, devId);
  2832. #else
  2833. ret = wc_InitRng(&rng);
  2834. (void)devId;
  2835. #endif
  2836. if (ret == 0) {
  2837. if (wc_RNG_GenerateBlock(&rng, csr->request.ocsp.nonce,
  2838. MAX_OCSP_NONCE_SZ) == 0)
  2839. csr->request.ocsp.nonceSz = MAX_OCSP_NONCE_SZ;
  2840. wc_FreeRng(&rng);
  2841. }
  2842. }
  2843. break;
  2844. }
  2845. if ((ret = TLSX_Push(extensions, TLSX_STATUS_REQUEST, csr, heap)) != 0) {
  2846. XFREE(csr, heap, DYNAMIC_TYPE_TLSX);
  2847. return ret;
  2848. }
  2849. return WOLFSSL_SUCCESS;
  2850. }
  2851. #define CSR_FREE_ALL TLSX_CSR_Free
  2852. #define CSR_GET_SIZE TLSX_CSR_GetSize
  2853. #define CSR_WRITE TLSX_CSR_Write
  2854. #define CSR_PARSE TLSX_CSR_Parse
  2855. #else
  2856. #define CSR_FREE_ALL(data, heap)
  2857. #define CSR_GET_SIZE(a, b) 0
  2858. #define CSR_WRITE(a, b, c) 0
  2859. #define CSR_PARSE(a, b, c, d) 0
  2860. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
  2861. /******************************************************************************/
  2862. /* Certificate Status Request v2 */
  2863. /******************************************************************************/
  2864. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2865. static void TLSX_CSR2_FreeAll(CertificateStatusRequestItemV2* csr2, void* heap)
  2866. {
  2867. CertificateStatusRequestItemV2* next;
  2868. for (; csr2; csr2 = next) {
  2869. next = csr2->next;
  2870. switch (csr2->status_type) {
  2871. case WOLFSSL_CSR2_OCSP:
  2872. case WOLFSSL_CSR2_OCSP_MULTI:
  2873. while(csr2->requests--)
  2874. FreeOcspRequest(&csr2->request.ocsp[csr2->requests]);
  2875. break;
  2876. }
  2877. XFREE(csr2, heap, DYNAMIC_TYPE_TLSX);
  2878. }
  2879. (void)heap;
  2880. }
  2881. static word16 TLSX_CSR2_GetSize(CertificateStatusRequestItemV2* csr2,
  2882. byte isRequest)
  2883. {
  2884. word16 size = 0;
  2885. /* shut up compiler warnings */
  2886. (void) csr2; (void) isRequest;
  2887. #ifndef NO_WOLFSSL_CLIENT
  2888. if (isRequest) {
  2889. CertificateStatusRequestItemV2* next;
  2890. for (size = OPAQUE16_LEN; csr2; csr2 = next) {
  2891. next = csr2->next;
  2892. switch (csr2->status_type) {
  2893. case WOLFSSL_CSR2_OCSP:
  2894. case WOLFSSL_CSR2_OCSP_MULTI:
  2895. size += ENUM_LEN + 3 * OPAQUE16_LEN;
  2896. if (csr2->request.ocsp[0].nonceSz)
  2897. size += OCSP_NONCE_EXT_SZ;
  2898. break;
  2899. }
  2900. }
  2901. }
  2902. #endif
  2903. return size;
  2904. }
  2905. static word16 TLSX_CSR2_Write(CertificateStatusRequestItemV2* csr2,
  2906. byte* output, byte isRequest)
  2907. {
  2908. /* shut up compiler warnings */
  2909. (void) csr2; (void) output; (void) isRequest;
  2910. #ifndef NO_WOLFSSL_CLIENT
  2911. if (isRequest) {
  2912. word16 offset;
  2913. word16 length;
  2914. for (offset = OPAQUE16_LEN; csr2 != NULL; csr2 = csr2->next) {
  2915. /* status_type */
  2916. output[offset++] = csr2->status_type;
  2917. /* request */
  2918. switch (csr2->status_type) {
  2919. case WOLFSSL_CSR2_OCSP:
  2920. case WOLFSSL_CSR2_OCSP_MULTI:
  2921. /* request_length */
  2922. length = 2 * OPAQUE16_LEN;
  2923. if (csr2->request.ocsp[0].nonceSz)
  2924. length += OCSP_NONCE_EXT_SZ;
  2925. c16toa(length, output + offset);
  2926. offset += OPAQUE16_LEN;
  2927. /* responder id list */
  2928. c16toa(0, output + offset);
  2929. offset += OPAQUE16_LEN;
  2930. /* request extensions */
  2931. length = 0;
  2932. if (csr2->request.ocsp[0].nonceSz)
  2933. length = (word16)EncodeOcspRequestExtensions(
  2934. &csr2->request.ocsp[0],
  2935. output + offset + OPAQUE16_LEN,
  2936. OCSP_NONCE_EXT_SZ);
  2937. c16toa(length, output + offset);
  2938. offset += OPAQUE16_LEN + length;
  2939. break;
  2940. }
  2941. }
  2942. /* list size */
  2943. c16toa(offset - OPAQUE16_LEN, output);
  2944. return offset;
  2945. }
  2946. #endif
  2947. return 0;
  2948. }
  2949. static int TLSX_CSR2_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  2950. byte isRequest)
  2951. {
  2952. int ret;
  2953. /* shut up compiler warnings */
  2954. (void) ssl; (void) input;
  2955. if (!isRequest) {
  2956. #ifndef NO_WOLFSSL_CLIENT
  2957. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST_V2);
  2958. CertificateStatusRequestItemV2* csr2 = extension ?
  2959. (CertificateStatusRequestItemV2*)extension->data : NULL;
  2960. if (!csr2) {
  2961. /* look at context level */
  2962. extension = TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST_V2);
  2963. csr2 = extension ?
  2964. (CertificateStatusRequestItemV2*)extension->data : NULL;
  2965. if (!csr2) /* unexpected extension */
  2966. return TLSX_HandleUnsupportedExtension(ssl);
  2967. /* enable extension at ssl level */
  2968. for (; csr2; csr2 = csr2->next) {
  2969. ret = TLSX_UseCertificateStatusRequestV2(&ssl->extensions,
  2970. csr2->status_type, csr2->options, ssl->heap,
  2971. ssl->devId);
  2972. if (ret != WOLFSSL_SUCCESS)
  2973. return ret;
  2974. switch (csr2->status_type) {
  2975. case WOLFSSL_CSR2_OCSP:
  2976. /* followed by */
  2977. case WOLFSSL_CSR2_OCSP_MULTI:
  2978. /* propagate nonce */
  2979. if (csr2->request.ocsp[0].nonceSz) {
  2980. OcspRequest* request =
  2981. (OcspRequest*)TLSX_CSR2_GetRequest(ssl->extensions,
  2982. csr2->status_type, 0);
  2983. if (request) {
  2984. XMEMCPY(request->nonce,
  2985. csr2->request.ocsp[0].nonce,
  2986. csr2->request.ocsp[0].nonceSz);
  2987. request->nonceSz =
  2988. csr2->request.ocsp[0].nonceSz;
  2989. }
  2990. }
  2991. break;
  2992. }
  2993. }
  2994. }
  2995. ssl->status_request_v2 = 1;
  2996. return length ? BUFFER_ERROR : 0; /* extension_data MUST be empty. */
  2997. #endif
  2998. }
  2999. else {
  3000. #ifndef NO_WOLFSSL_SERVER
  3001. byte status_type;
  3002. word16 request_length;
  3003. word16 offset = 0;
  3004. word16 size = 0;
  3005. /* list size */
  3006. if (offset + OPAQUE16_LEN >= length) {
  3007. return BUFFER_E;
  3008. }
  3009. ato16(input + offset, &request_length);
  3010. offset += OPAQUE16_LEN;
  3011. if (length - OPAQUE16_LEN != request_length)
  3012. return BUFFER_ERROR;
  3013. while (length > offset) {
  3014. if ((int)(length - offset) < ENUM_LEN + OPAQUE16_LEN)
  3015. return BUFFER_ERROR;
  3016. status_type = input[offset++];
  3017. ato16(input + offset, &request_length);
  3018. offset += OPAQUE16_LEN;
  3019. if (length - offset < request_length)
  3020. return BUFFER_ERROR;
  3021. switch (status_type) {
  3022. case WOLFSSL_CSR2_OCSP:
  3023. case WOLFSSL_CSR2_OCSP_MULTI:
  3024. /* skip responder_id_list */
  3025. if ((int)(length - offset) < OPAQUE16_LEN)
  3026. return BUFFER_ERROR;
  3027. ato16(input + offset, &size);
  3028. if (length - offset < size)
  3029. return BUFFER_ERROR;
  3030. offset += OPAQUE16_LEN + size;
  3031. /* skip request_extensions */
  3032. if ((int)(length - offset) < OPAQUE16_LEN)
  3033. return BUFFER_ERROR;
  3034. ato16(input + offset, &size);
  3035. if (length - offset < size)
  3036. return BUFFER_ERROR;
  3037. offset += OPAQUE16_LEN + size;
  3038. if (offset > length)
  3039. return BUFFER_ERROR;
  3040. /* is able to send OCSP response? */
  3041. if (SSL_CM(ssl) == NULL
  3042. || !SSL_CM(ssl)->ocspStaplingEnabled)
  3043. continue;
  3044. break;
  3045. default:
  3046. /* unknown status type, skipping! */
  3047. offset += request_length;
  3048. continue;
  3049. }
  3050. /* if using status_request and already sending it, remove it
  3051. * and prefer to use the v2 version */
  3052. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  3053. if (ssl->status_request) {
  3054. ssl->status_request = 0;
  3055. TLSX_Remove(&ssl->extensions, TLSX_STATUS_REQUEST, ssl->heap);
  3056. }
  3057. #endif
  3058. /* TLS 1.3 servers MUST NOT act upon presence or information in
  3059. * this extension (RFC 8448 Section 4.4.2.1).
  3060. */
  3061. if (!IsAtLeastTLSv1_3(ssl->version)) {
  3062. /* accept the first good status_type and return */
  3063. ret = TLSX_UseCertificateStatusRequestV2(&ssl->extensions,
  3064. status_type, 0, ssl->heap, ssl->devId);
  3065. if (ret != WOLFSSL_SUCCESS)
  3066. return ret; /* throw error */
  3067. TLSX_SetResponse(ssl, TLSX_STATUS_REQUEST_V2);
  3068. ssl->status_request_v2 = status_type;
  3069. }
  3070. return 0;
  3071. }
  3072. #endif
  3073. }
  3074. return 0;
  3075. }
  3076. int TLSX_CSR2_InitRequests(TLSX* extensions, DecodedCert* cert, byte isPeer,
  3077. void* heap)
  3078. {
  3079. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2);
  3080. CertificateStatusRequestItemV2* csr2 = extension ?
  3081. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3082. int ret = 0;
  3083. for (; csr2; csr2 = csr2->next) {
  3084. switch (csr2->status_type) {
  3085. case WOLFSSL_CSR2_OCSP:
  3086. if (!isPeer || csr2->requests != 0)
  3087. break;
  3088. FALL_THROUGH; /* followed by */
  3089. case WOLFSSL_CSR2_OCSP_MULTI: {
  3090. if (csr2->requests < 1 + MAX_CHAIN_DEPTH) {
  3091. byte nonce[MAX_OCSP_NONCE_SZ];
  3092. int nonceSz = csr2->request.ocsp[0].nonceSz;
  3093. /* preserve nonce, replicating nonce of ocsp[0] */
  3094. XMEMCPY(nonce, csr2->request.ocsp[0].nonce, nonceSz);
  3095. if ((ret = InitOcspRequest(
  3096. &csr2->request.ocsp[csr2->requests], cert,
  3097. 0, heap)) != 0)
  3098. return ret;
  3099. /* restore nonce */
  3100. XMEMCPY(csr2->request.ocsp[csr2->requests].nonce,
  3101. nonce, nonceSz);
  3102. csr2->request.ocsp[csr2->requests].nonceSz = nonceSz;
  3103. csr2->requests++;
  3104. }
  3105. }
  3106. break;
  3107. }
  3108. }
  3109. (void)cert;
  3110. return ret;
  3111. }
  3112. void* TLSX_CSR2_GetRequest(TLSX* extensions, byte status_type, byte idx)
  3113. {
  3114. TLSX* extension = TLSX_Find(extensions, TLSX_STATUS_REQUEST_V2);
  3115. CertificateStatusRequestItemV2* csr2 = extension ?
  3116. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3117. for (; csr2; csr2 = csr2->next) {
  3118. if (csr2->status_type == status_type) {
  3119. switch (csr2->status_type) {
  3120. case WOLFSSL_CSR2_OCSP:
  3121. /* followed by */
  3122. case WOLFSSL_CSR2_OCSP_MULTI:
  3123. /* requests are initialized in the reverse order */
  3124. return idx < csr2->requests
  3125. ? &csr2->request.ocsp[csr2->requests - idx - 1]
  3126. : NULL;
  3127. }
  3128. }
  3129. }
  3130. return NULL;
  3131. }
  3132. int TLSX_CSR2_ForceRequest(WOLFSSL* ssl)
  3133. {
  3134. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST_V2);
  3135. CertificateStatusRequestItemV2* csr2 = extension ?
  3136. (CertificateStatusRequestItemV2*)extension->data : NULL;
  3137. /* forces only the first one */
  3138. if (csr2) {
  3139. switch (csr2->status_type) {
  3140. case WOLFSSL_CSR2_OCSP:
  3141. /* followed by */
  3142. case WOLFSSL_CSR2_OCSP_MULTI:
  3143. if (SSL_CM(ssl)->ocspEnabled) {
  3144. csr2->request.ocsp[0].ssl = ssl;
  3145. return CheckOcspRequest(SSL_CM(ssl)->ocsp,
  3146. &csr2->request.ocsp[0], NULL, NULL);
  3147. }
  3148. else {
  3149. WOLFSSL_ERROR_VERBOSE(OCSP_LOOKUP_FAIL);
  3150. return OCSP_LOOKUP_FAIL;
  3151. }
  3152. }
  3153. }
  3154. return 0;
  3155. }
  3156. int TLSX_UseCertificateStatusRequestV2(TLSX** extensions, byte status_type,
  3157. byte options, void* heap, int devId)
  3158. {
  3159. TLSX* extension = NULL;
  3160. CertificateStatusRequestItemV2* csr2 = NULL;
  3161. int ret = 0;
  3162. if (!extensions)
  3163. return BAD_FUNC_ARG;
  3164. if (status_type != WOLFSSL_CSR2_OCSP
  3165. && status_type != WOLFSSL_CSR2_OCSP_MULTI)
  3166. return BAD_FUNC_ARG;
  3167. csr2 = (CertificateStatusRequestItemV2*)
  3168. XMALLOC(sizeof(CertificateStatusRequestItemV2), heap, DYNAMIC_TYPE_TLSX);
  3169. if (!csr2)
  3170. return MEMORY_E;
  3171. ForceZero(csr2, sizeof(CertificateStatusRequestItemV2));
  3172. csr2->status_type = status_type;
  3173. csr2->options = options;
  3174. csr2->next = NULL;
  3175. switch (csr2->status_type) {
  3176. case WOLFSSL_CSR2_OCSP:
  3177. case WOLFSSL_CSR2_OCSP_MULTI:
  3178. if (options & WOLFSSL_CSR2_OCSP_USE_NONCE) {
  3179. WC_RNG rng;
  3180. #ifndef HAVE_FIPS
  3181. ret = wc_InitRng_ex(&rng, heap, devId);
  3182. #else
  3183. ret = wc_InitRng(&rng);
  3184. (void)devId;
  3185. #endif
  3186. if (ret == 0) {
  3187. if (wc_RNG_GenerateBlock(&rng, csr2->request.ocsp[0].nonce,
  3188. MAX_OCSP_NONCE_SZ) == 0)
  3189. csr2->request.ocsp[0].nonceSz = MAX_OCSP_NONCE_SZ;
  3190. wc_FreeRng(&rng);
  3191. }
  3192. }
  3193. break;
  3194. }
  3195. /* append new item */
  3196. if ((extension = TLSX_Find(*extensions, TLSX_STATUS_REQUEST_V2))) {
  3197. CertificateStatusRequestItemV2* last =
  3198. (CertificateStatusRequestItemV2*)extension->data;
  3199. for (; last->next; last = last->next);
  3200. last->next = csr2;
  3201. }
  3202. else if ((ret = TLSX_Push(extensions, TLSX_STATUS_REQUEST_V2, csr2,heap))) {
  3203. XFREE(csr2, heap, DYNAMIC_TYPE_TLSX);
  3204. return ret;
  3205. }
  3206. return WOLFSSL_SUCCESS;
  3207. }
  3208. #define CSR2_FREE_ALL TLSX_CSR2_FreeAll
  3209. #define CSR2_GET_SIZE TLSX_CSR2_GetSize
  3210. #define CSR2_WRITE TLSX_CSR2_Write
  3211. #define CSR2_PARSE TLSX_CSR2_Parse
  3212. #else
  3213. #define CSR2_FREE_ALL(data, heap)
  3214. #define CSR2_GET_SIZE(a, b) 0
  3215. #define CSR2_WRITE(a, b, c) 0
  3216. #define CSR2_PARSE(a, b, c, d) 0
  3217. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  3218. /******************************************************************************/
  3219. /* Supported Elliptic Curves */
  3220. /******************************************************************************/
  3221. #ifdef HAVE_SUPPORTED_CURVES
  3222. #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) \
  3223. && !defined(HAVE_FFDHE) && !defined(HAVE_PQC)
  3224. #error Elliptic Curves Extension requires Elliptic Curve Cryptography or liboqs groups. \
  3225. Use --enable-ecc and/or --enable-liboqs in the configure script or \
  3226. define HAVE_ECC. Alternatively use FFDHE for DH cipher suites.
  3227. #endif
  3228. static int TLSX_SupportedCurve_New(SupportedCurve** curve, word16 name,
  3229. void* heap)
  3230. {
  3231. if (curve == NULL)
  3232. return BAD_FUNC_ARG;
  3233. (void)heap;
  3234. *curve = (SupportedCurve*)XMALLOC(sizeof(SupportedCurve), heap,
  3235. DYNAMIC_TYPE_TLSX);
  3236. if (*curve == NULL)
  3237. return MEMORY_E;
  3238. (*curve)->name = name;
  3239. (*curve)->next = NULL;
  3240. return 0;
  3241. }
  3242. static int TLSX_PointFormat_New(PointFormat** point, byte format, void* heap)
  3243. {
  3244. if (point == NULL)
  3245. return BAD_FUNC_ARG;
  3246. (void)heap;
  3247. *point = (PointFormat*)XMALLOC(sizeof(PointFormat), heap,
  3248. DYNAMIC_TYPE_TLSX);
  3249. if (*point == NULL)
  3250. return MEMORY_E;
  3251. (*point)->format = format;
  3252. (*point)->next = NULL;
  3253. return 0;
  3254. }
  3255. static void TLSX_SupportedCurve_FreeAll(SupportedCurve* list, void* heap)
  3256. {
  3257. SupportedCurve* curve;
  3258. while ((curve = list)) {
  3259. list = curve->next;
  3260. XFREE(curve, heap, DYNAMIC_TYPE_TLSX);
  3261. }
  3262. (void)heap;
  3263. }
  3264. static void TLSX_PointFormat_FreeAll(PointFormat* list, void* heap)
  3265. {
  3266. PointFormat* point;
  3267. while ((point = list)) {
  3268. list = point->next;
  3269. XFREE(point, heap, DYNAMIC_TYPE_TLSX);
  3270. }
  3271. (void)heap;
  3272. }
  3273. static int TLSX_SupportedCurve_Append(SupportedCurve* list, word16 name,
  3274. void* heap)
  3275. {
  3276. int ret = BAD_FUNC_ARG;
  3277. while (list) {
  3278. if (list->name == name) {
  3279. ret = 0; /* curve already in use */
  3280. break;
  3281. }
  3282. if (list->next == NULL) {
  3283. ret = TLSX_SupportedCurve_New(&list->next, name, heap);
  3284. break;
  3285. }
  3286. list = list->next;
  3287. }
  3288. return ret;
  3289. }
  3290. static int TLSX_PointFormat_Append(PointFormat* list, byte format, void* heap)
  3291. {
  3292. int ret = BAD_FUNC_ARG;
  3293. while (list) {
  3294. if (list->format == format) {
  3295. ret = 0; /* format already in use */
  3296. break;
  3297. }
  3298. if (list->next == NULL) {
  3299. ret = TLSX_PointFormat_New(&list->next, format, heap);
  3300. break;
  3301. }
  3302. list = list->next;
  3303. }
  3304. return ret;
  3305. }
  3306. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  3307. #if defined(HAVE_FFDHE) && (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3308. defined(HAVE_CURVE448))
  3309. static void TLSX_SupportedCurve_ValidateRequest(const WOLFSSL* ssl,
  3310. const byte* semaphore)
  3311. {
  3312. /* If all pre-defined parameter types for key exchange are supported then
  3313. * always send SupportedGroups extension.
  3314. */
  3315. (void)ssl;
  3316. (void)semaphore;
  3317. }
  3318. #else
  3319. static void TLSX_SupportedCurve_ValidateRequest(WOLFSSL* ssl, byte* semaphore)
  3320. {
  3321. word16 i;
  3322. const Suites* suites = WOLFSSL_SUITES(ssl);
  3323. for (i = 0; i < suites->suiteSz; i += 2) {
  3324. if (suites->suites[i] == TLS13_BYTE)
  3325. return;
  3326. #ifdef BUILD_TLS_SM4_GCM_SM3
  3327. if ((suites->suites[i] == CIPHER_BYTE) &&
  3328. (suites->suites[i+1] == TLS_SM4_GCM_SM3))
  3329. return;
  3330. #endif
  3331. #ifdef BUILD_TLS_SM4_CCM_SM3
  3332. if ((suites->suites[i] == CIPHER_BYTE) &&
  3333. (suites->suites[i+1] == TLS_SM4_CCM_SM3))
  3334. return;
  3335. #endif
  3336. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3337. if ((suites->suites[i] == SM_BYTE) &&
  3338. (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3339. return;
  3340. #endif
  3341. if ((suites->suites[i] == ECC_BYTE) ||
  3342. (suites->suites[i] == ECDHE_PSK_BYTE) ||
  3343. (suites->suites[i] == CHACHA_BYTE)) {
  3344. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3345. defined(HAVE_CURVE448)
  3346. return;
  3347. #endif
  3348. }
  3349. #ifdef HAVE_FFDHE
  3350. else {
  3351. return;
  3352. }
  3353. #endif
  3354. }
  3355. /* turns semaphore on to avoid sending this extension. */
  3356. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_GROUPS));
  3357. }
  3358. #endif
  3359. /* Only send PointFormats if TLSv13, ECC or CHACHA cipher suite present.
  3360. */
  3361. static void TLSX_PointFormat_ValidateRequest(WOLFSSL* ssl, byte* semaphore)
  3362. {
  3363. #ifdef HAVE_FFDHE
  3364. (void)ssl;
  3365. (void)semaphore;
  3366. #else
  3367. word16 i;
  3368. const Suites* suites = WOLFSSL_SUITES(ssl);
  3369. if (suites == NULL)
  3370. return;
  3371. for (i = 0; i < suites->suiteSz; i += 2) {
  3372. if (suites->suites[i] == TLS13_BYTE)
  3373. return;
  3374. #ifdef BUILD_TLS_SM4_GCM_SM3
  3375. if ((suites->suites[i] == CIPHER_BYTE) &&
  3376. (suites->suites[i+1] == TLS_SM4_GCM_SM3))
  3377. return;
  3378. #endif
  3379. #ifdef BUILD_TLS_SM4_CCM_SM3
  3380. if ((suites->suites[i] == CIPHER_BYTE) &&
  3381. (suites->suites[i+1] == TLS_SM4_CCM_SM3))
  3382. return;
  3383. #endif
  3384. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3385. if ((suites->suites[i] == SM_BYTE) &&
  3386. (suites->suites[i+1] == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3387. return;
  3388. #endif
  3389. if ((suites->suites[i] == ECC_BYTE) ||
  3390. (suites->suites[i] == ECDHE_PSK_BYTE) ||
  3391. (suites->suites[i] == CHACHA_BYTE)) {
  3392. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3393. defined(HAVE_CURVE448)
  3394. return;
  3395. #endif
  3396. }
  3397. }
  3398. /* turns semaphore on to avoid sending this extension. */
  3399. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  3400. #endif
  3401. }
  3402. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  3403. #ifndef NO_WOLFSSL_SERVER
  3404. static void TLSX_PointFormat_ValidateResponse(WOLFSSL* ssl, byte* semaphore)
  3405. {
  3406. #if defined(HAVE_FFDHE) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3407. defined(HAVE_CURVE448)
  3408. (void)semaphore;
  3409. #endif
  3410. if (ssl->options.cipherSuite0 == TLS13_BYTE)
  3411. return;
  3412. #ifdef BUILD_TLS_SM4_GCM_SM3
  3413. if ((ssl->options.cipherSuite0 == CIPHER_BYTE) &&
  3414. (ssl->options.cipherSuite == TLS_SM4_GCM_SM3))
  3415. return;
  3416. #endif
  3417. #ifdef BUILD_TLS_SM4_CCM_SM3
  3418. if ((ssl->options.cipherSuite0 == CIPHER_BYTE) &&
  3419. (ssl->options.cipherSuite == TLS_SM4_CCM_SM3))
  3420. return;
  3421. #endif
  3422. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3423. if ((ssl->options.cipherSuite0 == SM_BYTE) &&
  3424. (ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3))
  3425. return;
  3426. #endif
  3427. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  3428. if (ssl->options.cipherSuite0 == ECC_BYTE ||
  3429. ssl->options.cipherSuite0 == ECDHE_PSK_BYTE ||
  3430. ssl->options.cipherSuite0 == CHACHA_BYTE) {
  3431. return;
  3432. }
  3433. #endif
  3434. /* turns semaphore on to avoid sending this extension. */
  3435. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  3436. }
  3437. #endif /* !NO_WOLFSSL_SERVER */
  3438. #ifndef NO_WOLFSSL_CLIENT
  3439. static word16 TLSX_SupportedCurve_GetSize(SupportedCurve* list)
  3440. {
  3441. SupportedCurve* curve;
  3442. word16 length = OPAQUE16_LEN; /* list length */
  3443. while ((curve = list)) {
  3444. list = curve->next;
  3445. length += OPAQUE16_LEN; /* curve length */
  3446. }
  3447. return length;
  3448. }
  3449. #endif
  3450. static word16 TLSX_PointFormat_GetSize(PointFormat* list)
  3451. {
  3452. PointFormat* point;
  3453. word16 length = ENUM_LEN; /* list length */
  3454. while ((point = list)) {
  3455. list = point->next;
  3456. length += ENUM_LEN; /* format length */
  3457. }
  3458. return length;
  3459. }
  3460. #ifndef NO_WOLFSSL_CLIENT
  3461. static word16 TLSX_SupportedCurve_Write(SupportedCurve* list, byte* output)
  3462. {
  3463. word16 offset = OPAQUE16_LEN;
  3464. while (list) {
  3465. c16toa(list->name, output + offset);
  3466. offset += OPAQUE16_LEN;
  3467. list = list->next;
  3468. }
  3469. c16toa(offset - OPAQUE16_LEN, output); /* writing list length */
  3470. return offset;
  3471. }
  3472. #endif
  3473. static word16 TLSX_PointFormat_Write(PointFormat* list, byte* output)
  3474. {
  3475. word16 offset = ENUM_LEN;
  3476. while (list) {
  3477. output[offset++] = list->format;
  3478. list = list->next;
  3479. }
  3480. output[0] = (byte)(offset - ENUM_LEN);
  3481. return offset;
  3482. }
  3483. #if !defined(NO_WOLFSSL_SERVER) || (defined(WOLFSSL_TLS13) && \
  3484. !defined(WOLFSSL_NO_SERVER_GROUPS_EXT))
  3485. int TLSX_SupportedCurve_Parse(const WOLFSSL* ssl, const byte* input,
  3486. word16 length, byte isRequest, TLSX** extensions)
  3487. {
  3488. word16 offset;
  3489. word16 name;
  3490. int ret;
  3491. if(!isRequest && !IsAtLeastTLSv1_3(ssl->version)) {
  3492. #ifdef WOLFSSL_ALLOW_SERVER_SC_EXT
  3493. return 0;
  3494. #else
  3495. return BUFFER_ERROR; /* servers doesn't send this extension. */
  3496. #endif
  3497. }
  3498. if (OPAQUE16_LEN > length || length % OPAQUE16_LEN)
  3499. return BUFFER_ERROR;
  3500. ato16(input, &offset);
  3501. /* validating curve list length */
  3502. if (length != OPAQUE16_LEN + offset)
  3503. return BUFFER_ERROR;
  3504. offset = OPAQUE16_LEN;
  3505. if (offset == length)
  3506. return 0;
  3507. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3508. if (!isRequest) {
  3509. TLSX* extension;
  3510. SupportedCurve* curve;
  3511. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  3512. if (extension != NULL) {
  3513. /* Replace client list with server list of supported groups. */
  3514. curve = (SupportedCurve*)extension->data;
  3515. extension->data = NULL;
  3516. TLSX_SupportedCurve_FreeAll(curve, ssl->heap);
  3517. ato16(input + offset, &name);
  3518. offset += OPAQUE16_LEN;
  3519. ret = TLSX_SupportedCurve_New(&curve, name, ssl->heap);
  3520. if (ret != 0)
  3521. return ret; /* throw error */
  3522. extension->data = (void*)curve;
  3523. }
  3524. }
  3525. #endif
  3526. for (; offset < length; offset += OPAQUE16_LEN) {
  3527. ato16(input + offset, &name);
  3528. ret = TLSX_UseSupportedCurve(extensions, name, ssl->heap);
  3529. /* If it is BAD_FUNC_ARG then it is a group we do not support, but
  3530. * that is fine. */
  3531. if (ret != WOLFSSL_SUCCESS && ret != BAD_FUNC_ARG) {
  3532. return ret;
  3533. }
  3534. }
  3535. return 0;
  3536. }
  3537. #endif
  3538. #if !defined(NO_WOLFSSL_SERVER)
  3539. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3540. /* Checks the priority of the groups on the server and set the supported groups
  3541. * response if there is a group not advertised by the client that is preferred.
  3542. *
  3543. * ssl SSL/TLS object.
  3544. * returns 0 on success, otherwise an error.
  3545. */
  3546. int TLSX_SupportedCurve_CheckPriority(WOLFSSL* ssl)
  3547. {
  3548. int ret;
  3549. TLSX* extension;
  3550. TLSX* priority = NULL;
  3551. TLSX* ext = NULL;
  3552. word16 name;
  3553. SupportedCurve* curve;
  3554. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3555. /* May be doing PSK with no key exchange. */
  3556. if (extension == NULL)
  3557. return 0;
  3558. ret = TLSX_PopulateSupportedGroups(ssl, &priority);
  3559. if (ret != WOLFSSL_SUCCESS) {
  3560. TLSX_FreeAll(priority, ssl->heap);
  3561. return ret;
  3562. }
  3563. ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS);
  3564. if (ext == NULL) {
  3565. WOLFSSL_MSG("Could not find supported groups extension");
  3566. TLSX_FreeAll(priority, ssl->heap);
  3567. return 0;
  3568. }
  3569. curve = (SupportedCurve*)ext->data;
  3570. name = curve->name;
  3571. curve = (SupportedCurve*)extension->data;
  3572. while (curve != NULL) {
  3573. if (curve->name == name)
  3574. break;
  3575. curve = curve->next;
  3576. }
  3577. if (curve == NULL) {
  3578. /* Couldn't find the preferred group in client list. */
  3579. extension->resp = 1;
  3580. /* Send server list back and free client list. */
  3581. curve = (SupportedCurve*)extension->data;
  3582. extension->data = ext->data;
  3583. ext->data = curve;
  3584. }
  3585. TLSX_FreeAll(priority, ssl->heap);
  3586. return 0;
  3587. }
  3588. #endif /* WOLFSSL_TLS13 && !WOLFSSL_NO_SERVER_GROUPS_EXT */
  3589. #if defined(HAVE_FFDHE) && !defined(WOLFSSL_NO_TLS12)
  3590. #ifdef HAVE_PUBLIC_FFDHE
  3591. static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup,
  3592. SupportedCurve* serverGroup)
  3593. {
  3594. int ret = 0;
  3595. SupportedCurve* group;
  3596. const DhParams* params = NULL;
  3597. for (; serverGroup != NULL; serverGroup = serverGroup->next) {
  3598. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name))
  3599. continue;
  3600. for (group = clientGroup; group != NULL; group = group->next) {
  3601. if (serverGroup->name != group->name)
  3602. continue;
  3603. switch (serverGroup->name) {
  3604. #ifdef HAVE_FFDHE_2048
  3605. case WOLFSSL_FFDHE_2048:
  3606. params = wc_Dh_ffdhe2048_Get();
  3607. break;
  3608. #endif
  3609. #ifdef HAVE_FFDHE_3072
  3610. case WOLFSSL_FFDHE_3072:
  3611. params = wc_Dh_ffdhe3072_Get();
  3612. break;
  3613. #endif
  3614. #ifdef HAVE_FFDHE_4096
  3615. case WOLFSSL_FFDHE_4096:
  3616. params = wc_Dh_ffdhe4096_Get();
  3617. break;
  3618. #endif
  3619. #ifdef HAVE_FFDHE_6144
  3620. case WOLFSSL_FFDHE_6144:
  3621. params = wc_Dh_ffdhe6144_Get();
  3622. break;
  3623. #endif
  3624. #ifdef HAVE_FFDHE_8192
  3625. case WOLFSSL_FFDHE_8192:
  3626. params = wc_Dh_ffdhe8192_Get();
  3627. break;
  3628. #endif
  3629. default:
  3630. break;
  3631. }
  3632. if (params == NULL) {
  3633. ret = BAD_FUNC_ARG;
  3634. break;
  3635. }
  3636. if (params->p_len >= ssl->options.minDhKeySz &&
  3637. params->p_len <= ssl->options.maxDhKeySz) {
  3638. break;
  3639. }
  3640. }
  3641. if (ret != 0)
  3642. break;
  3643. if ((group != NULL) && (serverGroup->name == group->name))
  3644. break;
  3645. }
  3646. if ((ret == 0) && (serverGroup != NULL) && (params != NULL)) {
  3647. ssl->buffers.serverDH_P.buffer = (unsigned char *)params->p;
  3648. ssl->buffers.serverDH_P.length = params->p_len;
  3649. ssl->buffers.serverDH_G.buffer = (unsigned char *)params->g;
  3650. ssl->buffers.serverDH_G.length = params->g_len;
  3651. ssl->namedGroup = serverGroup->name;
  3652. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  3653. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  3654. ssl->options.dhDoKeyTest = 0;
  3655. #endif
  3656. ssl->options.haveDH = 1;
  3657. }
  3658. return ret;
  3659. }
  3660. #else
  3661. static int tlsx_ffdhe_find_group(WOLFSSL* ssl, SupportedCurve* clientGroup,
  3662. SupportedCurve* serverGroup)
  3663. {
  3664. int ret = 0;
  3665. SupportedCurve* group;
  3666. word32 p_len;
  3667. for (; serverGroup != NULL; serverGroup = serverGroup->next) {
  3668. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(serverGroup->name))
  3669. continue;
  3670. for (group = clientGroup; group != NULL; group = group->next) {
  3671. if (serverGroup->name != group->name)
  3672. continue;
  3673. wc_DhGetNamedKeyParamSize(serverGroup->name, &p_len, NULL, NULL);
  3674. if (p_len == 0) {
  3675. ret = BAD_FUNC_ARG;
  3676. break;
  3677. }
  3678. if (p_len >= ssl->options.minDhKeySz &&
  3679. p_len <= ssl->options.maxDhKeySz) {
  3680. break;
  3681. }
  3682. }
  3683. if (ret != 0)
  3684. break;
  3685. if ((group != NULL) && (serverGroup->name == group->name))
  3686. break;
  3687. }
  3688. if ((ret == 0) && (serverGroup != NULL)) {
  3689. word32 pSz, gSz;
  3690. ssl->buffers.serverDH_P.buffer = NULL;
  3691. ssl->buffers.serverDH_G.buffer = NULL;
  3692. ret = wc_DhGetNamedKeyParamSize(serverGroup->name, &pSz, &gSz, NULL);
  3693. if (ret == 0) {
  3694. ssl->buffers.serverDH_P.buffer =
  3695. (byte*)XMALLOC(pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  3696. if (ssl->buffers.serverDH_P.buffer == NULL)
  3697. ret = MEMORY_E;
  3698. else
  3699. ssl->buffers.serverDH_P.length = pSz;
  3700. }
  3701. if (ret == 0) {
  3702. ssl->buffers.serverDH_G.buffer =
  3703. (byte*)XMALLOC(gSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  3704. if (ssl->buffers.serverDH_G.buffer == NULL) {
  3705. ret = MEMORY_E;
  3706. } else
  3707. ssl->buffers.serverDH_G.length = gSz;
  3708. }
  3709. if (ret == 0) {
  3710. ret = wc_DhCopyNamedKey(serverGroup->name,
  3711. ssl->buffers.serverDH_P.buffer, &pSz,
  3712. ssl->buffers.serverDH_G.buffer, &gSz,
  3713. NULL, NULL);
  3714. }
  3715. if (ret == 0) {
  3716. ssl->buffers.weOwnDH = 1;
  3717. ssl->namedGroup = serverGroup->name;
  3718. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  3719. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  3720. ssl->options.dhDoKeyTest = 0;
  3721. #endif
  3722. ssl->options.haveDH = 1;
  3723. }
  3724. else {
  3725. if (ssl->buffers.serverDH_P.buffer != NULL) {
  3726. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  3727. DYNAMIC_TYPE_PUBLIC_KEY);
  3728. ssl->buffers.serverDH_P.length = 0;
  3729. ssl->buffers.serverDH_P.buffer = NULL;
  3730. }
  3731. if (ssl->buffers.serverDH_G.buffer != NULL) {
  3732. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  3733. DYNAMIC_TYPE_PUBLIC_KEY);
  3734. ssl->buffers.serverDH_G.length = 0;
  3735. ssl->buffers.serverDH_G.buffer = NULL;
  3736. }
  3737. }
  3738. }
  3739. return ret;
  3740. }
  3741. #endif
  3742. /* Set the highest priority common FFDHE group on the server as compared to
  3743. * client extensions.
  3744. *
  3745. * ssl SSL/TLS object.
  3746. * returns 0 on success, otherwise an error.
  3747. */
  3748. int TLSX_SupportedFFDHE_Set(WOLFSSL* ssl)
  3749. {
  3750. int ret;
  3751. TLSX* priority = NULL;
  3752. TLSX* ext = NULL;
  3753. TLSX* extension;
  3754. SupportedCurve* clientGroup;
  3755. SupportedCurve* group;
  3756. int found = 0;
  3757. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3758. /* May be doing PSK with no key exchange. */
  3759. if (extension == NULL)
  3760. return 0;
  3761. clientGroup = (SupportedCurve*)extension->data;
  3762. for (group = clientGroup; group != NULL; group = group->next) {
  3763. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(group->name)) {
  3764. found = 1;
  3765. break;
  3766. }
  3767. }
  3768. if (!found)
  3769. return 0;
  3770. if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH) {
  3771. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  3772. DYNAMIC_TYPE_PUBLIC_KEY);
  3773. }
  3774. if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH) {
  3775. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  3776. DYNAMIC_TYPE_PUBLIC_KEY);
  3777. }
  3778. ssl->buffers.serverDH_P.buffer = NULL;
  3779. ssl->buffers.serverDH_G.buffer = NULL;
  3780. ssl->buffers.weOwnDH = 0;
  3781. ssl->options.haveDH = 0;
  3782. ret = TLSX_PopulateSupportedGroups(ssl, &priority);
  3783. if (ret == WOLFSSL_SUCCESS) {
  3784. SupportedCurve* serverGroup;
  3785. ext = TLSX_Find(priority, TLSX_SUPPORTED_GROUPS);
  3786. serverGroup = (SupportedCurve*)ext->data;
  3787. ret = tlsx_ffdhe_find_group(ssl, clientGroup, serverGroup);
  3788. }
  3789. TLSX_FreeAll(priority, ssl->heap);
  3790. return ret;
  3791. }
  3792. #endif /* HAVE_FFDHE && !WOLFSSL_NO_TLS12 */
  3793. #endif /* !NO_WOLFSSL_SERVER */
  3794. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
  3795. /* Return the preferred group.
  3796. *
  3797. * ssl SSL/TLS object.
  3798. * checkSupported Whether to check for the first supported group.
  3799. * returns BAD_FUNC_ARG if no group found, otherwise the group.
  3800. */
  3801. int TLSX_SupportedCurve_Preferred(WOLFSSL* ssl, int checkSupported)
  3802. {
  3803. TLSX* extension;
  3804. SupportedCurve* curve;
  3805. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3806. if (extension == NULL)
  3807. return BAD_FUNC_ARG;
  3808. curve = (SupportedCurve*)extension->data;
  3809. while (curve != NULL) {
  3810. if (!checkSupported || TLSX_KeyShare_IsSupported(curve->name))
  3811. return curve->name;
  3812. curve = curve->next;
  3813. }
  3814. return BAD_FUNC_ARG;
  3815. }
  3816. #endif /* HAVE_SUPPORTED_CURVES */
  3817. #ifndef NO_WOLFSSL_SERVER
  3818. static int TLSX_PointFormat_Parse(WOLFSSL* ssl, const byte* input,
  3819. word16 length, byte isRequest)
  3820. {
  3821. int ret;
  3822. /* validating formats list length */
  3823. if (ENUM_LEN > length || length != (word16)ENUM_LEN + input[0])
  3824. return BUFFER_ERROR;
  3825. if (isRequest) {
  3826. /* adding uncompressed point format to response */
  3827. ret = TLSX_UsePointFormat(&ssl->extensions, WOLFSSL_EC_PF_UNCOMPRESSED,
  3828. ssl->heap);
  3829. if (ret != WOLFSSL_SUCCESS)
  3830. return ret; /* throw error */
  3831. TLSX_SetResponse(ssl, TLSX_EC_POINT_FORMATS);
  3832. }
  3833. return 0;
  3834. }
  3835. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  3836. int TLSX_ValidateSupportedCurves(const WOLFSSL* ssl, byte first, byte second,
  3837. word32* ecdhCurveOID) {
  3838. TLSX* extension = NULL;
  3839. SupportedCurve* curve = NULL;
  3840. word32 oid = 0;
  3841. word32 defOid = 0;
  3842. word32 defSz = 80; /* Maximum known curve size is 66. */
  3843. word32 nextOid = 0;
  3844. word32 nextSz = 80; /* Maximum known curve size is 66. */
  3845. word32 currOid = ssl->ecdhCurveOID;
  3846. int ephmSuite = 0;
  3847. word16 octets = 0; /* according to 'ecc_set_type ecc_sets[];' */
  3848. int key = 0; /* validate key */
  3849. (void)oid;
  3850. if (first == CHACHA_BYTE) {
  3851. switch (second) {
  3852. case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
  3853. case TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3854. case TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3855. case TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256:
  3856. return 1; /* no suite restriction */
  3857. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
  3858. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256:
  3859. case TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
  3860. break;
  3861. }
  3862. }
  3863. if (first == ECC_BYTE || first == ECDHE_PSK_BYTE || first == CHACHA_BYTE)
  3864. extension = TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS);
  3865. if (!extension)
  3866. return 1; /* no suite restriction */
  3867. for (curve = (SupportedCurve*)extension->data;
  3868. curve && !key;
  3869. curve = curve->next) {
  3870. #ifdef OPENSSL_EXTRA
  3871. /* skip if name is not in supported ECC range
  3872. * or disabled by user */
  3873. if (curve->name > WOLFSSL_ECC_MAX ||
  3874. wolfSSL_curve_is_disabled(ssl, curve->name))
  3875. continue;
  3876. #endif
  3877. /* find supported curve */
  3878. switch (curve->name) {
  3879. #ifdef HAVE_ECC
  3880. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  3881. #ifndef NO_ECC_SECP
  3882. case WOLFSSL_ECC_SECP160R1:
  3883. oid = ECC_SECP160R1_OID;
  3884. octets = 20;
  3885. break;
  3886. #endif /* !NO_ECC_SECP */
  3887. #ifdef HAVE_ECC_SECPR2
  3888. case WOLFSSL_ECC_SECP160R2:
  3889. oid = ECC_SECP160R2_OID;
  3890. octets = 20;
  3891. break;
  3892. #endif /* HAVE_ECC_SECPR2 */
  3893. #ifdef HAVE_ECC_KOBLITZ
  3894. case WOLFSSL_ECC_SECP160K1:
  3895. oid = ECC_SECP160K1_OID;
  3896. octets = 20;
  3897. break;
  3898. #endif /* HAVE_ECC_KOBLITZ */
  3899. #endif
  3900. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  3901. #ifndef NO_ECC_SECP
  3902. case WOLFSSL_ECC_SECP192R1:
  3903. oid = ECC_SECP192R1_OID;
  3904. octets = 24;
  3905. break;
  3906. #endif /* !NO_ECC_SECP */
  3907. #ifdef HAVE_ECC_KOBLITZ
  3908. case WOLFSSL_ECC_SECP192K1:
  3909. oid = ECC_SECP192K1_OID;
  3910. octets = 24;
  3911. break;
  3912. #endif /* HAVE_ECC_KOBLITZ */
  3913. #endif
  3914. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  3915. #ifndef NO_ECC_SECP
  3916. case WOLFSSL_ECC_SECP224R1:
  3917. oid = ECC_SECP224R1_OID;
  3918. octets = 28;
  3919. break;
  3920. #endif /* !NO_ECC_SECP */
  3921. #ifdef HAVE_ECC_KOBLITZ
  3922. case WOLFSSL_ECC_SECP224K1:
  3923. oid = ECC_SECP224K1_OID;
  3924. octets = 28;
  3925. break;
  3926. #endif /* HAVE_ECC_KOBLITZ */
  3927. #endif
  3928. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  3929. #ifndef NO_ECC_SECP
  3930. case WOLFSSL_ECC_SECP256R1:
  3931. oid = ECC_SECP256R1_OID;
  3932. octets = 32;
  3933. break;
  3934. #endif /* !NO_ECC_SECP */
  3935. #endif /* !NO_ECC256 || HAVE_ALL_CURVES */
  3936. #endif
  3937. #if (defined(HAVE_CURVE25519) || defined(HAVE_ED25519)) && ECC_MIN_KEY_SZ <= 256
  3938. case WOLFSSL_ECC_X25519:
  3939. oid = ECC_X25519_OID;
  3940. octets = 32;
  3941. break;
  3942. #endif /* HAVE_CURVE25519 */
  3943. #ifdef HAVE_ECC
  3944. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  3945. #ifdef HAVE_ECC_KOBLITZ
  3946. case WOLFSSL_ECC_SECP256K1:
  3947. oid = ECC_SECP256K1_OID;
  3948. octets = 32;
  3949. break;
  3950. #endif /* HAVE_ECC_KOBLITZ */
  3951. #ifdef HAVE_ECC_BRAINPOOL
  3952. case WOLFSSL_ECC_BRAINPOOLP256R1:
  3953. oid = ECC_BRAINPOOLP256R1_OID;
  3954. octets = 32;
  3955. break;
  3956. #endif /* HAVE_ECC_BRAINPOOL */
  3957. #ifdef WOLFSSL_SM2
  3958. case WOLFSSL_ECC_SM2P256V1:
  3959. oid = ECC_SM2P256V1_OID;
  3960. octets = 32;
  3961. break;
  3962. #endif /* WOLFSSL_SM2 */
  3963. #endif
  3964. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  3965. #ifndef NO_ECC_SECP
  3966. case WOLFSSL_ECC_SECP384R1:
  3967. oid = ECC_SECP384R1_OID;
  3968. octets = 48;
  3969. break;
  3970. #endif /* !NO_ECC_SECP */
  3971. #ifdef HAVE_ECC_BRAINPOOL
  3972. case WOLFSSL_ECC_BRAINPOOLP384R1:
  3973. oid = ECC_BRAINPOOLP384R1_OID;
  3974. octets = 48;
  3975. break;
  3976. #endif /* HAVE_ECC_BRAINPOOL */
  3977. #endif
  3978. #endif
  3979. #if (defined(HAVE_CURVE448) || defined(HAVE_ED448)) && ECC_MIN_KEY_SZ <= 448
  3980. case WOLFSSL_ECC_X448:
  3981. oid = ECC_X448_OID;
  3982. octets = 57;
  3983. break;
  3984. #endif /* HAVE_CURVE448 */
  3985. #ifdef HAVE_ECC
  3986. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  3987. #ifdef HAVE_ECC_BRAINPOOL
  3988. case WOLFSSL_ECC_BRAINPOOLP512R1:
  3989. oid = ECC_BRAINPOOLP512R1_OID;
  3990. octets = 64;
  3991. break;
  3992. #endif /* HAVE_ECC_BRAINPOOL */
  3993. #endif
  3994. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  3995. #ifndef NO_ECC_SECP
  3996. case WOLFSSL_ECC_SECP521R1:
  3997. oid = ECC_SECP521R1_OID;
  3998. octets = 66;
  3999. break;
  4000. #endif /* !NO_ECC_SECP */
  4001. #endif
  4002. #endif
  4003. default: continue; /* unsupported curve */
  4004. }
  4005. #ifdef HAVE_ECC
  4006. /* Set default Oid */
  4007. if (defOid == 0 && ssl->eccTempKeySz <= octets && defSz > octets) {
  4008. defOid = oid;
  4009. defSz = octets;
  4010. }
  4011. /* The eccTempKeySz is the preferred ephemeral key size */
  4012. if (currOid == 0 && ssl->eccTempKeySz == octets)
  4013. currOid = oid;
  4014. if ((nextOid == 0 || nextSz > octets) && ssl->eccTempKeySz <= octets) {
  4015. nextOid = oid;
  4016. nextSz = octets;
  4017. }
  4018. #else
  4019. if (defOid == 0 && defSz > octets) {
  4020. defOid = oid;
  4021. defSz = octets;
  4022. }
  4023. if (currOid == 0)
  4024. currOid = oid;
  4025. if (nextOid == 0 || nextSz > octets) {
  4026. nextOid = oid;
  4027. nextSz = octets;
  4028. }
  4029. #endif
  4030. if (first == ECC_BYTE) {
  4031. switch (second) {
  4032. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  4033. /* ECDHE_ECDSA */
  4034. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
  4035. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
  4036. case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
  4037. case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
  4038. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
  4039. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
  4040. case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
  4041. case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
  4042. case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
  4043. case TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
  4044. key |= ssl->ecdhCurveOID == oid;
  4045. ephmSuite = 1;
  4046. break;
  4047. #ifdef WOLFSSL_STATIC_DH
  4048. /* ECDH_ECDSA */
  4049. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
  4050. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
  4051. case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
  4052. case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
  4053. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
  4054. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
  4055. case TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
  4056. case TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
  4057. if (oid == ECC_X25519_OID && defOid == oid) {
  4058. defOid = 0;
  4059. defSz = 80;
  4060. }
  4061. if (oid == ECC_X448_OID && defOid == oid) {
  4062. defOid = 0;
  4063. defSz = 80;
  4064. }
  4065. key |= ssl->pkCurveOID == oid;
  4066. break;
  4067. #endif /* WOLFSSL_STATIC_DH */
  4068. #endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  4069. #ifndef NO_RSA
  4070. /* ECDHE_RSA */
  4071. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
  4072. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
  4073. case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
  4074. case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
  4075. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
  4076. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
  4077. case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
  4078. case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
  4079. key |= ssl->ecdhCurveOID == oid;
  4080. ephmSuite = 1;
  4081. break;
  4082. #if defined(HAVE_ECC) && defined(WOLFSSL_STATIC_DH)
  4083. /* ECDH_RSA */
  4084. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
  4085. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
  4086. case TLS_ECDH_RSA_WITH_RC4_128_SHA:
  4087. case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
  4088. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
  4089. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
  4090. case TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
  4091. case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
  4092. if (oid == ECC_X25519_OID && defOid == oid) {
  4093. defOid = 0;
  4094. defSz = 80;
  4095. }
  4096. if (oid == ECC_X448_OID && defOid == oid) {
  4097. defOid = 0;
  4098. defSz = 80;
  4099. }
  4100. key |= ssl->pkCurveOID == oid;
  4101. break;
  4102. #endif /* HAVE_ECC && WOLFSSL_STATIC_DH */
  4103. #endif
  4104. default:
  4105. if (oid == ECC_X25519_OID && defOid == oid) {
  4106. defOid = 0;
  4107. defSz = 80;
  4108. }
  4109. if (oid == ECC_X448_OID && defOid == oid) {
  4110. defOid = 0;
  4111. defSz = 80;
  4112. }
  4113. key = 1;
  4114. break;
  4115. }
  4116. }
  4117. /* ChaCha20-Poly1305 ECC cipher suites */
  4118. if (first == CHACHA_BYTE) {
  4119. switch (second) {
  4120. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  4121. /* ECDHE_ECDSA */
  4122. case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 :
  4123. case TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  4124. key |= ssl->ecdhCurveOID == oid;
  4125. ephmSuite = 1;
  4126. break;
  4127. #endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  4128. #ifndef NO_RSA
  4129. /* ECDHE_RSA */
  4130. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 :
  4131. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  4132. key |= ssl->ecdhCurveOID == oid;
  4133. ephmSuite = 1;
  4134. break;
  4135. #endif
  4136. default:
  4137. key = 1;
  4138. break;
  4139. }
  4140. }
  4141. }
  4142. *ecdhCurveOID = ssl->ecdhCurveOID;
  4143. /* Choose the default if it is at the required strength. */
  4144. #ifdef HAVE_ECC
  4145. if (*ecdhCurveOID == 0 && defSz == ssl->eccTempKeySz)
  4146. #else
  4147. if (*ecdhCurveOID == 0)
  4148. #endif
  4149. {
  4150. key = 1;
  4151. *ecdhCurveOID = defOid;
  4152. }
  4153. /* Choose any curve at the required strength. */
  4154. if (*ecdhCurveOID == 0) {
  4155. key = 1;
  4156. *ecdhCurveOID = currOid;
  4157. }
  4158. /* Choose the default if it is at the next highest strength. */
  4159. if (*ecdhCurveOID == 0 && defSz == nextSz)
  4160. *ecdhCurveOID = defOid;
  4161. /* Choose any curve at the next highest strength. */
  4162. if (*ecdhCurveOID == 0)
  4163. *ecdhCurveOID = nextOid;
  4164. /* No curve and ephemeral ECC suite requires a matching curve. */
  4165. if (*ecdhCurveOID == 0 && ephmSuite)
  4166. key = 0;
  4167. return key;
  4168. }
  4169. #endif
  4170. #endif /* NO_WOLFSSL_SERVER */
  4171. int TLSX_SupportedCurve_Copy(TLSX* src, TLSX** dst, void* heap)
  4172. {
  4173. TLSX* extension;
  4174. int ret;
  4175. extension = TLSX_Find(src, TLSX_SUPPORTED_GROUPS);
  4176. if (extension != NULL) {
  4177. SupportedCurve* curve;
  4178. for (curve = (SupportedCurve*)extension->data; curve != NULL;
  4179. curve = curve->next) {
  4180. ret = TLSX_UseSupportedCurve(dst, curve->name, heap);
  4181. if (ret != WOLFSSL_SUCCESS)
  4182. return MEMORY_E;
  4183. }
  4184. }
  4185. return 0;
  4186. }
  4187. int TLSX_UseSupportedCurve(TLSX** extensions, word16 name, void* heap)
  4188. {
  4189. TLSX* extension = NULL;
  4190. SupportedCurve* curve = NULL;
  4191. int ret;
  4192. if (extensions == NULL) {
  4193. return BAD_FUNC_ARG;
  4194. }
  4195. #ifdef WOLFSSL_TLS13
  4196. if (! TLSX_KeyShare_IsSupported(name)) {
  4197. return BAD_FUNC_ARG;
  4198. }
  4199. #endif
  4200. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  4201. if (!extension) {
  4202. ret = TLSX_SupportedCurve_New(&curve, name, heap);
  4203. if (ret != 0)
  4204. return ret;
  4205. ret = TLSX_Push(extensions, TLSX_SUPPORTED_GROUPS, curve, heap);
  4206. if (ret != 0) {
  4207. XFREE(curve, heap, DYNAMIC_TYPE_TLSX);
  4208. return ret;
  4209. }
  4210. }
  4211. else {
  4212. ret = TLSX_SupportedCurve_Append((SupportedCurve*)extension->data, name,
  4213. heap);
  4214. if (ret != 0)
  4215. return ret;
  4216. }
  4217. return WOLFSSL_SUCCESS;
  4218. }
  4219. int TLSX_UsePointFormat(TLSX** extensions, byte format, void* heap)
  4220. {
  4221. TLSX* extension = NULL;
  4222. PointFormat* point = NULL;
  4223. int ret = 0;
  4224. if (extensions == NULL)
  4225. return BAD_FUNC_ARG;
  4226. extension = TLSX_Find(*extensions, TLSX_EC_POINT_FORMATS);
  4227. if (!extension) {
  4228. ret = TLSX_PointFormat_New(&point, format, heap);
  4229. if (ret != 0)
  4230. return ret;
  4231. ret = TLSX_Push(extensions, TLSX_EC_POINT_FORMATS, point, heap);
  4232. if (ret != 0) {
  4233. XFREE(point, heap, DYNAMIC_TYPE_TLSX);
  4234. return ret;
  4235. }
  4236. }
  4237. else {
  4238. ret = TLSX_PointFormat_Append((PointFormat*)extension->data, format,
  4239. heap);
  4240. if (ret != 0)
  4241. return ret;
  4242. }
  4243. return WOLFSSL_SUCCESS;
  4244. }
  4245. #define EC_FREE_ALL TLSX_SupportedCurve_FreeAll
  4246. #define EC_VALIDATE_REQUEST TLSX_SupportedCurve_ValidateRequest
  4247. #ifndef NO_WOLFSSL_CLIENT
  4248. #define EC_GET_SIZE TLSX_SupportedCurve_GetSize
  4249. #define EC_WRITE TLSX_SupportedCurve_Write
  4250. #else
  4251. #define EC_GET_SIZE(list) 0
  4252. #define EC_WRITE(a, b) 0
  4253. #endif
  4254. #if !defined(NO_WOLFSSL_SERVER) || (defined(WOLFSSL_TLS13) && \
  4255. !defined(WOLFSSL_NO_SERVER_GROUPS_EXT))
  4256. #define EC_PARSE TLSX_SupportedCurve_Parse
  4257. #else
  4258. #define EC_PARSE(a, b, c, d, e) 0
  4259. #endif
  4260. #define PF_FREE_ALL TLSX_PointFormat_FreeAll
  4261. #define PF_VALIDATE_REQUEST TLSX_PointFormat_ValidateRequest
  4262. #define PF_VALIDATE_RESPONSE TLSX_PointFormat_ValidateResponse
  4263. #define PF_GET_SIZE TLSX_PointFormat_GetSize
  4264. #define PF_WRITE TLSX_PointFormat_Write
  4265. #ifndef NO_WOLFSSL_SERVER
  4266. #define PF_PARSE TLSX_PointFormat_Parse
  4267. #else
  4268. #define PF_PARSE(a, b, c, d) 0
  4269. #endif
  4270. #else
  4271. #define EC_FREE_ALL(list, heap)
  4272. #define EC_GET_SIZE(list) 0
  4273. #define EC_WRITE(a, b) 0
  4274. #define EC_PARSE(a, b, c, d, e) 0
  4275. #define EC_VALIDATE_REQUEST(a, b)
  4276. #define PF_FREE_ALL(list, heap)
  4277. #define PF_GET_SIZE(list) 0
  4278. #define PF_WRITE(a, b) 0
  4279. #define PF_PARSE(a, b, c, d) 0
  4280. #define PF_VALIDATE_REQUEST(a, b)
  4281. #define PF_VALIDATE_RESPONSE(a, b)
  4282. #endif /* HAVE_SUPPORTED_CURVES */
  4283. /******************************************************************************/
  4284. /* Renegotiation Indication */
  4285. /******************************************************************************/
  4286. #if defined(HAVE_SECURE_RENEGOTIATION) \
  4287. || defined(HAVE_SERVER_RENEGOTIATION_INFO)
  4288. static byte TLSX_SecureRenegotiation_GetSize(SecureRenegotiation* data,
  4289. int isRequest)
  4290. {
  4291. byte length = OPAQUE8_LEN; /* empty info length */
  4292. /* data will be NULL for HAVE_SERVER_RENEGOTIATION_INFO only */
  4293. if (data && data->enabled && data->verifySet) {
  4294. /* client sends client_verify_data only */
  4295. length += TLS_FINISHED_SZ;
  4296. /* server also sends server_verify_data */
  4297. if (!isRequest)
  4298. length += TLS_FINISHED_SZ;
  4299. }
  4300. return length;
  4301. }
  4302. static word16 TLSX_SecureRenegotiation_Write(SecureRenegotiation* data,
  4303. byte* output, int isRequest)
  4304. {
  4305. word16 offset = OPAQUE8_LEN; /* RenegotiationInfo length */
  4306. if (data && data->enabled && data->verifySet) {
  4307. /* client sends client_verify_data only */
  4308. XMEMCPY(output + offset, data->client_verify_data, TLS_FINISHED_SZ);
  4309. offset += TLS_FINISHED_SZ;
  4310. /* server also sends server_verify_data */
  4311. if (!isRequest) {
  4312. XMEMCPY(output + offset, data->server_verify_data, TLS_FINISHED_SZ);
  4313. offset += TLS_FINISHED_SZ;
  4314. }
  4315. }
  4316. output[0] = (byte)(offset - 1); /* info length - self */
  4317. return offset;
  4318. }
  4319. static int TLSX_SecureRenegotiation_Parse(WOLFSSL* ssl, const byte* input,
  4320. word16 length, byte isRequest)
  4321. {
  4322. int ret = SECURE_RENEGOTIATION_E;
  4323. if (length >= OPAQUE8_LEN) {
  4324. if (isRequest) {
  4325. #ifndef NO_WOLFSSL_SERVER
  4326. if (ssl->secure_renegotiation == NULL) {
  4327. ret = wolfSSL_UseSecureRenegotiation(ssl);
  4328. if (ret == WOLFSSL_SUCCESS)
  4329. ret = 0;
  4330. }
  4331. if (ret != 0 && ret != SECURE_RENEGOTIATION_E) {
  4332. }
  4333. else if (ssl->secure_renegotiation == NULL) {
  4334. }
  4335. else if (!ssl->secure_renegotiation->enabled) {
  4336. if (*input == 0) {
  4337. input++; /* get past size */
  4338. ssl->secure_renegotiation->enabled = 1;
  4339. TLSX_SetResponse(ssl, TLSX_RENEGOTIATION_INFO);
  4340. ret = 0;
  4341. }
  4342. else {
  4343. /* already in error state */
  4344. WOLFSSL_MSG("SCR client verify data present");
  4345. }
  4346. }
  4347. else if (*input == TLS_FINISHED_SZ) {
  4348. if (length < TLS_FINISHED_SZ + 1) {
  4349. WOLFSSL_MSG("SCR malformed buffer");
  4350. ret = BUFFER_E;
  4351. }
  4352. else {
  4353. input++; /* get past size */
  4354. /* validate client verify data */
  4355. if (XMEMCMP(input,
  4356. ssl->secure_renegotiation->client_verify_data,
  4357. TLS_FINISHED_SZ) == 0) {
  4358. WOLFSSL_MSG("SCR client verify data match");
  4359. TLSX_SetResponse(ssl, TLSX_RENEGOTIATION_INFO);
  4360. ret = 0; /* verified */
  4361. }
  4362. else {
  4363. /* already in error state */
  4364. WOLFSSL_MSG("SCR client verify data Failure");
  4365. }
  4366. }
  4367. }
  4368. #endif
  4369. }
  4370. else if (ssl->secure_renegotiation != NULL) {
  4371. #ifndef NO_WOLFSSL_CLIENT
  4372. if (!ssl->secure_renegotiation->enabled) {
  4373. if (*input == 0) {
  4374. ssl->secure_renegotiation->enabled = 1;
  4375. ret = 0;
  4376. }
  4377. }
  4378. else if (*input == 2 * TLS_FINISHED_SZ &&
  4379. length == 2 * TLS_FINISHED_SZ + OPAQUE8_LEN) {
  4380. input++; /* get past size */
  4381. /* validate client and server verify data */
  4382. if (XMEMCMP(input,
  4383. ssl->secure_renegotiation->client_verify_data,
  4384. TLS_FINISHED_SZ) == 0 &&
  4385. XMEMCMP(input + TLS_FINISHED_SZ,
  4386. ssl->secure_renegotiation->server_verify_data,
  4387. TLS_FINISHED_SZ) == 0) {
  4388. WOLFSSL_MSG("SCR client and server verify data match");
  4389. ret = 0; /* verified */
  4390. }
  4391. else {
  4392. /* already in error state */
  4393. WOLFSSL_MSG("SCR client and server verify data Failure");
  4394. }
  4395. }
  4396. #endif
  4397. }
  4398. }
  4399. if (ret != 0) {
  4400. WOLFSSL_ERROR_VERBOSE(ret);
  4401. SendAlert(ssl, alert_fatal, handshake_failure);
  4402. }
  4403. return ret;
  4404. }
  4405. int TLSX_UseSecureRenegotiation(TLSX** extensions, void* heap)
  4406. {
  4407. int ret = 0;
  4408. SecureRenegotiation* data;
  4409. data = (SecureRenegotiation*)XMALLOC(sizeof(SecureRenegotiation), heap,
  4410. DYNAMIC_TYPE_TLSX);
  4411. if (data == NULL)
  4412. return MEMORY_E;
  4413. XMEMSET(data, 0, sizeof(SecureRenegotiation));
  4414. ret = TLSX_Push(extensions, TLSX_RENEGOTIATION_INFO, data, heap);
  4415. if (ret != 0) {
  4416. XFREE(data, heap, DYNAMIC_TYPE_TLSX);
  4417. return ret;
  4418. }
  4419. return WOLFSSL_SUCCESS;
  4420. }
  4421. #ifdef HAVE_SERVER_RENEGOTIATION_INFO
  4422. int TLSX_AddEmptyRenegotiationInfo(TLSX** extensions, void* heap)
  4423. {
  4424. int ret;
  4425. /* send empty renegotiation_info extension */
  4426. TLSX* ext = TLSX_Find(*extensions, TLSX_RENEGOTIATION_INFO);
  4427. if (ext == NULL) {
  4428. ret = TLSX_UseSecureRenegotiation(extensions, heap);
  4429. if (ret != WOLFSSL_SUCCESS)
  4430. return ret;
  4431. ext = TLSX_Find(*extensions, TLSX_RENEGOTIATION_INFO);
  4432. }
  4433. if (ext)
  4434. ext->resp = 1;
  4435. return WOLFSSL_SUCCESS;
  4436. }
  4437. #endif /* HAVE_SERVER_RENEGOTIATION_INFO */
  4438. #define SCR_FREE_ALL(data, heap) XFREE(data, (heap), DYNAMIC_TYPE_TLSX)
  4439. #define SCR_GET_SIZE TLSX_SecureRenegotiation_GetSize
  4440. #define SCR_WRITE TLSX_SecureRenegotiation_Write
  4441. #define SCR_PARSE TLSX_SecureRenegotiation_Parse
  4442. #else
  4443. #define SCR_FREE_ALL(a, heap)
  4444. #define SCR_GET_SIZE(a, b) 0
  4445. #define SCR_WRITE(a, b, c) 0
  4446. #define SCR_PARSE(a, b, c, d) 0
  4447. #endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
  4448. /******************************************************************************/
  4449. /* Session Tickets */
  4450. /******************************************************************************/
  4451. #ifdef HAVE_SESSION_TICKET
  4452. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  4453. static void TLSX_SessionTicket_ValidateRequest(WOLFSSL* ssl)
  4454. {
  4455. TLSX* extension = TLSX_Find(ssl->extensions, TLSX_SESSION_TICKET);
  4456. SessionTicket* ticket = extension ?
  4457. (SessionTicket*)extension->data : NULL;
  4458. if (ticket) {
  4459. /* TODO validate ticket timeout here! */
  4460. if (ticket->lifetime == 0xfffffff) {
  4461. /* send empty ticket on timeout */
  4462. TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4463. }
  4464. }
  4465. }
  4466. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  4467. static word16 TLSX_SessionTicket_GetSize(SessionTicket* ticket, int isRequest)
  4468. {
  4469. (void)isRequest;
  4470. return ticket ? ticket->size : 0;
  4471. }
  4472. static word16 TLSX_SessionTicket_Write(SessionTicket* ticket, byte* output,
  4473. int isRequest)
  4474. {
  4475. word16 offset = 0; /* empty ticket */
  4476. if (isRequest && ticket) {
  4477. XMEMCPY(output + offset, ticket->data, ticket->size);
  4478. offset += ticket->size;
  4479. }
  4480. return offset;
  4481. }
  4482. static int TLSX_SessionTicket_Parse(WOLFSSL* ssl, const byte* input,
  4483. word16 length, byte isRequest)
  4484. {
  4485. int ret = 0;
  4486. (void) input; /* avoid unused parameter if NO_WOLFSSL_SERVER defined */
  4487. if (!isRequest) {
  4488. if (TLSX_CheckUnsupportedExtension(ssl, TLSX_SESSION_TICKET))
  4489. return TLSX_HandleUnsupportedExtension(ssl);
  4490. if (length != 0)
  4491. return BUFFER_ERROR;
  4492. #ifndef NO_WOLFSSL_CLIENT
  4493. ssl->expect_session_ticket = 1;
  4494. #endif
  4495. }
  4496. #ifndef NO_WOLFSSL_SERVER
  4497. else {
  4498. /* server side */
  4499. if (ssl->ctx->ticketEncCb == NULL) {
  4500. WOLFSSL_MSG("Client sent session ticket, server has no callback");
  4501. return 0;
  4502. }
  4503. if (length > SESSION_TICKET_LEN) {
  4504. ret = BAD_TICKET_MSG_SZ;
  4505. WOLFSSL_ERROR_VERBOSE(ret);
  4506. } else if (IsAtLeastTLSv1_3(ssl->version)) {
  4507. WOLFSSL_MSG("Process client ticket rejected, TLS 1.3 no support");
  4508. ssl->options.rejectTicket = 1;
  4509. ret = 0; /* not fatal */
  4510. } else if (ssl->options.noTicketTls12) {
  4511. /* ignore ticket request */
  4512. } else if (length == 0) {
  4513. /* blank ticket */
  4514. ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4515. if (ret == WOLFSSL_SUCCESS) {
  4516. ret = 0;
  4517. /* send blank ticket */
  4518. TLSX_SetResponse(ssl, TLSX_SESSION_TICKET);
  4519. ssl->options.createTicket = 1; /* will send ticket msg */
  4520. ssl->options.useTicket = 1;
  4521. ssl->options.resuming = 0; /* no standard resumption */
  4522. ssl->arrays->sessionIDSz = 0; /* no echo on blank ticket */
  4523. }
  4524. } else {
  4525. /* got actual ticket from client */
  4526. ret = DoClientTicket(ssl, input, length);
  4527. if (ret == WOLFSSL_TICKET_RET_OK) { /* use ticket to resume */
  4528. WOLFSSL_MSG("Using existing client ticket");
  4529. ssl->options.useTicket = 1;
  4530. ssl->options.resuming = 1;
  4531. /* SERVER: ticket is peer auth. */
  4532. ssl->options.peerAuthGood = 1;
  4533. } else if (ret == WOLFSSL_TICKET_RET_CREATE) {
  4534. WOLFSSL_MSG("Using existing client ticket, creating new one");
  4535. ret = TLSX_UseSessionTicket(&ssl->extensions, NULL, ssl->heap);
  4536. if (ret == WOLFSSL_SUCCESS) {
  4537. ret = 0;
  4538. TLSX_SetResponse(ssl, TLSX_SESSION_TICKET);
  4539. /* send blank ticket */
  4540. ssl->options.createTicket = 1; /* will send ticket msg */
  4541. ssl->options.useTicket = 1;
  4542. ssl->options.resuming = 1;
  4543. /* SERVER: ticket is peer auth. */
  4544. ssl->options.peerAuthGood = 1;
  4545. }
  4546. } else if (ret == WOLFSSL_TICKET_RET_REJECT) {
  4547. WOLFSSL_MSG("Process client ticket rejected, not using");
  4548. ssl->options.rejectTicket = 1;
  4549. ret = 0; /* not fatal */
  4550. } else if (ret == VERSION_ERROR) {
  4551. WOLFSSL_MSG("Process client ticket rejected, bad TLS version");
  4552. ssl->options.rejectTicket = 1;
  4553. ret = 0; /* not fatal */
  4554. } else if (ret == WOLFSSL_TICKET_RET_FATAL) {
  4555. WOLFSSL_MSG("Process client ticket fatal error, not using");
  4556. } else if (ret < 0) {
  4557. WOLFSSL_MSG("Process client ticket unknown error, not using");
  4558. }
  4559. }
  4560. }
  4561. #endif /* NO_WOLFSSL_SERVER */
  4562. #if defined(NO_WOLFSSL_CLIENT) && defined(NO_WOLFSSL_SERVER)
  4563. (void)ssl;
  4564. #endif
  4565. return ret;
  4566. }
  4567. WOLFSSL_LOCAL SessionTicket* TLSX_SessionTicket_Create(word32 lifetime,
  4568. byte* data, word16 size, void* heap)
  4569. {
  4570. SessionTicket* ticket = (SessionTicket*)XMALLOC(sizeof(SessionTicket),
  4571. heap, DYNAMIC_TYPE_TLSX);
  4572. if (ticket) {
  4573. ticket->data = (byte*)XMALLOC(size, heap, DYNAMIC_TYPE_TLSX);
  4574. if (ticket->data == NULL) {
  4575. XFREE(ticket, heap, DYNAMIC_TYPE_TLSX);
  4576. return NULL;
  4577. }
  4578. XMEMCPY(ticket->data, data, size);
  4579. ticket->size = size;
  4580. ticket->lifetime = lifetime;
  4581. }
  4582. (void)heap;
  4583. return ticket;
  4584. }
  4585. WOLFSSL_LOCAL void TLSX_SessionTicket_Free(SessionTicket* ticket, void* heap)
  4586. {
  4587. if (ticket) {
  4588. XFREE(ticket->data, heap, DYNAMIC_TYPE_TLSX);
  4589. XFREE(ticket, heap, DYNAMIC_TYPE_TLSX);
  4590. }
  4591. (void)heap;
  4592. }
  4593. int TLSX_UseSessionTicket(TLSX** extensions, SessionTicket* ticket, void* heap)
  4594. {
  4595. int ret = 0;
  4596. if (extensions == NULL)
  4597. return BAD_FUNC_ARG;
  4598. /* If the ticket is NULL, the client will request a new ticket from the
  4599. server. Otherwise, the client will use it in the next client hello. */
  4600. if ((ret = TLSX_Push(extensions, TLSX_SESSION_TICKET, (void*)ticket, heap))
  4601. != 0)
  4602. return ret;
  4603. return WOLFSSL_SUCCESS;
  4604. }
  4605. #define WOLF_STK_VALIDATE_REQUEST TLSX_SessionTicket_ValidateRequest
  4606. #define WOLF_STK_GET_SIZE TLSX_SessionTicket_GetSize
  4607. #define WOLF_STK_WRITE TLSX_SessionTicket_Write
  4608. #define WOLF_STK_PARSE TLSX_SessionTicket_Parse
  4609. #define WOLF_STK_FREE(stk, heap) TLSX_SessionTicket_Free((SessionTicket*)(stk),(heap))
  4610. #else
  4611. #define WOLF_STK_FREE(a, b)
  4612. #define WOLF_STK_VALIDATE_REQUEST(a)
  4613. #define WOLF_STK_GET_SIZE(a, b) 0
  4614. #define WOLF_STK_WRITE(a, b, c) 0
  4615. #define WOLF_STK_PARSE(a, b, c, d) 0
  4616. #endif /* HAVE_SESSION_TICKET */
  4617. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  4618. /******************************************************************************/
  4619. /* Encrypt-then-MAC */
  4620. /******************************************************************************/
  4621. #ifndef WOLFSSL_NO_TLS12
  4622. static int TLSX_EncryptThenMac_Use(WOLFSSL* ssl);
  4623. /**
  4624. * Get the size of the Encrypt-Then-MAC extension.
  4625. *
  4626. * msgType Type of message to put extension into.
  4627. * pSz Size of extension data.
  4628. * return SANITY_MSG_E when the message is not allowed to have extension and
  4629. * 0 otherwise.
  4630. */
  4631. static int TLSX_EncryptThenMac_GetSize(byte msgType, word16* pSz)
  4632. {
  4633. (void)pSz;
  4634. if (msgType != client_hello && msgType != server_hello) {
  4635. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4636. return SANITY_MSG_E;
  4637. }
  4638. /* Empty extension */
  4639. return 0;
  4640. }
  4641. /**
  4642. * Write the Encrypt-Then-MAC extension.
  4643. *
  4644. * data Unused
  4645. * output Extension data buffer. Unused.
  4646. * msgType Type of message to put extension into.
  4647. * pSz Size of extension data.
  4648. * return SANITY_MSG_E when the message is not allowed to have extension and
  4649. * 0 otherwise.
  4650. */
  4651. static int TLSX_EncryptThenMac_Write(void* data, byte* output, byte msgType,
  4652. word16* pSz)
  4653. {
  4654. (void)data;
  4655. (void)output;
  4656. (void)pSz;
  4657. if (msgType != client_hello && msgType != server_hello) {
  4658. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4659. return SANITY_MSG_E;
  4660. }
  4661. /* Empty extension */
  4662. return 0;
  4663. }
  4664. /**
  4665. * Parse the Encrypt-Then-MAC extension.
  4666. *
  4667. * ssl SSL object
  4668. * input Extension data buffer.
  4669. * length Length of this extension's data.
  4670. * msgType Type of message to extension appeared in.
  4671. * return SANITY_MSG_E when the message is not allowed to have extension,
  4672. * BUFFER_ERROR when the extension's data is invalid,
  4673. * MEMORY_E when unable to allocate memory and
  4674. * 0 otherwise.
  4675. */
  4676. static int TLSX_EncryptThenMac_Parse(WOLFSSL* ssl, const byte* input,
  4677. word16 length, byte msgType)
  4678. {
  4679. int ret;
  4680. (void)input;
  4681. if (msgType != client_hello && msgType != server_hello) {
  4682. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4683. return SANITY_MSG_E;
  4684. }
  4685. /* Empty extension */
  4686. if (length != 0)
  4687. return BUFFER_ERROR;
  4688. if (msgType == client_hello) {
  4689. /* Check the user hasn't disallowed use of Encrypt-Then-Mac. */
  4690. if (!ssl->options.disallowEncThenMac) {
  4691. ssl->options.encThenMac = 1;
  4692. /* Set the extension reply. */
  4693. ret = TLSX_EncryptThenMac_Use(ssl);
  4694. if (ret != 0)
  4695. return ret;
  4696. }
  4697. return 0;
  4698. }
  4699. /* Server Hello */
  4700. if (ssl->options.disallowEncThenMac) {
  4701. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  4702. return SANITY_MSG_E;
  4703. }
  4704. ssl->options.encThenMac = 1;
  4705. return 0;
  4706. }
  4707. /**
  4708. * Add the Encrypt-Then-MAC extension to list.
  4709. *
  4710. * ssl SSL object
  4711. * return MEMORY_E when unable to allocate memory and 0 otherwise.
  4712. */
  4713. static int TLSX_EncryptThenMac_Use(WOLFSSL* ssl)
  4714. {
  4715. int ret = 0;
  4716. TLSX* extension;
  4717. /* Find the Encrypt-Then-Mac extension if it exists. */
  4718. extension = TLSX_Find(ssl->extensions, TLSX_ENCRYPT_THEN_MAC);
  4719. if (extension == NULL) {
  4720. /* Push new Encrypt-Then-Mac extension. */
  4721. ret = TLSX_Push(&ssl->extensions, TLSX_ENCRYPT_THEN_MAC, NULL,
  4722. ssl->heap);
  4723. if (ret != 0)
  4724. return ret;
  4725. }
  4726. return 0;
  4727. }
  4728. /**
  4729. * Set the Encrypt-Then-MAC extension as one to respond too.
  4730. *
  4731. * ssl SSL object
  4732. * return EXT_MISSING when EncryptThenMac extension not in list.
  4733. */
  4734. int TLSX_EncryptThenMac_Respond(WOLFSSL* ssl)
  4735. {
  4736. TLSX* extension;
  4737. extension = TLSX_Find(ssl->extensions, TLSX_ENCRYPT_THEN_MAC);
  4738. if (extension == NULL)
  4739. return EXT_MISSING;
  4740. extension->resp = 1;
  4741. return 0;
  4742. }
  4743. #define ETM_GET_SIZE TLSX_EncryptThenMac_GetSize
  4744. #define ETM_WRITE TLSX_EncryptThenMac_Write
  4745. #define ETM_PARSE TLSX_EncryptThenMac_Parse
  4746. #else
  4747. #define ETM_GET_SIZE(a, b) 0
  4748. #define ETM_WRITE(a, b, c, d) 0
  4749. #define ETM_PARSE(a, b, c, d) 0
  4750. #endif /* !WOLFSSL_NO_TLS12 */
  4751. #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */
  4752. #ifdef WOLFSSL_SRTP
  4753. /******************************************************************************/
  4754. /* DTLS SRTP (Secure Real-time Transport Protocol) */
  4755. /******************************************************************************/
  4756. /* Only support single SRTP profile */
  4757. typedef struct TlsxSrtp {
  4758. word16 profileCount;
  4759. word16 ids; /* selected bits */
  4760. } TlsxSrtp;
  4761. static int TLSX_UseSRTP_GetSize(TlsxSrtp *srtp)
  4762. {
  4763. /* SRTP Profile Len (2)
  4764. * SRTP Profiles (2)
  4765. * MKI (master key id) Length */
  4766. return (OPAQUE16_LEN + (srtp->profileCount * OPAQUE16_LEN) + 1);
  4767. }
  4768. static TlsxSrtp* TLSX_UseSRTP_New(word16 ids, void* heap)
  4769. {
  4770. TlsxSrtp* srtp;
  4771. int i;
  4772. srtp = (TlsxSrtp*)XMALLOC(sizeof(TlsxSrtp), heap, DYNAMIC_TYPE_TLSX);
  4773. if (srtp == NULL) {
  4774. WOLFSSL_MSG("TLSX SRTP Memory failure");
  4775. return NULL;
  4776. }
  4777. /* count and test each bit set */
  4778. srtp->profileCount = 0;
  4779. for (i=0; i<16; i++) {
  4780. if (ids & (1 << i)) {
  4781. srtp->profileCount++;
  4782. }
  4783. }
  4784. srtp->ids = ids;
  4785. return srtp;
  4786. }
  4787. static void TLSX_UseSRTP_Free(TlsxSrtp *srtp, void* heap)
  4788. {
  4789. if (srtp != NULL) {
  4790. XFREE(srtp, heap, DYNAMIC_TYPE_TLSX);
  4791. }
  4792. (void)heap;
  4793. }
  4794. static int TLSX_UseSRTP_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  4795. byte isRequest)
  4796. {
  4797. int ret = BAD_FUNC_ARG;
  4798. word16 profile_len = 0;
  4799. word16 profile_value = 0;
  4800. word16 offset = 0;
  4801. #ifndef NO_WOLFSSL_SERVER
  4802. int i;
  4803. TlsxSrtp* srtp = NULL;
  4804. #endif
  4805. if (length < OPAQUE16_LEN) {
  4806. return BUFFER_ERROR;
  4807. }
  4808. /* reset selected DTLS SRTP profile ID */
  4809. ssl->dtlsSrtpId = 0;
  4810. /* total length, not include itself */
  4811. ato16(input, &profile_len);
  4812. offset += OPAQUE16_LEN;
  4813. if (!isRequest) {
  4814. #ifndef NO_WOLFSSL_CLIENT
  4815. if (length < offset + OPAQUE16_LEN)
  4816. return BUFFER_ERROR;
  4817. ato16(input + offset, &profile_value);
  4818. /* check that the profile received was in the ones we support */
  4819. if (profile_value < 16 &&
  4820. (ssl->dtlsSrtpProfiles & (1 << profile_value))) {
  4821. ssl->dtlsSrtpId = profile_value;
  4822. ret = 0; /* success */
  4823. }
  4824. #endif
  4825. }
  4826. #ifndef NO_WOLFSSL_SERVER
  4827. else {
  4828. /* parse remainder one profile at a time, looking for match in CTX */
  4829. ret = 0;
  4830. for (i=offset; i<length; i+=OPAQUE16_LEN) {
  4831. ato16(input+i, &profile_value);
  4832. /* find first match */
  4833. if (profile_value < 16 &&
  4834. ssl->dtlsSrtpProfiles & (1 << profile_value)) {
  4835. ssl->dtlsSrtpId = profile_value;
  4836. /* make sure we respond with selected SRTP id selected */
  4837. srtp = TLSX_UseSRTP_New((1 << profile_value), ssl->heap);
  4838. if (srtp != NULL) {
  4839. ret = TLSX_Push(&ssl->extensions, TLSX_USE_SRTP,
  4840. (void*)srtp, ssl->heap);
  4841. if (ret == 0) {
  4842. TLSX_SetResponse(ssl, TLSX_USE_SRTP);
  4843. /* successfully set extension */
  4844. }
  4845. }
  4846. else {
  4847. ret = MEMORY_E;
  4848. }
  4849. break;
  4850. }
  4851. }
  4852. }
  4853. if (ret == 0 && ssl->dtlsSrtpId == 0) {
  4854. WOLFSSL_MSG("TLSX_UseSRTP_Parse profile not found!");
  4855. /* not fatal */
  4856. }
  4857. else if (ret != 0) {
  4858. ssl->dtlsSrtpId = 0;
  4859. TLSX_UseSRTP_Free(srtp, ssl->heap);
  4860. }
  4861. #endif
  4862. (void)profile_len;
  4863. return ret;
  4864. }
  4865. static word16 TLSX_UseSRTP_Write(TlsxSrtp* srtp, byte* output)
  4866. {
  4867. word16 offset = 0;
  4868. int i, j;
  4869. c16toa(srtp->profileCount * 2, output + offset);
  4870. offset += OPAQUE16_LEN;
  4871. j = 0;
  4872. for (i = 0; i < srtp->profileCount; i++) {
  4873. for (; j < 16; j++) {
  4874. if (srtp->ids & (1 << j)) {
  4875. c16toa(j, output + offset);
  4876. offset += OPAQUE16_LEN;
  4877. }
  4878. }
  4879. }
  4880. output[offset++] = 0x00; /* MKI Length */
  4881. return offset;
  4882. }
  4883. static int TLSX_UseSRTP(TLSX** extensions, word16 profiles, void* heap)
  4884. {
  4885. int ret = 0;
  4886. TLSX* extension;
  4887. if (extensions == NULL) {
  4888. return BAD_FUNC_ARG;
  4889. }
  4890. extension = TLSX_Find(*extensions, TLSX_USE_SRTP);
  4891. if (extension == NULL) {
  4892. TlsxSrtp* srtp = TLSX_UseSRTP_New(profiles, heap);
  4893. if (srtp == NULL) {
  4894. return MEMORY_E;
  4895. }
  4896. ret = TLSX_Push(extensions, TLSX_USE_SRTP, (void*)srtp, heap);
  4897. if (ret != 0) {
  4898. TLSX_UseSRTP_Free(srtp, heap);
  4899. }
  4900. }
  4901. return ret;
  4902. }
  4903. #ifndef NO_WOLFSSL_SERVER
  4904. #define SRTP_FREE TLSX_UseSRTP_Free
  4905. #define SRTP_PARSE TLSX_UseSRTP_Parse
  4906. #define SRTP_WRITE TLSX_UseSRTP_Write
  4907. #define SRTP_GET_SIZE TLSX_UseSRTP_GetSize
  4908. #else
  4909. #define SRTP_FREE(a, b)
  4910. #define SRTP_PARSE(a, b, c, d) 0
  4911. #define SRTP_WRITE(a, b) 0
  4912. #define SRTP_GET_SIZE(a) 0
  4913. #endif
  4914. #endif /* WOLFSSL_SRTP */
  4915. /******************************************************************************/
  4916. /* Supported Versions */
  4917. /******************************************************************************/
  4918. #ifdef WOLFSSL_TLS13
  4919. static WC_INLINE int versionIsGreater(byte isDtls, byte a, byte b)
  4920. {
  4921. (void)isDtls;
  4922. #ifdef WOLFSSL_DTLS
  4923. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4924. if (isDtls)
  4925. return a < b;
  4926. #endif /* WOLFSSL_DTLS */
  4927. return a > b;
  4928. }
  4929. static WC_INLINE int versionIsLesser(byte isDtls, byte a, byte b)
  4930. {
  4931. (void)isDtls;
  4932. #ifdef WOLFSSL_DTLS
  4933. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4934. if (isDtls)
  4935. return a > b;
  4936. #endif /* WOLFSSL_DTLS */
  4937. return a < b;
  4938. }
  4939. static WC_INLINE int versionIsAtLeast(byte isDtls, byte a, byte b)
  4940. {
  4941. (void)isDtls;
  4942. #ifdef WOLFSSL_DTLS
  4943. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4944. if (isDtls)
  4945. return a <= b;
  4946. #endif /* WOLFSSL_DTLS */
  4947. return a >= b;
  4948. }
  4949. static WC_INLINE int versionIsLessEqual(byte isDtls, byte a, byte b)
  4950. {
  4951. (void)isDtls;
  4952. #ifdef WOLFSSL_DTLS
  4953. /* DTLS version increases backwards (-1,-2,-3,etc) */
  4954. if (isDtls)
  4955. return a >= b;
  4956. #endif /* WOLFSSL_DTLS */
  4957. return a <= b;
  4958. }
  4959. /* Return the size of the SupportedVersions extension's data.
  4960. *
  4961. * data The SSL/TLS object.
  4962. * msgType The type of the message this extension is being written into.
  4963. * returns the length of data that will be in the extension.
  4964. */
  4965. static int TLSX_SupportedVersions_GetSize(void* data, byte msgType, word16* pSz)
  4966. {
  4967. WOLFSSL* ssl = (WOLFSSL*)data;
  4968. byte tls13Minor, tls12Minor, tls11Minor, isDtls;
  4969. isDtls = !!ssl->options.dtls;
  4970. tls13Minor = (byte)(isDtls ? DTLSv1_3_MINOR : TLSv1_3_MINOR);
  4971. tls12Minor = (byte)(isDtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR);
  4972. tls11Minor = (byte)(isDtls ? DTLS_MINOR : TLSv1_1_MINOR);
  4973. /* unused on some configuration */
  4974. (void)tls12Minor;
  4975. (void)tls13Minor;
  4976. (void)tls11Minor;
  4977. if (msgType == client_hello) {
  4978. /* TLS v1.2 and TLS v1.3 */
  4979. int cnt = 0;
  4980. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13Minor)
  4981. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  4982. defined(WOLFSSL_WPAS_SMALL)
  4983. && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0
  4984. #endif
  4985. ) {
  4986. cnt++;
  4987. }
  4988. if (ssl->options.downgrade) {
  4989. #ifndef WOLFSSL_NO_TLS12
  4990. if (versionIsLessEqual(
  4991. isDtls, ssl->options.minDowngrade, tls12Minor)
  4992. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  4993. defined(WOLFSSL_WPAS_SMALL)
  4994. && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0
  4995. #endif
  4996. ) {
  4997. cnt++;
  4998. }
  4999. #endif
  5000. #ifndef NO_OLD_TLS
  5001. if (versionIsLessEqual(
  5002. isDtls, ssl->options.minDowngrade, tls11Minor)
  5003. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5004. defined(WOLFSSL_WPAS_SMALL)
  5005. && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0
  5006. #endif
  5007. ) {
  5008. cnt++;
  5009. }
  5010. #ifdef WOLFSSL_ALLOW_TLSV10
  5011. if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR)
  5012. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5013. defined(WOLFSSL_WPAS_SMALL)
  5014. && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0
  5015. #endif
  5016. ) {
  5017. cnt++;
  5018. }
  5019. #endif
  5020. #endif
  5021. }
  5022. *pSz += (word16)(OPAQUE8_LEN + cnt * OPAQUE16_LEN);
  5023. }
  5024. else if (msgType == server_hello || msgType == hello_retry_request) {
  5025. *pSz += OPAQUE16_LEN;
  5026. }
  5027. else {
  5028. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5029. return SANITY_MSG_E;
  5030. }
  5031. return 0;
  5032. }
  5033. /* Writes the SupportedVersions extension into the buffer.
  5034. *
  5035. * data The SSL/TLS object.
  5036. * output The buffer to write the extension into.
  5037. * msgType The type of the message this extension is being written into.
  5038. * returns the length of data that was written.
  5039. */
  5040. static int TLSX_SupportedVersions_Write(void* data, byte* output,
  5041. byte msgType, word16* pSz)
  5042. {
  5043. WOLFSSL* ssl = (WOLFSSL*)data;
  5044. byte tls13minor, tls12minor, tls11minor, isDtls = 0;
  5045. tls13minor = (byte)TLSv1_3_MINOR;
  5046. tls12minor = (byte)TLSv1_2_MINOR;
  5047. tls11minor = (byte)TLSv1_1_MINOR;
  5048. /* unused in some configuration */
  5049. (void)tls11minor;
  5050. (void)tls12minor;
  5051. #ifdef WOLFSSL_DTLS13
  5052. if (ssl->options.dtls) {
  5053. tls13minor = (byte)DTLSv1_3_MINOR;
  5054. tls12minor = (byte)DTLSv1_2_MINOR;
  5055. tls11minor = (byte)DTLS_MINOR;
  5056. isDtls = 1;
  5057. }
  5058. #endif /* WOLFSSL_DTLS13 */
  5059. if (msgType == client_hello) {
  5060. byte major = ssl->ctx->method->version.major;
  5061. byte* cnt = output++;
  5062. *cnt = 0;
  5063. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls13minor)
  5064. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5065. defined(WOLFSSL_WPAS_SMALL)
  5066. && (ssl->options.mask & SSL_OP_NO_TLSv1_3) == 0
  5067. #endif
  5068. ) {
  5069. *cnt += OPAQUE16_LEN;
  5070. #ifdef WOLFSSL_TLS13_DRAFT
  5071. /* The TLS draft major number. */
  5072. *(output++) = TLS_DRAFT_MAJOR;
  5073. /* Version of draft supported. */
  5074. *(output++) = TLS_DRAFT_MINOR;
  5075. #else
  5076. *(output++) = major;
  5077. *(output++) = tls13minor;
  5078. #endif
  5079. }
  5080. if (ssl->options.downgrade) {
  5081. #ifndef WOLFSSL_NO_TLS12
  5082. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls12minor)
  5083. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5084. defined(WOLFSSL_WPAS_SMALL)
  5085. && (ssl->options.mask & SSL_OP_NO_TLSv1_2) == 0
  5086. #endif
  5087. ) {
  5088. *cnt += OPAQUE16_LEN;
  5089. *(output++) = major;
  5090. *(output++) = tls12minor;
  5091. }
  5092. #endif
  5093. #ifndef NO_OLD_TLS
  5094. if (versionIsLessEqual(isDtls, ssl->options.minDowngrade, tls11minor)
  5095. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5096. defined(WOLFSSL_WPAS_SMALL)
  5097. && (ssl->options.mask & SSL_OP_NO_TLSv1_1) == 0
  5098. #endif
  5099. ) {
  5100. *cnt += OPAQUE16_LEN;
  5101. *(output++) = major;
  5102. *(output++) = tls11minor;
  5103. }
  5104. #ifdef WOLFSSL_ALLOW_TLSV10
  5105. if (!ssl->options.dtls && (ssl->options.minDowngrade <= TLSv1_MINOR)
  5106. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  5107. defined(WOLFSSL_WPAS_SMALL)
  5108. && (ssl->options.mask & SSL_OP_NO_TLSv1) == 0
  5109. #endif
  5110. ) {
  5111. *cnt += OPAQUE16_LEN;
  5112. *(output++) = major;
  5113. *(output++) = (byte)TLSv1_MINOR;
  5114. }
  5115. #endif
  5116. #endif
  5117. }
  5118. *pSz += (word16)(OPAQUE8_LEN + *cnt);
  5119. }
  5120. else if (msgType == server_hello || msgType == hello_retry_request) {
  5121. output[0] = ssl->version.major;
  5122. output[1] = ssl->version.minor;
  5123. *pSz += OPAQUE16_LEN;
  5124. }
  5125. else {
  5126. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5127. return SANITY_MSG_E;
  5128. }
  5129. return 0;
  5130. }
  5131. /* Parse the SupportedVersions extension.
  5132. *
  5133. * ssl The SSL/TLS object.
  5134. * input The buffer with the extension data.
  5135. * length The length of the extension data.
  5136. * msgType The type of the message this extension is being parsed from.
  5137. * pv The output ProtocolVersion for the negotiated version
  5138. * opts The output options structure. Can be NULL.
  5139. * exts The output extensions list. Can be NULL.
  5140. * returns 0 on success, otherwise failure.
  5141. */
  5142. int TLSX_SupportedVersions_Parse(const WOLFSSL* ssl, const byte* input,
  5143. word16 length, byte msgType, ProtocolVersion* pv, Options* opts,
  5144. TLSX** exts)
  5145. {
  5146. /* The client's greatest minor version that we support */
  5147. byte clientGreatestMinor = SSLv3_MINOR;
  5148. int ret;
  5149. byte major, minor;
  5150. byte tls13minor, tls12minor;
  5151. byte isDtls;
  5152. tls13minor = TLSv1_3_MINOR;
  5153. tls12minor = TLSv1_2_MINOR;
  5154. isDtls = ssl->options.dtls == 1;
  5155. #ifdef WOLFSSL_DTLS13
  5156. if (ssl->options.dtls) {
  5157. tls13minor = DTLSv1_3_MINOR;
  5158. tls12minor = DTLSv1_2_MINOR;
  5159. clientGreatestMinor = DTLS_MINOR;
  5160. }
  5161. #endif /* WOLFSSL_DTLS13 */
  5162. if (msgType == client_hello) {
  5163. int i;
  5164. int len;
  5165. int set = 0;
  5166. /* Must contain a length and at least one version. */
  5167. if (length < OPAQUE8_LEN + OPAQUE16_LEN || (length & 1) != 1)
  5168. return BUFFER_ERROR;
  5169. len = *input;
  5170. /* Protocol version array must fill rest of data. */
  5171. if (length != (word16)OPAQUE8_LEN + len)
  5172. return BUFFER_ERROR;
  5173. input++;
  5174. /* Find first match. */
  5175. for (i = 0; i < len; i += OPAQUE16_LEN) {
  5176. major = input[i];
  5177. minor = input[i + OPAQUE8_LEN];
  5178. #ifdef WOLFSSL_TLS13_DRAFT
  5179. if (major == TLS_DRAFT_MAJOR && minor == TLS_DRAFT_MINOR) {
  5180. major = SSLv3_MAJOR;
  5181. minor = TLSv1_3_MINOR;
  5182. }
  5183. #else
  5184. if (major == TLS_DRAFT_MAJOR)
  5185. continue;
  5186. #endif
  5187. if (major != ssl->ctx->method->version.major)
  5188. continue;
  5189. /* No upgrade allowed. */
  5190. if (versionIsGreater(isDtls, minor, ssl->version.minor))
  5191. continue;
  5192. /* Check downgrade. */
  5193. if (versionIsLesser(isDtls, minor, ssl->version.minor)) {
  5194. if (!ssl->options.downgrade)
  5195. continue;
  5196. if (versionIsLesser(isDtls, minor, ssl->options.minDowngrade))
  5197. continue;
  5198. }
  5199. if (versionIsGreater(isDtls, minor, clientGreatestMinor))
  5200. clientGreatestMinor = minor;
  5201. set = 1;
  5202. }
  5203. if (!set) {
  5204. /* No common supported version was negotiated */
  5205. SendAlert((WOLFSSL*)ssl, alert_fatal,
  5206. wolfssl_alert_protocol_version);
  5207. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5208. return VERSION_ERROR;
  5209. }
  5210. pv->minor = clientGreatestMinor;
  5211. if (versionIsAtLeast(isDtls, clientGreatestMinor, tls13minor)) {
  5212. if (opts != NULL)
  5213. opts->tls1_3 = 1;
  5214. /* TLS v1.3 requires supported version extension */
  5215. if (exts != NULL &&
  5216. TLSX_Find(*exts, TLSX_SUPPORTED_VERSIONS) == NULL) {
  5217. ret = TLSX_Push(exts,
  5218. TLSX_SUPPORTED_VERSIONS, ssl, ssl->heap);
  5219. if (ret != 0) {
  5220. return ret;
  5221. }
  5222. /* *exts should be pointing to the TLSX_SUPPORTED_VERSIONS
  5223. * ext in the list since it was pushed. */
  5224. (*exts)->resp = 1;
  5225. }
  5226. }
  5227. }
  5228. else if (msgType == server_hello || msgType == hello_retry_request) {
  5229. /* Must contain one version. */
  5230. if (length != OPAQUE16_LEN)
  5231. return BUFFER_ERROR;
  5232. major = input[0];
  5233. minor = input[OPAQUE8_LEN];
  5234. if (major != ssl->ctx->method->version.major) {
  5235. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5236. return VERSION_ERROR;
  5237. }
  5238. /* Can't downgrade with this extension below TLS v1.3. */
  5239. if (versionIsLesser(isDtls, minor, tls13minor)) {
  5240. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5241. return VERSION_ERROR;
  5242. }
  5243. /* Version is TLS v1.2 to handle downgrading from TLS v1.3+. */
  5244. if (ssl->options.downgrade && ssl->version.minor == tls12minor) {
  5245. /* Set minor version back to TLS v1.3+ */
  5246. pv->minor = ssl->ctx->method->version.minor;
  5247. }
  5248. /* No upgrade allowed. */
  5249. if (versionIsLesser(isDtls, ssl->version.minor, minor)) {
  5250. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5251. return VERSION_ERROR;
  5252. }
  5253. /* Check downgrade. */
  5254. if (versionIsGreater(isDtls, ssl->version.minor, minor)) {
  5255. if (!ssl->options.downgrade) {
  5256. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5257. return VERSION_ERROR;
  5258. }
  5259. if (versionIsLesser(
  5260. isDtls, minor, ssl->options.minDowngrade)) {
  5261. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5262. return VERSION_ERROR;
  5263. }
  5264. /* Downgrade the version. */
  5265. pv->minor = minor;
  5266. }
  5267. }
  5268. else {
  5269. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5270. return SANITY_MSG_E;
  5271. }
  5272. return 0;
  5273. }
  5274. /* Sets a new SupportedVersions extension into the extension list.
  5275. *
  5276. * extensions The list of extensions.
  5277. * data The extensions specific data.
  5278. * heap The heap used for allocation.
  5279. * returns 0 on success, otherwise failure.
  5280. */
  5281. static int TLSX_SetSupportedVersions(TLSX** extensions, const void* data,
  5282. void* heap)
  5283. {
  5284. if (extensions == NULL || data == NULL)
  5285. return BAD_FUNC_ARG;
  5286. return TLSX_Push(extensions, TLSX_SUPPORTED_VERSIONS, data, heap);
  5287. }
  5288. #define SV_GET_SIZE TLSX_SupportedVersions_GetSize
  5289. #define SV_WRITE TLSX_SupportedVersions_Write
  5290. #define SV_PARSE TLSX_SupportedVersions_Parse
  5291. #else
  5292. #define SV_GET_SIZE(a, b, c) 0
  5293. #define SV_WRITE(a, b, c, d) 0
  5294. #define SV_PARSE(a, b, c, d, e, f, g) 0
  5295. #endif /* WOLFSSL_TLS13 */
  5296. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  5297. /******************************************************************************/
  5298. /* Cookie */
  5299. /******************************************************************************/
  5300. /* Free the cookie data.
  5301. *
  5302. * cookie Cookie data.
  5303. * heap The heap used for allocation.
  5304. */
  5305. static void TLSX_Cookie_FreeAll(Cookie* cookie, void* heap)
  5306. {
  5307. (void)heap;
  5308. if (cookie != NULL)
  5309. XFREE(cookie, heap, DYNAMIC_TYPE_TLSX);
  5310. }
  5311. /* Get the size of the encoded Cookie extension.
  5312. * In messages: ClientHello and HelloRetryRequest.
  5313. *
  5314. * cookie The cookie to write.
  5315. * msgType The type of the message this extension is being written into.
  5316. * returns the number of bytes of the encoded Cookie extension.
  5317. */
  5318. static int TLSX_Cookie_GetSize(Cookie* cookie, byte msgType, word16* pSz)
  5319. {
  5320. if (msgType == client_hello || msgType == hello_retry_request) {
  5321. *pSz += OPAQUE16_LEN + cookie->len;
  5322. }
  5323. else {
  5324. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5325. return SANITY_MSG_E;
  5326. }
  5327. return 0;
  5328. }
  5329. /* Writes the Cookie extension into the output buffer.
  5330. * Assumes that the the output buffer is big enough to hold data.
  5331. * In messages: ClientHello and HelloRetryRequest.
  5332. *
  5333. * cookie The cookie to write.
  5334. * output The buffer to write into.
  5335. * msgType The type of the message this extension is being written into.
  5336. * returns the number of bytes written into the buffer.
  5337. */
  5338. static int TLSX_Cookie_Write(Cookie* cookie, byte* output, byte msgType,
  5339. word16* pSz)
  5340. {
  5341. if (msgType == client_hello || msgType == hello_retry_request) {
  5342. c16toa(cookie->len, output);
  5343. output += OPAQUE16_LEN;
  5344. XMEMCPY(output, cookie->data, cookie->len);
  5345. *pSz += OPAQUE16_LEN + cookie->len;
  5346. }
  5347. else {
  5348. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5349. return SANITY_MSG_E;
  5350. }
  5351. return 0;
  5352. }
  5353. /* Parse the Cookie extension.
  5354. * In messages: ClientHello and HelloRetryRequest.
  5355. *
  5356. * ssl The SSL/TLS object.
  5357. * input The extension data.
  5358. * length The length of the extension data.
  5359. * msgType The type of the message this extension is being parsed from.
  5360. * returns 0 on success and other values indicate failure.
  5361. */
  5362. static int TLSX_Cookie_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  5363. byte msgType)
  5364. {
  5365. word16 len;
  5366. word16 idx = 0;
  5367. TLSX* extension;
  5368. Cookie* cookie;
  5369. if (msgType != client_hello && msgType != hello_retry_request) {
  5370. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  5371. return SANITY_MSG_E;
  5372. }
  5373. /* Message contains length and Cookie which must be at least one byte
  5374. * in length.
  5375. */
  5376. if (length < OPAQUE16_LEN + 1)
  5377. return BUFFER_E;
  5378. ato16(input + idx, &len);
  5379. idx += OPAQUE16_LEN;
  5380. if (length - idx != len)
  5381. return BUFFER_E;
  5382. if (msgType == hello_retry_request)
  5383. return TLSX_Cookie_Use(ssl, input + idx, len, NULL, 0, 0,
  5384. &ssl->extensions);
  5385. /* client_hello */
  5386. extension = TLSX_Find(ssl->extensions, TLSX_COOKIE);
  5387. if (extension == NULL) {
  5388. #ifdef WOLFSSL_DTLS13
  5389. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version))
  5390. /* Allow a cookie extension with DTLS 1.3 because it is possible
  5391. * that a different SSL instance sent the cookie but we are now
  5392. * receiving it. */
  5393. return TLSX_Cookie_Use(ssl, input + idx, len, NULL, 0, 0,
  5394. &ssl->extensions);
  5395. else
  5396. #endif
  5397. {
  5398. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  5399. return HRR_COOKIE_ERROR;
  5400. }
  5401. }
  5402. cookie = (Cookie*)extension->data;
  5403. if (cookie->len != len || XMEMCMP(cookie->data, input + idx, len) != 0) {
  5404. WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
  5405. return HRR_COOKIE_ERROR;
  5406. }
  5407. /* Request seen. */
  5408. extension->resp = 0;
  5409. return 0;
  5410. }
  5411. /* Use the data to create a new Cookie object in the extensions.
  5412. *
  5413. * ssl SSL/TLS object.
  5414. * data Cookie data.
  5415. * len Length of cookie data in bytes.
  5416. * mac MAC data.
  5417. * macSz Length of MAC data in bytes.
  5418. * resp Indicates the extension will go into a response (HelloRetryRequest).
  5419. * returns 0 on success and other values indicate failure.
  5420. */
  5421. int TLSX_Cookie_Use(const WOLFSSL* ssl, const byte* data, word16 len, byte* mac,
  5422. byte macSz, int resp, TLSX** exts)
  5423. {
  5424. int ret = 0;
  5425. TLSX* extension;
  5426. Cookie* cookie;
  5427. /* Find the cookie extension if it exists. */
  5428. extension = TLSX_Find(*exts, TLSX_COOKIE);
  5429. if (extension == NULL) {
  5430. /* Push new cookie extension. */
  5431. ret = TLSX_Push(exts, TLSX_COOKIE, NULL, ssl->heap);
  5432. if (ret != 0)
  5433. return ret;
  5434. extension = TLSX_Find(*exts, TLSX_COOKIE);
  5435. if (extension == NULL)
  5436. return MEMORY_E;
  5437. }
  5438. cookie = (Cookie*)XMALLOC(sizeof(Cookie) + len + macSz, ssl->heap,
  5439. DYNAMIC_TYPE_TLSX);
  5440. if (cookie == NULL)
  5441. return MEMORY_E;
  5442. cookie->len = len + macSz;
  5443. XMEMCPY(cookie->data, data, len);
  5444. if (mac != NULL)
  5445. XMEMCPY(cookie->data + len, mac, macSz);
  5446. if (extension->data != NULL)
  5447. XFREE(extension->data, ssl->heap, DYNAMIC_TYPE_TLSX);
  5448. extension->data = (void*)cookie;
  5449. extension->resp = (byte)resp;
  5450. return 0;
  5451. }
  5452. #define CKE_FREE_ALL TLSX_Cookie_FreeAll
  5453. #define CKE_GET_SIZE TLSX_Cookie_GetSize
  5454. #define CKE_WRITE TLSX_Cookie_Write
  5455. #define CKE_PARSE TLSX_Cookie_Parse
  5456. #else
  5457. #define CKE_FREE_ALL(a, b) 0
  5458. #define CKE_GET_SIZE(a, b, c) 0
  5459. #define CKE_WRITE(a, b, c, d) 0
  5460. #define CKE_PARSE(a, b, c, d) 0
  5461. #endif
  5462. #if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && \
  5463. !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA)
  5464. /* Currently only settable through compatibility API */
  5465. /******************************************************************************/
  5466. /* Certificate Authorities */
  5467. /******************************************************************************/
  5468. static word16 TLSX_CA_Names_GetSize(void* data)
  5469. {
  5470. WOLFSSL* ssl = (WOLFSSL*)data;
  5471. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  5472. word16 size = 0;
  5473. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5474. /* To add support use a different member like ssl->ca_names and
  5475. * add accessor functions:
  5476. * - *_set0_CA_list
  5477. * - *_get0_CA_list */
  5478. WOLFSSL_MSG("We don't currently support sending the client's list.");
  5479. return 0;
  5480. }
  5481. /* Length of names */
  5482. size += OPAQUE16_LEN;
  5483. for (names = SSL_CA_NAMES(ssl); names != NULL; names = names->next) {
  5484. byte seq[MAX_SEQ_SZ];
  5485. WOLFSSL_X509_NAME* name = names->data.name;
  5486. if (name != NULL) {
  5487. /* 16-bit length | SEQ | Len | DER of name */
  5488. size += (word16)(OPAQUE16_LEN + SetSequence(name->rawLen, seq) +
  5489. name->rawLen);
  5490. }
  5491. }
  5492. return size;
  5493. }
  5494. static word16 TLSX_CA_Names_Write(void* data, byte* output)
  5495. {
  5496. WOLFSSL* ssl = (WOLFSSL*)data;
  5497. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  5498. byte* len;
  5499. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5500. /* To add support use a different member like ssl->ca_names and
  5501. * add accessor functions:
  5502. * - *_set0_CA_list
  5503. * - *_get0_CA_list */
  5504. WOLFSSL_MSG("We don't currently support sending the client's list.");
  5505. return 0;
  5506. }
  5507. /* Reserve space for the length value */
  5508. len = output;
  5509. output += OPAQUE16_LEN;
  5510. for (names = SSL_CA_NAMES(ssl); names != NULL; names = names->next) {
  5511. byte seq[MAX_SEQ_SZ];
  5512. WOLFSSL_X509_NAME* name = names->data.name;
  5513. if (name != NULL) {
  5514. c16toa((word16)name->rawLen +
  5515. (word16)SetSequence(name->rawLen, seq), output);
  5516. output += OPAQUE16_LEN;
  5517. output += SetSequence(name->rawLen, output);
  5518. XMEMCPY(output, name->raw, name->rawLen);
  5519. output += name->rawLen;
  5520. }
  5521. }
  5522. /* Write the total length */
  5523. c16toa((word16)(output - len - OPAQUE16_LEN), len);
  5524. return (word16)(output - len);
  5525. }
  5526. static int TLSX_CA_Names_Parse(WOLFSSL *ssl, const byte* input,
  5527. word16 length, byte isRequest)
  5528. {
  5529. word16 extLen;
  5530. (void)isRequest;
  5531. if (ssl->options.side == WOLFSSL_SERVER_END) {
  5532. /* To add support use a different member like ssl->ca_names and
  5533. * add accessor functions:
  5534. * - *_set0_CA_list
  5535. * - *_get0_CA_list */
  5536. WOLFSSL_MSG("We don't currently support parsing the client's list.");
  5537. return 0;
  5538. }
  5539. if (ssl->client_ca_names != ssl->ctx->client_ca_names)
  5540. wolfSSL_sk_X509_NAME_pop_free(ssl->client_ca_names, NULL);
  5541. ssl->client_ca_names = wolfSSL_sk_X509_NAME_new(NULL);
  5542. if (ssl->client_ca_names == NULL)
  5543. return MEMORY_ERROR;
  5544. ato16(input, &extLen);
  5545. input += OPAQUE16_LEN;
  5546. length -= OPAQUE16_LEN;
  5547. if (extLen != length)
  5548. return BUFFER_ERROR;
  5549. while (length) {
  5550. word32 idx = 0;
  5551. WOLFSSL_X509_NAME* name = NULL;
  5552. int ret = 0;
  5553. /* Use a DecodedCert struct to get access to GetName to
  5554. * parse DN name */
  5555. #ifdef WOLFSSL_SMALL_STACK
  5556. DecodedCert *cert = (DecodedCert *)XMALLOC(
  5557. sizeof(*cert), ssl->heap, DYNAMIC_TYPE_DCERT);
  5558. if (cert == NULL)
  5559. return MEMORY_ERROR;
  5560. #else
  5561. DecodedCert cert[1];
  5562. #endif
  5563. ato16(input, &extLen);
  5564. idx += OPAQUE16_LEN;
  5565. if (extLen > length)
  5566. return BUFFER_ERROR;
  5567. InitDecodedCert(cert, input + idx, extLen, ssl->heap);
  5568. idx += extLen;
  5569. ret = GetName(cert, SUBJECT, extLen);
  5570. if (ret == 0 && (name = wolfSSL_X509_NAME_new()) == NULL)
  5571. ret = MEMORY_ERROR;
  5572. if (ret == 0)
  5573. CopyDecodedName(name, cert, SUBJECT);
  5574. if (ret == 0 && wolfSSL_sk_X509_NAME_push(ssl->client_ca_names, name)
  5575. == WOLFSSL_FAILURE)
  5576. ret = MEMORY_ERROR;
  5577. FreeDecodedCert(cert);
  5578. #ifdef WOLFSSL_SMALL_STACK
  5579. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  5580. #endif
  5581. if (ret != 0)
  5582. return ret;
  5583. input += idx;
  5584. length -= (word16)idx;
  5585. }
  5586. return 0;
  5587. }
  5588. #define CAN_GET_SIZE TLSX_CA_Names_GetSize
  5589. #define CAN_WRITE TLSX_CA_Names_Write
  5590. #define CAN_PARSE TLSX_CA_Names_Parse
  5591. #else
  5592. #define CAN_GET_SIZE(...) 0
  5593. #define CAN_WRITE(...) 0
  5594. #define CAN_PARSE(...) 0
  5595. #endif
  5596. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  5597. /******************************************************************************/
  5598. /* Signature Algorithms */
  5599. /******************************************************************************/
  5600. /* Return the size of the SignatureAlgorithms extension's data.
  5601. *
  5602. * data Unused
  5603. * returns the length of data that will be in the extension.
  5604. */
  5605. static word16 TLSX_SignatureAlgorithms_GetSize(void* data)
  5606. {
  5607. SignatureAlgorithms* sa = (SignatureAlgorithms*)data;
  5608. if (sa->hashSigAlgoSz == 0)
  5609. return OPAQUE16_LEN + WOLFSSL_SUITES(sa->ssl)->hashSigAlgoSz;
  5610. else
  5611. return OPAQUE16_LEN + sa->hashSigAlgoSz;
  5612. }
  5613. /* Creates a bit string of supported hash algorithms with RSA PSS.
  5614. * The bit string is used when determining which signature algorithm to use
  5615. * when creating the CertificateVerify message.
  5616. * Note: Valid data has an even length as each signature algorithm is two bytes.
  5617. *
  5618. * ssl The SSL/TLS object.
  5619. * input The buffer with the list of supported signature algorithms.
  5620. * length The length of the list in bytes.
  5621. * returns 0 on success, BUFFER_ERROR when the length is not even.
  5622. */
  5623. static int TLSX_SignatureAlgorithms_MapPss(WOLFSSL *ssl, const byte* input,
  5624. word16 length)
  5625. {
  5626. word16 i;
  5627. if ((length & 1) == 1)
  5628. return BUFFER_ERROR;
  5629. ssl->pssAlgo = 0;
  5630. for (i = 0; i < length; i += 2) {
  5631. if (input[i] == rsa_pss_sa_algo && input[i + 1] <= sha512_mac)
  5632. ssl->pssAlgo |= 1 << input[i + 1];
  5633. #ifdef WOLFSSL_TLS13
  5634. if (input[i] == rsa_pss_sa_algo && input[i + 1] >= pss_sha256 &&
  5635. input[i + 1] <= pss_sha512) {
  5636. ssl->pssAlgo |= 1 << input[i + 1];
  5637. }
  5638. #endif
  5639. }
  5640. return 0;
  5641. }
  5642. /* Writes the SignatureAlgorithms extension into the buffer.
  5643. *
  5644. * data Unused
  5645. * output The buffer to write the extension into.
  5646. * returns the length of data that was written.
  5647. */
  5648. static word16 TLSX_SignatureAlgorithms_Write(void* data, byte* output)
  5649. {
  5650. SignatureAlgorithms* sa = (SignatureAlgorithms*)data;
  5651. const Suites* suites = WOLFSSL_SUITES(sa->ssl);
  5652. word16 hashSigAlgoSz;
  5653. if (sa->hashSigAlgoSz == 0) {
  5654. c16toa(suites->hashSigAlgoSz, output);
  5655. XMEMCPY(output + OPAQUE16_LEN, suites->hashSigAlgo,
  5656. suites->hashSigAlgoSz);
  5657. hashSigAlgoSz = suites->hashSigAlgoSz;
  5658. }
  5659. else {
  5660. c16toa(sa->hashSigAlgoSz, output);
  5661. XMEMCPY(output + OPAQUE16_LEN, sa->hashSigAlgo,
  5662. sa->hashSigAlgoSz);
  5663. hashSigAlgoSz = sa->hashSigAlgoSz;
  5664. }
  5665. #ifndef NO_RSA
  5666. TLSX_SignatureAlgorithms_MapPss(sa->ssl, output + OPAQUE16_LEN,
  5667. hashSigAlgoSz);
  5668. #endif
  5669. return OPAQUE16_LEN + hashSigAlgoSz;
  5670. }
  5671. /* Parse the SignatureAlgorithms extension.
  5672. *
  5673. * ssl The SSL/TLS object.
  5674. * input The buffer with the extension data.
  5675. * length The length of the extension data.
  5676. * returns 0 on success, otherwise failure.
  5677. */
  5678. static int TLSX_SignatureAlgorithms_Parse(WOLFSSL *ssl, const byte* input,
  5679. word16 length, byte isRequest, Suites* suites)
  5680. {
  5681. word16 len;
  5682. if (!isRequest)
  5683. return BUFFER_ERROR;
  5684. /* Must contain a length and at least algorithm. */
  5685. if (length < OPAQUE16_LEN + OPAQUE16_LEN || (length & 1) != 0)
  5686. return BUFFER_ERROR;
  5687. ato16(input, &len);
  5688. input += OPAQUE16_LEN;
  5689. /* Algorithm array must fill rest of data. */
  5690. if (length != OPAQUE16_LEN + len)
  5691. return BUFFER_ERROR;
  5692. /* Sig Algo list size must be even. */
  5693. if (suites->hashSigAlgoSz % 2 != 0)
  5694. return BUFFER_ERROR;
  5695. /* truncate hashSigAlgo list if too long */
  5696. suites->hashSigAlgoSz = len;
  5697. if (suites->hashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  5698. WOLFSSL_MSG("TLSX SigAlgo list exceeds max, truncating");
  5699. suites->hashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  5700. }
  5701. XMEMCPY(suites->hashSigAlgo, input, suites->hashSigAlgoSz);
  5702. return TLSX_SignatureAlgorithms_MapPss(ssl, input, len);
  5703. }
  5704. /* Sets a new SignatureAlgorithms extension into the extension list.
  5705. *
  5706. * extensions The list of extensions.
  5707. * data The extensions specific data.
  5708. * heap The heap used for allocation.
  5709. * returns 0 on success, otherwise failure.
  5710. */
  5711. static int TLSX_SetSignatureAlgorithms(TLSX** extensions, WOLFSSL* ssl,
  5712. void* heap)
  5713. {
  5714. SignatureAlgorithms* sa;
  5715. int ret;
  5716. if (extensions == NULL)
  5717. return BAD_FUNC_ARG;
  5718. /* Already present */
  5719. if (TLSX_Find(*extensions, TLSX_SIGNATURE_ALGORITHMS) != NULL)
  5720. return 0;
  5721. sa = TLSX_SignatureAlgorithms_New(ssl, 0, heap);
  5722. if (sa == NULL)
  5723. return MEMORY_ERROR;
  5724. ret = TLSX_Push(extensions, TLSX_SIGNATURE_ALGORITHMS, sa, heap);
  5725. if (ret != 0)
  5726. TLSX_SignatureAlgorithms_FreeAll(sa, heap);
  5727. return ret;
  5728. }
  5729. SignatureAlgorithms* TLSX_SignatureAlgorithms_New(WOLFSSL* ssl,
  5730. word16 hashSigAlgoSz, void* heap)
  5731. {
  5732. SignatureAlgorithms* sa;
  5733. (void)heap;
  5734. sa = (SignatureAlgorithms*)XMALLOC(sizeof(*sa) + hashSigAlgoSz, heap,
  5735. DYNAMIC_TYPE_TLSX);
  5736. if (sa != NULL) {
  5737. XMEMSET(sa, 0, sizeof(*sa) + hashSigAlgoSz);
  5738. sa->ssl = ssl;
  5739. sa->hashSigAlgoSz = hashSigAlgoSz;
  5740. }
  5741. return sa;
  5742. }
  5743. void TLSX_SignatureAlgorithms_FreeAll(SignatureAlgorithms* sa,
  5744. void* heap)
  5745. {
  5746. XFREE(sa, heap, DYNAMIC_TYPE_TLSX);
  5747. (void)heap;
  5748. }
  5749. #define SA_GET_SIZE TLSX_SignatureAlgorithms_GetSize
  5750. #define SA_WRITE TLSX_SignatureAlgorithms_Write
  5751. #define SA_PARSE TLSX_SignatureAlgorithms_Parse
  5752. #define SA_FREE_ALL TLSX_SignatureAlgorithms_FreeAll
  5753. #endif
  5754. /******************************************************************************/
  5755. /* Signature Algorithms Certificate */
  5756. /******************************************************************************/
  5757. #if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  5758. /* Return the size of the SignatureAlgorithms extension's data.
  5759. *
  5760. * data Unused
  5761. * returns the length of data that will be in the extension.
  5762. */
  5763. static word16 TLSX_SignatureAlgorithmsCert_GetSize(void* data)
  5764. {
  5765. WOLFSSL* ssl = (WOLFSSL*)data;
  5766. return OPAQUE16_LEN + ssl->certHashSigAlgoSz;
  5767. }
  5768. /* Writes the SignatureAlgorithmsCert extension into the buffer.
  5769. *
  5770. * data Unused
  5771. * output The buffer to write the extension into.
  5772. * returns the length of data that was written.
  5773. */
  5774. static word16 TLSX_SignatureAlgorithmsCert_Write(void* data, byte* output)
  5775. {
  5776. WOLFSSL* ssl = (WOLFSSL*)data;
  5777. c16toa(ssl->certHashSigAlgoSz, output);
  5778. XMEMCPY(output + OPAQUE16_LEN, ssl->certHashSigAlgo,
  5779. ssl->certHashSigAlgoSz);
  5780. return OPAQUE16_LEN + ssl->certHashSigAlgoSz;
  5781. }
  5782. /* Parse the SignatureAlgorithmsCert extension.
  5783. *
  5784. * ssl The SSL/TLS object.
  5785. * input The buffer with the extension data.
  5786. * length The length of the extension data.
  5787. * returns 0 on success, otherwise failure.
  5788. */
  5789. static int TLSX_SignatureAlgorithmsCert_Parse(WOLFSSL *ssl, const byte* input,
  5790. word16 length, byte isRequest)
  5791. {
  5792. word16 len;
  5793. if (!isRequest)
  5794. return BUFFER_ERROR;
  5795. /* Must contain a length and at least algorithm. */
  5796. if (length < OPAQUE16_LEN + OPAQUE16_LEN || (length & 1) != 0)
  5797. return BUFFER_ERROR;
  5798. ato16(input, &len);
  5799. input += OPAQUE16_LEN;
  5800. /* Algorithm array must fill rest of data. */
  5801. if (length != OPAQUE16_LEN + len)
  5802. return BUFFER_ERROR;
  5803. /* truncate hashSigAlgo list if too long */
  5804. ssl->certHashSigAlgoSz = len;
  5805. if (ssl->certHashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  5806. WOLFSSL_MSG("TLSX SigAlgo list exceeds max, truncating");
  5807. ssl->certHashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  5808. }
  5809. XMEMCPY(ssl->certHashSigAlgo, input, ssl->certHashSigAlgoSz);
  5810. return 0;
  5811. }
  5812. /* Sets a new SignatureAlgorithmsCert extension into the extension list.
  5813. *
  5814. * extensions The list of extensions.
  5815. * data The extensions specific data.
  5816. * heap The heap used for allocation.
  5817. * returns 0 on success, otherwise failure.
  5818. */
  5819. static int TLSX_SetSignatureAlgorithmsCert(TLSX** extensions,
  5820. const WOLFSSL* data, void* heap)
  5821. {
  5822. if (extensions == NULL)
  5823. return BAD_FUNC_ARG;
  5824. return TLSX_Push(extensions, TLSX_SIGNATURE_ALGORITHMS_CERT, data, heap);
  5825. }
  5826. #define SAC_GET_SIZE TLSX_SignatureAlgorithmsCert_GetSize
  5827. #define SAC_WRITE TLSX_SignatureAlgorithmsCert_Write
  5828. #define SAC_PARSE TLSX_SignatureAlgorithmsCert_Parse
  5829. #endif /* WOLFSSL_TLS13 */
  5830. /******************************************************************************/
  5831. /* Key Share */
  5832. /******************************************************************************/
  5833. #if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
  5834. /* Create a key share entry using named Diffie-Hellman parameters group.
  5835. * Generates a key pair.
  5836. *
  5837. * ssl The SSL/TLS object.
  5838. * kse The key share entry object.
  5839. * returns 0 on success, otherwise failure.
  5840. */
  5841. static int TLSX_KeyShare_GenDhKey(WOLFSSL *ssl, KeyShareEntry* kse)
  5842. {
  5843. int ret = 0;
  5844. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  5845. word32 pSz = 0, pvtSz = 0;
  5846. DhKey* dhKey = (DhKey*)kse->key;
  5847. /* Pick the parameters from the named group. */
  5848. #ifdef HAVE_PUBLIC_FFDHE
  5849. const DhParams* params = NULL;
  5850. switch (kse->group) {
  5851. #ifdef HAVE_FFDHE_2048
  5852. case WOLFSSL_FFDHE_2048:
  5853. params = wc_Dh_ffdhe2048_Get();
  5854. pvtSz = 29;
  5855. break;
  5856. #endif
  5857. #ifdef HAVE_FFDHE_3072
  5858. case WOLFSSL_FFDHE_3072:
  5859. params = wc_Dh_ffdhe3072_Get();
  5860. pvtSz = 34;
  5861. break;
  5862. #endif
  5863. #ifdef HAVE_FFDHE_4096
  5864. case WOLFSSL_FFDHE_4096:
  5865. params = wc_Dh_ffdhe4096_Get();
  5866. pvtSz = 39;
  5867. break;
  5868. #endif
  5869. #ifdef HAVE_FFDHE_6144
  5870. case WOLFSSL_FFDHE_6144:
  5871. params = wc_Dh_ffdhe6144_Get();
  5872. pvtSz = 46;
  5873. break;
  5874. #endif
  5875. #ifdef HAVE_FFDHE_8192
  5876. case WOLFSSL_FFDHE_8192:
  5877. params = wc_Dh_ffdhe8192_Get();
  5878. pvtSz = 52;
  5879. break;
  5880. #endif
  5881. default:
  5882. break;
  5883. }
  5884. if (params == NULL)
  5885. return BAD_FUNC_ARG;
  5886. pSz = params->p_len;
  5887. #else
  5888. pvtSz = wc_DhGetNamedKeyMinSize(kse->group);
  5889. if (pvtSz == 0) {
  5890. return BAD_FUNC_ARG;
  5891. }
  5892. ret = wc_DhGetNamedKeyParamSize(kse->group, &pSz, NULL, NULL);
  5893. if (ret != 0) {
  5894. return BAD_FUNC_ARG;
  5895. }
  5896. #endif
  5897. /* Trigger Key Generation */
  5898. if (kse->pubKey == NULL || kse->privKey == NULL) {
  5899. if (kse->key == NULL) {
  5900. kse->key = (DhKey*)XMALLOC(sizeof(DhKey), ssl->heap,
  5901. DYNAMIC_TYPE_DH);
  5902. if (kse->key == NULL)
  5903. return MEMORY_E;
  5904. /* Setup Key */
  5905. ret = wc_InitDhKey_ex((DhKey*)kse->key, ssl->heap, ssl->devId);
  5906. if (ret == 0) {
  5907. dhKey = (DhKey*)kse->key;
  5908. #ifdef HAVE_PUBLIC_FFDHE
  5909. ret = wc_DhSetKey(dhKey, params->p, params->p_len, params->g,
  5910. params->g_len);
  5911. #else
  5912. ret = wc_DhSetNamedKey(dhKey, kse->group);
  5913. #endif
  5914. }
  5915. }
  5916. /* Allocate space for the private and public key */
  5917. if (ret == 0 && kse->pubKey == NULL) {
  5918. kse->pubKey = (byte*)XMALLOC(pSz, ssl->heap,
  5919. DYNAMIC_TYPE_PUBLIC_KEY);
  5920. if (kse->pubKey == NULL)
  5921. ret = MEMORY_E;
  5922. }
  5923. if (ret == 0 && kse->privKey == NULL) {
  5924. kse->privKey = (byte*)XMALLOC(pvtSz, ssl->heap,
  5925. DYNAMIC_TYPE_PRIVATE_KEY);
  5926. if (kse->privKey == NULL)
  5927. ret = MEMORY_E;
  5928. }
  5929. if (ret == 0) {
  5930. #if defined(WOLFSSL_STATIC_EPHEMERAL) && defined(WOLFSSL_DH_EXTRA)
  5931. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_DH, kse->key);
  5932. kse->pubKeyLen = pSz;
  5933. kse->keyLen = pvtSz;
  5934. if (ret == 0) {
  5935. ret = wc_DhExportKeyPair(dhKey,
  5936. (byte*)kse->privKey, &kse->keyLen, /* private */
  5937. kse->pubKey, &kse->pubKeyLen /* public */
  5938. );
  5939. }
  5940. else
  5941. #endif
  5942. {
  5943. /* Generate a new key pair */
  5944. /* For async this is called once and when event is done, the
  5945. * provided buffers will be populated.
  5946. * Final processing is zero pad below. */
  5947. kse->pubKeyLen = pSz;
  5948. kse->keyLen = pvtSz;
  5949. ret = DhGenKeyPair(ssl, dhKey,
  5950. (byte*)kse->privKey, &kse->keyLen, /* private */
  5951. kse->pubKey, &kse->pubKeyLen /* public */
  5952. );
  5953. #ifdef WOLFSSL_ASYNC_CRYPT
  5954. if (ret == WC_PENDING_E) {
  5955. return ret;
  5956. }
  5957. #endif
  5958. }
  5959. }
  5960. }
  5961. if (ret == 0) {
  5962. if (pSz != kse->pubKeyLen) {
  5963. /* Zero pad the front of the public key to match prime "p" size */
  5964. XMEMMOVE(kse->pubKey + pSz - kse->pubKeyLen, kse->pubKey,
  5965. kse->pubKeyLen);
  5966. XMEMSET(kse->pubKey, 0, pSz - kse->pubKeyLen);
  5967. kse->pubKeyLen = pSz;
  5968. }
  5969. if (pvtSz != kse->keyLen) {
  5970. /* Zero pad the front of the private key */
  5971. XMEMMOVE(kse->privKey + pvtSz - kse->keyLen, kse->privKey,
  5972. kse->keyLen);
  5973. XMEMSET(kse->privKey, 0, pvtSz - kse->keyLen);
  5974. kse->keyLen = pvtSz;
  5975. }
  5976. #ifdef WOLFSSL_DEBUG_TLS
  5977. WOLFSSL_MSG("Public DH Key");
  5978. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  5979. #endif
  5980. }
  5981. /* Always release the DH key to free up memory.
  5982. * The DhKey will be setup again in TLSX_KeyShare_ProcessDh */
  5983. if (dhKey != NULL)
  5984. wc_FreeDhKey(dhKey);
  5985. if (kse->key != NULL) {
  5986. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_DH);
  5987. kse->key = NULL;
  5988. }
  5989. if (ret != 0) {
  5990. /* Cleanup on error, otherwise data owned by key share entry */
  5991. if (kse->privKey != NULL) {
  5992. XFREE(kse->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  5993. kse->privKey = NULL;
  5994. }
  5995. if (kse->pubKey != NULL) {
  5996. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  5997. kse->pubKey = NULL;
  5998. }
  5999. }
  6000. #else
  6001. (void)ssl;
  6002. (void)kse;
  6003. ret = NOT_COMPILED_IN;
  6004. WOLFSSL_ERROR_VERBOSE(ret);
  6005. #endif
  6006. return ret;
  6007. }
  6008. /* Create a key share entry using X25519 parameters group.
  6009. * Generates a key pair.
  6010. *
  6011. * ssl The SSL/TLS object.
  6012. * kse The key share entry object.
  6013. * returns 0 on success, otherwise failure.
  6014. */
  6015. static int TLSX_KeyShare_GenX25519Key(WOLFSSL *ssl, KeyShareEntry* kse)
  6016. {
  6017. int ret = 0;
  6018. #ifdef HAVE_CURVE25519
  6019. curve25519_key* key = (curve25519_key*)kse->key;
  6020. if (kse->key == NULL) {
  6021. /* Allocate a Curve25519 key to hold private key. */
  6022. kse->key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), ssl->heap,
  6023. DYNAMIC_TYPE_PRIVATE_KEY);
  6024. if (kse->key == NULL) {
  6025. WOLFSSL_MSG("GenX25519Key memory error");
  6026. return MEMORY_E;
  6027. }
  6028. /* Make an Curve25519 key. */
  6029. ret = wc_curve25519_init_ex((curve25519_key*)kse->key, ssl->heap,
  6030. INVALID_DEVID);
  6031. if (ret == 0) {
  6032. /* setting "key" means okay to call wc_curve25519_free */
  6033. key = (curve25519_key*)kse->key;
  6034. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6035. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE25519, kse->key);
  6036. if (ret != 0)
  6037. #endif
  6038. {
  6039. ret = wc_curve25519_make_key(ssl->rng, CURVE25519_KEYSIZE, key);
  6040. }
  6041. }
  6042. }
  6043. if (ret == 0 && kse->pubKey == NULL) {
  6044. /* Allocate space for the public key. */
  6045. kse->pubKey = (byte*)XMALLOC(CURVE25519_KEYSIZE, ssl->heap,
  6046. DYNAMIC_TYPE_PUBLIC_KEY);
  6047. if (kse->pubKey == NULL) {
  6048. WOLFSSL_MSG("GenX25519Key pub memory error");
  6049. ret = MEMORY_E;
  6050. }
  6051. }
  6052. if (ret == 0) {
  6053. /* Export Curve25519 public key. */
  6054. kse->pubKeyLen = CURVE25519_KEYSIZE;
  6055. if (wc_curve25519_export_public_ex(key, kse->pubKey, &kse->pubKeyLen,
  6056. EC25519_LITTLE_ENDIAN) != 0) {
  6057. ret = ECC_EXPORT_ERROR;
  6058. WOLFSSL_ERROR_VERBOSE(ret);
  6059. }
  6060. kse->pubKeyLen = CURVE25519_KEYSIZE; /* always CURVE25519_KEYSIZE */
  6061. }
  6062. #ifdef WOLFSSL_DEBUG_TLS
  6063. if (ret == 0) {
  6064. WOLFSSL_MSG("Public Curve25519 Key");
  6065. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6066. }
  6067. #endif
  6068. if (ret != 0) {
  6069. /* Data owned by key share entry otherwise. */
  6070. if (kse->pubKey != NULL) {
  6071. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6072. kse->pubKey = NULL;
  6073. }
  6074. if (key != NULL)
  6075. wc_curve25519_free(key);
  6076. if (kse->key != NULL) {
  6077. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6078. kse->key = NULL;
  6079. }
  6080. }
  6081. #else
  6082. (void)ssl;
  6083. (void)kse;
  6084. ret = NOT_COMPILED_IN;
  6085. WOLFSSL_ERROR_VERBOSE(ret);
  6086. #endif /* HAVE_CURVE25519 */
  6087. return ret;
  6088. }
  6089. /* Create a key share entry using X448 parameters group.
  6090. * Generates a key pair.
  6091. *
  6092. * ssl The SSL/TLS object.
  6093. * kse The key share entry object.
  6094. * returns 0 on success, otherwise failure.
  6095. */
  6096. static int TLSX_KeyShare_GenX448Key(WOLFSSL *ssl, KeyShareEntry* kse)
  6097. {
  6098. int ret = 0;
  6099. #ifdef HAVE_CURVE448
  6100. curve448_key* key = (curve448_key*)kse->key;
  6101. if (kse->key == NULL) {
  6102. /* Allocate a Curve448 key to hold private key. */
  6103. kse->key = (curve448_key*)XMALLOC(sizeof(curve448_key), ssl->heap,
  6104. DYNAMIC_TYPE_PRIVATE_KEY);
  6105. if (kse->key == NULL) {
  6106. WOLFSSL_MSG("GenX448Key memory error");
  6107. return MEMORY_E;
  6108. }
  6109. /* Make an Curve448 key. */
  6110. ret = wc_curve448_init((curve448_key*)kse->key);
  6111. if (ret == 0) {
  6112. key = (curve448_key*)kse->key;
  6113. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6114. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_CURVE448, kse->key);
  6115. if (ret != 0)
  6116. #endif
  6117. {
  6118. ret = wc_curve448_make_key(ssl->rng, CURVE448_KEY_SIZE, key);
  6119. }
  6120. }
  6121. }
  6122. if (ret == 0 && kse->pubKey == NULL) {
  6123. /* Allocate space for the public key. */
  6124. kse->pubKey = (byte*)XMALLOC(CURVE448_KEY_SIZE, ssl->heap,
  6125. DYNAMIC_TYPE_PUBLIC_KEY);
  6126. if (kse->pubKey == NULL) {
  6127. WOLFSSL_MSG("GenX448Key pub memory error");
  6128. ret = MEMORY_E;
  6129. }
  6130. }
  6131. if (ret == 0) {
  6132. /* Export Curve448 public key. */
  6133. kse->pubKeyLen = CURVE448_KEY_SIZE;
  6134. if (wc_curve448_export_public_ex(key, kse->pubKey, &kse->pubKeyLen,
  6135. EC448_LITTLE_ENDIAN) != 0) {
  6136. ret = ECC_EXPORT_ERROR;
  6137. }
  6138. kse->pubKeyLen = CURVE448_KEY_SIZE; /* always CURVE448_KEY_SIZE */
  6139. }
  6140. #ifdef WOLFSSL_DEBUG_TLS
  6141. if (ret == 0) {
  6142. WOLFSSL_MSG("Public Curve448 Key");
  6143. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6144. }
  6145. #endif
  6146. if (ret != 0) {
  6147. /* Data owned by key share entry otherwise. */
  6148. if (kse->pubKey != NULL) {
  6149. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6150. kse->pubKey = NULL;
  6151. }
  6152. if (key != NULL)
  6153. wc_curve448_free(key);
  6154. if (kse->key != NULL) {
  6155. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6156. kse->key = NULL;
  6157. }
  6158. }
  6159. #else
  6160. (void)ssl;
  6161. (void)kse;
  6162. ret = NOT_COMPILED_IN;
  6163. WOLFSSL_ERROR_VERBOSE(ret);
  6164. #endif /* HAVE_CURVE448 */
  6165. return ret;
  6166. }
  6167. /* Create a key share entry using named elliptic curve parameters group.
  6168. * Generates a key pair.
  6169. *
  6170. * ssl The SSL/TLS object.
  6171. * kse The key share entry object.
  6172. * returns 0 on success, otherwise failure.
  6173. */
  6174. static int TLSX_KeyShare_GenEccKey(WOLFSSL *ssl, KeyShareEntry* kse)
  6175. {
  6176. int ret = 0;
  6177. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  6178. word32 keySize = 0;
  6179. word16 curveId = (word16) ECC_CURVE_INVALID;
  6180. ecc_key* eccKey = (ecc_key*)kse->key;
  6181. /* TODO: [TLS13] The key sizes should come from wolfcrypt. */
  6182. /* Translate named group to a curve id. */
  6183. switch (kse->group) {
  6184. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  6185. #ifndef NO_ECC_SECP
  6186. case WOLFSSL_ECC_SECP256R1:
  6187. curveId = ECC_SECP256R1;
  6188. keySize = 32;
  6189. break;
  6190. #endif /* !NO_ECC_SECP */
  6191. #ifdef WOLFSSL_SM2
  6192. case WOLFSSL_ECC_SM2P256V1:
  6193. curveId = ECC_SM2P256V1;
  6194. keySize = 32;
  6195. break;
  6196. #endif /* !NO_ECC_SECP */
  6197. #endif
  6198. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  6199. #ifndef NO_ECC_SECP
  6200. case WOLFSSL_ECC_SECP384R1:
  6201. curveId = ECC_SECP384R1;
  6202. keySize = 48;
  6203. break;
  6204. #endif /* !NO_ECC_SECP */
  6205. #endif
  6206. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  6207. #ifndef NO_ECC_SECP
  6208. case WOLFSSL_ECC_SECP521R1:
  6209. curveId = ECC_SECP521R1;
  6210. keySize = 66;
  6211. break;
  6212. #endif /* !NO_ECC_SECP */
  6213. #endif
  6214. default:
  6215. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  6216. return BAD_FUNC_ARG;
  6217. }
  6218. if (kse->key == NULL) {
  6219. kse->keyLen = keySize;
  6220. kse->pubKeyLen = keySize * 2 + 1;
  6221. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  6222. ret = tsip_Tls13GenEccKeyPair(ssl, kse);
  6223. if (ret != CRYPTOCB_UNAVAILABLE) {
  6224. return ret;
  6225. }
  6226. #endif
  6227. /* Allocate an ECC key to hold private key. */
  6228. kse->key = (byte*)XMALLOC(sizeof(ecc_key), ssl->heap, DYNAMIC_TYPE_ECC);
  6229. if (kse->key == NULL) {
  6230. WOLFSSL_MSG("EccTempKey Memory error");
  6231. return MEMORY_E;
  6232. }
  6233. /* Make an ECC key */
  6234. ret = wc_ecc_init_ex((ecc_key*)kse->key, ssl->heap, ssl->devId);
  6235. if (ret == 0) {
  6236. /* setting eccKey means okay to call wc_ecc_free */
  6237. eccKey = (ecc_key*)kse->key;
  6238. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6239. ret = wolfSSL_StaticEphemeralKeyLoad(ssl, WC_PK_TYPE_ECDH, kse->key);
  6240. if (ret != 0)
  6241. #endif
  6242. {
  6243. /* set curve info for EccMakeKey "peer" info */
  6244. ret = wc_ecc_set_curve(eccKey, kse->keyLen, curveId);
  6245. if (ret == 0) {
  6246. /* Generate ephemeral ECC key */
  6247. /* For async this is called once and when event is done, the
  6248. * provided buffers in key be populated.
  6249. * Final processing is x963 key export below. */
  6250. ret = EccMakeKey(ssl, eccKey, eccKey);
  6251. }
  6252. #ifdef WOLFSSL_ASYNC_CRYPT
  6253. if (ret == WC_PENDING_E)
  6254. return ret;
  6255. #endif
  6256. }
  6257. }
  6258. }
  6259. if (ret == 0 && kse->pubKey == NULL) {
  6260. /* Allocate space for the public key */
  6261. kse->pubKey = (byte*)XMALLOC(kse->pubKeyLen, ssl->heap,
  6262. DYNAMIC_TYPE_PUBLIC_KEY);
  6263. if (kse->pubKey == NULL) {
  6264. WOLFSSL_MSG("Key data Memory error");
  6265. ret = MEMORY_E;
  6266. }
  6267. }
  6268. if (ret == 0) {
  6269. XMEMSET(kse->pubKey, 0, kse->pubKeyLen);
  6270. /* Export public key. */
  6271. PRIVATE_KEY_UNLOCK();
  6272. if (wc_ecc_export_x963(eccKey, kse->pubKey, &kse->pubKeyLen) != 0) {
  6273. ret = ECC_EXPORT_ERROR;
  6274. WOLFSSL_ERROR_VERBOSE(ret);
  6275. }
  6276. PRIVATE_KEY_LOCK();
  6277. }
  6278. #ifdef WOLFSSL_DEBUG_TLS
  6279. if (ret == 0) {
  6280. WOLFSSL_MSG("Public ECC Key");
  6281. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen);
  6282. }
  6283. #endif
  6284. if (ret != 0) {
  6285. /* Cleanup on error, otherwise data owned by key share entry */
  6286. if (kse->pubKey != NULL) {
  6287. XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6288. kse->pubKey = NULL;
  6289. }
  6290. if (eccKey != NULL)
  6291. wc_ecc_free(eccKey);
  6292. if (kse->key != NULL) {
  6293. XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6294. kse->key = NULL;
  6295. }
  6296. }
  6297. #else
  6298. (void)ssl;
  6299. (void)kse;
  6300. ret = NOT_COMPILED_IN;
  6301. WOLFSSL_ERROR_VERBOSE(ret);
  6302. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  6303. return ret;
  6304. }
  6305. #ifdef HAVE_PQC
  6306. static int kyber_id2type(int id, int *type)
  6307. {
  6308. int ret = 0;
  6309. switch (id) {
  6310. #ifdef WOLFSSL_KYBER512
  6311. case WOLFSSL_KYBER_LEVEL1:
  6312. *type = KYBER512;
  6313. break;
  6314. #endif
  6315. #ifdef WOLFSSL_KYBER768
  6316. case WOLFSSL_KYBER_LEVEL3:
  6317. *type = KYBER768;
  6318. break;
  6319. #endif
  6320. #ifdef WOLFSSL_KYBER1024
  6321. case WOLFSSL_KYBER_LEVEL5:
  6322. *type = KYBER1024;
  6323. break;
  6324. #endif
  6325. default:
  6326. ret = NOT_COMPILED_IN;
  6327. break;
  6328. }
  6329. return ret;
  6330. }
  6331. typedef struct PqcHybridMapping {
  6332. int hybrid;
  6333. int ecc;
  6334. int pqc;
  6335. } PqcHybridMapping;
  6336. static const PqcHybridMapping pqc_hybrid_mapping[] = {
  6337. {.hybrid = WOLFSSL_P256_KYBER_LEVEL1, .ecc = WOLFSSL_ECC_SECP256R1,
  6338. .pqc = WOLFSSL_KYBER_LEVEL1},
  6339. {.hybrid = WOLFSSL_P384_KYBER_LEVEL3, .ecc = WOLFSSL_ECC_SECP384R1,
  6340. .pqc = WOLFSSL_KYBER_LEVEL3},
  6341. {.hybrid = WOLFSSL_P521_KYBER_LEVEL5, .ecc = WOLFSSL_ECC_SECP521R1,
  6342. .pqc = WOLFSSL_KYBER_LEVEL5},
  6343. {.hybrid = 0, .ecc = 0, .pqc = 0}
  6344. };
  6345. /* This will map an ecc-pqs hybrid group into its ecc group and pqc kem group.
  6346. * If it cannot find a mapping then *pqc is set to group. ecc is optional. */
  6347. static void findEccPqc(int *ecc, int *pqc, int group)
  6348. {
  6349. int i;
  6350. if (pqc == NULL) {
  6351. return;
  6352. }
  6353. *pqc = 0;
  6354. if (ecc != NULL) {
  6355. *ecc = 0;
  6356. }
  6357. for (i = 0; pqc_hybrid_mapping[i].hybrid != 0; i++) {
  6358. if (pqc_hybrid_mapping[i].hybrid == group) {
  6359. *pqc = pqc_hybrid_mapping[i].pqc;
  6360. if (ecc != NULL) {
  6361. *ecc = pqc_hybrid_mapping[i].ecc;
  6362. }
  6363. break;
  6364. }
  6365. }
  6366. if (*pqc == 0) {
  6367. /* It is not a hybrid, so maybe its simple. */
  6368. *pqc = group;
  6369. }
  6370. }
  6371. /* Create a key share entry using liboqs parameters group.
  6372. * Generates a key pair.
  6373. *
  6374. * ssl The SSL/TLS object.
  6375. * kse The key share entry object.
  6376. * returns 0 on success, otherwise failure.
  6377. */
  6378. static int TLSX_KeyShare_GenPqcKey(WOLFSSL *ssl, KeyShareEntry* kse)
  6379. {
  6380. int ret = 0;
  6381. int type = 0;
  6382. KyberKey kem[1];
  6383. byte* pubKey = NULL;
  6384. byte* privKey = NULL;
  6385. KeyShareEntry *ecc_kse = NULL;
  6386. int oqs_group = 0;
  6387. int ecc_group = 0;
  6388. word32 privSz = 0;
  6389. word32 pubSz = 0;
  6390. findEccPqc(&ecc_group, &oqs_group, kse->group);
  6391. ret = kyber_id2type(oqs_group, &type);
  6392. if (ret == NOT_COMPILED_IN) {
  6393. WOLFSSL_MSG("Invalid Kyber algorithm specified.");
  6394. ret = BAD_FUNC_ARG;
  6395. }
  6396. if (ret == 0) {
  6397. ret = wc_KyberKey_Init(type, kem, ssl->heap, ssl->devId);
  6398. if (ret != 0) {
  6399. WOLFSSL_MSG("Failed to initialize Kyber Key.");
  6400. }
  6401. }
  6402. if (ret == 0) {
  6403. ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap,
  6404. DYNAMIC_TYPE_TLSX);
  6405. if (ecc_kse == NULL) {
  6406. WOLFSSL_MSG("ecc_kse memory allocation failure");
  6407. ret = MEMORY_ERROR;
  6408. }
  6409. }
  6410. if (ret == 0) {
  6411. XMEMSET(ecc_kse, 0, sizeof(*ecc_kse));
  6412. ret = wc_KyberKey_PrivateKeySize(kem, &privSz);
  6413. }
  6414. if (ret == 0) {
  6415. ret = wc_KyberKey_PublicKeySize(kem, &pubSz);
  6416. }
  6417. if (ret == 0 && ecc_group != 0) {
  6418. ecc_kse->group = ecc_group;
  6419. ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse);
  6420. /* If fail, no error message, TLSX_KeyShare_GenEccKey will do it. */
  6421. }
  6422. if (ret == 0) {
  6423. pubKey = (byte*)XMALLOC(ecc_kse->pubKeyLen + pubSz, ssl->heap,
  6424. DYNAMIC_TYPE_PUBLIC_KEY);
  6425. if (pubKey == NULL) {
  6426. WOLFSSL_MSG("pubkey memory allocation failure");
  6427. ret = MEMORY_ERROR;
  6428. }
  6429. }
  6430. if (ret == 0) {
  6431. privKey = (byte*)XMALLOC(privSz, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6432. if (privKey == NULL) {
  6433. WOLFSSL_MSG("privkey memory allocation failure");
  6434. ret = MEMORY_ERROR;
  6435. }
  6436. }
  6437. if (ret == 0) {
  6438. ret = wc_KyberKey_MakeKey(kem, ssl->rng);
  6439. if (ret != 0) {
  6440. WOLFSSL_MSG("Kyber keygen failure");
  6441. }
  6442. }
  6443. if (ret == 0) {
  6444. ret = wc_KyberKey_EncodePublicKey(kem, pubKey + ecc_kse->pubKeyLen,
  6445. pubSz);
  6446. }
  6447. if (ret == 0) {
  6448. ret = wc_KyberKey_EncodePrivateKey(kem, privKey, privSz);
  6449. }
  6450. if (ret == 0) {
  6451. XMEMCPY(pubKey, ecc_kse->pubKey, ecc_kse->pubKeyLen);
  6452. kse->pubKey = pubKey;
  6453. kse->pubKeyLen = ecc_kse->pubKeyLen + pubSz;
  6454. pubKey = NULL;
  6455. /* Note we are saving the OQS private key and ECC private key
  6456. * separately. That's because the ECC private key is not simply a
  6457. * buffer. Its is an ecc_key struct.
  6458. */
  6459. kse->privKey = privKey;
  6460. privKey = NULL;
  6461. kse->key = ecc_kse->key;
  6462. ecc_kse->key = NULL;
  6463. }
  6464. #ifdef WOLFSSL_DEBUG_TLS
  6465. WOLFSSL_MSG("Public Kyber Key");
  6466. WOLFSSL_BUFFER(kse->pubKey, kse->pubKeyLen );
  6467. #endif
  6468. wc_KyberKey_Free(kem);
  6469. TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap);
  6470. if (pubKey != NULL)
  6471. XFREE(pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6472. if (privKey != NULL)
  6473. XFREE(privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6474. return ret;
  6475. }
  6476. #endif /* HAVE_PQC */
  6477. /* Generate a secret/key using the key share entry.
  6478. *
  6479. * ssl The SSL/TLS object.
  6480. * kse The key share entry holding peer data.
  6481. */
  6482. int TLSX_KeyShare_GenKey(WOLFSSL *ssl, KeyShareEntry *kse)
  6483. {
  6484. int ret;
  6485. /* Named FFDHE groups have a bit set to identify them. */
  6486. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(kse->group))
  6487. ret = TLSX_KeyShare_GenDhKey(ssl, kse);
  6488. else if (kse->group == WOLFSSL_ECC_X25519)
  6489. ret = TLSX_KeyShare_GenX25519Key(ssl, kse);
  6490. else if (kse->group == WOLFSSL_ECC_X448)
  6491. ret = TLSX_KeyShare_GenX448Key(ssl, kse);
  6492. #ifdef HAVE_PQC
  6493. else if (WOLFSSL_NAMED_GROUP_IS_PQC(kse->group))
  6494. ret = TLSX_KeyShare_GenPqcKey(ssl, kse);
  6495. #endif
  6496. else
  6497. ret = TLSX_KeyShare_GenEccKey(ssl, kse);
  6498. #ifdef WOLFSSL_ASYNC_CRYPT
  6499. kse->lastRet = ret;
  6500. #endif
  6501. return ret;
  6502. }
  6503. /* Free the key share dynamic data.
  6504. *
  6505. * list The linked list of key share entry objects.
  6506. * heap The heap used for allocation.
  6507. */
  6508. static void TLSX_KeyShare_FreeAll(KeyShareEntry* list, void* heap)
  6509. {
  6510. KeyShareEntry* current;
  6511. while ((current = list) != NULL) {
  6512. list = current->next;
  6513. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(current->group)) {
  6514. #ifndef NO_DH
  6515. wc_FreeDhKey((DhKey*)current->key);
  6516. #endif
  6517. }
  6518. else if (current->group == WOLFSSL_ECC_X25519) {
  6519. #ifdef HAVE_CURVE25519
  6520. wc_curve25519_free((curve25519_key*)current->key);
  6521. #endif
  6522. }
  6523. else if (current->group == WOLFSSL_ECC_X448) {
  6524. #ifdef HAVE_CURVE448
  6525. wc_curve448_free((curve448_key*)current->key);
  6526. #endif
  6527. }
  6528. #ifdef HAVE_PQC
  6529. else if (WOLFSSL_NAMED_GROUP_IS_PQC(current->group) &&
  6530. current->key != NULL) {
  6531. ForceZero((byte*)current->key, current->keyLen);
  6532. }
  6533. #endif
  6534. else {
  6535. #ifdef HAVE_ECC
  6536. wc_ecc_free((ecc_key*)current->key);
  6537. #endif
  6538. }
  6539. XFREE(current->key, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6540. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  6541. XFREE(current->privKey, heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6542. #endif
  6543. XFREE(current->pubKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6544. XFREE(current->ke, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6545. XFREE(current, heap, DYNAMIC_TYPE_TLSX);
  6546. }
  6547. (void)heap;
  6548. }
  6549. /* Get the size of the encoded key share extension.
  6550. *
  6551. * list The linked list of key share extensions.
  6552. * msgType The type of the message this extension is being written into.
  6553. * returns the number of bytes of the encoded key share extension.
  6554. */
  6555. static word16 TLSX_KeyShare_GetSize(KeyShareEntry* list, byte msgType)
  6556. {
  6557. word16 len = 0;
  6558. byte isRequest = (msgType == client_hello);
  6559. KeyShareEntry* current;
  6560. /* The named group the server wants to use. */
  6561. if (msgType == hello_retry_request)
  6562. return OPAQUE16_LEN;
  6563. /* List of key exchange groups. */
  6564. if (isRequest)
  6565. len += OPAQUE16_LEN;
  6566. while ((current = list) != NULL) {
  6567. list = current->next;
  6568. if (!isRequest && current->pubKey == NULL)
  6569. continue;
  6570. len += (word16)(KE_GROUP_LEN + OPAQUE16_LEN + current->pubKeyLen);
  6571. }
  6572. return len;
  6573. }
  6574. /* Writes the key share extension into the output buffer.
  6575. * Assumes that the the output buffer is big enough to hold data.
  6576. *
  6577. * list The linked list of key share entries.
  6578. * output The buffer to write into.
  6579. * msgType The type of the message this extension is being written into.
  6580. * returns the number of bytes written into the buffer.
  6581. */
  6582. static word16 TLSX_KeyShare_Write(KeyShareEntry* list, byte* output,
  6583. byte msgType)
  6584. {
  6585. word16 i = 0;
  6586. byte isRequest = (msgType == client_hello);
  6587. KeyShareEntry* current;
  6588. if (msgType == hello_retry_request) {
  6589. c16toa(list->group, output);
  6590. return OPAQUE16_LEN;
  6591. }
  6592. /* ClientHello has a list but ServerHello is only the chosen. */
  6593. if (isRequest)
  6594. i += OPAQUE16_LEN;
  6595. /* Write out all in the list. */
  6596. while ((current = list) != NULL) {
  6597. list = current->next;
  6598. if (!isRequest && current->pubKey == NULL)
  6599. continue;
  6600. c16toa(current->group, &output[i]);
  6601. i += KE_GROUP_LEN;
  6602. c16toa((word16)(current->pubKeyLen), &output[i]);
  6603. i += OPAQUE16_LEN;
  6604. XMEMCPY(&output[i], current->pubKey, current->pubKeyLen);
  6605. i += (word16)current->pubKeyLen;
  6606. }
  6607. /* Write the length of the list if required. */
  6608. if (isRequest)
  6609. c16toa(i - OPAQUE16_LEN, output);
  6610. return i;
  6611. }
  6612. /* Process the DH key share extension on the client side.
  6613. *
  6614. * ssl The SSL/TLS object.
  6615. * keyShareEntry The key share entry object to use to calculate shared secret.
  6616. * returns 0 on success and other values indicate failure.
  6617. */
  6618. static int TLSX_KeyShare_ProcessDh(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6619. {
  6620. int ret = 0;
  6621. #if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
  6622. word32 pSz = 0;
  6623. DhKey* dhKey = (DhKey*)keyShareEntry->key;
  6624. #ifdef HAVE_PUBLIC_FFDHE
  6625. const DhParams* params = NULL;
  6626. switch (keyShareEntry->group) {
  6627. #ifdef HAVE_FFDHE_2048
  6628. case WOLFSSL_FFDHE_2048:
  6629. params = wc_Dh_ffdhe2048_Get();
  6630. break;
  6631. #endif
  6632. #ifdef HAVE_FFDHE_3072
  6633. case WOLFSSL_FFDHE_3072:
  6634. params = wc_Dh_ffdhe3072_Get();
  6635. break;
  6636. #endif
  6637. #ifdef HAVE_FFDHE_4096
  6638. case WOLFSSL_FFDHE_4096:
  6639. params = wc_Dh_ffdhe4096_Get();
  6640. break;
  6641. #endif
  6642. #ifdef HAVE_FFDHE_6144
  6643. case WOLFSSL_FFDHE_6144:
  6644. params = wc_Dh_ffdhe6144_Get();
  6645. break;
  6646. #endif
  6647. #ifdef HAVE_FFDHE_8192
  6648. case WOLFSSL_FFDHE_8192:
  6649. params = wc_Dh_ffdhe8192_Get();
  6650. break;
  6651. #endif
  6652. default:
  6653. break;
  6654. }
  6655. if (params == NULL) {
  6656. WOLFSSL_ERROR_VERBOSE(PEER_KEY_ERROR);
  6657. return PEER_KEY_ERROR;
  6658. }
  6659. pSz = params->p_len;
  6660. #else
  6661. ret = wc_DhGetNamedKeyParamSize(keyShareEntry->group, &pSz, NULL, NULL);
  6662. if (ret != 0 || pSz == 0) {
  6663. WOLFSSL_ERROR_VERBOSE(PEER_KEY_ERROR);
  6664. return PEER_KEY_ERROR;
  6665. }
  6666. #endif
  6667. /* if DhKey is not setup, do it now */
  6668. if (keyShareEntry->key == NULL) {
  6669. keyShareEntry->key = (DhKey*)XMALLOC(sizeof(DhKey), ssl->heap,
  6670. DYNAMIC_TYPE_DH);
  6671. if (keyShareEntry->key == NULL)
  6672. return MEMORY_E;
  6673. /* Setup Key */
  6674. ret = wc_InitDhKey_ex((DhKey*)keyShareEntry->key, ssl->heap, ssl->devId);
  6675. if (ret == 0) {
  6676. dhKey = (DhKey*)keyShareEntry->key;
  6677. /* Set key */
  6678. #ifdef HAVE_PUBLIC_FFDHE
  6679. ret = wc_DhSetKey(dhKey, params->p, params->p_len, params->g,
  6680. params->g_len);
  6681. #else
  6682. ret = wc_DhSetNamedKey(dhKey, keyShareEntry->group);
  6683. #endif
  6684. }
  6685. }
  6686. if (ret == 0
  6687. #ifdef WOLFSSL_ASYNC_CRYPT
  6688. && keyShareEntry->lastRet == 0 /* don't enter here if WC_PENDING_E */
  6689. #endif
  6690. ) {
  6691. #ifdef WOLFSSL_DEBUG_TLS
  6692. WOLFSSL_MSG("Peer DH Key");
  6693. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6694. #endif
  6695. ssl->options.dhKeySz = (word16)pSz;
  6696. /* Derive secret from private key and peer's public key. */
  6697. ret = DhAgree(ssl, dhKey,
  6698. (const byte*)keyShareEntry->privKey, keyShareEntry->keyLen, /* our private */
  6699. keyShareEntry->ke, keyShareEntry->keLen, /* peer's public key */
  6700. ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz, /* secret */
  6701. NULL, 0
  6702. );
  6703. #ifdef WOLFSSL_ASYNC_CRYPT
  6704. if (ret == WC_PENDING_E) {
  6705. return ret;
  6706. }
  6707. #endif
  6708. }
  6709. /* RFC 8446 Section 7.4.1:
  6710. * ... left-padded with zeros up to the size of the prime. ...
  6711. */
  6712. if (ret == 0 && (word32)ssl->options.dhKeySz > ssl->arrays->preMasterSz) {
  6713. word32 diff = (word32)ssl->options.dhKeySz - ssl->arrays->preMasterSz;
  6714. XMEMMOVE(ssl->arrays->preMasterSecret + diff,
  6715. ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  6716. XMEMSET(ssl->arrays->preMasterSecret, 0, diff);
  6717. ssl->arrays->preMasterSz = ssl->options.dhKeySz;
  6718. }
  6719. /* done with key share, release resources */
  6720. if (dhKey)
  6721. wc_FreeDhKey(dhKey);
  6722. if (keyShareEntry->key) {
  6723. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_DH);
  6724. keyShareEntry->key = NULL;
  6725. }
  6726. if (keyShareEntry->privKey != NULL) {
  6727. XFREE(keyShareEntry->privKey, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6728. keyShareEntry->privKey = NULL;
  6729. }
  6730. if (keyShareEntry->pubKey != NULL) {
  6731. XFREE(keyShareEntry->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6732. keyShareEntry->pubKey = NULL;
  6733. }
  6734. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  6735. keyShareEntry->ke = NULL;
  6736. #else
  6737. (void)ssl;
  6738. (void)keyShareEntry;
  6739. ret = PEER_KEY_ERROR;
  6740. WOLFSSL_ERROR_VERBOSE(ret);
  6741. #endif
  6742. return ret;
  6743. }
  6744. /* Process the X25519 key share extension on the client side.
  6745. *
  6746. * ssl The SSL/TLS object.
  6747. * keyShareEntry The key share entry object to use to calculate shared secret.
  6748. * returns 0 on success and other values indicate failure.
  6749. */
  6750. static int TLSX_KeyShare_ProcessX25519(WOLFSSL* ssl,
  6751. KeyShareEntry* keyShareEntry)
  6752. {
  6753. int ret;
  6754. #ifdef HAVE_CURVE25519
  6755. curve25519_key* key = (curve25519_key*)keyShareEntry->key;
  6756. curve25519_key* peerX25519Key;
  6757. #ifdef HAVE_ECC
  6758. if (ssl->peerEccKey != NULL) {
  6759. wc_ecc_free(ssl->peerEccKey);
  6760. ssl->peerEccKey = NULL;
  6761. ssl->peerEccKeyPresent = 0;
  6762. }
  6763. #endif
  6764. peerX25519Key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), ssl->heap,
  6765. DYNAMIC_TYPE_TLSX);
  6766. if (peerX25519Key == NULL) {
  6767. WOLFSSL_MSG("PeerEccKey Memory error");
  6768. return MEMORY_ERROR;
  6769. }
  6770. ret = wc_curve25519_init(peerX25519Key);
  6771. if (ret != 0) {
  6772. XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6773. return ret;
  6774. }
  6775. #ifdef WOLFSSL_DEBUG_TLS
  6776. WOLFSSL_MSG("Peer Curve25519 Key");
  6777. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6778. #endif
  6779. if (wc_curve25519_check_public(keyShareEntry->ke, keyShareEntry->keLen,
  6780. EC25519_LITTLE_ENDIAN) != 0) {
  6781. ret = ECC_PEERKEY_ERROR;
  6782. WOLFSSL_ERROR_VERBOSE(ret);
  6783. }
  6784. if (ret == 0) {
  6785. if (wc_curve25519_import_public_ex(keyShareEntry->ke,
  6786. keyShareEntry->keLen, peerX25519Key,
  6787. EC25519_LITTLE_ENDIAN) != 0) {
  6788. ret = ECC_PEERKEY_ERROR;
  6789. WOLFSSL_ERROR_VERBOSE(ret);
  6790. }
  6791. }
  6792. if (ret == 0) {
  6793. ssl->ecdhCurveOID = ECC_X25519_OID;
  6794. ret = wc_curve25519_shared_secret_ex(key, peerX25519Key,
  6795. ssl->arrays->preMasterSecret,
  6796. &ssl->arrays->preMasterSz,
  6797. EC25519_LITTLE_ENDIAN);
  6798. }
  6799. wc_curve25519_free(peerX25519Key);
  6800. XFREE(peerX25519Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6801. wc_curve25519_free((curve25519_key*)keyShareEntry->key);
  6802. if (keyShareEntry->key != NULL) {
  6803. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6804. keyShareEntry->key = NULL;
  6805. }
  6806. #else
  6807. (void)ssl;
  6808. (void)keyShareEntry;
  6809. ret = PEER_KEY_ERROR;
  6810. WOLFSSL_ERROR_VERBOSE(ret);
  6811. #endif /* HAVE_CURVE25519 */
  6812. return ret;
  6813. }
  6814. /* Process the X448 key share extension on the client side.
  6815. *
  6816. * ssl The SSL/TLS object.
  6817. * keyShareEntry The key share entry object to use to calculate shared secret.
  6818. * returns 0 on success and other values indicate failure.
  6819. */
  6820. static int TLSX_KeyShare_ProcessX448(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6821. {
  6822. int ret;
  6823. #ifdef HAVE_CURVE448
  6824. curve448_key* key = (curve448_key*)keyShareEntry->key;
  6825. curve448_key* peerX448Key;
  6826. #ifdef HAVE_ECC
  6827. if (ssl->peerEccKey != NULL) {
  6828. wc_ecc_free(ssl->peerEccKey);
  6829. ssl->peerEccKey = NULL;
  6830. ssl->peerEccKeyPresent = 0;
  6831. }
  6832. #endif
  6833. peerX448Key = (curve448_key*)XMALLOC(sizeof(curve448_key), ssl->heap,
  6834. DYNAMIC_TYPE_TLSX);
  6835. if (peerX448Key == NULL) {
  6836. WOLFSSL_MSG("PeerEccKey Memory error");
  6837. return MEMORY_ERROR;
  6838. }
  6839. ret = wc_curve448_init(peerX448Key);
  6840. if (ret != 0) {
  6841. XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6842. return ret;
  6843. }
  6844. #ifdef WOLFSSL_DEBUG_TLS
  6845. WOLFSSL_MSG("Peer Curve448 Key");
  6846. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6847. #endif
  6848. if (wc_curve448_check_public(keyShareEntry->ke, keyShareEntry->keLen,
  6849. EC448_LITTLE_ENDIAN) != 0) {
  6850. ret = ECC_PEERKEY_ERROR;
  6851. WOLFSSL_ERROR_VERBOSE(ret);
  6852. }
  6853. if (ret == 0) {
  6854. if (wc_curve448_import_public_ex(keyShareEntry->ke,
  6855. keyShareEntry->keLen, peerX448Key,
  6856. EC448_LITTLE_ENDIAN) != 0) {
  6857. ret = ECC_PEERKEY_ERROR;
  6858. WOLFSSL_ERROR_VERBOSE(ret);
  6859. }
  6860. }
  6861. if (ret == 0) {
  6862. ssl->ecdhCurveOID = ECC_X448_OID;
  6863. ret = wc_curve448_shared_secret_ex(key, peerX448Key,
  6864. ssl->arrays->preMasterSecret,
  6865. &ssl->arrays->preMasterSz,
  6866. EC448_LITTLE_ENDIAN);
  6867. }
  6868. wc_curve448_free(peerX448Key);
  6869. XFREE(peerX448Key, ssl->heap, DYNAMIC_TYPE_TLSX);
  6870. wc_curve448_free((curve448_key*)keyShareEntry->key);
  6871. if (keyShareEntry->key != NULL) {
  6872. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  6873. keyShareEntry->key = NULL;
  6874. }
  6875. #else
  6876. (void)ssl;
  6877. (void)keyShareEntry;
  6878. ret = PEER_KEY_ERROR;
  6879. WOLFSSL_ERROR_VERBOSE(ret);
  6880. #endif /* HAVE_CURVE448 */
  6881. return ret;
  6882. }
  6883. /* Process the ECC key share extension on the client side.
  6884. *
  6885. * ssl The SSL/TLS object.
  6886. * keyShareEntry The key share entry object to use to calculate shared secret.
  6887. * returns 0 on success and other values indicate failure.
  6888. */
  6889. static int TLSX_KeyShare_ProcessEcc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  6890. {
  6891. int ret = 0;
  6892. #ifdef HAVE_ECC
  6893. int curveId = ECC_CURVE_INVALID;
  6894. ecc_key* eccKey = (ecc_key*)keyShareEntry->key;
  6895. /* find supported curve */
  6896. switch (keyShareEntry->group) {
  6897. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  6898. #ifndef NO_ECC_SECP
  6899. case WOLFSSL_ECC_SECP256R1:
  6900. curveId = ECC_SECP256R1;
  6901. break;
  6902. #endif /* !NO_ECC_SECP */
  6903. #ifdef WOLFSSL_SM2
  6904. case WOLFSSL_ECC_SM2P256V1:
  6905. curveId = ECC_SM2P256V1;
  6906. break;
  6907. #endif
  6908. #endif
  6909. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  6910. #ifndef NO_ECC_SECP
  6911. case WOLFSSL_ECC_SECP384R1:
  6912. curveId = ECC_SECP384R1;
  6913. break;
  6914. #endif /* !NO_ECC_SECP */
  6915. #endif
  6916. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  6917. #ifndef NO_ECC_SECP
  6918. case WOLFSSL_ECC_SECP521R1:
  6919. curveId = ECC_SECP521R1;
  6920. break;
  6921. #endif /* !NO_ECC_SECP */
  6922. #endif
  6923. #if defined(HAVE_X448) && ECC_MIN_KEY_SZ <= 448
  6924. case WOLFSSL_ECC_X448:
  6925. curveId = ECC_X448;
  6926. break;
  6927. #endif
  6928. default:
  6929. /* unsupported curve */
  6930. WOLFSSL_ERROR_VERBOSE(ECC_PEERKEY_ERROR);
  6931. return ECC_PEERKEY_ERROR;
  6932. }
  6933. #ifdef WOLFSSL_ASYNC_CRYPT
  6934. if (keyShareEntry->lastRet == 0) /* don't enter here if WC_PENDING_E */
  6935. #endif
  6936. {
  6937. #ifdef WOLFSSL_DEBUG_TLS
  6938. WOLFSSL_MSG("Peer ECC Key");
  6939. WOLFSSL_BUFFER(keyShareEntry->ke, keyShareEntry->keLen);
  6940. #endif
  6941. if (ssl->peerEccKey != NULL) {
  6942. wc_ecc_free(ssl->peerEccKey);
  6943. XFREE(ssl->peerEccKey, ssl->heap, DYNAMIC_TYPE_ECC);
  6944. ssl->peerEccKeyPresent = 0;
  6945. }
  6946. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  6947. ret = tsip_Tls13GenSharedSecret(ssl, keyShareEntry);
  6948. if (ret != CRYPTOCB_UNAVAILABLE) {
  6949. return ret;
  6950. }
  6951. ret = 0;
  6952. #endif
  6953. ssl->peerEccKey = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
  6954. DYNAMIC_TYPE_ECC);
  6955. if (ssl->peerEccKey == NULL) {
  6956. WOLFSSL_MSG("PeerEccKey Memory error");
  6957. ret = MEMORY_ERROR;
  6958. }
  6959. if (ret == 0) {
  6960. ret = wc_ecc_init_ex(ssl->peerEccKey, ssl->heap, ssl->devId);
  6961. }
  6962. /* Point is validated by import function. */
  6963. if (ret == 0) {
  6964. ret = wc_ecc_import_x963_ex(keyShareEntry->ke, keyShareEntry->keLen,
  6965. ssl->peerEccKey, curveId);
  6966. if (ret != 0) {
  6967. ret = ECC_PEERKEY_ERROR;
  6968. WOLFSSL_ERROR_VERBOSE(ret);
  6969. }
  6970. }
  6971. if (ret == 0) {
  6972. ssl->ecdhCurveOID = ssl->peerEccKey->dp->oidSum;
  6973. ssl->peerEccKeyPresent = 1;
  6974. }
  6975. }
  6976. if (ret == 0 && eccKey == NULL)
  6977. ret = BAD_FUNC_ARG;
  6978. if (ret == 0) {
  6979. ret = EccSharedSecret(ssl, eccKey, ssl->peerEccKey,
  6980. keyShareEntry->ke, &keyShareEntry->keLen,
  6981. ssl->arrays->preMasterSecret, &ssl->arrays->preMasterSz,
  6982. ssl->options.side
  6983. );
  6984. #ifdef WOLFSSL_ASYNC_CRYPT
  6985. if (ret == WC_PENDING_E)
  6986. return ret;
  6987. #endif
  6988. }
  6989. /* done with key share, release resources */
  6990. if (ssl->peerEccKey != NULL
  6991. #ifdef HAVE_PK_CALLBACKS
  6992. && ssl->ctx->EccSharedSecretCb == NULL
  6993. #endif
  6994. ) {
  6995. wc_ecc_free(ssl->peerEccKey);
  6996. XFREE(ssl->peerEccKey, ssl->heap, DYNAMIC_TYPE_ECC);
  6997. ssl->peerEccKey = NULL;
  6998. ssl->peerEccKeyPresent = 0;
  6999. }
  7000. if (keyShareEntry->key) {
  7001. wc_ecc_free((ecc_key*)keyShareEntry->key);
  7002. XFREE(keyShareEntry->key, ssl->heap, DYNAMIC_TYPE_ECC);
  7003. keyShareEntry->key = NULL;
  7004. }
  7005. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7006. keyShareEntry->ke = NULL;
  7007. #else
  7008. (void)ssl;
  7009. (void)keyShareEntry;
  7010. ret = PEER_KEY_ERROR;
  7011. WOLFSSL_ERROR_VERBOSE(ret);
  7012. #endif /* HAVE_ECC */
  7013. return ret;
  7014. }
  7015. #ifdef HAVE_PQC
  7016. /* Process the Kyber key share extension on the client side.
  7017. *
  7018. * ssl The SSL/TLS object.
  7019. * keyShareEntry The key share entry object to use to calculate shared secret.
  7020. * returns 0 on success and other values indicate failure.
  7021. */
  7022. static int TLSX_KeyShare_ProcessPqc(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  7023. {
  7024. int ret = 0;
  7025. int type;
  7026. KyberKey kem[1];
  7027. byte* sharedSecret = NULL;
  7028. word32 sharedSecretLen = 0;
  7029. int oqs_group = 0;
  7030. int ecc_group = 0;
  7031. ecc_key eccpubkey;
  7032. word32 outlen = 0;
  7033. word32 privSz = 0;
  7034. word32 ctSz = 0;
  7035. word32 ssSz = 0;
  7036. if (keyShareEntry->ke == NULL) {
  7037. WOLFSSL_MSG("Invalid OQS algorithm specified.");
  7038. return BAD_FUNC_ARG;
  7039. }
  7040. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7041. /* I am the server, the shared secret has already been generated and
  7042. * is in keyShareEntry->ke; copy it to the pre-master secret
  7043. * pre-allocated buffer. */
  7044. if (keyShareEntry->keLen > ENCRYPT_LEN) {
  7045. WOLFSSL_MSG("shared secret is too long.");
  7046. return LENGTH_ERROR;
  7047. }
  7048. XMEMCPY(ssl->arrays->preMasterSecret, keyShareEntry->ke,
  7049. keyShareEntry->keLen);
  7050. ssl->arrays->preMasterSz = keyShareEntry->keLen;
  7051. XFREE(keyShareEntry->ke, sl->heap, DYNAMIC_TYPE_SECRET)
  7052. keyShareEntry->ke = NULL;
  7053. keyShareEntry->keLen = 0;
  7054. return 0;
  7055. }
  7056. /* I am the client, the ciphertext is in keyShareEntry->ke */
  7057. findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group);
  7058. ret = kyber_id2type(oqs_group, &type);
  7059. if (ret != 0) {
  7060. WOLFSSL_MSG("Invalid OQS algorithm specified.");
  7061. ret = BAD_FUNC_ARG;
  7062. }
  7063. if (ret == 0) {
  7064. ret = wc_KyberKey_Init(type, kem, ssl->heap, INVALID_DEVID);
  7065. if (ret != 0) {
  7066. WOLFSSL_MSG("Error creating Kyber KEM");
  7067. }
  7068. }
  7069. if (ret == 0) {
  7070. ret = wc_KyberKey_SharedSecretSize(kem, &ssSz);
  7071. }
  7072. if (ret == 0) {
  7073. sharedSecretLen = ssSz;
  7074. switch (ecc_group) {
  7075. case WOLFSSL_ECC_SECP256R1:
  7076. sharedSecretLen += 32;
  7077. outlen = 32;
  7078. break;
  7079. case WOLFSSL_ECC_SECP384R1:
  7080. sharedSecretLen += 48;
  7081. outlen = 48;
  7082. break;
  7083. case WOLFSSL_ECC_SECP521R1:
  7084. sharedSecretLen += 66;
  7085. outlen = 66;
  7086. break;
  7087. default:
  7088. break;
  7089. }
  7090. ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId);
  7091. if (ret != 0) {
  7092. WOLFSSL_MSG("Memory allocation error.");
  7093. ret = MEMORY_E;
  7094. }
  7095. }
  7096. if (ret == 0) {
  7097. sharedSecret = (byte*)XMALLOC(sharedSecretLen, ssl->heap,
  7098. DYNAMIC_TYPE_TLSX);
  7099. if (sharedSecret == NULL) {
  7100. WOLFSSL_MSG("Memory allocation error.");
  7101. ret = MEMORY_E;
  7102. }
  7103. }
  7104. if (ret == 0) {
  7105. ret = wc_KyberKey_CipherTextSize(kem, &ctSz);
  7106. }
  7107. if (ret == 0) {
  7108. ret = wc_KyberKey_PrivateKeySize(kem, &privSz);
  7109. }
  7110. if (ret == 0) {
  7111. ret = wc_KyberKey_DecodePrivateKey(kem, keyShareEntry->privKey, privSz);
  7112. }
  7113. if (ret == 0) {
  7114. ret = wc_KyberKey_Decapsulate(kem, sharedSecret + outlen,
  7115. keyShareEntry->ke + keyShareEntry->keLen - ctSz, ctSz);
  7116. if (ret != 0) {
  7117. WOLFSSL_MSG("wc_KyberKey decapsulation failure.");
  7118. ret = BAD_FUNC_ARG;
  7119. }
  7120. }
  7121. if (ecc_group != 0) {
  7122. if (ret == 0) {
  7123. /* Point is validated by import function. */
  7124. ret = wc_ecc_import_x963(keyShareEntry->ke,
  7125. keyShareEntry->keLen - ctSz,
  7126. &eccpubkey);
  7127. if (ret != 0) {
  7128. WOLFSSL_MSG("ECC Public key import error.");
  7129. }
  7130. }
  7131. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  7132. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  7133. !defined(HAVE_SELFTEST)
  7134. if (ret == 0) {
  7135. ret = wc_ecc_set_rng(keyShareEntry->key, ssl->rng);
  7136. if (ret != 0) {
  7137. WOLFSSL_MSG("Failure to set the ECC private key RNG.");
  7138. }
  7139. }
  7140. #endif
  7141. if (ret == 0) {
  7142. PRIVATE_KEY_UNLOCK();
  7143. ret = wc_ecc_shared_secret(keyShareEntry->key, &eccpubkey,
  7144. sharedSecret, &outlen);
  7145. PRIVATE_KEY_LOCK();
  7146. if (outlen != sharedSecretLen - ssSz) {
  7147. WOLFSSL_MSG("ECC shared secret derivation error.");
  7148. ret = BAD_FUNC_ARG;
  7149. }
  7150. }
  7151. }
  7152. if ((ret == 0) && (sharedSecretLen > ENCRYPT_LEN)) {
  7153. WOLFSSL_MSG("shared secret is too long.");
  7154. ret = LENGTH_ERROR;
  7155. }
  7156. if (ret == 0) {
  7157. /* Copy the shared secret to the pre-master secret pre-allocated
  7158. * buffer. */
  7159. XMEMCPY(ssl->arrays->preMasterSecret, sharedSecret, sharedSecretLen);
  7160. ssl->arrays->preMasterSz = (word32) sharedSecretLen;
  7161. }
  7162. if (sharedSecret != NULL) {
  7163. XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  7164. }
  7165. wc_ecc_free(&eccpubkey);
  7166. wc_KyberKey_Free(kem);
  7167. return ret;
  7168. }
  7169. #endif /* HAVE_PQC */
  7170. /* Process the key share extension on the client side.
  7171. *
  7172. * ssl The SSL/TLS object.
  7173. * keyShareEntry The key share entry object to use to calculate shared secret.
  7174. * returns 0 on success and other values indicate failure.
  7175. */
  7176. static int TLSX_KeyShare_Process(WOLFSSL* ssl, KeyShareEntry* keyShareEntry)
  7177. {
  7178. int ret;
  7179. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  7180. ssl->session->namedGroup = keyShareEntry->group;
  7181. #endif
  7182. /* reset the pre master secret size */
  7183. if (ssl->arrays->preMasterSz == 0)
  7184. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  7185. /* Use Key Share Data from server. */
  7186. if (WOLFSSL_NAMED_GROUP_IS_FFHDE(keyShareEntry->group))
  7187. ret = TLSX_KeyShare_ProcessDh(ssl, keyShareEntry);
  7188. else if (keyShareEntry->group == WOLFSSL_ECC_X25519)
  7189. ret = TLSX_KeyShare_ProcessX25519(ssl, keyShareEntry);
  7190. else if (keyShareEntry->group == WOLFSSL_ECC_X448)
  7191. ret = TLSX_KeyShare_ProcessX448(ssl, keyShareEntry);
  7192. #ifdef HAVE_PQC
  7193. else if (WOLFSSL_NAMED_GROUP_IS_PQC(keyShareEntry->group))
  7194. ret = TLSX_KeyShare_ProcessPqc(ssl, keyShareEntry);
  7195. #endif
  7196. else
  7197. ret = TLSX_KeyShare_ProcessEcc(ssl, keyShareEntry);
  7198. #ifdef WOLFSSL_DEBUG_TLS
  7199. if (ret == 0) {
  7200. WOLFSSL_MSG("KE Secret");
  7201. WOLFSSL_BUFFER(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  7202. }
  7203. #endif
  7204. #ifdef WOLFSSL_ASYNC_CRYPT
  7205. keyShareEntry->lastRet = ret;
  7206. #endif
  7207. return ret;
  7208. }
  7209. /* Parse an entry of the KeyShare extension.
  7210. *
  7211. * ssl The SSL/TLS object.
  7212. * input The extension data.
  7213. * length The length of the extension data.
  7214. * kse The new key share entry object.
  7215. * returns a positive number to indicate amount of data parsed and a negative
  7216. * number on error.
  7217. */
  7218. static int TLSX_KeyShareEntry_Parse(const WOLFSSL* ssl, const byte* input,
  7219. word16 length, KeyShareEntry **kse, TLSX** extensions)
  7220. {
  7221. int ret;
  7222. word16 group;
  7223. word16 keLen;
  7224. int offset = 0;
  7225. byte* ke;
  7226. if (length < OPAQUE16_LEN + OPAQUE16_LEN)
  7227. return BUFFER_ERROR;
  7228. /* Named group */
  7229. ato16(&input[offset], &group);
  7230. offset += OPAQUE16_LEN;
  7231. /* Key exchange data - public key. */
  7232. ato16(&input[offset], &keLen);
  7233. offset += OPAQUE16_LEN;
  7234. if (keLen == 0)
  7235. return INVALID_PARAMETER;
  7236. if (keLen > length - offset)
  7237. return BUFFER_ERROR;
  7238. #ifdef HAVE_PQC
  7239. if (WOLFSSL_NAMED_GROUP_IS_PQC(group) &&
  7240. ssl->options.side == WOLFSSL_SERVER_END) {
  7241. /* For KEMs, the public key is not stored. Casting away const because
  7242. * we know for KEMs, it will be read-only.*/
  7243. ke = (byte *)&input[offset];
  7244. } else
  7245. #endif
  7246. {
  7247. /* Store a copy in the key share object. */
  7248. ke = (byte*)XMALLOC(keLen, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7249. if (ke == NULL)
  7250. return MEMORY_E;
  7251. XMEMCPY(ke, &input[offset], keLen);
  7252. }
  7253. /* Populate a key share object in the extension. */
  7254. ret = TLSX_KeyShare_Use(ssl, group, keLen, ke, kse, extensions);
  7255. if (ret != 0) {
  7256. if (ke != &input[offset]) {
  7257. XFREE(ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7258. }
  7259. return ret;
  7260. }
  7261. /* Total length of the parsed data. */
  7262. return offset + keLen;
  7263. }
  7264. /* Searches the groups sent for the specified named group.
  7265. *
  7266. * ssl SSL/TLS object.
  7267. * name Group name to match.
  7268. * returns 1 when the extension has the group name and 0 otherwise.
  7269. */
  7270. static int TLSX_KeyShare_Find(WOLFSSL* ssl, word16 group)
  7271. {
  7272. TLSX* extension;
  7273. KeyShareEntry* list;
  7274. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  7275. if (extension == NULL) {
  7276. extension = TLSX_Find(ssl->ctx->extensions, TLSX_KEY_SHARE);
  7277. if (extension == NULL)
  7278. return 0;
  7279. }
  7280. list = (KeyShareEntry*)extension->data;
  7281. while (list != NULL) {
  7282. if (list->group == group)
  7283. return 1;
  7284. list = list->next;
  7285. }
  7286. return 0;
  7287. }
  7288. /* Searches the supported groups extension for the specified named group.
  7289. *
  7290. * ssl The SSL/TLS object.
  7291. * name The group name to match.
  7292. * returns 1 when the extension has the group name and 0 otherwise.
  7293. */
  7294. static int TLSX_SupportedGroups_Find(const WOLFSSL* ssl, word16 name,
  7295. TLSX* extensions)
  7296. {
  7297. #ifdef HAVE_SUPPORTED_CURVES
  7298. TLSX* extension;
  7299. SupportedCurve* curve = NULL;
  7300. if ((extension = TLSX_Find(extensions,
  7301. TLSX_SUPPORTED_GROUPS)) == NULL) {
  7302. if ((extension = TLSX_Find(ssl->ctx->extensions,
  7303. TLSX_SUPPORTED_GROUPS)) == NULL) {
  7304. return 0;
  7305. }
  7306. }
  7307. for (curve = (SupportedCurve*)extension->data; curve; curve = curve->next) {
  7308. if (curve->name == name)
  7309. return 1;
  7310. }
  7311. #endif
  7312. (void)ssl;
  7313. (void)name;
  7314. return 0;
  7315. }
  7316. int TLSX_KeyShare_Parse_ClientHello(const WOLFSSL* ssl,
  7317. const byte* input, word16 length, TLSX** extensions)
  7318. {
  7319. int ret;
  7320. int offset = 0;
  7321. word16 len;
  7322. TLSX* extension;
  7323. /* Add a KeyShare extension if it doesn't exist even if peer sent no
  7324. * entries. The presence of this extension signals that the peer can be
  7325. * negotiated with. */
  7326. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7327. if (extension == NULL) {
  7328. /* Push new KeyShare extension. */
  7329. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7330. if (ret != 0)
  7331. return ret;
  7332. }
  7333. if (length < OPAQUE16_LEN)
  7334. return BUFFER_ERROR;
  7335. /* ClientHello contains zero or more key share entries. */
  7336. ato16(input, &len);
  7337. if (len != length - OPAQUE16_LEN)
  7338. return BUFFER_ERROR;
  7339. offset += OPAQUE16_LEN;
  7340. while (offset < (int)length) {
  7341. ret = TLSX_KeyShareEntry_Parse(ssl, &input[offset],
  7342. length - (word16)offset, NULL, extensions);
  7343. if (ret < 0)
  7344. return ret;
  7345. offset += ret;
  7346. }
  7347. return 0;
  7348. }
  7349. /* Parse the KeyShare extension.
  7350. * Different formats in different messages.
  7351. *
  7352. * ssl The SSL/TLS object.
  7353. * input The extension data.
  7354. * length The length of the extension data.
  7355. * msgType The type of the message this extension is being parsed from.
  7356. * returns 0 on success and other values indicate failure.
  7357. */
  7358. int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  7359. byte msgType)
  7360. {
  7361. int ret;
  7362. KeyShareEntry *keyShareEntry = NULL;
  7363. word16 group;
  7364. if (msgType == client_hello) {
  7365. ret = TLSX_KeyShare_Parse_ClientHello(ssl, input, length,
  7366. &ssl->extensions);
  7367. }
  7368. else if (msgType == server_hello) {
  7369. int len;
  7370. if (length < OPAQUE16_LEN)
  7371. return BUFFER_ERROR;
  7372. /* The data is the named group the server wants to use. */
  7373. ato16(input, &group);
  7374. /* Check the selected group was supported by ClientHello extensions. */
  7375. if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) {
  7376. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7377. return BAD_KEY_SHARE_DATA;
  7378. }
  7379. /* Check if the group was sent. */
  7380. if (!TLSX_KeyShare_Find(ssl, group)) {
  7381. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7382. return BAD_KEY_SHARE_DATA;
  7383. }
  7384. /* ServerHello contains one key share entry. */
  7385. len = TLSX_KeyShareEntry_Parse(ssl, input, length, &keyShareEntry,
  7386. &ssl->extensions);
  7387. if (len != (int)length)
  7388. return BUFFER_ERROR;
  7389. /* Not in list sent if there isn't a private key. */
  7390. if (keyShareEntry == NULL || (keyShareEntry->key == NULL
  7391. #if !defined(NO_DH) || defined(HAVE_PQC)
  7392. && keyShareEntry->privKey == NULL
  7393. #endif
  7394. )) {
  7395. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7396. return BAD_KEY_SHARE_DATA;
  7397. }
  7398. /* Process the entry to calculate the secret. */
  7399. ret = TLSX_KeyShare_Process(ssl, keyShareEntry);
  7400. if (ret == 0)
  7401. ssl->session->namedGroup = ssl->namedGroup = group;
  7402. }
  7403. else if (msgType == hello_retry_request) {
  7404. if (length != OPAQUE16_LEN)
  7405. return BUFFER_ERROR;
  7406. /* The data is the named group the server wants to use. */
  7407. ato16(input, &group);
  7408. #ifdef WOLFSSL_ASYNC_CRYPT
  7409. /* only perform find and clear TLSX if not returning from async */
  7410. if (ssl->error != WC_PENDING_E)
  7411. #endif
  7412. {
  7413. /* Check the selected group was supported by ClientHello extensions. */
  7414. if (!TLSX_SupportedGroups_Find(ssl, group, ssl->extensions)) {
  7415. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7416. return BAD_KEY_SHARE_DATA;
  7417. }
  7418. /* Check if the group was sent. */
  7419. if (TLSX_KeyShare_Find(ssl, group)) {
  7420. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7421. return BAD_KEY_SHARE_DATA;
  7422. }
  7423. /* Clear out unusable key shares. */
  7424. ret = TLSX_KeyShare_Empty(ssl);
  7425. if (ret != 0)
  7426. return ret;
  7427. }
  7428. #ifdef HAVE_PQC
  7429. /* For post-quantum groups, do this in TLSX_PopulateExtensions(). */
  7430. if (!WOLFSSL_NAMED_GROUP_IS_PQC(group))
  7431. #endif
  7432. ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL, &ssl->extensions);
  7433. if (ret == 0)
  7434. ssl->session->namedGroup = ssl->namedGroup = group;
  7435. }
  7436. else {
  7437. /* Not a message type that is allowed to have this extension. */
  7438. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  7439. return SANITY_MSG_E;
  7440. }
  7441. return ret;
  7442. }
  7443. /* Create a new key share entry and put it into the list.
  7444. *
  7445. * list The linked list of key share entries.
  7446. * group The named group.
  7447. * heap The memory to allocate with.
  7448. * keyShareEntry The new key share entry object.
  7449. * returns 0 on success and other values indicate failure.
  7450. */
  7451. static int TLSX_KeyShare_New(KeyShareEntry** list, int group, void *heap,
  7452. KeyShareEntry** keyShareEntry)
  7453. {
  7454. KeyShareEntry* kse;
  7455. KeyShareEntry** next;
  7456. kse = (KeyShareEntry*)XMALLOC(sizeof(KeyShareEntry), heap,
  7457. DYNAMIC_TYPE_TLSX);
  7458. if (kse == NULL)
  7459. return MEMORY_E;
  7460. XMEMSET(kse, 0, sizeof(*kse));
  7461. kse->group = (word16)group;
  7462. /* Add it to the back and maintain the links. */
  7463. while (*list != NULL) {
  7464. /* Assign to temporary to work around compiler bug found by customer. */
  7465. next = &((*list)->next);
  7466. list = next;
  7467. }
  7468. *list = kse;
  7469. *keyShareEntry = kse;
  7470. (void)heap;
  7471. return 0;
  7472. }
  7473. #ifdef HAVE_PQC
  7474. static int server_generate_pqc_ciphertext(WOLFSSL* ssl,
  7475. KeyShareEntry* keyShareEntry, byte* data, word16 len)
  7476. {
  7477. /* I am the server. The data parameter is the client's public key. I need
  7478. * to generate the public information (AKA ciphertext) and shared secret
  7479. * here. Note the "public information" is equivalent to a the public key in
  7480. * key exchange parlance. That's why it is being assigned to pubKey.
  7481. */
  7482. int type;
  7483. KyberKey kem[1];
  7484. byte* sharedSecret = NULL;
  7485. byte* ciphertext = NULL;
  7486. int ret = 0;
  7487. int oqs_group = 0;
  7488. int ecc_group = 0;
  7489. KeyShareEntry *ecc_kse = NULL;
  7490. ecc_key eccpubkey;
  7491. word32 outlen = 0;
  7492. word32 pubSz = 0;
  7493. word32 ctSz = 0;
  7494. word32 ssSz = 0;
  7495. findEccPqc(&ecc_group, &oqs_group, keyShareEntry->group);
  7496. ret = kyber_id2type(oqs_group, &type);
  7497. if (ret != 0) {
  7498. WOLFSSL_MSG("Invalid Kyber algorithm specified.");
  7499. ret = BAD_FUNC_ARG;
  7500. }
  7501. if (ret == 0) {
  7502. ret = wc_ecc_init_ex(&eccpubkey, ssl->heap, ssl->devId);
  7503. if (ret != 0) {
  7504. WOLFSSL_MSG("Could not do ECC public key initialization.");
  7505. ret = MEMORY_E;
  7506. }
  7507. }
  7508. if (ret == 0) {
  7509. ecc_kse = (KeyShareEntry*)XMALLOC(sizeof(*ecc_kse), ssl->heap,
  7510. DYNAMIC_TYPE_TLSX);
  7511. if (ecc_kse == NULL) {
  7512. WOLFSSL_MSG("ecc_kse memory allocation failure");
  7513. ret = MEMORY_ERROR;
  7514. }
  7515. }
  7516. if (ret == 0) {
  7517. XMEMSET(ecc_kse, 0, sizeof(*ecc_kse));
  7518. }
  7519. if (ret == 0 && ecc_group != 0) {
  7520. ecc_kse->group = ecc_group;
  7521. ret = TLSX_KeyShare_GenEccKey(ssl, ecc_kse);
  7522. if (ret != 0) {
  7523. /* No message, TLSX_KeyShare_GenEccKey() will do it. */
  7524. return ret;
  7525. }
  7526. ret = 0;
  7527. }
  7528. if (ret == 0) {
  7529. ret = wc_KyberKey_Init(type, kem, ssl->heap, INVALID_DEVID);
  7530. if (ret != 0) {
  7531. WOLFSSL_MSG("Error creating Kyber KEM");
  7532. }
  7533. }
  7534. if (ret == 0) {
  7535. ret = wc_KyberKey_PublicKeySize(kem, &pubSz);
  7536. }
  7537. if (ret == 0) {
  7538. ret = wc_KyberKey_CipherTextSize(kem, &ctSz);
  7539. }
  7540. if (ret == 0) {
  7541. ret = wc_KyberKey_SharedSecretSize(kem, &ssSz);
  7542. }
  7543. if (ret == 0 && len != pubSz + ecc_kse->pubKeyLen) {
  7544. WOLFSSL_MSG("Invalid public key.");
  7545. ret = BAD_FUNC_ARG;
  7546. }
  7547. if (ret == 0) {
  7548. sharedSecret = (byte*)XMALLOC(ecc_kse->keyLen + ssSz, ssl->heap,
  7549. DYNAMIC_TYPE_TLSX);
  7550. ciphertext = (byte*)XMALLOC(ecc_kse->pubKeyLen + ctSz, ssl->heap,
  7551. DYNAMIC_TYPE_TLSX);
  7552. if (sharedSecret == NULL || ciphertext == NULL) {
  7553. WOLFSSL_MSG("Ciphertext/shared secret memory allocation failure.");
  7554. ret = MEMORY_E;
  7555. }
  7556. }
  7557. if (ecc_group != 0) {
  7558. if (ret == 0) {
  7559. /* Point is validated by import function. */
  7560. ret = wc_ecc_import_x963(data, len - pubSz, &eccpubkey);
  7561. if (ret != 0) {
  7562. WOLFSSL_MSG("Bad ECC public key.");
  7563. }
  7564. }
  7565. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  7566. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  7567. !defined(HAVE_SELFTEST)
  7568. if (ret == 0) {
  7569. ret = wc_ecc_set_rng(ecc_kse->key, ssl->rng);
  7570. }
  7571. #endif
  7572. if (ret == 0) {
  7573. outlen = ecc_kse->keyLen;
  7574. PRIVATE_KEY_UNLOCK();
  7575. ret = wc_ecc_shared_secret(ecc_kse->key, &eccpubkey,
  7576. sharedSecret,
  7577. &outlen);
  7578. PRIVATE_KEY_LOCK();
  7579. if (outlen != ecc_kse->keyLen) {
  7580. WOLFSSL_MSG("Data length mismatch.");
  7581. ret = BAD_FUNC_ARG;
  7582. }
  7583. }
  7584. }
  7585. if (ret == 0) {
  7586. ret = wc_KyberKey_DecodePublicKey(kem, data + ecc_kse->pubKeyLen,
  7587. pubSz);
  7588. }
  7589. if (ret == 0) {
  7590. ret = wc_KyberKey_Encapsulate(kem, ciphertext + ecc_kse->pubKeyLen,
  7591. sharedSecret + outlen, ssl->rng);
  7592. if (ret != 0) {
  7593. WOLFSSL_MSG("wc_KyberKey encapsulation failure.");
  7594. }
  7595. }
  7596. if (ret == 0) {
  7597. if (keyShareEntry->ke != NULL) {
  7598. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7599. }
  7600. keyShareEntry->ke = sharedSecret;
  7601. keyShareEntry->keLen = outlen + ssSz;
  7602. sharedSecret = NULL;
  7603. XMEMCPY(ciphertext, ecc_kse->pubKey, ecc_kse->pubKeyLen);
  7604. keyShareEntry->pubKey = ciphertext;
  7605. keyShareEntry->pubKeyLen = (word32)(ecc_kse->pubKeyLen + ctSz);
  7606. ciphertext = NULL;
  7607. }
  7608. TLSX_KeyShare_FreeAll(ecc_kse, ssl->heap);
  7609. if (sharedSecret != NULL)
  7610. XFREE(sharedSecret, ssl->heap, DYNAMIC_TYPE_TLSX);
  7611. if (ciphertext != NULL)
  7612. XFREE(ciphertext, ssl->heap, DYNAMIC_TYPE_TLSX);
  7613. wc_ecc_free(&eccpubkey);
  7614. wc_KyberKey_Free(kem);
  7615. return ret;
  7616. }
  7617. #endif /* HAVE_PQC */
  7618. /* Use the data to create a new key share object in the extensions.
  7619. *
  7620. * ssl The SSL/TLS object.
  7621. * group The named group.
  7622. * len The length of the public key data.
  7623. * data The public key data.
  7624. * kse The new key share entry object.
  7625. * returns 0 on success and other values indicate failure.
  7626. */
  7627. int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group, word16 len, byte* data,
  7628. KeyShareEntry **kse, TLSX** extensions)
  7629. {
  7630. int ret = 0;
  7631. TLSX* extension;
  7632. KeyShareEntry* keyShareEntry = NULL;
  7633. /* Find the KeyShare extension if it exists. */
  7634. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7635. if (extension == NULL) {
  7636. /* Push new KeyShare extension. */
  7637. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7638. if (ret != 0)
  7639. return ret;
  7640. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7641. if (extension == NULL)
  7642. return MEMORY_E;
  7643. }
  7644. extension->resp = 0;
  7645. /* Try to find the key share entry with this group. */
  7646. keyShareEntry = (KeyShareEntry*)extension->data;
  7647. while (keyShareEntry != NULL) {
  7648. if (keyShareEntry->group == group)
  7649. break;
  7650. keyShareEntry = keyShareEntry->next;
  7651. }
  7652. /* Create a new key share entry if not found. */
  7653. if (keyShareEntry == NULL) {
  7654. ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, group,
  7655. ssl->heap, &keyShareEntry);
  7656. if (ret != 0)
  7657. return ret;
  7658. }
  7659. #ifdef HAVE_PQC
  7660. if (WOLFSSL_NAMED_GROUP_IS_PQC(group) &&
  7661. ssl->options.side == WOLFSSL_SERVER_END) {
  7662. ret = server_generate_pqc_ciphertext((WOLFSSL*)ssl, keyShareEntry, data,
  7663. len);
  7664. if (ret != 0)
  7665. return ret;
  7666. }
  7667. else
  7668. #endif
  7669. if (data != NULL) {
  7670. if (keyShareEntry->ke != NULL) {
  7671. XFREE(keyShareEntry->ke, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7672. }
  7673. keyShareEntry->ke = data;
  7674. keyShareEntry->keLen = len;
  7675. }
  7676. else {
  7677. /* Generate a key pair. Casting to non-const since changes inside are
  7678. * minimal but would require an extensive redesign to refactor. Also
  7679. * this path shouldn't be taken when parsing a ClientHello in stateless
  7680. * mode. */
  7681. ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, keyShareEntry);
  7682. if (ret != 0)
  7683. return ret;
  7684. }
  7685. if (kse != NULL)
  7686. *kse = keyShareEntry;
  7687. return 0;
  7688. }
  7689. /* Set an empty Key Share extension.
  7690. *
  7691. * ssl The SSL/TLS object.
  7692. * returns 0 on success and other values indicate failure.
  7693. */
  7694. int TLSX_KeyShare_Empty(WOLFSSL* ssl)
  7695. {
  7696. int ret = 0;
  7697. TLSX* extension;
  7698. /* Find the KeyShare extension if it exists. */
  7699. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  7700. if (extension == NULL) {
  7701. /* Push new KeyShare extension. */
  7702. ret = TLSX_Push(&ssl->extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  7703. }
  7704. else if (extension->data != NULL) {
  7705. TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap);
  7706. extension->data = NULL;
  7707. }
  7708. return ret;
  7709. }
  7710. /* Returns whether this group is supported.
  7711. *
  7712. * namedGroup The named group to check.
  7713. * returns 1 when supported or 0 otherwise.
  7714. */
  7715. static int TLSX_KeyShare_IsSupported(int namedGroup)
  7716. {
  7717. switch (namedGroup) {
  7718. #ifdef HAVE_FFDHE_2048
  7719. case WOLFSSL_FFDHE_2048:
  7720. break;
  7721. #endif
  7722. #ifdef HAVE_FFDHE_3072
  7723. case WOLFSSL_FFDHE_3072:
  7724. break;
  7725. #endif
  7726. #ifdef HAVE_FFDHE_4096
  7727. case WOLFSSL_FFDHE_4096:
  7728. break;
  7729. #endif
  7730. #ifdef HAVE_FFDHE_6144
  7731. case WOLFSSL_FFDHE_6144:
  7732. break;
  7733. #endif
  7734. #ifdef HAVE_FFDHE_8192
  7735. case WOLFSSL_FFDHE_8192:
  7736. break;
  7737. #endif
  7738. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  7739. #ifdef HAVE_ECC_KOBLITZ
  7740. case WOLFSSL_ECC_SECP256K1:
  7741. break;
  7742. #endif
  7743. #ifndef NO_ECC_SECP
  7744. case WOLFSSL_ECC_SECP256R1:
  7745. break;
  7746. #endif /* !NO_ECC_SECP */
  7747. #ifdef HAVE_ECC_BRAINPOOL
  7748. case WOLFSSL_ECC_BRAINPOOLP256R1:
  7749. break;
  7750. #endif
  7751. #ifdef WOLFSSL_SM2
  7752. case WOLFSSL_ECC_SM2P256V1:
  7753. break;
  7754. #endif /* WOLFSSL_SM2 */
  7755. #endif
  7756. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  7757. case WOLFSSL_ECC_X25519:
  7758. break;
  7759. #endif
  7760. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  7761. case WOLFSSL_ECC_X448:
  7762. break;
  7763. #endif
  7764. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  7765. #ifndef NO_ECC_SECP
  7766. case WOLFSSL_ECC_SECP384R1:
  7767. break;
  7768. #endif /* !NO_ECC_SECP */
  7769. #ifdef HAVE_ECC_BRAINPOOL
  7770. case WOLFSSL_ECC_BRAINPOOLP384R1:
  7771. break;
  7772. #endif
  7773. #endif
  7774. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  7775. #ifndef NO_ECC_SECP
  7776. case WOLFSSL_ECC_SECP521R1:
  7777. break;
  7778. #endif /* !NO_ECC_SECP */
  7779. #endif
  7780. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  7781. #ifdef HAVE_ECC_KOBLITZ
  7782. case WOLFSSL_ECC_SECP160K1:
  7783. break;
  7784. #endif
  7785. #ifndef NO_ECC_SECP
  7786. case WOLFSSL_ECC_SECP160R1:
  7787. break;
  7788. #endif
  7789. #ifdef HAVE_ECC_SECPR2
  7790. case WOLFSSL_ECC_SECP160R2:
  7791. break;
  7792. #endif
  7793. #endif
  7794. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  7795. #ifdef HAVE_ECC_KOBLITZ
  7796. case WOLFSSL_ECC_SECP192K1:
  7797. break;
  7798. #endif
  7799. #ifndef NO_ECC_SECP
  7800. case WOLFSSL_ECC_SECP192R1:
  7801. break;
  7802. #endif
  7803. #endif
  7804. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  7805. #ifdef HAVE_ECC_KOBLITZ
  7806. case WOLFSSL_ECC_SECP224K1:
  7807. break;
  7808. #endif
  7809. #ifndef NO_ECC_SECP
  7810. case WOLFSSL_ECC_SECP224R1:
  7811. break;
  7812. #endif
  7813. #endif
  7814. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  7815. #ifdef HAVE_ECC_BRAINPOOL
  7816. case WOLFSSL_ECC_BRAINPOOLP512R1:
  7817. break;
  7818. #endif
  7819. #endif
  7820. #ifdef HAVE_PQC
  7821. #ifdef WOLFSSL_WC_KYBER
  7822. #ifdef WOLFSSL_KYBER512
  7823. case WOLFSSL_KYBER_LEVEL1:
  7824. #endif
  7825. #ifdef WOLFSSL_KYBER768
  7826. case WOLFSSL_KYBER_LEVEL3:
  7827. #endif
  7828. #ifdef WOLFSSL_KYBER1024
  7829. case WOLFSSL_KYBER_LEVEL5:
  7830. #endif
  7831. break;
  7832. #elif defined(HAVE_LIBOQS)
  7833. case WOLFSSL_KYBER_LEVEL1:
  7834. case WOLFSSL_KYBER_LEVEL3:
  7835. case WOLFSSL_KYBER_LEVEL5:
  7836. case WOLFSSL_P256_KYBER_LEVEL1:
  7837. case WOLFSSL_P384_KYBER_LEVEL3:
  7838. case WOLFSSL_P521_KYBER_LEVEL5:
  7839. {
  7840. int ret;
  7841. int id;
  7842. findEccPqc(NULL, &namedGroup, namedGroup);
  7843. ret = kyber_id2type(namedGroup, &id);
  7844. if (ret == NOT_COMPILED_IN) {
  7845. return 0;
  7846. }
  7847. if (! ext_kyber_enabled(id)) {
  7848. return 0;
  7849. }
  7850. break;
  7851. }
  7852. #elif defined(HAVE_PQM4)
  7853. case WOLFSSL_KYBER_LEVEL1:
  7854. break;
  7855. #endif
  7856. #endif /* HAVE_PQC */
  7857. default:
  7858. return 0;
  7859. }
  7860. return 1;
  7861. }
  7862. static const word16 preferredGroup[] = {
  7863. #if defined(HAVE_ECC) && (!defined(NO_ECC256) || \
  7864. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 256
  7865. WOLFSSL_ECC_SECP256R1,
  7866. #if !defined(HAVE_FIPS) && defined(WOLFSSL_SM2)
  7867. WOLFSSL_ECC_SM2P256V1,
  7868. #endif
  7869. #endif
  7870. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  7871. WOLFSSL_ECC_X25519,
  7872. #endif
  7873. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  7874. WOLFSSL_ECC_X448,
  7875. #endif
  7876. #if defined(HAVE_ECC) && (!defined(NO_ECC384) || \
  7877. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 384
  7878. WOLFSSL_ECC_SECP384R1,
  7879. #endif
  7880. #if defined(HAVE_ECC) && (!defined(NO_ECC521) || \
  7881. defined(HAVE_ALL_CURVES)) && !defined(NO_ECC_SECP) && ECC_MIN_KEY_SZ <= 521
  7882. WOLFSSL_ECC_SECP521R1,
  7883. #endif
  7884. #if defined(HAVE_FFDHE_2048)
  7885. WOLFSSL_FFDHE_2048,
  7886. #endif
  7887. #if defined(HAVE_FFDHE_3072)
  7888. WOLFSSL_FFDHE_3072,
  7889. #endif
  7890. #if defined(HAVE_FFDHE_4096)
  7891. WOLFSSL_FFDHE_4096,
  7892. #endif
  7893. #if defined(HAVE_FFDHE_6144)
  7894. WOLFSSL_FFDHE_6144,
  7895. #endif
  7896. #if defined(HAVE_FFDHE_8192)
  7897. WOLFSSL_FFDHE_8192,
  7898. #endif
  7899. #ifdef WOLFSSL_WC_KYBER
  7900. #ifdef WOLFSSL_KYBER512
  7901. WOLFSSL_KYBER_LEVEL1,
  7902. #endif
  7903. #ifdef WOLFSSL_KYBER768
  7904. WOLFSSL_KYBER_LEVEL3,
  7905. #endif
  7906. #ifdef WOLFSSL_KYBER1024
  7907. WOLFSSL_KYBER_LEVEL5,
  7908. #endif
  7909. #elif defined(HAVE_LIBOQS)
  7910. /* These require a runtime call to TLSX_KeyShare_IsSupported to use */
  7911. WOLFSSL_KYBER_LEVEL1,
  7912. WOLFSSL_KYBER_LEVEL3,
  7913. WOLFSSL_KYBER_LEVEL5,
  7914. WOLFSSL_P256_KYBER_LEVEL1,
  7915. WOLFSSL_P384_KYBER_LEVEL3,
  7916. WOLFSSL_P521_KYBER_LEVEL5,
  7917. #elif defined(HAVE_PQM4)
  7918. WOLFSSL_KYBER_LEVEL1,
  7919. #endif
  7920. WOLFSSL_NAMED_GROUP_INVALID
  7921. };
  7922. #define PREFERRED_GROUP_SZ \
  7923. ((sizeof(preferredGroup)/sizeof(*preferredGroup)) - 1)
  7924. /* -1 for the invalid group */
  7925. /* Examines the application specified group ranking and returns the rank of the
  7926. * group.
  7927. * If no group ranking set then all groups are rank 0 (highest).
  7928. *
  7929. * ssl The SSL/TLS object.
  7930. * group The group to check ranking for.
  7931. * returns ranking from 0 to MAX_GROUP_COUNT-1 or -1 when group not in list.
  7932. */
  7933. static int TLSX_KeyShare_GroupRank(const WOLFSSL* ssl, int group)
  7934. {
  7935. byte i;
  7936. const word16* groups;
  7937. byte numGroups;
  7938. if (ssl->numGroups == 0) {
  7939. groups = preferredGroup;
  7940. numGroups = PREFERRED_GROUP_SZ;
  7941. }
  7942. else {
  7943. groups = ssl->group;
  7944. numGroups = ssl->numGroups;
  7945. }
  7946. #ifdef HAVE_LIBOQS
  7947. if (!TLSX_KeyShare_IsSupported(group))
  7948. return -1;
  7949. #endif
  7950. for (i = 0; i < numGroups; i++)
  7951. if (groups[i] == (word16)group)
  7952. return i;
  7953. return -1;
  7954. }
  7955. /* Set a key share that is supported by the client into extensions.
  7956. *
  7957. * ssl The SSL/TLS object.
  7958. * returns BAD_KEY_SHARE_DATA if no supported group has a key share,
  7959. * 0 if a supported group has a key share and other values indicate an error.
  7960. */
  7961. int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl, TLSX** extensions)
  7962. {
  7963. int ret;
  7964. #ifdef HAVE_SUPPORTED_CURVES
  7965. TLSX* extension;
  7966. SupportedCurve* curve = NULL;
  7967. SupportedCurve* preferredCurve = NULL;
  7968. KeyShareEntry* kse = NULL;
  7969. int preferredRank = WOLFSSL_MAX_GROUP_COUNT;
  7970. int rank;
  7971. extension = TLSX_Find(*extensions, TLSX_SUPPORTED_GROUPS);
  7972. if (extension != NULL)
  7973. curve = (SupportedCurve*)extension->data;
  7974. /* Use server's preference order. */
  7975. for (; curve != NULL; curve = curve->next) {
  7976. if (!TLSX_KeyShare_IsSupported(curve->name))
  7977. continue;
  7978. if (wolfSSL_curve_is_disabled(ssl, curve->name))
  7979. continue;
  7980. rank = TLSX_KeyShare_GroupRank(ssl, curve->name);
  7981. if (rank == -1)
  7982. continue;
  7983. if (rank < preferredRank) {
  7984. preferredCurve = curve;
  7985. preferredRank = rank;
  7986. }
  7987. }
  7988. curve = preferredCurve;
  7989. if (curve == NULL) {
  7990. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  7991. return BAD_KEY_SHARE_DATA;
  7992. }
  7993. #ifdef WOLFSSL_ASYNC_CRYPT
  7994. /* Check the old key share data list. */
  7995. extension = TLSX_Find(*extensions, TLSX_KEY_SHARE);
  7996. if (extension != NULL) {
  7997. kse = (KeyShareEntry*)extension->data;
  7998. /* We should not be computing keys if we are only going to advertise
  7999. * our choice here. */
  8000. if (kse != NULL && kse->lastRet == WC_PENDING_E) {
  8001. WOLFSSL_ERROR_VERBOSE(BAD_KEY_SHARE_DATA);
  8002. return BAD_KEY_SHARE_DATA;
  8003. }
  8004. }
  8005. #endif
  8006. /* Push new KeyShare extension. This will also free the old one */
  8007. ret = TLSX_Push(extensions, TLSX_KEY_SHARE, NULL, ssl->heap);
  8008. if (ret != 0)
  8009. return ret;
  8010. /* Extension got pushed to head */
  8011. extension = *extensions;
  8012. /* Push the selected curve */
  8013. ret = TLSX_KeyShare_New((KeyShareEntry**)&extension->data, curve->name,
  8014. ssl->heap, &kse);
  8015. if (ret != 0)
  8016. return ret;
  8017. /* Set extension to be in response. */
  8018. extension->resp = 1;
  8019. #else
  8020. (void)ssl;
  8021. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  8022. ret = NOT_COMPILED_IN;
  8023. #endif
  8024. return ret;
  8025. }
  8026. /* Server side KSE processing */
  8027. int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions,
  8028. byte cipherSuite0, byte cipherSuite, KeyShareEntry** kse, byte* searched)
  8029. {
  8030. TLSX* extension;
  8031. KeyShareEntry* clientKSE = NULL;
  8032. KeyShareEntry* list = NULL;
  8033. KeyShareEntry* preferredKSE = NULL;
  8034. int preferredRank = WOLFSSL_MAX_GROUP_COUNT;
  8035. int rank;
  8036. (void)cipherSuite0;
  8037. (void)cipherSuite;
  8038. if (ssl == NULL || ssl->options.side != WOLFSSL_SERVER_END)
  8039. return BAD_FUNC_ARG;
  8040. *searched = 0;
  8041. /* Find the KeyShare extension if it exists. */
  8042. extension = TLSX_Find(extensions, TLSX_KEY_SHARE);
  8043. if (extension != NULL)
  8044. list = (KeyShareEntry*)extension->data;
  8045. if (extension && extension->resp == 1) {
  8046. /* Outside of the async case this path should not be taken. */
  8047. int ret = INCOMPLETE_DATA;
  8048. #ifdef WOLFSSL_ASYNC_CRYPT
  8049. /* in async case make sure key generation is finalized */
  8050. KeyShareEntry* serverKSE = (KeyShareEntry*)extension->data;
  8051. if (serverKSE && serverKSE->lastRet == WC_PENDING_E) {
  8052. if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
  8053. *searched = 1;
  8054. ret = TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE);
  8055. }
  8056. #endif
  8057. return ret;
  8058. }
  8059. /* Use server's preference order. */
  8060. for (clientKSE = list; clientKSE != NULL; clientKSE = clientKSE->next) {
  8061. if (clientKSE->ke == NULL)
  8062. continue;
  8063. #ifdef WOLFSSL_SM2
  8064. if ((cipherSuite0 == CIPHER_BYTE) &&
  8065. ((cipherSuite == TLS_SM4_GCM_SM3) ||
  8066. (cipherSuite == TLS_SM4_CCM_SM3))) {
  8067. if (clientKSE->group != WOLFSSL_ECC_SM2P256V1) {
  8068. continue;
  8069. }
  8070. }
  8071. else if (clientKSE->group == WOLFSSL_ECC_SM2P256V1) {
  8072. continue;
  8073. }
  8074. #endif
  8075. /* Check consistency now - extensions in any order. */
  8076. if (!TLSX_SupportedGroups_Find(ssl, clientKSE->group, extensions))
  8077. continue;
  8078. if (!WOLFSSL_NAMED_GROUP_IS_FFHDE(clientKSE->group)) {
  8079. /* Check max value supported. */
  8080. if (clientKSE->group > WOLFSSL_ECC_MAX) {
  8081. #ifdef HAVE_PQC
  8082. if (!WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group))
  8083. #endif
  8084. continue;
  8085. }
  8086. if (wolfSSL_curve_is_disabled(ssl, clientKSE->group))
  8087. continue;
  8088. }
  8089. if (!TLSX_KeyShare_IsSupported(clientKSE->group))
  8090. continue;
  8091. rank = TLSX_KeyShare_GroupRank(ssl, clientKSE->group);
  8092. if (rank == -1)
  8093. continue;
  8094. if (rank < preferredRank) {
  8095. preferredKSE = clientKSE;
  8096. preferredRank = rank;
  8097. }
  8098. }
  8099. *kse = preferredKSE;
  8100. *searched = 1;
  8101. return 0;
  8102. }
  8103. /* Server side KSE processing */
  8104. int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE)
  8105. {
  8106. int ret;
  8107. TLSX* extension;
  8108. KeyShareEntry* serverKSE;
  8109. KeyShareEntry* list = NULL;
  8110. if (ssl == NULL || ssl->options.side != WOLFSSL_SERVER_END)
  8111. return BAD_FUNC_ARG;
  8112. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  8113. if (extension == NULL)
  8114. return BAD_STATE_E;
  8115. if (clientKSE == NULL) {
  8116. #ifdef WOLFSSL_ASYNC_CRYPT
  8117. /* Not necessarily an error. The key may have already been setup. */
  8118. if (extension != NULL && extension->resp == 1) {
  8119. serverKSE = (KeyShareEntry*)extension->data;
  8120. if (serverKSE != NULL) {
  8121. /* in async case make sure key generation is finalized */
  8122. if (serverKSE->lastRet == WC_PENDING_E)
  8123. return TLSX_KeyShare_GenKey((WOLFSSL*)ssl, serverKSE);
  8124. else if (serverKSE->lastRet == 0)
  8125. return 0;
  8126. }
  8127. }
  8128. #endif
  8129. return BAD_FUNC_ARG;
  8130. }
  8131. /* Generate a new key pair except in the case of OQS KEM because we
  8132. * are going to encapsulate and that does not require us to generate a
  8133. * key pair.
  8134. */
  8135. ret = TLSX_KeyShare_New(&list, clientKSE->group, ssl->heap, &serverKSE);
  8136. if (ret != 0)
  8137. return ret;
  8138. if (clientKSE->key == NULL) {
  8139. #ifdef HAVE_PQC
  8140. if (WOLFSSL_NAMED_GROUP_IS_PQC(clientKSE->group)) {
  8141. /* Going to need the public key (AKA ciphertext). */
  8142. serverKSE->pubKey = clientKSE->pubKey;
  8143. clientKSE->pubKey = NULL;
  8144. serverKSE->pubKeyLen = clientKSE->pubKeyLen;
  8145. clientKSE->pubKeyLen = 0;
  8146. }
  8147. else
  8148. #endif
  8149. {
  8150. ret = TLSX_KeyShare_GenKey(ssl, serverKSE);
  8151. }
  8152. /* for async do setup of serverKSE below, but return WC_PENDING_E */
  8153. if (ret != 0
  8154. #ifdef WOLFSSL_ASYNC_CRYPT
  8155. && ret != WC_PENDING_E
  8156. #endif
  8157. ) {
  8158. TLSX_KeyShare_FreeAll(list, ssl->heap);
  8159. return ret;
  8160. }
  8161. }
  8162. else {
  8163. /* transfer buffers to serverKSE */
  8164. serverKSE->key = clientKSE->key;
  8165. clientKSE->key = NULL;
  8166. serverKSE->keyLen = clientKSE->keyLen;
  8167. serverKSE->pubKey = clientKSE->pubKey;
  8168. clientKSE->pubKey = NULL;
  8169. serverKSE->pubKeyLen = clientKSE->pubKeyLen;
  8170. #ifndef NO_DH
  8171. serverKSE->privKey = clientKSE->privKey;
  8172. clientKSE->privKey = NULL;
  8173. #endif
  8174. }
  8175. serverKSE->ke = clientKSE->ke;
  8176. serverKSE->keLen = clientKSE->keLen;
  8177. clientKSE->ke = NULL;
  8178. clientKSE->keLen = 0;
  8179. TLSX_KeyShare_FreeAll((KeyShareEntry*)extension->data, ssl->heap);
  8180. extension->data = (void *)serverKSE;
  8181. extension->resp = 1;
  8182. return ret;
  8183. }
  8184. /* Ensure there is a key pair that can be used for key exchange.
  8185. *
  8186. * ssl The SSL/TLS object.
  8187. * doHelloRetry If set to non-zero will do hello_retry
  8188. * returns 0 on success and other values indicate failure.
  8189. */
  8190. int TLSX_KeyShare_Establish(WOLFSSL *ssl, int* doHelloRetry)
  8191. {
  8192. int ret;
  8193. KeyShareEntry* clientKSE = NULL;
  8194. byte searched = 0;
  8195. *doHelloRetry = 0;
  8196. ret = TLSX_KeyShare_Choose(ssl, ssl->extensions, ssl->cipher.cipherSuite0,
  8197. ssl->cipher.cipherSuite, &clientKSE, &searched);
  8198. if (ret != 0 || !searched)
  8199. return ret;
  8200. /* No supported group found - send HelloRetryRequest. */
  8201. if (clientKSE == NULL) {
  8202. /* Set KEY_SHARE_ERROR to indicate HelloRetryRequest required. */
  8203. *doHelloRetry = 1;
  8204. return TLSX_KeyShare_SetSupported(ssl, &ssl->extensions);
  8205. }
  8206. return TLSX_KeyShare_Setup(ssl, clientKSE);
  8207. }
  8208. /* Derive the shared secret of the key exchange.
  8209. *
  8210. * ssl The SSL/TLS object.
  8211. * returns 0 on success and other values indicate failure.
  8212. */
  8213. int TLSX_KeyShare_DeriveSecret(WOLFSSL *ssl)
  8214. {
  8215. int ret;
  8216. TLSX* extension;
  8217. KeyShareEntry* list = NULL;
  8218. #ifdef WOLFSSL_ASYNC_CRYPT
  8219. ret = wolfSSL_AsyncPop(ssl, NULL);
  8220. /* Check for error */
  8221. if (ret != WC_NOT_PENDING_E && ret < 0) {
  8222. return ret;
  8223. }
  8224. #endif
  8225. /* Find the KeyShare extension if it exists. */
  8226. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  8227. if (extension != NULL)
  8228. list = (KeyShareEntry*)extension->data;
  8229. if (list == NULL)
  8230. return KEY_SHARE_ERROR;
  8231. /* Calculate secret. */
  8232. ret = TLSX_KeyShare_Process(ssl, list);
  8233. return ret;
  8234. }
  8235. #define KS_FREE_ALL TLSX_KeyShare_FreeAll
  8236. #define KS_GET_SIZE TLSX_KeyShare_GetSize
  8237. #define KS_WRITE TLSX_KeyShare_Write
  8238. #define KS_PARSE TLSX_KeyShare_Parse
  8239. #else
  8240. #define KS_FREE_ALL(a, b)
  8241. #define KS_GET_SIZE(a, b) 0
  8242. #define KS_WRITE(a, b, c) 0
  8243. #define KS_PARSE(a, b, c, d) 0
  8244. #endif /* WOLFSSL_TLS13 */
  8245. /******************************************************************************/
  8246. /* Pre-Shared Key */
  8247. /******************************************************************************/
  8248. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  8249. /* Free the pre-shared key dynamic data.
  8250. *
  8251. * list The linked list of key share entry objects.
  8252. * heap The heap used for allocation.
  8253. */
  8254. static void TLSX_PreSharedKey_FreeAll(PreSharedKey* list, void* heap)
  8255. {
  8256. PreSharedKey* current;
  8257. while ((current = list) != NULL) {
  8258. list = current->next;
  8259. XFREE(current->identity, heap, DYNAMIC_TYPE_TLSX);
  8260. XFREE(current, heap, DYNAMIC_TYPE_TLSX);
  8261. }
  8262. (void)heap;
  8263. }
  8264. /* Get the size of the encoded pre shared key extension.
  8265. *
  8266. * list The linked list of pre-shared key extensions.
  8267. * msgType The type of the message this extension is being written into.
  8268. * returns the number of bytes of the encoded pre-shared key extension or
  8269. * SANITY_MSG_E to indicate invalid message type.
  8270. */
  8271. static int TLSX_PreSharedKey_GetSize(PreSharedKey* list, byte msgType,
  8272. word16* pSz)
  8273. {
  8274. if (msgType == client_hello) {
  8275. /* Length of identities + Length of binders. */
  8276. word16 len = OPAQUE16_LEN + OPAQUE16_LEN;
  8277. while (list != NULL) {
  8278. /* Each entry has: identity, ticket age and binder. */
  8279. len += OPAQUE16_LEN + list->identityLen + OPAQUE32_LEN +
  8280. OPAQUE8_LEN + (word16)list->binderLen;
  8281. list = list->next;
  8282. }
  8283. *pSz += len;
  8284. return 0;
  8285. }
  8286. if (msgType == server_hello) {
  8287. *pSz += OPAQUE16_LEN;
  8288. return 0;
  8289. }
  8290. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8291. return SANITY_MSG_E;
  8292. }
  8293. /* The number of bytes to be written for the binders.
  8294. *
  8295. * list The linked list of pre-shared key extensions.
  8296. * msgType The type of the message this extension is being written into.
  8297. * returns the number of bytes of the encoded pre-shared key extension or
  8298. * SANITY_MSG_E to indicate invalid message type.
  8299. */
  8300. int TLSX_PreSharedKey_GetSizeBinders(PreSharedKey* list, byte msgType,
  8301. word16* pSz)
  8302. {
  8303. word16 len;
  8304. if (msgType != client_hello) {
  8305. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8306. return SANITY_MSG_E;
  8307. }
  8308. /* Length of all binders. */
  8309. len = OPAQUE16_LEN;
  8310. while (list != NULL) {
  8311. len += OPAQUE8_LEN + (word16)list->binderLen;
  8312. list = list->next;
  8313. }
  8314. *pSz = len;
  8315. return 0;
  8316. }
  8317. /* Writes the pre-shared key extension into the output buffer - binders only.
  8318. * Assumes that the the output buffer is big enough to hold data.
  8319. *
  8320. * list The linked list of key share entries.
  8321. * output The buffer to write into.
  8322. * msgType The type of the message this extension is being written into.
  8323. * returns the number of bytes written into the buffer.
  8324. */
  8325. int TLSX_PreSharedKey_WriteBinders(PreSharedKey* list, byte* output,
  8326. byte msgType, word16* pSz)
  8327. {
  8328. PreSharedKey* current = list;
  8329. word16 idx = 0;
  8330. word16 lenIdx;
  8331. word16 len;
  8332. if (msgType != client_hello) {
  8333. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8334. return SANITY_MSG_E;
  8335. }
  8336. /* Skip length of all binders. */
  8337. lenIdx = idx;
  8338. idx += OPAQUE16_LEN;
  8339. while (current != NULL) {
  8340. /* Binder data length. */
  8341. output[idx++] = (byte)current->binderLen;
  8342. /* Binder data. */
  8343. XMEMCPY(output + idx, current->binder, current->binderLen);
  8344. idx += (word16)current->binderLen;
  8345. current = current->next;
  8346. }
  8347. /* Length of the binders. */
  8348. len = idx - lenIdx - OPAQUE16_LEN;
  8349. c16toa(len, output + lenIdx);
  8350. *pSz = idx;
  8351. return 0;
  8352. }
  8353. /* Writes the pre-shared key extension into the output buffer.
  8354. * Assumes that the the output buffer is big enough to hold data.
  8355. *
  8356. * list The linked list of key share entries.
  8357. * output The buffer to write into.
  8358. * msgType The type of the message this extension is being written into.
  8359. * returns the number of bytes written into the buffer.
  8360. */
  8361. static int TLSX_PreSharedKey_Write(PreSharedKey* list, byte* output,
  8362. byte msgType, word16* pSz)
  8363. {
  8364. if (msgType == client_hello) {
  8365. PreSharedKey* current = list;
  8366. word16 idx = 0;
  8367. word16 lenIdx;
  8368. word16 len;
  8369. int ret;
  8370. /* Write identites only. Binders after HMACing over this. */
  8371. lenIdx = idx;
  8372. idx += OPAQUE16_LEN;
  8373. while (current != NULL) {
  8374. /* Identity length */
  8375. c16toa(current->identityLen, output + idx);
  8376. idx += OPAQUE16_LEN;
  8377. /* Identity data */
  8378. XMEMCPY(output + idx, current->identity, current->identityLen);
  8379. idx += current->identityLen;
  8380. /* Obfuscated ticket age. */
  8381. c32toa(current->ticketAge, output + idx);
  8382. idx += OPAQUE32_LEN;
  8383. current = current->next;
  8384. }
  8385. /* Length of the identites. */
  8386. len = idx - lenIdx - OPAQUE16_LEN;
  8387. c16toa(len, output + lenIdx);
  8388. /* Don't include binders here.
  8389. * The binders are based on the hash of all the ClientHello data up to
  8390. * and include the identities written above.
  8391. */
  8392. ret = TLSX_PreSharedKey_GetSizeBinders(list, msgType, &len);
  8393. if (ret < 0)
  8394. return ret;
  8395. *pSz += idx + len;
  8396. }
  8397. else if (msgType == server_hello) {
  8398. word16 i;
  8399. /* Find the index of the chosen identity. */
  8400. for (i=0; list != NULL && !list->chosen; i++)
  8401. list = list->next;
  8402. if (list == NULL) {
  8403. WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR);
  8404. return BUILD_MSG_ERROR;
  8405. }
  8406. /* The index of the identity chosen by the server from the list supplied
  8407. * by the client.
  8408. */
  8409. c16toa(i, output);
  8410. *pSz += OPAQUE16_LEN;
  8411. }
  8412. else {
  8413. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8414. return SANITY_MSG_E;
  8415. }
  8416. return 0;
  8417. }
  8418. int TLSX_PreSharedKey_Parse_ClientHello(TLSX** extensions, const byte* input,
  8419. word16 length, void* heap)
  8420. {
  8421. int ret;
  8422. word16 len;
  8423. word16 idx = 0;
  8424. TLSX* extension;
  8425. PreSharedKey* list;
  8426. TLSX_Remove(extensions, TLSX_PRE_SHARED_KEY, heap);
  8427. /* Length of identities and of binders. */
  8428. if ((int)(length - idx) < OPAQUE16_LEN + OPAQUE16_LEN)
  8429. return BUFFER_E;
  8430. /* Length of identities. */
  8431. ato16(input + idx, &len);
  8432. idx += OPAQUE16_LEN;
  8433. if (len < MIN_PSK_ID_LEN || length - idx < len)
  8434. return BUFFER_E;
  8435. /* Create a pre-shared key object for each identity. */
  8436. while (len > 0) {
  8437. const byte* identity;
  8438. word16 identityLen;
  8439. word32 age;
  8440. if (len < OPAQUE16_LEN)
  8441. return BUFFER_E;
  8442. /* Length of identity. */
  8443. ato16(input + idx, &identityLen);
  8444. idx += OPAQUE16_LEN;
  8445. if (len < OPAQUE16_LEN + identityLen + OPAQUE32_LEN ||
  8446. identityLen > MAX_PSK_ID_LEN)
  8447. return BUFFER_E;
  8448. /* Cache identity pointer. */
  8449. identity = input + idx;
  8450. idx += identityLen;
  8451. /* Ticket age. */
  8452. ato32(input + idx, &age);
  8453. idx += OPAQUE32_LEN;
  8454. ret = TLSX_PreSharedKey_Use(extensions, identity, identityLen, age, no_mac,
  8455. 0, 0, 1, NULL, heap);
  8456. if (ret != 0)
  8457. return ret;
  8458. /* Done with this identity. */
  8459. len -= OPAQUE16_LEN + identityLen + OPAQUE32_LEN;
  8460. }
  8461. /* Find the list of identities sent to server. */
  8462. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8463. if (extension == NULL)
  8464. return PSK_KEY_ERROR;
  8465. list = (PreSharedKey*)extension->data;
  8466. /* Length of binders. */
  8467. if (idx + OPAQUE16_LEN > length)
  8468. return BUFFER_E;
  8469. ato16(input + idx, &len);
  8470. idx += OPAQUE16_LEN;
  8471. if (len < MIN_PSK_BINDERS_LEN || length - idx < len)
  8472. return BUFFER_E;
  8473. /* Set binder for each identity. */
  8474. while (list != NULL && len > 0) {
  8475. /* Length of binder */
  8476. list->binderLen = input[idx++];
  8477. if (list->binderLen < WC_SHA256_DIGEST_SIZE ||
  8478. list->binderLen > WC_MAX_DIGEST_SIZE)
  8479. return BUFFER_E;
  8480. if (len < OPAQUE8_LEN + list->binderLen)
  8481. return BUFFER_E;
  8482. /* Copy binder into static buffer. */
  8483. XMEMCPY(list->binder, input + idx, list->binderLen);
  8484. idx += (word16)list->binderLen;
  8485. /* Done with binder entry. */
  8486. len -= OPAQUE8_LEN + (word16)list->binderLen;
  8487. /* Next identity. */
  8488. list = list->next;
  8489. }
  8490. if (list != NULL || len != 0)
  8491. return BUFFER_E;
  8492. return 0;
  8493. }
  8494. /* Parse the pre-shared key extension.
  8495. * Different formats in different messages.
  8496. *
  8497. * ssl The SSL/TLS object.
  8498. * input The extension data.
  8499. * length The length of the extension data.
  8500. * msgType The type of the message this extension is being parsed from.
  8501. * returns 0 on success and other values indicate failure.
  8502. */
  8503. static int TLSX_PreSharedKey_Parse(WOLFSSL* ssl, const byte* input,
  8504. word16 length, byte msgType)
  8505. {
  8506. if (msgType == client_hello) {
  8507. return TLSX_PreSharedKey_Parse_ClientHello(&ssl->extensions, input,
  8508. length, ssl->heap);
  8509. }
  8510. if (msgType == server_hello) {
  8511. word16 idx;
  8512. PreSharedKey* list;
  8513. TLSX* extension;
  8514. /* Index of identity chosen by server. */
  8515. if (length != OPAQUE16_LEN)
  8516. return BUFFER_E;
  8517. ato16(input, &idx);
  8518. #ifdef WOLFSSL_EARLY_DATA
  8519. ssl->options.pskIdIndex = idx + 1;
  8520. #endif
  8521. /* Find the list of identities sent to server. */
  8522. extension = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
  8523. if (extension == NULL)
  8524. return PSK_KEY_ERROR;
  8525. list = (PreSharedKey*)extension->data;
  8526. /* Mark the identity as chosen. */
  8527. for (; list != NULL && idx > 0; idx--)
  8528. list = list->next;
  8529. if (list == NULL) {
  8530. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8531. return PSK_KEY_ERROR;
  8532. }
  8533. list->chosen = 1;
  8534. #ifdef HAVE_SESSION_TICKET
  8535. if (list->resumption) {
  8536. /* Check that the session's details are the same as the server's. */
  8537. if (ssl->options.cipherSuite0 != ssl->session->cipherSuite0 ||
  8538. ssl->options.cipherSuite != ssl->session->cipherSuite ||
  8539. ssl->session->version.major != ssl->ctx->method->version.major ||
  8540. ssl->session->version.minor != ssl->ctx->method->version.minor) {
  8541. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8542. return PSK_KEY_ERROR;
  8543. }
  8544. }
  8545. #endif
  8546. return 0;
  8547. }
  8548. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8549. return SANITY_MSG_E;
  8550. }
  8551. /* Create a new pre-shared key and put it into the list.
  8552. *
  8553. * list The linked list of pre-shared key.
  8554. * identity The identity.
  8555. * len The length of the identity data.
  8556. * heap The memory to allocate with.
  8557. * preSharedKey The new pre-shared key object.
  8558. * returns 0 on success and other values indicate failure.
  8559. */
  8560. static int TLSX_PreSharedKey_New(PreSharedKey** list, const byte* identity,
  8561. word16 len, void *heap,
  8562. PreSharedKey** preSharedKey)
  8563. {
  8564. PreSharedKey* psk;
  8565. PreSharedKey** next;
  8566. psk = (PreSharedKey*)XMALLOC(sizeof(PreSharedKey), heap, DYNAMIC_TYPE_TLSX);
  8567. if (psk == NULL)
  8568. return MEMORY_E;
  8569. XMEMSET(psk, 0, sizeof(*psk));
  8570. /* Make a copy of the identity data. */
  8571. psk->identity = (byte*)XMALLOC(len + NULL_TERM_LEN, heap,
  8572. DYNAMIC_TYPE_TLSX);
  8573. if (psk->identity == NULL) {
  8574. XFREE(psk, heap, DYNAMIC_TYPE_TLSX);
  8575. return MEMORY_E;
  8576. }
  8577. XMEMCPY(psk->identity, identity, len);
  8578. psk->identityLen = len;
  8579. /* Use a NULL terminator in case it is a C string */
  8580. psk->identity[psk->identityLen] = '\0';
  8581. /* Add it to the end and maintain the links. */
  8582. while (*list != NULL) {
  8583. /* Assign to temporary to work around compiler bug found by customer. */
  8584. next = &((*list)->next);
  8585. list = next;
  8586. }
  8587. *list = psk;
  8588. *preSharedKey = psk;
  8589. (void)heap;
  8590. return 0;
  8591. }
  8592. static WC_INLINE byte GetHmacLength(int hmac)
  8593. {
  8594. switch (hmac) {
  8595. #ifndef NO_SHA256
  8596. case sha256_mac:
  8597. return WC_SHA256_DIGEST_SIZE;
  8598. #endif
  8599. #ifdef WOLFSSL_SHA384
  8600. case sha384_mac:
  8601. return WC_SHA384_DIGEST_SIZE;
  8602. #endif
  8603. #ifdef WOLFSSL_SHA512
  8604. case sha512_mac:
  8605. return WC_SHA512_DIGEST_SIZE;
  8606. #endif
  8607. #ifdef WOLFSSL_SM3
  8608. case sm3_mac:
  8609. return WC_SM3_DIGEST_SIZE;
  8610. #endif
  8611. }
  8612. return 0;
  8613. }
  8614. /* Use the data to create a new pre-shared key object in the extensions.
  8615. *
  8616. * ssl The SSL/TLS object.
  8617. * identity The identity.
  8618. * len The length of the identity data.
  8619. * age The age of the identity.
  8620. * hmac The HMAC algorithm.
  8621. * cipherSuite0 The first byte of the cipher suite to use.
  8622. * cipherSuite The second byte of the cipher suite to use.
  8623. * resumption The PSK is for resumption of a session.
  8624. * preSharedKey The new pre-shared key object.
  8625. * returns 0 on success and other values indicate failure.
  8626. */
  8627. int TLSX_PreSharedKey_Use(TLSX** extensions, const byte* identity, word16 len,
  8628. word32 age, byte hmac, byte cipherSuite0,
  8629. byte cipherSuite, byte resumption,
  8630. PreSharedKey **preSharedKey, void* heap)
  8631. {
  8632. int ret = 0;
  8633. TLSX* extension;
  8634. PreSharedKey* psk = NULL;
  8635. /* Find the pre-shared key extension if it exists. */
  8636. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8637. if (extension == NULL) {
  8638. /* Push new pre-shared key extension. */
  8639. ret = TLSX_Push(extensions, TLSX_PRE_SHARED_KEY, NULL, heap);
  8640. if (ret != 0)
  8641. return ret;
  8642. extension = TLSX_Find(*extensions, TLSX_PRE_SHARED_KEY);
  8643. if (extension == NULL)
  8644. return MEMORY_E;
  8645. }
  8646. /* Try to find the pre-shared key with this identity. */
  8647. psk = (PreSharedKey*)extension->data;
  8648. while (psk != NULL) {
  8649. if ((psk->identityLen == len) &&
  8650. (XMEMCMP(psk->identity, identity, len) == 0)) {
  8651. break;
  8652. }
  8653. psk = psk->next;
  8654. }
  8655. /* Create a new pre-shared key object if not found. */
  8656. if (psk == NULL) {
  8657. ret = TLSX_PreSharedKey_New((PreSharedKey**)&extension->data, identity,
  8658. len, heap, &psk);
  8659. if (ret != 0)
  8660. return ret;
  8661. }
  8662. /* Update/set age and HMAC algorithm. */
  8663. psk->ticketAge = age;
  8664. psk->hmac = hmac;
  8665. psk->cipherSuite0 = cipherSuite0;
  8666. psk->cipherSuite = cipherSuite;
  8667. psk->resumption = resumption;
  8668. psk->binderLen = GetHmacLength(psk->hmac);
  8669. if (preSharedKey != NULL)
  8670. *preSharedKey = psk;
  8671. return 0;
  8672. }
  8673. #define PSK_FREE_ALL TLSX_PreSharedKey_FreeAll
  8674. #define PSK_GET_SIZE TLSX_PreSharedKey_GetSize
  8675. #define PSK_WRITE TLSX_PreSharedKey_Write
  8676. #define PSK_PARSE TLSX_PreSharedKey_Parse
  8677. #else
  8678. #define PSK_FREE_ALL(a, b)
  8679. #define PSK_GET_SIZE(a, b, c) 0
  8680. #define PSK_WRITE(a, b, c, d) 0
  8681. #define PSK_PARSE(a, b, c, d) 0
  8682. #endif
  8683. /******************************************************************************/
  8684. /* PSK Key Exchange Modes */
  8685. /******************************************************************************/
  8686. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  8687. /* Get the size of the encoded PSK KE modes extension.
  8688. * Only in ClientHello.
  8689. *
  8690. * modes The PSK KE mode bit string.
  8691. * msgType The type of the message this extension is being written into.
  8692. * returns the number of bytes of the encoded PSK KE mode extension.
  8693. */
  8694. static int TLSX_PskKeModes_GetSize(byte modes, byte msgType, word16* pSz)
  8695. {
  8696. if (msgType == client_hello) {
  8697. /* Format: Len | Modes* */
  8698. word16 len = OPAQUE8_LEN;
  8699. /* Check whether each possible mode is to be written. */
  8700. if (modes & (1 << PSK_KE))
  8701. len += OPAQUE8_LEN;
  8702. if (modes & (1 << PSK_DHE_KE))
  8703. len += OPAQUE8_LEN;
  8704. *pSz += len;
  8705. return 0;
  8706. }
  8707. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8708. return SANITY_MSG_E;
  8709. }
  8710. /* Writes the PSK KE modes extension into the output buffer.
  8711. * Assumes that the the output buffer is big enough to hold data.
  8712. * Only in ClientHello.
  8713. *
  8714. * modes The PSK KE mode bit string.
  8715. * output The buffer to write into.
  8716. * msgType The type of the message this extension is being written into.
  8717. * returns the number of bytes written into the buffer.
  8718. */
  8719. static int TLSX_PskKeModes_Write(byte modes, byte* output, byte msgType,
  8720. word16* pSz)
  8721. {
  8722. if (msgType == client_hello) {
  8723. /* Format: Len | Modes* */
  8724. word16 idx = OPAQUE8_LEN;
  8725. /* Write out each possible mode. */
  8726. if (modes & (1 << PSK_KE))
  8727. output[idx++] = PSK_KE;
  8728. if (modes & (1 << PSK_DHE_KE))
  8729. output[idx++] = PSK_DHE_KE;
  8730. /* Write out length of mode list. */
  8731. output[0] = (byte)(idx - OPAQUE8_LEN);
  8732. *pSz += idx;
  8733. return 0;
  8734. }
  8735. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8736. return SANITY_MSG_E;
  8737. }
  8738. int TLSX_PskKeyModes_Parse_Modes(const byte* input, word16 length, byte msgType,
  8739. byte* modes)
  8740. {
  8741. if (msgType == client_hello) {
  8742. /* Format: Len | Modes* */
  8743. int idx = 0;
  8744. word16 len;
  8745. *modes = 0;
  8746. /* Ensure length byte exists. */
  8747. if (length < OPAQUE8_LEN)
  8748. return BUFFER_E;
  8749. /* Get length of mode list and ensure that is the only data. */
  8750. len = input[0];
  8751. if (length - OPAQUE8_LEN != len)
  8752. return BUFFER_E;
  8753. idx = OPAQUE8_LEN;
  8754. /* Set a bit for each recognized modes. */
  8755. while (len > 0) {
  8756. /* Ignore unrecognized modes. */
  8757. if (input[idx] <= PSK_DHE_KE)
  8758. *modes |= 1 << input[idx];
  8759. idx++;
  8760. len--;
  8761. }
  8762. return 0;
  8763. }
  8764. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8765. return SANITY_MSG_E;
  8766. }
  8767. /* Parse the PSK KE modes extension.
  8768. * Only in ClientHello.
  8769. *
  8770. * ssl The SSL/TLS object.
  8771. * input The extension data.
  8772. * length The length of the extension data.
  8773. * msgType The type of the message this extension is being parsed from.
  8774. * returns 0 on success and other values indicate failure.
  8775. */
  8776. static int TLSX_PskKeModes_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  8777. byte msgType)
  8778. {
  8779. int ret;
  8780. byte modes;
  8781. ret = TLSX_PskKeyModes_Parse_Modes(input, length, msgType, &modes);
  8782. if (ret == 0)
  8783. ret = TLSX_PskKeyModes_Use(ssl, modes);
  8784. if (ret != 0)
  8785. WOLFSSL_ERROR_VERBOSE(ret);
  8786. return ret;
  8787. }
  8788. /* Use the data to create a new PSK Key Exchange Modes object in the extensions.
  8789. *
  8790. * ssl The SSL/TLS object.
  8791. * modes The PSK key exchange modes.
  8792. * returns 0 on success and other values indicate failure.
  8793. */
  8794. int TLSX_PskKeyModes_Use(WOLFSSL* ssl, byte modes)
  8795. {
  8796. int ret = 0;
  8797. TLSX* extension;
  8798. /* Find the PSK key exchange modes extension if it exists. */
  8799. extension = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  8800. if (extension == NULL) {
  8801. /* Push new PSK key exchange modes extension. */
  8802. ret = TLSX_Push(&ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES, NULL,
  8803. ssl->heap);
  8804. if (ret != 0)
  8805. return ret;
  8806. extension = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
  8807. if (extension == NULL)
  8808. return MEMORY_E;
  8809. }
  8810. extension->val = modes;
  8811. return 0;
  8812. }
  8813. #define PKM_GET_SIZE TLSX_PskKeModes_GetSize
  8814. #define PKM_WRITE TLSX_PskKeModes_Write
  8815. #define PKM_PARSE TLSX_PskKeModes_Parse
  8816. #else
  8817. #define PKM_GET_SIZE(a, b, c) 0
  8818. #define PKM_WRITE(a, b, c, d) 0
  8819. #define PKM_PARSE(a, b, c, d) 0
  8820. #endif
  8821. /******************************************************************************/
  8822. /* Post-Handshake Authentication */
  8823. /******************************************************************************/
  8824. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  8825. /* Get the size of the encoded Post-Handshake Authentication extension.
  8826. * Only in ClientHello.
  8827. *
  8828. * msgType The type of the message this extension is being written into.
  8829. * returns the number of bytes of the encoded Post-Handshake Authentication
  8830. * extension.
  8831. */
  8832. static int TLSX_PostHandAuth_GetSize(byte msgType, word16* pSz)
  8833. {
  8834. if (msgType == client_hello) {
  8835. *pSz += 0;
  8836. return 0;
  8837. }
  8838. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8839. return SANITY_MSG_E;
  8840. }
  8841. /* Writes the Post-Handshake Authentication extension into the output buffer.
  8842. * Assumes that the the output buffer is big enough to hold data.
  8843. * Only in ClientHello.
  8844. *
  8845. * output The buffer to write into.
  8846. * msgType The type of the message this extension is being written into.
  8847. * returns the number of bytes written into the buffer.
  8848. */
  8849. static int TLSX_PostHandAuth_Write(byte* output, byte msgType, word16* pSz)
  8850. {
  8851. (void)output;
  8852. if (msgType == client_hello) {
  8853. *pSz += 0;
  8854. return 0;
  8855. }
  8856. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8857. return SANITY_MSG_E;
  8858. }
  8859. /* Parse the Post-Handshake Authentication extension.
  8860. * Only in ClientHello.
  8861. *
  8862. * ssl The SSL/TLS object.
  8863. * input The extension data.
  8864. * length The length of the extension data.
  8865. * msgType The type of the message this extension is being parsed from.
  8866. * returns 0 on success and other values indicate failure.
  8867. */
  8868. static int TLSX_PostHandAuth_Parse(WOLFSSL* ssl, const byte* input,
  8869. word16 length, byte msgType)
  8870. {
  8871. (void)input;
  8872. if (msgType == client_hello) {
  8873. /* Ensure extension is empty. */
  8874. if (length != 0)
  8875. return BUFFER_E;
  8876. ssl->options.postHandshakeAuth = 1;
  8877. return 0;
  8878. }
  8879. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8880. return SANITY_MSG_E;
  8881. }
  8882. /* Create a new Post-handshake authentication object in the extensions.
  8883. *
  8884. * ssl The SSL/TLS object.
  8885. * returns 0 on success and other values indicate failure.
  8886. */
  8887. static int TLSX_PostHandAuth_Use(WOLFSSL* ssl)
  8888. {
  8889. int ret = 0;
  8890. TLSX* extension;
  8891. /* Find the PSK key exchange modes extension if it exists. */
  8892. extension = TLSX_Find(ssl->extensions, TLSX_POST_HANDSHAKE_AUTH);
  8893. if (extension == NULL) {
  8894. /* Push new Post-handshake Authentication extension. */
  8895. ret = TLSX_Push(&ssl->extensions, TLSX_POST_HANDSHAKE_AUTH, NULL,
  8896. ssl->heap);
  8897. if (ret != 0)
  8898. return ret;
  8899. }
  8900. return 0;
  8901. }
  8902. #define PHA_GET_SIZE TLSX_PostHandAuth_GetSize
  8903. #define PHA_WRITE TLSX_PostHandAuth_Write
  8904. #define PHA_PARSE TLSX_PostHandAuth_Parse
  8905. #else
  8906. #define PHA_GET_SIZE(a, b) 0
  8907. #define PHA_WRITE(a, b, c) 0
  8908. #define PHA_PARSE(a, b, c, d) 0
  8909. #endif
  8910. /******************************************************************************/
  8911. /* Early Data Indication */
  8912. /******************************************************************************/
  8913. #ifdef WOLFSSL_EARLY_DATA
  8914. /* Get the size of the encoded Early Data Indication extension.
  8915. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  8916. *
  8917. * msgType The type of the message this extension is being written into.
  8918. * returns the number of bytes of the encoded Early Data Indication extension.
  8919. */
  8920. static int TLSX_EarlyData_GetSize(byte msgType, word16* pSz)
  8921. {
  8922. int ret = 0;
  8923. if (msgType == client_hello || msgType == encrypted_extensions)
  8924. *pSz += 0;
  8925. else if (msgType == session_ticket)
  8926. *pSz += OPAQUE32_LEN;
  8927. else {
  8928. ret = SANITY_MSG_E;
  8929. WOLFSSL_ERROR_VERBOSE(ret);
  8930. }
  8931. return ret;
  8932. }
  8933. /* Writes the Early Data Indicator extension into the output buffer.
  8934. * Assumes that the the output buffer is big enough to hold data.
  8935. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  8936. *
  8937. * maxSz The maximum early data size.
  8938. * output The buffer to write into.
  8939. * msgType The type of the message this extension is being written into.
  8940. * returns the number of bytes written into the buffer.
  8941. */
  8942. static int TLSX_EarlyData_Write(word32 maxSz, byte* output, byte msgType,
  8943. word16* pSz)
  8944. {
  8945. if (msgType == client_hello || msgType == encrypted_extensions)
  8946. return 0;
  8947. else if (msgType == session_ticket) {
  8948. c32toa(maxSz, output);
  8949. *pSz += OPAQUE32_LEN;
  8950. return 0;
  8951. }
  8952. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  8953. return SANITY_MSG_E;
  8954. }
  8955. /* Parse the Early Data Indicator extension.
  8956. * In messages: ClientHello, EncryptedExtensions and NewSessionTicket.
  8957. *
  8958. * ssl The SSL/TLS object.
  8959. * input The extension data.
  8960. * length The length of the extension data.
  8961. * msgType The type of the message this extension is being parsed from.
  8962. * returns 0 on success and other values indicate failure.
  8963. */
  8964. static int TLSX_EarlyData_Parse(WOLFSSL* ssl, const byte* input, word16 length,
  8965. byte msgType)
  8966. {
  8967. WOLFSSL_ENTER("TLSX_EarlyData_Parse");
  8968. if (msgType == client_hello) {
  8969. if (length != 0)
  8970. return BUFFER_E;
  8971. if (ssl->earlyData == expecting_early_data) {
  8972. if (ssl->options.maxEarlyDataSz != 0)
  8973. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_ACCEPTED;
  8974. else
  8975. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_REJECTED;
  8976. return TLSX_EarlyData_Use(ssl, 0, 0);
  8977. }
  8978. ssl->earlyData = early_data_ext;
  8979. return 0;
  8980. }
  8981. if (msgType == encrypted_extensions) {
  8982. if (length != 0)
  8983. return BUFFER_E;
  8984. /* Ensure the index of PSK identity chosen by server is 0.
  8985. * Index is plus one to handle 'not set' value of 0.
  8986. */
  8987. if (ssl->options.pskIdIndex != 1) {
  8988. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  8989. return PSK_KEY_ERROR;
  8990. }
  8991. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  8992. /* the extension from server comes in */
  8993. ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_ACCEPTED;
  8994. }
  8995. return TLSX_EarlyData_Use(ssl, 1, 1);
  8996. }
  8997. if (msgType == session_ticket) {
  8998. word32 maxSz;
  8999. if (length != OPAQUE32_LEN)
  9000. return BUFFER_E;
  9001. ato32(input, &maxSz);
  9002. ssl->session->maxEarlyDataSz = maxSz;
  9003. return 0;
  9004. }
  9005. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9006. return SANITY_MSG_E;
  9007. }
  9008. /* Use the data to create a new Early Data object in the extensions.
  9009. *
  9010. * ssl The SSL/TLS object.
  9011. * maxSz The maximum early data size.
  9012. * is_response if this extension is part of a response
  9013. * returns 0 on success and other values indicate failure.
  9014. */
  9015. int TLSX_EarlyData_Use(WOLFSSL* ssl, word32 maxSz, int is_response)
  9016. {
  9017. int ret = 0;
  9018. TLSX* extension;
  9019. /* Find the early data extension if it exists. */
  9020. extension = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  9021. if (extension == NULL) {
  9022. /* Push new early data extension. */
  9023. ret = TLSX_Push(&ssl->extensions, TLSX_EARLY_DATA, NULL, ssl->heap);
  9024. if (ret != 0)
  9025. return ret;
  9026. extension = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
  9027. if (extension == NULL)
  9028. return MEMORY_E;
  9029. }
  9030. extension->resp = is_response;
  9031. /* In QUIC, earlydata size is either 0 or 0xffffffff.
  9032. * Override any size between, possibly left from our initial value */
  9033. extension->val = (WOLFSSL_IS_QUIC(ssl) && is_response && maxSz > 0) ?
  9034. WOLFSSL_MAX_32BIT : maxSz;
  9035. return 0;
  9036. }
  9037. #define EDI_GET_SIZE TLSX_EarlyData_GetSize
  9038. #define EDI_WRITE TLSX_EarlyData_Write
  9039. #define EDI_PARSE TLSX_EarlyData_Parse
  9040. #else
  9041. #define EDI_GET_SIZE(a, b) 0
  9042. #define EDI_WRITE(a, b, c, d) 0
  9043. #define EDI_PARSE(a, b, c, d) 0
  9044. #endif
  9045. /******************************************************************************/
  9046. /* QUIC transport parameter extension */
  9047. /******************************************************************************/
  9048. #ifdef WOLFSSL_QUIC
  9049. static word16 TLSX_QuicTP_GetSize(TLSX* extension)
  9050. {
  9051. const QuicTransportParam *tp = (QuicTransportParam*)extension->data;
  9052. return tp ? tp->len : 0;
  9053. }
  9054. int TLSX_QuicTP_Use(WOLFSSL* ssl, TLSX_Type ext_type, int is_response)
  9055. {
  9056. int ret = 0;
  9057. TLSX* extension;
  9058. WOLFSSL_ENTER("TLSX_QuicTP_Use");
  9059. if (ssl->quic.transport_local == NULL) {
  9060. /* RFC9000, ch 7.3: "An endpoint MUST treat the absence of [...]
  9061. * from either endpoint [...] as a connection error of type
  9062. * TRANSPORT_PARAMETER_ERROR."
  9063. */
  9064. ret = QUIC_TP_MISSING_E;
  9065. goto cleanup;
  9066. }
  9067. extension = TLSX_Find(ssl->extensions, ext_type);
  9068. if (extension == NULL) {
  9069. ret = TLSX_Push(&ssl->extensions, ext_type, NULL, ssl->heap);
  9070. if (ret != 0)
  9071. goto cleanup;
  9072. extension = TLSX_Find(ssl->extensions, ext_type);
  9073. if (extension == NULL) {
  9074. ret = MEMORY_E;
  9075. goto cleanup;
  9076. }
  9077. }
  9078. if (extension->data) {
  9079. QuicTransportParam_free((QuicTransportParam*)extension->data, ssl->heap);
  9080. extension->data = NULL;
  9081. }
  9082. extension->resp = is_response;
  9083. extension->data = (void*)QuicTransportParam_dup(ssl->quic.transport_local, ssl->heap);
  9084. if (!extension->data) {
  9085. ret = MEMORY_E;
  9086. goto cleanup;
  9087. }
  9088. cleanup:
  9089. WOLFSSL_LEAVE("TLSX_QuicTP_Use", ret);
  9090. return ret;
  9091. }
  9092. static word16 TLSX_QuicTP_Write(QuicTransportParam *tp, byte* output)
  9093. {
  9094. word16 len = 0;
  9095. WOLFSSL_ENTER("TLSX_QuicTP_Write");
  9096. if (tp && tp->len) {
  9097. XMEMCPY(output, tp->data, tp->len);
  9098. len = tp->len;
  9099. }
  9100. WOLFSSL_LEAVE("TLSX_QuicTP_Write", len);
  9101. return len;
  9102. }
  9103. static int TLSX_QuicTP_Parse(WOLFSSL *ssl, const byte *input, size_t len, int ext_type, int msgType)
  9104. {
  9105. const QuicTransportParam *tp, **ptp;
  9106. (void)msgType;
  9107. tp = QuicTransportParam_new(input, len, ssl->heap);
  9108. if (!tp) {
  9109. return MEMORY_E;
  9110. }
  9111. ptp = (ext_type == TLSX_KEY_QUIC_TP_PARAMS_DRAFT) ?
  9112. &ssl->quic.transport_peer_draft : &ssl->quic.transport_peer;
  9113. if (*ptp) {
  9114. QTP_FREE(*ptp, ssl->heap);
  9115. }
  9116. *ptp = tp;
  9117. return 0;
  9118. }
  9119. #define QTP_GET_SIZE TLSX_QuicTP_GetSize
  9120. #define QTP_USE TLSX_QuicTP_Use
  9121. #define QTP_WRITE TLSX_QuicTP_Write
  9122. #define QTP_PARSE TLSX_QuicTP_Parse
  9123. #endif /* WOLFSSL_QUIC */
  9124. #if defined(WOLFSSL_DTLS_CID)
  9125. #define CID_GET_SIZE TLSX_ConnectionID_GetSize
  9126. #define CID_WRITE TLSX_ConnectionID_Write
  9127. #define CID_PARSE TLSX_ConnectionID_Parse
  9128. #define CID_FREE TLSX_ConnectionID_Free
  9129. #else
  9130. #define CID_GET_SIZE(a) 0
  9131. #define CID_WRITE(a, b) 0
  9132. #define CID_PARSE(a, b, c, d) 0
  9133. #define CID_FREE(a, b) 0
  9134. #endif /* defined(WOLFSSL_DTLS_CID) */
  9135. /******************************************************************************/
  9136. /* TLS Extensions Framework */
  9137. /******************************************************************************/
  9138. /** Finds an extension in the provided list. */
  9139. TLSX* TLSX_Find(TLSX* list, TLSX_Type type)
  9140. {
  9141. TLSX* extension = list;
  9142. while (extension && extension->type != type)
  9143. extension = extension->next;
  9144. return extension;
  9145. }
  9146. /** Remove an extension. */
  9147. void TLSX_Remove(TLSX** list, TLSX_Type type, void* heap)
  9148. {
  9149. TLSX* extension;
  9150. TLSX** next;
  9151. if (list == NULL)
  9152. return;
  9153. extension = *list;
  9154. next = list;
  9155. while (extension && extension->type != type) {
  9156. next = &extension->next;
  9157. extension = extension->next;
  9158. }
  9159. if (extension) {
  9160. *next = extension->next;
  9161. extension->next = NULL;
  9162. TLSX_FreeAll(extension, heap);
  9163. }
  9164. }
  9165. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  9166. #define GREASE_ECH_SIZE 160
  9167. #define MAX_PUBLIC_NAME_SZ 256
  9168. #define TLS_INFO_CONST_STRING "tls ech"
  9169. #define TLS_INFO_CONST_STRING_SZ 7
  9170. /* return status after setting up ech to write a grease ech */
  9171. static int TLSX_GreaseECH_Use(TLSX** extensions, void* heap, WC_RNG* rng)
  9172. {
  9173. int ret = 0;
  9174. WOLFSSL_ECH* ech;
  9175. if (extensions == NULL)
  9176. return BAD_FUNC_ARG;
  9177. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9178. DYNAMIC_TYPE_TMP_BUFFER);
  9179. if (ech == NULL)
  9180. return MEMORY_E;
  9181. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9182. ech->state = ECH_WRITE_GREASE;
  9183. /* 0 for outer */
  9184. ech->type = ECH_TYPE_OUTER;
  9185. /* kemId */
  9186. ech->kemId = DHKEM_X25519_HKDF_SHA256;
  9187. /* cipherSuite kdf */
  9188. ech->cipherSuite.kdfId = HKDF_SHA256;
  9189. /* cipherSuite aead */
  9190. ech->cipherSuite.aeadId = HPKE_AES_128_GCM;
  9191. /* random configId */
  9192. ret = wc_RNG_GenerateByte(rng, &(ech->configId));
  9193. /* curve25519 encLen */
  9194. ech->encLen = DHKEM_X25519_ENC_LEN;
  9195. if (ret == 0)
  9196. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9197. if (ret != 0) {
  9198. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9199. }
  9200. return ret;
  9201. }
  9202. /* return status after setting up ech to write real ech */
  9203. static int TLSX_ECH_Use(WOLFSSL_EchConfig* echConfig, TLSX** extensions,
  9204. void* heap, WC_RNG* rng)
  9205. {
  9206. int ret = 0;
  9207. int suiteIndex;
  9208. WOLFSSL_ECH* ech;
  9209. if (extensions == NULL)
  9210. return BAD_FUNC_ARG;
  9211. /* find a supported cipher suite */
  9212. suiteIndex = EchConfigGetSupportedCipherSuite(echConfig);
  9213. if (suiteIndex < 0)
  9214. return suiteIndex;
  9215. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9216. DYNAMIC_TYPE_TMP_BUFFER);
  9217. if (ech == NULL)
  9218. return MEMORY_E;
  9219. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9220. ech->state = ECH_WRITE_REAL;
  9221. ech->echConfig = echConfig;
  9222. /* 0 for outer */
  9223. ech->type = ECH_TYPE_OUTER;
  9224. /* kemId */
  9225. ech->kemId = echConfig->kemId;
  9226. /* cipherSuite kdf */
  9227. ech->cipherSuite.kdfId = echConfig->cipherSuites[suiteIndex].kdfId;
  9228. /* cipherSuite aead */
  9229. ech->cipherSuite.aeadId = echConfig->cipherSuites[suiteIndex].aeadId;
  9230. /* configId */
  9231. ech->configId = echConfig->configId;
  9232. /* encLen */
  9233. switch (echConfig->kemId)
  9234. {
  9235. case DHKEM_P256_HKDF_SHA256:
  9236. ech->encLen = DHKEM_P256_ENC_LEN;
  9237. break;
  9238. case DHKEM_P384_HKDF_SHA384:
  9239. ech->encLen = DHKEM_P384_ENC_LEN;
  9240. break;
  9241. case DHKEM_P521_HKDF_SHA512:
  9242. ech->encLen = DHKEM_P521_ENC_LEN;
  9243. break;
  9244. case DHKEM_X25519_HKDF_SHA256:
  9245. ech->encLen = DHKEM_X25519_ENC_LEN;
  9246. break;
  9247. case DHKEM_X448_HKDF_SHA512:
  9248. ech->encLen = DHKEM_X448_ENC_LEN;
  9249. break;
  9250. }
  9251. /* setup hpke */
  9252. ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER);
  9253. if (ech->hpke == NULL) {
  9254. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9255. return MEMORY_E;
  9256. }
  9257. ret = wc_HpkeInit(ech->hpke, ech->kemId, ech->cipherSuite.kdfId,
  9258. ech->cipherSuite.aeadId, heap);
  9259. /* setup the ephemeralKey */
  9260. if (ret == 0)
  9261. ret = wc_HpkeGenerateKeyPair(ech->hpke, &ech->ephemeralKey, rng);
  9262. if (ret == 0)
  9263. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9264. if (ret != 0) {
  9265. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9266. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9267. }
  9268. return ret;
  9269. }
  9270. /* return status after setting up ech to read and decrypt */
  9271. static int TLSX_ServerECH_Use(TLSX** extensions, void* heap,
  9272. WOLFSSL_EchConfig* configs)
  9273. {
  9274. int ret;
  9275. WOLFSSL_ECH* ech;
  9276. TLSX* echX;
  9277. if (extensions == NULL)
  9278. return BAD_FUNC_ARG;
  9279. /* if we already have ech don't override it */
  9280. echX = TLSX_Find(*extensions, TLSX_ECH);
  9281. if (echX != NULL)
  9282. return 0;
  9283. ech = (WOLFSSL_ECH*)XMALLOC(sizeof(WOLFSSL_ECH), heap,
  9284. DYNAMIC_TYPE_TMP_BUFFER);
  9285. if (ech == NULL)
  9286. return MEMORY_E;
  9287. ForceZero(ech, sizeof(WOLFSSL_ECH));
  9288. ech->state = ECH_WRITE_NONE;
  9289. /* 0 for outer */
  9290. ech->type = ECH_TYPE_OUTER;
  9291. ech->echConfig = configs;
  9292. /* setup the rest of the settings when we receive ech from the client */
  9293. ret = TLSX_Push(extensions, TLSX_ECH, ech, heap);
  9294. if (ret != 0)
  9295. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9296. return ret;
  9297. }
  9298. /* return length after writing the ech */
  9299. static int TLSX_ECH_Write(WOLFSSL_ECH* ech, byte* writeBuf, word16* offset)
  9300. {
  9301. int ret = 0;
  9302. int rngRet = -1;
  9303. word32 configsLen = 0;
  9304. void* ephemeralKey = NULL;
  9305. byte* writeBuf_p = writeBuf;
  9306. #ifdef WOLFSSL_SMALL_STACK
  9307. Hpke* hpke = NULL;
  9308. WC_RNG* rng = NULL;
  9309. #else
  9310. Hpke hpke[1];
  9311. WC_RNG rng[1];
  9312. #endif
  9313. WOLFSSL_MSG("TLSX_ECH_Write");
  9314. if (ech->state == ECH_WRITE_NONE || ech->state == ECH_PARSED_INTERNAL)
  9315. return 0;
  9316. if (ech->state == ECH_WRITE_RETRY_CONFIGS) {
  9317. /* get size then write */
  9318. ret = GetEchConfigsEx(ech->echConfig, NULL, &configsLen);
  9319. if (ret != LENGTH_ONLY_E)
  9320. return ret;
  9321. ret = GetEchConfigsEx(ech->echConfig, writeBuf, &configsLen);
  9322. if (ret != WOLFSSL_SUCCESS)
  9323. return ret;
  9324. *offset += configsLen;
  9325. return 0;
  9326. }
  9327. #ifdef WOLFSSL_SMALL_STACK
  9328. hpke = (Hpke*)XMALLOC(sizeof(Hpke), NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9329. if (hpke == NULL)
  9330. return MEMORY_E;
  9331. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  9332. if (rng == NULL) {
  9333. XFREE(hpke, NULL, DYNAMIC_TYPE_RNG);
  9334. return MEMORY_E;
  9335. }
  9336. #endif
  9337. /* type */
  9338. *writeBuf_p = ech->type;
  9339. writeBuf_p += sizeof(ech->type);
  9340. /* outer has body, inner does not */
  9341. if (ech->type == ECH_TYPE_OUTER) {
  9342. /* kdfId */
  9343. c16toa(ech->cipherSuite.kdfId, writeBuf_p);
  9344. writeBuf_p += sizeof(ech->cipherSuite.kdfId);
  9345. /* aeadId */
  9346. c16toa(ech->cipherSuite.aeadId, writeBuf_p);
  9347. writeBuf_p += sizeof(ech->cipherSuite.aeadId);
  9348. /* configId */
  9349. *writeBuf_p = ech->configId;
  9350. writeBuf_p += sizeof(ech->configId);
  9351. /* encLen */
  9352. c16toa(ech->encLen, writeBuf_p);
  9353. writeBuf_p += 2;
  9354. if (ech->state == ECH_WRITE_GREASE) {
  9355. /* hpke init */
  9356. ret = wc_HpkeInit(hpke, ech->kemId, ech->cipherSuite.kdfId,
  9357. ech->cipherSuite.aeadId, NULL);
  9358. if (ret == 0)
  9359. rngRet = ret = wc_InitRng(rng);
  9360. /* create the ephemeralKey */
  9361. if (ret == 0)
  9362. ret = wc_HpkeGenerateKeyPair(hpke, &ephemeralKey, rng);
  9363. /* enc */
  9364. if (ret == 0) {
  9365. ret = wc_HpkeSerializePublicKey(hpke, ephemeralKey, writeBuf_p,
  9366. &ech->encLen);
  9367. writeBuf_p += ech->encLen;
  9368. }
  9369. if (ret == 0) {
  9370. /* innerClientHelloLen */
  9371. c16toa(GREASE_ECH_SIZE + ((writeBuf_p + 2 - writeBuf) % 32),
  9372. writeBuf_p);
  9373. writeBuf_p += 2;
  9374. /* innerClientHello */
  9375. ret = wc_RNG_GenerateBlock(rng, writeBuf_p, GREASE_ECH_SIZE +
  9376. ((writeBuf_p - writeBuf) % 32));
  9377. writeBuf_p += GREASE_ECH_SIZE + ((writeBuf_p - writeBuf) % 32);
  9378. }
  9379. if (rngRet == 0)
  9380. wc_FreeRng(rng);
  9381. if (ephemeralKey != NULL)
  9382. wc_HpkeFreeKey(hpke, hpke->kem, ephemeralKey, hpke->heap);
  9383. }
  9384. else {
  9385. /* write enc to writeBuf_p */
  9386. ret = wc_HpkeSerializePublicKey(ech->hpke, ech->ephemeralKey,
  9387. writeBuf_p, &ech->encLen);
  9388. writeBuf_p += ech->encLen;
  9389. /* innerClientHelloLen */
  9390. c16toa(ech->innerClientHelloLen, writeBuf_p);
  9391. writeBuf_p += 2;
  9392. /* set payload offset for when we finalize */
  9393. ech->outerClientPayload = writeBuf_p;
  9394. /* write zeros for payload */
  9395. XMEMSET(writeBuf_p, 0, ech->innerClientHelloLen);
  9396. writeBuf_p += ech->innerClientHelloLen;
  9397. }
  9398. }
  9399. #ifdef WOLFSSL_SMALL_STACK
  9400. XFREE(hpke, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9401. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  9402. #endif
  9403. if (ret == 0)
  9404. *offset += (writeBuf_p - writeBuf);
  9405. return ret;
  9406. }
  9407. /* return the size needed for the ech extension */
  9408. static int TLSX_ECH_GetSize(WOLFSSL_ECH* ech)
  9409. {
  9410. int ret;
  9411. word32 size;
  9412. if (ech->state == ECH_WRITE_GREASE) {
  9413. size = sizeof(ech->type) + sizeof(ech->cipherSuite) +
  9414. sizeof(ech->configId) + sizeof(word16) + ech->encLen +
  9415. sizeof(word16);
  9416. size += GREASE_ECH_SIZE + (size % 32);
  9417. }
  9418. else if (ech->state == ECH_WRITE_NONE ||
  9419. ech->state == ECH_PARSED_INTERNAL) {
  9420. size = 0;
  9421. }
  9422. else if (ech->state == ECH_WRITE_RETRY_CONFIGS) {
  9423. /* get the size of the raw configs */
  9424. ret = GetEchConfigsEx(ech->echConfig, NULL, &size);
  9425. if (ret != LENGTH_ONLY_E)
  9426. return ret;
  9427. }
  9428. else if (ech->type == ECH_TYPE_INNER)
  9429. {
  9430. size = sizeof(ech->type);
  9431. }
  9432. else
  9433. {
  9434. size = sizeof(ech->type) + sizeof(ech->cipherSuite) +
  9435. sizeof(ech->configId) + sizeof(word16) + ech->encLen +
  9436. sizeof(word16) + ech->innerClientHelloLen;
  9437. }
  9438. return (int)size;
  9439. }
  9440. /* return status after attempting to open the hpke encrypted ech extension, if
  9441. * successful the inner client hello will be stored in
  9442. * ech->innerClientHelloLen */
  9443. static int TLSX_ExtractEch(WOLFSSL_ECH* ech, WOLFSSL_EchConfig* echConfig,
  9444. byte* aad, word32 aadLen, void* heap)
  9445. {
  9446. int ret = 0;
  9447. int expectedEncLen;
  9448. int i;
  9449. word32 rawConfigLen = 0;
  9450. byte* info = NULL;
  9451. word32 infoLen = 0;
  9452. if (ech == NULL || echConfig == NULL || aad == NULL)
  9453. return BAD_FUNC_ARG;
  9454. /* verify the kem and key len */
  9455. switch (echConfig->kemId)
  9456. {
  9457. case DHKEM_P256_HKDF_SHA256:
  9458. expectedEncLen = DHKEM_P256_ENC_LEN;
  9459. break;
  9460. case DHKEM_P384_HKDF_SHA384:
  9461. expectedEncLen = DHKEM_P384_ENC_LEN;
  9462. break;
  9463. case DHKEM_P521_HKDF_SHA512:
  9464. expectedEncLen = DHKEM_P521_ENC_LEN;
  9465. break;
  9466. case DHKEM_X25519_HKDF_SHA256:
  9467. expectedEncLen = DHKEM_X25519_ENC_LEN;
  9468. break;
  9469. case DHKEM_X448_HKDF_SHA512:
  9470. expectedEncLen = DHKEM_X448_ENC_LEN;
  9471. break;
  9472. default:
  9473. expectedEncLen = 0;
  9474. break;
  9475. }
  9476. if (expectedEncLen != ech->encLen)
  9477. return BAD_FUNC_ARG;
  9478. /* verify the cipher suite */
  9479. for (i = 0; i < echConfig->numCipherSuites; i++) {
  9480. if (echConfig->cipherSuites[i].kdfId == ech->cipherSuite.kdfId &&
  9481. echConfig->cipherSuites[i].aeadId == ech->cipherSuite.aeadId) {
  9482. break;
  9483. }
  9484. }
  9485. if (i >= echConfig->numCipherSuites) {
  9486. return BAD_FUNC_ARG;
  9487. }
  9488. ech->hpke = (Hpke*)XMALLOC(sizeof(Hpke), heap, DYNAMIC_TYPE_TMP_BUFFER);
  9489. if (ech->hpke == NULL)
  9490. return MEMORY_E;
  9491. ret = wc_HpkeInit(ech->hpke, echConfig->kemId, ech->cipherSuite.kdfId,
  9492. ech->cipherSuite.aeadId, heap);
  9493. /* get the rawConfigLen */
  9494. if (ret == 0)
  9495. ret = GetEchConfig(echConfig, NULL, &rawConfigLen);
  9496. if (ret == LENGTH_ONLY_E)
  9497. ret = 0;
  9498. /* create info */
  9499. if (ret == 0) {
  9500. infoLen = TLS_INFO_CONST_STRING_SZ + 1 + rawConfigLen;
  9501. info = (byte*)XMALLOC(infoLen, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9502. if (info == NULL)
  9503. ret = MEMORY_E;
  9504. else {
  9505. XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING,
  9506. TLS_INFO_CONST_STRING_SZ + 1);
  9507. ret = GetEchConfig(echConfig, info +
  9508. TLS_INFO_CONST_STRING_SZ + 1, &rawConfigLen);
  9509. }
  9510. }
  9511. /* decrypt the ech payload */
  9512. if (ret == 0)
  9513. ret = wc_HpkeOpenBase(ech->hpke, echConfig->receiverPrivkey, ech->enc,
  9514. ech->encLen, info, infoLen, aad, aadLen, ech->outerClientPayload,
  9515. ech->innerClientHelloLen,
  9516. ech->innerClientHello + HANDSHAKE_HEADER_SZ);
  9517. if (ret != 0) {
  9518. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9519. ech->hpke = NULL;
  9520. }
  9521. if (info != NULL)
  9522. XFREE(info, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9523. return ret;
  9524. }
  9525. /* parse the ech extension, if internal update ech->state and return, if
  9526. * external attempt to extract the inner client_hello, return the status */
  9527. static int TLSX_ECH_Parse(WOLFSSL* ssl, const byte* readBuf, word16 size,
  9528. byte msgType)
  9529. {
  9530. int ret = 0;
  9531. int i;
  9532. TLSX* echX;
  9533. WOLFSSL_ECH* ech;
  9534. WOLFSSL_EchConfig* echConfig;
  9535. byte* aadCopy;
  9536. byte* readBuf_p = (byte*)readBuf;
  9537. WOLFSSL_MSG("TLSX_ECH_Parse");
  9538. if (size == 0)
  9539. return BAD_FUNC_ARG;
  9540. if (msgType == encrypted_extensions) {
  9541. ret = wolfSSL_SetEchConfigs(ssl, readBuf, size);
  9542. if (ret == WOLFSSL_SUCCESS)
  9543. ret = 0;
  9544. }
  9545. else if (msgType == client_hello && ssl->ctx->echConfigs != NULL) {
  9546. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  9547. if (echX == NULL)
  9548. return BAD_FUNC_ARG;
  9549. ech = (WOLFSSL_ECH*)echX->data;
  9550. /* read the ech parameters before the payload */
  9551. ech->type = *readBuf_p;
  9552. readBuf_p++;
  9553. if (ech->type == ECH_TYPE_INNER) {
  9554. ech->state = ECH_PARSED_INTERNAL;
  9555. return 0;
  9556. }
  9557. /* technically the payload would only be 1 byte at this length */
  9558. if (size < 11 + ech->encLen)
  9559. return BAD_FUNC_ARG;
  9560. ato16(readBuf_p, &ech->cipherSuite.kdfId);
  9561. readBuf_p += 2;
  9562. ato16(readBuf_p, &ech->cipherSuite.aeadId);
  9563. readBuf_p += 2;
  9564. ech->configId = *readBuf_p;
  9565. readBuf_p++;
  9566. ato16(readBuf_p, &ech->encLen);
  9567. readBuf_p += 2;
  9568. if (ech->encLen > HPKE_Npk_MAX)
  9569. return BAD_FUNC_ARG;
  9570. XMEMCPY(ech->enc, readBuf_p, ech->encLen);
  9571. readBuf_p += ech->encLen;
  9572. ato16(readBuf_p, &ech->innerClientHelloLen);
  9573. ech->innerClientHelloLen -= AES_BLOCK_SIZE;
  9574. readBuf_p += 2;
  9575. ech->outerClientPayload = readBuf_p;
  9576. /* make a copy of the aad */
  9577. aadCopy = (byte*)XMALLOC(ech->aadLen, ssl->heap,
  9578. DYNAMIC_TYPE_TMP_BUFFER);
  9579. if (aadCopy == NULL)
  9580. return MEMORY_E;
  9581. XMEMCPY(aadCopy, ech->aad, ech->aadLen);
  9582. /* set the ech payload of the copy to zeros */
  9583. XMEMSET(aadCopy + (readBuf_p - ech->aad), 0,
  9584. ech->innerClientHelloLen + AES_BLOCK_SIZE);
  9585. /* allocate the inner payload buffer */
  9586. ech->innerClientHello =
  9587. (byte*)XMALLOC(ech->innerClientHelloLen + HANDSHAKE_HEADER_SZ,
  9588. ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9589. if (ech->innerClientHello == NULL) {
  9590. XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9591. return MEMORY_E;
  9592. }
  9593. /* first check if the config id matches */
  9594. echConfig = ssl->ctx->echConfigs;
  9595. while (echConfig != NULL) {
  9596. /* decrypt with this config */
  9597. if (echConfig->configId == ech->configId) {
  9598. ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen,
  9599. ssl->heap);
  9600. break;
  9601. }
  9602. echConfig = echConfig->next;
  9603. }
  9604. /* try to decrypt with all configs */
  9605. if (echConfig == NULL || ret != 0) {
  9606. echConfig = ssl->ctx->echConfigs;
  9607. while (echConfig != NULL) {
  9608. ret = TLSX_ExtractEch(ech, echConfig, aadCopy, ech->aadLen,
  9609. ssl->heap);
  9610. if (ret== 0)
  9611. break;
  9612. echConfig = echConfig->next;
  9613. }
  9614. }
  9615. /* if we failed to extract */
  9616. if (ret != 0) {
  9617. XFREE(ech->innerClientHello, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9618. ech->innerClientHello = NULL;
  9619. ech->state = ECH_WRITE_RETRY_CONFIGS;
  9620. }
  9621. else {
  9622. i = 0;
  9623. /* decrement until before the padding */
  9624. while (ech->innerClientHello[ech->innerClientHelloLen +
  9625. HANDSHAKE_HEADER_SZ - i - 1] != ECH_TYPE_INNER) {
  9626. i++;
  9627. }
  9628. /* subtract the length of the padding from the length */
  9629. ech->innerClientHelloLen -= i;
  9630. }
  9631. XFREE(aadCopy, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9632. return 0;
  9633. }
  9634. return ret;
  9635. }
  9636. /* free the ech struct and the dynamic buffer it uses */
  9637. static void TLSX_ECH_Free(WOLFSSL_ECH* ech, void* heap)
  9638. {
  9639. if (ech->innerClientHello != NULL)
  9640. XFREE(ech->innerClientHello, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9641. if (ech->ephemeralKey != NULL)
  9642. wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, ech->ephemeralKey,
  9643. ech->hpke->heap);
  9644. if (ech->hpke != NULL)
  9645. XFREE(ech->hpke, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9646. XFREE(ech, heap, DYNAMIC_TYPE_TMP_BUFFER);
  9647. (void)heap;
  9648. }
  9649. /* encrypt the client hello and store it in ech->outerClientPayload, return
  9650. * status */
  9651. int TLSX_FinalizeEch(WOLFSSL_ECH* ech, byte* aad, word32 aadLen)
  9652. {
  9653. int ret;
  9654. void* receiverPubkey = NULL;
  9655. byte* info;
  9656. int infoLen;
  9657. byte* aadCopy;
  9658. /* import the server public key */
  9659. ret = wc_HpkeDeserializePublicKey(ech->hpke, &receiverPubkey,
  9660. ech->echConfig->receiverPubkey, ech->encLen);
  9661. if (ret == 0) {
  9662. /* create info */
  9663. infoLen = TLS_INFO_CONST_STRING_SZ + 1 + ech->echConfig->rawLen;
  9664. info = (byte*)XMALLOC(infoLen, ech->hpke->heap,
  9665. DYNAMIC_TYPE_TMP_BUFFER);
  9666. if (info == NULL)
  9667. ret = MEMORY_E;
  9668. if (ret == 0) {
  9669. /* puts the null byte in for me */
  9670. XMEMCPY(info, (byte*)TLS_INFO_CONST_STRING, TLS_INFO_CONST_STRING_SZ
  9671. + 1);
  9672. XMEMCPY(info + TLS_INFO_CONST_STRING_SZ + 1, ech->echConfig->raw,
  9673. ech->echConfig->rawLen);
  9674. /* make a copy of the aad since we overwrite it */
  9675. aadCopy = (byte*)XMALLOC(aadLen, ech->hpke->heap,
  9676. DYNAMIC_TYPE_TMP_BUFFER);
  9677. if (aadCopy == NULL) {
  9678. XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9679. ret = MEMORY_E;
  9680. }
  9681. }
  9682. if (ret == 0) {
  9683. XMEMCPY(aadCopy, aad, aadLen);
  9684. /* seal the payload */
  9685. ret = wc_HpkeSealBase(ech->hpke, ech->ephemeralKey, receiverPubkey,
  9686. info, infoLen, aadCopy, aadLen, ech->innerClientHello,
  9687. ech->innerClientHelloLen - ech->hpke->Nt,
  9688. ech->outerClientPayload);
  9689. XFREE(info, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9690. XFREE(aadCopy, ech->hpke->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9691. }
  9692. }
  9693. if (receiverPubkey != NULL)
  9694. wc_HpkeFreeKey(ech->hpke, ech->hpke->kem, receiverPubkey,
  9695. ech->hpke->heap);
  9696. return ret;
  9697. }
  9698. #define GREASE_ECH_USE TLSX_GreaseECH_Use
  9699. #define ECH_USE TLSX_ECH_Use
  9700. #define SERVER_ECH_USE TLSX_ServerECH_Use
  9701. #define ECH_WRITE TLSX_ECH_Write
  9702. #define ECH_GET_SIZE TLSX_ECH_GetSize
  9703. #define ECH_PARSE TLSX_ECH_Parse
  9704. #define ECH_FREE TLSX_ECH_Free
  9705. #endif
  9706. /** Releases all extensions in the provided list. */
  9707. void TLSX_FreeAll(TLSX* list, void* heap)
  9708. {
  9709. TLSX* extension;
  9710. while ((extension = list)) {
  9711. list = extension->next;
  9712. switch (extension->type) {
  9713. #ifdef HAVE_SNI
  9714. case TLSX_SERVER_NAME:
  9715. SNI_FREE_ALL((SNI*)extension->data, heap);
  9716. break;
  9717. #endif
  9718. case TLSX_TRUSTED_CA_KEYS:
  9719. TCA_FREE_ALL((TCA*)extension->data, heap);
  9720. break;
  9721. case TLSX_MAX_FRAGMENT_LENGTH:
  9722. MFL_FREE_ALL(extension->data, heap);
  9723. break;
  9724. case TLSX_EXTENDED_MASTER_SECRET:
  9725. case TLSX_TRUNCATED_HMAC:
  9726. /* Nothing to do. */
  9727. break;
  9728. case TLSX_SUPPORTED_GROUPS:
  9729. EC_FREE_ALL((SupportedCurve*)extension->data, heap);
  9730. break;
  9731. case TLSX_EC_POINT_FORMATS:
  9732. PF_FREE_ALL((PointFormat*)extension->data, heap);
  9733. break;
  9734. case TLSX_STATUS_REQUEST:
  9735. CSR_FREE_ALL((CertificateStatusRequest*)extension->data, heap);
  9736. break;
  9737. case TLSX_STATUS_REQUEST_V2:
  9738. CSR2_FREE_ALL((CertificateStatusRequestItemV2*)extension->data,
  9739. heap);
  9740. break;
  9741. case TLSX_RENEGOTIATION_INFO:
  9742. SCR_FREE_ALL(extension->data, heap);
  9743. break;
  9744. case TLSX_SESSION_TICKET:
  9745. WOLF_STK_FREE(extension->data, heap);
  9746. break;
  9747. case TLSX_APPLICATION_LAYER_PROTOCOL:
  9748. ALPN_FREE_ALL((ALPN*)extension->data, heap);
  9749. break;
  9750. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  9751. case TLSX_SIGNATURE_ALGORITHMS:
  9752. SA_FREE_ALL((SignatureAlgorithms*)extension->data, heap);
  9753. break;
  9754. #endif
  9755. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  9756. case TLSX_ENCRYPT_THEN_MAC:
  9757. break;
  9758. #endif
  9759. #ifdef WOLFSSL_TLS13
  9760. case TLSX_SUPPORTED_VERSIONS:
  9761. break;
  9762. #ifdef WOLFSSL_SEND_HRR_COOKIE
  9763. case TLSX_COOKIE:
  9764. CKE_FREE_ALL((Cookie*)extension->data, heap);
  9765. break;
  9766. #endif
  9767. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  9768. case TLSX_PRE_SHARED_KEY:
  9769. PSK_FREE_ALL((PreSharedKey*)extension->data, heap);
  9770. break;
  9771. case TLSX_PSK_KEY_EXCHANGE_MODES:
  9772. break;
  9773. #endif
  9774. #ifdef WOLFSSL_EARLY_DATA
  9775. case TLSX_EARLY_DATA:
  9776. break;
  9777. #endif
  9778. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  9779. case TLSX_POST_HANDSHAKE_AUTH:
  9780. break;
  9781. #endif
  9782. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  9783. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  9784. break;
  9785. #endif
  9786. case TLSX_KEY_SHARE:
  9787. KS_FREE_ALL((KeyShareEntry*)extension->data, heap);
  9788. break;
  9789. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  9790. case TLSX_CERTIFICATE_AUTHORITIES:
  9791. break;
  9792. #endif
  9793. #endif
  9794. #ifdef WOLFSSL_SRTP
  9795. case TLSX_USE_SRTP:
  9796. SRTP_FREE((TlsxSrtp*)extension->data, heap);
  9797. break;
  9798. #endif
  9799. #ifdef WOLFSSL_QUIC
  9800. case TLSX_KEY_QUIC_TP_PARAMS:
  9801. FALL_THROUGH;
  9802. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  9803. QTP_FREE((QuicTransportParam*)extension->data, heap);
  9804. break;
  9805. #endif
  9806. #ifdef WOLFSSL_DTLS_CID
  9807. case TLSX_CONNECTION_ID:
  9808. CID_FREE((byte*)extension->data, heap);
  9809. break;
  9810. #endif /* WOLFSSL_DTLS_CID */
  9811. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  9812. case TLSX_ECH:
  9813. ECH_FREE((WOLFSSL_ECH*)extension->data, heap);
  9814. break;
  9815. #endif
  9816. default:
  9817. break;
  9818. }
  9819. XFREE(extension, heap, DYNAMIC_TYPE_TLSX);
  9820. }
  9821. (void)heap;
  9822. }
  9823. /** Checks if the tls extensions are supported based on the protocol version. */
  9824. int TLSX_SupportExtensions(WOLFSSL* ssl) {
  9825. return ssl && (IsTLS(ssl) || ssl->version.major == DTLS_MAJOR);
  9826. }
  9827. /** Tells the buffered size of the extensions in a list. */
  9828. static int TLSX_GetSize(TLSX* list, byte* semaphore, byte msgType,
  9829. word16* pLength)
  9830. {
  9831. int ret = 0;
  9832. TLSX* extension;
  9833. word16 length = 0;
  9834. byte isRequest = (msgType == client_hello ||
  9835. msgType == certificate_request);
  9836. while ((extension = list)) {
  9837. list = extension->next;
  9838. /* only extensions marked as response are sent back to the client. */
  9839. if (!isRequest && !extension->resp)
  9840. continue; /* skip! */
  9841. /* ssl level extensions are expected to override ctx level ones. */
  9842. if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type)))
  9843. continue; /* skip! */
  9844. /* extension type + extension data length. */
  9845. length += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN;
  9846. switch (extension->type) {
  9847. #ifdef HAVE_SNI
  9848. case TLSX_SERVER_NAME:
  9849. /* SNI only sends the name on the request. */
  9850. if (isRequest)
  9851. length += SNI_GET_SIZE((SNI*)extension->data);
  9852. break;
  9853. #endif
  9854. case TLSX_TRUSTED_CA_KEYS:
  9855. /* TCA only sends the list on the request. */
  9856. if (isRequest)
  9857. length += TCA_GET_SIZE((TCA*)extension->data);
  9858. break;
  9859. case TLSX_MAX_FRAGMENT_LENGTH:
  9860. length += MFL_GET_SIZE(extension->data);
  9861. break;
  9862. case TLSX_EXTENDED_MASTER_SECRET:
  9863. case TLSX_TRUNCATED_HMAC:
  9864. /* always empty. */
  9865. break;
  9866. case TLSX_SUPPORTED_GROUPS:
  9867. length += EC_GET_SIZE((SupportedCurve*)extension->data);
  9868. break;
  9869. case TLSX_EC_POINT_FORMATS:
  9870. length += PF_GET_SIZE((PointFormat*)extension->data);
  9871. break;
  9872. case TLSX_STATUS_REQUEST:
  9873. length += CSR_GET_SIZE(
  9874. (CertificateStatusRequest*)extension->data, isRequest);
  9875. break;
  9876. case TLSX_STATUS_REQUEST_V2:
  9877. length += CSR2_GET_SIZE(
  9878. (CertificateStatusRequestItemV2*)extension->data,
  9879. isRequest);
  9880. break;
  9881. case TLSX_RENEGOTIATION_INFO:
  9882. length += SCR_GET_SIZE((SecureRenegotiation*)extension->data,
  9883. isRequest);
  9884. break;
  9885. case TLSX_SESSION_TICKET:
  9886. length += WOLF_STK_GET_SIZE((SessionTicket*)extension->data,
  9887. isRequest);
  9888. break;
  9889. case TLSX_APPLICATION_LAYER_PROTOCOL:
  9890. length += ALPN_GET_SIZE((ALPN*)extension->data);
  9891. break;
  9892. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  9893. case TLSX_SIGNATURE_ALGORITHMS:
  9894. length += SA_GET_SIZE(extension->data);
  9895. break;
  9896. #endif
  9897. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  9898. case TLSX_ENCRYPT_THEN_MAC:
  9899. ret = ETM_GET_SIZE(msgType, &length);
  9900. break;
  9901. #endif /* HAVE_ENCRYPT_THEN_MAC */
  9902. #ifdef WOLFSSL_TLS13
  9903. case TLSX_SUPPORTED_VERSIONS:
  9904. ret = SV_GET_SIZE(extension->data, msgType, &length);
  9905. break;
  9906. #ifdef WOLFSSL_SEND_HRR_COOKIE
  9907. case TLSX_COOKIE:
  9908. ret = CKE_GET_SIZE((Cookie*)extension->data, msgType, &length);
  9909. break;
  9910. #endif
  9911. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  9912. case TLSX_PRE_SHARED_KEY:
  9913. ret = PSK_GET_SIZE((PreSharedKey*)extension->data, msgType,
  9914. &length);
  9915. break;
  9916. case TLSX_PSK_KEY_EXCHANGE_MODES:
  9917. ret = PKM_GET_SIZE((byte)extension->val, msgType, &length);
  9918. break;
  9919. #endif
  9920. #ifdef WOLFSSL_EARLY_DATA
  9921. case TLSX_EARLY_DATA:
  9922. ret = EDI_GET_SIZE(msgType, &length);
  9923. break;
  9924. #endif
  9925. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  9926. case TLSX_POST_HANDSHAKE_AUTH:
  9927. ret = PHA_GET_SIZE(msgType, &length);
  9928. break;
  9929. #endif
  9930. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  9931. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  9932. length += SAC_GET_SIZE(extension->data);
  9933. break;
  9934. #endif
  9935. case TLSX_KEY_SHARE:
  9936. length += KS_GET_SIZE((KeyShareEntry*)extension->data, msgType);
  9937. break;
  9938. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  9939. case TLSX_CERTIFICATE_AUTHORITIES:
  9940. length += CAN_GET_SIZE(extension->data);
  9941. break;
  9942. #endif
  9943. #endif
  9944. #ifdef WOLFSSL_SRTP
  9945. case TLSX_USE_SRTP:
  9946. length += SRTP_GET_SIZE((TlsxSrtp*)extension->data);
  9947. break;
  9948. #endif
  9949. #ifdef WOLFSSL_QUIC
  9950. case TLSX_KEY_QUIC_TP_PARAMS:
  9951. FALL_THROUGH; /* followed by */
  9952. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  9953. length += QTP_GET_SIZE(extension);
  9954. break;
  9955. #endif
  9956. #ifdef WOLFSSL_DTLS_CID
  9957. case TLSX_CONNECTION_ID:
  9958. length += CID_GET_SIZE((byte*)extension->data);
  9959. break;
  9960. #endif /* WOLFSSL_DTLS_CID */
  9961. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  9962. case TLSX_ECH:
  9963. length += ECH_GET_SIZE((WOLFSSL_ECH*)extension->data);
  9964. break;
  9965. #endif
  9966. default:
  9967. break;
  9968. }
  9969. /* marks the extension as processed so ctx level */
  9970. /* extensions don't overlap with ssl level ones. */
  9971. TURN_ON(semaphore, TLSX_ToSemaphore(extension->type));
  9972. }
  9973. *pLength += length;
  9974. return ret;
  9975. }
  9976. /** Writes the extensions of a list in a buffer. */
  9977. static int TLSX_Write(TLSX* list, byte* output, byte* semaphore,
  9978. byte msgType, word16* pOffset)
  9979. {
  9980. int ret = 0;
  9981. TLSX* extension;
  9982. word16 offset = 0;
  9983. word16 length_offset = 0;
  9984. byte isRequest = (msgType == client_hello ||
  9985. msgType == certificate_request);
  9986. while ((extension = list)) {
  9987. list = extension->next;
  9988. /* only extensions marked as response are written in a response. */
  9989. if (!isRequest && !extension->resp)
  9990. continue; /* skip! */
  9991. /* ssl level extensions are expected to override ctx level ones. */
  9992. if (!IS_OFF(semaphore, TLSX_ToSemaphore(extension->type)))
  9993. continue; /* skip! */
  9994. /* writes extension type. */
  9995. c16toa(extension->type, output + offset);
  9996. offset += HELLO_EXT_TYPE_SZ + OPAQUE16_LEN;
  9997. length_offset = offset;
  9998. /* extension data should be written internally. */
  9999. switch (extension->type) {
  10000. #ifdef HAVE_SNI
  10001. case TLSX_SERVER_NAME:
  10002. if (isRequest) {
  10003. WOLFSSL_MSG("SNI extension to write");
  10004. offset += SNI_WRITE((SNI*)extension->data, output + offset);
  10005. }
  10006. break;
  10007. #endif
  10008. case TLSX_TRUSTED_CA_KEYS:
  10009. WOLFSSL_MSG("Trusted CA Indication extension to write");
  10010. if (isRequest) {
  10011. offset += TCA_WRITE((TCA*)extension->data, output + offset);
  10012. }
  10013. break;
  10014. case TLSX_MAX_FRAGMENT_LENGTH:
  10015. WOLFSSL_MSG("Max Fragment Length extension to write");
  10016. offset += MFL_WRITE((byte*)extension->data, output + offset);
  10017. break;
  10018. case TLSX_EXTENDED_MASTER_SECRET:
  10019. WOLFSSL_MSG("Extended Master Secret");
  10020. /* always empty. */
  10021. break;
  10022. case TLSX_TRUNCATED_HMAC:
  10023. WOLFSSL_MSG("Truncated HMAC extension to write");
  10024. /* always empty. */
  10025. break;
  10026. case TLSX_SUPPORTED_GROUPS:
  10027. WOLFSSL_MSG("Supported Groups extension to write");
  10028. offset += EC_WRITE((SupportedCurve*)extension->data,
  10029. output + offset);
  10030. break;
  10031. case TLSX_EC_POINT_FORMATS:
  10032. WOLFSSL_MSG("Point Formats extension to write");
  10033. offset += PF_WRITE((PointFormat*)extension->data,
  10034. output + offset);
  10035. break;
  10036. case TLSX_STATUS_REQUEST:
  10037. WOLFSSL_MSG("Certificate Status Request extension to write");
  10038. offset += CSR_WRITE((CertificateStatusRequest*)extension->data,
  10039. output + offset, isRequest);
  10040. break;
  10041. case TLSX_STATUS_REQUEST_V2:
  10042. WOLFSSL_MSG("Certificate Status Request v2 extension to write");
  10043. offset += CSR2_WRITE(
  10044. (CertificateStatusRequestItemV2*)extension->data,
  10045. output + offset, isRequest);
  10046. break;
  10047. case TLSX_RENEGOTIATION_INFO:
  10048. WOLFSSL_MSG("Secure Renegotiation extension to write");
  10049. offset += SCR_WRITE((SecureRenegotiation*)extension->data,
  10050. output + offset, isRequest);
  10051. break;
  10052. case TLSX_SESSION_TICKET:
  10053. WOLFSSL_MSG("Session Ticket extension to write");
  10054. offset += WOLF_STK_WRITE((SessionTicket*)extension->data,
  10055. output + offset, isRequest);
  10056. break;
  10057. case TLSX_APPLICATION_LAYER_PROTOCOL:
  10058. WOLFSSL_MSG("ALPN extension to write");
  10059. offset += ALPN_WRITE((ALPN*)extension->data, output + offset);
  10060. break;
  10061. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10062. case TLSX_SIGNATURE_ALGORITHMS:
  10063. WOLFSSL_MSG("Signature Algorithms extension to write");
  10064. offset += SA_WRITE(extension->data, output + offset);
  10065. break;
  10066. #endif
  10067. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10068. case TLSX_ENCRYPT_THEN_MAC:
  10069. WOLFSSL_MSG("Encrypt-Then-Mac extension to write");
  10070. ret = ETM_WRITE(extension->data, output, msgType, &offset);
  10071. break;
  10072. #endif /* HAVE_ENCRYPT_THEN_MAC */
  10073. #ifdef WOLFSSL_TLS13
  10074. case TLSX_SUPPORTED_VERSIONS:
  10075. WOLFSSL_MSG("Supported Versions extension to write");
  10076. ret = SV_WRITE(extension->data, output + offset, msgType, &offset);
  10077. break;
  10078. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10079. case TLSX_COOKIE:
  10080. WOLFSSL_MSG("Cookie extension to write");
  10081. ret = CKE_WRITE((Cookie*)extension->data, output + offset,
  10082. msgType, &offset);
  10083. break;
  10084. #endif
  10085. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10086. case TLSX_PRE_SHARED_KEY:
  10087. WOLFSSL_MSG("Pre-Shared Key extension to write");
  10088. ret = PSK_WRITE((PreSharedKey*)extension->data, output + offset,
  10089. msgType, &offset);
  10090. break;
  10091. case TLSX_PSK_KEY_EXCHANGE_MODES:
  10092. WOLFSSL_MSG("PSK Key Exchange Modes extension to write");
  10093. ret = PKM_WRITE((byte)extension->val, output + offset, msgType,
  10094. &offset);
  10095. break;
  10096. #endif
  10097. #ifdef WOLFSSL_EARLY_DATA
  10098. case TLSX_EARLY_DATA:
  10099. WOLFSSL_MSG("Early Data extension to write");
  10100. ret = EDI_WRITE(extension->val, output + offset, msgType,
  10101. &offset);
  10102. break;
  10103. #endif
  10104. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10105. case TLSX_POST_HANDSHAKE_AUTH:
  10106. WOLFSSL_MSG("Post-Handshake Authentication extension to write");
  10107. ret = PHA_WRITE(output + offset, msgType, &offset);
  10108. break;
  10109. #endif
  10110. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10111. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  10112. WOLFSSL_MSG("Signature Algorithms extension to write");
  10113. offset += SAC_WRITE(extension->data, output + offset);
  10114. break;
  10115. #endif
  10116. case TLSX_KEY_SHARE:
  10117. WOLFSSL_MSG("Key Share extension to write");
  10118. offset += KS_WRITE((KeyShareEntry*)extension->data,
  10119. output + offset, msgType);
  10120. break;
  10121. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10122. case TLSX_CERTIFICATE_AUTHORITIES:
  10123. WOLFSSL_MSG("Certificate Authorities extension to write");
  10124. offset += CAN_WRITE(extension->data, output + offset);
  10125. break;
  10126. #endif
  10127. #endif
  10128. #ifdef WOLFSSL_SRTP
  10129. case TLSX_USE_SRTP:
  10130. offset += SRTP_WRITE((TlsxSrtp*)extension->data, output+offset);
  10131. break;
  10132. #endif
  10133. #ifdef WOLFSSL_QUIC
  10134. case TLSX_KEY_QUIC_TP_PARAMS:
  10135. FALL_THROUGH;
  10136. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  10137. WOLFSSL_MSG("QUIC transport parameter to write");
  10138. offset += QTP_WRITE((QuicTransportParam*)extension->data,
  10139. output + offset);
  10140. break;
  10141. #endif
  10142. #ifdef WOLFSSL_DTLS_CID
  10143. case TLSX_CONNECTION_ID:
  10144. offset += CID_WRITE((byte*)extension->data, output+offset);
  10145. break;
  10146. #endif /* WOLFSSL_DTLS_CID */
  10147. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10148. case TLSX_ECH:
  10149. ret = ECH_WRITE((WOLFSSL_ECH*)extension->data,
  10150. output + offset, &offset);
  10151. break;
  10152. #endif
  10153. default:
  10154. break;
  10155. }
  10156. /* writes extension data length. */
  10157. c16toa(offset - length_offset, output + length_offset - OPAQUE16_LEN);
  10158. /* marks the extension as processed so ctx level */
  10159. /* extensions don't overlap with ssl level ones. */
  10160. TURN_ON(semaphore, TLSX_ToSemaphore(extension->type));
  10161. /* if we encountered an error propagate it */
  10162. if (ret != 0)
  10163. break;
  10164. }
  10165. *pOffset += offset;
  10166. return ret;
  10167. }
  10168. #ifdef HAVE_SUPPORTED_CURVES
  10169. /* Populates the default supported groups / curves */
  10170. static int TLSX_PopulateSupportedGroups(WOLFSSL* ssl, TLSX** extensions)
  10171. {
  10172. int ret = WOLFSSL_SUCCESS;
  10173. #ifdef WOLFSSL_TLS13
  10174. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10175. if (ssl->options.resuming && ssl->session->namedGroup != 0) {
  10176. return TLSX_UseSupportedCurve(extensions, ssl->session->namedGroup,
  10177. ssl->heap);
  10178. }
  10179. #endif
  10180. if (ssl->numGroups != 0) {
  10181. int i;
  10182. for (i = 0; i < ssl->numGroups; i++) {
  10183. ret = TLSX_UseSupportedCurve(extensions, ssl->group[i], ssl->heap);
  10184. if (ret != WOLFSSL_SUCCESS)
  10185. return ret;
  10186. }
  10187. return WOLFSSL_SUCCESS;
  10188. }
  10189. #endif /* WOLFSSL_TLS13 */
  10190. #if defined(HAVE_ECC)
  10191. /* list in order by strength, since not all servers choose by strength */
  10192. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  10193. #ifndef NO_ECC_SECP
  10194. ret = TLSX_UseSupportedCurve(extensions,
  10195. WOLFSSL_ECC_SECP521R1, ssl->heap);
  10196. if (ret != WOLFSSL_SUCCESS) return ret;
  10197. #endif
  10198. #endif
  10199. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  10200. #ifdef HAVE_ECC_BRAINPOOL
  10201. ret = TLSX_UseSupportedCurve(extensions,
  10202. WOLFSSL_ECC_BRAINPOOLP512R1, ssl->heap);
  10203. if (ret != WOLFSSL_SUCCESS) return ret;
  10204. #endif
  10205. #endif
  10206. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  10207. #ifndef NO_ECC_SECP
  10208. ret = TLSX_UseSupportedCurve(extensions,
  10209. WOLFSSL_ECC_SECP384R1, ssl->heap);
  10210. if (ret != WOLFSSL_SUCCESS) return ret;
  10211. #endif
  10212. #ifdef HAVE_ECC_BRAINPOOL
  10213. ret = TLSX_UseSupportedCurve(extensions,
  10214. WOLFSSL_ECC_BRAINPOOLP384R1, ssl->heap);
  10215. if (ret != WOLFSSL_SUCCESS) return ret;
  10216. #endif
  10217. #endif
  10218. #endif /* HAVE_ECC */
  10219. #ifndef HAVE_FIPS
  10220. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  10221. ret = TLSX_UseSupportedCurve(extensions,
  10222. WOLFSSL_ECC_X448, ssl->heap);
  10223. if (ret != WOLFSSL_SUCCESS) return ret;
  10224. #endif
  10225. #endif /* HAVE_FIPS */
  10226. #if defined(HAVE_ECC) && defined(HAVE_SUPPORTED_CURVES)
  10227. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  10228. #ifndef NO_ECC_SECP
  10229. ret = TLSX_UseSupportedCurve(extensions,
  10230. WOLFSSL_ECC_SECP256R1, ssl->heap);
  10231. if (ret != WOLFSSL_SUCCESS) return ret;
  10232. #endif
  10233. #ifdef HAVE_ECC_KOBLITZ
  10234. ret = TLSX_UseSupportedCurve(extensions,
  10235. WOLFSSL_ECC_SECP256K1, ssl->heap);
  10236. if (ret != WOLFSSL_SUCCESS) return ret;
  10237. #endif
  10238. #ifdef HAVE_ECC_BRAINPOOL
  10239. ret = TLSX_UseSupportedCurve(extensions,
  10240. WOLFSSL_ECC_BRAINPOOLP256R1, ssl->heap);
  10241. if (ret != WOLFSSL_SUCCESS) return ret;
  10242. #endif
  10243. #ifdef WOLFSSL_SM2
  10244. ret = TLSX_UseSupportedCurve(extensions,
  10245. WOLFSSL_ECC_SM2P256V1, ssl->heap);
  10246. if (ret != WOLFSSL_SUCCESS) return ret;
  10247. #endif
  10248. #endif
  10249. #endif /* HAVE_ECC */
  10250. #ifndef HAVE_FIPS
  10251. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  10252. ret = TLSX_UseSupportedCurve(extensions,
  10253. WOLFSSL_ECC_X25519, ssl->heap);
  10254. if (ret != WOLFSSL_SUCCESS) return ret;
  10255. #endif
  10256. #endif /* HAVE_FIPS */
  10257. #if defined(HAVE_ECC) && defined(HAVE_SUPPORTED_CURVES)
  10258. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  10259. #ifndef NO_ECC_SECP
  10260. ret = TLSX_UseSupportedCurve(extensions,
  10261. WOLFSSL_ECC_SECP224R1, ssl->heap);
  10262. if (ret != WOLFSSL_SUCCESS) return ret;
  10263. #endif
  10264. #ifdef HAVE_ECC_KOBLITZ
  10265. ret = TLSX_UseSupportedCurve(extensions,
  10266. WOLFSSL_ECC_SECP224K1, ssl->heap);
  10267. if (ret != WOLFSSL_SUCCESS) return ret;
  10268. #endif
  10269. #endif
  10270. #ifndef HAVE_FIPS
  10271. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  10272. #ifndef NO_ECC_SECP
  10273. ret = TLSX_UseSupportedCurve(extensions,
  10274. WOLFSSL_ECC_SECP192R1, ssl->heap);
  10275. if (ret != WOLFSSL_SUCCESS) return ret;
  10276. #endif
  10277. #ifdef HAVE_ECC_KOBLITZ
  10278. ret = TLSX_UseSupportedCurve(extensions,
  10279. WOLFSSL_ECC_SECP192K1, ssl->heap);
  10280. if (ret != WOLFSSL_SUCCESS) return ret;
  10281. #endif
  10282. #endif
  10283. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  10284. #ifndef NO_ECC_SECP
  10285. ret = TLSX_UseSupportedCurve(extensions,
  10286. WOLFSSL_ECC_SECP160R1, ssl->heap);
  10287. if (ret != WOLFSSL_SUCCESS) return ret;
  10288. #endif
  10289. #ifdef HAVE_ECC_SECPR2
  10290. ret = TLSX_UseSupportedCurve(extensions,
  10291. WOLFSSL_ECC_SECP160R2, ssl->heap);
  10292. if (ret != WOLFSSL_SUCCESS) return ret;
  10293. #endif
  10294. #ifdef HAVE_ECC_KOBLITZ
  10295. ret = TLSX_UseSupportedCurve(extensions,
  10296. WOLFSSL_ECC_SECP160K1, ssl->heap);
  10297. if (ret != WOLFSSL_SUCCESS) return ret;
  10298. #endif
  10299. #endif
  10300. #endif /* HAVE_FIPS */
  10301. #endif /* HAVE_ECC */
  10302. #ifndef NO_DH
  10303. /* Add FFDHE supported groups. */
  10304. #ifdef HAVE_FFDHE_8192
  10305. if (8192/8 >= ssl->options.minDhKeySz &&
  10306. 8192/8 <= ssl->options.maxDhKeySz) {
  10307. ret = TLSX_UseSupportedCurve(extensions,
  10308. WOLFSSL_FFDHE_8192, ssl->heap);
  10309. if (ret != WOLFSSL_SUCCESS)
  10310. return ret;
  10311. }
  10312. #endif
  10313. #ifdef HAVE_FFDHE_6144
  10314. if (6144/8 >= ssl->options.minDhKeySz &&
  10315. 6144/8 <= ssl->options.maxDhKeySz) {
  10316. ret = TLSX_UseSupportedCurve(extensions,
  10317. WOLFSSL_FFDHE_6144, ssl->heap);
  10318. if (ret != WOLFSSL_SUCCESS)
  10319. return ret;
  10320. }
  10321. #endif
  10322. #ifdef HAVE_FFDHE_4096
  10323. if (4096/8 >= ssl->options.minDhKeySz &&
  10324. 4096/8 <= ssl->options.maxDhKeySz) {
  10325. ret = TLSX_UseSupportedCurve(extensions,
  10326. WOLFSSL_FFDHE_4096, ssl->heap);
  10327. if (ret != WOLFSSL_SUCCESS)
  10328. return ret;
  10329. }
  10330. #endif
  10331. #ifdef HAVE_FFDHE_3072
  10332. if (3072/8 >= ssl->options.minDhKeySz &&
  10333. 3072/8 <= ssl->options.maxDhKeySz) {
  10334. ret = TLSX_UseSupportedCurve(extensions,
  10335. WOLFSSL_FFDHE_3072, ssl->heap);
  10336. if (ret != WOLFSSL_SUCCESS)
  10337. return ret;
  10338. }
  10339. #endif
  10340. #ifdef HAVE_FFDHE_2048
  10341. if (2048/8 >= ssl->options.minDhKeySz &&
  10342. 2048/8 <= ssl->options.maxDhKeySz) {
  10343. ret = TLSX_UseSupportedCurve(extensions,
  10344. WOLFSSL_FFDHE_2048, ssl->heap);
  10345. if (ret != WOLFSSL_SUCCESS)
  10346. return ret;
  10347. }
  10348. #endif
  10349. #endif
  10350. #ifdef HAVE_PQC
  10351. #ifdef WOLFSSL_WC_KYBER
  10352. #ifdef WOLFSSL_KYBER512
  10353. if (ret == WOLFSSL_SUCCESS)
  10354. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1,
  10355. ssl->heap);
  10356. #endif
  10357. #ifdef WOLFSSL_KYBER768
  10358. if (ret == WOLFSSL_SUCCESS)
  10359. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3,
  10360. ssl->heap);
  10361. #endif
  10362. #ifdef WOLFSSL_KYBER768
  10363. if (ret == WOLFSSL_SUCCESS)
  10364. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5,
  10365. ssl->heap);
  10366. #endif
  10367. #elif defined(HAVE_LIBOQS)
  10368. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap);
  10369. if (ret == WOLFSSL_SUCCESS)
  10370. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL3,
  10371. ssl->heap);
  10372. if (ret == WOLFSSL_SUCCESS)
  10373. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL5,
  10374. ssl->heap);
  10375. if (ret == WOLFSSL_SUCCESS)
  10376. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P256_KYBER_LEVEL1,
  10377. ssl->heap);
  10378. if (ret == WOLFSSL_SUCCESS)
  10379. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P384_KYBER_LEVEL3,
  10380. ssl->heap);
  10381. if (ret == WOLFSSL_SUCCESS)
  10382. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_P521_KYBER_LEVEL5,
  10383. ssl->heap);
  10384. #elif defined(HAVE_PQM4)
  10385. ret = TLSX_UseSupportedCurve(extensions, WOLFSSL_KYBER_LEVEL1, ssl->heap);
  10386. #endif /* HAVE_LIBOQS */
  10387. #endif /* HAVE_PQC */
  10388. (void)ssl;
  10389. (void)extensions;
  10390. return ret;
  10391. }
  10392. #endif /* HAVE_SUPPORTED_CURVES */
  10393. int TLSX_PopulateExtensions(WOLFSSL* ssl, byte isServer)
  10394. {
  10395. int ret = 0;
  10396. byte* public_key = NULL;
  10397. word16 public_key_len = 0;
  10398. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  10399. int usingPSK = 0;
  10400. #endif
  10401. #if defined(HAVE_SUPPORTED_CURVES) && defined(WOLFSSL_TLS13)
  10402. TLSX* extension = NULL;
  10403. word16 namedGroup = WOLFSSL_NAMED_GROUP_INVALID;
  10404. #endif
  10405. /* server will add extension depending on what is parsed from client */
  10406. if (!isServer) {
  10407. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10408. if (!ssl->options.disallowEncThenMac) {
  10409. ret = TLSX_EncryptThenMac_Use(ssl);
  10410. if (ret != 0)
  10411. return ret;
  10412. }
  10413. #endif
  10414. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  10415. defined(HAVE_CURVE448)) && defined(HAVE_SUPPORTED_CURVES)
  10416. if (!ssl->options.userCurves && !ssl->ctx->userCurves) {
  10417. if (TLSX_Find(ssl->ctx->extensions,
  10418. TLSX_SUPPORTED_GROUPS) == NULL) {
  10419. ret = TLSX_PopulateSupportedGroups(ssl, &ssl->extensions);
  10420. if (ret != WOLFSSL_SUCCESS)
  10421. return ret;
  10422. }
  10423. }
  10424. if ((!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade) &&
  10425. TLSX_Find(ssl->ctx->extensions, TLSX_EC_POINT_FORMATS) == NULL &&
  10426. TLSX_Find(ssl->extensions, TLSX_EC_POINT_FORMATS) == NULL) {
  10427. ret = TLSX_UsePointFormat(&ssl->extensions,
  10428. WOLFSSL_EC_PF_UNCOMPRESSED, ssl->heap);
  10429. if (ret != WOLFSSL_SUCCESS)
  10430. return ret;
  10431. }
  10432. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && HAVE_SUPPORTED_CURVES */
  10433. #ifdef WOLFSSL_SRTP
  10434. if (ssl->options.dtls && ssl->dtlsSrtpProfiles != 0) {
  10435. WOLFSSL_MSG("Adding DTLS SRTP extension");
  10436. if ((ret = TLSX_UseSRTP(&ssl->extensions, ssl->dtlsSrtpProfiles,
  10437. ssl->heap)) != 0) {
  10438. return ret;
  10439. }
  10440. }
  10441. #endif
  10442. } /* is not server */
  10443. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10444. WOLFSSL_MSG("Adding signature algorithms extension");
  10445. if ((ret = TLSX_SetSignatureAlgorithms(&ssl->extensions, ssl, ssl->heap))
  10446. != 0) {
  10447. return ret;
  10448. }
  10449. #else
  10450. ret = 0;
  10451. #endif
  10452. #ifdef WOLFSSL_TLS13
  10453. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10454. if (isServer && IsAtLeastTLSv1_3(ssl->version)) {
  10455. if (SSL_CA_NAMES(ssl) != NULL) {
  10456. WOLFSSL_MSG("Adding certificate authorities extension");
  10457. if ((ret = TLSX_Push(&ssl->extensions,
  10458. TLSX_CERTIFICATE_AUTHORITIES, ssl, ssl->heap)) != 0) {
  10459. return ret;
  10460. }
  10461. }
  10462. }
  10463. #endif
  10464. if (!isServer && IsAtLeastTLSv1_3(ssl->version)) {
  10465. /* Add mandatory TLS v1.3 extension: supported version */
  10466. WOLFSSL_MSG("Adding supported versions extension");
  10467. if ((ret = TLSX_SetSupportedVersions(&ssl->extensions, ssl,
  10468. ssl->heap)) != 0) {
  10469. return ret;
  10470. }
  10471. #if !defined(HAVE_ECC) && !defined(HAVE_CURVE25519) && \
  10472. !defined(HAVE_CURVE448) && defined(HAVE_SUPPORTED_CURVES)
  10473. if (TLSX_Find(ssl->ctx->extensions, TLSX_SUPPORTED_GROUPS) == NULL) {
  10474. /* Put in DH groups for TLS 1.3 only. */
  10475. ret = TLSX_PopulateSupportedGroups(ssl, &ssl->extensions);
  10476. if (ret != WOLFSSL_SUCCESS)
  10477. return ret;
  10478. /* ret value will be overwritten in !NO_PSK case */
  10479. #ifdef NO_PSK
  10480. ret = 0;
  10481. #endif
  10482. }
  10483. #endif /* !(HAVE_ECC || CURVE25519 || CURVE448) && HAVE_SUPPORTED_CURVES */
  10484. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10485. if (ssl->certHashSigAlgoSz > 0) {
  10486. WOLFSSL_MSG("Adding signature algorithms cert extension");
  10487. if ((ret = TLSX_SetSignatureAlgorithmsCert(&ssl->extensions,
  10488. ssl, ssl->heap)) != 0) {
  10489. return ret;
  10490. }
  10491. }
  10492. #endif
  10493. #if defined(HAVE_SUPPORTED_CURVES)
  10494. extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
  10495. if (extension == NULL) {
  10496. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10497. if (ssl->options.resuming && ssl->session->namedGroup != 0)
  10498. namedGroup = ssl->session->namedGroup;
  10499. else
  10500. #endif
  10501. if (ssl->numGroups > 0) {
  10502. int set = 0;
  10503. int i, j;
  10504. /* try to find the highest element in ssl->group[]
  10505. * that is contained in preferredGroup[].
  10506. */
  10507. namedGroup = preferredGroup[0];
  10508. for (i = 0; i < ssl->numGroups && !set; i++) {
  10509. for (j = 0; preferredGroup[j] != WOLFSSL_NAMED_GROUP_INVALID; j++) {
  10510. if (preferredGroup[j] == ssl->group[i]
  10511. #ifdef HAVE_LIBOQS
  10512. && TLSX_KeyShare_IsSupported(preferredGroup[j])
  10513. #endif
  10514. ) {
  10515. namedGroup = ssl->group[i];
  10516. set = 1;
  10517. break;
  10518. }
  10519. }
  10520. }
  10521. if (!set)
  10522. namedGroup = WOLFSSL_NAMED_GROUP_INVALID;
  10523. }
  10524. else {
  10525. /* Choose the most preferred group. */
  10526. namedGroup = preferredGroup[0];
  10527. #ifdef HAVE_LIBOQS
  10528. if (!TLSX_KeyShare_IsSupported(namedGroup)) {
  10529. int i = 1;
  10530. for (;preferredGroup[i] != WOLFSSL_NAMED_GROUP_INVALID;
  10531. i++) {
  10532. if (TLSX_KeyShare_IsSupported(preferredGroup[i]))
  10533. break;
  10534. }
  10535. namedGroup = preferredGroup[i];
  10536. }
  10537. #endif
  10538. }
  10539. }
  10540. else {
  10541. KeyShareEntry* kse = (KeyShareEntry*)extension->data;
  10542. if (kse)
  10543. namedGroup = kse->group;
  10544. }
  10545. if (namedGroup != WOLFSSL_NAMED_GROUP_INVALID) {
  10546. #ifdef HAVE_PQC
  10547. /* For KEMs, the key share has already been generated, but not
  10548. * if we are resuming. */
  10549. if (!WOLFSSL_NAMED_GROUP_IS_PQC(namedGroup)
  10550. #ifdef HAVE_SESSION_TICKET
  10551. || ssl->options.resuming
  10552. #endif /* HAVE_SESSION_TICKET */
  10553. )
  10554. #endif /* HAVE_PQC */
  10555. {
  10556. ret = TLSX_KeyShare_Use(ssl, namedGroup, 0, NULL, NULL,
  10557. &ssl->extensions);
  10558. }
  10559. if (ret != 0)
  10560. return ret;
  10561. }
  10562. #endif /* HAVE_SUPPORTED_CURVES */
  10563. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10564. TLSX_Remove(&ssl->extensions, TLSX_PRE_SHARED_KEY, ssl->heap);
  10565. #endif
  10566. #if defined(HAVE_SESSION_TICKET)
  10567. if (ssl->options.resuming && ssl->session->ticketLen > 0) {
  10568. WOLFSSL_SESSION* sess = ssl->session;
  10569. #ifdef WOLFSSL_32BIT_MILLI_TIME
  10570. word32 now, milli;
  10571. #else
  10572. word64 now, milli;
  10573. #endif
  10574. if (sess->ticketLen > MAX_PSK_ID_LEN) {
  10575. WOLFSSL_MSG("Session ticket length for PSK ext is too large");
  10576. return BUFFER_ERROR;
  10577. }
  10578. /* Determine the MAC algorithm for the cipher suite used. */
  10579. ssl->options.cipherSuite0 = sess->cipherSuite0;
  10580. ssl->options.cipherSuite = sess->cipherSuite;
  10581. ret = SetCipherSpecs(ssl);
  10582. if (ret != 0)
  10583. return ret;
  10584. now = TimeNowInMilliseconds();
  10585. if (now == 0)
  10586. return GETTIME_ERROR;
  10587. #ifdef WOLFSSL_32BIT_MILLI_TIME
  10588. if (now < sess->ticketSeen)
  10589. milli = (0xFFFFFFFFU - sess->ticketSeen) + 1 + now;
  10590. else
  10591. milli = now - sess->ticketSeen;
  10592. milli += sess->ticketAdd;
  10593. /* Pre-shared key is mandatory extension for resumption. */
  10594. ret = TLSX_PreSharedKey_Use(&ssl->extensions, sess->ticket,
  10595. sess->ticketLen, milli, ssl->specs.mac_algorithm,
  10596. ssl->options.cipherSuite0, ssl->options.cipherSuite, 1,
  10597. NULL, ssl->heap);
  10598. #else
  10599. milli = now - sess->ticketSeen + sess->ticketAdd;
  10600. /* Pre-shared key is mandatory extension for resumption. */
  10601. ret = TLSX_PreSharedKey_Use(&ssl->extensions, sess->ticket,
  10602. sess->ticketLen, (word32)milli, ssl->specs.mac_algorithm,
  10603. ssl->options.cipherSuite0, ssl->options.cipherSuite, 1,
  10604. NULL, ssl->heap);
  10605. #endif
  10606. if (ret != 0)
  10607. return ret;
  10608. usingPSK = 1;
  10609. }
  10610. #endif
  10611. #ifndef NO_PSK
  10612. #ifndef WOLFSSL_PSK_ONE_ID
  10613. if (ssl->options.client_psk_cs_cb != NULL) {
  10614. int i;
  10615. const Suites* suites = WOLFSSL_SUITES(ssl);
  10616. for (i = 0; i < suites->suiteSz; i += 2) {
  10617. byte cipherSuite0 = suites->suites[i + 0];
  10618. byte cipherSuite = suites->suites[i + 1];
  10619. unsigned int keySz;
  10620. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  10621. int cnt = 0;
  10622. #endif
  10623. #ifdef HAVE_NULL_CIPHER
  10624. if (cipherSuite0 == ECC_BYTE ||
  10625. cipherSuite0 == ECDHE_PSK_BYTE) {
  10626. if (cipherSuite != TLS_SHA256_SHA256 &&
  10627. cipherSuite != TLS_SHA384_SHA384) {
  10628. continue;
  10629. }
  10630. }
  10631. else
  10632. #endif
  10633. #if (defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)) && \
  10634. defined(WOLFSSL_SM3)
  10635. if (cipherSuite0 == CIPHER_BYTE) {
  10636. if ((cipherSuite != TLS_SM4_GCM_SM3) &&
  10637. (cipherSuite != TLS_SM4_CCM_SM3)) {
  10638. continue;
  10639. }
  10640. }
  10641. else
  10642. #endif
  10643. if (cipherSuite0 != TLS13_BYTE)
  10644. continue;
  10645. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  10646. do {
  10647. ssl->arrays->client_identity[0] = cnt;
  10648. #endif
  10649. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  10650. keySz = ssl->options.client_psk_cs_cb(
  10651. ssl, ssl->arrays->server_hint,
  10652. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  10653. ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
  10654. GetCipherNameInternal(cipherSuite0, cipherSuite));
  10655. if (keySz > 0) {
  10656. ssl->arrays->psk_keySz = keySz;
  10657. ret = TLSX_PreSharedKey_Use(&ssl->extensions,
  10658. (byte*)ssl->arrays->client_identity,
  10659. (word16)XSTRLEN(ssl->arrays->client_identity),
  10660. 0, SuiteMac(WOLFSSL_SUITES(ssl)->suites + i),
  10661. cipherSuite0, cipherSuite, 0, NULL, ssl->heap);
  10662. if (ret != 0)
  10663. return ret;
  10664. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  10665. cnt++;
  10666. #endif
  10667. }
  10668. #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
  10669. }
  10670. while (keySz > 0);
  10671. #endif
  10672. }
  10673. usingPSK = 1;
  10674. }
  10675. else
  10676. #endif
  10677. if (ssl->options.client_psk_cb != NULL ||
  10678. ssl->options.client_psk_tls13_cb != NULL) {
  10679. /* Default cipher suite. */
  10680. byte cipherSuite0 = TLS13_BYTE;
  10681. byte cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
  10682. int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
  10683. const char* cipherName = NULL;
  10684. if (ssl->options.client_psk_tls13_cb != NULL) {
  10685. ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(
  10686. ssl, ssl->arrays->server_hint,
  10687. ssl->arrays->client_identity, MAX_PSK_ID_LEN,
  10688. ssl->arrays->psk_key, MAX_PSK_KEY_LEN, &cipherName);
  10689. if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
  10690. &cipherSuite, &cipherSuiteFlags) != 0) {
  10691. return PSK_KEY_ERROR;
  10692. }
  10693. }
  10694. else {
  10695. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  10696. ssl->arrays->server_hint, ssl->arrays->client_identity,
  10697. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  10698. }
  10699. #if defined(OPENSSL_EXTRA)
  10700. /* OpenSSL treats 0 as a PSK key length of 0
  10701. * and meaning no PSK available.
  10702. */
  10703. if (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  10704. return PSK_KEY_ERROR;
  10705. }
  10706. if (ssl->arrays->psk_keySz > 0) {
  10707. #else
  10708. if (ssl->arrays->psk_keySz == 0 ||
  10709. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  10710. return PSK_KEY_ERROR;
  10711. }
  10712. #endif
  10713. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  10714. ssl->options.cipherSuite0 = cipherSuite0;
  10715. ssl->options.cipherSuite = cipherSuite;
  10716. (void)cipherSuiteFlags;
  10717. ret = SetCipherSpecs(ssl);
  10718. if (ret != 0)
  10719. return ret;
  10720. ret = TLSX_PreSharedKey_Use(&ssl->extensions,
  10721. (byte*)ssl->arrays->client_identity,
  10722. (word16)XSTRLEN(ssl->arrays->client_identity),
  10723. 0, ssl->specs.mac_algorithm,
  10724. cipherSuite0, cipherSuite, 0,
  10725. NULL, ssl->heap);
  10726. if (ret != 0)
  10727. return ret;
  10728. usingPSK = 1;
  10729. #if defined(OPENSSL_EXTRA)
  10730. }
  10731. #endif
  10732. }
  10733. #endif /* !NO_PSK */
  10734. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10735. /* Some servers do not generate session tickets unless
  10736. * the extension is seen in a non-resume client hello.
  10737. * We used to send it only if we were otherwise using PSK.
  10738. * Now always send it. Define NO_TLSX_PSKKEM_PLAIN_ANNOUNCE
  10739. * to revert to the old behaviour. */
  10740. #ifdef NO_TLSX_PSKKEM_PLAIN_ANNOUNCE
  10741. if (usingPSK)
  10742. #endif
  10743. {
  10744. byte modes = 0;
  10745. (void)usingPSK;
  10746. /* Pre-shared key modes: mandatory extension for resumption. */
  10747. #ifdef HAVE_SUPPORTED_CURVES
  10748. if (!ssl->options.onlyPskDheKe)
  10749. #endif
  10750. {
  10751. modes = 1 << PSK_KE;
  10752. }
  10753. #if !defined(NO_DH) || defined(HAVE_ECC) || \
  10754. defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  10755. if (!ssl->options.noPskDheKe) {
  10756. modes |= 1 << PSK_DHE_KE;
  10757. }
  10758. #endif
  10759. ret = TLSX_PskKeyModes_Use(ssl, modes);
  10760. if (ret != 0)
  10761. return ret;
  10762. }
  10763. #endif
  10764. #if defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  10765. if (!isServer && ssl->options.postHandshakeAuth) {
  10766. ret = TLSX_PostHandAuth_Use(ssl);
  10767. if (ret != 0)
  10768. return ret;
  10769. }
  10770. #endif
  10771. #if defined(HAVE_ECH)
  10772. /* GREASE ECH */
  10773. if (ssl->echConfigs == NULL) {
  10774. ret = GREASE_ECH_USE(&(ssl->extensions), ssl->heap, ssl->rng);
  10775. }
  10776. else if (ssl->echConfigs != NULL) {
  10777. ret = ECH_USE(ssl->echConfigs, &(ssl->extensions), ssl->heap,
  10778. ssl->rng);
  10779. }
  10780. #endif
  10781. }
  10782. #if defined(HAVE_ECH)
  10783. else if (IsAtLeastTLSv1_3(ssl->version)) {
  10784. if (ssl->ctx->echConfigs != NULL) {
  10785. ret = SERVER_ECH_USE(&(ssl->extensions), ssl->heap,
  10786. ssl->ctx->echConfigs);
  10787. if (ret == 0)
  10788. TLSX_SetResponse(ssl, TLSX_ECH);
  10789. }
  10790. }
  10791. #endif
  10792. #endif
  10793. (void)isServer;
  10794. (void)public_key;
  10795. (void)public_key_len;
  10796. (void)ssl;
  10797. return ret;
  10798. }
  10799. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
  10800. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10801. /* because the size of ech depends on the size of other extensions we need to
  10802. * get the size with ech special and process ech last, return status */
  10803. static int TLSX_GetSizeWithEch(WOLFSSL* ssl, byte* semaphore, byte msgType,
  10804. word16* pLength)
  10805. {
  10806. int ret = 0;
  10807. TLSX* echX = NULL;
  10808. TLSX* serverNameX = NULL;
  10809. TLSX** extensions = NULL;
  10810. #ifdef WOLFSSL_SMALL_STACK
  10811. char* tmpServerName = NULL;
  10812. #else
  10813. char tmpServerName[MAX_PUBLIC_NAME_SZ];
  10814. #endif
  10815. /* calculate the rest of the extensions length with inner ech */
  10816. if (ssl->extensions)
  10817. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  10818. if (echX == NULL && ssl->ctx && ssl->ctx->extensions)
  10819. echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH);
  10820. /* if type is outer change sni to public name */
  10821. if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) {
  10822. if (ssl->extensions) {
  10823. serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  10824. if (serverNameX != NULL)
  10825. extensions = &ssl->extensions;
  10826. }
  10827. if (serverNameX == NULL && ssl->ctx && ssl->ctx->extensions) {
  10828. serverNameX = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  10829. extensions = &ssl->ctx->extensions;
  10830. }
  10831. /* store the inner server name */
  10832. if (serverNameX != NULL) {
  10833. char* hostName = ((SNI*)serverNameX->data)->data.host_name;
  10834. word32 hostNameSz = (word32)XSTRLEN(hostName) + 1;
  10835. #ifdef WOLFSSL_SMALL_STACK
  10836. tmpServerName = (char*)XMALLOC(hostNameSz, ssl->heap,
  10837. DYNAMIC_TYPE_TMP_BUFFER);
  10838. if (tmpServerName == NULL)
  10839. return MEMORY_E;
  10840. #else
  10841. /* truncate if too long */
  10842. if (hostNameSz > MAX_PUBLIC_NAME_SZ)
  10843. hostNameSz = MAX_PUBLIC_NAME_SZ;
  10844. #endif
  10845. XMEMCPY(tmpServerName, hostName, hostNameSz);
  10846. }
  10847. /* remove the inner server name */
  10848. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  10849. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  10850. ((WOLFSSL_ECH*)echX->data)->echConfig->publicName,
  10851. XSTRLEN(((WOLFSSL_ECH*)echX->data)->echConfig->publicName),
  10852. ssl->heap);
  10853. /* set the public name as the server name */
  10854. if (ret == WOLFSSL_SUCCESS)
  10855. ret = 0;
  10856. }
  10857. if (ret == 0 && ssl->extensions)
  10858. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, pLength);
  10859. if (ret == 0 && ssl->ctx && ssl->ctx->extensions)
  10860. ret = TLSX_GetSize(ssl->ctx->extensions, semaphore, msgType, pLength);
  10861. if (serverNameX != NULL) {
  10862. /* remove the public name SNI */
  10863. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  10864. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  10865. tmpServerName, XSTRLEN(tmpServerName), ssl->heap);
  10866. /* restore the inner server name */
  10867. if (ret == WOLFSSL_SUCCESS)
  10868. ret = 0;
  10869. }
  10870. #ifdef WOLFSSL_SMALL_STACK
  10871. XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10872. #endif
  10873. return ret;
  10874. }
  10875. #endif
  10876. /** Tells the buffered size of extensions to be sent into the client hello. */
  10877. int TLSX_GetRequestSize(WOLFSSL* ssl, byte msgType, word16* pLength)
  10878. {
  10879. int ret = 0;
  10880. word16 length = 0;
  10881. byte semaphore[SEMAPHORE_SIZE] = {0};
  10882. if (!TLSX_SupportExtensions(ssl))
  10883. return 0;
  10884. if (msgType == client_hello) {
  10885. EC_VALIDATE_REQUEST(ssl, semaphore);
  10886. PF_VALIDATE_REQUEST(ssl, semaphore);
  10887. WOLF_STK_VALIDATE_REQUEST(ssl);
  10888. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10889. if (WOLFSSL_SUITES(ssl)->hashSigAlgoSz == 0)
  10890. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  10891. #endif
  10892. #if defined(WOLFSSL_TLS13)
  10893. if (!IsAtLeastTLSv1_2(ssl)) {
  10894. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  10895. }
  10896. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  10897. if (!IsAtLeastTLSv1_3(ssl->version)) {
  10898. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  10899. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  10900. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  10901. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PSK_KEY_EXCHANGE_MODES));
  10902. #endif
  10903. #ifdef WOLFSSL_EARLY_DATA
  10904. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  10905. #endif
  10906. #ifdef WOLFSSL_SEND_HRR_COOKIE
  10907. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  10908. #endif
  10909. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  10910. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_POST_HANDSHAKE_AUTH));
  10911. #endif
  10912. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10913. TURN_ON(semaphore,
  10914. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  10915. #endif
  10916. }
  10917. #endif
  10918. #endif /* WOLFSSL_TLS13 */
  10919. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  10920. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  10921. if (!SSL_CM(ssl)->ocspStaplingEnabled) {
  10922. /* mark already sent, so it won't send it */
  10923. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  10924. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  10925. }
  10926. #endif
  10927. }
  10928. #ifdef WOLFSSL_TLS13
  10929. #ifndef NO_CERTS
  10930. else if (msgType == certificate_request) {
  10931. /* Don't send out any extension except those that are turned off. */
  10932. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  10933. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  10934. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  10935. #endif
  10936. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  10937. if (SSL_CA_NAMES(ssl) != NULL)
  10938. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  10939. #endif
  10940. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, OID_FILTERS
  10941. * TLSX_STATUS_REQUEST
  10942. */
  10943. }
  10944. #endif
  10945. #if defined(HAVE_ECH)
  10946. if (ssl->options.useEch == 1 && msgType == client_hello) {
  10947. ret = TLSX_GetSizeWithEch(ssl, semaphore, msgType, &length);
  10948. if (ret != 0)
  10949. return ret;
  10950. }
  10951. else
  10952. #endif /* HAVE_ECH */
  10953. #endif /* WOLFSSL_TLS13 */
  10954. {
  10955. if (ssl->extensions) {
  10956. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, &length);
  10957. if (ret != 0)
  10958. return ret;
  10959. }
  10960. if (ssl->ctx && ssl->ctx->extensions) {
  10961. ret = TLSX_GetSize(ssl->ctx->extensions, semaphore, msgType,
  10962. &length);
  10963. if (ret != 0)
  10964. return ret;
  10965. }
  10966. }
  10967. #ifdef HAVE_EXTENDED_MASTER
  10968. if (msgType == client_hello && ssl->options.haveEMS &&
  10969. (!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade)) {
  10970. length += HELLO_EXT_SZ;
  10971. }
  10972. #endif
  10973. if (length)
  10974. length += OPAQUE16_LEN; /* for total length storage. */
  10975. *pLength += length;
  10976. return ret;
  10977. }
  10978. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  10979. /* return status after writing the extensions with ech written last */
  10980. static int TLSX_WriteWithEch(WOLFSSL* ssl, byte* output, byte* semaphore,
  10981. byte msgType, word16* pOffset)
  10982. {
  10983. int ret = 0;
  10984. TLSX* echX = NULL;
  10985. TLSX* serverNameX = NULL;
  10986. TLSX** extensions = NULL;
  10987. #ifdef WOLFSSL_SMALL_STACK
  10988. char* tmpServerName = NULL;
  10989. #else
  10990. char tmpServerName[MAX_PUBLIC_NAME_SZ];
  10991. #endif
  10992. /* get the echX from either extensions or ctx */
  10993. if (ssl->extensions)
  10994. echX = TLSX_Find(ssl->extensions, TLSX_ECH);
  10995. if (echX == NULL && ssl->ctx && ssl->ctx->extensions) {
  10996. /* if not NULL the semaphore will stop it from being counted */
  10997. if (echX == NULL)
  10998. echX = TLSX_Find(ssl->ctx->extensions, TLSX_ECH);
  10999. }
  11000. /* if type is outer change sni to public name */
  11001. if (echX != NULL && ((WOLFSSL_ECH*)echX->data)->type == ECH_TYPE_OUTER) {
  11002. if (ssl->extensions) {
  11003. serverNameX = TLSX_Find(ssl->extensions, TLSX_SERVER_NAME);
  11004. if (serverNameX != NULL)
  11005. extensions = &ssl->extensions;
  11006. }
  11007. if (serverNameX == NULL && ssl->ctx && ssl->ctx->extensions) {
  11008. serverNameX = TLSX_Find(ssl->ctx->extensions, TLSX_SERVER_NAME);
  11009. extensions = &ssl->ctx->extensions;
  11010. }
  11011. /* store the inner server name */
  11012. if (serverNameX != NULL) {
  11013. char* hostName = ((SNI*)serverNameX->data)->data.host_name;
  11014. word32 hostNameSz = (word32)XSTRLEN(hostName) + 1;
  11015. #ifdef WOLFSSL_SMALL_STACK
  11016. tmpServerName = (char*)XMALLOC(hostNameSz, ssl->heap,
  11017. DYNAMIC_TYPE_TMP_BUFFER);
  11018. if (tmpServerName == NULL)
  11019. return MEMORY_E;
  11020. #else
  11021. /* truncate if too long */
  11022. if (hostNameSz > MAX_PUBLIC_NAME_SZ)
  11023. hostNameSz = MAX_PUBLIC_NAME_SZ;
  11024. #endif
  11025. XMEMCPY(tmpServerName, hostName, hostNameSz);
  11026. }
  11027. /* remove the inner server name */
  11028. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11029. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME,
  11030. ((WOLFSSL_ECH*)echX->data)->echConfig->publicName,
  11031. XSTRLEN(((WOLFSSL_ECH*)echX->data)->echConfig->publicName),
  11032. ssl->heap);
  11033. /* set the public name as the server name */
  11034. if (ret == WOLFSSL_SUCCESS)
  11035. ret = 0;
  11036. }
  11037. if (echX != NULL) {
  11038. /* turn ech on so it doesn't write, then write it last */
  11039. TURN_ON(semaphore, TLSX_ToSemaphore(echX->type));
  11040. }
  11041. if (ret == 0 && ssl->extensions) {
  11042. ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore,
  11043. msgType, pOffset);
  11044. }
  11045. if (ret == 0 && ssl->ctx && ssl->ctx->extensions) {
  11046. ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore,
  11047. msgType, pOffset);
  11048. }
  11049. if (echX != NULL) {
  11050. /* turn off and write it last */
  11051. TURN_OFF(semaphore, TLSX_ToSemaphore(echX->type));
  11052. }
  11053. if (ret == 0 && ssl->extensions) {
  11054. ret = TLSX_Write(ssl->extensions, output + *pOffset, semaphore,
  11055. msgType, pOffset);
  11056. }
  11057. if (ret == 0 && ssl->ctx && ssl->ctx->extensions) {
  11058. ret = TLSX_Write(ssl->ctx->extensions, output + *pOffset, semaphore,
  11059. msgType, pOffset);
  11060. }
  11061. if (serverNameX != NULL) {
  11062. /* remove the public name SNI */
  11063. TLSX_Remove(extensions, TLSX_SERVER_NAME, ssl->heap);
  11064. ret = TLSX_UseSNI(extensions, WOLFSSL_SNI_HOST_NAME, tmpServerName,
  11065. XSTRLEN(tmpServerName), ssl->heap);
  11066. /* restore the inner server name */
  11067. if (ret == WOLFSSL_SUCCESS)
  11068. ret = 0;
  11069. }
  11070. #ifdef WOLFSSL_SMALL_STACK
  11071. XFREE(tmpServerName, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11072. #endif
  11073. return ret;
  11074. }
  11075. #endif
  11076. /** Writes the extensions to be sent into the client hello. */
  11077. int TLSX_WriteRequest(WOLFSSL* ssl, byte* output, byte msgType, word16* pOffset)
  11078. {
  11079. int ret = 0;
  11080. word16 offset = 0;
  11081. byte semaphore[SEMAPHORE_SIZE] = {0};
  11082. if (!TLSX_SupportExtensions(ssl) || output == NULL)
  11083. return 0;
  11084. offset += OPAQUE16_LEN; /* extensions length */
  11085. if (msgType == client_hello) {
  11086. EC_VALIDATE_REQUEST(ssl, semaphore);
  11087. PF_VALIDATE_REQUEST(ssl, semaphore);
  11088. WOLF_STK_VALIDATE_REQUEST(ssl);
  11089. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11090. if (WOLFSSL_SUITES(ssl)->hashSigAlgoSz == 0)
  11091. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11092. #endif
  11093. #ifdef WOLFSSL_TLS13
  11094. if (!IsAtLeastTLSv1_2(ssl)) {
  11095. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11096. }
  11097. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11098. if (!IsAtLeastTLSv1_3(ssl->version)) {
  11099. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11100. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11101. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PSK_KEY_EXCHANGE_MODES));
  11102. #endif
  11103. #ifdef WOLFSSL_EARLY_DATA
  11104. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11105. #endif
  11106. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11107. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11108. #endif
  11109. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  11110. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_POST_HANDSHAKE_AUTH));
  11111. #endif
  11112. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11113. TURN_ON(semaphore,
  11114. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11115. #endif
  11116. }
  11117. #endif
  11118. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11119. /* Must write Pre-shared Key extension at the end in TLS v1.3.
  11120. * Must not write out Pre-shared Key extension in earlier versions of
  11121. * protocol.
  11122. */
  11123. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11124. #endif
  11125. #endif /* WOLFSSL_TLS13 */
  11126. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  11127. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  11128. /* mark already sent, so it won't send it */
  11129. if (!SSL_CM(ssl)->ocspStaplingEnabled) {
  11130. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11131. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11132. }
  11133. #endif
  11134. }
  11135. #ifdef WOLFSSL_TLS13
  11136. #ifndef NO_CERTS
  11137. else if (msgType == certificate_request) {
  11138. /* Don't send out any extension except those that are turned off. */
  11139. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11140. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11141. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SIGNATURE_ALGORITHMS));
  11142. #endif
  11143. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11144. if (SSL_CA_NAMES(ssl) != NULL) {
  11145. TURN_OFF(semaphore,
  11146. TLSX_ToSemaphore(TLSX_CERTIFICATE_AUTHORITIES));
  11147. }
  11148. #endif
  11149. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP, TLSX_OID_FILTERS
  11150. * TLSX_STATUS_REQUEST
  11151. */
  11152. }
  11153. #endif
  11154. #endif
  11155. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  11156. if (ssl->options.useEch == 1 && msgType == client_hello) {
  11157. ret = TLSX_WriteWithEch(ssl, output, semaphore,
  11158. msgType, &offset);
  11159. if (ret != 0)
  11160. return ret;
  11161. }
  11162. else
  11163. #endif
  11164. {
  11165. if (ssl->extensions) {
  11166. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11167. msgType, &offset);
  11168. if (ret != 0)
  11169. return ret;
  11170. }
  11171. if (ssl->ctx && ssl->ctx->extensions) {
  11172. ret = TLSX_Write(ssl->ctx->extensions, output + offset, semaphore,
  11173. msgType, &offset);
  11174. if (ret != 0)
  11175. return ret;
  11176. }
  11177. }
  11178. #ifdef HAVE_EXTENDED_MASTER
  11179. if (msgType == client_hello && ssl->options.haveEMS &&
  11180. (!IsAtLeastTLSv1_3(ssl->version) || ssl->options.downgrade)) {
  11181. WOLFSSL_MSG("EMS extension to write");
  11182. c16toa(HELLO_EXT_EXTMS, output + offset);
  11183. offset += HELLO_EXT_TYPE_SZ;
  11184. c16toa(0, output + offset);
  11185. offset += HELLO_EXT_SZ_SZ;
  11186. }
  11187. #endif
  11188. #ifdef WOLFSSL_TLS13
  11189. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11190. if (msgType == client_hello && IsAtLeastTLSv1_3(ssl->version)) {
  11191. /* Write out what we can of Pre-shared key extension. */
  11192. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11193. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11194. client_hello, &offset);
  11195. if (ret != 0)
  11196. return ret;
  11197. }
  11198. #endif
  11199. #endif
  11200. if (offset > OPAQUE16_LEN || msgType != client_hello)
  11201. c16toa(offset - OPAQUE16_LEN, output); /* extensions length */
  11202. *pOffset += offset;
  11203. return ret;
  11204. }
  11205. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  11206. #if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_SERVER)
  11207. /** Tells the buffered size of extensions to be sent into the server hello. */
  11208. int TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType, word16* pLength)
  11209. {
  11210. int ret = 0;
  11211. word16 length = 0;
  11212. byte semaphore[SEMAPHORE_SIZE] = {0};
  11213. switch (msgType) {
  11214. #ifndef NO_WOLFSSL_SERVER
  11215. case server_hello:
  11216. PF_VALIDATE_RESPONSE(ssl, semaphore);
  11217. #ifdef WOLFSSL_TLS13
  11218. if (IsAtLeastTLSv1_3(ssl->version)) {
  11219. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11220. TURN_OFF(semaphore,
  11221. TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11222. #if defined(HAVE_SUPPORTED_CURVES)
  11223. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11224. if (!ssl->options.noPskDheKe)
  11225. #endif
  11226. {
  11227. /* Expect KeyShare extension in ServerHello. */
  11228. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11229. }
  11230. #endif
  11231. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11232. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11233. #endif
  11234. #ifdef WOLFSSL_DTLS_CID
  11235. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11236. #endif
  11237. }
  11238. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11239. else {
  11240. #ifdef HAVE_SUPPORTED_CURVES
  11241. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11242. #endif
  11243. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11244. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11245. #endif
  11246. }
  11247. #endif
  11248. #endif /* WOLFSSL_TLS13 */
  11249. break;
  11250. #ifdef WOLFSSL_TLS13
  11251. case hello_retry_request:
  11252. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11253. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11254. #ifdef HAVE_SUPPORTED_CURVES
  11255. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11256. if (!ssl->options.noPskDheKe)
  11257. #endif
  11258. {
  11259. /* Expect KeyShare extension in HelloRetryRequest. */
  11260. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11261. }
  11262. #endif
  11263. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11264. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11265. #endif
  11266. break;
  11267. #endif
  11268. #ifdef WOLFSSL_TLS13
  11269. case encrypted_extensions:
  11270. /* Send out all extension except those that are turned on. */
  11271. #ifdef HAVE_ECC
  11272. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  11273. #endif
  11274. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11275. #ifdef HAVE_SESSION_TICKET
  11276. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SESSION_TICKET));
  11277. #endif
  11278. #ifdef HAVE_SUPPORTED_CURVES
  11279. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11280. #endif
  11281. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11282. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11283. #endif
  11284. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  11285. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11286. #endif
  11287. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  11288. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11289. #endif
  11290. #if defined(HAVE_SERVER_RENEGOTIATION_INFO)
  11291. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_RENEGOTIATION_INFO));
  11292. #endif
  11293. #ifdef WOLFSSL_DTLS_CID
  11294. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11295. #endif /* WOLFSSL_DTLS_CID */
  11296. break;
  11297. #ifdef WOLFSSL_EARLY_DATA
  11298. case session_ticket:
  11299. if (ssl->options.tls1_3) {
  11300. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11301. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11302. }
  11303. break;
  11304. #endif
  11305. #endif
  11306. #endif
  11307. #ifdef WOLFSSL_TLS13
  11308. #ifndef NO_CERTS
  11309. case certificate:
  11310. /* Don't send out any extension except those that are turned off. */
  11311. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11312. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11313. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP,
  11314. * TLSX_SERVER_CERTIFICATE_TYPE
  11315. */
  11316. break;
  11317. #endif
  11318. #endif
  11319. }
  11320. #ifdef HAVE_EXTENDED_MASTER
  11321. if (ssl->options.haveEMS && msgType == server_hello &&
  11322. !IsAtLeastTLSv1_3(ssl->version)) {
  11323. length += HELLO_EXT_SZ;
  11324. }
  11325. #endif
  11326. if (TLSX_SupportExtensions(ssl)) {
  11327. ret = TLSX_GetSize(ssl->extensions, semaphore, msgType, &length);
  11328. if (ret != 0)
  11329. return ret;
  11330. }
  11331. /* All the response data is set at the ssl object only, so no ctx here. */
  11332. if (length || msgType != server_hello)
  11333. length += OPAQUE16_LEN; /* for total length storage. */
  11334. *pLength += length;
  11335. return ret;
  11336. }
  11337. /** Writes the server hello extensions into a buffer. */
  11338. int TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType, word16* pOffset)
  11339. {
  11340. int ret = 0;
  11341. word16 offset = 0;
  11342. if (TLSX_SupportExtensions(ssl) && output) {
  11343. byte semaphore[SEMAPHORE_SIZE] = {0};
  11344. switch (msgType) {
  11345. #ifndef NO_WOLFSSL_SERVER
  11346. case server_hello:
  11347. PF_VALIDATE_RESPONSE(ssl, semaphore);
  11348. #ifdef WOLFSSL_TLS13
  11349. if (IsAtLeastTLSv1_3(ssl->version)) {
  11350. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11351. TURN_OFF(semaphore,
  11352. TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11353. #ifdef HAVE_SUPPORTED_CURVES
  11354. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11355. if (!ssl->options.noPskDheKe)
  11356. #endif
  11357. {
  11358. /* Write out KeyShare in ServerHello. */
  11359. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11360. }
  11361. #endif
  11362. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11363. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11364. #endif
  11365. #ifdef WOLFSSL_DTLS_CID
  11366. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11367. #endif /* WOLFSSL_DTLS_CID */
  11368. }
  11369. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
  11370. else {
  11371. #ifdef HAVE_SUPPORTED_CURVES
  11372. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11373. #endif
  11374. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11375. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11376. #endif
  11377. }
  11378. #endif
  11379. #endif
  11380. break;
  11381. #ifdef WOLFSSL_TLS13
  11382. case hello_retry_request:
  11383. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11384. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11385. #ifdef HAVE_SUPPORTED_CURVES
  11386. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11387. if (!ssl->options.noPskDheKe)
  11388. #endif
  11389. {
  11390. /* Write out KeyShare in HelloRetryRequest. */
  11391. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11392. }
  11393. #endif
  11394. /* Cookie is written below as last extension. */
  11395. break;
  11396. #endif
  11397. #ifdef WOLFSSL_TLS13
  11398. case encrypted_extensions:
  11399. /* Send out all extension except those that are turned on. */
  11400. #ifdef HAVE_ECC
  11401. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_EC_POINT_FORMATS));
  11402. #endif
  11403. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SUPPORTED_VERSIONS));
  11404. #ifdef HAVE_SESSION_TICKET
  11405. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_SESSION_TICKET));
  11406. #endif
  11407. #ifdef HAVE_SUPPORTED_CURVES
  11408. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_KEY_SHARE));
  11409. #endif
  11410. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11411. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_PRE_SHARED_KEY));
  11412. #endif
  11413. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  11414. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11415. #endif
  11416. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  11417. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST_V2));
  11418. #endif
  11419. #if defined(HAVE_SERVER_RENEGOTIATION_INFO)
  11420. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_RENEGOTIATION_INFO));
  11421. #endif
  11422. #ifdef WOLFSSL_DTLS_CID
  11423. TURN_ON(semaphore, TLSX_ToSemaphore(TLSX_CONNECTION_ID));
  11424. #endif /* WOLFSSL_DTLS_CID */
  11425. break;
  11426. #ifdef WOLFSSL_EARLY_DATA
  11427. case session_ticket:
  11428. if (ssl->options.tls1_3) {
  11429. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11430. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_EARLY_DATA));
  11431. }
  11432. break;
  11433. #endif
  11434. #endif
  11435. #endif
  11436. #ifdef WOLFSSL_TLS13
  11437. #ifndef NO_CERTS
  11438. case certificate:
  11439. /* Don't send out any extension except those that are turned
  11440. * off. */
  11441. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11442. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_STATUS_REQUEST));
  11443. /* TODO: TLSX_SIGNED_CERTIFICATE_TIMESTAMP,
  11444. * TLSX_SERVER_CERTIFICATE_TYPE
  11445. */
  11446. break;
  11447. #endif
  11448. #endif
  11449. default:
  11450. break;
  11451. }
  11452. offset += OPAQUE16_LEN; /* extensions length */
  11453. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11454. msgType, &offset);
  11455. if (ret != 0)
  11456. return ret;
  11457. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  11458. if (msgType == hello_retry_request) {
  11459. XMEMSET(semaphore, 0xff, SEMAPHORE_SIZE);
  11460. TURN_OFF(semaphore, TLSX_ToSemaphore(TLSX_COOKIE));
  11461. ret = TLSX_Write(ssl->extensions, output + offset, semaphore,
  11462. msgType, &offset);
  11463. if (ret != 0)
  11464. return ret;
  11465. }
  11466. #endif
  11467. #ifdef HAVE_EXTENDED_MASTER
  11468. if (ssl->options.haveEMS && msgType == server_hello &&
  11469. !IsAtLeastTLSv1_3(ssl->version)) {
  11470. WOLFSSL_MSG("EMS extension to write");
  11471. c16toa(HELLO_EXT_EXTMS, output + offset);
  11472. offset += HELLO_EXT_TYPE_SZ;
  11473. c16toa(0, output + offset);
  11474. offset += HELLO_EXT_SZ_SZ;
  11475. }
  11476. #endif
  11477. if (offset > OPAQUE16_LEN || msgType != server_hello)
  11478. c16toa(offset - OPAQUE16_LEN, output); /* extensions length */
  11479. }
  11480. if (pOffset)
  11481. *pOffset += offset;
  11482. return ret;
  11483. }
  11484. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_SERVER */
  11485. #ifdef WOLFSSL_TLS13
  11486. int TLSX_ParseVersion(WOLFSSL* ssl, const byte* input, word16 length,
  11487. byte msgType, int* found)
  11488. {
  11489. int ret = 0;
  11490. int offset = 0;
  11491. *found = 0;
  11492. while (offset < (int)length) {
  11493. word16 type;
  11494. word16 size;
  11495. if (offset + (2 * OPAQUE16_LEN) > length) {
  11496. ret = BUFFER_ERROR;
  11497. break;
  11498. }
  11499. ato16(input + offset, &type);
  11500. offset += HELLO_EXT_TYPE_SZ;
  11501. ato16(input + offset, &size);
  11502. offset += OPAQUE16_LEN;
  11503. if (offset + size > length) {
  11504. ret = BUFFER_ERROR;
  11505. break;
  11506. }
  11507. if (type == TLSX_SUPPORTED_VERSIONS) {
  11508. *found = 1;
  11509. WOLFSSL_MSG("Supported Versions extension received");
  11510. ret = SV_PARSE(ssl, input + offset, size, msgType, &ssl->version,
  11511. &ssl->options, &ssl->extensions);
  11512. break;
  11513. }
  11514. offset += size;
  11515. }
  11516. return ret;
  11517. }
  11518. #endif
  11519. /** Parses a buffer of TLS extensions. */
  11520. int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length, byte msgType,
  11521. Suites *suites)
  11522. {
  11523. int ret = 0;
  11524. word16 offset = 0;
  11525. byte isRequest = (msgType == client_hello ||
  11526. msgType == certificate_request);
  11527. #ifdef HAVE_EXTENDED_MASTER
  11528. byte pendingEMS = 0;
  11529. #endif
  11530. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  11531. int pskDone = 0;
  11532. #endif
  11533. byte seenType[SEMAPHORE_SIZE]; /* Seen known extensions. */
  11534. if (!ssl || !input || (isRequest && !suites))
  11535. return BAD_FUNC_ARG;
  11536. /* No known extensions seen yet. */
  11537. XMEMSET(seenType, 0, sizeof(seenType));
  11538. while (ret == 0 && offset < length) {
  11539. word16 type;
  11540. word16 size;
  11541. #if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
  11542. if (msgType == client_hello && pskDone) {
  11543. WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
  11544. return PSK_KEY_ERROR;
  11545. }
  11546. #endif
  11547. if (length - offset < HELLO_EXT_TYPE_SZ + OPAQUE16_LEN)
  11548. return BUFFER_ERROR;
  11549. ato16(input + offset, &type);
  11550. offset += HELLO_EXT_TYPE_SZ;
  11551. ato16(input + offset, &size);
  11552. offset += OPAQUE16_LEN;
  11553. /* Check we have a bit for extension type. */
  11554. if ((type <= 62) || (type == TLSX_RENEGOTIATION_INFO)
  11555. #ifdef WOLFSSL_QUIC
  11556. || (type == TLSX_KEY_QUIC_TP_PARAMS_DRAFT)
  11557. #endif
  11558. )
  11559. {
  11560. /* Detect duplicate recognized extensions. */
  11561. if (IS_OFF(seenType, TLSX_ToSemaphore(type))) {
  11562. TURN_ON(seenType, TLSX_ToSemaphore(type));
  11563. }
  11564. else {
  11565. return DUPLICATE_TLS_EXT_E;
  11566. }
  11567. }
  11568. if (length - offset < size)
  11569. return BUFFER_ERROR;
  11570. switch (type) {
  11571. #ifdef HAVE_SNI
  11572. case TLSX_SERVER_NAME:
  11573. WOLFSSL_MSG("SNI extension received");
  11574. #ifdef WOLFSSL_DEBUG_TLS
  11575. WOLFSSL_BUFFER(input + offset, size);
  11576. #endif
  11577. #ifdef WOLFSSL_TLS13
  11578. if (IsAtLeastTLSv1_3(ssl->version)) {
  11579. if (msgType != client_hello &&
  11580. msgType != encrypted_extensions)
  11581. return EXT_NOT_ALLOWED;
  11582. }
  11583. else
  11584. #endif
  11585. {
  11586. if (msgType != client_hello &&
  11587. msgType != server_hello)
  11588. return EXT_NOT_ALLOWED;
  11589. }
  11590. ret = SNI_PARSE(ssl, input + offset, size, isRequest);
  11591. break;
  11592. #endif
  11593. case TLSX_TRUSTED_CA_KEYS:
  11594. WOLFSSL_MSG("Trusted CA extension received");
  11595. #ifdef WOLFSSL_DEBUG_TLS
  11596. WOLFSSL_BUFFER(input + offset, size);
  11597. #endif
  11598. #ifdef WOLFSSL_TLS13
  11599. /* RFC 8446 4.2.4 states trusted_ca_keys is not used
  11600. in TLS 1.3. */
  11601. if (IsAtLeastTLSv1_3(ssl->version)) {
  11602. return EXT_NOT_ALLOWED;
  11603. }
  11604. else
  11605. #endif
  11606. {
  11607. if (msgType != client_hello &&
  11608. msgType != server_hello)
  11609. return EXT_NOT_ALLOWED;
  11610. }
  11611. ret = TCA_PARSE(ssl, input + offset, size, isRequest);
  11612. break;
  11613. case TLSX_MAX_FRAGMENT_LENGTH:
  11614. WOLFSSL_MSG("Max Fragment Length extension received");
  11615. #ifdef WOLFSSL_DEBUG_TLS
  11616. WOLFSSL_BUFFER(input + offset, size);
  11617. #endif
  11618. #ifdef WOLFSSL_TLS13
  11619. if (IsAtLeastTLSv1_3(ssl->version)) {
  11620. if (msgType != client_hello &&
  11621. msgType != encrypted_extensions) {
  11622. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11623. return EXT_NOT_ALLOWED;
  11624. }
  11625. }
  11626. else
  11627. #endif
  11628. {
  11629. if (msgType != client_hello &&
  11630. msgType != server_hello) {
  11631. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11632. return EXT_NOT_ALLOWED;
  11633. }
  11634. }
  11635. ret = MFL_PARSE(ssl, input + offset, size, isRequest);
  11636. break;
  11637. case TLSX_TRUNCATED_HMAC:
  11638. WOLFSSL_MSG("Truncated HMAC extension received");
  11639. #ifdef WOLFSSL_DEBUG_TLS
  11640. WOLFSSL_BUFFER(input + offset, size);
  11641. #endif
  11642. #ifdef WOLFSSL_TLS13
  11643. if (IsAtLeastTLSv1_3(ssl->version))
  11644. break;
  11645. #endif
  11646. if (msgType != client_hello)
  11647. return EXT_NOT_ALLOWED;
  11648. ret = THM_PARSE(ssl, input + offset, size, isRequest);
  11649. break;
  11650. case TLSX_SUPPORTED_GROUPS:
  11651. WOLFSSL_MSG("Supported Groups extension received");
  11652. #ifdef WOLFSSL_DEBUG_TLS
  11653. WOLFSSL_BUFFER(input + offset, size);
  11654. #endif
  11655. #ifdef WOLFSSL_TLS13
  11656. if (IsAtLeastTLSv1_3(ssl->version)) {
  11657. if (msgType != client_hello &&
  11658. msgType != encrypted_extensions) {
  11659. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11660. return EXT_NOT_ALLOWED;
  11661. }
  11662. }
  11663. else
  11664. #endif
  11665. {
  11666. if (msgType != client_hello) {
  11667. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11668. return EXT_NOT_ALLOWED;
  11669. }
  11670. }
  11671. ret = EC_PARSE(ssl, input + offset, size, isRequest,
  11672. &ssl->extensions);
  11673. break;
  11674. case TLSX_EC_POINT_FORMATS:
  11675. WOLFSSL_MSG("Point Formats extension received");
  11676. #ifdef WOLFSSL_DEBUG_TLS
  11677. WOLFSSL_BUFFER(input + offset, size);
  11678. #endif
  11679. #ifdef WOLFSSL_TLS13
  11680. if (IsAtLeastTLSv1_3(ssl->version))
  11681. break;
  11682. #endif
  11683. if (msgType != client_hello &&
  11684. msgType != server_hello) {
  11685. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11686. return EXT_NOT_ALLOWED;
  11687. }
  11688. ret = PF_PARSE(ssl, input + offset, size, isRequest);
  11689. break;
  11690. case TLSX_STATUS_REQUEST:
  11691. WOLFSSL_MSG("Certificate Status Request extension received");
  11692. #ifdef WOLFSSL_DEBUG_TLS
  11693. WOLFSSL_BUFFER(input + offset, size);
  11694. #endif
  11695. #ifdef WOLFSSL_TLS13
  11696. if (IsAtLeastTLSv1_3(ssl->version)) {
  11697. if (msgType != client_hello &&
  11698. msgType != certificate_request &&
  11699. msgType != certificate)
  11700. return EXT_NOT_ALLOWED;
  11701. }
  11702. else
  11703. #endif
  11704. {
  11705. if (msgType != client_hello &&
  11706. msgType != server_hello)
  11707. return EXT_NOT_ALLOWED;
  11708. }
  11709. ret = CSR_PARSE(ssl, input + offset, size, isRequest);
  11710. break;
  11711. case TLSX_STATUS_REQUEST_V2:
  11712. WOLFSSL_MSG("Certificate Status Request v2 extension received");
  11713. #ifdef WOLFSSL_DEBUG_TLS
  11714. WOLFSSL_BUFFER(input + offset, size);
  11715. #endif
  11716. #if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  11717. if (IsAtLeastTLSv1_3(ssl->version)) {
  11718. if (msgType != client_hello &&
  11719. msgType != certificate_request &&
  11720. msgType != certificate)
  11721. return EXT_NOT_ALLOWED;
  11722. }
  11723. else
  11724. #endif
  11725. {
  11726. if (msgType != client_hello &&
  11727. msgType != server_hello)
  11728. return EXT_NOT_ALLOWED;
  11729. }
  11730. ret = CSR2_PARSE(ssl, input + offset, size, isRequest);
  11731. break;
  11732. #ifdef HAVE_EXTENDED_MASTER
  11733. case HELLO_EXT_EXTMS:
  11734. WOLFSSL_MSG("Extended Master Secret extension received");
  11735. #ifdef WOLFSSL_DEBUG_TLS
  11736. WOLFSSL_BUFFER(input + offset, size);
  11737. #endif
  11738. #if defined(WOLFSSL_TLS13)
  11739. if (IsAtLeastTLSv1_3(ssl->version))
  11740. break;
  11741. #endif
  11742. if (msgType != client_hello &&
  11743. msgType != server_hello)
  11744. return EXT_NOT_ALLOWED;
  11745. if (size != 0)
  11746. return BUFFER_ERROR;
  11747. #ifndef NO_WOLFSSL_SERVER
  11748. if (isRequest)
  11749. ssl->options.haveEMS = 1;
  11750. #endif
  11751. pendingEMS = 1;
  11752. break;
  11753. #endif
  11754. case TLSX_RENEGOTIATION_INFO:
  11755. WOLFSSL_MSG("Secure Renegotiation extension received");
  11756. #ifdef WOLFSSL_DEBUG_TLS
  11757. WOLFSSL_BUFFER(input + offset, size);
  11758. #endif
  11759. #ifdef WOLFSSL_TLS13
  11760. if (IsAtLeastTLSv1_3(ssl->version))
  11761. break;
  11762. #endif
  11763. if (msgType != client_hello &&
  11764. msgType != server_hello)
  11765. return EXT_NOT_ALLOWED;
  11766. ret = SCR_PARSE(ssl, input + offset, size, isRequest);
  11767. break;
  11768. case TLSX_SESSION_TICKET:
  11769. WOLFSSL_MSG("Session Ticket extension received");
  11770. #ifdef WOLFSSL_DEBUG_TLS
  11771. WOLFSSL_BUFFER(input + offset, size);
  11772. #endif
  11773. #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET)
  11774. if (IsAtLeastTLSv1_3(ssl->version)) {
  11775. if (msgType != client_hello)
  11776. return EXT_NOT_ALLOWED;
  11777. }
  11778. else
  11779. #endif
  11780. {
  11781. if (msgType != client_hello &&
  11782. msgType != server_hello)
  11783. return EXT_NOT_ALLOWED;
  11784. }
  11785. ret = WOLF_STK_PARSE(ssl, input + offset, size, isRequest);
  11786. break;
  11787. case TLSX_APPLICATION_LAYER_PROTOCOL:
  11788. WOLFSSL_MSG("ALPN extension received");
  11789. #ifdef WOLFSSL_DEBUG_TLS
  11790. WOLFSSL_BUFFER(input + offset, size);
  11791. #endif
  11792. #if defined(WOLFSSL_TLS13) && defined(HAVE_ALPN)
  11793. if (IsAtLeastTLSv1_3(ssl->version)) {
  11794. if (msgType != client_hello &&
  11795. msgType != encrypted_extensions)
  11796. return EXT_NOT_ALLOWED;
  11797. }
  11798. else
  11799. #endif
  11800. {
  11801. if (msgType != client_hello &&
  11802. msgType != server_hello)
  11803. return EXT_NOT_ALLOWED;
  11804. }
  11805. ret = ALPN_PARSE(ssl, input + offset, size, isRequest);
  11806. break;
  11807. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11808. case TLSX_SIGNATURE_ALGORITHMS:
  11809. WOLFSSL_MSG("Signature Algorithms extension received");
  11810. #ifdef WOLFSSL_DEBUG_TLS
  11811. WOLFSSL_BUFFER(input + offset, size);
  11812. #endif
  11813. if (!IsAtLeastTLSv1_2(ssl))
  11814. break;
  11815. #ifdef WOLFSSL_TLS13
  11816. if (IsAtLeastTLSv1_3(ssl->version)) {
  11817. if (msgType != client_hello &&
  11818. msgType != certificate_request)
  11819. return EXT_NOT_ALLOWED;
  11820. }
  11821. else
  11822. #endif
  11823. {
  11824. if (msgType != client_hello)
  11825. return EXT_NOT_ALLOWED;
  11826. }
  11827. ret = SA_PARSE(ssl, input + offset, size, isRequest, suites);
  11828. break;
  11829. #endif
  11830. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  11831. case TLSX_ENCRYPT_THEN_MAC:
  11832. WOLFSSL_MSG("Encrypt-Then-Mac extension received");
  11833. /* Ignore for TLS 1.3+ */
  11834. if (IsAtLeastTLSv1_3(ssl->version))
  11835. break;
  11836. if (msgType != client_hello &&
  11837. msgType != server_hello)
  11838. return EXT_NOT_ALLOWED;
  11839. ret = ETM_PARSE(ssl, input + offset, size, msgType);
  11840. break;
  11841. #endif /* HAVE_ENCRYPT_THEN_MAC */
  11842. #ifdef WOLFSSL_TLS13
  11843. case TLSX_SUPPORTED_VERSIONS:
  11844. WOLFSSL_MSG("Skipping Supported Versions - already processed");
  11845. #ifdef WOLFSSL_DEBUG_TLS
  11846. WOLFSSL_BUFFER(input + offset, size);
  11847. #endif
  11848. if (msgType != client_hello &&
  11849. msgType != server_hello &&
  11850. msgType != hello_retry_request)
  11851. return EXT_NOT_ALLOWED;
  11852. break;
  11853. #ifdef WOLFSSL_SEND_HRR_COOKIE
  11854. case TLSX_COOKIE:
  11855. WOLFSSL_MSG("Cookie extension received");
  11856. #ifdef WOLFSSL_DEBUG_TLS
  11857. WOLFSSL_BUFFER(input + offset, size);
  11858. #endif
  11859. if (!IsAtLeastTLSv1_3(ssl->version))
  11860. break;
  11861. if (msgType != client_hello &&
  11862. msgType != hello_retry_request) {
  11863. return EXT_NOT_ALLOWED;
  11864. }
  11865. ret = CKE_PARSE(ssl, input + offset, size, msgType);
  11866. break;
  11867. #endif
  11868. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  11869. case TLSX_PRE_SHARED_KEY:
  11870. WOLFSSL_MSG("Pre-Shared Key extension received");
  11871. #ifdef WOLFSSL_DEBUG_TLS
  11872. WOLFSSL_BUFFER(input + offset, size);
  11873. #endif
  11874. if (!IsAtLeastTLSv1_3(ssl->version))
  11875. break;
  11876. if (msgType != client_hello &&
  11877. msgType != server_hello) {
  11878. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11879. return EXT_NOT_ALLOWED;
  11880. }
  11881. ret = PSK_PARSE(ssl, input + offset, size, msgType);
  11882. pskDone = 1;
  11883. break;
  11884. case TLSX_PSK_KEY_EXCHANGE_MODES:
  11885. WOLFSSL_MSG("PSK Key Exchange Modes extension received");
  11886. #ifdef WOLFSSL_DEBUG_TLS
  11887. WOLFSSL_BUFFER(input + offset, size);
  11888. #endif
  11889. if (!IsAtLeastTLSv1_3(ssl->version))
  11890. break;
  11891. if (msgType != client_hello) {
  11892. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11893. return EXT_NOT_ALLOWED;
  11894. }
  11895. ret = PKM_PARSE(ssl, input + offset, size, msgType);
  11896. break;
  11897. #endif
  11898. #ifdef WOLFSSL_EARLY_DATA
  11899. case TLSX_EARLY_DATA:
  11900. WOLFSSL_MSG("Early Data extension received");
  11901. #ifdef WOLFSSL_DEBUG_TLS
  11902. WOLFSSL_BUFFER(input + offset, size);
  11903. #endif
  11904. if (!IsAtLeastTLSv1_3(ssl->version))
  11905. break;
  11906. if (msgType != client_hello && msgType != session_ticket &&
  11907. msgType != encrypted_extensions) {
  11908. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11909. return EXT_NOT_ALLOWED;
  11910. }
  11911. ret = EDI_PARSE(ssl, input + offset, size, msgType);
  11912. break;
  11913. #endif
  11914. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  11915. case TLSX_POST_HANDSHAKE_AUTH:
  11916. WOLFSSL_MSG("Post Handshake Authentication extension received");
  11917. #ifdef WOLFSSL_DEBUG_TLS
  11918. WOLFSSL_BUFFER(input + offset, size);
  11919. #endif
  11920. if (!IsAtLeastTLSv1_3(ssl->version))
  11921. break;
  11922. if (msgType != client_hello) {
  11923. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11924. return EXT_NOT_ALLOWED;
  11925. }
  11926. ret = PHA_PARSE(ssl, input + offset, size, msgType);
  11927. break;
  11928. #endif
  11929. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  11930. case TLSX_SIGNATURE_ALGORITHMS_CERT:
  11931. WOLFSSL_MSG("Signature Algorithms extension received");
  11932. #ifdef WOLFSSL_DEBUG_TLS
  11933. WOLFSSL_BUFFER(input + offset, size);
  11934. #endif
  11935. if (!IsAtLeastTLSv1_3(ssl->version))
  11936. break;
  11937. if (msgType != client_hello &&
  11938. msgType != certificate_request) {
  11939. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11940. return EXT_NOT_ALLOWED;
  11941. }
  11942. ret = SAC_PARSE(ssl, input + offset, size, isRequest);
  11943. break;
  11944. #endif
  11945. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
  11946. case TLSX_CERTIFICATE_AUTHORITIES:
  11947. WOLFSSL_MSG("Certificate Authorities extension received");
  11948. #ifdef WOLFSSL_DEBUG_TLS
  11949. WOLFSSL_BUFFER(input + offset, size);
  11950. #endif
  11951. if (!IsAtLeastTLSv1_3(ssl->version))
  11952. break;
  11953. if (msgType != client_hello &&
  11954. msgType != certificate_request) {
  11955. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11956. return EXT_NOT_ALLOWED;
  11957. }
  11958. ret = CAN_PARSE(ssl, input + offset, size, isRequest);
  11959. break;
  11960. #endif
  11961. case TLSX_KEY_SHARE:
  11962. WOLFSSL_MSG("Key Share extension received");
  11963. #ifdef WOLFSSL_DEBUG_TLS
  11964. WOLFSSL_BUFFER(input + offset, size);
  11965. #endif
  11966. #ifdef HAVE_SUPPORTED_CURVES
  11967. if (!IsAtLeastTLSv1_3(ssl->version))
  11968. break;
  11969. if (msgType != client_hello && msgType != server_hello &&
  11970. msgType != hello_retry_request) {
  11971. WOLFSSL_ERROR_VERBOSE(EXT_NOT_ALLOWED);
  11972. return EXT_NOT_ALLOWED;
  11973. }
  11974. #endif
  11975. ret = KS_PARSE(ssl, input + offset, size, msgType);
  11976. break;
  11977. #endif
  11978. #ifdef WOLFSSL_SRTP
  11979. case TLSX_USE_SRTP:
  11980. WOLFSSL_MSG("Use SRTP extension received");
  11981. ret = SRTP_PARSE(ssl, input + offset, size, isRequest);
  11982. break;
  11983. #endif
  11984. #ifdef WOLFSSL_QUIC
  11985. case TLSX_KEY_QUIC_TP_PARAMS:
  11986. FALL_THROUGH;
  11987. case TLSX_KEY_QUIC_TP_PARAMS_DRAFT:
  11988. WOLFSSL_MSG("QUIC transport parameter received");
  11989. #ifdef WOLFSSL_DEBUG_TLS
  11990. WOLFSSL_BUFFER(input + offset, size);
  11991. #endif
  11992. if (IsAtLeastTLSv1_3(ssl->version) &&
  11993. msgType != client_hello &&
  11994. msgType != server_hello &&
  11995. msgType != encrypted_extensions) {
  11996. return EXT_NOT_ALLOWED;
  11997. }
  11998. else if (!IsAtLeastTLSv1_3(ssl->version) &&
  11999. msgType == encrypted_extensions) {
  12000. return EXT_NOT_ALLOWED;
  12001. }
  12002. else if (WOLFSSL_IS_QUIC(ssl)) {
  12003. ret = QTP_PARSE(ssl, input + offset, size, type, msgType);
  12004. }
  12005. else {
  12006. WOLFSSL_MSG("QUIC transport param TLS extension type, but no QUIC");
  12007. return EXT_NOT_ALLOWED; /* be safe, this should not happen */
  12008. }
  12009. break;
  12010. #endif /* WOLFSSL_QUIC */
  12011. #if defined(WOLFSSL_DTLS_CID)
  12012. case TLSX_CONNECTION_ID:
  12013. /* connection ID not supported in DTLSv1.2 */
  12014. if (!IsAtLeastTLSv1_3(ssl->version))
  12015. break;
  12016. if (msgType != client_hello && msgType != server_hello)
  12017. return EXT_NOT_ALLOWED;
  12018. WOLFSSL_MSG("ConnectionID extension received");
  12019. ret = CID_PARSE(ssl, input + offset, size, isRequest);
  12020. break;
  12021. #endif /* defined(WOLFSSL_DTLS_CID) */
  12022. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  12023. case TLSX_ECH:
  12024. ret = ECH_PARSE(ssl, input + offset, size, msgType);
  12025. break;
  12026. #endif
  12027. default:
  12028. WOLFSSL_MSG("Unknown TLS extension type");
  12029. }
  12030. /* offset should be updated here! */
  12031. offset += size;
  12032. }
  12033. #ifdef HAVE_EXTENDED_MASTER
  12034. if (IsAtLeastTLSv1_3(ssl->version) && msgType == hello_retry_request) {
  12035. /* Don't change EMS status until server_hello received.
  12036. * Second ClientHello must have same extensions.
  12037. */
  12038. }
  12039. else if (!isRequest && ssl->options.haveEMS && !pendingEMS)
  12040. ssl->options.haveEMS = 0;
  12041. #endif
  12042. if (ret == 0)
  12043. ret = SNI_VERIFY_PARSE(ssl, isRequest);
  12044. if (ret == 0)
  12045. ret = TCA_VERIFY_PARSE(ssl, isRequest);
  12046. return ret;
  12047. }
  12048. /* undefining semaphore macros */
  12049. #undef IS_OFF
  12050. #undef TURN_ON
  12051. #undef SEMAPHORE_SIZE
  12052. #endif /* HAVE_TLS_EXTENSIONS */
  12053. #ifndef NO_WOLFSSL_CLIENT
  12054. WOLFSSL_METHOD* wolfTLS_client_method(void)
  12055. {
  12056. return wolfTLS_client_method_ex(NULL);
  12057. }
  12058. WOLFSSL_METHOD* wolfTLS_client_method_ex(void* heap)
  12059. {
  12060. WOLFSSL_METHOD* method =
  12061. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12062. heap, DYNAMIC_TYPE_METHOD);
  12063. (void)heap;
  12064. WOLFSSL_ENTER("TLS_client_method_ex");
  12065. if (method) {
  12066. #if defined(WOLFSSL_TLS13)
  12067. InitSSL_Method(method, MakeTLSv1_3());
  12068. #elif !defined(WOLFSSL_NO_TLS12)
  12069. InitSSL_Method(method, MakeTLSv1_2());
  12070. #elif !defined(NO_OLD_TLS)
  12071. InitSSL_Method(method, MakeTLSv1_1());
  12072. #elif defined(WOLFSSL_ALLOW_TLSV10)
  12073. InitSSL_Method(method, MakeTLSv1());
  12074. #else
  12075. #error No TLS version enabled!
  12076. #endif
  12077. method->downgrade = 1;
  12078. method->side = WOLFSSL_CLIENT_END;
  12079. }
  12080. return method;
  12081. }
  12082. #ifndef NO_OLD_TLS
  12083. #ifdef WOLFSSL_ALLOW_TLSV10
  12084. WOLFSSL_METHOD* wolfTLSv1_client_method(void)
  12085. {
  12086. return wolfTLSv1_client_method_ex(NULL);
  12087. }
  12088. WOLFSSL_METHOD* wolfTLSv1_client_method_ex(void* heap)
  12089. {
  12090. WOLFSSL_METHOD* method =
  12091. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12092. heap, DYNAMIC_TYPE_METHOD);
  12093. (void)heap;
  12094. WOLFSSL_ENTER("TLSv1_client_method_ex");
  12095. if (method)
  12096. InitSSL_Method(method, MakeTLSv1());
  12097. return method;
  12098. }
  12099. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12100. WOLFSSL_METHOD* wolfTLSv1_1_client_method(void)
  12101. {
  12102. return wolfTLSv1_1_client_method_ex(NULL);
  12103. }
  12104. WOLFSSL_METHOD* wolfTLSv1_1_client_method_ex(void* heap)
  12105. {
  12106. WOLFSSL_METHOD* method =
  12107. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12108. heap, DYNAMIC_TYPE_METHOD);
  12109. (void)heap;
  12110. WOLFSSL_ENTER("TLSv1_1_client_method_ex");
  12111. if (method)
  12112. InitSSL_Method(method, MakeTLSv1_1());
  12113. return method;
  12114. }
  12115. #endif /* !NO_OLD_TLS */
  12116. #ifndef WOLFSSL_NO_TLS12
  12117. WOLFSSL_ABI
  12118. WOLFSSL_METHOD* wolfTLSv1_2_client_method(void)
  12119. {
  12120. return wolfTLSv1_2_client_method_ex(NULL);
  12121. }
  12122. WOLFSSL_METHOD* wolfTLSv1_2_client_method_ex(void* heap)
  12123. {
  12124. WOLFSSL_METHOD* method =
  12125. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12126. heap, DYNAMIC_TYPE_METHOD);
  12127. (void)heap;
  12128. WOLFSSL_ENTER("TLSv1_2_client_method_ex");
  12129. if (method)
  12130. InitSSL_Method(method, MakeTLSv1_2());
  12131. return method;
  12132. }
  12133. #endif /* WOLFSSL_NO_TLS12 */
  12134. #ifdef WOLFSSL_TLS13
  12135. /* The TLS v1.3 client method data.
  12136. *
  12137. * returns the method data for a TLS v1.3 client.
  12138. */
  12139. WOLFSSL_ABI
  12140. WOLFSSL_METHOD* wolfTLSv1_3_client_method(void)
  12141. {
  12142. return wolfTLSv1_3_client_method_ex(NULL);
  12143. }
  12144. /* The TLS v1.3 client method data.
  12145. *
  12146. * heap The heap used for allocation.
  12147. * returns the method data for a TLS v1.3 client.
  12148. */
  12149. WOLFSSL_METHOD* wolfTLSv1_3_client_method_ex(void* heap)
  12150. {
  12151. WOLFSSL_METHOD* method = (WOLFSSL_METHOD*)
  12152. XMALLOC(sizeof(WOLFSSL_METHOD), heap,
  12153. DYNAMIC_TYPE_METHOD);
  12154. (void)heap;
  12155. WOLFSSL_ENTER("TLSv1_3_client_method_ex");
  12156. if (method)
  12157. InitSSL_Method(method, MakeTLSv1_3());
  12158. return method;
  12159. }
  12160. #endif /* WOLFSSL_TLS13 */
  12161. #ifdef WOLFSSL_DTLS
  12162. WOLFSSL_METHOD* wolfDTLS_client_method(void)
  12163. {
  12164. return wolfDTLS_client_method_ex(NULL);
  12165. }
  12166. WOLFSSL_METHOD* wolfDTLS_client_method_ex(void* heap)
  12167. {
  12168. WOLFSSL_METHOD* method =
  12169. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12170. heap, DYNAMIC_TYPE_METHOD);
  12171. (void)heap;
  12172. WOLFSSL_ENTER("DTLS_client_method_ex");
  12173. if (method) {
  12174. #if defined(WOLFSSL_DTLS13)
  12175. InitSSL_Method(method, MakeDTLSv1_3());
  12176. #elif !defined(WOLFSSL_NO_TLS12)
  12177. InitSSL_Method(method, MakeDTLSv1_2());
  12178. #elif !defined(NO_OLD_TLS)
  12179. InitSSL_Method(method, MakeDTLSv1());
  12180. #else
  12181. #error No DTLS version enabled!
  12182. #endif
  12183. method->downgrade = 1;
  12184. method->side = WOLFSSL_CLIENT_END;
  12185. }
  12186. return method;
  12187. }
  12188. #ifndef NO_OLD_TLS
  12189. WOLFSSL_METHOD* wolfDTLSv1_client_method(void)
  12190. {
  12191. return wolfDTLSv1_client_method_ex(NULL);
  12192. }
  12193. WOLFSSL_METHOD* wolfDTLSv1_client_method_ex(void* heap)
  12194. {
  12195. WOLFSSL_METHOD* method =
  12196. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12197. heap, DYNAMIC_TYPE_METHOD);
  12198. (void)heap;
  12199. WOLFSSL_ENTER("DTLSv1_client_method_ex");
  12200. if (method)
  12201. InitSSL_Method(method, MakeDTLSv1());
  12202. return method;
  12203. }
  12204. #endif /* NO_OLD_TLS */
  12205. #ifndef WOLFSSL_NO_TLS12
  12206. WOLFSSL_METHOD* wolfDTLSv1_2_client_method(void)
  12207. {
  12208. return wolfDTLSv1_2_client_method_ex(NULL);
  12209. }
  12210. WOLFSSL_METHOD* wolfDTLSv1_2_client_method_ex(void* heap)
  12211. {
  12212. WOLFSSL_METHOD* method =
  12213. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12214. heap, DYNAMIC_TYPE_METHOD);
  12215. (void)heap;
  12216. WOLFSSL_ENTER("DTLSv1_2_client_method_ex");
  12217. if (method)
  12218. InitSSL_Method(method, MakeDTLSv1_2());
  12219. (void)heap;
  12220. return method;
  12221. }
  12222. #endif /* !WOLFSSL_NO_TLS12 */
  12223. #endif /* WOLFSSL_DTLS */
  12224. #endif /* NO_WOLFSSL_CLIENT */
  12225. /* EITHER SIDE METHODS */
  12226. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
  12227. #ifndef NO_OLD_TLS
  12228. #ifdef WOLFSSL_ALLOW_TLSV10
  12229. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12230. *
  12231. * Returns a pointer to a WOLFSSL_METHOD struct
  12232. */
  12233. WOLFSSL_METHOD* wolfTLSv1_method(void)
  12234. {
  12235. return wolfTLSv1_method_ex(NULL);
  12236. }
  12237. WOLFSSL_METHOD* wolfTLSv1_method_ex(void* heap)
  12238. {
  12239. WOLFSSL_METHOD* m;
  12240. WOLFSSL_ENTER("TLSv1_method");
  12241. #ifndef NO_WOLFSSL_CLIENT
  12242. m = wolfTLSv1_client_method_ex(heap);
  12243. #else
  12244. m = wolfTLSv1_server_method_ex(heap);
  12245. #endif
  12246. if (m != NULL) {
  12247. m->side = WOLFSSL_NEITHER_END;
  12248. }
  12249. return m;
  12250. }
  12251. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12252. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12253. *
  12254. * Returns a pointer to a WOLFSSL_METHOD struct
  12255. */
  12256. WOLFSSL_METHOD* wolfTLSv1_1_method(void)
  12257. {
  12258. return wolfTLSv1_1_method_ex(NULL);
  12259. }
  12260. WOLFSSL_METHOD* wolfTLSv1_1_method_ex(void* heap)
  12261. {
  12262. WOLFSSL_METHOD* m;
  12263. WOLFSSL_ENTER("TLSv1_1_method");
  12264. #ifndef NO_WOLFSSL_CLIENT
  12265. m = wolfTLSv1_1_client_method_ex(heap);
  12266. #else
  12267. m = wolfTLSv1_1_server_method_ex(heap);
  12268. #endif
  12269. if (m != NULL) {
  12270. m->side = WOLFSSL_NEITHER_END;
  12271. }
  12272. return m;
  12273. }
  12274. #endif /* !NO_OLD_TLS */
  12275. #ifndef WOLFSSL_NO_TLS12
  12276. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12277. *
  12278. * Returns a pointer to a WOLFSSL_METHOD struct
  12279. */
  12280. WOLFSSL_METHOD* wolfTLSv1_2_method(void)
  12281. {
  12282. return wolfTLSv1_2_method_ex(NULL);
  12283. }
  12284. WOLFSSL_METHOD* wolfTLSv1_2_method_ex(void* heap)
  12285. {
  12286. WOLFSSL_METHOD* m;
  12287. WOLFSSL_ENTER("TLSv1_2_method");
  12288. #ifndef NO_WOLFSSL_CLIENT
  12289. m = wolfTLSv1_2_client_method_ex(heap);
  12290. #else
  12291. m = wolfTLSv1_2_server_method_ex(heap);
  12292. #endif
  12293. if (m != NULL) {
  12294. m->side = WOLFSSL_NEITHER_END;
  12295. }
  12296. return m;
  12297. }
  12298. #endif /* !WOLFSSL_NO_TLS12 */
  12299. #ifdef WOLFSSL_TLS13
  12300. /* Gets a WOLFSSL_METHOD type that is not set as client or server
  12301. *
  12302. * Returns a pointer to a WOLFSSL_METHOD struct
  12303. */
  12304. WOLFSSL_METHOD* wolfTLSv1_3_method(void)
  12305. {
  12306. return wolfTLSv1_3_method_ex(NULL);
  12307. }
  12308. WOLFSSL_METHOD* wolfTLSv1_3_method_ex(void* heap)
  12309. {
  12310. WOLFSSL_METHOD* m;
  12311. WOLFSSL_ENTER("TLSv1_3_method");
  12312. #ifndef NO_WOLFSSL_CLIENT
  12313. m = wolfTLSv1_3_client_method_ex(heap);
  12314. #else
  12315. m = wolfTLSv1_3_server_method_ex(heap);
  12316. #endif
  12317. if (m != NULL) {
  12318. m->side = WOLFSSL_NEITHER_END;
  12319. }
  12320. return m;
  12321. }
  12322. #endif /* WOLFSSL_TLS13 */
  12323. #ifdef WOLFSSL_DTLS
  12324. WOLFSSL_METHOD* wolfDTLS_method(void)
  12325. {
  12326. return wolfDTLS_method_ex(NULL);
  12327. }
  12328. WOLFSSL_METHOD* wolfDTLS_method_ex(void* heap)
  12329. {
  12330. WOLFSSL_METHOD* m;
  12331. WOLFSSL_ENTER("DTLS_method_ex");
  12332. #ifndef NO_WOLFSSL_CLIENT
  12333. m = wolfDTLS_client_method_ex(heap);
  12334. #else
  12335. m = wolfDTLS_server_method_ex(heap);
  12336. #endif
  12337. if (m != NULL) {
  12338. m->side = WOLFSSL_NEITHER_END;
  12339. }
  12340. return m;
  12341. }
  12342. #ifndef NO_OLD_TLS
  12343. WOLFSSL_METHOD* wolfDTLSv1_method(void)
  12344. {
  12345. return wolfDTLSv1_method_ex(NULL);
  12346. }
  12347. WOLFSSL_METHOD* wolfDTLSv1_method_ex(void* heap)
  12348. {
  12349. WOLFSSL_METHOD* m;
  12350. WOLFSSL_ENTER("DTLSv1_method_ex");
  12351. #ifndef NO_WOLFSSL_CLIENT
  12352. m = wolfDTLSv1_client_method_ex(heap);
  12353. #else
  12354. m = wolfDTLSv1_server_method_ex(heap);
  12355. #endif
  12356. if (m != NULL) {
  12357. m->side = WOLFSSL_NEITHER_END;
  12358. }
  12359. return m;
  12360. }
  12361. #endif /* !NO_OLD_TLS */
  12362. #ifndef WOLFSSL_NO_TLS12
  12363. WOLFSSL_METHOD* wolfDTLSv1_2_method(void)
  12364. {
  12365. return wolfDTLSv1_2_method_ex(NULL);
  12366. }
  12367. WOLFSSL_METHOD* wolfDTLSv1_2_method_ex(void* heap)
  12368. {
  12369. WOLFSSL_METHOD* m;
  12370. WOLFSSL_ENTER("DTLSv1_2_method");
  12371. #ifndef NO_WOLFSSL_CLIENT
  12372. m = wolfDTLSv1_2_client_method_ex(heap);
  12373. #else
  12374. m = wolfDTLSv1_2_server_method_ex(heap);
  12375. #endif
  12376. if (m != NULL) {
  12377. m->side = WOLFSSL_NEITHER_END;
  12378. }
  12379. return m;
  12380. }
  12381. #endif /* !WOLFSSL_NO_TLS12 */
  12382. #endif /* WOLFSSL_DTLS */
  12383. #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
  12384. #ifndef NO_WOLFSSL_SERVER
  12385. WOLFSSL_METHOD* wolfTLS_server_method(void)
  12386. {
  12387. return wolfTLS_server_method_ex(NULL);
  12388. }
  12389. WOLFSSL_METHOD* wolfTLS_server_method_ex(void* heap)
  12390. {
  12391. WOLFSSL_METHOD* method =
  12392. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12393. heap, DYNAMIC_TYPE_METHOD);
  12394. (void)heap;
  12395. WOLFSSL_ENTER("TLS_server_method_ex");
  12396. if (method) {
  12397. #if defined(WOLFSSL_TLS13)
  12398. InitSSL_Method(method, MakeTLSv1_3());
  12399. #elif !defined(WOLFSSL_NO_TLS12)
  12400. InitSSL_Method(method, MakeTLSv1_2());
  12401. #elif !defined(NO_OLD_TLS)
  12402. InitSSL_Method(method, MakeTLSv1_1());
  12403. #elif defined(WOLFSSL_ALLOW_TLSV10)
  12404. InitSSL_Method(method, MakeTLSv1());
  12405. #else
  12406. #error No TLS version enabled!
  12407. #endif
  12408. method->downgrade = 1;
  12409. method->side = WOLFSSL_SERVER_END;
  12410. }
  12411. return method;
  12412. }
  12413. #ifndef NO_OLD_TLS
  12414. #ifdef WOLFSSL_ALLOW_TLSV10
  12415. WOLFSSL_METHOD* wolfTLSv1_server_method(void)
  12416. {
  12417. return wolfTLSv1_server_method_ex(NULL);
  12418. }
  12419. WOLFSSL_METHOD* wolfTLSv1_server_method_ex(void* heap)
  12420. {
  12421. WOLFSSL_METHOD* method =
  12422. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12423. heap, DYNAMIC_TYPE_METHOD);
  12424. (void)heap;
  12425. WOLFSSL_ENTER("TLSv1_server_method_ex");
  12426. if (method) {
  12427. InitSSL_Method(method, MakeTLSv1());
  12428. method->side = WOLFSSL_SERVER_END;
  12429. }
  12430. return method;
  12431. }
  12432. #endif /* WOLFSSL_ALLOW_TLSV10 */
  12433. WOLFSSL_METHOD* wolfTLSv1_1_server_method(void)
  12434. {
  12435. return wolfTLSv1_1_server_method_ex(NULL);
  12436. }
  12437. WOLFSSL_METHOD* wolfTLSv1_1_server_method_ex(void* heap)
  12438. {
  12439. WOLFSSL_METHOD* method =
  12440. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12441. heap, DYNAMIC_TYPE_METHOD);
  12442. (void)heap;
  12443. WOLFSSL_ENTER("TLSv1_1_server_method_ex");
  12444. if (method) {
  12445. InitSSL_Method(method, MakeTLSv1_1());
  12446. method->side = WOLFSSL_SERVER_END;
  12447. }
  12448. return method;
  12449. }
  12450. #endif /* !NO_OLD_TLS */
  12451. #ifndef WOLFSSL_NO_TLS12
  12452. WOLFSSL_ABI
  12453. WOLFSSL_METHOD* wolfTLSv1_2_server_method(void)
  12454. {
  12455. return wolfTLSv1_2_server_method_ex(NULL);
  12456. }
  12457. WOLFSSL_METHOD* wolfTLSv1_2_server_method_ex(void* heap)
  12458. {
  12459. WOLFSSL_METHOD* method =
  12460. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12461. heap, DYNAMIC_TYPE_METHOD);
  12462. (void)heap;
  12463. WOLFSSL_ENTER("TLSv1_2_server_method_ex");
  12464. if (method) {
  12465. InitSSL_Method(method, MakeTLSv1_2());
  12466. method->side = WOLFSSL_SERVER_END;
  12467. }
  12468. return method;
  12469. }
  12470. #endif /* !WOLFSSL_NO_TLS12 */
  12471. #ifdef WOLFSSL_TLS13
  12472. /* The TLS v1.3 server method data.
  12473. *
  12474. * returns the method data for a TLS v1.3 server.
  12475. */
  12476. WOLFSSL_ABI
  12477. WOLFSSL_METHOD* wolfTLSv1_3_server_method(void)
  12478. {
  12479. return wolfTLSv1_3_server_method_ex(NULL);
  12480. }
  12481. /* The TLS v1.3 server method data.
  12482. *
  12483. * heap The heap used for allocation.
  12484. * returns the method data for a TLS v1.3 server.
  12485. */
  12486. WOLFSSL_METHOD* wolfTLSv1_3_server_method_ex(void* heap)
  12487. {
  12488. WOLFSSL_METHOD* method =
  12489. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12490. heap, DYNAMIC_TYPE_METHOD);
  12491. (void)heap;
  12492. WOLFSSL_ENTER("TLSv1_3_server_method_ex");
  12493. if (method) {
  12494. InitSSL_Method(method, MakeTLSv1_3());
  12495. method->side = WOLFSSL_SERVER_END;
  12496. }
  12497. return method;
  12498. }
  12499. #endif /* WOLFSSL_TLS13 */
  12500. #ifdef WOLFSSL_DTLS
  12501. WOLFSSL_METHOD* wolfDTLS_server_method(void)
  12502. {
  12503. return wolfDTLS_server_method_ex(NULL);
  12504. }
  12505. WOLFSSL_METHOD* wolfDTLS_server_method_ex(void* heap)
  12506. {
  12507. WOLFSSL_METHOD* method =
  12508. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12509. heap, DYNAMIC_TYPE_METHOD);
  12510. (void)heap;
  12511. WOLFSSL_ENTER("DTLS_server_method_ex");
  12512. if (method) {
  12513. #if defined(WOLFSSL_DTLS13)
  12514. InitSSL_Method(method, MakeDTLSv1_3());
  12515. #elif !defined(WOLFSSL_NO_TLS12)
  12516. InitSSL_Method(method, MakeDTLSv1_2());
  12517. #elif !defined(NO_OLD_TLS)
  12518. InitSSL_Method(method, MakeDTLSv1());
  12519. #else
  12520. #error No DTLS version enabled!
  12521. #endif
  12522. method->downgrade = 1;
  12523. method->side = WOLFSSL_SERVER_END;
  12524. }
  12525. return method;
  12526. }
  12527. #ifndef NO_OLD_TLS
  12528. WOLFSSL_METHOD* wolfDTLSv1_server_method(void)
  12529. {
  12530. return wolfDTLSv1_server_method_ex(NULL);
  12531. }
  12532. WOLFSSL_METHOD* wolfDTLSv1_server_method_ex(void* heap)
  12533. {
  12534. WOLFSSL_METHOD* method =
  12535. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12536. heap, DYNAMIC_TYPE_METHOD);
  12537. (void)heap;
  12538. WOLFSSL_ENTER("DTLSv1_server_method_ex");
  12539. if (method) {
  12540. InitSSL_Method(method, MakeDTLSv1());
  12541. method->side = WOLFSSL_SERVER_END;
  12542. }
  12543. return method;
  12544. }
  12545. #endif /* !NO_OLD_TLS */
  12546. #ifndef WOLFSSL_NO_TLS12
  12547. WOLFSSL_METHOD* wolfDTLSv1_2_server_method(void)
  12548. {
  12549. return wolfDTLSv1_2_server_method_ex(NULL);
  12550. }
  12551. WOLFSSL_METHOD* wolfDTLSv1_2_server_method_ex(void* heap)
  12552. {
  12553. WOLFSSL_METHOD* method =
  12554. (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
  12555. heap, DYNAMIC_TYPE_METHOD);
  12556. WOLFSSL_ENTER("DTLSv1_2_server_method_ex");
  12557. (void)heap;
  12558. if (method) {
  12559. InitSSL_Method(method, MakeDTLSv1_2());
  12560. method->side = WOLFSSL_SERVER_END;
  12561. }
  12562. (void)heap;
  12563. return method;
  12564. }
  12565. #endif /* !WOLFSSL_NO_TLS12 */
  12566. #endif /* WOLFSSL_DTLS */
  12567. #endif /* NO_WOLFSSL_SERVER */
  12568. #endif /* NO_TLS */
  12569. #endif /* WOLFCRYPT_ONLY */