internal.c 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676
  1. /* internal.c
  2. *
  3. * Copyright (C) 2006-2024 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. /*
  26. * WOLFSSL_SMALL_CERT_VERIFY:
  27. * Verify the certificate signature without using DecodedCert. Doubles up
  28. * on some code but allows smaller peak heap memory usage.
  29. * Cannot be used with WOLFSSL_NONBLOCK_OCSP.
  30. * WOLFSSL_ALT_CERT_CHAINS:
  31. * Allows CA's to be presented by peer, but not part of a valid chain.
  32. * Default wolfSSL behavior is to require validation of all presented peer
  33. * certificates. This also allows loading intermediate CA's as trusted
  34. * and ignoring no signer failures for CA's up the chain to root.
  35. * WOLFSSL_DTLS_RESEND_ONLY_TIMEOUT:
  36. * Enable resending the previous DTLS handshake flight only on a network
  37. * read timeout. By default we resend in two more cases, when we receive:
  38. * - an out of order last msg of the peer's flight
  39. * - a duplicate of the first msg from the peer's flight
  40. * WOLFSSL_NO_DEF_TICKET_ENC_CB:
  41. * No default ticket encryption callback.
  42. * Server only.
  43. * Application must set its own callback to use session tickets.
  44. * WOLFSSL_TICKET_ENC_CHACHA20_POLY1305
  45. * Use ChaCha20-Poly1305 to encrypt/decrypt session tickets in default
  46. * callback. Default algorithm if none defined and algorithms compiled in.
  47. * Server only.
  48. * WOLFSSL_TICKET_ENC_AES128_GCM
  49. * Use AES128-GCM to encrypt/decrypt session tickets in default callback.
  50. * Server only. Default algorithm if ChaCha20/Poly1305 not compiled in.
  51. * WOLFSSL_TICKET_ENC_AES256_GCM
  52. * Use AES256-GCM to encrypt/decrypt session tickets in default callback.
  53. * Server only.
  54. * WOLFSSL_TICKET_DECRYPT_NO_CREATE
  55. * Default callback will not request creation of new ticket on successful
  56. * decryption.
  57. * Server only.
  58. * WOLFSSL_TLS13_NO_PEEK_HANDSHAKE_DONE
  59. * Once a normal TLS 1.3 handshake is complete, a session ticket message
  60. * may be received by a client. To support detecting this, peek will
  61. * return WOLFSSL_ERROR_WANT_READ.
  62. * This define turns off this behaviour.
  63. * WOLFSSL_HOSTNAME_VERIFY_ALT_NAME_ONLY
  64. * Verify hostname/ip address using alternate name (SAN) only and do not
  65. * use the common name. Forces use of the alternate name, so certificates
  66. * missing SAN will be rejected during the handshake
  67. * WOLFSSL_CHECK_SIG_FAULTS
  68. * Verifies the ECC signature after signing in case of faults in the
  69. * calculation of the signature. Useful when signature fault injection is a
  70. * possible attack.
  71. * WOLFSSL_TLS13_IGNORE_AEAD_LIMITS
  72. * Ignore the AEAD limits for messages specified in the RFC. After
  73. * reaching the limit, we initiate a key update. We enforce the AEAD limits
  74. * by default.
  75. * https://www.rfc-editor.org/rfc/rfc8446#section-5.5
  76. * https://www.rfc-editor.org/rfc/rfc9147.html#name-aead-limits
  77. * WOLFSSL_HARDEN_TLS
  78. * Implement the recommendations specified in RFC9325. This macro needs to
  79. * be defined to the desired number of bits of security. The currently
  80. * implemented values are 112 and 128 bits. The following macros disable
  81. * certain checks.
  82. * - WOLFSSL_HARDEN_TLS_ALLOW_TRUNCATED_HMAC
  83. * - WOLFSSL_HARDEN_TLS_ALLOW_OLD_TLS
  84. * - WOLFSSL_HARDEN_TLS_NO_SCR_CHECK
  85. * - WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK
  86. * - WOLFSSL_HARDEN_TLS_ALLOW_ALL_CIPHERSUITES
  87. * WOLFSSL_NO_INIT_CTX_KEY
  88. * Allows SSL objects to be created from a CTX without a loaded key/cert
  89. * pair
  90. */
  91. #ifdef EXTERNAL_OPTS_OPENVPN
  92. #error EXTERNAL_OPTS_OPENVPN should not be defined\
  93. when building wolfSSL
  94. #endif
  95. #ifndef WOLFCRYPT_ONLY
  96. #include <wolfssl/internal.h>
  97. #include <wolfssl/error-ssl.h>
  98. #include <wolfssl/wolfcrypt/asn.h>
  99. #include <wolfssl/wolfcrypt/dh.h>
  100. #ifdef NO_INLINE
  101. #include <wolfssl/wolfcrypt/misc.h>
  102. #else
  103. #define WOLFSSL_MISC_INCLUDED
  104. #include <wolfcrypt/src/misc.c>
  105. #endif
  106. #if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA)
  107. #include <wolfssl/wolfcrypt/srp.h>
  108. #endif
  109. #if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
  110. #include <wolfssl/wolfcrypt/coding.h>
  111. #endif
  112. #ifdef HAVE_LIBZ
  113. #include "zlib.h"
  114. #endif
  115. #ifdef WOLFSSL_QNX_CAAM
  116. /* included to get CAAM devId value */
  117. #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
  118. #endif
  119. #ifdef HAVE_ARIA
  120. /* included to get ARIA devId value */
  121. #include <wolfssl/wolfcrypt/port/aria/aria-cryptocb.h>
  122. #endif
  123. #if defined(DEBUG_WOLFSSL) || defined(SHOW_SECRETS) || \
  124. defined(CHACHA_AEAD_TEST) || defined(WOLFSSL_SESSION_EXPORT_DEBUG)
  125. #ifndef NO_STDIO_FILESYSTEM
  126. #ifdef FUSION_RTOS
  127. #include <fclstdio.h>
  128. #else
  129. #include <stdio.h>
  130. #endif
  131. #endif
  132. #endif
  133. #ifdef __sun
  134. #include <sys/filio.h>
  135. #endif
  136. #define ERROR_OUT(err, eLabel) { ret = (int)(err); goto eLabel; }
  137. #ifdef _MSC_VER
  138. /* disable for while(0) cases at the .c level for now */
  139. #pragma warning(disable:4127)
  140. #endif
  141. #if defined(WOLFSSL_CALLBACKS) && !defined(LARGE_STATIC_BUFFERS)
  142. #error \
  143. WOLFSSL_CALLBACKS needs LARGE_STATIC_BUFFERS, please add LARGE_STATIC_BUFFERS
  144. #endif
  145. #if defined(HAVE_SECURE_RENEGOTIATION) && defined(HAVE_RENEGOTIATION_INDICATION)
  146. #error Cannot use both secure-renegotiation and renegotiation-indication
  147. #endif
  148. #ifndef WOLFSSL_NO_TLS12
  149. #ifndef NO_WOLFSSL_CLIENT
  150. static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input,
  151. word32* inOutIdx, word32 size);
  152. #ifndef NO_CERTS
  153. static int DoCertificateRequest(WOLFSSL* ssl, const byte* input,
  154. word32* inOutIdx, word32 size);
  155. #endif
  156. #ifdef HAVE_SESSION_TICKET
  157. static int DoSessionTicket(WOLFSSL* ssl, const byte* input,
  158. word32* inOutIdx, word32 size);
  159. #endif
  160. #endif
  161. #ifndef NO_WOLFSSL_SERVER
  162. static int DoClientKeyExchange(WOLFSSL* ssl, byte* input,
  163. word32* inOutIdx, word32 size);
  164. #if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  165. defined(HAVE_ED448)) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  166. static int DoCertificateVerify(WOLFSSL* ssl, byte* input,
  167. word32* inOutIdx, word32 size);
  168. #endif
  169. #endif /* !NO_WOLFSSL_SERVER */
  170. #endif /* !WOLFSSL_NO_TLS12 */
  171. #if !defined(NO_WOLFSSL_SERVER) && defined(HAVE_SESSION_TICKET)
  172. #if defined(WOLFSSL_HAPROXY)
  173. #define SSL_TICKET_CTX(ssl) ssl->initial_ctx->ticketEncCtx
  174. #else
  175. #define SSL_TICKET_CTX(ssl) ssl->ctx->ticketEncCtx
  176. #endif
  177. #if !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB)
  178. static int TicketEncCbCtx_Init(WOLFSSL_CTX* ctx,
  179. TicketEncCbCtx* keyCtx);
  180. static void TicketEncCbCtx_Free(TicketEncCbCtx* keyCtx);
  181. static int DefTicketEncCb(WOLFSSL* ssl,
  182. byte key_name[WOLFSSL_TICKET_NAME_SZ],
  183. byte iv[WOLFSSL_TICKET_IV_SZ],
  184. byte mac[WOLFSSL_TICKET_MAC_SZ],
  185. int enc, byte* ticket, int inLen, int* outLen,
  186. void* userCtx);
  187. #endif
  188. #endif
  189. #ifdef WOLFSSL_DTLS
  190. static int _DtlsCheckWindow(WOLFSSL* ssl);
  191. #endif
  192. #if defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS)
  193. #include <Security/SecCertificate.h>
  194. #include <Security/SecTrust.h>
  195. #include <Security/SecPolicy.h>
  196. static int DoAppleNativeCertValidation(const WOLFSSL_BUFFER_INFO* certs,
  197. int totalCerts);
  198. #endif /* #if defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS) */
  199. #ifdef WOLFSSL_DTLS13
  200. #ifndef WOLFSSL_DTLS13_SEND_MOREACK_DEFAULT
  201. #define WOLFSSL_DTLS13_SEND_MOREACK_DEFAULT 0
  202. #endif
  203. #endif /* WOLFSSL_DTLS13 */
  204. enum processReply {
  205. doProcessInit = 0,
  206. #ifndef NO_WOLFSSL_SERVER
  207. runProcessOldClientHello,
  208. #endif
  209. getRecordLayerHeader,
  210. getData,
  211. verifyEncryptedMessage,
  212. decryptMessage,
  213. verifyMessage,
  214. runProcessingOneRecord,
  215. runProcessingOneMessage
  216. };
  217. #ifndef WOLFSSL_NO_TLS12
  218. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
  219. /* Server random bytes for TLS v1.3 described downgrade protection mechanism. */
  220. static const byte tls13Downgrade[7] = {
  221. 0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44
  222. };
  223. #define TLS13_DOWNGRADE_SZ sizeof(tls13Downgrade)
  224. #endif /* !NO_WOLFSSL_SERVER || !NO_WOLFSSL_CLIENT */
  225. #if !defined(NO_OLD_TLS) && !defined(WOLFSSL_AEAD_ONLY)
  226. static int SSL_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz,
  227. int padLen, int content, int verify, int epochOrder);
  228. #endif
  229. #endif /* !WOLFSSL_NO_TLS12 */
  230. #if !defined(NO_CERT) && defined(WOLFSSL_BLIND_PRIVATE_KEY)
  231. int wolfssl_priv_der_blind(WC_RNG* rng, DerBuffer* key, DerBuffer** mask)
  232. {
  233. int ret = 0;
  234. WC_RNG local_rng;
  235. if (key != NULL) {
  236. if (*mask != NULL) {
  237. FreeDer(mask);
  238. }
  239. ret = AllocDer(mask, key->length, key->type, key->heap);
  240. if ((ret == 0) && (rng == NULL)) {
  241. if (wc_InitRng(&local_rng) != 0) {
  242. ret = RNG_FAILURE_E;
  243. }
  244. else {
  245. rng = &local_rng;
  246. }
  247. }
  248. if (ret == 0) {
  249. ret = wc_RNG_GenerateBlock(rng, (*mask)->buffer, (*mask)->length);
  250. }
  251. if (ret == 0) {
  252. xorbuf(key->buffer, (*mask)->buffer, (*mask)->length);
  253. }
  254. if (rng == &local_rng) {
  255. wc_FreeRng(rng);
  256. }
  257. }
  258. return ret;
  259. }
  260. void wolfssl_priv_der_unblind(DerBuffer* key, DerBuffer* mask)
  261. {
  262. if (key != NULL) {
  263. xorbuf(key->buffer, mask->buffer, mask->length);
  264. }
  265. }
  266. #endif
  267. #if defined(WOLFSSL_RENESAS_FSPSM_TLS) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  268. #include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
  269. #endif
  270. #if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
  271. static int SessionSecret_callback(WOLFSSL* ssl, void* secret,
  272. int* secretSz, void* ctx);
  273. #ifdef WOLFSSL_TLS13
  274. static int SessionSecret_callback_Tls13(WOLFSSL* ssl, int id,
  275. const unsigned char* secret, int secretSz, void* ctx);
  276. #endif
  277. /* Label string for client random. */
  278. #define SSC_CR "CLIENT_RANDOM"
  279. /*
  280. * This function builds up string for key-logging then call user's
  281. * key-log-callback to pass the string for TLS1.2 and older.
  282. * The user's key-logging callback has been set via
  283. * wolfSSL_CTX_set_keylog_callback function. The logging string format is:
  284. * "CLIENT_RANDOM <hex-encoded client random> <hex-encoded master-secret>"
  285. * parameter
  286. * - ssl: WOLFSSL object
  287. * - secret: pointer to the buffer holding master-secret
  288. * - secretSz: size of secret
  289. * - ctx: not used
  290. * returns 0 on success, negative value on failure.
  291. */
  292. static int SessionSecret_callback(WOLFSSL* ssl, void* secret,
  293. int* secretSz, void* ctx)
  294. {
  295. wolfSSL_CTX_keylog_cb_func logCb = NULL;
  296. int msSz;
  297. int invalidCount;
  298. int i;
  299. const char* label = SSC_CR;
  300. int labelSz = sizeof(SSC_CR);
  301. int buffSz;
  302. byte* log = NULL;
  303. word32 outSz;
  304. int idx;
  305. int ret;
  306. (void)ctx;
  307. if (ssl == NULL || secret == NULL || secretSz == NULL || *secretSz == 0)
  308. return BAD_FUNC_ARG;
  309. if (ssl->arrays == NULL)
  310. return BAD_FUNC_ARG;
  311. /* get the user-callback func from CTX */
  312. logCb = ssl->ctx->keyLogCb;
  313. if (logCb == NULL) {
  314. return 0; /* no logging callback */
  315. }
  316. /* make sure the given master-secret has a meaningful value */
  317. msSz = *secretSz;
  318. invalidCount = 0;
  319. for (i = 0; i < msSz; i++) {
  320. if (((byte*)secret)[i] == 0) {
  321. invalidCount++;
  322. }
  323. }
  324. if (invalidCount == *secretSz) {
  325. WOLFSSL_MSG("master-secret is not valid");
  326. return 0; /* ignore error */
  327. }
  328. /* build up a hex-decoded keylog string
  329. * "CLIENT_RANDOM <hex-encoded client rand> <hex-encoded master-secret>"
  330. * note that each keylog string does not have CR/LF.
  331. */
  332. buffSz = labelSz + (RAN_LEN * 2) + 1 + ((*secretSz) * 2) + 1;
  333. log = XMALLOC(buffSz, ssl->heap, DYNAMIC_TYPE_SECRET);
  334. if (log == NULL)
  335. return MEMORY_E;
  336. #ifdef WOLFSSL_CHECK_MEM_ZERO
  337. wc_MemZero_Add("SessionSecret log", log, buffSz);
  338. #endif
  339. XMEMSET(log, 0, buffSz);
  340. XMEMCPY(log, label, labelSz -1); /* put label w/o terminator */
  341. log[labelSz - 1] = ' '; /* '\0' -> ' ' */
  342. idx = labelSz;
  343. outSz = buffSz - idx;
  344. if ((ret = Base16_Encode(ssl->arrays->clientRandom, RAN_LEN,
  345. log + idx, &outSz)) == 0) {
  346. idx += (outSz - 1); /* reduce terminator byte */
  347. outSz = buffSz - idx;
  348. if (outSz > 1) {
  349. log[idx++] = ' '; /* add space*/
  350. outSz = buffSz - idx;
  351. if ((ret = Base16_Encode((byte*)secret, *secretSz,
  352. log + idx, &outSz)) == 0) {
  353. /* pass the log to the client callback*/
  354. logCb(ssl, (char*)log);
  355. ret = 0;
  356. }
  357. }
  358. else {
  359. ret = BUFFER_E;
  360. }
  361. }
  362. /* Zero out Base16 encoded secret and other data. */
  363. ForceZero(log, buffSz);
  364. XFREE(log, ssl->heap, DYNAMIC_TYPE_SECRET);
  365. return ret;
  366. }
  367. #if defined(WOLFSSL_TLS13)
  368. /* Label string for client early traffic secret. */
  369. #define SSC_TLS13_CETS "CLIENT_EARLY_TRAFFIC_SECRET"
  370. /* Label string for client handshake traffic secret. */
  371. #define SSC_TLS13_CHTS "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
  372. /* Label string for server handshake traffic secret. */
  373. #define SSC_TLS13_SHTS "SERVER_HANDSHAKE_TRAFFIC_SECRET"
  374. /* Label string for client traffic secret. */
  375. #define SSC_TLS13_CTS "CLIENT_TRAFFIC_SECRET_0"
  376. /* Label string for server traffic secret. */
  377. #define SSC_TLS13_STS "SERVER_TRAFFIC_SECRET_0"
  378. /* Label string for early exporter secret. */
  379. #define SSC_TLS13_EES "EARLY_EXPORTER_SECRET"
  380. /* Label string for exporter secret. */
  381. #define SSC_TLS13_ES "EXPORTER_SECRET"
  382. /*
  383. * This function builds up string for key-logging then call user's
  384. * key-log-callback to pass the string for TLS1.3.
  385. * The user's key-logging callback has been set via
  386. * wolfSSL_CTX_set_keylog_callback function. The logging string format is:
  387. * "<Label> <hex-encoded client random> <hex-encoded secret>"
  388. *
  389. * parameter
  390. * - ssl: WOLFSSL object
  391. * - id: type of secret for logging
  392. * - secret: pointer to the buffer holding secret
  393. * - secretSz: size of secret
  394. * - ctx: not used
  395. * returns 0 on success, negative value on failure.
  396. */
  397. static int SessionSecret_callback_Tls13(WOLFSSL* ssl, int id,
  398. const unsigned char* secret, int secretSz, void* ctx)
  399. {
  400. wolfSSL_CTX_keylog_cb_func logCb = NULL;
  401. const char* label;
  402. int labelSz = 0;
  403. int buffSz = 0;
  404. byte* log = NULL;
  405. word32 outSz;
  406. int idx;
  407. int ret;
  408. (void)ctx;
  409. if (ssl == NULL || secret == NULL || secretSz == 0)
  410. return BAD_FUNC_ARG;
  411. if (ssl->arrays == NULL)
  412. return BAD_FUNC_ARG;
  413. /* get the user-callback func from CTX*/
  414. logCb = ssl->ctx->keyLogCb;
  415. if (logCb == NULL)
  416. return 0;
  417. switch (id) {
  418. case CLIENT_EARLY_TRAFFIC_SECRET:
  419. labelSz = sizeof(SSC_TLS13_CETS);
  420. label = SSC_TLS13_CETS;
  421. break;
  422. case CLIENT_HANDSHAKE_TRAFFIC_SECRET:
  423. labelSz = sizeof(SSC_TLS13_CHTS);
  424. label = SSC_TLS13_CHTS;
  425. break;
  426. case SERVER_HANDSHAKE_TRAFFIC_SECRET:
  427. labelSz = sizeof(SSC_TLS13_SHTS);
  428. label = SSC_TLS13_SHTS;
  429. break;
  430. case CLIENT_TRAFFIC_SECRET:
  431. labelSz = sizeof(SSC_TLS13_CTS);
  432. label = SSC_TLS13_CTS;
  433. break;
  434. case SERVER_TRAFFIC_SECRET:
  435. labelSz = sizeof(SSC_TLS13_STS);
  436. label = SSC_TLS13_STS;
  437. break;
  438. case EARLY_EXPORTER_SECRET:
  439. labelSz = sizeof(SSC_TLS13_EES);
  440. label = SSC_TLS13_EES;
  441. break;
  442. case EXPORTER_SECRET:
  443. labelSz = sizeof(SSC_TLS13_ES);
  444. label = SSC_TLS13_ES;
  445. break;
  446. default:
  447. return BAD_FUNC_ARG;
  448. }
  449. /* prepare a log string for passing user callback
  450. * "<Label> <hex-encoded client random> <hex-encoded secret>" */
  451. buffSz = labelSz + (RAN_LEN * 2) + 1 + secretSz * 2 + 1;
  452. log = XMALLOC(buffSz, ssl->heap, DYNAMIC_TYPE_SECRET);
  453. if (log == NULL)
  454. return MEMORY_E;
  455. #ifdef WOLFSSL_CHECK_MEM_ZERO
  456. wc_MemZero_Add("SessionSecret log", log, buffSz);
  457. #endif
  458. XMEMSET(log, 0, buffSz);
  459. XMEMCPY(log, label, labelSz - 1); /* put label w/o terminator */
  460. log[labelSz - 1] = ' '; /* '\0' -> ' ' */
  461. idx = labelSz;
  462. outSz = buffSz - idx;
  463. if ((ret = Base16_Encode(ssl->arrays->clientRandom, RAN_LEN,
  464. log + idx, &outSz)) == 0) {
  465. idx += (outSz - 1); /* reduce terminator byte */
  466. outSz = buffSz - idx;
  467. if (outSz >1) {
  468. log[idx++] = ' '; /* add space*/
  469. outSz = buffSz - idx;
  470. if ((ret = Base16_Encode((byte*)secret, secretSz,
  471. log + idx, &outSz)) == 0) {
  472. logCb(ssl, (char*)log);
  473. ret = 0;
  474. }
  475. }
  476. else
  477. ret = MEMORY_E;
  478. }
  479. /* Zero out Base16 encoded secret and other data. */
  480. ForceZero(log, buffSz);
  481. XFREE(log, ssl->heap, DYNAMIC_TYPE_SECRET);
  482. return ret;
  483. }
  484. #endif /* WOLFSSL_TLS13*/
  485. #endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK*/
  486. int IsTLS(const WOLFSSL* ssl)
  487. {
  488. if (ssl->version.major == SSLv3_MAJOR && ssl->version.minor >=TLSv1_MINOR)
  489. return 1;
  490. #ifdef WOLFSSL_DTLS
  491. if (ssl->version.major == DTLS_MAJOR)
  492. return 1;
  493. #endif
  494. return 0;
  495. }
  496. int IsTLS_ex(const ProtocolVersion pv)
  497. {
  498. if (pv.major == SSLv3_MAJOR && pv.minor >=TLSv1_MINOR)
  499. return 1;
  500. #ifdef WOLFSSL_DTLS
  501. if (pv.major == DTLS_MAJOR)
  502. return 1;
  503. #endif
  504. return 0;
  505. }
  506. int IsAtLeastTLSv1_2(const WOLFSSL* ssl)
  507. {
  508. if (ssl->version.major == SSLv3_MAJOR && ssl->version.minor >=TLSv1_2_MINOR)
  509. return 1;
  510. #ifdef WOLFSSL_DTLS
  511. if (ssl->version.major == DTLS_MAJOR && ssl->version.minor <= DTLSv1_2_MINOR)
  512. return 1;
  513. #endif
  514. return 0;
  515. }
  516. int IsAtLeastTLSv1_3(const ProtocolVersion pv)
  517. {
  518. int ret;
  519. ret = (pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_3_MINOR);
  520. #ifdef WOLFSSL_DTLS13
  521. if (ret == 0 && pv.major == DTLS_MAJOR && pv.minor <= DTLSv1_3_MINOR)
  522. return 1;
  523. #endif
  524. return ret;
  525. }
  526. int IsEncryptionOn(const WOLFSSL* ssl, int isSend)
  527. {
  528. #ifdef WOLFSSL_DTLS
  529. /* For DTLS, epoch 0 is always not encrypted. */
  530. if (ssl->options.dtls && !isSend) {
  531. if (!IsAtLeastTLSv1_3(ssl->version) && ssl->keys.curEpoch == 0)
  532. return 0;
  533. #ifdef WOLFSSL_DTLS13
  534. else if (IsAtLeastTLSv1_3(ssl->version)
  535. && w64IsZero(ssl->keys.curEpoch64))
  536. return 0;
  537. #endif /* WOLFSSL_DTLS13 */
  538. }
  539. #endif /* WOLFSSL_DTLS */
  540. #ifdef WOLFSSL_QUIC
  541. if (WOLFSSL_IS_QUIC(ssl) && IsAtLeastTLSv1_3(ssl->version)) {
  542. return 0;
  543. }
  544. #endif
  545. return ssl->keys.encryptionOn &&
  546. (isSend ? ssl->encrypt.setup : ssl->decrypt.setup);
  547. }
  548. #ifdef WOLFSSL_DTLS
  549. /* Stream Control Transmission Protocol */
  550. /* If SCTP is not enabled returns the state of the dtls option.
  551. * If SCTP is enabled returns dtls && !sctp. */
  552. int IsDtlsNotSctpMode(WOLFSSL* ssl)
  553. {
  554. #ifdef WOLFSSL_SCTP
  555. return ssl->options.dtls && !ssl->options.dtlsSctp;
  556. #else
  557. return ssl->options.dtls;
  558. #endif
  559. }
  560. #if !defined(WOLFSSL_NO_TLS12) && !defined(NO_WOLFSSL_SERVER)
  561. /* Secure Real-time Transport Protocol */
  562. /* If SRTP is not enabled returns the state of the dtls option.
  563. * If SRTP is enabled returns dtls && !dtlsSrtpProfiles. */
  564. int IsDtlsNotSrtpMode(WOLFSSL* ssl)
  565. {
  566. #ifdef WOLFSSL_SRTP
  567. return ssl->options.dtls && !ssl->dtlsSrtpProfiles;
  568. #else
  569. return ssl->options.dtls;
  570. #endif
  571. }
  572. #endif /* !WOLFSSL_NO_TLS12 && !NO_WOLFSSL_SERVER */
  573. #endif /* WOLFSSL_DTLS */
  574. #ifdef HAVE_LIBZ
  575. /* alloc user allocs to work with zlib */
  576. static void* myAlloc(void* opaque, unsigned int item, unsigned int size)
  577. {
  578. (void)opaque;
  579. return (void *)XMALLOC(item * size, opaque, DYNAMIC_TYPE_LIBZ);
  580. }
  581. static void myFree(void* opaque, void* memory)
  582. {
  583. (void)opaque;
  584. XFREE(memory, opaque, DYNAMIC_TYPE_LIBZ);
  585. }
  586. /* init zlib comp/decomp streams, 0 on success */
  587. static int InitStreams(WOLFSSL* ssl)
  588. {
  589. ssl->c_stream.zalloc = (alloc_func)myAlloc;
  590. ssl->c_stream.zfree = (free_func)myFree;
  591. ssl->c_stream.opaque = (voidpf)ssl->heap;
  592. if (deflateInit(&ssl->c_stream, Z_DEFAULT_COMPRESSION) != Z_OK)
  593. return ZLIB_INIT_ERROR;
  594. ssl->didStreamInit = 1;
  595. ssl->d_stream.zalloc = (alloc_func)myAlloc;
  596. ssl->d_stream.zfree = (free_func)myFree;
  597. ssl->d_stream.opaque = (voidpf)ssl->heap;
  598. if (inflateInit(&ssl->d_stream) != Z_OK) return ZLIB_INIT_ERROR;
  599. return 0;
  600. }
  601. static void FreeStreams(WOLFSSL* ssl)
  602. {
  603. if (ssl->didStreamInit) {
  604. deflateEnd(&ssl->c_stream);
  605. inflateEnd(&ssl->d_stream);
  606. }
  607. }
  608. /* compress in to out, return out size or error */
  609. static int myCompress(WOLFSSL* ssl, byte* in, int inSz, byte* out, int outSz)
  610. {
  611. int err;
  612. int currTotal = (int)ssl->c_stream.total_out;
  613. ssl->c_stream.next_in = in;
  614. ssl->c_stream.avail_in = inSz;
  615. ssl->c_stream.next_out = out;
  616. ssl->c_stream.avail_out = outSz;
  617. err = deflate(&ssl->c_stream, Z_SYNC_FLUSH);
  618. if (err != Z_OK && err != Z_STREAM_END) return ZLIB_COMPRESS_ERROR;
  619. return (int)ssl->c_stream.total_out - currTotal;
  620. }
  621. /* decompress in to out, return out size or error */
  622. static int myDeCompress(WOLFSSL* ssl, byte* in,int inSz, byte* out,int outSz)
  623. {
  624. int err;
  625. int currTotal = (int)ssl->d_stream.total_out;
  626. ssl->d_stream.next_in = in;
  627. ssl->d_stream.avail_in = inSz;
  628. ssl->d_stream.next_out = out;
  629. ssl->d_stream.avail_out = outSz;
  630. err = inflate(&ssl->d_stream, Z_SYNC_FLUSH);
  631. if (err != Z_OK && err != Z_STREAM_END) return ZLIB_DECOMPRESS_ERROR;
  632. return (int)ssl->d_stream.total_out - currTotal;
  633. }
  634. #endif /* HAVE_LIBZ */
  635. #ifdef WOLFSSL_SESSION_EXPORT
  636. /**
  637. * serializes the cipher specs struct for exporting
  638. * @return the amount written to 'exp' buffer
  639. */
  640. static int ExportCipherSpecState(WOLFSSL* ssl, byte* exp, word32 len, byte ver,
  641. int type)
  642. {
  643. word32 idx = 0;
  644. CipherSpecs* specs;
  645. WOLFSSL_ENTER("ExportCipherSpecState");
  646. if (exp == NULL || ssl == NULL) {
  647. return BAD_FUNC_ARG;
  648. }
  649. specs = &ssl->specs;
  650. if (WOLFSSL_EXPORT_SPC_SZ > len) {
  651. return BUFFER_E;
  652. }
  653. XMEMSET(exp, 0, WOLFSSL_EXPORT_SPC_SZ);
  654. c16toa(specs->key_size, exp + idx); idx += OPAQUE16_LEN;
  655. c16toa(specs->iv_size, exp + idx); idx += OPAQUE16_LEN;
  656. c16toa(specs->block_size, exp + idx); idx += OPAQUE16_LEN;
  657. c16toa(specs->aead_mac_size, exp + idx); idx += OPAQUE16_LEN;
  658. exp[idx++] = specs->bulk_cipher_algorithm;
  659. exp[idx++] = specs->cipher_type;
  660. exp[idx++] = specs->mac_algorithm;
  661. exp[idx++] = specs->kea;
  662. exp[idx++] = specs->sig_algo;
  663. exp[idx++] = specs->hash_size;
  664. exp[idx++] = specs->pad_size;
  665. exp[idx++] = specs->static_ecdh;
  666. if (idx != WOLFSSL_EXPORT_SPC_SZ) {
  667. WOLFSSL_MSG("WOLFSSL_EXPORT_SPC_SZ needs updated and export version");
  668. return DTLS_EXPORT_VER_E;
  669. }
  670. /* send over state of AES too */
  671. if (type == WOLFSSL_EXPORT_TLS &&
  672. ssl->specs.bulk_cipher_algorithm == wolfssl_aes) {
  673. byte *pt = (byte*)ssl->encrypt.aes->reg;
  674. if ((idx + 2*AES_BLOCK_SIZE) > len) {
  675. WOLFSSL_MSG("Can not fit AES state into buffer");
  676. return BUFFER_E;
  677. }
  678. XMEMCPY(exp + idx, pt, AES_BLOCK_SIZE);
  679. idx += AES_BLOCK_SIZE;
  680. pt = (byte*)ssl->decrypt.aes->reg;
  681. XMEMCPY(exp + idx, pt, AES_BLOCK_SIZE);
  682. idx += AES_BLOCK_SIZE;
  683. }
  684. WOLFSSL_LEAVE("ExportCipherSpecState", idx);
  685. (void)ver;
  686. return idx;
  687. }
  688. /* serializes the key struct for exporting */
  689. static int ExportKeyState(WOLFSSL* ssl, byte* exp, word32 len, byte ver,
  690. byte small, int type)
  691. {
  692. word32 idx = 0;
  693. byte sz;
  694. Keys* keys;
  695. WOLFSSL_ENTER("ExportKeyState");
  696. if (exp == NULL || ssl == NULL) {
  697. return BAD_FUNC_ARG;
  698. }
  699. keys = &(ssl->keys);
  700. if (DTLS_EXPORT_MIN_KEY_SZ > len) {
  701. WOLFSSL_MSG("Buffer not large enough for minimum key struct size");
  702. return BUFFER_E;
  703. }
  704. XMEMSET(exp, 0, DTLS_EXPORT_MIN_KEY_SZ);
  705. c32toa(keys->peer_sequence_number_hi, exp + idx); idx += OPAQUE32_LEN;
  706. c32toa(keys->peer_sequence_number_lo, exp + idx); idx += OPAQUE32_LEN;
  707. c32toa(keys->sequence_number_hi, exp + idx); idx += OPAQUE32_LEN;
  708. c32toa(keys->sequence_number_lo, exp + idx); idx += OPAQUE32_LEN;
  709. #if defined(WOLFSSL_DTLS)
  710. if (type == WOLFSSL_EXPORT_DTLS) {
  711. c16toa(keys->peerSeq[0].nextEpoch, exp + idx); idx += OPAQUE16_LEN;
  712. c16toa(keys->peerSeq[0].nextSeq_hi, exp + idx); idx += OPAQUE16_LEN;
  713. c32toa(keys->peerSeq[0].nextSeq_lo, exp + idx); idx += OPAQUE32_LEN;
  714. c16toa(keys->curEpoch, exp + idx); idx += OPAQUE16_LEN;
  715. c16toa(keys->curSeq_hi, exp + idx); idx += OPAQUE16_LEN;
  716. c32toa(keys->curSeq_lo, exp + idx); idx += OPAQUE32_LEN;
  717. c16toa(keys->peerSeq[0].prevSeq_hi, exp + idx); idx += OPAQUE16_LEN;
  718. c32toa(keys->peerSeq[0].prevSeq_lo, exp + idx); idx += OPAQUE32_LEN;
  719. c16toa(keys->dtls_peer_handshake_number, exp + idx);
  720. idx += OPAQUE16_LEN;
  721. c16toa(keys->dtls_expected_peer_handshake_number, exp + idx);
  722. idx += OPAQUE16_LEN;
  723. c16toa(keys->dtls_sequence_number_hi, exp + idx); idx += OPAQUE16_LEN;
  724. c32toa(keys->dtls_sequence_number_lo, exp + idx); idx += OPAQUE32_LEN;
  725. c16toa(keys->dtls_prev_sequence_number_hi, exp + idx);
  726. idx += OPAQUE16_LEN;
  727. c32toa(keys->dtls_prev_sequence_number_lo, exp + idx);
  728. idx += OPAQUE32_LEN;
  729. c16toa(keys->dtls_epoch, exp + idx); idx += OPAQUE16_LEN;
  730. c16toa(keys->dtls_handshake_number, exp + idx); idx += OPAQUE16_LEN;
  731. }
  732. #endif
  733. c32toa(keys->encryptSz, exp + idx); idx += OPAQUE32_LEN;
  734. c32toa(keys->padSz, exp + idx); idx += OPAQUE32_LEN;
  735. exp[idx++] = keys->encryptionOn;
  736. exp[idx++] = keys->decryptedCur;
  737. /* from here on the buffer needs checked because is variable length that
  738. * can be larger than DTLS_EXPORT_MIN_KEY_SZ */
  739. #ifdef WOLFSSL_DTLS
  740. if (type == WOLFSSL_EXPORT_DTLS) {
  741. word32 i;
  742. if ((OPAQUE16_LEN * 2) + idx +
  743. (2 * (WOLFSSL_DTLS_WINDOW_WORDS * OPAQUE32_LEN)) > len) {
  744. WOLFSSL_MSG("Buffer not large enough for WOLFSSL_DTLS_WINDOW_WORDS");
  745. return BUFFER_E;
  746. }
  747. c16toa(WOLFSSL_DTLS_WINDOW_WORDS, exp + idx); idx += OPAQUE16_LEN;
  748. for (i = 0; i < WOLFSSL_DTLS_WINDOW_WORDS; i++) {
  749. c32toa(keys->peerSeq[0].window[i], exp + idx);
  750. idx += OPAQUE32_LEN;
  751. }
  752. c16toa(WOLFSSL_DTLS_WINDOW_WORDS, exp + idx); idx += OPAQUE16_LEN;
  753. for (i = 0; i < WOLFSSL_DTLS_WINDOW_WORDS; i++) {
  754. c32toa(keys->peerSeq[0].prevWindow[i], exp + idx);
  755. idx += OPAQUE32_LEN;
  756. }
  757. }
  758. #endif
  759. if (idx >= len) {
  760. WOLFSSL_MSG("Buffer not large enough for truncated hmac flag");
  761. return BUFFER_E;
  762. }
  763. #ifdef HAVE_TRUNCATED_HMAC
  764. sz = ssl->truncated_hmac ? TRUNCATED_HMAC_SZ: ssl->specs.hash_size;
  765. exp[idx++] = ssl->truncated_hmac;
  766. #else
  767. sz = ssl->specs.hash_size;
  768. exp[idx++] = 0; /* no truncated hmac */
  769. #endif
  770. sz = (small)? 0: sz;
  771. if (idx + (sz * 2) + OPAQUE8_LEN > len) {
  772. WOLFSSL_MSG("Buffer not large enough for MAC secret");
  773. return BUFFER_E;
  774. }
  775. exp[idx++] = sz;
  776. if (sz > 0) {
  777. #ifndef WOLFSSL_AEAD_ONLY
  778. XMEMCPY(exp + idx, keys->client_write_MAC_secret, sz); idx += sz;
  779. XMEMCPY(exp + idx, keys->server_write_MAC_secret, sz); idx += sz;
  780. #else
  781. XMEMSET(exp + idx, 0, sz); idx += sz;
  782. XMEMSET(exp + idx, 0, sz); idx += sz;
  783. #endif
  784. }
  785. sz = (small)? 0: ssl->specs.key_size;
  786. if (idx + (sz * 2) + OPAQUE8_LEN > len) {
  787. WOLFSSL_MSG("Buffer not large enough for write key");
  788. return BUFFER_E;
  789. }
  790. exp[idx++] = sz;
  791. if (sz > 0) {
  792. XMEMCPY(exp + idx, keys->client_write_key, sz); idx += sz;
  793. XMEMCPY(exp + idx, keys->server_write_key, sz); idx += sz;
  794. }
  795. sz = (small)? 0: ssl->specs.iv_size;
  796. if (idx + (sz * 2) + OPAQUE8_LEN + AEAD_MAX_EXP_SZ > len) {
  797. WOLFSSL_MSG("Buffer not large enough for IVs");
  798. return BUFFER_E;
  799. }
  800. exp[idx++] = sz;
  801. if (sz > 0) {
  802. XMEMCPY(exp + idx, keys->client_write_IV, sz); idx += sz;
  803. XMEMCPY(exp + idx, keys->server_write_IV, sz); idx += sz;
  804. }
  805. XMEMCPY(exp + idx, keys->aead_exp_IV, AEAD_MAX_EXP_SZ);
  806. idx += AEAD_MAX_EXP_SZ;
  807. sz = (small)? 0: AEAD_MAX_IMP_SZ;
  808. if (idx + (sz * 2) + OPAQUE8_LEN > len) {
  809. WOLFSSL_MSG("Buffer not large enough for imp IVs");
  810. return BUFFER_E;
  811. }
  812. exp[idx++] = sz;
  813. if (sz > 0) {
  814. XMEMCPY(exp + idx, keys->aead_enc_imp_IV, sz); idx += sz;
  815. XMEMCPY(exp + idx, keys->aead_dec_imp_IV, sz); idx += sz;
  816. }
  817. /* DTLS_EXPORT_KEY_SZ is max value. idx size can vary */
  818. if (idx > DTLS_EXPORT_KEY_SZ) {
  819. WOLFSSL_MSG("DTLS_EXPORT_KEY_SZ needs updated and export version");
  820. return DTLS_EXPORT_VER_E;
  821. }
  822. WOLFSSL_LEAVE("ExportKeyState", idx);
  823. (void)ver;
  824. (void)type;
  825. return idx;
  826. }
  827. /**
  828. * Imports the buffer 'exp' into the 'ssl' CipherSpec structure.
  829. * @param ssl WOLFSSL structure to import into
  830. * @param exp input buffer to read from
  831. * @param len length of exp buffer
  832. * @param ver version of import buffer found
  833. * @param type flag for importing a TLS session or DTLS
  834. *
  835. * @return size of exp buffer consumed on success and negative value on fail
  836. */
  837. static int ImportCipherSpecState(WOLFSSL* ssl, const byte* exp, word32 len,
  838. byte ver, int type)
  839. {
  840. word32 idx = 0;
  841. CipherSpecs* specs;
  842. word32 tmp_seq_peer_lo;
  843. word32 tmp_seq_peer_hi;
  844. word32 tmp_seq_lo;
  845. word32 tmp_seq_hi;
  846. int ret;
  847. WOLFSSL_ENTER("ImportCipherSpecState");
  848. if (exp == NULL || ssl == NULL) {
  849. return BAD_FUNC_ARG;
  850. }
  851. specs= &(ssl->specs);
  852. if (WOLFSSL_EXPORT_SPC_SZ > len) {
  853. WOLFSSL_MSG("Buffer not large enough for max spec struct size");
  854. return BUFFER_E;
  855. }
  856. ato16(exp + idx, &specs->key_size); idx += OPAQUE16_LEN;
  857. ato16(exp + idx, &specs->iv_size); idx += OPAQUE16_LEN;
  858. ato16(exp + idx, &specs->block_size); idx += OPAQUE16_LEN;
  859. ato16(exp + idx, &specs->aead_mac_size); idx += OPAQUE16_LEN;
  860. specs->bulk_cipher_algorithm = exp[idx++];
  861. specs->cipher_type = exp[idx++];
  862. specs->mac_algorithm = exp[idx++];
  863. specs->kea = exp[idx++];
  864. specs->sig_algo = exp[idx++];
  865. specs->hash_size = exp[idx++];
  866. specs->pad_size = exp[idx++];
  867. specs->static_ecdh = exp[idx++];
  868. if (specs->pad_size != PAD_MD5 && specs->pad_size != PAD_SHA) {
  869. WOLFSSL_MSG("Importing bad or unknown pad size");
  870. return BAD_STATE_E;
  871. }
  872. /* temporarily save the sequence numbers */
  873. tmp_seq_peer_lo = ssl->keys.peer_sequence_number_lo;
  874. tmp_seq_peer_hi = ssl->keys.peer_sequence_number_hi;
  875. tmp_seq_lo = ssl->keys.sequence_number_lo;
  876. tmp_seq_hi = ssl->keys.sequence_number_hi;
  877. if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) < 0) {
  878. return ret;
  879. }
  880. /* reset sequence numbers after setting keys */
  881. ssl->keys.peer_sequence_number_lo = tmp_seq_peer_lo;
  882. ssl->keys.peer_sequence_number_hi = tmp_seq_peer_hi;
  883. ssl->keys.sequence_number_lo = tmp_seq_lo;
  884. ssl->keys.sequence_number_hi = tmp_seq_hi;
  885. if (type == WOLFSSL_EXPORT_TLS &&
  886. ssl->specs.bulk_cipher_algorithm == wolfssl_aes) {
  887. byte *pt = (byte*)ssl->encrypt.aes->reg;
  888. XMEMCPY(pt, exp + idx, AES_BLOCK_SIZE);
  889. idx += AES_BLOCK_SIZE;
  890. pt = (byte*)ssl->decrypt.aes->reg;
  891. XMEMCPY(pt, exp + idx, AES_BLOCK_SIZE);
  892. idx += AES_BLOCK_SIZE;
  893. }
  894. WOLFSSL_LEAVE("ImportCipherSpecState", idx);
  895. (void)ver;
  896. return idx;
  897. }
  898. /**
  899. * Import the Key structure
  900. *
  901. * @param ssl WOLFSSL structure to import into
  902. * @param exp buffer to read Key values from
  903. * @param len max length of buffer 'exp'
  904. * @param ver version of import buffer found
  905. * @param type flag for TLS vs DTLS
  906. *
  907. * @return amount of data read from exp on success or negative on fail
  908. */
  909. static int ImportKeyState(WOLFSSL* ssl, const byte* exp, word32 len, byte ver,
  910. int type)
  911. {
  912. word32 idx = 0;
  913. byte sz;
  914. Keys *keys;
  915. WOLFSSL_ENTER("ImportKeyState");
  916. if (exp == NULL || ssl == NULL) {
  917. return BAD_FUNC_ARG;
  918. }
  919. keys = &(ssl->keys);
  920. /* check minimum length -- includes byte used for size indicators */
  921. if (len < DTLS_EXPORT_MIN_KEY_SZ) {
  922. WOLFSSL_MSG("Buffer not large enough for minimum expected size");
  923. return BUFFER_E;
  924. }
  925. ato32(exp + idx, &keys->peer_sequence_number_hi); idx += OPAQUE32_LEN;
  926. ato32(exp + idx, &keys->peer_sequence_number_lo); idx += OPAQUE32_LEN;
  927. ato32(exp + idx, &keys->sequence_number_hi); idx += OPAQUE32_LEN;
  928. ato32(exp + idx, &keys->sequence_number_lo); idx += OPAQUE32_LEN;
  929. #if defined(WOLFSSL_DTLS)
  930. if (type == WOLFSSL_EXPORT_DTLS) {
  931. ato16(exp + idx, &keys->peerSeq[0].nextEpoch); idx += OPAQUE16_LEN;
  932. ato16(exp + idx, &keys->peerSeq[0].nextSeq_hi); idx += OPAQUE16_LEN;
  933. ato32(exp + idx, &keys->peerSeq[0].nextSeq_lo); idx += OPAQUE32_LEN;
  934. ato16(exp + idx, &keys->curEpoch); idx += OPAQUE16_LEN;
  935. ato16(exp + idx, &keys->curSeq_hi); idx += OPAQUE16_LEN;
  936. ato32(exp + idx, &keys->curSeq_lo); idx += OPAQUE32_LEN;
  937. ato16(exp + idx, &keys->peerSeq[0].prevSeq_hi); idx += OPAQUE16_LEN;
  938. ato32(exp + idx, &keys->peerSeq[0].prevSeq_lo); idx += OPAQUE32_LEN;
  939. ato16(exp + idx, &keys->dtls_peer_handshake_number);
  940. idx += OPAQUE16_LEN;
  941. ato16(exp + idx, &keys->dtls_expected_peer_handshake_number);
  942. idx += OPAQUE16_LEN;
  943. ato16(exp + idx, &keys->dtls_sequence_number_hi); idx += OPAQUE16_LEN;
  944. ato32(exp + idx, &keys->dtls_sequence_number_lo); idx += OPAQUE32_LEN;
  945. ato16(exp + idx, &keys->dtls_prev_sequence_number_hi);
  946. idx += OPAQUE16_LEN;
  947. ato32(exp + idx, &keys->dtls_prev_sequence_number_lo);
  948. idx += OPAQUE32_LEN;
  949. ato16(exp + idx, &keys->dtls_epoch); idx += OPAQUE16_LEN;
  950. ato16(exp + idx, &keys->dtls_handshake_number); idx += OPAQUE16_LEN;
  951. }
  952. #endif
  953. ato32(exp + idx, &keys->encryptSz); idx += OPAQUE32_LEN;
  954. ato32(exp + idx, &keys->padSz); idx += OPAQUE32_LEN;
  955. keys->encryptionOn = exp[idx++];
  956. keys->decryptedCur = exp[idx++];
  957. #if defined(WOLFSSL_DTLS)
  958. if (type == WOLFSSL_EXPORT_DTLS) {
  959. word16 i, wordCount, wordAdj = 0;
  960. /* do window */
  961. ato16(exp + idx, &wordCount);
  962. idx += OPAQUE16_LEN;
  963. if (wordCount > WOLFSSL_DTLS_WINDOW_WORDS) {
  964. wordCount = WOLFSSL_DTLS_WINDOW_WORDS;
  965. wordAdj = (WOLFSSL_DTLS_WINDOW_WORDS - wordCount) * sizeof(word32);
  966. }
  967. XMEMSET(keys->peerSeq[0].window, 0xFF, DTLS_SEQ_SZ);
  968. for (i = 0; i < wordCount; i++) {
  969. ato32(exp + idx, &keys->peerSeq[0].window[i]);
  970. idx += OPAQUE32_LEN;
  971. }
  972. idx += wordAdj;
  973. /* do prevWindow */
  974. ato16(exp + idx, &wordCount);
  975. idx += OPAQUE16_LEN;
  976. if (wordCount > WOLFSSL_DTLS_WINDOW_WORDS) {
  977. wordCount = WOLFSSL_DTLS_WINDOW_WORDS;
  978. wordAdj = (WOLFSSL_DTLS_WINDOW_WORDS - wordCount) * sizeof(word32);
  979. }
  980. XMEMSET(keys->peerSeq[0].prevWindow, 0xFF, DTLS_SEQ_SZ);
  981. for (i = 0; i < wordCount; i++) {
  982. ato32(exp + idx, &keys->peerSeq[0].prevWindow[i]);
  983. idx += OPAQUE32_LEN;
  984. }
  985. idx += wordAdj;
  986. }
  987. #endif
  988. #ifdef HAVE_TRUNCATED_HMAC
  989. ssl->truncated_hmac = exp[idx++];
  990. #else
  991. idx++; /* no truncated hmac */
  992. #endif
  993. sz = exp[idx++];
  994. #ifndef WOLFSSL_AEAD_ONLY
  995. if (sz > sizeof(keys->client_write_MAC_secret) || (sz * 2) + idx > len) {
  996. WOLFSSL_MSG("Buffer not large enough for MAC import");
  997. return BUFFER_E;
  998. }
  999. if (sz > 0) {
  1000. XMEMCPY(keys->client_write_MAC_secret, exp + idx, sz); idx += sz;
  1001. XMEMCPY(keys->server_write_MAC_secret, exp + idx, sz); idx += sz;
  1002. }
  1003. #else
  1004. if (sz + idx > len) {
  1005. return BUFFER_E;
  1006. }
  1007. idx += sz; idx += sz;
  1008. #endif
  1009. sz = exp[idx++];
  1010. if (sz > sizeof(keys->client_write_key) || (sz * 2) + idx > len) {
  1011. WOLFSSL_MSG("Buffer not large enough for key import");
  1012. return BUFFER_E;
  1013. }
  1014. if (sz > 0) {
  1015. XMEMCPY(keys->client_write_key, exp + idx, sz); idx += sz;
  1016. XMEMCPY(keys->server_write_key, exp + idx, sz); idx += sz;
  1017. }
  1018. sz = exp[idx++];
  1019. if (sz > sizeof(keys->client_write_IV) || (sz * 2) + idx > len) {
  1020. WOLFSSL_MSG("Buffer not large enough for write IV import");
  1021. return BUFFER_E;
  1022. }
  1023. if (sz > 0) {
  1024. XMEMCPY(keys->client_write_IV, exp + idx, sz); idx += sz;
  1025. XMEMCPY(keys->server_write_IV, exp + idx, sz); idx += sz;
  1026. }
  1027. XMEMCPY(keys->aead_exp_IV, exp + idx, AEAD_MAX_EXP_SZ);
  1028. idx += AEAD_MAX_EXP_SZ;
  1029. sz = exp[idx++];
  1030. if (sz > sizeof(keys->aead_enc_imp_IV) || (sz * 2) + idx > len) {
  1031. WOLFSSL_MSG("Buffer not large enough for imp IV import");
  1032. return BUFFER_E;
  1033. }
  1034. if (sz > 0) {
  1035. XMEMCPY(keys->aead_enc_imp_IV, exp + idx, sz); idx += sz;
  1036. XMEMCPY(keys->aead_dec_imp_IV, exp + idx, sz); idx += sz;
  1037. }
  1038. WOLFSSL_LEAVE("ImportKeyState", idx);
  1039. (void)ver;
  1040. (void)type;
  1041. return idx;
  1042. }
  1043. /* copy over necessary information from Options struct to buffer
  1044. * On success returns size of buffer used on failure returns a negative value */
  1045. static int ExportOptions(WOLFSSL* ssl, byte* exp, word32 len, byte ver,
  1046. int type)
  1047. {
  1048. int idx = 0;
  1049. word16 zero = 0;
  1050. Options *options;
  1051. WOLFSSL_ENTER("ExportOptions");
  1052. if (ssl == NULL || exp == NULL || len < DTLS_EXPORT_OPT_SZ) {
  1053. return BAD_FUNC_ARG;
  1054. }
  1055. options = &ssl->options;
  1056. if (options == NULL) {
  1057. return BAD_FUNC_ARG;
  1058. }
  1059. XMEMSET(exp, 0, DTLS_EXPORT_OPT_SZ);
  1060. /* these options are kept and sent to indicate verify status and strength
  1061. * of handshake */
  1062. exp[idx++] = options->sendVerify;
  1063. exp[idx++] = options->verifyPeer;
  1064. exp[idx++] = options->verifyNone;
  1065. exp[idx++] = options->downgrade;
  1066. #ifndef NO_DH
  1067. c16toa(options->minDhKeySz, exp + idx); idx += OPAQUE16_LEN;
  1068. c16toa(options->maxDhKeySz, exp + idx); idx += OPAQUE16_LEN;
  1069. c16toa(options->dhKeySz, exp + idx); idx += OPAQUE16_LEN;
  1070. #else
  1071. c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
  1072. c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
  1073. c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
  1074. #endif
  1075. #ifndef NO_RSA
  1076. c16toa((word16)(options->minRsaKeySz), exp + idx); idx += OPAQUE16_LEN;
  1077. #else
  1078. c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
  1079. #endif
  1080. #ifdef HAVE_ECC
  1081. c16toa((word16)(options->minEccKeySz), exp + idx); idx += OPAQUE16_LEN;
  1082. #else
  1083. c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
  1084. #endif
  1085. /* these options are kept to indicate state and behavior */
  1086. #ifndef NO_PSK
  1087. exp[idx++] = options->havePSK;
  1088. #else
  1089. exp[idx++] = 0;
  1090. #endif
  1091. exp[idx++] = options->sessionCacheOff;
  1092. exp[idx++] = options->sessionCacheFlushOff;
  1093. exp[idx++] = options->side;
  1094. exp[idx++] = options->resuming;
  1095. exp[idx++] = options->haveSessionId;
  1096. exp[idx++] = options->tls;
  1097. exp[idx++] = options->tls1_1;
  1098. exp[idx++] = options->dtls;
  1099. exp[idx++] = options->connReset;
  1100. exp[idx++] = options->isClosed;
  1101. exp[idx++] = options->closeNotify;
  1102. exp[idx++] = options->sentNotify;
  1103. exp[idx++] = options->usingCompression;
  1104. exp[idx++] = options->haveRSA;
  1105. exp[idx++] = options->haveECC;
  1106. exp[idx++] = options->haveDH;
  1107. exp[idx++] = 0; /* Historical: haveNTRU */
  1108. exp[idx++] = 0; /* Historical: haveQSH */
  1109. exp[idx++] = options->haveECDSAsig;
  1110. exp[idx++] = options->haveStaticECC;
  1111. exp[idx++] = options->havePeerVerify;
  1112. exp[idx++] = options->usingPSK_cipher;
  1113. exp[idx++] = options->usingAnon_cipher;
  1114. exp[idx++] = 0; /* Historical: options->sendAlertState */
  1115. exp[idx++] = options->partialWrite;
  1116. exp[idx++] = options->quietShutdown;
  1117. exp[idx++] = options->groupMessages;
  1118. #ifdef HAVE_POLY1305
  1119. exp[idx++] = options->oldPoly;
  1120. #else
  1121. exp[idx++] = 0;
  1122. #endif
  1123. #ifdef HAVE_ANON
  1124. exp[idx++] = options->useAnon;
  1125. #else
  1126. exp[idx++] = 0;
  1127. #endif
  1128. #ifdef HAVE_SESSION_TICKET
  1129. exp[idx++] = options->createTicket;
  1130. exp[idx++] = options->useTicket;
  1131. exp[idx++] = options->noTicketTls12;
  1132. #ifdef WOLFSSL_TLS13
  1133. if (ver > WOLFSSL_EXPORT_VERSION_3) {
  1134. exp[idx++] = options->noTicketTls13;
  1135. }
  1136. #else
  1137. if (ver > WOLFSSL_EXPORT_VERSION_3) {
  1138. exp[idx++] = 0;
  1139. }
  1140. #endif
  1141. #else
  1142. exp[idx++] = 0;
  1143. exp[idx++] = 0;
  1144. exp[idx++] = 0;
  1145. if (ver > WOLFSSL_EXPORT_VERSION_3) {
  1146. exp[idx++] = 0;
  1147. }
  1148. #endif
  1149. exp[idx++] = options->processReply;
  1150. exp[idx++] = options->cipherSuite0;
  1151. exp[idx++] = options->cipherSuite;
  1152. exp[idx++] = options->serverState;
  1153. exp[idx++] = options->clientState;
  1154. exp[idx++] = options->handShakeState;
  1155. exp[idx++] = options->handShakeDone;
  1156. exp[idx++] = options->minDowngrade;
  1157. exp[idx++] = options->connectState;
  1158. exp[idx++] = options->acceptState;
  1159. exp[idx++] = options->asyncState;
  1160. if (type == WOLFSSL_EXPORT_TLS) {
  1161. #ifdef HAVE_ENCRYPT_THEN_MAC
  1162. exp[idx++] = options->disallowEncThenMac;
  1163. exp[idx++] = options->encThenMac;
  1164. exp[idx++] = options->startedETMRead;
  1165. exp[idx++] = options->startedETMWrite;
  1166. #else
  1167. exp[idx++] = 0;
  1168. exp[idx++] = 0;
  1169. exp[idx++] = 0;
  1170. exp[idx++] = 0;
  1171. #endif
  1172. }
  1173. if (ver > WOLFSSL_EXPORT_VERSION_4) {
  1174. #ifdef WOLFSSL_DTLS
  1175. exp[idx++] = options->dtlsStateful;
  1176. #else
  1177. exp[idx++] = 0;
  1178. #endif
  1179. }
  1180. /* version of connection */
  1181. exp[idx++] = ssl->version.major;
  1182. exp[idx++] = ssl->version.minor;
  1183. (void)zero;
  1184. /* check if changes were made and notify of need to update export version */
  1185. switch (ver) {
  1186. case WOLFSSL_EXPORT_VERSION_3:
  1187. if (idx != DTLS_EXPORT_OPT_SZ_3) {
  1188. WOLFSSL_MSG("Update DTLS_EXPORT_OPT_SZ and version of export");
  1189. return DTLS_EXPORT_VER_E;
  1190. }
  1191. break;
  1192. case WOLFSSL_EXPORT_VERSION_4:
  1193. if (idx != DTLS_EXPORT_OPT_SZ_4 && type == WOLFSSL_EXPORT_DTLS) {
  1194. WOLFSSL_MSG("Update DTLS_EXPORT_OPT_SZ and version of export");
  1195. return DTLS_EXPORT_VER_E;
  1196. }
  1197. break;
  1198. case WOLFSSL_EXPORT_VERSION:
  1199. if (idx != DTLS_EXPORT_OPT_SZ && type == WOLFSSL_EXPORT_DTLS) {
  1200. WOLFSSL_MSG("Update DTLS_EXPORT_OPT_SZ and version of export");
  1201. return DTLS_EXPORT_VER_E;
  1202. }
  1203. break;
  1204. default:
  1205. WOLFSSL_MSG("New version case needs added to wolfSSL export");
  1206. return DTLS_EXPORT_VER_E;
  1207. }
  1208. WOLFSSL_LEAVE("ExportOptions", idx);
  1209. (void)type;
  1210. return idx;
  1211. }
  1212. /* copy items from Export struct to Options struct
  1213. * On success returns size of buffer used on failure returns a negative value */
  1214. static int ImportOptions(WOLFSSL* ssl, const byte* exp, word32 len, byte ver,
  1215. int type)
  1216. {
  1217. int idx = 0;
  1218. Options* options = &ssl->options;
  1219. switch (ver) {
  1220. case WOLFSSL_EXPORT_VERSION:
  1221. if (len < DTLS_EXPORT_OPT_SZ) {
  1222. WOLFSSL_MSG("Sanity check on buffer size failed");
  1223. return BAD_FUNC_ARG;
  1224. }
  1225. break;
  1226. case WOLFSSL_EXPORT_VERSION_4:
  1227. if (len < DTLS_EXPORT_OPT_SZ_4) {
  1228. WOLFSSL_MSG("Sanity check on buffer size failed");
  1229. return BAD_FUNC_ARG;
  1230. }
  1231. break;
  1232. case WOLFSSL_EXPORT_VERSION_3:
  1233. if (len < DTLS_EXPORT_OPT_SZ_3) {
  1234. WOLFSSL_MSG("Sanity check on buffer size failed");
  1235. return BAD_FUNC_ARG;
  1236. }
  1237. break;
  1238. default:
  1239. WOLFSSL_MSG("Export version not supported");
  1240. return BAD_FUNC_ARG;
  1241. }
  1242. if (exp == NULL || options == NULL) {
  1243. return BAD_FUNC_ARG;
  1244. }
  1245. /* these options are kept and sent to indicate verify status and strength
  1246. * of handshake */
  1247. options->sendVerify = exp[idx++];
  1248. options->verifyPeer = exp[idx++];
  1249. options->verifyNone = exp[idx++];
  1250. options->downgrade = exp[idx++];
  1251. #ifndef NO_DH
  1252. ato16(exp + idx, &(options->minDhKeySz)); idx += OPAQUE16_LEN;
  1253. ato16(exp + idx, &(options->maxDhKeySz)); idx += OPAQUE16_LEN;
  1254. ato16(exp + idx, &(options->dhKeySz)); idx += OPAQUE16_LEN;
  1255. #else
  1256. idx += OPAQUE16_LEN;
  1257. idx += OPAQUE16_LEN;
  1258. idx += OPAQUE16_LEN;
  1259. #endif
  1260. #ifndef NO_RSA
  1261. ato16(exp + idx, (word16*)&(options->minRsaKeySz)); idx += OPAQUE16_LEN;
  1262. #else
  1263. idx += OPAQUE16_LEN;
  1264. #endif
  1265. #ifdef HAVE_ECC
  1266. ato16(exp + idx, (word16*)&(options->minEccKeySz)); idx += OPAQUE16_LEN;
  1267. #else
  1268. idx += OPAQUE16_LEN;
  1269. #endif
  1270. /* these options are kept to indicate state and behavior */
  1271. #ifndef NO_PSK
  1272. options->havePSK = exp[idx++];
  1273. #else
  1274. idx++;
  1275. #endif
  1276. options->sessionCacheOff = exp[idx++];
  1277. options->sessionCacheFlushOff = exp[idx++];
  1278. options->side = exp[idx++];
  1279. options->resuming = exp[idx++];
  1280. options->haveSessionId = exp[idx++];
  1281. options->tls = exp[idx++];
  1282. options->tls1_1 = exp[idx++];
  1283. options->dtls = exp[idx++];
  1284. options->connReset = exp[idx++];
  1285. options->isClosed = exp[idx++];
  1286. options->closeNotify = exp[idx++];
  1287. options->sentNotify = exp[idx++];
  1288. options->usingCompression = exp[idx++];
  1289. options->haveRSA = exp[idx++];
  1290. options->haveECC = exp[idx++];
  1291. options->haveDH = exp[idx++];
  1292. idx++; /* Historical: haveNTRU */
  1293. idx++; /* Historical: haveQSH */
  1294. options->haveECDSAsig = exp[idx++];
  1295. options->haveStaticECC = exp[idx++];
  1296. options->havePeerVerify = exp[idx++];
  1297. options->usingPSK_cipher = exp[idx++];
  1298. options->usingAnon_cipher = exp[idx++];
  1299. idx++; /* Historical: options->sendAlertState */
  1300. options->partialWrite = exp[idx++];
  1301. options->quietShutdown = exp[idx++];
  1302. options->groupMessages = exp[idx++];
  1303. #ifdef HAVE_POLY1305
  1304. options->oldPoly = exp[idx++]; /* set when to use old rfc way of poly*/
  1305. #else
  1306. idx++;
  1307. #endif
  1308. #ifdef HAVE_ANON
  1309. options->useAnon = exp[idx++]; /* User wants to allow Anon suites */
  1310. #else
  1311. idx++;
  1312. #endif
  1313. #ifdef HAVE_SESSION_TICKET
  1314. options->createTicket = exp[idx++]; /* Server to create new Ticket */
  1315. options->useTicket = exp[idx++]; /* Use Ticket not session cache */
  1316. options->noTicketTls12 = exp[idx++]; /* Server won't create new Ticket */
  1317. #ifdef WOLFSSL_TLS13
  1318. if (ver > WOLFSSL_EXPORT_VERSION_3) {
  1319. options->noTicketTls13 = exp[idx++];/* Server won't create new Ticket */
  1320. }
  1321. #else
  1322. if (ver > WOLFSSL_EXPORT_VERSION_3) {
  1323. idx++;
  1324. }
  1325. #endif
  1326. #else
  1327. idx++;
  1328. idx++;
  1329. idx++;
  1330. if (ver > WOLFSSL_EXPORT_VERSION_3) {
  1331. idx++;
  1332. }
  1333. #endif
  1334. options->processReply = exp[idx++];
  1335. options->cipherSuite0 = exp[idx++];
  1336. options->cipherSuite = exp[idx++];
  1337. options->serverState = exp[idx++];
  1338. options->clientState = exp[idx++];
  1339. options->handShakeState = exp[idx++];
  1340. options->handShakeDone = exp[idx++];
  1341. options->minDowngrade = exp[idx++];
  1342. options->connectState = exp[idx++];
  1343. options->acceptState = exp[idx++];
  1344. options->asyncState = exp[idx++];
  1345. if (type == WOLFSSL_EXPORT_TLS) {
  1346. #ifdef HAVE_ENCRYPT_THEN_MAC
  1347. options->disallowEncThenMac = exp[idx++];
  1348. options->encThenMac = exp[idx++];
  1349. options->startedETMRead = exp[idx++];
  1350. options->startedETMWrite = exp[idx++];
  1351. #else
  1352. idx++;
  1353. idx++;
  1354. idx++;
  1355. idx++;
  1356. #endif
  1357. }
  1358. /* If we had a connection established, let's assume that we can act
  1359. * statefully */
  1360. options->dtlsStateful = 1;
  1361. if (ver > WOLFSSL_EXPORT_VERSION_4) {
  1362. #ifdef WOLFSSL_DTLS
  1363. options->dtlsStateful = exp[idx++];
  1364. #else
  1365. idx++;
  1366. #endif
  1367. }
  1368. /* version of connection */
  1369. if (ssl->version.major != exp[idx++] || ssl->version.minor != exp[idx++]) {
  1370. WOLFSSL_MSG("Version mismatch ie DTLS v1 vs v1.2");
  1371. return VERSION_ERROR;
  1372. }
  1373. /* set TLS 1.3 flag in options if this was a TLS 1.3 connection */
  1374. if (ssl->version.major == SSLv3_MAJOR &&
  1375. ssl->version.minor == TLSv1_3_MINOR) {
  1376. options->tls1_3 = 1;
  1377. }
  1378. return idx;
  1379. }
  1380. #ifndef WOLFSSL_SESSION_EXPORT_NOPEER
  1381. static int ExportPeerInfo(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
  1382. {
  1383. int idx = 0;
  1384. int ipSz = MAX_EXPORT_IP; /* start as max size */
  1385. int fam = 0;
  1386. word16 port = 0;
  1387. char ip[MAX_EXPORT_IP];
  1388. if (ver != WOLFSSL_EXPORT_VERSION) {
  1389. WOLFSSL_MSG("Export version not supported");
  1390. return BAD_FUNC_ARG;
  1391. }
  1392. if (ssl == NULL || exp == NULL ||
  1393. len < (sizeof(ip) + 3 * WOLFSSL_EXPORT_LEN)) {
  1394. return BAD_FUNC_ARG;
  1395. }
  1396. if (ssl->ctx->CBGetPeer == NULL) {
  1397. WOLFSSL_MSG("No get peer call back set");
  1398. return BAD_FUNC_ARG;
  1399. }
  1400. if (ssl->ctx->CBGetPeer(ssl, ip, &ipSz, &port, &fam) != WOLFSSL_SUCCESS) {
  1401. WOLFSSL_MSG("Get peer callback error");
  1402. return SOCKET_ERROR_E;
  1403. }
  1404. /* check that ipSz/fam is not negative or too large since user can set cb */
  1405. if (ipSz < 0 || ipSz > MAX_EXPORT_IP || fam < 0) {
  1406. WOLFSSL_MSG("Bad ipSz or fam returned from get peer callback");
  1407. return SOCKET_ERROR_E;
  1408. }
  1409. c16toa((word16)fam, exp + idx); idx += WOLFSSL_EXPORT_LEN;
  1410. c16toa((word16)ipSz, exp + idx); idx += WOLFSSL_EXPORT_LEN;
  1411. XMEMCPY(exp + idx, ip, ipSz); idx += ipSz;
  1412. c16toa(port, exp + idx); idx += WOLFSSL_EXPORT_LEN;
  1413. return idx;
  1414. }
  1415. #endif /* !WOLFSSL_SESSION_EXPORT_NOPEER */
  1416. static int ImportPeerInfo(WOLFSSL* ssl, const byte* buf, word32 len, byte ver)
  1417. {
  1418. word16 idx = 0;
  1419. word16 ipSz;
  1420. word16 fam;
  1421. word16 port;
  1422. char ip[MAX_EXPORT_IP];
  1423. if (ver != WOLFSSL_EXPORT_VERSION && ver != WOLFSSL_EXPORT_VERSION_4 &&
  1424. ver != WOLFSSL_EXPORT_VERSION_3) {
  1425. WOLFSSL_MSG("Export version not supported");
  1426. return BAD_FUNC_ARG;
  1427. }
  1428. if (len == 0) {
  1429. WOLFSSL_MSG("No peer info sent");
  1430. return 0;
  1431. }
  1432. if (ssl == NULL || buf == NULL || len < 3 * WOLFSSL_EXPORT_LEN) {
  1433. return BAD_FUNC_ARG;
  1434. }
  1435. /* import sin family */
  1436. ato16(buf + idx, &fam); idx += WOLFSSL_EXPORT_LEN;
  1437. /* import ip address idx, and ipSz are unsigned but cast for enum */
  1438. ato16(buf + idx, &ipSz); idx += WOLFSSL_EXPORT_LEN;
  1439. if (ipSz >= sizeof(ip) || (word16)(idx + ipSz + WOLFSSL_EXPORT_LEN) > len) {
  1440. return BUFFER_E;
  1441. }
  1442. XMEMSET(ip, 0, sizeof(ip));
  1443. XMEMCPY(ip, buf + idx, ipSz); idx += ipSz;
  1444. ip[ipSz] = '\0'; /* with check that ipSz less than ip this is valid */
  1445. ato16(buf + idx, &port); idx += WOLFSSL_EXPORT_LEN;
  1446. /* sanity check for a function to call, then use it to import peer info */
  1447. if (ssl->ctx->CBSetPeer == NULL) {
  1448. WOLFSSL_MSG("No set peer function");
  1449. return BAD_FUNC_ARG;
  1450. }
  1451. if (ssl->ctx->CBSetPeer(ssl, ip, ipSz, port, fam) != WOLFSSL_SUCCESS) {
  1452. WOLFSSL_MSG("Error setting peer info");
  1453. return SOCKET_ERROR_E;
  1454. }
  1455. return idx;
  1456. }
  1457. #ifdef WOLFSSL_DTLS
  1458. /* WOLFSSL_LOCAL function that serializes the current WOLFSSL session state only
  1459. * buf is used to hold the serialized WOLFSSL struct and sz is the size of buf
  1460. * passed in.
  1461. * On success returns the size of serialized session state.*/
  1462. int wolfSSL_dtls_export_state_internal(WOLFSSL* ssl, byte* buf, word32 sz)
  1463. {
  1464. int ret;
  1465. word32 idx = 0;
  1466. word32 totalLen = 0;
  1467. WOLFSSL_ENTER("wolfSSL_dtls_export_state_internal");
  1468. if (buf == NULL || ssl == NULL) {
  1469. WOLFSSL_LEAVE("wolfSSL_dtls_export_state_internal", BAD_FUNC_ARG);
  1470. return BAD_FUNC_ARG;
  1471. }
  1472. totalLen += WOLFSSL_EXPORT_LEN * 2; /* 2 protocol bytes and 2 length bytes */
  1473. /* each of the following have a 2 byte length before data */
  1474. totalLen += WOLFSSL_EXPORT_LEN + DTLS_EXPORT_MIN_KEY_SZ;
  1475. if (totalLen > sz) {
  1476. WOLFSSL_LEAVE("wolfSSL_dtls_export_state_internal", BUFFER_E);
  1477. return BUFFER_E;
  1478. }
  1479. buf[idx++] = (byte)DTLS_EXPORT_STATE_PRO;
  1480. buf[idx++] = ((byte)DTLS_EXPORT_STATE_PRO & 0xF0) |
  1481. ((byte)WOLFSSL_EXPORT_VERSION & 0X0F);
  1482. idx += WOLFSSL_EXPORT_LEN; /* leave room for total length */
  1483. /* export keys struct and dtls state -- variable length stored in ret */
  1484. idx += WOLFSSL_EXPORT_LEN; /* leave room for length */
  1485. if ((ret = ExportKeyState(ssl, buf + idx, sz - idx,
  1486. WOLFSSL_EXPORT_VERSION, 1, WOLFSSL_EXPORT_DTLS)) < 0) {
  1487. WOLFSSL_LEAVE("wolfSSL_dtls_export_state_internal", ret);
  1488. return ret;
  1489. }
  1490. c16toa((word16)ret, buf + idx - WOLFSSL_EXPORT_LEN); idx += ret;
  1491. /* place total length of exported buffer minus 2 bytes protocol/version */
  1492. c16toa((word16)(idx - WOLFSSL_EXPORT_LEN), buf + WOLFSSL_EXPORT_LEN);
  1493. #ifdef WOLFSSL_SESSION_EXPORT_DEBUG
  1494. /* if compiled with debug options then print the version, protocol, size */
  1495. {
  1496. char debug[256];
  1497. XSNPRINTF(debug, sizeof(debug), "Exporting DTLS session state\n"
  1498. "\tVersion : %d\n\tProtocol : %02X%01X\n\tLength of: %d\n\n"
  1499. , (int)WOLFSSL_EXPORT_VERSION, buf[0], (buf[1] >> 4), idx - 2);
  1500. WOLFSSL_MSG(debug);
  1501. }
  1502. #endif /* WOLFSSL_SESSION_EXPORT_DEBUG */
  1503. WOLFSSL_LEAVE("wolfSSL_dtls_export_state_internal", idx);
  1504. return idx;
  1505. }
  1506. /* On success return amount of buffer consumed */
  1507. int wolfSSL_dtls_import_state_internal(WOLFSSL* ssl, const byte* buf, word32 sz)
  1508. {
  1509. word32 idx = 0;
  1510. word16 length = 0;
  1511. int version;
  1512. int ret;
  1513. WOLFSSL_ENTER("wolfSSL_dtls_import_state_internal");
  1514. /* check at least enough room for protocol and length */
  1515. if (sz < WOLFSSL_EXPORT_LEN * 2 || ssl == NULL) {
  1516. WOLFSSL_LEAVE("wolfSSL_dtls_import_state_internal", BAD_FUNC_ARG);
  1517. return BAD_FUNC_ARG;
  1518. }
  1519. if (buf[idx++] != (byte)DTLS_EXPORT_STATE_PRO ||
  1520. (buf[idx] & 0xF0) != ((byte)DTLS_EXPORT_PRO & 0xF0)) {
  1521. WOLFSSL_MSG("Incorrect protocol");
  1522. return BAD_FUNC_ARG;
  1523. }
  1524. version = buf[idx++] & 0x0F;
  1525. ato16(buf + idx, &length); idx += WOLFSSL_EXPORT_LEN;
  1526. if (length > sz - WOLFSSL_EXPORT_LEN) { /* subtract 2 for protocol */
  1527. WOLFSSL_MSG("Buffer size sanity check failed");
  1528. return BUFFER_E;
  1529. }
  1530. #ifdef WOLFSSL_SESSION_EXPORT_DEBUG
  1531. /* if compiled with debug options then print the version, protocol, size */
  1532. {
  1533. char debug[256];
  1534. XSNPRINTF(debug, sizeof(debug), "Importing DTLS session state\n"
  1535. "\tVersion : %d\n\tProtocol : %02X%01X\n\tLength of: %d\n\n"
  1536. , (int)version, buf[0], (buf[1] >> 4), length);
  1537. WOLFSSL_MSG(debug);
  1538. }
  1539. #endif /* WOLFSSL_SESSION_EXPORT_DEBUG */
  1540. /* perform sanity checks and extract Options information used */
  1541. switch (version) {
  1542. case WOLFSSL_EXPORT_VERSION:
  1543. break;
  1544. default:
  1545. WOLFSSL_MSG("Bad export state version");
  1546. return BAD_FUNC_ARG;
  1547. }
  1548. /* perform sanity checks and extract Keys struct */
  1549. if (WOLFSSL_EXPORT_LEN + idx > sz) {
  1550. WOLFSSL_MSG("Import Key struct error");
  1551. return BUFFER_E;
  1552. }
  1553. ato16(buf + idx, &length); idx += WOLFSSL_EXPORT_LEN;
  1554. if (length > DTLS_EXPORT_KEY_SZ || length + idx > sz) {
  1555. WOLFSSL_MSG("Import Key struct error");
  1556. return BUFFER_E;
  1557. }
  1558. if ((ret = ImportKeyState(ssl, buf + idx, length, version,
  1559. WOLFSSL_EXPORT_DTLS)) < 0) {
  1560. WOLFSSL_MSG("Import Key struct error");
  1561. WOLFSSL_LEAVE("wolfSSL_dtls_import_state_internal", ret);
  1562. return ret;
  1563. }
  1564. idx += ret;
  1565. WOLFSSL_LEAVE("wolfSSL_dtls_import_state_internal", ret);
  1566. return idx;
  1567. }
  1568. #endif /* WOLFSSL_DTLS */
  1569. /**
  1570. * Imports a serialized buffer (both TLS and DTLS)
  1571. *
  1572. * @param ssl WOLFSSL structure to import into
  1573. * @param buf buffer containing serialized session
  1574. * @param sz size of buffer 'buf'
  1575. * @param type flag for TLS or DTLS
  1576. *
  1577. * @return the size of serialized buffer on success
  1578. */
  1579. int wolfSSL_session_import_internal(WOLFSSL* ssl, const unsigned char* buf,
  1580. unsigned int sz, int type)
  1581. {
  1582. word32 idx = 0;
  1583. word16 length = 0;
  1584. int version = 0;
  1585. int ret = 0;
  1586. int optSz = 0;
  1587. int rc;
  1588. WOLFSSL_ENTER("wolfSSL_session_import_internal");
  1589. /* check at least enough room for protocol and length */
  1590. if (sz < WOLFSSL_EXPORT_LEN * 2 || ssl == NULL) {
  1591. ret = BAD_FUNC_ARG;
  1592. }
  1593. /* Check if is TLS export protocol */
  1594. if (ret == 0) {
  1595. byte validProto = 0; /* did we find a valid protocol */
  1596. if (buf[idx] == (byte)TLS_EXPORT_PRO &&
  1597. (buf[idx + 1] & 0xF0) == ((byte)TLS_EXPORT_PRO & 0xF0)) {
  1598. validProto = 1;
  1599. }
  1600. /* Check if is DTLS export protocol */
  1601. if (buf[idx] == (byte)DTLS_EXPORT_PRO &&
  1602. (buf[idx + 1] & 0xF0) == ((byte)DTLS_EXPORT_PRO & 0xF0)) {
  1603. validProto = 1;
  1604. }
  1605. if (validProto == 0) {
  1606. #ifdef WOLFSSL_DTLS
  1607. /* check if importing state only */
  1608. return wolfSSL_dtls_import_state_internal(ssl, buf, sz);
  1609. #else
  1610. WOLFSSL_MSG("Invalid serialized session protocol value");
  1611. ret = BAD_FUNC_ARG;
  1612. #endif
  1613. }
  1614. idx += 1;
  1615. }
  1616. if (ret == 0) {
  1617. version = buf[idx++] & 0x0F;
  1618. ato16(buf + idx, &length); idx += WOLFSSL_EXPORT_LEN;
  1619. if (length > sz - WOLFSSL_EXPORT_LEN) { /* subtract 2 for protocol */
  1620. ret = BUFFER_E;
  1621. }
  1622. }
  1623. /* if compiled with debug options then print the version, protocol, size */
  1624. #ifdef WOLFSSL_SESSION_EXPORT_DEBUG
  1625. {
  1626. char debug[256];
  1627. XSNPRINTF(debug, sizeof(debug), "Importing DTLS session\n"
  1628. "\tVersion : %d\n\tProtocol : %02X%01X\n\tLength of: %d\n\n"
  1629. , (int)version, buf[0], (buf[1] >> 4), length);
  1630. WOLFSSL_MSG(debug);
  1631. }
  1632. #endif /* WOLFSSL_SESSION_EXPORT_DEBUG */
  1633. /* perform sanity checks and extract Options information used */
  1634. if (ret == 0) {
  1635. switch (version) {
  1636. case WOLFSSL_EXPORT_VERSION:
  1637. if (type == WOLFSSL_EXPORT_DTLS) {
  1638. optSz = DTLS_EXPORT_OPT_SZ;
  1639. }
  1640. else {
  1641. optSz = TLS_EXPORT_OPT_SZ;
  1642. }
  1643. break;
  1644. case WOLFSSL_EXPORT_VERSION_4:
  1645. if (type == WOLFSSL_EXPORT_DTLS) {
  1646. optSz = DTLS_EXPORT_OPT_SZ_4;
  1647. }
  1648. else {
  1649. optSz = TLS_EXPORT_OPT_SZ;
  1650. }
  1651. break;
  1652. case WOLFSSL_EXPORT_VERSION_3:
  1653. WOLFSSL_MSG("Importing older version 3");
  1654. optSz = DTLS_EXPORT_OPT_SZ_3;
  1655. break;
  1656. default:
  1657. WOLFSSL_MSG("Bad export version");
  1658. ret = BAD_FUNC_ARG;
  1659. }
  1660. }
  1661. if (ret == 0 && (WOLFSSL_EXPORT_LEN + optSz + idx > sz)) {
  1662. WOLFSSL_MSG("Import Options struct error");
  1663. ret = BUFFER_E;
  1664. }
  1665. if (ret == 0) {
  1666. ato16(buf + idx, &length); idx += WOLFSSL_EXPORT_LEN;
  1667. if (length != optSz) {
  1668. WOLFSSL_MSG("Import Options struct error");
  1669. ret = BUFFER_E;
  1670. }
  1671. }
  1672. if (ret == 0) {
  1673. rc = ImportOptions(ssl, buf + idx, length, version, type);
  1674. if (rc < 0) {
  1675. WOLFSSL_MSG("Import Options struct error");
  1676. ret = rc;
  1677. }
  1678. else {
  1679. idx += length;
  1680. }
  1681. }
  1682. /* perform sanity checks and extract Keys struct */
  1683. if (ret == 0 && (WOLFSSL_EXPORT_LEN + idx > sz)) {
  1684. WOLFSSL_MSG("Import Key struct error");
  1685. ret = BUFFER_E;
  1686. }
  1687. if (ret == 0) {
  1688. ato16(buf + idx, &length); idx += WOLFSSL_EXPORT_LEN;
  1689. if (length > DTLS_EXPORT_KEY_SZ || length + idx > sz) {
  1690. WOLFSSL_MSG("Import Key struct error");
  1691. ret = BUFFER_E;
  1692. }
  1693. }
  1694. if (ret == 0) {
  1695. rc = ImportKeyState(ssl, buf + idx, length, version, type);
  1696. if (rc < 0) {
  1697. WOLFSSL_MSG("Import Key struct error");
  1698. ret = rc;
  1699. }
  1700. else {
  1701. idx += rc;
  1702. }
  1703. }
  1704. /* perform sanity checks and extract CipherSpecs struct */
  1705. if (ret == 0 && (WOLFSSL_EXPORT_LEN + WOLFSSL_EXPORT_SPC_SZ + idx > sz)) {
  1706. WOLFSSL_MSG("Import CipherSpecs struct error");
  1707. ret = BUFFER_E;
  1708. }
  1709. if (ret == 0) {
  1710. ato16(buf + idx, &length); idx += WOLFSSL_EXPORT_LEN;
  1711. if (length != WOLFSSL_EXPORT_SPC_SZ) {
  1712. WOLFSSL_MSG("Import CipherSpecs struct error");
  1713. ret = BUFFER_E;
  1714. }
  1715. }
  1716. if (ret == 0) {
  1717. rc = ImportCipherSpecState(ssl, buf + idx, length, version, type);
  1718. if (rc < 0) {
  1719. WOLFSSL_MSG("Import CipherSpecs struct error");
  1720. ret = rc;
  1721. }
  1722. else {
  1723. idx += rc;
  1724. }
  1725. }
  1726. /* perform sanity checks and extract DTLS peer info */
  1727. if (ret == 0 && (WOLFSSL_EXPORT_LEN + idx > sz)) {
  1728. WOLFSSL_MSG("Import DTLS peer info error");
  1729. ret = BUFFER_E;
  1730. }
  1731. if (ret == 0) {
  1732. ato16(buf + idx, &length); idx += WOLFSSL_EXPORT_LEN;
  1733. if (idx + length > sz) {
  1734. WOLFSSL_MSG("Import DTLS peer info error");
  1735. ret = BUFFER_E;
  1736. }
  1737. }
  1738. if (ret == 0) {
  1739. rc = ImportPeerInfo(ssl, buf + idx, length, version);
  1740. if (rc < 0) {
  1741. WOLFSSL_MSG("Import Peer Addr error");
  1742. ret = rc;
  1743. }
  1744. else {
  1745. idx += rc;
  1746. }
  1747. }
  1748. /* make sure is a valid suite used */
  1749. if (ret == 0 && wolfSSL_get_cipher(ssl) == NULL) {
  1750. WOLFSSL_MSG("Can not match cipher suite imported");
  1751. ret = MATCH_SUITE_ERROR;
  1752. }
  1753. #ifndef WOLFSSL_AEAD_ONLY
  1754. /* set hmac function to use when verifying */
  1755. if (ret == 0 && (ssl->options.tls == 1 || ssl->options.tls1_1 == 1 ||
  1756. ssl->options.dtls == 1)) {
  1757. #if !defined(WOLFSSL_RENESAS_FSPSM_TLS) && \
  1758. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  1759. ssl->hmac = TLS_hmac;
  1760. #else
  1761. ssl->hmac = Renesas_cmn_TLS_hmac;
  1762. #endif
  1763. }
  1764. /* do not allow stream ciphers with DTLS, except for NULL cipher */
  1765. if (ret == 0 && ssl->specs.cipher_type == stream &&
  1766. ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) {
  1767. WOLFSSL_MSG("Can not import stream ciphers for DTLS");
  1768. ret = SANITY_CIPHER_E;
  1769. }
  1770. #endif /* !WOLFSSL_AEAD_ONLY */
  1771. if (ret != 0) {
  1772. idx = ret;
  1773. }
  1774. WOLFSSL_LEAVE("wolfSSL_session_import_internal", idx);
  1775. return idx;
  1776. }
  1777. /**
  1778. * Handles serializing the session information.
  1779. *
  1780. * @param ssl WOLFSSL structure to serialize session from
  1781. * @param buf output buffer to hold serialized session
  1782. * @param sz the size of buffer 'buf', if too small then gets updated
  1783. * @param type if the input WOLFSSL structure is expected to be TLS or DTLS
  1784. * 1 for yes is TLS and 0 for no is DTLS
  1785. *
  1786. * @return the size of serialized buffer on success and negative values on fail
  1787. */
  1788. int wolfSSL_session_export_internal(WOLFSSL* ssl, byte* buf, word32* sz,
  1789. int type)
  1790. {
  1791. int ret = 0;
  1792. word32 idx = 0;
  1793. word32 totalLen = 0;
  1794. WOLFSSL_ENTER("wolfSSL_session_export_internal");
  1795. if (ssl == NULL) {
  1796. WOLFSSL_MSG("unexpected null argument");
  1797. ret = BAD_FUNC_ARG;
  1798. }
  1799. if (ret == 0) {
  1800. totalLen += WOLFSSL_EXPORT_LEN * 2; /* 2 protocol bytes and 2 length bytes */
  1801. /* each of the following have a 2 byte length before data */
  1802. totalLen += WOLFSSL_EXPORT_LEN + DTLS_EXPORT_OPT_SZ;
  1803. totalLen += WOLFSSL_EXPORT_LEN + DTLS_EXPORT_KEY_SZ;
  1804. totalLen += WOLFSSL_EXPORT_LEN + WOLFSSL_EXPORT_SPC_SZ;
  1805. #ifdef WOLFSSL_DTLS
  1806. if (type == WOLFSSL_EXPORT_DTLS) {
  1807. totalLen += WOLFSSL_EXPORT_LEN + ssl->buffers.dtlsCtx.peer.sz;
  1808. }
  1809. #endif
  1810. }
  1811. /* check is at least the minimum size needed, TLS cipher states add more */
  1812. if (ret == 0 && (totalLen > *sz || buf == NULL)) {
  1813. WOLFSSL_MSG("export buffer was too small or null");
  1814. *sz = totalLen;
  1815. /* possible AES state needed */
  1816. if (type == WOLFSSL_EXPORT_TLS) {
  1817. *sz += AES_BLOCK_SIZE*2;
  1818. }
  1819. ret = WC_NO_ERR_TRACE(LENGTH_ONLY_E);
  1820. }
  1821. if (ret == 0) {
  1822. buf[idx++] = (byte)(type == WOLFSSL_EXPORT_TLS)? TLS_EXPORT_PRO :
  1823. DTLS_EXPORT_PRO;
  1824. buf[idx++] = ((byte)((type == WOLFSSL_EXPORT_TLS)? TLS_EXPORT_PRO :
  1825. DTLS_EXPORT_PRO) & 0xF0)
  1826. | ((byte)WOLFSSL_EXPORT_VERSION & 0X0F);
  1827. idx += WOLFSSL_EXPORT_LEN; /* leave spot for length of total buffer */
  1828. idx += WOLFSSL_EXPORT_LEN;
  1829. ret = ExportOptions(ssl, buf + idx, *sz - idx, WOLFSSL_EXPORT_VERSION,
  1830. type);
  1831. if (ret >= 0) {
  1832. c16toa((word16)ret, buf + idx - WOLFSSL_EXPORT_LEN);
  1833. idx += ret;
  1834. ret = 0;
  1835. }
  1836. }
  1837. /* export keys struct and dtls state -- variable length stored in ret */
  1838. if (ret == 0) {
  1839. idx += WOLFSSL_EXPORT_LEN; /* leave room for length */
  1840. ret = ExportKeyState(ssl, buf + idx, *sz - idx, WOLFSSL_EXPORT_VERSION,
  1841. 0, type);
  1842. if (ret >= 0) {
  1843. c16toa((word16)ret, buf + idx - WOLFSSL_EXPORT_LEN); idx += ret;
  1844. ret = 0;
  1845. }
  1846. }
  1847. /* export of cipher specs struct */
  1848. if (ret == 0) {
  1849. c16toa((word16)WOLFSSL_EXPORT_SPC_SZ, buf + idx);
  1850. idx += WOLFSSL_EXPORT_LEN;
  1851. ret = ExportCipherSpecState(ssl, buf + idx, *sz - idx,
  1852. WOLFSSL_EXPORT_VERSION, type);
  1853. if (ret >= 0) {
  1854. idx += ret;
  1855. ret = 0;
  1856. }
  1857. }
  1858. /* export of peer information */
  1859. if (ret == 0) {
  1860. idx += WOLFSSL_EXPORT_LEN;
  1861. #ifdef WOLFSSL_SESSION_EXPORT_NOPEER
  1862. ret = 0; /* not saving peer port/ip information */
  1863. #else
  1864. ret = ExportPeerInfo(ssl, buf + idx, *sz - idx, WOLFSSL_EXPORT_VERSION);
  1865. #endif
  1866. if (ret >= 0) {
  1867. c16toa(ret, buf + idx - WOLFSSL_EXPORT_LEN);
  1868. idx += ret;
  1869. ret = 0;
  1870. }
  1871. }
  1872. if (ret != 0 && ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E) && buf != NULL) {
  1873. /*in a fail case clear the buffer which could contain partial key info*/
  1874. XMEMSET(buf, 0, *sz);
  1875. }
  1876. /* place total length of exported buffer minus 2 bytes protocol/version */
  1877. if (ret == 0) {
  1878. c16toa((word16)(idx - WOLFSSL_EXPORT_LEN), buf + WOLFSSL_EXPORT_LEN);
  1879. ret = idx;
  1880. #ifdef WOLFSSL_SESSION_EXPORT_DEBUG
  1881. {
  1882. char debug[256];
  1883. XSNPRINTF(debug, sizeof(debug), "Exporting TLS session\n"
  1884. "\tVersion : %d\n\tProtocol : %02X%01X\n\tLength of: %d\n\n"
  1885. ,(int)WOLFSSL_EXPORT_VERSION, buf[0], (buf[1] >> 4), idx - 2);
  1886. WOLFSSL_MSG(debug);
  1887. }
  1888. #endif /* WOLFSSL_SESSION_EXPORT_DEBUG */
  1889. }
  1890. if (ret >= 0) {
  1891. *sz = ret;
  1892. }
  1893. WOLFSSL_LEAVE("wolfSSL_session_export_internal", ret);
  1894. return ret;
  1895. }
  1896. #endif /* WOLFSSL_SESSION_EXPORT */
  1897. void InitSSL_Method(WOLFSSL_METHOD* method, ProtocolVersion pv)
  1898. {
  1899. method->version = pv;
  1900. method->side = WOLFSSL_CLIENT_END;
  1901. method->downgrade = 0;
  1902. }
  1903. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE) || \
  1904. defined(WOLFSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  1905. int InitSSL_Side(WOLFSSL* ssl, word16 side)
  1906. {
  1907. if (ssl == NULL)
  1908. return BAD_FUNC_ARG;
  1909. /* set side */
  1910. ssl->options.side = side;
  1911. /* reset options that are side specific */
  1912. #ifdef HAVE_ECC
  1913. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  1914. ssl->options.haveECDSAsig = 1; /* always on client side */
  1915. ssl->options.haveECC = 1; /* server turns on with ECC key cert */
  1916. ssl->options.haveStaticECC = 1; /* server can turn on by loading key */
  1917. }
  1918. #elif defined(HAVE_ED25519) || defined(HAVE_ED448)
  1919. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  1920. ssl->options.haveECDSAsig = 1; /* always on client side */
  1921. ssl->options.haveECC = 1; /* server turns on with ECC key cert */
  1922. }
  1923. #endif
  1924. #ifdef HAVE_FALCON
  1925. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  1926. ssl->options.haveFalconSig = 1; /* always on client side */
  1927. }
  1928. #endif /* HAVE_FALCON */
  1929. #ifdef HAVE_DILITHIUM
  1930. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  1931. ssl->options.haveDilithiumSig = 1; /* always on client side */
  1932. }
  1933. #endif /* HAVE_DILITHIUM */
  1934. #if defined(HAVE_EXTENDED_MASTER) && !defined(NO_WOLFSSL_CLIENT)
  1935. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  1936. if ((ssl->ctx->method->version.major == SSLv3_MAJOR) &&
  1937. (ssl->ctx->method->version.minor >= TLSv1_MINOR)) {
  1938. ssl->options.haveEMS = 1;
  1939. }
  1940. #ifdef WOLFSSL_DTLS
  1941. if (ssl->ctx->method->version.major == DTLS_MAJOR)
  1942. ssl->options.haveEMS = 1;
  1943. #endif /* WOLFSSL_DTLS */
  1944. }
  1945. #endif /* HAVE_EXTENDED_MASTER && !NO_WOLFSSL_CLIENT */
  1946. #if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
  1947. if (ssl->options.dtls && ssl->options.side == WOLFSSL_SERVER_END) {
  1948. int ret;
  1949. ret = wolfSSL_DTLS_SetCookieSecret(ssl, NULL, 0);
  1950. if (ret != 0) {
  1951. WOLFSSL_MSG("DTLS Cookie Secret error");
  1952. return ret;
  1953. }
  1954. }
  1955. #endif /* WOLFSSL_DTLS && !NO_WOLFSSL_SERVER */
  1956. return InitSSL_Suites(ssl);
  1957. }
  1958. #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
  1959. /* Initialize SSL context, return 0 on success */
  1960. int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap)
  1961. {
  1962. int ret = 0;
  1963. XMEMSET(ctx, 0, sizeof(WOLFSSL_CTX));
  1964. ctx->method = method;
  1965. if (heap == NULL) {
  1966. ctx->heap = ctx; /* defaults to self */
  1967. }
  1968. else {
  1969. ctx->heap = heap; /* wolfSSL_CTX_load_static_memory sets */
  1970. }
  1971. ctx->timeout = WOLFSSL_SESSION_TIMEOUT;
  1972. #ifdef WOLFSSL_DTLS
  1973. if (method->version.major == DTLS_MAJOR) {
  1974. ctx->minDowngrade = WOLFSSL_MIN_DTLS_DOWNGRADE;
  1975. }
  1976. else
  1977. #endif /* WOLFSSL_DTLS */
  1978. {
  1979. /* current default: TLSv1_MINOR */
  1980. ctx->minDowngrade = WOLFSSL_MIN_DOWNGRADE;
  1981. }
  1982. wolfSSL_RefInit(&ctx->ref, &ret);
  1983. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  1984. if (ret < 0) {
  1985. WOLFSSL_MSG("Mutex error on CTX init");
  1986. ctx->err = CTX_INIT_MUTEX_E;
  1987. WOLFSSL_ERROR_VERBOSE(BAD_MUTEX_E);
  1988. return BAD_MUTEX_E;
  1989. }
  1990. #else
  1991. (void)ret;
  1992. #endif
  1993. #ifndef NO_CERTS
  1994. ctx->privateKeyDevId = INVALID_DEVID;
  1995. #ifdef WOLFSSL_DUAL_ALG_CERTS
  1996. ctx->altPrivateKeyDevId = INVALID_DEVID;
  1997. #endif
  1998. #endif
  1999. #ifndef NO_DH
  2000. ctx->minDhKeySz = MIN_DHKEY_SZ;
  2001. ctx->maxDhKeySz = MAX_DHKEY_SZ;
  2002. #endif
  2003. #ifndef NO_RSA
  2004. ctx->minRsaKeySz = MIN_RSAKEY_SZ;
  2005. #endif
  2006. #ifdef HAVE_ECC
  2007. ctx->minEccKeySz = MIN_ECCKEY_SZ;
  2008. ctx->eccTempKeySz = ECDHE_SIZE;
  2009. #endif
  2010. #ifdef HAVE_FALCON
  2011. ctx->minFalconKeySz = MIN_FALCONKEY_SZ;
  2012. #endif /* HAVE_FALCON */
  2013. #ifdef HAVE_DILITHIUM
  2014. ctx->minDilithiumKeySz = MIN_DILITHIUMKEY_SZ;
  2015. #endif /* HAVE_DILITHIUM */
  2016. ctx->verifyDepth = MAX_CHAIN_DEPTH;
  2017. #ifdef OPENSSL_EXTRA
  2018. ctx->cbioFlag = WOLFSSL_CBIO_NONE;
  2019. #endif
  2020. #ifdef HAVE_NETX
  2021. ctx->CBIORecv = NetX_Receive;
  2022. ctx->CBIOSend = NetX_Send;
  2023. #elif defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
  2024. ctx->CBIORecv = Mynewt_Receive;
  2025. ctx->CBIOSend = Mynewt_Send;
  2026. #elif defined WOLFSSL_LWIP_NATIVE
  2027. ctx->CBIORecv = LwIPNativeReceive;
  2028. ctx->CBIOSend = LwIPNativeSend;
  2029. #elif defined(WOLFSSL_GNRC)
  2030. ctx->CBIORecv = GNRC_ReceiveFrom;
  2031. ctx->CBIOSend = GNRC_SendTo;
  2032. #elif defined WOLFSSL_ISOTP
  2033. ctx->CBIORecv = ISOTP_Receive;
  2034. ctx->CBIOSend = ISOTP_Send;
  2035. #elif !defined(WOLFSSL_USER_IO)
  2036. #ifdef MICRIUM
  2037. ctx->CBIORecv = MicriumReceive;
  2038. ctx->CBIOSend = MicriumSend;
  2039. #ifdef WOLFSSL_DTLS
  2040. if (method->version.major == DTLS_MAJOR) {
  2041. ctx->CBIORecv = MicriumReceiveFrom;
  2042. ctx->CBIOSend = MicriumSendTo;
  2043. }
  2044. #ifdef WOLFSSL_SESSION_EXPORT
  2045. #error Micrium port does not support DTLS session export yet
  2046. #endif
  2047. #endif
  2048. #elif defined WOLFSSL_UIP
  2049. ctx->CBIORecv = uIPReceive;
  2050. ctx->CBIOSend = uIPSend;
  2051. #ifdef WOLFSSL_DTLS
  2052. if (method->version.major == DTLS_MAJOR) {
  2053. ctx->CBIOSendTo = uIPSendTo;
  2054. ctx->CBIORecvFrom = uIPRecvFrom;
  2055. }
  2056. #endif
  2057. #else
  2058. ctx->CBIORecv = EmbedReceive;
  2059. ctx->CBIOSend = EmbedSend;
  2060. #ifdef WOLFSSL_SESSION_EXPORT
  2061. ctx->CBGetPeer = EmbedGetPeer;
  2062. ctx->CBSetPeer = EmbedSetPeer;
  2063. #endif
  2064. #ifdef WOLFSSL_DTLS
  2065. if (method->version.major == DTLS_MAJOR) {
  2066. ctx->CBIORecv = EmbedReceiveFrom;
  2067. ctx->CBIOSend = EmbedSendTo;
  2068. }
  2069. #endif
  2070. #endif /* MICRIUM */
  2071. #endif /* WOLFSSL_USER_IO */
  2072. #if defined(HAVE_RPK)
  2073. wolfSSL_CTX_set_client_cert_type(ctx, NULL, 0); /* set to default */
  2074. wolfSSL_CTX_set_server_cert_type(ctx, NULL, 0); /* set to default */
  2075. #endif /* HAVE_RPK */
  2076. #ifdef HAVE_FALCON
  2077. if (method->side == WOLFSSL_CLIENT_END)
  2078. ctx->haveFalconSig = 1; /* always on client side */
  2079. /* server can turn on by loading key */
  2080. #endif /* HAVE_FALCON */
  2081. #ifdef HAVE_DILITHIUM
  2082. if (method->side == WOLFSSL_CLIENT_END)
  2083. ctx->haveDilithiumSig = 1; /* always on client side */
  2084. /* server can turn on by loading key */
  2085. #endif /* HAVE_DILITHIUM */
  2086. #ifdef HAVE_ECC
  2087. if (method->side == WOLFSSL_CLIENT_END) {
  2088. ctx->haveECDSAsig = 1; /* always on client side */
  2089. ctx->haveECC = 1; /* server turns on with ECC key cert */
  2090. ctx->haveStaticECC = 1; /* server can turn on by loading key */
  2091. }
  2092. #elif defined(HAVE_ED25519) || defined(HAVE_ED448)
  2093. if (method->side == WOLFSSL_CLIENT_END) {
  2094. ctx->haveECDSAsig = 1; /* always on client side */
  2095. ctx->haveECC = 1; /* server turns on with ECC key cert */
  2096. }
  2097. #endif
  2098. #ifdef WOLFSSL_QNX_CAAM
  2099. /* default to try using CAAM when built */
  2100. ctx->devId = WOLFSSL_CAAM_DEVID;
  2101. #elif defined(HAVE_ARIA) && defined(WOLF_CRYPTO_CB)
  2102. ctx->devId = WOLFSSL_ARIA_DEVID;
  2103. #else
  2104. ctx->devId = INVALID_DEVID;
  2105. #endif
  2106. #if defined(WOLFSSL_DTLS)
  2107. #ifdef WOLFSSL_SCTP
  2108. ctx->dtlsMtuSz = MAX_RECORD_SIZE;
  2109. #elif defined(WOLFSSL_DTLS_MTU)
  2110. ctx->dtlsMtuSz = MAX_MTU;
  2111. #endif
  2112. #endif
  2113. #ifndef NO_CERTS
  2114. ctx->cm = wolfSSL_CertManagerNew_ex(heap);
  2115. if (ctx->cm == NULL) {
  2116. WOLFSSL_MSG("Bad Cert Manager New");
  2117. WOLFSSL_ERROR_VERBOSE(BAD_CERT_MANAGER_ERROR);
  2118. return BAD_CERT_MANAGER_ERROR;
  2119. }
  2120. #ifdef OPENSSL_EXTRA
  2121. /* setup WOLFSSL_X509_STORE */
  2122. ctx->x509_store.cm = ctx->cm;
  2123. /* set pointer back to x509 store */
  2124. ctx->cm->x509_store_p = &ctx->x509_store;
  2125. /* WOLFSSL_X509_VERIFY_PARAM */
  2126. if ((ctx->param = (WOLFSSL_X509_VERIFY_PARAM*)XMALLOC(
  2127. sizeof(WOLFSSL_X509_VERIFY_PARAM),
  2128. heap, DYNAMIC_TYPE_OPENSSL)) == NULL) {
  2129. WOLFSSL_MSG("ctx->param memory error");
  2130. return MEMORY_E;
  2131. }
  2132. XMEMSET(ctx->param, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM));
  2133. /* WOLFSSL_X509_LOOKUP */
  2134. if ((ctx->x509_store.lookup.dirs = (WOLFSSL_BY_DIR*)XMALLOC(
  2135. sizeof(WOLFSSL_BY_DIR),
  2136. heap, DYNAMIC_TYPE_OPENSSL)) == NULL) {
  2137. WOLFSSL_MSG("ctx->x509_store.lookup.dirs: allocation error");
  2138. return MEMORY_E;
  2139. }
  2140. XMEMSET(ctx->x509_store.lookup.dirs, 0, sizeof(WOLFSSL_BY_DIR));
  2141. /* param */
  2142. if ((ctx->x509_store.param = (WOLFSSL_X509_VERIFY_PARAM*)XMALLOC(
  2143. sizeof(WOLFSSL_X509_VERIFY_PARAM),
  2144. heap, DYNAMIC_TYPE_OPENSSL)) == NULL) {
  2145. WOLFSSL_MSG("ctx->x509_store.param: allocation error");
  2146. return MEMORY_E;
  2147. }
  2148. XMEMSET(ctx->x509_store.param, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM));
  2149. if (wc_InitMutex(&ctx->x509_store.lookup.dirs->lock) != 0) {
  2150. WOLFSSL_MSG("Bad mutex init");
  2151. WOLFSSL_ERROR_VERBOSE(BAD_MUTEX_E);
  2152. return BAD_MUTEX_E;
  2153. }
  2154. #endif
  2155. #endif
  2156. #if defined(HAVE_EXTENDED_MASTER) && !defined(NO_WOLFSSL_CLIENT)
  2157. if (method->side == WOLFSSL_CLIENT_END) {
  2158. if ((method->version.major == SSLv3_MAJOR) &&
  2159. (method->version.minor >= TLSv1_MINOR)) {
  2160. ctx->haveEMS = 1;
  2161. }
  2162. #ifdef WOLFSSL_DTLS
  2163. if (method->version.major == DTLS_MAJOR)
  2164. ctx->haveEMS = 1;
  2165. #endif /* WOLFSSL_DTLS */
  2166. }
  2167. #endif /* HAVE_EXTENDED_MASTER && !NO_WOLFSSL_CLIENT */
  2168. #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
  2169. #ifndef WOLFSSL_NO_DEF_TICKET_ENC_CB
  2170. ret = TicketEncCbCtx_Init(ctx, &ctx->ticketKeyCtx);
  2171. if (ret != 0) return ret;
  2172. ctx->ticketEncCb = DefTicketEncCb;
  2173. ctx->ticketEncCtx = (void*)&ctx->ticketKeyCtx;
  2174. #endif
  2175. ctx->ticketHint = SESSION_TICKET_HINT_DEFAULT;
  2176. #if defined(WOLFSSL_TLS13)
  2177. ctx->maxTicketTls13 = 1; /* default to sending a session ticket if compiled
  2178. in */
  2179. #endif
  2180. #endif
  2181. #ifdef WOLFSSL_EARLY_DATA
  2182. ctx->maxEarlyDataSz = MAX_EARLY_DATA_SZ;
  2183. #endif
  2184. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  2185. #if defined(WOLFSSL_TLS13) && !defined(HAVE_SUPPORTED_CURVES)
  2186. ctx->noPskDheKe = 1;
  2187. #endif
  2188. #endif
  2189. #if defined(WOLFSSL_QT) && !defined(NO_PSK)
  2190. /* Qt retrieves supported cipher list at initialization
  2191. * from get_cipher_compat().
  2192. * Qt doesn't allow to use a cipher if it is not in the supported list.
  2193. * Therefore, we need to enable PSK cipher at the beginning.
  2194. */
  2195. ctx->havePSK = 1;
  2196. #endif
  2197. ctx->heap = heap; /* wolfSSL_CTX_load_static_memory sets */
  2198. #ifdef HAVE_WOLF_EVENT
  2199. ret = wolfEventQueue_Init(&ctx->event_queue);
  2200. #endif /* HAVE_WOLF_EVENT */
  2201. #ifdef WOLFSSL_MAXQ10XX_TLS
  2202. /* Let maxq10xx know what TLS version we are using. */
  2203. ctx->devId = MAXQ_DEVICE_ID;
  2204. maxq10xx_SetupPkCallbacks(ctx, &method->version);
  2205. #endif /* WOLFSSL_MAXQ10XX_TLS */
  2206. #if defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS)
  2207. /* Should only be set when wolfSSL_CTX_load_system_CA_certs() is called */
  2208. ctx->doAppleNativeCertValidationFlag = 0;
  2209. #endif /* defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS) */
  2210. return ret;
  2211. }
  2212. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  2213. void wolfSSL_CRYPTO_cleanup_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data)
  2214. {
  2215. int n_ex_data = (int)(sizeof ex_data->ex_data / sizeof ex_data->ex_data[0]);
  2216. for (--n_ex_data; n_ex_data >= 0; --n_ex_data) {
  2217. if (ex_data->ex_data[n_ex_data] != NULL)
  2218. (void)wolfSSL_CRYPTO_set_ex_data_with_cleanup(ex_data, n_ex_data,
  2219. NULL, NULL);
  2220. }
  2221. }
  2222. #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
  2223. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  2224. /* free all ech configs in the list */
  2225. void FreeEchConfigs(WOLFSSL_EchConfig* configs, void* heap)
  2226. {
  2227. WOLFSSL_EchConfig* working_config = configs;
  2228. WOLFSSL_EchConfig* next_config;
  2229. while (working_config != NULL) {
  2230. next_config = working_config->next;
  2231. XFREE(working_config->cipherSuites, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2232. XFREE(working_config->publicName, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2233. XFREE(working_config->raw, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2234. if (working_config->receiverPrivkey != NULL) {
  2235. wc_HpkeFreeKey(NULL, working_config->kemId,
  2236. working_config->receiverPrivkey, heap);
  2237. }
  2238. XFREE(working_config, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2239. working_config = next_config;
  2240. }
  2241. (void)heap;
  2242. }
  2243. #endif
  2244. /* In case contexts are held in array and don't want to free actual ctx. */
  2245. /* The allocations done in InitSSL_Ctx must be free'd with ctx->onHeapHint
  2246. * logic. A WOLFSSL_CTX can be assigned a static memory heap hint using
  2247. * wolfSSL_CTX_load_static_memory after CTX creation, which means variables
  2248. * allocated in InitSSL_Ctx were allocated from heap and should be free'd with
  2249. * a NULL heap hint. */
  2250. void SSL_CtxResourceFree(WOLFSSL_CTX* ctx)
  2251. {
  2252. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) && \
  2253. defined(HAVE_TLS_EXTENSIONS) && !defined(NO_WOLFSSL_SERVER)
  2254. int i;
  2255. #endif
  2256. void* heapAtCTXInit = ctx->heap;
  2257. #ifdef WOLFSSL_STATIC_MEMORY
  2258. if (ctx->onHeapHint == 0) {
  2259. heapAtCTXInit = NULL;
  2260. }
  2261. #endif
  2262. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  2263. wolfSSL_CRYPTO_cleanup_ex_data(&ctx->ex_data);
  2264. #endif
  2265. #ifdef HAVE_WOLF_EVENT
  2266. wolfEventQueue_Free(&ctx->event_queue);
  2267. #endif /* HAVE_WOLF_EVENT */
  2268. XFREE(ctx->method, heapAtCTXInit, DYNAMIC_TYPE_METHOD);
  2269. ctx->method = NULL;
  2270. XFREE(ctx->suites, ctx->heap, DYNAMIC_TYPE_SUITES);
  2271. ctx->suites = NULL;
  2272. #ifndef NO_DH
  2273. XFREE(ctx->serverDH_G.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  2274. ctx->serverDH_G.buffer = NULL;
  2275. XFREE(ctx->serverDH_P.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  2276. ctx->serverDH_P.buffer = NULL;
  2277. #endif /* !NO_DH */
  2278. #ifdef SINGLE_THREADED
  2279. if (ctx->rng) {
  2280. wc_FreeRng(ctx->rng);
  2281. XFREE(ctx->rng, ctx->heap, DYNAMIC_TYPE_RNG);
  2282. ctx->rng = NULL;
  2283. }
  2284. #endif /* SINGLE_THREADED */
  2285. #ifndef NO_CERTS
  2286. if (ctx->privateKey != NULL && ctx->privateKey->buffer != NULL) {
  2287. ForceZero(ctx->privateKey->buffer, ctx->privateKey->length);
  2288. }
  2289. FreeDer(&ctx->privateKey);
  2290. #ifdef WOLFSSL_BLIND_PRIVATE_KEY
  2291. FreeDer(&ctx->privateKeyMask);
  2292. #endif
  2293. #ifdef WOLFSSL_DUAL_ALG_CERTS
  2294. if (ctx->altPrivateKey != NULL && ctx->altPrivateKey->buffer != NULL) {
  2295. ForceZero(ctx->altPrivateKey->buffer, ctx->altPrivateKey->length);
  2296. }
  2297. FreeDer(&ctx->altPrivateKey);
  2298. #ifdef WOLFSSL_BLIND_PRIVATE_KEY
  2299. FreeDer(&ctx->altPrivateKeyMask);
  2300. #endif
  2301. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  2302. #ifdef OPENSSL_ALL
  2303. wolfSSL_EVP_PKEY_free(ctx->privateKeyPKey);
  2304. #endif
  2305. FreeDer(&ctx->certificate);
  2306. #ifdef KEEP_OUR_CERT
  2307. if (ctx->ourCert && ctx->ownOurCert) {
  2308. wolfSSL_X509_free(ctx->ourCert);
  2309. ctx->ourCert = NULL;
  2310. }
  2311. #endif /* KEEP_OUR_CERT */
  2312. FreeDer(&ctx->certChain);
  2313. wolfSSL_CertManagerFree(ctx->cm);
  2314. ctx->cm = NULL;
  2315. #ifdef OPENSSL_ALL
  2316. if (ctx->x509_store.objs != NULL) {
  2317. wolfSSL_sk_X509_OBJECT_pop_free(ctx->x509_store.objs, NULL);
  2318. ctx->x509_store.objs = NULL;
  2319. }
  2320. #endif
  2321. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
  2322. defined(WOLFSSL_WPAS_SMALL)
  2323. wolfSSL_X509_STORE_free(ctx->x509_store_pt);
  2324. #endif
  2325. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || defined(HAVE_LIGHTY)
  2326. wolfSSL_sk_X509_NAME_pop_free(ctx->client_ca_names, NULL);
  2327. ctx->client_ca_names = NULL;
  2328. #endif
  2329. #ifdef OPENSSL_EXTRA
  2330. if (ctx->x509Chain) {
  2331. wolfSSL_sk_X509_pop_free(ctx->x509Chain, NULL);
  2332. ctx->x509Chain = NULL;
  2333. }
  2334. #endif
  2335. #endif /* !NO_CERTS */
  2336. #ifdef HAVE_TLS_EXTENSIONS
  2337. #if !defined(NO_TLS)
  2338. TLSX_FreeAll(ctx->extensions, ctx->heap);
  2339. #endif /* !NO_TLS */
  2340. #ifndef NO_WOLFSSL_SERVER
  2341. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  2342. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  2343. if (ctx->certOcspRequest) {
  2344. FreeOcspRequest(ctx->certOcspRequest);
  2345. XFREE(ctx->certOcspRequest, ctx->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  2346. }
  2347. #endif
  2348. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  2349. for (i = 0; i < MAX_CHAIN_DEPTH; i++) {
  2350. if (ctx->chainOcspRequest[i]) {
  2351. FreeOcspRequest(ctx->chainOcspRequest[i]);
  2352. XFREE(ctx->chainOcspRequest[i], ctx->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  2353. ctx->chainOcspRequest[i] = NULL;
  2354. }
  2355. }
  2356. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  2357. #endif /* !NO_WOLFSSL_SERVER */
  2358. #endif /* HAVE_TLS_EXTENSIONS */
  2359. #ifdef OPENSSL_EXTRA
  2360. if (ctx->alpn_cli_protos) {
  2361. XFREE((void*)ctx->alpn_cli_protos, ctx->heap, DYNAMIC_TYPE_OPENSSL);
  2362. ctx->alpn_cli_protos = NULL;
  2363. }
  2364. XFREE(ctx->param, heapAtCTXInit, DYNAMIC_TYPE_OPENSSL);
  2365. ctx->param = NULL;
  2366. if (ctx->x509_store.param) {
  2367. XFREE(ctx->x509_store.param, heapAtCTXInit, DYNAMIC_TYPE_OPENSSL);
  2368. ctx->x509_store.param = NULL;
  2369. }
  2370. if (ctx->x509_store.lookup.dirs) {
  2371. #if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR)
  2372. if (ctx->x509_store.lookup.dirs->dir_entry) {
  2373. wolfSSL_sk_BY_DIR_entry_free(ctx->x509_store.lookup.dirs->dir_entry);
  2374. }
  2375. #endif
  2376. wc_FreeMutex(&ctx->x509_store.lookup.dirs->lock);
  2377. XFREE(ctx->x509_store.lookup.dirs, heapAtCTXInit, DYNAMIC_TYPE_OPENSSL);
  2378. }
  2379. #endif
  2380. #ifdef WOLFSSL_STATIC_EPHEMERAL
  2381. #ifndef NO_DH
  2382. FreeDer(&ctx->staticKE.dhKey);
  2383. #endif
  2384. #ifdef HAVE_ECC
  2385. FreeDer(&ctx->staticKE.ecKey);
  2386. #endif
  2387. #ifdef HAVE_CURVE25519
  2388. FreeDer(&ctx->staticKE.x25519Key);
  2389. #endif
  2390. #ifdef HAVE_CURVE448
  2391. FreeDer(&ctx->staticKE.x448Key);
  2392. #endif
  2393. #ifndef SINGLE_THREADED
  2394. if (ctx->staticKELockInit) {
  2395. wc_FreeMutex(&ctx->staticKELock);
  2396. ctx->staticKELockInit = 0;
  2397. }
  2398. #endif
  2399. #endif
  2400. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  2401. FreeEchConfigs(ctx->echConfigs, ctx->heap);
  2402. ctx->echConfigs = NULL;
  2403. #endif
  2404. (void)heapAtCTXInit;
  2405. }
  2406. #ifdef WOLFSSL_STATIC_MEMORY
  2407. static void SSL_CtxResourceFreeStaticMem(void* heap)
  2408. {
  2409. #ifndef SINGLE_THREADED
  2410. if (heap != NULL
  2411. #ifdef WOLFSSL_HEAP_TEST
  2412. /* avoid dereferencing a test value */
  2413. && heap != (void*)WOLFSSL_HEAP_TEST
  2414. #endif
  2415. ) {
  2416. WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)heap;
  2417. WOLFSSL_HEAP* mem = hint->memory;
  2418. wc_FreeMutex(&mem->memory_mutex);
  2419. }
  2420. #else
  2421. (void)heap;
  2422. #endif
  2423. }
  2424. #endif /* WOLFSSL_STATIC_MEMORY */
  2425. void FreeSSL_Ctx(WOLFSSL_CTX* ctx)
  2426. {
  2427. int isZero;
  2428. int ret;
  2429. void* heap = ctx->heap;
  2430. #ifdef WOLFSSL_STATIC_MEMORY
  2431. if (ctx->onHeapHint == 0) {
  2432. heap = NULL;
  2433. }
  2434. #endif
  2435. /* decrement CTX reference count */
  2436. wolfSSL_RefDec(&ctx->ref, &isZero, &ret);
  2437. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  2438. if (ret < 0) {
  2439. /* check error state, if mutex error code then mutex init failed but
  2440. * CTX was still malloc'd */
  2441. if (ctx->err == WC_NO_ERR_TRACE(CTX_INIT_MUTEX_E)) {
  2442. SSL_CtxResourceFree(ctx);
  2443. XFREE(ctx, heap, DYNAMIC_TYPE_CTX);
  2444. #ifdef WOLFSSL_STATIC_MEMORY
  2445. SSL_CtxResourceFreeStaticMem(heap);
  2446. #endif
  2447. }
  2448. return;
  2449. }
  2450. #else
  2451. (void)ret;
  2452. #endif
  2453. if (isZero) {
  2454. WOLFSSL_MSG("CTX ref count down to 0, doing full free");
  2455. SSL_CtxResourceFree(ctx);
  2456. #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER) && \
  2457. !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB)
  2458. TicketEncCbCtx_Free(&ctx->ticketKeyCtx);
  2459. #endif
  2460. wolfSSL_RefFree(&ctx->ref);
  2461. XFREE(ctx, heap, DYNAMIC_TYPE_CTX);
  2462. #ifdef WOLFSSL_STATIC_MEMORY
  2463. SSL_CtxResourceFreeStaticMem(heap);
  2464. #endif
  2465. }
  2466. else {
  2467. WOLFSSL_MSG("CTX ref count not 0 yet, no free");
  2468. }
  2469. (void)heap; /* not used in some builds */
  2470. }
  2471. /* Set cipher pointers to null */
  2472. void InitCiphers(WOLFSSL* ssl)
  2473. {
  2474. #ifdef BUILD_ARC4
  2475. ssl->encrypt.arc4 = NULL;
  2476. ssl->decrypt.arc4 = NULL;
  2477. #endif
  2478. #ifdef BUILD_DES3
  2479. ssl->encrypt.des3 = NULL;
  2480. ssl->decrypt.des3 = NULL;
  2481. #endif
  2482. #ifdef BUILD_AES
  2483. ssl->encrypt.aes = NULL;
  2484. ssl->decrypt.aes = NULL;
  2485. #endif
  2486. #ifdef HAVE_ARIA
  2487. ssl->encrypt.aria = NULL;
  2488. ssl->decrypt.aria = NULL;
  2489. #endif
  2490. #ifdef HAVE_CAMELLIA
  2491. ssl->encrypt.cam = NULL;
  2492. ssl->decrypt.cam = NULL;
  2493. #endif
  2494. #ifdef HAVE_CHACHA
  2495. ssl->encrypt.chacha = NULL;
  2496. ssl->decrypt.chacha = NULL;
  2497. #endif
  2498. #if defined(HAVE_POLY1305) && defined(HAVE_ONE_TIME_AUTH)
  2499. ssl->auth.poly1305 = NULL;
  2500. #endif
  2501. ssl->encrypt.setup = 0;
  2502. ssl->decrypt.setup = 0;
  2503. #ifdef HAVE_ONE_TIME_AUTH
  2504. ssl->auth.setup = 0;
  2505. #endif
  2506. #ifdef WOLFSSL_DTLS13
  2507. XMEMSET(&ssl->dtlsRecordNumberEncrypt, 0,
  2508. sizeof(ssl->dtlsRecordNumberEncrypt));
  2509. XMEMSET(&ssl->dtlsRecordNumberDecrypt, 0,
  2510. sizeof(ssl->dtlsRecordNumberEncrypt));
  2511. #endif /* WOLFSSL_DTLS13 */
  2512. }
  2513. /* Free ciphers */
  2514. void FreeCiphers(WOLFSSL* ssl)
  2515. {
  2516. (void)ssl;
  2517. #ifdef BUILD_ARC4
  2518. wc_Arc4Free(ssl->encrypt.arc4);
  2519. wc_Arc4Free(ssl->decrypt.arc4);
  2520. XFREE(ssl->encrypt.arc4, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2521. XFREE(ssl->decrypt.arc4, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2522. #endif
  2523. #ifdef BUILD_DES3
  2524. wc_Des3Free(ssl->encrypt.des3);
  2525. wc_Des3Free(ssl->decrypt.des3);
  2526. XFREE(ssl->encrypt.des3, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2527. XFREE(ssl->decrypt.des3, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2528. #endif
  2529. #if defined(BUILD_AES) || defined(BUILD_AESGCM) || defined(HAVE_ARIA)
  2530. /* See: InitKeys() in keys.c on addition of BUILD_AESGCM check (enc->aes, dec->aes) */
  2531. wc_AesFree(ssl->encrypt.aes);
  2532. wc_AesFree(ssl->decrypt.aes);
  2533. XFREE(ssl->encrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2534. XFREE(ssl->decrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2535. #endif
  2536. #if defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)
  2537. wc_Sm4Free(ssl->encrypt.sm4);
  2538. wc_Sm4Free(ssl->decrypt.sm4);
  2539. XFREE(ssl->encrypt.sm4, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2540. XFREE(ssl->decrypt.sm4, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2541. #endif
  2542. #if (defined(BUILD_AESGCM) || defined(BUILD_AESCCM) || defined(HAVE_ARIA)) && \
  2543. !defined(WOLFSSL_NO_TLS12)
  2544. XFREE(ssl->decrypt.additional, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2545. XFREE(ssl->encrypt.additional, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2546. #endif
  2547. #ifdef CIPHER_NONCE
  2548. XFREE(ssl->decrypt.nonce, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2549. XFREE(ssl->encrypt.nonce, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2550. #endif
  2551. #ifdef HAVE_ARIA
  2552. wc_AriaFreeCrypt(ssl->encrypt.aria);
  2553. wc_AriaFreeCrypt(ssl->decrypt.aria);
  2554. XFREE(ssl->encrypt.aria, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2555. XFREE(ssl->decrypt.aria, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2556. #endif
  2557. #ifdef HAVE_CAMELLIA
  2558. XFREE(ssl->encrypt.cam, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2559. XFREE(ssl->decrypt.cam, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2560. #endif
  2561. #ifdef HAVE_CHACHA
  2562. if (ssl->encrypt.chacha)
  2563. ForceZero(ssl->encrypt.chacha, sizeof(ChaCha));
  2564. if (ssl->decrypt.chacha)
  2565. ForceZero(ssl->decrypt.chacha, sizeof(ChaCha));
  2566. XFREE(ssl->encrypt.chacha, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2567. XFREE(ssl->decrypt.chacha, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2568. #endif
  2569. #if defined(HAVE_POLY1305) && defined(HAVE_ONE_TIME_AUTH)
  2570. if (ssl->auth.poly1305)
  2571. ForceZero(ssl->auth.poly1305, sizeof(Poly1305));
  2572. XFREE(ssl->auth.poly1305, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2573. #endif
  2574. #if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER)
  2575. wc_HmacFree(ssl->encrypt.hmac);
  2576. wc_HmacFree(ssl->decrypt.hmac);
  2577. XFREE(ssl->encrypt.hmac, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2578. XFREE(ssl->decrypt.hmac, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2579. #endif
  2580. #ifdef WOLFSSL_DTLS13
  2581. #ifdef BUILD_AES
  2582. if (ssl->dtlsRecordNumberEncrypt.aes != NULL) {
  2583. wc_AesFree(ssl->dtlsRecordNumberEncrypt.aes);
  2584. XFREE(ssl->dtlsRecordNumberEncrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2585. ssl->dtlsRecordNumberEncrypt.aes = NULL;
  2586. }
  2587. if (ssl->dtlsRecordNumberDecrypt.aes != NULL) {
  2588. wc_AesFree(ssl->dtlsRecordNumberDecrypt.aes);
  2589. XFREE(ssl->dtlsRecordNumberDecrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER);
  2590. ssl->dtlsRecordNumberDecrypt.aes = NULL;
  2591. }
  2592. #endif /* BUILD_AES */
  2593. #ifdef HAVE_CHACHA
  2594. XFREE(ssl->dtlsRecordNumberEncrypt.chacha,
  2595. ssl->heap, DYNAMIC_TYPE_CIPHER);
  2596. XFREE(ssl->dtlsRecordNumberDecrypt.chacha,
  2597. ssl->heap, DYNAMIC_TYPE_CIPHER);
  2598. ssl->dtlsRecordNumberEncrypt.chacha = NULL;
  2599. ssl->dtlsRecordNumberDecrypt.chacha = NULL;
  2600. #endif /* HAVE_CHACHA */
  2601. #endif /* WOLFSSL_DTLS13 */
  2602. }
  2603. void InitCipherSpecs(CipherSpecs* cs)
  2604. {
  2605. XMEMSET(cs, 0, sizeof(CipherSpecs));
  2606. cs->bulk_cipher_algorithm = INVALID_BYTE;
  2607. cs->cipher_type = INVALID_BYTE;
  2608. cs->mac_algorithm = INVALID_BYTE;
  2609. cs->kea = INVALID_BYTE;
  2610. cs->sig_algo = INVALID_BYTE;
  2611. }
  2612. #if defined(USE_ECDSA_KEYSZ_HASH_ALGO) || (defined(WOLFSSL_TLS13) && \
  2613. defined(HAVE_ECC))
  2614. static int GetMacDigestSize(byte macAlgo)
  2615. {
  2616. switch (macAlgo) {
  2617. #ifndef NO_SHA
  2618. case sha_mac:
  2619. return WC_SHA_DIGEST_SIZE;
  2620. #endif
  2621. #ifndef NO_SHA256
  2622. case sha256_mac:
  2623. return WC_SHA256_DIGEST_SIZE;
  2624. #endif
  2625. #ifdef WOLFSSL_SHA384
  2626. case sha384_mac:
  2627. return WC_SHA384_DIGEST_SIZE;
  2628. #endif
  2629. #ifdef WOLFSSL_SHA512
  2630. case sha512_mac:
  2631. return WC_SHA512_DIGEST_SIZE;
  2632. #endif
  2633. #ifdef WOLFSSL_SM3
  2634. case sm3_mac:
  2635. return WC_SM3_DIGEST_SIZE;
  2636. #endif
  2637. default:
  2638. break;
  2639. }
  2640. return NOT_COMPILED_IN;
  2641. }
  2642. #endif /* USE_ECDSA_KEYSZ_HASH_ALGO || (WOLFSSL_TLS13 && HAVE_ECC) */
  2643. #define ADD_HASH_SIG_ALGO(out, inOutIdx, major, minor) \
  2644. do { \
  2645. if ((out) != NULL) { \
  2646. (out)[*(inOutIdx) ] = (major); \
  2647. (out)[*(inOutIdx) + 1] = (minor); \
  2648. } \
  2649. *(inOutIdx) += 2; \
  2650. } while (0)
  2651. static WC_INLINE void AddSuiteHashSigAlgo(byte* hashSigAlgo, byte macAlgo,
  2652. byte sigAlgo, int keySz, word16* inOutIdx)
  2653. {
  2654. int addSigAlgo = 1;
  2655. #ifdef USE_ECDSA_KEYSZ_HASH_ALGO
  2656. if (sigAlgo == ecc_dsa_sa_algo) {
  2657. int digestSz = GetMacDigestSize(macAlgo);
  2658. /* do not add sig/algos with digest size larger than key size */
  2659. if (digestSz <= 0 || (keySz > 0 && digestSz > keySz)) {
  2660. addSigAlgo = 0;
  2661. }
  2662. }
  2663. #else
  2664. (void)keySz;
  2665. #endif /* USE_ECDSA_KEYSZ_HASH_ALGO */
  2666. if (addSigAlgo) {
  2667. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  2668. if (sigAlgo == sm2_sa_algo) {
  2669. ADD_HASH_SIG_ALGO(hashSigAlgo, inOutIdx,
  2670. SM2_SA_MAJOR, SM2_SA_MINOR);
  2671. }
  2672. else
  2673. #endif
  2674. #ifdef HAVE_ED25519
  2675. if (sigAlgo == ed25519_sa_algo) {
  2676. ADD_HASH_SIG_ALGO(hashSigAlgo, inOutIdx,
  2677. ED25519_SA_MAJOR, ED25519_SA_MINOR);
  2678. }
  2679. else
  2680. #endif
  2681. #ifdef HAVE_ED448
  2682. if (sigAlgo == ed448_sa_algo) {
  2683. ADD_HASH_SIG_ALGO(hashSigAlgo, inOutIdx,
  2684. ED448_SA_MAJOR, ED448_SA_MINOR);
  2685. }
  2686. else
  2687. #endif
  2688. #ifdef HAVE_FALCON
  2689. if (sigAlgo == falcon_level1_sa_algo) {
  2690. ADD_HASH_SIG_ALGO(hashSigAlgo, inOutIdx,
  2691. FALCON_LEVEL1_SA_MAJOR, FALCON_LEVEL1_SA_MINOR);
  2692. }
  2693. else
  2694. if (sigAlgo == falcon_level5_sa_algo) {
  2695. ADD_HASH_SIG_ALGO(hashSigAlgo, inOutIdx,
  2696. FALCON_LEVEL5_SA_MAJOR, FALCON_LEVEL5_SA_MINOR);
  2697. }
  2698. else
  2699. #endif /* HAVE_FALCON */
  2700. #ifdef HAVE_DILITHIUM
  2701. if (sigAlgo == dilithium_level2_sa_algo) {
  2702. ADD_HASH_SIG_ALGO(hashSigAlgo, inOutIdx,
  2703. DILITHIUM_LEVEL2_SA_MAJOR, DILITHIUM_LEVEL2_SA_MINOR);
  2704. }
  2705. else
  2706. if (sigAlgo == dilithium_level3_sa_algo) {
  2707. ADD_HASH_SIG_ALGO(hashSigAlgo, inOutIdx,
  2708. DILITHIUM_LEVEL3_SA_MAJOR, DILITHIUM_LEVEL3_SA_MINOR);
  2709. }
  2710. else
  2711. if (sigAlgo == dilithium_level5_sa_algo) {
  2712. ADD_HASH_SIG_ALGO(hashSigAlgo, inOutIdx,
  2713. DILITHIUM_LEVEL5_SA_MAJOR, DILITHIUM_LEVEL5_SA_MINOR);
  2714. }
  2715. else
  2716. #endif /* HAVE_DILITHIUM */
  2717. #ifdef WC_RSA_PSS
  2718. if (sigAlgo == rsa_pss_sa_algo) {
  2719. /* RSA PSS is sig then mac */
  2720. ADD_HASH_SIG_ALGO(hashSigAlgo, inOutIdx, sigAlgo, macAlgo);
  2721. #ifdef WOLFSSL_TLS13
  2722. /* Add the certificate algorithm as well */
  2723. ADD_HASH_SIG_ALGO(hashSigAlgo, inOutIdx, sigAlgo,
  2724. PSS_RSAE_TO_PSS_PSS(macAlgo));
  2725. #endif
  2726. }
  2727. else
  2728. #endif
  2729. {
  2730. ADD_HASH_SIG_ALGO(hashSigAlgo, inOutIdx, macAlgo, sigAlgo);
  2731. }
  2732. }
  2733. }
  2734. void InitSuitesHashSigAlgo(byte* hashSigAlgo, int haveSig, int tls1_2,
  2735. int keySz, word16* len)
  2736. {
  2737. word16 idx = 0;
  2738. (void)tls1_2;
  2739. (void)keySz;
  2740. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  2741. if (haveSig & SIG_ECDSA) {
  2742. #ifdef HAVE_ECC
  2743. #ifdef WOLFSSL_SHA512
  2744. AddSuiteHashSigAlgo(hashSigAlgo, sha512_mac, ecc_dsa_sa_algo, keySz,
  2745. &idx);
  2746. #endif
  2747. #ifdef WOLFSSL_SHA384
  2748. AddSuiteHashSigAlgo(hashSigAlgo, sha384_mac, ecc_dsa_sa_algo, keySz,
  2749. &idx);
  2750. #endif
  2751. #ifndef NO_SHA256
  2752. AddSuiteHashSigAlgo(hashSigAlgo, sha256_mac, ecc_dsa_sa_algo, keySz,
  2753. &idx);
  2754. #endif
  2755. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  2756. defined(WOLFSSL_ALLOW_TLS_SHA1))
  2757. AddSuiteHashSigAlgo(hashSigAlgo, sha_mac, ecc_dsa_sa_algo, keySz, &idx);
  2758. #endif
  2759. #endif
  2760. #ifdef HAVE_ED25519
  2761. AddSuiteHashSigAlgo(hashSigAlgo, no_mac, ed25519_sa_algo, keySz, &idx);
  2762. #endif
  2763. #ifdef HAVE_ED448
  2764. AddSuiteHashSigAlgo(hashSigAlgo, no_mac, ed448_sa_algo, keySz, &idx);
  2765. #endif
  2766. }
  2767. #endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  2768. #if defined(HAVE_ECC) && defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  2769. if (haveSig & SIG_SM2) {
  2770. AddSuiteHashSigAlgo(hashSigAlgo, sm3_mac, sm2_sa_algo, keySz,
  2771. &idx);
  2772. }
  2773. #endif
  2774. #ifdef HAVE_FALCON
  2775. if (haveSig & SIG_FALCON) {
  2776. AddSuiteHashSigAlgo(hashSigAlgo, no_mac, falcon_level1_sa_algo, keySz,
  2777. &idx);
  2778. AddSuiteHashSigAlgo(hashSigAlgo, no_mac, falcon_level5_sa_algo, keySz,
  2779. &idx);
  2780. }
  2781. #endif /* HAVE_FALCON */
  2782. #ifdef HAVE_DILITHIUM
  2783. if (haveSig & SIG_DILITHIUM) {
  2784. AddSuiteHashSigAlgo(hashSigAlgo, no_mac, dilithium_level2_sa_algo,
  2785. keySz, &idx);
  2786. AddSuiteHashSigAlgo(hashSigAlgo, no_mac, dilithium_level3_sa_algo,
  2787. keySz, &idx);
  2788. AddSuiteHashSigAlgo(hashSigAlgo, no_mac, dilithium_level5_sa_algo,
  2789. keySz, &idx);
  2790. }
  2791. #endif /* HAVE_DILITHIUM */
  2792. if (haveSig & SIG_RSA) {
  2793. #ifdef WC_RSA_PSS
  2794. if (tls1_2) {
  2795. #ifdef WOLFSSL_SHA512
  2796. AddSuiteHashSigAlgo(hashSigAlgo, sha512_mac, rsa_pss_sa_algo, keySz,
  2797. &idx);
  2798. #endif
  2799. #ifdef WOLFSSL_SHA384
  2800. AddSuiteHashSigAlgo(hashSigAlgo, sha384_mac, rsa_pss_sa_algo, keySz,
  2801. &idx);
  2802. #endif
  2803. #ifndef NO_SHA256
  2804. AddSuiteHashSigAlgo(hashSigAlgo, sha256_mac, rsa_pss_sa_algo, keySz,
  2805. &idx);
  2806. #endif
  2807. }
  2808. #endif
  2809. #ifdef WOLFSSL_SHA512
  2810. AddSuiteHashSigAlgo(hashSigAlgo, sha512_mac, rsa_sa_algo, keySz, &idx);
  2811. #endif
  2812. #ifdef WOLFSSL_SHA384
  2813. AddSuiteHashSigAlgo(hashSigAlgo, sha384_mac, rsa_sa_algo, keySz, &idx);
  2814. #endif
  2815. #ifndef NO_SHA256
  2816. AddSuiteHashSigAlgo(hashSigAlgo, sha256_mac, rsa_sa_algo, keySz, &idx);
  2817. #endif
  2818. #ifdef WOLFSSL_SHA224
  2819. AddSuiteHashSigAlgo(hashSigAlgo, sha224_mac, rsa_sa_algo, keySz, &idx);
  2820. #endif
  2821. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  2822. defined(WOLFSSL_ALLOW_TLS_SHA1))
  2823. AddSuiteHashSigAlgo(hashSigAlgo, sha_mac, rsa_sa_algo, keySz, &idx);
  2824. #endif
  2825. }
  2826. #ifdef HAVE_ANON
  2827. if (haveSig & SIG_ANON) {
  2828. AddSuiteHashSigAlgo(hashSigAlgo, sha_mac, anonymous_sa_algo, keySz,
  2829. &idx);
  2830. }
  2831. #endif
  2832. *len = idx;
  2833. }
  2834. int AllocateCtxSuites(WOLFSSL_CTX* ctx)
  2835. {
  2836. if (ctx->suites == NULL) {
  2837. ctx->suites = (Suites*)XMALLOC(sizeof(Suites), ctx->heap,
  2838. DYNAMIC_TYPE_SUITES);
  2839. if (ctx->suites == NULL) {
  2840. WOLFSSL_MSG("Memory alloc for Suites failed");
  2841. return MEMORY_ERROR;
  2842. }
  2843. XMEMSET(ctx->suites, 0, sizeof(Suites));
  2844. }
  2845. return 0;
  2846. }
  2847. /* Call this when the ssl object needs to have its own ssl->suites object */
  2848. int AllocateSuites(WOLFSSL* ssl)
  2849. {
  2850. if (ssl->suites == NULL) {
  2851. ssl->suites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap,
  2852. DYNAMIC_TYPE_SUITES);
  2853. if (ssl->suites == NULL) {
  2854. WOLFSSL_MSG("Suites Memory error");
  2855. return MEMORY_ERROR;
  2856. }
  2857. if (ssl->ctx != NULL && ssl->ctx->suites != NULL)
  2858. XMEMCPY(ssl->suites, ssl->ctx->suites, sizeof(Suites));
  2859. else
  2860. XMEMSET(ssl->suites, 0, sizeof(Suites));
  2861. }
  2862. return 0;
  2863. }
  2864. void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA,
  2865. word16 havePSK, word16 haveDH, word16 haveECDSAsig,
  2866. word16 haveECC, word16 haveStaticRSA, word16 haveStaticECC,
  2867. word16 haveFalconSig, word16 haveDilithiumSig, word16 haveAnon,
  2868. word16 haveNull, int side)
  2869. {
  2870. word16 idx = 0;
  2871. int tls = pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_MINOR;
  2872. int tls1_2 = pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_2_MINOR;
  2873. #ifdef WOLFSSL_TLS13
  2874. int tls1_3 = IsAtLeastTLSv1_3(pv);
  2875. #endif
  2876. int dtls = 0;
  2877. int haveRSAsig = 1;
  2878. #ifdef WOLFSSL_DTLS
  2879. if (pv.major == DTLS_MAJOR) {
  2880. dtls = 1;
  2881. tls = 1;
  2882. /* May be dead assignments dependent upon configuration */
  2883. (void) dtls;
  2884. (void) tls;
  2885. tls1_2 = pv.minor <= DTLSv1_2_MINOR;
  2886. }
  2887. #endif
  2888. (void)tls; /* shut up compiler */
  2889. (void)tls1_2;
  2890. (void)dtls;
  2891. (void)haveDH;
  2892. (void)havePSK;
  2893. (void)haveStaticRSA;
  2894. (void)haveStaticECC;
  2895. (void)haveECC;
  2896. (void)haveECDSAsig;
  2897. (void)side;
  2898. (void)haveRSA; /* some builds won't read */
  2899. (void)haveRSAsig; /* non ecc builds won't read */
  2900. (void)haveAnon; /* anon ciphers optional */
  2901. (void)haveNull;
  2902. (void)haveFalconSig;
  2903. (void)haveDilithiumSig;
  2904. if (suites == NULL) {
  2905. WOLFSSL_MSG("InitSuites pointer error");
  2906. return;
  2907. }
  2908. if (suites->setSuites)
  2909. return; /* trust user settings, don't override */
  2910. #ifdef WOLFSSL_TLS13
  2911. #ifdef BUILD_TLS_AES_128_GCM_SHA256
  2912. if (tls1_3) {
  2913. suites->suites[idx++] = TLS13_BYTE;
  2914. suites->suites[idx++] = TLS_AES_128_GCM_SHA256;
  2915. }
  2916. #endif
  2917. #ifdef BUILD_TLS_AES_256_GCM_SHA384
  2918. if (tls1_3) {
  2919. suites->suites[idx++] = TLS13_BYTE;
  2920. suites->suites[idx++] = TLS_AES_256_GCM_SHA384;
  2921. }
  2922. #endif
  2923. #ifdef BUILD_TLS_CHACHA20_POLY1305_SHA256
  2924. if (tls1_3) {
  2925. suites->suites[idx++] = TLS13_BYTE;
  2926. suites->suites[idx++] = TLS_CHACHA20_POLY1305_SHA256;
  2927. }
  2928. #endif
  2929. #ifdef BUILD_TLS_AES_128_CCM_SHA256
  2930. if (tls1_3) {
  2931. suites->suites[idx++] = TLS13_BYTE;
  2932. suites->suites[idx++] = TLS_AES_128_CCM_SHA256;
  2933. }
  2934. #endif
  2935. #ifdef BUILD_TLS_AES_128_CCM_8_SHA256
  2936. if (tls1_3) {
  2937. suites->suites[idx++] = TLS13_BYTE;
  2938. suites->suites[idx++] = TLS_AES_128_CCM_8_SHA256;
  2939. }
  2940. #endif
  2941. #ifdef BUILD_TLS_SM4_GCM_SM3
  2942. if (tls1_3) {
  2943. suites->suites[idx++] = CIPHER_BYTE;
  2944. suites->suites[idx++] = TLS_SM4_GCM_SM3;
  2945. }
  2946. #endif
  2947. #ifdef BUILD_TLS_SM4_CCM_SM3
  2948. if (tls1_3) {
  2949. suites->suites[idx++] = CIPHER_BYTE;
  2950. suites->suites[idx++] = TLS_SM4_CCM_SM3;
  2951. }
  2952. #endif
  2953. #ifdef HAVE_NULL_CIPHER
  2954. #ifdef BUILD_TLS_SHA256_SHA256
  2955. if (tls1_3 && haveNull) {
  2956. suites->suites[idx++] = ECC_BYTE;
  2957. suites->suites[idx++] = TLS_SHA256_SHA256;
  2958. }
  2959. #endif
  2960. #ifdef BUILD_TLS_SHA384_SHA384
  2961. if (tls1_3 && haveNull) {
  2962. suites->suites[idx++] = ECC_BYTE;
  2963. suites->suites[idx++] = TLS_SHA384_SHA384;
  2964. }
  2965. #endif
  2966. #endif
  2967. #endif /* WOLFSSL_TLS13 */
  2968. #ifndef WOLFSSL_NO_TLS12
  2969. #if !defined(NO_WOLFSSL_SERVER) && !defined(NO_RSA)
  2970. if (side == WOLFSSL_SERVER_END && haveStaticECC) {
  2971. haveRSA = 0; /* can't do RSA with ECDSA key */
  2972. }
  2973. if (side == WOLFSSL_SERVER_END && haveECDSAsig) {
  2974. haveRSAsig = 0; /* can't have RSA sig if signed by ECDSA */
  2975. }
  2976. #endif /* !NO_WOLFSSL_SERVER */
  2977. #ifdef NO_RSA
  2978. haveRSAsig = 0; /* can't have RSA sig if don't have RSA */
  2979. #endif
  2980. #ifdef HAVE_RENEGOTIATION_INDICATION
  2981. if (side == WOLFSSL_CLIENT_END) {
  2982. suites->suites[idx++] = CIPHER_BYTE;
  2983. suites->suites[idx++] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
  2984. }
  2985. #endif
  2986. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
  2987. if (tls1_2 && haveECC) {
  2988. suites->suites[idx++] = ECC_BYTE;
  2989. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384;
  2990. }
  2991. #endif
  2992. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
  2993. if (tls1_2 && haveECC) {
  2994. suites->suites[idx++] = ECC_BYTE;
  2995. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256;
  2996. }
  2997. #endif
  2998. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
  2999. /* OpenSSL enables ECDHE when using ECDHE aliases without RSA */
  3000. #ifdef OPENSSL_EXTRA
  3001. if ((tls1_2 && haveRSA) || (tls1_2 && haveECDSAsig)) {
  3002. #else
  3003. if (tls1_2 && haveRSA) {
  3004. #endif
  3005. suites->suites[idx++] = ECC_BYTE;
  3006. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384;
  3007. }
  3008. #endif
  3009. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  3010. #ifdef OPENSSL_EXTRA
  3011. if ((tls1_2 && haveRSA) || (tls1_2 && haveECDSAsig)) {
  3012. #else
  3013. if (tls1_2 && haveRSA) {
  3014. #endif
  3015. suites->suites[idx++] = ECC_BYTE;
  3016. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256;
  3017. }
  3018. #endif
  3019. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
  3020. if (tls1_2 && haveDH && haveRSA) {
  3021. suites->suites[idx++] = CIPHER_BYTE;
  3022. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_GCM_SHA384;
  3023. }
  3024. #endif
  3025. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
  3026. if (tls1_2 && haveDH && haveRSA) {
  3027. suites->suites[idx++] = CIPHER_BYTE;
  3028. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_128_GCM_SHA256;
  3029. }
  3030. #endif
  3031. #ifdef BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384
  3032. if (tls1_2 && haveRSA && haveStaticRSA) {
  3033. suites->suites[idx++] = CIPHER_BYTE;
  3034. suites->suites[idx++] = TLS_RSA_WITH_AES_256_GCM_SHA384;
  3035. }
  3036. #endif
  3037. #ifdef BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256
  3038. if (tls1_2 && haveRSA && haveStaticRSA) {
  3039. suites->suites[idx++] = CIPHER_BYTE;
  3040. suites->suites[idx++] = TLS_RSA_WITH_AES_128_GCM_SHA256;
  3041. }
  3042. #endif
  3043. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
  3044. if (tls1_2 && haveECC && haveStaticECC) {
  3045. suites->suites[idx++] = ECC_BYTE;
  3046. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384;
  3047. }
  3048. #endif
  3049. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
  3050. if (tls1_2 && haveECC && haveStaticECC) {
  3051. suites->suites[idx++] = ECC_BYTE;
  3052. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256;
  3053. }
  3054. #endif
  3055. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
  3056. if (tls1_2 && haveRSAsig && haveStaticECC) {
  3057. suites->suites[idx++] = ECC_BYTE;
  3058. suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384;
  3059. }
  3060. #endif
  3061. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
  3062. if (tls1_2 && haveRSAsig && haveStaticECC) {
  3063. suites->suites[idx++] = ECC_BYTE;
  3064. suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256;
  3065. }
  3066. #endif
  3067. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384
  3068. if (tls1_2 && haveECC) {
  3069. suites->suites[idx++] = ECC_BYTE;
  3070. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384;
  3071. }
  3072. #endif
  3073. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256
  3074. if (tls1_2 && haveECC) {
  3075. suites->suites[idx++] = ECC_BYTE;
  3076. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256;
  3077. }
  3078. #endif
  3079. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
  3080. if (tls1_2 && haveDH && havePSK) {
  3081. suites->suites[idx++] = CIPHER_BYTE;
  3082. suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_256_GCM_SHA384;
  3083. }
  3084. #endif
  3085. #ifdef BUILD_TLS_DH_anon_WITH_AES_128_CBC_SHA
  3086. if (tls1_2 && haveDH && haveAnon) {
  3087. suites->suites[idx++] = CIPHER_BYTE;
  3088. suites->suites[idx++] = TLS_DH_anon_WITH_AES_128_CBC_SHA;
  3089. }
  3090. #endif
  3091. #ifdef BUILD_TLS_DH_anon_WITH_AES_256_GCM_SHA384
  3092. if (tls1_2 && haveDH && haveAnon) {
  3093. suites->suites[idx++] = CIPHER_BYTE;
  3094. suites->suites[idx++] = TLS_DH_anon_WITH_AES_256_GCM_SHA384;
  3095. }
  3096. #endif
  3097. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
  3098. if (tls1_2 && haveDH && havePSK) {
  3099. suites->suites[idx++] = CIPHER_BYTE;
  3100. suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_128_GCM_SHA256;
  3101. }
  3102. #endif
  3103. #ifdef BUILD_TLS_PSK_WITH_AES_256_GCM_SHA384
  3104. if (tls1_2 && havePSK) {
  3105. suites->suites[idx++] = CIPHER_BYTE;
  3106. suites->suites[idx++] = TLS_PSK_WITH_AES_256_GCM_SHA384;
  3107. }
  3108. #endif
  3109. #ifdef BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256
  3110. if (tls1_2 && havePSK) {
  3111. suites->suites[idx++] = CIPHER_BYTE;
  3112. suites->suites[idx++] = TLS_PSK_WITH_AES_128_GCM_SHA256;
  3113. }
  3114. #endif
  3115. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
  3116. if (tls1_2 && haveECC) {
  3117. suites->suites[idx++] = CHACHA_BYTE;
  3118. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256;
  3119. }
  3120. #endif
  3121. #ifdef BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
  3122. #ifdef OPENSSL_EXTRA
  3123. if ((tls1_2 && haveRSA) || (tls1_2 && haveECDSAsig)) {
  3124. #else
  3125. if (tls1_2 && haveRSA) {
  3126. #endif
  3127. suites->suites[idx++] = CHACHA_BYTE;
  3128. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256;
  3129. }
  3130. #endif
  3131. #ifdef BUILD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
  3132. if (tls1_2 && haveRSA) {
  3133. suites->suites[idx++] = CHACHA_BYTE;
  3134. suites->suites[idx++] = TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256;
  3135. }
  3136. #endif
  3137. /* Place as higher priority for MYSQL */
  3138. #if defined(WOLFSSL_MYSQL_COMPATIBLE)
  3139. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
  3140. if (tls && haveDH && haveRSA) {
  3141. suites->suites[idx++] = CIPHER_BYTE;
  3142. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA;
  3143. }
  3144. #endif
  3145. #endif
  3146. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
  3147. #ifdef OPENSSL_EXTRA
  3148. if ((tls1_2 && haveRSA) || (tls1_2 && haveECDSAsig)) {
  3149. #else
  3150. if (tls1_2 && haveRSA) {
  3151. #endif
  3152. suites->suites[idx++] = ECC_BYTE;
  3153. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256;
  3154. }
  3155. #endif
  3156. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
  3157. if (tls1_2 && haveECC) {
  3158. suites->suites[idx++] = ECC_BYTE;
  3159. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256;
  3160. }
  3161. #endif
  3162. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
  3163. if (tls1_2 && haveRSAsig && haveStaticECC) {
  3164. suites->suites[idx++] = ECC_BYTE;
  3165. suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256;
  3166. }
  3167. #endif
  3168. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
  3169. if (tls1_2 && haveECC && haveStaticECC) {
  3170. suites->suites[idx++] = ECC_BYTE;
  3171. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256;
  3172. }
  3173. #endif
  3174. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
  3175. #ifdef OPENSSL_EXTRA
  3176. if ((tls1_2 && haveRSA) || (tls1_2 && haveECDSAsig)) {
  3177. #else
  3178. if (tls1_2 && haveRSA) {
  3179. #endif
  3180. suites->suites[idx++] = ECC_BYTE;
  3181. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384;
  3182. }
  3183. #endif
  3184. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
  3185. if (tls1_2 && haveECC) {
  3186. suites->suites[idx++] = ECC_BYTE;
  3187. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384;
  3188. }
  3189. #endif
  3190. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
  3191. if (tls1_2 && haveRSAsig && haveStaticECC) {
  3192. suites->suites[idx++] = ECC_BYTE;
  3193. suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384;
  3194. }
  3195. #endif
  3196. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
  3197. if (tls1_2 && haveECC && haveStaticECC) {
  3198. suites->suites[idx++] = ECC_BYTE;
  3199. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384;
  3200. }
  3201. #endif
  3202. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
  3203. if (tls && haveECC) {
  3204. suites->suites[idx++] = ECC_BYTE;
  3205. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA;
  3206. }
  3207. #endif
  3208. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
  3209. if (tls && haveECC && haveStaticECC) {
  3210. suites->suites[idx++] = ECC_BYTE;
  3211. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA;
  3212. }
  3213. #endif
  3214. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
  3215. if (tls && haveECC) {
  3216. suites->suites[idx++] = ECC_BYTE;
  3217. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA;
  3218. }
  3219. #endif
  3220. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
  3221. if (tls && haveECC && haveStaticECC) {
  3222. suites->suites[idx++] = ECC_BYTE;
  3223. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA;
  3224. }
  3225. #endif
  3226. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
  3227. if (!dtls && tls && haveECC) {
  3228. suites->suites[idx++] = ECC_BYTE;
  3229. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_RC4_128_SHA;
  3230. }
  3231. #endif
  3232. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA
  3233. if (!dtls && tls && haveECC && haveStaticECC) {
  3234. suites->suites[idx++] = ECC_BYTE;
  3235. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_RC4_128_SHA;
  3236. }
  3237. #endif
  3238. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
  3239. if (tls && haveECC) {
  3240. suites->suites[idx++] = ECC_BYTE;
  3241. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA;
  3242. }
  3243. #endif
  3244. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
  3245. if (tls && haveECC && haveStaticECC) {
  3246. suites->suites[idx++] = ECC_BYTE;
  3247. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA;
  3248. }
  3249. #endif
  3250. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
  3251. #ifdef OPENSSL_EXTRA
  3252. if ((tls && haveRSA) || (tls && haveECDSAsig)) {
  3253. #else
  3254. if (tls && haveRSA) {
  3255. #endif
  3256. suites->suites[idx++] = ECC_BYTE;
  3257. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA;
  3258. }
  3259. #endif
  3260. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
  3261. if (tls && haveRSAsig && haveStaticECC) {
  3262. suites->suites[idx++] = ECC_BYTE;
  3263. suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_256_CBC_SHA;
  3264. }
  3265. #endif
  3266. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
  3267. #ifdef OPENSSL_EXTRA
  3268. if ((tls && haveRSA) || (tls && haveECDSAsig)) {
  3269. #else
  3270. if (tls && haveRSA) {
  3271. #endif
  3272. suites->suites[idx++] = ECC_BYTE;
  3273. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA;
  3274. }
  3275. #endif
  3276. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
  3277. if (tls && haveRSAsig && haveStaticECC) {
  3278. suites->suites[idx++] = ECC_BYTE;
  3279. suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_128_CBC_SHA;
  3280. }
  3281. #endif
  3282. #ifdef BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA
  3283. if (!dtls && tls && haveRSA) {
  3284. suites->suites[idx++] = ECC_BYTE;
  3285. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_RC4_128_SHA;
  3286. }
  3287. #endif
  3288. #ifdef BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA
  3289. if (!dtls && tls && haveRSAsig && haveStaticECC) {
  3290. suites->suites[idx++] = ECC_BYTE;
  3291. suites->suites[idx++] = TLS_ECDH_RSA_WITH_RC4_128_SHA;
  3292. }
  3293. #endif
  3294. #ifdef BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
  3295. #ifdef OPENSSL_EXTRA
  3296. if ((tls && haveRSA) || (tls && haveECDSAsig)) {
  3297. #else
  3298. if (tls && haveRSA) {
  3299. #endif
  3300. suites->suites[idx++] = ECC_BYTE;
  3301. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA;
  3302. }
  3303. #endif
  3304. #ifdef BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
  3305. if (tls && haveRSAsig && haveStaticECC) {
  3306. suites->suites[idx++] = ECC_BYTE;
  3307. suites->suites[idx++] = TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA;
  3308. }
  3309. #endif
  3310. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM
  3311. if (tls1_2 && haveECC) {
  3312. suites->suites[idx++] = ECC_BYTE;
  3313. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CCM;
  3314. }
  3315. #endif
  3316. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
  3317. if (tls1_2 && haveECC) {
  3318. suites->suites[idx++] = ECC_BYTE;
  3319. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
  3320. }
  3321. #endif
  3322. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8
  3323. if (tls1_2 && haveECC) {
  3324. suites->suites[idx++] = ECC_BYTE;
  3325. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8;
  3326. }
  3327. #endif
  3328. #ifdef BUILD_TLS_RSA_WITH_AES_128_CCM_8
  3329. if (tls1_2 && haveRSA && haveStaticRSA) {
  3330. suites->suites[idx++] = ECC_BYTE;
  3331. suites->suites[idx++] = TLS_RSA_WITH_AES_128_CCM_8;
  3332. }
  3333. #endif
  3334. #ifdef BUILD_TLS_RSA_WITH_AES_256_CCM_8
  3335. if (tls1_2 && haveRSA && haveStaticRSA) {
  3336. suites->suites[idx++] = ECC_BYTE;
  3337. suites->suites[idx++] = TLS_RSA_WITH_AES_256_CCM_8;
  3338. }
  3339. #endif
  3340. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
  3341. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3342. if (tls1_2 && haveDH && haveRSA)
  3343. #else
  3344. if (tls && haveDH && haveRSA)
  3345. #endif
  3346. {
  3347. suites->suites[idx++] = CIPHER_BYTE;
  3348. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA256;
  3349. }
  3350. #endif
  3351. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
  3352. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3353. if (tls1_2 && haveDH && haveRSA)
  3354. #else
  3355. if (tls && haveDH && haveRSA)
  3356. #endif
  3357. {
  3358. suites->suites[idx++] = CIPHER_BYTE;
  3359. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_128_CBC_SHA256;
  3360. }
  3361. #endif
  3362. /* Place as higher priority for MYSQL testing */
  3363. #if !defined(WOLFSSL_MYSQL_COMPATIBLE)
  3364. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
  3365. if (tls && haveDH && haveRSA) {
  3366. suites->suites[idx++] = CIPHER_BYTE;
  3367. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA;
  3368. }
  3369. #endif
  3370. #endif
  3371. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
  3372. if (tls && haveDH && haveRSA) {
  3373. suites->suites[idx++] = CIPHER_BYTE;
  3374. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_128_CBC_SHA;
  3375. }
  3376. #endif
  3377. #ifdef BUILD_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
  3378. if (tls && haveDH && haveRSA) {
  3379. suites->suites[idx++] = CIPHER_BYTE;
  3380. suites->suites[idx++] = TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA;
  3381. }
  3382. #endif
  3383. #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA256
  3384. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3385. if (tls1_2 && haveRSA && haveStaticRSA)
  3386. #else
  3387. if (tls && haveRSA && haveStaticRSA)
  3388. #endif
  3389. {
  3390. suites->suites[idx++] = CIPHER_BYTE;
  3391. suites->suites[idx++] = TLS_RSA_WITH_AES_256_CBC_SHA256;
  3392. }
  3393. #endif
  3394. #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256
  3395. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3396. if (tls1_2 && haveRSA && haveStaticRSA)
  3397. #else
  3398. if (tls && haveRSA && haveStaticRSA)
  3399. #endif
  3400. {
  3401. suites->suites[idx++] = CIPHER_BYTE;
  3402. suites->suites[idx++] = TLS_RSA_WITH_AES_128_CBC_SHA256;
  3403. }
  3404. #endif
  3405. #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA
  3406. if (tls && haveRSA && haveStaticRSA) {
  3407. suites->suites[idx++] = CIPHER_BYTE;
  3408. suites->suites[idx++] = TLS_RSA_WITH_AES_256_CBC_SHA;
  3409. }
  3410. #endif
  3411. #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA
  3412. if (tls && haveRSA && haveStaticRSA) {
  3413. suites->suites[idx++] = CIPHER_BYTE;
  3414. suites->suites[idx++] = TLS_RSA_WITH_AES_128_CBC_SHA;
  3415. }
  3416. #endif
  3417. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256
  3418. if (tls1_2 && haveECC) {
  3419. suites->suites[idx++] = CHACHA_BYTE;
  3420. suites->suites[idx++] =
  3421. TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256;
  3422. }
  3423. #endif
  3424. #ifdef BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
  3425. #ifdef OPENSSL_EXTRA
  3426. if ((tls1_2 && haveRSA) || (tls1_2 && haveECDSAsig)) {
  3427. #else
  3428. if (tls1_2 && haveRSA) {
  3429. #endif
  3430. suites->suites[idx++] = CHACHA_BYTE;
  3431. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256;
  3432. }
  3433. #endif
  3434. #ifdef BUILD_TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
  3435. #ifdef OPENSSL_EXTRA
  3436. if ((tls1_2 && haveRSA) || (tls1_2 && haveECDSAsig)) {
  3437. #else
  3438. if (tls1_2 && haveRSA) {
  3439. #endif
  3440. suites->suites[idx++] = CHACHA_BYTE;
  3441. suites->suites[idx++] = TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256;
  3442. }
  3443. #endif
  3444. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_NULL_SHA
  3445. if (tls && haveECC && haveNull) {
  3446. suites->suites[idx++] = ECC_BYTE;
  3447. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_NULL_SHA;
  3448. }
  3449. #endif
  3450. #ifdef BUILD_TLS_RSA_WITH_NULL_MD5
  3451. if (tls && haveRSA && haveNull && haveStaticRSA) {
  3452. suites->suites[idx++] = CIPHER_BYTE;
  3453. suites->suites[idx++] = TLS_RSA_WITH_NULL_MD5;
  3454. }
  3455. #endif
  3456. #ifdef BUILD_TLS_RSA_WITH_NULL_SHA
  3457. if (tls && haveRSA && haveNull && haveStaticRSA) {
  3458. suites->suites[idx++] = CIPHER_BYTE;
  3459. suites->suites[idx++] = TLS_RSA_WITH_NULL_SHA;
  3460. }
  3461. #endif
  3462. #ifdef BUILD_TLS_RSA_WITH_NULL_SHA256
  3463. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3464. if (tls1_2 && haveRSA && haveNull && haveStaticRSA)
  3465. #else
  3466. if (tls && haveRSA && haveNull && haveStaticRSA)
  3467. #endif
  3468. {
  3469. suites->suites[idx++] = CIPHER_BYTE;
  3470. suites->suites[idx++] = TLS_RSA_WITH_NULL_SHA256;
  3471. }
  3472. #endif
  3473. #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA
  3474. if (tls && havePSK) {
  3475. suites->suites[idx++] = CIPHER_BYTE;
  3476. suites->suites[idx++] = TLS_PSK_WITH_AES_256_CBC_SHA;
  3477. }
  3478. #endif
  3479. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
  3480. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3481. if (tls1_2 && haveDH && havePSK)
  3482. #else
  3483. if (tls && haveDH && havePSK)
  3484. #endif
  3485. {
  3486. suites->suites[idx++] = CIPHER_BYTE;
  3487. suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_256_CBC_SHA384;
  3488. }
  3489. #endif
  3490. #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA384
  3491. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3492. if (tls1_2 && havePSK)
  3493. #else
  3494. if (tls && havePSK)
  3495. #endif
  3496. {
  3497. suites->suites[idx++] = CIPHER_BYTE;
  3498. suites->suites[idx++] = TLS_PSK_WITH_AES_256_CBC_SHA384;
  3499. }
  3500. #endif
  3501. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
  3502. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3503. if (tls1_2 && haveDH && havePSK)
  3504. #else
  3505. if (tls && haveDH && havePSK)
  3506. #endif
  3507. {
  3508. suites->suites[idx++] = CIPHER_BYTE;
  3509. suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_128_CBC_SHA256;
  3510. }
  3511. #endif
  3512. #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA256
  3513. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3514. if (tls1_2 && havePSK)
  3515. #else
  3516. if (tls1 && havePSK)
  3517. #endif
  3518. {
  3519. suites->suites[idx++] = CIPHER_BYTE;
  3520. suites->suites[idx++] = TLS_PSK_WITH_AES_128_CBC_SHA256;
  3521. }
  3522. #endif
  3523. #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA
  3524. if (tls && havePSK) {
  3525. suites->suites[idx++] = CIPHER_BYTE;
  3526. suites->suites[idx++] = TLS_PSK_WITH_AES_128_CBC_SHA;
  3527. }
  3528. #endif
  3529. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CCM
  3530. if (tls && haveDH && havePSK) {
  3531. suites->suites[idx++] = ECC_BYTE;
  3532. suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_128_CCM;
  3533. }
  3534. #endif
  3535. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_CCM
  3536. if (tls && haveDH && havePSK) {
  3537. suites->suites[idx++] = ECC_BYTE;
  3538. suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_256_CCM;
  3539. }
  3540. #endif
  3541. #ifdef BUILD_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256
  3542. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3543. if (tls1_2 && havePSK)
  3544. #else
  3545. if (tls && havePSK)
  3546. #endif
  3547. {
  3548. suites->suites[idx++] = CHACHA_BYTE;
  3549. suites->suites[idx++] = TLS_PSK_WITH_CHACHA20_POLY1305_SHA256;
  3550. }
  3551. #endif
  3552. #ifdef BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256
  3553. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3554. if (tls1_2 && havePSK)
  3555. #else
  3556. if (tls && havePSK)
  3557. #endif
  3558. {
  3559. suites->suites[idx++] = CHACHA_BYTE;
  3560. suites->suites[idx++] = TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256;
  3561. }
  3562. #endif
  3563. #ifdef BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256
  3564. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3565. if (tls1_2 && havePSK)
  3566. #else
  3567. if (tls && havePSK)
  3568. #endif
  3569. {
  3570. suites->suites[idx++] = CHACHA_BYTE;
  3571. suites->suites[idx++] = TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256;
  3572. }
  3573. #endif
  3574. #ifdef BUILD_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
  3575. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3576. if (tls1_2 && havePSK)
  3577. #else
  3578. if (tls && havePSK)
  3579. #endif
  3580. {
  3581. suites->suites[idx++] = ECC_BYTE;
  3582. suites->suites[idx++] = TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
  3583. }
  3584. #endif
  3585. #ifdef BUILD_TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256
  3586. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3587. if (tls1_2 && havePSK)
  3588. #else
  3589. if (tls && havePSK)
  3590. #endif
  3591. {
  3592. suites->suites[idx++] = ECDHE_PSK_BYTE;
  3593. suites->suites[idx++] = TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256;
  3594. }
  3595. #endif
  3596. #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM
  3597. if (tls && havePSK) {
  3598. suites->suites[idx++] = ECC_BYTE;
  3599. suites->suites[idx++] = TLS_PSK_WITH_AES_128_CCM;
  3600. }
  3601. #endif
  3602. #ifdef BUILD_TLS_PSK_WITH_AES_256_CCM
  3603. if (tls && havePSK) {
  3604. suites->suites[idx++] = ECC_BYTE;
  3605. suites->suites[idx++] = TLS_PSK_WITH_AES_256_CCM;
  3606. }
  3607. #endif
  3608. #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM_8
  3609. if (tls && havePSK) {
  3610. suites->suites[idx++] = ECC_BYTE;
  3611. suites->suites[idx++] = TLS_PSK_WITH_AES_128_CCM_8;
  3612. }
  3613. #endif
  3614. #ifdef BUILD_TLS_PSK_WITH_AES_256_CCM_8
  3615. if (tls && havePSK) {
  3616. suites->suites[idx++] = ECC_BYTE;
  3617. suites->suites[idx++] = TLS_PSK_WITH_AES_256_CCM_8;
  3618. }
  3619. #endif
  3620. #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA384
  3621. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3622. if (tls1_2 && haveDH && havePSK)
  3623. #else
  3624. if (tls && haveDH && havePSK && haveNull)
  3625. #endif
  3626. {
  3627. suites->suites[idx++] = CIPHER_BYTE;
  3628. suites->suites[idx++] = TLS_DHE_PSK_WITH_NULL_SHA384;
  3629. }
  3630. #endif
  3631. #ifdef BUILD_TLS_PSK_WITH_NULL_SHA384
  3632. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3633. if (tls1_2 && havePSK && haveNull)
  3634. #else
  3635. if (tls && havePSK && haveNull)
  3636. #endif
  3637. {
  3638. suites->suites[idx++] = CIPHER_BYTE;
  3639. suites->suites[idx++] = TLS_PSK_WITH_NULL_SHA384;
  3640. }
  3641. #endif
  3642. #ifdef BUILD_TLS_ECDHE_PSK_WITH_NULL_SHA256
  3643. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3644. if (tls1_2 && havePSK && haveNull)
  3645. #else
  3646. if (tls && havePSK && haveNull)
  3647. #endif
  3648. {
  3649. suites->suites[idx++] = ECC_BYTE;
  3650. suites->suites[idx++] = TLS_ECDHE_PSK_WITH_NULL_SHA256;
  3651. }
  3652. #endif
  3653. #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA256
  3654. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3655. if (tls1_2 && haveDH && havePSK && haveNull)
  3656. #else
  3657. if (tls && haveDH && havePSK && haveNull)
  3658. #endif
  3659. {
  3660. suites->suites[idx++] = CIPHER_BYTE;
  3661. suites->suites[idx++] = TLS_DHE_PSK_WITH_NULL_SHA256;
  3662. }
  3663. #endif
  3664. #ifdef BUILD_TLS_PSK_WITH_NULL_SHA256
  3665. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3666. if (tls1_2 && havePSK && haveNull)
  3667. #else
  3668. if (tls && havePSK && haveNull)
  3669. #endif
  3670. {
  3671. suites->suites[idx++] = CIPHER_BYTE;
  3672. suites->suites[idx++] = TLS_PSK_WITH_NULL_SHA256;
  3673. }
  3674. #endif
  3675. #ifdef BUILD_TLS_PSK_WITH_NULL_SHA
  3676. if (tls && havePSK && haveNull) {
  3677. suites->suites[idx++] = CIPHER_BYTE;
  3678. suites->suites[idx++] = TLS_PSK_WITH_NULL_SHA;
  3679. }
  3680. #endif
  3681. #ifdef BUILD_SSL_RSA_WITH_RC4_128_SHA
  3682. if (!dtls && haveRSA && haveStaticRSA) {
  3683. suites->suites[idx++] = CIPHER_BYTE;
  3684. suites->suites[idx++] = SSL_RSA_WITH_RC4_128_SHA;
  3685. }
  3686. #endif
  3687. #ifdef BUILD_SSL_RSA_WITH_RC4_128_MD5
  3688. if (!dtls && haveRSA && haveStaticRSA) {
  3689. suites->suites[idx++] = CIPHER_BYTE;
  3690. suites->suites[idx++] = SSL_RSA_WITH_RC4_128_MD5;
  3691. }
  3692. #endif
  3693. #ifdef BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA
  3694. if (haveRSA && haveStaticRSA) {
  3695. suites->suites[idx++] = CIPHER_BYTE;
  3696. suites->suites[idx++] = SSL_RSA_WITH_3DES_EDE_CBC_SHA;
  3697. }
  3698. #endif
  3699. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
  3700. if (tls && haveRSA && haveStaticRSA) {
  3701. suites->suites[idx++] = CIPHER_BYTE;
  3702. suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_128_CBC_SHA;
  3703. }
  3704. #endif
  3705. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
  3706. if (tls && haveDH && haveRSA && haveStaticRSA) {
  3707. suites->suites[idx++] = CIPHER_BYTE;
  3708. suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA;
  3709. }
  3710. #endif
  3711. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
  3712. if (tls && haveRSA && haveStaticRSA) {
  3713. suites->suites[idx++] = CIPHER_BYTE;
  3714. suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_256_CBC_SHA;
  3715. }
  3716. #endif
  3717. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
  3718. if (tls && haveDH && haveRSA && haveStaticRSA) {
  3719. suites->suites[idx++] = CIPHER_BYTE;
  3720. suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA;
  3721. }
  3722. #endif
  3723. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
  3724. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3725. if (tls1_2 && haveRSA && haveStaticRSA)
  3726. #else
  3727. if (tls && haveRSA && haveStaticRSA)
  3728. #endif
  3729. {
  3730. suites->suites[idx++] = CIPHER_BYTE;
  3731. suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256;
  3732. }
  3733. #endif
  3734. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
  3735. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3736. if (tls1_2 && haveDH && haveRSA && haveStaticRSA)
  3737. #else
  3738. if (tls && haveDH && haveRSA && haveStaticRSA)
  3739. #endif
  3740. {
  3741. suites->suites[idx++] = CIPHER_BYTE;
  3742. suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256;
  3743. }
  3744. #endif
  3745. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256
  3746. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3747. if (tls1_2 && haveRSA && haveStaticRSA)
  3748. #else
  3749. if (tls && haveRSA && haveStaticRSA)
  3750. #endif
  3751. {
  3752. suites->suites[idx++] = CIPHER_BYTE;
  3753. suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256;
  3754. }
  3755. #endif
  3756. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
  3757. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  3758. if (tls1_2 && haveDH && haveRSA && haveStaticRSA)
  3759. #else
  3760. if (tls && haveDH && haveRSA && haveStaticRSA)
  3761. #endif
  3762. {
  3763. suites->suites[idx++] = CIPHER_BYTE;
  3764. suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256;
  3765. }
  3766. #endif
  3767. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  3768. if (tls && haveECC) {
  3769. suites->suites[idx++] = SM_BYTE;
  3770. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3;
  3771. }
  3772. #endif
  3773. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3
  3774. if (tls && haveECC) {
  3775. suites->suites[idx++] = SM_BYTE;
  3776. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3;
  3777. }
  3778. #endif
  3779. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3
  3780. if (tls && haveECC) {
  3781. suites->suites[idx++] = SM_BYTE;
  3782. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3;
  3783. }
  3784. #endif
  3785. #endif /* !WOLFSSL_NO_TLS12 */
  3786. suites->suiteSz = idx;
  3787. if (suites->hashSigAlgoSz == 0) {
  3788. InitSuitesHashSigAlgo(suites->hashSigAlgo, SIG_ALL, tls1_2, keySz,
  3789. &suites->hashSigAlgoSz);
  3790. }
  3791. /* Moved to the end as we set some of the vars but never use them */
  3792. (void)tls; /* shut up compiler */
  3793. (void)tls1_2;
  3794. (void)dtls;
  3795. (void)haveDH;
  3796. (void)havePSK;
  3797. (void)haveStaticRSA;
  3798. (void)haveStaticECC;
  3799. (void)haveECC;
  3800. (void)haveECDSAsig;
  3801. (void)side;
  3802. (void)haveRSA; /* some builds won't read */
  3803. (void)haveRSAsig; /* non ecc builds won't read */
  3804. (void)haveAnon; /* anon ciphers optional */
  3805. (void)haveNull;
  3806. (void)haveFalconSig;
  3807. (void)haveDilithiumSig;
  3808. }
  3809. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_CERTS) || \
  3810. (!defined(NO_WOLFSSL_CLIENT) && (!defined(NO_DH) || defined(HAVE_ECC)))
  3811. /* Decode the signature algorithm.
  3812. *
  3813. * input The encoded signature algorithm.
  3814. * hashalgo The hash algorithm.
  3815. * hsType The signature type.
  3816. */
  3817. void DecodeSigAlg(const byte* input, byte* hashAlgo, byte* hsType)
  3818. {
  3819. *hsType = invalid_sa_algo;
  3820. switch (input[0]) {
  3821. case NEW_SA_MAJOR:
  3822. #ifdef HAVE_ED25519
  3823. /* ED25519: 0x0807 */
  3824. if (input[1] == ED25519_SA_MINOR) {
  3825. *hsType = ed25519_sa_algo;
  3826. /* Hash performed as part of sign/verify operation. */
  3827. *hashAlgo = sha512_mac;
  3828. }
  3829. else
  3830. #endif
  3831. #ifdef HAVE_ED448
  3832. /* ED448: 0x0808 */
  3833. if (input[1] == ED448_SA_MINOR) {
  3834. *hsType = ed448_sa_algo;
  3835. /* Hash performed as part of sign/verify operation. */
  3836. *hashAlgo = sha512_mac;
  3837. }
  3838. else
  3839. #endif
  3840. #ifdef WC_RSA_PSS
  3841. /* PSS PSS signatures: 0x080[9-b] */
  3842. if (input[1] >= pss_sha256 && input[1] <= pss_sha512) {
  3843. *hsType = rsa_pss_pss_algo;
  3844. *hashAlgo = PSS_PSS_HASH_TO_MAC(input[1]);
  3845. }
  3846. else
  3847. #endif
  3848. {
  3849. *hsType = input[0];
  3850. *hashAlgo = input[1];
  3851. }
  3852. break;
  3853. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  3854. case SM2_SA_MAJOR:
  3855. /* SM2: 0x0708 */
  3856. if (input[1] == SM2_SA_MINOR) {
  3857. *hsType = sm2_sa_algo;
  3858. /* Hash performed as part of sign/verify operation. */
  3859. *hashAlgo = sm3_mac;
  3860. }
  3861. break;
  3862. #endif
  3863. #if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM)
  3864. case PQC_SA_MAJOR:
  3865. /* Hash performed as part of sign/verify operation.
  3866. * However, if we want a dual alg signature with a
  3867. * classic algorithm as alternative, we need an explicit
  3868. * hash algo here.
  3869. */
  3870. #ifdef HAVE_FALCON
  3871. if (input[1] == FALCON_LEVEL1_SA_MINOR) {
  3872. *hsType = falcon_level1_sa_algo;
  3873. *hashAlgo = sha256_mac;
  3874. }
  3875. else if (input[1] == FALCON_LEVEL5_SA_MINOR) {
  3876. *hsType = falcon_level5_sa_algo;
  3877. *hashAlgo = sha512_mac;
  3878. }
  3879. #endif /* HAVE_FALCON */
  3880. #ifdef HAVE_DILITHIUM
  3881. if (input[1] == DILITHIUM_LEVEL2_SA_MINOR) {
  3882. *hsType = dilithium_level2_sa_algo;
  3883. *hashAlgo = sha256_mac;
  3884. }
  3885. else if (input[1] == DILITHIUM_LEVEL3_SA_MINOR) {
  3886. *hsType = dilithium_level3_sa_algo;
  3887. *hashAlgo = sha384_mac;
  3888. }
  3889. else if (input[1] == DILITHIUM_LEVEL5_SA_MINOR) {
  3890. *hsType = dilithium_level5_sa_algo;
  3891. *hashAlgo = sha512_mac;
  3892. }
  3893. #endif /* HAVE_DILITHIUM */
  3894. break;
  3895. #endif
  3896. default:
  3897. *hashAlgo = input[0];
  3898. *hsType = input[1];
  3899. break;
  3900. }
  3901. }
  3902. #endif /* !NO_WOLFSSL_SERVER || !NO_CERTS */
  3903. #ifndef WOLFSSL_NO_TLS12
  3904. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
  3905. #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  3906. defined(HAVE_CURVE448) || (!defined(NO_RSA) && defined(WC_RSA_PSS))
  3907. enum wc_HashType HashAlgoToType(int hashAlgo)
  3908. {
  3909. switch (hashAlgo) {
  3910. #ifdef WOLFSSL_SHA512
  3911. case sha512_mac:
  3912. return WC_HASH_TYPE_SHA512;
  3913. #endif
  3914. #ifdef WOLFSSL_SHA384
  3915. case sha384_mac:
  3916. return WC_HASH_TYPE_SHA384;
  3917. #endif
  3918. #ifdef WOLFSSL_SM3
  3919. case sm3_mac:
  3920. return WC_HASH_TYPE_SM3;
  3921. #endif
  3922. #ifndef NO_SHA256
  3923. case sha256_mac:
  3924. return WC_HASH_TYPE_SHA256;
  3925. #endif
  3926. #ifdef WOLFSSL_SHA224
  3927. case sha224_mac:
  3928. return WC_HASH_TYPE_SHA224;
  3929. #endif
  3930. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  3931. defined(WOLFSSL_ALLOW_TLS_SHA1))
  3932. case sha_mac:
  3933. return WC_HASH_TYPE_SHA;
  3934. #endif
  3935. default:
  3936. WOLFSSL_MSG("Bad hash sig algo");
  3937. break;
  3938. }
  3939. return WC_HASH_TYPE_NONE;
  3940. }
  3941. #endif /* !NO_DH || HAVE_ECC || (!NO_RSA && WC_RSA_PSS) */
  3942. #endif /* !NO_WOLFSSL_SERVER || !NO_WOLFSSL_CLIENT */
  3943. #endif /* !WOLFSSL_NO_TLS12 */
  3944. #ifndef NO_CERTS
  3945. void InitX509Name(WOLFSSL_X509_NAME* name, int dynamicFlag, void* heap)
  3946. {
  3947. (void)dynamicFlag;
  3948. if (name != NULL) {
  3949. XMEMSET(name, 0, sizeof(WOLFSSL_X509_NAME));
  3950. name->name = name->staticName;
  3951. name->heap = heap;
  3952. name->dynamicName = 0;
  3953. }
  3954. }
  3955. void FreeX509Name(WOLFSSL_X509_NAME* name)
  3956. {
  3957. if (name != NULL) {
  3958. if (name->dynamicName) {
  3959. XFREE(name->name, name->heap, DYNAMIC_TYPE_SUBJECT_CN);
  3960. name->name = NULL;
  3961. }
  3962. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  3963. {
  3964. int i;
  3965. for (i = 0; i < MAX_NAME_ENTRIES; i++) {
  3966. if (name->entry[i].object != NULL)
  3967. wolfSSL_ASN1_OBJECT_free(name->entry[i].object);
  3968. if (name->entry[i].value != NULL)
  3969. wolfSSL_ASN1_STRING_free(name->entry[i].value);
  3970. XMEMSET(&name->entry[i], 0, sizeof(WOLFSSL_X509_NAME_ENTRY));
  3971. }
  3972. }
  3973. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  3974. #ifdef OPENSSL_ALL
  3975. if (name->entries) {
  3976. wolfSSL_sk_X509_NAME_ENTRY_free(name->entries);
  3977. name->entries = NULL;
  3978. }
  3979. #endif
  3980. }
  3981. }
  3982. /* Initialize wolfSSL X509 type */
  3983. void InitX509(WOLFSSL_X509* x509, int dynamicFlag, void* heap)
  3984. {
  3985. if (x509 == NULL) {
  3986. WOLFSSL_MSG("Null parameter passed in!");
  3987. return;
  3988. }
  3989. XMEMSET(x509, 0, sizeof(WOLFSSL_X509));
  3990. x509->heap = heap;
  3991. InitX509Name(&x509->issuer, 0, heap);
  3992. InitX509Name(&x509->subject, 0, heap);
  3993. x509->dynamicMemory = (byte)dynamicFlag;
  3994. #if defined(OPENSSL_EXTRA_X509_SMALL) || defined(OPENSSL_EXTRA)
  3995. {
  3996. int ret;
  3997. wolfSSL_RefInit(&x509->ref, &ret);
  3998. (void)ret;
  3999. }
  4000. #endif
  4001. }
  4002. /* Free wolfSSL X509 type */
  4003. void FreeX509(WOLFSSL_X509* x509)
  4004. {
  4005. #if defined(WOLFSSL_CERT_REQ) && defined(OPENSSL_ALL) \
  4006. && defined( WOLFSSL_CUSTOM_OID)
  4007. int idx;
  4008. #endif /* WOLFSSL_CERT_REQ && OPENSSL_ALL && WOLFSSL_CUSTOM_OID */
  4009. if (x509 == NULL)
  4010. return;
  4011. FreeX509Name(&x509->issuer);
  4012. FreeX509Name(&x509->subject);
  4013. if (x509->pubKey.buffer) {
  4014. XFREE(x509->pubKey.buffer, x509->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  4015. x509->pubKey.buffer = NULL;
  4016. }
  4017. FreeDer(&x509->derCert);
  4018. XFREE(x509->sig.buffer, x509->heap, DYNAMIC_TYPE_SIGNATURE);
  4019. x509->sig.buffer = NULL;
  4020. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  4021. if (x509->authKeyIdSrc != NULL) {
  4022. XFREE(x509->authKeyIdSrc, x509->heap, DYNAMIC_TYPE_X509_EXT);
  4023. }
  4024. else {
  4025. XFREE(x509->authKeyId, x509->heap, DYNAMIC_TYPE_X509_EXT);
  4026. }
  4027. x509->authKeyIdSrc = NULL;
  4028. x509->authKeyId = NULL;
  4029. XFREE(x509->subjKeyId, x509->heap, DYNAMIC_TYPE_X509_EXT);
  4030. x509->subjKeyId = NULL;
  4031. wolfSSL_ASN1_STRING_free(x509->subjKeyIdStr);
  4032. x509->subjKeyIdStr = NULL;
  4033. XFREE(x509->authInfo, x509->heap, DYNAMIC_TYPE_X509_EXT);
  4034. x509->authInfo = NULL;
  4035. XFREE(x509->rawCRLInfo, x509->heap, DYNAMIC_TYPE_X509_EXT);
  4036. x509->rawCRLInfo = NULL;
  4037. XFREE(x509->CRLInfo, x509->heap, DYNAMIC_TYPE_X509_EXT);
  4038. x509->CRLInfo = NULL;
  4039. #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \
  4040. defined(WOLFSSL_QT)
  4041. XFREE(x509->authInfoCaIssuer, x509->heap, DYNAMIC_TYPE_X509_EXT);
  4042. if (x509->ext_sk != NULL) {
  4043. wolfSSL_sk_X509_EXTENSION_pop_free(x509->ext_sk, NULL);
  4044. }
  4045. if (x509->ext_sk_full != NULL) {
  4046. wolfSSL_sk_X509_EXTENSION_pop_free(x509->ext_sk_full, NULL);
  4047. }
  4048. #endif /* OPENSSL_ALL || WOLFSSL_QT */
  4049. #ifdef OPENSSL_EXTRA
  4050. /* Free serialNumber that was set by wolfSSL_X509_get_serialNumber */
  4051. if (x509->serialNumber != NULL) {
  4052. wolfSSL_ASN1_INTEGER_free(x509->serialNumber);
  4053. }
  4054. #endif
  4055. if (x509->extKeyUsageSrc != NULL) {
  4056. XFREE(x509->extKeyUsageSrc, x509->heap, DYNAMIC_TYPE_X509_EXT);
  4057. x509->extKeyUsageSrc= NULL;
  4058. }
  4059. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  4060. #if defined(OPENSSL_ALL)
  4061. if (x509->algor.algorithm) {
  4062. wolfSSL_ASN1_OBJECT_free(x509->algor.algorithm);
  4063. x509->algor.algorithm = NULL;
  4064. }
  4065. if (x509->key.algor) {
  4066. wolfSSL_X509_ALGOR_free(x509->key.algor);
  4067. x509->key.algor = NULL;
  4068. }
  4069. if (x509->key.pkey) {
  4070. wolfSSL_EVP_PKEY_free(x509->key.pkey);
  4071. x509->key.pkey = NULL;
  4072. }
  4073. if (x509->subjAltNameSrc != NULL) {
  4074. XFREE(x509->subjAltNameSrc, x509->heap, DYNAMIC_TYPE_X509_EXT);
  4075. x509->subjAltNameSrc= NULL;
  4076. }
  4077. #endif /* OPENSSL_ALL */
  4078. #if defined(WOLFSSL_CERT_REQ) && defined(OPENSSL_ALL)
  4079. if (x509->reqAttributes) {
  4080. wolfSSL_sk_pop_free(x509->reqAttributes, NULL);
  4081. }
  4082. #ifdef WOLFSSL_CUSTOM_OID
  4083. for (idx = 0; idx < x509->customExtCount; idx++) {
  4084. XFREE(x509->custom_exts[idx].oid, x509->heap,
  4085. DYNAMIC_TYPE_X509_EXT);
  4086. XFREE(x509->custom_exts[idx].val, x509->heap,
  4087. DYNAMIC_TYPE_X509_EXT);
  4088. }
  4089. #endif /* WOLFSSL_CUSTOM_OID */
  4090. #endif /* WOLFSSL_CERT_REQ && OPENSSL_ALL */
  4091. if (x509->altNames) {
  4092. FreeAltNames(x509->altNames, x509->heap);
  4093. x509->altNames = NULL;
  4094. }
  4095. #ifdef WOLFSSL_DUAL_ALG_CERTS
  4096. XFREE(x509->sapkiDer, x509->heap, DYNAMIC_TYPE_X509_EXT);
  4097. x509->sapkiDer = NULL;
  4098. XFREE(x509->altSigAlgDer, x509->heap, DYNAMIC_TYPE_X509_EXT);
  4099. x509->altSigAlgDer = NULL;
  4100. if (x509->altSigValDer) {
  4101. XFREE(x509->altSigValDer, x509->heap, DYNAMIC_TYPE_X509_EXT);
  4102. x509->altSigValDer= NULL;
  4103. }
  4104. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  4105. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
  4106. wolfSSL_RefFree(&x509->ref);
  4107. #endif
  4108. }
  4109. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
  4110. #if !defined(WOLFSSL_NO_TLS12)
  4111. /* Encode the signature algorithm into buffer.
  4112. *
  4113. * hashalgo The hash algorithm.
  4114. * hsType The signature type.
  4115. * output The buffer to encode into.
  4116. */
  4117. static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output)
  4118. {
  4119. switch (hsType) {
  4120. #ifdef HAVE_ECC
  4121. case ecc_dsa_sa_algo:
  4122. output[0] = hashAlgo;
  4123. output[1] = ecc_dsa_sa_algo;
  4124. break;
  4125. #endif
  4126. #ifdef HAVE_ED25519
  4127. case ed25519_sa_algo:
  4128. output[0] = ED25519_SA_MAJOR;
  4129. output[1] = ED25519_SA_MINOR;
  4130. (void)hashAlgo;
  4131. break;
  4132. #endif
  4133. #ifdef HAVE_ED448
  4134. case ed448_sa_algo:
  4135. output[0] = ED448_SA_MAJOR;
  4136. output[1] = ED448_SA_MINOR;
  4137. (void)hashAlgo;
  4138. break;
  4139. #endif
  4140. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  4141. case sm2_sa_algo:
  4142. output[0] = SM2_SA_MAJOR;
  4143. output[1] = SM2_SA_MINOR;
  4144. (void)hashAlgo;
  4145. break;
  4146. #endif
  4147. #ifndef NO_RSA
  4148. case rsa_sa_algo:
  4149. output[0] = hashAlgo;
  4150. output[1] = rsa_sa_algo;
  4151. break;
  4152. #ifdef WC_RSA_PSS
  4153. /* PSS signatures: 0x080[4-6] */
  4154. case rsa_pss_sa_algo:
  4155. output[0] = rsa_pss_sa_algo;
  4156. output[1] = hashAlgo;
  4157. break;
  4158. #endif
  4159. #endif
  4160. default:
  4161. break;
  4162. }
  4163. (void)hashAlgo;
  4164. (void)output;
  4165. }
  4166. #endif
  4167. #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  4168. static void SetDigest(WOLFSSL* ssl, int hashAlgo)
  4169. {
  4170. switch (hashAlgo) {
  4171. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  4172. defined(WOLFSSL_ALLOW_TLS_SHA1))
  4173. case sha_mac:
  4174. ssl->options.dontFreeDigest = 1;
  4175. ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha;
  4176. ssl->buffers.digest.length = WC_SHA_DIGEST_SIZE;
  4177. break;
  4178. #endif /* !NO_SHA */
  4179. #ifndef NO_SHA256
  4180. case sha256_mac:
  4181. ssl->options.dontFreeDigest = 1;
  4182. ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha256;
  4183. ssl->buffers.digest.length = WC_SHA256_DIGEST_SIZE;
  4184. break;
  4185. #endif /* !NO_SHA256 */
  4186. #ifdef WOLFSSL_SM3
  4187. case sm3_mac:
  4188. ssl->options.dontFreeDigest = 1;
  4189. ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sm3;
  4190. ssl->buffers.digest.length = WC_SM3_DIGEST_SIZE;
  4191. break;
  4192. #endif /* WOLFSSL_SM2 */
  4193. #ifdef WOLFSSL_SHA384
  4194. case sha384_mac:
  4195. ssl->options.dontFreeDigest = 1;
  4196. ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha384;
  4197. ssl->buffers.digest.length = WC_SHA384_DIGEST_SIZE;
  4198. break;
  4199. #endif /* WOLFSSL_SHA384 */
  4200. #ifdef WOLFSSL_SHA512
  4201. case sha512_mac:
  4202. ssl->options.dontFreeDigest = 1;
  4203. ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha512;
  4204. ssl->buffers.digest.length = WC_SHA512_DIGEST_SIZE;
  4205. break;
  4206. #endif /* WOLFSSL_SHA512 */
  4207. default:
  4208. break;
  4209. } /* switch */
  4210. }
  4211. #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_NO_CLIENT_AUTH */
  4212. #endif /* !NO_WOLFSSL_SERVER || !NO_WOLFSSL_CLIENT */
  4213. #endif /* !NO_CERTS */
  4214. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  4215. static word32 MacSize(const WOLFSSL* ssl)
  4216. {
  4217. #ifdef HAVE_TRUNCATED_HMAC
  4218. word32 digestSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  4219. : ssl->specs.hash_size;
  4220. #else
  4221. word32 digestSz = ssl->specs.hash_size;
  4222. #endif
  4223. return digestSz;
  4224. }
  4225. #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */
  4226. #ifndef NO_RSA
  4227. #if !defined(WOLFSSL_NO_TLS12) || \
  4228. (defined(WC_RSA_PSS) && defined(HAVE_PK_CALLBACKS))
  4229. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
  4230. static int TypeHash(int hashAlgo)
  4231. {
  4232. switch (hashAlgo) {
  4233. #ifdef WOLFSSL_SHA512
  4234. case sha512_mac:
  4235. return SHA512h;
  4236. #endif
  4237. #ifdef WOLFSSL_SHA384
  4238. case sha384_mac:
  4239. return SHA384h;
  4240. #endif
  4241. #ifndef NO_SHA256
  4242. case sha256_mac:
  4243. return SHA256h;
  4244. #endif
  4245. #ifdef WOLFSSL_SHA224
  4246. case sha224_mac:
  4247. return SHA224h;
  4248. #endif
  4249. #ifndef NO_SHA
  4250. case sha_mac:
  4251. return SHAh;
  4252. #endif
  4253. default:
  4254. break;
  4255. }
  4256. return 0;
  4257. }
  4258. #endif /* !NO_WOLFSSL_SERVER && !NO_WOLFSSL_CLIENT */
  4259. #endif /* !WOLFSSL_NO_TLS12 */
  4260. #if defined(WC_RSA_PSS)
  4261. int ConvertHashPss(int hashAlgo, enum wc_HashType* hashType, int* mgf)
  4262. {
  4263. switch (hashAlgo) {
  4264. #ifdef WOLFSSL_SHA512
  4265. case sha512_mac:
  4266. *hashType = WC_HASH_TYPE_SHA512;
  4267. if (mgf != NULL)
  4268. *mgf = WC_MGF1SHA512;
  4269. break;
  4270. #endif
  4271. #ifdef WOLFSSL_SHA384
  4272. case sha384_mac:
  4273. *hashType = WC_HASH_TYPE_SHA384;
  4274. if (mgf != NULL)
  4275. *mgf = WC_MGF1SHA384;
  4276. break;
  4277. #endif
  4278. #ifndef NO_SHA256
  4279. case sha256_mac:
  4280. *hashType = WC_HASH_TYPE_SHA256;
  4281. if (mgf != NULL)
  4282. *mgf = WC_MGF1SHA256;
  4283. break;
  4284. #endif
  4285. default:
  4286. return BAD_FUNC_ARG;
  4287. }
  4288. return 0;
  4289. }
  4290. #endif
  4291. #if !defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  4292. int RsaSign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
  4293. word32* outSz, int sigAlgo, int hashAlgo, RsaKey* key,
  4294. DerBuffer* keyBufInfo)
  4295. {
  4296. int ret;
  4297. #ifdef HAVE_PK_CALLBACKS
  4298. const byte* keyBuf = NULL;
  4299. word32 keySz = 0;
  4300. if (keyBufInfo) {
  4301. keyBuf = keyBufInfo->buffer;
  4302. keySz = keyBufInfo->length;
  4303. }
  4304. #endif
  4305. (void)ssl;
  4306. (void)keyBufInfo;
  4307. (void)sigAlgo;
  4308. (void)hashAlgo;
  4309. WOLFSSL_ENTER("RsaSign");
  4310. #ifdef WOLFSSL_ASYNC_CRYPT
  4311. /* initialize event */
  4312. if (key) {
  4313. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  4314. if (ret != 0)
  4315. return ret;
  4316. }
  4317. #endif
  4318. #if defined(WC_RSA_PSS)
  4319. if (sigAlgo == rsa_pss_sa_algo) {
  4320. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  4321. int mgf = 0;
  4322. ret = ConvertHashPss(hashAlgo, &hashType, &mgf);
  4323. if (ret != 0)
  4324. return ret;
  4325. #if defined(HAVE_PK_CALLBACKS)
  4326. if (ssl->ctx->RsaPssSignCb) {
  4327. void* ctx = wolfSSL_GetRsaPssSignCtx(ssl);
  4328. ret = ssl->ctx->RsaPssSignCb(ssl, in, inSz, out, outSz,
  4329. TypeHash(hashAlgo), mgf,
  4330. keyBuf, keySz, ctx);
  4331. }
  4332. else
  4333. #endif
  4334. {
  4335. ret = wc_RsaPSS_Sign(in, inSz, out, *outSz, hashType, mgf, key,
  4336. ssl->rng);
  4337. }
  4338. }
  4339. else
  4340. #endif
  4341. #if defined(HAVE_PK_CALLBACKS)
  4342. if (ssl->ctx->RsaSignCb) {
  4343. void* ctx = wolfSSL_GetRsaSignCtx(ssl);
  4344. ret = ssl->ctx->RsaSignCb(ssl, in, inSz, out, outSz, keyBuf, keySz,
  4345. ctx);
  4346. }
  4347. else
  4348. #endif /*HAVE_PK_CALLBACKS */
  4349. ret = wc_RsaSSL_Sign(in, inSz, out, *outSz, key, ssl->rng);
  4350. /* Handle async pending response */
  4351. #ifdef WOLFSSL_ASYNC_CRYPT
  4352. if (key && ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  4353. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  4354. }
  4355. #endif /* WOLFSSL_ASYNC_CRYPT */
  4356. /* For positive response return in outSz */
  4357. if (ret > 0) {
  4358. *outSz = (word32)ret;
  4359. ret = 0;
  4360. }
  4361. WOLFSSL_LEAVE("RsaSign", ret);
  4362. return ret;
  4363. }
  4364. #endif
  4365. int RsaVerify(WOLFSSL* ssl, byte* in, word32 inSz, byte** out, int sigAlgo,
  4366. int hashAlgo, RsaKey* key, buffer* keyBufInfo)
  4367. {
  4368. int ret = WC_NO_ERR_TRACE(SIG_VERIFY_E);
  4369. #ifdef HAVE_PK_CALLBACKS
  4370. const byte* keyBuf = NULL;
  4371. word32 keySz = 0;
  4372. if (keyBufInfo) {
  4373. keyBuf = keyBufInfo->buffer;
  4374. keySz = keyBufInfo->length;
  4375. }
  4376. #endif
  4377. (void)ssl;
  4378. (void)keyBufInfo;
  4379. (void)sigAlgo;
  4380. (void)hashAlgo;
  4381. WOLFSSL_ENTER("RsaVerify");
  4382. #ifdef WOLFSSL_ASYNC_CRYPT
  4383. /* initialize event */
  4384. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  4385. if (ret != 0)
  4386. return ret;
  4387. #endif
  4388. #if defined(WC_RSA_PSS)
  4389. if (sigAlgo == rsa_pss_sa_algo) {
  4390. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  4391. int mgf = 0;
  4392. ret = ConvertHashPss(hashAlgo, &hashType, &mgf);
  4393. if (ret != 0)
  4394. return ret;
  4395. #ifdef HAVE_PK_CALLBACKS
  4396. if (ssl->ctx->RsaPssVerifyCb) {
  4397. void* ctx = wolfSSL_GetRsaPssVerifyCtx(ssl);
  4398. ret = ssl->ctx->RsaPssVerifyCb(ssl, in, inSz, out,
  4399. TypeHash(hashAlgo), mgf,
  4400. keyBuf, keySz, ctx);
  4401. }
  4402. else
  4403. #endif /*HAVE_PK_CALLBACKS */
  4404. ret = wc_RsaPSS_VerifyInline(in, inSz, out, hashType, mgf, key);
  4405. }
  4406. else
  4407. #endif
  4408. #ifdef HAVE_PK_CALLBACKS
  4409. if (ssl->ctx->RsaVerifyCb) {
  4410. void* ctx = wolfSSL_GetRsaVerifyCtx(ssl);
  4411. ret = ssl->ctx->RsaVerifyCb(ssl, in, inSz, out, keyBuf, keySz, ctx);
  4412. }
  4413. #if !defined(WOLFSSL_RENESAS_FSPSM_TLS) && \
  4414. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  4415. else
  4416. #else
  4417. if (!ssl->ctx->RsaVerifyCb || ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
  4418. #endif
  4419. #endif /*HAVE_PK_CALLBACKS */
  4420. {
  4421. ret = wc_RsaSSL_VerifyInline(in, inSz, out, key);
  4422. }
  4423. /* Handle async pending response */
  4424. #ifdef WOLFSSL_ASYNC_CRYPT
  4425. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  4426. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  4427. }
  4428. #endif /* WOLFSSL_ASYNC_CRYPT */
  4429. WOLFSSL_LEAVE("RsaVerify", ret);
  4430. return ret;
  4431. }
  4432. /* Verify RSA signature, 0 on success */
  4433. /* This function is used to check the sign result */
  4434. int VerifyRsaSign(WOLFSSL* ssl, byte* verifySig, word32 sigSz,
  4435. const byte* plain, word32 plainSz, int sigAlgo, int hashAlgo, RsaKey* key,
  4436. DerBuffer* keyBufInfo)
  4437. {
  4438. byte* out = NULL; /* inline result */
  4439. int ret;
  4440. #ifdef HAVE_PK_CALLBACKS
  4441. const byte* keyBuf = NULL;
  4442. word32 keySz = 0;
  4443. if (keyBufInfo) {
  4444. keyBuf = keyBufInfo->buffer;
  4445. keySz = keyBufInfo->length;
  4446. }
  4447. #endif
  4448. (void)ssl;
  4449. (void)keyBufInfo;
  4450. (void)sigAlgo;
  4451. (void)hashAlgo;
  4452. WOLFSSL_ENTER("VerifyRsaSign");
  4453. if (verifySig == NULL || plain == NULL) {
  4454. return BAD_FUNC_ARG;
  4455. }
  4456. if (sigSz > ENCRYPT_LEN) {
  4457. WOLFSSL_MSG("Signature buffer too big");
  4458. return BUFFER_E;
  4459. }
  4460. #ifdef WOLFSSL_ASYNC_CRYPT
  4461. /* initialize event */
  4462. if (key) {
  4463. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  4464. if (ret != 0)
  4465. return ret;
  4466. }
  4467. #endif
  4468. #if defined(WC_RSA_PSS)
  4469. if (sigAlgo == rsa_pss_sa_algo) {
  4470. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  4471. int mgf = 0;
  4472. ret = ConvertHashPss(hashAlgo, &hashType, &mgf);
  4473. if (ret != 0)
  4474. return ret;
  4475. #ifdef HAVE_PK_CALLBACKS
  4476. if (ssl->ctx->RsaPssSignCheckCb) {
  4477. /* The key buffer includes private/public portion,
  4478. but only public is used */
  4479. /* If HSM hardware is checking the signature result you can
  4480. optionally skip the sign check and return 0 */
  4481. /* The ctx here is the RsaSignCtx set using wolfSSL_SetRsaSignCtx */
  4482. void* ctx = wolfSSL_GetRsaPssSignCtx(ssl);
  4483. ret = ssl->ctx->RsaPssSignCheckCb(ssl, verifySig, sigSz, &out,
  4484. TypeHash(hashAlgo), mgf,
  4485. keyBuf, keySz, ctx);
  4486. if (ret > 0) {
  4487. ret = wc_RsaPSS_CheckPadding(plain, plainSz, out, (word32)ret,
  4488. hashType);
  4489. if (ret != 0) {
  4490. ret = VERIFY_CERT_ERROR;
  4491. WOLFSSL_ERROR_VERBOSE(ret);
  4492. }
  4493. }
  4494. }
  4495. else
  4496. #endif /* HAVE_PK_CALLBACKS */
  4497. {
  4498. ret = wc_RsaPSS_VerifyInline(verifySig, sigSz, &out, hashType, mgf,
  4499. key);
  4500. if (ret > 0) {
  4501. #ifdef HAVE_SELFTEST
  4502. ret = wc_RsaPSS_CheckPadding(plain, plainSz, out, ret,
  4503. hashType);
  4504. #else
  4505. ret = wc_RsaPSS_CheckPadding_ex(plain, plainSz, out, (word32)ret,
  4506. hashType, -1,
  4507. mp_count_bits(&key->n));
  4508. #endif
  4509. if (ret != 0) {
  4510. ret = VERIFY_CERT_ERROR;
  4511. WOLFSSL_ERROR_VERBOSE(ret);
  4512. }
  4513. }
  4514. }
  4515. }
  4516. else
  4517. #endif /* WC_RSA_PSS */
  4518. {
  4519. #ifdef HAVE_PK_CALLBACKS
  4520. if (ssl->ctx->RsaSignCheckCb) {
  4521. /* The key buffer includes private/public portion,
  4522. but only public is used */
  4523. /* If HSM hardware is checking the signature result you can
  4524. optionally skip the sign check and return 0 */
  4525. /* The ctx here is the RsaSignCtx set using wolfSSL_SetRsaSignCtx */
  4526. void* ctx = wolfSSL_GetRsaSignCtx(ssl);
  4527. ret = ssl->ctx->RsaSignCheckCb(ssl, verifySig, sigSz, &out,
  4528. keyBuf, keySz, ctx);
  4529. }
  4530. else
  4531. #endif /* HAVE_PK_CALLBACKS */
  4532. {
  4533. ret = wc_RsaSSL_VerifyInline(verifySig, sigSz, &out, key);
  4534. }
  4535. if (ret > 0) {
  4536. if (ret != (int)plainSz || !out ||
  4537. XMEMCMP(plain, out, plainSz) != 0) {
  4538. WOLFSSL_MSG("RSA Signature verification failed");
  4539. ret = RSA_SIGN_FAULT;
  4540. WOLFSSL_ERROR_VERBOSE(ret);
  4541. }
  4542. else {
  4543. ret = 0; /* RSA reset */
  4544. }
  4545. }
  4546. }
  4547. /* Handle async pending response */
  4548. #ifdef WOLFSSL_ASYNC_CRYPT
  4549. if (key && ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  4550. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  4551. }
  4552. #endif /* WOLFSSL_ASYNC_CRYPT */
  4553. WOLFSSL_LEAVE("VerifyRsaSign", ret);
  4554. return ret;
  4555. }
  4556. #ifndef WOLFSSL_NO_TLS12
  4557. #if !defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  4558. int RsaDec(WOLFSSL* ssl, byte* in, word32 inSz, byte** out, word32* outSz,
  4559. RsaKey* key, DerBuffer* keyBufInfo)
  4560. {
  4561. byte *outTmp;
  4562. byte mask;
  4563. int ret;
  4564. #ifdef HAVE_PK_CALLBACKS
  4565. const byte* keyBuf = NULL;
  4566. word32 keySz = 0;
  4567. if (keyBufInfo) {
  4568. keyBuf = keyBufInfo->buffer;
  4569. keySz = keyBufInfo->length;
  4570. }
  4571. #endif
  4572. (void)ssl;
  4573. (void)keyBufInfo;
  4574. WOLFSSL_ENTER("RsaDec");
  4575. outTmp = *out;
  4576. #ifdef WOLFSSL_ASYNC_CRYPT
  4577. /* initialize event */
  4578. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  4579. if (ret != 0)
  4580. return ret;
  4581. #endif
  4582. #ifdef HAVE_PK_CALLBACKS
  4583. if (ssl->ctx->RsaDecCb) {
  4584. void* ctx = wolfSSL_GetRsaDecCtx(ssl);
  4585. ret = ssl->ctx->RsaDecCb(ssl, in, inSz, &outTmp, keyBuf, keySz, ctx);
  4586. }
  4587. else
  4588. #endif /* HAVE_PK_CALLBACKS */
  4589. {
  4590. #ifdef WC_RSA_BLINDING
  4591. ret = wc_RsaSetRNG(key, ssl->rng);
  4592. if (ret != 0)
  4593. return ret;
  4594. #endif
  4595. ret = wc_RsaPrivateDecryptInline(in, inSz, &outTmp, key);
  4596. }
  4597. /* Handle async pending response */
  4598. #ifdef WOLFSSL_ASYNC_CRYPT
  4599. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  4600. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  4601. }
  4602. #endif /* WOLFSSL_ASYNC_CRYPT */
  4603. mask = ctMaskGT(ret, 0);
  4604. *outSz = (word32)(ret & (int)(sword8)mask);
  4605. ret &= (int)(sword8)(~mask);
  4606. /* Copy pointer */
  4607. ctMaskCopy(mask, (byte*)out, (byte*)&outTmp, sizeof(*out));
  4608. WOLFSSL_LEAVE("RsaDec", ret);
  4609. return ret;
  4610. }
  4611. #endif /* !NO_WOLFSSL_SERVER) || !WOLFSSL_NO_CLIENT_AUTH */
  4612. int RsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, word32* outSz,
  4613. RsaKey* key, buffer* keyBufInfo)
  4614. {
  4615. int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
  4616. #ifdef HAVE_PK_CALLBACKS
  4617. const byte* keyBuf = NULL;
  4618. word32 keySz = 0;
  4619. if (keyBufInfo) {
  4620. keyBuf = keyBufInfo->buffer;
  4621. keySz = keyBufInfo->length;
  4622. }
  4623. #endif
  4624. (void)ssl;
  4625. (void)keyBufInfo;
  4626. WOLFSSL_ENTER("RsaEnc");
  4627. #ifdef WOLFSSL_ASYNC_CRYPT
  4628. /* initialize event */
  4629. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  4630. if (ret != 0)
  4631. return ret;
  4632. #endif
  4633. #ifdef HAVE_PK_CALLBACKS
  4634. if (ssl->ctx->RsaEncCb) {
  4635. void* ctx = wolfSSL_GetRsaEncCtx(ssl);
  4636. ret = ssl->ctx->RsaEncCb(ssl, in, inSz, out, outSz, keyBuf, keySz, ctx);
  4637. }
  4638. #if !defined(WOLFSSL_RENESAS_FSPSM_TLS) && \
  4639. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  4640. else
  4641. #else
  4642. if (!ssl->ctx->RsaEncCb || ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
  4643. #endif
  4644. #endif /* HAVE_PK_CALLBACKS */
  4645. {
  4646. ret = wc_RsaPublicEncrypt(in, inSz, out, *outSz, key, ssl->rng);
  4647. }
  4648. /* Handle async pending response */
  4649. #ifdef WOLFSSL_ASYNC_CRYPT
  4650. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  4651. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  4652. }
  4653. #endif /* WOLFSSL_ASYNC_CRYPT */
  4654. /* For positive response return in outSz */
  4655. if (ret > 0) {
  4656. *outSz = (word32)ret;
  4657. ret = 0;
  4658. }
  4659. WOLFSSL_LEAVE("RsaEnc", ret);
  4660. return ret;
  4661. }
  4662. #endif /* !WOLFSSL_NO_TLS12 */
  4663. #endif /* NO_RSA */
  4664. #ifdef HAVE_ECC
  4665. int EccSign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
  4666. word32* outSz, ecc_key* key, DerBuffer* keyBufInfo)
  4667. {
  4668. int ret;
  4669. #ifdef HAVE_PK_CALLBACKS
  4670. const byte* keyBuf = NULL;
  4671. word32 keySz = 0;
  4672. if (keyBufInfo) {
  4673. keyBuf = keyBufInfo->buffer;
  4674. keySz = keyBufInfo->length;
  4675. }
  4676. #endif
  4677. (void)ssl;
  4678. (void)keyBufInfo;
  4679. WOLFSSL_ENTER("EccSign");
  4680. #ifdef WOLFSSL_ASYNC_CRYPT
  4681. /* initialize event */
  4682. if (key) {
  4683. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  4684. if (ret != 0)
  4685. return ret;
  4686. }
  4687. #endif
  4688. #if defined(HAVE_PK_CALLBACKS)
  4689. if (ssl->ctx->EccSignCb) {
  4690. void* ctx = wolfSSL_GetEccSignCtx(ssl);
  4691. if (ctx == NULL) {
  4692. /* Try to get the WOLFSSL_CTX EccSignCtx*/
  4693. ctx = wolfSSL_CTX_GetEccSignCtx(ssl->ctx);
  4694. }
  4695. ret = ssl->ctx->EccSignCb(ssl, in, inSz, out, outSz, keyBuf,
  4696. keySz, ctx);
  4697. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  4698. if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
  4699. ret = wc_ecc_sign_hash(in, inSz, out, outSz, ssl->rng, key);
  4700. }
  4701. #endif /* WOLFSSL_RENESAS_TSIP_TLS */
  4702. }
  4703. else
  4704. #endif /* HAVE_PK_CALLBACKS */
  4705. {
  4706. ret = wc_ecc_sign_hash(in, inSz, out, outSz, ssl->rng, key);
  4707. }
  4708. /* Handle async pending response */
  4709. #ifdef WOLFSSL_ASYNC_CRYPT
  4710. if (key && ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  4711. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  4712. }
  4713. #endif /* WOLFSSL_ASYNC_CRYPT */
  4714. WOLFSSL_LEAVE("EccSign", ret);
  4715. return ret;
  4716. }
  4717. int EccVerify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* out,
  4718. word32 outSz, ecc_key* key, buffer* keyBufInfo)
  4719. {
  4720. int ret = WC_NO_ERR_TRACE(SIG_VERIFY_E);
  4721. #ifdef HAVE_PK_CALLBACKS
  4722. const byte* keyBuf = NULL;
  4723. word32 keySz = 0;
  4724. if (keyBufInfo) {
  4725. keyBuf = keyBufInfo->buffer;
  4726. keySz = keyBufInfo->length;
  4727. }
  4728. #endif
  4729. (void)ssl;
  4730. (void)keyBufInfo;
  4731. WOLFSSL_ENTER("EccVerify");
  4732. #ifdef WOLFSSL_ASYNC_CRYPT
  4733. /* initialize event */
  4734. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  4735. if (ret != 0)
  4736. return ret;
  4737. #endif
  4738. #ifdef HAVE_PK_CALLBACKS
  4739. if (ssl->ctx->EccVerifyCb) {
  4740. void* ctx = wolfSSL_GetEccVerifyCtx(ssl);
  4741. ret = ssl->ctx->EccVerifyCb(ssl, in, inSz, out, outSz, keyBuf, keySz,
  4742. &ssl->eccVerifyRes, ctx);
  4743. }
  4744. #if !defined(WOLFSSL_RENESAS_FSPSM_TLS) && \
  4745. !defined(WOLFSSL_RENESAS_TSIP_TLS) && \
  4746. !defined(WOLFSSL_MAXQ108X)
  4747. else
  4748. #else
  4749. if (!ssl->ctx->EccVerifyCb || ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
  4750. #endif
  4751. #endif /* HAVE_PK_CALLBACKS */
  4752. {
  4753. ret = wc_ecc_verify_hash(in, inSz, out, outSz, &ssl->eccVerifyRes, key);
  4754. }
  4755. /* Handle async pending response */
  4756. #ifdef WOLFSSL_ASYNC_CRYPT
  4757. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  4758. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  4759. }
  4760. else
  4761. #endif /* WOLFSSL_ASYNC_CRYPT */
  4762. {
  4763. if (ret != 0 || ssl->eccVerifyRes == 0) {
  4764. if (ret == 0) {
  4765. ret = VERIFY_SIGN_ERROR;
  4766. }
  4767. WOLFSSL_ERROR_VERBOSE(ret);
  4768. }
  4769. else {
  4770. ret = 0;
  4771. }
  4772. }
  4773. WOLFSSL_LEAVE("EccVerify", ret);
  4774. return ret;
  4775. }
  4776. int EccSharedSecret(WOLFSSL* ssl, ecc_key* priv_key, ecc_key* pub_key,
  4777. byte* pubKeyDer, word32* pubKeySz, byte* out, word32* outlen,
  4778. int side)
  4779. {
  4780. int ret;
  4781. #ifdef WOLFSSL_ASYNC_CRYPT
  4782. WC_ASYNC_DEV* asyncDev = NULL;
  4783. #endif
  4784. (void)ssl;
  4785. (void)pubKeyDer;
  4786. (void)pubKeySz;
  4787. (void)side;
  4788. WOLFSSL_ENTER("EccSharedSecret");
  4789. #ifdef WOLFSSL_ASYNC_CRYPT
  4790. /* initialize event */
  4791. if (priv_key != NULL) {
  4792. asyncDev = &priv_key->asyncDev;
  4793. ret = wolfSSL_AsyncInit(ssl, asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  4794. if (ret != 0)
  4795. return ret;
  4796. }
  4797. #endif
  4798. #ifdef HAVE_PK_CALLBACKS
  4799. if (ssl->ctx->EccSharedSecretCb) {
  4800. void* ctx = wolfSSL_GetEccSharedSecretCtx(ssl);
  4801. ecc_key* otherKey = (side == WOLFSSL_CLIENT_END) ? pub_key : priv_key;
  4802. ret = ssl->ctx->EccSharedSecretCb(ssl, otherKey, pubKeyDer,
  4803. pubKeySz, out, outlen, side, ctx);
  4804. }
  4805. else
  4806. #endif
  4807. {
  4808. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  4809. !defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2)) && \
  4810. !defined(HAVE_SELFTEST)
  4811. ret = wc_ecc_set_rng(priv_key, ssl->rng);
  4812. if (ret == 0)
  4813. #endif
  4814. {
  4815. PRIVATE_KEY_UNLOCK();
  4816. ret = wc_ecc_shared_secret(priv_key, pub_key, out, outlen);
  4817. PRIVATE_KEY_LOCK();
  4818. }
  4819. }
  4820. /* Handle async pending response */
  4821. #ifdef WOLFSSL_ASYNC_CRYPT
  4822. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  4823. ret = wolfSSL_AsyncPush(ssl, asyncDev);
  4824. }
  4825. #endif /* WOLFSSL_ASYNC_CRYPT */
  4826. WOLFSSL_LEAVE("EccSharedSecret", ret);
  4827. return ret;
  4828. }
  4829. int EccMakeKey(WOLFSSL* ssl, ecc_key* key, ecc_key* peer)
  4830. {
  4831. int ret = 0;
  4832. int keySz = 0;
  4833. int ecc_curve = ECC_CURVE_DEF;
  4834. WOLFSSL_ENTER("EccMakeKey");
  4835. #ifdef WOLFSSL_ASYNC_CRYPT
  4836. /* initialize event */
  4837. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_NONE);
  4838. if (ret != 0)
  4839. return ret;
  4840. #endif
  4841. /* get key size */
  4842. if (peer == NULL || peer->dp == NULL) {
  4843. keySz = ssl->eccTempKeySz;
  4844. /* get curve type */
  4845. if (ssl->ecdhCurveOID > 0) {
  4846. ecc_curve = wc_ecc_get_oid(ssl->ecdhCurveOID, NULL, NULL);
  4847. }
  4848. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) && \
  4849. (defined(WOLFSSL_SM4_CBC) || defined(WOLFSSL_SM4_GCM) || \
  4850. defined(WOLFSSL_SM4_CCM))
  4851. if ((ssl->options.cipherSuite0 == SM_BYTE) && (0
  4852. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  4853. || (ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3)
  4854. #endif
  4855. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3
  4856. || (ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3)
  4857. #endif
  4858. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3
  4859. || (ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3)
  4860. #endif
  4861. )) {
  4862. keySz = 32;
  4863. ecc_curve = ECC_SM2P256V1;
  4864. }
  4865. #endif
  4866. }
  4867. else {
  4868. keySz = peer->dp->size;
  4869. ecc_curve = peer->dp->id;
  4870. }
  4871. #ifdef HAVE_PK_CALLBACKS
  4872. if (ssl->ctx->EccKeyGenCb) {
  4873. void* ctx = wolfSSL_GetEccKeyGenCtx(ssl);
  4874. ret = ssl->ctx->EccKeyGenCb(ssl, key, (unsigned int)keySz, ecc_curve, ctx);
  4875. }
  4876. else
  4877. #endif
  4878. {
  4879. ret = wc_ecc_make_key_ex(ssl->rng, keySz, key, ecc_curve);
  4880. }
  4881. /* make sure the curve is set for TLS */
  4882. if (ret == 0 && key->dp) {
  4883. ssl->ecdhCurveOID = key->dp->oidSum;
  4884. #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
  4885. ssl->namedGroup = 0;
  4886. #endif
  4887. }
  4888. /* Handle async pending response */
  4889. #ifdef WOLFSSL_ASYNC_CRYPT
  4890. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  4891. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  4892. }
  4893. #endif /* WOLFSSL_ASYNC_CRYPT */
  4894. WOLFSSL_LEAVE("EccMakeKey", ret);
  4895. return ret;
  4896. }
  4897. #endif /* HAVE_ECC */
  4898. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  4899. int Sm2wSm3Sign(WOLFSSL* ssl, const byte* id, word32 idSz, const byte* in,
  4900. word32 inSz, byte* out, word32* outSz, ecc_key* key, DerBuffer* keyBufInfo)
  4901. {
  4902. int ret;
  4903. byte hash[WC_SM3_DIGEST_SIZE];
  4904. (void)ssl;
  4905. (void)keyBufInfo;
  4906. WOLFSSL_ENTER("Sm2wSm3Sign");
  4907. ret = wc_ecc_sm2_create_digest(id, idSz, in, inSz, WC_HASH_TYPE_SM3, hash,
  4908. sizeof(hash), key);
  4909. if (ret == 0) {
  4910. ret = wc_ecc_sm2_sign_hash(hash, sizeof(hash), out, outSz, ssl->rng,
  4911. key);
  4912. }
  4913. WOLFSSL_LEAVE("Sm2wSm3Sign", ret);
  4914. return ret;
  4915. }
  4916. int Sm2wSm3Verify(WOLFSSL* ssl, const byte* id, word32 idSz, const byte* sig,
  4917. word32 sigSz, const byte* msg, word32 msgSz, ecc_key* key,
  4918. buffer* keyBufInfo)
  4919. {
  4920. int ret = WC_NO_ERR_TRACE(SIG_VERIFY_E);
  4921. byte hash[WC_SM3_DIGEST_SIZE];
  4922. (void)ssl;
  4923. (void)keyBufInfo;
  4924. WOLFSSL_ENTER("Sm2wSm3Verify");
  4925. ret = wc_ecc_sm2_create_digest(id, idSz, msg, msgSz, WC_HASH_TYPE_SM3, hash,
  4926. sizeof(hash), key);
  4927. if (ret == 0) {
  4928. ret = wc_ecc_sm2_verify_hash(sig, sigSz, hash, sizeof(hash),
  4929. &ssl->eccVerifyRes, key);
  4930. if (ret == 0 && ssl->eccVerifyRes == 0) {
  4931. ret = VERIFY_SIGN_ERROR;
  4932. }
  4933. }
  4934. if (ret != 0) {
  4935. WOLFSSL_ERROR_VERBOSE(ret);
  4936. }
  4937. WOLFSSL_LEAVE("Sm2wSm3Verify", ret);
  4938. return ret;
  4939. }
  4940. #endif /* WOLFSSL_SM2 */
  4941. #ifdef HAVE_ED25519
  4942. /* Check whether the key contains a public key.
  4943. * If not then pull it out of the leaf certificate.
  4944. *
  4945. * ssl SSL/TLS object.
  4946. * returns MEMORY_E when unable to allocate memory, a parsing error, otherwise
  4947. * 0 on success.
  4948. */
  4949. int Ed25519CheckPubKey(WOLFSSL* ssl)
  4950. {
  4951. #ifndef HAVE_ED25519_KEY_IMPORT
  4952. (void)ssl;
  4953. return NOT_COMPILED_IN;
  4954. #else /* HAVE_ED25519_KEY_IMPORT */
  4955. ed25519_key* key = (ed25519_key*)ssl->hsKey;
  4956. int ret = 0;
  4957. /* Public key required for signing. */
  4958. if (key != NULL && !key->pubKeySet) {
  4959. const unsigned char* pubKey;
  4960. word32 pubKeySz;
  4961. ret = wc_CertGetPubKey(ssl->buffers.certificate->buffer,
  4962. ssl->buffers.certificate->length, &pubKey, &pubKeySz);
  4963. if (ret == 0) {
  4964. ret = wc_ed25519_import_public(pubKey, pubKeySz, key);
  4965. }
  4966. }
  4967. return ret;
  4968. #endif /* HAVE_ED25519_KEY_IMPORT */
  4969. }
  4970. /* Sign the data using EdDSA and key using Ed25519.
  4971. *
  4972. * ssl SSL object.
  4973. * in Data or message to sign.
  4974. * inSz Length of the data.
  4975. * out Buffer to hold signature.
  4976. * outSz On entry, size of the buffer. On exit, the size of the signature.
  4977. * key The private Ed25519 key data.
  4978. * keySz The length of the private key data in bytes.
  4979. * ctx The callback context.
  4980. * returns 0 on success, otherwise the value is an error.
  4981. */
  4982. int Ed25519Sign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
  4983. word32* outSz, ed25519_key* key, DerBuffer* keyBufInfo)
  4984. {
  4985. #ifndef HAVE_ED25519_SIGN
  4986. (void)ssl;
  4987. (void)in;
  4988. (void)inSz;
  4989. (void)out;
  4990. (void)outSz;
  4991. (void)key;
  4992. (void)keyBufInfo;
  4993. return NOT_COMPILED_IN;
  4994. #else /* HAVE_ED25519_SIGN */
  4995. int ret;
  4996. #ifdef HAVE_PK_CALLBACKS
  4997. const byte* keyBuf = NULL;
  4998. word32 keySz = 0;
  4999. if (keyBufInfo) {
  5000. keyBuf = keyBufInfo->buffer;
  5001. keySz = keyBufInfo->length;
  5002. }
  5003. #endif
  5004. (void)ssl;
  5005. (void)keyBufInfo;
  5006. WOLFSSL_ENTER("Ed25519Sign");
  5007. #ifdef WOLFSSL_ASYNC_CRYPT
  5008. /* initialize event */
  5009. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  5010. if (ret != 0)
  5011. return ret;
  5012. #endif
  5013. #if defined(HAVE_PK_CALLBACKS)
  5014. if (ssl->ctx->Ed25519SignCb) {
  5015. void* ctx = wolfSSL_GetEd25519SignCtx(ssl);
  5016. ret = ssl->ctx->Ed25519SignCb(ssl, in, inSz, out, outSz, keyBuf,
  5017. keySz, ctx);
  5018. }
  5019. else
  5020. #endif /* HAVE_PK_CALLBACKS */
  5021. {
  5022. ret = wc_ed25519_sign_msg(in, inSz, out, outSz, key);
  5023. }
  5024. /* Handle async pending response */
  5025. #ifdef WOLFSSL_ASYNC_CRYPT
  5026. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  5027. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  5028. }
  5029. #endif /* WOLFSSL_ASYNC_CRYPT */
  5030. WOLFSSL_LEAVE("Ed25519Sign", ret);
  5031. return ret;
  5032. #endif /* HAVE_ED25519_SIGN */
  5033. }
  5034. /* Verify the data using EdDSA and key using Ed25519.
  5035. *
  5036. * ssl SSL object.
  5037. * in Signature data.
  5038. * inSz Length of the signature data in bytes.
  5039. * msg Message to verify.
  5040. * outSz Length of message in bytes.
  5041. * key The public Ed25519 key data.
  5042. * keySz The length of the private key data in bytes.
  5043. * ctx The callback context.
  5044. * returns 0 on success, otherwise the value is an error.
  5045. */
  5046. int Ed25519Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg,
  5047. word32 msgSz, ed25519_key* key, buffer* keyBufInfo)
  5048. {
  5049. #ifndef HAVE_ED25519_VERIFY
  5050. (void)ssl;
  5051. (void)in;
  5052. (void)inSz;
  5053. (void)msg;
  5054. (void)msgSz;
  5055. (void)key;
  5056. (void)keyBufInfo;
  5057. return NOT_COMPILED_IN;
  5058. #else /* HAVE_ED25519_VERIFY */
  5059. int ret;
  5060. #ifdef HAVE_PK_CALLBACKS
  5061. const byte* keyBuf = NULL;
  5062. word32 keySz = 0;
  5063. if (keyBufInfo) {
  5064. keyBuf = keyBufInfo->buffer;
  5065. keySz = keyBufInfo->length;
  5066. }
  5067. #endif
  5068. (void)ssl;
  5069. (void)keyBufInfo;
  5070. WOLFSSL_ENTER("Ed25519Verify");
  5071. #ifdef WOLFSSL_ASYNC_CRYPT
  5072. /* initialize event */
  5073. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  5074. if (ret != 0)
  5075. return ret;
  5076. #endif
  5077. #ifdef HAVE_PK_CALLBACKS
  5078. if (ssl->ctx->Ed25519VerifyCb) {
  5079. void* ctx = wolfSSL_GetEd25519VerifyCtx(ssl);
  5080. ret = ssl->ctx->Ed25519VerifyCb(ssl, in, inSz, msg, msgSz, keyBuf,
  5081. keySz, &ssl->eccVerifyRes, ctx);
  5082. }
  5083. else
  5084. #endif /* HAVE_PK_CALLBACKS */
  5085. {
  5086. ret = wc_ed25519_verify_msg(in, inSz, msg, msgSz,
  5087. &ssl->eccVerifyRes, key);
  5088. }
  5089. /* Handle async pending response */
  5090. #ifdef WOLFSSL_ASYNC_CRYPT
  5091. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  5092. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  5093. }
  5094. else
  5095. #endif /* WOLFSSL_ASYNC_CRYPT */
  5096. {
  5097. ret = (ret != 0 || ssl->eccVerifyRes == 0) ? VERIFY_SIGN_ERROR : 0;
  5098. }
  5099. WOLFSSL_LEAVE("Ed25519Verify", ret);
  5100. return ret;
  5101. #endif /* HAVE_ED25519_VERIFY */
  5102. }
  5103. #endif /* HAVE_ED25519 */
  5104. #ifndef WOLFSSL_NO_TLS12
  5105. #ifdef HAVE_CURVE25519
  5106. #ifdef HAVE_PK_CALLBACKS
  5107. /* Gets X25519 key for shared secret callback testing
  5108. * Client side: returns peer key
  5109. * Server side: returns private key
  5110. */
  5111. static int X25519GetKey(WOLFSSL* ssl, curve25519_key** otherKey)
  5112. {
  5113. struct curve25519_key* tmpKey = NULL;
  5114. if (ssl == NULL || otherKey == NULL) {
  5115. return BAD_FUNC_ARG;
  5116. }
  5117. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5118. if (!ssl->peerX25519Key || !ssl->peerX25519KeyPresent ||
  5119. !ssl->peerX25519Key->dp) {
  5120. return NO_PEER_KEY;
  5121. }
  5122. tmpKey = (struct curve25519_key*)ssl->peerX25519Key;
  5123. }
  5124. else if (ssl->options.side == WOLFSSL_SERVER_END) {
  5125. if (!ssl->eccTempKeyPresent) {
  5126. return NO_PRIVATE_KEY;
  5127. }
  5128. tmpKey = (struct curve25519_key*)ssl->eccTempKey;
  5129. }
  5130. if (tmpKey) {
  5131. *otherKey = (curve25519_key *)tmpKey;
  5132. return 0;
  5133. }
  5134. else {
  5135. return NO_PEER_KEY;
  5136. }
  5137. }
  5138. #endif /* HAVE_PK_CALLBACKS */
  5139. static int X25519SharedSecret(WOLFSSL* ssl, curve25519_key* priv_key,
  5140. curve25519_key* pub_key, byte* pubKeyDer, word32* pubKeySz,
  5141. byte* out, word32* outlen, int side)
  5142. {
  5143. int ret;
  5144. (void)ssl;
  5145. (void)pubKeyDer;
  5146. (void)pubKeySz;
  5147. (void)side;
  5148. WOLFSSL_ENTER("X25519SharedSecret");
  5149. #ifdef WOLFSSL_ASYNC_CRYPT
  5150. /* initialize event */
  5151. ret = wolfSSL_AsyncInit(ssl, &priv_key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  5152. if (ret != 0)
  5153. return ret;
  5154. #endif
  5155. #ifdef HAVE_PK_CALLBACKS
  5156. if (ssl->ctx->X25519SharedSecretCb) {
  5157. curve25519_key* otherKey = NULL;
  5158. ret = X25519GetKey(ssl, &otherKey);
  5159. if (ret == 0) {
  5160. void* ctx = wolfSSL_GetX25519SharedSecretCtx(ssl);
  5161. ret = ssl->ctx->X25519SharedSecretCb(ssl, otherKey, pubKeyDer,
  5162. pubKeySz, out, outlen, side, ctx);
  5163. }
  5164. }
  5165. else
  5166. #endif
  5167. {
  5168. ret = wc_curve25519_shared_secret_ex(priv_key, pub_key, out, outlen,
  5169. EC25519_LITTLE_ENDIAN);
  5170. }
  5171. /* Handle async pending response */
  5172. #ifdef WOLFSSL_ASYNC_CRYPT
  5173. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  5174. ret = wolfSSL_AsyncPush(ssl, &priv_key->asyncDev);
  5175. }
  5176. #endif /* WOLFSSL_ASYNC_CRYPT */
  5177. WOLFSSL_LEAVE("X25519SharedSecret", ret);
  5178. return ret;
  5179. }
  5180. static int X25519MakeKey(WOLFSSL* ssl, curve25519_key* key,
  5181. curve25519_key* peer)
  5182. {
  5183. int ret = 0;
  5184. (void)peer;
  5185. WOLFSSL_ENTER("X25519MakeKey");
  5186. #ifdef WOLFSSL_ASYNC_CRYPT
  5187. /* initialize event */
  5188. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_NONE);
  5189. if (ret != 0)
  5190. return ret;
  5191. #endif
  5192. #ifdef HAVE_PK_CALLBACKS
  5193. if (ssl->ctx->X25519KeyGenCb) {
  5194. void* ctx = wolfSSL_GetX25519KeyGenCtx(ssl);
  5195. ret = ssl->ctx->X25519KeyGenCb(ssl, key, CURVE25519_KEYSIZE, ctx);
  5196. }
  5197. else
  5198. #endif
  5199. {
  5200. ret = wc_curve25519_make_key(ssl->rng, CURVE25519_KEYSIZE, key);
  5201. }
  5202. if (ret == 0) {
  5203. ssl->ecdhCurveOID = ECC_X25519_OID;
  5204. #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
  5205. ssl->namedGroup = 0;
  5206. #endif
  5207. }
  5208. /* Handle async pending response */
  5209. #ifdef WOLFSSL_ASYNC_CRYPT
  5210. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  5211. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  5212. }
  5213. #endif /* WOLFSSL_ASYNC_CRYPT */
  5214. WOLFSSL_LEAVE("X25519MakeKey", ret);
  5215. return ret;
  5216. }
  5217. #endif /* HAVE_CURVE25519 */
  5218. #endif /* !WOLFSSL_NO_TLS12 */
  5219. #ifdef HAVE_ED448
  5220. /* Check whether the key contains a public key.
  5221. * If not then pull it out of the leaf certificate.
  5222. *
  5223. * ssl SSL/TLS object.
  5224. * returns MEMORY_E when unable to allocate memory, a parsing error, otherwise
  5225. * 0 on success.
  5226. */
  5227. int Ed448CheckPubKey(WOLFSSL* ssl)
  5228. {
  5229. #ifndef HAVE_ED448_KEY_IMPORT
  5230. (void)ssl;
  5231. return NOT_COMPILED_IN;
  5232. #else /* HAVE_ED448_KEY_IMPORT */
  5233. ed448_key* key = (ed448_key*)ssl->hsKey;
  5234. int ret = 0;
  5235. /* Public key required for signing. */
  5236. if (key != NULL && !key->pubKeySet) {
  5237. const unsigned char* pubKey;
  5238. word32 pubKeySz;
  5239. ret = wc_CertGetPubKey(ssl->buffers.certificate->buffer,
  5240. ssl->buffers.certificate->length, &pubKey, &pubKeySz);
  5241. if (ret == 0) {
  5242. ret = wc_ed448_import_public(pubKey, pubKeySz, key);
  5243. }
  5244. }
  5245. return ret;
  5246. #endif /* HAVE_ED448_KEY_IMPORT */
  5247. }
  5248. /* Sign the data using EdDSA and key using Ed448.
  5249. *
  5250. * ssl SSL object.
  5251. * in Data or message to sign.
  5252. * inSz Length of the data.
  5253. * out Buffer to hold signature.
  5254. * outSz On entry, size of the buffer. On exit, the size of the signature.
  5255. * key The private Ed448 key data.
  5256. * keySz The length of the private key data in bytes.
  5257. * ctx The callback context.
  5258. * returns 0 on success, otherwise the value is an error.
  5259. */
  5260. int Ed448Sign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
  5261. word32* outSz, ed448_key* key, DerBuffer* keyBufInfo)
  5262. {
  5263. #ifndef HAVE_ED448_SIGN
  5264. (void)ssl;
  5265. (void)in;
  5266. (void)inSz;
  5267. (void)out;
  5268. (void)outSz;
  5269. (void)key;
  5270. (void)keyBufInfo;
  5271. return NOT_COMPILED_IN;
  5272. #else /* HAVE_ED448_SIGN */
  5273. int ret;
  5274. #ifdef HAVE_PK_CALLBACKS
  5275. const byte* keyBuf = NULL;
  5276. word32 keySz = 0;
  5277. if (keyBufInfo) {
  5278. keyBuf = keyBufInfo->buffer;
  5279. keySz = keyBufInfo->length;
  5280. }
  5281. #endif
  5282. (void)ssl;
  5283. (void)keyBufInfo;
  5284. WOLFSSL_ENTER("Ed448Sign");
  5285. #ifdef WOLFSSL_ASYNC_CRYPT
  5286. /* initialize event */
  5287. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  5288. if (ret != 0)
  5289. return ret;
  5290. #endif
  5291. #if defined(HAVE_PK_CALLBACKS)
  5292. if (ssl->ctx->Ed448SignCb) {
  5293. void* ctx = wolfSSL_GetEd448SignCtx(ssl);
  5294. ret = ssl->ctx->Ed448SignCb(ssl, in, inSz, out, outSz, keyBuf, keySz,
  5295. ctx);
  5296. }
  5297. else
  5298. #endif /* HAVE_PK_CALLBACKS */
  5299. {
  5300. ret = wc_ed448_sign_msg(in, inSz, out, outSz, key, NULL, 0);
  5301. }
  5302. /* Handle async pending response */
  5303. #ifdef WOLFSSL_ASYNC_CRYPT
  5304. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  5305. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  5306. }
  5307. #endif /* WOLFSSL_ASYNC_CRYPT */
  5308. WOLFSSL_LEAVE("Ed448Sign", ret);
  5309. return ret;
  5310. #endif /* HAVE_ED448_SIGN */
  5311. }
  5312. /* Verify the data using EdDSA and key using Ed448.
  5313. *
  5314. * ssl SSL object.
  5315. * in Signature data.
  5316. * inSz Length of the signature data in bytes.
  5317. * msg Message to verify.
  5318. * outSz Length of message in bytes.
  5319. * key The public Ed448 key data.
  5320. * keySz The length of the private key data in bytes.
  5321. * ctx The callback context.
  5322. * returns 0 on success, otherwise the value is an error.
  5323. */
  5324. int Ed448Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg,
  5325. word32 msgSz, ed448_key* key, buffer* keyBufInfo)
  5326. {
  5327. #ifndef HAVE_ED448_VERIFY
  5328. (void)ssl;
  5329. (void)in;
  5330. (void)inSz;
  5331. (void)msg;
  5332. (void)msgSz;
  5333. (void)key;
  5334. (void)keyBufInfo;
  5335. return NOT_COMPILED_IN;
  5336. #else /* HAVE_ED448_VERIFY */
  5337. int ret;
  5338. #ifdef HAVE_PK_CALLBACKS
  5339. const byte* keyBuf = NULL;
  5340. word32 keySz = 0;
  5341. if (keyBufInfo) {
  5342. keyBuf = keyBufInfo->buffer;
  5343. keySz = keyBufInfo->length;
  5344. }
  5345. #endif
  5346. (void)ssl;
  5347. (void)keyBufInfo;
  5348. WOLFSSL_ENTER("Ed448Verify");
  5349. #ifdef WOLFSSL_ASYNC_CRYPT
  5350. /* initialize event */
  5351. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  5352. if (ret != 0)
  5353. return ret;
  5354. #endif
  5355. #ifdef HAVE_PK_CALLBACKS
  5356. if (ssl->ctx->Ed448VerifyCb) {
  5357. void* ctx = wolfSSL_GetEd448VerifyCtx(ssl);
  5358. ret = ssl->ctx->Ed448VerifyCb(ssl, in, inSz, msg, msgSz, keyBuf, keySz,
  5359. &ssl->eccVerifyRes, ctx);
  5360. }
  5361. else
  5362. #endif /* HAVE_PK_CALLBACKS */
  5363. {
  5364. ret = wc_ed448_verify_msg(in, inSz, msg, msgSz, &ssl->eccVerifyRes, key,
  5365. NULL, 0);
  5366. }
  5367. /* Handle async pending response */
  5368. #ifdef WOLFSSL_ASYNC_CRYPT
  5369. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  5370. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  5371. }
  5372. else
  5373. #endif /* WOLFSSL_ASYNC_CRYPT */
  5374. {
  5375. ret = (ret != 0 || ssl->eccVerifyRes == 0) ? VERIFY_SIGN_ERROR : 0;
  5376. }
  5377. WOLFSSL_LEAVE("Ed448Verify", ret);
  5378. return ret;
  5379. #endif /* HAVE_ED448_VERIFY */
  5380. }
  5381. #endif /* HAVE_ED448 */
  5382. #ifndef WOLFSSL_NO_TLS12
  5383. #ifdef HAVE_CURVE448
  5384. #ifdef HAVE_PK_CALLBACKS
  5385. /* Gets X448 key for shared secret callback testing
  5386. * Client side: returns peer key
  5387. * Server side: returns private key
  5388. */
  5389. static int X448GetKey(WOLFSSL* ssl, curve448_key** otherKey)
  5390. {
  5391. struct curve448_key* tmpKey = NULL;
  5392. if (ssl == NULL || otherKey == NULL) {
  5393. return BAD_FUNC_ARG;
  5394. }
  5395. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5396. if (!ssl->peerX448Key || !ssl->peerX448KeyPresent) {
  5397. return NO_PEER_KEY;
  5398. }
  5399. tmpKey = (struct curve448_key*)ssl->peerX448Key;
  5400. }
  5401. else if (ssl->options.side == WOLFSSL_SERVER_END) {
  5402. if (!ssl->eccTempKeyPresent) {
  5403. return NO_PRIVATE_KEY;
  5404. }
  5405. tmpKey = (struct curve448_key*)ssl->eccTempKey;
  5406. }
  5407. if (tmpKey) {
  5408. *otherKey = (curve448_key *)tmpKey;
  5409. return 0;
  5410. }
  5411. else {
  5412. return NO_PEER_KEY;
  5413. }
  5414. }
  5415. #endif /* HAVE_PK_CALLBACKS */
  5416. static int X448SharedSecret(WOLFSSL* ssl, curve448_key* priv_key,
  5417. curve448_key* pub_key, byte* pubKeyDer,
  5418. word32* pubKeySz, byte* out, word32* outlen,
  5419. int side)
  5420. {
  5421. int ret;
  5422. (void)ssl;
  5423. (void)pubKeyDer;
  5424. (void)pubKeySz;
  5425. (void)side;
  5426. WOLFSSL_ENTER("X448SharedSecret");
  5427. #ifdef WOLFSSL_ASYNC_CRYPT
  5428. /* initialize event */
  5429. ret = wolfSSL_AsyncInit(ssl, &priv_key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  5430. if (ret != 0)
  5431. return ret;
  5432. #endif
  5433. #ifdef HAVE_PK_CALLBACKS
  5434. if (ssl->ctx->X448SharedSecretCb) {
  5435. curve448_key* otherKey = NULL;
  5436. ret = X448GetKey(ssl, &otherKey);
  5437. if (ret == 0) {
  5438. void* ctx = wolfSSL_GetX448SharedSecretCtx(ssl);
  5439. ret = ssl->ctx->X448SharedSecretCb(ssl, otherKey, pubKeyDer,
  5440. pubKeySz, out, outlen, side, ctx);
  5441. }
  5442. }
  5443. else
  5444. #endif
  5445. {
  5446. ret = wc_curve448_shared_secret_ex(priv_key, pub_key, out, outlen,
  5447. EC448_LITTLE_ENDIAN);
  5448. }
  5449. /* Handle async pending response */
  5450. #ifdef WOLFSSL_ASYNC_CRYPT
  5451. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  5452. ret = wolfSSL_AsyncPush(ssl, &priv_key->asyncDev);
  5453. }
  5454. #endif /* WOLFSSL_ASYNC_CRYPT */
  5455. WOLFSSL_LEAVE("X448SharedSecret", ret);
  5456. return ret;
  5457. }
  5458. static int X448MakeKey(WOLFSSL* ssl, curve448_key* key, curve448_key* peer)
  5459. {
  5460. int ret = 0;
  5461. (void)peer;
  5462. WOLFSSL_ENTER("X448MakeKey");
  5463. #ifdef WOLFSSL_ASYNC_CRYPT
  5464. /* initialize event */
  5465. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_NONE);
  5466. if (ret != 0)
  5467. return ret;
  5468. #endif
  5469. #ifdef HAVE_PK_CALLBACKS
  5470. if (ssl->ctx->X448KeyGenCb) {
  5471. void* ctx = wolfSSL_GetX448KeyGenCtx(ssl);
  5472. ret = ssl->ctx->X448KeyGenCb(ssl, key, CURVE448_KEY_SIZE, ctx);
  5473. }
  5474. else
  5475. #endif
  5476. {
  5477. ret = wc_curve448_make_key(ssl->rng, CURVE448_KEY_SIZE, key);
  5478. }
  5479. if (ret == 0) {
  5480. ssl->ecdhCurveOID = ECC_X448_OID;
  5481. #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
  5482. ssl->namedGroup = 0;
  5483. #endif
  5484. }
  5485. /* Handle async pending response */
  5486. #ifdef WOLFSSL_ASYNC_CRYPT
  5487. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  5488. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  5489. }
  5490. #endif /* WOLFSSL_ASYNC_CRYPT */
  5491. WOLFSSL_LEAVE("X448MakeKey", ret);
  5492. return ret;
  5493. }
  5494. #endif /* HAVE_CURVE448 */
  5495. #endif /* !WOLFSSL_NO_TLS12 */
  5496. #if !defined(NO_CERTS) || !defined(NO_PSK)
  5497. #if !defined(NO_DH)
  5498. int DhGenKeyPair(WOLFSSL* ssl, DhKey* dhKey,
  5499. byte* priv, word32* privSz,
  5500. byte* pub, word32* pubSz)
  5501. {
  5502. int ret;
  5503. WOLFSSL_ENTER("DhGenKeyPair");
  5504. #ifdef WOLFSSL_ASYNC_CRYPT
  5505. /* initialize event */
  5506. ret = wolfSSL_AsyncInit(ssl, &dhKey->asyncDev, WC_ASYNC_FLAG_NONE);
  5507. if (ret != 0)
  5508. return ret;
  5509. #endif
  5510. #if defined(HAVE_PK_CALLBACKS)
  5511. ret = NOT_COMPILED_IN;
  5512. if (ssl && ssl->ctx && ssl->ctx->DhGenerateKeyPairCb) {
  5513. ret = ssl->ctx->DhGenerateKeyPairCb(dhKey, ssl->rng, priv, privSz,
  5514. pub, pubSz);
  5515. }
  5516. if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
  5517. #endif
  5518. {
  5519. PRIVATE_KEY_UNLOCK();
  5520. ret = wc_DhGenerateKeyPair(dhKey, ssl->rng, priv, privSz, pub, pubSz);
  5521. PRIVATE_KEY_LOCK();
  5522. }
  5523. /* Handle async pending response */
  5524. #ifdef WOLFSSL_ASYNC_CRYPT
  5525. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  5526. ret = wolfSSL_AsyncPush(ssl, &dhKey->asyncDev);
  5527. }
  5528. #endif /* WOLFSSL_ASYNC_CRYPT */
  5529. WOLFSSL_LEAVE("DhGenKeyPair", ret);
  5530. return ret;
  5531. }
  5532. int DhAgree(WOLFSSL* ssl, DhKey* dhKey,
  5533. const byte* priv, word32 privSz,
  5534. const byte* otherPub, word32 otherPubSz,
  5535. byte* agree, word32* agreeSz,
  5536. const byte* prime, word32 primeSz)
  5537. {
  5538. int ret;
  5539. (void)ssl;
  5540. WOLFSSL_ENTER("DhAgree");
  5541. #ifdef WOLFSSL_ASYNC_CRYPT
  5542. /* initialize event */
  5543. ret = wolfSSL_AsyncInit(ssl, &dhKey->asyncDev, WC_ASYNC_FLAG_NONE);
  5544. if (ret != 0)
  5545. return ret;
  5546. #endif
  5547. #ifdef HAVE_PK_CALLBACKS
  5548. if (ssl->ctx->DhAgreeCb) {
  5549. void* ctx = wolfSSL_GetDhAgreeCtx(ssl);
  5550. WOLFSSL_MSG("Calling DhAgree Callback Function");
  5551. ret = ssl->ctx->DhAgreeCb(ssl, dhKey, priv, privSz,
  5552. otherPub, otherPubSz, agree, agreeSz, ctx);
  5553. }
  5554. else
  5555. #endif
  5556. {
  5557. #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  5558. /* check the public key has valid number */
  5559. if (dhKey != NULL && (prime == NULL || primeSz == 0)) {
  5560. /* wc_DhCheckPubKey does not do exponentiation */
  5561. ret = wc_DhCheckPubKey(dhKey, otherPub, otherPubSz);
  5562. }
  5563. else {
  5564. ret = wc_DhCheckPubValue(prime, primeSz, otherPub, otherPubSz);
  5565. }
  5566. if (ret != 0) {
  5567. /* translate to valid error (wc_DhCheckPubValue returns MP_VAL -1) */
  5568. ret = PEER_KEY_ERROR;
  5569. WOLFSSL_ERROR_VERBOSE(ret);
  5570. #ifdef OPENSSL_EXTRA
  5571. SendAlert(ssl, alert_fatal, illegal_parameter);
  5572. #endif
  5573. }
  5574. else
  5575. #endif
  5576. {
  5577. PRIVATE_KEY_UNLOCK();
  5578. ret = wc_DhAgree(dhKey, agree, agreeSz, priv, privSz, otherPub,
  5579. otherPubSz);
  5580. PRIVATE_KEY_LOCK();
  5581. }
  5582. }
  5583. /* Handle async pending response */
  5584. #ifdef WOLFSSL_ASYNC_CRYPT
  5585. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  5586. ret = wolfSSL_AsyncPush(ssl, &dhKey->asyncDev);
  5587. }
  5588. #endif /* WOLFSSL_ASYNC_CRYPT */
  5589. WOLFSSL_LEAVE("DhAgree", ret);
  5590. (void)prime;
  5591. (void)primeSz;
  5592. return ret;
  5593. }
  5594. #endif /* !NO_DH */
  5595. #endif /* !NO_CERTS || !NO_PSK */
  5596. #ifdef HAVE_PK_CALLBACKS
  5597. int wolfSSL_IsPrivatePkSet(WOLFSSL* ssl)
  5598. {
  5599. int pkcbset = 0;
  5600. (void)ssl;
  5601. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  5602. !defined(NO_RSA)
  5603. if (0
  5604. #ifdef HAVE_ECC
  5605. || (ssl->ctx->EccSignCb != NULL &&
  5606. ssl->buffers.keyType == ecc_dsa_sa_algo)
  5607. #endif
  5608. #ifdef HAVE_ED25519
  5609. || (ssl->ctx->Ed25519SignCb != NULL &&
  5610. ssl->buffers.keyType == ed25519_sa_algo)
  5611. #endif
  5612. #ifdef HAVE_ED448
  5613. || (ssl->ctx->Ed448SignCb != NULL &&
  5614. ssl->buffers.keyType == ed448_sa_algo)
  5615. #endif
  5616. #ifndef NO_RSA
  5617. || (ssl->ctx->RsaSignCb != NULL && ssl->buffers.keyType == rsa_sa_algo)
  5618. || (ssl->ctx->RsaDecCb != NULL && ssl->buffers.keyType == rsa_kea)
  5619. #ifdef WC_RSA_PSS
  5620. || (ssl->ctx->RsaPssSignCb != NULL &&
  5621. ssl->buffers.keyType == rsa_pss_sa_algo)
  5622. #endif
  5623. #endif
  5624. ) {
  5625. pkcbset = 1;
  5626. }
  5627. #endif
  5628. return pkcbset;
  5629. }
  5630. int wolfSSL_CTX_IsPrivatePkSet(WOLFSSL_CTX* ctx)
  5631. {
  5632. int pkcbset = 0;
  5633. (void)ctx;
  5634. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  5635. !defined(NO_RSA)
  5636. if (0
  5637. #ifdef HAVE_ECC
  5638. || ctx->EccSignCb != NULL
  5639. #endif
  5640. #ifdef HAVE_ED25519
  5641. || ctx->Ed25519SignCb != NULL
  5642. #endif
  5643. #ifdef HAVE_ED448
  5644. || ctx->Ed448SignCb != NULL
  5645. #endif
  5646. #ifndef NO_RSA
  5647. || ctx->RsaSignCb != NULL
  5648. || ctx->RsaDecCb != NULL
  5649. #ifdef WC_RSA_PSS
  5650. || ctx->RsaPssSignCb != NULL
  5651. #endif
  5652. #endif
  5653. ) {
  5654. pkcbset = 1;
  5655. }
  5656. #endif
  5657. return pkcbset;
  5658. }
  5659. #endif /* HAVE_PK_CALLBACKS */
  5660. static void InitSuites_EitherSide(Suites* suites, ProtocolVersion pv, int keySz,
  5661. word16 haveRSA, word16 havePSK, word16 haveDH, word16 haveECDSAsig,
  5662. word16 haveECC, word16 haveStaticECC,
  5663. word16 haveFalconSig, word16 haveDilithiumSig, word16 haveAnon,
  5664. int side)
  5665. {
  5666. /* make sure server has DH params, and add PSK if there */
  5667. if (side == WOLFSSL_SERVER_END) {
  5668. InitSuites(suites, pv, keySz, haveRSA, havePSK, haveDH, haveECDSAsig,
  5669. haveECC, TRUE, haveStaticECC, haveFalconSig,
  5670. haveDilithiumSig, haveAnon, TRUE, side);
  5671. }
  5672. else {
  5673. InitSuites(suites, pv, keySz, haveRSA, havePSK, TRUE, haveECDSAsig,
  5674. haveECC, TRUE, haveStaticECC, haveFalconSig,
  5675. haveDilithiumSig, haveAnon, TRUE, side);
  5676. }
  5677. }
  5678. void InitSSL_CTX_Suites(WOLFSSL_CTX* ctx)
  5679. {
  5680. int keySz = 0;
  5681. byte havePSK = 0;
  5682. byte haveAnon = 0;
  5683. byte haveRSA = 0;
  5684. #ifndef NO_RSA
  5685. haveRSA = 1;
  5686. #endif
  5687. #ifndef NO_PSK
  5688. havePSK = ctx->havePSK;
  5689. #endif /* NO_PSK */
  5690. #ifdef HAVE_ANON
  5691. haveAnon = ctx->useAnon;
  5692. #endif /* HAVE_ANON*/
  5693. #ifndef NO_CERTS
  5694. keySz = ctx->privateKeySz;
  5695. #endif
  5696. InitSuites_EitherSide(ctx->suites, ctx->method->version, keySz,
  5697. haveRSA, havePSK, ctx->haveDH, ctx->haveECDSAsig, ctx->haveECC,
  5698. ctx->haveStaticECC, ctx->haveFalconSig, ctx->haveDilithiumSig,
  5699. haveAnon, ctx->method->side);
  5700. }
  5701. int InitSSL_Suites(WOLFSSL* ssl)
  5702. {
  5703. int keySz = 0;
  5704. byte havePSK = 0;
  5705. byte haveAnon = 0;
  5706. byte haveRSA = 0;
  5707. byte haveMcast = 0;
  5708. (void)haveAnon; /* Squash unused var warnings */
  5709. (void)haveMcast;
  5710. if (!ssl)
  5711. return BAD_FUNC_ARG;
  5712. #ifndef NO_RSA
  5713. haveRSA = 1;
  5714. #endif
  5715. #ifndef NO_PSK
  5716. havePSK = (byte)ssl->options.havePSK;
  5717. #endif /* NO_PSK */
  5718. #if !defined(NO_CERTS) && !defined(WOLFSSL_SESSION_EXPORT)
  5719. #ifdef HAVE_ANON
  5720. haveAnon = (byte)ssl->options.useAnon;
  5721. #endif /* HAVE_ANON*/
  5722. #ifdef WOLFSSL_MULTICAST
  5723. haveMcast = (byte)ssl->options.haveMcast;
  5724. #endif /* WOLFSSL_MULTICAST */
  5725. #endif /* !NO_CERTS && !WOLFSSL_SESSION_EXPORT */
  5726. #ifdef WOLFSSL_EARLY_DATA
  5727. if (ssl->options.side == WOLFSSL_SERVER_END)
  5728. ssl->options.maxEarlyDataSz = ssl->ctx->maxEarlyDataSz;
  5729. #endif
  5730. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  5731. ((defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)) || \
  5732. (defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  5733. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  5734. ssl->options.cacheMessages = ssl->options.side == WOLFSSL_SERVER_END ||
  5735. ssl->buffers.keyType == ed25519_sa_algo ||
  5736. ssl->buffers.keyType == ed448_sa_algo ||
  5737. ssl->buffers.keyType == sm2_sa_algo;
  5738. #endif
  5739. #ifndef NO_CERTS
  5740. keySz = ssl->buffers.keySz;
  5741. #endif
  5742. if (ssl->suites != NULL) {
  5743. InitSuites_EitherSide(ssl->suites, ssl->version, keySz, haveRSA,
  5744. havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig,
  5745. ssl->options.haveECC, ssl->options.haveStaticECC,
  5746. ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
  5747. ssl->options.useAnon, ssl->options.side);
  5748. }
  5749. #if !defined(NO_CERTS) && !defined(WOLFSSL_SESSION_EXPORT)
  5750. /* make sure server has cert and key unless using PSK, Anon, or
  5751. * Multicast. This should be true even if just switching ssl ctx */
  5752. if (ssl->options.side == WOLFSSL_SERVER_END &&
  5753. !havePSK && !haveAnon && !haveMcast) {
  5754. /* server certificate must be loaded */
  5755. if (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer) {
  5756. WOLFSSL_MSG("Server missing certificate");
  5757. WOLFSSL_ERROR_VERBOSE(NO_PRIVATE_KEY);
  5758. return NO_PRIVATE_KEY;
  5759. }
  5760. if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
  5761. /* allow no private key if using existing key */
  5762. #ifdef WOLF_PRIVATE_KEY_ID
  5763. if (ssl->devId != INVALID_DEVID
  5764. #ifdef HAVE_PK_CALLBACKS
  5765. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  5766. #endif
  5767. ) {
  5768. WOLFSSL_MSG("Allowing no server private key (external)");
  5769. }
  5770. else
  5771. #endif
  5772. {
  5773. WOLFSSL_MSG("Server missing private key");
  5774. WOLFSSL_ERROR_VERBOSE(NO_PRIVATE_KEY);
  5775. return NO_PRIVATE_KEY;
  5776. }
  5777. }
  5778. }
  5779. #endif
  5780. return WOLFSSL_SUCCESS;
  5781. }
  5782. /* This function inherits a WOLFSSL_CTX's fields into an SSL object.
  5783. It is used during initialization and to switch an ssl's CTX with
  5784. wolfSSL_Set_SSL_CTX. Requires ssl->suites alloc and ssl-arrays with PSK
  5785. unless writeDup is on.
  5786. ssl object to initialize
  5787. ctx parent factory
  5788. writeDup flag indicating this is a write dup only
  5789. WOLFSSL_SUCCESS return value on success */
  5790. int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
  5791. {
  5792. int ret = WOLFSSL_SUCCESS; /* set default ret */
  5793. byte newSSL;
  5794. WOLFSSL_ENTER("SetSSL_CTX");
  5795. if (!ssl || !ctx)
  5796. return BAD_FUNC_ARG;
  5797. newSSL = ssl->ctx == NULL; /* Assign after null check */
  5798. #ifndef NO_PSK
  5799. if (ctx->server_hint[0] && ssl->arrays == NULL && !writeDup) {
  5800. return BAD_FUNC_ARG; /* needed for copy below */
  5801. }
  5802. #endif
  5803. /* decrement previous CTX reference count if exists.
  5804. * This should only happen if switching ctxs!*/
  5805. if (!newSSL) {
  5806. WOLFSSL_MSG("freeing old ctx to decrement reference count. Switching ctx.");
  5807. wolfSSL_CTX_free(ssl->ctx);
  5808. }
  5809. /* increment CTX reference count */
  5810. ret = wolfSSL_CTX_up_ref(ctx);
  5811. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  5812. if (ret != WOLFSSL_SUCCESS) {
  5813. return ret;
  5814. }
  5815. #else
  5816. (void)ret;
  5817. #endif
  5818. ssl->ctx = ctx; /* only for passing to calls, options could change */
  5819. /* Don't change version on a SSL object that has already started a
  5820. * handshake */
  5821. #if defined(WOLFSSL_HAPROXY)
  5822. if (ssl->initial_ctx == NULL) {
  5823. ret = wolfSSL_CTX_up_ref(ctx);
  5824. if (ret == WOLFSSL_SUCCESS) {
  5825. ssl->initial_ctx = ctx; /* Save access to session key materials */
  5826. }
  5827. else {
  5828. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  5829. return ret;
  5830. #else
  5831. (void)ret;
  5832. #endif
  5833. }
  5834. }
  5835. #endif
  5836. if (!ssl->msgsReceived.got_client_hello &&
  5837. !ssl->msgsReceived.got_server_hello)
  5838. ssl->version = ctx->method->version;
  5839. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  5840. ssl->options.mask = ctx->mask;
  5841. ssl->options.minProto = ctx->minProto;
  5842. ssl->options.maxProto = ctx->maxProto;
  5843. #endif
  5844. #ifdef OPENSSL_EXTRA
  5845. #ifdef WOLFSSL_TLS13
  5846. if (ssl->version.minor == TLSv1_3_MINOR &&
  5847. (ssl->options.mask & SSL_OP_NO_TLSv1_3) == SSL_OP_NO_TLSv1_3) {
  5848. if (!ctx->method->downgrade) {
  5849. WOLFSSL_MSG("\tInconsistent protocol options. TLS 1.3 set but not "
  5850. "allowed and downgrading disabled.");
  5851. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5852. return VERSION_ERROR;
  5853. }
  5854. WOLFSSL_MSG("\tOption set to not allow TLSv1.3, Downgrading");
  5855. ssl->version.minor = TLSv1_2_MINOR;
  5856. }
  5857. #endif
  5858. if (ssl->version.minor == TLSv1_2_MINOR &&
  5859. (ssl->options.mask & SSL_OP_NO_TLSv1_2) == SSL_OP_NO_TLSv1_2) {
  5860. if (!ctx->method->downgrade) {
  5861. WOLFSSL_MSG("\tInconsistent protocol options. TLS 1.2 set but not "
  5862. "allowed and downgrading disabled.");
  5863. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5864. return VERSION_ERROR;
  5865. }
  5866. WOLFSSL_MSG("\tOption set to not allow TLSv1.2, Downgrading");
  5867. ssl->version.minor = TLSv1_1_MINOR;
  5868. }
  5869. if (ssl->version.minor == TLSv1_1_MINOR &&
  5870. (ssl->options.mask & SSL_OP_NO_TLSv1_1) == SSL_OP_NO_TLSv1_1) {
  5871. if (!ctx->method->downgrade) {
  5872. WOLFSSL_MSG("\tInconsistent protocol options. TLS 1.1 set but not "
  5873. "allowed and downgrading disabled.");
  5874. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5875. return VERSION_ERROR;
  5876. }
  5877. WOLFSSL_MSG("\tOption set to not allow TLSv1.1, Downgrading");
  5878. ssl->options.tls1_1 = 0;
  5879. ssl->version.minor = TLSv1_MINOR;
  5880. }
  5881. if (ssl->version.minor == TLSv1_MINOR &&
  5882. (ssl->options.mask & SSL_OP_NO_TLSv1) == SSL_OP_NO_TLSv1) {
  5883. if (!ctx->method->downgrade) {
  5884. WOLFSSL_MSG("\tInconsistent protocol options. TLS 1 set but not "
  5885. "allowed and downgrading disabled.");
  5886. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5887. return VERSION_ERROR;
  5888. }
  5889. WOLFSSL_MSG("\tOption set to not allow TLSv1, Downgrading");
  5890. ssl->options.tls = 0;
  5891. ssl->options.tls1_1 = 0;
  5892. ssl->version.minor = SSLv3_MINOR;
  5893. }
  5894. if (ssl->version.minor == SSLv3_MINOR &&
  5895. (ssl->options.mask & SSL_OP_NO_SSLv3) == SSL_OP_NO_SSLv3) {
  5896. WOLFSSL_MSG("\tError, option set to not allow SSLv3");
  5897. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5898. return VERSION_ERROR;
  5899. }
  5900. if (ssl->version.minor < ssl->options.minDowngrade) {
  5901. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  5902. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  5903. return VERSION_ERROR;
  5904. }
  5905. #endif
  5906. #ifdef HAVE_ECC
  5907. ssl->eccTempKeySz = ctx->eccTempKeySz;
  5908. ssl->ecdhCurveOID = ctx->ecdhCurveOID;
  5909. #endif
  5910. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  5911. ssl->pkCurveOID = ctx->pkCurveOID;
  5912. #endif
  5913. #ifdef OPENSSL_EXTRA
  5914. ssl->CBIS = ctx->CBIS;
  5915. #endif
  5916. ssl->timeout = ctx->timeout;
  5917. ssl->verifyCallback = ctx->verifyCallback;
  5918. /* If we are setting the ctx on an already initialized SSL object
  5919. * then we possibly already have a side defined. Don't overwrite unless
  5920. * the context has a well defined role. */
  5921. if (newSSL || ctx->method->side != WOLFSSL_NEITHER_END)
  5922. ssl->options.side = ctx->method->side;
  5923. ssl->options.downgrade = ctx->method->downgrade;
  5924. ssl->options.minDowngrade = ctx->minDowngrade;
  5925. ssl->options.haveRSA = ctx->haveRSA;
  5926. ssl->options.haveDH = ctx->haveDH;
  5927. ssl->options.haveECDSAsig = ctx->haveECDSAsig;
  5928. ssl->options.haveECC = ctx->haveECC;
  5929. ssl->options.haveStaticECC = ctx->haveStaticECC;
  5930. ssl->options.haveFalconSig = ctx->haveFalconSig;
  5931. ssl->options.haveDilithiumSig = ctx->haveDilithiumSig;
  5932. #ifndef NO_PSK
  5933. ssl->options.havePSK = ctx->havePSK;
  5934. ssl->options.client_psk_cb = ctx->client_psk_cb;
  5935. ssl->options.server_psk_cb = ctx->server_psk_cb;
  5936. ssl->options.psk_ctx = ctx->psk_ctx;
  5937. #ifdef WOLFSSL_TLS13
  5938. ssl->options.client_psk_cs_cb = ctx->client_psk_cs_cb;
  5939. ssl->options.client_psk_tls13_cb = ctx->client_psk_tls13_cb;
  5940. ssl->options.server_psk_tls13_cb = ctx->server_psk_tls13_cb;
  5941. #endif
  5942. #endif /* NO_PSK */
  5943. #ifdef WOLFSSL_EARLY_DATA
  5944. if (ssl->options.side == WOLFSSL_SERVER_END)
  5945. ssl->options.maxEarlyDataSz = ctx->maxEarlyDataSz;
  5946. #endif
  5947. #ifdef HAVE_ANON
  5948. ssl->options.useAnon = ctx->useAnon;
  5949. #endif
  5950. #ifndef NO_DH
  5951. ssl->options.minDhKeySz = ctx->minDhKeySz;
  5952. ssl->options.maxDhKeySz = ctx->maxDhKeySz;
  5953. #endif
  5954. #ifndef NO_RSA
  5955. ssl->options.minRsaKeySz = ctx->minRsaKeySz;
  5956. #endif
  5957. #ifdef HAVE_ECC
  5958. ssl->options.minEccKeySz = ctx->minEccKeySz;
  5959. #endif
  5960. #ifdef HAVE_FALCON
  5961. ssl->options.minFalconKeySz = ctx->minFalconKeySz;
  5962. #endif /* HAVE_FALCON */
  5963. #ifdef HAVE_DILITHIUM
  5964. ssl->options.minDilithiumKeySz = ctx->minDilithiumKeySz;
  5965. #endif /* HAVE_DILITHIUM */
  5966. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  5967. ssl->options.verifyDepth = ctx->verifyDepth;
  5968. #endif
  5969. ssl->options.sessionCacheOff = ctx->sessionCacheOff;
  5970. ssl->options.sessionCacheFlushOff = ctx->sessionCacheFlushOff;
  5971. #ifdef HAVE_EXT_CACHE
  5972. ssl->options.internalCacheOff = ctx->internalCacheOff;
  5973. ssl->options.internalCacheLookupOff = ctx->internalCacheLookupOff;
  5974. #endif
  5975. ssl->options.verifyPeer = ctx->verifyPeer;
  5976. ssl->options.verifyNone = ctx->verifyNone;
  5977. ssl->options.failNoCert = ctx->failNoCert;
  5978. ssl->options.failNoCertxPSK = ctx->failNoCertxPSK;
  5979. ssl->options.sendVerify = ctx->sendVerify;
  5980. ssl->options.partialWrite = ctx->partialWrite;
  5981. ssl->options.quietShutdown = ctx->quietShutdown;
  5982. ssl->options.groupMessages = ctx->groupMessages;
  5983. #ifndef NO_DH
  5984. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
  5985. !defined(HAVE_SELFTEST)
  5986. ssl->options.dhKeyTested = ctx->dhKeyTested;
  5987. #endif
  5988. ssl->buffers.serverDH_P = ctx->serverDH_P;
  5989. ssl->buffers.serverDH_G = ctx->serverDH_G;
  5990. #endif
  5991. #if defined(HAVE_RPK)
  5992. ssl->options.rpkConfig = ctx->rpkConfig;
  5993. ssl->options.rpkState = ctx->rpkState;
  5994. #endif /* HAVE_RPK */
  5995. #ifndef NO_CERTS
  5996. #ifdef WOLFSSL_COPY_CERT
  5997. /* If WOLFSSL_COPY_CERT is defined, always copy the cert */
  5998. if (ctx->certificate != NULL) {
  5999. ret = AllocCopyDer(&ssl->buffers.certificate, ctx->certificate->buffer,
  6000. ctx->certificate->length, ctx->certificate->type,
  6001. ctx->certificate->heap);
  6002. if (ret != 0) {
  6003. return ret;
  6004. }
  6005. ssl->buffers.weOwnCert = 1;
  6006. ret = WOLFSSL_SUCCESS;
  6007. }
  6008. if (ctx->certChain != NULL) {
  6009. ret = AllocCopyDer(&ssl->buffers.certChain, ctx->certChain->buffer,
  6010. ctx->certChain->length, ctx->certChain->type,
  6011. ctx->certChain->heap);
  6012. if (ret != 0) {
  6013. return ret;
  6014. }
  6015. ssl->buffers.weOwnCertChain = 1;
  6016. ret = WOLFSSL_SUCCESS;
  6017. }
  6018. #else
  6019. /* ctx still owns certificate, certChain, key, dh, and cm */
  6020. ssl->buffers.certificate = ctx->certificate;
  6021. ssl->buffers.certChain = ctx->certChain;
  6022. #endif
  6023. #ifdef WOLFSSL_TLS13
  6024. ssl->buffers.certChainCnt = ctx->certChainCnt;
  6025. #endif
  6026. #ifndef WOLFSSL_BLIND_PRIVATE_KEY
  6027. ssl->buffers.key = ctx->privateKey;
  6028. #else
  6029. if (ctx->privateKey != NULL) {
  6030. AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
  6031. ctx->privateKey->length, ctx->privateKey->type,
  6032. ctx->privateKey->heap);
  6033. ssl->buffers.weOwnKey = 1;
  6034. /* Blind the private key for the SSL with new random mask. */
  6035. wolfssl_priv_der_unblind(ssl->buffers.key, ctx->privateKeyMask);
  6036. ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
  6037. &ssl->buffers.keyMask);
  6038. if (ret != 0) {
  6039. return ret;
  6040. }
  6041. }
  6042. #endif
  6043. ssl->buffers.keyType = ctx->privateKeyType;
  6044. ssl->buffers.keyId = ctx->privateKeyId;
  6045. ssl->buffers.keyLabel = ctx->privateKeyLabel;
  6046. ssl->buffers.keySz = ctx->privateKeySz;
  6047. ssl->buffers.keyDevId = ctx->privateKeyDevId;
  6048. #ifdef WOLFSSL_DUAL_ALG_CERTS
  6049. #ifndef WOLFSSL_BLIND_PRIVATE_KEY
  6050. ssl->buffers.altKey = ctx->altPrivateKey;
  6051. #else
  6052. if (ctx->altPrivateKey != NULL) {
  6053. AllocCopyDer(&ssl->buffers.altkey, ctx->altPrivateKey->buffer,
  6054. ctx->altPrivateKey->length, ctx->altPrivateKey->type,
  6055. ctx->altPrivateKey->heap);
  6056. /* Blind the private key for the SSL with new random mask. */
  6057. wolfssl_priv_der_unblind(ssl->buffers.altKey, ctx->altPrivateKeyMask);
  6058. ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey,
  6059. &ssl->buffers.altKeyMask);
  6060. if (ret != 0) {
  6061. return ret;
  6062. }
  6063. }
  6064. #endif
  6065. ssl->buffers.altKeyType = ctx->altPrivateKeyType;
  6066. ssl->buffers.altKeyId = ctx->altPrivateKeyId;
  6067. ssl->buffers.altKeyLabel = ctx->altPrivateKeyLabel;
  6068. ssl->buffers.altKeySz = ctx->altPrivateKeySz;
  6069. ssl->buffers.altKeyDevId = ctx->altPrivateKeyDevId;
  6070. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  6071. #endif
  6072. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  6073. ((defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)) || \
  6074. (defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  6075. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  6076. ssl->options.cacheMessages = ssl->options.side == WOLFSSL_SERVER_END ||
  6077. ssl->buffers.keyType == ed25519_sa_algo ||
  6078. ssl->buffers.keyType == ed448_sa_algo ||
  6079. ssl->buffers.keyType == sm2_sa_algo;
  6080. #endif
  6081. #ifdef WOLFSSL_ASYNC_CRYPT
  6082. ssl->devId = ctx->devId;
  6083. #endif
  6084. if (writeDup == 0) {
  6085. #ifndef NO_PSK
  6086. if (ctx->server_hint[0]) { /* set in CTX */
  6087. XSTRNCPY(ssl->arrays->server_hint, ctx->server_hint,
  6088. sizeof(ssl->arrays->server_hint));
  6089. ssl->arrays->server_hint[MAX_PSK_ID_LEN] = '\0'; /* null term */
  6090. }
  6091. #endif /* NO_PSK */
  6092. if (ssl->suites != NULL) {
  6093. if (ctx->suites == NULL)
  6094. XMEMSET(ssl->suites, 0, sizeof(Suites));
  6095. else
  6096. XMEMCPY(ssl->suites, ctx->suites, sizeof(Suites));
  6097. }
  6098. if (ssl->options.side != WOLFSSL_NEITHER_END) {
  6099. /* Defer initializing suites until accept or connect */
  6100. ret = InitSSL_Suites(ssl);
  6101. }
  6102. } /* writeDup check */
  6103. if (ctx->mask != 0 && wolfSSL_set_options(ssl, (long)ctx->mask) == 0) {
  6104. WOLFSSL_MSG("wolfSSL_set_options error");
  6105. return BAD_FUNC_ARG;
  6106. }
  6107. #ifdef WOLFSSL_SESSION_EXPORT
  6108. #ifdef WOLFSSL_DTLS
  6109. ssl->dtls_export = ctx->dtls_export; /* export function for session */
  6110. #endif
  6111. #endif
  6112. #ifdef WOLFSSL_WOLFSENTRY_HOOKS
  6113. ssl->AcceptFilter = ctx->AcceptFilter;
  6114. ssl->AcceptFilter_arg = ctx->AcceptFilter_arg;
  6115. ssl->ConnectFilter = ctx->ConnectFilter;
  6116. ssl->ConnectFilter_arg = ctx->ConnectFilter_arg;
  6117. #endif
  6118. #ifdef OPENSSL_EXTRA
  6119. ssl->readAhead = ctx->readAhead;
  6120. #endif
  6121. #if defined(OPENSSL_EXTRA) && !defined(NO_BIO)
  6122. /* Don't change recv callback if currently using BIO's */
  6123. if (ssl->CBIORecv != SslBioReceive)
  6124. #endif
  6125. ssl->CBIORecv = ctx->CBIORecv;
  6126. #if defined(OPENSSL_EXTRA) && !defined(NO_BIO)
  6127. /* Don't change send callback if currently using BIO's */
  6128. if (ssl->CBIOSend != SslBioSend)
  6129. #endif
  6130. ssl->CBIOSend = ctx->CBIOSend;
  6131. ssl->verifyDepth = ctx->verifyDepth;
  6132. return ret;
  6133. }
  6134. int InitHandshakeHashes(WOLFSSL* ssl)
  6135. {
  6136. int ret;
  6137. /* make sure existing handshake hashes are free'd */
  6138. if (ssl->hsHashes != NULL) {
  6139. FreeHandshakeHashes(ssl);
  6140. }
  6141. /* allocate handshake hashes */
  6142. ssl->hsHashes = (HS_Hashes*)XMALLOC(sizeof(HS_Hashes), ssl->heap,
  6143. DYNAMIC_TYPE_HASHES);
  6144. if (ssl->hsHashes == NULL) {
  6145. WOLFSSL_MSG("HS_Hashes Memory error");
  6146. return MEMORY_E;
  6147. }
  6148. XMEMSET(ssl->hsHashes, 0, sizeof(HS_Hashes));
  6149. #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
  6150. ret = wc_InitMd5_ex(&ssl->hsHashes->hashMd5, ssl->heap, ssl->devId);
  6151. if (ret != 0)
  6152. return ret;
  6153. #ifdef WOLFSSL_HASH_FLAGS
  6154. wc_Md5SetFlags(&ssl->hsHashes->hashMd5, WC_HASH_FLAG_WILLCOPY);
  6155. #endif
  6156. #endif
  6157. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  6158. defined(WOLFSSL_ALLOW_TLS_SHA1))
  6159. ret = wc_InitSha_ex(&ssl->hsHashes->hashSha, ssl->heap, ssl->devId);
  6160. if (ret != 0)
  6161. return ret;
  6162. #ifdef WOLFSSL_HASH_FLAGS
  6163. wc_ShaSetFlags(&ssl->hsHashes->hashSha, WC_HASH_FLAG_WILLCOPY);
  6164. #endif
  6165. #endif
  6166. #ifndef NO_SHA256
  6167. ret = wc_InitSha256_ex(&ssl->hsHashes->hashSha256, ssl->heap, ssl->devId);
  6168. if (ret != 0)
  6169. return ret;
  6170. #ifdef WOLFSSL_HASH_FLAGS
  6171. wc_Sha256SetFlags(&ssl->hsHashes->hashSha256, WC_HASH_FLAG_WILLCOPY);
  6172. #endif
  6173. #endif
  6174. #ifdef WOLFSSL_SHA384
  6175. ret = wc_InitSha384_ex(&ssl->hsHashes->hashSha384, ssl->heap, ssl->devId);
  6176. if (ret != 0)
  6177. return ret;
  6178. #ifdef WOLFSSL_HASH_FLAGS
  6179. wc_Sha384SetFlags(&ssl->hsHashes->hashSha384, WC_HASH_FLAG_WILLCOPY);
  6180. #endif
  6181. #endif
  6182. #ifdef WOLFSSL_SHA512
  6183. ret = wc_InitSha512_ex(&ssl->hsHashes->hashSha512, ssl->heap, ssl->devId);
  6184. if (ret != 0)
  6185. return ret;
  6186. #ifdef WOLFSSL_HASH_FLAGS
  6187. wc_Sha512SetFlags(&ssl->hsHashes->hashSha512, WC_HASH_FLAG_WILLCOPY);
  6188. #endif
  6189. #endif
  6190. #ifdef WOLFSSL_SM3
  6191. ret = wc_InitSm3(&ssl->hsHashes->hashSm3, ssl->heap, ssl->devId);
  6192. if (ret != 0)
  6193. return ret;
  6194. #ifdef WOLFSSL_HASH_FLAGS
  6195. wc_Sm3SetFlags(&ssl->hsHashes->hashSm3, WC_HASH_FLAG_WILLCOPY);
  6196. #endif
  6197. #endif
  6198. return ret;
  6199. }
  6200. void FreeHandshakeHashes(WOLFSSL* ssl)
  6201. {
  6202. if (ssl->hsHashes) {
  6203. #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
  6204. wc_Md5Free(&ssl->hsHashes->hashMd5);
  6205. #endif
  6206. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  6207. defined(WOLFSSL_ALLOW_TLS_SHA1))
  6208. wc_ShaFree(&ssl->hsHashes->hashSha);
  6209. #endif
  6210. #ifndef NO_SHA256
  6211. wc_Sha256Free(&ssl->hsHashes->hashSha256);
  6212. #endif
  6213. #ifdef WOLFSSL_SHA384
  6214. wc_Sha384Free(&ssl->hsHashes->hashSha384);
  6215. #endif
  6216. #ifdef WOLFSSL_SHA512
  6217. wc_Sha512Free(&ssl->hsHashes->hashSha512);
  6218. #endif
  6219. #ifdef WOLFSSL_SM3
  6220. wc_Sm3Free(&ssl->hsHashes->hashSm3);
  6221. #endif
  6222. #if (defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  6223. (defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3))) && \
  6224. !defined(WOLFSSL_NO_CLIENT_AUTH)
  6225. if (ssl->hsHashes->messages != NULL) {
  6226. ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length);
  6227. XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
  6228. ssl->hsHashes->messages = NULL;
  6229. }
  6230. #endif
  6231. XFREE(ssl->hsHashes, ssl->heap, DYNAMIC_TYPE_HASHES);
  6232. ssl->hsHashes = NULL;
  6233. }
  6234. }
  6235. /* copy the hashes from source to a newly made destination return status */
  6236. int InitHandshakeHashesAndCopy(WOLFSSL* ssl, HS_Hashes* source,
  6237. HS_Hashes** destination)
  6238. {
  6239. int ret;
  6240. HS_Hashes* tmpHashes;
  6241. if (source == NULL)
  6242. return BAD_FUNC_ARG;
  6243. /* save the original so we can put it back afterward */
  6244. tmpHashes = ssl->hsHashes;
  6245. ssl->hsHashes = NULL;
  6246. ret = InitHandshakeHashes(ssl);
  6247. if (ret != 0) {
  6248. WOLFSSL_MSG_EX("InitHandshakeHashes failed. err = %d", ret);
  6249. return ret;
  6250. }
  6251. *destination = ssl->hsHashes;
  6252. ssl->hsHashes = tmpHashes;
  6253. /* now copy the source contents to the destination */
  6254. #ifndef NO_OLD_TLS
  6255. #ifndef NO_SHA
  6256. ret = wc_ShaCopy(&source->hashSha, &(*destination)->hashSha);
  6257. #endif
  6258. #ifndef NO_MD5
  6259. if (ret == 0)
  6260. ret = wc_Md5Copy(&source->hashMd5, &(*destination)->hashMd5);
  6261. #endif
  6262. #endif /* !NO_OLD_TLS */
  6263. #ifndef NO_SHA256
  6264. if (ret == 0)
  6265. ret = wc_Sha256Copy(&source->hashSha256,
  6266. &(*destination)->hashSha256);
  6267. #endif
  6268. #ifdef WOLFSSL_SHA384
  6269. if (ret == 0)
  6270. ret = wc_Sha384Copy(&source->hashSha384,
  6271. &(*destination)->hashSha384);
  6272. #endif
  6273. #ifdef WOLFSSL_SHA512
  6274. if (ret == 0)
  6275. ret = wc_Sha512Copy(&source->hashSha512,
  6276. &(*destination)->hashSha512);
  6277. #endif
  6278. #ifdef WOLFSSL_SM3
  6279. if (ret == 0)
  6280. ret = wc_Sm3Copy(&source->hashSm3,
  6281. &(*destination)->hashSm3);
  6282. #endif
  6283. #if (defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  6284. (defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3))) && \
  6285. !defined(WOLFSSL_NO_CLIENT_AUTH)
  6286. if (ret == 0 && source->messages != NULL) {
  6287. (*destination)->messages = (byte*)XMALLOC(source->length, ssl->heap,
  6288. DYNAMIC_TYPE_HASHES);
  6289. (*destination)->length = source->length;
  6290. (*destination)->prevLen = source->prevLen;
  6291. if ((*destination)->messages == NULL) {
  6292. ret = MEMORY_E;
  6293. }
  6294. else {
  6295. XMEMCPY((*destination)->messages, source->messages,
  6296. source->length);
  6297. }
  6298. }
  6299. #endif
  6300. return ret;
  6301. }
  6302. /* called if user attempts to reuse WOLFSSL object for a new session.
  6303. * For example wolfSSL_clear() is called then wolfSSL_connect or accept */
  6304. int ReinitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
  6305. {
  6306. int ret = 0;
  6307. WOLFSSL_ENTER("ReinitSSL");
  6308. /* arrays */
  6309. if (!writeDup && ssl->arrays == NULL) {
  6310. ssl->arrays = (Arrays*)XMALLOC(sizeof(Arrays), ssl->heap,
  6311. DYNAMIC_TYPE_ARRAYS);
  6312. if (ssl->arrays == NULL) {
  6313. WOLFSSL_MSG("Arrays Memory error");
  6314. return MEMORY_E;
  6315. }
  6316. #ifdef WOLFSSL_CHECK_MEM_ZERO
  6317. wc_MemZero_Add("SSL Arrays", ssl->arrays, sizeof(*ssl->arrays));
  6318. #endif
  6319. XMEMSET(ssl->arrays, 0, sizeof(Arrays));
  6320. #if defined(WOLFSSL_TLS13) || defined(WOLFSSL_SNIFFER)
  6321. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  6322. ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN, ssl->heap,
  6323. DYNAMIC_TYPE_SECRET);
  6324. if (ssl->arrays->preMasterSecret == NULL) {
  6325. return MEMORY_E;
  6326. }
  6327. #ifdef WOLFSSL_CHECK_MEM_ZERO
  6328. wc_MemZero_Add("SSL Arrays", ssl->arrays->preMasterSecret, ENCRYPT_LEN);
  6329. #endif
  6330. XMEMSET(ssl->arrays->preMasterSecret, 0, ENCRYPT_LEN);
  6331. #endif
  6332. }
  6333. /* RNG */
  6334. #ifdef SINGLE_THREADED
  6335. if (ssl->rng == NULL) {
  6336. ssl->rng = ctx->rng; /* CTX may have one, if so use it */
  6337. }
  6338. #endif
  6339. if (ssl->rng == NULL) {
  6340. ssl->rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), ssl->heap,DYNAMIC_TYPE_RNG);
  6341. if (ssl->rng == NULL) {
  6342. WOLFSSL_MSG("RNG Memory error");
  6343. return MEMORY_E;
  6344. }
  6345. XMEMSET(ssl->rng, 0, sizeof(WC_RNG));
  6346. ssl->options.weOwnRng = 1;
  6347. /* FIPS RNG API does not accept a heap hint */
  6348. #ifndef HAVE_FIPS
  6349. if ( (ret = wc_InitRng_ex(ssl->rng, ssl->heap, ssl->devId)) != 0) {
  6350. WOLFSSL_MSG("RNG Init error");
  6351. return ret;
  6352. }
  6353. #else
  6354. if ( (ret = wc_InitRng(ssl->rng)) != 0) {
  6355. WOLFSSL_MSG("RNG Init error");
  6356. return ret;
  6357. }
  6358. #endif
  6359. }
  6360. (void)ctx;
  6361. ssl->options.shutdownDone = 0;
  6362. if (ssl->session != NULL)
  6363. ssl->session->side = (byte)ssl->options.side;
  6364. return ret;
  6365. }
  6366. /* init everything to 0, NULL, default values before calling anything that may
  6367. fail so that destructor has a "good" state to cleanup
  6368. ssl object to initialize
  6369. ctx parent factory
  6370. writeDup flag indicating this is a write dup only
  6371. 0 on success */
  6372. int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
  6373. {
  6374. int ret;
  6375. XMEMSET(ssl, 0, sizeof(WOLFSSL));
  6376. #ifdef WOLFSSL_CHECK_MEM_ZERO
  6377. wc_MemZero_Add("SSL Keys", &ssl->keys, sizeof(ssl->keys));
  6378. #ifdef WOLFSSL_TLS13
  6379. wc_MemZero_Add("SSL client secret", &ssl->clientSecret,
  6380. sizeof(ssl->clientSecret));
  6381. wc_MemZero_Add("SSL client secret", &ssl->serverSecret,
  6382. sizeof(ssl->serverSecret));
  6383. #endif
  6384. #ifdef WOLFSSL_HAVE_TLS_UNIQUE
  6385. wc_MemZero_Add("ClientFinished hash", &ssl->clientFinished,
  6386. TLS_FINISHED_SZ_MAX);
  6387. wc_MemZero_Add("ServerFinished hash", &ssl->serverFinished,
  6388. TLS_FINISHED_SZ_MAX);
  6389. #endif
  6390. #endif
  6391. #if defined(WOLFSSL_STATIC_MEMORY)
  6392. if (ctx->heap != NULL) {
  6393. WOLFSSL_HEAP_HINT* ssl_hint;
  6394. WOLFSSL_HEAP_HINT* ctx_hint;
  6395. /* avoid dereferencing a test value */
  6396. #ifdef WOLFSSL_HEAP_TEST
  6397. if (ctx->heap == (void*)WOLFSSL_HEAP_TEST) {
  6398. ssl->heap = ctx->heap;
  6399. }
  6400. else {
  6401. #endif
  6402. ssl->heap = (WOLFSSL_HEAP_HINT*)XMALLOC(sizeof(WOLFSSL_HEAP_HINT),
  6403. ctx->heap, DYNAMIC_TYPE_SSL);
  6404. if (ssl->heap == NULL) {
  6405. return MEMORY_E;
  6406. }
  6407. XMEMSET(ssl->heap, 0, sizeof(WOLFSSL_HEAP_HINT));
  6408. ssl_hint = ((WOLFSSL_HEAP_HINT*)(ssl->heap));
  6409. ctx_hint = ((WOLFSSL_HEAP_HINT*)(ctx->heap));
  6410. ssl_hint->memory = ctx_hint->memory;
  6411. #ifndef WOLFSSL_STATIC_MEMORY_LEAN
  6412. #ifndef SINGLE_THREADED
  6413. /* lock and check IO count / handshake count */
  6414. if (wc_LockMutex(&(ctx_hint->memory->memory_mutex)) != 0) {
  6415. WOLFSSL_MSG("Bad memory_mutex lock");
  6416. XFREE(ssl->heap, ctx->heap, DYNAMIC_TYPE_SSL);
  6417. ssl->heap = NULL; /* free and set to NULL for IO counter */
  6418. WOLFSSL_ERROR_VERBOSE(BAD_MUTEX_E);
  6419. return BAD_MUTEX_E;
  6420. }
  6421. #endif
  6422. if (ctx_hint->memory->maxHa > 0 &&
  6423. ctx_hint->memory->maxHa <= ctx_hint->memory->curHa) {
  6424. WOLFSSL_MSG("At max number of handshakes for static memory");
  6425. #ifndef SINGLE_THREADED
  6426. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  6427. #endif
  6428. XFREE(ssl->heap, ctx->heap, DYNAMIC_TYPE_SSL);
  6429. ssl->heap = NULL; /* free and set to NULL for IO counter */
  6430. return MEMORY_E;
  6431. }
  6432. if (ctx_hint->memory->maxIO > 0 &&
  6433. ctx_hint->memory->maxIO <= ctx_hint->memory->curIO) {
  6434. WOLFSSL_MSG("At max number of IO allowed for static memory");
  6435. #ifndef SINGLE_THREADED
  6436. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  6437. #endif
  6438. XFREE(ssl->heap, ctx->heap, DYNAMIC_TYPE_SSL);
  6439. ssl->heap = NULL; /* free and set to NULL for IO counter */
  6440. return MEMORY_E;
  6441. }
  6442. ctx_hint->memory->curIO++;
  6443. ctx_hint->memory->curHa++;
  6444. ssl_hint->haFlag = 1;
  6445. #ifndef SINGLE_THREADED
  6446. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  6447. #endif
  6448. /* check if tracking stats */
  6449. if (ctx_hint->memory->flag & WOLFMEM_TRACK_STATS) {
  6450. ssl_hint->stats = (WOLFSSL_MEM_CONN_STATS*)XMALLOC(
  6451. sizeof(WOLFSSL_MEM_CONN_STATS), ctx->heap, DYNAMIC_TYPE_SSL);
  6452. if (ssl_hint->stats == NULL) {
  6453. return MEMORY_E;
  6454. }
  6455. XMEMSET(ssl_hint->stats, 0, sizeof(WOLFSSL_MEM_CONN_STATS));
  6456. }
  6457. /* check if using fixed IO buffers */
  6458. if (ctx_hint->memory->flag & WOLFMEM_IO_POOL_FIXED) {
  6459. #ifndef SINGLE_THREADED
  6460. if (wc_LockMutex(&(ctx_hint->memory->memory_mutex)) != 0) {
  6461. WOLFSSL_MSG("Bad memory_mutex lock");
  6462. WOLFSSL_ERROR_VERBOSE(BAD_MUTEX_E);
  6463. return BAD_MUTEX_E;
  6464. }
  6465. #endif
  6466. if (SetFixedIO(ctx_hint->memory, &(ssl_hint->inBuf)) != 1) {
  6467. #ifndef SINGLE_THREADED
  6468. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  6469. #endif
  6470. return MEMORY_E;
  6471. }
  6472. if (SetFixedIO(ctx_hint->memory, &(ssl_hint->outBuf)) != 1) {
  6473. #ifndef SINGLE_THREADED
  6474. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  6475. #endif
  6476. return MEMORY_E;
  6477. }
  6478. if (ssl_hint->outBuf == NULL || ssl_hint->inBuf == NULL) {
  6479. WOLFSSL_MSG("Not enough memory to create fixed IO buffers");
  6480. #ifndef SINGLE_THREADED
  6481. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  6482. #endif
  6483. return MEMORY_E;
  6484. }
  6485. #ifndef SINGLE_THREADED
  6486. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  6487. #endif
  6488. }
  6489. #endif /* !WOLFSSL_STATIC_MEMORY_LEAN */
  6490. #ifdef WOLFSSL_HEAP_TEST
  6491. }
  6492. #endif
  6493. }
  6494. else {
  6495. ssl->heap = ctx->heap;
  6496. }
  6497. #else
  6498. ssl->heap = ctx->heap; /* carry over user heap without static memory */
  6499. #endif /* WOLFSSL_STATIC_MEMORY */
  6500. ssl->buffers.inputBuffer.buffer = ssl->buffers.inputBuffer.staticBuffer;
  6501. ssl->buffers.inputBuffer.bufferSize = STATIC_BUFFER_LEN;
  6502. ssl->buffers.outputBuffer.buffer = ssl->buffers.outputBuffer.staticBuffer;
  6503. ssl->buffers.outputBuffer.bufferSize = STATIC_BUFFER_LEN;
  6504. #ifdef KEEP_PEER_CERT
  6505. InitX509(&ssl->peerCert, 0, ssl->heap);
  6506. #endif
  6507. ssl->rfd = -1; /* set to invalid descriptor */
  6508. ssl->wfd = -1;
  6509. ssl->devId = ctx->devId; /* device for async HW (from wolfAsync_DevOpen) */
  6510. /* initialize states */
  6511. ssl->options.serverState = NULL_STATE;
  6512. ssl->options.clientState = NULL_STATE;
  6513. ssl->options.connectState = CONNECT_BEGIN;
  6514. ssl->options.acceptState = ACCEPT_BEGIN;
  6515. ssl->options.handShakeState = NULL_STATE;
  6516. ssl->options.processReply = doProcessInit;
  6517. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  6518. ssl->options.buildMsgState = BUILD_MSG_BEGIN;
  6519. ssl->encrypt.state = CIPHER_STATE_BEGIN;
  6520. ssl->decrypt.state = CIPHER_STATE_BEGIN;
  6521. #ifndef NO_DH
  6522. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
  6523. !defined(HAVE_SELFTEST)
  6524. ssl->options.dhDoKeyTest = 1;
  6525. #endif
  6526. #endif
  6527. #ifdef WOLFSSL_DTLS
  6528. #ifdef WOLFSSL_SCTP
  6529. ssl->options.dtlsSctp = ctx->dtlsSctp;
  6530. #endif
  6531. #ifdef WOLFSSL_SRTP
  6532. ssl->dtlsSrtpProfiles = ctx->dtlsSrtpProfiles;
  6533. #endif
  6534. #if defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)
  6535. ssl->dtlsMtuSz = ctx->dtlsMtuSz;
  6536. #endif
  6537. ssl->dtls_timeout_init = DTLS_TIMEOUT_INIT;
  6538. ssl->dtls_timeout_max = DTLS_TIMEOUT_MAX;
  6539. ssl->dtls_timeout = ssl->dtls_timeout_init;
  6540. ssl->buffers.dtlsCtx.rfd = -1;
  6541. ssl->buffers.dtlsCtx.wfd = -1;
  6542. ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx; /* prevent invalid pointer access if not */
  6543. ssl->IOCB_WriteCtx = &ssl->buffers.dtlsCtx; /* correctly set */
  6544. #else
  6545. #ifdef HAVE_NETX
  6546. ssl->IOCB_ReadCtx = &ssl->nxCtx; /* default NetX IO ctx, same for read */
  6547. ssl->IOCB_WriteCtx = &ssl->nxCtx; /* and write */
  6548. #elif defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
  6549. ssl->mnCtx = mynewt_ctx_new();
  6550. if(!ssl->mnCtx) {
  6551. return MEMORY_E;
  6552. }
  6553. ssl->IOCB_ReadCtx = ssl->mnCtx; /* default Mynewt IO ctx, same for read */
  6554. ssl->IOCB_WriteCtx = ssl->mnCtx; /* and write */
  6555. #elif defined (WOLFSSL_GNRC)
  6556. ssl->IOCB_ReadCtx = ssl->gnrcCtx;
  6557. ssl->IOCB_WriteCtx = ssl->gnrcCtx;
  6558. #else
  6559. ssl->IOCB_ReadCtx = &ssl->rfd; /* prevent invalid pointer access if not */
  6560. ssl->IOCB_WriteCtx = &ssl->wfd; /* correctly set */
  6561. #endif
  6562. #endif
  6563. #ifndef WOLFSSL_AEAD_ONLY
  6564. #ifndef NO_OLD_TLS
  6565. ssl->hmac = SSL_hmac; /* default to SSLv3 */
  6566. #elif !defined(WOLFSSL_NO_TLS12) && !defined(NO_TLS)
  6567. #if !defined(WOLFSSL_RENESAS_FSPSM_TLS) && \
  6568. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  6569. ssl->hmac = TLS_hmac;
  6570. #else
  6571. ssl->hmac = Renesas_cmn_TLS_hmac;
  6572. #endif
  6573. #endif
  6574. #endif
  6575. #if defined(WOLFSSL_OPENVPN) && defined(HAVE_KEYING_MATERIAL)
  6576. /* Save arrays by default for OpenVPN */
  6577. ssl->options.saveArrays = 1;
  6578. #endif
  6579. ssl->cipher.ssl = ssl;
  6580. #ifdef HAVE_EXTENDED_MASTER
  6581. ssl->options.haveEMS = ctx->haveEMS;
  6582. #endif
  6583. ssl->options.useClientOrder = ctx->useClientOrder;
  6584. ssl->options.mutualAuth = ctx->mutualAuth;
  6585. #ifdef WOLFSSL_TLS13
  6586. #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
  6587. ssl->options.maxTicketTls13 = ctx->maxTicketTls13;
  6588. #endif
  6589. #ifdef HAVE_SESSION_TICKET
  6590. ssl->options.noTicketTls13 = ctx->noTicketTls13;
  6591. #endif
  6592. #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
  6593. ssl->options.noPskDheKe = ctx->noPskDheKe;
  6594. #ifdef HAVE_SUPPORTED_CURVES
  6595. ssl->options.onlyPskDheKe = ctx->onlyPskDheKe;
  6596. #endif /* HAVE_SUPPORTED_CURVES */
  6597. #endif /* HAVE_SESSION_TICKET || !NO_PSK */
  6598. #if defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  6599. ssl->options.postHandshakeAuth = ctx->postHandshakeAuth;
  6600. ssl->options.verifyPostHandshake = ctx->verifyPostHandshake;
  6601. #endif
  6602. if (ctx->numGroups > 0) {
  6603. XMEMCPY(ssl->group, ctx->group, sizeof(*ctx->group) * ctx->numGroups);
  6604. ssl->numGroups = ctx->numGroups;
  6605. }
  6606. #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
  6607. ssl->options.tls13MiddleBoxCompat = 1;
  6608. #endif
  6609. #endif
  6610. #ifdef HAVE_TLS_EXTENSIONS
  6611. #ifdef HAVE_MAX_FRAGMENT
  6612. ssl->max_fragment = MAX_RECORD_SIZE;
  6613. #endif
  6614. #ifdef HAVE_ALPN
  6615. ssl->alpn_peer_requested = NULL;
  6616. ssl->alpn_peer_requested_length = 0;
  6617. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  6618. ssl->alpnSelect = ctx->alpnSelect;
  6619. ssl->alpnSelectArg = ctx->alpnSelectArg;
  6620. #endif
  6621. #if !defined(NO_BIO) && defined(OPENSSL_EXTRA)
  6622. if (ctx->alpn_cli_protos != NULL && ctx->alpn_cli_protos_len > 0) {
  6623. ret = wolfSSL_set_alpn_protos(ssl, ctx->alpn_cli_protos,
  6624. ctx->alpn_cli_protos_len);
  6625. #if defined(WOLFSSL_ERROR_CODE_OPENSSL)
  6626. if (ret) {
  6627. #else
  6628. if (!ret) {
  6629. #endif
  6630. WOLFSSL_MSG("failed to set alpn protos to ssl object");
  6631. return ret;
  6632. }
  6633. }
  6634. #endif
  6635. #endif
  6636. #ifdef HAVE_SUPPORTED_CURVES
  6637. ssl->options.userCurves = ctx->userCurves;
  6638. #endif
  6639. #endif /* HAVE_TLS_EXTENSIONS */
  6640. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  6641. ssl->options.disallowEncThenMac = ctx->disallowEncThenMac;
  6642. #endif
  6643. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
  6644. ssl->options.disableECH = ctx->disableECH;
  6645. #endif
  6646. /* default alert state (none) */
  6647. ssl->alert_history.last_rx.code = -1;
  6648. ssl->alert_history.last_rx.level = -1;
  6649. ssl->alert_history.last_tx.code = -1;
  6650. ssl->alert_history.last_tx.level = -1;
  6651. #ifdef WOLFSSL_SESSION_ID_CTX
  6652. /* copy over application session context ID */
  6653. ssl->sessionCtxSz = ctx->sessionCtxSz;
  6654. XMEMCPY(ssl->sessionCtx, ctx->sessionCtx, ctx->sessionCtxSz);
  6655. #endif
  6656. #ifdef OPENSSL_EXTRA
  6657. ssl->cbioFlag = ctx->cbioFlag;
  6658. ssl->protoMsgCb = ctx->protoMsgCb;
  6659. ssl->protoMsgCtx = ctx->protoMsgCtx;
  6660. /* follow default behavior of setting toInfoOn similar to
  6661. * wolfSSL_set_msg_callback when the callback is set */
  6662. if (ctx->protoMsgCb != NULL) {
  6663. ssl->toInfoOn = 1;
  6664. }
  6665. ssl->disabledCurves = ctx->disabledCurves;
  6666. #endif
  6667. InitCiphers(ssl);
  6668. InitCipherSpecs(&ssl->specs);
  6669. /* all done with init, now can return errors, call other stuff */
  6670. if ((ret = ReinitSSL(ssl, ctx, writeDup)) != 0) {
  6671. WOLFSSL_MSG_EX("ReinitSSL failed. err = %d", ret);
  6672. return ret;
  6673. }
  6674. if (!writeDup) {
  6675. #ifdef OPENSSL_EXTRA
  6676. if ((ssl->param = (WOLFSSL_X509_VERIFY_PARAM*)XMALLOC(
  6677. sizeof(WOLFSSL_X509_VERIFY_PARAM),
  6678. ssl->heap, DYNAMIC_TYPE_OPENSSL)) == NULL) {
  6679. WOLFSSL_MSG("ssl->param memory error");
  6680. return MEMORY_E;
  6681. }
  6682. XMEMSET(ssl->param, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM));
  6683. #endif
  6684. if (ctx->suites == NULL) {
  6685. /* suites */
  6686. ret = AllocateCtxSuites(ctx);
  6687. if (ret != 0)
  6688. return ret;
  6689. InitSSL_CTX_Suites(ctx);
  6690. }
  6691. #ifdef OPENSSL_ALL
  6692. ssl->suitesStack = NULL;
  6693. #endif
  6694. } /* !writeDup */
  6695. /* Initialize SSL with the appropriate fields from it's ctx */
  6696. /* requires valid arrays and suites unless writeDup ing */
  6697. if ((ret = SetSSL_CTX(ssl, ctx, writeDup)) != WOLFSSL_SUCCESS
  6698. #ifdef WOLFSSL_NO_INIT_CTX_KEY
  6699. && ret != WC_NO_ERR_TRACE(NO_PRIVATE_KEY)
  6700. #endif
  6701. ) {
  6702. WOLFSSL_MSG_EX("SetSSL_CTX failed. err = %d", ret);
  6703. return ret;
  6704. }
  6705. ssl->options.dtls = ssl->version.major == DTLS_MAJOR;
  6706. #ifdef HAVE_WRITE_DUP
  6707. if (writeDup) {
  6708. /* all done */
  6709. return 0;
  6710. }
  6711. #endif
  6712. /* hsHashes */
  6713. ret = InitHandshakeHashes(ssl);
  6714. if (ret != 0) {
  6715. WOLFSSL_MSG_EX("InitHandshakeHashes failed. err = %d", ret);
  6716. return ret;
  6717. }
  6718. #if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
  6719. if (ssl->options.dtls && ssl->options.side == WOLFSSL_SERVER_END) {
  6720. /* Initialize both in case we allow downgrading. */
  6721. ret = wolfSSL_DTLS_SetCookieSecret(ssl, NULL, 0);
  6722. if (ret != 0) {
  6723. WOLFSSL_MSG("DTLS Cookie Secret error");
  6724. return ret;
  6725. }
  6726. #if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
  6727. if (IsAtLeastTLSv1_3(ssl->version)) {
  6728. ret = wolfSSL_send_hrr_cookie(ssl, NULL, 0);
  6729. if (ret != WOLFSSL_SUCCESS) {
  6730. WOLFSSL_MSG("DTLS1.3 Cookie secret error");
  6731. return ret;
  6732. }
  6733. }
  6734. #endif /* WOLFSSL_DTLS13 && WOLFSSL_SEND_HRR_COOKIE */
  6735. }
  6736. #endif /* WOLFSSL_DTLS && !NO_WOLFSSL_SERVER */
  6737. #ifdef HAVE_SECRET_CALLBACK
  6738. ssl->sessionSecretCb = NULL;
  6739. ssl->sessionSecretCtx = NULL;
  6740. #ifdef WOLFSSL_TLS13
  6741. ssl->tls13SecretCb = NULL;
  6742. ssl->tls13SecretCtx = NULL;
  6743. #endif
  6744. #endif
  6745. #if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
  6746. if (ctx->keyLogCb != NULL) {
  6747. ssl->keyLogCb = SessionSecret_callback;
  6748. #if defined(WOLFSSL_TLS13)
  6749. ssl->tls13KeyLogCb = SessionSecret_callback_Tls13;
  6750. #endif /*WOLFSSL_TLS13*/
  6751. }
  6752. #endif /*OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */
  6753. ssl->session = wolfSSL_NewSession(ssl->heap);
  6754. if (ssl->session == NULL) {
  6755. WOLFSSL_MSG_EX("SSL Session Memory error. wolfSSL_NewSession "
  6756. "err = %d", ret);
  6757. return MEMORY_E;
  6758. }
  6759. #ifdef HAVE_SESSION_TICKET
  6760. ssl->options.noTicketTls12 = ctx->noTicketTls12;
  6761. #endif
  6762. #ifdef WOLFSSL_MULTICAST
  6763. if (ctx->haveMcast) {
  6764. int i;
  6765. ssl->options.haveMcast = 1;
  6766. ssl->options.mcastID = ctx->mcastID;
  6767. /* Force the state to look like handshake has completed. */
  6768. /* Keying material is supplied externally. */
  6769. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  6770. ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
  6771. ssl->options.connectState = SECOND_REPLY_DONE;
  6772. ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
  6773. ssl->options.handShakeState = HANDSHAKE_DONE;
  6774. ssl->options.handShakeDone = 1;
  6775. for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++)
  6776. ssl->keys.peerSeq[i].peerId = INVALID_PEER_ID;
  6777. }
  6778. #endif
  6779. #if defined(HAVE_SECURE_RENEGOTIATION) || \
  6780. defined(HAVE_SERVER_RENEGOTIATION_INFO)
  6781. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  6782. int useSecureReneg = ssl->ctx->useSecureReneg;
  6783. /* use secure renegotiation by default (not recommend) */
  6784. #if defined(WOLFSSL_SECURE_RENEGOTIATION_ON_BY_DEFAULT) || \
  6785. (defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_NO_TLS12) && \
  6786. !defined(WOLFSSL_HARDEN_TLS_NO_SCR_CHECK))
  6787. useSecureReneg = 1;
  6788. #endif
  6789. if (useSecureReneg) {
  6790. ret = wolfSSL_UseSecureRenegotiation(ssl);
  6791. if (ret != WOLFSSL_SUCCESS)
  6792. return ret;
  6793. }
  6794. }
  6795. #endif /* HAVE_SECURE_RENEGOTIATION */
  6796. #ifdef WOLFSSL_DTLS13
  6797. /* setup 0 (un-protected) epoch */
  6798. ssl->dtls13Epochs[0].isValid = 1;
  6799. ssl->dtls13Epochs[0].side = ENCRYPT_AND_DECRYPT_SIDE;
  6800. ssl->dtls13EncryptEpoch = &ssl->dtls13Epochs[0];
  6801. ssl->dtls13DecryptEpoch = &ssl->dtls13Epochs[0];
  6802. ssl->options.dtls13SendMoreAcks = WOLFSSL_DTLS13_SEND_MOREACK_DEFAULT;
  6803. ssl->dtls13Rtx.rtxRecordTailPtr = &ssl->dtls13Rtx.rtxRecords;
  6804. #endif /* WOLFSSL_DTLS13 */
  6805. #ifdef WOLFSSL_QUIC
  6806. if (ctx->quic.method) {
  6807. ret = wolfSSL_set_quic_method(ssl, ctx->quic.method);
  6808. if (ret != WOLFSSL_SUCCESS)
  6809. return ret;
  6810. }
  6811. #endif
  6812. #if defined(WOLFSSL_MAXQ10XX_TLS)
  6813. ret = wolfSSL_maxq10xx_load_certificate(ssl);
  6814. if (ret != WOLFSSL_SUCCESS)
  6815. return ret;
  6816. #endif
  6817. #if defined(HAVE_SECRET_CALLBACK) && defined(SHOW_SECRETS) && \
  6818. defined(WOLFSSL_SSLKEYLOGFILE) && defined(WOLFSSL_TLS13)
  6819. (void)wolfSSL_set_tls13_secret_cb(ssl, tls13ShowSecrets, NULL);
  6820. #endif
  6821. #if defined(HAVE_SECRET_CALLBACK) && defined(SHOW_SECRETS)
  6822. (void)wolfSSL_set_secret_cb(ssl, tlsShowSecrets, NULL);
  6823. #endif
  6824. #ifdef WOLFSSL_DUAL_ALG_CERTS
  6825. ssl->sigSpec = ctx->sigSpec;
  6826. ssl->sigSpecSz = ctx->sigSpecSz;
  6827. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  6828. /* Returns 0 on success, not WOLFSSL_SUCCESS (1) */
  6829. WOLFSSL_MSG_EX("InitSSL done. return 0 (success)");
  6830. return 0;
  6831. }
  6832. /* free use of temporary arrays */
  6833. void FreeArrays(WOLFSSL* ssl, int keep)
  6834. {
  6835. if (ssl->arrays) {
  6836. if (keep && !IsAtLeastTLSv1_3(ssl->version)) {
  6837. /* keeps session id for user retrieval */
  6838. XMEMCPY(ssl->session->sessionID, ssl->arrays->sessionID, ID_LEN);
  6839. ssl->session->sessionIDSz = ssl->arrays->sessionIDSz;
  6840. }
  6841. if (ssl->arrays->preMasterSecret) {
  6842. ForceZero(ssl->arrays->preMasterSecret, ENCRYPT_LEN);
  6843. XFREE(ssl->arrays->preMasterSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  6844. ssl->arrays->preMasterSecret = NULL;
  6845. }
  6846. XFREE(ssl->arrays->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
  6847. ssl->arrays->pendingMsg = NULL;
  6848. ForceZero(ssl->arrays, sizeof(Arrays)); /* clear arrays struct */
  6849. }
  6850. XFREE(ssl->arrays, ssl->heap, DYNAMIC_TYPE_ARRAYS);
  6851. ssl->arrays = NULL;
  6852. }
  6853. void FreeKey(WOLFSSL* ssl, int type, void** pKey)
  6854. {
  6855. if (ssl && pKey && *pKey) {
  6856. switch (type) {
  6857. #ifndef NO_RSA
  6858. case DYNAMIC_TYPE_RSA:
  6859. wc_FreeRsaKey((RsaKey*)*pKey);
  6860. break;
  6861. #endif /* ! NO_RSA */
  6862. #ifdef HAVE_ECC
  6863. case DYNAMIC_TYPE_ECC:
  6864. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  6865. defined(WC_ASYNC_ENABLE_ECC)
  6866. if (((ecc_key*)*pKey)->nb_ctx != NULL) {
  6867. XFREE(((ecc_key*)*pKey)->nb_ctx, ((ecc_key*)*pKey)->heap,
  6868. DYNAMIC_TYPE_TMP_BUFFER);
  6869. }
  6870. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  6871. WC_ASYNC_ENABLE_ECC */
  6872. wc_ecc_free((ecc_key*)*pKey);
  6873. break;
  6874. #endif /* HAVE_ECC */
  6875. #ifdef HAVE_ED25519
  6876. case DYNAMIC_TYPE_ED25519:
  6877. wc_ed25519_free((ed25519_key*)*pKey);
  6878. break;
  6879. #endif /* HAVE_ED25519 */
  6880. #ifdef HAVE_CURVE25519
  6881. case DYNAMIC_TYPE_CURVE25519:
  6882. wc_curve25519_free((curve25519_key*)*pKey);
  6883. break;
  6884. #endif /* HAVE_CURVE25519 */
  6885. #ifdef HAVE_ED448
  6886. case DYNAMIC_TYPE_ED448:
  6887. wc_ed448_free((ed448_key*)*pKey);
  6888. break;
  6889. #endif /* HAVE_ED448 */
  6890. #ifdef HAVE_CURVE448
  6891. case DYNAMIC_TYPE_CURVE448:
  6892. wc_curve448_free((curve448_key*)*pKey);
  6893. break;
  6894. #endif /* HAVE_CURVE448 */
  6895. #if defined(HAVE_FALCON)
  6896. case DYNAMIC_TYPE_FALCON:
  6897. wc_falcon_free((falcon_key*)*pKey);
  6898. break;
  6899. #endif /* HAVE_FALCON */
  6900. #if defined(HAVE_DILITHIUM)
  6901. case DYNAMIC_TYPE_DILITHIUM:
  6902. wc_dilithium_free((dilithium_key*)*pKey);
  6903. break;
  6904. #endif /* HAVE_DILITHIUM */
  6905. #ifndef NO_DH
  6906. case DYNAMIC_TYPE_DH:
  6907. wc_FreeDhKey((DhKey*)*pKey);
  6908. break;
  6909. #endif /* !NO_DH */
  6910. default:
  6911. break;
  6912. }
  6913. XFREE(*pKey, ssl->heap, type);
  6914. /* Reset pointer */
  6915. *pKey = NULL;
  6916. }
  6917. }
  6918. int AllocKey(WOLFSSL* ssl, int type, void** pKey)
  6919. {
  6920. int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
  6921. size_t sz = 0;
  6922. #ifdef HAVE_ECC
  6923. ecc_key* eccKey;
  6924. #endif /* HAVE_ECC */
  6925. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  6926. defined(WC_ASYNC_ENABLE_ECC)
  6927. ecc_nb_ctx_t* nbCtx;
  6928. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW && WC_ASYNC_ENABLE_ECC*/
  6929. if (ssl == NULL || pKey == NULL) {
  6930. return BAD_FUNC_ARG;
  6931. }
  6932. /* Sanity check key destination */
  6933. if (*pKey != NULL) {
  6934. WOLFSSL_MSG("Key already present!");
  6935. #ifdef WOLFSSL_ASYNC_CRYPT
  6936. /* allow calling this again for async reentry */
  6937. if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  6938. return 0;
  6939. }
  6940. #endif
  6941. return BAD_STATE_E;
  6942. }
  6943. /* Determine size */
  6944. switch (type) {
  6945. #ifndef NO_RSA
  6946. case DYNAMIC_TYPE_RSA:
  6947. sz = sizeof(RsaKey);
  6948. break;
  6949. #endif /* ! NO_RSA */
  6950. #ifdef HAVE_ECC
  6951. case DYNAMIC_TYPE_ECC:
  6952. sz = sizeof(ecc_key);
  6953. break;
  6954. #endif /* HAVE_ECC */
  6955. #ifdef HAVE_ED25519
  6956. case DYNAMIC_TYPE_ED25519:
  6957. sz = sizeof(ed25519_key);
  6958. break;
  6959. #endif /* HAVE_ED25519 */
  6960. #ifdef HAVE_CURVE25519
  6961. case DYNAMIC_TYPE_CURVE25519:
  6962. sz = sizeof(curve25519_key);
  6963. break;
  6964. #endif /* HAVE_CURVE25519 */
  6965. #ifdef HAVE_ED448
  6966. case DYNAMIC_TYPE_ED448:
  6967. sz = sizeof(ed448_key);
  6968. break;
  6969. #endif /* HAVE_ED448 */
  6970. #ifdef HAVE_CURVE448
  6971. case DYNAMIC_TYPE_CURVE448:
  6972. sz = sizeof(curve448_key);
  6973. break;
  6974. #endif /* HAVE_CURVE448 */
  6975. #if defined(HAVE_FALCON)
  6976. case DYNAMIC_TYPE_FALCON:
  6977. sz = sizeof(falcon_key);
  6978. break;
  6979. #endif /* HAVE_FALCON */
  6980. #if defined(HAVE_DILITHIUM)
  6981. case DYNAMIC_TYPE_DILITHIUM:
  6982. sz = sizeof(dilithium_key);
  6983. break;
  6984. #endif /* HAVE_DILITHIUM */
  6985. #ifndef NO_DH
  6986. case DYNAMIC_TYPE_DH:
  6987. sz = sizeof(DhKey);
  6988. break;
  6989. #endif /* !NO_DH */
  6990. default:
  6991. return BAD_FUNC_ARG;
  6992. }
  6993. /* Allocate memory for key */
  6994. *pKey = (void *)XMALLOC(sz, ssl->heap, type);
  6995. if (*pKey == NULL) {
  6996. return MEMORY_E;
  6997. }
  6998. /* Initialize key */
  6999. switch (type) {
  7000. #ifndef NO_RSA
  7001. case DYNAMIC_TYPE_RSA:
  7002. ret = wc_InitRsaKey_ex((RsaKey*)*pKey, ssl->heap, ssl->devId);
  7003. break;
  7004. #endif /* ! NO_RSA */
  7005. #ifdef HAVE_ECC
  7006. case DYNAMIC_TYPE_ECC:
  7007. eccKey = (ecc_key*)*pKey;
  7008. ret = wc_ecc_init_ex(eccKey, ssl->heap, ssl->devId);
  7009. if (ret == 0) {
  7010. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  7011. defined(WC_ASYNC_ENABLE_ECC)
  7012. nbCtx = (ecc_nb_ctx_t*)XMALLOC(sizeof(ecc_nb_ctx_t),
  7013. eccKey->heap, DYNAMIC_TYPE_TMP_BUFFER);
  7014. if (nbCtx == NULL) {
  7015. ret = MEMORY_E;
  7016. }
  7017. else {
  7018. ret = wc_ecc_set_nonblock(eccKey, nbCtx);
  7019. if (ret != 0) {
  7020. XFREE(nbCtx, eccKey->heap, DYNAMIC_TYPE_TMP_BUFFER);
  7021. }
  7022. }
  7023. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  7024. WC_ASYNC_ENABLE_ECC */
  7025. }
  7026. break;
  7027. #endif /* HAVE_ECC */
  7028. #ifdef HAVE_ED25519
  7029. case DYNAMIC_TYPE_ED25519:
  7030. wc_ed25519_init_ex((ed25519_key*)*pKey, ssl->heap, ssl->devId);
  7031. ret = 0;
  7032. break;
  7033. #endif /* HAVE_CURVE25519 */
  7034. #ifdef HAVE_CURVE25519
  7035. case DYNAMIC_TYPE_CURVE25519:
  7036. wc_curve25519_init_ex((curve25519_key*)*pKey, ssl->heap, ssl->devId);
  7037. ret = 0;
  7038. break;
  7039. #endif /* HAVE_CURVE25519 */
  7040. #ifdef HAVE_ED448
  7041. case DYNAMIC_TYPE_ED448:
  7042. wc_ed448_init_ex((ed448_key*)*pKey, ssl->heap, ssl->devId);
  7043. ret = 0;
  7044. break;
  7045. #endif /* HAVE_CURVE448 */
  7046. #if defined(HAVE_FALCON)
  7047. case DYNAMIC_TYPE_FALCON:
  7048. wc_falcon_init_ex((falcon_key*)*pKey, ssl->heap, ssl->devId);
  7049. ret = 0;
  7050. break;
  7051. #endif /* HAVE_FALCON */
  7052. #if defined(HAVE_DILITHIUM)
  7053. case DYNAMIC_TYPE_DILITHIUM:
  7054. wc_dilithium_init_ex((dilithium_key*)*pKey, ssl->heap, ssl->devId);
  7055. ret = 0;
  7056. break;
  7057. #endif /* HAVE_DILITHIUM */
  7058. #ifdef HAVE_CURVE448
  7059. case DYNAMIC_TYPE_CURVE448:
  7060. wc_curve448_init((curve448_key*)*pKey);
  7061. ret = 0;
  7062. break;
  7063. #endif /* HAVE_CURVE448 */
  7064. #ifndef NO_DH
  7065. case DYNAMIC_TYPE_DH:
  7066. ret = wc_InitDhKey_ex((DhKey*)*pKey, ssl->heap, ssl->devId);
  7067. break;
  7068. #endif /* !NO_DH */
  7069. default:
  7070. return BAD_FUNC_ARG;
  7071. }
  7072. /* On error free handshake key */
  7073. if (ret != 0) {
  7074. FreeKey(ssl, type, pKey);
  7075. }
  7076. return ret;
  7077. }
  7078. #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  7079. defined(HAVE_CURVE25519) || defined(HAVE_ED448) || \
  7080. defined(HAVE_CURVE448) || defined(HAVE_FALCON) || defined(HAVE_DILITHIUM)
  7081. static int ReuseKey(WOLFSSL* ssl, int type, void* pKey)
  7082. {
  7083. int ret = 0;
  7084. (void)ssl;
  7085. switch (type) {
  7086. #ifndef NO_RSA
  7087. case DYNAMIC_TYPE_RSA:
  7088. wc_FreeRsaKey((RsaKey*)pKey);
  7089. ret = wc_InitRsaKey_ex((RsaKey*)pKey, ssl->heap, ssl->devId);
  7090. break;
  7091. #endif /* ! NO_RSA */
  7092. #ifdef HAVE_ECC
  7093. case DYNAMIC_TYPE_ECC:
  7094. wc_ecc_free((ecc_key*)pKey);
  7095. ret = wc_ecc_init_ex((ecc_key*)pKey, ssl->heap, ssl->devId);
  7096. break;
  7097. #endif /* HAVE_ECC */
  7098. #ifdef HAVE_ED25519
  7099. case DYNAMIC_TYPE_ED25519:
  7100. wc_ed25519_free((ed25519_key*)pKey);
  7101. ret = wc_ed25519_init_ex((ed25519_key*)pKey, ssl->heap,
  7102. ssl->devId);
  7103. break;
  7104. #endif /* HAVE_CURVE25519 */
  7105. #ifdef HAVE_CURVE25519
  7106. case DYNAMIC_TYPE_CURVE25519:
  7107. wc_curve25519_free((curve25519_key*)pKey);
  7108. ret = wc_curve25519_init_ex((curve25519_key*)pKey, ssl->heap,
  7109. ssl->devId);
  7110. break;
  7111. #endif /* HAVE_CURVE25519 */
  7112. #ifdef HAVE_ED448
  7113. case DYNAMIC_TYPE_ED448:
  7114. wc_ed448_free((ed448_key*)pKey);
  7115. ret = wc_ed448_init_ex((ed448_key*)pKey, ssl->heap, ssl->devId);
  7116. break;
  7117. #endif /* HAVE_CURVE448 */
  7118. #ifdef HAVE_CURVE448
  7119. case DYNAMIC_TYPE_CURVE448:
  7120. wc_curve448_free((curve448_key*)pKey);
  7121. ret = wc_curve448_init((curve448_key*)pKey);
  7122. break;
  7123. #endif /* HAVE_CURVE448 */
  7124. #if defined(HAVE_FALCON)
  7125. case DYNAMIC_TYPE_FALCON:
  7126. wc_falcon_free((falcon_key*)pKey);
  7127. ret = wc_falcon_init((falcon_key*)pKey);
  7128. break;
  7129. #endif /* HAVE_FALCON */
  7130. #if defined(HAVE_DILITHIUM)
  7131. case DYNAMIC_TYPE_DILITHIUM:
  7132. wc_dilithium_free((dilithium_key*)pKey);
  7133. ret = wc_dilithium_init((dilithium_key*)pKey);
  7134. break;
  7135. #endif /* HAVE_DILITHIUM */
  7136. #ifndef NO_DH
  7137. case DYNAMIC_TYPE_DH:
  7138. wc_FreeDhKey((DhKey*)pKey);
  7139. ret = wc_InitDhKey_ex((DhKey*)pKey, ssl->heap, ssl->devId);
  7140. break;
  7141. #endif /* !NO_DH */
  7142. default:
  7143. return BAD_FUNC_ARG;
  7144. }
  7145. return ret;
  7146. }
  7147. #endif
  7148. #ifdef WOLFSSL_ASYNC_IO
  7149. void FreeAsyncCtx(WOLFSSL* ssl, byte freeAsync)
  7150. {
  7151. if (ssl->async != NULL) {
  7152. if (ssl->async->freeArgs != NULL) {
  7153. ssl->async->freeArgs(ssl, ssl->async->args);
  7154. ssl->async->freeArgs = NULL;
  7155. }
  7156. #if defined(WOLFSSL_ASYNC_CRYPT) && !defined(WOLFSSL_NO_TLS12)
  7157. if (ssl->options.buildArgsSet) {
  7158. FreeBuildMsgArgs(ssl, &ssl->async->buildArgs);
  7159. ssl->options.buildArgsSet = 0;
  7160. }
  7161. #endif
  7162. if (freeAsync) {
  7163. XFREE(ssl->async, ssl->heap, DYNAMIC_TYPE_ASYNC);
  7164. ssl->async = NULL;
  7165. }
  7166. }
  7167. }
  7168. #endif
  7169. void FreeKeyExchange(WOLFSSL* ssl)
  7170. {
  7171. /* Cleanup signature buffer */
  7172. if (ssl->buffers.sig.buffer) {
  7173. XFREE(ssl->buffers.sig.buffer, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  7174. ssl->buffers.sig.buffer = NULL;
  7175. ssl->buffers.sig.length = 0;
  7176. }
  7177. /* Cleanup digest buffer */
  7178. if (ssl->buffers.digest.buffer) {
  7179. /* Only free if digest buffer was not set using SetDigest */
  7180. if (!ssl->options.dontFreeDigest) {
  7181. XFREE(ssl->buffers.digest.buffer, ssl->heap, DYNAMIC_TYPE_DIGEST);
  7182. }
  7183. ssl->buffers.digest.buffer = NULL;
  7184. ssl->buffers.digest.length = 0;
  7185. ssl->options.dontFreeDigest = 0;
  7186. }
  7187. /* Free handshake key */
  7188. FreeKey(ssl, (int)ssl->hsType, &ssl->hsKey);
  7189. #ifdef WOLFSSL_DUAL_ALG_CERTS
  7190. FreeKey(ssl, ssl->hsAltType, &ssl->hsAltKey);
  7191. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  7192. #ifndef NO_DH
  7193. /* Free temp DH key */
  7194. FreeKey(ssl, DYNAMIC_TYPE_DH, (void**)&ssl->buffers.serverDH_Key);
  7195. #endif
  7196. }
  7197. /* Free up all memory used by Suites structure from WOLFSSL */
  7198. void FreeSuites(WOLFSSL* ssl)
  7199. {
  7200. #ifdef OPENSSL_ALL
  7201. if (ssl->suitesStack != NULL) {
  7202. /* Enough to free stack structure since WOLFSSL_CIPHER
  7203. * isn't allocated separately. */
  7204. wolfSSL_sk_SSL_CIPHER_free(ssl->suitesStack);
  7205. ssl->suitesStack = NULL;
  7206. }
  7207. #endif
  7208. XFREE(ssl->suites, ssl->heap, DYNAMIC_TYPE_SUITES);
  7209. ssl->suites = NULL;
  7210. }
  7211. /* In case holding SSL object in array and don't want to free actual ssl */
  7212. void SSL_ResourceFree(WOLFSSL* ssl)
  7213. {
  7214. /* Note: any resources used during the handshake should be released in the
  7215. * function FreeHandshakeResources(). Be careful with the special cases
  7216. * like the RNG which may optionally be kept for the whole session. (For
  7217. * example with the RNG, it isn't used beyond the handshake except when
  7218. * using stream ciphers where it is retained. */
  7219. if (ssl->options.side == WOLFSSL_SERVER_END) {
  7220. WOLFSSL_MSG("Free'ing server ssl");
  7221. }
  7222. else {
  7223. WOLFSSL_MSG("Free'ing client ssl");
  7224. }
  7225. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  7226. wolfSSL_CRYPTO_cleanup_ex_data(&ssl->ex_data);
  7227. #endif
  7228. FreeCiphers(ssl);
  7229. FreeArrays(ssl, 0);
  7230. FreeKeyExchange(ssl);
  7231. #ifdef WOLFSSL_ASYNC_IO
  7232. /* Cleanup async */
  7233. FreeAsyncCtx(ssl, 1);
  7234. #endif
  7235. if (ssl->options.weOwnRng) {
  7236. wc_FreeRng(ssl->rng);
  7237. XFREE(ssl->rng, ssl->heap, DYNAMIC_TYPE_RNG);
  7238. ssl->rng = NULL;
  7239. ssl->options.weOwnRng = 0;
  7240. }
  7241. FreeSuites(ssl);
  7242. FreeHandshakeHashes(ssl);
  7243. XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
  7244. /* clear keys struct after session */
  7245. ForceZero(&ssl->keys, sizeof(Keys));
  7246. #ifdef WOLFSSL_TLS13
  7247. ForceZero(&ssl->clientSecret, sizeof(ssl->clientSecret));
  7248. ForceZero(&ssl->serverSecret, sizeof(ssl->serverSecret));
  7249. #if defined(HAVE_ECH)
  7250. if (ssl->options.useEch == 1) {
  7251. FreeEchConfigs(ssl->echConfigs, ssl->heap);
  7252. ssl->echConfigs = NULL;
  7253. /* free the ech specific hashes */
  7254. ssl->hsHashes = ssl->hsHashesEch;
  7255. FreeHandshakeHashes(ssl);
  7256. ssl->options.useEch = 0;
  7257. }
  7258. #endif /* HAVE_ECH */
  7259. #endif /* WOLFSSL_TLS13 */
  7260. #ifdef WOLFSSL_HAVE_TLS_UNIQUE
  7261. ForceZero(&ssl->clientFinished, TLS_FINISHED_SZ_MAX);
  7262. ForceZero(&ssl->serverFinished, TLS_FINISHED_SZ_MAX);
  7263. ssl->serverFinished_len = 0;
  7264. ssl->clientFinished_len = 0;
  7265. #endif
  7266. #ifndef NO_DH
  7267. if (ssl->buffers.serverDH_Priv.buffer != NULL) {
  7268. ForceZero(ssl->buffers.serverDH_Priv.buffer,
  7269. ssl->buffers.serverDH_Priv.length);
  7270. }
  7271. XFREE(ssl->buffers.serverDH_Priv.buffer, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  7272. XFREE(ssl->buffers.serverDH_Pub.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7273. /* parameters (p,g) may be owned by ctx */
  7274. if (ssl->buffers.weOwnDH) {
  7275. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7276. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7277. }
  7278. #endif /* !NO_DH */
  7279. #ifndef NO_CERTS
  7280. ssl->keepCert = 0; /* make sure certificate is free'd */
  7281. wolfSSL_UnloadCertsKeys(ssl);
  7282. #endif
  7283. #ifndef NO_RSA
  7284. FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
  7285. ssl->peerRsaKeyPresent = 0;
  7286. #endif
  7287. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  7288. XFREE(ssl->peerSceTsipEncRsaKeyIndex, ssl->heap, DYNAMIC_TYPE_RSA);
  7289. Renesas_cmn_Cleanup(ssl);
  7290. #endif
  7291. if (ssl->buffers.inputBuffer.dynamicFlag)
  7292. ShrinkInputBuffer(ssl, FORCED_FREE);
  7293. if (ssl->buffers.outputBuffer.dynamicFlag)
  7294. ShrinkOutputBuffer(ssl);
  7295. #if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
  7296. if (ssl->buffers.tls13CookieSecret.buffer != NULL) {
  7297. ForceZero(ssl->buffers.tls13CookieSecret.buffer,
  7298. ssl->buffers.tls13CookieSecret.length);
  7299. }
  7300. XFREE(ssl->buffers.tls13CookieSecret.buffer, ssl->heap,
  7301. DYNAMIC_TYPE_COOKIE_PWD);
  7302. #endif
  7303. #ifdef WOLFSSL_DTLS
  7304. DtlsMsgPoolReset(ssl);
  7305. if (ssl->dtls_rx_msg_list != NULL) {
  7306. DtlsMsgListDelete(ssl->dtls_rx_msg_list, ssl->heap);
  7307. ssl->dtls_rx_msg_list = NULL;
  7308. ssl->dtls_rx_msg_list_sz = 0;
  7309. }
  7310. XFREE(ssl->buffers.dtlsCtx.peer.sa, ssl->heap, DYNAMIC_TYPE_SOCKADDR);
  7311. ssl->buffers.dtlsCtx.peer.sa = NULL;
  7312. #ifndef NO_WOLFSSL_SERVER
  7313. if (ssl->buffers.dtlsCookieSecret.buffer != NULL) {
  7314. ForceZero(ssl->buffers.dtlsCookieSecret.buffer,
  7315. ssl->buffers.dtlsCookieSecret.length);
  7316. }
  7317. XFREE(ssl->buffers.dtlsCookieSecret.buffer, ssl->heap,
  7318. DYNAMIC_TYPE_COOKIE_PWD);
  7319. #endif
  7320. #ifdef WOLFSSL_DTLS13
  7321. if (ssl->dtls13ClientHello != NULL) {
  7322. XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  7323. ssl->dtls13ClientHello = NULL;
  7324. ssl->dtls13ClientHelloSz = 0;
  7325. }
  7326. #endif /* WOLFSSL_DTLS13 */
  7327. #endif /* WOLFSSL_DTLS */
  7328. #ifdef OPENSSL_EXTRA
  7329. #ifndef NO_BIO
  7330. /* Don't free if there was/is a previous element in the chain.
  7331. * This means that this BIO was part of a chain that will be
  7332. * free'd separately. */
  7333. if (ssl->biord != ssl->biowr) /* only free write if different */
  7334. if (ssl->biowr != NULL && ssl->biowr->prev == NULL)
  7335. wolfSSL_BIO_free(ssl->biowr);
  7336. if (ssl->biord != NULL && ssl->biord->prev == NULL)
  7337. wolfSSL_BIO_free(ssl->biord);
  7338. ssl->biowr = NULL;
  7339. ssl->biord = NULL;
  7340. #endif
  7341. #endif
  7342. #ifdef HAVE_LIBZ
  7343. FreeStreams(ssl);
  7344. #endif
  7345. #ifdef HAVE_ECC
  7346. FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccKey);
  7347. ssl->peerEccKeyPresent = 0;
  7348. FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
  7349. ssl->peerEccDsaKeyPresent = 0;
  7350. #endif
  7351. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) ||defined(HAVE_CURVE448)
  7352. {
  7353. int dtype = 0;
  7354. #ifdef HAVE_ECC
  7355. dtype = DYNAMIC_TYPE_ECC;
  7356. #endif
  7357. #ifdef HAVE_CURVE25519
  7358. if (ssl->peerX25519KeyPresent
  7359. #ifdef HAVE_ECC
  7360. || ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE25519
  7361. #endif /* HAVE_ECC */
  7362. )
  7363. {
  7364. dtype = DYNAMIC_TYPE_CURVE25519;
  7365. }
  7366. #endif /* HAVE_CURVE25519 */
  7367. #ifdef HAVE_CURVE448
  7368. if (ssl->peerX448KeyPresent
  7369. #ifdef HAVE_ECC
  7370. || ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE448
  7371. #endif /* HAVE_ECC */
  7372. )
  7373. {
  7374. dtype = DYNAMIC_TYPE_CURVE448;
  7375. }
  7376. #endif /* HAVE_CURVE448 */
  7377. FreeKey(ssl, dtype, (void**)&ssl->eccTempKey);
  7378. ssl->eccTempKeyPresent = 0;
  7379. }
  7380. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  7381. #ifdef HAVE_CURVE25519
  7382. FreeKey(ssl, DYNAMIC_TYPE_CURVE25519, (void**)&ssl->peerX25519Key);
  7383. ssl->peerX25519KeyPresent = 0;
  7384. #endif
  7385. #ifdef HAVE_ED25519
  7386. FreeKey(ssl, DYNAMIC_TYPE_ED25519, (void**)&ssl->peerEd25519Key);
  7387. ssl->peerEd25519KeyPresent = 0;
  7388. #ifdef HAVE_PK_CALLBACKS
  7389. if (ssl->buffers.peerEd25519Key.buffer != NULL) {
  7390. XFREE(ssl->buffers.peerEd25519Key.buffer, ssl->heap,
  7391. DYNAMIC_TYPE_ED25519);
  7392. ssl->buffers.peerEd25519Key.buffer = NULL;
  7393. }
  7394. #endif
  7395. #endif
  7396. #ifdef HAVE_CURVE448
  7397. FreeKey(ssl, DYNAMIC_TYPE_CURVE448, (void**)&ssl->peerX448Key);
  7398. ssl->peerX448KeyPresent = 0;
  7399. #endif
  7400. #ifdef HAVE_ED448
  7401. FreeKey(ssl, DYNAMIC_TYPE_ED448, (void**)&ssl->peerEd448Key);
  7402. ssl->peerEd448KeyPresent = 0;
  7403. #ifdef HAVE_PK_CALLBACKS
  7404. if (ssl->buffers.peerEd448Key.buffer != NULL) {
  7405. XFREE(ssl->buffers.peerEd448Key.buffer, ssl->heap,
  7406. DYNAMIC_TYPE_ED448);
  7407. ssl->buffers.peerEd448Key.buffer = NULL;
  7408. }
  7409. #endif
  7410. #endif
  7411. #if defined(HAVE_FALCON)
  7412. FreeKey(ssl, DYNAMIC_TYPE_FALCON, (void**)&ssl->peerFalconKey);
  7413. ssl->peerFalconKeyPresent = 0;
  7414. #endif
  7415. #ifdef HAVE_PK_CALLBACKS
  7416. #ifdef HAVE_ECC
  7417. XFREE(ssl->buffers.peerEccDsaKey.buffer, ssl->heap, DYNAMIC_TYPE_ECC);
  7418. #endif /* HAVE_ECC */
  7419. #ifndef NO_RSA
  7420. XFREE(ssl->buffers.peerRsaKey.buffer, ssl->heap, DYNAMIC_TYPE_RSA);
  7421. #endif /* NO_RSA */
  7422. #endif /* HAVE_PK_CALLBACKS */
  7423. #ifdef HAVE_TLS_EXTENSIONS
  7424. #if !defined(NO_TLS)
  7425. TLSX_FreeAll(ssl->extensions, ssl->heap);
  7426. #endif /* !NO_TLS */
  7427. #ifdef HAVE_ALPN
  7428. if (ssl->alpn_peer_requested != NULL) {
  7429. XFREE(ssl->alpn_peer_requested, ssl->heap, DYNAMIC_TYPE_ALPN);
  7430. ssl->alpn_peer_requested = NULL;
  7431. ssl->alpn_peer_requested_length = 0;
  7432. }
  7433. #endif
  7434. #endif /* HAVE_TLS_EXTENSIONS */
  7435. #if defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
  7436. if (ssl->mnCtx) {
  7437. mynewt_ctx_clear(ssl->mnCtx);
  7438. ssl->mnCtx = NULL;
  7439. }
  7440. #endif
  7441. #ifdef HAVE_NETX
  7442. if (ssl->nxCtx.nxPacket)
  7443. nx_packet_release(ssl->nxCtx.nxPacket);
  7444. #endif
  7445. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  7446. if (ssl->x509_store_pt)
  7447. wolfSSL_X509_STORE_free(ssl->x509_store_pt);
  7448. #endif
  7449. #ifdef KEEP_PEER_CERT
  7450. FreeX509(&ssl->peerCert);
  7451. #endif
  7452. if (ssl->session != NULL)
  7453. wolfSSL_FreeSession(ssl->ctx, ssl->session);
  7454. #ifdef HAVE_WRITE_DUP
  7455. if (ssl->dupWrite) {
  7456. FreeWriteDup(ssl);
  7457. }
  7458. #endif
  7459. #ifdef OPENSSL_EXTRA
  7460. XFREE(ssl->param, ssl->heap, DYNAMIC_TYPE_OPENSSL);
  7461. #endif
  7462. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  7463. while (ssl->certReqCtx != NULL) {
  7464. CertReqCtx* curr = ssl->certReqCtx;
  7465. ssl->certReqCtx = curr->next;
  7466. XFREE(curr, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  7467. }
  7468. #endif
  7469. #ifdef WOLFSSL_STATIC_EPHEMERAL
  7470. #ifndef NO_DH
  7471. FreeDer(&ssl->staticKE.dhKey);
  7472. #endif
  7473. #ifdef HAVE_ECC
  7474. FreeDer(&ssl->staticKE.ecKey);
  7475. #endif
  7476. #ifdef HAVE_CURVE25519
  7477. FreeDer(&ssl->staticKE.x25519Key);
  7478. #endif
  7479. #ifdef HAVE_CURVE448
  7480. FreeDer(&ssl->staticKE.x448Key);
  7481. #endif
  7482. #endif
  7483. #ifdef WOLFSSL_STATIC_MEMORY
  7484. /* check if using fixed io buffers and free them */
  7485. if (ssl->heap != NULL) {
  7486. #ifdef WOLFSSL_HEAP_TEST
  7487. /* avoid dereferencing a test value */
  7488. if (ssl->heap != (void*)WOLFSSL_HEAP_TEST) {
  7489. #endif
  7490. void* heap = ssl->ctx ? ssl->ctx->heap : ssl->heap;
  7491. #ifndef WOLFSSL_STATIC_MEMORY_LEAN
  7492. WOLFSSL_HEAP_HINT* ssl_hint = (WOLFSSL_HEAP_HINT*)ssl->heap;
  7493. WOLFSSL_HEAP* ctx_heap;
  7494. ctx_heap = ssl_hint->memory;
  7495. #ifndef SINGLE_THREADED
  7496. if (wc_LockMutex(&(ctx_heap->memory_mutex)) != 0) {
  7497. WOLFSSL_MSG("Bad memory_mutex lock");
  7498. }
  7499. #endif
  7500. ctx_heap->curIO--;
  7501. if (FreeFixedIO(ctx_heap, &(ssl_hint->outBuf)) != 1) {
  7502. WOLFSSL_MSG("Error freeing fixed output buffer");
  7503. }
  7504. if (FreeFixedIO(ctx_heap, &(ssl_hint->inBuf)) != 1) {
  7505. WOLFSSL_MSG("Error freeing fixed output buffer");
  7506. }
  7507. /* check if handshake count has been decreased*/
  7508. if (ssl_hint->haFlag && ctx_heap->curHa > 0) {
  7509. ctx_heap->curHa--;
  7510. }
  7511. #ifndef SINGLE_THREADED
  7512. wc_UnLockMutex(&(ctx_heap->memory_mutex));
  7513. #endif
  7514. /* check if tracking stats */
  7515. if (ctx_heap->flag & WOLFMEM_TRACK_STATS) {
  7516. XFREE(ssl_hint->stats, heap, DYNAMIC_TYPE_SSL);
  7517. }
  7518. #endif /* !WOLFSSL_STATIC_MEMORY_LEAN */
  7519. XFREE(ssl->heap, heap, DYNAMIC_TYPE_SSL);
  7520. #ifdef WOLFSSL_HEAP_TEST
  7521. }
  7522. #endif
  7523. }
  7524. #endif /* WOLFSSL_STATIC_MEMORY */
  7525. #ifdef OPENSSL_EXTRA
  7526. /* Enough to free stack structure since WOLFSSL_CIPHER
  7527. * isn't allocated separately. */
  7528. wolfSSL_sk_CIPHER_free(ssl->supportedCiphers);
  7529. wolfSSL_sk_X509_pop_free(ssl->peerCertChain, NULL);
  7530. #ifdef KEEP_OUR_CERT
  7531. wolfSSL_sk_X509_pop_free(ssl->ourCertChain, NULL);
  7532. #endif
  7533. #endif
  7534. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || defined(HAVE_LIGHTY)
  7535. wolfSSL_sk_X509_NAME_pop_free(ssl->client_ca_names, NULL);
  7536. ssl->client_ca_names = NULL;
  7537. #endif
  7538. #ifdef WOLFSSL_DTLS13
  7539. Dtls13FreeFsmResources(ssl);
  7540. #endif /* WOLFSSL_DTLS13 */
  7541. #ifdef WOLFSSL_QUIC
  7542. wolfSSL_quic_free(ssl);
  7543. #endif
  7544. #if defined(WOLFSSL_HAPROXY)
  7545. wolfSSL_CTX_free(ssl->initial_ctx);
  7546. ssl->initial_ctx = NULL;
  7547. #endif
  7548. #ifdef WOLFSSL_DUAL_ALG_CERTS
  7549. XFREE(ssl->peerSigSpec, ssl->heap, DYNAMIC_TYPE_TLSX);
  7550. #endif
  7551. }
  7552. /* Free any handshake resources no longer needed */
  7553. void FreeHandshakeResources(WOLFSSL* ssl)
  7554. {
  7555. WOLFSSL_ENTER("FreeHandshakeResources");
  7556. #ifdef WOLFSSL_DTLS
  7557. if (ssl->options.dtls) {
  7558. /* DTLS_POOL (DTLSv1.3 flushes the queue autonomously) */
  7559. if(!IsAtLeastTLSv1_3(ssl->version)) {
  7560. DtlsMsgPoolReset(ssl);
  7561. DtlsMsgListDelete(ssl->dtls_rx_msg_list, ssl->heap);
  7562. ssl->dtls_rx_msg_list = NULL;
  7563. ssl->dtls_rx_msg_list_sz = 0;
  7564. }
  7565. #ifdef WOLFSSL_DTLS13
  7566. if (ssl->dtls13ClientHello != NULL) {
  7567. XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
  7568. ssl->dtls13ClientHello = NULL;
  7569. ssl->dtls13ClientHelloSz = 0;
  7570. }
  7571. #endif /* WOLFSSL_DTLS13 */
  7572. }
  7573. #endif
  7574. #ifdef HAVE_SECURE_RENEGOTIATION
  7575. if (ssl->secure_renegotiation && ssl->secure_renegotiation->enabled) {
  7576. WOLFSSL_MSG("Secure Renegotiation needs to retain handshake resources");
  7577. return;
  7578. }
  7579. #endif
  7580. /* input buffer */
  7581. if (ssl->buffers.inputBuffer.dynamicFlag)
  7582. ShrinkInputBuffer(ssl, NO_FORCED_FREE);
  7583. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  7584. if (!ssl->options.tls1_3)
  7585. #endif
  7586. {
  7587. #ifndef OPENSSL_EXTRA
  7588. /* free suites unless using compatibility layer */
  7589. FreeSuites(ssl);
  7590. #endif
  7591. /* hsHashes */
  7592. FreeHandshakeHashes(ssl);
  7593. }
  7594. /* RNG */
  7595. if (ssl->options.tls1_1 == 0
  7596. #ifndef WOLFSSL_AEAD_ONLY
  7597. || ssl->specs.cipher_type == stream
  7598. #endif
  7599. #if defined(WOLFSSL_TLS13)
  7600. /* Post-handshake auth requires random on client side for TLS 1.3.
  7601. * Session ticket requires random on server side.
  7602. */
  7603. #if !defined(WOLFSSL_POST_HANDSHAKE_AUTH) && !defined(HAVE_SESSION_TICKET)
  7604. || ssl->options.tls1_3
  7605. #elif !defined(WOLFSSL_POST_HANDSHAKE_AUTH) && defined(HAVE_SESSION_TICKET)
  7606. || (ssl->options.tls1_3 && ssl->options.side == WOLFSSL_CLIENT_END)
  7607. #elif !defined(HAVE_SESSION_TICKET)
  7608. || (ssl->options.tls1_3 && ssl->options.side == WOLFSSL_SERVER_END)
  7609. #endif
  7610. #endif
  7611. ) {
  7612. if (ssl->options.weOwnRng) {
  7613. wc_FreeRng(ssl->rng);
  7614. XFREE(ssl->rng, ssl->heap, DYNAMIC_TYPE_RNG);
  7615. ssl->rng = NULL;
  7616. ssl->options.weOwnRng = 0;
  7617. }
  7618. }
  7619. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) && \
  7620. defined(HAVE_SESSION_TICKET)
  7621. if (!ssl->options.tls1_3)
  7622. #endif
  7623. /* arrays */
  7624. if (ssl->options.saveArrays == 0)
  7625. FreeArrays(ssl, 1);
  7626. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  7627. if (!ssl->options.tls1_3 || ssl->options.side == WOLFSSL_CLIENT_END)
  7628. #endif
  7629. {
  7630. #ifndef NO_RSA
  7631. /* peerRsaKey */
  7632. FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
  7633. ssl->peerRsaKeyPresent = 0;
  7634. #endif
  7635. #ifdef HAVE_ECC
  7636. FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
  7637. ssl->peerEccDsaKeyPresent = 0;
  7638. #endif /* HAVE_ECC */
  7639. #ifdef HAVE_ED25519
  7640. FreeKey(ssl, DYNAMIC_TYPE_ED25519, (void**)&ssl->peerEd25519Key);
  7641. ssl->peerEd25519KeyPresent = 0;
  7642. #endif /* HAVE_ED25519 */
  7643. #ifdef HAVE_ED448
  7644. FreeKey(ssl, DYNAMIC_TYPE_ED448, (void**)&ssl->peerEd448Key);
  7645. ssl->peerEd448KeyPresent = 0;
  7646. #endif /* HAVE_ED448 */
  7647. #if defined(HAVE_FALCON)
  7648. FreeKey(ssl, DYNAMIC_TYPE_FALCON, (void**)&ssl->peerFalconKey);
  7649. ssl->peerFalconKeyPresent = 0;
  7650. #endif /* HAVE_FALCON */
  7651. }
  7652. #ifdef HAVE_ECC
  7653. FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccKey);
  7654. ssl->peerEccKeyPresent = 0;
  7655. #endif
  7656. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  7657. {
  7658. int dtype;
  7659. #ifdef HAVE_ECC
  7660. dtype = DYNAMIC_TYPE_ECC;
  7661. #elif defined(HAVE_CURVE25519)
  7662. dtype = DYNAMIC_TYPE_CURVE25519;
  7663. #else
  7664. dtype = DYNAMIC_TYPE_CURVE448;
  7665. #endif
  7666. #if defined(HAVE_ECC) && defined(HAVE_CURVE25519)
  7667. if (ssl->peerX25519KeyPresent ||
  7668. ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE25519)
  7669. {
  7670. dtype = DYNAMIC_TYPE_CURVE25519;
  7671. }
  7672. #endif
  7673. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519)) && \
  7674. defined(HAVE_CURVE448)
  7675. if (ssl->peerX448KeyPresent ||
  7676. ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE448)
  7677. {
  7678. dtype = DYNAMIC_TYPE_CURVE448;
  7679. }
  7680. #endif
  7681. FreeKey(ssl, dtype, (void**)&ssl->eccTempKey);
  7682. ssl->eccTempKeyPresent = 0;
  7683. }
  7684. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  7685. #ifdef HAVE_CURVE25519
  7686. FreeKey(ssl, DYNAMIC_TYPE_CURVE25519, (void**)&ssl->peerX25519Key);
  7687. ssl->peerX25519KeyPresent = 0;
  7688. #endif
  7689. #ifdef HAVE_CURVE448
  7690. FreeKey(ssl, DYNAMIC_TYPE_CURVE448, (void**)&ssl->peerX448Key);
  7691. ssl->peerX448KeyPresent = 0;
  7692. #endif
  7693. #ifndef NO_DH
  7694. if (ssl->buffers.serverDH_Priv.buffer) {
  7695. ForceZero(ssl->buffers.serverDH_Priv.buffer,
  7696. ssl->buffers.serverDH_Priv.length);
  7697. }
  7698. XFREE(ssl->buffers.serverDH_Priv.buffer, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  7699. ssl->buffers.serverDH_Priv.buffer = NULL;
  7700. XFREE(ssl->buffers.serverDH_Pub.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7701. ssl->buffers.serverDH_Pub.buffer = NULL;
  7702. /* parameters (p,g) may be owned by ctx */
  7703. if (ssl->buffers.weOwnDH) {
  7704. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7705. ssl->buffers.serverDH_G.buffer = NULL;
  7706. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  7707. ssl->buffers.serverDH_P.buffer = NULL;
  7708. }
  7709. #endif /* !NO_DH */
  7710. #if !defined(NO_CERTS) && !defined(OPENSSL_EXTRA) && \
  7711. !defined(WOLFSSL_WPAS_SMALL)
  7712. #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
  7713. if (ssl->options.side != WOLFSSL_CLIENT_END)
  7714. #endif
  7715. {
  7716. wolfSSL_UnloadCertsKeys(ssl);
  7717. }
  7718. #endif
  7719. #ifdef HAVE_PK_CALLBACKS
  7720. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  7721. if (!ssl->options.tls1_3 || ssl->options.side == WOLFSSL_CLIENT_END)
  7722. #endif
  7723. {
  7724. #ifdef HAVE_ECC
  7725. XFREE(ssl->buffers.peerEccDsaKey.buffer, ssl->heap, DYNAMIC_TYPE_ECC);
  7726. ssl->buffers.peerEccDsaKey.buffer = NULL;
  7727. #endif /* HAVE_ECC */
  7728. #ifndef NO_RSA
  7729. XFREE(ssl->buffers.peerRsaKey.buffer, ssl->heap, DYNAMIC_TYPE_RSA);
  7730. ssl->buffers.peerRsaKey.buffer = NULL;
  7731. #endif /* NO_RSA */
  7732. #ifdef HAVE_ED25519
  7733. XFREE(ssl->buffers.peerEd25519Key.buffer, ssl->heap,
  7734. DYNAMIC_TYPE_ED25519);
  7735. ssl->buffers.peerEd25519Key.buffer = NULL;
  7736. #endif
  7737. #ifdef HAVE_ED448
  7738. XFREE(ssl->buffers.peerEd448Key.buffer, ssl->heap, DYNAMIC_TYPE_ED448);
  7739. ssl->buffers.peerEd448Key.buffer = NULL;
  7740. #endif
  7741. }
  7742. #endif /* HAVE_PK_CALLBACKS */
  7743. #if defined(HAVE_TLS_EXTENSIONS) && !defined(NO_TLS)
  7744. #if !defined(HAVE_SNI) && !defined(HAVE_ALPN) && !defined(WOLFSSL_DTLS_CID) && \
  7745. !defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  7746. /* Some extensions need to be kept for post-handshake querying. */
  7747. TLSX_FreeAll(ssl->extensions, ssl->heap);
  7748. ssl->extensions = NULL;
  7749. #else
  7750. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
  7751. TLSX_Remove(&ssl->extensions, TLSX_SIGNATURE_ALGORITHMS, ssl->heap);
  7752. #endif
  7753. TLSX_Remove(&ssl->extensions, TLSX_EC_POINT_FORMATS, ssl->heap);
  7754. TLSX_Remove(&ssl->extensions, TLSX_SUPPORTED_GROUPS, ssl->heap);
  7755. #ifdef WOLFSSL_TLS13
  7756. TLSX_Remove(&ssl->extensions, TLSX_SUPPORTED_VERSIONS, ssl->heap);
  7757. TLSX_Remove(&ssl->extensions, TLSX_KEY_SHARE, ssl->heap);
  7758. #endif
  7759. #endif /* !HAVE_SNI && && !HAVE_ALPN && !WOLFSSL_DTLS_CID &&
  7760. * !WOLFSSL_POST_HANDSHAKE_AUTH */
  7761. #endif /* HAVE_TLS_EXTENSIONS && !NO_TLS */
  7762. #ifdef WOLFSSL_STATIC_MEMORY
  7763. /* when done with handshake decrement current handshake count */
  7764. if (ssl->heap != NULL) {
  7765. #ifdef WOLFSSL_HEAP_TEST
  7766. /* avoid dereferencing a test value */
  7767. if (ssl->heap != (void*)WOLFSSL_HEAP_TEST) {
  7768. #endif
  7769. WOLFSSL_HEAP_HINT* ssl_hint = (WOLFSSL_HEAP_HINT*)ssl->heap;
  7770. WOLFSSL_HEAP* ctx_heap;
  7771. ctx_heap = ssl_hint->memory;
  7772. #ifndef SINGLE_THREADED
  7773. if (wc_LockMutex(&(ctx_heap->memory_mutex)) != 0) {
  7774. WOLFSSL_MSG("Bad memory_mutex lock");
  7775. }
  7776. #endif
  7777. #ifndef WOLFSSL_STATIC_MEMORY_LEAN
  7778. if (ctx_heap->curHa > 0) {
  7779. ctx_heap->curHa--;
  7780. }
  7781. ssl_hint->haFlag = 0; /* set to zero since handshake has been dec */
  7782. #endif
  7783. #ifndef SINGLE_THREADED
  7784. wc_UnLockMutex(&(ctx_heap->memory_mutex));
  7785. #endif
  7786. #ifdef WOLFSSL_HEAP_TEST
  7787. }
  7788. #endif
  7789. }
  7790. #endif /* WOLFSSL_STATIC_MEMORY */
  7791. }
  7792. /* heap argument is the heap hint used when creating SSL */
  7793. void FreeSSL(WOLFSSL* ssl, void* heap)
  7794. {
  7795. WOLFSSL_CTX* ctx = ssl->ctx;
  7796. SSL_ResourceFree(ssl);
  7797. XFREE(ssl, heap, DYNAMIC_TYPE_SSL);
  7798. if (ctx)
  7799. FreeSSL_Ctx(ctx); /* will decrement and free underlying CTX if 0 */
  7800. (void)heap;
  7801. #ifdef WOLFSSL_CHECK_MEM_ZERO
  7802. wc_MemZero_Check(ssl, sizeof(*ssl));
  7803. #endif
  7804. }
  7805. #if !defined(NO_OLD_TLS) || defined(WOLFSSL_DTLS) || \
  7806. !defined(WOLFSSL_NO_TLS12) || \
  7807. ((defined(HAVE_CHACHA) || defined(HAVE_AESCCM) || defined(HAVE_AESGCM) || \
  7808. defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)) \
  7809. && defined(HAVE_AEAD))
  7810. #if defined(WOLFSSL_DTLS) || !defined(WOLFSSL_NO_TLS12)
  7811. static WC_INLINE void GetSEQIncrement(WOLFSSL* ssl, int verify, word32 seq[2])
  7812. {
  7813. if (verify) {
  7814. seq[0] = ssl->keys.peer_sequence_number_hi;
  7815. seq[1] = ssl->keys.peer_sequence_number_lo++;
  7816. if (seq[1] > ssl->keys.peer_sequence_number_lo) {
  7817. /* handle rollover */
  7818. ssl->keys.peer_sequence_number_hi++;
  7819. }
  7820. }
  7821. else {
  7822. seq[0] = ssl->keys.sequence_number_hi;
  7823. seq[1] = ssl->keys.sequence_number_lo++;
  7824. if (seq[1] > ssl->keys.sequence_number_lo) {
  7825. /* handle rollover */
  7826. ssl->keys.sequence_number_hi++;
  7827. }
  7828. }
  7829. }
  7830. #endif /* WOLFSSL_DTLS || !WOLFSSL_NO_TLS12 */
  7831. #ifdef WOLFSSL_DTLS
  7832. static WC_INLINE void DtlsGetSEQ(WOLFSSL* ssl, int order, word32 seq[2])
  7833. {
  7834. #ifdef HAVE_SECURE_RENEGOTIATION
  7835. order = DtlsCheckOrder(ssl, order);
  7836. #endif
  7837. if (order == PREV_ORDER) {
  7838. /* Previous epoch case */
  7839. if (ssl->options.haveMcast) {
  7840. #ifdef WOLFSSL_MULTICAST
  7841. seq[0] = (((word32)ssl->keys.dtls_epoch - 1) << 16) |
  7842. (ssl->options.mcastID << 8) |
  7843. (ssl->keys.dtls_prev_sequence_number_hi & 0xFF);
  7844. #endif
  7845. }
  7846. else
  7847. seq[0] = (((word32)ssl->keys.dtls_epoch - 1) << 16) |
  7848. (ssl->keys.dtls_prev_sequence_number_hi & 0xFFFF);
  7849. seq[1] = ssl->keys.dtls_prev_sequence_number_lo;
  7850. }
  7851. else if (order == PEER_ORDER) {
  7852. if (ssl->options.haveMcast) {
  7853. #ifdef WOLFSSL_MULTICAST
  7854. seq[0] = ((word32)ssl->keys.curEpoch << 16) |
  7855. (ssl->keys.curPeerId << 8) |
  7856. (ssl->keys.curSeq_hi & 0xFF);
  7857. #endif
  7858. }
  7859. else
  7860. seq[0] = ((word32)ssl->keys.curEpoch << 16) |
  7861. (ssl->keys.curSeq_hi & 0xFFFF);
  7862. seq[1] = ssl->keys.curSeq_lo; /* explicit from peer */
  7863. }
  7864. else {
  7865. if (ssl->options.haveMcast) {
  7866. #ifdef WOLFSSL_MULTICAST
  7867. seq[0] = ((word32)ssl->keys.dtls_epoch << 16) |
  7868. (ssl->options.mcastID << 8) |
  7869. (ssl->keys.dtls_sequence_number_hi & 0xFF);
  7870. #endif
  7871. }
  7872. else
  7873. seq[0] = ((word32)ssl->keys.dtls_epoch << 16) |
  7874. (ssl->keys.dtls_sequence_number_hi & 0xFFFF);
  7875. seq[1] = ssl->keys.dtls_sequence_number_lo;
  7876. }
  7877. }
  7878. static WC_INLINE void DtlsSEQIncrement(WOLFSSL* ssl, int order)
  7879. {
  7880. word32 seq;
  7881. #ifdef HAVE_SECURE_RENEGOTIATION
  7882. order = DtlsCheckOrder(ssl, order);
  7883. #endif
  7884. if (order == PREV_ORDER) {
  7885. seq = ssl->keys.dtls_prev_sequence_number_lo++;
  7886. if (seq > ssl->keys.dtls_prev_sequence_number_lo) {
  7887. /* handle rollover */
  7888. ssl->keys.dtls_prev_sequence_number_hi++;
  7889. }
  7890. }
  7891. else if (order == PEER_ORDER) {
  7892. seq = ssl->keys.peer_sequence_number_lo++;
  7893. if (seq > ssl->keys.peer_sequence_number_lo) {
  7894. /* handle rollover */
  7895. ssl->keys.peer_sequence_number_hi++;
  7896. }
  7897. }
  7898. else {
  7899. seq = ssl->keys.dtls_sequence_number_lo++;
  7900. if (seq > ssl->keys.dtls_sequence_number_lo) {
  7901. /* handle rollover */
  7902. ssl->keys.dtls_sequence_number_hi++;
  7903. }
  7904. }
  7905. }
  7906. #endif /* WOLFSSL_DTLS */
  7907. #if defined(WOLFSSL_DTLS) || !defined(WOLFSSL_NO_TLS12)
  7908. void WriteSEQ(WOLFSSL* ssl, int verifyOrder, byte* out)
  7909. {
  7910. word32 seq[2] = {0, 0};
  7911. if (!ssl->options.dtls) {
  7912. GetSEQIncrement(ssl, verifyOrder, seq);
  7913. }
  7914. else {
  7915. #ifdef WOLFSSL_DTLS
  7916. DtlsGetSEQ(ssl, verifyOrder, seq);
  7917. #endif
  7918. }
  7919. c32toa(seq[0], out);
  7920. c32toa(seq[1], out + OPAQUE32_LEN);
  7921. }
  7922. #endif /* WOLFSSL_DTLS || !WOLFSSL_NO_TLS12 */
  7923. #endif /* !NO_OLD_TLS || WOLFSSL_DTLS || !WOLFSSL_NO_TLS12 ||
  7924. * ((HAVE_CHACHA || HAVE_AESCCM || HAVE_AESGCM || WOLFSSL_SM4_GCM ||
  7925. * WOLFSSL_SM4_CCM) && HAVE_AEAD) */
  7926. #ifdef WOLFSSL_DTLS
  7927. /* functions for managing DTLS datagram reordering */
  7928. /* Need to allocate space for the handshake message header. The hashing
  7929. * routines assume the message pointer is still within the buffer that
  7930. * has the headers, and will include those headers in the hash. The store
  7931. * routines need to take that into account as well. New will allocate
  7932. * extra space for the headers. */
  7933. DtlsMsg* DtlsMsgNew(word32 sz, byte tx, void* heap)
  7934. {
  7935. DtlsMsg* msg;
  7936. WOLFSSL_ENTER("DtlsMsgNew");
  7937. (void)heap;
  7938. msg = (DtlsMsg*)XMALLOC(sizeof(DtlsMsg), heap, DYNAMIC_TYPE_DTLS_MSG);
  7939. if (msg != NULL) {
  7940. XMEMSET(msg, 0, sizeof(DtlsMsg));
  7941. msg->sz = sz;
  7942. msg->type = no_shake;
  7943. if (tx) {
  7944. msg->raw = msg->fullMsg =
  7945. (byte*)XMALLOC(sz + DTLS_HANDSHAKE_HEADER_SZ, heap,
  7946. DYNAMIC_TYPE_DTLS_FRAG);
  7947. msg->ready = 1;
  7948. if (msg->raw == NULL) {
  7949. DtlsMsgDelete(msg, heap);
  7950. msg = NULL;
  7951. }
  7952. }
  7953. }
  7954. return msg;
  7955. }
  7956. void DtlsMsgDelete(DtlsMsg* item, void* heap)
  7957. {
  7958. (void)heap;
  7959. WOLFSSL_ENTER("DtlsMsgDelete");
  7960. if (item != NULL) {
  7961. while (item->fragBucketList != NULL) {
  7962. DtlsFragBucket* next = item->fragBucketList->m.m.next;
  7963. DtlsMsgDestroyFragBucket(item->fragBucketList, heap);
  7964. item->fragBucketList = next;
  7965. }
  7966. XFREE(item->raw, heap, DYNAMIC_TYPE_DTLS_FRAG);
  7967. XFREE(item, heap, DYNAMIC_TYPE_DTLS_MSG);
  7968. }
  7969. }
  7970. void DtlsMsgListDelete(DtlsMsg* head, void* heap)
  7971. {
  7972. DtlsMsg* next;
  7973. WOLFSSL_ENTER("DtlsMsgListDelete");
  7974. while (head) {
  7975. next = head->next;
  7976. DtlsMsgDelete(head, heap);
  7977. head = next;
  7978. }
  7979. }
  7980. /**
  7981. * Drop messages when they are no longer going to be retransmitted
  7982. */
  7983. void DtlsTxMsgListClean(WOLFSSL* ssl)
  7984. {
  7985. DtlsMsg* head = ssl->dtls_tx_msg_list;
  7986. DtlsMsg* next;
  7987. WOLFSSL_ENTER("DtlsTxMsgListClean");
  7988. while (head) {
  7989. next = head->next;
  7990. if (VerifyForTxDtlsMsgDelete(ssl, head))
  7991. DtlsMsgDelete(head, ssl->heap);
  7992. else
  7993. /* Stored packets should be in order so break on first failed
  7994. * verify */
  7995. break;
  7996. ssl->dtls_tx_msg_list_sz--;
  7997. head = next;
  7998. }
  7999. ssl->dtls_tx_msg_list = head;
  8000. }
  8001. static DtlsFragBucket* DtlsMsgCreateFragBucket(word32 offset, const byte* data,
  8002. word32 dataSz, void* heap)
  8003. {
  8004. DtlsFragBucket* bucket =
  8005. (DtlsFragBucket*)XMALLOC(sizeof(DtlsFragBucket) + dataSz, heap,
  8006. DYNAMIC_TYPE_DTLS_FRAG);
  8007. if (bucket != NULL) {
  8008. XMEMSET(bucket, 0, sizeof(*bucket));
  8009. bucket->m.m.next = NULL;
  8010. bucket->m.m.offset = offset;
  8011. bucket->m.m.sz = dataSz;
  8012. if (data != NULL)
  8013. XMEMCPY(bucket->buf, data, dataSz);
  8014. }
  8015. (void)heap;
  8016. return bucket;
  8017. }
  8018. void DtlsMsgDestroyFragBucket(DtlsFragBucket* fragBucket, void* heap)
  8019. {
  8020. (void)heap;
  8021. XFREE(fragBucket, heap, DYNAMIC_TYPE_DTLS_FRAG);
  8022. }
  8023. /*
  8024. * data overlaps with cur but is before next.
  8025. * data + dataSz has to end before or inside next. next can be NULL.
  8026. */
  8027. static DtlsFragBucket* DtlsMsgCombineFragBuckets(DtlsMsg* msg,
  8028. DtlsFragBucket* cur, DtlsFragBucket* next, word32 offset,
  8029. const byte* data, word32 dataSz, void* heap)
  8030. {
  8031. word32 offsetEnd = offset + dataSz;
  8032. word32 newOffset = min(cur->m.m.offset, offset);
  8033. word32 newOffsetEnd;
  8034. word32 newSz;
  8035. word32 overlapSz = cur->m.m.sz;
  8036. DtlsFragBucket** chosenBucket;
  8037. DtlsFragBucket* newBucket;
  8038. DtlsFragBucket* otherBucket;
  8039. byte combineNext = FALSE;
  8040. if (next != NULL && offsetEnd >= next->m.m.offset)
  8041. combineNext = TRUE;
  8042. if (combineNext)
  8043. newOffsetEnd = next->m.m.offset + next->m.m.sz;
  8044. else
  8045. newOffsetEnd = max(cur->m.m.offset + cur->m.m.sz, offsetEnd);
  8046. newSz = newOffsetEnd - newOffset;
  8047. /* Expand the larger bucket if data bridges the gap between cur and next */
  8048. if (!combineNext || cur->m.m.sz >= next->m.m.sz) {
  8049. chosenBucket = &cur;
  8050. otherBucket = next;
  8051. }
  8052. else {
  8053. chosenBucket = &next;
  8054. otherBucket = cur;
  8055. }
  8056. {
  8057. #ifdef XREALLOC
  8058. DtlsFragBucket* tmp = (DtlsFragBucket*)XREALLOC(*chosenBucket,
  8059. sizeof(DtlsFragBucket) + newSz, heap, DYNAMIC_TYPE_DTLS_FRAG);
  8060. #else
  8061. DtlsFragBucket* tmp = (DtlsFragBucket*)XMALLOC(
  8062. sizeof(DtlsFragBucket) + newSz, heap, DYNAMIC_TYPE_DTLS_FRAG);
  8063. #endif
  8064. if (tmp == NULL)
  8065. return NULL;
  8066. #ifndef XREALLOC
  8067. XMEMCPY(tmp, *chosenBucket, sizeof(DtlsFragBucket) +
  8068. (*chosenBucket)->m.m.sz);
  8069. #endif
  8070. if (chosenBucket == &next) {
  8071. /* Update the link */
  8072. DtlsFragBucket* beforeNext = cur;
  8073. while (beforeNext->m.m.next != next)
  8074. beforeNext = beforeNext->m.m.next;
  8075. beforeNext->m.m.next = tmp;
  8076. }
  8077. #ifndef XREALLOC
  8078. XFREE(*chosenBucket, heap, DYNAMIC_TYPE_DTLS_FRAG);
  8079. #endif
  8080. newBucket = *chosenBucket = tmp;
  8081. }
  8082. if (combineNext) {
  8083. /* Put next first since it will always be at the end. Use memmove since
  8084. * newBucket may be next. */
  8085. XMEMMOVE(newBucket->buf + (next->m.m.offset - newOffset), next->buf,
  8086. next->m.m.sz);
  8087. /* memory after newOffsetEnd is already copied. Don't do extra work. */
  8088. newOffsetEnd = next->m.m.offset;
  8089. }
  8090. if (newOffset == offset) {
  8091. /* data comes first */
  8092. if (newOffsetEnd <= offsetEnd) {
  8093. /* data encompasses cur. only copy data */
  8094. XMEMCPY(newBucket->buf, data,
  8095. min(dataSz, newOffsetEnd - newOffset));
  8096. }
  8097. else {
  8098. /* data -> cur. memcpy as much possible as its faster. */
  8099. XMEMMOVE(newBucket->buf + dataSz, cur->buf,
  8100. cur->m.m.sz - (offsetEnd - cur->m.m.offset));
  8101. XMEMCPY(newBucket->buf, data, dataSz);
  8102. }
  8103. }
  8104. else {
  8105. /* cur -> data */
  8106. word32 curOffsetEnd = cur->m.m.offset + cur->m.m.sz;
  8107. if (newBucket != cur)
  8108. XMEMCPY(newBucket->buf, cur->buf, cur->m.m.sz);
  8109. XMEMCPY(newBucket->buf + cur->m.m.sz,
  8110. data + (curOffsetEnd - offset),
  8111. newOffsetEnd - curOffsetEnd);
  8112. }
  8113. /* FINALLY the newBucket is populated correctly */
  8114. /* All buckets up to and including next (if combining) have to be free'd */
  8115. {
  8116. DtlsFragBucket* toFree = cur->m.m.next;
  8117. while (toFree != next) {
  8118. DtlsFragBucket* n = toFree->m.m.next;
  8119. overlapSz += toFree->m.m.sz;
  8120. DtlsMsgDestroyFragBucket(toFree, heap);
  8121. msg->fragBucketListCount--;
  8122. toFree = n;
  8123. }
  8124. if (combineNext) {
  8125. newBucket->m.m.next = next->m.m.next;
  8126. overlapSz += next->m.m.sz;
  8127. DtlsMsgDestroyFragBucket(otherBucket, heap);
  8128. msg->fragBucketListCount--;
  8129. }
  8130. else {
  8131. newBucket->m.m.next = next;
  8132. }
  8133. }
  8134. /* Adjust size in msg */
  8135. msg->bytesReceived += newSz - overlapSz;
  8136. newBucket->m.m.offset = newOffset;
  8137. newBucket->m.m.sz = newSz;
  8138. return newBucket;
  8139. }
  8140. static void DtlsMsgAssembleCompleteMessage(DtlsMsg* msg)
  8141. {
  8142. DtlsHandShakeHeader* dtls;
  8143. /* We have received all necessary fragments. Reconstruct the header. */
  8144. if (msg->fragBucketListCount != 1 || msg->fragBucketList->m.m.offset != 0 ||
  8145. msg->fragBucketList->m.m.sz != msg->sz) {
  8146. WOLFSSL_MSG("Major error in fragment assembly logic");
  8147. return;
  8148. }
  8149. /* Re-cycle the DtlsFragBucket as the buffer that holds the complete
  8150. * handshake message and the header. */
  8151. msg->raw = (byte*)msg->fragBucketList;
  8152. msg->fullMsg = msg->fragBucketList->buf;
  8153. msg->ready = 1;
  8154. /* frag->padding makes sure we can fit the entire DTLS handshake header
  8155. * before frag->buf */
  8156. /* note the dtls pointer needs to be computed from msg->fragBucketList, not
  8157. * from msg->fragBucketList->buf, to avoid a pointerOutOfBounds access
  8158. * detected by cppcheck.
  8159. *
  8160. * also note, the (void *) intermediate cast is necessary to avoid a
  8161. * potential -Wcast-align around alignment of DtlsHandShakeHeader exceeding
  8162. * alignment of char.
  8163. */
  8164. dtls = (DtlsHandShakeHeader*)(void *)((char *)msg->fragBucketList
  8165. + OFFSETOF(DtlsFragBucket,buf)
  8166. - DTLS_HANDSHAKE_HEADER_SZ);
  8167. msg->fragBucketList = NULL;
  8168. msg->fragBucketListCount = 0;
  8169. dtls->type = msg->type;
  8170. c32to24(msg->sz, dtls->length);
  8171. c16toa((word16)msg->seq, dtls->message_seq);
  8172. c32to24(0, dtls->fragment_offset);
  8173. c32to24(msg->sz, dtls->fragment_length);
  8174. }
  8175. int DtlsMsgSet(DtlsMsg* msg, word32 seq, word16 epoch, const byte* data, byte type,
  8176. word32 fragOffset, word32 fragSz, void* heap, word32 totalLen,
  8177. byte encrypted)
  8178. {
  8179. word32 fragOffsetEnd = fragOffset + fragSz;
  8180. WOLFSSL_ENTER("DtlsMsgSet");
  8181. if (msg == NULL || data == NULL || msg->sz != totalLen ||
  8182. fragOffsetEnd > totalLen) {
  8183. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  8184. return BAD_FUNC_ARG;
  8185. }
  8186. if (msg->ready)
  8187. return 0; /* msg is already complete */
  8188. if (msg->type != no_shake) {
  8189. /* msg is already populated with the correct seq, epoch, and type */
  8190. if (msg->type != type || msg->epoch != epoch || msg->seq != seq) {
  8191. WOLFSSL_ERROR_VERBOSE(SEQUENCE_ERROR);
  8192. return SEQUENCE_ERROR;
  8193. }
  8194. msg->encrypted = msg->encrypted && encrypted;
  8195. }
  8196. else {
  8197. msg->type = type;
  8198. msg->epoch = epoch;
  8199. msg->seq = seq;
  8200. msg->encrypted = encrypted;
  8201. }
  8202. if (msg->fragBucketList == NULL) {
  8203. /* Clean list. Create first fragment. */
  8204. msg->fragBucketList = DtlsMsgCreateFragBucket(fragOffset, data, fragSz, heap);
  8205. if (msg->fragBucketList != NULL) {
  8206. msg->bytesReceived = fragSz;
  8207. msg->fragBucketListCount++;
  8208. }
  8209. else {
  8210. return MEMORY_ERROR;
  8211. }
  8212. }
  8213. else {
  8214. /* See if we can expand any existing bucket to fit this new data into */
  8215. DtlsFragBucket* prev = NULL;
  8216. DtlsFragBucket* cur = msg->fragBucketList;
  8217. byte done = 0;
  8218. for (; cur != NULL; prev = cur, cur = cur->m.m.next) {
  8219. word32 curOffset = cur->m.m.offset;
  8220. word32 curEnd = cur->m.m.offset + cur->m.m.sz;
  8221. if (fragOffset >= curOffset && fragOffsetEnd <= curEnd) {
  8222. /* We already have this fragment */
  8223. done = 1;
  8224. break;
  8225. }
  8226. else if (fragOffset <= curEnd) {
  8227. /* found place to store fragment */
  8228. break;
  8229. }
  8230. }
  8231. if (!done) {
  8232. if (cur == NULL) {
  8233. /* We reached the end of the list. data is after and disjointed
  8234. * from anything we have received so far. */
  8235. if (msg->fragBucketListCount >= DTLS_FRAG_POOL_SZ) {
  8236. WOLFSSL_ERROR_VERBOSE(DTLS_TOO_MANY_FRAGMENTS_E);
  8237. return DTLS_TOO_MANY_FRAGMENTS_E;
  8238. }
  8239. prev->m.m.next =
  8240. DtlsMsgCreateFragBucket(fragOffset, data, fragSz, heap);
  8241. if (prev->m.m.next != NULL) {
  8242. msg->bytesReceived += fragSz;
  8243. msg->fragBucketListCount++;
  8244. }
  8245. }
  8246. else if (prev == NULL && fragOffsetEnd < cur->m.m.offset) {
  8247. /* This is the new first fragment we have received */
  8248. if (msg->fragBucketListCount >= DTLS_FRAG_POOL_SZ) {
  8249. WOLFSSL_ERROR_VERBOSE(DTLS_TOO_MANY_FRAGMENTS_E);
  8250. return DTLS_TOO_MANY_FRAGMENTS_E;
  8251. }
  8252. msg->fragBucketList = DtlsMsgCreateFragBucket(fragOffset, data,
  8253. fragSz, heap);
  8254. if (msg->fragBucketList != NULL) {
  8255. msg->fragBucketList->m.m.next = cur;
  8256. msg->bytesReceived += fragSz;
  8257. msg->fragBucketListCount++;
  8258. }
  8259. else {
  8260. /* reset on error */
  8261. msg->fragBucketList = cur;
  8262. }
  8263. }
  8264. else {
  8265. /* Find if this fragment overlaps with any more */
  8266. DtlsFragBucket* next = cur->m.m.next;
  8267. DtlsFragBucket** prev_next = prev != NULL
  8268. ? &prev->m.m.next : &msg->fragBucketList;
  8269. while (next != NULL &&
  8270. (next->m.m.offset + next->m.m.sz) <= fragOffsetEnd)
  8271. next = next->m.m.next;
  8272. /* We can combine the buckets */
  8273. *prev_next = DtlsMsgCombineFragBuckets(msg, cur, next,
  8274. fragOffset, data, fragSz, heap);
  8275. if (*prev_next == NULL) /* reset on error */
  8276. *prev_next = cur;
  8277. }
  8278. }
  8279. }
  8280. if (msg->bytesReceived == msg->sz)
  8281. DtlsMsgAssembleCompleteMessage(msg);
  8282. return 0;
  8283. }
  8284. DtlsMsg* DtlsMsgFind(DtlsMsg* head, word16 epoch, word32 seq)
  8285. {
  8286. WOLFSSL_ENTER("DtlsMsgFind");
  8287. while (head != NULL && !(head->epoch == epoch && head->seq == seq)) {
  8288. head = head->next;
  8289. }
  8290. return head;
  8291. }
  8292. void DtlsMsgStore(WOLFSSL* ssl, word16 epoch, word32 seq, const byte* data,
  8293. word32 dataSz, byte type, word32 fragOffset, word32 fragSz, void* heap)
  8294. {
  8295. /* See if seq exists in the list. If it isn't in the list, make
  8296. * a new item of size dataSz, copy fragSz bytes from data to msg->msg
  8297. * starting at offset fragOffset, and add fragSz to msg->fragSz. If
  8298. * the seq is in the list and it isn't full, copy fragSz bytes from
  8299. * data to msg->msg starting at offset fragOffset, and add fragSz to
  8300. * msg->fragSz. Insertions take into account data already in the list
  8301. * in case there are overlaps in the handshake message due to retransmit
  8302. * messages. The new item should be inserted into the list in its
  8303. * proper position.
  8304. *
  8305. * 1. Find seq in list, or where seq should go in list. If seq not in
  8306. * list, create new item and insert into list. Either case, keep
  8307. * pointer to item.
  8308. * 2. Copy the data from the message to the stored message where it
  8309. * belongs without overlaps.
  8310. */
  8311. DtlsMsg* head = ssl->dtls_rx_msg_list;
  8312. byte encrypted = ssl->keys.decryptedCur == 1;
  8313. WOLFSSL_ENTER("DtlsMsgStore");
  8314. if (head != NULL) {
  8315. DtlsMsg* cur = DtlsMsgFind(head, epoch, seq);
  8316. if (cur == NULL) {
  8317. cur = DtlsMsgNew(dataSz, 0, heap);
  8318. if (cur != NULL) {
  8319. if (DtlsMsgSet(cur, seq, epoch, data, type,
  8320. fragOffset, fragSz, heap, dataSz, encrypted) < 0) {
  8321. DtlsMsgDelete(cur, heap);
  8322. }
  8323. else {
  8324. ssl->dtls_rx_msg_list_sz++;
  8325. head = DtlsMsgInsert(head, cur);
  8326. }
  8327. }
  8328. }
  8329. else {
  8330. /* If this fails, the data is just dropped. */
  8331. DtlsMsgSet(cur, seq, epoch, data, type, fragOffset,
  8332. fragSz, heap, dataSz, encrypted);
  8333. }
  8334. }
  8335. else {
  8336. head = DtlsMsgNew(dataSz, 0, heap);
  8337. if (DtlsMsgSet(head, seq, epoch, data, type, fragOffset,
  8338. fragSz, heap, dataSz, encrypted) < 0) {
  8339. DtlsMsgDelete(head, heap);
  8340. head = NULL;
  8341. }
  8342. else {
  8343. ssl->dtls_rx_msg_list_sz++;
  8344. }
  8345. }
  8346. ssl->dtls_rx_msg_list = head;
  8347. }
  8348. /* DtlsMsgInsert() is an in-order insert. */
  8349. DtlsMsg* DtlsMsgInsert(DtlsMsg* head, DtlsMsg* item)
  8350. {
  8351. WOLFSSL_ENTER("DtlsMsgInsert");
  8352. if (head == NULL || (item->epoch <= head->epoch &&
  8353. item->seq < head->seq)) {
  8354. item->next = head;
  8355. head = item;
  8356. }
  8357. else if (head->next == NULL) {
  8358. head->next = item;
  8359. }
  8360. else {
  8361. DtlsMsg* cur = head->next;
  8362. DtlsMsg* prev = head;
  8363. while (cur) {
  8364. if (item->epoch <= cur->epoch &&
  8365. item->seq < cur->seq) {
  8366. item->next = cur;
  8367. prev->next = item;
  8368. break;
  8369. }
  8370. prev = cur;
  8371. cur = cur->next;
  8372. }
  8373. if (cur == NULL) {
  8374. prev->next = item;
  8375. }
  8376. }
  8377. return head;
  8378. }
  8379. /**
  8380. * DtlsMsgPoolSave() adds the message to the end of the stored transmit
  8381. * list. Must be called BEFORE BuildMessage or DtlsSEQIncrement or
  8382. * anything else that increments ssl->keys.dtls_handshake_number.
  8383. */
  8384. int DtlsMsgPoolSave(WOLFSSL* ssl, const byte* data, word32 dataSz,
  8385. enum HandShakeType type)
  8386. {
  8387. DtlsMsg* item;
  8388. int ret = 0;
  8389. WOLFSSL_ENTER("DtlsMsgPoolSave");
  8390. if (ssl->dtls_tx_msg_list_sz > DTLS_POOL_SZ) {
  8391. WOLFSSL_ERROR(DTLS_POOL_SZ_E);
  8392. return DTLS_POOL_SZ_E;
  8393. }
  8394. item = DtlsMsgNew(dataSz, 1, ssl->heap);
  8395. if (item != NULL) {
  8396. DtlsMsg* cur = ssl->dtls_tx_msg_list;
  8397. XMEMCPY(item->raw, data, dataSz);
  8398. item->epoch = ssl->keys.dtls_epoch;
  8399. item->seq = ssl->keys.dtls_handshake_number;
  8400. item->type = type;
  8401. if (cur == NULL)
  8402. ssl->dtls_tx_msg_list = item;
  8403. else {
  8404. while (cur->next)
  8405. cur = cur->next;
  8406. cur->next = item;
  8407. }
  8408. ssl->dtls_tx_msg_list_sz++;
  8409. }
  8410. else
  8411. ret = MEMORY_E;
  8412. WOLFSSL_LEAVE("DtlsMsgPoolSave()", ret);
  8413. return ret;
  8414. }
  8415. /* DtlsMsgPoolTimeout() updates the timeout time. */
  8416. int DtlsMsgPoolTimeout(WOLFSSL* ssl)
  8417. {
  8418. int result = -1;
  8419. WOLFSSL_ENTER("DtlsMsgPoolTimeout");
  8420. if (ssl->dtls_timeout < ssl->dtls_timeout_max) {
  8421. ssl->dtls_timeout *= DTLS_TIMEOUT_MULTIPLIER;
  8422. result = 0;
  8423. }
  8424. WOLFSSL_LEAVE("DtlsMsgPoolTimeout()", result);
  8425. return result;
  8426. }
  8427. /* DtlsMsgPoolReset() deletes the stored transmit list. */
  8428. void DtlsMsgPoolReset(WOLFSSL* ssl)
  8429. {
  8430. WOLFSSL_ENTER("DtlsMsgPoolReset");
  8431. if (ssl->dtls_tx_msg_list) {
  8432. DtlsMsgListDelete(ssl->dtls_tx_msg_list, ssl->heap);
  8433. ssl->dtls_tx_msg_list = NULL;
  8434. ssl->dtls_tx_msg = NULL;
  8435. ssl->dtls_tx_msg_list_sz = 0;
  8436. }
  8437. #ifdef WOLFSSL_DTLS13
  8438. /* Clear DTLS 1.3 buffer too */
  8439. Dtls13RtxFlushBuffered(ssl, 1);
  8440. #endif
  8441. }
  8442. int VerifyForDtlsMsgPoolSend(WOLFSSL* ssl, byte type, word32 fragOffset)
  8443. {
  8444. /**
  8445. * only the first message from previous flight should be valid
  8446. * to be used for triggering retransmission of whole DtlsMsgPool.
  8447. * change cipher suite type is not verified here
  8448. */
  8449. if (fragOffset == 0) {
  8450. if (ssl->options.side == WOLFSSL_SERVER_END) {
  8451. if (type == client_hello)
  8452. return 1;
  8453. else if (ssl->options.verifyPeer && type == certificate)
  8454. return 1;
  8455. else if (!ssl->options.verifyPeer && type == client_key_exchange)
  8456. return 1;
  8457. }
  8458. else {
  8459. if (type == hello_request || type == server_hello)
  8460. return 1;
  8461. }
  8462. }
  8463. return 0;
  8464. }
  8465. /**
  8466. * Verify if message `item` from `ssl->dtls_tx_msg_list` should be deleted
  8467. * depending on the current state of the handshake negotiation.
  8468. */
  8469. int VerifyForTxDtlsMsgDelete(WOLFSSL* ssl, DtlsMsg* item)
  8470. {
  8471. WOLFSSL_ENTER("VerifyForTxDtlsMsgDelete");
  8472. if (item->epoch < ssl->keys.dtls_epoch - 1)
  8473. /* Messages not from current or previous epoch can be deleted */
  8474. return 1;
  8475. switch (ssl->options.side) {
  8476. case WOLFSSL_CLIENT_END:
  8477. if (item->type == client_hello &&
  8478. ssl->options.serverState >= SERVER_HELLODONE_COMPLETE)
  8479. return 1; /* client can forget first client_hello if received full
  8480. * flight of packets from server */
  8481. else
  8482. return 0;
  8483. case WOLFSSL_SERVER_END:
  8484. if (ssl->options.clientState >= CLIENT_HELLO_COMPLETE &&
  8485. item->type == hello_request)
  8486. return 1; /* Server can forget HelloRequest if client sent a valid
  8487. * ClientHello */
  8488. if (ssl->options.clientState >= CLIENT_FINISHED_COMPLETE &&
  8489. item->type <= server_hello_done)
  8490. return 1; /* server can forget everything up to ServerHelloDone if
  8491. * a client finished message has been received and
  8492. * successfully processed */
  8493. else
  8494. return 0;
  8495. default:
  8496. return 0;
  8497. }
  8498. }
  8499. /* DtlsMsgPoolSend() will send the stored transmit list. The stored list is
  8500. * updated with new sequence numbers, and will be re-encrypted if needed. */
  8501. int DtlsMsgPoolSend(WOLFSSL* ssl, int sendOnlyFirstPacket)
  8502. {
  8503. int ret = 0;
  8504. DtlsMsg* pool;
  8505. WOLFSSL_ENTER("DtlsMsgPoolSend");
  8506. pool = ssl->dtls_tx_msg == NULL ? ssl->dtls_tx_msg_list : ssl->dtls_tx_msg;
  8507. if (pool != NULL) {
  8508. if ((ssl->options.side == WOLFSSL_SERVER_END &&
  8509. !(ssl->options.acceptState == ACCEPT_BEGIN_RENEG ||
  8510. ssl->options.acceptState == SERVER_HELLO_DONE ||
  8511. ssl->options.acceptState == ACCEPT_FINISHED_DONE ||
  8512. ssl->options.acceptState == ACCEPT_THIRD_REPLY_DONE)) ||
  8513. (ssl->options.side == WOLFSSL_CLIENT_END &&
  8514. !(ssl->options.connectState == CLIENT_HELLO_SENT ||
  8515. ssl->options.connectState == HELLO_AGAIN_REPLY ||
  8516. ssl->options.connectState == FINISHED_DONE ||
  8517. ssl->options.connectState == SECOND_REPLY_DONE))) {
  8518. WOLFSSL_ERROR(DTLS_RETX_OVER_TX);
  8519. ssl->error = DTLS_RETX_OVER_TX;
  8520. return WOLFSSL_FATAL_ERROR;
  8521. }
  8522. while (pool != NULL) {
  8523. int epochOrder;
  8524. if (pool->epoch == 0) {
  8525. DtlsRecordLayerHeader* dtls;
  8526. dtls = (DtlsRecordLayerHeader*)pool->raw;
  8527. /* If the stored record's epoch is 0, and the currently set
  8528. * epoch is 0, use the "current order" sequence number.
  8529. * If the stored record's epoch is 0 and the currently set
  8530. * epoch is not 0, the stored record is considered a "previous
  8531. * order" sequence number. */
  8532. epochOrder = (ssl->keys.dtls_epoch == 0) ?
  8533. CUR_ORDER : PREV_ORDER;
  8534. WriteSEQ(ssl, epochOrder, dtls->sequence_number);
  8535. DtlsSEQIncrement(ssl, epochOrder);
  8536. if ((ret = CheckAvailableSize(ssl, pool->sz)) != 0) {
  8537. WOLFSSL_ERROR(ret);
  8538. return ret;
  8539. }
  8540. XMEMCPY(GetOutputBuffer(ssl), pool->raw, pool->sz);
  8541. ssl->buffers.outputBuffer.length += pool->sz;
  8542. }
  8543. else {
  8544. /* Handle sending packets from previous epoch */
  8545. byte* input;
  8546. byte* output;
  8547. int inputSz, sendSz;
  8548. input = pool->raw;
  8549. inputSz = (int)pool->sz;
  8550. sendSz = inputSz + cipherExtraData(ssl);
  8551. #ifdef HAVE_SECURE_RENEGOTIATION
  8552. /*
  8553. * CUR_ORDER will use ssl->secure_renegotiation from epoch 2+.
  8554. * ssl->keys otherwise
  8555. * PREV_ORDER will always use ssl->keys
  8556. */
  8557. if (DtlsSCRKeysSet(ssl)) {
  8558. if (pool->epoch == ssl->secure_renegotiation->tmp_keys.dtls_epoch)
  8559. epochOrder = CUR_ORDER;
  8560. else
  8561. epochOrder = PREV_ORDER;
  8562. }
  8563. else {
  8564. epochOrder = CUR_ORDER;
  8565. }
  8566. #else
  8567. epochOrder = CUR_ORDER;
  8568. #endif
  8569. /* add back in record header space from saved pool size */
  8570. sendSz += DTLS_RECORD_HEADER_SZ;
  8571. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0) {
  8572. WOLFSSL_ERROR(ret);
  8573. return ret;
  8574. }
  8575. output = GetOutputBuffer(ssl);
  8576. if (inputSz != ENUM_LEN)
  8577. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  8578. handshake, 0, 0, 0, epochOrder);
  8579. else
  8580. /* inputSz == ENUM_LEN must mean that this is a change cipher
  8581. * spec message */
  8582. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  8583. change_cipher_spec, 0, 0, 0, epochOrder);
  8584. if (sendSz < 0) {
  8585. WOLFSSL_ERROR(BUILD_MSG_ERROR);
  8586. return BUILD_MSG_ERROR;
  8587. }
  8588. ssl->buffers.outputBuffer.length += sendSz;
  8589. }
  8590. if (!ssl->options.groupMessages)
  8591. ret = SendBuffered(ssl);
  8592. /**
  8593. * on server side, retransmission is being triggered only by sending
  8594. * first message of given flight, in order to trigger client
  8595. * to retransmit its whole flight. Sending the whole previous flight
  8596. * could lead to retransmission of previous client flight for each
  8597. * server message from previous flight. Therefore one message should
  8598. * be enough to do the trick.
  8599. */
  8600. if (sendOnlyFirstPacket &&
  8601. ssl->options.side == WOLFSSL_SERVER_END)
  8602. pool = NULL;
  8603. else
  8604. pool = pool->next;
  8605. ssl->dtls_tx_msg = pool;
  8606. }
  8607. if (ret == 0 && ssl->options.groupMessages)
  8608. ret = SendBuffered(ssl);
  8609. }
  8610. WOLFSSL_LEAVE("DtlsMsgPoolSend()", ret);
  8611. return ret;
  8612. }
  8613. #endif /* WOLFSSL_DTLS */
  8614. #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
  8615. ProtocolVersion MakeSSLv3(void)
  8616. {
  8617. ProtocolVersion pv;
  8618. pv.major = SSLv3_MAJOR;
  8619. pv.minor = SSLv3_MINOR;
  8620. return pv;
  8621. }
  8622. #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
  8623. #ifdef WOLFSSL_DTLS
  8624. ProtocolVersion MakeDTLSv1(void)
  8625. {
  8626. ProtocolVersion pv;
  8627. pv.major = DTLS_MAJOR;
  8628. pv.minor = DTLS_MINOR;
  8629. return pv;
  8630. }
  8631. #ifndef WOLFSSL_NO_TLS12
  8632. ProtocolVersion MakeDTLSv1_2(void)
  8633. {
  8634. ProtocolVersion pv;
  8635. pv.major = DTLS_MAJOR;
  8636. pv.minor = DTLSv1_2_MINOR;
  8637. return pv;
  8638. }
  8639. #endif /* !WOLFSSL_NO_TLS12 */
  8640. #ifdef WOLFSSL_DTLS13
  8641. ProtocolVersion MakeDTLSv1_3(void)
  8642. {
  8643. ProtocolVersion pv;
  8644. pv.major = DTLS_MAJOR;
  8645. pv.minor = DTLSv1_3_MINOR;
  8646. return pv;
  8647. }
  8648. #endif /* WOLFSSL_DTLS13 */
  8649. #endif /* WOLFSSL_DTLS */
  8650. #ifndef NO_ASN_TIME
  8651. #if defined(USER_TICKS)
  8652. #if 0
  8653. word32 LowResTimer(void)
  8654. {
  8655. /*
  8656. write your own clock tick function if don't want time(0)
  8657. needs second accuracy but doesn't have to correlated to EPOCH
  8658. */
  8659. }
  8660. #endif
  8661. #elif defined(TIME_OVERRIDES)
  8662. #if !defined(NO_ASN) && !defined(NO_ASN_TIME)
  8663. /* use same asn time overrides unless user wants tick override above */
  8664. word32 LowResTimer(void)
  8665. {
  8666. return (word32) wc_Time(0);
  8667. }
  8668. #else
  8669. #ifndef HAVE_TIME_T_TYPE
  8670. typedef long time_t;
  8671. #endif
  8672. extern time_t XTIME(time_t * timer);
  8673. word32 LowResTimer(void)
  8674. {
  8675. return (word32) XTIME(0);
  8676. }
  8677. #endif
  8678. #elif defined(USE_WINDOWS_API)
  8679. word32 LowResTimer(void)
  8680. {
  8681. static int init = 0;
  8682. static LARGE_INTEGER freq;
  8683. LARGE_INTEGER count;
  8684. if (!init) {
  8685. QueryPerformanceFrequency(&freq);
  8686. init = 1;
  8687. }
  8688. QueryPerformanceCounter(&count);
  8689. return (word32)(count.QuadPart / freq.QuadPart);
  8690. }
  8691. #elif defined(HAVE_RTP_SYS)
  8692. #include "rtptime.h"
  8693. word32 LowResTimer(void)
  8694. {
  8695. return (word32)rtp_get_system_sec();
  8696. }
  8697. #elif defined(WOLFSSL_DEOS)
  8698. word32 LowResTimer(void)
  8699. {
  8700. const word32 systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
  8701. const volatile word32 *systemTickPtr = systemTickPointer();
  8702. return (word32) *systemTickPtr/systemTickTimeInHz;
  8703. }
  8704. #elif defined(MICRIUM)
  8705. word32 LowResTimer(void)
  8706. {
  8707. OS_TICK ticks = 0;
  8708. OS_ERR err;
  8709. ticks = OSTimeGet(&err);
  8710. return (word32) (ticks / OSCfg_TickRate_Hz);
  8711. }
  8712. #elif defined(MICROCHIP_TCPIP_V5)
  8713. word32 LowResTimer(void)
  8714. {
  8715. return (word32) (TickGet() / TICKS_PER_SECOND);
  8716. }
  8717. #elif defined(MICROCHIP_TCPIP)
  8718. #if defined(MICROCHIP_MPLAB_HARMONY)
  8719. #include <system/tmr/sys_tmr.h>
  8720. word32 LowResTimer(void)
  8721. {
  8722. return (word32) (SYS_TMR_TickCountGet() /
  8723. SYS_TMR_TickCounterFrequencyGet());
  8724. }
  8725. #else
  8726. word32 LowResTimer(void)
  8727. {
  8728. return (word32) (SYS_TICK_Get() / SYS_TICK_TicksPerSecondGet());
  8729. }
  8730. #endif
  8731. #elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
  8732. word32 LowResTimer(void)
  8733. {
  8734. TIME_STRUCT mqxTime;
  8735. _time_get_elapsed(&mqxTime);
  8736. return (word32) mqxTime.SECONDS;
  8737. }
  8738. #elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
  8739. #include "include/task.h"
  8740. unsigned int LowResTimer(void)
  8741. {
  8742. return (unsigned int)(((float)xTaskGetTickCount())/configTICK_RATE_HZ);
  8743. }
  8744. #elif defined(FREERTOS)
  8745. #ifdef PLATFORMIO
  8746. #include <freertos/FreeRTOS.h>
  8747. #include <freertos/task.h>
  8748. #else
  8749. #include "task.h"
  8750. #endif
  8751. unsigned int LowResTimer(void)
  8752. {
  8753. return (unsigned int)(((float)xTaskGetTickCount())/configTICK_RATE_HZ);
  8754. }
  8755. #elif defined(FREESCALE_KSDK_BM)
  8756. #include "lwip/sys.h" /* lwIP */
  8757. word32 LowResTimer(void)
  8758. {
  8759. return sys_now()/1000;
  8760. }
  8761. #elif defined(WOLFSSL_CMSIS_RTOS) || defined(WOLFSSL_CMSIS_RTOSv2)
  8762. word32 LowResTimer(void)
  8763. {
  8764. return (word32)osKernelGetTickCount() / 1000;
  8765. }
  8766. #elif defined(WOLFSSL_TIRTOS)
  8767. word32 LowResTimer(void)
  8768. {
  8769. return (word32) Seconds_get();
  8770. }
  8771. #elif defined(WOLFSSL_XILINX)
  8772. #include "xrtcpsu.h"
  8773. word32 LowResTimer(void)
  8774. {
  8775. XRtcPsu_Config* con;
  8776. XRtcPsu rtc;
  8777. con = XRtcPsu_LookupConfig(XPAR_XRTCPSU_0_DEVICE_ID);
  8778. if (con != NULL) {
  8779. if (XRtcPsu_CfgInitialize(&rtc, con, con->BaseAddr)
  8780. == XST_SUCCESS) {
  8781. return (word32)XRtcPsu_GetCurrentTime(&rtc);
  8782. }
  8783. else {
  8784. WOLFSSL_MSG("Unable to initialize RTC");
  8785. }
  8786. }
  8787. return 0;
  8788. }
  8789. #elif defined(WOLFSSL_UTASKER)
  8790. word32 LowResTimer(void)
  8791. {
  8792. return (word32)(uTaskerSystemTick / TICK_RESOLUTION);
  8793. }
  8794. #elif defined(WOLFSSL_NUCLEUS_1_2)
  8795. #define NU_TICKS_PER_SECOND 100
  8796. word32 LowResTimer(void)
  8797. {
  8798. /* returns number of 10ms ticks, so 100 ticks/sec */
  8799. return NU_Retrieve_Clock() / NU_TICKS_PER_SECOND;
  8800. }
  8801. #elif defined(WOLFSSL_APACHE_MYNEWT)
  8802. #include "os/os_time.h"
  8803. word32 LowResTimer(void)
  8804. {
  8805. word32 now;
  8806. struct os_timeval tv;
  8807. os_gettimeofday(&tv, NULL);
  8808. now = (word32)tv.tv_sec;
  8809. return now;
  8810. }
  8811. #elif defined(WOLFSSL_ZEPHYR)
  8812. word32 LowResTimer(void)
  8813. {
  8814. int64_t t;
  8815. #if defined(CONFIG_ARCH_POSIX) && !defined(CONFIG_BOARD_NATIVE_POSIX)
  8816. k_cpu_idle();
  8817. #endif
  8818. t = k_uptime_get(); /* returns current uptime in milliseconds */
  8819. return (word32)(t / 1000);
  8820. }
  8821. #elif defined(WOLFSSL_LINUXKM)
  8822. word32 LowResTimer(void)
  8823. {
  8824. return (word32)time(NULL);
  8825. }
  8826. #else
  8827. /* Posix style time */
  8828. #if !defined(USER_TIME) && !defined(USE_WOLF_TM)
  8829. #include <time.h>
  8830. #endif
  8831. word32 LowResTimer(void)
  8832. {
  8833. #if !defined(NO_ASN) && !defined(NO_ASN_TIME)
  8834. return (word32)wc_Time(0);
  8835. #else
  8836. return (word32)XTIME(0);
  8837. #endif
  8838. }
  8839. #endif
  8840. #else
  8841. /* user must supply timer function to return elapsed seconds:
  8842. * word32 LowResTimer(void);
  8843. */
  8844. #endif /* !NO_ASN_TIME */
  8845. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  8846. ((defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)) || \
  8847. (defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  8848. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  8849. /* Store the message for use with CertificateVerify using EdDSA.
  8850. *
  8851. * ssl SSL/TLS object.
  8852. * data Message to store.
  8853. * sz Size of message to store.
  8854. * returns MEMORY_E if not able to reallocate, otherwise 0.
  8855. */
  8856. static int EdDSA_Update(WOLFSSL* ssl, const byte* data, int sz)
  8857. {
  8858. int ret = 0;
  8859. byte* msgs;
  8860. if (ssl->options.cacheMessages) {
  8861. msgs = (byte*)XMALLOC(ssl->hsHashes->length + sz, ssl->heap,
  8862. DYNAMIC_TYPE_HASHES);
  8863. if (msgs == NULL)
  8864. ret = MEMORY_E;
  8865. if ((ret == 0) && (ssl->hsHashes->messages != NULL)) {
  8866. XMEMCPY(msgs, ssl->hsHashes->messages, ssl->hsHashes->length);
  8867. ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length);
  8868. XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
  8869. }
  8870. if (ret == 0) {
  8871. #ifdef WOLFSSL_CHECK_MEM_ZERO
  8872. wc_MemZero_Add("Handshake messages", msgs,
  8873. ssl->hsHashes->length + sz);
  8874. #endif
  8875. ssl->hsHashes->messages = msgs;
  8876. XMEMCPY(msgs + ssl->hsHashes->length, data, sz);
  8877. ssl->hsHashes->prevLen = ssl->hsHashes->length;
  8878. ssl->hsHashes->length += sz;
  8879. }
  8880. }
  8881. return ret;
  8882. }
  8883. #endif /* (HAVE_ED25519 || HAVE_ED448) && !WOLFSSL_NO_CLIENT_AUTH */
  8884. int HashRaw(WOLFSSL* ssl, const byte* data, int sz)
  8885. {
  8886. int ret = 0;
  8887. #ifdef WOLFSSL_DEBUG_TLS
  8888. byte digest[WC_MAX_DIGEST_SIZE];
  8889. WOLFSSL_MSG("HashRaw:");
  8890. WOLFSSL_MSG("Data:");
  8891. WOLFSSL_BUFFER(data, sz);
  8892. WOLFSSL_MSG("Hashes:");
  8893. #endif
  8894. (void)data;
  8895. (void)sz;
  8896. if (ssl->hsHashes == NULL) {
  8897. return BAD_FUNC_ARG;
  8898. }
  8899. #if defined(WOLFSSL_RENESAS_TSIP_TLS)
  8900. ret = tsip_StoreMessage(ssl, data, sz);
  8901. if (ret != 0 && ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
  8902. return ret;
  8903. }
  8904. #endif /* WOLFSSL_RENESAS_TSIP_TLS */
  8905. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  8906. defined(WOLFSSL_ALLOW_TLS_SHA1))
  8907. wc_ShaUpdate(&ssl->hsHashes->hashSha, data, sz);
  8908. #endif
  8909. #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
  8910. wc_Md5Update(&ssl->hsHashes->hashMd5, data, sz);
  8911. #endif
  8912. if (IsAtLeastTLSv1_2(ssl)) {
  8913. #ifndef NO_SHA256
  8914. ret = wc_Sha256Update(&ssl->hsHashes->hashSha256, data, (word32)sz);
  8915. if (ret != 0)
  8916. return ret;
  8917. #ifdef WOLFSSL_DEBUG_TLS
  8918. WOLFSSL_MSG("Sha256");
  8919. wc_Sha256GetHash(&ssl->hsHashes->hashSha256, digest);
  8920. WOLFSSL_BUFFER(digest, WC_SHA256_DIGEST_SIZE);
  8921. #endif
  8922. #endif
  8923. #ifdef WOLFSSL_SHA384
  8924. ret = wc_Sha384Update(&ssl->hsHashes->hashSha384, data, (word32)sz);
  8925. if (ret != 0)
  8926. return ret;
  8927. #ifdef WOLFSSL_DEBUG_TLS
  8928. WOLFSSL_MSG("Sha384");
  8929. wc_Sha384GetHash(&ssl->hsHashes->hashSha384, digest);
  8930. WOLFSSL_BUFFER(digest, WC_SHA384_DIGEST_SIZE);
  8931. #endif
  8932. #endif
  8933. #ifdef WOLFSSL_SHA512
  8934. ret = wc_Sha512Update(&ssl->hsHashes->hashSha512, data, (word32)sz);
  8935. if (ret != 0)
  8936. return ret;
  8937. #ifdef WOLFSSL_DEBUG_TLS
  8938. WOLFSSL_MSG("Sha512");
  8939. wc_Sha512GetHash(&ssl->hsHashes->hashSha512, digest);
  8940. WOLFSSL_BUFFER(digest, WC_SHA512_DIGEST_SIZE);
  8941. #endif
  8942. #endif
  8943. #ifdef WOLFSSL_SM3
  8944. ret = wc_Sm3Update(&ssl->hsHashes->hashSm3, data, sz);
  8945. if (ret != 0)
  8946. return ret;
  8947. #ifdef WOLFSSL_DEBUG_TLS
  8948. WOLFSSL_MSG("SM3");
  8949. wc_Sm3GetHash(&ssl->hsHashes->hashSm3, digest);
  8950. WOLFSSL_BUFFER(digest, WC_SM3_DIGEST_SIZE);
  8951. #endif
  8952. #endif
  8953. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  8954. ((defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)) || \
  8955. (defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  8956. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  8957. ret = EdDSA_Update(ssl, data, sz);
  8958. if (ret != 0)
  8959. return ret;
  8960. #endif
  8961. }
  8962. return ret;
  8963. }
  8964. /* add output to md5 and sha handshake hashes, exclude record header */
  8965. int HashOutput(WOLFSSL* ssl, const byte* output, int sz, int ivSz)
  8966. {
  8967. const byte* adj;
  8968. if (ssl->hsHashes == NULL)
  8969. return BAD_FUNC_ARG;
  8970. adj = output + RECORD_HEADER_SZ + ivSz;
  8971. sz -= RECORD_HEADER_SZ;
  8972. #ifdef HAVE_FUZZER
  8973. if (ssl->fuzzerCb)
  8974. ssl->fuzzerCb(ssl, output, sz, FUZZ_HASH, ssl->fuzzerCtx);
  8975. #endif
  8976. #ifdef WOLFSSL_DTLS
  8977. if (ssl->options.dtls) {
  8978. if (IsAtLeastTLSv1_3(ssl->version)) {
  8979. #ifdef WOLFSSL_DTLS13
  8980. word16 dtls_record_extra;
  8981. dtls_record_extra = Dtls13GetRlHeaderLength(ssl, (byte)IsEncryptionOn(ssl, 1));
  8982. dtls_record_extra -= RECORD_HEADER_SZ;
  8983. adj += dtls_record_extra;
  8984. sz -= dtls_record_extra;
  8985. #endif /* WOLFSSL_DTLS13 */
  8986. } else {
  8987. adj += DTLS_RECORD_EXTRA;
  8988. sz -= DTLS_RECORD_EXTRA;
  8989. }
  8990. }
  8991. #endif
  8992. return HashRaw(ssl, adj, sz);
  8993. }
  8994. /* add input to md5 and sha handshake hashes, include handshake header */
  8995. int HashInput(WOLFSSL* ssl, const byte* input, int sz)
  8996. {
  8997. const byte* adj;
  8998. if (ssl->hsHashes == NULL) {
  8999. return BAD_FUNC_ARG;
  9000. }
  9001. adj = input - HANDSHAKE_HEADER_SZ;
  9002. sz += HANDSHAKE_HEADER_SZ;
  9003. #ifdef WOLFSSL_DTLS
  9004. if (ssl->options.dtls) {
  9005. adj -= DTLS_HANDSHAKE_EXTRA;
  9006. sz += DTLS_HANDSHAKE_EXTRA;
  9007. #ifdef WOLFSSL_DTLS13
  9008. if (IsAtLeastTLSv1_3(ssl->version))
  9009. return Dtls13HashHandshake(ssl, adj, (word16)sz);
  9010. #endif /* WOLFSSL_DTLS13 */
  9011. }
  9012. #endif
  9013. return HashRaw(ssl, adj, sz);
  9014. }
  9015. /* add record layer header for message */
  9016. static void AddRecordHeader(byte* output, word32 length, byte type, WOLFSSL* ssl, int epochOrder)
  9017. {
  9018. RecordLayerHeader* rl;
  9019. (void)epochOrder;
  9020. /* record layer header */
  9021. rl = (RecordLayerHeader*)output;
  9022. if (rl == NULL) {
  9023. return;
  9024. }
  9025. rl->type = type;
  9026. rl->pvMajor = ssl->version.major; /* type and version same in each */
  9027. #ifdef WOLFSSL_TLS13
  9028. if (IsAtLeastTLSv1_3(ssl->version)) {
  9029. rl->pvMinor = TLSv1_2_MINOR;
  9030. #ifdef WOLFSSL_DTLS
  9031. if (ssl->options.dtls)
  9032. rl->pvMinor = DTLSv1_2_MINOR;
  9033. #endif /* WOLFSSL_DTLS */
  9034. }
  9035. else
  9036. #endif
  9037. rl->pvMinor = ssl->version.minor;
  9038. #ifdef WOLFSSL_ALTERNATIVE_DOWNGRADE
  9039. if (ssl->options.side == WOLFSSL_CLIENT_END
  9040. && ssl->options.connectState == CONNECT_BEGIN
  9041. && !ssl->options.resuming) {
  9042. rl->pvMinor = ssl->options.downgrade ? ssl->options.minDowngrade
  9043. : ssl->version.minor;
  9044. }
  9045. #endif
  9046. if (!ssl->options.dtls) {
  9047. c16toa((word16)length, rl->length);
  9048. }
  9049. else {
  9050. #ifdef WOLFSSL_DTLS
  9051. DtlsRecordLayerHeader* dtls;
  9052. /* dtls record layer header extensions */
  9053. dtls = (DtlsRecordLayerHeader*)output;
  9054. WriteSEQ(ssl, epochOrder, dtls->sequence_number);
  9055. c16toa((word16)length, dtls->length);
  9056. #endif
  9057. }
  9058. }
  9059. #if !defined(WOLFSSL_NO_TLS12) || (defined(HAVE_SESSION_TICKET) && \
  9060. !defined(NO_WOLFSSL_SERVER))
  9061. /* add handshake header for message */
  9062. static void AddHandShakeHeader(byte* output, word32 length,
  9063. word32 fragOffset, word32 fragLength,
  9064. byte type, WOLFSSL* ssl)
  9065. {
  9066. HandShakeHeader* hs;
  9067. (void)fragOffset;
  9068. (void)fragLength;
  9069. (void)ssl;
  9070. /* handshake header */
  9071. hs = (HandShakeHeader*)output;
  9072. if (hs == NULL)
  9073. return;
  9074. hs->type = type;
  9075. c32to24(length, hs->length); /* type and length same for each */
  9076. #ifdef WOLFSSL_DTLS
  9077. if (ssl->options.dtls) {
  9078. DtlsHandShakeHeader* dtls;
  9079. /* dtls handshake header extensions */
  9080. dtls = (DtlsHandShakeHeader*)output;
  9081. c16toa(ssl->keys.dtls_handshake_number++, dtls->message_seq);
  9082. c32to24(fragOffset, dtls->fragment_offset);
  9083. c32to24(fragLength, dtls->fragment_length);
  9084. }
  9085. #endif
  9086. }
  9087. /* add both headers for handshake message */
  9088. static void AddHeaders(byte* output, word32 length, byte type, WOLFSSL* ssl)
  9089. {
  9090. word32 lengthAdj = HANDSHAKE_HEADER_SZ;
  9091. word32 outputAdj = RECORD_HEADER_SZ;
  9092. #ifdef WOLFSSL_DTLS
  9093. if (ssl->options.dtls) {
  9094. lengthAdj += DTLS_HANDSHAKE_EXTRA;
  9095. outputAdj += DTLS_RECORD_EXTRA;
  9096. }
  9097. #endif
  9098. AddRecordHeader(output, length + lengthAdj, handshake, ssl, CUR_ORDER);
  9099. AddHandShakeHeader(output + outputAdj, length, 0, length, type, ssl);
  9100. }
  9101. #endif /* !WOLFSSL_NO_TLS12 || (HAVE_SESSION_TICKET && !NO_WOLFSSL_SERVER) */
  9102. #ifndef WOLFSSL_NO_TLS12
  9103. #if !defined(NO_CERTS) && (!defined(NO_WOLFSSL_SERVER) || \
  9104. !defined(WOLFSSL_NO_CLIENT_AUTH)) || \
  9105. defined(WOLFSSL_DTLS)
  9106. static void AddFragHeaders(byte* output, word32 fragSz, word32 fragOffset,
  9107. word32 length, byte type, WOLFSSL* ssl)
  9108. {
  9109. word32 lengthAdj = HANDSHAKE_HEADER_SZ;
  9110. word32 outputAdj = RECORD_HEADER_SZ;
  9111. (void)fragSz;
  9112. #ifdef WOLFSSL_DTLS
  9113. if (ssl->options.dtls) {
  9114. lengthAdj += DTLS_HANDSHAKE_EXTRA;
  9115. outputAdj += DTLS_RECORD_EXTRA;
  9116. }
  9117. #endif
  9118. AddRecordHeader(output, fragSz + lengthAdj, handshake, ssl, CUR_ORDER);
  9119. AddHandShakeHeader(output + outputAdj, length, fragOffset, fragSz, type, ssl);
  9120. }
  9121. #endif /* NO_CERTS */
  9122. #if !defined(NO_WOLFSSL_SERVER) || \
  9123. (!defined(NO_WOLFSSL_CLIENT) && !defined(NO_CERTS) && \
  9124. !defined(WOLFSSL_NO_CLIENT_AUTH))
  9125. /**
  9126. * Send the handshake message. This function handles fragmenting the message
  9127. * so that it will fit into the desired MTU or the max fragment size.
  9128. * @param ssl Connection object
  9129. * @param input Input starting at the record layer header. This function
  9130. * assumes that the appropriate record and handshake headers
  9131. * are present. These headers must assume no fragmentation.
  9132. * That is handled here.
  9133. * @param inputSz Length of message excluding headers (this is the total
  9134. * length of all fragments)
  9135. * @param type Type of message being sent
  9136. * @return 0 on success and negative otherwise
  9137. */
  9138. static int SendHandshakeMsg(WOLFSSL* ssl, byte* input, word32 inputSz,
  9139. enum HandShakeType type, const char* packetName)
  9140. {
  9141. int maxFrag;
  9142. int ret = 0;
  9143. int headerSz;
  9144. WOLFSSL_ENTER("SendHandshakeMsg");
  9145. (void)type;
  9146. (void)packetName;
  9147. if (ssl == NULL || input == NULL)
  9148. return BAD_FUNC_ARG;
  9149. #ifdef WOLFSSL_DTLS
  9150. if (ssl->options.dtls)
  9151. headerSz = DTLS_RECORD_HEADER_SZ + DTLS_HANDSHAKE_HEADER_SZ;
  9152. else
  9153. #endif
  9154. {
  9155. /* In TLS we send one handshake header in total, not one
  9156. * per fragment like in DTLS. The handshake header should
  9157. * already be in the input buffer. */
  9158. inputSz += HANDSHAKE_HEADER_SZ;
  9159. headerSz = RECORD_HEADER_SZ;
  9160. }
  9161. maxFrag = wolfSSL_GetMaxFragSize(ssl, (int)inputSz);
  9162. /* Make sure input is not the ssl output buffer as this
  9163. * function doesn't handle that */
  9164. if (input >= ssl->buffers.outputBuffer.buffer &&
  9165. input < ssl->buffers.outputBuffer.buffer +
  9166. ssl->buffers.outputBuffer.bufferSize) {
  9167. WOLFSSL_MSG("Can't use output buffer for input in SendHandshakeMsg");
  9168. return BAD_FUNC_ARG;
  9169. }
  9170. if (!ssl->options.buildingMsg) {
  9171. /* Hash it before the loop as we modify the input with
  9172. * encryption on */
  9173. ret = HashOutput(ssl, input, headerSz + (int)inputSz, 0);
  9174. if (ret != 0)
  9175. return ret;
  9176. #ifdef WOLFSSL_DTLS
  9177. /* Decrement msg number so that we continue to use the
  9178. * same msg number for this msg */
  9179. if (ssl->options.dtls)
  9180. ssl->keys.dtls_handshake_number--;
  9181. #endif
  9182. }
  9183. while (ssl->fragOffset < inputSz) {
  9184. byte* output;
  9185. int outputSz;
  9186. byte* data = input + ssl->fragOffset + headerSz;
  9187. word32 fragSz = (word32)maxFrag;
  9188. ssl->options.buildingMsg = 1;
  9189. if (inputSz - ssl->fragOffset < fragSz)
  9190. fragSz = inputSz - ssl->fragOffset;
  9191. /* check for available size */
  9192. outputSz = headerSz + (int)fragSz;
  9193. if (IsEncryptionOn(ssl, 1))
  9194. outputSz += cipherExtraData(ssl);
  9195. if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
  9196. return ret;
  9197. if (ssl->buffers.outputBuffer.buffer == NULL)
  9198. return MEMORY_E;
  9199. output = GetOutputBuffer(ssl);
  9200. if (IsEncryptionOn(ssl, 1)) {
  9201. /* First we need to add the fragment header ourselves.
  9202. * We do this in the input to minimize allocations */
  9203. int dataSz = (int)fragSz;
  9204. #ifdef WOLFSSL_DTLS
  9205. if (ssl->options.dtls) {
  9206. data -= DTLS_HANDSHAKE_HEADER_SZ;
  9207. dataSz += DTLS_HANDSHAKE_HEADER_SZ;
  9208. AddHandShakeHeader(data, inputSz, ssl->fragOffset, fragSz,
  9209. type, ssl);
  9210. ssl->keys.dtls_handshake_number--;
  9211. }
  9212. if (IsDtlsNotSctpMode(ssl) &&
  9213. (ret = DtlsMsgPoolSave(ssl, data,
  9214. fragSz + DTLS_HANDSHAKE_HEADER_SZ, type))
  9215. != 0)
  9216. return ret;
  9217. #endif
  9218. ret = BuildMessage(ssl, output, outputSz,
  9219. data, dataSz, handshake, 0, 0, 0, CUR_ORDER);
  9220. if (ret >= 0)
  9221. outputSz = ret;
  9222. else
  9223. return ret;
  9224. ret = 0;
  9225. }
  9226. else {
  9227. #ifdef WOLFSSL_DTLS
  9228. if (ssl->options.dtls)
  9229. AddFragHeaders(output, fragSz, ssl->fragOffset,
  9230. inputSz, type, ssl);
  9231. else
  9232. #endif
  9233. AddRecordHeader(output, fragSz, handshake, ssl, CUR_ORDER);
  9234. XMEMCPY(output + headerSz, data, fragSz);
  9235. #ifdef WOLFSSL_DTLS
  9236. if (ssl->options.dtls) {
  9237. ssl->keys.dtls_handshake_number--;
  9238. DtlsSEQIncrement(ssl, CUR_ORDER);
  9239. }
  9240. if (IsDtlsNotSctpMode(ssl)) {
  9241. if ((ret = DtlsMsgPoolSave(ssl, output, headerSz + fragSz,
  9242. type)) != 0) {
  9243. return ret;
  9244. }
  9245. }
  9246. #endif
  9247. }
  9248. ssl->buffers.outputBuffer.length += (word32)outputSz;
  9249. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  9250. if (ssl->hsInfoOn) {
  9251. AddPacketName(ssl, packetName);
  9252. }
  9253. if (ssl->toInfoOn) {
  9254. ret = AddPacketInfo(ssl, packetName, handshake,
  9255. output, outputSz, WRITE_PROTO, 0, ssl->heap);
  9256. if (ret != 0)
  9257. return ret;
  9258. }
  9259. #endif
  9260. ssl->fragOffset += fragSz;
  9261. if (!ssl->options.groupMessages)
  9262. ret = SendBuffered(ssl);
  9263. if (ret != 0)
  9264. return ret;
  9265. }
  9266. #ifdef WOLFSSL_DTLS
  9267. /* Increment msg number once we sent all fragments */
  9268. if (ssl->options.dtls)
  9269. ssl->keys.dtls_handshake_number++;
  9270. #endif
  9271. ssl->fragOffset = 0;
  9272. ssl->options.buildingMsg = 0;
  9273. return ret;
  9274. }
  9275. #endif /* !NO_WOLFSSL_SERVER || (!NO_WOLFSSL_CLIENT && !NO_CERTS &&
  9276. * !WOLFSSL_NO_CLIENT_AUTH) */
  9277. #endif /* !WOLFSSL_NO_TLS12 */
  9278. /* return bytes received, -1 on error */
  9279. static int wolfSSLReceive(WOLFSSL* ssl, byte* buf, word32 sz)
  9280. {
  9281. int recvd;
  9282. int retryLimit = WOLFSSL_MODE_AUTO_RETRY_ATTEMPTS;
  9283. #ifdef WOLFSSL_QUIC
  9284. if (WOLFSSL_IS_QUIC(ssl)) {
  9285. /* QUIC only "reads" from data provided by the application
  9286. * via wolfSSL_provide_quic_data(). Transfer from there
  9287. * into the inputBuffer. */
  9288. return wolfSSL_quic_receive(ssl, buf, sz);
  9289. }
  9290. #endif
  9291. if (ssl->CBIORecv == NULL) {
  9292. WOLFSSL_MSG("Your IO Recv callback is null, please set");
  9293. return WOLFSSL_FATAL_ERROR;
  9294. }
  9295. retry:
  9296. recvd = ssl->CBIORecv(ssl, (char *)buf, (int)sz, ssl->IOCB_ReadCtx);
  9297. if (recvd < 0) {
  9298. switch (recvd) {
  9299. case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_GENERAL):
  9300. #ifdef WOLFSSL_APACHE_HTTPD
  9301. #ifndef NO_BIO
  9302. if (ssl->biord) {
  9303. /* If retry and read flags are set, return WANT_READ */
  9304. if ((ssl->biord->flags & WOLFSSL_BIO_FLAG_READ) &&
  9305. (ssl->biord->flags & WOLFSSL_BIO_FLAG_RETRY)) {
  9306. return WANT_READ;
  9307. }
  9308. }
  9309. #endif
  9310. #endif
  9311. return WOLFSSL_FATAL_ERROR;
  9312. case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ):
  9313. if (retryLimit > 0 && ssl->ctx->autoRetry &&
  9314. !ssl->options.handShakeDone && !ssl->options.dtls) {
  9315. retryLimit--;
  9316. goto retry;
  9317. }
  9318. return WC_NO_ERR_TRACE(WANT_READ);
  9319. case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_RST):
  9320. #ifdef USE_WINDOWS_API
  9321. if (ssl->options.dtls) {
  9322. goto retry;
  9323. }
  9324. #endif
  9325. ssl->options.connReset = 1;
  9326. return WOLFSSL_FATAL_ERROR;
  9327. case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_ISR): /* interrupt */
  9328. /* see if we got our timeout */
  9329. #ifdef WOLFSSL_CALLBACKS
  9330. if (ssl->toInfoOn) {
  9331. struct itimerval timeout;
  9332. getitimer(ITIMER_REAL, &timeout);
  9333. if (timeout.it_value.tv_sec == 0 &&
  9334. timeout.it_value.tv_usec == 0) {
  9335. XSTRNCPY(ssl->timeoutInfo.timeoutName,
  9336. "recv() timeout", MAX_TIMEOUT_NAME_SZ);
  9337. ssl->timeoutInfo.timeoutName[
  9338. MAX_TIMEOUT_NAME_SZ] = '\0';
  9339. WOLFSSL_MSG("Got our timeout");
  9340. return WANT_READ;
  9341. }
  9342. }
  9343. #endif
  9344. goto retry;
  9345. case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_CLOSE):
  9346. ssl->options.isClosed = 1;
  9347. return WOLFSSL_FATAL_ERROR;
  9348. case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_TIMEOUT):
  9349. #ifdef WOLFSSL_DTLS
  9350. #ifdef WOLFSSL_DTLS13
  9351. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) {
  9352. /* TODO: support WANT_WRITE here */
  9353. if (Dtls13RtxTimeout(ssl) < 0) {
  9354. WOLFSSL_MSG(
  9355. "Error trying to retransmit DTLS buffered message");
  9356. return WOLFSSL_FATAL_ERROR;
  9357. }
  9358. goto retry;
  9359. }
  9360. #endif /* WOLFSSL_DTLS13 */
  9361. if (IsDtlsNotSctpMode(ssl) &&
  9362. ssl->options.handShakeState != HANDSHAKE_DONE &&
  9363. DtlsMsgPoolTimeout(ssl) == 0 &&
  9364. DtlsMsgPoolSend(ssl, 0) == 0) {
  9365. /* retry read for DTLS during handshake only */
  9366. goto retry;
  9367. }
  9368. #endif
  9369. return WOLFSSL_FATAL_ERROR;
  9370. default:
  9371. WOLFSSL_MSG("Unexpected recv return code");
  9372. return recvd;
  9373. }
  9374. }
  9375. return recvd;
  9376. }
  9377. /* Switch dynamic output buffer back to static, buffer is assumed clear */
  9378. void ShrinkOutputBuffer(WOLFSSL* ssl)
  9379. {
  9380. WOLFSSL_MSG("Shrinking output buffer");
  9381. XFREE(ssl->buffers.outputBuffer.buffer - ssl->buffers.outputBuffer.offset,
  9382. ssl->heap, DYNAMIC_TYPE_OUT_BUFFER);
  9383. ssl->buffers.outputBuffer.buffer = ssl->buffers.outputBuffer.staticBuffer;
  9384. ssl->buffers.outputBuffer.bufferSize = STATIC_BUFFER_LEN;
  9385. ssl->buffers.outputBuffer.dynamicFlag = 0;
  9386. ssl->buffers.outputBuffer.offset = 0;
  9387. /* idx and length are assumed to be 0. */
  9388. }
  9389. /* Switch dynamic input buffer back to static, keep any remaining input */
  9390. /* forced free means cleaning up */
  9391. /* Be *CAREFUL* where this function is called. ProcessReply relies on
  9392. * inputBuffer.idx *NOT* changing inside the ProcessReply function. ProcessReply
  9393. * calls ShrinkInputBuffer itself when it is safe to do so. Don't overuse it. */
  9394. void ShrinkInputBuffer(WOLFSSL* ssl, int forcedFree)
  9395. {
  9396. int usedLength = (int)(ssl->buffers.inputBuffer.length -
  9397. ssl->buffers.inputBuffer.idx);
  9398. if (!forcedFree && (usedLength > STATIC_BUFFER_LEN ||
  9399. ssl->buffers.clearOutputBuffer.length > 0))
  9400. return;
  9401. WOLFSSL_MSG("Shrinking input buffer");
  9402. if (!forcedFree && usedLength > 0) {
  9403. XMEMCPY(ssl->buffers.inputBuffer.staticBuffer,
  9404. ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.idx,
  9405. usedLength);
  9406. }
  9407. ForceZero(ssl->buffers.inputBuffer.buffer,
  9408. ssl->buffers.inputBuffer.length);
  9409. XFREE(ssl->buffers.inputBuffer.buffer - ssl->buffers.inputBuffer.offset,
  9410. ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  9411. ssl->buffers.inputBuffer.buffer = ssl->buffers.inputBuffer.staticBuffer;
  9412. ssl->buffers.inputBuffer.bufferSize = STATIC_BUFFER_LEN;
  9413. ssl->buffers.inputBuffer.dynamicFlag = 0;
  9414. ssl->buffers.inputBuffer.offset = 0;
  9415. ssl->buffers.inputBuffer.idx = 0;
  9416. ssl->buffers.inputBuffer.length = (word32)usedLength;
  9417. }
  9418. int SendBuffered(WOLFSSL* ssl)
  9419. {
  9420. int retryLimit = WOLFSSL_MODE_AUTO_RETRY_ATTEMPTS;
  9421. if (ssl->CBIOSend == NULL && !WOLFSSL_IS_QUIC(ssl)) {
  9422. WOLFSSL_MSG("Your IO Send callback is null, please set");
  9423. return SOCKET_ERROR_E;
  9424. }
  9425. #ifdef WOLFSSL_DEBUG_TLS
  9426. if (ssl->buffers.outputBuffer.idx == 0) {
  9427. WOLFSSL_MSG("Data to send");
  9428. WOLFSSL_BUFFER(ssl->buffers.outputBuffer.buffer,
  9429. ssl->buffers.outputBuffer.length);
  9430. }
  9431. #endif
  9432. #ifdef WOLFSSL_QUIC
  9433. if (WOLFSSL_IS_QUIC(ssl)) {
  9434. return wolfSSL_quic_send(ssl);
  9435. }
  9436. #endif
  9437. while (ssl->buffers.outputBuffer.length > 0) {
  9438. int sent = 0;
  9439. retry:
  9440. sent = ssl->CBIOSend(ssl,
  9441. (char*)ssl->buffers.outputBuffer.buffer +
  9442. ssl->buffers.outputBuffer.idx,
  9443. (int)ssl->buffers.outputBuffer.length,
  9444. ssl->IOCB_WriteCtx);
  9445. if (sent < 0) {
  9446. switch (sent) {
  9447. case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_WRITE):
  9448. if (retryLimit > 0 && ssl->ctx->autoRetry &&
  9449. !ssl->options.handShakeDone && !ssl->options.dtls) {
  9450. retryLimit--;
  9451. goto retry;
  9452. }
  9453. return WC_NO_ERR_TRACE(WANT_WRITE);
  9454. case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_RST):
  9455. ssl->options.connReset = 1;
  9456. break;
  9457. case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_ISR): /* interrupt */
  9458. /* see if we got our timeout */
  9459. #ifdef WOLFSSL_CALLBACKS
  9460. if (ssl->toInfoOn) {
  9461. struct itimerval timeout;
  9462. getitimer(ITIMER_REAL, &timeout);
  9463. if (timeout.it_value.tv_sec == 0 &&
  9464. timeout.it_value.tv_usec == 0) {
  9465. XSTRNCPY(ssl->timeoutInfo.timeoutName,
  9466. "send() timeout", MAX_TIMEOUT_NAME_SZ);
  9467. ssl->timeoutInfo.timeoutName[
  9468. MAX_TIMEOUT_NAME_SZ] = '\0';
  9469. WOLFSSL_MSG("Got our timeout");
  9470. return WANT_WRITE;
  9471. }
  9472. }
  9473. #endif
  9474. continue;
  9475. case WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_CLOSE): /* epipe */
  9476. ssl->options.connReset = 1; /* treat same as reset */
  9477. break;
  9478. default:
  9479. return SOCKET_ERROR_E;
  9480. }
  9481. return SOCKET_ERROR_E;
  9482. }
  9483. if (sent > (int)ssl->buffers.outputBuffer.length) {
  9484. WOLFSSL_MSG("SendBuffered() out of bounds read");
  9485. return SEND_OOB_READ_E;
  9486. }
  9487. ssl->buffers.outputBuffer.idx += (word32)sent;
  9488. ssl->buffers.outputBuffer.length -= (word32)sent;
  9489. }
  9490. ssl->buffers.outputBuffer.idx = 0;
  9491. if (ssl->buffers.outputBuffer.dynamicFlag)
  9492. ShrinkOutputBuffer(ssl);
  9493. return 0;
  9494. }
  9495. /* returns the current location in the output buffer to start writing to */
  9496. byte* GetOutputBuffer(WOLFSSL* ssl)
  9497. {
  9498. return ssl->buffers.outputBuffer.buffer + ssl->buffers.outputBuffer.idx +
  9499. ssl->buffers.outputBuffer.length;
  9500. }
  9501. /* Grow the output buffer */
  9502. static WC_INLINE int GrowOutputBuffer(WOLFSSL* ssl, int size)
  9503. {
  9504. byte* tmp;
  9505. #if WOLFSSL_GENERAL_ALIGNMENT > 0
  9506. byte hdrSz = ssl->options.dtls ? DTLS_RECORD_HEADER_SZ :
  9507. RECORD_HEADER_SZ;
  9508. byte align = WOLFSSL_GENERAL_ALIGNMENT;
  9509. #else
  9510. const byte align = WOLFSSL_GENERAL_ALIGNMENT;
  9511. #endif
  9512. word32 newSz;
  9513. #if WOLFSSL_GENERAL_ALIGNMENT > 0
  9514. /* the encrypted data will be offset from the front of the buffer by
  9515. the header, if the user wants encrypted alignment they need
  9516. to define their alignment requirement */
  9517. while (align < hdrSz)
  9518. align *= 2;
  9519. #endif
  9520. if (! WC_SAFE_SUM_WORD32(ssl->buffers.outputBuffer.idx,
  9521. ssl->buffers.outputBuffer.length, newSz))
  9522. return BUFFER_E;
  9523. if (! WC_SAFE_SUM_WORD32(newSz, (word32)size, newSz))
  9524. return BUFFER_E;
  9525. if (! WC_SAFE_SUM_WORD32(newSz, align, newSz))
  9526. return BUFFER_E;
  9527. tmp = (byte*)XMALLOC(newSz, ssl->heap, DYNAMIC_TYPE_OUT_BUFFER);
  9528. newSz -= align;
  9529. WOLFSSL_MSG("growing output buffer");
  9530. if (tmp == NULL)
  9531. return MEMORY_E;
  9532. #if WOLFSSL_GENERAL_ALIGNMENT > 0
  9533. if (align)
  9534. tmp += align - hdrSz;
  9535. #endif
  9536. #ifdef WOLFSSL_STATIC_MEMORY
  9537. /* can be from IO memory pool which does not need copy if same buffer */
  9538. if (ssl->buffers.outputBuffer.length &&
  9539. tmp == ssl->buffers.outputBuffer.buffer) {
  9540. ssl->buffers.outputBuffer.bufferSize = newSz;
  9541. return 0;
  9542. }
  9543. #endif
  9544. if (ssl->buffers.outputBuffer.length)
  9545. XMEMCPY(tmp, ssl->buffers.outputBuffer.buffer,
  9546. ssl->buffers.outputBuffer.idx +
  9547. ssl->buffers.outputBuffer.length);
  9548. if (ssl->buffers.outputBuffer.dynamicFlag) {
  9549. XFREE(ssl->buffers.outputBuffer.buffer -
  9550. ssl->buffers.outputBuffer.offset, ssl->heap,
  9551. DYNAMIC_TYPE_OUT_BUFFER);
  9552. }
  9553. ssl->buffers.outputBuffer.dynamicFlag = 1;
  9554. #if WOLFSSL_GENERAL_ALIGNMENT > 0
  9555. if (align)
  9556. ssl->buffers.outputBuffer.offset = align - hdrSz;
  9557. else
  9558. #endif
  9559. ssl->buffers.outputBuffer.offset = 0;
  9560. ssl->buffers.outputBuffer.buffer = tmp;
  9561. ssl->buffers.outputBuffer.bufferSize = newSz;
  9562. return 0;
  9563. }
  9564. /* Grow the input buffer, should only be to read cert or big app data */
  9565. int GrowInputBuffer(WOLFSSL* ssl, int size, int usedLength)
  9566. {
  9567. byte* tmp;
  9568. #if defined(WOLFSSL_DTLS) || WOLFSSL_GENERAL_ALIGNMENT > 0
  9569. byte align = ssl->options.dtls ? WOLFSSL_GENERAL_ALIGNMENT : 0;
  9570. byte hdrSz = DTLS_RECORD_HEADER_SZ;
  9571. #else
  9572. const byte align = WOLFSSL_GENERAL_ALIGNMENT;
  9573. #endif
  9574. #if defined(WOLFSSL_DTLS) || WOLFSSL_GENERAL_ALIGNMENT > 0
  9575. /* the encrypted data will be offset from the front of the buffer by
  9576. the dtls record header, if the user wants encrypted alignment they need
  9577. to define their alignment requirement. in tls we read record header
  9578. to get size of record and put actual data back at front, so don't need */
  9579. if (align) {
  9580. while (align < hdrSz)
  9581. align *= 2;
  9582. }
  9583. #endif
  9584. if (usedLength < 0 || size < 0) {
  9585. WOLFSSL_MSG("GrowInputBuffer() called with negative number");
  9586. return BAD_FUNC_ARG;
  9587. }
  9588. tmp = (byte*)XMALLOC((size_t)(size + usedLength + align),
  9589. ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  9590. WOLFSSL_MSG("growing input buffer");
  9591. if (tmp == NULL)
  9592. return MEMORY_E;
  9593. #if defined(WOLFSSL_DTLS) || WOLFSSL_GENERAL_ALIGNMENT > 0
  9594. if (align)
  9595. tmp += align - hdrSz;
  9596. #endif
  9597. #ifdef WOLFSSL_STATIC_MEMORY
  9598. /* can be from IO memory pool which does not need copy if same buffer */
  9599. if (usedLength && tmp == ssl->buffers.inputBuffer.buffer) {
  9600. ssl->buffers.inputBuffer.bufferSize = size + usedLength;
  9601. ssl->buffers.inputBuffer.idx = 0;
  9602. ssl->buffers.inputBuffer.length = usedLength;
  9603. return 0;
  9604. }
  9605. #endif
  9606. if (usedLength)
  9607. XMEMCPY(tmp, ssl->buffers.inputBuffer.buffer +
  9608. ssl->buffers.inputBuffer.idx, usedLength);
  9609. if (ssl->buffers.inputBuffer.dynamicFlag) {
  9610. if (IsEncryptionOn(ssl, 1)) {
  9611. ForceZero(ssl->buffers.inputBuffer.buffer,
  9612. ssl->buffers.inputBuffer.length);
  9613. }
  9614. XFREE(ssl->buffers.inputBuffer.buffer - ssl->buffers.inputBuffer.offset,
  9615. ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  9616. }
  9617. ssl->buffers.inputBuffer.dynamicFlag = 1;
  9618. #if defined(WOLFSSL_DTLS) || WOLFSSL_GENERAL_ALIGNMENT > 0
  9619. if (align)
  9620. ssl->buffers.inputBuffer.offset = align - hdrSz;
  9621. else
  9622. #endif
  9623. ssl->buffers.inputBuffer.offset = 0;
  9624. ssl->buffers.inputBuffer.buffer = tmp;
  9625. ssl->buffers.inputBuffer.bufferSize = (word32)(size + usedLength);
  9626. ssl->buffers.inputBuffer.idx = 0;
  9627. ssl->buffers.inputBuffer.length = (word32)usedLength;
  9628. return 0;
  9629. }
  9630. /* Check available size into output buffer, make room if needed.
  9631. * This function needs to be called before anything gets put
  9632. * into the output buffers since it flushes pending data if it
  9633. * predicts that the msg will exceed MTU. */
  9634. int CheckAvailableSize(WOLFSSL *ssl, int size)
  9635. {
  9636. if (size < 0) {
  9637. WOLFSSL_MSG("CheckAvailableSize() called with negative number");
  9638. return BAD_FUNC_ARG;
  9639. }
  9640. #ifdef WOLFSSL_DTLS
  9641. if (ssl->options.dtls) {
  9642. #if defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)
  9643. word32 mtu = (word32)ssl->dtlsMtuSz;
  9644. #else
  9645. word32 mtu = MAX_MTU;
  9646. #endif
  9647. if ((word32)size + ssl->buffers.outputBuffer.length > mtu) {
  9648. int ret;
  9649. WOLFSSL_MSG("CheckAvailableSize() flushing buffer "
  9650. "to make room for new message");
  9651. if ((ret = SendBuffered(ssl)) != 0) {
  9652. return ret;
  9653. }
  9654. }
  9655. if ((word32)size > mtu
  9656. #ifdef WOLFSSL_DTLS13
  9657. /* DTLS1.3 uses the output buffer to store the full message and deal
  9658. with fragmentation later in dtls13HandshakeSend() */
  9659. && !IsAtLeastTLSv1_3(ssl->version)
  9660. #endif /* WOLFSSL_DTLS13 */
  9661. ) {
  9662. WOLFSSL_MSG("CheckAvailableSize() called with size greater than MTU.");
  9663. return DTLS_SIZE_ERROR;
  9664. }
  9665. }
  9666. #endif
  9667. if ((ssl->buffers.outputBuffer.bufferSize -
  9668. ssl->buffers.outputBuffer.length -
  9669. ssl->buffers.outputBuffer.idx) < (word32)size) {
  9670. if (GrowOutputBuffer(ssl, size) < 0)
  9671. return MEMORY_E;
  9672. }
  9673. return 0;
  9674. }
  9675. #ifndef WOLFSSL_DISABLE_EARLY_SANITY_CHECKS
  9676. int MsgCheckEncryption(WOLFSSL* ssl, byte type, byte encrypted)
  9677. {
  9678. #ifdef WOLFSSL_QUIC
  9679. /* QUIC protects messages outside of the TLS scope */
  9680. if (WOLFSSL_IS_QUIC(ssl) && IsAtLeastTLSv1_3(ssl->version))
  9681. return 0;
  9682. #endif
  9683. /* Verify which messages always have to be encrypted */
  9684. if (IsAtLeastTLSv1_3(ssl->version)) {
  9685. switch ((enum HandShakeType)type) {
  9686. case client_hello:
  9687. case server_hello:
  9688. case hello_verify_request:
  9689. case hello_retry_request:
  9690. case change_cipher_hs:
  9691. if (encrypted) {
  9692. WOLFSSL_MSG("Message can not be encrypted");
  9693. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  9694. return OUT_OF_ORDER_E;
  9695. }
  9696. break;
  9697. case hello_request:
  9698. case session_ticket:
  9699. case end_of_early_data:
  9700. case encrypted_extensions:
  9701. case certificate:
  9702. case server_key_exchange:
  9703. case certificate_request:
  9704. case server_hello_done:
  9705. case certificate_verify:
  9706. case client_key_exchange:
  9707. case finished:
  9708. case certificate_status:
  9709. case key_update:
  9710. if (!encrypted) {
  9711. WOLFSSL_MSG("Message always has to be encrypted");
  9712. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  9713. return OUT_OF_ORDER_E;
  9714. }
  9715. break;
  9716. case message_hash:
  9717. case no_shake:
  9718. default:
  9719. WOLFSSL_MSG("Unknown message type");
  9720. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9721. return SANITY_MSG_E;
  9722. }
  9723. }
  9724. else {
  9725. switch ((enum HandShakeType)type) {
  9726. case client_hello:
  9727. if ((IsSCR(ssl) || ssl->options.handShakeDone) && !encrypted) {
  9728. WOLFSSL_MSG("Message has to be encrypted for SCR");
  9729. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  9730. return OUT_OF_ORDER_E;
  9731. }
  9732. break;
  9733. case server_hello:
  9734. case hello_verify_request:
  9735. case hello_retry_request:
  9736. case certificate:
  9737. case server_key_exchange:
  9738. case certificate_request:
  9739. case server_hello_done:
  9740. case certificate_verify:
  9741. case client_key_exchange:
  9742. case certificate_status:
  9743. case session_ticket:
  9744. case change_cipher_hs:
  9745. if (IsSCR(ssl)) {
  9746. if (!encrypted) {
  9747. WOLFSSL_MSG("Message has to be encrypted during SCR");
  9748. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  9749. return OUT_OF_ORDER_E;
  9750. }
  9751. }
  9752. else if (encrypted) {
  9753. WOLFSSL_MSG("Message can not be encrypted in regular "
  9754. "handshake");
  9755. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  9756. return OUT_OF_ORDER_E;
  9757. }
  9758. break;
  9759. case hello_request:
  9760. case finished:
  9761. if (!encrypted) {
  9762. WOLFSSL_MSG("Message always has to be encrypted");
  9763. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  9764. return OUT_OF_ORDER_E;
  9765. }
  9766. break;
  9767. case key_update:
  9768. case encrypted_extensions:
  9769. case end_of_early_data:
  9770. case message_hash:
  9771. case no_shake:
  9772. default:
  9773. WOLFSSL_MSG("Unknown message type");
  9774. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9775. return SANITY_MSG_E;
  9776. }
  9777. }
  9778. return 0;
  9779. }
  9780. static WC_INLINE int isLastMsg(const WOLFSSL* ssl, word32 msgSz)
  9781. {
  9782. word32 extra = 0;
  9783. if (IsEncryptionOn(ssl, 0)) {
  9784. extra = ssl->keys.padSz;
  9785. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  9786. if (ssl->options.startedETMRead)
  9787. extra += MacSize(ssl);
  9788. #endif
  9789. }
  9790. return (ssl->buffers.inputBuffer.idx - ssl->curStartIdx) + msgSz + extra
  9791. == ssl->curSize;
  9792. }
  9793. /* Check if the msg is the last msg in a record. This is also an easy way
  9794. * to check that a record doesn't span different key boundaries. */
  9795. static int MsgCheckBoundary(const WOLFSSL* ssl, byte type,
  9796. byte version_negotiated, word32 msgSz)
  9797. {
  9798. if (version_negotiated) {
  9799. if (IsAtLeastTLSv1_3(ssl->version)) {
  9800. switch ((enum HandShakeType)type) {
  9801. case hello_request:
  9802. case client_hello:
  9803. case server_hello:
  9804. case hello_verify_request:
  9805. case hello_retry_request:
  9806. case finished:
  9807. case end_of_early_data:
  9808. if (!isLastMsg(ssl, msgSz)) {
  9809. WOLFSSL_MSG("Message type is not last in record");
  9810. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  9811. return OUT_OF_ORDER_E;
  9812. }
  9813. break;
  9814. case session_ticket:
  9815. case encrypted_extensions:
  9816. case certificate:
  9817. case server_key_exchange:
  9818. case certificate_request:
  9819. case certificate_verify:
  9820. case client_key_exchange:
  9821. case certificate_status:
  9822. case key_update:
  9823. case change_cipher_hs:
  9824. break;
  9825. case server_hello_done:
  9826. case message_hash:
  9827. case no_shake:
  9828. default:
  9829. WOLFSSL_MSG("Unknown message type");
  9830. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9831. return SANITY_MSG_E;
  9832. }
  9833. }
  9834. else {
  9835. switch ((enum HandShakeType)type) {
  9836. case hello_request:
  9837. case client_hello:
  9838. case hello_verify_request:
  9839. if (!isLastMsg(ssl, msgSz)) {
  9840. WOLFSSL_MSG("Message type is not last in record");
  9841. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  9842. return OUT_OF_ORDER_E;
  9843. }
  9844. break;
  9845. case server_hello:
  9846. case session_ticket:
  9847. case end_of_early_data:
  9848. case certificate:
  9849. case server_key_exchange:
  9850. case certificate_request:
  9851. case server_hello_done:
  9852. case certificate_verify:
  9853. case client_key_exchange:
  9854. case finished:
  9855. case certificate_status:
  9856. case change_cipher_hs:
  9857. break;
  9858. case hello_retry_request:
  9859. case encrypted_extensions:
  9860. case key_update:
  9861. case message_hash:
  9862. case no_shake:
  9863. default:
  9864. WOLFSSL_MSG("Unknown message type");
  9865. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9866. return SANITY_MSG_E;
  9867. }
  9868. }
  9869. }
  9870. else {
  9871. switch ((enum HandShakeType)type) {
  9872. case hello_request:
  9873. case client_hello:
  9874. case hello_verify_request:
  9875. if (!isLastMsg(ssl, msgSz)) {
  9876. WOLFSSL_MSG("Message type is not last in record");
  9877. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  9878. return OUT_OF_ORDER_E;
  9879. }
  9880. break;
  9881. case server_hello:
  9882. case session_ticket:
  9883. case end_of_early_data:
  9884. case hello_retry_request:
  9885. case encrypted_extensions:
  9886. case certificate:
  9887. case server_key_exchange:
  9888. case certificate_request:
  9889. case server_hello_done:
  9890. case certificate_verify:
  9891. case client_key_exchange:
  9892. case finished:
  9893. case certificate_status:
  9894. case key_update:
  9895. case change_cipher_hs:
  9896. break;
  9897. case message_hash:
  9898. case no_shake:
  9899. default:
  9900. WOLFSSL_MSG("Unknown message type");
  9901. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  9902. return SANITY_MSG_E;
  9903. }
  9904. }
  9905. return 0;
  9906. }
  9907. #endif /* WOLFSSL_DISABLE_EARLY_SANITY_CHECKS */
  9908. /**
  9909. * This check is performed as soon as the handshake message type becomes known.
  9910. * These checks can not be delayed and need to be performed when the msg is
  9911. * received and not when it is processed (fragmentation may cause messages to
  9912. * be processed at a later time). This function CAN NOT be called on stored
  9913. * messages as it relies on the state of the WOLFSSL object right after
  9914. * receiving the message.
  9915. *
  9916. * @param ssl The current connection
  9917. * @param type The enum HandShakeType of the current message
  9918. * @param msgSz Size of the current message
  9919. * @return int (less than 0 on fail, 0 on success)
  9920. */
  9921. int EarlySanityCheckMsgReceived(WOLFSSL* ssl, byte type, word32 msgSz)
  9922. {
  9923. int ret = 0;
  9924. #ifndef WOLFSSL_DISABLE_EARLY_SANITY_CHECKS
  9925. /* Version has only been negotiated after we either send or process a
  9926. * ServerHello message */
  9927. byte version_negotiated = ssl->options.serverState >= SERVER_HELLO_COMPLETE;
  9928. WOLFSSL_ENTER("EarlySanityCheckMsgReceived");
  9929. if (version_negotiated)
  9930. ret = MsgCheckEncryption(ssl, type, ssl->keys.decryptedCur == 1);
  9931. if (ret == 0)
  9932. ret = MsgCheckBoundary(ssl, type, version_negotiated, msgSz);
  9933. if (ret != 0
  9934. #ifdef WOLFSSL_DTLS
  9935. && ssl->options.dtls && ssl->options.dtlsStateful
  9936. #endif
  9937. )
  9938. SendAlert(ssl, alert_fatal, unexpected_message);
  9939. WOLFSSL_LEAVE("EarlySanityCheckMsgReceived", ret);
  9940. #else
  9941. (void)ssl;
  9942. (void)type;
  9943. (void)msgSz;
  9944. #endif
  9945. return ret;
  9946. }
  9947. #ifdef WOLFSSL_DTLS13
  9948. static int GetInputData(WOLFSSL *ssl, word32 size);
  9949. static int GetDtls13RecordHeader(WOLFSSL* ssl, word32* inOutIdx,
  9950. RecordLayerHeader* rh, word16* size)
  9951. {
  9952. Dtls13UnifiedHdrInfo hdrInfo;
  9953. w64wrapper epochNumber;
  9954. byte epochBits;
  9955. int readSize;
  9956. int ret;
  9957. readSize = ssl->buffers.inputBuffer.length - *inOutIdx;
  9958. if (readSize < DTLS_UNIFIED_HEADER_MIN_SZ)
  9959. return BUFFER_ERROR;
  9960. epochBits = *(ssl->buffers.inputBuffer.buffer + *inOutIdx) & EE_MASK;
  9961. ret = Dtls13ReconstructEpochNumber(ssl, epochBits, &epochNumber);
  9962. if (ret != 0)
  9963. return ret;
  9964. #ifdef WOLFSSL_DEBUG_TLS
  9965. WOLFSSL_MSG_EX("reconstructed epoch number: %ld",
  9966. epochNumber);
  9967. #endif /* WOLFSSL_DEBUG_TLS */
  9968. /* protected records always use unified_headers in DTLSv1.3 */
  9969. if (w64IsZero(epochNumber))
  9970. return SEQUENCE_ERROR;
  9971. if (ssl->dtls13DecryptEpoch == NULL)
  9972. return BAD_STATE_E;
  9973. #ifdef WOLFSSL_EARLY_DATA
  9974. if (w64Equal(epochNumber, w64From32(0x0, DTLS13_EPOCH_EARLYDATA)) &&
  9975. ssl->options.handShakeDone) {
  9976. WOLFSSL_MSG("discarding early data after handshake");
  9977. return SEQUENCE_ERROR;
  9978. }
  9979. #endif /* WOLFSSL_DTLS13 */
  9980. if (!w64Equal(ssl->dtls13DecryptEpoch->epochNumber, epochNumber)) {
  9981. ret = Dtls13SetEpochKeys(ssl, epochNumber, DECRYPT_SIDE_ONLY);
  9982. if (ret != 0)
  9983. return SEQUENCE_ERROR;
  9984. }
  9985. ret = Dtls13GetUnifiedHeaderSize(ssl,
  9986. *(ssl->buffers.inputBuffer.buffer+*inOutIdx), &ssl->dtls13CurRlLength);
  9987. if (ret != 0)
  9988. return ret;
  9989. if (readSize < ssl->dtls13CurRlLength + DTLS13_RN_MASK_SIZE) {
  9990. /* when using DTLS over a medium that does not guarantee that a full
  9991. * message is received in a single read, we may end up without the full
  9992. * header and minimum ciphertext to decrypt record sequence numbers */
  9993. ret = GetInputData(ssl, ssl->dtls13CurRlLength + DTLS13_RN_MASK_SIZE);
  9994. if (ret != 0)
  9995. return ret;
  9996. readSize = ssl->buffers.inputBuffer.length - *inOutIdx;
  9997. }
  9998. ret = Dtls13ParseUnifiedRecordLayer(ssl,
  9999. ssl->buffers.inputBuffer.buffer + *inOutIdx, (word16)readSize,
  10000. &hdrInfo);
  10001. if (ret != 0)
  10002. return ret;
  10003. *size = hdrInfo.recordLength;
  10004. c16toa(*size, rh->length);
  10005. /* type is implicit */
  10006. rh->type = application_data;
  10007. /* version is implicit */
  10008. rh->pvMajor = ssl->version.major;
  10009. rh->pvMinor = DTLSv1_2_MINOR;
  10010. ssl->keys.curEpoch64 = epochNumber;
  10011. ret = Dtls13ReconstructSeqNumber(ssl, &hdrInfo, &ssl->keys.curSeq);
  10012. if (ret != 0)
  10013. return ret;
  10014. #ifdef WOLFSSL_DEBUG_TLS
  10015. WOLFSSL_MSG_EX("reconstructed seq number: %ld",
  10016. ssl->keys.curSeq);
  10017. #endif /* WOLFSSL_DEBUG_TLS */
  10018. XMEMCPY(ssl->dtls13CurRL, ssl->buffers.inputBuffer.buffer + *inOutIdx,
  10019. ssl->dtls13CurRlLength);
  10020. *inOutIdx += ssl->dtls13CurRlLength;
  10021. return 0;
  10022. }
  10023. #endif /* WOLFSSL_DTLS13 */
  10024. #ifdef WOLFSSL_DTLS
  10025. static int GetDtlsRecordHeader(WOLFSSL* ssl, word32* inOutIdx,
  10026. RecordLayerHeader* rh, word16* size)
  10027. {
  10028. #ifdef HAVE_FUZZER
  10029. if (ssl->fuzzerCb)
  10030. ssl->fuzzerCb(ssl, ssl->buffers.inputBuffer.buffer + *inOutIdx,
  10031. DTLS_RECORD_HEADER_SZ, FUZZ_HEAD, ssl->fuzzerCtx);
  10032. #endif
  10033. #ifdef WOLFSSL_DTLS13
  10034. int ret;
  10035. if (Dtls13IsUnifiedHeader(*(ssl->buffers.inputBuffer.buffer + *inOutIdx))) {
  10036. ssl->options.seenUnifiedHdr = 1; /* We can send ACKs to the peer */
  10037. /* version 1.3 already negotiated */
  10038. if (ssl->options.tls1_3) {
  10039. ret = GetDtls13RecordHeader(ssl, inOutIdx, rh, size);
  10040. if (ret == 0 ||
  10041. ret != WC_NO_ERR_TRACE(SEQUENCE_ERROR) ||
  10042. ret != WC_NO_ERR_TRACE(DTLS_CID_ERROR))
  10043. return ret;
  10044. }
  10045. #ifndef NO_WOLFSSL_CLIENT
  10046. if (ssl->options.side == WOLFSSL_CLIENT_END
  10047. && ssl->options.serverState < SERVER_HELLO_COMPLETE
  10048. && IsAtLeastTLSv1_3(ssl->version)
  10049. && !ssl->options.handShakeDone) {
  10050. /* we may have lost ServerHello. Try to send a empty ACK to shortcut
  10051. Server retransmission timer */
  10052. ssl->dtls13Rtx.sendAcks = 1;
  10053. }
  10054. #endif
  10055. return SEQUENCE_ERROR;
  10056. }
  10057. /* not a unified header, check that we have at least
  10058. * DTLS_RECORD_HEADER_SZ */
  10059. if (ssl->buffers.inputBuffer.length - *inOutIdx < DTLS_RECORD_HEADER_SZ) {
  10060. ret = GetInputData(ssl, DTLS_RECORD_HEADER_SZ);
  10061. /* Check if Dtls13RtxTimeout(ssl) returned socket error */
  10062. if (ret == WC_NO_ERR_TRACE(SOCKET_ERROR_E))
  10063. return ret;
  10064. if (ret != 0)
  10065. return LENGTH_ERROR;
  10066. }
  10067. #endif /* WOLFSSL_DTLS13 */
  10068. /* type and version in same spot */
  10069. XMEMCPY(rh, ssl->buffers.inputBuffer.buffer + *inOutIdx,
  10070. ENUM_LEN + VERSION_SZ);
  10071. *inOutIdx += ENUM_LEN + VERSION_SZ;
  10072. ato16(ssl->buffers.inputBuffer.buffer + *inOutIdx, &ssl->keys.curEpoch);
  10073. #ifdef WOLFSSL_DTLS13
  10074. /* only non protected message can use the DTLSPlaintext record header */
  10075. if (IsAtLeastTLSv1_3(ssl->version)) {
  10076. if (ssl->keys.curEpoch != 0)
  10077. return SEQUENCE_ERROR;
  10078. w64Zero(&ssl->keys.curEpoch64);
  10079. if (!w64IsZero(ssl->dtls13DecryptEpoch->epochNumber))
  10080. Dtls13SetEpochKeys(ssl, ssl->keys.curEpoch64, DECRYPT_SIDE_ONLY);
  10081. }
  10082. #endif /* WOLFSSL_DTLS13 */
  10083. *inOutIdx += OPAQUE16_LEN;
  10084. if (ssl->options.haveMcast) {
  10085. #ifdef WOLFSSL_MULTICAST
  10086. ssl->keys.curPeerId = ssl->buffers.inputBuffer.buffer[*inOutIdx];
  10087. ssl->keys.curSeq_hi = ssl->buffers.inputBuffer.buffer[*inOutIdx+1];
  10088. #endif
  10089. }
  10090. else
  10091. ato16(ssl->buffers.inputBuffer.buffer + *inOutIdx, &ssl->keys.curSeq_hi);
  10092. *inOutIdx += OPAQUE16_LEN;
  10093. ato32(ssl->buffers.inputBuffer.buffer + *inOutIdx, &ssl->keys.curSeq_lo);
  10094. *inOutIdx += OPAQUE32_LEN; /* advance past rest of seq */
  10095. #ifdef WOLFSSL_DTLS13
  10096. /* DTLSv1.3 PlainText records use DTLSv1.2 sequence number encoding. Update
  10097. the DTLv1.3 word64 version as well */
  10098. ssl->keys.curSeq = w64From32(ssl->keys.curSeq_hi, ssl->keys.curSeq_lo);
  10099. #endif /* WOLFSSL_DTLS13 */
  10100. ato16(ssl->buffers.inputBuffer.buffer + *inOutIdx, size);
  10101. *inOutIdx += LENGTH_SZ;
  10102. return 0;
  10103. }
  10104. #endif /* WOLFSSL_DTLS */
  10105. /* do all verify and sanity checks on record header */
  10106. static int GetRecordHeader(WOLFSSL* ssl, word32* inOutIdx,
  10107. RecordLayerHeader* rh, word16 *size)
  10108. {
  10109. byte tls12minor = 0;
  10110. #ifdef OPENSSL_ALL
  10111. word32 start = *inOutIdx;
  10112. #endif
  10113. (void)tls12minor;
  10114. if (!ssl->options.dtls) {
  10115. #ifdef HAVE_FUZZER
  10116. if (ssl->fuzzerCb)
  10117. ssl->fuzzerCb(ssl, ssl->buffers.inputBuffer.buffer + *inOutIdx,
  10118. RECORD_HEADER_SZ, FUZZ_HEAD, ssl->fuzzerCtx);
  10119. #endif
  10120. /* Set explicitly rather than make assumptions on struct layout */
  10121. rh->type = ssl->buffers.inputBuffer.buffer[*inOutIdx];
  10122. rh->pvMajor = ssl->buffers.inputBuffer.buffer[*inOutIdx + 1];
  10123. rh->pvMinor = ssl->buffers.inputBuffer.buffer[*inOutIdx + 2];
  10124. rh->length[0] = ssl->buffers.inputBuffer.buffer[*inOutIdx + 3];
  10125. rh->length[1] = ssl->buffers.inputBuffer.buffer[*inOutIdx + 4];
  10126. *inOutIdx += RECORD_HEADER_SZ;
  10127. ato16(rh->length, size);
  10128. }
  10129. else {
  10130. #ifdef WOLFSSL_DTLS
  10131. int ret = GetDtlsRecordHeader(ssl, inOutIdx, rh, size);
  10132. if (ret != 0)
  10133. return ret;
  10134. #endif
  10135. }
  10136. #ifdef WOLFSSL_DTLS
  10137. /* DTLSv1.3 MUST check window after deprotecting to avoid timing channel
  10138. (RFC9147 Section 4.5.1) */
  10139. if (IsDtlsNotSctpMode(ssl) && !IsAtLeastTLSv1_3(ssl->version)) {
  10140. if (!_DtlsCheckWindow(ssl) ||
  10141. (rh->type == application_data && ssl->keys.curEpoch == 0) ||
  10142. (rh->type == alert && ssl->options.handShakeDone &&
  10143. ssl->keys.curEpoch == 0 && ssl->keys.dtls_epoch != 0)) {
  10144. WOLFSSL_LEAVE("GetRecordHeader()", SEQUENCE_ERROR);
  10145. return SEQUENCE_ERROR;
  10146. }
  10147. }
  10148. #endif
  10149. #if defined(WOLFSSL_DTLS13) || defined(WOLFSSL_TLS13)
  10150. tls12minor = TLSv1_2_MINOR;
  10151. #endif
  10152. #ifdef WOLFSSL_DTLS13
  10153. if (ssl->options.dtls)
  10154. tls12minor = DTLSv1_2_MINOR;
  10155. #endif /* WOLFSSL_DTLS13 */
  10156. /* catch version mismatch */
  10157. #ifndef WOLFSSL_TLS13
  10158. if (rh->pvMajor != ssl->version.major || rh->pvMinor != ssl->version.minor)
  10159. #else
  10160. if (rh->pvMajor != ssl->version.major ||
  10161. (rh->pvMinor != ssl->version.minor &&
  10162. (!IsAtLeastTLSv1_3(ssl->version) || rh->pvMinor != tls12minor)
  10163. ))
  10164. #endif
  10165. {
  10166. if (ssl->options.side == WOLFSSL_SERVER_END &&
  10167. ssl->options.acceptState < ACCEPT_FIRST_REPLY_DONE)
  10168. WOLFSSL_MSG("Client attempting to connect with different version");
  10169. else if (ssl->options.side == WOLFSSL_CLIENT_END &&
  10170. ssl->options.downgrade &&
  10171. ssl->options.connectState < FIRST_REPLY_DONE)
  10172. WOLFSSL_MSG("Server attempting to accept with different version");
  10173. else if (ssl->options.dtls && rh->type == handshake)
  10174. /* Check the DTLS handshake message RH version later. */
  10175. WOLFSSL_MSG("DTLS handshake, skip RH version number check");
  10176. #ifdef WOLFSSL_DTLS13
  10177. else if (ssl->options.dtls && !ssl->options.handShakeDone) {
  10178. /* we may have lost the ServerHello and this is a unified record
  10179. before version been negotiated */
  10180. if (Dtls13IsUnifiedHeader(*ssl->buffers.inputBuffer.buffer)) {
  10181. return SEQUENCE_ERROR;
  10182. }
  10183. }
  10184. #endif /* WOLFSSL_DTLS13 */
  10185. /* Don't care about protocol version being lower than expected on alerts
  10186. * sent back before version negotiation. */
  10187. else if (!(ssl->options.side == WOLFSSL_CLIENT_END &&
  10188. ssl->options.connectState == CLIENT_HELLO_SENT &&
  10189. rh->type == alert &&
  10190. rh->pvMajor == ssl->version.major &&
  10191. #ifdef WOLFSSL_DTLS
  10192. ((ssl->options.dtls && rh->pvMinor == DTLS_MINOR) ||
  10193. (!ssl->options.dtls &&
  10194. rh->pvMinor < ssl->version.minor))
  10195. #else
  10196. rh->pvMinor < ssl->version.minor
  10197. #endif
  10198. )) {
  10199. WOLFSSL_MSG("SSL version error");
  10200. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  10201. return VERSION_ERROR; /* only use requested version */
  10202. }
  10203. }
  10204. /* record layer length check */
  10205. #ifdef HAVE_MAX_FRAGMENT
  10206. if (*size > (ssl->max_fragment + MAX_COMP_EXTRA + MAX_MSG_EXTRA)) {
  10207. WOLFSSL_ERROR_VERBOSE(LENGTH_ERROR);
  10208. return LENGTH_ERROR;
  10209. }
  10210. #else
  10211. if (*size > (MAX_RECORD_SIZE + MAX_COMP_EXTRA + MAX_MSG_EXTRA)) {
  10212. WOLFSSL_ERROR_VERBOSE(LENGTH_ERROR);
  10213. return LENGTH_ERROR;
  10214. }
  10215. #endif
  10216. if (*size == 0 && rh->type != application_data) {
  10217. WOLFSSL_MSG("0 length, non-app data record.");
  10218. WOLFSSL_ERROR_VERBOSE(LENGTH_ERROR);
  10219. return LENGTH_ERROR;
  10220. }
  10221. /* verify record type here as well */
  10222. switch (rh->type) {
  10223. case handshake:
  10224. case change_cipher_spec:
  10225. case application_data:
  10226. case alert:
  10227. #ifdef WOLFSSL_DTLS13
  10228. case ack:
  10229. #endif /* WOLFSSL_DTLS13 */
  10230. break;
  10231. case no_type:
  10232. default:
  10233. #ifdef OPENSSL_ALL
  10234. if (!ssl->options.dtls) {
  10235. char *method = (char*)ssl->buffers.inputBuffer.buffer + start;
  10236. /* Attempt to identify if this is a plain HTTP request.
  10237. * No size checks because this function assumes at least
  10238. * RECORD_HEADER_SZ size of data has been read which is
  10239. * also the longest string comparison in this if. */
  10240. if (XSTRNCMP(method, "GET ", XSTR_SIZEOF("GET ")) == 0 ||
  10241. XSTRNCMP(method, "POST ", XSTR_SIZEOF("POST ")) == 0 ||
  10242. XSTRNCMP(method, "HEAD ", XSTR_SIZEOF("HEAD ")) == 0 ||
  10243. XSTRNCMP(method, "PUT ", XSTR_SIZEOF("PUT ")) == 0) {
  10244. WOLFSSL_MSG("Plain HTTP request detected");
  10245. return SSL_R_HTTP_REQUEST;
  10246. }
  10247. }
  10248. #endif
  10249. WOLFSSL_MSG("Unknown Record Type");
  10250. WOLFSSL_ERROR_VERBOSE(UNKNOWN_RECORD_TYPE);
  10251. return UNKNOWN_RECORD_TYPE;
  10252. }
  10253. /* haven't decrypted this record yet */
  10254. ssl->keys.decryptedCur = 0;
  10255. return 0;
  10256. }
  10257. #ifndef WOLFSSL_NO_TLS12
  10258. static int GetHandShakeHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  10259. byte *type, word32 *size, word32 totalSz)
  10260. {
  10261. const byte *ptr = input + *inOutIdx;
  10262. (void)ssl;
  10263. *inOutIdx += HANDSHAKE_HEADER_SZ;
  10264. if (*inOutIdx > totalSz)
  10265. return BUFFER_E;
  10266. *type = ptr[0];
  10267. c24to32(&ptr[1], size);
  10268. return 0;
  10269. }
  10270. #endif
  10271. #ifdef WOLFSSL_DTLS
  10272. int GetDtlsHandShakeHeader(WOLFSSL* ssl, const byte* input,
  10273. word32* inOutIdx, byte *type, word32 *size,
  10274. word32 *fragOffset, word32 *fragSz,
  10275. word32 totalSz)
  10276. {
  10277. word32 idx = *inOutIdx;
  10278. *inOutIdx += HANDSHAKE_HEADER_SZ + DTLS_HANDSHAKE_EXTRA;
  10279. if (*inOutIdx > totalSz) {
  10280. WOLFSSL_ERROR(BUFFER_E);
  10281. return BUFFER_E;
  10282. }
  10283. *type = input[idx++];
  10284. c24to32(input + idx, size);
  10285. idx += OPAQUE24_LEN;
  10286. ato16(input + idx, &ssl->keys.dtls_peer_handshake_number);
  10287. idx += DTLS_HANDSHAKE_SEQ_SZ;
  10288. c24to32(input + idx, fragOffset);
  10289. idx += DTLS_HANDSHAKE_FRAG_SZ;
  10290. c24to32(input + idx, fragSz);
  10291. if ((ssl->curRL.pvMajor != ssl->version.major) ||
  10292. (!IsAtLeastTLSv1_3(ssl->version) && ssl->curRL.pvMinor != ssl->version.minor) ||
  10293. (IsAtLeastTLSv1_3(ssl->version) && ssl->curRL.pvMinor != DTLSv1_2_MINOR)
  10294. ) {
  10295. if (*type != client_hello && *type != hello_verify_request && *type != server_hello) {
  10296. WOLFSSL_ERROR(VERSION_ERROR);
  10297. return VERSION_ERROR;
  10298. }
  10299. else {
  10300. WOLFSSL_MSG("DTLS Handshake ignoring hello or verify version");
  10301. }
  10302. }
  10303. return 0;
  10304. }
  10305. #endif
  10306. #if !defined(NO_OLD_TLS) || \
  10307. (defined(NO_OLD_TLS) && defined(WOLFSSL_ALLOW_TLS_SHA1))
  10308. /* fill with MD5 pad size since biggest required */
  10309. static const byte PAD1[PAD_MD5] =
  10310. { 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  10311. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  10312. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  10313. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  10314. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  10315. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
  10316. };
  10317. static const byte PAD2[PAD_MD5] =
  10318. { 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  10319. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  10320. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  10321. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  10322. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  10323. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
  10324. };
  10325. #endif /* !NO_OLD_TLS || (NO_OLD_TLS && WOLFSSL_ALLOW_TLS_SHA1) */
  10326. #ifndef NO_OLD_TLS
  10327. /* calculate MD5 hash for finished */
  10328. #ifdef WOLFSSL_TI_HASH
  10329. #include <wolfssl/wolfcrypt/hash.h>
  10330. #endif
  10331. static int BuildMD5(WOLFSSL* ssl, Hashes* hashes, const byte* sender)
  10332. {
  10333. int ret;
  10334. byte md5_result[WC_MD5_DIGEST_SIZE];
  10335. #ifdef WOLFSSL_SMALL_STACK
  10336. wc_Md5* md5 = (wc_Md5*)XMALLOC(sizeof(wc_Md5), ssl->heap, DYNAMIC_TYPE_HASHCTX);
  10337. if (md5 == NULL)
  10338. return MEMORY_E;
  10339. #else
  10340. wc_Md5 md5[1];
  10341. #endif
  10342. /* make md5 inner */
  10343. ret = wc_Md5Copy(&ssl->hsHashes->hashMd5, md5);
  10344. if (ret == 0)
  10345. ret = wc_Md5Update(md5, sender, SIZEOF_SENDER);
  10346. if (ret == 0)
  10347. ret = wc_Md5Update(md5, ssl->arrays->masterSecret, SECRET_LEN);
  10348. if (ret == 0)
  10349. ret = wc_Md5Update(md5, PAD1, PAD_MD5);
  10350. if (ret == 0)
  10351. ret = wc_Md5Final(md5, md5_result);
  10352. /* make md5 outer */
  10353. if (ret == 0) {
  10354. ret = wc_InitMd5_ex(md5, ssl->heap, ssl->devId);
  10355. if (ret == 0) {
  10356. ret = wc_Md5Update(md5, ssl->arrays->masterSecret, SECRET_LEN);
  10357. if (ret == 0)
  10358. ret = wc_Md5Update(md5, PAD2, PAD_MD5);
  10359. if (ret == 0)
  10360. ret = wc_Md5Update(md5, md5_result, WC_MD5_DIGEST_SIZE);
  10361. if (ret == 0)
  10362. ret = wc_Md5Final(md5, hashes->md5);
  10363. wc_Md5Free(md5);
  10364. }
  10365. }
  10366. #ifdef WOLFSSL_SMALL_STACK
  10367. XFREE(md5, ssl->heap, DYNAMIC_TYPE_HASHCTX);
  10368. #endif
  10369. return ret;
  10370. }
  10371. /* calculate SHA hash for finished */
  10372. static int BuildSHA(WOLFSSL* ssl, Hashes* hashes, const byte* sender)
  10373. {
  10374. int ret;
  10375. byte sha_result[WC_SHA_DIGEST_SIZE];
  10376. #ifdef WOLFSSL_SMALL_STACK
  10377. wc_Sha* sha = (wc_Sha*)XMALLOC(sizeof(wc_Sha), ssl->heap, DYNAMIC_TYPE_HASHCTX);
  10378. if (sha == NULL)
  10379. return MEMORY_E;
  10380. #else
  10381. wc_Sha sha[1];
  10382. #endif
  10383. /* make sha inner */
  10384. ret = wc_ShaCopy(&ssl->hsHashes->hashSha, sha); /* Save current position */
  10385. if (ret == 0)
  10386. ret = wc_ShaUpdate(sha, sender, SIZEOF_SENDER);
  10387. if (ret == 0)
  10388. ret = wc_ShaUpdate(sha, ssl->arrays->masterSecret, SECRET_LEN);
  10389. if (ret == 0)
  10390. ret = wc_ShaUpdate(sha, PAD1, PAD_SHA);
  10391. if (ret == 0)
  10392. ret = wc_ShaFinal(sha, sha_result);
  10393. /* make sha outer */
  10394. if (ret == 0) {
  10395. ret = wc_InitSha_ex(sha, ssl->heap, ssl->devId);
  10396. if (ret == 0) {
  10397. ret = wc_ShaUpdate(sha, ssl->arrays->masterSecret, SECRET_LEN);
  10398. if (ret == 0)
  10399. ret = wc_ShaUpdate(sha, PAD2, PAD_SHA);
  10400. if (ret == 0)
  10401. ret = wc_ShaUpdate(sha, sha_result, WC_SHA_DIGEST_SIZE);
  10402. if (ret == 0)
  10403. ret = wc_ShaFinal(sha, hashes->sha);
  10404. wc_ShaFree(sha);
  10405. }
  10406. }
  10407. #ifdef WOLFSSL_SMALL_STACK
  10408. XFREE(sha, ssl->heap, DYNAMIC_TYPE_HASHCTX);
  10409. #endif
  10410. return ret;
  10411. }
  10412. #endif
  10413. #ifndef WOLFSSL_NO_TLS12
  10414. /* Finished doesn't support SHA512, not SHA512 cipher suites yet */
  10415. static int BuildFinished(WOLFSSL* ssl, Hashes* hashes, const byte* sender)
  10416. {
  10417. int ret = 0;
  10418. if (ssl == NULL)
  10419. return BAD_FUNC_ARG;
  10420. #ifndef NO_TLS
  10421. if (ssl->options.tls) {
  10422. ret = BuildTlsFinished(ssl, hashes, sender);
  10423. }
  10424. #else
  10425. (void)hashes;
  10426. (void)sender;
  10427. #endif
  10428. #ifndef NO_OLD_TLS
  10429. if (!ssl->options.tls) {
  10430. ret = BuildMD5(ssl, hashes, sender);
  10431. if (ret == 0) {
  10432. ret = BuildSHA(ssl, hashes, sender);
  10433. }
  10434. }
  10435. #endif
  10436. return ret;
  10437. }
  10438. #endif /* WOLFSSL_NO_TLS12 */
  10439. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
  10440. /* Does this cipher suite (first, second) have the requirement
  10441. an ephemeral key exchange will still require the key for signing
  10442. the key exchange so ECDHE_RSA requires an rsa key thus rsa_kea */
  10443. int CipherRequires(byte first, byte second, int requirement)
  10444. {
  10445. (void)requirement;
  10446. #ifndef WOLFSSL_NO_TLS12
  10447. #ifdef HAVE_CHACHA
  10448. if (first == CHACHA_BYTE) {
  10449. switch (second) {
  10450. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 :
  10451. if (requirement == REQUIRES_RSA)
  10452. return 1;
  10453. break;
  10454. case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 :
  10455. if (requirement == REQUIRES_ECC)
  10456. return 1;
  10457. break;
  10458. case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 :
  10459. if (requirement == REQUIRES_RSA)
  10460. return 1;
  10461. if (requirement == REQUIRES_DHE)
  10462. return 1;
  10463. break;
  10464. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  10465. if (requirement == REQUIRES_RSA)
  10466. return 1;
  10467. break;
  10468. case TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  10469. if (requirement == REQUIRES_ECC)
  10470. return 1;
  10471. break;
  10472. case TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  10473. if (requirement == REQUIRES_RSA)
  10474. return 1;
  10475. if (requirement == REQUIRES_DHE)
  10476. return 1;
  10477. break;
  10478. case TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 :
  10479. if (requirement == REQUIRES_PSK)
  10480. return 1;
  10481. break;
  10482. case TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 :
  10483. if (requirement == REQUIRES_PSK)
  10484. return 1;
  10485. break;
  10486. case TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 :
  10487. if (requirement == REQUIRES_PSK)
  10488. return 1;
  10489. if (requirement == REQUIRES_DHE)
  10490. return 1;
  10491. break;
  10492. default:
  10493. WOLFSSL_MSG("Unsupported cipher suite, CipherRequires CHACHA");
  10494. return 0;
  10495. }
  10496. if (requirement == REQUIRES_AEAD)
  10497. return 1;
  10498. }
  10499. #endif /* HAVE_CHACHA */
  10500. /* ECC extensions */
  10501. if (first == ECC_BYTE) {
  10502. switch (second) {
  10503. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  10504. #ifndef NO_RSA
  10505. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA :
  10506. if (requirement == REQUIRES_RSA)
  10507. return 1;
  10508. break;
  10509. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA :
  10510. if (requirement == REQUIRES_ECC_STATIC)
  10511. return 1;
  10512. if (requirement == REQUIRES_RSA_SIG)
  10513. return 1;
  10514. break;
  10515. #ifndef NO_DES3
  10516. case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA :
  10517. if (requirement == REQUIRES_RSA)
  10518. return 1;
  10519. break;
  10520. case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA :
  10521. if (requirement == REQUIRES_ECC_STATIC)
  10522. return 1;
  10523. if (requirement == REQUIRES_RSA_SIG)
  10524. return 1;
  10525. break;
  10526. #endif /* !NO_DES3 */
  10527. #ifndef NO_RC4
  10528. case TLS_ECDHE_RSA_WITH_RC4_128_SHA :
  10529. if (requirement == REQUIRES_RSA)
  10530. return 1;
  10531. break;
  10532. case TLS_ECDH_RSA_WITH_RC4_128_SHA :
  10533. if (requirement == REQUIRES_ECC_STATIC)
  10534. return 1;
  10535. if (requirement == REQUIRES_RSA_SIG)
  10536. return 1;
  10537. break;
  10538. #endif /* !NO_RC4 */
  10539. #endif /* NO_RSA */
  10540. #ifndef NO_DES3
  10541. case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA :
  10542. if (requirement == REQUIRES_ECC)
  10543. return 1;
  10544. break;
  10545. case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA :
  10546. if (requirement == REQUIRES_ECC_STATIC)
  10547. return 1;
  10548. break;
  10549. #endif /* !NO_DES3 */
  10550. #ifndef NO_RC4
  10551. case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA :
  10552. if (requirement == REQUIRES_ECC)
  10553. return 1;
  10554. break;
  10555. case TLS_ECDH_ECDSA_WITH_RC4_128_SHA :
  10556. if (requirement == REQUIRES_ECC_STATIC)
  10557. return 1;
  10558. break;
  10559. #endif /* !NO_RC4 */
  10560. #ifndef NO_RSA
  10561. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA :
  10562. if (requirement == REQUIRES_RSA)
  10563. return 1;
  10564. break;
  10565. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA :
  10566. if (requirement == REQUIRES_ECC_STATIC)
  10567. return 1;
  10568. if (requirement == REQUIRES_RSA_SIG)
  10569. return 1;
  10570. break;
  10571. #endif /* !NO_RSA */
  10572. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA :
  10573. if (requirement == REQUIRES_ECC)
  10574. return 1;
  10575. break;
  10576. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA :
  10577. if (requirement == REQUIRES_ECC_STATIC)
  10578. return 1;
  10579. break;
  10580. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA :
  10581. if (requirement == REQUIRES_ECC)
  10582. return 1;
  10583. break;
  10584. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA :
  10585. if (requirement == REQUIRES_ECC_STATIC)
  10586. return 1;
  10587. break;
  10588. case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 :
  10589. if (requirement == REQUIRES_ECC)
  10590. return 1;
  10591. if (requirement == REQUIRES_AEAD)
  10592. return 1;
  10593. break;
  10594. case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 :
  10595. if (requirement == REQUIRES_ECC)
  10596. return 1;
  10597. if (requirement == REQUIRES_AEAD)
  10598. return 1;
  10599. break;
  10600. case TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 :
  10601. if (requirement == REQUIRES_ECC_STATIC)
  10602. return 1;
  10603. if (requirement == REQUIRES_AEAD)
  10604. return 1;
  10605. break;
  10606. case TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 :
  10607. if (requirement == REQUIRES_ECC_STATIC)
  10608. return 1;
  10609. if (requirement == REQUIRES_AEAD)
  10610. return 1;
  10611. break;
  10612. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  10613. #ifndef NO_RSA
  10614. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  10615. case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 :
  10616. if (requirement == REQUIRES_RSA)
  10617. return 1;
  10618. if (requirement == REQUIRES_AEAD)
  10619. return 1;
  10620. break;
  10621. case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 :
  10622. if (requirement == REQUIRES_RSA)
  10623. return 1;
  10624. if (requirement == REQUIRES_AEAD)
  10625. return 1;
  10626. break;
  10627. case TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 :
  10628. if (requirement == REQUIRES_ECC_STATIC)
  10629. return 1;
  10630. if (requirement == REQUIRES_RSA_SIG)
  10631. return 1;
  10632. if (requirement == REQUIRES_AEAD)
  10633. return 1;
  10634. break;
  10635. case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 :
  10636. if (requirement == REQUIRES_ECC_STATIC)
  10637. return 1;
  10638. if (requirement == REQUIRES_RSA_SIG)
  10639. return 1;
  10640. if (requirement == REQUIRES_AEAD)
  10641. return 1;
  10642. break;
  10643. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  10644. #ifdef HAVE_AESCCM
  10645. case TLS_RSA_WITH_AES_128_CCM_8 :
  10646. case TLS_RSA_WITH_AES_256_CCM_8 :
  10647. if (requirement == REQUIRES_RSA)
  10648. return 1;
  10649. if (requirement == REQUIRES_RSA_SIG)
  10650. return 1;
  10651. if (requirement == REQUIRES_AEAD)
  10652. return 1;
  10653. break;
  10654. #endif /* HAVE_AESCCM */
  10655. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  10656. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 :
  10657. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 :
  10658. if (requirement == REQUIRES_RSA)
  10659. return 1;
  10660. break;
  10661. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 :
  10662. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 :
  10663. if (requirement == REQUIRES_RSA_SIG)
  10664. return 1;
  10665. if (requirement == REQUIRES_ECC_STATIC)
  10666. return 1;
  10667. break;
  10668. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  10669. #endif /* !NO_RSA */
  10670. #ifdef HAVE_ARIA
  10671. case TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 :
  10672. case TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 :
  10673. if (requirement == REQUIRES_ECC)
  10674. return 1;
  10675. break;
  10676. #endif /* HAVE_ARIA */
  10677. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  10678. case TLS_ECDHE_ECDSA_WITH_AES_128_CCM :
  10679. case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 :
  10680. case TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 :
  10681. if (requirement == REQUIRES_ECC)
  10682. return 1;
  10683. if (requirement == REQUIRES_AEAD)
  10684. return 1;
  10685. break;
  10686. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 :
  10687. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 :
  10688. if (requirement == REQUIRES_ECC)
  10689. return 1;
  10690. break;
  10691. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 :
  10692. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 :
  10693. if (requirement == REQUIRES_ECC)
  10694. return 1;
  10695. if (requirement == REQUIRES_ECC_STATIC)
  10696. return 1;
  10697. break;
  10698. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  10699. #ifndef NO_PSK
  10700. case TLS_PSK_WITH_AES_128_CCM:
  10701. case TLS_PSK_WITH_AES_256_CCM:
  10702. case TLS_PSK_WITH_AES_128_CCM_8:
  10703. case TLS_PSK_WITH_AES_256_CCM_8:
  10704. if (requirement == REQUIRES_PSK)
  10705. return 1;
  10706. if (requirement == REQUIRES_AEAD)
  10707. return 1;
  10708. break;
  10709. case TLS_DHE_PSK_WITH_AES_128_CCM:
  10710. case TLS_DHE_PSK_WITH_AES_256_CCM:
  10711. if (requirement == REQUIRES_PSK)
  10712. return 1;
  10713. if (requirement == REQUIRES_DHE)
  10714. return 1;
  10715. if (requirement == REQUIRES_AEAD)
  10716. return 1;
  10717. break;
  10718. #endif /* !NO_PSK */
  10719. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  10720. case TLS_ECDHE_ECDSA_WITH_NULL_SHA :
  10721. if (requirement == REQUIRES_ECC)
  10722. return 1;
  10723. break;
  10724. case TLS_ECDHE_PSK_WITH_NULL_SHA256 :
  10725. if (requirement == REQUIRES_PSK)
  10726. return 1;
  10727. break;
  10728. case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 :
  10729. if (requirement == REQUIRES_PSK)
  10730. return 1;
  10731. break;
  10732. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  10733. #if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER)
  10734. case TLS_SHA256_SHA256:
  10735. break;
  10736. case TLS_SHA384_SHA384:
  10737. break;
  10738. #endif
  10739. default:
  10740. WOLFSSL_MSG("Unsupported cipher suite, CipherRequires ECC");
  10741. return 0;
  10742. } /* switch */
  10743. } /* if */
  10744. /* ECC extensions */
  10745. if (first == ECDHE_PSK_BYTE) {
  10746. switch (second) {
  10747. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  10748. case TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256 :
  10749. if (requirement == REQUIRES_PSK)
  10750. return 1;
  10751. break;
  10752. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  10753. default:
  10754. WOLFSSL_MSG("Unsupported cipher suite, CipherRequires ECC PSK");
  10755. return 0;
  10756. } /* switch */
  10757. } /* if */
  10758. #endif /* !WOLFSSL_NO_TLS12 */
  10759. #ifdef WOLFSSL_TLS13
  10760. /* Distinct TLS v1.3 cipher suites with cipher and digest only. */
  10761. if (first == TLS13_BYTE) {
  10762. switch (second) {
  10763. case TLS_AES_128_GCM_SHA256:
  10764. case TLS_AES_256_GCM_SHA384:
  10765. case TLS_CHACHA20_POLY1305_SHA256:
  10766. case TLS_AES_128_CCM_SHA256:
  10767. case TLS_AES_128_CCM_8_SHA256:
  10768. if (requirement == REQUIRES_AEAD)
  10769. return 1;
  10770. return 0;
  10771. default:
  10772. WOLFSSL_MSG("Unsupported cipher suite, CipherRequires "
  10773. "TLS v1.3");
  10774. return 0;
  10775. }
  10776. }
  10777. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) && defined(WOLFSSL_SM4)
  10778. if (first == CIPHER_BYTE) {
  10779. /* Other cipher suites for TLS 1.2 below. */
  10780. switch (second) {
  10781. #if defined(WOLFSSL_SM4_GCM)
  10782. case TLS_SM4_GCM_SM3:
  10783. return 0;
  10784. break;
  10785. #endif
  10786. #if defined(WOLFSSL_SM4_CCM)
  10787. case TLS_SM4_CCM_SM3:
  10788. return 0;
  10789. break;
  10790. #endif
  10791. }
  10792. }
  10793. #endif /* WOLFSSL_SM2 && WOLFSSL_SM3 && WOLFSSL_SM4 */
  10794. #endif /* WOLFSSL_TLS13 */
  10795. #ifndef WOLFSSL_NO_TLS12
  10796. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) && defined(WOLFSSL_SM4)
  10797. if (first == SM_BYTE) {
  10798. switch (second) {
  10799. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  10800. case TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3:
  10801. if (requirement == REQUIRES_ECC)
  10802. return 1;
  10803. break;
  10804. #endif
  10805. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3
  10806. case TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3:
  10807. if (requirement == REQUIRES_ECC)
  10808. return 1;
  10809. break;
  10810. #endif
  10811. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3
  10812. case TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3:
  10813. if (requirement == REQUIRES_ECC)
  10814. return 1;
  10815. break;
  10816. #endif
  10817. default:
  10818. WOLFSSL_MSG("Unsupported cipher suite, CipherRequires SM");
  10819. return 0;
  10820. }
  10821. }
  10822. #endif
  10823. if (first == CIPHER_BYTE) {
  10824. /* normal suites */
  10825. switch (second) {
  10826. #ifndef NO_RSA
  10827. #ifndef NO_RC4
  10828. case SSL_RSA_WITH_RC4_128_SHA :
  10829. if (requirement == REQUIRES_RSA)
  10830. return 1;
  10831. break;
  10832. case SSL_RSA_WITH_RC4_128_MD5 :
  10833. if (requirement == REQUIRES_RSA)
  10834. return 1;
  10835. break;
  10836. #endif /* NO_RC4 */
  10837. case SSL_RSA_WITH_3DES_EDE_CBC_SHA :
  10838. if (requirement == REQUIRES_RSA)
  10839. return 1;
  10840. break;
  10841. case TLS_RSA_WITH_AES_128_CBC_SHA :
  10842. if (requirement == REQUIRES_RSA)
  10843. return 1;
  10844. break;
  10845. case TLS_RSA_WITH_AES_128_CBC_SHA256 :
  10846. if (requirement == REQUIRES_RSA)
  10847. return 1;
  10848. break;
  10849. case TLS_RSA_WITH_AES_256_CBC_SHA :
  10850. if (requirement == REQUIRES_RSA)
  10851. return 1;
  10852. break;
  10853. case TLS_RSA_WITH_AES_256_CBC_SHA256 :
  10854. if (requirement == REQUIRES_RSA)
  10855. return 1;
  10856. break;
  10857. case TLS_RSA_WITH_NULL_MD5 :
  10858. case TLS_RSA_WITH_NULL_SHA :
  10859. case TLS_RSA_WITH_NULL_SHA256 :
  10860. if (requirement == REQUIRES_RSA)
  10861. return 1;
  10862. break;
  10863. #endif /* !NO_RSA */
  10864. #ifndef NO_PSK
  10865. case TLS_PSK_WITH_AES_128_GCM_SHA256 :
  10866. if (requirement == REQUIRES_PSK)
  10867. return 1;
  10868. if (requirement == REQUIRES_AEAD)
  10869. return 1;
  10870. break;
  10871. case TLS_PSK_WITH_AES_256_GCM_SHA384 :
  10872. if (requirement == REQUIRES_PSK)
  10873. return 1;
  10874. if (requirement == REQUIRES_AEAD)
  10875. return 1;
  10876. break;
  10877. case TLS_PSK_WITH_AES_128_CBC_SHA256 :
  10878. case TLS_PSK_WITH_AES_256_CBC_SHA384 :
  10879. case TLS_PSK_WITH_AES_128_CBC_SHA :
  10880. case TLS_PSK_WITH_AES_256_CBC_SHA :
  10881. case TLS_PSK_WITH_NULL_SHA384 :
  10882. case TLS_PSK_WITH_NULL_SHA256 :
  10883. case TLS_PSK_WITH_NULL_SHA :
  10884. if (requirement == REQUIRES_PSK)
  10885. return 1;
  10886. break;
  10887. case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 :
  10888. case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 :
  10889. if (requirement == REQUIRES_DHE)
  10890. return 1;
  10891. if (requirement == REQUIRES_PSK)
  10892. return 1;
  10893. if (requirement == REQUIRES_AEAD)
  10894. return 1;
  10895. break;
  10896. case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 :
  10897. case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 :
  10898. case TLS_DHE_PSK_WITH_NULL_SHA384 :
  10899. case TLS_DHE_PSK_WITH_NULL_SHA256 :
  10900. if (requirement == REQUIRES_DHE)
  10901. return 1;
  10902. if (requirement == REQUIRES_PSK)
  10903. return 1;
  10904. break;
  10905. #endif /* NO_PSK */
  10906. #ifndef NO_RSA
  10907. case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 :
  10908. if (requirement == REQUIRES_RSA)
  10909. return 1;
  10910. if (requirement == REQUIRES_DHE)
  10911. return 1;
  10912. break;
  10913. case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 :
  10914. if (requirement == REQUIRES_RSA)
  10915. return 1;
  10916. if (requirement == REQUIRES_DHE)
  10917. return 1;
  10918. break;
  10919. case TLS_DHE_RSA_WITH_AES_128_CBC_SHA :
  10920. if (requirement == REQUIRES_RSA)
  10921. return 1;
  10922. if (requirement == REQUIRES_DHE)
  10923. return 1;
  10924. break;
  10925. case TLS_DHE_RSA_WITH_AES_256_CBC_SHA :
  10926. if (requirement == REQUIRES_RSA)
  10927. return 1;
  10928. if (requirement == REQUIRES_DHE)
  10929. return 1;
  10930. break;
  10931. case TLS_RSA_WITH_AES_128_GCM_SHA256 :
  10932. case TLS_RSA_WITH_AES_256_GCM_SHA384 :
  10933. if (requirement == REQUIRES_RSA)
  10934. return 1;
  10935. if (requirement == REQUIRES_AEAD)
  10936. return 1;
  10937. break;
  10938. case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
  10939. case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
  10940. if (requirement == REQUIRES_RSA)
  10941. return 1;
  10942. if (requirement == REQUIRES_DHE)
  10943. return 1;
  10944. if (requirement == REQUIRES_AEAD)
  10945. return 1;
  10946. break;
  10947. #ifdef HAVE_CAMELLIA
  10948. case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA :
  10949. case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA :
  10950. case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 :
  10951. case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 :
  10952. if (requirement == REQUIRES_RSA)
  10953. return 1;
  10954. break;
  10955. case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA :
  10956. case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA :
  10957. case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 :
  10958. case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 :
  10959. if (requirement == REQUIRES_RSA)
  10960. return 1;
  10961. if (requirement == REQUIRES_RSA_SIG)
  10962. return 1;
  10963. if (requirement == REQUIRES_DHE)
  10964. return 1;
  10965. break;
  10966. #endif /* HAVE_CAMELLIA */
  10967. case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
  10968. if (requirement == REQUIRES_RSA)
  10969. return 1;
  10970. if (requirement == REQUIRES_RSA_SIG)
  10971. return 1;
  10972. if (requirement == REQUIRES_DHE)
  10973. return 1;
  10974. break;
  10975. #endif /* !NO_RSA */
  10976. #ifdef HAVE_ANON
  10977. case TLS_DH_anon_WITH_AES_128_CBC_SHA :
  10978. if (requirement == REQUIRES_DHE)
  10979. return 1;
  10980. break;
  10981. case TLS_DH_anon_WITH_AES_256_GCM_SHA384:
  10982. if (requirement == REQUIRES_DHE)
  10983. return 1;
  10984. if (requirement == REQUIRES_AEAD)
  10985. return 1;
  10986. break;
  10987. #endif
  10988. #ifdef WOLFSSL_MULTICAST
  10989. case WDM_WITH_NULL_SHA256 :
  10990. break;
  10991. #endif
  10992. default:
  10993. WOLFSSL_MSG("Unsupported cipher suite, CipherRequires");
  10994. return 0;
  10995. } /* switch */
  10996. } /* if ECC / Normal suites else */
  10997. #endif /* !WOLFSSL_NO_TLS12 */
  10998. return 0;
  10999. }
  11000. #endif /* !NO_WOLFSSL_SERVER && !NO_WOLFSSL_CLIENT */
  11001. #ifndef NO_CERTS
  11002. /* Match names with wildcards, each wildcard can represent a single name
  11003. component or fragment but not multiple names, i.e.,
  11004. *.z.com matches y.z.com but not x.y.z.com
  11005. return 1 on success */
  11006. int MatchDomainName(const char* pattern, int patternLen, const char* str,
  11007. word32 strLen)
  11008. {
  11009. int ret = 0;
  11010. if (pattern == NULL || str == NULL || patternLen <= 0 || strLen == 0)
  11011. return 0;
  11012. while (patternLen > 0) {
  11013. /* Get the next pattern char to evaluate */
  11014. char p = (char)XTOLOWER((unsigned char)*pattern);
  11015. if (p == '\0')
  11016. break;
  11017. pattern++;
  11018. if (p == '*') {
  11019. char s;
  11020. /* We will always match '*' */
  11021. patternLen--;
  11022. /* Consume any extra '*' chars until the next non '*' char. */
  11023. while (patternLen > 0) {
  11024. p = (char)XTOLOWER((unsigned char)*pattern);
  11025. pattern++;
  11026. if (p == '\0' && patternLen > 0)
  11027. return 0;
  11028. if (p != '*')
  11029. break;
  11030. patternLen--;
  11031. }
  11032. /* Consume str until we reach next char in pattern after '*' or
  11033. * end of string */
  11034. while (strLen > 0) {
  11035. s = (char)XTOLOWER((unsigned char) *str);
  11036. str++;
  11037. strLen--;
  11038. /* p is next char in pattern after '*', or '*' if '*' is the
  11039. * last char in the pattern (in which case patternLen is 1) */
  11040. if ( ((s == p) && (patternLen > 0))) {
  11041. /* We had already counted the '*' as matched, this means
  11042. * we also matched the next non '*' char in pattern */
  11043. patternLen--;
  11044. break;
  11045. }
  11046. /* If strlen is 0, we have consumed the entire string. Count that
  11047. * as a match of '*' */
  11048. if (strLen == 0) {
  11049. break;
  11050. }
  11051. if (s == '.')
  11052. return 0;
  11053. }
  11054. }
  11055. else {
  11056. /* Simple case, pattern match exactly */
  11057. if (p != (char)XTOLOWER((unsigned char) *str))
  11058. return 0;
  11059. str++;
  11060. strLen--;
  11061. patternLen--;
  11062. }
  11063. }
  11064. if (strLen == 0 && patternLen == 0) {
  11065. ret = 1; /* success */
  11066. }
  11067. return ret;
  11068. }
  11069. /* Check that alternative names, if they exists, match the domain.
  11070. * Fail if there are wild patterns and they didn't match.
  11071. * Check the common name if no alternative names matched.
  11072. *
  11073. * dCert Decoded cert to get the alternative names from.
  11074. * domain Domain name to compare against.
  11075. * domainLen Length of the domain name.
  11076. * checkCN Whether to check the common name.
  11077. * returns 1 : match was found.
  11078. * 0 : no match found.
  11079. * -1 : No matches and wild pattern match failed.
  11080. */
  11081. int CheckForAltNames(DecodedCert* dCert, const char* domain, word32 domainLen,
  11082. int* checkCN)
  11083. {
  11084. int match = 0;
  11085. DNS_entry* altName = NULL;
  11086. char *buf;
  11087. word32 len;
  11088. WOLFSSL_MSG("Checking AltNames");
  11089. if (dCert)
  11090. altName = dCert->altNames;
  11091. if (checkCN != NULL) {
  11092. *checkCN = (altName == NULL) ? 1 : 0;
  11093. }
  11094. while (altName) {
  11095. WOLFSSL_MSG("\tindividual AltName check");
  11096. #ifdef WOLFSSL_IP_ALT_NAME
  11097. if (altName->type == ASN_IP_TYPE) {
  11098. buf = altName->ipString;
  11099. len = (word32)XSTRLEN(buf);
  11100. }
  11101. else
  11102. #endif /* WOLFSSL_IP_ALT_NAME */
  11103. {
  11104. buf = altName->name;
  11105. len = (word32)altName->len;
  11106. }
  11107. if (MatchDomainName(buf, (int)len, domain, domainLen)) {
  11108. match = 1;
  11109. if (checkCN != NULL) {
  11110. *checkCN = 0;
  11111. }
  11112. WOLFSSL_MSG("\tmatch found");
  11113. break;
  11114. }
  11115. /* No matches and wild pattern match failed. */
  11116. else if (buf && (len >=1) && (buf[0] == '*')) {
  11117. match = -1;
  11118. WOLFSSL_MSG("\twildcard match failed");
  11119. }
  11120. altName = altName->next;
  11121. }
  11122. return match;
  11123. }
  11124. /* Check the domain name matches the subject alternative name or the subject
  11125. * name.
  11126. *
  11127. * dcert Decoded certificate.
  11128. * domainName The domain name.
  11129. * domainNameLen The length of the domain name.
  11130. * returns DOMAIN_NAME_MISMATCH when no match found and 0 on success.
  11131. */
  11132. int CheckHostName(DecodedCert* dCert, const char *domainName, size_t domainNameLen)
  11133. {
  11134. int checkCN;
  11135. int ret = WC_NO_ERR_TRACE(DOMAIN_NAME_MISMATCH);
  11136. if (CheckForAltNames(dCert, domainName, (word32)domainNameLen,
  11137. &checkCN) != 1) {
  11138. ret = DOMAIN_NAME_MISMATCH;
  11139. WOLFSSL_MSG("DomainName match on alt names failed");
  11140. }
  11141. else {
  11142. ret = 0;
  11143. }
  11144. #ifndef WOLFSSL_HOSTNAME_VERIFY_ALT_NAME_ONLY
  11145. if (checkCN == 1) {
  11146. if (MatchDomainName(dCert->subjectCN, dCert->subjectCNLen,
  11147. domainName, (word32)domainNameLen) == 1) {
  11148. ret = 0;
  11149. }
  11150. else {
  11151. ret = DOMAIN_NAME_MISMATCH;
  11152. WOLFSSL_MSG("DomainName match on common name failed");
  11153. }
  11154. }
  11155. #endif /* !WOLFSSL_HOSTNAME_VERIFY_ALT_NAME_ONLY */
  11156. return ret;
  11157. }
  11158. int CheckIPAddr(DecodedCert* dCert, const char* ipasc)
  11159. {
  11160. WOLFSSL_MSG("Checking IPAddr");
  11161. return CheckHostName(dCert, ipasc, (size_t)XSTRLEN(ipasc));
  11162. }
  11163. #ifdef SESSION_CERTS
  11164. static void AddSessionCertToChain(WOLFSSL_X509_CHAIN* chain,
  11165. byte* certBuf, word32 certSz)
  11166. {
  11167. if (chain->count < MAX_CHAIN_DEPTH &&
  11168. certSz < MAX_X509_SIZE) {
  11169. chain->certs[chain->count].length = (int)certSz;
  11170. XMEMCPY(chain->certs[chain->count].buffer, certBuf, certSz);
  11171. chain->count++;
  11172. }
  11173. else {
  11174. WOLFSSL_MSG("Couldn't store chain cert for session");
  11175. }
  11176. }
  11177. #endif
  11178. #if defined(KEEP_PEER_CERT) || defined(SESSION_CERTS) || \
  11179. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  11180. defined(WOLFSSL_ACERT)
  11181. static int CopyAltNames(DNS_entry** to, DNS_entry* from, int type, void* heap)
  11182. {
  11183. /* Copy from to the beginning of to */
  11184. DNS_entry** prev_next = to;
  11185. DNS_entry* next;
  11186. if (to == NULL) {
  11187. return BAD_FUNC_ARG;
  11188. }
  11189. next = *to;
  11190. for (; from != NULL; from = from->next) {
  11191. DNS_entry* dnsEntry;
  11192. if (type != -1 && from->type != type)
  11193. continue;
  11194. dnsEntry = AltNameDup(from, heap);
  11195. if (dnsEntry == NULL) {
  11196. WOLFSSL_MSG("\tOut of Memory");
  11197. return MEMORY_E;
  11198. }
  11199. dnsEntry->next = next;
  11200. *prev_next = dnsEntry;
  11201. prev_next = &dnsEntry->next;
  11202. }
  11203. return 0;
  11204. }
  11205. #endif /* KEEP_PEER_CERT || SESSION_CERTS ||
  11206. * OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL ||
  11207. * WOLFSSL_ACERT */
  11208. #if defined(KEEP_PEER_CERT) || defined(SESSION_CERTS) || \
  11209. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  11210. void CopyDecodedName(WOLFSSL_X509_NAME* name, DecodedCert* dCert, int nameType)
  11211. {
  11212. if (name->dynamicName) {
  11213. XFREE(name->name, name->heap, DYNAMIC_TYPE_X509);
  11214. name->name = name->staticName;
  11215. name->dynamicName = 0;
  11216. }
  11217. if (nameType == ASN_SUBJECT) {
  11218. XSTRNCPY(name->name, dCert->subject, ASN_NAME_MAX);
  11219. name->name[ASN_NAME_MAX - 1] = '\0';
  11220. name->sz = (int)XSTRLEN(name->name) + 1;
  11221. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)
  11222. name->rawLen = min(dCert->subjectRawLen, ASN_NAME_MAX);
  11223. if (name->rawLen > 0)
  11224. XMEMCPY(name->raw, dCert->subjectRaw, name->rawLen);
  11225. #endif
  11226. }
  11227. else {
  11228. XSTRNCPY(name->name, dCert->issuer, ASN_NAME_MAX);
  11229. name->name[ASN_NAME_MAX - 1] = '\0';
  11230. name->sz = (int)XSTRLEN(name->name) + 1;
  11231. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) \
  11232. && (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  11233. name->rawLen = min(dCert->issuerRawLen, ASN_NAME_MAX);
  11234. if (name->rawLen > 0) {
  11235. XMEMCPY(name->raw, dCert->issuerRaw, name->rawLen);
  11236. }
  11237. #endif
  11238. }
  11239. }
  11240. #ifdef WOLFSSL_CERT_REQ
  11241. static int CopyREQAttributes(WOLFSSL_X509* x509, DecodedCert* dCert)
  11242. {
  11243. int ret = 0;
  11244. if (dCert->cPwd) {
  11245. if (dCert->cPwdLen < CTC_NAME_SIZE) {
  11246. XMEMCPY(x509->challengePw, dCert->cPwd, dCert->cPwdLen);
  11247. x509->challengePw[dCert->cPwdLen] = '\0';
  11248. #if defined(OPENSSL_ALL) && defined(WOLFSSL_CERT_GEN)
  11249. if (wolfSSL_X509_REQ_add1_attr_by_NID(x509,
  11250. NID_pkcs9_challengePassword,
  11251. MBSTRING_ASC,
  11252. (const byte*)dCert->cPwd,
  11253. dCert->cPwdLen) != WOLFSSL_SUCCESS) {
  11254. ret = REQ_ATTRIBUTE_E;
  11255. WOLFSSL_ERROR_VERBOSE(ret);
  11256. }
  11257. #endif
  11258. }
  11259. else {
  11260. WOLFSSL_MSG("Challenge password too long");
  11261. ret = MEMORY_E;
  11262. }
  11263. }
  11264. if (dCert->contentType) {
  11265. if (dCert->contentTypeLen < CTC_NAME_SIZE) {
  11266. XMEMCPY(x509->contentType, dCert->contentType, dCert->contentTypeLen);
  11267. x509->contentType[dCert->contentTypeLen] = '\0';
  11268. }
  11269. #if defined(OPENSSL_ALL) && defined(WOLFSSL_CERT_GEN)
  11270. if (wolfSSL_X509_REQ_add1_attr_by_NID(x509,
  11271. NID_pkcs9_contentType,
  11272. MBSTRING_ASC,
  11273. (const byte*)dCert->contentType,
  11274. dCert->contentTypeLen) !=
  11275. WOLFSSL_SUCCESS) {
  11276. ret = REQ_ATTRIBUTE_E;
  11277. WOLFSSL_ERROR_VERBOSE(ret);
  11278. }
  11279. #endif
  11280. }
  11281. #if defined(OPENSSL_ALL) && defined(WOLFSSL_CERT_GEN)
  11282. if (dCert->sNum) {
  11283. if (wolfSSL_X509_REQ_add1_attr_by_NID(x509,
  11284. NID_serialNumber,
  11285. MBSTRING_ASC,
  11286. (const byte*)dCert->sNum,
  11287. dCert->sNumLen) != WOLFSSL_SUCCESS) {
  11288. ret = REQ_ATTRIBUTE_E;
  11289. WOLFSSL_ERROR_VERBOSE(ret);
  11290. }
  11291. }
  11292. if (dCert->unstructuredName) {
  11293. if (wolfSSL_X509_REQ_add1_attr_by_NID(x509,
  11294. NID_pkcs9_unstructuredName,
  11295. MBSTRING_ASC,
  11296. (const byte*)dCert->unstructuredName,
  11297. dCert->unstructuredNameLen)
  11298. != WOLFSSL_SUCCESS) {
  11299. ret = REQ_ATTRIBUTE_E;
  11300. WOLFSSL_ERROR_VERBOSE(ret);
  11301. }
  11302. }
  11303. if (dCert->surname) {
  11304. if (wolfSSL_X509_REQ_add1_attr_by_NID(x509,
  11305. NID_surname,
  11306. MBSTRING_ASC,
  11307. (const byte*)dCert->surname,
  11308. dCert->surnameLen) != WOLFSSL_SUCCESS) {
  11309. ret = REQ_ATTRIBUTE_E;
  11310. WOLFSSL_ERROR_VERBOSE(ret);
  11311. }
  11312. }
  11313. if (dCert->givenName) {
  11314. if (wolfSSL_X509_REQ_add1_attr_by_NID(x509,
  11315. NID_givenName,
  11316. MBSTRING_ASC,
  11317. (const byte*)dCert->givenName,
  11318. dCert->givenNameLen) != WOLFSSL_SUCCESS) {
  11319. ret = REQ_ATTRIBUTE_E;
  11320. WOLFSSL_ERROR_VERBOSE(ret);
  11321. }
  11322. }
  11323. if (dCert->dnQualifier) {
  11324. if (wolfSSL_X509_REQ_add1_attr_by_NID(x509,
  11325. NID_dnQualifier,
  11326. MBSTRING_ASC,
  11327. (const byte*)dCert->dnQualifier,
  11328. dCert->dnQualifierLen) != WOLFSSL_SUCCESS) {
  11329. ret = REQ_ATTRIBUTE_E;
  11330. WOLFSSL_ERROR_VERBOSE(ret);
  11331. }
  11332. }
  11333. if (dCert->initials) {
  11334. if (wolfSSL_X509_REQ_add1_attr_by_NID(x509,
  11335. NID_initials,
  11336. MBSTRING_ASC,
  11337. (const byte*)dCert->initials,
  11338. dCert->initialsLen) != WOLFSSL_SUCCESS) {
  11339. ret = REQ_ATTRIBUTE_E;
  11340. WOLFSSL_ERROR_VERBOSE(ret);
  11341. }
  11342. }
  11343. #endif /* OPENSSL_ALL */
  11344. return ret;
  11345. }
  11346. #endif /* WOLFSSL_CERT_REQ */
  11347. /* Copy parts X509 needs from Decoded cert, 0 on success */
  11348. int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert)
  11349. {
  11350. int ret = 0;
  11351. int minSz;
  11352. if (x509 == NULL || dCert == NULL ||
  11353. dCert->subjectCNLen < 0)
  11354. return BAD_FUNC_ARG;
  11355. if (x509->issuer.name == NULL || x509->subject.name == NULL) {
  11356. WOLFSSL_MSG("Either init was not called on X509 or programming error");
  11357. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  11358. return BAD_FUNC_ARG;
  11359. }
  11360. x509->version = dCert->version + 1;
  11361. CopyDecodedName(&x509->issuer, dCert, ASN_ISSUER);
  11362. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  11363. if (dCert->issuerName != NULL) {
  11364. wolfSSL_X509_set_issuer_name(x509,
  11365. (WOLFSSL_X509_NAME*)dCert->issuerName);
  11366. x509->issuer.x509 = x509;
  11367. }
  11368. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  11369. CopyDecodedName(&x509->subject, dCert, ASN_SUBJECT);
  11370. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  11371. if (dCert->subjectName != NULL) {
  11372. wolfSSL_X509_set_subject_name(x509,
  11373. (WOLFSSL_X509_NAME*)dCert->subjectName);
  11374. x509->subject.x509 = x509;
  11375. }
  11376. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  11377. XMEMCPY(x509->serial, dCert->serial, EXTERNAL_SERIAL_SIZE);
  11378. x509->serialSz = dCert->serialSz;
  11379. if (dCert->subjectCN && dCert->subjectCNLen < ASN_NAME_MAX) {
  11380. XMEMCPY(x509->subjectCN, dCert->subjectCN, dCert->subjectCNLen);
  11381. x509->subjectCN[dCert->subjectCNLen] = '\0';
  11382. }
  11383. else
  11384. x509->subjectCN[0] = '\0';
  11385. #ifdef WOLFSSL_CERT_REQ
  11386. x509->isCSR = dCert->isCSR;
  11387. /* CSR attributes */
  11388. if (x509->isCSR) {
  11389. ret = CopyREQAttributes(x509, dCert);
  11390. }
  11391. #endif /* WOLFSSL_CERT_REQ */
  11392. #ifdef WOLFSSL_SEP
  11393. minSz = min(dCert->deviceTypeSz, EXTERNAL_SERIAL_SIZE);
  11394. if (minSz > 0) {
  11395. x509->deviceTypeSz = minSz;
  11396. XMEMCPY(x509->deviceType, dCert->deviceType, minSz);
  11397. }
  11398. else
  11399. x509->deviceTypeSz = 0;
  11400. minSz = min(dCert->hwTypeSz, EXTERNAL_SERIAL_SIZE);
  11401. if (minSz > 0) {
  11402. x509->hwTypeSz = minSz;
  11403. XMEMCPY(x509->hwType, dCert->hwType, minSz);
  11404. }
  11405. else
  11406. x509->hwTypeSz = 0;
  11407. minSz = min(dCert->hwSerialNumSz, EXTERNAL_SERIAL_SIZE);
  11408. if (minSz > 0) {
  11409. x509->hwSerialNumSz = minSz;
  11410. XMEMCPY(x509->hwSerialNum, dCert->hwSerialNum, minSz);
  11411. }
  11412. else
  11413. x509->hwSerialNumSz = 0;
  11414. #endif /* WOLFSSL_SEP */
  11415. if (dCert->beforeDateLen > 0) {
  11416. minSz = (int)min(dCert->beforeDate[1], MAX_DATE_SZ);
  11417. x509->notBefore.type = dCert->beforeDate[0];
  11418. x509->notBefore.length = minSz;
  11419. XMEMCPY(x509->notBefore.data, &dCert->beforeDate[2], minSz);
  11420. }
  11421. else
  11422. x509->notBefore.length = 0;
  11423. if (dCert->afterDateLen > 0) {
  11424. minSz = (int)min(dCert->afterDate[1], MAX_DATE_SZ);
  11425. x509->notAfter.type = dCert->afterDate[0];
  11426. x509->notAfter.length = minSz;
  11427. XMEMCPY(x509->notAfter.data, &dCert->afterDate[2], minSz);
  11428. }
  11429. else
  11430. x509->notAfter.length = 0;
  11431. if (dCert->publicKey != NULL && dCert->pubKeySize != 0) {
  11432. x509->pubKey.buffer = (byte*)XMALLOC(
  11433. dCert->pubKeySize, x509->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  11434. if (x509->pubKey.buffer != NULL) {
  11435. x509->pubKeyOID = (int)dCert->keyOID;
  11436. x509->pubKey.length = dCert->pubKeySize;
  11437. XMEMCPY(x509->pubKey.buffer, dCert->publicKey, dCert->pubKeySize);
  11438. }
  11439. else
  11440. ret = MEMORY_E;
  11441. #if defined(OPENSSL_ALL)
  11442. if (ret == 0) {
  11443. x509->key.pubKeyOID = (int)dCert->keyOID;
  11444. if (!x509->key.algor) {
  11445. x509->key.algor = wolfSSL_X509_ALGOR_new();
  11446. } else {
  11447. wolfSSL_ASN1_OBJECT_free(x509->key.algor->algorithm);
  11448. }
  11449. if (!x509->key.algor) {
  11450. ret = MEMORY_E;
  11451. } else {
  11452. if (!(x509->key.algor->algorithm =
  11453. wolfSSL_OBJ_nid2obj(oid2nid(dCert->keyOID, oidKeyType)))) {
  11454. ret = PUBLIC_KEY_E;
  11455. WOLFSSL_ERROR_VERBOSE(ret);
  11456. }
  11457. }
  11458. wolfSSL_EVP_PKEY_free(x509->key.pkey);
  11459. if (!(x509->key.pkey = wolfSSL_d2i_PUBKEY(NULL,
  11460. &dCert->publicKey,
  11461. dCert->pubKeySize))) {
  11462. ret = PUBLIC_KEY_E;
  11463. WOLFSSL_ERROR_VERBOSE(ret);
  11464. }
  11465. }
  11466. #endif
  11467. }
  11468. if (dCert->signature != NULL && dCert->sigLength != 0 &&
  11469. dCert->sigLength <= MAX_ENCODED_SIG_SZ) {
  11470. x509->sig.buffer = (byte*)XMALLOC(
  11471. dCert->sigLength, x509->heap, DYNAMIC_TYPE_SIGNATURE);
  11472. if (x509->sig.buffer == NULL) {
  11473. ret = MEMORY_E;
  11474. }
  11475. else {
  11476. XMEMCPY(x509->sig.buffer, dCert->signature, dCert->sigLength);
  11477. x509->sig.length = dCert->sigLength;
  11478. x509->sigOID = (int)dCert->signatureOID;
  11479. }
  11480. #if defined(OPENSSL_ALL)
  11481. wolfSSL_ASN1_OBJECT_free(x509->algor.algorithm);
  11482. if (!(x509->algor.algorithm =
  11483. wolfSSL_OBJ_nid2obj(oid2nid(dCert->signatureOID, oidSigType)))) {
  11484. ret = PUBLIC_KEY_E;
  11485. WOLFSSL_ERROR_VERBOSE(ret);
  11486. }
  11487. #endif
  11488. }
  11489. /* if der contains original source buffer then store for potential
  11490. * retrieval */
  11491. if (dCert->source != NULL && dCert->maxIdx > 0) {
  11492. if (AllocDer(&x509->derCert, dCert->maxIdx, CERT_TYPE, x509->heap)
  11493. == 0) {
  11494. XMEMCPY(x509->derCert->buffer, dCert->source, dCert->maxIdx);
  11495. }
  11496. else {
  11497. ret = MEMORY_E;
  11498. }
  11499. }
  11500. /* add alt names from dCert to X509 */
  11501. if (CopyAltNames(&x509->altNames, dCert->altNames, -1, x509->heap) != 0) {
  11502. return MEMORY_E;
  11503. }
  11504. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11505. !defined(IGNORE_NAME_CONSTRAINTS)
  11506. /* add copies of email names from dCert to X509 */
  11507. if (CopyAltNames(&x509->altNames, dCert->altEmailNames,
  11508. ASN_RFC822_TYPE, x509->heap) != 0) {
  11509. return MEMORY_E;
  11510. }
  11511. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  11512. #if defined(OPENSSL_EXTRA) && !defined(IGNORE_NAME_CONSTRAINTS)
  11513. /* add copies of alternate directory names from dCert to X509 */
  11514. if (CopyAltNames(&x509->altNames, dCert->altDirNames,
  11515. ASN_DIR_TYPE, x509->heap) != 0) {
  11516. return MEMORY_E;
  11517. }
  11518. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  11519. x509->altNamesNext = x509->altNames; /* index hint */
  11520. x509->isCa = dCert->isCA;
  11521. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  11522. x509->pathLength = dCert->pathLength;
  11523. x509->keyUsage = dCert->extKeyUsage;
  11524. x509->CRLdistSet = dCert->extCRLdistSet;
  11525. x509->CRLdistCrit = dCert->extCRLdistCrit;
  11526. if (dCert->extCrlInfoRaw != NULL && dCert->extCrlInfoRawSz > 0) {
  11527. x509->rawCRLInfo = (byte*)XMALLOC(dCert->extCrlInfoRawSz, x509->heap,
  11528. DYNAMIC_TYPE_X509_EXT);
  11529. if (x509->rawCRLInfo != NULL) {
  11530. XMEMCPY(x509->rawCRLInfo, dCert->extCrlInfoRaw, dCert->extCrlInfoRawSz);
  11531. x509->rawCRLInfoSz = dCert->extCrlInfoRawSz;
  11532. }
  11533. else {
  11534. ret = MEMORY_E;
  11535. }
  11536. }
  11537. if (dCert->extCrlInfo != NULL && dCert->extCrlInfoSz > 0) {
  11538. x509->CRLInfo = (byte*)XMALLOC(dCert->extCrlInfoSz, x509->heap,
  11539. DYNAMIC_TYPE_X509_EXT);
  11540. if (x509->CRLInfo != NULL) {
  11541. XMEMCPY(x509->CRLInfo, dCert->extCrlInfo, dCert->extCrlInfoSz);
  11542. x509->CRLInfoSz = dCert->extCrlInfoSz;
  11543. }
  11544. else {
  11545. ret = MEMORY_E;
  11546. }
  11547. }
  11548. x509->authInfoSet = dCert->extAuthInfoSet;
  11549. x509->authInfoCrit = dCert->extAuthInfoCrit;
  11550. if (dCert->extAuthInfo != NULL && dCert->extAuthInfoSz > 0) {
  11551. x509->authInfo = (byte*)XMALLOC(dCert->extAuthInfoSz, x509->heap,
  11552. DYNAMIC_TYPE_X509_EXT);
  11553. if (x509->authInfo != NULL) {
  11554. XMEMCPY(x509->authInfo, dCert->extAuthInfo, dCert->extAuthInfoSz);
  11555. x509->authInfoSz = dCert->extAuthInfoSz;
  11556. }
  11557. else {
  11558. ret = MEMORY_E;
  11559. }
  11560. }
  11561. #ifdef WOLFSSL_ASN_CA_ISSUER
  11562. if (dCert->extAuthInfoCaIssuer != NULL && dCert->extAuthInfoCaIssuerSz > 0) {
  11563. x509->authInfoCaIssuer = (byte*)XMALLOC(dCert->extAuthInfoCaIssuerSz, x509->heap,
  11564. DYNAMIC_TYPE_X509_EXT);
  11565. if (x509->authInfoCaIssuer != NULL) {
  11566. XMEMCPY(x509->authInfoCaIssuer, dCert->extAuthInfoCaIssuer, dCert->extAuthInfoCaIssuerSz);
  11567. x509->authInfoCaIssuerSz = dCert->extAuthInfoCaIssuerSz;
  11568. }
  11569. else {
  11570. ret = MEMORY_E;
  11571. }
  11572. }
  11573. #endif
  11574. x509->basicConstSet = dCert->extBasicConstSet;
  11575. x509->basicConstCrit = dCert->extBasicConstCrit;
  11576. x509->basicConstPlSet = dCert->pathLengthSet;
  11577. x509->subjAltNameSet = dCert->extSubjAltNameSet;
  11578. x509->subjAltNameCrit = dCert->extSubjAltNameCrit;
  11579. x509->authKeyIdSet = dCert->extAuthKeyIdSet;
  11580. x509->authKeyIdCrit = dCert->extAuthKeyIdCrit;
  11581. if (dCert->extAuthKeyIdSrc != NULL && dCert->extAuthKeyIdSz != 0) {
  11582. #ifdef WOLFSSL_AKID_NAME
  11583. if (dCert->extRawAuthKeyIdSrc != NULL &&
  11584. dCert->extAuthKeyIdSrc > dCert->extRawAuthKeyIdSrc &&
  11585. dCert->extAuthKeyIdSrc <
  11586. (dCert->extRawAuthKeyIdSrc + dCert->extRawAuthKeyIdSz)) {
  11587. /* Confirmed: extAuthKeyIdSrc points inside extRawAuthKeyIdSrc */
  11588. x509->authKeyIdSrc = (byte*)XMALLOC(dCert->extRawAuthKeyIdSz,
  11589. x509->heap, DYNAMIC_TYPE_X509_EXT);
  11590. if (x509->authKeyIdSrc != NULL) {
  11591. XMEMCPY(x509->authKeyIdSrc, dCert->extRawAuthKeyIdSrc,
  11592. dCert->extRawAuthKeyIdSz);
  11593. x509->authKeyIdSrcSz = dCert->extRawAuthKeyIdSz;
  11594. /* Set authKeyId to same offset inside authKeyIdSrc */
  11595. x509->authKeyId = x509->authKeyIdSrc +
  11596. (dCert->extAuthKeyIdSrc - dCert->extRawAuthKeyIdSrc);
  11597. x509->authKeyIdSz = dCert->extAuthKeyIdSz;
  11598. }
  11599. else
  11600. ret = MEMORY_E;
  11601. }
  11602. #else
  11603. x509->authKeyId = (byte*)XMALLOC(dCert->extAuthKeyIdSz, x509->heap,
  11604. DYNAMIC_TYPE_X509_EXT);
  11605. if (x509->authKeyId != NULL) {
  11606. XMEMCPY(x509->authKeyId,
  11607. dCert->extAuthKeyIdSrc, dCert->extAuthKeyIdSz);
  11608. x509->authKeyIdSz = dCert->extAuthKeyIdSz;
  11609. }
  11610. #endif
  11611. else
  11612. ret = MEMORY_E;
  11613. }
  11614. x509->subjKeyIdSet = dCert->extSubjKeyIdSet;
  11615. x509->subjKeyIdCrit = dCert->extSubjKeyIdCrit;
  11616. if (dCert->extSubjKeyIdSrc != NULL && dCert->extSubjKeyIdSz != 0) {
  11617. x509->subjKeyId = (byte*)XMALLOC(dCert->extSubjKeyIdSz, x509->heap,
  11618. DYNAMIC_TYPE_X509_EXT);
  11619. if (x509->subjKeyId != NULL) {
  11620. XMEMCPY(x509->subjKeyId,
  11621. dCert->extSubjKeyIdSrc, dCert->extSubjKeyIdSz);
  11622. x509->subjKeyIdSz = dCert->extSubjKeyIdSz;
  11623. }
  11624. else
  11625. ret = MEMORY_E;
  11626. }
  11627. x509->keyUsageSet = dCert->extKeyUsageSet;
  11628. x509->keyUsageCrit = dCert->extKeyUsageCrit;
  11629. if (dCert->extExtKeyUsageSrc != NULL && dCert->extExtKeyUsageSz > 0) {
  11630. x509->extKeyUsageSrc = (byte*)XMALLOC(dCert->extExtKeyUsageSz,
  11631. x509->heap, DYNAMIC_TYPE_X509_EXT);
  11632. if (x509->extKeyUsageSrc != NULL) {
  11633. XMEMCPY(x509->extKeyUsageSrc, dCert->extExtKeyUsageSrc,
  11634. dCert->extExtKeyUsageSz);
  11635. x509->extKeyUsage = dCert->extExtKeyUsage;
  11636. x509->extKeyUsageSz = dCert->extExtKeyUsageSz;
  11637. x509->extKeyUsageCrit = dCert->extExtKeyUsageCrit;
  11638. x509->extKeyUsageCount = dCert->extExtKeyUsageCount;
  11639. }
  11640. else {
  11641. ret = MEMORY_E;
  11642. }
  11643. }
  11644. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  11645. x509->nsCertType = dCert->nsCertType;
  11646. #endif
  11647. #ifdef WOLFSSL_SEP
  11648. x509->certPolicySet = dCert->extCertPolicySet;
  11649. x509->certPolicyCrit = dCert->extCertPolicyCrit;
  11650. #endif
  11651. #ifdef WOLFSSL_CERT_EXT
  11652. {
  11653. int i;
  11654. for (i = 0; i < dCert->extCertPoliciesNb && i < MAX_CERTPOL_NB; i++)
  11655. XMEMCPY(x509->certPolicies[i], dCert->extCertPolicies[i],
  11656. MAX_CERTPOL_SZ);
  11657. x509->certPoliciesNb = dCert->extCertPoliciesNb;
  11658. }
  11659. #endif /* WOLFSSL_CERT_EXT */
  11660. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  11661. #ifdef OPENSSL_ALL
  11662. if (dCert->extSubjAltNameSrc != NULL && dCert->extSubjAltNameSz != 0) {
  11663. x509->subjAltNameSrc = (byte*)XMALLOC(dCert->extSubjAltNameSz, x509->heap,
  11664. DYNAMIC_TYPE_X509_EXT);
  11665. if (x509->subjAltNameSrc != NULL) {
  11666. XMEMCPY(x509->subjAltNameSrc,
  11667. dCert->extSubjAltNameSrc, dCert->extSubjAltNameSz);
  11668. x509->subjAltNameSz = dCert->extSubjAltNameSz;
  11669. }
  11670. else
  11671. ret = MEMORY_E;
  11672. }
  11673. #endif
  11674. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  11675. x509->pkCurveOID = dCert->pkCurveOID;
  11676. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  11677. #ifdef WOLFSSL_DUAL_ALG_CERTS
  11678. /* Copy over alternative sig and pubkey. In this case we will allocate new
  11679. * buffers for them as we have no knowledge of when the DecodedCert is
  11680. * freed. */
  11681. if (dCert->extSapkiSet) {
  11682. x509->sapkiDer = (byte*)XMALLOC(dCert->sapkiLen, x509->heap,
  11683. DYNAMIC_TYPE_X509_EXT);
  11684. if (x509->sapkiDer != NULL) {
  11685. XMEMCPY(x509->sapkiDer, dCert->sapkiDer, dCert->sapkiLen);
  11686. x509->sapkiLen = dCert->sapkiLen;
  11687. }
  11688. else {
  11689. ret = MEMORY_E;
  11690. }
  11691. }
  11692. if (dCert->extAltSigAlgSet) {
  11693. x509->altSigAlgDer = (byte*)XMALLOC(dCert->altSigAlgLen, x509->heap,
  11694. DYNAMIC_TYPE_X509_EXT);
  11695. if (x509->altSigAlgDer != NULL) {
  11696. XMEMCPY(x509->altSigAlgDer, dCert->altSigAlgDer,
  11697. dCert->altSigAlgLen);
  11698. x509->altSigAlgLen = dCert->altSigAlgLen;
  11699. }
  11700. else {
  11701. ret = MEMORY_E;
  11702. }
  11703. }
  11704. if (dCert->extAltSigValSet) {
  11705. x509->altSigValDer = (byte*)XMALLOC(dCert->altSigValLen, x509->heap,
  11706. DYNAMIC_TYPE_X509_EXT);
  11707. if (x509->altSigValDer != NULL) {
  11708. XMEMCPY(x509->altSigValDer, dCert->altSigValDer,
  11709. dCert->altSigValLen);
  11710. x509->altSigValLen = dCert->altSigValLen;
  11711. }
  11712. else {
  11713. ret = MEMORY_E;
  11714. }
  11715. }
  11716. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  11717. return ret;
  11718. }
  11719. #endif /* KEEP_PEER_CERT || SESSION_CERTS */
  11720. #if defined(WOLFSSL_ACERT)
  11721. /* Copy a DecodedAcert structure to an X509_ACERT.
  11722. *
  11723. * @param [out] x509 the dst X509 acert structure
  11724. * @param [in] dAcert the src decoded acert structure
  11725. *
  11726. * @return 0 on success
  11727. * @return < 0 on error
  11728. * */
  11729. int CopyDecodedAcertToX509(WOLFSSL_X509_ACERT* x509, DecodedAcert* dAcert)
  11730. {
  11731. int ret = 0;
  11732. if (x509 == NULL || dAcert == NULL) {
  11733. return BAD_FUNC_ARG;
  11734. }
  11735. /* Copy version and serial number. */
  11736. x509->version = dAcert->version + 1;
  11737. XMEMCPY(x509->serial, dAcert->serial, EXTERNAL_SERIAL_SIZE);
  11738. x509->serialSz = dAcert->serialSz;
  11739. if (dAcert->holderSerialSz > 0) {
  11740. /* This ACERT Holder field had a serial number. Copy it. */
  11741. XMEMCPY(x509->holderSerial, dAcert->holderSerial,
  11742. dAcert->holderSerialSz);
  11743. x509->holderSerialSz = dAcert->holderSerialSz;
  11744. }
  11745. /* Copy before and after dates. */
  11746. {
  11747. int minSz = 0;
  11748. if (dAcert->beforeDateLen > 0) {
  11749. minSz = (int)min(dAcert->beforeDate[1], MAX_DATE_SZ);
  11750. x509->notBefore.type = dAcert->beforeDate[0];
  11751. x509->notBefore.length = minSz;
  11752. XMEMCPY(x509->notBefore.data, &dAcert->beforeDate[2], minSz);
  11753. }
  11754. else {
  11755. x509->notBefore.length = 0;
  11756. }
  11757. if (dAcert->afterDateLen > 0) {
  11758. minSz = (int)min(dAcert->afterDate[1], MAX_DATE_SZ);
  11759. x509->notAfter.type = dAcert->afterDate[0];
  11760. x509->notAfter.length = minSz;
  11761. XMEMCPY(x509->notAfter.data, &dAcert->afterDate[2], minSz);
  11762. }
  11763. else {
  11764. x509->notAfter.length = 0;
  11765. }
  11766. }
  11767. /* Copy the signature. */
  11768. if (dAcert->signature != NULL && dAcert->sigLength != 0 &&
  11769. dAcert->sigLength <= MAX_ENCODED_SIG_SZ) {
  11770. x509->sig.buffer = (byte*)XMALLOC(
  11771. dAcert->sigLength, x509->heap, DYNAMIC_TYPE_SIGNATURE);
  11772. if (x509->sig.buffer == NULL) {
  11773. ret = MEMORY_E;
  11774. }
  11775. else {
  11776. XMEMCPY(x509->sig.buffer, dAcert->signature, dAcert->sigLength);
  11777. x509->sig.length = dAcert->sigLength;
  11778. x509->sigOID = (int)dAcert->signatureOID;
  11779. }
  11780. }
  11781. /* if der contains original source buffer then store for potential
  11782. * retrieval */
  11783. if (dAcert->source != NULL && dAcert->maxIdx > 0) {
  11784. if (AllocDer(&x509->derCert, dAcert->maxIdx, CERT_TYPE, x509->heap)
  11785. == 0) {
  11786. XMEMCPY(x509->derCert->buffer, dAcert->source, dAcert->maxIdx);
  11787. }
  11788. else {
  11789. ret = MEMORY_E;
  11790. }
  11791. }
  11792. /* Copy holder and att cert issuer names if present. */
  11793. if (CopyAltNames(&x509->holderIssuerName, dAcert->holderIssuerName,
  11794. ASN_DIR_TYPE, x509->heap) != 0) {
  11795. return MEMORY_E;
  11796. }
  11797. if (CopyAltNames(&x509->holderEntityName, dAcert->holderEntityName,
  11798. ASN_DIR_TYPE, x509->heap) != 0) {
  11799. return MEMORY_E;
  11800. }
  11801. if (CopyAltNames(&x509->AttCertIssuerName, dAcert->AttCertIssuerName,
  11802. ASN_DIR_TYPE, x509->heap) != 0) {
  11803. return MEMORY_E;
  11804. }
  11805. if (dAcert->rawAttr && dAcert->rawAttrLen > 0) {
  11806. /* Allocate space for the raw Attributes field, then copy it in. */
  11807. x509->rawAttr = (byte*)XMALLOC(dAcert->rawAttrLen, x509->heap,
  11808. DYNAMIC_TYPE_X509_EXT);
  11809. if (x509->rawAttr != NULL) {
  11810. XMEMCPY(x509->rawAttr, dAcert->rawAttr, dAcert->rawAttrLen);
  11811. x509->rawAttrLen = dAcert->rawAttrLen;
  11812. }
  11813. else {
  11814. ret = MEMORY_E;
  11815. }
  11816. }
  11817. return ret;
  11818. }
  11819. #endif /* WOLFSSL_ACERT */
  11820. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
  11821. (defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) && !defined(WOLFSSL_NO_TLS12))
  11822. static int ProcessCSR(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  11823. word32 status_length)
  11824. {
  11825. int ret = 0;
  11826. OcspRequest* request;
  11827. #ifdef WOLFSSL_SMALL_STACK
  11828. CertStatus* status;
  11829. OcspEntry* single;
  11830. OcspResponse* response;
  11831. #else
  11832. CertStatus status[1];
  11833. OcspEntry single[1];
  11834. OcspResponse response[1];
  11835. #endif
  11836. WOLFSSL_ENTER("ProcessCSR");
  11837. do {
  11838. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  11839. if (ssl->status_request) {
  11840. request = (OcspRequest*)TLSX_CSR_GetRequest(ssl->extensions);
  11841. ssl->status_request = 0;
  11842. break;
  11843. }
  11844. #endif
  11845. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  11846. if (ssl->status_request_v2) {
  11847. request = (OcspRequest*)TLSX_CSR2_GetRequest(ssl->extensions,
  11848. WOLFSSL_CSR2_OCSP, 0);
  11849. ssl->status_request_v2 = 0;
  11850. break;
  11851. }
  11852. #endif
  11853. return BUFFER_ERROR;
  11854. } while(0);
  11855. if (request == NULL)
  11856. return BAD_CERTIFICATE_STATUS_ERROR; /* not expected */
  11857. #ifdef WOLFSSL_SMALL_STACK
  11858. status = (CertStatus*)XMALLOC(sizeof(CertStatus), ssl->heap,
  11859. DYNAMIC_TYPE_OCSP_STATUS);
  11860. single = (OcspEntry*)XMALLOC(sizeof(OcspEntry), ssl->heap,
  11861. DYNAMIC_TYPE_OCSP_ENTRY);
  11862. response = (OcspResponse*)XMALLOC(sizeof(OcspResponse), ssl->heap,
  11863. DYNAMIC_TYPE_OCSP_REQUEST);
  11864. if (status == NULL || single == NULL || response == NULL) {
  11865. XFREE(status, ssl->heap, DYNAMIC_TYPE_OCSP_STATUS);
  11866. XFREE(single, ssl->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  11867. XFREE(response, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  11868. return MEMORY_ERROR;
  11869. }
  11870. #endif
  11871. InitOcspResponse(response, single, status, input +*inOutIdx, status_length, ssl->heap);
  11872. if (OcspResponseDecode(response, SSL_CM(ssl), ssl->heap, 0) != 0)
  11873. ret = BAD_CERTIFICATE_STATUS_ERROR;
  11874. else if (CompareOcspReqResp(request, response) != 0)
  11875. ret = BAD_CERTIFICATE_STATUS_ERROR;
  11876. else if (response->responseStatus != OCSP_SUCCESSFUL)
  11877. ret = BAD_CERTIFICATE_STATUS_ERROR;
  11878. else if (response->single->status->status == CERT_REVOKED)
  11879. ret = OCSP_CERT_REVOKED;
  11880. else if (response->single->status->status != CERT_GOOD)
  11881. ret = BAD_CERTIFICATE_STATUS_ERROR;
  11882. else {
  11883. XMEMCPY(ssl->ocspProducedDate, response->producedDate, sizeof ssl->ocspProducedDate);
  11884. ssl->ocspProducedDateFormat = response->producedDateFormat;
  11885. }
  11886. *inOutIdx += status_length;
  11887. FreeOcspResponse(response);
  11888. #ifdef WOLFSSL_SMALL_STACK
  11889. XFREE(status, ssl->heap, DYNAMIC_TYPE_OCSP_STATUS);
  11890. XFREE(single, ssl->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  11891. XFREE(response, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  11892. #endif
  11893. WOLFSSL_LEAVE("ProcessCSR", ret);
  11894. return ret;
  11895. }
  11896. #endif
  11897. #ifdef HAVE_PK_CALLBACKS
  11898. #ifdef HAVE_ECC
  11899. static int SigPkCbEccVerify(const unsigned char* sig, unsigned int sigSz,
  11900. const unsigned char* hash, unsigned int hashSz,
  11901. const unsigned char* keyDer, unsigned int keySz,
  11902. int* result, void* ctx)
  11903. {
  11904. int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
  11905. WOLFSSL* ssl = (WOLFSSL*)ctx;
  11906. if (ssl && ssl->ctx->EccVerifyCb) {
  11907. ret = ssl->ctx->EccVerifyCb(ssl, sig, sigSz, hash, hashSz,
  11908. keyDer, keySz, result, ssl->EccVerifyCtx);
  11909. }
  11910. return ret;
  11911. }
  11912. #endif
  11913. #ifndef NO_RSA
  11914. static int SigPkCbRsaVerify(unsigned char* sig, unsigned int sigSz,
  11915. unsigned char** out, const unsigned char* keyDer, unsigned int keySz,
  11916. void* ctx)
  11917. {
  11918. int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
  11919. WOLFSSL* ssl = (WOLFSSL*)ctx;
  11920. if (ssl && ssl->ctx->RsaVerifyCb) {
  11921. ret = ssl->ctx->RsaVerifyCb(ssl, sig, sigSz, out, keyDer, keySz,
  11922. ssl->RsaVerifyCtx);
  11923. }
  11924. return ret;
  11925. }
  11926. #endif
  11927. int InitSigPkCb(WOLFSSL* ssl, SignatureCtx* sigCtx)
  11928. {
  11929. if (ssl == NULL || sigCtx == NULL)
  11930. return BAD_FUNC_ARG;
  11931. /* only setup the verify callback if a PK is set */
  11932. #ifdef HAVE_ECC
  11933. #if defined(WOLFSSL_RENESAS_FSPSM_TLS) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  11934. sigCtx->pkCbEcc = Renesas_cmn_SigPkCbEccVerify;
  11935. sigCtx->pkCtxEcc = (void*)&sigCtx->CertAtt;
  11936. (void)SigPkCbEccVerify;
  11937. #else
  11938. if (ssl->ctx->EccVerifyCb) {
  11939. sigCtx->pkCbEcc = SigPkCbEccVerify;
  11940. sigCtx->pkCtxEcc = ssl;
  11941. }
  11942. #endif
  11943. #endif
  11944. #ifndef NO_RSA
  11945. /* only setup the verify callback if a PK is set */
  11946. #if defined(WOLFSSL_RENESAS_FSPSM_TLS) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  11947. sigCtx->pkCbRsa = Renesas_cmn_SigPkCbRsaVerify;
  11948. sigCtx->pkCtxRsa = (void*)&sigCtx->CertAtt;
  11949. (void)SigPkCbRsaVerify;
  11950. #else
  11951. if (ssl->ctx->RsaVerifyCb) {
  11952. sigCtx->pkCbRsa = SigPkCbRsaVerify;
  11953. sigCtx->pkCtxRsa = ssl;
  11954. }
  11955. #endif
  11956. #endif
  11957. return 0;
  11958. }
  11959. #endif /* HAVE_PK_CALLBACKS */
  11960. #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  11961. void DoCertFatalAlert(WOLFSSL* ssl, int ret)
  11962. {
  11963. int alertWhy;
  11964. if (ssl == NULL || ret == 0) {
  11965. return;
  11966. }
  11967. WOLFSSL_ERROR(ret);
  11968. /* Determine alert reason */
  11969. alertWhy = bad_certificate;
  11970. if (ret == WC_NO_ERR_TRACE(ASN_AFTER_DATE_E) ||
  11971. ret == WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E)) {
  11972. alertWhy = certificate_expired;
  11973. }
  11974. else if (ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E) ||
  11975. ret == WC_NO_ERR_TRACE(ASN_PATHLEN_INV_E) ||
  11976. ret == WC_NO_ERR_TRACE(ASN_PATHLEN_SIZE_E)) {
  11977. alertWhy = unknown_ca;
  11978. }
  11979. #ifdef OPENSSL_EXTRA
  11980. else if (ret == WC_NO_ERR_TRACE(CRL_CERT_REVOKED)) {
  11981. alertWhy = certificate_revoked;
  11982. }
  11983. #endif
  11984. #if defined(HAVE_RPK)
  11985. else if (ret == WC_NO_ERR_TRACE(UNSUPPORTED_CERTIFICATE)) {
  11986. alertWhy = unsupported_certificate;
  11987. }
  11988. #endif /* HAVE_RPK */
  11989. else if (ret == WC_NO_ERR_TRACE(NO_PEER_CERT)) {
  11990. #ifdef WOLFSSL_TLS13
  11991. if (ssl->options.tls1_3) {
  11992. alertWhy = certificate_required;
  11993. }
  11994. else
  11995. #endif
  11996. {
  11997. alertWhy = handshake_failure;
  11998. }
  11999. }
  12000. /* send fatal alert and mark connection closed */
  12001. SendAlert(ssl, alert_fatal, alertWhy); /* try to send */
  12002. ssl->options.isClosed = 1;
  12003. }
  12004. int SetupStoreCtxCallback(WOLFSSL_X509_STORE_CTX** store_pt,
  12005. WOLFSSL* ssl, WOLFSSL_CERT_MANAGER* cm, ProcPeerCertArgs* args,
  12006. int cert_err, void* heap, int* x509Free)
  12007. {
  12008. WOLFSSL_X509_STORE_CTX* store = NULL;
  12009. char* domain = NULL;
  12010. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  12011. WOLFSSL_X509* x509 = NULL;
  12012. #endif
  12013. *x509Free = 0;
  12014. store = wolfSSL_X509_STORE_CTX_new_ex(heap);
  12015. if (store == NULL)
  12016. goto mem_error;
  12017. domain = (char*)XMALLOC(ASN_NAME_MAX, heap, DYNAMIC_TYPE_STRING);
  12018. if (domain == NULL)
  12019. goto mem_error;
  12020. domain[0] = '\0';
  12021. /* build subject CN as string to return in store */
  12022. if (args->dCertInit && args->dCert && args->dCert->subjectCN) {
  12023. int subjectCNLen = args->dCert->subjectCNLen;
  12024. if (subjectCNLen > ASN_NAME_MAX-1)
  12025. subjectCNLen = ASN_NAME_MAX-1;
  12026. if (subjectCNLen > 0) {
  12027. XMEMCPY(domain, args->dCert->subjectCN, subjectCNLen);
  12028. domain[subjectCNLen] = '\0';
  12029. }
  12030. }
  12031. #ifndef OPENSSL_COMPATIBLE_DEFAULTS
  12032. store->error = cert_err;
  12033. #else
  12034. store->error = GetX509Error(cert_err);
  12035. #endif
  12036. store->error_depth = args->certIdx;
  12037. store->discardSessionCerts = 0;
  12038. store->domain = domain;
  12039. if (ssl != NULL) {
  12040. if (ssl->verifyCbCtx != NULL) {
  12041. /* Use the WOLFSSL user context if set */
  12042. store->userCtx = ssl->verifyCbCtx;
  12043. }
  12044. else {
  12045. /* Else use the WOLFSSL_CTX user context */
  12046. store->userCtx = ssl->ctx->verifyCbCtx;
  12047. }
  12048. }
  12049. else {
  12050. store->userCtx = cm;
  12051. }
  12052. store->certs = args->certs;
  12053. store->totalCerts = args->totalCerts;
  12054. #if defined(HAVE_EX_DATA) && \
  12055. (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL))
  12056. if (wolfSSL_CRYPTO_set_ex_data(&store->ex_data, 0, ssl)
  12057. != WOLFSSL_SUCCESS) {
  12058. WOLFSSL_MSG("Failed to store ssl context in WOLFSSL_X509_STORE_CTX");
  12059. }
  12060. #endif
  12061. if (ssl != NULL) {
  12062. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
  12063. store->store = SSL_STORE(ssl);
  12064. #if defined(OPENSSL_EXTRA)
  12065. store->depth = args->count;
  12066. /* Overwrite with non-default param values in SSL */
  12067. if (ssl->param) {
  12068. if (ssl->param->check_time)
  12069. store->param->check_time = ssl->param->check_time;
  12070. if (ssl->param->flags)
  12071. store->param->flags = ssl->param->flags;
  12072. #ifdef WOLFSSL_LOCAL_X509_STORE
  12073. else if (SSL_STORE(ssl) && SSL_STORE(ssl)->param &&
  12074. SSL_STORE(ssl)->param->flags)
  12075. store->param->flags = SSL_STORE(ssl)->param->flags;
  12076. #endif
  12077. if (ssl->param->hostName[0])
  12078. XMEMCPY(store->param->hostName, ssl->param->hostName,
  12079. WOLFSSL_HOST_NAME_MAX);
  12080. }
  12081. #endif /* defined(OPENSSL_EXTRA) */
  12082. #endif /* defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)*/
  12083. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  12084. #ifdef KEEP_PEER_CERT
  12085. if (args->certIdx == 0) {
  12086. FreeX509(&ssl->peerCert);
  12087. InitX509(&ssl->peerCert, 0, ssl->heap);
  12088. if (CopyDecodedToX509(&ssl->peerCert, args->dCert) == 0)
  12089. WOLFSSL_MSG("Unable to copy to ssl->peerCert");
  12090. store->current_cert = &ssl->peerCert; /* use existing X509 */
  12091. }
  12092. else
  12093. #endif
  12094. {
  12095. x509 = wolfSSL_X509_new_ex(heap);
  12096. if (x509 == NULL)
  12097. goto mem_error;
  12098. if (CopyDecodedToX509(x509, args->dCert) == 0) {
  12099. store->current_cert = x509;
  12100. *x509Free = 1;
  12101. }
  12102. else {
  12103. goto mem_error;
  12104. }
  12105. }
  12106. #endif
  12107. #ifdef SESSION_CERTS
  12108. store->sesChain = &ssl->session->chain;
  12109. #endif
  12110. }
  12111. *store_pt = store;
  12112. return 0;
  12113. mem_error:
  12114. if (store != NULL)
  12115. wolfSSL_X509_STORE_CTX_free(store);
  12116. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  12117. if (x509 != NULL)
  12118. wolfSSL_X509_free(x509);
  12119. #endif
  12120. XFREE(domain, heap, DYNAMIC_TYPE_STRING);
  12121. return MEMORY_E;
  12122. }
  12123. void CleanupStoreCtxCallback(WOLFSSL_X509_STORE_CTX* store,
  12124. WOLFSSL* ssl, void* heap, int x509Free)
  12125. {
  12126. (void)ssl;
  12127. (void)x509Free;
  12128. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  12129. wolfSSL_sk_X509_pop_free(store->chain, NULL);
  12130. store->chain = NULL;
  12131. #endif
  12132. #ifdef SESSION_CERTS
  12133. if ((ssl != NULL) && (store->discardSessionCerts)) {
  12134. WOLFSSL_MSG("Verify callback requested discard sess certs");
  12135. ssl->session->chain.count = 0;
  12136. #ifdef WOLFSSL_ALT_CERT_CHAINS
  12137. ssl->session->altChain.count = 0;
  12138. #endif
  12139. }
  12140. #endif /* SESSION_CERTS */
  12141. XFREE(store->domain, heap, DYNAMIC_TYPE_STRING);
  12142. store->domain = NULL;
  12143. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  12144. if (x509Free)
  12145. wolfSSL_X509_free(store->current_cert);
  12146. store->current_cert = NULL;
  12147. #endif
  12148. wolfSSL_X509_STORE_CTX_free(store);
  12149. }
  12150. /* WOLFSSL_ALWAYS_VERIFY_CB: Use verify callback for success or failure cases */
  12151. /* WOLFSSL_VERIFY_CB_ALL_CERTS: Issue callback for all intermediate certificates */
  12152. /* Callback is issued for certificate presented in TLS Certificate (11) packet.
  12153. * The intermediates are done first then peer leaf cert last. Use the
  12154. * store->error_depth member to determine index (0=peer, >1 intermediates)
  12155. */
  12156. int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int cert_err,
  12157. ProcPeerCertArgs* args)
  12158. {
  12159. int verify_ok = 0, use_cb = 0, ret = cert_err;
  12160. void *heap;
  12161. if (cm == NULL) {
  12162. return BAD_FUNC_ARG;
  12163. }
  12164. heap = (ssl != NULL) ? ssl->heap : cm->heap;
  12165. /* Determine if verify was okay */
  12166. if (cert_err == 0) {
  12167. verify_ok = 1;
  12168. }
  12169. /* Determine if verify callback should be used */
  12170. if (cert_err != 0) {
  12171. if ((ssl != NULL) && (!ssl->options.verifyNone)) {
  12172. use_cb = 1; /* always report errors */
  12173. }
  12174. }
  12175. #ifdef WOLFSSL_ALWAYS_VERIFY_CB
  12176. /* always use verify callback on peer leaf cert */
  12177. if (args->certIdx == 0) {
  12178. use_cb = 1;
  12179. }
  12180. #endif
  12181. #ifdef WOLFSSL_VERIFY_CB_ALL_CERTS
  12182. /* perform verify callback on other intermediate certs (not just peer) */
  12183. if (args->certIdx > 0) {
  12184. use_cb = 1;
  12185. }
  12186. #endif
  12187. #if defined(OPENSSL_EXTRA)
  12188. /* Perform domain and IP check only for the leaf certificate */
  12189. if (args->certIdx == 0) {
  12190. /* perform domain name check on the peer certificate */
  12191. if (args->dCertInit && args->dCert && (ssl != NULL) &&
  12192. ssl->param && ssl->param->hostName[0]) {
  12193. /* If altNames names is present, then subject common name is ignored */
  12194. if (args->dCert->altNames != NULL) {
  12195. if (CheckForAltNames(args->dCert, ssl->param->hostName,
  12196. (word32)XSTRLEN(ssl->param->hostName), NULL) != 1) {
  12197. if (cert_err == 0) {
  12198. ret = DOMAIN_NAME_MISMATCH;
  12199. WOLFSSL_ERROR_VERBOSE(ret);
  12200. }
  12201. }
  12202. }
  12203. #ifndef WOLFSSL_HOSTNAME_VERIFY_ALT_NAME_ONLY
  12204. else {
  12205. if (args->dCert->subjectCN) {
  12206. if (MatchDomainName(
  12207. args->dCert->subjectCN,
  12208. args->dCert->subjectCNLen,
  12209. ssl->param->hostName,
  12210. (word32)XSTRLEN(ssl->param->hostName)) == 0) {
  12211. if (cert_err == 0) {
  12212. ret = DOMAIN_NAME_MISMATCH;
  12213. WOLFSSL_ERROR_VERBOSE(ret);
  12214. }
  12215. }
  12216. }
  12217. }
  12218. #else
  12219. else {
  12220. if (cert_err == 0) {
  12221. ret = DOMAIN_NAME_MISMATCH;
  12222. WOLFSSL_ERROR_VERBOSE(ret);
  12223. }
  12224. }
  12225. #endif /* !WOLFSSL_HOSTNAME_VERIFY_ALT_NAME_ONLY */
  12226. }
  12227. /* perform IP address check on the peer certificate */
  12228. if ((args->dCertInit != 0) && (args->dCert != NULL) && (ssl != NULL) &&
  12229. (ssl->param != NULL) && (XSTRLEN(ssl->param->ipasc) > 0)) {
  12230. if (CheckIPAddr(args->dCert, ssl->param->ipasc) != 0) {
  12231. if (cert_err == 0) {
  12232. ret = IPADDR_MISMATCH;
  12233. WOLFSSL_ERROR_VERBOSE(ret);
  12234. }
  12235. }
  12236. }
  12237. }
  12238. #endif
  12239. /* if verify callback has been set */
  12240. if ((use_cb && (ssl != NULL) && ((ssl->verifyCallback != NULL)
  12241. #ifdef OPENSSL_ALL
  12242. || (ssl->ctx->verifyCertCb != NULL)
  12243. #endif
  12244. #if defined(WOLFSSL_LOCAL_X509_STORE) && \
  12245. (defined(OPENSSL_ALL) || defined(WOLFSSL_QT))
  12246. || (SSL_STORE(ssl) != NULL && SSL_STORE(ssl)->verify_cb != NULL)
  12247. #endif
  12248. ))
  12249. #ifndef NO_WOLFSSL_CM_VERIFY
  12250. || (cm->verifyCallback != NULL)
  12251. #endif
  12252. ) {
  12253. int verifyFail = 0;
  12254. WOLFSSL_X509_STORE_CTX* store = NULL;
  12255. int x509Free = 0;
  12256. int setupRet = SetupStoreCtxCallback(&store, ssl, cm, args, cert_err,
  12257. heap, &x509Free);
  12258. if (setupRet != 0)
  12259. return setupRet;
  12260. #ifndef NO_WOLFSSL_CM_VERIFY
  12261. /* non-zero return code indicates failure override */
  12262. if (cm->verifyCallback != NULL) {
  12263. store->userCtx = cm;
  12264. if (cm->verifyCallback(verify_ok, store)) {
  12265. if (cert_err != 0) {
  12266. WOLFSSL_MSG("Verify CM callback overriding error!");
  12267. ret = 0;
  12268. }
  12269. }
  12270. else {
  12271. verifyFail = 1;
  12272. }
  12273. }
  12274. #endif
  12275. if (ssl != NULL) {
  12276. #ifdef OPENSSL_ALL
  12277. /* non-zero return code indicates failure override */
  12278. if (ssl->ctx->verifyCertCb) {
  12279. if (ssl->ctx->verifyCertCb(store, ssl->ctx->verifyCertCbArg)) {
  12280. if (cert_err != 0) {
  12281. WOLFSSL_MSG("Verify Cert callback overriding error!");
  12282. ret = 0;
  12283. }
  12284. }
  12285. else {
  12286. verifyFail = 1;
  12287. }
  12288. }
  12289. #endif
  12290. /* non-zero return code indicates failure override */
  12291. if (ssl->verifyCallback) {
  12292. if (ssl->verifyCallback(verify_ok, store)) {
  12293. if (cert_err != 0) {
  12294. WOLFSSL_MSG("Verify callback overriding error!");
  12295. ret = 0;
  12296. }
  12297. }
  12298. else {
  12299. verifyFail = 1;
  12300. }
  12301. }
  12302. #if defined(WOLFSSL_LOCAL_X509_STORE) && \
  12303. (defined(OPENSSL_ALL) || defined(WOLFSSL_QT))
  12304. if (SSL_STORE(ssl) != NULL && SSL_STORE(ssl)->verify_cb != NULL) {
  12305. if (SSL_STORE(ssl)->verify_cb(verify_ok, store)) {
  12306. if (cert_err != 0) {
  12307. WOLFSSL_MSG("Store Verify callback overriding error!");
  12308. ret = 0;
  12309. }
  12310. }
  12311. else {
  12312. verifyFail = 1;
  12313. }
  12314. }
  12315. #endif
  12316. }
  12317. if (verifyFail) {
  12318. /* induce error if one not present */
  12319. if (cert_err == 0) {
  12320. ret = VERIFY_CERT_ERROR;
  12321. WOLFSSL_ERROR_VERBOSE(ret);
  12322. }
  12323. /* mark as verify error */
  12324. args->verifyErr = 1;
  12325. }
  12326. CleanupStoreCtxCallback(store, ssl, heap, x509Free);
  12327. }
  12328. (void)heap;
  12329. return ret;
  12330. }
  12331. #ifdef HAVE_CRL
  12332. void DoCrlCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl,
  12333. ProcPeerCertArgs* args, int* outRet)
  12334. {
  12335. #if defined(WOLFSSL_LOCAL_X509_STORE) && \
  12336. (defined(OPENSSL_ALL) || defined(WOLFSSL_QT))
  12337. int ret = 0;
  12338. void* heap = (ssl != NULL) ? ssl->heap : cm->heap;
  12339. WOLFSSL_X509_STORE* cert_store = (ssl != NULL) ? SSL_STORE(ssl) : NULL;
  12340. if (cert_store != NULL && cert_store->get_crl_cb != NULL) {
  12341. WOLFSSL_CRL* userCrl = NULL;
  12342. WOLFSSL_X509_STORE_CTX* store = NULL;
  12343. int x509Free = 0;
  12344. ret = SetupStoreCtxCallback(&store, ssl, cm, args, 0, heap,
  12345. &x509Free);
  12346. if (ret != 0) {
  12347. *outRet = ret;
  12348. return;
  12349. }
  12350. ret = cert_store->get_crl_cb(store, &userCrl, store->current_cert);
  12351. if (ret == 1 && userCrl != NULL) {
  12352. /* Point to current cm to be able to verify CRL */
  12353. userCrl->cm = SSL_CM(ssl);
  12354. *outRet = CheckCertCRL(userCrl, args->dCert);
  12355. }
  12356. else
  12357. *outRet = CRL_MISSING;
  12358. if (userCrl != NULL)
  12359. wolfSSL_X509_CRL_free(userCrl);
  12360. CleanupStoreCtxCallback(store, ssl, heap, x509Free);
  12361. }
  12362. #else
  12363. (void)cm;
  12364. (void)ssl;
  12365. (void)args;
  12366. (void)outRet;
  12367. #endif
  12368. }
  12369. #endif
  12370. static void FreeProcPeerCertArgs(WOLFSSL* ssl, void* pArgs)
  12371. {
  12372. ProcPeerCertArgs* args = (ProcPeerCertArgs*)pArgs;
  12373. (void)ssl;
  12374. XFREE(args->certs, ssl->heap, DYNAMIC_TYPE_DER);
  12375. args->certs = NULL;
  12376. #ifdef WOLFSSL_TLS13
  12377. XFREE(args->exts, ssl->heap, DYNAMIC_TYPE_CERT_EXT);
  12378. args->exts = NULL;
  12379. #endif
  12380. if (args->dCert) {
  12381. if (args->dCertInit) {
  12382. FreeDecodedCert(args->dCert);
  12383. args->dCertInit = 0;
  12384. }
  12385. XFREE(args->dCert, ssl->heap, DYNAMIC_TYPE_DCERT);
  12386. args->dCert = NULL;
  12387. }
  12388. }
  12389. #if defined(OPENSSL_ALL) && defined(WOLFSSL_CERT_GEN) && \
  12390. (defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT)) && \
  12391. !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) && \
  12392. !defined(NO_STDIO_FILESYSTEM)
  12393. /* load certificate file which has the form <hash>.(r)N[0..N] */
  12394. /* in the folder. */
  12395. /* (r), in the case of CRL file */
  12396. /* @param store a pointer to X509_STORE structure */
  12397. /* @param issuer a pointer to X509_NAME that presents an issuer */
  12398. /* @param type X509_LU_X509 or X509_LU_CRL */
  12399. /* @return WOLFSSL_SUCCESS on successful, otherwise WOLFSSL_FAILURE */
  12400. int LoadCertByIssuer(WOLFSSL_X509_STORE* store, X509_NAME* issuer, int type)
  12401. {
  12402. const int MAX_SUFFIX = 10;/* The number comes from CA_TABLE_SIZE=10 */
  12403. int ret = WOLFSSL_SUCCESS;
  12404. WOLFSSL_X509_LOOKUP* lookup;
  12405. WOLFSSL_BY_DIR_entry* entry;
  12406. WOLFSSL_BY_DIR_HASH hash_tmp;
  12407. WOLFSSL_BY_DIR_HASH* ph = NULL;
  12408. WOLFSSL_X509* x509;
  12409. unsigned long hash = 0;
  12410. char* filename = NULL;
  12411. const char* post = "";
  12412. byte* pbuf = NULL;
  12413. int len, num, i, idx;
  12414. int suffix = 0;
  12415. int retHash = NOT_COMPILED_IN;
  12416. byte dgt[WC_MAX_DIGEST_SIZE];
  12417. WOLFSSL_ENTER("LoadCertByIssuer");
  12418. /* sanity check */
  12419. if (store == NULL || issuer == NULL || (type != X509_LU_X509 && type != X509_LU_CRL)) {
  12420. return WOLFSSL_FAILURE;
  12421. }
  12422. lookup = &store->lookup;
  12423. if (lookup->dirs == NULL || lookup->type != 1) {
  12424. return WOLFSSL_FAILURE;
  12425. }
  12426. len = wolfSSL_i2d_X509_NAME_canon(issuer, &pbuf);
  12427. if (len > 0) {
  12428. #if defined(NO_SHA) && !defined(NO_SHA256)
  12429. retHash = wc_Sha256Hash((const byte*)pbuf, len, dgt);
  12430. #elif !defined(NO_SHA)
  12431. retHash = wc_ShaHash((const byte*)pbuf, (word32)len, dgt);
  12432. #endif
  12433. if (retHash == 0) {
  12434. /* 4 bytes in little endian as unsigned long */
  12435. hash = (((unsigned long)dgt[3] << 24) |
  12436. ((unsigned long)dgt[2] << 16) |
  12437. ((unsigned long)dgt[1] << 8) |
  12438. ((unsigned long)dgt[0]));
  12439. } else {
  12440. WOLFSSL_MSG("failed hash operation");
  12441. return WOLFSSL_FAILURE;
  12442. }
  12443. wolfSSL_OPENSSL_free(pbuf);
  12444. }
  12445. /* try to load each hashed name file in path */
  12446. #if !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR)
  12447. if (type == X509_LU_CRL) {
  12448. post = "r";
  12449. }
  12450. num = wolfSSL_sk_BY_DIR_entry_num(lookup->dirs->dir_entry);
  12451. for (i=0; i<num; i++) {
  12452. entry = wolfSSL_sk_BY_DIR_entry_value(lookup->dirs->dir_entry, i);
  12453. if (type == X509_LU_CRL && entry->hashes != NULL &&
  12454. wolfSSL_sk_BY_DIR_HASH_num(entry->hashes) > 0) {
  12455. /* lock the list */
  12456. if (wc_LockMutex(&lookup->dirs->lock) != 0) {
  12457. WOLFSSL_MSG("wc_LockMutex cdir Lock error");
  12458. return BAD_MUTEX_E;
  12459. }
  12460. hash_tmp.hash_value = hash;
  12461. idx = wolfSSL_sk_BY_DIR_HASH_find(entry->hashes, &hash_tmp);
  12462. if (idx >= 0) {
  12463. WOLFSSL_MSG("find hashed CRL in list");
  12464. ph = wolfSSL_sk_BY_DIR_HASH_value(entry->hashes, idx);
  12465. suffix = ph->last_suffix;
  12466. } else {
  12467. ph = NULL;
  12468. suffix = 0;
  12469. }
  12470. wc_UnLockMutex(&lookup->dirs->lock);
  12471. }
  12472. /* Additional buffer length for file name memory allocation : */
  12473. /* / <hashvalue>.(r)N\0 */
  12474. /*|1| 8 |1|1|1|1| => 13 */
  12475. len = (int)XSTRLEN(entry->dir_name) + 13;
  12476. XFREE(filename, NULL, DYNAMIC_TYPE_OPENSSL);
  12477. filename = (char*)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL);
  12478. if (filename == NULL) {
  12479. WOLFSSL_MSG("memory allocation error");
  12480. return MEMORY_E;
  12481. }
  12482. /* set as FAILURE, if successfully loading cert of CRL, this becomes */
  12483. /* WOLFSSL_SUCCESS */
  12484. ret = WOLFSSL_FAILURE;
  12485. for (; suffix < MAX_SUFFIX; suffix++) {
  12486. /* /folder-path/<hash>.(r)N[0..9] */
  12487. if (XSNPRINTF(filename, (size_t)len, "%s/%08lx.%s%d", entry->dir_name,
  12488. hash, post, suffix)
  12489. >= len)
  12490. {
  12491. WOLFSSL_MSG("buffer overrun in LoadCertByIssuer");
  12492. ret = BUFFER_E;
  12493. break;
  12494. }
  12495. if(wc_FileExists(filename) == 0/*0 file exists */) {
  12496. if (type == X509_LU_X509) {
  12497. x509 = wolfSSL_X509_load_certificate_file(filename,
  12498. WOLFSSL_FILETYPE_PEM);
  12499. if (x509 != NULL) {
  12500. ret = wolfSSL_X509_STORE_add_cert(store, x509);
  12501. wolfSSL_X509_free(x509);
  12502. } else {
  12503. WOLFSSL_MSG("failed to load certificate");
  12504. ret = WOLFSSL_FAILURE;
  12505. break;
  12506. }
  12507. }
  12508. else if (type == X509_LU_CRL) {
  12509. #if defined(HAVE_CRL)
  12510. ret = wolfSSL_X509_load_crl_file(&store->lookup, filename,
  12511. entry->dir_type);
  12512. if (ret != WOLFSSL_SUCCESS) {
  12513. WOLFSSL_MSG("failed to load CRL");
  12514. break;
  12515. }
  12516. #else
  12517. WOLFSSL_MSG("CRL is not supported");
  12518. ret = WOLFSSL_FAILURE;
  12519. break;
  12520. #endif /* HAVE_CRL */
  12521. }
  12522. } else
  12523. break;
  12524. }
  12525. if (ret != WOLFSSL_SUCCESS) {
  12526. WOLFSSL_MSG("not found file");
  12527. ret = WOLFSSL_FAILURE;
  12528. } else {
  12529. if (type == X509_LU_CRL) {
  12530. if (wc_LockMutex(&lookup->dirs->lock) != 0) {
  12531. WOLFSSL_MSG("wc_LockMutex cdir Lock error");
  12532. XFREE(filename, NULL, DYNAMIC_TYPE_OPENSSL);
  12533. WOLFSSL_ERROR_VERBOSE(BAD_MUTEX_E);
  12534. return BAD_MUTEX_E;
  12535. }
  12536. if (ph == NULL) {
  12537. ph = wolfSSL_BY_DIR_HASH_new();
  12538. if (ph == NULL) {
  12539. WOLFSSL_MSG("failed to allocate hash stack");
  12540. ret = WOLFSSL_FAILURE;
  12541. } else {
  12542. ph->hash_value = hash;
  12543. ph->last_suffix = suffix;
  12544. ret = wolfSSL_sk_BY_DIR_HASH_push(entry->hashes, ph) > 0
  12545. ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
  12546. }
  12547. }
  12548. wc_UnLockMutex(&lookup->dirs->lock);
  12549. }
  12550. }
  12551. XFREE(filename, NULL, DYNAMIC_TYPE_OPENSSL);
  12552. filename = NULL;
  12553. }
  12554. #else
  12555. (void) type;
  12556. (void) ret;
  12557. (void) x509;
  12558. (void) filename;
  12559. (void) suffix;
  12560. (void) num;
  12561. (void) i;
  12562. ret = WOLFSSL_NOT_IMPLEMENTED;
  12563. #endif
  12564. WOLFSSL_LEAVE("LoadCertByIssuer", ret);
  12565. return ret;
  12566. }
  12567. #endif
  12568. static int ProcessPeerCertParse(WOLFSSL* ssl, ProcPeerCertArgs* args,
  12569. int certType, int verify, byte** pSubjectHash, int* pAlreadySigner)
  12570. {
  12571. int ret = 0;
  12572. buffer* cert;
  12573. byte* subjectHash = NULL;
  12574. int alreadySigner = 0;
  12575. Signer *extraSigners = NULL;
  12576. #if defined(HAVE_RPK)
  12577. int cType;
  12578. #endif
  12579. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  12580. int sigRet = 0;
  12581. #endif
  12582. if (ssl == NULL || args == NULL
  12583. #ifndef WOLFSSL_SMALL_CERT_VERIFY
  12584. || args->dCert == NULL
  12585. #endif
  12586. ) {
  12587. return BAD_FUNC_ARG;
  12588. }
  12589. PRAGMA_GCC_DIAG_PUSH
  12590. PRAGMA_GCC("GCC diagnostic ignored \"-Wstrict-overflow\"")
  12591. /* Surrounded in gcc pragma to avoid -Werror=strict-overflow when the
  12592. * compiler optimizes out the check and assumes no underflow. Keeping the
  12593. * check in place to handle multiple build configurations and future
  12594. * changes. */
  12595. /* check to make sure certificate index is valid */
  12596. if (args->certIdx > args->count)
  12597. return BUFFER_E;
  12598. PRAGMA_GCC_DIAG_POP
  12599. /* check if returning from non-blocking OCSP */
  12600. /* skip this section because cert is already initialized and parsed */
  12601. #ifdef WOLFSSL_NONBLOCK_OCSP
  12602. if (args->lastErr == WC_NO_ERR_TRACE(OCSP_WANT_READ)) {
  12603. args->lastErr = 0; /* clear error */
  12604. return 0;
  12605. }
  12606. #endif
  12607. #ifdef WOLFSSL_TRUST_PEER_CERT
  12608. /* we have trusted peer */
  12609. if (args->haveTrustPeer) {
  12610. return 0;
  12611. }
  12612. #endif
  12613. /* get certificate buffer */
  12614. cert = &args->certs[args->certIdx];
  12615. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  12616. if (verify == VERIFY) {
  12617. /* for small cert verify, release decoded cert during signature check to
  12618. reduce peak memory usage */
  12619. if (args->dCert != NULL) {
  12620. if (args->dCertInit) {
  12621. FreeDecodedCert(args->dCert);
  12622. args->dCertInit = 0;
  12623. }
  12624. XFREE(args->dCert, ssl->heap, DYNAMIC_TYPE_DCERT);
  12625. args->dCert = NULL;
  12626. }
  12627. /* perform cert parsing and signature check */
  12628. sigRet = wc_CheckCertSignature(cert->buffer, cert->length,
  12629. ssl->heap, SSL_CM(ssl));
  12630. /* fail on errors here after the ParseCertRelative call, so dCert is populated */
  12631. /* verify name only in ParseCertRelative below, signature check done */
  12632. verify = VERIFY_NAME;
  12633. }
  12634. #endif /* WOLFSSL_SMALL_CERT_VERIFY */
  12635. /* make sure the decoded cert structure is allocated and initialized */
  12636. if (!args->dCertInit
  12637. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  12638. || args->dCert == NULL
  12639. #endif
  12640. ) {
  12641. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  12642. if (args->dCert == NULL) {
  12643. args->dCert = (DecodedCert*)XMALLOC(
  12644. sizeof(DecodedCert), ssl->heap,
  12645. DYNAMIC_TYPE_DCERT);
  12646. if (args->dCert == NULL) {
  12647. return MEMORY_E;
  12648. }
  12649. }
  12650. #endif
  12651. InitDecodedCert(args->dCert, cert->buffer, cert->length, ssl->heap);
  12652. args->dCertInit = 1;
  12653. args->dCert->sigCtx.devId = ssl->devId;
  12654. #ifdef WOLFSSL_ASYNC_CRYPT
  12655. args->dCert->sigCtx.asyncCtx = ssl;
  12656. #endif
  12657. #ifdef HAVE_PK_CALLBACKS
  12658. /* setup the PK callback context */
  12659. ret = InitSigPkCb(ssl, &args->dCert->sigCtx);
  12660. if (ret != 0)
  12661. return ret;
  12662. #endif
  12663. }
  12664. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  12665. if (verify != NO_VERIFY && TLSX_CSR2_IsMulti(ssl->extensions)) {
  12666. extraSigners = TLSX_CSR2_GetPendingSigners(ssl->extensions);
  12667. }
  12668. #endif
  12669. /* Parse Certificate */
  12670. ret = ParseCertRelative(args->dCert, certType, verify, SSL_CM(ssl), extraSigners);
  12671. #if defined(HAVE_RPK)
  12672. /* if cert type has negotiated with peer, confirm the cert received has
  12673. * the same type.
  12674. */
  12675. if (ret == 0 ) {
  12676. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  12677. if (ssl->options.rpkState.received_ServerCertTypeCnt == 1) {
  12678. cType = ssl->options.rpkState.received_ServerCertTypes[0];
  12679. if ((cType == WOLFSSL_CERT_TYPE_RPK && !args->dCert->isRPK) ||
  12680. (cType == WOLFSSL_CERT_TYPE_X509 && args->dCert->isRPK)) {
  12681. /* cert type mismatch */
  12682. WOLFSSL_MSG("unsupported certificate type received");
  12683. ret = UNSUPPORTED_CERTIFICATE;
  12684. }
  12685. }
  12686. }
  12687. else if (ssl->options.side == WOLFSSL_SERVER_END) {
  12688. if (ssl->options.rpkState.received_ClientCertTypeCnt == 1) {
  12689. cType = ssl->options.rpkState.sending_ClientCertTypes[0];
  12690. if ((cType == WOLFSSL_CERT_TYPE_RPK && !args->dCert->isRPK) ||
  12691. (cType == WOLFSSL_CERT_TYPE_X509 && args->dCert->isRPK)) {
  12692. /* cert type mismatch */
  12693. WOLFSSL_MSG("unsupported certificate type received");
  12694. ret = UNSUPPORTED_CERTIFICATE;
  12695. }
  12696. }
  12697. }
  12698. }
  12699. #endif /* HAVE_RPK */
  12700. /* perform below checks for date failure cases */
  12701. if (ret == 0 ||
  12702. ret == WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E) ||
  12703. ret == WC_NO_ERR_TRACE(ASN_AFTER_DATE_E)) {
  12704. /* get subject and determine if already loaded */
  12705. #ifndef NO_SKID
  12706. if (args->dCert->extAuthKeyIdSet)
  12707. subjectHash = args->dCert->extSubjKeyId;
  12708. else
  12709. #endif
  12710. subjectHash = args->dCert->subjectHash;
  12711. alreadySigner = AlreadySigner(SSL_CM(ssl), subjectHash);
  12712. }
  12713. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  12714. /* get signature check failures from above */
  12715. if (ret == 0)
  12716. ret = sigRet;
  12717. #endif
  12718. if (pSubjectHash)
  12719. *pSubjectHash = subjectHash;
  12720. if (pAlreadySigner)
  12721. *pAlreadySigner = alreadySigner;
  12722. #ifdef WOLFSSL_ASYNC_CRYPT
  12723. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  12724. ret = wolfSSL_AsyncPush(ssl,
  12725. args->dCert->sigCtx.asyncDev);
  12726. }
  12727. #endif
  12728. #if defined(WOLFSSL_PUBLIC_ASN) && defined(HAVE_PK_CALLBACKS)
  12729. /* This block gives the callback a chance to process the peer cert.
  12730. * If there is no callback set or it returns NOT_COMPILED_IN, then the
  12731. * original return code is returned. */
  12732. if (ssl->ctx && ssl->ctx->ProcessPeerCertCb) {
  12733. int new_ret = ssl->ctx->ProcessPeerCertCb(ssl, args->dCert);
  12734. if (new_ret != WC_NO_ERR_TRACE(NOT_COMPILED_IN)) {
  12735. ret = new_ret;
  12736. }
  12737. }
  12738. #endif /* WOLFSSL_PUBLIC_ASN && HAVE_PK_CALLBACKS */
  12739. return ret;
  12740. }
  12741. /* Check key sizes for certs. Is redundant check since
  12742. ProcessBuffer also performs this check. */
  12743. static int ProcessPeerCertCheckKey(WOLFSSL* ssl, ProcPeerCertArgs* args)
  12744. {
  12745. int ret = 0;
  12746. if (ssl->options.verifyNone) {
  12747. return ret;
  12748. }
  12749. switch (args->dCert->keyOID) {
  12750. #ifndef NO_RSA
  12751. #ifdef WC_RSA_PSS
  12752. case RSAPSSk:
  12753. #endif
  12754. case RSAk:
  12755. if (ssl->options.minRsaKeySz < 0 ||
  12756. args->dCert->pubKeySize <
  12757. (word16)ssl->options.minRsaKeySz) {
  12758. WOLFSSL_MSG(
  12759. "RSA key size in cert chain error");
  12760. ret = RSA_KEY_SIZE_E;
  12761. WOLFSSL_ERROR_VERBOSE(ret);
  12762. }
  12763. break;
  12764. #endif /* !NO_RSA */
  12765. #ifdef HAVE_ECC
  12766. case ECDSAk:
  12767. if (ssl->options.minEccKeySz < 0 ||
  12768. args->dCert->pubKeySize <
  12769. (word16)ssl->options.minEccKeySz) {
  12770. WOLFSSL_MSG(
  12771. "ECC key size in cert chain error");
  12772. ret = ECC_KEY_SIZE_E;
  12773. WOLFSSL_ERROR_VERBOSE(ret);
  12774. }
  12775. break;
  12776. #endif /* HAVE_ECC */
  12777. #ifdef HAVE_ED25519
  12778. case ED25519k:
  12779. if (ssl->options.minEccKeySz < 0 ||
  12780. ED25519_KEY_SIZE < (word16)ssl->options.minEccKeySz) {
  12781. WOLFSSL_MSG(
  12782. "ECC key size in cert chain error");
  12783. ret = ECC_KEY_SIZE_E;
  12784. WOLFSSL_ERROR_VERBOSE(ret);
  12785. }
  12786. break;
  12787. #endif /* HAVE_ED25519 */
  12788. #ifdef HAVE_ED448
  12789. case ED448k:
  12790. if (ssl->options.minEccKeySz < 0 ||
  12791. ED448_KEY_SIZE < (word16)ssl->options.minEccKeySz) {
  12792. WOLFSSL_MSG(
  12793. "ECC key size in cert chain error");
  12794. ret = ECC_KEY_SIZE_E;
  12795. WOLFSSL_ERROR_VERBOSE(ret);
  12796. }
  12797. break;
  12798. #endif /* HAVE_ED448 */
  12799. #if defined(HAVE_FALCON)
  12800. case FALCON_LEVEL1k:
  12801. if (ssl->options.minFalconKeySz < 0 ||
  12802. FALCON_LEVEL1_KEY_SIZE < (word16)ssl->options.minFalconKeySz) {
  12803. WOLFSSL_MSG("Falcon key size in cert chain error");
  12804. ret = FALCON_KEY_SIZE_E;
  12805. WOLFSSL_ERROR_VERBOSE(ret);
  12806. }
  12807. break;
  12808. case FALCON_LEVEL5k:
  12809. if (ssl->options.minFalconKeySz < 0 ||
  12810. FALCON_LEVEL5_KEY_SIZE < (word16)ssl->options.minFalconKeySz) {
  12811. WOLFSSL_MSG("Falcon key size in cert chain error");
  12812. ret = FALCON_KEY_SIZE_E;
  12813. WOLFSSL_ERROR_VERBOSE(ret);
  12814. }
  12815. break;
  12816. #endif /* HAVE_FALCON */
  12817. #if defined(HAVE_DILITHIUM)
  12818. case DILITHIUM_LEVEL2k:
  12819. if (ssl->options.minDilithiumKeySz < 0 ||
  12820. DILITHIUM_LEVEL2_KEY_SIZE
  12821. < (word16)ssl->options.minDilithiumKeySz) {
  12822. WOLFSSL_MSG("Dilithium key size in cert chain error");
  12823. ret = DILITHIUM_KEY_SIZE_E;
  12824. }
  12825. break;
  12826. case DILITHIUM_LEVEL3k:
  12827. if (ssl->options.minDilithiumKeySz < 0 ||
  12828. DILITHIUM_LEVEL3_KEY_SIZE
  12829. < (word16)ssl->options.minDilithiumKeySz) {
  12830. WOLFSSL_MSG( "Dilithium key size in cert chain error");
  12831. ret = DILITHIUM_KEY_SIZE_E;
  12832. }
  12833. break;
  12834. case DILITHIUM_LEVEL5k:
  12835. if (ssl->options.minDilithiumKeySz < 0 ||
  12836. DILITHIUM_LEVEL5_KEY_SIZE
  12837. < (word16)ssl->options.minDilithiumKeySz) {
  12838. WOLFSSL_MSG("Dilithium key size in cert chain error");
  12839. ret = DILITHIUM_KEY_SIZE_E;
  12840. }
  12841. break;
  12842. #endif /* HAVE_DILITHIUM */
  12843. default:
  12844. WOLFSSL_MSG("Key size not checked");
  12845. /* key not being checked for size if not in
  12846. switch */
  12847. break;
  12848. }
  12849. return ret;
  12850. }
  12851. #ifdef HAVE_CRL
  12852. static int ProcessPeerCertsChainCRLCheck(WOLFSSL* ssl, ProcPeerCertArgs* args)
  12853. {
  12854. Signer* prev = NULL;
  12855. int ret = 0;
  12856. WOLFSSL_CERT_MANAGER* cm = SSL_CM(ssl);
  12857. Signer* ca = args->dCert->ca;
  12858. /* End loop if no more issuers found or if we have
  12859. * found a self signed cert (ca == prev) */
  12860. for (; ret == 0 && ca != NULL && ca != prev;
  12861. prev = ca, ca = GetCAByName(cm, ca->issuerNameHash)) {
  12862. ret = CheckCertCRL_ex(cm->crl, ca->issuerNameHash, NULL, 0,
  12863. ca->serialHash, NULL, 0, NULL);
  12864. if (ret != 0)
  12865. DoCrlCallback(cm, ssl, args, &ret);
  12866. if (ret != 0){
  12867. WOLFSSL_ERROR_VERBOSE(ret);
  12868. WOLFSSL_MSG("\tCRL check not ok");
  12869. break;
  12870. }
  12871. }
  12872. return ret;
  12873. }
  12874. #endif
  12875. int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  12876. word32 totalSz)
  12877. {
  12878. int ret = 0;
  12879. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  12880. ProcPeerCertArgs* args = NULL;
  12881. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  12882. #elif defined(WOLFSSL_SMALL_STACK)
  12883. ProcPeerCertArgs* args = NULL;
  12884. #else
  12885. ProcPeerCertArgs args[1];
  12886. #endif
  12887. byte* subjectHash = NULL;
  12888. int alreadySigner = 0;
  12889. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  12890. int addToPendingCAs = 0;
  12891. #endif
  12892. WOLFSSL_ENTER("ProcessPeerCerts");
  12893. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  12894. if (ssl->async == NULL) {
  12895. ssl->async = (struct WOLFSSL_ASYNC*)
  12896. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  12897. DYNAMIC_TYPE_ASYNC);
  12898. if (ssl->async == NULL)
  12899. ERROR_OUT(MEMORY_E, exit_ppc);
  12900. }
  12901. args = (ProcPeerCertArgs*)ssl->async->args;
  12902. #ifdef WOLFSSL_ASYNC_CRYPT
  12903. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  12904. if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
  12905. /* Check for error */
  12906. if (ret < 0)
  12907. goto exit_ppc;
  12908. }
  12909. else
  12910. #endif /* WOLFSSL_ASYNC_CRYPT */
  12911. #ifdef WOLFSSL_NONBLOCK_OCSP
  12912. if (ssl->error == WC_NO_ERR_TRACE(OCSP_WANT_READ)) {
  12913. /* Re-entry after non-blocking OCSP */
  12914. #ifdef WOLFSSL_ASYNC_CRYPT
  12915. /* if async operationg not pending, reset error code */
  12916. if (ret == WC_NO_ERR_TRACE(WC_NO_PENDING_E))
  12917. ret = 0;
  12918. #endif
  12919. }
  12920. else
  12921. #endif /* WOLFSSL_NONBLOCK_OCSP */
  12922. #elif defined(WOLFSSL_SMALL_STACK)
  12923. args = (ProcPeerCertArgs*)XMALLOC(
  12924. sizeof(ProcPeerCertArgs), ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  12925. if (args == NULL) {
  12926. ERROR_OUT(MEMORY_E, exit_ppc);
  12927. }
  12928. #endif /* WOLFSSL_ASYNC_CRYPT || WOLFSSL_NONBLOCK_OCSP */
  12929. {
  12930. /* Reset state */
  12931. ret = 0;
  12932. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  12933. XMEMSET(args, 0, sizeof(ProcPeerCertArgs));
  12934. args->idx = *inOutIdx;
  12935. args->begin = *inOutIdx;
  12936. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  12937. ssl->async->freeArgs = FreeProcPeerCertArgs;
  12938. #endif
  12939. }
  12940. switch (ssl->options.asyncState)
  12941. {
  12942. case TLS_ASYNC_BEGIN:
  12943. {
  12944. word32 listSz;
  12945. #ifdef WOLFSSL_CALLBACKS
  12946. if (ssl->hsInfoOn)
  12947. AddPacketName(ssl, "Certificate");
  12948. if (ssl->toInfoOn)
  12949. AddLateName("Certificate", &ssl->timeoutInfo);
  12950. #endif
  12951. #ifdef WOLFSSL_TLS13
  12952. if (ssl->options.tls1_3) {
  12953. byte ctxSz;
  12954. /* Certificate Request Context */
  12955. if ((args->idx - args->begin) + OPAQUE8_LEN > totalSz)
  12956. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  12957. ctxSz = *(input + args->idx);
  12958. args->idx++;
  12959. if ((args->idx - args->begin) + ctxSz > totalSz)
  12960. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  12961. #ifndef NO_WOLFSSL_CLIENT
  12962. /* Must be empty when received from server. */
  12963. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  12964. if (ctxSz != 0) {
  12965. WOLFSSL_ERROR_VERBOSE(INVALID_CERT_CTX_E);
  12966. ERROR_OUT(INVALID_CERT_CTX_E, exit_ppc);
  12967. }
  12968. }
  12969. #endif
  12970. #ifndef NO_WOLFSSL_SERVER
  12971. /* Must contain value sent in request. */
  12972. if (ssl->options.side == WOLFSSL_SERVER_END) {
  12973. if (ssl->options.handShakeState != HANDSHAKE_DONE &&
  12974. ctxSz != 0) {
  12975. WOLFSSL_ERROR_VERBOSE(INVALID_CERT_CTX_E);
  12976. ERROR_OUT(INVALID_CERT_CTX_E, exit_ppc);
  12977. }
  12978. else if (ssl->options.handShakeState == HANDSHAKE_DONE) {
  12979. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  12980. CertReqCtx* curr = ssl->certReqCtx;
  12981. CertReqCtx* prev = NULL;
  12982. while (curr != NULL) {
  12983. if ((ctxSz == curr->len) &&
  12984. XMEMCMP(&curr->ctx, input + args->idx, ctxSz)
  12985. == 0) {
  12986. if (prev != NULL)
  12987. prev->next = curr->next;
  12988. else
  12989. ssl->certReqCtx = curr->next;
  12990. XFREE(curr, ssl->heap,
  12991. DYNAMIC_TYPE_TMP_BUFFER);
  12992. break;
  12993. }
  12994. prev = curr;
  12995. curr = curr->next;
  12996. }
  12997. if (curr == NULL)
  12998. #endif
  12999. {
  13000. WOLFSSL_ERROR_VERBOSE(INVALID_CERT_CTX_E);
  13001. ERROR_OUT(INVALID_CERT_CTX_E, exit_ppc);
  13002. }
  13003. }
  13004. }
  13005. #endif
  13006. args->idx += ctxSz;
  13007. /* allocate buffer for cert extensions */
  13008. args->exts = (buffer*)XMALLOC(sizeof(buffer) *
  13009. MAX_CHAIN_DEPTH, ssl->heap, DYNAMIC_TYPE_CERT_EXT);
  13010. if (args->exts == NULL) {
  13011. ERROR_OUT(MEMORY_E, exit_ppc);
  13012. }
  13013. }
  13014. #endif
  13015. /* allocate buffer for certs */
  13016. args->certs = (buffer*)XMALLOC(sizeof(buffer) * MAX_CHAIN_DEPTH,
  13017. ssl->heap, DYNAMIC_TYPE_DER);
  13018. if (args->certs == NULL) {
  13019. ERROR_OUT(MEMORY_E, exit_ppc);
  13020. }
  13021. XMEMSET(args->certs, 0, sizeof(buffer) * MAX_CHAIN_DEPTH);
  13022. /* Certificate List */
  13023. if ((args->idx - args->begin) + OPAQUE24_LEN > totalSz) {
  13024. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  13025. }
  13026. c24to32(input + args->idx, &listSz);
  13027. #ifdef HAVE_RPK
  13028. /*
  13029. * If this is RPK from the peer, then single cert (if TLS1.2).
  13030. * So, ListSz location is same as CertSz location, so fake
  13031. * we have just seen this ListSz.
  13032. */
  13033. if (!IsAtLeastTLSv1_3(ssl->version) &&
  13034. ((ssl->options.side == WOLFSSL_SERVER_END &&
  13035. ssl->options.rpkState.received_ClientCertTypeCnt == 1 &&
  13036. ssl->options.rpkState.received_ClientCertTypes[0] == WOLFSSL_CERT_TYPE_RPK) ||
  13037. (ssl->options.side == WOLFSSL_CLIENT_END &&
  13038. ssl->options.rpkState.received_ServerCertTypeCnt == 1 &&
  13039. ssl->options.rpkState.received_ServerCertTypes[0] == WOLFSSL_CERT_TYPE_RPK))) {
  13040. listSz += OPAQUE24_LEN;
  13041. } else
  13042. #endif /* HAVE_RPK */
  13043. {
  13044. args->idx += OPAQUE24_LEN;
  13045. }
  13046. if (listSz > MAX_CERTIFICATE_SZ) {
  13047. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  13048. }
  13049. if ((args->idx - args->begin) + listSz != totalSz) {
  13050. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  13051. }
  13052. WOLFSSL_MSG("Loading peer's cert chain");
  13053. /* first put cert chain into buffer so can verify top down
  13054. we're sent bottom up */
  13055. while (listSz) {
  13056. word32 certSz;
  13057. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13058. if (args->totalCerts >= MAX_CHAIN_DEPTH) {
  13059. if (ssl->peerVerifyRet == 0) /* Return first cert error here */
  13060. ssl->peerVerifyRet =
  13061. WOLFSSL_X509_V_ERR_CERT_CHAIN_TOO_LONG;
  13062. ret = MAX_CHAIN_ERROR;
  13063. WOLFSSL_ERROR_VERBOSE(ret);
  13064. WOLFSSL_MSG("Too many certs for MAX_CHAIN_DEPTH");
  13065. break; /* break out to avoid reading more certs then buffer
  13066. * can hold */
  13067. }
  13068. #else
  13069. if (args->totalCerts >= ssl->verifyDepth ||
  13070. args->totalCerts >= MAX_CHAIN_DEPTH) {
  13071. WOLFSSL_ERROR_VERBOSE(MAX_CHAIN_ERROR);
  13072. ERROR_OUT(MAX_CHAIN_ERROR, exit_ppc);
  13073. }
  13074. #endif
  13075. if ((args->idx - args->begin) + OPAQUE24_LEN > totalSz) {
  13076. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  13077. }
  13078. c24to32(input + args->idx, &certSz);
  13079. args->idx += OPAQUE24_LEN;
  13080. if ((args->idx - args->begin) + certSz > totalSz) {
  13081. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  13082. }
  13083. args->certs[args->totalCerts].length = certSz;
  13084. args->certs[args->totalCerts].buffer = input + args->idx;
  13085. #ifdef SESSION_CERTS
  13086. AddSessionCertToChain(&ssl->session->chain,
  13087. input + args->idx, certSz);
  13088. #endif /* SESSION_CERTS */
  13089. args->idx += certSz;
  13090. listSz -= certSz + CERT_HEADER_SZ;
  13091. #ifdef WOLFSSL_TLS13
  13092. /* Extensions */
  13093. if (ssl->options.tls1_3) {
  13094. word16 extSz;
  13095. if (args->exts == NULL) {
  13096. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  13097. }
  13098. if ((args->idx - args->begin) + OPAQUE16_LEN > totalSz) {
  13099. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  13100. }
  13101. ato16(input + args->idx, &extSz);
  13102. args->idx += OPAQUE16_LEN;
  13103. if ((args->idx - args->begin) + extSz > totalSz) {
  13104. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  13105. }
  13106. /* Store extension data info for later processing. */
  13107. args->exts[args->totalCerts].length = extSz;
  13108. args->exts[args->totalCerts].buffer = input + args->idx;
  13109. args->idx += extSz;
  13110. listSz -= extSz + OPAQUE16_LEN;
  13111. WOLFSSL_MSG_EX("\tParsing %d bytes of cert extensions",
  13112. args->exts[args->totalCerts].length);
  13113. #if !defined(NO_TLS)
  13114. ret = TLSX_Parse(ssl, args->exts[args->totalCerts].buffer,
  13115. (word16)args->exts[args->totalCerts].length,
  13116. certificate, NULL);
  13117. #endif /* !NO_TLS */
  13118. if (ret < 0) {
  13119. WOLFSSL_ERROR_VERBOSE(ret);
  13120. ERROR_OUT(ret, exit_ppc);
  13121. }
  13122. }
  13123. #endif
  13124. args->totalCerts++;
  13125. WOLFSSL_MSG("\tPut another cert into chain");
  13126. } /* while (listSz) */
  13127. args->count = args->totalCerts;
  13128. args->certIdx = 0; /* select peer cert (first one) */
  13129. if (args->count == 0) {
  13130. /* Empty certificate message. */
  13131. if ((ssl->options.side == WOLFSSL_SERVER_END) &&
  13132. (ssl->options.mutualAuth || (ssl->options.failNoCert &&
  13133. IsAtLeastTLSv1_3(ssl->version)))) {
  13134. WOLFSSL_MSG("No peer cert from Client");
  13135. ret = NO_PEER_CERT;
  13136. WOLFSSL_ERROR_VERBOSE(ret);
  13137. DoCertFatalAlert(ssl, ret);
  13138. }
  13139. else if ((ssl->options.side == WOLFSSL_CLIENT_END) &&
  13140. IsAtLeastTLSv1_3(ssl->version)) {
  13141. WOLFSSL_MSG("No peer cert from Server");
  13142. ret = NO_PEER_CERT;
  13143. WOLFSSL_ERROR_VERBOSE(ret);
  13144. SendAlert(ssl, alert_fatal, decode_error);
  13145. }
  13146. }
  13147. args->dCertInit = 0;
  13148. #ifndef WOLFSSL_SMALL_CERT_VERIFY
  13149. args->dCert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
  13150. DYNAMIC_TYPE_DCERT);
  13151. if (args->dCert == NULL) {
  13152. ERROR_OUT(MEMORY_E, exit_ppc);
  13153. }
  13154. XMEMSET(args->dCert, 0, sizeof(DecodedCert));
  13155. #endif
  13156. /* Advance state and proceed */
  13157. ssl->options.asyncState = TLS_ASYNC_BUILD;
  13158. } /* case TLS_ASYNC_BEGIN */
  13159. FALL_THROUGH;
  13160. case TLS_ASYNC_BUILD:
  13161. {
  13162. if (args->count > 0) {
  13163. /* check for trusted peer and get untrustedDepth */
  13164. #if defined(WOLFSSL_TRUST_PEER_CERT) || defined(OPENSSL_EXTRA)
  13165. if (args->certIdx == 0) {
  13166. #ifdef WOLFSSL_TRUST_PEER_CERT
  13167. TrustedPeerCert* tp;
  13168. #endif
  13169. ret = ProcessPeerCertParse(ssl, args, CERT_TYPE, NO_VERIFY,
  13170. &subjectHash, &alreadySigner);
  13171. if (ret != 0)
  13172. goto exit_ppc;
  13173. #ifdef OPENSSL_EXTRA
  13174. /* Determine untrusted depth */
  13175. if (!alreadySigner && (!args->dCert ||
  13176. !args->dCertInit || !args->dCert->selfSigned)) {
  13177. args->untrustedDepth = 1;
  13178. }
  13179. #endif
  13180. #ifdef WOLFSSL_TRUST_PEER_CERT
  13181. tp = GetTrustedPeer(SSL_CM(ssl), args->dCert);
  13182. WOLFSSL_MSG("Checking for trusted peer cert");
  13183. if (tp && MatchTrustedPeer(tp, args->dCert)) {
  13184. WOLFSSL_MSG("Found matching trusted peer cert");
  13185. args->haveTrustPeer = 1;
  13186. }
  13187. else if (tp == NULL) {
  13188. /* no trusted peer cert */
  13189. WOLFSSL_MSG("No matching trusted peer cert. Checking CAs");
  13190. }
  13191. else {
  13192. WOLFSSL_MSG("Trusted peer cert did not match!");
  13193. }
  13194. if (!args->haveTrustPeer)
  13195. #endif
  13196. {
  13197. /* free cert if not trusted peer */
  13198. FreeDecodedCert(args->dCert);
  13199. args->dCertInit = 0;
  13200. }
  13201. }
  13202. #endif /* WOLFSSL_TRUST_PEER_CERT || OPENSSL_EXTRA */
  13203. /* check certificate up to peer's first */
  13204. /* do not verify chain if trusted peer cert found */
  13205. while (args->count > 1
  13206. #ifdef WOLFSSL_TRUST_PEER_CERT
  13207. && !args->haveTrustPeer
  13208. #endif /* WOLFSSL_TRUST_PEER_CERT */
  13209. ) {
  13210. int skipAddCA = 0;
  13211. /* select last certificate */
  13212. args->certIdx = args->count - 1;
  13213. ret = ProcessPeerCertParse(ssl, args, CHAIN_CERT_TYPE,
  13214. !ssl->options.verifyNone ? VERIFY : NO_VERIFY,
  13215. &subjectHash, &alreadySigner);
  13216. #if defined(OPENSSL_ALL) && defined(WOLFSSL_CERT_GEN) && \
  13217. (defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT)) && \
  13218. !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) && \
  13219. !defined(NO_STDIO_FILESYSTEM)
  13220. if (ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E) ||
  13221. ret == WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E)) {
  13222. WOLFSSL_MSG("try to load certificate if hash dir is set");
  13223. ret = LoadCertByIssuer(SSL_STORE(ssl),
  13224. (WOLFSSL_X509_NAME*)args->dCert->issuerName,
  13225. X509_LU_X509);
  13226. if (ret == WOLFSSL_SUCCESS) {
  13227. FreeDecodedCert(args->dCert);
  13228. args->dCertInit = 0;
  13229. /* once again */
  13230. ret = ProcessPeerCertParse(ssl, args, CHAIN_CERT_TYPE,
  13231. !ssl->options.verifyNone ? VERIFY : NO_VERIFY,
  13232. &subjectHash, &alreadySigner);
  13233. }
  13234. else {
  13235. ret = ASN_NO_SIGNER_E;
  13236. WOLFSSL_ERROR_VERBOSE(ret);
  13237. }
  13238. }
  13239. #endif
  13240. #ifdef WOLFSSL_ASYNC_CRYPT
  13241. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
  13242. goto exit_ppc;
  13243. #endif
  13244. if (ret == 0) {
  13245. ret = ProcessPeerCertCheckKey(ssl, args);
  13246. }
  13247. else if (ret == WC_NO_ERR_TRACE(ASN_PARSE_E) ||
  13248. ret == WC_NO_ERR_TRACE(BUFFER_E) ||
  13249. ret == WC_NO_ERR_TRACE(MEMORY_E)) {
  13250. WOLFSSL_MSG(
  13251. "Got Peer cert ASN PARSE_E, BUFFER E, MEMORY_E");
  13252. ERROR_OUT(ret, exit_ppc);
  13253. }
  13254. if (ret == 0 && args->dCert->isCA == 0) {
  13255. WOLFSSL_MSG("Chain cert is not a CA, not adding as one");
  13256. }
  13257. else if (ret == 0 && ssl->options.verifyNone) {
  13258. WOLFSSL_MSG("Chain cert not verified by option, "
  13259. "not adding as CA");
  13260. }
  13261. else if (ret == 0) {
  13262. #ifdef OPENSSL_EXTRA
  13263. if (args->certIdx > args->untrustedDepth) {
  13264. args->untrustedDepth = (char)args->certIdx + 1;
  13265. }
  13266. #endif
  13267. if (alreadySigner) {
  13268. WOLFSSL_MSG("Verified CA from chain and already had it");
  13269. }
  13270. }
  13271. else {
  13272. WOLFSSL_MSG("Failed to verify CA from chain");
  13273. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13274. if (ssl->peerVerifyRet == 0) /* Return first cert error here */
  13275. ssl->peerVerifyRet = WOLFSSL_X509_V_ERR_INVALID_CA;
  13276. #endif
  13277. }
  13278. if (ret == 0) {
  13279. #ifdef HAVE_OCSP
  13280. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  13281. addToPendingCAs = 0;
  13282. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  13283. ssl->status_request_v2 &&
  13284. TLSX_CSR2_IsMulti(ssl->extensions)) {
  13285. ret = TLSX_CSR2_InitRequests(ssl->extensions,
  13286. args->dCert, 0, ssl->heap);
  13287. addToPendingCAs = 1;
  13288. }
  13289. else /* skips OCSP and force CRL check */
  13290. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  13291. if (SSL_CM(ssl)->ocspEnabled &&
  13292. SSL_CM(ssl)->ocspCheckAll) {
  13293. WOLFSSL_MSG("Doing Non Leaf OCSP check");
  13294. ret = CheckCertOCSP_ex(SSL_CM(ssl)->ocsp,
  13295. args->dCert, ssl);
  13296. #ifdef WOLFSSL_NONBLOCK_OCSP
  13297. if (ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) {
  13298. args->lastErr = ret;
  13299. goto exit_ppc;
  13300. }
  13301. #endif
  13302. if (ret != 0) {
  13303. WOLFSSL_ERROR_VERBOSE(ret);
  13304. WOLFSSL_MSG("\tOCSP Lookup not ok");
  13305. }
  13306. }
  13307. #endif /* HAVE_OCSP */
  13308. #ifdef HAVE_CRL
  13309. if (SSL_CM(ssl)->crlEnabled &&
  13310. SSL_CM(ssl)->crlCheckAll) {
  13311. int doCrlLookup = 1;
  13312. #ifdef HAVE_OCSP
  13313. if (SSL_CM(ssl)->ocspEnabled &&
  13314. SSL_CM(ssl)->ocspCheckAll) {
  13315. /* If the cert status is unknown to the OCSP
  13316. responder, do a CRL lookup. If any other
  13317. error, skip the CRL lookup and fail the
  13318. certificate. */
  13319. doCrlLookup = (ret == WC_NO_ERR_TRACE(OCSP_CERT_UNKNOWN));
  13320. }
  13321. #endif /* HAVE_OCSP */
  13322. if (doCrlLookup) {
  13323. WOLFSSL_MSG("Doing Non Leaf CRL check");
  13324. ret = CheckCertCRL(SSL_CM(ssl)->crl,
  13325. args->dCert);
  13326. #ifdef WOLFSSL_NONBLOCK_OCSP
  13327. /* The CRL lookup I/O callback is using the
  13328. * same WOULD_BLOCK error code as OCSP's I/O
  13329. * callback, and it is enabling it using the
  13330. * same flag. */
  13331. if (ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) {
  13332. args->lastErr = ret;
  13333. goto exit_ppc;
  13334. }
  13335. #endif
  13336. if (ret != 0)
  13337. DoCrlCallback(SSL_CM(ssl), ssl, args, &ret);
  13338. if (ret != 0) {
  13339. WOLFSSL_ERROR_VERBOSE(ret);
  13340. WOLFSSL_MSG("\tCRL check not ok");
  13341. }
  13342. if (ret == 0 &&
  13343. args->certIdx == args->totalCerts-1) {
  13344. ret = ProcessPeerCertsChainCRLCheck(ssl,
  13345. args);
  13346. if (ret != 0) {
  13347. WOLFSSL_ERROR_VERBOSE(ret);
  13348. WOLFSSL_MSG("\tCRL chain check not ok");
  13349. args->fatal = 0;
  13350. }
  13351. }
  13352. }
  13353. }
  13354. #endif /* HAVE_CRL */
  13355. }
  13356. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13357. if (ret == 0 &&
  13358. /* extend the limit "+1" until reaching
  13359. * an ultimately trusted issuer.*/
  13360. args->count > (ssl->verifyDepth + 1)) {
  13361. if (ssl->peerVerifyRet == 0) /* Return first cert error here */
  13362. ssl->peerVerifyRet =
  13363. WOLFSSL_X509_V_ERR_CERT_CHAIN_TOO_LONG;
  13364. ret = MAX_CHAIN_ERROR;
  13365. WOLFSSL_ERROR_VERBOSE(ret);
  13366. }
  13367. #endif
  13368. #ifdef WOLFSSL_ALT_CERT_CHAINS
  13369. /* For alternate cert chain, its okay for a CA cert to fail
  13370. with ASN_NO_SIGNER_E here. The "alternate" certificate
  13371. chain mode only requires that the peer certificate
  13372. validate to a trusted CA */
  13373. if (ret != 0 && args->dCert->isCA) {
  13374. if (ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E) ||
  13375. ret == WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E)) {
  13376. if (!ssl->options.usingAltCertChain) {
  13377. WOLFSSL_MSG("Trying alternate cert chain");
  13378. ssl->options.usingAltCertChain = 1;
  13379. }
  13380. ret = 0; /* clear errors and continue */
  13381. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13382. ssl->peerVerifyRet = 0;
  13383. #endif
  13384. args->verifyErr = 0;
  13385. /* do not add to certificate manager */
  13386. skipAddCA = 1;
  13387. }
  13388. }
  13389. #endif /* WOLFSSL_ALT_CERT_CHAINS */
  13390. #if defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS)
  13391. /* If we are using native Apple CA validation, it is okay
  13392. * for a CA cert to fail validation here, as we will verify
  13393. * the entire chain when we hit the peer (leaf) cert */
  13394. if ((ssl->ctx->doAppleNativeCertValidationFlag)
  13395. && (ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E))) {
  13396. WOLFSSL_MSG("Bypassing errors to allow for Apple native"
  13397. " CA validation");
  13398. ret = 0; /* clear errors and continue */
  13399. args->verifyErr = 0;
  13400. #if defined(OPENSSL_EXTRA) \
  13401. || defined(OPENSSL_EXTRA_X509_SMALL)
  13402. ssl->peerVerifyRet = 0;
  13403. #endif
  13404. /* do not add to certificate manager */
  13405. skipAddCA = 1;
  13406. }
  13407. #endif /* defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS) */
  13408. /* Do verify callback */
  13409. ret = DoVerifyCallback(SSL_CM(ssl), ssl, ret, args);
  13410. if (ssl->options.verifyNone &&
  13411. (ret == WC_NO_ERR_TRACE(CRL_MISSING) ||
  13412. ret == WC_NO_ERR_TRACE(CRL_CERT_REVOKED) ||
  13413. ret == WC_NO_ERR_TRACE(CRL_CERT_DATE_ERR))) {
  13414. WOLFSSL_MSG("Ignoring CRL problem based on verify setting");
  13415. ret = ssl->error = 0;
  13416. }
  13417. #ifdef WOLFSSL_ALT_CERT_CHAINS
  13418. if (ret != 0 && args->dCert->isCA) {
  13419. /* do not add to certificate manager */
  13420. skipAddCA = 1;
  13421. }
  13422. #endif
  13423. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  13424. if (ret == 0 && addToPendingCAs && !alreadySigner) {
  13425. #ifdef WOLFSSL_SMALL_STACK
  13426. DecodedCert *dCertAdd = NULL;
  13427. #else
  13428. DecodedCert dCertAdd[1];
  13429. #endif
  13430. int dCertAdd_inited = 0;
  13431. DerBuffer *derBuffer = NULL;
  13432. buffer* cert = &args->certs[args->certIdx];
  13433. Signer *s = NULL;
  13434. #ifdef WOLFSSL_SMALL_STACK
  13435. dCertAdd = (DecodedCert *)
  13436. XMALLOC(sizeof(*dCertAdd), ssl->heap,
  13437. DYNAMIC_TYPE_TMP_BUFFER);
  13438. if (dCertAdd == NULL) {
  13439. ret = MEMORY_E;
  13440. goto exit_req_v2;
  13441. }
  13442. #endif
  13443. InitDecodedCert(dCertAdd, cert->buffer, cert->length,
  13444. ssl->heap);
  13445. dCertAdd_inited = 1;
  13446. ret = ParseCert(dCertAdd, CA_TYPE, NO_VERIFY,
  13447. SSL_CM(ssl));
  13448. if (ret != 0) {
  13449. goto exit_req_v2;
  13450. }
  13451. ret = AllocDer(&derBuffer, cert->length, CA_TYPE, ssl->heap);
  13452. if (ret != 0 || derBuffer == NULL) {
  13453. goto exit_req_v2;
  13454. }
  13455. XMEMCPY(derBuffer->buffer, cert->buffer, cert->length);
  13456. s = MakeSigner(SSL_CM(ssl)->heap);
  13457. if (s == NULL) {
  13458. ret = MEMORY_E;
  13459. goto exit_req_v2;
  13460. }
  13461. ret = FillSigner(s, dCertAdd, CA_TYPE, derBuffer);
  13462. if (ret != 0) {
  13463. goto exit_req_v2;
  13464. }
  13465. skipAddCA = 1;
  13466. ret = TLSX_CSR2_AddPendingSigner(ssl->extensions, s);
  13467. exit_req_v2:
  13468. if (s && (ret != 0))
  13469. FreeSigner(s, SSL_CM(ssl)->heap);
  13470. if (derBuffer)
  13471. FreeDer(&derBuffer);
  13472. if (dCertAdd_inited)
  13473. FreeDecodedCert(dCertAdd);
  13474. #ifdef WOLFSSL_SMALL_STACK
  13475. XFREE(dCertAdd, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  13476. #endif
  13477. if (ret != 0)
  13478. goto exit_ppc;
  13479. }
  13480. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  13481. /* If valid CA then add to Certificate Manager */
  13482. if (ret == 0 && args->dCert->isCA &&
  13483. !ssl->options.verifyNone && !skipAddCA) {
  13484. buffer* cert = &args->certs[args->certIdx];
  13485. /* Is valid CA */
  13486. #if defined(SESSION_CERTS) && defined(WOLFSSL_ALT_CERT_CHAINS)
  13487. /* if using alternate chain, store the cert used */
  13488. if (ssl->options.usingAltCertChain) {
  13489. AddSessionCertToChain(&ssl->session->altChain,
  13490. cert->buffer, cert->length);
  13491. }
  13492. #endif /* SESSION_CERTS && WOLFSSL_ALT_CERT_CHAINS */
  13493. if (!alreadySigner) {
  13494. DerBuffer* add = NULL;
  13495. ret = AllocDer(&add, cert->length, CA_TYPE, ssl->heap);
  13496. if (ret < 0)
  13497. goto exit_ppc;
  13498. XMEMCPY(add->buffer, cert->buffer, cert->length);
  13499. /* CA already verified above in ParseCertRelative */
  13500. WOLFSSL_MSG("Adding CA from chain");
  13501. SSL_CM_WARNING(ssl);
  13502. ret = AddCA(SSL_CM(ssl), &add, WOLFSSL_CHAIN_CA,
  13503. NO_VERIFY);
  13504. if (ret == WOLFSSL_SUCCESS) {
  13505. ret = 0;
  13506. }
  13507. }
  13508. }
  13509. /* Handle error codes */
  13510. ssl->error = ret; /* Report SSL error or clear error if
  13511. * callback overrides. */
  13512. if (ret != 0) {
  13513. if (!ssl->options.verifyNone) {
  13514. WOLFSSL_ERROR_VERBOSE(ret);
  13515. DoCertFatalAlert(ssl, ret);
  13516. args->lastErr = ret;
  13517. break; /* We sent a fatal alert.
  13518. * No point continuing. */
  13519. }
  13520. if (args->lastErr == 0) {
  13521. args->lastErr = ret; /* save error from last time */
  13522. ret = 0; /* reset error */
  13523. }
  13524. }
  13525. FreeDecodedCert(args->dCert);
  13526. args->dCertInit = 0;
  13527. args->count--;
  13528. } /* while (count > 1 && !args->haveTrustPeer) */
  13529. } /* if (count > 0) */
  13530. /* Check for error */
  13531. if (ret != 0) {
  13532. goto exit_ppc;
  13533. }
  13534. /* Advance state and proceed */
  13535. ssl->options.asyncState = TLS_ASYNC_DO;
  13536. } /* case TLS_ASYNC_BUILD */
  13537. FALL_THROUGH;
  13538. case TLS_ASYNC_DO:
  13539. {
  13540. /* peer's, may not have one if blank client cert sent by TLSv1.2 */
  13541. if (args->count > 0) {
  13542. WOLFSSL_MSG("Verifying Peer's cert");
  13543. /* select peer cert (first one) */
  13544. args->certIdx = 0;
  13545. ret = ProcessPeerCertParse(ssl, args, CERT_TYPE,
  13546. !ssl->options.verifyNone ? VERIFY : NO_VERIFY,
  13547. &subjectHash, &alreadySigner);
  13548. #if defined(OPENSSL_ALL) && defined(WOLFSSL_CERT_GEN) && \
  13549. (defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT)) && \
  13550. !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) && \
  13551. !defined(NO_STDIO_FILESYSTEM)
  13552. if (ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E) ||
  13553. ret == WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E)) {
  13554. int lastErr = ret; /* save error from last time */
  13555. WOLFSSL_MSG("try to load certificate if hash dir is set");
  13556. ret = LoadCertByIssuer(SSL_STORE(ssl),
  13557. (WOLFSSL_X509_NAME*)args->dCert->issuerName,
  13558. X509_LU_X509);
  13559. if (ret == WOLFSSL_SUCCESS) {
  13560. FreeDecodedCert(args->dCert);
  13561. args->dCertInit = 0;
  13562. /* once again */
  13563. ret = ProcessPeerCertParse(ssl, args, CERT_TYPE,
  13564. !ssl->options.verifyNone ? VERIFY : NO_VERIFY,
  13565. &subjectHash, &alreadySigner);
  13566. }
  13567. else {
  13568. ret = lastErr; /* restore error */
  13569. WOLFSSL_ERROR_VERBOSE(ret);
  13570. }
  13571. }
  13572. #endif
  13573. #ifdef WOLFSSL_ASYNC_CRYPT
  13574. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
  13575. goto exit_ppc;
  13576. #endif
  13577. if (ret == 0) {
  13578. WOLFSSL_MSG("Verified Peer's cert");
  13579. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13580. if (ssl->peerVerifyRet == 0) /* Return first cert error here */
  13581. ssl->peerVerifyRet = WOLFSSL_X509_V_OK;
  13582. #endif
  13583. #if defined(SESSION_CERTS) && defined(WOLFSSL_ALT_CERT_CHAINS)
  13584. /* if using alternate chain, store the cert used */
  13585. if (ssl->options.usingAltCertChain) {
  13586. buffer* cert = &args->certs[args->certIdx];
  13587. AddSessionCertToChain(&ssl->session->altChain,
  13588. cert->buffer, cert->length);
  13589. }
  13590. #endif /* SESSION_CERTS && WOLFSSL_ALT_CERT_CHAINS */
  13591. #ifndef OPENSSL_COMPATIBLE_DEFAULTS
  13592. /* Check peer's certificate version number. TLS 1.2 / 1.3
  13593. * requires the clients certificate be version 3 unless a
  13594. * different version has been negotiated using RFC 7250.
  13595. * OpenSSL doesn't appear to be performing this check.
  13596. * For TLS 1.3 see RFC8446 Section 4.4.2.3 */
  13597. if (ssl->options.side == WOLFSSL_SERVER_END) {
  13598. #if defined(HAVE_RPK)
  13599. if (args->dCert->isRPK) {
  13600. /* to verify Raw Public Key cert, DANE(RFC6698)
  13601. * should be introduced. Without DANE, no
  13602. * authentication is performed.
  13603. */
  13604. #if defined(HAVE_DANE)
  13605. if (ssl->useDANE) {
  13606. /* DANE authentication should be added */
  13607. }
  13608. #endif /* HAVE_DANE */
  13609. }
  13610. else /* skip followingx509 version check */
  13611. #endif /* HAVE_RPK */
  13612. if (args->dCert->version != WOLFSSL_X509_V3) {
  13613. WOLFSSL_MSG("Peers certificate was not version 3!");
  13614. args->lastErr = ASN_VERSION_E;
  13615. /* setting last error but not considering it fatal
  13616. * giving the user a chance to override */
  13617. }
  13618. }
  13619. #endif
  13620. /* check if fatal error */
  13621. if (args->verifyErr) {
  13622. args->fatal = 1;
  13623. ret = args->lastErr;
  13624. }
  13625. else {
  13626. args->fatal = 0;
  13627. }
  13628. }
  13629. else if (ret == WC_NO_ERR_TRACE(ASN_PARSE_E) ||
  13630. ret == WC_NO_ERR_TRACE(BUFFER_E) ||
  13631. ret == WC_NO_ERR_TRACE(MEMORY_E) ||
  13632. ret == WC_NO_ERR_TRACE(BAD_FUNC_ARG)) {
  13633. WOLFSSL_MSG("Got Peer cert ASN_PARSE_E, BUFFER_E, MEMORY_E,"
  13634. " BAD_FUNC_ARG");
  13635. #if defined(WOLFSSL_EXTRA_ALERTS) || defined(OPENSSL_EXTRA) || \
  13636. defined(OPENSSL_EXTRA_X509_SMALL)
  13637. DoCertFatalAlert(ssl, ret);
  13638. #endif
  13639. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13640. if (ssl->peerVerifyRet == 0) /* Return first cert error here */
  13641. ssl->peerVerifyRet = WOLFSSL_X509_V_ERR_CERT_REJECTED;
  13642. #endif
  13643. args->fatal = 1;
  13644. }
  13645. else {
  13646. WOLFSSL_MSG("Failed to verify Peer's cert");
  13647. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13648. if (ssl->peerVerifyRet == 0) { /* Return first cert error here */
  13649. if (ret == WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E)) {
  13650. ssl->peerVerifyRet =
  13651. (unsigned long)WOLFSSL_X509_V_ERR_CERT_NOT_YET_VALID;
  13652. }
  13653. else if (ret == WC_NO_ERR_TRACE(ASN_AFTER_DATE_E)) {
  13654. ssl->peerVerifyRet =
  13655. (unsigned long)WOLFSSL_X509_V_ERR_CERT_HAS_EXPIRED;
  13656. }
  13657. else {
  13658. ssl->peerVerifyRet =
  13659. (unsigned long)
  13660. WOLFSSL_X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
  13661. }
  13662. }
  13663. #endif
  13664. if (ssl->verifyCallback) {
  13665. WOLFSSL_MSG(
  13666. "\tCallback override available, will continue");
  13667. /* check if fatal error */
  13668. args->fatal = (args->verifyErr) ? 1 : 0;
  13669. if (args->fatal)
  13670. DoCertFatalAlert(ssl, ret);
  13671. }
  13672. #if defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS)
  13673. /* Disregard failure to verify peer cert, as we will verify
  13674. * the whole chain with the native API later */
  13675. else if (ssl->ctx->doAppleNativeCertValidationFlag) {
  13676. WOLFSSL_MSG("\tApple native CA validation override"
  13677. " available, will continue");
  13678. /* check if fatal error */
  13679. args->fatal = (args->verifyErr) ? 1 : 0;
  13680. if (args->fatal)
  13681. DoCertFatalAlert(ssl, ret);
  13682. }
  13683. #endif/*defined(__APPLE__)&& defined(WOLFSSL_SYS_CA_CERTS)*/
  13684. else {
  13685. WOLFSSL_MSG("\tNo callback override available, fatal");
  13686. args->fatal = 1;
  13687. DoCertFatalAlert(ssl, ret);
  13688. }
  13689. }
  13690. #ifdef HAVE_SECURE_RENEGOTIATION
  13691. if (args->fatal == 0 && !IsAtLeastTLSv1_3(ssl->version)
  13692. && ssl->secure_renegotiation
  13693. && ssl->secure_renegotiation->enabled) {
  13694. if (IsEncryptionOn(ssl, 0)) {
  13695. /* compare against previous time */
  13696. if (ssl->secure_renegotiation->subject_hash_set) {
  13697. if (XMEMCMP(args->dCert->subjectHash,
  13698. ssl->secure_renegotiation->subject_hash,
  13699. KEYID_SIZE) != 0) {
  13700. WOLFSSL_MSG(
  13701. "Peer sent different cert during scr, fatal");
  13702. args->fatal = 1;
  13703. ret = SCR_DIFFERENT_CERT_E;
  13704. WOLFSSL_ERROR_VERBOSE(ret);
  13705. }
  13706. }
  13707. }
  13708. /* cache peer's hash */
  13709. if (args->fatal == 0) {
  13710. XMEMCPY(ssl->secure_renegotiation->subject_hash,
  13711. args->dCert->subjectHash, KEYID_SIZE);
  13712. ssl->secure_renegotiation->subject_hash_set = 1;
  13713. }
  13714. }
  13715. #endif /* HAVE_SECURE_RENEGOTIATION */
  13716. } /* if (count > 0) */
  13717. /* Check for error */
  13718. if (args->fatal && ret != 0) {
  13719. goto exit_ppc;
  13720. }
  13721. /* Advance state and proceed */
  13722. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  13723. } /* case TLS_ASYNC_DO */
  13724. FALL_THROUGH;
  13725. case TLS_ASYNC_VERIFY:
  13726. {
  13727. if (args->count > 0) {
  13728. #if defined(HAVE_OCSP) || defined(HAVE_CRL)
  13729. /* only attempt to check OCSP or CRL if not previous error such
  13730. * as ASN_BEFORE_DATE_E or ASN_AFTER_DATE_E */
  13731. if (args->fatal == 0 && ret == 0) {
  13732. int doLookup = 1;
  13733. WOLFSSL_MSG("Checking if ocsp needed");
  13734. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  13735. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  13736. if (ssl->status_request) {
  13737. args->fatal = (TLSX_CSR_InitRequest(ssl->extensions,
  13738. args->dCert, ssl->heap) != 0);
  13739. doLookup = 0;
  13740. WOLFSSL_MSG("\tHave status request");
  13741. #if defined(WOLFSSL_TLS13)
  13742. if (ssl->options.tls1_3) {
  13743. TLSX* ext = TLSX_Find(ssl->extensions,
  13744. TLSX_STATUS_REQUEST);
  13745. if (ext != NULL) {
  13746. word32 idx = 0;
  13747. CertificateStatusRequest* csr =
  13748. (CertificateStatusRequest*)ext->data;
  13749. ret = ProcessCSR(ssl, csr->response.buffer,
  13750. &idx, csr->response.length);
  13751. if (ret < 0) {
  13752. WOLFSSL_ERROR_VERBOSE(ret);
  13753. goto exit_ppc;
  13754. }
  13755. }
  13756. }
  13757. #endif
  13758. }
  13759. /* Ensure a stapling response was seen */
  13760. else if (ssl->options.tls1_3 &&
  13761. SSL_CM(ssl)->ocspMustStaple) {
  13762. ret = OCSP_CERT_UNKNOWN;
  13763. goto exit_ppc;
  13764. }
  13765. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
  13766. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  13767. if (ssl->status_request_v2) {
  13768. args->fatal = (TLSX_CSR2_InitRequests(ssl->extensions,
  13769. args->dCert, 1, ssl->heap) != 0);
  13770. doLookup = 0;
  13771. WOLFSSL_MSG("\tHave status request v2");
  13772. }
  13773. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  13774. }
  13775. #ifdef HAVE_OCSP
  13776. if (doLookup && SSL_CM(ssl)->ocspEnabled) {
  13777. WOLFSSL_MSG("Doing Leaf OCSP check");
  13778. ret = CheckCertOCSP_ex(SSL_CM(ssl)->ocsp,
  13779. args->dCert, ssl);
  13780. #ifdef WOLFSSL_NONBLOCK_OCSP
  13781. if (ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) {
  13782. goto exit_ppc;
  13783. }
  13784. #endif
  13785. doLookup = (ret == WC_NO_ERR_TRACE(OCSP_CERT_UNKNOWN));
  13786. if (ret != 0) {
  13787. WOLFSSL_MSG("\tOCSP Lookup not ok");
  13788. args->fatal = 0;
  13789. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13790. if (ssl->peerVerifyRet == 0) {
  13791. /* Return first cert error here */
  13792. ssl->peerVerifyRet =
  13793. ret == WC_NO_ERR_TRACE(OCSP_CERT_REVOKED)
  13794. ? WOLFSSL_X509_V_ERR_CERT_REVOKED
  13795. : WOLFSSL_X509_V_ERR_CERT_REJECTED;
  13796. }
  13797. #endif
  13798. }
  13799. }
  13800. #endif /* HAVE_OCSP */
  13801. #ifdef HAVE_CRL
  13802. if (ret == 0 && doLookup && SSL_CM(ssl)->crlEnabled) {
  13803. WOLFSSL_MSG("Doing Leaf CRL check");
  13804. ret = CheckCertCRL(SSL_CM(ssl)->crl, args->dCert);
  13805. #ifdef WOLFSSL_NONBLOCK_OCSP
  13806. /* The CRL lookup I/O callback is using the
  13807. * same WOULD_BLOCK error code as OCSP's I/O
  13808. * callback, and it is enabling it using the
  13809. * same flag. */
  13810. if (ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) {
  13811. goto exit_ppc;
  13812. }
  13813. #endif
  13814. if (ret != 0)
  13815. DoCrlCallback(SSL_CM(ssl), ssl, args, &ret);
  13816. if (ret != 0) {
  13817. WOLFSSL_MSG("\tCRL check not ok");
  13818. args->fatal = 0;
  13819. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13820. if (ssl->peerVerifyRet == 0) {
  13821. /* Return first cert error here */
  13822. ssl->peerVerifyRet =
  13823. ret == WC_NO_ERR_TRACE(CRL_CERT_REVOKED)
  13824. ? WOLFSSL_X509_V_ERR_CERT_REVOKED
  13825. : WOLFSSL_X509_V_ERR_CERT_REJECTED;
  13826. }
  13827. #endif
  13828. }
  13829. }
  13830. if (ret == 0 && doLookup && SSL_CM(ssl)->crlEnabled &&
  13831. SSL_CM(ssl)->crlCheckAll && args->totalCerts == 1) {
  13832. /* Check the entire cert chain */
  13833. if (args->dCert->ca != NULL) {
  13834. ret = ProcessPeerCertsChainCRLCheck(ssl, args);
  13835. if (ret != 0) {
  13836. WOLFSSL_ERROR_VERBOSE(ret);
  13837. WOLFSSL_MSG("\tCRL chain check not ok");
  13838. args->fatal = 0;
  13839. }
  13840. }
  13841. else {
  13842. WOLFSSL_MSG("No CA signer set");
  13843. }
  13844. }
  13845. #endif /* HAVE_CRL */
  13846. (void)doLookup;
  13847. }
  13848. #endif /* HAVE_OCSP || HAVE_CRL */
  13849. #ifdef KEEP_PEER_CERT
  13850. if (args->fatal == 0) {
  13851. int copyRet = 0;
  13852. /* free old peer cert */
  13853. FreeX509(&ssl->peerCert);
  13854. InitX509(&ssl->peerCert, 0, ssl->heap);
  13855. copyRet = CopyDecodedToX509(&ssl->peerCert, args->dCert);
  13856. if (copyRet == WC_NO_ERR_TRACE(MEMORY_E)) {
  13857. args->fatal = 1;
  13858. }
  13859. }
  13860. #endif /* KEEP_PEER_CERT */
  13861. #ifndef IGNORE_KEY_EXTENSIONS
  13862. #if defined(OPENSSL_EXTRA)
  13863. /* when compatibility layer is turned on and no verify is
  13864. * set then ignore the certificate key extension */
  13865. if (args->dCert->extKeyUsageSet &&
  13866. args->dCert->extKeyUsageCrit == 0 &&
  13867. ssl->options.verifyNone) {
  13868. WOLFSSL_MSG("Not verifying certificate key usage");
  13869. }
  13870. else
  13871. #endif
  13872. if (args->dCert->extKeyUsageSet) {
  13873. if ((ssl->specs.kea == rsa_kea) &&
  13874. (ssl->options.side == WOLFSSL_CLIENT_END) &&
  13875. (args->dCert->extKeyUsage & KEYUSE_KEY_ENCIPHER) == 0) {
  13876. ret = KEYUSE_ENCIPHER_E;
  13877. WOLFSSL_ERROR_VERBOSE(ret);
  13878. }
  13879. if ((ssl->specs.kea != rsa_kea) &&
  13880. (ssl->specs.sig_algo == rsa_sa_algo ||
  13881. (ssl->specs.sig_algo == ecc_dsa_sa_algo &&
  13882. !ssl->specs.static_ecdh)) &&
  13883. (args->dCert->extKeyUsage & KEYUSE_DIGITAL_SIG) == 0) {
  13884. WOLFSSL_MSG("KeyUse Digital Sig not set");
  13885. ret = KEYUSE_SIGNATURE_E;
  13886. WOLFSSL_ERROR_VERBOSE(ret);
  13887. }
  13888. }
  13889. #if defined(OPENSSL_EXTRA)
  13890. /* when compatibility layer is turned on and no verify is
  13891. * set then ignore the certificate key extension */
  13892. if (args->dCert->extExtKeyUsageSet &&
  13893. args->dCert->extExtKeyUsageCrit == 0 &&
  13894. ssl->options.verifyNone) {
  13895. WOLFSSL_MSG("Not verifying certificate ext key usage");
  13896. }
  13897. else
  13898. #endif
  13899. if (args->dCert->extExtKeyUsageSet) {
  13900. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  13901. if ((args->dCert->extExtKeyUsage &
  13902. (EXTKEYUSE_ANY | EXTKEYUSE_SERVER_AUTH)) == 0) {
  13903. WOLFSSL_MSG("ExtKeyUse Server Auth not set");
  13904. ret = EXTKEYUSE_AUTH_E;
  13905. WOLFSSL_ERROR_VERBOSE(ret);
  13906. }
  13907. }
  13908. else {
  13909. if ((args->dCert->extExtKeyUsage &
  13910. (EXTKEYUSE_ANY | EXTKEYUSE_CLIENT_AUTH)) == 0) {
  13911. WOLFSSL_MSG("ExtKeyUse Client Auth not set");
  13912. ret = EXTKEYUSE_AUTH_E;
  13913. WOLFSSL_ERROR_VERBOSE(ret);
  13914. }
  13915. }
  13916. }
  13917. #endif /* IGNORE_KEY_EXTENSIONS */
  13918. if (args->fatal) {
  13919. ssl->error = ret;
  13920. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13921. SendAlert(ssl, alert_fatal, bad_certificate);
  13922. if (ssl->peerVerifyRet == 0) /* Return first cert error here */
  13923. ssl->peerVerifyRet = WOLFSSL_X509_V_ERR_CERT_REJECTED;
  13924. #endif
  13925. goto exit_ppc;
  13926. }
  13927. /* Certificate validated and stored. */
  13928. ssl->options.havePeerCert = 1;
  13929. #if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_RSA)
  13930. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  13931. ssl->specs.sig_algo == rsa_kea) {
  13932. /* CLIENT: No ServerKeyExchange message sent by server. */
  13933. ssl->options.peerAuthGood = 1;
  13934. }
  13935. #endif
  13936. #if !defined(NO_WOLFSSL_CLIENT) && defined(HAVE_ECC)
  13937. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  13938. ssl->specs.static_ecdh) {
  13939. /* CLIENT: No ServerKeyExchange message sent by server. */
  13940. ssl->options.peerAuthGood = 1;
  13941. }
  13942. #endif
  13943. if (!ssl->options.verifyNone && ssl->buffers.domainName.buffer) {
  13944. #ifndef WOLFSSL_ALLOW_NO_CN_IN_SAN
  13945. /* Per RFC 5280 section 4.2.1.6, "Whenever such identities
  13946. * are to be bound into a certificate, the subject
  13947. * alternative name extension MUST be used." */
  13948. if (args->dCert->altNames) {
  13949. if (CheckForAltNames(args->dCert,
  13950. (char*)ssl->buffers.domainName.buffer,
  13951. (ssl->buffers.domainName.buffer == NULL ? 0 :
  13952. (word32)XSTRLEN(
  13953. (const char *)ssl->buffers.domainName.buffer)),
  13954. NULL) != 1) {
  13955. WOLFSSL_MSG("DomainName match on alt names failed");
  13956. /* try to get peer key still */
  13957. ret = DOMAIN_NAME_MISMATCH;
  13958. WOLFSSL_ERROR_VERBOSE(ret);
  13959. }
  13960. }
  13961. else {
  13962. if (MatchDomainName(
  13963. args->dCert->subjectCN,
  13964. args->dCert->subjectCNLen,
  13965. (char*)ssl->buffers.domainName.buffer,
  13966. (ssl->buffers.domainName.buffer == NULL ? 0 :
  13967. (word32)XSTRLEN(
  13968. (const char *)ssl->buffers.domainName.buffer)
  13969. )) == 0)
  13970. {
  13971. WOLFSSL_MSG("DomainName match on common name failed");
  13972. ret = DOMAIN_NAME_MISMATCH;
  13973. WOLFSSL_ERROR_VERBOSE(ret);
  13974. }
  13975. }
  13976. #else /* WOLFSSL_ALL_NO_CN_IN_SAN */
  13977. /* Old behavior. */
  13978. if (MatchDomainName(args->dCert->subjectCN,
  13979. args->dCert->subjectCNLen,
  13980. (char*)ssl->buffers.domainName.buffer,
  13981. (ssl->buffers.domainName.buffer == NULL ? 0 :
  13982. (word32)XSTRLEN(ssl->buffers.domainName.buffer))) == 0)
  13983. {
  13984. WOLFSSL_MSG("DomainName match on common name failed");
  13985. if (CheckForAltNames(args->dCert,
  13986. (char*)ssl->buffers.domainName.buffer,
  13987. (ssl->buffers.domainName.buffer == NULL ? 0 :
  13988. (word32)XSTRLEN(ssl->buffers.domainName.buffer)),
  13989. NULL) != 1) {
  13990. WOLFSSL_MSG(
  13991. "DomainName match on alt names failed too");
  13992. /* try to get peer key still */
  13993. ret = DOMAIN_NAME_MISMATCH;
  13994. WOLFSSL_ERROR_VERBOSE(ret);
  13995. }
  13996. }
  13997. #endif /* WOLFSSL_ALL_NO_CN_IN_SAN */
  13998. }
  13999. /* decode peer key */
  14000. switch (args->dCert->keyOID) {
  14001. #ifndef NO_RSA
  14002. #ifdef WC_RSA_PSS
  14003. case RSAPSSk:
  14004. #endif
  14005. case RSAk:
  14006. {
  14007. word32 keyIdx = 0;
  14008. int keyRet = 0;
  14009. if (ssl->peerRsaKey == NULL) {
  14010. keyRet = AllocKey(ssl, DYNAMIC_TYPE_RSA,
  14011. (void**)&ssl->peerRsaKey);
  14012. } else if (ssl->peerRsaKeyPresent) {
  14013. keyRet = ReuseKey(ssl, DYNAMIC_TYPE_RSA,
  14014. ssl->peerRsaKey);
  14015. ssl->peerRsaKeyPresent = 0;
  14016. }
  14017. if (keyRet != 0 || wc_RsaPublicKeyDecode(
  14018. args->dCert->publicKey, &keyIdx, ssl->peerRsaKey,
  14019. args->dCert->pubKeySize) != 0) {
  14020. ret = PEER_KEY_ERROR;
  14021. WOLFSSL_ERROR_VERBOSE(ret);
  14022. }
  14023. else {
  14024. ssl->peerRsaKeyPresent = 1;
  14025. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || \
  14026. defined(WOLFSSL_RENESAS_FSPSM_TLS)
  14027. /* copy encrypted tsip key index into ssl object */
  14028. if (args->dCert->sce_tsip_encRsaKeyIdx) {
  14029. if (!ssl->peerSceTsipEncRsaKeyIndex) {
  14030. ssl->peerSceTsipEncRsaKeyIndex = (byte*)XMALLOC(
  14031. TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  14032. ssl->heap, DYNAMIC_TYPE_RSA);
  14033. if (!ssl->peerSceTsipEncRsaKeyIndex) {
  14034. args->lastErr = MEMORY_E;
  14035. goto exit_ppc;
  14036. }
  14037. }
  14038. XMEMCPY(ssl->peerSceTsipEncRsaKeyIndex,
  14039. args->dCert->sce_tsip_encRsaKeyIdx,
  14040. TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY);
  14041. }
  14042. #endif
  14043. #ifdef HAVE_PK_CALLBACKS
  14044. #if defined(HAVE_SECURE_RENEGOTIATION) || \
  14045. defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  14046. if (ssl->buffers.peerRsaKey.buffer) {
  14047. XFREE(ssl->buffers.peerRsaKey.buffer,
  14048. ssl->heap, DYNAMIC_TYPE_RSA);
  14049. ssl->buffers.peerRsaKey.buffer = NULL;
  14050. }
  14051. #endif
  14052. ssl->buffers.peerRsaKey.buffer =
  14053. (byte*)XMALLOC(args->dCert->pubKeySize,
  14054. ssl->heap, DYNAMIC_TYPE_RSA);
  14055. if (ssl->buffers.peerRsaKey.buffer == NULL) {
  14056. ret = MEMORY_ERROR;
  14057. }
  14058. else {
  14059. XMEMCPY(ssl->buffers.peerRsaKey.buffer,
  14060. args->dCert->publicKey,
  14061. args->dCert->pubKeySize);
  14062. ssl->buffers.peerRsaKey.length =
  14063. args->dCert->pubKeySize;
  14064. }
  14065. #endif /* HAVE_PK_CALLBACKS */
  14066. }
  14067. /* check size of peer RSA key */
  14068. if (ret == 0 && ssl->peerRsaKeyPresent &&
  14069. !ssl->options.verifyNone &&
  14070. wc_RsaEncryptSize(ssl->peerRsaKey)
  14071. < ssl->options.minRsaKeySz) {
  14072. ret = RSA_KEY_SIZE_E;
  14073. WOLFSSL_ERROR_VERBOSE(ret);
  14074. WOLFSSL_MSG("Peer RSA key is too small");
  14075. }
  14076. break;
  14077. }
  14078. #endif /* NO_RSA */
  14079. #ifdef HAVE_ECC
  14080. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  14081. case SM2k:
  14082. #endif
  14083. case ECDSAk:
  14084. {
  14085. int keyRet = 0;
  14086. word32 idx = 0;
  14087. #if defined(WOLFSSL_RENESAS_FSPSM_TLS) || \
  14088. defined(WOLFSSL_RENESAS_TSIP_TLS)
  14089. /* copy encrypted tsip/sce key index into ssl object */
  14090. if (args->dCert->sce_tsip_encRsaKeyIdx) {
  14091. if (!ssl->peerSceTsipEncRsaKeyIndex) {
  14092. ssl->peerSceTsipEncRsaKeyIndex = (byte*)XMALLOC(
  14093. TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  14094. ssl->heap, DYNAMIC_TYPE_RSA);
  14095. if (!ssl->peerSceTsipEncRsaKeyIndex) {
  14096. args->lastErr = MEMORY_E;
  14097. ERROR_OUT(MEMORY_ERROR, exit_ppc);
  14098. }
  14099. }
  14100. XMEMCPY(ssl->peerSceTsipEncRsaKeyIndex,
  14101. args->dCert->sce_tsip_encRsaKeyIdx,
  14102. TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY);
  14103. }
  14104. #endif
  14105. if (ssl->peerEccDsaKey == NULL) {
  14106. /* alloc/init on demand */
  14107. keyRet = AllocKey(ssl, DYNAMIC_TYPE_ECC,
  14108. (void**)&ssl->peerEccDsaKey);
  14109. } else if (ssl->peerEccDsaKeyPresent) {
  14110. keyRet = ReuseKey(ssl, DYNAMIC_TYPE_ECC,
  14111. ssl->peerEccDsaKey);
  14112. ssl->peerEccDsaKeyPresent = 0;
  14113. }
  14114. if (keyRet != 0 ||
  14115. wc_EccPublicKeyDecode(args->dCert->publicKey, &idx,
  14116. ssl->peerEccDsaKey,
  14117. args->dCert->pubKeySize) != 0) {
  14118. ret = PEER_KEY_ERROR;
  14119. WOLFSSL_ERROR_VERBOSE(ret);
  14120. }
  14121. else {
  14122. ssl->peerEccDsaKeyPresent = 1;
  14123. #ifdef HAVE_PK_CALLBACKS
  14124. if (ssl->buffers.peerEccDsaKey.buffer)
  14125. XFREE(ssl->buffers.peerEccDsaKey.buffer,
  14126. ssl->heap, DYNAMIC_TYPE_ECC);
  14127. ssl->buffers.peerEccDsaKey.buffer =
  14128. (byte*)XMALLOC(args->dCert->pubKeySize,
  14129. ssl->heap, DYNAMIC_TYPE_ECC);
  14130. if (ssl->buffers.peerEccDsaKey.buffer == NULL) {
  14131. ERROR_OUT(MEMORY_ERROR, exit_ppc);
  14132. }
  14133. else {
  14134. XMEMCPY(ssl->buffers.peerEccDsaKey.buffer,
  14135. args->dCert->publicKey,
  14136. args->dCert->pubKeySize);
  14137. ssl->buffers.peerEccDsaKey.length =
  14138. args->dCert->pubKeySize;
  14139. }
  14140. #endif /* HAVE_PK_CALLBACKS */
  14141. }
  14142. /* check size of peer ECC key */
  14143. if (ret == 0 && ssl->peerEccDsaKeyPresent &&
  14144. !ssl->options.verifyNone &&
  14145. wc_ecc_size(ssl->peerEccDsaKey)
  14146. < ssl->options.minEccKeySz) {
  14147. ret = ECC_KEY_SIZE_E;
  14148. WOLFSSL_ERROR_VERBOSE(ret);
  14149. WOLFSSL_MSG("Peer ECC key is too small");
  14150. }
  14151. /* populate curve oid - if missing */
  14152. if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->ecdhCurveOID == 0)
  14153. ssl->ecdhCurveOID = args->dCert->pkCurveOID;
  14154. break;
  14155. }
  14156. #endif /* HAVE_ECC */
  14157. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  14158. case ED25519k:
  14159. {
  14160. int keyRet = 0;
  14161. if (ssl->peerEd25519Key == NULL) {
  14162. /* alloc/init on demand */
  14163. keyRet = AllocKey(ssl, DYNAMIC_TYPE_ED25519,
  14164. (void**)&ssl->peerEd25519Key);
  14165. } else if (ssl->peerEd25519KeyPresent) {
  14166. keyRet = ReuseKey(ssl, DYNAMIC_TYPE_ED25519,
  14167. ssl->peerEd25519Key);
  14168. ssl->peerEd25519KeyPresent = 0;
  14169. }
  14170. if (keyRet != 0 ||
  14171. wc_ed25519_import_public(args->dCert->publicKey,
  14172. args->dCert->pubKeySize,
  14173. ssl->peerEd25519Key)
  14174. != 0) {
  14175. ret = PEER_KEY_ERROR;
  14176. WOLFSSL_ERROR_VERBOSE(ret);
  14177. }
  14178. else {
  14179. ssl->peerEd25519KeyPresent = 1;
  14180. #ifdef HAVE_PK_CALLBACKS
  14181. ssl->buffers.peerEd25519Key.buffer =
  14182. (byte*)XMALLOC(args->dCert->pubKeySize,
  14183. ssl->heap, DYNAMIC_TYPE_ED25519);
  14184. if (ssl->buffers.peerEd25519Key.buffer == NULL) {
  14185. ERROR_OUT(MEMORY_ERROR, exit_ppc);
  14186. }
  14187. else {
  14188. XMEMCPY(ssl->buffers.peerEd25519Key.buffer,
  14189. args->dCert->publicKey,
  14190. args->dCert->pubKeySize);
  14191. ssl->buffers.peerEd25519Key.length =
  14192. args->dCert->pubKeySize;
  14193. }
  14194. #endif /*HAVE_PK_CALLBACKS */
  14195. }
  14196. /* check size of peer ECC key */
  14197. if (ret == 0 && ssl->peerEd25519KeyPresent &&
  14198. !ssl->options.verifyNone &&
  14199. ED25519_KEY_SIZE < ssl->options.minEccKeySz) {
  14200. ret = ECC_KEY_SIZE_E;
  14201. WOLFSSL_ERROR_VERBOSE(ret);
  14202. WOLFSSL_MSG("Peer ECC key is too small");
  14203. }
  14204. /* populate curve oid - if missing */
  14205. if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->ecdhCurveOID == 0)
  14206. ssl->ecdhCurveOID = ECC_X25519_OID;
  14207. break;
  14208. }
  14209. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */
  14210. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  14211. case ED448k:
  14212. {
  14213. int keyRet = 0;
  14214. if (ssl->peerEd448Key == NULL) {
  14215. /* alloc/init on demand */
  14216. keyRet = AllocKey(ssl, DYNAMIC_TYPE_ED448,
  14217. (void**)&ssl->peerEd448Key);
  14218. } else if (ssl->peerEd448KeyPresent) {
  14219. keyRet = ReuseKey(ssl, DYNAMIC_TYPE_ED448,
  14220. ssl->peerEd448Key);
  14221. ssl->peerEd448KeyPresent = 0;
  14222. }
  14223. if (keyRet != 0 ||
  14224. wc_ed448_import_public(args->dCert->publicKey,
  14225. args->dCert->pubKeySize,
  14226. ssl->peerEd448Key) != 0) {
  14227. ret = PEER_KEY_ERROR;
  14228. WOLFSSL_ERROR_VERBOSE(ret);
  14229. }
  14230. else {
  14231. ssl->peerEd448KeyPresent = 1;
  14232. #ifdef HAVE_PK_CALLBACKS
  14233. ssl->buffers.peerEd448Key.buffer =
  14234. (byte*)XMALLOC(args->dCert->pubKeySize,
  14235. ssl->heap, DYNAMIC_TYPE_ED448);
  14236. if (ssl->buffers.peerEd448Key.buffer == NULL) {
  14237. ERROR_OUT(MEMORY_ERROR, exit_ppc);
  14238. }
  14239. else {
  14240. XMEMCPY(ssl->buffers.peerEd448Key.buffer,
  14241. args->dCert->publicKey,
  14242. args->dCert->pubKeySize);
  14243. ssl->buffers.peerEd448Key.length =
  14244. args->dCert->pubKeySize;
  14245. }
  14246. #endif /*HAVE_PK_CALLBACKS */
  14247. }
  14248. /* check size of peer ECC key */
  14249. if (ret == 0 && ssl->peerEd448KeyPresent &&
  14250. !ssl->options.verifyNone &&
  14251. ED448_KEY_SIZE < ssl->options.minEccKeySz) {
  14252. ret = ECC_KEY_SIZE_E;
  14253. WOLFSSL_ERROR_VERBOSE(ret);
  14254. WOLFSSL_MSG("Peer ECC key is too small");
  14255. }
  14256. /* populate curve oid - if missing */
  14257. if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->ecdhCurveOID == 0)
  14258. ssl->ecdhCurveOID = ECC_X448_OID;
  14259. break;
  14260. }
  14261. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
  14262. #if defined(HAVE_FALCON)
  14263. case FALCON_LEVEL1k:
  14264. case FALCON_LEVEL5k:
  14265. {
  14266. int keyRet = 0;
  14267. if (ssl->peerFalconKey == NULL) {
  14268. /* alloc/init on demand */
  14269. keyRet = AllocKey(ssl, DYNAMIC_TYPE_FALCON,
  14270. (void**)&ssl->peerFalconKey);
  14271. } else if (ssl->peerFalconKeyPresent) {
  14272. keyRet = ReuseKey(ssl, DYNAMIC_TYPE_FALCON,
  14273. ssl->peerFalconKey);
  14274. ssl->peerFalconKeyPresent = 0;
  14275. }
  14276. if (keyRet == 0) {
  14277. if (args->dCert->keyOID == FALCON_LEVEL1k) {
  14278. keyRet = wc_falcon_set_level(ssl->peerFalconKey,
  14279. 1);
  14280. }
  14281. else {
  14282. keyRet = wc_falcon_set_level(ssl->peerFalconKey,
  14283. 5);
  14284. }
  14285. }
  14286. if (keyRet != 0 ||
  14287. wc_falcon_import_public(args->dCert->publicKey,
  14288. args->dCert->pubKeySize,
  14289. ssl->peerFalconKey) != 0) {
  14290. ret = PEER_KEY_ERROR;
  14291. WOLFSSL_ERROR_VERBOSE(ret);
  14292. }
  14293. else {
  14294. ssl->peerFalconKeyPresent = 1;
  14295. }
  14296. /* check size of peer Falcon key */
  14297. if (ret == 0 && ssl->peerFalconKeyPresent &&
  14298. !ssl->options.verifyNone &&
  14299. FALCON_MAX_KEY_SIZE <
  14300. ssl->options.minFalconKeySz) {
  14301. ret = FALCON_KEY_SIZE_E;
  14302. WOLFSSL_ERROR_VERBOSE(ret);
  14303. WOLFSSL_MSG("Peer Falcon key is too small");
  14304. }
  14305. break;
  14306. }
  14307. #endif /* HAVE_FALCON */
  14308. #if defined(HAVE_DILITHIUM) && \
  14309. !defined(WOLFSSL_DILITHIUM_NO_VERIFY)
  14310. case DILITHIUM_LEVEL2k:
  14311. case DILITHIUM_LEVEL3k:
  14312. case DILITHIUM_LEVEL5k:
  14313. {
  14314. int keyRet = 0;
  14315. if (ssl->peerDilithiumKey == NULL) {
  14316. /* alloc/init on demand */
  14317. keyRet = AllocKey(ssl, DYNAMIC_TYPE_DILITHIUM,
  14318. (void**)&ssl->peerDilithiumKey);
  14319. } else if (ssl->peerDilithiumKeyPresent) {
  14320. keyRet = ReuseKey(ssl, DYNAMIC_TYPE_DILITHIUM,
  14321. ssl->peerDilithiumKey);
  14322. ssl->peerDilithiumKeyPresent = 0;
  14323. }
  14324. if (keyRet == 0) {
  14325. if (args->dCert->keyOID == DILITHIUM_LEVEL2k) {
  14326. keyRet = wc_dilithium_set_level(
  14327. ssl->peerDilithiumKey, 2);
  14328. }
  14329. else if (args->dCert->keyOID == DILITHIUM_LEVEL3k) {
  14330. keyRet = wc_dilithium_set_level(
  14331. ssl->peerDilithiumKey, 3);
  14332. }
  14333. else if (args->dCert->keyOID == DILITHIUM_LEVEL5k) {
  14334. keyRet = wc_dilithium_set_level(
  14335. ssl->peerDilithiumKey, 5);
  14336. }
  14337. }
  14338. if (keyRet != 0 ||
  14339. wc_dilithium_import_public(args->dCert->publicKey,
  14340. args->dCert->pubKeySize,
  14341. ssl->peerDilithiumKey)
  14342. != 0) {
  14343. ret = PEER_KEY_ERROR;
  14344. }
  14345. else {
  14346. ssl->peerDilithiumKeyPresent = 1;
  14347. }
  14348. /* check size of peer Dilithium key */
  14349. if (ret == 0 && ssl->peerDilithiumKeyPresent &&
  14350. !ssl->options.verifyNone &&
  14351. DILITHIUM_MAX_KEY_SIZE <
  14352. ssl->options.minDilithiumKeySz) {
  14353. ret = DILITHIUM_KEY_SIZE_E;
  14354. WOLFSSL_MSG("Peer Dilithium key is too small");
  14355. }
  14356. break;
  14357. }
  14358. #endif /* HAVE_DILITHIUM */
  14359. default:
  14360. break;
  14361. }
  14362. /* args->dCert free'd in function cleanup after callback */
  14363. } /* if (count > 0) */
  14364. /* Check for error */
  14365. if (args->fatal && ret != 0) {
  14366. goto exit_ppc;
  14367. }
  14368. /* Advance state and proceed */
  14369. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  14370. } /* case TLS_ASYNC_VERIFY */
  14371. FALL_THROUGH;
  14372. case TLS_ASYNC_FINALIZE:
  14373. {
  14374. /* load last error */
  14375. if (args->lastErr != 0 && ret == 0) {
  14376. ret = args->lastErr;
  14377. }
  14378. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  14379. /* limit compliant with OpenSSL verify Depth + 1
  14380. * OpenSSL tries to expand the chain one longer than limit until
  14381. * reaching an ultimately trusted issuer. Becoming failure if
  14382. * we hit the limit, with WOLFSSL_X509_V_ERR_CERT_CHAIN_TOO_LONG
  14383. */
  14384. if (args->untrustedDepth > (ssl->options.verifyDepth + 1)) {
  14385. if (ssl->peerVerifyRet == 0) /* Return first cert error here */
  14386. ssl->peerVerifyRet = WOLFSSL_X509_V_ERR_CERT_CHAIN_TOO_LONG;
  14387. ret = MAX_CHAIN_ERROR;
  14388. WOLFSSL_ERROR_VERBOSE(ret);
  14389. }
  14390. #endif
  14391. #if defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS)
  14392. /* If we can't validate the peer cert chain against the CAs loaded
  14393. * into wolfSSL, try to validate against the system certificates
  14394. * using Apple's native trust APIs */
  14395. if ((ret != 0) && (ssl->ctx->doAppleNativeCertValidationFlag)) {
  14396. if (DoAppleNativeCertValidation(args->certs,
  14397. args->totalCerts)) {
  14398. WOLFSSL_MSG("Apple native cert chain validation SUCCESS");
  14399. ret = 0;
  14400. }
  14401. else {
  14402. WOLFSSL_MSG("Apple native cert chain validation FAIL");
  14403. }
  14404. }
  14405. #endif /* defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS) */
  14406. /* Do verify callback */
  14407. ret = DoVerifyCallback(SSL_CM(ssl), ssl, ret, args);
  14408. if (ssl->options.verifyNone &&
  14409. (ret == WC_NO_ERR_TRACE(CRL_MISSING) ||
  14410. ret == WC_NO_ERR_TRACE(CRL_CERT_REVOKED) ||
  14411. ret == WC_NO_ERR_TRACE(CRL_CERT_DATE_ERR))) {
  14412. WOLFSSL_MSG("Ignoring CRL problem based on verify setting");
  14413. ret = ssl->error = 0;
  14414. }
  14415. if (ret != 0) {
  14416. if (!ssl->options.verifyNone) {
  14417. DoCertFatalAlert(ssl, ret);
  14418. }
  14419. ssl->error = ret; /* Report SSL error */
  14420. }
  14421. if (ret == 0 && ssl->options.side == WOLFSSL_CLIENT_END) {
  14422. ssl->options.serverState = SERVER_CERT_COMPLETE;
  14423. }
  14424. if (IsEncryptionOn(ssl, 0)) {
  14425. args->idx += ssl->keys.padSz;
  14426. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  14427. if (ssl->options.startedETMRead)
  14428. args->idx += MacSize(ssl);
  14429. #endif
  14430. }
  14431. /* Advance state and proceed */
  14432. ssl->options.asyncState = TLS_ASYNC_END;
  14433. } /* case TLS_ASYNC_FINALIZE */
  14434. FALL_THROUGH;
  14435. case TLS_ASYNC_END:
  14436. {
  14437. /* Set final index */
  14438. *inOutIdx = args->idx;
  14439. break;
  14440. }
  14441. default:
  14442. ret = INPUT_CASE_ERROR;
  14443. break;
  14444. } /* switch(ssl->options.asyncState) */
  14445. exit_ppc:
  14446. WOLFSSL_LEAVE("ProcessPeerCerts", ret);
  14447. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  14448. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) ||
  14449. ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) {
  14450. /* Mark message as not received so it can process again */
  14451. ssl->msgsReceived.got_certificate = 0;
  14452. return ret;
  14453. }
  14454. #endif /* WOLFSSL_ASYNC_CRYPT || WOLFSSL_NONBLOCK_OCSP */
  14455. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  14456. /* Cleanup async */
  14457. FreeAsyncCtx(ssl, 0);
  14458. #elif defined(WOLFSSL_SMALL_STACK)
  14459. if (args)
  14460. {
  14461. FreeProcPeerCertArgs(ssl, args);
  14462. }
  14463. #else
  14464. FreeProcPeerCertArgs(ssl, args);
  14465. #endif /* WOLFSSL_ASYNC_CRYPT || WOLFSSL_NONBLOCK_OCSP || WOLFSSL_SMALL_STACK */
  14466. #if !defined(WOLFSSL_ASYNC_CRYPT) && defined(WOLFSSL_SMALL_STACK)
  14467. XFREE(args, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14468. #endif
  14469. FreeKeyExchange(ssl);
  14470. return ret;
  14471. }
  14472. #endif
  14473. #ifndef WOLFSSL_NO_TLS12
  14474. #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  14475. /* handle processing of certificate (11) */
  14476. static int DoCertificate(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  14477. word32 size)
  14478. {
  14479. int ret;
  14480. WOLFSSL_START(WC_FUNC_CERTIFICATE_DO);
  14481. WOLFSSL_ENTER("DoCertificate");
  14482. #ifdef SESSION_CERTS
  14483. /* Reset the session cert chain count in case the session resume failed,
  14484. * do not reset if we are resuming after an async wait */
  14485. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  14486. if (ssl->error != WC_NO_ERR_TRACE(OCSP_WANT_READ) &&
  14487. ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E))
  14488. #endif
  14489. {
  14490. ssl->session->chain.count = 0;
  14491. #ifdef WOLFSSL_ALT_CERT_CHAINS
  14492. ssl->session->altChain.count = 0;
  14493. #endif
  14494. }
  14495. #endif /* SESSION_CERTS */
  14496. ret = ProcessPeerCerts(ssl, input, inOutIdx, size);
  14497. #ifdef OPENSSL_EXTRA
  14498. ssl->options.serverState = SERVER_CERT_COMPLETE;
  14499. #endif
  14500. WOLFSSL_LEAVE("DoCertificate", ret);
  14501. WOLFSSL_END(WC_FUNC_CERTIFICATE_DO);
  14502. return ret;
  14503. }
  14504. /* handle processing of certificate_status (22) */
  14505. static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  14506. word32 size)
  14507. {
  14508. int ret = 0;
  14509. byte status_type;
  14510. word32 status_length;
  14511. int endCertificateOK = 0;
  14512. WOLFSSL_START(WC_FUNC_CERTIFICATE_STATUS_DO);
  14513. WOLFSSL_ENTER("DoCertificateStatus");
  14514. if (size < ENUM_LEN + OPAQUE24_LEN)
  14515. return BUFFER_ERROR;
  14516. status_type = input[(*inOutIdx)++];
  14517. c24to32(input + *inOutIdx, &status_length);
  14518. *inOutIdx += OPAQUE24_LEN;
  14519. if (size != ENUM_LEN + OPAQUE24_LEN + status_length)
  14520. return BUFFER_ERROR;
  14521. switch (status_type) {
  14522. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  14523. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  14524. /* WOLFSSL_CSR_OCSP overlaps with WOLFSSL_CSR2_OCSP */
  14525. case WOLFSSL_CSR2_OCSP:
  14526. ret = ProcessCSR(ssl, input, inOutIdx, status_length);
  14527. endCertificateOK = (ret == 0);
  14528. break;
  14529. #endif
  14530. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  14531. case WOLFSSL_CSR2_OCSP_MULTI: {
  14532. OcspRequest* request;
  14533. word32 list_length = status_length;
  14534. byte idx = 0;
  14535. Signer *pendingCAs = NULL;
  14536. #ifdef WOLFSSL_SMALL_STACK
  14537. CertStatus* status;
  14538. OcspEntry* single;
  14539. OcspResponse* response;
  14540. #else
  14541. CertStatus status[1];
  14542. OcspEntry single[1];
  14543. OcspResponse response[1];
  14544. #endif
  14545. if (!ssl->status_request_v2)
  14546. return BUFFER_ERROR;
  14547. ssl->status_request_v2 = 0;
  14548. pendingCAs = TLSX_CSR2_GetPendingSigners(ssl->extensions);
  14549. #ifdef WOLFSSL_SMALL_STACK
  14550. status = (CertStatus*)XMALLOC(sizeof(CertStatus), ssl->heap,
  14551. DYNAMIC_TYPE_OCSP_STATUS);
  14552. single = (OcspEntry*)XMALLOC(sizeof(OcspEntry), ssl->heap,
  14553. DYNAMIC_TYPE_OCSP_ENTRY);
  14554. response = (OcspResponse*)XMALLOC(sizeof(OcspResponse), ssl->heap,
  14555. DYNAMIC_TYPE_OCSP_REQUEST);
  14556. if (status == NULL || single == NULL || response == NULL) {
  14557. XFREE(status, ssl->heap, DYNAMIC_TYPE_OCSP_STATUS);
  14558. XFREE(single, ssl->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  14559. XFREE(response, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  14560. return MEMORY_ERROR;
  14561. }
  14562. #endif
  14563. while (list_length && ret == 0) {
  14564. if (OPAQUE24_LEN > list_length) {
  14565. ret = BUFFER_ERROR;
  14566. break;
  14567. }
  14568. c24to32(input + *inOutIdx, &status_length);
  14569. *inOutIdx += OPAQUE24_LEN;
  14570. list_length -= OPAQUE24_LEN;
  14571. if (status_length > list_length) {
  14572. ret = BUFFER_ERROR;
  14573. break;
  14574. }
  14575. if (status_length) {
  14576. InitOcspResponse(response, single, status, input +*inOutIdx,
  14577. status_length, ssl->heap);
  14578. response->pendingCAs = pendingCAs;
  14579. if ((OcspResponseDecode(response, SSL_CM(ssl), ssl->heap,
  14580. 0) != 0)
  14581. || (response->responseStatus != OCSP_SUCCESSFUL)
  14582. || (response->single->status->status != CERT_GOOD))
  14583. ret = BAD_CERTIFICATE_STATUS_ERROR;
  14584. if (ret == 0) {
  14585. request = (OcspRequest*)TLSX_CSR2_GetRequest(
  14586. ssl->extensions, status_type, idx);
  14587. if (request == NULL) {
  14588. ret = BAD_CERTIFICATE_STATUS_ERROR;
  14589. }
  14590. else if (CompareOcspReqResp(request, response) != 0) {
  14591. ret = BAD_CERTIFICATE_STATUS_ERROR;
  14592. }
  14593. else {
  14594. if (idx == 0) /* server cert must be OK */
  14595. endCertificateOK = 1;
  14596. }
  14597. }
  14598. /* only frees 'single' if single->isDynamic is set */
  14599. FreeOcspResponse(response);
  14600. *inOutIdx += status_length;
  14601. list_length -= status_length;
  14602. }
  14603. idx++;
  14604. }
  14605. ssl->status_request_v2 = 0;
  14606. #ifdef WOLFSSL_SMALL_STACK
  14607. XFREE(status, NULL, DYNAMIC_TYPE_OCSP_STATUS);
  14608. XFREE(single, NULL, DYNAMIC_TYPE_OCSP_ENTRY);
  14609. XFREE(response, NULL, DYNAMIC_TYPE_OCSP_REQUEST);
  14610. #endif
  14611. }
  14612. break;
  14613. #endif
  14614. default:
  14615. ret = BUFFER_ERROR;
  14616. }
  14617. /* end certificate MUST be present */
  14618. if (endCertificateOK == 0)
  14619. ret = BAD_CERTIFICATE_STATUS_ERROR;
  14620. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  14621. if (ret == 0) {
  14622. if (TLSX_CSR2_MergePendingCA(ssl) < 0) {
  14623. WOLFSSL_MSG("Failed to merge pending CAs");
  14624. }
  14625. }
  14626. else {
  14627. TLSX_CSR2_ClearPendingCA(ssl);
  14628. }
  14629. #endif
  14630. if (ret != 0) {
  14631. WOLFSSL_ERROR_VERBOSE(ret);
  14632. SendAlert(ssl, alert_fatal, bad_certificate_status_response);
  14633. }
  14634. if (IsEncryptionOn(ssl, 0)) {
  14635. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  14636. if (ssl->options.startedETMRead) {
  14637. word32 digestSz = MacSize(ssl);
  14638. if (*inOutIdx + ssl->keys.padSz + digestSz > size)
  14639. return BUFFER_E;
  14640. *inOutIdx += ssl->keys.padSz + digestSz;
  14641. }
  14642. else
  14643. #endif
  14644. {
  14645. if (*inOutIdx + ssl->keys.padSz > size)
  14646. return BUFFER_E;
  14647. *inOutIdx += ssl->keys.padSz;
  14648. }
  14649. }
  14650. WOLFSSL_LEAVE("DoCertificateStatus", ret);
  14651. WOLFSSL_END(WC_FUNC_CERTIFICATE_STATUS_DO);
  14652. return ret;
  14653. }
  14654. #endif
  14655. #endif /* !WOLFSSL_NO_TLS12 */
  14656. #endif /* !NO_CERTS */
  14657. #ifndef WOLFSSL_NO_TLS12
  14658. static int DoHelloRequest(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  14659. word32 size, word32 totalSz)
  14660. {
  14661. (void)input;
  14662. WOLFSSL_START(WC_FUNC_HELLO_REQUEST_DO);
  14663. WOLFSSL_ENTER("DoHelloRequest");
  14664. if (size) /* must be 0 */
  14665. return BUFFER_ERROR;
  14666. if (IsEncryptionOn(ssl, 0)) {
  14667. /* If size == totalSz then we are in DtlsMsgDrain so no need to worry
  14668. * about padding */
  14669. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  14670. if (ssl->options.startedETMRead) {
  14671. word32 digestSz = MacSize(ssl);
  14672. if (size != totalSz &&
  14673. *inOutIdx + ssl->keys.padSz + digestSz > totalSz)
  14674. return BUFFER_E;
  14675. *inOutIdx += ssl->keys.padSz + digestSz;
  14676. }
  14677. else
  14678. #endif
  14679. {
  14680. /* access beyond input + size should be checked against totalSz */
  14681. if (size != totalSz &&
  14682. *inOutIdx + ssl->keys.padSz > totalSz)
  14683. return BUFFER_E;
  14684. *inOutIdx += ssl->keys.padSz;
  14685. }
  14686. }
  14687. if (ssl->options.side == WOLFSSL_SERVER_END) {
  14688. SendAlert(ssl, alert_fatal, unexpected_message); /* try */
  14689. WOLFSSL_ERROR_VERBOSE(FATAL_ERROR);
  14690. return FATAL_ERROR;
  14691. }
  14692. #ifdef HAVE_SECURE_RENEGOTIATION
  14693. else if (ssl->secure_renegotiation && ssl->secure_renegotiation->enabled) {
  14694. ssl->secure_renegotiation->startScr = 1;
  14695. WOLFSSL_LEAVE("DoHelloRequest", 0);
  14696. WOLFSSL_END(WC_FUNC_HELLO_REQUEST_DO);
  14697. return 0;
  14698. }
  14699. #endif
  14700. else {
  14701. return SendAlert(ssl, alert_warning, no_renegotiation);
  14702. }
  14703. }
  14704. int DoFinished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, word32 size,
  14705. word32 totalSz, int sniff)
  14706. {
  14707. word32 finishedSz = (ssl->options.tls ? TLS_FINISHED_SZ : FINISHED_SZ);
  14708. WOLFSSL_START(WC_FUNC_FINISHED_DO);
  14709. WOLFSSL_ENTER("DoFinished");
  14710. if (finishedSz != size)
  14711. return BUFFER_ERROR;
  14712. /* check against totalSz
  14713. * If size == totalSz then we are in DtlsMsgDrain so no need to worry about
  14714. * padding */
  14715. if (size != totalSz) {
  14716. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  14717. if (ssl->options.startedETMRead) {
  14718. if (*inOutIdx + size + ssl->keys.padSz + MacSize(ssl) > totalSz)
  14719. return BUFFER_E;
  14720. }
  14721. else
  14722. #endif
  14723. {
  14724. if (*inOutIdx + size + ssl->keys.padSz > totalSz)
  14725. return BUFFER_E;
  14726. }
  14727. }
  14728. #ifdef WOLFSSL_CALLBACKS
  14729. if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
  14730. if (ssl->toInfoOn) AddLateName("Finished", &ssl->timeoutInfo);
  14731. #endif
  14732. if (sniff == NO_SNIFF) {
  14733. if (XMEMCMP(input + *inOutIdx, &ssl->hsHashes->verifyHashes,size) != 0){
  14734. WOLFSSL_MSG("Verify finished error on hashes");
  14735. WOLFSSL_ERROR_VERBOSE(VERIFY_FINISHED_ERROR);
  14736. return VERIFY_FINISHED_ERROR;
  14737. }
  14738. }
  14739. #ifdef HAVE_SECURE_RENEGOTIATION
  14740. if (ssl->secure_renegotiation) {
  14741. /* save peer's state */
  14742. if (ssl->options.side == WOLFSSL_CLIENT_END)
  14743. XMEMCPY(ssl->secure_renegotiation->server_verify_data,
  14744. input + *inOutIdx, TLS_FINISHED_SZ);
  14745. else
  14746. XMEMCPY(ssl->secure_renegotiation->client_verify_data,
  14747. input + *inOutIdx, TLS_FINISHED_SZ);
  14748. ssl->secure_renegotiation->verifySet = 1;
  14749. }
  14750. #endif
  14751. #ifdef WOLFSSL_HAVE_TLS_UNIQUE
  14752. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  14753. XMEMCPY(ssl->serverFinished,
  14754. input + *inOutIdx, TLS_FINISHED_SZ);
  14755. ssl->serverFinished_len = TLS_FINISHED_SZ;
  14756. }
  14757. else {
  14758. XMEMCPY(ssl->clientFinished,
  14759. input + *inOutIdx, TLS_FINISHED_SZ);
  14760. ssl->clientFinished_len = TLS_FINISHED_SZ;
  14761. }
  14762. #endif
  14763. /* force input exhaustion at ProcessReply consuming padSz */
  14764. *inOutIdx += size + ssl->keys.padSz;
  14765. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  14766. if (ssl->options.startedETMRead)
  14767. *inOutIdx += MacSize(ssl);
  14768. #endif
  14769. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  14770. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  14771. #ifdef OPENSSL_EXTRA
  14772. ssl->cbmode = SSL_CB_MODE_WRITE;
  14773. ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
  14774. #endif
  14775. if (!ssl->options.resuming) {
  14776. #ifdef OPENSSL_EXTRA
  14777. if (ssl->CBIS != NULL) {
  14778. ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, WOLFSSL_SUCCESS);
  14779. }
  14780. #endif
  14781. ssl->options.handShakeState = HANDSHAKE_DONE;
  14782. ssl->options.handShakeDone = 1;
  14783. #ifdef HAVE_SECURE_RENEGOTIATION
  14784. ssl->options.resumed = ssl->options.resuming;
  14785. #endif
  14786. }
  14787. }
  14788. else {
  14789. ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
  14790. #ifdef OPENSSL_EXTRA
  14791. ssl->cbmode = SSL_CB_MODE_READ;
  14792. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  14793. #endif
  14794. if (ssl->options.resuming) {
  14795. #ifdef OPENSSL_EXTRA
  14796. if (ssl->CBIS != NULL) {
  14797. ssl->CBIS(ssl, SSL_CB_ACCEPT_LOOP, WOLFSSL_SUCCESS);
  14798. }
  14799. #endif
  14800. ssl->options.handShakeState = HANDSHAKE_DONE;
  14801. ssl->options.handShakeDone = 1;
  14802. #ifdef HAVE_SECURE_RENEGOTIATION
  14803. ssl->options.resumed = ssl->options.resuming;
  14804. #endif
  14805. }
  14806. }
  14807. #ifdef WOLFSSL_DTLS
  14808. if (ssl->options.dtls) {
  14809. if ((!ssl->options.resuming && ssl->options.side == WOLFSSL_CLIENT_END) ||
  14810. (ssl->options.resuming && ssl->options.side == WOLFSSL_SERVER_END)){
  14811. DtlsMsgPoolReset(ssl);
  14812. ssl->keys.dtls_handshake_number = 0;
  14813. ssl->keys.dtls_expected_peer_handshake_number = 0;
  14814. }
  14815. }
  14816. #endif
  14817. WOLFSSL_LEAVE("DoFinished", 0);
  14818. WOLFSSL_END(WC_FUNC_FINISHED_DO);
  14819. return 0;
  14820. }
  14821. /* Make sure no duplicates, no fast forward, or other problems; 0 on success */
  14822. static int SanityCheckMsgReceived(WOLFSSL* ssl, byte type)
  14823. {
  14824. /* verify not a duplicate, mark received, check state */
  14825. switch (type) {
  14826. #ifndef NO_WOLFSSL_CLIENT
  14827. case hello_request:
  14828. #ifndef NO_WOLFSSL_SERVER
  14829. if (ssl->options.side == WOLFSSL_SERVER_END) {
  14830. WOLFSSL_MSG("HelloRequest received by server");
  14831. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  14832. return SIDE_ERROR;
  14833. }
  14834. #endif
  14835. if (ssl->msgsReceived.got_hello_request) {
  14836. WOLFSSL_MSG("Duplicate HelloRequest received");
  14837. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  14838. return DUPLICATE_MSG_E;
  14839. }
  14840. ssl->msgsReceived.got_hello_request = 1;
  14841. break;
  14842. #endif
  14843. #ifndef NO_WOLFSSL_SERVER
  14844. case client_hello:
  14845. #ifndef NO_WOLFSSL_CLIENT
  14846. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  14847. WOLFSSL_MSG("ClientHello received by client");
  14848. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  14849. return SIDE_ERROR;
  14850. }
  14851. #endif
  14852. if (ssl->msgsReceived.got_client_hello) {
  14853. WOLFSSL_MSG("Duplicate ClientHello received");
  14854. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  14855. return DUPLICATE_MSG_E;
  14856. }
  14857. ssl->msgsReceived.got_client_hello = 1;
  14858. break;
  14859. #endif
  14860. #ifndef NO_WOLFSSL_CLIENT
  14861. case server_hello:
  14862. #ifndef NO_WOLFSSL_SERVER
  14863. if (ssl->options.side == WOLFSSL_SERVER_END) {
  14864. WOLFSSL_MSG("ServerHello received by server");
  14865. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  14866. return SIDE_ERROR;
  14867. }
  14868. #endif
  14869. if (ssl->msgsReceived.got_server_hello) {
  14870. WOLFSSL_MSG("Duplicate ServerHello received");
  14871. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  14872. return DUPLICATE_MSG_E;
  14873. }
  14874. ssl->msgsReceived.got_server_hello = 1;
  14875. break;
  14876. #endif
  14877. #ifndef NO_WOLFSSL_CLIENT
  14878. case hello_verify_request:
  14879. #ifndef NO_WOLFSSL_SERVER
  14880. if (ssl->options.side == WOLFSSL_SERVER_END) {
  14881. WOLFSSL_MSG("HelloVerifyRequest received by server");
  14882. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  14883. return SIDE_ERROR;
  14884. }
  14885. #endif
  14886. if (ssl->msgsReceived.got_hello_verify_request) {
  14887. WOLFSSL_MSG("Duplicate HelloVerifyRequest received");
  14888. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  14889. return DUPLICATE_MSG_E;
  14890. }
  14891. if (ssl->msgsReceived.got_hello_retry_request) {
  14892. WOLFSSL_MSG("Received HelloVerifyRequest after a "
  14893. "HelloRetryRequest");
  14894. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  14895. return VERSION_ERROR;
  14896. }
  14897. ssl->msgsReceived.got_hello_verify_request = 1;
  14898. break;
  14899. #endif
  14900. #ifndef NO_WOLFSSL_CLIENT
  14901. case session_ticket:
  14902. #ifndef NO_WOLFSSL_SERVER
  14903. if (ssl->options.side == WOLFSSL_SERVER_END) {
  14904. WOLFSSL_MSG("SessionTicket received by server");
  14905. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  14906. return SIDE_ERROR;
  14907. }
  14908. #endif
  14909. if (ssl->msgsReceived.got_session_ticket) {
  14910. WOLFSSL_MSG("Duplicate SessionTicket received");
  14911. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  14912. return DUPLICATE_MSG_E;
  14913. }
  14914. ssl->msgsReceived.got_session_ticket = 1;
  14915. break;
  14916. #endif
  14917. case certificate:
  14918. if (ssl->msgsReceived.got_certificate) {
  14919. WOLFSSL_MSG("Duplicate Certificate received");
  14920. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  14921. return DUPLICATE_MSG_E;
  14922. }
  14923. ssl->msgsReceived.got_certificate = 1;
  14924. #ifndef NO_WOLFSSL_CLIENT
  14925. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  14926. if ( ssl->msgsReceived.got_server_hello == 0) {
  14927. WOLFSSL_MSG("No ServerHello before Cert");
  14928. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  14929. return OUT_OF_ORDER_E;
  14930. }
  14931. }
  14932. #endif
  14933. #ifndef NO_WOLFSSL_SERVER
  14934. if (ssl->options.side == WOLFSSL_SERVER_END) {
  14935. if ( ssl->msgsReceived.got_client_hello == 0) {
  14936. WOLFSSL_MSG("No ClientHello before Cert");
  14937. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  14938. return OUT_OF_ORDER_E;
  14939. }
  14940. }
  14941. #endif
  14942. break;
  14943. #ifndef NO_WOLFSSL_CLIENT
  14944. case certificate_status:
  14945. #ifndef NO_WOLFSSL_SERVER
  14946. if (ssl->options.side == WOLFSSL_SERVER_END) {
  14947. WOLFSSL_MSG("CertificateStatus received by server");
  14948. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  14949. return SIDE_ERROR;
  14950. }
  14951. #endif
  14952. if (ssl->msgsReceived.got_certificate_status) {
  14953. WOLFSSL_MSG("Duplicate CertificateStatus received");
  14954. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  14955. return DUPLICATE_MSG_E;
  14956. }
  14957. ssl->msgsReceived.got_certificate_status = 1;
  14958. if (ssl->msgsReceived.got_certificate == 0) {
  14959. WOLFSSL_MSG("No Certificate before CertificateStatus");
  14960. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  14961. return OUT_OF_ORDER_E;
  14962. }
  14963. if (ssl->msgsReceived.got_server_key_exchange != 0) {
  14964. WOLFSSL_MSG("CertificateStatus after ServerKeyExchange");
  14965. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  14966. return OUT_OF_ORDER_E;
  14967. }
  14968. break;
  14969. #endif
  14970. #ifndef NO_WOLFSSL_CLIENT
  14971. case server_key_exchange:
  14972. #ifndef NO_WOLFSSL_SERVER
  14973. if (ssl->options.side == WOLFSSL_SERVER_END) {
  14974. WOLFSSL_MSG("ServerKeyExchange received by server");
  14975. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  14976. return SIDE_ERROR;
  14977. }
  14978. #endif
  14979. if (ssl->msgsReceived.got_server_key_exchange) {
  14980. WOLFSSL_MSG("Duplicate ServerKeyExchange received");
  14981. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  14982. return DUPLICATE_MSG_E;
  14983. }
  14984. ssl->msgsReceived.got_server_key_exchange = 1;
  14985. if (ssl->msgsReceived.got_server_hello == 0) {
  14986. WOLFSSL_MSG("No ServerHello before ServerKeyExchange");
  14987. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  14988. return OUT_OF_ORDER_E;
  14989. }
  14990. break;
  14991. #endif
  14992. #ifndef NO_WOLFSSL_CLIENT
  14993. case certificate_request:
  14994. #ifndef NO_WOLFSSL_SERVER
  14995. if (ssl->options.side == WOLFSSL_SERVER_END) {
  14996. WOLFSSL_MSG("CertificateRequest received by server");
  14997. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  14998. return SIDE_ERROR;
  14999. }
  15000. #endif
  15001. if (ssl->msgsReceived.got_certificate_request) {
  15002. WOLFSSL_MSG("Duplicate CertificateRequest received");
  15003. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  15004. return DUPLICATE_MSG_E;
  15005. }
  15006. ssl->msgsReceived.got_certificate_request = 1;
  15007. break;
  15008. #endif
  15009. #ifndef NO_WOLFSSL_CLIENT
  15010. case server_hello_done:
  15011. #ifndef NO_WOLFSSL_SERVER
  15012. if (ssl->options.side == WOLFSSL_SERVER_END) {
  15013. WOLFSSL_MSG("ServerHelloDone received by server");
  15014. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  15015. return SIDE_ERROR;
  15016. }
  15017. #endif
  15018. if (ssl->msgsReceived.got_server_hello_done) {
  15019. WOLFSSL_MSG("Duplicate ServerHelloDone received");
  15020. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  15021. return DUPLICATE_MSG_E;
  15022. }
  15023. ssl->msgsReceived.got_server_hello_done = 1;
  15024. if (ssl->msgsReceived.got_certificate == 0) {
  15025. if (ssl->specs.kea == psk_kea ||
  15026. ssl->specs.kea == dhe_psk_kea ||
  15027. ssl->specs.kea == ecdhe_psk_kea ||
  15028. ssl->options.usingAnon_cipher) {
  15029. WOLFSSL_MSG("No Cert required");
  15030. }
  15031. else {
  15032. WOLFSSL_MSG("No Certificate before ServerHelloDone");
  15033. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15034. return OUT_OF_ORDER_E;
  15035. }
  15036. }
  15037. if (ssl->msgsReceived.got_server_key_exchange == 0) {
  15038. int pskNoServerHint = 0; /* not required in this case */
  15039. #ifndef NO_PSK
  15040. if (ssl->specs.kea == psk_kea &&
  15041. ssl->arrays != NULL &&
  15042. ssl->arrays->server_hint[0] == 0)
  15043. pskNoServerHint = 1;
  15044. #endif
  15045. if (ssl->specs.static_ecdh == 1 ||
  15046. ssl->specs.kea == rsa_kea ||
  15047. pskNoServerHint) {
  15048. WOLFSSL_MSG("No KeyExchange required");
  15049. }
  15050. else {
  15051. WOLFSSL_MSG("No ServerKeyExchange before ServerDone");
  15052. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15053. return OUT_OF_ORDER_E;
  15054. }
  15055. }
  15056. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
  15057. defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  15058. if (ssl->msgsReceived.got_certificate_status == 0) {
  15059. int csrRet = 0;
  15060. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  15061. if (csrRet == 0 && ssl->status_request) {
  15062. WOLFSSL_MSG("No CertificateStatus before ServerHelloDone");
  15063. csrRet = TLSX_CSR_ForceRequest(ssl);
  15064. }
  15065. #endif
  15066. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  15067. if (csrRet == 0 && ssl->status_request_v2) {
  15068. WOLFSSL_MSG("No CertificateStatus before ServerHelloDone");
  15069. csrRet = TLSX_CSR2_ForceRequest(ssl);
  15070. }
  15071. if (ssl->status_request_v2) {
  15072. if (csrRet == 0) {
  15073. if (TLSX_CSR2_MergePendingCA(ssl) < 0) {
  15074. WOLFSSL_MSG("Failed to merge pending CAs");
  15075. }
  15076. }
  15077. else {
  15078. TLSX_CSR2_ClearPendingCA(ssl);
  15079. }
  15080. }
  15081. #endif
  15082. if (csrRet != 0) {
  15083. /* Error out if OCSP lookups are enabled and failed or if
  15084. * the user requires stapling. */
  15085. if (SSL_CM(ssl)->ocspEnabled || SSL_CM(ssl)->ocspMustStaple)
  15086. return csrRet;
  15087. }
  15088. /* Check that a status request extension was seen as the
  15089. * CertificateStatus wasn't when an OCSP staple is required.
  15090. */
  15091. if (
  15092. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  15093. !ssl->status_request &&
  15094. #endif
  15095. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  15096. !ssl->status_request_v2 &&
  15097. #endif
  15098. SSL_CM(ssl)->ocspMustStaple) {
  15099. WOLFSSL_ERROR_VERBOSE(OCSP_CERT_UNKNOWN);
  15100. return OCSP_CERT_UNKNOWN;
  15101. }
  15102. }
  15103. #endif
  15104. break;
  15105. #endif
  15106. #ifndef NO_WOLFSSL_SERVER
  15107. case certificate_verify:
  15108. #ifndef NO_WOLFSSL_CLIENT
  15109. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  15110. WOLFSSL_MSG("CertificateVerify received by client");
  15111. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  15112. return SIDE_ERROR;
  15113. }
  15114. #endif
  15115. if (ssl->msgsReceived.got_certificate_verify) {
  15116. WOLFSSL_MSG("Duplicate CertificateVerify received");
  15117. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  15118. return DUPLICATE_MSG_E;
  15119. }
  15120. ssl->msgsReceived.got_certificate_verify = 1;
  15121. if ( ssl->msgsReceived.got_certificate == 0) {
  15122. WOLFSSL_MSG("No Cert before CertVerify");
  15123. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15124. return OUT_OF_ORDER_E;
  15125. }
  15126. break;
  15127. #endif
  15128. #ifndef NO_WOLFSSL_SERVER
  15129. case client_key_exchange:
  15130. #ifndef NO_WOLFSSL_CLIENT
  15131. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  15132. WOLFSSL_MSG("ClientKeyExchange received by client");
  15133. WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
  15134. return SIDE_ERROR;
  15135. }
  15136. #endif
  15137. if (ssl->msgsReceived.got_client_key_exchange) {
  15138. WOLFSSL_MSG("Duplicate ClientKeyExchange received");
  15139. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  15140. return DUPLICATE_MSG_E;
  15141. }
  15142. ssl->msgsReceived.got_client_key_exchange = 1;
  15143. if (ssl->msgsReceived.got_client_hello == 0) {
  15144. WOLFSSL_MSG("No ClientHello before ClientKeyExchange");
  15145. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15146. return OUT_OF_ORDER_E;
  15147. }
  15148. break;
  15149. #endif
  15150. case finished:
  15151. if (ssl->msgsReceived.got_finished) {
  15152. WOLFSSL_MSG("Duplicate Finished received");
  15153. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  15154. return DUPLICATE_MSG_E;
  15155. }
  15156. #ifdef WOLFSSL_DTLS
  15157. if (ssl->options.dtls) {
  15158. if (ssl->keys.curEpoch == 0) {
  15159. WOLFSSL_MSG("Finished received with epoch 0");
  15160. WOLFSSL_ERROR_VERBOSE(SEQUENCE_ERROR);
  15161. return SEQUENCE_ERROR;
  15162. }
  15163. }
  15164. #endif
  15165. ssl->msgsReceived.got_finished = 1;
  15166. if (ssl->msgsReceived.got_change_cipher == 0) {
  15167. WOLFSSL_MSG("Finished received before ChangeCipher");
  15168. WOLFSSL_ERROR_VERBOSE(NO_CHANGE_CIPHER_E);
  15169. return NO_CHANGE_CIPHER_E;
  15170. }
  15171. break;
  15172. case change_cipher_hs:
  15173. if (ssl->msgsReceived.got_change_cipher) {
  15174. WOLFSSL_MSG("Duplicate ChangeCipher received");
  15175. WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
  15176. return DUPLICATE_MSG_E;
  15177. }
  15178. /* DTLS is going to ignore the CCS message if the client key
  15179. * exchange message wasn't received yet. */
  15180. if (!ssl->options.dtls)
  15181. ssl->msgsReceived.got_change_cipher = 1;
  15182. #ifndef NO_WOLFSSL_CLIENT
  15183. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  15184. if (!ssl->options.resuming) {
  15185. if (ssl->msgsReceived.got_server_hello_done == 0) {
  15186. WOLFSSL_MSG("No ServerHelloDone before ChangeCipher");
  15187. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15188. return OUT_OF_ORDER_E;
  15189. }
  15190. }
  15191. else {
  15192. if (ssl->msgsReceived.got_server_hello == 0) {
  15193. WOLFSSL_MSG("No ServerHello before ChangeCipher on "
  15194. "Resume");
  15195. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15196. return OUT_OF_ORDER_E;
  15197. }
  15198. }
  15199. #ifdef HAVE_SESSION_TICKET
  15200. if (ssl->expect_session_ticket) {
  15201. WOLFSSL_MSG("Expected session ticket missing");
  15202. #ifdef WOLFSSL_DTLS
  15203. if (ssl->options.dtls) {
  15204. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15205. return OUT_OF_ORDER_E;
  15206. }
  15207. #endif
  15208. WOLFSSL_ERROR_VERBOSE(SESSION_TICKET_EXPECT_E);
  15209. return SESSION_TICKET_EXPECT_E;
  15210. }
  15211. #endif
  15212. }
  15213. #endif
  15214. #ifndef NO_WOLFSSL_SERVER
  15215. if (ssl->options.side == WOLFSSL_SERVER_END) {
  15216. if (!ssl->options.resuming &&
  15217. ssl->msgsReceived.got_client_key_exchange == 0) {
  15218. WOLFSSL_MSG("No ClientKeyExchange before ChangeCipher");
  15219. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15220. return OUT_OF_ORDER_E;
  15221. }
  15222. #ifndef NO_CERTS
  15223. if (ssl->options.verifyPeer &&
  15224. ssl->options.havePeerCert) {
  15225. if (!ssl->options.havePeerVerify ||
  15226. !ssl->msgsReceived.got_certificate_verify) {
  15227. WOLFSSL_MSG("client didn't send cert verify");
  15228. #ifdef WOLFSSL_DTLS
  15229. if (ssl->options.dtls) {
  15230. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15231. return OUT_OF_ORDER_E;
  15232. }
  15233. #endif
  15234. WOLFSSL_ERROR_VERBOSE(NO_PEER_VERIFY);
  15235. return NO_PEER_VERIFY;
  15236. }
  15237. }
  15238. #endif
  15239. }
  15240. #endif
  15241. if (ssl->options.dtls)
  15242. ssl->msgsReceived.got_change_cipher = 1;
  15243. break;
  15244. default:
  15245. WOLFSSL_MSG("Unknown message type");
  15246. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  15247. return SANITY_MSG_E;
  15248. }
  15249. return 0;
  15250. }
  15251. int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  15252. byte type, word32 size, word32 totalSz)
  15253. {
  15254. int ret = 0;
  15255. word32 expectedIdx;
  15256. WOLFSSL_ENTER("DoHandShakeMsgType");
  15257. #ifdef WOLFSSL_TLS13
  15258. if (type == hello_retry_request) {
  15259. return DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
  15260. totalSz);
  15261. }
  15262. #endif
  15263. /* make sure can read the message */
  15264. if (*inOutIdx + size > totalSz) {
  15265. WOLFSSL_MSG("Incomplete Data");
  15266. WOLFSSL_ERROR_VERBOSE(INCOMPLETE_DATA);
  15267. return INCOMPLETE_DATA;
  15268. }
  15269. expectedIdx = *inOutIdx + size +
  15270. (ssl->keys.encryptionOn ? ssl->keys.padSz : 0);
  15271. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  15272. if (ssl->options.startedETMRead && ssl->keys.encryptionOn)
  15273. expectedIdx += MacSize(ssl);
  15274. #endif
  15275. #if !defined(NO_WOLFSSL_SERVER) && \
  15276. defined(HAVE_SECURE_RENEGOTIATION) && \
  15277. defined(HAVE_SERVER_RENEGOTIATION_INFO)
  15278. if (ssl->options.handShakeDone && type == client_hello &&
  15279. ssl->secure_renegotiation &&
  15280. ssl->secure_renegotiation->enabled)
  15281. {
  15282. WOLFSSL_MSG("Reset handshake state");
  15283. XMEMSET(&ssl->msgsReceived, 0, sizeof(MsgsReceived));
  15284. ssl->options.serverState = NULL_STATE;
  15285. ssl->options.clientState = NULL_STATE;
  15286. ssl->options.connectState = CONNECT_BEGIN;
  15287. ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
  15288. ssl->options.handShakeState = NULL_STATE;
  15289. ssl->secure_renegotiation->cache_status = SCR_CACHE_NEEDED;
  15290. ret = InitHandshakeHashes(ssl);
  15291. if (ret != 0)
  15292. return ret;
  15293. }
  15294. #endif
  15295. /* sanity check msg received */
  15296. if ( (ret = SanityCheckMsgReceived(ssl, type)) != 0) {
  15297. WOLFSSL_MSG("Sanity Check on handshake message type received failed");
  15298. return ret;
  15299. }
  15300. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  15301. /* add name later, add the handshake header part back on and record layer
  15302. * header */
  15303. if (ssl->toInfoOn) {
  15304. ret = AddPacketInfo(ssl, 0, handshake, input + *inOutIdx -
  15305. HANDSHAKE_HEADER_SZ, size + HANDSHAKE_HEADER_SZ, READ_PROTO,
  15306. RECORD_HEADER_SZ, ssl->heap);
  15307. if (ret != 0)
  15308. return ret;
  15309. #ifdef WOLFSSL_CALLBACKS
  15310. AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
  15311. #endif
  15312. }
  15313. #endif
  15314. if (ssl->options.handShakeState == HANDSHAKE_DONE && type != hello_request){
  15315. WOLFSSL_MSG("HandShake message after handshake complete");
  15316. SendAlert(ssl, alert_fatal, unexpected_message);
  15317. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15318. return OUT_OF_ORDER_E;
  15319. }
  15320. if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.dtls == 0 &&
  15321. ssl->options.serverState == NULL_STATE && type != server_hello &&
  15322. type != hello_request) {
  15323. WOLFSSL_MSG("First server message not server hello or "
  15324. "hello request");
  15325. SendAlert(ssl, alert_fatal, unexpected_message);
  15326. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15327. return OUT_OF_ORDER_E;
  15328. }
  15329. if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.dtls &&
  15330. type == server_hello_done &&
  15331. ssl->options.serverState < SERVER_HELLO_COMPLETE) {
  15332. WOLFSSL_MSG("Server hello done received before server hello in DTLS");
  15333. SendAlert(ssl, alert_fatal, unexpected_message);
  15334. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15335. return OUT_OF_ORDER_E;
  15336. }
  15337. if (ssl->options.side == WOLFSSL_SERVER_END &&
  15338. ssl->options.clientState == NULL_STATE && type != client_hello) {
  15339. WOLFSSL_MSG("First client message not client hello");
  15340. SendAlert(ssl, alert_fatal, unexpected_message);
  15341. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15342. return OUT_OF_ORDER_E;
  15343. }
  15344. /* above checks handshake state */
  15345. /* hello_request not hashed */
  15346. if (type != hello_request
  15347. #ifdef WOLFSSL_ASYNC_CRYPT
  15348. && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
  15349. #endif
  15350. #ifdef WOLFSSL_NONBLOCK_OCSP
  15351. && ssl->error != WC_NO_ERR_TRACE(OCSP_WANT_READ)
  15352. #endif
  15353. ) {
  15354. ret = HashInput(ssl, input + *inOutIdx, (int)size);
  15355. if (ret != 0) {
  15356. WOLFSSL_MSG("Incomplete handshake hashes");
  15357. return ret;
  15358. }
  15359. }
  15360. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  15361. switch (type) {
  15362. case certificate:
  15363. case server_key_exchange:
  15364. case certificate_request:
  15365. case server_hello_done:
  15366. if (ssl->options.resuming) {
  15367. /* https://www.rfc-editor.org/rfc/rfc5077.html#section-3.4
  15368. * Alternatively, the client MAY include an empty Session ID
  15369. * in the ClientHello. In this case, the client ignores the
  15370. * Session ID sent in the ServerHello and determines if the
  15371. * server is resuming a session by the subsequent handshake
  15372. * messages.
  15373. */
  15374. #ifndef WOLFSSL_WPAS
  15375. if (ssl->session->sessionIDSz != 0) {
  15376. /* Fatal error. Only try to send an alert. RFC 5246 does not
  15377. * allow for reverting back to a full handshake after the
  15378. * server has indicated the intention to do a resumption. */
  15379. (void)SendAlert(ssl, alert_fatal, unexpected_message);
  15380. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  15381. return OUT_OF_ORDER_E;
  15382. }
  15383. #endif
  15384. /* This can occur when ssl->sessionSecretCb is set. EAP-FAST
  15385. * (RFC 4851) allows for detecting server session resumption
  15386. * based on the msg received after the ServerHello. */
  15387. WOLFSSL_MSG("Not resuming as thought");
  15388. ssl->options.resuming = 0;
  15389. /* No longer resuming, reset peer authentication state. */
  15390. ssl->options.peerAuthGood = 0;
  15391. }
  15392. }
  15393. }
  15394. #ifdef OPENSSL_EXTRA
  15395. if (ssl->CBIS != NULL){
  15396. ssl->cbmode = SSL_CB_MODE_READ;
  15397. ssl->cbtype = type;
  15398. ssl->CBIS(ssl, SSL_CB_ACCEPT_LOOP, WOLFSSL_SUCCESS);
  15399. }
  15400. #endif
  15401. switch (type) {
  15402. case hello_request:
  15403. WOLFSSL_MSG("processing hello request");
  15404. ret = DoHelloRequest(ssl, input, inOutIdx, size, totalSz);
  15405. break;
  15406. #ifndef NO_WOLFSSL_CLIENT
  15407. case hello_verify_request:
  15408. WOLFSSL_MSG("processing hello verify request");
  15409. ret = DoHelloVerifyRequest(ssl, input,inOutIdx, size);
  15410. if (IsEncryptionOn(ssl, 0)) {
  15411. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  15412. if (ssl->options.startedETMRead) {
  15413. word32 digestSz = MacSize(ssl);
  15414. if (*inOutIdx + ssl->keys.padSz + digestSz > totalSz)
  15415. return BUFFER_E;
  15416. *inOutIdx += ssl->keys.padSz + digestSz;
  15417. }
  15418. else
  15419. #endif
  15420. {
  15421. /* access beyond input + size should be checked against totalSz
  15422. */
  15423. if (*inOutIdx + ssl->keys.padSz > totalSz)
  15424. return BUFFER_E;
  15425. *inOutIdx += ssl->keys.padSz;
  15426. }
  15427. }
  15428. break;
  15429. case server_hello:
  15430. WOLFSSL_MSG("processing server hello");
  15431. ret = DoServerHello(ssl, input, inOutIdx, size);
  15432. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  15433. ((defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)) || \
  15434. (defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  15435. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  15436. if (ssl->options.resuming || !IsAtLeastTLSv1_2(ssl) ||
  15437. IsAtLeastTLSv1_3(ssl->version)) {
  15438. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  15439. if (ret != WC_NO_ERR_TRACE(WC_PENDING_E) &&
  15440. ret != WC_NO_ERR_TRACE(OCSP_WANT_READ))
  15441. #endif
  15442. {
  15443. ssl->options.cacheMessages = 0;
  15444. if ((ssl->hsHashes != NULL) && (ssl->hsHashes->messages != NULL)) {
  15445. ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length);
  15446. XFREE(ssl->hsHashes->messages, ssl->heap,
  15447. DYNAMIC_TYPE_HASHES);
  15448. ssl->hsHashes->messages = NULL;
  15449. }
  15450. }
  15451. }
  15452. #endif
  15453. break;
  15454. #ifndef NO_CERTS
  15455. case certificate_request:
  15456. WOLFSSL_MSG("processing certificate request");
  15457. ret = DoCertificateRequest(ssl, input, inOutIdx, size);
  15458. break;
  15459. #endif
  15460. case server_key_exchange:
  15461. WOLFSSL_MSG("processing server key exchange");
  15462. ret = DoServerKeyExchange(ssl, input, inOutIdx, size);
  15463. break;
  15464. #ifdef HAVE_SESSION_TICKET
  15465. case session_ticket:
  15466. WOLFSSL_MSG("processing session ticket");
  15467. ret = DoSessionTicket(ssl, input, inOutIdx, size);
  15468. break;
  15469. #endif /* HAVE_SESSION_TICKET */
  15470. #endif
  15471. #if !defined(NO_CERTS) && (!defined(NO_WOLFSSL_CLIENT) || \
  15472. !defined(WOLFSSL_NO_CLIENT_AUTH))
  15473. case certificate:
  15474. WOLFSSL_MSG("processing certificate");
  15475. ret = DoCertificate(ssl, input, inOutIdx, size);
  15476. break;
  15477. case certificate_status:
  15478. WOLFSSL_MSG("processing certificate status");
  15479. ret = DoCertificateStatus(ssl, input, inOutIdx, size);
  15480. break;
  15481. #endif
  15482. case server_hello_done:
  15483. WOLFSSL_MSG("processing server hello done");
  15484. #ifdef WOLFSSL_CALLBACKS
  15485. if (ssl->hsInfoOn)
  15486. AddPacketName(ssl, "ServerHelloDone");
  15487. if (ssl->toInfoOn)
  15488. AddLateName("ServerHelloDone", &ssl->timeoutInfo);
  15489. #endif
  15490. ssl->options.serverState = SERVER_HELLODONE_COMPLETE;
  15491. if (IsEncryptionOn(ssl, 0)) {
  15492. *inOutIdx += ssl->keys.padSz;
  15493. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  15494. if (ssl->options.startedETMRead)
  15495. *inOutIdx += MacSize(ssl);
  15496. #endif
  15497. }
  15498. break;
  15499. case finished:
  15500. WOLFSSL_MSG("processing finished");
  15501. ret = DoFinished(ssl, input, inOutIdx, size, totalSz, NO_SNIFF);
  15502. break;
  15503. #ifndef NO_WOLFSSL_SERVER
  15504. case client_hello:
  15505. WOLFSSL_MSG("processing client hello");
  15506. ret = DoClientHello(ssl, input, inOutIdx, size);
  15507. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  15508. ((defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)) || \
  15509. (defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  15510. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  15511. if (ssl->options.resuming || !ssl->options.verifyPeer || \
  15512. !IsAtLeastTLSv1_2(ssl) || IsAtLeastTLSv1_3(ssl->version)) {
  15513. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  15514. if (ret != WC_NO_ERR_TRACE(WC_PENDING_E) &&
  15515. ret != WC_NO_ERR_TRACE(OCSP_WANT_READ))
  15516. #endif
  15517. {
  15518. ssl->options.cacheMessages = 0;
  15519. if ((ssl->hsHashes != NULL) && (ssl->hsHashes->messages != NULL)) {
  15520. ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length);
  15521. XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
  15522. ssl->hsHashes->messages = NULL;
  15523. }
  15524. }
  15525. }
  15526. #endif
  15527. /* If size == totalSz then we are in DtlsMsgDrain so no need to worry
  15528. * about padding */
  15529. if (IsEncryptionOn(ssl, 0)) {
  15530. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  15531. if (ssl->options.startedETMRead) {
  15532. word32 digestSz = MacSize(ssl);
  15533. if (size != totalSz &&
  15534. *inOutIdx + ssl->keys.padSz + digestSz > totalSz)
  15535. return BUFFER_E;
  15536. *inOutIdx += ssl->keys.padSz + digestSz;
  15537. }
  15538. else
  15539. #endif
  15540. {
  15541. /* access beyond input + size should be checked against totalSz
  15542. */
  15543. if (size != totalSz &&
  15544. *inOutIdx + ssl->keys.padSz > totalSz)
  15545. return BUFFER_E;
  15546. *inOutIdx += ssl->keys.padSz;
  15547. }
  15548. }
  15549. break;
  15550. case client_key_exchange:
  15551. WOLFSSL_MSG("processing client key exchange");
  15552. ret = DoClientKeyExchange(ssl, input, inOutIdx, size);
  15553. break;
  15554. #if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  15555. defined(HAVE_ED448)) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  15556. case certificate_verify:
  15557. WOLFSSL_MSG("processing certificate verify");
  15558. ret = DoCertificateVerify(ssl, input, inOutIdx, size);
  15559. break;
  15560. #endif /* (!NO_RSA || ECC || ED25519 || ED448) && !WOLFSSL_NO_CLIENT_AUTH */
  15561. #endif /* !NO_WOLFSSL_SERVER */
  15562. default:
  15563. WOLFSSL_MSG("Unknown handshake message type");
  15564. ret = UNKNOWN_HANDSHAKE_TYPE;
  15565. break;
  15566. }
  15567. if (ret == 0 && expectedIdx != *inOutIdx) {
  15568. WOLFSSL_MSG("Extra data in handshake message");
  15569. if (!ssl->options.dtls)
  15570. SendAlert(ssl, alert_fatal, decode_error);
  15571. ret = DECODE_E;
  15572. WOLFSSL_ERROR_VERBOSE(ret);
  15573. }
  15574. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  15575. /* if async, offset index so this msg will be processed again */
  15576. if ((ret == WC_NO_ERR_TRACE(WC_PENDING_E) ||
  15577. ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) && *inOutIdx > 0) {
  15578. *inOutIdx -= HANDSHAKE_HEADER_SZ;
  15579. #ifdef WOLFSSL_DTLS
  15580. if (ssl->options.dtls) {
  15581. *inOutIdx -= DTLS_HANDSHAKE_EXTRA;
  15582. }
  15583. #endif
  15584. }
  15585. /* make sure async error is cleared */
  15586. if (ret == 0 && (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E) ||
  15587. ssl->error == WC_NO_ERR_TRACE(OCSP_WANT_READ))) {
  15588. ssl->error = 0;
  15589. }
  15590. #endif /* WOLFSSL_ASYNC_CRYPT || WOLFSSL_NONBLOCK_OCSP */
  15591. #ifdef WOLFSSL_DTLS
  15592. if (ret == 0) {
  15593. if (type == client_hello) {
  15594. /* Advance expected number only if cookie exchange complete */
  15595. if (ssl->msgsReceived.got_client_hello)
  15596. ssl->keys.dtls_expected_peer_handshake_number =
  15597. ssl->keys.dtls_peer_handshake_number + 1;
  15598. }
  15599. else if (type != finished) {
  15600. ssl->keys.dtls_expected_peer_handshake_number++;
  15601. }
  15602. }
  15603. #endif
  15604. WOLFSSL_LEAVE("DoHandShakeMsgType()", ret);
  15605. return ret;
  15606. }
  15607. static int DoHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  15608. word32 totalSz)
  15609. {
  15610. int ret = 0;
  15611. word32 inputLength;
  15612. WOLFSSL_ENTER("DoHandShakeMsg");
  15613. if (ssl->arrays == NULL) {
  15614. byte type;
  15615. word32 size;
  15616. if (GetHandShakeHeader(ssl,input,inOutIdx,&type, &size, totalSz) != 0) {
  15617. WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
  15618. return PARSE_ERROR;
  15619. }
  15620. ret = EarlySanityCheckMsgReceived(ssl, type, size);
  15621. if (ret != 0) {
  15622. WOLFSSL_ERROR(ret);
  15623. return ret;
  15624. }
  15625. if (size > MAX_HANDSHAKE_SZ) {
  15626. WOLFSSL_MSG("Handshake message too large");
  15627. WOLFSSL_ERROR_VERBOSE(HANDSHAKE_SIZE_ERROR);
  15628. return HANDSHAKE_SIZE_ERROR;
  15629. }
  15630. return DoHandShakeMsgType(ssl, input, inOutIdx, type, size, totalSz);
  15631. }
  15632. inputLength = ssl->buffers.inputBuffer.length - *inOutIdx;
  15633. /* If there is a pending fragmented handshake message,
  15634. * pending message size will be non-zero. */
  15635. if (ssl->arrays->pendingMsgSz == 0) {
  15636. byte type;
  15637. word32 size;
  15638. if (GetHandShakeHeader(ssl, input, inOutIdx, &type, &size,
  15639. totalSz) != 0) {
  15640. WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
  15641. return PARSE_ERROR;
  15642. }
  15643. ret = EarlySanityCheckMsgReceived(ssl, type,
  15644. min(inputLength - HANDSHAKE_HEADER_SZ, size));
  15645. if (ret != 0) {
  15646. WOLFSSL_ERROR(ret);
  15647. return ret;
  15648. }
  15649. /* Cap the maximum size of a handshake message to something reasonable.
  15650. * By default is the maximum size of a certificate message assuming
  15651. * nine 2048-bit RSA certificates in the chain. */
  15652. if (size > MAX_HANDSHAKE_SZ) {
  15653. WOLFSSL_MSG("Handshake message too large");
  15654. WOLFSSL_ERROR_VERBOSE(HANDSHAKE_SIZE_ERROR);
  15655. return HANDSHAKE_SIZE_ERROR;
  15656. }
  15657. /* size is the size of the certificate message payload */
  15658. if (inputLength - HANDSHAKE_HEADER_SZ < size) {
  15659. ssl->arrays->pendingMsgType = type;
  15660. ssl->arrays->pendingMsgSz = size + HANDSHAKE_HEADER_SZ;
  15661. ssl->arrays->pendingMsg = (byte*)XMALLOC(size + HANDSHAKE_HEADER_SZ,
  15662. ssl->heap,
  15663. DYNAMIC_TYPE_ARRAYS);
  15664. if (ssl->arrays->pendingMsg == NULL)
  15665. return MEMORY_E;
  15666. XMEMCPY(ssl->arrays->pendingMsg,
  15667. input + *inOutIdx - HANDSHAKE_HEADER_SZ,
  15668. inputLength);
  15669. ssl->arrays->pendingMsgOffset = inputLength;
  15670. *inOutIdx += inputLength - HANDSHAKE_HEADER_SZ;
  15671. return 0;
  15672. }
  15673. ret = DoHandShakeMsgType(ssl, input, inOutIdx, type, size, totalSz);
  15674. }
  15675. else {
  15676. word32 pendSz =
  15677. ssl->arrays->pendingMsgSz - ssl->arrays->pendingMsgOffset;
  15678. /* Catch the case where there may be the remainder of a fragmented
  15679. * handshake message and the next handshake message in the same
  15680. * record. */
  15681. if (inputLength > pendSz)
  15682. inputLength = pendSz;
  15683. ret = EarlySanityCheckMsgReceived(ssl, ssl->arrays->pendingMsgType,
  15684. inputLength);
  15685. if (ret != 0) {
  15686. WOLFSSL_ERROR(ret);
  15687. return ret;
  15688. }
  15689. #ifdef WOLFSSL_ASYNC_CRYPT
  15690. if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E))
  15691. #endif
  15692. {
  15693. /* for async this copy was already done, do not replace, since
  15694. * contents may have been changed for inline operations */
  15695. XMEMCPY(ssl->arrays->pendingMsg + ssl->arrays->pendingMsgOffset,
  15696. input + *inOutIdx, inputLength);
  15697. }
  15698. ssl->arrays->pendingMsgOffset += inputLength;
  15699. *inOutIdx += inputLength;
  15700. if (ssl->arrays->pendingMsgOffset == ssl->arrays->pendingMsgSz)
  15701. {
  15702. word32 idx = HANDSHAKE_HEADER_SZ;
  15703. ret = DoHandShakeMsgType(ssl,
  15704. ssl->arrays->pendingMsg,
  15705. &idx, ssl->arrays->pendingMsgType,
  15706. ssl->arrays->pendingMsgSz - idx,
  15707. ssl->arrays->pendingMsgSz);
  15708. #ifdef WOLFSSL_ASYNC_CRYPT
  15709. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  15710. /* setup to process fragment again */
  15711. ssl->arrays->pendingMsgOffset -= inputLength;
  15712. *inOutIdx -= inputLength;
  15713. }
  15714. else
  15715. #endif
  15716. {
  15717. XFREE(ssl->arrays->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
  15718. ssl->arrays->pendingMsg = NULL;
  15719. ssl->arrays->pendingMsgSz = 0;
  15720. }
  15721. }
  15722. }
  15723. WOLFSSL_LEAVE("DoHandShakeMsg()", ret);
  15724. return ret;
  15725. }
  15726. #endif /* !WOLFSSL_NO_TLS12 */
  15727. #ifdef WOLFSSL_EXTRA_ALERTS
  15728. int SendFatalAlertOnly(WOLFSSL *ssl, int error)
  15729. {
  15730. int why;
  15731. /* already sent a more specific fatal alert */
  15732. if (ssl->alert_history.last_tx.level == alert_fatal)
  15733. return 0;
  15734. switch (error) {
  15735. /* not fatal errors */
  15736. case WC_NO_ERR_TRACE(WANT_WRITE):
  15737. case WC_NO_ERR_TRACE(WANT_READ):
  15738. case WC_NO_ERR_TRACE(ZERO_RETURN):
  15739. #ifdef WOLFSSL_NONBLOCK_OCSP
  15740. case WC_NO_ERR_TRACE(OCSP_WANT_READ):
  15741. #endif
  15742. #ifdef WOLFSSL_ASYNC_CRYPT
  15743. case WC_NO_ERR_TRACE(WC_PENDING_E):
  15744. #endif
  15745. return 0;
  15746. /* peer already disconnected and ssl is possibly in bad state
  15747. * don't try to send an alert */
  15748. case WC_NO_ERR_TRACE(SOCKET_ERROR_E):
  15749. return error;
  15750. case WC_NO_ERR_TRACE(BUFFER_ERROR):
  15751. case WC_NO_ERR_TRACE(ASN_PARSE_E):
  15752. case WC_NO_ERR_TRACE(COMPRESSION_ERROR):
  15753. why = decode_error;
  15754. break;
  15755. case WC_NO_ERR_TRACE(VERIFY_FINISHED_ERROR):
  15756. case WC_NO_ERR_TRACE(SIG_VERIFY_E):
  15757. why = decrypt_error;
  15758. break;
  15759. case WC_NO_ERR_TRACE(DUPLICATE_MSG_E):
  15760. case WC_NO_ERR_TRACE(NO_CHANGE_CIPHER_E):
  15761. case WC_NO_ERR_TRACE(OUT_OF_ORDER_E):
  15762. why = unexpected_message;
  15763. break;
  15764. case WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E):
  15765. why = bad_record_mac;
  15766. break;
  15767. case WC_NO_ERR_TRACE(MATCH_SUITE_ERROR):
  15768. case WC_NO_ERR_TRACE(VERSION_ERROR):
  15769. default:
  15770. why = handshake_failure;
  15771. break;
  15772. }
  15773. return SendAlert(ssl, alert_fatal, why);
  15774. }
  15775. #else
  15776. int SendFatalAlertOnly(WOLFSSL *ssl, int error)
  15777. {
  15778. (void)ssl;
  15779. (void)error;
  15780. /* no op */
  15781. return 0;
  15782. }
  15783. #endif /* WOLFSSL_EXTRA_ALERTS */
  15784. #ifdef WOLFSSL_DTLS
  15785. static int _DtlsCheckWindow(WOLFSSL* ssl)
  15786. {
  15787. word32* window;
  15788. word16 cur_hi, next_hi;
  15789. word32 cur_lo, next_lo, diff;
  15790. int curLT;
  15791. WOLFSSL_DTLS_PEERSEQ* peerSeq = NULL;
  15792. if (!ssl->options.haveMcast)
  15793. peerSeq = ssl->keys.peerSeq;
  15794. else {
  15795. #ifdef WOLFSSL_MULTICAST
  15796. WOLFSSL_DTLS_PEERSEQ* p;
  15797. int i;
  15798. for (i = 0, p = ssl->keys.peerSeq;
  15799. i < WOLFSSL_DTLS_PEERSEQ_SZ;
  15800. i++, p++) {
  15801. if (p->peerId == ssl->keys.curPeerId) {
  15802. peerSeq = p;
  15803. break;
  15804. }
  15805. }
  15806. #endif
  15807. }
  15808. if (peerSeq == NULL) {
  15809. WOLFSSL_MSG("Could not find peer sequence");
  15810. return 0;
  15811. }
  15812. if (ssl->keys.curEpoch == peerSeq->nextEpoch) {
  15813. next_hi = peerSeq->nextSeq_hi;
  15814. next_lo = peerSeq->nextSeq_lo;
  15815. window = peerSeq->window;
  15816. }
  15817. else if (ssl->keys.curEpoch == peerSeq->nextEpoch - 1) {
  15818. next_hi = peerSeq->prevSeq_hi;
  15819. next_lo = peerSeq->prevSeq_lo;
  15820. window = peerSeq->prevWindow;
  15821. }
  15822. else {
  15823. return 0;
  15824. }
  15825. cur_hi = ssl->keys.curSeq_hi;
  15826. cur_lo = ssl->keys.curSeq_lo;
  15827. /* If the difference between next and cur is > 2^32, way outside window. */
  15828. if ((cur_hi > next_hi + 1) || (next_hi > cur_hi + 1)) {
  15829. WOLFSSL_MSG("Current record from way too far in the future.");
  15830. return 0;
  15831. }
  15832. if (cur_hi == next_hi) {
  15833. curLT = cur_lo < next_lo;
  15834. diff = curLT ? next_lo - cur_lo : cur_lo - next_lo;
  15835. }
  15836. else {
  15837. curLT = cur_hi < next_hi;
  15838. diff = curLT ? cur_lo - next_lo : next_lo - cur_lo;
  15839. }
  15840. /* Check to see that the next value is greater than the number of messages
  15841. * trackable in the window, and that the difference between the next
  15842. * expected sequence number and the received sequence number is inside the
  15843. * window. */
  15844. if ((next_hi || next_lo > DTLS_SEQ_BITS) &&
  15845. curLT && (diff > DTLS_SEQ_BITS)) {
  15846. WOLFSSL_MSG("Current record sequence number from the past.");
  15847. return 0;
  15848. }
  15849. #ifdef WOLFSSL_DTLS_DISALLOW_FUTURE
  15850. else if (!curLT && (diff > DTLS_SEQ_BITS)) {
  15851. WOLFSSL_MSG("Rejecting message too far into the future.");
  15852. return 0;
  15853. }
  15854. #endif
  15855. else if (curLT) {
  15856. word32 idx;
  15857. word32 newDiff;
  15858. if (diff == 0) {
  15859. WOLFSSL_MSG("DTLS sanity check failed");
  15860. return 0;
  15861. }
  15862. diff--;
  15863. idx = diff / DTLS_WORD_BITS;
  15864. newDiff = diff % DTLS_WORD_BITS;
  15865. /* verify idx is valid for window array */
  15866. if (idx >= WOLFSSL_DTLS_WINDOW_WORDS) {
  15867. WOLFSSL_MSG("Invalid DTLS windows index");
  15868. return 0;
  15869. }
  15870. if (window[idx] & (1 << newDiff)) {
  15871. WOLFSSL_MSG("Current record sequence number already received.");
  15872. return 0;
  15873. }
  15874. }
  15875. return 1;
  15876. }
  15877. #ifdef WOLFSSL_DTLS13
  15878. static WC_INLINE int Dtls13CheckWindow(WOLFSSL* ssl)
  15879. {
  15880. w64wrapper nextSeq, seq;
  15881. w64wrapper diff64;
  15882. word32 *window;
  15883. int wordOffset;
  15884. int wordIndex;
  15885. word32 diff;
  15886. WOLFSSL_ENTER("Dtls13CheckWindow");
  15887. if (ssl->dtls13DecryptEpoch == NULL) {
  15888. WOLFSSL_MSG("Can't find decrypting epoch");
  15889. return 0;
  15890. }
  15891. nextSeq = ssl->dtls13DecryptEpoch->nextPeerSeqNumber;
  15892. window = ssl->dtls13DecryptEpoch->window;
  15893. seq = ssl->keys.curSeq;
  15894. if (w64GTE(seq, nextSeq))
  15895. return 1;
  15896. /* seq < nextSeq, nextSeq - seq */
  15897. diff64 = w64Sub(nextSeq, seq);
  15898. /* diff >= DTLS_SEQ_BITS, outside of the window */
  15899. if (w64GT(diff64, w64From32(0, DTLS_SEQ_BITS)))
  15900. return 0;
  15901. /* we are assuming DTLS_SEQ_BITS <= 2**32 */
  15902. diff = w64GetLow32(diff64);
  15903. /* zero based index */
  15904. diff--;
  15905. wordIndex = ((int)diff) / DTLS_WORD_BITS;
  15906. wordOffset = ((int)diff) % DTLS_WORD_BITS;
  15907. if (window[wordIndex] & (1 << wordOffset))
  15908. return 0;
  15909. return 1;
  15910. }
  15911. #endif /* WOLFSSL_DTLS13 */
  15912. #ifdef WOLFSSL_MULTICAST
  15913. static WC_INLINE word32 UpdateHighwaterMark(word32 cur, word32 first,
  15914. word32 second, word32 high)
  15915. {
  15916. word32 newCur = 0;
  15917. if (cur < first)
  15918. newCur = first;
  15919. else if (cur < second)
  15920. newCur = second;
  15921. else if (cur < high)
  15922. newCur = high;
  15923. return newCur;
  15924. }
  15925. #endif /* WOLFSSL_MULTICAST */
  15926. /* diff is the difference between the message sequence and the
  15927. * expected sequence number. 0 is special where it is an overflow. */
  15928. static void _DtlsUpdateWindowGTSeq(word32 diff, word32* window)
  15929. {
  15930. word32 oldWindow[WOLFSSL_DTLS_WINDOW_WORDS];
  15931. if (diff == 0 || diff >= DTLS_SEQ_BITS)
  15932. XMEMSET(window, 0, DTLS_SEQ_SZ);
  15933. else {
  15934. word32 i;
  15935. word32 temp = 0;
  15936. word32 idx = diff / DTLS_WORD_BITS;
  15937. diff %= DTLS_WORD_BITS;
  15938. XMEMCPY(oldWindow, window, sizeof(oldWindow));
  15939. for (i = 0; i < WOLFSSL_DTLS_WINDOW_WORDS; i++) {
  15940. if (i < idx)
  15941. window[i] = 0;
  15942. else {
  15943. temp |= (oldWindow[i-idx] << diff);
  15944. window[i] = temp;
  15945. if (diff > 0)
  15946. temp = oldWindow[i-idx] >> (DTLS_WORD_BITS - diff);
  15947. else
  15948. temp = 0;
  15949. }
  15950. }
  15951. }
  15952. window[0] |= 1;
  15953. }
  15954. int wolfSSL_DtlsUpdateWindow(word16 cur_hi, word32 cur_lo,
  15955. word16* next_hi, word32* next_lo, word32 *window)
  15956. {
  15957. word32 diff;
  15958. int curLT;
  15959. if (cur_hi == *next_hi) {
  15960. curLT = cur_lo < *next_lo;
  15961. diff = curLT ? *next_lo - cur_lo : cur_lo - *next_lo;
  15962. }
  15963. else {
  15964. if (cur_hi > *next_hi + 1) {
  15965. /* reset window */
  15966. _DtlsUpdateWindowGTSeq(0, window);
  15967. *next_lo = cur_lo + 1;
  15968. if (*next_lo == 0)
  15969. *next_hi = cur_hi + 1;
  15970. else
  15971. *next_hi = cur_hi;
  15972. return 1;
  15973. }
  15974. else if (*next_hi > cur_hi + 1) {
  15975. return 1;
  15976. }
  15977. else {
  15978. curLT = cur_hi < *next_hi;
  15979. if (curLT) {
  15980. if (*next_lo < DTLS_SEQ_BITS &&
  15981. cur_lo >= (((word32)0xFFFFFFFF) - DTLS_SEQ_BITS)) {
  15982. /* diff here can still result in a difference that can not
  15983. * be stored in the window. The index is checked against
  15984. * WOLFSSL_DTLS_WINDOW_WORDS later. */
  15985. diff = *next_lo + ((word32)0xFFFFFFFF - cur_lo) + 1;
  15986. }
  15987. else {
  15988. /* Too far back to update */
  15989. return 1;
  15990. }
  15991. }
  15992. else {
  15993. if (*next_lo >= (((word32)0xFFFFFFFF) - DTLS_SEQ_BITS) &&
  15994. cur_lo < DTLS_SEQ_BITS) {
  15995. /* diff here can still result in a difference that can not
  15996. * be stored in the window. The index is checked against
  15997. * WOLFSSL_DTLS_WINDOW_WORDS later. */
  15998. diff = cur_lo - *next_lo;
  15999. }
  16000. else {
  16001. _DtlsUpdateWindowGTSeq(0, window);
  16002. *next_lo = cur_lo + 1;
  16003. if (*next_lo == 0)
  16004. *next_hi = cur_hi + 1;
  16005. else
  16006. *next_hi = cur_hi;
  16007. return 1;
  16008. }
  16009. }
  16010. }
  16011. }
  16012. if (curLT) {
  16013. word32 idx;
  16014. diff--;
  16015. idx = diff / DTLS_WORD_BITS;
  16016. diff %= DTLS_WORD_BITS;
  16017. if (idx < WOLFSSL_DTLS_WINDOW_WORDS)
  16018. window[idx] |= (1U << diff);
  16019. }
  16020. else {
  16021. _DtlsUpdateWindowGTSeq(diff + 1, window);
  16022. *next_lo = cur_lo + 1;
  16023. if (*next_lo == 0)
  16024. *next_hi = cur_hi + 1;
  16025. else
  16026. *next_hi = cur_hi;
  16027. }
  16028. return 1;
  16029. }
  16030. int DtlsUpdateWindow(WOLFSSL* ssl)
  16031. {
  16032. WOLFSSL_DTLS_PEERSEQ* peerSeq = ssl->keys.peerSeq;
  16033. word16 *next_hi;
  16034. word32 *next_lo;
  16035. word32* window;
  16036. #ifdef WOLFSSL_MULTICAST
  16037. word32 cur_lo = ssl->keys.curSeq_lo;
  16038. if (ssl->options.haveMcast) {
  16039. WOLFSSL_DTLS_PEERSEQ* p;
  16040. int i;
  16041. peerSeq = NULL;
  16042. for (i = 0, p = ssl->keys.peerSeq;
  16043. i < WOLFSSL_DTLS_PEERSEQ_SZ;
  16044. i++, p++) {
  16045. if (p->peerId == ssl->keys.curPeerId) {
  16046. peerSeq = p;
  16047. break;
  16048. }
  16049. }
  16050. if (peerSeq == NULL) {
  16051. WOLFSSL_MSG("Couldn't find that peer ID to update window.");
  16052. return 0;
  16053. }
  16054. if (p->highwaterMark && cur_lo >= p->highwaterMark) {
  16055. int cbError = 0;
  16056. if (ssl->ctx->mcastHwCb)
  16057. cbError = ssl->ctx->mcastHwCb(p->peerId,
  16058. ssl->ctx->mcastMaxSeq,
  16059. cur_lo, ssl->mcastHwCbCtx);
  16060. if (cbError) {
  16061. WOLFSSL_MSG("Multicast highwater callback returned an error.");
  16062. return MCAST_HIGHWATER_CB_E;
  16063. }
  16064. p->highwaterMark = UpdateHighwaterMark(cur_lo,
  16065. ssl->ctx->mcastFirstSeq,
  16066. ssl->ctx->mcastSecondSeq,
  16067. ssl->ctx->mcastMaxSeq);
  16068. }
  16069. }
  16070. #endif
  16071. if (ssl->keys.curEpoch == peerSeq->nextEpoch) {
  16072. next_hi = &peerSeq->nextSeq_hi;
  16073. next_lo = &peerSeq->nextSeq_lo;
  16074. window = peerSeq->window;
  16075. }
  16076. else {
  16077. next_hi = &peerSeq->prevSeq_hi;
  16078. next_lo = &peerSeq->prevSeq_lo;
  16079. window = peerSeq->prevWindow;
  16080. }
  16081. return wolfSSL_DtlsUpdateWindow(ssl->keys.curSeq_hi, ssl->keys.curSeq_lo,
  16082. next_hi, next_lo, window);
  16083. }
  16084. #ifdef WOLFSSL_DTLS13
  16085. /* Update DTLS 1.3 window
  16086. * Return
  16087. * 0 on successful update
  16088. * <0 on error
  16089. */
  16090. static int Dtls13UpdateWindow(WOLFSSL* ssl)
  16091. {
  16092. w64wrapper nextSeq, seq;
  16093. w64wrapper diff64;
  16094. word32 *window;
  16095. int wordOffset;
  16096. int wordIndex;
  16097. word32 diff;
  16098. Dtls13Epoch* e = ssl->dtls13DecryptEpoch;
  16099. WOLFSSL_ENTER("Dtls13UpdateWindow");
  16100. if (ssl->dtls13DecryptEpoch == NULL) {
  16101. WOLFSSL_MSG("Can't find decrypting Epoch");
  16102. return BAD_STATE_E;
  16103. }
  16104. if (!w64Equal(ssl->keys.curEpoch64, ssl->dtls13DecryptEpoch->epochNumber)) {
  16105. /* ssl->dtls13DecryptEpoch has been updated since we received the msg */
  16106. e = Dtls13GetEpoch(ssl, ssl->keys.curEpoch64);
  16107. if (e == NULL) {
  16108. WOLFSSL_MSG("Can't find decrypting Epoch");
  16109. return BAD_STATE_E;
  16110. }
  16111. }
  16112. nextSeq = e->nextPeerSeqNumber;
  16113. window = e->window;
  16114. seq = ssl->keys.curSeq;
  16115. /* seq < nextSeq */
  16116. if (w64LT(seq, nextSeq)) {
  16117. diff64 = w64Sub(nextSeq, seq);
  16118. /* zero based index */
  16119. w64Decrement(&diff64);
  16120. /* FIXME: check that diff64 < DTLS_WORDS_BITS */
  16121. diff = w64GetLow32(diff64);
  16122. wordIndex = ((int)diff) / DTLS_WORD_BITS;
  16123. wordOffset = ((int)diff) % DTLS_WORD_BITS;
  16124. if (wordIndex >= WOLFSSL_DTLS_WINDOW_WORDS) {
  16125. WOLFSSL_MSG("Invalid sequence number to Dtls13UpdateWindow");
  16126. return BAD_STATE_E;
  16127. }
  16128. window[wordIndex] |= (1 << wordOffset);
  16129. return 0;
  16130. }
  16131. /* seq >= nextSeq, seq - nextSeq */
  16132. diff64 = w64Sub(seq, nextSeq);
  16133. /* as we are considering nextSeq inside the window, we should add + 1 */
  16134. w64Increment(&diff64);
  16135. _DtlsUpdateWindowGTSeq(w64GetLow32(diff64), window);
  16136. w64Increment(&seq);
  16137. e->nextPeerSeqNumber = seq;
  16138. return 0;
  16139. }
  16140. int Dtls13UpdateWindowRecordRecvd(WOLFSSL* ssl)
  16141. {
  16142. int ret = Dtls13UpdateWindow(ssl);
  16143. if (ret != 0)
  16144. return ret;
  16145. return Dtls13RecordRecvd(ssl);
  16146. }
  16147. #endif /* WOLFSSL_DTLS13 */
  16148. int DtlsMsgDrain(WOLFSSL* ssl)
  16149. {
  16150. DtlsMsg* item = ssl->dtls_rx_msg_list;
  16151. int ret = 0;
  16152. WOLFSSL_ENTER("DtlsMsgDrain");
  16153. /* While there is an item in the store list, and it is the expected
  16154. * message, and it is complete, and there hasn't been an error in the
  16155. * last message... */
  16156. while (item != NULL &&
  16157. ssl->keys.dtls_expected_peer_handshake_number == item->seq &&
  16158. item->ready && ret == 0) {
  16159. word32 idx = 0;
  16160. #ifndef WOLFSSL_DISABLE_EARLY_SANITY_CHECKS
  16161. ret = MsgCheckEncryption(ssl, item->type, item->encrypted);
  16162. if (ret != 0) {
  16163. SendAlert(ssl, alert_fatal, unexpected_message);
  16164. break;
  16165. }
  16166. #endif
  16167. #ifdef WOLFSSL_NO_TLS12
  16168. ret = DoTls13HandShakeMsgType(ssl, item->fullMsg, &idx, item->type,
  16169. item->sz, item->sz);
  16170. #else
  16171. ret = DoHandShakeMsgType(ssl, item->fullMsg, &idx, item->type,
  16172. item->sz, item->sz);
  16173. #endif
  16174. if (ret == 0) {
  16175. DtlsTxMsgListClean(ssl);
  16176. }
  16177. else if (!IsAtLeastTLSv1_3(ssl->version)) {
  16178. if (SendFatalAlertOnly(ssl, ret) == WC_NO_ERR_TRACE(SOCKET_ERROR_E)) {
  16179. ret = SOCKET_ERROR_E;
  16180. }
  16181. }
  16182. #ifdef WOLFSSL_ASYNC_CRYPT
  16183. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  16184. break;
  16185. }
  16186. #endif
  16187. ssl->dtls_rx_msg_list = item->next;
  16188. DtlsMsgDelete(item, ssl->heap);
  16189. item = ssl->dtls_rx_msg_list;
  16190. ssl->dtls_rx_msg_list_sz--;
  16191. }
  16192. WOLFSSL_LEAVE("DtlsMsgDrain()", ret);
  16193. return ret;
  16194. }
  16195. static int DoDtlsHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  16196. word32 totalSz)
  16197. {
  16198. byte type;
  16199. word32 size;
  16200. word32 fragOffset, fragSz;
  16201. int ret = 0;
  16202. int ignoreFinished = 0;
  16203. WOLFSSL_ENTER("DoDtlsHandShakeMsg");
  16204. /* parse header */
  16205. if (GetDtlsHandShakeHeader(ssl, input, inOutIdx, &type,
  16206. &size, &fragOffset, &fragSz, totalSz) != 0) {
  16207. WOLFSSL_ERROR(PARSE_ERROR);
  16208. return PARSE_ERROR;
  16209. }
  16210. ret = EarlySanityCheckMsgReceived(ssl, type, fragSz);
  16211. if (ret != 0) {
  16212. WOLFSSL_ERROR(ret);
  16213. return ret;
  16214. }
  16215. /* Cap the maximum size of a handshake message to something reasonable.
  16216. * By default is the maximum size of a certificate message assuming
  16217. * nine 2048-bit RSA certificates in the chain. */
  16218. if (size > MAX_HANDSHAKE_SZ) {
  16219. WOLFSSL_MSG("Handshake message too large");
  16220. return HANDSHAKE_SIZE_ERROR;
  16221. }
  16222. /* check that we have complete fragment */
  16223. if (*inOutIdx + fragSz > totalSz) {
  16224. WOLFSSL_ERROR(INCOMPLETE_DATA);
  16225. return INCOMPLETE_DATA;
  16226. }
  16227. /* check that the fragment is contained in the message */
  16228. if (fragOffset + fragSz > size) {
  16229. WOLFSSL_ERROR(LENGTH_ERROR);
  16230. return LENGTH_ERROR;
  16231. }
  16232. if (type == finished && ssl->keys.dtls_peer_handshake_number >=
  16233. ssl->keys.dtls_expected_peer_handshake_number &&
  16234. ssl->keys.curEpoch == ssl->keys.dtls_epoch) {
  16235. /* finished msg should be ignore from the current epoch
  16236. * if it comes from a previous handshake */
  16237. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  16238. ignoreFinished = ssl->options.connectState < FINISHED_DONE;
  16239. }
  16240. else {
  16241. ignoreFinished = ssl->options.acceptState < ACCEPT_FINISHED_DONE;
  16242. }
  16243. }
  16244. #if !defined(NO_WOLFSSL_SERVER)
  16245. if (ssl->options.side == WOLFSSL_SERVER_END &&
  16246. ssl->options.acceptState < ACCEPT_FIRST_REPLY_DONE &&
  16247. type != client_hello) {
  16248. WOLFSSL_MSG("Ignoring other messages before we verify a ClientHello");
  16249. *inOutIdx = totalSz;
  16250. return 0;
  16251. }
  16252. #endif
  16253. /* Check the handshake sequence number first. If out of order,
  16254. * add the current message to the list. If the message is in order,
  16255. * but it is a fragment, add the current message to the list, then
  16256. * check the head of the list to see if it is complete, if so, pop
  16257. * it out as the current message. If the message is complete and in
  16258. * order, process it. Check the head of the list to see if it is in
  16259. * order, if so, process it. (Repeat until list exhausted.) If the
  16260. * head is out of order, return for more processing.
  16261. */
  16262. if (ssl->keys.dtls_peer_handshake_number >
  16263. ssl->keys.dtls_expected_peer_handshake_number &&
  16264. /* Only client_hello shouldn't be ignored if the handshake
  16265. * num is greater */
  16266. (type == client_hello ||
  16267. ssl->options.handShakeState != HANDSHAKE_DONE) &&
  16268. !ignoreFinished) {
  16269. /* Current message is out of order. It will get stored in the list.
  16270. * Storing also takes care of defragmentation. If the messages is a
  16271. * client hello, we need to process this out of order; the server
  16272. * is not supposed to keep state, but the second client hello will
  16273. * have a different handshake sequence number than is expected, and
  16274. * the server shouldn't be expecting any particular handshake sequence
  16275. * number. (If the cookie changes multiple times in quick succession,
  16276. * the client could be sending multiple new client hello messages
  16277. * with newer and newer cookies.) */
  16278. if (type != client_hello) {
  16279. WOLFSSL_MSG("Current message is out of order");
  16280. if (ssl->dtls_rx_msg_list_sz >= DTLS_POOL_SZ) {
  16281. WOLFSSL_MSG("Reached rx msg limit error");
  16282. return DTLS_TOO_MANY_FRAGMENTS_E;
  16283. }
  16284. DtlsMsgStore(ssl, ssl->keys.curEpoch,
  16285. ssl->keys.dtls_peer_handshake_number,
  16286. input + *inOutIdx, size, type,
  16287. fragOffset, fragSz, ssl->heap);
  16288. *inOutIdx += fragSz;
  16289. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  16290. if (ssl->options.startedETMRead && ssl->keys.curEpoch != 0) {
  16291. word32 digestSz = MacSize(ssl);
  16292. if (*inOutIdx + ssl->keys.padSz + digestSz > totalSz) {
  16293. WOLFSSL_ERROR(BUFFER_E);
  16294. return BUFFER_E;
  16295. }
  16296. *inOutIdx += digestSz;
  16297. }
  16298. else
  16299. #endif
  16300. {
  16301. if (*inOutIdx + ssl->keys.padSz > totalSz) {
  16302. WOLFSSL_ERROR(BUFFER_E);
  16303. return BUFFER_E;
  16304. }
  16305. }
  16306. *inOutIdx += ssl->keys.padSz;
  16307. ret = 0;
  16308. #ifndef WOLFSSL_DTLS_RESEND_ONLY_TIMEOUT
  16309. /* If we receive an out of order last flight msg then retransmit */
  16310. if (type == server_hello_done || type == finished) {
  16311. ret = DtlsMsgPoolSend(ssl, 0);
  16312. }
  16313. #endif
  16314. }
  16315. else {
  16316. if (fragSz < size) {
  16317. /* a fragmented ClientHello, very probably forged or
  16318. erroneous. Even if the packet is valid, we don't want to save
  16319. state while processing a ClientHello to avoid DoS attacks */
  16320. WOLFSSL_MSG("Ignoring datagram with fragmented ClientHello");
  16321. *inOutIdx = totalSz;
  16322. }
  16323. else {
  16324. #ifdef WOLFSSL_NO_TLS12
  16325. ret = DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
  16326. totalSz);
  16327. #else
  16328. ret = DoHandShakeMsgType(ssl, input, inOutIdx, type, size,
  16329. totalSz);
  16330. #endif
  16331. }
  16332. }
  16333. }
  16334. else if (ssl->keys.dtls_peer_handshake_number <
  16335. ssl->keys.dtls_expected_peer_handshake_number ||
  16336. /* ignore all handshake messages if we are done with the
  16337. * handshake */
  16338. (ssl->keys.dtls_peer_handshake_number >
  16339. ssl->keys.dtls_expected_peer_handshake_number &&
  16340. ssl->options.handShakeState == HANDSHAKE_DONE) ||
  16341. ignoreFinished) {
  16342. /* Already saw this message and processed it. It can be ignored. */
  16343. WOLFSSL_MSG("Already saw this message and processed it");
  16344. *inOutIdx += fragSz;
  16345. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  16346. if (ssl->options.startedETMRead && ssl->keys.curEpoch != 0) {
  16347. word32 digestSz = MacSize(ssl);
  16348. if (*inOutIdx + ssl->keys.padSz + digestSz > totalSz) {
  16349. WOLFSSL_ERROR(BUFFER_E);
  16350. return BUFFER_E;
  16351. }
  16352. *inOutIdx += digestSz;
  16353. }
  16354. else
  16355. #endif
  16356. {
  16357. if (*inOutIdx + ssl->keys.padSz > totalSz) {
  16358. WOLFSSL_ERROR(BUFFER_E);
  16359. return BUFFER_E;
  16360. }
  16361. }
  16362. #ifndef WOLFSSL_DTLS_RESEND_ONLY_TIMEOUT
  16363. if (IsDtlsNotSctpMode(ssl) &&
  16364. VerifyForDtlsMsgPoolSend(ssl, type, fragOffset)) {
  16365. ret = DtlsMsgPoolSend(ssl, 0);
  16366. }
  16367. #endif
  16368. *inOutIdx += ssl->keys.padSz;
  16369. }
  16370. else if (fragSz < size) {
  16371. /* Since this branch is in order, but fragmented, dtls_rx_msg_list will
  16372. * be pointing to the message with this fragment in it. Check it to see
  16373. * if it is completed. */
  16374. WOLFSSL_MSG("Branch is in order, but fragmented");
  16375. if (type == client_hello) {
  16376. WOLFSSL_MSG("Ignoring datagram with fragmented ClientHello");
  16377. *inOutIdx = totalSz;
  16378. return 0;
  16379. }
  16380. if (ssl->dtls_rx_msg_list_sz >= DTLS_POOL_SZ) {
  16381. WOLFSSL_MSG("Reached rx msg limit error");
  16382. WOLFSSL_ERROR(DTLS_TOO_MANY_FRAGMENTS_E);
  16383. return DTLS_TOO_MANY_FRAGMENTS_E;
  16384. }
  16385. DtlsMsgStore(ssl, ssl->keys.curEpoch,
  16386. ssl->keys.dtls_peer_handshake_number,
  16387. input + *inOutIdx, size, type,
  16388. fragOffset, fragSz, ssl->heap);
  16389. *inOutIdx += fragSz;
  16390. *inOutIdx += ssl->keys.padSz;
  16391. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  16392. if (ssl->options.startedETMRead && ssl->keys.curEpoch != 0) {
  16393. word32 digestSz = MacSize(ssl);
  16394. if (*inOutIdx + digestSz > totalSz) {
  16395. WOLFSSL_ERROR(BUFFER_E);
  16396. return BUFFER_E;
  16397. }
  16398. *inOutIdx += digestSz;
  16399. }
  16400. #endif
  16401. ret = 0;
  16402. if (ssl->dtls_rx_msg_list != NULL && ssl->dtls_rx_msg_list->ready)
  16403. ret = DtlsMsgDrain(ssl);
  16404. }
  16405. else {
  16406. /* This branch is in order next, and a complete message. On success
  16407. * clean the tx list. */
  16408. WOLFSSL_MSG("Branch is in order and a complete message");
  16409. #ifdef WOLFSSL_ASYNC_CRYPT
  16410. if (ssl->devId != INVALID_DEVID) {
  16411. word32 idx = *inOutIdx;
  16412. if (ssl->dtls_rx_msg_list_sz >= DTLS_POOL_SZ) {
  16413. WOLFSSL_ERROR(BUFFER_ERROR);
  16414. return BUFFER_ERROR;
  16415. }
  16416. if (idx + fragSz + ssl->keys.padSz > totalSz)
  16417. return BUFFER_E;
  16418. *inOutIdx = idx + fragSz + ssl->keys.padSz;
  16419. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  16420. if (ssl->options.startedETMRead && ssl->keys.curEpoch != 0) {
  16421. word32 digestSz = MacSize(ssl);
  16422. if (*inOutIdx + digestSz > totalSz)
  16423. return BUFFER_E;
  16424. *inOutIdx += digestSz;
  16425. }
  16426. #endif
  16427. /* In async mode always store the message and process it with
  16428. * DtlsMsgDrain because in case of a WC_PENDING_E it will be
  16429. * easier this way. */
  16430. if (ssl->dtls_rx_msg_list_sz >= DTLS_POOL_SZ) {
  16431. WOLFSSL_MSG("Reached rx msg limit error");
  16432. return DTLS_TOO_MANY_FRAGMENTS_E;
  16433. }
  16434. DtlsMsgStore(ssl, ssl->keys.curEpoch,
  16435. ssl->keys.dtls_peer_handshake_number,
  16436. input + idx, size, type,
  16437. fragOffset, fragSz, ssl->heap);
  16438. ret = DtlsMsgDrain(ssl);
  16439. }
  16440. else
  16441. #endif
  16442. {
  16443. #ifdef WOLFSSL_NO_TLS12
  16444. ret = DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
  16445. totalSz);
  16446. #else
  16447. ret = DoHandShakeMsgType(ssl, input, inOutIdx, type, size, totalSz);
  16448. #endif
  16449. if (ret == 0) {
  16450. DtlsTxMsgListClean(ssl);
  16451. if (ssl->dtls_rx_msg_list != NULL) {
  16452. ret = DtlsMsgDrain(ssl);
  16453. }
  16454. }
  16455. }
  16456. }
  16457. WOLFSSL_LEAVE("DoDtlsHandShakeMsg()", ret);
  16458. return ret;
  16459. }
  16460. #endif /* WOLFSSL_DTLS13 */
  16461. #ifndef WOLFSSL_NO_TLS12
  16462. #ifdef HAVE_AEAD
  16463. #if (!defined(NO_PUBLIC_GCM_SET_IV) && \
  16464. ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
  16465. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))) || \
  16466. (defined(HAVE_POLY1305) && defined(HAVE_CHACHA))
  16467. static WC_INLINE void AeadIncrementExpIV(WOLFSSL* ssl)
  16468. {
  16469. int i;
  16470. for (i = AEAD_MAX_EXP_SZ-1; i >= 0; i--) {
  16471. if (++ssl->keys.aead_exp_IV[i]) return;
  16472. }
  16473. }
  16474. #endif
  16475. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && !defined(NO_CHAPOL_AEAD)
  16476. /* Used for the older version of creating AEAD tags with Poly1305 */
  16477. static int Poly1305TagOld(WOLFSSL* ssl, byte* additional, const byte* out,
  16478. byte* cipher, word16 sz, byte* tag)
  16479. {
  16480. int ret = 0;
  16481. int msglen = (sz - ssl->specs.aead_mac_size);
  16482. word32 keySz = 32;
  16483. byte padding[8]; /* used to temporarily store lengths */
  16484. #ifdef CHACHA_AEAD_TEST
  16485. printf("Using old version of poly1305 input.\n");
  16486. #endif
  16487. if (msglen < 0)
  16488. return INPUT_CASE_ERROR;
  16489. if ((ret = wc_Poly1305SetKey(ssl->auth.poly1305, cipher, keySz)) != 0)
  16490. return ret;
  16491. if ((ret = wc_Poly1305Update(ssl->auth.poly1305, additional,
  16492. AEAD_AUTH_DATA_SZ)) != 0)
  16493. return ret;
  16494. /* length of additional input plus padding */
  16495. XMEMSET(padding, 0, sizeof(padding));
  16496. padding[0] = AEAD_AUTH_DATA_SZ;
  16497. if ((ret = wc_Poly1305Update(ssl->auth.poly1305, padding,
  16498. sizeof(padding))) != 0)
  16499. return ret;
  16500. /* add cipher info and then its length */
  16501. XMEMSET(padding, 0, sizeof(padding));
  16502. if ((ret = wc_Poly1305Update(ssl->auth.poly1305, out, (word32)msglen)) != 0)
  16503. return ret;
  16504. /* 32 bit size of cipher to 64 bit endian */
  16505. padding[0] = msglen & 0xff;
  16506. padding[1] = (msglen >> 8) & 0xff;
  16507. padding[2] = ((word32)msglen >> 16) & 0xff;
  16508. padding[3] = ((word32)msglen >> 24) & 0xff;
  16509. if ((ret = wc_Poly1305Update(ssl->auth.poly1305, padding, sizeof(padding)))
  16510. != 0)
  16511. return ret;
  16512. /* generate tag */
  16513. if ((ret = wc_Poly1305Final(ssl->auth.poly1305, tag)) != 0)
  16514. return ret;
  16515. return ret;
  16516. }
  16517. /* When the flag oldPoly is not set this follows RFC7905. When oldPoly is set
  16518. * the implementation follows an older draft for creating the nonce and MAC.
  16519. * The flag oldPoly gets set automatically depending on what cipher suite was
  16520. * negotiated in the handshake. This is able to be done because the IDs for the
  16521. * cipher suites was updated in RFC7905 giving unique values for the older
  16522. * draft in comparison to the more recent RFC.
  16523. *
  16524. * ssl WOLFSSL structure to get cipher and TLS state from
  16525. * out output buffer to hold encrypted data
  16526. * input data to encrypt
  16527. * sz size of input
  16528. *
  16529. * Return 0 on success negative values in error case
  16530. */
  16531. int ChachaAEADEncrypt(WOLFSSL* ssl, byte* out, const byte* input,
  16532. word16 sz)
  16533. {
  16534. const byte* additionalSrc = input - RECORD_HEADER_SZ;
  16535. int ret = 0;
  16536. word32 msgLen = (sz - ssl->specs.aead_mac_size);
  16537. byte tag[POLY1305_AUTH_SZ];
  16538. byte add[AEAD_AUTH_DATA_SZ];
  16539. byte nonce[CHACHA20_NONCE_SZ];
  16540. byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for poly1305 */
  16541. #ifdef CHACHA_AEAD_TEST
  16542. int i;
  16543. #endif
  16544. Keys* keys = &ssl->keys;
  16545. XMEMSET(tag, 0, sizeof(tag));
  16546. XMEMSET(nonce, 0, sizeof(nonce));
  16547. XMEMSET(poly, 0, sizeof(poly));
  16548. XMEMSET(add, 0, sizeof(add));
  16549. #if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION)
  16550. /*
  16551. * For epochs 2+:
  16552. * * use ssl->secure_renegotiation when encrypting the current epoch as it
  16553. * has the current epoch cipher material
  16554. * * use PREV_ORDER if encrypting the epoch not in
  16555. * ssl->secure_renegotiation
  16556. */
  16557. /* opaque SEQ number stored for AD */
  16558. if (ssl->options.dtls && DtlsSCRKeysSet(ssl)) {
  16559. if (ssl->keys.dtls_epoch ==
  16560. ssl->secure_renegotiation->tmp_keys.dtls_epoch) {
  16561. keys = &ssl->secure_renegotiation->tmp_keys;
  16562. WriteSEQ(ssl, CUR_ORDER, add);
  16563. }
  16564. else
  16565. WriteSEQ(ssl, PREV_ORDER, add);
  16566. }
  16567. else
  16568. #endif
  16569. WriteSEQ(ssl, CUR_ORDER, add);
  16570. if (ssl->options.oldPoly != 0) {
  16571. /* get nonce. SEQ should not be incremented again here */
  16572. XMEMCPY(nonce + CHACHA20_OLD_OFFSET, add, OPAQUE32_LEN * 2);
  16573. }
  16574. /* Store the type, version. Unfortunately, they are in
  16575. * the input buffer ahead of the plaintext. */
  16576. #ifdef WOLFSSL_DTLS
  16577. if (ssl->options.dtls) {
  16578. additionalSrc -= DTLS_HANDSHAKE_EXTRA;
  16579. }
  16580. #endif
  16581. /* add TLS message size to additional data */
  16582. add[AEAD_AUTH_DATA_SZ - 2] = (msgLen >> 8) & 0xff;
  16583. add[AEAD_AUTH_DATA_SZ - 1] = msgLen & 0xff;
  16584. XMEMCPY(add + AEAD_TYPE_OFFSET, additionalSrc, 3);
  16585. #ifdef CHACHA_AEAD_TEST
  16586. printf("Encrypt Additional : ");
  16587. for (i = 0; i < AEAD_AUTH_DATA_SZ; i++) {
  16588. printf("%02x", add[i]);
  16589. }
  16590. printf("\n\n");
  16591. printf("input before encryption :\n");
  16592. for (i = 0; i < sz; i++) {
  16593. printf("%02x", input[i]);
  16594. if ((i + 1) % 16 == 0)
  16595. printf("\n");
  16596. }
  16597. printf("\n");
  16598. #endif
  16599. if (ssl->options.oldPoly == 0) {
  16600. /* nonce is formed by 4 0x00 byte padded to the left followed by 8 byte
  16601. * record sequence number XORed with client_write_IV/server_write_IV */
  16602. XMEMCPY(nonce, keys->aead_enc_imp_IV, CHACHA20_IMP_IV_SZ);
  16603. nonce[4] ^= add[0];
  16604. nonce[5] ^= add[1];
  16605. nonce[6] ^= add[2];
  16606. nonce[7] ^= add[3];
  16607. nonce[8] ^= add[4];
  16608. nonce[9] ^= add[5];
  16609. nonce[10] ^= add[6];
  16610. nonce[11] ^= add[7];
  16611. }
  16612. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16613. wc_MemZero_Add("ChachaAEADEncrypt nonce", nonce, CHACHA20_NONCE_SZ);
  16614. #endif
  16615. /* set the nonce for chacha and get poly1305 key */
  16616. if ((ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 0)) != 0) {
  16617. ForceZero(nonce, CHACHA20_NONCE_SZ);
  16618. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16619. wc_MemZero_Check(nonce, CHACHA20_NONCE_SZ);
  16620. #endif
  16621. return ret;
  16622. }
  16623. /* create Poly1305 key using chacha20 keystream */
  16624. if ((ret = wc_Chacha_Process(ssl->encrypt.chacha, poly,
  16625. poly, sizeof(poly))) != 0) {
  16626. ForceZero(nonce, CHACHA20_NONCE_SZ);
  16627. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16628. wc_MemZero_Check(nonce, CHACHA20_NONCE_SZ);
  16629. #endif
  16630. return ret;
  16631. }
  16632. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16633. wc_MemZero_Add("ChachaAEADEncrypt poly", poly, CHACHA20_256_KEY_SIZE);
  16634. #endif
  16635. /* set the counter after getting poly1305 key */
  16636. if ((ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 1)) != 0) {
  16637. ForceZero(nonce, CHACHA20_NONCE_SZ);
  16638. ForceZero(poly, sizeof(poly));
  16639. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16640. wc_MemZero_Check(nonce, CHACHA20_NONCE_SZ);
  16641. wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE);
  16642. #endif
  16643. return ret;
  16644. }
  16645. ForceZero(nonce, CHACHA20_NONCE_SZ); /* done with nonce, clear it */
  16646. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16647. wc_MemZero_Check(nonce, CHACHA20_NONCE_SZ);
  16648. #endif
  16649. /* encrypt the plain text */
  16650. if ((ret = wc_Chacha_Process(ssl->encrypt.chacha, out,
  16651. input, msgLen)) != 0) {
  16652. ForceZero(poly, sizeof(poly));
  16653. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16654. wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE);
  16655. #endif
  16656. return ret;
  16657. }
  16658. /* get the poly1305 tag using either old padding scheme or more recent */
  16659. if (ssl->options.oldPoly != 0) {
  16660. if ((ret = Poly1305TagOld(ssl, add, (const byte* )out,
  16661. poly, sz, tag)) != 0) {
  16662. ForceZero(poly, sizeof(poly));
  16663. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16664. wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE);
  16665. #endif
  16666. return ret;
  16667. }
  16668. }
  16669. else {
  16670. if ((ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly,
  16671. sizeof(poly))) != 0) {
  16672. ForceZero(poly, sizeof(poly));
  16673. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16674. wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE);
  16675. #endif
  16676. return ret;
  16677. }
  16678. if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, add,
  16679. sizeof(add), out, msgLen, tag, sizeof(tag))) != 0) {
  16680. ForceZero(poly, sizeof(poly));
  16681. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16682. wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE);
  16683. #endif
  16684. return ret;
  16685. }
  16686. }
  16687. ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
  16688. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16689. wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE);
  16690. #endif
  16691. /* append tag to ciphertext */
  16692. XMEMCPY(out + msgLen, tag, sizeof(tag));
  16693. AeadIncrementExpIV(ssl);
  16694. #ifdef CHACHA_AEAD_TEST
  16695. printf("mac tag :\n");
  16696. for (i = 0; i < 16; i++) {
  16697. printf("%02x", tag[i]);
  16698. if ((i + 1) % 16 == 0)
  16699. printf("\n");
  16700. }
  16701. printf("\n\noutput after encrypt :\n");
  16702. for (i = 0; i < sz; i++) {
  16703. printf("%02x", out[i]);
  16704. if ((i + 1) % 16 == 0)
  16705. printf("\n");
  16706. }
  16707. printf("\n");
  16708. #endif
  16709. return ret;
  16710. }
  16711. /* When the flag oldPoly is not set this follows RFC7905. When oldPoly is set
  16712. * the implementation follows an older draft for creating the nonce and MAC.
  16713. * The flag oldPoly gets set automatically depending on what cipher suite was
  16714. * negotiated in the handshake. This is able to be done because the IDs for the
  16715. * cipher suites was updated in RFC7905 giving unique values for the older
  16716. * draft in comparison to the more recent RFC.
  16717. *
  16718. * ssl WOLFSSL structure to get cipher and TLS state from
  16719. * plain output buffer to hold decrypted data
  16720. * input data to decrypt
  16721. * sz size of input
  16722. *
  16723. * Return 0 on success negative values in error case
  16724. */
  16725. int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input,
  16726. word16 sz)
  16727. {
  16728. byte add[AEAD_AUTH_DATA_SZ];
  16729. byte nonce[CHACHA20_NONCE_SZ];
  16730. byte tag[POLY1305_AUTH_SZ];
  16731. byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for mac */
  16732. int ret = 0;
  16733. int msgLen = (sz - ssl->specs.aead_mac_size);
  16734. Keys* keys = &ssl->keys;
  16735. #ifdef CHACHA_AEAD_TEST
  16736. int i;
  16737. printf("input before decrypt :\n");
  16738. for (i = 0; i < sz; i++) {
  16739. printf("%02x", input[i]);
  16740. if ((i + 1) % 16 == 0)
  16741. printf("\n");
  16742. }
  16743. printf("\n");
  16744. #endif
  16745. XMEMSET(tag, 0, sizeof(tag));
  16746. XMEMSET(poly, 0, sizeof(poly));
  16747. XMEMSET(nonce, 0, sizeof(nonce));
  16748. XMEMSET(add, 0, sizeof(add));
  16749. #if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION)
  16750. /*
  16751. * For epochs 2+:
  16752. * * use ssl->secure_renegotiation when decrypting the latest epoch as it
  16753. * has the latest epoch cipher material
  16754. */
  16755. if (ssl->options.dtls && DtlsSCRKeysSet(ssl) &&
  16756. ssl->keys.curEpoch == ssl->secure_renegotiation->tmp_keys.dtls_epoch)
  16757. keys = &ssl->secure_renegotiation->tmp_keys;
  16758. #endif
  16759. /* sequence number field is 64-bits */
  16760. WriteSEQ(ssl, PEER_ORDER, add);
  16761. if (ssl->options.oldPoly != 0) {
  16762. /* get nonce, SEQ should not be incremented again here */
  16763. XMEMCPY(nonce + CHACHA20_OLD_OFFSET, add, OPAQUE32_LEN * 2);
  16764. }
  16765. /* get AD info */
  16766. /* Store the type, version. */
  16767. add[AEAD_TYPE_OFFSET] = ssl->curRL.type;
  16768. add[AEAD_VMAJ_OFFSET] = ssl->curRL.pvMajor;
  16769. add[AEAD_VMIN_OFFSET] = ssl->curRL.pvMinor;
  16770. /* add TLS message size to additional data */
  16771. add[AEAD_AUTH_DATA_SZ - 2] = (msgLen >> 8) & 0xff;
  16772. add[AEAD_AUTH_DATA_SZ - 1] = msgLen & 0xff;
  16773. #ifdef CHACHA_AEAD_TEST
  16774. printf("Decrypt Additional : ");
  16775. for (i = 0; i < AEAD_AUTH_DATA_SZ; i++) {
  16776. printf("%02x", add[i]);
  16777. }
  16778. printf("\n\n");
  16779. #endif
  16780. if (ssl->options.oldPoly == 0) {
  16781. /* nonce is formed by 4 0x00 byte padded to the left followed by 8 byte
  16782. * record sequence number XORed with client_write_IV/server_write_IV */
  16783. XMEMCPY(nonce, keys->aead_dec_imp_IV, CHACHA20_IMP_IV_SZ);
  16784. nonce[4] ^= add[0];
  16785. nonce[5] ^= add[1];
  16786. nonce[6] ^= add[2];
  16787. nonce[7] ^= add[3];
  16788. nonce[8] ^= add[4];
  16789. nonce[9] ^= add[5];
  16790. nonce[10] ^= add[6];
  16791. nonce[11] ^= add[7];
  16792. }
  16793. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16794. wc_MemZero_Add("ChachaAEADEncrypt nonce", nonce, CHACHA20_NONCE_SZ);
  16795. #endif
  16796. /* set nonce and get poly1305 key */
  16797. if ((ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 0)) != 0) {
  16798. ForceZero(nonce, CHACHA20_NONCE_SZ);
  16799. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16800. wc_MemZero_Check(nonce, CHACHA20_NONCE_SZ);
  16801. #endif
  16802. return ret;
  16803. }
  16804. /* use chacha20 keystream to get poly1305 key for tag */
  16805. if ((ret = wc_Chacha_Process(ssl->decrypt.chacha, poly,
  16806. poly, sizeof(poly))) != 0) {
  16807. ForceZero(nonce, CHACHA20_NONCE_SZ);
  16808. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16809. wc_MemZero_Check(nonce, CHACHA20_NONCE_SZ);
  16810. #endif
  16811. return ret;
  16812. }
  16813. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16814. wc_MemZero_Add("ChachaAEADEncrypt poly", poly, CHACHA20_256_KEY_SIZE);
  16815. #endif
  16816. /* set counter after getting poly1305 key */
  16817. if ((ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 1)) != 0) {
  16818. ForceZero(nonce, CHACHA20_NONCE_SZ);
  16819. ForceZero(poly, sizeof(poly));
  16820. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16821. wc_MemZero_Check(nonce, CHACHA20_NONCE_SZ);
  16822. wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE);
  16823. #endif
  16824. return ret;
  16825. }
  16826. ForceZero(nonce, CHACHA20_NONCE_SZ); /* done with nonce, clear it */
  16827. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16828. wc_MemZero_Check(nonce, CHACHA20_NONCE_SZ);
  16829. #endif
  16830. /* get the tag using Poly1305 */
  16831. if (ssl->options.oldPoly != 0) {
  16832. if ((ret = Poly1305TagOld(ssl, add, input, poly, sz, tag)) != 0) {
  16833. ForceZero(poly, sizeof(poly));
  16834. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16835. wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE);
  16836. #endif
  16837. return ret;
  16838. }
  16839. }
  16840. else {
  16841. if ((ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly,
  16842. sizeof(poly))) != 0) {
  16843. ForceZero(poly, sizeof(poly));
  16844. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16845. wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE);
  16846. #endif
  16847. return ret;
  16848. }
  16849. if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, add,
  16850. sizeof(add), input, (word32)msgLen, tag, sizeof(tag))) != 0) {
  16851. ForceZero(poly, sizeof(poly));
  16852. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16853. wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE);
  16854. #endif
  16855. return ret;
  16856. }
  16857. }
  16858. ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
  16859. #ifdef WOLFSSL_CHECK_MEM_ZERO
  16860. wc_MemZero_Check(poly, CHACHA20_256_KEY_SIZE);
  16861. #endif
  16862. /* check tag sent along with packet */
  16863. if (ConstantCompare(input + msgLen, tag, ssl->specs.aead_mac_size) != 0) {
  16864. WOLFSSL_MSG("MAC did not match");
  16865. if (!ssl->options.dtls)
  16866. SendAlert(ssl, alert_fatal, bad_record_mac);
  16867. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  16868. return VERIFY_MAC_ERROR;
  16869. }
  16870. /* if the tag was good decrypt message */
  16871. if ((ret = wc_Chacha_Process(ssl->decrypt.chacha, plain,
  16872. input, (word32)msgLen)) != 0)
  16873. return ret;
  16874. #ifdef CHACHA_AEAD_TEST
  16875. printf("plain after decrypt :\n");
  16876. for (i = 0; i < sz; i++) {
  16877. printf("%02x", plain[i]);
  16878. if ((i + 1) % 16 == 0)
  16879. printf("\n");
  16880. }
  16881. printf("\n");
  16882. #endif
  16883. return ret;
  16884. }
  16885. #endif /* HAVE_CHACHA && HAVE_POLY1305 && !NO_CHAPOL_AEAD*/
  16886. #endif /* HAVE_AEAD */
  16887. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
  16888. #if !defined(NO_GCM_ENCRYPT_EXTRA) && \
  16889. ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
  16890. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
  16891. /* The following type is used to share code between AES-GCM and AES-CCM. */
  16892. typedef int (*AesAuthEncryptFunc)(Aes* aes, byte* out,
  16893. const byte* in, word32 sz,
  16894. byte* iv, word32 ivSz,
  16895. byte* authTag, word32 authTagSz,
  16896. const byte* authIn, word32 authInSz);
  16897. #define AES_AUTH_ENCRYPT_FUNC AesAuthEncryptFunc
  16898. #define AES_GCM_ENCRYPT wc_AesGcmEncrypt_ex
  16899. #define AES_CCM_ENCRYPT wc_AesCcmEncrypt_ex
  16900. #else
  16901. #define AES_AUTH_ENCRYPT_FUNC wc_AesAuthEncryptFunc
  16902. #define AES_GCM_ENCRYPT wc_AesGcmEncrypt
  16903. #define AES_CCM_ENCRYPT wc_AesCcmEncrypt
  16904. #endif
  16905. #endif
  16906. #if defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)
  16907. /* The following type is used to share code between SM4-GCM and SM4-CCM. */
  16908. typedef int (*Sm4AuthEncryptFunc)(wc_Sm4* sm4, byte* out, const byte* in,
  16909. word32 sz, const byte* nonce, word32 nonceSz, byte* tag, word32 tagSz,
  16910. const byte* aad, word32 aadSz);
  16911. typedef int (*Sm4AuthDecryptFunc)(wc_Sm4* sm4, byte* out, const byte* in,
  16912. word32 sz, const byte* nonce, word32 nonceSz, const byte* tag, word32 tagSz,
  16913. const byte* aad, word32 aadSz);
  16914. #define SM4_AUTH_ENCRYPT_FUNC Sm4AuthEncryptFunc
  16915. #define SM4_AUTH_DECRYPT_FUNC Sm4AuthDecryptFunc
  16916. #define SM4_GCM_ENCRYPT_FUNC wc_Sm4GcmEncrypt
  16917. #define SM4_CCM_ENCRYPT_FUNC wc_Sm4CcmEncrypt
  16918. #define SM4_GCM_DECRYPT_FUNC wc_Sm4GcmDecrypt
  16919. #define SM4_CCM_DECRYPT_FUNC wc_Sm4CcmDecrypt
  16920. #endif
  16921. static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input,
  16922. word16 sz, int asyncOkay)
  16923. {
  16924. int ret = 0;
  16925. #ifdef WOLFSSL_ASYNC_CRYPT
  16926. WC_ASYNC_DEV* asyncDev = NULL;
  16927. word32 event_flags = WC_ASYNC_FLAG_CALL_AGAIN;
  16928. #else
  16929. (void)asyncOkay;
  16930. #endif
  16931. (void)out;
  16932. (void)input;
  16933. (void)sz;
  16934. if (input == NULL) {
  16935. return BAD_FUNC_ARG;
  16936. }
  16937. switch (ssl->specs.bulk_cipher_algorithm) {
  16938. #ifdef BUILD_ARC4
  16939. case wolfssl_rc4:
  16940. wc_Arc4Process(ssl->encrypt.arc4, out, input, sz);
  16941. break;
  16942. #endif
  16943. #ifdef BUILD_DES3
  16944. case wolfssl_triple_des:
  16945. #ifdef WOLFSSL_ASYNC_CRYPT
  16946. /* initialize event */
  16947. asyncDev = &ssl->encrypt.des3->asyncDev;
  16948. ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
  16949. if (ret != 0)
  16950. break;
  16951. #endif
  16952. ret = wc_Des3_CbcEncrypt(ssl->encrypt.des3, out, input, sz);
  16953. #ifdef WOLFSSL_ASYNC_CRYPT
  16954. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && asyncOkay) {
  16955. ret = wolfSSL_AsyncPush(ssl, asyncDev);
  16956. }
  16957. #endif
  16958. break;
  16959. #endif
  16960. #if defined(BUILD_AES) && defined(HAVE_AES_CBC)
  16961. case wolfssl_aes:
  16962. #ifdef WOLFSSL_ASYNC_CRYPT
  16963. /* initialize event */
  16964. asyncDev = &ssl->encrypt.aes->asyncDev;
  16965. ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
  16966. if (ret != 0)
  16967. break;
  16968. #endif
  16969. ret = wc_AesCbcEncrypt(ssl->encrypt.aes, out, input, sz);
  16970. #ifdef WOLFSSL_ASYNC_CRYPT
  16971. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && asyncOkay) {
  16972. ret = wolfSSL_AsyncPush(ssl, asyncDev);
  16973. }
  16974. #endif
  16975. break;
  16976. #endif
  16977. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
  16978. case wolfssl_aes_gcm:
  16979. case wolfssl_aes_ccm:/* GCM AEAD macros use same size as CCM */
  16980. {
  16981. AES_AUTH_ENCRYPT_FUNC aes_auth_fn;
  16982. const byte* additionalSrc;
  16983. #ifdef WOLFSSL_ASYNC_CRYPT
  16984. /* initialize event */
  16985. asyncDev = &ssl->encrypt.aes->asyncDev;
  16986. ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
  16987. if (ret != 0)
  16988. break;
  16989. #endif
  16990. #if defined(BUILD_AESGCM) && defined(HAVE_AESCCM)
  16991. aes_auth_fn = (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm)
  16992. ? AES_GCM_ENCRYPT : AES_CCM_ENCRYPT;
  16993. #elif defined(BUILD_AESGCM)
  16994. aes_auth_fn = AES_GCM_ENCRYPT;
  16995. #else
  16996. aes_auth_fn = AES_CCM_ENCRYPT;
  16997. #endif
  16998. additionalSrc = input - 5;
  16999. XMEMSET(ssl->encrypt.additional, 0, AEAD_AUTH_DATA_SZ);
  17000. /* sequence number field is 64-bits */
  17001. WriteSEQ(ssl, CUR_ORDER, ssl->encrypt.additional);
  17002. /* Store the type, version. Unfortunately, they are in
  17003. * the input buffer ahead of the plaintext. */
  17004. #ifdef WOLFSSL_DTLS
  17005. if (ssl->options.dtls) {
  17006. additionalSrc -= DTLS_HANDSHAKE_EXTRA;
  17007. }
  17008. #endif
  17009. XMEMCPY(ssl->encrypt.additional + AEAD_TYPE_OFFSET,
  17010. additionalSrc, 3);
  17011. /* Store the length of the plain text minus the explicit
  17012. * IV length minus the authentication tag size. */
  17013. c16toa(sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17014. ssl->encrypt.additional + AEAD_LEN_OFFSET);
  17015. #if !defined(NO_PUBLIC_GCM_SET_IV) && \
  17016. ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
  17017. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
  17018. XMEMCPY(ssl->encrypt.nonce,
  17019. ssl->keys.aead_enc_imp_IV, AESGCM_IMP_IV_SZ);
  17020. XMEMCPY(ssl->encrypt.nonce + AESGCM_IMP_IV_SZ,
  17021. ssl->keys.aead_exp_IV, AESGCM_EXP_IV_SZ);
  17022. #endif
  17023. #ifdef HAVE_PK_CALLBACKS
  17024. ret = NOT_COMPILED_IN;
  17025. if (ssl->ctx && ssl->ctx->PerformTlsRecordProcessingCb) {
  17026. ret = ssl->ctx->PerformTlsRecordProcessingCb(ssl, 1,
  17027. out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ,
  17028. sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17029. ssl->encrypt.nonce, AESGCM_NONCE_SZ,
  17030. out + sz - ssl->specs.aead_mac_size,
  17031. ssl->specs.aead_mac_size,
  17032. ssl->encrypt.additional, AEAD_AUTH_DATA_SZ);
  17033. }
  17034. if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
  17035. #endif /* HAVE_PK_CALLBACKS */
  17036. {
  17037. ret = aes_auth_fn(ssl->encrypt.aes,
  17038. out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ,
  17039. sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17040. ssl->encrypt.nonce, AESGCM_NONCE_SZ,
  17041. out + sz - ssl->specs.aead_mac_size,
  17042. ssl->specs.aead_mac_size,
  17043. ssl->encrypt.additional, AEAD_AUTH_DATA_SZ);
  17044. }
  17045. #ifdef WOLFSSL_ASYNC_CRYPT
  17046. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && asyncOkay) {
  17047. ret = wolfSSL_AsyncPush(ssl, asyncDev);
  17048. }
  17049. #endif
  17050. #if !defined(NO_PUBLIC_GCM_SET_IV) && \
  17051. ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
  17052. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
  17053. XMEMCPY(out,
  17054. ssl->encrypt.nonce + AESGCM_IMP_IV_SZ, AESGCM_EXP_IV_SZ);
  17055. #endif
  17056. }
  17057. break;
  17058. #endif /* BUILD_AESGCM || HAVE_AESCCM */
  17059. #ifdef HAVE_ARIA
  17060. case wolfssl_aria_gcm:
  17061. {
  17062. const byte* additionalSrc = input - RECORD_HEADER_SZ;
  17063. byte *outBuf = NULL;
  17064. XMEMSET(ssl->encrypt.additional, 0, AEAD_AUTH_DATA_SZ);
  17065. /* sequence number field is 64-bits */
  17066. WriteSEQ(ssl, CUR_ORDER, ssl->encrypt.additional);
  17067. /* Store the type, version. Unfortunately, they are in
  17068. * the input buffer ahead of the plaintext. */
  17069. #ifdef WOLFSSL_DTLS
  17070. if (ssl->options.dtls) {
  17071. additionalSrc -= DTLS_HANDSHAKE_EXTRA;
  17072. }
  17073. #endif
  17074. XMEMCPY(ssl->encrypt.additional + AEAD_TYPE_OFFSET,
  17075. additionalSrc, 3);
  17076. /* Store the length of the plain text minus the explicit
  17077. * IV length minus the authentication tag size. */
  17078. c16toa(sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17079. ssl->encrypt.additional + AEAD_LEN_OFFSET);
  17080. XMEMCPY(ssl->encrypt.nonce,
  17081. ssl->keys.aead_enc_imp_IV, AESGCM_IMP_IV_SZ);
  17082. XMEMCPY(ssl->encrypt.nonce + AESGCM_IMP_IV_SZ,
  17083. ssl->keys.aead_exp_IV, AESGCM_EXP_IV_SZ);
  17084. outBuf = (byte*)XMALLOC(sz - AESGCM_EXP_IV_SZ, ssl->heap,
  17085. DYNAMIC_TYPE_TMP_BUFFER);
  17086. if (outBuf == NULL) {
  17087. ret = MEMORY_ERROR;
  17088. break;
  17089. }
  17090. ret = wc_AriaEncrypt(ssl->encrypt.aria, outBuf,
  17091. (byte*) input + AESGCM_EXP_IV_SZ,
  17092. sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17093. ssl->encrypt.nonce, AESGCM_NONCE_SZ,
  17094. ssl->encrypt.additional, AEAD_AUTH_DATA_SZ,
  17095. out + sz - ssl->specs.aead_mac_size,
  17096. ssl->specs.aead_mac_size
  17097. );
  17098. if (ret != 0)
  17099. break;
  17100. XMEMCPY(out,
  17101. ssl->encrypt.nonce + AESGCM_IMP_IV_SZ, AESGCM_EXP_IV_SZ);
  17102. XMEMCPY(out + AESGCM_EXP_IV_SZ,outBuf,sz - AESGCM_EXP_IV_SZ);
  17103. XFREE(outBuf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  17104. break;
  17105. }
  17106. #endif
  17107. #ifdef HAVE_CAMELLIA
  17108. case wolfssl_camellia:
  17109. ret = wc_CamelliaCbcEncrypt(ssl->encrypt.cam, out, input, sz);
  17110. break;
  17111. #endif
  17112. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \
  17113. !defined(NO_CHAPOL_AEAD)
  17114. case wolfssl_chacha:
  17115. ret = ChachaAEADEncrypt(ssl, out, input, sz);
  17116. break;
  17117. #endif
  17118. #ifdef WOLFSSL_SM4_CBC
  17119. case wolfssl_sm4_cbc:
  17120. #ifdef WOLFSSL_ASYNC_CRYPT
  17121. /* initialize event */
  17122. asyncDev = &ssl->encrypt.sm4->asyncDev;
  17123. ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
  17124. if (ret != 0)
  17125. break;
  17126. #endif
  17127. ret = wc_Sm4CbcEncrypt(ssl->encrypt.sm4, out, input, sz);
  17128. #ifdef WOLFSSL_ASYNC_CRYPT
  17129. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && asyncOkay) {
  17130. ret = wolfSSL_AsyncPush(ssl, asyncDev);
  17131. }
  17132. #endif
  17133. break;
  17134. #endif
  17135. #if defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)
  17136. case wolfssl_sm4_gcm:
  17137. case wolfssl_sm4_ccm:/* GCM AEAD macros use same size as CCM */
  17138. {
  17139. SM4_AUTH_ENCRYPT_FUNC sm4_auth_fn;
  17140. const byte* additionalSrc;
  17141. #ifdef WOLFSSL_ASYNC_CRYPT
  17142. /* initialize event */
  17143. asyncDev = &ssl->encrypt.sm4->asyncDev;
  17144. ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
  17145. if (ret != 0)
  17146. break;
  17147. #endif
  17148. #if defined(WOLFSSL_SM4_GCM) && defined(WOLFSSL_SM4_CCM)
  17149. sm4_auth_fn = (ssl->specs.bulk_cipher_algorithm == wolfssl_sm4_gcm)
  17150. ? SM4_GCM_ENCRYPT_FUNC : SM4_CCM_ENCRYPT_FUNC;
  17151. #elif defined(WOLFSSL_SM4_GCM)
  17152. sm4_auth_fn = SM4_GCM_ENCRYPT_FUNC;
  17153. #else
  17154. sm4_auth_fn = SM4_CCM_ENCRYPT_FUNC;
  17155. #endif
  17156. additionalSrc = input - 5;
  17157. XMEMSET(ssl->encrypt.additional, 0, AEAD_AUTH_DATA_SZ);
  17158. /* sequence number field is 64-bits */
  17159. WriteSEQ(ssl, CUR_ORDER, ssl->encrypt.additional);
  17160. /* Store the type, version. Unfortunately, they are in
  17161. * the input buffer ahead of the plaintext. */
  17162. #ifdef WOLFSSL_DTLS
  17163. if (ssl->options.dtls) {
  17164. additionalSrc -= DTLS_HANDSHAKE_EXTRA;
  17165. }
  17166. #endif
  17167. XMEMCPY(ssl->encrypt.additional + AEAD_TYPE_OFFSET,
  17168. additionalSrc, 3);
  17169. /* Store the length of the plain text minus the explicit
  17170. * IV length minus the authentication tag size. */
  17171. c16toa(sz - GCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17172. ssl->encrypt.additional + AEAD_LEN_OFFSET);
  17173. XMEMCPY(ssl->encrypt.nonce,
  17174. ssl->keys.aead_enc_imp_IV, GCM_IMP_IV_SZ);
  17175. XMEMCPY(ssl->encrypt.nonce + GCM_IMP_IV_SZ,
  17176. ssl->keys.aead_exp_IV, GCM_EXP_IV_SZ);
  17177. ret = sm4_auth_fn(ssl->encrypt.sm4,
  17178. out + GCM_EXP_IV_SZ, input + GCM_EXP_IV_SZ,
  17179. sz - GCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17180. ssl->encrypt.nonce, GCM_NONCE_SZ,
  17181. out + sz - ssl->specs.aead_mac_size,
  17182. ssl->specs.aead_mac_size,
  17183. ssl->encrypt.additional, AEAD_AUTH_DATA_SZ);
  17184. #ifdef WOLFSSL_ASYNC_CRYPT
  17185. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && asyncOkay) {
  17186. ret = wolfSSL_AsyncPush(ssl, asyncDev);
  17187. }
  17188. #endif
  17189. #if !defined(NO_PUBLIC_GCM_SET_IV) && \
  17190. ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
  17191. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
  17192. XMEMCPY(out,
  17193. ssl->encrypt.nonce + GCM_IMP_IV_SZ, GCM_EXP_IV_SZ);
  17194. #endif
  17195. }
  17196. break;
  17197. #endif /* WOLFSSL_SM4_GCM || WOLFSSL_SM4_CCM */
  17198. #ifdef HAVE_NULL_CIPHER
  17199. case wolfssl_cipher_null:
  17200. if (input != out) {
  17201. XMEMMOVE(out, input, sz);
  17202. }
  17203. break;
  17204. #endif
  17205. default:
  17206. WOLFSSL_MSG("wolfSSL Encrypt programming error");
  17207. ret = ENCRYPT_ERROR;
  17208. WOLFSSL_ERROR_VERBOSE(ret);
  17209. }
  17210. #ifdef WOLFSSL_ASYNC_CRYPT
  17211. /* if async is not okay, then block */
  17212. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) && !asyncOkay) {
  17213. ret = wc_AsyncWait(ret, asyncDev, event_flags);
  17214. }
  17215. #endif
  17216. return ret;
  17217. }
  17218. static WC_INLINE int Encrypt(WOLFSSL* ssl, byte* out, const byte* input,
  17219. word16 sz, int asyncOkay)
  17220. {
  17221. int ret = 0;
  17222. #ifdef WOLFSSL_ASYNC_CRYPT
  17223. if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  17224. ssl->error = 0; /* clear async */
  17225. }
  17226. #endif
  17227. switch (ssl->encrypt.state) {
  17228. case CIPHER_STATE_BEGIN:
  17229. {
  17230. if (ssl->encrypt.setup == 0) {
  17231. WOLFSSL_MSG("Encrypt ciphers not setup");
  17232. WOLFSSL_ERROR_VERBOSE(ENCRYPT_ERROR);
  17233. return ENCRYPT_ERROR;
  17234. }
  17235. #ifdef WOLFSSL_CIPHER_TEXT_CHECK
  17236. if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) {
  17237. XMEMCPY(ssl->encrypt.sanityCheck, input,
  17238. min(sz, sizeof(ssl->encrypt.sanityCheck)));
  17239. }
  17240. #endif
  17241. #ifdef HAVE_FUZZER
  17242. if (ssl->fuzzerCb)
  17243. ssl->fuzzerCb(ssl, input, sz, FUZZ_ENCRYPT, ssl->fuzzerCtx);
  17244. #endif
  17245. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM) || defined(HAVE_ARIA)
  17246. /* make sure AES GCM/CCM memory is allocated */
  17247. /* free for these happens in FreeCiphers */
  17248. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
  17249. ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm ||
  17250. ssl->specs.bulk_cipher_algorithm == wolfssl_aria_gcm) {
  17251. /* make sure auth iv and auth are allocated */
  17252. if (ssl->encrypt.additional == NULL)
  17253. ssl->encrypt.additional = (byte*)XMALLOC(AEAD_AUTH_DATA_SZ,
  17254. ssl->heap, DYNAMIC_TYPE_CIPHER);
  17255. if (ssl->encrypt.nonce == NULL) {
  17256. ssl->encrypt.nonce = (byte*)XMALLOC(AESGCM_NONCE_SZ,
  17257. ssl->heap, DYNAMIC_TYPE_CIPHER);
  17258. #ifdef WOLFSSL_CHECK_MEM_ZERO
  17259. if (ssl->encrypt.nonce != NULL) {
  17260. wc_MemZero_Add("Encrypt nonce", ssl->encrypt.nonce,
  17261. AESGCM_NONCE_SZ);
  17262. }
  17263. #endif
  17264. }
  17265. if (ssl->encrypt.additional == NULL ||
  17266. ssl->encrypt.nonce == NULL) {
  17267. return MEMORY_E;
  17268. }
  17269. }
  17270. #endif /* BUILD_AESGCM || HAVE_AESCCM || HAVE_ARIA */
  17271. #if defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)
  17272. /* make sure SM4 GCM/CCM memory is allocated */
  17273. /* free for these happens in FreeCiphers */
  17274. if (ssl->specs.bulk_cipher_algorithm == wolfssl_sm4_ccm ||
  17275. ssl->specs.bulk_cipher_algorithm == wolfssl_sm4_gcm) {
  17276. /* make sure auth iv and auth are allocated */
  17277. if (ssl->encrypt.additional == NULL)
  17278. ssl->encrypt.additional = (byte*)XMALLOC(AEAD_AUTH_DATA_SZ,
  17279. ssl->heap, DYNAMIC_TYPE_CIPHER);
  17280. if (ssl->encrypt.nonce == NULL) {
  17281. ssl->encrypt.nonce = (byte*)XMALLOC(GCM_NONCE_SZ,
  17282. ssl->heap, DYNAMIC_TYPE_CIPHER);
  17283. #ifdef WOLFSSL_CHECK_MEM_ZERO
  17284. if (ssl->encrypt.nonce != NULL) {
  17285. wc_MemZero_Add("Encrypt nonce", ssl->encrypt.nonce,
  17286. GCM_NONCE_SZ);
  17287. }
  17288. #endif
  17289. }
  17290. if (ssl->encrypt.additional == NULL ||
  17291. ssl->encrypt.nonce == NULL) {
  17292. return MEMORY_E;
  17293. }
  17294. }
  17295. #endif /* WOLFSSL_SM4_GCM || WOLFSSL_SM4_CCM */
  17296. /* Advance state and proceed */
  17297. ssl->encrypt.state = CIPHER_STATE_DO;
  17298. }
  17299. FALL_THROUGH;
  17300. case CIPHER_STATE_DO:
  17301. {
  17302. ret = EncryptDo(ssl, out, input, sz, asyncOkay);
  17303. /* Advance state */
  17304. ssl->encrypt.state = CIPHER_STATE_END;
  17305. #ifdef WOLFSSL_ASYNC_CRYPT
  17306. /* If pending, then leave and return will resume below */
  17307. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  17308. return ret;
  17309. }
  17310. #endif
  17311. }
  17312. FALL_THROUGH;
  17313. case CIPHER_STATE_END:
  17314. {
  17315. #ifdef WOLFSSL_CIPHER_TEXT_CHECK
  17316. if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null &&
  17317. XMEMCMP(out, ssl->encrypt.sanityCheck,
  17318. min(sz, sizeof(ssl->encrypt.sanityCheck))) == 0) {
  17319. WOLFSSL_MSG("Encrypt sanity check failed! Glitch?");
  17320. WOLFSSL_ERROR_VERBOSE(ENCRYPT_ERROR);
  17321. return ENCRYPT_ERROR;
  17322. }
  17323. ForceZero(ssl->encrypt.sanityCheck,
  17324. sizeof(ssl->encrypt.sanityCheck));
  17325. #endif
  17326. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM) || defined(HAVE_ARIA)
  17327. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
  17328. ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm ||
  17329. ssl->specs.bulk_cipher_algorithm == wolfssl_aria_gcm)
  17330. {
  17331. /* finalize authentication cipher */
  17332. #if !defined(NO_PUBLIC_GCM_SET_IV) && \
  17333. ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
  17334. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
  17335. AeadIncrementExpIV(ssl);
  17336. #endif
  17337. if (ssl->encrypt.nonce)
  17338. ForceZero(ssl->encrypt.nonce, AESGCM_NONCE_SZ);
  17339. }
  17340. #endif /* BUILD_AESGCM || HAVE_AESCCM || HAVE_ARIA */
  17341. #if defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)
  17342. if (ssl->specs.bulk_cipher_algorithm == wolfssl_sm4_ccm ||
  17343. ssl->specs.bulk_cipher_algorithm == wolfssl_sm4_gcm)
  17344. {
  17345. /* finalize authentication cipher */
  17346. AeadIncrementExpIV(ssl);
  17347. if (ssl->encrypt.nonce)
  17348. ForceZero(ssl->encrypt.nonce, GCM_NONCE_SZ);
  17349. }
  17350. #endif /* WOLFSSL_SM4_GCM || WOLFSSL_SM4_CCM */
  17351. #ifdef WOLFSSL_CHECK_MEM_ZERO
  17352. if ((ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) &&
  17353. (out != input) && (ret == 0)) {
  17354. wc_MemZero_Add("TLS Encrypt plaintext", input, sz);
  17355. }
  17356. #endif
  17357. break;
  17358. }
  17359. default:
  17360. break;
  17361. }
  17362. /* Reset state */
  17363. ssl->encrypt.state = CIPHER_STATE_BEGIN;
  17364. return ret;
  17365. }
  17366. static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input,
  17367. word16 sz)
  17368. {
  17369. int ret = 0;
  17370. (void)plain;
  17371. (void)input;
  17372. (void)sz;
  17373. switch (ssl->specs.bulk_cipher_algorithm)
  17374. {
  17375. #ifdef BUILD_ARC4
  17376. case wolfssl_rc4:
  17377. wc_Arc4Process(ssl->decrypt.arc4, plain, input, sz);
  17378. break;
  17379. #endif
  17380. #ifdef BUILD_DES3
  17381. case wolfssl_triple_des:
  17382. #ifdef WOLFSSL_ASYNC_CRYPT
  17383. /* initialize event */
  17384. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.des3->asyncDev,
  17385. WC_ASYNC_FLAG_CALL_AGAIN);
  17386. if (ret != 0)
  17387. break;
  17388. #endif
  17389. ret = wc_Des3_CbcDecrypt(ssl->decrypt.des3, plain, input, sz);
  17390. #ifdef WOLFSSL_ASYNC_CRYPT
  17391. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  17392. ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.des3->asyncDev);
  17393. }
  17394. #endif
  17395. break;
  17396. #endif
  17397. #if defined(BUILD_AES) && defined(HAVE_AES_CBC)
  17398. case wolfssl_aes:
  17399. #ifdef WOLFSSL_ASYNC_CRYPT
  17400. /* initialize event */
  17401. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
  17402. WC_ASYNC_FLAG_CALL_AGAIN);
  17403. if (ret != 0)
  17404. break;
  17405. #endif
  17406. ret = wc_AesCbcDecrypt(ssl->decrypt.aes, plain, input, sz);
  17407. #ifdef WOLFSSL_ASYNC_CRYPT
  17408. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  17409. ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev);
  17410. }
  17411. #endif
  17412. break;
  17413. #endif
  17414. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
  17415. case wolfssl_aes_gcm:
  17416. case wolfssl_aes_ccm: /* GCM AEAD macros use same size as CCM */
  17417. {
  17418. wc_AesAuthDecryptFunc aes_auth_fn;
  17419. #ifdef WOLFSSL_ASYNC_CRYPT
  17420. /* initialize event */
  17421. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
  17422. WC_ASYNC_FLAG_CALL_AGAIN);
  17423. if (ret != 0)
  17424. break;
  17425. #endif
  17426. #if defined(BUILD_AESGCM) && defined(HAVE_AESCCM)
  17427. aes_auth_fn = (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm)
  17428. ? wc_AesGcmDecrypt : wc_AesCcmDecrypt;
  17429. #elif defined(BUILD_AESGCM)
  17430. aes_auth_fn = wc_AesGcmDecrypt;
  17431. #else
  17432. aes_auth_fn = wc_AesCcmDecrypt;
  17433. #endif
  17434. XMEMSET(ssl->decrypt.additional, 0, AEAD_AUTH_DATA_SZ);
  17435. /* sequence number field is 64-bits */
  17436. WriteSEQ(ssl, PEER_ORDER, ssl->decrypt.additional);
  17437. ssl->decrypt.additional[AEAD_TYPE_OFFSET] = ssl->curRL.type;
  17438. ssl->decrypt.additional[AEAD_VMAJ_OFFSET] = ssl->curRL.pvMajor;
  17439. ssl->decrypt.additional[AEAD_VMIN_OFFSET] = ssl->curRL.pvMinor;
  17440. c16toa(sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17441. ssl->decrypt.additional + AEAD_LEN_OFFSET);
  17442. #if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION)
  17443. if (ssl->options.dtls && IsDtlsMsgSCRKeys(ssl))
  17444. XMEMCPY(ssl->decrypt.nonce,
  17445. ssl->secure_renegotiation->tmp_keys.aead_dec_imp_IV,
  17446. AESGCM_IMP_IV_SZ);
  17447. else
  17448. #endif
  17449. XMEMCPY(ssl->decrypt.nonce, ssl->keys.aead_dec_imp_IV,
  17450. AESGCM_IMP_IV_SZ);
  17451. XMEMCPY(ssl->decrypt.nonce + AESGCM_IMP_IV_SZ, input,
  17452. AESGCM_EXP_IV_SZ);
  17453. #ifdef HAVE_PK_CALLBACKS
  17454. ret = NOT_COMPILED_IN;
  17455. if (ssl->ctx && ssl->ctx->PerformTlsRecordProcessingCb) {
  17456. ret = ssl->ctx->PerformTlsRecordProcessingCb(ssl, 0,
  17457. plain + AESGCM_EXP_IV_SZ,
  17458. input + AESGCM_EXP_IV_SZ,
  17459. sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17460. ssl->decrypt.nonce, AESGCM_NONCE_SZ,
  17461. (byte *)(input + sz - ssl->specs.aead_mac_size),
  17462. ssl->specs.aead_mac_size,
  17463. ssl->decrypt.additional, AEAD_AUTH_DATA_SZ);
  17464. }
  17465. if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
  17466. #endif /* HAVE_PK_CALLBACKS */
  17467. {
  17468. if ((ret = aes_auth_fn(ssl->decrypt.aes,
  17469. plain + AESGCM_EXP_IV_SZ,
  17470. input + AESGCM_EXP_IV_SZ,
  17471. sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17472. ssl->decrypt.nonce, AESGCM_NONCE_SZ,
  17473. input + sz - ssl->specs.aead_mac_size,
  17474. ssl->specs.aead_mac_size,
  17475. ssl->decrypt.additional, AEAD_AUTH_DATA_SZ)) < 0) {
  17476. #ifdef WOLFSSL_ASYNC_CRYPT
  17477. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  17478. ret = wolfSSL_AsyncPush(ssl,
  17479. &ssl->decrypt.aes->asyncDev);
  17480. }
  17481. #endif
  17482. }
  17483. }
  17484. }
  17485. break;
  17486. #endif /* BUILD_AESGCM || HAVE_AESCCM */
  17487. #ifdef HAVE_ARIA
  17488. case wolfssl_aria_gcm:
  17489. {
  17490. byte *outBuf = NULL;
  17491. XMEMSET(ssl->decrypt.additional, 0, AEAD_AUTH_DATA_SZ);
  17492. /* sequence number field is 64-bits */
  17493. WriteSEQ(ssl, PEER_ORDER, ssl->decrypt.additional);
  17494. ssl->decrypt.additional[AEAD_TYPE_OFFSET] = ssl->curRL.type;
  17495. ssl->decrypt.additional[AEAD_VMAJ_OFFSET] = ssl->curRL.pvMajor;
  17496. ssl->decrypt.additional[AEAD_VMIN_OFFSET] = ssl->curRL.pvMinor;
  17497. c16toa(sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17498. ssl->decrypt.additional + AEAD_LEN_OFFSET);
  17499. #if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION)
  17500. if (ssl->options.dtls && IsDtlsMsgSCRKeys(ssl))
  17501. XMEMCPY(ssl->decrypt.nonce,
  17502. ssl->secure_renegotiation->tmp_keys.aead_dec_imp_IV,
  17503. AESGCM_IMP_IV_SZ);
  17504. else
  17505. #endif
  17506. XMEMCPY(ssl->decrypt.nonce, ssl->keys.aead_dec_imp_IV,
  17507. AESGCM_IMP_IV_SZ);
  17508. XMEMCPY(ssl->decrypt.nonce + AESGCM_IMP_IV_SZ, input,
  17509. AESGCM_EXP_IV_SZ);
  17510. outBuf = (byte*)XMALLOC(sz - AESGCM_EXP_IV_SZ, ssl->heap,
  17511. DYNAMIC_TYPE_TMP_BUFFER);
  17512. if (outBuf == NULL) {
  17513. ret = MEMORY_ERROR;
  17514. break;
  17515. }
  17516. ret = wc_AriaDecrypt(ssl->decrypt.aria, outBuf,
  17517. (byte *)input + AESGCM_EXP_IV_SZ,
  17518. sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17519. ssl->decrypt.nonce, AESGCM_NONCE_SZ,
  17520. ssl->decrypt.additional, AEAD_AUTH_DATA_SZ,
  17521. (byte *)input + sz - ssl->specs.aead_mac_size,
  17522. ssl->specs.aead_mac_size
  17523. );
  17524. if (ret != 0)
  17525. break;
  17526. XMEMCPY(plain + AESGCM_EXP_IV_SZ,
  17527. outBuf,
  17528. sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size);
  17529. XFREE(outBuf, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  17530. break;
  17531. }
  17532. #endif /* HAVE_ARIA */
  17533. #ifdef HAVE_CAMELLIA
  17534. case wolfssl_camellia:
  17535. ret = wc_CamelliaCbcDecrypt(ssl->decrypt.cam, plain, input, sz);
  17536. break;
  17537. #endif
  17538. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \
  17539. !defined(NO_CHAPOL_AEAD)
  17540. case wolfssl_chacha:
  17541. ret = ChachaAEADDecrypt(ssl, plain, input, sz);
  17542. break;
  17543. #endif
  17544. #ifdef WOLFSSL_SM4_CBC
  17545. case wolfssl_sm4_cbc:
  17546. #ifdef WOLFSSL_ASYNC_CRYPT
  17547. /* initialize event */
  17548. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
  17549. WC_ASYNC_FLAG_CALL_AGAIN);
  17550. if (ret != 0)
  17551. break;
  17552. #endif
  17553. ret = wc_Sm4CbcDecrypt(ssl->decrypt.sm4, plain, input, sz);
  17554. #ifdef WOLFSSL_ASYNC_CRYPT
  17555. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  17556. ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev);
  17557. }
  17558. #endif
  17559. break;
  17560. #endif
  17561. #if defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)
  17562. case wolfssl_sm4_gcm:
  17563. case wolfssl_sm4_ccm: /* GCM AEAD macros use same size as CCM */
  17564. {
  17565. SM4_AUTH_DECRYPT_FUNC sm4_auth_fn;
  17566. #ifdef WOLFSSL_ASYNC_CRYPT
  17567. /* initialize event */
  17568. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.sm4->asyncDev,
  17569. WC_ASYNC_FLAG_CALL_AGAIN);
  17570. if (ret != 0)
  17571. break;
  17572. #endif
  17573. #if defined(WOLFSSL_SM4_GCM) && defined(WOLFSSL_SM4_CCM)
  17574. sm4_auth_fn = (ssl->specs.bulk_cipher_algorithm == wolfssl_sm4_gcm)
  17575. ? SM4_GCM_DECRYPT_FUNC : SM4_CCM_DECRYPT_FUNC;
  17576. #elif defined(WOLFSSL_SM4_GCM)
  17577. sm4_auth_fn = SM4_GCM_DECRYPT_FUNC;
  17578. #else
  17579. sm4_auth_fn = SM4_CCM_DECRYPT_FUNC;
  17580. #endif
  17581. XMEMSET(ssl->decrypt.additional, 0, AEAD_AUTH_DATA_SZ);
  17582. /* sequence number field is 64-bits */
  17583. WriteSEQ(ssl, PEER_ORDER, ssl->decrypt.additional);
  17584. ssl->decrypt.additional[AEAD_TYPE_OFFSET] = ssl->curRL.type;
  17585. ssl->decrypt.additional[AEAD_VMAJ_OFFSET] = ssl->curRL.pvMajor;
  17586. ssl->decrypt.additional[AEAD_VMIN_OFFSET] = ssl->curRL.pvMinor;
  17587. c16toa(sz - GCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17588. ssl->decrypt.additional + AEAD_LEN_OFFSET);
  17589. #if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION)
  17590. if (ssl->options.dtls && IsDtlsMsgSCRKeys(ssl))
  17591. XMEMCPY(ssl->decrypt.nonce,
  17592. ssl->secure_renegotiation->tmp_keys.aead_dec_imp_IV,
  17593. GCM_IMP_IV_SZ);
  17594. else
  17595. #endif
  17596. XMEMCPY(ssl->decrypt.nonce, ssl->keys.aead_dec_imp_IV,
  17597. GCM_IMP_IV_SZ);
  17598. XMEMCPY(ssl->decrypt.nonce + GCM_IMP_IV_SZ, input, GCM_EXP_IV_SZ);
  17599. if ((ret = sm4_auth_fn(ssl->decrypt.sm4,
  17600. plain + GCM_EXP_IV_SZ,
  17601. input + GCM_EXP_IV_SZ,
  17602. sz - GCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  17603. ssl->decrypt.nonce, GCM_NONCE_SZ,
  17604. input + sz - ssl->specs.aead_mac_size,
  17605. ssl->specs.aead_mac_size,
  17606. ssl->decrypt.additional, AEAD_AUTH_DATA_SZ)) < 0) {
  17607. #ifdef WOLFSSL_ASYNC_CRYPT
  17608. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  17609. ret = wolfSSL_AsyncPush(ssl,
  17610. &ssl->decrypt.sm4->asyncDev);
  17611. }
  17612. #endif
  17613. }
  17614. }
  17615. break;
  17616. #endif /* WOLFSSL_SM4_GCM || WOLFSSL_SM4_CCM */
  17617. #ifdef HAVE_NULL_CIPHER
  17618. case wolfssl_cipher_null:
  17619. if (input != plain) {
  17620. XMEMMOVE(plain, input, sz);
  17621. }
  17622. break;
  17623. #endif
  17624. default:
  17625. WOLFSSL_MSG("wolfSSL Decrypt programming error");
  17626. WOLFSSL_ERROR_VERBOSE(DECRYPT_ERROR);
  17627. ret = DECRYPT_ERROR;
  17628. }
  17629. #ifdef WOLFSSL_CHECK_MEM_ZERO
  17630. if ((ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) &&
  17631. (ret == 0)) {
  17632. wc_MemZero_Add("Decrypted data", plain, sz);
  17633. }
  17634. #endif
  17635. return ret;
  17636. }
  17637. static int DecryptTls(WOLFSSL* ssl, byte* plain, const byte* input, word16 sz)
  17638. {
  17639. int ret = 0;
  17640. #ifdef WOLFSSL_ASYNC_CRYPT
  17641. ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state);
  17642. if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
  17643. /* check for still pending */
  17644. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
  17645. return ret;
  17646. ssl->error = 0; /* clear async */
  17647. /* let failures through so CIPHER_STATE_END logic is run */
  17648. }
  17649. else
  17650. #endif
  17651. {
  17652. /* Reset state */
  17653. ret = 0;
  17654. ssl->decrypt.state = CIPHER_STATE_BEGIN;
  17655. }
  17656. switch (ssl->decrypt.state) {
  17657. case CIPHER_STATE_BEGIN:
  17658. {
  17659. if (ssl->decrypt.setup == 0) {
  17660. WOLFSSL_MSG("Decrypt ciphers not setup");
  17661. WOLFSSL_ERROR_VERBOSE(DECRYPT_ERROR);
  17662. return DECRYPT_ERROR;
  17663. }
  17664. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM) || defined(HAVE_ARIA)
  17665. /* make sure AES GCM/CCM memory is allocated */
  17666. /* free for these happens in FreeCiphers */
  17667. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
  17668. ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm ||
  17669. ssl->specs.bulk_cipher_algorithm == wolfssl_aria_gcm) {
  17670. /* make sure auth iv and auth are allocated */
  17671. if (ssl->decrypt.additional == NULL)
  17672. ssl->decrypt.additional = (byte*)XMALLOC(AEAD_AUTH_DATA_SZ,
  17673. ssl->heap, DYNAMIC_TYPE_CIPHER);
  17674. if (ssl->decrypt.nonce == NULL) {
  17675. ssl->decrypt.nonce = (byte*)XMALLOC(AESGCM_NONCE_SZ,
  17676. ssl->heap, DYNAMIC_TYPE_CIPHER);
  17677. #ifdef WOLFSSL_CHECK_MEM_ZERO
  17678. if (ssl->decrypt.nonce != NULL) {
  17679. wc_MemZero_Add("DecryptTls nonce", ssl->decrypt.nonce,
  17680. AESGCM_NONCE_SZ);
  17681. }
  17682. #endif
  17683. }
  17684. if (ssl->decrypt.additional == NULL ||
  17685. ssl->decrypt.nonce == NULL) {
  17686. return MEMORY_E;
  17687. }
  17688. }
  17689. #endif /* BUILD_AESGCM || HAVE_AESCCM || HAVE_ARIA */
  17690. #if defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)
  17691. /* make sure SM4 GCM/CCM memory is allocated */
  17692. /* free for these happens in FreeCiphers */
  17693. if (ssl->specs.bulk_cipher_algorithm == wolfssl_sm4_ccm ||
  17694. ssl->specs.bulk_cipher_algorithm == wolfssl_sm4_gcm) {
  17695. /* make sure auth iv and auth are allocated */
  17696. if (ssl->decrypt.additional == NULL)
  17697. ssl->decrypt.additional = (byte*)XMALLOC(AEAD_AUTH_DATA_SZ,
  17698. ssl->heap, DYNAMIC_TYPE_CIPHER);
  17699. if (ssl->decrypt.nonce == NULL) {
  17700. ssl->decrypt.nonce = (byte*)XMALLOC(GCM_NONCE_SZ,
  17701. ssl->heap, DYNAMIC_TYPE_CIPHER);
  17702. #ifdef WOLFSSL_CHECK_MEM_ZERO
  17703. if (ssl->decrypt.nonce != NULL) {
  17704. wc_MemZero_Add("DecryptTls nonce", ssl->decrypt.nonce,
  17705. GCM_NONCE_SZ);
  17706. }
  17707. #endif
  17708. }
  17709. if (ssl->decrypt.additional == NULL ||
  17710. ssl->decrypt.nonce == NULL) {
  17711. return MEMORY_E;
  17712. }
  17713. }
  17714. #endif /* WOLFSSL_SM4_GCM || WOLFSSL_SM4_CCM */
  17715. /* Advance state and proceed */
  17716. ssl->decrypt.state = CIPHER_STATE_DO;
  17717. }
  17718. FALL_THROUGH;
  17719. case CIPHER_STATE_DO:
  17720. {
  17721. #if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION)
  17722. if (ssl->options.dtls && DtlsSCRKeysSet(ssl)) {
  17723. /* For epochs >1 the current cipher parameters are located in
  17724. * ssl->secure_renegotiation->tmp_keys. Previous cipher
  17725. * parameters and for epoch 1 use ssl->keys */
  17726. if (ssl->keys.curEpoch ==
  17727. ssl->secure_renegotiation->tmp_keys.dtls_epoch) {
  17728. if (ssl->decrypt.src != SCR) {
  17729. ssl->secure_renegotiation->cache_status =
  17730. SCR_CACHE_NEEDED;
  17731. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  17732. break;
  17733. }
  17734. }
  17735. else {
  17736. if (ssl->decrypt.src != KEYS) {
  17737. ssl->secure_renegotiation->cache_status =
  17738. SCR_CACHE_NULL;
  17739. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  17740. break;
  17741. }
  17742. }
  17743. }
  17744. #endif
  17745. ret = DecryptDo(ssl, plain, input, sz);
  17746. /* Advance state */
  17747. ssl->decrypt.state = CIPHER_STATE_END;
  17748. #ifdef WOLFSSL_ASYNC_CRYPT
  17749. /* If pending, leave and return below */
  17750. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  17751. return ret;
  17752. }
  17753. #endif
  17754. }
  17755. FALL_THROUGH;
  17756. case CIPHER_STATE_END:
  17757. {
  17758. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM) || defined(HAVE_ARIA)
  17759. /* make sure AES GCM/CCM nonce is cleared */
  17760. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
  17761. ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
  17762. if (ssl->decrypt.nonce)
  17763. ForceZero(ssl->decrypt.nonce, AESGCM_NONCE_SZ);
  17764. if (ret < 0) {
  17765. ret = VERIFY_MAC_ERROR;
  17766. WOLFSSL_ERROR_VERBOSE(ret);
  17767. }
  17768. }
  17769. #endif /* BUILD_AESGCM || HAVE_AESCCM || HAVE_ARIA */
  17770. #if defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)
  17771. /* make sure SM4 GCM/CCM nonce is cleared */
  17772. if (ssl->specs.bulk_cipher_algorithm == wolfssl_sm4_ccm ||
  17773. ssl->specs.bulk_cipher_algorithm == wolfssl_sm4_gcm) {
  17774. if (ssl->decrypt.nonce)
  17775. ForceZero(ssl->decrypt.nonce, GCM_NONCE_SZ);
  17776. if (ret < 0) {
  17777. ret = VERIFY_MAC_ERROR;
  17778. WOLFSSL_ERROR_VERBOSE(ret);
  17779. }
  17780. }
  17781. #endif /* BUILD_AESGCM || HAVE_AESCCM */
  17782. break;
  17783. }
  17784. default:
  17785. break;
  17786. }
  17787. /* Reset state */
  17788. ssl->decrypt.state = CIPHER_STATE_BEGIN;
  17789. return ret;
  17790. }
  17791. #endif /* !WOLFSSL_NO_TLS12 */
  17792. /* Check conditions for a cipher to have an explicit IV.
  17793. *
  17794. * ssl The SSL/TLS object.
  17795. * returns 1 if the cipher in use has an explicit IV and 0 otherwise.
  17796. */
  17797. static WC_INLINE int CipherHasExpIV(WOLFSSL *ssl)
  17798. {
  17799. #ifdef WOLFSSL_TLS13
  17800. if (ssl->options.tls1_3)
  17801. return 0;
  17802. #endif
  17803. return (ssl->specs.cipher_type == aead) &&
  17804. (ssl->specs.bulk_cipher_algorithm != wolfssl_chacha);
  17805. }
  17806. /* check cipher text size for sanity */
  17807. static int SanityCheckCipherText(WOLFSSL* ssl, word32 encryptSz)
  17808. {
  17809. #ifdef HAVE_TRUNCATED_HMAC
  17810. word32 minLength = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  17811. : ssl->specs.hash_size;
  17812. #else
  17813. word32 minLength = ssl->specs.hash_size; /* covers stream */
  17814. #endif
  17815. #ifndef WOLFSSL_AEAD_ONLY
  17816. if (ssl->specs.cipher_type == block) {
  17817. #ifdef HAVE_ENCRYPT_THEN_MAC
  17818. if (ssl->options.startedETMRead) {
  17819. if ((encryptSz - MacSize(ssl)) % ssl->specs.block_size) {
  17820. WOLFSSL_MSG("Block ciphertext not block size");
  17821. WOLFSSL_ERROR_VERBOSE(SANITY_CIPHER_E);
  17822. return SANITY_CIPHER_E;
  17823. }
  17824. }
  17825. else
  17826. #endif
  17827. if (encryptSz % ssl->specs.block_size) {
  17828. WOLFSSL_MSG("Block ciphertext not block size");
  17829. WOLFSSL_ERROR_VERBOSE(SANITY_CIPHER_E);
  17830. return SANITY_CIPHER_E;
  17831. }
  17832. minLength++; /* pad byte */
  17833. if (ssl->specs.block_size > minLength)
  17834. minLength = ssl->specs.block_size;
  17835. if (ssl->options.tls1_1)
  17836. minLength += ssl->specs.block_size; /* explicit IV */
  17837. }
  17838. else
  17839. #endif
  17840. if (ssl->specs.cipher_type == aead) {
  17841. minLength = ssl->specs.aead_mac_size; /* authTag size */
  17842. if (CipherHasExpIV(ssl))
  17843. minLength += AESGCM_EXP_IV_SZ; /* explicit IV */
  17844. }
  17845. if (encryptSz < minLength) {
  17846. WOLFSSL_MSG("Ciphertext not minimum size");
  17847. WOLFSSL_ERROR_VERBOSE(SANITY_CIPHER_E);
  17848. return SANITY_CIPHER_E;
  17849. }
  17850. return 0;
  17851. }
  17852. #ifndef WOLFSSL_AEAD_ONLY
  17853. #ifdef WOLSSL_OLD_TIMINGPADVERIFY
  17854. #define COMPRESS_LOWER 64
  17855. #define COMPRESS_UPPER 55
  17856. #define COMPRESS_CONSTANT 13
  17857. #ifndef NO_OLD_TLS
  17858. static WC_INLINE void Md5Rounds(int rounds, const byte* data, int sz)
  17859. {
  17860. wc_Md5 md5;
  17861. int i;
  17862. wc_InitMd5(&md5); /* no error check on purpose, dummy round */
  17863. for (i = 0; i < rounds; i++)
  17864. wc_Md5Update(&md5, data, sz);
  17865. wc_Md5Free(&md5); /* in case needed to release resources */
  17866. }
  17867. /* do a dummy sha round */
  17868. static WC_INLINE void ShaRounds(int rounds, const byte* data, int sz)
  17869. {
  17870. wc_Sha sha;
  17871. int i;
  17872. wc_InitSha(&sha); /* no error check on purpose, dummy round */
  17873. for (i = 0; i < rounds; i++)
  17874. wc_ShaUpdate(&sha, data, sz);
  17875. wc_ShaFree(&sha); /* in case needed to release resources */
  17876. }
  17877. #endif
  17878. #ifndef NO_SHA256
  17879. static WC_INLINE void Sha256Rounds(int rounds, const byte* data, int sz)
  17880. {
  17881. wc_Sha256 sha256;
  17882. int i;
  17883. wc_InitSha256(&sha256); /* no error check on purpose, dummy round */
  17884. for (i = 0; i < rounds; i++) {
  17885. wc_Sha256Update(&sha256, data, sz);
  17886. /* no error check on purpose, dummy round */
  17887. }
  17888. wc_Sha256Free(&sha256); /* in case needed to release resources */
  17889. }
  17890. #endif
  17891. #ifdef WOLFSSL_SHA384
  17892. static WC_INLINE void Sha384Rounds(int rounds, const byte* data, int sz)
  17893. {
  17894. wc_Sha384 sha384;
  17895. int i;
  17896. wc_InitSha384(&sha384); /* no error check on purpose, dummy round */
  17897. for (i = 0; i < rounds; i++) {
  17898. wc_Sha384Update(&sha384, data, sz);
  17899. /* no error check on purpose, dummy round */
  17900. }
  17901. wc_Sha384Free(&sha384); /* in case needed to release resources */
  17902. }
  17903. #endif
  17904. #ifdef WOLFSSL_SHA512
  17905. static WC_INLINE void Sha512Rounds(int rounds, const byte* data, int sz)
  17906. {
  17907. wc_Sha512 sha512;
  17908. int i;
  17909. wc_InitSha512(&sha512); /* no error check on purpose, dummy round */
  17910. for (i = 0; i < rounds; i++) {
  17911. wc_Sha512Update(&sha512, data, sz);
  17912. /* no error check on purpose, dummy round */
  17913. }
  17914. wc_Sha512Free(&sha512); /* in case needed to release resources */
  17915. }
  17916. #endif
  17917. #ifdef WOLFSSL_RIPEMD
  17918. static WC_INLINE void RmdRounds(int rounds, const byte* data, int sz)
  17919. {
  17920. RipeMd ripemd;
  17921. int i;
  17922. wc_InitRipeMd(&ripemd);
  17923. for (i = 0; i < rounds; i++)
  17924. wc_RipeMdUpdate(&ripemd, data, sz);
  17925. }
  17926. #endif
  17927. /* Do dummy rounds */
  17928. static WC_INLINE void DoRounds(int type, int rounds, const byte* data, int sz)
  17929. {
  17930. (void)rounds;
  17931. (void)data;
  17932. (void)sz;
  17933. switch (type) {
  17934. case no_mac :
  17935. break;
  17936. #ifndef NO_OLD_TLS
  17937. #ifndef NO_MD5
  17938. case md5_mac :
  17939. Md5Rounds(rounds, data, sz);
  17940. break;
  17941. #endif
  17942. #ifndef NO_SHA
  17943. case sha_mac :
  17944. ShaRounds(rounds, data, sz);
  17945. break;
  17946. #endif
  17947. #endif
  17948. #ifndef NO_SHA256
  17949. case sha256_mac :
  17950. Sha256Rounds(rounds, data, sz);
  17951. break;
  17952. #endif
  17953. #ifdef WOLFSSL_SHA384
  17954. case sha384_mac :
  17955. Sha384Rounds(rounds, data, sz);
  17956. break;
  17957. #endif
  17958. #ifdef WOLFSSL_SHA512
  17959. case sha512_mac :
  17960. Sha512Rounds(rounds, data, sz);
  17961. break;
  17962. #endif
  17963. #ifdef WOLFSSL_RIPEMD
  17964. case rmd_mac :
  17965. RmdRounds(rounds, data, sz);
  17966. break;
  17967. #endif
  17968. default:
  17969. WOLFSSL_MSG("Bad round type");
  17970. break;
  17971. }
  17972. }
  17973. /* do number of compression rounds on dummy data */
  17974. static WC_INLINE void CompressRounds(WOLFSSL* ssl, int rounds, const byte* dummy)
  17975. {
  17976. if (rounds)
  17977. DoRounds(ssl->specs.mac_algorithm, rounds, dummy, COMPRESS_LOWER);
  17978. }
  17979. /* check all length bytes for the pad value, return 0 on success */
  17980. static int PadCheck(const byte* a, byte pad, int length)
  17981. {
  17982. int i;
  17983. int compareSum = 0;
  17984. for (i = 0; i < length; i++) {
  17985. compareSum |= a[i] ^ pad;
  17986. }
  17987. return compareSum;
  17988. }
  17989. /* get compression extra rounds */
  17990. static WC_INLINE int GetRounds(int pLen, int padLen, int t)
  17991. {
  17992. int roundL1 = 1; /* round up flags */
  17993. int roundL2 = 1;
  17994. int L1 = COMPRESS_CONSTANT + pLen - t;
  17995. int L2 = COMPRESS_CONSTANT + pLen - padLen - 1 - t;
  17996. L1 -= COMPRESS_UPPER;
  17997. L2 -= COMPRESS_UPPER;
  17998. if ( (L1 % COMPRESS_LOWER) == 0)
  17999. roundL1 = 0;
  18000. if ( (L2 % COMPRESS_LOWER) == 0)
  18001. roundL2 = 0;
  18002. L1 /= COMPRESS_LOWER;
  18003. L2 /= COMPRESS_LOWER;
  18004. L1 += roundL1;
  18005. L2 += roundL2;
  18006. return L1 - L2;
  18007. }
  18008. /* timing resistant pad/verify check, return 0 on success */
  18009. int TimingPadVerify(WOLFSSL* ssl, const byte* input, int padLen, int t,
  18010. int pLen, int content)
  18011. {
  18012. byte verify[WC_MAX_DIGEST_SIZE];
  18013. byte dmy[sizeof(WOLFSSL) >= MAX_PAD_SIZE ? 1 : MAX_PAD_SIZE] = {0};
  18014. byte* dummy = sizeof(dmy) < MAX_PAD_SIZE ? (byte*) ssl : dmy;
  18015. int ret = 0;
  18016. (void)dmy;
  18017. if ( (t + padLen + 1) > pLen) {
  18018. WOLFSSL_MSG("Plain Len not long enough for pad/mac");
  18019. PadCheck(dummy, (byte)padLen, MAX_PAD_SIZE);
  18020. /* still compare */
  18021. ssl->hmac(ssl, verify, input, pLen - t, -1, content, 1, PEER_ORDER);
  18022. ConstantCompare(verify, input + pLen - t, t);
  18023. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  18024. return VERIFY_MAC_ERROR;
  18025. }
  18026. if (PadCheck(input + pLen - (padLen + 1), (byte)padLen, padLen + 1) != 0) {
  18027. WOLFSSL_MSG("PadCheck failed");
  18028. PadCheck(dummy, (byte)padLen, MAX_PAD_SIZE - padLen - 1);
  18029. /* still compare */
  18030. ssl->hmac(ssl, verify, input, pLen - t, -1, content, 1, PEER_ORDER);
  18031. ConstantCompare(verify, input + pLen - t, t);
  18032. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  18033. return VERIFY_MAC_ERROR;
  18034. }
  18035. PadCheck(dummy, (byte)padLen, MAX_PAD_SIZE - padLen - 1);
  18036. ret = ssl->hmac(ssl, verify, input, pLen - padLen - 1 - t, -1, content,
  18037. 1, PEER_ORDER);
  18038. CompressRounds(ssl, GetRounds(pLen, padLen, t), dummy);
  18039. if (ConstantCompare(verify, input + (pLen - padLen - 1 - t), t) != 0) {
  18040. WOLFSSL_MSG("Verify MAC compare failed");
  18041. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  18042. return VERIFY_MAC_ERROR;
  18043. }
  18044. /* treat any failure as verify MAC error */
  18045. if (ret != 0) {
  18046. ret = VERIFY_MAC_ERROR;
  18047. WOLFSSL_ERROR_VERBOSE(ret);
  18048. }
  18049. return ret;
  18050. }
  18051. #else
  18052. #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
  18053. /* check all length bytes for the pad value, return 0 on success */
  18054. static int PadCheck(const byte* a, byte pad, int length)
  18055. {
  18056. int i;
  18057. int compareSum = 0;
  18058. for (i = 0; i < length; i++) {
  18059. compareSum |= a[i] ^ pad;
  18060. }
  18061. return compareSum;
  18062. }
  18063. /* Mask the padding bytes with the expected values.
  18064. * Constant time implementation - does maximum pad size possible.
  18065. *
  18066. * data Message data.
  18067. * sz Size of the message including MAC and padding and padding length.
  18068. * macSz Size of the MAC.
  18069. * returns 0 on success, otherwise failure.
  18070. */
  18071. static byte MaskPadding(const byte* data, int sz, int macSz)
  18072. {
  18073. int i;
  18074. int checkSz = sz - 1;
  18075. byte paddingSz = data[sz - 1];
  18076. byte good = ctMaskGT(paddingSz, sz - 1 - macSz);
  18077. if (checkSz > TLS_MAX_PAD_SZ)
  18078. checkSz = TLS_MAX_PAD_SZ;
  18079. for (i = 0; i < checkSz; i++) {
  18080. byte mask = ctMaskLTE(i, paddingSz);
  18081. good |= mask & (data[sz - 1 - i] ^ paddingSz);
  18082. }
  18083. return good;
  18084. }
  18085. /* Mask the MAC in the message with the MAC calculated.
  18086. * Constant time implementation - starts looking for MAC where maximum padding
  18087. * size has it.
  18088. *
  18089. * data Message data.
  18090. * sz Size of the message including MAC and padding and padding length.
  18091. * macSz Size of the MAC data.
  18092. * expMac Expected MAC value.
  18093. * returns 0 on success, otherwise failure.
  18094. */
  18095. static byte MaskMac(const byte* data, int sz, int macSz, byte* expMac)
  18096. {
  18097. int i, j;
  18098. unsigned char mac[WC_MAX_DIGEST_SIZE];
  18099. int scanStart = sz - 1 - TLS_MAX_PAD_SZ - macSz;
  18100. int macEnd = sz - 1 - data[sz - 1];
  18101. int macStart = macEnd - macSz;
  18102. int r = 0;
  18103. unsigned char started, notEnded;
  18104. unsigned char good = 0;
  18105. scanStart &= ctMaskIntGTE(scanStart, 0);
  18106. macStart &= ctMaskIntGTE(macStart, 0);
  18107. /* Div on Intel has different speeds depending on value.
  18108. * Use a bitwise AND or mod a specific value (converted to mul). */
  18109. if ((macSz & (macSz - 1)) == 0)
  18110. r = (macSz - (scanStart - macStart)) & (macSz - 1);
  18111. #ifndef NO_SHA
  18112. else if (macSz == WC_SHA_DIGEST_SIZE)
  18113. r = (macSz - (scanStart - macStart)) % WC_SHA_DIGEST_SIZE;
  18114. #endif
  18115. #ifdef WOLFSSL_SHA384
  18116. else if (macSz == WC_SHA384_DIGEST_SIZE)
  18117. r = (macSz - (scanStart - macStart)) % WC_SHA384_DIGEST_SIZE;
  18118. #endif
  18119. XMEMSET(mac, 0, macSz);
  18120. for (i = scanStart; i < sz; i += macSz) {
  18121. for (j = 0; j < macSz && j + i < sz; j++) {
  18122. started = ctMaskGTE(i + j, macStart);
  18123. notEnded = ctMaskLT(i + j, macEnd);
  18124. mac[j] |= started & notEnded & data[i + j];
  18125. }
  18126. }
  18127. if ((macSz & (macSz - 1)) == 0) {
  18128. for (i = 0; i < macSz; i++)
  18129. good |= expMac[i] ^ mac[(i + r) & (macSz - 1)];
  18130. }
  18131. #ifndef NO_SHA
  18132. else if (macSz == WC_SHA_DIGEST_SIZE) {
  18133. for (i = 0; i < macSz; i++)
  18134. good |= expMac[i] ^ mac[(i + r) % WC_SHA_DIGEST_SIZE];
  18135. }
  18136. #endif
  18137. #ifdef WOLFSSL_SHA384
  18138. else if (macSz == WC_SHA384_DIGEST_SIZE) {
  18139. for (i = 0; i < macSz; i++)
  18140. good |= expMac[i] ^ mac[(i + r) % WC_SHA384_DIGEST_SIZE];
  18141. }
  18142. #endif
  18143. return good;
  18144. }
  18145. /* timing resistant pad/verify check, return 0 on success */
  18146. int TimingPadVerify(WOLFSSL* ssl, const byte* input, int padLen, int macSz,
  18147. int pLen, int content)
  18148. {
  18149. byte verify[WC_MAX_DIGEST_SIZE];
  18150. byte good;
  18151. int ret = 0;
  18152. good = MaskPadding(input, pLen, macSz);
  18153. /* 4th argument has potential to underflow, ssl->hmac function should
  18154. * either increment the size by (macSz + padLen + 1) before use or check on
  18155. * the size to make sure is valid. */
  18156. ret = ssl->hmac(ssl, verify, input, (word32)(pLen - macSz - padLen - 1), padLen,
  18157. content, 1, PEER_ORDER);
  18158. good |= MaskMac(input, pLen, ssl->specs.hash_size, verify);
  18159. /* Non-zero on failure. */
  18160. good = (byte)~(word32)good;
  18161. good &= good >> 4;
  18162. good &= good >> 2;
  18163. good &= good >> 1;
  18164. /* Make ret negative on masking failure. */
  18165. ret -= 1 - good;
  18166. /* Treat any failure as verify MAC error. */
  18167. if (ret != 0) {
  18168. ret = VERIFY_MAC_ERROR;
  18169. WOLFSSL_ERROR_VERBOSE(ret);
  18170. }
  18171. return ret;
  18172. }
  18173. #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
  18174. #endif /* WOLSSL_OLD_TIMINGPADVERIFY */
  18175. #endif /* WOLFSSL_AEAD_ONLY */
  18176. int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx, int sniff)
  18177. {
  18178. word32 msgSz = WOLFSSL_IS_QUIC(ssl)? ssl->curSize : ssl->keys.encryptSz;
  18179. word32 idx = *inOutIdx;
  18180. int dataSz;
  18181. int ivExtra = 0;
  18182. byte* rawData = input + idx; /* keep current for hmac */
  18183. #ifdef HAVE_LIBZ
  18184. byte decomp[MAX_RECORD_SIZE + MAX_COMP_EXTRA];
  18185. #endif
  18186. #ifdef WOLFSSL_EARLY_DATA
  18187. if (ssl->options.tls1_3 && ssl->options.handShakeDone == 0) {
  18188. int process = 0;
  18189. if (ssl->options.side == WOLFSSL_SERVER_END) {
  18190. if ((ssl->earlyData != no_early_data) &&
  18191. (ssl->options.clientState == CLIENT_HELLO_COMPLETE)) {
  18192. process = 1;
  18193. }
  18194. if (!process) {
  18195. WOLFSSL_MSG("Ignoring EarlyData!");
  18196. *inOutIdx += ssl->curSize;
  18197. if (*inOutIdx > ssl->buffers.inputBuffer.length)
  18198. return BUFFER_E;
  18199. return 0;
  18200. }
  18201. }
  18202. if (!process) {
  18203. WOLFSSL_MSG("Received App data before a handshake completed");
  18204. if (sniff == NO_SNIFF) {
  18205. SendAlert(ssl, alert_fatal, unexpected_message);
  18206. }
  18207. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  18208. return OUT_OF_ORDER_E;
  18209. }
  18210. }
  18211. else
  18212. #endif
  18213. if (ssl->options.handShakeDone == 0) {
  18214. WOLFSSL_MSG("Received App data before a handshake completed");
  18215. if (sniff == NO_SNIFF) {
  18216. SendAlert(ssl, alert_fatal, unexpected_message);
  18217. }
  18218. WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
  18219. return OUT_OF_ORDER_E;
  18220. }
  18221. #if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_TLS13_IGNORE_AEAD_LIMITS)
  18222. /* Check if we want to invalidate old epochs. If
  18223. * ssl->dtls13InvalidateBefore is set then we want to mark all old
  18224. * epochs as encrypt only. This is done when we detect too many failed
  18225. * decryptions. We do this here to confirm that the peer has updated its
  18226. * keys and we can stop using the old keys. */
  18227. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) {
  18228. if (!w64IsZero(ssl->dtls13InvalidateBefore) &&
  18229. w64Equal(ssl->keys.curEpoch64, ssl->dtls13InvalidateBefore)) {
  18230. Dtls13SetOlderEpochSide(ssl, ssl->dtls13InvalidateBefore,
  18231. ENCRYPT_SIDE_ONLY);
  18232. w64Zero(&ssl->dtls13InvalidateBefore);
  18233. }
  18234. }
  18235. #endif
  18236. #ifndef WOLFSSL_AEAD_ONLY
  18237. if (ssl->specs.cipher_type == block) {
  18238. if (ssl->options.tls1_1)
  18239. ivExtra = ssl->specs.block_size;
  18240. }
  18241. else
  18242. #endif
  18243. if (ssl->specs.cipher_type == aead) {
  18244. if (CipherHasExpIV(ssl))
  18245. ivExtra = AESGCM_EXP_IV_SZ;
  18246. }
  18247. dataSz = (int)(msgSz - (word32)ivExtra - ssl->keys.padSz);
  18248. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  18249. if (ssl->options.startedETMRead)
  18250. dataSz -= MacSize(ssl);
  18251. #endif
  18252. if (dataSz < 0) {
  18253. WOLFSSL_MSG("App data buffer error, malicious input?");
  18254. if (sniff == NO_SNIFF) {
  18255. SendAlert(ssl, alert_fatal, unexpected_message);
  18256. }
  18257. WOLFSSL_ERROR_VERBOSE(BUFFER_ERROR);
  18258. return BUFFER_ERROR;
  18259. }
  18260. #ifdef WOLFSSL_EARLY_DATA
  18261. if (ssl->options.side == WOLFSSL_SERVER_END &&
  18262. ssl->earlyData > early_data_ext) {
  18263. if (ssl->earlyDataSz + dataSz > ssl->options.maxEarlyDataSz) {
  18264. if (sniff == NO_SNIFF) {
  18265. SendAlert(ssl, alert_fatal, unexpected_message);
  18266. }
  18267. return WOLFSSL_FATAL_ERROR;
  18268. }
  18269. ssl->earlyDataSz += dataSz;
  18270. }
  18271. #endif
  18272. /* read data */
  18273. if (dataSz) {
  18274. int rawSz = dataSz; /* keep raw size for idx adjustment */
  18275. #ifdef HAVE_LIBZ
  18276. if (ssl->options.usingCompression) {
  18277. dataSz = myDeCompress(ssl, rawData, dataSz, decomp, sizeof(decomp));
  18278. if (dataSz < 0) return dataSz;
  18279. }
  18280. #endif
  18281. idx += (word32)rawSz;
  18282. ssl->buffers.clearOutputBuffer.buffer = rawData;
  18283. ssl->buffers.clearOutputBuffer.length = (unsigned int)dataSz;
  18284. }
  18285. idx += ssl->keys.padSz;
  18286. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  18287. if (ssl->options.startedETMRead)
  18288. idx += MacSize(ssl);
  18289. #endif
  18290. #ifdef HAVE_LIBZ
  18291. /* decompress could be bigger, overwrite after verify */
  18292. if (ssl->options.usingCompression)
  18293. XMEMMOVE(rawData, decomp, dataSz);
  18294. #endif
  18295. *inOutIdx = idx;
  18296. #ifdef WOLFSSL_DTLS13
  18297. if (ssl->options.connectState == WAIT_FINISHED_ACK) {
  18298. /* DTLS 1.3 is waiting for an ACK but we can still return app data. */
  18299. return APP_DATA_READY;
  18300. }
  18301. #endif
  18302. #ifdef HAVE_SECURE_RENEGOTIATION
  18303. if (IsSCR(ssl)) {
  18304. /* If we are in a secure renegotiation then APP DATA is treated
  18305. * differently */
  18306. return APP_DATA_READY;
  18307. }
  18308. #endif
  18309. return 0;
  18310. }
  18311. const char* AlertTypeToString(int type)
  18312. {
  18313. switch (type) {
  18314. case close_notify:
  18315. {
  18316. static const char close_notify_str[] =
  18317. "close_notify";
  18318. return close_notify_str;
  18319. }
  18320. case unexpected_message:
  18321. {
  18322. static const char unexpected_message_str[] =
  18323. "unexpected_message";
  18324. return unexpected_message_str;
  18325. }
  18326. case bad_record_mac:
  18327. {
  18328. static const char bad_record_mac_str[] =
  18329. "bad_record_mac";
  18330. return bad_record_mac_str;
  18331. }
  18332. case record_overflow:
  18333. {
  18334. static const char record_overflow_str[] =
  18335. "record_overflow";
  18336. return record_overflow_str;
  18337. }
  18338. case decompression_failure:
  18339. {
  18340. static const char decompression_failure_str[] =
  18341. "decompression_failure";
  18342. return decompression_failure_str;
  18343. }
  18344. case handshake_failure:
  18345. {
  18346. static const char handshake_failure_str[] =
  18347. "handshake_failure";
  18348. return handshake_failure_str;
  18349. }
  18350. case no_certificate:
  18351. {
  18352. static const char no_certificate_str[] =
  18353. "no_certificate";
  18354. return no_certificate_str;
  18355. }
  18356. case bad_certificate:
  18357. {
  18358. static const char bad_certificate_str[] =
  18359. "bad_certificate";
  18360. return bad_certificate_str;
  18361. }
  18362. case unsupported_certificate:
  18363. {
  18364. static const char unsupported_certificate_str[] =
  18365. "unsupported_certificate";
  18366. return unsupported_certificate_str;
  18367. }
  18368. case certificate_revoked:
  18369. {
  18370. static const char certificate_revoked_str[] =
  18371. "certificate_revoked";
  18372. return certificate_revoked_str;
  18373. }
  18374. case certificate_expired:
  18375. {
  18376. static const char certificate_expired_str[] =
  18377. "certificate_expired";
  18378. return certificate_expired_str;
  18379. }
  18380. case certificate_unknown:
  18381. {
  18382. static const char certificate_unknown_str[] =
  18383. "certificate_unknown";
  18384. return certificate_unknown_str;
  18385. }
  18386. case illegal_parameter:
  18387. {
  18388. static const char illegal_parameter_str[] =
  18389. "illegal_parameter";
  18390. return illegal_parameter_str;
  18391. }
  18392. case unknown_ca:
  18393. {
  18394. static const char unknown_ca_str[] =
  18395. "unknown_ca";
  18396. return unknown_ca_str;
  18397. }
  18398. case access_denied:
  18399. {
  18400. static const char access_denied_str[] =
  18401. "access_denied";
  18402. return access_denied_str;
  18403. }
  18404. case decode_error:
  18405. {
  18406. static const char decode_error_str[] =
  18407. "decode_error";
  18408. return decode_error_str;
  18409. }
  18410. case decrypt_error:
  18411. {
  18412. static const char decrypt_error_str[] =
  18413. "decrypt_error";
  18414. return decrypt_error_str;
  18415. }
  18416. case wolfssl_alert_protocol_version:
  18417. {
  18418. static const char protocol_version_str[] =
  18419. "protocol_version";
  18420. return protocol_version_str;
  18421. }
  18422. case insufficient_security:
  18423. {
  18424. static const char insufficient_security_str[] =
  18425. "insufficient_security";
  18426. return insufficient_security_str;
  18427. }
  18428. case internal_error:
  18429. {
  18430. static const char internal_error_str[] =
  18431. "internal_error";
  18432. return internal_error_str;
  18433. }
  18434. case user_canceled:
  18435. {
  18436. static const char user_canceled_str[] =
  18437. "user_canceled";
  18438. return user_canceled_str;
  18439. }
  18440. case no_renegotiation:
  18441. {
  18442. static const char no_renegotiation_str[] =
  18443. "no_renegotiation";
  18444. return no_renegotiation_str;
  18445. }
  18446. case unrecognized_name:
  18447. {
  18448. static const char unrecognized_name_str[] =
  18449. "unrecognized_name";
  18450. return unrecognized_name_str;
  18451. }
  18452. case bad_certificate_status_response:
  18453. {
  18454. static const char bad_certificate_status_response_str[] =
  18455. "bad_certificate_status_response";
  18456. return bad_certificate_status_response_str;
  18457. }
  18458. case no_application_protocol:
  18459. {
  18460. static const char no_application_protocol_str[] =
  18461. "no_application_protocol";
  18462. return no_application_protocol_str;
  18463. }
  18464. default:
  18465. WOLFSSL_MSG("Unknown Alert");
  18466. return NULL;
  18467. }
  18468. }
  18469. static void LogAlert(int type)
  18470. {
  18471. #ifdef DEBUG_WOLFSSL
  18472. const char* typeStr;
  18473. typeStr = AlertTypeToString(type);
  18474. if (typeStr != NULL) {
  18475. char buff[60];
  18476. if (XSNPRINTF(buff, sizeof(buff), "Alert type: %s", typeStr)
  18477. >= (int)sizeof(buff))
  18478. {
  18479. buff[sizeof(buff) - 1] = 0;
  18480. }
  18481. WOLFSSL_MSG(buff);
  18482. }
  18483. #else
  18484. (void)type;
  18485. #endif /* DEBUG_WOLFSSL */
  18486. }
  18487. /* process alert, return level */
  18488. static int DoAlert(WOLFSSL* ssl, byte* input, word32* inOutIdx, int* type)
  18489. {
  18490. byte level;
  18491. byte code;
  18492. word32 dataSz = (word32)ssl->curSize;
  18493. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  18494. if (ssl->hsInfoOn)
  18495. AddPacketName(ssl, "Alert");
  18496. if (ssl->toInfoOn) {
  18497. /* add record header back on to info + alert bytes level/code */
  18498. int ret = AddPacketInfo(ssl, "Alert", alert, input + *inOutIdx,
  18499. ALERT_SIZE, READ_PROTO, RECORD_HEADER_SZ, ssl->heap);
  18500. if (ret != 0)
  18501. return ret;
  18502. #ifdef WOLFSSL_CALLBACKS
  18503. AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
  18504. #endif
  18505. }
  18506. #endif
  18507. if (IsEncryptionOn(ssl, 0)) {
  18508. word32 ivExtra = 0;
  18509. #ifndef WOLFSSL_AEAD_ONLY
  18510. if (ssl->specs.cipher_type == block) {
  18511. if (ssl->options.tls1_1)
  18512. ivExtra = ssl->specs.block_size;
  18513. }
  18514. else
  18515. #endif
  18516. if (ssl->specs.cipher_type == aead) {
  18517. if (CipherHasExpIV(ssl))
  18518. ivExtra = AESGCM_EXP_IV_SZ;
  18519. }
  18520. dataSz -= ivExtra;
  18521. dataSz -= ssl->keys.padSz;
  18522. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  18523. if (ssl->options.startedETMRead)
  18524. dataSz -= MacSize(ssl);
  18525. #endif
  18526. }
  18527. /* make sure can read the message */
  18528. if (dataSz != ALERT_SIZE) {
  18529. #ifdef WOLFSSL_EXTRA_ALERTS
  18530. SendAlert(ssl, alert_fatal, unexpected_message);
  18531. #endif
  18532. return BUFFER_E;
  18533. }
  18534. level = input[(*inOutIdx)++];
  18535. code = input[(*inOutIdx)++];
  18536. ssl->alert_history.last_rx.code = code;
  18537. ssl->alert_history.last_rx.level = level;
  18538. *type = code;
  18539. if (level == alert_fatal) {
  18540. ssl->options.isClosed = 1; /* Don't send close_notify */
  18541. }
  18542. if (++ssl->options.alertCount >= WOLFSSL_ALERT_COUNT_MAX) {
  18543. WOLFSSL_MSG("Alert count exceeded");
  18544. #ifdef WOLFSSL_EXTRA_ALERTS
  18545. if (level != alert_warning || code != close_notify)
  18546. SendAlert(ssl, alert_fatal, unexpected_message);
  18547. #endif
  18548. WOLFSSL_ERROR_VERBOSE(ALERT_COUNT_E);
  18549. return ALERT_COUNT_E;
  18550. }
  18551. LogAlert(*type);
  18552. if (*type == close_notify) {
  18553. ssl->options.closeNotify = 1;
  18554. }
  18555. else {
  18556. /*
  18557. * A close_notify alert doesn't mean there's been an error, so we only
  18558. * add other types of alerts to the error queue
  18559. */
  18560. WOLFSSL_ERROR(*type);
  18561. }
  18562. if (IsEncryptionOn(ssl, 0)) {
  18563. *inOutIdx += ssl->keys.padSz;
  18564. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  18565. if (ssl->options.startedETMRead)
  18566. *inOutIdx += MacSize(ssl);
  18567. #endif
  18568. }
  18569. return level;
  18570. }
  18571. static int GetInputData(WOLFSSL *ssl, word32 size)
  18572. {
  18573. int inSz;
  18574. int maxLength;
  18575. int usedLength;
  18576. int dtlsExtra = 0;
  18577. /* check max input length */
  18578. usedLength = (int)(ssl->buffers.inputBuffer.length - ssl->buffers.inputBuffer.idx);
  18579. maxLength = (int)(ssl->buffers.inputBuffer.bufferSize - (word32)usedLength);
  18580. inSz = (int)(size - (word32)usedLength); /* from last partial read */
  18581. #ifdef WOLFSSL_DTLS
  18582. if (ssl->options.dtls && IsDtlsNotSctpMode(ssl)) {
  18583. /* Add DTLS_MTU_ADDITIONAL_READ_BUFFER bytes so that we can operate with
  18584. * slight difference in set MTU size on each peer */
  18585. #ifdef WOLFSSL_DTLS_MTU
  18586. inSz = (word32)ssl->dtlsMtuSz + DTLS_MTU_ADDITIONAL_READ_BUFFER;
  18587. #else
  18588. inSz = MAX_MTU + DTLS_MTU_ADDITIONAL_READ_BUFFER;
  18589. #endif
  18590. if (size < (word32)inSz)
  18591. dtlsExtra = (int)(inSz - size);
  18592. }
  18593. #endif
  18594. /* check that no lengths or size values are negative */
  18595. if (usedLength < 0 || maxLength < 0 || inSz <= 0) {
  18596. return BUFFER_ERROR;
  18597. }
  18598. if (inSz > maxLength) {
  18599. if (GrowInputBuffer(ssl, (int)(size + (word32)dtlsExtra), usedLength) < 0)
  18600. return MEMORY_E;
  18601. }
  18602. /* Put buffer data at start if not there */
  18603. if (usedLength > 0 && ssl->buffers.inputBuffer.idx != 0)
  18604. XMEMMOVE(ssl->buffers.inputBuffer.buffer,
  18605. ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.idx,
  18606. usedLength);
  18607. /* remove processed data */
  18608. ssl->buffers.inputBuffer.idx = 0;
  18609. ssl->buffers.inputBuffer.length = (word32)usedLength;
  18610. /* read data from network */
  18611. do {
  18612. int in = wolfSSLReceive(ssl,
  18613. ssl->buffers.inputBuffer.buffer +
  18614. ssl->buffers.inputBuffer.length,
  18615. (word32)inSz);
  18616. if (in == WC_NO_ERR_TRACE(WANT_READ))
  18617. return WC_NO_ERR_TRACE(WANT_READ);
  18618. if (in < 0) {
  18619. WOLFSSL_ERROR_VERBOSE(SOCKET_ERROR_E);
  18620. return SOCKET_ERROR_E;
  18621. }
  18622. if (in > inSz) {
  18623. WOLFSSL_ERROR_VERBOSE(RECV_OVERFLOW_E);
  18624. return RECV_OVERFLOW_E;
  18625. }
  18626. ssl->buffers.inputBuffer.length += (word32)in;
  18627. inSz -= in;
  18628. } while (ssl->buffers.inputBuffer.length < size);
  18629. #ifdef WOLFSSL_DEBUG_TLS
  18630. if (ssl->buffers.inputBuffer.idx == 0) {
  18631. WOLFSSL_MSG("Data received");
  18632. WOLFSSL_BUFFER(ssl->buffers.inputBuffer.buffer,
  18633. ssl->buffers.inputBuffer.length);
  18634. }
  18635. #endif
  18636. return 0;
  18637. }
  18638. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  18639. static WC_INLINE int VerifyMacEnc(WOLFSSL* ssl, const byte* input, word32 msgSz,
  18640. int content)
  18641. {
  18642. int ret;
  18643. #ifdef HAVE_TRUNCATED_HMAC
  18644. word32 digestSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  18645. : ssl->specs.hash_size;
  18646. #else
  18647. word32 digestSz = ssl->specs.hash_size;
  18648. #endif
  18649. byte verify[WC_MAX_DIGEST_SIZE];
  18650. WOLFSSL_MSG("Verify MAC of Encrypted Data");
  18651. if (msgSz < digestSz) {
  18652. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  18653. return VERIFY_MAC_ERROR;
  18654. }
  18655. ret = ssl->hmac(ssl, verify, input, msgSz - digestSz, -1, content, 1, PEER_ORDER);
  18656. ret |= ConstantCompare(verify, input + msgSz - digestSz, (int)digestSz);
  18657. if (ret != 0) {
  18658. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  18659. return VERIFY_MAC_ERROR;
  18660. }
  18661. return 0;
  18662. }
  18663. #endif
  18664. static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz,
  18665. int content, word32* padSz)
  18666. {
  18667. #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
  18668. int ret;
  18669. word32 pad = 0;
  18670. word32 padByte = 0;
  18671. #ifdef HAVE_TRUNCATED_HMAC
  18672. word32 digestSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  18673. : ssl->specs.hash_size;
  18674. #else
  18675. word32 digestSz = ssl->specs.hash_size;
  18676. #endif
  18677. byte verify[WC_MAX_DIGEST_SIZE];
  18678. if (ssl->specs.cipher_type == block) {
  18679. int ivExtra = 0;
  18680. if (ssl->options.tls1_1)
  18681. ivExtra = ssl->specs.block_size;
  18682. pad = *(input + msgSz - ivExtra - 1);
  18683. padByte = 1;
  18684. if (ssl->options.tls) {
  18685. #if !defined(NO_CERTS) && defined(HAVE_PK_CALLBACKS)
  18686. ret = PROTOCOLCB_UNAVAILABLE;
  18687. if(ssl->ctx->VerifyMacCb) {
  18688. void* ctx = wolfSSL_GetVerifyMacCtx(ssl);
  18689. ret = ssl->ctx->VerifyMacCb(ssl, input,
  18690. (msgSz - ivExtra) - digestSz - pad - 1,
  18691. digestSz, (word32)content, ctx);
  18692. if (ret != 0 &&
  18693. ret != WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) {
  18694. return ret;
  18695. }
  18696. }
  18697. if (!ssl->ctx->VerifyMacCb ||
  18698. ret == WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE))
  18699. #endif
  18700. ret = TimingPadVerify(ssl, input, (int)pad, (int)digestSz,
  18701. (int)(msgSz - (word32)ivExtra), content);
  18702. if (ret != 0)
  18703. return ret;
  18704. }
  18705. else { /* sslv3, some implementations have bad padding, but don't
  18706. * allow bad read */
  18707. int badPadLen = 0;
  18708. byte dmy[sizeof(WOLFSSL) >= MAX_PAD_SIZE ? 1 : MAX_PAD_SIZE];
  18709. byte* dummy = sizeof(dmy) < MAX_PAD_SIZE ? (byte*) ssl : dmy;
  18710. XMEMSET(dmy, 0, sizeof(dmy));
  18711. if (pad > (msgSz - digestSz - 1)) {
  18712. WOLFSSL_MSG("Plain Len not long enough for pad/mac");
  18713. pad = 0; /* no bad read */
  18714. badPadLen = 1;
  18715. }
  18716. (void)PadCheck(dummy, (byte)pad, MAX_PAD_SIZE); /* timing only */
  18717. ret = ssl->hmac(ssl, verify, input, msgSz - digestSz - pad - 1,
  18718. (int)pad, content, 1, PEER_ORDER);
  18719. if (ConstantCompare(verify, input + msgSz - digestSz - pad - 1,
  18720. (int)digestSz) != 0) {
  18721. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  18722. return VERIFY_MAC_ERROR;
  18723. }
  18724. if (ret != 0 || badPadLen) {
  18725. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  18726. return VERIFY_MAC_ERROR;
  18727. }
  18728. }
  18729. }
  18730. else if (ssl->specs.cipher_type == stream) {
  18731. ret = ssl->hmac(ssl, verify, input, msgSz - digestSz, -1, content, 1,
  18732. PEER_ORDER);
  18733. if (ConstantCompare(verify, input + msgSz - digestSz, (int)digestSz) != 0) {
  18734. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  18735. return VERIFY_MAC_ERROR;
  18736. }
  18737. if (ret != 0) {
  18738. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  18739. return VERIFY_MAC_ERROR;
  18740. }
  18741. }
  18742. #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
  18743. if (ssl->specs.cipher_type == aead) {
  18744. *padSz = ssl->specs.aead_mac_size;
  18745. }
  18746. #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
  18747. else {
  18748. *padSz = digestSz + pad + padByte;
  18749. }
  18750. #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
  18751. (void)input;
  18752. (void)msgSz;
  18753. (void)content;
  18754. return 0;
  18755. }
  18756. #ifdef WOLFSSL_DTLS
  18757. static int HandleDTLSDecryptFailed(WOLFSSL* ssl)
  18758. {
  18759. int ret = 0;
  18760. #ifdef WOLFSSL_DTLS_DROP_STATS
  18761. ssl->macDropCount++;
  18762. #endif
  18763. #if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_TLS13_IGNORE_AEAD_LIMITS)
  18764. /* Handle AEAD limits specified by the RFC for failed decryption */
  18765. if (IsAtLeastTLSv1_3(ssl->version))
  18766. ret = Dtls13CheckAEADFailLimit(ssl);
  18767. #endif
  18768. (void)ssl;
  18769. WOLFSSL_MSG("DTLS: Ignoring failed decryption");
  18770. return ret;
  18771. }
  18772. static int DtlsShouldDrop(WOLFSSL* ssl, int retcode)
  18773. {
  18774. if (ssl->options.handShakeDone && !IsEncryptionOn(ssl, 0) &&
  18775. !ssl->options.dtlsHsRetain) {
  18776. WOLFSSL_MSG("Silently dropping plaintext DTLS message "
  18777. "on established connection when we have nothing to send.");
  18778. return 1;
  18779. }
  18780. if ((ssl->options.handShakeDone && retcode != 0)
  18781. || retcode == WC_NO_ERR_TRACE(SEQUENCE_ERROR)
  18782. || retcode == WC_NO_ERR_TRACE(DTLS_CID_ERROR)) {
  18783. WOLFSSL_MSG_EX("Silently dropping DTLS message: %d", retcode);
  18784. return 1;
  18785. }
  18786. #ifdef WOLFSSL_DTLS13
  18787. if (IsAtLeastTLSv1_3(ssl->version) && !w64IsZero(ssl->dtls13Epoch)
  18788. && w64IsZero(ssl->keys.curEpoch64) && ssl->curRL.type != ack) {
  18789. WOLFSSL_MSG("Silently dropping plaintext DTLS message "
  18790. "during encrypted handshake.");
  18791. return 1;
  18792. }
  18793. #endif /* WOLFSSL_DTLS13 */
  18794. #ifndef NO_WOLFSSL_SERVER
  18795. if (ssl->options.side == WOLFSSL_SERVER_END
  18796. && ssl->curRL.type != handshake && !IsSCR(ssl)) {
  18797. if (!ssl->options.dtlsStateful) {
  18798. WOLFSSL_MSG("Drop non-handshake record when not stateful");
  18799. return 1;
  18800. }
  18801. }
  18802. #endif /* NO_WOLFSSL_SERVER */
  18803. return 0;
  18804. }
  18805. #endif /* WOLFSSL_DTLS */
  18806. int ProcessReply(WOLFSSL* ssl)
  18807. {
  18808. return ProcessReplyEx(ssl, 0);
  18809. }
  18810. /* Process input requests. Return 0 is done, 1 is call again to complete, and
  18811. negative number is error. If allowSocketErr is set, SOCKET_ERROR_E in
  18812. ssl->error will be whitelisted. This is useful when the connection has been
  18813. closed and the endpoint wants to check for an alert sent by the other end. */
  18814. int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr)
  18815. {
  18816. int ret = 0, type = internal_error, readSz;
  18817. int atomicUser = 0;
  18818. #if defined(WOLFSSL_DTLS)
  18819. int used;
  18820. #endif
  18821. #ifdef ATOMIC_USER
  18822. if (ssl->ctx->DecryptVerifyCb)
  18823. atomicUser = 1;
  18824. #endif
  18825. if (ssl->error != 0 &&
  18826. ssl->error != WC_NO_ERR_TRACE(WANT_READ) &&
  18827. ssl->error != WC_NO_ERR_TRACE(WANT_WRITE)
  18828. #if defined(HAVE_SECURE_RENEGOTIATION) || defined(WOLFSSL_DTLS13)
  18829. && ssl->error != WC_NO_ERR_TRACE(APP_DATA_READY)
  18830. #endif
  18831. #ifdef WOLFSSL_ASYNC_CRYPT
  18832. && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
  18833. #endif
  18834. #ifdef WOLFSSL_NONBLOCK_OCSP
  18835. && ssl->error != WC_NO_ERR_TRACE(OCSP_WANT_READ)
  18836. #endif
  18837. && (allowSocketErr != 1 ||
  18838. ssl->error != WC_NO_ERR_TRACE(SOCKET_ERROR_E))
  18839. ) {
  18840. WOLFSSL_MSG("ProcessReply retry in error state, not allowed");
  18841. return ssl->error;
  18842. }
  18843. /* If checking alert on error (allowSocketErr == 1) do not try and
  18844. * process alerts for async or ocsp non blocking */
  18845. #if defined(WOLFSSL_CHECK_ALERT_ON_ERR) && \
  18846. (defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP))
  18847. if (allowSocketErr == 1 && \
  18848. (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E) ||
  18849. ssl->error == WC_NO_ERR_TRACE(OCSP_WANT_READ))) {
  18850. return ssl->error;
  18851. }
  18852. #endif
  18853. #if defined(WOLFSSL_DTLS) && defined(WOLFSSL_ASYNC_CRYPT)
  18854. /* process any pending DTLS messages - this flow can happen with async */
  18855. if (ssl->dtls_rx_msg_list != NULL) {
  18856. word32 pendingMsg = ssl->dtls_rx_msg_list_sz;
  18857. if(IsAtLeastTLSv1_3(ssl->version)) {
  18858. #ifdef WOLFSSL_DTLS13
  18859. ret = Dtls13ProcessBufferedMessages(ssl);
  18860. #else
  18861. ret = NOT_COMPILED_IN;
  18862. #endif /* WOLFSSL_DTLS13 */
  18863. }
  18864. else {
  18865. ret = DtlsMsgDrain(ssl);
  18866. }
  18867. if (ret != 0) {
  18868. WOLFSSL_ERROR(ret);
  18869. return ret;
  18870. }
  18871. /* we processed some messages, return so connect/accept can make
  18872. progress */
  18873. if (ssl->dtls_rx_msg_list_sz != pendingMsg)
  18874. return ret;
  18875. }
  18876. #endif
  18877. ret = RetrySendAlert(ssl);
  18878. if (ret != 0) {
  18879. WOLFSSL_MSG_EX("RetrySendAlert failed, giving up. err = %d", ret);
  18880. return ret;
  18881. }
  18882. for (;;) {
  18883. switch (ssl->options.processReply) {
  18884. /* in the WOLFSSL_SERVER case, get the first byte for detecting
  18885. * old client hello */
  18886. case doProcessInit:
  18887. readSz = RECORD_HEADER_SZ;
  18888. #ifdef WOLFSSL_DTLS
  18889. if (ssl->options.dtls) {
  18890. readSz = DTLS_RECORD_HEADER_SZ;
  18891. #ifdef WOLFSSL_DTLS13
  18892. if (ssl->options.tls1_3) {
  18893. /* dtls1.3 unified header can be as little as 2 bytes */
  18894. readSz = DTLS_UNIFIED_HEADER_MIN_SZ;
  18895. }
  18896. #endif /* WOLFSSL_DTLS13 */
  18897. }
  18898. #endif
  18899. /* get header or return error */
  18900. if (!ssl->options.dtls) {
  18901. if ((ret = GetInputData(ssl, (word32)readSz)) < 0)
  18902. return ret;
  18903. } else {
  18904. #ifdef WOLFSSL_DTLS
  18905. /* read ahead may already have header */
  18906. used = ssl->buffers.inputBuffer.length -
  18907. ssl->buffers.inputBuffer.idx;
  18908. if (used < readSz) {
  18909. if ((ret = GetInputData(ssl, (word32)readSz)) < 0)
  18910. return ret;
  18911. }
  18912. #endif
  18913. }
  18914. #ifdef OLD_HELLO_ALLOWED
  18915. /* see if sending SSLv2 client hello */
  18916. if ( ssl->options.side == WOLFSSL_SERVER_END &&
  18917. ssl->options.clientState == NULL_STATE &&
  18918. ssl->buffers.inputBuffer.buffer[ssl->buffers.inputBuffer.idx]
  18919. != handshake) {
  18920. byte b0, b1;
  18921. ssl->options.processReply = runProcessOldClientHello;
  18922. /* sanity checks before getting size at front */
  18923. if (ssl->buffers.inputBuffer.buffer[
  18924. ssl->buffers.inputBuffer.idx + OPAQUE16_LEN] != OLD_HELLO_ID) {
  18925. WOLFSSL_MSG("Not a valid old client hello");
  18926. WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
  18927. return PARSE_ERROR;
  18928. }
  18929. if (ssl->buffers.inputBuffer.buffer[
  18930. ssl->buffers.inputBuffer.idx + OPAQUE24_LEN] != SSLv3_MAJOR &&
  18931. ssl->buffers.inputBuffer.buffer[
  18932. ssl->buffers.inputBuffer.idx + OPAQUE24_LEN] != DTLS_MAJOR) {
  18933. WOLFSSL_MSG("Not a valid version in old client hello");
  18934. WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
  18935. return PARSE_ERROR;
  18936. }
  18937. /* how many bytes need ProcessOldClientHello */
  18938. b0 =
  18939. ssl->buffers.inputBuffer.buffer[ssl->buffers.inputBuffer.idx++];
  18940. b1 =
  18941. ssl->buffers.inputBuffer.buffer[ssl->buffers.inputBuffer.idx++];
  18942. ssl->curSize = (word16)(((b0 & 0x7f) << 8) | b1);
  18943. }
  18944. else {
  18945. ssl->options.processReply = getRecordLayerHeader;
  18946. continue;
  18947. }
  18948. FALL_THROUGH;
  18949. /* in the WOLFSSL_SERVER case, run the old client hello */
  18950. case runProcessOldClientHello:
  18951. /* get sz bytes or return error */
  18952. if (!ssl->options.dtls) {
  18953. if ((ret = GetInputData(ssl, ssl->curSize)) < 0)
  18954. return ret;
  18955. } else {
  18956. #ifdef WOLFSSL_DTLS
  18957. /* read ahead may already have */
  18958. used = ssl->buffers.inputBuffer.length -
  18959. ssl->buffers.inputBuffer.idx;
  18960. if (used < ssl->curSize)
  18961. if ((ret = GetInputData(ssl, ssl->curSize - used)) < 0)
  18962. return ret;
  18963. #endif /* WOLFSSL_DTLS */
  18964. }
  18965. ret = ProcessOldClientHello(ssl, ssl->buffers.inputBuffer.buffer,
  18966. &ssl->buffers.inputBuffer.idx,
  18967. ssl->buffers.inputBuffer.length -
  18968. ssl->buffers.inputBuffer.idx,
  18969. ssl->curSize);
  18970. if (ret < 0)
  18971. return ret;
  18972. else if (ssl->buffers.inputBuffer.idx ==
  18973. ssl->buffers.inputBuffer.length) {
  18974. ssl->options.processReply = doProcessInit;
  18975. return 0;
  18976. }
  18977. #endif /* OLD_HELLO_ALLOWED */
  18978. FALL_THROUGH;
  18979. /* get the record layer header */
  18980. case getRecordLayerHeader:
  18981. /* DTLSv1.3 record numbers in the header are encrypted, and AAD
  18982. * uses the unencrypted form. Because of this we need to modify the
  18983. * header, decrypting the numbers inside
  18984. * DtlsParseUnifiedRecordLayer(). This violates the const attribute
  18985. * of the buffer parameter of GetRecordHeader() used here. */
  18986. ret = GetRecordHeader(ssl, &ssl->buffers.inputBuffer.idx,
  18987. &ssl->curRL, &ssl->curSize);
  18988. #ifdef WOLFSSL_DTLS
  18989. if (ssl->options.dtls && DtlsShouldDrop(ssl, ret)) {
  18990. ssl->options.processReply = doProcessInit;
  18991. ssl->buffers.inputBuffer.length = 0;
  18992. ssl->buffers.inputBuffer.idx = 0;
  18993. #ifdef WOLFSSL_DTLS_DROP_STATS
  18994. ssl->replayDropCount++;
  18995. #endif /* WOLFSSL_DTLS_DROP_STATS */
  18996. #ifdef WOLFSSL_DTLS13
  18997. /* return to send ACKS and shortcut rtx timer */
  18998. if (IsAtLeastTLSv1_3(ssl->version)
  18999. && ssl->dtls13Rtx.sendAcks)
  19000. return 0;
  19001. #endif /* WOLFSSL_DTLS13 */
  19002. continue;
  19003. }
  19004. #endif
  19005. if (ret != 0) {
  19006. switch (ret) {
  19007. case WC_NO_ERR_TRACE(VERSION_ERROR):
  19008. /* send alert per RFC5246 Appendix E. Backward
  19009. * Compatibility */
  19010. if (ssl->options.side == WOLFSSL_CLIENT_END)
  19011. SendAlert(ssl, alert_fatal,
  19012. wolfssl_alert_protocol_version);
  19013. break;
  19014. #ifdef HAVE_MAX_FRAGMENT
  19015. case WC_NO_ERR_TRACE(LENGTH_ERROR):
  19016. SendAlert(ssl, alert_fatal, record_overflow);
  19017. break;
  19018. #endif /* HAVE_MAX_FRAGMENT */
  19019. default:
  19020. break;
  19021. }
  19022. return ret;
  19023. }
  19024. #ifdef WOLFSSL_TLS13
  19025. if (IsAtLeastTLSv1_3(ssl->version) && IsEncryptionOn(ssl, 0) &&
  19026. ssl->curRL.type != application_data &&
  19027. ssl->curRL.type != change_cipher_spec) {
  19028. SendAlert(ssl, alert_fatal, unexpected_message);
  19029. WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
  19030. return PARSE_ERROR;
  19031. }
  19032. #endif
  19033. ssl->options.processReply = getData;
  19034. FALL_THROUGH;
  19035. /* retrieve record layer data */
  19036. case getData:
  19037. /* get sz bytes or return error */
  19038. if (!ssl->options.dtls) {
  19039. if ((ret = GetInputData(ssl, ssl->curSize)) < 0) {
  19040. #ifdef WOLFSSL_EXTRA_ALERTS
  19041. if (ret != WC_NO_ERR_TRACE(WANT_READ))
  19042. SendAlert(ssl, alert_fatal, bad_record_mac);
  19043. #endif
  19044. return ret;
  19045. }
  19046. }
  19047. else {
  19048. #ifdef WOLFSSL_DTLS
  19049. /* read ahead may already have */
  19050. used = ssl->buffers.inputBuffer.length -
  19051. ssl->buffers.inputBuffer.idx;
  19052. if (used < ssl->curSize)
  19053. if ((ret = GetInputData(ssl, ssl->curSize)) < 0)
  19054. return ret;
  19055. #endif
  19056. }
  19057. if (IsEncryptionOn(ssl, 0)) {
  19058. #if defined(WOLFSSL_TLS13) || defined(WOLFSSL_EXTRA_ALERTS)
  19059. int tooLong = 0;
  19060. #endif
  19061. #ifdef WOLFSSL_TLS13
  19062. if (IsAtLeastTLSv1_3(ssl->version)) {
  19063. tooLong = ssl->curSize > MAX_TLS13_ENC_SZ;
  19064. tooLong |= ssl->curSize - ssl->specs.aead_mac_size >
  19065. MAX_TLS13_PLAIN_SZ;
  19066. }
  19067. #endif
  19068. #ifdef WOLFSSL_EXTRA_ALERTS
  19069. if (!IsAtLeastTLSv1_3(ssl->version))
  19070. tooLong = ssl->curSize > MAX_TLS_CIPHER_SZ;
  19071. #endif
  19072. #if defined(WOLFSSL_TLS13) || defined(WOLFSSL_EXTRA_ALERTS)
  19073. if (tooLong) {
  19074. WOLFSSL_MSG("Encrypted data too long");
  19075. SendAlert(ssl, alert_fatal, record_overflow);
  19076. return BUFFER_ERROR;
  19077. }
  19078. #endif
  19079. }
  19080. ssl->keys.padSz = 0;
  19081. ssl->options.processReply = verifyEncryptedMessage;
  19082. /* in case > 1 msg per record */
  19083. ssl->curStartIdx = ssl->buffers.inputBuffer.idx;
  19084. FALL_THROUGH;
  19085. /* verify digest of encrypted message */
  19086. case verifyEncryptedMessage:
  19087. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  19088. if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0 &&
  19089. !atomicUser && ssl->options.startedETMRead) {
  19090. ret = VerifyMacEnc(ssl, ssl->buffers.inputBuffer.buffer +
  19091. ssl->buffers.inputBuffer.idx,
  19092. ssl->curSize, ssl->curRL.type);
  19093. #ifdef WOLFSSL_ASYNC_CRYPT
  19094. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
  19095. return ret;
  19096. #endif
  19097. if (ret < 0) {
  19098. WOLFSSL_MSG("VerifyMacEnc failed");
  19099. #ifdef WOLFSSL_DTLS
  19100. /* If in DTLS mode, if the decrypt fails for any
  19101. * reason, pretend the datagram never happened. */
  19102. if (ssl->options.dtls) {
  19103. ssl->options.processReply = doProcessInit;
  19104. ssl->buffers.inputBuffer.idx =
  19105. ssl->buffers.inputBuffer.length;
  19106. return HandleDTLSDecryptFailed(ssl);
  19107. }
  19108. #endif /* WOLFSSL_DTLS */
  19109. #ifdef WOLFSSL_EXTRA_ALERTS
  19110. if (!ssl->options.dtls)
  19111. SendAlert(ssl, alert_fatal, bad_record_mac);
  19112. #endif
  19113. WOLFSSL_ERROR_VERBOSE(DECRYPT_ERROR);
  19114. return DECRYPT_ERROR;
  19115. }
  19116. ssl->keys.encryptSz = ssl->curSize;
  19117. }
  19118. #endif
  19119. ssl->options.processReply = decryptMessage;
  19120. FALL_THROUGH;
  19121. /* decrypt message */
  19122. case decryptMessage:
  19123. if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0 &&
  19124. (!IsAtLeastTLSv1_3(ssl->version) ||
  19125. ssl->curRL.type != change_cipher_spec))
  19126. {
  19127. bufferStatic* in = &ssl->buffers.inputBuffer;
  19128. ret = SanityCheckCipherText(ssl, ssl->curSize);
  19129. if (ret < 0) {
  19130. #ifdef WOLFSSL_EXTRA_ALERTS
  19131. SendAlert(ssl, alert_fatal, bad_record_mac);
  19132. #endif
  19133. return ret;
  19134. }
  19135. if (atomicUser) {
  19136. #ifdef ATOMIC_USER
  19137. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  19138. if (ssl->options.startedETMRead) {
  19139. ret = ssl->ctx->VerifyDecryptCb(ssl,
  19140. in->buffer + in->idx, in->buffer + in->idx,
  19141. ssl->curSize - MacSize(ssl),
  19142. ssl->curRL.type, 1, &ssl->keys.padSz,
  19143. ssl->DecryptVerifyCtx);
  19144. }
  19145. else
  19146. #endif
  19147. {
  19148. ret = ssl->ctx->DecryptVerifyCb(ssl,
  19149. in->buffer + in->idx,
  19150. in->buffer + in->idx,
  19151. ssl->curSize, ssl->curRL.type, 1,
  19152. &ssl->keys.padSz, ssl->DecryptVerifyCtx);
  19153. }
  19154. #endif /* ATOMIC_USER */
  19155. }
  19156. else {
  19157. if (!ssl->options.tls1_3) {
  19158. #ifndef WOLFSSL_NO_TLS12
  19159. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  19160. if (ssl->options.startedETMRead) {
  19161. word32 digestSz = MacSize(ssl);
  19162. ret = DecryptTls(ssl,
  19163. in->buffer + in->idx,
  19164. in->buffer + in->idx,
  19165. ssl->curSize - (word16)digestSz);
  19166. if (ret == 0) {
  19167. byte invalid = 0;
  19168. byte padding = (byte)-1;
  19169. word32 i;
  19170. word32 off = in->idx + ssl->curSize - digestSz - 1;
  19171. /* Last of padding bytes - indicates length. */
  19172. ssl->keys.padSz = in->buffer[off];
  19173. /* Constant time checking of padding - don't leak
  19174. * the length of the data.
  19175. */
  19176. /* Compare max pad bytes or at most data + pad. */
  19177. for (i = 1; i < MAX_PAD_SIZE && off >= i; i++) {
  19178. /* Mask on indicates this is expected to be a
  19179. * padding byte.
  19180. */
  19181. padding &= ctMaskLTE((int)i,
  19182. (int)ssl->keys.padSz);
  19183. /* When this is a padding byte and not equal
  19184. * to length then mask is set.
  19185. */
  19186. invalid |= padding &
  19187. ctMaskNotEq(in->buffer[off - i],
  19188. (int)ssl->keys.padSz);
  19189. }
  19190. /* If mask is set then there was an error. */
  19191. if (invalid) {
  19192. ret = DECRYPT_ERROR;
  19193. }
  19194. ssl->keys.padSz += 1;
  19195. ssl->keys.decryptedCur = 1;
  19196. }
  19197. }
  19198. else
  19199. #endif
  19200. {
  19201. ret = DecryptTls(ssl,
  19202. in->buffer + in->idx,
  19203. in->buffer + in->idx,
  19204. ssl->curSize);
  19205. }
  19206. #else
  19207. ret = DECRYPT_ERROR;
  19208. #endif
  19209. }
  19210. else
  19211. {
  19212. #ifdef WOLFSSL_TLS13
  19213. byte *aad = (byte*)&ssl->curRL;
  19214. word16 aad_size = RECORD_HEADER_SZ;
  19215. #ifdef WOLFSSL_DTLS13
  19216. if (ssl->options.dtls) {
  19217. /* aad now points to the record header */
  19218. aad = ssl->dtls13CurRL;
  19219. aad_size = ssl->dtls13CurRlLength;
  19220. }
  19221. #endif /* WOLFSSL_DTLS13 */
  19222. /* Don't send an alert for DTLS. We will just drop it
  19223. * silently later. */
  19224. ret = DecryptTls13(ssl,
  19225. in->buffer + in->idx,
  19226. in->buffer + in->idx,
  19227. ssl->curSize,
  19228. aad, aad_size);
  19229. #else
  19230. ret = DECRYPT_ERROR;
  19231. #endif /* WOLFSSL_TLS13 */
  19232. }
  19233. (void)in;
  19234. }
  19235. #ifdef WOLFSSL_ASYNC_CRYPT
  19236. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
  19237. return ret;
  19238. #endif
  19239. if (ret >= 0) {
  19240. #ifndef WOLFSSL_NO_TLS12
  19241. /* handle success */
  19242. #ifndef WOLFSSL_AEAD_ONLY
  19243. if (ssl->options.tls1_1 && ssl->specs.cipher_type == block)
  19244. ssl->buffers.inputBuffer.idx += ssl->specs.block_size;
  19245. #endif
  19246. /* go past TLSv1.1 IV */
  19247. if (CipherHasExpIV(ssl))
  19248. ssl->buffers.inputBuffer.idx += AESGCM_EXP_IV_SZ;
  19249. #endif
  19250. }
  19251. else {
  19252. WOLFSSL_MSG("Decrypt failed");
  19253. #ifdef WOLFSSL_DTLS
  19254. /* If in DTLS mode, if the decrypt fails for any
  19255. * reason, pretend the datagram never happened. */
  19256. if (ssl->options.dtls) {
  19257. ssl->options.processReply = doProcessInit;
  19258. ssl->buffers.inputBuffer.idx =
  19259. ssl->buffers.inputBuffer.length;
  19260. return HandleDTLSDecryptFailed(ssl);
  19261. }
  19262. #endif /* WOLFSSL_DTLS */
  19263. #ifdef WOLFSSL_EARLY_DATA
  19264. if (ssl->options.tls1_3) {
  19265. if (ssl->options.side == WOLFSSL_SERVER_END &&
  19266. ssl->earlyData != no_early_data &&
  19267. ssl->options.clientState <
  19268. CLIENT_FINISHED_COMPLETE) {
  19269. ssl->earlyDataSz += ssl->curSize;
  19270. if (ssl->earlyDataSz <=
  19271. ssl->options.maxEarlyDataSz) {
  19272. WOLFSSL_MSG("Ignoring EarlyData!");
  19273. if (ssl->keys.peer_sequence_number_lo-- == 0)
  19274. ssl->keys.peer_sequence_number_hi--;
  19275. ssl->options.processReply = doProcessInit;
  19276. ssl->buffers.inputBuffer.idx += ssl->curSize;
  19277. if (ssl->buffers.inputBuffer.idx >
  19278. ssl->buffers.inputBuffer.length) {
  19279. WOLFSSL_ERROR(BUFFER_E);
  19280. return BUFFER_E;
  19281. }
  19282. return 0;
  19283. }
  19284. WOLFSSL_MSG("Too much EarlyData!");
  19285. SendAlert(ssl, alert_fatal, unexpected_message);
  19286. WOLFSSL_ERROR(TOO_MUCH_EARLY_DATA);
  19287. return TOO_MUCH_EARLY_DATA;
  19288. }
  19289. }
  19290. #endif
  19291. SendAlert(ssl, alert_fatal, bad_record_mac);
  19292. /* Push error once we know that we will error out here */
  19293. WOLFSSL_ERROR(ret);
  19294. return ret;
  19295. }
  19296. }
  19297. ssl->options.processReply = verifyMessage;
  19298. FALL_THROUGH;
  19299. /* verify digest of message */
  19300. case verifyMessage:
  19301. if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0 &&
  19302. (!IsAtLeastTLSv1_3(ssl->version) ||
  19303. ssl->curRL.type != change_cipher_spec))
  19304. {
  19305. if (!atomicUser
  19306. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  19307. && !ssl->options.startedETMRead
  19308. #endif
  19309. ) {
  19310. ret = VerifyMac(ssl, ssl->buffers.inputBuffer.buffer +
  19311. ssl->buffers.inputBuffer.idx,
  19312. ssl->curSize, ssl->curRL.type,
  19313. &ssl->keys.padSz);
  19314. #ifdef WOLFSSL_ASYNC_CRYPT
  19315. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
  19316. return ret;
  19317. #endif
  19318. if (ret < 0) {
  19319. #ifdef WOLFSSL_DTLS
  19320. /* If in DTLS mode, if the decrypt fails for any
  19321. * reason, pretend the datagram never happened. */
  19322. if (ssl->options.dtls) {
  19323. ssl->options.processReply = doProcessInit;
  19324. ssl->buffers.inputBuffer.idx =
  19325. ssl->buffers.inputBuffer.length;
  19326. return HandleDTLSDecryptFailed(ssl);
  19327. }
  19328. #endif /* WOLFSSL_DTLS */
  19329. #if defined(WOLFSSL_EXTRA_ALERTS) && !defined(WOLFSSL_NO_ETM_ALERT)
  19330. if (!ssl->options.dtls)
  19331. SendAlert(ssl, alert_fatal, bad_record_mac);
  19332. #endif
  19333. WOLFSSL_MSG("VerifyMac failed");
  19334. WOLFSSL_ERROR_VERBOSE(DECRYPT_ERROR);
  19335. return DECRYPT_ERROR;
  19336. }
  19337. }
  19338. ssl->keys.encryptSz = ssl->curSize;
  19339. ssl->keys.decryptedCur = 1;
  19340. #ifdef WOLFSSL_TLS13
  19341. if (ssl->options.tls1_3) {
  19342. word32 i = (ssl->buffers.inputBuffer.idx +
  19343. ssl->curSize - ssl->specs.aead_mac_size);
  19344. /* check that the end of the logical length doesn't extend
  19345. * past the real buffer */
  19346. if (i > ssl->buffers.inputBuffer.length || i == 0) {
  19347. WOLFSSL_ERROR(BUFFER_ERROR);
  19348. return BUFFER_ERROR;
  19349. }
  19350. /* Remove padding from end of plain text. */
  19351. for (--i; i > ssl->buffers.inputBuffer.idx; i--) {
  19352. if (ssl->buffers.inputBuffer.buffer[i] != 0)
  19353. break;
  19354. }
  19355. /* Get the real content type from the end of the data. */
  19356. ssl->curRL.type = ssl->buffers.inputBuffer.buffer[i];
  19357. /* consider both contentType byte and MAC as padding */
  19358. ssl->keys.padSz = ssl->buffers.inputBuffer.idx
  19359. + ssl->curSize - i;
  19360. }
  19361. #endif
  19362. }
  19363. ssl->options.processReply = runProcessingOneRecord;
  19364. FALL_THROUGH;
  19365. /* the record layer is here */
  19366. case runProcessingOneRecord:
  19367. #ifdef WOLFSSL_DTLS13
  19368. if (ssl->options.dtls) {
  19369. if (IsAtLeastTLSv1_3(ssl->version)) {
  19370. if (!Dtls13CheckWindow(ssl)) {
  19371. /* drop packet */
  19372. WOLFSSL_MSG("Dropping DTLS record outside receiving "
  19373. "window");
  19374. ssl->options.processReply = doProcessInit;
  19375. ssl->buffers.inputBuffer.idx += ssl->curSize;
  19376. if (ssl->buffers.inputBuffer.idx >
  19377. ssl->buffers.inputBuffer.length)
  19378. return BUFFER_E;
  19379. continue;
  19380. }
  19381. /* Only update the window once we enter stateful parsing */
  19382. if (ssl->options.dtlsStateful) {
  19383. ret = Dtls13UpdateWindowRecordRecvd(ssl);
  19384. if (ret != 0) {
  19385. WOLFSSL_ERROR(ret);
  19386. return ret;
  19387. }
  19388. }
  19389. }
  19390. else if (IsDtlsNotSctpMode(ssl)) {
  19391. DtlsUpdateWindow(ssl);
  19392. }
  19393. }
  19394. #endif /* WOLFSSL_DTLS13 */
  19395. ssl->options.processReply = runProcessingOneMessage;
  19396. FALL_THROUGH;
  19397. case runProcessingOneMessage:
  19398. /* can't process a message if we have no data. */
  19399. if (ssl->buffers.inputBuffer.idx
  19400. >= ssl->buffers.inputBuffer.length) {
  19401. return BUFFER_ERROR;
  19402. }
  19403. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  19404. if (IsEncryptionOn(ssl, 0) && ssl->options.startedETMRead) {
  19405. /* For TLS v1.1 the block size and explicit IV are added to idx,
  19406. * so it needs to be included in this limit check */
  19407. if ((ssl->curSize - ssl->keys.padSz -
  19408. (ssl->buffers.inputBuffer.idx - ssl->curStartIdx) -
  19409. MacSize(ssl) > MAX_PLAINTEXT_SZ)
  19410. #ifdef WOLFSSL_ASYNC_CRYPT
  19411. && ssl->buffers.inputBuffer.length !=
  19412. ssl->buffers.inputBuffer.idx
  19413. #endif
  19414. ) {
  19415. WOLFSSL_MSG("Plaintext too long - Encrypt-Then-MAC");
  19416. #if defined(WOLFSSL_EXTRA_ALERTS) && !defined(WOLFSSL_NO_ETM_ALERT)
  19417. SendAlert(ssl, alert_fatal, record_overflow);
  19418. #endif
  19419. WOLFSSL_ERROR_VERBOSE(BUFFER_ERROR);
  19420. return BUFFER_ERROR;
  19421. }
  19422. }
  19423. else
  19424. #endif
  19425. /* TLS13 plaintext limit is checked earlier before decryption */
  19426. /* For TLS v1.1 the block size and explicit IV are added to idx,
  19427. * so it needs to be included in this limit check */
  19428. if (!IsAtLeastTLSv1_3(ssl->version)
  19429. && ssl->curSize - ssl->keys.padSz -
  19430. (ssl->buffers.inputBuffer.idx - ssl->curStartIdx)
  19431. > MAX_PLAINTEXT_SZ
  19432. #ifdef WOLFSSL_ASYNC_CRYPT
  19433. && ssl->buffers.inputBuffer.length !=
  19434. ssl->buffers.inputBuffer.idx
  19435. #endif
  19436. ) {
  19437. WOLFSSL_MSG("Plaintext too long");
  19438. #if defined(WOLFSSL_TLS13) || defined(WOLFSSL_EXTRA_ALERTS)
  19439. SendAlert(ssl, alert_fatal, record_overflow);
  19440. #endif
  19441. WOLFSSL_ERROR_VERBOSE(BUFFER_ERROR);
  19442. return BUFFER_ERROR;
  19443. }
  19444. WOLFSSL_MSG("received record layer msg");
  19445. switch (ssl->curRL.type) {
  19446. case handshake :
  19447. WOLFSSL_MSG("got HANDSHAKE");
  19448. /* debugging in DoHandShakeMsg */
  19449. if (ssl->options.dtls) {
  19450. #ifdef WOLFSSL_DTLS
  19451. if (!IsAtLeastTLSv1_3(ssl->version)) {
  19452. ret = DoDtlsHandShakeMsg(ssl,
  19453. ssl->buffers.inputBuffer.buffer,
  19454. &ssl->buffers.inputBuffer.idx,
  19455. ssl->buffers.inputBuffer.length);
  19456. if (ret == 0 ||
  19457. ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  19458. /* Reset timeout as we have received a valid
  19459. * DTLS handshake message */
  19460. ssl->dtls_timeout = ssl->dtls_timeout_init;
  19461. }
  19462. else {
  19463. if (SendFatalAlertOnly(ssl, ret)
  19464. == WC_NO_ERR_TRACE(SOCKET_ERROR_E)) {
  19465. ret = SOCKET_ERROR_E;
  19466. }
  19467. }
  19468. }
  19469. #endif
  19470. #ifdef WOLFSSL_DTLS13
  19471. if (IsAtLeastTLSv1_3(ssl->version)) {
  19472. ret = Dtls13HandshakeRecv(ssl,
  19473. ssl->buffers.inputBuffer.buffer,
  19474. &ssl->buffers.inputBuffer.idx,
  19475. ssl->buffers.inputBuffer.length);
  19476. #ifdef WOLFSSL_EARLY_DATA
  19477. if (ret == 0 &&
  19478. ssl->options.side == WOLFSSL_SERVER_END &&
  19479. ssl->earlyData > early_data_ext &&
  19480. ssl->options.handShakeState == HANDSHAKE_DONE) {
  19481. /* return so wolfSSL_read_early_data can return
  19482. exit */
  19483. ssl->earlyData = no_early_data;
  19484. ssl->options.processReply = doProcessInit;
  19485. return ZERO_RETURN;
  19486. }
  19487. #endif /* WOLFSSL_EARLY_DATA */
  19488. }
  19489. #endif /* WOLFSSL_DTLS13 */
  19490. }
  19491. else if (!IsAtLeastTLSv1_3(ssl->version)
  19492. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_TLS12)
  19493. || !TLSv1_3_Capable(ssl)
  19494. #endif
  19495. ) {
  19496. #ifndef WOLFSSL_NO_TLS12
  19497. ret = DoHandShakeMsg(ssl,
  19498. ssl->buffers.inputBuffer.buffer,
  19499. &ssl->buffers.inputBuffer.idx,
  19500. ssl->buffers.inputBuffer.length);
  19501. if (ret != 0) {
  19502. if (SendFatalAlertOnly(ssl, ret) ==
  19503. WC_NO_ERR_TRACE(SOCKET_ERROR_E))
  19504. ret = SOCKET_ERROR_E;
  19505. }
  19506. #else
  19507. ret = BUFFER_ERROR;
  19508. #endif
  19509. }
  19510. else {
  19511. #ifdef WOLFSSL_TLS13
  19512. ssl->msgsReceived.got_change_cipher = 0;
  19513. ret = DoTls13HandShakeMsg(ssl,
  19514. ssl->buffers.inputBuffer.buffer,
  19515. &ssl->buffers.inputBuffer.idx,
  19516. ssl->buffers.inputBuffer.length);
  19517. #ifdef WOLFSSL_EARLY_DATA
  19518. if (ret != 0)
  19519. return ret;
  19520. if (ssl->options.side == WOLFSSL_SERVER_END &&
  19521. ssl->earlyData > early_data_ext &&
  19522. ssl->options.handShakeState == HANDSHAKE_DONE) {
  19523. ssl->earlyData = no_early_data;
  19524. ssl->options.processReply = doProcessInit;
  19525. return ZERO_RETURN;
  19526. }
  19527. #endif
  19528. #else
  19529. ret = BUFFER_ERROR;
  19530. #endif
  19531. }
  19532. if (ret != 0
  19533. /* DoDtlsHandShakeMsg can return a WANT_WRITE when
  19534. * calling DtlsMsgPoolSend. This msg is done
  19535. * processing so let's move on. */
  19536. && (!ssl->options.dtls
  19537. || ret != WC_NO_ERR_TRACE(WANT_WRITE))
  19538. #ifdef WOLFSSL_ASYNC_CRYPT
  19539. /* In async case, on pending, move onto next message.
  19540. * Current message should have been DtlsMsgStore'ed and
  19541. * should be processed with DtlsMsgDrain */
  19542. && (!ssl->options.dtls
  19543. || ret != WC_NO_ERR_TRACE(WC_PENDING_E))
  19544. #endif
  19545. ) {
  19546. WOLFSSL_ERROR(ret);
  19547. return ret;
  19548. }
  19549. break;
  19550. case change_cipher_spec:
  19551. WOLFSSL_MSG("got CHANGE CIPHER SPEC");
  19552. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  19553. if (ssl->hsInfoOn)
  19554. AddPacketName(ssl, "ChangeCipher");
  19555. /* add record header back on info */
  19556. if (ssl->toInfoOn) {
  19557. ret = AddPacketInfo(ssl, "ChangeCipher",
  19558. change_cipher_spec,
  19559. ssl->buffers.inputBuffer.buffer +
  19560. ssl->buffers.inputBuffer.idx,
  19561. 1, READ_PROTO, RECORD_HEADER_SZ, ssl->heap);
  19562. if (ret != 0)
  19563. return ret;
  19564. #ifdef WOLFSSL_CALLBACKS
  19565. AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
  19566. #endif
  19567. }
  19568. #endif
  19569. #ifdef WOLFSSL_TLS13
  19570. if (IsAtLeastTLSv1_3(ssl->version)) {
  19571. word32 i = ssl->buffers.inputBuffer.idx;
  19572. if (ssl->options.handShakeState == HANDSHAKE_DONE) {
  19573. SendAlert(ssl, alert_fatal, unexpected_message);
  19574. WOLFSSL_ERROR_VERBOSE(UNKNOWN_RECORD_TYPE);
  19575. return UNKNOWN_RECORD_TYPE;
  19576. }
  19577. if (ssl->curSize != 1 ||
  19578. ssl->buffers.inputBuffer.buffer[i] != 1) {
  19579. SendAlert(ssl, alert_fatal, illegal_parameter);
  19580. WOLFSSL_ERROR_VERBOSE(UNKNOWN_RECORD_TYPE);
  19581. return UNKNOWN_RECORD_TYPE;
  19582. }
  19583. ssl->buffers.inputBuffer.idx++;
  19584. if (!ssl->msgsReceived.got_change_cipher) {
  19585. ssl->msgsReceived.got_change_cipher = 1;
  19586. }
  19587. else {
  19588. SendAlert(ssl, alert_fatal, illegal_parameter);
  19589. WOLFSSL_ERROR_VERBOSE(UNKNOWN_RECORD_TYPE);
  19590. return UNKNOWN_RECORD_TYPE;
  19591. }
  19592. break;
  19593. }
  19594. #endif
  19595. #ifndef WOLFSSL_NO_TLS12
  19596. if (ssl->buffers.inputBuffer.idx >=
  19597. ssl->buffers.inputBuffer.length ||
  19598. ssl->curSize < 1) {
  19599. WOLFSSL_MSG("ChangeCipher msg too short");
  19600. WOLFSSL_ERROR_VERBOSE(LENGTH_ERROR);
  19601. return LENGTH_ERROR;
  19602. }
  19603. if (ssl->buffers.inputBuffer.buffer[
  19604. ssl->buffers.inputBuffer.idx] != 1) {
  19605. WOLFSSL_MSG("ChangeCipher msg wrong value");
  19606. WOLFSSL_ERROR_VERBOSE(LENGTH_ERROR);
  19607. return LENGTH_ERROR;
  19608. }
  19609. if (IsEncryptionOn(ssl, 0) && ssl->options.handShakeDone) {
  19610. #ifdef HAVE_AEAD
  19611. if (ssl->specs.cipher_type == aead) {
  19612. if (ssl->specs.bulk_cipher_algorithm != wolfssl_chacha)
  19613. ssl->curSize -= AESGCM_EXP_IV_SZ;
  19614. ssl->buffers.inputBuffer.idx += ssl->specs.aead_mac_size;
  19615. ssl->curSize -= ssl->specs.aead_mac_size;
  19616. }
  19617. else
  19618. #endif
  19619. {
  19620. ssl->buffers.inputBuffer.idx += ssl->keys.padSz;
  19621. ssl->curSize -= (word16)ssl->keys.padSz;
  19622. ssl->curSize -= ssl->specs.iv_size;
  19623. }
  19624. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  19625. if (ssl->options.startedETMRead) {
  19626. word32 digestSz = MacSize(ssl);
  19627. ssl->buffers.inputBuffer.idx += digestSz;
  19628. ssl->curSize -= (word16)digestSz;
  19629. }
  19630. #endif
  19631. }
  19632. if (ssl->curSize != 1) {
  19633. WOLFSSL_MSG("Malicious or corrupted ChangeCipher msg");
  19634. WOLFSSL_ERROR_VERBOSE(LENGTH_ERROR);
  19635. return LENGTH_ERROR;
  19636. }
  19637. ssl->buffers.inputBuffer.idx++;
  19638. ret = SanityCheckMsgReceived(ssl, change_cipher_hs);
  19639. if (ret != 0) {
  19640. if (!ssl->options.dtls) {
  19641. return ret;
  19642. }
  19643. else {
  19644. #ifdef WOLFSSL_DTLS
  19645. /* Check for duplicate CCS message in DTLS mode.
  19646. * DTLS allows for duplicate messages, and it should be
  19647. * skipped. Also skip if out of order. */
  19648. if (ret != WC_NO_ERR_TRACE(DUPLICATE_MSG_E) &&
  19649. ret != WC_NO_ERR_TRACE(OUT_OF_ORDER_E))
  19650. return ret;
  19651. /* Reset error */
  19652. ret = 0;
  19653. break;
  19654. #endif /* WOLFSSL_DTLS */
  19655. }
  19656. }
  19657. ssl->keys.encryptionOn = 1;
  19658. /* setup decrypt keys for following messages */
  19659. /* XXX This might not be what we want to do when
  19660. * receiving a CCS with multicast. We update the
  19661. * key when the application updates them. */
  19662. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  19663. return ret;
  19664. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  19665. ssl->options.startedETMRead = ssl->options.encThenMac;
  19666. #endif
  19667. #ifdef WOLFSSL_DTLS
  19668. if (ssl->options.dtls) {
  19669. WOLFSSL_DTLS_PEERSEQ* peerSeq = ssl->keys.peerSeq;
  19670. #ifdef WOLFSSL_MULTICAST
  19671. if (ssl->options.haveMcast) {
  19672. peerSeq += ssl->keys.curPeerId;
  19673. peerSeq->highwaterMark = UpdateHighwaterMark(0,
  19674. ssl->ctx->mcastFirstSeq,
  19675. ssl->ctx->mcastSecondSeq,
  19676. ssl->ctx->mcastMaxSeq);
  19677. }
  19678. #endif
  19679. peerSeq->nextEpoch++;
  19680. peerSeq->prevSeq_lo = peerSeq->nextSeq_lo;
  19681. peerSeq->prevSeq_hi = peerSeq->nextSeq_hi;
  19682. peerSeq->nextSeq_lo = 0;
  19683. peerSeq->nextSeq_hi = 0;
  19684. XMEMCPY(peerSeq->prevWindow, peerSeq->window,
  19685. DTLS_SEQ_SZ);
  19686. XMEMSET(peerSeq->window, 0, DTLS_SEQ_SZ);
  19687. }
  19688. #endif
  19689. #ifdef HAVE_LIBZ
  19690. if (ssl->options.usingCompression)
  19691. if ( (ret = InitStreams(ssl)) != 0)
  19692. return ret;
  19693. #endif
  19694. ret = BuildFinished(ssl, &ssl->hsHashes->verifyHashes,
  19695. ssl->options.side == WOLFSSL_CLIENT_END ?
  19696. kTlsServerStr : kTlsClientStr);
  19697. if (ret != 0)
  19698. return ret;
  19699. #endif /* !WOLFSSL_NO_TLS12 */
  19700. break;
  19701. case application_data:
  19702. WOLFSSL_MSG("got app DATA");
  19703. #ifdef WOLFSSL_DTLS
  19704. if (ssl->options.dtls && ssl->options.dtlsHsRetain) {
  19705. #ifdef HAVE_SECURE_RENEGOTIATION
  19706. /*
  19707. * Only free HS resources when not in the process of a
  19708. * secure renegotiation and we have received APP DATA
  19709. * from the current epoch
  19710. */
  19711. if (!IsSCR(ssl) && (DtlsUseSCRKeys(ssl)
  19712. || !DtlsSCRKeysSet(ssl))) {
  19713. FreeHandshakeResources(ssl);
  19714. ssl->options.dtlsHsRetain = 0;
  19715. }
  19716. #else
  19717. FreeHandshakeResources(ssl);
  19718. ssl->options.dtlsHsRetain = 0;
  19719. #endif
  19720. }
  19721. #endif
  19722. #ifdef WOLFSSL_TLS13
  19723. if (ssl->keys.keyUpdateRespond) {
  19724. WOLFSSL_MSG("No KeyUpdate from peer seen");
  19725. WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
  19726. return SANITY_MSG_E;
  19727. }
  19728. #endif
  19729. if ((ret = DoApplicationData(ssl,
  19730. ssl->buffers.inputBuffer.buffer,
  19731. &ssl->buffers.inputBuffer.idx,
  19732. NO_SNIFF)) != 0) {
  19733. WOLFSSL_ERROR(ret);
  19734. #if defined(WOLFSSL_DTLS13) || \
  19735. defined(HAVE_SECURE_RENEGOTIATION)
  19736. /* Not really an error. We will return after cleaning
  19737. * up the processReply state. */
  19738. if (ret != WC_NO_ERR_TRACE(APP_DATA_READY))
  19739. #endif
  19740. return ret;
  19741. }
  19742. break;
  19743. case alert:
  19744. WOLFSSL_MSG("got ALERT!");
  19745. ret = DoAlert(ssl, ssl->buffers.inputBuffer.buffer,
  19746. &ssl->buffers.inputBuffer.idx, &type);
  19747. if (ret == alert_fatal)
  19748. return FATAL_ERROR;
  19749. else if (ret < 0)
  19750. return ret;
  19751. /* catch warnings that are handled as errors */
  19752. if (type == close_notify) {
  19753. ssl->buffers.inputBuffer.idx =
  19754. ssl->buffers.inputBuffer.length;
  19755. ssl->options.processReply = doProcessInit;
  19756. return ssl->error = ZERO_RETURN;
  19757. }
  19758. if (type == decrypt_error)
  19759. return FATAL_ERROR;
  19760. /* Reset error if we got an alert level in ret */
  19761. if (ret > 0)
  19762. ret = 0;
  19763. break;
  19764. #ifdef WOLFSSL_DTLS13
  19765. case ack:
  19766. WOLFSSL_MSG("got ACK");
  19767. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) {
  19768. word32 processedSize = 0;
  19769. ret = DoDtls13Ack(ssl, ssl->buffers.inputBuffer.buffer +
  19770. ssl->buffers.inputBuffer.idx,
  19771. ssl->buffers.inputBuffer.length -
  19772. ssl->buffers.inputBuffer.idx -
  19773. ssl->keys.padSz, &processedSize);
  19774. ssl->buffers.inputBuffer.idx += processedSize;
  19775. ssl->buffers.inputBuffer.idx += ssl->keys.padSz;
  19776. if (ret != 0)
  19777. return ret;
  19778. break;
  19779. }
  19780. FALL_THROUGH;
  19781. #endif /* WOLFSSL_DTLS13 */
  19782. default:
  19783. WOLFSSL_ERROR(UNKNOWN_RECORD_TYPE);
  19784. return UNKNOWN_RECORD_TYPE;
  19785. }
  19786. ssl->options.processReply = doProcessInit;
  19787. /* input exhausted */
  19788. if (ssl->buffers.inputBuffer.idx >= ssl->buffers.inputBuffer.length
  19789. #ifdef WOLFSSL_DTLS
  19790. || (ssl->options.dtls &&
  19791. /* If app data was processed then return now to avoid
  19792. * dropping any app data. */
  19793. (ssl->curRL.type == application_data ||
  19794. /* client: if we processed a finished message, return to
  19795. * allow higher layers to establish the crypto
  19796. * parameters of the connection. The remaining data
  19797. * may be app data that we would drop without the
  19798. * crypto setup. */
  19799. (ssl->options.side == WOLFSSL_CLIENT_END &&
  19800. ssl->options.serverState == SERVER_FINISHED_COMPLETE &&
  19801. ssl->options.handShakeState != HANDSHAKE_DONE)))
  19802. #endif
  19803. ) {
  19804. /* Shrink input buffer when we successfully finish record
  19805. * processing */
  19806. if ((ret == 0) && ssl->buffers.inputBuffer.dynamicFlag)
  19807. ShrinkInputBuffer(ssl, NO_FORCED_FREE);
  19808. return ret;
  19809. }
  19810. /* more messages per record */
  19811. else if ((ssl->buffers.inputBuffer.idx - ssl->curStartIdx)
  19812. < ssl->curSize) {
  19813. WOLFSSL_MSG("More messages in record");
  19814. ssl->options.processReply = runProcessingOneMessage;
  19815. if (IsEncryptionOn(ssl, 0)) {
  19816. WOLFSSL_MSG("Bundled encrypted messages, remove middle pad");
  19817. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  19818. if (ssl->options.startedETMRead) {
  19819. word32 digestSz = MacSize(ssl);
  19820. if (ssl->buffers.inputBuffer.idx >=
  19821. ssl->keys.padSz + digestSz) {
  19822. ssl->buffers.inputBuffer.idx -=
  19823. ssl->keys.padSz + digestSz;
  19824. }
  19825. else {
  19826. WOLFSSL_MSG("\tmiddle padding error");
  19827. WOLFSSL_ERROR_VERBOSE(FATAL_ERROR);
  19828. return FATAL_ERROR;
  19829. }
  19830. }
  19831. else
  19832. #endif
  19833. {
  19834. if (ssl->buffers.inputBuffer.idx >= ssl->keys.padSz) {
  19835. ssl->buffers.inputBuffer.idx -= ssl->keys.padSz;
  19836. }
  19837. else {
  19838. WOLFSSL_MSG("\tmiddle padding error");
  19839. WOLFSSL_ERROR_VERBOSE(FATAL_ERROR);
  19840. return FATAL_ERROR;
  19841. }
  19842. }
  19843. }
  19844. }
  19845. /* more records */
  19846. else {
  19847. WOLFSSL_MSG("More records in input");
  19848. }
  19849. #ifdef WOLFSSL_ASYNC_CRYPT
  19850. /* We are setup to read next message/record but we had an error
  19851. * (probably WC_PENDING_E) so return that so it can be handled
  19852. * by higher layers. */
  19853. if (ret != 0)
  19854. return ret;
  19855. #endif
  19856. #if defined(WOLFSSL_DTLS13) || defined(HAVE_SECURE_RENEGOTIATION)
  19857. /* Signal to user that we have application data ready to read */
  19858. if (ret == WC_NO_ERR_TRACE(APP_DATA_READY))
  19859. return ret;
  19860. #endif
  19861. /* It is safe to shrink the input buffer here now. local vars will
  19862. * be reset to the new starting value. */
  19863. if (ret == 0 && ssl->buffers.inputBuffer.dynamicFlag)
  19864. ShrinkInputBuffer(ssl, NO_FORCED_FREE);
  19865. continue;
  19866. default:
  19867. WOLFSSL_MSG("Bad process input state, programming error");
  19868. WOLFSSL_ERROR_VERBOSE(INPUT_CASE_ERROR);
  19869. return INPUT_CASE_ERROR;
  19870. }
  19871. }
  19872. }
  19873. #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS) || \
  19874. (defined(WOLFSSL_TLS13) && defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT))
  19875. int SendChangeCipher(WOLFSSL* ssl)
  19876. {
  19877. byte *output;
  19878. int sendSz = RECORD_HEADER_SZ + ENUM_LEN;
  19879. int idx = RECORD_HEADER_SZ;
  19880. int ret;
  19881. #ifdef OPENSSL_EXTRA
  19882. ssl->cbmode = SSL_CB_MODE_WRITE;
  19883. if (ssl->options.side == WOLFSSL_SERVER_END){
  19884. ssl->options.serverState = SERVER_CHANGECIPHERSPEC_COMPLETE;
  19885. if (ssl->CBIS != NULL)
  19886. ssl->CBIS(ssl, SSL_CB_ACCEPT_LOOP, WOLFSSL_SUCCESS);
  19887. }
  19888. else{
  19889. ssl->options.clientState =
  19890. CLIENT_CHANGECIPHERSPEC_COMPLETE;
  19891. if (ssl->CBIS != NULL)
  19892. ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, WOLFSSL_SUCCESS);
  19893. }
  19894. #endif
  19895. #ifdef WOLFSSL_DTLS
  19896. if (ssl->options.dtls) {
  19897. sendSz += DTLS_RECORD_EXTRA;
  19898. idx += DTLS_RECORD_EXTRA;
  19899. }
  19900. #endif
  19901. /* are we in scr */
  19902. if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone) {
  19903. sendSz += MAX_MSG_EXTRA;
  19904. }
  19905. /* Set this in case CheckAvailableSize returns a WANT_WRITE so that state
  19906. * is not advanced yet */
  19907. ssl->options.buildingMsg = 1;
  19908. /* check for available size */
  19909. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  19910. return ret;
  19911. /* get output buffer */
  19912. output = GetOutputBuffer(ssl);
  19913. AddRecordHeader(output, 1, change_cipher_spec, ssl, CUR_ORDER);
  19914. output[idx] = 1; /* turn it on */
  19915. if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone) {
  19916. byte input[ENUM_LEN];
  19917. int inputSz = ENUM_LEN;
  19918. input[0] = 1; /* turn it on */
  19919. #ifdef WOLFSSL_DTLS
  19920. if (IsDtlsNotSctpMode(ssl) &&
  19921. (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, change_cipher_hs)) != 0) {
  19922. return ret;
  19923. }
  19924. #endif
  19925. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  19926. change_cipher_spec, 0, 0, 0, CUR_ORDER);
  19927. if (sendSz < 0) {
  19928. return sendSz;
  19929. }
  19930. }
  19931. #ifdef WOLFSSL_DTLS
  19932. else {
  19933. if (IsDtlsNotSctpMode(ssl)) {
  19934. if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, change_cipher_hs)) != 0)
  19935. return ret;
  19936. DtlsSEQIncrement(ssl, CUR_ORDER);
  19937. }
  19938. }
  19939. #endif
  19940. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  19941. if (ssl->hsInfoOn) AddPacketName(ssl, "ChangeCipher");
  19942. if (ssl->toInfoOn) {
  19943. ret = AddPacketInfo(ssl, "ChangeCipher", change_cipher_spec, output,
  19944. sendSz, WRITE_PROTO, 0, ssl->heap);
  19945. if (ret != 0)
  19946. return ret;
  19947. }
  19948. #endif
  19949. ssl->buffers.outputBuffer.length += (word32)sendSz;
  19950. #ifdef WOLFSSL_TLS13
  19951. if (!ssl->options.tls1_3)
  19952. #endif
  19953. {
  19954. /* setup encrypt keys */
  19955. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  19956. return ret;
  19957. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  19958. ssl->options.startedETMWrite = ssl->options.encThenMac;
  19959. #endif
  19960. }
  19961. ssl->options.buildingMsg = 0;
  19962. if (ssl->options.groupMessages)
  19963. return 0;
  19964. #if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_DEBUG_DTLS)
  19965. else if (ssl->options.dtls) {
  19966. /* If using DTLS, force the ChangeCipherSpec message to be in the
  19967. * same datagram as the finished message. */
  19968. return 0;
  19969. }
  19970. #endif
  19971. else
  19972. return SendBuffered(ssl);
  19973. }
  19974. #endif
  19975. #if !defined(NO_OLD_TLS) && !defined(WOLFSSL_AEAD_ONLY)
  19976. static int SSL_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz,
  19977. int padLen, int content, int verify, int epochOrder)
  19978. {
  19979. byte result[WC_MAX_DIGEST_SIZE];
  19980. word32 digestSz = ssl->specs.hash_size; /* actual sizes */
  19981. word32 padSz = ssl->specs.pad_size;
  19982. int ret = 0;
  19983. wc_Md5 md5;
  19984. wc_Sha sha;
  19985. /* data */
  19986. byte seq[SEQ_SZ];
  19987. byte conLen[ENUM_LEN + LENGTH_SZ]; /* content & length */
  19988. const byte* macSecret = NULL;
  19989. (void)padLen;
  19990. #ifdef HAVE_FUZZER
  19991. if (ssl->fuzzerCb)
  19992. ssl->fuzzerCb(ssl, in, sz, FUZZ_HMAC, ssl->fuzzerCtx);
  19993. #endif
  19994. #ifdef WOLFSSL_DTLS
  19995. if (ssl->options.dtls)
  19996. macSecret = wolfSSL_GetDtlsMacSecret(ssl, verify, epochOrder);
  19997. else
  19998. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  19999. #else
  20000. macSecret = wolfSSL_GetMacSecret(ssl, verify);
  20001. #endif
  20002. XMEMSET(seq, 0, SEQ_SZ);
  20003. conLen[0] = (byte)content;
  20004. c16toa((word16)sz, &conLen[ENUM_LEN]);
  20005. WriteSEQ(ssl, epochOrder, seq);
  20006. if (ssl->specs.mac_algorithm == md5_mac) {
  20007. ret = wc_InitMd5_ex(&md5, ssl->heap, ssl->devId);
  20008. if (ret != 0)
  20009. return ret;
  20010. /* inner */
  20011. ret = wc_Md5Update(&md5, macSecret, digestSz);
  20012. ret |= wc_Md5Update(&md5, PAD1, padSz);
  20013. ret |= wc_Md5Update(&md5, seq, SEQ_SZ);
  20014. ret |= wc_Md5Update(&md5, conLen, sizeof(conLen));
  20015. /* in buffer */
  20016. ret |= wc_Md5Update(&md5, in, sz);
  20017. if (ret != 0) {
  20018. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  20019. return VERIFY_MAC_ERROR;
  20020. }
  20021. ret = wc_Md5Final(&md5, result);
  20022. #ifdef WOLFSSL_ASYNC_CRYPT
  20023. /* TODO: Make non-blocking */
  20024. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  20025. ret = wc_AsyncWait(ret, &md5.asyncDev, WC_ASYNC_FLAG_NONE);
  20026. }
  20027. #endif
  20028. if (ret != 0) {
  20029. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  20030. return VERIFY_MAC_ERROR;
  20031. }
  20032. /* outer */
  20033. ret = wc_Md5Update(&md5, macSecret, digestSz);
  20034. ret |= wc_Md5Update(&md5, PAD2, padSz);
  20035. ret |= wc_Md5Update(&md5, result, digestSz);
  20036. if (ret != 0) {
  20037. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  20038. return VERIFY_MAC_ERROR;
  20039. }
  20040. ret = wc_Md5Final(&md5, digest);
  20041. #ifdef WOLFSSL_ASYNC_CRYPT
  20042. /* TODO: Make non-blocking */
  20043. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  20044. ret = wc_AsyncWait(ret, &md5.asyncDev, WC_ASYNC_FLAG_NONE);
  20045. }
  20046. #endif
  20047. if (ret != 0) {
  20048. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  20049. return VERIFY_MAC_ERROR;
  20050. }
  20051. wc_Md5Free(&md5);
  20052. }
  20053. else {
  20054. ret = wc_InitSha_ex(&sha, ssl->heap, ssl->devId);
  20055. if (ret != 0)
  20056. return ret;
  20057. /* inner */
  20058. ret = wc_ShaUpdate(&sha, macSecret, digestSz);
  20059. ret |= wc_ShaUpdate(&sha, PAD1, padSz);
  20060. ret |= wc_ShaUpdate(&sha, seq, SEQ_SZ);
  20061. ret |= wc_ShaUpdate(&sha, conLen, sizeof(conLen));
  20062. /* in buffer */
  20063. ret |= wc_ShaUpdate(&sha, in, sz);
  20064. if (ret != 0) {
  20065. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  20066. return VERIFY_MAC_ERROR;
  20067. }
  20068. ret = wc_ShaFinal(&sha, result);
  20069. #ifdef WOLFSSL_ASYNC_CRYPT
  20070. /* TODO: Make non-blocking */
  20071. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  20072. ret = wc_AsyncWait(ret, &sha.asyncDev, WC_ASYNC_FLAG_NONE);
  20073. }
  20074. #endif
  20075. if (ret != 0) {
  20076. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  20077. return VERIFY_MAC_ERROR;
  20078. }
  20079. /* outer */
  20080. ret = wc_ShaUpdate(&sha, macSecret, digestSz);
  20081. ret |= wc_ShaUpdate(&sha, PAD2, padSz);
  20082. ret |= wc_ShaUpdate(&sha, result, digestSz);
  20083. if (ret != 0) {
  20084. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  20085. return VERIFY_MAC_ERROR;
  20086. }
  20087. ret = wc_ShaFinal(&sha, digest);
  20088. #ifdef WOLFSSL_ASYNC_CRYPT
  20089. /* TODO: Make non-blocking */
  20090. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  20091. ret = wc_AsyncWait(ret, &sha.asyncDev, WC_ASYNC_FLAG_NONE);
  20092. }
  20093. #endif
  20094. if (ret != 0) {
  20095. WOLFSSL_ERROR_VERBOSE(VERIFY_MAC_ERROR);
  20096. return VERIFY_MAC_ERROR;
  20097. }
  20098. wc_ShaFree(&sha);
  20099. }
  20100. return 0;
  20101. }
  20102. #endif /* !NO_OLD_TLS && !WOLFSSL_AEAD_ONLY */
  20103. #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
  20104. static int BuildMD5_CertVerify(const WOLFSSL* ssl, byte* digest)
  20105. {
  20106. int ret;
  20107. byte md5_result[WC_MD5_DIGEST_SIZE];
  20108. #ifdef WOLFSSL_SMALL_STACK
  20109. wc_Md5* md5 = (wc_Md5*)XMALLOC(sizeof(wc_Md5), ssl->heap,
  20110. DYNAMIC_TYPE_HASHCTX);
  20111. #else
  20112. wc_Md5 md5[1];
  20113. #endif
  20114. /* make md5 inner */
  20115. ret = wc_Md5Copy(&ssl->hsHashes->hashMd5, md5); /* Save current position */
  20116. if (ret == 0)
  20117. ret = wc_Md5Update(md5, ssl->arrays->masterSecret, SECRET_LEN);
  20118. if (ret == 0)
  20119. ret = wc_Md5Update(md5, PAD1, PAD_MD5);
  20120. if (ret == 0)
  20121. ret = wc_Md5Final(md5, md5_result);
  20122. /* make md5 outer */
  20123. if (ret == 0) {
  20124. ret = wc_InitMd5_ex(md5, ssl->heap, ssl->devId);
  20125. if (ret == 0) {
  20126. ret = wc_Md5Update(md5, ssl->arrays->masterSecret, SECRET_LEN);
  20127. if (ret == 0)
  20128. ret = wc_Md5Update(md5, PAD2, PAD_MD5);
  20129. if (ret == 0)
  20130. ret = wc_Md5Update(md5, md5_result, WC_MD5_DIGEST_SIZE);
  20131. if (ret == 0)
  20132. ret = wc_Md5Final(md5, digest);
  20133. wc_Md5Free(md5);
  20134. }
  20135. }
  20136. #ifdef WOLFSSL_SMALL_STACK
  20137. XFREE(md5, ssl->heap, DYNAMIC_TYPE_HASHCTX);
  20138. #endif
  20139. return ret;
  20140. }
  20141. #endif /* !NO_MD5 && !NO_OLD_TLS */
  20142. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  20143. defined(WOLFSSL_ALLOW_TLS_SHA1))
  20144. static int BuildSHA_CertVerify(const WOLFSSL* ssl, byte* digest)
  20145. {
  20146. int ret;
  20147. byte sha_result[WC_SHA_DIGEST_SIZE];
  20148. #ifdef WOLFSSL_SMALL_STACK
  20149. wc_Sha* sha = (wc_Sha*)XMALLOC(sizeof(wc_Sha), ssl->heap,
  20150. DYNAMIC_TYPE_HASHCTX);
  20151. #else
  20152. wc_Sha sha[1];
  20153. #endif
  20154. /* make sha inner */
  20155. ret = wc_ShaCopy(&ssl->hsHashes->hashSha, sha); /* Save current position */
  20156. if (ret == 0)
  20157. ret = wc_ShaUpdate(sha, ssl->arrays->masterSecret, SECRET_LEN);
  20158. if (ret == 0)
  20159. ret = wc_ShaUpdate(sha, PAD1, PAD_SHA);
  20160. if (ret == 0)
  20161. ret = wc_ShaFinal(sha, sha_result);
  20162. /* make sha outer */
  20163. if (ret == 0) {
  20164. ret = wc_InitSha_ex(sha, ssl->heap, ssl->devId);
  20165. if (ret == 0) {
  20166. ret = wc_ShaUpdate(sha, ssl->arrays->masterSecret, SECRET_LEN);
  20167. if (ret == 0)
  20168. ret = wc_ShaUpdate(sha, PAD2, PAD_SHA);
  20169. if (ret == 0)
  20170. ret = wc_ShaUpdate(sha, sha_result, WC_SHA_DIGEST_SIZE);
  20171. if (ret == 0)
  20172. ret = wc_ShaFinal(sha, digest);
  20173. wc_ShaFree(sha);
  20174. }
  20175. }
  20176. #ifdef WOLFSSL_SMALL_STACK
  20177. XFREE(sha, ssl->heap, DYNAMIC_TYPE_HASHCTX);
  20178. #endif
  20179. return ret;
  20180. }
  20181. #endif /* !NO_SHA && (!NO_OLD_TLS || WOLFSSL_ALLOW_TLS_SHA1) */
  20182. int BuildCertHashes(const WOLFSSL* ssl, Hashes* hashes)
  20183. {
  20184. int ret = 0;
  20185. (void)hashes;
  20186. if (ssl->options.tls) {
  20187. #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
  20188. ret = wc_Md5GetHash(&ssl->hsHashes->hashMd5, hashes->md5);
  20189. if (ret != 0)
  20190. return ret;
  20191. #endif
  20192. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  20193. defined(WOLFSSL_ALLOW_TLS_SHA1))
  20194. ret = wc_ShaGetHash(&ssl->hsHashes->hashSha, hashes->sha);
  20195. if (ret != 0)
  20196. return ret;
  20197. #endif
  20198. if (IsAtLeastTLSv1_2(ssl)) {
  20199. #ifndef NO_SHA256
  20200. ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256,
  20201. hashes->sha256);
  20202. if (ret != 0)
  20203. return ret;
  20204. #endif
  20205. #ifdef WOLFSSL_SHA384
  20206. ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384,
  20207. hashes->sha384);
  20208. if (ret != 0)
  20209. return ret;
  20210. #endif
  20211. #ifdef WOLFSSL_SHA512
  20212. ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512,
  20213. hashes->sha512);
  20214. if (ret != 0)
  20215. return ret;
  20216. #endif
  20217. #ifdef WOLFSSL_SM3
  20218. ret = wc_Sm3GetHash(&ssl->hsHashes->hashSm3,
  20219. hashes->sm3);
  20220. if (ret != 0)
  20221. return ret;
  20222. #endif
  20223. }
  20224. }
  20225. else {
  20226. #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
  20227. ret = BuildMD5_CertVerify(ssl, hashes->md5);
  20228. if (ret != 0)
  20229. return ret;
  20230. #endif
  20231. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  20232. defined(WOLFSSL_ALLOW_TLS_SHA1))
  20233. ret = BuildSHA_CertVerify(ssl, hashes->sha);
  20234. if (ret != 0)
  20235. return ret;
  20236. #endif
  20237. }
  20238. return ret;
  20239. }
  20240. #ifndef WOLFSSL_NO_TLS12
  20241. void FreeBuildMsgArgs(WOLFSSL* ssl, BuildMsgArgs* args)
  20242. {
  20243. (void)ssl;
  20244. if (args
  20245. #ifdef WOLFSSL_ASYNC_CRYPT
  20246. && ssl->options.buildArgsSet
  20247. #endif
  20248. ) {
  20249. /* only free the IV if it was dynamically allocated */
  20250. if (args->iv && (args->iv != args->staticIvBuffer)) {
  20251. XFREE(args->iv, ssl->heap, DYNAMIC_TYPE_SALT);
  20252. }
  20253. }
  20254. #ifdef WOLFSSL_ASYNC_CRYPT
  20255. ssl->options.buildArgsSet = 0;
  20256. #endif
  20257. }
  20258. #endif
  20259. /* Build SSL Message, encrypted */
  20260. int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input,
  20261. int inSz, int type, int hashOutput, int sizeOnly, int asyncOkay,
  20262. int epochOrder)
  20263. {
  20264. #ifndef WOLFSSL_NO_TLS12
  20265. int ret;
  20266. BuildMsgArgs* args;
  20267. BuildMsgArgs lcl_args;
  20268. #endif
  20269. WOLFSSL_ENTER("BuildMessage");
  20270. if (ssl == NULL) {
  20271. return BAD_FUNC_ARG;
  20272. }
  20273. /* catch mistaken sizeOnly parameter */
  20274. if (!sizeOnly && (output == NULL || input == NULL) ) {
  20275. return BAD_FUNC_ARG;
  20276. }
  20277. if (sizeOnly && (output || input) ) {
  20278. return BAD_FUNC_ARG;
  20279. }
  20280. (void)epochOrder;
  20281. #ifndef NO_TLS
  20282. #if defined(WOLFSSL_NO_TLS12) && defined(WOLFSSL_TLS13)
  20283. return BuildTls13Message(ssl, output, outSz, input, inSz, type,
  20284. hashOutput, sizeOnly, asyncOkay);
  20285. #else
  20286. #ifdef WOLFSSL_TLS13
  20287. if (ssl->options.tls1_3) {
  20288. return BuildTls13Message(ssl, output, outSz, input, inSz, type,
  20289. hashOutput, sizeOnly, asyncOkay);
  20290. }
  20291. #endif
  20292. #ifdef WOLFSSL_ASYNC_CRYPT
  20293. ret = WC_NO_PENDING_E;
  20294. if (asyncOkay) {
  20295. if (ssl->async == NULL) {
  20296. return BAD_FUNC_ARG;
  20297. }
  20298. args = &ssl->async->buildArgs;
  20299. ret = wolfSSL_AsyncPop(ssl, &ssl->options.buildMsgState);
  20300. if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
  20301. /* Check for error */
  20302. if (ret < 0)
  20303. goto exit_buildmsg;
  20304. }
  20305. }
  20306. else
  20307. #endif
  20308. {
  20309. args = &lcl_args;
  20310. }
  20311. /* Reset state */
  20312. #ifdef WOLFSSL_ASYNC_CRYPT
  20313. if (ret == WC_NO_ERR_TRACE(WC_NO_PENDING_E))
  20314. #endif
  20315. {
  20316. ret = 0;
  20317. #ifdef WOLFSSL_ASYNC_CRYPT
  20318. ssl->options.buildArgsSet = 1;
  20319. #endif
  20320. ssl->options.buildMsgState = BUILD_MSG_BEGIN;
  20321. XMEMSET(args, 0, sizeof(BuildMsgArgs));
  20322. args->sz = RECORD_HEADER_SZ + (word32)inSz;
  20323. args->idx = RECORD_HEADER_SZ;
  20324. args->headerSz = RECORD_HEADER_SZ;
  20325. }
  20326. switch (ssl->options.buildMsgState) {
  20327. case BUILD_MSG_BEGIN:
  20328. {
  20329. #if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION)
  20330. if (ssl->options.dtls && DtlsSCRKeysSet(ssl)) {
  20331. /* For epochs >1 the current cipher parameters are located in
  20332. * ssl->secure_renegotiation->tmp_keys. Previous cipher
  20333. * parameters and for epoch 1 use ssl->keys */
  20334. switch (epochOrder) {
  20335. case PREV_ORDER:
  20336. if (ssl->encrypt.src != KEYS) {
  20337. ssl->secure_renegotiation->cache_status =
  20338. SCR_CACHE_NULL;
  20339. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  20340. ERROR_OUT(ret, exit_buildmsg);
  20341. }
  20342. break;
  20343. case CUR_ORDER:
  20344. if (ssl->keys.dtls_epoch ==
  20345. ssl->secure_renegotiation->tmp_keys.dtls_epoch) {
  20346. if (ssl->encrypt.src != SCR) {
  20347. ssl->secure_renegotiation->cache_status =
  20348. SCR_CACHE_NEEDED;
  20349. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY))
  20350. != 0)
  20351. ERROR_OUT(ret, exit_buildmsg);
  20352. }
  20353. }
  20354. else {
  20355. if (ssl->encrypt.src != KEYS) {
  20356. ssl->secure_renegotiation->cache_status =
  20357. SCR_CACHE_NULL;
  20358. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY))
  20359. != 0)
  20360. ERROR_OUT(ret, exit_buildmsg);
  20361. }
  20362. }
  20363. break;
  20364. default:
  20365. WOLFSSL_MSG("BuildMessage only supports PREV_ORDER and "
  20366. "CUR_ORDER");
  20367. ERROR_OUT(BAD_FUNC_ARG, exit_buildmsg);
  20368. }
  20369. }
  20370. #endif
  20371. ssl->options.buildMsgState = BUILD_MSG_SIZE;
  20372. }
  20373. FALL_THROUGH;
  20374. case BUILD_MSG_SIZE:
  20375. {
  20376. args->digestSz = ssl->specs.hash_size;
  20377. #ifdef HAVE_TRUNCATED_HMAC
  20378. if (ssl->truncated_hmac)
  20379. args->digestSz = min(TRUNCATED_HMAC_SZ, args->digestSz);
  20380. #endif
  20381. args->sz += args->digestSz;
  20382. #ifdef WOLFSSL_DTLS
  20383. if (ssl->options.dtls) {
  20384. args->sz += DTLS_RECORD_EXTRA;
  20385. args->idx += DTLS_RECORD_EXTRA;
  20386. args->headerSz += DTLS_RECORD_EXTRA;
  20387. }
  20388. #endif
  20389. #ifndef WOLFSSL_AEAD_ONLY
  20390. if (ssl->specs.cipher_type == block) {
  20391. word32 blockSz = ssl->specs.block_size;
  20392. if (blockSz == 0) {
  20393. WOLFSSL_MSG("Invalid block size with block cipher type");
  20394. ERROR_OUT(BAD_STATE_E, exit_buildmsg);
  20395. }
  20396. if (ssl->options.tls1_1) {
  20397. args->ivSz = blockSz;
  20398. args->sz += args->ivSz;
  20399. if (args->ivSz > MAX_IV_SZ)
  20400. ERROR_OUT(BUFFER_E, exit_buildmsg);
  20401. }
  20402. args->sz += 1; /* pad byte */
  20403. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  20404. if (ssl->options.startedETMWrite) {
  20405. args->pad = (args->sz - args->headerSz -
  20406. args->digestSz) % blockSz;
  20407. }
  20408. else
  20409. #endif
  20410. {
  20411. args->pad = (args->sz - args->headerSz) % blockSz;
  20412. }
  20413. if (args->pad != 0)
  20414. args->pad = blockSz - args->pad;
  20415. args->sz += args->pad;
  20416. }
  20417. #endif /* WOLFSSL_AEAD_ONLY */
  20418. #ifdef HAVE_AEAD
  20419. if (ssl->specs.cipher_type == aead) {
  20420. if (ssl->specs.bulk_cipher_algorithm != wolfssl_chacha)
  20421. args->ivSz = AESGCM_EXP_IV_SZ;
  20422. args->sz += (args->ivSz + ssl->specs.aead_mac_size - args->digestSz);
  20423. }
  20424. #endif
  20425. /* done with size calculations */
  20426. if (sizeOnly)
  20427. goto exit_buildmsg;
  20428. if (args->sz > (word32)outSz) {
  20429. WOLFSSL_MSG("Oops, want to write past output buffer size");
  20430. ERROR_OUT(BUFFER_E, exit_buildmsg);
  20431. }
  20432. if (args->ivSz > 0) {
  20433. if (args->ivSz > sizeof(args->staticIvBuffer)) {
  20434. args->iv = (byte*)XMALLOC(args->ivSz, ssl->heap,
  20435. DYNAMIC_TYPE_SALT);
  20436. if (args->iv == NULL) {
  20437. ERROR_OUT(MEMORY_E, exit_buildmsg);
  20438. }
  20439. }
  20440. else {
  20441. args->iv = args->staticIvBuffer;
  20442. }
  20443. ret = wc_RNG_GenerateBlock(ssl->rng, args->iv, args->ivSz);
  20444. if (ret != 0)
  20445. goto exit_buildmsg;
  20446. }
  20447. #if !defined(NO_PUBLIC_GCM_SET_IV) && \
  20448. ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
  20449. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)) && \
  20450. defined(HAVE_AEAD))
  20451. if (ssl->specs.cipher_type == aead) {
  20452. if (ssl->specs.bulk_cipher_algorithm != wolfssl_chacha)
  20453. XMEMCPY(args->iv, ssl->keys.aead_exp_IV, AESGCM_EXP_IV_SZ);
  20454. }
  20455. #endif
  20456. args->size = (word16)(args->sz - args->headerSz); /* include mac and digest */
  20457. AddRecordHeader(output, args->size, (byte)type, ssl, epochOrder);
  20458. /* write to output */
  20459. if (args->ivSz > 0) {
  20460. XMEMCPY(output + args->idx, args->iv,
  20461. min(args->ivSz, MAX_IV_SZ));
  20462. args->idx += min(args->ivSz, MAX_IV_SZ);
  20463. }
  20464. XMEMCPY(output + args->idx, input, inSz);
  20465. args->idx += (word32)inSz;
  20466. ssl->options.buildMsgState = BUILD_MSG_HASH;
  20467. }
  20468. FALL_THROUGH;
  20469. case BUILD_MSG_HASH:
  20470. {
  20471. /* done with size calculations */
  20472. if (sizeOnly)
  20473. goto exit_buildmsg;
  20474. if (type == handshake && hashOutput) {
  20475. ret = HashOutput(ssl, output,
  20476. (int)(args->headerSz + (word32)inSz), (int)args->ivSz);
  20477. if (ret != 0)
  20478. goto exit_buildmsg;
  20479. }
  20480. #ifndef WOLFSSL_AEAD_ONLY
  20481. if (ssl->specs.cipher_type == block) {
  20482. word32 tmpIdx;
  20483. word32 i;
  20484. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  20485. if (ssl->options.startedETMWrite)
  20486. tmpIdx = args->idx;
  20487. else
  20488. #endif
  20489. tmpIdx = args->idx + args->digestSz;
  20490. for (i = 0; i <= args->pad; i++)
  20491. output[tmpIdx++] = (byte)args->pad; /* pad byte gets pad value */
  20492. }
  20493. #endif
  20494. ssl->options.buildMsgState = BUILD_MSG_VERIFY_MAC;
  20495. }
  20496. FALL_THROUGH;
  20497. case BUILD_MSG_VERIFY_MAC:
  20498. {
  20499. /* done with size calculations */
  20500. if (sizeOnly)
  20501. goto exit_buildmsg;
  20502. /* User Record Layer Callback handling */
  20503. #ifdef ATOMIC_USER
  20504. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  20505. if (ssl->options.startedETMWrite) {
  20506. if (ssl->ctx->EncryptMacCb) {
  20507. ret = ssl->ctx->EncryptMacCb(ssl, output + args->idx +
  20508. args->pad + 1, type, 0,
  20509. output + args->headerSz,
  20510. output + args->headerSz,
  20511. args->size - args->digestSz,
  20512. ssl->MacEncryptCtx);
  20513. goto exit_buildmsg;
  20514. }
  20515. }
  20516. else
  20517. #endif
  20518. {
  20519. if (ssl->ctx->MacEncryptCb) {
  20520. ret = ssl->ctx->MacEncryptCb(ssl, output + args->idx,
  20521. output + args->headerSz + args->ivSz, (unsigned int)inSz,
  20522. type, 0, output + args->headerSz,
  20523. output + args->headerSz, args->size,
  20524. ssl->MacEncryptCtx);
  20525. goto exit_buildmsg;
  20526. }
  20527. }
  20528. #endif
  20529. #ifndef WOLFSSL_AEAD_ONLY
  20530. if (ssl->specs.cipher_type != aead
  20531. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  20532. && !ssl->options.startedETMWrite
  20533. #endif
  20534. ) {
  20535. #ifdef HAVE_TRUNCATED_HMAC
  20536. if (ssl->truncated_hmac &&
  20537. ssl->specs.hash_size > args->digestSz) {
  20538. #ifdef WOLFSSL_SMALL_STACK
  20539. byte* hmac;
  20540. #else
  20541. byte hmac[WC_MAX_DIGEST_SIZE];
  20542. #endif
  20543. #ifdef WOLFSSL_SMALL_STACK
  20544. hmac = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, ssl->heap,
  20545. DYNAMIC_TYPE_DIGEST);
  20546. if (hmac == NULL)
  20547. ERROR_OUT(MEMORY_E, exit_buildmsg);
  20548. #endif
  20549. ret = ssl->hmac(ssl, hmac,
  20550. output + args->headerSz + args->ivSz, (word32)inSz,
  20551. -1, type, 0, epochOrder);
  20552. XMEMCPY(output + args->idx, hmac, args->digestSz);
  20553. #ifdef WOLFSSL_SMALL_STACK
  20554. XFREE(hmac, ssl->heap, DYNAMIC_TYPE_DIGEST);
  20555. #endif
  20556. }
  20557. else
  20558. #endif
  20559. {
  20560. ret = ssl->hmac(ssl, output + args->idx, output +
  20561. args->headerSz + args->ivSz, (word32)inSz, -1, type, 0, epochOrder);
  20562. }
  20563. }
  20564. #endif /* WOLFSSL_AEAD_ONLY */
  20565. if (ret != 0)
  20566. goto exit_buildmsg;
  20567. ssl->options.buildMsgState = BUILD_MSG_ENCRYPT;
  20568. }
  20569. FALL_THROUGH;
  20570. case BUILD_MSG_ENCRYPT:
  20571. {
  20572. /* done with size calculations */
  20573. if (sizeOnly)
  20574. goto exit_buildmsg;
  20575. {
  20576. #if defined(HAVE_SECURE_RENEGOTIATION) && defined(WOLFSSL_DTLS)
  20577. /* If we want the PREV_ORDER then modify CUR_ORDER sequence number
  20578. * for all encryption algos that use it for encryption parameters */
  20579. word16 dtls_epoch = 0;
  20580. word16 dtls_sequence_number_hi = 0;
  20581. word32 dtls_sequence_number_lo = 0;
  20582. int swap_seq = ssl->options.dtls && epochOrder == PREV_ORDER &&
  20583. DtlsUseSCRKeys(ssl);
  20584. if (swap_seq) {
  20585. dtls_epoch = ssl->keys.dtls_epoch;
  20586. dtls_sequence_number_hi = ssl->keys.dtls_sequence_number_hi;
  20587. dtls_sequence_number_lo = ssl->keys.dtls_sequence_number_lo;
  20588. ssl->keys.dtls_epoch--;
  20589. ssl->keys.dtls_sequence_number_hi =
  20590. ssl->keys.dtls_prev_sequence_number_hi;
  20591. ssl->keys.dtls_sequence_number_lo =
  20592. ssl->keys.dtls_prev_sequence_number_lo;
  20593. }
  20594. #endif
  20595. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  20596. if (ssl->options.startedETMWrite) {
  20597. ret = Encrypt(ssl, output + args->headerSz,
  20598. output + args->headerSz,
  20599. (word16)(args->size - args->digestSz),
  20600. asyncOkay);
  20601. }
  20602. else
  20603. #endif
  20604. {
  20605. ret = Encrypt(ssl, output + args->headerSz,
  20606. output + args->headerSz, args->size, asyncOkay);
  20607. }
  20608. #if defined(HAVE_SECURE_RENEGOTIATION) && defined(WOLFSSL_DTLS)
  20609. /* Restore sequence numbers */
  20610. if (swap_seq) {
  20611. ssl->keys.dtls_epoch = dtls_epoch;
  20612. ssl->keys.dtls_sequence_number_hi = dtls_sequence_number_hi;
  20613. ssl->keys.dtls_sequence_number_lo = dtls_sequence_number_lo;
  20614. }
  20615. #endif
  20616. }
  20617. if (ret != 0) {
  20618. #ifdef WOLFSSL_ASYNC_CRYPT
  20619. if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
  20620. #endif
  20621. {
  20622. /* Zeroize plaintext. */
  20623. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  20624. if (ssl->options.startedETMWrite) {
  20625. ForceZero(output + args->headerSz,
  20626. (word16)(args->size - args->digestSz));
  20627. }
  20628. else
  20629. #endif
  20630. {
  20631. ForceZero(output + args->headerSz, (word16)args->size);
  20632. }
  20633. }
  20634. goto exit_buildmsg;
  20635. }
  20636. ssl->options.buildMsgState = BUILD_MSG_ENCRYPTED_VERIFY_MAC;
  20637. }
  20638. FALL_THROUGH;
  20639. case BUILD_MSG_ENCRYPTED_VERIFY_MAC:
  20640. {
  20641. /* done with size calculations */
  20642. if (sizeOnly)
  20643. goto exit_buildmsg;
  20644. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  20645. if (ssl->options.startedETMWrite) {
  20646. WOLFSSL_MSG("Calculate MAC of Encrypted Data");
  20647. #ifdef HAVE_TRUNCATED_HMAC
  20648. if (ssl->truncated_hmac &&
  20649. ssl->specs.hash_size > args->digestSz) {
  20650. #ifdef WOLFSSL_SMALL_STACK
  20651. byte* hmac = NULL;
  20652. #else
  20653. byte hmac[WC_MAX_DIGEST_SIZE];
  20654. #endif
  20655. #ifdef WOLFSSL_SMALL_STACK
  20656. hmac = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, ssl->heap,
  20657. DYNAMIC_TYPE_DIGEST);
  20658. if (hmac == NULL)
  20659. ERROR_OUT(MEMORY_E, exit_buildmsg);
  20660. #endif
  20661. ret = ssl->hmac(ssl, hmac, output + args->headerSz,
  20662. args->ivSz + inSz + args->pad + 1, -1, type,
  20663. 0, epochOrder);
  20664. XMEMCPY(output + args->idx + args->pad + 1, hmac,
  20665. args->digestSz);
  20666. #ifdef WOLFSSL_SMALL_STACK
  20667. XFREE(hmac, ssl->heap, DYNAMIC_TYPE_DIGEST);
  20668. #endif
  20669. }
  20670. else
  20671. #endif
  20672. {
  20673. ret = ssl->hmac(ssl, output + args->idx + args->pad + 1,
  20674. output + args->headerSz,
  20675. args->ivSz + (word32)inSz + args->pad + 1,
  20676. -1, type,
  20677. 0, epochOrder);
  20678. }
  20679. }
  20680. #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */
  20681. }
  20682. FALL_THROUGH;
  20683. default:
  20684. break;
  20685. }
  20686. exit_buildmsg:
  20687. WOLFSSL_LEAVE("BuildMessage", ret);
  20688. #ifdef WOLFSSL_ASYNC_CRYPT
  20689. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  20690. return ret;
  20691. }
  20692. #endif
  20693. /* make sure build message state is reset */
  20694. ssl->options.buildMsgState = BUILD_MSG_BEGIN;
  20695. #ifdef WOLFSSL_DTLS
  20696. if (ret == 0 && ssl->options.dtls && !sizeOnly)
  20697. DtlsSEQIncrement(ssl, epochOrder);
  20698. #endif
  20699. /* return sz on success */
  20700. if (ret == 0) {
  20701. ret = (int)args->sz;
  20702. }
  20703. else {
  20704. WOLFSSL_ERROR_VERBOSE(ret);
  20705. }
  20706. /* Final cleanup */
  20707. FreeBuildMsgArgs(ssl, args);
  20708. return ret;
  20709. #endif /* !WOLFSSL_NO_TLS12 */
  20710. #else
  20711. (void)outSz;
  20712. (void)inSz;
  20713. (void)type;
  20714. (void)hashOutput;
  20715. (void)asyncOkay;
  20716. return NOT_COMPILED_IN;
  20717. #endif /* NO_TLS */
  20718. }
  20719. #ifndef WOLFSSL_NO_TLS12
  20720. int SendFinished(WOLFSSL* ssl)
  20721. {
  20722. int sendSz,
  20723. finishedSz = ssl->options.tls ? TLS_FINISHED_SZ :
  20724. FINISHED_SZ;
  20725. byte input[FINISHED_SZ + DTLS_HANDSHAKE_HEADER_SZ]; /* max */
  20726. byte *output;
  20727. Hashes* hashes;
  20728. int ret;
  20729. int headerSz = HANDSHAKE_HEADER_SZ;
  20730. int outputSz;
  20731. WOLFSSL_START(WC_FUNC_FINISHED_SEND);
  20732. WOLFSSL_ENTER("SendFinished");
  20733. /* check for available size */
  20734. outputSz = sizeof(input) + MAX_MSG_EXTRA;
  20735. /* Set this in case CheckAvailableSize returns a WANT_WRITE so that state
  20736. * is not advanced yet */
  20737. ssl->options.buildingMsg = 1;
  20738. if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
  20739. return ret;
  20740. #ifdef WOLFSSL_DTLS
  20741. if (ssl->options.dtls) {
  20742. headerSz += DTLS_HANDSHAKE_EXTRA;
  20743. ssl->keys.dtls_epoch++;
  20744. ssl->keys.dtls_prev_sequence_number_hi =
  20745. ssl->keys.dtls_sequence_number_hi;
  20746. ssl->keys.dtls_prev_sequence_number_lo =
  20747. ssl->keys.dtls_sequence_number_lo;
  20748. ssl->keys.dtls_sequence_number_hi = 0;
  20749. ssl->keys.dtls_sequence_number_lo = 0;
  20750. }
  20751. #endif
  20752. /* get output buffer */
  20753. output = GetOutputBuffer(ssl);
  20754. AddHandShakeHeader(input, (word32)finishedSz, 0,
  20755. (word32)finishedSz, finished, ssl);
  20756. /* make finished hashes */
  20757. hashes = (Hashes*)&input[headerSz];
  20758. ret = BuildFinished(ssl, hashes, ssl->options.side == WOLFSSL_CLIENT_END ?
  20759. kTlsClientStr : kTlsServerStr);
  20760. if (ret != 0) return ret;
  20761. #ifdef HAVE_SECURE_RENEGOTIATION
  20762. if (ssl->secure_renegotiation) {
  20763. if (ssl->options.side == WOLFSSL_CLIENT_END)
  20764. XMEMCPY(ssl->secure_renegotiation->client_verify_data, hashes,
  20765. TLS_FINISHED_SZ);
  20766. else
  20767. XMEMCPY(ssl->secure_renegotiation->server_verify_data, hashes,
  20768. TLS_FINISHED_SZ);
  20769. }
  20770. #endif
  20771. #ifdef WOLFSSL_HAVE_TLS_UNIQUE
  20772. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  20773. XMEMCPY(ssl->clientFinished,
  20774. hashes, TLS_FINISHED_SZ);
  20775. ssl->clientFinished_len = TLS_FINISHED_SZ;
  20776. }
  20777. else {
  20778. XMEMCPY(ssl->serverFinished,
  20779. hashes, TLS_FINISHED_SZ);
  20780. ssl->serverFinished_len = TLS_FINISHED_SZ;
  20781. }
  20782. #endif
  20783. #ifdef WOLFSSL_DTLS
  20784. if (IsDtlsNotSctpMode(ssl)) {
  20785. if ((ret = DtlsMsgPoolSave(ssl, input, headerSz + finishedSz,
  20786. finished)) != 0) {
  20787. return ret;
  20788. }
  20789. }
  20790. #endif
  20791. sendSz = BuildMessage(ssl, output, outputSz, input, headerSz + finishedSz,
  20792. handshake, 1, 0, 0, CUR_ORDER);
  20793. if (sendSz < 0)
  20794. return BUILD_MSG_ERROR;
  20795. if (!ssl->options.resuming) {
  20796. SetupSession(ssl);
  20797. #ifndef NO_SESSION_CACHE
  20798. AddSession(ssl);
  20799. #endif
  20800. if (ssl->options.side == WOLFSSL_SERVER_END) {
  20801. #ifdef OPENSSL_EXTRA
  20802. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  20803. ssl->cbmode = SSL_CB_MODE_WRITE;
  20804. if (ssl->CBIS != NULL)
  20805. ssl->CBIS(ssl, SSL_CB_HANDSHAKE_DONE, WOLFSSL_SUCCESS);
  20806. #endif
  20807. ssl->options.handShakeState = HANDSHAKE_DONE;
  20808. ssl->options.handShakeDone = 1;
  20809. #ifdef HAVE_SECURE_RENEGOTIATION
  20810. ssl->options.resumed = ssl->options.resuming;
  20811. #endif
  20812. }
  20813. }
  20814. else {
  20815. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  20816. #ifdef OPENSSL_EXTRA
  20817. ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
  20818. ssl->cbmode = SSL_CB_MODE_WRITE;
  20819. if (ssl->CBIS != NULL)
  20820. ssl->CBIS(ssl, SSL_CB_HANDSHAKE_DONE, WOLFSSL_SUCCESS);
  20821. #endif
  20822. ssl->options.handShakeState = HANDSHAKE_DONE;
  20823. ssl->options.handShakeDone = 1;
  20824. #ifdef HAVE_SECURE_RENEGOTIATION
  20825. ssl->options.resumed = ssl->options.resuming;
  20826. #endif
  20827. }
  20828. }
  20829. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  20830. if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
  20831. if (ssl->toInfoOn) {
  20832. ret = AddPacketInfo(ssl, "Finished", handshake, output, sendSz,
  20833. WRITE_PROTO, 0, ssl->heap);
  20834. if (ret != 0)
  20835. return ret;
  20836. }
  20837. #endif
  20838. ssl->buffers.outputBuffer.length += (word32)sendSz;
  20839. ret = SendBuffered(ssl);
  20840. ssl->options.buildingMsg = 0;
  20841. #ifdef WOLFSSL_DTLS
  20842. if ((!ssl->options.resuming &&
  20843. ssl->options.side == WOLFSSL_SERVER_END) ||
  20844. (ssl->options.resuming &&
  20845. ssl->options.side == WOLFSSL_CLIENT_END)) {
  20846. ssl->keys.dtls_handshake_number = 0;
  20847. ssl->keys.dtls_expected_peer_handshake_number = 0;
  20848. }
  20849. #endif
  20850. WOLFSSL_LEAVE("SendFinished", ret);
  20851. WOLFSSL_END(WC_FUNC_FINISHED_SEND);
  20852. return ret;
  20853. }
  20854. #endif /* WOLFSSL_NO_TLS12 */
  20855. #ifndef NO_WOLFSSL_SERVER
  20856. #if (!defined(WOLFSSL_NO_TLS12) && \
  20857. (defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
  20858. defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))) || \
  20859. (defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST))
  20860. /* Parses and decodes the certificate then initializes "request". In the case
  20861. * of !ssl->buffers.weOwnCert, ssl->ctx->certOcspRequest gets set to "request".
  20862. *
  20863. * Returns 0 on success
  20864. */
  20865. static int CreateOcspRequest(WOLFSSL* ssl, OcspRequest* request,
  20866. DecodedCert* cert, byte* certData, word32 length,
  20867. byte *ctxOwnsRequest)
  20868. {
  20869. int ret;
  20870. if (request != NULL)
  20871. XMEMSET(request, 0, sizeof(OcspRequest));
  20872. if (ctxOwnsRequest!= NULL)
  20873. *ctxOwnsRequest = 0;
  20874. InitDecodedCert(cert, certData, length, ssl->heap);
  20875. /* TODO: Setup async support here */
  20876. ret = ParseCertRelative(cert, CERT_TYPE, VERIFY, SSL_CM(ssl), NULL);
  20877. if (ret != 0) {
  20878. WOLFSSL_MSG("ParseCert failed");
  20879. }
  20880. if (ret == 0)
  20881. ret = InitOcspRequest(request, cert, 0, ssl->heap);
  20882. if (ret == 0) {
  20883. /* make sure ctx OCSP request is updated */
  20884. if (!ssl->buffers.weOwnCert) {
  20885. wolfSSL_Mutex* ocspLock = &SSL_CM(ssl)->ocsp_stapling->ocspLock;
  20886. if (wc_LockMutex(ocspLock) == 0) {
  20887. if (ssl->ctx->certOcspRequest == NULL) {
  20888. ssl->ctx->certOcspRequest = request;
  20889. if (ctxOwnsRequest!= NULL)
  20890. *ctxOwnsRequest = 1;
  20891. }
  20892. wc_UnLockMutex(ocspLock);
  20893. }
  20894. }
  20895. }
  20896. FreeDecodedCert(cert);
  20897. return ret;
  20898. }
  20899. /* Creates OCSP response and places it in variable "response". Memory
  20900. * management for "buffer* response" is up to the caller.
  20901. *
  20902. * Also creates an OcspRequest in the case that ocspRequest is null or that
  20903. * ssl->buffers.weOwnCert is set. In those cases managing ocspRequest free'ing
  20904. * is up to the caller. NOTE: in OcspCreateRequest ssl->ctx->certOcspRequest can
  20905. * be set to point to "ocspRequest" and it then should not be free'd since
  20906. * wolfSSL_CTX_free will take care of it.
  20907. *
  20908. * Returns 0 on success
  20909. */
  20910. int CreateOcspResponse(WOLFSSL* ssl, OcspRequest** ocspRequest,
  20911. buffer* response)
  20912. {
  20913. int ret = 0;
  20914. OcspRequest* request = NULL;
  20915. byte createdRequest = 0;
  20916. byte ctxOwnsRequest = 0;
  20917. if (ssl == NULL || ocspRequest == NULL || response == NULL)
  20918. return BAD_FUNC_ARG;
  20919. XMEMSET(response, 0, sizeof(*response));
  20920. request = *ocspRequest;
  20921. /* unable to fetch status. skip. */
  20922. if (SSL_CM(ssl) == NULL || SSL_CM(ssl)->ocspStaplingEnabled == 0)
  20923. return 0;
  20924. if (request == NULL || ssl->buffers.weOwnCert) {
  20925. DerBuffer* der = ssl->buffers.certificate;
  20926. #ifdef WOLFSSL_SMALL_STACK
  20927. DecodedCert* cert = NULL;
  20928. #else
  20929. DecodedCert cert[1];
  20930. #endif
  20931. /* unable to fetch status. skip. */
  20932. if (der->buffer == NULL || der->length == 0)
  20933. return 0;
  20934. #ifdef WOLFSSL_SMALL_STACK
  20935. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
  20936. DYNAMIC_TYPE_DCERT);
  20937. if (cert == NULL)
  20938. return MEMORY_E;
  20939. #endif
  20940. request = (OcspRequest*)XMALLOC(sizeof(OcspRequest), ssl->heap,
  20941. DYNAMIC_TYPE_OCSP_REQUEST);
  20942. if (request == NULL)
  20943. ret = MEMORY_E;
  20944. createdRequest = 1;
  20945. if (ret == 0) {
  20946. ret = CreateOcspRequest(ssl, request, cert, der->buffer,
  20947. der->length, &ctxOwnsRequest);
  20948. }
  20949. if (ret != 0) {
  20950. XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  20951. request = NULL;
  20952. }
  20953. #ifdef WOLFSSL_SMALL_STACK
  20954. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  20955. #endif
  20956. }
  20957. if (ret == 0) {
  20958. request->ssl = ssl;
  20959. ret = CheckOcspRequest(SSL_CM(ssl)->ocsp_stapling, request, response,
  20960. ssl->heap);
  20961. /* Suppressing, not critical */
  20962. if (ret == WC_NO_ERR_TRACE(OCSP_CERT_REVOKED) ||
  20963. ret == WC_NO_ERR_TRACE(OCSP_CERT_UNKNOWN) ||
  20964. ret == WC_NO_ERR_TRACE(OCSP_LOOKUP_FAIL)) {
  20965. ret = 0;
  20966. }
  20967. }
  20968. /* free request up if error case found otherwise return it */
  20969. if (ret != 0 && createdRequest && !ctxOwnsRequest) {
  20970. FreeOcspRequest(request);
  20971. XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  20972. }
  20973. if (ret == 0)
  20974. *ocspRequest = request;
  20975. return ret;
  20976. }
  20977. #endif
  20978. #endif /* !NO_WOLFSSL_SERVER */
  20979. int cipherExtraData(WOLFSSL* ssl)
  20980. {
  20981. int cipherExtra;
  20982. /* Cipher data that may be added by BuildMessage */
  20983. /* There is always an IV (expect for chacha). For AEAD ciphers,
  20984. * there is the authentication tag (aead_mac_size). For block
  20985. * ciphers we have the hash_size MAC on the message, and one
  20986. * block size for possible padding. */
  20987. if (ssl->specs.cipher_type == aead) {
  20988. cipherExtra = ssl->specs.aead_mac_size;
  20989. /* CHACHA does not have an explicit IV. */
  20990. if (ssl->specs.bulk_cipher_algorithm != wolfssl_chacha) {
  20991. cipherExtra += AESGCM_EXP_IV_SZ;
  20992. }
  20993. }
  20994. else {
  20995. cipherExtra = ssl->specs.iv_size + ssl->specs.block_size +
  20996. ssl->specs.hash_size;
  20997. }
  20998. /* Sanity check so we don't ever return negative. */
  20999. return cipherExtra > 0 ? cipherExtra : 0;
  21000. }
  21001. #ifndef WOLFSSL_NO_TLS12
  21002. #ifndef NO_CERTS
  21003. #if !defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  21004. /* handle generation of certificate (11) */
  21005. int SendCertificate(WOLFSSL* ssl)
  21006. {
  21007. int ret = 0;
  21008. word32 certSz, certChainSz, headerSz, listSz, payloadSz;
  21009. word32 length, maxFragment;
  21010. #ifdef HAVE_RPK
  21011. int usingRpkTls12 = 0;
  21012. #endif /* HAVE_RPK */
  21013. WOLFSSL_START(WC_FUNC_CERTIFICATE_SEND);
  21014. WOLFSSL_ENTER("SendCertificate");
  21015. if (ssl->options.usingPSK_cipher || ssl->options.usingAnon_cipher) {
  21016. WOLFSSL_MSG("Not sending certificate msg. Using PSK or ANON cipher.");
  21017. return 0; /* not needed */
  21018. }
  21019. #ifdef HAVE_RPK
  21020. if (!IsAtLeastTLSv1_3(ssl->version)) {
  21021. /* If this is (D)TLS1.2 and RPK, then single cert, not list. */
  21022. if (ssl->options.side == WOLFSSL_SERVER_END) {
  21023. if (ssl->options.rpkState.sending_ServerCertTypeCnt == 1 &&
  21024. ssl->options.rpkState.sending_ServerCertTypes[0] == WOLFSSL_CERT_TYPE_RPK)
  21025. usingRpkTls12 = 1;
  21026. } else if (ssl->options.side == WOLFSSL_CLIENT_END) {
  21027. if (ssl->options.rpkState.sending_ClientCertTypeCnt == 1 &&
  21028. ssl->options.rpkState.sending_ClientCertTypes[0] == WOLFSSL_CERT_TYPE_RPK)
  21029. usingRpkTls12 = 1;
  21030. }
  21031. }
  21032. #endif /* HAVE_RPK */
  21033. if (ssl->options.sendVerify == SEND_BLANK_CERT) {
  21034. #ifdef OPENSSL_EXTRA
  21035. if (ssl->version.major == SSLv3_MAJOR
  21036. && ssl->version.minor == SSLv3_MINOR){
  21037. return SendAlert(ssl, alert_warning, no_certificate);
  21038. } else {
  21039. #endif
  21040. certSz = 0;
  21041. certChainSz = 0;
  21042. headerSz = CERT_HEADER_SZ;
  21043. length = CERT_HEADER_SZ;
  21044. listSz = 0;
  21045. #ifdef OPENSSL_EXTRA
  21046. }
  21047. #endif
  21048. }
  21049. else {
  21050. if (!ssl->buffers.certificate) {
  21051. WOLFSSL_MSG("Send Cert missing certificate buffer");
  21052. return BUFFER_ERROR;
  21053. }
  21054. certSz = ssl->buffers.certificate->length;
  21055. #ifdef HAVE_RPK
  21056. if (usingRpkTls12) {
  21057. headerSz = 1 * CERT_HEADER_SZ;
  21058. listSz = certSz;
  21059. } else {
  21060. #endif /* HAVE_RPK */
  21061. headerSz = 2 * CERT_HEADER_SZ;
  21062. listSz = certSz + CERT_HEADER_SZ;
  21063. #ifdef HAVE_RPK
  21064. }
  21065. #endif /* HAVE_RPK */
  21066. /* list + cert size */
  21067. length = certSz + headerSz;
  21068. /* may need to send rest of chain, already has leading size(s) */
  21069. if (certSz && ssl->buffers.certChain) {
  21070. certChainSz = ssl->buffers.certChain->length;
  21071. length += certChainSz;
  21072. listSz += certChainSz;
  21073. }
  21074. else
  21075. certChainSz = 0;
  21076. }
  21077. payloadSz = length;
  21078. if (ssl->fragOffset != 0)
  21079. length -= (ssl->fragOffset + headerSz);
  21080. maxFragment = MAX_RECORD_SIZE;
  21081. maxFragment = (word32)wolfSSL_GetMaxFragSize(ssl, (int)maxFragment);
  21082. while (length > 0 && ret == 0) {
  21083. byte* output = NULL;
  21084. word32 fragSz = 0;
  21085. word32 i = RECORD_HEADER_SZ;
  21086. int sendSz = RECORD_HEADER_SZ;
  21087. ssl->options.buildingMsg = 1;
  21088. if (!ssl->options.dtls) {
  21089. if (ssl->fragOffset == 0) {
  21090. if (headerSz + certSz + certChainSz <=
  21091. maxFragment - HANDSHAKE_HEADER_SZ) {
  21092. fragSz = headerSz + certSz + certChainSz;
  21093. }
  21094. else {
  21095. fragSz = maxFragment - HANDSHAKE_HEADER_SZ;
  21096. }
  21097. sendSz += fragSz + HANDSHAKE_HEADER_SZ;
  21098. i += HANDSHAKE_HEADER_SZ;
  21099. }
  21100. else {
  21101. fragSz = min(length, maxFragment);
  21102. sendSz += fragSz;
  21103. }
  21104. if (IsEncryptionOn(ssl, 1))
  21105. sendSz += MAX_MSG_EXTRA;
  21106. }
  21107. else {
  21108. #ifdef WOLFSSL_DTLS
  21109. fragSz = min(length, maxFragment);
  21110. sendSz += fragSz + DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_HEADER_SZ;
  21111. i += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_HEADER_SZ;
  21112. #endif
  21113. }
  21114. if (IsEncryptionOn(ssl, 1))
  21115. sendSz += cipherExtraData(ssl);
  21116. /* check for available size */
  21117. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  21118. return ret;
  21119. /* get output buffer */
  21120. output = GetOutputBuffer(ssl);
  21121. /* Safe to use ssl->fragOffset since it will be incremented immediately
  21122. * after this block. This block needs to be entered only once to not
  21123. * hash the cert msg twice. */
  21124. if (ssl->fragOffset == 0) {
  21125. if (!ssl->options.dtls) {
  21126. AddFragHeaders(output, fragSz, 0, payloadSz, certificate, ssl);
  21127. if (!IsEncryptionOn(ssl, 1))
  21128. HashRaw(ssl, output + RECORD_HEADER_SZ,
  21129. HANDSHAKE_HEADER_SZ);
  21130. }
  21131. else {
  21132. #ifdef WOLFSSL_DTLS
  21133. AddHeaders(output, payloadSz, certificate, ssl);
  21134. HashRaw(ssl,
  21135. output + RECORD_HEADER_SZ + DTLS_RECORD_EXTRA,
  21136. HANDSHAKE_HEADER_SZ + DTLS_HANDSHAKE_EXTRA);
  21137. /* Adding the headers increments these, decrement them for
  21138. * actual message header. */
  21139. ssl->keys.dtls_handshake_number--;
  21140. AddFragHeaders(output, fragSz, 0, payloadSz, certificate, ssl);
  21141. ssl->keys.dtls_handshake_number--;
  21142. #endif /* WOLFSSL_DTLS */
  21143. }
  21144. /* list total */
  21145. #ifdef HAVE_RPK
  21146. if (!usingRpkTls12) {
  21147. #endif /* HAVE_RPK */
  21148. c32to24(listSz, output + i);
  21149. if (ssl->options.dtls || !IsEncryptionOn(ssl, 1))
  21150. HashRaw(ssl, output + i, CERT_HEADER_SZ);
  21151. i += CERT_HEADER_SZ;
  21152. length -= CERT_HEADER_SZ;
  21153. fragSz -= CERT_HEADER_SZ;
  21154. #ifdef HAVE_RPK
  21155. }
  21156. #endif /* HAVE_RPK */
  21157. if (certSz) {
  21158. c32to24(certSz, output + i);
  21159. if (ssl->options.dtls || !IsEncryptionOn(ssl, 1))
  21160. HashRaw(ssl, output + i, CERT_HEADER_SZ);
  21161. i += CERT_HEADER_SZ;
  21162. length -= CERT_HEADER_SZ;
  21163. fragSz -= CERT_HEADER_SZ;
  21164. if (ssl->options.dtls || !IsEncryptionOn(ssl, 1)) {
  21165. HashRaw(ssl, ssl->buffers.certificate->buffer, (int)certSz);
  21166. if (certChainSz)
  21167. HashRaw(ssl, ssl->buffers.certChain->buffer,
  21168. (int)certChainSz);
  21169. }
  21170. }
  21171. }
  21172. else {
  21173. if (!ssl->options.dtls) {
  21174. AddRecordHeader(output, fragSz, handshake, ssl, CUR_ORDER);
  21175. }
  21176. else {
  21177. #ifdef WOLFSSL_DTLS
  21178. AddFragHeaders(output, fragSz, ssl->fragOffset + headerSz,
  21179. payloadSz, certificate, ssl);
  21180. ssl->keys.dtls_handshake_number--;
  21181. #endif /* WOLFSSL_DTLS */
  21182. }
  21183. }
  21184. /* member */
  21185. if (certSz && ssl->fragOffset < certSz) {
  21186. word32 copySz = min(certSz - ssl->fragOffset, fragSz);
  21187. XMEMCPY(output + i,
  21188. ssl->buffers.certificate->buffer + ssl->fragOffset, copySz);
  21189. i += copySz;
  21190. ssl->fragOffset += copySz;
  21191. length -= copySz;
  21192. fragSz -= copySz;
  21193. }
  21194. if (certChainSz && fragSz) {
  21195. word32 copySz = min(certChainSz + certSz - ssl->fragOffset, fragSz);
  21196. XMEMCPY(output + i,
  21197. ssl->buffers.certChain->buffer + ssl->fragOffset - certSz,
  21198. copySz);
  21199. i += copySz;
  21200. ssl->fragOffset += copySz;
  21201. length -= copySz;
  21202. }
  21203. if (IsEncryptionOn(ssl, 1)) {
  21204. byte* input = NULL;
  21205. int inputSz = (int)i; /* build msg adds rec hdr */
  21206. int recordHeaderSz = RECORD_HEADER_SZ;
  21207. if (ssl->options.dtls)
  21208. recordHeaderSz += DTLS_RECORD_EXTRA;
  21209. inputSz -= recordHeaderSz;
  21210. if (inputSz < 0) {
  21211. WOLFSSL_MSG("Send Cert bad inputSz");
  21212. return BUFFER_E;
  21213. }
  21214. if (inputSz > 0) { /* clang thinks could be zero, let's help */
  21215. input = (byte*)XMALLOC((size_t)inputSz, ssl->heap,
  21216. DYNAMIC_TYPE_IN_BUFFER);
  21217. if (input == NULL)
  21218. return MEMORY_E;
  21219. XMEMCPY(input, output + recordHeaderSz, inputSz);
  21220. }
  21221. #ifndef WOLFSSL_DTLS
  21222. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  21223. handshake, 1, 0, 0, CUR_ORDER);
  21224. #else
  21225. if (!ssl->options.dtls)
  21226. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  21227. handshake, 1, 0, 0, CUR_ORDER);
  21228. else /* DTLS 1.2 has to ignore fragmentation in hashing so we need to
  21229. * calculate the hash ourselves above */ {
  21230. if ((ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, certificate)) != 0) {
  21231. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  21232. return ret;
  21233. }
  21234. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  21235. handshake, 0, 0, 0, CUR_ORDER);
  21236. }
  21237. #endif
  21238. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  21239. if (sendSz < 0)
  21240. return sendSz;
  21241. }
  21242. else {
  21243. sendSz = (int)i;
  21244. #ifdef WOLFSSL_DTLS
  21245. if (IsDtlsNotSctpMode(ssl)) {
  21246. if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, certificate)) != 0)
  21247. return ret;
  21248. }
  21249. if (ssl->options.dtls)
  21250. DtlsSEQIncrement(ssl, CUR_ORDER);
  21251. #endif
  21252. }
  21253. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  21254. if (ssl->hsInfoOn)
  21255. AddPacketName(ssl, "Certificate");
  21256. if (ssl->toInfoOn) {
  21257. ret = AddPacketInfo(ssl, "Certificate", handshake, output, sendSz,
  21258. WRITE_PROTO, 0, ssl->heap);
  21259. if (ret != 0)
  21260. return ret;
  21261. }
  21262. #endif
  21263. ssl->buffers.outputBuffer.length += (word32)sendSz;
  21264. if (!ssl->options.groupMessages)
  21265. ret = SendBuffered(ssl);
  21266. }
  21267. if (ret != WC_NO_ERR_TRACE(WANT_WRITE)) {
  21268. /* Clean up the fragment offset. */
  21269. ssl->options.buildingMsg = 0;
  21270. ssl->fragOffset = 0;
  21271. #ifdef WOLFSSL_DTLS
  21272. if (ssl->options.dtls)
  21273. ssl->keys.dtls_handshake_number++;
  21274. #endif
  21275. if (ssl->options.side == WOLFSSL_SERVER_END){
  21276. ssl->options.serverState = SERVER_CERT_COMPLETE;
  21277. }
  21278. }
  21279. WOLFSSL_LEAVE("SendCertificate", ret);
  21280. WOLFSSL_END(WC_FUNC_CERTIFICATE_SEND);
  21281. return ret;
  21282. }
  21283. #endif /* !NO_WOLFSSL_SERVER || !WOLFSSL_NO_CLIENT_AUTH */
  21284. /* handle generation of certificate_request (13) */
  21285. int SendCertificateRequest(WOLFSSL* ssl)
  21286. {
  21287. byte *output;
  21288. int ret;
  21289. int sendSz;
  21290. word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  21291. word32 dnLen = 0;
  21292. #ifndef WOLFSSL_NO_CA_NAMES
  21293. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  21294. #endif
  21295. const Suites* suites = WOLFSSL_SUITES(ssl);
  21296. int typeTotal = 1; /* only 1 for now */
  21297. int reqSz = ENUM_LEN + typeTotal + REQ_HEADER_SZ; /* add auth later */
  21298. WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_SEND);
  21299. WOLFSSL_ENTER("SendCertificateRequest");
  21300. if (IsAtLeastTLSv1_2(ssl))
  21301. reqSz += LENGTH_SZ + suites->hashSigAlgoSz;
  21302. #ifndef WOLFSSL_NO_CA_NAMES
  21303. /* Certificate Authorities */
  21304. names = SSL_CA_NAMES(ssl);
  21305. while (names != NULL) {
  21306. byte seq[MAX_SEQ_SZ];
  21307. WOLFSSL_X509_NAME* name = names->data.name;
  21308. if (name != NULL) {
  21309. /* 16-bit length | SEQ | Len | DER of name */
  21310. dnLen += OPAQUE16_LEN + SetSequence(name->rawLen, seq) +
  21311. name->rawLen;
  21312. }
  21313. names = names->next;
  21314. }
  21315. reqSz += dnLen;
  21316. #endif
  21317. if (ssl->options.usingPSK_cipher || ssl->options.usingAnon_cipher)
  21318. return 0; /* not needed */
  21319. sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + reqSz;
  21320. if (!ssl->options.dtls) {
  21321. if (IsEncryptionOn(ssl, 1))
  21322. sendSz += MAX_MSG_EXTRA;
  21323. }
  21324. else {
  21325. #ifdef WOLFSSL_DTLS
  21326. sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  21327. i += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  21328. #endif
  21329. }
  21330. if (IsEncryptionOn(ssl, 1))
  21331. sendSz += cipherExtraData(ssl);
  21332. /* Set this in case CheckAvailableSize returns a WANT_WRITE so that state
  21333. * is not advanced yet */
  21334. ssl->options.buildingMsg = 1;
  21335. /* check for available size */
  21336. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  21337. return ret;
  21338. /* get output buffer */
  21339. output = GetOutputBuffer(ssl);
  21340. AddHeaders(output, (word32)reqSz, certificate_request, ssl);
  21341. /* write to output */
  21342. output[i++] = (byte)typeTotal; /* # of types */
  21343. #ifdef HAVE_ECC
  21344. if ((ssl->options.cipherSuite0 == ECC_BYTE ||
  21345. ssl->options.cipherSuite0 == CHACHA_BYTE) &&
  21346. ssl->specs.sig_algo == ecc_dsa_sa_algo) {
  21347. output[i++] = ecdsa_sign;
  21348. }
  21349. else
  21350. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) && \
  21351. (defined(WOLFSSL_SM4_CBC) || defined(WOLFSSL_SM4_GCM) || \
  21352. defined(WOLFSSL_SM4_CCM))
  21353. if (ssl->options.cipherSuite0 == SM_BYTE && (0
  21354. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  21355. || ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  21356. #endif
  21357. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3
  21358. || ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3
  21359. #endif
  21360. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3
  21361. || ssl->options.cipherSuite == TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3
  21362. #endif
  21363. )) {
  21364. output[i++] = ecdsa_sign;
  21365. }
  21366. else
  21367. #endif
  21368. #endif /* HAVE_ECC */
  21369. {
  21370. output[i++] = rsa_sign;
  21371. }
  21372. /* supported hash/sig */
  21373. if (IsAtLeastTLSv1_2(ssl)) {
  21374. c16toa(suites->hashSigAlgoSz, &output[i]);
  21375. i += OPAQUE16_LEN;
  21376. XMEMCPY(&output[i], suites->hashSigAlgo, suites->hashSigAlgoSz);
  21377. i += suites->hashSigAlgoSz;
  21378. }
  21379. /* Certificate Authorities */
  21380. c16toa((word16)dnLen, &output[i]); /* auth's */
  21381. i += REQ_HEADER_SZ;
  21382. #ifndef WOLFSSL_NO_CA_NAMES
  21383. names = SSL_CA_NAMES(ssl);
  21384. while (names != NULL) {
  21385. byte seq[MAX_SEQ_SZ];
  21386. WOLFSSL_X509_NAME* name = names->data.name;
  21387. if (name != NULL) {
  21388. c16toa((word16)name->rawLen +
  21389. (word16)SetSequence(name->rawLen, seq), &output[i]);
  21390. i += OPAQUE16_LEN;
  21391. i += SetSequence(name->rawLen, output + i);
  21392. XMEMCPY(output + i, name->raw, name->rawLen);
  21393. i += name->rawLen;
  21394. }
  21395. names = names->next;
  21396. }
  21397. #endif
  21398. (void)i;
  21399. if (IsEncryptionOn(ssl, 1)) {
  21400. byte* input = NULL;
  21401. int inputSz = (int)i; /* build msg adds rec hdr */
  21402. int recordHeaderSz = RECORD_HEADER_SZ;
  21403. if (ssl->options.dtls)
  21404. recordHeaderSz += DTLS_RECORD_EXTRA;
  21405. inputSz -= recordHeaderSz;
  21406. if (inputSz <= 0) {
  21407. WOLFSSL_MSG("Send Cert Req bad inputSz");
  21408. return BUFFER_E;
  21409. }
  21410. input = (byte*)XMALLOC((size_t)inputSz, ssl->heap,
  21411. DYNAMIC_TYPE_IN_BUFFER);
  21412. if (input == NULL)
  21413. return MEMORY_E;
  21414. XMEMCPY(input, output + recordHeaderSz, inputSz);
  21415. #ifdef WOLFSSL_DTLS
  21416. if (IsDtlsNotSctpMode(ssl) &&
  21417. (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz,
  21418. certificate_request)) != 0) {
  21419. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  21420. return ret;
  21421. }
  21422. #endif
  21423. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  21424. handshake, 1, 0, 0, CUR_ORDER);
  21425. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  21426. if (sendSz < 0)
  21427. return sendSz;
  21428. } else {
  21429. sendSz = (int)i;
  21430. #ifdef WOLFSSL_DTLS
  21431. if (IsDtlsNotSctpMode(ssl)) {
  21432. if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz,
  21433. certificate_request)) != 0)
  21434. return ret;
  21435. }
  21436. if (ssl->options.dtls)
  21437. DtlsSEQIncrement(ssl, CUR_ORDER);
  21438. #endif
  21439. ret = HashOutput(ssl, output, sendSz, 0);
  21440. if (ret != 0)
  21441. return ret;
  21442. }
  21443. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  21444. if (ssl->hsInfoOn)
  21445. AddPacketName(ssl, "CertificateRequest");
  21446. if (ssl->toInfoOn) {
  21447. ret = AddPacketInfo(ssl, "CertificateRequest", handshake, output,
  21448. sendSz, WRITE_PROTO, 0, ssl->heap);
  21449. if (ret != 0)
  21450. return ret;
  21451. }
  21452. #endif
  21453. ssl->buffers.outputBuffer.length += (word32)sendSz;
  21454. if (ssl->options.groupMessages)
  21455. ret = 0;
  21456. else
  21457. ret = SendBuffered(ssl);
  21458. ssl->options.buildingMsg = 0;
  21459. WOLFSSL_LEAVE("SendCertificateRequest", ret);
  21460. WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
  21461. return ret;
  21462. }
  21463. #ifndef NO_WOLFSSL_SERVER
  21464. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  21465. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  21466. static int BuildCertificateStatus(WOLFSSL* ssl, byte type, buffer* status,
  21467. byte count)
  21468. {
  21469. byte* output = NULL;
  21470. word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  21471. word32 length = ENUM_LEN;
  21472. word32 headerSz= idx;
  21473. int sendSz = 0;
  21474. int ret = 0;
  21475. int i = 0;
  21476. WOLFSSL_ENTER("BuildCertificateStatus");
  21477. switch (type) {
  21478. case WOLFSSL_CSR2_OCSP_MULTI:
  21479. length += OPAQUE24_LEN;
  21480. FALL_THROUGH; /* followed by */
  21481. case WOLFSSL_CSR2_OCSP:
  21482. for (i = 0; i < count; i++)
  21483. length += OPAQUE24_LEN + status[i].length;
  21484. break;
  21485. default:
  21486. return 0;
  21487. }
  21488. #ifdef WOLFSSL_DTLS
  21489. if (ssl->options.dtls) {
  21490. headerSz = idx = DTLS_RECORD_HEADER_SZ + DTLS_HANDSHAKE_HEADER_SZ;
  21491. sendSz = idx + length;
  21492. } else
  21493. #endif
  21494. sendSz = (int)(idx + length);
  21495. if (ssl->keys.encryptionOn)
  21496. sendSz += MAX_MSG_EXTRA;
  21497. output =(byte*)XMALLOC(sendSz, ssl->heap, DYNAMIC_TYPE_OCSP);
  21498. if (output == NULL)
  21499. return MEMORY_E;
  21500. AddHeaders(output, length, certificate_status, ssl);
  21501. output[idx++] = type;
  21502. if (type == WOLFSSL_CSR2_OCSP_MULTI) {
  21503. c32to24(length - (ENUM_LEN + OPAQUE24_LEN), output + idx);
  21504. idx += OPAQUE24_LEN;
  21505. }
  21506. for (i = 0; i < count; i++) {
  21507. c32to24(status[i].length, output + idx);
  21508. idx += OPAQUE24_LEN;
  21509. XMEMCPY(output + idx, status[i].buffer, status[i].length);
  21510. idx += status[i].length;
  21511. }
  21512. /* Send Message. Handled message fragmentation in the function if needed */
  21513. ret = SendHandshakeMsg(ssl, output, (sendSz - headerSz), certificate_status,
  21514. "Certificate Status");
  21515. XFREE(output, ssl->heap, DYNAMIC_TYPE_OCSP);
  21516. WOLFSSL_LEAVE("BuildCertificateStatus", ret);
  21517. return ret;
  21518. }
  21519. #endif
  21520. #endif /* NO_WOLFSSL_SERVER */
  21521. /* handle generation of certificate_status (22) */
  21522. int SendCertificateStatus(WOLFSSL* ssl)
  21523. {
  21524. int ret = 0;
  21525. byte status_type = 0;
  21526. WOLFSSL_START(WC_FUNC_CERTIFICATE_STATUS_SEND);
  21527. WOLFSSL_ENTER("SendCertificateStatus");
  21528. (void) ssl;
  21529. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  21530. status_type = ssl->status_request;
  21531. #endif
  21532. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  21533. status_type = status_type ? status_type : ssl->status_request_v2;
  21534. #endif
  21535. switch (status_type) {
  21536. #ifndef NO_WOLFSSL_SERVER
  21537. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  21538. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  21539. /* case WOLFSSL_CSR_OCSP: */
  21540. case WOLFSSL_CSR2_OCSP:
  21541. {
  21542. OcspRequest* request = ssl->ctx->certOcspRequest;
  21543. buffer response;
  21544. ret = CreateOcspResponse(ssl, &request, &response);
  21545. /* if a request was successfully created and not stored in
  21546. * ssl->ctx then free it */
  21547. if (ret == 0 && request != ssl->ctx->certOcspRequest) {
  21548. FreeOcspRequest(request);
  21549. XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  21550. request = NULL;
  21551. }
  21552. if (ret == 0 && response.buffer) {
  21553. ret = BuildCertificateStatus(ssl, status_type, &response, 1);
  21554. }
  21555. /* Let's not error out the connection if we can't verify our cert */
  21556. if (ret == WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E) ||
  21557. ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E))
  21558. ret = 0;
  21559. if (response.buffer) {
  21560. XFREE(response.buffer, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  21561. response.buffer = NULL;
  21562. }
  21563. break;
  21564. }
  21565. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
  21566. /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  21567. #if defined HAVE_CERTIFICATE_STATUS_REQUEST_V2
  21568. case WOLFSSL_CSR2_OCSP_MULTI:
  21569. {
  21570. OcspRequest* request = ssl->ctx->certOcspRequest;
  21571. buffer responses[1 + MAX_CHAIN_DEPTH];
  21572. byte ctxOwnsRequest = 0;
  21573. int i = 0;
  21574. XMEMSET(responses, 0, sizeof(responses));
  21575. ret = CreateOcspResponse(ssl, &request, &responses[0]);
  21576. /* if a request was successfully created and not stored in
  21577. * ssl->ctx then free it */
  21578. if (ret == 0 && request != ssl->ctx->certOcspRequest) {
  21579. FreeOcspRequest(request);
  21580. XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  21581. request = NULL;
  21582. }
  21583. if (ret == 0 && (!ssl->ctx->chainOcspRequest[0]
  21584. || ssl->buffers.weOwnCertChain)) {
  21585. buffer der;
  21586. word32 idx = 0;
  21587. #ifdef WOLFSSL_SMALL_STACK
  21588. DecodedCert* cert;
  21589. #else
  21590. DecodedCert cert[1];
  21591. #endif
  21592. DerBuffer* chain;
  21593. #ifdef WOLFSSL_SMALL_STACK
  21594. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
  21595. DYNAMIC_TYPE_DCERT);
  21596. if (cert == NULL)
  21597. return MEMORY_E;
  21598. #endif
  21599. request = (OcspRequest*)XMALLOC(sizeof(OcspRequest), ssl->heap,
  21600. DYNAMIC_TYPE_OCSP_REQUEST);
  21601. if (request == NULL) {
  21602. #ifdef WOLFSSL_SMALL_STACK
  21603. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  21604. #endif
  21605. return MEMORY_E;
  21606. }
  21607. /* use certChain if available, otherwise use peer certificate */
  21608. chain = ssl->buffers.certChain;
  21609. if (chain == NULL) {
  21610. chain = ssl->buffers.certificate;
  21611. }
  21612. if (chain && chain->buffer) {
  21613. while (idx + OPAQUE24_LEN < chain->length) {
  21614. c24to32(chain->buffer + idx, &der.length);
  21615. idx += OPAQUE24_LEN;
  21616. der.buffer = chain->buffer + idx;
  21617. idx += der.length;
  21618. if (idx > chain->length)
  21619. break;
  21620. ret = CreateOcspRequest(ssl, request, cert, der.buffer,
  21621. der.length, &ctxOwnsRequest);
  21622. if (ret == 0) {
  21623. request->ssl = ssl;
  21624. ret = CheckOcspRequest(SSL_CM(ssl)->ocsp_stapling,
  21625. request, &responses[i + 1], ssl->heap);
  21626. /* Suppressing, not critical */
  21627. if (ret == WC_NO_ERR_TRACE(OCSP_CERT_REVOKED) ||
  21628. ret == WC_NO_ERR_TRACE(OCSP_CERT_UNKNOWN) ||
  21629. ret == WC_NO_ERR_TRACE(OCSP_LOOKUP_FAIL)) {
  21630. ret = 0;
  21631. }
  21632. i++;
  21633. if (!ctxOwnsRequest)
  21634. FreeOcspRequest(request);
  21635. }
  21636. }
  21637. }
  21638. if (!ctxOwnsRequest)
  21639. XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  21640. #ifdef WOLFSSL_SMALL_STACK
  21641. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  21642. #endif
  21643. }
  21644. else {
  21645. while (ret == 0 &&
  21646. NULL != (request = ssl->ctx->chainOcspRequest[i])) {
  21647. request->ssl = ssl;
  21648. ret = CheckOcspRequest(SSL_CM(ssl)->ocsp_stapling,
  21649. request, &responses[++i], ssl->heap);
  21650. /* Suppressing, not critical */
  21651. if (ret == WC_NO_ERR_TRACE(OCSP_CERT_REVOKED) ||
  21652. ret == WC_NO_ERR_TRACE(OCSP_CERT_UNKNOWN) ||
  21653. ret == WC_NO_ERR_TRACE(OCSP_LOOKUP_FAIL)) {
  21654. ret = 0;
  21655. }
  21656. }
  21657. }
  21658. if (responses[0].buffer) {
  21659. if (ret == 0) {
  21660. ret = BuildCertificateStatus(ssl, status_type, responses,
  21661. (byte)i + 1);
  21662. }
  21663. for (i = 0; i < 1 + MAX_CHAIN_DEPTH; i++) {
  21664. if (responses[i].buffer) {
  21665. XFREE(responses[i].buffer, ssl->heap,
  21666. DYNAMIC_TYPE_OCSP_REQUEST);
  21667. }
  21668. }
  21669. }
  21670. /* Let's not error out the connection if we can't verify our cert */
  21671. if (ret == WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E) ||
  21672. ret == WC_NO_ERR_TRACE(ASN_NO_SIGNER_E))
  21673. ret = 0;
  21674. break;
  21675. }
  21676. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  21677. #endif /* NO_WOLFSSL_SERVER */
  21678. default:
  21679. break;
  21680. }
  21681. WOLFSSL_LEAVE("SendCertificateStatus", ret);
  21682. WOLFSSL_END(WC_FUNC_CERTIFICATE_STATUS_SEND);
  21683. return ret;
  21684. }
  21685. #endif /* !NO_CERTS */
  21686. #endif /* WOLFSSL_NO_TLS12 */
  21687. #if defined(HAVE_SECURE_RENEGOTIATION) && defined(WOLFSSL_DTLS)
  21688. /**
  21689. * Check if the SCR keys are set in ssl->secure_renegotiation->tmp_keys.
  21690. */
  21691. int DtlsSCRKeysSet(WOLFSSL* ssl)
  21692. {
  21693. return ssl->secure_renegotiation &&
  21694. ssl->secure_renegotiation->tmp_keys.dtls_epoch != 0;
  21695. }
  21696. /**
  21697. * ssl->keys contains the current cipher parameters only for epoch 1. For
  21698. * epochs >1 ssl->secure_renegotiation->tmp_keys contains the current
  21699. * cipher parameters. This function checks if the message currently being
  21700. * processed should use ssl->keys or ssl->secure_renegotiation->tmp_keys.
  21701. */
  21702. int IsDtlsMsgSCRKeys(WOLFSSL* ssl)
  21703. {
  21704. return DtlsSCRKeysSet(ssl) &&
  21705. ssl->keys.curEpoch ==
  21706. ssl->secure_renegotiation->tmp_keys.dtls_epoch;
  21707. }
  21708. /**
  21709. * ssl->keys contains the current cipher parameters only for epoch 1. For
  21710. * epochs >1 ssl->secure_renegotiation->tmp_keys contains the current
  21711. * cipher parameters. This function checks if the message currently being
  21712. * built should use ssl->keys or ssl->secure_renegotiation->tmp_keys.
  21713. */
  21714. int DtlsUseSCRKeys(WOLFSSL* ssl)
  21715. {
  21716. return DtlsSCRKeysSet(ssl) &&
  21717. ssl->secure_renegotiation->tmp_keys.dtls_epoch ==
  21718. ssl->keys.dtls_epoch;
  21719. }
  21720. /**
  21721. * If ssl->secure_renegotiation->tmp_keys.dtls_epoch > ssl->keys.dtls_epoch
  21722. * then PREV_ORDER refers to the current epoch.
  21723. * */
  21724. int DtlsCheckOrder(WOLFSSL* ssl, int order)
  21725. {
  21726. if (order == PREV_ORDER && ssl->secure_renegotiation &&
  21727. ssl->secure_renegotiation->tmp_keys.dtls_epoch > ssl->keys.dtls_epoch) {
  21728. return CUR_ORDER;
  21729. }
  21730. else {
  21731. return order;
  21732. }
  21733. }
  21734. #endif /* HAVE_SECURE_RENEGOTIATION && WOLFSSL_DTLS */
  21735. /* If secure renegotiation is disabled, this will always return false.
  21736. * Otherwise it checks to see if we are currently renegotiating. */
  21737. int IsSCR(WOLFSSL* ssl)
  21738. {
  21739. #ifndef HAVE_SECURE_RENEGOTIATION
  21740. (void)ssl;
  21741. #else /* HAVE_SECURE_RENEGOTIATION */
  21742. if (ssl->secure_renegotiation &&
  21743. ssl->secure_renegotiation->enabled && /* Is SCR enabled? */
  21744. ssl->options.handShakeDone && /* At least one handshake done? */
  21745. ssl->options.handShakeState != HANDSHAKE_DONE) /* Currently handshaking? */
  21746. return 1;
  21747. #endif /* HAVE_SECURE_RENEGOTIATION */
  21748. return 0;
  21749. }
  21750. #ifdef WOLFSSL_DTLS
  21751. static int ModifyForMTU(WOLFSSL* ssl, int buffSz, int outputSz, int mtuSz)
  21752. {
  21753. int recordExtra = outputSz - buffSz;
  21754. (void)ssl;
  21755. if (recordExtra > 0 && outputSz > mtuSz) {
  21756. buffSz = mtuSz - recordExtra;
  21757. #ifndef WOLFSSL_AEAD_ONLY
  21758. /* Subtract a block size to be certain that returned fragment
  21759. * size won't get more padding. */
  21760. if (ssl->specs.cipher_type == block)
  21761. buffSz -= ssl->specs.block_size;
  21762. #endif
  21763. }
  21764. return buffSz;
  21765. }
  21766. #endif /* WOLFSSL_DTLS */
  21767. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_TLS13_IGNORE_AEAD_LIMITS)
  21768. /*
  21769. * Enforce limits specified in
  21770. * https://www.rfc-editor.org/rfc/rfc8446#section-5.5
  21771. */
  21772. static int CheckTLS13AEADSendLimit(WOLFSSL* ssl)
  21773. {
  21774. w64wrapper seq;
  21775. w64wrapper limit;
  21776. switch (ssl->specs.bulk_cipher_algorithm) {
  21777. #ifdef BUILD_AESGCM
  21778. case wolfssl_aes_gcm:
  21779. /* Limit is 2^24.5 */
  21780. limit = AEAD_AES_LIMIT;
  21781. break;
  21782. #endif
  21783. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  21784. case wolfssl_chacha:
  21785. /* For ChaCha20/Poly1305, the record sequence number would wrap
  21786. * before the safety limit is reached. */
  21787. return 0;
  21788. #endif
  21789. #ifdef HAVE_AESCCM
  21790. case wolfssl_aes_ccm:
  21791. /* Use the limits calculated in the DTLS 1.3 spec
  21792. * https://www.rfc-editor.org/rfc/rfc9147.html#name-analysis-of-limits-on-ccm-u */
  21793. #ifdef WOLFSSL_DTLS13
  21794. if (ssl->options.dtls)
  21795. limit = DTLS_AEAD_AES_CCM_LIMIT; /* Limit is 2^23 */
  21796. else
  21797. #endif
  21798. limit = AEAD_AES_LIMIT; /* Limit is 2^24.5 */
  21799. break;
  21800. #endif
  21801. #ifdef WOLFSSL_SM4_GCM
  21802. case wolfssl_sm4_gcm:
  21803. /* Limit is 2^22 - 1 */
  21804. limit = AEAD_SM4_GCM_LIMIT;
  21805. break;
  21806. #endif
  21807. #ifdef WOLFSSL_SM4_CCM
  21808. case wolfssl_sm4_ccm:
  21809. /* Limit is 2^10 - 1 */
  21810. limit = AEAD_SM4_CCM_LIMIT;
  21811. break;
  21812. #endif
  21813. case wolfssl_cipher_null:
  21814. /* No encryption being done */
  21815. return 0;
  21816. default:
  21817. WOLFSSL_MSG("Unrecognized ciphersuite for AEAD limit check");
  21818. return BAD_STATE_E;
  21819. }
  21820. #ifdef WOLFSSL_DTLS13
  21821. if (ssl->options.dtls) {
  21822. seq = ssl->dtls13EncryptEpoch->nextSeqNumber;
  21823. }
  21824. else
  21825. #endif
  21826. {
  21827. seq = w64From32(ssl->keys.sequence_number_hi,
  21828. ssl->keys.sequence_number_lo);
  21829. }
  21830. if (w64GTE(seq, limit)) { /* cppcheck-suppress uninitvar
  21831. * (false positive from cppcheck-2.13.0)
  21832. */
  21833. return Tls13UpdateKeys(ssl); /* Need to generate new keys */
  21834. }
  21835. return 0;
  21836. }
  21837. #endif /* WOLFSSL_TLS13 && !WOLFSSL_TLS13_IGNORE_AEAD_LIMITS */
  21838. /**
  21839. * ssl_in_handshake():
  21840. * Invoked in wolfSSL_read/wolfSSL_write to check if wolfSSL_negotiate() is
  21841. * needed in the handshake.
  21842. *
  21843. * In TLSv1.2 negotiate until the end of the handshake, unless:
  21844. * 1 in SCR and sending data or
  21845. * 2 in SCR and we have plain data ready
  21846. * Early data logic may bypass this logic in TLSv1.3 when appropriate.
  21847. */
  21848. static int ssl_in_handshake(WOLFSSL *ssl, int send)
  21849. {
  21850. if (IsSCR(ssl)) {
  21851. if (send) {
  21852. /* allow sending data in SCR */
  21853. return 0;
  21854. } else {
  21855. /* allow reading buffered data in SCR */
  21856. if (ssl->buffers.clearOutputBuffer.length != 0)
  21857. return 0;
  21858. }
  21859. return 1;
  21860. }
  21861. if (ssl->options.handShakeState != HANDSHAKE_DONE)
  21862. return 1;
  21863. if (ssl->options.side == WOLFSSL_SERVER_END) {
  21864. if (IsAtLeastTLSv1_3(ssl->version))
  21865. return ssl->options.acceptState < TLS13_TICKET_SENT;
  21866. if (IsAtLeastTLSv1_2(ssl))
  21867. return ssl->options.acceptState < ACCEPT_THIRD_REPLY_DONE;
  21868. return 0;
  21869. }
  21870. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  21871. if (IsAtLeastTLSv1_3(ssl->version))
  21872. return ssl->options.connectState < FINISHED_DONE;
  21873. if (IsAtLeastTLSv1_2(ssl))
  21874. return ssl->options.connectState < SECOND_REPLY_DONE;
  21875. return 0;
  21876. }
  21877. return 0;
  21878. }
  21879. int SendData(WOLFSSL* ssl, const void* data, int sz)
  21880. {
  21881. int sent = 0, /* plainText size */
  21882. sendSz,
  21883. ret;
  21884. #if defined(WOLFSSL_EARLY_DATA) && defined(WOLFSSL_EARLY_DATA_GROUP)
  21885. int groupMsgs = 0;
  21886. #endif
  21887. if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)
  21888. #ifdef WOLFSSL_ASYNC_CRYPT
  21889. || ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)
  21890. #endif
  21891. ) {
  21892. ssl->error = 0;
  21893. }
  21894. /* don't allow write after decrypt or mac error */
  21895. if (ssl->error == WC_NO_ERR_TRACE(VERIFY_MAC_ERROR) ||
  21896. ssl->error == WC_NO_ERR_TRACE(DECRYPT_ERROR)) {
  21897. /* For DTLS allow these possible errors and allow the session
  21898. to continue despite them */
  21899. if (ssl->options.dtls) {
  21900. ssl->error = 0;
  21901. }
  21902. else {
  21903. WOLFSSL_MSG("Not allowing write after decrypt or mac error");
  21904. return WOLFSSL_FATAL_ERROR;
  21905. }
  21906. }
  21907. #ifdef WOLFSSL_EARLY_DATA
  21908. if (ssl->options.side == WOLFSSL_CLIENT_END &&
  21909. ssl->earlyData != no_early_data &&
  21910. ssl->earlyData != done_early_data) {
  21911. if (ssl->options.handShakeState == HANDSHAKE_DONE) {
  21912. WOLFSSL_MSG("handshake complete, trying to send early data");
  21913. ssl->error = BUILD_MSG_ERROR;
  21914. return WOLFSSL_FATAL_ERROR;
  21915. }
  21916. #ifdef WOLFSSL_EARLY_DATA_GROUP
  21917. groupMsgs = 1;
  21918. #endif
  21919. }
  21920. else if (IsAtLeastTLSv1_3(ssl->version) &&
  21921. ssl->options.side == WOLFSSL_SERVER_END &&
  21922. ssl->options.acceptState >= TLS13_ACCEPT_FINISHED_SENT) {
  21923. /* We can send data without waiting on peer finished msg */
  21924. WOLFSSL_MSG("server sending data before receiving client finished");
  21925. }
  21926. else
  21927. #endif
  21928. if (ssl_in_handshake(ssl, 1)) {
  21929. int err;
  21930. WOLFSSL_MSG("handshake not complete, trying to finish");
  21931. if ( (err = wolfSSL_negotiate(ssl)) != WOLFSSL_SUCCESS) {
  21932. #ifdef WOLFSSL_ASYNC_CRYPT
  21933. /* if async would block return WANT_WRITE */
  21934. if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  21935. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  21936. }
  21937. #endif
  21938. return err;
  21939. }
  21940. }
  21941. /* last time system socket output buffer was full, try again to send */
  21942. if (ssl->buffers.outputBuffer.length > 0
  21943. #if defined(WOLFSSL_EARLY_DATA) && defined(WOLFSSL_EARLY_DATA_GROUP)
  21944. && !groupMsgs
  21945. #endif
  21946. ) {
  21947. WOLFSSL_MSG("output buffer was full, trying to send again");
  21948. if ( (ssl->error = SendBuffered(ssl)) < 0) {
  21949. WOLFSSL_ERROR(ssl->error);
  21950. if (ssl->error == WC_NO_ERR_TRACE(SOCKET_ERROR_E) &&
  21951. (ssl->options.connReset || ssl->options.isClosed)) {
  21952. ssl->error = SOCKET_PEER_CLOSED_E;
  21953. WOLFSSL_ERROR(ssl->error);
  21954. return 0; /* peer reset or closed */
  21955. }
  21956. return ssl->error;
  21957. }
  21958. else {
  21959. /* advance sent to previous sent + plain size just sent */
  21960. sent = ssl->buffers.prevSent + ssl->buffers.plainSz;
  21961. WOLFSSL_MSG("sent write buffered data");
  21962. if (sent > sz) {
  21963. WOLFSSL_MSG("error: write() after WANT_WRITE with short size");
  21964. return ssl->error = BAD_FUNC_ARG;
  21965. }
  21966. }
  21967. }
  21968. ret = RetrySendAlert(ssl);
  21969. if (ret != 0) {
  21970. ssl->error = ret;
  21971. return WOLFSSL_FATAL_ERROR;
  21972. }
  21973. for (;;) {
  21974. byte* out;
  21975. byte* sendBuffer = (byte*)data + sent; /* may switch on comp */
  21976. int buffSz; /* may switch on comp */
  21977. int outputSz;
  21978. #ifdef HAVE_LIBZ
  21979. byte comp[MAX_RECORD_SIZE + MAX_COMP_EXTRA];
  21980. #endif
  21981. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_TLS13_IGNORE_AEAD_LIMITS)
  21982. if (IsAtLeastTLSv1_3(ssl->version)) {
  21983. ret = CheckTLS13AEADSendLimit(ssl);
  21984. if (ret != 0) {
  21985. ssl->error = ret;
  21986. return WOLFSSL_FATAL_ERROR;
  21987. }
  21988. }
  21989. #endif
  21990. #ifdef WOLFSSL_DTLS13
  21991. if (ssl->options.dtls && ssl->options.tls1_3) {
  21992. byte isEarlyData = 0;
  21993. if (ssl->dtls13EncryptEpoch == NULL)
  21994. return ssl->error = BAD_STATE_E;
  21995. #ifdef WOLFSSL_EARLY_DATA
  21996. isEarlyData = ssl->options.side == WOLFSSL_CLIENT_END &&
  21997. ssl->earlyData != no_early_data &&
  21998. ssl->earlyData != done_early_data;
  21999. #endif
  22000. if (isEarlyData) {
  22001. #ifdef WOLFSSL_EARLY_DATA
  22002. ret = Dtls13SetEpochKeys(ssl,
  22003. w64From32(0x0, DTLS13_EPOCH_EARLYDATA), ENCRYPT_SIDE_ONLY);
  22004. if (ret != 0) {
  22005. WOLFSSL_MSG(
  22006. "trying to send early data without epoch 1");
  22007. ssl->error = BUILD_MSG_ERROR;
  22008. return WOLFSSL_FATAL_ERROR;
  22009. }
  22010. #endif /* WOLFSSL_EARLY_DATA */
  22011. }
  22012. else if (!w64Equal(
  22013. ssl->dtls13EncryptEpoch->epochNumber,
  22014. ssl->dtls13Epoch)) {
  22015. ret = Dtls13SetEpochKeys(
  22016. ssl, ssl->dtls13Epoch, ENCRYPT_SIDE_ONLY);
  22017. if (ret != 0) {
  22018. ssl->error = BUILD_MSG_ERROR;
  22019. return WOLFSSL_FATAL_ERROR;
  22020. }
  22021. }
  22022. }
  22023. #endif /* WOLFSSL_DTLS13 */
  22024. #ifdef WOLFSSL_DTLS
  22025. if (ssl->options.dtls) {
  22026. buffSz = wolfSSL_GetMaxFragSize(ssl, sz - sent);
  22027. }
  22028. else
  22029. #endif
  22030. {
  22031. buffSz = wolfSSL_GetMaxFragSize(ssl, sz - sent);
  22032. }
  22033. if (sent == sz) break;
  22034. #if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_NO_DTLS_SIZE_CHECK)
  22035. if (ssl->options.dtls && (buffSz < sz - sent)) {
  22036. ssl->error = DTLS_SIZE_ERROR;
  22037. WOLFSSL_ERROR(ssl->error);
  22038. return ssl->error;
  22039. }
  22040. #endif
  22041. outputSz = buffSz + COMP_EXTRA + DTLS_RECORD_HEADER_SZ;
  22042. if (IsEncryptionOn(ssl, 1) || ssl->options.tls1_3)
  22043. outputSz += cipherExtraData(ssl);
  22044. /* check for available size */
  22045. if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
  22046. return ssl->error = ret;
  22047. /* get output buffer */
  22048. out = GetOutputBuffer(ssl);
  22049. #ifdef HAVE_LIBZ
  22050. if (ssl->options.usingCompression) {
  22051. buffSz = myCompress(ssl, sendBuffer, buffSz, comp, sizeof(comp));
  22052. if (buffSz < 0) {
  22053. return buffSz;
  22054. }
  22055. sendBuffer = comp;
  22056. }
  22057. #endif
  22058. if (!ssl->options.tls1_3) {
  22059. #ifdef WOLFSSL_ASYNC_CRYPT
  22060. if (ssl->async == NULL) {
  22061. ssl->async = (struct WOLFSSL_ASYNC*)
  22062. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  22063. DYNAMIC_TYPE_ASYNC);
  22064. if (ssl->async == NULL)
  22065. return MEMORY_E;
  22066. ssl->async->freeArgs = NULL;
  22067. }
  22068. #endif
  22069. sendSz = BuildMessage(ssl, out, outputSz, sendBuffer, buffSz,
  22070. application_data, 0, 0, 1, CUR_ORDER);
  22071. }
  22072. else {
  22073. #ifdef WOLFSSL_TLS13
  22074. sendSz = BuildTls13Message(ssl, out, outputSz, sendBuffer, buffSz,
  22075. application_data, 0, 0, 1);
  22076. #else
  22077. sendSz = BUFFER_ERROR;
  22078. #endif
  22079. }
  22080. if (sendSz < 0) {
  22081. #ifdef WOLFSSL_ASYNC_CRYPT
  22082. if (sendSz == WC_NO_ERR_TRACE(WC_PENDING_E))
  22083. ssl->error = sendSz;
  22084. #endif
  22085. return BUILD_MSG_ERROR;
  22086. }
  22087. #ifdef WOLFSSL_ASYNC_CRYPT
  22088. FreeAsyncCtx(ssl, 0);
  22089. #endif
  22090. ssl->buffers.outputBuffer.length += (word32)sendSz;
  22091. if ( (ssl->error = SendBuffered(ssl)) < 0) {
  22092. WOLFSSL_ERROR(ssl->error);
  22093. /* store for next call if WANT_WRITE or user embedSend() that
  22094. doesn't present like WANT_WRITE */
  22095. ssl->buffers.plainSz = buffSz;
  22096. ssl->buffers.prevSent = sent;
  22097. if (ssl->error == WC_NO_ERR_TRACE(SOCKET_ERROR_E) &&
  22098. (ssl->options.connReset || ssl->options.isClosed)) {
  22099. ssl->error = SOCKET_PEER_CLOSED_E;
  22100. WOLFSSL_ERROR(ssl->error);
  22101. return 0; /* peer reset or closed */
  22102. }
  22103. return ssl->error;
  22104. }
  22105. sent += buffSz;
  22106. /* only one message per attempt */
  22107. if (ssl->options.partialWrite == 1) {
  22108. WOLFSSL_MSG("Partial Write on, only sending one record");
  22109. break;
  22110. }
  22111. }
  22112. return sent;
  22113. }
  22114. /* process input data */
  22115. int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek)
  22116. {
  22117. int size;
  22118. WOLFSSL_ENTER("ReceiveData");
  22119. /* reset error state */
  22120. if (ssl->error == WC_NO_ERR_TRACE(WANT_READ) ||
  22121. ssl->error == WOLFSSL_ERROR_WANT_READ)
  22122. {
  22123. ssl->error = 0;
  22124. }
  22125. #ifdef WOLFSSL_DTLS
  22126. if (ssl->options.dtls) {
  22127. /* In DTLS mode, we forgive some errors and allow the session
  22128. * to continue despite them. */
  22129. if (ssl->error == WC_NO_ERR_TRACE(VERIFY_MAC_ERROR) ||
  22130. ssl->error == WC_NO_ERR_TRACE(DECRYPT_ERROR) ||
  22131. ssl->error == WC_NO_ERR_TRACE(DTLS_SIZE_ERROR)) {
  22132. ssl->error = 0;
  22133. }
  22134. }
  22135. #endif /* WOLFSSL_DTLS */
  22136. if (ssl->error != 0 && ssl->error != WC_NO_ERR_TRACE(WANT_WRITE)
  22137. #ifdef WOLFSSL_ASYNC_CRYPT
  22138. && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
  22139. #endif
  22140. #if defined(HAVE_SECURE_RENEGOTIATION) || defined(WOLFSSL_DTLS13)
  22141. && ssl->error != WC_NO_ERR_TRACE(APP_DATA_READY)
  22142. #endif
  22143. ) {
  22144. WOLFSSL_MSG("User calling wolfSSL_read in error state, not allowed");
  22145. return ssl->error;
  22146. }
  22147. #ifdef WOLFSSL_EARLY_DATA
  22148. if (ssl->options.side == WOLFSSL_SERVER_END &&
  22149. ssl->earlyData > early_data_ext && ssl->earlyData < done_early_data) {
  22150. }
  22151. else
  22152. #endif
  22153. {
  22154. if (ssl_in_handshake(ssl, 0)) {
  22155. int err;
  22156. WOLFSSL_MSG("Handshake not complete, trying to finish");
  22157. if ( (err = wolfSSL_negotiate(ssl)) != WOLFSSL_SUCCESS) {
  22158. #ifdef WOLFSSL_ASYNC_CRYPT
  22159. /* if async would block return WANT_WRITE */
  22160. if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  22161. return WOLFSSL_CBIO_ERR_WANT_READ;
  22162. }
  22163. #endif
  22164. return err;
  22165. }
  22166. }
  22167. }
  22168. #ifdef HAVE_SECURE_RENEGOTIATION
  22169. startScr:
  22170. if (ssl->secure_renegotiation && ssl->secure_renegotiation->startScr) {
  22171. int ret;
  22172. WOLFSSL_MSG("Need to start scr, server requested");
  22173. ret = wolfSSL_Rehandshake(ssl);
  22174. ssl->secure_renegotiation->startScr = 0; /* only start once */
  22175. if (ret != WOLFSSL_SUCCESS)
  22176. return ret;
  22177. }
  22178. #endif
  22179. while (ssl->buffers.clearOutputBuffer.length == 0) {
  22180. if ( (ssl->error = ProcessReply(ssl)) < 0) {
  22181. if (ssl->error == WC_NO_ERR_TRACE(ZERO_RETURN)) {
  22182. WOLFSSL_MSG("Zero return, no more data coming");
  22183. return 0; /* no more data coming */
  22184. }
  22185. if (ssl->error == WC_NO_ERR_TRACE(SOCKET_ERROR_E)) {
  22186. if (ssl->options.connReset || ssl->options.isClosed) {
  22187. WOLFSSL_MSG("Peer reset or closed, connection done");
  22188. ssl->error = SOCKET_PEER_CLOSED_E;
  22189. WOLFSSL_ERROR(ssl->error);
  22190. return 0; /* peer reset or closed */
  22191. }
  22192. }
  22193. WOLFSSL_ERROR(ssl->error);
  22194. return ssl->error;
  22195. }
  22196. #ifdef WOLFSSL_DTLS13
  22197. if (ssl->options.dtls) {
  22198. /* Dtls13DoScheduledWork(ssl) may return WANT_WRITE */
  22199. if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
  22200. WOLFSSL_ERROR(ssl->error);
  22201. return ssl->error;
  22202. }
  22203. }
  22204. #endif /* WOLFSSL_DTLS13 */
  22205. #ifdef HAVE_SECURE_RENEGOTIATION
  22206. if (ssl->secure_renegotiation &&
  22207. ssl->secure_renegotiation->startScr) {
  22208. goto startScr;
  22209. }
  22210. if (ssl->secure_renegotiation && ssl->secure_renegotiation->enabled &&
  22211. ssl->options.handShakeState != HANDSHAKE_DONE
  22212. && ssl->buffers.clearOutputBuffer.length == 0) {
  22213. /* ProcessReply processed a handshake packet and not any APP DATA
  22214. * so let's move the handshake along */
  22215. int err;
  22216. WOLFSSL_MSG("Handshake not complete, trying to finish");
  22217. if ( (err = wolfSSL_negotiate(ssl)) != WOLFSSL_SUCCESS) {
  22218. #ifdef WOLFSSL_ASYNC_CRYPT
  22219. /* if async would block return WANT_WRITE */
  22220. if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  22221. return WOLFSSL_CBIO_ERR_WANT_READ;
  22222. }
  22223. #endif
  22224. return err;
  22225. }
  22226. }
  22227. #endif
  22228. #ifdef WOLFSSL_DTLS13
  22229. /* if wolfSSL_Peek() is invoked with sz == 0 it will not block (but
  22230. * it processes pending non-application records) */
  22231. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version) && peek &&
  22232. sz == 0 && ssl->buffers.inputBuffer.idx
  22233. - ssl->buffers.inputBuffer.length == 0) {
  22234. return 0;
  22235. }
  22236. #endif /* WOLFSSL_DTLS13 */
  22237. #ifndef WOLFSSL_TLS13_NO_PEEK_HANDSHAKE_DONE
  22238. #ifdef WOLFSSL_TLS13
  22239. if (IsAtLeastTLSv1_3(ssl->version) && ssl->options.handShakeDone &&
  22240. ssl->curRL.type == handshake && peek) {
  22241. WOLFSSL_MSG("Got Handshake Message in APP data");
  22242. if (ssl->buffers.inputBuffer.length == 0) {
  22243. ssl->error = WOLFSSL_ERROR_WANT_READ;
  22244. return 0;
  22245. }
  22246. }
  22247. #endif
  22248. #endif
  22249. }
  22250. size = (int)min((word32)sz, ssl->buffers.clearOutputBuffer.length);
  22251. XMEMCPY(output, ssl->buffers.clearOutputBuffer.buffer, size);
  22252. if (peek == 0) {
  22253. ssl->buffers.clearOutputBuffer.length -= (word32)size;
  22254. ssl->buffers.clearOutputBuffer.buffer += size;
  22255. }
  22256. if (ssl->buffers.inputBuffer.dynamicFlag)
  22257. ShrinkInputBuffer(ssl, NO_FORCED_FREE);
  22258. WOLFSSL_LEAVE("ReceiveData()", size);
  22259. return size;
  22260. }
  22261. static int SendAlert_ex(WOLFSSL* ssl, int severity, int type)
  22262. {
  22263. byte input[ALERT_SIZE];
  22264. byte *output;
  22265. int sendSz;
  22266. int ret;
  22267. int outputSz;
  22268. int dtlsExtra = 0;
  22269. WOLFSSL_ENTER("SendAlert");
  22270. WOLFSSL_MSG_EX("SendAlert: %d %s", type, AlertTypeToString(type));
  22271. #ifdef WOLFSSL_QUIC
  22272. if (WOLFSSL_IS_QUIC(ssl)) {
  22273. ret = !ssl->quic.method->send_alert(ssl, ssl->quic.enc_level_write, (uint8_t)type);
  22274. if (ret) {
  22275. WOLFSSL_MSG("QUIC send_alert callback error");
  22276. }
  22277. return ret;
  22278. }
  22279. #endif
  22280. #ifdef HAVE_WRITE_DUP
  22281. if (ssl->dupWrite && ssl->dupSide == READ_DUP_SIDE) {
  22282. int notifyErr = 0;
  22283. WOLFSSL_MSG("Read dup side cannot write alerts, notifying sibling");
  22284. if (type == close_notify) {
  22285. notifyErr = ZERO_RETURN;
  22286. } else if (severity == alert_fatal) {
  22287. notifyErr = FATAL_ERROR;
  22288. }
  22289. if (notifyErr != 0) {
  22290. return NotifyWriteSide(ssl, notifyErr);
  22291. }
  22292. return 0;
  22293. }
  22294. #endif
  22295. ssl->pendingAlert.code = type;
  22296. ssl->pendingAlert.level = severity;
  22297. #ifdef OPENSSL_EXTRA
  22298. if (ssl->CBIS != NULL) {
  22299. ssl->CBIS(ssl, SSL_CB_ALERT, type);
  22300. }
  22301. #endif
  22302. #ifdef WOLFSSL_DTLS
  22303. if (ssl->options.dtls)
  22304. dtlsExtra = DTLS_RECORD_EXTRA;
  22305. #endif
  22306. /* check for available size */
  22307. outputSz = ALERT_SIZE + MAX_MSG_EXTRA + dtlsExtra;
  22308. if ((ret = CheckAvailableSize(ssl, outputSz)) != 0) {
  22309. #ifdef WOLFSSL_DTLS
  22310. /* If CheckAvailableSize returned WANT_WRITE due to a blocking write
  22311. * then discard pending output and just send the alert. */
  22312. if (ssl->options.dtls) {
  22313. if (ret != WC_NO_ERR_TRACE(WANT_WRITE) || severity != alert_fatal)
  22314. return ret;
  22315. ShrinkOutputBuffer(ssl);
  22316. if ((ret = CheckAvailableSize(ssl, outputSz)) != 0) {
  22317. return ret;
  22318. }
  22319. }
  22320. else {
  22321. return ret;
  22322. }
  22323. #else
  22324. return ret;
  22325. #endif
  22326. }
  22327. /* Check output buffer */
  22328. if (ssl->buffers.outputBuffer.buffer == NULL)
  22329. return BUFFER_E;
  22330. /* get output buffer */
  22331. output = GetOutputBuffer(ssl);
  22332. input[0] = (byte)severity;
  22333. input[1] = (byte)type;
  22334. ssl->alert_history.last_tx.code = type;
  22335. ssl->alert_history.last_tx.level = severity;
  22336. if (severity == alert_fatal) {
  22337. #ifdef WOLFSSL_DTLS
  22338. /* Mark as closed in dtls only once we enter stateful mode. */
  22339. if (!ssl->options.dtls || ssl->options.dtlsStateful)
  22340. #endif
  22341. ssl->options.isClosed = 1; /* Don't send close_notify */
  22342. }
  22343. /* send encrypted alert if encryption is on - can be a rehandshake over
  22344. * an existing encrypted channel.
  22345. * TLS 1.3 encrypts handshake packets after the ServerHello
  22346. */
  22347. if (IsEncryptionOn(ssl, 1)) {
  22348. #ifdef WOLFSSL_DTLS13
  22349. if (ssl->options.dtls
  22350. && IsAtLeastTLSv1_3(ssl->version)
  22351. && !w64Equal(ssl->dtls13EncryptEpoch->epochNumber, ssl->dtls13Epoch)) {
  22352. ret = Dtls13SetEpochKeys(ssl, ssl->dtls13Epoch, ENCRYPT_SIDE_ONLY);
  22353. if (ret != 0)
  22354. return ret;
  22355. }
  22356. #endif /* WOLFSSL_DTLS13 */
  22357. sendSz = BuildMessage(ssl, output, outputSz, input, ALERT_SIZE, alert,
  22358. 0, 0, 0, CUR_ORDER);
  22359. }
  22360. else {
  22361. #ifdef WOLFSSL_DTLS13
  22362. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) {
  22363. ret = Dtls13RlAddPlaintextHeader(ssl, output, alert, ALERT_SIZE);
  22364. if (ret != 0)
  22365. return ret;
  22366. }
  22367. else
  22368. #endif /* WOLFSSL_DTLS13 */
  22369. {
  22370. AddRecordHeader(output, ALERT_SIZE, alert, ssl, CUR_ORDER);
  22371. #ifdef WOLFSSL_DTLS
  22372. /* AddRecordHeader doesn't increment the seq number */
  22373. if (ssl->options.dtls)
  22374. DtlsSEQIncrement(ssl, CUR_ORDER);
  22375. #endif
  22376. }
  22377. output += RECORD_HEADER_SZ;
  22378. #ifdef WOLFSSL_DTLS
  22379. if (ssl->options.dtls)
  22380. output += DTLS_RECORD_EXTRA;
  22381. #endif
  22382. XMEMCPY(output, input, ALERT_SIZE);
  22383. sendSz = RECORD_HEADER_SZ + ALERT_SIZE;
  22384. #ifdef WOLFSSL_DTLS
  22385. if (ssl->options.dtls)
  22386. sendSz += DTLS_RECORD_EXTRA;
  22387. #endif
  22388. }
  22389. if (sendSz < 0)
  22390. return BUILD_MSG_ERROR;
  22391. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  22392. if (ssl->hsInfoOn)
  22393. AddPacketName(ssl, "Alert");
  22394. if (ssl->toInfoOn) {
  22395. ret = AddPacketInfo(ssl, "Alert", alert, output, sendSz,
  22396. WRITE_PROTO, 0, ssl->heap);
  22397. if (ret != 0)
  22398. return ret;
  22399. }
  22400. #endif
  22401. /*
  22402. * We check if we are trying to send a
  22403. * CLOSE_NOTIFY alert.
  22404. * */
  22405. if (type == close_notify) {
  22406. if (!ssl->options.sentNotify) {
  22407. ssl->options.sentNotify = 1;
  22408. }
  22409. else {
  22410. /* CLOSE_NOTIFY already sent */
  22411. return 0;
  22412. }
  22413. }
  22414. ssl->buffers.outputBuffer.length += (word32)sendSz;
  22415. ret = SendBuffered(ssl);
  22416. ssl->pendingAlert.code = 0;
  22417. ssl->pendingAlert.level = alert_none;
  22418. WOLFSSL_LEAVE("SendAlert", ret);
  22419. return ret;
  22420. }
  22421. int RetrySendAlert(WOLFSSL* ssl)
  22422. {
  22423. int type;
  22424. int severity;
  22425. WOLFSSL_ENTER("RetrySendAlert");
  22426. if (ssl == NULL) {
  22427. return BAD_FUNC_ARG;
  22428. }
  22429. type = ssl->pendingAlert.code;
  22430. severity = ssl->pendingAlert.level;
  22431. if (severity == alert_none)
  22432. return 0;
  22433. ssl->pendingAlert.code = 0;
  22434. ssl->pendingAlert.level = alert_none;
  22435. return SendAlert_ex(ssl, severity, type);
  22436. }
  22437. /* send alert message */
  22438. int SendAlert(WOLFSSL* ssl, int severity, int type)
  22439. {
  22440. WOLFSSL_ENTER("SendAlert");
  22441. if (ssl == NULL) {
  22442. return BAD_FUNC_ARG;
  22443. }
  22444. if (ssl->pendingAlert.level != alert_none) {
  22445. int ret = RetrySendAlert(ssl);
  22446. if (ret != 0) {
  22447. if (ssl->pendingAlert.level == alert_none ||
  22448. (ssl->pendingAlert.level != alert_fatal &&
  22449. severity == alert_fatal)) {
  22450. /* Store current alert if pendingAlert is empty or if current
  22451. * is fatal and previous was not */
  22452. ssl->pendingAlert.code = type;
  22453. ssl->pendingAlert.level = severity;
  22454. }
  22455. return ret;
  22456. }
  22457. }
  22458. return SendAlert_ex(ssl, severity, type);
  22459. }
  22460. #ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES_H
  22461. #include <wolfssl/debug-untrace-error-codes.h>
  22462. #endif
  22463. const char* wolfSSL_ERR_reason_error_string(unsigned long e)
  22464. {
  22465. #ifdef NO_ERROR_STRINGS
  22466. (void)e;
  22467. return "no support for error strings built in";
  22468. #else
  22469. int error = (int)e;
  22470. /* OpenSSL uses positive error codes */
  22471. if (error > 0) {
  22472. error = -error;
  22473. }
  22474. /* pass to wolfCrypt */
  22475. if (error <= WC_FIRST_E && error >= WC_LAST_E) {
  22476. return wc_GetErrorString(error);
  22477. }
  22478. if (error == 0) {
  22479. #ifdef OPENSSL_EXTRA
  22480. return "ok";
  22481. #else
  22482. return "unknown error number";
  22483. #endif
  22484. }
  22485. switch ((enum wolfSSL_ErrorCodes)error) {
  22486. case UNSUPPORTED_SUITE :
  22487. return "unsupported cipher suite";
  22488. case INPUT_CASE_ERROR :
  22489. return "input state error";
  22490. case PREFIX_ERROR :
  22491. return "bad index to key rounds";
  22492. case MEMORY_ERROR :
  22493. return "out of memory";
  22494. case VERIFY_FINISHED_ERROR :
  22495. return "verify problem on finished";
  22496. case VERIFY_MAC_ERROR :
  22497. return "verify mac problem";
  22498. case PARSE_ERROR :
  22499. return "parse error on header";
  22500. case SIDE_ERROR :
  22501. return "wrong client/server type";
  22502. case NO_PEER_CERT : /* OpenSSL compatibility expects this exact text */
  22503. return "peer did not return a certificate";
  22504. case UNKNOWN_HANDSHAKE_TYPE :
  22505. return "weird handshake type";
  22506. case SOCKET_ERROR_E :
  22507. return "error state on socket";
  22508. case SOCKET_NODATA :
  22509. return "expected data, not there";
  22510. case INCOMPLETE_DATA :
  22511. return "don't have enough data to complete task";
  22512. case UNKNOWN_RECORD_TYPE :
  22513. return "unknown type in record hdr";
  22514. case DECRYPT_ERROR :
  22515. return "error during decryption";
  22516. case FATAL_ERROR :
  22517. return "received alert fatal error";
  22518. case ENCRYPT_ERROR :
  22519. return "error during encryption";
  22520. case FREAD_ERROR :
  22521. return "fread problem";
  22522. case NO_PEER_KEY :
  22523. return "need peer's key";
  22524. case NO_PRIVATE_KEY :
  22525. return "need the private key";
  22526. case NO_DH_PARAMS :
  22527. return "server missing DH params";
  22528. case RSA_PRIVATE_ERROR :
  22529. return "error during rsa priv op";
  22530. case MATCH_SUITE_ERROR :
  22531. return "can't match cipher suite";
  22532. case COMPRESSION_ERROR :
  22533. return "compression mismatch error";
  22534. case BUILD_MSG_ERROR :
  22535. return "build message failure";
  22536. case BAD_HELLO :
  22537. return "client hello malformed";
  22538. case DOMAIN_NAME_MISMATCH :
  22539. return "peer subject name mismatch";
  22540. case IPADDR_MISMATCH :
  22541. return "peer ip address mismatch";
  22542. case WANT_READ :
  22543. case -WOLFSSL_ERROR_WANT_READ :
  22544. return "non-blocking socket wants data to be read";
  22545. case NOT_READY_ERROR :
  22546. return "handshake layer not ready yet, complete first";
  22547. case VERSION_ERROR :
  22548. return "record layer version error";
  22549. case WANT_WRITE :
  22550. case -WOLFSSL_ERROR_WANT_WRITE :
  22551. return "non-blocking socket write buffer full";
  22552. case -WOLFSSL_ERROR_WANT_CONNECT:
  22553. case -WOLFSSL_ERROR_WANT_ACCEPT:
  22554. return "The underlying BIO was not yet connected";
  22555. case -WOLFSSL_ERROR_SYSCALL:
  22556. return "fatal I/O error in TLS layer";
  22557. case -WOLFSSL_ERROR_WANT_X509_LOOKUP:
  22558. return "application client cert callback asked to be called again";
  22559. case BUFFER_ERROR :
  22560. return "malformed buffer input error";
  22561. case VERIFY_CERT_ERROR :
  22562. return "verify problem on certificate";
  22563. case VERIFY_SIGN_ERROR :
  22564. return "verify problem based on signature";
  22565. case CLIENT_ID_ERROR :
  22566. return "psk client identity error";
  22567. case SERVER_HINT_ERROR:
  22568. return "psk server hint error";
  22569. case PSK_KEY_ERROR:
  22570. return "psk key callback error";
  22571. case GETTIME_ERROR:
  22572. return "gettimeofday() error";
  22573. case GETITIMER_ERROR:
  22574. return "getitimer() error";
  22575. case SIGACT_ERROR:
  22576. return "sigaction() error";
  22577. case SETITIMER_ERROR:
  22578. return "setitimer() error";
  22579. case LENGTH_ERROR:
  22580. return "record layer length error";
  22581. case PEER_KEY_ERROR:
  22582. return "can't decode peer key";
  22583. case ZERO_RETURN:
  22584. case -WOLFSSL_ERROR_ZERO_RETURN:
  22585. return "peer sent close notify alert";
  22586. case ECC_CURVETYPE_ERROR:
  22587. return "Bad ECC Curve Type or unsupported";
  22588. case ECC_CURVE_ERROR:
  22589. return "Bad ECC Curve or unsupported";
  22590. case ECC_PEERKEY_ERROR:
  22591. return "Bad ECC Peer Key";
  22592. case ECC_MAKEKEY_ERROR:
  22593. return "ECC Make Key failure";
  22594. case ECC_EXPORT_ERROR:
  22595. return "ECC Export Key failure";
  22596. case ECC_SHARED_ERROR:
  22597. return "ECC DHE shared failure";
  22598. case NOT_CA_ERROR:
  22599. return "Not a CA by basic constraint error";
  22600. case BAD_CERT_MANAGER_ERROR:
  22601. return "Bad Cert Manager error";
  22602. case OCSP_CERT_REVOKED:
  22603. return "OCSP Cert revoked";
  22604. case CRL_CERT_REVOKED:
  22605. #ifdef OPENSSL_EXTRA
  22606. return "certificate revoked";
  22607. #else
  22608. return "CRL Cert revoked";
  22609. #endif
  22610. case CRL_MISSING:
  22611. return "CRL missing, not loaded";
  22612. case MONITOR_SETUP_E:
  22613. return "CRL monitor setup error";
  22614. case THREAD_CREATE_E:
  22615. return "Thread creation problem";
  22616. case OCSP_NEED_URL:
  22617. return "OCSP need URL";
  22618. case OCSP_CERT_UNKNOWN:
  22619. return "OCSP Cert unknown";
  22620. case OCSP_LOOKUP_FAIL:
  22621. return "OCSP Responder lookup fail";
  22622. case MAX_CHAIN_ERROR:
  22623. return "Maximum Chain Depth Exceeded";
  22624. case COOKIE_ERROR:
  22625. return "DTLS Cookie Error";
  22626. case SEQUENCE_ERROR:
  22627. return "DTLS Sequence Error";
  22628. case SUITES_ERROR:
  22629. return "Suites Pointer Error";
  22630. case OUT_OF_ORDER_E:
  22631. return "Out of order message, fatal";
  22632. case BAD_KEA_TYPE_E:
  22633. return "Bad KEA type found";
  22634. case SANITY_CIPHER_E:
  22635. return "Sanity check on ciphertext failed";
  22636. case RECV_OVERFLOW_E:
  22637. return "Receive callback returned more than requested";
  22638. case GEN_COOKIE_E:
  22639. return "Generate Cookie Error";
  22640. case NO_PEER_VERIFY:
  22641. return "Need peer certificate verify Error";
  22642. case FWRITE_ERROR:
  22643. return "fwrite Error";
  22644. case CACHE_MATCH_ERROR:
  22645. return "Cache restore header match Error";
  22646. case UNKNOWN_SNI_HOST_NAME_E:
  22647. return "Unrecognized host name Error";
  22648. case UNKNOWN_MAX_FRAG_LEN_E:
  22649. return "Unrecognized max frag len Error";
  22650. case KEYUSE_SIGNATURE_E:
  22651. return "Key Use digitalSignature not set Error";
  22652. case KEYUSE_ENCIPHER_E:
  22653. return "Key Use keyEncipherment not set Error";
  22654. case EXTKEYUSE_AUTH_E:
  22655. return "Ext Key Use server/client auth not set Error";
  22656. case SEND_OOB_READ_E:
  22657. return "Send Callback Out of Bounds Read Error";
  22658. case SECURE_RENEGOTIATION_E:
  22659. return "Invalid Renegotiation Error";
  22660. case SESSION_TICKET_LEN_E:
  22661. return "Session Ticket Too Long Error";
  22662. case SESSION_TICKET_EXPECT_E:
  22663. return "Session Ticket Error";
  22664. case SCR_DIFFERENT_CERT_E:
  22665. return "SCR Different cert error";
  22666. case SESSION_SECRET_CB_E:
  22667. return "Session Secret Callback Error";
  22668. case NO_CHANGE_CIPHER_E:
  22669. return "Finished received from peer before Change Cipher Error";
  22670. case SANITY_MSG_E:
  22671. return "Sanity Check on message order Error";
  22672. case DUPLICATE_MSG_E:
  22673. return "Duplicate HandShake message Error";
  22674. case SNI_UNSUPPORTED:
  22675. return "Protocol version does not support SNI Error";
  22676. case SOCKET_PEER_CLOSED_E:
  22677. return "Peer closed underlying transport Error";
  22678. case BAD_TICKET_KEY_CB_SZ:
  22679. return "Bad user session ticket key callback Size Error";
  22680. case BAD_TICKET_MSG_SZ:
  22681. return "Bad session ticket message Size Error";
  22682. case BAD_TICKET_ENCRYPT:
  22683. return "Bad user ticket callback encrypt Error";
  22684. case DH_KEY_SIZE_E:
  22685. return "DH key too small Error";
  22686. case SNI_ABSENT_ERROR:
  22687. return "No Server Name Indication extension Error";
  22688. case RSA_SIGN_FAULT:
  22689. return "RSA Signature Fault Error";
  22690. case HANDSHAKE_SIZE_ERROR:
  22691. return "Handshake message too large Error";
  22692. case UNKNOWN_ALPN_PROTOCOL_NAME_E:
  22693. return "Unrecognized protocol name Error";
  22694. case BAD_CERTIFICATE_STATUS_ERROR:
  22695. return "Bad Certificate Status Message Error";
  22696. case OCSP_INVALID_STATUS:
  22697. return "Invalid OCSP Status Error";
  22698. case OCSP_WANT_READ:
  22699. return "OCSP nonblock wants read";
  22700. case RSA_KEY_SIZE_E:
  22701. return "RSA key too small";
  22702. case ECC_KEY_SIZE_E:
  22703. return "ECC key too small";
  22704. case DTLS_EXPORT_VER_E:
  22705. return "Version needs updated after code change or version mismatch";
  22706. case INPUT_SIZE_E:
  22707. return "Input size too large Error";
  22708. case CTX_INIT_MUTEX_E:
  22709. return "Initialize ctx mutex error";
  22710. case EXT_MASTER_SECRET_NEEDED_E:
  22711. return "Extended Master Secret must be enabled to resume EMS session";
  22712. case DTLS_POOL_SZ_E:
  22713. return "Maximum DTLS pool size exceeded";
  22714. case DECODE_E:
  22715. return "Decode handshake message error";
  22716. case WRITE_DUP_READ_E:
  22717. return "Write dup write side can't read error";
  22718. case WRITE_DUP_WRITE_E:
  22719. return "Write dup read side can't write error";
  22720. case INVALID_CERT_CTX_E:
  22721. return "Certificate context does not match request or not empty";
  22722. case BAD_KEY_SHARE_DATA:
  22723. return "The Key Share data contains group that wasn't in Client Hello";
  22724. case MISSING_HANDSHAKE_DATA:
  22725. return "The handshake message is missing required data";
  22726. case BAD_BINDER: /* OpenSSL compatibility expects this exact text */
  22727. return "binder does not verify";
  22728. case EXT_NOT_ALLOWED:
  22729. return "Extension type not allowed in handshake message type";
  22730. case INVALID_PARAMETER:
  22731. return "The security parameter is invalid";
  22732. case UNSUPPORTED_EXTENSION:
  22733. return "TLS Extension not requested by the client";
  22734. case PRF_MISSING:
  22735. return "Pseudo-random function is not enabled";
  22736. case KEY_SHARE_ERROR:
  22737. return "Key share extension did not contain a valid named group";
  22738. case POST_HAND_AUTH_ERROR:
  22739. return "Client will not do post handshake authentication";
  22740. case HRR_COOKIE_ERROR:
  22741. return "Cookie does not match one sent in HelloRetryRequest";
  22742. case MCAST_HIGHWATER_CB_E:
  22743. return "Multicast highwater callback returned error";
  22744. case ALERT_COUNT_E:
  22745. return "Alert Count exceeded error";
  22746. case EXT_MISSING:
  22747. return "Required TLS extension missing";
  22748. case DTLS_RETX_OVER_TX:
  22749. return "DTLS interrupting flight transmit with retransmit";
  22750. case DH_PARAMS_NOT_FFDHE_E:
  22751. return "Server DH parameters were not from the FFDHE set as required";
  22752. case TCA_INVALID_ID_TYPE:
  22753. return "TLS Extension Trusted CA ID type invalid";
  22754. case TCA_ABSENT_ERROR:
  22755. return "TLS Extension Trusted CA ID response absent";
  22756. case TSIP_MAC_DIGSZ_E:
  22757. return "TSIP MAC size invalid, must be sized for SHA-1 or SHA-256";
  22758. case CLIENT_CERT_CB_ERROR:
  22759. return "Error importing client cert or key from callback";
  22760. case SSL_SHUTDOWN_ALREADY_DONE_E:
  22761. return "Shutdown has already occurred";
  22762. case TLS13_SECRET_CB_E:
  22763. return "TLS1.3 Secret Callback Error";
  22764. case DTLS_SIZE_ERROR:
  22765. return "DTLS trying to send too much in single datagram error";
  22766. case NO_CERT_ERROR:
  22767. return "TLS1.3 No Certificate Set Error";
  22768. case APP_DATA_READY:
  22769. return "Application data is available for reading";
  22770. case TOO_MUCH_EARLY_DATA:
  22771. return "Too much early data";
  22772. case SOCKET_FILTERED_E:
  22773. return "Session stopped by network filter";
  22774. case UNSUPPORTED_CERTIFICATE:
  22775. return "Unsupported certificate type";
  22776. case HTTP_TIMEOUT:
  22777. return "HTTP timeout for OCSP or CRL req";
  22778. case HTTP_RECV_ERR:
  22779. return "HTTP Receive error";
  22780. case HTTP_HEADER_ERR:
  22781. return "HTTP Header error";
  22782. case HTTP_PROTO_ERR:
  22783. return "HTTP Protocol error";
  22784. case HTTP_STATUS_ERR:
  22785. return "HTTP Status error";
  22786. case HTTP_VERSION_ERR:
  22787. return "HTTP Version error";
  22788. case HTTP_APPSTR_ERR:
  22789. return "HTTP Application string error";
  22790. case UNSUPPORTED_PROTO_VERSION:
  22791. #ifdef OPENSSL_EXTRA
  22792. return "WRONG_SSL_VERSION";
  22793. #else
  22794. return "bad/unsupported protocol version";
  22795. #endif
  22796. case FALCON_KEY_SIZE_E:
  22797. return "Wrong key size for Falcon.";
  22798. case DILITHIUM_KEY_SIZE_E:
  22799. return "Wrong key size for Dilithium.";
  22800. case QUIC_TP_MISSING_E:
  22801. return "QUIC transport parameter not set";
  22802. case QUIC_WRONG_ENC_LEVEL:
  22803. return "QUIC data received at wrong encryption level";
  22804. case DTLS_CID_ERROR:
  22805. return "DTLS ConnectionID mismatch or missing";
  22806. case DTLS_TOO_MANY_FRAGMENTS_E:
  22807. return "Received too many fragmented messages from peer error";
  22808. case DUPLICATE_TLS_EXT_E:
  22809. return "Duplicate TLS extension in message.";
  22810. case WOLFSSL_ALPN_NOT_FOUND:
  22811. return "TLS extension not found";
  22812. case WOLFSSL_BAD_CERTTYPE:
  22813. return "Certificate type not supported";
  22814. case WOLFSSL_BAD_STAT:
  22815. return "bad status";
  22816. case WOLFSSL_BAD_PATH:
  22817. return "No certificates found at designated path";
  22818. case WOLFSSL_BAD_FILETYPE:
  22819. return "Data format not supported";
  22820. case WOLFSSL_BAD_FILE:
  22821. return "Input/output error on file";
  22822. case WOLFSSL_NOT_IMPLEMENTED:
  22823. return "Function not implemented";
  22824. case WOLFSSL_UNKNOWN:
  22825. return "Unknown algorithm (EVP)";
  22826. case WOLFSSL_FATAL_ERROR:
  22827. return "fatal error";
  22828. }
  22829. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  22830. defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
  22831. switch (error) {
  22832. /* TODO: -WOLFSSL_X509_V_ERR_CERT_SIGNATURE_FAILURE. Conflicts with
  22833. * -WOLFSSL_ERROR_WANT_CONNECT.
  22834. */
  22835. case -WOLFSSL_X509_V_ERR_CERT_NOT_YET_VALID:
  22836. return "certificate not yet valid";
  22837. case -WOLFSSL_X509_V_ERR_CERT_HAS_EXPIRED:
  22838. return "certificate has expired";
  22839. case -WOLFSSL_X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
  22840. return "certificate signature failure";
  22841. case -WOLFSSL_X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
  22842. return "format error in certificate's notAfter field";
  22843. case -WOLFSSL_X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
  22844. return "self-signed certificate in certificate chain";
  22845. case -WOLFSSL_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
  22846. return "unable to get local issuer certificate";
  22847. case -WOLFSSL_X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
  22848. return "unable to verify the first certificate";
  22849. case -WOLFSSL_X509_V_ERR_CERT_CHAIN_TOO_LONG:
  22850. return "certificate chain too long";
  22851. case -WOLFSSL_X509_V_ERR_CERT_REVOKED:
  22852. return "certificate revoked";
  22853. case -WOLFSSL_X509_V_ERR_INVALID_CA:
  22854. return "invalid CA certificate";
  22855. case -WOLFSSL_X509_V_ERR_PATH_LENGTH_EXCEEDED:
  22856. return "path length constraint exceeded";
  22857. case -WOLFSSL_X509_V_ERR_CERT_REJECTED:
  22858. return "certificate rejected";
  22859. case -WOLFSSL_X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
  22860. return "subject issuer mismatch";
  22861. }
  22862. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL || HAVE_WEBSERVER || HAVE_MEMCACHED */
  22863. return "unknown error number";
  22864. #endif /* NO_ERROR_STRINGS */
  22865. }
  22866. #ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES
  22867. #include <wolfssl/debug-trace-error-codes.h>
  22868. #endif
  22869. const char* wolfSSL_ERR_func_error_string(unsigned long e)
  22870. {
  22871. (void)e;
  22872. WOLFSSL_MSG("wolfSSL_ERR_func_error_string does not return the name of "
  22873. "the function that failed. Please inspect the wolfSSL debug "
  22874. "logs to determine where the error occurred.");
  22875. return "";
  22876. }
  22877. /* return library name
  22878. * @param e error code
  22879. * @return text library name,
  22880. * if there is no suitable library found, returns empty string
  22881. */
  22882. const char* wolfSSL_ERR_lib_error_string(unsigned long e)
  22883. {
  22884. int libe = 0;
  22885. (void)libe;
  22886. (void)e;
  22887. #if defined(OPENSSL_EXTRA)
  22888. libe = wolfSSL_ERR_GET_LIB(e);
  22889. switch (libe) {
  22890. case ERR_LIB_PEM:
  22891. return "wolfSSL PEM routines";
  22892. case ERR_LIB_EVP:
  22893. return "wolfSSL digital envelope routines";
  22894. default:
  22895. return "";
  22896. }
  22897. #else
  22898. return "";
  22899. #endif
  22900. }
  22901. void SetErrorString(int error, char* str)
  22902. {
  22903. XSTRNCPY(str, wolfSSL_ERR_reason_error_string((unsigned long)error), WOLFSSL_MAX_ERROR_SZ);
  22904. str[WOLFSSL_MAX_ERROR_SZ-1] = 0;
  22905. }
  22906. #ifdef NO_CIPHER_SUITE_ALIASES
  22907. #ifndef NO_ERROR_STRINGS
  22908. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  22909. #define SUITE_INFO(x,y,z,w,v,u) {(x),(y),(z),(w),(v),(u),WOLFSSL_CIPHER_SUITE_FLAG_NONE}
  22910. #define SUITE_ALIAS(x,z,w,v,u) /* null expansion */
  22911. #else
  22912. #define SUITE_INFO(x,y,z,w,v,u) {(x),(y),(z),(w),WOLFSSL_CIPHER_SUITE_FLAG_NONE}
  22913. #define SUITE_ALIAS(x,z,w,v,u) /* null expansion */
  22914. #endif
  22915. #else
  22916. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  22917. #define SUITE_INFO(x,y,z,w,v,u) {(x),(z),(w),(v),(u),WOLFSSL_CIPHER_SUITE_FLAG_NONE}
  22918. #define SUITE_ALIAS(x,z,w,v,u) /* null expansion */
  22919. #else
  22920. #define SUITE_INFO(x,y,z,w,v,u) {(x),(z),(w),WOLFSSL_CIPHER_SUITE_FLAG_NONE}
  22921. #define SUITE_ALIAS(x,z,w,v,u) /* null expansion */
  22922. #endif
  22923. #endif
  22924. #else /* !NO_CIPHER_SUITE_ALIASES */
  22925. /* note that the comma is included at the end of the SUITE_ALIAS() macro
  22926. * definitions, to allow aliases to be gated out by the above null macros
  22927. * in the NO_CIPHER_SUITE_ALIASES section.
  22928. */
  22929. #ifndef NO_ERROR_STRINGS
  22930. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) || \
  22931. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX)
  22932. #define SUITE_INFO(x,y,z,w,v,u) {(x),(y),(z),(w),(v),(u),WOLFSSL_CIPHER_SUITE_FLAG_NONE}
  22933. #define SUITE_ALIAS(x,z,w,v,u) {(x),"",(z),(w),(v),(u),WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS},
  22934. #else
  22935. #define SUITE_INFO(x,y,z,w,v,u) {(x),(y),(z),(w),WOLFSSL_CIPHER_SUITE_FLAG_NONE}
  22936. #define SUITE_ALIAS(x,z,w,v,u) {(x),"",(z),(w),WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS},
  22937. #endif
  22938. #else
  22939. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT) || \
  22940. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX)
  22941. #define SUITE_INFO(x,y,z,w,v,u) {(x),(z),(w),(v),(u),WOLFSSL_CIPHER_SUITE_FLAG_NONE}
  22942. #define SUITE_ALIAS(x,z,w,v,u) {(x),(z),(w),(v),(u),WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS},
  22943. #else
  22944. #define SUITE_INFO(x,y,z,w,v,u) {(x),(z),(w),WOLFSSL_CIPHER_SUITE_FLAG_NONE}
  22945. #define SUITE_ALIAS(x,z,w,v,u) {(x),(z),(w),WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS},
  22946. #endif
  22947. #endif
  22948. #endif /* NO_CIPHER_SUITE_ALIASES */
  22949. static const CipherSuiteInfo cipher_names[] =
  22950. {
  22951. #ifdef BUILD_TLS_AES_128_GCM_SHA256
  22952. SUITE_INFO("TLS13-AES128-GCM-SHA256","TLS_AES_128_GCM_SHA256",TLS13_BYTE,TLS_AES_128_GCM_SHA256, TLSv1_3_MINOR, SSLv3_MAJOR),
  22953. #endif
  22954. #ifdef BUILD_TLS_AES_256_GCM_SHA384
  22955. SUITE_INFO("TLS13-AES256-GCM-SHA384","TLS_AES_256_GCM_SHA384",TLS13_BYTE,TLS_AES_256_GCM_SHA384, TLSv1_3_MINOR, SSLv3_MAJOR),
  22956. #endif
  22957. #ifdef BUILD_TLS_CHACHA20_POLY1305_SHA256
  22958. SUITE_INFO("TLS13-CHACHA20-POLY1305-SHA256","TLS_CHACHA20_POLY1305_SHA256",TLS13_BYTE,TLS_CHACHA20_POLY1305_SHA256, TLSv1_3_MINOR, SSLv3_MAJOR),
  22959. #endif
  22960. #ifdef BUILD_TLS_AES_128_CCM_SHA256
  22961. SUITE_INFO("TLS13-AES128-CCM-SHA256","TLS_AES_128_CCM_SHA256",TLS13_BYTE,TLS_AES_128_CCM_SHA256, TLSv1_3_MINOR, SSLv3_MAJOR),
  22962. #endif
  22963. #ifdef BUILD_TLS_AES_128_CCM_8_SHA256
  22964. SUITE_INFO("TLS13-AES128-CCM-8-SHA256","TLS_AES_128_CCM_8_SHA256",TLS13_BYTE,TLS_AES_128_CCM_8_SHA256,TLSv1_3_MINOR, SSLv3_MAJOR),
  22965. SUITE_ALIAS("TLS13-AES128-CCM8-SHA256",TLS13_BYTE,TLS_AES_128_CCM_8_SHA256,TLSv1_3_MINOR, SSLv3_MAJOR)
  22966. #endif
  22967. #ifdef BUILD_TLS_SM4_GCM_SM3
  22968. SUITE_INFO("TLS13-SM4-GCM-SM3","TLS_SM4_GCM_SM3",CIPHER_BYTE,TLS_SM4_GCM_SM3, TLSv1_3_MINOR, SSLv3_MAJOR),
  22969. #endif
  22970. #ifdef BUILD_TLS_SM4_CCM_SM3
  22971. SUITE_INFO("TLS13-SM4-CCM-SM3","TLS_SM4_CCM_SM3",CIPHER_BYTE,TLS_SM4_CCM_SM3, TLSv1_3_MINOR, SSLv3_MAJOR),
  22972. #endif
  22973. #ifdef BUILD_TLS_SHA256_SHA256
  22974. SUITE_INFO("TLS13-SHA256-SHA256","TLS_SHA256_SHA256",ECC_BYTE,TLS_SHA256_SHA256,TLSv1_3_MINOR, SSLv3_MAJOR),
  22975. #endif
  22976. #ifdef BUILD_TLS_SHA384_SHA384
  22977. SUITE_INFO("TLS13-SHA384-SHA384","TLS_SHA384_SHA384",ECC_BYTE,TLS_SHA384_SHA384,TLSv1_3_MINOR, SSLv3_MAJOR),
  22978. #endif
  22979. #ifndef WOLFSSL_NO_TLS12
  22980. #ifdef BUILD_SSL_RSA_WITH_RC4_128_SHA
  22981. SUITE_INFO("RC4-SHA","SSL_RSA_WITH_RC4_128_SHA",CIPHER_BYTE,SSL_RSA_WITH_RC4_128_SHA,SSLv3_MINOR,SSLv3_MAJOR),
  22982. #endif
  22983. #ifdef BUILD_SSL_RSA_WITH_RC4_128_MD5
  22984. SUITE_INFO("RC4-MD5","SSL_RSA_WITH_RC4_128_MD5",CIPHER_BYTE,SSL_RSA_WITH_RC4_128_MD5,SSLv3_MINOR,SSLv3_MAJOR),
  22985. #endif
  22986. #ifdef BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA
  22987. SUITE_INFO("DES-CBC3-SHA","SSL_RSA_WITH_3DES_EDE_CBC_SHA",CIPHER_BYTE,SSL_RSA_WITH_3DES_EDE_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
  22988. #endif
  22989. #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA
  22990. SUITE_INFO("AES128-SHA","TLS_RSA_WITH_AES_128_CBC_SHA",CIPHER_BYTE,TLS_RSA_WITH_AES_128_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
  22991. #endif
  22992. #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA
  22993. SUITE_INFO("AES256-SHA","TLS_RSA_WITH_AES_256_CBC_SHA",CIPHER_BYTE,TLS_RSA_WITH_AES_256_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
  22994. #endif
  22995. #ifdef BUILD_TLS_RSA_WITH_NULL_MD5
  22996. SUITE_INFO("NULL-MD5","TLS_RSA_WITH_NULL_MD5",CIPHER_BYTE,TLS_RSA_WITH_NULL_MD5,SSLv3_MINOR,SSLv3_MAJOR),
  22997. #endif
  22998. #ifdef BUILD_TLS_RSA_WITH_NULL_SHA
  22999. SUITE_INFO("NULL-SHA","TLS_RSA_WITH_NULL_SHA",CIPHER_BYTE,TLS_RSA_WITH_NULL_SHA,SSLv3_MINOR,SSLv3_MAJOR),
  23000. #endif
  23001. #ifdef BUILD_TLS_RSA_WITH_NULL_SHA256
  23002. SUITE_INFO("NULL-SHA256","TLS_RSA_WITH_NULL_SHA256",CIPHER_BYTE,TLS_RSA_WITH_NULL_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
  23003. #endif
  23004. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
  23005. SUITE_INFO("DHE-RSA-AES128-SHA","TLS_DHE_RSA_WITH_AES_128_CBC_SHA",CIPHER_BYTE,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
  23006. #endif
  23007. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
  23008. SUITE_INFO("DHE-RSA-AES256-SHA","TLS_DHE_RSA_WITH_AES_256_CBC_SHA",CIPHER_BYTE,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
  23009. #endif
  23010. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
  23011. SUITE_INFO("DHE-PSK-AES256-GCM-SHA384","TLS_DHE_PSK_WITH_AES_256_GCM_SHA384",CIPHER_BYTE,TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,TLSv1_2_MINOR,SSLv3_MAJOR),
  23012. #endif
  23013. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
  23014. SUITE_INFO("DHE-PSK-AES128-GCM-SHA256","TLS_DHE_PSK_WITH_AES_128_GCM_SHA256",CIPHER_BYTE,TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
  23015. #endif
  23016. #ifdef BUILD_TLS_PSK_WITH_AES_256_GCM_SHA384
  23017. SUITE_INFO("PSK-AES256-GCM-SHA384","TLS_PSK_WITH_AES_256_GCM_SHA384",CIPHER_BYTE,TLS_PSK_WITH_AES_256_GCM_SHA384,TLSv1_2_MINOR,SSLv3_MAJOR),
  23018. #endif
  23019. #ifdef BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256
  23020. SUITE_INFO("PSK-AES128-GCM-SHA256","TLS_PSK_WITH_AES_128_GCM_SHA256",CIPHER_BYTE,TLS_PSK_WITH_AES_128_GCM_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
  23021. #endif
  23022. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
  23023. SUITE_INFO("DHE-PSK-AES256-CBC-SHA384","TLS_DHE_PSK_WITH_AES_256_CBC_SHA384",CIPHER_BYTE,TLS_DHE_PSK_WITH_AES_256_CBC_SHA384,TLSv1_MINOR,SSLv3_MAJOR),
  23024. #endif
  23025. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
  23026. SUITE_INFO("DHE-PSK-AES128-CBC-SHA256","TLS_DHE_PSK_WITH_AES_128_CBC_SHA256",CIPHER_BYTE,TLS_DHE_PSK_WITH_AES_128_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  23027. #endif
  23028. #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA384
  23029. SUITE_INFO("PSK-AES256-CBC-SHA384","TLS_PSK_WITH_AES_256_CBC_SHA384",CIPHER_BYTE,TLS_PSK_WITH_AES_256_CBC_SHA384,TLSv1_MINOR,SSLv3_MAJOR),
  23030. #endif
  23031. #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA256
  23032. SUITE_INFO("PSK-AES128-CBC-SHA256","TLS_PSK_WITH_AES_128_CBC_SHA256",CIPHER_BYTE,TLS_PSK_WITH_AES_128_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  23033. #endif
  23034. #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA
  23035. SUITE_INFO("PSK-AES128-CBC-SHA","TLS_PSK_WITH_AES_128_CBC_SHA",CIPHER_BYTE,TLS_PSK_WITH_AES_128_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  23036. #endif
  23037. #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA
  23038. SUITE_INFO("PSK-AES256-CBC-SHA","TLS_PSK_WITH_AES_256_CBC_SHA",CIPHER_BYTE,TLS_PSK_WITH_AES_256_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23039. #endif
  23040. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CCM
  23041. SUITE_INFO("DHE-PSK-AES128-CCM","TLS_DHE_PSK_WITH_AES_128_CCM",ECC_BYTE,TLS_DHE_PSK_WITH_AES_128_CCM,TLSv1_MINOR,SSLv3_MAJOR),
  23042. #endif
  23043. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_CCM
  23044. SUITE_INFO("DHE-PSK-AES256-CCM","TLS_DHE_PSK_WITH_AES_256_CCM",ECC_BYTE,TLS_DHE_PSK_WITH_AES_256_CCM,TLSv1_MINOR,SSLv3_MAJOR),
  23045. #endif
  23046. #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM
  23047. SUITE_INFO("PSK-AES128-CCM","TLS_PSK_WITH_AES_128_CCM",ECC_BYTE,TLS_PSK_WITH_AES_128_CCM,TLSv1_MINOR,SSLv3_MAJOR),
  23048. #endif
  23049. #ifdef BUILD_TLS_PSK_WITH_AES_256_CCM
  23050. SUITE_INFO("PSK-AES256-CCM","TLS_PSK_WITH_AES_256_CCM",ECC_BYTE,TLS_PSK_WITH_AES_256_CCM,TLSv1_MINOR,SSLv3_MAJOR),
  23051. #endif
  23052. #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM_8
  23053. SUITE_INFO("PSK-AES128-CCM-8","TLS_PSK_WITH_AES_128_CCM_8",ECC_BYTE,TLS_PSK_WITH_AES_128_CCM_8,TLSv1_MINOR,SSLv3_MAJOR),
  23054. SUITE_ALIAS("PSK-AES128-CCM8",ECC_BYTE,TLS_PSK_WITH_AES_128_CCM_8,TLSv1_MINOR,SSLv3_MAJOR)
  23055. #endif
  23056. #ifdef BUILD_TLS_PSK_WITH_AES_256_CCM_8
  23057. SUITE_INFO("PSK-AES256-CCM-8","TLS_PSK_WITH_AES_256_CCM_8",ECC_BYTE,TLS_PSK_WITH_AES_256_CCM_8,TLSv1_MINOR,SSLv3_MAJOR),
  23058. SUITE_ALIAS("PSK-AES256-CCM8",ECC_BYTE,TLS_PSK_WITH_AES_256_CCM_8,TLSv1_MINOR,SSLv3_MAJOR)
  23059. #endif
  23060. #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA384
  23061. SUITE_INFO("DHE-PSK-NULL-SHA384","TLS_DHE_PSK_WITH_NULL_SHA384",CIPHER_BYTE,TLS_DHE_PSK_WITH_NULL_SHA384,TLSv1_MINOR,SSLv3_MAJOR),
  23062. #endif
  23063. #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA256
  23064. SUITE_INFO("DHE-PSK-NULL-SHA256","TLS_DHE_PSK_WITH_NULL_SHA256",CIPHER_BYTE,TLS_DHE_PSK_WITH_NULL_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  23065. #endif
  23066. #ifdef BUILD_TLS_PSK_WITH_NULL_SHA384
  23067. SUITE_INFO("PSK-NULL-SHA384","TLS_PSK_WITH_NULL_SHA384",CIPHER_BYTE,TLS_PSK_WITH_NULL_SHA384,TLSv1_MINOR,SSLv3_MAJOR),
  23068. #endif
  23069. #ifdef BUILD_TLS_PSK_WITH_NULL_SHA256
  23070. SUITE_INFO("PSK-NULL-SHA256","TLS_PSK_WITH_NULL_SHA256",CIPHER_BYTE,TLS_PSK_WITH_NULL_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  23071. #endif
  23072. #ifdef BUILD_TLS_PSK_WITH_NULL_SHA
  23073. SUITE_INFO("PSK-NULL-SHA","TLS_PSK_WITH_NULL_SHA",CIPHER_BYTE,TLS_PSK_WITH_NULL_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  23074. #endif
  23075. #ifdef BUILD_TLS_RSA_WITH_AES_128_CCM_8
  23076. SUITE_INFO("AES128-CCM-8","TLS_RSA_WITH_AES_128_CCM_8",ECC_BYTE,TLS_RSA_WITH_AES_128_CCM_8, TLSv1_2_MINOR, SSLv3_MAJOR),
  23077. SUITE_ALIAS("AES128-CCM8",ECC_BYTE,TLS_RSA_WITH_AES_128_CCM_8, TLSv1_2_MINOR, SSLv3_MAJOR)
  23078. #endif
  23079. #ifdef BUILD_TLS_RSA_WITH_AES_256_CCM_8
  23080. SUITE_INFO("AES256-CCM-8","TLS_RSA_WITH_AES_256_CCM_8",ECC_BYTE,TLS_RSA_WITH_AES_256_CCM_8, TLSv1_2_MINOR, SSLv3_MAJOR),
  23081. SUITE_ALIAS("AES256-CCM8",ECC_BYTE,TLS_RSA_WITH_AES_256_CCM_8, TLSv1_2_MINOR, SSLv3_MAJOR)
  23082. #endif
  23083. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM
  23084. SUITE_INFO("ECDHE-ECDSA-AES128-CCM","TLS_ECDHE_ECDSA_WITH_AES_128_CCM",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_128_CCM, TLSv1_2_MINOR, SSLv3_MAJOR),
  23085. #endif
  23086. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
  23087. SUITE_INFO("ECDHE-ECDSA-AES128-CCM-8","TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, TLSv1_2_MINOR, SSLv3_MAJOR),
  23088. SUITE_ALIAS("ECDHE-ECDSA-AES128-CCM8",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, TLSv1_2_MINOR, SSLv3_MAJOR)
  23089. #endif
  23090. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8
  23091. SUITE_INFO("ECDHE-ECDSA-AES256-CCM-8","TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8, TLSv1_2_MINOR, SSLv3_MAJOR),
  23092. SUITE_ALIAS("ECDHE-ECDSA-AES256-CCM8",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8, TLSv1_2_MINOR, SSLv3_MAJOR)
  23093. #endif
  23094. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
  23095. SUITE_INFO("ECDHE-RSA-AES128-SHA","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",ECC_BYTE,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  23096. #endif
  23097. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
  23098. SUITE_INFO("ECDHE-RSA-AES256-SHA","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",ECC_BYTE,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  23099. #endif
  23100. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
  23101. SUITE_INFO("ECDHE-ECDSA-AES128-SHA","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23102. #endif
  23103. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
  23104. SUITE_INFO("ECDHE-ECDSA-AES256-SHA","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23105. #endif
  23106. #ifdef BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA
  23107. SUITE_INFO("ECDHE-RSA-RC4-SHA","TLS_ECDHE_RSA_WITH_RC4_128_SHA",ECC_BYTE,TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23108. #endif
  23109. #ifdef BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
  23110. SUITE_INFO("ECDHE-RSA-DES-CBC3-SHA","TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",ECC_BYTE,TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23111. #endif
  23112. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
  23113. SUITE_INFO("ECDHE-ECDSA-RC4-SHA","TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23114. #endif
  23115. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
  23116. SUITE_INFO("ECDHE-ECDSA-DES-CBC3-SHA","TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23117. #endif
  23118. #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256
  23119. SUITE_INFO("AES128-SHA256","TLS_RSA_WITH_AES_128_CBC_SHA256",CIPHER_BYTE,TLS_RSA_WITH_AES_128_CBC_SHA256, TLSv1_MINOR, SSLv3_MAJOR),
  23120. #endif
  23121. #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA256
  23122. SUITE_INFO("AES256-SHA256","TLS_RSA_WITH_AES_256_CBC_SHA256",CIPHER_BYTE,TLS_RSA_WITH_AES_256_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23123. #endif
  23124. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
  23125. SUITE_INFO("DHE-RSA-AES128-SHA256","TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",CIPHER_BYTE,TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23126. #endif
  23127. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
  23128. SUITE_INFO("DHE-RSA-AES256-SHA256","TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",CIPHER_BYTE,TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23129. #endif
  23130. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
  23131. SUITE_INFO("ECDH-RSA-AES128-SHA","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",ECC_BYTE,TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23132. #endif
  23133. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
  23134. SUITE_INFO("ECDH-RSA-AES256-SHA","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",ECC_BYTE,TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23135. #endif
  23136. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
  23137. SUITE_INFO("ECDH-ECDSA-AES128-SHA","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",ECC_BYTE,TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23138. #endif
  23139. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
  23140. SUITE_INFO("ECDH-ECDSA-AES256-SHA","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",ECC_BYTE,TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23141. #endif
  23142. #ifdef BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA
  23143. SUITE_INFO("ECDH-RSA-RC4-SHA","TLS_ECDH_RSA_WITH_RC4_128_SHA",ECC_BYTE,TLS_ECDH_RSA_WITH_RC4_128_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23144. #endif
  23145. #ifdef BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
  23146. SUITE_INFO("ECDH-RSA-DES-CBC3-SHA","TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",ECC_BYTE,TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23147. #endif
  23148. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA
  23149. SUITE_INFO("ECDH-ECDSA-RC4-SHA","TLS_ECDH_ECDSA_WITH_RC4_128_SHA",ECC_BYTE,TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23150. #endif
  23151. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
  23152. SUITE_INFO("ECDH-ECDSA-DES-CBC3-SHA","TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",ECC_BYTE,TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23153. #endif
  23154. #ifdef BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256
  23155. SUITE_INFO("AES128-GCM-SHA256","TLS_RSA_WITH_AES_128_GCM_SHA256",CIPHER_BYTE,TLS_RSA_WITH_AES_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23156. #endif
  23157. #ifdef BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384
  23158. SUITE_INFO("AES256-GCM-SHA384","TLS_RSA_WITH_AES_256_GCM_SHA384",CIPHER_BYTE,TLS_RSA_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
  23159. #endif
  23160. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
  23161. SUITE_INFO("DHE-RSA-AES128-GCM-SHA256","TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",CIPHER_BYTE,TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23162. #endif
  23163. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
  23164. SUITE_INFO("DHE-RSA-AES256-GCM-SHA384","TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",CIPHER_BYTE,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
  23165. #endif
  23166. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  23167. SUITE_INFO("ECDHE-RSA-AES128-GCM-SHA256","TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",ECC_BYTE,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23168. #endif
  23169. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
  23170. SUITE_INFO("ECDHE-RSA-AES256-GCM-SHA384","TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",ECC_BYTE,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
  23171. #endif
  23172. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
  23173. SUITE_INFO("ECDHE-ECDSA-AES128-GCM-SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23174. #endif
  23175. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
  23176. SUITE_INFO("ECDHE-ECDSA-AES256-GCM-SHA384","TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
  23177. #endif
  23178. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
  23179. SUITE_INFO("ECDH-RSA-AES128-GCM-SHA256","TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256",ECC_BYTE,TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23180. #endif
  23181. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
  23182. SUITE_INFO("ECDH-RSA-AES256-GCM-SHA384","TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384",ECC_BYTE,TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
  23183. #endif
  23184. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
  23185. SUITE_INFO("ECDH-ECDSA-AES128-GCM-SHA256","TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256",ECC_BYTE,TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23186. #endif
  23187. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
  23188. SUITE_INFO("ECDH-ECDSA-AES256-GCM-SHA384","TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384",ECC_BYTE,TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
  23189. #endif
  23190. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
  23191. SUITE_INFO("CAMELLIA128-SHA","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA",CIPHER_BYTE,TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  23192. #endif
  23193. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
  23194. SUITE_INFO("DHE-RSA-CAMELLIA128-SHA","TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA",CIPHER_BYTE,TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  23195. #endif
  23196. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
  23197. SUITE_INFO("CAMELLIA256-SHA","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA",CIPHER_BYTE,TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  23198. #endif
  23199. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
  23200. SUITE_INFO("DHE-RSA-CAMELLIA256-SHA","TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA",CIPHER_BYTE,TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  23201. #endif
  23202. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
  23203. SUITE_INFO("CAMELLIA128-SHA256","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256",CIPHER_BYTE,TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  23204. #endif
  23205. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
  23206. SUITE_INFO("DHE-RSA-CAMELLIA128-SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256",CIPHER_BYTE,TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  23207. #endif
  23208. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256
  23209. SUITE_INFO("CAMELLIA256-SHA256","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256",CIPHER_BYTE,TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  23210. #endif
  23211. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
  23212. SUITE_INFO("DHE-RSA-CAMELLIA256-SHA256","TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256",CIPHER_BYTE,TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  23213. #endif
  23214. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
  23215. SUITE_INFO("ECDHE-RSA-AES128-SHA256","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",ECC_BYTE,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23216. #endif
  23217. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
  23218. SUITE_INFO("ECDHE-ECDSA-AES128-SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23219. #endif
  23220. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
  23221. SUITE_INFO("ECDH-RSA-AES128-SHA256","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256",ECC_BYTE,TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23222. #endif
  23223. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
  23224. SUITE_INFO("ECDH-ECDSA-AES128-SHA256","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256",ECC_BYTE,TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23225. #endif
  23226. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
  23227. SUITE_INFO("ECDHE-RSA-AES256-SHA384","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",ECC_BYTE,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
  23228. #endif
  23229. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
  23230. SUITE_INFO("ECDHE-ECDSA-AES256-SHA384","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
  23231. #endif
  23232. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
  23233. SUITE_INFO("ECDH-RSA-AES256-SHA384","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384",ECC_BYTE,TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
  23234. #endif
  23235. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
  23236. SUITE_INFO("ECDH-ECDSA-AES256-SHA384","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384",ECC_BYTE,TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
  23237. #endif
  23238. #ifdef BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
  23239. SUITE_INFO("ECDHE-RSA-CHACHA20-POLY1305","TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23240. #endif
  23241. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
  23242. SUITE_INFO("ECDHE-ECDSA-CHACHA20-POLY1305","TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23243. #endif
  23244. #ifdef BUILD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
  23245. SUITE_INFO("DHE-RSA-CHACHA20-POLY1305","TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23246. #endif
  23247. #ifdef BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
  23248. SUITE_INFO("ECDHE-RSA-CHACHA20-POLY1305-OLD","TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256",CHACHA_BYTE,TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23249. #endif
  23250. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256
  23251. SUITE_INFO("ECDHE-ECDSA-CHACHA20-POLY1305-OLD","TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256",CHACHA_BYTE,TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23252. #endif
  23253. #ifdef BUILD_TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
  23254. SUITE_INFO("DHE-RSA-CHACHA20-POLY1305-OLD","TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256",CHACHA_BYTE,TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23255. #endif
  23256. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  23257. SUITE_INFO("ECDHE-ECDSA-SM4-CBC-SM3","TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3",SM_BYTE,TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3, TLSv1_2_MINOR, SSLv3_MAJOR),
  23258. #endif
  23259. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3
  23260. SUITE_INFO("ECDHE-ECDSA-SM4-GCM-SM3","TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3",SM_BYTE,TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3, TLSv1_2_MINOR, SSLv3_MAJOR),
  23261. #endif
  23262. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3
  23263. SUITE_INFO("ECDHE-ECDSA-SM4-CCM-SM3","TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3",SM_BYTE,TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3, TLSv1_2_MINOR, SSLv3_MAJOR),
  23264. #endif
  23265. #ifdef BUILD_TLS_DH_anon_WITH_AES_128_CBC_SHA
  23266. SUITE_INFO("ADH-AES128-SHA","TLS_DH_anon_WITH_AES_128_CBC_SHA",CIPHER_BYTE,TLS_DH_anon_WITH_AES_128_CBC_SHA, TLSv1_2_MINOR, SSLv3_MAJOR),
  23267. #endif
  23268. #ifdef BUILD_TLS_DH_anon_WITH_AES_256_GCM_SHA384
  23269. SUITE_INFO("ADH-AES256-GCM-SHA384","TLS_DH_anon_WITH_AES_256_GCM_SHA384",CIPHER_BYTE,TLS_DH_anon_WITH_AES_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
  23270. #endif
  23271. #ifdef HAVE_RENEGOTIATION_INDICATION
  23272. SUITE_INFO("RENEGOTIATION-INFO","TLS_EMPTY_RENEGOTIATION_INFO_SCSV",CIPHER_BYTE,TLS_EMPTY_RENEGOTIATION_INFO_SCSV,SSLv3_MINOR,SSLv3_MAJOR),
  23273. #endif
  23274. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_NULL_SHA
  23275. SUITE_INFO("ECDHE-ECDSA-NULL-SHA","TLS_ECDHE_ECDSA_WITH_NULL_SHA",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23276. #endif
  23277. #ifdef BUILD_TLS_ECDHE_PSK_WITH_NULL_SHA256
  23278. SUITE_INFO("ECDHE-PSK-NULL-SHA256","TLS_ECDHE_PSK_WITH_NULL_SHA256",ECC_BYTE,TLS_ECDHE_PSK_WITH_NULL_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  23279. #endif
  23280. #ifdef BUILD_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
  23281. SUITE_INFO("ECDHE-PSK-AES128-CBC-SHA256","TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256",ECC_BYTE,TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  23282. #endif
  23283. #ifdef BUILD_TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256
  23284. SUITE_INFO("ECDHE-PSK-AES128-GCM-SHA256","TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256",ECDHE_PSK_BYTE,TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  23285. #endif
  23286. #ifdef BUILD_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256
  23287. SUITE_INFO("PSK-CHACHA20-POLY1305","TLS_PSK_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_PSK_WITH_CHACHA20_POLY1305_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
  23288. #endif
  23289. #ifdef BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256
  23290. SUITE_INFO("ECDHE-PSK-CHACHA20-POLY1305","TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
  23291. #endif
  23292. #ifdef BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256
  23293. SUITE_INFO("DHE-PSK-CHACHA20-POLY1305","TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
  23294. #endif
  23295. #ifdef BUILD_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
  23296. SUITE_INFO("EDH-RSA-DES-CBC3-SHA","TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA",CIPHER_BYTE,TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  23297. #endif
  23298. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256
  23299. SUITE_INFO("ECDHE-ECDSA-ARIA128-GCM-SHA256","TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256, TLSv1_2_MINOR, SSLv3_MAJOR),
  23300. #endif
  23301. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384
  23302. SUITE_INFO("ECDHE-ECDSA-ARIA256-GCM-SHA384","TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384, TLSv1_2_MINOR, SSLv3_MAJOR),
  23303. #endif
  23304. #ifdef BUILD_WDM_WITH_NULL_SHA256
  23305. SUITE_INFO("WDM-NULL-SHA256","WDM_WITH_NULL_SHA256",CIPHER_BYTE,WDM_WITH_NULL_SHA256, TLSv1_3_MINOR, SSLv3_MAJOR)
  23306. #endif
  23307. #endif /* WOLFSSL_NO_TLS12 */
  23308. };
  23309. /* returns the cipher_names array */
  23310. const CipherSuiteInfo* GetCipherNames(void)
  23311. {
  23312. return cipher_names;
  23313. }
  23314. /* returns the number of elements in the cipher_names array */
  23315. int GetCipherNamesSize(void)
  23316. {
  23317. return (int)(sizeof(cipher_names) / sizeof(CipherSuiteInfo));
  23318. }
  23319. const char* GetCipherNameInternal(const byte cipherSuite0, const byte cipherSuite)
  23320. {
  23321. int i;
  23322. const char* nameInternal = "None";
  23323. for (i = 0; i < GetCipherNamesSize(); i++) {
  23324. if ((cipher_names[i].cipherSuite0 == cipherSuite0) &&
  23325. (cipher_names[i].cipherSuite == cipherSuite)
  23326. #ifndef NO_CIPHER_SUITE_ALIASES
  23327. && (! (cipher_names[i].flags & WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS))
  23328. #endif
  23329. ) {
  23330. nameInternal = cipher_names[i].name;
  23331. break;
  23332. }
  23333. }
  23334. return nameInternal;
  23335. }
  23336. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
  23337. /* Segment cipher name into n[n0,n1,n2,n4]
  23338. * @param cipher a pointer to WOLFSSL_CIPHER
  23339. * @param n return segment cipher name
  23340. * return cipher name if cipher is in the list,
  23341. * otherwise NULL
  23342. */
  23343. const char* GetCipherSegment(const WOLFSSL_CIPHER* cipher, char n[][MAX_SEGMENT_SZ])
  23344. {
  23345. int i,j,k;
  23346. int strLen;
  23347. unsigned long offset;
  23348. const char* name;
  23349. /* sanity check */
  23350. if (cipher == NULL || n == NULL)
  23351. return NULL;
  23352. offset = cipher->offset;
  23353. if (offset >= (unsigned long)GetCipherNamesSize())
  23354. return NULL;
  23355. name = cipher_names[offset].name;
  23356. if (name == NULL)
  23357. return NULL;
  23358. /* Segment cipher name into n[n0,n1,n2,n4]
  23359. * These are used later for comparisons to create:
  23360. * keaStr, authStr, encStr, macStr
  23361. *
  23362. * If cipher_name = ECDHE-ECDSA-AES256-SHA
  23363. * then n0 = "ECDHE", n1 = "ECDSA", n2 = "AES256", n3 = "SHA"
  23364. * and n = [n0,n1,n2,n3,0]
  23365. */
  23366. strLen = (int)XSTRLEN(name);
  23367. for (i = 0, j = 0, k = 0; i <= strLen; i++) {
  23368. if (k >= MAX_SEGMENTS || j >= MAX_SEGMENT_SZ)
  23369. break;
  23370. if (name[i] != '-' && name[i] != '\0') {
  23371. n[k][j] = name[i]; /* Fill kth segment string until '-' */
  23372. j++;
  23373. }
  23374. else {
  23375. n[k][j] = '\0';
  23376. j = 0;
  23377. k++;
  23378. }
  23379. }
  23380. return name;
  23381. }
  23382. /* gcc-12 and later, building with ASAN at -O2 and higher, generate spurious
  23383. * stringop-overread warnings on some (but not all...) reads of n[1] in
  23384. * GetCipherKeaStr().
  23385. */
  23386. #if defined(__GNUC__) && __GNUC__ > 11 && defined(__SANITIZE_ADDRESS__)
  23387. PRAGMA_GCC_DIAG_PUSH
  23388. PRAGMA_GCC("GCC diagnostic ignored \"-Wstringop-overread\"")
  23389. #endif
  23390. const char* GetCipherKeaStr(char n[][MAX_SEGMENT_SZ]) {
  23391. const char* keaStr = NULL;
  23392. if (XSTRCMP(n[0],"ECDHE") == 0 && XSTRCMP(n[1],"PSK") == 0)
  23393. keaStr = "ECDHEPSK";
  23394. else if ((XSTRCMP(n[0],"ECDH") == 0) || (XSTRCMP(n[0],"ECDHE") == 0))
  23395. keaStr = "ECDH";
  23396. else if (XSTRCMP(n[0],"DHE") == 0 && XSTRCMP(n[1],"PSK") == 0)
  23397. keaStr = "DHEPSK";
  23398. else if (XSTRCMP(n[0],"DHE") == 0)
  23399. keaStr = "DH";
  23400. else if (XSTRCMP(n[0],"RSA") == 0 && XSTRCMP(n[1],"PSK") == 0)
  23401. keaStr = "RSAPSK";
  23402. else if (XSTRCMP(n[0],"SRP") == 0)
  23403. keaStr = "SRP";
  23404. else if (XSTRCMP(n[0],"PSK") == 0)
  23405. keaStr = "PSK";
  23406. else if (XSTRCMP(n[0],"EDH") == 0)
  23407. keaStr = "EDH";
  23408. else if ((XSTRNCMP(n[1],"SHA", 3) == 0) || (XSTRNCMP(n[2],"SHA", 3) == 0) ||
  23409. (XSTRNCMP(n[3],"SHA", 3) == 0) || (XSTRNCMP(n[4],"SHA", 3) == 0) ||
  23410. (XSTRCMP(n[2],"RSA") == 0) || (XSTRCMP(n[0],"AES128") == 0) ||
  23411. (XSTRCMP(n[0],"AES256") == 0) || (XSTRCMP(n[1],"MD5") == 0))
  23412. keaStr = "RSA";
  23413. else if (XSTRCMP(n[0],"NULL") == 0)
  23414. keaStr = "None";
  23415. else
  23416. keaStr = "unknown";
  23417. return keaStr;
  23418. }
  23419. #if defined(__GNUC__) && __GNUC__ > 11 && defined(__SANITIZE_ADDRESS__)
  23420. PRAGMA_GCC_DIAG_POP
  23421. #endif
  23422. const char* GetCipherAuthStr(char n[][MAX_SEGMENT_SZ]) {
  23423. const char* authStr = NULL;
  23424. if ((XSTRCMP(n[0],"AES128") == 0) || (XSTRCMP(n[0],"AES256") == 0) ||
  23425. ((XSTRCMP(n[0],"TLS13") == 0) && ((XSTRCMP(n[1],"AES128") == 0) ||
  23426. (XSTRCMP(n[1],"AES256") == 0) || (XSTRCMP(n[1],"CHACHA20") == 0))) ||
  23427. (XSTRCMP(n[0],"RSA") == 0) || (XSTRCMP(n[1],"RSA") == 0) ||
  23428. (XSTRNCMP(n[1],"SHA", 3) == 0) || (XSTRNCMP(n[2],"SHA", 3) == 0) ||
  23429. (XSTRCMP(n[1],"MD5") == 0))
  23430. authStr = "RSA";
  23431. else if (XSTRCMP(n[0],"PSK") == 0 || XSTRCMP(n[1],"PSK") == 0)
  23432. authStr = "PSK";
  23433. else if (XSTRCMP(n[0],"SRP") == 0 && XSTRCMP(n[1],"AES") == 0)
  23434. authStr = "SRP";
  23435. else if (XSTRCMP(n[1],"ECDSA") == 0)
  23436. authStr = "ECDSA";
  23437. else if (XSTRCMP(n[0],"ADH") == 0 || XSTRCMP(n[0],"NULL") == 0)
  23438. authStr = "None";
  23439. else
  23440. authStr = "unknown";
  23441. return authStr;
  23442. }
  23443. const char* GetCipherEncStr(char n[][MAX_SEGMENT_SZ]) {
  23444. const char* encStr = NULL;
  23445. if ((XSTRCMP(n[0],"AES256") == 0 && XSTRCMP(n[1],"GCM") == 0) ||
  23446. (XSTRCMP(n[1],"AES256") == 0 && XSTRCMP(n[2],"GCM") == 0) ||
  23447. (XSTRCMP(n[2],"AES256") == 0 && XSTRCMP(n[3],"GCM") == 0))
  23448. encStr = "AESGCM(256)";
  23449. else if ((XSTRCMP(n[0],"AES128") == 0 && XSTRCMP(n[1],"GCM") == 0) ||
  23450. (XSTRCMP(n[1],"AES128") == 0 && XSTRCMP(n[2],"GCM") == 0) ||
  23451. (XSTRCMP(n[2],"AES128") == 0 && XSTRCMP(n[3],"GCM") == 0))
  23452. encStr = "AESGCM(128)";
  23453. else if ((XSTRCMP(n[0],"AES128") == 0 && XSTRCMP(n[1],"CCM") == 0) ||
  23454. (XSTRCMP(n[1],"AES128") == 0 && XSTRCMP(n[2],"CCM") == 0) ||
  23455. (XSTRCMP(n[2],"AES128") == 0 && XSTRCMP(n[3],"CCM") == 0))
  23456. encStr = "AESCCM(128)";
  23457. else if ((XSTRCMP(n[0],"AES128") == 0) ||
  23458. (XSTRCMP(n[1],"AES128") == 0) ||
  23459. (XSTRCMP(n[2],"AES128") == 0) ||
  23460. (XSTRCMP(n[1],"AES") == 0 && XSTRCMP(n[2],"128") == 0) ||
  23461. (XSTRCMP(n[2],"AES") == 0 && XSTRCMP(n[3],"128") == 0))
  23462. encStr = "AES(128)";
  23463. else if ((XSTRCMP(n[0],"AES256") == 0) ||
  23464. (XSTRCMP(n[1],"AES256") == 0) ||
  23465. (XSTRCMP(n[2],"AES256") == 0) ||
  23466. (XSTRCMP(n[1],"AES") == 0 && XSTRCMP(n[2],"256") == 0) ||
  23467. (XSTRCMP(n[2],"AES") == 0 && XSTRCMP(n[3],"256") == 0))
  23468. encStr = "AES(256)";
  23469. #ifdef HAVE_ARIA
  23470. else if ((XSTRCMP(n[0],"ARIA256") == 0) ||
  23471. (XSTRCMP(n[2],"ARIA256") == 0))
  23472. encStr = "ARIA(256)";
  23473. else if ((XSTRCMP(n[0],"ARIA128") == 0) ||
  23474. (XSTRCMP(n[2],"ARIA128") == 0))
  23475. encStr = "ARIA(128)";
  23476. #endif
  23477. else if ((XSTRCMP(n[0],"CAMELLIA256") == 0) ||
  23478. (XSTRCMP(n[2],"CAMELLIA256") == 0))
  23479. encStr = "CAMELLIA(256)";
  23480. else if ((XSTRCMP(n[0],"CAMELLIA128") == 0) ||
  23481. (XSTRCMP(n[2],"CAMELLIA128") == 0))
  23482. encStr = "CAMELLIA(128)";
  23483. #ifdef WOLFSSL_SM4_GCM
  23484. else if ((XSTRCMP(n[0],"SM4") == 0 && XSTRCMP(n[1],"GCM") == 0) ||
  23485. (XSTRCMP(n[1],"SM4") == 0 && XSTRCMP(n[2],"GCM") == 0) ||
  23486. (XSTRCMP(n[2],"SM4") == 0 && XSTRCMP(n[3],"GCM") == 0))
  23487. encStr = "SM4-GCM";
  23488. #endif
  23489. #ifdef WOLFSSL_SM4_CCM
  23490. else if ((XSTRCMP(n[0],"SM4") == 0 && XSTRCMP(n[1],"CCM") == 0) ||
  23491. (XSTRCMP(n[1],"SM4") == 0 && XSTRCMP(n[2],"CCM") == 0) ||
  23492. (XSTRCMP(n[2],"SM4") == 0 && XSTRCMP(n[3],"CCM") == 0))
  23493. encStr = "SM4-CCM";
  23494. #endif
  23495. #ifdef WOLFSSL_SM4_CBC
  23496. else if ((XSTRCMP(n[0],"SM4") == 0) ||
  23497. (XSTRCMP(n[2],"SM4") == 0))
  23498. encStr = "SM4";
  23499. #endif
  23500. else if ((XSTRCMP(n[0],"RC4") == 0) || (XSTRCMP(n[1],"RC4") == 0) ||
  23501. (XSTRCMP(n[2],"RC4") == 0))
  23502. encStr = "RC4";
  23503. else if (((XSTRCMP(n[0],"DES") == 0) || (XSTRCMP(n[1],"DES") == 0) ||
  23504. (XSTRCMP(n[2],"DES") == 0)) &&
  23505. ((XSTRCMP(n[1],"CBC3") == 0) || (XSTRCMP(n[2],"CBC3") == 0) ||
  23506. (XSTRCMP(n[3],"CBC3") == 0)))
  23507. encStr = "3DES";
  23508. else if ((XSTRCMP(n[1],"CHACHA20") == 0 && XSTRCMP(n[2],"POLY1305") == 0) ||
  23509. (XSTRCMP(n[2],"CHACHA20") == 0 && XSTRCMP(n[3],"POLY1305") == 0))
  23510. encStr = "CHACHA20/POLY1305(256)";
  23511. else if ((XSTRCMP(n[0],"NULL") == 0) || (XSTRCMP(n[1],"NULL") == 0) ||
  23512. (XSTRCMP(n[2],"NULL") == 0) ||
  23513. ((XSTRCMP(n[0],"TLS13") == 0) && (XSTRCMP(n[3],"") == 0)))
  23514. encStr = "None";
  23515. else
  23516. encStr = "unknown";
  23517. return encStr;
  23518. }
  23519. /* Check if a cipher is AEAD
  23520. * @param n return segment cipher name
  23521. * return 1 if the cipher is AEAD, otherwise 0
  23522. */
  23523. int IsCipherAEAD(char n[][MAX_SEGMENT_SZ])
  23524. {
  23525. WOLFSSL_ENTER("IsCipherAEAD");
  23526. if (n == NULL) {
  23527. WOLFSSL_MSG("bad function argument. n is NULL.");
  23528. return 0;
  23529. }
  23530. if ((XSTRCMP(n[2],"GCM") == 0) || (XSTRCMP(n[3],"GCM") == 0) ||
  23531. (XSTRCMP(n[1],"CCM") == 0) ||
  23532. (XSTRCMP(n[2],"CCM") == 0) || (XSTRCMP(n[3],"CCM") == 0) ||
  23533. (XSTRCMP(n[1],"CHACHA20") == 0 && XSTRCMP(n[2],"POLY1305") == 0) ||
  23534. (XSTRCMP(n[2],"CHACHA20") == 0 && XSTRCMP(n[3],"POLY1305") == 0))
  23535. return 1;
  23536. return 0;
  23537. }
  23538. /* Returns the MAC string of a cipher or "unknown" on failure */
  23539. const char* GetCipherMacStr(char n[][MAX_SEGMENT_SZ]) {
  23540. const char* macStr = NULL;
  23541. if ((XSTRCMP(n[4],"SHA256") == 0) || (XSTRCMP(n[3],"SHA256") == 0) ||
  23542. (XSTRCMP(n[2],"SHA256") == 0) || (XSTRCMP(n[1],"SHA256") == 0))
  23543. macStr = "SHA256";
  23544. else if ((XSTRCMP(n[4],"SHA384") == 0) ||
  23545. (XSTRCMP(n[3],"SHA384") == 0) ||
  23546. (XSTRCMP(n[2],"SHA384") == 0) ||
  23547. (XSTRCMP(n[1],"SHA384") == 0))
  23548. macStr = "SHA384";
  23549. #ifdef WOLFSSL_SM3
  23550. else if ((XSTRCMP(n[4],"SM3") == 0) ||
  23551. (XSTRCMP(n[3],"SM3") == 0) ||
  23552. (XSTRCMP(n[2],"SM3") == 0) ||
  23553. (XSTRCMP(n[1],"SM3") == 0))
  23554. macStr = "SM3";
  23555. #endif
  23556. else if ((XSTRCMP(n[4],"SHA") == 0) || (XSTRCMP(n[3],"SHA") == 0) ||
  23557. (XSTRCMP(n[2],"SHA") == 0) || (XSTRCMP(n[1],"SHA") == 0) ||
  23558. (XSTRCMP(n[1],"MD5") == 0))
  23559. macStr = "SHA1";
  23560. else if ((XSTRCMP(n[3],"GCM") == 0) ||
  23561. (XSTRCMP(n[1],"CCM") == 0) ||
  23562. (XSTRCMP(n[2],"CCM") == 0) || (XSTRCMP(n[3],"CCM") == 0) ||
  23563. (XSTRCMP(n[1],"CHACHA20") == 0 && XSTRCMP(n[2],"POLY1305") == 0) ||
  23564. (XSTRCMP(n[2],"CHACHA20") == 0 && XSTRCMP(n[3],"POLY1305") == 0))
  23565. macStr = "AEAD";
  23566. else
  23567. macStr = "unknown";
  23568. return macStr;
  23569. }
  23570. /* Returns the number of bits based on the cipher enc string, or 0 on failure */
  23571. int SetCipherBits(const char* enc) {
  23572. int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
  23573. if ((XSTRCMP(enc,"AESGCM(256)") == 0) ||
  23574. (XSTRCMP(enc,"AES(256)") == 0) ||
  23575. (XSTRCMP(enc,"CAMELLIA(256)") == 0) ||
  23576. (XSTRCMP(enc,"CHACHA20/POLY1305(256)") == 0))
  23577. ret = 256;
  23578. else if
  23579. ((XSTRCMP(enc,"3DES") == 0))
  23580. ret = 168;
  23581. else if
  23582. ((XSTRCMP(enc,"AESGCM(128)") == 0) ||
  23583. (XSTRCMP(enc,"AES(128)") == 0) ||
  23584. (XSTRCMP(enc,"CAMELLIA(128)") == 0) ||
  23585. (XSTRCMP(enc,"RC4") == 0))
  23586. ret = 128;
  23587. else if
  23588. ((XSTRCMP(enc,"DES") == 0))
  23589. ret = 56;
  23590. return ret;
  23591. }
  23592. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  23593. const char* GetCipherNameIana(const byte cipherSuite0, const byte cipherSuite)
  23594. {
  23595. #ifndef NO_ERROR_STRINGS
  23596. int i;
  23597. const char* nameIana = "NONE";
  23598. for (i = 0; i < GetCipherNamesSize(); i++) {
  23599. if ((cipher_names[i].cipherSuite0 == cipherSuite0) &&
  23600. (cipher_names[i].cipherSuite == cipherSuite)
  23601. #ifndef NO_CIPHER_SUITE_ALIASES
  23602. && (! (cipher_names[i].flags & WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS))
  23603. #endif
  23604. ) {
  23605. nameIana = cipher_names[i].name_iana;
  23606. break;
  23607. }
  23608. }
  23609. return nameIana;
  23610. #else
  23611. (void)cipherSuite0;
  23612. (void)cipherSuite;
  23613. return NULL;
  23614. #endif
  23615. }
  23616. const char* wolfSSL_get_cipher_name_internal(WOLFSSL* ssl)
  23617. {
  23618. if (ssl == NULL) {
  23619. return NULL;
  23620. }
  23621. return GetCipherNameInternal(ssl->options.cipherSuite0, ssl->options.cipherSuite);
  23622. }
  23623. const char* wolfSSL_get_cipher_name_iana(WOLFSSL* ssl)
  23624. {
  23625. if (ssl == NULL) {
  23626. return NULL;
  23627. }
  23628. return GetCipherNameIana(ssl->options.cipherSuite0, ssl->options.cipherSuite);
  23629. }
  23630. int GetCipherSuiteFromName(const char* name, byte* cipherSuite0,
  23631. byte* cipherSuite, int* flags)
  23632. {
  23633. int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
  23634. int i;
  23635. unsigned long len;
  23636. const char* nameDelim;
  23637. /* Support trailing : */
  23638. nameDelim = XSTRSTR(name, ":");
  23639. if (nameDelim)
  23640. len = (unsigned long)(nameDelim - name);
  23641. else
  23642. len = (unsigned long)XSTRLEN(name);
  23643. for (i = 0; i < GetCipherNamesSize(); i++) {
  23644. int found = (XSTRNCMP(name, cipher_names[i].name, len) == 0) &&
  23645. (cipher_names[i].name[len] == 0);
  23646. #ifndef NO_ERROR_STRINGS
  23647. if (!found)
  23648. found = (XSTRNCMP(name, cipher_names[i].name_iana, len) == 0) &&
  23649. (cipher_names[i].name_iana[len] == 0);
  23650. #endif
  23651. if (found) {
  23652. *cipherSuite0 = cipher_names[i].cipherSuite0;
  23653. *cipherSuite = cipher_names[i].cipherSuite;
  23654. *flags = cipher_names[i].flags;
  23655. ret = 0;
  23656. break;
  23657. }
  23658. }
  23659. return ret;
  23660. }
  23661. /**
  23662. Set the enabled cipher suites.
  23663. With OPENSSL_EXTRA we attempt to understand some of the available "bulk"
  23664. ciphersuites. We can not perfectly filter ciphersuites based on the "bulk"
  23665. names but we do what we can. Ciphersuites named explicitly take precedence to
  23666. ciphersuites introduced through the "bulk" ciphersuites.
  23667. @param [out] suites Suites structure.
  23668. @param [in] list List of cipher suites, only supports full name from
  23669. cipher_names[] delimited by ':'.
  23670. @return true on success, else false.
  23671. */
  23672. static int ParseCipherList(Suites* suites,
  23673. const char* list, ProtocolVersion version, int privateKeySz, byte side)
  23674. {
  23675. int ret = 0;
  23676. int idx = 0;
  23677. int haveSig = 0;
  23678. word16 haveRSA = 0;
  23679. #ifdef OPENSSL_EXTRA
  23680. word16 haveDH = 0;
  23681. word16 haveECC = 0;
  23682. word16 haveStaticRSA = 1; /* allowed by default if compiled in */
  23683. word16 haveStaticECC = 0;
  23684. word16 haveNull = 1; /* allowed by default if compiled in */
  23685. int callInitSuites = 0;
  23686. word16 havePSK = 0;
  23687. #endif
  23688. const int suiteSz = GetCipherNamesSize();
  23689. const char* next = list;
  23690. if (suites == NULL || list == NULL) {
  23691. WOLFSSL_MSG("SetCipherList parameter error");
  23692. return 0;
  23693. }
  23694. if (next[0] == '\0' ||
  23695. XSTRCMP(next, "ALL") == 0 ||
  23696. XSTRCMP(next, "DEFAULT") == 0 ||
  23697. XSTRCMP(next, "HIGH") == 0)
  23698. {
  23699. /* Add all ciphersuites except anonymous and null ciphers. Prefer RSA */
  23700. #ifndef NO_RSA
  23701. haveRSA = 1;
  23702. #endif
  23703. InitSuites(suites, version,
  23704. #ifndef NO_CERTS
  23705. privateKeySz,
  23706. #else
  23707. 0,
  23708. #endif
  23709. haveRSA, 1, 1, !haveRSA, 1, haveRSA, !haveRSA, 1, 1, 0, 0,
  23710. side
  23711. );
  23712. return 1; /* wolfSSL default */
  23713. }
  23714. do {
  23715. const char* current = next;
  23716. char name[MAX_SUITE_NAME + 1];
  23717. int i;
  23718. word32 length;
  23719. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
  23720. word16 allowing = 1;
  23721. #endif
  23722. next = XSTRSTR(next, ":");
  23723. length = MAX_SUITE_NAME;
  23724. if (next != NULL) {
  23725. word32 currLen = (word32)(next - current);
  23726. if (length > currLen) {
  23727. length = currLen;
  23728. }
  23729. if (currLen == 0)
  23730. break;
  23731. }
  23732. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
  23733. if (length > 1) {
  23734. if (*current == '!') {
  23735. allowing = 0;
  23736. current++;
  23737. length--;
  23738. }
  23739. }
  23740. #endif
  23741. XSTRNCPY(name, current, length);
  23742. name[(length == sizeof(name)) ? length - 1 : length] = 0;
  23743. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
  23744. if (length > 1) {
  23745. char* substr = NULL;
  23746. char* substrCurrent = name;
  23747. /* extract first public key type from a string like ECDHE+AESGCM */
  23748. substr = XSTRSTR(substrCurrent, "+");
  23749. if (substr != NULL) {
  23750. do {
  23751. if (substr) {
  23752. length = (word32)(substr - substrCurrent);
  23753. substrCurrent[length] = '\0';
  23754. }
  23755. else {
  23756. length = (word32)XSTRLEN(substrCurrent);
  23757. }
  23758. /* check if is a public key type */
  23759. if (XSTRCMP(substrCurrent, "ECDHE") == 0 ||
  23760. XSTRCMP(substrCurrent, "RSA") == 0 ||
  23761. XSTRCMP(substrCurrent, "DHE") == 0) {
  23762. if (name != substrCurrent)
  23763. XMEMMOVE(name, substrCurrent, length);
  23764. name[length] = '\0';
  23765. break;
  23766. }
  23767. substrCurrent = substr;
  23768. if (substr) {
  23769. substrCurrent = substrCurrent + 1; /* +1 to skip over '+' */
  23770. substr = XSTRSTR(substrCurrent, "+");
  23771. }
  23772. } while (substrCurrent != NULL);
  23773. }
  23774. }
  23775. if (XSTRCMP(name, "DEFAULT") == 0 || XSTRCMP(name, "ALL") == 0) {
  23776. if (XSTRCMP(name, "ALL") == 0)
  23777. haveSig |= SIG_ANON;
  23778. else
  23779. haveSig &= ~SIG_ANON;
  23780. haveRSA = 1;
  23781. haveDH = 1;
  23782. haveECC = 1;
  23783. /* having static ECC will disable all RSA use, do not set
  23784. * static ECC suites here
  23785. * haveStaticECC = 1; */
  23786. haveStaticRSA = 1;
  23787. haveSig |= SIG_RSA;
  23788. havePSK = 1;
  23789. haveNull = 0;
  23790. callInitSuites = 1;
  23791. ret = 1;
  23792. continue;
  23793. }
  23794. /* We don't have a way to disallow high bit sizes. Only disable unsafe
  23795. * ciphersuites. */
  23796. if (XSTRCMP(name, "HIGH") == 0 && allowing) {
  23797. /* Disable static, anonymous, and null ciphers */
  23798. haveSig &= ~SIG_ANON;
  23799. haveRSA = 1;
  23800. haveDH = 1;
  23801. haveECC = 1;
  23802. haveStaticECC = 0;
  23803. haveStaticRSA = 0;
  23804. haveSig |= SIG_RSA;
  23805. havePSK = 1;
  23806. haveNull = 0;
  23807. callInitSuites = 1;
  23808. ret = 1;
  23809. continue;
  23810. }
  23811. if (XSTRCMP(name, "aNULL") == 0) {
  23812. if (allowing)
  23813. haveSig |= SIG_ANON;
  23814. else
  23815. haveSig &= ~SIG_ANON;
  23816. if (allowing) {
  23817. /* Allow RSA by default. */
  23818. if (!haveECC)
  23819. haveRSA = 1;
  23820. if ((haveSig & SIG_ECDSA) == 0)
  23821. haveSig |= SIG_RSA;
  23822. callInitSuites = 1;
  23823. ret = 1;
  23824. }
  23825. continue;
  23826. }
  23827. if (XSTRCMP(name, "eNULL") == 0 || XSTRCMP(name, "NULL") == 0) {
  23828. haveNull = allowing;
  23829. if (allowing) {
  23830. /* Allow RSA by default. */
  23831. if (!haveECC)
  23832. haveRSA = 1;
  23833. if ((haveSig & SIG_ECDSA) == 0)
  23834. haveSig |= SIG_RSA;
  23835. callInitSuites = 1;
  23836. ret = 1;
  23837. }
  23838. continue;
  23839. }
  23840. if (XSTRCMP(name, "kDH") == 0) {
  23841. if (allowing) {
  23842. haveDH = 1;
  23843. callInitSuites = 1;
  23844. ret = 1;
  23845. }
  23846. continue;
  23847. }
  23848. if (XSTRCMP(name, "DHE") == 0 || XSTRCMP(name, "EDH") == 0) {
  23849. if (allowing) {
  23850. haveDH = 1;
  23851. callInitSuites = 1;
  23852. ret = 1;
  23853. }
  23854. continue;
  23855. }
  23856. if (XSTRCMP(name, "ECDHE") == 0 || XSTRCMP(name, "EECDH") == 0) {
  23857. if (allowing) {
  23858. haveECC = 1;
  23859. haveSig |= SIG_ECDSA;
  23860. callInitSuites = 1;
  23861. ret = 1;
  23862. }
  23863. continue;
  23864. }
  23865. if (XSTRCMP(name, "kRSA") == 0 || XSTRCMP(name, "RSA") == 0) {
  23866. haveStaticRSA = allowing;
  23867. if (allowing) {
  23868. haveRSA = 1;
  23869. haveSig |= SIG_RSA;
  23870. callInitSuites = 1;
  23871. ret = 1;
  23872. }
  23873. continue;
  23874. }
  23875. if (XSTRCMP(name, "PSK") == 0) {
  23876. havePSK = allowing;
  23877. haveSig |= SIG_RSA;
  23878. if (allowing) {
  23879. /* Allow RSA by default. */
  23880. if (!haveECC)
  23881. haveRSA = 1;
  23882. if ((haveSig & SIG_ECDSA) == 0)
  23883. haveSig |= SIG_RSA;
  23884. callInitSuites = 1;
  23885. ret = 1;
  23886. }
  23887. continue;
  23888. }
  23889. if (XSTRCMP(name, "LOW") == 0 || XSTRCMP(name, "MEDIUM") == 0) {
  23890. /* No way to limit or allow low bit sizes */
  23891. if (allowing) {
  23892. /* Allow RSA by default */
  23893. haveRSA = 1;
  23894. haveSig |= SIG_RSA;
  23895. callInitSuites = 1;
  23896. ret = 1;
  23897. }
  23898. continue;
  23899. }
  23900. if (XSTRCMP(name, "DSS") == 0) {
  23901. /* No support for DSA ciphersuites */
  23902. continue;
  23903. }
  23904. if (XSTRCMP(name, "EXP") == 0 || XSTRCMP(name, "EXPORT") == 0) {
  23905. /* wolfSSL doesn't support "export" ciphers. We can skip this */
  23906. continue;
  23907. }
  23908. #endif /* OPENSSL_EXTRA */
  23909. for (i = 0; i < suiteSz; i++) {
  23910. if (XSTRNCMP(name, cipher_names[i].name, sizeof(name)) == 0
  23911. #ifndef NO_ERROR_STRINGS
  23912. || XSTRNCMP(name, cipher_names[i].name_iana, sizeof(name)) == 0
  23913. #endif
  23914. ) {
  23915. int j;
  23916. #ifdef WOLFSSL_DTLS
  23917. /* don't allow stream ciphers with DTLS */
  23918. if (version.major == DTLS_MAJOR) {
  23919. if (XSTRSTR(name, "RC4"))
  23920. {
  23921. WOLFSSL_MSG("Stream ciphers not supported with DTLS");
  23922. continue;
  23923. }
  23924. }
  23925. #endif /* WOLFSSL_DTLS */
  23926. for (j = 0; j < idx; j += 2) {
  23927. if ((suites->suites[j+0] == cipher_names[i].cipherSuite0) &&
  23928. (suites->suites[j+1] == cipher_names[i].cipherSuite)) {
  23929. break;
  23930. }
  23931. }
  23932. /* Silently drop duplicates from list. */
  23933. if (j != idx) {
  23934. break;
  23935. }
  23936. if (idx + 1 >= WOLFSSL_MAX_SUITE_SZ) {
  23937. WOLFSSL_MSG("WOLFSSL_MAX_SUITE_SZ set too low");
  23938. return 0; /* suites buffer not large enough, error out */
  23939. }
  23940. suites->suites[idx++] = cipher_names[i].cipherSuite0;
  23941. suites->suites[idx++] = cipher_names[i].cipherSuite;
  23942. /* The suites are either ECDSA, RSA, PSK, or Anon. The RSA
  23943. * suites don't necessarily have RSA in the name. */
  23944. #ifdef WOLFSSL_TLS13
  23945. if (cipher_names[i].cipherSuite0 == TLS13_BYTE ||
  23946. (cipher_names[i].cipherSuite0 == ECC_BYTE &&
  23947. (cipher_names[i].cipherSuite == TLS_SHA256_SHA256 ||
  23948. cipher_names[i].cipherSuite == TLS_SHA384_SHA384))) {
  23949. #ifndef NO_RSA
  23950. haveSig |= SIG_RSA;
  23951. #endif
  23952. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  23953. defined(HAVE_ED448)
  23954. haveSig |= SIG_ECDSA;
  23955. #endif
  23956. #ifdef HAVE_FALCON
  23957. haveSig |= SIG_FALCON;
  23958. #endif /* HAVE_FALCON */
  23959. #ifdef HAVE_DILITHIUM
  23960. haveSig |= SIG_DILITHIUM;
  23961. #endif /* HAVE_DILITHIUM */
  23962. }
  23963. else
  23964. #ifdef BUILD_TLS_SM4_GCM_SM3
  23965. if ((cipher_names[i].cipherSuite0 == CIPHER_BYTE) &&
  23966. (cipher_names[i].cipherSuite == TLS_SM4_GCM_SM3)) {
  23967. haveSig |= SIG_SM2;
  23968. }
  23969. else
  23970. #endif
  23971. #ifdef BUILD_TLS_SM4_CCM_SM3
  23972. if ((cipher_names[i].cipherSuite0 == CIPHER_BYTE) &&
  23973. (cipher_names[i].cipherSuite == TLS_SM4_CCM_SM3)) {
  23974. haveSig |= SIG_SM2;
  23975. }
  23976. else
  23977. #endif
  23978. #endif /* WOLFSSL_TLS13 */
  23979. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3) && \
  23980. (defined(WOLFSSL_SM4_CBC) || defined(WOLFSSL_SM4_GCM) || \
  23981. defined(WOLFSSL_SM4_CCM))
  23982. if ((cipher_names[i].cipherSuite0 == SM_BYTE) && (0
  23983. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
  23984. || (cipher_names[i].cipherSuite ==
  23985. TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3)
  23986. #endif
  23987. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3
  23988. || (cipher_names[i].cipherSuite ==
  23989. TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3)
  23990. #endif
  23991. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3
  23992. || (cipher_names[i].cipherSuite ==
  23993. TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3)
  23994. #endif
  23995. )) {
  23996. haveSig |= SIG_SM2;
  23997. }
  23998. else
  23999. #endif
  24000. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  24001. defined(HAVE_ED448)
  24002. if (XSTRSTR(name, "ECDSA"))
  24003. haveSig |= SIG_ECDSA;
  24004. else
  24005. #endif
  24006. #ifdef HAVE_ANON
  24007. if (XSTRSTR(name, "ADH"))
  24008. haveSig |= SIG_ANON;
  24009. else
  24010. #endif
  24011. #ifndef NO_PSK
  24012. if (XSTRSTR(name, "PSK") == NULL)
  24013. #endif
  24014. {
  24015. /* Fall back to RSA */
  24016. haveSig |= SIG_RSA;
  24017. }
  24018. ret = 1; /* found at least one */
  24019. break;
  24020. }
  24021. }
  24022. }
  24023. while (next++); /* increment to skip ':' */
  24024. if (ret) {
  24025. int keySz = 0;
  24026. #ifndef NO_CERTS
  24027. keySz = privateKeySz;
  24028. #endif
  24029. #ifdef OPENSSL_EXTRA
  24030. if (callInitSuites) {
  24031. suites->setSuites = 0; /* Force InitSuites */
  24032. suites->hashSigAlgoSz = 0; /* Force InitSuitesHashSigAlgo call
  24033. * inside InitSuites */
  24034. InitSuites(suites, version, keySz, (word16)haveRSA,
  24035. (word16)havePSK, (word16)haveDH,
  24036. (word16)((haveSig & SIG_ECDSA) != 0),
  24037. (word16)haveECC, (word16)haveStaticRSA,
  24038. (word16)haveStaticECC,
  24039. (word16)((haveSig & SIG_FALCON) != 0),
  24040. (word16)((haveSig & SIG_DILITHIUM) != 0),
  24041. (word16)((haveSig & SIG_ANON) != 0),
  24042. (word16)haveNull, side);
  24043. /* Restore user ciphers ahead of defaults */
  24044. XMEMMOVE(suites->suites + idx, suites->suites,
  24045. min(suites->suiteSz, WOLFSSL_MAX_SUITE_SZ-idx));
  24046. suites->suiteSz += (word16)idx;
  24047. }
  24048. else
  24049. #endif
  24050. {
  24051. suites->suiteSz = (word16)idx;
  24052. InitSuitesHashSigAlgo(suites->hashSigAlgo, haveSig, 1, keySz,
  24053. &suites->hashSigAlgoSz);
  24054. }
  24055. #ifdef HAVE_RENEGOTIATION_INDICATION
  24056. if (side == WOLFSSL_CLIENT_END) {
  24057. if (suites->suiteSz > WOLFSSL_MAX_SUITE_SZ - 2) {
  24058. WOLFSSL_MSG("Too many ciphersuites");
  24059. return 0;
  24060. }
  24061. suites->suites[suites->suiteSz] = CIPHER_BYTE;
  24062. suites->suites[suites->suiteSz+1] =
  24063. TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
  24064. suites->suiteSz += 2;
  24065. }
  24066. #endif
  24067. suites->setSuites = 1;
  24068. }
  24069. #ifdef NO_CERTS
  24070. (void)privateKeySz;
  24071. #endif
  24072. return ret;
  24073. }
  24074. int SetCipherList_ex(const WOLFSSL_CTX* ctx, const WOLFSSL* ssl,
  24075. Suites* suites, const char* list)
  24076. {
  24077. ProtocolVersion version;
  24078. int privateKeySz = 0;
  24079. byte side;
  24080. if (ctx != NULL) {
  24081. version = ctx->method->version;
  24082. #ifndef NO_CERTS
  24083. privateKeySz = ctx->privateKeySz;
  24084. #endif
  24085. side = ctx->method->side;
  24086. }
  24087. else if (ssl != NULL) {
  24088. version = ssl->version;
  24089. #ifndef NO_CERTS
  24090. privateKeySz = ssl->buffers.keySz;
  24091. #endif
  24092. side = (byte)ssl->options.side;
  24093. }
  24094. else {
  24095. WOLFSSL_MSG("SetCipherList_ex parameter error");
  24096. return 0;
  24097. }
  24098. return ParseCipherList(suites, list, version, privateKeySz, side);
  24099. }
  24100. int SetCipherList(const WOLFSSL_CTX* ctx, Suites* suites,
  24101. const char* list)
  24102. {
  24103. return SetCipherList_ex(ctx, NULL, suites, list);
  24104. }
  24105. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
  24106. int SetCipherListFromBytes(WOLFSSL_CTX* ctx, Suites* suites, const byte* list,
  24107. const int listSz)
  24108. {
  24109. int ret = 0;
  24110. int idx = 0;
  24111. int i;
  24112. int haveRSAsig = 0;
  24113. int haveECDSAsig = 0;
  24114. int haveFalconSig = 0;
  24115. int haveDilithiumSig = 0;
  24116. int haveAnon = 0;
  24117. if (suites == NULL || list == NULL) {
  24118. WOLFSSL_MSG("SetCipherListFromBytes parameter error");
  24119. return 0;
  24120. }
  24121. if ((listSz % 2) != 0) {
  24122. return 0;
  24123. }
  24124. for (i = 0; (i + 1) < listSz; i += 2) {
  24125. const byte firstByte = list[i];
  24126. const byte secondByte = list[i + 1];
  24127. const char* name = NULL;
  24128. int j;
  24129. name = GetCipherNameInternal(firstByte, secondByte);
  24130. if (XSTRCMP(name, "None") == 0) {
  24131. /* bytes don't match any known cipher */
  24132. continue;
  24133. }
  24134. #ifdef WOLFSSL_DTLS
  24135. /* don't allow stream ciphers with DTLS */
  24136. if (ctx->method->version.major == DTLS_MAJOR) {
  24137. if (XSTRSTR(name, "RC4")) {
  24138. WOLFSSL_MSG("Stream ciphers not supported with DTLS");
  24139. continue;
  24140. }
  24141. }
  24142. #endif /* WOLFSSL_DTLS */
  24143. for (j = 0; j < idx; j += 2) {
  24144. if ((suites->suites[j+0] == firstByte) &&
  24145. (suites->suites[j+1] == secondByte)) {
  24146. break;
  24147. }
  24148. }
  24149. /* Silently drop duplicates from list. */
  24150. if (j != idx) {
  24151. continue;
  24152. }
  24153. if (idx + 1 >= WOLFSSL_MAX_SUITE_SZ) {
  24154. WOLFSSL_MSG("WOLFSSL_MAX_SUITE_SZ set too low");
  24155. return 0; /* suites buffer not large enough, error out */
  24156. }
  24157. suites->suites[idx++] = firstByte;
  24158. suites->suites[idx++] = secondByte;
  24159. /* The suites are either ECDSA, RSA, PSK, or Anon. The RSA
  24160. * suites don't necessarily have RSA in the name. */
  24161. #ifdef WOLFSSL_TLS13
  24162. if (firstByte == TLS13_BYTE || (firstByte == ECC_BYTE &&
  24163. (secondByte == TLS_SHA256_SHA256 ||
  24164. secondByte == TLS_SHA384_SHA384)) ||
  24165. (firstByte == CIPHER_BYTE && (secondByte == TLS_SM4_GCM_SM3 ||
  24166. secondByte == TLS_SM4_CCM_SM3))) {
  24167. #ifndef NO_RSA
  24168. haveRSAsig = 1;
  24169. #endif
  24170. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  24171. haveECDSAsig = 1;
  24172. #endif
  24173. #ifdef HAVE_FALCON
  24174. haveFalconSig = 1;
  24175. #endif /* HAVE_FALCON */
  24176. #ifdef HAVE_DILITHIUM
  24177. haveDilithiumSig = 1;
  24178. #endif /* HAVE_DILITHIUM */
  24179. }
  24180. else
  24181. #endif /* WOLFSSL_TLS13 */
  24182. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  24183. if ((haveECDSAsig == 0) && XSTRSTR(name, "ECDSA"))
  24184. haveECDSAsig = 1;
  24185. else
  24186. #endif
  24187. #ifdef HAVE_ANON
  24188. if (XSTRSTR(name, "ADH"))
  24189. haveAnon = 1;
  24190. else
  24191. #endif
  24192. if (haveRSAsig == 0
  24193. #ifndef NO_PSK
  24194. && (XSTRSTR(name, "PSK") == NULL)
  24195. #endif
  24196. ) {
  24197. haveRSAsig = 1;
  24198. }
  24199. ret = 1; /* found at least one */
  24200. }
  24201. if (ret) {
  24202. int keySz = 0;
  24203. int haveSig = 0;
  24204. #ifndef NO_CERTS
  24205. keySz = ctx->privateKeySz;
  24206. #endif
  24207. suites->suiteSz = (word16)idx;
  24208. haveSig |= haveECDSAsig ? SIG_ECDSA : 0;
  24209. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  24210. haveSig |= haveECDSAsig ? SIG_SM2 : 0;
  24211. #endif
  24212. haveSig |= haveRSAsig ? SIG_RSA : 0;
  24213. haveSig |= haveFalconSig ? SIG_FALCON : 0;
  24214. haveSig |= haveDilithiumSig ? SIG_DILITHIUM : 0;
  24215. haveSig |= haveAnon ? SIG_ANON : 0;
  24216. InitSuitesHashSigAlgo(suites->hashSigAlgo, haveSig, 1, keySz,
  24217. &suites->hashSigAlgoSz);
  24218. #ifdef HAVE_RENEGOTIATION_INDICATION
  24219. if (ctx->method->side == WOLFSSL_CLIENT_END) {
  24220. if (suites->suiteSz > WOLFSSL_MAX_SUITE_SZ - 2) {
  24221. WOLFSSL_MSG("Too many ciphersuites");
  24222. return 0;
  24223. }
  24224. suites->suites[suites->suiteSz] = CIPHER_BYTE;
  24225. suites->suites[suites->suiteSz+1] =
  24226. TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
  24227. suites->suiteSz += 2;
  24228. }
  24229. #endif
  24230. suites->setSuites = 1;
  24231. }
  24232. (void)ctx;
  24233. return ret;
  24234. }
  24235. #endif /* OPENSSL_EXTRA */
  24236. #ifdef OPENSSL_EXTRA
  24237. struct mac_algs {
  24238. byte alg;
  24239. const char* name;
  24240. } mac_names[] = {
  24241. #ifndef NO_SHA256
  24242. { sha256_mac, "SHA256" },
  24243. #endif
  24244. #ifdef WOLFSSL_SHA384
  24245. { sha384_mac, "SHA384" },
  24246. #endif
  24247. #ifdef WOLFSSL_SHA512
  24248. { sha512_mac, "SHA512" },
  24249. #endif
  24250. #ifdef WOLFSSL_SHA224
  24251. { sha224_mac, "SHA224" },
  24252. #endif
  24253. #ifdef WOLFSSL_SM3
  24254. { sm3_mac, "SM3" },
  24255. #endif
  24256. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  24257. defined(WOLFSSL_ALLOW_TLS_SHA1))
  24258. { sha_mac, "SHA1" },
  24259. #endif
  24260. };
  24261. #define MAC_NAMES_SZ (int)(sizeof(mac_names)/sizeof(*mac_names))
  24262. /* Convert the hash algorithm string to a TLS MAC algorithm num. */
  24263. static byte GetMacAlgFromName(const char* name, int len)
  24264. {
  24265. byte alg = no_mac;
  24266. int i;
  24267. for (i = 0; i < MAC_NAMES_SZ; i++) {
  24268. if (((int)XSTRLEN(mac_names[i].name) == len) &&
  24269. (XMEMCMP(mac_names[i].name, name, len) == 0)) {
  24270. alg = mac_names[i].alg;
  24271. break;
  24272. }
  24273. }
  24274. return alg;
  24275. }
  24276. struct sig_algs {
  24277. byte alg;
  24278. const char* name;
  24279. } sig_names[] = {
  24280. #ifndef NO_RSA
  24281. { rsa_sa_algo, "RSA" },
  24282. #ifdef WC_RSA_PSS
  24283. { rsa_pss_sa_algo, "RSA-PSS" },
  24284. { rsa_pss_sa_algo, "PSS" },
  24285. #endif
  24286. #endif
  24287. #ifdef HAVE_ECC
  24288. { ecc_dsa_sa_algo, "ECDSA" },
  24289. #endif
  24290. #ifdef HAVE_ED25519
  24291. { ed25519_sa_algo, "ED25519" },
  24292. #endif
  24293. #ifdef HAVE_ED448
  24294. { ed448_sa_algo, "ED448" },
  24295. #endif
  24296. #ifndef NO_DSA
  24297. { dsa_sa_algo, "DSA" },
  24298. #endif
  24299. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  24300. { sm2_sa_algo, "SM2" },
  24301. #endif
  24302. };
  24303. #define SIG_NAMES_SZ (int)(sizeof(sig_names)/sizeof(*sig_names))
  24304. /* Convert the signature algorithm string to a TLS signature algorithm num. */
  24305. static byte GetSigAlgFromName(const char* name, int len)
  24306. {
  24307. byte alg = anonymous_sa_algo;
  24308. int i;
  24309. for (i = 0; i < SIG_NAMES_SZ; i++) {
  24310. if (((int)XSTRLEN(sig_names[i].name) == len) &&
  24311. (XMEMCMP(sig_names[i].name, name, len) == 0)) {
  24312. alg = sig_names[i].alg;
  24313. break;
  24314. }
  24315. }
  24316. return alg;
  24317. }
  24318. /* Set the hash/signature algorithms that are supported for certificate signing.
  24319. *
  24320. * suites [in,out] Cipher suites and signature algorithms.
  24321. * list [in] String representing hash/signature algorithms to set.
  24322. * returns 0 on failure.
  24323. * 1 on success.
  24324. */
  24325. int SetSuitesHashSigAlgo(Suites* suites, const char* list)
  24326. {
  24327. int ret = 1;
  24328. word16 idx = 0;
  24329. const char* s = list;
  24330. byte sig_alg = 0;
  24331. byte mac_alg = no_mac;
  24332. /* Setting is destructive on error. */
  24333. suites->hashSigAlgoSz = 0;
  24334. do {
  24335. if (*list == '+') {
  24336. if (mac_alg != 0) {
  24337. ret = 0;
  24338. break;
  24339. }
  24340. sig_alg = GetSigAlgFromName(s, (int)(list - s));
  24341. if (sig_alg == 0) {
  24342. ret = 0;
  24343. break;
  24344. }
  24345. s = list + 1;
  24346. }
  24347. else if (*list == ':' || *list == '\0') {
  24348. if (sig_alg == 0) {
  24349. /* No signature algorithm set yet.
  24350. * Ed25519 and Ed448 have implied MAC algorithm.
  24351. */
  24352. sig_alg = GetSigAlgFromName(s, (int)(list - s));
  24353. if (sig_alg != ed25519_sa_algo && sig_alg != ed448_sa_algo) {
  24354. ret = 0;
  24355. break;
  24356. }
  24357. }
  24358. else {
  24359. mac_alg = GetMacAlgFromName(s, (int)(list - s));
  24360. if (mac_alg == 0) {
  24361. ret = 0;
  24362. break;
  24363. }
  24364. }
  24365. AddSuiteHashSigAlgo(suites->hashSigAlgo, mac_alg, sig_alg, 0, &idx);
  24366. sig_alg = 0;
  24367. mac_alg = no_mac;
  24368. s = list + 1;
  24369. }
  24370. list++;
  24371. }
  24372. while (*(list-1) != '\0');
  24373. if (s != list && (sig_alg != 0 || mac_alg != 0)) {
  24374. ret = 0;
  24375. }
  24376. else {
  24377. suites->hashSigAlgoSz = idx;
  24378. }
  24379. return ret;
  24380. }
  24381. #endif /* OPENSSL_EXTRA */
  24382. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_CERTS)
  24383. static int MatchSigAlgo(WOLFSSL* ssl, int sigAlgo)
  24384. {
  24385. #ifdef HAVE_ED25519
  24386. if (ssl->pkCurveOID == ECC_ED25519_OID) {
  24387. /* Certificate has Ed25519 key, only match with Ed25519 sig alg */
  24388. return sigAlgo == ed25519_sa_algo;
  24389. }
  24390. #endif
  24391. #ifdef HAVE_ED448
  24392. if (ssl->pkCurveOID == ECC_ED448_OID) {
  24393. /* Certificate has Ed448 key, only match with Ed448 sig alg */
  24394. return sigAlgo == ed448_sa_algo;
  24395. }
  24396. #endif
  24397. #ifdef HAVE_FALCON
  24398. if (ssl->pkCurveOID == CTC_FALCON_LEVEL1) {
  24399. /* Certificate has Falcon level 1 key, only match with Falcon level 1
  24400. * sig alg */
  24401. return sigAlgo == falcon_level1_sa_algo;
  24402. }
  24403. if (ssl->pkCurveOID == CTC_FALCON_LEVEL5) {
  24404. /* Certificate has Falcon level 5 key, only match with Falcon level 5
  24405. * sig alg */
  24406. return sigAlgo == falcon_level5_sa_algo;
  24407. }
  24408. #endif /* HAVE_FALCON */
  24409. #ifdef HAVE_DILITHIUM
  24410. if (ssl->pkCurveOID == CTC_DILITHIUM_LEVEL2) {
  24411. /* Certificate has Dilithium level 2 key, only match with it. */
  24412. return sigAlgo == dilithium_level2_sa_algo;
  24413. }
  24414. if (ssl->pkCurveOID == CTC_DILITHIUM_LEVEL3) {
  24415. /* Certificate has Dilithium level 3 key, only match with it. */
  24416. return sigAlgo == dilithium_level3_sa_algo;
  24417. }
  24418. if (ssl->pkCurveOID == CTC_DILITHIUM_LEVEL5) {
  24419. /* Certificate has Dilithium level 5 key, only match with it. */
  24420. return sigAlgo == dilithium_level5_sa_algo;
  24421. }
  24422. #endif /* HAVE_DILITHIUM */
  24423. #ifdef WC_RSA_PSS
  24424. /* RSA certificate and PSS sig alg. */
  24425. if (ssl->options.sigAlgo == rsa_sa_algo) {
  24426. #if defined(WOLFSSL_TLS13)
  24427. /* TLS 1.3 only supports RSA-PSS. */
  24428. if (IsAtLeastTLSv1_3(ssl->version))
  24429. return sigAlgo == rsa_pss_sa_algo;
  24430. #endif
  24431. /* TLS 1.2 and below - RSA-PSS allowed. */
  24432. if (sigAlgo == rsa_pss_sa_algo)
  24433. return 1;
  24434. }
  24435. #endif
  24436. /* Signature algorithm matches certificate. */
  24437. return sigAlgo == ssl->options.sigAlgo;
  24438. }
  24439. #if defined(HAVE_ECC) && defined(WOLFSSL_TLS13) || \
  24440. defined(USE_ECDSA_KEYSZ_HASH_ALGO)
  24441. static int CmpEccStrength(int hashAlgo, int curveSz)
  24442. {
  24443. int dgstSz = GetMacDigestSize((byte)hashAlgo);
  24444. if (dgstSz <= 0)
  24445. return WOLFSSL_FATAL_ERROR;
  24446. return dgstSz - (curveSz & (~0x3));
  24447. }
  24448. #endif
  24449. static byte MinHashAlgo(WOLFSSL* ssl)
  24450. {
  24451. #ifdef WOLFSSL_TLS13
  24452. #ifndef NO_SHA256
  24453. if (IsAtLeastTLSv1_3(ssl->version)) {
  24454. return sha256_mac;
  24455. }
  24456. #elif defined(WOLFSSL_SM3)
  24457. if (IsAtLeastTLSv1_3(ssl->version)) {
  24458. return sm3_mac;
  24459. }
  24460. #endif
  24461. #endif
  24462. #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_ALLOW_TLS_SHA1)
  24463. if (IsAtLeastTLSv1_2(ssl)) {
  24464. return sha256_mac;
  24465. }
  24466. #endif /* WOLFSSL_NO_TLS12 */
  24467. (void)ssl;
  24468. return sha_mac;
  24469. }
  24470. /* Check if a given peer hashSigAlgo is supported in our ssl->suites or
  24471. * ssl->ctx->suites.
  24472. *
  24473. * Returns 1 on match.
  24474. * Returns 0 otherwise.
  24475. * */
  24476. static int SupportedHashSigAlgo(WOLFSSL* ssl, const byte * hashSigAlgo)
  24477. {
  24478. const Suites * suites = NULL;
  24479. word32 i = 0;
  24480. if (ssl == NULL || hashSigAlgo == NULL) {
  24481. return 0;
  24482. }
  24483. suites = WOLFSSL_SUITES(ssl);
  24484. if (suites == NULL || suites->hashSigAlgoSz == 0) {
  24485. return 0;
  24486. }
  24487. for (i = 0; (i+1) < suites->hashSigAlgoSz; i += HELLO_EXT_SIGALGO_SZ) {
  24488. if (XMEMCMP(&suites->hashSigAlgo[i], hashSigAlgo,
  24489. HELLO_EXT_SIGALGO_SZ) == 0) {
  24490. /* Match found. */
  24491. return 1;
  24492. }
  24493. }
  24494. return 0;
  24495. }
  24496. int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, word32 hashSigAlgoSz,
  24497. int matchSuites)
  24498. {
  24499. word32 i;
  24500. int ret = WC_NO_ERR_TRACE(MATCH_SUITE_ERROR);
  24501. byte minHash;
  24502. /* set defaults */
  24503. if (IsAtLeastTLSv1_3(ssl->version)) {
  24504. #ifndef NO_CERTS
  24505. /* TLS 1.3 cipher suites don't have public key algorithms in them.
  24506. * Using the one in the certificate - if any.
  24507. */
  24508. ssl->options.sigAlgo = ssl->buffers.keyType;
  24509. #endif
  24510. }
  24511. else {
  24512. ssl->options.sigAlgo = ssl->specs.sig_algo;
  24513. }
  24514. if (ssl->options.sigAlgo == anonymous_sa_algo) {
  24515. /* PSK ciphersuite - get digest to use from cipher suite */
  24516. ssl->options.hashAlgo = ssl->specs.mac_algorithm;
  24517. return 0;
  24518. }
  24519. ssl->options.hashAlgo = minHash = MinHashAlgo(ssl);
  24520. /* No list means go with the defaults. */
  24521. if (hashSigAlgoSz == 0)
  24522. return 0;
  24523. /* i+1 since two bytes used to describe hash and signature algorithm */
  24524. for (i = 0; (i+1) < hashSigAlgoSz; i += HELLO_EXT_SIGALGO_SZ) {
  24525. byte hashAlgo = 0, sigAlgo = 0;
  24526. DecodeSigAlg(&hashSigAlgo[i], &hashAlgo, &sigAlgo);
  24527. /* Keep looking if hash algorithm not strong enough. */
  24528. if (hashAlgo < minHash)
  24529. continue;
  24530. /* Keep looking if signature algorithm isn't supported by cert. */
  24531. if (!MatchSigAlgo(ssl, sigAlgo))
  24532. continue;
  24533. if (matchSuites) {
  24534. /* Keep looking if peer algorithm isn't supported in our ssl->suites
  24535. * or ssl->ctx->suites. */
  24536. if (!SupportedHashSigAlgo(ssl, &hashSigAlgo[i])) {
  24537. continue;
  24538. }
  24539. }
  24540. #ifdef HAVE_ED25519
  24541. if (ssl->pkCurveOID == ECC_ED25519_OID) {
  24542. /* Matched Ed25519 - set chosen and finished. */
  24543. ssl->options.sigAlgo = sigAlgo;
  24544. ssl->options.hashAlgo = hashAlgo;
  24545. ret = 0;
  24546. break;
  24547. }
  24548. #endif
  24549. #ifdef HAVE_ED448
  24550. if (ssl->pkCurveOID == ECC_ED448_OID) {
  24551. /* Matched Ed448 - set chosen and finished. */
  24552. ssl->options.sigAlgo = sigAlgo;
  24553. ssl->options.hashAlgo = hashAlgo;
  24554. ret = 0;
  24555. break;
  24556. }
  24557. #endif
  24558. #if defined(HAVE_FALCON)
  24559. if (ssl->pkCurveOID == CTC_FALCON_LEVEL1 ||
  24560. ssl->pkCurveOID == CTC_FALCON_LEVEL5 ) {
  24561. /* Matched Falcon - set chosen and finished. */
  24562. ssl->options.sigAlgo = sigAlgo;
  24563. ssl->options.hashAlgo = hashAlgo;
  24564. ret = 0;
  24565. break;
  24566. }
  24567. #endif /* HAVE_FALCON */
  24568. #if defined(HAVE_DILITHIUM)
  24569. if (ssl->pkCurveOID == CTC_DILITHIUM_LEVEL2 ||
  24570. ssl->pkCurveOID == CTC_DILITHIUM_LEVEL3 ||
  24571. ssl->pkCurveOID == CTC_DILITHIUM_LEVEL5) {
  24572. /* Matched Dilithium - set chosen and finished. */
  24573. ssl->options.sigAlgo = sigAlgo;
  24574. ssl->options.hashAlgo = hashAlgo;
  24575. ret = 0;
  24576. break;
  24577. }
  24578. #endif /* HAVE_DILITHIUM */
  24579. #if defined(WOLFSSL_ECDSA_MATCH_HASH) && defined(USE_ECDSA_KEYSZ_HASH_ALGO)
  24580. #error "WOLFSSL_ECDSA_MATCH_HASH and USE_ECDSA_KEYSZ_HASH_ALGO cannot "
  24581. "be used together"
  24582. #endif
  24583. #if defined(HAVE_ECC) && (defined(WOLFSSL_TLS13) || \
  24584. defined(WOLFSSL_ECDSA_MATCH_HASH))
  24585. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  24586. if (sigAlgo == sm2_sa_algo && hashAlgo == sm3_mac
  24587. #ifndef WOLFSSL_ECDSA_MATCH_HASH
  24588. && IsAtLeastTLSv1_3(ssl->version)
  24589. #endif
  24590. ) {
  24591. /* Must be exact match. */
  24592. if (CmpEccStrength(hashAlgo, ssl->buffers.keySz) != 0)
  24593. continue;
  24594. /* Matched SM2-SM3 - set chosen and finished. */
  24595. ssl->options.sigAlgo = sigAlgo;
  24596. ssl->options.hashAlgo = hashAlgo;
  24597. ret = 0;
  24598. break;
  24599. }
  24600. else
  24601. #endif
  24602. if (sigAlgo == ecc_dsa_sa_algo
  24603. #ifndef WOLFSSL_ECDSA_MATCH_HASH
  24604. && IsAtLeastTLSv1_3(ssl->version)
  24605. #endif
  24606. ) {
  24607. /* Must be exact match. */
  24608. if (CmpEccStrength(hashAlgo, ssl->buffers.keySz) != 0)
  24609. continue;
  24610. /* Matched ECDSA exactly - set chosen and finished. */
  24611. ssl->options.hashAlgo = hashAlgo;
  24612. ssl->options.sigAlgo = sigAlgo;
  24613. ret = 0;
  24614. break;
  24615. }
  24616. #endif
  24617. /* For ECDSA the `USE_ECDSA_KEYSZ_HASH_ALGO` build option will choose a hash
  24618. * algorithm that matches the ephemeral ECDHE key size or the next highest
  24619. * available. This workaround resolves issue with some peer's that do not
  24620. * properly support scenarios such as a P-256 key hashed with SHA512.
  24621. */
  24622. #if defined(HAVE_ECC) && defined(USE_ECDSA_KEYSZ_HASH_ALGO)
  24623. if (sigAlgo == ecc_dsa_sa_algo) {
  24624. int cmp = CmpEccStrength(hashAlgo, ssl->eccTempKeySz);
  24625. /* Keep looking if digest not strong enough. */
  24626. if (cmp < 0)
  24627. continue;
  24628. /* Looking for exact match or next highest. */
  24629. if (ret != 0 || hashAlgo <= ssl->options.hashAlgo) {
  24630. ssl->options.hashAlgo = hashAlgo;
  24631. ssl->options.sigAlgo = sigAlgo;
  24632. #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
  24633. ssl->namedGroup = 0;
  24634. #endif
  24635. ret = 0;
  24636. }
  24637. /* Continue looking if not the same strength. */
  24638. if (cmp > 0)
  24639. continue;
  24640. /* Exact match - finished. */
  24641. break;
  24642. }
  24643. #endif
  24644. switch (hashAlgo) {
  24645. #ifndef NO_SHA
  24646. case sha_mac:
  24647. #endif
  24648. #ifdef WOLFSSL_SHA224
  24649. case sha224_mac:
  24650. #endif
  24651. #ifndef NO_SHA256
  24652. case sha256_mac:
  24653. #endif
  24654. #ifdef WOLFSSL_SHA384
  24655. case sha384_mac:
  24656. #endif
  24657. #ifdef WOLFSSL_SHA512
  24658. case sha512_mac:
  24659. #endif
  24660. #ifdef WOLFSSL_SM3
  24661. case sm3_mac:
  24662. #endif
  24663. #ifdef WOLFSSL_STRONGEST_HASH_SIG
  24664. /* Is hash algorithm weaker than chosen/min? */
  24665. if (hashAlgo < ssl->options.hashAlgo)
  24666. break;
  24667. #else
  24668. /* Is hash algorithm stronger than last chosen? */
  24669. if (ret == 0 && hashAlgo > ssl->options.hashAlgo)
  24670. break;
  24671. #endif
  24672. if (IsAtLeastTLSv1_2(ssl) && !IsAtLeastTLSv1_3(ssl->version) &&
  24673. (ssl->options.side == WOLFSSL_CLIENT_END)) {
  24674. /* TLS 1.2 client deciding hash algorithm for
  24675. * CertificateVerify. Hash must be one of the handshake
  24676. * hashes being maintained. */
  24677. if (1
  24678. #ifndef NO_SHA
  24679. && (hashAlgo != sha_mac)
  24680. #endif
  24681. #ifndef NO_SHA256
  24682. && (hashAlgo != sha256_mac)
  24683. #endif
  24684. #ifdef WOLFSSL_SHA384
  24685. && (hashAlgo != sha384_mac)
  24686. #endif
  24687. #ifdef WOLFSSL_SHA512
  24688. && (hashAlgo != sha512_mac)
  24689. #endif
  24690. #ifdef WOLFSSL_SM3
  24691. && (hashAlgo != sm3_mac)
  24692. #endif
  24693. )
  24694. {
  24695. break;
  24696. }
  24697. }
  24698. /* The chosen one - but keep looking. */
  24699. ssl->options.hashAlgo = hashAlgo;
  24700. ssl->options.sigAlgo = sigAlgo;
  24701. ret = 0;
  24702. break;
  24703. default:
  24704. /* Support for hash algorithm not compiled in. */
  24705. break;
  24706. }
  24707. }
  24708. return ret;
  24709. }
  24710. #endif /* !defined(NO_WOLFSSL_SERVER) || !defined(NO_CERTS) */
  24711. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  24712. /* Initialize HandShakeInfo */
  24713. void InitHandShakeInfo(HandShakeInfo* info, WOLFSSL* ssl)
  24714. {
  24715. int i;
  24716. info->ssl = ssl;
  24717. info->cipherName[0] = 0;
  24718. for (i = 0; i < MAX_PACKETS_HANDSHAKE; i++)
  24719. info->packetNames[i][0] = 0;
  24720. info->numberPackets = 0;
  24721. info->negotiationError = 0;
  24722. }
  24723. /* Set Final HandShakeInfo parameters */
  24724. void FinishHandShakeInfo(HandShakeInfo* info)
  24725. {
  24726. int i;
  24727. int sz = GetCipherNamesSize();
  24728. for (i = 0; i < sz; i++) {
  24729. #ifndef NO_CIPHER_SUITE_ALIASES
  24730. if (cipher_names[i].flags & WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS)
  24731. continue;
  24732. #endif
  24733. if (info->ssl->options.cipherSuite ==
  24734. (byte)cipher_names[i].cipherSuite) {
  24735. if (info->ssl->options.cipherSuite0 == ECC_BYTE)
  24736. continue; /* ECC suites at end */
  24737. XSTRNCPY(info->cipherName, cipher_names[i].name, MAX_CIPHERNAME_SZ);
  24738. info->cipherName[MAX_CIPHERNAME_SZ] = '\0';
  24739. break;
  24740. }
  24741. }
  24742. /* error max and min are negative numbers */
  24743. if (info->ssl->error <= MIN_PARAM_ERR && info->ssl->error >= MAX_PARAM_ERR)
  24744. info->negotiationError = info->ssl->error;
  24745. }
  24746. /* Add name to info packet names, increase packet name count */
  24747. void AddPacketName(WOLFSSL* ssl, const char* name)
  24748. {
  24749. #ifdef WOLFSSL_CALLBACKS
  24750. HandShakeInfo* info = &ssl->handShakeInfo;
  24751. if (info->numberPackets < MAX_PACKETS_HANDSHAKE) {
  24752. char* packetName = info->packetNames[info->numberPackets];
  24753. XSTRNCPY(packetName, name, MAX_PACKETNAME_SZ);
  24754. packetName[MAX_PACKETNAME_SZ] = '\0';
  24755. info->numberPackets++;
  24756. }
  24757. #endif
  24758. (void)ssl;
  24759. (void)name;
  24760. }
  24761. #ifdef WOLFSSL_CALLBACKS
  24762. /* Initialize TimeoutInfo */
  24763. void InitTimeoutInfo(TimeoutInfo* info)
  24764. {
  24765. XMEMSET(info, 0, sizeof(TimeoutInfo));
  24766. }
  24767. /* Free TimeoutInfo */
  24768. void FreeTimeoutInfo(TimeoutInfo* info, void* heap)
  24769. {
  24770. int i;
  24771. (void)heap;
  24772. for (i = 0; i < MAX_PACKETS_HANDSHAKE; i++) {
  24773. if (info->packets[i].bufferValue) {
  24774. XFREE(info->packets[i].bufferValue, heap, DYNAMIC_TYPE_INFO);
  24775. info->packets[i].bufferValue = NULL;
  24776. }
  24777. }
  24778. }
  24779. /* Add packet name to previously added packet info */
  24780. void AddLateName(const char* name, TimeoutInfo* info)
  24781. {
  24782. /* make sure we have a valid previous one */
  24783. if (info->numberPackets > 0 && info->numberPackets <
  24784. MAX_PACKETS_HANDSHAKE) {
  24785. char* packetName = info->packets[info->numberPackets-1].packetName;
  24786. XSTRNCPY(packetName, name, MAX_PACKETNAME_SZ);
  24787. packetName[MAX_PACKETNAME_SZ] = '\0';
  24788. }
  24789. }
  24790. /* Add record header to previously added packet info */
  24791. void AddLateRecordHeader(const RecordLayerHeader* rl, TimeoutInfo* info)
  24792. {
  24793. /* make sure we have a valid previous one */
  24794. if (info->numberPackets > 0 && info->numberPackets <
  24795. MAX_PACKETS_HANDSHAKE) {
  24796. if (info->packets[info->numberPackets - 1].bufferValue)
  24797. XMEMCPY(info->packets[info->numberPackets - 1].bufferValue, rl,
  24798. RECORD_HEADER_SZ);
  24799. else
  24800. XMEMCPY(info->packets[info->numberPackets - 1].value, rl,
  24801. RECORD_HEADER_SZ);
  24802. }
  24803. }
  24804. #endif /* WOLFSSL_CALLBACKS */
  24805. /* Add PacketInfo to TimeoutInfo
  24806. *
  24807. * ssl WOLFSSL structure sending or receiving packet
  24808. * name name of packet being sent
  24809. * type type of packet being sent
  24810. * data data bing sent with packet
  24811. * sz size of data buffer
  24812. * lateRL save space for record layer in TimoutInfo struct
  24813. * written 1 if this packet is being written to wire, 0 if being read
  24814. * heap custom heap to use for mallocs/frees
  24815. */
  24816. int AddPacketInfo(WOLFSSL* ssl, const char* name, int type,
  24817. const byte* data, int sz, int written, int lateRL, void* heap)
  24818. {
  24819. #ifdef WOLFSSL_CALLBACKS
  24820. TimeoutInfo* info = &ssl->timeoutInfo;
  24821. if (info->numberPackets < (MAX_PACKETS_HANDSHAKE - 1)) {
  24822. WOLFSSL_TIMEVAL currTime;
  24823. int totalSz;
  24824. /* add in space for post record layer */
  24825. totalSz = sz + lateRL;
  24826. /* may add name after */
  24827. if (name) {
  24828. char* packetName = info->packets[info->numberPackets].packetName;
  24829. XSTRNCPY(packetName, name, MAX_PACKETNAME_SZ);
  24830. packetName[MAX_PACKETNAME_SZ] = '\0';
  24831. }
  24832. /* add data, put in buffer if bigger than static buffer */
  24833. info->packets[info->numberPackets].valueSz = totalSz;
  24834. if (totalSz < MAX_VALUE_SZ) {
  24835. XMEMCPY(info->packets[info->numberPackets].value + lateRL, data,
  24836. sz);
  24837. }
  24838. else {
  24839. info->packets[info->numberPackets].bufferValue =
  24840. (byte*)XMALLOC(totalSz, heap, DYNAMIC_TYPE_INFO);
  24841. if (!info->packets[info->numberPackets].bufferValue) {
  24842. /* let next alloc catch, just don't fill, not fatal here */
  24843. info->packets[info->numberPackets].valueSz = 0;
  24844. }
  24845. else {
  24846. /* copy over data (which has the handshake header), leaving
  24847. * room for post record layer header if set */
  24848. XMEMCPY(info->packets[info->numberPackets].bufferValue +
  24849. lateRL, data, sz);
  24850. }
  24851. }
  24852. if (gettimeofday(&currTime, 0) < 0)
  24853. return SYSLIB_FAILED_E;
  24854. info->packets[info->numberPackets].timestamp.tv_sec =
  24855. currTime.tv_sec;
  24856. info->packets[info->numberPackets].timestamp.tv_usec =
  24857. currTime.tv_usec;
  24858. info->numberPackets++;
  24859. }
  24860. #endif /* WOLFSSL_CALLBACKS */
  24861. #ifdef OPENSSL_EXTRA
  24862. if ((ssl->protoMsgCb != NULL) && (sz > 0) &&
  24863. (ssl->keys.encryptionOn != 1)) {
  24864. /* version from hex to dec 16 is 16^1, 256 from 16^2 and
  24865. 4096 from 16^3 */
  24866. int version = (ssl->version.minor & 0x0F) +
  24867. ((ssl->version.minor & 0xF0) << 4) +
  24868. ((ssl->version.major & 0x0F) << 8) +
  24869. ((ssl->version.major & 0xF0) << 12);
  24870. ssl->protoMsgCb(written, version, type,
  24871. (const void *)data, (size_t)sz,
  24872. ssl, ssl->protoMsgCtx);
  24873. }
  24874. #endif /* OPENSSL_EXTRA */
  24875. (void)written;
  24876. (void)name;
  24877. (void)heap;
  24878. (void)type;
  24879. (void)ssl;
  24880. (void)lateRL;
  24881. return 0;
  24882. }
  24883. #endif /* WOLFSSL_CALLBACKS */
  24884. #if !defined(NO_CERTS)
  24885. #if defined(WOLF_PRIVATE_KEY_ID) && !defined(NO_CHECK_PRIVATE_KEY)
  24886. /* Create a private key for a device.
  24887. *
  24888. * pkey Key object.
  24889. * data Data to identify key.
  24890. * length Length of data.
  24891. * hsType Type of the key to create.
  24892. * heap Custom heap to use for mallocs/frees
  24893. * devId Id for device.
  24894. * return 0 on success.
  24895. * return NOT_COMPILED_IN if algorithm type not supported.
  24896. * return MEMORY_E on memory allocation failure.
  24897. * return other internal error
  24898. */
  24899. int CreateDevPrivateKey(void** pkey, byte* data, word32 length, int hsType,
  24900. int label, int id, void* heap, int devId)
  24901. {
  24902. int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
  24903. if (hsType == DYNAMIC_TYPE_RSA) {
  24904. #ifndef NO_RSA
  24905. RsaKey* rsaKey;
  24906. rsaKey = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA);
  24907. if (rsaKey == NULL) {
  24908. return MEMORY_E;
  24909. }
  24910. if (label) {
  24911. ret = wc_InitRsaKey_Label(rsaKey, (char*)data, heap, devId);
  24912. }
  24913. else if (id) {
  24914. ret = wc_InitRsaKey_Id(rsaKey, data, (int)length, heap, devId);
  24915. }
  24916. if (ret == 0) {
  24917. *pkey = (void*)rsaKey;
  24918. }
  24919. else {
  24920. XFREE(rsaKey, heap, DYNAMIC_TYPE_RSA);
  24921. }
  24922. #endif
  24923. }
  24924. else if (hsType == DYNAMIC_TYPE_ECC) {
  24925. #ifdef HAVE_ECC
  24926. ecc_key* ecKey;
  24927. ecKey = (ecc_key*)XMALLOC(sizeof(ecc_key), heap, DYNAMIC_TYPE_ECC);
  24928. if (ecKey == NULL) {
  24929. return MEMORY_E;
  24930. }
  24931. if (label) {
  24932. ret = wc_ecc_init_label(ecKey, (char*)data, heap, devId);
  24933. }
  24934. else if (id) {
  24935. ret = wc_ecc_init_id(ecKey, data, (int)length, heap, devId);
  24936. }
  24937. if (ret == 0) {
  24938. *pkey = (void*)ecKey;
  24939. }
  24940. else {
  24941. XFREE(ecKey, heap, DYNAMIC_TYPE_ECC);
  24942. }
  24943. #endif
  24944. }
  24945. else if (hsType == DYNAMIC_TYPE_DILITHIUM) {
  24946. #if defined(HAVE_DILITHIUM)
  24947. dilithium_key* dilithiumKey;
  24948. dilithiumKey = (dilithium_key*)XMALLOC(sizeof(dilithium_key), heap,
  24949. DYNAMIC_TYPE_DILITHIUM);
  24950. if (dilithiumKey == NULL) {
  24951. return MEMORY_E;
  24952. }
  24953. if (label) {
  24954. ret = wc_dilithium_init_label(dilithiumKey, (char*)data,
  24955. heap, devId);
  24956. }
  24957. else if (id) {
  24958. ret = wc_dilithium_init_id(dilithiumKey, data, length, heap, devId);
  24959. }
  24960. if (ret == 0) {
  24961. *pkey = (void*)dilithiumKey;
  24962. }
  24963. else {
  24964. XFREE(dilithiumKey, heap, DYNAMIC_TYPE_DILITHIUM);
  24965. }
  24966. #endif
  24967. }
  24968. else if (hsType == DYNAMIC_TYPE_FALCON) {
  24969. #if defined(HAVE_FALCON)
  24970. falcon_key* falconKey;
  24971. falconKey = (falcon_key*)XMALLOC(sizeof(falcon_key), heap,
  24972. DYNAMIC_TYPE_FALCON);
  24973. if (falconKey == NULL) {
  24974. return MEMORY_E;
  24975. }
  24976. if (label) {
  24977. ret = wc_falcon_init_label(falconKey, (char*)data, heap, devId);
  24978. }
  24979. else if (id) {
  24980. ret = wc_falcon_init_id(falconKey, data, length, heap, devId);
  24981. }
  24982. if (ret == 0) {
  24983. *pkey = (void*)falconKey;
  24984. }
  24985. else {
  24986. XFREE(falconKey, heap, DYNAMIC_TYPE_FALCON);
  24987. }
  24988. #endif
  24989. }
  24990. return ret;
  24991. }
  24992. #endif /* WOLF_PRIVATE_KEY_ID && !NO_CHECK_PRIVATE_KEY */
  24993. /* Decode the private key - RSA/ECC/Ed25519/Ed448/Falcon/Dilithium - and
  24994. * creates a key object.
  24995. *
  24996. * The signature type is set as well.
  24997. * The maximum length of a signature is returned.
  24998. *
  24999. * ssl The SSL/TLS object.
  25000. * length The length of a signature.
  25001. * returns 0 on success, otherwise failure.
  25002. */
  25003. int DecodePrivateKey(WOLFSSL *ssl, word32* length)
  25004. {
  25005. int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
  25006. int keySz;
  25007. word32 idx;
  25008. /* make sure private key exists */
  25009. if (ssl->buffers.key == NULL || ssl->buffers.key->buffer == NULL) {
  25010. /* allow no private key if using external */
  25011. #ifdef WOLF_PRIVATE_KEY_ID
  25012. if (ssl->devId != INVALID_DEVID
  25013. #ifdef HAVE_PK_CALLBACKS
  25014. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  25015. #endif
  25016. ) {
  25017. *length = (word32)GetPrivateKeySigSize(ssl);
  25018. return 0;
  25019. }
  25020. else
  25021. #endif
  25022. {
  25023. WOLFSSL_MSG("Private key missing!");
  25024. ERROR_OUT(NO_PRIVATE_KEY, exit_dpk);
  25025. }
  25026. }
  25027. #ifdef WOLF_PRIVATE_KEY_ID
  25028. if (ssl->buffers.keyDevId != INVALID_DEVID && (ssl->buffers.keyId ||
  25029. ssl->buffers.keyLabel)) {
  25030. if (ssl->buffers.keyType == rsa_sa_algo)
  25031. ssl->hsType = DYNAMIC_TYPE_RSA;
  25032. else if (ssl->buffers.keyType == ecc_dsa_sa_algo)
  25033. ssl->hsType = DYNAMIC_TYPE_ECC;
  25034. else if ((ssl->buffers.keyType == falcon_level1_sa_algo) ||
  25035. (ssl->buffers.keyType == falcon_level5_sa_algo))
  25036. ssl->hsType = DYNAMIC_TYPE_FALCON;
  25037. else if ((ssl->buffers.keyType == dilithium_level2_sa_algo) ||
  25038. (ssl->buffers.keyType == dilithium_level3_sa_algo) ||
  25039. (ssl->buffers.keyType == dilithium_level5_sa_algo))
  25040. ssl->hsType = DYNAMIC_TYPE_DILITHIUM;
  25041. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  25042. if (ret != 0) {
  25043. goto exit_dpk;
  25044. }
  25045. if (ssl->buffers.keyType == rsa_sa_algo) {
  25046. #ifndef NO_RSA
  25047. if (ssl->buffers.keyLabel) {
  25048. ret = wc_InitRsaKey_Label((RsaKey*)ssl->hsKey,
  25049. (char*)ssl->buffers.key->buffer,
  25050. ssl->heap, ssl->buffers.keyDevId);
  25051. }
  25052. else if (ssl->buffers.keyId) {
  25053. ret = wc_InitRsaKey_Id((RsaKey*)ssl->hsKey,
  25054. ssl->buffers.key->buffer,
  25055. ssl->buffers.key->length, ssl->heap,
  25056. ssl->buffers.keyDevId);
  25057. }
  25058. if (ret == 0) {
  25059. if (ssl->buffers.keySz < ssl->options.minRsaKeySz) {
  25060. WOLFSSL_MSG("RSA key size too small");
  25061. ERROR_OUT(RSA_KEY_SIZE_E, exit_dpk);
  25062. }
  25063. /* Return the maximum signature length. */
  25064. *length = (word32)ssl->buffers.keySz;
  25065. }
  25066. #else
  25067. ret = NOT_COMPILED_IN;
  25068. #endif
  25069. }
  25070. else if (ssl->buffers.keyType == ecc_dsa_sa_algo) {
  25071. #ifdef HAVE_ECC
  25072. if (ssl->buffers.keyLabel) {
  25073. ret = wc_ecc_init_label((ecc_key*)ssl->hsKey,
  25074. (char*)ssl->buffers.key->buffer,
  25075. ssl->heap, ssl->buffers.keyDevId);
  25076. }
  25077. else if (ssl->buffers.keyId) {
  25078. ret = wc_ecc_init_id((ecc_key*)ssl->hsKey,
  25079. ssl->buffers.key->buffer,
  25080. ssl->buffers.key->length, ssl->heap,
  25081. ssl->buffers.keyDevId);
  25082. }
  25083. if (ret == 0) {
  25084. if (ssl->buffers.keySz < ssl->options.minEccKeySz) {
  25085. WOLFSSL_MSG("ECC key size too small");
  25086. ERROR_OUT(ECC_KEY_SIZE_E, exit_dpk);
  25087. }
  25088. /* Return the maximum signature length. */
  25089. *length = (word32)wc_ecc_sig_size_calc(ssl->buffers.keySz);
  25090. }
  25091. #else
  25092. ret = NOT_COMPILED_IN;
  25093. #endif
  25094. }
  25095. else if ((ssl->buffers.keyType == falcon_level1_sa_algo) ||
  25096. (ssl->buffers.keyType == falcon_level5_sa_algo)) {
  25097. #if defined(HAVE_FALCON)
  25098. if (ssl->buffers.keyLabel) {
  25099. ret = wc_falcon_init_label((falcon_key*)ssl->hsKey,
  25100. (char*)ssl->buffers.key->buffer,
  25101. ssl->heap, ssl->buffers.keyDevId);
  25102. }
  25103. else if (ssl->buffers.keyId) {
  25104. ret = wc_falcon_init_id((falcon_key*)ssl->hsKey,
  25105. ssl->buffers.key->buffer,
  25106. ssl->buffers.key->length, ssl->heap,
  25107. ssl->buffers.keyDevId);
  25108. }
  25109. if (ret == 0) {
  25110. if (ssl->buffers.keyType == falcon_level1_sa_algo) {
  25111. ret = wc_falcon_set_level((falcon_key*)ssl->hsKey, 1);
  25112. }
  25113. else if (ssl->buffers.keyType == falcon_level5_sa_algo) {
  25114. ret = wc_falcon_set_level((falcon_key*)ssl->hsKey, 5);
  25115. }
  25116. }
  25117. if (ret == 0) {
  25118. if (ssl->buffers.keySz < ssl->options.minFalconKeySz) {
  25119. WOLFSSL_MSG("Falcon key size too small");
  25120. ERROR_OUT(FALCON_KEY_SIZE_E, exit_dpk);
  25121. }
  25122. /* Return the maximum signature length. */
  25123. *length = wc_falcon_sig_size((falcon_key*)ssl->hsKey);
  25124. }
  25125. #else
  25126. ret = NOT_COMPILED_IN;
  25127. #endif
  25128. }
  25129. else if ((ssl->buffers.keyType == dilithium_level2_sa_algo) ||
  25130. (ssl->buffers.keyType == dilithium_level3_sa_algo) ||
  25131. (ssl->buffers.keyType == dilithium_level5_sa_algo)) {
  25132. #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN)
  25133. if (ssl->buffers.keyLabel) {
  25134. ret = wc_dilithium_init_label((dilithium_key*)ssl->hsKey,
  25135. (char*)ssl->buffers.key->buffer,
  25136. ssl->heap, ssl->buffers.keyDevId);
  25137. }
  25138. else if (ssl->buffers.keyId) {
  25139. ret = wc_dilithium_init_id((dilithium_key*)ssl->hsKey,
  25140. ssl->buffers.key->buffer,
  25141. ssl->buffers.key->length, ssl->heap,
  25142. ssl->buffers.keyDevId);
  25143. }
  25144. if (ret == 0) {
  25145. if (ssl->buffers.keyType == dilithium_level2_sa_algo) {
  25146. ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 2);
  25147. }
  25148. else if (ssl->buffers.keyType == dilithium_level3_sa_algo) {
  25149. ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 3);
  25150. }
  25151. else if (ssl->buffers.keyType == dilithium_level5_sa_algo) {
  25152. ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 5);
  25153. }
  25154. }
  25155. if (ret == 0) {
  25156. if (ssl->buffers.keySz < ssl->options.minDilithiumKeySz) {
  25157. WOLFSSL_MSG("Dilithium key size too small");
  25158. ERROR_OUT(DILITHIUM_KEY_SIZE_E, exit_dpk);
  25159. }
  25160. /* Return the maximum signature length. */
  25161. *length = wc_dilithium_sig_size(
  25162. (dilithium_key*)ssl->hsKey);
  25163. }
  25164. #else
  25165. ret = NOT_COMPILED_IN;
  25166. #endif
  25167. }
  25168. goto exit_dpk;
  25169. }
  25170. #endif /* WOLF_PRIVATE_KEY_ID */
  25171. #ifndef NO_RSA
  25172. if (ssl->buffers.keyType == rsa_sa_algo || ssl->buffers.keyType == 0) {
  25173. ssl->hsType = DYNAMIC_TYPE_RSA;
  25174. ret = AllocKey(ssl, (int)ssl->hsType, &ssl->hsKey);
  25175. if (ret != 0) {
  25176. goto exit_dpk;
  25177. }
  25178. WOLFSSL_MSG("Trying RSA private key");
  25179. /* Set start of data to beginning of buffer. */
  25180. idx = 0;
  25181. /* Decode the key assuming it is an RSA private key. */
  25182. ret = wc_RsaPrivateKeyDecode(ssl->buffers.key->buffer, &idx,
  25183. (RsaKey*)ssl->hsKey, ssl->buffers.key->length);
  25184. #ifdef WOLF_PRIVATE_KEY_ID
  25185. /* if using external key then allow using a public key */
  25186. if (ret != 0 && (ssl->devId != INVALID_DEVID
  25187. #ifdef HAVE_PK_CALLBACKS
  25188. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  25189. #endif
  25190. )) {
  25191. WOLFSSL_MSG("Trying RSA public key with crypto callbacks");
  25192. idx = 0;
  25193. ret = wc_RsaPublicKeyDecode(ssl->buffers.key->buffer, &idx,
  25194. (RsaKey*)ssl->hsKey, ssl->buffers.key->length);
  25195. }
  25196. #endif
  25197. if (ret == 0) {
  25198. WOLFSSL_MSG("Using RSA private key");
  25199. /* It worked so check it meets minimum key size requirements. */
  25200. keySz = wc_RsaEncryptSize((RsaKey*)ssl->hsKey);
  25201. if (keySz < 0) { /* check if keySz has error case */
  25202. ERROR_OUT(keySz, exit_dpk);
  25203. }
  25204. if (keySz < ssl->options.minRsaKeySz) {
  25205. WOLFSSL_MSG("RSA key size too small");
  25206. ERROR_OUT(RSA_KEY_SIZE_E, exit_dpk);
  25207. }
  25208. /* Return the maximum signature length. */
  25209. *length = (word32)keySz;
  25210. goto exit_dpk;
  25211. }
  25212. }
  25213. #endif /* !NO_RSA */
  25214. #ifdef HAVE_ECC
  25215. #ifndef NO_RSA
  25216. FreeKey(ssl, (int)ssl->hsType, (void**)&ssl->hsKey);
  25217. #endif /* !NO_RSA */
  25218. if (ssl->buffers.keyType == ecc_dsa_sa_algo || ssl->buffers.keyType == 0
  25219. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  25220. || ssl->buffers.keyType == sm2_sa_algo
  25221. #endif
  25222. ) {
  25223. ssl->hsType = DYNAMIC_TYPE_ECC;
  25224. ret = AllocKey(ssl, (int)ssl->hsType, &ssl->hsKey);
  25225. if (ret != 0) {
  25226. goto exit_dpk;
  25227. }
  25228. #ifndef NO_RSA
  25229. WOLFSSL_MSG("Trying ECC private key, RSA didn't work");
  25230. #else
  25231. WOLFSSL_MSG("Trying ECC private key");
  25232. #endif
  25233. /* Set start of data to beginning of buffer. */
  25234. idx = 0;
  25235. /* Decode the key assuming it is an ECC private key. */
  25236. ret = wc_EccPrivateKeyDecode(ssl->buffers.key->buffer, &idx,
  25237. (ecc_key*)ssl->hsKey,
  25238. ssl->buffers.key->length);
  25239. #ifdef WOLF_PRIVATE_KEY_ID
  25240. /* if using external key then allow using a public key */
  25241. if (ret != 0 && (ssl->devId != INVALID_DEVID
  25242. #ifdef HAVE_PK_CALLBACKS
  25243. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  25244. #endif
  25245. )) {
  25246. WOLFSSL_MSG("Trying ECC public key with crypto callbacks");
  25247. idx = 0;
  25248. ret = wc_EccPublicKeyDecode(ssl->buffers.key->buffer, &idx,
  25249. (ecc_key*)ssl->hsKey,
  25250. ssl->buffers.key->length);
  25251. }
  25252. #endif
  25253. #ifdef WOLFSSL_SM2
  25254. if ((ret == 0) && (ssl->buffers.keyType == sm2_sa_algo)) {
  25255. ret = wc_ecc_set_curve((ecc_key*)ssl->hsKey,
  25256. WOLFSSL_SM2_KEY_BITS / 8, ECC_SM2P256V1);
  25257. }
  25258. #endif
  25259. if (ret == 0) {
  25260. WOLFSSL_MSG("Using ECC private key");
  25261. /* Check it meets the minimum ECC key size requirements. */
  25262. keySz = wc_ecc_size((ecc_key*)ssl->hsKey);
  25263. if (keySz < ssl->options.minEccKeySz) {
  25264. WOLFSSL_MSG("ECC key size too small");
  25265. ERROR_OUT(ECC_KEY_SIZE_E, exit_dpk);
  25266. }
  25267. /* Return the maximum signature length. */
  25268. *length = (word32)wc_ecc_sig_size((ecc_key*)ssl->hsKey);
  25269. goto exit_dpk;
  25270. }
  25271. }
  25272. #endif
  25273. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  25274. #if !defined(NO_RSA) || defined(HAVE_ECC)
  25275. FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey);
  25276. #endif
  25277. if (ssl->buffers.keyType == ed25519_sa_algo || ssl->buffers.keyType == 0) {
  25278. ssl->hsType = DYNAMIC_TYPE_ED25519;
  25279. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  25280. if (ret != 0) {
  25281. goto exit_dpk;
  25282. }
  25283. #ifdef HAVE_ECC
  25284. WOLFSSL_MSG("Trying ED25519 private key, ECC didn't work");
  25285. #elif !defined(NO_RSA)
  25286. WOLFSSL_MSG("Trying ED25519 private key, RSA didn't work");
  25287. #else
  25288. WOLFSSL_MSG("Trying ED25519 private key");
  25289. #endif
  25290. /* Set start of data to beginning of buffer. */
  25291. idx = 0;
  25292. /* Decode the key assuming it is an ED25519 private key. */
  25293. ret = wc_Ed25519PrivateKeyDecode(ssl->buffers.key->buffer, &idx,
  25294. (ed25519_key*)ssl->hsKey,
  25295. ssl->buffers.key->length);
  25296. #ifdef WOLF_PRIVATE_KEY_ID
  25297. /* if using external key then allow using a public key */
  25298. if (ret != 0 && (ssl->devId != INVALID_DEVID
  25299. #ifdef HAVE_PK_CALLBACKS
  25300. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  25301. #endif
  25302. )) {
  25303. WOLFSSL_MSG("Trying ED25519 public key with crypto callbacks");
  25304. idx = 0;
  25305. ret = wc_Ed25519PublicKeyDecode(ssl->buffers.key->buffer, &idx,
  25306. (ed25519_key*)ssl->hsKey,
  25307. ssl->buffers.key->length);
  25308. }
  25309. #endif
  25310. if (ret == 0) {
  25311. WOLFSSL_MSG("Using ED25519 private key");
  25312. /* Check it meets the minimum ECC key size requirements. */
  25313. if (ED25519_KEY_SIZE < ssl->options.minEccKeySz) {
  25314. WOLFSSL_MSG("ED25519 key size too small");
  25315. ERROR_OUT(ECC_KEY_SIZE_E, exit_dpk);
  25316. }
  25317. /* Return the maximum signature length. */
  25318. *length = ED25519_SIG_SIZE;
  25319. goto exit_dpk;
  25320. }
  25321. }
  25322. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */
  25323. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  25324. #if !defined(NO_RSA) || defined(HAVE_ECC)
  25325. FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey);
  25326. #endif
  25327. if (ssl->buffers.keyType == ed448_sa_algo || ssl->buffers.keyType == 0) {
  25328. ssl->hsType = DYNAMIC_TYPE_ED448;
  25329. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  25330. if (ret != 0) {
  25331. goto exit_dpk;
  25332. }
  25333. #ifdef HAVE_ED25519
  25334. WOLFSSL_MSG("Trying ED448 private key, ED25519 didn't work");
  25335. #elif defined(HAVE_ECC)
  25336. WOLFSSL_MSG("Trying ED448 private key, ECC didn't work");
  25337. #elif !defined(NO_RSA)
  25338. WOLFSSL_MSG("Trying ED448 private key, RSA didn't work");
  25339. #else
  25340. WOLFSSL_MSG("Trying ED448 private key");
  25341. #endif
  25342. /* Set start of data to beginning of buffer. */
  25343. idx = 0;
  25344. /* Decode the key assuming it is an ED448 private key. */
  25345. ret = wc_Ed448PrivateKeyDecode(ssl->buffers.key->buffer, &idx,
  25346. (ed448_key*)ssl->hsKey,
  25347. ssl->buffers.key->length);
  25348. #ifdef WOLF_PRIVATE_KEY_ID
  25349. /* if using external key then allow using a public key */
  25350. if (ret != 0 && (ssl->devId != INVALID_DEVID
  25351. #ifdef HAVE_PK_CALLBACKS
  25352. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  25353. #endif
  25354. )) {
  25355. WOLFSSL_MSG("Trying ED25519 public key with crypto callbacks");
  25356. idx = 0;
  25357. ret = wc_Ed448PublicKeyDecode(ssl->buffers.key->buffer, &idx,
  25358. (ed448_key*)ssl->hsKey,
  25359. ssl->buffers.key->length);
  25360. }
  25361. #endif
  25362. if (ret == 0) {
  25363. WOLFSSL_MSG("Using ED448 private key");
  25364. /* Check it meets the minimum ECC key size requirements. */
  25365. if (ED448_KEY_SIZE < ssl->options.minEccKeySz) {
  25366. WOLFSSL_MSG("ED448 key size too small");
  25367. ERROR_OUT(ECC_KEY_SIZE_E, exit_dpk);
  25368. }
  25369. /* Return the maximum signature length. */
  25370. *length = ED448_SIG_SIZE;
  25371. goto exit_dpk;
  25372. }
  25373. }
  25374. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
  25375. #if defined(HAVE_FALCON)
  25376. #if !defined(NO_RSA) || defined(HAVE_ECC)
  25377. FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey);
  25378. #endif
  25379. if (ssl->buffers.keyType == falcon_level1_sa_algo ||
  25380. ssl->buffers.keyType == falcon_level5_sa_algo ||
  25381. ssl->buffers.keyType == 0) {
  25382. ssl->hsType = DYNAMIC_TYPE_FALCON;
  25383. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  25384. if (ret != 0) {
  25385. goto exit_dpk;
  25386. }
  25387. if (ssl->buffers.keyType == falcon_level1_sa_algo) {
  25388. ret = wc_falcon_set_level((falcon_key*)ssl->hsKey, 1);
  25389. }
  25390. else if (ssl->buffers.keyType == falcon_level5_sa_algo) {
  25391. ret = wc_falcon_set_level((falcon_key*)ssl->hsKey, 5);
  25392. }
  25393. else {
  25394. /* What if ssl->buffers.keyType is 0? We might want to do something
  25395. * more graceful here. */
  25396. ret = ALGO_ID_E;
  25397. }
  25398. if (ret != 0) {
  25399. goto exit_dpk;
  25400. }
  25401. #if defined(HAVE_ED448)
  25402. WOLFSSL_MSG("Trying Falcon private key, ED448 didn't work");
  25403. #elif defined(HAVE_ED25519)
  25404. WOLFSSL_MSG("Trying Falcon private key, ED25519 didn't work");
  25405. #elif defined(HAVE_ECC)
  25406. WOLFSSL_MSG("Trying Falcon private key, ECC didn't work");
  25407. #elif !defined(NO_RSA)
  25408. WOLFSSL_MSG("Trying Falcon private key, RSA didn't work");
  25409. #else
  25410. WOLFSSL_MSG("Trying Falcon private key");
  25411. #endif
  25412. /* Set start of data to beginning of buffer. */
  25413. idx = 0;
  25414. /* Decode the key assuming it is a Falcon private key. */
  25415. ret = wc_falcon_import_private_only(ssl->buffers.key->buffer,
  25416. ssl->buffers.key->length,
  25417. (falcon_key*)ssl->hsKey);
  25418. if (ret == 0) {
  25419. WOLFSSL_MSG("Using Falcon private key");
  25420. /* Check it meets the minimum Falcon key size requirements. */
  25421. keySz = wc_falcon_size((falcon_key*)ssl->hsKey);
  25422. if (keySz < ssl->options.minFalconKeySz) {
  25423. WOLFSSL_MSG("Falcon key size too small");
  25424. ERROR_OUT(FALCON_KEY_SIZE_E, exit_dpk);
  25425. }
  25426. /* Return the maximum signature length. */
  25427. *length = wc_falcon_sig_size((falcon_key*)ssl->hsKey);
  25428. goto exit_dpk;
  25429. }
  25430. }
  25431. #endif /* HAVE_FALCON */
  25432. #if defined(HAVE_DILITHIUM) && !defined(WOLFSSL_DILITHIUM_NO_SIGN) && \
  25433. !defined(WOLFSSL_DILITHIUM_NO_ASN1)
  25434. #if !defined(NO_RSA) || defined(HAVE_ECC)
  25435. FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey);
  25436. #endif
  25437. if (ssl->buffers.keyType == dilithium_level2_sa_algo ||
  25438. ssl->buffers.keyType == dilithium_level3_sa_algo ||
  25439. ssl->buffers.keyType == dilithium_level5_sa_algo ||
  25440. ssl->buffers.keyType == 0) {
  25441. ssl->hsType = DYNAMIC_TYPE_DILITHIUM;
  25442. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  25443. if (ret != 0) {
  25444. goto exit_dpk;
  25445. }
  25446. if (ssl->buffers.keyType == dilithium_level2_sa_algo) {
  25447. ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 2);
  25448. }
  25449. else if (ssl->buffers.keyType == dilithium_level3_sa_algo) {
  25450. ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 3);
  25451. }
  25452. else if (ssl->buffers.keyType == dilithium_level5_sa_algo) {
  25453. ret = wc_dilithium_set_level((dilithium_key*)ssl->hsKey, 5);
  25454. }
  25455. else {
  25456. /* What if ssl->buffers.keyType is 0? We might want to do something
  25457. * more graceful here. */
  25458. ret = ALGO_ID_E;
  25459. }
  25460. if (ret != 0) {
  25461. goto exit_dpk;
  25462. }
  25463. #if defined(HAVE_ED448)
  25464. WOLFSSL_MSG("Trying Dilithium private key, ED448 didn't work");
  25465. #elif defined(HAVE_ED25519)
  25466. WOLFSSL_MSG("Trying Dilithium private key, ED25519 didn't work");
  25467. #elif defined(HAVE_ECC)
  25468. WOLFSSL_MSG("Trying Dilithium private key, ECC didn't work");
  25469. #elif !defined(NO_RSA)
  25470. WOLFSSL_MSG("Trying Dilithium private key, RSA didn't work");
  25471. #elif defined(HAVE_FALCON)
  25472. WOLFSSL_MSG("Trying Dilithium private key, Falcon didn't work");
  25473. #else
  25474. WOLFSSL_MSG("Trying Dilithium private key");
  25475. #endif
  25476. /* Set start of data to beginning of buffer. */
  25477. idx = 0;
  25478. /* Decode the key assuming it is a Dilithium private key. */
  25479. ret = wc_Dilithium_PrivateKeyDecode(ssl->buffers.key->buffer,
  25480. &idx,
  25481. (dilithium_key*)ssl->hsKey,
  25482. ssl->buffers.key->length);
  25483. if (ret == 0) {
  25484. WOLFSSL_MSG("Using Dilithium private key");
  25485. /* Check it meets the minimum Dilithium key size requirements. */
  25486. keySz = wc_dilithium_size((dilithium_key*)ssl->hsKey);
  25487. if (keySz < ssl->options.minDilithiumKeySz) {
  25488. WOLFSSL_MSG("Dilithium key size too small");
  25489. ERROR_OUT(DILITHIUM_KEY_SIZE_E, exit_dpk);
  25490. }
  25491. /* Return the maximum signature length. */
  25492. *length = wc_dilithium_sig_size((dilithium_key*)ssl->hsKey);
  25493. goto exit_dpk;
  25494. }
  25495. }
  25496. #endif /* HAVE_DILITHIUM */
  25497. (void)idx;
  25498. (void)keySz;
  25499. (void)length;
  25500. exit_dpk:
  25501. if (ret != 0) {
  25502. WOLFSSL_ERROR_VERBOSE(ret);
  25503. }
  25504. return ret;
  25505. }
  25506. #if defined(WOLFSSL_DUAL_ALG_CERTS)
  25507. /* This is just like the above, but only consider RSA, ECC, Falcon and
  25508. * Dilthium; Furthermore, use the alternative key, not the native key.
  25509. */
  25510. int DecodeAltPrivateKey(WOLFSSL *ssl, word32* length)
  25511. {
  25512. int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
  25513. int keySz;
  25514. word32 idx;
  25515. /* make sure alt private key exists */
  25516. if (ssl->buffers.altKey == NULL || ssl->buffers.altKey->buffer == NULL) {
  25517. WOLFSSL_MSG("Alternative Private key missing!");
  25518. ERROR_OUT(NO_PRIVATE_KEY, exit_dapk);
  25519. }
  25520. #ifdef WOLFSSL_BLIND_PRIVATE_KEY
  25521. wolfssl_priv_der_unblind(ssl->buffers.altKey, ssl->buffers.altKeyMask);
  25522. #endif
  25523. #ifdef WOLF_PRIVATE_KEY_ID
  25524. if (ssl->buffers.altKeyDevId != INVALID_DEVID &&
  25525. (ssl->buffers.altKeyId || ssl->buffers.altKeyLabel)) {
  25526. if (ssl->buffers.altKeyType == rsa_sa_algo)
  25527. ssl->hsAltType = DYNAMIC_TYPE_RSA;
  25528. else if (ssl->buffers.altKeyType == ecc_dsa_sa_algo)
  25529. ssl->hsAltType = DYNAMIC_TYPE_ECC;
  25530. else if ((ssl->buffers.altKeyType == falcon_level1_sa_algo) ||
  25531. (ssl->buffers.altKeyType == falcon_level5_sa_algo))
  25532. ssl->hsAltType = DYNAMIC_TYPE_FALCON;
  25533. else if ((ssl->buffers.altKeyType == dilithium_level2_sa_algo) ||
  25534. (ssl->buffers.altKeyType == dilithium_level3_sa_algo) ||
  25535. (ssl->buffers.altKeyType == dilithium_level5_sa_algo))
  25536. ssl->hsAltType = DYNAMIC_TYPE_DILITHIUM;
  25537. ret = AllocKey(ssl, ssl->hsAltType, &ssl->hsAltKey);
  25538. if (ret != 0) {
  25539. goto exit_dapk;
  25540. }
  25541. if (ssl->buffers.altKeyType == rsa_sa_algo) {
  25542. #ifndef NO_RSA
  25543. if (ssl->buffers.altKeyLabel) {
  25544. ret = wc_InitRsaKey_Label((RsaKey*)ssl->hsAltKey,
  25545. (char*)ssl->buffers.altKey->buffer,
  25546. ssl->heap, ssl->buffers.altKeyDevId);
  25547. }
  25548. else if (ssl->buffers.altKeyId) {
  25549. ret = wc_InitRsaKey_Id((RsaKey*)ssl->hsAltKey,
  25550. ssl->buffers.altKey->buffer,
  25551. ssl->buffers.altKey->length, ssl->heap,
  25552. ssl->buffers.altKeyDevId);
  25553. }
  25554. if (ret == 0) {
  25555. if (ssl->buffers.altKeySz < ssl->options.minRsaKeySz) {
  25556. WOLFSSL_MSG("RSA key size too small");
  25557. ERROR_OUT(RSA_KEY_SIZE_E, exit_dapk);
  25558. }
  25559. /* Return the maximum signature length. */
  25560. *length = ssl->buffers.altKeySz;
  25561. }
  25562. #else
  25563. ret = NOT_COMPILED_IN;
  25564. #endif
  25565. }
  25566. else if (ssl->buffers.altKeyType == ecc_dsa_sa_algo) {
  25567. #ifdef HAVE_ECC
  25568. if (ssl->buffers.altKeyLabel) {
  25569. ret = wc_ecc_init_label((ecc_key*)ssl->hsAltKey,
  25570. (char*)ssl->buffers.altKey->buffer,
  25571. ssl->heap, ssl->buffers.altKeyDevId);
  25572. }
  25573. else if (ssl->buffers.altKeyId) {
  25574. ret = wc_ecc_init_id((ecc_key*)ssl->hsAltKey,
  25575. ssl->buffers.altKey->buffer,
  25576. ssl->buffers.altKey->length, ssl->heap,
  25577. ssl->buffers.altKeyDevId);
  25578. }
  25579. if (ret == 0) {
  25580. if (ssl->buffers.altKeySz < ssl->options.minEccKeySz) {
  25581. WOLFSSL_MSG("ECC key size too small");
  25582. ERROR_OUT(ECC_KEY_SIZE_E, exit_dapk);
  25583. }
  25584. /* Return the maximum signature length. */
  25585. *length = wc_ecc_sig_size_calc(ssl->buffers.altKeySz);
  25586. }
  25587. #else
  25588. ret = NOT_COMPILED_IN;
  25589. #endif
  25590. }
  25591. else if ((ssl->buffers.altKeyType == falcon_level1_sa_algo) ||
  25592. (ssl->buffers.altKeyType == falcon_level5_sa_algo)) {
  25593. #if defined(HAVE_FALCON)
  25594. if (ssl->buffers.altKeyLabel) {
  25595. ret = wc_falcon_init_label((falcon_key*)ssl->hsAltKey,
  25596. (char*)ssl->buffers.altKey->buffer,
  25597. ssl->heap, ssl->buffers.altKeyDevId);
  25598. }
  25599. else if (ssl->buffers.altKeyId) {
  25600. ret = wc_falcon_init_id((falcon_key*)ssl->hsAltKey,
  25601. ssl->buffers.altKey->buffer,
  25602. ssl->buffers.altKey->length, ssl->heap,
  25603. ssl->buffers.altKeyDevId);
  25604. }
  25605. if (ret == 0) {
  25606. if (ssl->buffers.altKeyType == falcon_level1_sa_algo) {
  25607. ret = wc_falcon_set_level((falcon_key*)ssl->hsAltKey, 1);
  25608. }
  25609. else if (ssl->buffers.altKeyType == falcon_level5_sa_algo) {
  25610. ret = wc_falcon_set_level((falcon_key*)ssl->hsAltKey, 5);
  25611. }
  25612. }
  25613. if (ret == 0) {
  25614. if (ssl->buffers.altKeySz < ssl->options.minFalconKeySz) {
  25615. WOLFSSL_MSG("Falcon key size too small");
  25616. ERROR_OUT(FALCON_KEY_SIZE_E, exit_dapk);
  25617. }
  25618. /* Return the maximum signature length. */
  25619. *length = wc_falcon_sig_size((falcon_key*)ssl->hsAltKey);
  25620. }
  25621. #else
  25622. ret = NOT_COMPILED_IN;
  25623. #endif
  25624. }
  25625. else if ((ssl->buffers.altKeyType == dilithium_level2_sa_algo) ||
  25626. (ssl->buffers.altKeyType == dilithium_level3_sa_algo) ||
  25627. (ssl->buffers.altKeyType == dilithium_level5_sa_algo)) {
  25628. #if defined(HAVE_DILITHIUM)
  25629. if (ssl->buffers.altKeyLabel) {
  25630. ret = wc_dilithium_init_label((dilithium_key*)ssl->hsAltKey,
  25631. (char*)ssl->buffers.altKey->buffer,
  25632. ssl->heap, ssl->buffers.altKeyDevId);
  25633. }
  25634. else if (ssl->buffers.altKeyId) {
  25635. ret = wc_dilithium_init_id((dilithium_key*)ssl->hsAltKey,
  25636. ssl->buffers.altKey->buffer,
  25637. ssl->buffers.altKey->length, ssl->heap,
  25638. ssl->buffers.altKeyDevId);
  25639. }
  25640. if (ret == 0) {
  25641. if (ssl->buffers.altKeyType == dilithium_level2_sa_algo) {
  25642. ret = wc_dilithium_set_level(
  25643. (dilithium_key*)ssl->hsAltKey, 2);
  25644. }
  25645. else if (ssl->buffers.altKeyType == dilithium_level3_sa_algo) {
  25646. ret = wc_dilithium_set_level(
  25647. (dilithium_key*)ssl->hsAltKey, 3);
  25648. }
  25649. else if (ssl->buffers.altKeyType == dilithium_level5_sa_algo) {
  25650. ret = wc_dilithium_set_level(
  25651. (dilithium_key*)ssl->hsAltKey, 5);
  25652. }
  25653. }
  25654. if (ret == 0) {
  25655. if (ssl->buffers.altKeySz < ssl->options.minDilithiumKeySz) {
  25656. WOLFSSL_MSG("Dilithium key size too small");
  25657. ERROR_OUT(DILITHIUM_KEY_SIZE_E, exit_dapk);
  25658. }
  25659. /* Return the maximum signature length. */
  25660. *length = wc_dilithium_sig_size(
  25661. (dilithium_key*)ssl->hsAltKey);
  25662. }
  25663. #else
  25664. ret = NOT_COMPILED_IN;
  25665. #endif
  25666. }
  25667. goto exit_dapk;
  25668. }
  25669. #endif /* WOLF_PRIVATE_KEY_ID */
  25670. #ifndef NO_RSA
  25671. if (ssl->buffers.altKeyType == rsa_sa_algo ||
  25672. ssl->buffers.altKeyType == 0) {
  25673. ssl->hsAltType = DYNAMIC_TYPE_RSA;
  25674. ret = AllocKey(ssl, ssl->hsAltType, &ssl->hsAltKey);
  25675. if (ret != 0) {
  25676. goto exit_dapk;
  25677. }
  25678. WOLFSSL_MSG("Trying RSA private key");
  25679. /* Set start of data to beginning of buffer. */
  25680. idx = 0;
  25681. /* Decode the key assuming it is an RSA private key. */
  25682. ret = wc_RsaPrivateKeyDecode(ssl->buffers.altKey->buffer, &idx,
  25683. (RsaKey*)ssl->hsAltKey, ssl->buffers.altKey->length);
  25684. #ifdef WOLF_PRIVATE_KEY_ID
  25685. /* if using external key then allow using a public key */
  25686. if (ret != 0 && (ssl->devId != INVALID_DEVID
  25687. #ifdef HAVE_PK_CALLBACKS
  25688. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  25689. #endif
  25690. )) {
  25691. WOLFSSL_MSG("Trying RSA public key with crypto callbacks");
  25692. idx = 0;
  25693. ret = wc_RsaPublicKeyDecode(ssl->buffers.altKey->buffer, &idx,
  25694. (RsaKey*)ssl->hsAltKey, ssl->buffers.altKey->length);
  25695. }
  25696. #endif
  25697. if (ret == 0) {
  25698. WOLFSSL_MSG("Using RSA private key");
  25699. /* It worked so check it meets minimum key size requirements. */
  25700. keySz = wc_RsaEncryptSize((RsaKey*)ssl->hsAltKey);
  25701. if (keySz < 0) { /* check if keySz has error case */
  25702. ERROR_OUT(keySz, exit_dapk);
  25703. }
  25704. if (keySz < ssl->options.minRsaKeySz) {
  25705. WOLFSSL_MSG("RSA key size too small");
  25706. ERROR_OUT(RSA_KEY_SIZE_E, exit_dapk);
  25707. }
  25708. /* Return the maximum signature length. */
  25709. *length = keySz;
  25710. goto exit_dapk;
  25711. }
  25712. }
  25713. #endif /* !NO_RSA */
  25714. #ifdef HAVE_ECC
  25715. #ifndef NO_RSA
  25716. FreeKey(ssl, ssl->hsAltType, (void**)&ssl->hsAltKey);
  25717. #endif /* !NO_RSA */
  25718. if (ssl->buffers.altKeyType == ecc_dsa_sa_algo ||
  25719. ssl->buffers.altKeyType == 0
  25720. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  25721. || ssl->buffers.altKeyType == sm2_sa_algo
  25722. #endif
  25723. ) {
  25724. ssl->hsAltType = DYNAMIC_TYPE_ECC;
  25725. ret = AllocKey(ssl, ssl->hsAltType, &ssl->hsAltKey);
  25726. if (ret != 0) {
  25727. goto exit_dapk;
  25728. }
  25729. #ifndef NO_RSA
  25730. WOLFSSL_MSG("Trying ECC private key, RSA didn't work");
  25731. #else
  25732. WOLFSSL_MSG("Trying ECC private key");
  25733. #endif
  25734. /* Set start of data to beginning of buffer. */
  25735. idx = 0;
  25736. /* Decode the key assuming it is an ECC private key. */
  25737. ret = wc_EccPrivateKeyDecode(ssl->buffers.altKey->buffer, &idx,
  25738. (ecc_key*)ssl->hsAltKey,
  25739. ssl->buffers.altKey->length);
  25740. #ifdef WOLF_PRIVATE_KEY_ID
  25741. /* if using external key then allow using a public key */
  25742. if (ret != 0 && (ssl->devId != INVALID_DEVID
  25743. #ifdef HAVE_PK_CALLBACKS
  25744. || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
  25745. #endif
  25746. )) {
  25747. WOLFSSL_MSG("Trying ECC public key with crypto callbacks");
  25748. idx = 0;
  25749. ret = wc_EccPublicKeyDecode(ssl->buffers.altKey->buffer, &idx,
  25750. (ecc_key*)ssl->hsAltKey,
  25751. ssl->buffers.altKey->length);
  25752. }
  25753. #endif
  25754. if (ret == 0) {
  25755. WOLFSSL_MSG("Using ECC private key");
  25756. /* Check it meets the minimum ECC key size requirements. */
  25757. keySz = wc_ecc_size((ecc_key*)ssl->hsAltKey);
  25758. if (keySz < ssl->options.minEccKeySz) {
  25759. WOLFSSL_MSG("ECC key size too small");
  25760. ERROR_OUT(ECC_KEY_SIZE_E, exit_dapk);
  25761. }
  25762. /* Return the maximum signature length. */
  25763. *length = wc_ecc_sig_size((ecc_key*)ssl->hsAltKey);
  25764. goto exit_dapk;
  25765. }
  25766. }
  25767. #endif
  25768. #if defined(HAVE_FALCON)
  25769. #if !defined(NO_RSA) || defined(HAVE_ECC)
  25770. FreeKey(ssl, ssl->hsAltType, (void**)&ssl->hsAltKey);
  25771. #endif
  25772. if (ssl->buffers.altKeyType == falcon_level1_sa_algo ||
  25773. ssl->buffers.altKeyType == falcon_level5_sa_algo ||
  25774. ssl->buffers.altKeyType == 0) {
  25775. ssl->hsAltType = DYNAMIC_TYPE_FALCON;
  25776. ret = AllocKey(ssl, ssl->hsAltType, &ssl->hsAltKey);
  25777. if (ret != 0) {
  25778. goto exit_dapk;
  25779. }
  25780. if (ssl->buffers.altKeyType == falcon_level1_sa_algo) {
  25781. ret = wc_falcon_set_level((falcon_key*)ssl->hsAltKey, 1);
  25782. }
  25783. else if (ssl->buffers.altKeyType == falcon_level5_sa_algo) {
  25784. ret = wc_falcon_set_level((falcon_key*)ssl->hsAltKey, 5);
  25785. }
  25786. else {
  25787. /* What if ssl->buffers.keyType is 0? We might want to do something
  25788. * more graceful here. */
  25789. ret = ALGO_ID_E;
  25790. }
  25791. if (ret != 0) {
  25792. goto exit_dapk;
  25793. }
  25794. #if defined(HAVE_ECC)
  25795. WOLFSSL_MSG("Trying Falcon private key, ECC didn't work");
  25796. #elif !defined(NO_RSA)
  25797. WOLFSSL_MSG("Trying Falcon private key, RSA didn't work");
  25798. #else
  25799. WOLFSSL_MSG("Trying Falcon private key");
  25800. #endif
  25801. /* Set start of data to beginning of buffer. */
  25802. idx = 0;
  25803. /* Decode the key assuming it is a Falcon private key. */
  25804. ret = wc_falcon_import_private_only(ssl->buffers.altKey->buffer,
  25805. ssl->buffers.altKey->length,
  25806. (falcon_key*)ssl->hsAltKey);
  25807. if (ret == 0) {
  25808. WOLFSSL_MSG("Using Falcon private key");
  25809. /* Check it meets the minimum Falcon key size requirements. */
  25810. keySz = wc_falcon_size((falcon_key*)ssl->hsAltKey);
  25811. if (keySz < ssl->options.minFalconKeySz) {
  25812. WOLFSSL_MSG("Falcon key size too small");
  25813. ERROR_OUT(FALCON_KEY_SIZE_E, exit_dapk);
  25814. }
  25815. /* Return the maximum signature length. */
  25816. *length = wc_falcon_sig_size((falcon_key*)ssl->hsAltKey);
  25817. goto exit_dapk;
  25818. }
  25819. }
  25820. #endif /* HAVE_FALCON */
  25821. #if defined(HAVE_DILITHIUM)
  25822. #if !defined(NO_RSA) || defined(HAVE_ECC)
  25823. FreeKey(ssl, ssl->hsAltType, (void**)&ssl->hsAltKey);
  25824. #endif
  25825. if (ssl->buffers.altKeyType == dilithium_level2_sa_algo ||
  25826. ssl->buffers.altKeyType == dilithium_level3_sa_algo ||
  25827. ssl->buffers.altKeyType == dilithium_level5_sa_algo ||
  25828. ssl->buffers.altKeyType == 0) {
  25829. ssl->hsAltType = DYNAMIC_TYPE_DILITHIUM;
  25830. ret = AllocKey(ssl, ssl->hsAltType, &ssl->hsAltKey);
  25831. if (ret != 0) {
  25832. goto exit_dapk;
  25833. }
  25834. if (ssl->buffers.altKeyType == dilithium_level2_sa_algo) {
  25835. ret = wc_dilithium_set_level((dilithium_key*)ssl->hsAltKey, 2);
  25836. }
  25837. else if (ssl->buffers.altKeyType == dilithium_level3_sa_algo) {
  25838. ret = wc_dilithium_set_level((dilithium_key*)ssl->hsAltKey, 3);
  25839. }
  25840. else if (ssl->buffers.altKeyType == dilithium_level5_sa_algo) {
  25841. ret = wc_dilithium_set_level((dilithium_key*)ssl->hsAltKey, 5);
  25842. }
  25843. else {
  25844. /* What if ssl->buffers.keyType is 0? We might want to do something
  25845. * more graceful here. */
  25846. ret = ALGO_ID_E;
  25847. }
  25848. if (ret != 0) {
  25849. goto exit_dapk;
  25850. }
  25851. #if defined(HAVE_FALCON)
  25852. WOLFSSL_MSG("Trying Dilithium private key, Falcon didn't work");
  25853. #elif defined(HAVE_ECC)
  25854. WOLFSSL_MSG("Trying Dilithium private key, ECC didn't work");
  25855. #elif !defined(NO_RSA)
  25856. WOLFSSL_MSG("Trying Dilithium private key, RSA didn't work");
  25857. #else
  25858. WOLFSSL_MSG("Trying Dilithium private key");
  25859. #endif
  25860. /* Set start of data to beginning of buffer. */
  25861. idx = 0;
  25862. /* Decode the key assuming it is a Dilithium private key. */
  25863. ret = wc_Dilithium_PrivateKeyDecode(ssl->buffers.altKey->buffer,
  25864. &idx,
  25865. (dilithium_key*)ssl->hsAltKey,
  25866. ssl->buffers.altKey->length);
  25867. if (ret == 0) {
  25868. WOLFSSL_MSG("Using Dilithium private key");
  25869. /* Check it meets the minimum Dilithium key size requirements. */
  25870. keySz = wc_dilithium_size((dilithium_key*)ssl->hsAltKey);
  25871. if (keySz < ssl->options.minDilithiumKeySz) {
  25872. WOLFSSL_MSG("Dilithium key size too small");
  25873. ERROR_OUT(DILITHIUM_KEY_SIZE_E, exit_dapk);
  25874. }
  25875. /* Return the maximum signature length. */
  25876. *length = wc_dilithium_sig_size((dilithium_key*)ssl->hsAltKey);
  25877. goto exit_dapk;
  25878. }
  25879. }
  25880. #endif /* HAVE_DILITHIUM */
  25881. (void)idx;
  25882. (void)keySz;
  25883. (void)length;
  25884. exit_dapk:
  25885. #ifdef WOLFSSL_BLIND_PRIVATE_KEY
  25886. if (ret == 0) {
  25887. ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey,
  25888. &ssl->buffers.altKeyMask);
  25889. }
  25890. else {
  25891. wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask);
  25892. }
  25893. #endif
  25894. if (ret != 0) {
  25895. WOLFSSL_ERROR_VERBOSE(ret);
  25896. }
  25897. return ret;
  25898. }
  25899. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  25900. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  25901. #if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_NO_TLS12)
  25902. /* returns 1 if able to do TLS 1.3 otherwise 0 */
  25903. int TLSv1_3_Capable(WOLFSSL* ssl)
  25904. {
  25905. #ifndef WOLFSSL_TLS13
  25906. return 0;
  25907. #else
  25908. int ret = 0;
  25909. if (IsAtLeastTLSv1_3(ssl->ctx->method->version)) {
  25910. ret = 1;
  25911. }
  25912. if ((wolfSSL_get_options(ssl) & WOLFSSL_OP_NO_TLSv1_3)) {
  25913. /* option set at run time to disable TLS 1.3 */
  25914. ret = 0;
  25915. }
  25916. return ret;
  25917. #endif
  25918. }
  25919. #endif /* WOLFSSL_TLS13 */
  25920. #ifndef WOLFSSL_NO_TLS12
  25921. #if (!defined(NO_WOLFSSL_CLIENT) && (!defined(NO_DH) || defined(HAVE_ECC) || \
  25922. defined(HAVE_CURVE25519) || defined(HAVE_CURVE448))) || \
  25923. (!defined(NO_WOLFSSL_SERVER) && (defined(HAVE_ECC) || \
  25924. ((defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)) && \
  25925. (defined(HAVE_ED25519) || defined(HAVE_ED448) || !defined(NO_RSA)))) || \
  25926. (!defined(NO_DH) && (!defined(NO_RSA) || defined(HAVE_ANON))))
  25927. /* Returns whether the signature algorithm requires caching of messages.
  25928. *
  25929. * @param [in] sigAlgo Signature algorithm.
  25930. * @return 1 when caching required.
  25931. * @return 0 when caching not required.
  25932. */
  25933. static int SigAlgoCachesMsgs(int sigAlgo)
  25934. {
  25935. int ret;
  25936. (void)sigAlgo;
  25937. #ifdef HAVE_ED25519
  25938. if (sigAlgo == ed25519_sa_algo) {
  25939. ret = 1;
  25940. }
  25941. else
  25942. #endif
  25943. #ifdef HAVE_ED448
  25944. if (sigAlgo == ed448_sa_algo) {
  25945. ret = 1;
  25946. }
  25947. else
  25948. #endif
  25949. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  25950. if (sigAlgo == sm2_sa_algo) {
  25951. ret = 1;
  25952. }
  25953. else
  25954. #endif
  25955. {
  25956. ret = 0;
  25957. }
  25958. return ret;
  25959. }
  25960. static int HashSkeData(WOLFSSL* ssl, enum wc_HashType hashType,
  25961. const byte* data, word32 sz, byte sigAlgo)
  25962. {
  25963. int ret = 0;
  25964. int digest_sz = wc_HashGetDigestSize(hashType);
  25965. if (digest_sz <= 0) {
  25966. ret = BUFFER_ERROR;
  25967. }
  25968. if (ret == 0) {
  25969. word32 new_size = SEED_LEN;
  25970. /* buffer for signature */
  25971. if (! WC_SAFE_SUM_WORD32(new_size, sz, new_size))
  25972. ret = MEMORY_E;
  25973. else {
  25974. ssl->buffers.sig.buffer = (byte*)XMALLOC(new_size, ssl->heap,
  25975. DYNAMIC_TYPE_SIGNATURE);
  25976. if (ssl->buffers.sig.buffer == NULL) {
  25977. ret = MEMORY_E;
  25978. }
  25979. }
  25980. }
  25981. if (ret == 0) {
  25982. ssl->buffers.sig.length = SEED_LEN + sz;
  25983. /* build message to hash */
  25984. XMEMCPY(ssl->buffers.sig.buffer, ssl->arrays->clientRandom, RAN_LEN);
  25985. XMEMCPY(&ssl->buffers.sig.buffer[RAN_LEN], ssl->arrays->serverRandom,
  25986. RAN_LEN);
  25987. /* message */
  25988. XMEMCPY(&ssl->buffers.sig.buffer[RAN_LEN * 2], data, sz);
  25989. }
  25990. if (ret == 0 && !SigAlgoCachesMsgs(sigAlgo)) {
  25991. ssl->buffers.digest.length = (unsigned int)digest_sz;
  25992. /* buffer for hash */
  25993. if (!ssl->buffers.digest.buffer) {
  25994. if (!ssl->options.dontFreeDigest) {
  25995. XFREE(ssl->buffers.digest.buffer, ssl->heap,
  25996. DYNAMIC_TYPE_DIGEST);
  25997. }
  25998. }
  25999. ssl->options.dontFreeDigest = 0;
  26000. ssl->buffers.digest.buffer = (byte*)XMALLOC(ssl->buffers.digest.length,
  26001. ssl->heap, DYNAMIC_TYPE_DIGEST);
  26002. if (ssl->buffers.digest.buffer == NULL) {
  26003. ret = MEMORY_E;
  26004. }
  26005. }
  26006. if (ret == 0 && !SigAlgoCachesMsgs(sigAlgo)) {
  26007. /* Perform hash. Only wc_Hash supports MD5_SHA1. */
  26008. ret = wc_Hash(hashType, ssl->buffers.sig.buffer,
  26009. ssl->buffers.sig.length,
  26010. ssl->buffers.digest.buffer,
  26011. ssl->buffers.digest.length);
  26012. #ifdef HAVE_PK_CALLBACKS
  26013. if (ssl->ctx->ProcessServerSigKexCb == NULL)
  26014. #endif
  26015. {
  26016. /* No further processing will be done. It can be freed. */
  26017. XFREE(ssl->buffers.sig.buffer, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  26018. ssl->buffers.sig.buffer = NULL;
  26019. }
  26020. }
  26021. return ret;
  26022. }
  26023. #endif
  26024. #endif /* !WOLFSSL_NO_TLS12 */
  26025. /* client only parts */
  26026. #ifndef NO_WOLFSSL_CLIENT
  26027. int HaveUniqueSessionObj(WOLFSSL* ssl)
  26028. {
  26029. if (ssl->session->ref.count > 1) {
  26030. WOLFSSL_SESSION* newSession = wolfSSL_SESSION_dup(ssl->session);
  26031. if (newSession == NULL) {
  26032. WOLFSSL_MSG("Session duplicate failed");
  26033. return 0;
  26034. }
  26035. wolfSSL_FreeSession(ssl->ctx, ssl->session);
  26036. ssl->session = newSession;
  26037. }
  26038. return 1;
  26039. }
  26040. #ifndef WOLFSSL_NO_TLS12
  26041. /* handle generation of client_hello (1) */
  26042. int SendClientHello(WOLFSSL* ssl)
  26043. {
  26044. byte *output;
  26045. word32 length, idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  26046. int sendSz;
  26047. int idSz;
  26048. int ret;
  26049. word32 extSz = 0;
  26050. const Suites* suites;
  26051. if (ssl == NULL) {
  26052. return BAD_FUNC_ARG;
  26053. }
  26054. #ifdef WOLFSSL_TLS13
  26055. if (IsAtLeastTLSv1_3(ssl->version))
  26056. return SendTls13ClientHello(ssl);
  26057. #endif
  26058. #ifdef HAVE_SECURE_RENEGOTIATION
  26059. /* We don't want to resume in SCR */
  26060. if (IsSCR(ssl))
  26061. ssl->options.resuming = 0;
  26062. #endif
  26063. idSz = ssl->options.resuming ? ssl->session->sessionIDSz : 0;
  26064. WOLFSSL_START(WC_FUNC_CLIENT_HELLO_SEND);
  26065. WOLFSSL_ENTER("SendClientHello");
  26066. suites = WOLFSSL_SUITES(ssl);
  26067. if (suites == NULL) {
  26068. WOLFSSL_MSG("Bad suites pointer in SendClientHello");
  26069. return SUITES_ERROR;
  26070. }
  26071. #ifdef HAVE_SESSION_TICKET
  26072. if (ssl->options.resuming && ssl->session->ticketLen > 0) {
  26073. SessionTicket* ticket;
  26074. ticket = TLSX_SessionTicket_Create(0, ssl->session->ticket,
  26075. ssl->session->ticketLen, ssl->heap);
  26076. if (ticket == NULL) return MEMORY_E;
  26077. ret = TLSX_UseSessionTicket(&ssl->extensions, ticket, ssl->heap);
  26078. if (ret != WOLFSSL_SUCCESS) {
  26079. TLSX_SessionTicket_Free(ticket, ssl->heap);
  26080. return ret;
  26081. }
  26082. idSz = 0;
  26083. }
  26084. #endif
  26085. length = VERSION_SZ + RAN_LEN
  26086. + (word32)idSz + ENUM_LEN
  26087. + SUITE_LEN
  26088. + COMP_LEN + ENUM_LEN;
  26089. #ifndef NO_FORCE_SCR_SAME_SUITE
  26090. if (IsSCR(ssl))
  26091. length += SUITE_LEN;
  26092. else
  26093. #endif
  26094. length += suites->suiteSz;
  26095. #ifdef HAVE_TLS_EXTENSIONS
  26096. /* auto populate extensions supported unless user defined */
  26097. if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
  26098. return ret;
  26099. extSz = 0;
  26100. ret = TLSX_GetRequestSize(ssl, client_hello, &extSz);
  26101. if (ret != 0)
  26102. return ret;
  26103. length += extSz;
  26104. #else
  26105. if (IsAtLeastTLSv1_2(ssl) && suites->hashSigAlgoSz)
  26106. extSz += HELLO_EXT_SZ + HELLO_EXT_SIGALGO_SZ
  26107. + suites->hashSigAlgoSz;
  26108. #ifdef HAVE_EXTENDED_MASTER
  26109. if (ssl->options.haveEMS)
  26110. extSz += HELLO_EXT_SZ;
  26111. #endif
  26112. if (extSz != 0)
  26113. length += extSz + HELLO_EXT_SZ_SZ;
  26114. #endif
  26115. sendSz = (int)length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  26116. if (ssl->arrays == NULL) {
  26117. return BAD_FUNC_ARG;
  26118. }
  26119. #ifdef WOLFSSL_DTLS
  26120. if (ssl->options.dtls) {
  26121. length += ENUM_LEN; /* cookie */
  26122. if (ssl->arrays->cookieSz != 0) length += ssl->arrays->cookieSz;
  26123. sendSz = (int)length + DTLS_HANDSHAKE_HEADER_SZ + DTLS_RECORD_HEADER_SZ;
  26124. idx += DTLS_HANDSHAKE_EXTRA + DTLS_RECORD_EXTRA;
  26125. }
  26126. #endif
  26127. if (IsEncryptionOn(ssl, 1))
  26128. sendSz += MAX_MSG_EXTRA;
  26129. /* Set this in case CheckAvailableSize returns a WANT_WRITE so that state
  26130. * is not advanced yet */
  26131. ssl->options.buildingMsg = 1;
  26132. /* check for available size */
  26133. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  26134. return ret;
  26135. /* get output buffer */
  26136. output = GetOutputBuffer(ssl);
  26137. AddHeaders(output, length, client_hello, ssl);
  26138. /* client hello, first version */
  26139. output[idx++] = ssl->version.major;
  26140. output[idx++] = ssl->version.minor;
  26141. ssl->chVersion = ssl->version; /* store in case changed */
  26142. /* then random */
  26143. if (ssl->options.connectState == CONNECT_BEGIN) {
  26144. ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN);
  26145. if (ret != 0)
  26146. return ret;
  26147. /* store random */
  26148. XMEMCPY(ssl->arrays->clientRandom, output + idx, RAN_LEN);
  26149. } else {
  26150. #ifdef WOLFSSL_DTLS
  26151. /* send same random on hello again */
  26152. XMEMCPY(output + idx, ssl->arrays->clientRandom, RAN_LEN);
  26153. #endif
  26154. }
  26155. idx += RAN_LEN;
  26156. /* then session id */
  26157. output[idx++] = (byte)idSz;
  26158. if (idSz) {
  26159. XMEMCPY(output + idx, ssl->session->sessionID,
  26160. ssl->session->sessionIDSz);
  26161. idx += ssl->session->sessionIDSz;
  26162. }
  26163. /* then DTLS cookie */
  26164. #ifdef WOLFSSL_DTLS
  26165. if (ssl->options.dtls) {
  26166. byte cookieSz = ssl->arrays->cookieSz;
  26167. output[idx++] = cookieSz;
  26168. if (cookieSz) {
  26169. XMEMCPY(&output[idx], ssl->arrays->cookie, cookieSz);
  26170. idx += cookieSz;
  26171. }
  26172. }
  26173. #endif
  26174. #ifndef NO_FORCE_SCR_SAME_SUITE
  26175. if (IsSCR(ssl)) {
  26176. c16toa(SUITE_LEN, output + idx);
  26177. idx += OPAQUE16_LEN;
  26178. output[idx++] = ssl->options.cipherSuite0;
  26179. output[idx++] = ssl->options.cipherSuite;
  26180. }
  26181. else
  26182. #endif
  26183. {
  26184. /* then cipher suites */
  26185. c16toa(suites->suiteSz, output + idx);
  26186. idx += OPAQUE16_LEN;
  26187. XMEMCPY(output + idx, &suites->suites, suites->suiteSz);
  26188. idx += suites->suiteSz;
  26189. }
  26190. /* last, compression */
  26191. output[idx++] = COMP_LEN;
  26192. if (ssl->options.usingCompression)
  26193. output[idx++] = ZLIB_COMPRESSION;
  26194. else
  26195. output[idx++] = NO_COMPRESSION;
  26196. #ifdef HAVE_TLS_EXTENSIONS
  26197. extSz = 0;
  26198. ret = TLSX_WriteRequest(ssl, output + idx, client_hello, &extSz);
  26199. if (ret != 0)
  26200. return ret;
  26201. idx += extSz;
  26202. (void)idx; /* suppress analyzer warning, keep idx current */
  26203. #else
  26204. if (extSz != 0) {
  26205. c16toa(extSz, output + idx);
  26206. idx += HELLO_EXT_SZ_SZ;
  26207. if (IsAtLeastTLSv1_2(ssl)) {
  26208. if (suites->hashSigAlgoSz) {
  26209. word16 i;
  26210. /* extension type */
  26211. c16toa(HELLO_EXT_SIG_ALGO, output + idx);
  26212. idx += HELLO_EXT_TYPE_SZ;
  26213. /* extension data length */
  26214. c16toa(HELLO_EXT_SIGALGO_SZ + suites->hashSigAlgoSz,
  26215. output + idx);
  26216. idx += HELLO_EXT_SZ_SZ;
  26217. /* sig algos length */
  26218. c16toa(suites->hashSigAlgoSz, output + idx);
  26219. idx += HELLO_EXT_SIGALGO_SZ;
  26220. for (i=0; i < suites->hashSigAlgoSz; i++, idx++) {
  26221. output[idx] = suites->hashSigAlgo[i];
  26222. }
  26223. }
  26224. }
  26225. #ifdef HAVE_EXTENDED_MASTER
  26226. if (ssl->options.haveEMS) {
  26227. c16toa(HELLO_EXT_EXTMS, output + idx);
  26228. idx += HELLO_EXT_TYPE_SZ;
  26229. c16toa(0, output + idx);
  26230. idx += HELLO_EXT_SZ_SZ;
  26231. }
  26232. #endif
  26233. }
  26234. #endif
  26235. if (IsEncryptionOn(ssl, 1)) {
  26236. byte* input;
  26237. int inputSz = (int)idx; /* build msg adds rec hdr */
  26238. int recordHeaderSz = RECORD_HEADER_SZ;
  26239. if (ssl->options.dtls)
  26240. recordHeaderSz += DTLS_RECORD_EXTRA;
  26241. inputSz -= recordHeaderSz;
  26242. input = (byte*)XMALLOC((size_t)inputSz, ssl->heap,
  26243. DYNAMIC_TYPE_IN_BUFFER);
  26244. if (input == NULL)
  26245. return MEMORY_E;
  26246. XMEMCPY(input, output + recordHeaderSz, inputSz);
  26247. #ifdef WOLFSSL_DTLS
  26248. if (IsDtlsNotSctpMode(ssl) &&
  26249. (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz,
  26250. client_hello)) != 0) {
  26251. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  26252. return ret;
  26253. }
  26254. #endif
  26255. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  26256. handshake, 1, 0, 0, CUR_ORDER);
  26257. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  26258. if (sendSz < 0)
  26259. return sendSz;
  26260. } else {
  26261. #ifdef WOLFSSL_DTLS
  26262. if (IsDtlsNotSctpMode(ssl)) {
  26263. if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, client_hello)) != 0)
  26264. return ret;
  26265. }
  26266. if (ssl->options.dtls)
  26267. DtlsSEQIncrement(ssl, CUR_ORDER);
  26268. #endif
  26269. ret = HashOutput(ssl, output, sendSz, 0);
  26270. if (ret != 0)
  26271. return ret;
  26272. }
  26273. ssl->options.clientState = CLIENT_HELLO_COMPLETE;
  26274. #ifdef OPENSSL_EXTRA
  26275. ssl->cbmode = SSL_CB_MODE_WRITE;
  26276. if (ssl->CBIS != NULL)
  26277. ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, WOLFSSL_SUCCESS);
  26278. #endif
  26279. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  26280. if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
  26281. if (ssl->toInfoOn) {
  26282. ret = AddPacketInfo(ssl, "ClientHello", handshake, output, sendSz,
  26283. WRITE_PROTO, 0, ssl->heap);
  26284. if (ret != 0)
  26285. return ret;
  26286. }
  26287. #endif
  26288. ssl->options.buildingMsg = 0;
  26289. ssl->buffers.outputBuffer.length += (word32)sendSz;
  26290. ret = SendBuffered(ssl);
  26291. WOLFSSL_LEAVE("SendClientHello", ret);
  26292. WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
  26293. return ret;
  26294. }
  26295. /* handle processing of DTLS hello_verify_request (3) */
  26296. int DoHelloVerifyRequest(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  26297. word32 size)
  26298. {
  26299. ProtocolVersion pv;
  26300. byte cookieSz;
  26301. word32 begin = *inOutIdx;
  26302. #ifdef WOLFSSL_CALLBACKS
  26303. if (ssl->hsInfoOn) AddPacketName(ssl, "HelloVerifyRequest");
  26304. if (ssl->toInfoOn) AddLateName("HelloVerifyRequest", &ssl->timeoutInfo);
  26305. #endif
  26306. #ifdef WOLFSSL_DTLS
  26307. if (ssl->options.dtls) {
  26308. DtlsMsgPoolReset(ssl);
  26309. #ifdef WOLFSSL_DTLS_CID
  26310. if (ssl->options.useDtlsCID)
  26311. DtlsCIDOnExtensionsParsed(ssl);
  26312. #endif /* WOLFSSL_DTLS_CID */
  26313. }
  26314. #endif
  26315. if (OPAQUE16_LEN + OPAQUE8_LEN > size)
  26316. return BUFFER_ERROR;
  26317. XMEMCPY(&pv, input + *inOutIdx, OPAQUE16_LEN);
  26318. *inOutIdx += OPAQUE16_LEN;
  26319. if (pv.major != DTLS_MAJOR ||
  26320. (pv.minor != DTLS_MINOR && pv.minor != DTLSv1_2_MINOR))
  26321. return VERSION_ERROR;
  26322. cookieSz = input[(*inOutIdx)++];
  26323. if (cookieSz) {
  26324. if ((*inOutIdx - begin) + cookieSz > size)
  26325. return BUFFER_ERROR;
  26326. #ifdef WOLFSSL_DTLS
  26327. if (cookieSz <= MAX_COOKIE_LEN) {
  26328. XMEMCPY(ssl->arrays->cookie, input + *inOutIdx, cookieSz);
  26329. ssl->arrays->cookieSz = cookieSz;
  26330. }
  26331. #endif
  26332. *inOutIdx += cookieSz;
  26333. }
  26334. #if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_TLS13)
  26335. if (IsAtLeastTLSv1_3(ssl->version) && ssl->options.dtls) {
  26336. /* we sent a TLSv1.3 ClientHello but received a
  26337. * HELLO_VERIFY_REQUEST. We only check if DTLSv1_3_MINOR is the
  26338. * min downgrade option as per the server_version field comments in
  26339. * https://www.rfc-editor.org/rfc/rfc6347#section-4.2.1 */
  26340. if (!ssl->options.downgrade ||
  26341. ssl->options.minDowngrade <= DTLSv1_3_MINOR)
  26342. return VERSION_ERROR;
  26343. /* Cannot be DTLS1.3 as HELLO_VERIFY_REQUEST */
  26344. ssl->options.tls1_3 = 0;
  26345. }
  26346. #endif /* defined(WOLFSSL_DTLS13) && defined(WOLFSSL_TLS13) */
  26347. ssl->options.serverState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
  26348. return 0;
  26349. }
  26350. static WC_INLINE int DSH_CheckSessionId(WOLFSSL* ssl)
  26351. {
  26352. int ret = 0;
  26353. #ifdef HAVE_SECRET_CALLBACK
  26354. /* If a session secret callback exists, we are using that
  26355. * key instead of the saved session key. Requires a ticket. */
  26356. ret = ret || (ssl->sessionSecretCb != NULL
  26357. #ifdef HAVE_SESSION_TICKET
  26358. && ssl->session->ticketLen > 0
  26359. #endif
  26360. );
  26361. #endif
  26362. #ifdef HAVE_SESSION_TICKET
  26363. /* server may send blank ticket which may not be expected to indicate
  26364. * existing one ok but will also be sending a new one */
  26365. ret = ret || (ssl->session->ticketLen > 0);
  26366. #endif
  26367. ret = ret ||
  26368. (ssl->options.haveSessionId && XMEMCMP(ssl->arrays->sessionID,
  26369. ssl->session->sessionID, ID_LEN) == 0);
  26370. return ret;
  26371. }
  26372. /* Check the version in the received message is valid and set protocol
  26373. * version to use.
  26374. *
  26375. * ssl The SSL/TLS object.
  26376. * pv The protocol version from the packet.
  26377. * returns 0 on success, otherwise failure.
  26378. */
  26379. int CheckVersion(WOLFSSL *ssl, ProtocolVersion pv)
  26380. {
  26381. byte lowerVersion, higherVersion;
  26382. #ifdef WOLFSSL_TLS13_DRAFT
  26383. if (pv.major == TLS_DRAFT_MAJOR) {
  26384. pv.major = SSLv3_MAJOR;
  26385. pv.minor = TLSv1_3_MINOR;
  26386. }
  26387. #endif
  26388. #ifdef OPENSSL_EXTRA
  26389. if (ssl->CBIS != NULL) {
  26390. ssl->CBIS(ssl, SSL_CB_HANDSHAKE_START, WOLFSSL_SUCCESS);
  26391. }
  26392. #endif
  26393. if (ssl->options.dtls) {
  26394. if (pv.major != DTLS_MAJOR || pv.minor == DTLS_BOGUS_MINOR) {
  26395. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  26396. return VERSION_ERROR;
  26397. }
  26398. lowerVersion = pv.minor > ssl->version.minor;
  26399. higherVersion = pv.minor < ssl->version.minor;
  26400. }
  26401. else {
  26402. if (pv.major != SSLv3_MAJOR) {
  26403. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  26404. return VERSION_ERROR;
  26405. }
  26406. lowerVersion = pv.minor < ssl->version.minor;
  26407. higherVersion = pv.minor > ssl->version.minor;
  26408. }
  26409. if (higherVersion) {
  26410. WOLFSSL_MSG("Server using higher version, fatal error");
  26411. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  26412. return VERSION_ERROR;
  26413. }
  26414. if (lowerVersion) {
  26415. WOLFSSL_MSG("server using lower version");
  26416. /* Check for downgrade attack. */
  26417. if (!ssl->options.downgrade) {
  26418. WOLFSSL_MSG("\tno downgrade allowed, fatal error");
  26419. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  26420. return VERSION_ERROR;
  26421. }
  26422. if ((!ssl->options.dtls && pv.minor < ssl->options.minDowngrade) ||
  26423. (ssl->options.dtls && pv.minor > ssl->options.minDowngrade)) {
  26424. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  26425. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  26426. return VERSION_ERROR;
  26427. }
  26428. #ifdef HAVE_SECURE_RENEGOTIATION
  26429. if (ssl->secure_renegotiation &&
  26430. ssl->secure_renegotiation->enabled &&
  26431. ssl->options.handShakeDone) {
  26432. WOLFSSL_MSG("Server changed version during scr");
  26433. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  26434. return VERSION_ERROR;
  26435. }
  26436. #endif
  26437. /* Checks made - OK to downgrade. */
  26438. ssl->version.minor = pv.minor;
  26439. switch(pv.minor) {
  26440. case SSLv3_MINOR:
  26441. /* turn off tls */
  26442. WOLFSSL_MSG("\tdowngrading to SSLv3");
  26443. ssl->options.tls = 0;
  26444. ssl->options.tls1_1 = 0;
  26445. break;
  26446. case TLSv1_MINOR:
  26447. /* turn off tls 1.1+ */
  26448. WOLFSSL_MSG("\tdowngrading to TLSv1");
  26449. ssl->options.tls1_1 = 0;
  26450. break;
  26451. case TLSv1_1_MINOR:
  26452. WOLFSSL_MSG("\tdowngrading to TLSv1.1");
  26453. break;
  26454. case DTLS_MINOR:
  26455. WOLFSSL_MSG("\tdowngrading to DTLSv1.1");
  26456. break;
  26457. case TLSv1_2_MINOR:
  26458. WOLFSSL_MSG("\tdowngrading to TLSv1.2");
  26459. break;
  26460. case DTLSv1_2_MINOR:
  26461. WOLFSSL_MSG("\tdowngrading to DTLSv1.2");
  26462. break;
  26463. default:
  26464. WOLFSSL_MSG("\tbad minor version");
  26465. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  26466. return VERSION_ERROR;
  26467. }
  26468. }
  26469. /* check if option is set to not allow the current version
  26470. * set from either wolfSSL_set_options or wolfSSL_CTX_set_options */
  26471. if (!ssl->options.dtls && ssl->options.downgrade &&
  26472. ssl->options.mask > 0) {
  26473. if (ssl->version.minor == TLSv1_2_MINOR &&
  26474. (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) ==
  26475. WOLFSSL_OP_NO_TLSv1_2) {
  26476. WOLFSSL_MSG("\tOption set to not allow TLSv1.2, Downgrading");
  26477. ssl->version.minor = TLSv1_1_MINOR;
  26478. }
  26479. if (ssl->version.minor == TLSv1_1_MINOR &&
  26480. (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) ==
  26481. WOLFSSL_OP_NO_TLSv1_1) {
  26482. WOLFSSL_MSG("\tOption set to not allow TLSv1.1, Downgrading");
  26483. ssl->options.tls1_1 = 0;
  26484. ssl->version.minor = TLSv1_MINOR;
  26485. }
  26486. if (ssl->version.minor == TLSv1_MINOR &&
  26487. (ssl->options.mask & WOLFSSL_OP_NO_TLSv1) ==
  26488. WOLFSSL_OP_NO_TLSv1) {
  26489. WOLFSSL_MSG("\tOption set to not allow TLSv1, Downgrading");
  26490. ssl->options.tls = 0;
  26491. ssl->options.tls1_1 = 0;
  26492. ssl->version.minor = SSLv3_MINOR;
  26493. }
  26494. if (ssl->version.minor == SSLv3_MINOR &&
  26495. (ssl->options.mask & WOLFSSL_OP_NO_SSLv3) ==
  26496. WOLFSSL_OP_NO_SSLv3) {
  26497. WOLFSSL_MSG("\tError, option set to not allow SSLv3");
  26498. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  26499. return VERSION_ERROR;
  26500. }
  26501. if (ssl->version.minor < ssl->options.minDowngrade) {
  26502. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  26503. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  26504. return VERSION_ERROR;
  26505. }
  26506. }
  26507. return 0;
  26508. }
  26509. /* handle processing of server_hello (2) */
  26510. int DoServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  26511. word32 helloSz)
  26512. {
  26513. byte cs0; /* cipher suite bytes 0, 1 */
  26514. byte cs1;
  26515. ProtocolVersion pv;
  26516. byte compression;
  26517. word32 i = *inOutIdx;
  26518. word32 begin = i;
  26519. int ret;
  26520. WOLFSSL_START(WC_FUNC_SERVER_HELLO_DO);
  26521. WOLFSSL_ENTER("DoServerHello");
  26522. #ifdef WOLFSSL_CALLBACKS
  26523. if (ssl->hsInfoOn) AddPacketName(ssl, "ServerHello");
  26524. if (ssl->toInfoOn) AddLateName("ServerHello", &ssl->timeoutInfo);
  26525. #endif
  26526. /* protocol version, random and session id length check */
  26527. if (OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz)
  26528. return BUFFER_ERROR;
  26529. /* protocol version */
  26530. XMEMCPY(&pv, input + i, OPAQUE16_LEN);
  26531. i += OPAQUE16_LEN;
  26532. ret = CheckVersion(ssl, pv);
  26533. if (ret != 0) {
  26534. SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
  26535. return ret;
  26536. }
  26537. #ifdef WOLFSSL_TLS13
  26538. if (IsAtLeastTLSv1_3(pv)) {
  26539. byte type = server_hello;
  26540. return DoTls13ServerHello(ssl, input, inOutIdx, helloSz, &type);
  26541. }
  26542. #endif
  26543. /* random */
  26544. XMEMCPY(ssl->arrays->serverRandom, input + i, RAN_LEN);
  26545. i += RAN_LEN;
  26546. /* session id */
  26547. ssl->arrays->sessionIDSz = input[i++];
  26548. if (ssl->arrays->sessionIDSz > ID_LEN) {
  26549. WOLFSSL_MSG("Invalid session ID size");
  26550. ssl->arrays->sessionIDSz = 0;
  26551. return BUFFER_ERROR;
  26552. }
  26553. else if (ssl->arrays->sessionIDSz) {
  26554. if ((i - begin) + ssl->arrays->sessionIDSz > helloSz)
  26555. return BUFFER_ERROR;
  26556. XMEMCPY(ssl->arrays->sessionID, input + i,
  26557. ssl->arrays->sessionIDSz);
  26558. i += ssl->arrays->sessionIDSz;
  26559. ssl->options.haveSessionId = 1;
  26560. }
  26561. /* suite and compression */
  26562. if ((i - begin) + OPAQUE16_LEN + OPAQUE8_LEN > helloSz)
  26563. return BUFFER_ERROR;
  26564. cs0 = input[i++];
  26565. cs1 = input[i++];
  26566. #ifndef WOLFSSL_NO_STRICT_CIPHER_SUITE
  26567. #if defined(HAVE_SECURE_RENEGOTIATION) && !defined(NO_FORCE_SCR_SAME_SUITE)
  26568. if (IsSCR(ssl)) {
  26569. if (ssl->options.cipherSuite0 != cs0 ||
  26570. ssl->options.cipherSuite != cs1) {
  26571. WOLFSSL_MSG("Server changed cipher suite during scr");
  26572. WOLFSSL_ERROR_VERBOSE(MATCH_SUITE_ERROR);
  26573. return MATCH_SUITE_ERROR;
  26574. }
  26575. }
  26576. else
  26577. #endif
  26578. {
  26579. word32 idx, found = 0;
  26580. const Suites* suites = WOLFSSL_SUITES(ssl);
  26581. /* confirm server_hello cipher suite is one sent in client_hello */
  26582. for (idx = 0; idx < suites->suiteSz; idx += 2) {
  26583. if (suites->suites[idx] == cs0 &&
  26584. suites->suites[idx+1] == cs1) {
  26585. found = 1;
  26586. break;
  26587. }
  26588. }
  26589. if (!found) {
  26590. WOLFSSL_MSG("ServerHello did not use cipher suite from ClientHello");
  26591. WOLFSSL_ERROR_VERBOSE(MATCH_SUITE_ERROR);
  26592. return MATCH_SUITE_ERROR;
  26593. }
  26594. }
  26595. #endif /* !WOLFSSL_NO_STRICT_CIPHER_SUITE */
  26596. ssl->options.cipherSuite0 = cs0;
  26597. ssl->options.cipherSuite = cs1;
  26598. #ifdef WOLFSSL_DEBUG_TLS
  26599. WOLFSSL_MSG("Chosen cipher suite:");
  26600. WOLFSSL_MSG(GetCipherNameInternal(ssl->options.cipherSuite0,
  26601. ssl->options.cipherSuite));
  26602. #endif
  26603. compression = input[i++];
  26604. if (compression != NO_COMPRESSION && !ssl->options.usingCompression) {
  26605. WOLFSSL_MSG("Server forcing compression w/o support");
  26606. WOLFSSL_ERROR_VERBOSE(COMPRESSION_ERROR);
  26607. return COMPRESSION_ERROR;
  26608. }
  26609. if (compression != ZLIB_COMPRESSION && ssl->options.usingCompression) {
  26610. WOLFSSL_MSG("Server refused compression, turning off");
  26611. ssl->options.usingCompression = 0; /* turn off if server refused */
  26612. }
  26613. *inOutIdx = i;
  26614. #ifdef HAVE_TLS_EXTENSIONS
  26615. if ( (i - begin) < helloSz) {
  26616. if (TLSX_SupportExtensions(ssl)) {
  26617. word16 totalExtSz;
  26618. if ((i - begin) + OPAQUE16_LEN > helloSz)
  26619. return BUFFER_ERROR;
  26620. ato16(&input[i], &totalExtSz);
  26621. i += OPAQUE16_LEN;
  26622. if ((i - begin) + totalExtSz > helloSz)
  26623. return BUFFER_ERROR;
  26624. if ((ret = TLSX_Parse(ssl, (byte *) input + i, totalExtSz,
  26625. server_hello, NULL)))
  26626. return ret;
  26627. i += totalExtSz;
  26628. *inOutIdx = i;
  26629. }
  26630. else
  26631. *inOutIdx = begin + helloSz; /* skip extensions */
  26632. }
  26633. else
  26634. ssl->options.haveEMS = 0; /* If no extensions, no EMS */
  26635. #else
  26636. {
  26637. byte pendingEMS = 0;
  26638. if ( (i - begin) < helloSz) {
  26639. int allowExt = 0;
  26640. if (ssl->version.major == SSLv3_MAJOR &&
  26641. ssl->version.minor >= TLSv1_MINOR) {
  26642. allowExt = 1;
  26643. }
  26644. #ifdef WOLFSSL_DTLS
  26645. if (ssl->version.major == DTLS_MAJOR)
  26646. allowExt = 1;
  26647. #endif
  26648. if (allowExt) {
  26649. word16 totalExtSz;
  26650. if ((i - begin) + OPAQUE16_LEN > helloSz)
  26651. return BUFFER_ERROR;
  26652. ato16(&input[i], &totalExtSz);
  26653. i += OPAQUE16_LEN;
  26654. if ((i - begin) + totalExtSz > helloSz)
  26655. return BUFFER_ERROR;
  26656. while (totalExtSz) {
  26657. word16 extId, extSz;
  26658. if (OPAQUE16_LEN + OPAQUE16_LEN > totalExtSz)
  26659. return BUFFER_ERROR;
  26660. ato16(&input[i], &extId);
  26661. i += OPAQUE16_LEN;
  26662. ato16(&input[i], &extSz);
  26663. i += OPAQUE16_LEN;
  26664. if (OPAQUE16_LEN + OPAQUE16_LEN + extSz > totalExtSz)
  26665. return BUFFER_ERROR;
  26666. if (extId == HELLO_EXT_EXTMS)
  26667. pendingEMS = 1;
  26668. else
  26669. i += extSz;
  26670. totalExtSz -= OPAQUE16_LEN + OPAQUE16_LEN + extSz;
  26671. }
  26672. *inOutIdx = i;
  26673. }
  26674. else
  26675. *inOutIdx = begin + helloSz; /* skip extensions */
  26676. }
  26677. if (!pendingEMS && ssl->options.haveEMS)
  26678. ssl->options.haveEMS = 0;
  26679. }
  26680. #endif
  26681. #if defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_HARDEN_TLS_NO_SCR_CHECK)
  26682. if (ssl->secure_renegotiation == NULL ||
  26683. !ssl->secure_renegotiation->enabled) {
  26684. /* If the server does not acknowledge the extension, the client
  26685. * MUST generate a fatal handshake_failure alert prior to
  26686. * terminating the connection.
  26687. * https://www.rfc-editor.org/rfc/rfc9325#name-renegotiation-in-tls-12 */
  26688. WOLFSSL_MSG("ServerHello did not contain SCR extension");
  26689. return SECURE_RENEGOTIATION_E;
  26690. }
  26691. #endif
  26692. ssl->options.serverState = SERVER_HELLO_COMPLETE;
  26693. if (IsEncryptionOn(ssl, 0)) {
  26694. *inOutIdx += ssl->keys.padSz;
  26695. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  26696. if (ssl->options.startedETMWrite &&
  26697. ssl->specs.cipher_type == block) {
  26698. *inOutIdx += MacSize(ssl);
  26699. }
  26700. #endif
  26701. }
  26702. #ifdef HAVE_SECRET_CALLBACK
  26703. if (ssl->sessionSecretCb != NULL
  26704. #ifdef HAVE_SESSION_TICKET
  26705. && ssl->session->ticketLen > 0
  26706. #endif
  26707. ) {
  26708. int secretSz = SECRET_LEN;
  26709. ret = ssl->sessionSecretCb(ssl, ssl->session->masterSecret,
  26710. &secretSz, ssl->sessionSecretCtx);
  26711. if (ret != 0 || secretSz != SECRET_LEN) {
  26712. WOLFSSL_ERROR_VERBOSE(SESSION_SECRET_CB_E);
  26713. return SESSION_SECRET_CB_E;
  26714. }
  26715. }
  26716. #endif /* HAVE_SECRET_CALLBACK */
  26717. ret = CompleteServerHello(ssl);
  26718. WOLFSSL_LEAVE("DoServerHello", ret);
  26719. WOLFSSL_END(WC_FUNC_SERVER_HELLO_DO);
  26720. return ret;
  26721. }
  26722. int CompleteServerHello(WOLFSSL* ssl)
  26723. {
  26724. int ret;
  26725. if (!ssl->options.resuming) {
  26726. byte* down = ssl->arrays->serverRandom + RAN_LEN -
  26727. TLS13_DOWNGRADE_SZ - 1;
  26728. byte vers = ssl->arrays->serverRandom[RAN_LEN - 1];
  26729. #ifdef WOLFSSL_TLS13
  26730. if (TLSv1_3_Capable(ssl)) {
  26731. /* TLS v1.3 capable client not allowed to downgrade when
  26732. * connecting to TLS v1.3 capable server unless cipher suite
  26733. * demands it.
  26734. */
  26735. if (XMEMCMP(down, tls13Downgrade, TLS13_DOWNGRADE_SZ) == 0 &&
  26736. (vers == 0 || vers == 1)) {
  26737. SendAlert(ssl, alert_fatal, illegal_parameter);
  26738. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  26739. return VERSION_ERROR;
  26740. }
  26741. }
  26742. else
  26743. #endif
  26744. if (ssl->ctx->method->version.major == SSLv3_MAJOR &&
  26745. ssl->ctx->method->version.minor == TLSv1_2_MINOR &&
  26746. (wolfSSL_get_options(ssl) & WOLFSSL_OP_NO_TLSv1_2) == 0) {
  26747. /* TLS v1.2 capable client not allowed to downgrade when
  26748. * connecting to TLS v1.2 capable server.
  26749. */
  26750. if (XMEMCMP(down, tls13Downgrade, TLS13_DOWNGRADE_SZ) == 0 &&
  26751. vers == 0) {
  26752. SendAlert(ssl, alert_fatal, illegal_parameter);
  26753. WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
  26754. return VERSION_ERROR;
  26755. }
  26756. }
  26757. }
  26758. else {
  26759. if (DSH_CheckSessionId(ssl)) {
  26760. if (SetCipherSpecs(ssl) == 0) {
  26761. if (!HaveUniqueSessionObj(ssl)) {
  26762. WOLFSSL_MSG("Unable to have unique session object");
  26763. WOLFSSL_ERROR_VERBOSE(MEMORY_ERROR);
  26764. return MEMORY_ERROR;
  26765. }
  26766. XMEMCPY(ssl->arrays->masterSecret,
  26767. ssl->session->masterSecret, SECRET_LEN);
  26768. #ifdef NO_OLD_TLS
  26769. ret = DeriveTlsKeys(ssl);
  26770. #else
  26771. ret = -1; /* default value */
  26772. #ifndef NO_TLS
  26773. if (ssl->options.tls)
  26774. ret = DeriveTlsKeys(ssl);
  26775. #endif
  26776. if (!ssl->options.tls)
  26777. ret = DeriveKeys(ssl);
  26778. #endif /* NO_OLD_TLS */
  26779. /* SERVER: peer auth based on session secret. */
  26780. ssl->options.peerAuthGood = (ret == 0);
  26781. ssl->options.serverState = SERVER_HELLODONE_COMPLETE;
  26782. return ret;
  26783. }
  26784. else {
  26785. WOLFSSL_MSG("Unsupported cipher suite, DoServerHello");
  26786. WOLFSSL_ERROR_VERBOSE(UNSUPPORTED_SUITE);
  26787. return UNSUPPORTED_SUITE;
  26788. }
  26789. }
  26790. else {
  26791. WOLFSSL_MSG("Server denied resumption attempt");
  26792. ssl->options.resuming = 0; /* server denied resumption try */
  26793. }
  26794. }
  26795. return SetCipherSpecs(ssl);
  26796. }
  26797. #endif /* !WOLFSSL_NO_TLS12 */
  26798. /* Make sure client setup is valid for this suite, true on success */
  26799. int VerifyClientSuite(word16 havePSK, byte cipherSuite0, byte cipherSuite)
  26800. {
  26801. (void)havePSK;
  26802. WOLFSSL_ENTER("VerifyClientSuite");
  26803. if (CipherRequires(cipherSuite0, cipherSuite, REQUIRES_PSK)) {
  26804. WOLFSSL_MSG("Requires PSK");
  26805. #ifndef NO_PSK
  26806. if (havePSK == 0)
  26807. #endif
  26808. {
  26809. WOLFSSL_MSG("Don't have PSK");
  26810. return 0;
  26811. }
  26812. }
  26813. return 1; /* success */
  26814. }
  26815. #ifndef WOLFSSL_NO_TLS12
  26816. #ifndef NO_CERTS
  26817. /* handle processing of certificate_request (13) */
  26818. static int DoCertificateRequest(WOLFSSL* ssl, const byte* input, word32*
  26819. inOutIdx, word32 size)
  26820. {
  26821. word16 len;
  26822. word32 begin = *inOutIdx;
  26823. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \
  26824. defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)
  26825. int ret;
  26826. #endif
  26827. #ifdef OPENSSL_EXTRA
  26828. WOLFSSL_X509* x509 = NULL;
  26829. WOLFSSL_EVP_PKEY* pkey = NULL;
  26830. #endif
  26831. WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_DO);
  26832. WOLFSSL_ENTER("DoCertificateRequest");
  26833. #ifdef WOLFSSL_CALLBACKS
  26834. if (ssl->hsInfoOn)
  26835. AddPacketName(ssl, "CertificateRequest");
  26836. if (ssl->toInfoOn)
  26837. AddLateName("CertificateRequest", &ssl->timeoutInfo);
  26838. #endif
  26839. if (OPAQUE8_LEN > size)
  26840. return BUFFER_ERROR;
  26841. len = input[(*inOutIdx)++];
  26842. if ((*inOutIdx - begin) + len > size)
  26843. return BUFFER_ERROR;
  26844. /* types, read in here */
  26845. *inOutIdx += len;
  26846. /* signature and hash signature algorithm */
  26847. if (IsAtLeastTLSv1_2(ssl)) {
  26848. if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
  26849. return BUFFER_ERROR;
  26850. ato16(input + *inOutIdx, &len);
  26851. *inOutIdx += OPAQUE16_LEN;
  26852. if ((len > size) || ((*inOutIdx - begin) + len > size))
  26853. return BUFFER_ERROR;
  26854. if (PickHashSigAlgo(ssl, input + *inOutIdx, len, 0) != 0 &&
  26855. ssl->buffers.certificate &&
  26856. ssl->buffers.certificate->buffer) {
  26857. #ifdef HAVE_PK_CALLBACKS
  26858. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
  26859. WOLFSSL_MSG("Using PK for client private key");
  26860. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  26861. return INVALID_PARAMETER;
  26862. }
  26863. #endif
  26864. if (ssl->buffers.key && ssl->buffers.key->buffer) {
  26865. WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
  26866. return INVALID_PARAMETER;
  26867. }
  26868. }
  26869. *inOutIdx += len;
  26870. #ifdef WC_RSA_PSS
  26871. ssl->pssAlgo = 0;
  26872. if (ssl->options.sigAlgo == rsa_pss_sa_algo)
  26873. ssl->pssAlgo |= 1 << ssl->options.hashAlgo;
  26874. #endif
  26875. }
  26876. /* authorities */
  26877. if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
  26878. return BUFFER_ERROR;
  26879. /* DN seq length */
  26880. ato16(input + *inOutIdx, &len);
  26881. *inOutIdx += OPAQUE16_LEN;
  26882. if ((*inOutIdx - begin) + len > size)
  26883. return BUFFER_ERROR;
  26884. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)
  26885. if (ssl->client_ca_names != ssl->ctx->client_ca_names)
  26886. wolfSSL_sk_X509_NAME_pop_free(ssl->client_ca_names, NULL);
  26887. ssl->client_ca_names = wolfSSL_sk_X509_NAME_new(NULL);
  26888. if (ssl->client_ca_names == NULL) {
  26889. return MEMORY_ERROR;
  26890. }
  26891. #endif
  26892. while (len) {
  26893. word16 dnSz;
  26894. if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
  26895. return BUFFER_ERROR;
  26896. ato16(input + *inOutIdx, &dnSz);
  26897. *inOutIdx += OPAQUE16_LEN;
  26898. if ((*inOutIdx - begin) + dnSz > size)
  26899. return BUFFER_ERROR;
  26900. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)
  26901. {
  26902. WOLFSSL_X509_NAME* name = NULL;
  26903. /* Use a DecodedCert struct to get access to GetName to
  26904. * parse DN name */
  26905. #ifdef WOLFSSL_SMALL_STACK
  26906. DecodedCert *cert = (DecodedCert *)XMALLOC(
  26907. sizeof(*cert), ssl->heap, DYNAMIC_TYPE_DCERT);
  26908. if (cert == NULL)
  26909. return MEMORY_ERROR;
  26910. #else
  26911. DecodedCert cert[1];
  26912. #endif
  26913. InitDecodedCert(cert, input + *inOutIdx, dnSz, ssl->heap);
  26914. ret = GetName(cert, ASN_SUBJECT, dnSz);
  26915. if (ret == 0) {
  26916. if ((name = wolfSSL_X509_NAME_new_ex(cert->heap)) == NULL)
  26917. ret = MEMORY_ERROR;
  26918. }
  26919. if (ret == 0) {
  26920. CopyDecodedName(name, cert, ASN_SUBJECT);
  26921. }
  26922. if (ret == 0) {
  26923. if (wolfSSL_sk_X509_NAME_push(ssl->client_ca_names, name)
  26924. <= 0)
  26925. {
  26926. ret = MEMORY_ERROR;
  26927. }
  26928. }
  26929. FreeDecodedCert(cert);
  26930. #ifdef WOLFSSL_SMALL_STACK
  26931. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  26932. #endif
  26933. if (ret != 0) {
  26934. if (name != NULL)
  26935. wolfSSL_X509_NAME_free(name);
  26936. return ret;
  26937. }
  26938. }
  26939. #endif
  26940. *inOutIdx += dnSz;
  26941. len -= OPAQUE16_LEN + dnSz;
  26942. }
  26943. #ifdef OPENSSL_EXTRA
  26944. /* call client cert callback if no cert has been loaded */
  26945. if ((ssl->ctx->CBClientCert != NULL) &&
  26946. (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer)) {
  26947. ret = ssl->ctx->CBClientCert(ssl, &x509, &pkey);
  26948. if (ret == 1) {
  26949. if ((wolfSSL_use_certificate(ssl, x509) != WOLFSSL_SUCCESS) ||
  26950. (wolfSSL_use_PrivateKey(ssl, pkey) != WOLFSSL_SUCCESS)) {
  26951. WOLFSSL_ERROR_VERBOSE(CLIENT_CERT_CB_ERROR);
  26952. return CLIENT_CERT_CB_ERROR;
  26953. }
  26954. wolfSSL_X509_free(x509);
  26955. wolfSSL_EVP_PKEY_free(pkey);
  26956. }
  26957. else if (ret < 0) {
  26958. return WOLFSSL_ERROR_WANT_X509_LOOKUP;
  26959. }
  26960. }
  26961. if ((ret = CertSetupCbWrapper(ssl)) != 0)
  26962. return ret;
  26963. #endif
  26964. /* don't send client cert or cert verify if user hasn't provided
  26965. cert and private key */
  26966. if (ssl->buffers.certificate && ssl->buffers.certificate->buffer) {
  26967. #ifdef HAVE_PK_CALLBACKS
  26968. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
  26969. WOLFSSL_MSG("Using PK for client private key");
  26970. ssl->options.sendVerify = SEND_CERT;
  26971. }
  26972. #endif
  26973. if (ssl->buffers.key && ssl->buffers.key->buffer) {
  26974. ssl->options.sendVerify = SEND_CERT;
  26975. }
  26976. }
  26977. #ifdef OPENSSL_EXTRA
  26978. else
  26979. #else
  26980. else if (IsTLS(ssl) || ssl->options.dtls)
  26981. #endif
  26982. {
  26983. ssl->options.sendVerify = SEND_BLANK_CERT;
  26984. }
  26985. if (IsEncryptionOn(ssl, 0)) {
  26986. *inOutIdx += ssl->keys.padSz;
  26987. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  26988. if (ssl->options.startedETMRead)
  26989. *inOutIdx += MacSize(ssl);
  26990. #endif
  26991. }
  26992. WOLFSSL_LEAVE("DoCertificateRequest", 0);
  26993. WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_DO);
  26994. return 0;
  26995. }
  26996. #endif /* !NO_CERTS */
  26997. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  26998. static int CheckCurveId(int tlsCurveId)
  26999. {
  27000. int ret = WC_NO_ERR_TRACE(ECC_CURVE_ERROR);
  27001. switch (tlsCurveId) {
  27002. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  27003. #ifndef NO_ECC_SECP
  27004. case WOLFSSL_ECC_SECP160R1: return ECC_SECP160R1_OID;
  27005. #endif /* !NO_ECC_SECP */
  27006. #ifdef HAVE_ECC_SECPR2
  27007. case WOLFSSL_ECC_SECP160R2: return ECC_SECP160R2_OID;
  27008. #endif /* HAVE_ECC_SECPR2 */
  27009. #ifdef HAVE_ECC_KOBLITZ
  27010. case WOLFSSL_ECC_SECP160K1: return ECC_SECP160K1_OID;
  27011. #endif /* HAVE_ECC_KOBLITZ */
  27012. #endif
  27013. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  27014. #ifndef NO_ECC_SECP
  27015. case WOLFSSL_ECC_SECP192R1: return ECC_SECP192R1_OID;
  27016. #endif /* !NO_ECC_SECP */
  27017. #ifdef HAVE_ECC_KOBLITZ
  27018. case WOLFSSL_ECC_SECP192K1: return ECC_SECP192K1_OID;
  27019. #endif /* HAVE_ECC_KOBLITZ */
  27020. #endif
  27021. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  27022. #ifndef NO_ECC_SECP
  27023. case WOLFSSL_ECC_SECP224R1: return ECC_SECP224R1_OID;
  27024. #endif /* !NO_ECC_SECP */
  27025. #ifdef HAVE_ECC_KOBLITZ
  27026. case WOLFSSL_ECC_SECP224K1: return ECC_SECP224K1_OID;
  27027. #endif /* HAVE_ECC_KOBLITZ */
  27028. #endif
  27029. #if defined(HAVE_CURVE25519) && ECC_MIN_KEY_SZ <= 256
  27030. case WOLFSSL_ECC_X25519: return ECC_X25519_OID;
  27031. #endif
  27032. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  27033. #ifndef NO_ECC_SECP
  27034. case WOLFSSL_ECC_SECP256R1: return ECC_SECP256R1_OID;
  27035. #endif /* !NO_ECC_SECP */
  27036. #ifdef HAVE_ECC_KOBLITZ
  27037. case WOLFSSL_ECC_SECP256K1: return ECC_SECP256K1_OID;
  27038. #endif /* HAVE_ECC_KOBLITZ */
  27039. #ifdef HAVE_ECC_BRAINPOOL
  27040. case WOLFSSL_ECC_BRAINPOOLP256R1: return ECC_BRAINPOOLP256R1_OID;
  27041. #endif /* HAVE_ECC_BRAINPOOL */
  27042. #ifdef WOLFSSL_SM2
  27043. case WOLFSSL_ECC_SM2P256V1: return ECC_SM2P256V1_OID;
  27044. #endif /* WOLFSSL_SM2 */
  27045. #endif
  27046. #if defined(HAVE_CURVE448) && ECC_MIN_KEY_SZ <= 448
  27047. case WOLFSSL_ECC_X448: return ECC_X448_OID;
  27048. #endif
  27049. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  27050. #ifndef NO_ECC_SECP
  27051. case WOLFSSL_ECC_SECP384R1: return ECC_SECP384R1_OID;
  27052. #endif /* !NO_ECC_SECP */
  27053. #ifdef HAVE_ECC_BRAINPOOL
  27054. case WOLFSSL_ECC_BRAINPOOLP384R1: return ECC_BRAINPOOLP384R1_OID;
  27055. #endif /* HAVE_ECC_BRAINPOOL */
  27056. #endif
  27057. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  27058. #ifdef HAVE_ECC_BRAINPOOL
  27059. case WOLFSSL_ECC_BRAINPOOLP512R1: return ECC_BRAINPOOLP512R1_OID;
  27060. #endif /* HAVE_ECC_BRAINPOOL */
  27061. #endif
  27062. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  27063. #ifndef NO_ECC_SECP
  27064. case WOLFSSL_ECC_SECP521R1: return ECC_SECP521R1_OID;
  27065. #endif /* !NO_ECC_SECP */
  27066. #endif
  27067. default:
  27068. ret = WC_NO_ERR_TRACE(ECC_CURVE_ERROR);
  27069. break;
  27070. }
  27071. return ret;
  27072. }
  27073. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  27074. /* Persistable DoServerKeyExchange arguments */
  27075. typedef struct DskeArgs {
  27076. byte* output; /* not allocated */
  27077. #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  27078. defined(HAVE_CURVE448)
  27079. byte* verifySig;
  27080. #endif
  27081. word32 idx;
  27082. word32 begin;
  27083. #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  27084. defined(HAVE_CURVE448)
  27085. word16 verifySigSz;
  27086. #endif
  27087. word16 sigSz;
  27088. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  27089. int bits;
  27090. #endif
  27091. } DskeArgs;
  27092. static void FreeDskeArgs(WOLFSSL* ssl, void* pArgs)
  27093. {
  27094. DskeArgs* args = (DskeArgs*)pArgs;
  27095. (void)ssl;
  27096. (void)args;
  27097. #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  27098. defined(HAVE_CURVE448)
  27099. XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  27100. args->verifySig = NULL;
  27101. #endif
  27102. }
  27103. #ifndef NO_DH
  27104. static int GetDhPublicKey(WOLFSSL* ssl, const byte* input, word32 size,
  27105. DskeArgs* args)
  27106. {
  27107. int ret = 0;
  27108. word16 length;
  27109. #ifdef HAVE_FFDHE
  27110. #ifdef HAVE_PUBLIC_FFDHE
  27111. const DhParams* params = NULL;
  27112. #endif
  27113. word16 group = 0;
  27114. #endif
  27115. if (ssl->buffers.weOwnDH) {
  27116. if (ssl->buffers.serverDH_P.buffer) {
  27117. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  27118. DYNAMIC_TYPE_PUBLIC_KEY);
  27119. ssl->buffers.serverDH_P.buffer = NULL;
  27120. }
  27121. if (ssl->buffers.serverDH_G.buffer) {
  27122. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  27123. DYNAMIC_TYPE_PUBLIC_KEY);
  27124. ssl->buffers.serverDH_G.buffer = NULL;
  27125. }
  27126. }
  27127. if (ssl->buffers.serverDH_Pub.buffer) {
  27128. XFREE(ssl->buffers.serverDH_Pub.buffer, ssl->heap,
  27129. DYNAMIC_TYPE_PUBLIC_KEY);
  27130. ssl->buffers.serverDH_Pub.buffer = NULL;
  27131. }
  27132. /* p */
  27133. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  27134. ERROR_OUT(BUFFER_ERROR, exit_gdpk);
  27135. }
  27136. ato16(input + args->idx, &length);
  27137. args->idx += OPAQUE16_LEN;
  27138. if ((args->idx - args->begin) + length > size) {
  27139. ERROR_OUT(BUFFER_ERROR, exit_gdpk);
  27140. }
  27141. if (length < ssl->options.minDhKeySz) {
  27142. WOLFSSL_MSG("Server using a DH key that is too small");
  27143. SendAlert(ssl, alert_fatal, handshake_failure);
  27144. ERROR_OUT(DH_KEY_SIZE_E, exit_gdpk);
  27145. }
  27146. if (length > ssl->options.maxDhKeySz) {
  27147. WOLFSSL_MSG("Server using a DH key that is too big");
  27148. SendAlert(ssl, alert_fatal, handshake_failure);
  27149. ERROR_OUT(DH_KEY_SIZE_E, exit_gdpk);
  27150. }
  27151. ssl->buffers.serverDH_P.buffer =
  27152. (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  27153. if (ssl->buffers.serverDH_P.buffer) {
  27154. ssl->buffers.serverDH_P.length = length;
  27155. }
  27156. else {
  27157. ERROR_OUT(MEMORY_ERROR, exit_gdpk);
  27158. }
  27159. XMEMCPY(ssl->buffers.serverDH_P.buffer, input + args->idx,
  27160. length);
  27161. args->idx += length;
  27162. ssl->options.dhKeySz = length;
  27163. /* g */
  27164. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  27165. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  27166. DYNAMIC_TYPE_PUBLIC_KEY);
  27167. ssl->buffers.serverDH_P.buffer = NULL;
  27168. ERROR_OUT(BUFFER_ERROR, exit_gdpk);
  27169. }
  27170. ato16(input + args->idx, &length);
  27171. args->idx += OPAQUE16_LEN;
  27172. if ((args->idx - args->begin) + length > size) {
  27173. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  27174. DYNAMIC_TYPE_PUBLIC_KEY);
  27175. ssl->buffers.serverDH_P.buffer = NULL;
  27176. ERROR_OUT(BUFFER_ERROR, exit_gdpk);
  27177. }
  27178. if (length > ssl->options.maxDhKeySz) {
  27179. WOLFSSL_MSG("Server using a DH key generator that is too big");
  27180. SendAlert(ssl, alert_fatal, handshake_failure);
  27181. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  27182. DYNAMIC_TYPE_PUBLIC_KEY);
  27183. ssl->buffers.serverDH_P.buffer = NULL;
  27184. ERROR_OUT(DH_KEY_SIZE_E, exit_gdpk);
  27185. }
  27186. ssl->buffers.serverDH_G.buffer =
  27187. (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  27188. if (ssl->buffers.serverDH_G.buffer) {
  27189. ssl->buffers.serverDH_G.length = length;
  27190. }
  27191. else {
  27192. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  27193. DYNAMIC_TYPE_PUBLIC_KEY);
  27194. ssl->buffers.serverDH_P.buffer = NULL;
  27195. ERROR_OUT(MEMORY_ERROR, exit_gdpk);
  27196. }
  27197. XMEMCPY(ssl->buffers.serverDH_G.buffer, input + args->idx,
  27198. length);
  27199. args->idx += length;
  27200. /* pub */
  27201. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  27202. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  27203. DYNAMIC_TYPE_PUBLIC_KEY);
  27204. ssl->buffers.serverDH_P.buffer = NULL;
  27205. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  27206. DYNAMIC_TYPE_PUBLIC_KEY);
  27207. ssl->buffers.serverDH_G.buffer = NULL;
  27208. ERROR_OUT(BUFFER_ERROR, exit_gdpk);
  27209. }
  27210. ato16(input + args->idx, &length);
  27211. args->idx += OPAQUE16_LEN;
  27212. if ((args->idx - args->begin) + length > size) {
  27213. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  27214. DYNAMIC_TYPE_PUBLIC_KEY);
  27215. ssl->buffers.serverDH_P.buffer = NULL;
  27216. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  27217. DYNAMIC_TYPE_PUBLIC_KEY);
  27218. ssl->buffers.serverDH_G.buffer = NULL;
  27219. ERROR_OUT(BUFFER_ERROR, exit_gdpk);
  27220. }
  27221. if (length > ssl->options.maxDhKeySz) {
  27222. WOLFSSL_MSG("Server using a public DH key that is too big");
  27223. SendAlert(ssl, alert_fatal, handshake_failure);
  27224. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  27225. DYNAMIC_TYPE_PUBLIC_KEY);
  27226. ssl->buffers.serverDH_P.buffer = NULL;
  27227. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  27228. DYNAMIC_TYPE_PUBLIC_KEY);
  27229. ssl->buffers.serverDH_G.buffer = NULL;
  27230. ERROR_OUT(DH_KEY_SIZE_E, exit_gdpk);
  27231. }
  27232. ssl->buffers.serverDH_Pub.buffer =
  27233. (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  27234. if (ssl->buffers.serverDH_Pub.buffer) {
  27235. ssl->buffers.serverDH_Pub.length = length;
  27236. }
  27237. else {
  27238. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
  27239. DYNAMIC_TYPE_PUBLIC_KEY);
  27240. ssl->buffers.serverDH_P.buffer = NULL;
  27241. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
  27242. DYNAMIC_TYPE_PUBLIC_KEY);
  27243. ssl->buffers.serverDH_G.buffer = NULL;
  27244. ERROR_OUT(MEMORY_ERROR, exit_gdpk);
  27245. }
  27246. XMEMCPY(ssl->buffers.serverDH_Pub.buffer, input + args->idx,
  27247. length);
  27248. ssl->buffers.weOwnDH = 1;
  27249. args->idx += length;
  27250. #ifdef HAVE_FFDHE
  27251. switch (ssl->options.dhKeySz) {
  27252. #ifdef HAVE_FFDHE_2048
  27253. case 2048/8:
  27254. #ifdef HAVE_PUBLIC_FFDHE
  27255. params = wc_Dh_ffdhe2048_Get();
  27256. #endif
  27257. group = WOLFSSL_FFDHE_2048;
  27258. break;
  27259. #endif
  27260. #ifdef HAVE_FFDHE_3072
  27261. case 3072/8:
  27262. #ifdef HAVE_PUBLIC_FFDHE
  27263. params = wc_Dh_ffdhe3072_Get();
  27264. #endif
  27265. group = WOLFSSL_FFDHE_3072;
  27266. break;
  27267. #endif
  27268. #ifdef HAVE_FFDHE_4096
  27269. case 4096/8:
  27270. #ifdef HAVE_PUBLIC_FFDHE
  27271. params = wc_Dh_ffdhe4096_Get();
  27272. #endif
  27273. group = WOLFSSL_FFDHE_4096;
  27274. break;
  27275. #endif
  27276. #ifdef HAVE_FFDHE_6144
  27277. case 6144/8:
  27278. #ifdef HAVE_PUBLIC_FFDHE
  27279. params = wc_Dh_ffdhe6144_Get();
  27280. #endif
  27281. group = WOLFSSL_FFDHE_6144;
  27282. break;
  27283. #endif
  27284. #ifdef HAVE_FFDHE_8192
  27285. case 8192/8:
  27286. #ifdef HAVE_PUBLIC_FFDHE
  27287. params = wc_Dh_ffdhe8192_Get();
  27288. #endif
  27289. group = WOLFSSL_FFDHE_8192;
  27290. break;
  27291. #endif
  27292. default:
  27293. break;
  27294. }
  27295. #ifdef HAVE_PUBLIC_FFDHE
  27296. if (params == NULL || params->g_len != ssl->buffers.serverDH_G.length ||
  27297. (XMEMCMP(ssl->buffers.serverDH_G.buffer, params->g,
  27298. params->g_len) != 0) ||
  27299. (XMEMCMP(ssl->buffers.serverDH_P.buffer, params->p,
  27300. params->p_len) != 0))
  27301. #else
  27302. if (!wc_DhCmpNamedKey(group, 1,
  27303. ssl->buffers.serverDH_P.buffer, ssl->buffers.serverDH_P.length,
  27304. ssl->buffers.serverDH_G.buffer, ssl->buffers.serverDH_G.length,
  27305. NULL, 0))
  27306. #endif
  27307. {
  27308. WOLFSSL_MSG("Server not using FFDHE parameters");
  27309. #ifdef WOLFSSL_REQUIRE_FFDHE
  27310. SendAlert(ssl, alert_fatal, handshake_failure);
  27311. ERROR_OUT(DH_PARAMS_NOT_FFDHE_E, exit_gdpk);
  27312. #endif
  27313. }
  27314. else {
  27315. ssl->namedGroup = group;
  27316. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
  27317. !defined(HAVE_SELFTEST)
  27318. ssl->options.dhDoKeyTest = 0;
  27319. #endif
  27320. }
  27321. #endif /* HAVE_FFDHE */
  27322. exit_gdpk:
  27323. if (ret != 0) {
  27324. WOLFSSL_ERROR_VERBOSE(ret);
  27325. }
  27326. return ret;
  27327. }
  27328. #endif
  27329. /* handle processing of server_key_exchange (12) */
  27330. static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input,
  27331. word32* inOutIdx, word32 size)
  27332. {
  27333. int ret = 0;
  27334. #ifdef WOLFSSL_ASYNC_CRYPT
  27335. DskeArgs* args = NULL;
  27336. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  27337. #else
  27338. DskeArgs args[1];
  27339. #endif
  27340. (void)input;
  27341. (void)size;
  27342. WOLFSSL_START(WC_FUNC_SERVER_KEY_EXCHANGE_DO);
  27343. WOLFSSL_ENTER("DoServerKeyExchange");
  27344. #ifdef WOLFSSL_ASYNC_CRYPT
  27345. if (ssl->async == NULL) {
  27346. ssl->async = (struct WOLFSSL_ASYNC*)
  27347. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  27348. DYNAMIC_TYPE_ASYNC);
  27349. if (ssl->async == NULL)
  27350. ERROR_OUT(MEMORY_E, exit_dske);
  27351. }
  27352. args = (DskeArgs*)ssl->async->args;
  27353. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  27354. if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
  27355. /* Check for error */
  27356. if (ret < 0)
  27357. goto exit_dske;
  27358. }
  27359. else
  27360. #endif
  27361. {
  27362. /* Reset state */
  27363. ret = 0;
  27364. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  27365. XMEMSET(args, 0, sizeof(DskeArgs));
  27366. args->idx = *inOutIdx;
  27367. args->begin = *inOutIdx;
  27368. ssl->options.peerSigAlgo = ssl->specs.sig_algo;
  27369. ssl->options.peerHashAlgo = sha_mac;
  27370. #ifdef WOLFSSL_ASYNC_CRYPT
  27371. ssl->async->freeArgs = FreeDskeArgs;
  27372. #endif
  27373. }
  27374. switch(ssl->options.asyncState)
  27375. {
  27376. case TLS_ASYNC_BEGIN:
  27377. {
  27378. #ifdef WOLFSSL_CALLBACKS
  27379. if (ssl->hsInfoOn)
  27380. AddPacketName(ssl, "ServerKeyExchange");
  27381. if (ssl->toInfoOn)
  27382. AddLateName("ServerKeyExchange", &ssl->timeoutInfo);
  27383. #endif
  27384. switch(ssl->specs.kea)
  27385. {
  27386. #ifndef NO_PSK
  27387. case psk_kea:
  27388. {
  27389. int srvHintLen;
  27390. word16 length;
  27391. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  27392. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27393. }
  27394. ato16(input + args->idx, &length);
  27395. args->idx += OPAQUE16_LEN;
  27396. if ((args->idx - args->begin) + length > size) {
  27397. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27398. }
  27399. /* get PSK server hint from the wire */
  27400. srvHintLen = (int)min(length, MAX_PSK_ID_LEN);
  27401. XMEMCPY(ssl->arrays->server_hint, input + args->idx,
  27402. srvHintLen);
  27403. ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */
  27404. args->idx += length;
  27405. break;
  27406. }
  27407. #endif /* !NO_PSK */
  27408. #ifndef NO_DH
  27409. case diffie_hellman_kea:
  27410. {
  27411. ret = GetDhPublicKey(ssl, input, size, args);
  27412. if (ret != 0)
  27413. goto exit_dske;
  27414. break;
  27415. }
  27416. #endif /* !NO_DH */
  27417. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  27418. defined(HAVE_CURVE448)
  27419. case ecc_diffie_hellman_kea:
  27420. {
  27421. byte b;
  27422. #ifdef HAVE_ECC
  27423. int curveId;
  27424. #endif
  27425. int curveOid;
  27426. word16 length;
  27427. if ((args->idx - args->begin) + ENUM_LEN + OPAQUE16_LEN +
  27428. OPAQUE8_LEN > size) {
  27429. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27430. }
  27431. b = input[args->idx++];
  27432. if (b != named_curve) {
  27433. ERROR_OUT(ECC_CURVETYPE_ERROR, exit_dske);
  27434. }
  27435. args->idx += 1; /* curve type, eat leading 0 */
  27436. b = input[args->idx++];
  27437. if ((curveOid = CheckCurveId(b)) < 0) {
  27438. ERROR_OUT(ECC_CURVE_ERROR, exit_dske);
  27439. }
  27440. ssl->ecdhCurveOID = (word32)curveOid;
  27441. #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
  27442. ssl->namedGroup = 0;
  27443. #endif
  27444. length = input[args->idx++];
  27445. if ((args->idx - args->begin) + length > size) {
  27446. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27447. }
  27448. #ifdef HAVE_CURVE25519
  27449. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  27450. if (ssl->peerX25519Key == NULL) {
  27451. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
  27452. (void**)&ssl->peerX25519Key);
  27453. if (ret != 0) {
  27454. goto exit_dske;
  27455. }
  27456. } else if (ssl->peerX25519KeyPresent) {
  27457. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE25519,
  27458. ssl->peerX25519Key);
  27459. ssl->peerX25519KeyPresent = 0;
  27460. if (ret != 0) {
  27461. goto exit_dske;
  27462. }
  27463. }
  27464. if ((ret = wc_curve25519_check_public(
  27465. input + args->idx, length,
  27466. EC25519_LITTLE_ENDIAN)) != 0) {
  27467. #ifdef WOLFSSL_EXTRA_ALERTS
  27468. if (ret == WC_NO_ERR_TRACE(BUFFER_E))
  27469. SendAlert(ssl, alert_fatal, decode_error);
  27470. else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E))
  27471. SendAlert(ssl, alert_fatal, bad_record_mac);
  27472. else {
  27473. SendAlert(ssl, alert_fatal, illegal_parameter);
  27474. }
  27475. #endif
  27476. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  27477. }
  27478. if (wc_curve25519_import_public_ex(input + args->idx,
  27479. length, ssl->peerX25519Key,
  27480. EC25519_LITTLE_ENDIAN) != 0) {
  27481. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  27482. }
  27483. args->idx += length;
  27484. ssl->peerX25519KeyPresent = 1;
  27485. break;
  27486. }
  27487. #endif
  27488. #ifdef HAVE_CURVE448
  27489. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  27490. if (ssl->peerX448Key == NULL) {
  27491. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
  27492. (void**)&ssl->peerX448Key);
  27493. if (ret != 0) {
  27494. goto exit_dske;
  27495. }
  27496. } else if (ssl->peerX448KeyPresent) {
  27497. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE448,
  27498. ssl->peerX448Key);
  27499. ssl->peerX448KeyPresent = 0;
  27500. if (ret != 0) {
  27501. goto exit_dske;
  27502. }
  27503. }
  27504. if ((ret = wc_curve448_check_public(
  27505. input + args->idx, length,
  27506. EC448_LITTLE_ENDIAN)) != 0) {
  27507. #ifdef WOLFSSL_EXTRA_ALERTS
  27508. if (ret == WC_NO_ERR_TRACE(BUFFER_E))
  27509. SendAlert(ssl, alert_fatal, decode_error);
  27510. else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E))
  27511. SendAlert(ssl, alert_fatal, bad_record_mac);
  27512. else {
  27513. SendAlert(ssl, alert_fatal, illegal_parameter);
  27514. }
  27515. #endif
  27516. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  27517. }
  27518. if (wc_curve448_import_public_ex(input + args->idx,
  27519. length, ssl->peerX448Key,
  27520. EC448_LITTLE_ENDIAN) != 0) {
  27521. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  27522. }
  27523. args->idx += length;
  27524. ssl->peerX448KeyPresent = 1;
  27525. break;
  27526. }
  27527. #endif
  27528. #ifdef HAVE_ECC
  27529. if (ssl->peerEccKey == NULL) {
  27530. ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
  27531. (void**)&ssl->peerEccKey);
  27532. if (ret != 0) {
  27533. goto exit_dske;
  27534. }
  27535. } else if (ssl->peerEccKeyPresent) {
  27536. ret = ReuseKey(ssl, DYNAMIC_TYPE_ECC, ssl->peerEccKey);
  27537. ssl->peerEccKeyPresent = 0;
  27538. if (ret != 0) {
  27539. goto exit_dske;
  27540. }
  27541. }
  27542. curveId = wc_ecc_get_oid((word32)curveOid, NULL, NULL);
  27543. if (wc_ecc_import_x963_ex(input + args->idx, length,
  27544. ssl->peerEccKey, curveId) != 0) {
  27545. #ifdef WOLFSSL_EXTRA_ALERTS
  27546. SendAlert(ssl, alert_fatal, illegal_parameter);
  27547. #endif
  27548. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  27549. }
  27550. args->idx += length;
  27551. ssl->peerEccKeyPresent = 1;
  27552. #endif
  27553. break;
  27554. }
  27555. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  27556. #if !defined(NO_DH) && !defined(NO_PSK)
  27557. case dhe_psk_kea:
  27558. {
  27559. int srvHintLen;
  27560. word16 length;
  27561. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  27562. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27563. }
  27564. ato16(input + args->idx, &length);
  27565. args->idx += OPAQUE16_LEN;
  27566. if ((args->idx - args->begin) + length > size) {
  27567. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27568. }
  27569. /* get PSK server hint from the wire */
  27570. srvHintLen = (int)min(length, MAX_PSK_ID_LEN);
  27571. XMEMCPY(ssl->arrays->server_hint, input + args->idx,
  27572. srvHintLen);
  27573. ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */
  27574. args->idx += length;
  27575. ret = GetDhPublicKey(ssl, input, size, args);
  27576. if (ret != 0)
  27577. goto exit_dske;
  27578. break;
  27579. }
  27580. #endif /* !NO_DH && !NO_PSK */
  27581. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  27582. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  27583. case ecdhe_psk_kea:
  27584. {
  27585. byte b;
  27586. int curveOid, curveId;
  27587. int srvHintLen;
  27588. word16 length;
  27589. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  27590. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27591. }
  27592. ato16(input + args->idx, &length);
  27593. args->idx += OPAQUE16_LEN;
  27594. if ((args->idx - args->begin) + length > size) {
  27595. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27596. }
  27597. /* get PSK server hint from the wire */
  27598. srvHintLen = (int)min(length, MAX_PSK_ID_LEN);
  27599. XMEMCPY(ssl->arrays->server_hint, input + args->idx,
  27600. srvHintLen);
  27601. ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */
  27602. args->idx += length;
  27603. if ((args->idx - args->begin) + ENUM_LEN + OPAQUE16_LEN +
  27604. OPAQUE8_LEN > size) {
  27605. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27606. }
  27607. /* Check curve name and ID */
  27608. b = input[args->idx++];
  27609. if (b != named_curve) {
  27610. ERROR_OUT(ECC_CURVETYPE_ERROR, exit_dske);
  27611. }
  27612. args->idx += 1; /* curve type, eat leading 0 */
  27613. b = input[args->idx++];
  27614. if ((curveOid = CheckCurveId(b)) < 0) {
  27615. ERROR_OUT(ECC_CURVE_ERROR, exit_dske);
  27616. }
  27617. ssl->ecdhCurveOID = (word32)curveOid;
  27618. length = input[args->idx++];
  27619. if ((args->idx - args->begin) + length > size) {
  27620. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27621. }
  27622. #ifdef HAVE_CURVE25519
  27623. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  27624. if (ssl->peerX25519Key == NULL) {
  27625. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
  27626. (void**)&ssl->peerX25519Key);
  27627. if (ret != 0) {
  27628. goto exit_dske;
  27629. }
  27630. } else if (ssl->peerEccKeyPresent) {
  27631. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE25519,
  27632. ssl->peerX25519Key);
  27633. ssl->peerX25519KeyPresent = 0;
  27634. if (ret != 0) {
  27635. goto exit_dske;
  27636. }
  27637. }
  27638. if ((ret = wc_curve25519_check_public(
  27639. input + args->idx, length,
  27640. EC25519_LITTLE_ENDIAN)) != 0) {
  27641. #ifdef WOLFSSL_EXTRA_ALERTS
  27642. if (ret == WC_NO_ERR_TRACE(BUFFER_E))
  27643. SendAlert(ssl, alert_fatal, decode_error);
  27644. else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E))
  27645. SendAlert(ssl, alert_fatal, bad_record_mac);
  27646. else {
  27647. SendAlert(ssl, alert_fatal, illegal_parameter);
  27648. }
  27649. #endif
  27650. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  27651. }
  27652. if (wc_curve25519_import_public_ex(input + args->idx,
  27653. length, ssl->peerX25519Key,
  27654. EC25519_LITTLE_ENDIAN) != 0) {
  27655. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  27656. }
  27657. args->idx += length;
  27658. ssl->peerX25519KeyPresent = 1;
  27659. break;
  27660. }
  27661. #endif
  27662. #ifdef HAVE_CURVE448
  27663. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  27664. if (ssl->peerX448Key == NULL) {
  27665. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
  27666. (void**)&ssl->peerX448Key);
  27667. if (ret != 0) {
  27668. goto exit_dske;
  27669. }
  27670. } else if (ssl->peerEccKeyPresent) {
  27671. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE448,
  27672. ssl->peerX448Key);
  27673. ssl->peerX448KeyPresent = 0;
  27674. if (ret != 0) {
  27675. goto exit_dske;
  27676. }
  27677. }
  27678. if ((ret = wc_curve448_check_public(
  27679. input + args->idx, length,
  27680. EC448_LITTLE_ENDIAN)) != 0) {
  27681. #ifdef WOLFSSL_EXTRA_ALERTS
  27682. if (ret == WC_NO_ERR_TRACE(BUFFER_E))
  27683. SendAlert(ssl, alert_fatal, decode_error);
  27684. else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E))
  27685. SendAlert(ssl, alert_fatal, bad_record_mac);
  27686. else {
  27687. SendAlert(ssl, alert_fatal, illegal_parameter);
  27688. }
  27689. #endif
  27690. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  27691. }
  27692. if (wc_curve448_import_public_ex(input + args->idx,
  27693. length, ssl->peerX448Key,
  27694. EC448_LITTLE_ENDIAN) != 0) {
  27695. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  27696. }
  27697. args->idx += length;
  27698. ssl->peerX448KeyPresent = 1;
  27699. break;
  27700. }
  27701. #endif
  27702. if (ssl->peerEccKey == NULL) {
  27703. ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
  27704. (void**)&ssl->peerEccKey);
  27705. if (ret != 0) {
  27706. goto exit_dske;
  27707. }
  27708. } else if (ssl->peerEccKeyPresent) {
  27709. ret = ReuseKey(ssl, DYNAMIC_TYPE_ECC, ssl->peerEccKey);
  27710. ssl->peerEccKeyPresent = 0;
  27711. if (ret != 0) {
  27712. goto exit_dske;
  27713. }
  27714. }
  27715. curveId = wc_ecc_get_oid((word32)curveOid, NULL, NULL);
  27716. if (wc_ecc_import_x963_ex(input + args->idx, length,
  27717. ssl->peerEccKey, curveId) != 0) {
  27718. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  27719. }
  27720. args->idx += length;
  27721. ssl->peerEccKeyPresent = 1;
  27722. break;
  27723. }
  27724. #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
  27725. default:
  27726. ret = BAD_KEA_TYPE_E;
  27727. } /* switch(ssl->specs.kea) */
  27728. /* Check for error */
  27729. if (ret != 0) {
  27730. goto exit_dske;
  27731. }
  27732. /* Advance state and proceed */
  27733. ssl->options.asyncState = TLS_ASYNC_BUILD;
  27734. } /* case TLS_ASYNC_BEGIN */
  27735. FALL_THROUGH;
  27736. case TLS_ASYNC_BUILD:
  27737. {
  27738. switch(ssl->specs.kea)
  27739. {
  27740. case psk_kea:
  27741. case dhe_psk_kea:
  27742. case ecdhe_psk_kea:
  27743. {
  27744. /* Nothing to do in this sub-state */
  27745. break;
  27746. }
  27747. case diffie_hellman_kea:
  27748. case ecc_diffie_hellman_kea:
  27749. {
  27750. #if defined(NO_DH) && !defined(HAVE_ECC) && \
  27751. !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448)
  27752. ERROR_OUT(NOT_COMPILED_IN, exit_dske);
  27753. #else
  27754. enum wc_HashType hashType;
  27755. word32 verifySz;
  27756. byte sigAlgo;
  27757. if (ssl->options.usingAnon_cipher) {
  27758. break;
  27759. }
  27760. verifySz = (args->idx - args->begin);
  27761. if (verifySz > MAX_DH_SZ) {
  27762. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27763. }
  27764. if (IsAtLeastTLSv1_2(ssl)) {
  27765. if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN >
  27766. size) {
  27767. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27768. }
  27769. /* Check if hashSigAlgo in Server Key Exchange is supported
  27770. * in our ssl->suites or ssl->ctx->suites. */
  27771. if (!SupportedHashSigAlgo(ssl, &input[args->idx])) {
  27772. #ifdef WOLFSSL_EXTRA_ALERTS
  27773. SendAlert(ssl, alert_fatal, handshake_failure);
  27774. #endif
  27775. ERROR_OUT(MATCH_SUITE_ERROR, exit_dske);
  27776. }
  27777. DecodeSigAlg(&input[args->idx], &ssl->options.peerHashAlgo,
  27778. &sigAlgo);
  27779. #ifndef NO_RSA
  27780. if (sigAlgo == rsa_pss_sa_algo &&
  27781. ssl->options.peerSigAlgo == rsa_sa_algo) {
  27782. ssl->options.peerSigAlgo = sigAlgo;
  27783. }
  27784. else
  27785. #endif
  27786. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27787. if (sigAlgo == sm2_sa_algo &&
  27788. ssl->options.peerSigAlgo == ecc_dsa_sa_algo) {
  27789. ssl->options.peerSigAlgo = sigAlgo;
  27790. }
  27791. else
  27792. #endif
  27793. #ifdef HAVE_ED25519
  27794. if (sigAlgo == ed25519_sa_algo &&
  27795. ssl->options.peerSigAlgo == ecc_dsa_sa_algo) {
  27796. ssl->options.peerSigAlgo = sigAlgo;
  27797. }
  27798. else
  27799. #endif
  27800. #ifdef HAVE_ED448
  27801. if (sigAlgo == ed448_sa_algo &&
  27802. ssl->options.peerSigAlgo == ecc_dsa_sa_algo) {
  27803. ssl->options.peerSigAlgo = sigAlgo;
  27804. }
  27805. else
  27806. #endif
  27807. /* Signature algorithm from message must match signature
  27808. * algorithm in cipher suite. */
  27809. if (sigAlgo != ssl->options.peerSigAlgo) {
  27810. ERROR_OUT(ALGO_ID_E, exit_dske);
  27811. }
  27812. args->idx += 2;
  27813. hashType = HashAlgoToType(ssl->options.peerHashAlgo);
  27814. if (hashType == WC_HASH_TYPE_NONE) {
  27815. ERROR_OUT(ALGO_ID_E, exit_dske);
  27816. }
  27817. } else {
  27818. /* only using sha and md5 for rsa */
  27819. #ifndef NO_OLD_TLS
  27820. hashType = WC_HASH_TYPE_SHA;
  27821. if (ssl->options.peerSigAlgo == rsa_sa_algo) {
  27822. hashType = WC_HASH_TYPE_MD5_SHA;
  27823. }
  27824. #else
  27825. ERROR_OUT(ALGO_ID_E, exit_dske);
  27826. #endif
  27827. }
  27828. /* signature */
  27829. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  27830. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27831. }
  27832. ato16(input + args->idx, &args->verifySigSz);
  27833. args->idx += OPAQUE16_LEN;
  27834. if ((args->idx - args->begin) + args->verifySigSz > size) {
  27835. ERROR_OUT(BUFFER_ERROR, exit_dske);
  27836. }
  27837. ret = HashSkeData(ssl, hashType, input + args->begin,
  27838. verifySz, ssl->options.peerSigAlgo);
  27839. if (ret != 0) {
  27840. goto exit_dske;
  27841. }
  27842. switch (ssl->options.peerSigAlgo)
  27843. {
  27844. #ifndef NO_RSA
  27845. #ifdef WC_RSA_PSS
  27846. case rsa_pss_sa_algo:
  27847. #endif
  27848. case rsa_sa_algo:
  27849. {
  27850. if (ssl->peerRsaKey == NULL ||
  27851. !ssl->peerRsaKeyPresent) {
  27852. ERROR_OUT(NO_PEER_KEY, exit_dske);
  27853. }
  27854. break;
  27855. }
  27856. #endif /* !NO_RSA */
  27857. #ifdef HAVE_ECC
  27858. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27859. case sm2_sa_algo:
  27860. #endif
  27861. case ecc_dsa_sa_algo:
  27862. {
  27863. if (!ssl->peerEccDsaKeyPresent) {
  27864. ERROR_OUT(NO_PEER_KEY, exit_dske);
  27865. }
  27866. break;
  27867. }
  27868. #endif /* HAVE_ECC */
  27869. #if defined(HAVE_ED25519)
  27870. case ed25519_sa_algo:
  27871. {
  27872. if (!ssl->peerEd25519KeyPresent) {
  27873. ERROR_OUT(NO_PEER_KEY, exit_dske);
  27874. }
  27875. break;
  27876. }
  27877. #endif /* HAVE_ED25519 */
  27878. #if defined(HAVE_ED448)
  27879. case ed448_sa_algo:
  27880. {
  27881. if (!ssl->peerEd448KeyPresent) {
  27882. ERROR_OUT(NO_PEER_KEY, exit_dske);
  27883. }
  27884. break;
  27885. }
  27886. #endif /* HAVE_ED448 */
  27887. default:
  27888. ret = ALGO_ID_E;
  27889. } /* switch (ssl->options.peerSigAlgo) */
  27890. #endif /* NO_DH && !HAVE_ECC && !HAVE_ED25519 && !HAVE_ED448 */
  27891. break;
  27892. }
  27893. default:
  27894. ret = BAD_KEA_TYPE_E;
  27895. } /* switch(ssl->specs.kea) */
  27896. /* Check for error */
  27897. if (ret != 0) {
  27898. goto exit_dske;
  27899. }
  27900. /* Advance state and proceed */
  27901. ssl->options.asyncState = TLS_ASYNC_DO;
  27902. } /* case TLS_ASYNC_BUILD */
  27903. FALL_THROUGH;
  27904. case TLS_ASYNC_DO:
  27905. {
  27906. switch(ssl->specs.kea)
  27907. {
  27908. case psk_kea:
  27909. case dhe_psk_kea:
  27910. case ecdhe_psk_kea:
  27911. {
  27912. /* Nothing to do in this sub-state */
  27913. break;
  27914. }
  27915. case diffie_hellman_kea:
  27916. case ecc_diffie_hellman_kea:
  27917. {
  27918. #if defined(NO_DH) && !defined(HAVE_ECC) && \
  27919. !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448)
  27920. ERROR_OUT(NOT_COMPILED_IN, exit_dske);
  27921. #else
  27922. if (ssl->options.usingAnon_cipher) {
  27923. break;
  27924. }
  27925. if (args->verifySig == NULL) {
  27926. args->verifySig = (byte*)XMALLOC(args->verifySigSz,
  27927. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  27928. if (args->verifySig == NULL) {
  27929. ERROR_OUT(MEMORY_E, exit_dske);
  27930. }
  27931. XMEMCPY(args->verifySig, input + args->idx,
  27932. args->verifySigSz);
  27933. }
  27934. switch (ssl->options.peerSigAlgo)
  27935. {
  27936. #ifndef NO_RSA
  27937. #ifdef WC_RSA_PSS
  27938. case rsa_pss_sa_algo:
  27939. #endif
  27940. case rsa_sa_algo:
  27941. {
  27942. ret = RsaVerify(ssl,
  27943. args->verifySig, args->verifySigSz,
  27944. &args->output,
  27945. ssl->options.peerSigAlgo, ssl->options.peerHashAlgo,
  27946. ssl->peerRsaKey,
  27947. #ifdef HAVE_PK_CALLBACKS
  27948. &ssl->buffers.peerRsaKey
  27949. #else
  27950. NULL
  27951. #endif
  27952. );
  27953. if (ret >= 0) {
  27954. args->sigSz = (word16)ret;
  27955. #ifdef WC_RSA_PSS
  27956. args->bits = mp_count_bits(&ssl->peerRsaKey->n);
  27957. #endif
  27958. ret = 0;
  27959. }
  27960. #ifdef WOLFSSL_ASYNC_CRYPT
  27961. if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
  27962. #endif
  27963. {
  27964. /* peerRsaKey */
  27965. FreeKey(ssl, DYNAMIC_TYPE_RSA,
  27966. (void**)&ssl->peerRsaKey);
  27967. ssl->peerRsaKeyPresent = 0;
  27968. }
  27969. break;
  27970. }
  27971. #endif /* !NO_RSA */
  27972. #ifdef HAVE_ECC
  27973. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27974. case sm2_sa_algo:
  27975. #endif
  27976. case ecc_dsa_sa_algo:
  27977. {
  27978. ret = NOT_COMPILED_IN;
  27979. #ifdef HAVE_PK_CALLBACKS
  27980. if (ssl->ctx && ssl->ctx->ProcessServerSigKexCb) {
  27981. ret = ssl->ctx->ProcessServerSigKexCb(ssl,
  27982. ssl->options.peerSigAlgo,
  27983. args->verifySig, args->verifySigSz,
  27984. ssl->buffers.sig.buffer, SEED_LEN,
  27985. &ssl->buffers.sig.buffer[SEED_LEN],
  27986. (ssl->buffers.sig.length - SEED_LEN));
  27987. }
  27988. #endif /* HAVE_PK_CALLBACKS */
  27989. if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) {
  27990. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27991. if (ssl->options.peerSigAlgo == sm2_sa_algo) {
  27992. ret = Sm2wSm3Verify(ssl,
  27993. TLS12_SM2_SIG_ID, TLS12_SM2_SIG_ID_SZ,
  27994. args->verifySig, args->verifySigSz,
  27995. ssl->buffers.sig.buffer,
  27996. ssl->buffers.sig.length,
  27997. ssl->peerEccDsaKey,
  27998. #ifdef HAVE_PK_CALLBACKS
  27999. &ssl->buffers.peerEccDsaKey
  28000. #else
  28001. NULL
  28002. #endif
  28003. );
  28004. }
  28005. else
  28006. #endif
  28007. {
  28008. ret = EccVerify(ssl,
  28009. args->verifySig, args->verifySigSz,
  28010. ssl->buffers.digest.buffer,
  28011. ssl->buffers.digest.length,
  28012. ssl->peerEccDsaKey,
  28013. #ifdef HAVE_PK_CALLBACKS
  28014. &ssl->buffers.peerEccDsaKey
  28015. #else
  28016. NULL
  28017. #endif
  28018. );
  28019. }
  28020. }
  28021. #ifdef WOLFSSL_ASYNC_CRYPT
  28022. if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
  28023. #endif
  28024. {
  28025. /* peerEccDsaKey */
  28026. FreeKey(ssl, DYNAMIC_TYPE_ECC,
  28027. (void**)&ssl->peerEccDsaKey);
  28028. ssl->peerEccDsaKeyPresent = 0;
  28029. }
  28030. /* CLIENT: Data verified with cert's public key. */
  28031. ssl->options.peerAuthGood =
  28032. ssl->options.havePeerCert && (ret == 0);
  28033. break;
  28034. }
  28035. #endif /* HAVE_ECC */
  28036. #if defined(HAVE_ED25519)
  28037. case ed25519_sa_algo:
  28038. {
  28039. ret = Ed25519Verify(ssl,
  28040. args->verifySig, args->verifySigSz,
  28041. ssl->buffers.sig.buffer,
  28042. ssl->buffers.sig.length,
  28043. ssl->peerEd25519Key,
  28044. #ifdef HAVE_PK_CALLBACKS
  28045. &ssl->buffers.peerEd25519Key
  28046. #else
  28047. NULL
  28048. #endif
  28049. );
  28050. #ifdef WOLFSSL_ASYNC_CRYPT
  28051. if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
  28052. #endif
  28053. {
  28054. /* peerEccDsaKey */
  28055. FreeKey(ssl, DYNAMIC_TYPE_ED25519,
  28056. (void**)&ssl->peerEd25519Key);
  28057. ssl->peerEd25519KeyPresent = 0;
  28058. }
  28059. /* CLIENT: Data verified with cert's public key. */
  28060. ssl->options.peerAuthGood =
  28061. ssl->options.havePeerCert && (ret == 0);
  28062. break;
  28063. }
  28064. #endif /* HAVE_ED25519 */
  28065. #if defined(HAVE_ED448)
  28066. case ed448_sa_algo:
  28067. {
  28068. ret = Ed448Verify(ssl,
  28069. args->verifySig, args->verifySigSz,
  28070. ssl->buffers.sig.buffer,
  28071. ssl->buffers.sig.length,
  28072. ssl->peerEd448Key,
  28073. #ifdef HAVE_PK_CALLBACKS
  28074. &ssl->buffers.peerEd448Key
  28075. #else
  28076. NULL
  28077. #endif
  28078. );
  28079. #ifdef WOLFSSL_ASYNC_CRYPT
  28080. if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
  28081. #endif
  28082. {
  28083. /* peerEccDsaKey */
  28084. FreeKey(ssl, DYNAMIC_TYPE_ED448,
  28085. (void**)&ssl->peerEd448Key);
  28086. ssl->peerEd448KeyPresent = 0;
  28087. }
  28088. /* CLIENT: Data verified with cert's public key. */
  28089. ssl->options.peerAuthGood =
  28090. ssl->options.havePeerCert && (ret == 0);
  28091. break;
  28092. }
  28093. #endif /* HAVE_ED448 */
  28094. default:
  28095. ret = ALGO_ID_E;
  28096. } /* switch (sigAlgo) */
  28097. #endif /* NO_DH && !HAVE_ECC && !HAVE_ED25519 && !HAVE_ED448 */
  28098. break;
  28099. }
  28100. default:
  28101. ret = BAD_KEA_TYPE_E;
  28102. } /* switch(ssl->specs.kea) */
  28103. /* Check for error */
  28104. if (ret != 0) {
  28105. goto exit_dske;
  28106. }
  28107. /* Advance state and proceed */
  28108. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  28109. } /* case TLS_ASYNC_DO */
  28110. FALL_THROUGH;
  28111. case TLS_ASYNC_VERIFY:
  28112. {
  28113. switch(ssl->specs.kea)
  28114. {
  28115. case psk_kea:
  28116. case dhe_psk_kea:
  28117. case ecdhe_psk_kea:
  28118. {
  28119. /* Nothing to do in this sub-state */
  28120. break;
  28121. }
  28122. case diffie_hellman_kea:
  28123. case ecc_diffie_hellman_kea:
  28124. {
  28125. #if defined(NO_DH) && !defined(HAVE_ECC) && \
  28126. !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448)
  28127. ERROR_OUT(NOT_COMPILED_IN, exit_dske);
  28128. #else
  28129. if (ssl->options.usingAnon_cipher) {
  28130. break;
  28131. }
  28132. /* increment index after verify is done */
  28133. args->idx += args->verifySigSz;
  28134. switch(ssl->options.peerSigAlgo)
  28135. {
  28136. #ifndef NO_RSA
  28137. #ifdef WC_RSA_PSS
  28138. case rsa_pss_sa_algo:
  28139. #ifdef HAVE_SELFTEST
  28140. ret = wc_RsaPSS_CheckPadding(
  28141. ssl->buffers.digest.buffer,
  28142. ssl->buffers.digest.length,
  28143. args->output, args->sigSz,
  28144. HashAlgoToType(ssl->options.peerHashAlgo));
  28145. #else
  28146. ret = wc_RsaPSS_CheckPadding_ex(
  28147. ssl->buffers.digest.buffer,
  28148. ssl->buffers.digest.length,
  28149. args->output, args->sigSz,
  28150. HashAlgoToType(ssl->options.peerHashAlgo),
  28151. -1, args->bits);
  28152. #endif
  28153. if (ret != 0)
  28154. goto exit_dske;
  28155. /* CLIENT: Data verified with cert's public key. */
  28156. ssl->options.peerAuthGood =
  28157. ssl->options.havePeerCert;
  28158. break;
  28159. #endif
  28160. case rsa_sa_algo:
  28161. {
  28162. #if (defined(WOLFSSL_RENESAS_FSPSM_TLS) && \
  28163. defined(WOLFSSL_RENESAS_FSPSM_ECC)) || \
  28164. defined(WOLFSSL_RENESAS_TSIP_TLS)
  28165. /* already checked signature result by SCE */
  28166. /* skip the sign checks below */
  28167. if (Renesas_cmn_usable(ssl, 0)) {
  28168. break;
  28169. }
  28170. #endif
  28171. if (IsAtLeastTLSv1_2(ssl)) {
  28172. #ifdef WOLFSSL_SMALL_STACK
  28173. byte* encodedSig;
  28174. #else
  28175. byte encodedSig[MAX_ENCODED_SIG_SZ];
  28176. #endif
  28177. word32 encSigSz;
  28178. #ifdef WOLFSSL_SMALL_STACK
  28179. encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  28180. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  28181. if (encodedSig == NULL) {
  28182. ERROR_OUT(MEMORY_E, exit_dske);
  28183. }
  28184. #endif
  28185. encSigSz = wc_EncodeSignature(encodedSig,
  28186. ssl->buffers.digest.buffer,
  28187. ssl->buffers.digest.length,
  28188. TypeHash(ssl->options.peerHashAlgo));
  28189. if (encSigSz != args->sigSz || !args->output ||
  28190. XMEMCMP(args->output, encodedSig,
  28191. min(encSigSz, MAX_ENCODED_SIG_SZ)) != 0) {
  28192. ret = VERIFY_SIGN_ERROR;
  28193. }
  28194. #ifdef WOLFSSL_SMALL_STACK
  28195. XFREE(encodedSig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  28196. #endif
  28197. if (ret != 0) {
  28198. goto exit_dske;
  28199. }
  28200. }
  28201. else if (args->sigSz != FINISHED_SZ ||
  28202. !args->output ||
  28203. XMEMCMP(args->output,
  28204. ssl->buffers.digest.buffer,
  28205. FINISHED_SZ) != 0) {
  28206. ERROR_OUT(VERIFY_SIGN_ERROR, exit_dske);
  28207. }
  28208. /* CLIENT: Data verified with cert's public key. */
  28209. ssl->options.peerAuthGood =
  28210. ssl->options.havePeerCert;
  28211. break;
  28212. }
  28213. #endif /* !NO_RSA */
  28214. #ifdef HAVE_ECC
  28215. case ecc_dsa_sa_algo:
  28216. /* Nothing to do in this algo */
  28217. break;
  28218. #endif /* HAVE_ECC */
  28219. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  28220. case sm2_sa_algo:
  28221. /* Nothing to do in this algo */
  28222. break;
  28223. #endif /* WOLFSSL_SM2 && WOLFSSL_SM3 */
  28224. #if defined(HAVE_ED25519)
  28225. case ed25519_sa_algo:
  28226. /* Nothing to do in this algo */
  28227. break;
  28228. #endif /* HAVE_ED25519 */
  28229. #if defined(HAVE_ED448)
  28230. case ed448_sa_algo:
  28231. /* Nothing to do in this algo */
  28232. break;
  28233. #endif /* HAVE_ED448 */
  28234. default:
  28235. ret = ALGO_ID_E;
  28236. } /* switch (sigAlgo) */
  28237. #endif /* NO_DH && !HAVE_ECC && !HAVE_ED25519 && !HAVE_ED448 */
  28238. break;
  28239. }
  28240. default:
  28241. ret = BAD_KEA_TYPE_E;
  28242. } /* switch(ssl->specs.kea) */
  28243. /* Check for error */
  28244. if (ret != 0) {
  28245. goto exit_dske;
  28246. }
  28247. /* Advance state and proceed */
  28248. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  28249. } /* case TLS_ASYNC_VERIFY */
  28250. FALL_THROUGH;
  28251. case TLS_ASYNC_FINALIZE:
  28252. {
  28253. if (IsEncryptionOn(ssl, 0)) {
  28254. args->idx += ssl->keys.padSz;
  28255. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  28256. if (ssl->options.startedETMRead)
  28257. args->idx += MacSize(ssl);
  28258. #endif
  28259. }
  28260. /* Advance state and proceed */
  28261. ssl->options.asyncState = TLS_ASYNC_END;
  28262. } /* case TLS_ASYNC_FINALIZE */
  28263. FALL_THROUGH;
  28264. case TLS_ASYNC_END:
  28265. {
  28266. /* return index */
  28267. *inOutIdx = args->idx;
  28268. ssl->options.serverState = SERVER_KEYEXCHANGE_COMPLETE;
  28269. break;
  28270. }
  28271. default:
  28272. ret = INPUT_CASE_ERROR;
  28273. } /* switch(ssl->options.asyncState) */
  28274. exit_dske:
  28275. WOLFSSL_LEAVE("DoServerKeyExchange", ret);
  28276. WOLFSSL_END(WC_FUNC_SERVER_KEY_EXCHANGE_DO);
  28277. #ifdef WOLFSSL_ASYNC_CRYPT
  28278. /* Handle async operation */
  28279. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  28280. /* Mark message as not received so it can process again */
  28281. ssl->msgsReceived.got_server_key_exchange = 0;
  28282. return ret;
  28283. }
  28284. /* Cleanup async */
  28285. FreeAsyncCtx(ssl, 0);
  28286. #else
  28287. FreeDskeArgs(ssl, args);
  28288. #endif /* WOLFSSL_ASYNC_CRYPT */
  28289. /* Final cleanup */
  28290. FreeKeyExchange(ssl);
  28291. if (ret != 0) {
  28292. WOLFSSL_ERROR_VERBOSE(ret);
  28293. }
  28294. return ret;
  28295. }
  28296. typedef struct SckeArgs {
  28297. byte* output; /* not allocated */
  28298. byte* encSecret;
  28299. byte* input;
  28300. word32 encSz;
  28301. word32 length;
  28302. int sendSz;
  28303. int inputSz;
  28304. } SckeArgs;
  28305. static void FreeSckeArgs(WOLFSSL* ssl, void* pArgs)
  28306. {
  28307. SckeArgs* args = (SckeArgs*)pArgs;
  28308. (void)ssl;
  28309. XFREE(args->encSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  28310. args->encSecret = NULL;
  28311. XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  28312. args->input = NULL;
  28313. }
  28314. /* handle generation client_key_exchange (16) */
  28315. int SendClientKeyExchange(WOLFSSL* ssl)
  28316. {
  28317. int ret = 0;
  28318. #ifdef WOLFSSL_ASYNC_IO
  28319. SckeArgs* args = NULL;
  28320. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  28321. #else
  28322. SckeArgs args[1];
  28323. #endif
  28324. WOLFSSL_START(WC_FUNC_CLIENT_KEY_EXCHANGE_SEND);
  28325. WOLFSSL_ENTER("SendClientKeyExchange");
  28326. #ifdef OPENSSL_EXTRA
  28327. ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
  28328. ssl->cbmode = SSL_CB_MODE_WRITE;
  28329. if (ssl->CBIS != NULL)
  28330. ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, WOLFSSL_SUCCESS);
  28331. #endif
  28332. #ifdef WOLFSSL_ASYNC_IO
  28333. if (ssl->async == NULL) {
  28334. ssl->async = (struct WOLFSSL_ASYNC*)
  28335. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  28336. DYNAMIC_TYPE_ASYNC);
  28337. if (ssl->async == NULL)
  28338. ERROR_OUT(MEMORY_E, exit_scke);
  28339. XMEMSET(ssl->async, 0, sizeof(struct WOLFSSL_ASYNC));
  28340. }
  28341. args = (SckeArgs*)ssl->async->args;
  28342. #ifdef WOLFSSL_ASYNC_CRYPT
  28343. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  28344. if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
  28345. /* Check for error */
  28346. if (ret < 0)
  28347. goto exit_scke;
  28348. }
  28349. else
  28350. #endif
  28351. if (ssl->options.buildingMsg) {
  28352. /* Continue building the message */
  28353. }
  28354. else
  28355. #endif
  28356. {
  28357. /* Reset state */
  28358. ret = 0;
  28359. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  28360. XMEMSET(args, 0, sizeof(SckeArgs));
  28361. /* Set this in case CheckAvailableSize returns a WANT_WRITE so that state
  28362. * is not advanced yet */
  28363. ssl->options.buildingMsg = 1;
  28364. #ifdef WOLFSSL_ASYNC_IO
  28365. ssl->async->freeArgs = FreeSckeArgs;
  28366. #endif
  28367. }
  28368. switch(ssl->options.asyncState)
  28369. {
  28370. case TLS_ASYNC_BEGIN:
  28371. {
  28372. switch (ssl->specs.kea) {
  28373. #ifndef NO_RSA
  28374. case rsa_kea:
  28375. if (ssl->peerRsaKey == NULL ||
  28376. ssl->peerRsaKeyPresent == 0) {
  28377. ERROR_OUT(NO_PEER_KEY, exit_scke);
  28378. }
  28379. break;
  28380. #endif
  28381. #ifndef NO_DH
  28382. case diffie_hellman_kea:
  28383. if (ssl->buffers.serverDH_P.buffer == NULL ||
  28384. ssl->buffers.serverDH_G.buffer == NULL ||
  28385. ssl->buffers.serverDH_Pub.buffer == NULL) {
  28386. ERROR_OUT(NO_PEER_KEY, exit_scke);
  28387. }
  28388. break;
  28389. #endif /* NO_DH */
  28390. #ifndef NO_PSK
  28391. case psk_kea:
  28392. /* sanity check that PSK client callback has been set */
  28393. if (ssl->options.client_psk_cb == NULL) {
  28394. WOLFSSL_MSG("No client PSK callback set");
  28395. ERROR_OUT(PSK_KEY_ERROR, exit_scke);
  28396. }
  28397. break;
  28398. #endif /* NO_PSK */
  28399. #if !defined(NO_DH) && !defined(NO_PSK)
  28400. case dhe_psk_kea:
  28401. if (ssl->buffers.serverDH_P.buffer == NULL ||
  28402. ssl->buffers.serverDH_G.buffer == NULL ||
  28403. ssl->buffers.serverDH_Pub.buffer == NULL) {
  28404. ERROR_OUT(NO_PEER_KEY, exit_scke);
  28405. }
  28406. /* sanity check that PSK client callback has been set */
  28407. if (ssl->options.client_psk_cb == NULL) {
  28408. WOLFSSL_MSG("No client PSK callback set");
  28409. ERROR_OUT(PSK_KEY_ERROR, exit_scke);
  28410. }
  28411. break;
  28412. #endif /* !NO_DH && !NO_PSK */
  28413. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  28414. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  28415. case ecdhe_psk_kea:
  28416. /* sanity check that PSK client callback has been set */
  28417. if (ssl->options.client_psk_cb == NULL) {
  28418. WOLFSSL_MSG("No client PSK callback set");
  28419. ERROR_OUT(PSK_KEY_ERROR, exit_scke);
  28420. }
  28421. #ifdef HAVE_CURVE25519
  28422. if (ssl->peerX25519KeyPresent) {
  28423. /* Check client ECC public key */
  28424. if (!ssl->peerX25519Key || !ssl->peerX25519Key->dp) {
  28425. ERROR_OUT(NO_PEER_KEY, exit_scke);
  28426. }
  28427. #ifdef HAVE_PK_CALLBACKS
  28428. /* if callback then use it for shared secret */
  28429. if (ssl->ctx->X25519SharedSecretCb != NULL) {
  28430. break;
  28431. }
  28432. #endif
  28433. /* create private key */
  28434. ssl->hsType = DYNAMIC_TYPE_CURVE25519;
  28435. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  28436. if (ret != 0) {
  28437. goto exit_scke;
  28438. }
  28439. ret = X25519MakeKey(ssl, (curve25519_key*)ssl->hsKey,
  28440. ssl->peerX25519Key);
  28441. break;
  28442. }
  28443. #endif
  28444. #ifdef HAVE_CURVE448
  28445. if (ssl->peerX448KeyPresent) {
  28446. /* Check client ECC public key */
  28447. if (!ssl->peerX448Key) {
  28448. ERROR_OUT(NO_PEER_KEY, exit_scke);
  28449. }
  28450. #ifdef HAVE_PK_CALLBACKS
  28451. /* if callback then use it for shared secret */
  28452. if (ssl->ctx->X448SharedSecretCb != NULL) {
  28453. break;
  28454. }
  28455. #endif
  28456. /* create private key */
  28457. ssl->hsType = DYNAMIC_TYPE_CURVE448;
  28458. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  28459. if (ret != 0) {
  28460. goto exit_scke;
  28461. }
  28462. ret = X448MakeKey(ssl, (curve448_key*)ssl->hsKey,
  28463. ssl->peerX448Key);
  28464. break;
  28465. }
  28466. #endif
  28467. /* Check client ECC public key */
  28468. if (!ssl->peerEccKey || !ssl->peerEccKeyPresent ||
  28469. !ssl->peerEccKey->dp) {
  28470. ERROR_OUT(NO_PEER_KEY, exit_scke);
  28471. }
  28472. #ifdef HAVE_PK_CALLBACKS
  28473. /* if callback then use it for shared secret */
  28474. if (ssl->ctx->EccSharedSecretCb != NULL) {
  28475. break;
  28476. }
  28477. #endif
  28478. /* create ephemeral private key */
  28479. ssl->hsType = DYNAMIC_TYPE_ECC;
  28480. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  28481. if (ret != 0) {
  28482. goto exit_scke;
  28483. }
  28484. ret = EccMakeKey(ssl, (ecc_key*)ssl->hsKey, ssl->peerEccKey);
  28485. break;
  28486. #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
  28487. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  28488. defined(HAVE_CURVE448)
  28489. case ecc_diffie_hellman_kea:
  28490. {
  28491. #ifdef HAVE_ECC
  28492. ecc_key* peerKey;
  28493. #endif
  28494. #ifdef HAVE_PK_CALLBACKS
  28495. /* if callback then use it for shared secret */
  28496. #ifdef HAVE_CURVE25519
  28497. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  28498. if (ssl->ctx->X25519SharedSecretCb != NULL)
  28499. break;
  28500. }
  28501. else
  28502. #endif
  28503. #ifdef HAVE_CURVE448
  28504. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  28505. if (ssl->ctx->X448SharedSecretCb != NULL)
  28506. break;
  28507. }
  28508. else
  28509. #endif
  28510. #ifdef HAVE_ECC
  28511. if (ssl->ctx->EccSharedSecretCb != NULL) {
  28512. break;
  28513. }
  28514. else
  28515. #endif
  28516. {
  28517. }
  28518. #endif /* HAVE_PK_CALLBACKS */
  28519. #ifdef HAVE_CURVE25519
  28520. if (ssl->peerX25519KeyPresent) {
  28521. if (!ssl->peerX25519Key || !ssl->peerX25519Key->dp) {
  28522. ERROR_OUT(NO_PEER_KEY, exit_scke);
  28523. }
  28524. /* create private key */
  28525. ssl->hsType = DYNAMIC_TYPE_CURVE25519;
  28526. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  28527. if (ret != 0) {
  28528. goto exit_scke;
  28529. }
  28530. ret = X25519MakeKey(ssl, (curve25519_key*)ssl->hsKey,
  28531. ssl->peerX25519Key);
  28532. break;
  28533. }
  28534. #endif
  28535. #ifdef HAVE_CURVE448
  28536. if (ssl->peerX448KeyPresent) {
  28537. if (!ssl->peerX448Key) {
  28538. ERROR_OUT(NO_PEER_KEY, exit_scke);
  28539. }
  28540. /* create private key */
  28541. ssl->hsType = DYNAMIC_TYPE_CURVE448;
  28542. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  28543. if (ret != 0) {
  28544. goto exit_scke;
  28545. }
  28546. ret = X448MakeKey(ssl, (curve448_key*)ssl->hsKey,
  28547. ssl->peerX448Key);
  28548. break;
  28549. }
  28550. #endif
  28551. #ifdef HAVE_ECC
  28552. if (ssl->specs.static_ecdh) {
  28553. /* Note: EccDsa is really fixed Ecc key here */
  28554. if (!ssl->peerEccDsaKey || !ssl->peerEccDsaKeyPresent) {
  28555. ERROR_OUT(NO_PEER_KEY, exit_scke);
  28556. }
  28557. peerKey = ssl->peerEccDsaKey;
  28558. }
  28559. else {
  28560. if (!ssl->peerEccKey || !ssl->peerEccKeyPresent) {
  28561. ERROR_OUT(NO_PEER_KEY, exit_scke);
  28562. }
  28563. peerKey = ssl->peerEccKey;
  28564. }
  28565. if (peerKey == NULL) {
  28566. ERROR_OUT(NO_PEER_KEY, exit_scke);
  28567. }
  28568. /* create ephemeral private key */
  28569. ssl->hsType = DYNAMIC_TYPE_ECC;
  28570. ret = AllocKey(ssl, (int)ssl->hsType, &ssl->hsKey);
  28571. if (ret != 0) {
  28572. goto exit_scke;
  28573. }
  28574. ret = EccMakeKey(ssl, (ecc_key*)ssl->hsKey, peerKey);
  28575. #endif /* HAVE_ECC */
  28576. break;
  28577. }
  28578. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  28579. default:
  28580. ret = BAD_KEA_TYPE_E;
  28581. } /* switch(ssl->specs.kea) */
  28582. /* Check for error */
  28583. if (ret != 0) {
  28584. goto exit_scke;
  28585. }
  28586. /* Advance state and proceed */
  28587. ssl->options.asyncState = TLS_ASYNC_BUILD;
  28588. } /* case TLS_ASYNC_BEGIN */
  28589. FALL_THROUGH;
  28590. case TLS_ASYNC_BUILD:
  28591. {
  28592. args->encSz = MAX_ENCRYPT_SZ;
  28593. args->encSecret = (byte*)XMALLOC(MAX_ENCRYPT_SZ, ssl->heap,
  28594. DYNAMIC_TYPE_SECRET);
  28595. if (args->encSecret == NULL) {
  28596. ERROR_OUT(MEMORY_E, exit_scke);
  28597. }
  28598. if (ssl->arrays->preMasterSecret == NULL) {
  28599. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  28600. ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN,
  28601. ssl->heap, DYNAMIC_TYPE_SECRET);
  28602. if (ssl->arrays->preMasterSecret == NULL) {
  28603. ERROR_OUT(MEMORY_E, exit_scke);
  28604. }
  28605. XMEMSET(ssl->arrays->preMasterSecret, 0, ENCRYPT_LEN);
  28606. }
  28607. switch(ssl->specs.kea)
  28608. {
  28609. #ifndef NO_RSA
  28610. case rsa_kea:
  28611. {
  28612. #ifdef HAVE_PK_CALLBACKS
  28613. if (ssl->ctx->GenPreMasterCb) {
  28614. void* ctx = wolfSSL_GetGenPreMasterCtx(ssl);
  28615. ret = ssl->ctx->GenPreMasterCb(ssl,
  28616. ssl->arrays->preMasterSecret, ENCRYPT_LEN, ctx);
  28617. if (ret != 0 &&
  28618. ret != WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE)) {
  28619. goto exit_scke;
  28620. }
  28621. }
  28622. if (!ssl->ctx->GenPreMasterCb ||
  28623. ret == WC_NO_ERR_TRACE(PROTOCOLCB_UNAVAILABLE))
  28624. #endif
  28625. {
  28626. /* build PreMasterSecret with RNG data */
  28627. ret = wc_RNG_GenerateBlock(ssl->rng,
  28628. &ssl->arrays->preMasterSecret[VERSION_SZ],
  28629. SECRET_LEN - VERSION_SZ);
  28630. if (ret != 0) {
  28631. goto exit_scke;
  28632. }
  28633. ssl->arrays->preMasterSecret[0] = ssl->chVersion.major;
  28634. ssl->arrays->preMasterSecret[1] = ssl->chVersion.minor;
  28635. ssl->arrays->preMasterSz = SECRET_LEN;
  28636. }
  28637. break;
  28638. }
  28639. #endif /* !NO_RSA */
  28640. #ifndef NO_DH
  28641. case diffie_hellman_kea:
  28642. {
  28643. ssl->buffers.sig.length = ENCRYPT_LEN;
  28644. ssl->buffers.sig.buffer = (byte*)XMALLOC(ENCRYPT_LEN,
  28645. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  28646. if (ssl->buffers.sig.buffer == NULL) {
  28647. ERROR_OUT(MEMORY_E, exit_scke);
  28648. }
  28649. ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
  28650. (void**)&ssl->buffers.serverDH_Key);
  28651. if (ret != 0) {
  28652. goto exit_scke;
  28653. }
  28654. #if defined(HAVE_FFDHE) && !defined(HAVE_PUBLIC_FFDHE)
  28655. if (ssl->namedGroup) {
  28656. ret = wc_DhSetNamedKey(ssl->buffers.serverDH_Key,
  28657. ssl->namedGroup);
  28658. if (ret != 0) {
  28659. goto exit_scke;
  28660. }
  28661. ssl->buffers.sig.length =
  28662. wc_DhGetNamedKeyMinSize(ssl->namedGroup);
  28663. }
  28664. else
  28665. #endif
  28666. #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \
  28667. !defined(WOLFSSL_OLD_PRIME_CHECK)
  28668. if (ssl->options.dhDoKeyTest &&
  28669. !ssl->options.dhKeyTested)
  28670. {
  28671. ret = wc_DhSetCheckKey(ssl->buffers.serverDH_Key,
  28672. ssl->buffers.serverDH_P.buffer,
  28673. ssl->buffers.serverDH_P.length,
  28674. ssl->buffers.serverDH_G.buffer,
  28675. ssl->buffers.serverDH_G.length,
  28676. NULL, 0, 0, ssl->rng);
  28677. if (ret != 0) {
  28678. goto exit_scke;
  28679. }
  28680. ssl->options.dhKeyTested = 1;
  28681. }
  28682. else
  28683. #endif
  28684. {
  28685. ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
  28686. ssl->buffers.serverDH_P.buffer,
  28687. ssl->buffers.serverDH_P.length,
  28688. ssl->buffers.serverDH_G.buffer,
  28689. ssl->buffers.serverDH_G.length);
  28690. if (ret != 0) {
  28691. goto exit_scke;
  28692. }
  28693. }
  28694. /* for DH, encSecret is Yc, agree is pre-master */
  28695. ret = DhGenKeyPair(ssl, ssl->buffers.serverDH_Key,
  28696. ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
  28697. args->encSecret, &args->encSz);
  28698. /* set the max agree result size */
  28699. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  28700. break;
  28701. }
  28702. #endif /* !NO_DH */
  28703. #ifndef NO_PSK
  28704. case psk_kea:
  28705. {
  28706. byte* pms = ssl->arrays->preMasterSecret;
  28707. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  28708. ssl->arrays->server_hint, ssl->arrays->client_identity,
  28709. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  28710. if (ssl->arrays->psk_keySz == 0 ||
  28711. (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN &&
  28712. (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) {
  28713. ERROR_OUT(PSK_KEY_ERROR, exit_scke);
  28714. }
  28715. /* Ensure the buffer is null-terminated. */
  28716. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0';
  28717. args->encSz = (word32)XSTRLEN(ssl->arrays->client_identity);
  28718. if (args->encSz > MAX_PSK_ID_LEN) {
  28719. ERROR_OUT(CLIENT_ID_ERROR, exit_scke);
  28720. }
  28721. XMEMCPY(args->encSecret, ssl->arrays->client_identity,
  28722. args->encSz);
  28723. ssl->options.peerAuthGood = 1;
  28724. if ((int)ssl->arrays->psk_keySz > 0) {
  28725. /* CLIENT: Pre-shared Key for peer authentication. */
  28726. /* make psk pre master secret */
  28727. /* length of key + length 0s + length of key + key */
  28728. c16toa((word16)ssl->arrays->psk_keySz, pms);
  28729. pms += OPAQUE16_LEN;
  28730. XMEMSET(pms, 0, ssl->arrays->psk_keySz);
  28731. pms += ssl->arrays->psk_keySz;
  28732. c16toa((word16)ssl->arrays->psk_keySz, pms);
  28733. pms += OPAQUE16_LEN;
  28734. XMEMCPY(pms, ssl->arrays->psk_key,
  28735. ssl->arrays->psk_keySz);
  28736. ssl->arrays->preMasterSz = (ssl->arrays->psk_keySz * 2)
  28737. + (2 * OPAQUE16_LEN);
  28738. ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  28739. }
  28740. ssl->arrays->psk_keySz = 0; /* No further need */
  28741. break;
  28742. }
  28743. #endif /* !NO_PSK */
  28744. #if !defined(NO_DH) && !defined(NO_PSK)
  28745. case dhe_psk_kea:
  28746. {
  28747. word32 esSz = 0;
  28748. args->output = args->encSecret;
  28749. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  28750. ssl->arrays->server_hint, ssl->arrays->client_identity,
  28751. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  28752. if (ssl->arrays->psk_keySz == 0 ||
  28753. (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN &&
  28754. (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) {
  28755. ERROR_OUT(PSK_KEY_ERROR, exit_scke);
  28756. }
  28757. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0'; /* null term */
  28758. esSz = (word32)XSTRLEN(ssl->arrays->client_identity);
  28759. if (esSz > MAX_PSK_ID_LEN) {
  28760. ERROR_OUT(CLIENT_ID_ERROR, exit_scke);
  28761. }
  28762. /* CLIENT: Pre-shared Key for peer authentication. */
  28763. ssl->options.peerAuthGood = 1;
  28764. ssl->buffers.sig.length = ENCRYPT_LEN;
  28765. ssl->buffers.sig.buffer = (byte*)XMALLOC(ENCRYPT_LEN,
  28766. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  28767. if (ssl->buffers.sig.buffer == NULL) {
  28768. ERROR_OUT(MEMORY_E, exit_scke);
  28769. }
  28770. c16toa((word16)esSz, args->output);
  28771. args->output += OPAQUE16_LEN;
  28772. XMEMCPY(args->output, ssl->arrays->client_identity, esSz);
  28773. args->output += esSz;
  28774. args->length = args->encSz - esSz - OPAQUE16_LEN;
  28775. args->encSz = esSz + OPAQUE16_LEN;
  28776. ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
  28777. (void**)&ssl->buffers.serverDH_Key);
  28778. if (ret != 0) {
  28779. goto exit_scke;
  28780. }
  28781. #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \
  28782. !defined(WOLFSSL_OLD_PRIME_CHECK)
  28783. if (ssl->options.dhDoKeyTest &&
  28784. !ssl->options.dhKeyTested)
  28785. {
  28786. ret = wc_DhSetCheckKey(ssl->buffers.serverDH_Key,
  28787. ssl->buffers.serverDH_P.buffer,
  28788. ssl->buffers.serverDH_P.length,
  28789. ssl->buffers.serverDH_G.buffer,
  28790. ssl->buffers.serverDH_G.length,
  28791. NULL, 0, 0, ssl->rng);
  28792. if (ret != 0) {
  28793. goto exit_scke;
  28794. }
  28795. ssl->options.dhKeyTested = 1;
  28796. }
  28797. else
  28798. #endif
  28799. {
  28800. ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
  28801. ssl->buffers.serverDH_P.buffer,
  28802. ssl->buffers.serverDH_P.length,
  28803. ssl->buffers.serverDH_G.buffer,
  28804. ssl->buffers.serverDH_G.length);
  28805. if (ret != 0) {
  28806. goto exit_scke;
  28807. }
  28808. }
  28809. /* for DH, encSecret is Yc, agree is pre-master */
  28810. ret = DhGenKeyPair(ssl, ssl->buffers.serverDH_Key,
  28811. ssl->buffers.sig.buffer,
  28812. (word32*)&ssl->buffers.sig.length,
  28813. args->output + OPAQUE16_LEN, &args->length);
  28814. break;
  28815. }
  28816. #endif /* !NO_DH && !NO_PSK */
  28817. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  28818. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  28819. case ecdhe_psk_kea:
  28820. {
  28821. word32 esSz = 0;
  28822. args->output = args->encSecret;
  28823. /* Send PSK client identity */
  28824. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  28825. ssl->arrays->server_hint, ssl->arrays->client_identity,
  28826. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  28827. if (ssl->arrays->psk_keySz == 0 ||
  28828. (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN &&
  28829. (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) {
  28830. ERROR_OUT(PSK_KEY_ERROR, exit_scke);
  28831. }
  28832. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0'; /* null term */
  28833. esSz = (word32)XSTRLEN(ssl->arrays->client_identity);
  28834. if (esSz > MAX_PSK_ID_LEN) {
  28835. ERROR_OUT(CLIENT_ID_ERROR, exit_scke);
  28836. }
  28837. /* CLIENT: Pre-shared Key for peer authentication. */
  28838. ssl->options.peerAuthGood = 1;
  28839. /* place size and identity in output buffer sz:identity */
  28840. c16toa((word16)esSz, args->output);
  28841. args->output += OPAQUE16_LEN;
  28842. XMEMCPY(args->output, ssl->arrays->client_identity, esSz);
  28843. args->output += esSz;
  28844. args->encSz = esSz + OPAQUE16_LEN;
  28845. /* length is used for public key size */
  28846. args->length = MAX_ENCRYPT_SZ;
  28847. /* Create shared ECC key leaving room at the beginning
  28848. * of buffer for size of shared key. */
  28849. ssl->arrays->preMasterSz = ENCRYPT_LEN - OPAQUE16_LEN;
  28850. #ifdef HAVE_CURVE25519
  28851. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  28852. #ifdef HAVE_PK_CALLBACKS
  28853. /* if callback then use it for shared secret */
  28854. if (ssl->ctx->X25519SharedSecretCb != NULL) {
  28855. break;
  28856. }
  28857. #endif
  28858. ret = wc_curve25519_export_public_ex(
  28859. (curve25519_key*)ssl->hsKey,
  28860. args->output + OPAQUE8_LEN, &args->length,
  28861. EC25519_LITTLE_ENDIAN);
  28862. if (ret != 0) {
  28863. ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
  28864. }
  28865. break;
  28866. }
  28867. #endif
  28868. #ifdef HAVE_CURVE448
  28869. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  28870. #ifdef HAVE_PK_CALLBACKS
  28871. /* if callback then use it for shared secret */
  28872. if (ssl->ctx->X448SharedSecretCb != NULL) {
  28873. break;
  28874. }
  28875. #endif
  28876. ret = wc_curve448_export_public_ex(
  28877. (curve448_key*)ssl->hsKey,
  28878. args->output + OPAQUE8_LEN, &args->length,
  28879. EC448_LITTLE_ENDIAN);
  28880. if (ret != 0) {
  28881. ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
  28882. }
  28883. break;
  28884. }
  28885. #endif
  28886. #ifdef HAVE_PK_CALLBACKS
  28887. /* if callback then use it for shared secret */
  28888. if (ssl->ctx->EccSharedSecretCb != NULL) {
  28889. break;
  28890. }
  28891. #endif
  28892. /* Place ECC key in output buffer, leaving room for size */
  28893. PRIVATE_KEY_UNLOCK();
  28894. ret = wc_ecc_export_x963((ecc_key*)ssl->hsKey,
  28895. args->output + OPAQUE8_LEN, &args->length);
  28896. PRIVATE_KEY_LOCK();
  28897. if (ret != 0) {
  28898. ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
  28899. }
  28900. break;
  28901. }
  28902. #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
  28903. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  28904. defined(HAVE_CURVE448)
  28905. case ecc_diffie_hellman_kea:
  28906. {
  28907. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  28908. #ifdef HAVE_CURVE25519
  28909. if (ssl->hsType == DYNAMIC_TYPE_CURVE25519) {
  28910. #ifdef HAVE_PK_CALLBACKS
  28911. /* if callback then use it for shared secret */
  28912. if (ssl->ctx->X25519SharedSecretCb != NULL) {
  28913. break;
  28914. }
  28915. #endif
  28916. ret = wc_curve25519_export_public_ex(
  28917. (curve25519_key*)ssl->hsKey,
  28918. args->encSecret + OPAQUE8_LEN, &args->encSz,
  28919. EC25519_LITTLE_ENDIAN);
  28920. if (ret != 0) {
  28921. ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
  28922. }
  28923. break;
  28924. }
  28925. #endif
  28926. #ifdef HAVE_CURVE448
  28927. if (ssl->hsType == DYNAMIC_TYPE_CURVE448) {
  28928. #ifdef HAVE_PK_CALLBACKS
  28929. /* if callback then use it for shared secret */
  28930. if (ssl->ctx->X448SharedSecretCb != NULL) {
  28931. break;
  28932. }
  28933. #endif
  28934. ret = wc_curve448_export_public_ex(
  28935. (curve448_key*)ssl->hsKey,
  28936. args->encSecret + OPAQUE8_LEN, &args->encSz,
  28937. EC448_LITTLE_ENDIAN);
  28938. if (ret != 0) {
  28939. ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
  28940. }
  28941. break;
  28942. }
  28943. #endif
  28944. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  28945. #ifdef HAVE_PK_CALLBACKS
  28946. /* if callback then use it for shared secret */
  28947. if (ssl->ctx->EccSharedSecretCb != NULL) {
  28948. break;
  28949. }
  28950. #endif
  28951. /* Place ECC key in buffer, leaving room for size */
  28952. PRIVATE_KEY_UNLOCK();
  28953. ret = wc_ecc_export_x963((ecc_key*)ssl->hsKey,
  28954. args->encSecret + OPAQUE8_LEN, &args->encSz);
  28955. PRIVATE_KEY_LOCK();
  28956. if (ret != 0) {
  28957. ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
  28958. }
  28959. #endif /* HAVE_ECC */
  28960. break;
  28961. }
  28962. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  28963. default:
  28964. ret = BAD_KEA_TYPE_E;
  28965. } /* switch(ssl->specs.kea) */
  28966. /* Check for error */
  28967. if (ret != 0) {
  28968. goto exit_scke;
  28969. }
  28970. /* Advance state and proceed */
  28971. ssl->options.asyncState = TLS_ASYNC_DO;
  28972. } /* case TLS_ASYNC_BUILD */
  28973. FALL_THROUGH;
  28974. case TLS_ASYNC_DO:
  28975. {
  28976. switch(ssl->specs.kea)
  28977. {
  28978. #ifndef NO_RSA
  28979. case rsa_kea:
  28980. {
  28981. ret = RsaEnc(ssl,
  28982. ssl->arrays->preMasterSecret, SECRET_LEN,
  28983. args->encSecret, &args->encSz,
  28984. ssl->peerRsaKey,
  28985. #if defined(HAVE_PK_CALLBACKS)
  28986. &ssl->buffers.peerRsaKey
  28987. #else
  28988. NULL
  28989. #endif
  28990. );
  28991. break;
  28992. }
  28993. #endif /* !NO_RSA */
  28994. #ifndef NO_DH
  28995. case diffie_hellman_kea:
  28996. {
  28997. ret = DhAgree(ssl, ssl->buffers.serverDH_Key,
  28998. ssl->buffers.sig.buffer, ssl->buffers.sig.length,
  28999. ssl->buffers.serverDH_Pub.buffer,
  29000. ssl->buffers.serverDH_Pub.length,
  29001. ssl->arrays->preMasterSecret,
  29002. &ssl->arrays->preMasterSz,
  29003. ssl->buffers.serverDH_P.buffer,
  29004. ssl->buffers.serverDH_P.length);
  29005. break;
  29006. }
  29007. #endif /* !NO_DH */
  29008. #ifndef NO_PSK
  29009. case psk_kea:
  29010. {
  29011. break;
  29012. }
  29013. #endif /* !NO_PSK */
  29014. #if !defined(NO_DH) && !defined(NO_PSK)
  29015. case dhe_psk_kea:
  29016. {
  29017. ret = DhAgree(ssl, ssl->buffers.serverDH_Key,
  29018. ssl->buffers.sig.buffer, ssl->buffers.sig.length,
  29019. ssl->buffers.serverDH_Pub.buffer,
  29020. ssl->buffers.serverDH_Pub.length,
  29021. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  29022. &ssl->arrays->preMasterSz,
  29023. ssl->buffers.serverDH_P.buffer,
  29024. ssl->buffers.serverDH_P.length);
  29025. break;
  29026. }
  29027. #endif /* !NO_DH && !NO_PSK */
  29028. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  29029. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  29030. case ecdhe_psk_kea:
  29031. {
  29032. #ifdef HAVE_CURVE25519
  29033. if (ssl->peerX25519KeyPresent) {
  29034. ret = X25519SharedSecret(ssl,
  29035. (curve25519_key*)ssl->hsKey, ssl->peerX25519Key,
  29036. args->output + OPAQUE8_LEN, &args->length,
  29037. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  29038. &ssl->arrays->preMasterSz,
  29039. WOLFSSL_CLIENT_END
  29040. );
  29041. if (!ssl->specs.static_ecdh
  29042. #ifdef WOLFSSL_ASYNC_CRYPT
  29043. && ret != WC_NO_ERR_TRACE(WC_PENDING_E)
  29044. #endif
  29045. ) {
  29046. FreeKey(ssl, DYNAMIC_TYPE_CURVE25519,
  29047. (void**)&ssl->peerX25519Key);
  29048. ssl->peerX25519KeyPresent = 0;
  29049. }
  29050. break;
  29051. }
  29052. #endif
  29053. #ifdef HAVE_CURVE448
  29054. if (ssl->peerX448KeyPresent) {
  29055. ret = X448SharedSecret(ssl,
  29056. (curve448_key*)ssl->hsKey, ssl->peerX448Key,
  29057. args->output + OPAQUE8_LEN, &args->length,
  29058. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  29059. &ssl->arrays->preMasterSz,
  29060. WOLFSSL_CLIENT_END
  29061. );
  29062. if (!ssl->specs.static_ecdh
  29063. #ifdef WOLFSSL_ASYNC_CRYPT
  29064. && ret != WC_NO_ERR_TRACE(WC_PENDING_E)
  29065. #endif
  29066. ) {
  29067. FreeKey(ssl, DYNAMIC_TYPE_CURVE448,
  29068. (void**)&ssl->peerX448Key);
  29069. ssl->peerX448KeyPresent = 0;
  29070. }
  29071. break;
  29072. }
  29073. #endif
  29074. ret = EccSharedSecret(ssl,
  29075. (ecc_key*)ssl->hsKey, ssl->peerEccKey,
  29076. args->output + OPAQUE8_LEN, &args->length,
  29077. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  29078. &ssl->arrays->preMasterSz,
  29079. WOLFSSL_CLIENT_END
  29080. );
  29081. #ifdef WOLFSSL_ASYNC_CRYPT
  29082. if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
  29083. #endif
  29084. {
  29085. FreeKey(ssl, DYNAMIC_TYPE_ECC,
  29086. (void**)&ssl->peerEccKey);
  29087. ssl->peerEccKeyPresent = 0;
  29088. }
  29089. break;
  29090. }
  29091. #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
  29092. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  29093. defined(HAVE_CURVE448)
  29094. case ecc_diffie_hellman_kea:
  29095. {
  29096. #ifdef HAVE_ECC
  29097. ecc_key* peerKey;
  29098. #endif
  29099. #ifdef HAVE_CURVE25519
  29100. if (ssl->peerX25519KeyPresent) {
  29101. ret = X25519SharedSecret(ssl,
  29102. (curve25519_key*)ssl->hsKey, ssl->peerX25519Key,
  29103. args->encSecret + OPAQUE8_LEN, &args->encSz,
  29104. ssl->arrays->preMasterSecret,
  29105. &ssl->arrays->preMasterSz,
  29106. WOLFSSL_CLIENT_END
  29107. );
  29108. if (!ssl->specs.static_ecdh
  29109. #ifdef WOLFSSL_ASYNC_CRYPT
  29110. && ret != WC_NO_ERR_TRACE(WC_PENDING_E)
  29111. #endif
  29112. ) {
  29113. FreeKey(ssl, DYNAMIC_TYPE_CURVE25519,
  29114. (void**)&ssl->peerX25519Key);
  29115. ssl->peerX25519KeyPresent = 0;
  29116. }
  29117. break;
  29118. }
  29119. #endif
  29120. #ifdef HAVE_CURVE448
  29121. if (ssl->peerX448KeyPresent) {
  29122. ret = X448SharedSecret(ssl,
  29123. (curve448_key*)ssl->hsKey, ssl->peerX448Key,
  29124. args->encSecret + OPAQUE8_LEN, &args->encSz,
  29125. ssl->arrays->preMasterSecret,
  29126. &ssl->arrays->preMasterSz,
  29127. WOLFSSL_CLIENT_END
  29128. );
  29129. if (!ssl->specs.static_ecdh
  29130. #ifdef WOLFSSL_ASYNC_CRYPT
  29131. && ret != WC_NO_ERR_TRACE(WC_PENDING_E)
  29132. #endif
  29133. ) {
  29134. FreeKey(ssl, DYNAMIC_TYPE_CURVE448,
  29135. (void**)&ssl->peerX448Key);
  29136. ssl->peerX448KeyPresent = 0;
  29137. }
  29138. break;
  29139. }
  29140. #endif
  29141. #ifdef HAVE_ECC
  29142. peerKey = (ssl->specs.static_ecdh) ?
  29143. ssl->peerEccDsaKey : ssl->peerEccKey;
  29144. ret = EccSharedSecret(ssl,
  29145. (ecc_key*)ssl->hsKey, peerKey,
  29146. args->encSecret + OPAQUE8_LEN, &args->encSz,
  29147. ssl->arrays->preMasterSecret,
  29148. &ssl->arrays->preMasterSz,
  29149. WOLFSSL_CLIENT_END);
  29150. if (!ssl->specs.static_ecdh
  29151. #ifdef WOLFSSL_ASYNC_CRYPT
  29152. && ret != WC_NO_ERR_TRACE(WC_PENDING_E)
  29153. #endif
  29154. && !ssl->options.keepResources) {
  29155. FreeKey(ssl, DYNAMIC_TYPE_ECC,
  29156. (void**)&ssl->peerEccKey);
  29157. ssl->peerEccKeyPresent = 0;
  29158. }
  29159. #endif
  29160. break;
  29161. }
  29162. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  29163. default:
  29164. ret = BAD_KEA_TYPE_E;
  29165. } /* switch(ssl->specs.kea) */
  29166. /* Check for error */
  29167. if (ret != 0) {
  29168. goto exit_scke;
  29169. }
  29170. /* Advance state and proceed */
  29171. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  29172. } /* case TLS_ASYNC_DO */
  29173. FALL_THROUGH;
  29174. case TLS_ASYNC_VERIFY:
  29175. {
  29176. switch(ssl->specs.kea)
  29177. {
  29178. #ifndef NO_RSA
  29179. case rsa_kea:
  29180. {
  29181. break;
  29182. }
  29183. #endif /* !NO_RSA */
  29184. #ifndef NO_DH
  29185. case diffie_hellman_kea:
  29186. {
  29187. break;
  29188. }
  29189. #endif /* !NO_DH */
  29190. #ifndef NO_PSK
  29191. case psk_kea:
  29192. {
  29193. break;
  29194. }
  29195. #endif /* !NO_PSK */
  29196. #if !defined(NO_DH) && !defined(NO_PSK)
  29197. case dhe_psk_kea:
  29198. {
  29199. byte* pms = ssl->arrays->preMasterSecret;
  29200. /* validate args */
  29201. if (args->output == NULL || args->length == 0) {
  29202. ERROR_OUT(BAD_FUNC_ARG, exit_scke);
  29203. }
  29204. c16toa((word16)args->length, args->output);
  29205. args->encSz += args->length + OPAQUE16_LEN;
  29206. c16toa((word16)ssl->arrays->preMasterSz, pms);
  29207. ssl->arrays->preMasterSz += OPAQUE16_LEN;
  29208. pms += ssl->arrays->preMasterSz;
  29209. /* make psk pre master secret */
  29210. if ((int)ssl->arrays->psk_keySz > 0) {
  29211. /* length of key + length 0s + length of key + key */
  29212. c16toa((word16)ssl->arrays->psk_keySz, pms);
  29213. pms += OPAQUE16_LEN;
  29214. XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  29215. ssl->arrays->preMasterSz +=
  29216. ssl->arrays->psk_keySz + OPAQUE16_LEN;
  29217. ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  29218. }
  29219. ssl->arrays->psk_keySz = 0; /* No further need */
  29220. break;
  29221. }
  29222. #endif /* !NO_DH && !NO_PSK */
  29223. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  29224. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  29225. case ecdhe_psk_kea:
  29226. {
  29227. byte* pms = ssl->arrays->preMasterSecret;
  29228. /* validate args */
  29229. if (args->output == NULL || args->length > ENCRYPT_LEN) {
  29230. ERROR_OUT(BAD_FUNC_ARG, exit_scke);
  29231. }
  29232. /* place size of public key in output buffer */
  29233. *args->output = (byte)args->length;
  29234. args->encSz += args->length + OPAQUE8_LEN;
  29235. /* Create pre master secret is the concatenation of
  29236. * eccSize + eccSharedKey + pskSize + pskKey */
  29237. c16toa((word16)ssl->arrays->preMasterSz, pms);
  29238. ssl->arrays->preMasterSz += OPAQUE16_LEN;
  29239. pms += ssl->arrays->preMasterSz;
  29240. if ((int)ssl->arrays->psk_keySz > 0) {
  29241. c16toa((word16)ssl->arrays->psk_keySz, pms);
  29242. pms += OPAQUE16_LEN;
  29243. XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  29244. ssl->arrays->preMasterSz += ssl->arrays->psk_keySz + OPAQUE16_LEN;
  29245. ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  29246. }
  29247. ssl->arrays->psk_keySz = 0; /* No further need */
  29248. break;
  29249. }
  29250. #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
  29251. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  29252. defined(HAVE_CURVE448)
  29253. case ecc_diffie_hellman_kea:
  29254. {
  29255. if (args->encSecret == NULL) {
  29256. ret = BAD_STATE_E;
  29257. goto exit_scke;
  29258. }
  29259. else {
  29260. /* place size of public key in buffer */
  29261. *args->encSecret = (byte)args->encSz;
  29262. args->encSz += OPAQUE8_LEN;
  29263. }
  29264. break;
  29265. }
  29266. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  29267. default:
  29268. ret = BAD_KEA_TYPE_E;
  29269. } /* switch(ssl->specs.kea) */
  29270. /* Check for error */
  29271. if (ret != 0) {
  29272. goto exit_scke;
  29273. }
  29274. /* Advance state and proceed */
  29275. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  29276. } /* case TLS_ASYNC_VERIFY */
  29277. FALL_THROUGH;
  29278. case TLS_ASYNC_FINALIZE:
  29279. {
  29280. word32 tlsSz = 0;
  29281. word32 idx = 0;
  29282. if (ssl->options.tls || ssl->specs.kea == diffie_hellman_kea) {
  29283. tlsSz = 2;
  29284. }
  29285. if (ssl->specs.kea == ecc_diffie_hellman_kea ||
  29286. ssl->specs.kea == dhe_psk_kea ||
  29287. ssl->specs.kea == ecdhe_psk_kea) { /* always off */
  29288. tlsSz = 0;
  29289. }
  29290. idx = HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  29291. args->sendSz = (int)(args->encSz + tlsSz + idx);
  29292. #ifdef WOLFSSL_DTLS
  29293. if (ssl->options.dtls) {
  29294. idx += DTLS_HANDSHAKE_EXTRA + DTLS_RECORD_EXTRA;
  29295. args->sendSz += DTLS_HANDSHAKE_EXTRA + DTLS_RECORD_EXTRA;
  29296. }
  29297. #endif
  29298. if (IsEncryptionOn(ssl, 1)) {
  29299. args->sendSz += MAX_MSG_EXTRA;
  29300. }
  29301. /* check for available size */
  29302. if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0)
  29303. goto exit_scke;
  29304. /* get output buffer */
  29305. args->output = GetOutputBuffer(ssl);
  29306. AddHeaders(args->output, args->encSz + tlsSz, client_key_exchange, ssl);
  29307. if (tlsSz) {
  29308. c16toa((word16)args->encSz, &args->output[idx]);
  29309. idx += OPAQUE16_LEN;
  29310. }
  29311. XMEMCPY(args->output + idx, args->encSecret, args->encSz);
  29312. idx += args->encSz;
  29313. if (IsEncryptionOn(ssl, 1)) {
  29314. int recordHeaderSz = RECORD_HEADER_SZ;
  29315. if (ssl->options.dtls)
  29316. recordHeaderSz += DTLS_RECORD_EXTRA;
  29317. args->inputSz = (int)idx - recordHeaderSz; /* buildmsg adds rechdr */
  29318. args->input = (byte*)XMALLOC((size_t)args->inputSz, ssl->heap,
  29319. DYNAMIC_TYPE_IN_BUFFER);
  29320. if (args->input == NULL) {
  29321. ERROR_OUT(MEMORY_E, exit_scke);
  29322. }
  29323. XMEMCPY(args->input, args->output + recordHeaderSz,
  29324. args->inputSz);
  29325. }
  29326. /* Advance state and proceed */
  29327. ssl->options.asyncState = TLS_ASYNC_END;
  29328. } /* case TLS_ASYNC_FINALIZE */
  29329. FALL_THROUGH;
  29330. case TLS_ASYNC_END:
  29331. {
  29332. if (IsEncryptionOn(ssl, 1)) {
  29333. #ifdef WOLFSSL_DTLS
  29334. if (IsDtlsNotSctpMode(ssl) &&
  29335. (ret = DtlsMsgPoolSave(ssl, args->input, args->inputSz, client_key_exchange)) != 0) {
  29336. goto exit_scke;
  29337. }
  29338. #endif
  29339. ret = BuildMessage(ssl, args->output, args->sendSz,
  29340. args->input, args->inputSz, handshake, 1, 0, 0, CUR_ORDER);
  29341. XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  29342. args->input = NULL; /* make sure its not double free'd on cleanup */
  29343. if (ret >= 0) {
  29344. args->sendSz = ret;
  29345. ret = 0;
  29346. }
  29347. }
  29348. else {
  29349. #ifdef WOLFSSL_DTLS
  29350. if (IsDtlsNotSctpMode(ssl)) {
  29351. if ((ret = DtlsMsgPoolSave(ssl, args->output, args->sendSz, client_key_exchange)) != 0) {
  29352. goto exit_scke;
  29353. }
  29354. }
  29355. if (ssl->options.dtls)
  29356. DtlsSEQIncrement(ssl, CUR_ORDER);
  29357. #endif
  29358. ret = HashOutput(ssl, args->output, args->sendSz, 0);
  29359. }
  29360. if (ret != 0) {
  29361. goto exit_scke;
  29362. }
  29363. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  29364. if (ssl->hsInfoOn)
  29365. AddPacketName(ssl, "ClientKeyExchange");
  29366. if (ssl->toInfoOn) {
  29367. ret = AddPacketInfo(ssl, "ClientKeyExchange", handshake,
  29368. args->output, args->sendSz, WRITE_PROTO, 0, ssl->heap);
  29369. if (ret != 0) {
  29370. goto exit_scke;
  29371. }
  29372. }
  29373. #endif
  29374. ssl->buffers.outputBuffer.length += (word32)args->sendSz;
  29375. if (!ssl->options.groupMessages) {
  29376. ret = SendBuffered(ssl);
  29377. }
  29378. if (ret == 0 || ret == WC_NO_ERR_TRACE(WANT_WRITE)) {
  29379. int tmpRet = MakeMasterSecret(ssl);
  29380. if (tmpRet != 0) {
  29381. ret = tmpRet; /* save WANT_WRITE unless more serious */
  29382. }
  29383. ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
  29384. ssl->options.buildingMsg = 0;
  29385. }
  29386. #if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
  29387. if (ssl->keyLogCb != NULL) {
  29388. int secretSz = SECRET_LEN;
  29389. ret = ssl->keyLogCb(ssl, ssl->arrays->masterSecret, &secretSz,
  29390. NULL);
  29391. if (ret != 0 || secretSz != SECRET_LEN)
  29392. return SESSION_SECRET_CB_E;
  29393. }
  29394. #endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */
  29395. break;
  29396. }
  29397. default:
  29398. ret = INPUT_CASE_ERROR;
  29399. } /* switch(ssl->options.asyncState) */
  29400. exit_scke:
  29401. WOLFSSL_LEAVE("SendClientKeyExchange", ret);
  29402. WOLFSSL_END(WC_FUNC_CLIENT_KEY_EXCHANGE_SEND);
  29403. #ifdef WOLFSSL_ASYNC_IO
  29404. /* Handle async operation */
  29405. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E) ||
  29406. ret == WC_NO_ERR_TRACE(WANT_WRITE))
  29407. {
  29408. if (ssl->options.buildingMsg)
  29409. return ret;
  29410. /* If we have completed all states then we will not enter this function
  29411. * again. We need to do clean up now. */
  29412. }
  29413. #endif
  29414. /* No further need for PMS */
  29415. if (ssl->arrays->preMasterSecret != NULL) {
  29416. ForceZero(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  29417. }
  29418. ssl->arrays->preMasterSz = 0;
  29419. /* Final cleanup */
  29420. #ifdef WOLFSSL_ASYNC_IO
  29421. /* Cleanup async */
  29422. FreeAsyncCtx(ssl, 0);
  29423. #else
  29424. FreeSckeArgs(ssl, args);
  29425. #endif
  29426. FreeKeyExchange(ssl);
  29427. if (ret != 0) {
  29428. WOLFSSL_ERROR_VERBOSE(ret);
  29429. }
  29430. return ret;
  29431. }
  29432. #endif /* !WOLFSSL_NO_TLS12 */
  29433. #ifndef NO_CERTS
  29434. #ifndef WOLFSSL_NO_TLS12
  29435. #ifndef WOLFSSL_NO_CLIENT_AUTH
  29436. typedef struct ScvArgs {
  29437. byte* output; /* not allocated */
  29438. #ifndef NO_RSA
  29439. byte* verifySig;
  29440. #endif
  29441. byte* verify; /* not allocated */
  29442. byte* input;
  29443. word32 idx;
  29444. word32 extraSz;
  29445. word32 sigSz;
  29446. int sendSz;
  29447. int inputSz;
  29448. word32 length;
  29449. byte sigAlgo;
  29450. } ScvArgs;
  29451. static void FreeScvArgs(WOLFSSL* ssl, void* pArgs)
  29452. {
  29453. ScvArgs* args = (ScvArgs*)pArgs;
  29454. (void)ssl;
  29455. #ifndef NO_RSA
  29456. XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  29457. args->verifySig = NULL;
  29458. #endif
  29459. XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  29460. args->input = NULL;
  29461. }
  29462. /* handle generation of certificate_verify (15) */
  29463. int SendCertificateVerify(WOLFSSL* ssl)
  29464. {
  29465. int ret = 0;
  29466. #ifdef WOLFSSL_ASYNC_IO
  29467. ScvArgs* args = NULL;
  29468. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  29469. #else
  29470. ScvArgs args[1];
  29471. #endif
  29472. WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_SEND);
  29473. WOLFSSL_ENTER("SendCertificateVerify");
  29474. #ifdef WOLFSSL_BLIND_PRIVATE_KEY
  29475. wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask);
  29476. #endif
  29477. #ifdef WOLFSSL_ASYNC_IO
  29478. if (ssl->async == NULL) {
  29479. ssl->async = (struct WOLFSSL_ASYNC*)
  29480. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  29481. DYNAMIC_TYPE_ASYNC);
  29482. if (ssl->async == NULL)
  29483. ERROR_OUT(MEMORY_E, exit_scv);
  29484. XMEMSET(ssl->async, 0, sizeof(struct WOLFSSL_ASYNC));
  29485. }
  29486. args = (ScvArgs*)ssl->async->args;
  29487. #ifdef WOLFSSL_ASYNC_CRYPT
  29488. /* BuildMessage does its own Pop */
  29489. if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E) ||
  29490. ssl->options.asyncState != TLS_ASYNC_END)
  29491. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  29492. if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
  29493. /* Check for error */
  29494. if (ret < 0)
  29495. goto exit_scv;
  29496. }
  29497. else
  29498. #endif
  29499. if (ssl->options.buildingMsg) {
  29500. /* We should be in the sending state. */
  29501. if (ssl->options.asyncState != TLS_ASYNC_END) {
  29502. ret = BAD_STATE_E;
  29503. goto exit_scv;
  29504. }
  29505. }
  29506. else
  29507. #endif
  29508. {
  29509. /* Reset state */
  29510. ret = 0;
  29511. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  29512. XMEMSET(args, 0, sizeof(ScvArgs));
  29513. #ifdef WOLFSSL_ASYNC_IO
  29514. ssl->async->freeArgs = FreeScvArgs;
  29515. #endif
  29516. }
  29517. switch(ssl->options.asyncState)
  29518. {
  29519. case TLS_ASYNC_BEGIN:
  29520. {
  29521. if (ssl->options.sendVerify == SEND_BLANK_CERT) {
  29522. #ifdef WOLFSSL_BLIND_PRIVATE_KEY
  29523. wolfssl_priv_der_unblind(ssl->buffers.key,
  29524. ssl->buffers.keyMask);
  29525. #endif
  29526. return 0; /* sent blank cert, can't verify */
  29527. }
  29528. args->sendSz = MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA;
  29529. if (IsEncryptionOn(ssl, 1)) {
  29530. args->sendSz += MAX_MSG_EXTRA;
  29531. }
  29532. /* Use tmp buffer */
  29533. args->input = (byte*)XMALLOC((size_t)args->sendSz,
  29534. ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  29535. if (args->input == NULL)
  29536. ERROR_OUT(MEMORY_E, exit_scv);
  29537. args->output = args->input;
  29538. /* Advance state and proceed */
  29539. ssl->options.asyncState = TLS_ASYNC_BUILD;
  29540. } /* case TLS_ASYNC_BEGIN */
  29541. FALL_THROUGH;
  29542. case TLS_ASYNC_BUILD:
  29543. {
  29544. ret = BuildCertHashes(ssl, &ssl->hsHashes->certHashes);
  29545. if (ret != 0) {
  29546. goto exit_scv;
  29547. }
  29548. if (ssl->buffers.key == NULL) {
  29549. #ifdef HAVE_PK_CALLBACKS
  29550. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
  29551. args->length = (word16)GetPrivateKeySigSize(ssl);
  29552. else
  29553. #endif
  29554. ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
  29555. }
  29556. else {
  29557. /* Decode private key. */
  29558. ret = DecodePrivateKey(ssl, &args->length);
  29559. if (ret != 0) {
  29560. goto exit_scv;
  29561. }
  29562. }
  29563. if (args->length == 0) {
  29564. ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
  29565. }
  29566. /* idx is used to track verify pointer offset to output */
  29567. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  29568. args->verify = &args->output[RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ];
  29569. args->extraSz = 0; /* tls 1.2 hash/sig */
  29570. /* build encoded signature buffer */
  29571. ssl->buffers.sig.length = MAX_ENCODED_SIG_SZ;
  29572. ssl->buffers.sig.buffer = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  29573. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  29574. if (ssl->buffers.sig.buffer == NULL) {
  29575. ERROR_OUT(MEMORY_E, exit_scv);
  29576. }
  29577. #ifdef WOLFSSL_DTLS
  29578. if (ssl->options.dtls) {
  29579. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  29580. args->verify += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  29581. }
  29582. #endif
  29583. if (!IsAtLeastTLSv1_2(ssl)) {
  29584. #ifndef NO_OLD_TLS
  29585. #ifndef NO_SHA
  29586. /* old tls default */
  29587. SetDigest(ssl, sha_mac);
  29588. #endif
  29589. #else
  29590. #ifndef NO_SHA256
  29591. /* new tls default */
  29592. SetDigest(ssl, sha256_mac);
  29593. #endif
  29594. #endif /* !NO_OLD_TLS */
  29595. }
  29596. else {
  29597. SetDigest(ssl, ssl->options.hashAlgo);
  29598. }
  29599. if (ssl->hsType == DYNAMIC_TYPE_RSA) {
  29600. #ifdef WC_RSA_PSS
  29601. if (IsAtLeastTLSv1_2(ssl) &&
  29602. (ssl->pssAlgo & (1 << ssl->options.hashAlgo))) {
  29603. args->sigAlgo = rsa_pss_sa_algo;
  29604. }
  29605. else
  29606. #endif
  29607. args->sigAlgo = rsa_sa_algo;
  29608. }
  29609. else if (ssl->hsType == DYNAMIC_TYPE_ECC)
  29610. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  29611. if (ssl->buffers.keyType == sm2_sa_algo) {
  29612. args->sigAlgo = sm2_sa_algo;
  29613. }
  29614. else
  29615. #endif
  29616. {
  29617. args->sigAlgo = ecc_dsa_sa_algo;
  29618. }
  29619. else if (ssl->hsType == DYNAMIC_TYPE_ED25519)
  29620. args->sigAlgo = ed25519_sa_algo;
  29621. else if (ssl->hsType == DYNAMIC_TYPE_ED448)
  29622. args->sigAlgo = ed448_sa_algo;
  29623. if (IsAtLeastTLSv1_2(ssl)) {
  29624. EncodeSigAlg(ssl->options.hashAlgo, args->sigAlgo,
  29625. args->verify);
  29626. args->extraSz = HASH_SIG_SIZE;
  29627. SetDigest(ssl, ssl->options.hashAlgo);
  29628. }
  29629. #ifndef NO_OLD_TLS
  29630. else {
  29631. /* if old TLS load MD5 and SHA hash as value to sign
  29632. * MD5 and SHA must be first two buffers in structure */
  29633. XMEMCPY(ssl->buffers.sig.buffer,
  29634. (byte*)&ssl->hsHashes->certHashes, FINISHED_SZ);
  29635. }
  29636. #endif
  29637. #ifndef NO_RSA
  29638. if (args->sigAlgo == rsa_sa_algo) {
  29639. ssl->buffers.sig.length = FINISHED_SZ;
  29640. args->sigSz = ENCRYPT_LEN;
  29641. if (IsAtLeastTLSv1_2(ssl)) {
  29642. ssl->buffers.sig.length = wc_EncodeSignature(
  29643. ssl->buffers.sig.buffer, ssl->buffers.digest.buffer,
  29644. ssl->buffers.digest.length,
  29645. TypeHash(ssl->options.hashAlgo));
  29646. }
  29647. /* prepend hdr */
  29648. c16toa((word16)args->length, args->verify + args->extraSz);
  29649. }
  29650. #ifdef WC_RSA_PSS
  29651. else if (args->sigAlgo == rsa_pss_sa_algo) {
  29652. XMEMCPY(ssl->buffers.sig.buffer, ssl->buffers.digest.buffer,
  29653. ssl->buffers.digest.length);
  29654. ssl->buffers.sig.length = ssl->buffers.digest.length;
  29655. args->sigSz = ENCRYPT_LEN;
  29656. /* prepend hdr */
  29657. c16toa((word16)args->length, args->verify + args->extraSz);
  29658. }
  29659. #endif
  29660. #endif /* !NO_RSA */
  29661. #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
  29662. if (args->sigAlgo == ed25519_sa_algo) {
  29663. ret = Ed25519CheckPubKey(ssl);
  29664. if (ret != 0)
  29665. goto exit_scv;
  29666. }
  29667. #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
  29668. #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
  29669. if (args->sigAlgo == ed448_sa_algo) {
  29670. ret = Ed448CheckPubKey(ssl);
  29671. if (ret != 0)
  29672. goto exit_scv;
  29673. }
  29674. #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
  29675. /* Advance state and proceed */
  29676. ssl->options.asyncState = TLS_ASYNC_DO;
  29677. } /* case TLS_ASYNC_BUILD */
  29678. FALL_THROUGH;
  29679. case TLS_ASYNC_DO:
  29680. {
  29681. #ifdef HAVE_ECC
  29682. if (ssl->hsType == DYNAMIC_TYPE_ECC) {
  29683. ecc_key* key = (ecc_key*)ssl->hsKey;
  29684. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  29685. if (args->sigAlgo == sm2_sa_algo) {
  29686. ret = Sm2wSm3Sign(ssl,
  29687. TLS12_SM2_SIG_ID, TLS12_SM2_SIG_ID_SZ,
  29688. ssl->hsHashes->messages, ssl->hsHashes->length,
  29689. ssl->buffers.sig.buffer,
  29690. (word32*)&ssl->buffers.sig.length,
  29691. key,
  29692. #ifdef HAVE_PK_CALLBACKS
  29693. ssl->buffers.key
  29694. #else
  29695. NULL
  29696. #endif
  29697. );
  29698. }
  29699. else
  29700. #endif
  29701. {
  29702. ret = EccSign(ssl,
  29703. ssl->buffers.digest.buffer, ssl->buffers.digest.length,
  29704. ssl->buffers.sig.buffer,
  29705. (word32*)&ssl->buffers.sig.length,
  29706. key,
  29707. #ifdef HAVE_PK_CALLBACKS
  29708. ssl->buffers.key
  29709. #else
  29710. NULL
  29711. #endif
  29712. );
  29713. }
  29714. }
  29715. #endif /* HAVE_ECC */
  29716. #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
  29717. if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
  29718. ed25519_key* key = (ed25519_key*)ssl->hsKey;
  29719. ret = Ed25519Sign(ssl,
  29720. ssl->hsHashes->messages, ssl->hsHashes->length,
  29721. ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
  29722. key,
  29723. #ifdef HAVE_PK_CALLBACKS
  29724. ssl->buffers.key
  29725. #else
  29726. NULL
  29727. #endif
  29728. );
  29729. }
  29730. #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
  29731. #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
  29732. if (ssl->hsType == DYNAMIC_TYPE_ED448) {
  29733. ed448_key* key = (ed448_key*)ssl->hsKey;
  29734. ret = Ed448Sign(ssl,
  29735. ssl->hsHashes->messages, ssl->hsHashes->length,
  29736. ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
  29737. key,
  29738. #ifdef HAVE_PK_CALLBACKS
  29739. ssl->buffers.key
  29740. #else
  29741. NULL
  29742. #endif
  29743. );
  29744. }
  29745. #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
  29746. #ifndef NO_RSA
  29747. if (ssl->hsType == DYNAMIC_TYPE_RSA) {
  29748. RsaKey* key = (RsaKey*)ssl->hsKey;
  29749. /* restore verify pointer */
  29750. args->verify = &args->output[args->idx];
  29751. ret = RsaSign(ssl,
  29752. ssl->buffers.sig.buffer, ssl->buffers.sig.length,
  29753. args->verify + args->extraSz + VERIFY_HEADER, &args->sigSz,
  29754. args->sigAlgo, ssl->options.hashAlgo, key,
  29755. ssl->buffers.key
  29756. );
  29757. }
  29758. #endif /* !NO_RSA */
  29759. /* Check for error */
  29760. if (ret != 0) {
  29761. goto exit_scv;
  29762. }
  29763. /* Advance state and proceed */
  29764. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  29765. } /* case TLS_ASYNC_DO */
  29766. FALL_THROUGH;
  29767. case TLS_ASYNC_VERIFY:
  29768. {
  29769. /* restore verify pointer */
  29770. args->verify = &args->output[args->idx];
  29771. switch (ssl->hsType) {
  29772. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  29773. #ifdef HAVE_ECC
  29774. case DYNAMIC_TYPE_ECC:
  29775. #ifdef WOLFSSL_CHECK_SIG_FAULTS
  29776. {
  29777. ecc_key* key = (ecc_key*)ssl->hsKey;
  29778. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  29779. if (ssl->buffers.keyType == sm2_sa_algo) {
  29780. ret = Sm3wSm2Verify(ssl,
  29781. TLS12_SM2_SIG_ID, TLS12_SM2_SIG_ID_SZ,
  29782. ssl->buffers.sig.buffer, ssl->buffers.sig.length,
  29783. ssl->buffers.digest.buffer,
  29784. ssl->buffers.digest.length, key,
  29785. #ifdef HAVE_PK_CALLBACKS
  29786. ssl->buffers.key
  29787. #else
  29788. NULL
  29789. #endif
  29790. );
  29791. }
  29792. else
  29793. #endif
  29794. {
  29795. ret = EccVerify(ssl,
  29796. ssl->buffers.sig.buffer, ssl->buffers.sig.length,
  29797. ssl->buffers.digest.buffer,
  29798. ssl->buffers.digest.length, key,
  29799. #ifdef HAVE_PK_CALLBACKS
  29800. ssl->buffers.key
  29801. #else
  29802. NULL
  29803. #endif
  29804. );
  29805. }
  29806. if (ret != 0) {
  29807. WOLFSSL_MSG("Failed to verify ECC signature");
  29808. goto exit_scv;
  29809. }
  29810. }
  29811. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  29812. FALL_THROUGH;
  29813. #endif
  29814. #endif /* WOLFSSL_CHECK_SIG_FAULTS */
  29815. #endif /* HAVE_ECC */
  29816. #ifdef HAVE_ED25519
  29817. case DYNAMIC_TYPE_ED25519:
  29818. #endif
  29819. #ifdef HAVE_ED448
  29820. case DYNAMIC_TYPE_ED448:
  29821. #endif
  29822. args->length = (word16)ssl->buffers.sig.length;
  29823. /* prepend hdr */
  29824. c16toa((word16)args->length, args->verify + args->extraSz);
  29825. XMEMCPY(args->verify + args->extraSz + VERIFY_HEADER,
  29826. ssl->buffers.sig.buffer, ssl->buffers.sig.length);
  29827. break;
  29828. #endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  29829. #ifndef NO_RSA
  29830. case DYNAMIC_TYPE_RSA:
  29831. {
  29832. RsaKey* key = (RsaKey*)ssl->hsKey;
  29833. if (args->verifySig == NULL) {
  29834. args->verifySig = (byte*)XMALLOC(args->sigSz, ssl->heap,
  29835. DYNAMIC_TYPE_SIGNATURE);
  29836. if (args->verifySig == NULL) {
  29837. ERROR_OUT(MEMORY_E, exit_scv);
  29838. }
  29839. XMEMCPY(args->verifySig, args->verify + args->extraSz +
  29840. VERIFY_HEADER, args->sigSz);
  29841. }
  29842. /* check for signature faults */
  29843. ret = VerifyRsaSign(ssl,
  29844. args->verifySig, args->sigSz,
  29845. ssl->buffers.sig.buffer, ssl->buffers.sig.length,
  29846. args->sigAlgo, ssl->options.hashAlgo, key,
  29847. ssl->buffers.key
  29848. );
  29849. /* free temporary buffer now */
  29850. if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) {
  29851. XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  29852. args->verifySig = NULL;
  29853. }
  29854. break;
  29855. }
  29856. #endif /* !NO_RSA */
  29857. default:
  29858. break;
  29859. }
  29860. /* Check for error */
  29861. if (ret != 0) {
  29862. goto exit_scv;
  29863. }
  29864. /* Advance state and proceed */
  29865. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  29866. } /* case TLS_ASYNC_VERIFY */
  29867. FALL_THROUGH;
  29868. case TLS_ASYNC_FINALIZE:
  29869. {
  29870. if (args->output == NULL) {
  29871. ERROR_OUT(BUFFER_ERROR, exit_scv);
  29872. }
  29873. AddHeaders(args->output, (word32)args->length + args->extraSz +
  29874. VERIFY_HEADER, certificate_verify, ssl);
  29875. /* Advance state and proceed */
  29876. ssl->options.asyncState = TLS_ASYNC_END;
  29877. } /* case TLS_ASYNC_FINALIZE */
  29878. FALL_THROUGH;
  29879. case TLS_ASYNC_END:
  29880. {
  29881. ret = SendHandshakeMsg(ssl, args->output,
  29882. (word32)args->length + args->extraSz + VERIFY_HEADER,
  29883. certificate_verify, "CertificateVerify");
  29884. if (ret != 0)
  29885. goto exit_scv;
  29886. break;
  29887. }
  29888. default:
  29889. ret = INPUT_CASE_ERROR;
  29890. } /* switch(ssl->options.asyncState) */
  29891. exit_scv:
  29892. #ifdef WOLFSSL_BLIND_PRIVATE_KEY
  29893. if (ret == 0) {
  29894. ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
  29895. &ssl->buffers.keyMask);
  29896. }
  29897. else {
  29898. wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask);
  29899. }
  29900. #endif
  29901. WOLFSSL_LEAVE("SendCertificateVerify", ret);
  29902. WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_SEND);
  29903. #ifdef WOLFSSL_ASYNC_IO
  29904. /* Handle async operation */
  29905. if (ret == WC_NO_ERR_TRACE(WANT_WRITE)
  29906. #ifdef WOLFSSL_ASYNC_CRYPT
  29907. || ret == WC_NO_ERR_TRACE(WC_PENDING_E)
  29908. #endif
  29909. )
  29910. return ret;
  29911. #endif /* WOLFSSL_ASYNC_IO */
  29912. /* Digest is not allocated, so do this to prevent free */
  29913. if(ssl->buffers.digest.buffer) {
  29914. if (!ssl->options.dontFreeDigest) {
  29915. /*This should not happen*/
  29916. XFREE(ssl->buffers.digest.buffer,
  29917. ssl->heap, DYNAMIC_TYPE_DIGEST);
  29918. }
  29919. }
  29920. ssl->buffers.digest.buffer = NULL;
  29921. ssl->buffers.digest.length = 0;
  29922. ssl->options.dontFreeDigest = 0;
  29923. /* Final cleanup */
  29924. #ifdef WOLFSSL_ASYNC_IO
  29925. /* Cleanup async */
  29926. FreeAsyncCtx(ssl, 0);
  29927. #else
  29928. FreeScvArgs(ssl, args);
  29929. #endif
  29930. FreeKeyExchange(ssl);
  29931. if (ret != 0) {
  29932. WOLFSSL_ERROR_VERBOSE(ret);
  29933. }
  29934. return ret;
  29935. }
  29936. #endif /* WOLFSSL_NO_CLIENT_AUTH */
  29937. #endif /* WOLFSSL_NO_TLS12 */
  29938. #endif /* NO_CERTS */
  29939. #ifdef HAVE_SESSION_TICKET
  29940. int SetTicket(WOLFSSL* ssl, const byte* ticket, word32 length)
  29941. {
  29942. if (!HaveUniqueSessionObj(ssl))
  29943. return MEMORY_ERROR;
  29944. /* Free old dynamic ticket if we already had one */
  29945. if (ssl->session->ticketLenAlloc > 0) {
  29946. XFREE(ssl->session->ticket, ssl->heap, DYNAMIC_TYPE_SESSION_TICK);
  29947. ssl->session->ticket = ssl->session->staticTicket;
  29948. ssl->session->ticketLenAlloc = 0;
  29949. }
  29950. if (length > sizeof(ssl->session->staticTicket)) {
  29951. byte* sessionTicket =
  29952. (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_SESSION_TICK);
  29953. if (sessionTicket == NULL)
  29954. return MEMORY_E;
  29955. ssl->session->ticket = sessionTicket;
  29956. ssl->session->ticketLenAlloc = (word16)length;
  29957. }
  29958. ssl->session->ticketLen = (word16)length;
  29959. if (length > 0) {
  29960. XMEMCPY(ssl->session->ticket, ticket, length);
  29961. if (ssl->session_ticket_cb != NULL) {
  29962. ssl->session_ticket_cb(ssl,
  29963. ssl->session->ticket, ssl->session->ticketLen,
  29964. ssl->session_ticket_ctx);
  29965. }
  29966. /* Create a fake sessionID based on the ticket, this will
  29967. * supersede the existing session cache info. */
  29968. ssl->options.haveSessionId = 1;
  29969. #ifdef WOLFSSL_TLS13
  29970. if (ssl->options.tls1_3) {
  29971. XMEMCPY(ssl->session->sessionID,
  29972. ssl->session->ticket + length - ID_LEN, ID_LEN);
  29973. ssl->session->sessionIDSz = ID_LEN;
  29974. }
  29975. else
  29976. #endif
  29977. {
  29978. XMEMCPY(ssl->arrays->sessionID,
  29979. ssl->session->ticket + length - ID_LEN, ID_LEN);
  29980. ssl->arrays->sessionIDSz = ID_LEN;
  29981. }
  29982. }
  29983. return 0;
  29984. }
  29985. #ifndef WOLFSSL_NO_TLS12
  29986. /* handle processing of session_ticket (4) */
  29987. static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  29988. word32 size)
  29989. {
  29990. word32 begin = *inOutIdx;
  29991. word32 lifetime;
  29992. word16 length;
  29993. int ret;
  29994. if (ssl->expect_session_ticket == 0) {
  29995. WOLFSSL_MSG("Unexpected session ticket");
  29996. WOLFSSL_ERROR_VERBOSE(SESSION_TICKET_EXPECT_E);
  29997. return SESSION_TICKET_EXPECT_E;
  29998. }
  29999. if (OPAQUE32_LEN > size)
  30000. return BUFFER_ERROR;
  30001. ato32(input + *inOutIdx, &lifetime);
  30002. *inOutIdx += OPAQUE32_LEN;
  30003. if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
  30004. return BUFFER_ERROR;
  30005. ato16(input + *inOutIdx, &length);
  30006. *inOutIdx += OPAQUE16_LEN;
  30007. if ((*inOutIdx - begin) + length > size)
  30008. return BUFFER_ERROR;
  30009. if ((ret = SetTicket(ssl, input + *inOutIdx, length)) != 0)
  30010. return ret;
  30011. *inOutIdx += length;
  30012. if (length > 0) {
  30013. ssl->timeout = lifetime;
  30014. SetupSession(ssl);
  30015. #ifndef NO_SESSION_CACHE
  30016. AddSession(ssl);
  30017. #endif
  30018. }
  30019. if (IsEncryptionOn(ssl, 0)) {
  30020. *inOutIdx += ssl->keys.padSz;
  30021. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  30022. if (ssl->options.startedETMRead)
  30023. *inOutIdx += MacSize(ssl);
  30024. #endif
  30025. }
  30026. ssl->expect_session_ticket = 0;
  30027. return 0;
  30028. }
  30029. #endif /* !WOLFSSL_NO_TLS12 */
  30030. #endif /* HAVE_SESSION_TICKET */
  30031. #endif /* NO_WOLFSSL_CLIENT */
  30032. #ifndef NO_CERTS
  30033. #if defined(WOLF_PRIVATE_KEY_ID) || defined(HAVE_PK_CALLBACKS)
  30034. int GetPrivateKeySigSize(WOLFSSL* ssl)
  30035. {
  30036. int sigSz = 0;
  30037. if (ssl == NULL)
  30038. return 0;
  30039. switch (ssl->buffers.keyType) {
  30040. #ifndef NO_RSA
  30041. #ifdef WC_RSA_PSS
  30042. case rsa_pss_sa_algo:
  30043. #endif
  30044. case rsa_sa_algo:
  30045. sigSz = ssl->buffers.keySz;
  30046. ssl->hsType = DYNAMIC_TYPE_RSA;
  30047. break;
  30048. #endif
  30049. #ifdef HAVE_ECC
  30050. case ecc_dsa_sa_algo:
  30051. sigSz = wc_ecc_sig_size_calc(ssl->buffers.keySz);
  30052. ssl->hsType = DYNAMIC_TYPE_ECC;
  30053. break;
  30054. #endif
  30055. #ifdef HAVE_ED25519
  30056. case ed25519_sa_algo:
  30057. sigSz = ED25519_SIG_SIZE; /* fixed known value */
  30058. ssl->hsType = DYNAMIC_TYPE_ED25519;
  30059. break;
  30060. #endif
  30061. #ifdef HAVE_ED448
  30062. case ed448_sa_algo:
  30063. sigSz = ED448_SIG_SIZE; /* fixed known value */
  30064. ssl->hsType = DYNAMIC_TYPE_ED448;
  30065. break;
  30066. #endif
  30067. default:
  30068. break;
  30069. }
  30070. return sigSz;
  30071. }
  30072. #endif /* WOLF_PRIVATE_KEY_ID || HAVE_PK_CALLBACKS */
  30073. #endif /* NO_CERTS */
  30074. #ifdef HAVE_ECC
  30075. /* returns the WOLFSSL_* version of the curve from the OID sum */
  30076. word16 GetCurveByOID(int oidSum) {
  30077. switch(oidSum) {
  30078. #if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
  30079. #ifndef NO_ECC_SECP
  30080. case ECC_SECP160R1_OID:
  30081. return WOLFSSL_ECC_SECP160R1;
  30082. #endif /* !NO_ECC_SECP */
  30083. #ifdef HAVE_ECC_SECPR2
  30084. case ECC_SECP160R2_OID:
  30085. return WOLFSSL_ECC_SECP160R2;
  30086. #endif /* HAVE_ECC_SECPR2 */
  30087. #ifdef HAVE_ECC_KOBLITZ
  30088. case ECC_SECP160K1_OID:
  30089. return WOLFSSL_ECC_SECP160K1;
  30090. #endif /* HAVE_ECC_KOBLITZ */
  30091. #endif
  30092. #if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
  30093. #ifndef NO_ECC_SECP
  30094. case ECC_SECP192R1_OID:
  30095. return WOLFSSL_ECC_SECP192R1;
  30096. #endif /* !NO_ECC_SECP */
  30097. #ifdef HAVE_ECC_KOBLITZ
  30098. case ECC_SECP192K1_OID:
  30099. return WOLFSSL_ECC_SECP192K1;
  30100. #endif /* HAVE_ECC_KOBLITZ */
  30101. #endif
  30102. #if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
  30103. #ifndef NO_ECC_SECP
  30104. case ECC_SECP224R1_OID:
  30105. return WOLFSSL_ECC_SECP224R1;
  30106. #endif /* !NO_ECC_SECP */
  30107. #ifdef HAVE_ECC_KOBLITZ
  30108. case ECC_SECP224K1_OID:
  30109. return WOLFSSL_ECC_SECP224K1;
  30110. #endif /* HAVE_ECC_KOBLITZ */
  30111. #endif
  30112. #if (!defined(NO_ECC256) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
  30113. #ifndef NO_ECC_SECP
  30114. case ECC_SECP256R1_OID:
  30115. return WOLFSSL_ECC_SECP256R1;
  30116. #endif /* !NO_ECC_SECP */
  30117. #ifdef HAVE_ECC_KOBLITZ
  30118. case ECC_SECP256K1_OID:
  30119. return WOLFSSL_ECC_SECP256K1;
  30120. #endif /* HAVE_ECC_KOBLITZ */
  30121. #ifdef HAVE_ECC_BRAINPOOL
  30122. case ECC_BRAINPOOLP256R1_OID:
  30123. return WOLFSSL_ECC_BRAINPOOLP256R1;
  30124. #endif /* HAVE_ECC_BRAINPOOL */
  30125. #ifdef WOLFSSL_SM2
  30126. case ECC_SM2P256V1_OID:
  30127. return WOLFSSL_ECC_SM2P256V1;
  30128. #endif /* WOLFSSL_SM2 */
  30129. #endif
  30130. #if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
  30131. #ifndef NO_ECC_SECP
  30132. case ECC_SECP384R1_OID:
  30133. return WOLFSSL_ECC_SECP384R1;
  30134. #endif /* !NO_ECC_SECP */
  30135. #ifdef HAVE_ECC_BRAINPOOL
  30136. case ECC_BRAINPOOLP384R1_OID:
  30137. return WOLFSSL_ECC_BRAINPOOLP384R1;
  30138. #endif /* HAVE_ECC_BRAINPOOL */
  30139. #endif
  30140. #if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
  30141. #ifdef HAVE_ECC_BRAINPOOL
  30142. case ECC_BRAINPOOLP512R1_OID:
  30143. return WOLFSSL_ECC_BRAINPOOLP512R1;
  30144. #endif /* HAVE_ECC_BRAINPOOL */
  30145. #endif
  30146. #if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
  30147. #ifndef NO_ECC_SECP
  30148. case ECC_SECP521R1_OID:
  30149. return WOLFSSL_ECC_SECP521R1;
  30150. #endif /* !NO_ECC_SECP */
  30151. #endif
  30152. default:
  30153. WOLFSSL_MSG("Curve OID not compiled in or implemented");
  30154. return 0;
  30155. }
  30156. }
  30157. #endif /* HAVE_ECC */
  30158. int TranslateErrorToAlert(int err)
  30159. {
  30160. switch (err) {
  30161. case WC_NO_ERR_TRACE(BUFFER_ERROR):
  30162. return decode_error;
  30163. case WC_NO_ERR_TRACE(EXT_NOT_ALLOWED):
  30164. case WC_NO_ERR_TRACE(PEER_KEY_ERROR):
  30165. case WC_NO_ERR_TRACE(ECC_PEERKEY_ERROR):
  30166. case WC_NO_ERR_TRACE(BAD_KEY_SHARE_DATA):
  30167. case WC_NO_ERR_TRACE(PSK_KEY_ERROR):
  30168. case WC_NO_ERR_TRACE(INVALID_PARAMETER):
  30169. case WC_NO_ERR_TRACE(HRR_COOKIE_ERROR):
  30170. case WC_NO_ERR_TRACE(BAD_BINDER):
  30171. return illegal_parameter;
  30172. case WC_NO_ERR_TRACE(INCOMPLETE_DATA):
  30173. return missing_extension;
  30174. case WC_NO_ERR_TRACE(MATCH_SUITE_ERROR):
  30175. case WC_NO_ERR_TRACE(MISSING_HANDSHAKE_DATA):
  30176. return handshake_failure;
  30177. case WC_NO_ERR_TRACE(VERSION_ERROR):
  30178. return wolfssl_alert_protocol_version;
  30179. default:
  30180. return invalid_alert;
  30181. }
  30182. }
  30183. /* search suites for specific one, idx on success, negative on error */
  30184. int FindSuite(const Suites* suites, byte first, byte second)
  30185. {
  30186. int i;
  30187. if (suites == NULL || suites->suiteSz == 0) {
  30188. WOLFSSL_MSG("Suites pointer error or suiteSz 0");
  30189. return SUITES_ERROR;
  30190. }
  30191. for (i = 0; i < suites->suiteSz-1; i += SUITE_LEN) {
  30192. if (suites->suites[i] == first &&
  30193. suites->suites[i+1] == second )
  30194. return i;
  30195. }
  30196. return MATCH_SUITE_ERROR;
  30197. }
  30198. #ifndef NO_WOLFSSL_SERVER
  30199. #ifndef WOLFSSL_NO_TLS12
  30200. /* handle generation of server_hello (2) */
  30201. int SendServerHello(WOLFSSL* ssl)
  30202. {
  30203. int ret;
  30204. byte *output;
  30205. word16 length;
  30206. word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  30207. int sendSz;
  30208. byte sessIdSz = ID_LEN;
  30209. #if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_SESSION_TICKET)
  30210. byte echoId = 0; /* ticket echo id flag */
  30211. #endif
  30212. byte cacheOff = 0; /* session cache off flag */
  30213. WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND);
  30214. WOLFSSL_ENTER("SendServerHello");
  30215. length = VERSION_SZ + RAN_LEN
  30216. + ID_LEN + ENUM_LEN
  30217. + SUITE_LEN
  30218. + ENUM_LEN;
  30219. #ifdef HAVE_TLS_EXTENSIONS
  30220. ret = TLSX_GetResponseSize(ssl, server_hello, &length);
  30221. if (ret != 0)
  30222. return ret;
  30223. #ifdef HAVE_SESSION_TICKET
  30224. if (ssl->options.useTicket) {
  30225. /* echo session id sz can be 0,32 or bogus len in between */
  30226. sessIdSz = ssl->arrays->sessionIDSz;
  30227. if (sessIdSz > ID_LEN) {
  30228. WOLFSSL_MSG("Bad bogus session id len");
  30229. return BUFFER_ERROR;
  30230. }
  30231. if (!IsAtLeastTLSv1_3(ssl->version))
  30232. length -= (ID_LEN - sessIdSz); /* adjust ID_LEN assumption */
  30233. echoId = 1;
  30234. }
  30235. #endif /* HAVE_SESSION_TICKET */
  30236. #else
  30237. if (ssl->options.haveEMS) {
  30238. length += HELLO_EXT_SZ_SZ + HELLO_EXT_SZ;
  30239. }
  30240. #endif
  30241. /* is the session cache off at build or runtime */
  30242. #ifdef NO_SESSION_CACHE
  30243. cacheOff = 1;
  30244. #else
  30245. if (ssl->options.sessionCacheOff == 1) {
  30246. cacheOff = 1;
  30247. }
  30248. #endif
  30249. /* if no session cache don't send a session ID unless we're echoing
  30250. * an ID as part of session tickets */
  30251. if (cacheOff == 1
  30252. #if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_SESSION_TICKET)
  30253. && echoId == 0
  30254. #endif
  30255. ) {
  30256. length -= ID_LEN; /* adjust ID_LEN assumption */
  30257. sessIdSz = 0;
  30258. }
  30259. sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  30260. #ifdef WOLFSSL_DTLS
  30261. if (ssl->options.dtls) {
  30262. idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  30263. sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  30264. }
  30265. #endif /* WOLFSSL_DTLS */
  30266. if (IsEncryptionOn(ssl, 1))
  30267. sendSz += MAX_MSG_EXTRA;
  30268. /* Set this in case CheckAvailableSize returns a WANT_WRITE so that state
  30269. * is not advanced yet */
  30270. ssl->options.buildingMsg = 1;
  30271. /* check for available size */
  30272. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  30273. return ret;
  30274. /* get output buffer */
  30275. output = GetOutputBuffer(ssl);
  30276. AddHeaders(output, length, server_hello, ssl);
  30277. /* now write to output */
  30278. /* first version */
  30279. output[idx++] = (byte)ssl->version.major;
  30280. output[idx++] = (byte)ssl->version.minor;
  30281. /* then random and session id */
  30282. if (!ssl->options.resuming) {
  30283. /* generate random part and session id */
  30284. ret = wc_RNG_GenerateBlock(ssl->rng, output + idx,
  30285. RAN_LEN + sizeof(sessIdSz) + sessIdSz);
  30286. if (ret != 0)
  30287. return ret;
  30288. #ifdef WOLFSSL_TLS13
  30289. if (TLSv1_3_Capable(ssl)) {
  30290. /* TLS v1.3 capable server downgraded. */
  30291. XMEMCPY(output + idx + RAN_LEN - (TLS13_DOWNGRADE_SZ + 1),
  30292. tls13Downgrade, TLS13_DOWNGRADE_SZ);
  30293. output[idx + RAN_LEN - 1] = (byte)IsAtLeastTLSv1_2(ssl);
  30294. }
  30295. else
  30296. #endif
  30297. if (ssl->ctx->method->version.major == SSLv3_MAJOR &&
  30298. ssl->ctx->method->version.minor == TLSv1_2_MINOR &&
  30299. (wolfSSL_get_options(ssl) & WOLFSSL_OP_NO_TLSv1_2) == 0 &&
  30300. !IsAtLeastTLSv1_2(ssl)) {
  30301. /* TLS v1.2 capable server downgraded. */
  30302. XMEMCPY(output + idx + RAN_LEN - (TLS13_DOWNGRADE_SZ + 1),
  30303. tls13Downgrade, TLS13_DOWNGRADE_SZ);
  30304. output[idx + RAN_LEN - 1] = 0;
  30305. }
  30306. /* store info in SSL for later */
  30307. XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
  30308. idx += RAN_LEN;
  30309. output[idx++] = sessIdSz;
  30310. XMEMCPY(ssl->arrays->sessionID, output + idx, sessIdSz);
  30311. ssl->arrays->sessionIDSz = sessIdSz;
  30312. }
  30313. else {
  30314. /* If resuming, use info from SSL */
  30315. XMEMCPY(output + idx, ssl->arrays->serverRandom, RAN_LEN);
  30316. idx += RAN_LEN;
  30317. output[idx++] = sessIdSz;
  30318. XMEMCPY(output + idx, ssl->arrays->sessionID, sessIdSz);
  30319. }
  30320. idx += sessIdSz;
  30321. #ifdef SHOW_SECRETS
  30322. {
  30323. int j;
  30324. printf("server random: ");
  30325. for (j = 0; j < RAN_LEN; j++)
  30326. printf("%02x", ssl->arrays->serverRandom[j]);
  30327. printf("\n");
  30328. }
  30329. #endif
  30330. /* then cipher suite */
  30331. output[idx++] = ssl->options.cipherSuite0;
  30332. output[idx++] = ssl->options.cipherSuite;
  30333. /* then compression */
  30334. if (ssl->options.usingCompression)
  30335. output[idx++] = ZLIB_COMPRESSION;
  30336. else
  30337. output[idx++] = NO_COMPRESSION;
  30338. /* last, extensions */
  30339. #ifdef HAVE_TLS_EXTENSIONS
  30340. {
  30341. word16 offset = 0;
  30342. ret = TLSX_WriteResponse(ssl, output + idx, server_hello, &offset);
  30343. if (ret != 0)
  30344. return ret;
  30345. idx += offset;
  30346. }
  30347. #else
  30348. #ifdef HAVE_EXTENDED_MASTER
  30349. if (ssl->options.haveEMS) {
  30350. c16toa(HELLO_EXT_SZ, output + idx);
  30351. idx += HELLO_EXT_SZ_SZ;
  30352. c16toa(HELLO_EXT_EXTMS, output + idx);
  30353. idx += HELLO_EXT_TYPE_SZ;
  30354. c16toa(0, output + idx);
  30355. /*idx += HELLO_EXT_SZ_SZ;*/
  30356. /* idx is not used after this point. uncomment the line above
  30357. * if adding any more extensions in the future. */
  30358. }
  30359. #endif
  30360. #endif
  30361. if (IsEncryptionOn(ssl, 1)) {
  30362. byte* input;
  30363. int inputSz = (int)idx; /* build msg adds rec hdr */
  30364. int recordHeaderSz = RECORD_HEADER_SZ;
  30365. if (ssl->options.dtls)
  30366. recordHeaderSz += DTLS_RECORD_EXTRA;
  30367. inputSz -= recordHeaderSz;
  30368. input = (byte*)XMALLOC((size_t)inputSz, ssl->heap,
  30369. DYNAMIC_TYPE_IN_BUFFER);
  30370. if (input == NULL)
  30371. return MEMORY_E;
  30372. XMEMCPY(input, output + recordHeaderSz, inputSz);
  30373. #ifdef WOLFSSL_DTLS
  30374. if (IsDtlsNotSctpMode(ssl) &&
  30375. (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, server_hello)) != 0) {
  30376. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  30377. return ret;
  30378. }
  30379. #endif
  30380. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  30381. handshake, 1, 0, 0, CUR_ORDER);
  30382. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  30383. if (sendSz < 0)
  30384. return sendSz;
  30385. } else {
  30386. #ifdef WOLFSSL_DTLS
  30387. if (IsDtlsNotSctpMode(ssl)) {
  30388. if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, server_hello)) != 0)
  30389. return ret;
  30390. }
  30391. if (ssl->options.dtls)
  30392. DtlsSEQIncrement(ssl, CUR_ORDER);
  30393. #endif
  30394. ret = HashOutput(ssl, output, sendSz, 0);
  30395. if (ret != 0)
  30396. return ret;
  30397. }
  30398. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  30399. if (ssl->hsInfoOn)
  30400. AddPacketName(ssl, "ServerHello");
  30401. if (ssl->toInfoOn) {
  30402. ret = AddPacketInfo(ssl, "ServerHello", handshake, output, sendSz,
  30403. WRITE_PROTO, 0, ssl->heap);
  30404. if (ret != 0)
  30405. return ret;
  30406. }
  30407. #endif
  30408. ssl->options.serverState = SERVER_HELLO_COMPLETE;
  30409. ssl->options.buildingMsg = 0;
  30410. ssl->buffers.outputBuffer.length += (word32)sendSz;
  30411. if (ssl->options.groupMessages)
  30412. ret = 0;
  30413. else
  30414. ret = SendBuffered(ssl);
  30415. WOLFSSL_LEAVE("SendServerHello", ret);
  30416. WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
  30417. return ret;
  30418. }
  30419. #if defined(HAVE_ECC)
  30420. static byte SetCurveId(ecc_key* key)
  30421. {
  30422. if (key == NULL || key->dp == NULL) {
  30423. WOLFSSL_MSG("SetCurveId: Invalid key!");
  30424. return 0;
  30425. }
  30426. return (byte)GetCurveByOID((int)key->dp->oidSum);
  30427. }
  30428. #endif /* HAVE_ECC */
  30429. typedef struct SskeArgs {
  30430. byte* output; /* not allocated */
  30431. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  30432. byte* exportBuf;
  30433. #endif
  30434. #ifndef NO_RSA
  30435. byte* verifySig;
  30436. #endif
  30437. byte* input;
  30438. word32 idx;
  30439. word32 tmpSigSz;
  30440. word32 length;
  30441. word32 sigSz;
  30442. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  30443. !defined(NO_RSA)
  30444. word32 sigDataSz;
  30445. #endif
  30446. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  30447. word32 exportSz;
  30448. #endif
  30449. word32 sendSz;
  30450. int inputSz;
  30451. } SskeArgs;
  30452. static void FreeSskeArgs(WOLFSSL* ssl, void* pArgs)
  30453. {
  30454. SskeArgs* args = (SskeArgs*)pArgs;
  30455. (void)ssl;
  30456. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  30457. XFREE(args->exportBuf, ssl->heap, DYNAMIC_TYPE_DER);
  30458. args->exportBuf = NULL;
  30459. #endif
  30460. #ifndef NO_RSA
  30461. XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  30462. args->verifySig = NULL;
  30463. #endif
  30464. (void)args;
  30465. }
  30466. /* handle generation of server_key_exchange (12) */
  30467. int SendServerKeyExchange(WOLFSSL* ssl)
  30468. {
  30469. int ret = 0;
  30470. #ifdef WOLFSSL_ASYNC_IO
  30471. SskeArgs* args = NULL;
  30472. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  30473. #else
  30474. SskeArgs args[1];
  30475. #endif
  30476. WOLFSSL_START(WC_FUNC_SERVER_KEY_EXCHANGE_SEND);
  30477. WOLFSSL_ENTER("SendServerKeyExchange");
  30478. #ifdef WOLFSSL_BLIND_PRIVATE_KEY
  30479. wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask);
  30480. #endif
  30481. #ifdef WOLFSSL_ASYNC_IO
  30482. if (ssl->async == NULL) {
  30483. ssl->async = (struct WOLFSSL_ASYNC*)
  30484. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  30485. DYNAMIC_TYPE_ASYNC);
  30486. if (ssl->async == NULL)
  30487. ERROR_OUT(MEMORY_E, exit_sske);
  30488. XMEMSET(ssl->async, 0, sizeof(struct WOLFSSL_ASYNC));
  30489. }
  30490. args = (SskeArgs*)ssl->async->args;
  30491. #ifdef WOLFSSL_ASYNC_CRYPT
  30492. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  30493. if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
  30494. /* Check for error */
  30495. if (ret < 0)
  30496. goto exit_sske;
  30497. }
  30498. else
  30499. #endif
  30500. if (ssl->options.buildingMsg) {
  30501. /* We should be in the sending state. */
  30502. if (ssl->options.asyncState != TLS_ASYNC_END) {
  30503. ret = BAD_STATE_E;
  30504. goto exit_sske;
  30505. }
  30506. }
  30507. else
  30508. #endif
  30509. {
  30510. /* Reset state */
  30511. ret = 0;
  30512. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  30513. XMEMSET(args, 0, sizeof(SskeArgs));
  30514. #ifdef WOLFSSL_ASYNC_IO
  30515. ssl->async->freeArgs = FreeSskeArgs;
  30516. #endif
  30517. }
  30518. switch(ssl->options.asyncState)
  30519. {
  30520. case TLS_ASYNC_BEGIN:
  30521. {
  30522. /* Do some checks / debug msgs */
  30523. switch(ssl->specs.kea)
  30524. {
  30525. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  30526. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  30527. case ecdhe_psk_kea:
  30528. {
  30529. WOLFSSL_MSG("Using ephemeral ECDH PSK");
  30530. break;
  30531. }
  30532. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  30533. #if defined(HAVE_ECC)
  30534. case ecc_diffie_hellman_kea:
  30535. {
  30536. if (ssl->specs.static_ecdh) {
  30537. WOLFSSL_MSG("Using Static ECDH, not sending "
  30538. "ServerKeyExchange");
  30539. ERROR_OUT(0, exit_sske);
  30540. }
  30541. WOLFSSL_MSG("Using ephemeral ECDH");
  30542. break;
  30543. }
  30544. #endif /* HAVE_ECC */
  30545. }
  30546. /* Preparing keys */
  30547. switch(ssl->specs.kea)
  30548. {
  30549. #ifndef NO_PSK
  30550. case psk_kea:
  30551. {
  30552. /* Nothing to do in this sub-state */
  30553. break;
  30554. }
  30555. #endif /* !NO_PSK */
  30556. #if !defined(NO_DH) && (!defined(NO_PSK) || !defined(NO_RSA) \
  30557. || (defined(HAVE_ANON) && !defined(WOLFSSL_NO_TLS12)))
  30558. #if !defined(NO_PSK)
  30559. case dhe_psk_kea:
  30560. #endif
  30561. #if !defined(NO_RSA) || (defined(HAVE_ANON) && \
  30562. !defined(WOLFSSL_NO_TLS12))
  30563. case diffie_hellman_kea:
  30564. #endif
  30565. #if (defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)) && !defined(HAVE_PUBLIC_FFDHE)
  30566. if (ssl->namedGroup) {
  30567. word32 pSz = 0;
  30568. ret = wc_DhGetNamedKeyParamSize(ssl->namedGroup, &pSz,
  30569. NULL, NULL);
  30570. if (ret != 0)
  30571. goto exit_sske;
  30572. if (ssl->buffers.serverDH_Pub.buffer == NULL) {
  30573. /* Free'd in SSL_ResourceFree and
  30574. * FreeHandshakeResources */
  30575. ssl->buffers.serverDH_Pub.buffer = (byte*)XMALLOC(
  30576. pSz, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  30577. if (ssl->buffers.serverDH_Pub.buffer == NULL) {
  30578. ERROR_OUT(MEMORY_E, exit_sske);
  30579. }
  30580. ssl->buffers.serverDH_Pub.length = pSz;
  30581. }
  30582. ssl->options.dhKeySz =(word16)pSz;
  30583. pSz = wc_DhGetNamedKeyMinSize(ssl->namedGroup);
  30584. if (ssl->buffers.serverDH_Priv.buffer == NULL) {
  30585. /* Free'd in SSL_ResourceFree and
  30586. * FreeHandshakeResources */
  30587. ssl->buffers.serverDH_Priv.buffer = (byte*)XMALLOC(
  30588. pSz, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  30589. if (ssl->buffers.serverDH_Priv.buffer == NULL) {
  30590. ERROR_OUT(MEMORY_E, exit_sske);
  30591. }
  30592. ssl->buffers.serverDH_Priv.length = pSz;
  30593. }
  30594. ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
  30595. (void**)&ssl->buffers.serverDH_Key);
  30596. if (ret != 0) {
  30597. goto exit_sske;
  30598. }
  30599. ret = wc_DhSetNamedKey(ssl->buffers.serverDH_Key,
  30600. ssl->namedGroup);
  30601. if (ret != 0) {
  30602. goto exit_sske;
  30603. }
  30604. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  30605. !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  30606. ssl->options.dhKeyTested = 1;
  30607. #endif
  30608. #ifdef HAVE_SECURE_RENEGOTIATION
  30609. /* Check that the DH public key buffer is large
  30610. * enough to hold the key. This may occur on a
  30611. * renegotiation when the key generated in the
  30612. * initial handshake is shorter than the key
  30613. * generated in the renegotiation. */
  30614. if (ssl->buffers.serverDH_Pub.length <
  30615. ssl->buffers.serverDH_P.length) {
  30616. byte* tmp = (byte*)XREALLOC(
  30617. ssl->buffers.serverDH_Pub.buffer,
  30618. ssl->buffers.serverDH_P.length +
  30619. OPAQUE16_LEN,
  30620. ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  30621. if (tmp == NULL)
  30622. ERROR_OUT(MEMORY_E, exit_sske);
  30623. ssl->buffers.serverDH_Pub.buffer = tmp;
  30624. ssl->buffers.serverDH_Pub.length =
  30625. ssl->buffers.serverDH_P.length + OPAQUE16_LEN;
  30626. }
  30627. #endif
  30628. ret = DhGenKeyPair(ssl, ssl->buffers.serverDH_Key,
  30629. ssl->buffers.serverDH_Priv.buffer,
  30630. (word32*)&ssl->buffers.serverDH_Priv.length,
  30631. ssl->buffers.serverDH_Pub.buffer,
  30632. (word32*)&ssl->buffers.serverDH_Pub.length);
  30633. #ifdef WOLFSSL_CHECK_MEM_ZERO
  30634. wc_MemZero_Add("DH private key buffer",
  30635. ssl->buffers.serverDH_Priv.buffer,
  30636. ssl->buffers.serverDH_Priv.length);
  30637. #endif
  30638. break;
  30639. }
  30640. else
  30641. #endif
  30642. {
  30643. /* Allocate DH key buffers and generate key */
  30644. if (ssl->buffers.serverDH_P.buffer == NULL ||
  30645. ssl->buffers.serverDH_G.buffer == NULL) {
  30646. ERROR_OUT(NO_DH_PARAMS, exit_sske);
  30647. }
  30648. if (ssl->buffers.serverDH_Pub.buffer == NULL) {
  30649. /* Free'd in SSL_ResourceFree and FreeHandshakeResources */
  30650. ssl->buffers.serverDH_Pub.buffer = (byte*)XMALLOC(
  30651. ssl->buffers.serverDH_P.length,
  30652. ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  30653. if (ssl->buffers.serverDH_Pub.buffer == NULL) {
  30654. ERROR_OUT(MEMORY_E, exit_sske);
  30655. }
  30656. ssl->buffers.serverDH_Pub.length =
  30657. ssl->buffers.serverDH_P.length;
  30658. }
  30659. if (ssl->buffers.serverDH_Priv.buffer == NULL) {
  30660. /* Free'd in SSL_ResourceFree and FreeHandshakeResources */
  30661. ssl->buffers.serverDH_Priv.buffer = (byte*)XMALLOC(
  30662. ssl->buffers.serverDH_P.length,
  30663. ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  30664. if (ssl->buffers.serverDH_Priv.buffer == NULL) {
  30665. ERROR_OUT(MEMORY_E, exit_sske);
  30666. }
  30667. ssl->buffers.serverDH_Priv.length =
  30668. ssl->buffers.serverDH_P.length;
  30669. }
  30670. ssl->options.dhKeySz =
  30671. (word16)ssl->buffers.serverDH_P.length;
  30672. ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
  30673. (void**)&ssl->buffers.serverDH_Key);
  30674. if (ret != 0) {
  30675. goto exit_sske;
  30676. }
  30677. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  30678. !defined(HAVE_FIPS) && \
  30679. !defined(HAVE_SELFTEST)
  30680. if (ssl->options.dhDoKeyTest &&
  30681. !ssl->options.dhKeyTested)
  30682. {
  30683. ret = wc_DhSetCheckKey(
  30684. ssl->buffers.serverDH_Key,
  30685. ssl->buffers.serverDH_P.buffer,
  30686. ssl->buffers.serverDH_P.length,
  30687. ssl->buffers.serverDH_G.buffer,
  30688. ssl->buffers.serverDH_G.length,
  30689. NULL, 0, 0, ssl->rng);
  30690. if (ret != 0) {
  30691. goto exit_sske;
  30692. }
  30693. ssl->options.dhKeyTested = 1;
  30694. }
  30695. else
  30696. #endif
  30697. {
  30698. ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
  30699. ssl->buffers.serverDH_P.buffer,
  30700. ssl->buffers.serverDH_P.length,
  30701. ssl->buffers.serverDH_G.buffer,
  30702. ssl->buffers.serverDH_G.length);
  30703. if (ret != 0) {
  30704. goto exit_sske;
  30705. }
  30706. }
  30707. #ifdef HAVE_SECURE_RENEGOTIATION
  30708. /* Check that the DH public key buffer is large
  30709. * enough to hold the key. This may occur on a
  30710. * renegotiation when the key generated in the
  30711. * initial handshake is shorter than the key
  30712. * generated in the renegotiation. */
  30713. if (ssl->buffers.serverDH_Pub.length <
  30714. ssl->buffers.serverDH_P.length) {
  30715. byte* tmp = (byte*)XREALLOC(
  30716. ssl->buffers.serverDH_Pub.buffer,
  30717. ssl->buffers.serverDH_P.length +
  30718. OPAQUE16_LEN,
  30719. ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  30720. if (tmp == NULL)
  30721. ERROR_OUT(MEMORY_E, exit_sske);
  30722. ssl->buffers.serverDH_Pub.buffer = tmp;
  30723. ssl->buffers.serverDH_Pub.length =
  30724. ssl->buffers.serverDH_P.length + OPAQUE16_LEN;
  30725. }
  30726. #endif
  30727. ret = DhGenKeyPair(ssl, ssl->buffers.serverDH_Key,
  30728. ssl->buffers.serverDH_Priv.buffer,
  30729. (word32*)&ssl->buffers.serverDH_Priv.length,
  30730. ssl->buffers.serverDH_Pub.buffer,
  30731. (word32*)&ssl->buffers.serverDH_Pub.length);
  30732. #ifdef WOLFSSL_CHECK_MEM_ZERO
  30733. wc_MemZero_Add("DH private key buffer",
  30734. ssl->buffers.serverDH_Priv.buffer,
  30735. ssl->buffers.serverDH_Priv.length);
  30736. #endif
  30737. break;
  30738. }
  30739. #endif /* !NO_DH && (!NO_PSK || !NO_RSA) */
  30740. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  30741. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  30742. case ecdhe_psk_kea:
  30743. /* Fall through to create temp ECC key */
  30744. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  30745. #if defined(HAVE_ECC) || \
  30746. ((defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)) && \
  30747. (defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  30748. !defined(NO_RSA)))
  30749. case ecc_diffie_hellman_kea:
  30750. {
  30751. #ifdef HAVE_CURVE25519
  30752. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  30753. /* need ephemeral key now, create it if missing */
  30754. if (ssl->eccTempKey == NULL) {
  30755. /* alloc/init on demand */
  30756. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
  30757. (void**)&ssl->eccTempKey);
  30758. if (ret != 0) {
  30759. goto exit_sske;
  30760. }
  30761. }
  30762. if (ssl->eccTempKeyPresent == 0) {
  30763. ret = X25519MakeKey(ssl,
  30764. (curve25519_key*)ssl->eccTempKey, NULL);
  30765. if (ret == 0 ||
  30766. ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  30767. ssl->eccTempKeyPresent =
  30768. DYNAMIC_TYPE_CURVE25519;
  30769. }
  30770. else {
  30771. FreeKey(ssl, DYNAMIC_TYPE_CURVE25519,
  30772. (void**)&ssl->eccTempKey);
  30773. }
  30774. }
  30775. break;
  30776. }
  30777. #endif
  30778. #ifdef HAVE_CURVE448
  30779. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  30780. /* need ephemeral key now, create it if missing */
  30781. if (ssl->eccTempKey == NULL) {
  30782. /* alloc/init on demand */
  30783. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
  30784. (void**)&ssl->eccTempKey);
  30785. if (ret != 0) {
  30786. goto exit_sske;
  30787. }
  30788. }
  30789. if (ssl->eccTempKeyPresent == 0) {
  30790. ret = X448MakeKey(ssl,
  30791. (curve448_key*)ssl->eccTempKey, NULL);
  30792. if (ret == 0 ||
  30793. ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  30794. ssl->eccTempKeyPresent =
  30795. DYNAMIC_TYPE_CURVE448;
  30796. }
  30797. else {
  30798. FreeKey(ssl, DYNAMIC_TYPE_CURVE448,
  30799. (void**)&ssl->eccTempKey);
  30800. }
  30801. }
  30802. break;
  30803. }
  30804. #endif
  30805. #ifdef HAVE_ECC
  30806. /* need ephemeral key now, create it if missing */
  30807. if (ssl->eccTempKey == NULL) {
  30808. /* alloc/init on demand */
  30809. ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
  30810. (void**)&ssl->eccTempKey);
  30811. if (ret != 0) {
  30812. goto exit_sske;
  30813. }
  30814. }
  30815. if (ssl->eccTempKeyPresent == 0) {
  30816. ret = EccMakeKey(ssl, ssl->eccTempKey, NULL);
  30817. if (ret == 0 ||
  30818. ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  30819. ssl->eccTempKeyPresent = DYNAMIC_TYPE_ECC;
  30820. }
  30821. }
  30822. #endif
  30823. break;
  30824. }
  30825. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  30826. default:
  30827. /* Skip ServerKeyExchange */
  30828. goto exit_sske;
  30829. } /* switch(ssl->specs.kea) */
  30830. /* Check for error */
  30831. if (ret != 0) {
  30832. goto exit_sske;
  30833. }
  30834. /* Advance state and proceed */
  30835. ssl->options.asyncState = TLS_ASYNC_BUILD;
  30836. } /* case TLS_ASYNC_BEGIN */
  30837. FALL_THROUGH;
  30838. case TLS_ASYNC_BUILD:
  30839. {
  30840. switch(ssl->specs.kea)
  30841. {
  30842. #ifndef NO_PSK
  30843. case psk_kea:
  30844. {
  30845. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  30846. if (ssl->arrays->server_hint[0] == 0) {
  30847. ERROR_OUT(0, exit_sske); /* don't send */
  30848. }
  30849. /* include size part */
  30850. args->length = (word32)XSTRLEN(ssl->arrays->server_hint);
  30851. if (args->length > MAX_PSK_ID_LEN) {
  30852. ERROR_OUT(SERVER_HINT_ERROR, exit_sske);
  30853. }
  30854. args->length += HINT_LEN_SZ;
  30855. args->sendSz = args->length + HANDSHAKE_HEADER_SZ +
  30856. RECORD_HEADER_SZ;
  30857. #ifdef WOLFSSL_DTLS
  30858. if (ssl->options.dtls) {
  30859. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  30860. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  30861. }
  30862. #endif
  30863. if (IsEncryptionOn(ssl, 1)) {
  30864. args->sendSz += MAX_MSG_EXTRA;
  30865. }
  30866. /* Use tmp buffer */
  30867. args->input = (byte*)XMALLOC(args->sendSz,
  30868. ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  30869. if (args->input == NULL)
  30870. ERROR_OUT(MEMORY_E, exit_sske);
  30871. args->output = args->input;
  30872. AddHeaders(args->output, args->length,
  30873. server_key_exchange, ssl);
  30874. /* key data */
  30875. c16toa((word16)(args->length - HINT_LEN_SZ),
  30876. args->output + args->idx);
  30877. args->idx += HINT_LEN_SZ;
  30878. XMEMCPY(args->output + args->idx,
  30879. ssl->arrays->server_hint,
  30880. args->length - HINT_LEN_SZ);
  30881. break;
  30882. }
  30883. #endif /* !NO_PSK */
  30884. #if !defined(NO_DH) && !defined(NO_PSK)
  30885. case dhe_psk_kea:
  30886. {
  30887. word32 hintLen;
  30888. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  30889. args->length = LENGTH_SZ * 3 + /* p, g, pub */
  30890. ssl->buffers.serverDH_P.length +
  30891. ssl->buffers.serverDH_G.length +
  30892. ssl->buffers.serverDH_Pub.length;
  30893. /* include size part */
  30894. hintLen = (word32)XSTRLEN(ssl->arrays->server_hint);
  30895. if (hintLen > MAX_PSK_ID_LEN) {
  30896. ERROR_OUT(SERVER_HINT_ERROR, exit_sske);
  30897. }
  30898. args->length += hintLen + HINT_LEN_SZ;
  30899. args->sendSz = args->length + HANDSHAKE_HEADER_SZ +
  30900. RECORD_HEADER_SZ;
  30901. #ifdef WOLFSSL_DTLS
  30902. if (ssl->options.dtls) {
  30903. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  30904. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  30905. }
  30906. #endif
  30907. if (IsEncryptionOn(ssl, 1)) {
  30908. args->sendSz += MAX_MSG_EXTRA;
  30909. }
  30910. /* Use tmp buffer */
  30911. args->input = (byte*)XMALLOC(args->sendSz,
  30912. ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  30913. if (args->input == NULL)
  30914. ERROR_OUT(MEMORY_E, exit_sske);
  30915. args->output = args->input;
  30916. AddHeaders(args->output, args->length,
  30917. server_key_exchange, ssl);
  30918. /* key data */
  30919. c16toa((word16)hintLen, args->output + args->idx);
  30920. args->idx += HINT_LEN_SZ;
  30921. XMEMCPY(args->output + args->idx,
  30922. ssl->arrays->server_hint, hintLen);
  30923. args->idx += hintLen;
  30924. /* add p, g, pub */
  30925. c16toa((word16)ssl->buffers.serverDH_P.length,
  30926. args->output + args->idx);
  30927. args->idx += LENGTH_SZ;
  30928. XMEMCPY(args->output + args->idx,
  30929. ssl->buffers.serverDH_P.buffer,
  30930. ssl->buffers.serverDH_P.length);
  30931. args->idx += ssl->buffers.serverDH_P.length;
  30932. /* g */
  30933. c16toa((word16)ssl->buffers.serverDH_G.length,
  30934. args->output + args->idx);
  30935. args->idx += LENGTH_SZ;
  30936. XMEMCPY(args->output + args->idx,
  30937. ssl->buffers.serverDH_G.buffer,
  30938. ssl->buffers.serverDH_G.length);
  30939. args->idx += ssl->buffers.serverDH_G.length;
  30940. /* pub */
  30941. c16toa((word16)ssl->buffers.serverDH_Pub.length,
  30942. args->output + args->idx);
  30943. args->idx += LENGTH_SZ;
  30944. XMEMCPY(args->output + args->idx,
  30945. ssl->buffers.serverDH_Pub.buffer,
  30946. ssl->buffers.serverDH_Pub.length);
  30947. /* No need to update idx, since sizes are already set */
  30948. /* args->idx += ssl->buffers.serverDH_Pub.length; */
  30949. break;
  30950. }
  30951. #endif /* !defined(NO_DH) && !defined(NO_PSK) */
  30952. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  30953. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  30954. case ecdhe_psk_kea:
  30955. {
  30956. word32 hintLen;
  30957. /* curve type, named curve, length(1) */
  30958. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  30959. args->length = ENUM_LEN + CURVE_LEN + ENUM_LEN;
  30960. args->exportSz = MAX_EXPORT_ECC_SZ;
  30961. args->exportBuf = (byte*)XMALLOC(MAX_EXPORT_ECC_SZ,
  30962. ssl->heap, DYNAMIC_TYPE_DER);
  30963. if (args->exportBuf == NULL) {
  30964. ERROR_OUT(MEMORY_E, exit_sske);
  30965. }
  30966. #ifdef HAVE_CURVE25519
  30967. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  30968. if (wc_curve25519_export_public_ex(
  30969. (curve25519_key*)ssl->eccTempKey,
  30970. args->exportBuf, &args->exportSz,
  30971. EC25519_LITTLE_ENDIAN) != 0) {
  30972. ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
  30973. }
  30974. }
  30975. else
  30976. #endif
  30977. #ifdef HAVE_CURVE448
  30978. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  30979. if (wc_curve448_export_public_ex(
  30980. (curve448_key*)ssl->eccTempKey,
  30981. args->exportBuf, &args->exportSz,
  30982. EC448_LITTLE_ENDIAN) != 0) {
  30983. ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
  30984. }
  30985. }
  30986. else
  30987. #endif
  30988. {
  30989. PRIVATE_KEY_UNLOCK();
  30990. ret = wc_ecc_export_x963(ssl->eccTempKey,
  30991. args->exportBuf, &args->exportSz);
  30992. PRIVATE_KEY_LOCK();
  30993. if (ret != 0) {
  30994. ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
  30995. }
  30996. }
  30997. args->length += args->exportSz;
  30998. /* include size part */
  30999. hintLen = (word32)XSTRLEN(ssl->arrays->server_hint);
  31000. if (hintLen > MAX_PSK_ID_LEN) {
  31001. ERROR_OUT(SERVER_HINT_ERROR, exit_sske);
  31002. }
  31003. args->length += hintLen + HINT_LEN_SZ;
  31004. args->sendSz = args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  31005. #ifdef WOLFSSL_DTLS
  31006. if (ssl->options.dtls) {
  31007. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  31008. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  31009. }
  31010. #endif
  31011. if (IsEncryptionOn(ssl, 1)) {
  31012. args->sendSz += MAX_MSG_EXTRA;
  31013. }
  31014. /* Use tmp buffer */
  31015. args->input = (byte*)XMALLOC(args->sendSz,
  31016. ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  31017. if (args->input == NULL)
  31018. ERROR_OUT(MEMORY_E, exit_sske);
  31019. args->output = args->input;
  31020. /* key data */
  31021. c16toa((word16)hintLen, args->output + args->idx);
  31022. args->idx += HINT_LEN_SZ;
  31023. XMEMCPY(args->output + args->idx,
  31024. ssl->arrays->server_hint, hintLen);
  31025. args->idx += hintLen;
  31026. /* ECC key exchange data */
  31027. args->output[args->idx++] = named_curve;
  31028. args->output[args->idx++] = 0x00; /* leading zero */
  31029. #ifdef HAVE_CURVE25519
  31030. if (ssl->ecdhCurveOID == ECC_X25519_OID)
  31031. args->output[args->idx++] = WOLFSSL_ECC_X25519;
  31032. else
  31033. #endif
  31034. #ifdef HAVE_CURVE448
  31035. if (ssl->ecdhCurveOID == ECC_X448_OID)
  31036. args->output[args->idx++] = WOLFSSL_ECC_X448;
  31037. else
  31038. #endif
  31039. {
  31040. #ifdef HAVE_ECC
  31041. args->output[args->idx++] =
  31042. SetCurveId(ssl->eccTempKey);
  31043. #endif
  31044. }
  31045. args->output[args->idx++] = (byte)args->exportSz;
  31046. XMEMCPY(args->output + args->idx, args->exportBuf,
  31047. args->exportSz);
  31048. break;
  31049. }
  31050. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  31051. #if defined(HAVE_ECC) || \
  31052. ((defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)) && \
  31053. (defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  31054. !defined(NO_RSA)))
  31055. case ecc_diffie_hellman_kea:
  31056. {
  31057. enum wc_HashType hashType;
  31058. word32 preSigSz, preSigIdx;
  31059. /* curve type, named curve, length(1) */
  31060. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  31061. args->length = ENUM_LEN + CURVE_LEN + ENUM_LEN;
  31062. /* Export temp ECC key and add to length */
  31063. args->exportSz = MAX_EXPORT_ECC_SZ;
  31064. args->exportBuf = (byte*)XMALLOC(MAX_EXPORT_ECC_SZ,
  31065. ssl->heap, DYNAMIC_TYPE_DER);
  31066. if (args->exportBuf == NULL) {
  31067. ERROR_OUT(MEMORY_E, exit_sske);
  31068. }
  31069. #ifdef HAVE_CURVE25519
  31070. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  31071. if (wc_curve25519_export_public_ex(
  31072. (curve25519_key*)ssl->eccTempKey,
  31073. args->exportBuf, &args->exportSz,
  31074. EC25519_LITTLE_ENDIAN) != 0) {
  31075. ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
  31076. }
  31077. }
  31078. else
  31079. #endif
  31080. #ifdef HAVE_CURVE448
  31081. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  31082. if (wc_curve448_export_public_ex(
  31083. (curve448_key*)ssl->eccTempKey,
  31084. args->exportBuf, &args->exportSz,
  31085. EC448_LITTLE_ENDIAN) != 0) {
  31086. ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
  31087. }
  31088. }
  31089. else
  31090. #endif
  31091. {
  31092. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  31093. PRIVATE_KEY_UNLOCK();
  31094. ret = wc_ecc_export_x963(ssl->eccTempKey,
  31095. args->exportBuf, &args->exportSz);
  31096. PRIVATE_KEY_LOCK();
  31097. if (ret != 0) {
  31098. ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
  31099. }
  31100. #endif
  31101. }
  31102. args->length += args->exportSz;
  31103. preSigSz = args->length;
  31104. preSigIdx = args->idx;
  31105. if (ssl->buffers.key == NULL) {
  31106. #ifdef HAVE_PK_CALLBACKS
  31107. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
  31108. args->tmpSigSz = (word32)GetPrivateKeySigSize(ssl);
  31109. if (args->tmpSigSz == 0) {
  31110. ERROR_OUT(NO_PRIVATE_KEY, exit_sske);
  31111. }
  31112. }
  31113. else
  31114. #endif
  31115. ERROR_OUT(NO_PRIVATE_KEY, exit_sske);
  31116. }
  31117. else {
  31118. switch(ssl->options.sigAlgo) {
  31119. #ifndef NO_RSA
  31120. #ifdef WC_RSA_PSS
  31121. case rsa_pss_sa_algo:
  31122. #endif
  31123. case rsa_sa_algo:
  31124. {
  31125. word32 keySz;
  31126. ssl->buffers.keyType = rsa_sa_algo;
  31127. ret = DecodePrivateKey(ssl, &keySz);
  31128. if (ret != 0) {
  31129. goto exit_sske;
  31130. }
  31131. args->tmpSigSz = (word32)keySz;
  31132. break;
  31133. }
  31134. #endif /* !NO_RSA */
  31135. #ifdef HAVE_ECC
  31136. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  31137. case sm2_sa_algo:
  31138. #endif
  31139. case ecc_dsa_sa_algo:
  31140. {
  31141. word32 keySz;
  31142. ssl->buffers.keyType = ssl->options.sigAlgo;
  31143. ret = DecodePrivateKey(ssl, &keySz);
  31144. if (ret != 0) {
  31145. goto exit_sske;
  31146. }
  31147. /* worst case estimate */
  31148. args->tmpSigSz = keySz;
  31149. break;
  31150. }
  31151. #endif
  31152. #ifdef HAVE_ED25519
  31153. case ed25519_sa_algo:
  31154. {
  31155. word32 keySz;
  31156. ssl->buffers.keyType = ed25519_sa_algo;
  31157. ret = DecodePrivateKey(ssl, &keySz);
  31158. if (ret != 0) {
  31159. goto exit_sske;
  31160. }
  31161. /* worst case estimate */
  31162. args->tmpSigSz = ED25519_SIG_SIZE;
  31163. break;
  31164. }
  31165. #endif /* HAVE_ED25519 */
  31166. #ifdef HAVE_ED448
  31167. case ed448_sa_algo:
  31168. {
  31169. word32 keySz;
  31170. ssl->buffers.keyType = ed448_sa_algo;
  31171. ret = DecodePrivateKey(ssl, &keySz);
  31172. if (ret != 0) {
  31173. goto exit_sske;
  31174. }
  31175. /* worst case estimate */
  31176. args->tmpSigSz = ED448_SIG_SIZE;
  31177. break;
  31178. }
  31179. #endif /* HAVE_ED448 */
  31180. default:
  31181. ERROR_OUT(ALGO_ID_E, exit_sske); /* unsupported type */
  31182. } /* switch(ssl->specs.sig_algo) */
  31183. }
  31184. /* sig length */
  31185. args->length += LENGTH_SZ;
  31186. args->length += args->tmpSigSz;
  31187. if (IsAtLeastTLSv1_2(ssl)) {
  31188. args->length += HASH_SIG_SIZE;
  31189. }
  31190. args->sendSz = args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  31191. #ifdef WOLFSSL_DTLS
  31192. if (ssl->options.dtls) {
  31193. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  31194. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  31195. preSigIdx = args->idx;
  31196. }
  31197. #endif
  31198. if (IsEncryptionOn(ssl, 1)) {
  31199. args->sendSz += MAX_MSG_EXTRA;
  31200. }
  31201. /* Use tmp buffer */
  31202. args->input = (byte*)XMALLOC(args->sendSz,
  31203. ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  31204. if (args->input == NULL)
  31205. ERROR_OUT(MEMORY_E, exit_sske);
  31206. args->output = args->input;
  31207. /* record and message headers will be added below, when we're sure
  31208. of the sig length */
  31209. /* key exchange data */
  31210. args->output[args->idx++] = named_curve;
  31211. args->output[args->idx++] = 0x00; /* leading zero */
  31212. #ifdef HAVE_CURVE25519
  31213. if (ssl->ecdhCurveOID == ECC_X25519_OID)
  31214. args->output[args->idx++] = WOLFSSL_ECC_X25519;
  31215. else
  31216. #endif
  31217. #ifdef HAVE_CURVE448
  31218. if (ssl->ecdhCurveOID == ECC_X448_OID)
  31219. args->output[args->idx++] = WOLFSSL_ECC_X448;
  31220. else
  31221. #endif
  31222. {
  31223. #ifdef HAVE_ECC
  31224. args->output[args->idx++] =
  31225. SetCurveId(ssl->eccTempKey);
  31226. #endif
  31227. }
  31228. args->output[args->idx++] = (byte)args->exportSz;
  31229. XMEMCPY(args->output + args->idx, args->exportBuf, args->exportSz);
  31230. args->idx += args->exportSz;
  31231. /* Determine hash type */
  31232. if (IsAtLeastTLSv1_2(ssl)) {
  31233. EncodeSigAlg(ssl->options.hashAlgo,
  31234. ssl->options.sigAlgo,
  31235. &args->output[args->idx]);
  31236. args->idx += 2;
  31237. hashType = HashAlgoToType(ssl->options.hashAlgo);
  31238. if (hashType == WC_HASH_TYPE_NONE) {
  31239. ERROR_OUT(ALGO_ID_E, exit_sske);
  31240. }
  31241. } else {
  31242. /* only using sha and md5 for rsa */
  31243. #ifndef NO_OLD_TLS
  31244. hashType = WC_HASH_TYPE_SHA;
  31245. if (ssl->options.sigAlgo == rsa_sa_algo) {
  31246. hashType = WC_HASH_TYPE_MD5_SHA;
  31247. }
  31248. #else
  31249. ERROR_OUT(ALGO_ID_E, exit_sske);
  31250. #endif
  31251. }
  31252. /* Signature length will be written later, when we're sure what it is */
  31253. #ifdef HAVE_FUZZER
  31254. if (ssl->fuzzerCb) {
  31255. ssl->fuzzerCb(ssl, args->output + preSigIdx,
  31256. preSigSz, FUZZ_SIGNATURE, ssl->fuzzerCtx);
  31257. }
  31258. #endif
  31259. ret = HashSkeData(ssl, hashType,
  31260. args->output + preSigIdx, preSigSz,
  31261. ssl->options.sigAlgo);
  31262. if (ret != 0) {
  31263. goto exit_sske;
  31264. }
  31265. args->sigSz = args->tmpSigSz;
  31266. /* Sign hash to create signature */
  31267. switch (ssl->options.sigAlgo)
  31268. {
  31269. #ifndef NO_RSA
  31270. case rsa_sa_algo:
  31271. {
  31272. /* For TLS 1.2 re-encode signature */
  31273. if (IsAtLeastTLSv1_2(ssl)) {
  31274. byte* encodedSig = (byte*)XMALLOC(
  31275. MAX_ENCODED_SIG_SZ, ssl->heap,
  31276. DYNAMIC_TYPE_DIGEST);
  31277. if (encodedSig == NULL) {
  31278. ERROR_OUT(MEMORY_E, exit_sske);
  31279. }
  31280. ssl->buffers.digest.length =
  31281. wc_EncodeSignature(encodedSig,
  31282. ssl->buffers.digest.buffer,
  31283. ssl->buffers.digest.length,
  31284. TypeHash(ssl->options.hashAlgo));
  31285. /* Replace sig buffer with new one */
  31286. if (!ssl->options.dontFreeDigest) {
  31287. XFREE(ssl->buffers.digest.buffer,
  31288. ssl->heap, DYNAMIC_TYPE_DIGEST);
  31289. }
  31290. ssl->options.dontFreeDigest = 0;
  31291. ssl->buffers.digest.buffer = encodedSig;
  31292. }
  31293. /* write sig size here */
  31294. c16toa((word16)args->sigSz,
  31295. args->output + args->idx);
  31296. args->idx += LENGTH_SZ;
  31297. break;
  31298. }
  31299. #ifdef WC_RSA_PSS
  31300. case rsa_pss_sa_algo:
  31301. /* write sig size here */
  31302. c16toa((word16)args->sigSz,
  31303. args->output + args->idx);
  31304. args->idx += LENGTH_SZ;
  31305. break;
  31306. #endif
  31307. #endif /* !NO_RSA */
  31308. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  31309. case sm2_sa_algo:
  31310. #endif
  31311. case ecc_dsa_sa_algo:
  31312. {
  31313. break;
  31314. }
  31315. #ifdef HAVE_ED25519
  31316. case ed25519_sa_algo:
  31317. ret = Ed25519CheckPubKey(ssl);
  31318. if (ret != 0)
  31319. goto exit_sske;
  31320. break;
  31321. #endif /* HAVE_ED25519 */
  31322. #ifdef HAVE_ED448
  31323. case ed448_sa_algo:
  31324. ret = Ed448CheckPubKey(ssl);
  31325. if (ret != 0)
  31326. goto exit_sske;
  31327. break;
  31328. #endif /* HAVE_ED448 */
  31329. default:
  31330. break;
  31331. } /* switch(ssl->specs.sig_algo) */
  31332. break;
  31333. }
  31334. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  31335. #if !defined(NO_DH) && (!defined(NO_RSA) || \
  31336. (defined(HAVE_ANON) && !defined(WOLFSSL_NO_TLS12)))
  31337. case diffie_hellman_kea:
  31338. {
  31339. enum wc_HashType hashType;
  31340. word32 preSigSz, preSigIdx;
  31341. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  31342. args->length = LENGTH_SZ * 3; /* p, g, pub */
  31343. args->length += ssl->buffers.serverDH_P.length +
  31344. ssl->buffers.serverDH_G.length +
  31345. ssl->buffers.serverDH_Pub.length;
  31346. preSigIdx = args->idx;
  31347. preSigSz = args->length;
  31348. if (!ssl->options.usingAnon_cipher) {
  31349. word32 keySz = 0;
  31350. /* sig length */
  31351. args->length += LENGTH_SZ;
  31352. if (ssl->buffers.key == NULL) {
  31353. #ifdef HAVE_PK_CALLBACKS
  31354. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
  31355. keySz = (word16)GetPrivateKeySigSize(ssl);
  31356. else
  31357. #endif
  31358. ERROR_OUT(NO_PRIVATE_KEY, exit_sske);
  31359. }
  31360. else
  31361. {
  31362. if (ssl->buffers.keyType == 0)
  31363. ssl->buffers.keyType = rsa_sa_algo;
  31364. ret = DecodePrivateKey(ssl, &keySz);
  31365. if (ret != 0) {
  31366. goto exit_sske;
  31367. }
  31368. }
  31369. /* test if keySz has error */
  31370. if (keySz == 0) {
  31371. ERROR_OUT(keySz, exit_sske);
  31372. }
  31373. args->tmpSigSz = (word32)keySz;
  31374. args->length += args->tmpSigSz;
  31375. if (IsAtLeastTLSv1_2(ssl)) {
  31376. args->length += HASH_SIG_SIZE;
  31377. }
  31378. }
  31379. args->sendSz = args->length + HANDSHAKE_HEADER_SZ +
  31380. RECORD_HEADER_SZ;
  31381. #ifdef WOLFSSL_DTLS
  31382. if (ssl->options.dtls) {
  31383. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  31384. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  31385. preSigIdx = args->idx;
  31386. }
  31387. #endif
  31388. if (IsEncryptionOn(ssl, 1)) {
  31389. args->sendSz += MAX_MSG_EXTRA;
  31390. }
  31391. /* Use tmp buffer */
  31392. args->input = (byte*)XMALLOC(args->sendSz,
  31393. ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  31394. if (args->input == NULL)
  31395. ERROR_OUT(MEMORY_E, exit_sske);
  31396. args->output = args->input;
  31397. AddHeaders(args->output, args->length,
  31398. server_key_exchange, ssl);
  31399. /* add p, g, pub */
  31400. c16toa((word16)ssl->buffers.serverDH_P.length,
  31401. args->output + args->idx);
  31402. args->idx += LENGTH_SZ;
  31403. XMEMCPY(args->output + args->idx,
  31404. ssl->buffers.serverDH_P.buffer,
  31405. ssl->buffers.serverDH_P.length);
  31406. args->idx += ssl->buffers.serverDH_P.length;
  31407. /* g */
  31408. c16toa((word16)ssl->buffers.serverDH_G.length,
  31409. args->output + args->idx);
  31410. args->idx += LENGTH_SZ;
  31411. XMEMCPY(args->output + args->idx,
  31412. ssl->buffers.serverDH_G.buffer,
  31413. ssl->buffers.serverDH_G.length);
  31414. args->idx += ssl->buffers.serverDH_G.length;
  31415. /* pub */
  31416. c16toa((word16)ssl->buffers.serverDH_Pub.length,
  31417. args->output + args->idx);
  31418. args->idx += LENGTH_SZ;
  31419. XMEMCPY(args->output + args->idx,
  31420. ssl->buffers.serverDH_Pub.buffer,
  31421. ssl->buffers.serverDH_Pub.length);
  31422. args->idx += ssl->buffers.serverDH_Pub.length;
  31423. #ifdef HAVE_FUZZER
  31424. if (ssl->fuzzerCb) {
  31425. ssl->fuzzerCb(ssl, args->output + preSigIdx,
  31426. preSigSz, FUZZ_SIGNATURE, ssl->fuzzerCtx);
  31427. }
  31428. #endif
  31429. if (ssl->options.usingAnon_cipher) {
  31430. break;
  31431. }
  31432. /* Determine hash type */
  31433. if (IsAtLeastTLSv1_2(ssl)) {
  31434. EncodeSigAlg(ssl->options.hashAlgo,
  31435. ssl->options.sigAlgo,
  31436. &args->output[args->idx]);
  31437. args->idx += 2;
  31438. hashType = HashAlgoToType(ssl->options.hashAlgo);
  31439. if (hashType == WC_HASH_TYPE_NONE) {
  31440. ERROR_OUT(ALGO_ID_E, exit_sske);
  31441. }
  31442. } else {
  31443. /* only using sha and md5 for rsa */
  31444. #ifndef NO_OLD_TLS
  31445. hashType = WC_HASH_TYPE_SHA;
  31446. if (ssl->options.sigAlgo == rsa_sa_algo) {
  31447. hashType = WC_HASH_TYPE_MD5_SHA;
  31448. }
  31449. #else
  31450. ERROR_OUT(ALGO_ID_E, exit_sske);
  31451. #endif
  31452. }
  31453. /* signature size */
  31454. c16toa((word16)args->tmpSigSz, args->output + args->idx);
  31455. args->idx += LENGTH_SZ;
  31456. ret = HashSkeData(ssl, hashType,
  31457. args->output + preSigIdx, preSigSz,
  31458. ssl->options.sigAlgo);
  31459. if (ret != 0) {
  31460. goto exit_sske;
  31461. }
  31462. args->sigSz = args->tmpSigSz;
  31463. /* Sign hash to create signature */
  31464. switch (ssl->options.sigAlgo)
  31465. {
  31466. #ifndef NO_RSA
  31467. case rsa_sa_algo:
  31468. {
  31469. /* For TLS 1.2 re-encode signature */
  31470. if (IsAtLeastTLSv1_2(ssl)) {
  31471. byte* encodedSig = (byte*)XMALLOC(
  31472. MAX_ENCODED_SIG_SZ, ssl->heap,
  31473. DYNAMIC_TYPE_DIGEST);
  31474. if (encodedSig == NULL) {
  31475. ERROR_OUT(MEMORY_E, exit_sske);
  31476. }
  31477. ssl->buffers.digest.length =
  31478. wc_EncodeSignature(encodedSig,
  31479. ssl->buffers.digest.buffer,
  31480. ssl->buffers.digest.length,
  31481. TypeHash(ssl->options.hashAlgo));
  31482. /* Replace sig buffer with new one */
  31483. if (!ssl->options.dontFreeDigest) {
  31484. XFREE(ssl->buffers.digest.buffer,
  31485. ssl->heap, DYNAMIC_TYPE_DIGEST);
  31486. }
  31487. ssl->options.dontFreeDigest = 0;
  31488. ssl->buffers.digest.buffer = encodedSig;
  31489. }
  31490. break;
  31491. }
  31492. #endif /* NO_RSA */
  31493. default:
  31494. break;
  31495. } /* switch (ssl->options.sigAlgo) */
  31496. break;
  31497. }
  31498. #endif /* !defined(NO_DH) && !defined(NO_RSA) */
  31499. default:
  31500. break;
  31501. } /* switch(ssl->specs.kea) */
  31502. /* Check for error */
  31503. if (ret != 0) {
  31504. goto exit_sske;
  31505. }
  31506. /* Advance state and proceed */
  31507. ssl->options.asyncState = TLS_ASYNC_DO;
  31508. } /* case TLS_ASYNC_BUILD */
  31509. FALL_THROUGH;
  31510. case TLS_ASYNC_DO:
  31511. {
  31512. switch(ssl->specs.kea)
  31513. {
  31514. #ifndef NO_PSK
  31515. case psk_kea:
  31516. {
  31517. break;
  31518. }
  31519. #endif /* !NO_PSK */
  31520. #if !defined(NO_DH) && !defined(NO_PSK)
  31521. case dhe_psk_kea:
  31522. {
  31523. break;
  31524. }
  31525. #endif /* !defined(NO_DH) && !defined(NO_PSK) */
  31526. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  31527. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  31528. case ecdhe_psk_kea:
  31529. {
  31530. break;
  31531. }
  31532. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  31533. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  31534. defined(HAVE_CURVE448)
  31535. case ecc_diffie_hellman_kea:
  31536. {
  31537. /* Sign hash to create signature */
  31538. switch (ssl->options.sigAlgo)
  31539. {
  31540. #ifndef NO_RSA
  31541. #ifdef WC_RSA_PSS
  31542. case rsa_pss_sa_algo:
  31543. #endif
  31544. case rsa_sa_algo:
  31545. {
  31546. RsaKey* key = (RsaKey*)ssl->hsKey;
  31547. ret = RsaSign(ssl,
  31548. ssl->buffers.digest.buffer,
  31549. ssl->buffers.digest.length,
  31550. args->output + args->idx,
  31551. &args->sigSz,
  31552. ssl->options.sigAlgo, ssl->options.hashAlgo,
  31553. key,
  31554. ssl->buffers.key
  31555. );
  31556. break;
  31557. }
  31558. #endif /* !NO_RSA */
  31559. #ifdef HAVE_ECC
  31560. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  31561. case sm2_sa_algo:
  31562. {
  31563. ecc_key* key = (ecc_key*)ssl->hsKey;
  31564. ret = Sm2wSm3Sign(ssl,
  31565. TLS12_SM2_SIG_ID, TLS12_SM2_SIG_ID_SZ,
  31566. ssl->buffers.sig.buffer,
  31567. ssl->buffers.sig.length,
  31568. args->output + LENGTH_SZ + args->idx,
  31569. &args->sigSz,
  31570. key,
  31571. #ifdef HAVE_PK_CALLBACKS
  31572. ssl->buffers.key
  31573. #else
  31574. NULL
  31575. #endif
  31576. );
  31577. break;
  31578. }
  31579. #endif
  31580. case ecc_dsa_sa_algo:
  31581. {
  31582. ecc_key* key = (ecc_key*)ssl->hsKey;
  31583. ret = EccSign(ssl,
  31584. ssl->buffers.digest.buffer,
  31585. ssl->buffers.digest.length,
  31586. args->output + LENGTH_SZ + args->idx,
  31587. &args->sigSz,
  31588. key,
  31589. #ifdef HAVE_PK_CALLBACKS
  31590. ssl->buffers.key
  31591. #else
  31592. NULL
  31593. #endif
  31594. );
  31595. break;
  31596. }
  31597. #endif /* HAVE_ECC */
  31598. #ifdef HAVE_ED25519
  31599. case ed25519_sa_algo:
  31600. {
  31601. ed25519_key* key = (ed25519_key*)ssl->hsKey;
  31602. ret = Ed25519Sign(ssl,
  31603. ssl->buffers.sig.buffer,
  31604. ssl->buffers.sig.length,
  31605. args->output + LENGTH_SZ + args->idx,
  31606. &args->sigSz,
  31607. key,
  31608. #ifdef HAVE_PK_CALLBACKS
  31609. ssl->buffers.key
  31610. #else
  31611. NULL
  31612. #endif
  31613. );
  31614. break;
  31615. }
  31616. #endif
  31617. #ifdef HAVE_ED448
  31618. case ed448_sa_algo:
  31619. {
  31620. ed448_key* key = (ed448_key*)ssl->hsKey;
  31621. ret = Ed448Sign(ssl,
  31622. ssl->buffers.sig.buffer,
  31623. ssl->buffers.sig.length,
  31624. args->output + LENGTH_SZ + args->idx,
  31625. &args->sigSz,
  31626. key,
  31627. #ifdef HAVE_PK_CALLBACKS
  31628. ssl->buffers.key
  31629. #else
  31630. NULL
  31631. #endif
  31632. );
  31633. break;
  31634. }
  31635. #endif
  31636. default:
  31637. ERROR_OUT(ALGO_ID_E, exit_sske);
  31638. } /* switch(ssl->specs.sig_algo) */
  31639. break;
  31640. }
  31641. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  31642. #if !defined(NO_DH) && !defined(NO_RSA)
  31643. case diffie_hellman_kea:
  31644. {
  31645. /* Sign hash to create signature */
  31646. switch (ssl->options.sigAlgo)
  31647. {
  31648. #ifndef NO_RSA
  31649. #ifdef WC_RSA_PSS
  31650. case rsa_pss_sa_algo:
  31651. #endif
  31652. case rsa_sa_algo:
  31653. {
  31654. RsaKey* key = (RsaKey*)ssl->hsKey;
  31655. if (ssl->options.usingAnon_cipher) {
  31656. break;
  31657. }
  31658. ret = RsaSign(ssl,
  31659. ssl->buffers.digest.buffer,
  31660. ssl->buffers.digest.length,
  31661. args->output + args->idx,
  31662. &args->sigSz,
  31663. ssl->options.sigAlgo, ssl->options.hashAlgo,
  31664. key,
  31665. ssl->buffers.key
  31666. );
  31667. break;
  31668. }
  31669. #endif /* NO_RSA */
  31670. default:
  31671. break;
  31672. } /* switch (ssl->options.sigAlgo) */
  31673. break;
  31674. }
  31675. #endif /* !defined(NO_DH) && !defined(NO_RSA) */
  31676. default:
  31677. break;
  31678. } /* switch(ssl->specs.kea) */
  31679. /* Check for error */
  31680. if (ret != 0) {
  31681. goto exit_sske;
  31682. }
  31683. /* Advance state and proceed */
  31684. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  31685. } /* case TLS_ASYNC_DO */
  31686. FALL_THROUGH;
  31687. case TLS_ASYNC_VERIFY:
  31688. {
  31689. switch(ssl->specs.kea)
  31690. {
  31691. #ifndef NO_PSK
  31692. case psk_kea:
  31693. {
  31694. /* Nothing to do in this sub-state */
  31695. break;
  31696. }
  31697. #endif /* !NO_PSK */
  31698. #if !defined(NO_DH) && !defined(NO_PSK)
  31699. case dhe_psk_kea:
  31700. {
  31701. /* Nothing to do in this sub-state */
  31702. break;
  31703. }
  31704. #endif /* !defined(NO_DH) && !defined(NO_PSK) */
  31705. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  31706. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  31707. case ecdhe_psk_kea:
  31708. {
  31709. /* Nothing to do in this sub-state */
  31710. break;
  31711. }
  31712. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  31713. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  31714. defined(HAVE_CURVE448)
  31715. case ecc_diffie_hellman_kea:
  31716. {
  31717. switch(ssl->options.sigAlgo)
  31718. {
  31719. #ifndef NO_RSA
  31720. #ifdef WC_RSA_PSS
  31721. case rsa_pss_sa_algo:
  31722. #endif
  31723. case rsa_sa_algo:
  31724. {
  31725. RsaKey* key = (RsaKey*)ssl->hsKey;
  31726. if (args->verifySig == NULL) {
  31727. if (args->sigSz == 0) {
  31728. ERROR_OUT(BAD_COND_E, exit_sske);
  31729. }
  31730. args->verifySig = (byte*)XMALLOC(
  31731. args->sigSz, ssl->heap,
  31732. DYNAMIC_TYPE_SIGNATURE);
  31733. if (!args->verifySig) {
  31734. ERROR_OUT(MEMORY_E, exit_sske);
  31735. }
  31736. XMEMCPY(args->verifySig,
  31737. args->output + args->idx, args->sigSz);
  31738. }
  31739. /* check for signature faults */
  31740. ret = VerifyRsaSign(ssl,
  31741. args->verifySig, args->sigSz,
  31742. ssl->buffers.digest.buffer,
  31743. ssl->buffers.digest.length,
  31744. ssl->options.sigAlgo, ssl->options.hashAlgo,
  31745. key, ssl->buffers.key
  31746. );
  31747. break;
  31748. }
  31749. #endif
  31750. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  31751. case sm2_sa_algo:
  31752. #endif /* WOLFSSL_SM2 */
  31753. case ecc_dsa_sa_algo:
  31754. #ifdef WOLFSSL_CHECK_SIG_FAULTS
  31755. {
  31756. ecc_key* key = (ecc_key*)ssl->hsKey;
  31757. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  31758. if (ssl->options.sigAlgo == sm2_sa_algo) {
  31759. ret = Sm2wSm3Verify(ssl,
  31760. TLS12_SM2_SIG_ID, TLS12_SM2_SIG_ID_SZ,
  31761. args->output + LENGTH_SZ + args->idx,
  31762. args->sigSz,
  31763. ssl->buffers.sig.buffer,
  31764. ssl->buffers.sig.length,
  31765. key,
  31766. #ifdef HAVE_PK_CALLBACKS
  31767. ssl->buffers.key
  31768. #else
  31769. NULL
  31770. #endif
  31771. );
  31772. }
  31773. else
  31774. #endif /* WOLFSSL_SM2 */
  31775. {
  31776. ret = EccVerify(ssl,
  31777. args->output + LENGTH_SZ + args->idx,
  31778. args->sigSz,
  31779. ssl->buffers.digest.buffer,
  31780. ssl->buffers.digest.length,
  31781. key,
  31782. #ifdef HAVE_PK_CALLBACKS
  31783. ssl->buffers.key
  31784. #else
  31785. NULL
  31786. #endif
  31787. );
  31788. }
  31789. if (ret != 0) {
  31790. WOLFSSL_MSG(
  31791. "Failed to verify ECC signature");
  31792. goto exit_sske;
  31793. }
  31794. }
  31795. #if defined(HAVE_E25519) || defined(HAVE_ED448)
  31796. FALL_THROUGH;
  31797. #endif
  31798. #endif /* WOLFSSL_CHECK_SIG_FAULTS */
  31799. #ifdef HAVE_ED25519
  31800. case ed25519_sa_algo:
  31801. #endif
  31802. #ifdef HAVE_ED448
  31803. case ed448_sa_algo:
  31804. #endif
  31805. {
  31806. /* Now that we know the real sig size, write it. */
  31807. c16toa((word16)args->sigSz,
  31808. args->output + args->idx);
  31809. /* And adjust length and sendSz from estimates */
  31810. args->length += args->sigSz - args->tmpSigSz;
  31811. args->sendSz += args->sigSz - args->tmpSigSz;
  31812. break;
  31813. }
  31814. default:
  31815. ERROR_OUT(ALGO_ID_E, exit_sske); /* unsupported type */
  31816. } /* switch(ssl->specs.sig_algo) */
  31817. break;
  31818. }
  31819. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  31820. #if !defined(NO_DH) && !defined(NO_RSA)
  31821. case diffie_hellman_kea:
  31822. {
  31823. switch (ssl->options.sigAlgo)
  31824. {
  31825. #ifndef NO_RSA
  31826. #ifndef WC_RSA_PSS
  31827. case rsa_pss_sa_algo:
  31828. #endif
  31829. case rsa_sa_algo:
  31830. {
  31831. RsaKey* key = (RsaKey*)ssl->hsKey;
  31832. if (ssl->options.usingAnon_cipher) {
  31833. break;
  31834. }
  31835. if (args->verifySig == NULL) {
  31836. if (args->sigSz == 0) {
  31837. ERROR_OUT(BAD_COND_E, exit_sske);
  31838. }
  31839. args->verifySig = (byte*)XMALLOC(
  31840. args->sigSz, ssl->heap,
  31841. DYNAMIC_TYPE_SIGNATURE);
  31842. if (!args->verifySig) {
  31843. ERROR_OUT(MEMORY_E, exit_sske);
  31844. }
  31845. XMEMCPY(args->verifySig,
  31846. args->output + args->idx, args->sigSz);
  31847. }
  31848. /* check for signature faults */
  31849. ret = VerifyRsaSign(ssl,
  31850. args->verifySig, args->sigSz,
  31851. ssl->buffers.digest.buffer,
  31852. ssl->buffers.digest.length,
  31853. ssl->options.sigAlgo, ssl->options.hashAlgo,
  31854. key, ssl->buffers.key
  31855. );
  31856. break;
  31857. }
  31858. #endif
  31859. } /* switch (ssl->options.sigAlgo) */
  31860. break;
  31861. }
  31862. #endif /* !defined(NO_DH) && !defined(NO_RSA) */
  31863. default:
  31864. break;
  31865. } /* switch(ssl->specs.kea) */
  31866. /* Check for error */
  31867. if (ret != 0) {
  31868. goto exit_sske;
  31869. }
  31870. /* Advance state and proceed */
  31871. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  31872. } /* case TLS_ASYNC_VERIFY */
  31873. FALL_THROUGH;
  31874. case TLS_ASYNC_FINALIZE:
  31875. {
  31876. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  31877. defined(HAVE_CURVE448)
  31878. if (ssl->specs.kea == ecdhe_psk_kea ||
  31879. ssl->specs.kea == ecc_diffie_hellman_kea) {
  31880. /* Check output to make sure it was set */
  31881. if (args->output) {
  31882. AddHeaders(args->output, args->length,
  31883. server_key_exchange, ssl);
  31884. }
  31885. else {
  31886. ERROR_OUT(BUFFER_ERROR, exit_sske);
  31887. }
  31888. }
  31889. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  31890. /* Advance state and proceed */
  31891. ssl->options.asyncState = TLS_ASYNC_END;
  31892. } /* case TLS_ASYNC_FINALIZE */
  31893. FALL_THROUGH;
  31894. case TLS_ASYNC_END:
  31895. {
  31896. ret = SendHandshakeMsg(ssl, args->output, args->length,
  31897. server_key_exchange, "ServerKeyExchange");
  31898. if (ret != 0)
  31899. goto exit_sske;
  31900. ssl->options.serverState = SERVER_KEYEXCHANGE_COMPLETE;
  31901. break;
  31902. }
  31903. default:
  31904. ret = INPUT_CASE_ERROR;
  31905. } /* switch(ssl->options.asyncState) */
  31906. exit_sske:
  31907. #ifdef WOLFSSL_BLIND_PRIVATE_KEY
  31908. if (ret == 0) {
  31909. ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
  31910. &ssl->buffers.keyMask);
  31911. }
  31912. else {
  31913. wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask);
  31914. }
  31915. #endif
  31916. WOLFSSL_LEAVE("SendServerKeyExchange", ret);
  31917. WOLFSSL_END(WC_FUNC_SERVER_KEY_EXCHANGE_SEND);
  31918. #ifdef WOLFSSL_ASYNC_IO
  31919. /* Handle async operation */
  31920. if (ret == WC_NO_ERR_TRACE(WANT_WRITE)
  31921. #ifdef WOLFSSL_ASYNC_CRYPT
  31922. || ret == WC_NO_ERR_TRACE(WC_PENDING_E)
  31923. #endif
  31924. )
  31925. return ret;
  31926. #endif /* WOLFSSL_ASYNC_IO */
  31927. /* Final cleanup */
  31928. if (
  31929. #ifdef WOLFSSL_ASYNC_IO
  31930. args != NULL &&
  31931. #endif
  31932. args->input != NULL) {
  31933. XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  31934. args->input = NULL;
  31935. }
  31936. #ifdef WOLFSSL_ASYNC_IO
  31937. /* Cleanup async */
  31938. FreeAsyncCtx(ssl, 0);
  31939. #else
  31940. FreeSskeArgs(ssl, args);
  31941. #endif
  31942. FreeKeyExchange(ssl);
  31943. if (ret != 0) {
  31944. WOLFSSL_ERROR_VERBOSE(ret);
  31945. }
  31946. return ret;
  31947. }
  31948. #endif /* !WOLFSSL_NO_TLS12 */
  31949. /* Make sure server cert/key are valid for this suite, true on success
  31950. * Returns 1 for valid server suite or 0 if not found
  31951. * For asynchronous this can return WC_PENDING_E
  31952. */
  31953. static int VerifyServerSuite(const WOLFSSL* ssl, const Suites* suites,
  31954. word16 idx, CipherSuite* cs, TLSX* extensions)
  31955. {
  31956. #ifndef NO_PSK
  31957. int havePSK = ssl->options.havePSK;
  31958. #endif
  31959. byte first;
  31960. byte second;
  31961. (void)cs;
  31962. (void)extensions;
  31963. WOLFSSL_ENTER("VerifyServerSuite");
  31964. if (suites == NULL) {
  31965. WOLFSSL_MSG("Suites pointer error");
  31966. return 0;
  31967. }
  31968. first = suites->suites[idx];
  31969. second = suites->suites[idx+1];
  31970. if (CipherRequires(first, second, REQUIRES_RSA)) {
  31971. WOLFSSL_MSG("Requires RSA");
  31972. if (ssl->options.haveRSA == 0) {
  31973. WOLFSSL_MSG("Don't have RSA");
  31974. return 0;
  31975. }
  31976. }
  31977. if (CipherRequires(first, second, REQUIRES_DHE)) {
  31978. WOLFSSL_MSG("Requires DHE");
  31979. if (ssl->options.haveDH == 0) {
  31980. WOLFSSL_MSG("Don't have DHE");
  31981. return 0;
  31982. }
  31983. }
  31984. if (CipherRequires(first, second, REQUIRES_ECC)) {
  31985. WOLFSSL_MSG("Requires ECC");
  31986. if (ssl->options.haveECC == 0) {
  31987. WOLFSSL_MSG("Don't have ECC");
  31988. return 0;
  31989. }
  31990. }
  31991. if (CipherRequires(first, second, REQUIRES_ECC_STATIC)) {
  31992. WOLFSSL_MSG("Requires static ECC");
  31993. if (ssl->options.haveStaticECC == 0) {
  31994. WOLFSSL_MSG("Don't have static ECC");
  31995. return 0;
  31996. }
  31997. }
  31998. if (CipherRequires(first, second, REQUIRES_PSK)) {
  31999. WOLFSSL_MSG("Requires PSK");
  32000. #ifndef NO_PSK
  32001. if (havePSK == 0)
  32002. #endif
  32003. {
  32004. WOLFSSL_MSG("Don't have PSK");
  32005. return 0;
  32006. }
  32007. }
  32008. if (CipherRequires(first, second, REQUIRES_RSA_SIG)) {
  32009. WOLFSSL_MSG("Requires RSA Signature");
  32010. if (ssl->options.side == WOLFSSL_SERVER_END &&
  32011. ssl->options.haveECDSAsig == 1) {
  32012. WOLFSSL_MSG("Don't have RSA Signature");
  32013. return 0;
  32014. }
  32015. }
  32016. #if !defined(WOLFSSL_OLDTLS_AEAD_CIPHERSUITES)
  32017. if (CipherRequires(first, second, REQUIRES_AEAD)) {
  32018. WOLFSSL_MSG("Requires AEAD");
  32019. if (ssl->version.major == SSLv3_MAJOR &&
  32020. ssl->version.minor < TLSv1_2_MINOR) {
  32021. WOLFSSL_MSG("Version of SSL does not support AEAD ciphers");
  32022. return 0;
  32023. }
  32024. }
  32025. #endif
  32026. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  32027. defined(HAVE_CURVE448)) && defined(HAVE_SUPPORTED_CURVES)
  32028. if (!TLSX_ValidateSupportedCurves(ssl, first, second,
  32029. &cs->ecdhCurveOID)) {
  32030. WOLFSSL_MSG("Don't have matching curves");
  32031. return 0;
  32032. }
  32033. #endif
  32034. #ifdef WOLFSSL_TLS13
  32035. if (IsAtLeastTLSv1_3(ssl->version) &&
  32036. ssl->options.side == WOLFSSL_SERVER_END) {
  32037. #ifdef HAVE_SUPPORTED_CURVES
  32038. byte searched = 0;
  32039. int ret = TLSX_KeyShare_Choose(ssl, extensions, first, second,
  32040. &cs->clientKSE, &searched);
  32041. if (ret == WC_NO_ERR_TRACE(MEMORY_E)) {
  32042. WOLFSSL_MSG("TLSX_KeyShare_Choose() failed in "
  32043. "VerifyServerSuite() with MEMORY_E");
  32044. return 0;
  32045. }
  32046. if (cs->clientKSE == NULL && searched) {
  32047. #ifdef WOLFSSL_SEND_HRR_COOKIE
  32048. /* If the CH contains a cookie then we need to send an alert to
  32049. * start from scratch. */
  32050. if (TLSX_Find(extensions, TLSX_COOKIE) != NULL)
  32051. return INVALID_PARAMETER;
  32052. #endif
  32053. cs->doHelloRetry = 1;
  32054. }
  32055. #ifdef WOLFSSL_ASYNC_CRYPT
  32056. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
  32057. return ret;
  32058. #endif
  32059. if (!cs->doHelloRetry && ret != 0)
  32060. return 0; /* not found */
  32061. #endif /* HAVE_SUPPORTED_CURVES */
  32062. }
  32063. else if ((first == TLS13_BYTE) || ((first == ECC_BYTE) &&
  32064. ((second == TLS_SHA256_SHA256) ||
  32065. (second == TLS_SHA384_SHA384))) ||
  32066. ((first == CIPHER_BYTE) && ((second == TLS_SM4_GCM_SM3) ||
  32067. (second == TLS_SM4_CCM_SM3)))) {
  32068. /* Can't negotiate TLS 1.3 cipher suites with lower protocol
  32069. * version. */
  32070. return 0;
  32071. }
  32072. #endif /* WOLFSSL_TLS13 */
  32073. return 1;
  32074. }
  32075. static int CompareSuites(const WOLFSSL* ssl, const Suites* suites,
  32076. Suites* peerSuites, word16 i, word16 j,
  32077. CipherSuite* cs, TLSX* extensions)
  32078. {
  32079. if (suites->suites[i] == peerSuites->suites[j] &&
  32080. suites->suites[i+1] == peerSuites->suites[j+1] ) {
  32081. int ret = VerifyServerSuite(ssl, suites, i, cs, extensions);
  32082. if (ret < 0) {
  32083. return ret;
  32084. }
  32085. if (ret) {
  32086. WOLFSSL_MSG("Verified suite validity");
  32087. cs->cipherSuite0 = suites->suites[i];
  32088. cs->cipherSuite = suites->suites[i+1];
  32089. return 0;
  32090. }
  32091. else {
  32092. WOLFSSL_MSG("Could not verify suite validity, continue");
  32093. }
  32094. }
  32095. return MATCH_SUITE_ERROR;
  32096. }
  32097. int MatchSuite_ex(const WOLFSSL* ssl, Suites* peerSuites, CipherSuite* cs,
  32098. TLSX* extensions)
  32099. {
  32100. int ret;
  32101. word16 i, j;
  32102. const Suites* suites = WOLFSSL_SUITES(ssl);
  32103. WOLFSSL_ENTER("MatchSuite");
  32104. /* & 0x1 equivalent % 2 */
  32105. if (peerSuites->suiteSz == 0 || peerSuites->suiteSz & 0x1)
  32106. return BUFFER_ERROR;
  32107. if (suites == NULL)
  32108. return SUITES_ERROR;
  32109. if (!ssl->options.useClientOrder) {
  32110. /* Server order */
  32111. for (i = 0; i < suites->suiteSz; i += 2) {
  32112. for (j = 0; j < peerSuites->suiteSz; j += 2) {
  32113. ret = CompareSuites(ssl, suites, peerSuites, i, j, cs, extensions);
  32114. if (ret != WC_NO_ERR_TRACE(MATCH_SUITE_ERROR))
  32115. return ret;
  32116. }
  32117. }
  32118. }
  32119. else {
  32120. /* Client order */
  32121. for (j = 0; j < peerSuites->suiteSz; j += 2) {
  32122. for (i = 0; i < suites->suiteSz; i += 2) {
  32123. ret = CompareSuites(ssl, suites, peerSuites, i, j, cs, extensions);
  32124. if (ret != WC_NO_ERR_TRACE(MATCH_SUITE_ERROR))
  32125. return ret;
  32126. }
  32127. }
  32128. }
  32129. WOLFSSL_ERROR_VERBOSE(MATCH_SUITE_ERROR);
  32130. return MATCH_SUITE_ERROR;
  32131. }
  32132. int MatchSuite(WOLFSSL* ssl, Suites* peerSuites)
  32133. {
  32134. int ret;
  32135. CipherSuite cs;
  32136. XMEMSET(&cs, 0, sizeof(cs));
  32137. ret = MatchSuite_ex(ssl, peerSuites, &cs,
  32138. #ifdef HAVE_TLS_EXTENSIONS
  32139. ssl->extensions
  32140. #else
  32141. NULL
  32142. #endif
  32143. );
  32144. if (ret != 0)
  32145. return ret;
  32146. ssl->options.cipherSuite0 = cs.cipherSuite0;
  32147. ssl->options.cipherSuite = cs.cipherSuite;
  32148. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_CURVE25519) || \
  32149. defined(HAVE_ED448) || defined(HAVE_CURVE448)
  32150. ssl->ecdhCurveOID = cs.ecdhCurveOID;
  32151. #endif
  32152. ret = SetCipherSpecs(ssl);
  32153. if (ret != 0)
  32154. return ret;
  32155. ret = PickHashSigAlgo(ssl, peerSuites->hashSigAlgo,
  32156. peerSuites->hashSigAlgoSz, 1);
  32157. if (ret != 0)
  32158. return ret;
  32159. #if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
  32160. if (cs.doHelloRetry) {
  32161. /* Make sure we don't send HRR twice */
  32162. if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
  32163. return INVALID_PARAMETER;
  32164. ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
  32165. return TLSX_KeyShare_SetSupported(ssl, &ssl->extensions);
  32166. }
  32167. #endif
  32168. #if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
  32169. if (IsAtLeastTLSv1_3(ssl->version) &&
  32170. ssl->options.side == WOLFSSL_SERVER_END) {
  32171. ret = TLSX_KeyShare_Setup(ssl, cs.clientKSE);
  32172. if (ret != 0)
  32173. return ret;
  32174. }
  32175. #endif
  32176. return ret;
  32177. }
  32178. #ifdef OLD_HELLO_ALLOWED
  32179. /* process old style client hello, deprecate? */
  32180. int ProcessOldClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  32181. word32 inSz, word16 sz)
  32182. {
  32183. word32 idx = *inOutIdx;
  32184. word16 sessionSz;
  32185. word16 randomSz;
  32186. word16 i, j;
  32187. ProtocolVersion pv;
  32188. Suites clSuites;
  32189. int ret = -1;
  32190. (void)inSz;
  32191. WOLFSSL_MSG("Got old format client hello");
  32192. #ifdef WOLFSSL_CALLBACKS
  32193. if (ssl->hsInfoOn)
  32194. AddPacketName(ssl, "ClientHello");
  32195. if (ssl->toInfoOn)
  32196. AddLateName("ClientHello", &ssl->timeoutInfo);
  32197. #endif
  32198. /* manually hash input since different format */
  32199. #ifndef NO_OLD_TLS
  32200. #ifndef NO_MD5
  32201. wc_Md5Update(&ssl->hsHashes->hashMd5, input + idx, sz);
  32202. #endif
  32203. #ifndef NO_SHA
  32204. wc_ShaUpdate(&ssl->hsHashes->hashSha, input + idx, sz);
  32205. #endif
  32206. #endif /* !NO_OLD_TLS */
  32207. #ifndef NO_SHA256
  32208. if (IsAtLeastTLSv1_2(ssl)) {
  32209. int shaRet = wc_Sha256Update(&ssl->hsHashes->hashSha256,
  32210. input + idx, sz);
  32211. if (shaRet != 0)
  32212. return shaRet;
  32213. }
  32214. #endif
  32215. /* does this value mean client_hello? */
  32216. idx++;
  32217. /* version */
  32218. pv.major = input[idx++];
  32219. pv.minor = input[idx++];
  32220. ssl->chVersion = pv; /* store */
  32221. if (ssl->version.minor > pv.minor) {
  32222. byte haveRSA = 0;
  32223. byte havePSK = 0;
  32224. int keySz = 0;
  32225. if (!ssl->options.downgrade) {
  32226. WOLFSSL_MSG("Client trying to connect with lesser version");
  32227. return VERSION_ERROR;
  32228. }
  32229. if (pv.minor < ssl->options.minDowngrade) {
  32230. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  32231. return VERSION_ERROR;
  32232. }
  32233. if (pv.minor == SSLv3_MINOR) {
  32234. /* turn off tls */
  32235. WOLFSSL_MSG("\tdowngrading to SSLv3");
  32236. ssl->options.tls = 0;
  32237. ssl->options.tls1_1 = 0;
  32238. ssl->version.minor = SSLv3_MINOR;
  32239. }
  32240. else if (pv.minor == TLSv1_MINOR) {
  32241. WOLFSSL_MSG("\tdowngrading to TLSv1");
  32242. /* turn off tls 1.1+ */
  32243. ssl->options.tls1_1 = 0;
  32244. ssl->version.minor = TLSv1_MINOR;
  32245. }
  32246. else if (pv.minor == TLSv1_1_MINOR) {
  32247. WOLFSSL_MSG("\tdowngrading to TLSv1.1");
  32248. ssl->version.minor = TLSv1_1_MINOR;
  32249. }
  32250. else if (pv.minor == TLSv1_2_MINOR) {
  32251. WOLFSSL_MSG(" downgrading to TLSv1.2");
  32252. ssl->version.minor = TLSv1_2_MINOR;
  32253. }
  32254. #ifndef NO_RSA
  32255. haveRSA = 1;
  32256. #endif
  32257. #ifndef NO_PSK
  32258. havePSK = ssl->options.havePSK;
  32259. #endif
  32260. #ifndef NO_CERTS
  32261. keySz = ssl->buffers.keySz;
  32262. #endif
  32263. ret = AllocateSuites(ssl);
  32264. if (ret != 0)
  32265. return ret;
  32266. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
  32267. ssl->options.haveDH, ssl->options.haveECDSAsig,
  32268. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  32269. ssl->options.haveFalconSig,
  32270. ssl->options.haveDilithiumSig, ssl->options.useAnon,
  32271. TRUE, ssl->options.side);
  32272. }
  32273. /* suite size */
  32274. ato16(&input[idx], &clSuites.suiteSz);
  32275. idx += OPAQUE16_LEN;
  32276. if (clSuites.suiteSz > WOLFSSL_MAX_SUITE_SZ)
  32277. return BUFFER_ERROR;
  32278. /* Make sure the suiteSz is a multiple of 3. (Old Client Hello) */
  32279. if (clSuites.suiteSz % 3 != 0)
  32280. return BUFFER_ERROR;
  32281. clSuites.hashSigAlgoSz = 0;
  32282. /* session size */
  32283. ato16(&input[idx], &sessionSz);
  32284. idx += OPAQUE16_LEN;
  32285. if (sessionSz > ID_LEN)
  32286. return BUFFER_ERROR;
  32287. /* random size */
  32288. ato16(&input[idx], &randomSz);
  32289. idx += OPAQUE16_LEN;
  32290. if (randomSz > RAN_LEN)
  32291. return BUFFER_ERROR;
  32292. /* suites */
  32293. for (i = 0, j = 0; i < clSuites.suiteSz; i += 3) {
  32294. byte first = input[idx++];
  32295. if (!first) { /* implicit: skip sslv2 type */
  32296. XMEMCPY(&clSuites.suites[j], &input[idx], SUITE_LEN);
  32297. j += SUITE_LEN;
  32298. }
  32299. idx += SUITE_LEN;
  32300. }
  32301. clSuites.suiteSz = j;
  32302. /* session id */
  32303. if (sessionSz) {
  32304. XMEMCPY(ssl->arrays->sessionID, input + idx, sessionSz);
  32305. ssl->arrays->sessionIDSz = (byte)sessionSz;
  32306. idx += sessionSz;
  32307. ssl->options.resuming = 1;
  32308. }
  32309. /* random */
  32310. if (randomSz < RAN_LEN)
  32311. XMEMSET(ssl->arrays->clientRandom, 0, RAN_LEN - randomSz);
  32312. XMEMCPY(&ssl->arrays->clientRandom[RAN_LEN - randomSz], input + idx,
  32313. randomSz);
  32314. idx += randomSz;
  32315. if (ssl->options.usingCompression)
  32316. ssl->options.usingCompression = 0; /* turn off */
  32317. ssl->options.clientState = CLIENT_HELLO_COMPLETE;
  32318. ssl->cbmode = SSL_CB_MODE_WRITE;
  32319. *inOutIdx = idx;
  32320. ssl->options.haveSessionId = 1;
  32321. /* DoClientHello uses same resume code */
  32322. if (ssl->options.resuming) { /* let's try */
  32323. WOLFSSL_SESSION* session;
  32324. #ifdef HAVE_SESSION_TICKET
  32325. if (ssl->options.useTicket == 1) {
  32326. session = ssl->session;
  32327. }
  32328. else
  32329. #endif
  32330. {
  32331. session = wolfSSL_GetSession(ssl, ssl->arrays->masterSecret, 1);
  32332. }
  32333. if (!session) {
  32334. WOLFSSL_MSG("Session lookup for resume failed");
  32335. ssl->options.resuming = 0;
  32336. } else {
  32337. if (MatchSuite(ssl, &clSuites) < 0) {
  32338. WOLFSSL_MSG("Unsupported cipher suite, OldClientHello");
  32339. return UNSUPPORTED_SUITE;
  32340. }
  32341. ret = wc_RNG_GenerateBlock(ssl->rng, ssl->arrays->serverRandom,
  32342. RAN_LEN);
  32343. if (ret != 0)
  32344. return ret;
  32345. #ifdef NO_OLD_TLS
  32346. ret = DeriveTlsKeys(ssl);
  32347. #else
  32348. #ifndef NO_TLS
  32349. if (ssl->options.tls)
  32350. ret = DeriveTlsKeys(ssl);
  32351. #endif
  32352. if (!ssl->options.tls)
  32353. ret = DeriveKeys(ssl);
  32354. #endif
  32355. /* SERVER: peer auth based on session secret. */
  32356. ssl->options.peerAuthGood = (ret == 0);
  32357. ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
  32358. return ret;
  32359. }
  32360. }
  32361. ret = MatchSuite(ssl, &clSuites);
  32362. if (ret != 0)return ret;
  32363. return SanityCheckMsgReceived(ssl, client_hello);
  32364. }
  32365. #endif /* OLD_HELLO_ALLOWED */
  32366. #ifndef WOLFSSL_NO_TLS12
  32367. /**
  32368. * Handles session resumption.
  32369. * Session tickets are checked for validity based on the time each ticket
  32370. * was created, timeout value and the current time. If the tickets are
  32371. * judged expired, falls back to full-handshake. If you want disable this
  32372. * session ticket validation check in TLS1.2 and below, define
  32373. * WOLFSSL_NO_TICKET_EXPIRE.
  32374. */
  32375. int HandleTlsResumption(WOLFSSL* ssl, Suites* clSuites)
  32376. {
  32377. int ret = 0;
  32378. WOLFSSL_SESSION* session;
  32379. #ifdef HAVE_SECRET_CALLBACK
  32380. if (ssl->sessionSecretCb != NULL
  32381. #ifdef HAVE_SESSION_TICKET
  32382. && ssl->session->ticketLen > 0
  32383. #endif
  32384. ) {
  32385. int secretSz = SECRET_LEN;
  32386. WOLFSSL_MSG("Calling session secret callback");
  32387. ret = wc_RNG_GenerateBlock(ssl->rng, ssl->arrays->serverRandom,
  32388. RAN_LEN);
  32389. if (ret == 0) {
  32390. ret = ssl->sessionSecretCb(ssl, ssl->arrays->masterSecret,
  32391. &secretSz, ssl->sessionSecretCtx);
  32392. if (secretSz != SECRET_LEN)
  32393. ret = SESSION_SECRET_CB_E;
  32394. }
  32395. if (ret == 0)
  32396. ret = MatchSuite(ssl, clSuites);
  32397. if (ret == 0) {
  32398. #ifdef NO_OLD_TLS
  32399. ret = DeriveTlsKeys(ssl);
  32400. #else
  32401. #ifndef NO_TLS
  32402. if (ssl->options.tls)
  32403. ret = DeriveTlsKeys(ssl);
  32404. #endif
  32405. if (!ssl->options.tls)
  32406. ret = DeriveKeys(ssl);
  32407. #endif
  32408. /* SERVER: peer auth based on session secret. */
  32409. ssl->options.peerAuthGood = (ret == 0);
  32410. ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
  32411. }
  32412. if (ret != 0)
  32413. WOLFSSL_ERROR_VERBOSE(ret);
  32414. WOLFSSL_LEAVE("HandleTlsResumption", ret);
  32415. return ret;
  32416. }
  32417. #endif /* HAVE_SECRET_CALLBACK */
  32418. #ifdef HAVE_SESSION_TICKET
  32419. if (ssl->options.useTicket == 1) {
  32420. session = ssl->session;
  32421. }
  32422. else
  32423. #endif
  32424. {
  32425. session = wolfSSL_GetSession(ssl, ssl->arrays->masterSecret, 1);
  32426. }
  32427. if (!session) {
  32428. WOLFSSL_MSG("Session lookup for resume failed");
  32429. ssl->options.resuming = 0;
  32430. return ret;
  32431. }
  32432. #if !defined(WOLFSSL_NO_TICKET_EXPIRE) && !defined(NO_ASN_TIME)
  32433. /* check if the ticket is valid */
  32434. if (LowResTimer() > session->bornOn + ssl->timeout) {
  32435. WOLFSSL_MSG("Expired session, fall back to full handshake.");
  32436. ssl->options.resuming = 0;
  32437. }
  32438. #endif /* !WOLFSSL_NO_TICKET_EXPIRE && !NO_ASN_TIME */
  32439. else if (session->haveEMS != ssl->options.haveEMS) {
  32440. /* RFC 7627, 5.3, server-side */
  32441. /* if old sess didn't have EMS, but new does, full handshake */
  32442. if (!session->haveEMS && ssl->options.haveEMS) {
  32443. WOLFSSL_MSG("Attempting to resume a session that didn't "
  32444. "use EMS with a new session with EMS. Do full "
  32445. "handshake.");
  32446. ssl->options.resuming = 0;
  32447. }
  32448. /* if old sess used EMS, but new doesn't, MUST abort */
  32449. else if (session->haveEMS && !ssl->options.haveEMS) {
  32450. WOLFSSL_MSG("Trying to resume a session with EMS without "
  32451. "using EMS");
  32452. #ifdef WOLFSSL_EXTRA_ALERTS
  32453. SendAlert(ssl, alert_fatal, handshake_failure);
  32454. #endif
  32455. ret = EXT_MASTER_SECRET_NEEDED_E;
  32456. WOLFSSL_ERROR_VERBOSE(ret);
  32457. }
  32458. }
  32459. else {
  32460. #ifndef NO_RESUME_SUITE_CHECK
  32461. int j;
  32462. /* Check client suites include the one in session */
  32463. for (j = 0; j < clSuites->suiteSz; j += 2) {
  32464. if (clSuites->suites[j] == session->cipherSuite0 &&
  32465. clSuites->suites[j+1] == session->cipherSuite) {
  32466. break;
  32467. }
  32468. }
  32469. if (j == clSuites->suiteSz) {
  32470. WOLFSSL_MSG("Prev session's cipher suite not in ClientHello");
  32471. #ifdef WOLFSSL_EXTRA_ALERTS
  32472. SendAlert(ssl, alert_fatal, illegal_parameter);
  32473. #endif
  32474. ret = UNSUPPORTED_SUITE;
  32475. WOLFSSL_ERROR_VERBOSE(ret);
  32476. }
  32477. #endif
  32478. if (ret == 0 && ssl->options.resuming) {
  32479. /* for resumption use the cipher suite from session */
  32480. ssl->options.cipherSuite0 = session->cipherSuite0;
  32481. ssl->options.cipherSuite = session->cipherSuite;
  32482. ret = SetCipherSpecs(ssl);
  32483. if (ret == 0) {
  32484. ret = PickHashSigAlgo(ssl, clSuites->hashSigAlgo,
  32485. clSuites->hashSigAlgoSz, 0);
  32486. }
  32487. }
  32488. else if (ret == 0) {
  32489. if (MatchSuite(ssl, clSuites) < 0) {
  32490. WOLFSSL_MSG("Unsupported cipher suite, ClientHello");
  32491. ret = UNSUPPORTED_SUITE;
  32492. WOLFSSL_ERROR_VERBOSE(ret);
  32493. }
  32494. }
  32495. if (ret == 0) {
  32496. ret = wc_RNG_GenerateBlock(ssl->rng,
  32497. ssl->arrays->serverRandom, RAN_LEN);
  32498. }
  32499. if (ret == 0) {
  32500. #ifdef NO_OLD_TLS
  32501. ret = DeriveTlsKeys(ssl);
  32502. #else
  32503. #ifndef NO_TLS
  32504. if (ssl->options.tls)
  32505. ret = DeriveTlsKeys(ssl);
  32506. #endif
  32507. if (!ssl->options.tls)
  32508. ret = DeriveKeys(ssl);
  32509. #endif
  32510. /* SERVER: peer auth based on session secret. */
  32511. ssl->options.peerAuthGood = (ret == 0);
  32512. ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
  32513. }
  32514. }
  32515. return ret;
  32516. }
  32517. /* handle processing of client_hello (1) */
  32518. int DoClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  32519. word32 helloSz)
  32520. {
  32521. byte b;
  32522. ProtocolVersion pv;
  32523. #ifdef WOLFSSL_SMALL_STACK
  32524. Suites* clSuites = NULL;
  32525. #else
  32526. Suites clSuites[1];
  32527. #endif
  32528. word32 i = *inOutIdx;
  32529. word32 begin = i;
  32530. int ret = 0;
  32531. byte lesserVersion;
  32532. WOLFSSL_START(WC_FUNC_CLIENT_HELLO_DO);
  32533. WOLFSSL_ENTER("DoClientHello");
  32534. #ifdef WOLFSSL_CALLBACKS
  32535. if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
  32536. if (ssl->toInfoOn) AddLateName("ClientHello", &ssl->timeoutInfo);
  32537. #endif
  32538. /* do not change state in the SSL object before the next region of code
  32539. * to be able to statelessly compute a DTLS cookie */
  32540. #ifdef WOLFSSL_DTLS
  32541. /* Update the ssl->options.dtlsStateful setting `if` statement in
  32542. * wolfSSL_accept when changing this one. */
  32543. if (IsDtlsNotSctpMode(ssl) && IsDtlsNotSrtpMode(ssl) && !IsSCR(ssl) &&
  32544. !ssl->options.dtlsStateful) {
  32545. DtlsSetSeqNumForReply(ssl);
  32546. ret = DoClientHelloStateless(ssl, input + *inOutIdx, helloSz, 0,
  32547. NULL);
  32548. if (ret != 0 || !ssl->options.dtlsStateful) {
  32549. int alertType = TranslateErrorToAlert(ret);
  32550. if (alertType != invalid_alert) {
  32551. int err;
  32552. /* propagate socket errors to avoid re-calling send alert */
  32553. err = SendAlert(ssl, alert_fatal, alertType);
  32554. if (err == WC_NO_ERR_TRACE(SOCKET_ERROR_E))
  32555. ret = SOCKET_ERROR_E;
  32556. }
  32557. *inOutIdx += helloSz;
  32558. DtlsResetState(ssl);
  32559. if (DtlsIgnoreError(ret))
  32560. ret = 0;
  32561. return ret;
  32562. }
  32563. if (ssl->chGoodCb != NULL) {
  32564. int cbret = ssl->chGoodCb(ssl, ssl->chGoodCtx);
  32565. if (cbret < 0) {
  32566. ssl->error = cbret;
  32567. WOLFSSL_MSG("ClientHello Good Cb don't continue error");
  32568. return WOLFSSL_FATAL_ERROR;
  32569. }
  32570. }
  32571. }
  32572. ssl->options.dtlsStateful = 1;
  32573. #endif /* WOLFSSL_DTLS */
  32574. /* Reset to sane value for SCR */
  32575. ssl->options.resuming = 0;
  32576. ssl->arrays->sessionIDSz = 0;
  32577. /* protocol version, random and session id length check */
  32578. if (OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz)
  32579. return BUFFER_ERROR;
  32580. /* protocol version */
  32581. XMEMCPY(&pv, input + i, OPAQUE16_LEN);
  32582. ssl->chVersion = pv; /* store */
  32583. i += OPAQUE16_LEN;
  32584. /* Legacy protocol version cannot negotiate TLS 1.3 or higher. */
  32585. if (pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_3_MINOR)
  32586. pv.minor = TLSv1_2_MINOR;
  32587. lesserVersion = !ssl->options.dtls && ssl->version.minor > pv.minor;
  32588. lesserVersion |= ssl->options.dtls && ssl->version.minor < pv.minor;
  32589. if (lesserVersion) {
  32590. byte belowMinDowngrade;
  32591. word16 haveRSA = 0;
  32592. word16 havePSK = 0;
  32593. int keySz = 0;
  32594. if (!ssl->options.downgrade) {
  32595. WOLFSSL_MSG("Client trying to connect with lesser version");
  32596. ret = VERSION_ERROR;
  32597. goto out;
  32598. }
  32599. belowMinDowngrade = pv.minor < ssl->options.minDowngrade;
  32600. /* DTLS versions increase backwards (-1,-2,-3) ecc */
  32601. if (ssl->options.dtls)
  32602. belowMinDowngrade = ssl->options.dtls
  32603. && pv.minor > ssl->options.minDowngrade;
  32604. if (belowMinDowngrade) {
  32605. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  32606. ret = VERSION_ERROR;
  32607. goto out;
  32608. }
  32609. if (!ssl->options.dtls) {
  32610. if (pv.minor == SSLv3_MINOR) {
  32611. /* turn off tls */
  32612. WOLFSSL_MSG("\tdowngrading to SSLv3");
  32613. ssl->options.tls = 0;
  32614. ssl->options.tls1_1 = 0;
  32615. ssl->version.minor = SSLv3_MINOR;
  32616. }
  32617. else if (pv.minor == TLSv1_MINOR) {
  32618. /* turn off tls 1.1+ */
  32619. WOLFSSL_MSG("\tdowngrading to TLSv1");
  32620. ssl->options.tls1_1 = 0;
  32621. ssl->version.minor = TLSv1_MINOR;
  32622. }
  32623. else if (pv.minor == TLSv1_1_MINOR) {
  32624. WOLFSSL_MSG("\tdowngrading to TLSv1.1");
  32625. ssl->version.minor = TLSv1_1_MINOR;
  32626. }
  32627. else if (pv.minor == TLSv1_2_MINOR) {
  32628. WOLFSSL_MSG(" downgrading to TLSv1.2");
  32629. ssl->version.minor = TLSv1_2_MINOR;
  32630. }
  32631. }
  32632. else {
  32633. if (pv.minor == DTLSv1_2_MINOR) {
  32634. WOLFSSL_MSG("\tDowngrading to DTLSv1.2");
  32635. ssl->options.tls1_3 = 0;
  32636. ssl->version.minor = DTLSv1_2_MINOR;
  32637. }
  32638. else if (pv.minor == DTLS_MINOR) {
  32639. WOLFSSL_MSG("\tDowngrading to DTLSv1.0");
  32640. ssl->options.tls1_3 = 0;
  32641. ssl->version.minor = DTLS_MINOR;
  32642. }
  32643. }
  32644. #ifndef NO_RSA
  32645. haveRSA = 1;
  32646. #endif
  32647. #ifndef NO_PSK
  32648. havePSK = ssl->options.havePSK;
  32649. #endif
  32650. #ifndef NO_CERTS
  32651. keySz = ssl->buffers.keySz;
  32652. #endif
  32653. ret = AllocateSuites(ssl);
  32654. if (ret != 0)
  32655. goto out;
  32656. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
  32657. ssl->options.haveDH, ssl->options.haveECDSAsig,
  32658. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  32659. ssl->options.haveFalconSig,
  32660. ssl->options.haveDilithiumSig, ssl->options.useAnon,
  32661. TRUE, ssl->options.side);
  32662. }
  32663. /* check if option is set to not allow the current version
  32664. * set from either wolfSSL_set_options or wolfSSL_CTX_set_options */
  32665. if (!ssl->options.dtls && ssl->options.downgrade &&
  32666. ssl->options.mask > 0) {
  32667. int reset = 0;
  32668. if (ssl->version.minor == TLSv1_2_MINOR &&
  32669. (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) ==
  32670. WOLFSSL_OP_NO_TLSv1_2) {
  32671. WOLFSSL_MSG("\tOption set to not allow TLSv1.2, Downgrading");
  32672. ssl->version.minor = TLSv1_1_MINOR;
  32673. reset = 1;
  32674. }
  32675. if (ssl->version.minor == TLSv1_1_MINOR &&
  32676. (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) ==
  32677. WOLFSSL_OP_NO_TLSv1_1) {
  32678. WOLFSSL_MSG("\tOption set to not allow TLSv1.1, Downgrading");
  32679. ssl->options.tls1_1 = 0;
  32680. ssl->version.minor = TLSv1_MINOR;
  32681. reset = 1;
  32682. }
  32683. if (ssl->version.minor == TLSv1_MINOR &&
  32684. (ssl->options.mask & WOLFSSL_OP_NO_TLSv1) ==
  32685. WOLFSSL_OP_NO_TLSv1) {
  32686. WOLFSSL_MSG("\tOption set to not allow TLSv1, Downgrading");
  32687. ssl->options.tls = 0;
  32688. ssl->options.tls1_1 = 0;
  32689. ssl->version.minor = SSLv3_MINOR;
  32690. reset = 1;
  32691. }
  32692. if (ssl->version.minor == SSLv3_MINOR &&
  32693. (ssl->options.mask & WOLFSSL_OP_NO_SSLv3) ==
  32694. WOLFSSL_OP_NO_SSLv3) {
  32695. WOLFSSL_MSG("\tError, option set to not allow SSLv3");
  32696. ret = VERSION_ERROR;
  32697. #ifdef WOLFSSL_EXTRA_ALERTS
  32698. SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
  32699. #endif
  32700. goto out;
  32701. }
  32702. if (ssl->version.minor < ssl->options.minDowngrade) {
  32703. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  32704. ret = VERSION_ERROR;
  32705. goto out;
  32706. }
  32707. if (reset) {
  32708. word16 haveRSA = 0;
  32709. word16 havePSK = 0;
  32710. int keySz = 0;
  32711. #ifndef NO_RSA
  32712. haveRSA = 1;
  32713. #endif
  32714. #ifndef NO_PSK
  32715. havePSK = ssl->options.havePSK;
  32716. #endif
  32717. #ifndef NO_CERTS
  32718. keySz = ssl->buffers.keySz;
  32719. #endif
  32720. ret = AllocateSuites(ssl);
  32721. if (ret != 0)
  32722. goto out;
  32723. /* reset cipher suites to account for TLS version change */
  32724. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
  32725. ssl->options.haveDH, ssl->options.haveECDSAsig,
  32726. ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
  32727. ssl->options.haveFalconSig,
  32728. ssl->options.haveDilithiumSig, ssl->options.useAnon,
  32729. TRUE, ssl->options.side);
  32730. }
  32731. }
  32732. /* random */
  32733. XMEMCPY(ssl->arrays->clientRandom, input + i, RAN_LEN);
  32734. i += RAN_LEN;
  32735. #ifdef SHOW_SECRETS
  32736. {
  32737. int j;
  32738. printf("client random: ");
  32739. for (j = 0; j < RAN_LEN; j++)
  32740. printf("%02x", ssl->arrays->clientRandom[j]);
  32741. printf("\n");
  32742. }
  32743. #endif
  32744. /* session id */
  32745. b = input[i++];
  32746. if (b > ID_LEN) {
  32747. WOLFSSL_MSG("Invalid session ID size");
  32748. ret = BUFFER_ERROR; /* session ID greater than 32 bytes long */
  32749. goto out;
  32750. }
  32751. else if (b > 0 && !IsSCR(ssl)) {
  32752. if ((i - begin) + b > helloSz) {
  32753. ret = BUFFER_ERROR;
  32754. goto out;
  32755. }
  32756. /* Always save session ID in case we want to echo it. */
  32757. XMEMCPY(ssl->arrays->sessionID, input + i, b);
  32758. ssl->arrays->sessionIDSz = b;
  32759. if (b == ID_LEN)
  32760. ssl->options.resuming = 1; /* client wants to resume */
  32761. WOLFSSL_MSG("Client wants to resume session");
  32762. }
  32763. i += b;
  32764. #ifdef WOLFSSL_DTLS
  32765. /* cookie */
  32766. if (ssl->options.dtls) {
  32767. word8 peerCookieSz;
  32768. if ((i - begin) + OPAQUE8_LEN > helloSz) {
  32769. ret = BUFFER_ERROR;
  32770. goto out;
  32771. }
  32772. peerCookieSz = input[i++];
  32773. if (peerCookieSz) {
  32774. if (peerCookieSz > MAX_COOKIE_LEN) {
  32775. ret = BUFFER_ERROR;
  32776. goto out;
  32777. }
  32778. if ((i - begin) + peerCookieSz > helloSz) {
  32779. ret = BUFFER_ERROR;
  32780. goto out;
  32781. }
  32782. i += peerCookieSz;
  32783. }
  32784. }
  32785. #endif /* WOLFSSL_DTLS */
  32786. /* suites */
  32787. if ((i - begin) + OPAQUE16_LEN > helloSz) {
  32788. ret = BUFFER_ERROR;
  32789. goto out;
  32790. }
  32791. #ifdef WOLFSSL_SMALL_STACK
  32792. clSuites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap,
  32793. DYNAMIC_TYPE_SUITES);
  32794. if (clSuites == NULL) {
  32795. ret = MEMORY_E;
  32796. goto out;
  32797. }
  32798. #endif
  32799. XMEMSET(clSuites, 0, sizeof(Suites));
  32800. ato16(&input[i], &clSuites->suiteSz);
  32801. i += OPAQUE16_LEN;
  32802. /* Cipher suite lists are always multiples of two in length. */
  32803. if (clSuites->suiteSz % 2 != 0) {
  32804. ret = BUFFER_ERROR;
  32805. goto out;
  32806. }
  32807. /* suites and compression length check */
  32808. if ((i - begin) + clSuites->suiteSz + OPAQUE8_LEN > helloSz) {
  32809. ret = BUFFER_ERROR;
  32810. goto out;
  32811. }
  32812. if (clSuites->suiteSz > WOLFSSL_MAX_SUITE_SZ) {
  32813. ret = BUFFER_ERROR;
  32814. goto out;
  32815. }
  32816. XMEMCPY(clSuites->suites, input + i, clSuites->suiteSz);
  32817. #ifdef HAVE_SERVER_RENEGOTIATION_INFO
  32818. /* check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV suite */
  32819. if (FindSuite(clSuites, 0, TLS_EMPTY_RENEGOTIATION_INFO_SCSV) >= 0) {
  32820. TLSX* extension;
  32821. /* check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV suite */
  32822. ret = TLSX_AddEmptyRenegotiationInfo(&ssl->extensions, ssl->heap);
  32823. if (ret != WOLFSSL_SUCCESS) {
  32824. ret = SECURE_RENEGOTIATION_E;
  32825. goto out;
  32826. } else {
  32827. ret = 0;
  32828. }
  32829. extension = TLSX_Find(ssl->extensions, TLSX_RENEGOTIATION_INFO);
  32830. if (extension) {
  32831. ssl->secure_renegotiation =
  32832. (SecureRenegotiation*)extension->data;
  32833. ssl->secure_renegotiation->enabled = 1;
  32834. }
  32835. }
  32836. #endif /* HAVE_SERVER_RENEGOTIATION_INFO */
  32837. #if defined(HAVE_FALLBACK_SCSV) || defined(OPENSSL_ALL)
  32838. /* check for TLS_FALLBACK_SCSV suite */
  32839. if (FindSuite(clSuites, TLS_FALLBACK_SCSV, 0) >= 0) {
  32840. WOLFSSL_MSG("Found Fallback SCSV");
  32841. if (ssl->ctx->method->version.minor > pv.minor) {
  32842. WOLFSSL_MSG("Client trying to connect with lesser version");
  32843. SendAlert(ssl, alert_fatal, inappropriate_fallback);
  32844. ret = VERSION_ERROR;
  32845. goto out;
  32846. }
  32847. }
  32848. #endif
  32849. i += clSuites->suiteSz;
  32850. clSuites->hashSigAlgoSz = 0;
  32851. /* compression length */
  32852. b = input[i++];
  32853. if ((i - begin) + b > helloSz) {
  32854. ret = BUFFER_ERROR;
  32855. goto out;
  32856. }
  32857. if (b == 0) {
  32858. WOLFSSL_MSG("No compression types in list");
  32859. #ifdef WOLFSSL_EXTRA_ALERTS
  32860. SendAlert(ssl, alert_fatal, decode_error);
  32861. #endif
  32862. ret = COMPRESSION_ERROR;
  32863. goto out;
  32864. }
  32865. {
  32866. /* compression match types */
  32867. int matchNo = 0;
  32868. int matchZlib = 0;
  32869. while (b--) {
  32870. byte comp = input[i++];
  32871. if (comp == NO_COMPRESSION) {
  32872. matchNo = 1;
  32873. }
  32874. if (comp == ZLIB_COMPRESSION) {
  32875. matchZlib = 1;
  32876. }
  32877. }
  32878. if (ssl->options.usingCompression == 0 && matchNo) {
  32879. WOLFSSL_MSG("Matched No Compression");
  32880. } else if (ssl->options.usingCompression && matchZlib) {
  32881. WOLFSSL_MSG("Matched zlib Compression");
  32882. } else if (ssl->options.usingCompression && matchNo) {
  32883. WOLFSSL_MSG("Could only match no compression, turning off");
  32884. ssl->options.usingCompression = 0; /* turn off */
  32885. } else {
  32886. WOLFSSL_MSG("Could not match compression");
  32887. #ifdef WOLFSSL_EXTRA_ALERTS
  32888. SendAlert(ssl, alert_fatal, illegal_parameter);
  32889. #endif
  32890. ret = COMPRESSION_ERROR;
  32891. goto out;
  32892. }
  32893. }
  32894. *inOutIdx = i;
  32895. /* tls extensions */
  32896. if ((i - begin) < helloSz) {
  32897. #ifdef HAVE_TLS_EXTENSIONS
  32898. if (TLSX_SupportExtensions(ssl))
  32899. #else
  32900. if (IsAtLeastTLSv1_2(ssl))
  32901. #endif
  32902. {
  32903. /* Process the hello extension. Skip unsupported. */
  32904. word16 totalExtSz;
  32905. #ifdef HAVE_TLS_EXTENSIONS
  32906. /* auto populate extensions supported unless user defined */
  32907. if ((ret = TLSX_PopulateExtensions(ssl, 1)) != 0)
  32908. goto out;
  32909. #endif
  32910. if ((i - begin) + OPAQUE16_LEN > helloSz) {
  32911. ret = BUFFER_ERROR;
  32912. goto out;
  32913. }
  32914. ato16(&input[i], &totalExtSz);
  32915. i += OPAQUE16_LEN;
  32916. if ((i - begin) + totalExtSz > helloSz) {
  32917. ret = BUFFER_ERROR;
  32918. goto out;
  32919. }
  32920. #ifdef HAVE_TLS_EXTENSIONS
  32921. /* tls extensions */
  32922. if ((ret = TLSX_Parse(ssl, input + i, totalExtSz, client_hello,
  32923. clSuites)))
  32924. goto out;
  32925. #ifdef WOLFSSL_TLS13
  32926. if (TLSX_Find(ssl->extensions,
  32927. TLSX_SUPPORTED_VERSIONS) != NULL) {
  32928. WOLFSSL_MSG(
  32929. "Client attempting to connect with higher version");
  32930. ret = VERSION_ERROR;
  32931. goto out;
  32932. }
  32933. #endif
  32934. #ifdef HAVE_SNI
  32935. if((ret=SNI_Callback(ssl)))
  32936. goto out;
  32937. #endif
  32938. #ifdef HAVE_ALPN
  32939. if((ret=ALPN_Select(ssl)))
  32940. goto out;
  32941. #endif
  32942. i += totalExtSz;
  32943. #else
  32944. while (totalExtSz) {
  32945. word16 extId, extSz;
  32946. if (OPAQUE16_LEN + OPAQUE16_LEN > totalExtSz) {
  32947. ret = BUFFER_ERROR;
  32948. goto out;
  32949. }
  32950. ato16(&input[i], &extId);
  32951. i += OPAQUE16_LEN;
  32952. ato16(&input[i], &extSz);
  32953. i += OPAQUE16_LEN;
  32954. if (OPAQUE16_LEN + OPAQUE16_LEN + extSz > totalExtSz) {
  32955. ret = BUFFER_ERROR;
  32956. goto out;
  32957. }
  32958. if (extId == HELLO_EXT_SIG_ALGO) {
  32959. word16 hashSigAlgoSz;
  32960. ato16(&input[i], &hashSigAlgoSz);
  32961. i += OPAQUE16_LEN;
  32962. if (OPAQUE16_LEN + hashSigAlgoSz > extSz) {
  32963. ret = BUFFER_ERROR;
  32964. goto out;
  32965. }
  32966. if (hashSigAlgoSz % 2 != 0) {
  32967. ret = BUFFER_ERROR;
  32968. goto out;
  32969. }
  32970. clSuites->hashSigAlgoSz = hashSigAlgoSz;
  32971. if (clSuites->hashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  32972. WOLFSSL_MSG("ClientHello SigAlgo list exceeds max, "
  32973. "truncating");
  32974. clSuites->hashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  32975. }
  32976. XMEMCPY(clSuites->hashSigAlgo, &input[i],
  32977. clSuites->hashSigAlgoSz);
  32978. i += hashSigAlgoSz;
  32979. }
  32980. #ifdef HAVE_EXTENDED_MASTER
  32981. else if (extId == HELLO_EXT_EXTMS)
  32982. ssl->options.haveEMS = 1;
  32983. #endif
  32984. else
  32985. i += extSz;
  32986. totalExtSz -= OPAQUE16_LEN + OPAQUE16_LEN + extSz;
  32987. }
  32988. #endif
  32989. *inOutIdx = i;
  32990. }
  32991. else
  32992. *inOutIdx = begin + helloSz; /* skip extensions */
  32993. }
  32994. #ifdef WOLFSSL_DTLS_CID
  32995. if (ssl->options.useDtlsCID)
  32996. DtlsCIDOnExtensionsParsed(ssl);
  32997. #endif /* WOLFSSL_DTLS_CID */
  32998. ssl->options.clientState = CLIENT_HELLO_COMPLETE;
  32999. ssl->options.haveSessionId = 1;
  33000. /* ProcessOld uses same resume code */
  33001. WOLFSSL_MSG_EX("ssl->options.resuming %d", ssl->options.resuming);
  33002. if (ssl->options.resuming) {
  33003. ret = HandleTlsResumption(ssl, clSuites);
  33004. if (ret != 0)
  33005. goto out;
  33006. #if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_ENCRYPT_THEN_MAC) && \
  33007. !defined(WOLFSSL_AEAD_ONLY)
  33008. if (ssl->options.encThenMac && ssl->specs.cipher_type == block) {
  33009. ret = TLSX_EncryptThenMac_Respond(ssl);
  33010. if (ret != 0)
  33011. goto out;
  33012. }
  33013. else
  33014. ssl->options.encThenMac = 0;
  33015. #endif
  33016. if (ssl->options.clientState == CLIENT_KEYEXCHANGE_COMPLETE) {
  33017. WOLFSSL_LEAVE("DoClientHello", ret);
  33018. WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
  33019. goto out;
  33020. }
  33021. }
  33022. #if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_DH_DEFAULT_PARAMS)
  33023. #if defined(HAVE_FFDHE) && defined(HAVE_SUPPORTED_CURVES)
  33024. if (TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS) != NULL) {
  33025. /* Set FFDHE parameters or clear DHE parameters if FFDH parameters
  33026. * present and no matches in the server's list. */
  33027. ret = TLSX_SupportedFFDHE_Set(ssl);
  33028. if (ret != 0)
  33029. goto out;
  33030. }
  33031. #endif
  33032. #endif
  33033. #ifdef OPENSSL_EXTRA
  33034. ssl->clSuites = clSuites; /* cppcheck-suppress autoVariables
  33035. *
  33036. * (suppress warning that ssl, a persistent
  33037. * non-local allocation, has its ->clSuites
  33038. * set to clSuites, a local stack allocation.
  33039. * we clear this assignment before returning.)
  33040. */
  33041. /* Give user last chance to provide a cert for cipher selection */
  33042. if (ret == 0 && ssl->ctx->certSetupCb != NULL)
  33043. ret = CertSetupCbWrapper(ssl);
  33044. #endif
  33045. if (ret == 0)
  33046. ret = MatchSuite(ssl, clSuites);
  33047. #if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_ENCRYPT_THEN_MAC) && \
  33048. !defined(WOLFSSL_AEAD_ONLY)
  33049. if (ret == 0 && ssl->options.encThenMac &&
  33050. ssl->specs.cipher_type == block) {
  33051. ret = TLSX_EncryptThenMac_Respond(ssl);
  33052. }
  33053. else
  33054. ssl->options.encThenMac = 0;
  33055. #endif
  33056. #ifdef WOLFSSL_DTLS
  33057. if (ret == 0 && ssl->options.dtls)
  33058. DtlsMsgPoolReset(ssl);
  33059. #endif
  33060. out:
  33061. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  33062. ssl->clSuites = NULL;
  33063. #endif
  33064. #ifdef WOLFSSL_SMALL_STACK
  33065. XFREE(clSuites, ssl->heap, DYNAMIC_TYPE_SUITES);
  33066. #endif
  33067. WOLFSSL_LEAVE("DoClientHello", ret);
  33068. WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
  33069. if (ret != 0) {
  33070. WOLFSSL_ERROR_VERBOSE(ret);
  33071. }
  33072. return ret;
  33073. }
  33074. #if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  33075. defined(HAVE_ED448)) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  33076. typedef struct DcvArgs {
  33077. byte* output; /* not allocated */
  33078. word32 sendSz;
  33079. word16 sz;
  33080. word32 sigSz;
  33081. word32 idx;
  33082. word32 begin;
  33083. } DcvArgs;
  33084. static void FreeDcvArgs(WOLFSSL* ssl, void* pArgs)
  33085. {
  33086. DcvArgs* args = (DcvArgs*)pArgs;
  33087. (void)ssl;
  33088. (void)args;
  33089. }
  33090. /* handle processing of certificate_verify (15) */
  33091. static int DoCertificateVerify(WOLFSSL* ssl, byte* input,
  33092. word32* inOutIdx, word32 size)
  33093. {
  33094. int ret = 0;
  33095. #ifdef WOLFSSL_ASYNC_CRYPT
  33096. DcvArgs* args = NULL;
  33097. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  33098. #else
  33099. DcvArgs args[1];
  33100. #endif
  33101. WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_DO);
  33102. WOLFSSL_ENTER("DoCertificateVerify");
  33103. #ifdef WOLFSSL_ASYNC_CRYPT
  33104. if (ssl->async == NULL) {
  33105. ssl->async = (struct WOLFSSL_ASYNC*)
  33106. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  33107. DYNAMIC_TYPE_ASYNC);
  33108. if (ssl->async == NULL)
  33109. ERROR_OUT(MEMORY_E, exit_dcv);
  33110. }
  33111. args = (DcvArgs*)ssl->async->args;
  33112. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  33113. if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
  33114. /* Check for error */
  33115. if (ret < 0)
  33116. goto exit_dcv;
  33117. }
  33118. else
  33119. #endif
  33120. {
  33121. /* Reset state */
  33122. ret = 0;
  33123. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  33124. XMEMSET(args, 0, sizeof(DcvArgs));
  33125. ssl->options.peerHashAlgo = sha_mac;
  33126. ssl->options.peerSigAlgo = anonymous_sa_algo;
  33127. args->idx = *inOutIdx;
  33128. args->begin = *inOutIdx;
  33129. #ifdef WOLFSSL_ASYNC_CRYPT
  33130. ssl->async->freeArgs = FreeDcvArgs;
  33131. #endif
  33132. }
  33133. switch(ssl->options.asyncState)
  33134. {
  33135. case TLS_ASYNC_BEGIN:
  33136. {
  33137. #ifdef WOLFSSL_CALLBACKS
  33138. if (ssl->hsInfoOn)
  33139. AddPacketName(ssl, "CertificateVerify");
  33140. if (ssl->toInfoOn)
  33141. AddLateName("CertificateVerify", &ssl->timeoutInfo);
  33142. #endif
  33143. /* Advance state and proceed */
  33144. ssl->options.asyncState = TLS_ASYNC_BUILD;
  33145. } /* case TLS_ASYNC_BEGIN */
  33146. FALL_THROUGH;
  33147. case TLS_ASYNC_BUILD:
  33148. {
  33149. if (IsAtLeastTLSv1_2(ssl)) {
  33150. if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN > size) {
  33151. ERROR_OUT(BUFFER_ERROR, exit_dcv);
  33152. }
  33153. DecodeSigAlg(&input[args->idx], &ssl->options.peerHashAlgo,
  33154. &ssl->options.peerSigAlgo);
  33155. args->idx += 2;
  33156. }
  33157. #ifndef NO_RSA
  33158. else if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0)
  33159. ssl->options.peerSigAlgo = rsa_sa_algo;
  33160. #endif
  33161. #ifdef HAVE_ECC
  33162. else if (ssl->peerEccDsaKeyPresent) {
  33163. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  33164. if (ssl->peerEccDsaKey->dp->id == ECC_SM2P256V1) {
  33165. ssl->options.peerSigAlgo = sm2_sa_algo;
  33166. }
  33167. else
  33168. #endif
  33169. {
  33170. ssl->options.peerSigAlgo = ecc_dsa_sa_algo;
  33171. }
  33172. }
  33173. #endif
  33174. #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
  33175. else if (ssl->peerEd25519KeyPresent)
  33176. ssl->options.peerSigAlgo = ed25519_sa_algo;
  33177. #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
  33178. #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
  33179. else if (ssl->peerEd448KeyPresent)
  33180. ssl->options.peerSigAlgo = ed448_sa_algo;
  33181. #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
  33182. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  33183. ERROR_OUT(BUFFER_ERROR, exit_dcv);
  33184. }
  33185. ato16(input + args->idx, &args->sz);
  33186. args->idx += OPAQUE16_LEN;
  33187. if ((args->idx - args->begin) + args->sz > size ||
  33188. args->sz > ENCRYPT_LEN) {
  33189. ERROR_OUT(BUFFER_ERROR, exit_dcv);
  33190. }
  33191. #ifdef HAVE_ECC
  33192. if (ssl->peerEccDsaKeyPresent) {
  33193. WOLFSSL_MSG("Doing ECC peer cert verify");
  33194. /* make sure a default is defined */
  33195. #if !defined(NO_SHA)
  33196. SetDigest(ssl, sha_mac);
  33197. #elif !defined(NO_SHA256)
  33198. SetDigest(ssl, sha256_mac);
  33199. #elif defined(WOLFSSL_SM3)
  33200. SetDigest(ssl, sm3_mac);
  33201. #elif defined(WOLFSSL_SHA384)
  33202. SetDigest(ssl, sha384_mac);
  33203. #elif defined(WOLFSSL_SHA512)
  33204. SetDigest(ssl, sha512_mac);
  33205. #else
  33206. #error No digest enabled for ECC sig verify
  33207. #endif
  33208. if (IsAtLeastTLSv1_2(ssl)) {
  33209. if (ssl->options.peerSigAlgo != ecc_dsa_sa_algo
  33210. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  33211. && ssl->options.peerSigAlgo != sm2_sa_algo
  33212. #endif
  33213. ) {
  33214. WOLFSSL_MSG("Oops, peer sent ECC key but not in verify");
  33215. }
  33216. SetDigest(ssl, ssl->options.peerHashAlgo);
  33217. }
  33218. }
  33219. #endif /* HAVE_ECC */
  33220. #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
  33221. if (ssl->peerEd25519KeyPresent) {
  33222. WOLFSSL_MSG("Doing ED25519 peer cert verify");
  33223. if (IsAtLeastTLSv1_2(ssl) &&
  33224. ssl->options.peerSigAlgo != ed25519_sa_algo) {
  33225. WOLFSSL_MSG(
  33226. "Oops, peer sent ED25519 key but not in verify");
  33227. }
  33228. }
  33229. #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
  33230. #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
  33231. if (ssl->peerEd448KeyPresent) {
  33232. WOLFSSL_MSG("Doing ED448 peer cert verify");
  33233. if (IsAtLeastTLSv1_2(ssl) &&
  33234. ssl->options.peerSigAlgo != ed448_sa_algo) {
  33235. WOLFSSL_MSG(
  33236. "Oops, peer sent ED448 key but not in verify");
  33237. }
  33238. }
  33239. #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
  33240. /* Advance state and proceed */
  33241. ssl->options.asyncState = TLS_ASYNC_DO;
  33242. } /* case TLS_ASYNC_BUILD */
  33243. FALL_THROUGH;
  33244. case TLS_ASYNC_DO:
  33245. {
  33246. #ifndef NO_RSA
  33247. if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
  33248. WOLFSSL_MSG("Doing RSA peer cert verify");
  33249. ret = RsaVerify(ssl,
  33250. input + args->idx,
  33251. args->sz,
  33252. &args->output,
  33253. ssl->options.peerSigAlgo, ssl->options.peerHashAlgo,
  33254. ssl->peerRsaKey,
  33255. #ifdef HAVE_PK_CALLBACKS
  33256. &ssl->buffers.peerRsaKey
  33257. #else
  33258. NULL
  33259. #endif
  33260. );
  33261. if (ret >= 0) {
  33262. if (ssl->options.peerSigAlgo == rsa_sa_algo)
  33263. args->sendSz = (word32)ret;
  33264. else {
  33265. args->sigSz = (word32)ret;
  33266. args->sendSz = ssl->buffers.digest.length;
  33267. }
  33268. ret = 0;
  33269. }
  33270. }
  33271. #endif /* !NO_RSA */
  33272. #ifdef HAVE_ECC
  33273. if (ssl->peerEccDsaKeyPresent) {
  33274. WOLFSSL_MSG("Doing ECC peer cert verify");
  33275. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  33276. if (ssl->options.peerSigAlgo == sm2_sa_algo) {
  33277. ret = Sm2wSm3Verify(ssl,
  33278. TLS12_SM2_SIG_ID, TLS12_SM2_SIG_ID_SZ,
  33279. input + args->idx, args->sz,
  33280. ssl->hsHashes->messages, ssl->hsHashes->prevLen,
  33281. ssl->peerEccDsaKey,
  33282. #ifdef HAVE_PK_CALLBACKS
  33283. &ssl->buffers.peerEccDsaKey
  33284. #else
  33285. NULL
  33286. #endif
  33287. );
  33288. }
  33289. else
  33290. #endif
  33291. {
  33292. ret = EccVerify(ssl,
  33293. input + args->idx, args->sz,
  33294. ssl->buffers.digest.buffer,
  33295. ssl->buffers.digest.length,
  33296. ssl->peerEccDsaKey,
  33297. #ifdef HAVE_PK_CALLBACKS
  33298. &ssl->buffers.peerEccDsaKey
  33299. #else
  33300. NULL
  33301. #endif
  33302. );
  33303. }
  33304. /* SERVER: Data verified with certificate's public key. */
  33305. ssl->options.peerAuthGood = ssl->options.havePeerCert &&
  33306. (ret == 0);
  33307. }
  33308. #endif /* HAVE_ECC */
  33309. #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
  33310. if (ssl->peerEd25519KeyPresent) {
  33311. WOLFSSL_MSG("Doing Ed25519 peer cert verify");
  33312. ret = Ed25519Verify(ssl,
  33313. input + args->idx, args->sz,
  33314. ssl->hsHashes->messages, ssl->hsHashes->prevLen,
  33315. ssl->peerEd25519Key,
  33316. #ifdef HAVE_PK_CALLBACKS
  33317. &ssl->buffers.peerEd25519Key
  33318. #else
  33319. NULL
  33320. #endif
  33321. );
  33322. /* SERVER: Data verified with certificate's public key. */
  33323. ssl->options.peerAuthGood = ssl->options.havePeerCert &&
  33324. (ret == 0);
  33325. }
  33326. #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
  33327. #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
  33328. if (ssl->peerEd448KeyPresent) {
  33329. WOLFSSL_MSG("Doing Ed448 peer cert verify");
  33330. ret = Ed448Verify(ssl,
  33331. input + args->idx, args->sz,
  33332. ssl->hsHashes->messages, ssl->hsHashes->prevLen,
  33333. ssl->peerEd448Key,
  33334. #ifdef HAVE_PK_CALLBACKS
  33335. &ssl->buffers.peerEd448Key
  33336. #else
  33337. NULL
  33338. #endif
  33339. );
  33340. /* SERVER: Data verified with certificate's public key. */
  33341. ssl->options.peerAuthGood = ssl->options.havePeerCert &&
  33342. (ret == 0);
  33343. }
  33344. #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
  33345. #ifdef WOLFSSL_ASYNC_CRYPT
  33346. /* handle async pending */
  33347. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
  33348. goto exit_dcv;
  33349. #endif
  33350. /* Check for error */
  33351. if (ret != 0) {
  33352. ret = SIG_VERIFY_E;
  33353. goto exit_dcv;
  33354. }
  33355. /* Advance state and proceed */
  33356. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  33357. } /* case TLS_ASYNC_DO */
  33358. FALL_THROUGH;
  33359. case TLS_ASYNC_VERIFY:
  33360. {
  33361. #ifndef NO_RSA
  33362. if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
  33363. if (IsAtLeastTLSv1_2(ssl)) {
  33364. #ifdef WC_RSA_PSS
  33365. if (ssl->options.peerSigAlgo == rsa_pss_sa_algo) {
  33366. SetDigest(ssl, ssl->options.peerHashAlgo);
  33367. #ifdef HAVE_SELFTEST
  33368. ret = wc_RsaPSS_CheckPadding(
  33369. ssl->buffers.digest.buffer,
  33370. ssl->buffers.digest.length,
  33371. args->output, args->sigSz,
  33372. HashAlgoToType(ssl->options.peerHashAlgo));
  33373. #else
  33374. ret = wc_RsaPSS_CheckPadding_ex(
  33375. ssl->buffers.digest.buffer,
  33376. ssl->buffers.digest.length,
  33377. args->output, args->sigSz,
  33378. HashAlgoToType(ssl->options.peerHashAlgo), -1,
  33379. mp_count_bits(&ssl->peerRsaKey->n));
  33380. #endif
  33381. if (ret != 0) {
  33382. ret = SIG_VERIFY_E;
  33383. goto exit_dcv;
  33384. }
  33385. }
  33386. else
  33387. #endif
  33388. {
  33389. #ifndef WOLFSSL_SMALL_STACK
  33390. byte encodedSig[MAX_ENCODED_SIG_SZ];
  33391. #else
  33392. byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  33393. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  33394. if (encodedSig == NULL) {
  33395. ERROR_OUT(MEMORY_E, exit_dcv);
  33396. }
  33397. #endif
  33398. if (ssl->options.peerSigAlgo != rsa_sa_algo) {
  33399. WOLFSSL_MSG("Oops, peer sent RSA key but not "
  33400. "in verify");
  33401. }
  33402. SetDigest(ssl, ssl->options.peerHashAlgo);
  33403. args->sigSz = wc_EncodeSignature(encodedSig,
  33404. ssl->buffers.digest.buffer,
  33405. ssl->buffers.digest.length,
  33406. TypeHash(ssl->options.peerHashAlgo));
  33407. if (args->sendSz != args->sigSz || !args->output ||
  33408. XMEMCMP(args->output, encodedSig,
  33409. min(args->sigSz, MAX_ENCODED_SIG_SZ)) != 0) {
  33410. ret = VERIFY_CERT_ERROR;
  33411. }
  33412. #ifdef WOLFSSL_SMALL_STACK
  33413. XFREE(encodedSig, ssl->heap,
  33414. DYNAMIC_TYPE_SIGNATURE);
  33415. #endif
  33416. }
  33417. }
  33418. else {
  33419. if (args->sendSz != FINISHED_SZ || !args->output ||
  33420. XMEMCMP(args->output,
  33421. &ssl->hsHashes->certHashes, FINISHED_SZ) != 0) {
  33422. ret = VERIFY_CERT_ERROR;
  33423. }
  33424. }
  33425. if (ret == 0) {
  33426. /* SERVER: Data verified with cert's public key. */
  33427. ssl->options.peerAuthGood = ssl->options.havePeerCert &&
  33428. (ret == 0);
  33429. }
  33430. }
  33431. #endif /* !NO_RSA */
  33432. if (ret != 0)
  33433. break;
  33434. /* Advance state and proceed */
  33435. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  33436. } /* case TLS_ASYNC_VERIFY */
  33437. FALL_THROUGH;
  33438. case TLS_ASYNC_FINALIZE:
  33439. {
  33440. if (IsEncryptionOn(ssl, 0)) {
  33441. args->idx += ssl->keys.padSz;
  33442. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  33443. if (ssl->options.startedETMRead)
  33444. args->idx += MacSize(ssl);
  33445. #endif
  33446. }
  33447. ssl->options.havePeerVerify = 1;
  33448. /* Set final index */
  33449. args->idx += args->sz;
  33450. *inOutIdx = args->idx;
  33451. /* Advance state and proceed */
  33452. ssl->options.asyncState = TLS_ASYNC_END;
  33453. } /* case TLS_ASYNC_FINALIZE */
  33454. FALL_THROUGH;
  33455. case TLS_ASYNC_END:
  33456. {
  33457. break;
  33458. }
  33459. default:
  33460. ret = INPUT_CASE_ERROR;
  33461. } /* switch(ssl->options.asyncState) */
  33462. exit_dcv:
  33463. WOLFSSL_LEAVE("DoCertificateVerify", ret);
  33464. WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_DO);
  33465. #ifdef WOLFSSL_ASYNC_CRYPT
  33466. /* Handle async operation */
  33467. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  33468. /* Mark message as not received so it can process again */
  33469. ssl->msgsReceived.got_certificate_verify = 0;
  33470. return ret;
  33471. }
  33472. #endif /* WOLFSSL_ASYNC_CRYPT */
  33473. #ifdef WOLFSSL_EXTRA_ALERTS
  33474. if (ret == WC_NO_ERR_TRACE(BUFFER_ERROR))
  33475. SendAlert(ssl, alert_fatal, decode_error);
  33476. else if (ret == WC_NO_ERR_TRACE(SIG_VERIFY_E))
  33477. SendAlert(ssl, alert_fatal, decrypt_error);
  33478. else if (ret != 0)
  33479. SendAlert(ssl, alert_fatal, bad_certificate);
  33480. #endif
  33481. /* Digest is not allocated, so do this to prevent free */
  33482. if(ssl->buffers.digest.buffer) {
  33483. if (!ssl->options.dontFreeDigest) {
  33484. /*This should not happen*/
  33485. XFREE(ssl->buffers.digest.buffer,
  33486. ssl->heap, DYNAMIC_TYPE_DIGEST);
  33487. }
  33488. }
  33489. ssl->buffers.digest.buffer = NULL;
  33490. ssl->buffers.digest.length = 0;
  33491. ssl->options.dontFreeDigest = 0;
  33492. #ifdef WOLFSSL_ASYNC_CRYPT
  33493. /* Cleanup async */
  33494. FreeAsyncCtx(ssl, 0);
  33495. #else
  33496. FreeDcvArgs(ssl, args);
  33497. #endif
  33498. /* Final cleanup */
  33499. FreeKeyExchange(ssl);
  33500. if (ret != 0) {
  33501. WOLFSSL_ERROR_VERBOSE(ret);
  33502. }
  33503. return ret;
  33504. }
  33505. #endif /* (!NO_RSA || ECC || ED25519 || ED448) && !WOLFSSL_NO_CLIENT_AUTH */
  33506. /* handle generation of server_hello_done (14) */
  33507. int SendServerHelloDone(WOLFSSL* ssl)
  33508. {
  33509. byte* output;
  33510. int sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  33511. int ret;
  33512. WOLFSSL_START(WC_FUNC_SERVER_HELLO_DONE_SEND);
  33513. WOLFSSL_ENTER("SendServerHelloDone");
  33514. #ifdef WOLFSSL_DTLS
  33515. if (ssl->options.dtls)
  33516. sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  33517. #endif
  33518. if (IsEncryptionOn(ssl, 1))
  33519. sendSz += MAX_MSG_EXTRA;
  33520. /* Set this in case CheckAvailableSize returns a WANT_WRITE so that state
  33521. * is not advanced yet */
  33522. ssl->options.buildingMsg = 1;
  33523. /* check for available size */
  33524. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  33525. return ret;
  33526. /* get output buffer */
  33527. output = GetOutputBuffer(ssl);
  33528. AddHeaders(output, 0, server_hello_done, ssl);
  33529. if (IsEncryptionOn(ssl, 1)) {
  33530. byte* input;
  33531. int inputSz = HANDSHAKE_HEADER_SZ; /* build msg adds rec hdr */
  33532. int recordHeaderSz = RECORD_HEADER_SZ;
  33533. if (ssl->options.dtls) {
  33534. recordHeaderSz += DTLS_RECORD_EXTRA;
  33535. inputSz += DTLS_HANDSHAKE_EXTRA;
  33536. }
  33537. input = (byte*)XMALLOC((size_t)inputSz, ssl->heap,
  33538. DYNAMIC_TYPE_IN_BUFFER);
  33539. if (input == NULL)
  33540. return MEMORY_E;
  33541. XMEMCPY(input, output + recordHeaderSz, inputSz);
  33542. #ifdef WOLFSSL_DTLS
  33543. if (IsDtlsNotSctpMode(ssl) &&
  33544. (ret = DtlsMsgPoolSave(ssl, input, (word32)inputSz, server_hello_done)) != 0) {
  33545. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  33546. return ret;
  33547. }
  33548. #endif
  33549. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  33550. handshake, 1, 0, 0, CUR_ORDER);
  33551. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  33552. if (sendSz < 0)
  33553. return sendSz;
  33554. } else {
  33555. #ifdef WOLFSSL_DTLS
  33556. if (IsDtlsNotSctpMode(ssl)) {
  33557. if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, server_hello_done)) != 0)
  33558. return ret;
  33559. }
  33560. if (ssl->options.dtls)
  33561. DtlsSEQIncrement(ssl, CUR_ORDER);
  33562. #endif
  33563. ret = HashOutput(ssl, output, sendSz, 0);
  33564. if (ret != 0)
  33565. return ret;
  33566. }
  33567. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  33568. if (ssl->hsInfoOn)
  33569. AddPacketName(ssl, "ServerHelloDone");
  33570. if (ssl->toInfoOn) {
  33571. ret = AddPacketInfo(ssl, "ServerHelloDone", handshake, output,
  33572. sendSz, WRITE_PROTO, 0, ssl->heap);
  33573. if (ret != 0)
  33574. return ret;
  33575. }
  33576. #endif
  33577. ssl->options.serverState = SERVER_HELLODONE_COMPLETE;
  33578. ssl->options.buildingMsg = 0;
  33579. ssl->buffers.outputBuffer.length += (word32)sendSz;
  33580. ret = SendBuffered(ssl);
  33581. WOLFSSL_LEAVE("SendServerHelloDone", ret);
  33582. WOLFSSL_END(WC_FUNC_SERVER_HELLO_DONE_SEND);
  33583. return ret;
  33584. }
  33585. #endif /* !WOLFSSL_NO_TLS12 */
  33586. #ifdef HAVE_SESSION_TICKET
  33587. #ifdef WOLFSSL_TICKET_HAVE_ID
  33588. static void GetRealSessionID(WOLFSSL* ssl, const byte** id, byte* idSz)
  33589. {
  33590. if (ssl->session->haveAltSessionID) {
  33591. *id = ssl->session->altSessionID;
  33592. *idSz = ID_LEN;
  33593. }
  33594. else if (!IsAtLeastTLSv1_3(ssl->version) && ssl->arrays != NULL) {
  33595. *id = ssl->arrays->sessionID;
  33596. *idSz = ssl->arrays->sessionIDSz;
  33597. }
  33598. else {
  33599. *id = ssl->session->sessionID;
  33600. *idSz = ssl->session->sessionIDSz;
  33601. }
  33602. }
  33603. #endif
  33604. int SetupTicket(WOLFSSL* ssl)
  33605. {
  33606. int ret = 0;
  33607. (void)ssl;
  33608. #ifdef WOLFSSL_TLS13
  33609. {
  33610. /* Client adds to ticket age to obfuscate. */
  33611. byte ageAdd[AGEADD_LEN]; /* Obfuscation of age */
  33612. ret = wc_RNG_GenerateBlock(ssl->rng, ageAdd, AGEADD_LEN);
  33613. if (ret != 0)
  33614. return ret;
  33615. ato32(ageAdd, &ssl->session->ticketAdd);
  33616. }
  33617. #endif
  33618. #ifdef WOLFSSL_TICKET_HAVE_ID
  33619. {
  33620. const byte* id = NULL;
  33621. byte idSz = 0;
  33622. GetRealSessionID(ssl, &id, &idSz);
  33623. if (idSz == 0) {
  33624. ret = wc_RNG_GenerateBlock(ssl->rng, ssl->session->altSessionID,
  33625. ID_LEN);
  33626. if (ret != 0)
  33627. return ret;
  33628. ssl->session->haveAltSessionID = 1;
  33629. }
  33630. }
  33631. #endif
  33632. return ret;
  33633. }
  33634. /* create a new session ticket, 0 on success
  33635. * Do any kind of setup in SetupTicket */
  33636. int CreateTicket(WOLFSSL* ssl)
  33637. {
  33638. InternalTicket* it;
  33639. ExternalTicket* et;
  33640. int encLen;
  33641. int ret;
  33642. int error;
  33643. word32 itHash = 0;
  33644. byte zeros[WOLFSSL_TICKET_MAC_SZ]; /* biggest cmp size */
  33645. WOLFSSL_ASSERT_SIZEOF_GE(ssl->session->staticTicket, *et);
  33646. WOLFSSL_ASSERT_SIZEOF_GE(et->enc_ticket, *it);
  33647. if (ssl->session->ticket != ssl->session->staticTicket) {
  33648. /* Always use the static ticket buffer */
  33649. XFREE(ssl->session->ticket, NULL, DYNAMIC_TYPE_SESSION_TICK);
  33650. ssl->session->ticket = ssl->session->staticTicket;
  33651. ssl->session->ticketLenAlloc = 0;
  33652. }
  33653. et = (ExternalTicket*)ssl->session->ticket;
  33654. it = (InternalTicket*)et->enc_ticket;
  33655. #ifdef WOLFSSL_ASYNC_CRYPT
  33656. if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E))
  33657. #endif
  33658. {
  33659. XMEMSET(et, 0, sizeof(*et));
  33660. }
  33661. /* build internal */
  33662. it->pv.major = ssl->version.major;
  33663. it->pv.minor = ssl->version.minor;
  33664. it->suite[0] = ssl->options.cipherSuite0;
  33665. it->suite[1] = ssl->options.cipherSuite;
  33666. #ifdef WOLFSSL_EARLY_DATA
  33667. c32toa(ssl->options.maxEarlyDataSz, it->maxEarlyDataSz);
  33668. #endif
  33669. if (!ssl->options.tls1_3) {
  33670. if (ssl->arrays == NULL) {
  33671. WOLFSSL_MSG("CreateTicket called with null arrays");
  33672. ret = BAD_FUNC_ARG;
  33673. goto error;
  33674. }
  33675. XMEMCPY(it->msecret, ssl->arrays->masterSecret, SECRET_LEN);
  33676. #ifndef NO_ASN_TIME
  33677. c32toa(LowResTimer(), it->timestamp);
  33678. #endif
  33679. it->haveEMS = (byte) ssl->options.haveEMS;
  33680. }
  33681. else {
  33682. #ifdef WOLFSSL_TLS13
  33683. #ifdef WOLFSSL_32BIT_MILLI_TIME
  33684. word32 now = TimeNowInMilliseconds();
  33685. #else
  33686. sword64 now = TimeNowInMilliseconds();
  33687. #endif
  33688. if (now == 0) {
  33689. ret = GETTIME_ERROR;
  33690. goto error;
  33691. }
  33692. c32toa(ssl->session->ticketAdd, it->ageAdd);
  33693. c16toa(ssl->session->namedGroup, it->namedGroup);
  33694. #ifdef WOLFSSL_32BIT_MILLI_TIME
  33695. c32toa(now, it->timestamp);
  33696. #else
  33697. c32toa((word32)(now >> 32), it->timestamp);
  33698. c32toa((word32)now , it->timestamp + OPAQUE32_LEN);
  33699. #endif
  33700. /* Resumption master secret. */
  33701. XMEMCPY(it->msecret, ssl->session->masterSecret, SECRET_LEN);
  33702. if (ssl->session->ticketNonce.len > MAX_TICKET_NONCE_STATIC_SZ) {
  33703. WOLFSSL_MSG("Bad ticket nonce value");
  33704. ret = BAD_TICKET_MSG_SZ;
  33705. goto error;
  33706. }
  33707. XMEMCPY(it->ticketNonce, ssl->session->ticketNonce.data,
  33708. ssl->session->ticketNonce.len);
  33709. it->ticketNonceLen = ssl->session->ticketNonce.len;
  33710. #endif
  33711. }
  33712. #ifdef OPENSSL_EXTRA
  33713. it->sessionCtxSz = ssl->sessionCtxSz;
  33714. XMEMCPY(it->sessionCtx, ssl->sessionCtx, ID_LEN);
  33715. #endif
  33716. #ifdef WOLFSSL_TICKET_HAVE_ID
  33717. {
  33718. const byte* id = NULL;
  33719. byte idSz = 0;
  33720. GetRealSessionID(ssl, &id, &idSz);
  33721. /* make sure idSz is not larger than ID_LEN */
  33722. if (idSz > ID_LEN)
  33723. idSz = ID_LEN;
  33724. XMEMCPY(it->id, id, idSz);
  33725. }
  33726. #endif
  33727. /* encrypt */
  33728. encLen = WOLFSSL_TICKET_ENC_SZ; /* max size user can use */
  33729. if (ssl->ctx->ticketEncCb == NULL
  33730. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL)
  33731. ||
  33732. /* SSL_OP_NO_TICKET turns off tickets in <= 1.2. Forces
  33733. * "stateful" tickets for 1.3 so just use the regular
  33734. * stateless ones. */
  33735. (!IsAtLeastTLSv1_3(ssl->version) &&
  33736. (ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0)
  33737. #endif
  33738. ) {
  33739. /* Use BAD_TICKET_ENCRYPT to signal missing ticket callback */
  33740. ret = BAD_TICKET_ENCRYPT;
  33741. }
  33742. else {
  33743. itHash = HashObject((byte*)it, sizeof(*it), &error);
  33744. if (error == 0) {
  33745. ret = ssl->ctx->ticketEncCb(ssl, et->key_name, et->iv, et->mac,
  33746. 1, et->enc_ticket, WOLFSSL_INTERNAL_TICKET_LEN, &encLen,
  33747. SSL_TICKET_CTX(ssl));
  33748. }
  33749. else {
  33750. ret = WOLFSSL_TICKET_RET_FATAL;
  33751. }
  33752. }
  33753. if (ret != WOLFSSL_TICKET_RET_OK) {
  33754. #ifdef WOLFSSL_ASYNC_CRYPT
  33755. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  33756. return ret;
  33757. }
  33758. #endif
  33759. goto error;
  33760. }
  33761. if (encLen < (int)WOLFSSL_INTERNAL_TICKET_LEN ||
  33762. encLen > (int)WOLFSSL_TICKET_ENC_SZ) {
  33763. WOLFSSL_MSG("Bad user ticket encrypt size");
  33764. ret = BAD_TICKET_KEY_CB_SZ;
  33765. }
  33766. /* sanity checks on encrypt callback */
  33767. /* internal ticket can't be the same if encrypted */
  33768. if (itHash == HashObject((byte*)it, sizeof(*it), &error) || error != 0)
  33769. {
  33770. WOLFSSL_MSG("User ticket encrypt didn't encrypt or hash failed");
  33771. ret = BAD_TICKET_ENCRYPT;
  33772. goto error;
  33773. }
  33774. XMEMSET(zeros, 0, sizeof(zeros));
  33775. /* name */
  33776. if (XMEMCMP(et->key_name, zeros, WOLFSSL_TICKET_NAME_SZ) == 0) {
  33777. WOLFSSL_MSG("User ticket encrypt didn't set name");
  33778. ret = BAD_TICKET_ENCRYPT;
  33779. goto error;
  33780. }
  33781. /* iv */
  33782. if (XMEMCMP(et->iv, zeros, WOLFSSL_TICKET_IV_SZ) == 0) {
  33783. WOLFSSL_MSG("User ticket encrypt didn't set iv");
  33784. ret = BAD_TICKET_ENCRYPT;
  33785. goto error;
  33786. }
  33787. /* mac */
  33788. if (XMEMCMP(et->mac, zeros, WOLFSSL_TICKET_MAC_SZ) == 0) {
  33789. WOLFSSL_MSG("User ticket encrypt didn't set mac");
  33790. ret = BAD_TICKET_ENCRYPT;
  33791. goto error;
  33792. }
  33793. /* set size */
  33794. c16toa((word16)encLen, et->enc_len);
  33795. if (encLen < (int)WOLFSSL_TICKET_ENC_SZ) {
  33796. /* move mac up since whole enc buffer not used */
  33797. XMEMMOVE(et->enc_ticket + encLen, et->mac,
  33798. WOLFSSL_TICKET_MAC_SZ);
  33799. }
  33800. ssl->session->ticketLen =
  33801. (word16)(encLen + WOLFSSL_TICKET_FIXED_SZ);
  33802. return ret;
  33803. error:
  33804. #ifdef WOLFSSL_CHECK_MEM_ZERO
  33805. /* Ticket has sensitive data in it now. */
  33806. wc_MemZero_Add("Create Ticket internal", it, sizeof(InternalTicket));
  33807. #endif
  33808. ForceZero(it, sizeof(*it));
  33809. #ifdef WOLFSSL_CHECK_MEM_ZERO
  33810. wc_MemZero_Check(it, sizeof(InternalTicket));
  33811. #endif
  33812. WOLFSSL_ERROR_VERBOSE(ret);
  33813. return ret;
  33814. }
  33815. int DoDecryptTicket(const WOLFSSL* ssl, const byte* input, word32 len,
  33816. InternalTicket **it)
  33817. {
  33818. ExternalTicket* et;
  33819. int ret;
  33820. int outLen;
  33821. word16 inLen;
  33822. WOLFSSL_START(WC_FUNC_TICKET_DO);
  33823. WOLFSSL_ENTER("DoDecryptTicket");
  33824. if (len > SESSION_TICKET_LEN ||
  33825. len < (word32)(WOLFSSL_INTERNAL_TICKET_LEN +
  33826. WOLFSSL_TICKET_FIXED_SZ)) {
  33827. WOLFSSL_ERROR_VERBOSE(BAD_TICKET_MSG_SZ);
  33828. return WOLFSSL_TICKET_RET_REJECT;
  33829. }
  33830. et = (ExternalTicket*)input;
  33831. /* decrypt */
  33832. ato16(et->enc_len, &inLen);
  33833. if (inLen > WOLFSSL_TICKET_ENC_SZ) {
  33834. WOLFSSL_ERROR_VERBOSE(BAD_TICKET_MSG_SZ);
  33835. return WOLFSSL_TICKET_RET_REJECT;
  33836. }
  33837. outLen = (int)inLen; /* may be reduced by user padding */
  33838. if (ssl->ctx->ticketEncCb == NULL
  33839. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL)
  33840. ||
  33841. /* SSL_OP_NO_TICKET turns off tickets in < 1.2. Forces
  33842. * "stateful" tickets for 1.3 so just use the regular
  33843. * stateless ones. */
  33844. (!IsAtLeastTLSv1_3(ssl->version) &&
  33845. (ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0)
  33846. #endif
  33847. ) {
  33848. /* Use BAD_TICKET_ENCRYPT to signal missing ticket callback */
  33849. WOLFSSL_ERROR_VERBOSE(BAD_TICKET_ENCRYPT);
  33850. ret = WOLFSSL_TICKET_RET_REJECT;
  33851. }
  33852. else {
  33853. /* Callback uses ssl without const but for DTLS, it really shouldn't
  33854. * modify its state. */
  33855. ret = ssl->ctx->ticketEncCb((WOLFSSL*)ssl, et->key_name, et->iv,
  33856. et->enc_ticket + inLen, 0,
  33857. et->enc_ticket, inLen, &outLen,
  33858. SSL_TICKET_CTX(ssl));
  33859. }
  33860. if (ret != WOLFSSL_TICKET_RET_OK) {
  33861. #ifdef WOLFSSL_ASYNC_CRYPT
  33862. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  33863. return ret;
  33864. }
  33865. #endif /* WOLFSSL_ASYNC_CRYPT */
  33866. if (ret != WOLFSSL_TICKET_RET_CREATE) {
  33867. WOLFSSL_ERROR_VERBOSE(BAD_TICKET_KEY_CB_SZ);
  33868. return WOLFSSL_TICKET_RET_REJECT;
  33869. }
  33870. }
  33871. if (outLen > (int)inLen || outLen < (int)WOLFSSL_INTERNAL_TICKET_LEN) {
  33872. WOLFSSL_MSG("Bad user ticket decrypt len");
  33873. WOLFSSL_ERROR_VERBOSE(BAD_TICKET_KEY_CB_SZ);
  33874. return BAD_TICKET_KEY_CB_SZ;
  33875. }
  33876. *it = (InternalTicket*)et->enc_ticket;
  33877. return ret;
  33878. }
  33879. static int DoClientTicketCheckVersion(const WOLFSSL* ssl,
  33880. InternalTicket* it)
  33881. {
  33882. if (ssl->version.minor < it->pv.minor) {
  33883. WOLFSSL_MSG("Ticket has greater version");
  33884. return VERSION_ERROR;
  33885. }
  33886. else if (ssl->version.minor > it->pv.minor) {
  33887. if (IsAtLeastTLSv1_3(it->pv) != IsAtLeastTLSv1_3(ssl->version)) {
  33888. WOLFSSL_MSG("Tickets cannot be shared between "
  33889. "TLS 1.3 and TLS 1.2 and lower");
  33890. return VERSION_ERROR;
  33891. }
  33892. if (!ssl->options.downgrade) {
  33893. WOLFSSL_MSG("Ticket has lesser version");
  33894. return VERSION_ERROR;
  33895. }
  33896. WOLFSSL_MSG("Downgrading protocol due to ticket");
  33897. if (it->pv.minor < ssl->options.minDowngrade) {
  33898. WOLFSSL_MSG("Ticket has lesser version than allowed");
  33899. return VERSION_ERROR;
  33900. }
  33901. }
  33902. #ifdef WOLFSSL_TLS13
  33903. /* Check resumption master secret. */
  33904. if (IsAtLeastTLSv1_3(it->pv) &&
  33905. it->ticketNonceLen > MAX_TICKET_NONCE_STATIC_SZ) {
  33906. WOLFSSL_MSG("Unsupported ticketNonce len in ticket");
  33907. return BAD_TICKET_ENCRYPT;
  33908. }
  33909. #endif
  33910. return 0;
  33911. }
  33912. #if defined(WOLFSSL_TLS13)
  33913. /* Return 0 when check successful. <0 on failure. */
  33914. int DoClientTicketCheck(const WOLFSSL* ssl, const PreSharedKey* psk,
  33915. sword64 timeout, const byte* suite)
  33916. {
  33917. word32 ticketAdd;
  33918. #ifdef WOLFSSL_32BIT_MILLI_TIME
  33919. word32 now;
  33920. sword64 diff;
  33921. word32 ticketSeen; /* Time ticket seen (ms) */
  33922. ato32(psk->it->timestamp, &ticketSeen);
  33923. now = TimeNowInMilliseconds();
  33924. if (now == 0)
  33925. return GETTIME_ERROR;
  33926. /* Difference between now and time ticket constructed
  33927. * (from decrypted ticket). */
  33928. diff = now;
  33929. diff -= ticketSeen;
  33930. if (diff > timeout * 1000 ||
  33931. diff > (sword64)TLS13_MAX_TICKET_AGE * 1000)
  33932. return WOLFSSL_FATAL_ERROR;
  33933. #else
  33934. sword64 diff;
  33935. sword64 ticketSeen; /* Time ticket seen (ms) */
  33936. word32 seenHi, seenLo;
  33937. ato32(psk->it->timestamp , &seenHi);
  33938. ato32(psk->it->timestamp + OPAQUE32_LEN, &seenLo);
  33939. ticketSeen = ((sword64)seenHi << 32) + seenLo;
  33940. diff = TimeNowInMilliseconds();
  33941. if (diff == 0)
  33942. return GETTIME_ERROR;
  33943. /* Difference between now and time ticket constructed
  33944. * (from decrypted ticket). */
  33945. diff -= ticketSeen;
  33946. if (diff > timeout * 1000 ||
  33947. diff > (sword64)TLS13_MAX_TICKET_AGE * 1000)
  33948. return WOLFSSL_FATAL_ERROR;
  33949. #endif
  33950. ato32(psk->it->ageAdd, &ticketAdd);
  33951. /* Subtract client's ticket age and unobfuscate. */
  33952. diff -= psk->ticketAge;
  33953. diff += ticketAdd;
  33954. /* Check session and ticket age timeout.
  33955. * Allow +/- 1000 milliseconds on ticket age.
  33956. */
  33957. if (diff < -1000 || diff - MAX_TICKET_AGE_DIFF * 1000 > 1000)
  33958. return WOLFSSL_FATAL_ERROR;
  33959. #if !defined(WOLFSSL_PSK_ONE_ID) && !defined(WOLFSSL_PRIORITIZE_PSK)
  33960. /* Check whether resumption is possible based on suites in SSL and
  33961. * ciphersuite in ticket.
  33962. */
  33963. (void)ssl;
  33964. if (XMEMCMP(suite, psk->it->suite, SUITE_LEN) != 0)
  33965. return WOLFSSL_FATAL_ERROR;
  33966. #else
  33967. (void)suite;
  33968. if (!FindSuiteSSL(ssl, psk->it->suite))
  33969. return WOLFSSL_FATAL_ERROR;
  33970. #endif
  33971. #ifdef OPENSSL_EXTRA
  33972. if (ssl->sessionCtxSz > 0 &&
  33973. (psk->it->sessionCtxSz != ssl->sessionCtxSz ||
  33974. XMEMCMP(psk->it->sessionCtx, ssl->sessionCtx,
  33975. ssl->sessionCtxSz) != 0))
  33976. return WOLFSSL_FATAL_ERROR;
  33977. #endif
  33978. return 0;
  33979. }
  33980. #endif /* WOLFSSL_SLT13 */
  33981. void DoClientTicketFinalize(WOLFSSL* ssl, InternalTicket* it,
  33982. const WOLFSSL_SESSION* sess)
  33983. {
  33984. #ifdef WOLFSSL_TICKET_HAVE_ID
  33985. ssl->session->haveAltSessionID = 1;
  33986. XMEMCPY(ssl->session->altSessionID, it->id, ID_LEN);
  33987. #endif
  33988. if (sess != NULL) {
  33989. byte bogusID[ID_LEN];
  33990. byte bogusIDSz = ssl->session->sessionIDSz;
  33991. XMEMCPY(bogusID, ssl->session->sessionID, ID_LEN);
  33992. /* Failure here should not interrupt the resumption. We already have
  33993. * all the cipher material we need in `it` */
  33994. WOLFSSL_MSG("Copying in session from passed in arg");
  33995. (void)wolfSSL_DupSession(sess, ssl->session, 1);
  33996. /* Restore the fake ID */
  33997. XMEMCPY(ssl->session->sessionID, bogusID, ID_LEN);
  33998. ssl->session->sessionIDSz= bogusIDSz;
  33999. }
  34000. #ifdef WOLFSSL_TICKET_HAVE_ID
  34001. else {
  34002. if (wolfSSL_GetSession(ssl, NULL, 1) != NULL) {
  34003. WOLFSSL_MSG("Found session matching the session id"
  34004. " found in the ticket");
  34005. }
  34006. else {
  34007. WOLFSSL_MSG("Can't find session matching the session id"
  34008. " found in the ticket");
  34009. }
  34010. }
  34011. #endif
  34012. if (!IsAtLeastTLSv1_3(ssl->version)) {
  34013. XMEMCPY(ssl->arrays->masterSecret, it->msecret, SECRET_LEN);
  34014. /* Copy the haveExtendedMasterSecret property from the ticket to
  34015. * the saved session, so the property may be checked later. */
  34016. ssl->session->haveEMS = it->haveEMS;
  34017. ato32((const byte*)&it->timestamp, &ssl->session->bornOn);
  34018. #ifndef NO_RESUME_SUITE_CHECK
  34019. ssl->session->cipherSuite0 = it->suite[0];
  34020. ssl->session->cipherSuite = it->suite[1];
  34021. #endif
  34022. }
  34023. else {
  34024. #ifdef WOLFSSL_TLS13
  34025. /* This should have been already checked in
  34026. * DoClientTicketCheckVersion */
  34027. if (it->ticketNonceLen > MAX_TICKET_NONCE_STATIC_SZ) {
  34028. WOLFSSL_MSG("Unsupported ticketNonce len in ticket");
  34029. return;
  34030. }
  34031. /* Restore information to renegotiate. */
  34032. #ifdef WOLFSSL_32BIT_MILLI_TIME
  34033. ato32(it->timestamp, &ssl->session->ticketSeen);
  34034. #else
  34035. {
  34036. word32 seenHi, seenLo;
  34037. ato32(it->timestamp , &seenHi);
  34038. ato32(it->timestamp + OPAQUE32_LEN, &seenLo);
  34039. ssl->session->ticketSeen = ((sword64)seenHi << 32) + seenLo;
  34040. }
  34041. #endif
  34042. ato32(it->ageAdd, &ssl->session->ticketAdd);
  34043. ssl->session->cipherSuite0 = it->suite[0];
  34044. ssl->session->cipherSuite = it->suite[1];
  34045. #ifdef WOLFSSL_EARLY_DATA
  34046. ato32(it->maxEarlyDataSz, &ssl->session->maxEarlyDataSz);
  34047. #endif
  34048. /* Resumption master secret. */
  34049. XMEMCPY(ssl->session->masterSecret, it->msecret, SECRET_LEN);
  34050. #if defined(WOLFSSL_TICKET_NONCE_MALLOC) && \
  34051. (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
  34052. if (ssl->session->ticketNonce.data
  34053. != ssl->session->ticketNonce.dataStatic) {
  34054. XFREE(ssl->session->ticketNonce.data, ssl->heap,
  34055. DYNAMIC_TYPE_SESSION_TICK);
  34056. ssl->session->ticketNonce.data =
  34057. ssl->session->ticketNonce.dataStatic;
  34058. }
  34059. #endif /* defined(WOLFSSL_TICKET_NONCE_MALLOC) && FIPS_VERSION_GE(5,3) */
  34060. XMEMCPY(ssl->session->ticketNonce.data, it->ticketNonce,
  34061. it->ticketNonceLen);
  34062. ssl->session->ticketNonce.len = it->ticketNonceLen;
  34063. ato16(it->namedGroup, &ssl->session->namedGroup);
  34064. #endif
  34065. }
  34066. ssl->version.minor = it->pv.minor;
  34067. }
  34068. #if defined(WOLFSSL_TLS13)
  34069. static void PopulateInternalTicketFromSession(const WOLFSSL_SESSION* sess,
  34070. InternalTicket* it)
  34071. {
  34072. #ifdef WOLFSSL_32BIT_MILLI_TIME
  34073. word32 milliBornOn = sess->bornOn;
  34074. #else
  34075. sword64 milliBornOn = (sword64)sess->bornOn;
  34076. #endif
  34077. /* Convert to milliseconds */
  34078. milliBornOn *= 1000;
  34079. it->pv = sess->version;
  34080. it->suite[0] = sess->cipherSuite0;
  34081. it->suite[1] = sess->cipherSuite;
  34082. XMEMCPY(it->msecret, sess->masterSecret, SECRET_LEN);
  34083. #ifdef WOLFSSL_32BIT_MILLI_TIME
  34084. c32toa(milliBornOn, it->timestamp);
  34085. #else
  34086. c32toa((word32)(milliBornOn >> 32), it->timestamp);
  34087. c32toa((word32)milliBornOn , it->timestamp + OPAQUE32_LEN);
  34088. #endif
  34089. it->haveEMS = (byte)sess->haveEMS;
  34090. c32toa(sess->ticketAdd, it->ageAdd);
  34091. c16toa(sess->namedGroup, it->namedGroup);
  34092. if (sess->ticketNonce.len <= MAX_TICKET_NONCE_STATIC_SZ) {
  34093. it->ticketNonceLen = sess->ticketNonce.len;
  34094. XMEMCPY(it->ticketNonce, sess->ticketNonce.data,
  34095. sess->ticketNonce.len);
  34096. }
  34097. #ifdef WOLFSSL_EARLY_DATA
  34098. c32toa(sess->maxEarlyDataSz, it->maxEarlyDataSz);
  34099. #endif
  34100. #ifdef WOLFSSL_TICKET_HAVE_ID
  34101. if (sess->haveAltSessionID)
  34102. XMEMCPY(it->id, sess->altSessionID, ID_LEN);
  34103. else
  34104. XMEMCPY(it->id, sess->sessionID, ID_LEN);
  34105. #endif
  34106. #ifdef OPENSSL_EXTRA
  34107. it->sessionCtxSz = sess->sessionCtxSz;
  34108. XMEMCPY(it->sessionCtx, sess->sessionCtx, sess->sessionCtxSz);
  34109. #endif
  34110. }
  34111. static const WOLFSSL_SESSION* GetSesionFromCacheOrExt(const WOLFSSL* ssl,
  34112. const byte* id, psk_sess_free_cb_ctx* freeCtx)
  34113. {
  34114. const WOLFSSL_SESSION* sess = NULL;
  34115. int ret;
  34116. XMEMSET(freeCtx, 0, sizeof(*freeCtx));
  34117. #ifdef HAVE_EXT_CACHE
  34118. if (ssl->ctx->get_sess_cb != NULL) {
  34119. int copy = 0;
  34120. sess = ssl->ctx->get_sess_cb((WOLFSSL*)ssl,
  34121. id, ID_LEN, &copy);
  34122. if (sess != NULL) {
  34123. freeCtx->extCache = 1;
  34124. /* If copy not set then free immediately */
  34125. if (!copy)
  34126. freeCtx->freeSess = 1;
  34127. }
  34128. }
  34129. #endif
  34130. if (sess == NULL) {
  34131. ret = TlsSessionCacheGetAndRdLock(id, &sess, &freeCtx->row,
  34132. (byte)ssl->options.side);
  34133. if (ret != 0)
  34134. sess = NULL;
  34135. }
  34136. return sess;
  34137. }
  34138. static void FreeSessionFromCacheOrExt(const WOLFSSL* ssl,
  34139. const WOLFSSL_SESSION* sess, psk_sess_free_cb_ctx* freeCtx)
  34140. {
  34141. (void)ssl;
  34142. (void)sess;
  34143. #ifdef HAVE_EXT_CACHE
  34144. if (freeCtx->extCache) {
  34145. if (freeCtx->freeSess)
  34146. /* In this case sess is not longer const and the external cache
  34147. * wants us to free it. */
  34148. wolfSSL_FreeSession(ssl->ctx, (WOLFSSL_SESSION*)sess);
  34149. }
  34150. else
  34151. #endif
  34152. TlsSessionCacheUnlockRow(freeCtx->row);
  34153. }
  34154. /* Parse ticket sent by client, returns callback return value. Doesn't
  34155. * modify ssl and stores the InternalTicket inside psk */
  34156. int DoClientTicket_ex(const WOLFSSL* ssl, PreSharedKey* psk, int retainSess)
  34157. {
  34158. int ret;
  34159. int decryptRet = WOLFSSL_TICKET_RET_REJECT;
  34160. WOLFSSL_START(WC_FUNC_TICKET_DO);
  34161. WOLFSSL_ENTER("DoClientTicket_ex");
  34162. if (psk->identityLen == ID_LEN && IsAtLeastTLSv1_3(ssl->version)) {
  34163. /* This is a stateful ticket. We can be sure about this because
  34164. * stateless tickets are much longer. */
  34165. const WOLFSSL_SESSION* sess = NULL;
  34166. sess = GetSesionFromCacheOrExt(ssl, psk->identity,
  34167. &psk->sess_free_cb_ctx);
  34168. if (sess != NULL) {
  34169. /* Session found in cache. Copy in relevant info to psk */
  34170. byte* tmp;
  34171. WOLFSSL_MSG("Found session matching the session id"
  34172. " found in the ticket");
  34173. /* Allocate and populate an InternalTicket */
  34174. tmp = (byte*)XREALLOC(psk->identity, sizeof(InternalTicket),
  34175. ssl->heap, DYNAMIC_TYPE_TLSX);
  34176. if (tmp != NULL) {
  34177. XMEMSET(tmp, 0, sizeof(InternalTicket));
  34178. psk->identity = tmp;
  34179. psk->identityLen = sizeof(InternalTicket);
  34180. psk->it = (InternalTicket*)tmp;
  34181. PopulateInternalTicketFromSession(sess, psk->it);
  34182. decryptRet = WOLFSSL_TICKET_RET_OK;
  34183. if (retainSess) {
  34184. psk->sess = sess;
  34185. psk->sess_free_cb = FreeSessionFromCacheOrExt;
  34186. }
  34187. }
  34188. if (psk->sess == NULL) {
  34189. FreeSessionFromCacheOrExt(ssl, sess,
  34190. &psk->sess_free_cb_ctx);
  34191. XMEMSET(&psk->sess_free_cb_ctx, 0,
  34192. sizeof(psk_sess_free_cb_ctx));
  34193. }
  34194. }
  34195. }
  34196. else {
  34197. decryptRet = DoDecryptTicket(ssl, psk->identity, psk->identityLen,
  34198. &psk->it);
  34199. }
  34200. switch (decryptRet) {
  34201. case WOLFSSL_TICKET_RET_OK:
  34202. psk->decryptRet = PSK_DECRYPT_OK;
  34203. break;
  34204. case WOLFSSL_TICKET_RET_CREATE:
  34205. psk->decryptRet = PSK_DECRYPT_CREATE;
  34206. break;
  34207. default:
  34208. psk->decryptRet = PSK_DECRYPT_FAIL;
  34209. WOLFSSL_LEAVE("DoClientTicket_ex", decryptRet);
  34210. return decryptRet;
  34211. }
  34212. #ifdef WOLFSSL_CHECK_MEM_ZERO
  34213. /* Internal ticket successfully decrypted. */
  34214. wc_MemZero_Add("Do Client Ticket internal", psk->it,
  34215. sizeof(InternalTicket));
  34216. #endif
  34217. ret = DoClientTicketCheckVersion(ssl, psk->it);
  34218. if (ret != 0) {
  34219. psk->decryptRet = PSK_DECRYPT_FAIL;
  34220. ForceZero(psk->identity, psk->identityLen);
  34221. #ifdef WOLFSSL_CHECK_MEM_ZERO
  34222. wc_MemZero_Check(psk->it, sizeof(InternalTicket));
  34223. #endif
  34224. WOLFSSL_LEAVE("DoClientTicket_ex", ret);
  34225. return ret;
  34226. }
  34227. WOLFSSL_LEAVE("DoClientTicket_ex", decryptRet);
  34228. return decryptRet;
  34229. }
  34230. #endif /* WOLFSL_TLS13 */
  34231. /* Parse ticket sent by client, returns callback return value */
  34232. int DoClientTicket(WOLFSSL* ssl, const byte* input, word32 len)
  34233. {
  34234. int decryptRet = WOLFSSL_TICKET_RET_REJECT;
  34235. int ret;
  34236. InternalTicket* it = NULL;
  34237. #ifdef WOLFSSL_TLS13
  34238. InternalTicket staticIt;
  34239. const WOLFSSL_SESSION* sess = NULL;
  34240. psk_sess_free_cb_ctx freeCtx;
  34241. XMEMSET(&freeCtx, 0, sizeof(psk_sess_free_cb_ctx));
  34242. #endif
  34243. WOLFSSL_START(WC_FUNC_TICKET_DO);
  34244. WOLFSSL_ENTER("DoClientTicket");
  34245. #ifdef HAVE_SECRET_CALLBACK
  34246. if (ssl->ticketParseCb != NULL) {
  34247. decryptRet = WOLFSSL_TICKET_RET_OK;
  34248. if (!ssl->ticketParseCb(ssl, input, len, ssl->ticketParseCtx)) {
  34249. /* Failure kills the connection */
  34250. decryptRet = WOLFSSL_TICKET_RET_FATAL;
  34251. }
  34252. else {
  34253. if (wolfSSL_set_SessionTicket(ssl, input, len) !=
  34254. WOLFSSL_SUCCESS)
  34255. decryptRet = WOLFSSL_TICKET_RET_REJECT;
  34256. }
  34257. goto cleanup;
  34258. }
  34259. else
  34260. #endif
  34261. #ifdef WOLFSSL_TLS13
  34262. if (len == ID_LEN && IsAtLeastTLSv1_3(ssl->version)) {
  34263. /* This is a stateful ticket. We can be sure about this because
  34264. * stateless tickets are much longer. */
  34265. sess = GetSesionFromCacheOrExt(ssl, input, &freeCtx);
  34266. if (sess != NULL) {
  34267. it = &staticIt;
  34268. XMEMSET(it, 0, sizeof(InternalTicket));
  34269. PopulateInternalTicketFromSession(sess, it);
  34270. decryptRet = WOLFSSL_TICKET_RET_OK;
  34271. }
  34272. }
  34273. else
  34274. #endif
  34275. if (len >= sizeof(*it))
  34276. decryptRet = DoDecryptTicket(ssl, input, len, &it);
  34277. else
  34278. WOLFSSL_MSG("Ticket is smaller than InternalTicket. Rejecting.");
  34279. if (decryptRet != WOLFSSL_TICKET_RET_OK &&
  34280. decryptRet != WOLFSSL_TICKET_RET_CREATE) {
  34281. it = NULL;
  34282. goto cleanup;
  34283. }
  34284. #ifdef WOLFSSL_CHECK_MEM_ZERO
  34285. /* Internal ticket successfully decrypted. */
  34286. wc_MemZero_Add("Do Client Ticket internal", it, sizeof(InternalTicket));
  34287. #endif
  34288. ret = DoClientTicketCheckVersion(ssl, it);
  34289. if (ret != 0) {
  34290. decryptRet = ret;
  34291. goto cleanup;
  34292. }
  34293. DoClientTicketFinalize(ssl, it, NULL);
  34294. cleanup:
  34295. if (it != NULL) {
  34296. ForceZero(it, sizeof(*it));
  34297. #ifdef WOLFSSL_CHECK_MEM_ZERO
  34298. wc_MemZero_Check(it, sizeof(InternalTicket));
  34299. #endif
  34300. }
  34301. #ifdef WOLFSSL_TLS13
  34302. if (sess != NULL)
  34303. FreeSessionFromCacheOrExt(ssl, sess, &freeCtx);
  34304. #endif
  34305. return decryptRet;
  34306. }
  34307. #ifdef WOLFSSL_TLS13
  34308. void CleanupClientTickets(PreSharedKey* psk)
  34309. {
  34310. for (; psk != NULL; psk = psk->next) {
  34311. if (psk->decryptRet == PSK_DECRYPT_OK ||
  34312. psk->decryptRet == PSK_DECRYPT_CREATE) {
  34313. psk->decryptRet = PSK_DECRYPT_NONE;
  34314. ForceZero(psk->identity, psk->identityLen);
  34315. #ifdef WOLFSSL_CHECK_MEM_ZERO
  34316. /* We want to check the InternalTicket area since that is what
  34317. * we registered in DoClientTicket_ex */
  34318. wc_MemZero_Check((((ExternalTicket*)psk->identity)->enc_ticket),
  34319. sizeof(InternalTicket));
  34320. #endif
  34321. }
  34322. }
  34323. }
  34324. #endif /* WOLFSSL_TLS13 */
  34325. /* send Session Ticket */
  34326. int SendTicket(WOLFSSL* ssl)
  34327. {
  34328. byte* output;
  34329. int ret;
  34330. int sendSz;
  34331. word32 length = SESSION_HINT_SZ + LENGTH_SZ;
  34332. word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  34333. WOLFSSL_START(WC_FUNC_TICKET_SEND);
  34334. WOLFSSL_ENTER("SendTicket");
  34335. if (ssl->options.createTicket) {
  34336. ret = SetupTicket(ssl);
  34337. if (ret != 0)
  34338. return ret;
  34339. ret = CreateTicket(ssl);
  34340. if (ret != 0)
  34341. return ret;
  34342. }
  34343. length += ssl->session->ticketLen;
  34344. sendSz = (int)length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  34345. if (!ssl->options.dtls) {
  34346. if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone)
  34347. sendSz += MAX_MSG_EXTRA;
  34348. }
  34349. else {
  34350. #ifdef WOLFSSL_DTLS
  34351. sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  34352. idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  34353. #endif
  34354. }
  34355. if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone)
  34356. sendSz += cipherExtraData(ssl);
  34357. /* Set this in case CheckAvailableSize returns a WANT_WRITE so that state
  34358. * is not advanced yet */
  34359. ssl->options.buildingMsg = 1;
  34360. /* check for available size */
  34361. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  34362. return ret;
  34363. /* get output buffer */
  34364. output = GetOutputBuffer(ssl);
  34365. AddHeaders(output, length, session_ticket, ssl);
  34366. /* hint */
  34367. c32toa(ssl->ctx->ticketHint, output + idx);
  34368. idx += SESSION_HINT_SZ;
  34369. /* length */
  34370. c16toa(ssl->session->ticketLen, output + idx);
  34371. idx += LENGTH_SZ;
  34372. /* ticket */
  34373. XMEMCPY(output + idx, ssl->session->ticket, ssl->session->ticketLen);
  34374. idx += ssl->session->ticketLen;
  34375. if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone) {
  34376. byte* input;
  34377. int inputSz = (int)idx; /* build msg adds rec hdr */
  34378. int recordHeaderSz = RECORD_HEADER_SZ;
  34379. if (ssl->options.dtls)
  34380. recordHeaderSz += DTLS_RECORD_EXTRA;
  34381. inputSz -= recordHeaderSz;
  34382. input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  34383. if (input == NULL)
  34384. return MEMORY_E;
  34385. XMEMCPY(input, output + recordHeaderSz, inputSz);
  34386. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  34387. handshake, 1, 0, 0, CUR_ORDER);
  34388. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  34389. if (sendSz < 0)
  34390. return sendSz;
  34391. }
  34392. else {
  34393. #ifdef WOLFSSL_DTLS
  34394. if (ssl->options.dtls) {
  34395. if ((ret = DtlsMsgPoolSave(ssl, output, (word32)sendSz, session_ticket)) != 0)
  34396. return ret;
  34397. DtlsSEQIncrement(ssl, CUR_ORDER);
  34398. }
  34399. #endif
  34400. ret = HashOutput(ssl, output, sendSz, 0);
  34401. if (ret != 0)
  34402. return ret;
  34403. }
  34404. ssl->buffers.outputBuffer.length += sendSz;
  34405. ssl->options.buildingMsg = 0;
  34406. if (!ssl->options.groupMessages)
  34407. ret = SendBuffered(ssl);
  34408. WOLFSSL_LEAVE("SendTicket", ret);
  34409. WOLFSSL_END(WC_FUNC_TICKET_SEND);
  34410. return ret;
  34411. }
  34412. #ifndef WOLFSSL_NO_DEF_TICKET_ENC_CB
  34413. /* Initialize the context for session ticket encryption.
  34414. *
  34415. * @param [in] ctx SSL context.
  34416. * @param [in] keyCtx Context for session ticket encryption.
  34417. * @return 0 on success.
  34418. * @return BAD_MUTEX_E when initializing mutex fails.
  34419. */
  34420. static int TicketEncCbCtx_Init(WOLFSSL_CTX* ctx, TicketEncCbCtx* keyCtx)
  34421. {
  34422. int ret = 0;
  34423. XMEMSET(keyCtx, 0, sizeof(*keyCtx));
  34424. keyCtx->ctx = ctx;
  34425. #ifdef WOLFSSL_CHECK_MEM_ZERO
  34426. wc_MemZero_Add("TicketEncCbCtx_Init keyCtx->name", keyCtx->name,
  34427. sizeof(keyCtx->name));
  34428. wc_MemZero_Add("TicketEncCbCtx_Init keyCtx->key[0]", keyCtx->key[0],
  34429. sizeof(keyCtx->key[0]));
  34430. wc_MemZero_Add("TicketEncCbCtx_Init keyCtx->key[1]", keyCtx->key[1],
  34431. sizeof(keyCtx->key[1]));
  34432. #endif
  34433. #ifndef SINGLE_THREADED
  34434. ret = wc_InitMutex(&keyCtx->mutex);
  34435. #endif
  34436. return ret;
  34437. }
  34438. /* Setup the session ticket encryption context for this.
  34439. *
  34440. * Initialize RNG, generate name, generate primary key and set primary key
  34441. * expirary.
  34442. *
  34443. * @param [in] keyCtx Context for session ticket encryption.
  34444. * @param [in] heap Dynamic memory allocation hint.
  34445. * @param [in] devId Device identifier.
  34446. * @return 0 on success.
  34447. * @return Other value when random number generator fails.
  34448. */
  34449. static int TicketEncCbCtx_Setup(TicketEncCbCtx* keyCtx, void* heap, int devId)
  34450. {
  34451. int ret;
  34452. #ifndef SINGLE_THREADED
  34453. ret = 0;
  34454. /* Check that key wasn't set up while waiting. */
  34455. if (keyCtx->expirary[0] == 0)
  34456. #endif
  34457. {
  34458. ret = wc_InitRng_ex(&keyCtx->rng, heap, devId);
  34459. if (ret == 0) {
  34460. ret = wc_RNG_GenerateBlock(&keyCtx->rng, keyCtx->name,
  34461. sizeof(keyCtx->name));
  34462. }
  34463. if (ret == 0) {
  34464. /* Mask of the bottom bit - used for index of key. */
  34465. keyCtx->name[WOLFSSL_TICKET_NAME_SZ - 1] &= 0xfe;
  34466. /* Generate initial primary key. */
  34467. ret = wc_RNG_GenerateBlock(&keyCtx->rng, keyCtx->key[0],
  34468. WOLFSSL_TICKET_KEY_SZ);
  34469. }
  34470. if (ret == 0) {
  34471. keyCtx->expirary[0] = LowResTimer() + WOLFSSL_TICKET_KEY_LIFETIME;
  34472. }
  34473. }
  34474. return ret;
  34475. }
  34476. /* Free the context for session ticket encryption.
  34477. *
  34478. * Zeroize keys and name.
  34479. *
  34480. * @param [in] keyCtx Context for session ticket encryption.
  34481. */
  34482. static void TicketEncCbCtx_Free(TicketEncCbCtx* keyCtx)
  34483. {
  34484. /* Zeroize sensitive data. */
  34485. ForceZero(keyCtx->name, sizeof(keyCtx->name));
  34486. ForceZero(keyCtx->key[0], sizeof(keyCtx->key[0]));
  34487. ForceZero(keyCtx->key[1], sizeof(keyCtx->key[1]));
  34488. #ifdef WOLFSSL_CHECK_MEM_ZERO
  34489. wc_MemZero_Check(keyCtx->name, sizeof(keyCtx->name));
  34490. wc_MemZero_Check(keyCtx->key[0], sizeof(keyCtx->key[0]));
  34491. wc_MemZero_Check(keyCtx->key[1], sizeof(keyCtx->key[1]));
  34492. #endif
  34493. #ifndef SINGLE_THREADED
  34494. wc_FreeMutex(&keyCtx->mutex);
  34495. #endif
  34496. wc_FreeRng(&keyCtx->rng);
  34497. }
  34498. #ifdef WOLFSSL_TICKET_ENC_CBC_HMAC
  34499. /* Ticket encryption/decryption implementation.
  34500. *
  34501. * @param [in] key Key for encryption/decryption and HMAC.
  34502. * @param [in] keyLen Length of key in bytes.
  34503. * @param [in] iv IV/Nonce for encryption/decryption.
  34504. * @param [in] aad Additional authentication data.
  34505. * @param [in] aadSz Length of additional authentication data.
  34506. * @param [in] in Data to encrypt/decrypt.
  34507. * @param [in] inLen Length of encrypted data.
  34508. * @param [out] out Resulting data from encrypt/decrypt.
  34509. * @param [out] outLen Size of resulting data.
  34510. * @param [in] tag Authentication tag for encrypted data.
  34511. * @param [in] heap Dynamic memory allocation data hint.
  34512. * @param [in] enc 1 when encrypting, 0 when decrypting.
  34513. * @return 0 on success.
  34514. * @return Other value when encryption/decryption fails.
  34515. */
  34516. static int TicketEncDec(byte* key, int keyLen, byte* iv, byte* aad, int aadSz,
  34517. byte* in, int inLen, byte* out, int* outLen, byte* tag,
  34518. void* heap, int enc)
  34519. {
  34520. int ret;
  34521. #ifdef WOLFSSL_SMALL_STACK
  34522. Aes* aes;
  34523. Hmac* hmac;
  34524. #else
  34525. Aes aes[1];
  34526. Hmac hmac[1];
  34527. #endif
  34528. (void)heap;
  34529. #ifdef WOLFSSL_SMALL_STACK
  34530. aes = (Aes*)XMALLOC(sizeof(Aes), heap, DYNAMIC_TYPE_TMP_BUFFER);
  34531. if (aes == NULL)
  34532. return MEMORY_E;
  34533. hmac = (Hmac*)XMALLOC(sizeof(Hmac), heap, DYNAMIC_TYPE_TMP_BUFFER);
  34534. if (hmac == NULL) {
  34535. XFREE(aes, heap, DYNAMIC_TYPE_TMP_BUFFER);
  34536. return MEMORY_E;
  34537. }
  34538. #endif
  34539. XMEMSET(aes, 0, sizeof(Aes));
  34540. XMEMSET(hmac, 0, sizeof(Hmac));
  34541. ret = wc_HmacInit(hmac, heap, DYNAMIC_TYPE_TMP_BUFFER);
  34542. if (ret == 0) {
  34543. ret = wc_HmacSetKey(hmac, WOLFSSL_TICKET_ENC_HMAC, key + keyLen -
  34544. WOLFSSL_TICKET_HMAC_KEY_SZ, WOLFSSL_TICKET_HMAC_KEY_SZ);
  34545. }
  34546. if (ret == 0) {
  34547. ret = wc_HmacUpdate(hmac, aad, aadSz);
  34548. }
  34549. if (ret == 0) {
  34550. if (enc) {
  34551. ret = wc_AesInit(aes, NULL, INVALID_DEVID);
  34552. if (ret == 0) {
  34553. ret = wc_AesSetKey(aes, key,
  34554. keyLen - WOLFSSL_TICKET_HMAC_KEY_SZ, iv, AES_ENCRYPTION);
  34555. }
  34556. if (ret == 0) {
  34557. ret = wc_HmacUpdate(hmac, in, inLen);
  34558. }
  34559. if (ret == 0) {
  34560. ret = wc_AesCbcEncrypt(aes, in, out, inLen);
  34561. }
  34562. if (ret == 0) {
  34563. XMEMSET(tag, 0, WOLFSSL_TICKET_MAC_SZ);
  34564. ret = wc_HmacFinal(hmac, tag);
  34565. }
  34566. wc_AesFree(aes);
  34567. }
  34568. else {
  34569. unsigned char calcTag[WOLFSSL_TICKET_MAC_SZ];
  34570. ret = wc_AesInit(aes, NULL, INVALID_DEVID);
  34571. if (ret == 0) {
  34572. ret = wc_AesSetKey(aes, key,
  34573. keyLen - WOLFSSL_TICKET_HMAC_KEY_SZ, iv, AES_DECRYPTION);
  34574. }
  34575. if (ret == 0) {
  34576. ret = wc_AesCbcDecrypt(aes, in, out, inLen);
  34577. }
  34578. if (ret == 0) {
  34579. ret = wc_HmacUpdate(hmac, out, inLen);
  34580. }
  34581. if (ret == 0) {
  34582. XMEMSET(calcTag, 0, WOLFSSL_TICKET_MAC_SZ);
  34583. ret = wc_HmacFinal(hmac, calcTag);
  34584. }
  34585. if (ret == 0) {
  34586. int i;
  34587. calcTag[0] ^= tag[0];
  34588. for (i = 1; i < WOLFSSL_TICKET_MAC_SZ; i++) {
  34589. calcTag[0] |= calcTag[i] ^ tag[i];
  34590. }
  34591. /* Return a negative value when no match. */
  34592. ret = -calcTag[0];
  34593. }
  34594. wc_AesFree(aes);
  34595. }
  34596. }
  34597. wc_HmacFree(hmac);
  34598. #ifdef WOLFSSL_SMALL_STACK
  34599. XFREE(hmac, heap, DYNAMIC_TYPE_TMP_BUFFER);
  34600. XFREE(aes, heap, DYNAMIC_TYPE_TMP_BUFFER);
  34601. #endif
  34602. *outLen = inLen;
  34603. return ret;
  34604. }
  34605. #elif defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \
  34606. !defined(WOLFSSL_TICKET_ENC_AES128_GCM) && \
  34607. !defined(WOLFSSL_TICKET_ENC_AES256_GCM)
  34608. /* Ticket encryption/decryption implementation.
  34609. *
  34610. * @param [in] key Key for encryption/decryption.
  34611. * @param [in] keyLen Length of key in bytes.
  34612. * @param [in] iv IV/Nonce for encryption/decryption.
  34613. * @param [in] aad Additional authentication data.
  34614. * @param [in] aadSz Length of additional authentication data.
  34615. * @param [in] in Data to encrypt/decrypt.
  34616. * @param [in] inLen Length of encrypted data.
  34617. * @param [out] out Resulting data from encrypt/decrypt.
  34618. * @param [out] outLen Size of resulting data.
  34619. * @param [in] tag Authentication tag for encrypted data.
  34620. * @param [in] heap Dynamic memory allocation data hint.
  34621. * @param [in] enc 1 when encrypting, 0 when decrypting.
  34622. * @return 0 on success.
  34623. * @return Other value when encryption/decryption fails.
  34624. */
  34625. static int TicketEncDec(byte* key, int keyLen, byte* iv, byte* aad, int aadSz,
  34626. byte* in, int inLen, byte* out, int* outLen, byte* tag,
  34627. void* heap, int enc)
  34628. {
  34629. int ret;
  34630. (void)keyLen;
  34631. (void)heap;
  34632. if (enc) {
  34633. ret = wc_ChaCha20Poly1305_Encrypt(key, iv, aad, aadSz, in, inLen, out,
  34634. tag);
  34635. }
  34636. else {
  34637. ret = wc_ChaCha20Poly1305_Decrypt(key, iv, aad, aadSz, in, inLen, tag,
  34638. out);
  34639. }
  34640. *outLen = inLen;
  34641. return ret;
  34642. }
  34643. #elif defined(HAVE_AESGCM)
  34644. /* Ticket encryption/decryption implementation.
  34645. *
  34646. * @param [in] key Key for encryption/decryption.
  34647. * @param [in] keyLen Length of key in bytes.
  34648. * @param [in] iv IV/Nonce for encryption/decryption.
  34649. * @param [in] aad Additional authentication data.
  34650. * @param [in] aadSz Length of additional authentication data.
  34651. * @param [in] in Data to encrypt/decrypt.
  34652. * @param [in] inLen Length of encrypted data.
  34653. * @param [out] out Resulting data from encrypt/decrypt.
  34654. * @param [out] outLen Size of resulting data.
  34655. * @param [in] tag Authentication tag for encrypted data.
  34656. * @param [in] heap Dynamic memory allocation data hint.
  34657. * @param [in] enc 1 when encrypting, 0 when decrypting.
  34658. * @return 0 on success.
  34659. * @return MEMORY_E when dynamic memory allocation fails.
  34660. * @return Other value when encryption/decryption fails.
  34661. */
  34662. static int TicketEncDec(byte* key, int keyLen, byte* iv, byte* aad, int aadSz,
  34663. byte* in, int inLen, byte* out, int* outLen, byte* tag,
  34664. void* heap, int enc)
  34665. {
  34666. int ret;
  34667. #ifdef WOLFSSL_SMALL_STACK
  34668. Aes* aes;
  34669. #else
  34670. Aes aes[1];
  34671. #endif
  34672. (void)heap;
  34673. #ifdef WOLFSSL_SMALL_STACK
  34674. aes = (Aes*)XMALLOC(sizeof(Aes), heap, DYNAMIC_TYPE_TMP_BUFFER);
  34675. if (aes == NULL)
  34676. return MEMORY_E;
  34677. #endif
  34678. if (enc) {
  34679. ret = wc_AesInit(aes, NULL, INVALID_DEVID);
  34680. if (ret == 0) {
  34681. ret = wc_AesGcmSetKey(aes, key, keyLen);
  34682. }
  34683. if (ret == 0) {
  34684. ret = wc_AesGcmEncrypt(aes, in, out, inLen, iv, GCM_NONCE_MID_SZ,
  34685. tag, AES_BLOCK_SIZE, aad, aadSz);
  34686. }
  34687. wc_AesFree(aes);
  34688. }
  34689. else {
  34690. ret = wc_AesInit(aes, NULL, INVALID_DEVID);
  34691. if (ret == 0) {
  34692. ret = wc_AesGcmSetKey(aes, key, keyLen);
  34693. }
  34694. if (ret == 0) {
  34695. ret = wc_AesGcmDecrypt(aes, in, out, inLen, iv, GCM_NONCE_MID_SZ,
  34696. tag, AES_BLOCK_SIZE, aad, aadSz);
  34697. }
  34698. wc_AesFree(aes);
  34699. }
  34700. #ifdef WOLFSSL_SMALL_STACK
  34701. XFREE(aes, heap, DYNAMIC_TYPE_TMP_BUFFER);
  34702. #endif
  34703. *outLen = inLen;
  34704. return ret;
  34705. }
  34706. #elif defined(WOLFSSL_SM4_GCM)
  34707. /* Ticket encryption/decryption implementation.
  34708. *
  34709. * @param [in] key Key for encryption/decryption.
  34710. * @param [in] keyLen Length of key in bytes.
  34711. * @param [in] iv IV/Nonce for encryption/decryption.
  34712. * @param [in] aad Additional authentication data.
  34713. * @param [in] aadSz Length of additional authentication data.
  34714. * @param [in] in Data to encrypt/decrypt.
  34715. * @param [in] inLen Length of encrypted data.
  34716. * @param [out] out Resulting data from encrypt/decrypt.
  34717. * @param [out] outLen Size of resulting data.
  34718. * @param [in] tag Authentication tag for encrypted data.
  34719. * @param [in] heap Dynamic memory allocation data hint.
  34720. * @param [in] enc 1 when encrypting, 0 when decrypting.
  34721. * @return 0 on success.
  34722. * @return MEMORY_E when dynamic memory allocation fails.
  34723. * @return Other value when encryption/decryption fails.
  34724. */
  34725. static int TicketEncDec(byte* key, int keyLen, byte* iv, byte* aad, int aadSz,
  34726. byte* in, int inLen, byte* out, int* outLen, byte* tag,
  34727. void* heap, int enc)
  34728. {
  34729. int ret;
  34730. #ifdef WOLFSSL_SMALL_STACK
  34731. wc_Sm4* sm4;
  34732. #else
  34733. wc_Sm4 sm4[1];
  34734. #endif
  34735. (void)heap;
  34736. #ifdef WOLFSSL_SMALL_STACK
  34737. sm4 = (wc_Sm4*)XMALLOC(sizeof(wc_Sm4), heap, DYNAMIC_TYPE_TMP_BUFFER);
  34738. if (sm4 == NULL)
  34739. return MEMORY_E;
  34740. #endif
  34741. if (enc) {
  34742. ret = wc_Sm4Init(sm4, NULL, INVALID_DEVID);
  34743. if (ret == 0) {
  34744. ret = wc_Sm4GcmSetKey(sm4, key, keyLen);
  34745. }
  34746. if (ret == 0) {
  34747. ret = wc_Sm4GcmEncrypt(sm4, in, out, inLen, iv, GCM_NONCE_MID_SZ,
  34748. tag, SM4_BLOCK_SIZE, aad, aadSz);
  34749. }
  34750. wc_Sm4Free(sm4);
  34751. }
  34752. else {
  34753. ret = wc_Sm4Init(sm4, NULL, INVALID_DEVID);
  34754. if (ret == 0) {
  34755. ret = wc_Sm4GcmSetKey(sm4, key, keyLen);
  34756. }
  34757. if (ret == 0) {
  34758. ret = wc_Sm4GcmDecrypt(sm4, in, out, inLen, iv, GCM_NONCE_MID_SZ,
  34759. tag, SM$_BLOCK_SIZE, aad, aadSz);
  34760. }
  34761. wc_Sm4Free(sm4);
  34762. }
  34763. #ifdef WOLFSSL_SMALL_STACK
  34764. XFREE(sm4, heap, DYNAMIC_TYPE_TMP_BUFFER);
  34765. #endif
  34766. *outLen = inLen;
  34767. return ret;
  34768. }
  34769. #else
  34770. #error "No encryption algorithm available for default ticket encryption."
  34771. #endif
  34772. /* Choose a key to use for encryption.
  34773. *
  34774. * Generate a new key if the current ones are expired.
  34775. * If the secondary key has not been used and the primary key has expired then
  34776. * generate a new primary key.
  34777. *
  34778. * @param [in] Ticket encryption callback context.
  34779. * @param [in] Session ticket lifetime.
  34780. * @param [out] Index of key to use for encryption.
  34781. * @return 0 on success.
  34782. * @return Other value when random number generation fails.
  34783. */
  34784. static int TicketEncCbCtx_ChooseKey(TicketEncCbCtx* keyCtx, int ticketHint,
  34785. int* keyIdx)
  34786. {
  34787. int ret = 0;
  34788. /* Get new current time as lock may have taken some time. */
  34789. word32 now = LowResTimer();
  34790. /* Check expirary of primary key for encrypt. */
  34791. if (keyCtx->expirary[0] >= now + ticketHint) {
  34792. *keyIdx = 0;
  34793. }
  34794. /* Check expirary of primary key for encrypt. */
  34795. else if (keyCtx->expirary[1] >= now + ticketHint) {
  34796. *keyIdx = 1;
  34797. }
  34798. /* No key available to use. */
  34799. else {
  34800. int genKey;
  34801. /* Generate which ever key is expired for decrypt - primary first. */
  34802. if (keyCtx->expirary[0] < now) {
  34803. genKey = 0;
  34804. }
  34805. else if (keyCtx->expirary[1] < now) {
  34806. genKey = 1;
  34807. }
  34808. /* Timeouts and expirary should not allow this to happen. */
  34809. else {
  34810. return BAD_STATE_E;
  34811. }
  34812. /* Generate the required key */
  34813. ret = wc_RNG_GenerateBlock(&keyCtx->rng, keyCtx->key[genKey],
  34814. WOLFSSL_TICKET_KEY_SZ);
  34815. if (ret == 0) {
  34816. keyCtx->expirary[genKey] = now + WOLFSSL_TICKET_KEY_LIFETIME;
  34817. *keyIdx = genKey;
  34818. }
  34819. }
  34820. return ret;
  34821. }
  34822. /* Default Session Ticket encryption/decryption callback.
  34823. *
  34824. * Use ChaCha20-Poly1305, AES-GCM or SM4-GCM to encrypt/decrypt the ticket.
  34825. * Two keys are used:
  34826. * - When the first expires for encryption, then use the other.
  34827. * - Don't encrypt with key if the ticket lifetime will go beyond expirary.
  34828. * - Generate a new primary key when primary key expired for decrypt and
  34829. * no secondary key is activate for encryption.
  34830. * - Generate a new secondary key when expired and needed.
  34831. * - Calculate expirary starting from first encrypted ticket.
  34832. * - Key name has last bit set to indicate index of key.
  34833. * Keys expire for decryption after ticket key lifetime from the first encrypted
  34834. * ticket.
  34835. * Keys can only be use for encryption while the ticket hint does not exceed
  34836. * the key lifetime.
  34837. * Lifetime of a key must be greater than the lifetime of a ticket. This means
  34838. * that if one ticket is only valid for decryption, then the other will be
  34839. * valid for encryption.
  34840. * AAD = key_name | iv | ticket len (16-bits network order)
  34841. *
  34842. * @param [in] ssl SSL connection.
  34843. * @param [in,out] key_name Name of key from client.
  34844. * Encrypt: name of key returned.
  34845. * Decrypt: name from ticket message to check.
  34846. * @param [in] iv IV to use in encryption/decryption.
  34847. * @param [in] mac MAC for authentication of encrypted data.
  34848. * @param [in] enc 1 when encrypting ticket, 0 when decrypting.
  34849. * @param [in,out] ticket Encrypted/decrypted session ticket bytes.
  34850. * @param [in] inLen Length of incoming ticket.
  34851. * @param [out] outLen Length of outgoing ticket.
  34852. * @param [in] userCtx Context for encryption/decryption of ticket.
  34853. * @return WOLFSSL_TICKET_RET_OK when successful.
  34854. * @return WOLFSSL_TICKET_RET_CREATE when successful and a new ticket is to
  34855. * be created for TLS 1.2 and below.
  34856. * @return WOLFSSL_TICKET_RET_REJECT when failed to produce valid encrypted or
  34857. * decrypted ticket.
  34858. * @return WOLFSSL_TICKET_RET_FATAL when key name does not match.
  34859. */
  34860. static int DefTicketEncCb(WOLFSSL* ssl, byte key_name[WOLFSSL_TICKET_NAME_SZ],
  34861. byte iv[WOLFSSL_TICKET_IV_SZ],
  34862. byte mac[WOLFSSL_TICKET_MAC_SZ],
  34863. int enc, byte* ticket, int inLen, int* outLen,
  34864. void* userCtx)
  34865. {
  34866. int ret;
  34867. TicketEncCbCtx* keyCtx = (TicketEncCbCtx*)userCtx;
  34868. WOLFSSL_CTX* ctx = keyCtx->ctx;
  34869. word16 sLen = XHTONS((word16)inLen);
  34870. byte aad[WOLFSSL_TICKET_NAME_SZ + WOLFSSL_TICKET_IV_SZ + sizeof(sLen)];
  34871. int aadSz = WOLFSSL_TICKET_NAME_SZ + WOLFSSL_TICKET_IV_SZ + sizeof(sLen);
  34872. byte* p = aad;
  34873. int keyIdx = 0;
  34874. WOLFSSL_ENTER("DefTicketEncCb");
  34875. if ((!enc) && (inLen != WOLFSSL_INTERNAL_TICKET_LEN)) {
  34876. return BUFFER_E;
  34877. }
  34878. /* Check we have setup the RNG, name and primary key. */
  34879. if (keyCtx->expirary[0] == 0) {
  34880. #ifndef SINGLE_THREADED
  34881. /* Lock around access to expirary and key - stop initial key being
  34882. * generated twice at the same time. */
  34883. if (wc_LockMutex(&keyCtx->mutex) != 0) {
  34884. WOLFSSL_MSG("Couldn't lock key context mutex");
  34885. return WOLFSSL_TICKET_RET_REJECT;
  34886. }
  34887. #endif
  34888. /* Sets expirary of primary key in setup. */
  34889. ret = TicketEncCbCtx_Setup(keyCtx, ssl->ctx->heap, ssl->ctx->devId);
  34890. #ifndef SINGLE_THREADED
  34891. wc_UnLockMutex(&keyCtx->mutex);
  34892. #endif
  34893. if (ret != 0)
  34894. return ret;
  34895. }
  34896. if (enc) {
  34897. /* Return the name of the key - missing key index. */
  34898. XMEMCPY(key_name, keyCtx->name, WOLFSSL_TICKET_NAME_SZ);
  34899. /* Generate a new IV into buffer to be returned.
  34900. * Don't use the RNG in keyCtx as it's for generating private data. */
  34901. ret = wc_RNG_GenerateBlock(ssl->rng, iv, WOLFSSL_TICKET_IV_SZ);
  34902. if (ret != 0) {
  34903. return WOLFSSL_TICKET_RET_REJECT;
  34904. }
  34905. }
  34906. else {
  34907. /* Mask of last bit that is the key index. */
  34908. byte lastByte = key_name[WOLFSSL_TICKET_NAME_SZ - 1] & 0xfe;
  34909. /* For decryption, see if we know this key - check all but last byte. */
  34910. if (XMEMCMP(key_name, keyCtx->name, WOLFSSL_TICKET_NAME_SZ - 1) != 0) {
  34911. return WOLFSSL_TICKET_RET_FATAL;
  34912. }
  34913. /* Ensure last byte without index bit matches too. */
  34914. if (lastByte != keyCtx->name[WOLFSSL_TICKET_NAME_SZ - 1]) {
  34915. return WOLFSSL_TICKET_RET_FATAL;
  34916. }
  34917. }
  34918. /* Build AAD from: key name, iv, and length of ticket. */
  34919. XMEMCPY(p, keyCtx->name, WOLFSSL_TICKET_NAME_SZ);
  34920. p += WOLFSSL_TICKET_NAME_SZ;
  34921. XMEMCPY(p, iv, WOLFSSL_TICKET_IV_SZ);
  34922. p += WOLFSSL_TICKET_IV_SZ;
  34923. XMEMCPY(p, &sLen, sizeof(sLen));
  34924. /* Encrypt ticket. */
  34925. if (enc) {
  34926. word32 now;
  34927. now = LowResTimer();
  34928. /* As long as encryption expirary isn't imminent - no lock. */
  34929. if (keyCtx->expirary[0] > now + ctx->ticketHint) {
  34930. keyIdx = 0;
  34931. }
  34932. else if (keyCtx->expirary[1] > now + ctx->ticketHint) {
  34933. keyIdx = 1;
  34934. }
  34935. else {
  34936. #ifndef SINGLE_THREADED
  34937. /* Lock around access to expirary and key - stop key being generated
  34938. * twice at the same time. */
  34939. if (wc_LockMutex(&keyCtx->mutex) != 0) {
  34940. WOLFSSL_MSG("Couldn't lock key context mutex");
  34941. return WOLFSSL_TICKET_RET_REJECT;
  34942. }
  34943. #endif
  34944. ret = TicketEncCbCtx_ChooseKey(keyCtx, ctx->ticketHint, &keyIdx);
  34945. #ifndef SINGLE_THREADED
  34946. wc_UnLockMutex(&keyCtx->mutex);
  34947. #endif
  34948. if (ret != 0) {
  34949. return WOLFSSL_TICKET_RET_REJECT;
  34950. }
  34951. }
  34952. /* Set the name of the key to the index chosen. */
  34953. key_name[WOLFSSL_TICKET_NAME_SZ - 1] |= keyIdx;
  34954. /* Update AAD too. */
  34955. aad[WOLFSSL_TICKET_NAME_SZ - 1] |= keyIdx;
  34956. /* Encrypt ticket data. */
  34957. ret = TicketEncDec(keyCtx->key[keyIdx], WOLFSSL_TICKET_KEY_SZ, iv, aad,
  34958. aadSz, ticket, inLen, ticket, outLen, mac, ssl->heap,
  34959. 1);
  34960. if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
  34961. }
  34962. /* Decrypt ticket. */
  34963. else {
  34964. /* Get index of key from name. */
  34965. keyIdx = key_name[WOLFSSL_TICKET_NAME_SZ - 1] & 0x1;
  34966. /* Update AAD with index. */
  34967. aad[WOLFSSL_TICKET_NAME_SZ - 1] |= keyIdx;
  34968. /* Check expirary */
  34969. if (keyCtx->expirary[keyIdx] <= LowResTimer()) {
  34970. return WOLFSSL_TICKET_RET_REJECT;
  34971. }
  34972. /* Decrypt ticket data. */
  34973. ret = TicketEncDec(keyCtx->key[keyIdx], WOLFSSL_TICKET_KEY_SZ, iv, aad,
  34974. aadSz, ticket, inLen, ticket, outLen, mac, ssl->heap,
  34975. 0);
  34976. if (ret != 0) {
  34977. return WOLFSSL_TICKET_RET_REJECT;
  34978. }
  34979. }
  34980. #ifndef WOLFSSL_TICKET_DECRYPT_NO_CREATE
  34981. if (!IsAtLeastTLSv1_3(ssl->version) && !enc)
  34982. return WOLFSSL_TICKET_RET_CREATE;
  34983. #endif
  34984. return WOLFSSL_TICKET_RET_OK;
  34985. }
  34986. #endif /* !WOLFSSL_NO_DEF_TICKET_ENC_CB */
  34987. #endif /* HAVE_SESSION_TICKET */
  34988. #ifndef WOLFSSL_NO_TLS12
  34989. #if defined(HAVE_SECURE_RENEGOTIATION) && \
  34990. !defined(NO_WOLFSSL_SERVER)
  34991. /* handle generation of server's hello_request (0) */
  34992. int SendHelloRequest(WOLFSSL* ssl)
  34993. {
  34994. byte* output;
  34995. int sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  34996. int ret;
  34997. WOLFSSL_START(WC_FUNC_HELLO_REQUEST_SEND);
  34998. WOLFSSL_ENTER("SendHelloRequest");
  34999. if (IsEncryptionOn(ssl, 1))
  35000. sendSz += MAX_MSG_EXTRA;
  35001. if (ssl->options.dtls)
  35002. sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  35003. /* Set this in case CheckAvailableSize returns a WANT_WRITE so that state
  35004. * is not advanced yet */
  35005. ssl->options.buildingMsg = 1;
  35006. /* check for available size */
  35007. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  35008. return ret;
  35009. /* get output buffer */
  35010. output = GetOutputBuffer(ssl);
  35011. AddHeaders(output, 0, hello_request, ssl);
  35012. if (IsEncryptionOn(ssl, 1)) {
  35013. byte* input;
  35014. int inputSz = HANDSHAKE_HEADER_SZ; /* build msg adds rec hdr */
  35015. int recordHeaderSz = RECORD_HEADER_SZ;
  35016. if (ssl->options.dtls) {
  35017. recordHeaderSz += DTLS_RECORD_EXTRA;
  35018. inputSz += DTLS_HANDSHAKE_EXTRA;
  35019. }
  35020. input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  35021. if (input == NULL)
  35022. return MEMORY_E;
  35023. XMEMCPY(input, output + recordHeaderSz, inputSz);
  35024. #ifdef WOLFSSL_DTLS
  35025. if (IsDtlsNotSctpMode(ssl) &&
  35026. (ret = DtlsMsgPoolSave(ssl, input, inputSz, hello_request)) != 0) {
  35027. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  35028. return ret;
  35029. }
  35030. #endif
  35031. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  35032. handshake, 0, 0, 0, CUR_ORDER);
  35033. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  35034. if (sendSz < 0)
  35035. return sendSz;
  35036. }
  35037. ssl->buffers.outputBuffer.length += sendSz;
  35038. ssl->options.buildingMsg = 0;
  35039. ret = SendBuffered(ssl);
  35040. WOLFSSL_LEAVE("SendHelloRequest", ret);
  35041. WOLFSSL_END(WC_FUNC_HELLO_REQUEST_SEND);
  35042. return ret;
  35043. }
  35044. #endif /* HAVE_SECURE_RENEGOTIATION && !NO_WOLFSSL_SERVER */
  35045. #ifdef WOLFSSL_DTLS
  35046. /* handle generation of DTLS hello_verify_request (3) */
  35047. int SendHelloVerifyRequest(WOLFSSL* ssl,
  35048. const byte* cookie, byte cookieSz)
  35049. {
  35050. byte* output;
  35051. int length = VERSION_SZ + ENUM_LEN + cookieSz;
  35052. int idx = DTLS_RECORD_HEADER_SZ + DTLS_HANDSHAKE_HEADER_SZ;
  35053. int sendSz = length + idx;
  35054. int ret;
  35055. /* are we in scr */
  35056. if (IsEncryptionOn(ssl, 1)) {
  35057. sendSz += MAX_MSG_EXTRA;
  35058. }
  35059. /* reset hashes */
  35060. ret = InitHandshakeHashes(ssl);
  35061. if (ret != 0)
  35062. return ret;
  35063. /* check for available size */
  35064. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  35065. return ret;
  35066. /* get output buffer */
  35067. output = GetOutputBuffer(ssl);
  35068. /* Hello Verify Request should use the same sequence number
  35069. * as the Client Hello unless we are in renegotiation then
  35070. * don't change numbers */
  35071. #ifdef HAVE_SECURE_RENEGOTIATION
  35072. if (!IsSCR(ssl))
  35073. #endif
  35074. {
  35075. ssl->keys.dtls_sequence_number_hi = ssl->keys.curSeq_hi;
  35076. ssl->keys.dtls_sequence_number_lo = ssl->keys.curSeq_lo;
  35077. }
  35078. AddHeaders(output, (word32)length, hello_verify_request, ssl);
  35079. output[idx++] = DTLS_MAJOR;
  35080. output[idx++] = DTLS_MINOR;
  35081. output[idx++] = cookieSz;
  35082. if (cookie == NULL || cookieSz == 0)
  35083. return COOKIE_ERROR;
  35084. XMEMCPY(output + idx, cookie, cookieSz);
  35085. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  35086. if (ssl->hsInfoOn)
  35087. AddPacketName(ssl, "HelloVerifyRequest");
  35088. if (ssl->toInfoOn) {
  35089. ret = AddPacketInfo(ssl, "HelloVerifyRequest", handshake, output,
  35090. sendSz, WRITE_PROTO, 0, ssl->heap);
  35091. if (ret != 0)
  35092. return ret;
  35093. }
  35094. #endif
  35095. /* are we in scr */
  35096. if (IsEncryptionOn(ssl, 1)) {
  35097. byte* input;
  35098. int inputSz = DTLS_HANDSHAKE_HEADER_SZ + length; /* build msg adds rec hdr */
  35099. int recordHeaderSz = DTLS_RECORD_HEADER_SZ;
  35100. input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  35101. if (input == NULL)
  35102. return MEMORY_E;
  35103. XMEMCPY(input, output + recordHeaderSz, inputSz);
  35104. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  35105. handshake, 0, 0, 0, CUR_ORDER);
  35106. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  35107. if (sendSz < 0)
  35108. return sendSz;
  35109. }
  35110. ssl->buffers.outputBuffer.length += sendSz;
  35111. return SendBuffered(ssl);
  35112. }
  35113. #endif /* WOLFSSL_DTLS */
  35114. typedef struct DckeArgs {
  35115. byte* output; /* not allocated */
  35116. word32 length;
  35117. word32 idx;
  35118. word32 begin;
  35119. word32 sigSz;
  35120. #ifndef NO_RSA
  35121. int lastErr;
  35122. #endif
  35123. } DckeArgs;
  35124. static void FreeDckeArgs(WOLFSSL* ssl, void* pArgs)
  35125. {
  35126. DckeArgs* args = (DckeArgs*)pArgs;
  35127. (void)ssl;
  35128. (void)args;
  35129. }
  35130. /* handle processing client_key_exchange (16) */
  35131. static int DoClientKeyExchange(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  35132. word32 size)
  35133. {
  35134. int ret;
  35135. #ifdef WOLFSSL_ASYNC_CRYPT
  35136. DckeArgs* args = NULL;
  35137. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  35138. #else
  35139. DckeArgs args[1];
  35140. #endif
  35141. (void)size;
  35142. (void)input;
  35143. WOLFSSL_START(WC_FUNC_CLIENT_KEY_EXCHANGE_DO);
  35144. WOLFSSL_ENTER("DoClientKeyExchange");
  35145. #ifdef WOLFSSL_BLIND_PRIVATE_KEY
  35146. wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask);
  35147. #endif
  35148. #ifdef WOLFSSL_ASYNC_CRYPT
  35149. if (ssl->async == NULL) {
  35150. ssl->async = (struct WOLFSSL_ASYNC*)
  35151. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  35152. DYNAMIC_TYPE_ASYNC);
  35153. if (ssl->async == NULL)
  35154. ERROR_OUT(MEMORY_E, exit_dcke);
  35155. }
  35156. args = (DckeArgs*)ssl->async->args;
  35157. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  35158. if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
  35159. /* Check for error */
  35160. if (ret < 0)
  35161. goto exit_dcke;
  35162. }
  35163. else
  35164. #endif /* WOLFSSL_ASYNC_CRYPT */
  35165. {
  35166. /* Reset state */
  35167. ret = 0;
  35168. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  35169. XMEMSET(args, 0, sizeof(DckeArgs));
  35170. args->idx = *inOutIdx;
  35171. args->begin = *inOutIdx;
  35172. #ifdef WOLFSSL_ASYNC_CRYPT
  35173. ssl->async->freeArgs = FreeDckeArgs;
  35174. #endif
  35175. }
  35176. /* Do Client Key Exchange State Machine */
  35177. switch(ssl->options.asyncState)
  35178. {
  35179. case TLS_ASYNC_BEGIN:
  35180. {
  35181. /* Sanity checks */
  35182. /* server side checked in SanityCheckMsgReceived */
  35183. if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  35184. WOLFSSL_MSG("Client sending keyexchange at wrong time");
  35185. SendAlert(ssl, alert_fatal, unexpected_message);
  35186. ERROR_OUT(OUT_OF_ORDER_E, exit_dcke);
  35187. }
  35188. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  35189. if (ssl->options.verifyPeer &&
  35190. (ssl->options.mutualAuth || ssl->options.failNoCert)) {
  35191. if (!ssl->options.havePeerCert) {
  35192. WOLFSSL_MSG("client didn't present peer cert");
  35193. ERROR_OUT(NO_PEER_CERT, exit_dcke);
  35194. }
  35195. }
  35196. if (ssl->options.verifyPeer && ssl->options.failNoCertxPSK) {
  35197. if (!ssl->options.havePeerCert &&
  35198. !ssl->options.usingPSK_cipher) {
  35199. WOLFSSL_MSG("client didn't present peer cert");
  35200. ERROR_OUT(NO_PEER_CERT, exit_dcke);
  35201. }
  35202. }
  35203. #endif /* !NO_CERTS && !WOLFSSL_NO_CLIENT_AUTH */
  35204. #if defined(WOLFSSL_CALLBACKS)
  35205. if (ssl->hsInfoOn) {
  35206. AddPacketName(ssl, "ClientKeyExchange");
  35207. }
  35208. if (ssl->toInfoOn) {
  35209. AddLateName("ClientKeyExchange", &ssl->timeoutInfo);
  35210. }
  35211. #endif
  35212. if (ssl->arrays->preMasterSecret == NULL) {
  35213. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  35214. ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN,
  35215. ssl->heap, DYNAMIC_TYPE_SECRET);
  35216. if (ssl->arrays->preMasterSecret == NULL) {
  35217. ERROR_OUT(MEMORY_E, exit_dcke);
  35218. }
  35219. XMEMSET(ssl->arrays->preMasterSecret, 0, ENCRYPT_LEN);
  35220. }
  35221. switch (ssl->specs.kea) {
  35222. #ifndef NO_RSA
  35223. case rsa_kea:
  35224. {
  35225. break;
  35226. } /* rsa_kea */
  35227. #endif /* !NO_RSA */
  35228. #ifndef NO_PSK
  35229. case psk_kea:
  35230. {
  35231. /* sanity check that PSK server callback has been set */
  35232. if (ssl->options.server_psk_cb == NULL) {
  35233. WOLFSSL_MSG("No server PSK callback set");
  35234. ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
  35235. }
  35236. break;
  35237. }
  35238. #endif /* !NO_PSK */
  35239. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  35240. defined(HAVE_CURVE448)
  35241. case ecc_diffie_hellman_kea:
  35242. {
  35243. break;
  35244. }
  35245. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  35246. #ifndef NO_DH
  35247. case diffie_hellman_kea:
  35248. {
  35249. break;
  35250. }
  35251. #endif /* !NO_DH */
  35252. #if !defined(NO_DH) && !defined(NO_PSK)
  35253. case dhe_psk_kea:
  35254. {
  35255. /* sanity check that PSK server callback has been set */
  35256. if (ssl->options.server_psk_cb == NULL) {
  35257. WOLFSSL_MSG("No server PSK callback set");
  35258. ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
  35259. }
  35260. break;
  35261. }
  35262. #endif /* !NO_DH && !NO_PSK */
  35263. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  35264. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  35265. case ecdhe_psk_kea:
  35266. {
  35267. /* sanity check that PSK server callback has been set */
  35268. if (ssl->options.server_psk_cb == NULL) {
  35269. WOLFSSL_MSG("No server PSK callback set");
  35270. ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
  35271. }
  35272. break;
  35273. }
  35274. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  35275. default:
  35276. WOLFSSL_MSG("Bad kea type");
  35277. ret = BAD_KEA_TYPE_E;
  35278. } /* switch (ssl->specs.kea) */
  35279. /* Check for error */
  35280. if (ret != 0) {
  35281. goto exit_dcke;
  35282. }
  35283. /* Advance state and proceed */
  35284. ssl->options.asyncState = TLS_ASYNC_BUILD;
  35285. } /* TLS_ASYNC_BEGIN */
  35286. FALL_THROUGH;
  35287. case TLS_ASYNC_BUILD:
  35288. {
  35289. switch (ssl->specs.kea) {
  35290. #ifndef NO_RSA
  35291. case rsa_kea:
  35292. {
  35293. word32 keySz;
  35294. ssl->buffers.keyType = rsa_sa_algo;
  35295. ret = DecodePrivateKey(ssl, &keySz);
  35296. if (ret != 0) {
  35297. goto exit_dcke;
  35298. }
  35299. args->length = (word32)keySz;
  35300. ssl->arrays->preMasterSz = SECRET_LEN;
  35301. if (ssl->options.tls) {
  35302. word16 check;
  35303. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  35304. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35305. }
  35306. ato16(input + args->idx, &check);
  35307. args->idx += OPAQUE16_LEN;
  35308. if ((word32)check != args->length) {
  35309. WOLFSSL_MSG("RSA explicit size doesn't match");
  35310. #ifdef WOLFSSL_EXTRA_ALERTS
  35311. SendAlert(ssl, alert_fatal, bad_record_mac);
  35312. #endif
  35313. ERROR_OUT(RSA_PRIVATE_ERROR, exit_dcke);
  35314. }
  35315. }
  35316. if ((args->idx - args->begin) + args->length > size) {
  35317. WOLFSSL_MSG("RSA message too big");
  35318. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35319. }
  35320. /* pre-load PreMasterSecret with RNG data */
  35321. ret = wc_RNG_GenerateBlock(ssl->rng,
  35322. &ssl->arrays->preMasterSecret[VERSION_SZ],
  35323. SECRET_LEN - VERSION_SZ);
  35324. if (ret != 0) {
  35325. goto exit_dcke;
  35326. }
  35327. args->output = NULL;
  35328. break;
  35329. } /* rsa_kea */
  35330. #endif /* !NO_RSA */
  35331. #ifndef NO_PSK
  35332. case psk_kea:
  35333. {
  35334. byte* pms = ssl->arrays->preMasterSecret;
  35335. word16 ci_sz;
  35336. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  35337. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35338. }
  35339. ato16(input + args->idx, &ci_sz);
  35340. args->idx += OPAQUE16_LEN;
  35341. if (ci_sz > MAX_PSK_ID_LEN) {
  35342. ERROR_OUT(CLIENT_ID_ERROR, exit_dcke);
  35343. }
  35344. if ((args->idx - args->begin) + ci_sz > size) {
  35345. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35346. }
  35347. XMEMCPY(ssl->arrays->client_identity,
  35348. input + args->idx, ci_sz);
  35349. args->idx += ci_sz;
  35350. ssl->arrays->client_identity[ci_sz] = '\0'; /* null term */
  35351. ssl->arrays->psk_keySz = ssl->options.server_psk_cb(ssl,
  35352. ssl->arrays->client_identity, ssl->arrays->psk_key,
  35353. MAX_PSK_KEY_LEN);
  35354. if (ssl->arrays->psk_keySz == 0 ||
  35355. (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN &&
  35356. (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) {
  35357. #if defined(WOLFSSL_EXTRA_ALERTS) || \
  35358. defined(WOLFSSL_PSK_IDENTITY_ALERT)
  35359. SendAlert(ssl, alert_fatal,
  35360. unknown_psk_identity);
  35361. #endif
  35362. ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
  35363. }
  35364. /* SERVER: Pre-shared Key for peer authentication. */
  35365. ssl->options.peerAuthGood = 1;
  35366. /* make psk pre master secret */
  35367. if ((int)ssl->arrays->psk_keySz > 0) {
  35368. /* length of key + length 0s + length of key + key */
  35369. c16toa((word16) ssl->arrays->psk_keySz, pms);
  35370. pms += OPAQUE16_LEN;
  35371. XMEMSET(pms, 0, ssl->arrays->psk_keySz);
  35372. pms += ssl->arrays->psk_keySz;
  35373. c16toa((word16) ssl->arrays->psk_keySz, pms);
  35374. pms += OPAQUE16_LEN;
  35375. XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  35376. ssl->arrays->preMasterSz = (ssl->arrays->psk_keySz * 2) +
  35377. (OPAQUE16_LEN * 2);
  35378. }
  35379. ssl->arrays->psk_keySz = 0; /* no further need */
  35380. break;
  35381. }
  35382. #endif /* !NO_PSK */
  35383. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  35384. defined(HAVE_CURVE448)
  35385. case ecc_diffie_hellman_kea:
  35386. {
  35387. #ifdef HAVE_ECC
  35388. ecc_key* private_key = ssl->eccTempKey;
  35389. /* handle static private key */
  35390. if (ssl->specs.static_ecdh &&
  35391. ssl->ecdhCurveOID != ECC_X25519_OID &&
  35392. ssl->ecdhCurveOID != ECC_X448_OID) {
  35393. word32 keySz;
  35394. ssl->buffers.keyType = ecc_dsa_sa_algo;
  35395. ret = DecodePrivateKey(ssl, &keySz);
  35396. if (ret != 0) {
  35397. goto exit_dcke;
  35398. }
  35399. private_key = (ecc_key*)ssl->hsKey;
  35400. }
  35401. #endif
  35402. /* import peer ECC key */
  35403. if ((args->idx - args->begin) + OPAQUE8_LEN > size) {
  35404. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35405. }
  35406. args->length = input[args->idx++];
  35407. if ((args->idx - args->begin) + args->length > size) {
  35408. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35409. }
  35410. #ifdef HAVE_CURVE25519
  35411. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  35412. #ifdef HAVE_PK_CALLBACKS
  35413. /* if callback then use it for shared secret */
  35414. if (ssl->ctx->X25519SharedSecretCb != NULL) {
  35415. break;
  35416. }
  35417. #endif
  35418. if (ssl->peerX25519Key == NULL) {
  35419. /* alloc/init on demand */
  35420. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
  35421. (void**)&ssl->peerX25519Key);
  35422. if (ret != 0) {
  35423. goto exit_dcke;
  35424. }
  35425. } else if (ssl->peerX25519KeyPresent) {
  35426. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE25519,
  35427. ssl->peerX25519Key);
  35428. ssl->peerX25519KeyPresent = 0;
  35429. if (ret != 0) {
  35430. goto exit_dcke;
  35431. }
  35432. }
  35433. if ((ret = wc_curve25519_check_public(
  35434. input + args->idx, args->length,
  35435. EC25519_LITTLE_ENDIAN)) != 0) {
  35436. #ifdef WOLFSSL_EXTRA_ALERTS
  35437. if (ret == WC_NO_ERR_TRACE(BUFFER_E))
  35438. SendAlert(ssl, alert_fatal, decode_error);
  35439. else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E))
  35440. SendAlert(ssl, alert_fatal, bad_record_mac);
  35441. else {
  35442. SendAlert(ssl, alert_fatal,
  35443. illegal_parameter);
  35444. }
  35445. #endif
  35446. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  35447. }
  35448. if (wc_curve25519_import_public_ex(
  35449. input + args->idx, args->length,
  35450. ssl->peerX25519Key,
  35451. EC25519_LITTLE_ENDIAN)) {
  35452. #ifdef WOLFSSL_EXTRA_ALERTS
  35453. SendAlert(ssl, alert_fatal, illegal_parameter);
  35454. #endif
  35455. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  35456. }
  35457. ssl->arrays->preMasterSz = CURVE25519_KEYSIZE;
  35458. ssl->peerX25519KeyPresent = 1;
  35459. break;
  35460. }
  35461. #endif
  35462. #ifdef HAVE_CURVE448
  35463. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  35464. #ifdef HAVE_PK_CALLBACKS
  35465. /* if callback then use it for shared secret */
  35466. if (ssl->ctx->X448SharedSecretCb != NULL) {
  35467. break;
  35468. }
  35469. #endif
  35470. if (ssl->peerX448Key == NULL) {
  35471. /* alloc/init on demand */
  35472. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
  35473. (void**)&ssl->peerX448Key);
  35474. if (ret != 0) {
  35475. goto exit_dcke;
  35476. }
  35477. } else if (ssl->peerX448KeyPresent) {
  35478. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE448,
  35479. ssl->peerX448Key);
  35480. ssl->peerX448KeyPresent = 0;
  35481. if (ret != 0) {
  35482. goto exit_dcke;
  35483. }
  35484. }
  35485. if ((ret = wc_curve448_check_public(
  35486. input + args->idx, args->length,
  35487. EC448_LITTLE_ENDIAN)) != 0) {
  35488. #ifdef WOLFSSL_EXTRA_ALERTS
  35489. if (ret == WC_NO_ERR_TRACE(BUFFER_E))
  35490. SendAlert(ssl, alert_fatal, decode_error);
  35491. else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E))
  35492. SendAlert(ssl, alert_fatal, bad_record_mac);
  35493. else {
  35494. SendAlert(ssl, alert_fatal,
  35495. illegal_parameter);
  35496. }
  35497. #endif
  35498. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  35499. }
  35500. if (wc_curve448_import_public_ex(
  35501. input + args->idx, args->length,
  35502. ssl->peerX448Key,
  35503. EC448_LITTLE_ENDIAN)) {
  35504. #ifdef WOLFSSL_EXTRA_ALERTS
  35505. SendAlert(ssl, alert_fatal, illegal_parameter);
  35506. #endif
  35507. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  35508. }
  35509. ssl->arrays->preMasterSz = CURVE448_KEY_SIZE;
  35510. ssl->peerX448KeyPresent = 1;
  35511. break;
  35512. }
  35513. #endif
  35514. #ifdef HAVE_ECC
  35515. #ifdef HAVE_PK_CALLBACKS
  35516. /* if callback then use it for shared secret */
  35517. if (ssl->ctx->EccSharedSecretCb != NULL) {
  35518. break;
  35519. }
  35520. #endif
  35521. if (!ssl->specs.static_ecdh &&
  35522. ssl->eccTempKeyPresent == 0) {
  35523. WOLFSSL_MSG("Ecc ephemeral key not made correctly");
  35524. ERROR_OUT(ECC_MAKEKEY_ERROR, exit_dcke);
  35525. }
  35526. if (ssl->peerEccKey == NULL) {
  35527. /* alloc/init on demand */
  35528. ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
  35529. (void**)&ssl->peerEccKey);
  35530. if (ret != 0) {
  35531. goto exit_dcke;
  35532. }
  35533. } else if (ssl->peerEccKeyPresent) {
  35534. ret = ReuseKey(ssl, DYNAMIC_TYPE_ECC,
  35535. ssl->peerEccKey);
  35536. ssl->peerEccKeyPresent = 0;
  35537. if (ret != 0) {
  35538. goto exit_dcke;
  35539. }
  35540. }
  35541. if (wc_ecc_import_x963_ex(input + args->idx,
  35542. args->length, ssl->peerEccKey,
  35543. private_key->dp->id)) {
  35544. #ifdef WOLFSSL_EXTRA_ALERTS
  35545. SendAlert(ssl, alert_fatal, illegal_parameter);
  35546. #endif
  35547. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  35548. }
  35549. ssl->arrays->preMasterSz = (word32)private_key->dp->size;
  35550. ssl->peerEccKeyPresent = 1;
  35551. #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
  35552. /* client_hello may have sent FFEDH2048, which sets namedGroup,
  35553. but that is not being used, so clear it */
  35554. /* resolves issue with server side wolfSSL_get_curve_name */
  35555. ssl->namedGroup = 0;
  35556. #endif
  35557. #endif /* HAVE_ECC */
  35558. break;
  35559. }
  35560. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  35561. #ifndef NO_DH
  35562. case diffie_hellman_kea:
  35563. {
  35564. word16 clientPubSz;
  35565. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  35566. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35567. }
  35568. ato16(input + args->idx, &clientPubSz);
  35569. args->idx += OPAQUE16_LEN;
  35570. if ((args->idx - args->begin) + clientPubSz > size) {
  35571. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35572. }
  35573. args->sigSz = clientPubSz;
  35574. ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
  35575. (void**)&ssl->buffers.serverDH_Key);
  35576. if (ret != 0) {
  35577. goto exit_dcke;
  35578. }
  35579. ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
  35580. ssl->buffers.serverDH_P.buffer,
  35581. ssl->buffers.serverDH_P.length,
  35582. ssl->buffers.serverDH_G.buffer,
  35583. ssl->buffers.serverDH_G.length);
  35584. /* set the max agree result size */
  35585. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  35586. break;
  35587. }
  35588. #endif /* !NO_DH */
  35589. #if !defined(NO_DH) && !defined(NO_PSK)
  35590. case dhe_psk_kea:
  35591. {
  35592. word16 clientSz;
  35593. /* Read in the PSK hint */
  35594. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  35595. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35596. }
  35597. ato16(input + args->idx, &clientSz);
  35598. args->idx += OPAQUE16_LEN;
  35599. if (clientSz > MAX_PSK_ID_LEN) {
  35600. ERROR_OUT(CLIENT_ID_ERROR, exit_dcke);
  35601. }
  35602. if ((args->idx - args->begin) + clientSz > size) {
  35603. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35604. }
  35605. XMEMCPY(ssl->arrays->client_identity, input + args->idx,
  35606. clientSz);
  35607. args->idx += clientSz;
  35608. ssl->arrays->client_identity[clientSz] = '\0'; /* null term */
  35609. /* Read in the DHE business */
  35610. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  35611. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35612. }
  35613. ato16(input + args->idx, &clientSz);
  35614. args->idx += OPAQUE16_LEN;
  35615. if ((args->idx - args->begin) + clientSz > size) {
  35616. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35617. }
  35618. args->sigSz = clientSz;
  35619. ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
  35620. (void**)&ssl->buffers.serverDH_Key);
  35621. if (ret != 0) {
  35622. goto exit_dcke;
  35623. }
  35624. ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
  35625. ssl->buffers.serverDH_P.buffer,
  35626. ssl->buffers.serverDH_P.length,
  35627. ssl->buffers.serverDH_G.buffer,
  35628. ssl->buffers.serverDH_G.length);
  35629. break;
  35630. }
  35631. #endif /* !NO_DH && !NO_PSK */
  35632. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  35633. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  35634. case ecdhe_psk_kea:
  35635. {
  35636. word16 clientSz;
  35637. /* Read in the PSK hint */
  35638. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  35639. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35640. }
  35641. ato16(input + args->idx, &clientSz);
  35642. args->idx += OPAQUE16_LEN;
  35643. if (clientSz > MAX_PSK_ID_LEN) {
  35644. ERROR_OUT(CLIENT_ID_ERROR, exit_dcke);
  35645. }
  35646. if ((args->idx - args->begin) + clientSz > size) {
  35647. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35648. }
  35649. XMEMCPY(ssl->arrays->client_identity,
  35650. input + args->idx, clientSz);
  35651. args->idx += clientSz;
  35652. ssl->arrays->client_identity[clientSz] = '\0'; /* null term */
  35653. /* import peer ECC key */
  35654. if ((args->idx - args->begin) + OPAQUE8_LEN > size) {
  35655. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35656. }
  35657. args->length = input[args->idx++];
  35658. if ((args->idx - args->begin) + args->length > size) {
  35659. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  35660. }
  35661. args->sigSz = ENCRYPT_LEN - OPAQUE16_LEN;
  35662. #ifdef HAVE_CURVE25519
  35663. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  35664. #ifdef HAVE_PK_CALLBACKS
  35665. /* if callback then use it for shared secret */
  35666. if (ssl->ctx->X25519SharedSecretCb != NULL) {
  35667. break;
  35668. }
  35669. #endif
  35670. if (ssl->eccTempKeyPresent == 0) {
  35671. WOLFSSL_MSG(
  35672. "X25519 ephemeral key not made correctly");
  35673. ERROR_OUT(ECC_MAKEKEY_ERROR, exit_dcke);
  35674. }
  35675. if (ssl->peerX25519Key == NULL) {
  35676. /* alloc/init on demand */
  35677. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
  35678. (void**)&ssl->peerX25519Key);
  35679. if (ret != 0) {
  35680. goto exit_dcke;
  35681. }
  35682. } else if (ssl->peerX25519KeyPresent) {
  35683. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE25519,
  35684. ssl->peerX25519Key);
  35685. ssl->peerX25519KeyPresent = 0;
  35686. if (ret != 0) {
  35687. goto exit_dcke;
  35688. }
  35689. }
  35690. if ((ret = wc_curve25519_check_public(
  35691. input + args->idx, args->length,
  35692. EC25519_LITTLE_ENDIAN)) != 0) {
  35693. #ifdef WOLFSSL_EXTRA_ALERTS
  35694. if (ret == WC_NO_ERR_TRACE(BUFFER_E))
  35695. SendAlert(ssl, alert_fatal, decode_error);
  35696. else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E))
  35697. SendAlert(ssl, alert_fatal, bad_record_mac);
  35698. else {
  35699. SendAlert(ssl, alert_fatal,
  35700. illegal_parameter);
  35701. }
  35702. #endif
  35703. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  35704. }
  35705. if (wc_curve25519_import_public_ex(
  35706. input + args->idx, args->length,
  35707. ssl->peerX25519Key,
  35708. EC25519_LITTLE_ENDIAN)) {
  35709. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  35710. }
  35711. ssl->peerX25519KeyPresent = 1;
  35712. break;
  35713. }
  35714. #endif
  35715. #ifdef HAVE_CURVE448
  35716. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  35717. #ifdef HAVE_PK_CALLBACKS
  35718. /* if callback then use it for shared secret */
  35719. if (ssl->ctx->X448SharedSecretCb != NULL) {
  35720. break;
  35721. }
  35722. #endif
  35723. if (ssl->eccTempKeyPresent == 0) {
  35724. WOLFSSL_MSG(
  35725. "X448 ephemeral key not made correctly");
  35726. ERROR_OUT(ECC_MAKEKEY_ERROR, exit_dcke);
  35727. }
  35728. if (ssl->peerX448Key == NULL) {
  35729. /* alloc/init on demand */
  35730. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
  35731. (void**)&ssl->peerX448Key);
  35732. if (ret != 0) {
  35733. goto exit_dcke;
  35734. }
  35735. } else if (ssl->peerX448KeyPresent) {
  35736. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE448,
  35737. ssl->peerX448Key);
  35738. ssl->peerX448KeyPresent = 0;
  35739. if (ret != 0) {
  35740. goto exit_dcke;
  35741. }
  35742. }
  35743. if ((ret = wc_curve448_check_public(
  35744. input + args->idx, args->length,
  35745. EC448_LITTLE_ENDIAN)) != 0) {
  35746. #ifdef WOLFSSL_EXTRA_ALERTS
  35747. if (ret == WC_NO_ERR_TRACE(BUFFER_E))
  35748. SendAlert(ssl, alert_fatal, decode_error);
  35749. else if (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E))
  35750. SendAlert(ssl, alert_fatal, bad_record_mac);
  35751. else {
  35752. SendAlert(ssl, alert_fatal,
  35753. illegal_parameter);
  35754. }
  35755. #endif
  35756. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  35757. }
  35758. if (wc_curve448_import_public_ex(
  35759. input + args->idx, args->length,
  35760. ssl->peerX448Key,
  35761. EC448_LITTLE_ENDIAN)) {
  35762. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  35763. }
  35764. ssl->peerX448KeyPresent = 1;
  35765. break;
  35766. }
  35767. #endif
  35768. #ifdef HAVE_PK_CALLBACKS
  35769. /* if callback then use it for shared secret */
  35770. if (ssl->ctx->EccSharedSecretCb != NULL) {
  35771. break;
  35772. }
  35773. #endif
  35774. if (ssl->eccTempKeyPresent == 0) {
  35775. WOLFSSL_MSG("Ecc ephemeral key not made correctly");
  35776. ERROR_OUT(ECC_MAKEKEY_ERROR, exit_dcke);
  35777. }
  35778. if (ssl->peerEccKey == NULL) {
  35779. /* alloc/init on demand */
  35780. ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
  35781. (void**)&ssl->peerEccKey);
  35782. if (ret != 0) {
  35783. goto exit_dcke;
  35784. }
  35785. }
  35786. else if (ssl->peerEccKeyPresent) {
  35787. ret = ReuseKey(ssl, DYNAMIC_TYPE_ECC,
  35788. ssl->peerEccKey);
  35789. ssl->peerEccKeyPresent = 0;
  35790. if (ret != 0) {
  35791. goto exit_dcke;
  35792. }
  35793. }
  35794. if (wc_ecc_import_x963_ex(input + args->idx,
  35795. args->length, ssl->peerEccKey,
  35796. ssl->eccTempKey->dp->id)) {
  35797. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  35798. }
  35799. ssl->peerEccKeyPresent = 1;
  35800. break;
  35801. }
  35802. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  35803. default:
  35804. ret = BAD_KEA_TYPE_E;
  35805. } /* switch (ssl->specs.kea) */
  35806. /* Check for error */
  35807. if (ret != 0) {
  35808. goto exit_dcke;
  35809. }
  35810. /* Advance state and proceed */
  35811. ssl->options.asyncState = TLS_ASYNC_DO;
  35812. } /* TLS_ASYNC_BUILD */
  35813. FALL_THROUGH;
  35814. case TLS_ASYNC_DO:
  35815. {
  35816. switch (ssl->specs.kea) {
  35817. #ifndef NO_RSA
  35818. case rsa_kea:
  35819. {
  35820. RsaKey* key = (RsaKey*)ssl->hsKey;
  35821. int lenErrMask;
  35822. ret = RsaDec(ssl,
  35823. input + args->idx,
  35824. args->length,
  35825. &args->output,
  35826. &args->sigSz,
  35827. key,
  35828. #ifdef HAVE_PK_CALLBACKS
  35829. ssl->buffers.key
  35830. #else
  35831. NULL
  35832. #endif
  35833. );
  35834. /* Errors that can occur here that should be
  35835. * indistinguishable:
  35836. * RSA_BUFFER_E, RSA_PAD_E and RSA_PRIVATE_ERROR
  35837. */
  35838. #ifdef WOLFSSL_ASYNC_CRYPT
  35839. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
  35840. goto exit_dcke;
  35841. #endif
  35842. if (ret == WC_NO_ERR_TRACE(BAD_FUNC_ARG))
  35843. goto exit_dcke;
  35844. lenErrMask = 0 - (SECRET_LEN != args->sigSz);
  35845. args->lastErr = (ret & (~lenErrMask)) |
  35846. (WC_NO_ERR_TRACE(RSA_PAD_E) & lenErrMask);
  35847. ret = 0;
  35848. break;
  35849. } /* rsa_kea */
  35850. #endif /* !NO_RSA */
  35851. #ifndef NO_PSK
  35852. case psk_kea:
  35853. {
  35854. break;
  35855. }
  35856. #endif /* !NO_PSK */
  35857. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  35858. defined(HAVE_CURVE448)
  35859. case ecc_diffie_hellman_kea:
  35860. {
  35861. void* private_key = ssl->eccTempKey;
  35862. (void)private_key;
  35863. #ifdef HAVE_CURVE25519
  35864. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  35865. ret = X25519SharedSecret(ssl,
  35866. (curve25519_key*)private_key,
  35867. ssl->peerX25519Key,
  35868. input + args->idx, &args->length,
  35869. ssl->arrays->preMasterSecret,
  35870. &ssl->arrays->preMasterSz,
  35871. WOLFSSL_SERVER_END
  35872. );
  35873. break;
  35874. }
  35875. #endif
  35876. #ifdef HAVE_CURVE448
  35877. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  35878. ret = X448SharedSecret(ssl,
  35879. (curve448_key*)private_key,
  35880. ssl->peerX448Key,
  35881. input + args->idx, &args->length,
  35882. ssl->arrays->preMasterSecret,
  35883. &ssl->arrays->preMasterSz,
  35884. WOLFSSL_SERVER_END
  35885. );
  35886. break;
  35887. }
  35888. #endif
  35889. #ifdef HAVE_ECC
  35890. if (ssl->specs.static_ecdh) {
  35891. private_key = ssl->hsKey;
  35892. }
  35893. /* Generate shared secret */
  35894. ret = EccSharedSecret(ssl,
  35895. (ecc_key*)private_key, ssl->peerEccKey,
  35896. input + args->idx, &args->length,
  35897. ssl->arrays->preMasterSecret,
  35898. &ssl->arrays->preMasterSz,
  35899. WOLFSSL_SERVER_END
  35900. );
  35901. #ifdef WOLFSSL_ASYNC_CRYPT
  35902. if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
  35903. #endif
  35904. {
  35905. FreeKey(ssl, DYNAMIC_TYPE_ECC,
  35906. (void**)&ssl->peerEccKey);
  35907. ssl->peerEccKeyPresent = 0;
  35908. }
  35909. #endif
  35910. break;
  35911. }
  35912. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  35913. #ifndef NO_DH
  35914. case diffie_hellman_kea:
  35915. {
  35916. ret = DhAgree(ssl, ssl->buffers.serverDH_Key,
  35917. ssl->buffers.serverDH_Priv.buffer,
  35918. ssl->buffers.serverDH_Priv.length,
  35919. input + args->idx,
  35920. (word16)args->sigSz,
  35921. ssl->arrays->preMasterSecret,
  35922. &ssl->arrays->preMasterSz,
  35923. ssl->buffers.serverDH_P.buffer,
  35924. ssl->buffers.serverDH_P.length);
  35925. break;
  35926. }
  35927. #endif /* !NO_DH */
  35928. #if !defined(NO_DH) && !defined(NO_PSK)
  35929. case dhe_psk_kea:
  35930. {
  35931. ret = DhAgree(ssl, ssl->buffers.serverDH_Key,
  35932. ssl->buffers.serverDH_Priv.buffer,
  35933. ssl->buffers.serverDH_Priv.length,
  35934. input + args->idx,
  35935. (word16)args->sigSz,
  35936. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  35937. &ssl->arrays->preMasterSz,
  35938. ssl->buffers.serverDH_P.buffer,
  35939. ssl->buffers.serverDH_P.length);
  35940. break;
  35941. }
  35942. #endif /* !NO_DH && !NO_PSK */
  35943. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  35944. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  35945. case ecdhe_psk_kea:
  35946. {
  35947. #ifdef HAVE_CURVE25519
  35948. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  35949. ret = X25519SharedSecret(ssl,
  35950. (curve25519_key*)ssl->eccTempKey,
  35951. ssl->peerX25519Key,
  35952. input + args->idx, &args->length,
  35953. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  35954. &args->sigSz,
  35955. WOLFSSL_SERVER_END
  35956. );
  35957. #ifdef WOLFSSL_ASYNC_CRYPT
  35958. if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
  35959. #endif
  35960. {
  35961. FreeKey(ssl, DYNAMIC_TYPE_CURVE25519,
  35962. (void**)&ssl->peerX25519Key);
  35963. ssl->peerX25519KeyPresent = 0;
  35964. }
  35965. break;
  35966. }
  35967. #endif
  35968. #ifdef HAVE_CURVE448
  35969. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  35970. ret = X448SharedSecret(ssl,
  35971. (curve448_key*)ssl->eccTempKey,
  35972. ssl->peerX448Key,
  35973. input + args->idx, &args->length,
  35974. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  35975. &args->sigSz,
  35976. WOLFSSL_SERVER_END
  35977. );
  35978. #ifdef WOLFSSL_ASYNC_CRYPT
  35979. if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
  35980. #endif
  35981. {
  35982. FreeKey(ssl, DYNAMIC_TYPE_CURVE448,
  35983. (void**)&ssl->peerX448Key);
  35984. ssl->peerX448KeyPresent = 0;
  35985. }
  35986. break;
  35987. }
  35988. #endif
  35989. /* Generate shared secret */
  35990. ret = EccSharedSecret(ssl,
  35991. ssl->eccTempKey, ssl->peerEccKey,
  35992. input + args->idx, &args->length,
  35993. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  35994. &args->sigSz,
  35995. WOLFSSL_SERVER_END
  35996. );
  35997. if (!ssl->specs.static_ecdh
  35998. #ifdef WOLFSSL_ASYNC_CRYPT
  35999. && ret != WC_NO_ERR_TRACE(WC_PENDING_E)
  36000. #endif
  36001. ) {
  36002. FreeKey(ssl, DYNAMIC_TYPE_ECC,
  36003. (void**)&ssl->peerEccKey);
  36004. ssl->peerEccKeyPresent = 0;
  36005. }
  36006. break;
  36007. }
  36008. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  36009. default:
  36010. ret = BAD_KEA_TYPE_E;
  36011. } /* switch (ssl->specs.kea) */
  36012. /* Check for error */
  36013. if (ret != 0) {
  36014. goto exit_dcke;
  36015. }
  36016. /* Advance state and proceed */
  36017. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  36018. } /* TLS_ASYNC_DO */
  36019. FALL_THROUGH;
  36020. case TLS_ASYNC_VERIFY:
  36021. {
  36022. switch (ssl->specs.kea) {
  36023. #ifndef NO_RSA
  36024. case rsa_kea:
  36025. {
  36026. byte *tmpRsa;
  36027. byte mask;
  36028. /* Add the signature length to idx */
  36029. args->idx += args->length;
  36030. #ifdef DEBUG_WOLFSSL
  36031. /* check version (debug warning message only) */
  36032. if (args->output != NULL) {
  36033. if (args->output[0] != ssl->chVersion.major ||
  36034. args->output[1] != ssl->chVersion.minor) {
  36035. WOLFSSL_MSG("preMasterSecret version mismatch");
  36036. }
  36037. }
  36038. #endif
  36039. /* RFC5246 7.4.7.1:
  36040. * Treat incorrectly formatted message blocks and/or
  36041. * mismatched version numbers in a manner
  36042. * indistinguishable from correctly formatted RSA blocks
  36043. */
  36044. ret = args->lastErr;
  36045. args->lastErr = 0; /* reset */
  36046. /* On error 'ret' will be negative */
  36047. mask = ((unsigned int)ret >>
  36048. ((sizeof(ret) * 8) - 1)) - 1;
  36049. /* build PreMasterSecret */
  36050. ssl->arrays->preMasterSecret[0] = ssl->chVersion.major;
  36051. ssl->arrays->preMasterSecret[1] = ssl->chVersion.minor;
  36052. tmpRsa = input + args->idx - VERSION_SZ - SECRET_LEN;
  36053. ctMaskCopy(~mask, (byte*)&args->output, (byte*)&tmpRsa,
  36054. sizeof(args->output));
  36055. if (args->output != NULL) {
  36056. int i;
  36057. /* Use random secret on error */
  36058. for (i = VERSION_SZ; i < SECRET_LEN; i++) {
  36059. ssl->arrays->preMasterSecret[i] =
  36060. ctMaskSel(mask, args->output[i],
  36061. ssl->arrays->preMasterSecret[i]);
  36062. }
  36063. }
  36064. /* preMasterSecret has RNG and version set
  36065. * return proper length and ignore error
  36066. * error will be caught as decryption error
  36067. */
  36068. args->sigSz = SECRET_LEN;
  36069. ret = 0;
  36070. break;
  36071. } /* rsa_kea */
  36072. #endif /* !NO_RSA */
  36073. #ifndef NO_PSK
  36074. case psk_kea:
  36075. {
  36076. break;
  36077. }
  36078. #endif /* !NO_PSK */
  36079. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  36080. defined(HAVE_CURVE448)
  36081. case ecc_diffie_hellman_kea:
  36082. {
  36083. /* skip past the imported peer key */
  36084. args->idx += args->length;
  36085. break;
  36086. }
  36087. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  36088. #ifndef NO_DH
  36089. case diffie_hellman_kea:
  36090. {
  36091. args->idx += (word16)args->sigSz;
  36092. break;
  36093. }
  36094. #endif /* !NO_DH */
  36095. #if !defined(NO_DH) && !defined(NO_PSK)
  36096. case dhe_psk_kea:
  36097. {
  36098. byte* pms = ssl->arrays->preMasterSecret;
  36099. word16 clientSz = (word16)args->sigSz;
  36100. args->idx += clientSz;
  36101. c16toa((word16)ssl->arrays->preMasterSz, pms);
  36102. ssl->arrays->preMasterSz += OPAQUE16_LEN;
  36103. pms += ssl->arrays->preMasterSz;
  36104. /* Use the PSK hint to look up the PSK and add it to the
  36105. * preMasterSecret here. */
  36106. ssl->arrays->psk_keySz = ssl->options.server_psk_cb(ssl,
  36107. ssl->arrays->client_identity, ssl->arrays->psk_key,
  36108. MAX_PSK_KEY_LEN);
  36109. if (ssl->arrays->psk_keySz == 0 ||
  36110. (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN &&
  36111. (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) {
  36112. #if defined(WOLFSSL_EXTRA_ALERTS) || \
  36113. defined(WOLFSSL_PSK_IDENTITY_ALERT)
  36114. SendAlert(ssl, alert_fatal,
  36115. unknown_psk_identity);
  36116. #endif
  36117. ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
  36118. }
  36119. /* SERVER: Pre-shared Key for peer authentication. */
  36120. ssl->options.peerAuthGood = 1;
  36121. if ((int)ssl->arrays->psk_keySz > 0) {
  36122. c16toa((word16) ssl->arrays->psk_keySz, pms);
  36123. pms += OPAQUE16_LEN;
  36124. XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  36125. ssl->arrays->preMasterSz += ssl->arrays->psk_keySz + OPAQUE16_LEN;
  36126. ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  36127. }
  36128. ssl->arrays->psk_keySz = 0; /* no further need */
  36129. break;
  36130. }
  36131. #endif /* !NO_DH && !NO_PSK */
  36132. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  36133. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  36134. case ecdhe_psk_kea:
  36135. {
  36136. byte* pms = ssl->arrays->preMasterSecret;
  36137. word16 clientSz = (word16)args->sigSz;
  36138. /* skip past the imported peer key */
  36139. args->idx += args->length;
  36140. /* Add preMasterSecret */
  36141. c16toa(clientSz, pms);
  36142. ssl->arrays->preMasterSz = OPAQUE16_LEN + clientSz;
  36143. pms += ssl->arrays->preMasterSz;
  36144. /* Use the PSK hint to look up the PSK and add it to the
  36145. * preMasterSecret here. */
  36146. ssl->arrays->psk_keySz = ssl->options.server_psk_cb(ssl,
  36147. ssl->arrays->client_identity, ssl->arrays->psk_key,
  36148. MAX_PSK_KEY_LEN);
  36149. if (ssl->arrays->psk_keySz == 0 ||
  36150. (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN &&
  36151. (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) {
  36152. ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
  36153. }
  36154. /* SERVER: Pre-shared Key for peer authentication. */
  36155. ssl->options.peerAuthGood = 1;
  36156. if ((int)ssl->arrays->psk_keySz > 0) {
  36157. c16toa((word16) ssl->arrays->psk_keySz, pms);
  36158. pms += OPAQUE16_LEN;
  36159. XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  36160. ssl->arrays->preMasterSz += ssl->arrays->psk_keySz + OPAQUE16_LEN;
  36161. ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  36162. }
  36163. ssl->arrays->psk_keySz = 0; /* no further need */
  36164. break;
  36165. }
  36166. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  36167. default:
  36168. ret = BAD_KEA_TYPE_E;
  36169. } /* switch (ssl->specs.kea) */
  36170. /* Check for error */
  36171. if (ret != 0) {
  36172. goto exit_dcke;
  36173. }
  36174. /* Advance state and proceed */
  36175. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  36176. } /* TLS_ASYNC_VERIFY */
  36177. FALL_THROUGH;
  36178. case TLS_ASYNC_FINALIZE:
  36179. {
  36180. if (IsEncryptionOn(ssl, 0)) {
  36181. args->idx += ssl->keys.padSz;
  36182. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  36183. if (ssl->options.startedETMRead)
  36184. args->idx += MacSize(ssl);
  36185. #endif
  36186. }
  36187. ret = MakeMasterSecret(ssl);
  36188. /* Check for error */
  36189. if (ret != 0) {
  36190. goto exit_dcke;
  36191. }
  36192. /* Advance state and proceed */
  36193. ssl->options.asyncState = TLS_ASYNC_END;
  36194. } /* TLS_ASYNC_FINALIZE */
  36195. FALL_THROUGH;
  36196. case TLS_ASYNC_END:
  36197. {
  36198. /* Set final index */
  36199. *inOutIdx = args->idx;
  36200. ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
  36201. #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  36202. if (ssl->options.verifyPeer) {
  36203. ret = BuildCertHashes(ssl, &ssl->hsHashes->certHashes);
  36204. }
  36205. #endif
  36206. break;
  36207. } /* TLS_ASYNC_END */
  36208. default:
  36209. ret = INPUT_CASE_ERROR;
  36210. } /* switch(ssl->options.asyncState) */
  36211. exit_dcke:
  36212. #ifdef WOLFSSL_BLIND_PRIVATE_KEY
  36213. if (ret == 0) {
  36214. ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
  36215. &ssl->buffers.keyMask);
  36216. }
  36217. else {
  36218. wolfssl_priv_der_unblind(ssl->buffers.key, ssl->buffers.keyMask);
  36219. }
  36220. #endif
  36221. WOLFSSL_LEAVE("DoClientKeyExchange", ret);
  36222. WOLFSSL_END(WC_FUNC_CLIENT_KEY_EXCHANGE_DO);
  36223. #ifdef WOLFSSL_ASYNC_CRYPT
  36224. /* Handle async operation */
  36225. if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  36226. /* Mark message as not received so it can process again */
  36227. ssl->msgsReceived.got_client_key_exchange = 0;
  36228. return ret;
  36229. }
  36230. /* Cleanup async */
  36231. FreeAsyncCtx(ssl, 0);
  36232. #else
  36233. FreeDckeArgs(ssl, args);
  36234. #endif /* WOLFSSL_ASYNC_CRYPT */
  36235. #ifdef OPENSSL_ALL
  36236. /* add error ret value to error queue */
  36237. if (ret != 0) {
  36238. WOLFSSL_ERROR(ret);
  36239. }
  36240. #endif
  36241. /* Cleanup PMS */
  36242. if (ssl->arrays->preMasterSecret != NULL) {
  36243. ForceZero(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  36244. }
  36245. ssl->arrays->preMasterSz = 0;
  36246. /* Final cleanup */
  36247. FreeKeyExchange(ssl);
  36248. return ret;
  36249. }
  36250. #endif /* !WOLFSSL_NO_TLS12 */
  36251. #ifdef HAVE_SNI
  36252. int SNI_Callback(WOLFSSL* ssl)
  36253. {
  36254. int ad = 0;
  36255. int sniRet = 0;
  36256. int ret = 0;
  36257. /* OpenSSL defaults alert to SSL_AD_UNRECOGNIZED_NAME, use this if
  36258. WOLFSSL_EXTRA_ALERTS is defined, indicating user is OK with
  36259. potential information disclosure from alerts. */
  36260. #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_EXTRA_ALERTS)
  36261. ad = SSL_AD_UNRECOGNIZED_NAME;
  36262. #endif
  36263. /* Stunnel supports a custom sni callback to switch an SSL's ctx
  36264. * when SNI is received. Call it now if exists */
  36265. if(ssl && ssl->ctx && ssl->ctx->sniRecvCb) {
  36266. WOLFSSL_MSG("Calling custom sni callback");
  36267. sniRet = ssl->ctx->sniRecvCb(ssl, &ad, ssl->ctx->sniRecvCbArg);
  36268. switch (sniRet) {
  36269. case warning_return:
  36270. WOLFSSL_MSG("Error in custom sni callback. Warning alert");
  36271. ret = SendAlert(ssl, alert_warning, ad);
  36272. break;
  36273. case fatal_return:
  36274. WOLFSSL_MSG("Error in custom sni callback. Fatal alert");
  36275. SendAlert(ssl, alert_fatal, ad);
  36276. return FATAL_ERROR;
  36277. case noack_return:
  36278. WOLFSSL_MSG("Server quietly not acking servername.");
  36279. break;
  36280. default:
  36281. break;
  36282. }
  36283. }
  36284. return ret;
  36285. }
  36286. #endif /* HAVE_SNI */
  36287. #endif /* NO_WOLFSSL_SERVER */
  36288. #ifdef WOLFSSL_ASYNC_CRYPT
  36289. int wolfSSL_AsyncPop(WOLFSSL* ssl, byte* state)
  36290. {
  36291. int ret = 0;
  36292. WC_ASYNC_DEV* asyncDev;
  36293. WOLF_EVENT* event;
  36294. if (ssl == NULL) {
  36295. return BAD_FUNC_ARG;
  36296. }
  36297. /* check for pending async */
  36298. asyncDev = ssl->asyncDev;
  36299. if (asyncDev) {
  36300. /* grab event pointer */
  36301. event = &asyncDev->event;
  36302. ret = wolfAsync_EventPop(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL);
  36303. if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E) &&
  36304. ret != WC_NO_ERR_TRACE(WC_PENDING_E)) {
  36305. /* advance key share state if doesn't need called again */
  36306. if (state && (asyncDev->event.flags & WC_ASYNC_FLAG_CALL_AGAIN) == 0) {
  36307. (*state)++;
  36308. }
  36309. /* clear event and async device */
  36310. XMEMSET(&asyncDev->event, 0, sizeof(WOLF_EVENT));
  36311. ssl->asyncDev = NULL;
  36312. }
  36313. /* for crypto or PK callback, if pending remove from queue */
  36314. #if (defined(WOLF_CRYPTO_CB) || defined(HAVE_PK_CALLBACKS)) && \
  36315. !defined(WOLFSSL_ASYNC_CRYPT_SW) && !defined(HAVE_INTEL_QA) && \
  36316. !defined(HAVE_CAVIUM)
  36317. else if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
  36318. /* Allow the underlying crypto API to be called again to trigger the
  36319. * crypto or PK callback. The actual callback must be called, since
  36320. * the completion is not detected in the poll like Intel QAT or
  36321. * Nitrox */
  36322. ret = wolfEventQueue_Remove(&ssl->ctx->event_queue, event);
  36323. }
  36324. #endif
  36325. }
  36326. else {
  36327. ret = WC_NO_PENDING_E;
  36328. }
  36329. WOLFSSL_LEAVE("wolfSSL_AsyncPop", ret);
  36330. return ret;
  36331. }
  36332. int wolfSSL_AsyncInit(WOLFSSL* ssl, WC_ASYNC_DEV* asyncDev, word32 flags)
  36333. {
  36334. int ret;
  36335. WOLF_EVENT* event;
  36336. if (ssl == NULL || asyncDev == NULL) {
  36337. return BAD_FUNC_ARG;
  36338. }
  36339. /* grab event pointer */
  36340. event = &asyncDev->event;
  36341. /* init event */
  36342. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL, ssl, flags);
  36343. WOLFSSL_LEAVE("wolfSSL_AsyncInit", ret);
  36344. return ret;
  36345. }
  36346. int wolfSSL_AsyncPush(WOLFSSL* ssl, WC_ASYNC_DEV* asyncDev)
  36347. {
  36348. int ret;
  36349. WOLF_EVENT* event;
  36350. if (ssl == NULL || asyncDev == NULL) {
  36351. return BAD_FUNC_ARG;
  36352. }
  36353. /* grab event pointer */
  36354. event = &asyncDev->event;
  36355. /* store reference to active async operation */
  36356. ssl->asyncDev = asyncDev;
  36357. /* place event into queue */
  36358. ret = wolfAsync_EventQueuePush(&ssl->ctx->event_queue, event);
  36359. /* success means return WC_PENDING_E */
  36360. if (ret == 0) {
  36361. ret = WC_PENDING_E;
  36362. }
  36363. WOLFSSL_LEAVE("wolfSSL_AsyncPush", ret);
  36364. return ret;
  36365. }
  36366. #endif /* WOLFSSL_ASYNC_CRYPT */
  36367. /**
  36368. * Return the max fragment size. This is essentially the maximum
  36369. * fragment_length available.
  36370. * @param ssl WOLFSSL object containing ciphersuite information.
  36371. * @param maxFragment The amount of space we want to check is available. This
  36372. * is only the fragment length WITHOUT the (D)TLS headers.
  36373. * @return Max fragment size
  36374. */
  36375. int wolfSSL_GetMaxFragSize(WOLFSSL* ssl, int maxFragment)
  36376. {
  36377. (void) ssl; /* Avoid compiler warnings */
  36378. if (maxFragment > MAX_RECORD_SIZE) {
  36379. maxFragment = MAX_RECORD_SIZE;
  36380. }
  36381. #ifdef HAVE_MAX_FRAGMENT
  36382. if ((ssl->max_fragment != 0) && ((word16)maxFragment > ssl->max_fragment)) {
  36383. maxFragment = ssl->max_fragment;
  36384. }
  36385. #endif /* HAVE_MAX_FRAGMENT */
  36386. #ifdef WOLFSSL_DTLS
  36387. if (IsDtlsNotSctpMode(ssl)) {
  36388. int outputSz, mtuSz;
  36389. /* Given a input buffer size of maxFragment, how big will the
  36390. * encrypted output be? */
  36391. if (IsEncryptionOn(ssl, 1)) {
  36392. outputSz = BuildMessage(ssl, NULL, 0, NULL,
  36393. maxFragment + DTLS_HANDSHAKE_HEADER_SZ,
  36394. application_data, 0, 1, 0, CUR_ORDER);
  36395. }
  36396. else {
  36397. outputSz = maxFragment + DTLS_RECORD_HEADER_SZ +
  36398. DTLS_HANDSHAKE_HEADER_SZ;
  36399. }
  36400. /* Readjust maxFragment for MTU size. */
  36401. #if defined(WOLFSSL_DTLS_MTU)
  36402. mtuSz = ssl->dtlsMtuSz;
  36403. #else
  36404. mtuSz = MAX_MTU;
  36405. #endif
  36406. maxFragment = ModifyForMTU(ssl, maxFragment, outputSz, mtuSz);
  36407. }
  36408. #endif
  36409. return maxFragment;
  36410. }
  36411. #if defined(WOLFSSL_IOTSAFE) && defined(HAVE_PK_CALLBACKS)
  36412. IOTSAFE *wolfSSL_get_iotsafe_ctx(WOLFSSL *ssl)
  36413. {
  36414. if (ssl == NULL)
  36415. return NULL;
  36416. return &ssl->iotsafe;
  36417. }
  36418. int wolfSSL_set_iotsafe_ctx(WOLFSSL *ssl, IOTSAFE *iotsafe)
  36419. {
  36420. if ((ssl == NULL) || (iotsafe == NULL))
  36421. return BAD_FUNC_ARG;
  36422. XMEMCPY(&ssl->iotsafe, iotsafe, sizeof(IOTSAFE));
  36423. return 0;
  36424. }
  36425. #endif
  36426. #if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR)
  36427. /* create an instance of WOLFSSL_BY_DIR_HASH structure */
  36428. WOLFSSL_BY_DIR_HASH* wolfSSL_BY_DIR_HASH_new(void)
  36429. {
  36430. WOLFSSL_BY_DIR_HASH* dir_hash;
  36431. WOLFSSL_ENTER("wolfSSL_BY_DIR_HASH_new");
  36432. dir_hash = (WOLFSSL_BY_DIR_HASH*)XMALLOC(sizeof(WOLFSSL_BY_DIR_HASH), NULL,
  36433. DYNAMIC_TYPE_OPENSSL);
  36434. if (dir_hash) {
  36435. XMEMSET(dir_hash, 0, sizeof(WOLFSSL_BY_DIR_HASH));
  36436. }
  36437. return dir_hash;
  36438. }
  36439. /* release a WOLFSSL_BY_DIR_HASH resource */
  36440. void wolfSSL_BY_DIR_HASH_free(WOLFSSL_BY_DIR_HASH* dir_hash)
  36441. {
  36442. if (dir_hash == NULL)
  36443. return;
  36444. XFREE(dir_hash, NULL, DYNAMIC_TYPE_OPENSSL);
  36445. }
  36446. /* create an instance of WOLFSSL_STACK for STACK_TYPE_BY_DIR_hash */
  36447. WOLFSSL_STACK* wolfSSL_sk_BY_DIR_HASH_new_null(void)
  36448. {
  36449. WOLFSSL_STACK* sk = wolfSSL_sk_new_node(NULL);
  36450. WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_HASH_new_null");
  36451. if (sk) {
  36452. sk->type = STACK_TYPE_BY_DIR_hash;
  36453. }
  36454. return sk;
  36455. }
  36456. /* returns value less than 0 on fail to match
  36457. * On a successful match the priority level found is returned
  36458. */
  36459. int wolfSSL_sk_BY_DIR_HASH_find(
  36460. WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk, const WOLFSSL_BY_DIR_HASH* toFind)
  36461. {
  36462. WOLFSSL_STACK* next;
  36463. int i, sz;
  36464. WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_HASH_find");
  36465. if (sk == NULL || toFind == NULL) {
  36466. return WOLFSSL_FAILURE;
  36467. }
  36468. sz = wolfSSL_sk_BY_DIR_HASH_num(sk);
  36469. next = sk;
  36470. for (i = 0; i < sz && next != NULL; i++) {
  36471. if (next->data.dir_hash->hash_value == toFind->hash_value) {
  36472. return sz - i; /* reverse because stack pushed highest on first */
  36473. }
  36474. next = next->next;
  36475. }
  36476. return WOLFSSL_FATAL_ERROR;
  36477. }
  36478. /* return a number of WOLFSSL_BY_DIR_HASH in stack */
  36479. int wolfSSL_sk_BY_DIR_HASH_num(const WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *sk)
  36480. {
  36481. WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_HASH_num");
  36482. if (sk == NULL)
  36483. return WOLFSSL_FATAL_ERROR;
  36484. return (int)sk->num;
  36485. }
  36486. /* return WOLFSSL_BY_DIR_HASH instance at i */
  36487. WOLFSSL_BY_DIR_HASH* wolfSSL_sk_BY_DIR_HASH_value(
  36488. const WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *sk, int i)
  36489. {
  36490. WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_HASH_value");
  36491. for (; sk != NULL && i > 0; i--)
  36492. sk = sk->next;
  36493. if (i != 0 || sk == NULL)
  36494. return NULL;
  36495. return sk->data.dir_hash;
  36496. }
  36497. /* pop WOLFSSL_BY_DIR_HASH instance, and remove its node from stack */
  36498. WOLFSSL_BY_DIR_HASH* wolfSSL_sk_BY_DIR_HASH_pop(
  36499. WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk)
  36500. {
  36501. WOLFSSL_STACK* node;
  36502. WOLFSSL_BY_DIR_HASH* hash;
  36503. WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_HASH_pop");
  36504. if (sk == NULL) {
  36505. return NULL;
  36506. }
  36507. node = sk->next;
  36508. hash = sk->data.dir_hash;
  36509. if (node != NULL) { /* update sk and remove node from stack */
  36510. sk->data.dir_hash = node->data.dir_hash;
  36511. sk->next = node->next;
  36512. wolfSSL_sk_free_node(node);
  36513. }
  36514. else { /* last x509 in stack */
  36515. sk->data.dir_hash = NULL;
  36516. }
  36517. if (sk->num > 0) {
  36518. sk->num -= 1;
  36519. }
  36520. return hash;
  36521. }
  36522. /* release all contents in stack, and then release stack itself. */
  36523. /* Second argument is a function pointer to release resources. */
  36524. /* It calls the function to release resources when it is passed */
  36525. /* instead of wolfSSL_BY_DIR_HASH_free(). */
  36526. void wolfSSL_sk_BY_DIR_HASH_pop_free(WOLF_STACK_OF(BY_DIR_HASH)* sk,
  36527. void (*f) (WOLFSSL_BY_DIR_HASH*))
  36528. {
  36529. WOLFSSL_STACK* node;
  36530. WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_HASH_pop_free");
  36531. if (sk == NULL) {
  36532. return;
  36533. }
  36534. /* parse through stack freeing each node */
  36535. node = sk->next;
  36536. while (node && sk->num > 1) {
  36537. WOLFSSL_STACK* tmp = node;
  36538. node = node->next;
  36539. if (f)
  36540. f(tmp->data.dir_hash);
  36541. else
  36542. wolfSSL_BY_DIR_HASH_free(tmp->data.dir_hash);
  36543. tmp->data.dir_hash = NULL;
  36544. XFREE(tmp, NULL, DYNAMIC_TYPE_OPENSSL);
  36545. sk->num -= 1;
  36546. }
  36547. /* free head of stack */
  36548. if (sk->num == 1) {
  36549. if (f)
  36550. f(sk->data.dir_hash);
  36551. else
  36552. wolfSSL_BY_DIR_HASH_free(sk->data.dir_hash);
  36553. sk->data.dir_hash = NULL;
  36554. }
  36555. XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL);
  36556. }
  36557. /* release all contents in stack, and then release stack itself */
  36558. void wolfSSL_sk_BY_DIR_HASH_free(WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *sk)
  36559. {
  36560. wolfSSL_sk_BY_DIR_HASH_pop_free(sk, NULL);
  36561. }
  36562. /* Adds the WOLFSSL_BY_DIR_HASH to the stack "sk". "sk" takes control of "in" and
  36563. * tries to free it when the stack is free'd.
  36564. *
  36565. * return 1 on success 0 on fail
  36566. */
  36567. int wolfSSL_sk_BY_DIR_HASH_push(WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk,
  36568. WOLFSSL_BY_DIR_HASH* in)
  36569. {
  36570. WOLFSSL_STACK* node;
  36571. WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_HASH_push");
  36572. if (sk == NULL || in == NULL) {
  36573. return WOLFSSL_FAILURE;
  36574. }
  36575. /* no previous values in stack */
  36576. if (sk->data.dir_hash == NULL) {
  36577. sk->data.dir_hash = in;
  36578. sk->num += 1;
  36579. return WOLFSSL_SUCCESS;
  36580. }
  36581. /* stack already has value(s) create a new node and add more */
  36582. node = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), NULL,
  36583. DYNAMIC_TYPE_OPENSSL);
  36584. if (node == NULL) {
  36585. WOLFSSL_MSG("Memory error");
  36586. return WOLFSSL_FAILURE;
  36587. }
  36588. XMEMSET(node, 0, sizeof(WOLFSSL_STACK));
  36589. /* push new obj onto head of stack */
  36590. node->data.dir_hash = sk->data.dir_hash;
  36591. node->next = sk->next;
  36592. node->type = sk->type;
  36593. sk->next = node;
  36594. sk->data.dir_hash = in;
  36595. sk->num += 1;
  36596. return WOLFSSL_SUCCESS;
  36597. }
  36598. /* create an instance of WOLFSSL_BY_DIR_entry structure */
  36599. WOLFSSL_BY_DIR_entry* wolfSSL_BY_DIR_entry_new(void)
  36600. {
  36601. WOLFSSL_BY_DIR_entry* entry;
  36602. WOLFSSL_ENTER("wolfSSL_BY_DIR_entry_new");
  36603. entry = (WOLFSSL_BY_DIR_entry*)XMALLOC(sizeof(WOLFSSL_BY_DIR_entry), NULL,
  36604. DYNAMIC_TYPE_OPENSSL);
  36605. if (entry) {
  36606. XMEMSET(entry, 0, sizeof(WOLFSSL_BY_DIR_entry));
  36607. }
  36608. return entry;
  36609. }
  36610. /* release a WOLFSSL_BY_DIR_entry resource */
  36611. void wolfSSL_BY_DIR_entry_free(WOLFSSL_BY_DIR_entry* entry)
  36612. {
  36613. WOLFSSL_ENTER("wolfSSL_BY_DIR_entry_free");
  36614. if (entry == NULL)
  36615. return;
  36616. if (entry->hashes) {
  36617. wolfSSL_sk_BY_DIR_HASH_free(entry->hashes);
  36618. }
  36619. XFREE(entry->dir_name, NULL, DYNAMIC_TYPE_OPENSSL);
  36620. XFREE(entry, NULL, DYNAMIC_TYPE_OPENSSL);
  36621. }
  36622. WOLFSSL_STACK* wolfSSL_sk_BY_DIR_entry_new_null(void)
  36623. {
  36624. WOLFSSL_STACK* sk = wolfSSL_sk_new_node(NULL);
  36625. WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_entry_new_null");
  36626. if (sk) {
  36627. sk->type = STACK_TYPE_BY_DIR_entry;
  36628. }
  36629. return sk;
  36630. }
  36631. /* return a number of WOLFSSL_BY_DIR_entry in stack */
  36632. int wolfSSL_sk_BY_DIR_entry_num(const WOLF_STACK_OF(WOLFSSL_BY_DIR_entry) *sk)
  36633. {
  36634. WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_entry_num");
  36635. if (sk == NULL)
  36636. return WOLFSSL_FATAL_ERROR;
  36637. return (int)sk->num;
  36638. }
  36639. /* return WOLFSSL_BY_DIR_entry instance at i */
  36640. WOLFSSL_BY_DIR_entry* wolfSSL_sk_BY_DIR_entry_value(
  36641. const WOLF_STACK_OF(WOLFSSL_BY_DIR_entry) *sk, int i)
  36642. {
  36643. WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_entry_value");
  36644. for (; sk != NULL && i > 0; i--)
  36645. sk = sk->next;
  36646. if (i != 0 || sk == NULL)
  36647. return NULL;
  36648. return sk->data.dir_entry;
  36649. }
  36650. /* pop WOLFSSL_BY_DIR_entry instance first, and remove its node from stack */
  36651. WOLFSSL_BY_DIR_entry* wolfSSL_sk_BY_DIR_entry_pop(
  36652. WOLF_STACK_OF(WOLFSSL_BY_DIR_entry)* sk)
  36653. {
  36654. WOLFSSL_STACK* node;
  36655. WOLFSSL_BY_DIR_entry* entry;
  36656. WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_entry_pop");
  36657. if (sk == NULL) {
  36658. return NULL;
  36659. }
  36660. node = sk->next;
  36661. entry = sk->data.dir_entry;
  36662. if (node != NULL) { /* update sk and remove node from stack */
  36663. sk->data.dir_entry = node->data.dir_entry;
  36664. sk->next = node->next;
  36665. wolfSSL_sk_free_node(node);
  36666. }
  36667. else { /* last x509 in stack */
  36668. sk->data.dir_entry = NULL;
  36669. }
  36670. if (sk->num > 0) {
  36671. sk->num -= 1;
  36672. }
  36673. return entry;
  36674. }
  36675. /* release all contents in stack, and then release stack itself. */
  36676. /* Second argument is a function pointer to release resources. */
  36677. /* It calls the function to release resources when it is passed */
  36678. /* instead of wolfSSL_BY_DIR_entry_free(). */
  36679. void wolfSSL_sk_BY_DIR_entry_pop_free(WOLF_STACK_OF(WOLFSSL_BY_DIR_entry)* sk,
  36680. void (*f) (WOLFSSL_BY_DIR_entry*))
  36681. {
  36682. WOLFSSL_STACK* node;
  36683. WOLFSSL_ENTER("wolfSSL_sk_BY_DIR_entry_pop_free");
  36684. if (sk == NULL) {
  36685. return;
  36686. }
  36687. /* parse through stack freeing each node */
  36688. node = sk->next;
  36689. while (node && sk->num > 1) {
  36690. WOLFSSL_STACK* tmp = node;
  36691. node = node->next;
  36692. if (f)
  36693. f(tmp->data.dir_entry);
  36694. else
  36695. wolfSSL_BY_DIR_entry_free(tmp->data.dir_entry);
  36696. tmp->data.dir_entry = NULL;
  36697. XFREE(tmp, NULL, DYNAMIC_TYPE_OPENSSL);
  36698. sk->num -= 1;
  36699. }
  36700. /* free head of stack */
  36701. if (sk->num == 1) {
  36702. if (f)
  36703. f(sk->data.dir_entry);
  36704. else
  36705. wolfSSL_BY_DIR_entry_free(sk->data.dir_entry);
  36706. sk->data.dir_entry = NULL;
  36707. }
  36708. XFREE(sk, NULL, DYNAMIC_TYPE_OPENSSL);
  36709. }
  36710. /* release all contents in stack, and then release stack itself */
  36711. void wolfSSL_sk_BY_DIR_entry_free(WOLF_STACK_OF(wolfSSL_BY_DIR_entry) *sk)
  36712. {
  36713. wolfSSL_sk_BY_DIR_entry_pop_free(sk, NULL);
  36714. }
  36715. /* Adds the wolfSSL_BY_DIR_entry to the stack "sk". "sk" takes control of "in" and
  36716. * tries to free it when the stack is free'd.
  36717. *
  36718. * return 1 on success 0 on fail
  36719. */
  36720. int wolfSSL_sk_BY_DIR_entry_push(WOLF_STACK_OF(WOLFSSL_BY_DIR_entry)* sk,
  36721. WOLFSSL_BY_DIR_entry* in)
  36722. {
  36723. WOLFSSL_STACK* node;
  36724. if (sk == NULL || in == NULL) {
  36725. return WOLFSSL_FAILURE;
  36726. }
  36727. /* no previous values in stack */
  36728. if (sk->data.dir_entry == NULL) {
  36729. sk->data.dir_entry = in;
  36730. sk->num += 1;
  36731. return WOLFSSL_SUCCESS;
  36732. }
  36733. /* stack already has value(s) create a new node and add more */
  36734. node = (WOLFSSL_STACK*)XMALLOC(sizeof(WOLFSSL_STACK), NULL,
  36735. DYNAMIC_TYPE_OPENSSL);
  36736. if (node == NULL) {
  36737. WOLFSSL_MSG("Memory error");
  36738. return WOLFSSL_FAILURE;
  36739. }
  36740. XMEMSET(node, 0, sizeof(WOLFSSL_STACK));
  36741. /* push new obj onto head of stack */
  36742. node->data.dir_entry = sk->data.dir_entry;
  36743. node->next = sk->next;
  36744. node->type = sk->type;
  36745. sk->next = node;
  36746. sk->data.dir_entry = in;
  36747. sk->num += 1;
  36748. return WOLFSSL_SUCCESS;
  36749. }
  36750. #endif /* OPENSSL_ALL */
  36751. #if defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS)
  36752. /*
  36753. * Converts a DER formatted certificate to a SecCertificateRef
  36754. *
  36755. * @param derCert pointer to the DER formatted certificate
  36756. * @param derLen length of the DER formatted cert, in bytes
  36757. *
  36758. * @return The newly created SecCertificateRef. Must be freed by caller when
  36759. * no longer in use
  36760. */
  36761. static SecCertificateRef ConvertToSecCertificateRef(const byte* derCert,
  36762. int derLen)
  36763. {
  36764. CFDataRef derData = NULL;
  36765. SecCertificateRef secCert = NULL;
  36766. WOLFSSL_ENTER("ConvertToSecCertificateRef");
  36767. /* Create a CFDataRef from the DER encoded certificate */
  36768. derData = CFDataCreate(kCFAllocatorDefault, derCert, derLen);
  36769. if (!derData) {
  36770. WOLFSSL_MSG("Error: can't create CFDataRef object for DER cert");
  36771. goto cleanup;
  36772. }
  36773. /* Create a SecCertificateRef from the CFDataRef */
  36774. secCert = SecCertificateCreateWithData(kCFAllocatorDefault, derData);
  36775. if (!secCert) {
  36776. WOLFSSL_MSG("Error: can't create SecCertificateRef from CFDataRef");
  36777. goto cleanup;
  36778. }
  36779. cleanup:
  36780. if (derData) {
  36781. CFRelease(derData);
  36782. }
  36783. WOLFSSL_LEAVE("ConvertToSecCertificateRef", !!secCert);
  36784. return secCert;
  36785. }
  36786. /*
  36787. * Validates a chain of certificates using the Apple system trust APIs
  36788. *
  36789. * @param certs pointer to the certificate chain to validate
  36790. * @param totalCerts the number of certificates in certs
  36791. *
  36792. * @return 1 if chain is valid and trusted
  36793. * @return 0 if chain is invalid or untrusted
  36794. *
  36795. * As of MacOS 14.0 we are still able to access system certificates and load
  36796. * them manually into wolfSSL. For other apple devices, apple has removed the
  36797. * ability to obtain certificates from the trust store, so we can't use
  36798. * wolfSSL's built-in certificate validation mechanisms anymore. We instead
  36799. * must call into the Security Framework APIs to authenticate peer certificates
  36800. */
  36801. static int DoAppleNativeCertValidation(const WOLFSSL_BUFFER_INFO* certs,
  36802. int totalCerts)
  36803. {
  36804. int i;
  36805. int ret;
  36806. OSStatus status;
  36807. CFMutableArrayRef certArray = NULL;
  36808. SecCertificateRef secCert = NULL;
  36809. SecTrustRef trust = NULL;
  36810. SecPolicyRef policy = NULL ;
  36811. WOLFSSL_ENTER("DoAppleNativeCertValidation");
  36812. certArray = CFArrayCreateMutable(kCFAllocatorDefault,
  36813. totalCerts,
  36814. &kCFTypeArrayCallBacks);
  36815. if (!certArray) {
  36816. WOLFSSL_MSG("Error: can't allocate CFArray for certificates");
  36817. ret = 0;
  36818. goto cleanup;
  36819. }
  36820. for (i = 0; i < totalCerts; i++) {
  36821. secCert = ConvertToSecCertificateRef(certs[i].buffer,
  36822. (int)certs[i].length);
  36823. if (!secCert) {
  36824. WOLFSSL_MSG("Error: can't convert DER cert to SecCertificateRef");
  36825. ret = 0;
  36826. goto cleanup;
  36827. }
  36828. else {
  36829. CFArrayAppendValue(certArray, secCert);
  36830. /* Release, since the array now holds the reference */
  36831. CFRelease(secCert);
  36832. }
  36833. }
  36834. /* Create trust object for SecCertifiate Ref */
  36835. policy = SecPolicyCreateSSL(true, NULL);
  36836. status = SecTrustCreateWithCertificates(certArray, policy, &trust);
  36837. if (status != errSecSuccess) {
  36838. WOLFSSL_MSG_EX("Error creating trust object, "
  36839. "SecTrustCreateWithCertificates returned %d",status);
  36840. ret = 0;
  36841. goto cleanup;
  36842. }
  36843. /* Evaluate the certificate's authenticity */
  36844. if (SecTrustEvaluateWithError(trust, NULL) == 1) {
  36845. WOLFSSL_MSG("Cert chain is trusted");
  36846. ret = 1;
  36847. }
  36848. else {
  36849. WOLFSSL_MSG("Cert chain trust evaluation failed"
  36850. "SecTrustEvaluateWithError returned 0");
  36851. ret = 0;
  36852. }
  36853. /* Cleanup */
  36854. cleanup:
  36855. if (certArray) {
  36856. CFRelease(certArray);
  36857. }
  36858. if (trust) {
  36859. CFRelease(trust);
  36860. }
  36861. if (policy) {
  36862. CFRelease(policy);
  36863. }
  36864. WOLFSSL_LEAVE("DoAppleNativeCertValidation", ret);
  36865. return ret;
  36866. }
  36867. #endif /* defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS) */
  36868. #undef ERROR_OUT
  36869. #endif /* WOLFCRYPT_ONLY */