internal.c 988 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420
  1. /* internal.c
  2. *
  3. * Copyright (C) 2006-2020 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. */
  36. #ifdef EXTERNAL_OPTS_OPENVPN
  37. #error EXTERNAL_OPTS_OPENVPN should not be defined\
  38. when building wolfSSL
  39. #endif
  40. #ifndef WOLFCRYPT_ONLY
  41. #include <wolfssl/internal.h>
  42. #include <wolfssl/error-ssl.h>
  43. #include <wolfssl/wolfcrypt/asn.h>
  44. #include <wolfssl/wolfcrypt/dh.h>
  45. #ifdef NO_INLINE
  46. #include <wolfssl/wolfcrypt/misc.h>
  47. #else
  48. #define WOLFSSL_MISC_INCLUDED
  49. #include <wolfcrypt/src/misc.c>
  50. #endif
  51. #if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA)
  52. #include <wolfssl/wolfcrypt/srp.h>
  53. #endif
  54. #ifdef HAVE_LIBZ
  55. #include "zlib.h"
  56. #endif
  57. #ifdef HAVE_NTRU
  58. #include "libntruencrypt/ntru_crypto.h"
  59. #endif
  60. #if defined(DEBUG_WOLFSSL) || defined(SHOW_SECRETS) || \
  61. defined(CHACHA_AEAD_TEST) || defined(WOLFSSL_SESSION_EXPORT_DEBUG)
  62. #ifndef NO_STDIO_FILESYSTEM
  63. #include <stdio.h>
  64. #endif
  65. #endif
  66. #ifdef __sun
  67. #include <sys/filio.h>
  68. #endif
  69. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  70. #ifdef _MSC_VER
  71. /* disable for while(0) cases at the .c level for now */
  72. #pragma warning(disable:4127)
  73. #endif
  74. #if defined(WOLFSSL_CALLBACKS) && !defined(LARGE_STATIC_BUFFERS)
  75. #error \
  76. WOLFSSL_CALLBACKS needs LARGE_STATIC_BUFFERS, please add LARGE_STATIC_BUFFERS
  77. #endif
  78. #if defined(HAVE_SECURE_RENEGOTIATION) && defined(HAVE_RENEGOTIATION_INDICATION)
  79. #error Cannot use both secure-renegotiation and renegotiation-indication
  80. #endif
  81. #ifndef WOLFSSL_NO_TLS12
  82. #ifndef NO_WOLFSSL_CLIENT
  83. static int DoHelloVerifyRequest(WOLFSSL* ssl, const byte* input, word32*,
  84. word32);
  85. static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input, word32*,
  86. word32);
  87. #ifndef NO_CERTS
  88. static int DoCertificateRequest(WOLFSSL* ssl, const byte* input, word32*,
  89. word32);
  90. #endif
  91. #ifdef HAVE_SESSION_TICKET
  92. static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32*,
  93. word32);
  94. #endif
  95. #endif
  96. #ifndef NO_WOLFSSL_SERVER
  97. static int DoClientKeyExchange(WOLFSSL* ssl, byte* input, word32*, word32);
  98. #if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  99. defined(HAVE_ED448)) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  100. static int DoCertificateVerify(WOLFSSL* ssl, byte*, word32*, word32);
  101. #endif
  102. #ifdef WOLFSSL_DTLS
  103. static int SendHelloVerifyRequest(WOLFSSL*, const byte*, byte);
  104. #endif /* WOLFSSL_DTLS */
  105. #endif
  106. #endif /* !WOLFSSL_NO_TLS12 */
  107. #ifdef WOLFSSL_DTLS
  108. static WC_INLINE int DtlsCheckWindow(WOLFSSL* ssl);
  109. static WC_INLINE int DtlsUpdateWindow(WOLFSSL* ssl);
  110. #endif
  111. enum processReply {
  112. doProcessInit = 0,
  113. #ifndef NO_WOLFSSL_SERVER
  114. runProcessOldClientHello,
  115. #endif
  116. getRecordLayerHeader,
  117. getData,
  118. verifyEncryptedMessage,
  119. decryptMessage,
  120. verifyMessage,
  121. runProcessingOneMessage
  122. };
  123. #ifndef WOLFSSL_NO_TLS12
  124. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
  125. /* Server random bytes for TLS v1.3 described downgrade protection mechanism. */
  126. static const byte tls13Downgrade[7] = {
  127. 0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44
  128. };
  129. #define TLS13_DOWNGRADE_SZ sizeof(tls13Downgrade)
  130. #endif /* !NO_WOLFSSL_SERVER || !NO_WOLFSSL_CLIENT */
  131. #if !defined(NO_OLD_TLS) && !defined(WOLFSSL_AEAD_ONLY)
  132. static int SSL_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz,
  133. int padSz, int content, int verify);
  134. #endif
  135. #endif /* !WOLFSSL_NO_TLS12 */
  136. #ifdef HAVE_QSH
  137. int QSH_Init(WOLFSSL* ssl);
  138. #endif
  139. #ifdef WOLFSSL_RENESAS_TSIP_TLS
  140. int tsip_useable(const WOLFSSL *ssl);
  141. int tsip_generatePremasterSecret();
  142. int tsip_generateEncryptPreMasterSecret(WOLFSSL *ssl, byte *out, word32 *outSz);
  143. #endif
  144. int IsTLS(const WOLFSSL* ssl)
  145. {
  146. if (ssl->version.major == SSLv3_MAJOR && ssl->version.minor >=TLSv1_MINOR)
  147. return 1;
  148. return 0;
  149. }
  150. int IsAtLeastTLSv1_2(const WOLFSSL* ssl)
  151. {
  152. if (ssl->version.major == SSLv3_MAJOR && ssl->version.minor >=TLSv1_2_MINOR)
  153. return 1;
  154. #ifdef WOLFSSL_DTLS
  155. if (ssl->version.major == DTLS_MAJOR && ssl->version.minor <= DTLSv1_2_MINOR)
  156. return 1;
  157. #endif
  158. return 0;
  159. }
  160. int IsAtLeastTLSv1_3(const ProtocolVersion pv)
  161. {
  162. return (pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_3_MINOR);
  163. }
  164. static WC_INLINE int IsEncryptionOn(WOLFSSL* ssl, int isSend)
  165. {
  166. (void)isSend;
  167. #ifdef WOLFSSL_DTLS
  168. /* For DTLS, epoch 0 is always not encrypted. */
  169. if (ssl->options.dtls && !isSend && ssl->keys.curEpoch == 0)
  170. return 0;
  171. #endif /* WOLFSSL_DTLS */
  172. #ifdef WOLFSSL_TLS13
  173. if (isSend)
  174. return ssl->encrypt.setup;
  175. else
  176. return ssl->decrypt.setup;
  177. #else
  178. return ssl->keys.encryptionOn;
  179. #endif
  180. }
  181. #if defined(WOLFSSL_DTLS) || !defined(WOLFSSL_NO_TLS12)
  182. /* If SCTP is not enabled returns the state of the dtls option.
  183. * If SCTP is enabled returns dtls && !sctp. */
  184. static WC_INLINE int IsDtlsNotSctpMode(WOLFSSL* ssl)
  185. {
  186. int result = ssl->options.dtls;
  187. if (result) {
  188. #ifdef WOLFSSL_SCTP
  189. result = !ssl->options.dtlsSctp;
  190. #endif
  191. }
  192. return result;
  193. }
  194. #endif /* DTLS || !WOLFSSL_NO_TLS12 */
  195. #ifdef HAVE_QSH
  196. /* free all structs that where used with QSH */
  197. static int QSH_FreeAll(WOLFSSL* ssl)
  198. {
  199. QSHKey* key = ssl->QSH_Key;
  200. QSHKey* preKey = NULL;
  201. QSHSecret* secret = ssl->QSH_secret;
  202. QSHScheme* list = NULL;
  203. QSHScheme* preList = NULL;
  204. /* free elements in struct */
  205. while (key) {
  206. preKey = key;
  207. if (key->pri.buffer) {
  208. ForceZero(key->pri.buffer, key->pri.length);
  209. XFREE(key->pri.buffer, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  210. }
  211. if (key->pub.buffer)
  212. XFREE(key->pub.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  213. key = (QSHKey*)key->next;
  214. /* free struct */
  215. XFREE(preKey, ssl->heap, DYNAMIC_TYPE_QSH);
  216. }
  217. /* free all of peers QSH keys */
  218. key = ssl->peerQSHKey;
  219. while (key) {
  220. preKey = key;
  221. if (key->pri.buffer) {
  222. ForceZero(key->pri.buffer, key->pri.length);
  223. XFREE(key->pri.buffer, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  224. }
  225. if (key->pub.buffer)
  226. XFREE(key->pub.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  227. key = (QSHKey*)key->next;
  228. /* free struct */
  229. XFREE(preKey, ssl->heap, DYNAMIC_TYPE_QSH);
  230. }
  231. key = NULL;
  232. /* free secret information */
  233. if (secret) {
  234. /* free up the QSHScheme list in QSHSecret */
  235. if (secret->list)
  236. list = secret->list;
  237. while (list) {
  238. preList = list;
  239. if (list->PK)
  240. XFREE(list->PK, ssl->heap, DYNAMIC_TYPE_SECRET);
  241. list = (QSHScheme*)list->next;
  242. XFREE(preList, ssl->heap, DYNAMIC_TYPE_QSH);
  243. }
  244. /* free secret buffers */
  245. if (secret->SerSi) {
  246. if (secret->SerSi->buffer) {
  247. /* clear extra secret material that supplemented Master Secret*/
  248. ForceZero(secret->SerSi->buffer, secret->SerSi->length);
  249. XFREE(secret->SerSi->buffer, ssl->heap, DYNAMIC_TYPE_SECRET);
  250. }
  251. XFREE(secret->SerSi, ssl->heap, DYNAMIC_TYPE_SECRET);
  252. }
  253. if (secret->CliSi) {
  254. if (secret->CliSi->buffer) {
  255. /* clear extra secret material that supplemented Master Secret*/
  256. ForceZero(secret->CliSi->buffer, secret->CliSi->length);
  257. XFREE(secret->CliSi->buffer, ssl->heap, DYNAMIC_TYPE_SECRET);
  258. }
  259. XFREE(secret->CliSi, ssl->heap, DYNAMIC_TYPE_SECRET);
  260. }
  261. }
  262. XFREE(secret, ssl->heap, DYNAMIC_TYPE_QSH);
  263. secret = NULL;
  264. return 0;
  265. }
  266. #endif
  267. #ifdef HAVE_NTRU
  268. static WOLFSSL_GLOBAL WC_RNG* rng;
  269. static WOLFSSL_GLOBAL wolfSSL_Mutex* rngMutex;
  270. static word32 GetEntropy(unsigned char* out, word32 num_bytes)
  271. {
  272. int ret = 0;
  273. if (rng == NULL) {
  274. if ((rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), 0,
  275. DYNAMIC_TYPE_RNG)) == NULL)
  276. return DRBG_OUT_OF_MEMORY;
  277. wc_InitRng(rng);
  278. }
  279. if (rngMutex == NULL) {
  280. if ((rngMutex = (wolfSSL_Mutex*)XMALLOC(sizeof(wolfSSL_Mutex), 0,
  281. DYNAMIC_TYPE_MUTEX)) == NULL)
  282. return DRBG_OUT_OF_MEMORY;
  283. wc_InitMutex(rngMutex);
  284. }
  285. ret |= wc_LockMutex(rngMutex);
  286. ret |= wc_RNG_GenerateBlock(rng, out, num_bytes);
  287. ret |= wc_UnLockMutex(rngMutex);
  288. if (ret != 0)
  289. return DRBG_ENTROPY_FAIL;
  290. return DRBG_OK;
  291. }
  292. #endif /* HAVE_NTRU */
  293. #ifdef HAVE_LIBZ
  294. /* alloc user allocs to work with zlib */
  295. static void* myAlloc(void* opaque, unsigned int item, unsigned int size)
  296. {
  297. (void)opaque;
  298. return XMALLOC(item * size, opaque, DYNAMIC_TYPE_LIBZ);
  299. }
  300. static void myFree(void* opaque, void* memory)
  301. {
  302. (void)opaque;
  303. XFREE(memory, opaque, DYNAMIC_TYPE_LIBZ);
  304. }
  305. /* init zlib comp/decomp streams, 0 on success */
  306. static int InitStreams(WOLFSSL* ssl)
  307. {
  308. ssl->c_stream.zalloc = (alloc_func)myAlloc;
  309. ssl->c_stream.zfree = (free_func)myFree;
  310. ssl->c_stream.opaque = (voidpf)ssl->heap;
  311. if (deflateInit(&ssl->c_stream, Z_DEFAULT_COMPRESSION) != Z_OK)
  312. return ZLIB_INIT_ERROR;
  313. ssl->didStreamInit = 1;
  314. ssl->d_stream.zalloc = (alloc_func)myAlloc;
  315. ssl->d_stream.zfree = (free_func)myFree;
  316. ssl->d_stream.opaque = (voidpf)ssl->heap;
  317. if (inflateInit(&ssl->d_stream) != Z_OK) return ZLIB_INIT_ERROR;
  318. return 0;
  319. }
  320. static void FreeStreams(WOLFSSL* ssl)
  321. {
  322. if (ssl->didStreamInit) {
  323. deflateEnd(&ssl->c_stream);
  324. inflateEnd(&ssl->d_stream);
  325. }
  326. }
  327. /* compress in to out, return out size or error */
  328. static int myCompress(WOLFSSL* ssl, byte* in, int inSz, byte* out, int outSz)
  329. {
  330. int err;
  331. int currTotal = (int)ssl->c_stream.total_out;
  332. ssl->c_stream.next_in = in;
  333. ssl->c_stream.avail_in = inSz;
  334. ssl->c_stream.next_out = out;
  335. ssl->c_stream.avail_out = outSz;
  336. err = deflate(&ssl->c_stream, Z_SYNC_FLUSH);
  337. if (err != Z_OK && err != Z_STREAM_END) return ZLIB_COMPRESS_ERROR;
  338. return (int)ssl->c_stream.total_out - currTotal;
  339. }
  340. /* decompress in to out, return out size or error */
  341. static int myDeCompress(WOLFSSL* ssl, byte* in,int inSz, byte* out,int outSz)
  342. {
  343. int err;
  344. int currTotal = (int)ssl->d_stream.total_out;
  345. ssl->d_stream.next_in = in;
  346. ssl->d_stream.avail_in = inSz;
  347. ssl->d_stream.next_out = out;
  348. ssl->d_stream.avail_out = outSz;
  349. err = inflate(&ssl->d_stream, Z_SYNC_FLUSH);
  350. if (err != Z_OK && err != Z_STREAM_END) return ZLIB_DECOMPRESS_ERROR;
  351. return (int)ssl->d_stream.total_out - currTotal;
  352. }
  353. #endif /* HAVE_LIBZ */
  354. #ifdef WOLFSSL_SESSION_EXPORT
  355. #ifdef WOLFSSL_DTLS
  356. /* serializes the cipher specs struct for exporting */
  357. static int ExportCipherSpecState(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
  358. {
  359. word32 idx = 0;
  360. CipherSpecs* specs;
  361. WOLFSSL_ENTER("ExportCipherSpecState");
  362. if (exp == NULL || ssl == NULL) {
  363. return BAD_FUNC_ARG;
  364. }
  365. specs= &(ssl->specs);
  366. if (DTLS_EXPORT_SPC_SZ > len) {
  367. return BUFFER_E;
  368. }
  369. XMEMSET(exp, 0, DTLS_EXPORT_SPC_SZ);
  370. c16toa(specs->key_size, exp + idx); idx += OPAQUE16_LEN;
  371. c16toa(specs->iv_size, exp + idx); idx += OPAQUE16_LEN;
  372. c16toa(specs->block_size, exp + idx); idx += OPAQUE16_LEN;
  373. c16toa(specs->aead_mac_size, exp + idx); idx += OPAQUE16_LEN;
  374. exp[idx++] = specs->bulk_cipher_algorithm;
  375. exp[idx++] = specs->cipher_type;
  376. exp[idx++] = specs->mac_algorithm;
  377. exp[idx++] = specs->kea;
  378. exp[idx++] = specs->sig_algo;
  379. exp[idx++] = specs->hash_size;
  380. exp[idx++] = specs->pad_size;
  381. exp[idx++] = specs->static_ecdh;
  382. if (idx != DTLS_EXPORT_SPC_SZ) {
  383. WOLFSSL_MSG("DTLS_EXPORT_SPC_SZ needs updated and export version");
  384. return DTLS_EXPORT_VER_E;
  385. }
  386. WOLFSSL_LEAVE("ExportCipherSpecState", idx);
  387. (void)ver;
  388. return idx;
  389. }
  390. /* serializes the key struct for exporting */
  391. static int ExportKeyState(WOLFSSL* ssl, byte* exp, word32 len, byte ver,
  392. byte small)
  393. {
  394. word32 idx = 0;
  395. byte sz;
  396. Keys* keys;
  397. WOLFSSL_ENTER("ExportKeyState");
  398. if (exp == NULL || ssl == NULL) {
  399. return BAD_FUNC_ARG;
  400. }
  401. keys = &(ssl->keys);
  402. if (DTLS_EXPORT_MIN_KEY_SZ > len) {
  403. WOLFSSL_MSG("Buffer not large enough for minimum key struct size");
  404. return BUFFER_E;
  405. }
  406. XMEMSET(exp, 0, DTLS_EXPORT_MIN_KEY_SZ);
  407. c32toa(keys->peer_sequence_number_hi, exp + idx); idx += OPAQUE32_LEN;
  408. c32toa(keys->peer_sequence_number_lo, exp + idx); idx += OPAQUE32_LEN;
  409. c32toa(keys->sequence_number_hi, exp + idx); idx += OPAQUE32_LEN;
  410. c32toa(keys->sequence_number_lo, exp + idx); idx += OPAQUE32_LEN;
  411. c16toa(keys->peerSeq[0].nextEpoch, exp + idx); idx += OPAQUE16_LEN;
  412. c16toa(keys->peerSeq[0].nextSeq_hi, exp + idx); idx += OPAQUE16_LEN;
  413. c32toa(keys->peerSeq[0].nextSeq_lo, exp + idx); idx += OPAQUE32_LEN;
  414. c16toa(keys->curEpoch, exp + idx); idx += OPAQUE16_LEN;
  415. c16toa(keys->curSeq_hi, exp + idx); idx += OPAQUE16_LEN;
  416. c32toa(keys->curSeq_lo, exp + idx); idx += OPAQUE32_LEN;
  417. c16toa(keys->peerSeq[0].prevSeq_hi, exp + idx); idx += OPAQUE16_LEN;
  418. c32toa(keys->peerSeq[0].prevSeq_lo, exp + idx); idx += OPAQUE32_LEN;
  419. c16toa(keys->dtls_peer_handshake_number, exp + idx); idx += OPAQUE16_LEN;
  420. c16toa(keys->dtls_expected_peer_handshake_number, exp + idx);
  421. idx += OPAQUE16_LEN;
  422. c16toa(keys->dtls_sequence_number_hi, exp + idx); idx += OPAQUE16_LEN;
  423. c32toa(keys->dtls_sequence_number_lo, exp + idx); idx += OPAQUE32_LEN;
  424. c16toa(keys->dtls_prev_sequence_number_hi, exp + idx); idx += OPAQUE16_LEN;
  425. c32toa(keys->dtls_prev_sequence_number_lo, exp + idx); idx += OPAQUE32_LEN;
  426. c16toa(keys->dtls_epoch, exp + idx); idx += OPAQUE16_LEN;
  427. c16toa(keys->dtls_handshake_number, exp + idx); idx += OPAQUE16_LEN;
  428. c32toa(keys->encryptSz, exp + idx); idx += OPAQUE32_LEN;
  429. c32toa(keys->padSz, exp + idx); idx += OPAQUE32_LEN;
  430. exp[idx++] = keys->encryptionOn;
  431. exp[idx++] = keys->decryptedCur;
  432. /* from here on the buffer needs checked because is variable length that
  433. * can be larger than DTLS_EXPORT_MIN_KEY_SZ */
  434. {
  435. word32 i;
  436. if ((OPAQUE16_LEN * 2) + idx +
  437. (2 * (WOLFSSL_DTLS_WINDOW_WORDS * OPAQUE32_LEN)) > len) {
  438. WOLFSSL_MSG("Buffer not large enough for WOLFSSL_DTLS_WINDOW_WORDS");
  439. return BUFFER_E;
  440. }
  441. c16toa(WOLFSSL_DTLS_WINDOW_WORDS, exp + idx); idx += OPAQUE16_LEN;
  442. for (i = 0; i < WOLFSSL_DTLS_WINDOW_WORDS; i++) {
  443. c32toa(keys->peerSeq[0].window[i], exp + idx);
  444. idx += OPAQUE32_LEN;
  445. }
  446. c16toa(WOLFSSL_DTLS_WINDOW_WORDS, exp + idx); idx += OPAQUE16_LEN;
  447. for (i = 0; i < WOLFSSL_DTLS_WINDOW_WORDS; i++) {
  448. c32toa(keys->peerSeq[0].prevWindow[i], exp + idx);
  449. idx += OPAQUE32_LEN;
  450. }
  451. }
  452. if (idx >= len) {
  453. WOLFSSL_MSG("Buffer not large enough for truncated hmac flag");
  454. return BUFFER_E;
  455. }
  456. #ifdef HAVE_TRUNCATED_HMAC
  457. sz = ssl->truncated_hmac ? TRUNCATED_HMAC_SZ: ssl->specs.hash_size;
  458. exp[idx++] = ssl->truncated_hmac;
  459. #else
  460. sz = ssl->specs.hash_size;
  461. exp[idx++] = 0; /* no truncated hmac */
  462. #endif
  463. sz = (small)? 0: sz;
  464. if (idx + (sz * 2) + OPAQUE8_LEN > len) {
  465. WOLFSSL_MSG("Buffer not large enough for MAC secret");
  466. return BUFFER_E;
  467. }
  468. exp[idx++] = sz;
  469. if (sz > 0) {
  470. #ifndef WOLFSSL_AEAD_ONLY
  471. XMEMCPY(exp + idx, keys->client_write_MAC_secret, sz); idx += sz;
  472. XMEMCPY(exp + idx, keys->server_write_MAC_secret, sz); idx += sz;
  473. #else
  474. XMEMSET(exp + idx, 0, sz); idx += sz;
  475. XMEMSET(exp + idx, 0, sz); idx += sz;
  476. #endif
  477. }
  478. sz = (small)? 0: ssl->specs.key_size;
  479. if (idx + (sz * 2) + OPAQUE8_LEN > len) {
  480. WOLFSSL_MSG("Buffer not large enough for write key");
  481. return BUFFER_E;
  482. }
  483. exp[idx++] = sz;
  484. if (sz > 0) {
  485. XMEMCPY(exp + idx, keys->client_write_key, sz); idx += sz;
  486. XMEMCPY(exp + idx, keys->server_write_key, sz); idx += sz;
  487. }
  488. sz = (small)? 0: ssl->specs.iv_size;
  489. if (idx + (sz * 2) + OPAQUE8_LEN + AEAD_MAX_EXP_SZ > len) {
  490. WOLFSSL_MSG("Buffer not large enough for IVs");
  491. return BUFFER_E;
  492. }
  493. exp[idx++] = sz;
  494. if (sz > 0) {
  495. XMEMCPY(exp + idx, keys->client_write_IV, sz); idx += sz;
  496. XMEMCPY(exp + idx, keys->server_write_IV, sz); idx += sz;
  497. }
  498. XMEMCPY(exp + idx, keys->aead_exp_IV, AEAD_MAX_EXP_SZ);
  499. idx += AEAD_MAX_EXP_SZ;
  500. sz = (small)? 0: AEAD_MAX_IMP_SZ;
  501. if (idx + (sz * 2) + OPAQUE8_LEN > len) {
  502. WOLFSSL_MSG("Buffer not large enough for imp IVs");
  503. return BUFFER_E;
  504. }
  505. exp[idx++] = sz;
  506. if (sz > 0) {
  507. XMEMCPY(exp + idx, keys->aead_enc_imp_IV, sz); idx += sz;
  508. XMEMCPY(exp + idx, keys->aead_dec_imp_IV, sz); idx += sz;
  509. }
  510. /* DTLS_EXPORT_KEY_SZ is max value. idx size can vary */
  511. if (idx > DTLS_EXPORT_KEY_SZ) {
  512. WOLFSSL_MSG("DTLS_EXPORT_KEY_SZ needs updated and export version");
  513. return DTLS_EXPORT_VER_E;
  514. }
  515. WOLFSSL_LEAVE("ExportKeyState", idx);
  516. (void)ver;
  517. return idx;
  518. }
  519. static int ImportCipherSpecState(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
  520. {
  521. word32 idx = 0;
  522. CipherSpecs* specs;
  523. WOLFSSL_ENTER("ImportCipherSpecState");
  524. if (exp == NULL || ssl == NULL) {
  525. return BAD_FUNC_ARG;
  526. }
  527. specs= &(ssl->specs);
  528. if (DTLS_EXPORT_SPC_SZ > len) {
  529. WOLFSSL_MSG("Buffer not large enough for max spec struct size");
  530. return BUFFER_E;
  531. }
  532. ato16(exp + idx, &specs->key_size); idx += OPAQUE16_LEN;
  533. ato16(exp + idx, &specs->iv_size); idx += OPAQUE16_LEN;
  534. ato16(exp + idx, &specs->block_size); idx += OPAQUE16_LEN;
  535. ato16(exp + idx, &specs->aead_mac_size); idx += OPAQUE16_LEN;
  536. specs->bulk_cipher_algorithm = exp[idx++];
  537. specs->cipher_type = exp[idx++];
  538. specs->mac_algorithm = exp[idx++];
  539. specs->kea = exp[idx++];
  540. specs->sig_algo = exp[idx++];
  541. specs->hash_size = exp[idx++];
  542. specs->pad_size = exp[idx++];
  543. specs->static_ecdh = exp[idx++];
  544. WOLFSSL_LEAVE("ImportCipherSpecState", idx);
  545. (void)ver;
  546. return idx;
  547. }
  548. static int ImportKeyState(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
  549. {
  550. word32 idx = 0;
  551. byte sz;
  552. Keys* keys;
  553. WOLFSSL_ENTER("ImportKeyState");
  554. if (exp == NULL || ssl == NULL) {
  555. return BAD_FUNC_ARG;
  556. }
  557. keys = &(ssl->keys);
  558. /* check minimum length -- includes byte used for size indicators */
  559. if (len < DTLS_EXPORT_MIN_KEY_SZ) {
  560. WOLFSSL_MSG("Buffer not large enough for minimum expected size");
  561. return BUFFER_E;
  562. }
  563. ato32(exp + idx, &keys->peer_sequence_number_hi); idx += OPAQUE32_LEN;
  564. ato32(exp + idx, &keys->peer_sequence_number_lo); idx += OPAQUE32_LEN;
  565. ato32(exp + idx, &keys->sequence_number_hi); idx += OPAQUE32_LEN;
  566. ato32(exp + idx, &keys->sequence_number_lo); idx += OPAQUE32_LEN;
  567. ato16(exp + idx, &keys->peerSeq[0].nextEpoch); idx += OPAQUE16_LEN;
  568. ato16(exp + idx, &keys->peerSeq[0].nextSeq_hi); idx += OPAQUE16_LEN;
  569. ato32(exp + idx, &keys->peerSeq[0].nextSeq_lo); idx += OPAQUE32_LEN;
  570. ato16(exp + idx, &keys->curEpoch); idx += OPAQUE16_LEN;
  571. ato16(exp + idx, &keys->curSeq_hi); idx += OPAQUE16_LEN;
  572. ato32(exp + idx, &keys->curSeq_lo); idx += OPAQUE32_LEN;
  573. ato16(exp + idx, &keys->peerSeq[0].prevSeq_hi); idx += OPAQUE16_LEN;
  574. ato32(exp + idx, &keys->peerSeq[0].prevSeq_lo); idx += OPAQUE32_LEN;
  575. ato16(exp + idx, &keys->dtls_peer_handshake_number); idx += OPAQUE16_LEN;
  576. ato16(exp + idx, &keys->dtls_expected_peer_handshake_number);
  577. idx += OPAQUE16_LEN;
  578. ato16(exp + idx, &keys->dtls_sequence_number_hi); idx += OPAQUE16_LEN;
  579. ato32(exp + idx, &keys->dtls_sequence_number_lo); idx += OPAQUE32_LEN;
  580. ato16(exp + idx, &keys->dtls_prev_sequence_number_hi); idx += OPAQUE16_LEN;
  581. ato32(exp + idx, &keys->dtls_prev_sequence_number_lo); idx += OPAQUE32_LEN;
  582. ato16(exp + idx, &keys->dtls_epoch); idx += OPAQUE16_LEN;
  583. ato16(exp + idx, &keys->dtls_handshake_number); idx += OPAQUE16_LEN;
  584. ato32(exp + idx, &keys->encryptSz); idx += OPAQUE32_LEN;
  585. ato32(exp + idx, &keys->padSz); idx += OPAQUE32_LEN;
  586. keys->encryptionOn = exp[idx++];
  587. keys->decryptedCur = exp[idx++];
  588. {
  589. word16 i, wordCount, wordAdj = 0;
  590. /* do window */
  591. ato16(exp + idx, &wordCount);
  592. idx += OPAQUE16_LEN;
  593. if (wordCount > WOLFSSL_DTLS_WINDOW_WORDS) {
  594. wordCount = WOLFSSL_DTLS_WINDOW_WORDS;
  595. wordAdj = (WOLFSSL_DTLS_WINDOW_WORDS - wordCount) * sizeof(word32);
  596. }
  597. XMEMSET(keys->peerSeq[0].window, 0xFF, DTLS_SEQ_SZ);
  598. for (i = 0; i < wordCount; i++) {
  599. ato32(exp + idx, &keys->peerSeq[0].window[i]);
  600. idx += OPAQUE32_LEN;
  601. }
  602. idx += wordAdj;
  603. /* do prevWindow */
  604. ato16(exp + idx, &wordCount);
  605. idx += OPAQUE16_LEN;
  606. if (wordCount > WOLFSSL_DTLS_WINDOW_WORDS) {
  607. wordCount = WOLFSSL_DTLS_WINDOW_WORDS;
  608. wordAdj = (WOLFSSL_DTLS_WINDOW_WORDS - wordCount) * sizeof(word32);
  609. }
  610. XMEMSET(keys->peerSeq[0].prevWindow, 0xFF, DTLS_SEQ_SZ);
  611. for (i = 0; i < wordCount; i++) {
  612. ato32(exp + idx, &keys->peerSeq[0].prevWindow[i]);
  613. idx += OPAQUE32_LEN;
  614. }
  615. idx += wordAdj;
  616. }
  617. #ifdef HAVE_TRUNCATED_HMAC
  618. ssl->truncated_hmac = exp[idx++];
  619. #else
  620. idx++; /* no truncated hmac */
  621. #endif
  622. sz = exp[idx++];
  623. #ifndef WOLFSSL_AEAD_ONLY
  624. if (sz > sizeof(keys->client_write_MAC_secret) || (sz * 2) + idx > len) {
  625. WOLFSSL_MSG("Buffer not large enough for MAC import");
  626. return BUFFER_E;
  627. }
  628. if (sz > 0) {
  629. XMEMCPY(keys->client_write_MAC_secret, exp + idx, sz); idx += sz;
  630. XMEMCPY(keys->server_write_MAC_secret, exp + idx, sz); idx += sz;
  631. }
  632. #else
  633. if (sz + idx > len) {
  634. return BUFFER_E;
  635. }
  636. idx += sz; idx += sz;
  637. #endif
  638. sz = exp[idx++];
  639. if (sz > sizeof(keys->client_write_key) || (sz * 2) + idx > len) {
  640. WOLFSSL_MSG("Buffer not large enough for key import");
  641. return BUFFER_E;
  642. }
  643. if (sz > 0) {
  644. XMEMCPY(keys->client_write_key, exp + idx, sz); idx += sz;
  645. XMEMCPY(keys->server_write_key, exp + idx, sz); idx += sz;
  646. }
  647. sz = exp[idx++];
  648. if (sz > sizeof(keys->client_write_IV) || (sz * 2) + idx > len) {
  649. WOLFSSL_MSG("Buffer not large enough for write IV import");
  650. return BUFFER_E;
  651. }
  652. if (sz > 0) {
  653. XMEMCPY(keys->client_write_IV, exp + idx, sz); idx += sz;
  654. XMEMCPY(keys->server_write_IV, exp + idx, sz); idx += sz;
  655. }
  656. XMEMCPY(keys->aead_exp_IV, exp + idx, AEAD_MAX_EXP_SZ);
  657. idx += AEAD_MAX_EXP_SZ;
  658. sz = exp[idx++];
  659. if (sz > sizeof(keys->aead_enc_imp_IV) || (sz * 2) + idx > len) {
  660. WOLFSSL_MSG("Buffer not large enough for imp IV import");
  661. return BUFFER_E;
  662. }
  663. if (sz > 0) {
  664. XMEMCPY(keys->aead_enc_imp_IV, exp + idx, sz); idx += sz;
  665. XMEMCPY(keys->aead_dec_imp_IV, exp + idx, sz); idx += sz;
  666. }
  667. WOLFSSL_LEAVE("ImportKeyState", idx);
  668. (void)ver;
  669. return idx;
  670. }
  671. /* copy over necessary information from Options struct to buffer
  672. * On success returns size of buffer used on failure returns a negative value */
  673. static int dtls_export_new(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
  674. {
  675. int idx = 0;
  676. word16 zero = 0;
  677. Options* options = &ssl->options;
  678. WOLFSSL_ENTER("dtls_export_new");
  679. if (exp == NULL || options == NULL || len < DTLS_EXPORT_OPT_SZ) {
  680. return BAD_FUNC_ARG;
  681. }
  682. XMEMSET(exp, 0, DTLS_EXPORT_OPT_SZ);
  683. /* these options are kept and sent to indicate verify status and strength
  684. * of handshake */
  685. exp[idx++] = options->sendVerify;
  686. exp[idx++] = options->verifyPeer;
  687. exp[idx++] = options->verifyNone;
  688. exp[idx++] = options->downgrade;
  689. #ifndef NO_DH
  690. c16toa(options->minDhKeySz, exp + idx); idx += OPAQUE16_LEN;
  691. c16toa(options->maxDhKeySz, exp + idx); idx += OPAQUE16_LEN;
  692. c16toa(options->dhKeySz, exp + idx); idx += OPAQUE16_LEN;
  693. #else
  694. c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
  695. c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
  696. c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
  697. #endif
  698. #ifndef NO_RSA
  699. c16toa((word16)(options->minRsaKeySz), exp + idx); idx += OPAQUE16_LEN;
  700. #else
  701. c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
  702. #endif
  703. #ifdef HAVE_ECC
  704. c16toa((word16)(options->minEccKeySz), exp + idx); idx += OPAQUE16_LEN;
  705. #else
  706. c16toa(zero, exp + idx); idx += OPAQUE16_LEN;
  707. #endif
  708. /* these options are kept to indicate state and behavior */
  709. #ifndef NO_PSK
  710. exp[idx++] = options->havePSK;
  711. #else
  712. exp[idx++] = 0;
  713. #endif
  714. exp[idx++] = options->sessionCacheOff;
  715. exp[idx++] = options->sessionCacheFlushOff;
  716. exp[idx++] = options->side;
  717. exp[idx++] = options->resuming;
  718. exp[idx++] = options->haveSessionId;
  719. exp[idx++] = options->tls;
  720. exp[idx++] = options->tls1_1;
  721. exp[idx++] = options->dtls;
  722. exp[idx++] = options->connReset;
  723. exp[idx++] = options->isClosed;
  724. exp[idx++] = options->closeNotify;
  725. exp[idx++] = options->sentNotify;
  726. exp[idx++] = options->usingCompression;
  727. exp[idx++] = options->haveRSA;
  728. exp[idx++] = options->haveECC;
  729. exp[idx++] = options->haveDH;
  730. exp[idx++] = options->haveNTRU;
  731. exp[idx++] = options->haveQSH;
  732. exp[idx++] = options->haveECDSAsig;
  733. exp[idx++] = options->haveStaticECC;
  734. exp[idx++] = options->havePeerVerify;
  735. exp[idx++] = options->usingPSK_cipher;
  736. exp[idx++] = options->usingAnon_cipher;
  737. exp[idx++] = options->sendAlertState;
  738. exp[idx++] = options->partialWrite;
  739. exp[idx++] = options->quietShutdown;
  740. exp[idx++] = options->groupMessages;
  741. #ifdef HAVE_POLY1305
  742. exp[idx++] = options->oldPoly;
  743. #else
  744. exp[idx++] = 0;
  745. #endif
  746. #ifdef HAVE_ANON
  747. exp[idx++] = options->haveAnon;
  748. #else
  749. exp[idx++] = 0;
  750. #endif
  751. #ifdef HAVE_SESSION_TICKET
  752. exp[idx++] = options->createTicket;
  753. exp[idx++] = options->useTicket;
  754. #ifdef WOLFSSL_TLS13
  755. if (ver > DTLS_EXPORT_VERSION_3) {
  756. exp[idx++] = options->noTicketTls13;
  757. }
  758. #else
  759. if (ver > DTLS_EXPORT_VERSION_3) {
  760. exp[idx++] = 0;
  761. }
  762. #endif
  763. #else
  764. exp[idx++] = 0;
  765. exp[idx++] = 0;
  766. if (ver > DTLS_EXPORT_VERSION_3) {
  767. exp[idx++] = 0;
  768. }
  769. #endif
  770. exp[idx++] = options->processReply;
  771. exp[idx++] = options->cipherSuite0;
  772. exp[idx++] = options->cipherSuite;
  773. exp[idx++] = options->serverState;
  774. exp[idx++] = options->clientState;
  775. exp[idx++] = options->handShakeState;
  776. exp[idx++] = options->handShakeDone;
  777. exp[idx++] = options->minDowngrade;
  778. exp[idx++] = options->connectState;
  779. exp[idx++] = options->acceptState;
  780. exp[idx++] = options->asyncState;
  781. /* version of connection */
  782. exp[idx++] = ssl->version.major;
  783. exp[idx++] = ssl->version.minor;
  784. (void)zero;
  785. /* check if changes were made and notify of need to update export version */
  786. switch (ver) {
  787. case DTLS_EXPORT_VERSION_3:
  788. if (idx != DTLS_EXPORT_OPT_SZ_3) {
  789. WOLFSSL_MSG("Update DTLS_EXPORT_OPT_SZ and version of export");
  790. return DTLS_EXPORT_VER_E;
  791. }
  792. break;
  793. case DTLS_EXPORT_VERSION:
  794. if (idx != DTLS_EXPORT_OPT_SZ) {
  795. WOLFSSL_MSG("Update DTLS_EXPORT_OPT_SZ and version of export");
  796. return DTLS_EXPORT_VER_E;
  797. }
  798. break;
  799. default:
  800. WOLFSSL_MSG("New version case needs added to wolfSSL export");
  801. return DTLS_EXPORT_VER_E;
  802. }
  803. WOLFSSL_LEAVE("dtls_export_new", idx);
  804. return idx;
  805. }
  806. /* copy items from Export struct to Options struct
  807. * On success returns size of buffer used on failure returns a negative value */
  808. static int dtls_export_load(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
  809. {
  810. int idx = 0;
  811. Options* options = &ssl->options;
  812. switch (ver) {
  813. case DTLS_EXPORT_VERSION:
  814. if (len < DTLS_EXPORT_OPT_SZ) {
  815. WOLFSSL_MSG("Sanity check on buffer size failed");
  816. return BAD_FUNC_ARG;
  817. }
  818. break;
  819. case DTLS_EXPORT_VERSION_3:
  820. if (len < DTLS_EXPORT_OPT_SZ_3) {
  821. WOLFSSL_MSG("Sanity check on buffer size failed");
  822. return BAD_FUNC_ARG;
  823. }
  824. break;
  825. default:
  826. WOLFSSL_MSG("Export version not supported");
  827. return BAD_FUNC_ARG;
  828. }
  829. if (exp == NULL || options == NULL) {
  830. return BAD_FUNC_ARG;
  831. }
  832. /* these options are kept and sent to indicate verify status and strength
  833. * of handshake */
  834. options->sendVerify = exp[idx++];
  835. options->verifyPeer = exp[idx++];
  836. options->verifyNone = exp[idx++];
  837. options->downgrade = exp[idx++];
  838. #ifndef NO_DH
  839. ato16(exp + idx, &(options->minDhKeySz)); idx += OPAQUE16_LEN;
  840. ato16(exp + idx, &(options->maxDhKeySz)); idx += OPAQUE16_LEN;
  841. ato16(exp + idx, &(options->dhKeySz)); idx += OPAQUE16_LEN;
  842. #else
  843. idx += OPAQUE16_LEN;
  844. idx += OPAQUE16_LEN;
  845. idx += OPAQUE16_LEN;
  846. #endif
  847. #ifndef NO_RSA
  848. ato16(exp + idx, (word16*)&(options->minRsaKeySz)); idx += OPAQUE16_LEN;
  849. #else
  850. idx += OPAQUE16_LEN;
  851. #endif
  852. #ifdef HAVE_ECC
  853. ato16(exp + idx, (word16*)&(options->minEccKeySz)); idx += OPAQUE16_LEN;
  854. #else
  855. idx += OPAQUE16_LEN;
  856. #endif
  857. /* these options are kept to indicate state and behavior */
  858. #ifndef NO_PSK
  859. options->havePSK = exp[idx++];
  860. #else
  861. idx++;
  862. #endif
  863. options->sessionCacheOff = exp[idx++];
  864. options->sessionCacheFlushOff = exp[idx++];
  865. options->side = exp[idx++];
  866. options->resuming = exp[idx++];
  867. options->haveSessionId = exp[idx++];
  868. options->tls = exp[idx++];
  869. options->tls1_1 = exp[idx++];
  870. options->dtls = exp[idx++];
  871. options->connReset = exp[idx++];
  872. options->isClosed = exp[idx++];
  873. options->closeNotify = exp[idx++];
  874. options->sentNotify = exp[idx++];
  875. options->usingCompression = exp[idx++];
  876. options->haveRSA = exp[idx++];
  877. options->haveECC = exp[idx++];
  878. options->haveDH = exp[idx++];
  879. options->haveNTRU = exp[idx++];
  880. options->haveQSH = exp[idx++];
  881. options->haveECDSAsig = exp[idx++];
  882. options->haveStaticECC = exp[idx++];
  883. options->havePeerVerify = exp[idx++];
  884. options->usingPSK_cipher = exp[idx++];
  885. options->usingAnon_cipher = exp[idx++];
  886. options->sendAlertState = exp[idx++];
  887. options->partialWrite = exp[idx++];
  888. options->quietShutdown = exp[idx++];
  889. options->groupMessages = exp[idx++];
  890. #ifdef HAVE_POLY1305
  891. options->oldPoly = exp[idx++]; /* set when to use old rfc way of poly*/
  892. #else
  893. idx++;
  894. #endif
  895. #ifdef HAVE_ANON
  896. options->haveAnon = exp[idx++]; /* User wants to allow Anon suites */
  897. #else
  898. idx++;
  899. #endif
  900. #ifdef HAVE_SESSION_TICKET
  901. options->createTicket = exp[idx++]; /* Server to create new Ticket */
  902. options->useTicket = exp[idx++]; /* Use Ticket not session cache */
  903. #ifdef WOLFSSL_TLS13
  904. if (ver > DTLS_EXPORT_VERSION_3) {
  905. options->noTicketTls13 = exp[idx++];/* Server won't create new Ticket */
  906. }
  907. #else
  908. if (ver > DTLS_EXPORT_VERSION_3) {
  909. exp[idx++] = 0;
  910. }
  911. #endif
  912. #else
  913. idx++;
  914. idx++;
  915. if (ver > DTLS_EXPORT_VERSION_3) {
  916. idx++;
  917. }
  918. #endif
  919. options->processReply = exp[idx++];
  920. options->cipherSuite0 = exp[idx++];
  921. options->cipherSuite = exp[idx++];
  922. options->serverState = exp[idx++];
  923. options->clientState = exp[idx++];
  924. options->handShakeState = exp[idx++];
  925. options->handShakeDone = exp[idx++];
  926. options->minDowngrade = exp[idx++];
  927. options->connectState = exp[idx++];
  928. options->acceptState = exp[idx++];
  929. options->asyncState = exp[idx++];
  930. /* version of connection */
  931. if (ssl->version.major != exp[idx++] || ssl->version.minor != exp[idx++]) {
  932. WOLFSSL_MSG("Version mismatch ie DTLS v1 vs v1.2");
  933. return VERSION_ERROR;
  934. }
  935. return idx;
  936. }
  937. #ifndef WOLFSSL_SESSION_EXPORT_NOPEER
  938. static int ExportPeerInfo(WOLFSSL* ssl, byte* exp, word32 len, byte ver)
  939. {
  940. int idx = 0;
  941. int ipSz = DTLS_EXPORT_IP; /* start as max size */
  942. int fam = 0;
  943. word16 port = 0;
  944. char ip[DTLS_EXPORT_IP];
  945. if (ver != DTLS_EXPORT_VERSION) {
  946. WOLFSSL_MSG("Export version not supported");
  947. return BAD_FUNC_ARG;
  948. }
  949. if (ssl == NULL || exp == NULL || len < sizeof(ip) + 3 * DTLS_EXPORT_LEN) {
  950. return BAD_FUNC_ARG;
  951. }
  952. if (ssl->ctx->CBGetPeer == NULL) {
  953. WOLFSSL_MSG("No get peer call back set");
  954. return BAD_FUNC_ARG;
  955. }
  956. if (ssl->ctx->CBGetPeer(ssl, ip, &ipSz, &port, &fam) != WOLFSSL_SUCCESS) {
  957. WOLFSSL_MSG("Get peer callback error");
  958. return SOCKET_ERROR_E;
  959. }
  960. /* check that ipSz/fam is not negative or too large since user can set cb */
  961. if (ipSz < 0 || ipSz > DTLS_EXPORT_IP || fam < 0) {
  962. WOLFSSL_MSG("Bad ipSz or fam returned from get peer callback");
  963. return SOCKET_ERROR_E;
  964. }
  965. c16toa((word16)fam, exp + idx); idx += DTLS_EXPORT_LEN;
  966. c16toa((word16)ipSz, exp + idx); idx += DTLS_EXPORT_LEN;
  967. XMEMCPY(exp + idx, ip, ipSz); idx += ipSz;
  968. c16toa(port, exp + idx); idx += DTLS_EXPORT_LEN;
  969. return idx;
  970. }
  971. #endif /* !WOLFSSL_SESSION_EXPORT_NOPEER */
  972. static int ImportPeerInfo(WOLFSSL* ssl, byte* buf, word32 len, byte ver)
  973. {
  974. word16 idx = 0;
  975. word16 ipSz;
  976. word16 fam;
  977. word16 port;
  978. char ip[DTLS_EXPORT_IP];
  979. if (ver != DTLS_EXPORT_VERSION && ver != DTLS_EXPORT_VERSION_3) {
  980. WOLFSSL_MSG("Export version not supported");
  981. return BAD_FUNC_ARG;
  982. }
  983. if (len == 0) {
  984. WOLFSSL_MSG("No peer info sent");
  985. return 0;
  986. }
  987. if (ssl == NULL || buf == NULL || len < 3 * DTLS_EXPORT_LEN) {
  988. return BAD_FUNC_ARG;
  989. }
  990. /* import sin family */
  991. ato16(buf + idx, &fam); idx += DTLS_EXPORT_LEN;
  992. /* import ip address idx, and ipSz are unsigned but cast for enum */
  993. ato16(buf + idx, &ipSz); idx += DTLS_EXPORT_LEN;
  994. if (ipSz >= sizeof(ip) || (word16)(idx + ipSz + DTLS_EXPORT_LEN) > len) {
  995. return BUFFER_E;
  996. }
  997. XMEMSET(ip, 0, sizeof(ip));
  998. XMEMCPY(ip, buf + idx, ipSz); idx += ipSz;
  999. ip[ipSz] = '\0'; /* with check that ipSz less than ip this is valid */
  1000. ato16(buf + idx, &port); idx += DTLS_EXPORT_LEN;
  1001. /* sanity check for a function to call, then use it to import peer info */
  1002. if (ssl->ctx->CBSetPeer == NULL) {
  1003. WOLFSSL_MSG("No set peer function");
  1004. return BAD_FUNC_ARG;
  1005. }
  1006. if (ssl->ctx->CBSetPeer(ssl, ip, ipSz, port, fam) != WOLFSSL_SUCCESS) {
  1007. WOLFSSL_MSG("Error setting peer info");
  1008. return SOCKET_ERROR_E;
  1009. }
  1010. return idx;
  1011. }
  1012. /* WOLFSSL_LOCAL function that serializes the current WOLFSSL session state only
  1013. * buf is used to hold the serialized WOLFSSL struct and sz is the size of buf
  1014. * passed in.
  1015. * On success returns the size of serialized session state.*/
  1016. int wolfSSL_dtls_export_state_internal(WOLFSSL* ssl, byte* buf, word32 sz)
  1017. {
  1018. int ret;
  1019. word32 idx = 0;
  1020. word32 totalLen = 0;
  1021. WOLFSSL_ENTER("wolfSSL_dtls_export_state_internal");
  1022. if (buf == NULL || ssl == NULL) {
  1023. WOLFSSL_LEAVE("wolfSSL_dtls_export_state_internal", BAD_FUNC_ARG);
  1024. return BAD_FUNC_ARG;
  1025. }
  1026. totalLen += DTLS_EXPORT_LEN * 2; /* 2 protocol bytes and 2 length bytes */
  1027. /* each of the following have a 2 byte length before data */
  1028. totalLen += DTLS_EXPORT_LEN + DTLS_EXPORT_MIN_KEY_SZ;
  1029. if (totalLen > sz) {
  1030. WOLFSSL_LEAVE("wolfSSL_dtls_export_state_internal", BUFFER_E);
  1031. return BUFFER_E;
  1032. }
  1033. buf[idx++] = (byte)DTLS_EXPORT_STATE_PRO;
  1034. buf[idx++] = ((byte)DTLS_EXPORT_STATE_PRO & 0xF0) |
  1035. ((byte)DTLS_EXPORT_VERSION & 0X0F);
  1036. idx += DTLS_EXPORT_LEN; /* leave room for total length */
  1037. /* export keys struct and dtls state -- variable length stored in ret */
  1038. idx += DTLS_EXPORT_LEN; /* leave room for length */
  1039. if ((ret = ExportKeyState(ssl, buf + idx, sz - idx,
  1040. DTLS_EXPORT_VERSION, 1)) < 0) {
  1041. WOLFSSL_LEAVE("wolfSSL_dtls_export_state_internal", ret);
  1042. return ret;
  1043. }
  1044. c16toa((word16)ret, buf + idx - DTLS_EXPORT_LEN); idx += ret;
  1045. /* place total length of exported buffer minus 2 bytes protocol/version */
  1046. c16toa((word16)(idx - DTLS_EXPORT_LEN), buf + DTLS_EXPORT_LEN);
  1047. #ifdef WOLFSSL_SESSION_EXPORT_DEBUG
  1048. /* if compiled with debug options then print the version, protocol, size */
  1049. {
  1050. char debug[256];
  1051. XSNPRINTF(debug, sizeof(debug), "Exporting DTLS session state\n"
  1052. "\tVersion : %d\n\tProtocol : %02X%01X\n\tLength of: %d\n\n"
  1053. , (int)DTLS_EXPORT_VERSION, buf[0], (buf[1] >> 4), idx - 2);
  1054. WOLFSSL_MSG(debug);
  1055. }
  1056. #endif /* WOLFSSL_SESSION_EXPORT_DEBUG */
  1057. WOLFSSL_LEAVE("wolfSSL_dtls_export_state_internal", idx);
  1058. return idx;
  1059. }
  1060. /* WOLFSSL_LOCAL function that serializes the current WOLFSSL session
  1061. * buf is used to hold the serialized WOLFSSL struct and sz is the size of buf
  1062. * passed in.
  1063. * On success returns the size of serialized session.*/
  1064. int wolfSSL_dtls_export_internal(WOLFSSL* ssl, byte* buf, word32 sz)
  1065. {
  1066. int ret;
  1067. word32 idx = 0;
  1068. word32 totalLen = 0;
  1069. WOLFSSL_ENTER("wolfSSL_dtls_export_internal");
  1070. if (buf == NULL || ssl == NULL) {
  1071. WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", BAD_FUNC_ARG);
  1072. return BAD_FUNC_ARG;
  1073. }
  1074. totalLen += DTLS_EXPORT_LEN * 2; /* 2 protocol bytes and 2 length bytes */
  1075. /* each of the following have a 2 byte length before data */
  1076. totalLen += DTLS_EXPORT_LEN + DTLS_EXPORT_OPT_SZ;
  1077. totalLen += DTLS_EXPORT_LEN + DTLS_EXPORT_KEY_SZ;
  1078. totalLen += DTLS_EXPORT_LEN + DTLS_EXPORT_SPC_SZ;
  1079. totalLen += DTLS_EXPORT_LEN + ssl->buffers.dtlsCtx.peer.sz;
  1080. if (totalLen > sz) {
  1081. WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", BUFFER_E);
  1082. return BUFFER_E;
  1083. }
  1084. buf[idx++] = (byte)DTLS_EXPORT_PRO;
  1085. buf[idx++] = ((byte)DTLS_EXPORT_PRO & 0xF0) |
  1086. ((byte)DTLS_EXPORT_VERSION & 0X0F);
  1087. idx += DTLS_EXPORT_LEN; /* leave spot for length */
  1088. c16toa((word16)DTLS_EXPORT_OPT_SZ, buf + idx); idx += DTLS_EXPORT_LEN;
  1089. if ((ret = dtls_export_new(ssl, buf + idx, sz - idx,
  1090. DTLS_EXPORT_VERSION)) < 0) {
  1091. WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", ret);
  1092. return ret;
  1093. }
  1094. idx += ret;
  1095. /* export keys struct and dtls state -- variable length stored in ret */
  1096. idx += DTLS_EXPORT_LEN; /* leave room for length */
  1097. if ((ret = ExportKeyState(ssl, buf + idx, sz - idx,
  1098. DTLS_EXPORT_VERSION, 0)) < 0) {
  1099. WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", ret);
  1100. return ret;
  1101. }
  1102. c16toa((word16)ret, buf + idx - DTLS_EXPORT_LEN); idx += ret;
  1103. /* export of cipher specs struct */
  1104. c16toa((word16)DTLS_EXPORT_SPC_SZ, buf + idx); idx += DTLS_EXPORT_LEN;
  1105. if ((ret = ExportCipherSpecState(ssl, buf + idx, sz - idx,
  1106. DTLS_EXPORT_VERSION)) < 0) {
  1107. WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", ret);
  1108. return ret;
  1109. }
  1110. idx += ret;
  1111. /* export of dtls peer information */
  1112. idx += DTLS_EXPORT_LEN;
  1113. #ifdef WOLFSSL_SESSION_EXPORT_NOPEER
  1114. ret = 0; /* not saving peer port/ip information */
  1115. #else
  1116. if ((ret = ExportPeerInfo(ssl, buf + idx, sz - idx,
  1117. DTLS_EXPORT_VERSION)) < 0) {
  1118. WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", ret);
  1119. return ret;
  1120. }
  1121. #endif
  1122. c16toa(ret, buf + idx - DTLS_EXPORT_LEN);
  1123. idx += ret;
  1124. /* place total length of exported buffer minus 2 bytes protocol/version */
  1125. c16toa((word16)(idx - DTLS_EXPORT_LEN), buf + DTLS_EXPORT_LEN);
  1126. /* if compiled with debug options then print the version, protocol, size */
  1127. #ifdef WOLFSSL_SESSION_EXPORT_DEBUG
  1128. {
  1129. char debug[256];
  1130. XSNPRINTF(debug, sizeof(debug), "Exporting DTLS session\n"
  1131. "\tVersion : %d\n\tProtocol : %02X%01X\n\tLength of: %d\n\n"
  1132. , (int)DTLS_EXPORT_VERSION, buf[0], (buf[1] >> 4), idx - 2);
  1133. WOLFSSL_MSG(debug);
  1134. }
  1135. #endif /* WOLFSSL_SESSION_EXPORT_DEBUG */
  1136. WOLFSSL_LEAVE("wolfSSL_dtls_export_internal", idx);
  1137. return idx;
  1138. }
  1139. /* On success return amount of buffer consumed */
  1140. int wolfSSL_dtls_import_state_internal(WOLFSSL* ssl, byte* buf, word32 sz)
  1141. {
  1142. word32 idx = 0;
  1143. word16 length = 0;
  1144. int version;
  1145. int ret;
  1146. WOLFSSL_ENTER("wolfSSL_dtls_import_state_internal");
  1147. /* check at least enough room for protocol and length */
  1148. if (sz < DTLS_EXPORT_LEN * 2 || ssl == NULL) {
  1149. WOLFSSL_LEAVE("wolfSSL_dtls_import_state_internal", BAD_FUNC_ARG);
  1150. return BAD_FUNC_ARG;
  1151. }
  1152. if (buf[idx++] != (byte)DTLS_EXPORT_STATE_PRO ||
  1153. (buf[idx] & 0xF0) != ((byte)DTLS_EXPORT_PRO & 0xF0)) {
  1154. WOLFSSL_MSG("Incorrect protocol");
  1155. return BAD_FUNC_ARG;
  1156. }
  1157. version = buf[idx++] & 0x0F;
  1158. ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
  1159. if (length > sz - DTLS_EXPORT_LEN) { /* subtract 2 for protocol */
  1160. WOLFSSL_MSG("Buffer size sanity check failed");
  1161. return BUFFER_E;
  1162. }
  1163. #ifdef WOLFSSL_SESSION_EXPORT_DEBUG
  1164. /* if compiled with debug options then print the version, protocol, size */
  1165. {
  1166. char debug[256];
  1167. XSNPRINTF(debug, sizeof(debug), "Importing DTLS session state\n"
  1168. "\tVersion : %d\n\tProtocol : %02X%01X\n\tLength of: %d\n\n"
  1169. , (int)version, buf[0], (buf[1] >> 4), length);
  1170. WOLFSSL_MSG(debug);
  1171. }
  1172. #endif /* WOLFSSL_SESSION_EXPORT_DEBUG */
  1173. /* perform sanity checks and extract Options information used */
  1174. switch (version) {
  1175. case DTLS_EXPORT_VERSION:
  1176. break;
  1177. default:
  1178. WOLFSSL_MSG("Bad export state version");
  1179. return BAD_FUNC_ARG;
  1180. }
  1181. /* perform sanity checks and extract Keys struct */
  1182. if (DTLS_EXPORT_LEN + idx > sz) {
  1183. WOLFSSL_MSG("Import Key struct error");
  1184. return BUFFER_E;
  1185. }
  1186. ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
  1187. if (length > DTLS_EXPORT_KEY_SZ || length + idx > sz) {
  1188. WOLFSSL_MSG("Import Key struct error");
  1189. return BUFFER_E;
  1190. }
  1191. if ((ret = ImportKeyState(ssl, buf + idx, length, version)) < 0) {
  1192. WOLFSSL_MSG("Import Key struct error");
  1193. WOLFSSL_LEAVE("wolfSSL_dtls_import_state_internal", ret);
  1194. return ret;
  1195. }
  1196. idx += ret;
  1197. WOLFSSL_LEAVE("wolfSSL_dtls_import_state_internal", ret);
  1198. return ret;
  1199. }
  1200. /* On success return amount of buffer consumed */
  1201. int wolfSSL_dtls_import_internal(WOLFSSL* ssl, byte* buf, word32 sz)
  1202. {
  1203. word32 idx = 0;
  1204. word16 length = 0;
  1205. int version;
  1206. int ret;
  1207. int optSz;
  1208. WOLFSSL_ENTER("wolfSSL_dtls_import_internal");
  1209. /* check at least enough room for protocol and length */
  1210. if (sz < DTLS_EXPORT_LEN * 2 || ssl == NULL) {
  1211. return BAD_FUNC_ARG;
  1212. }
  1213. /* sanity check on protocol ID and size of buffer */
  1214. if (buf[idx++] != (byte)DTLS_EXPORT_PRO ||
  1215. (buf[idx] & 0xF0) != ((byte)DTLS_EXPORT_PRO & 0xF0)) {
  1216. /* don't increment on second idx to next get version */
  1217. /* check if importing state only */
  1218. return wolfSSL_dtls_import_state_internal(ssl, buf, sz);
  1219. }
  1220. version = buf[idx++] & 0x0F;
  1221. ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
  1222. if (length > sz - DTLS_EXPORT_LEN) { /* subtract 2 for protocol */
  1223. return BUFFER_E;
  1224. }
  1225. /* if compiled with debug options then print the version, protocol, size */
  1226. #ifdef WOLFSSL_SESSION_EXPORT_DEBUG
  1227. {
  1228. char debug[256];
  1229. XSNPRINTF(debug, sizeof(debug), "Importing DTLS session\n"
  1230. "\tVersion : %d\n\tProtocol : %02X%01X\n\tLength of: %d\n\n"
  1231. , (int)version, buf[0], (buf[1] >> 4), length);
  1232. WOLFSSL_MSG(debug);
  1233. }
  1234. #endif /* WOLFSSL_SESSION_EXPORT_DEBUG */
  1235. /* perform sanity checks and extract Options information used */
  1236. switch (version) {
  1237. case DTLS_EXPORT_VERSION:
  1238. optSz = DTLS_EXPORT_OPT_SZ;
  1239. break;
  1240. case DTLS_EXPORT_VERSION_3:
  1241. WOLFSSL_MSG("Importing older version 3");
  1242. optSz = DTLS_EXPORT_OPT_SZ_3;
  1243. break;
  1244. default:
  1245. WOLFSSL_MSG("Bad export version");
  1246. return BAD_FUNC_ARG;
  1247. }
  1248. if (DTLS_EXPORT_LEN + optSz + idx > sz) {
  1249. WOLFSSL_MSG("Import Options struct error");
  1250. return BUFFER_E;
  1251. }
  1252. ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
  1253. if (length != optSz) {
  1254. WOLFSSL_MSG("Import Options struct error");
  1255. return BUFFER_E;
  1256. }
  1257. if ((ret = dtls_export_load(ssl, buf + idx, length, version)) < 0) {
  1258. WOLFSSL_MSG("Import Options struct error");
  1259. return ret;
  1260. }
  1261. idx += length;
  1262. /* perform sanity checks and extract Keys struct */
  1263. if (DTLS_EXPORT_LEN + idx > sz) {
  1264. WOLFSSL_MSG("Import Key struct error");
  1265. return BUFFER_E;
  1266. }
  1267. ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
  1268. if (length > DTLS_EXPORT_KEY_SZ || length + idx > sz) {
  1269. WOLFSSL_MSG("Import Key struct error");
  1270. return BUFFER_E;
  1271. }
  1272. if ((ret = ImportKeyState(ssl, buf + idx, length, version)) < 0) {
  1273. WOLFSSL_MSG("Import Key struct error");
  1274. return ret;
  1275. }
  1276. idx += ret;
  1277. /* perform sanity checks and extract CipherSpecs struct */
  1278. if (DTLS_EXPORT_LEN + DTLS_EXPORT_SPC_SZ + idx > sz) {
  1279. WOLFSSL_MSG("Import CipherSpecs struct error");
  1280. return BUFFER_E;
  1281. }
  1282. ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
  1283. if ( length != DTLS_EXPORT_SPC_SZ) {
  1284. WOLFSSL_MSG("Import CipherSpecs struct error");
  1285. return BUFFER_E;
  1286. }
  1287. if ((ret = ImportCipherSpecState(ssl, buf + idx, length, version)) < 0) {
  1288. WOLFSSL_MSG("Import CipherSpecs struct error");
  1289. return ret;
  1290. }
  1291. idx += ret;
  1292. /* perform sanity checks and extract DTLS peer info */
  1293. if (DTLS_EXPORT_LEN + idx > sz) {
  1294. WOLFSSL_MSG("Import DTLS peer info error");
  1295. return BUFFER_E;
  1296. }
  1297. ato16(buf + idx, &length); idx += DTLS_EXPORT_LEN;
  1298. if (idx + length > sz) {
  1299. WOLFSSL_MSG("Import DTLS peer info error");
  1300. return BUFFER_E;
  1301. }
  1302. if ((ret = ImportPeerInfo(ssl, buf + idx, length, version)) < 0) {
  1303. WOLFSSL_MSG("Import Peer Addr error");
  1304. return ret;
  1305. }
  1306. idx += ret;
  1307. SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE);
  1308. /* set hmac function to use when verifying */
  1309. if (ssl->options.tls == 1 || ssl->options.tls1_1 == 1 ||
  1310. ssl->options.dtls == 1) {
  1311. ssl->hmac = TLS_hmac;
  1312. }
  1313. /* make sure is a valid suite used */
  1314. if (wolfSSL_get_cipher(ssl) == NULL) {
  1315. WOLFSSL_MSG("Can not match cipher suite imported");
  1316. return MATCH_SUITE_ERROR;
  1317. }
  1318. /* do not allow stream ciphers with DTLS, except for NULL cipher */
  1319. if (ssl->specs.cipher_type == stream &&
  1320. ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) {
  1321. WOLFSSL_MSG("Can not import stream ciphers for DTLS");
  1322. return SANITY_CIPHER_E;
  1323. }
  1324. return idx;
  1325. }
  1326. #endif /* WOLFSSL_DTLS */
  1327. #endif /* WOLFSSL_SESSION_EXPORT */
  1328. void InitSSL_Method(WOLFSSL_METHOD* method, ProtocolVersion pv)
  1329. {
  1330. method->version = pv;
  1331. method->side = WOLFSSL_CLIENT_END;
  1332. method->downgrade = 0;
  1333. }
  1334. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
  1335. int InitSSL_Side(WOLFSSL* ssl, word16 side)
  1336. {
  1337. if (ssl == NULL)
  1338. return BAD_FUNC_ARG;
  1339. /* set side */
  1340. ssl->options.side = side;
  1341. /* reset options that are side specific */
  1342. #ifdef HAVE_NTRU
  1343. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  1344. ssl->options.haveNTRU = 1; /* always on client side */
  1345. /* server can turn on by loading key */
  1346. }
  1347. #endif
  1348. #ifdef HAVE_ECC
  1349. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  1350. ssl->options.haveECDSAsig = 1; /* always on client side */
  1351. ssl->options.haveECC = 1; /* server turns on with ECC key cert */
  1352. ssl->options.haveStaticECC = 1; /* server can turn on by loading key */
  1353. }
  1354. #elif defined(HAVE_ED25519) || defined(HAVE_ED448)
  1355. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  1356. ssl->options.haveECDSAsig = 1; /* always on client side */
  1357. ssl->options.haveECC = 1; /* server turns on with ECC key cert */
  1358. }
  1359. #endif
  1360. #if defined(HAVE_EXTENDED_MASTER) && !defined(NO_WOLFSSL_CLIENT)
  1361. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  1362. if ((ssl->ctx->method->version.major == SSLv3_MAJOR) &&
  1363. (ssl->ctx->method->version.minor >= TLSv1_MINOR)) {
  1364. ssl->options.haveEMS = 1;
  1365. }
  1366. #ifdef WOLFSSL_DTLS
  1367. if (ssl->ctx->method->version.major == DTLS_MAJOR)
  1368. ssl->options.haveEMS = 1;
  1369. #endif /* WOLFSSL_DTLS */
  1370. }
  1371. #endif /* HAVE_EXTENDED_MASTER && !NO_WOLFSSL_CLIENT */
  1372. #if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
  1373. if (ssl->options.dtls && ssl->options.side == WOLFSSL_SERVER_END) {
  1374. int ret;
  1375. ret = wolfSSL_DTLS_SetCookieSecret(ssl, NULL, 0);
  1376. if (ret != 0) {
  1377. WOLFSSL_MSG("DTLS Cookie Secret error");
  1378. return ret;
  1379. }
  1380. }
  1381. #endif /* WOLFSSL_DTLS && !NO_WOLFSSL_SERVER */
  1382. return InitSSL_Suites(ssl);
  1383. }
  1384. #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
  1385. /* Initialize SSL context, return 0 on success */
  1386. int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap)
  1387. {
  1388. int ret = 0;
  1389. XMEMSET(ctx, 0, sizeof(WOLFSSL_CTX));
  1390. ctx->method = method;
  1391. ctx->refCount = 1; /* so either CTX_free or SSL_free can release */
  1392. ctx->heap = ctx; /* defaults to self */
  1393. ctx->timeout = WOLFSSL_SESSION_TIMEOUT;
  1394. ctx->minDowngrade = WOLFSSL_MIN_DOWNGRADE; /* current default: TLSv1_MINOR */
  1395. if (wc_InitMutex(&ctx->countMutex) < 0) {
  1396. WOLFSSL_MSG("Mutex error on CTX init");
  1397. ctx->err = CTX_INIT_MUTEX_E;
  1398. return BAD_MUTEX_E;
  1399. }
  1400. #ifndef NO_DH
  1401. ctx->minDhKeySz = MIN_DHKEY_SZ;
  1402. ctx->maxDhKeySz = MAX_DHKEY_SZ;
  1403. #endif
  1404. #ifndef NO_RSA
  1405. ctx->minRsaKeySz = MIN_RSAKEY_SZ;
  1406. #endif
  1407. #ifdef HAVE_ECC
  1408. ctx->minEccKeySz = MIN_ECCKEY_SZ;
  1409. ctx->eccTempKeySz = ECDHE_SIZE;
  1410. #endif
  1411. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  1412. ctx->verifyDepth = MAX_CHAIN_DEPTH;
  1413. #endif
  1414. #ifdef OPENSSL_EXTRA
  1415. ctx->cbioFlag = WOLFSSL_CBIO_NONE;
  1416. #endif
  1417. #ifndef WOLFSSL_USER_IO
  1418. #ifdef MICRIUM
  1419. ctx->CBIORecv = MicriumReceive;
  1420. ctx->CBIOSend = MicriumSend;
  1421. #ifdef WOLFSSL_DTLS
  1422. if (method->version.major == DTLS_MAJOR) {
  1423. ctx->CBIORecv = MicriumReceiveFrom;
  1424. ctx->CBIOSend = MicriumSendTo;
  1425. }
  1426. #ifdef WOLFSSL_SESSION_EXPORT
  1427. #error Micrium port does not support DTLS session export yet
  1428. #endif
  1429. #endif
  1430. #elif defined WOLFSSL_UIP
  1431. ctx->CBIORecv = uIPReceive;
  1432. ctx->CBIOSend = uIPSend;
  1433. #ifdef WOLFSSL_DTLS
  1434. if (method->version.major == DTLS_MAJOR) {
  1435. ctx->CBIOSendTo = uIPSendTo;
  1436. ctx->CBIORecvFrom = uIPRecvFrom;
  1437. }
  1438. #endif
  1439. #else
  1440. ctx->CBIORecv = EmbedReceive;
  1441. ctx->CBIOSend = EmbedSend;
  1442. #ifdef WOLFSSL_DTLS
  1443. if (method->version.major == DTLS_MAJOR) {
  1444. ctx->CBIORecv = EmbedReceiveFrom;
  1445. ctx->CBIOSend = EmbedSendTo;
  1446. }
  1447. #ifdef WOLFSSL_SESSION_EXPORT
  1448. ctx->CBGetPeer = EmbedGetPeer;
  1449. ctx->CBSetPeer = EmbedSetPeer;
  1450. #endif
  1451. #endif
  1452. #endif /* MICRIUM */
  1453. #endif /* WOLFSSL_USER_IO */
  1454. #ifdef HAVE_NETX
  1455. ctx->CBIORecv = NetX_Receive;
  1456. ctx->CBIOSend = NetX_Send;
  1457. #elif defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
  1458. ctx->CBIORecv = Mynewt_Receive;
  1459. ctx->CBIOSend = Mynewt_Send;
  1460. #elif defined(WOLFSSL_GNRC)
  1461. ctx->CBIORecv = GNRC_ReceiveFrom;
  1462. ctx->CBIOSend = GNRC_SendTo;
  1463. #endif
  1464. #ifdef HAVE_NTRU
  1465. if (method->side == WOLFSSL_CLIENT_END)
  1466. ctx->haveNTRU = 1; /* always on client side */
  1467. /* server can turn on by loading key */
  1468. #endif
  1469. #ifdef HAVE_ECC
  1470. if (method->side == WOLFSSL_CLIENT_END) {
  1471. ctx->haveECDSAsig = 1; /* always on client side */
  1472. ctx->haveECC = 1; /* server turns on with ECC key cert */
  1473. ctx->haveStaticECC = 1; /* server can turn on by loading key */
  1474. }
  1475. #elif defined(HAVE_ED25519) || defined(HAVE_ED448)
  1476. if (method->side == WOLFSSL_CLIENT_END) {
  1477. ctx->haveECDSAsig = 1; /* always on client side */
  1478. ctx->haveECC = 1; /* server turns on with ECC key cert */
  1479. }
  1480. #endif
  1481. ctx->devId = INVALID_DEVID;
  1482. #if defined(WOLFSSL_DTLS)
  1483. #ifdef WOLFSSL_SCTP
  1484. ctx->dtlsMtuSz = MAX_RECORD_SIZE;
  1485. #elif defined(WOLFSSL_DTLS_MTU)
  1486. ctx->dtlsMtuSz = MAX_MTU;
  1487. #endif
  1488. #endif
  1489. #ifndef NO_CERTS
  1490. ctx->cm = wolfSSL_CertManagerNew_ex(heap);
  1491. if (ctx->cm == NULL) {
  1492. WOLFSSL_MSG("Bad Cert Manager New");
  1493. return BAD_CERT_MANAGER_ERROR;
  1494. }
  1495. #ifdef OPENSSL_EXTRA
  1496. /* setup WOLFSSL_X509_STORE */
  1497. ctx->x509_store.cm = ctx->cm;
  1498. #endif
  1499. #endif
  1500. #if defined(HAVE_EXTENDED_MASTER) && !defined(NO_WOLFSSL_CLIENT)
  1501. if (method->side == WOLFSSL_CLIENT_END) {
  1502. if ((method->version.major == SSLv3_MAJOR) &&
  1503. (method->version.minor >= TLSv1_MINOR)) {
  1504. ctx->haveEMS = 1;
  1505. }
  1506. #ifdef WOLFSSL_DTLS
  1507. if (method->version.major == DTLS_MAJOR)
  1508. ctx->haveEMS = 1;
  1509. #endif /* WOLFSSL_DTLS */
  1510. }
  1511. #endif /* HAVE_EXTENDED_MASTER && !NO_WOLFSSL_CLIENT */
  1512. #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
  1513. ctx->ticketHint = SESSION_TICKET_HINT_DEFAULT;
  1514. #endif
  1515. #ifdef HAVE_WOLF_EVENT
  1516. ret = wolfEventQueue_Init(&ctx->event_queue);
  1517. #endif /* HAVE_WOLF_EVENT */
  1518. #ifdef WOLFSSL_EARLY_DATA
  1519. ctx->maxEarlyDataSz = MAX_EARLY_DATA_SZ;
  1520. #endif
  1521. ctx->heap = heap; /* wolfSSL_CTX_load_static_memory sets */
  1522. ctx->verifyDepth = MAX_CHAIN_DEPTH;
  1523. return ret;
  1524. }
  1525. /* In case contexts are held in array and don't want to free actual ctx */
  1526. void SSL_CtxResourceFree(WOLFSSL_CTX* ctx)
  1527. {
  1528. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) && \
  1529. defined(HAVE_TLS_EXTENSIONS) && !defined(NO_WOLFSSL_SERVER)
  1530. int i;
  1531. #endif
  1532. #ifdef HAVE_WOLF_EVENT
  1533. wolfEventQueue_Free(&ctx->event_queue);
  1534. #endif /* HAVE_WOLF_EVENT */
  1535. #ifdef WOLFSSL_STATIC_MEMORY
  1536. if (ctx->onHeap == 1) {
  1537. XFREE(ctx->method, ctx->heap, DYNAMIC_TYPE_METHOD);
  1538. }
  1539. else {
  1540. XFREE(ctx->method, NULL, DYNAMIC_TYPE_METHOD);
  1541. }
  1542. #else
  1543. XFREE(ctx->method, ctx->heap, DYNAMIC_TYPE_METHOD);
  1544. #endif
  1545. ctx->method = NULL;
  1546. if (ctx->suites) {
  1547. XFREE(ctx->suites, ctx->heap, DYNAMIC_TYPE_SUITES);
  1548. ctx->suites = NULL;
  1549. }
  1550. #ifndef NO_DH
  1551. XFREE(ctx->serverDH_G.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  1552. ctx->serverDH_G.buffer = NULL;
  1553. XFREE(ctx->serverDH_P.buffer, ctx->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  1554. ctx->serverDH_P.buffer = NULL;
  1555. #endif /* !NO_DH */
  1556. #ifdef SINGLE_THREADED
  1557. if (ctx->rng) {
  1558. wc_FreeRng(ctx->rng);
  1559. XFREE(ctx->rng, ctx->heap, DYNAMIC_TYPE_RNG);
  1560. ctx->rng = NULL;
  1561. }
  1562. #endif /* SINGLE_THREADED */
  1563. #ifndef NO_CERTS
  1564. FreeDer(&ctx->privateKey);
  1565. FreeDer(&ctx->certificate);
  1566. #ifdef KEEP_OUR_CERT
  1567. if (ctx->ourCert && ctx->ownOurCert) {
  1568. FreeX509(ctx->ourCert);
  1569. XFREE(ctx->ourCert, ctx->heap, DYNAMIC_TYPE_X509);
  1570. ctx->ourCert = NULL;
  1571. }
  1572. #endif /* KEEP_OUR_CERT */
  1573. FreeDer(&ctx->certChain);
  1574. wolfSSL_CertManagerFree(ctx->cm);
  1575. ctx->cm = NULL;
  1576. #ifdef OPENSSL_EXTRA
  1577. /* ctx->cm was free'd so cm of x509 store should now be NULL */
  1578. if (ctx->x509_store_pt != NULL) {
  1579. ctx->x509_store_pt->cm = NULL;
  1580. }
  1581. wolfSSL_X509_STORE_free(ctx->x509_store_pt);
  1582. while (ctx->ca_names != NULL) {
  1583. WOLFSSL_STACK *next = ctx->ca_names->next;
  1584. wolfSSL_X509_NAME_free(ctx->ca_names->data.name);
  1585. XFREE(ctx->ca_names, NULL, DYNAMIC_TYPE_OPENSSL);
  1586. ctx->ca_names = next;
  1587. }
  1588. #endif
  1589. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  1590. while (ctx->x509Chain != NULL) {
  1591. WOLFSSL_STACK *next = ctx->x509Chain->next;
  1592. wolfSSL_X509_free(ctx->x509Chain->data.x509);
  1593. XFREE(ctx->x509Chain, NULL, DYNAMIC_TYPE_OPENSSL);
  1594. ctx->x509Chain = next;
  1595. }
  1596. #endif
  1597. #endif /* !NO_CERTS */
  1598. #ifdef HAVE_TLS_EXTENSIONS
  1599. TLSX_FreeAll(ctx->extensions, ctx->heap);
  1600. #ifndef NO_WOLFSSL_SERVER
  1601. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  1602. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  1603. if (ctx->certOcspRequest) {
  1604. FreeOcspRequest(ctx->certOcspRequest);
  1605. XFREE(ctx->certOcspRequest, ctx->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  1606. }
  1607. #endif
  1608. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  1609. for (i = 0; i < MAX_CHAIN_DEPTH; i++) {
  1610. if (ctx->chainOcspRequest[i]) {
  1611. FreeOcspRequest(ctx->chainOcspRequest[i]);
  1612. XFREE(ctx->chainOcspRequest[i], ctx->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  1613. ctx->chainOcspRequest[i] = NULL;
  1614. }
  1615. }
  1616. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  1617. #endif /* !NO_WOLFSSL_SERVER */
  1618. #endif /* HAVE_TLS_EXTENSIONS */
  1619. #ifdef OPENSSL_EXTRA
  1620. if(ctx->alpn_cli_protos) {
  1621. XFREE((void *)ctx->alpn_cli_protos, NULL, DYNAMIC_TYPE_OPENSSL);
  1622. ctx->alpn_cli_protos = NULL;
  1623. }
  1624. #endif
  1625. #ifdef WOLFSSL_STATIC_MEMORY
  1626. if (ctx->heap != NULL) {
  1627. #ifdef WOLFSSL_HEAP_TEST
  1628. /* avoid dereferencing a test value */
  1629. if (ctx->heap != (void*)WOLFSSL_HEAP_TEST)
  1630. #endif
  1631. {
  1632. WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)(ctx->heap);
  1633. wc_FreeMutex(&((WOLFSSL_HEAP*)(hint->memory))->memory_mutex);
  1634. }
  1635. }
  1636. #endif /* WOLFSSL_STATIC_MEMORY */
  1637. }
  1638. void FreeSSL_Ctx(WOLFSSL_CTX* ctx)
  1639. {
  1640. int refCount;
  1641. /* decrement CTX reference count */
  1642. if ((refCount = SSL_CTX_RefCount(ctx, -1)) < 0) {
  1643. /* check error state, if mutex error code then mutex init failed but
  1644. * CTX was still malloc'd */
  1645. if (ctx->err == CTX_INIT_MUTEX_E) {
  1646. SSL_CtxResourceFree(ctx);
  1647. XFREE(ctx, ctx->heap, DYNAMIC_TYPE_CTX);
  1648. }
  1649. return;
  1650. }
  1651. if (refCount == 0) {
  1652. void* heap = ctx->heap;
  1653. WOLFSSL_MSG("CTX ref count down to 0, doing full free");
  1654. SSL_CtxResourceFree(ctx);
  1655. wc_FreeMutex(&ctx->countMutex);
  1656. #ifdef WOLFSSL_STATIC_MEMORY
  1657. if (ctx->onHeap == 0) {
  1658. heap = NULL;
  1659. }
  1660. #endif
  1661. XFREE(ctx, heap, DYNAMIC_TYPE_CTX);
  1662. (void)heap; /* not used in some builds */
  1663. }
  1664. else {
  1665. (void)ctx;
  1666. WOLFSSL_MSG("CTX ref count not 0 yet, no free");
  1667. }
  1668. }
  1669. /* Set cipher pointers to null */
  1670. void InitCiphers(WOLFSSL* ssl)
  1671. {
  1672. #ifdef BUILD_ARC4
  1673. ssl->encrypt.arc4 = NULL;
  1674. ssl->decrypt.arc4 = NULL;
  1675. #endif
  1676. #ifdef BUILD_DES3
  1677. ssl->encrypt.des3 = NULL;
  1678. ssl->decrypt.des3 = NULL;
  1679. #endif
  1680. #ifdef BUILD_AES
  1681. ssl->encrypt.aes = NULL;
  1682. ssl->decrypt.aes = NULL;
  1683. #endif
  1684. #ifdef HAVE_CAMELLIA
  1685. ssl->encrypt.cam = NULL;
  1686. ssl->decrypt.cam = NULL;
  1687. #endif
  1688. #ifdef HAVE_HC128
  1689. ssl->encrypt.hc128 = NULL;
  1690. ssl->decrypt.hc128 = NULL;
  1691. #endif
  1692. #ifdef BUILD_RABBIT
  1693. ssl->encrypt.rabbit = NULL;
  1694. ssl->decrypt.rabbit = NULL;
  1695. #endif
  1696. #ifdef HAVE_CHACHA
  1697. ssl->encrypt.chacha = NULL;
  1698. ssl->decrypt.chacha = NULL;
  1699. #endif
  1700. #if defined(HAVE_POLY1305) && defined(HAVE_ONE_TIME_AUTH)
  1701. ssl->auth.poly1305 = NULL;
  1702. #endif
  1703. ssl->encrypt.setup = 0;
  1704. ssl->decrypt.setup = 0;
  1705. #ifdef HAVE_ONE_TIME_AUTH
  1706. ssl->auth.setup = 0;
  1707. #endif
  1708. #ifdef HAVE_IDEA
  1709. ssl->encrypt.idea = NULL;
  1710. ssl->decrypt.idea = NULL;
  1711. #endif
  1712. }
  1713. /* Free ciphers */
  1714. void FreeCiphers(WOLFSSL* ssl)
  1715. {
  1716. (void)ssl;
  1717. #ifdef BUILD_ARC4
  1718. wc_Arc4Free(ssl->encrypt.arc4);
  1719. wc_Arc4Free(ssl->decrypt.arc4);
  1720. XFREE(ssl->encrypt.arc4, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1721. XFREE(ssl->decrypt.arc4, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1722. #endif
  1723. #ifdef BUILD_DES3
  1724. wc_Des3Free(ssl->encrypt.des3);
  1725. wc_Des3Free(ssl->decrypt.des3);
  1726. XFREE(ssl->encrypt.des3, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1727. XFREE(ssl->decrypt.des3, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1728. #endif
  1729. #if defined(BUILD_AES) || defined(BUILD_AESGCM) /* See: InitKeys() in keys.c
  1730. * on addition of BUILD_AESGCM
  1731. * check (enc->aes, dec->aes) */
  1732. wc_AesFree(ssl->encrypt.aes);
  1733. wc_AesFree(ssl->decrypt.aes);
  1734. #if (defined(BUILD_AESGCM) || defined(HAVE_AESCCM)) && \
  1735. !defined(WOLFSSL_NO_TLS12)
  1736. XFREE(ssl->decrypt.additional, ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  1737. XFREE(ssl->encrypt.additional, ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  1738. #endif
  1739. XFREE(ssl->encrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1740. XFREE(ssl->decrypt.aes, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1741. #endif
  1742. #ifdef CIPHER_NONCE
  1743. XFREE(ssl->decrypt.nonce, ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  1744. XFREE(ssl->encrypt.nonce, ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  1745. #endif
  1746. #ifdef HAVE_CAMELLIA
  1747. XFREE(ssl->encrypt.cam, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1748. XFREE(ssl->decrypt.cam, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1749. #endif
  1750. #ifdef HAVE_HC128
  1751. XFREE(ssl->encrypt.hc128, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1752. XFREE(ssl->decrypt.hc128, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1753. #endif
  1754. #ifdef BUILD_RABBIT
  1755. XFREE(ssl->encrypt.rabbit, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1756. XFREE(ssl->decrypt.rabbit, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1757. #endif
  1758. #ifdef HAVE_CHACHA
  1759. XFREE(ssl->encrypt.chacha, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1760. XFREE(ssl->decrypt.chacha, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1761. #endif
  1762. #if defined(HAVE_POLY1305) && defined(HAVE_ONE_TIME_AUTH)
  1763. XFREE(ssl->auth.poly1305, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1764. #endif
  1765. #ifdef HAVE_IDEA
  1766. XFREE(ssl->encrypt.idea, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1767. XFREE(ssl->decrypt.idea, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1768. #endif
  1769. #if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER)
  1770. wc_HmacFree(ssl->encrypt.hmac);
  1771. wc_HmacFree(ssl->decrypt.hmac);
  1772. XFREE(ssl->encrypt.hmac, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1773. XFREE(ssl->decrypt.hmac, ssl->heap, DYNAMIC_TYPE_CIPHER);
  1774. #endif
  1775. }
  1776. void InitCipherSpecs(CipherSpecs* cs)
  1777. {
  1778. XMEMSET(cs, 0, sizeof(CipherSpecs));
  1779. cs->bulk_cipher_algorithm = INVALID_BYTE;
  1780. cs->cipher_type = INVALID_BYTE;
  1781. cs->mac_algorithm = INVALID_BYTE;
  1782. cs->kea = INVALID_BYTE;
  1783. cs->sig_algo = INVALID_BYTE;
  1784. }
  1785. #if defined(USE_ECDSA_KEYSZ_HASH_ALGO) || (defined(WOLFSSL_TLS13) && \
  1786. defined(HAVE_ECC))
  1787. static int GetMacDigestSize(byte macAlgo)
  1788. {
  1789. switch (macAlgo) {
  1790. #ifndef NO_SHA
  1791. case sha_mac:
  1792. return WC_SHA_DIGEST_SIZE;
  1793. #endif
  1794. #ifndef NO_SHA256
  1795. case sha256_mac:
  1796. return WC_SHA256_DIGEST_SIZE;
  1797. #endif
  1798. #ifdef WOLFSSL_SHA384
  1799. case sha384_mac:
  1800. return WC_SHA384_DIGEST_SIZE;
  1801. #endif
  1802. #ifdef WOLFSSL_SHA512
  1803. case sha512_mac:
  1804. return WC_SHA512_DIGEST_SIZE;
  1805. #endif
  1806. default:
  1807. break;
  1808. }
  1809. return NOT_COMPILED_IN;
  1810. }
  1811. #endif /* USE_ECDSA_KEYSZ_HASH_ALGO */
  1812. static WC_INLINE void AddSuiteHashSigAlgo(Suites* suites, byte macAlgo, byte sigAlgo,
  1813. int keySz, word16* inOutIdx)
  1814. {
  1815. int addSigAlgo = 1;
  1816. #ifdef USE_ECDSA_KEYSZ_HASH_ALGO
  1817. if (sigAlgo == ecc_dsa_sa_algo) {
  1818. int digestSz = GetMacDigestSize(macAlgo);
  1819. /* do not add sig/algos with digest size larger than key size */
  1820. if (digestSz <= 0 || (keySz > 0 && digestSz > keySz)) {
  1821. addSigAlgo = 0;
  1822. }
  1823. }
  1824. #else
  1825. (void)keySz;
  1826. #endif /* USE_ECDSA_KEYSZ_HASH_ALGO */
  1827. if (addSigAlgo) {
  1828. #ifdef WC_RSA_PSS
  1829. if (sigAlgo == rsa_pss_sa_algo) {
  1830. /* RSA PSS is sig then mac */
  1831. suites->hashSigAlgo[*inOutIdx] = sigAlgo;
  1832. *inOutIdx += 1;
  1833. suites->hashSigAlgo[*inOutIdx] = macAlgo;
  1834. *inOutIdx += 1;
  1835. #ifdef WOLFSSL_TLS13
  1836. /* Add the certificate algorithm as well */
  1837. suites->hashSigAlgo[*inOutIdx] = sigAlgo;
  1838. *inOutIdx += 1;
  1839. suites->hashSigAlgo[*inOutIdx] = PSS_RSAE_TO_PSS_PSS(macAlgo);
  1840. *inOutIdx += 1;
  1841. #endif
  1842. }
  1843. else
  1844. #endif
  1845. {
  1846. suites->hashSigAlgo[*inOutIdx] = macAlgo;
  1847. *inOutIdx += 1;
  1848. suites->hashSigAlgo[*inOutIdx] = sigAlgo;
  1849. *inOutIdx += 1;
  1850. }
  1851. }
  1852. }
  1853. void InitSuitesHashSigAlgo(Suites* suites, int haveECDSAsig, int haveRSAsig,
  1854. int haveAnon, int tls1_2, int keySz)
  1855. {
  1856. word16 idx = 0;
  1857. (void)tls1_2;
  1858. (void)keySz;
  1859. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  1860. if (haveECDSAsig) {
  1861. #ifdef HAVE_ECC
  1862. #ifdef WOLFSSL_SHA512
  1863. AddSuiteHashSigAlgo(suites, sha512_mac, ecc_dsa_sa_algo, keySz, &idx);
  1864. #endif
  1865. #ifdef WOLFSSL_SHA384
  1866. AddSuiteHashSigAlgo(suites, sha384_mac, ecc_dsa_sa_algo, keySz, &idx);
  1867. #endif
  1868. #ifndef NO_SHA256
  1869. AddSuiteHashSigAlgo(suites, sha256_mac, ecc_dsa_sa_algo, keySz, &idx);
  1870. #endif
  1871. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  1872. defined(WOLFSSL_ALLOW_TLS_SHA1))
  1873. AddSuiteHashSigAlgo(suites, sha_mac, ecc_dsa_sa_algo, keySz, &idx);
  1874. #endif
  1875. #endif
  1876. #ifdef HAVE_ED25519
  1877. AddSuiteHashSigAlgo(suites, ED25519_SA_MAJOR, ED25519_SA_MINOR, keySz,
  1878. &idx);
  1879. #endif
  1880. #ifdef HAVE_ED448
  1881. AddSuiteHashSigAlgo(suites, ED448_SA_MAJOR, ED448_SA_MINOR, keySz,
  1882. &idx);
  1883. #endif
  1884. }
  1885. #endif /* HAVE_ECC || HAVE_ED25519 || defined(HAVE_ED448 */
  1886. if (haveRSAsig) {
  1887. #ifdef WC_RSA_PSS
  1888. if (tls1_2) {
  1889. #ifdef WOLFSSL_SHA512
  1890. AddSuiteHashSigAlgo(suites, sha512_mac, rsa_pss_sa_algo, keySz,
  1891. &idx);
  1892. #endif
  1893. #ifdef WOLFSSL_SHA384
  1894. AddSuiteHashSigAlgo(suites, sha384_mac, rsa_pss_sa_algo, keySz,
  1895. &idx);
  1896. #endif
  1897. #ifndef NO_SHA256
  1898. AddSuiteHashSigAlgo(suites, sha256_mac, rsa_pss_sa_algo, keySz,
  1899. &idx);
  1900. #endif
  1901. }
  1902. #endif
  1903. #ifdef WOLFSSL_SHA512
  1904. AddSuiteHashSigAlgo(suites, sha512_mac, rsa_sa_algo, keySz, &idx);
  1905. #endif
  1906. #ifdef WOLFSSL_SHA384
  1907. AddSuiteHashSigAlgo(suites, sha384_mac, rsa_sa_algo, keySz, &idx);
  1908. #endif
  1909. #ifndef NO_SHA256
  1910. AddSuiteHashSigAlgo(suites, sha256_mac, rsa_sa_algo, keySz, &idx);
  1911. #endif
  1912. #ifdef WOLFSSL_SHA224
  1913. AddSuiteHashSigAlgo(suites, sha224_mac, rsa_sa_algo, keySz, &idx);
  1914. #endif
  1915. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  1916. defined(WOLFSSL_ALLOW_TLS_SHA1))
  1917. AddSuiteHashSigAlgo(suites, sha_mac, rsa_sa_algo, keySz, &idx);
  1918. #endif
  1919. }
  1920. #ifdef HAVE_ANON
  1921. if (haveAnon) {
  1922. AddSuiteHashSigAlgo(suites, sha_mac, anonymous_sa_algo, keySz, &idx);
  1923. }
  1924. #endif
  1925. (void)haveAnon;
  1926. (void)haveECDSAsig;
  1927. suites->hashSigAlgoSz = idx;
  1928. }
  1929. void InitSuites(Suites* suites, ProtocolVersion pv, int keySz, word16 haveRSA,
  1930. word16 havePSK, word16 haveDH, word16 haveNTRU,
  1931. word16 haveECDSAsig, word16 haveECC,
  1932. word16 haveStaticECC, int side)
  1933. {
  1934. word16 idx = 0;
  1935. int tls = pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_MINOR;
  1936. int tls1_2 = pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_2_MINOR;
  1937. #ifdef WOLFSSL_TLS13
  1938. int tls1_3 = IsAtLeastTLSv1_3(pv);
  1939. #endif
  1940. int dtls = 0;
  1941. int haveRSAsig = 1;
  1942. (void)tls; /* shut up compiler */
  1943. (void)tls1_2;
  1944. (void)dtls;
  1945. (void)haveDH;
  1946. (void)havePSK;
  1947. (void)haveNTRU;
  1948. (void)haveStaticECC;
  1949. (void)haveECC;
  1950. (void)side;
  1951. (void)haveRSA; /* some builds won't read */
  1952. (void)haveRSAsig; /* non ecc builds won't read */
  1953. if (suites == NULL) {
  1954. WOLFSSL_MSG("InitSuites pointer error");
  1955. return;
  1956. }
  1957. if (suites->setSuites)
  1958. return; /* trust user settings, don't override */
  1959. #ifdef WOLFSSL_TLS13
  1960. #ifdef BUILD_TLS_AES_128_GCM_SHA256
  1961. if (tls1_3) {
  1962. suites->suites[idx++] = TLS13_BYTE;
  1963. suites->suites[idx++] = TLS_AES_128_GCM_SHA256;
  1964. }
  1965. #endif
  1966. #ifdef BUILD_TLS_AES_256_GCM_SHA384
  1967. if (tls1_3) {
  1968. suites->suites[idx++] = TLS13_BYTE;
  1969. suites->suites[idx++] = TLS_AES_256_GCM_SHA384;
  1970. }
  1971. #endif
  1972. #ifdef BUILD_TLS_CHACHA20_POLY1305_SHA256
  1973. if (tls1_3) {
  1974. suites->suites[idx++] = TLS13_BYTE;
  1975. suites->suites[idx++] = TLS_CHACHA20_POLY1305_SHA256;
  1976. }
  1977. #endif
  1978. #ifdef BUILD_TLS_AES_128_CCM_SHA256
  1979. if (tls1_3) {
  1980. suites->suites[idx++] = TLS13_BYTE;
  1981. suites->suites[idx++] = TLS_AES_128_CCM_SHA256;
  1982. }
  1983. #endif
  1984. #ifdef BUILD_TLS_AES_128_CCM_8_SHA256
  1985. if (tls1_3) {
  1986. suites->suites[idx++] = TLS13_BYTE;
  1987. suites->suites[idx++] = TLS_AES_128_CCM_8_SHA256;
  1988. }
  1989. #endif
  1990. #ifdef HAVE_NULL_CIPHER
  1991. #ifdef BUILD_TLS_SHA256_SHA256
  1992. if (tls1_3) {
  1993. suites->suites[idx++] = ECC_BYTE;
  1994. suites->suites[idx++] = TLS_SHA256_SHA256;
  1995. }
  1996. #endif
  1997. #ifdef BUILD_TLS_SHA384_SHA384
  1998. if (tls1_3) {
  1999. suites->suites[idx++] = ECC_BYTE;
  2000. suites->suites[idx++] = TLS_SHA384_SHA384;
  2001. }
  2002. #endif
  2003. #endif
  2004. #endif /* WOLFSSL_TLS13 */
  2005. #ifndef WOLFSSL_NO_TLS12
  2006. #if !defined(NO_WOLFSSL_SERVER) && !defined(NO_RSA)
  2007. if (side == WOLFSSL_SERVER_END && haveStaticECC) {
  2008. haveRSA = 0; /* can't do RSA with ECDSA key */
  2009. }
  2010. if (side == WOLFSSL_SERVER_END && haveECDSAsig) {
  2011. haveRSAsig = 0; /* can't have RSA sig if signed by ECDSA */
  2012. }
  2013. #endif /* !NO_WOLFSSL_SERVER */
  2014. #ifdef WOLFSSL_DTLS
  2015. if (pv.major == DTLS_MAJOR) {
  2016. dtls = 1;
  2017. tls = 1;
  2018. /* May be dead assignments dependent upon configuration */
  2019. (void) dtls;
  2020. (void) tls;
  2021. tls1_2 = pv.minor <= DTLSv1_2_MINOR;
  2022. }
  2023. #endif
  2024. #ifdef HAVE_RENEGOTIATION_INDICATION
  2025. if (side == WOLFSSL_CLIENT_END) {
  2026. suites->suites[idx++] = CIPHER_BYTE;
  2027. suites->suites[idx++] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
  2028. }
  2029. #endif
  2030. #ifdef BUILD_TLS_QSH
  2031. if (tls) {
  2032. suites->suites[idx++] = QSH_BYTE;
  2033. suites->suites[idx++] = TLS_QSH;
  2034. }
  2035. #endif
  2036. #ifdef BUILD_TLS_NTRU_RSA_WITH_AES_256_CBC_SHA
  2037. if (tls && haveNTRU && haveRSA) {
  2038. suites->suites[idx++] = CIPHER_BYTE;
  2039. suites->suites[idx++] = TLS_NTRU_RSA_WITH_AES_256_CBC_SHA;
  2040. }
  2041. #endif
  2042. #ifdef BUILD_TLS_NTRU_RSA_WITH_AES_128_CBC_SHA
  2043. if (tls && haveNTRU && haveRSA) {
  2044. suites->suites[idx++] = CIPHER_BYTE;
  2045. suites->suites[idx++] = TLS_NTRU_RSA_WITH_AES_128_CBC_SHA;
  2046. }
  2047. #endif
  2048. #ifdef BUILD_TLS_NTRU_RSA_WITH_RC4_128_SHA
  2049. if (!dtls && tls && haveNTRU && haveRSA) {
  2050. suites->suites[idx++] = CIPHER_BYTE;
  2051. suites->suites[idx++] = TLS_NTRU_RSA_WITH_RC4_128_SHA;
  2052. }
  2053. #endif
  2054. #ifdef BUILD_TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA
  2055. if (tls && haveNTRU && haveRSA) {
  2056. suites->suites[idx++] = CIPHER_BYTE;
  2057. suites->suites[idx++] = TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA;
  2058. }
  2059. #endif
  2060. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
  2061. if (tls1_2 && haveECC) {
  2062. suites->suites[idx++] = ECC_BYTE;
  2063. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384;
  2064. }
  2065. #endif
  2066. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
  2067. if (tls1_2 && haveECC) {
  2068. suites->suites[idx++] = ECC_BYTE;
  2069. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256;
  2070. }
  2071. #endif
  2072. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
  2073. if (tls1_2 && haveRSA) {
  2074. suites->suites[idx++] = ECC_BYTE;
  2075. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384;
  2076. }
  2077. #endif
  2078. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  2079. if (tls1_2 && haveRSA) {
  2080. suites->suites[idx++] = ECC_BYTE;
  2081. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256;
  2082. }
  2083. #endif
  2084. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
  2085. if (tls1_2 && haveDH && haveRSA) {
  2086. suites->suites[idx++] = CIPHER_BYTE;
  2087. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_GCM_SHA384;
  2088. }
  2089. #endif
  2090. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
  2091. if (tls1_2 && haveDH && haveRSA) {
  2092. suites->suites[idx++] = CIPHER_BYTE;
  2093. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_128_GCM_SHA256;
  2094. }
  2095. #endif
  2096. #ifdef BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384
  2097. if (tls1_2 && haveRSA) {
  2098. suites->suites[idx++] = CIPHER_BYTE;
  2099. suites->suites[idx++] = TLS_RSA_WITH_AES_256_GCM_SHA384;
  2100. }
  2101. #endif
  2102. #ifdef BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256
  2103. if (tls1_2 && haveRSA) {
  2104. suites->suites[idx++] = CIPHER_BYTE;
  2105. suites->suites[idx++] = TLS_RSA_WITH_AES_128_GCM_SHA256;
  2106. }
  2107. #endif
  2108. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
  2109. if (tls1_2 && haveECC && haveStaticECC) {
  2110. suites->suites[idx++] = ECC_BYTE;
  2111. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384;
  2112. }
  2113. #endif
  2114. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
  2115. if (tls1_2 && haveECC && haveStaticECC) {
  2116. suites->suites[idx++] = ECC_BYTE;
  2117. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256;
  2118. }
  2119. #endif
  2120. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
  2121. if (tls1_2 && haveRSAsig && haveStaticECC) {
  2122. suites->suites[idx++] = ECC_BYTE;
  2123. suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384;
  2124. }
  2125. #endif
  2126. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
  2127. if (tls1_2 && haveRSAsig && haveStaticECC) {
  2128. suites->suites[idx++] = ECC_BYTE;
  2129. suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256;
  2130. }
  2131. #endif
  2132. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
  2133. if (tls1_2 && haveDH && havePSK) {
  2134. suites->suites[idx++] = CIPHER_BYTE;
  2135. suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_256_GCM_SHA384;
  2136. }
  2137. #endif
  2138. #ifdef BUILD_TLS_DH_anon_WITH_AES_128_CBC_SHA
  2139. if (tls1_2 && haveDH) {
  2140. suites->suites[idx++] = CIPHER_BYTE;
  2141. suites->suites[idx++] = TLS_DH_anon_WITH_AES_128_CBC_SHA;
  2142. }
  2143. #endif
  2144. #ifdef BUILD_TLS_DH_anon_WITH_AES_256_GCM_SHA384
  2145. if (tls1_2 && haveDH) {
  2146. suites->suites[idx++] = CIPHER_BYTE;
  2147. suites->suites[idx++] = TLS_DH_anon_WITH_AES_256_GCM_SHA384;
  2148. }
  2149. #endif
  2150. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
  2151. if (tls1_2 && haveDH && havePSK) {
  2152. suites->suites[idx++] = CIPHER_BYTE;
  2153. suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_128_GCM_SHA256;
  2154. }
  2155. #endif
  2156. #ifdef BUILD_TLS_PSK_WITH_AES_256_GCM_SHA384
  2157. if (tls1_2 && havePSK) {
  2158. suites->suites[idx++] = CIPHER_BYTE;
  2159. suites->suites[idx++] = TLS_PSK_WITH_AES_256_GCM_SHA384;
  2160. }
  2161. #endif
  2162. #ifdef BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256
  2163. if (tls1_2 && havePSK) {
  2164. suites->suites[idx++] = CIPHER_BYTE;
  2165. suites->suites[idx++] = TLS_PSK_WITH_AES_128_GCM_SHA256;
  2166. }
  2167. #endif
  2168. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
  2169. if (tls1_2 && haveECC) {
  2170. suites->suites[idx++] = CHACHA_BYTE;
  2171. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256;
  2172. }
  2173. #endif
  2174. #ifdef BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
  2175. if (tls1_2 && haveRSA) {
  2176. suites->suites[idx++] = CHACHA_BYTE;
  2177. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256;
  2178. }
  2179. #endif
  2180. #ifdef BUILD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
  2181. if (tls1_2 && haveRSA) {
  2182. suites->suites[idx++] = CHACHA_BYTE;
  2183. suites->suites[idx++] = TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256;
  2184. }
  2185. #endif
  2186. /* Place as higher priority for MYSQL */
  2187. #if defined(WOLFSSL_MYSQL_COMPATIBLE)
  2188. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
  2189. if (tls && haveDH && haveRSA) {
  2190. suites->suites[idx++] = CIPHER_BYTE;
  2191. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA;
  2192. }
  2193. #endif
  2194. #endif
  2195. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
  2196. if (tls1_2 && haveRSA) {
  2197. suites->suites[idx++] = ECC_BYTE;
  2198. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256;
  2199. }
  2200. #endif
  2201. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
  2202. if (tls1_2 && haveECC) {
  2203. suites->suites[idx++] = ECC_BYTE;
  2204. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256;
  2205. }
  2206. #endif
  2207. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
  2208. if (tls1_2 && haveRSAsig && haveStaticECC) {
  2209. suites->suites[idx++] = ECC_BYTE;
  2210. suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256;
  2211. }
  2212. #endif
  2213. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
  2214. if (tls1_2 && haveECC && haveStaticECC) {
  2215. suites->suites[idx++] = ECC_BYTE;
  2216. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256;
  2217. }
  2218. #endif
  2219. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
  2220. if (tls1_2 && haveRSA) {
  2221. suites->suites[idx++] = ECC_BYTE;
  2222. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384;
  2223. }
  2224. #endif
  2225. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
  2226. if (tls1_2 && haveECC) {
  2227. suites->suites[idx++] = ECC_BYTE;
  2228. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384;
  2229. }
  2230. #endif
  2231. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
  2232. if (tls1_2 && haveRSAsig && haveStaticECC) {
  2233. suites->suites[idx++] = ECC_BYTE;
  2234. suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384;
  2235. }
  2236. #endif
  2237. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
  2238. if (tls1_2 && haveECC && haveStaticECC) {
  2239. suites->suites[idx++] = ECC_BYTE;
  2240. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384;
  2241. }
  2242. #endif
  2243. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
  2244. if (tls && haveECC) {
  2245. suites->suites[idx++] = ECC_BYTE;
  2246. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA;
  2247. }
  2248. #endif
  2249. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
  2250. if (tls && haveECC && haveStaticECC) {
  2251. suites->suites[idx++] = ECC_BYTE;
  2252. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA;
  2253. }
  2254. #endif
  2255. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
  2256. if (tls && haveECC) {
  2257. suites->suites[idx++] = ECC_BYTE;
  2258. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA;
  2259. }
  2260. #endif
  2261. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
  2262. if (tls && haveECC && haveStaticECC) {
  2263. suites->suites[idx++] = ECC_BYTE;
  2264. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA;
  2265. }
  2266. #endif
  2267. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
  2268. if (!dtls && tls && haveECC) {
  2269. suites->suites[idx++] = ECC_BYTE;
  2270. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_RC4_128_SHA;
  2271. }
  2272. #endif
  2273. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA
  2274. if (!dtls && tls && haveECC && haveStaticECC) {
  2275. suites->suites[idx++] = ECC_BYTE;
  2276. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_RC4_128_SHA;
  2277. }
  2278. #endif
  2279. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
  2280. if (tls && haveECC) {
  2281. suites->suites[idx++] = ECC_BYTE;
  2282. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA;
  2283. }
  2284. #endif
  2285. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
  2286. if (tls && haveECC && haveStaticECC) {
  2287. suites->suites[idx++] = ECC_BYTE;
  2288. suites->suites[idx++] = TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA;
  2289. }
  2290. #endif
  2291. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
  2292. if (tls && haveRSA) {
  2293. suites->suites[idx++] = ECC_BYTE;
  2294. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA;
  2295. }
  2296. #endif
  2297. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
  2298. if (tls && haveRSAsig && haveStaticECC) {
  2299. suites->suites[idx++] = ECC_BYTE;
  2300. suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_256_CBC_SHA;
  2301. }
  2302. #endif
  2303. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
  2304. if (tls && haveRSA) {
  2305. suites->suites[idx++] = ECC_BYTE;
  2306. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA;
  2307. }
  2308. #endif
  2309. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
  2310. if (tls && haveRSAsig && haveStaticECC) {
  2311. suites->suites[idx++] = ECC_BYTE;
  2312. suites->suites[idx++] = TLS_ECDH_RSA_WITH_AES_128_CBC_SHA;
  2313. }
  2314. #endif
  2315. #ifdef BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA
  2316. if (!dtls && tls && haveRSA) {
  2317. suites->suites[idx++] = ECC_BYTE;
  2318. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_RC4_128_SHA;
  2319. }
  2320. #endif
  2321. #ifdef BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA
  2322. if (!dtls && tls && haveRSAsig && haveStaticECC) {
  2323. suites->suites[idx++] = ECC_BYTE;
  2324. suites->suites[idx++] = TLS_ECDH_RSA_WITH_RC4_128_SHA;
  2325. }
  2326. #endif
  2327. #ifdef BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
  2328. if (tls && haveRSA) {
  2329. suites->suites[idx++] = ECC_BYTE;
  2330. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA;
  2331. }
  2332. #endif
  2333. #ifdef BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
  2334. if (tls && haveRSAsig && haveStaticECC) {
  2335. suites->suites[idx++] = ECC_BYTE;
  2336. suites->suites[idx++] = TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA;
  2337. }
  2338. #endif
  2339. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM
  2340. if (tls1_2 && haveECC) {
  2341. suites->suites[idx++] = ECC_BYTE;
  2342. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CCM;
  2343. }
  2344. #endif
  2345. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
  2346. if (tls1_2 && haveECC) {
  2347. suites->suites[idx++] = ECC_BYTE;
  2348. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
  2349. }
  2350. #endif
  2351. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8
  2352. if (tls1_2 && haveECC) {
  2353. suites->suites[idx++] = ECC_BYTE;
  2354. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8;
  2355. }
  2356. #endif
  2357. #ifdef BUILD_TLS_RSA_WITH_AES_128_CCM_8
  2358. if (tls1_2 && haveRSA) {
  2359. suites->suites[idx++] = ECC_BYTE;
  2360. suites->suites[idx++] = TLS_RSA_WITH_AES_128_CCM_8;
  2361. }
  2362. #endif
  2363. #ifdef BUILD_TLS_RSA_WITH_AES_256_CCM_8
  2364. if (tls1_2 && haveRSA) {
  2365. suites->suites[idx++] = ECC_BYTE;
  2366. suites->suites[idx++] = TLS_RSA_WITH_AES_256_CCM_8;
  2367. }
  2368. #endif
  2369. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
  2370. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2371. if (tls1_2 && haveDH && haveRSA)
  2372. #else
  2373. if (tls && haveDH && haveRSA)
  2374. #endif
  2375. {
  2376. suites->suites[idx++] = CIPHER_BYTE;
  2377. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA256;
  2378. }
  2379. #endif
  2380. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
  2381. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2382. if (tls1_2 && haveDH && haveRSA)
  2383. #else
  2384. if (tls && haveDH && haveRSA)
  2385. #endif
  2386. {
  2387. suites->suites[idx++] = CIPHER_BYTE;
  2388. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_128_CBC_SHA256;
  2389. }
  2390. #endif
  2391. /* Place as higher priority for MYSQL testing */
  2392. #if !defined(WOLFSSL_MYSQL_COMPATIBLE)
  2393. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
  2394. if (tls && haveDH && haveRSA) {
  2395. suites->suites[idx++] = CIPHER_BYTE;
  2396. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA;
  2397. }
  2398. #endif
  2399. #endif
  2400. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
  2401. if (tls && haveDH && haveRSA) {
  2402. suites->suites[idx++] = CIPHER_BYTE;
  2403. suites->suites[idx++] = TLS_DHE_RSA_WITH_AES_128_CBC_SHA;
  2404. }
  2405. #endif
  2406. #ifdef BUILD_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
  2407. if (tls && haveDH && haveRSA) {
  2408. suites->suites[idx++] = CIPHER_BYTE;
  2409. suites->suites[idx++] = TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA;
  2410. }
  2411. #endif
  2412. #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA256
  2413. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2414. if (tls1_2 && haveRSA)
  2415. #else
  2416. if (tls && haveRSA)
  2417. #endif
  2418. {
  2419. suites->suites[idx++] = CIPHER_BYTE;
  2420. suites->suites[idx++] = TLS_RSA_WITH_AES_256_CBC_SHA256;
  2421. }
  2422. #endif
  2423. #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256
  2424. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2425. if (tls1_2 && haveRSA)
  2426. #else
  2427. if (tls && haveRSA)
  2428. #endif
  2429. {
  2430. suites->suites[idx++] = CIPHER_BYTE;
  2431. suites->suites[idx++] = TLS_RSA_WITH_AES_128_CBC_SHA256;
  2432. }
  2433. #endif
  2434. #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA
  2435. if (tls && haveRSA) {
  2436. suites->suites[idx++] = CIPHER_BYTE;
  2437. suites->suites[idx++] = TLS_RSA_WITH_AES_256_CBC_SHA;
  2438. }
  2439. #endif
  2440. #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA
  2441. if (tls && haveRSA) {
  2442. suites->suites[idx++] = CIPHER_BYTE;
  2443. suites->suites[idx++] = TLS_RSA_WITH_AES_128_CBC_SHA;
  2444. }
  2445. #endif
  2446. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256
  2447. if (tls1_2 && haveECC) {
  2448. suites->suites[idx++] = CHACHA_BYTE;
  2449. suites->suites[idx++] =
  2450. TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256;
  2451. }
  2452. #endif
  2453. #ifdef BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
  2454. if (tls1_2 && haveRSA) {
  2455. suites->suites[idx++] = CHACHA_BYTE;
  2456. suites->suites[idx++] = TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256;
  2457. }
  2458. #endif
  2459. #ifdef BUILD_TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
  2460. if (tls1_2 && haveRSA) {
  2461. suites->suites[idx++] = CHACHA_BYTE;
  2462. suites->suites[idx++] = TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256;
  2463. }
  2464. #endif
  2465. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_NULL_SHA
  2466. if (tls && haveECC) {
  2467. suites->suites[idx++] = ECC_BYTE;
  2468. suites->suites[idx++] = TLS_ECDHE_ECDSA_WITH_NULL_SHA;
  2469. }
  2470. #endif
  2471. #ifdef BUILD_TLS_RSA_WITH_NULL_MD5
  2472. if (tls && haveRSA) {
  2473. suites->suites[idx++] = CIPHER_BYTE;
  2474. suites->suites[idx++] = TLS_RSA_WITH_NULL_MD5;
  2475. }
  2476. #endif
  2477. #ifdef BUILD_TLS_RSA_WITH_NULL_SHA
  2478. if (tls && haveRSA) {
  2479. suites->suites[idx++] = CIPHER_BYTE;
  2480. suites->suites[idx++] = TLS_RSA_WITH_NULL_SHA;
  2481. }
  2482. #endif
  2483. #ifdef BUILD_TLS_RSA_WITH_NULL_SHA256
  2484. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2485. if (tls1_2 && haveRSA)
  2486. #else
  2487. if (tls && haveRSA)
  2488. #endif
  2489. {
  2490. suites->suites[idx++] = CIPHER_BYTE;
  2491. suites->suites[idx++] = TLS_RSA_WITH_NULL_SHA256;
  2492. }
  2493. #endif
  2494. #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA
  2495. if (tls && havePSK) {
  2496. suites->suites[idx++] = CIPHER_BYTE;
  2497. suites->suites[idx++] = TLS_PSK_WITH_AES_256_CBC_SHA;
  2498. }
  2499. #endif
  2500. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
  2501. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2502. if (tls1_2 && haveDH && havePSK)
  2503. #else
  2504. if (tls && haveDH && havePSK)
  2505. #endif
  2506. {
  2507. suites->suites[idx++] = CIPHER_BYTE;
  2508. suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_256_CBC_SHA384;
  2509. }
  2510. #endif
  2511. #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA384
  2512. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2513. if (tls1_2 && havePSK)
  2514. #else
  2515. if (tls && havePSK)
  2516. #endif
  2517. {
  2518. suites->suites[idx++] = CIPHER_BYTE;
  2519. suites->suites[idx++] = TLS_PSK_WITH_AES_256_CBC_SHA384;
  2520. }
  2521. #endif
  2522. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
  2523. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2524. if (tls1_2 && haveDH && havePSK)
  2525. #else
  2526. if (tls && haveDH && havePSK)
  2527. #endif
  2528. {
  2529. suites->suites[idx++] = CIPHER_BYTE;
  2530. suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_128_CBC_SHA256;
  2531. }
  2532. #endif
  2533. #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA256
  2534. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2535. if (tls1_2 && havePSK)
  2536. #else
  2537. if (tls1 && havePSK)
  2538. #endif
  2539. {
  2540. suites->suites[idx++] = CIPHER_BYTE;
  2541. suites->suites[idx++] = TLS_PSK_WITH_AES_128_CBC_SHA256;
  2542. }
  2543. #endif
  2544. #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA
  2545. if (tls && havePSK) {
  2546. suites->suites[idx++] = CIPHER_BYTE;
  2547. suites->suites[idx++] = TLS_PSK_WITH_AES_128_CBC_SHA;
  2548. }
  2549. #endif
  2550. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CCM
  2551. if (tls && haveDH && havePSK) {
  2552. suites->suites[idx++] = ECC_BYTE;
  2553. suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_128_CCM;
  2554. }
  2555. #endif
  2556. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_CCM
  2557. if (tls && haveDH && havePSK) {
  2558. suites->suites[idx++] = ECC_BYTE;
  2559. suites->suites[idx++] = TLS_DHE_PSK_WITH_AES_256_CCM;
  2560. }
  2561. #endif
  2562. #ifdef BUILD_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256
  2563. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2564. if (tls1_2 && havePSK)
  2565. #else
  2566. if (tls && havePSK)
  2567. #endif
  2568. {
  2569. suites->suites[idx++] = CHACHA_BYTE;
  2570. suites->suites[idx++] = TLS_PSK_WITH_CHACHA20_POLY1305_SHA256;
  2571. }
  2572. #endif
  2573. #ifdef BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256
  2574. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2575. if (tls1_2 && havePSK)
  2576. #else
  2577. if (tls && havePSK)
  2578. #endif
  2579. {
  2580. suites->suites[idx++] = CHACHA_BYTE;
  2581. suites->suites[idx++] = TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256;
  2582. }
  2583. #endif
  2584. #ifdef BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256
  2585. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2586. if (tls1_2 && havePSK)
  2587. #else
  2588. if (tls && havePSK)
  2589. #endif
  2590. {
  2591. suites->suites[idx++] = CHACHA_BYTE;
  2592. suites->suites[idx++] = TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256;
  2593. }
  2594. #endif
  2595. #ifdef BUILD_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
  2596. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2597. if (tls1_2 && havePSK)
  2598. #else
  2599. if (tls && havePSK)
  2600. #endif
  2601. {
  2602. suites->suites[idx++] = ECC_BYTE;
  2603. suites->suites[idx++] = TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
  2604. }
  2605. #endif
  2606. #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM
  2607. if (tls && havePSK) {
  2608. suites->suites[idx++] = ECC_BYTE;
  2609. suites->suites[idx++] = TLS_PSK_WITH_AES_128_CCM;
  2610. }
  2611. #endif
  2612. #ifdef BUILD_TLS_PSK_WITH_AES_256_CCM
  2613. if (tls && havePSK) {
  2614. suites->suites[idx++] = ECC_BYTE;
  2615. suites->suites[idx++] = TLS_PSK_WITH_AES_256_CCM;
  2616. }
  2617. #endif
  2618. #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM_8
  2619. if (tls && havePSK) {
  2620. suites->suites[idx++] = ECC_BYTE;
  2621. suites->suites[idx++] = TLS_PSK_WITH_AES_128_CCM_8;
  2622. }
  2623. #endif
  2624. #ifdef BUILD_TLS_PSK_WITH_AES_256_CCM_8
  2625. if (tls && havePSK) {
  2626. suites->suites[idx++] = ECC_BYTE;
  2627. suites->suites[idx++] = TLS_PSK_WITH_AES_256_CCM_8;
  2628. }
  2629. #endif
  2630. #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA384
  2631. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2632. if (tls1_2 && haveDH && havePSK)
  2633. #else
  2634. if (tls && haveDH && havePSK)
  2635. #endif
  2636. {
  2637. suites->suites[idx++] = CIPHER_BYTE;
  2638. suites->suites[idx++] = TLS_DHE_PSK_WITH_NULL_SHA384;
  2639. }
  2640. #endif
  2641. #ifdef BUILD_TLS_PSK_WITH_NULL_SHA384
  2642. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2643. if (tls1_2 && havePSK)
  2644. #else
  2645. if (tls && havePSK)
  2646. #endif
  2647. {
  2648. suites->suites[idx++] = CIPHER_BYTE;
  2649. suites->suites[idx++] = TLS_PSK_WITH_NULL_SHA384;
  2650. }
  2651. #endif
  2652. #ifdef BUILD_TLS_ECDHE_PSK_WITH_NULL_SHA256
  2653. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2654. if (tls1_2 && havePSK)
  2655. #else
  2656. if (tls && havePSK)
  2657. #endif
  2658. {
  2659. suites->suites[idx++] = ECC_BYTE;
  2660. suites->suites[idx++] = TLS_ECDHE_PSK_WITH_NULL_SHA256;
  2661. }
  2662. #endif
  2663. #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA256
  2664. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2665. if (tls1_2 && haveDH && havePSK)
  2666. #else
  2667. if (tls && haveDH && havePSK)
  2668. #endif
  2669. {
  2670. suites->suites[idx++] = CIPHER_BYTE;
  2671. suites->suites[idx++] = TLS_DHE_PSK_WITH_NULL_SHA256;
  2672. }
  2673. #endif
  2674. #ifdef BUILD_TLS_PSK_WITH_NULL_SHA256
  2675. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2676. if (tls1_2 && havePSK)
  2677. #else
  2678. if (tls && havePSK)
  2679. #endif
  2680. {
  2681. suites->suites[idx++] = CIPHER_BYTE;
  2682. suites->suites[idx++] = TLS_PSK_WITH_NULL_SHA256;
  2683. }
  2684. #endif
  2685. #ifdef BUILD_TLS_PSK_WITH_NULL_SHA
  2686. if (tls && havePSK) {
  2687. suites->suites[idx++] = CIPHER_BYTE;
  2688. suites->suites[idx++] = TLS_PSK_WITH_NULL_SHA;
  2689. }
  2690. #endif
  2691. #ifdef BUILD_SSL_RSA_WITH_RC4_128_SHA
  2692. if (!dtls && haveRSA) {
  2693. suites->suites[idx++] = CIPHER_BYTE;
  2694. suites->suites[idx++] = SSL_RSA_WITH_RC4_128_SHA;
  2695. }
  2696. #endif
  2697. #ifdef BUILD_SSL_RSA_WITH_RC4_128_MD5
  2698. if (!dtls && haveRSA) {
  2699. suites->suites[idx++] = CIPHER_BYTE;
  2700. suites->suites[idx++] = SSL_RSA_WITH_RC4_128_MD5;
  2701. }
  2702. #endif
  2703. #ifdef BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA
  2704. if (haveRSA ) {
  2705. suites->suites[idx++] = CIPHER_BYTE;
  2706. suites->suites[idx++] = SSL_RSA_WITH_3DES_EDE_CBC_SHA;
  2707. }
  2708. #endif
  2709. #ifdef BUILD_TLS_RSA_WITH_HC_128_MD5
  2710. if (!dtls && tls && haveRSA) {
  2711. suites->suites[idx++] = CIPHER_BYTE;
  2712. suites->suites[idx++] = TLS_RSA_WITH_HC_128_MD5;
  2713. }
  2714. #endif
  2715. #ifdef BUILD_TLS_RSA_WITH_HC_128_SHA
  2716. if (!dtls && tls && haveRSA) {
  2717. suites->suites[idx++] = CIPHER_BYTE;
  2718. suites->suites[idx++] = TLS_RSA_WITH_HC_128_SHA;
  2719. }
  2720. #endif
  2721. #ifdef BUILD_TLS_RSA_WITH_RABBIT_SHA
  2722. if (!dtls && tls && haveRSA) {
  2723. suites->suites[idx++] = CIPHER_BYTE;
  2724. suites->suites[idx++] = TLS_RSA_WITH_RABBIT_SHA;
  2725. }
  2726. #endif
  2727. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
  2728. if (tls && haveRSA) {
  2729. suites->suites[idx++] = CIPHER_BYTE;
  2730. suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_128_CBC_SHA;
  2731. }
  2732. #endif
  2733. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
  2734. if (tls && haveDH && haveRSA) {
  2735. suites->suites[idx++] = CIPHER_BYTE;
  2736. suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA;
  2737. }
  2738. #endif
  2739. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
  2740. if (tls && haveRSA) {
  2741. suites->suites[idx++] = CIPHER_BYTE;
  2742. suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_256_CBC_SHA;
  2743. }
  2744. #endif
  2745. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
  2746. if (tls && haveDH && haveRSA) {
  2747. suites->suites[idx++] = CIPHER_BYTE;
  2748. suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA;
  2749. }
  2750. #endif
  2751. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
  2752. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2753. if (tls1_2 && haveRSA)
  2754. #else
  2755. if (tls && haveRSA)
  2756. #endif
  2757. {
  2758. suites->suites[idx++] = CIPHER_BYTE;
  2759. suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256;
  2760. }
  2761. #endif
  2762. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
  2763. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2764. if (tls1_2 && haveDH && haveRSA)
  2765. #else
  2766. if (tls && haveDH && haveRSA)
  2767. #endif
  2768. {
  2769. suites->suites[idx++] = CIPHER_BYTE;
  2770. suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256;
  2771. }
  2772. #endif
  2773. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256
  2774. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2775. if (tls1_2 && haveRSA)
  2776. #else
  2777. if (tls && haveRSA)
  2778. #endif
  2779. {
  2780. suites->suites[idx++] = CIPHER_BYTE;
  2781. suites->suites[idx++] = TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256;
  2782. }
  2783. #endif
  2784. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
  2785. #ifndef WOLFSSL_OLDTLS_SHA2_CIPHERSUITES
  2786. if (tls1_2 && haveDH && haveRSA)
  2787. #else
  2788. if (tls && haveDH && haveRSA)
  2789. #endif
  2790. {
  2791. suites->suites[idx++] = CIPHER_BYTE;
  2792. suites->suites[idx++] = TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256;
  2793. }
  2794. #endif
  2795. #ifdef BUILD_SSL_RSA_WITH_IDEA_CBC_SHA
  2796. if (haveRSA) {
  2797. suites->suites[idx++] = CIPHER_BYTE;
  2798. suites->suites[idx++] = SSL_RSA_WITH_IDEA_CBC_SHA;
  2799. }
  2800. #endif
  2801. #endif /* !WOLFSSL_NO_TLS12 */
  2802. suites->suiteSz = idx;
  2803. InitSuitesHashSigAlgo(suites, haveECDSAsig | haveECC, haveRSAsig | haveRSA,
  2804. 0, tls1_2, keySz);
  2805. }
  2806. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_CERTS) || \
  2807. (!defined(NO_WOLFSSL_CLIENT) && (!defined(NO_DH) || defined(HAVE_ECC)))
  2808. /* Decode the signature algorithm.
  2809. *
  2810. * input The encoded signature algorithm.
  2811. * hashalgo The hash algorithm.
  2812. * hsType The signature type.
  2813. */
  2814. static WC_INLINE void DecodeSigAlg(const byte* input, byte* hashAlgo, byte* hsType)
  2815. {
  2816. switch (input[0]) {
  2817. case NEW_SA_MAJOR:
  2818. #ifdef HAVE_ED25519
  2819. /* ED25519: 0x0807 */
  2820. if (input[1] == ED25519_SA_MINOR) {
  2821. *hsType = ed25519_sa_algo;
  2822. /* Hash performed as part of sign/verify operation. */
  2823. *hashAlgo = sha512_mac;
  2824. }
  2825. else
  2826. #endif
  2827. #ifdef HAVE_ED448
  2828. /* ED448: 0x0808 */
  2829. if (input[1] == ED448_SA_MINOR) {
  2830. *hsType = ed448_sa_algo;
  2831. /* Hash performed as part of sign/verify operation. */
  2832. *hashAlgo = sha512_mac;
  2833. }
  2834. else
  2835. #endif
  2836. #ifdef WC_RSA_PSS
  2837. /* PSS PSS signatures: 0x080[9-b] */
  2838. if (input[1] >= pss_sha256 && input[1] <= pss_sha512) {
  2839. *hsType = rsa_pss_pss_algo;
  2840. *hashAlgo = PSS_PSS_HASH_TO_MAC(input[1]);
  2841. }
  2842. else
  2843. #endif
  2844. {
  2845. *hsType = input[0];
  2846. *hashAlgo = input[1];
  2847. }
  2848. break;
  2849. default:
  2850. *hashAlgo = input[0];
  2851. *hsType = input[1];
  2852. break;
  2853. }
  2854. }
  2855. #endif /* !NO_WOLFSSL_SERVER || !NO_CERTS */
  2856. #ifndef WOLFSSL_NO_TLS12
  2857. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
  2858. #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  2859. defined(HAVE_CURVE448) || (!defined(NO_RSA) && defined(WC_RSA_PSS))
  2860. static enum wc_HashType HashAlgoToType(int hashAlgo)
  2861. {
  2862. switch (hashAlgo) {
  2863. #ifdef WOLFSSL_SHA512
  2864. case sha512_mac:
  2865. return WC_HASH_TYPE_SHA512;
  2866. #endif
  2867. #ifdef WOLFSSL_SHA384
  2868. case sha384_mac:
  2869. return WC_HASH_TYPE_SHA384;
  2870. #endif
  2871. #ifndef NO_SHA256
  2872. case sha256_mac:
  2873. return WC_HASH_TYPE_SHA256;
  2874. #endif
  2875. #ifdef WOLFSSL_SHA224
  2876. case sha224_mac:
  2877. return WC_HASH_TYPE_SHA224;
  2878. #endif
  2879. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  2880. defined(WOLFSSL_ALLOW_TLS_SHA1))
  2881. case sha_mac:
  2882. return WC_HASH_TYPE_SHA;
  2883. #endif
  2884. default:
  2885. WOLFSSL_MSG("Bad hash sig algo");
  2886. break;
  2887. }
  2888. return WC_HASH_TYPE_NONE;
  2889. }
  2890. #endif /* !NO_DH || HAVE_ECC || (!NO_RSA && WC_RSA_PSS) */
  2891. #endif /* !NO_WOLFSSL_SERVER || !NO_WOLFSSL_CLIENT */
  2892. #endif /* !WOLFSSL_NO_TLS12 */
  2893. #ifndef NO_CERTS
  2894. void InitX509Name(WOLFSSL_X509_NAME* name, int dynamicFlag)
  2895. {
  2896. (void)dynamicFlag;
  2897. if (name != NULL) {
  2898. name->name = name->staticName;
  2899. name->dynamicName = 0;
  2900. name->sz = 0;
  2901. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  2902. XMEMSET(&name->fullName, 0, sizeof(DecodedName));
  2903. XMEMSET(&name->cnEntry, 0, sizeof(WOLFSSL_X509_NAME_ENTRY));
  2904. XMEMSET(&name->extra, 0, sizeof(name->extra));
  2905. name->cnEntry.value = &(name->cnEntry.data); /* point to internal data*/
  2906. name->cnEntry.nid = ASN_COMMON_NAME;
  2907. name->x509 = NULL;
  2908. #endif /* OPENSSL_EXTRA */
  2909. }
  2910. }
  2911. void FreeX509Name(WOLFSSL_X509_NAME* name, void* heap)
  2912. {
  2913. if (name != NULL) {
  2914. if (name->dynamicName) {
  2915. XFREE(name->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  2916. name->name = NULL;
  2917. }
  2918. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  2919. {
  2920. int i;
  2921. if (name->fullName.fullName != NULL) {
  2922. XFREE(name->fullName.fullName, heap, DYNAMIC_TYPE_X509);
  2923. name->fullName.fullName = NULL;
  2924. }
  2925. for (i = 0; i < MAX_NAME_ENTRIES; i++) {
  2926. /* free ASN1 string data */
  2927. if (name->extra[i].set && name->extra[i].data.data != NULL) {
  2928. XFREE(name->extra[i].data.data, heap, DYNAMIC_TYPE_OPENSSL);
  2929. }
  2930. }
  2931. wolfSSL_ASN1_OBJECT_free(&name->cnEntry.object);
  2932. }
  2933. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  2934. }
  2935. (void)heap;
  2936. }
  2937. /* Initialize wolfSSL X509 type */
  2938. void InitX509(WOLFSSL_X509* x509, int dynamicFlag, void* heap)
  2939. {
  2940. if (x509 == NULL) {
  2941. WOLFSSL_MSG("Null parameter passed in!");
  2942. return;
  2943. }
  2944. XMEMSET(x509, 0, sizeof(WOLFSSL_X509));
  2945. x509->heap = heap;
  2946. InitX509Name(&x509->issuer, 0);
  2947. InitX509Name(&x509->subject, 0);
  2948. x509->dynamicMemory = (byte)dynamicFlag;
  2949. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
  2950. x509->refCount = 1;
  2951. (void)wc_InitMutex(&x509->refMutex);
  2952. #endif
  2953. }
  2954. /* Free wolfSSL X509 type */
  2955. void FreeX509(WOLFSSL_X509* x509)
  2956. {
  2957. if (x509 == NULL)
  2958. return;
  2959. FreeX509Name(&x509->issuer, x509->heap);
  2960. FreeX509Name(&x509->subject, x509->heap);
  2961. if (x509->pubKey.buffer) {
  2962. XFREE(x509->pubKey.buffer, x509->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  2963. x509->pubKey.buffer = NULL;
  2964. }
  2965. FreeDer(&x509->derCert);
  2966. XFREE(x509->sig.buffer, x509->heap, DYNAMIC_TYPE_SIGNATURE);
  2967. x509->sig.buffer = NULL;
  2968. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  2969. XFREE(x509->authKeyId, x509->heap, DYNAMIC_TYPE_X509_EXT);
  2970. x509->authKeyId = NULL;
  2971. XFREE(x509->subjKeyId, x509->heap, DYNAMIC_TYPE_X509_EXT);
  2972. x509->subjKeyId = NULL;
  2973. if (x509->authInfo != NULL) {
  2974. XFREE(x509->authInfo, x509->heap, DYNAMIC_TYPE_X509_EXT);
  2975. x509->authInfo = NULL;
  2976. }
  2977. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  2978. if (x509->authInfoCaIssuer != NULL) {
  2979. XFREE(x509->authInfoCaIssuer, x509->heap, DYNAMIC_TYPE_X509_EXT);
  2980. }
  2981. if (x509->ext_sk != NULL) {
  2982. wolfSSL_sk_X509_EXTENSION_free(x509->ext_sk);
  2983. }
  2984. #endif /* OPENSSL_ALL || WOLFSSL_QT */
  2985. #ifdef OPENSSL_EXTRA
  2986. /* Free serialNumber that was set by wolfSSL_X509_get_serialNumber */
  2987. if (x509->serialNumber != NULL) {
  2988. wolfSSL_ASN1_INTEGER_free(x509->serialNumber);
  2989. }
  2990. #endif
  2991. if (x509->extKeyUsageSrc != NULL) {
  2992. XFREE(x509->extKeyUsageSrc, x509->heap, DYNAMIC_TYPE_X509_EXT);
  2993. x509->extKeyUsageSrc= NULL;
  2994. }
  2995. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  2996. #if defined(OPENSSL_ALL)
  2997. if (x509->algor.algorithm) {
  2998. wolfSSL_ASN1_OBJECT_free(x509->algor.algorithm);
  2999. x509->algor.algorithm = NULL;
  3000. }
  3001. if (x509->key.algor) {
  3002. wolfSSL_X509_ALGOR_free(x509->key.algor);
  3003. x509->key.algor = NULL;
  3004. }
  3005. if (x509->key.pkey) {
  3006. wolfSSL_EVP_PKEY_free(x509->key.pkey);
  3007. x509->key.pkey = NULL;
  3008. }
  3009. #endif /* OPENSSL_ALL */
  3010. if (x509->altNames) {
  3011. FreeAltNames(x509->altNames, x509->heap);
  3012. x509->altNames = NULL;
  3013. }
  3014. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
  3015. wc_FreeMutex(&x509->refMutex);
  3016. #endif
  3017. }
  3018. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
  3019. #if !defined(WOLFSSL_NO_TLS12)
  3020. /* Encode the signature algorithm into buffer.
  3021. *
  3022. * hashalgo The hash algorithm.
  3023. * hsType The signature type.
  3024. * output The buffer to encode into.
  3025. */
  3026. static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output)
  3027. {
  3028. switch (hsType) {
  3029. #ifdef HAVE_ECC
  3030. case ecc_dsa_sa_algo:
  3031. output[0] = hashAlgo;
  3032. output[1] = ecc_dsa_sa_algo;
  3033. break;
  3034. #endif
  3035. #ifdef HAVE_ED25519
  3036. case ed25519_sa_algo:
  3037. output[0] = ED25519_SA_MAJOR;
  3038. output[1] = ED25519_SA_MINOR;
  3039. (void)hashAlgo;
  3040. break;
  3041. #endif
  3042. #ifdef HAVE_ED448
  3043. case ed448_sa_algo:
  3044. output[0] = ED448_SA_MAJOR;
  3045. output[1] = ED448_SA_MINOR;
  3046. (void)hashAlgo;
  3047. break;
  3048. #endif
  3049. #ifndef NO_RSA
  3050. case rsa_sa_algo:
  3051. output[0] = hashAlgo;
  3052. output[1] = rsa_sa_algo;
  3053. break;
  3054. #ifdef WC_RSA_PSS
  3055. /* PSS signatures: 0x080[4-6] */
  3056. case rsa_pss_sa_algo:
  3057. output[0] = rsa_pss_sa_algo;
  3058. output[1] = hashAlgo;
  3059. break;
  3060. #endif
  3061. #endif
  3062. }
  3063. (void)hashAlgo;
  3064. (void)output;
  3065. }
  3066. #endif
  3067. #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  3068. static void SetDigest(WOLFSSL* ssl, int hashAlgo)
  3069. {
  3070. switch (hashAlgo) {
  3071. #ifndef NO_SHA
  3072. case sha_mac:
  3073. ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha;
  3074. ssl->buffers.digest.length = WC_SHA_DIGEST_SIZE;
  3075. break;
  3076. #endif /* !NO_SHA */
  3077. #ifndef NO_SHA256
  3078. case sha256_mac:
  3079. ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha256;
  3080. ssl->buffers.digest.length = WC_SHA256_DIGEST_SIZE;
  3081. break;
  3082. #endif /* !NO_SHA256 */
  3083. #ifdef WOLFSSL_SHA384
  3084. case sha384_mac:
  3085. ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha384;
  3086. ssl->buffers.digest.length = WC_SHA384_DIGEST_SIZE;
  3087. break;
  3088. #endif /* WOLFSSL_SHA384 */
  3089. #ifdef WOLFSSL_SHA512
  3090. case sha512_mac:
  3091. ssl->buffers.digest.buffer = ssl->hsHashes->certHashes.sha512;
  3092. ssl->buffers.digest.length = WC_SHA512_DIGEST_SIZE;
  3093. break;
  3094. #endif /* WOLFSSL_SHA512 */
  3095. } /* switch */
  3096. }
  3097. #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_NO_CLIENT_AUTH */
  3098. #endif /* !NO_WOLFSSL_SERVER || !NO_WOLFSSL_CLIENT */
  3099. #endif /* !NO_CERTS */
  3100. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  3101. static word32 MacSize(WOLFSSL* ssl)
  3102. {
  3103. #ifdef HAVE_TRUNCATED_HMAC
  3104. word32 digestSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  3105. : ssl->specs.hash_size;
  3106. #else
  3107. word32 digestSz = ssl->specs.hash_size;
  3108. #endif
  3109. return digestSz;
  3110. }
  3111. #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */
  3112. #ifndef NO_RSA
  3113. #ifndef WOLFSSL_NO_TLS12
  3114. #if !defined(NO_WOLFSSL_SERVER) || (!defined(NO_WOLFSSL_CLIENT) && \
  3115. !defined(WOLFSSL_NO_CLIENT_AUTH))
  3116. static int TypeHash(int hashAlgo)
  3117. {
  3118. switch (hashAlgo) {
  3119. #ifdef WOLFSSL_SHA512
  3120. case sha512_mac:
  3121. return SHA512h;
  3122. #endif
  3123. #ifdef WOLFSSL_SHA384
  3124. case sha384_mac:
  3125. return SHA384h;
  3126. #endif
  3127. #ifndef NO_SHA256
  3128. case sha256_mac:
  3129. return SHA256h;
  3130. #endif
  3131. #ifdef WOLFSSL_SHA224
  3132. case sha224_mac:
  3133. return SHA224h;
  3134. #endif
  3135. #ifndef NO_SHA
  3136. case sha_mac:
  3137. return SHAh;
  3138. #endif
  3139. }
  3140. return 0;
  3141. }
  3142. #endif /* !NO_WOLFSSL_SERVER && !NO_WOLFSSL_CLIENT */
  3143. #endif /* !WOLFSSL_NO_TLS12 */
  3144. #if defined(WC_RSA_PSS)
  3145. int ConvertHashPss(int hashAlgo, enum wc_HashType* hashType, int* mgf)
  3146. {
  3147. switch (hashAlgo) {
  3148. #ifdef WOLFSSL_SHA512
  3149. case sha512_mac:
  3150. *hashType = WC_HASH_TYPE_SHA512;
  3151. if (mgf != NULL)
  3152. *mgf = WC_MGF1SHA512;
  3153. break;
  3154. #endif
  3155. #ifdef WOLFSSL_SHA384
  3156. case sha384_mac:
  3157. *hashType = WC_HASH_TYPE_SHA384;
  3158. if (mgf != NULL)
  3159. *mgf = WC_MGF1SHA384;
  3160. break;
  3161. #endif
  3162. #ifndef NO_SHA256
  3163. case sha256_mac:
  3164. *hashType = WC_HASH_TYPE_SHA256;
  3165. if (mgf != NULL)
  3166. *mgf = WC_MGF1SHA256;
  3167. break;
  3168. #endif
  3169. default:
  3170. return BAD_FUNC_ARG;
  3171. }
  3172. return 0;
  3173. }
  3174. #endif
  3175. #if !defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  3176. int RsaSign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
  3177. word32* outSz, int sigAlgo, int hashAlgo, RsaKey* key,
  3178. DerBuffer* keyBufInfo)
  3179. {
  3180. int ret;
  3181. #ifdef HAVE_PK_CALLBACKS
  3182. const byte* keyBuf = NULL;
  3183. word32 keySz = 0;
  3184. if (keyBufInfo) {
  3185. keyBuf = keyBufInfo->buffer;
  3186. keySz = keyBufInfo->length;
  3187. }
  3188. #endif
  3189. (void)ssl;
  3190. (void)keyBufInfo;
  3191. (void)sigAlgo;
  3192. (void)hashAlgo;
  3193. WOLFSSL_ENTER("RsaSign");
  3194. #ifdef WOLFSSL_ASYNC_CRYPT
  3195. /* initialize event */
  3196. if (key) {
  3197. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  3198. if (ret != 0)
  3199. return ret;
  3200. }
  3201. #endif
  3202. #if defined(WC_RSA_PSS)
  3203. if (sigAlgo == rsa_pss_sa_algo) {
  3204. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  3205. int mgf = 0;
  3206. ret = ConvertHashPss(hashAlgo, &hashType, &mgf);
  3207. if (ret != 0)
  3208. return ret;
  3209. #if defined(HAVE_PK_CALLBACKS)
  3210. if (ssl->ctx->RsaPssSignCb) {
  3211. void* ctx = wolfSSL_GetRsaPssSignCtx(ssl);
  3212. ret = ssl->ctx->RsaPssSignCb(ssl, in, inSz, out, outSz,
  3213. TypeHash(hashAlgo), mgf,
  3214. keyBuf, keySz, ctx);
  3215. }
  3216. else
  3217. #endif
  3218. {
  3219. ret = wc_RsaPSS_Sign(in, inSz, out, *outSz, hashType, mgf, key,
  3220. ssl->rng);
  3221. }
  3222. }
  3223. else
  3224. #endif
  3225. #if defined(HAVE_PK_CALLBACKS)
  3226. if (ssl->ctx->RsaSignCb) {
  3227. void* ctx = wolfSSL_GetRsaSignCtx(ssl);
  3228. ret = ssl->ctx->RsaSignCb(ssl, in, inSz, out, outSz, keyBuf, keySz,
  3229. ctx);
  3230. }
  3231. else
  3232. #endif /*HAVE_PK_CALLBACKS */
  3233. ret = wc_RsaSSL_Sign(in, inSz, out, *outSz, key, ssl->rng);
  3234. /* Handle async pending response */
  3235. #ifdef WOLFSSL_ASYNC_CRYPT
  3236. if (key && ret == WC_PENDING_E) {
  3237. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  3238. }
  3239. #endif /* WOLFSSL_ASYNC_CRYPT */
  3240. /* For positive response return in outSz */
  3241. if (ret > 0) {
  3242. *outSz = ret;
  3243. ret = 0;
  3244. }
  3245. WOLFSSL_LEAVE("RsaSign", ret);
  3246. return ret;
  3247. }
  3248. #endif
  3249. int RsaVerify(WOLFSSL* ssl, byte* in, word32 inSz, byte** out, int sigAlgo,
  3250. int hashAlgo, RsaKey* key, buffer* keyBufInfo)
  3251. {
  3252. int ret;
  3253. #ifdef HAVE_PK_CALLBACKS
  3254. const byte* keyBuf = NULL;
  3255. word32 keySz = 0;
  3256. if (keyBufInfo) {
  3257. keyBuf = keyBufInfo->buffer;
  3258. keySz = keyBufInfo->length;
  3259. }
  3260. #endif
  3261. (void)ssl;
  3262. (void)keyBufInfo;
  3263. (void)sigAlgo;
  3264. (void)hashAlgo;
  3265. WOLFSSL_ENTER("RsaVerify");
  3266. #ifdef WOLFSSL_ASYNC_CRYPT
  3267. /* initialize event */
  3268. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  3269. if (ret != 0)
  3270. return ret;
  3271. #endif
  3272. #if defined(WC_RSA_PSS)
  3273. if (sigAlgo == rsa_pss_sa_algo) {
  3274. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  3275. int mgf = 0;
  3276. ret = ConvertHashPss(hashAlgo, &hashType, &mgf);
  3277. if (ret != 0)
  3278. return ret;
  3279. #ifdef HAVE_PK_CALLBACKS
  3280. if (ssl->ctx->RsaPssVerifyCb) {
  3281. void* ctx = wolfSSL_GetRsaPssVerifyCtx(ssl);
  3282. ret = ssl->ctx->RsaPssVerifyCb(ssl, in, inSz, out,
  3283. TypeHash(hashAlgo), mgf,
  3284. keyBuf, keySz, ctx);
  3285. }
  3286. else
  3287. #endif /*HAVE_PK_CALLBACKS */
  3288. ret = wc_RsaPSS_VerifyInline(in, inSz, out, hashType, mgf, key);
  3289. }
  3290. else
  3291. #endif
  3292. #ifdef HAVE_PK_CALLBACKS
  3293. if (ssl->ctx->RsaVerifyCb) {
  3294. void* ctx = wolfSSL_GetRsaVerifyCtx(ssl);
  3295. ret = ssl->ctx->RsaVerifyCb(ssl, in, inSz, out, keyBuf, keySz, ctx);
  3296. }
  3297. else
  3298. #endif /*HAVE_PK_CALLBACKS */
  3299. {
  3300. ret = wc_RsaSSL_VerifyInline(in, inSz, out, key);
  3301. }
  3302. /* Handle async pending response */
  3303. #ifdef WOLFSSL_ASYNC_CRYPT
  3304. if (ret == WC_PENDING_E) {
  3305. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  3306. }
  3307. #endif /* WOLFSSL_ASYNC_CRYPT */
  3308. WOLFSSL_LEAVE("RsaVerify", ret);
  3309. return ret;
  3310. }
  3311. /* Verify RSA signature, 0 on success */
  3312. /* This function is used to check the sign result */
  3313. int VerifyRsaSign(WOLFSSL* ssl, byte* verifySig, word32 sigSz,
  3314. const byte* plain, word32 plainSz, int sigAlgo, int hashAlgo, RsaKey* key,
  3315. DerBuffer* keyBufInfo)
  3316. {
  3317. byte* out = NULL; /* inline result */
  3318. int ret;
  3319. #ifdef HAVE_PK_CALLBACKS
  3320. const byte* keyBuf = NULL;
  3321. word32 keySz = 0;
  3322. if (keyBufInfo) {
  3323. keyBuf = keyBufInfo->buffer;
  3324. keySz = keyBufInfo->length;
  3325. }
  3326. #endif
  3327. (void)ssl;
  3328. (void)keyBufInfo;
  3329. (void)sigAlgo;
  3330. (void)hashAlgo;
  3331. WOLFSSL_ENTER("VerifyRsaSign");
  3332. if (verifySig == NULL || plain == NULL) {
  3333. return BAD_FUNC_ARG;
  3334. }
  3335. if (sigSz > ENCRYPT_LEN) {
  3336. WOLFSSL_MSG("Signature buffer too big");
  3337. return BUFFER_E;
  3338. }
  3339. #ifdef WOLFSSL_ASYNC_CRYPT
  3340. /* initialize event */
  3341. if (key) {
  3342. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  3343. if (ret != 0)
  3344. return ret;
  3345. }
  3346. #endif
  3347. #if defined(WC_RSA_PSS)
  3348. if (sigAlgo == rsa_pss_sa_algo) {
  3349. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  3350. int mgf = 0;
  3351. ret = ConvertHashPss(hashAlgo, &hashType, &mgf);
  3352. if (ret != 0)
  3353. return ret;
  3354. #ifdef HAVE_PK_CALLBACKS
  3355. if (ssl->ctx->RsaPssSignCheckCb) {
  3356. /* The key buffer includes private/public portion,
  3357. but only public is used */
  3358. /* If HSM hardware is checking the signature result you can
  3359. optionally skip the sign check and return 0 */
  3360. /* The ctx here is the RsaSignCtx set using wolfSSL_SetRsaSignCtx */
  3361. void* ctx = wolfSSL_GetRsaPssSignCtx(ssl);
  3362. ret = ssl->ctx->RsaPssSignCheckCb(ssl, verifySig, sigSz, &out,
  3363. TypeHash(hashAlgo), mgf,
  3364. keyBuf, keySz, ctx);
  3365. if (ret > 0) {
  3366. ret = wc_RsaPSS_CheckPadding(plain, plainSz, out, ret,
  3367. hashType);
  3368. if (ret != 0)
  3369. ret = VERIFY_CERT_ERROR;
  3370. }
  3371. }
  3372. else
  3373. #endif /* HAVE_PK_CALLBACKS */
  3374. {
  3375. ret = wc_RsaPSS_VerifyInline(verifySig, sigSz, &out, hashType, mgf,
  3376. key);
  3377. if (ret > 0) {
  3378. #ifdef HAVE_SELFTEST
  3379. ret = wc_RsaPSS_CheckPadding(plain, plainSz, out, ret,
  3380. hashType);
  3381. #else
  3382. ret = wc_RsaPSS_CheckPadding_ex(plain, plainSz, out, ret,
  3383. hashType, -1,
  3384. mp_count_bits(&key->n));
  3385. #endif
  3386. if (ret != 0)
  3387. ret = VERIFY_CERT_ERROR;
  3388. }
  3389. }
  3390. }
  3391. else
  3392. #endif /* WC_RSA_PSS */
  3393. {
  3394. #ifdef HAVE_PK_CALLBACKS
  3395. if (ssl->ctx->RsaSignCheckCb) {
  3396. /* The key buffer includes private/public portion,
  3397. but only public is used */
  3398. /* If HSM hardware is checking the signature result you can
  3399. optionally skip the sign check and return 0 */
  3400. /* The ctx here is the RsaSignCtx set using wolfSSL_SetRsaSignCtx */
  3401. void* ctx = wolfSSL_GetRsaSignCtx(ssl);
  3402. ret = ssl->ctx->RsaSignCheckCb(ssl, verifySig, sigSz, &out,
  3403. keyBuf, keySz, ctx);
  3404. }
  3405. else
  3406. #endif /* HAVE_PK_CALLBACKS */
  3407. {
  3408. ret = wc_RsaSSL_VerifyInline(verifySig, sigSz, &out, key);
  3409. }
  3410. if (ret > 0) {
  3411. if (ret != (int)plainSz || !out ||
  3412. XMEMCMP(plain, out, plainSz) != 0) {
  3413. WOLFSSL_MSG("RSA Signature verification failed");
  3414. ret = RSA_SIGN_FAULT;
  3415. } else {
  3416. ret = 0; /* RSA reset */
  3417. }
  3418. }
  3419. }
  3420. /* Handle async pending response */
  3421. #ifdef WOLFSSL_ASYNC_CRYPT
  3422. if (key && ret == WC_PENDING_E) {
  3423. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  3424. }
  3425. #endif /* WOLFSSL_ASYNC_CRYPT */
  3426. WOLFSSL_LEAVE("VerifyRsaSign", ret);
  3427. return ret;
  3428. }
  3429. #ifndef WOLFSSL_NO_TLS12
  3430. #if !defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  3431. int RsaDec(WOLFSSL* ssl, byte* in, word32 inSz, byte** out, word32* outSz,
  3432. RsaKey* key, DerBuffer* keyBufInfo)
  3433. {
  3434. int ret;
  3435. #ifdef HAVE_PK_CALLBACKS
  3436. const byte* keyBuf = NULL;
  3437. word32 keySz = 0;
  3438. if (keyBufInfo) {
  3439. keyBuf = keyBufInfo->buffer;
  3440. keySz = keyBufInfo->length;
  3441. }
  3442. #endif
  3443. (void)ssl;
  3444. (void)keyBufInfo;
  3445. WOLFSSL_ENTER("RsaDec");
  3446. #ifdef WOLFSSL_ASYNC_CRYPT
  3447. /* initialize event */
  3448. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  3449. if (ret != 0)
  3450. return ret;
  3451. #endif
  3452. #ifdef HAVE_PK_CALLBACKS
  3453. if (ssl->ctx->RsaDecCb) {
  3454. void* ctx = wolfSSL_GetRsaDecCtx(ssl);
  3455. ret = ssl->ctx->RsaDecCb(ssl, in, inSz, out, keyBuf, keySz, ctx);
  3456. }
  3457. else
  3458. #endif /* HAVE_PK_CALLBACKS */
  3459. {
  3460. #ifdef WC_RSA_BLINDING
  3461. ret = wc_RsaSetRNG(key, ssl->rng);
  3462. if (ret != 0)
  3463. return ret;
  3464. #endif
  3465. ret = wc_RsaPrivateDecryptInline(in, inSz, out, key);
  3466. }
  3467. /* Handle async pending response */
  3468. #ifdef WOLFSSL_ASYNC_CRYPT
  3469. if (ret == WC_PENDING_E) {
  3470. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  3471. }
  3472. #endif /* WOLFSSL_ASYNC_CRYPT */
  3473. /* For positive response return in outSz */
  3474. if (ret > 0) {
  3475. *outSz = ret;
  3476. ret = 0;
  3477. }
  3478. WOLFSSL_LEAVE("RsaDec", ret);
  3479. return ret;
  3480. }
  3481. #endif /* !NO_WOLFSSL_SERVER) || !WOLFSSL_NO_CLIENT_AUTH */
  3482. int RsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out, word32* outSz,
  3483. RsaKey* key, buffer* keyBufInfo)
  3484. {
  3485. int ret;
  3486. #ifdef HAVE_PK_CALLBACKS
  3487. const byte* keyBuf = NULL;
  3488. word32 keySz = 0;
  3489. if (keyBufInfo) {
  3490. keyBuf = keyBufInfo->buffer;
  3491. keySz = keyBufInfo->length;
  3492. }
  3493. #endif
  3494. (void)ssl;
  3495. (void)keyBufInfo;
  3496. WOLFSSL_ENTER("RsaEnc");
  3497. #ifdef WOLFSSL_ASYNC_CRYPT
  3498. /* initialize event */
  3499. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  3500. if (ret != 0)
  3501. return ret;
  3502. #endif
  3503. #ifdef HAVE_PK_CALLBACKS
  3504. if (ssl->ctx->RsaEncCb) {
  3505. void* ctx = wolfSSL_GetRsaEncCtx(ssl);
  3506. ret = ssl->ctx->RsaEncCb(ssl, in, inSz, out, outSz, keyBuf, keySz, ctx);
  3507. }
  3508. else
  3509. #endif /* HAVE_PK_CALLBACKS */
  3510. {
  3511. ret = wc_RsaPublicEncrypt(in, inSz, out, *outSz, key, ssl->rng);
  3512. }
  3513. /* Handle async pending response */
  3514. #ifdef WOLFSSL_ASYNC_CRYPT
  3515. if (ret == WC_PENDING_E) {
  3516. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  3517. }
  3518. #endif /* WOLFSSL_ASYNC_CRYPT */
  3519. /* For positive response return in outSz */
  3520. if (ret > 0) {
  3521. *outSz = ret;
  3522. ret = 0;
  3523. }
  3524. WOLFSSL_LEAVE("RsaEnc", ret);
  3525. return ret;
  3526. }
  3527. #endif /* !WOLFSSL_NO_TLS12 */
  3528. #endif /* NO_RSA */
  3529. #ifdef HAVE_ECC
  3530. int EccSign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
  3531. word32* outSz, ecc_key* key, DerBuffer* keyBufInfo)
  3532. {
  3533. int ret;
  3534. #ifdef HAVE_PK_CALLBACKS
  3535. const byte* keyBuf = NULL;
  3536. word32 keySz = 0;
  3537. if (keyBufInfo) {
  3538. keyBuf = keyBufInfo->buffer;
  3539. keySz = keyBufInfo->length;
  3540. }
  3541. #endif
  3542. (void)ssl;
  3543. (void)keyBufInfo;
  3544. WOLFSSL_ENTER("EccSign");
  3545. #ifdef WOLFSSL_ASYNC_CRYPT
  3546. /* initialize event */
  3547. if (key) {
  3548. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  3549. if (ret != 0)
  3550. return ret;
  3551. }
  3552. #endif
  3553. #if defined(HAVE_PK_CALLBACKS)
  3554. if (ssl->ctx->EccSignCb) {
  3555. void* ctx = wolfSSL_GetEccSignCtx(ssl);
  3556. ret = ssl->ctx->EccSignCb(ssl, in, inSz, out, outSz, keyBuf,
  3557. keySz, ctx);
  3558. }
  3559. else
  3560. #endif /* HAVE_PK_CALLBACKS */
  3561. {
  3562. ret = wc_ecc_sign_hash(in, inSz, out, outSz, ssl->rng, key);
  3563. }
  3564. /* Handle async pending response */
  3565. #ifdef WOLFSSL_ASYNC_CRYPT
  3566. if (key && ret == WC_PENDING_E) {
  3567. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  3568. }
  3569. #endif /* WOLFSSL_ASYNC_CRYPT */
  3570. WOLFSSL_LEAVE("EccSign", ret);
  3571. return ret;
  3572. }
  3573. int EccVerify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* out,
  3574. word32 outSz, ecc_key* key, buffer* keyBufInfo)
  3575. {
  3576. int ret;
  3577. #ifdef HAVE_PK_CALLBACKS
  3578. const byte* keyBuf = NULL;
  3579. word32 keySz = 0;
  3580. if (keyBufInfo) {
  3581. keyBuf = keyBufInfo->buffer;
  3582. keySz = keyBufInfo->length;
  3583. }
  3584. #endif
  3585. (void)ssl;
  3586. (void)keyBufInfo;
  3587. WOLFSSL_ENTER("EccVerify");
  3588. #ifdef WOLFSSL_ASYNC_CRYPT
  3589. /* initialize event */
  3590. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  3591. if (ret != 0)
  3592. return ret;
  3593. #endif
  3594. #ifdef HAVE_PK_CALLBACKS
  3595. if (ssl->ctx->EccVerifyCb) {
  3596. void* ctx = wolfSSL_GetEccVerifyCtx(ssl);
  3597. ret = ssl->ctx->EccVerifyCb(ssl, in, inSz, out, outSz, keyBuf, keySz,
  3598. &ssl->eccVerifyRes, ctx);
  3599. }
  3600. else
  3601. #endif /* HAVE_PK_CALLBACKS */
  3602. {
  3603. ret = wc_ecc_verify_hash(in, inSz, out, outSz, &ssl->eccVerifyRes, key);
  3604. }
  3605. /* Handle async pending response */
  3606. #ifdef WOLFSSL_ASYNC_CRYPT
  3607. if (ret == WC_PENDING_E) {
  3608. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  3609. }
  3610. else
  3611. #endif /* WOLFSSL_ASYNC_CRYPT */
  3612. {
  3613. ret = (ret != 0 || ssl->eccVerifyRes == 0) ? VERIFY_SIGN_ERROR : 0;
  3614. }
  3615. WOLFSSL_LEAVE("EccVerify", ret);
  3616. return ret;
  3617. }
  3618. #ifdef HAVE_PK_CALLBACKS
  3619. /* Gets ECC key for shared secret callback testing
  3620. * Client side: returns peer key
  3621. * Server side: returns private key
  3622. */
  3623. static int EccGetKey(WOLFSSL* ssl, ecc_key** otherKey)
  3624. {
  3625. int ret = NO_PEER_KEY;
  3626. ecc_key* tmpKey = NULL;
  3627. if (ssl == NULL || otherKey == NULL) {
  3628. return BAD_FUNC_ARG;
  3629. }
  3630. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  3631. if (ssl->specs.static_ecdh) {
  3632. if (!ssl->peerEccDsaKey || !ssl->peerEccDsaKeyPresent ||
  3633. !ssl->peerEccDsaKey->dp) {
  3634. return NO_PEER_KEY;
  3635. }
  3636. tmpKey = (struct ecc_key*)ssl->peerEccDsaKey;
  3637. }
  3638. else {
  3639. if (!ssl->peerEccKey || !ssl->peerEccKeyPresent ||
  3640. !ssl->peerEccKey->dp) {
  3641. return NO_PEER_KEY;
  3642. }
  3643. tmpKey = (struct ecc_key*)ssl->peerEccKey;
  3644. }
  3645. }
  3646. else if (ssl->options.side == WOLFSSL_SERVER_END) {
  3647. if (ssl->specs.static_ecdh) {
  3648. if (ssl->hsKey == NULL) {
  3649. return NO_PRIVATE_KEY;
  3650. }
  3651. tmpKey = (struct ecc_key*)ssl->hsKey;
  3652. }
  3653. else {
  3654. if (!ssl->eccTempKeyPresent) {
  3655. return NO_PRIVATE_KEY;
  3656. }
  3657. tmpKey = (struct ecc_key*)ssl->eccTempKey;
  3658. }
  3659. }
  3660. if (tmpKey) {
  3661. *otherKey = tmpKey;
  3662. ret = 0;
  3663. }
  3664. return ret;
  3665. }
  3666. #endif /* HAVE_PK_CALLBACKS */
  3667. int EccSharedSecret(WOLFSSL* ssl, ecc_key* priv_key, ecc_key* pub_key,
  3668. byte* pubKeyDer, word32* pubKeySz, byte* out, word32* outlen,
  3669. int side)
  3670. {
  3671. int ret;
  3672. #ifdef HAVE_PK_CALLBACKS
  3673. ecc_key* otherKey = NULL;
  3674. #endif
  3675. #ifdef WOLFSSL_ASYNC_CRYPT
  3676. WC_ASYNC_DEV* asyncDev = &priv_key->asyncDev;
  3677. #endif
  3678. (void)ssl;
  3679. (void)pubKeyDer;
  3680. (void)pubKeySz;
  3681. (void)side;
  3682. WOLFSSL_ENTER("EccSharedSecret");
  3683. #ifdef HAVE_PK_CALLBACKS
  3684. if (ssl->ctx->EccSharedSecretCb) {
  3685. ret = EccGetKey(ssl, &otherKey);
  3686. if (ret != 0)
  3687. return ret;
  3688. #ifdef WOLFSSL_ASYNC_CRYPT
  3689. asyncDev = &otherKey->asyncDev;
  3690. #endif
  3691. }
  3692. #endif
  3693. #ifdef WOLFSSL_ASYNC_CRYPT
  3694. /* initialize event */
  3695. ret = wolfSSL_AsyncInit(ssl, asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  3696. if (ret != 0)
  3697. return ret;
  3698. #endif
  3699. #ifdef HAVE_PK_CALLBACKS
  3700. if (ssl->ctx->EccSharedSecretCb) {
  3701. void* ctx = wolfSSL_GetEccSharedSecretCtx(ssl);
  3702. ret = ssl->ctx->EccSharedSecretCb(ssl, otherKey, pubKeyDer,
  3703. pubKeySz, out, outlen, side, ctx);
  3704. }
  3705. else
  3706. #endif
  3707. {
  3708. ret = wc_ecc_shared_secret(priv_key, pub_key, out, outlen);
  3709. }
  3710. /* Handle async pending response */
  3711. #ifdef WOLFSSL_ASYNC_CRYPT
  3712. if (ret == WC_PENDING_E) {
  3713. ret = wolfSSL_AsyncPush(ssl, asyncDev);
  3714. }
  3715. #endif /* WOLFSSL_ASYNC_CRYPT */
  3716. WOLFSSL_LEAVE("EccSharedSecret", ret);
  3717. return ret;
  3718. }
  3719. int EccMakeKey(WOLFSSL* ssl, ecc_key* key, ecc_key* peer)
  3720. {
  3721. int ret = 0;
  3722. int keySz = 0;
  3723. int ecc_curve = ECC_CURVE_DEF;
  3724. WOLFSSL_ENTER("EccMakeKey");
  3725. #ifdef WOLFSSL_ASYNC_CRYPT
  3726. /* initialize event */
  3727. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_NONE);
  3728. if (ret != 0)
  3729. return ret;
  3730. #endif
  3731. /* get key size */
  3732. if (peer == NULL) {
  3733. keySz = ssl->eccTempKeySz;
  3734. }
  3735. else {
  3736. keySz = peer->dp->size;
  3737. }
  3738. /* get curve type */
  3739. if (ssl->ecdhCurveOID > 0) {
  3740. ecc_curve = wc_ecc_get_oid(ssl->ecdhCurveOID, NULL, NULL);
  3741. }
  3742. #ifdef HAVE_PK_CALLBACKS
  3743. if (ssl->ctx->EccKeyGenCb) {
  3744. void* ctx = wolfSSL_GetEccKeyGenCtx(ssl);
  3745. ret = ssl->ctx->EccKeyGenCb(ssl, key, keySz, ecc_curve, ctx);
  3746. }
  3747. else
  3748. #endif
  3749. {
  3750. ret = wc_ecc_make_key_ex(ssl->rng, keySz, key, ecc_curve);
  3751. }
  3752. /* make sure the curve is set for TLS */
  3753. if (ret == 0 && key->dp) {
  3754. ssl->ecdhCurveOID = key->dp->oidSum;
  3755. #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
  3756. ssl->namedGroup = 0;
  3757. #endif
  3758. }
  3759. /* Handle async pending response */
  3760. #ifdef WOLFSSL_ASYNC_CRYPT
  3761. if (ret == WC_PENDING_E) {
  3762. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  3763. }
  3764. #endif /* WOLFSSL_ASYNC_CRYPT */
  3765. WOLFSSL_LEAVE("EccMakeKey", ret);
  3766. return ret;
  3767. }
  3768. #endif /* HAVE_ECC */
  3769. #ifdef HAVE_ED25519
  3770. /* Check whether the key contains a public key.
  3771. * If not then pull it out of the leaf certificate.
  3772. *
  3773. * ssl SSL/TLS object.
  3774. * returns MEMORY_E when unable to allocate memory, a parsing error, otherwise
  3775. * 0 on success.
  3776. */
  3777. int Ed25519CheckPubKey(WOLFSSL* ssl)
  3778. {
  3779. ed25519_key* key = (ed25519_key*)ssl->hsKey;
  3780. int ret = 0;
  3781. /* Public key required for signing. */
  3782. if (!key->pubKeySet) {
  3783. DerBuffer* leaf = ssl->buffers.certificate;
  3784. DecodedCert* cert = (DecodedCert*)XMALLOC(sizeof(*cert),
  3785. ssl->heap, DYNAMIC_TYPE_DCERT);
  3786. if (cert == NULL)
  3787. ret = MEMORY_E;
  3788. if (ret == 0) {
  3789. InitDecodedCert(cert, leaf->buffer, leaf->length, ssl->heap);
  3790. ret = DecodeToKey(cert, 0);
  3791. }
  3792. if (ret == 0) {
  3793. ret = wc_ed25519_import_public(cert->publicKey, cert->pubKeySize,
  3794. key);
  3795. }
  3796. if (cert != NULL) {
  3797. FreeDecodedCert(cert);
  3798. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  3799. }
  3800. }
  3801. return ret;
  3802. }
  3803. /* Sign the data using EdDSA and key using Ed25519.
  3804. *
  3805. * ssl SSL object.
  3806. * in Data or message to sign.
  3807. * inSz Length of the data.
  3808. * out Buffer to hold signature.
  3809. * outSz On entry, size of the buffer. On exit, the size of the signature.
  3810. * key The private Ed25519 key data.
  3811. * keySz The length of the private key data in bytes.
  3812. * ctx The callback context.
  3813. * returns 0 on success, otherwise the value is an error.
  3814. */
  3815. int Ed25519Sign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
  3816. word32* outSz, ed25519_key* key, DerBuffer* keyBufInfo)
  3817. {
  3818. int ret;
  3819. #ifdef HAVE_PK_CALLBACKS
  3820. const byte* keyBuf = NULL;
  3821. word32 keySz = 0;
  3822. if (keyBufInfo) {
  3823. keyBuf = keyBufInfo->buffer;
  3824. keySz = keyBufInfo->length;
  3825. }
  3826. #endif
  3827. (void)ssl;
  3828. (void)keyBufInfo;
  3829. WOLFSSL_ENTER("Ed25519Sign");
  3830. #ifdef WOLFSSL_ASYNC_CRYPT
  3831. /* initialize event */
  3832. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  3833. if (ret != 0)
  3834. return ret;
  3835. #endif
  3836. #if defined(HAVE_PK_CALLBACKS)
  3837. if (ssl->ctx->Ed25519SignCb) {
  3838. void* ctx = wolfSSL_GetEd25519SignCtx(ssl);
  3839. ret = ssl->ctx->Ed25519SignCb(ssl, in, inSz, out, outSz, keyBuf,
  3840. keySz, ctx);
  3841. }
  3842. else
  3843. #endif /* HAVE_PK_CALLBACKS */
  3844. {
  3845. ret = wc_ed25519_sign_msg(in, inSz, out, outSz, key);
  3846. }
  3847. /* Handle async pending response */
  3848. #ifdef WOLFSSL_ASYNC_CRYPT
  3849. if (ret == WC_PENDING_E) {
  3850. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  3851. }
  3852. #endif /* WOLFSSL_ASYNC_CRYPT */
  3853. WOLFSSL_LEAVE("Ed25519Sign", ret);
  3854. return ret;
  3855. }
  3856. /* Verify the data using EdDSA and key using Ed25519.
  3857. *
  3858. * ssl SSL object.
  3859. * in Signature data.
  3860. * inSz Length of the signature data in bytes.
  3861. * msg Message to verify.
  3862. * outSz Length of message in bytes.
  3863. * key The public Ed25519 key data.
  3864. * keySz The length of the private key data in bytes.
  3865. * ctx The callback context.
  3866. * returns 0 on success, otherwise the value is an error.
  3867. */
  3868. int Ed25519Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg,
  3869. word32 msgSz, ed25519_key* key, buffer* keyBufInfo)
  3870. {
  3871. int ret;
  3872. #ifdef HAVE_PK_CALLBACKS
  3873. const byte* keyBuf = NULL;
  3874. word32 keySz = 0;
  3875. if (keyBufInfo) {
  3876. keyBuf = keyBufInfo->buffer;
  3877. keySz = keyBufInfo->length;
  3878. }
  3879. #endif
  3880. (void)ssl;
  3881. (void)keyBufInfo;
  3882. WOLFSSL_ENTER("Ed25519Verify");
  3883. #ifdef WOLFSSL_ASYNC_CRYPT
  3884. /* initialize event */
  3885. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  3886. if (ret != 0)
  3887. return ret;
  3888. #endif
  3889. #ifdef HAVE_PK_CALLBACKS
  3890. if (ssl->ctx->Ed25519VerifyCb) {
  3891. void* ctx = wolfSSL_GetEd25519VerifyCtx(ssl);
  3892. ret = ssl->ctx->Ed25519VerifyCb(ssl, in, inSz, msg, msgSz, keyBuf,
  3893. keySz, &ssl->eccVerifyRes, ctx);
  3894. }
  3895. else
  3896. #endif /* HAVE_PK_CALLBACKS */
  3897. {
  3898. ret = wc_ed25519_verify_msg(in, inSz, msg, msgSz,
  3899. &ssl->eccVerifyRes, key);
  3900. }
  3901. /* Handle async pending response */
  3902. #ifdef WOLFSSL_ASYNC_CRYPT
  3903. if (ret == WC_PENDING_E) {
  3904. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  3905. }
  3906. else
  3907. #endif /* WOLFSSL_ASYNC_CRYPT */
  3908. {
  3909. ret = (ret != 0 || ssl->eccVerifyRes == 0) ? VERIFY_SIGN_ERROR : 0;
  3910. }
  3911. WOLFSSL_LEAVE("Ed25519Verify", ret);
  3912. return ret;
  3913. }
  3914. #endif /* HAVE_ED25519 */
  3915. #ifndef WOLFSSL_NO_TLS12
  3916. #ifdef HAVE_CURVE25519
  3917. #ifdef HAVE_PK_CALLBACKS
  3918. /* Gets X25519 key for shared secret callback testing
  3919. * Client side: returns peer key
  3920. * Server side: returns private key
  3921. */
  3922. static int X25519GetKey(WOLFSSL* ssl, curve25519_key** otherKey)
  3923. {
  3924. int ret = NO_PEER_KEY;
  3925. struct curve25519_key* tmpKey = NULL;
  3926. if (ssl == NULL || otherKey == NULL) {
  3927. return BAD_FUNC_ARG;
  3928. }
  3929. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  3930. if (!ssl->peerX25519Key || !ssl->peerX25519KeyPresent ||
  3931. !ssl->peerX25519Key->dp) {
  3932. return NO_PEER_KEY;
  3933. }
  3934. tmpKey = (struct curve25519_key*)ssl->peerX25519Key;
  3935. }
  3936. else if (ssl->options.side == WOLFSSL_SERVER_END) {
  3937. if (!ssl->eccTempKeyPresent) {
  3938. return NO_PRIVATE_KEY;
  3939. }
  3940. tmpKey = (struct curve25519_key*)ssl->eccTempKey;
  3941. }
  3942. if (tmpKey) {
  3943. *otherKey = (curve25519_key *)tmpKey;
  3944. ret = 0;
  3945. }
  3946. return ret;
  3947. }
  3948. #endif /* HAVE_PK_CALLBACKS */
  3949. static int X25519SharedSecret(WOLFSSL* ssl, curve25519_key* priv_key,
  3950. curve25519_key* pub_key, byte* pubKeyDer, word32* pubKeySz,
  3951. byte* out, word32* outlen, int side)
  3952. {
  3953. int ret;
  3954. (void)ssl;
  3955. (void)pubKeyDer;
  3956. (void)pubKeySz;
  3957. (void)side;
  3958. WOLFSSL_ENTER("X25519SharedSecret");
  3959. #ifdef WOLFSSL_ASYNC_CRYPT
  3960. /* initialize event */
  3961. ret = wolfSSL_AsyncInit(ssl, &priv_key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  3962. if (ret != 0)
  3963. return ret;
  3964. #endif
  3965. #ifdef HAVE_PK_CALLBACKS
  3966. if (ssl->ctx->X25519SharedSecretCb) {
  3967. curve25519_key* otherKey = NULL;
  3968. ret = X25519GetKey(ssl, &otherKey);
  3969. if (ret == 0) {
  3970. void* ctx = wolfSSL_GetX25519SharedSecretCtx(ssl);
  3971. ret = ssl->ctx->X25519SharedSecretCb(ssl, otherKey, pubKeyDer,
  3972. pubKeySz, out, outlen, side, ctx);
  3973. }
  3974. }
  3975. else
  3976. #endif
  3977. {
  3978. ret = wc_curve25519_shared_secret_ex(priv_key, pub_key, out, outlen,
  3979. EC25519_LITTLE_ENDIAN);
  3980. }
  3981. /* Handle async pending response */
  3982. #ifdef WOLFSSL_ASYNC_CRYPT
  3983. if (ret == WC_PENDING_E) {
  3984. ret = wolfSSL_AsyncPush(ssl, &priv_key->asyncDev);
  3985. }
  3986. #endif /* WOLFSSL_ASYNC_CRYPT */
  3987. WOLFSSL_LEAVE("X25519SharedSecret", ret);
  3988. return ret;
  3989. }
  3990. static int X25519MakeKey(WOLFSSL* ssl, curve25519_key* key,
  3991. curve25519_key* peer)
  3992. {
  3993. int ret = 0;
  3994. (void)peer;
  3995. WOLFSSL_ENTER("X25519MakeKey");
  3996. #ifdef WOLFSSL_ASYNC_CRYPT
  3997. /* initialize event */
  3998. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_NONE);
  3999. if (ret != 0)
  4000. return ret;
  4001. #endif
  4002. #ifdef HAVE_PK_CALLBACKS
  4003. if (ssl->ctx->X25519KeyGenCb) {
  4004. void* ctx = wolfSSL_GetX25519KeyGenCtx(ssl);
  4005. ret = ssl->ctx->X25519KeyGenCb(ssl, key, CURVE25519_KEYSIZE, ctx);
  4006. }
  4007. else
  4008. #endif
  4009. {
  4010. ret = wc_curve25519_make_key(ssl->rng, CURVE25519_KEYSIZE, key);
  4011. }
  4012. if (ret == 0) {
  4013. ssl->ecdhCurveOID = ECC_X25519_OID;
  4014. #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
  4015. ssl->namedGroup = 0;
  4016. #endif
  4017. }
  4018. /* Handle async pending response */
  4019. #ifdef WOLFSSL_ASYNC_CRYPT
  4020. if (ret == WC_PENDING_E) {
  4021. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  4022. }
  4023. #endif /* WOLFSSL_ASYNC_CRYPT */
  4024. WOLFSSL_LEAVE("X25519MakeKey", ret);
  4025. return ret;
  4026. }
  4027. #endif /* HAVE_CURVE25519 */
  4028. #ifdef HAVE_ED448
  4029. /* Check whether the key contains a public key.
  4030. * If not then pull it out of the leaf certificate.
  4031. *
  4032. * ssl SSL/TLS object.
  4033. * returns MEMORY_E when unable to allocate memory, a parsing error, otherwise
  4034. * 0 on success.
  4035. */
  4036. int Ed448CheckPubKey(WOLFSSL* ssl)
  4037. {
  4038. ed448_key* key = (ed448_key*)ssl->hsKey;
  4039. int ret = 0;
  4040. /* Public key required for signing. */
  4041. if (!key->pubKeySet) {
  4042. DerBuffer* leaf = ssl->buffers.certificate;
  4043. DecodedCert* cert = (DecodedCert*)XMALLOC(sizeof(*cert), ssl->heap,
  4044. DYNAMIC_TYPE_DCERT);
  4045. if (cert == NULL)
  4046. ret = MEMORY_E;
  4047. if (ret == 0) {
  4048. InitDecodedCert(cert, leaf->buffer, leaf->length, ssl->heap);
  4049. ret = DecodeToKey(cert, 0);
  4050. }
  4051. if (ret == 0) {
  4052. ret = wc_ed448_import_public(cert->publicKey, cert->pubKeySize,
  4053. key);
  4054. }
  4055. if (cert != NULL) {
  4056. FreeDecodedCert(cert);
  4057. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  4058. }
  4059. }
  4060. return ret;
  4061. }
  4062. /* Sign the data using EdDSA and key using Ed448.
  4063. *
  4064. * ssl SSL object.
  4065. * in Data or message to sign.
  4066. * inSz Length of the data.
  4067. * out Buffer to hold signature.
  4068. * outSz On entry, size of the buffer. On exit, the size of the signature.
  4069. * key The private Ed448 key data.
  4070. * keySz The length of the private key data in bytes.
  4071. * ctx The callback context.
  4072. * returns 0 on success, otherwise the value is an error.
  4073. */
  4074. int Ed448Sign(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
  4075. word32* outSz, ed448_key* key, DerBuffer* keyBufInfo)
  4076. {
  4077. int ret;
  4078. #ifdef HAVE_PK_CALLBACKS
  4079. const byte* keyBuf = NULL;
  4080. word32 keySz = 0;
  4081. if (keyBufInfo) {
  4082. keyBuf = keyBufInfo->buffer;
  4083. keySz = keyBufInfo->length;
  4084. }
  4085. #endif
  4086. (void)ssl;
  4087. (void)keyBufInfo;
  4088. WOLFSSL_ENTER("Ed448Sign");
  4089. #ifdef WOLFSSL_ASYNC_CRYPT
  4090. /* initialize event */
  4091. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  4092. if (ret != 0)
  4093. return ret;
  4094. #endif
  4095. #if defined(HAVE_PK_CALLBACKS)
  4096. if (ssl->ctx->Ed448SignCb) {
  4097. void* ctx = wolfSSL_GetEd448SignCtx(ssl);
  4098. ret = ssl->ctx->Ed448SignCb(ssl, in, inSz, out, outSz, keyBuf, keySz,
  4099. ctx);
  4100. }
  4101. else
  4102. #endif /* HAVE_PK_CALLBACKS */
  4103. {
  4104. ret = wc_ed448_sign_msg(in, inSz, out, outSz, key, NULL, 0);
  4105. }
  4106. /* Handle async pending response */
  4107. #ifdef WOLFSSL_ASYNC_CRYPT
  4108. if (ret == WC_PENDING_E) {
  4109. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  4110. }
  4111. #endif /* WOLFSSL_ASYNC_CRYPT */
  4112. WOLFSSL_LEAVE("Ed448Sign", ret);
  4113. return ret;
  4114. }
  4115. /* Verify the data using EdDSA and key using Ed448.
  4116. *
  4117. * ssl SSL object.
  4118. * in Signature data.
  4119. * inSz Length of the signature data in bytes.
  4120. * msg Message to verify.
  4121. * outSz Length of message in bytes.
  4122. * key The public Ed448 key data.
  4123. * keySz The length of the private key data in bytes.
  4124. * ctx The callback context.
  4125. * returns 0 on success, otherwise the value is an error.
  4126. */
  4127. int Ed448Verify(WOLFSSL* ssl, const byte* in, word32 inSz, const byte* msg,
  4128. word32 msgSz, ed448_key* key, buffer* keyBufInfo)
  4129. {
  4130. int ret;
  4131. #ifdef HAVE_PK_CALLBACKS
  4132. const byte* keyBuf = NULL;
  4133. word32 keySz = 0;
  4134. if (keyBufInfo) {
  4135. keyBuf = keyBufInfo->buffer;
  4136. keySz = keyBufInfo->length;
  4137. }
  4138. #endif
  4139. (void)ssl;
  4140. (void)keyBufInfo;
  4141. WOLFSSL_ENTER("Ed448Verify");
  4142. #ifdef WOLFSSL_ASYNC_CRYPT
  4143. /* initialize event */
  4144. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  4145. if (ret != 0)
  4146. return ret;
  4147. #endif
  4148. #ifdef HAVE_PK_CALLBACKS
  4149. if (ssl->ctx->Ed448VerifyCb) {
  4150. void* ctx = wolfSSL_GetEd448VerifyCtx(ssl);
  4151. ret = ssl->ctx->Ed448VerifyCb(ssl, in, inSz, msg, msgSz, keyBuf, keySz,
  4152. &ssl->eccVerifyRes, ctx);
  4153. }
  4154. else
  4155. #endif /* HAVE_PK_CALLBACKS */
  4156. {
  4157. ret = wc_ed448_verify_msg(in, inSz, msg, msgSz, &ssl->eccVerifyRes, key,
  4158. NULL, 0);
  4159. }
  4160. /* Handle async pending response */
  4161. #ifdef WOLFSSL_ASYNC_CRYPT
  4162. if (ret == WC_PENDING_E) {
  4163. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  4164. }
  4165. else
  4166. #endif /* WOLFSSL_ASYNC_CRYPT */
  4167. {
  4168. ret = (ret != 0 || ssl->eccVerifyRes == 0) ? VERIFY_SIGN_ERROR : 0;
  4169. }
  4170. WOLFSSL_LEAVE("Ed448Verify", ret);
  4171. return ret;
  4172. }
  4173. #endif /* HAVE_ED448 */
  4174. #ifdef HAVE_CURVE448
  4175. #ifdef HAVE_PK_CALLBACKS
  4176. /* Gets X448 key for shared secret callback testing
  4177. * Client side: returns peer key
  4178. * Server side: returns private key
  4179. */
  4180. static int X448GetKey(WOLFSSL* ssl, curve448_key** otherKey)
  4181. {
  4182. int ret = NO_PEER_KEY;
  4183. struct curve448_key* tmpKey = NULL;
  4184. if (ssl == NULL || otherKey == NULL) {
  4185. return BAD_FUNC_ARG;
  4186. }
  4187. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  4188. if (!ssl->peerX448Key || !ssl->peerX448KeyPresent) {
  4189. return NO_PEER_KEY;
  4190. }
  4191. tmpKey = (struct curve448_key*)ssl->peerX448Key;
  4192. }
  4193. else if (ssl->options.side == WOLFSSL_SERVER_END) {
  4194. if (!ssl->eccTempKeyPresent) {
  4195. return NO_PRIVATE_KEY;
  4196. }
  4197. tmpKey = (struct curve448_key*)ssl->eccTempKey;
  4198. }
  4199. if (tmpKey) {
  4200. *otherKey = (curve448_key *)tmpKey;
  4201. ret = 0;
  4202. }
  4203. return ret;
  4204. }
  4205. #endif /* HAVE_PK_CALLBACKS */
  4206. static int X448SharedSecret(WOLFSSL* ssl, curve448_key* priv_key,
  4207. curve448_key* pub_key, byte* pubKeyDer,
  4208. word32* pubKeySz, byte* out, word32* outlen,
  4209. int side)
  4210. {
  4211. int ret;
  4212. (void)ssl;
  4213. (void)pubKeyDer;
  4214. (void)pubKeySz;
  4215. (void)side;
  4216. WOLFSSL_ENTER("X448SharedSecret");
  4217. #ifdef WOLFSSL_ASYNC_CRYPT
  4218. /* initialize event */
  4219. ret = wolfSSL_AsyncInit(ssl, &priv_key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  4220. if (ret != 0)
  4221. return ret;
  4222. #endif
  4223. #ifdef HAVE_PK_CALLBACKS
  4224. if (ssl->ctx->X448SharedSecretCb) {
  4225. curve448_key* otherKey = NULL;
  4226. ret = X448GetKey(ssl, &otherKey);
  4227. if (ret == 0) {
  4228. void* ctx = wolfSSL_GetX448SharedSecretCtx(ssl);
  4229. ret = ssl->ctx->X448SharedSecretCb(ssl, otherKey, pubKeyDer,
  4230. pubKeySz, out, outlen, side, ctx);
  4231. }
  4232. }
  4233. else
  4234. #endif
  4235. {
  4236. ret = wc_curve448_shared_secret_ex(priv_key, pub_key, out, outlen,
  4237. EC448_LITTLE_ENDIAN);
  4238. }
  4239. /* Handle async pending response */
  4240. #ifdef WOLFSSL_ASYNC_CRYPT
  4241. if (ret == WC_PENDING_E) {
  4242. ret = wolfSSL_AsyncPush(ssl, &priv_key->asyncDev);
  4243. }
  4244. #endif /* WOLFSSL_ASYNC_CRYPT */
  4245. WOLFSSL_LEAVE("X448SharedSecret", ret);
  4246. return ret;
  4247. }
  4248. static int X448MakeKey(WOLFSSL* ssl, curve448_key* key, curve448_key* peer)
  4249. {
  4250. int ret = 0;
  4251. (void)peer;
  4252. WOLFSSL_ENTER("X448MakeKey");
  4253. #ifdef WOLFSSL_ASYNC_CRYPT
  4254. /* initialize event */
  4255. ret = wolfSSL_AsyncInit(ssl, &key->asyncDev, WC_ASYNC_FLAG_NONE);
  4256. if (ret != 0)
  4257. return ret;
  4258. #endif
  4259. #ifdef HAVE_PK_CALLBACKS
  4260. if (ssl->ctx->X448KeyGenCb) {
  4261. void* ctx = wolfSSL_GetX448KeyGenCtx(ssl);
  4262. ret = ssl->ctx->X448KeyGenCb(ssl, key, CURVE448_KEY_SIZE, ctx);
  4263. }
  4264. else
  4265. #endif
  4266. {
  4267. ret = wc_curve448_make_key(ssl->rng, CURVE448_KEY_SIZE, key);
  4268. }
  4269. if (ret == 0) {
  4270. ssl->ecdhCurveOID = ECC_X448_OID;
  4271. #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
  4272. ssl->namedGroup = 0;
  4273. #endif
  4274. }
  4275. /* Handle async pending response */
  4276. #ifdef WOLFSSL_ASYNC_CRYPT
  4277. if (ret == WC_PENDING_E) {
  4278. ret = wolfSSL_AsyncPush(ssl, &key->asyncDev);
  4279. }
  4280. #endif /* WOLFSSL_ASYNC_CRYPT */
  4281. WOLFSSL_LEAVE("X448MakeKey", ret);
  4282. return ret;
  4283. }
  4284. #endif /* HAVE_CURVE448 */
  4285. #if !defined(NO_CERTS) || !defined(NO_PSK)
  4286. #if !defined(NO_DH)
  4287. int DhGenKeyPair(WOLFSSL* ssl, DhKey* dhKey,
  4288. byte* priv, word32* privSz,
  4289. byte* pub, word32* pubSz)
  4290. {
  4291. int ret;
  4292. WOLFSSL_ENTER("DhGenKeyPair");
  4293. #ifdef WOLFSSL_ASYNC_CRYPT
  4294. /* initialize event */
  4295. ret = wolfSSL_AsyncInit(ssl, &dhKey->asyncDev, WC_ASYNC_FLAG_NONE);
  4296. if (ret != 0)
  4297. return ret;
  4298. #endif
  4299. ret = wc_DhGenerateKeyPair(dhKey, ssl->rng, priv, privSz, pub, pubSz);
  4300. /* Handle async pending response */
  4301. #ifdef WOLFSSL_ASYNC_CRYPT
  4302. if (ret == WC_PENDING_E) {
  4303. ret = wolfSSL_AsyncPush(ssl, &dhKey->asyncDev);
  4304. }
  4305. #endif /* WOLFSSL_ASYNC_CRYPT */
  4306. WOLFSSL_LEAVE("DhGenKeyPair", ret);
  4307. return ret;
  4308. }
  4309. int DhAgree(WOLFSSL* ssl, DhKey* dhKey,
  4310. const byte* priv, word32 privSz,
  4311. const byte* otherPub, word32 otherPubSz,
  4312. byte* agree, word32* agreeSz)
  4313. {
  4314. int ret;
  4315. (void)ssl;
  4316. WOLFSSL_ENTER("DhAgree");
  4317. #ifdef WOLFSSL_ASYNC_CRYPT
  4318. /* initialize event */
  4319. ret = wolfSSL_AsyncInit(ssl, &dhKey->asyncDev, WC_ASYNC_FLAG_NONE);
  4320. if (ret != 0)
  4321. return ret;
  4322. #endif
  4323. #ifdef HAVE_PK_CALLBACKS
  4324. if (ssl->ctx->DhAgreeCb) {
  4325. void* ctx = wolfSSL_GetDhAgreeCtx(ssl);
  4326. WOLFSSL_MSG("Calling DhAgree Callback Function");
  4327. ret = ssl->ctx->DhAgreeCb(ssl, dhKey, priv, privSz,
  4328. otherPub, otherPubSz, agree, agreeSz, ctx);
  4329. }
  4330. else
  4331. #endif
  4332. {
  4333. #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
  4334. ret = wc_DhCheckPubValue(ssl->buffers.serverDH_P.buffer,
  4335. ssl->buffers.serverDH_P.length, otherPub, otherPubSz);
  4336. if (ret != 0) {
  4337. #ifdef OPENSSL_EXTRA
  4338. SendAlert(ssl, alert_fatal, illegal_parameter);
  4339. #endif
  4340. }
  4341. else
  4342. #endif
  4343. {
  4344. ret = wc_DhAgree(dhKey, agree, agreeSz, priv, privSz, otherPub,
  4345. otherPubSz);
  4346. }
  4347. }
  4348. /* Handle async pending response */
  4349. #ifdef WOLFSSL_ASYNC_CRYPT
  4350. if (ret == WC_PENDING_E) {
  4351. ret = wolfSSL_AsyncPush(ssl, &dhKey->asyncDev);
  4352. }
  4353. #endif /* WOLFSSL_ASYNC_CRYPT */
  4354. WOLFSSL_LEAVE("DhAgree", ret);
  4355. return ret;
  4356. }
  4357. #endif /* !NO_DH */
  4358. #endif /* !NO_CERTS || !NO_PSK */
  4359. #endif /* !WOLFSSL_NO_TLS12 */
  4360. #ifdef HAVE_PK_CALLBACKS
  4361. int wolfSSL_IsPrivatePkSet(WOLFSSL* ssl)
  4362. {
  4363. int pkcbset = 0;
  4364. (void)ssl;
  4365. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  4366. !defined(NO_RSA)
  4367. if (0
  4368. #ifdef HAVE_ECC
  4369. || (ssl->ctx->EccSignCb != NULL &&
  4370. ssl->buffers.keyType == ecc_dsa_sa_algo)
  4371. #endif
  4372. #ifdef HAVE_ED25519
  4373. || (ssl->ctx->Ed25519SignCb != NULL &&
  4374. ssl->buffers.keyType == ed25519_sa_algo)
  4375. #endif
  4376. #ifdef HAVE_ED448
  4377. || (ssl->ctx->Ed448SignCb != NULL &&
  4378. ssl->buffers.keyType == ed448_sa_algo)
  4379. #endif
  4380. #ifndef NO_RSA
  4381. || (ssl->ctx->RsaSignCb != NULL && ssl->buffers.keyType == rsa_sa_algo)
  4382. || (ssl->ctx->RsaDecCb != NULL && ssl->buffers.keyType == rsa_kea)
  4383. #ifdef WC_RSA_PSS
  4384. || (ssl->ctx->RsaPssSignCb != NULL &&
  4385. ssl->buffers.keyType == rsa_pss_sa_algo)
  4386. #endif
  4387. #endif
  4388. ) {
  4389. pkcbset = 1;
  4390. }
  4391. #endif
  4392. return pkcbset;
  4393. }
  4394. int wolfSSL_CTX_IsPrivatePkSet(WOLFSSL_CTX* ctx)
  4395. {
  4396. int pkcbset = 0;
  4397. (void)ctx;
  4398. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  4399. !defined(NO_RSA)
  4400. if (0
  4401. #ifdef HAVE_ECC
  4402. || ctx->EccSignCb != NULL
  4403. #endif
  4404. #ifdef HAVE_ED25519
  4405. || ctx->Ed25519SignCb != NULL
  4406. #endif
  4407. #ifdef HAVE_ED448
  4408. || ctx->Ed448SignCb != NULL
  4409. #endif
  4410. #ifndef NO_RSA
  4411. || ctx->RsaSignCb != NULL
  4412. || ctx->RsaDecCb != NULL
  4413. #ifdef WC_RSA_PSS
  4414. || ctx->RsaPssSignCb != NULL
  4415. #endif
  4416. #endif
  4417. ) {
  4418. pkcbset = 1;
  4419. }
  4420. #endif
  4421. return pkcbset;
  4422. }
  4423. #endif /* HAVE_PK_CALLBACKS */
  4424. int InitSSL_Suites(WOLFSSL* ssl)
  4425. {
  4426. int keySz = 0;
  4427. byte havePSK = 0;
  4428. byte haveAnon = 0;
  4429. byte haveRSA = 0;
  4430. byte haveMcast = 0;
  4431. (void)haveAnon; /* Squash unused var warnings */
  4432. (void)haveMcast;
  4433. if (!ssl)
  4434. return BAD_FUNC_ARG;
  4435. #ifndef NO_RSA
  4436. haveRSA = 1;
  4437. #endif
  4438. #ifndef NO_PSK
  4439. havePSK = (byte)ssl->options.havePSK;
  4440. #endif /* NO_PSK */
  4441. #ifdef HAVE_ANON
  4442. haveAnon = (byte)ssl->options.haveAnon;
  4443. #endif /* HAVE_ANON*/
  4444. #ifdef WOLFSSL_MULTICAST
  4445. haveMcast = (byte)ssl->options.haveMcast;
  4446. #endif /* WOLFSSL_MULTICAST */
  4447. #ifdef WOLFSSL_EARLY_DATA
  4448. if (ssl->options.side == WOLFSSL_SERVER_END)
  4449. ssl->options.maxEarlyDataSz = ssl->ctx->maxEarlyDataSz;
  4450. #endif
  4451. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  4452. ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  4453. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  4454. ssl->options.cacheMessages = ssl->options.side == WOLFSSL_SERVER_END ||
  4455. ssl->buffers.keyType == ed25519_sa_algo ||
  4456. ssl->buffers.keyType == ed448_sa_algo;
  4457. #endif
  4458. #ifndef NO_CERTS
  4459. keySz = ssl->buffers.keySz;
  4460. #endif
  4461. /* make sure server has DH parms, and add PSK if there, add NTRU too */
  4462. if (ssl->options.side == WOLFSSL_SERVER_END) {
  4463. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
  4464. ssl->options.haveDH, ssl->options.haveNTRU,
  4465. ssl->options.haveECDSAsig, ssl->options.haveECC,
  4466. ssl->options.haveStaticECC, ssl->options.side);
  4467. }
  4468. else {
  4469. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
  4470. TRUE, ssl->options.haveNTRU,
  4471. ssl->options.haveECDSAsig, ssl->options.haveECC,
  4472. ssl->options.haveStaticECC, ssl->options.side);
  4473. }
  4474. #if !defined(NO_CERTS) && !defined(WOLFSSL_SESSION_EXPORT)
  4475. /* make sure server has cert and key unless using PSK, Anon, or
  4476. * Multicast. This should be true even if just switching ssl ctx */
  4477. if (ssl->options.side == WOLFSSL_SERVER_END &&
  4478. !havePSK && !haveAnon && !haveMcast) {
  4479. /* server certificate must be loaded */
  4480. if (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer) {
  4481. WOLFSSL_MSG("Server missing certificate");
  4482. return NO_PRIVATE_KEY;
  4483. }
  4484. /* allow no private key if using PK callbacks and CB is set */
  4485. #ifdef HAVE_PK_CALLBACKS
  4486. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
  4487. WOLFSSL_MSG("Using PK for server private key");
  4488. }
  4489. else
  4490. #endif
  4491. if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
  4492. WOLFSSL_MSG("Server missing private key");
  4493. return NO_PRIVATE_KEY;
  4494. }
  4495. }
  4496. #endif
  4497. return WOLFSSL_SUCCESS;
  4498. }
  4499. /* returns new reference count. Arg incr positive=up or negative=down */
  4500. int SSL_CTX_RefCount(WOLFSSL_CTX* ctx, int incr)
  4501. {
  4502. int refCount;
  4503. if (ctx == NULL) {
  4504. return BAD_FUNC_ARG;
  4505. }
  4506. if (wc_LockMutex(&ctx->countMutex) != 0) {
  4507. WOLFSSL_MSG("Couldn't lock CTX count mutex");
  4508. return BAD_MUTEX_E;
  4509. }
  4510. ctx->refCount += incr;
  4511. /* make sure refCount is never negative */
  4512. if (ctx->refCount < 0) {
  4513. ctx->refCount = 0;
  4514. }
  4515. refCount = ctx->refCount;
  4516. wc_UnLockMutex(&ctx->countMutex);
  4517. return refCount;
  4518. }
  4519. /* This function inherits a WOLFSSL_CTX's fields into an SSL object.
  4520. It is used during initialization and to switch an ssl's CTX with
  4521. wolfSSL_Set_SSL_CTX. Requires ssl->suites alloc and ssl-arrays with PSK
  4522. unless writeDup is on.
  4523. ssl object to initialize
  4524. ctx parent factory
  4525. writeDup flag indicating this is a write dup only
  4526. WOLFSSL_SUCCESS return value on success */
  4527. int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
  4528. {
  4529. int ret;
  4530. byte newSSL;
  4531. if (!ssl || !ctx)
  4532. return BAD_FUNC_ARG;
  4533. #ifndef SINGLE_THREADED
  4534. if (ssl->suites == NULL && !writeDup)
  4535. return BAD_FUNC_ARG;
  4536. #endif
  4537. newSSL = ssl->ctx == NULL; /* Assign after null check */
  4538. #ifndef NO_PSK
  4539. if (ctx->server_hint[0] && ssl->arrays == NULL && !writeDup) {
  4540. return BAD_FUNC_ARG; /* needed for copy below */
  4541. }
  4542. #endif
  4543. /* decrement previous CTX reference count if exists.
  4544. * This should only happen if switching ctxs!*/
  4545. if (!newSSL) {
  4546. WOLFSSL_MSG("freeing old ctx to decrement reference count. Switching ctx.");
  4547. wolfSSL_CTX_free(ssl->ctx);
  4548. }
  4549. /* increment CTX reference count */
  4550. if ((ret = SSL_CTX_RefCount(ctx, 1)) < 0) {
  4551. return ret;
  4552. }
  4553. ret = WOLFSSL_SUCCESS; /* set default ret */
  4554. ssl->ctx = ctx; /* only for passing to calls, options could change */
  4555. ssl->version = ctx->method->version;
  4556. #ifdef HAVE_ECC
  4557. ssl->eccTempKeySz = ctx->eccTempKeySz;
  4558. ssl->ecdhCurveOID = ctx->ecdhCurveOID;
  4559. #endif
  4560. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  4561. ssl->pkCurveOID = ctx->pkCurveOID;
  4562. #endif
  4563. #ifdef OPENSSL_EXTRA
  4564. ssl->options.mask = ctx->mask;
  4565. ssl->CBIS = ctx->CBIS;
  4566. #endif
  4567. ssl->timeout = ctx->timeout;
  4568. ssl->verifyCallback = ctx->verifyCallback;
  4569. ssl->options.side = ctx->method->side;
  4570. ssl->options.downgrade = ctx->method->downgrade;
  4571. ssl->options.minDowngrade = ctx->minDowngrade;
  4572. ssl->options.haveDH = ctx->haveDH;
  4573. ssl->options.haveNTRU = ctx->haveNTRU;
  4574. ssl->options.haveECDSAsig = ctx->haveECDSAsig;
  4575. ssl->options.haveECC = ctx->haveECC;
  4576. ssl->options.haveStaticECC = ctx->haveStaticECC;
  4577. #ifndef NO_PSK
  4578. ssl->options.havePSK = ctx->havePSK;
  4579. ssl->options.client_psk_cb = ctx->client_psk_cb;
  4580. ssl->options.server_psk_cb = ctx->server_psk_cb;
  4581. #ifdef WOLFSSL_TLS13
  4582. ssl->options.client_psk_tls13_cb = ctx->client_psk_tls13_cb;
  4583. ssl->options.server_psk_tls13_cb = ctx->server_psk_tls13_cb;
  4584. #endif
  4585. #endif /* NO_PSK */
  4586. #ifdef WOLFSSL_EARLY_DATA
  4587. if (ssl->options.side == WOLFSSL_SERVER_END)
  4588. ssl->options.maxEarlyDataSz = ctx->maxEarlyDataSz;
  4589. #endif
  4590. #ifdef HAVE_ANON
  4591. ssl->options.haveAnon = ctx->haveAnon;
  4592. #endif
  4593. #ifndef NO_DH
  4594. ssl->options.minDhKeySz = ctx->minDhKeySz;
  4595. ssl->options.maxDhKeySz = ctx->maxDhKeySz;
  4596. #endif
  4597. #ifndef NO_RSA
  4598. ssl->options.minRsaKeySz = ctx->minRsaKeySz;
  4599. #endif
  4600. #ifdef HAVE_ECC
  4601. ssl->options.minEccKeySz = ctx->minEccKeySz;
  4602. #endif
  4603. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  4604. ssl->options.verifyDepth = ctx->verifyDepth;
  4605. #endif
  4606. ssl->options.sessionCacheOff = ctx->sessionCacheOff;
  4607. ssl->options.sessionCacheFlushOff = ctx->sessionCacheFlushOff;
  4608. #ifdef HAVE_EXT_CACHE
  4609. ssl->options.internalCacheOff = ctx->internalCacheOff;
  4610. #endif
  4611. ssl->options.verifyPeer = ctx->verifyPeer;
  4612. ssl->options.verifyNone = ctx->verifyNone;
  4613. ssl->options.failNoCert = ctx->failNoCert;
  4614. ssl->options.failNoCertxPSK = ctx->failNoCertxPSK;
  4615. ssl->options.sendVerify = ctx->sendVerify;
  4616. ssl->options.partialWrite = ctx->partialWrite;
  4617. ssl->options.quietShutdown = ctx->quietShutdown;
  4618. ssl->options.groupMessages = ctx->groupMessages;
  4619. #ifndef NO_DH
  4620. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
  4621. !defined(HAVE_SELFTEST)
  4622. ssl->options.dhKeyTested = ctx->dhKeyTested;
  4623. #endif
  4624. ssl->buffers.serverDH_P = ctx->serverDH_P;
  4625. ssl->buffers.serverDH_G = ctx->serverDH_G;
  4626. #endif
  4627. #ifndef NO_CERTS
  4628. /* ctx still owns certificate, certChain, key, dh, and cm */
  4629. ssl->buffers.certificate = ctx->certificate;
  4630. ssl->buffers.certChain = ctx->certChain;
  4631. #ifdef WOLFSSL_TLS13
  4632. ssl->buffers.certChainCnt = ctx->certChainCnt;
  4633. #endif
  4634. ssl->buffers.key = ctx->privateKey;
  4635. ssl->buffers.keyType = ctx->privateKeyType;
  4636. ssl->buffers.keyId = ctx->privateKeyId;
  4637. ssl->buffers.keySz = ctx->privateKeySz;
  4638. ssl->buffers.keyDevId = ctx->privateKeyDevId;
  4639. #endif
  4640. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  4641. ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  4642. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  4643. ssl->options.cacheMessages = ssl->options.side == WOLFSSL_SERVER_END ||
  4644. ssl->buffers.keyType == ed25519_sa_algo ||
  4645. ssl->buffers.keyType == ed448_sa_algo;
  4646. #endif
  4647. #ifdef WOLFSSL_ASYNC_CRYPT
  4648. ssl->devId = ctx->devId;
  4649. #endif
  4650. if (writeDup == 0) {
  4651. #ifndef NO_PSK
  4652. if (ctx->server_hint[0]) { /* set in CTX */
  4653. XSTRNCPY(ssl->arrays->server_hint, ctx->server_hint,
  4654. sizeof(ssl->arrays->server_hint));
  4655. ssl->arrays->server_hint[MAX_PSK_ID_LEN] = '\0'; /* null term */
  4656. }
  4657. #endif /* NO_PSK */
  4658. if (ctx->suites) {
  4659. #ifndef SINGLE_THREADED
  4660. *ssl->suites = *ctx->suites;
  4661. #else
  4662. ssl->suites = ctx->suites;
  4663. #endif
  4664. }
  4665. else {
  4666. XMEMSET(ssl->suites, 0, sizeof(Suites));
  4667. }
  4668. if (ssl->options.side != WOLFSSL_NEITHER_END) {
  4669. /* Defer initializing suites until accept or connect */
  4670. ret = InitSSL_Suites(ssl);
  4671. }
  4672. } /* writeDup check */
  4673. #ifdef WOLFSSL_SESSION_EXPORT
  4674. #ifdef WOLFSSL_DTLS
  4675. ssl->dtls_export = ctx->dtls_export; /* export function for session */
  4676. #endif
  4677. #endif
  4678. ssl->CBIORecv = ctx->CBIORecv;
  4679. ssl->CBIOSend = ctx->CBIOSend;
  4680. #ifdef OPENSSL_EXTRA
  4681. ssl->readAhead = ctx->readAhead;
  4682. #endif
  4683. ssl->verifyDepth = ctx->verifyDepth;
  4684. return ret;
  4685. }
  4686. int InitHandshakeHashes(WOLFSSL* ssl)
  4687. {
  4688. int ret;
  4689. /* make sure existing handshake hashes are free'd */
  4690. if (ssl->hsHashes != NULL) {
  4691. FreeHandshakeHashes(ssl);
  4692. }
  4693. /* allocate handshake hashes */
  4694. ssl->hsHashes = (HS_Hashes*)XMALLOC(sizeof(HS_Hashes), ssl->heap,
  4695. DYNAMIC_TYPE_HASHES);
  4696. if (ssl->hsHashes == NULL) {
  4697. WOLFSSL_MSG("HS_Hashes Memory error");
  4698. return MEMORY_E;
  4699. }
  4700. XMEMSET(ssl->hsHashes, 0, sizeof(HS_Hashes));
  4701. #ifndef NO_OLD_TLS
  4702. #ifndef NO_MD5
  4703. ret = wc_InitMd5_ex(&ssl->hsHashes->hashMd5, ssl->heap, ssl->devId);
  4704. if (ret != 0)
  4705. return ret;
  4706. #if defined(WOLFSSL_HASH_FLAGS) || defined(WOLF_CRYPTO_CB)
  4707. wc_Md5SetFlags(&ssl->hsHashes->hashMd5, WC_HASH_FLAG_WILLCOPY);
  4708. #endif
  4709. #endif
  4710. #ifndef NO_SHA
  4711. ret = wc_InitSha_ex(&ssl->hsHashes->hashSha, ssl->heap, ssl->devId);
  4712. if (ret != 0)
  4713. return ret;
  4714. #if defined(WOLFSSL_HASH_FLAGS) || defined(WOLF_CRYPTO_CB)
  4715. wc_ShaSetFlags(&ssl->hsHashes->hashSha, WC_HASH_FLAG_WILLCOPY);
  4716. #endif
  4717. #endif
  4718. #endif /* !NO_OLD_TLS */
  4719. #ifndef NO_SHA256
  4720. ret = wc_InitSha256_ex(&ssl->hsHashes->hashSha256, ssl->heap, ssl->devId);
  4721. if (ret != 0)
  4722. return ret;
  4723. #if defined(WOLFSSL_HASH_FLAGS) || defined(WOLF_CRYPTO_CB)
  4724. wc_Sha256SetFlags(&ssl->hsHashes->hashSha256, WC_HASH_FLAG_WILLCOPY);
  4725. #endif
  4726. #endif
  4727. #ifdef WOLFSSL_SHA384
  4728. ret = wc_InitSha384_ex(&ssl->hsHashes->hashSha384, ssl->heap, ssl->devId);
  4729. if (ret != 0)
  4730. return ret;
  4731. #if defined(WOLFSSL_HASH_FLAGS) || defined(WOLF_CRYPTO_CB)
  4732. wc_Sha384SetFlags(&ssl->hsHashes->hashSha384, WC_HASH_FLAG_WILLCOPY);
  4733. #endif
  4734. #endif
  4735. #ifdef WOLFSSL_SHA512
  4736. ret = wc_InitSha512_ex(&ssl->hsHashes->hashSha512, ssl->heap, ssl->devId);
  4737. if (ret != 0)
  4738. return ret;
  4739. #if defined(WOLFSSL_HASH_FLAGS) || defined(WOLF_CRYPTO_CB)
  4740. wc_Sha512SetFlags(&ssl->hsHashes->hashSha512, WC_HASH_FLAG_WILLCOPY);
  4741. #endif
  4742. #endif
  4743. return ret;
  4744. }
  4745. void FreeHandshakeHashes(WOLFSSL* ssl)
  4746. {
  4747. if (ssl->hsHashes) {
  4748. #ifndef NO_OLD_TLS
  4749. #ifndef NO_MD5
  4750. wc_Md5Free(&ssl->hsHashes->hashMd5);
  4751. #endif
  4752. #ifndef NO_SHA
  4753. wc_ShaFree(&ssl->hsHashes->hashSha);
  4754. #endif
  4755. #endif /* !NO_OLD_TLS */
  4756. #ifndef NO_SHA256
  4757. wc_Sha256Free(&ssl->hsHashes->hashSha256);
  4758. #endif
  4759. #ifdef WOLFSSL_SHA384
  4760. wc_Sha384Free(&ssl->hsHashes->hashSha384);
  4761. #endif
  4762. #ifdef WOLFSSL_SHA512
  4763. wc_Sha512Free(&ssl->hsHashes->hashSha512);
  4764. #endif
  4765. #if (defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
  4766. !defined(WOLFSSL_NO_CLIENT_AUTH)
  4767. if (ssl->hsHashes->messages != NULL) {
  4768. XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
  4769. ssl->hsHashes->messages = NULL;
  4770. }
  4771. #endif
  4772. XFREE(ssl->hsHashes, ssl->heap, DYNAMIC_TYPE_HASHES);
  4773. ssl->hsHashes = NULL;
  4774. }
  4775. }
  4776. /* init everything to 0, NULL, default values before calling anything that may
  4777. fail so that destructor has a "good" state to cleanup
  4778. ssl object to initialize
  4779. ctx parent factory
  4780. writeDup flag indicating this is a write dup only
  4781. 0 on success */
  4782. int InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
  4783. {
  4784. int ret;
  4785. XMEMSET(ssl, 0, sizeof(WOLFSSL));
  4786. #if defined(WOLFSSL_STATIC_MEMORY)
  4787. if (ctx->heap != NULL) {
  4788. WOLFSSL_HEAP_HINT* ssl_hint;
  4789. WOLFSSL_HEAP_HINT* ctx_hint;
  4790. /* avoid dereferencing a test value */
  4791. #ifdef WOLFSSL_HEAP_TEST
  4792. if (ctx->heap == (void*)WOLFSSL_HEAP_TEST) {
  4793. ssl->heap = ctx->heap;
  4794. }
  4795. else {
  4796. #endif
  4797. ssl->heap = (WOLFSSL_HEAP_HINT*)XMALLOC(sizeof(WOLFSSL_HEAP_HINT),
  4798. ctx->heap, DYNAMIC_TYPE_SSL);
  4799. if (ssl->heap == NULL) {
  4800. return MEMORY_E;
  4801. }
  4802. XMEMSET(ssl->heap, 0, sizeof(WOLFSSL_HEAP_HINT));
  4803. ssl_hint = ((WOLFSSL_HEAP_HINT*)(ssl->heap));
  4804. ctx_hint = ((WOLFSSL_HEAP_HINT*)(ctx->heap));
  4805. /* lock and check IO count / handshake count */
  4806. if (wc_LockMutex(&(ctx_hint->memory->memory_mutex)) != 0) {
  4807. WOLFSSL_MSG("Bad memory_mutex lock");
  4808. XFREE(ssl->heap, ctx->heap, DYNAMIC_TYPE_SSL);
  4809. ssl->heap = NULL; /* free and set to NULL for IO counter */
  4810. return BAD_MUTEX_E;
  4811. }
  4812. if (ctx_hint->memory->maxHa > 0 &&
  4813. ctx_hint->memory->maxHa <= ctx_hint->memory->curHa) {
  4814. WOLFSSL_MSG("At max number of handshakes for static memory");
  4815. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  4816. XFREE(ssl->heap, ctx->heap, DYNAMIC_TYPE_SSL);
  4817. ssl->heap = NULL; /* free and set to NULL for IO counter */
  4818. return MEMORY_E;
  4819. }
  4820. if (ctx_hint->memory->maxIO > 0 &&
  4821. ctx_hint->memory->maxIO <= ctx_hint->memory->curIO) {
  4822. WOLFSSL_MSG("At max number of IO allowed for static memory");
  4823. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  4824. XFREE(ssl->heap, ctx->heap, DYNAMIC_TYPE_SSL);
  4825. ssl->heap = NULL; /* free and set to NULL for IO counter */
  4826. return MEMORY_E;
  4827. }
  4828. ctx_hint->memory->curIO++;
  4829. ctx_hint->memory->curHa++;
  4830. ssl_hint->memory = ctx_hint->memory;
  4831. ssl_hint->haFlag = 1;
  4832. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  4833. /* check if tracking stats */
  4834. if (ctx_hint->memory->flag & WOLFMEM_TRACK_STATS) {
  4835. ssl_hint->stats = (WOLFSSL_MEM_CONN_STATS*)XMALLOC(
  4836. sizeof(WOLFSSL_MEM_CONN_STATS), ctx->heap, DYNAMIC_TYPE_SSL);
  4837. if (ssl_hint->stats == NULL) {
  4838. return MEMORY_E;
  4839. }
  4840. XMEMSET(ssl_hint->stats, 0, sizeof(WOLFSSL_MEM_CONN_STATS));
  4841. }
  4842. /* check if using fixed IO buffers */
  4843. if (ctx_hint->memory->flag & WOLFMEM_IO_POOL_FIXED) {
  4844. if (wc_LockMutex(&(ctx_hint->memory->memory_mutex)) != 0) {
  4845. WOLFSSL_MSG("Bad memory_mutex lock");
  4846. return BAD_MUTEX_E;
  4847. }
  4848. if (SetFixedIO(ctx_hint->memory, &(ssl_hint->inBuf)) != 1) {
  4849. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  4850. return MEMORY_E;
  4851. }
  4852. if (SetFixedIO(ctx_hint->memory, &(ssl_hint->outBuf)) != 1) {
  4853. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  4854. return MEMORY_E;
  4855. }
  4856. if (ssl_hint->outBuf == NULL || ssl_hint->inBuf == NULL) {
  4857. WOLFSSL_MSG("Not enough memory to create fixed IO buffers");
  4858. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  4859. return MEMORY_E;
  4860. }
  4861. wc_UnLockMutex(&(ctx_hint->memory->memory_mutex));
  4862. }
  4863. #ifdef WOLFSSL_HEAP_TEST
  4864. }
  4865. #endif
  4866. }
  4867. else {
  4868. ssl->heap = ctx->heap;
  4869. }
  4870. #else
  4871. ssl->heap = ctx->heap; /* carry over user heap without static memory */
  4872. #endif /* WOLFSSL_STATIC_MEMORY */
  4873. ssl->buffers.inputBuffer.buffer = ssl->buffers.inputBuffer.staticBuffer;
  4874. ssl->buffers.inputBuffer.bufferSize = STATIC_BUFFER_LEN;
  4875. ssl->buffers.outputBuffer.buffer = ssl->buffers.outputBuffer.staticBuffer;
  4876. ssl->buffers.outputBuffer.bufferSize = STATIC_BUFFER_LEN;
  4877. #ifdef KEEP_PEER_CERT
  4878. InitX509(&ssl->peerCert, 0, ssl->heap);
  4879. #endif
  4880. ssl->rfd = -1; /* set to invalid descriptor */
  4881. ssl->wfd = -1;
  4882. ssl->devId = ctx->devId; /* device for async HW (from wolfAsync_DevOpen) */
  4883. ssl->IOCB_ReadCtx = &ssl->rfd; /* prevent invalid pointer access if not */
  4884. ssl->IOCB_WriteCtx = &ssl->wfd; /* correctly set */
  4885. #ifdef HAVE_NETX
  4886. ssl->IOCB_ReadCtx = &ssl->nxCtx; /* default NetX IO ctx, same for read */
  4887. ssl->IOCB_WriteCtx = &ssl->nxCtx; /* and write */
  4888. #elif defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
  4889. ssl->mnCtx = mynewt_ctx_new();
  4890. if(!ssl->mnCtx) {
  4891. return MEMORY_E;
  4892. }
  4893. ssl->IOCB_ReadCtx = ssl->mnCtx; /* default Mynewt IO ctx, same for read */
  4894. ssl->IOCB_WriteCtx = ssl->mnCtx; /* and write */
  4895. #elif defined (WOLFSSL_GNRC)
  4896. ssl->IOCB_ReadCtx = ssl->gnrcCtx;
  4897. ssl->IOCB_WriteCtx = ssl->gnrcCtx;
  4898. #endif
  4899. /* initialize states */
  4900. ssl->options.serverState = NULL_STATE;
  4901. ssl->options.clientState = NULL_STATE;
  4902. ssl->options.connectState = CONNECT_BEGIN;
  4903. ssl->options.acceptState = ACCEPT_BEGIN;
  4904. ssl->options.handShakeState = NULL_STATE;
  4905. ssl->options.processReply = doProcessInit;
  4906. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  4907. ssl->options.buildMsgState = BUILD_MSG_BEGIN;
  4908. ssl->encrypt.state = CIPHER_STATE_BEGIN;
  4909. ssl->decrypt.state = CIPHER_STATE_BEGIN;
  4910. #ifndef NO_DH
  4911. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
  4912. !defined(HAVE_SELFTEST)
  4913. ssl->options.dhDoKeyTest = 1;
  4914. #endif
  4915. #endif
  4916. #ifdef WOLFSSL_DTLS
  4917. #ifdef WOLFSSL_SCTP
  4918. ssl->options.dtlsSctp = ctx->dtlsSctp;
  4919. #endif
  4920. #if defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)
  4921. ssl->dtlsMtuSz = ctx->dtlsMtuSz;
  4922. ssl->dtls_expected_rx = ssl->dtlsMtuSz;
  4923. #else
  4924. ssl->dtls_expected_rx = MAX_MTU;
  4925. #endif
  4926. ssl->dtls_timeout_init = DTLS_TIMEOUT_INIT;
  4927. ssl->dtls_timeout_max = DTLS_TIMEOUT_MAX;
  4928. ssl->dtls_timeout = ssl->dtls_timeout_init;
  4929. ssl->buffers.dtlsCtx.rfd = -1;
  4930. ssl->buffers.dtlsCtx.wfd = -1;
  4931. #endif
  4932. #ifndef WOLFSSL_AEAD_ONLY
  4933. #ifndef NO_OLD_TLS
  4934. ssl->hmac = SSL_hmac; /* default to SSLv3 */
  4935. #elif !defined(WOLFSSL_NO_TLS12)
  4936. ssl->hmac = TLS_hmac;
  4937. #endif
  4938. #endif
  4939. ssl->cipher.ssl = ssl;
  4940. #ifdef HAVE_EXTENDED_MASTER
  4941. ssl->options.haveEMS = ctx->haveEMS;
  4942. #endif
  4943. ssl->options.useClientOrder = ctx->useClientOrder;
  4944. ssl->options.mutualAuth = ctx->mutualAuth;
  4945. #ifdef WOLFSSL_TLS13
  4946. #ifdef HAVE_SESSION_TICKET
  4947. ssl->options.noTicketTls13 = ctx->noTicketTls13;
  4948. #endif
  4949. ssl->options.noPskDheKe = ctx->noPskDheKe;
  4950. #if defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  4951. ssl->options.postHandshakeAuth = ctx->postHandshakeAuth;
  4952. #endif
  4953. if (ctx->numGroups > 0) {
  4954. XMEMCPY(ssl->group, ctx->group, sizeof(*ctx->group) * ctx->numGroups);
  4955. ssl->numGroups = ctx->numGroups;
  4956. }
  4957. #endif
  4958. #ifdef HAVE_TLS_EXTENSIONS
  4959. #ifdef HAVE_MAX_FRAGMENT
  4960. ssl->max_fragment = MAX_RECORD_SIZE;
  4961. #endif
  4962. #ifdef HAVE_ALPN
  4963. ssl->alpn_client_list = NULL;
  4964. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  4965. ssl->alpnSelect = ctx->alpnSelect;
  4966. ssl->alpnSelectArg = ctx->alpnSelectArg;
  4967. #endif
  4968. #endif
  4969. #ifdef HAVE_SUPPORTED_CURVES
  4970. ssl->options.userCurves = ctx->userCurves;
  4971. #endif
  4972. #endif /* HAVE_TLS_EXTENSIONS */
  4973. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  4974. ssl->options.disallowEncThenMac = ctx->disallowEncThenMac;
  4975. #endif
  4976. /* default alert state (none) */
  4977. ssl->alert_history.last_rx.code = -1;
  4978. ssl->alert_history.last_rx.level = -1;
  4979. ssl->alert_history.last_tx.code = -1;
  4980. ssl->alert_history.last_tx.level = -1;
  4981. #ifdef OPENSSL_EXTRA
  4982. /* copy over application session context ID */
  4983. ssl->sessionCtxSz = ctx->sessionCtxSz;
  4984. XMEMCPY(ssl->sessionCtx, ctx->sessionCtx, ctx->sessionCtxSz);
  4985. ssl->cbioFlag = ctx->cbioFlag;
  4986. #endif
  4987. InitCiphers(ssl);
  4988. InitCipherSpecs(&ssl->specs);
  4989. /* all done with init, now can return errors, call other stuff */
  4990. if (!writeDup) {
  4991. /* arrays */
  4992. ssl->arrays = (Arrays*)XMALLOC(sizeof(Arrays), ssl->heap,
  4993. DYNAMIC_TYPE_ARRAYS);
  4994. if (ssl->arrays == NULL) {
  4995. WOLFSSL_MSG("Arrays Memory error");
  4996. return MEMORY_E;
  4997. }
  4998. XMEMSET(ssl->arrays, 0, sizeof(Arrays));
  4999. #if defined(WOLFSSL_TLS13) || defined(WOLFSSL_SNIFFER)
  5000. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  5001. ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN, ssl->heap,
  5002. DYNAMIC_TYPE_SECRET);
  5003. if (ssl->arrays->preMasterSecret == NULL) {
  5004. return MEMORY_E;
  5005. }
  5006. XMEMSET(ssl->arrays->preMasterSecret, 0, ENCRYPT_LEN);
  5007. #endif
  5008. #ifdef OPENSSL_EXTRA
  5009. if ((ssl->param = (WOLFSSL_X509_VERIFY_PARAM*)XMALLOC(
  5010. sizeof(WOLFSSL_X509_VERIFY_PARAM),
  5011. ssl->heap, DYNAMIC_TYPE_OPENSSL)) == NULL) {
  5012. WOLFSSL_MSG("ssl->param memory error");
  5013. return MEMORY_E;
  5014. }
  5015. XMEMSET(ssl->param, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM));
  5016. #endif
  5017. #ifdef SINGLE_THREADED
  5018. if (ctx->suites == NULL)
  5019. #endif
  5020. {
  5021. /* suites */
  5022. ssl->suites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap,
  5023. DYNAMIC_TYPE_SUITES);
  5024. if (ssl->suites == NULL) {
  5025. WOLFSSL_MSG("Suites Memory error");
  5026. return MEMORY_E;
  5027. }
  5028. #ifdef OPENSSL_ALL
  5029. ssl->suites->stack = NULL;
  5030. #endif
  5031. #ifdef SINGLE_THREADED
  5032. ssl->options.ownSuites = 1;
  5033. #endif
  5034. }
  5035. #ifdef SINGLE_THREADED
  5036. else {
  5037. ssl->options.ownSuites = 0;
  5038. }
  5039. #endif
  5040. }
  5041. /* Initialize SSL with the appropriate fields from it's ctx */
  5042. /* requires valid arrays and suites unless writeDup ing */
  5043. if ((ret = SetSSL_CTX(ssl, ctx, writeDup)) != WOLFSSL_SUCCESS)
  5044. return ret;
  5045. ssl->options.dtls = ssl->version.major == DTLS_MAJOR;
  5046. #ifdef SINGLE_THREADED
  5047. ssl->rng = ctx->rng; /* CTX may have one, if so use it */
  5048. #endif
  5049. if (ssl->rng == NULL) {
  5050. /* RNG */
  5051. ssl->rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), ssl->heap,DYNAMIC_TYPE_RNG);
  5052. if (ssl->rng == NULL) {
  5053. WOLFSSL_MSG("RNG Memory error");
  5054. return MEMORY_E;
  5055. }
  5056. XMEMSET(ssl->rng, 0, sizeof(WC_RNG));
  5057. ssl->options.weOwnRng = 1;
  5058. /* FIPS RNG API does not accept a heap hint */
  5059. #ifndef HAVE_FIPS
  5060. if ( (ret = wc_InitRng_ex(ssl->rng, ssl->heap, ssl->devId)) != 0) {
  5061. WOLFSSL_MSG("RNG Init error");
  5062. return ret;
  5063. }
  5064. #else
  5065. if ( (ret = wc_InitRng(ssl->rng)) != 0) {
  5066. WOLFSSL_MSG("RNG Init error");
  5067. return ret;
  5068. }
  5069. #endif
  5070. }
  5071. #ifdef HAVE_WRITE_DUP
  5072. if (writeDup) {
  5073. /* all done */
  5074. return 0;
  5075. }
  5076. #endif
  5077. /* hsHashes */
  5078. ret = InitHandshakeHashes(ssl);
  5079. if (ret != 0)
  5080. return ret;
  5081. #if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
  5082. if (ssl->options.dtls && ssl->options.side == WOLFSSL_SERVER_END) {
  5083. ret = wolfSSL_DTLS_SetCookieSecret(ssl, NULL, 0);
  5084. if (ret != 0) {
  5085. WOLFSSL_MSG("DTLS Cookie Secret error");
  5086. return ret;
  5087. }
  5088. }
  5089. #endif /* WOLFSSL_DTLS && !NO_WOLFSSL_SERVER */
  5090. #ifdef HAVE_SECRET_CALLBACK
  5091. ssl->sessionSecretCb = NULL;
  5092. ssl->sessionSecretCtx = NULL;
  5093. #ifdef WOLFSSL_TLS13
  5094. ssl->tls13SecretCb = NULL;
  5095. ssl->tls13SecretCtx = NULL;
  5096. #endif
  5097. #endif
  5098. #ifdef HAVE_SESSION_TICKET
  5099. ssl->session.ticket = ssl->session.staticTicket;
  5100. #endif
  5101. #ifdef WOLFSSL_MULTICAST
  5102. if (ctx->haveMcast) {
  5103. int i;
  5104. ssl->options.haveMcast = 1;
  5105. ssl->options.mcastID = ctx->mcastID;
  5106. /* Force the state to look like handshake has completed. */
  5107. /* Keying material is supplied externally. */
  5108. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  5109. ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
  5110. ssl->options.connectState = SECOND_REPLY_DONE;
  5111. ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
  5112. ssl->options.handShakeState = HANDSHAKE_DONE;
  5113. ssl->options.handShakeDone = 1;
  5114. for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++)
  5115. ssl->keys.peerSeq[i].peerId = INVALID_PEER_ID;
  5116. }
  5117. #endif
  5118. #ifdef HAVE_SECURE_RENEGOTIATION
  5119. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  5120. int useSecureReneg = ssl->ctx->useSecureReneg;
  5121. /* use secure renegotiation by default (not recommend) */
  5122. #ifdef WOLFSSL_SECURE_RENEGOTIATION_ON_BY_DEFAULT
  5123. useSecureReneg = 1;
  5124. #endif
  5125. if (useSecureReneg) {
  5126. ret = wolfSSL_UseSecureRenegotiation(ssl);
  5127. if (ret != WOLFSSL_SUCCESS)
  5128. return ret;
  5129. }
  5130. }
  5131. #endif /* HAVE_SECURE_RENEGOTIATION */
  5132. return 0;
  5133. }
  5134. /* free use of temporary arrays */
  5135. void FreeArrays(WOLFSSL* ssl, int keep)
  5136. {
  5137. if (ssl->arrays) {
  5138. if (keep) {
  5139. /* keeps session id for user retrieval */
  5140. XMEMCPY(ssl->session.sessionID, ssl->arrays->sessionID, ID_LEN);
  5141. ssl->session.sessionIDSz = ssl->arrays->sessionIDSz;
  5142. }
  5143. if (ssl->arrays->preMasterSecret) {
  5144. XFREE(ssl->arrays->preMasterSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  5145. ssl->arrays->preMasterSecret = NULL;
  5146. }
  5147. XFREE(ssl->arrays->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
  5148. ssl->arrays->pendingMsg = NULL;
  5149. ForceZero(ssl->arrays, sizeof(Arrays)); /* clear arrays struct */
  5150. }
  5151. XFREE(ssl->arrays, ssl->heap, DYNAMIC_TYPE_ARRAYS);
  5152. ssl->arrays = NULL;
  5153. }
  5154. void FreeKey(WOLFSSL* ssl, int type, void** pKey)
  5155. {
  5156. if (ssl && pKey && *pKey) {
  5157. switch (type) {
  5158. #ifndef NO_RSA
  5159. case DYNAMIC_TYPE_RSA:
  5160. wc_FreeRsaKey((RsaKey*)*pKey);
  5161. break;
  5162. #endif /* ! NO_RSA */
  5163. #ifdef HAVE_ECC
  5164. case DYNAMIC_TYPE_ECC:
  5165. wc_ecc_free((ecc_key*)*pKey);
  5166. break;
  5167. #endif /* HAVE_ECC */
  5168. #ifdef HAVE_ED25519
  5169. case DYNAMIC_TYPE_ED25519:
  5170. wc_ed25519_free((ed25519_key*)*pKey);
  5171. break;
  5172. #endif /* HAVE_ED25519 */
  5173. #ifdef HAVE_CURVE25519
  5174. case DYNAMIC_TYPE_CURVE25519:
  5175. wc_curve25519_free((curve25519_key*)*pKey);
  5176. break;
  5177. #endif /* HAVE_CURVE25519 */
  5178. #ifdef HAVE_ED448
  5179. case DYNAMIC_TYPE_ED448:
  5180. wc_ed448_free((ed448_key*)*pKey);
  5181. break;
  5182. #endif /* HAVE_ED448 */
  5183. #ifdef HAVE_CURVE448
  5184. case DYNAMIC_TYPE_CURVE448:
  5185. wc_curve448_free((curve448_key*)*pKey);
  5186. break;
  5187. #endif /* HAVE_CURVE448 */
  5188. #ifndef NO_DH
  5189. case DYNAMIC_TYPE_DH:
  5190. wc_FreeDhKey((DhKey*)*pKey);
  5191. break;
  5192. #endif /* !NO_DH */
  5193. default:
  5194. break;
  5195. }
  5196. XFREE(*pKey, ssl->heap, type);
  5197. /* Reset pointer */
  5198. *pKey = NULL;
  5199. }
  5200. }
  5201. int AllocKey(WOLFSSL* ssl, int type, void** pKey)
  5202. {
  5203. int ret = BAD_FUNC_ARG;
  5204. int sz = 0;
  5205. if (ssl == NULL || pKey == NULL) {
  5206. return BAD_FUNC_ARG;
  5207. }
  5208. /* Sanity check key destination */
  5209. if (*pKey != NULL) {
  5210. WOLFSSL_MSG("Key already present!");
  5211. return BAD_STATE_E;
  5212. }
  5213. /* Determine size */
  5214. switch (type) {
  5215. #ifndef NO_RSA
  5216. case DYNAMIC_TYPE_RSA:
  5217. sz = sizeof(RsaKey);
  5218. break;
  5219. #endif /* ! NO_RSA */
  5220. #ifdef HAVE_ECC
  5221. case DYNAMIC_TYPE_ECC:
  5222. sz = sizeof(ecc_key);
  5223. break;
  5224. #endif /* HAVE_ECC */
  5225. #ifdef HAVE_ED25519
  5226. case DYNAMIC_TYPE_ED25519:
  5227. sz = sizeof(ed25519_key);
  5228. break;
  5229. #endif /* HAVE_ED25519 */
  5230. #ifdef HAVE_CURVE25519
  5231. case DYNAMIC_TYPE_CURVE25519:
  5232. sz = sizeof(curve25519_key);
  5233. break;
  5234. #endif /* HAVE_CURVE25519 */
  5235. #ifdef HAVE_ED448
  5236. case DYNAMIC_TYPE_ED448:
  5237. sz = sizeof(ed448_key);
  5238. break;
  5239. #endif /* HAVE_ED448 */
  5240. #ifdef HAVE_CURVE448
  5241. case DYNAMIC_TYPE_CURVE448:
  5242. sz = sizeof(curve448_key);
  5243. break;
  5244. #endif /* HAVE_CURVE448 */
  5245. #ifndef NO_DH
  5246. case DYNAMIC_TYPE_DH:
  5247. sz = sizeof(DhKey);
  5248. break;
  5249. #endif /* !NO_DH */
  5250. default:
  5251. return BAD_FUNC_ARG;
  5252. }
  5253. if (sz == 0) {
  5254. return NOT_COMPILED_IN;
  5255. }
  5256. /* Allocate memory for key */
  5257. *pKey = XMALLOC(sz, ssl->heap, type);
  5258. if (*pKey == NULL) {
  5259. return MEMORY_E;
  5260. }
  5261. /* Initialize key */
  5262. switch (type) {
  5263. #ifndef NO_RSA
  5264. case DYNAMIC_TYPE_RSA:
  5265. ret = wc_InitRsaKey_ex((RsaKey*)*pKey, ssl->heap, ssl->devId);
  5266. break;
  5267. #endif /* ! NO_RSA */
  5268. #ifdef HAVE_ECC
  5269. case DYNAMIC_TYPE_ECC:
  5270. ret = wc_ecc_init_ex((ecc_key*)*pKey, ssl->heap, ssl->devId);
  5271. break;
  5272. #endif /* HAVE_ECC */
  5273. #ifdef HAVE_ED25519
  5274. case DYNAMIC_TYPE_ED25519:
  5275. wc_ed25519_init((ed25519_key*)*pKey);
  5276. ret = 0;
  5277. break;
  5278. #endif /* HAVE_CURVE25519 */
  5279. #ifdef HAVE_CURVE25519
  5280. case DYNAMIC_TYPE_CURVE25519:
  5281. wc_curve25519_init((curve25519_key*)*pKey);
  5282. ret = 0;
  5283. break;
  5284. #endif /* HAVE_CURVE25519 */
  5285. #ifdef HAVE_ED448
  5286. case DYNAMIC_TYPE_ED448:
  5287. wc_ed448_init((ed448_key*)*pKey);
  5288. ret = 0;
  5289. break;
  5290. #endif /* HAVE_CURVE448 */
  5291. #ifdef HAVE_CURVE448
  5292. case DYNAMIC_TYPE_CURVE448:
  5293. wc_curve448_init((curve448_key*)*pKey);
  5294. ret = 0;
  5295. break;
  5296. #endif /* HAVE_CURVE448 */
  5297. #ifndef NO_DH
  5298. case DYNAMIC_TYPE_DH:
  5299. ret = wc_InitDhKey_ex((DhKey*)*pKey, ssl->heap, ssl->devId);
  5300. break;
  5301. #endif /* !NO_DH */
  5302. default:
  5303. return BAD_FUNC_ARG;
  5304. }
  5305. /* On error free handshake key */
  5306. if (ret != 0) {
  5307. FreeKey(ssl, type, pKey);
  5308. }
  5309. return ret;
  5310. }
  5311. #if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  5312. defined(HAVE_CURVE25519) || defined(HHAVE_ED448) || defined(HAVE_CURVE448)
  5313. static int ReuseKey(WOLFSSL* ssl, int type, void* pKey)
  5314. {
  5315. int ret = 0;
  5316. (void)ssl;
  5317. switch (type) {
  5318. #ifndef NO_RSA
  5319. case DYNAMIC_TYPE_RSA:
  5320. wc_FreeRsaKey((RsaKey*)pKey);
  5321. ret = wc_InitRsaKey_ex((RsaKey*)pKey, ssl->heap, ssl->devId);
  5322. break;
  5323. #endif /* ! NO_RSA */
  5324. #ifdef HAVE_ECC
  5325. case DYNAMIC_TYPE_ECC:
  5326. wc_ecc_free((ecc_key*)pKey);
  5327. ret = wc_ecc_init_ex((ecc_key*)pKey, ssl->heap, ssl->devId);
  5328. break;
  5329. #endif /* HAVE_ECC */
  5330. #ifdef HAVE_ED25519
  5331. case DYNAMIC_TYPE_ED25519:
  5332. wc_ed25519_free((ed25519_key*)pKey);
  5333. ret = wc_ed25519_init((ed25519_key*)pKey);
  5334. break;
  5335. #endif /* HAVE_CURVE25519 */
  5336. #ifdef HAVE_CURVE25519
  5337. case DYNAMIC_TYPE_CURVE25519:
  5338. wc_curve25519_free((curve25519_key*)pKey);
  5339. ret = wc_curve25519_init((curve25519_key*)pKey);
  5340. break;
  5341. #endif /* HAVE_CURVE25519 */
  5342. #ifdef HAVE_ED448
  5343. case DYNAMIC_TYPE_ED448:
  5344. wc_ed448_free((ed448_key*)pKey);
  5345. ret = wc_ed448_init((ed448_key*)pKey);
  5346. break;
  5347. #endif /* HAVE_CURVE448 */
  5348. #ifdef HAVE_CURVE448
  5349. case DYNAMIC_TYPE_CURVE448:
  5350. wc_curve448_free((curve448_key*)pKey);
  5351. ret = wc_curve448_init((curve448_key*)pKey);
  5352. break;
  5353. #endif /* HAVE_CURVE448 */
  5354. #ifndef NO_DH
  5355. case DYNAMIC_TYPE_DH:
  5356. wc_FreeDhKey((DhKey*)pKey);
  5357. ret = wc_InitDhKey_ex((DhKey*)pKey, ssl->heap, ssl->devId);
  5358. break;
  5359. #endif /* !NO_DH */
  5360. default:
  5361. return BAD_FUNC_ARG;
  5362. }
  5363. return ret;
  5364. }
  5365. #endif
  5366. void FreeKeyExchange(WOLFSSL* ssl)
  5367. {
  5368. /* Cleanup signature buffer */
  5369. if (ssl->buffers.sig.buffer) {
  5370. XFREE(ssl->buffers.sig.buffer, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  5371. ssl->buffers.sig.buffer = NULL;
  5372. ssl->buffers.sig.length = 0;
  5373. }
  5374. /* Cleanup digest buffer */
  5375. if (ssl->buffers.digest.buffer) {
  5376. XFREE(ssl->buffers.digest.buffer, ssl->heap, DYNAMIC_TYPE_DIGEST);
  5377. ssl->buffers.digest.buffer = NULL;
  5378. ssl->buffers.digest.length = 0;
  5379. }
  5380. /* Free handshake key */
  5381. FreeKey(ssl, ssl->hsType, &ssl->hsKey);
  5382. #ifndef NO_DH
  5383. /* Free temp DH key */
  5384. FreeKey(ssl, DYNAMIC_TYPE_DH, (void**)&ssl->buffers.serverDH_Key);
  5385. #endif
  5386. /* Cleanup async */
  5387. #ifdef WOLFSSL_ASYNC_CRYPT
  5388. if (ssl->async.freeArgs) {
  5389. ssl->async.freeArgs(ssl, ssl->async.args);
  5390. ssl->async.freeArgs = NULL;
  5391. }
  5392. #endif
  5393. }
  5394. /* Free up all memory used by Suites structure from WOLFSSL */
  5395. void FreeSuites(WOLFSSL* ssl)
  5396. {
  5397. #ifdef SINGLE_THREADED
  5398. if (ssl->options.ownSuites)
  5399. #endif
  5400. {
  5401. #ifdef OPENSSL_ALL
  5402. wolfSSL_sk_SSL_CIPHER_free(ssl->suites->stack);
  5403. #endif
  5404. XFREE(ssl->suites, ssl->heap, DYNAMIC_TYPE_SUITES);
  5405. }
  5406. ssl->suites = NULL;
  5407. }
  5408. /* In case holding SSL object in array and don't want to free actual ssl */
  5409. void SSL_ResourceFree(WOLFSSL* ssl)
  5410. {
  5411. /* Note: any resources used during the handshake should be released in the
  5412. * function FreeHandshakeResources(). Be careful with the special cases
  5413. * like the RNG which may optionally be kept for the whole session. (For
  5414. * example with the RNG, it isn't used beyond the handshake except when
  5415. * using stream ciphers where it is retained. */
  5416. FreeCiphers(ssl);
  5417. FreeArrays(ssl, 0);
  5418. FreeKeyExchange(ssl);
  5419. if (ssl->options.weOwnRng) {
  5420. wc_FreeRng(ssl->rng);
  5421. XFREE(ssl->rng, ssl->heap, DYNAMIC_TYPE_RNG);
  5422. }
  5423. FreeSuites(ssl);
  5424. FreeHandshakeHashes(ssl);
  5425. XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
  5426. /* clear keys struct after session */
  5427. ForceZero(&ssl->keys, sizeof(Keys));
  5428. #ifdef WOLFSSL_TLS13
  5429. if (ssl->options.tls1_3) {
  5430. ForceZero(&ssl->clientSecret, sizeof(ssl->clientSecret));
  5431. ForceZero(&ssl->serverSecret, sizeof(ssl->serverSecret));
  5432. }
  5433. #endif
  5434. #ifndef NO_DH
  5435. if (ssl->buffers.serverDH_Priv.buffer) {
  5436. ForceZero(ssl->buffers.serverDH_Priv.buffer,
  5437. ssl->buffers.serverDH_Priv.length);
  5438. }
  5439. XFREE(ssl->buffers.serverDH_Priv.buffer, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  5440. XFREE(ssl->buffers.serverDH_Pub.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  5441. /* parameters (p,g) may be owned by ctx */
  5442. if (ssl->buffers.weOwnDH) {
  5443. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  5444. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  5445. }
  5446. #endif /* !NO_DH */
  5447. #ifndef NO_CERTS
  5448. ssl->keepCert = 0; /* make sure certificate is free'd */
  5449. wolfSSL_UnloadCertsKeys(ssl);
  5450. #endif
  5451. #ifndef NO_RSA
  5452. FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
  5453. ssl->peerRsaKeyPresent = 0;
  5454. #endif
  5455. #ifdef WOLFSSL_RENESAS_TSIP_TLS
  5456. XFREE(ssl->peerTsipEncRsaKeyIndex, ssl->heap, DYNAMIC_TYPE_RSA);
  5457. #endif
  5458. if (ssl->buffers.inputBuffer.dynamicFlag)
  5459. ShrinkInputBuffer(ssl, FORCED_FREE);
  5460. if (ssl->buffers.outputBuffer.dynamicFlag)
  5461. ShrinkOutputBuffer(ssl);
  5462. #if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
  5463. XFREE(ssl->buffers.tls13CookieSecret.buffer, ssl->heap,
  5464. DYNAMIC_TYPE_COOKIE_PWD);
  5465. #endif
  5466. #ifdef WOLFSSL_DTLS
  5467. DtlsMsgPoolReset(ssl);
  5468. if (ssl->dtls_rx_msg_list != NULL) {
  5469. DtlsMsgListDelete(ssl->dtls_rx_msg_list, ssl->heap);
  5470. ssl->dtls_rx_msg_list = NULL;
  5471. ssl->dtls_rx_msg_list_sz = 0;
  5472. }
  5473. XFREE(ssl->buffers.dtlsCtx.peer.sa, ssl->heap, DYNAMIC_TYPE_SOCKADDR);
  5474. ssl->buffers.dtlsCtx.peer.sa = NULL;
  5475. #ifndef NO_WOLFSSL_SERVER
  5476. XFREE(ssl->buffers.dtlsCookieSecret.buffer, ssl->heap,
  5477. DYNAMIC_TYPE_COOKIE_PWD);
  5478. #endif
  5479. #endif /* WOLFSSL_DTLS */
  5480. #ifdef OPENSSL_EXTRA
  5481. if (ssl->biord != ssl->biowr) /* only free write if different */
  5482. wolfSSL_BIO_free(ssl->biowr);
  5483. wolfSSL_BIO_free(ssl->biord); /* always free read bio */
  5484. ssl->biowr = NULL;
  5485. ssl->biord = NULL;
  5486. #endif
  5487. #ifdef HAVE_LIBZ
  5488. FreeStreams(ssl);
  5489. #endif
  5490. #ifdef HAVE_ECC
  5491. FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccKey);
  5492. ssl->peerEccKeyPresent = 0;
  5493. FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
  5494. ssl->peerEccDsaKeyPresent = 0;
  5495. #endif
  5496. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) ||defined(HAVE_CURVE448)
  5497. {
  5498. int dtype = 0;
  5499. #ifdef HAVE_ECC
  5500. dtype = DYNAMIC_TYPE_ECC;
  5501. #endif
  5502. #ifdef HAVE_CURVE25519
  5503. if (ssl->peerX25519KeyPresent
  5504. #ifdef HAVE_ECC
  5505. || ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE25519
  5506. #endif /* HAVE_ECC */
  5507. )
  5508. {
  5509. dtype = DYNAMIC_TYPE_CURVE25519;
  5510. }
  5511. #endif /* HAVE_CURVE25519 */
  5512. #ifdef HAVE_CURVE448
  5513. if (ssl->peerX448KeyPresent
  5514. #ifdef HAVE_ECC
  5515. || ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE448
  5516. #endif /* HAVE_ECC */
  5517. )
  5518. {
  5519. dtype = DYNAMIC_TYPE_CURVE448;
  5520. }
  5521. #endif /* HAVE_CURVE448 */
  5522. FreeKey(ssl, dtype, (void**)&ssl->eccTempKey);
  5523. ssl->eccTempKeyPresent = 0;
  5524. }
  5525. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  5526. #ifdef HAVE_CURVE25519
  5527. FreeKey(ssl, DYNAMIC_TYPE_CURVE25519, (void**)&ssl->peerX25519Key);
  5528. ssl->peerX25519KeyPresent = 0;
  5529. #endif
  5530. #ifdef HAVE_ED25519
  5531. FreeKey(ssl, DYNAMIC_TYPE_ED25519, (void**)&ssl->peerEd25519Key);
  5532. ssl->peerEd25519KeyPresent = 0;
  5533. #ifdef HAVE_PK_CALLBACKS
  5534. if (ssl->buffers.peerEd25519Key.buffer != NULL) {
  5535. XFREE(ssl->buffers.peerEd25519Key.buffer, ssl->heap,
  5536. DYNAMIC_TYPE_ED25519);
  5537. ssl->buffers.peerEd25519Key.buffer = NULL;
  5538. }
  5539. #endif
  5540. #endif
  5541. #ifdef HAVE_CURVE448
  5542. FreeKey(ssl, DYNAMIC_TYPE_CURVE448, (void**)&ssl->peerX448Key);
  5543. ssl->peerX448KeyPresent = 0;
  5544. #endif
  5545. #ifdef HAVE_ED448
  5546. FreeKey(ssl, DYNAMIC_TYPE_ED448, (void**)&ssl->peerEd448Key);
  5547. ssl->peerEd448KeyPresent = 0;
  5548. #ifdef HAVE_PK_CALLBACKS
  5549. if (ssl->buffers.peerEd448Key.buffer != NULL) {
  5550. XFREE(ssl->buffers.peerEd448Key.buffer, ssl->heap,
  5551. DYNAMIC_TYPE_ED448);
  5552. ssl->buffers.peerEd448Key.buffer = NULL;
  5553. }
  5554. #endif
  5555. #endif
  5556. #ifdef HAVE_PK_CALLBACKS
  5557. #ifdef HAVE_ECC
  5558. XFREE(ssl->buffers.peerEccDsaKey.buffer, ssl->heap, DYNAMIC_TYPE_ECC);
  5559. #endif /* HAVE_ECC */
  5560. #ifndef NO_RSA
  5561. XFREE(ssl->buffers.peerRsaKey.buffer, ssl->heap, DYNAMIC_TYPE_RSA);
  5562. #endif /* NO_RSA */
  5563. #endif /* HAVE_PK_CALLBACKS */
  5564. #ifdef HAVE_TLS_EXTENSIONS
  5565. TLSX_FreeAll(ssl->extensions, ssl->heap);
  5566. #ifdef HAVE_ALPN
  5567. if (ssl->alpn_client_list != NULL) {
  5568. XFREE(ssl->alpn_client_list, ssl->heap, DYNAMIC_TYPE_ALPN);
  5569. ssl->alpn_client_list = NULL;
  5570. }
  5571. #endif
  5572. #endif /* HAVE_TLS_EXTENSIONS */
  5573. #if defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
  5574. if (ssl->mnCtx) {
  5575. mynewt_ctx_clear(ssl->mnCtx);
  5576. ssl->mnCtx = NULL;
  5577. }
  5578. #endif
  5579. #ifdef HAVE_NETX
  5580. if (ssl->nxCtx.nxPacket)
  5581. nx_packet_release(ssl->nxCtx.nxPacket);
  5582. #endif
  5583. #ifdef KEEP_PEER_CERT
  5584. FreeX509(&ssl->peerCert);
  5585. #endif
  5586. #ifdef HAVE_SESSION_TICKET
  5587. if (ssl->session.isDynamic) {
  5588. XFREE(ssl->session.ticket, ssl->heap, DYNAMIC_TYPE_SESSION_TICK);
  5589. ssl->session.ticket = ssl->session.staticTicket;
  5590. ssl->session.isDynamic = 0;
  5591. ssl->session.ticketLen = 0;
  5592. }
  5593. #endif
  5594. #ifdef HAVE_EXT_CACHE
  5595. wolfSSL_SESSION_free(ssl->extSession);
  5596. #endif
  5597. #ifdef HAVE_WRITE_DUP
  5598. if (ssl->dupWrite) {
  5599. FreeWriteDup(ssl);
  5600. }
  5601. #endif
  5602. #ifdef OPENSSL_EXTRA
  5603. if (ssl->param) {
  5604. XFREE(ssl->param, ssl->heap, DYNAMIC_TYPE_OPENSSL);
  5605. }
  5606. #endif
  5607. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  5608. while (ssl->certReqCtx != NULL) {
  5609. CertReqCtx* curr = ssl->certReqCtx;
  5610. ssl->certReqCtx = curr->next;
  5611. XFREE(curr, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  5612. }
  5613. #endif
  5614. #ifdef WOLFSSL_STATIC_MEMORY
  5615. /* check if using fixed io buffers and free them */
  5616. if (ssl->heap != NULL) {
  5617. #ifdef WOLFSSL_HEAP_TEST
  5618. /* avoid dereferencing a test value */
  5619. if (ssl->heap != (void*)WOLFSSL_HEAP_TEST) {
  5620. #endif
  5621. WOLFSSL_HEAP_HINT* ssl_hint = (WOLFSSL_HEAP_HINT*)ssl->heap;
  5622. WOLFSSL_HEAP* ctx_heap;
  5623. void* heap = ssl->ctx ? ssl->ctx->heap : ssl->heap;
  5624. ctx_heap = ssl_hint->memory;
  5625. if (wc_LockMutex(&(ctx_heap->memory_mutex)) != 0) {
  5626. WOLFSSL_MSG("Bad memory_mutex lock");
  5627. }
  5628. ctx_heap->curIO--;
  5629. if (FreeFixedIO(ctx_heap, &(ssl_hint->outBuf)) != 1) {
  5630. WOLFSSL_MSG("Error freeing fixed output buffer");
  5631. }
  5632. if (FreeFixedIO(ctx_heap, &(ssl_hint->inBuf)) != 1) {
  5633. WOLFSSL_MSG("Error freeing fixed output buffer");
  5634. }
  5635. if (ssl_hint->haFlag) { /* check if handshake count has been decreased*/
  5636. ctx_heap->curHa--;
  5637. }
  5638. wc_UnLockMutex(&(ctx_heap->memory_mutex));
  5639. /* check if tracking stats */
  5640. if (ctx_heap->flag & WOLFMEM_TRACK_STATS) {
  5641. XFREE(ssl_hint->stats, heap, DYNAMIC_TYPE_SSL);
  5642. }
  5643. XFREE(ssl->heap, heap, DYNAMIC_TYPE_SSL);
  5644. #ifdef WOLFSSL_HEAP_TEST
  5645. }
  5646. #endif
  5647. }
  5648. #endif /* WOLFSSL_STATIC_MEMORY */
  5649. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  5650. wolfSSL_sk_CIPHER_free(ssl->supportedCiphers);
  5651. wolfSSL_sk_X509_free(ssl->peerCertChain);
  5652. #endif
  5653. }
  5654. /* Free any handshake resources no longer needed */
  5655. void FreeHandshakeResources(WOLFSSL* ssl)
  5656. {
  5657. #ifdef HAVE_SECURE_RENEGOTIATION
  5658. if (ssl->secure_renegotiation && ssl->secure_renegotiation->enabled) {
  5659. WOLFSSL_MSG("Secure Renegotiation needs to retain handshake resources");
  5660. return;
  5661. }
  5662. #endif
  5663. /* input buffer */
  5664. if (ssl->buffers.inputBuffer.dynamicFlag)
  5665. ShrinkInputBuffer(ssl, NO_FORCED_FREE);
  5666. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  5667. if (!ssl->options.tls1_3)
  5668. #endif
  5669. {
  5670. #ifndef OPENSSL_ALL
  5671. /* free suites unless using compatibility layer */
  5672. FreeSuites(ssl);
  5673. #endif
  5674. /* hsHashes */
  5675. FreeHandshakeHashes(ssl);
  5676. }
  5677. /* RNG */
  5678. if (ssl->options.tls1_1 == 0
  5679. #ifndef WOLFSSL_AEAD_ONLY
  5680. || ssl->specs.cipher_type == stream
  5681. #endif
  5682. #if defined(WOLFSSL_TLS13)
  5683. #if !defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  5684. || ssl->options.tls1_3
  5685. #elif !defined(HAVE_SESSION_TICKET)
  5686. || (ssl->options.tls1_3 && ssl->options.side == WOLFSSL_SERVER_END)
  5687. #endif
  5688. #endif
  5689. ) {
  5690. if (ssl->options.weOwnRng) {
  5691. wc_FreeRng(ssl->rng);
  5692. XFREE(ssl->rng, ssl->heap, DYNAMIC_TYPE_RNG);
  5693. ssl->rng = NULL;
  5694. ssl->options.weOwnRng = 0;
  5695. }
  5696. }
  5697. #ifdef WOLFSSL_DTLS
  5698. /* DTLS_POOL */
  5699. if (ssl->options.dtls) {
  5700. DtlsMsgPoolReset(ssl);
  5701. DtlsMsgListDelete(ssl->dtls_rx_msg_list, ssl->heap);
  5702. ssl->dtls_rx_msg_list = NULL;
  5703. ssl->dtls_rx_msg_list_sz = 0;
  5704. }
  5705. #endif
  5706. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH) && \
  5707. defined(HAVE_SESSION_TICKET)
  5708. if (!ssl->options.tls1_3)
  5709. #endif
  5710. /* arrays */
  5711. if (ssl->options.saveArrays == 0)
  5712. FreeArrays(ssl, 1);
  5713. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  5714. if (!ssl->options.tls1_3 || ssl->options.side == WOLFSSL_CLIENT_END)
  5715. #endif
  5716. {
  5717. #ifndef NO_RSA
  5718. /* peerRsaKey */
  5719. FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
  5720. ssl->peerRsaKeyPresent = 0;
  5721. #endif
  5722. #ifdef HAVE_ECC
  5723. FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
  5724. ssl->peerEccDsaKeyPresent = 0;
  5725. #endif /* HAVE_ECC */
  5726. #ifdef HAVE_ED25519
  5727. FreeKey(ssl, DYNAMIC_TYPE_ED25519, (void**)&ssl->peerEd25519Key);
  5728. ssl->peerEd25519KeyPresent = 0;
  5729. #endif /* HAVE_ED25519 */
  5730. #ifdef HAVE_ED448
  5731. FreeKey(ssl, DYNAMIC_TYPE_ED448, (void**)&ssl->peerEd448Key);
  5732. ssl->peerEd448KeyPresent = 0;
  5733. #endif /* HAVE_ED448 */
  5734. }
  5735. #ifdef HAVE_ECC
  5736. FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccKey);
  5737. ssl->peerEccKeyPresent = 0;
  5738. #endif
  5739. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  5740. {
  5741. int dtype;
  5742. #ifdef HAVE_ECC
  5743. dtype = DYNAMIC_TYPE_ECC;
  5744. #endif
  5745. #ifdef HAVE_CURVE25519
  5746. #ifdef HAVE_ECC
  5747. if (ssl->peerX25519KeyPresent ||
  5748. ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE25519)
  5749. #endif /* HAVE_ECC */
  5750. {
  5751. dtype = DYNAMIC_TYPE_CURVE25519;
  5752. }
  5753. #endif /* HAVE_CURVE25519 */
  5754. #ifdef HAVE_CURVE448
  5755. #ifdef HAVE_ECC
  5756. if (ssl->peerX448KeyPresent ||
  5757. ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE448)
  5758. #endif /* HAVE_ECC */
  5759. {
  5760. dtype = DYNAMIC_TYPE_CURVE448;
  5761. }
  5762. #endif /* HAVE_CURVE448 */
  5763. FreeKey(ssl, dtype, (void**)&ssl->eccTempKey);
  5764. ssl->eccTempKeyPresent = 0;
  5765. }
  5766. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  5767. #ifdef HAVE_CURVE25519
  5768. FreeKey(ssl, DYNAMIC_TYPE_CURVE25519, (void**)&ssl->peerX25519Key);
  5769. ssl->peerX25519KeyPresent = 0;
  5770. #endif
  5771. #ifdef HAVE_CURVE448
  5772. FreeKey(ssl, DYNAMIC_TYPE_CURVE448, (void**)&ssl->peerX448Key);
  5773. ssl->peerX448KeyPresent = 0;
  5774. #endif
  5775. #ifndef NO_DH
  5776. if (ssl->buffers.serverDH_Priv.buffer) {
  5777. ForceZero(ssl->buffers.serverDH_Priv.buffer,
  5778. ssl->buffers.serverDH_Priv.length);
  5779. }
  5780. XFREE(ssl->buffers.serverDH_Priv.buffer, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  5781. ssl->buffers.serverDH_Priv.buffer = NULL;
  5782. XFREE(ssl->buffers.serverDH_Pub.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  5783. ssl->buffers.serverDH_Pub.buffer = NULL;
  5784. /* parameters (p,g) may be owned by ctx */
  5785. if (ssl->buffers.weOwnDH) {
  5786. XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  5787. ssl->buffers.serverDH_G.buffer = NULL;
  5788. XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  5789. ssl->buffers.serverDH_P.buffer = NULL;
  5790. }
  5791. #endif /* !NO_DH */
  5792. #ifndef NO_CERTS
  5793. wolfSSL_UnloadCertsKeys(ssl);
  5794. #endif
  5795. #ifdef HAVE_PK_CALLBACKS
  5796. #if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  5797. if (!ssl->options.tls1_3 || ssl->options.side == WOLFSSL_CLIENT_END)
  5798. #endif
  5799. {
  5800. #ifdef HAVE_ECC
  5801. XFREE(ssl->buffers.peerEccDsaKey.buffer, ssl->heap, DYNAMIC_TYPE_ECC);
  5802. ssl->buffers.peerEccDsaKey.buffer = NULL;
  5803. #endif /* HAVE_ECC */
  5804. #ifndef NO_RSA
  5805. XFREE(ssl->buffers.peerRsaKey.buffer, ssl->heap, DYNAMIC_TYPE_RSA);
  5806. ssl->buffers.peerRsaKey.buffer = NULL;
  5807. #endif /* NO_RSA */
  5808. #ifdef HAVE_ED25519
  5809. XFREE(ssl->buffers.peerEd25519Key.buffer, ssl->heap,
  5810. DYNAMIC_TYPE_ED25519);
  5811. ssl->buffers.peerEd25519Key.buffer = NULL;
  5812. #endif
  5813. #ifdef HAVE_ED448
  5814. XFREE(ssl->buffers.peerEd448Key.buffer, ssl->heap, DYNAMIC_TYPE_ED448);
  5815. ssl->buffers.peerEd448Key.buffer = NULL;
  5816. #endif
  5817. }
  5818. #endif /* HAVE_PK_CALLBACKS */
  5819. #ifdef HAVE_QSH
  5820. QSH_FreeAll(ssl);
  5821. #endif
  5822. #ifdef HAVE_SESSION_TICKET
  5823. if (ssl->session.isDynamic) {
  5824. XFREE(ssl->session.ticket, ssl->heap, DYNAMIC_TYPE_SESSION_TICK);
  5825. ssl->session.ticket = ssl->session.staticTicket;
  5826. ssl->session.isDynamic = 0;
  5827. ssl->session.ticketLen = 0;
  5828. }
  5829. #endif
  5830. #if defined(HAVE_TLS_EXTENSIONS) && !defined(HAVE_SNI) && \
  5831. !defined(HAVE_ALPN) && !defined(WOLFSSL_POST_HANDSHAKE_AUTH)
  5832. /* Some extensions need to be kept for post-handshake querying. */
  5833. TLSX_FreeAll(ssl->extensions, ssl->heap);
  5834. ssl->extensions = NULL;
  5835. #endif
  5836. #ifdef WOLFSSL_STATIC_MEMORY
  5837. /* when done with handshake decrement current handshake count */
  5838. if (ssl->heap != NULL) {
  5839. #ifdef WOLFSSL_HEAP_TEST
  5840. /* avoid dereferencing a test value */
  5841. if (ssl->heap != (void*)WOLFSSL_HEAP_TEST) {
  5842. #endif
  5843. WOLFSSL_HEAP_HINT* ssl_hint = (WOLFSSL_HEAP_HINT*)ssl->heap;
  5844. WOLFSSL_HEAP* ctx_heap;
  5845. ctx_heap = ssl_hint->memory;
  5846. if (wc_LockMutex(&(ctx_heap->memory_mutex)) != 0) {
  5847. WOLFSSL_MSG("Bad memory_mutex lock");
  5848. }
  5849. ctx_heap->curHa--;
  5850. ssl_hint->haFlag = 0; /* set to zero since handshake has been dec */
  5851. wc_UnLockMutex(&(ctx_heap->memory_mutex));
  5852. #ifdef WOLFSSL_HEAP_TEST
  5853. }
  5854. #endif
  5855. }
  5856. #endif /* WOLFSSL_STATIC_MEMORY */
  5857. }
  5858. /* heap argument is the heap hint used when creating SSL */
  5859. void FreeSSL(WOLFSSL* ssl, void* heap)
  5860. {
  5861. if (ssl->ctx) {
  5862. FreeSSL_Ctx(ssl->ctx); /* will decrement and free underlying CTX if 0 */
  5863. }
  5864. SSL_ResourceFree(ssl);
  5865. XFREE(ssl, heap, DYNAMIC_TYPE_SSL);
  5866. (void)heap;
  5867. }
  5868. #if !defined(NO_OLD_TLS) || defined(WOLFSSL_DTLS) || \
  5869. ((defined(HAVE_CHACHA) || defined(HAVE_AESCCM) || defined(HAVE_AESGCM)) \
  5870. && defined(HAVE_AEAD))
  5871. #if defined(WOLFSSL_DTLS) || !defined(WOLFSSL_NO_TLS12)
  5872. static WC_INLINE void GetSEQIncrement(WOLFSSL* ssl, int verify, word32 seq[2])
  5873. {
  5874. if (verify) {
  5875. seq[0] = ssl->keys.peer_sequence_number_hi;
  5876. seq[1] = ssl->keys.peer_sequence_number_lo++;
  5877. if (seq[1] > ssl->keys.peer_sequence_number_lo) {
  5878. /* handle rollover */
  5879. ssl->keys.peer_sequence_number_hi++;
  5880. }
  5881. }
  5882. else {
  5883. seq[0] = ssl->keys.sequence_number_hi;
  5884. seq[1] = ssl->keys.sequence_number_lo++;
  5885. if (seq[1] > ssl->keys.sequence_number_lo) {
  5886. /* handle rollover */
  5887. ssl->keys.sequence_number_hi++;
  5888. }
  5889. }
  5890. }
  5891. #endif /* WOLFSSL_DTLS || !WOLFSSL_NO_TLS12 */
  5892. #ifdef WOLFSSL_DTLS
  5893. static WC_INLINE void DtlsGetSEQ(WOLFSSL* ssl, int order, word32 seq[2])
  5894. {
  5895. if (order == PREV_ORDER) {
  5896. /* Previous epoch case */
  5897. if (ssl->options.haveMcast) {
  5898. #ifdef WOLFSSL_MULTICAST
  5899. seq[0] = (((word32)ssl->keys.dtls_epoch - 1) << 16) |
  5900. (ssl->options.mcastID << 8) |
  5901. (ssl->keys.dtls_prev_sequence_number_hi & 0xFF);
  5902. #endif
  5903. }
  5904. else
  5905. seq[0] = (((word32)ssl->keys.dtls_epoch - 1) << 16) |
  5906. (ssl->keys.dtls_prev_sequence_number_hi & 0xFFFF);
  5907. seq[1] = ssl->keys.dtls_prev_sequence_number_lo;
  5908. }
  5909. else if (order == PEER_ORDER) {
  5910. if (ssl->options.haveMcast) {
  5911. #ifdef WOLFSSL_MULTICAST
  5912. seq[0] = ((word32)ssl->keys.curEpoch << 16) |
  5913. (ssl->keys.curPeerId << 8) |
  5914. (ssl->keys.curSeq_hi & 0xFF);
  5915. #endif
  5916. }
  5917. else
  5918. seq[0] = ((word32)ssl->keys.curEpoch << 16) |
  5919. (ssl->keys.curSeq_hi & 0xFFFF);
  5920. seq[1] = ssl->keys.curSeq_lo; /* explicit from peer */
  5921. }
  5922. else {
  5923. if (ssl->options.haveMcast) {
  5924. #ifdef WOLFSSL_MULTICAST
  5925. seq[0] = ((word32)ssl->keys.dtls_epoch << 16) |
  5926. (ssl->options.mcastID << 8) |
  5927. (ssl->keys.dtls_sequence_number_hi & 0xFF);
  5928. #endif
  5929. }
  5930. else
  5931. seq[0] = ((word32)ssl->keys.dtls_epoch << 16) |
  5932. (ssl->keys.dtls_sequence_number_hi & 0xFFFF);
  5933. seq[1] = ssl->keys.dtls_sequence_number_lo;
  5934. }
  5935. }
  5936. static WC_INLINE void DtlsSEQIncrement(WOLFSSL* ssl, int order)
  5937. {
  5938. word32 seq;
  5939. if (order == PREV_ORDER) {
  5940. seq = ssl->keys.dtls_prev_sequence_number_lo++;
  5941. if (seq > ssl->keys.dtls_prev_sequence_number_lo) {
  5942. /* handle rollover */
  5943. ssl->keys.dtls_prev_sequence_number_hi++;
  5944. }
  5945. }
  5946. else if (order == PEER_ORDER) {
  5947. seq = ssl->keys.peer_sequence_number_lo++;
  5948. if (seq > ssl->keys.peer_sequence_number_lo) {
  5949. /* handle rollover */
  5950. ssl->keys.peer_sequence_number_hi++;
  5951. }
  5952. }
  5953. else {
  5954. seq = ssl->keys.dtls_sequence_number_lo++;
  5955. if (seq > ssl->keys.dtls_sequence_number_lo) {
  5956. /* handle rollover */
  5957. ssl->keys.dtls_sequence_number_hi++;
  5958. }
  5959. }
  5960. }
  5961. #endif /* WOLFSSL_DTLS */
  5962. #if defined(WOLFSSL_DTLS) || !defined(WOLFSSL_NO_TLS12)
  5963. static WC_INLINE void WriteSEQ(WOLFSSL* ssl, int verifyOrder, byte* out)
  5964. {
  5965. word32 seq[2] = {0, 0};
  5966. if (!ssl->options.dtls) {
  5967. GetSEQIncrement(ssl, verifyOrder, seq);
  5968. }
  5969. else {
  5970. #ifdef WOLFSSL_DTLS
  5971. DtlsGetSEQ(ssl, verifyOrder, seq);
  5972. #endif
  5973. }
  5974. c32toa(seq[0], out);
  5975. c32toa(seq[1], out + OPAQUE32_LEN);
  5976. }
  5977. #endif /* WOLFSSL_DTLS || !WOLFSSL_NO_TLS12 */
  5978. #endif /* !NO_OLD_TLS || WOLFSSL_DTLS ||
  5979. * ((HAVE_CHACHA || HAVE_AESCCM || HAVE_AESGCM) && HAVE_AEAD) */
  5980. #ifdef WOLFSSL_DTLS
  5981. /* functions for managing DTLS datagram reordering */
  5982. /* Need to allocate space for the handshake message header. The hashing
  5983. * routines assume the message pointer is still within the buffer that
  5984. * has the headers, and will include those headers in the hash. The store
  5985. * routines need to take that into account as well. New will allocate
  5986. * extra space for the headers. */
  5987. DtlsMsg* DtlsMsgNew(word32 sz, void* heap)
  5988. {
  5989. DtlsMsg* msg;
  5990. (void)heap;
  5991. msg = (DtlsMsg*)XMALLOC(sizeof(DtlsMsg), heap, DYNAMIC_TYPE_DTLS_MSG);
  5992. if (msg != NULL) {
  5993. XMEMSET(msg, 0, sizeof(DtlsMsg));
  5994. msg->buf = (byte*)XMALLOC(sz + DTLS_HANDSHAKE_HEADER_SZ,
  5995. heap, DYNAMIC_TYPE_DTLS_BUFFER);
  5996. if (msg->buf != NULL) {
  5997. msg->sz = sz;
  5998. msg->type = no_shake;
  5999. msg->msg = msg->buf + DTLS_HANDSHAKE_HEADER_SZ;
  6000. }
  6001. else {
  6002. XFREE(msg, heap, DYNAMIC_TYPE_DTLS_MSG);
  6003. msg = NULL;
  6004. }
  6005. }
  6006. return msg;
  6007. }
  6008. void DtlsMsgDelete(DtlsMsg* item, void* heap)
  6009. {
  6010. (void)heap;
  6011. if (item != NULL) {
  6012. DtlsFrag* cur = item->fragList;
  6013. while (cur != NULL) {
  6014. DtlsFrag* next = cur->next;
  6015. XFREE(cur, heap, DYNAMIC_TYPE_DTLS_FRAG);
  6016. cur = next;
  6017. }
  6018. if (item->buf != NULL)
  6019. XFREE(item->buf, heap, DYNAMIC_TYPE_DTLS_BUFFER);
  6020. XFREE(item, heap, DYNAMIC_TYPE_DTLS_MSG);
  6021. }
  6022. }
  6023. void DtlsMsgListDelete(DtlsMsg* head, void* heap)
  6024. {
  6025. DtlsMsg* next;
  6026. while (head) {
  6027. next = head->next;
  6028. DtlsMsgDelete(head, heap);
  6029. head = next;
  6030. }
  6031. }
  6032. /* Create a DTLS Fragment from *begin - end, adjust new *begin and bytesLeft */
  6033. static DtlsFrag* CreateFragment(word32* begin, word32 end, const byte* data,
  6034. byte* buf, word32* bytesLeft, void* heap)
  6035. {
  6036. DtlsFrag* newFrag;
  6037. word32 added = end - *begin + 1;
  6038. (void)heap;
  6039. newFrag = (DtlsFrag*)XMALLOC(sizeof(DtlsFrag), heap,
  6040. DYNAMIC_TYPE_DTLS_FRAG);
  6041. if (newFrag != NULL) {
  6042. newFrag->next = NULL;
  6043. newFrag->begin = *begin;
  6044. newFrag->end = end;
  6045. XMEMCPY(buf + *begin, data, added);
  6046. *bytesLeft -= added;
  6047. *begin = newFrag->end + 1;
  6048. }
  6049. return newFrag;
  6050. }
  6051. int DtlsMsgSet(DtlsMsg* msg, word32 seq, const byte* data, byte type,
  6052. word32 fragOffset, word32 fragSz, void* heap)
  6053. {
  6054. if (msg != NULL && data != NULL && msg->fragSz <= msg->sz &&
  6055. (fragOffset + fragSz) <= msg->sz) {
  6056. DtlsFrag* cur = msg->fragList;
  6057. DtlsFrag* prev = cur;
  6058. DtlsFrag* newFrag;
  6059. word32 bytesLeft = fragSz; /* could be overlapping fragment */
  6060. word32 startOffset = fragOffset;
  6061. word32 added;
  6062. msg->seq = seq;
  6063. msg->type = type;
  6064. if (fragOffset == 0) {
  6065. XMEMCPY(msg->buf, data - DTLS_HANDSHAKE_HEADER_SZ,
  6066. DTLS_HANDSHAKE_HEADER_SZ);
  6067. c32to24(msg->sz, msg->msg - DTLS_HANDSHAKE_FRAG_SZ);
  6068. }
  6069. /* if no message data, just return */
  6070. if (fragSz == 0)
  6071. return 0;
  6072. /* if list is empty add full fragment to front */
  6073. if (cur == NULL) {
  6074. newFrag = CreateFragment(&fragOffset, fragOffset + fragSz - 1, data,
  6075. msg->msg, &bytesLeft, heap);
  6076. if (newFrag == NULL)
  6077. return MEMORY_E;
  6078. msg->fragSz = fragSz;
  6079. msg->fragList = newFrag;
  6080. return 0;
  6081. }
  6082. /* add to front if before current front, up to next->begin */
  6083. if (fragOffset < cur->begin) {
  6084. word32 end = fragOffset + fragSz - 1;
  6085. if (end >= cur->begin)
  6086. end = cur->begin - 1;
  6087. added = end - fragOffset + 1;
  6088. newFrag = CreateFragment(&fragOffset, end, data, msg->msg,
  6089. &bytesLeft, heap);
  6090. if (newFrag == NULL)
  6091. return MEMORY_E;
  6092. msg->fragSz += added;
  6093. newFrag->next = cur;
  6094. msg->fragList = newFrag;
  6095. }
  6096. /* while we have bytes left, try to find a gap to fill */
  6097. while (bytesLeft > 0) {
  6098. /* get previous packet in list */
  6099. while (cur && (fragOffset >= cur->begin)) {
  6100. prev = cur;
  6101. cur = cur->next;
  6102. }
  6103. /* don't add duplicate data */
  6104. if (prev->end >= fragOffset) {
  6105. if ( (fragOffset + bytesLeft - 1) <= prev->end)
  6106. return 0;
  6107. fragOffset = prev->end + 1;
  6108. bytesLeft = startOffset + fragSz - fragOffset;
  6109. }
  6110. if (cur == NULL)
  6111. /* we're at the end */
  6112. added = bytesLeft;
  6113. else
  6114. /* we're in between two frames */
  6115. added = min(bytesLeft, cur->begin - fragOffset);
  6116. /* data already there */
  6117. if (added == 0)
  6118. continue;
  6119. newFrag = CreateFragment(&fragOffset, fragOffset + added - 1,
  6120. data + fragOffset - startOffset,
  6121. msg->msg, &bytesLeft, heap);
  6122. if (newFrag == NULL)
  6123. return MEMORY_E;
  6124. msg->fragSz += added;
  6125. newFrag->next = prev->next;
  6126. prev->next = newFrag;
  6127. }
  6128. }
  6129. return 0;
  6130. }
  6131. DtlsMsg* DtlsMsgFind(DtlsMsg* head, word32 seq)
  6132. {
  6133. while (head != NULL && head->seq != seq) {
  6134. head = head->next;
  6135. }
  6136. return head;
  6137. }
  6138. void DtlsMsgStore(WOLFSSL* ssl, word32 seq, const byte* data,
  6139. word32 dataSz, byte type, word32 fragOffset, word32 fragSz, void* heap)
  6140. {
  6141. /* See if seq exists in the list. If it isn't in the list, make
  6142. * a new item of size dataSz, copy fragSz bytes from data to msg->msg
  6143. * starting at offset fragOffset, and add fragSz to msg->fragSz. If
  6144. * the seq is in the list and it isn't full, copy fragSz bytes from
  6145. * data to msg->msg starting at offset fragOffset, and add fragSz to
  6146. * msg->fragSz. Insertions take into account data already in the list
  6147. * in case there are overlaps in the handshake message due to retransmit
  6148. * messages. The new item should be inserted into the list in its
  6149. * proper position.
  6150. *
  6151. * 1. Find seq in list, or where seq should go in list. If seq not in
  6152. * list, create new item and insert into list. Either case, keep
  6153. * pointer to item.
  6154. * 2. Copy the data from the message to the stored message where it
  6155. * belongs without overlaps.
  6156. */
  6157. DtlsMsg* head = ssl->dtls_rx_msg_list;
  6158. if (head != NULL) {
  6159. DtlsMsg* cur = DtlsMsgFind(head, seq);
  6160. if (cur == NULL) {
  6161. cur = DtlsMsgNew(dataSz, heap);
  6162. if (cur != NULL) {
  6163. if (DtlsMsgSet(cur, seq, data, type,
  6164. fragOffset, fragSz, heap) < 0) {
  6165. DtlsMsgDelete(cur, heap);
  6166. }
  6167. else {
  6168. ssl->dtls_rx_msg_list_sz++;
  6169. head = DtlsMsgInsert(head, cur);
  6170. }
  6171. }
  6172. }
  6173. else {
  6174. /* If this fails, the data is just dropped. */
  6175. DtlsMsgSet(cur, seq, data, type, fragOffset, fragSz, heap);
  6176. }
  6177. }
  6178. else {
  6179. head = DtlsMsgNew(dataSz, heap);
  6180. if (DtlsMsgSet(head, seq, data, type, fragOffset, fragSz, heap) < 0) {
  6181. DtlsMsgDelete(head, heap);
  6182. head = NULL;
  6183. }
  6184. else {
  6185. ssl->dtls_rx_msg_list_sz++;
  6186. }
  6187. }
  6188. ssl->dtls_rx_msg_list = head;
  6189. }
  6190. /* DtlsMsgInsert() is an in-order insert. */
  6191. DtlsMsg* DtlsMsgInsert(DtlsMsg* head, DtlsMsg* item)
  6192. {
  6193. if (head == NULL || item->seq < head->seq) {
  6194. item->next = head;
  6195. head = item;
  6196. }
  6197. else if (head->next == NULL) {
  6198. head->next = item;
  6199. }
  6200. else {
  6201. DtlsMsg* cur = head->next;
  6202. DtlsMsg* prev = head;
  6203. while (cur) {
  6204. if (item->seq < cur->seq) {
  6205. item->next = cur;
  6206. prev->next = item;
  6207. break;
  6208. }
  6209. prev = cur;
  6210. cur = cur->next;
  6211. }
  6212. if (cur == NULL) {
  6213. prev->next = item;
  6214. }
  6215. }
  6216. return head;
  6217. }
  6218. /* DtlsMsgPoolSave() adds the message to the end of the stored transmit list. */
  6219. int DtlsMsgPoolSave(WOLFSSL* ssl, const byte* data, word32 dataSz)
  6220. {
  6221. DtlsMsg* item;
  6222. int ret = 0;
  6223. WOLFSSL_ENTER("DtlsMsgPoolSave()");
  6224. if (ssl->dtls_tx_msg_list_sz > DTLS_POOL_SZ) {
  6225. WOLFSSL_ERROR(DTLS_POOL_SZ_E);
  6226. return DTLS_POOL_SZ_E;
  6227. }
  6228. item = DtlsMsgNew(dataSz, ssl->heap);
  6229. if (item != NULL) {
  6230. DtlsMsg* cur = ssl->dtls_tx_msg_list;
  6231. XMEMCPY(item->buf, data, dataSz);
  6232. item->sz = dataSz;
  6233. item->seq = ssl->keys.dtls_epoch;
  6234. if (cur == NULL)
  6235. ssl->dtls_tx_msg_list = item;
  6236. else {
  6237. while (cur->next)
  6238. cur = cur->next;
  6239. cur->next = item;
  6240. }
  6241. ssl->dtls_tx_msg_list_sz++;
  6242. }
  6243. else
  6244. ret = MEMORY_E;
  6245. WOLFSSL_LEAVE("DtlsMsgPoolSave()", ret);
  6246. return ret;
  6247. }
  6248. /* DtlsMsgPoolTimeout() updates the timeout time. */
  6249. int DtlsMsgPoolTimeout(WOLFSSL* ssl)
  6250. {
  6251. int result = -1;
  6252. if (ssl->dtls_timeout < ssl->dtls_timeout_max) {
  6253. ssl->dtls_timeout *= DTLS_TIMEOUT_MULTIPLIER;
  6254. result = 0;
  6255. }
  6256. WOLFSSL_LEAVE("DtlsMsgPoolTimeout()", result);
  6257. return result;
  6258. }
  6259. /* DtlsMsgPoolReset() deletes the stored transmit list and resets the timeout
  6260. * value. */
  6261. void DtlsMsgPoolReset(WOLFSSL* ssl)
  6262. {
  6263. WOLFSSL_ENTER("DtlsMsgPoolReset()");
  6264. if (ssl->dtls_tx_msg_list) {
  6265. DtlsMsgListDelete(ssl->dtls_tx_msg_list, ssl->heap);
  6266. ssl->dtls_tx_msg_list = NULL;
  6267. ssl->dtls_tx_msg = NULL;
  6268. ssl->dtls_tx_msg_list_sz = 0;
  6269. ssl->dtls_timeout = ssl->dtls_timeout_init;
  6270. }
  6271. }
  6272. int VerifyForDtlsMsgPoolSend(WOLFSSL* ssl, byte type, word32 fragOffset)
  6273. {
  6274. /**
  6275. * only the first message from previous flight should be valid
  6276. * to be used for triggering retransmission of whole DtlsMsgPool.
  6277. * change cipher suite type is not verified here
  6278. */
  6279. return ((fragOffset == 0) &&
  6280. (((ssl->options.side == WOLFSSL_SERVER_END) &&
  6281. ((type == client_hello) ||
  6282. ((ssl->options.verifyPeer) && (type == certificate)) ||
  6283. ((!ssl->options.verifyPeer) && (type == client_key_exchange)))) ||
  6284. ((ssl->options.side == WOLFSSL_CLIENT_END) &&
  6285. (type == server_hello))));
  6286. }
  6287. /* DtlsMsgPoolSend() will send the stored transmit list. The stored list is
  6288. * updated with new sequence numbers, and will be re-encrypted if needed. */
  6289. int DtlsMsgPoolSend(WOLFSSL* ssl, int sendOnlyFirstPacket)
  6290. {
  6291. int ret = 0;
  6292. DtlsMsg* pool;
  6293. WOLFSSL_ENTER("DtlsMsgPoolSend()");
  6294. pool = ssl->dtls_tx_msg == NULL ? ssl->dtls_tx_msg_list : ssl->dtls_tx_msg;
  6295. if (pool != NULL) {
  6296. if ((ssl->options.side == WOLFSSL_SERVER_END &&
  6297. !(ssl->options.acceptState == SERVER_HELLO_DONE ||
  6298. ssl->options.acceptState == ACCEPT_FINISHED_DONE ||
  6299. ssl->options.acceptState == ACCEPT_THIRD_REPLY_DONE)) ||
  6300. (ssl->options.side == WOLFSSL_CLIENT_END &&
  6301. !(ssl->options.connectState == CLIENT_HELLO_SENT ||
  6302. ssl->options.connectState == HELLO_AGAIN_REPLY ||
  6303. ssl->options.connectState == FINISHED_DONE ||
  6304. ssl->options.connectState == SECOND_REPLY_DONE))) {
  6305. WOLFSSL_ERROR(DTLS_RETX_OVER_TX);
  6306. ssl->error = DTLS_RETX_OVER_TX;
  6307. return WOLFSSL_FATAL_ERROR;
  6308. }
  6309. while (pool != NULL) {
  6310. if (pool->seq == 0) {
  6311. DtlsRecordLayerHeader* dtls;
  6312. int epochOrder;
  6313. dtls = (DtlsRecordLayerHeader*)pool->buf;
  6314. /* If the stored record's epoch is 0, and the currently set
  6315. * epoch is 0, use the "current order" sequence number.
  6316. * If the stored record's epoch is 0 and the currently set
  6317. * epoch is not 0, the stored record is considered a "previous
  6318. * order" sequence number. */
  6319. epochOrder = (ssl->keys.dtls_epoch == 0) ?
  6320. CUR_ORDER : PREV_ORDER;
  6321. WriteSEQ(ssl, epochOrder, dtls->sequence_number);
  6322. DtlsSEQIncrement(ssl, epochOrder);
  6323. if ((ret = CheckAvailableSize(ssl, pool->sz)) != 0) {
  6324. WOLFSSL_ERROR(ret);
  6325. return ret;
  6326. }
  6327. XMEMCPY(ssl->buffers.outputBuffer.buffer,
  6328. pool->buf, pool->sz);
  6329. ssl->buffers.outputBuffer.idx = 0;
  6330. ssl->buffers.outputBuffer.length = pool->sz;
  6331. }
  6332. else if (pool->seq == ssl->keys.dtls_epoch) {
  6333. byte* input;
  6334. byte* output;
  6335. int inputSz, sendSz;
  6336. input = pool->buf;
  6337. inputSz = pool->sz;
  6338. sendSz = inputSz + MAX_MSG_EXTRA;
  6339. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0) {
  6340. WOLFSSL_ERROR(ret);
  6341. return ret;
  6342. }
  6343. output = ssl->buffers.outputBuffer.buffer +
  6344. ssl->buffers.outputBuffer.length;
  6345. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  6346. handshake, 0, 0, 0);
  6347. if (sendSz < 0) {
  6348. WOLFSSL_ERROR(BUILD_MSG_ERROR);
  6349. return BUILD_MSG_ERROR;
  6350. }
  6351. ssl->buffers.outputBuffer.length += sendSz;
  6352. }
  6353. ret = SendBuffered(ssl);
  6354. if (ret < 0) {
  6355. WOLFSSL_ERROR(ret);
  6356. return ret;
  6357. }
  6358. /**
  6359. * on server side, retransmission is being triggered only by sending
  6360. * first message of given flight, in order to trigger client
  6361. * to retransmit its whole flight. Sending the whole previous flight
  6362. * could lead to retransmission of previous client flight for each
  6363. * server message from previous flight. Therefore one message should
  6364. * be enough to do the trick.
  6365. */
  6366. if (sendOnlyFirstPacket &&
  6367. ssl->options.side == WOLFSSL_SERVER_END) {
  6368. pool = NULL;
  6369. }
  6370. else
  6371. pool = pool->next;
  6372. ssl->dtls_tx_msg = pool;
  6373. }
  6374. }
  6375. WOLFSSL_LEAVE("DtlsMsgPoolSend()", ret);
  6376. return ret;
  6377. }
  6378. #endif /* WOLFSSL_DTLS */
  6379. #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
  6380. ProtocolVersion MakeSSLv3(void)
  6381. {
  6382. ProtocolVersion pv;
  6383. pv.major = SSLv3_MAJOR;
  6384. pv.minor = SSLv3_MINOR;
  6385. return pv;
  6386. }
  6387. #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
  6388. #ifdef WOLFSSL_DTLS
  6389. ProtocolVersion MakeDTLSv1(void)
  6390. {
  6391. ProtocolVersion pv;
  6392. pv.major = DTLS_MAJOR;
  6393. pv.minor = DTLS_MINOR;
  6394. return pv;
  6395. }
  6396. #ifndef WOLFSSL_NO_TLS12
  6397. ProtocolVersion MakeDTLSv1_2(void)
  6398. {
  6399. ProtocolVersion pv;
  6400. pv.major = DTLS_MAJOR;
  6401. pv.minor = DTLSv1_2_MINOR;
  6402. return pv;
  6403. }
  6404. #endif /* !WOLFSSL_NO_TLS12 */
  6405. #endif /* WOLFSSL_DTLS */
  6406. #ifndef NO_ASN_TIME
  6407. #if defined(USER_TICKS)
  6408. #if 0
  6409. word32 LowResTimer(void)
  6410. {
  6411. /*
  6412. write your own clock tick function if don't want time(0)
  6413. needs second accuracy but doesn't have to correlated to EPOCH
  6414. */
  6415. }
  6416. #endif
  6417. #elif defined(TIME_OVERRIDES)
  6418. /* use same asn time overrides unless user wants tick override above */
  6419. #ifndef HAVE_TIME_T_TYPE
  6420. typedef long time_t;
  6421. #endif
  6422. extern time_t XTIME(time_t * timer);
  6423. word32 LowResTimer(void)
  6424. {
  6425. return (word32) XTIME(0);
  6426. }
  6427. #elif defined(USE_WINDOWS_API)
  6428. word32 LowResTimer(void)
  6429. {
  6430. static int init = 0;
  6431. static LARGE_INTEGER freq;
  6432. LARGE_INTEGER count;
  6433. if (!init) {
  6434. QueryPerformanceFrequency(&freq);
  6435. init = 1;
  6436. }
  6437. QueryPerformanceCounter(&count);
  6438. return (word32)(count.QuadPart / freq.QuadPart);
  6439. }
  6440. #elif defined(HAVE_RTP_SYS)
  6441. #include "rtptime.h"
  6442. word32 LowResTimer(void)
  6443. {
  6444. return (word32)rtp_get_system_sec();
  6445. }
  6446. #elif defined(WOLFSSL_DEOS)
  6447. word32 LowResTimer(void)
  6448. {
  6449. const uint32_t systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
  6450. uint32_t *systemTickPtr = systemTickPointer();
  6451. return (word32) *systemTickPtr/systemTickTimeInHz;
  6452. }
  6453. #elif defined(MICRIUM)
  6454. word32 LowResTimer(void)
  6455. {
  6456. OS_TICK ticks = 0;
  6457. OS_ERR err;
  6458. ticks = OSTimeGet(&err);
  6459. return (word32) (ticks / OSCfg_TickRate_Hz);
  6460. }
  6461. #elif defined(MICROCHIP_TCPIP_V5)
  6462. word32 LowResTimer(void)
  6463. {
  6464. return (word32) (TickGet() / TICKS_PER_SECOND);
  6465. }
  6466. #elif defined(MICROCHIP_TCPIP)
  6467. #if defined(MICROCHIP_MPLAB_HARMONY)
  6468. #include <system/tmr/sys_tmr.h>
  6469. word32 LowResTimer(void)
  6470. {
  6471. return (word32) (SYS_TMR_TickCountGet() /
  6472. SYS_TMR_TickCounterFrequencyGet());
  6473. }
  6474. #else
  6475. word32 LowResTimer(void)
  6476. {
  6477. return (word32) (SYS_TICK_Get() / SYS_TICK_TicksPerSecondGet());
  6478. }
  6479. #endif
  6480. #elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
  6481. word32 LowResTimer(void)
  6482. {
  6483. TIME_STRUCT mqxTime;
  6484. _time_get_elapsed(&mqxTime);
  6485. return (word32) mqxTime.SECONDS;
  6486. }
  6487. #elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
  6488. #include "include/task.h"
  6489. unsigned int LowResTimer(void)
  6490. {
  6491. return (unsigned int)(((float)xTaskGetTickCount())/configTICK_RATE_HZ);
  6492. }
  6493. #elif defined(FREERTOS)
  6494. #include "task.h"
  6495. unsigned int LowResTimer(void)
  6496. {
  6497. return (unsigned int)(((float)xTaskGetTickCount())/configTICK_RATE_HZ);
  6498. }
  6499. #elif defined(FREESCALE_KSDK_BM)
  6500. #include "lwip/sys.h" /* lwIP */
  6501. word32 LowResTimer(void)
  6502. {
  6503. return sys_now()/1000;
  6504. }
  6505. #elif defined(WOLFSSL_TIRTOS)
  6506. word32 LowResTimer(void)
  6507. {
  6508. return (word32) Seconds_get();
  6509. }
  6510. #elif defined(WOLFSSL_XILINX)
  6511. #include "xrtcpsu.h"
  6512. word32 LowResTimer(void)
  6513. {
  6514. XRtcPsu_Config* con;
  6515. XRtcPsu rtc;
  6516. con = XRtcPsu_LookupConfig(XPAR_XRTCPSU_0_DEVICE_ID);
  6517. if (con != NULL) {
  6518. if (XRtcPsu_CfgInitialize(&rtc, con, con->BaseAddr)
  6519. == XST_SUCCESS) {
  6520. return (word32)XRtcPsu_GetCurrentTime(&rtc);
  6521. }
  6522. else {
  6523. WOLFSSL_MSG("Unable to initialize RTC");
  6524. }
  6525. }
  6526. return 0;
  6527. }
  6528. #elif defined(WOLFSSL_UTASKER)
  6529. word32 LowResTimer(void)
  6530. {
  6531. return (word32)(uTaskerSystemTick / TICK_RESOLUTION);
  6532. }
  6533. #elif defined(WOLFSSL_NUCLEUS_1_2)
  6534. #define NU_TICKS_PER_SECOND 100
  6535. word32 LowResTimer(void)
  6536. {
  6537. /* returns number of 10ms ticks, so 100 ticks/sec */
  6538. return NU_Retrieve_Clock() / NU_TICKS_PER_SECOND;
  6539. }
  6540. #elif defined(WOLFSSL_APACHE_MYNEWT)
  6541. #include "os/os_time.h"
  6542. word32 LowResTimer(void)
  6543. {
  6544. word32 now;
  6545. struct os_timeval tv;
  6546. os_gettimeofday(&tv, NULL);
  6547. now = (word32)tv.tv_sec;
  6548. return now;
  6549. }
  6550. #elif defined(WOLFSSL_ZEPHYR)
  6551. word32 LowResTimer(void)
  6552. {
  6553. return k_uptime_get() / 1000;
  6554. }
  6555. #else
  6556. /* Posix style time */
  6557. #if !defined(USER_TIME) && !defined(USE_WOLF_TM)
  6558. #include <time.h>
  6559. #endif
  6560. word32 LowResTimer(void)
  6561. {
  6562. return (word32)XTIME(0);
  6563. }
  6564. #endif
  6565. #endif /* !NO_ASN_TIME */
  6566. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  6567. ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  6568. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  6569. /* Store the message for use with CertificateVerify using EdDSA.
  6570. *
  6571. * ssl SSL/TLS object.
  6572. * data Message to store.
  6573. * sz Size of message to store.
  6574. * returns MEMORY_E if not able to reallocate, otherwise 0.
  6575. */
  6576. static int EdDSA_Update(WOLFSSL* ssl, const byte* data, int sz)
  6577. {
  6578. int ret = 0;
  6579. byte* msgs;
  6580. if (ssl->options.cacheMessages) {
  6581. msgs = (byte*)XREALLOC(ssl->hsHashes->messages,
  6582. ssl->hsHashes->length + sz,
  6583. ssl->heap, DYNAMIC_TYPE_HASHES);
  6584. if (msgs == NULL)
  6585. ret = MEMORY_E;
  6586. if (ret == 0) {
  6587. ssl->hsHashes->messages = msgs;
  6588. XMEMCPY(msgs + ssl->hsHashes->length, data, sz);
  6589. ssl->hsHashes->prevLen = ssl->hsHashes->length;
  6590. ssl->hsHashes->length += sz;
  6591. }
  6592. }
  6593. return ret;
  6594. }
  6595. #endif /* (HAVE_ED25519 || HAVE_ED448) && !WOLFSSL_NO_CLIENT_AUTH */
  6596. #ifndef NO_CERTS
  6597. int HashOutputRaw(WOLFSSL* ssl, const byte* output, int sz)
  6598. {
  6599. int ret = 0;
  6600. (void)output;
  6601. (void)sz;
  6602. if (ssl->hsHashes == NULL)
  6603. return BAD_FUNC_ARG;
  6604. #ifdef HAVE_FUZZER
  6605. if (ssl->fuzzerCb)
  6606. ssl->fuzzerCb(ssl, output, sz, FUZZ_HASH, ssl->fuzzerCtx);
  6607. #endif
  6608. #ifndef NO_OLD_TLS
  6609. #ifndef NO_SHA
  6610. wc_ShaUpdate(&ssl->hsHashes->hashSha, output, sz);
  6611. #endif
  6612. #ifndef NO_MD5
  6613. wc_Md5Update(&ssl->hsHashes->hashMd5, output, sz);
  6614. #endif
  6615. #endif /* NO_OLD_TLS */
  6616. if (IsAtLeastTLSv1_2(ssl)) {
  6617. #ifndef NO_SHA256
  6618. ret = wc_Sha256Update(&ssl->hsHashes->hashSha256, output, sz);
  6619. if (ret != 0)
  6620. return ret;
  6621. #endif
  6622. #ifdef WOLFSSL_SHA384
  6623. ret = wc_Sha384Update(&ssl->hsHashes->hashSha384, output, sz);
  6624. if (ret != 0)
  6625. return ret;
  6626. #endif
  6627. #ifdef WOLFSSL_SHA512
  6628. ret = wc_Sha512Update(&ssl->hsHashes->hashSha512, output, sz);
  6629. if (ret != 0)
  6630. return ret;
  6631. #endif
  6632. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  6633. ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  6634. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  6635. ret = EdDSA_Update(ssl, output, sz);
  6636. if (ret != 0)
  6637. return ret;
  6638. #endif
  6639. }
  6640. return ret;
  6641. }
  6642. #endif /* NO_CERTS */
  6643. /* add output to md5 and sha handshake hashes, exclude record header */
  6644. int HashOutput(WOLFSSL* ssl, const byte* output, int sz, int ivSz)
  6645. {
  6646. int ret = 0;
  6647. const byte* adj;
  6648. if (ssl->hsHashes == NULL)
  6649. return BAD_FUNC_ARG;
  6650. adj = output + RECORD_HEADER_SZ + ivSz;
  6651. sz -= RECORD_HEADER_SZ;
  6652. #ifdef HAVE_FUZZER
  6653. if (ssl->fuzzerCb)
  6654. ssl->fuzzerCb(ssl, output, sz, FUZZ_HASH, ssl->fuzzerCtx);
  6655. #endif
  6656. #ifdef WOLFSSL_DTLS
  6657. if (ssl->options.dtls) {
  6658. adj += DTLS_RECORD_EXTRA;
  6659. sz -= DTLS_RECORD_EXTRA;
  6660. }
  6661. #endif
  6662. #ifndef NO_OLD_TLS
  6663. #ifndef NO_SHA
  6664. wc_ShaUpdate(&ssl->hsHashes->hashSha, adj, sz);
  6665. #endif
  6666. #ifndef NO_MD5
  6667. wc_Md5Update(&ssl->hsHashes->hashMd5, adj, sz);
  6668. #endif
  6669. #endif
  6670. if (IsAtLeastTLSv1_2(ssl)) {
  6671. #ifndef NO_SHA256
  6672. ret = wc_Sha256Update(&ssl->hsHashes->hashSha256, adj, sz);
  6673. if (ret != 0)
  6674. return ret;
  6675. #endif
  6676. #ifdef WOLFSSL_SHA384
  6677. ret = wc_Sha384Update(&ssl->hsHashes->hashSha384, adj, sz);
  6678. if (ret != 0)
  6679. return ret;
  6680. #endif
  6681. #ifdef WOLFSSL_SHA512
  6682. ret = wc_Sha512Update(&ssl->hsHashes->hashSha512, adj, sz);
  6683. if (ret != 0)
  6684. return ret;
  6685. #endif
  6686. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  6687. ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  6688. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  6689. ret = EdDSA_Update(ssl, adj, sz);
  6690. if (ret != 0)
  6691. return ret;
  6692. #endif
  6693. }
  6694. return ret;
  6695. }
  6696. /* add input to md5 and sha handshake hashes, include handshake header */
  6697. int HashInput(WOLFSSL* ssl, const byte* input, int sz)
  6698. {
  6699. int ret = 0;
  6700. const byte* adj;
  6701. adj = input - HANDSHAKE_HEADER_SZ;
  6702. sz += HANDSHAKE_HEADER_SZ;
  6703. (void)adj;
  6704. #ifdef WOLFSSL_DTLS
  6705. if (ssl->options.dtls) {
  6706. adj -= DTLS_HANDSHAKE_EXTRA;
  6707. sz += DTLS_HANDSHAKE_EXTRA;
  6708. }
  6709. #endif
  6710. if (ssl->hsHashes == NULL) {
  6711. return BAD_FUNC_ARG;
  6712. }
  6713. #ifndef NO_OLD_TLS
  6714. #ifndef NO_SHA
  6715. wc_ShaUpdate(&ssl->hsHashes->hashSha, adj, sz);
  6716. #endif
  6717. #ifndef NO_MD5
  6718. wc_Md5Update(&ssl->hsHashes->hashMd5, adj, sz);
  6719. #endif
  6720. #endif
  6721. if (IsAtLeastTLSv1_2(ssl)) {
  6722. #ifndef NO_SHA256
  6723. ret = wc_Sha256Update(&ssl->hsHashes->hashSha256, adj, sz);
  6724. if (ret != 0)
  6725. return ret;
  6726. #endif
  6727. #ifdef WOLFSSL_SHA384
  6728. ret = wc_Sha384Update(&ssl->hsHashes->hashSha384, adj, sz);
  6729. if (ret != 0)
  6730. return ret;
  6731. #endif
  6732. #ifdef WOLFSSL_SHA512
  6733. ret = wc_Sha512Update(&ssl->hsHashes->hashSha512, adj, sz);
  6734. if (ret != 0)
  6735. return ret;
  6736. #endif
  6737. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  6738. ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  6739. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  6740. ret = EdDSA_Update(ssl, adj, sz);
  6741. if (ret != 0)
  6742. return ret;
  6743. #endif
  6744. }
  6745. return ret;
  6746. }
  6747. /* add record layer header for message */
  6748. static void AddRecordHeader(byte* output, word32 length, byte type, WOLFSSL* ssl)
  6749. {
  6750. RecordLayerHeader* rl;
  6751. /* record layer header */
  6752. rl = (RecordLayerHeader*)output;
  6753. if (rl == NULL) {
  6754. return;
  6755. }
  6756. rl->type = type;
  6757. rl->pvMajor = ssl->version.major; /* type and version same in each */
  6758. #ifdef WOLFSSL_TLS13
  6759. if (IsAtLeastTLSv1_3(ssl->version)) {
  6760. #ifdef WOLFSSL_TLS13_DRAFT_18
  6761. rl->pvMinor = TLSv1_MINOR;
  6762. #else
  6763. rl->pvMinor = TLSv1_2_MINOR;
  6764. #endif
  6765. }
  6766. else
  6767. #endif
  6768. rl->pvMinor = ssl->version.minor;
  6769. #ifdef WOLFSSL_ALTERNATIVE_DOWNGRADE
  6770. if (ssl->options.side == WOLFSSL_CLIENT_END
  6771. && ssl->options.connectState == CONNECT_BEGIN
  6772. && !ssl->options.resuming) {
  6773. rl->pvMinor = ssl->options.downgrade ? ssl->options.minDowngrade
  6774. : ssl->version.minor;
  6775. }
  6776. #endif
  6777. if (!ssl->options.dtls) {
  6778. c16toa((word16)length, rl->length);
  6779. }
  6780. else {
  6781. #ifdef WOLFSSL_DTLS
  6782. DtlsRecordLayerHeader* dtls;
  6783. /* dtls record layer header extensions */
  6784. dtls = (DtlsRecordLayerHeader*)output;
  6785. WriteSEQ(ssl, 0, dtls->sequence_number);
  6786. c16toa((word16)length, dtls->length);
  6787. #endif
  6788. }
  6789. }
  6790. #if !defined(WOLFSSL_NO_TLS12) || (defined(HAVE_SESSION_TICKET) && \
  6791. !defined(NO_WOLFSSL_SERVER))
  6792. /* add handshake header for message */
  6793. static void AddHandShakeHeader(byte* output, word32 length,
  6794. word32 fragOffset, word32 fragLength,
  6795. byte type, WOLFSSL* ssl)
  6796. {
  6797. HandShakeHeader* hs;
  6798. (void)fragOffset;
  6799. (void)fragLength;
  6800. (void)ssl;
  6801. /* handshake header */
  6802. hs = (HandShakeHeader*)output;
  6803. if (hs == NULL)
  6804. return;
  6805. hs->type = type;
  6806. c32to24(length, hs->length); /* type and length same for each */
  6807. #ifdef WOLFSSL_DTLS
  6808. if (ssl->options.dtls) {
  6809. DtlsHandShakeHeader* dtls;
  6810. /* dtls handshake header extensions */
  6811. dtls = (DtlsHandShakeHeader*)output;
  6812. c16toa(ssl->keys.dtls_handshake_number++, dtls->message_seq);
  6813. c32to24(fragOffset, dtls->fragment_offset);
  6814. c32to24(fragLength, dtls->fragment_length);
  6815. }
  6816. #endif
  6817. }
  6818. /* add both headers for handshake message */
  6819. static void AddHeaders(byte* output, word32 length, byte type, WOLFSSL* ssl)
  6820. {
  6821. word32 lengthAdj = HANDSHAKE_HEADER_SZ;
  6822. word32 outputAdj = RECORD_HEADER_SZ;
  6823. #ifdef WOLFSSL_DTLS
  6824. if (ssl->options.dtls) {
  6825. lengthAdj += DTLS_HANDSHAKE_EXTRA;
  6826. outputAdj += DTLS_RECORD_EXTRA;
  6827. }
  6828. #endif
  6829. AddRecordHeader(output, length + lengthAdj, handshake, ssl);
  6830. AddHandShakeHeader(output + outputAdj, length, 0, length, type, ssl);
  6831. }
  6832. #endif /* !WOLFSSL_NO_TLS12 || (HAVE_SESSION_TICKET && !NO_WOLFSSL_SERVER) */
  6833. #ifndef WOLFSSL_NO_TLS12
  6834. #if !defined(NO_CERTS) && (!defined(NO_WOLFSSL_SERVER) || \
  6835. !defined(WOLFSSL_NO_CLIENT_AUTH))
  6836. static void AddFragHeaders(byte* output, word32 fragSz, word32 fragOffset,
  6837. word32 length, byte type, WOLFSSL* ssl)
  6838. {
  6839. word32 lengthAdj = HANDSHAKE_HEADER_SZ;
  6840. word32 outputAdj = RECORD_HEADER_SZ;
  6841. (void)fragSz;
  6842. #ifdef WOLFSSL_DTLS
  6843. if (ssl->options.dtls) {
  6844. lengthAdj += DTLS_HANDSHAKE_EXTRA;
  6845. outputAdj += DTLS_RECORD_EXTRA;
  6846. }
  6847. #endif
  6848. AddRecordHeader(output, fragSz + lengthAdj, handshake, ssl);
  6849. AddHandShakeHeader(output + outputAdj, length, fragOffset, fragSz, type, ssl);
  6850. }
  6851. #endif /* NO_CERTS */
  6852. #endif /* !WOLFSSL_NO_TLS12 */
  6853. /* return bytes received, -1 on error */
  6854. static int wolfSSLReceive(WOLFSSL* ssl, byte* buf, word32 sz)
  6855. {
  6856. int recvd;
  6857. if (ssl->CBIORecv == NULL) {
  6858. WOLFSSL_MSG("Your IO Recv callback is null, please set");
  6859. return -1;
  6860. }
  6861. retry:
  6862. recvd = ssl->CBIORecv(ssl, (char *)buf, (int)sz, ssl->IOCB_ReadCtx);
  6863. if (recvd < 0) {
  6864. switch (recvd) {
  6865. case WOLFSSL_CBIO_ERR_GENERAL: /* general/unknown error */
  6866. #if defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD)
  6867. if (ssl->biord) {
  6868. /* If retry and read flags are set, return WANT_READ */
  6869. if ((ssl->biord->flags & WOLFSSL_BIO_FLAG_READ) &&
  6870. (ssl->biord->flags & WOLFSSL_BIO_FLAG_RETRY)) {
  6871. return WANT_READ;
  6872. }
  6873. }
  6874. #endif
  6875. return -1;
  6876. case WOLFSSL_CBIO_ERR_WANT_READ: /* want read, would block */
  6877. return WANT_READ;
  6878. case WOLFSSL_CBIO_ERR_CONN_RST: /* connection reset */
  6879. #ifdef USE_WINDOWS_API
  6880. if (ssl->options.dtls) {
  6881. goto retry;
  6882. }
  6883. #endif
  6884. ssl->options.connReset = 1;
  6885. return -1;
  6886. case WOLFSSL_CBIO_ERR_ISR: /* interrupt */
  6887. /* see if we got our timeout */
  6888. #ifdef WOLFSSL_CALLBACKS
  6889. if (ssl->toInfoOn) {
  6890. struct itimerval timeout;
  6891. getitimer(ITIMER_REAL, &timeout);
  6892. if (timeout.it_value.tv_sec == 0 &&
  6893. timeout.it_value.tv_usec == 0) {
  6894. XSTRNCPY(ssl->timeoutInfo.timeoutName,
  6895. "recv() timeout", MAX_TIMEOUT_NAME_SZ);
  6896. ssl->timeoutInfo.timeoutName[
  6897. MAX_TIMEOUT_NAME_SZ] = '\0';
  6898. WOLFSSL_MSG("Got our timeout");
  6899. return WANT_READ;
  6900. }
  6901. }
  6902. #endif
  6903. goto retry;
  6904. case WOLFSSL_CBIO_ERR_CONN_CLOSE: /* peer closed connection */
  6905. ssl->options.isClosed = 1;
  6906. return -1;
  6907. case WOLFSSL_CBIO_ERR_TIMEOUT:
  6908. #ifdef WOLFSSL_DTLS
  6909. if (IsDtlsNotSctpMode(ssl) &&
  6910. !ssl->options.handShakeDone &&
  6911. DtlsMsgPoolTimeout(ssl) == 0 &&
  6912. DtlsMsgPoolSend(ssl, 0) == 0) {
  6913. /* retry read for DTLS during handshake only */
  6914. goto retry;
  6915. }
  6916. #endif
  6917. return -1;
  6918. default:
  6919. WOLFSSL_MSG("Unexpected recv return code");
  6920. return recvd;
  6921. }
  6922. }
  6923. return recvd;
  6924. }
  6925. /* Switch dynamic output buffer back to static, buffer is assumed clear */
  6926. void ShrinkOutputBuffer(WOLFSSL* ssl)
  6927. {
  6928. WOLFSSL_MSG("Shrinking output buffer\n");
  6929. XFREE(ssl->buffers.outputBuffer.buffer - ssl->buffers.outputBuffer.offset,
  6930. ssl->heap, DYNAMIC_TYPE_OUT_BUFFER);
  6931. ssl->buffers.outputBuffer.buffer = ssl->buffers.outputBuffer.staticBuffer;
  6932. ssl->buffers.outputBuffer.bufferSize = STATIC_BUFFER_LEN;
  6933. ssl->buffers.outputBuffer.dynamicFlag = 0;
  6934. ssl->buffers.outputBuffer.offset = 0;
  6935. }
  6936. /* Switch dynamic input buffer back to static, keep any remaining input */
  6937. /* forced free means cleaning up */
  6938. void ShrinkInputBuffer(WOLFSSL* ssl, int forcedFree)
  6939. {
  6940. int usedLength = ssl->buffers.inputBuffer.length -
  6941. ssl->buffers.inputBuffer.idx;
  6942. if (!forcedFree && usedLength > STATIC_BUFFER_LEN)
  6943. return;
  6944. WOLFSSL_MSG("Shrinking input buffer\n");
  6945. if (!forcedFree && usedLength > 0)
  6946. XMEMCPY(ssl->buffers.inputBuffer.staticBuffer,
  6947. ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.idx,
  6948. usedLength);
  6949. XFREE(ssl->buffers.inputBuffer.buffer - ssl->buffers.inputBuffer.offset,
  6950. ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  6951. ssl->buffers.inputBuffer.buffer = ssl->buffers.inputBuffer.staticBuffer;
  6952. ssl->buffers.inputBuffer.bufferSize = STATIC_BUFFER_LEN;
  6953. ssl->buffers.inputBuffer.dynamicFlag = 0;
  6954. ssl->buffers.inputBuffer.offset = 0;
  6955. ssl->buffers.inputBuffer.idx = 0;
  6956. ssl->buffers.inputBuffer.length = usedLength;
  6957. }
  6958. int SendBuffered(WOLFSSL* ssl)
  6959. {
  6960. if (ssl->CBIOSend == NULL) {
  6961. WOLFSSL_MSG("Your IO Send callback is null, please set");
  6962. return SOCKET_ERROR_E;
  6963. }
  6964. #ifdef WOLFSSL_DEBUG_TLS
  6965. if (ssl->buffers.outputBuffer.idx == 0) {
  6966. WOLFSSL_MSG("Data to send");
  6967. WOLFSSL_BUFFER(ssl->buffers.outputBuffer.buffer,
  6968. ssl->buffers.outputBuffer.length);
  6969. }
  6970. #endif
  6971. while (ssl->buffers.outputBuffer.length > 0) {
  6972. int sent = ssl->CBIOSend(ssl,
  6973. (char*)ssl->buffers.outputBuffer.buffer +
  6974. ssl->buffers.outputBuffer.idx,
  6975. (int)ssl->buffers.outputBuffer.length,
  6976. ssl->IOCB_WriteCtx);
  6977. if (sent < 0) {
  6978. switch (sent) {
  6979. case WOLFSSL_CBIO_ERR_WANT_WRITE: /* would block */
  6980. return WANT_WRITE;
  6981. case WOLFSSL_CBIO_ERR_CONN_RST: /* connection reset */
  6982. ssl->options.connReset = 1;
  6983. break;
  6984. case WOLFSSL_CBIO_ERR_ISR: /* interrupt */
  6985. /* see if we got our timeout */
  6986. #ifdef WOLFSSL_CALLBACKS
  6987. if (ssl->toInfoOn) {
  6988. struct itimerval timeout;
  6989. getitimer(ITIMER_REAL, &timeout);
  6990. if (timeout.it_value.tv_sec == 0 &&
  6991. timeout.it_value.tv_usec == 0) {
  6992. XSTRNCPY(ssl->timeoutInfo.timeoutName,
  6993. "send() timeout", MAX_TIMEOUT_NAME_SZ);
  6994. ssl->timeoutInfo.timeoutName[
  6995. MAX_TIMEOUT_NAME_SZ] = '\0';
  6996. WOLFSSL_MSG("Got our timeout");
  6997. return WANT_WRITE;
  6998. }
  6999. }
  7000. #endif
  7001. continue;
  7002. case WOLFSSL_CBIO_ERR_CONN_CLOSE: /* epipe / conn closed */
  7003. ssl->options.connReset = 1; /* treat same as reset */
  7004. break;
  7005. default:
  7006. return SOCKET_ERROR_E;
  7007. }
  7008. return SOCKET_ERROR_E;
  7009. }
  7010. if (sent > (int)ssl->buffers.outputBuffer.length) {
  7011. WOLFSSL_MSG("SendBuffered() out of bounds read");
  7012. return SEND_OOB_READ_E;
  7013. }
  7014. ssl->buffers.outputBuffer.idx += sent;
  7015. ssl->buffers.outputBuffer.length -= sent;
  7016. }
  7017. ssl->buffers.outputBuffer.idx = 0;
  7018. if (ssl->buffers.outputBuffer.dynamicFlag)
  7019. ShrinkOutputBuffer(ssl);
  7020. return 0;
  7021. }
  7022. /* Grow the output buffer */
  7023. static WC_INLINE int GrowOutputBuffer(WOLFSSL* ssl, int size)
  7024. {
  7025. byte* tmp;
  7026. #if WOLFSSL_GENERAL_ALIGNMENT > 0
  7027. byte hdrSz = ssl->options.dtls ? DTLS_RECORD_HEADER_SZ :
  7028. RECORD_HEADER_SZ;
  7029. byte align = WOLFSSL_GENERAL_ALIGNMENT;
  7030. #else
  7031. const byte align = WOLFSSL_GENERAL_ALIGNMENT;
  7032. #endif
  7033. #if WOLFSSL_GENERAL_ALIGNMENT > 0
  7034. /* the encrypted data will be offset from the front of the buffer by
  7035. the header, if the user wants encrypted alignment they need
  7036. to define their alignment requirement */
  7037. if (align) {
  7038. while (align < hdrSz)
  7039. align *= 2;
  7040. }
  7041. #endif
  7042. tmp = (byte*)XMALLOC(size + ssl->buffers.outputBuffer.length + align,
  7043. ssl->heap, DYNAMIC_TYPE_OUT_BUFFER);
  7044. WOLFSSL_MSG("growing output buffer\n");
  7045. if (tmp == NULL)
  7046. return MEMORY_E;
  7047. #if WOLFSSL_GENERAL_ALIGNMENT > 0
  7048. if (align)
  7049. tmp += align - hdrSz;
  7050. #endif
  7051. #ifdef WOLFSSL_STATIC_MEMORY
  7052. /* can be from IO memory pool which does not need copy if same buffer */
  7053. if (ssl->buffers.outputBuffer.length &&
  7054. tmp == ssl->buffers.outputBuffer.buffer) {
  7055. ssl->buffers.outputBuffer.bufferSize =
  7056. size + ssl->buffers.outputBuffer.length;
  7057. return 0;
  7058. }
  7059. #endif
  7060. if (ssl->buffers.outputBuffer.length)
  7061. XMEMCPY(tmp, ssl->buffers.outputBuffer.buffer,
  7062. ssl->buffers.outputBuffer.length);
  7063. if (ssl->buffers.outputBuffer.dynamicFlag)
  7064. XFREE(ssl->buffers.outputBuffer.buffer -
  7065. ssl->buffers.outputBuffer.offset, ssl->heap,
  7066. DYNAMIC_TYPE_OUT_BUFFER);
  7067. ssl->buffers.outputBuffer.dynamicFlag = 1;
  7068. #if WOLFSSL_GENERAL_ALIGNMENT > 0
  7069. if (align)
  7070. ssl->buffers.outputBuffer.offset = align - hdrSz;
  7071. else
  7072. #endif
  7073. ssl->buffers.outputBuffer.offset = 0;
  7074. ssl->buffers.outputBuffer.buffer = tmp;
  7075. ssl->buffers.outputBuffer.bufferSize = size +
  7076. ssl->buffers.outputBuffer.length;
  7077. return 0;
  7078. }
  7079. /* Grow the input buffer, should only be to read cert or big app data */
  7080. int GrowInputBuffer(WOLFSSL* ssl, int size, int usedLength)
  7081. {
  7082. byte* tmp;
  7083. #if defined(WOLFSSL_DTLS) || WOLFSSL_GENERAL_ALIGNMENT > 0
  7084. byte align = ssl->options.dtls ? WOLFSSL_GENERAL_ALIGNMENT : 0;
  7085. byte hdrSz = DTLS_RECORD_HEADER_SZ;
  7086. #else
  7087. const byte align = WOLFSSL_GENERAL_ALIGNMENT;
  7088. #endif
  7089. #if defined(WOLFSSL_DTLS) || WOLFSSL_GENERAL_ALIGNMENT > 0
  7090. /* the encrypted data will be offset from the front of the buffer by
  7091. the dtls record header, if the user wants encrypted alignment they need
  7092. to define their alignment requirement. in tls we read record header
  7093. to get size of record and put actual data back at front, so don't need */
  7094. if (align) {
  7095. while (align < hdrSz)
  7096. align *= 2;
  7097. }
  7098. #endif
  7099. if (usedLength < 0 || size < 0) {
  7100. WOLFSSL_MSG("GrowInputBuffer() called with negative number");
  7101. return BAD_FUNC_ARG;
  7102. }
  7103. tmp = (byte*)XMALLOC(size + usedLength + align,
  7104. ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  7105. WOLFSSL_MSG("growing input buffer\n");
  7106. if (tmp == NULL)
  7107. return MEMORY_E;
  7108. #if defined(WOLFSSL_DTLS) || WOLFSSL_GENERAL_ALIGNMENT > 0
  7109. if (align)
  7110. tmp += align - hdrSz;
  7111. #endif
  7112. #ifdef WOLFSSL_STATIC_MEMORY
  7113. /* can be from IO memory pool which does not need copy if same buffer */
  7114. if (usedLength && tmp == ssl->buffers.inputBuffer.buffer) {
  7115. ssl->buffers.inputBuffer.bufferSize = size + usedLength;
  7116. ssl->buffers.inputBuffer.idx = 0;
  7117. ssl->buffers.inputBuffer.length = usedLength;
  7118. return 0;
  7119. }
  7120. #endif
  7121. if (usedLength)
  7122. XMEMCPY(tmp, ssl->buffers.inputBuffer.buffer +
  7123. ssl->buffers.inputBuffer.idx, usedLength);
  7124. if (ssl->buffers.inputBuffer.dynamicFlag)
  7125. XFREE(ssl->buffers.inputBuffer.buffer - ssl->buffers.inputBuffer.offset,
  7126. ssl->heap,DYNAMIC_TYPE_IN_BUFFER);
  7127. ssl->buffers.inputBuffer.dynamicFlag = 1;
  7128. #if defined(WOLFSSL_DTLS) || WOLFSSL_GENERAL_ALIGNMENT > 0
  7129. if (align)
  7130. ssl->buffers.inputBuffer.offset = align - hdrSz;
  7131. else
  7132. #endif
  7133. ssl->buffers.inputBuffer.offset = 0;
  7134. ssl->buffers.inputBuffer.buffer = tmp;
  7135. ssl->buffers.inputBuffer.bufferSize = size + usedLength;
  7136. ssl->buffers.inputBuffer.idx = 0;
  7137. ssl->buffers.inputBuffer.length = usedLength;
  7138. return 0;
  7139. }
  7140. /* check available size into output buffer, make room if needed */
  7141. int CheckAvailableSize(WOLFSSL *ssl, int size)
  7142. {
  7143. if (size < 0) {
  7144. WOLFSSL_MSG("CheckAvailableSize() called with negative number");
  7145. return BAD_FUNC_ARG;
  7146. }
  7147. if (ssl->buffers.outputBuffer.bufferSize - ssl->buffers.outputBuffer.length
  7148. < (word32)size) {
  7149. if (GrowOutputBuffer(ssl, size) < 0)
  7150. return MEMORY_E;
  7151. }
  7152. return 0;
  7153. }
  7154. /* do all verify and sanity checks on record header */
  7155. static int GetRecordHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  7156. RecordLayerHeader* rh, word16 *size)
  7157. {
  7158. if (!ssl->options.dtls) {
  7159. #ifdef HAVE_FUZZER
  7160. if (ssl->fuzzerCb)
  7161. ssl->fuzzerCb(ssl, input + *inOutIdx, RECORD_HEADER_SZ, FUZZ_HEAD,
  7162. ssl->fuzzerCtx);
  7163. #endif
  7164. XMEMCPY(rh, input + *inOutIdx, RECORD_HEADER_SZ);
  7165. *inOutIdx += RECORD_HEADER_SZ;
  7166. ato16(rh->length, size);
  7167. }
  7168. else {
  7169. #ifdef WOLFSSL_DTLS
  7170. #ifdef HAVE_FUZZER
  7171. if (ssl->fuzzerCb)
  7172. ssl->fuzzerCb(ssl, input + *inOutIdx, DTLS_RECORD_HEADER_SZ,
  7173. FUZZ_HEAD, ssl->fuzzerCtx);
  7174. #endif
  7175. /* type and version in same sport */
  7176. XMEMCPY(rh, input + *inOutIdx, ENUM_LEN + VERSION_SZ);
  7177. *inOutIdx += ENUM_LEN + VERSION_SZ;
  7178. ato16(input + *inOutIdx, &ssl->keys.curEpoch);
  7179. *inOutIdx += OPAQUE16_LEN;
  7180. if (ssl->options.haveMcast) {
  7181. #ifdef WOLFSSL_MULTICAST
  7182. ssl->keys.curPeerId = input[*inOutIdx];
  7183. ssl->keys.curSeq_hi = input[*inOutIdx+1];
  7184. #endif
  7185. }
  7186. else
  7187. ato16(input + *inOutIdx, &ssl->keys.curSeq_hi);
  7188. *inOutIdx += OPAQUE16_LEN;
  7189. ato32(input + *inOutIdx, &ssl->keys.curSeq_lo);
  7190. *inOutIdx += OPAQUE32_LEN; /* advance past rest of seq */
  7191. ato16(input + *inOutIdx, size);
  7192. *inOutIdx += LENGTH_SZ;
  7193. #endif
  7194. }
  7195. #ifdef WOLFSSL_DTLS
  7196. if (IsDtlsNotSctpMode(ssl) && !DtlsCheckWindow(ssl)) {
  7197. WOLFSSL_LEAVE("GetRecordHeader()", SEQUENCE_ERROR);
  7198. return SEQUENCE_ERROR;
  7199. }
  7200. #endif
  7201. /* catch version mismatch */
  7202. #ifndef WOLFSSL_TLS13
  7203. if (rh->pvMajor != ssl->version.major || rh->pvMinor != ssl->version.minor)
  7204. #else
  7205. if (rh->pvMajor != ssl->version.major ||
  7206. (rh->pvMinor != ssl->version.minor &&
  7207. #ifdef WOLFSSL_TLS13_DRAFT_18
  7208. (!IsAtLeastTLSv1_3(ssl->version) || rh->pvMinor != TLSv1_MINOR)
  7209. #else
  7210. (!IsAtLeastTLSv1_3(ssl->version) || rh->pvMinor != TLSv1_2_MINOR)
  7211. #endif
  7212. ))
  7213. #endif
  7214. {
  7215. if (ssl->options.side == WOLFSSL_SERVER_END &&
  7216. ssl->options.acceptState < ACCEPT_FIRST_REPLY_DONE)
  7217. WOLFSSL_MSG("Client attempting to connect with different version");
  7218. else if (ssl->options.side == WOLFSSL_CLIENT_END &&
  7219. ssl->options.downgrade &&
  7220. ssl->options.connectState < FIRST_REPLY_DONE)
  7221. WOLFSSL_MSG("Server attempting to accept with different version");
  7222. else if (ssl->options.dtls && rh->type == handshake)
  7223. /* Check the DTLS handshake message RH version later. */
  7224. WOLFSSL_MSG("DTLS handshake, skip RH version number check");
  7225. else {
  7226. WOLFSSL_MSG("SSL version error");
  7227. /* send alert per RFC5246 Appendix E. Backward Compatibility */
  7228. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  7229. #ifdef WOLFSSL_MYSQL_COMPATIBLE
  7230. SendAlert(ssl, alert_fatal, wc_protocol_version);
  7231. #else
  7232. SendAlert(ssl, alert_fatal, protocol_version);
  7233. #endif
  7234. }
  7235. return VERSION_ERROR; /* only use requested version */
  7236. }
  7237. }
  7238. /* record layer length check */
  7239. #ifdef HAVE_MAX_FRAGMENT
  7240. if (*size > (ssl->max_fragment + MAX_COMP_EXTRA + MAX_MSG_EXTRA)) {
  7241. SendAlert(ssl, alert_fatal, record_overflow);
  7242. return LENGTH_ERROR;
  7243. }
  7244. #else
  7245. if (*size > (MAX_RECORD_SIZE + MAX_COMP_EXTRA + MAX_MSG_EXTRA))
  7246. return LENGTH_ERROR;
  7247. #endif
  7248. /* verify record type here as well */
  7249. switch (rh->type) {
  7250. case handshake:
  7251. case change_cipher_spec:
  7252. case application_data:
  7253. case alert:
  7254. break;
  7255. case no_type:
  7256. default:
  7257. WOLFSSL_MSG("Unknown Record Type");
  7258. return UNKNOWN_RECORD_TYPE;
  7259. }
  7260. /* haven't decrypted this record yet */
  7261. ssl->keys.decryptedCur = 0;
  7262. return 0;
  7263. }
  7264. #ifndef WOLFSSL_NO_TLS12
  7265. static int GetHandShakeHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  7266. byte *type, word32 *size, word32 totalSz)
  7267. {
  7268. const byte *ptr = input + *inOutIdx;
  7269. (void)ssl;
  7270. *inOutIdx += HANDSHAKE_HEADER_SZ;
  7271. if (*inOutIdx > totalSz)
  7272. return BUFFER_E;
  7273. *type = ptr[0];
  7274. c24to32(&ptr[1], size);
  7275. return 0;
  7276. }
  7277. #endif
  7278. #ifdef WOLFSSL_DTLS
  7279. static int GetDtlsHandShakeHeader(WOLFSSL* ssl, const byte* input,
  7280. word32* inOutIdx, byte *type, word32 *size,
  7281. word32 *fragOffset, word32 *fragSz,
  7282. word32 totalSz)
  7283. {
  7284. word32 idx = *inOutIdx;
  7285. *inOutIdx += HANDSHAKE_HEADER_SZ + DTLS_HANDSHAKE_EXTRA;
  7286. if (*inOutIdx > totalSz) {
  7287. WOLFSSL_ERROR(BUFFER_E);
  7288. return BUFFER_E;
  7289. }
  7290. *type = input[idx++];
  7291. c24to32(input + idx, size);
  7292. idx += OPAQUE24_LEN;
  7293. ato16(input + idx, &ssl->keys.dtls_peer_handshake_number);
  7294. idx += DTLS_HANDSHAKE_SEQ_SZ;
  7295. c24to32(input + idx, fragOffset);
  7296. idx += DTLS_HANDSHAKE_FRAG_SZ;
  7297. c24to32(input + idx, fragSz);
  7298. if (ssl->curRL.pvMajor != ssl->version.major ||
  7299. ssl->curRL.pvMinor != ssl->version.minor) {
  7300. if (*type != client_hello && *type != hello_verify_request) {
  7301. WOLFSSL_ERROR(VERSION_ERROR);
  7302. return VERSION_ERROR;
  7303. }
  7304. else {
  7305. WOLFSSL_MSG("DTLS Handshake ignoring hello or verify version");
  7306. }
  7307. }
  7308. return 0;
  7309. }
  7310. #endif
  7311. #if !defined(NO_OLD_TLS) || \
  7312. (defined(NO_OLD_TLS) && defined(WOLFSSL_ALLOW_TLS_SHA1))
  7313. /* fill with MD5 pad size since biggest required */
  7314. static const byte PAD1[PAD_MD5] =
  7315. { 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  7316. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  7317. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  7318. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  7319. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
  7320. 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
  7321. };
  7322. static const byte PAD2[PAD_MD5] =
  7323. { 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  7324. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  7325. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  7326. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  7327. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
  7328. 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
  7329. };
  7330. #endif /* !NO_OLD_TLS || (NO_OLD_TLS && WOLFSSL_ALLOW_TLS_SHA1) */
  7331. #ifndef NO_OLD_TLS
  7332. /* calculate MD5 hash for finished */
  7333. #ifdef WOLFSSL_TI_HASH
  7334. #include <wolfssl/wolfcrypt/hash.h>
  7335. #endif
  7336. static int BuildMD5(WOLFSSL* ssl, Hashes* hashes, const byte* sender)
  7337. {
  7338. int ret;
  7339. byte md5_result[WC_MD5_DIGEST_SIZE];
  7340. #ifdef WOLFSSL_SMALL_STACK
  7341. wc_Md5* md5 = (wc_Md5*)XMALLOC(sizeof(wc_Md5), ssl->heap, DYNAMIC_TYPE_HASHCTX);
  7342. if (md5 == NULL)
  7343. return MEMORY_E;
  7344. #else
  7345. wc_Md5 md5[1];
  7346. #endif
  7347. /* make md5 inner */
  7348. ret = wc_Md5Copy(&ssl->hsHashes->hashMd5, md5);
  7349. if (ret == 0)
  7350. ret = wc_Md5Update(md5, sender, SIZEOF_SENDER);
  7351. if (ret == 0)
  7352. ret = wc_Md5Update(md5, ssl->arrays->masterSecret,SECRET_LEN);
  7353. if (ret == 0)
  7354. ret = wc_Md5Update(md5, PAD1, PAD_MD5);
  7355. if (ret == 0)
  7356. ret = wc_Md5Final(md5, md5_result);
  7357. /* make md5 outer */
  7358. if (ret == 0) {
  7359. ret = wc_InitMd5_ex(md5, ssl->heap, ssl->devId);
  7360. if (ret == 0) {
  7361. ret = wc_Md5Update(md5, ssl->arrays->masterSecret,SECRET_LEN);
  7362. if (ret == 0)
  7363. ret = wc_Md5Update(md5, PAD2, PAD_MD5);
  7364. if (ret == 0)
  7365. ret = wc_Md5Update(md5, md5_result, WC_MD5_DIGEST_SIZE);
  7366. if (ret == 0)
  7367. ret = wc_Md5Final(md5, hashes->md5);
  7368. wc_Md5Free(md5);
  7369. }
  7370. }
  7371. #ifdef WOLFSSL_SMALL_STACK
  7372. XFREE(md5, ssl->heap, DYNAMIC_TYPE_HASHCTX);
  7373. #endif
  7374. return ret;
  7375. }
  7376. /* calculate SHA hash for finished */
  7377. static int BuildSHA(WOLFSSL* ssl, Hashes* hashes, const byte* sender)
  7378. {
  7379. int ret;
  7380. byte sha_result[WC_SHA_DIGEST_SIZE];
  7381. #ifdef WOLFSSL_SMALL_STACK
  7382. wc_Sha* sha = (wc_Sha*)XMALLOC(sizeof(wc_Sha), ssl->heap, DYNAMIC_TYPE_HASHCTX);
  7383. if (sha == NULL)
  7384. return MEMORY_E;
  7385. #else
  7386. wc_Sha sha[1];
  7387. #endif
  7388. /* make sha inner */
  7389. ret = wc_ShaCopy(&ssl->hsHashes->hashSha, sha); /* Save current position */
  7390. if (ret == 0)
  7391. ret = wc_ShaUpdate(sha, sender, SIZEOF_SENDER);
  7392. if (ret == 0)
  7393. ret = wc_ShaUpdate(sha, ssl->arrays->masterSecret,SECRET_LEN);
  7394. if (ret == 0)
  7395. ret = wc_ShaUpdate(sha, PAD1, PAD_SHA);
  7396. if (ret == 0)
  7397. ret = wc_ShaFinal(sha, sha_result);
  7398. /* make sha outer */
  7399. if (ret == 0) {
  7400. ret = wc_InitSha_ex(sha, ssl->heap, ssl->devId);
  7401. if (ret == 0) {
  7402. ret = wc_ShaUpdate(sha, ssl->arrays->masterSecret,SECRET_LEN);
  7403. if (ret == 0)
  7404. ret = wc_ShaUpdate(sha, PAD2, PAD_SHA);
  7405. if (ret == 0)
  7406. ret = wc_ShaUpdate(sha, sha_result, WC_SHA_DIGEST_SIZE);
  7407. if (ret == 0)
  7408. ret = wc_ShaFinal(sha, hashes->sha);
  7409. wc_ShaFree(sha);
  7410. }
  7411. }
  7412. #ifdef WOLFSSL_SMALL_STACK
  7413. XFREE(sha, ssl->heap, DYNAMIC_TYPE_HASHCTX);
  7414. #endif
  7415. return ret;
  7416. }
  7417. #endif
  7418. #ifndef WOLFSSL_NO_TLS12
  7419. /* Finished doesn't support SHA512, not SHA512 cipher suites yet */
  7420. static int BuildFinished(WOLFSSL* ssl, Hashes* hashes, const byte* sender)
  7421. {
  7422. int ret = 0;
  7423. if (ssl == NULL)
  7424. return BAD_FUNC_ARG;
  7425. #ifndef NO_TLS
  7426. if (ssl->options.tls) {
  7427. ret = BuildTlsFinished(ssl, hashes, sender);
  7428. }
  7429. #endif
  7430. #ifndef NO_OLD_TLS
  7431. if (!ssl->options.tls) {
  7432. ret = BuildMD5(ssl, hashes, sender);
  7433. if (ret == 0) {
  7434. ret = BuildSHA(ssl, hashes, sender);
  7435. }
  7436. }
  7437. #endif
  7438. return ret;
  7439. }
  7440. #endif /* WOLFSSL_NO_TLS12 */
  7441. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_WOLFSSL_CLIENT)
  7442. /* cipher requirements */
  7443. enum {
  7444. REQUIRES_RSA,
  7445. REQUIRES_DHE,
  7446. REQUIRES_ECC,
  7447. REQUIRES_ECC_STATIC,
  7448. REQUIRES_PSK,
  7449. REQUIRES_NTRU,
  7450. REQUIRES_RSA_SIG,
  7451. REQUIRES_AEAD
  7452. };
  7453. /* Does this cipher suite (first, second) have the requirement
  7454. an ephemeral key exchange will still require the key for signing
  7455. the key exchange so ECHDE_RSA requires an rsa key thus rsa_kea */
  7456. static int CipherRequires(byte first, byte second, int requirement)
  7457. {
  7458. (void)requirement;
  7459. #ifndef WOLFSSL_NO_TLS12
  7460. #ifdef HAVE_CHACHA
  7461. if (first == CHACHA_BYTE) {
  7462. switch (second) {
  7463. case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 :
  7464. if (requirement == REQUIRES_RSA)
  7465. return 1;
  7466. break;
  7467. case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 :
  7468. if (requirement == REQUIRES_ECC)
  7469. return 1;
  7470. break;
  7471. case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 :
  7472. if (requirement == REQUIRES_RSA)
  7473. return 1;
  7474. if (requirement == REQUIRES_DHE)
  7475. return 1;
  7476. break;
  7477. case TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  7478. if (requirement == REQUIRES_RSA)
  7479. return 1;
  7480. break;
  7481. case TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  7482. if (requirement == REQUIRES_ECC)
  7483. return 1;
  7484. break;
  7485. case TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256 :
  7486. if (requirement == REQUIRES_RSA)
  7487. return 1;
  7488. if (requirement == REQUIRES_DHE)
  7489. return 1;
  7490. break;
  7491. case TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 :
  7492. if (requirement == REQUIRES_PSK)
  7493. return 1;
  7494. break;
  7495. case TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 :
  7496. if (requirement == REQUIRES_PSK)
  7497. return 1;
  7498. break;
  7499. case TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 :
  7500. if (requirement == REQUIRES_PSK)
  7501. return 1;
  7502. if (requirement == REQUIRES_DHE)
  7503. return 1;
  7504. break;
  7505. }
  7506. if (requirement == REQUIRES_AEAD)
  7507. return 1;
  7508. }
  7509. #endif /* HAVE_CHACHA */
  7510. /* ECC extensions */
  7511. if (first == ECC_BYTE) {
  7512. switch (second) {
  7513. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  7514. #ifndef NO_RSA
  7515. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA :
  7516. if (requirement == REQUIRES_RSA)
  7517. return 1;
  7518. break;
  7519. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA :
  7520. if (requirement == REQUIRES_ECC_STATIC)
  7521. return 1;
  7522. if (requirement == REQUIRES_RSA_SIG)
  7523. return 1;
  7524. break;
  7525. #ifndef NO_DES3
  7526. case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA :
  7527. if (requirement == REQUIRES_RSA)
  7528. return 1;
  7529. break;
  7530. case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA :
  7531. if (requirement == REQUIRES_ECC_STATIC)
  7532. return 1;
  7533. if (requirement == REQUIRES_RSA_SIG)
  7534. return 1;
  7535. break;
  7536. #endif /* !NO_DES3 */
  7537. #ifndef NO_RC4
  7538. case TLS_ECDHE_RSA_WITH_RC4_128_SHA :
  7539. if (requirement == REQUIRES_RSA)
  7540. return 1;
  7541. break;
  7542. case TLS_ECDH_RSA_WITH_RC4_128_SHA :
  7543. if (requirement == REQUIRES_ECC_STATIC)
  7544. return 1;
  7545. if (requirement == REQUIRES_RSA_SIG)
  7546. return 1;
  7547. break;
  7548. #endif /* !NO_RC4 */
  7549. #endif /* NO_RSA */
  7550. #ifndef NO_DES3
  7551. case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA :
  7552. if (requirement == REQUIRES_ECC)
  7553. return 1;
  7554. break;
  7555. case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA :
  7556. if (requirement == REQUIRES_ECC_STATIC)
  7557. return 1;
  7558. break;
  7559. #endif /* !NO_DES3 */
  7560. #ifndef NO_RC4
  7561. case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA :
  7562. if (requirement == REQUIRES_ECC)
  7563. return 1;
  7564. break;
  7565. case TLS_ECDH_ECDSA_WITH_RC4_128_SHA :
  7566. if (requirement == REQUIRES_ECC_STATIC)
  7567. return 1;
  7568. break;
  7569. #endif /* !NO_RC4 */
  7570. #ifndef NO_RSA
  7571. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA :
  7572. if (requirement == REQUIRES_RSA)
  7573. return 1;
  7574. break;
  7575. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA :
  7576. if (requirement == REQUIRES_ECC_STATIC)
  7577. return 1;
  7578. if (requirement == REQUIRES_RSA_SIG)
  7579. return 1;
  7580. break;
  7581. #endif /* !NO_RSA */
  7582. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA :
  7583. if (requirement == REQUIRES_ECC)
  7584. return 1;
  7585. break;
  7586. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA :
  7587. if (requirement == REQUIRES_ECC_STATIC)
  7588. return 1;
  7589. break;
  7590. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA :
  7591. if (requirement == REQUIRES_ECC)
  7592. return 1;
  7593. break;
  7594. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA :
  7595. if (requirement == REQUIRES_ECC_STATIC)
  7596. return 1;
  7597. break;
  7598. case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 :
  7599. if (requirement == REQUIRES_ECC)
  7600. return 1;
  7601. if (requirement == REQUIRES_AEAD)
  7602. return 1;
  7603. break;
  7604. case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 :
  7605. if (requirement == REQUIRES_ECC)
  7606. return 1;
  7607. if (requirement == REQUIRES_AEAD)
  7608. return 1;
  7609. break;
  7610. case TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 :
  7611. if (requirement == REQUIRES_ECC_STATIC)
  7612. return 1;
  7613. if (requirement == REQUIRES_AEAD)
  7614. return 1;
  7615. break;
  7616. case TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 :
  7617. if (requirement == REQUIRES_ECC_STATIC)
  7618. return 1;
  7619. if (requirement == REQUIRES_AEAD)
  7620. return 1;
  7621. break;
  7622. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  7623. #ifndef NO_RSA
  7624. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  7625. case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 :
  7626. if (requirement == REQUIRES_RSA)
  7627. return 1;
  7628. if (requirement == REQUIRES_AEAD)
  7629. return 1;
  7630. break;
  7631. case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 :
  7632. if (requirement == REQUIRES_RSA)
  7633. return 1;
  7634. if (requirement == REQUIRES_AEAD)
  7635. return 1;
  7636. break;
  7637. case TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 :
  7638. if (requirement == REQUIRES_ECC_STATIC)
  7639. return 1;
  7640. if (requirement == REQUIRES_RSA_SIG)
  7641. return 1;
  7642. if (requirement == REQUIRES_AEAD)
  7643. return 1;
  7644. break;
  7645. case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 :
  7646. if (requirement == REQUIRES_ECC_STATIC)
  7647. return 1;
  7648. if (requirement == REQUIRES_RSA_SIG)
  7649. return 1;
  7650. if (requirement == REQUIRES_AEAD)
  7651. return 1;
  7652. break;
  7653. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  7654. #ifdef HAVE_AESCCM
  7655. case TLS_RSA_WITH_AES_128_CCM_8 :
  7656. case TLS_RSA_WITH_AES_256_CCM_8 :
  7657. if (requirement == REQUIRES_RSA)
  7658. return 1;
  7659. if (requirement == REQUIRES_RSA_SIG)
  7660. return 1;
  7661. if (requirement == REQUIRES_AEAD)
  7662. return 1;
  7663. break;
  7664. #endif /* HAVE_AESCCM */
  7665. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  7666. case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 :
  7667. case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 :
  7668. if (requirement == REQUIRES_RSA)
  7669. return 1;
  7670. break;
  7671. case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 :
  7672. case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 :
  7673. if (requirement == REQUIRES_RSA_SIG)
  7674. return 1;
  7675. if (requirement == REQUIRES_ECC_STATIC)
  7676. return 1;
  7677. break;
  7678. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  7679. #endif /* !NO_RSA */
  7680. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  7681. case TLS_ECDHE_ECDSA_WITH_AES_128_CCM :
  7682. case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 :
  7683. case TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 :
  7684. if (requirement == REQUIRES_ECC)
  7685. return 1;
  7686. if (requirement == REQUIRES_AEAD)
  7687. return 1;
  7688. break;
  7689. case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 :
  7690. case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 :
  7691. if (requirement == REQUIRES_ECC)
  7692. return 1;
  7693. break;
  7694. case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 :
  7695. case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 :
  7696. if (requirement == REQUIRES_ECC)
  7697. return 1;
  7698. if (requirement == REQUIRES_ECC_STATIC)
  7699. return 1;
  7700. break;
  7701. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  7702. #ifndef NO_PSK
  7703. case TLS_PSK_WITH_AES_128_CCM:
  7704. case TLS_PSK_WITH_AES_256_CCM:
  7705. case TLS_PSK_WITH_AES_128_CCM_8:
  7706. case TLS_PSK_WITH_AES_256_CCM_8:
  7707. if (requirement == REQUIRES_PSK)
  7708. return 1;
  7709. if (requirement == REQUIRES_AEAD)
  7710. return 1;
  7711. break;
  7712. case TLS_DHE_PSK_WITH_AES_128_CCM:
  7713. case TLS_DHE_PSK_WITH_AES_256_CCM:
  7714. if (requirement == REQUIRES_PSK)
  7715. return 1;
  7716. if (requirement == REQUIRES_DHE)
  7717. return 1;
  7718. if (requirement == REQUIRES_AEAD)
  7719. return 1;
  7720. break;
  7721. #endif /* !NO_PSK */
  7722. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  7723. case TLS_ECDHE_ECDSA_WITH_NULL_SHA :
  7724. if (requirement == REQUIRES_ECC)
  7725. return 1;
  7726. break;
  7727. case TLS_ECDHE_PSK_WITH_NULL_SHA256 :
  7728. if (requirement == REQUIRES_PSK)
  7729. return 1;
  7730. break;
  7731. case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 :
  7732. if (requirement == REQUIRES_PSK)
  7733. return 1;
  7734. break;
  7735. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  7736. #if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER)
  7737. case TLS_SHA256_SHA256:
  7738. break;
  7739. case TLS_SHA384_SHA384:
  7740. break;
  7741. #endif
  7742. default:
  7743. WOLFSSL_MSG("Unsupported cipher suite, CipherRequires ECC");
  7744. return 0;
  7745. } /* switch */
  7746. } /* if */
  7747. #endif /* !WOLFSSL_NO_TLS12 */
  7748. /* Distinct TLS v1.3 cipher suites with cipher and digest only. */
  7749. if (first == TLS13_BYTE) {
  7750. switch (second) {
  7751. #ifdef WOLFSSL_TLS13
  7752. case TLS_AES_128_GCM_SHA256:
  7753. case TLS_AES_256_GCM_SHA384:
  7754. case TLS_CHACHA20_POLY1305_SHA256:
  7755. case TLS_AES_128_CCM_SHA256:
  7756. case TLS_AES_128_CCM_8_SHA256:
  7757. break;
  7758. #endif
  7759. default:
  7760. WOLFSSL_MSG("Unsupported cipher suite, CipherRequires "
  7761. "TLS v1.3");
  7762. return 0;
  7763. }
  7764. }
  7765. #ifndef WOLFSSL_NO_TLS12
  7766. if (first != ECC_BYTE && first != CHACHA_BYTE &&
  7767. first != TLS13_BYTE) { /* normal suites */
  7768. switch (second) {
  7769. #ifndef NO_RSA
  7770. #ifndef NO_RC4
  7771. case SSL_RSA_WITH_RC4_128_SHA :
  7772. if (requirement == REQUIRES_RSA)
  7773. return 1;
  7774. break;
  7775. case SSL_RSA_WITH_RC4_128_MD5 :
  7776. if (requirement == REQUIRES_RSA)
  7777. return 1;
  7778. break;
  7779. #endif /* NO_RC4 */
  7780. case SSL_RSA_WITH_3DES_EDE_CBC_SHA :
  7781. if (requirement == REQUIRES_RSA)
  7782. return 1;
  7783. break;
  7784. #ifdef HAVE_NTRU
  7785. case TLS_NTRU_RSA_WITH_RC4_128_SHA :
  7786. if (requirement == REQUIRES_NTRU)
  7787. return 1;
  7788. break;
  7789. #endif /* HAVE_NTRU */
  7790. case TLS_RSA_WITH_AES_128_CBC_SHA :
  7791. if (requirement == REQUIRES_RSA)
  7792. return 1;
  7793. break;
  7794. case TLS_RSA_WITH_AES_128_CBC_SHA256 :
  7795. if (requirement == REQUIRES_RSA)
  7796. return 1;
  7797. break;
  7798. #ifdef HAVE_NTRU
  7799. case TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA :
  7800. if (requirement == REQUIRES_NTRU)
  7801. return 1;
  7802. break;
  7803. #endif /* HAVE_NTRU */
  7804. case TLS_RSA_WITH_AES_256_CBC_SHA :
  7805. if (requirement == REQUIRES_RSA)
  7806. return 1;
  7807. break;
  7808. #ifdef HAVE_NTRU
  7809. case TLS_NTRU_RSA_WITH_AES_128_CBC_SHA :
  7810. if (requirement == REQUIRES_NTRU)
  7811. return 1;
  7812. break;
  7813. #endif /* HAVE_NTRU */
  7814. case TLS_RSA_WITH_AES_256_CBC_SHA256 :
  7815. if (requirement == REQUIRES_RSA)
  7816. return 1;
  7817. break;
  7818. case TLS_RSA_WITH_NULL_MD5 :
  7819. case TLS_RSA_WITH_NULL_SHA :
  7820. case TLS_RSA_WITH_NULL_SHA256 :
  7821. if (requirement == REQUIRES_RSA)
  7822. return 1;
  7823. break;
  7824. #ifdef HAVE_NTRU
  7825. case TLS_NTRU_RSA_WITH_AES_256_CBC_SHA :
  7826. if (requirement == REQUIRES_NTRU)
  7827. return 1;
  7828. break;
  7829. #endif /* HAVE_NTRU */
  7830. #ifdef HAVE_IDEA
  7831. case SSL_RSA_WITH_IDEA_CBC_SHA :
  7832. if (requirement == REQUIRES_RSA)
  7833. return 1;
  7834. break;
  7835. #endif /* HAVE_IDEA */
  7836. #endif /* !NO_RSA */
  7837. #ifndef NO_PSK
  7838. case TLS_PSK_WITH_AES_128_GCM_SHA256 :
  7839. if (requirement == REQUIRES_PSK)
  7840. return 1;
  7841. if (requirement == REQUIRES_AEAD)
  7842. return 1;
  7843. break;
  7844. case TLS_PSK_WITH_AES_256_GCM_SHA384 :
  7845. if (requirement == REQUIRES_PSK)
  7846. return 1;
  7847. if (requirement == REQUIRES_AEAD)
  7848. return 1;
  7849. break;
  7850. case TLS_PSK_WITH_AES_128_CBC_SHA256 :
  7851. case TLS_PSK_WITH_AES_256_CBC_SHA384 :
  7852. case TLS_PSK_WITH_AES_128_CBC_SHA :
  7853. case TLS_PSK_WITH_AES_256_CBC_SHA :
  7854. case TLS_PSK_WITH_NULL_SHA384 :
  7855. case TLS_PSK_WITH_NULL_SHA256 :
  7856. case TLS_PSK_WITH_NULL_SHA :
  7857. if (requirement == REQUIRES_PSK)
  7858. return 1;
  7859. break;
  7860. case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 :
  7861. case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 :
  7862. if (requirement == REQUIRES_DHE)
  7863. return 1;
  7864. if (requirement == REQUIRES_PSK)
  7865. return 1;
  7866. if (requirement == REQUIRES_AEAD)
  7867. return 1;
  7868. break;
  7869. case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 :
  7870. case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 :
  7871. case TLS_DHE_PSK_WITH_NULL_SHA384 :
  7872. case TLS_DHE_PSK_WITH_NULL_SHA256 :
  7873. if (requirement == REQUIRES_DHE)
  7874. return 1;
  7875. if (requirement == REQUIRES_PSK)
  7876. return 1;
  7877. break;
  7878. #endif /* NO_PSK */
  7879. #ifndef NO_RSA
  7880. case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 :
  7881. if (requirement == REQUIRES_RSA)
  7882. return 1;
  7883. if (requirement == REQUIRES_DHE)
  7884. return 1;
  7885. break;
  7886. case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 :
  7887. if (requirement == REQUIRES_RSA)
  7888. return 1;
  7889. if (requirement == REQUIRES_DHE)
  7890. return 1;
  7891. break;
  7892. case TLS_DHE_RSA_WITH_AES_128_CBC_SHA :
  7893. if (requirement == REQUIRES_RSA)
  7894. return 1;
  7895. if (requirement == REQUIRES_DHE)
  7896. return 1;
  7897. break;
  7898. case TLS_DHE_RSA_WITH_AES_256_CBC_SHA :
  7899. if (requirement == REQUIRES_RSA)
  7900. return 1;
  7901. if (requirement == REQUIRES_DHE)
  7902. return 1;
  7903. break;
  7904. #ifndef NO_HC128
  7905. case TLS_RSA_WITH_HC_128_MD5 :
  7906. if (requirement == REQUIRES_RSA)
  7907. return 1;
  7908. break;
  7909. case TLS_RSA_WITH_HC_128_SHA :
  7910. if (requirement == REQUIRES_RSA)
  7911. return 1;
  7912. break;
  7913. #endif /* NO_HC128 */
  7914. #ifndef NO_RABBIT
  7915. case TLS_RSA_WITH_RABBIT_SHA :
  7916. if (requirement == REQUIRES_RSA)
  7917. return 1;
  7918. break;
  7919. #endif /* !NO_RABBIT */
  7920. case TLS_RSA_WITH_AES_128_GCM_SHA256 :
  7921. case TLS_RSA_WITH_AES_256_GCM_SHA384 :
  7922. if (requirement == REQUIRES_RSA)
  7923. return 1;
  7924. if (requirement == REQUIRES_AEAD)
  7925. return 1;
  7926. break;
  7927. case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 :
  7928. case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 :
  7929. if (requirement == REQUIRES_RSA)
  7930. return 1;
  7931. if (requirement == REQUIRES_DHE)
  7932. return 1;
  7933. if (requirement == REQUIRES_AEAD)
  7934. return 1;
  7935. break;
  7936. #ifdef HAVE_CAMELLIA
  7937. case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA :
  7938. case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA :
  7939. case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 :
  7940. case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 :
  7941. if (requirement == REQUIRES_RSA)
  7942. return 1;
  7943. break;
  7944. case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA :
  7945. case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA :
  7946. case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 :
  7947. case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 :
  7948. if (requirement == REQUIRES_RSA)
  7949. return 1;
  7950. if (requirement == REQUIRES_RSA_SIG)
  7951. return 1;
  7952. if (requirement == REQUIRES_DHE)
  7953. return 1;
  7954. break;
  7955. #endif /* HAVE_CAMELLIA */
  7956. case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
  7957. if (requirement == REQUIRES_RSA)
  7958. return 1;
  7959. if (requirement == REQUIRES_RSA_SIG)
  7960. return 1;
  7961. if (requirement == REQUIRES_DHE)
  7962. return 1;
  7963. break;
  7964. #endif
  7965. #ifdef HAVE_ANON
  7966. case TLS_DH_anon_WITH_AES_128_CBC_SHA :
  7967. if (requirement == REQUIRES_DHE)
  7968. return 1;
  7969. break;
  7970. case TLS_DH_anon_WITH_AES_256_GCM_SHA384:
  7971. if (requirement == REQUIRES_DHE)
  7972. return 1;
  7973. if (requirement == REQUIRES_AEAD)
  7974. return 1;
  7975. break;
  7976. #endif
  7977. #ifdef WOLFSSL_MULTICAST
  7978. case WDM_WITH_NULL_SHA256 :
  7979. break;
  7980. #endif
  7981. default:
  7982. WOLFSSL_MSG("Unsupported cipher suite, CipherRequires");
  7983. return 0;
  7984. } /* switch */
  7985. } /* if ECC / Normal suites else */
  7986. #endif /* !WOLFSSL_NO_TLS12 */
  7987. return 0;
  7988. }
  7989. #endif /* !NO_WOLFSSL_SERVER && !NO_WOLFSSL_CLIENT */
  7990. #ifndef NO_CERTS
  7991. /* Match names with wildcards, each wildcard can represent a single name
  7992. component or fragment but not multiple names, i.e.,
  7993. *.z.com matches y.z.com but not x.y.z.com
  7994. return 1 on success */
  7995. int MatchDomainName(const char* pattern, int len, const char* str)
  7996. {
  7997. int ret = 0;
  7998. char p, s;
  7999. if (pattern == NULL || str == NULL || len <= 0)
  8000. return 0;
  8001. while (len > 0) {
  8002. p = (char)XTOLOWER((unsigned char)*pattern++);
  8003. if (p == '\0')
  8004. break;
  8005. if (p == '*') {
  8006. while (--len > 0 &&
  8007. (p = (char)XTOLOWER((unsigned char)*pattern++)) == '*') {
  8008. }
  8009. if (len == 0)
  8010. p = '\0';
  8011. while ( (s = (char)XTOLOWER((unsigned char) *str)) != '\0') {
  8012. if (s == p)
  8013. break;
  8014. if (s == '.')
  8015. return 0;
  8016. str++;
  8017. }
  8018. }
  8019. else {
  8020. if (p != (char)XTOLOWER((unsigned char) *str))
  8021. return 0;
  8022. }
  8023. if (len > 0) {
  8024. str++;
  8025. len--;
  8026. }
  8027. }
  8028. if (*str == '\0' && len == 0) {
  8029. ret = 1; /* success */
  8030. }
  8031. return ret;
  8032. }
  8033. /* try to find an altName match to domain, return 1 on success */
  8034. int CheckAltNames(DecodedCert* dCert, char* domain)
  8035. {
  8036. int match = 0;
  8037. DNS_entry* altName = NULL;
  8038. WOLFSSL_MSG("Checking AltNames");
  8039. if (dCert)
  8040. altName = dCert->altNames;
  8041. while (altName) {
  8042. WOLFSSL_MSG("\tindividual AltName check");
  8043. if (MatchDomainName(altName->name, altName->len, domain)){
  8044. match = 1;
  8045. break;
  8046. }
  8047. altName = altName->next;
  8048. }
  8049. return match;
  8050. }
  8051. #ifdef OPENSSL_EXTRA
  8052. /* Check that alternative names, if they exists, match the domain.
  8053. * Fail if there are wild patterns and they didn't match.
  8054. * Check the common name if no alternative names matched.
  8055. *
  8056. * dCert Decoded cert to get the alternative names from.
  8057. * domain Domain name to compare against.
  8058. * checkCN Whether to check the common name.
  8059. * returns whether there was a problem in matching.
  8060. */
  8061. static int CheckForAltNames(DecodedCert* dCert, char* domain, int* checkCN)
  8062. {
  8063. int match;
  8064. DNS_entry* altName = NULL;
  8065. WOLFSSL_MSG("Checking AltNames");
  8066. if (dCert)
  8067. altName = dCert->altNames;
  8068. *checkCN = altName == NULL;
  8069. match = 0;
  8070. while (altName) {
  8071. WOLFSSL_MSG("\tindividual AltName check");
  8072. if (MatchDomainName(altName->name, altName->len, domain)) {
  8073. match = 1;
  8074. *checkCN = 0;
  8075. break;
  8076. }
  8077. /* No matches and wild pattern match failed. */
  8078. else if (altName->name && altName->len >=1 &&
  8079. altName->name[0] == '*' && match == 0) {
  8080. match = -1;
  8081. }
  8082. altName = altName->next;
  8083. }
  8084. return match != -1;
  8085. }
  8086. /* Check the domain name matches the subject alternative name or the subject
  8087. * name.
  8088. *
  8089. * dcert Decoded certificate.
  8090. * domainName The domain name.
  8091. * domainNameLen The length of the domain name.
  8092. * returns DOMAIN_NAME_MISMATCH when no match found and 0 on success.
  8093. */
  8094. int CheckHostName(DecodedCert* dCert, char *domainName, size_t domainNameLen)
  8095. {
  8096. int checkCN;
  8097. /* Assume name is NUL terminated. */
  8098. (void)domainNameLen;
  8099. if (CheckForAltNames(dCert, domainName, &checkCN) == 0) {
  8100. WOLFSSL_MSG("DomainName match on alt names failed too");
  8101. return DOMAIN_NAME_MISMATCH;
  8102. }
  8103. if (checkCN == 1) {
  8104. if (MatchDomainName(dCert->subjectCN, dCert->subjectCNLen,
  8105. domainName) == 0) {
  8106. WOLFSSL_MSG("DomainName match on common name failed");
  8107. return DOMAIN_NAME_MISMATCH;
  8108. }
  8109. }
  8110. return 0;
  8111. }
  8112. int CheckIPAddr(DecodedCert* dCert, char* ipasc)
  8113. {
  8114. WOLFSSL_MSG("Checking IPAddr");
  8115. return CheckHostName(dCert, ipasc, (size_t)XSTRLEN(ipasc));
  8116. }
  8117. #endif
  8118. #ifdef SESSION_CERTS
  8119. static void AddSessionCertToChain(WOLFSSL_X509_CHAIN* chain,
  8120. byte* certBuf, word32 certSz)
  8121. {
  8122. if (chain->count < MAX_CHAIN_DEPTH &&
  8123. certSz < MAX_X509_SIZE) {
  8124. chain->certs[chain->count].length = certSz;
  8125. XMEMCPY(chain->certs[chain->count].buffer, certBuf, certSz);
  8126. chain->count++;
  8127. }
  8128. else {
  8129. WOLFSSL_MSG("Couldn't store chain cert for session");
  8130. }
  8131. }
  8132. #endif
  8133. #if defined(KEEP_PEER_CERT) || defined(SESSION_CERTS) || \
  8134. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8135. /* Copy parts X509 needs from Decoded cert, 0 on success */
  8136. /* The same DecodedCert cannot be copied to WOLFSSL_X509 twice otherwise the
  8137. * altNames pointers could be free'd by second x509 still active by first */
  8138. int CopyDecodedToX509(WOLFSSL_X509* x509, DecodedCert* dCert)
  8139. {
  8140. int ret = 0;
  8141. if (x509 == NULL || dCert == NULL ||
  8142. dCert->subjectCNLen < 0)
  8143. return BAD_FUNC_ARG;
  8144. x509->version = dCert->version + 1;
  8145. XSTRNCPY(x509->issuer.name, dCert->issuer, ASN_NAME_MAX);
  8146. x509->issuer.name[ASN_NAME_MAX - 1] = '\0';
  8147. x509->issuer.sz = (int)XSTRLEN(x509->issuer.name) + 1;
  8148. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8149. if (dCert->issuerName.fullName != NULL) {
  8150. XMEMCPY(&x509->issuer.fullName,
  8151. &dCert->issuerName, sizeof(DecodedName));
  8152. x509->issuer.fullName.fullName = (char*)XMALLOC(
  8153. dCert->issuerName.fullNameLen, x509->heap,
  8154. DYNAMIC_TYPE_X509);
  8155. if (x509->issuer.fullName.fullName != NULL)
  8156. XMEMCPY(x509->issuer.fullName.fullName,
  8157. dCert->issuerName.fullName, dCert->issuerName.fullNameLen);
  8158. }
  8159. x509->issuer.x509 = x509;
  8160. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8161. XSTRNCPY(x509->subject.name, dCert->subject, ASN_NAME_MAX);
  8162. x509->subject.name[ASN_NAME_MAX - 1] = '\0';
  8163. x509->subject.sz = (int)XSTRLEN(x509->subject.name) + 1;
  8164. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8165. if (dCert->subjectName.fullName != NULL) {
  8166. XMEMCPY(&x509->subject.fullName,
  8167. &dCert->subjectName, sizeof(DecodedName));
  8168. x509->subject.fullName.fullName = (char*)XMALLOC(
  8169. dCert->subjectName.fullNameLen, x509->heap, DYNAMIC_TYPE_X509);
  8170. if (x509->subject.fullName.fullName != NULL)
  8171. XMEMCPY(x509->subject.fullName.fullName,
  8172. dCert->subjectName.fullName, dCert->subjectName.fullNameLen);
  8173. }
  8174. x509->subject.x509 = x509;
  8175. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8176. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  8177. x509->subject.rawLen = min(dCert->subjectRawLen, sizeof(x509->subject.raw));
  8178. XMEMCPY(x509->subject.raw, dCert->subjectRaw, x509->subject.rawLen);
  8179. #ifdef WOLFSSL_CERT_EXT
  8180. x509->issuer.rawLen = min(dCert->issuerRawLen, sizeof(x509->issuer.raw));
  8181. XMEMCPY(x509->issuer.raw, dCert->issuerRaw, x509->issuer.rawLen);
  8182. #endif
  8183. #endif
  8184. XMEMCPY(x509->serial, dCert->serial, EXTERNAL_SERIAL_SIZE);
  8185. x509->serialSz = dCert->serialSz;
  8186. if (dCert->subjectCN && dCert->subjectCNLen < ASN_NAME_MAX) {
  8187. XMEMCPY(x509->subjectCN, dCert->subjectCN, dCert->subjectCNLen);
  8188. x509->subjectCN[dCert->subjectCNLen] = '\0';
  8189. }
  8190. else
  8191. x509->subjectCN[0] = '\0';
  8192. #ifdef WOLFSSL_SEP
  8193. {
  8194. int minSz = min(dCert->deviceTypeSz, EXTERNAL_SERIAL_SIZE);
  8195. if (minSz > 0) {
  8196. x509->deviceTypeSz = minSz;
  8197. XMEMCPY(x509->deviceType, dCert->deviceType, minSz);
  8198. }
  8199. else
  8200. x509->deviceTypeSz = 0;
  8201. minSz = min(dCert->hwTypeSz, EXTERNAL_SERIAL_SIZE);
  8202. if (minSz > 0) {
  8203. x509->hwTypeSz = minSz;
  8204. XMEMCPY(x509->hwType, dCert->hwType, minSz);
  8205. }
  8206. else
  8207. x509->hwTypeSz = 0;
  8208. minSz = min(dCert->hwSerialNumSz, EXTERNAL_SERIAL_SIZE);
  8209. if (minSz > 0) {
  8210. x509->hwSerialNumSz = minSz;
  8211. XMEMCPY(x509->hwSerialNum, dCert->hwSerialNum, minSz);
  8212. }
  8213. else
  8214. x509->hwSerialNumSz = 0;
  8215. }
  8216. #endif /* WOLFSSL_SEP */
  8217. {
  8218. int minSz;
  8219. if (dCert->beforeDateLen > 0) {
  8220. minSz = min(dCert->beforeDate[1], MAX_DATE_SZ);
  8221. x509->notBefore.type = dCert->beforeDate[0];
  8222. x509->notBefore.length = minSz;
  8223. XMEMCPY(x509->notBefore.data, &dCert->beforeDate[2], minSz);
  8224. }
  8225. else
  8226. x509->notBefore.length = 0;
  8227. if (dCert->afterDateLen > 0) {
  8228. minSz = min(dCert->afterDate[1], MAX_DATE_SZ);
  8229. x509->notAfter.type = dCert->afterDate[0];
  8230. x509->notAfter.length = minSz;
  8231. XMEMCPY(x509->notAfter.data, &dCert->afterDate[2], minSz);
  8232. }
  8233. else
  8234. x509->notAfter.length = 0;
  8235. }
  8236. if (dCert->publicKey != NULL && dCert->pubKeySize != 0) {
  8237. x509->pubKey.buffer = (byte*)XMALLOC(
  8238. dCert->pubKeySize, x509->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  8239. if (x509->pubKey.buffer != NULL) {
  8240. x509->pubKeyOID = dCert->keyOID;
  8241. x509->pubKey.length = dCert->pubKeySize;
  8242. XMEMCPY(x509->pubKey.buffer, dCert->publicKey, dCert->pubKeySize);
  8243. }
  8244. else
  8245. ret = MEMORY_E;
  8246. #if defined(OPENSSL_ALL)
  8247. if (ret == 0) {
  8248. x509->key.pubKeyOID = dCert->keyOID;
  8249. if (!x509->key.algor) {
  8250. x509->key.algor = wolfSSL_X509_ALGOR_new();
  8251. } else {
  8252. wolfSSL_ASN1_OBJECT_free(x509->key.algor->algorithm);
  8253. }
  8254. if (!(x509->key.algor->algorithm =
  8255. wolfSSL_OBJ_nid2obj(dCert->keyOID))) {
  8256. ret = PUBLIC_KEY_E;
  8257. }
  8258. wolfSSL_EVP_PKEY_free(x509->key.pkey);
  8259. if (!(x509->key.pkey = wolfSSL_d2i_PUBKEY(NULL,
  8260. &dCert->publicKey,
  8261. dCert->pubKeySize))) {
  8262. ret = PUBLIC_KEY_E;
  8263. }
  8264. }
  8265. #endif
  8266. }
  8267. if (dCert->signature != NULL && dCert->sigLength != 0 &&
  8268. dCert->sigLength <= MAX_ENCODED_SIG_SZ) {
  8269. x509->sig.buffer = (byte*)XMALLOC(
  8270. dCert->sigLength, x509->heap, DYNAMIC_TYPE_SIGNATURE);
  8271. if (x509->sig.buffer == NULL) {
  8272. ret = MEMORY_E;
  8273. }
  8274. else {
  8275. XMEMCPY(x509->sig.buffer, dCert->signature, dCert->sigLength);
  8276. x509->sig.length = dCert->sigLength;
  8277. x509->sigOID = dCert->signatureOID;
  8278. }
  8279. #if defined(OPENSSL_ALL)
  8280. wolfSSL_ASN1_OBJECT_free(x509->algor.algorithm);
  8281. if (!(x509->algor.algorithm =
  8282. wolfSSL_OBJ_nid2obj(dCert->signatureOID))) {
  8283. ret = PUBLIC_KEY_E;
  8284. }
  8285. #endif
  8286. }
  8287. /* store cert for potential retrieval */
  8288. if (AllocDer(&x509->derCert, dCert->maxIdx, CERT_TYPE, x509->heap) == 0) {
  8289. XMEMCPY(x509->derCert->buffer, dCert->source, dCert->maxIdx);
  8290. }
  8291. else {
  8292. ret = MEMORY_E;
  8293. }
  8294. x509->altNames = dCert->altNames;
  8295. dCert->weOwnAltNames = 0;
  8296. x509->altNamesNext = x509->altNames; /* index hint */
  8297. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  8298. !defined(IGNORE_NAME_CONSTRAINTS)
  8299. /* add copies of alternate emails from dCert to X509 */
  8300. if (dCert->altEmailNames != NULL) {
  8301. DNS_entry* cur = dCert->altEmailNames;
  8302. while (cur != NULL) {
  8303. if (cur->type == ASN_RFC822_TYPE) {
  8304. DNS_entry* dnsEntry;
  8305. int strLen = cur->len;
  8306. dnsEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), x509->heap,
  8307. DYNAMIC_TYPE_ALTNAME);
  8308. if (dnsEntry == NULL) {
  8309. WOLFSSL_MSG("\tOut of Memory");
  8310. return MEMORY_E;
  8311. }
  8312. dnsEntry->type = ASN_RFC822_TYPE;
  8313. dnsEntry->name = (char*)XMALLOC(strLen + 1, x509->heap,
  8314. DYNAMIC_TYPE_ALTNAME);
  8315. if (dnsEntry->name == NULL) {
  8316. WOLFSSL_MSG("\tOut of Memory");
  8317. XFREE(dnsEntry, x509->heap, DYNAMIC_TYPE_ALTNAME);
  8318. return MEMORY_E;
  8319. }
  8320. dnsEntry->len = strLen;
  8321. XMEMCPY(dnsEntry->name, cur->name, strLen);
  8322. dnsEntry->name[strLen] = '\0';
  8323. dnsEntry->next = x509->altNames;
  8324. x509->altNames = dnsEntry;
  8325. }
  8326. cur = cur->next;
  8327. }
  8328. }
  8329. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8330. x509->isCa = dCert->isCA;
  8331. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8332. x509->pathLength = dCert->pathLength;
  8333. x509->keyUsage = dCert->extKeyUsage;
  8334. x509->CRLdistSet = dCert->extCRLdistSet;
  8335. x509->CRLdistCrit = dCert->extCRLdistCrit;
  8336. x509->CRLInfo = dCert->extCrlInfo;
  8337. x509->CRLInfoSz = dCert->extCrlInfoSz;
  8338. x509->authInfoSet = dCert->extAuthInfoSet;
  8339. x509->authInfoCrit = dCert->extAuthInfoCrit;
  8340. if (dCert->extAuthInfo != NULL && dCert->extAuthInfoSz > 0) {
  8341. x509->authInfo = (byte*)XMALLOC(dCert->extAuthInfoSz, x509->heap,
  8342. DYNAMIC_TYPE_X509_EXT);
  8343. if (x509->authInfo != NULL) {
  8344. XMEMCPY(x509->authInfo, dCert->extAuthInfo, dCert->extAuthInfoSz);
  8345. x509->authInfoSz = dCert->extAuthInfoSz;
  8346. }
  8347. else {
  8348. ret = MEMORY_E;
  8349. }
  8350. }
  8351. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  8352. if (dCert->extAuthInfoCaIssuer != NULL && dCert->extAuthInfoCaIssuerSz > 0) {
  8353. x509->authInfoCaIssuer = (byte*)XMALLOC(dCert->extAuthInfoCaIssuerSz, x509->heap,
  8354. DYNAMIC_TYPE_X509_EXT);
  8355. if (x509->authInfoCaIssuer != NULL) {
  8356. XMEMCPY(x509->authInfoCaIssuer, dCert->extAuthInfoCaIssuer, dCert->extAuthInfoCaIssuerSz);
  8357. x509->authInfoCaIssuerSz = dCert->extAuthInfoCaIssuerSz;
  8358. }
  8359. else {
  8360. ret = MEMORY_E;
  8361. }
  8362. }
  8363. #endif
  8364. x509->basicConstSet = dCert->extBasicConstSet;
  8365. x509->basicConstCrit = dCert->extBasicConstCrit;
  8366. x509->basicConstPlSet = dCert->pathLengthSet;
  8367. x509->subjAltNameSet = dCert->extSubjAltNameSet;
  8368. x509->subjAltNameCrit = dCert->extSubjAltNameCrit;
  8369. x509->authKeyIdSet = dCert->extAuthKeyIdSet;
  8370. x509->authKeyIdCrit = dCert->extAuthKeyIdCrit;
  8371. if (dCert->extAuthKeyIdSrc != NULL && dCert->extAuthKeyIdSz != 0) {
  8372. x509->authKeyId = (byte*)XMALLOC(dCert->extAuthKeyIdSz, x509->heap,
  8373. DYNAMIC_TYPE_X509_EXT);
  8374. if (x509->authKeyId != NULL) {
  8375. XMEMCPY(x509->authKeyId,
  8376. dCert->extAuthKeyIdSrc, dCert->extAuthKeyIdSz);
  8377. x509->authKeyIdSz = dCert->extAuthKeyIdSz;
  8378. }
  8379. else
  8380. ret = MEMORY_E;
  8381. }
  8382. x509->subjKeyIdSet = dCert->extSubjKeyIdSet;
  8383. x509->subjKeyIdCrit = dCert->extSubjKeyIdCrit;
  8384. if (dCert->extSubjKeyIdSrc != NULL && dCert->extSubjKeyIdSz != 0) {
  8385. x509->subjKeyId = (byte*)XMALLOC(dCert->extSubjKeyIdSz, x509->heap,
  8386. DYNAMIC_TYPE_X509_EXT);
  8387. if (x509->subjKeyId != NULL) {
  8388. XMEMCPY(x509->subjKeyId,
  8389. dCert->extSubjKeyIdSrc, dCert->extSubjKeyIdSz);
  8390. x509->subjKeyIdSz = dCert->extSubjKeyIdSz;
  8391. }
  8392. else
  8393. ret = MEMORY_E;
  8394. }
  8395. x509->keyUsageSet = dCert->extKeyUsageSet;
  8396. x509->keyUsageCrit = dCert->extKeyUsageCrit;
  8397. if (dCert->extExtKeyUsageSrc != NULL && dCert->extExtKeyUsageSz > 0) {
  8398. x509->extKeyUsageSrc = (byte*)XMALLOC(dCert->extExtKeyUsageSz,
  8399. x509->heap, DYNAMIC_TYPE_X509_EXT);
  8400. if (x509->extKeyUsageSrc != NULL) {
  8401. XMEMCPY(x509->extKeyUsageSrc, dCert->extExtKeyUsageSrc,
  8402. dCert->extExtKeyUsageSz);
  8403. x509->extKeyUsageSz = dCert->extExtKeyUsageSz;
  8404. x509->extKeyUsageCrit = dCert->extExtKeyUsageCrit;
  8405. x509->extKeyUsageCount = dCert->extExtKeyUsageCount;
  8406. }
  8407. else {
  8408. ret = MEMORY_E;
  8409. }
  8410. }
  8411. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
  8412. x509->certPolicySet = dCert->extCertPolicySet;
  8413. x509->certPolicyCrit = dCert->extCertPolicyCrit;
  8414. #endif /* WOLFSSL_SEP || WOLFSSL_QT */
  8415. #ifdef WOLFSSL_CERT_EXT
  8416. {
  8417. int i;
  8418. for (i = 0; i < dCert->extCertPoliciesNb && i < MAX_CERTPOL_NB; i++)
  8419. XMEMCPY(x509->certPolicies[i], dCert->extCertPolicies[i],
  8420. MAX_CERTPOL_SZ);
  8421. x509->certPoliciesNb = dCert->extCertPoliciesNb;
  8422. }
  8423. #endif /* WOLFSSL_CERT_EXT */
  8424. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8425. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  8426. x509->pkCurveOID = dCert->pkCurveOID;
  8427. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  8428. return ret;
  8429. }
  8430. #endif /* KEEP_PEER_CERT || SESSION_CERTS */
  8431. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
  8432. (defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) && !defined(WOLFSSL_NO_TLS12))
  8433. static int ProcessCSR(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  8434. word32 status_length)
  8435. {
  8436. int ret = 0;
  8437. OcspRequest* request;
  8438. #ifdef WOLFSSL_SMALL_STACK
  8439. CertStatus* status;
  8440. OcspResponse* response;
  8441. #else
  8442. CertStatus status[1];
  8443. OcspResponse response[1];
  8444. #endif
  8445. do {
  8446. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  8447. if (ssl->status_request) {
  8448. request = (OcspRequest*)TLSX_CSR_GetRequest(ssl->extensions);
  8449. ssl->status_request = 0;
  8450. break;
  8451. }
  8452. #endif
  8453. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  8454. if (ssl->status_request_v2) {
  8455. request = (OcspRequest*)TLSX_CSR2_GetRequest(ssl->extensions,
  8456. WOLFSSL_CSR2_OCSP, 0);
  8457. ssl->status_request_v2 = 0;
  8458. break;
  8459. }
  8460. #endif
  8461. return BUFFER_ERROR;
  8462. } while(0);
  8463. if (request == NULL)
  8464. return BAD_CERTIFICATE_STATUS_ERROR; /* not expected */
  8465. #ifdef WOLFSSL_SMALL_STACK
  8466. status = (CertStatus*)XMALLOC(sizeof(CertStatus), ssl->heap,
  8467. DYNAMIC_TYPE_OCSP_STATUS);
  8468. response = (OcspResponse*)XMALLOC(sizeof(OcspResponse), ssl->heap,
  8469. DYNAMIC_TYPE_OCSP_REQUEST);
  8470. if (status == NULL || response == NULL) {
  8471. if (status)
  8472. XFREE(status, NULL, DYNAMIC_TYPE_OCSP_STATUS);
  8473. if (response)
  8474. XFREE(response, NULL, DYNAMIC_TYPE_OCSP_REQUEST);
  8475. return MEMORY_ERROR;
  8476. }
  8477. #endif
  8478. InitOcspResponse(response, status, input +*inOutIdx, status_length);
  8479. if (OcspResponseDecode(response, ssl->ctx->cm, ssl->heap, 0) != 0)
  8480. ret = BAD_CERTIFICATE_STATUS_ERROR;
  8481. else if (CompareOcspReqResp(request, response) != 0)
  8482. ret = BAD_CERTIFICATE_STATUS_ERROR;
  8483. else if (response->responseStatus != OCSP_SUCCESSFUL)
  8484. ret = BAD_CERTIFICATE_STATUS_ERROR;
  8485. else if (response->status->status == CERT_REVOKED)
  8486. ret = OCSP_CERT_REVOKED;
  8487. else if (response->status->status != CERT_GOOD)
  8488. ret = BAD_CERTIFICATE_STATUS_ERROR;
  8489. *inOutIdx += status_length;
  8490. #ifdef WOLFSSL_SMALL_STACK
  8491. XFREE(status, ssl->heap, DYNAMIC_TYPE_OCSP_STATUS);
  8492. XFREE(response, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  8493. #endif
  8494. return ret;
  8495. }
  8496. #endif
  8497. #ifdef HAVE_PK_CALLBACKS
  8498. #ifdef HAVE_ECC
  8499. static int SigPkCbEccVerify(const unsigned char* sig, unsigned int sigSz,
  8500. const unsigned char* hash, unsigned int hashSz,
  8501. const unsigned char* keyDer, unsigned int keySz,
  8502. int* result, void* ctx)
  8503. {
  8504. int ret = NOT_COMPILED_IN;
  8505. WOLFSSL* ssl = (WOLFSSL*)ctx;
  8506. if (ssl && ssl->ctx->EccVerifyCb) {
  8507. ret = ssl->ctx->EccVerifyCb(ssl, sig, sigSz, hash, hashSz,
  8508. keyDer, keySz, result, ssl->EccVerifyCtx);
  8509. }
  8510. return ret;
  8511. }
  8512. #endif
  8513. #ifndef NO_RSA
  8514. static int SigPkCbRsaVerify(unsigned char* sig, unsigned int sigSz,
  8515. unsigned char** out, const unsigned char* keyDer, unsigned int keySz,
  8516. void* ctx)
  8517. {
  8518. int ret = NOT_COMPILED_IN;
  8519. WOLFSSL* ssl = (WOLFSSL*)ctx;
  8520. if (ssl && ssl->ctx->RsaVerifyCb) {
  8521. ret = ssl->ctx->RsaVerifyCb(ssl, sig, sigSz, out, keyDer, keySz,
  8522. ssl->RsaVerifyCtx);
  8523. }
  8524. return ret;
  8525. }
  8526. #endif
  8527. int InitSigPkCb(WOLFSSL* ssl, SignatureCtx* sigCtx)
  8528. {
  8529. if (ssl == NULL || sigCtx == NULL)
  8530. return BAD_FUNC_ARG;
  8531. /* only setup the verify callback if a PK is set */
  8532. #ifdef HAVE_ECC
  8533. if (ssl->ctx->EccVerifyCb) {
  8534. sigCtx->pkCbEcc = SigPkCbEccVerify;
  8535. sigCtx->pkCtxEcc = ssl;
  8536. }
  8537. #endif
  8538. #ifndef NO_RSA
  8539. /* only setup the verify callback if a PK is set */
  8540. if (ssl->ctx->RsaVerifyCb) {
  8541. sigCtx->pkCbRsa = SigPkCbRsaVerify;
  8542. sigCtx->pkCtxRsa = ssl;
  8543. }
  8544. #endif
  8545. return 0;
  8546. }
  8547. #endif /* HAVE_PK_CALLBACKS */
  8548. #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  8549. static void DoCertFatalAlert(WOLFSSL* ssl, int ret)
  8550. {
  8551. int alertWhy;
  8552. if (ssl == NULL || ret == 0) {
  8553. return;
  8554. }
  8555. /* Determine alert reason */
  8556. alertWhy = bad_certificate;
  8557. if (ret == ASN_AFTER_DATE_E || ret == ASN_BEFORE_DATE_E) {
  8558. alertWhy = certificate_expired;
  8559. }
  8560. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_APACHE_HTTPD))
  8561. else if (ret == CRL_CERT_REVOKED) {
  8562. alertWhy = certificate_revoked;
  8563. }
  8564. #endif
  8565. else if (ret == NO_PEER_CERT) {
  8566. #ifdef WOLFSSL_TLS13
  8567. if (ssl->options.tls1_3) {
  8568. alertWhy = certificate_required;
  8569. }
  8570. else
  8571. #endif
  8572. {
  8573. alertWhy = handshake_failure;
  8574. }
  8575. }
  8576. /* send fatal alert and mark connection closed */
  8577. SendAlert(ssl, alert_fatal, alertWhy); /* try to send */
  8578. ssl->options.isClosed = 1;
  8579. }
  8580. /* WOLFSSL_ALWAYS_VERIFY_CB: Use verify callback for success or failure cases */
  8581. /* WOLFSSL_VERIFY_CB_ALL_CERTS: Issue callback for all intermediate certificates */
  8582. /* Callback is issued for certificate presented in TLS Certificate (11) packet.
  8583. * The intermediates are done first then peer leaf cert last. Use the
  8584. * store->error_depth member to determine index (0=peer, >1 intermediates)
  8585. */
  8586. int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl, int ret,
  8587. ProcPeerCertArgs* args)
  8588. {
  8589. int verify_ok = 0, use_cb = 0;
  8590. void *heap = (ssl != NULL) ? ssl->heap : cm->heap;
  8591. /* Determine if verify was okay */
  8592. if (ret == 0) {
  8593. verify_ok = 1;
  8594. }
  8595. /* Determine if verify callback should be used */
  8596. if (ret != 0) {
  8597. if ((ssl != NULL) && (!ssl->options.verifyNone)) {
  8598. use_cb = 1; /* always report errors */
  8599. }
  8600. }
  8601. #ifdef WOLFSSL_ALWAYS_VERIFY_CB
  8602. /* always use verify callback on peer leaf cert */
  8603. if (args->certIdx == 0) {
  8604. use_cb = 1;
  8605. }
  8606. #endif
  8607. #ifdef WOLFSSL_VERIFY_CB_ALL_CERTS
  8608. /* perform verify callback on other intermediate certs (not just peer) */
  8609. if (args->certIdx > 0) {
  8610. use_cb = 1;
  8611. }
  8612. #endif
  8613. #if defined(OPENSSL_EXTRA)
  8614. /* perform domain name check on the peer certificate */
  8615. if (args->dCertInit && args->dCert && (ssl != NULL) &&
  8616. ssl->param && ssl->param->hostName[0]) {
  8617. /* If altNames names is present, then subject common name is ignored */
  8618. if (args->dCert->altNames != NULL) {
  8619. if (CheckAltNames(args->dCert, ssl->param->hostName) == 0 ) {
  8620. if (ret == 0) {
  8621. ret = DOMAIN_NAME_MISMATCH;
  8622. }
  8623. }
  8624. }
  8625. else {
  8626. if (args->dCert->subjectCN) {
  8627. if (MatchDomainName(args->dCert->subjectCN,
  8628. args->dCert->subjectCNLen,
  8629. ssl->param->hostName) == 0) {
  8630. if (ret == 0) {
  8631. ret = DOMAIN_NAME_MISMATCH;
  8632. }
  8633. }
  8634. }
  8635. }
  8636. }
  8637. /* perform IP address check on the peer certificate */
  8638. if ((args->dCertInit != 0) && (args->dCert != NULL) && (ssl != NULL) &&
  8639. (ssl->param != NULL) && (XSTRLEN(ssl->param->ipasc) > 0)) {
  8640. if (CheckIPAddr(args->dCert, ssl->param->ipasc) != 0) {
  8641. if (ret == 0) {
  8642. ret = IPADDR_MISMATCH;
  8643. }
  8644. }
  8645. }
  8646. #endif
  8647. /* if verify callback has been set */
  8648. if ((use_cb && (ssl != NULL) && ((ssl->verifyCallback != NULL)
  8649. #ifdef OPENSSL_ALL
  8650. || (ssl->ctx->verifyCertCb != NULL)
  8651. #endif
  8652. ))
  8653. #ifndef NO_WOLFSSL_CM_VERIFY
  8654. || (cm->verifyCallback != NULL)
  8655. #endif
  8656. ) {
  8657. int verifyFail = 0;
  8658. #ifdef WOLFSSL_SMALL_STACK
  8659. WOLFSSL_X509_STORE_CTX* store;
  8660. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8661. WOLFSSL_X509* x509;
  8662. #endif
  8663. char* domain = NULL;
  8664. #else
  8665. WOLFSSL_X509_STORE_CTX store[1];
  8666. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8667. WOLFSSL_X509 x509[1];
  8668. #endif
  8669. char domain[ASN_NAME_MAX];
  8670. #endif
  8671. #ifdef WOLFSSL_SMALL_STACK
  8672. store = (WOLFSSL_X509_STORE_CTX*)XMALLOC(
  8673. sizeof(WOLFSSL_X509_STORE_CTX), heap, DYNAMIC_TYPE_X509_STORE);
  8674. if (store == NULL) {
  8675. return MEMORY_E;
  8676. }
  8677. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8678. x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), heap,
  8679. DYNAMIC_TYPE_X509);
  8680. if (x509 == NULL) {
  8681. XFREE(store, heap, DYNAMIC_TYPE_X509);
  8682. return MEMORY_E;
  8683. }
  8684. #endif
  8685. domain = (char*)XMALLOC(ASN_NAME_MAX, heap, DYNAMIC_TYPE_STRING);
  8686. if (domain == NULL) {
  8687. XFREE(store, heap, DYNAMIC_TYPE_X509);
  8688. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8689. XFREE(x509, heap, DYNAMIC_TYPE_X509);
  8690. #endif
  8691. return MEMORY_E;
  8692. }
  8693. #endif /* WOLFSSL_SMALL_STACK */
  8694. XMEMSET(store, 0, sizeof(WOLFSSL_X509_STORE_CTX));
  8695. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8696. XMEMSET(x509, 0, sizeof(WOLFSSL_X509));
  8697. #endif
  8698. domain[0] = '\0';
  8699. /* build subject CN as string to return in store */
  8700. if (args->dCertInit && args->dCert && args->dCert->subjectCN) {
  8701. int subjectCNLen = args->dCert->subjectCNLen;
  8702. if (subjectCNLen > ASN_NAME_MAX-1)
  8703. subjectCNLen = ASN_NAME_MAX-1;
  8704. if (subjectCNLen > 0) {
  8705. XMEMCPY(domain, args->dCert->subjectCN, subjectCNLen);
  8706. domain[subjectCNLen] = '\0';
  8707. }
  8708. }
  8709. store->error = ret;
  8710. store->error_depth = args->certIdx;
  8711. store->discardSessionCerts = 0;
  8712. store->domain = domain;
  8713. store->userCtx = (ssl != NULL) ? ssl->verifyCbCtx : cm;
  8714. store->certs = args->certs;
  8715. store->totalCerts = args->totalCerts;
  8716. #if defined(HAVE_EX_DATA) || defined(FORTRESS)
  8717. if (wolfSSL_CRYPTO_set_ex_data(&store->ex_data, 0, ssl)
  8718. != WOLFSSL_SUCCESS) {
  8719. WOLFSSL_MSG("Failed to store ssl context in WOLFSSL_X509_STORE_CTX");
  8720. }
  8721. #endif
  8722. if (ssl != NULL) {
  8723. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
  8724. if (ssl->ctx->x509_store_pt != NULL) {
  8725. store->store = ssl->ctx->x509_store_pt;
  8726. }
  8727. else {
  8728. store->store = &ssl->ctx->x509_store;
  8729. }
  8730. #if defined(OPENSSL_EXTRA)
  8731. store->depth = args->count;
  8732. store->param = (WOLFSSL_X509_VERIFY_PARAM*)XMALLOC(
  8733. sizeof(WOLFSSL_X509_VERIFY_PARAM),
  8734. heap, DYNAMIC_TYPE_OPENSSL);
  8735. if (store->param == NULL) {
  8736. #ifdef WOLFSSL_SMALL_STACK
  8737. XFREE(domain, heap, DYNAMIC_TYPE_STRING);
  8738. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8739. XFREE(x509, heap, DYNAMIC_TYPE_X509);
  8740. #endif
  8741. XFREE(store, heap, DYNAMIC_TYPE_X509_STORE);
  8742. #endif
  8743. return MEMORY_E;
  8744. }
  8745. XMEMSET(store->param, 0, sizeof(WOLFSSL_X509_VERIFY_PARAM));
  8746. /* Overwrite with non-default param values in SSL */
  8747. if (ssl->param) {
  8748. if (ssl->param->check_time)
  8749. store->param->check_time = ssl->param->check_time;
  8750. if (ssl->param->flags)
  8751. store->param->flags = ssl->param->flags;
  8752. if (ssl->param->hostName[0])
  8753. XMEMCPY(store->param->hostName, ssl->param->hostName,
  8754. WOLFSSL_HOST_NAME_MAX);
  8755. }
  8756. #endif /* defined(OPENSSL_EXTRA) */
  8757. #endif /* defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)*/
  8758. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8759. #ifdef KEEP_PEER_CERT
  8760. if (args->certIdx == 0) {
  8761. store->current_cert = &ssl->peerCert; /* use existing X509 */
  8762. }
  8763. else
  8764. #endif
  8765. {
  8766. InitX509(x509, 0, heap);
  8767. if (CopyDecodedToX509(x509, args->dCert) == 0) {
  8768. store->current_cert = x509;
  8769. }
  8770. else {
  8771. FreeX509(x509);
  8772. }
  8773. }
  8774. #endif
  8775. #ifdef SESSION_CERTS
  8776. store->sesChain = &ssl->session.chain;
  8777. #endif
  8778. }
  8779. #ifndef NO_WOLFSSL_CM_VERIFY
  8780. /* non-zero return code indicates failure override */
  8781. if ((cm != NULL) && (cm->verifyCallback != NULL)) {
  8782. store->userCtx = cm;
  8783. if (cm->verifyCallback(verify_ok, store)) {
  8784. if (ret != 0) {
  8785. WOLFSSL_MSG("Verify CM callback overriding error!");
  8786. ret = 0;
  8787. }
  8788. }
  8789. else {
  8790. verifyFail = 1;
  8791. }
  8792. }
  8793. #endif
  8794. if (ssl != NULL) {
  8795. #ifdef OPENSSL_ALL
  8796. /* non-zero return code indicates failure override */
  8797. if (ssl->ctx->verifyCertCb) {
  8798. if (ssl->ctx->verifyCertCb(store, ssl->ctx->verifyCertCbArg)) {
  8799. if (ret != 0) {
  8800. WOLFSSL_MSG("Verify Cert callback overriding error!");
  8801. ret = 0;
  8802. }
  8803. }
  8804. else {
  8805. verifyFail = 1;
  8806. }
  8807. }
  8808. #endif
  8809. /* non-zero return code indicates failure override */
  8810. if (ssl->verifyCallback) {
  8811. if (ssl->verifyCallback(verify_ok, store)) {
  8812. if (ret != 0) {
  8813. WOLFSSL_MSG("Verify callback overriding error!");
  8814. ret = 0;
  8815. }
  8816. }
  8817. else {
  8818. verifyFail = 1;
  8819. }
  8820. }
  8821. }
  8822. if (verifyFail) {
  8823. /* induce error if one not present */
  8824. if (ret == 0) {
  8825. ret = VERIFY_CERT_ERROR;
  8826. }
  8827. /* mark as verify error */
  8828. args->verifyErr = 1;
  8829. }
  8830. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8831. if (args->certIdx > 0)
  8832. FreeX509(x509);
  8833. #endif
  8834. #if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
  8835. wolfSSL_sk_X509_free(store->chain);
  8836. store->chain = NULL;
  8837. #endif
  8838. #ifdef SESSION_CERTS
  8839. if ((ssl != NULL) && (store->discardSessionCerts)) {
  8840. WOLFSSL_MSG("Verify callback requested discard sess certs");
  8841. ssl->session.chain.count = 0;
  8842. #ifdef WOLFSSL_ALT_CERT_CHAINS
  8843. ssl->session.altChain.count = 0;
  8844. #endif
  8845. }
  8846. #endif /* SESSION_CERTS */
  8847. #ifdef OPENSSL_EXTRA
  8848. if ((ssl != NULL) && (store->param)) {
  8849. XFREE(store->param, heap, DYNAMIC_TYPE_OPENSSL);
  8850. }
  8851. #endif
  8852. #ifdef WOLFSSL_SMALL_STACK
  8853. XFREE(domain, heap, DYNAMIC_TYPE_STRING);
  8854. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8855. XFREE(x509, heap, DYNAMIC_TYPE_X509);
  8856. #endif
  8857. XFREE(store, heap, DYNAMIC_TYPE_X509_STORE);
  8858. #endif
  8859. }
  8860. (void)heap;
  8861. return ret;
  8862. }
  8863. static void FreeProcPeerCertArgs(WOLFSSL* ssl, void* pArgs)
  8864. {
  8865. ProcPeerCertArgs* args = (ProcPeerCertArgs*)pArgs;
  8866. (void)ssl;
  8867. if (args->certs) {
  8868. XFREE(args->certs, ssl->heap, DYNAMIC_TYPE_DER);
  8869. args->certs = NULL;
  8870. }
  8871. #ifdef WOLFSSL_TLS13
  8872. if (args->exts) {
  8873. XFREE(args->exts, ssl->heap, DYNAMIC_TYPE_CERT_EXT);
  8874. args->exts = NULL;
  8875. }
  8876. #endif
  8877. if (args->dCert) {
  8878. if (args->dCertInit) {
  8879. FreeDecodedCert(args->dCert);
  8880. args->dCertInit = 0;
  8881. }
  8882. XFREE(args->dCert, ssl->heap, DYNAMIC_TYPE_DCERT);
  8883. args->dCert = NULL;
  8884. }
  8885. }
  8886. static int ProcessPeerCertParse(WOLFSSL* ssl, ProcPeerCertArgs* args,
  8887. int certType, int verify, byte** pSubjectHash, int* pAlreadySigner)
  8888. {
  8889. int ret = 0;
  8890. buffer* cert;
  8891. byte* subjectHash = NULL;
  8892. int alreadySigner = 0;
  8893. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  8894. int sigRet = 0;
  8895. #endif
  8896. if (ssl == NULL || args == NULL)
  8897. return BAD_FUNC_ARG;
  8898. /* check to make sure certificate index is valid */
  8899. if (args->certIdx > args->count)
  8900. return BUFFER_E;
  8901. /* check if returning from non-blocking OCSP */
  8902. /* skip this section because cert is already initialized and parsed */
  8903. #ifdef WOLFSSL_NONBLOCK_OCSP
  8904. if (args->lastErr == OCSP_WANT_READ) {
  8905. args->lastErr = 0; /* clear error */
  8906. return 0;
  8907. }
  8908. #endif
  8909. #ifdef WOLFSSL_TRUST_PEER_CERT
  8910. /* we have trusted peer */
  8911. if (args->haveTrustPeer) {
  8912. return 0;
  8913. }
  8914. #endif
  8915. /* get certificate buffer */
  8916. cert = &args->certs[args->certIdx];
  8917. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  8918. if (verify == VERIFY) {
  8919. /* for small cert verify, release decoded cert during signature check to
  8920. reduce peak memory usage */
  8921. if (args->dCert != NULL) {
  8922. if (args->dCertInit) {
  8923. FreeDecodedCert(args->dCert);
  8924. args->dCertInit = 0;
  8925. }
  8926. XFREE(args->dCert, ssl->heap, DYNAMIC_TYPE_DCERT);
  8927. args->dCert = NULL;
  8928. }
  8929. /* perform cert parsing and signature check */
  8930. sigRet = CheckCertSignature(cert->buffer, cert->length,
  8931. ssl->heap, ssl->ctx->cm);
  8932. /* fail on errors here after the ParseCertRelative call, so dCert is populated */
  8933. /* verify name only in ParseCertRelative below, signature check done */
  8934. verify = VERIFY_NAME;
  8935. }
  8936. #endif /* WOLFSSL_SMALL_CERT_VERIFY */
  8937. /* make sure the decoded cert structure is allocated and initialized */
  8938. if (!args->dCertInit
  8939. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  8940. || args->dCert == NULL
  8941. #endif
  8942. ) {
  8943. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  8944. if (args->dCert == NULL) {
  8945. args->dCert = (DecodedCert*)XMALLOC(
  8946. sizeof(DecodedCert), ssl->heap,
  8947. DYNAMIC_TYPE_DCERT);
  8948. if (args->dCert == NULL) {
  8949. return MEMORY_E;
  8950. }
  8951. }
  8952. #endif
  8953. InitDecodedCert(args->dCert, cert->buffer, cert->length, ssl->heap);
  8954. args->dCertInit = 1;
  8955. args->dCert->sigCtx.devId = ssl->devId;
  8956. #ifdef WOLFSSL_ASYNC_CRYPT
  8957. args->dCert->sigCtx.asyncCtx = ssl;
  8958. #endif
  8959. #ifdef HAVE_PK_CALLBACKS
  8960. /* setup the PK callback context */
  8961. ret = InitSigPkCb(ssl, &args->dCert->sigCtx);
  8962. if (ret != 0)
  8963. return ret;
  8964. #endif
  8965. }
  8966. /* Parse Certificate */
  8967. ret = ParseCertRelative(args->dCert, certType, verify, ssl->ctx->cm);
  8968. /* perform below checks for date failure cases */
  8969. if (ret == 0 || ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  8970. /* get subject and determine if already loaded */
  8971. #ifndef NO_SKID
  8972. if (args->dCert->extAuthKeyIdSet)
  8973. subjectHash = args->dCert->extSubjKeyId;
  8974. else
  8975. #endif
  8976. subjectHash = args->dCert->subjectHash;
  8977. alreadySigner = AlreadySigner(ssl->ctx->cm, subjectHash);
  8978. }
  8979. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  8980. /* get signature check failures from above */
  8981. if (ret == 0)
  8982. ret = sigRet;
  8983. #endif
  8984. if (pSubjectHash)
  8985. *pSubjectHash = subjectHash;
  8986. if (pAlreadySigner)
  8987. *pAlreadySigner = alreadySigner;
  8988. #ifdef WOLFSSL_ASYNC_CRYPT
  8989. if (ret == WC_PENDING_E) {
  8990. ret = wolfSSL_AsyncPush(ssl,
  8991. args->dCert->sigCtx.asyncDev);
  8992. }
  8993. #endif
  8994. return ret;
  8995. }
  8996. /* Check key sizes for certs. Is redundant check since
  8997. ProcessBuffer also performs this check. */
  8998. static int ProcessPeerCertCheckKey(WOLFSSL* ssl, ProcPeerCertArgs* args)
  8999. {
  9000. int ret = 0;
  9001. if (ssl->options.verifyNone) {
  9002. return ret;
  9003. }
  9004. switch (args->dCert->keyOID) {
  9005. #ifndef NO_RSA
  9006. case RSAk:
  9007. if (ssl->options.minRsaKeySz < 0 ||
  9008. args->dCert->pubKeySize <
  9009. (word16)ssl->options.minRsaKeySz) {
  9010. WOLFSSL_MSG(
  9011. "RSA key size in cert chain error");
  9012. ret = RSA_KEY_SIZE_E;
  9013. }
  9014. break;
  9015. #endif /* !NO_RSA */
  9016. #ifdef HAVE_ECC
  9017. case ECDSAk:
  9018. if (ssl->options.minEccKeySz < 0 ||
  9019. args->dCert->pubKeySize <
  9020. (word16)ssl->options.minEccKeySz) {
  9021. WOLFSSL_MSG(
  9022. "ECC key size in cert chain error");
  9023. ret = ECC_KEY_SIZE_E;
  9024. }
  9025. break;
  9026. #endif /* HAVE_ECC */
  9027. #ifdef HAVE_ED25519
  9028. case ED25519k:
  9029. if (ssl->options.minEccKeySz < 0 ||
  9030. ED25519_KEY_SIZE < (word16)ssl->options.minEccKeySz) {
  9031. WOLFSSL_MSG(
  9032. "ECC key size in cert chain error");
  9033. ret = ECC_KEY_SIZE_E;
  9034. }
  9035. break;
  9036. #endif /* HAVE_ED25519 */
  9037. #ifdef HAVE_ED448
  9038. case ED448k:
  9039. if (ssl->options.minEccKeySz < 0 ||
  9040. ED448_KEY_SIZE < (word16)ssl->options.minEccKeySz) {
  9041. WOLFSSL_MSG(
  9042. "ECC key size in cert chain error");
  9043. ret = ECC_KEY_SIZE_E;
  9044. }
  9045. break;
  9046. #endif /* HAVE_ED448 */
  9047. default:
  9048. WOLFSSL_MSG("Key size not checked");
  9049. /* key not being checked for size if not in
  9050. switch */
  9051. break;
  9052. }
  9053. return ret;
  9054. }
  9055. int ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  9056. word32 totalSz)
  9057. {
  9058. int ret = 0;
  9059. #ifdef WOLFSSL_ASYNC_CRYPT
  9060. ProcPeerCertArgs* args = (ProcPeerCertArgs*)ssl->async.args;
  9061. typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
  9062. (void)sizeof(args_test);
  9063. #elif defined(WOLFSSL_NONBLOCK_OCSP)
  9064. ProcPeerCertArgs* args = ssl->nonblockarg;
  9065. #elif defined(WOLFSSL_SMALL_STACK)
  9066. ProcPeerCertArgs* args = NULL;
  9067. #else
  9068. ProcPeerCertArgs args[1];
  9069. #endif
  9070. byte* subjectHash = NULL;
  9071. int alreadySigner = 0;
  9072. WOLFSSL_ENTER("ProcessPeerCerts");
  9073. #ifdef WOLFSSL_ASYNC_CRYPT
  9074. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  9075. if (ret != WC_NOT_PENDING_E) {
  9076. /* Check for error */
  9077. if (ret < 0)
  9078. goto exit_ppc;
  9079. }
  9080. else
  9081. #elif defined(WOLFSSL_NONBLOCK_OCSP)
  9082. if (args == NULL) {
  9083. args = (ProcPeerCertArgs*)XMALLOC(
  9084. sizeof(ProcPeerCertArgs), ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9085. if (args == NULL) {
  9086. ERROR_OUT(MEMORY_E, exit_ppc);
  9087. }
  9088. }
  9089. if (ssl->nonblockarg == NULL) /* new args */
  9090. #elif defined(WOLFSSL_SMALL_STACK)
  9091. args = (ProcPeerCertArgs*)XMALLOC(
  9092. sizeof(ProcPeerCertArgs), ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9093. if (args == NULL) {
  9094. ERROR_OUT(MEMORY_E, exit_ppc);
  9095. }
  9096. #endif
  9097. {
  9098. /* Reset state */
  9099. ret = 0;
  9100. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  9101. XMEMSET(args, 0, sizeof(ProcPeerCertArgs));
  9102. args->idx = *inOutIdx;
  9103. args->begin = *inOutIdx;
  9104. #ifdef WOLFSSL_ASYNC_CRYPT
  9105. ssl->async.freeArgs = FreeProcPeerCertArgs;
  9106. #elif defined(WOLFSSL_NONBLOCK_OCSP)
  9107. ssl->nonblockarg = args;
  9108. #endif
  9109. }
  9110. switch (ssl->options.asyncState)
  9111. {
  9112. case TLS_ASYNC_BEGIN:
  9113. {
  9114. word32 listSz;
  9115. #ifdef WOLFSSL_CALLBACKS
  9116. if (ssl->hsInfoOn)
  9117. AddPacketName(ssl, "Certificate");
  9118. if (ssl->toInfoOn)
  9119. AddLateName("Certificate", &ssl->timeoutInfo);
  9120. #endif
  9121. #ifdef WOLFSSL_TLS13
  9122. if (ssl->options.tls1_3) {
  9123. byte ctxSz;
  9124. /* Certificate Request Context */
  9125. if ((args->idx - args->begin) + OPAQUE8_LEN > totalSz)
  9126. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  9127. ctxSz = *(input + args->idx);
  9128. args->idx++;
  9129. if ((args->idx - args->begin) + ctxSz > totalSz)
  9130. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  9131. #ifndef NO_WOLFSSL_CLIENT
  9132. /* Must be empty when received from server. */
  9133. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  9134. if (ctxSz != 0) {
  9135. ERROR_OUT(INVALID_CERT_CTX_E, exit_ppc);
  9136. }
  9137. }
  9138. #endif
  9139. #ifndef NO_WOLFSSL_SERVER
  9140. /* Must contain value sent in request. */
  9141. if (ssl->options.side == WOLFSSL_SERVER_END) {
  9142. if (ssl->options.handShakeState != HANDSHAKE_DONE &&
  9143. ctxSz != 0) {
  9144. ERROR_OUT(INVALID_CERT_CTX_E, exit_ppc);
  9145. }
  9146. else if (ssl->options.handShakeState == HANDSHAKE_DONE) {
  9147. #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
  9148. CertReqCtx* curr = ssl->certReqCtx;
  9149. CertReqCtx* prev = NULL;
  9150. while (curr != NULL) {
  9151. if ((ctxSz == curr->len) &&
  9152. XMEMCMP(&curr->ctx, input + args->idx, ctxSz)
  9153. == 0) {
  9154. if (prev != NULL)
  9155. prev->next = curr->next;
  9156. else
  9157. ssl->certReqCtx = curr->next;
  9158. XFREE(curr, ssl->heap,
  9159. DYNAMIC_TYPE_TMP_BUFFER);
  9160. break;
  9161. }
  9162. prev = curr;
  9163. curr = curr->next;
  9164. }
  9165. if (curr == NULL)
  9166. #endif
  9167. ERROR_OUT(INVALID_CERT_CTX_E, exit_ppc);
  9168. }
  9169. }
  9170. #endif
  9171. args->idx += ctxSz;
  9172. #ifdef OPENSSL_EXTRA
  9173. /* allocate buffer for cert extensions */
  9174. args->exts = (buffer*)XMALLOC(sizeof(buffer) *
  9175. (ssl->verifyDepth + 1), ssl->heap, DYNAMIC_TYPE_CERT_EXT);
  9176. if (args->exts == NULL) {
  9177. ERROR_OUT(MEMORY_E, exit_ppc);
  9178. }
  9179. #else
  9180. /* allocate buffer for cert extensions */
  9181. args->exts = (buffer*)XMALLOC(sizeof(buffer) * MAX_CHAIN_DEPTH,
  9182. ssl->heap, DYNAMIC_TYPE_CERT_EXT);
  9183. if (args->exts == NULL) {
  9184. ERROR_OUT(MEMORY_E, exit_ppc);
  9185. }
  9186. #endif
  9187. }
  9188. #endif
  9189. /* allocate buffer for certs */
  9190. #ifdef OPENSSL_EXTRA
  9191. args->certs = (buffer*)XMALLOC(sizeof(buffer) *
  9192. (ssl->verifyDepth + 1), ssl->heap, DYNAMIC_TYPE_DER);
  9193. if (args->certs == NULL) {
  9194. ERROR_OUT(MEMORY_E, exit_ppc);
  9195. }
  9196. XMEMSET(args->certs, 0, sizeof(buffer) * (ssl->verifyDepth + 1));
  9197. #else
  9198. args->certs = (buffer*)XMALLOC(sizeof(buffer) * MAX_CHAIN_DEPTH,
  9199. ssl->heap, DYNAMIC_TYPE_DER);
  9200. if (args->certs == NULL) {
  9201. ERROR_OUT(MEMORY_E, exit_ppc);
  9202. }
  9203. XMEMSET(args->certs, 0, sizeof(buffer) * MAX_CHAIN_DEPTH);
  9204. #endif /* OPENSSL_EXTRA */
  9205. /* Certificate List */
  9206. if ((args->idx - args->begin) + OPAQUE24_LEN > totalSz) {
  9207. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  9208. }
  9209. c24to32(input + args->idx, &listSz);
  9210. args->idx += OPAQUE24_LEN;
  9211. if (listSz > MAX_CERTIFICATE_SZ) {
  9212. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  9213. }
  9214. if ((args->idx - args->begin) + listSz != totalSz) {
  9215. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  9216. }
  9217. WOLFSSL_MSG("Loading peer's cert chain");
  9218. /* first put cert chain into buffer so can verify top down
  9219. we're sent bottom up */
  9220. while (listSz) {
  9221. word32 certSz;
  9222. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  9223. if (args->totalCerts > ssl->verifyDepth) {
  9224. ssl->peerVerifyRet = X509_V_ERR_CERT_CHAIN_TOO_LONG;
  9225. ERROR_OUT(MAX_CHAIN_ERROR, exit_ppc);
  9226. }
  9227. #else
  9228. if (args->totalCerts >= ssl->verifyDepth ||
  9229. args->totalCerts >= MAX_CHAIN_DEPTH) {
  9230. ERROR_OUT(MAX_CHAIN_ERROR, exit_ppc);
  9231. }
  9232. #endif
  9233. if ((args->idx - args->begin) + OPAQUE24_LEN > totalSz) {
  9234. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  9235. }
  9236. c24to32(input + args->idx, &certSz);
  9237. args->idx += OPAQUE24_LEN;
  9238. if ((args->idx - args->begin) + certSz > totalSz) {
  9239. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  9240. }
  9241. args->certs[args->totalCerts].length = certSz;
  9242. args->certs[args->totalCerts].buffer = input + args->idx;
  9243. #ifdef SESSION_CERTS
  9244. AddSessionCertToChain(&ssl->session.chain,
  9245. input + args->idx, certSz);
  9246. #endif /* SESSION_CERTS */
  9247. args->idx += certSz;
  9248. listSz -= certSz + CERT_HEADER_SZ;
  9249. #ifdef WOLFSSL_TLS13
  9250. /* Extensions */
  9251. if (ssl->options.tls1_3) {
  9252. word16 extSz;
  9253. if ((args->idx - args->begin) + OPAQUE16_LEN > totalSz) {
  9254. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  9255. }
  9256. ato16(input + args->idx, &extSz);
  9257. args->idx += OPAQUE16_LEN;
  9258. if ((args->idx - args->begin) + extSz > totalSz) {
  9259. ERROR_OUT(BUFFER_ERROR, exit_ppc);
  9260. }
  9261. /* Store extension data info for later processing. */
  9262. args->exts[args->totalCerts].length = extSz;
  9263. args->exts[args->totalCerts].buffer = input + args->idx;
  9264. args->idx += extSz;
  9265. listSz -= extSz + OPAQUE16_LEN;
  9266. ret = TLSX_Parse(ssl, args->exts[args->totalCerts].buffer,
  9267. args->exts[args->totalCerts].length, certificate, NULL);
  9268. if (ret < 0) {
  9269. ERROR_OUT(ret, exit_ppc);
  9270. }
  9271. }
  9272. #endif
  9273. args->totalCerts++;
  9274. WOLFSSL_MSG("\tPut another cert into chain");
  9275. } /* while (listSz) */
  9276. args->count = args->totalCerts;
  9277. args->certIdx = 0; /* select peer cert (first one) */
  9278. if (args->count == 0 && ssl->options.mutualAuth &&
  9279. ssl->options.side == WOLFSSL_SERVER_END) {
  9280. ret = NO_PEER_CERT;
  9281. DoCertFatalAlert(ssl, ret);
  9282. }
  9283. args->dCertInit = 0;
  9284. #ifndef WOLFSSL_SMALL_CERT_VERIFY
  9285. args->dCert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
  9286. DYNAMIC_TYPE_DCERT);
  9287. if (args->dCert == NULL) {
  9288. ERROR_OUT(MEMORY_E, exit_ppc);
  9289. }
  9290. XMEMSET(args->dCert, 0, sizeof(DecodedCert));
  9291. #endif
  9292. /* Advance state and proceed */
  9293. ssl->options.asyncState = TLS_ASYNC_BUILD;
  9294. } /* case TLS_ASYNC_BEGIN */
  9295. FALL_THROUGH;
  9296. case TLS_ASYNC_BUILD:
  9297. {
  9298. if (args->count > 0) {
  9299. /* check for trusted peer and get untrustedDepth */
  9300. #if defined(WOLFSSL_TRUST_PEER_CERT) || defined(OPENSSL_EXTRA)
  9301. if (args->certIdx == 0) {
  9302. #ifdef WOLFSSL_TRUST_PEER_CERT
  9303. TrustedPeerCert* tp;
  9304. int matchType = WC_MATCH_NAME;
  9305. #endif
  9306. ret = ProcessPeerCertParse(ssl, args, CERT_TYPE, NO_VERIFY,
  9307. &subjectHash, &alreadySigner);
  9308. if (ret != 0)
  9309. goto exit_ppc;
  9310. #ifdef OPENSSL_EXTRA
  9311. /* Determine untrusted depth */
  9312. if (!alreadySigner && (!args->dCert ||
  9313. !args->dCertInit || !args->dCert->selfSigned)) {
  9314. args->untrustedDepth = 1;
  9315. }
  9316. #endif
  9317. #ifdef WOLFSSL_TRUST_PEER_CERT
  9318. #ifndef NO_SKID
  9319. if (args->dCert->extAuthKeyIdSet)
  9320. matchType = WC_MATCH_SKID;
  9321. #endif
  9322. tp = GetTrustedPeer(ssl->ctx->cm, subjectHash, matchType);
  9323. WOLFSSL_MSG("Checking for trusted peer cert");
  9324. if (tp && MatchTrustedPeer(tp, args->dCert)) {
  9325. WOLFSSL_MSG("Found matching trusted peer cert");
  9326. args->haveTrustPeer = 1;
  9327. }
  9328. else if (tp == NULL) {
  9329. /* no trusted peer cert */
  9330. WOLFSSL_MSG("No matching trusted peer cert. Checking CAs");
  9331. }
  9332. else {
  9333. WOLFSSL_MSG("Trusted peer cert did not match!");
  9334. }
  9335. if (!args->haveTrustPeer)
  9336. #endif
  9337. {
  9338. /* free cert if not trusted peer */
  9339. FreeDecodedCert(args->dCert);
  9340. args->dCertInit = 0;
  9341. }
  9342. }
  9343. #endif /* WOLFSSL_TRUST_PEER_CERT || OPENSSL_EXTRA */
  9344. /* check certificate up to peer's first */
  9345. /* do not verify chain if trusted peer cert found */
  9346. while (args->count > 1
  9347. #ifdef WOLFSSL_TRUST_PEER_CERT
  9348. && !args->haveTrustPeer
  9349. #endif /* WOLFSSL_TRUST_PEER_CERT */
  9350. ) {
  9351. int skipAddCA = 0;
  9352. /* select last certificate */
  9353. args->certIdx = args->count - 1;
  9354. ret = ProcessPeerCertParse(ssl, args, CERT_TYPE,
  9355. !ssl->options.verifyNone ? VERIFY : NO_VERIFY,
  9356. &subjectHash, &alreadySigner);
  9357. #ifdef WOLFSSL_ASYNC_CRYPT
  9358. if (ret == WC_PENDING_E)
  9359. goto exit_ppc;
  9360. #endif
  9361. if (ret == 0) {
  9362. ret = ProcessPeerCertCheckKey(ssl, args);
  9363. }
  9364. if (ret == 0 && args->dCert->isCA == 0) {
  9365. WOLFSSL_MSG("Chain cert is not a CA, not adding as one");
  9366. }
  9367. else if (ret == 0 && ssl->options.verifyNone) {
  9368. WOLFSSL_MSG("Chain cert not verified by option, "
  9369. "not adding as CA");
  9370. }
  9371. else if (ret == 0) {
  9372. #ifdef OPENSSL_EXTRA
  9373. if (args->certIdx > args->untrustedDepth) {
  9374. args->untrustedDepth = (char)args->certIdx + 1;
  9375. }
  9376. #endif
  9377. if (alreadySigner) {
  9378. WOLFSSL_MSG("Verified CA from chain and already had it");
  9379. }
  9380. }
  9381. else {
  9382. WOLFSSL_MSG("Failed to verify CA from chain");
  9383. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  9384. ssl->peerVerifyRet = X509_V_ERR_INVALID_CA;
  9385. #endif
  9386. }
  9387. #if defined(HAVE_OCSP) || defined(HAVE_CRL)
  9388. if (ret == 0) {
  9389. int doCrlLookup = 1;
  9390. #ifdef HAVE_OCSP
  9391. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  9392. if (ssl->status_request_v2) {
  9393. ret = TLSX_CSR2_InitRequests(ssl->extensions,
  9394. args->dCert, 0, ssl->heap);
  9395. }
  9396. else /* skips OCSP and force CRL check */
  9397. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  9398. if (ssl->ctx->cm->ocspEnabled &&
  9399. ssl->ctx->cm->ocspCheckAll) {
  9400. WOLFSSL_MSG("Doing Non Leaf OCSP check");
  9401. ret = CheckCertOCSP_ex(ssl->ctx->cm->ocsp,
  9402. args->dCert, NULL, ssl);
  9403. #ifdef WOLFSSL_NONBLOCK_OCSP
  9404. if (ret == OCSP_WANT_READ) {
  9405. args->lastErr = ret;
  9406. goto exit_ppc;
  9407. }
  9408. #endif
  9409. doCrlLookup = (ret == OCSP_CERT_UNKNOWN);
  9410. if (ret != 0) {
  9411. doCrlLookup = 0;
  9412. WOLFSSL_MSG("\tOCSP Lookup not ok");
  9413. }
  9414. }
  9415. #endif /* HAVE_OCSP */
  9416. #ifdef HAVE_CRL
  9417. if (ret == 0 && doCrlLookup &&
  9418. ssl->ctx->cm->crlEnabled &&
  9419. ssl->ctx->cm->crlCheckAll) {
  9420. WOLFSSL_MSG("Doing Non Leaf CRL check");
  9421. ret = CheckCertCRL(ssl->ctx->cm->crl, args->dCert);
  9422. #ifdef WOLFSSL_NONBLOCK_OCSP
  9423. if (ret == OCSP_WANT_READ) {
  9424. args->lastErr = ret;
  9425. goto exit_ppc;
  9426. }
  9427. #endif
  9428. if (ret != 0) {
  9429. WOLFSSL_MSG("\tCRL check not ok");
  9430. }
  9431. }
  9432. #endif /* HAVE_CRL */
  9433. (void)doCrlLookup;
  9434. }
  9435. #endif /* HAVE_OCSP || HAVE_CRL */
  9436. /* Do verify callback */
  9437. ret = DoVerifyCallback(ssl->ctx->cm, ssl, ret, args);
  9438. #ifdef WOLFSSL_ALT_CERT_CHAINS
  9439. /* For alternate cert chain, its okay for a CA cert to fail
  9440. with ASN_NO_SIGNER_E here. The "alternate" certificate
  9441. chain mode only requires that the peer certificate
  9442. validate to a trusted CA */
  9443. if (ret != 0 && args->dCert->isCA) {
  9444. if (ret == ASN_NO_SIGNER_E) {
  9445. if (!ssl->options.usingAltCertChain) {
  9446. WOLFSSL_MSG("Trying alternate cert chain");
  9447. ssl->options.usingAltCertChain = 1;
  9448. }
  9449. ret = 0; /* clear error and continue */
  9450. }
  9451. /* do not add to certificate manager */
  9452. skipAddCA = 1;
  9453. }
  9454. #endif /* WOLFSSL_ALT_CERT_CHAINS */
  9455. /* If valid CA then add to Certificate Manager */
  9456. if (ret == 0 && args->dCert->isCA &&
  9457. !ssl->options.verifyNone && !skipAddCA) {
  9458. buffer* cert = &args->certs[args->certIdx];
  9459. /* Is valid CA */
  9460. #if defined(SESSION_CERTS) && defined(WOLFSSL_ALT_CERT_CHAINS)
  9461. /* if using alternate chain, store the cert used */
  9462. if (ssl->options.usingAltCertChain) {
  9463. AddSessionCertToChain(&ssl->session.altChain,
  9464. cert->buffer, cert->length);
  9465. }
  9466. #endif /* SESSION_CERTS && WOLFSSL_ALT_CERT_CHAINS */
  9467. if (!alreadySigner) {
  9468. DerBuffer* add = NULL;
  9469. ret = AllocDer(&add, cert->length, CA_TYPE, ssl->heap);
  9470. if (ret < 0)
  9471. goto exit_ppc;
  9472. XMEMCPY(add->buffer, cert->buffer, cert->length);
  9473. /* CA already verified above in ParseCertRelative */
  9474. WOLFSSL_MSG("Adding CA from chain");
  9475. ret = AddCA(ssl->ctx->cm, &add, WOLFSSL_CHAIN_CA,
  9476. NO_VERIFY);
  9477. if (ret == WOLFSSL_SUCCESS) {
  9478. ret = 0;
  9479. }
  9480. }
  9481. }
  9482. /* Handle error codes */
  9483. if (ret != 0) {
  9484. if (!ssl->options.verifyNone) {
  9485. DoCertFatalAlert(ssl, ret);
  9486. }
  9487. ssl->error = ret; /* Report SSL error */
  9488. if (args->lastErr == 0) {
  9489. args->lastErr = ret; /* save error from last time */
  9490. ret = 0; /* reset error */
  9491. }
  9492. }
  9493. FreeDecodedCert(args->dCert);
  9494. args->dCertInit = 0;
  9495. args->count--;
  9496. } /* while (count > 0 && !args->haveTrustPeer) */
  9497. } /* if (count > 0) */
  9498. /* Check for error */
  9499. if (ret != 0) {
  9500. goto exit_ppc;
  9501. }
  9502. /* Advance state and proceed */
  9503. ssl->options.asyncState = TLS_ASYNC_DO;
  9504. } /* case TLS_ASYNC_BUILD */
  9505. FALL_THROUGH;
  9506. case TLS_ASYNC_DO:
  9507. {
  9508. /* peer's, may not have one if blank client cert sent by TLSv1.2 */
  9509. if (args->count > 0) {
  9510. WOLFSSL_MSG("Verifying Peer's cert");
  9511. /* select peer cert (first one) */
  9512. args->certIdx = 0;
  9513. ret = ProcessPeerCertParse(ssl, args, CERT_TYPE,
  9514. !ssl->options.verifyNone ? VERIFY : NO_VERIFY,
  9515. &subjectHash, &alreadySigner);
  9516. #ifdef WOLFSSL_ASYNC_CRYPT
  9517. if (ret == WC_PENDING_E)
  9518. goto exit_ppc;
  9519. #endif
  9520. if (ret == 0) {
  9521. WOLFSSL_MSG("Verified Peer's cert");
  9522. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  9523. ssl->peerVerifyRet = X509_V_OK;
  9524. #endif
  9525. #if defined(SESSION_CERTS) && defined(WOLFSSL_ALT_CERT_CHAINS)
  9526. /* if using alternate chain, store the cert used */
  9527. if (ssl->options.usingAltCertChain) {
  9528. buffer* cert = &args->certs[args->certIdx];
  9529. AddSessionCertToChain(&ssl->session.altChain,
  9530. cert->buffer, cert->length);
  9531. }
  9532. #endif /* SESSION_CERTS && WOLFSSL_ALT_CERT_CHAINS */
  9533. /* check if fatal error */
  9534. if (args->verifyErr) {
  9535. args->fatal = 1;
  9536. if (ret == 0) {
  9537. ret = args->lastErr;
  9538. }
  9539. }
  9540. else {
  9541. args->fatal = 0;
  9542. }
  9543. }
  9544. else if (ret == ASN_PARSE_E || ret == BUFFER_E) {
  9545. WOLFSSL_MSG("Got Peer cert ASN PARSE or BUFFER ERROR");
  9546. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  9547. SendAlert(ssl, alert_fatal, bad_certificate);
  9548. ssl->peerVerifyRet = X509_V_ERR_CERT_REJECTED;
  9549. #endif
  9550. args->fatal = 1;
  9551. }
  9552. else {
  9553. WOLFSSL_MSG("Failed to verify Peer's cert");
  9554. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  9555. ssl->peerVerifyRet = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
  9556. #endif
  9557. if (ssl->verifyCallback) {
  9558. WOLFSSL_MSG(
  9559. "\tCallback override available, will continue");
  9560. /* check if fatal error */
  9561. args->fatal = (args->verifyErr) ? 1 : 0;
  9562. }
  9563. else {
  9564. WOLFSSL_MSG("\tNo callback override available, fatal");
  9565. args->fatal = 1;
  9566. #ifdef OPENSSL_EXTRA
  9567. SendAlert(ssl, alert_fatal, bad_certificate);
  9568. #endif
  9569. }
  9570. }
  9571. #ifdef HAVE_SECURE_RENEGOTIATION
  9572. if (args->fatal == 0 && !IsAtLeastTLSv1_3(ssl->version)
  9573. && ssl->secure_renegotiation
  9574. && ssl->secure_renegotiation->enabled) {
  9575. if (IsEncryptionOn(ssl, 0)) {
  9576. /* compare against previous time */
  9577. if (ssl->secure_renegotiation->subject_hash_set) {
  9578. if (XMEMCMP(args->dCert->subjectHash,
  9579. ssl->secure_renegotiation->subject_hash,
  9580. KEYID_SIZE) != 0) {
  9581. WOLFSSL_MSG(
  9582. "Peer sent different cert during scr, fatal");
  9583. args->fatal = 1;
  9584. ret = SCR_DIFFERENT_CERT_E;
  9585. }
  9586. }
  9587. }
  9588. /* cache peer's hash */
  9589. if (args->fatal == 0) {
  9590. XMEMCPY(ssl->secure_renegotiation->subject_hash,
  9591. args->dCert->subjectHash, KEYID_SIZE);
  9592. ssl->secure_renegotiation->subject_hash_set = 1;
  9593. }
  9594. }
  9595. #endif /* HAVE_SECURE_RENEGOTIATION */
  9596. } /* if (count > 0) */
  9597. /* Check for error */
  9598. if (args->fatal && ret != 0) {
  9599. goto exit_ppc;
  9600. }
  9601. /* Advance state and proceed */
  9602. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  9603. } /* case TLS_ASYNC_DO */
  9604. FALL_THROUGH;
  9605. case TLS_ASYNC_VERIFY:
  9606. {
  9607. if (args->count > 0) {
  9608. #if defined(HAVE_OCSP) || defined(HAVE_CRL)
  9609. if (args->fatal == 0) {
  9610. int doLookup = 1;
  9611. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  9612. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  9613. if (ssl->status_request) {
  9614. args->fatal = TLSX_CSR_InitRequest(ssl->extensions,
  9615. args->dCert, ssl->heap);
  9616. doLookup = 0;
  9617. #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_SERVER)
  9618. if (ssl->options.tls1_3) {
  9619. TLSX* ext = TLSX_Find(ssl->extensions,
  9620. TLSX_STATUS_REQUEST);
  9621. if (ext != NULL) {
  9622. word32 idx = 0;
  9623. CertificateStatusRequest* csr =
  9624. (CertificateStatusRequest*)ext->data;
  9625. ret = ProcessCSR(ssl, csr->response.buffer,
  9626. &idx, csr->response.length);
  9627. if (ret < 0)
  9628. goto exit_ppc;
  9629. }
  9630. }
  9631. #endif
  9632. }
  9633. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
  9634. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  9635. if (ssl->status_request_v2) {
  9636. args->fatal = TLSX_CSR2_InitRequests(ssl->extensions,
  9637. args->dCert, 1, ssl->heap);
  9638. doLookup = 0;
  9639. }
  9640. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  9641. }
  9642. #ifdef HAVE_OCSP
  9643. if (doLookup && ssl->ctx->cm->ocspEnabled) {
  9644. WOLFSSL_MSG("Doing Leaf OCSP check");
  9645. ret = CheckCertOCSP_ex(ssl->ctx->cm->ocsp,
  9646. args->dCert, NULL, ssl);
  9647. #ifdef WOLFSSL_NONBLOCK_OCSP
  9648. if (ret == OCSP_WANT_READ) {
  9649. goto exit_ppc;
  9650. }
  9651. #endif
  9652. doLookup = (ret == OCSP_CERT_UNKNOWN);
  9653. if (ret != 0) {
  9654. WOLFSSL_MSG("\tOCSP Lookup not ok");
  9655. args->fatal = 0;
  9656. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  9657. ssl->peerVerifyRet = X509_V_ERR_CERT_REJECTED;
  9658. #endif
  9659. }
  9660. }
  9661. #endif /* HAVE_OCSP */
  9662. #ifdef HAVE_CRL
  9663. if (doLookup && ssl->ctx->cm->crlEnabled) {
  9664. WOLFSSL_MSG("Doing Leaf CRL check");
  9665. ret = CheckCertCRL(ssl->ctx->cm->crl, args->dCert);
  9666. #ifdef WOLFSSL_NONBLOCK_OCSP
  9667. if (ret == OCSP_WANT_READ) {
  9668. goto exit_ppc;
  9669. }
  9670. #endif
  9671. if (ret != 0) {
  9672. WOLFSSL_MSG("\tCRL check not ok");
  9673. args->fatal = 0;
  9674. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  9675. ssl->peerVerifyRet = X509_V_ERR_CERT_REJECTED;
  9676. #endif
  9677. }
  9678. }
  9679. #endif /* HAVE_CRL */
  9680. (void)doLookup;
  9681. }
  9682. #endif /* HAVE_OCSP || HAVE_CRL */
  9683. #ifdef KEEP_PEER_CERT
  9684. if (args->fatal == 0) {
  9685. int copyRet = 0;
  9686. #ifdef HAVE_SECURE_RENEGOTIATION
  9687. if (ssl->secure_renegotiation &&
  9688. ssl->secure_renegotiation->enabled) {
  9689. /* free old peer cert */
  9690. FreeX509(&ssl->peerCert);
  9691. }
  9692. #endif
  9693. /* set X509 format for peer cert */
  9694. copyRet = CopyDecodedToX509(&ssl->peerCert, args->dCert);
  9695. if (copyRet == MEMORY_E) {
  9696. args->fatal = 1;
  9697. }
  9698. }
  9699. #endif /* KEEP_PEER_CERT */
  9700. #ifndef IGNORE_KEY_EXTENSIONS
  9701. #if defined(OPENSSL_EXTRA)
  9702. /* when compatibility layer is turned on and no verify is
  9703. * set then ignore the certificate key extension */
  9704. if (args->dCert->extKeyUsageSet &&
  9705. args->dCert->extKeyUsageCrit == 0 &&
  9706. ssl->options.verifyNone) {
  9707. WOLFSSL_MSG("Not verifying certificate key usage");
  9708. }
  9709. else
  9710. #endif
  9711. if (args->dCert->extKeyUsageSet) {
  9712. if ((ssl->specs.kea == rsa_kea) &&
  9713. (ssl->options.side == WOLFSSL_CLIENT_END) &&
  9714. (args->dCert->extKeyUsage & KEYUSE_KEY_ENCIPHER) == 0) {
  9715. ret = KEYUSE_ENCIPHER_E;
  9716. }
  9717. if ((ssl->specs.sig_algo == rsa_sa_algo ||
  9718. (ssl->specs.sig_algo == ecc_dsa_sa_algo &&
  9719. !ssl->specs.static_ecdh)) &&
  9720. (args->dCert->extKeyUsage & KEYUSE_DIGITAL_SIG) == 0) {
  9721. WOLFSSL_MSG("KeyUse Digital Sig not set");
  9722. ret = KEYUSE_SIGNATURE_E;
  9723. }
  9724. }
  9725. #if defined(OPENSSL_EXTRA)
  9726. /* when compatibility layer is turned on and no verify is
  9727. * set then ignore the certificate key extension */
  9728. if (args->dCert->extExtKeyUsageSet &&
  9729. args->dCert->extExtKeyUsageCrit == 0 &&
  9730. ssl->options.verifyNone) {
  9731. WOLFSSL_MSG("Not verifying certificate ext key usage");
  9732. }
  9733. else
  9734. #endif
  9735. if (args->dCert->extExtKeyUsageSet) {
  9736. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  9737. if ((args->dCert->extExtKeyUsage &
  9738. (EXTKEYUSE_ANY | EXTKEYUSE_SERVER_AUTH)) == 0) {
  9739. WOLFSSL_MSG("ExtKeyUse Server Auth not set");
  9740. ret = EXTKEYUSE_AUTH_E;
  9741. }
  9742. }
  9743. else {
  9744. if ((args->dCert->extExtKeyUsage &
  9745. (EXTKEYUSE_ANY | EXTKEYUSE_CLIENT_AUTH)) == 0) {
  9746. WOLFSSL_MSG("ExtKeyUse Client Auth not set");
  9747. ret = EXTKEYUSE_AUTH_E;
  9748. }
  9749. }
  9750. }
  9751. #endif /* IGNORE_KEY_EXTENSIONS */
  9752. if (args->fatal) {
  9753. ssl->error = ret;
  9754. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  9755. SendAlert(ssl, alert_fatal, bad_certificate);
  9756. ssl->peerVerifyRet = X509_V_ERR_CERT_REJECTED;
  9757. #endif
  9758. goto exit_ppc;
  9759. }
  9760. ssl->options.havePeerCert = 1;
  9761. if (!ssl->options.verifyNone && ssl->buffers.domainName.buffer) {
  9762. #ifndef WOLFSSL_ALLOW_NO_CN_IN_SAN
  9763. /* Per RFC 5280 section 4.2.1.6, "Whenever such identities
  9764. * are to be bound into a certificate, the subject
  9765. * alternative name extension MUST be used." */
  9766. if (args->dCert->altNames) {
  9767. if (CheckAltNames(args->dCert,
  9768. (char*)ssl->buffers.domainName.buffer) == 0 ) {
  9769. WOLFSSL_MSG("DomainName match on alt names failed");
  9770. /* try to get peer key still */
  9771. ret = DOMAIN_NAME_MISMATCH;
  9772. }
  9773. }
  9774. else {
  9775. if (MatchDomainName(
  9776. args->dCert->subjectCN,
  9777. args->dCert->subjectCNLen,
  9778. (char*)ssl->buffers.domainName.buffer) == 0) {
  9779. WOLFSSL_MSG("DomainName match on common name failed");
  9780. ret = DOMAIN_NAME_MISMATCH;
  9781. }
  9782. }
  9783. #else /* WOLFSSL_ALL_NO_CN_IN_SAN */
  9784. /* Old behavior. */
  9785. if (MatchDomainName(args->dCert->subjectCN,
  9786. args->dCert->subjectCNLen,
  9787. (char*)ssl->buffers.domainName.buffer) == 0) {
  9788. WOLFSSL_MSG("DomainName match on common name failed");
  9789. if (CheckAltNames(args->dCert,
  9790. (char*)ssl->buffers.domainName.buffer) == 0 ) {
  9791. WOLFSSL_MSG(
  9792. "DomainName match on alt names failed too");
  9793. /* try to get peer key still */
  9794. ret = DOMAIN_NAME_MISMATCH;
  9795. }
  9796. }
  9797. #endif /* WOLFSSL_ALL_NO_CN_IN_SAN */
  9798. }
  9799. /* decode peer key */
  9800. switch (args->dCert->keyOID) {
  9801. #ifndef NO_RSA
  9802. case RSAk:
  9803. {
  9804. word32 keyIdx = 0;
  9805. int keyRet = 0;
  9806. if (ssl->peerRsaKey == NULL) {
  9807. keyRet = AllocKey(ssl, DYNAMIC_TYPE_RSA,
  9808. (void**)&ssl->peerRsaKey);
  9809. } else if (ssl->peerRsaKeyPresent) {
  9810. keyRet = ReuseKey(ssl, DYNAMIC_TYPE_RSA,
  9811. ssl->peerRsaKey);
  9812. ssl->peerRsaKeyPresent = 0;
  9813. }
  9814. if (keyRet != 0 || wc_RsaPublicKeyDecode(
  9815. args->dCert->publicKey, &keyIdx, ssl->peerRsaKey,
  9816. args->dCert->pubKeySize) != 0) {
  9817. ret = PEER_KEY_ERROR;
  9818. }
  9819. else {
  9820. ssl->peerRsaKeyPresent = 1;
  9821. #ifdef WOLFSSL_RENESAS_TSIP_TLS
  9822. /* copy encrypted tsip key index into ssl object */
  9823. if (args->dCert->tsip_encRsaKeyIdx) {
  9824. if (!ssl->peerTsipEncRsaKeyIndex) {
  9825. ssl->peerTsipEncRsaKeyIndex = (byte*)XMALLOC(
  9826. TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  9827. ssl->heap, DYNAMIC_TYPE_RSA);
  9828. if (!ssl->peerTsipEncRsaKeyIndex) {
  9829. args->lastErr = MEMORY_E;
  9830. goto exit_ppc;
  9831. }
  9832. }
  9833. XMEMCPY(ssl->peerTsipEncRsaKeyIndex,
  9834. args->dCert->tsip_encRsaKeyIdx,
  9835. TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY);
  9836. }
  9837. #endif
  9838. #ifdef HAVE_PK_CALLBACKS
  9839. #ifndef NO_RSA
  9840. #ifdef HAVE_SECURE_RENEGOTIATION
  9841. if (ssl->buffers.peerRsaKey.buffer) {
  9842. XFREE(ssl->buffers.peerRsaKey.buffer,
  9843. ssl->heap, DYNAMIC_TYPE_RSA);
  9844. ssl->buffers.peerRsaKey.buffer = NULL;
  9845. }
  9846. #endif
  9847. ssl->buffers.peerRsaKey.buffer =
  9848. (byte*)XMALLOC(args->dCert->pubKeySize,
  9849. ssl->heap, DYNAMIC_TYPE_RSA);
  9850. if (ssl->buffers.peerRsaKey.buffer == NULL) {
  9851. ret = MEMORY_ERROR;
  9852. }
  9853. else {
  9854. XMEMCPY(ssl->buffers.peerRsaKey.buffer,
  9855. args->dCert->publicKey,
  9856. args->dCert->pubKeySize);
  9857. ssl->buffers.peerRsaKey.length =
  9858. args->dCert->pubKeySize;
  9859. }
  9860. #endif /* NO_RSA */
  9861. #endif /* HAVE_PK_CALLBACKS */
  9862. }
  9863. /* check size of peer RSA key */
  9864. if (ret == 0 && ssl->peerRsaKeyPresent &&
  9865. !ssl->options.verifyNone &&
  9866. wc_RsaEncryptSize(ssl->peerRsaKey)
  9867. < ssl->options.minRsaKeySz) {
  9868. ret = RSA_KEY_SIZE_E;
  9869. WOLFSSL_MSG("Peer RSA key is too small");
  9870. }
  9871. break;
  9872. }
  9873. #endif /* NO_RSA */
  9874. #ifdef HAVE_NTRU
  9875. case NTRUk:
  9876. {
  9877. if (args->dCert->pubKeySize > sizeof(ssl->peerNtruKey)) {
  9878. ret = PEER_KEY_ERROR;
  9879. }
  9880. else {
  9881. XMEMCPY(ssl->peerNtruKey, args->dCert->publicKey,
  9882. args->dCert->pubKeySize);
  9883. ssl->peerNtruKeyLen =
  9884. (word16)args->dCert->pubKeySize;
  9885. ssl->peerNtruKeyPresent = 1;
  9886. }
  9887. break;
  9888. }
  9889. #endif /* HAVE_NTRU */
  9890. #ifdef HAVE_ECC
  9891. case ECDSAk:
  9892. {
  9893. int keyRet = 0;
  9894. word32 idx = 0;
  9895. if (ssl->peerEccDsaKey == NULL) {
  9896. /* alloc/init on demand */
  9897. keyRet = AllocKey(ssl, DYNAMIC_TYPE_ECC,
  9898. (void**)&ssl->peerEccDsaKey);
  9899. } else if (ssl->peerEccDsaKeyPresent) {
  9900. keyRet = ReuseKey(ssl, DYNAMIC_TYPE_ECC,
  9901. ssl->peerEccDsaKey);
  9902. ssl->peerEccDsaKeyPresent = 0;
  9903. }
  9904. if (keyRet != 0 ||
  9905. wc_EccPublicKeyDecode(args->dCert->publicKey, &idx,
  9906. ssl->peerEccDsaKey,
  9907. args->dCert->pubKeySize) != 0) {
  9908. ret = PEER_KEY_ERROR;
  9909. }
  9910. else {
  9911. ssl->peerEccDsaKeyPresent = 1;
  9912. #ifdef HAVE_PK_CALLBACKS
  9913. ssl->buffers.peerEccDsaKey.buffer =
  9914. (byte*)XMALLOC(args->dCert->pubKeySize,
  9915. ssl->heap, DYNAMIC_TYPE_ECC);
  9916. if (ssl->buffers.peerEccDsaKey.buffer == NULL) {
  9917. ERROR_OUT(MEMORY_ERROR, exit_ppc);
  9918. }
  9919. else {
  9920. XMEMCPY(ssl->buffers.peerEccDsaKey.buffer,
  9921. args->dCert->publicKey,
  9922. args->dCert->pubKeySize);
  9923. ssl->buffers.peerEccDsaKey.length =
  9924. args->dCert->pubKeySize;
  9925. }
  9926. #endif /* HAVE_PK_CALLBACKS */
  9927. }
  9928. /* check size of peer ECC key */
  9929. if (ret == 0 && ssl->peerEccDsaKeyPresent &&
  9930. !ssl->options.verifyNone &&
  9931. wc_ecc_size(ssl->peerEccDsaKey)
  9932. < ssl->options.minEccKeySz) {
  9933. ret = ECC_KEY_SIZE_E;
  9934. WOLFSSL_MSG("Peer ECC key is too small");
  9935. }
  9936. break;
  9937. }
  9938. #endif /* HAVE_ECC */
  9939. #ifdef HAVE_ED25519
  9940. case ED25519k:
  9941. {
  9942. int keyRet = 0;
  9943. if (ssl->peerEd25519Key == NULL) {
  9944. /* alloc/init on demand */
  9945. keyRet = AllocKey(ssl, DYNAMIC_TYPE_ED25519,
  9946. (void**)&ssl->peerEd25519Key);
  9947. } else if (ssl->peerEd25519KeyPresent) {
  9948. keyRet = ReuseKey(ssl, DYNAMIC_TYPE_ED25519,
  9949. ssl->peerEd25519Key);
  9950. ssl->peerEd25519KeyPresent = 0;
  9951. }
  9952. if (keyRet != 0 ||
  9953. wc_ed25519_import_public(args->dCert->publicKey,
  9954. args->dCert->pubKeySize,
  9955. ssl->peerEd25519Key)
  9956. != 0) {
  9957. ret = PEER_KEY_ERROR;
  9958. }
  9959. else {
  9960. ssl->peerEd25519KeyPresent = 1;
  9961. #ifdef HAVE_PK_CALLBACKS
  9962. ssl->buffers.peerEd25519Key.buffer =
  9963. (byte*)XMALLOC(args->dCert->pubKeySize,
  9964. ssl->heap, DYNAMIC_TYPE_ED25519);
  9965. if (ssl->buffers.peerEd25519Key.buffer == NULL) {
  9966. ERROR_OUT(MEMORY_ERROR, exit_ppc);
  9967. }
  9968. else {
  9969. XMEMCPY(ssl->buffers.peerEd25519Key.buffer,
  9970. args->dCert->publicKey,
  9971. args->dCert->pubKeySize);
  9972. ssl->buffers.peerEd25519Key.length =
  9973. args->dCert->pubKeySize;
  9974. }
  9975. #endif /*HAVE_PK_CALLBACKS */
  9976. }
  9977. /* check size of peer ECC key */
  9978. if (ret == 0 && ssl->peerEd25519KeyPresent &&
  9979. !ssl->options.verifyNone &&
  9980. ED25519_KEY_SIZE < ssl->options.minEccKeySz) {
  9981. ret = ECC_KEY_SIZE_E;
  9982. WOLFSSL_MSG("Peer ECC key is too small");
  9983. }
  9984. break;
  9985. }
  9986. #endif /* HAVE_ED25519 */
  9987. #ifdef HAVE_ED448
  9988. case ED448k:
  9989. {
  9990. int keyRet = 0;
  9991. if (ssl->peerEd448Key == NULL) {
  9992. /* alloc/init on demand */
  9993. keyRet = AllocKey(ssl, DYNAMIC_TYPE_ED448,
  9994. (void**)&ssl->peerEd448Key);
  9995. } else if (ssl->peerEd448KeyPresent) {
  9996. keyRet = ReuseKey(ssl, DYNAMIC_TYPE_ED448,
  9997. ssl->peerEd448Key);
  9998. ssl->peerEd448KeyPresent = 0;
  9999. }
  10000. if (keyRet != 0 ||
  10001. wc_ed448_import_public(args->dCert->publicKey,
  10002. args->dCert->pubKeySize,
  10003. ssl->peerEd448Key) != 0) {
  10004. ret = PEER_KEY_ERROR;
  10005. }
  10006. else {
  10007. ssl->peerEd448KeyPresent = 1;
  10008. #ifdef HAVE_PK_CALLBACKS
  10009. ssl->buffers.peerEd448Key.buffer =
  10010. (byte*)XMALLOC(args->dCert->pubKeySize,
  10011. ssl->heap, DYNAMIC_TYPE_ED448);
  10012. if (ssl->buffers.peerEd448Key.buffer == NULL) {
  10013. ERROR_OUT(MEMORY_ERROR, exit_ppc);
  10014. }
  10015. else {
  10016. XMEMCPY(ssl->buffers.peerEd448Key.buffer,
  10017. args->dCert->publicKey,
  10018. args->dCert->pubKeySize);
  10019. ssl->buffers.peerEd448Key.length =
  10020. args->dCert->pubKeySize;
  10021. }
  10022. #endif /*HAVE_PK_CALLBACKS */
  10023. }
  10024. /* check size of peer ECC key */
  10025. if (ret == 0 && ssl->peerEd448KeyPresent &&
  10026. !ssl->options.verifyNone &&
  10027. ED448_KEY_SIZE < ssl->options.minEccKeySz) {
  10028. ret = ECC_KEY_SIZE_E;
  10029. WOLFSSL_MSG("Peer ECC key is too small");
  10030. }
  10031. break;
  10032. }
  10033. #endif /* HAVE_ED448 */
  10034. default:
  10035. break;
  10036. }
  10037. /* args->dCert free'd in function cleanup after callback */
  10038. } /* if (count > 0) */
  10039. /* Check for error */
  10040. if (args->fatal && ret != 0) {
  10041. goto exit_ppc;
  10042. }
  10043. /* Advance state and proceed */
  10044. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  10045. } /* case TLS_ASYNC_VERIFY */
  10046. FALL_THROUGH;
  10047. case TLS_ASYNC_FINALIZE:
  10048. {
  10049. /* load last error */
  10050. if (args->lastErr != 0 && ret == 0) {
  10051. ret = args->lastErr;
  10052. }
  10053. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  10054. if (args->untrustedDepth > ssl->options.verifyDepth) {
  10055. ssl->peerVerifyRet = X509_V_ERR_CERT_CHAIN_TOO_LONG;
  10056. ret = MAX_CHAIN_ERROR;
  10057. }
  10058. #endif
  10059. /* Do verify callback */
  10060. ret = DoVerifyCallback(ssl->ctx->cm, ssl, ret, args);
  10061. if (ssl->options.verifyNone &&
  10062. (ret == CRL_MISSING || ret == CRL_CERT_REVOKED)) {
  10063. WOLFSSL_MSG("Ignoring CRL problem based on verify setting");
  10064. ret = ssl->error = 0;
  10065. }
  10066. if (ret != 0) {
  10067. if (!ssl->options.verifyNone) {
  10068. DoCertFatalAlert(ssl, ret);
  10069. }
  10070. ssl->error = ret; /* Report SSL error */
  10071. }
  10072. if (ret == 0 && ssl->options.side == WOLFSSL_CLIENT_END) {
  10073. ssl->options.serverState = SERVER_CERT_COMPLETE;
  10074. }
  10075. if (IsEncryptionOn(ssl, 0)) {
  10076. args->idx += ssl->keys.padSz;
  10077. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10078. if (ssl->options.startedETMRead)
  10079. args->idx += MacSize(ssl);
  10080. #endif
  10081. }
  10082. /* Advance state and proceed */
  10083. ssl->options.asyncState = TLS_ASYNC_END;
  10084. } /* case TLS_ASYNC_FINALIZE */
  10085. FALL_THROUGH;
  10086. case TLS_ASYNC_END:
  10087. {
  10088. /* Set final index */
  10089. *inOutIdx = args->idx;
  10090. break;
  10091. }
  10092. default:
  10093. ret = INPUT_CASE_ERROR;
  10094. break;
  10095. } /* switch(ssl->options.asyncState) */
  10096. exit_ppc:
  10097. WOLFSSL_LEAVE("ProcessPeerCerts", ret);
  10098. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  10099. if (ret == WC_PENDING_E || ret == OCSP_WANT_READ) {
  10100. /* Mark message as not received so it can process again */
  10101. ssl->msgsReceived.got_certificate = 0;
  10102. return ret;
  10103. }
  10104. #endif /* WOLFSSL_ASYNC_CRYPT || WOLFSSL_NONBLOCK_OCSP */
  10105. FreeProcPeerCertArgs(ssl, args);
  10106. #if defined(WOLFSSL_ASYNC_CRYPT)
  10107. #elif defined(WOLFSSL_NONBLOCK_OCSP)
  10108. XFREE(args, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10109. ssl->nonblockarg = NULL;
  10110. #elif defined(WOLFSSL_SMALL_STACK)
  10111. XFREE(args, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10112. #endif
  10113. FreeKeyExchange(ssl);
  10114. return ret;
  10115. }
  10116. #endif
  10117. #ifndef WOLFSSL_NO_TLS12
  10118. #if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  10119. /* handle processing of certificate (11) */
  10120. static int DoCertificate(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  10121. word32 size)
  10122. {
  10123. int ret;
  10124. WOLFSSL_START(WC_FUNC_CERTIFICATE_DO);
  10125. WOLFSSL_ENTER("DoCertificate");
  10126. #ifdef SESSION_CERTS
  10127. /* Reset the session cert chain count in case the session resume failed. */
  10128. ssl->session.chain.count = 0;
  10129. #ifdef WOLFSSL_ALT_CERT_CHAINS
  10130. ssl->session.altChain.count = 0;
  10131. #endif
  10132. #endif /* SESSION_CERTS */
  10133. ret = ProcessPeerCerts(ssl, input, inOutIdx, size);
  10134. #ifdef WOLFSSL_EXTRA_ALERTS
  10135. if (ret == BUFFER_ERROR || ret == ASN_PARSE_E)
  10136. SendAlert(ssl, alert_fatal, decode_error);
  10137. #endif
  10138. #ifdef OPENSSL_EXTRA
  10139. ssl->options.serverState = SERVER_CERT_COMPLETE;
  10140. #endif
  10141. WOLFSSL_LEAVE("DoCertificate", ret);
  10142. WOLFSSL_END(WC_FUNC_CERTIFICATE_DO);
  10143. return ret;
  10144. }
  10145. /* handle processing of certificate_status (22) */
  10146. static int DoCertificateStatus(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  10147. word32 size)
  10148. {
  10149. int ret = 0;
  10150. byte status_type;
  10151. word32 status_length;
  10152. WOLFSSL_START(WC_FUNC_CERTIFICATE_STATUS_DO);
  10153. WOLFSSL_ENTER("DoCertificateStatus");
  10154. if (size < ENUM_LEN + OPAQUE24_LEN)
  10155. return BUFFER_ERROR;
  10156. status_type = input[(*inOutIdx)++];
  10157. c24to32(input + *inOutIdx, &status_length);
  10158. *inOutIdx += OPAQUE24_LEN;
  10159. if (size != ENUM_LEN + OPAQUE24_LEN + status_length)
  10160. return BUFFER_ERROR;
  10161. switch (status_type) {
  10162. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  10163. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  10164. /* WOLFSSL_CSR_OCSP overlaps with WOLFSSL_CSR2_OCSP */
  10165. case WOLFSSL_CSR2_OCSP:
  10166. ret = ProcessCSR(ssl, input, inOutIdx, status_length);
  10167. break;
  10168. #endif
  10169. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  10170. case WOLFSSL_CSR2_OCSP_MULTI: {
  10171. OcspRequest* request;
  10172. word32 list_length = status_length;
  10173. byte idx = 0;
  10174. #ifdef WOLFSSL_SMALL_STACK
  10175. CertStatus* status;
  10176. OcspResponse* response;
  10177. #else
  10178. CertStatus status[1];
  10179. OcspResponse response[1];
  10180. #endif
  10181. do {
  10182. if (ssl->status_request_v2) {
  10183. ssl->status_request_v2 = 0;
  10184. break;
  10185. }
  10186. return BUFFER_ERROR;
  10187. } while(0);
  10188. #ifdef WOLFSSL_SMALL_STACK
  10189. status = (CertStatus*)XMALLOC(sizeof(CertStatus), ssl->heap,
  10190. DYNAMIC_TYPE_OCSP_STATUS);
  10191. response = (OcspResponse*)XMALLOC(sizeof(OcspResponse), ssl->heap,
  10192. DYNAMIC_TYPE_OCSP_REQUEST);
  10193. if (status == NULL || response == NULL) {
  10194. if (status)
  10195. XFREE(status, ssl->heap, DYNAMIC_TYPE_OCSP_STATUS);
  10196. if (response)
  10197. XFREE(response, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  10198. return MEMORY_ERROR;
  10199. }
  10200. #endif
  10201. while (list_length && ret == 0) {
  10202. if (OPAQUE24_LEN > list_length) {
  10203. ret = BUFFER_ERROR;
  10204. break;
  10205. }
  10206. c24to32(input + *inOutIdx, &status_length);
  10207. *inOutIdx += OPAQUE24_LEN;
  10208. list_length -= OPAQUE24_LEN;
  10209. if (status_length > list_length) {
  10210. ret = BUFFER_ERROR;
  10211. break;
  10212. }
  10213. if (status_length) {
  10214. InitOcspResponse(response, status, input +*inOutIdx,
  10215. status_length);
  10216. if ((OcspResponseDecode(response, ssl->ctx->cm, ssl->heap,
  10217. 0) != 0)
  10218. || (response->responseStatus != OCSP_SUCCESSFUL)
  10219. || (response->status->status != CERT_GOOD))
  10220. ret = BAD_CERTIFICATE_STATUS_ERROR;
  10221. while (ret == 0) {
  10222. request = (OcspRequest*)TLSX_CSR2_GetRequest(
  10223. ssl->extensions, status_type, idx++);
  10224. if (request == NULL)
  10225. ret = BAD_CERTIFICATE_STATUS_ERROR;
  10226. else if (CompareOcspReqResp(request, response) == 0)
  10227. break;
  10228. else if (idx == 1) /* server cert must be OK */
  10229. ret = BAD_CERTIFICATE_STATUS_ERROR;
  10230. }
  10231. *inOutIdx += status_length;
  10232. list_length -= status_length;
  10233. }
  10234. }
  10235. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  10236. ssl->status_request_v2 = 0;
  10237. #endif
  10238. #ifdef WOLFSSL_SMALL_STACK
  10239. XFREE(status, NULL, DYNAMIC_TYPE_OCSP_STATUS);
  10240. XFREE(response, NULL, DYNAMIC_TYPE_OCSP_REQUEST);
  10241. #endif
  10242. }
  10243. break;
  10244. #endif
  10245. default:
  10246. ret = BUFFER_ERROR;
  10247. }
  10248. if (ret != 0)
  10249. SendAlert(ssl, alert_fatal, bad_certificate_status_response);
  10250. if (IsEncryptionOn(ssl, 0)) {
  10251. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10252. if (ssl->options.startedETMRead) {
  10253. word32 digestSz = MacSize(ssl);
  10254. if (*inOutIdx + ssl->keys.padSz + digestSz > size)
  10255. return BUFFER_E;
  10256. *inOutIdx += ssl->keys.padSz + digestSz;
  10257. }
  10258. else
  10259. #endif
  10260. {
  10261. if (*inOutIdx + ssl->keys.padSz > size)
  10262. return BUFFER_E;
  10263. *inOutIdx += ssl->keys.padSz;
  10264. }
  10265. }
  10266. WOLFSSL_LEAVE("DoCertificateStatus", ret);
  10267. WOLFSSL_END(WC_FUNC_CERTIFICATE_STATUS_DO);
  10268. return ret;
  10269. }
  10270. #endif
  10271. #endif /* !WOLFSSL_NO_TLS12 */
  10272. #endif /* !NO_CERTS */
  10273. #ifndef WOLFSSL_NO_TLS12
  10274. static int DoHelloRequest(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  10275. word32 size, word32 totalSz)
  10276. {
  10277. (void)input;
  10278. WOLFSSL_START(WC_FUNC_HELLO_REQUEST_DO);
  10279. WOLFSSL_ENTER("DoHelloRequest");
  10280. if (size) /* must be 0 */
  10281. return BUFFER_ERROR;
  10282. if (IsEncryptionOn(ssl, 0)) {
  10283. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10284. if (ssl->options.startedETMRead) {
  10285. word32 digestSz = MacSize(ssl);
  10286. if (*inOutIdx + ssl->keys.padSz + digestSz > totalSz)
  10287. return BUFFER_E;
  10288. *inOutIdx += ssl->keys.padSz + digestSz;
  10289. }
  10290. else
  10291. #endif
  10292. {
  10293. /* access beyond input + size should be checked against totalSz */
  10294. if (*inOutIdx + ssl->keys.padSz > totalSz)
  10295. return BUFFER_E;
  10296. *inOutIdx += ssl->keys.padSz;
  10297. }
  10298. }
  10299. if (ssl->options.side == WOLFSSL_SERVER_END) {
  10300. SendAlert(ssl, alert_fatal, unexpected_message); /* try */
  10301. return FATAL_ERROR;
  10302. }
  10303. #ifdef HAVE_SECURE_RENEGOTIATION
  10304. else if (ssl->secure_renegotiation && ssl->secure_renegotiation->enabled) {
  10305. ssl->secure_renegotiation->startScr = 1;
  10306. WOLFSSL_LEAVE("DoHelloRequest", 0);
  10307. WOLFSSL_END(WC_FUNC_HELLO_REQUEST_DO);
  10308. return 0;
  10309. }
  10310. #endif
  10311. else {
  10312. return SendAlert(ssl, alert_warning, no_renegotiation);
  10313. }
  10314. }
  10315. int DoFinished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, word32 size,
  10316. word32 totalSz, int sniff)
  10317. {
  10318. word32 finishedSz = (ssl->options.tls ? TLS_FINISHED_SZ : FINISHED_SZ);
  10319. WOLFSSL_START(WC_FUNC_FINISHED_DO);
  10320. WOLFSSL_ENTER("DoFinished");
  10321. if (finishedSz != size)
  10322. return BUFFER_ERROR;
  10323. /* check against totalSz */
  10324. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10325. if (ssl->options.startedETMRead) {
  10326. if (*inOutIdx + size + ssl->keys.padSz + MacSize(ssl) > totalSz)
  10327. return BUFFER_E;
  10328. }
  10329. else
  10330. #endif
  10331. {
  10332. if (*inOutIdx + size + ssl->keys.padSz > totalSz)
  10333. return BUFFER_E;
  10334. }
  10335. #ifdef WOLFSSL_CALLBACKS
  10336. if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
  10337. if (ssl->toInfoOn) AddLateName("Finished", &ssl->timeoutInfo);
  10338. #endif
  10339. if (sniff == NO_SNIFF) {
  10340. if (XMEMCMP(input + *inOutIdx, &ssl->hsHashes->verifyHashes,size) != 0){
  10341. WOLFSSL_MSG("Verify finished error on hashes");
  10342. #ifdef WOLFSSL_EXTRA_ALERTS
  10343. SendAlert(ssl, alert_fatal, decrypt_error);
  10344. #endif
  10345. return VERIFY_FINISHED_ERROR;
  10346. }
  10347. }
  10348. #ifdef HAVE_SECURE_RENEGOTIATION
  10349. if (ssl->secure_renegotiation) {
  10350. /* save peer's state */
  10351. if (ssl->options.side == WOLFSSL_CLIENT_END)
  10352. XMEMCPY(ssl->secure_renegotiation->server_verify_data,
  10353. input + *inOutIdx, TLS_FINISHED_SZ);
  10354. else
  10355. XMEMCPY(ssl->secure_renegotiation->client_verify_data,
  10356. input + *inOutIdx, TLS_FINISHED_SZ);
  10357. ssl->secure_renegotiation->verifySet = 1;
  10358. }
  10359. #endif
  10360. /* force input exhaustion at ProcessReply consuming padSz */
  10361. *inOutIdx += size + ssl->keys.padSz;
  10362. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10363. if (ssl->options.startedETMRead)
  10364. *inOutIdx += MacSize(ssl);
  10365. #endif
  10366. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  10367. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  10368. #ifdef OPENSSL_EXTRA
  10369. ssl->cbmode = SSL_CB_MODE_WRITE;
  10370. ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
  10371. #endif
  10372. if (!ssl->options.resuming) {
  10373. #ifdef OPENSSL_EXTRA
  10374. if (ssl->CBIS != NULL) {
  10375. ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, SSL_SUCCESS);
  10376. }
  10377. #endif
  10378. ssl->options.handShakeState = HANDSHAKE_DONE;
  10379. ssl->options.handShakeDone = 1;
  10380. }
  10381. }
  10382. else {
  10383. ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
  10384. #ifdef OPENSSL_EXTRA
  10385. ssl->cbmode = SSL_CB_MODE_READ;
  10386. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  10387. #endif
  10388. if (ssl->options.resuming) {
  10389. #ifdef OPENSSL_EXTRA
  10390. if (ssl->CBIS != NULL) {
  10391. ssl->CBIS(ssl, SSL_CB_ACCEPT_LOOP, SSL_SUCCESS);
  10392. }
  10393. #endif
  10394. ssl->options.handShakeState = HANDSHAKE_DONE;
  10395. ssl->options.handShakeDone = 1;
  10396. }
  10397. }
  10398. #ifdef WOLFSSL_DTLS
  10399. if (ssl->options.dtls) {
  10400. DtlsMsgPoolReset(ssl);
  10401. }
  10402. #endif
  10403. WOLFSSL_LEAVE("DoFinished", 0);
  10404. WOLFSSL_END(WC_FUNC_FINISHED_DO);
  10405. return 0;
  10406. }
  10407. /* Make sure no duplicates, no fast forward, or other problems; 0 on success */
  10408. static int SanityCheckMsgReceived(WOLFSSL* ssl, byte type)
  10409. {
  10410. /* verify not a duplicate, mark received, check state */
  10411. switch (type) {
  10412. #ifndef NO_WOLFSSL_CLIENT
  10413. case hello_request:
  10414. if (ssl->msgsReceived.got_hello_request) {
  10415. WOLFSSL_MSG("Duplicate HelloRequest received");
  10416. return DUPLICATE_MSG_E;
  10417. }
  10418. ssl->msgsReceived.got_hello_request = 1;
  10419. break;
  10420. #endif
  10421. #ifndef NO_WOLFSSL_SERVER
  10422. case client_hello:
  10423. if (ssl->msgsReceived.got_client_hello) {
  10424. WOLFSSL_MSG("Duplicate ClientHello received");
  10425. #ifdef WOLFSSL_EXTRA_ALERTS
  10426. SendAlert(ssl, alert_fatal, unexpected_message);
  10427. #endif
  10428. return DUPLICATE_MSG_E;
  10429. }
  10430. ssl->msgsReceived.got_client_hello = 1;
  10431. break;
  10432. #endif
  10433. #ifndef NO_WOLFSSL_CLIENT
  10434. case server_hello:
  10435. if (ssl->msgsReceived.got_server_hello) {
  10436. WOLFSSL_MSG("Duplicate ServerHello received");
  10437. return DUPLICATE_MSG_E;
  10438. }
  10439. ssl->msgsReceived.got_server_hello = 1;
  10440. break;
  10441. #endif
  10442. #ifndef NO_WOLFSSL_CLIENT
  10443. case hello_verify_request:
  10444. if (ssl->msgsReceived.got_hello_verify_request) {
  10445. WOLFSSL_MSG("Duplicate HelloVerifyRequest received");
  10446. return DUPLICATE_MSG_E;
  10447. }
  10448. ssl->msgsReceived.got_hello_verify_request = 1;
  10449. break;
  10450. #endif
  10451. #ifndef NO_WOLFSSL_CLIENT
  10452. case session_ticket:
  10453. if (ssl->msgsReceived.got_session_ticket) {
  10454. WOLFSSL_MSG("Duplicate SessionTicket received");
  10455. return DUPLICATE_MSG_E;
  10456. }
  10457. ssl->msgsReceived.got_session_ticket = 1;
  10458. break;
  10459. #endif
  10460. case certificate:
  10461. if (ssl->msgsReceived.got_certificate) {
  10462. WOLFSSL_MSG("Duplicate Certificate received");
  10463. return DUPLICATE_MSG_E;
  10464. }
  10465. ssl->msgsReceived.got_certificate = 1;
  10466. #ifndef NO_WOLFSSL_CLIENT
  10467. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  10468. if ( ssl->msgsReceived.got_server_hello == 0) {
  10469. WOLFSSL_MSG("No ServerHello before Cert");
  10470. return OUT_OF_ORDER_E;
  10471. }
  10472. }
  10473. #endif
  10474. #ifndef NO_WOLFSSL_SERVER
  10475. if (ssl->options.side == WOLFSSL_SERVER_END) {
  10476. if ( ssl->msgsReceived.got_client_hello == 0) {
  10477. WOLFSSL_MSG("No ClientHello before Cert");
  10478. return OUT_OF_ORDER_E;
  10479. }
  10480. }
  10481. #endif
  10482. break;
  10483. #ifndef NO_WOLFSSL_CLIENT
  10484. case certificate_status:
  10485. if (ssl->msgsReceived.got_certificate_status) {
  10486. WOLFSSL_MSG("Duplicate CertificateSatatus received");
  10487. return DUPLICATE_MSG_E;
  10488. }
  10489. ssl->msgsReceived.got_certificate_status = 1;
  10490. if (ssl->msgsReceived.got_certificate == 0) {
  10491. WOLFSSL_MSG("No Certificate before CertificateStatus");
  10492. return OUT_OF_ORDER_E;
  10493. }
  10494. if (ssl->msgsReceived.got_server_key_exchange != 0) {
  10495. WOLFSSL_MSG("CertificateStatus after ServerKeyExchange");
  10496. return OUT_OF_ORDER_E;
  10497. }
  10498. break;
  10499. #endif
  10500. #ifndef NO_WOLFSSL_CLIENT
  10501. case server_key_exchange:
  10502. if (ssl->msgsReceived.got_server_key_exchange) {
  10503. WOLFSSL_MSG("Duplicate ServerKeyExchange received");
  10504. return DUPLICATE_MSG_E;
  10505. }
  10506. ssl->msgsReceived.got_server_key_exchange = 1;
  10507. if (ssl->msgsReceived.got_server_hello == 0) {
  10508. WOLFSSL_MSG("No ServerHello before ServerKeyExchange");
  10509. return OUT_OF_ORDER_E;
  10510. }
  10511. if (ssl->msgsReceived.got_certificate_status == 0) {
  10512. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  10513. if (ssl->status_request) {
  10514. int ret;
  10515. WOLFSSL_MSG("No CertificateStatus before ServerKeyExchange");
  10516. if ((ret = TLSX_CSR_ForceRequest(ssl)) != 0)
  10517. return ret;
  10518. }
  10519. #endif
  10520. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  10521. if (ssl->status_request_v2) {
  10522. int ret;
  10523. WOLFSSL_MSG("No CertificateStatus before ServerKeyExchange");
  10524. if ((ret = TLSX_CSR2_ForceRequest(ssl)) != 0)
  10525. return ret;
  10526. }
  10527. #endif
  10528. }
  10529. break;
  10530. #endif
  10531. #ifndef NO_WOLFSSL_CLIENT
  10532. case certificate_request:
  10533. if (ssl->msgsReceived.got_certificate_request) {
  10534. WOLFSSL_MSG("Duplicate CertificateRequest received");
  10535. return DUPLICATE_MSG_E;
  10536. }
  10537. ssl->msgsReceived.got_certificate_request = 1;
  10538. break;
  10539. #endif
  10540. #ifndef NO_WOLFSSL_CLIENT
  10541. case server_hello_done:
  10542. if (ssl->msgsReceived.got_server_hello_done) {
  10543. WOLFSSL_MSG("Duplicate ServerHelloDone received");
  10544. return DUPLICATE_MSG_E;
  10545. }
  10546. ssl->msgsReceived.got_server_hello_done = 1;
  10547. if (ssl->msgsReceived.got_certificate == 0) {
  10548. if (ssl->specs.kea == psk_kea ||
  10549. ssl->specs.kea == dhe_psk_kea ||
  10550. ssl->specs.kea == ecdhe_psk_kea ||
  10551. ssl->options.usingAnon_cipher) {
  10552. WOLFSSL_MSG("No Cert required");
  10553. } else {
  10554. WOLFSSL_MSG("No Certificate before ServerHelloDone");
  10555. return OUT_OF_ORDER_E;
  10556. }
  10557. }
  10558. if (ssl->msgsReceived.got_server_key_exchange == 0) {
  10559. int pskNoServerHint = 0; /* not required in this case */
  10560. #ifndef NO_PSK
  10561. if (ssl->specs.kea == psk_kea &&
  10562. ssl->arrays != NULL &&
  10563. ssl->arrays->server_hint[0] == 0)
  10564. pskNoServerHint = 1;
  10565. #endif
  10566. if (ssl->specs.static_ecdh == 1 ||
  10567. ssl->specs.kea == rsa_kea ||
  10568. ssl->specs.kea == ntru_kea ||
  10569. pskNoServerHint) {
  10570. WOLFSSL_MSG("No KeyExchange required");
  10571. } else {
  10572. WOLFSSL_MSG("No ServerKeyExchange before ServerDone");
  10573. return OUT_OF_ORDER_E;
  10574. }
  10575. }
  10576. break;
  10577. #endif
  10578. #ifndef NO_WOLFSSL_SERVER
  10579. case certificate_verify:
  10580. if (ssl->msgsReceived.got_certificate_verify) {
  10581. WOLFSSL_MSG("Duplicate CertificateVerify received");
  10582. return DUPLICATE_MSG_E;
  10583. }
  10584. ssl->msgsReceived.got_certificate_verify = 1;
  10585. if ( ssl->msgsReceived.got_certificate == 0) {
  10586. WOLFSSL_MSG("No Cert before CertVerify");
  10587. return OUT_OF_ORDER_E;
  10588. }
  10589. break;
  10590. #endif
  10591. #ifndef NO_WOLFSSL_SERVER
  10592. case client_key_exchange:
  10593. if (ssl->msgsReceived.got_client_key_exchange) {
  10594. WOLFSSL_MSG("Duplicate ClientKeyExchange received");
  10595. #ifdef WOLFSSL_EXTRA_ALERTS
  10596. SendAlert(ssl, alert_fatal, unexpected_message);
  10597. #endif
  10598. return DUPLICATE_MSG_E;
  10599. }
  10600. ssl->msgsReceived.got_client_key_exchange = 1;
  10601. if (ssl->msgsReceived.got_client_hello == 0) {
  10602. WOLFSSL_MSG("No ClientHello before ClientKeyExchange");
  10603. return OUT_OF_ORDER_E;
  10604. }
  10605. break;
  10606. #endif
  10607. case finished:
  10608. if (ssl->msgsReceived.got_finished) {
  10609. WOLFSSL_MSG("Duplicate Finished received");
  10610. return DUPLICATE_MSG_E;
  10611. }
  10612. ssl->msgsReceived.got_finished = 1;
  10613. if (ssl->msgsReceived.got_change_cipher == 0) {
  10614. WOLFSSL_MSG("Finished received before ChangeCipher");
  10615. #ifdef WOLFSSL_EXTRA_ALERTS
  10616. SendAlert(ssl, alert_fatal, unexpected_message);
  10617. #endif
  10618. return NO_CHANGE_CIPHER_E;
  10619. }
  10620. break;
  10621. case change_cipher_hs:
  10622. if (ssl->msgsReceived.got_change_cipher) {
  10623. WOLFSSL_MSG("Duplicate ChangeCipher received");
  10624. #ifdef WOLFSSL_EXTRA_ALERTS
  10625. SendAlert(ssl, alert_fatal, unexpected_message);
  10626. #endif
  10627. return DUPLICATE_MSG_E;
  10628. }
  10629. /* DTLS is going to ignore the CCS message if the client key
  10630. * exchange message wasn't received yet. */
  10631. if (!ssl->options.dtls)
  10632. ssl->msgsReceived.got_change_cipher = 1;
  10633. #ifndef NO_WOLFSSL_CLIENT
  10634. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  10635. if (!ssl->options.resuming) {
  10636. if (ssl->msgsReceived.got_server_hello_done == 0) {
  10637. WOLFSSL_MSG("No ServerHelloDone before ChangeCipher");
  10638. return OUT_OF_ORDER_E;
  10639. }
  10640. }
  10641. else {
  10642. if (ssl->msgsReceived.got_server_hello == 0) {
  10643. WOLFSSL_MSG("No ServerHello before ChangeCipher on Resume");
  10644. return OUT_OF_ORDER_E;
  10645. }
  10646. }
  10647. #ifdef HAVE_SESSION_TICKET
  10648. if (ssl->expect_session_ticket) {
  10649. WOLFSSL_MSG("Expected session ticket missing");
  10650. #ifdef WOLFSSL_DTLS
  10651. if (ssl->options.dtls)
  10652. return OUT_OF_ORDER_E;
  10653. #endif
  10654. return SESSION_TICKET_EXPECT_E;
  10655. }
  10656. #endif
  10657. }
  10658. #endif
  10659. #ifndef NO_WOLFSSL_SERVER
  10660. if (ssl->options.side == WOLFSSL_SERVER_END) {
  10661. if (!ssl->options.resuming &&
  10662. ssl->msgsReceived.got_client_key_exchange == 0) {
  10663. WOLFSSL_MSG("No ClientKeyExchange before ChangeCipher");
  10664. #ifdef WOLFSSL_EXTRA_ALERTS
  10665. SendAlert(ssl, alert_fatal, unexpected_message);
  10666. #endif
  10667. return OUT_OF_ORDER_E;
  10668. }
  10669. #ifndef NO_CERTS
  10670. if (ssl->options.verifyPeer &&
  10671. ssl->options.havePeerCert) {
  10672. if (!ssl->options.havePeerVerify) {
  10673. WOLFSSL_MSG("client didn't send cert verify");
  10674. #ifdef WOLFSSL_DTLS
  10675. if (ssl->options.dtls)
  10676. return OUT_OF_ORDER_E;
  10677. #endif
  10678. return NO_PEER_VERIFY;
  10679. }
  10680. }
  10681. #endif
  10682. }
  10683. #endif
  10684. if (ssl->options.dtls)
  10685. ssl->msgsReceived.got_change_cipher = 1;
  10686. break;
  10687. default:
  10688. WOLFSSL_MSG("Unknown message type");
  10689. return SANITY_MSG_E;
  10690. }
  10691. return 0;
  10692. }
  10693. static int DoHandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  10694. byte type, word32 size, word32 totalSz)
  10695. {
  10696. int ret = 0;
  10697. word32 expectedIdx;
  10698. WOLFSSL_ENTER("DoHandShakeMsgType");
  10699. #ifdef WOLFSSL_TLS13
  10700. if (type == hello_retry_request) {
  10701. return DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
  10702. totalSz);
  10703. }
  10704. #endif
  10705. /* make sure can read the message */
  10706. if (*inOutIdx + size > totalSz) {
  10707. WOLFSSL_MSG("Incomplete Data");
  10708. return INCOMPLETE_DATA;
  10709. }
  10710. expectedIdx = *inOutIdx + size +
  10711. (ssl->keys.encryptionOn ? ssl->keys.padSz : 0);
  10712. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10713. if (ssl->options.startedETMRead && ssl->keys.encryptionOn)
  10714. expectedIdx += MacSize(ssl);
  10715. #endif
  10716. #if !defined(WOLFSSL_NO_SERVER) && \
  10717. defined(HAVE_SECURE_RENEGOTIATION) && \
  10718. defined(HAVE_SERVER_RENEGOTIATION_INFO)
  10719. if (ssl->options.handShakeDone && type == client_hello &&
  10720. ssl->secure_renegotiation &&
  10721. ssl->secure_renegotiation->enabled)
  10722. {
  10723. WOLFSSL_MSG("Reset handshake state");
  10724. XMEMSET(&ssl->msgsReceived, 0, sizeof(MsgsReceived));
  10725. ssl->options.serverState = NULL_STATE;
  10726. ssl->options.clientState = NULL_STATE;
  10727. ssl->options.connectState = CONNECT_BEGIN;
  10728. ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
  10729. ssl->options.handShakeState = NULL_STATE;
  10730. ssl->secure_renegotiation->cache_status = SCR_CACHE_NEEDED;
  10731. ret = InitHandshakeHashes(ssl);
  10732. if (ret != 0)
  10733. return ret;
  10734. }
  10735. #endif
  10736. /* sanity check msg received */
  10737. if ( (ret = SanityCheckMsgReceived(ssl, type)) != 0) {
  10738. WOLFSSL_MSG("Sanity Check on handshake message type received failed");
  10739. return ret;
  10740. }
  10741. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  10742. /* add name later, add on record and handshake header part back on */
  10743. if (ssl->toInfoOn) {
  10744. int add = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  10745. AddPacketInfo(ssl, 0, handshake, input + *inOutIdx - add,
  10746. size + add, READ_PROTO, ssl->heap);
  10747. #ifdef WOLFSSL_CALLBACKS
  10748. AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
  10749. #endif
  10750. }
  10751. #endif
  10752. if (ssl->options.handShakeState == HANDSHAKE_DONE && type != hello_request){
  10753. WOLFSSL_MSG("HandShake message after handshake complete");
  10754. SendAlert(ssl, alert_fatal, unexpected_message);
  10755. return OUT_OF_ORDER_E;
  10756. }
  10757. if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.dtls == 0 &&
  10758. ssl->options.serverState == NULL_STATE && type != server_hello) {
  10759. WOLFSSL_MSG("First server message not server hello");
  10760. SendAlert(ssl, alert_fatal, unexpected_message);
  10761. return OUT_OF_ORDER_E;
  10762. }
  10763. if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.dtls &&
  10764. type == server_hello_done &&
  10765. ssl->options.serverState < SERVER_HELLO_COMPLETE) {
  10766. WOLFSSL_MSG("Server hello done received before server hello in DTLS");
  10767. SendAlert(ssl, alert_fatal, unexpected_message);
  10768. return OUT_OF_ORDER_E;
  10769. }
  10770. if (ssl->options.side == WOLFSSL_SERVER_END &&
  10771. ssl->options.clientState == NULL_STATE && type != client_hello) {
  10772. WOLFSSL_MSG("First client message not client hello");
  10773. SendAlert(ssl, alert_fatal, unexpected_message);
  10774. return OUT_OF_ORDER_E;
  10775. }
  10776. /* above checks handshake state */
  10777. /* hello_request not hashed */
  10778. /* Also, skip hashing the client_hello message here for DTLS. It will be
  10779. * hashed later if the DTLS cookie is correct. */
  10780. if (type != hello_request &&
  10781. !(IsDtlsNotSctpMode(ssl) && type == client_hello)
  10782. #ifdef WOLFSSL_ASYNC_CRYPT
  10783. && ssl->error != WC_PENDING_E
  10784. #endif
  10785. #ifdef WOLFSSL_NONBLOCK_OCSP
  10786. && ssl->error != OCSP_WANT_READ
  10787. #endif
  10788. ) {
  10789. ret = HashInput(ssl, input + *inOutIdx, size);
  10790. if (ret != 0) {
  10791. WOLFSSL_MSG("Incomplete handshake hashes");
  10792. return ret;
  10793. }
  10794. }
  10795. #ifdef OPENSSL_EXTRA
  10796. if (ssl->CBIS != NULL){
  10797. ssl->cbmode = SSL_CB_MODE_READ;
  10798. ssl->cbtype = type;
  10799. ssl->CBIS(ssl, SSL_CB_ACCEPT_LOOP, SSL_SUCCESS);
  10800. }
  10801. #endif
  10802. switch (type) {
  10803. case hello_request:
  10804. WOLFSSL_MSG("processing hello request");
  10805. ret = DoHelloRequest(ssl, input, inOutIdx, size, totalSz);
  10806. break;
  10807. #ifndef NO_WOLFSSL_CLIENT
  10808. case hello_verify_request:
  10809. WOLFSSL_MSG("processing hello verify request");
  10810. ret = DoHelloVerifyRequest(ssl, input,inOutIdx, size);
  10811. break;
  10812. case server_hello:
  10813. WOLFSSL_MSG("processing server hello");
  10814. ret = DoServerHello(ssl, input, inOutIdx, size);
  10815. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  10816. ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  10817. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  10818. if (ssl->options.resuming || !IsAtLeastTLSv1_2(ssl) ||
  10819. IsAtLeastTLSv1_3(ssl->version)) {
  10820. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  10821. if (ret != WC_PENDING_E && ret != OCSP_WANT_READ)
  10822. #endif
  10823. {
  10824. ssl->options.cacheMessages = 0;
  10825. if (ssl->hsHashes->messages != NULL) {
  10826. XFREE(ssl->hsHashes->messages, ssl->heap,
  10827. DYNAMIC_TYPE_HASHES);
  10828. ssl->hsHashes->messages = NULL;
  10829. }
  10830. }
  10831. }
  10832. #endif
  10833. break;
  10834. #ifndef NO_CERTS
  10835. case certificate_request:
  10836. WOLFSSL_MSG("processing certificate request");
  10837. ret = DoCertificateRequest(ssl, input, inOutIdx, size);
  10838. break;
  10839. #endif
  10840. case server_key_exchange:
  10841. WOLFSSL_MSG("processing server key exchange");
  10842. ret = DoServerKeyExchange(ssl, input, inOutIdx, size);
  10843. break;
  10844. #ifdef HAVE_SESSION_TICKET
  10845. case session_ticket:
  10846. WOLFSSL_MSG("processing session ticket");
  10847. ret = DoSessionTicket(ssl, input, inOutIdx, size);
  10848. break;
  10849. #endif /* HAVE_SESSION_TICKET */
  10850. #endif
  10851. #if !defined(NO_CERTS) && (!defined(NO_WOLFSSL_CLIENT) || \
  10852. !defined(WOLFSSL_NO_CLIENT_AUTH))
  10853. case certificate:
  10854. WOLFSSL_MSG("processing certificate");
  10855. ret = DoCertificate(ssl, input, inOutIdx, size);
  10856. break;
  10857. case certificate_status:
  10858. WOLFSSL_MSG("processing certificate status");
  10859. ret = DoCertificateStatus(ssl, input, inOutIdx, size);
  10860. break;
  10861. #endif
  10862. case server_hello_done:
  10863. WOLFSSL_MSG("processing server hello done");
  10864. #ifdef WOLFSSL_CALLBACKS
  10865. if (ssl->hsInfoOn)
  10866. AddPacketName(ssl, "ServerHelloDone");
  10867. if (ssl->toInfoOn)
  10868. AddLateName("ServerHelloDone", &ssl->timeoutInfo);
  10869. #endif
  10870. ssl->options.serverState = SERVER_HELLODONE_COMPLETE;
  10871. if (IsEncryptionOn(ssl, 0)) {
  10872. *inOutIdx += ssl->keys.padSz;
  10873. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10874. if (ssl->options.startedETMRead)
  10875. *inOutIdx += MacSize(ssl);
  10876. #endif
  10877. }
  10878. if (ssl->options.resuming) {
  10879. WOLFSSL_MSG("Not resuming as thought");
  10880. ssl->options.resuming = 0;
  10881. }
  10882. break;
  10883. case finished:
  10884. WOLFSSL_MSG("processing finished");
  10885. ret = DoFinished(ssl, input, inOutIdx, size, totalSz, NO_SNIFF);
  10886. break;
  10887. #ifndef NO_WOLFSSL_SERVER
  10888. case client_hello:
  10889. WOLFSSL_MSG("processing client hello");
  10890. ret = DoClientHello(ssl, input, inOutIdx, size);
  10891. #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
  10892. ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
  10893. (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
  10894. if (ssl->options.resuming || !ssl->options.verifyPeer || \
  10895. !IsAtLeastTLSv1_2(ssl) || IsAtLeastTLSv1_3(ssl->version)) {
  10896. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  10897. if (ret != WC_PENDING_E && ret != OCSP_WANT_READ)
  10898. #endif
  10899. {
  10900. ssl->options.cacheMessages = 0;
  10901. if (ssl->hsHashes->messages != NULL) {
  10902. XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
  10903. ssl->hsHashes->messages = NULL;
  10904. }
  10905. }
  10906. }
  10907. #endif
  10908. if (IsEncryptionOn(ssl, 0)) {
  10909. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  10910. if (ssl->options.startedETMRead) {
  10911. word32 digestSz = MacSize(ssl);
  10912. if (*inOutIdx + ssl->keys.padSz + digestSz > totalSz)
  10913. return BUFFER_E;
  10914. *inOutIdx += ssl->keys.padSz + digestSz;
  10915. }
  10916. else
  10917. #endif
  10918. {
  10919. /* access beyond input + size should be checked against totalSz
  10920. */
  10921. if (*inOutIdx + ssl->keys.padSz > totalSz)
  10922. return BUFFER_E;
  10923. *inOutIdx += ssl->keys.padSz;
  10924. }
  10925. }
  10926. break;
  10927. case client_key_exchange:
  10928. WOLFSSL_MSG("processing client key exchange");
  10929. ret = DoClientKeyExchange(ssl, input, inOutIdx, size);
  10930. break;
  10931. #if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  10932. defined(HAVE_ED448)) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  10933. case certificate_verify:
  10934. WOLFSSL_MSG("processing certificate verify");
  10935. ret = DoCertificateVerify(ssl, input, inOutIdx, size);
  10936. break;
  10937. #endif /* (!NO_RSA || ECC || ED25519 || ED448) && !WOLFSSL_NO_CLIENT_AUTH */
  10938. #endif /* !NO_WOLFSSL_SERVER */
  10939. default:
  10940. WOLFSSL_MSG("Unknown handshake message type");
  10941. ret = UNKNOWN_HANDSHAKE_TYPE;
  10942. break;
  10943. }
  10944. if (ret == 0 && expectedIdx != *inOutIdx) {
  10945. WOLFSSL_MSG("Extra data in handshake message");
  10946. if (!ssl->options.dtls)
  10947. SendAlert(ssl, alert_fatal, decode_error);
  10948. ret = DECODE_E;
  10949. }
  10950. if (ret == 0 && ssl->buffers.inputBuffer.dynamicFlag
  10951. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  10952. /* do not shrink input for async or non-block */
  10953. && ssl->error != WC_PENDING_E && ssl->error != OCSP_WANT_READ
  10954. #endif
  10955. ) {
  10956. ShrinkInputBuffer(ssl, NO_FORCED_FREE);
  10957. }
  10958. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
  10959. /* if async, offset index so this msg will be processed again */
  10960. if ((ret == WC_PENDING_E || ret == OCSP_WANT_READ) && *inOutIdx > 0) {
  10961. *inOutIdx -= HANDSHAKE_HEADER_SZ;
  10962. #ifdef WOLFSSL_DTLS
  10963. if (ssl->options.dtls) {
  10964. *inOutIdx -= DTLS_HANDSHAKE_EXTRA;
  10965. }
  10966. #endif
  10967. }
  10968. /* make sure async error is cleared */
  10969. if (ret == 0 && (ssl->error == WC_PENDING_E || ssl->error == OCSP_WANT_READ)) {
  10970. ssl->error = 0;
  10971. }
  10972. #endif /* WOLFSSL_ASYNC_CRYPT || WOLFSSL_NONBLOCK_OCSP */
  10973. WOLFSSL_LEAVE("DoHandShakeMsgType()", ret);
  10974. return ret;
  10975. }
  10976. static int DoHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  10977. word32 totalSz)
  10978. {
  10979. int ret = 0;
  10980. word32 inputLength;
  10981. WOLFSSL_ENTER("DoHandShakeMsg()");
  10982. if (ssl->arrays == NULL) {
  10983. byte type;
  10984. word32 size;
  10985. if (GetHandShakeHeader(ssl,input,inOutIdx,&type, &size, totalSz) != 0)
  10986. return PARSE_ERROR;
  10987. ssl->options.handShakeState = type;
  10988. return DoHandShakeMsgType(ssl, input, inOutIdx, type, size, totalSz);
  10989. }
  10990. inputLength = ssl->buffers.inputBuffer.length - *inOutIdx;
  10991. /* If there is a pending fragmented handshake message,
  10992. * pending message size will be non-zero. */
  10993. if (ssl->arrays->pendingMsgSz == 0) {
  10994. byte type;
  10995. word32 size;
  10996. if (GetHandShakeHeader(ssl,input, inOutIdx, &type, &size, totalSz) != 0)
  10997. return PARSE_ERROR;
  10998. /* Cap the maximum size of a handshake message to something reasonable.
  10999. * By default is the maximum size of a certificate message assuming
  11000. * nine 2048-bit RSA certificates in the chain. */
  11001. if (size > MAX_HANDSHAKE_SZ) {
  11002. WOLFSSL_MSG("Handshake message too large");
  11003. return HANDSHAKE_SIZE_ERROR;
  11004. }
  11005. /* size is the size of the certificate message payload */
  11006. if (inputLength - HANDSHAKE_HEADER_SZ < size) {
  11007. ssl->arrays->pendingMsgType = type;
  11008. ssl->arrays->pendingMsgSz = size + HANDSHAKE_HEADER_SZ;
  11009. ssl->arrays->pendingMsg = (byte*)XMALLOC(size + HANDSHAKE_HEADER_SZ,
  11010. ssl->heap,
  11011. DYNAMIC_TYPE_ARRAYS);
  11012. if (ssl->arrays->pendingMsg == NULL)
  11013. return MEMORY_E;
  11014. XMEMCPY(ssl->arrays->pendingMsg,
  11015. input + *inOutIdx - HANDSHAKE_HEADER_SZ,
  11016. inputLength);
  11017. ssl->arrays->pendingMsgOffset = inputLength;
  11018. *inOutIdx += inputLength - HANDSHAKE_HEADER_SZ;
  11019. return 0;
  11020. }
  11021. ret = DoHandShakeMsgType(ssl, input, inOutIdx, type, size, totalSz);
  11022. }
  11023. else {
  11024. word32 pendSz =
  11025. ssl->arrays->pendingMsgSz - ssl->arrays->pendingMsgOffset;
  11026. /* Catch the case where there may be the remainder of a fragmented
  11027. * handshake message and the next handshake message in the same
  11028. * record. */
  11029. if (inputLength > pendSz)
  11030. inputLength = pendSz;
  11031. XMEMCPY(ssl->arrays->pendingMsg + ssl->arrays->pendingMsgOffset,
  11032. input + *inOutIdx, inputLength);
  11033. ssl->arrays->pendingMsgOffset += inputLength;
  11034. *inOutIdx += inputLength;
  11035. if (ssl->arrays->pendingMsgOffset == ssl->arrays->pendingMsgSz)
  11036. {
  11037. word32 idx = HANDSHAKE_HEADER_SZ;
  11038. ret = DoHandShakeMsgType(ssl,
  11039. ssl->arrays->pendingMsg,
  11040. &idx, ssl->arrays->pendingMsgType,
  11041. ssl->arrays->pendingMsgSz - idx,
  11042. ssl->arrays->pendingMsgSz);
  11043. #ifdef WOLFSSL_ASYNC_CRYPT
  11044. if (ret == WC_PENDING_E) {
  11045. /* setup to process fragment again */
  11046. ssl->arrays->pendingMsgOffset -= inputLength;
  11047. *inOutIdx -= inputLength;
  11048. }
  11049. else
  11050. #endif
  11051. {
  11052. XFREE(ssl->arrays->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
  11053. ssl->arrays->pendingMsg = NULL;
  11054. ssl->arrays->pendingMsgSz = 0;
  11055. }
  11056. }
  11057. }
  11058. WOLFSSL_LEAVE("DoHandShakeMsg()", ret);
  11059. return ret;
  11060. }
  11061. #endif /* !WOLFSSL_NO_TLS12 */
  11062. #ifdef WOLFSSL_DTLS
  11063. static WC_INLINE int DtlsCheckWindow(WOLFSSL* ssl)
  11064. {
  11065. word32* window;
  11066. word16 cur_hi, next_hi;
  11067. word32 cur_lo, next_lo, diff;
  11068. int curLT;
  11069. WOLFSSL_DTLS_PEERSEQ* peerSeq = NULL;
  11070. if (!ssl->options.haveMcast)
  11071. peerSeq = ssl->keys.peerSeq;
  11072. else {
  11073. #ifdef WOLFSSL_MULTICAST
  11074. WOLFSSL_DTLS_PEERSEQ* p;
  11075. int i;
  11076. for (i = 0, p = ssl->keys.peerSeq;
  11077. i < WOLFSSL_DTLS_PEERSEQ_SZ;
  11078. i++, p++) {
  11079. if (p->peerId == ssl->keys.curPeerId) {
  11080. peerSeq = p;
  11081. break;
  11082. }
  11083. }
  11084. #endif
  11085. }
  11086. if (peerSeq == NULL) {
  11087. WOLFSSL_MSG("Could not find peer sequence");
  11088. return 0;
  11089. }
  11090. if (ssl->keys.curEpoch == peerSeq->nextEpoch) {
  11091. next_hi = peerSeq->nextSeq_hi;
  11092. next_lo = peerSeq->nextSeq_lo;
  11093. window = peerSeq->window;
  11094. }
  11095. else if (ssl->keys.curEpoch == peerSeq->nextEpoch - 1) {
  11096. next_hi = peerSeq->prevSeq_hi;
  11097. next_lo = peerSeq->prevSeq_lo;
  11098. window = peerSeq->prevWindow;
  11099. }
  11100. else {
  11101. return 0;
  11102. }
  11103. cur_hi = ssl->keys.curSeq_hi;
  11104. cur_lo = ssl->keys.curSeq_lo;
  11105. /* If the difference between next and cur is > 2^32, way outside window. */
  11106. if ((cur_hi > next_hi + 1) || (next_hi > cur_hi + 1)) {
  11107. WOLFSSL_MSG("Current record from way too far in the future.");
  11108. return 0;
  11109. }
  11110. if (cur_hi == next_hi) {
  11111. curLT = cur_lo < next_lo;
  11112. diff = curLT ? next_lo - cur_lo : cur_lo - next_lo;
  11113. }
  11114. else {
  11115. curLT = cur_hi < next_hi;
  11116. diff = curLT ? cur_lo - next_lo : next_lo - cur_lo;
  11117. }
  11118. /* Check to see that the next value is greater than the number of messages
  11119. * trackable in the window, and that the difference between the next
  11120. * expected sequence number and the received sequence number is inside the
  11121. * window. */
  11122. if ((next_hi || next_lo > DTLS_SEQ_BITS) &&
  11123. curLT && (diff > DTLS_SEQ_BITS)) {
  11124. WOLFSSL_MSG("Current record sequence number from the past.");
  11125. return 0;
  11126. }
  11127. #ifndef WOLFSSL_DTLS_ALLOW_FUTURE
  11128. else if (!curLT && (diff > DTLS_SEQ_BITS)) {
  11129. WOLFSSL_MSG("Rejecting message too far into the future.");
  11130. return 0;
  11131. }
  11132. #endif
  11133. else if (curLT) {
  11134. word32 idx = diff / DTLS_WORD_BITS;
  11135. word32 newDiff = diff % DTLS_WORD_BITS;
  11136. /* verify idx is valid for window array */
  11137. if (idx >= WOLFSSL_DTLS_WINDOW_WORDS) {
  11138. WOLFSSL_MSG("Invalid DTLS windows index");
  11139. return 0;
  11140. }
  11141. if (window[idx] & (1 << newDiff)) {
  11142. WOLFSSL_MSG("Current record sequence number already received.");
  11143. return 0;
  11144. }
  11145. }
  11146. return 1;
  11147. }
  11148. #ifdef WOLFSSL_MULTICAST
  11149. static WC_INLINE word32 UpdateHighwaterMark(word32 cur, word32 first,
  11150. word32 second, word32 max)
  11151. {
  11152. word32 newCur = 0;
  11153. if (cur < first)
  11154. newCur = first;
  11155. else if (cur < second)
  11156. newCur = second;
  11157. else if (cur < max)
  11158. newCur = max;
  11159. return newCur;
  11160. }
  11161. #endif /* WOLFSSL_MULTICAST */
  11162. static WC_INLINE int DtlsUpdateWindow(WOLFSSL* ssl)
  11163. {
  11164. word32* window;
  11165. word32* next_lo;
  11166. word16* next_hi;
  11167. int curLT;
  11168. word32 cur_lo, diff;
  11169. word16 cur_hi;
  11170. WOLFSSL_DTLS_PEERSEQ* peerSeq = ssl->keys.peerSeq;
  11171. cur_hi = ssl->keys.curSeq_hi;
  11172. cur_lo = ssl->keys.curSeq_lo;
  11173. #ifdef WOLFSSL_MULTICAST
  11174. if (ssl->options.haveMcast) {
  11175. WOLFSSL_DTLS_PEERSEQ* p;
  11176. int i;
  11177. peerSeq = NULL;
  11178. for (i = 0, p = ssl->keys.peerSeq;
  11179. i < WOLFSSL_DTLS_PEERSEQ_SZ;
  11180. i++, p++) {
  11181. if (p->peerId == ssl->keys.curPeerId) {
  11182. peerSeq = p;
  11183. break;
  11184. }
  11185. }
  11186. if (peerSeq == NULL) {
  11187. WOLFSSL_MSG("Couldn't find that peer ID to update window.");
  11188. return 0;
  11189. }
  11190. if (p->highwaterMark && cur_lo >= p->highwaterMark) {
  11191. int cbError = 0;
  11192. if (ssl->ctx->mcastHwCb)
  11193. cbError = ssl->ctx->mcastHwCb(p->peerId,
  11194. ssl->ctx->mcastMaxSeq,
  11195. cur_lo, ssl->mcastHwCbCtx);
  11196. if (cbError) {
  11197. WOLFSSL_MSG("Multicast highwater callback returned an error.");
  11198. return MCAST_HIGHWATER_CB_E;
  11199. }
  11200. p->highwaterMark = UpdateHighwaterMark(cur_lo,
  11201. ssl->ctx->mcastFirstSeq,
  11202. ssl->ctx->mcastSecondSeq,
  11203. ssl->ctx->mcastMaxSeq);
  11204. }
  11205. }
  11206. #endif
  11207. if (ssl->keys.curEpoch == peerSeq->nextEpoch) {
  11208. next_hi = &peerSeq->nextSeq_hi;
  11209. next_lo = &peerSeq->nextSeq_lo;
  11210. window = peerSeq->window;
  11211. }
  11212. else {
  11213. next_hi = &peerSeq->prevSeq_hi;
  11214. next_lo = &peerSeq->prevSeq_lo;
  11215. window = peerSeq->prevWindow;
  11216. }
  11217. if (cur_hi == *next_hi) {
  11218. curLT = cur_lo < *next_lo;
  11219. diff = curLT ? *next_lo - cur_lo : cur_lo - *next_lo;
  11220. }
  11221. else {
  11222. curLT = cur_hi < *next_hi;
  11223. diff = curLT ? cur_lo - *next_lo : *next_lo - cur_lo;
  11224. }
  11225. if (curLT) {
  11226. word32 idx = diff / DTLS_WORD_BITS;
  11227. word32 newDiff = diff % DTLS_WORD_BITS;
  11228. if (idx < WOLFSSL_DTLS_WINDOW_WORDS)
  11229. window[idx] |= (1 << newDiff);
  11230. }
  11231. else {
  11232. if (diff >= DTLS_SEQ_BITS)
  11233. XMEMSET(window, 0, DTLS_SEQ_SZ);
  11234. else {
  11235. word32 idx, newDiff, temp, i;
  11236. word32 oldWindow[WOLFSSL_DTLS_WINDOW_WORDS];
  11237. temp = 0;
  11238. diff++;
  11239. idx = diff / DTLS_WORD_BITS;
  11240. newDiff = diff % DTLS_WORD_BITS;
  11241. XMEMCPY(oldWindow, window, sizeof(oldWindow));
  11242. for (i = 0; i < WOLFSSL_DTLS_WINDOW_WORDS; i++) {
  11243. if (i < idx)
  11244. window[i] = 0;
  11245. else {
  11246. temp |= (oldWindow[i-idx] << newDiff);
  11247. window[i] = temp;
  11248. temp = oldWindow[i-idx] >> (DTLS_WORD_BITS - newDiff - 1);
  11249. }
  11250. }
  11251. }
  11252. window[0] |= 1;
  11253. *next_lo = cur_lo + 1;
  11254. if (*next_lo < cur_lo)
  11255. (*next_hi)++;
  11256. }
  11257. return 1;
  11258. }
  11259. static int DtlsMsgDrain(WOLFSSL* ssl)
  11260. {
  11261. DtlsMsg* item = ssl->dtls_rx_msg_list;
  11262. int ret = 0;
  11263. WOLFSSL_ENTER("DtlsMsgDrain()");
  11264. /* While there is an item in the store list, and it is the expected
  11265. * message, and it is complete, and there hasn't been an error in the
  11266. * last message... */
  11267. while (item != NULL &&
  11268. ssl->keys.dtls_expected_peer_handshake_number == item->seq &&
  11269. item->fragSz == item->sz &&
  11270. ret == 0) {
  11271. word32 idx = 0;
  11272. ssl->keys.dtls_expected_peer_handshake_number++;
  11273. ret = DoHandShakeMsgType(ssl, item->msg,
  11274. &idx, item->type, item->sz, item->sz);
  11275. #ifdef WOLFSSL_ASYNC_CRYPT
  11276. if (ret == WC_PENDING_E) {
  11277. ssl->keys.dtls_expected_peer_handshake_number--;
  11278. break;
  11279. }
  11280. #endif
  11281. ssl->dtls_rx_msg_list = item->next;
  11282. DtlsMsgDelete(item, ssl->heap);
  11283. item = ssl->dtls_rx_msg_list;
  11284. ssl->dtls_rx_msg_list_sz--;
  11285. }
  11286. WOLFSSL_LEAVE("DtlsMsgDrain()", ret);
  11287. return ret;
  11288. }
  11289. static int DoDtlsHandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  11290. word32 totalSz)
  11291. {
  11292. byte type;
  11293. word32 size;
  11294. word32 fragOffset, fragSz;
  11295. int ret = 0;
  11296. WOLFSSL_ENTER("DoDtlsHandShakeMsg()");
  11297. /* process any pending DTLS messages - this flow can happen with async */
  11298. if (ssl->dtls_rx_msg_list != NULL) {
  11299. ret = DtlsMsgDrain(ssl);
  11300. if (ret != 0)
  11301. return ret;
  11302. /* if done processing fragment exit with success */
  11303. if (totalSz == *inOutIdx)
  11304. return ret;
  11305. }
  11306. /* parse header */
  11307. if (GetDtlsHandShakeHeader(ssl, input, inOutIdx, &type,
  11308. &size, &fragOffset, &fragSz, totalSz) != 0) {
  11309. WOLFSSL_ERROR(PARSE_ERROR);
  11310. return PARSE_ERROR;
  11311. }
  11312. /* Cap the maximum size of a handshake message to something reasonable.
  11313. * By default is the maximum size of a certificate message assuming
  11314. * nine 2048-bit RSA certificates in the chain. */
  11315. if (size > MAX_HANDSHAKE_SZ) {
  11316. WOLFSSL_MSG("Handshake message too large");
  11317. return HANDSHAKE_SIZE_ERROR;
  11318. }
  11319. /* check that we have complete fragment */
  11320. if (*inOutIdx + fragSz > totalSz) {
  11321. WOLFSSL_ERROR(INCOMPLETE_DATA);
  11322. return INCOMPLETE_DATA;
  11323. }
  11324. /* Check the handshake sequence number first. If out of order,
  11325. * add the current message to the list. If the message is in order,
  11326. * but it is a fragment, add the current message to the list, then
  11327. * check the head of the list to see if it is complete, if so, pop
  11328. * it out as the current message. If the message is complete and in
  11329. * order, process it. Check the head of the list to see if it is in
  11330. * order, if so, process it. (Repeat until list exhausted.) If the
  11331. * head is out of order, return for more processing.
  11332. */
  11333. if (ssl->keys.dtls_peer_handshake_number >
  11334. ssl->keys.dtls_expected_peer_handshake_number) {
  11335. /* Current message is out of order. It will get stored in the list.
  11336. * Storing also takes care of defragmentation. If the messages is a
  11337. * client hello, we need to process this out of order; the server
  11338. * is not supposed to keep state, but the second client hello will
  11339. * have a different handshake sequence number than is expected, and
  11340. * the server shouldn't be expecting any particular handshake sequence
  11341. * number. (If the cookie changes multiple times in quick succession,
  11342. * the client could be sending multiple new client hello messages
  11343. * with newer and newer cookies.) */
  11344. if (type != client_hello) {
  11345. if (ssl->dtls_rx_msg_list_sz < DTLS_POOL_SZ) {
  11346. DtlsMsgStore(ssl, ssl->keys.dtls_peer_handshake_number,
  11347. input + *inOutIdx, size, type,
  11348. fragOffset, fragSz, ssl->heap);
  11349. }
  11350. *inOutIdx += fragSz;
  11351. ret = 0;
  11352. }
  11353. else {
  11354. ret = DoHandShakeMsgType(ssl, input, inOutIdx, type, size, totalSz);
  11355. if (ret == 0) {
  11356. ssl->keys.dtls_expected_peer_handshake_number =
  11357. ssl->keys.dtls_peer_handshake_number + 1;
  11358. }
  11359. }
  11360. }
  11361. else if (ssl->keys.dtls_peer_handshake_number <
  11362. ssl->keys.dtls_expected_peer_handshake_number) {
  11363. /* Already saw this message and processed it. It can be ignored. */
  11364. *inOutIdx += fragSz;
  11365. if(type == finished ) {
  11366. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  11367. if (ssl->options.startedETMRead) {
  11368. word32 digestSz = MacSize(ssl);
  11369. if (*inOutIdx + ssl->keys.padSz + digestSz > totalSz)
  11370. return BUFFER_E;
  11371. *inOutIdx += ssl->keys.padSz + digestSz;
  11372. }
  11373. else
  11374. #endif
  11375. {
  11376. if (*inOutIdx + ssl->keys.padSz > totalSz) {
  11377. WOLFSSL_ERROR(BUFFER_E);
  11378. return BUFFER_E;
  11379. }
  11380. *inOutIdx += ssl->keys.padSz;
  11381. }
  11382. }
  11383. if (IsDtlsNotSctpMode(ssl) &&
  11384. VerifyForDtlsMsgPoolSend(ssl, type, fragOffset)) {
  11385. ret = DtlsMsgPoolSend(ssl, 0);
  11386. }
  11387. }
  11388. else if (fragSz < size) {
  11389. /* Since this branch is in order, but fragmented, dtls_rx_msg_list will
  11390. * be pointing to the message with this fragment in it. Check it to see
  11391. * if it is completed. */
  11392. if (ssl->dtls_rx_msg_list_sz < DTLS_POOL_SZ) {
  11393. DtlsMsgStore(ssl, ssl->keys.dtls_peer_handshake_number,
  11394. input + *inOutIdx, size, type,
  11395. fragOffset, fragSz, ssl->heap);
  11396. }
  11397. *inOutIdx += fragSz;
  11398. ret = 0;
  11399. if (ssl->dtls_rx_msg_list != NULL &&
  11400. ssl->dtls_rx_msg_list->fragSz >= ssl->dtls_rx_msg_list->sz)
  11401. ret = DtlsMsgDrain(ssl);
  11402. }
  11403. else {
  11404. /* This branch is in order next, and a complete message. */
  11405. ret = DoHandShakeMsgType(ssl, input, inOutIdx, type, size, totalSz);
  11406. if (ret == 0) {
  11407. if (type != client_hello || !IsDtlsNotSctpMode(ssl))
  11408. ssl->keys.dtls_expected_peer_handshake_number++;
  11409. if (ssl->dtls_rx_msg_list != NULL) {
  11410. ret = DtlsMsgDrain(ssl);
  11411. }
  11412. }
  11413. }
  11414. WOLFSSL_LEAVE("DoDtlsHandShakeMsg()", ret);
  11415. return ret;
  11416. }
  11417. #endif
  11418. #ifndef WOLFSSL_NO_TLS12
  11419. #ifdef HAVE_AEAD
  11420. #if !defined(NO_PUBLIC_GCM_SET_IV) && \
  11421. (((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
  11422. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2))) || \
  11423. (defined(HAVE_POLY1305) && defined(HAVE_CHACHA)))
  11424. static WC_INLINE void AeadIncrementExpIV(WOLFSSL* ssl)
  11425. {
  11426. int i;
  11427. for (i = AEAD_MAX_EXP_SZ-1; i >= 0; i--) {
  11428. if (++ssl->keys.aead_exp_IV[i]) return;
  11429. }
  11430. }
  11431. #endif
  11432. #if defined(HAVE_POLY1305) && defined(HAVE_CHACHA)
  11433. /* Used for the older version of creating AEAD tags with Poly1305 */
  11434. static int Poly1305TagOld(WOLFSSL* ssl, byte* additional, const byte* out,
  11435. byte* cipher, word16 sz, byte* tag)
  11436. {
  11437. int ret = 0;
  11438. int msglen = (sz - ssl->specs.aead_mac_size);
  11439. word32 keySz = 32;
  11440. byte padding[8]; /* used to temporarily store lengths */
  11441. #ifdef CHACHA_AEAD_TEST
  11442. printf("Using old version of poly1305 input.\n");
  11443. #endif
  11444. if (msglen < 0)
  11445. return INPUT_CASE_ERROR;
  11446. if ((ret = wc_Poly1305SetKey(ssl->auth.poly1305, cipher, keySz)) != 0)
  11447. return ret;
  11448. if ((ret = wc_Poly1305Update(ssl->auth.poly1305, additional,
  11449. AEAD_AUTH_DATA_SZ)) != 0)
  11450. return ret;
  11451. /* length of additional input plus padding */
  11452. XMEMSET(padding, 0, sizeof(padding));
  11453. padding[0] = AEAD_AUTH_DATA_SZ;
  11454. if ((ret = wc_Poly1305Update(ssl->auth.poly1305, padding,
  11455. sizeof(padding))) != 0)
  11456. return ret;
  11457. /* add cipher info and then its length */
  11458. XMEMSET(padding, 0, sizeof(padding));
  11459. if ((ret = wc_Poly1305Update(ssl->auth.poly1305, out, msglen)) != 0)
  11460. return ret;
  11461. /* 32 bit size of cipher to 64 bit endian */
  11462. padding[0] = msglen & 0xff;
  11463. padding[1] = (msglen >> 8) & 0xff;
  11464. padding[2] = ((word32)msglen >> 16) & 0xff;
  11465. padding[3] = ((word32)msglen >> 24) & 0xff;
  11466. if ((ret = wc_Poly1305Update(ssl->auth.poly1305, padding, sizeof(padding)))
  11467. != 0)
  11468. return ret;
  11469. /* generate tag */
  11470. if ((ret = wc_Poly1305Final(ssl->auth.poly1305, tag)) != 0)
  11471. return ret;
  11472. return ret;
  11473. }
  11474. /* When the flag oldPoly is not set this follows RFC7905. When oldPoly is set
  11475. * the implementation follows an older draft for creating the nonce and MAC.
  11476. * The flag oldPoly gets set automatically depending on what cipher suite was
  11477. * negotiated in the handshake. This is able to be done because the IDs for the
  11478. * cipher suites was updated in RFC7905 giving unique values for the older
  11479. * draft in comparison to the more recent RFC.
  11480. *
  11481. * ssl WOLFSSL structure to get cipher and TLS state from
  11482. * out output buffer to hold encrypted data
  11483. * input data to encrypt
  11484. * sz size of input
  11485. *
  11486. * Return 0 on success negative values in error case
  11487. */
  11488. static int ChachaAEADEncrypt(WOLFSSL* ssl, byte* out, const byte* input,
  11489. word16 sz)
  11490. {
  11491. const byte* additionalSrc = input - RECORD_HEADER_SZ;
  11492. int ret = 0;
  11493. word32 msgLen = (sz - ssl->specs.aead_mac_size);
  11494. byte tag[POLY1305_AUTH_SZ];
  11495. byte add[AEAD_AUTH_DATA_SZ];
  11496. byte nonce[CHACHA20_NONCE_SZ];
  11497. byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for poly1305 */
  11498. #ifdef CHACHA_AEAD_TEST
  11499. int i;
  11500. #endif
  11501. XMEMSET(tag, 0, sizeof(tag));
  11502. XMEMSET(nonce, 0, sizeof(nonce));
  11503. XMEMSET(poly, 0, sizeof(poly));
  11504. XMEMSET(add, 0, sizeof(add));
  11505. /* opaque SEQ number stored for AD */
  11506. WriteSEQ(ssl, CUR_ORDER, add);
  11507. if (ssl->options.oldPoly != 0) {
  11508. /* get nonce. SEQ should not be incremented again here */
  11509. XMEMCPY(nonce + CHACHA20_OLD_OFFSET, add, OPAQUE32_LEN * 2);
  11510. }
  11511. /* Store the type, version. Unfortunately, they are in
  11512. * the input buffer ahead of the plaintext. */
  11513. #ifdef WOLFSSL_DTLS
  11514. if (ssl->options.dtls) {
  11515. additionalSrc -= DTLS_HANDSHAKE_EXTRA;
  11516. }
  11517. #endif
  11518. /* add TLS message size to additional data */
  11519. add[AEAD_AUTH_DATA_SZ - 2] = (msgLen >> 8) & 0xff;
  11520. add[AEAD_AUTH_DATA_SZ - 1] = msgLen & 0xff;
  11521. XMEMCPY(add + AEAD_TYPE_OFFSET, additionalSrc, 3);
  11522. #ifdef CHACHA_AEAD_TEST
  11523. printf("Encrypt Additional : ");
  11524. for (i = 0; i < AEAD_AUTH_DATA_SZ; i++) {
  11525. printf("%02x", add[i]);
  11526. }
  11527. printf("\n\n");
  11528. printf("input before encryption :\n");
  11529. for (i = 0; i < sz; i++) {
  11530. printf("%02x", input[i]);
  11531. if ((i + 1) % 16 == 0)
  11532. printf("\n");
  11533. }
  11534. printf("\n");
  11535. #endif
  11536. if (ssl->options.oldPoly == 0) {
  11537. /* nonce is formed by 4 0x00 byte padded to the left followed by 8 byte
  11538. * record sequence number XORed with client_write_IV/server_write_IV */
  11539. XMEMCPY(nonce, ssl->keys.aead_enc_imp_IV, CHACHA20_IMP_IV_SZ);
  11540. nonce[4] ^= add[0];
  11541. nonce[5] ^= add[1];
  11542. nonce[6] ^= add[2];
  11543. nonce[7] ^= add[3];
  11544. nonce[8] ^= add[4];
  11545. nonce[9] ^= add[5];
  11546. nonce[10] ^= add[6];
  11547. nonce[11] ^= add[7];
  11548. }
  11549. /* set the nonce for chacha and get poly1305 key */
  11550. if ((ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 0)) != 0) {
  11551. ForceZero(nonce, CHACHA20_NONCE_SZ);
  11552. return ret;
  11553. }
  11554. /* create Poly1305 key using chacha20 keystream */
  11555. if ((ret = wc_Chacha_Process(ssl->encrypt.chacha, poly,
  11556. poly, sizeof(poly))) != 0) {
  11557. ForceZero(nonce, CHACHA20_NONCE_SZ);
  11558. return ret;
  11559. }
  11560. /* set the counter after getting poly1305 key */
  11561. if ((ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 1)) != 0) {
  11562. ForceZero(nonce, CHACHA20_NONCE_SZ);
  11563. return ret;
  11564. }
  11565. ForceZero(nonce, CHACHA20_NONCE_SZ); /* done with nonce, clear it */
  11566. /* encrypt the plain text */
  11567. if ((ret = wc_Chacha_Process(ssl->encrypt.chacha, out,
  11568. input, msgLen)) != 0) {
  11569. ForceZero(poly, sizeof(poly));
  11570. return ret;
  11571. }
  11572. /* get the poly1305 tag using either old padding scheme or more recent */
  11573. if (ssl->options.oldPoly != 0) {
  11574. if ((ret = Poly1305TagOld(ssl, add, (const byte* )out,
  11575. poly, sz, tag)) != 0) {
  11576. ForceZero(poly, sizeof(poly));
  11577. return ret;
  11578. }
  11579. }
  11580. else {
  11581. if ((ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly,
  11582. sizeof(poly))) != 0) {
  11583. ForceZero(poly, sizeof(poly));
  11584. return ret;
  11585. }
  11586. if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, add,
  11587. sizeof(add), out, msgLen, tag, sizeof(tag))) != 0) {
  11588. ForceZero(poly, sizeof(poly));
  11589. return ret;
  11590. }
  11591. }
  11592. ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
  11593. /* append tag to ciphertext */
  11594. XMEMCPY(out + msgLen, tag, sizeof(tag));
  11595. AeadIncrementExpIV(ssl);
  11596. #ifdef CHACHA_AEAD_TEST
  11597. printf("mac tag :\n");
  11598. for (i = 0; i < 16; i++) {
  11599. printf("%02x", tag[i]);
  11600. if ((i + 1) % 16 == 0)
  11601. printf("\n");
  11602. }
  11603. printf("\n\noutput after encrypt :\n");
  11604. for (i = 0; i < sz; i++) {
  11605. printf("%02x", out[i]);
  11606. if ((i + 1) % 16 == 0)
  11607. printf("\n");
  11608. }
  11609. printf("\n");
  11610. #endif
  11611. return ret;
  11612. }
  11613. /* When the flag oldPoly is not set this follows RFC7905. When oldPoly is set
  11614. * the implementation follows an older draft for creating the nonce and MAC.
  11615. * The flag oldPoly gets set automatically depending on what cipher suite was
  11616. * negotiated in the handshake. This is able to be done because the IDs for the
  11617. * cipher suites was updated in RFC7905 giving unique values for the older
  11618. * draft in comparison to the more recent RFC.
  11619. *
  11620. * ssl WOLFSSL structure to get cipher and TLS state from
  11621. * plain output buffer to hold decrypted data
  11622. * input data to decrypt
  11623. * sz size of input
  11624. *
  11625. * Return 0 on success negative values in error case
  11626. */
  11627. static int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input,
  11628. word16 sz)
  11629. {
  11630. byte add[AEAD_AUTH_DATA_SZ];
  11631. byte nonce[CHACHA20_NONCE_SZ];
  11632. byte tag[POLY1305_AUTH_SZ];
  11633. byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for mac */
  11634. int ret = 0;
  11635. int msgLen = (sz - ssl->specs.aead_mac_size);
  11636. #ifdef CHACHA_AEAD_TEST
  11637. int i;
  11638. printf("input before decrypt :\n");
  11639. for (i = 0; i < sz; i++) {
  11640. printf("%02x", input[i]);
  11641. if ((i + 1) % 16 == 0)
  11642. printf("\n");
  11643. }
  11644. printf("\n");
  11645. #endif
  11646. XMEMSET(tag, 0, sizeof(tag));
  11647. XMEMSET(poly, 0, sizeof(poly));
  11648. XMEMSET(nonce, 0, sizeof(nonce));
  11649. XMEMSET(add, 0, sizeof(add));
  11650. /* sequence number field is 64-bits */
  11651. WriteSEQ(ssl, PEER_ORDER, add);
  11652. if (ssl->options.oldPoly != 0) {
  11653. /* get nonce, SEQ should not be incremented again here */
  11654. XMEMCPY(nonce + CHACHA20_OLD_OFFSET, add, OPAQUE32_LEN * 2);
  11655. }
  11656. /* get AD info */
  11657. /* Store the type, version. */
  11658. add[AEAD_TYPE_OFFSET] = ssl->curRL.type;
  11659. add[AEAD_VMAJ_OFFSET] = ssl->curRL.pvMajor;
  11660. add[AEAD_VMIN_OFFSET] = ssl->curRL.pvMinor;
  11661. /* add TLS message size to additional data */
  11662. add[AEAD_AUTH_DATA_SZ - 2] = (msgLen >> 8) & 0xff;
  11663. add[AEAD_AUTH_DATA_SZ - 1] = msgLen & 0xff;
  11664. #ifdef CHACHA_AEAD_TEST
  11665. printf("Decrypt Additional : ");
  11666. for (i = 0; i < AEAD_AUTH_DATA_SZ; i++) {
  11667. printf("%02x", add[i]);
  11668. }
  11669. printf("\n\n");
  11670. #endif
  11671. if (ssl->options.oldPoly == 0) {
  11672. /* nonce is formed by 4 0x00 byte padded to the left followed by 8 byte
  11673. * record sequence number XORed with client_write_IV/server_write_IV */
  11674. XMEMCPY(nonce, ssl->keys.aead_dec_imp_IV, CHACHA20_IMP_IV_SZ);
  11675. nonce[4] ^= add[0];
  11676. nonce[5] ^= add[1];
  11677. nonce[6] ^= add[2];
  11678. nonce[7] ^= add[3];
  11679. nonce[8] ^= add[4];
  11680. nonce[9] ^= add[5];
  11681. nonce[10] ^= add[6];
  11682. nonce[11] ^= add[7];
  11683. }
  11684. /* set nonce and get poly1305 key */
  11685. if ((ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 0)) != 0) {
  11686. ForceZero(nonce, CHACHA20_NONCE_SZ);
  11687. return ret;
  11688. }
  11689. /* use chacha20 keystream to get poly1305 key for tag */
  11690. if ((ret = wc_Chacha_Process(ssl->decrypt.chacha, poly,
  11691. poly, sizeof(poly))) != 0) {
  11692. ForceZero(nonce, CHACHA20_NONCE_SZ);
  11693. return ret;
  11694. }
  11695. /* set counter after getting poly1305 key */
  11696. if ((ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 1)) != 0) {
  11697. ForceZero(nonce, CHACHA20_NONCE_SZ);
  11698. return ret;
  11699. }
  11700. ForceZero(nonce, CHACHA20_NONCE_SZ); /* done with nonce, clear it */
  11701. /* get the tag using Poly1305 */
  11702. if (ssl->options.oldPoly != 0) {
  11703. if ((ret = Poly1305TagOld(ssl, add, input, poly, sz, tag)) != 0) {
  11704. ForceZero(poly, sizeof(poly));
  11705. return ret;
  11706. }
  11707. }
  11708. else {
  11709. if ((ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly,
  11710. sizeof(poly))) != 0) {
  11711. ForceZero(poly, sizeof(poly));
  11712. return ret;
  11713. }
  11714. if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, add,
  11715. sizeof(add), (byte*)input, msgLen, tag, sizeof(tag))) != 0) {
  11716. ForceZero(poly, sizeof(poly));
  11717. return ret;
  11718. }
  11719. }
  11720. ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
  11721. /* check tag sent along with packet */
  11722. if (ConstantCompare(input + msgLen, tag, ssl->specs.aead_mac_size) != 0) {
  11723. WOLFSSL_MSG("MAC did not match");
  11724. if (!ssl->options.dtls)
  11725. SendAlert(ssl, alert_fatal, bad_record_mac);
  11726. return VERIFY_MAC_ERROR;
  11727. }
  11728. /* if the tag was good decrypt message */
  11729. if ((ret = wc_Chacha_Process(ssl->decrypt.chacha, plain,
  11730. input, msgLen)) != 0)
  11731. return ret;
  11732. #ifdef CHACHA_AEAD_TEST
  11733. printf("plain after decrypt :\n");
  11734. for (i = 0; i < sz; i++) {
  11735. printf("%02x", plain[i]);
  11736. if ((i + 1) % 16 == 0)
  11737. printf("\n");
  11738. }
  11739. printf("\n");
  11740. #endif
  11741. return ret;
  11742. }
  11743. #endif /* HAVE_CHACHA && HAVE_POLY1305 */
  11744. #endif /* HAVE_AEAD */
  11745. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
  11746. #if !defined(NO_GCM_ENCRYPT_EXTRA) && \
  11747. ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
  11748. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
  11749. /* The following type is used to share code between AES-GCM and AES-CCM. */
  11750. typedef int (*AesAuthEncryptFunc)(Aes* aes, byte* out,
  11751. const byte* in, word32 sz,
  11752. byte* iv, word32 ivSz,
  11753. byte* authTag, word32 authTagSz,
  11754. const byte* authIn, word32 authInSz);
  11755. #define AES_AUTH_ENCRYPT_FUNC AesAuthEncryptFunc
  11756. #define AES_GCM_ENCRYPT wc_AesGcmEncrypt_ex
  11757. #define AES_CCM_ENCRYPT wc_AesCcmEncrypt_ex
  11758. #else
  11759. #define AES_AUTH_ENCRYPT_FUNC wc_AesAuthEncryptFunc
  11760. #define AES_GCM_ENCRYPT wc_AesGcmEncrypt
  11761. #define AES_CCM_ENCRYPT wc_AesCcmEncrypt
  11762. #endif
  11763. #endif
  11764. static WC_INLINE int EncryptDo(WOLFSSL* ssl, byte* out, const byte* input,
  11765. word16 sz, int asyncOkay)
  11766. {
  11767. int ret = 0;
  11768. #ifdef WOLFSSL_ASYNC_CRYPT
  11769. WC_ASYNC_DEV* asyncDev = NULL;
  11770. word32 event_flags = WC_ASYNC_FLAG_CALL_AGAIN;
  11771. #else
  11772. (void)asyncOkay;
  11773. #endif
  11774. (void)out;
  11775. (void)input;
  11776. (void)sz;
  11777. switch (ssl->specs.bulk_cipher_algorithm) {
  11778. #ifdef BUILD_ARC4
  11779. case wolfssl_rc4:
  11780. wc_Arc4Process(ssl->encrypt.arc4, out, input, sz);
  11781. break;
  11782. #endif
  11783. #ifdef BUILD_DES3
  11784. case wolfssl_triple_des:
  11785. #ifdef WOLFSSL_ASYNC_CRYPT
  11786. /* initialize event */
  11787. asyncDev = &ssl->encrypt.des3->asyncDev;
  11788. ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
  11789. if (ret != 0)
  11790. break;
  11791. #endif
  11792. ret = wc_Des3_CbcEncrypt(ssl->encrypt.des3, out, input, sz);
  11793. #ifdef WOLFSSL_ASYNC_CRYPT
  11794. if (ret == WC_PENDING_E && asyncOkay) {
  11795. ret = wolfSSL_AsyncPush(ssl, asyncDev);
  11796. }
  11797. #endif
  11798. break;
  11799. #endif
  11800. #if defined(BUILD_AES) && defined(HAVE_AES_CBC)
  11801. case wolfssl_aes:
  11802. #ifdef WOLFSSL_ASYNC_CRYPT
  11803. /* initialize event */
  11804. asyncDev = &ssl->encrypt.aes->asyncDev;
  11805. ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
  11806. if (ret != 0)
  11807. break;
  11808. #endif
  11809. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && \
  11810. !defined(NO_WOLFSSL_RENESAS_TSIP_TLS_SESSION)
  11811. if (tsip_useable(ssl)) {
  11812. ret = wc_tsip_AesCbcEncrypt(ssl->encrypt.aes, out, input, sz);
  11813. } else
  11814. #endif
  11815. ret = wc_AesCbcEncrypt(ssl->encrypt.aes, out, input, sz);
  11816. #ifdef WOLFSSL_ASYNC_CRYPT
  11817. if (ret == WC_PENDING_E && asyncOkay) {
  11818. ret = wolfSSL_AsyncPush(ssl, asyncDev);
  11819. }
  11820. #endif
  11821. break;
  11822. #endif
  11823. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
  11824. case wolfssl_aes_gcm:
  11825. case wolfssl_aes_ccm:/* GCM AEAD macros use same size as CCM */
  11826. {
  11827. AES_AUTH_ENCRYPT_FUNC aes_auth_fn;
  11828. const byte* additionalSrc;
  11829. #ifdef WOLFSSL_ASYNC_CRYPT
  11830. /* initialize event */
  11831. asyncDev = &ssl->encrypt.aes->asyncDev;
  11832. ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
  11833. if (ret != 0)
  11834. break;
  11835. #endif
  11836. #if defined(BUILD_AESGCM) && defined(HAVE_AESCCM)
  11837. aes_auth_fn = (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm)
  11838. ? AES_GCM_ENCRYPT : AES_CCM_ENCRYPT;
  11839. #elif defined(BUILD_AESGCM)
  11840. aes_auth_fn = AES_GCM_ENCRYPT;
  11841. #else
  11842. aes_auth_fn = AES_CCM_ENCRYPT;
  11843. #endif
  11844. additionalSrc = input - 5;
  11845. XMEMSET(ssl->encrypt.additional, 0, AEAD_AUTH_DATA_SZ);
  11846. /* sequence number field is 64-bits */
  11847. WriteSEQ(ssl, CUR_ORDER, ssl->encrypt.additional);
  11848. /* Store the type, version. Unfortunately, they are in
  11849. * the input buffer ahead of the plaintext. */
  11850. #ifdef WOLFSSL_DTLS
  11851. if (ssl->options.dtls) {
  11852. additionalSrc -= DTLS_HANDSHAKE_EXTRA;
  11853. }
  11854. #endif
  11855. XMEMCPY(ssl->encrypt.additional + AEAD_TYPE_OFFSET,
  11856. additionalSrc, 3);
  11857. /* Store the length of the plain text minus the explicit
  11858. * IV length minus the authentication tag size. */
  11859. c16toa(sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  11860. ssl->encrypt.additional + AEAD_LEN_OFFSET);
  11861. #if !defined(NO_PUBLIC_GCM_SET_IV) && \
  11862. ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
  11863. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
  11864. XMEMCPY(ssl->encrypt.nonce,
  11865. ssl->keys.aead_enc_imp_IV, AESGCM_IMP_IV_SZ);
  11866. XMEMCPY(ssl->encrypt.nonce + AESGCM_IMP_IV_SZ,
  11867. ssl->keys.aead_exp_IV, AESGCM_EXP_IV_SZ);
  11868. #endif
  11869. ret = aes_auth_fn(ssl->encrypt.aes,
  11870. out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ,
  11871. sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  11872. ssl->encrypt.nonce, AESGCM_NONCE_SZ,
  11873. out + sz - ssl->specs.aead_mac_size,
  11874. ssl->specs.aead_mac_size,
  11875. ssl->encrypt.additional, AEAD_AUTH_DATA_SZ);
  11876. #ifdef WOLFSSL_ASYNC_CRYPT
  11877. if (ret == WC_PENDING_E && asyncOkay) {
  11878. ret = wolfSSL_AsyncPush(ssl, asyncDev);
  11879. }
  11880. #endif
  11881. #if !defined(NO_PUBLIC_GCM_SET_IV) && \
  11882. ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
  11883. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
  11884. XMEMCPY(out,
  11885. ssl->encrypt.nonce + AESGCM_IMP_IV_SZ, AESGCM_EXP_IV_SZ);
  11886. #endif
  11887. }
  11888. break;
  11889. #endif /* BUILD_AESGCM || HAVE_AESCCM */
  11890. #ifdef HAVE_CAMELLIA
  11891. case wolfssl_camellia:
  11892. ret = wc_CamelliaCbcEncrypt(ssl->encrypt.cam, out, input, sz);
  11893. break;
  11894. #endif
  11895. #ifdef HAVE_HC128
  11896. case wolfssl_hc128:
  11897. ret = wc_Hc128_Process(ssl->encrypt.hc128, out, input, sz);
  11898. break;
  11899. #endif
  11900. #ifdef BUILD_RABBIT
  11901. case wolfssl_rabbit:
  11902. ret = wc_RabbitProcess(ssl->encrypt.rabbit, out, input, sz);
  11903. break;
  11904. #endif
  11905. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  11906. case wolfssl_chacha:
  11907. ret = ChachaAEADEncrypt(ssl, out, input, sz);
  11908. break;
  11909. #endif
  11910. #ifdef HAVE_NULL_CIPHER
  11911. case wolfssl_cipher_null:
  11912. if (input != out) {
  11913. XMEMMOVE(out, input, sz);
  11914. }
  11915. break;
  11916. #endif
  11917. #ifdef HAVE_IDEA
  11918. case wolfssl_idea:
  11919. ret = wc_IdeaCbcEncrypt(ssl->encrypt.idea, out, input, sz);
  11920. break;
  11921. #endif
  11922. default:
  11923. WOLFSSL_MSG("wolfSSL Encrypt programming error");
  11924. ret = ENCRYPT_ERROR;
  11925. }
  11926. #ifdef WOLFSSL_ASYNC_CRYPT
  11927. /* if async is not okay, then block */
  11928. if (ret == WC_PENDING_E && !asyncOkay) {
  11929. ret = wc_AsyncWait(ret, asyncDev, event_flags);
  11930. }
  11931. #endif
  11932. return ret;
  11933. }
  11934. static WC_INLINE int Encrypt(WOLFSSL* ssl, byte* out, const byte* input, word16 sz,
  11935. int asyncOkay)
  11936. {
  11937. int ret = 0;
  11938. #ifdef WOLFSSL_ASYNC_CRYPT
  11939. if (ssl->error == WC_PENDING_E) {
  11940. ssl->error = 0; /* clear async */
  11941. }
  11942. #endif
  11943. switch (ssl->encrypt.state) {
  11944. case CIPHER_STATE_BEGIN:
  11945. {
  11946. if (ssl->encrypt.setup == 0) {
  11947. WOLFSSL_MSG("Encrypt ciphers not setup");
  11948. return ENCRYPT_ERROR;
  11949. }
  11950. #ifdef HAVE_FUZZER
  11951. if (ssl->fuzzerCb)
  11952. ssl->fuzzerCb(ssl, input, sz, FUZZ_ENCRYPT, ssl->fuzzerCtx);
  11953. #endif
  11954. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
  11955. /* make sure AES GCM/CCM memory is allocated */
  11956. /* free for these happens in FreeCiphers */
  11957. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
  11958. ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
  11959. /* make sure auth iv and auth are allocated */
  11960. if (ssl->encrypt.additional == NULL)
  11961. ssl->encrypt.additional = (byte*)XMALLOC(AEAD_AUTH_DATA_SZ,
  11962. ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  11963. if (ssl->encrypt.nonce == NULL)
  11964. ssl->encrypt.nonce = (byte*)XMALLOC(AESGCM_NONCE_SZ,
  11965. ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  11966. if (ssl->encrypt.additional == NULL ||
  11967. ssl->encrypt.nonce == NULL) {
  11968. return MEMORY_E;
  11969. }
  11970. }
  11971. #endif /* BUILD_AESGCM || HAVE_AESCCM */
  11972. /* Advance state and proceed */
  11973. ssl->encrypt.state = CIPHER_STATE_DO;
  11974. }
  11975. FALL_THROUGH;
  11976. case CIPHER_STATE_DO:
  11977. {
  11978. ret = EncryptDo(ssl, out, input, sz, asyncOkay);
  11979. /* Advance state */
  11980. ssl->encrypt.state = CIPHER_STATE_END;
  11981. #ifdef WOLFSSL_ASYNC_CRYPT
  11982. /* If pending, then leave and return will resume below */
  11983. if (ret == WC_PENDING_E) {
  11984. return ret;
  11985. }
  11986. #endif
  11987. }
  11988. FALL_THROUGH;
  11989. case CIPHER_STATE_END:
  11990. {
  11991. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
  11992. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
  11993. ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm)
  11994. {
  11995. /* finalize authentication cipher */
  11996. #if !defined(NO_PUBLIC_GCM_SET_IV) && \
  11997. ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
  11998. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
  11999. AeadIncrementExpIV(ssl);
  12000. #endif
  12001. if (ssl->encrypt.nonce)
  12002. ForceZero(ssl->encrypt.nonce, AESGCM_NONCE_SZ);
  12003. }
  12004. #endif /* BUILD_AESGCM || HAVE_AESCCM */
  12005. break;
  12006. }
  12007. }
  12008. /* Reset state */
  12009. ssl->encrypt.state = CIPHER_STATE_BEGIN;
  12010. return ret;
  12011. }
  12012. static WC_INLINE int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input,
  12013. word16 sz)
  12014. {
  12015. int ret = 0;
  12016. (void)plain;
  12017. (void)input;
  12018. (void)sz;
  12019. switch (ssl->specs.bulk_cipher_algorithm)
  12020. {
  12021. #ifdef BUILD_ARC4
  12022. case wolfssl_rc4:
  12023. wc_Arc4Process(ssl->decrypt.arc4, plain, input, sz);
  12024. break;
  12025. #endif
  12026. #ifdef BUILD_DES3
  12027. case wolfssl_triple_des:
  12028. #ifdef WOLFSSL_ASYNC_CRYPT
  12029. /* initialize event */
  12030. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.des3->asyncDev,
  12031. WC_ASYNC_FLAG_CALL_AGAIN);
  12032. if (ret != 0)
  12033. break;
  12034. #endif
  12035. ret = wc_Des3_CbcDecrypt(ssl->decrypt.des3, plain, input, sz);
  12036. #ifdef WOLFSSL_ASYNC_CRYPT
  12037. if (ret == WC_PENDING_E) {
  12038. ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.des3->asyncDev);
  12039. }
  12040. #endif
  12041. break;
  12042. #endif
  12043. #if defined(BUILD_AES) && defined(HAVE_AES_CBC)
  12044. case wolfssl_aes:
  12045. #ifdef WOLFSSL_ASYNC_CRYPT
  12046. /* initialize event */
  12047. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
  12048. WC_ASYNC_FLAG_CALL_AGAIN);
  12049. if (ret != 0)
  12050. break;
  12051. #endif
  12052. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && \
  12053. !defined(NO_WOLFSSL_RENESAS_TSIP_TLS_SESSION)
  12054. if (tsip_useable(ssl)) {
  12055. ret = wc_tsip_AesCbcDecrypt(ssl->decrypt.aes, plain, input, sz);
  12056. } else
  12057. #endif
  12058. ret = wc_AesCbcDecrypt(ssl->decrypt.aes, plain, input, sz);
  12059. #ifdef WOLFSSL_ASYNC_CRYPT
  12060. if (ret == WC_PENDING_E) {
  12061. ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev);
  12062. }
  12063. #endif
  12064. break;
  12065. #endif
  12066. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
  12067. case wolfssl_aes_gcm:
  12068. case wolfssl_aes_ccm: /* GCM AEAD macros use same size as CCM */
  12069. {
  12070. wc_AesAuthDecryptFunc aes_auth_fn;
  12071. #ifdef WOLFSSL_ASYNC_CRYPT
  12072. /* initialize event */
  12073. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
  12074. WC_ASYNC_FLAG_CALL_AGAIN);
  12075. if (ret != 0)
  12076. break;
  12077. #endif
  12078. #if defined(BUILD_AESGCM) && defined(HAVE_AESCCM)
  12079. aes_auth_fn = (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm)
  12080. ? wc_AesGcmDecrypt : wc_AesCcmDecrypt;
  12081. #elif defined(BUILD_AESGCM)
  12082. aes_auth_fn = wc_AesGcmDecrypt;
  12083. #else
  12084. aes_auth_fn = wc_AesCcmDecrypt;
  12085. #endif
  12086. XMEMSET(ssl->decrypt.additional, 0, AEAD_AUTH_DATA_SZ);
  12087. /* sequence number field is 64-bits */
  12088. WriteSEQ(ssl, PEER_ORDER, ssl->decrypt.additional);
  12089. ssl->decrypt.additional[AEAD_TYPE_OFFSET] = ssl->curRL.type;
  12090. ssl->decrypt.additional[AEAD_VMAJ_OFFSET] = ssl->curRL.pvMajor;
  12091. ssl->decrypt.additional[AEAD_VMIN_OFFSET] = ssl->curRL.pvMinor;
  12092. c16toa(sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  12093. ssl->decrypt.additional + AEAD_LEN_OFFSET);
  12094. XMEMCPY(ssl->decrypt.nonce, ssl->keys.aead_dec_imp_IV,
  12095. AESGCM_IMP_IV_SZ);
  12096. XMEMCPY(ssl->decrypt.nonce + AESGCM_IMP_IV_SZ, input,
  12097. AESGCM_EXP_IV_SZ);
  12098. if ((ret = aes_auth_fn(ssl->decrypt.aes,
  12099. plain + AESGCM_EXP_IV_SZ,
  12100. input + AESGCM_EXP_IV_SZ,
  12101. sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  12102. ssl->decrypt.nonce, AESGCM_NONCE_SZ,
  12103. input + sz - ssl->specs.aead_mac_size,
  12104. ssl->specs.aead_mac_size,
  12105. ssl->decrypt.additional, AEAD_AUTH_DATA_SZ)) < 0) {
  12106. #ifdef WOLFSSL_ASYNC_CRYPT
  12107. if (ret == WC_PENDING_E) {
  12108. ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev);
  12109. }
  12110. #endif
  12111. }
  12112. }
  12113. break;
  12114. #endif /* BUILD_AESGCM || HAVE_AESCCM */
  12115. #ifdef HAVE_CAMELLIA
  12116. case wolfssl_camellia:
  12117. ret = wc_CamelliaCbcDecrypt(ssl->decrypt.cam, plain, input, sz);
  12118. break;
  12119. #endif
  12120. #ifdef HAVE_HC128
  12121. case wolfssl_hc128:
  12122. ret = wc_Hc128_Process(ssl->decrypt.hc128, plain, input, sz);
  12123. break;
  12124. #endif
  12125. #ifdef BUILD_RABBIT
  12126. case wolfssl_rabbit:
  12127. ret = wc_RabbitProcess(ssl->decrypt.rabbit, plain, input, sz);
  12128. break;
  12129. #endif
  12130. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  12131. case wolfssl_chacha:
  12132. ret = ChachaAEADDecrypt(ssl, plain, input, sz);
  12133. break;
  12134. #endif
  12135. #ifdef HAVE_NULL_CIPHER
  12136. case wolfssl_cipher_null:
  12137. if (input != plain) {
  12138. XMEMMOVE(plain, input, sz);
  12139. }
  12140. break;
  12141. #endif
  12142. #ifdef HAVE_IDEA
  12143. case wolfssl_idea:
  12144. ret = wc_IdeaCbcDecrypt(ssl->decrypt.idea, plain, input, sz);
  12145. break;
  12146. #endif
  12147. default:
  12148. WOLFSSL_MSG("wolfSSL Decrypt programming error");
  12149. ret = DECRYPT_ERROR;
  12150. }
  12151. return ret;
  12152. }
  12153. static WC_INLINE int Decrypt(WOLFSSL* ssl, byte* plain, const byte* input,
  12154. word16 sz)
  12155. {
  12156. int ret = 0;
  12157. #ifdef WOLFSSL_ASYNC_CRYPT
  12158. ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state);
  12159. if (ret != WC_NOT_PENDING_E) {
  12160. /* check for still pending */
  12161. if (ret == WC_PENDING_E)
  12162. return ret;
  12163. ssl->error = 0; /* clear async */
  12164. /* let failures through so CIPHER_STATE_END logic is run */
  12165. }
  12166. else
  12167. #endif
  12168. {
  12169. /* Reset state */
  12170. ret = 0;
  12171. ssl->decrypt.state = CIPHER_STATE_BEGIN;
  12172. }
  12173. switch (ssl->decrypt.state) {
  12174. case CIPHER_STATE_BEGIN:
  12175. {
  12176. if (ssl->decrypt.setup == 0) {
  12177. WOLFSSL_MSG("Decrypt ciphers not setup");
  12178. return DECRYPT_ERROR;
  12179. }
  12180. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
  12181. /* make sure AES GCM/CCM memory is allocated */
  12182. /* free for these happens in FreeCiphers */
  12183. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
  12184. ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
  12185. /* make sure auth iv and auth are allocated */
  12186. if (ssl->decrypt.additional == NULL)
  12187. ssl->decrypt.additional = (byte*)XMALLOC(AEAD_AUTH_DATA_SZ,
  12188. ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  12189. if (ssl->decrypt.nonce == NULL)
  12190. ssl->decrypt.nonce = (byte*)XMALLOC(AESGCM_NONCE_SZ,
  12191. ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  12192. if (ssl->decrypt.additional == NULL ||
  12193. ssl->decrypt.nonce == NULL) {
  12194. return MEMORY_E;
  12195. }
  12196. }
  12197. #endif /* BUILD_AESGCM || HAVE_AESCCM */
  12198. /* Advance state and proceed */
  12199. ssl->decrypt.state = CIPHER_STATE_DO;
  12200. }
  12201. FALL_THROUGH;
  12202. case CIPHER_STATE_DO:
  12203. {
  12204. ret = DecryptDo(ssl, plain, input, sz);
  12205. /* Advance state */
  12206. ssl->decrypt.state = CIPHER_STATE_END;
  12207. #ifdef WOLFSSL_ASYNC_CRYPT
  12208. /* If pending, leave and return below */
  12209. if (ret == WC_PENDING_E) {
  12210. return ret;
  12211. }
  12212. #endif
  12213. }
  12214. FALL_THROUGH;
  12215. case CIPHER_STATE_END:
  12216. {
  12217. #if defined(BUILD_AESGCM) || defined(HAVE_AESCCM)
  12218. /* make sure AES GCM/CCM nonce is cleared */
  12219. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
  12220. ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
  12221. if (ssl->decrypt.nonce)
  12222. ForceZero(ssl->decrypt.nonce, AESGCM_NONCE_SZ);
  12223. if (ret < 0)
  12224. ret = VERIFY_MAC_ERROR;
  12225. }
  12226. #endif /* BUILD_AESGCM || HAVE_AESCCM */
  12227. break;
  12228. }
  12229. }
  12230. /* Reset state */
  12231. ssl->decrypt.state = CIPHER_STATE_BEGIN;
  12232. /* handle mac error case */
  12233. if (ret == VERIFY_MAC_ERROR) {
  12234. if (!ssl->options.dtls)
  12235. SendAlert(ssl, alert_fatal, bad_record_mac);
  12236. #ifdef WOLFSSL_DTLS_DROP_STATS
  12237. ssl->macDropCount++;
  12238. #endif /* WOLFSSL_DTLS_DROP_STATS */
  12239. }
  12240. return ret;
  12241. }
  12242. #endif /* !WOLFSSL_NO_TLS12 */
  12243. /* Check conditions for a cipher to have an explicit IV.
  12244. *
  12245. * ssl The SSL/TLS object.
  12246. * returns 1 if the cipher in use has an explicit IV and 0 otherwise.
  12247. */
  12248. static WC_INLINE int CipherHasExpIV(WOLFSSL *ssl)
  12249. {
  12250. #ifdef WOLFSSL_TLS13
  12251. if (ssl->options.tls1_3)
  12252. return 0;
  12253. #endif
  12254. return (ssl->specs.cipher_type == aead) &&
  12255. (ssl->specs.bulk_cipher_algorithm != wolfssl_chacha);
  12256. }
  12257. /* check cipher text size for sanity */
  12258. static int SanityCheckCipherText(WOLFSSL* ssl, word32 encryptSz)
  12259. {
  12260. #ifdef HAVE_TRUNCATED_HMAC
  12261. word32 minLength = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  12262. : ssl->specs.hash_size;
  12263. #else
  12264. word32 minLength = ssl->specs.hash_size; /* covers stream */
  12265. #endif
  12266. #ifndef WOLFSSL_AEAD_ONLY
  12267. if (ssl->specs.cipher_type == block) {
  12268. #ifdef HAVE_ENCRYPT_THEN_MAC
  12269. if (ssl->options.startedETMRead) {
  12270. if ((encryptSz - MacSize(ssl)) % ssl->specs.block_size) {
  12271. WOLFSSL_MSG("Block ciphertext not block size");
  12272. return SANITY_CIPHER_E;
  12273. }
  12274. }
  12275. else
  12276. #endif
  12277. if (encryptSz % ssl->specs.block_size) {
  12278. WOLFSSL_MSG("Block ciphertext not block size");
  12279. return SANITY_CIPHER_E;
  12280. }
  12281. minLength++; /* pad byte */
  12282. if (ssl->specs.block_size > minLength)
  12283. minLength = ssl->specs.block_size;
  12284. if (ssl->options.tls1_1)
  12285. minLength += ssl->specs.block_size; /* explicit IV */
  12286. }
  12287. else
  12288. #endif
  12289. if (ssl->specs.cipher_type == aead) {
  12290. minLength = ssl->specs.aead_mac_size; /* authTag size */
  12291. if (CipherHasExpIV(ssl))
  12292. minLength += AESGCM_EXP_IV_SZ; /* explicit IV */
  12293. }
  12294. if (encryptSz < minLength) {
  12295. WOLFSSL_MSG("Ciphertext not minimum size");
  12296. return SANITY_CIPHER_E;
  12297. }
  12298. return 0;
  12299. }
  12300. #ifndef WOLFSSL_AEAD_ONLY
  12301. /* check all length bytes for the pad value, return 0 on success */
  12302. static int PadCheck(const byte* a, byte pad, int length)
  12303. {
  12304. int i;
  12305. int compareSum = 0;
  12306. for (i = 0; i < length; i++) {
  12307. compareSum |= a[i] ^ pad;
  12308. }
  12309. return compareSum;
  12310. }
  12311. /* Mask the padding bytes with the expected values.
  12312. * Constant time implementation - does maximum pad size possible.
  12313. *
  12314. * data Message data.
  12315. * sz Size of the message including MAC and padding and padding length.
  12316. * macSz Size of the MAC.
  12317. * returns 0 on success, otherwise failure.
  12318. */
  12319. static byte MaskPadding(const byte* data, int sz, int macSz)
  12320. {
  12321. int i;
  12322. int checkSz = sz - 1;
  12323. byte paddingSz = data[sz - 1];
  12324. byte mask;
  12325. byte good = ctMaskGT(paddingSz, sz - 1 - macSz);
  12326. if (checkSz > TLS_MAX_PAD_SZ)
  12327. checkSz = TLS_MAX_PAD_SZ;
  12328. for (i = 0; i < checkSz; i++) {
  12329. mask = ctMaskLTE(i, paddingSz);
  12330. good |= mask & (data[sz - 1 - i] ^ paddingSz);
  12331. }
  12332. return good;
  12333. }
  12334. /* Mask the MAC in the message with the MAC calculated.
  12335. * Constant time implementation - starts looking for MAC where maximum padding
  12336. * size has it.
  12337. *
  12338. * data Message data.
  12339. * sz Size of the message including MAC and padding and padding length.
  12340. * macSz Size of the MAC data.
  12341. * expMac Expected MAC value.
  12342. * returns 0 on success, otherwise failure.
  12343. */
  12344. static byte MaskMac(const byte* data, int sz, int macSz, byte* expMac)
  12345. {
  12346. int i, j;
  12347. unsigned char mac[WC_MAX_DIGEST_SIZE];
  12348. int scanStart = sz - 1 - TLS_MAX_PAD_SZ - macSz;
  12349. int macEnd = sz - 1 - data[sz - 1];
  12350. int macStart = macEnd - macSz;
  12351. int r = 0;
  12352. unsigned char started, notEnded;
  12353. unsigned char good = 0;
  12354. scanStart &= ctMaskIntGTE(scanStart, 0);
  12355. macStart &= ctMaskIntGTE(macStart, 0);
  12356. /* Div on Intel has different speeds depending on value.
  12357. * Use a bitwise AND or mod a specific value (converted to mul). */
  12358. if ((macSz & (macSz - 1)) == 0)
  12359. r = (macSz - (scanStart - macStart)) & (macSz - 1);
  12360. #ifndef NO_SHA
  12361. else if (macSz == WC_SHA_DIGEST_SIZE)
  12362. r = (macSz - (scanStart - macStart)) % WC_SHA_DIGEST_SIZE;
  12363. #endif
  12364. #ifdef WOLFSSL_SHA384
  12365. else if (macSz == WC_SHA384_DIGEST_SIZE)
  12366. r = (macSz - (scanStart - macStart)) % WC_SHA384_DIGEST_SIZE;
  12367. #endif
  12368. XMEMSET(mac, 0, macSz);
  12369. for (i = scanStart; i < sz; i += macSz) {
  12370. for (j = 0; j < macSz && j + i < sz; j++) {
  12371. started = ctMaskGTE(i + j, macStart);
  12372. notEnded = ctMaskLT(i + j, macEnd);
  12373. mac[j] |= started & notEnded & data[i + j];
  12374. }
  12375. }
  12376. if ((macSz & (macSz - 1)) == 0) {
  12377. for (i = 0; i < macSz; i++)
  12378. good |= expMac[i] ^ mac[(i + r) & (macSz - 1)];
  12379. }
  12380. #ifndef NO_SHA
  12381. else if (macSz == WC_SHA_DIGEST_SIZE) {
  12382. for (i = 0; i < macSz; i++)
  12383. good |= expMac[i] ^ mac[(i + r) % WC_SHA_DIGEST_SIZE];
  12384. }
  12385. #endif
  12386. #ifdef WOLFSSL_SHA384
  12387. else if (macSz == WC_SHA384_DIGEST_SIZE) {
  12388. for (i = 0; i < macSz; i++)
  12389. good |= expMac[i] ^ mac[(i + r) % WC_SHA384_DIGEST_SIZE];
  12390. }
  12391. #endif
  12392. return good;
  12393. }
  12394. /* timing resistant pad/verify check, return 0 on success */
  12395. int TimingPadVerify(WOLFSSL* ssl, const byte* input, int padLen, int macSz,
  12396. int pLen, int content)
  12397. {
  12398. byte verify[WC_MAX_DIGEST_SIZE];
  12399. byte good;
  12400. int ret = 0;
  12401. good = MaskPadding(input, pLen, macSz);
  12402. /* 4th argument has potential to underflow, ssl->hmac function should
  12403. * either increment the size by (macSz + padLen + 1) before use or check on
  12404. * the size to make sure is valid. */
  12405. ret = ssl->hmac(ssl, verify, input, pLen - macSz - padLen - 1, padLen,
  12406. content, 1);
  12407. good |= MaskMac(input, pLen, ssl->specs.hash_size, verify);
  12408. /* Non-zero on failure. */
  12409. good = (byte)~(word32)good;
  12410. good &= good >> 4;
  12411. good &= good >> 2;
  12412. good &= good >> 1;
  12413. /* Make ret negative on masking failure. */
  12414. ret -= 1 - good;
  12415. /* Treat any failure as verify MAC error. */
  12416. if (ret != 0)
  12417. ret = VERIFY_MAC_ERROR;
  12418. return ret;
  12419. }
  12420. #endif
  12421. int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx)
  12422. {
  12423. word32 msgSz = ssl->keys.encryptSz;
  12424. word32 idx = *inOutIdx;
  12425. int dataSz;
  12426. int ivExtra = 0;
  12427. byte* rawData = input + idx; /* keep current for hmac */
  12428. #ifdef HAVE_LIBZ
  12429. byte decomp[MAX_RECORD_SIZE + MAX_COMP_EXTRA];
  12430. #endif
  12431. #ifdef WOLFSSL_EARLY_DATA
  12432. if (ssl->options.tls1_3 && ssl->options.handShakeDone == 0) {
  12433. if (ssl->options.side == WOLFSSL_SERVER_END &&
  12434. ssl->earlyData != no_early_data &&
  12435. ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
  12436. ssl->earlyDataSz += ssl->curSize;
  12437. if (ssl->earlyDataSz <= ssl->options.maxEarlyDataSz) {
  12438. WOLFSSL_MSG("Ignoring EarlyData!");
  12439. *inOutIdx = ssl->buffers.inputBuffer.length;
  12440. return 0;
  12441. }
  12442. WOLFSSL_MSG("Too much EarlyData!");
  12443. }
  12444. }
  12445. #endif
  12446. if (ssl->options.handShakeDone == 0) {
  12447. WOLFSSL_MSG("Received App data before a handshake completed");
  12448. SendAlert(ssl, alert_fatal, unexpected_message);
  12449. return OUT_OF_ORDER_E;
  12450. }
  12451. #ifndef WOLFSSL_AEAD_ONLY
  12452. if (ssl->specs.cipher_type == block) {
  12453. if (ssl->options.tls1_1)
  12454. ivExtra = ssl->specs.block_size;
  12455. }
  12456. else
  12457. #endif
  12458. if (ssl->specs.cipher_type == aead) {
  12459. if (CipherHasExpIV(ssl))
  12460. ivExtra = AESGCM_EXP_IV_SZ;
  12461. }
  12462. dataSz = msgSz - ivExtra - ssl->keys.padSz;
  12463. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  12464. if (ssl->options.startedETMRead)
  12465. dataSz -= MacSize(ssl);
  12466. #endif
  12467. if (dataSz < 0) {
  12468. WOLFSSL_MSG("App data buffer error, malicious input?");
  12469. SendAlert(ssl, alert_fatal, unexpected_message);
  12470. return BUFFER_ERROR;
  12471. }
  12472. #ifdef WOLFSSL_EARLY_DATA
  12473. if (ssl->earlyData > early_data_ext) {
  12474. if (ssl->earlyDataSz + dataSz > ssl->options.maxEarlyDataSz) {
  12475. SendAlert(ssl, alert_fatal, unexpected_message);
  12476. return WOLFSSL_FATAL_ERROR;
  12477. }
  12478. ssl->earlyDataSz += dataSz;
  12479. }
  12480. #endif
  12481. /* read data */
  12482. if (dataSz) {
  12483. int rawSz = dataSz; /* keep raw size for idx adjustment */
  12484. #ifdef HAVE_LIBZ
  12485. if (ssl->options.usingCompression) {
  12486. dataSz = myDeCompress(ssl, rawData, dataSz, decomp, sizeof(decomp));
  12487. if (dataSz < 0) return dataSz;
  12488. }
  12489. #endif
  12490. idx += rawSz;
  12491. ssl->buffers.clearOutputBuffer.buffer = rawData;
  12492. ssl->buffers.clearOutputBuffer.length = dataSz;
  12493. }
  12494. idx += ssl->keys.padSz;
  12495. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  12496. if (ssl->options.startedETMRead)
  12497. idx += MacSize(ssl);
  12498. #endif
  12499. #ifdef HAVE_LIBZ
  12500. /* decompress could be bigger, overwrite after verify */
  12501. if (ssl->options.usingCompression)
  12502. XMEMMOVE(rawData, decomp, dataSz);
  12503. #endif
  12504. *inOutIdx = idx;
  12505. return 0;
  12506. }
  12507. /* process alert, return level */
  12508. static int DoAlert(WOLFSSL* ssl, byte* input, word32* inOutIdx, int* type,
  12509. word32 totalSz)
  12510. {
  12511. byte level;
  12512. byte code;
  12513. word32 dataSz = totalSz - *inOutIdx;
  12514. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  12515. if (ssl->hsInfoOn)
  12516. AddPacketName(ssl, "Alert");
  12517. if (ssl->toInfoOn)
  12518. /* add record header back on to info + alert bytes level/code */
  12519. AddPacketInfo(ssl, "Alert", alert, input + *inOutIdx -
  12520. RECORD_HEADER_SZ, RECORD_HEADER_SZ + ALERT_SIZE,
  12521. READ_PROTO, ssl->heap);
  12522. #endif
  12523. if (IsEncryptionOn(ssl, 0)) {
  12524. dataSz -= ssl->keys.padSz;
  12525. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  12526. if (ssl->options.startedETMRead)
  12527. dataSz -= MacSize(ssl);
  12528. #endif
  12529. }
  12530. /* make sure can read the message */
  12531. if (dataSz != ALERT_SIZE) {
  12532. #ifdef WOLFSSL_EXTRA_ALERTS
  12533. SendAlert(ssl, alert_fatal, unexpected_message);
  12534. #endif
  12535. return BUFFER_E;
  12536. }
  12537. level = input[(*inOutIdx)++];
  12538. code = input[(*inOutIdx)++];
  12539. ssl->alert_history.last_rx.code = code;
  12540. ssl->alert_history.last_rx.level = level;
  12541. *type = code;
  12542. if (level == alert_fatal) {
  12543. ssl->options.isClosed = 1; /* Don't send close_notify */
  12544. }
  12545. if (++ssl->options.alertCount >= WOLFSSL_ALERT_COUNT_MAX) {
  12546. WOLFSSL_MSG("Alert count exceeded");
  12547. #ifdef WOLFSSL_EXTRA_ALERTS
  12548. if (level != alert_warning || code != close_notify)
  12549. SendAlert(ssl, alert_fatal, unexpected_message);
  12550. #endif
  12551. return ALERT_COUNT_E;
  12552. }
  12553. WOLFSSL_MSG("Got alert");
  12554. if (*type == close_notify) {
  12555. WOLFSSL_MSG("\tclose notify");
  12556. ssl->options.closeNotify = 1;
  12557. }
  12558. #ifdef WOLFSSL_TLS13
  12559. if (*type == decode_error) {
  12560. WOLFSSL_MSG("\tdecode error");
  12561. }
  12562. if (*type == illegal_parameter) {
  12563. WOLFSSL_MSG("\tillegal parameter");
  12564. }
  12565. #endif
  12566. WOLFSSL_ERROR(*type);
  12567. if (IsEncryptionOn(ssl, 0)) {
  12568. *inOutIdx += ssl->keys.padSz;
  12569. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  12570. if (ssl->options.startedETMRead)
  12571. *inOutIdx += MacSize(ssl);
  12572. #endif
  12573. }
  12574. return level;
  12575. }
  12576. static int GetInputData(WOLFSSL *ssl, word32 size)
  12577. {
  12578. int in;
  12579. int inSz;
  12580. int maxLength;
  12581. int usedLength;
  12582. int dtlsExtra = 0;
  12583. /* check max input length */
  12584. usedLength = ssl->buffers.inputBuffer.length - ssl->buffers.inputBuffer.idx;
  12585. maxLength = ssl->buffers.inputBuffer.bufferSize - usedLength;
  12586. inSz = (int)(size - usedLength); /* from last partial read */
  12587. #ifdef WOLFSSL_DTLS
  12588. if (ssl->options.dtls) {
  12589. if (size < ssl->dtls_expected_rx)
  12590. dtlsExtra = (int)(ssl->dtls_expected_rx - size);
  12591. inSz = ssl->dtls_expected_rx;
  12592. }
  12593. #endif
  12594. /* check that no lengths or size values are negative */
  12595. if (usedLength < 0 || maxLength < 0 || inSz <= 0) {
  12596. return BUFFER_ERROR;
  12597. }
  12598. if (inSz > maxLength) {
  12599. if (GrowInputBuffer(ssl, size + dtlsExtra, usedLength) < 0)
  12600. return MEMORY_E;
  12601. }
  12602. /* Put buffer data at start if not there */
  12603. if (usedLength > 0 && ssl->buffers.inputBuffer.idx != 0)
  12604. XMEMMOVE(ssl->buffers.inputBuffer.buffer,
  12605. ssl->buffers.inputBuffer.buffer + ssl->buffers.inputBuffer.idx,
  12606. usedLength);
  12607. /* remove processed data */
  12608. ssl->buffers.inputBuffer.idx = 0;
  12609. ssl->buffers.inputBuffer.length = usedLength;
  12610. /* read data from network */
  12611. do {
  12612. in = wolfSSLReceive(ssl,
  12613. ssl->buffers.inputBuffer.buffer +
  12614. ssl->buffers.inputBuffer.length,
  12615. inSz);
  12616. if (in == WANT_READ)
  12617. return WANT_READ;
  12618. if (in < 0)
  12619. return SOCKET_ERROR_E;
  12620. if (in > inSz)
  12621. return RECV_OVERFLOW_E;
  12622. ssl->buffers.inputBuffer.length += in;
  12623. inSz -= in;
  12624. } while (ssl->buffers.inputBuffer.length < size);
  12625. #ifdef WOLFSSL_DEBUG_TLS
  12626. if (ssl->buffers.inputBuffer.idx == 0) {
  12627. WOLFSSL_MSG("Data received");
  12628. WOLFSSL_BUFFER(ssl->buffers.inputBuffer.buffer,
  12629. ssl->buffers.inputBuffer.length);
  12630. }
  12631. #endif
  12632. return 0;
  12633. }
  12634. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  12635. static WC_INLINE int VerifyMacEnc(WOLFSSL* ssl, const byte* input, word32 msgSz,
  12636. int content)
  12637. {
  12638. int ret;
  12639. #ifdef HAVE_TRUNCATED_HMAC
  12640. word32 digestSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  12641. : ssl->specs.hash_size;
  12642. #else
  12643. word32 digestSz = ssl->specs.hash_size;
  12644. #endif
  12645. byte verify[WC_MAX_DIGEST_SIZE];
  12646. WOLFSSL_MSG("Verify MAC of Encrypted Data");
  12647. if (msgSz < digestSz) {
  12648. return VERIFY_MAC_ERROR;
  12649. }
  12650. ret = ssl->hmac(ssl, verify, input, msgSz - digestSz, -1, content, 1);
  12651. ret |= ConstantCompare(verify, input + msgSz - digestSz, digestSz);
  12652. if (ret != 0) {
  12653. return VERIFY_MAC_ERROR;
  12654. }
  12655. return 0;
  12656. }
  12657. #endif
  12658. static WC_INLINE int VerifyMac(WOLFSSL* ssl, const byte* input, word32 msgSz,
  12659. int content, word32* padSz)
  12660. {
  12661. #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
  12662. int ivExtra = 0;
  12663. int ret;
  12664. word32 pad = 0;
  12665. word32 padByte = 0;
  12666. #ifdef HAVE_TRUNCATED_HMAC
  12667. word32 digestSz = ssl->truncated_hmac ? (byte)TRUNCATED_HMAC_SZ
  12668. : ssl->specs.hash_size;
  12669. #else
  12670. word32 digestSz = ssl->specs.hash_size;
  12671. #endif
  12672. byte verify[WC_MAX_DIGEST_SIZE];
  12673. if (ssl->specs.cipher_type == block) {
  12674. if (ssl->options.tls1_1)
  12675. ivExtra = ssl->specs.block_size;
  12676. pad = *(input + msgSz - ivExtra - 1);
  12677. padByte = 1;
  12678. if (ssl->options.tls) {
  12679. ret = TimingPadVerify(ssl, input, pad, digestSz, msgSz - ivExtra,
  12680. content);
  12681. if (ret != 0)
  12682. return ret;
  12683. }
  12684. else { /* sslv3, some implementations have bad padding, but don't
  12685. * allow bad read */
  12686. int badPadLen = 0;
  12687. byte dmy[sizeof(WOLFSSL) >= MAX_PAD_SIZE ? 1 : MAX_PAD_SIZE] = {0};
  12688. byte* dummy = sizeof(dmy) < MAX_PAD_SIZE ? (byte*) ssl : dmy;
  12689. (void)dmy;
  12690. if (pad > (msgSz - digestSz - 1)) {
  12691. WOLFSSL_MSG("Plain Len not long enough for pad/mac");
  12692. pad = 0; /* no bad read */
  12693. badPadLen = 1;
  12694. }
  12695. PadCheck(dummy, (byte)pad, MAX_PAD_SIZE); /* timing only */
  12696. ret = ssl->hmac(ssl, verify, input, msgSz - digestSz - pad - 1, pad,
  12697. content, 1);
  12698. if (ConstantCompare(verify, input + msgSz - digestSz - pad - 1,
  12699. digestSz) != 0)
  12700. return VERIFY_MAC_ERROR;
  12701. if (ret != 0 || badPadLen)
  12702. return VERIFY_MAC_ERROR;
  12703. }
  12704. }
  12705. else if (ssl->specs.cipher_type == stream) {
  12706. ret = ssl->hmac(ssl, verify, input, msgSz - digestSz, -1, content, 1);
  12707. if (ConstantCompare(verify, input + msgSz - digestSz, digestSz) != 0){
  12708. return VERIFY_MAC_ERROR;
  12709. }
  12710. if (ret != 0)
  12711. return VERIFY_MAC_ERROR;
  12712. }
  12713. #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
  12714. if (ssl->specs.cipher_type == aead) {
  12715. *padSz = ssl->specs.aead_mac_size;
  12716. }
  12717. #if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
  12718. else {
  12719. *padSz = digestSz + pad + padByte;
  12720. }
  12721. #endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
  12722. (void)input;
  12723. (void)msgSz;
  12724. (void)content;
  12725. return 0;
  12726. }
  12727. /* process input requests, return 0 is done, 1 is call again to complete, and
  12728. negative number is error */
  12729. int ProcessReply(WOLFSSL* ssl)
  12730. {
  12731. int ret = 0, type, readSz;
  12732. int atomicUser = 0;
  12733. word32 startIdx = 0;
  12734. #if defined(WOLFSSL_DTLS)
  12735. int used;
  12736. #endif
  12737. #ifdef ATOMIC_USER
  12738. if (ssl->ctx->DecryptVerifyCb)
  12739. atomicUser = 1;
  12740. #endif
  12741. if (ssl->error != 0 && ssl->error != WANT_READ && ssl->error != WANT_WRITE
  12742. #ifdef WOLFSSL_ASYNC_CRYPT
  12743. && ssl->error != WC_PENDING_E
  12744. #endif
  12745. #ifdef WOLFSSL_NONBLOCK_OCSP
  12746. && ssl->error != OCSP_WANT_READ
  12747. #endif
  12748. ) {
  12749. WOLFSSL_MSG("ProcessReply retry in error state, not allowed");
  12750. return ssl->error;
  12751. }
  12752. for (;;) {
  12753. switch (ssl->options.processReply) {
  12754. /* in the WOLFSSL_SERVER case, get the first byte for detecting
  12755. * old client hello */
  12756. case doProcessInit:
  12757. readSz = RECORD_HEADER_SZ;
  12758. #ifdef WOLFSSL_DTLS
  12759. if (ssl->options.dtls)
  12760. readSz = DTLS_RECORD_HEADER_SZ;
  12761. #endif
  12762. /* get header or return error */
  12763. if (!ssl->options.dtls) {
  12764. if ((ret = GetInputData(ssl, readSz)) < 0)
  12765. return ret;
  12766. } else {
  12767. #ifdef WOLFSSL_DTLS
  12768. /* read ahead may already have header */
  12769. used = ssl->buffers.inputBuffer.length -
  12770. ssl->buffers.inputBuffer.idx;
  12771. if (used < readSz) {
  12772. if ((ret = GetInputData(ssl, readSz)) < 0)
  12773. return ret;
  12774. }
  12775. #endif
  12776. }
  12777. #ifdef OLD_HELLO_ALLOWED
  12778. /* see if sending SSLv2 client hello */
  12779. if ( ssl->options.side == WOLFSSL_SERVER_END &&
  12780. ssl->options.clientState == NULL_STATE &&
  12781. ssl->buffers.inputBuffer.buffer[ssl->buffers.inputBuffer.idx]
  12782. != handshake) {
  12783. byte b0, b1;
  12784. ssl->options.processReply = runProcessOldClientHello;
  12785. /* sanity checks before getting size at front */
  12786. if (ssl->buffers.inputBuffer.buffer[
  12787. ssl->buffers.inputBuffer.idx + OPAQUE16_LEN] != OLD_HELLO_ID) {
  12788. WOLFSSL_MSG("Not a valid old client hello");
  12789. return PARSE_ERROR;
  12790. }
  12791. if (ssl->buffers.inputBuffer.buffer[
  12792. ssl->buffers.inputBuffer.idx + OPAQUE24_LEN] != SSLv3_MAJOR &&
  12793. ssl->buffers.inputBuffer.buffer[
  12794. ssl->buffers.inputBuffer.idx + OPAQUE24_LEN] != DTLS_MAJOR) {
  12795. WOLFSSL_MSG("Not a valid version in old client hello");
  12796. return PARSE_ERROR;
  12797. }
  12798. /* how many bytes need ProcessOldClientHello */
  12799. b0 =
  12800. ssl->buffers.inputBuffer.buffer[ssl->buffers.inputBuffer.idx++];
  12801. b1 =
  12802. ssl->buffers.inputBuffer.buffer[ssl->buffers.inputBuffer.idx++];
  12803. ssl->curSize = (word16)(((b0 & 0x7f) << 8) | b1);
  12804. }
  12805. else {
  12806. ssl->options.processReply = getRecordLayerHeader;
  12807. continue;
  12808. }
  12809. FALL_THROUGH;
  12810. /* in the WOLFSSL_SERVER case, run the old client hello */
  12811. case runProcessOldClientHello:
  12812. /* get sz bytes or return error */
  12813. if (!ssl->options.dtls) {
  12814. if ((ret = GetInputData(ssl, ssl->curSize)) < 0)
  12815. return ret;
  12816. } else {
  12817. #ifdef WOLFSSL_DTLS
  12818. /* read ahead may already have */
  12819. used = ssl->buffers.inputBuffer.length -
  12820. ssl->buffers.inputBuffer.idx;
  12821. if (used < ssl->curSize)
  12822. if ((ret = GetInputData(ssl, ssl->curSize)) < 0)
  12823. return ret;
  12824. #endif /* WOLFSSL_DTLS */
  12825. }
  12826. ret = ProcessOldClientHello(ssl, ssl->buffers.inputBuffer.buffer,
  12827. &ssl->buffers.inputBuffer.idx,
  12828. ssl->buffers.inputBuffer.length -
  12829. ssl->buffers.inputBuffer.idx,
  12830. ssl->curSize);
  12831. if (ret < 0)
  12832. return ret;
  12833. else if (ssl->buffers.inputBuffer.idx ==
  12834. ssl->buffers.inputBuffer.length) {
  12835. ssl->options.processReply = doProcessInit;
  12836. return 0;
  12837. }
  12838. #endif /* OLD_HELLO_ALLOWED */
  12839. FALL_THROUGH;
  12840. /* get the record layer header */
  12841. case getRecordLayerHeader:
  12842. ret = GetRecordHeader(ssl, ssl->buffers.inputBuffer.buffer,
  12843. &ssl->buffers.inputBuffer.idx,
  12844. &ssl->curRL, &ssl->curSize);
  12845. #ifdef WOLFSSL_DTLS
  12846. if (ssl->options.dtls && ret == SEQUENCE_ERROR) {
  12847. WOLFSSL_MSG("Silently dropping out of order DTLS message");
  12848. ssl->options.processReply = doProcessInit;
  12849. ssl->buffers.inputBuffer.length = 0;
  12850. ssl->buffers.inputBuffer.idx = 0;
  12851. #ifdef WOLFSSL_DTLS_DROP_STATS
  12852. ssl->replayDropCount++;
  12853. #endif /* WOLFSSL_DTLS_DROP_STATS */
  12854. if (IsDtlsNotSctpMode(ssl) && ssl->options.dtlsHsRetain) {
  12855. ret = DtlsMsgPoolSend(ssl, 0);
  12856. if (ret != 0)
  12857. return ret;
  12858. }
  12859. continue;
  12860. }
  12861. #endif
  12862. if (ret != 0)
  12863. return ret;
  12864. #ifdef WOLFSSL_TLS13
  12865. if (IsAtLeastTLSv1_3(ssl->version) && IsEncryptionOn(ssl, 0) &&
  12866. ssl->curRL.type != application_data &&
  12867. ssl->curRL.type != change_cipher_spec) {
  12868. SendAlert(ssl, alert_fatal, unexpected_message);
  12869. return PARSE_ERROR;
  12870. }
  12871. #endif
  12872. ssl->options.processReply = getData;
  12873. FALL_THROUGH;
  12874. /* retrieve record layer data */
  12875. case getData:
  12876. /* get sz bytes or return error */
  12877. if (!ssl->options.dtls) {
  12878. if ((ret = GetInputData(ssl, ssl->curSize)) < 0) {
  12879. #ifdef WOLFSSL_EXTRA_ALERTS
  12880. if (ret != WANT_READ)
  12881. SendAlert(ssl, alert_fatal, bad_record_mac);
  12882. #endif
  12883. return ret;
  12884. }
  12885. }
  12886. else {
  12887. #ifdef WOLFSSL_DTLS
  12888. /* read ahead may already have */
  12889. used = ssl->buffers.inputBuffer.length -
  12890. ssl->buffers.inputBuffer.idx;
  12891. if (used < ssl->curSize)
  12892. if ((ret = GetInputData(ssl, ssl->curSize)) < 0)
  12893. return ret;
  12894. #endif
  12895. }
  12896. if (IsEncryptionOn(ssl, 0)) {
  12897. int tooLong = 0;
  12898. #ifdef WOLFSSL_TLS13
  12899. if (IsAtLeastTLSv1_3(ssl->version)) {
  12900. tooLong = ssl->curSize > MAX_TLS13_ENC_SZ;
  12901. tooLong |= ssl->curSize - ssl->specs.aead_mac_size >
  12902. MAX_TLS13_PLAIN_SZ;
  12903. }
  12904. #endif
  12905. #ifdef WOLFSSL_EXTRA_ALERTS
  12906. if (!IsAtLeastTLSv1_3(ssl->version))
  12907. tooLong = ssl->curSize > MAX_TLS_CIPHER_SZ;
  12908. #endif
  12909. if (tooLong) {
  12910. WOLFSSL_MSG("Encrypted data too long");
  12911. #if defined(WOLFSSL_TLS13) || defined(WOLFSSL_EXTRA_ALERTS)
  12912. SendAlert(ssl, alert_fatal, record_overflow);
  12913. #endif
  12914. return BUFFER_ERROR;
  12915. }
  12916. }
  12917. ssl->keys.padSz = 0;
  12918. ssl->options.processReply = verifyEncryptedMessage;
  12919. startIdx = ssl->buffers.inputBuffer.idx; /* in case > 1 msg per */
  12920. FALL_THROUGH;
  12921. /* verify digest of encrypted message */
  12922. case verifyEncryptedMessage:
  12923. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  12924. if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0 &&
  12925. !atomicUser && ssl->options.startedETMRead) {
  12926. ret = VerifyMacEnc(ssl, ssl->buffers.inputBuffer.buffer +
  12927. ssl->buffers.inputBuffer.idx,
  12928. ssl->curSize, ssl->curRL.type);
  12929. #ifdef WOLFSSL_ASYNC_CRYPT
  12930. if (ret == WC_PENDING_E)
  12931. return ret;
  12932. #endif
  12933. if (ret < 0) {
  12934. WOLFSSL_MSG("VerifyMacEnc failed");
  12935. WOLFSSL_ERROR(ret);
  12936. #ifdef WOLFSSL_DTLS
  12937. /* If in DTLS mode, if the decrypt fails for any
  12938. * reason, pretend the datagram never happened. */
  12939. if (ssl->options.dtls) {
  12940. ssl->options.processReply = doProcessInit;
  12941. ssl->buffers.inputBuffer.idx =
  12942. ssl->buffers.inputBuffer.length;
  12943. #ifdef WOLFSSL_DTLS_DROP_STATS
  12944. ssl->macDropCount++;
  12945. #endif /* WOLFSSL_DTLS_DROP_STATS */
  12946. }
  12947. #endif /* WOLFSSL_DTLS */
  12948. #ifdef WOLFSSL_EXTRA_ALERTS
  12949. if (!ssl->options.dtls)
  12950. SendAlert(ssl, alert_fatal, bad_record_mac);
  12951. #endif
  12952. return DECRYPT_ERROR;
  12953. }
  12954. ssl->keys.encryptSz = ssl->curSize;
  12955. }
  12956. #endif
  12957. ssl->options.processReply = decryptMessage;
  12958. FALL_THROUGH;
  12959. /* decrypt message */
  12960. case decryptMessage:
  12961. #if !defined(WOLFSSL_TLS13) || defined(WOLFSSL_TLS13_DRAFT_18)
  12962. if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0)
  12963. #else
  12964. if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0 &&
  12965. (!IsAtLeastTLSv1_3(ssl->version) ||
  12966. ssl->curRL.type != change_cipher_spec))
  12967. #endif
  12968. {
  12969. bufferStatic* in = &ssl->buffers.inputBuffer;
  12970. ret = SanityCheckCipherText(ssl, ssl->curSize);
  12971. if (ret < 0) {
  12972. #ifdef WOLFSSL_EXTRA_ALERTS
  12973. SendAlert(ssl, alert_fatal, bad_record_mac);
  12974. #endif
  12975. return ret;
  12976. }
  12977. if (atomicUser) {
  12978. #ifdef ATOMIC_USER
  12979. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  12980. if (ssl->options.startedETMRead) {
  12981. ret = ssl->ctx->VerifyDecryptCb(ssl,
  12982. in->buffer + in->idx, in->buffer + in->idx,
  12983. ssl->curSize - MacSize(ssl),
  12984. ssl->curRL.type, 1, &ssl->keys.padSz,
  12985. ssl->DecryptVerifyCtx);
  12986. }
  12987. else
  12988. #endif
  12989. {
  12990. ret = ssl->ctx->DecryptVerifyCb(ssl,
  12991. in->buffer + in->idx,
  12992. in->buffer + in->idx,
  12993. ssl->curSize, ssl->curRL.type, 1,
  12994. &ssl->keys.padSz, ssl->DecryptVerifyCtx);
  12995. }
  12996. #endif /* ATOMIC_USER */
  12997. }
  12998. else {
  12999. if (!ssl->options.tls1_3) {
  13000. #ifndef WOLFSSL_NO_TLS12
  13001. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  13002. if (ssl->options.startedETMRead) {
  13003. word32 digestSz = MacSize(ssl);
  13004. ret = Decrypt(ssl,
  13005. in->buffer + in->idx,
  13006. in->buffer + in->idx,
  13007. ssl->curSize - digestSz);
  13008. ssl->keys.padSz =
  13009. in->buffer[in->idx + ssl->curSize - digestSz - 1];
  13010. ssl->keys.padSz += 1;
  13011. ssl->keys.decryptedCur = 1;
  13012. }
  13013. else
  13014. #endif
  13015. {
  13016. ret = Decrypt(ssl,
  13017. in->buffer + in->idx,
  13018. in->buffer + in->idx,
  13019. ssl->curSize);
  13020. }
  13021. #else
  13022. ret = DECRYPT_ERROR;
  13023. #endif
  13024. }
  13025. else
  13026. {
  13027. #ifdef WOLFSSL_TLS13
  13028. #if defined(WOLFSSL_TLS13_DRAFT_18) || \
  13029. defined(WOLFSSL_TLS13_DRAFT_22) || \
  13030. defined(WOLFSSL_TLS13_DRAFT_23)
  13031. ret = DecryptTls13(ssl,
  13032. in->buffer + in->idx,
  13033. in->buffer + in->idx,
  13034. ssl->curSize, NULL, 0);
  13035. #else
  13036. ret = DecryptTls13(ssl,
  13037. in->buffer + in->idx,
  13038. in->buffer + in->idx,
  13039. ssl->curSize,
  13040. (byte*)&ssl->curRL, RECORD_HEADER_SZ);
  13041. #endif
  13042. #else
  13043. ret = DECRYPT_ERROR;
  13044. #endif /* WOLFSSL_TLS13 */
  13045. }
  13046. }
  13047. #ifdef WOLFSSL_ASYNC_CRYPT
  13048. if (ret == WC_PENDING_E)
  13049. return ret;
  13050. #endif
  13051. if (ret >= 0) {
  13052. #ifndef WOLFSSL_NO_TLS12
  13053. /* handle success */
  13054. #ifndef WOLFSSL_AEAD_ONLY
  13055. if (ssl->options.tls1_1 && ssl->specs.cipher_type == block)
  13056. ssl->buffers.inputBuffer.idx += ssl->specs.block_size;
  13057. #endif
  13058. /* go past TLSv1.1 IV */
  13059. if (CipherHasExpIV(ssl))
  13060. ssl->buffers.inputBuffer.idx += AESGCM_EXP_IV_SZ;
  13061. #endif
  13062. }
  13063. else {
  13064. WOLFSSL_MSG("Decrypt failed");
  13065. WOLFSSL_ERROR(ret);
  13066. #ifdef WOLFSSL_EARLY_DATA
  13067. if (ssl->options.tls1_3) {
  13068. if (ssl->options.side == WOLFSSL_SERVER_END &&
  13069. ssl->earlyData != no_early_data &&
  13070. ssl->options.clientState <
  13071. CLIENT_FINISHED_COMPLETE) {
  13072. ssl->earlyDataSz += ssl->curSize;
  13073. if (ssl->earlyDataSz <=
  13074. ssl->options.maxEarlyDataSz) {
  13075. WOLFSSL_MSG("Ignoring EarlyData!");
  13076. if (ssl->keys.peer_sequence_number_lo-- == 0)
  13077. ssl->keys.peer_sequence_number_hi--;
  13078. ssl->options.processReply = doProcessInit;
  13079. ssl->buffers.inputBuffer.idx =
  13080. ssl->buffers.inputBuffer.length;
  13081. return 0;
  13082. }
  13083. WOLFSSL_MSG("Too much EarlyData!");
  13084. }
  13085. SendAlert(ssl, alert_fatal, bad_record_mac);
  13086. }
  13087. #endif
  13088. #ifdef WOLFSSL_DTLS
  13089. /* If in DTLS mode, if the decrypt fails for any
  13090. * reason, pretend the datagram never happened. */
  13091. if (ssl->options.dtls) {
  13092. ssl->options.processReply = doProcessInit;
  13093. ssl->buffers.inputBuffer.idx =
  13094. ssl->buffers.inputBuffer.length;
  13095. #ifdef WOLFSSL_DTLS_DROP_STATS
  13096. ssl->macDropCount++;
  13097. #endif /* WOLFSSL_DTLS_DROP_STATS */
  13098. }
  13099. #endif /* WOLFSSL_DTLS */
  13100. return DECRYPT_ERROR;
  13101. }
  13102. }
  13103. ssl->options.processReply = verifyMessage;
  13104. FALL_THROUGH;
  13105. /* verify digest of message */
  13106. case verifyMessage:
  13107. #if !defined(WOLFSSL_TLS13) || defined(WOLFSSL_TLS13_DRAFT_18)
  13108. if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0)
  13109. #else
  13110. if (IsEncryptionOn(ssl, 0) && ssl->keys.decryptedCur == 0 &&
  13111. (!IsAtLeastTLSv1_3(ssl->version) ||
  13112. ssl->curRL.type != change_cipher_spec))
  13113. #endif
  13114. {
  13115. if (!atomicUser
  13116. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  13117. && !ssl->options.startedETMRead
  13118. #endif
  13119. ) {
  13120. ret = VerifyMac(ssl, ssl->buffers.inputBuffer.buffer +
  13121. ssl->buffers.inputBuffer.idx,
  13122. ssl->curSize, ssl->curRL.type,
  13123. &ssl->keys.padSz);
  13124. #ifdef WOLFSSL_ASYNC_CRYPT
  13125. if (ret == WC_PENDING_E)
  13126. return ret;
  13127. #endif
  13128. if (ret < 0) {
  13129. WOLFSSL_MSG("VerifyMac failed");
  13130. WOLFSSL_ERROR(ret);
  13131. #ifdef WOLFSSL_DTLS
  13132. /* If in DTLS mode, if the decrypt fails for any
  13133. * reason, pretend the datagram never happened. */
  13134. if (ssl->options.dtls) {
  13135. ssl->options.processReply = doProcessInit;
  13136. ssl->buffers.inputBuffer.idx =
  13137. ssl->buffers.inputBuffer.length;
  13138. #ifdef WOLFSSL_DTLS_DROP_STATS
  13139. ssl->macDropCount++;
  13140. #endif /* WOLFSSL_DTLS_DROP_STATS */
  13141. }
  13142. #endif /* WOLFSSL_DTLS */
  13143. #ifdef WOLFSSL_EXTRA_ALERTS
  13144. if (!ssl->options.dtls)
  13145. SendAlert(ssl, alert_fatal, bad_record_mac);
  13146. #endif
  13147. return DECRYPT_ERROR;
  13148. }
  13149. }
  13150. ssl->keys.encryptSz = ssl->curSize;
  13151. ssl->keys.decryptedCur = 1;
  13152. #ifdef WOLFSSL_TLS13
  13153. if (ssl->options.tls1_3) {
  13154. word16 i = (word16)(ssl->buffers.inputBuffer.length -
  13155. ssl->keys.padSz);
  13156. /* Remove padding from end of plain text. */
  13157. for (--i; i > ssl->buffers.inputBuffer.idx; i--) {
  13158. if (ssl->buffers.inputBuffer.buffer[i] != 0)
  13159. break;
  13160. }
  13161. /* Get the real content type from the end of the data. */
  13162. ssl->curRL.type = ssl->buffers.inputBuffer.buffer[i];
  13163. ssl->keys.padSz = ssl->buffers.inputBuffer.length - i;
  13164. }
  13165. #endif
  13166. }
  13167. ssl->options.processReply = runProcessingOneMessage;
  13168. FALL_THROUGH;
  13169. /* the record layer is here */
  13170. case runProcessingOneMessage:
  13171. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  13172. if (IsEncryptionOn(ssl, 0) && ssl->options.startedETMRead) {
  13173. if (ssl->buffers.inputBuffer.length - ssl->keys.padSz -
  13174. ssl->buffers.inputBuffer.idx -
  13175. MacSize(ssl) > MAX_PLAINTEXT_SZ) {
  13176. WOLFSSL_MSG("Plaintext too long - Encrypt-Then-MAC");
  13177. #if defined(WOLFSSL_EXTRA_ALERTS)
  13178. SendAlert(ssl, alert_fatal, record_overflow);
  13179. #endif
  13180. return BUFFER_ERROR;
  13181. }
  13182. }
  13183. else
  13184. #endif
  13185. if (ssl->buffers.inputBuffer.length - ssl->keys.padSz -
  13186. ssl->buffers.inputBuffer.idx > MAX_PLAINTEXT_SZ) {
  13187. WOLFSSL_MSG("Plaintext too long");
  13188. #if defined(WOLFSSL_TLS13) || defined(WOLFSSL_EXTRA_ALERTS)
  13189. SendAlert(ssl, alert_fatal, record_overflow);
  13190. #endif
  13191. return BUFFER_ERROR;
  13192. }
  13193. #ifdef WOLFSSL_DTLS
  13194. if (IsDtlsNotSctpMode(ssl)) {
  13195. DtlsUpdateWindow(ssl);
  13196. }
  13197. #endif /* WOLFSSL_DTLS */
  13198. WOLFSSL_MSG("received record layer msg");
  13199. switch (ssl->curRL.type) {
  13200. case handshake :
  13201. /* debugging in DoHandShakeMsg */
  13202. if (ssl->options.dtls) {
  13203. #ifdef WOLFSSL_DTLS
  13204. ret = DoDtlsHandShakeMsg(ssl,
  13205. ssl->buffers.inputBuffer.buffer,
  13206. &ssl->buffers.inputBuffer.idx,
  13207. ssl->buffers.inputBuffer.length);
  13208. #endif
  13209. }
  13210. else if (!IsAtLeastTLSv1_3(ssl->version)) {
  13211. #ifndef WOLFSSL_NO_TLS12
  13212. ret = DoHandShakeMsg(ssl,
  13213. ssl->buffers.inputBuffer.buffer,
  13214. &ssl->buffers.inputBuffer.idx,
  13215. ssl->buffers.inputBuffer.length);
  13216. #else
  13217. ret = BUFFER_ERROR;
  13218. #endif
  13219. }
  13220. else {
  13221. #ifdef WOLFSSL_TLS13
  13222. ssl->msgsReceived.got_change_cipher = 0;
  13223. ret = DoTls13HandShakeMsg(ssl,
  13224. ssl->buffers.inputBuffer.buffer,
  13225. &ssl->buffers.inputBuffer.idx,
  13226. ssl->buffers.inputBuffer.length);
  13227. #ifdef WOLFSSL_EARLY_DATA
  13228. if (ret != 0)
  13229. return ret;
  13230. if (ssl->options.side == WOLFSSL_SERVER_END &&
  13231. ssl->earlyData > early_data_ext &&
  13232. ssl->options.handShakeState == HANDSHAKE_DONE) {
  13233. ssl->earlyData = no_early_data;
  13234. ssl->options.processReply = doProcessInit;
  13235. return ZERO_RETURN;
  13236. }
  13237. #endif
  13238. #else
  13239. ret = BUFFER_ERROR;
  13240. #endif
  13241. }
  13242. if (ret != 0) {
  13243. WOLFSSL_ERROR(ret);
  13244. return ret;
  13245. }
  13246. break;
  13247. case change_cipher_spec:
  13248. WOLFSSL_MSG("got CHANGE CIPHER SPEC");
  13249. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  13250. if (ssl->hsInfoOn)
  13251. AddPacketName(ssl, "ChangeCipher");
  13252. /* add record header back on info */
  13253. if (ssl->toInfoOn) {
  13254. AddPacketInfo(ssl, "ChangeCipher",
  13255. change_cipher_spec,
  13256. ssl->buffers.inputBuffer.buffer +
  13257. ssl->buffers.inputBuffer.idx - RECORD_HEADER_SZ,
  13258. 1 + RECORD_HEADER_SZ, READ_PROTO, ssl->heap);
  13259. #ifdef WOLFSSL_CALLBACKS
  13260. AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
  13261. #endif
  13262. }
  13263. #endif
  13264. #ifdef WOLFSSL_TLS13
  13265. #ifdef WOLFSSL_TLS13_DRAFT_18
  13266. if (IsAtLeastTLSv1_3(ssl->version)) {
  13267. SendAlert(ssl, alert_fatal, illegal_parameter);
  13268. return UNKNOWN_RECORD_TYPE;
  13269. }
  13270. #else
  13271. if (IsAtLeastTLSv1_3(ssl->version)) {
  13272. word32 i = ssl->buffers.inputBuffer.idx;
  13273. if (ssl->options.handShakeState == HANDSHAKE_DONE) {
  13274. SendAlert(ssl, alert_fatal, unexpected_message);
  13275. return UNKNOWN_RECORD_TYPE;
  13276. }
  13277. if (ssl->curSize != 1 ||
  13278. ssl->buffers.inputBuffer.buffer[i] != 1) {
  13279. SendAlert(ssl, alert_fatal, illegal_parameter);
  13280. return UNKNOWN_RECORD_TYPE;
  13281. }
  13282. ssl->buffers.inputBuffer.idx++;
  13283. if (!ssl->msgsReceived.got_change_cipher) {
  13284. ssl->msgsReceived.got_change_cipher = 1;
  13285. }
  13286. else {
  13287. SendAlert(ssl, alert_fatal, illegal_parameter);
  13288. return UNKNOWN_RECORD_TYPE;
  13289. }
  13290. break;
  13291. }
  13292. #endif
  13293. #endif
  13294. #ifndef WOLFSSL_NO_TLS12
  13295. ret = SanityCheckMsgReceived(ssl, change_cipher_hs);
  13296. if (ret != 0) {
  13297. if (!ssl->options.dtls) {
  13298. return ret;
  13299. }
  13300. else {
  13301. #ifdef WOLFSSL_DTLS
  13302. /* Check for duplicate CCS message in DTLS mode.
  13303. * DTLS allows for duplicate messages, and it should be
  13304. * skipped. Also skip if out of order. */
  13305. if (ret != DUPLICATE_MSG_E && ret != OUT_OF_ORDER_E)
  13306. return ret;
  13307. if (IsDtlsNotSctpMode(ssl)) {
  13308. ret = DtlsMsgPoolSend(ssl, 1);
  13309. if (ret != 0)
  13310. return ret;
  13311. }
  13312. if (ssl->curSize != 1) {
  13313. WOLFSSL_MSG("Malicious or corrupted"
  13314. " duplicate ChangeCipher msg");
  13315. return LENGTH_ERROR;
  13316. }
  13317. ssl->buffers.inputBuffer.idx++;
  13318. break;
  13319. #endif /* WOLFSSL_DTLS */
  13320. }
  13321. }
  13322. if (IsEncryptionOn(ssl, 0) && ssl->options.handShakeDone) {
  13323. ssl->buffers.inputBuffer.idx += ssl->keys.padSz;
  13324. ssl->curSize -= (word16) ssl->buffers.inputBuffer.idx;
  13325. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  13326. if (ssl->options.startedETMRead) {
  13327. word32 digestSz = MacSize(ssl);
  13328. ssl->buffers.inputBuffer.idx += digestSz;
  13329. ssl->curSize -= digestSz;
  13330. }
  13331. #endif
  13332. }
  13333. if (ssl->curSize != 1) {
  13334. WOLFSSL_MSG("Malicious or corrupted ChangeCipher msg");
  13335. return LENGTH_ERROR;
  13336. }
  13337. ssl->buffers.inputBuffer.idx++;
  13338. ssl->keys.encryptionOn = 1;
  13339. /* setup decrypt keys for following messages */
  13340. /* XXX This might not be what we want to do when
  13341. * receiving a CCS with multicast. We update the
  13342. * key when the application updates them. */
  13343. if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
  13344. return ret;
  13345. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  13346. ssl->options.startedETMRead = ssl->options.encThenMac;
  13347. #endif
  13348. #ifdef WOLFSSL_DTLS
  13349. if (ssl->options.dtls) {
  13350. WOLFSSL_DTLS_PEERSEQ* peerSeq = ssl->keys.peerSeq;
  13351. #ifdef WOLFSSL_MULTICAST
  13352. if (ssl->options.haveMcast) {
  13353. peerSeq += ssl->keys.curPeerId;
  13354. peerSeq->highwaterMark = UpdateHighwaterMark(0,
  13355. ssl->ctx->mcastFirstSeq,
  13356. ssl->ctx->mcastSecondSeq,
  13357. ssl->ctx->mcastMaxSeq);
  13358. }
  13359. #endif
  13360. peerSeq->nextEpoch++;
  13361. peerSeq->prevSeq_lo = peerSeq->nextSeq_lo;
  13362. peerSeq->prevSeq_hi = peerSeq->nextSeq_hi;
  13363. peerSeq->nextSeq_lo = 0;
  13364. peerSeq->nextSeq_hi = 0;
  13365. XMEMCPY(peerSeq->prevWindow, peerSeq->window,
  13366. DTLS_SEQ_SZ);
  13367. XMEMSET(peerSeq->window, 0, DTLS_SEQ_SZ);
  13368. }
  13369. #endif
  13370. #ifdef HAVE_LIBZ
  13371. if (ssl->options.usingCompression)
  13372. if ( (ret = InitStreams(ssl)) != 0)
  13373. return ret;
  13374. #endif
  13375. ret = BuildFinished(ssl, &ssl->hsHashes->verifyHashes,
  13376. ssl->options.side == WOLFSSL_CLIENT_END ?
  13377. server : client);
  13378. if (ret != 0)
  13379. return ret;
  13380. #endif /* !WOLFSSL_NO_TLS12 */
  13381. break;
  13382. case application_data:
  13383. WOLFSSL_MSG("got app DATA");
  13384. #ifdef WOLFSSL_DTLS
  13385. if (ssl->options.dtls && ssl->options.dtlsHsRetain) {
  13386. FreeHandshakeResources(ssl);
  13387. ssl->options.dtlsHsRetain = 0;
  13388. }
  13389. #endif
  13390. #ifdef WOLFSSL_TLS13
  13391. if (ssl->keys.keyUpdateRespond) {
  13392. WOLFSSL_MSG("No KeyUpdate from peer seen");
  13393. return SANITY_MSG_E;
  13394. }
  13395. #endif
  13396. if ((ret = DoApplicationData(ssl,
  13397. ssl->buffers.inputBuffer.buffer,
  13398. &ssl->buffers.inputBuffer.idx))
  13399. != 0) {
  13400. WOLFSSL_ERROR(ret);
  13401. return ret;
  13402. }
  13403. break;
  13404. case alert:
  13405. WOLFSSL_MSG("got ALERT!");
  13406. ret = DoAlert(ssl, ssl->buffers.inputBuffer.buffer,
  13407. &ssl->buffers.inputBuffer.idx, &type,
  13408. ssl->buffers.inputBuffer.length);
  13409. if (ret == alert_fatal)
  13410. return FATAL_ERROR;
  13411. else if (ret < 0)
  13412. return ret;
  13413. /* catch warnings that are handled as errors */
  13414. if (type == close_notify)
  13415. return ssl->error = ZERO_RETURN;
  13416. if (type == decrypt_error)
  13417. return FATAL_ERROR;
  13418. break;
  13419. default:
  13420. WOLFSSL_ERROR(UNKNOWN_RECORD_TYPE);
  13421. return UNKNOWN_RECORD_TYPE;
  13422. }
  13423. ssl->options.processReply = doProcessInit;
  13424. /* input exhausted? */
  13425. if (ssl->buffers.inputBuffer.idx >= ssl->buffers.inputBuffer.length)
  13426. return 0;
  13427. /* more messages per record */
  13428. else if ((ssl->buffers.inputBuffer.idx - startIdx) < ssl->curSize) {
  13429. WOLFSSL_MSG("More messages in record");
  13430. ssl->options.processReply = runProcessingOneMessage;
  13431. if (IsEncryptionOn(ssl, 0)) {
  13432. WOLFSSL_MSG("Bundled encrypted messages, remove middle pad");
  13433. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  13434. if (ssl->options.startedETMRead) {
  13435. word32 digestSz = MacSize(ssl);
  13436. if (ssl->buffers.inputBuffer.idx >=
  13437. ssl->keys.padSz + digestSz) {
  13438. ssl->buffers.inputBuffer.idx -=
  13439. ssl->keys.padSz + digestSz;
  13440. }
  13441. else {
  13442. WOLFSSL_MSG("\tmiddle padding error");
  13443. return FATAL_ERROR;
  13444. }
  13445. }
  13446. else
  13447. #endif
  13448. {
  13449. if (ssl->buffers.inputBuffer.idx >= ssl->keys.padSz) {
  13450. ssl->buffers.inputBuffer.idx -= ssl->keys.padSz;
  13451. }
  13452. else {
  13453. WOLFSSL_MSG("\tmiddle padding error");
  13454. return FATAL_ERROR;
  13455. }
  13456. }
  13457. }
  13458. continue;
  13459. }
  13460. /* more records */
  13461. else {
  13462. WOLFSSL_MSG("More records in input");
  13463. ssl->options.processReply = doProcessInit;
  13464. continue;
  13465. }
  13466. default:
  13467. WOLFSSL_MSG("Bad process input state, programming error");
  13468. return INPUT_CASE_ERROR;
  13469. }
  13470. }
  13471. }
  13472. int SendChangeCipher(WOLFSSL* ssl)
  13473. {
  13474. byte *output;
  13475. int sendSz = RECORD_HEADER_SZ + ENUM_LEN;
  13476. int idx = RECORD_HEADER_SZ;
  13477. int ret;
  13478. #ifdef OPENSSL_EXTRA
  13479. ssl->cbmode = SSL_CB_MODE_WRITE;
  13480. if (ssl->options.side == WOLFSSL_SERVER_END){
  13481. ssl->options.serverState = SERVER_CHANGECIPHERSPEC_COMPLETE;
  13482. if (ssl->CBIS != NULL)
  13483. ssl->CBIS(ssl, SSL_CB_ACCEPT_LOOP, SSL_SUCCESS);
  13484. }
  13485. else{
  13486. ssl->options.clientState =
  13487. CLIENT_CHANGECIPHERSPEC_COMPLETE;
  13488. if (ssl->CBIS != NULL)
  13489. ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, SSL_SUCCESS);
  13490. }
  13491. #endif
  13492. #ifdef WOLFSSL_DTLS
  13493. if (ssl->options.dtls) {
  13494. sendSz += DTLS_RECORD_EXTRA;
  13495. idx += DTLS_RECORD_EXTRA;
  13496. }
  13497. #endif
  13498. /* are we in scr */
  13499. if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone) {
  13500. sendSz += MAX_MSG_EXTRA;
  13501. }
  13502. /* check for available size */
  13503. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  13504. return ret;
  13505. /* get output buffer */
  13506. output = ssl->buffers.outputBuffer.buffer +
  13507. ssl->buffers.outputBuffer.length;
  13508. AddRecordHeader(output, 1, change_cipher_spec, ssl);
  13509. output[idx] = 1; /* turn it on */
  13510. if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone) {
  13511. byte input[ENUM_LEN];
  13512. int inputSz = ENUM_LEN;
  13513. input[0] = 1; /* turn it on */
  13514. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  13515. change_cipher_spec, 0, 0, 0);
  13516. if (sendSz < 0) {
  13517. return sendSz;
  13518. }
  13519. }
  13520. #ifdef WOLFSSL_DTLS
  13521. if (IsDtlsNotSctpMode(ssl)) {
  13522. DtlsSEQIncrement(ssl, CUR_ORDER);
  13523. if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
  13524. return ret;
  13525. }
  13526. #endif
  13527. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  13528. if (ssl->hsInfoOn) AddPacketName(ssl, "ChangeCipher");
  13529. if (ssl->toInfoOn)
  13530. AddPacketInfo(ssl, "ChangeCipher", change_cipher_spec, output,
  13531. sendSz, WRITE_PROTO, ssl->heap);
  13532. #endif
  13533. ssl->buffers.outputBuffer.length += sendSz;
  13534. if (ssl->options.groupMessages)
  13535. return 0;
  13536. #if defined(WOLFSSL_DTLS) && !defined(WOLFSSL_DEBUG_DTLS)
  13537. else if (ssl->options.dtls) {
  13538. /* If using DTLS, force the ChangeCipherSpec message to be in the
  13539. * same datagram as the finished message. */
  13540. return 0;
  13541. }
  13542. #endif
  13543. else
  13544. return SendBuffered(ssl);
  13545. }
  13546. #if !defined(NO_OLD_TLS) && !defined(WOLFSSL_AEAD_ONLY)
  13547. static int SSL_hmac(WOLFSSL* ssl, byte* digest, const byte* in, word32 sz,
  13548. int padLen, int content, int verify)
  13549. {
  13550. byte result[WC_MAX_DIGEST_SIZE];
  13551. word32 digestSz = ssl->specs.hash_size; /* actual sizes */
  13552. word32 padSz = ssl->specs.pad_size;
  13553. int ret = 0;
  13554. wc_Md5 md5;
  13555. wc_Sha sha;
  13556. /* data */
  13557. byte seq[SEQ_SZ];
  13558. byte conLen[ENUM_LEN + LENGTH_SZ]; /* content & length */
  13559. const byte* macSecret = wolfSSL_GetMacSecret(ssl, verify);
  13560. (void)padLen;
  13561. #ifdef HAVE_FUZZER
  13562. if (ssl->fuzzerCb)
  13563. ssl->fuzzerCb(ssl, in, sz, FUZZ_HMAC, ssl->fuzzerCtx);
  13564. #endif
  13565. XMEMSET(seq, 0, SEQ_SZ);
  13566. conLen[0] = (byte)content;
  13567. c16toa((word16)sz, &conLen[ENUM_LEN]);
  13568. WriteSEQ(ssl, verify, seq);
  13569. if (ssl->specs.mac_algorithm == md5_mac) {
  13570. ret = wc_InitMd5_ex(&md5, ssl->heap, ssl->devId);
  13571. if (ret != 0)
  13572. return ret;
  13573. /* inner */
  13574. ret = wc_Md5Update(&md5, macSecret, digestSz);
  13575. ret |= wc_Md5Update(&md5, PAD1, padSz);
  13576. ret |= wc_Md5Update(&md5, seq, SEQ_SZ);
  13577. ret |= wc_Md5Update(&md5, conLen, sizeof(conLen));
  13578. /* in buffer */
  13579. ret |= wc_Md5Update(&md5, in, sz);
  13580. if (ret != 0)
  13581. return VERIFY_MAC_ERROR;
  13582. ret = wc_Md5Final(&md5, result);
  13583. #ifdef WOLFSSL_ASYNC_CRYPT
  13584. /* TODO: Make non-blocking */
  13585. if (ret == WC_PENDING_E) {
  13586. ret = wc_AsyncWait(ret, &md5.asyncDev, WC_ASYNC_FLAG_NONE);
  13587. }
  13588. #endif
  13589. if (ret != 0)
  13590. return VERIFY_MAC_ERROR;
  13591. /* outer */
  13592. ret = wc_Md5Update(&md5, macSecret, digestSz);
  13593. ret |= wc_Md5Update(&md5, PAD2, padSz);
  13594. ret |= wc_Md5Update(&md5, result, digestSz);
  13595. if (ret != 0)
  13596. return VERIFY_MAC_ERROR;
  13597. ret = wc_Md5Final(&md5, digest);
  13598. #ifdef WOLFSSL_ASYNC_CRYPT
  13599. /* TODO: Make non-blocking */
  13600. if (ret == WC_PENDING_E) {
  13601. ret = wc_AsyncWait(ret, &md5.asyncDev, WC_ASYNC_FLAG_NONE);
  13602. }
  13603. #endif
  13604. if (ret != 0)
  13605. return VERIFY_MAC_ERROR;
  13606. wc_Md5Free(&md5);
  13607. }
  13608. else {
  13609. ret = wc_InitSha_ex(&sha, ssl->heap, ssl->devId);
  13610. if (ret != 0)
  13611. return ret;
  13612. /* inner */
  13613. ret = wc_ShaUpdate(&sha, macSecret, digestSz);
  13614. ret |= wc_ShaUpdate(&sha, PAD1, padSz);
  13615. ret |= wc_ShaUpdate(&sha, seq, SEQ_SZ);
  13616. ret |= wc_ShaUpdate(&sha, conLen, sizeof(conLen));
  13617. /* in buffer */
  13618. ret |= wc_ShaUpdate(&sha, in, sz);
  13619. if (ret != 0)
  13620. return VERIFY_MAC_ERROR;
  13621. ret = wc_ShaFinal(&sha, result);
  13622. #ifdef WOLFSSL_ASYNC_CRYPT
  13623. /* TODO: Make non-blocking */
  13624. if (ret == WC_PENDING_E) {
  13625. ret = wc_AsyncWait(ret, &sha.asyncDev, WC_ASYNC_FLAG_NONE);
  13626. }
  13627. #endif
  13628. if (ret != 0)
  13629. return VERIFY_MAC_ERROR;
  13630. /* outer */
  13631. ret = wc_ShaUpdate(&sha, macSecret, digestSz);
  13632. ret |= wc_ShaUpdate(&sha, PAD2, padSz);
  13633. ret |= wc_ShaUpdate(&sha, result, digestSz);
  13634. if (ret != 0)
  13635. return VERIFY_MAC_ERROR;
  13636. ret = wc_ShaFinal(&sha, digest);
  13637. #ifdef WOLFSSL_ASYNC_CRYPT
  13638. /* TODO: Make non-blocking */
  13639. if (ret == WC_PENDING_E) {
  13640. ret = wc_AsyncWait(ret, &sha.asyncDev, WC_ASYNC_FLAG_NONE);
  13641. }
  13642. #endif
  13643. if (ret != 0)
  13644. return VERIFY_MAC_ERROR;
  13645. wc_ShaFree(&sha);
  13646. }
  13647. return 0;
  13648. }
  13649. #endif /* !NO_OLD_TLS && !WOLFSSL_AEAD_ONLY */
  13650. #ifndef NO_CERTS
  13651. #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
  13652. static int BuildMD5_CertVerify(WOLFSSL* ssl, byte* digest)
  13653. {
  13654. int ret;
  13655. byte md5_result[WC_MD5_DIGEST_SIZE];
  13656. #ifdef WOLFSSL_SMALL_STACK
  13657. wc_Md5* md5 = (wc_Md5*)XMALLOC(sizeof(wc_Md5), ssl->heap, DYNAMIC_TYPE_HASHCTX);
  13658. #else
  13659. wc_Md5 md5[1];
  13660. #endif
  13661. /* make md5 inner */
  13662. ret = wc_Md5Copy(&ssl->hsHashes->hashMd5, md5); /* Save current position */
  13663. if (ret == 0)
  13664. ret = wc_Md5Update(md5, ssl->arrays->masterSecret,SECRET_LEN);
  13665. if (ret == 0)
  13666. ret = wc_Md5Update(md5, PAD1, PAD_MD5);
  13667. if (ret == 0)
  13668. ret = wc_Md5Final(md5, md5_result);
  13669. /* make md5 outer */
  13670. if (ret == 0) {
  13671. ret = wc_InitMd5_ex(md5, ssl->heap, ssl->devId);
  13672. if (ret == 0) {
  13673. ret = wc_Md5Update(md5, ssl->arrays->masterSecret, SECRET_LEN);
  13674. if (ret == 0)
  13675. ret = wc_Md5Update(md5, PAD2, PAD_MD5);
  13676. if (ret == 0)
  13677. ret = wc_Md5Update(md5, md5_result, WC_MD5_DIGEST_SIZE);
  13678. if (ret == 0)
  13679. ret = wc_Md5Final(md5, digest);
  13680. wc_Md5Free(md5);
  13681. }
  13682. }
  13683. #ifdef WOLFSSL_SMALL_STACK
  13684. XFREE(md5, ssl->heap, DYNAMIC_TYPE_HASHCTX);
  13685. #endif
  13686. return ret;
  13687. }
  13688. #endif /* !NO_MD5 && !NO_OLD_TLS */
  13689. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  13690. defined(WOLFSSL_ALLOW_TLS_SHA1))
  13691. static int BuildSHA_CertVerify(WOLFSSL* ssl, byte* digest)
  13692. {
  13693. int ret;
  13694. byte sha_result[WC_SHA_DIGEST_SIZE];
  13695. #ifdef WOLFSSL_SMALL_STACK
  13696. wc_Sha* sha = (wc_Sha*)XMALLOC(sizeof(wc_Sha), ssl->heap, DYNAMIC_TYPE_HASHCTX);
  13697. #else
  13698. wc_Sha sha[1];
  13699. #endif
  13700. /* make sha inner */
  13701. ret = wc_ShaCopy(&ssl->hsHashes->hashSha, sha); /* Save current position */
  13702. if (ret == 0)
  13703. ret = wc_ShaUpdate(sha, ssl->arrays->masterSecret,SECRET_LEN);
  13704. if (ret == 0)
  13705. ret = wc_ShaUpdate(sha, PAD1, PAD_SHA);
  13706. if (ret == 0)
  13707. ret = wc_ShaFinal(sha, sha_result);
  13708. /* make sha outer */
  13709. if (ret == 0) {
  13710. ret = wc_InitSha_ex(sha, ssl->heap, ssl->devId);
  13711. if (ret == 0) {
  13712. ret = wc_ShaUpdate(sha, ssl->arrays->masterSecret,SECRET_LEN);
  13713. if (ret == 0)
  13714. ret = wc_ShaUpdate(sha, PAD2, PAD_SHA);
  13715. if (ret == 0)
  13716. ret = wc_ShaUpdate(sha, sha_result, WC_SHA_DIGEST_SIZE);
  13717. if (ret == 0)
  13718. ret = wc_ShaFinal(sha, digest);
  13719. wc_ShaFree(sha);
  13720. }
  13721. }
  13722. #ifdef WOLFSSL_SMALL_STACK
  13723. XFREE(sha, ssl->heap, DYNAMIC_TYPE_HASHCTX);
  13724. #endif
  13725. return ret;
  13726. }
  13727. #endif /* !NO_SHA && (!NO_OLD_TLS || WOLFSSL_ALLOW_TLS_SHA1) */
  13728. int BuildCertHashes(WOLFSSL* ssl, Hashes* hashes)
  13729. {
  13730. int ret = 0;
  13731. (void)hashes;
  13732. if (ssl->options.tls) {
  13733. #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
  13734. ret = wc_Md5GetHash(&ssl->hsHashes->hashMd5, hashes->md5);
  13735. if (ret != 0)
  13736. return ret;
  13737. #endif
  13738. #if !defined(NO_SHA)
  13739. ret = wc_ShaGetHash(&ssl->hsHashes->hashSha, hashes->sha);
  13740. if (ret != 0)
  13741. return ret;
  13742. #endif
  13743. if (IsAtLeastTLSv1_2(ssl)) {
  13744. #ifndef NO_SHA256
  13745. ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256,
  13746. hashes->sha256);
  13747. if (ret != 0)
  13748. return ret;
  13749. #endif
  13750. #ifdef WOLFSSL_SHA384
  13751. ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384,
  13752. hashes->sha384);
  13753. if (ret != 0)
  13754. return ret;
  13755. #endif
  13756. #ifdef WOLFSSL_SHA512
  13757. ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512,
  13758. hashes->sha512);
  13759. if (ret != 0)
  13760. return ret;
  13761. #endif
  13762. }
  13763. }
  13764. else {
  13765. #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
  13766. ret = BuildMD5_CertVerify(ssl, hashes->md5);
  13767. if (ret != 0)
  13768. return ret;
  13769. #endif
  13770. #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
  13771. defined(WOLFSSL_ALLOW_TLS_SHA1))
  13772. ret = BuildSHA_CertVerify(ssl, hashes->sha);
  13773. if (ret != 0)
  13774. return ret;
  13775. #endif
  13776. }
  13777. return ret;
  13778. }
  13779. #endif /* !NO_CERTS */
  13780. #ifndef WOLFSSL_NO_TLS12
  13781. /* Persistable BuildMessage arguments */
  13782. typedef struct BuildMsgArgs {
  13783. word32 digestSz;
  13784. word32 sz;
  13785. word32 pad;
  13786. word32 idx;
  13787. word32 headerSz;
  13788. word16 size;
  13789. word32 ivSz; /* TLSv1.1 IV */
  13790. byte* iv;
  13791. } BuildMsgArgs;
  13792. static void FreeBuildMsgArgs(WOLFSSL* ssl, void* pArgs)
  13793. {
  13794. BuildMsgArgs* args = (BuildMsgArgs*)pArgs;
  13795. (void)ssl;
  13796. (void)args;
  13797. if (args->iv) {
  13798. XFREE(args->iv, ssl->heap, DYNAMIC_TYPE_SALT);
  13799. args->iv = NULL;
  13800. }
  13801. }
  13802. #endif
  13803. /* Build SSL Message, encrypted */
  13804. int BuildMessage(WOLFSSL* ssl, byte* output, int outSz, const byte* input,
  13805. int inSz, int type, int hashOutput, int sizeOnly, int asyncOkay)
  13806. {
  13807. #ifndef WOLFSSL_NO_TLS12
  13808. int ret = 0;
  13809. BuildMsgArgs* args;
  13810. BuildMsgArgs lcl_args;
  13811. #ifdef WOLFSSL_ASYNC_CRYPT
  13812. args = (BuildMsgArgs*)ssl->async.args;
  13813. typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
  13814. (void)sizeof(args_test);
  13815. #endif
  13816. #endif
  13817. WOLFSSL_ENTER("BuildMessage");
  13818. if (ssl == NULL) {
  13819. return BAD_FUNC_ARG;
  13820. }
  13821. #ifdef WOLFSSL_NO_TLS12
  13822. return BuildTls13Message(ssl, output, outSz, input, inSz, type,
  13823. hashOutput, sizeOnly, asyncOkay);
  13824. #else
  13825. #ifdef WOLFSSL_TLS13
  13826. if (ssl->options.tls1_3) {
  13827. return BuildTls13Message(ssl, output, outSz, input, inSz, type,
  13828. hashOutput, sizeOnly, asyncOkay);
  13829. }
  13830. #endif
  13831. ret = WC_NOT_PENDING_E;
  13832. #ifdef WOLFSSL_ASYNC_CRYPT
  13833. if (asyncOkay) {
  13834. ret = wolfSSL_AsyncPop(ssl, &ssl->options.buildMsgState);
  13835. if (ret != WC_NOT_PENDING_E) {
  13836. /* Check for error */
  13837. if (ret < 0)
  13838. goto exit_buildmsg;
  13839. }
  13840. }
  13841. else
  13842. #endif
  13843. {
  13844. args = &lcl_args;
  13845. }
  13846. /* Reset state */
  13847. if (ret == WC_NOT_PENDING_E) {
  13848. ret = 0;
  13849. ssl->options.buildMsgState = BUILD_MSG_BEGIN;
  13850. XMEMSET(args, 0, sizeof(BuildMsgArgs));
  13851. args->sz = RECORD_HEADER_SZ + inSz;
  13852. args->idx = RECORD_HEADER_SZ;
  13853. args->headerSz = RECORD_HEADER_SZ;
  13854. #ifdef WOLFSSL_ASYNC_CRYPT
  13855. ssl->async.freeArgs = FreeBuildMsgArgs;
  13856. #endif
  13857. }
  13858. switch (ssl->options.buildMsgState) {
  13859. case BUILD_MSG_BEGIN:
  13860. {
  13861. /* catch mistaken sizeOnly parameter */
  13862. if (!sizeOnly && (output == NULL || input == NULL) ) {
  13863. ERROR_OUT(BAD_FUNC_ARG, exit_buildmsg);
  13864. }
  13865. if (sizeOnly && (output || input) ) {
  13866. WOLFSSL_MSG("BuildMessage w/sizeOnly doesn't need input/output");
  13867. ERROR_OUT(BAD_FUNC_ARG, exit_buildmsg);
  13868. }
  13869. ssl->options.buildMsgState = BUILD_MSG_SIZE;
  13870. }
  13871. FALL_THROUGH;
  13872. case BUILD_MSG_SIZE:
  13873. {
  13874. args->digestSz = ssl->specs.hash_size;
  13875. #ifdef HAVE_TRUNCATED_HMAC
  13876. if (ssl->truncated_hmac)
  13877. args->digestSz = min(TRUNCATED_HMAC_SZ, args->digestSz);
  13878. #endif
  13879. args->sz += args->digestSz;
  13880. #ifdef WOLFSSL_DTLS
  13881. if (ssl->options.dtls) {
  13882. args->sz += DTLS_RECORD_EXTRA;
  13883. args->idx += DTLS_RECORD_EXTRA;
  13884. args->headerSz += DTLS_RECORD_EXTRA;
  13885. }
  13886. #endif
  13887. #ifndef WOLFSSL_AEAD_ONLY
  13888. if (ssl->specs.cipher_type == block) {
  13889. word32 blockSz = ssl->specs.block_size;
  13890. if (ssl->options.tls1_1) {
  13891. args->ivSz = blockSz;
  13892. args->sz += args->ivSz;
  13893. if (args->ivSz > MAX_IV_SZ)
  13894. ERROR_OUT(BUFFER_E, exit_buildmsg);
  13895. }
  13896. args->sz += 1; /* pad byte */
  13897. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  13898. if (ssl->options.startedETMWrite) {
  13899. args->pad = (args->sz - args->headerSz -
  13900. args->digestSz) % blockSz;
  13901. }
  13902. else
  13903. #endif
  13904. args->pad = (args->sz - args->headerSz) % blockSz;
  13905. #ifdef OPENSSL_EXTRA
  13906. if(args->pad != 0)
  13907. #endif
  13908. args->pad = blockSz - args->pad;
  13909. args->sz += args->pad;
  13910. }
  13911. #endif /* WOLFSSL_AEAD_ONLY */
  13912. #ifdef HAVE_AEAD
  13913. if (ssl->specs.cipher_type == aead) {
  13914. if (ssl->specs.bulk_cipher_algorithm != wolfssl_chacha)
  13915. args->ivSz = AESGCM_EXP_IV_SZ;
  13916. args->sz += (args->ivSz + ssl->specs.aead_mac_size - args->digestSz);
  13917. }
  13918. #endif
  13919. /* done with size calculations */
  13920. if (sizeOnly)
  13921. goto exit_buildmsg;
  13922. if (args->sz > (word32)outSz) {
  13923. WOLFSSL_MSG("Oops, want to write past output buffer size");
  13924. ERROR_OUT(BUFFER_E, exit_buildmsg);
  13925. }
  13926. if (args->ivSz > 0) {
  13927. args->iv = (byte*)XMALLOC(args->ivSz, ssl->heap, DYNAMIC_TYPE_SALT);
  13928. if (args->iv == NULL)
  13929. ERROR_OUT(MEMORY_E, exit_buildmsg);
  13930. ret = wc_RNG_GenerateBlock(ssl->rng, args->iv, args->ivSz);
  13931. if (ret != 0)
  13932. goto exit_buildmsg;
  13933. }
  13934. #if !defined(NO_PUBLIC_GCM_SET_IV) && \
  13935. ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
  13936. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)) && \
  13937. defined(HAVE_AEAD))
  13938. if (ssl->specs.cipher_type == aead) {
  13939. if (ssl->specs.bulk_cipher_algorithm != wolfssl_chacha)
  13940. XMEMCPY(args->iv, ssl->keys.aead_exp_IV, AESGCM_EXP_IV_SZ);
  13941. }
  13942. #endif
  13943. args->size = (word16)(args->sz - args->headerSz); /* include mac and digest */
  13944. AddRecordHeader(output, args->size, (byte)type, ssl);
  13945. /* write to output */
  13946. if (args->ivSz > 0) {
  13947. XMEMCPY(output + args->idx, args->iv,
  13948. min(args->ivSz, MAX_IV_SZ));
  13949. args->idx += args->ivSz;
  13950. }
  13951. XMEMCPY(output + args->idx, input, inSz);
  13952. args->idx += inSz;
  13953. ssl->options.buildMsgState = BUILD_MSG_HASH;
  13954. }
  13955. FALL_THROUGH;
  13956. case BUILD_MSG_HASH:
  13957. {
  13958. if (type == handshake && hashOutput) {
  13959. ret = HashOutput(ssl, output, args->headerSz + inSz, args->ivSz);
  13960. if (ret != 0)
  13961. goto exit_buildmsg;
  13962. }
  13963. #ifndef WOLFSSL_AEAD_ONLY
  13964. if (ssl->specs.cipher_type == block) {
  13965. word32 tmpIdx;
  13966. word32 i;
  13967. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  13968. if (ssl->options.startedETMWrite)
  13969. tmpIdx = args->idx;
  13970. else
  13971. #endif
  13972. tmpIdx = args->idx + args->digestSz;
  13973. for (i = 0; i <= args->pad; i++)
  13974. output[tmpIdx++] = (byte)args->pad; /* pad byte gets pad value */
  13975. }
  13976. #endif
  13977. ssl->options.buildMsgState = BUILD_MSG_VERIFY_MAC;
  13978. }
  13979. FALL_THROUGH;
  13980. case BUILD_MSG_VERIFY_MAC:
  13981. {
  13982. /* User Record Layer Callback handling */
  13983. #ifdef ATOMIC_USER
  13984. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  13985. if (ssl->options.startedETMWrite) {
  13986. if (ssl->ctx->EncryptMacCb) {
  13987. ret = ssl->ctx->EncryptMacCb(ssl, output + args->idx +
  13988. args->pad + 1, type, 0,
  13989. output + args->headerSz,
  13990. output + args->headerSz,
  13991. args->size - args->digestSz,
  13992. ssl->MacEncryptCtx);
  13993. goto exit_buildmsg;
  13994. }
  13995. }
  13996. else
  13997. #endif
  13998. {
  13999. if (ssl->ctx->MacEncryptCb) {
  14000. ret = ssl->ctx->MacEncryptCb(ssl, output + args->idx,
  14001. output + args->headerSz + args->ivSz, inSz,
  14002. type, 0, output + args->headerSz,
  14003. output + args->headerSz, args->size,
  14004. ssl->MacEncryptCtx);
  14005. goto exit_buildmsg;
  14006. }
  14007. }
  14008. #endif
  14009. #ifndef WOLFSSL_AEAD_ONLY
  14010. if (ssl->specs.cipher_type != aead
  14011. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  14012. && !ssl->options.startedETMWrite
  14013. #endif
  14014. ) {
  14015. #ifdef HAVE_TRUNCATED_HMAC
  14016. if (ssl->truncated_hmac &&
  14017. ssl->specs.hash_size > args->digestSz) {
  14018. #ifdef WOLFSSL_SMALL_STACK
  14019. byte* hmac;
  14020. #else
  14021. byte hmac[WC_MAX_DIGEST_SIZE];
  14022. #endif
  14023. #ifdef WOLFSSL_SMALL_STACK
  14024. hmac = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, ssl->heap,
  14025. DYNAMIC_TYPE_DIGEST);
  14026. if (hmac == NULL)
  14027. ERROR_OUT(MEMORY_E, exit_buildmsg);
  14028. #endif
  14029. ret = ssl->hmac(ssl, hmac,
  14030. output + args->headerSz + args->ivSz, inSz,
  14031. -1, type, 0);
  14032. XMEMCPY(output + args->idx, hmac, args->digestSz);
  14033. #ifdef WOLFSSL_SMALL_STACK
  14034. XFREE(hmac, ssl->heap, DYNAMIC_TYPE_DIGEST);
  14035. #endif
  14036. }
  14037. else
  14038. #endif
  14039. {
  14040. ret = ssl->hmac(ssl, output + args->idx, output +
  14041. args->headerSz + args->ivSz, inSz, -1, type, 0);
  14042. }
  14043. }
  14044. #endif /* WOLFSSL_AEAD_ONLY */
  14045. if (ret != 0)
  14046. goto exit_buildmsg;
  14047. ssl->options.buildMsgState = BUILD_MSG_ENCRYPT;
  14048. }
  14049. FALL_THROUGH;
  14050. case BUILD_MSG_ENCRYPT:
  14051. {
  14052. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  14053. if (ssl->options.startedETMWrite) {
  14054. ret = Encrypt(ssl, output + args->headerSz,
  14055. output + args->headerSz,
  14056. args->size - args->digestSz, asyncOkay);
  14057. }
  14058. else
  14059. #endif
  14060. {
  14061. ret = Encrypt(ssl, output + args->headerSz,
  14062. output + args->headerSz, args->size, asyncOkay);
  14063. }
  14064. if (ret != 0)
  14065. goto exit_buildmsg;
  14066. ssl->options.buildMsgState = BUILD_MSG_ENCRYPTED_VERIFY_MAC;
  14067. }
  14068. FALL_THROUGH;
  14069. case BUILD_MSG_ENCRYPTED_VERIFY_MAC:
  14070. {
  14071. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  14072. if (ssl->options.startedETMWrite) {
  14073. WOLFSSL_MSG("Calculate MAC of Encrypted Data");
  14074. #ifdef HAVE_TRUNCATED_HMAC
  14075. if (ssl->truncated_hmac &&
  14076. ssl->specs.hash_size > args->digestSz) {
  14077. #ifdef WOLFSSL_SMALL_STACK
  14078. byte* hmac = NULL;
  14079. #else
  14080. byte hmac[WC_MAX_DIGEST_SIZE];
  14081. #endif
  14082. #ifdef WOLFSSL_SMALL_STACK
  14083. hmac = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, ssl->heap,
  14084. DYNAMIC_TYPE_DIGEST);
  14085. if (hmac == NULL)
  14086. ERROR_OUT(MEMORY_E, exit_buildmsg);
  14087. #endif
  14088. ret = ssl->hmac(ssl, hmac, output + args->headerSz,
  14089. args->ivSz + inSz + args->pad + 1, -1, type,
  14090. 0);
  14091. XMEMCPY(output + args->idx + args->pad + 1, hmac,
  14092. args->digestSz);
  14093. #ifdef WOLFSSL_SMALL_STACK
  14094. XFREE(hmac, ssl->heap, DYNAMIC_TYPE_DIGEST);
  14095. #endif
  14096. }
  14097. else
  14098. #endif
  14099. {
  14100. ret = ssl->hmac(ssl, output + args->idx + args->pad + 1,
  14101. output + args->headerSz,
  14102. args->ivSz + inSz + args->pad + 1, -1, type,
  14103. 0);
  14104. }
  14105. }
  14106. #endif /* HAVE_ENCRYPT_THEN_MAC && !WOLFSSL_AEAD_ONLY */
  14107. }
  14108. }
  14109. exit_buildmsg:
  14110. WOLFSSL_LEAVE("BuildMessage", ret);
  14111. #ifdef WOLFSSL_ASYNC_CRYPT
  14112. if (ret == WC_PENDING_E) {
  14113. return ret;
  14114. }
  14115. #endif
  14116. /* make sure build message state is reset */
  14117. ssl->options.buildMsgState = BUILD_MSG_BEGIN;
  14118. #ifdef WOLFSSL_DTLS
  14119. if (ret == 0 && ssl->options.dtls)
  14120. DtlsSEQIncrement(ssl, CUR_ORDER);
  14121. #endif
  14122. /* return sz on success */
  14123. if (ret == 0)
  14124. ret = args->sz;
  14125. /* Final cleanup */
  14126. FreeBuildMsgArgs(ssl, args);
  14127. #ifdef WOLFSSL_ASYNC_CRYPT
  14128. ssl->async.freeArgs = NULL;
  14129. #endif
  14130. return ret;
  14131. #endif /* !WOLFSSL_NO_TLS12 */
  14132. }
  14133. #ifndef WOLFSSL_NO_TLS12
  14134. int SendFinished(WOLFSSL* ssl)
  14135. {
  14136. int sendSz,
  14137. finishedSz = ssl->options.tls ? TLS_FINISHED_SZ :
  14138. FINISHED_SZ;
  14139. byte input[FINISHED_SZ + DTLS_HANDSHAKE_HEADER_SZ]; /* max */
  14140. byte *output;
  14141. Hashes* hashes;
  14142. int ret;
  14143. int headerSz = HANDSHAKE_HEADER_SZ;
  14144. int outputSz;
  14145. WOLFSSL_START(WC_FUNC_FINISHED_SEND);
  14146. WOLFSSL_ENTER("SendFinished");
  14147. /* setup encrypt keys */
  14148. if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
  14149. return ret;
  14150. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  14151. ssl->options.startedETMWrite = ssl->options.encThenMac;
  14152. #endif
  14153. /* check for available size */
  14154. outputSz = sizeof(input) + MAX_MSG_EXTRA;
  14155. if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
  14156. return ret;
  14157. #ifdef WOLFSSL_DTLS
  14158. if (ssl->options.dtls) {
  14159. headerSz += DTLS_HANDSHAKE_EXTRA;
  14160. ssl->keys.dtls_epoch++;
  14161. ssl->keys.dtls_prev_sequence_number_hi =
  14162. ssl->keys.dtls_sequence_number_hi;
  14163. ssl->keys.dtls_prev_sequence_number_lo =
  14164. ssl->keys.dtls_sequence_number_lo;
  14165. ssl->keys.dtls_sequence_number_hi = 0;
  14166. ssl->keys.dtls_sequence_number_lo = 0;
  14167. }
  14168. #endif
  14169. /* get output buffer */
  14170. output = ssl->buffers.outputBuffer.buffer +
  14171. ssl->buffers.outputBuffer.length;
  14172. AddHandShakeHeader(input, finishedSz, 0, finishedSz, finished, ssl);
  14173. /* make finished hashes */
  14174. hashes = (Hashes*)&input[headerSz];
  14175. ret = BuildFinished(ssl, hashes,
  14176. ssl->options.side == WOLFSSL_CLIENT_END ? client : server);
  14177. if (ret != 0) return ret;
  14178. #ifdef HAVE_SECURE_RENEGOTIATION
  14179. if (ssl->secure_renegotiation) {
  14180. if (ssl->options.side == WOLFSSL_CLIENT_END)
  14181. XMEMCPY(ssl->secure_renegotiation->client_verify_data, hashes,
  14182. TLS_FINISHED_SZ);
  14183. else
  14184. XMEMCPY(ssl->secure_renegotiation->server_verify_data, hashes,
  14185. TLS_FINISHED_SZ);
  14186. }
  14187. #endif
  14188. #ifdef WOLFSSL_DTLS
  14189. if (IsDtlsNotSctpMode(ssl)) {
  14190. if ((ret = DtlsMsgPoolSave(ssl, input, headerSz + finishedSz)) != 0)
  14191. return ret;
  14192. }
  14193. #endif
  14194. sendSz = BuildMessage(ssl, output, outputSz, input, headerSz + finishedSz,
  14195. handshake, 1, 0, 0);
  14196. if (sendSz < 0)
  14197. return BUILD_MSG_ERROR;
  14198. if (!ssl->options.resuming) {
  14199. #ifndef NO_SESSION_CACHE
  14200. AddSession(ssl); /* just try */
  14201. #endif
  14202. if (ssl->options.side == WOLFSSL_SERVER_END) {
  14203. #ifdef OPENSSL_EXTRA
  14204. ssl->options.serverState = SERVER_FINISHED_COMPLETE;
  14205. ssl->cbmode = SSL_CB_MODE_WRITE;
  14206. if (ssl->CBIS != NULL)
  14207. ssl->CBIS(ssl, SSL_CB_HANDSHAKE_DONE, SSL_SUCCESS);
  14208. #endif
  14209. ssl->options.handShakeState = HANDSHAKE_DONE;
  14210. ssl->options.handShakeDone = 1;
  14211. }
  14212. }
  14213. else {
  14214. if (ssl->options.side == WOLFSSL_CLIENT_END) {
  14215. #ifdef OPENSSL_EXTRA
  14216. ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
  14217. ssl->cbmode = SSL_CB_MODE_WRITE;
  14218. if (ssl->CBIS != NULL)
  14219. ssl->CBIS(ssl, SSL_CB_HANDSHAKE_DONE, SSL_SUCCESS);
  14220. #endif
  14221. ssl->options.handShakeState = HANDSHAKE_DONE;
  14222. ssl->options.handShakeDone = 1;
  14223. }
  14224. }
  14225. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  14226. if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
  14227. if (ssl->toInfoOn)
  14228. AddPacketInfo(ssl, "Finished", handshake, output, sendSz,
  14229. WRITE_PROTO, ssl->heap);
  14230. #endif
  14231. ssl->buffers.outputBuffer.length += sendSz;
  14232. ret = SendBuffered(ssl);
  14233. WOLFSSL_LEAVE("SendFinished", ret);
  14234. WOLFSSL_END(WC_FUNC_FINISHED_SEND);
  14235. return ret;
  14236. }
  14237. #endif /* WOLFSSL_NO_TLS12 */
  14238. #ifndef NO_WOLFSSL_SERVER
  14239. #if (!defined(WOLFSSL_NO_TLS12) && \
  14240. (defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
  14241. defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))) || \
  14242. (defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST))
  14243. /* Parses and decodes the certificate then initializes "request". In the case
  14244. * of !ssl->buffers.weOwnCert, ssl->ctx->certOcspRequest gets set to "request".
  14245. *
  14246. * Returns 0 on success
  14247. */
  14248. static int CreateOcspRequest(WOLFSSL* ssl, OcspRequest* request,
  14249. DecodedCert* cert, byte* certData, word32 length)
  14250. {
  14251. int ret;
  14252. if (request != NULL)
  14253. XMEMSET(request, 0, sizeof(OcspRequest));
  14254. InitDecodedCert(cert, certData, length, ssl->heap);
  14255. /* TODO: Setup async support here */
  14256. ret = ParseCertRelative(cert, CERT_TYPE, VERIFY, ssl->ctx->cm);
  14257. if (ret != 0) {
  14258. WOLFSSL_MSG("ParseCert failed");
  14259. }
  14260. if (ret == 0)
  14261. ret = InitOcspRequest(request, cert, 0, ssl->heap);
  14262. if (ret == 0) {
  14263. /* make sure ctx OCSP request is updated */
  14264. if (!ssl->buffers.weOwnCert) {
  14265. wolfSSL_Mutex* ocspLock = &ssl->ctx->cm->ocsp_stapling->ocspLock;
  14266. if (wc_LockMutex(ocspLock) == 0) {
  14267. if (ssl->ctx->certOcspRequest == NULL)
  14268. ssl->ctx->certOcspRequest = request;
  14269. wc_UnLockMutex(ocspLock);
  14270. }
  14271. }
  14272. }
  14273. FreeDecodedCert(cert);
  14274. return ret;
  14275. }
  14276. /* Creates OCSP response and places it in variable "response". Memory
  14277. * management for "buffer* response" is up to the caller.
  14278. *
  14279. * Also creates an OcspRequest in the case that ocspRequest is null or that
  14280. * ssl->buffers.weOwnCert is set. In those cases managing ocspRequest free'ing
  14281. * is up to the caller. NOTE: in OcspCreateRequest ssl->ctx->certOcspRequest can
  14282. * be set to point to "ocspRequest" and it then should not be free'd since
  14283. * wolfSSL_CTX_free will take care of it.
  14284. *
  14285. * Returns 0 on success
  14286. */
  14287. int CreateOcspResponse(WOLFSSL* ssl, OcspRequest** ocspRequest,
  14288. buffer* response)
  14289. {
  14290. int ret = 0;
  14291. OcspRequest* request = NULL;
  14292. byte createdRequest = 0;
  14293. if (ssl == NULL || ocspRequest == NULL || response == NULL)
  14294. return BAD_FUNC_ARG;
  14295. XMEMSET(response, 0, sizeof(*response));
  14296. request = *ocspRequest;
  14297. /* unable to fetch status. skip. */
  14298. if (ssl->ctx->cm == NULL || ssl->ctx->cm->ocspStaplingEnabled == 0)
  14299. return 0;
  14300. if (request == NULL || ssl->buffers.weOwnCert) {
  14301. DerBuffer* der = ssl->buffers.certificate;
  14302. #ifdef WOLFSSL_SMALL_STACK
  14303. DecodedCert* cert = NULL;
  14304. #else
  14305. DecodedCert cert[1];
  14306. #endif
  14307. /* unable to fetch status. skip. */
  14308. if (der->buffer == NULL || der->length == 0)
  14309. return 0;
  14310. #ifdef WOLFSSL_SMALL_STACK
  14311. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
  14312. DYNAMIC_TYPE_DCERT);
  14313. if (cert == NULL)
  14314. return MEMORY_E;
  14315. #endif
  14316. request = (OcspRequest*)XMALLOC(sizeof(OcspRequest), ssl->heap,
  14317. DYNAMIC_TYPE_OCSP_REQUEST);
  14318. if (request == NULL)
  14319. ret = MEMORY_E;
  14320. createdRequest = 1;
  14321. if (ret == 0) {
  14322. ret = CreateOcspRequest(ssl, request, cert, der->buffer,
  14323. der->length);
  14324. }
  14325. if (ret != 0) {
  14326. XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  14327. request = NULL;
  14328. }
  14329. #ifdef WOLFSSL_SMALL_STACK
  14330. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  14331. #endif
  14332. }
  14333. if (ret == 0) {
  14334. request->ssl = ssl;
  14335. ret = CheckOcspRequest(ssl->ctx->cm->ocsp_stapling, request, response);
  14336. /* Suppressing, not critical */
  14337. if (ret == OCSP_CERT_REVOKED ||
  14338. ret == OCSP_CERT_UNKNOWN ||
  14339. ret == OCSP_LOOKUP_FAIL) {
  14340. ret = 0;
  14341. }
  14342. }
  14343. /* free request up if error case found otherwise return it */
  14344. if (ret != 0 && createdRequest) {
  14345. FreeOcspRequest(request);
  14346. XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  14347. }
  14348. if (ret == 0)
  14349. *ocspRequest = request;
  14350. return ret;
  14351. }
  14352. #endif
  14353. #endif /* !NO_WOLFSSL_SERVER */
  14354. #ifndef WOLFSSL_NO_TLS12
  14355. #ifndef NO_CERTS
  14356. #if !defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)
  14357. /* handle generation of certificate (11) */
  14358. int SendCertificate(WOLFSSL* ssl)
  14359. {
  14360. int ret = 0;
  14361. word32 certSz, certChainSz, headerSz, listSz, payloadSz;
  14362. word32 length, maxFragment;
  14363. WOLFSSL_START(WC_FUNC_CERTIFICATE_SEND);
  14364. WOLFSSL_ENTER("SendCertificate");
  14365. if (ssl->options.usingPSK_cipher || ssl->options.usingAnon_cipher)
  14366. return 0; /* not needed */
  14367. if (ssl->options.sendVerify == SEND_BLANK_CERT) {
  14368. #ifdef OPENSSL_EXTRA
  14369. if (ssl->version.major == SSLv3_MAJOR
  14370. && ssl->version.minor == SSLv3_MINOR){
  14371. SendAlert(ssl, alert_warning, no_certificate);
  14372. return 0;
  14373. } else {
  14374. #endif
  14375. certSz = 0;
  14376. certChainSz = 0;
  14377. headerSz = CERT_HEADER_SZ;
  14378. length = CERT_HEADER_SZ;
  14379. listSz = 0;
  14380. #ifdef OPENSSL_EXTRA
  14381. }
  14382. #endif
  14383. }
  14384. else {
  14385. if (!ssl->buffers.certificate) {
  14386. WOLFSSL_MSG("Send Cert missing certificate buffer");
  14387. return BUFFER_ERROR;
  14388. }
  14389. certSz = ssl->buffers.certificate->length;
  14390. headerSz = 2 * CERT_HEADER_SZ;
  14391. /* list + cert size */
  14392. length = certSz + headerSz;
  14393. listSz = certSz + CERT_HEADER_SZ;
  14394. /* may need to send rest of chain, already has leading size(s) */
  14395. if (certSz && ssl->buffers.certChain) {
  14396. certChainSz = ssl->buffers.certChain->length;
  14397. length += certChainSz;
  14398. listSz += certChainSz;
  14399. }
  14400. else
  14401. certChainSz = 0;
  14402. }
  14403. payloadSz = length;
  14404. if (ssl->fragOffset != 0)
  14405. length -= (ssl->fragOffset + headerSz);
  14406. maxFragment = MAX_RECORD_SIZE;
  14407. if (ssl->options.dtls) {
  14408. #ifdef WOLFSSL_DTLS
  14409. /* The 100 bytes is used to account for the UDP and IP headers.
  14410. It can also include the record padding and MAC if the
  14411. SendCertificate is called for a secure renegotiation. */
  14412. maxFragment = MAX_MTU - DTLS_RECORD_HEADER_SZ
  14413. - DTLS_HANDSHAKE_HEADER_SZ - 100;
  14414. #endif /* WOLFSSL_DTLS */
  14415. }
  14416. maxFragment = wolfSSL_GetMaxRecordSize(ssl, maxFragment);
  14417. while (length > 0 && ret == 0) {
  14418. byte* output = NULL;
  14419. word32 fragSz = 0;
  14420. word32 i = RECORD_HEADER_SZ;
  14421. int sendSz = RECORD_HEADER_SZ;
  14422. if (!ssl->options.dtls) {
  14423. if (ssl->fragOffset == 0) {
  14424. if (headerSz + certSz + certChainSz <=
  14425. maxFragment - HANDSHAKE_HEADER_SZ) {
  14426. fragSz = headerSz + certSz + certChainSz;
  14427. }
  14428. else {
  14429. fragSz = maxFragment - HANDSHAKE_HEADER_SZ;
  14430. }
  14431. sendSz += fragSz + HANDSHAKE_HEADER_SZ;
  14432. i += HANDSHAKE_HEADER_SZ;
  14433. }
  14434. else {
  14435. fragSz = min(length, maxFragment);
  14436. sendSz += fragSz;
  14437. }
  14438. if (IsEncryptionOn(ssl, 1))
  14439. sendSz += MAX_MSG_EXTRA;
  14440. }
  14441. else {
  14442. #ifdef WOLFSSL_DTLS
  14443. fragSz = min(length, maxFragment);
  14444. sendSz += fragSz + DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA
  14445. + HANDSHAKE_HEADER_SZ;
  14446. i += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA
  14447. + HANDSHAKE_HEADER_SZ;
  14448. #endif
  14449. }
  14450. /* check for available size */
  14451. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  14452. return ret;
  14453. /* get output buffer */
  14454. output = ssl->buffers.outputBuffer.buffer +
  14455. ssl->buffers.outputBuffer.length;
  14456. if (ssl->fragOffset == 0) {
  14457. if (!ssl->options.dtls) {
  14458. AddFragHeaders(output, fragSz, 0, payloadSz, certificate, ssl);
  14459. if (!IsEncryptionOn(ssl, 1))
  14460. HashOutputRaw(ssl, output + RECORD_HEADER_SZ,
  14461. HANDSHAKE_HEADER_SZ);
  14462. }
  14463. else {
  14464. #ifdef WOLFSSL_DTLS
  14465. AddHeaders(output, payloadSz, certificate, ssl);
  14466. if (!IsEncryptionOn(ssl, 1))
  14467. HashOutputRaw(ssl,
  14468. output + RECORD_HEADER_SZ + DTLS_RECORD_EXTRA,
  14469. HANDSHAKE_HEADER_SZ + DTLS_HANDSHAKE_EXTRA);
  14470. /* Adding the headers increments these, decrement them for
  14471. * actual message header. */
  14472. ssl->keys.dtls_handshake_number--;
  14473. AddFragHeaders(output, fragSz, 0, payloadSz, certificate, ssl);
  14474. ssl->keys.dtls_handshake_number--;
  14475. #endif /* WOLFSSL_DTLS */
  14476. }
  14477. /* list total */
  14478. c32to24(listSz, output + i);
  14479. if (!IsEncryptionOn(ssl, 1))
  14480. HashOutputRaw(ssl, output + i, CERT_HEADER_SZ);
  14481. i += CERT_HEADER_SZ;
  14482. length -= CERT_HEADER_SZ;
  14483. fragSz -= CERT_HEADER_SZ;
  14484. if (certSz) {
  14485. c32to24(certSz, output + i);
  14486. if (!IsEncryptionOn(ssl, 1))
  14487. HashOutputRaw(ssl, output + i, CERT_HEADER_SZ);
  14488. i += CERT_HEADER_SZ;
  14489. length -= CERT_HEADER_SZ;
  14490. fragSz -= CERT_HEADER_SZ;
  14491. if (!IsEncryptionOn(ssl, 1)) {
  14492. HashOutputRaw(ssl, ssl->buffers.certificate->buffer, certSz);
  14493. if (certChainSz)
  14494. HashOutputRaw(ssl, ssl->buffers.certChain->buffer,
  14495. certChainSz);
  14496. }
  14497. }
  14498. }
  14499. else {
  14500. if (!ssl->options.dtls) {
  14501. AddRecordHeader(output, fragSz, handshake, ssl);
  14502. }
  14503. else {
  14504. #ifdef WOLFSSL_DTLS
  14505. AddFragHeaders(output, fragSz, ssl->fragOffset + headerSz,
  14506. payloadSz, certificate, ssl);
  14507. ssl->keys.dtls_handshake_number--;
  14508. #endif /* WOLFSSL_DTLS */
  14509. }
  14510. }
  14511. /* member */
  14512. if (certSz && ssl->fragOffset < certSz) {
  14513. word32 copySz = min(certSz - ssl->fragOffset, fragSz);
  14514. XMEMCPY(output + i,
  14515. ssl->buffers.certificate->buffer + ssl->fragOffset, copySz);
  14516. i += copySz;
  14517. ssl->fragOffset += copySz;
  14518. length -= copySz;
  14519. fragSz -= copySz;
  14520. }
  14521. if (certChainSz && fragSz) {
  14522. word32 copySz = min(certChainSz + certSz - ssl->fragOffset, fragSz);
  14523. XMEMCPY(output + i,
  14524. ssl->buffers.certChain->buffer + ssl->fragOffset - certSz,
  14525. copySz);
  14526. i += copySz;
  14527. ssl->fragOffset += copySz;
  14528. length -= copySz;
  14529. }
  14530. if (IsEncryptionOn(ssl, 1)) {
  14531. byte* input = NULL;
  14532. int inputSz = i - RECORD_HEADER_SZ; /* build msg adds rec hdr */
  14533. if (inputSz < 0) {
  14534. WOLFSSL_MSG("Send Cert bad inputSz");
  14535. return BUFFER_E;
  14536. }
  14537. if (inputSz > 0) { /* clang thinks could be zero, let's help */
  14538. input = (byte*)XMALLOC(inputSz, ssl->heap,
  14539. DYNAMIC_TYPE_IN_BUFFER);
  14540. if (input == NULL)
  14541. return MEMORY_E;
  14542. XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
  14543. }
  14544. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  14545. handshake, 1, 0, 0);
  14546. if (inputSz > 0)
  14547. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  14548. if (sendSz < 0)
  14549. return sendSz;
  14550. }
  14551. else {
  14552. #ifdef WOLFSSL_DTLS
  14553. if (ssl->options.dtls)
  14554. DtlsSEQIncrement(ssl, CUR_ORDER);
  14555. #endif
  14556. }
  14557. #ifdef WOLFSSL_DTLS
  14558. if (IsDtlsNotSctpMode(ssl)) {
  14559. if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
  14560. return ret;
  14561. }
  14562. #endif
  14563. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  14564. if (ssl->hsInfoOn)
  14565. AddPacketName(ssl, "Certificate");
  14566. if (ssl->toInfoOn)
  14567. AddPacketInfo(ssl, "Certificate", handshake, output, sendSz,
  14568. WRITE_PROTO, ssl->heap);
  14569. #endif
  14570. ssl->buffers.outputBuffer.length += sendSz;
  14571. if (!ssl->options.groupMessages)
  14572. ret = SendBuffered(ssl);
  14573. }
  14574. if (ret != WANT_WRITE) {
  14575. /* Clean up the fragment offset. */
  14576. ssl->fragOffset = 0;
  14577. #ifdef WOLFSSL_DTLS
  14578. if (ssl->options.dtls)
  14579. ssl->keys.dtls_handshake_number++;
  14580. #endif
  14581. if (ssl->options.side == WOLFSSL_SERVER_END){
  14582. ssl->options.serverState = SERVER_CERT_COMPLETE;
  14583. }
  14584. }
  14585. WOLFSSL_LEAVE("SendCertificate", ret);
  14586. WOLFSSL_END(WC_FUNC_CERTIFICATE_SEND);
  14587. return ret;
  14588. }
  14589. #endif /* !NO_WOLFSSL_SERVER || !WOLFSSL_NO_CLIENT_AUTH */
  14590. /* handle generation of certificate_request (13) */
  14591. int SendCertificateRequest(WOLFSSL* ssl)
  14592. {
  14593. byte *output;
  14594. int ret;
  14595. int sendSz;
  14596. word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  14597. word32 dnLen = 0;
  14598. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  14599. WOLF_STACK_OF(WOLFSSL_X509_NAME)* names;
  14600. #endif
  14601. int typeTotal = 1; /* only 1 for now */
  14602. int reqSz = ENUM_LEN + typeTotal + REQ_HEADER_SZ; /* add auth later */
  14603. WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_SEND);
  14604. WOLFSSL_ENTER("SendCertificateRequest");
  14605. if (IsAtLeastTLSv1_2(ssl))
  14606. reqSz += LENGTH_SZ + ssl->suites->hashSigAlgoSz;
  14607. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  14608. /* Certificate Authorities */
  14609. names = ssl->ctx->ca_names;
  14610. while (names != NULL) {
  14611. byte seq[MAX_SEQ_SZ];
  14612. /* 16-bit length | SEQ | Len | DER of name */
  14613. dnLen += OPAQUE16_LEN + SetSequence(names->data.name->rawLen, seq) +
  14614. names->data.name->rawLen;
  14615. names = names->next;
  14616. }
  14617. reqSz += dnLen;
  14618. #endif
  14619. if (ssl->options.usingPSK_cipher || ssl->options.usingAnon_cipher)
  14620. return 0; /* not needed */
  14621. sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + reqSz;
  14622. if (!ssl->options.dtls) {
  14623. if (IsEncryptionOn(ssl, 1))
  14624. sendSz += MAX_MSG_EXTRA;
  14625. }
  14626. else {
  14627. #ifdef WOLFSSL_DTLS
  14628. sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  14629. i += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  14630. #endif
  14631. }
  14632. /* check for available size */
  14633. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  14634. return ret;
  14635. /* get output buffer */
  14636. output = ssl->buffers.outputBuffer.buffer +
  14637. ssl->buffers.outputBuffer.length;
  14638. AddHeaders(output, reqSz, certificate_request, ssl);
  14639. /* write to output */
  14640. output[i++] = (byte)typeTotal; /* # of types */
  14641. #ifdef HAVE_ECC
  14642. if ((ssl->options.cipherSuite0 == ECC_BYTE ||
  14643. ssl->options.cipherSuite0 == CHACHA_BYTE) &&
  14644. ssl->specs.sig_algo == ecc_dsa_sa_algo) {
  14645. output[i++] = ecdsa_sign;
  14646. } else
  14647. #endif /* HAVE_ECC */
  14648. {
  14649. output[i++] = rsa_sign;
  14650. }
  14651. /* supported hash/sig */
  14652. if (IsAtLeastTLSv1_2(ssl)) {
  14653. c16toa(ssl->suites->hashSigAlgoSz, &output[i]);
  14654. i += OPAQUE16_LEN;
  14655. XMEMCPY(&output[i],
  14656. ssl->suites->hashSigAlgo, ssl->suites->hashSigAlgoSz);
  14657. i += ssl->suites->hashSigAlgoSz;
  14658. }
  14659. /* Certificate Authorities */
  14660. c16toa((word16)dnLen, &output[i]); /* auth's */
  14661. i += REQ_HEADER_SZ;
  14662. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  14663. names = ssl->ctx->ca_names;
  14664. while (names != NULL) {
  14665. byte seq[MAX_SEQ_SZ];
  14666. c16toa((word16)names->data.name->rawLen +
  14667. SetSequence(names->data.name->rawLen, seq), &output[i]);
  14668. i += OPAQUE16_LEN;
  14669. i += SetSequence(names->data.name->rawLen, output + i);
  14670. XMEMCPY(output + i, names->data.name->raw, names->data.name->rawLen);
  14671. i += names->data.name->rawLen;
  14672. names = names->next;
  14673. }
  14674. #endif
  14675. (void)i;
  14676. if (IsEncryptionOn(ssl, 1)) {
  14677. byte* input;
  14678. int inputSz = i - RECORD_HEADER_SZ; /* build msg adds rec hdr */
  14679. input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  14680. if (input == NULL)
  14681. return MEMORY_E;
  14682. XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
  14683. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  14684. handshake, 1, 0, 0);
  14685. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  14686. if (sendSz < 0)
  14687. return sendSz;
  14688. } else {
  14689. #ifdef WOLFSSL_DTLS
  14690. if (ssl->options.dtls)
  14691. DtlsSEQIncrement(ssl, CUR_ORDER);
  14692. if (IsDtlsNotSctpMode(ssl)) {
  14693. if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
  14694. return ret;
  14695. }
  14696. #endif
  14697. ret = HashOutput(ssl, output, sendSz, 0);
  14698. if (ret != 0)
  14699. return ret;
  14700. }
  14701. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  14702. if (ssl->hsInfoOn)
  14703. AddPacketName(ssl, "CertificateRequest");
  14704. if (ssl->toInfoOn)
  14705. AddPacketInfo(ssl, "CertificateRequest", handshake, output, sendSz,
  14706. WRITE_PROTO, ssl->heap);
  14707. #endif
  14708. ssl->buffers.outputBuffer.length += sendSz;
  14709. if (ssl->options.groupMessages)
  14710. ret = 0;
  14711. else
  14712. ret = SendBuffered(ssl);
  14713. WOLFSSL_LEAVE("SendCertificateRequest", ret);
  14714. WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
  14715. return ret;
  14716. }
  14717. #ifndef NO_WOLFSSL_SERVER
  14718. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  14719. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  14720. static int BuildCertificateStatus(WOLFSSL* ssl, byte type, buffer* status,
  14721. byte count)
  14722. {
  14723. byte* output = NULL;
  14724. word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  14725. word32 length = ENUM_LEN;
  14726. int sendSz = 0;
  14727. int ret = 0;
  14728. int i = 0;
  14729. WOLFSSL_ENTER("BuildCertificateStatus");
  14730. switch (type) {
  14731. case WOLFSSL_CSR2_OCSP_MULTI:
  14732. length += OPAQUE24_LEN;
  14733. FALL_THROUGH; /* followed by */
  14734. case WOLFSSL_CSR2_OCSP:
  14735. for (i = 0; i < count; i++)
  14736. length += OPAQUE24_LEN + status[i].length;
  14737. break;
  14738. default:
  14739. return 0;
  14740. }
  14741. sendSz = idx + length;
  14742. if (ssl->keys.encryptionOn)
  14743. sendSz += MAX_MSG_EXTRA;
  14744. if ((ret = CheckAvailableSize(ssl, sendSz)) == 0) {
  14745. output = ssl->buffers.outputBuffer.buffer +
  14746. ssl->buffers.outputBuffer.length;
  14747. AddHeaders(output, length, certificate_status, ssl);
  14748. output[idx++] = type;
  14749. if (type == WOLFSSL_CSR2_OCSP_MULTI) {
  14750. c32to24(length - (ENUM_LEN + OPAQUE24_LEN), output + idx);
  14751. idx += OPAQUE24_LEN;
  14752. }
  14753. for (i = 0; i < count; i++) {
  14754. c32to24(status[i].length, output + idx);
  14755. idx += OPAQUE24_LEN;
  14756. XMEMCPY(output + idx, status[i].buffer, status[i].length);
  14757. idx += status[i].length;
  14758. }
  14759. if (IsEncryptionOn(ssl, 1)) {
  14760. byte* input;
  14761. int inputSz = idx - RECORD_HEADER_SZ;
  14762. input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  14763. if (input == NULL)
  14764. return MEMORY_E;
  14765. XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
  14766. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  14767. handshake, 1, 0, 0);
  14768. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  14769. if (sendSz < 0)
  14770. ret = sendSz;
  14771. }
  14772. else {
  14773. #ifdef WOLFSSL_DTLS
  14774. if (ssl->options.dtls)
  14775. DtlsSEQIncrement(ssl, CUR_ORDER);
  14776. #endif
  14777. ret = HashOutput(ssl, output, sendSz, 0);
  14778. }
  14779. #ifdef WOLFSSL_DTLS
  14780. if (ret == 0 && IsDtlsNotSctpMode(ssl))
  14781. ret = DtlsMsgPoolSave(ssl, output, sendSz);
  14782. #endif
  14783. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  14784. if (ret == 0 && ssl->hsInfoOn)
  14785. AddPacketName(ssl, "CertificateStatus");
  14786. if (ret == 0 && ssl->toInfoOn)
  14787. AddPacketInfo(ssl, "CertificateStatus", handshake, output, sendSz,
  14788. WRITE_PROTO, ssl->heap);
  14789. #endif
  14790. if (ret == 0) {
  14791. ssl->buffers.outputBuffer.length += sendSz;
  14792. if (!ssl->options.groupMessages)
  14793. ret = SendBuffered(ssl);
  14794. }
  14795. }
  14796. WOLFSSL_LEAVE("BuildCertificateStatus", ret);
  14797. return ret;
  14798. }
  14799. #endif
  14800. #endif /* NO_WOLFSSL_SERVER */
  14801. /* handle generation of certificate_status (22) */
  14802. int SendCertificateStatus(WOLFSSL* ssl)
  14803. {
  14804. int ret = 0;
  14805. byte status_type = 0;
  14806. WOLFSSL_START(WC_FUNC_CERTIFICATE_STATUS_SEND);
  14807. WOLFSSL_ENTER("SendCertificateStatus");
  14808. (void) ssl;
  14809. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
  14810. status_type = ssl->status_request;
  14811. #endif
  14812. #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
  14813. status_type = status_type ? status_type : ssl->status_request_v2;
  14814. #endif
  14815. switch (status_type) {
  14816. #ifndef NO_WOLFSSL_SERVER
  14817. #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  14818. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
  14819. /* case WOLFSSL_CSR_OCSP: */
  14820. case WOLFSSL_CSR2_OCSP:
  14821. {
  14822. OcspRequest* request = ssl->ctx->certOcspRequest;
  14823. buffer response;
  14824. ret = CreateOcspResponse(ssl, &request, &response);
  14825. /* if a request was successfully created and not stored in
  14826. * ssl->ctx then free it */
  14827. if (ret == 0 && request != ssl->ctx->certOcspRequest) {
  14828. FreeOcspRequest(request);
  14829. XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  14830. request = NULL;
  14831. }
  14832. if (ret == 0 && response.buffer) {
  14833. ret = BuildCertificateStatus(ssl, status_type, &response, 1);
  14834. XFREE(response.buffer, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  14835. response.buffer = NULL;
  14836. }
  14837. break;
  14838. }
  14839. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
  14840. /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  14841. #if defined HAVE_CERTIFICATE_STATUS_REQUEST_V2
  14842. case WOLFSSL_CSR2_OCSP_MULTI:
  14843. {
  14844. OcspRequest* request = ssl->ctx->certOcspRequest;
  14845. buffer responses[1 + MAX_CHAIN_DEPTH];
  14846. int i = 0;
  14847. XMEMSET(responses, 0, sizeof(responses));
  14848. ret = CreateOcspResponse(ssl, &request, &responses[0]);
  14849. /* if a request was successfully created and not stored in
  14850. * ssl->ctx then free it */
  14851. if (ret == 0 && request != ssl->ctx->certOcspRequest) {
  14852. FreeOcspRequest(request);
  14853. XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  14854. request = NULL;
  14855. }
  14856. if (ret == 0 && (!ssl->ctx->chainOcspRequest[0]
  14857. || ssl->buffers.weOwnCertChain)) {
  14858. buffer der;
  14859. word32 idx = 0;
  14860. #ifdef WOLFSSL_SMALL_STACK
  14861. DecodedCert* cert;
  14862. #else
  14863. DecodedCert cert[1];
  14864. #endif
  14865. #ifdef WOLFSSL_SMALL_STACK
  14866. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
  14867. DYNAMIC_TYPE_DCERT);
  14868. if (cert == NULL)
  14869. return MEMORY_E;
  14870. #endif
  14871. request = (OcspRequest*)XMALLOC(sizeof(OcspRequest), ssl->heap,
  14872. DYNAMIC_TYPE_OCSP_REQUEST);
  14873. if (request == NULL) {
  14874. #ifdef WOLFSSL_SMALL_STACK
  14875. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  14876. #endif
  14877. return MEMORY_E;
  14878. }
  14879. while (idx + OPAQUE24_LEN < ssl->buffers.certChain->length) {
  14880. c24to32(ssl->buffers.certChain->buffer + idx, &der.length);
  14881. idx += OPAQUE24_LEN;
  14882. der.buffer = ssl->buffers.certChain->buffer + idx;
  14883. idx += der.length;
  14884. if (idx > ssl->buffers.certChain->length)
  14885. break;
  14886. ret = CreateOcspRequest(ssl, request, cert, der.buffer,
  14887. der.length);
  14888. if (ret == 0) {
  14889. request->ssl = ssl;
  14890. ret = CheckOcspRequest(ssl->ctx->cm->ocsp_stapling,
  14891. request, &responses[i + 1]);
  14892. /* Suppressing, not critical */
  14893. if (ret == OCSP_CERT_REVOKED ||
  14894. ret == OCSP_CERT_UNKNOWN ||
  14895. ret == OCSP_LOOKUP_FAIL) {
  14896. ret = 0;
  14897. }
  14898. i++;
  14899. FreeOcspRequest(request);
  14900. }
  14901. }
  14902. XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  14903. #ifdef WOLFSSL_SMALL_STACK
  14904. XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
  14905. #endif
  14906. }
  14907. else {
  14908. while (ret == 0 &&
  14909. NULL != (request = ssl->ctx->chainOcspRequest[i])) {
  14910. request->ssl = ssl;
  14911. ret = CheckOcspRequest(ssl->ctx->cm->ocsp_stapling,
  14912. request, &responses[++i]);
  14913. /* Suppressing, not critical */
  14914. if (ret == OCSP_CERT_REVOKED ||
  14915. ret == OCSP_CERT_UNKNOWN ||
  14916. ret == OCSP_LOOKUP_FAIL) {
  14917. ret = 0;
  14918. }
  14919. }
  14920. }
  14921. if (responses[0].buffer) {
  14922. if (ret == 0) {
  14923. ret = BuildCertificateStatus(ssl, status_type, responses,
  14924. (byte)i + 1);
  14925. }
  14926. for (i = 0; i < 1 + MAX_CHAIN_DEPTH; i++) {
  14927. if (responses[i].buffer) {
  14928. XFREE(responses[i].buffer, ssl->heap,
  14929. DYNAMIC_TYPE_OCSP_REQUEST);
  14930. }
  14931. }
  14932. }
  14933. break;
  14934. }
  14935. #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
  14936. #endif /* NO_WOLFSSL_SERVER */
  14937. default:
  14938. break;
  14939. }
  14940. WOLFSSL_LEAVE("SendCertificateStatus", ret);
  14941. WOLFSSL_END(WC_FUNC_CERTIFICATE_STATUS_SEND);
  14942. return ret;
  14943. }
  14944. #endif /* !NO_CERTS */
  14945. #endif /* WOLFSSL_NO_TLS12 */
  14946. /* If secure renegotiation is disabled, this will always return false.
  14947. * Otherwise it checks to see if we are currently renegotiating. */
  14948. static WC_INLINE int IsSCR(WOLFSSL* ssl)
  14949. {
  14950. #ifndef HAVE_SECURE_RENEGOTIATION
  14951. (void)ssl;
  14952. #else /* HAVE_SECURE_RENEGOTIATION */
  14953. if (ssl->secure_renegotiation &&
  14954. ssl->secure_renegotiation->enabled &&
  14955. ssl->options.handShakeState != HANDSHAKE_DONE)
  14956. return 1;
  14957. #endif /* HAVE_SECURE_RENEGOTIATION */
  14958. return 0;
  14959. }
  14960. int SendData(WOLFSSL* ssl, const void* data, int sz)
  14961. {
  14962. int sent = 0, /* plainText size */
  14963. sendSz,
  14964. ret,
  14965. dtlsExtra = 0;
  14966. int groupMsgs = 0;
  14967. if (ssl->error == WANT_WRITE
  14968. #ifdef WOLFSSL_ASYNC_CRYPT
  14969. || ssl->error == WC_PENDING_E
  14970. #endif
  14971. ) {
  14972. ssl->error = 0;
  14973. }
  14974. /* don't allow write after decrypt or mac error */
  14975. if (ssl->error == VERIFY_MAC_ERROR || ssl->error == DECRYPT_ERROR) {
  14976. /* For DTLS allow these possible errors and allow the session
  14977. to continue despite them */
  14978. if (ssl->options.dtls) {
  14979. ssl->error = 0;
  14980. }
  14981. else {
  14982. WOLFSSL_MSG("Not allowing write after decrypt or mac error");
  14983. return WOLFSSL_FATAL_ERROR;
  14984. }
  14985. }
  14986. #ifdef WOLFSSL_EARLY_DATA
  14987. if (ssl->earlyData != no_early_data) {
  14988. if (ssl->options.handShakeState == HANDSHAKE_DONE) {
  14989. WOLFSSL_MSG("handshake complete, trying to send early data");
  14990. return BUILD_MSG_ERROR;
  14991. }
  14992. #ifdef WOLFSSL_EARLY_DATA_GROUP
  14993. groupMsgs = 1;
  14994. #endif
  14995. }
  14996. else
  14997. #endif
  14998. if (ssl->options.handShakeState != HANDSHAKE_DONE && !IsSCR(ssl)) {
  14999. int err;
  15000. WOLFSSL_MSG("handshake not complete, trying to finish");
  15001. if ( (err = wolfSSL_negotiate(ssl)) != WOLFSSL_SUCCESS) {
  15002. #ifdef WOLFSSL_ASYNC_CRYPT
  15003. /* if async would block return WANT_WRITE */
  15004. if (ssl->error == WC_PENDING_E) {
  15005. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  15006. }
  15007. #endif
  15008. return err;
  15009. }
  15010. }
  15011. /* last time system socket output buffer was full, try again to send */
  15012. if (!groupMsgs && ssl->buffers.outputBuffer.length > 0) {
  15013. WOLFSSL_MSG("output buffer was full, trying to send again");
  15014. if ( (ssl->error = SendBuffered(ssl)) < 0) {
  15015. WOLFSSL_ERROR(ssl->error);
  15016. if (ssl->error == SOCKET_ERROR_E && (ssl->options.connReset ||
  15017. ssl->options.isClosed)) {
  15018. ssl->error = SOCKET_PEER_CLOSED_E;
  15019. WOLFSSL_ERROR(ssl->error);
  15020. return 0; /* peer reset or closed */
  15021. }
  15022. return ssl->error;
  15023. }
  15024. else {
  15025. /* advance sent to previous sent + plain size just sent */
  15026. sent = ssl->buffers.prevSent + ssl->buffers.plainSz;
  15027. WOLFSSL_MSG("sent write buffered data");
  15028. if (sent > sz) {
  15029. WOLFSSL_MSG("error: write() after WANT_WRITE with short size");
  15030. return ssl->error = BAD_FUNC_ARG;
  15031. }
  15032. }
  15033. }
  15034. #ifdef WOLFSSL_DTLS
  15035. if (ssl->options.dtls) {
  15036. dtlsExtra = DTLS_RECORD_EXTRA;
  15037. }
  15038. #endif
  15039. for (;;) {
  15040. int len;
  15041. byte* out;
  15042. byte* sendBuffer = (byte*)data + sent; /* may switch on comp */
  15043. int buffSz; /* may switch on comp */
  15044. int outputSz;
  15045. #ifdef HAVE_LIBZ
  15046. byte comp[MAX_RECORD_SIZE + MAX_COMP_EXTRA];
  15047. #endif
  15048. if (sent == sz) break;
  15049. len = wolfSSL_GetMaxRecordSize(ssl, sz - sent);
  15050. #ifdef WOLFSSL_DTLS
  15051. if (IsDtlsNotSctpMode(ssl)) {
  15052. len = min(len, MAX_UDP_SIZE);
  15053. }
  15054. #endif
  15055. buffSz = len;
  15056. /* check for available size */
  15057. outputSz = len + COMP_EXTRA + dtlsExtra + MAX_MSG_EXTRA;
  15058. if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
  15059. return ssl->error = ret;
  15060. /* get output buffer */
  15061. out = ssl->buffers.outputBuffer.buffer +
  15062. ssl->buffers.outputBuffer.length;
  15063. #ifdef HAVE_LIBZ
  15064. if (ssl->options.usingCompression) {
  15065. buffSz = myCompress(ssl, sendBuffer, buffSz, comp, sizeof(comp));
  15066. if (buffSz < 0) {
  15067. return buffSz;
  15068. }
  15069. sendBuffer = comp;
  15070. }
  15071. #endif
  15072. if (!ssl->options.tls1_3) {
  15073. sendSz = BuildMessage(ssl, out, outputSz, sendBuffer, buffSz,
  15074. application_data, 0, 0, 1);
  15075. }
  15076. else {
  15077. #ifdef WOLFSSL_TLS13
  15078. sendSz = BuildTls13Message(ssl, out, outputSz, sendBuffer, buffSz,
  15079. application_data, 0, 0, 1);
  15080. #else
  15081. sendSz = BUFFER_ERROR;
  15082. #endif
  15083. }
  15084. if (sendSz < 0) {
  15085. #ifdef WOLFSSL_ASYNC_CRYPT
  15086. if (sendSz == WC_PENDING_E)
  15087. ssl->error = sendSz;
  15088. #endif
  15089. return BUILD_MSG_ERROR;
  15090. }
  15091. ssl->buffers.outputBuffer.length += sendSz;
  15092. if ( (ssl->error = SendBuffered(ssl)) < 0) {
  15093. WOLFSSL_ERROR(ssl->error);
  15094. /* store for next call if WANT_WRITE or user embedSend() that
  15095. doesn't present like WANT_WRITE */
  15096. ssl->buffers.plainSz = len;
  15097. ssl->buffers.prevSent = sent;
  15098. if (ssl->error == SOCKET_ERROR_E && (ssl->options.connReset ||
  15099. ssl->options.isClosed)) {
  15100. ssl->error = SOCKET_PEER_CLOSED_E;
  15101. WOLFSSL_ERROR(ssl->error);
  15102. return 0; /* peer reset or closed */
  15103. }
  15104. return ssl->error;
  15105. }
  15106. sent += len;
  15107. /* only one message per attempt */
  15108. if (ssl->options.partialWrite == 1) {
  15109. WOLFSSL_MSG("Partial Write on, only sending one record");
  15110. break;
  15111. }
  15112. }
  15113. return sent;
  15114. }
  15115. /* process input data */
  15116. int ReceiveData(WOLFSSL* ssl, byte* output, int sz, int peek)
  15117. {
  15118. int size;
  15119. WOLFSSL_ENTER("ReceiveData()");
  15120. /* reset error state */
  15121. if (ssl->error == WANT_READ
  15122. #ifdef WOLFSSL_ASYNC_CRYPT
  15123. || ssl->error == WC_PENDING_E
  15124. #endif
  15125. ) {
  15126. ssl->error = 0;
  15127. }
  15128. #ifdef WOLFSSL_DTLS
  15129. if (ssl->options.dtls) {
  15130. /* In DTLS mode, we forgive some errors and allow the session
  15131. * to continue despite them. */
  15132. if (ssl->error == VERIFY_MAC_ERROR || ssl->error == DECRYPT_ERROR)
  15133. ssl->error = 0;
  15134. }
  15135. #endif /* WOLFSSL_DTLS */
  15136. if (ssl->error != 0 && ssl->error != WANT_WRITE) {
  15137. WOLFSSL_MSG("User calling wolfSSL_read in error state, not allowed");
  15138. return ssl->error;
  15139. }
  15140. #ifdef WOLFSSL_EARLY_DATA
  15141. if (ssl->earlyData != no_early_data) {
  15142. }
  15143. else
  15144. #endif
  15145. if (ssl->options.handShakeState != HANDSHAKE_DONE) {
  15146. int err;
  15147. WOLFSSL_MSG("Handshake not complete, trying to finish");
  15148. if ( (err = wolfSSL_negotiate(ssl)) != WOLFSSL_SUCCESS) {
  15149. #ifdef WOLFSSL_ASYNC_CRYPT
  15150. /* if async would block return WANT_WRITE */
  15151. if (ssl->error == WC_PENDING_E) {
  15152. return WOLFSSL_CBIO_ERR_WANT_READ;
  15153. }
  15154. #endif
  15155. return err;
  15156. }
  15157. }
  15158. #ifdef HAVE_SECURE_RENEGOTIATION
  15159. startScr:
  15160. if (ssl->secure_renegotiation && ssl->secure_renegotiation->startScr) {
  15161. int err;
  15162. WOLFSSL_MSG("Need to start scr, server requested");
  15163. if ( (err = wolfSSL_Rehandshake(ssl)) != WOLFSSL_SUCCESS)
  15164. return err;
  15165. ssl->secure_renegotiation->startScr = 0; /* only start once */
  15166. }
  15167. #endif
  15168. while (ssl->buffers.clearOutputBuffer.length == 0) {
  15169. if ( (ssl->error = ProcessReply(ssl)) < 0) {
  15170. WOLFSSL_ERROR(ssl->error);
  15171. if (ssl->error == ZERO_RETURN) {
  15172. WOLFSSL_MSG("Zero return, no more data coming");
  15173. return 0; /* no more data coming */
  15174. }
  15175. if (ssl->error == SOCKET_ERROR_E) {
  15176. if (ssl->options.connReset || ssl->options.isClosed) {
  15177. WOLFSSL_MSG("Peer reset or closed, connection done");
  15178. ssl->error = SOCKET_PEER_CLOSED_E;
  15179. WOLFSSL_ERROR(ssl->error);
  15180. return 0; /* peer reset or closed */
  15181. }
  15182. }
  15183. return ssl->error;
  15184. }
  15185. #ifdef HAVE_SECURE_RENEGOTIATION
  15186. if (ssl->secure_renegotiation &&
  15187. ssl->secure_renegotiation->startScr) {
  15188. goto startScr;
  15189. }
  15190. #endif
  15191. }
  15192. if (sz < (int)ssl->buffers.clearOutputBuffer.length)
  15193. size = sz;
  15194. else
  15195. size = ssl->buffers.clearOutputBuffer.length;
  15196. XMEMCPY(output, ssl->buffers.clearOutputBuffer.buffer, size);
  15197. if (peek == 0) {
  15198. ssl->buffers.clearOutputBuffer.length -= size;
  15199. ssl->buffers.clearOutputBuffer.buffer += size;
  15200. }
  15201. if (ssl->buffers.clearOutputBuffer.length == 0 &&
  15202. ssl->buffers.inputBuffer.dynamicFlag)
  15203. ShrinkInputBuffer(ssl, NO_FORCED_FREE);
  15204. WOLFSSL_LEAVE("ReceiveData()", size);
  15205. return size;
  15206. }
  15207. /* send alert message */
  15208. int SendAlert(WOLFSSL* ssl, int severity, int type)
  15209. {
  15210. byte input[ALERT_SIZE];
  15211. byte *output;
  15212. int sendSz;
  15213. int ret;
  15214. int outputSz;
  15215. int dtlsExtra = 0;
  15216. WOLFSSL_ENTER("SendAlert");
  15217. #ifdef HAVE_WRITE_DUP
  15218. if (ssl->dupWrite && ssl->dupSide == READ_DUP_SIDE) {
  15219. int notifyErr = 0;
  15220. WOLFSSL_MSG("Read dup side cannot write alerts, notifying sibling");
  15221. if (type == close_notify) {
  15222. notifyErr = ZERO_RETURN;
  15223. } else if (severity == alert_fatal) {
  15224. notifyErr = FATAL_ERROR;
  15225. }
  15226. if (notifyErr != 0) {
  15227. return NotifyWriteSide(ssl, notifyErr);
  15228. }
  15229. return 0;
  15230. }
  15231. #endif
  15232. /* if sendalert is called again for nonblocking */
  15233. if (ssl->options.sendAlertState != 0) {
  15234. ret = SendBuffered(ssl);
  15235. if (ret == 0)
  15236. ssl->options.sendAlertState = 0;
  15237. return ret;
  15238. }
  15239. #ifdef OPENSSL_EXTRA
  15240. if (ssl->CBIS != NULL) {
  15241. ssl->CBIS(ssl, SSL_CB_ALERT, type);
  15242. }
  15243. #endif
  15244. #ifdef WOLFSSL_DTLS
  15245. if (ssl->options.dtls)
  15246. dtlsExtra = DTLS_RECORD_EXTRA;
  15247. #endif
  15248. /* check for available size */
  15249. outputSz = ALERT_SIZE + MAX_MSG_EXTRA + dtlsExtra;
  15250. if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
  15251. return ret;
  15252. /* Check output buffer */
  15253. if (ssl->buffers.outputBuffer.buffer == NULL)
  15254. return BUFFER_E;
  15255. /* get output buffer */
  15256. output = ssl->buffers.outputBuffer.buffer +
  15257. ssl->buffers.outputBuffer.length;
  15258. input[0] = (byte)severity;
  15259. input[1] = (byte)type;
  15260. ssl->alert_history.last_tx.code = type;
  15261. ssl->alert_history.last_tx.level = severity;
  15262. if (severity == alert_fatal) {
  15263. ssl->options.isClosed = 1; /* Don't send close_notify */
  15264. }
  15265. /* only send encrypted alert if handshake actually complete, otherwise
  15266. other side may not be able to handle it */
  15267. if (IsEncryptionOn(ssl, 1) && (IsAtLeastTLSv1_3(ssl->version) ||
  15268. ssl->options.handShakeDone)) {
  15269. sendSz = BuildMessage(ssl, output, outputSz, input, ALERT_SIZE, alert,
  15270. 0, 0, 0);
  15271. }
  15272. else {
  15273. AddRecordHeader(output, ALERT_SIZE, alert, ssl);
  15274. output += RECORD_HEADER_SZ;
  15275. #ifdef WOLFSSL_DTLS
  15276. if (ssl->options.dtls)
  15277. output += DTLS_RECORD_EXTRA;
  15278. #endif
  15279. XMEMCPY(output, input, ALERT_SIZE);
  15280. sendSz = RECORD_HEADER_SZ + ALERT_SIZE;
  15281. #ifdef WOLFSSL_DTLS
  15282. if (ssl->options.dtls)
  15283. sendSz += DTLS_RECORD_EXTRA;
  15284. #endif
  15285. }
  15286. if (sendSz < 0)
  15287. return BUILD_MSG_ERROR;
  15288. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  15289. if (ssl->hsInfoOn)
  15290. AddPacketName(ssl, "Alert");
  15291. if (ssl->toInfoOn)
  15292. AddPacketInfo(ssl, "Alert", alert, output, sendSz, WRITE_PROTO,
  15293. ssl->heap);
  15294. #endif
  15295. ssl->buffers.outputBuffer.length += sendSz;
  15296. ssl->options.sendAlertState = 1;
  15297. ret = SendBuffered(ssl);
  15298. WOLFSSL_LEAVE("SendAlert", ret);
  15299. return ret;
  15300. }
  15301. const char* wolfSSL_ERR_reason_error_string(unsigned long e)
  15302. {
  15303. #ifdef NO_ERROR_STRINGS
  15304. (void)e;
  15305. return "no support for error strings built in";
  15306. #else
  15307. int error = (int)e;
  15308. /* pass to wolfCrypt */
  15309. if (error < MAX_CODE_E && error > MIN_CODE_E) {
  15310. return wc_GetErrorString(error);
  15311. }
  15312. switch (error) {
  15313. #ifdef WOLFSSL_WPAS
  15314. case 0 :
  15315. return "ok";
  15316. #endif
  15317. case UNSUPPORTED_SUITE :
  15318. return "unsupported cipher suite";
  15319. case INPUT_CASE_ERROR :
  15320. return "input state error";
  15321. case PREFIX_ERROR :
  15322. return "bad index to key rounds";
  15323. case MEMORY_ERROR :
  15324. return "out of memory";
  15325. case VERIFY_FINISHED_ERROR :
  15326. return "verify problem on finished";
  15327. case VERIFY_MAC_ERROR :
  15328. return "verify mac problem";
  15329. case PARSE_ERROR :
  15330. return "parse error on header";
  15331. case SIDE_ERROR :
  15332. return "wrong client/server type";
  15333. case NO_PEER_CERT :
  15334. return "peer didn't send cert";
  15335. case UNKNOWN_HANDSHAKE_TYPE :
  15336. return "weird handshake type";
  15337. case SOCKET_ERROR_E :
  15338. return "error state on socket";
  15339. case SOCKET_NODATA :
  15340. return "expected data, not there";
  15341. case INCOMPLETE_DATA :
  15342. return "don't have enough data to complete task";
  15343. case UNKNOWN_RECORD_TYPE :
  15344. return "unknown type in record hdr";
  15345. case DECRYPT_ERROR :
  15346. return "error during decryption";
  15347. case FATAL_ERROR :
  15348. return "received alert fatal error";
  15349. case ENCRYPT_ERROR :
  15350. return "error during encryption";
  15351. case FREAD_ERROR :
  15352. return "fread problem";
  15353. case NO_PEER_KEY :
  15354. return "need peer's key";
  15355. case NO_PRIVATE_KEY :
  15356. return "need the private key";
  15357. case NO_DH_PARAMS :
  15358. return "server missing DH params";
  15359. case RSA_PRIVATE_ERROR :
  15360. return "error during rsa priv op";
  15361. case MATCH_SUITE_ERROR :
  15362. return "can't match cipher suite";
  15363. case COMPRESSION_ERROR :
  15364. return "compression mismatch error";
  15365. case BUILD_MSG_ERROR :
  15366. return "build message failure";
  15367. case BAD_HELLO :
  15368. return "client hello malformed";
  15369. case DOMAIN_NAME_MISMATCH :
  15370. return "peer subject name mismatch";
  15371. case IPADDR_MISMATCH :
  15372. return "peer ip address mismatch";
  15373. case WANT_READ :
  15374. case WOLFSSL_ERROR_WANT_READ :
  15375. return "non-blocking socket wants data to be read";
  15376. case NOT_READY_ERROR :
  15377. return "handshake layer not ready yet, complete first";
  15378. case VERSION_ERROR :
  15379. return "record layer version error";
  15380. case WANT_WRITE :
  15381. case WOLFSSL_ERROR_WANT_WRITE :
  15382. return "non-blocking socket write buffer full";
  15383. case BUFFER_ERROR :
  15384. return "malformed buffer input error";
  15385. case VERIFY_CERT_ERROR :
  15386. return "verify problem on certificate";
  15387. case VERIFY_SIGN_ERROR :
  15388. return "verify problem based on signature";
  15389. case CLIENT_ID_ERROR :
  15390. return "psk client identity error";
  15391. case SERVER_HINT_ERROR:
  15392. return "psk server hint error";
  15393. case PSK_KEY_ERROR:
  15394. return "psk key callback error";
  15395. case NTRU_KEY_ERROR:
  15396. return "NTRU key error";
  15397. case NTRU_DRBG_ERROR:
  15398. return "NTRU drbg error";
  15399. case NTRU_ENCRYPT_ERROR:
  15400. return "NTRU encrypt error";
  15401. case NTRU_DECRYPT_ERROR:
  15402. return "NTRU decrypt error";
  15403. case GETTIME_ERROR:
  15404. return "gettimeofday() error";
  15405. case GETITIMER_ERROR:
  15406. return "getitimer() error";
  15407. case SIGACT_ERROR:
  15408. return "sigaction() error";
  15409. case SETITIMER_ERROR:
  15410. return "setitimer() error";
  15411. case LENGTH_ERROR:
  15412. return "record layer length error";
  15413. case PEER_KEY_ERROR:
  15414. return "cant decode peer key";
  15415. case ZERO_RETURN:
  15416. case WOLFSSL_ERROR_ZERO_RETURN:
  15417. return "peer sent close notify alert";
  15418. case ECC_CURVETYPE_ERROR:
  15419. return "Bad ECC Curve Type or unsupported";
  15420. case ECC_CURVE_ERROR:
  15421. return "Bad ECC Curve or unsupported";
  15422. case ECC_PEERKEY_ERROR:
  15423. return "Bad ECC Peer Key";
  15424. case ECC_MAKEKEY_ERROR:
  15425. return "ECC Make Key failure";
  15426. case ECC_EXPORT_ERROR:
  15427. return "ECC Export Key failure";
  15428. case ECC_SHARED_ERROR:
  15429. return "ECC DHE shared failure";
  15430. case NOT_CA_ERROR:
  15431. return "Not a CA by basic constraint error";
  15432. case HTTP_TIMEOUT:
  15433. return "HTTP timeout for OCSP or CRL req";
  15434. case BAD_CERT_MANAGER_ERROR:
  15435. return "Bad Cert Manager error";
  15436. case OCSP_CERT_REVOKED:
  15437. return "OCSP Cert revoked";
  15438. case CRL_CERT_REVOKED:
  15439. return "CRL Cert revoked";
  15440. case CRL_MISSING:
  15441. return "CRL missing, not loaded";
  15442. case MONITOR_SETUP_E:
  15443. return "CRL monitor setup error";
  15444. case THREAD_CREATE_E:
  15445. return "Thread creation problem";
  15446. case OCSP_NEED_URL:
  15447. return "OCSP need URL";
  15448. case OCSP_CERT_UNKNOWN:
  15449. return "OCSP Cert unknown";
  15450. case OCSP_LOOKUP_FAIL:
  15451. return "OCSP Responder lookup fail";
  15452. case MAX_CHAIN_ERROR:
  15453. return "Maximum Chain Depth Exceeded";
  15454. case COOKIE_ERROR:
  15455. return "DTLS Cookie Error";
  15456. case SEQUENCE_ERROR:
  15457. return "DTLS Sequence Error";
  15458. case SUITES_ERROR:
  15459. return "Suites Pointer Error";
  15460. case OUT_OF_ORDER_E:
  15461. return "Out of order message, fatal";
  15462. case BAD_KEA_TYPE_E:
  15463. return "Bad KEA type found";
  15464. case SANITY_CIPHER_E:
  15465. return "Sanity check on ciphertext failed";
  15466. case RECV_OVERFLOW_E:
  15467. return "Receive callback returned more than requested";
  15468. case GEN_COOKIE_E:
  15469. return "Generate Cookie Error";
  15470. case NO_PEER_VERIFY:
  15471. return "Need peer certificate verify Error";
  15472. case FWRITE_ERROR:
  15473. return "fwrite Error";
  15474. case CACHE_MATCH_ERROR:
  15475. return "Cache restore header match Error";
  15476. case UNKNOWN_SNI_HOST_NAME_E:
  15477. return "Unrecognized host name Error";
  15478. case UNKNOWN_MAX_FRAG_LEN_E:
  15479. return "Unrecognized max frag len Error";
  15480. case KEYUSE_SIGNATURE_E:
  15481. return "Key Use digitalSignature not set Error";
  15482. case KEYUSE_ENCIPHER_E:
  15483. return "Key Use keyEncipherment not set Error";
  15484. case EXTKEYUSE_AUTH_E:
  15485. return "Ext Key Use server/client auth not set Error";
  15486. case SEND_OOB_READ_E:
  15487. return "Send Callback Out of Bounds Read Error";
  15488. case SECURE_RENEGOTIATION_E:
  15489. return "Invalid Renegotiation Error";
  15490. case SESSION_TICKET_LEN_E:
  15491. return "Session Ticket Too Long Error";
  15492. case SESSION_TICKET_EXPECT_E:
  15493. return "Session Ticket Error";
  15494. case SESSION_SECRET_CB_E:
  15495. return "Session Secret Callback Error";
  15496. case NO_CHANGE_CIPHER_E:
  15497. return "Finished received from peer before Change Cipher Error";
  15498. case SANITY_MSG_E:
  15499. return "Sanity Check on message order Error";
  15500. case DUPLICATE_MSG_E:
  15501. return "Duplicate HandShake message Error";
  15502. case SNI_UNSUPPORTED:
  15503. return "Protocol version does not support SNI Error";
  15504. case SOCKET_PEER_CLOSED_E:
  15505. return "Peer closed underlying transport Error";
  15506. case BAD_TICKET_KEY_CB_SZ:
  15507. return "Bad user session ticket key callback Size Error";
  15508. case BAD_TICKET_MSG_SZ:
  15509. return "Bad session ticket message Size Error";
  15510. case BAD_TICKET_ENCRYPT:
  15511. return "Bad user ticket callback encrypt Error";
  15512. case DH_KEY_SIZE_E:
  15513. return "DH key too small Error";
  15514. case SNI_ABSENT_ERROR:
  15515. return "No Server Name Indication extension Error";
  15516. case RSA_SIGN_FAULT:
  15517. return "RSA Signature Fault Error";
  15518. case HANDSHAKE_SIZE_ERROR:
  15519. return "Handshake message too large Error";
  15520. case UNKNOWN_ALPN_PROTOCOL_NAME_E:
  15521. return "Unrecognized protocol name Error";
  15522. case BAD_CERTIFICATE_STATUS_ERROR:
  15523. return "Bad Certificate Status Message Error";
  15524. case OCSP_INVALID_STATUS:
  15525. return "Invalid OCSP Status Error";
  15526. case OCSP_WANT_READ:
  15527. return "OCSP nonblock wants read";
  15528. case RSA_KEY_SIZE_E:
  15529. return "RSA key too small";
  15530. case ECC_KEY_SIZE_E:
  15531. return "ECC key too small";
  15532. case DTLS_EXPORT_VER_E:
  15533. return "Version needs updated after code change or version mismatch";
  15534. case INPUT_SIZE_E:
  15535. return "Input size too large Error";
  15536. case CTX_INIT_MUTEX_E:
  15537. return "Initialize ctx mutex error";
  15538. case EXT_MASTER_SECRET_NEEDED_E:
  15539. return "Extended Master Secret must be enabled to resume EMS session";
  15540. case DTLS_POOL_SZ_E:
  15541. return "Maximum DTLS pool size exceeded";
  15542. case DECODE_E:
  15543. return "Decode handshake message error";
  15544. case WRITE_DUP_READ_E:
  15545. return "Write dup write side can't read error";
  15546. case WRITE_DUP_WRITE_E:
  15547. return "Write dup read side can't write error";
  15548. case INVALID_CERT_CTX_E:
  15549. return "Certificate context does not match request or not empty";
  15550. case BAD_KEY_SHARE_DATA:
  15551. return "The Key Share data contains group that wasn't in Client Hello";
  15552. case MISSING_HANDSHAKE_DATA:
  15553. return "The handshake message is missing required data";
  15554. case BAD_BINDER:
  15555. return "Binder value does not match value server calculated";
  15556. case EXT_NOT_ALLOWED:
  15557. return "Extension type not allowed in handshake message type";
  15558. case INVALID_PARAMETER:
  15559. return "The security parameter is invalid";
  15560. case UNSUPPORTED_EXTENSION:
  15561. return "TLS Extension not requested by the client";
  15562. case PRF_MISSING:
  15563. return "Pseudo-random function is not enabled";
  15564. case KEY_SHARE_ERROR:
  15565. return "Key share extension did not contain a valid named group";
  15566. case POST_HAND_AUTH_ERROR:
  15567. return "Client will not do post handshake authentication";
  15568. case HRR_COOKIE_ERROR:
  15569. return "Cookie does not match one sent in HelloRetryRequest";
  15570. case MCAST_HIGHWATER_CB_E:
  15571. return "Multicast highwater callback returned error";
  15572. case ALERT_COUNT_E:
  15573. return "Alert Count exceeded error";
  15574. case EXT_MISSING:
  15575. return "Required TLS extension missing";
  15576. case DTLS_RETX_OVER_TX:
  15577. return "DTLS interrupting flight transmit with retransmit";
  15578. case DH_PARAMS_NOT_FFDHE_E:
  15579. return "Server DH parameters were not from the FFDHE set as required";
  15580. case TCA_INVALID_ID_TYPE:
  15581. return "TLS Extension Trusted CA ID type invalid";
  15582. case TCA_ABSENT_ERROR:
  15583. return "TLS Extension Trusted CA ID response absent";
  15584. case TSIP_MAC_DIGSZ_E:
  15585. return "TSIP MAC size invalid, must be sized for SHA-1 or SHA-256";
  15586. case CLIENT_CERT_CB_ERROR:
  15587. return "Error importing client cert or key from callback";
  15588. case SSL_SHUTDOWN_ALREADY_DONE_E:
  15589. return "Shutdown has already occurred";
  15590. case TLS13_SECRET_CB_E:
  15591. return "TLS1.3 Secret Callback Error";
  15592. default :
  15593. return "unknown error number";
  15594. }
  15595. #endif /* NO_ERROR_STRINGS */
  15596. }
  15597. void SetErrorString(int error, char* str)
  15598. {
  15599. XSTRNCPY(str, wolfSSL_ERR_reason_error_string(error), WOLFSSL_MAX_ERROR_SZ);
  15600. str[WOLFSSL_MAX_ERROR_SZ-1] = 0;
  15601. }
  15602. #ifndef NO_ERROR_STRINGS
  15603. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  15604. #define SUITE_INFO(x,y,z,w,v,u) {(x),(y),(z),(w),(v),(u)}
  15605. #else
  15606. #define SUITE_INFO(x,y,z,w,v,u) {(x),(y),(z),(w)}
  15607. #endif
  15608. #else
  15609. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  15610. #define SUITE_INFO(x,y,z,w,v,u) {(x),(z),(w),(v),(u)}
  15611. #else
  15612. #define SUITE_INFO(x,y,z,w,v,u) {(x),(z),(w)}
  15613. #endif
  15614. #endif
  15615. static const CipherSuiteInfo cipher_names[] =
  15616. {
  15617. #ifdef BUILD_TLS_AES_128_GCM_SHA256
  15618. SUITE_INFO("TLS13-AES128-GCM-SHA256","TLS_AES_128_GCM_SHA256",TLS13_BYTE,TLS_AES_128_GCM_SHA256, TLSv1_3_MINOR, SSLv3_MAJOR),
  15619. #endif
  15620. #ifdef BUILD_TLS_AES_256_GCM_SHA384
  15621. SUITE_INFO("TLS13-AES256-GCM-SHA384","TLS_AES_256_GCM_SHA384",TLS13_BYTE,TLS_AES_256_GCM_SHA384, TLSv1_3_MINOR, SSLv3_MAJOR),
  15622. #endif
  15623. #ifdef BUILD_TLS_CHACHA20_POLY1305_SHA256
  15624. SUITE_INFO("TLS13-CHACHA20-POLY1305-SHA256","TLS_CHACHA20_POLY1305_SHA256",TLS13_BYTE,TLS_CHACHA20_POLY1305_SHA256, TLSv1_3_MINOR, SSLv3_MAJOR),
  15625. #endif
  15626. #ifdef BUILD_TLS_AES_128_CCM_SHA256
  15627. SUITE_INFO("TLS13-AES128-CCM-SHA256","TLS_AES_128_CCM_SHA256",TLS13_BYTE,TLS_AES_128_CCM_SHA256, TLSv1_3_MINOR, SSLv3_MAJOR),
  15628. #endif
  15629. #ifdef BUILD_TLS_AES_128_CCM_8_SHA256
  15630. 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),
  15631. #endif
  15632. #ifdef BUILD_TLS_SHA256_SHA256
  15633. SUITE_INFO("TLS13-SHA256-SHA256","TLS_SHA256_SHA256",ECC_BYTE,TLS_SHA256_SHA256,TLSv1_3_MINOR, SSLv3_MAJOR),
  15634. #endif
  15635. #ifdef BUILD_TLS_SHA384_SHA384
  15636. SUITE_INFO("TLS13-SHA384-SHA384","TLS_SHA384_SHA384",ECC_BYTE,TLS_SHA384_SHA384,TLSv1_3_MINOR, SSLv3_MAJOR),
  15637. #endif
  15638. #ifndef WOLFSSL_NO_TLS12
  15639. #ifdef BUILD_SSL_RSA_WITH_RC4_128_SHA
  15640. SUITE_INFO("RC4-SHA","SSL_RSA_WITH_RC4_128_SHA",CIPHER_BYTE,SSL_RSA_WITH_RC4_128_SHA,SSLv3_MINOR,SSLv3_MAJOR),
  15641. #endif
  15642. #ifdef BUILD_SSL_RSA_WITH_RC4_128_MD5
  15643. SUITE_INFO("RC4-MD5","SSL_RSA_WITH_RC4_128_MD5",CIPHER_BYTE,SSL_RSA_WITH_RC4_128_MD5,SSLv3_MINOR,SSLv3_MAJOR),
  15644. #endif
  15645. #ifdef BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA
  15646. 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),
  15647. #endif
  15648. #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA
  15649. SUITE_INFO("AES128-SHA","TLS_RSA_WITH_AES_128_CBC_SHA",CIPHER_BYTE,TLS_RSA_WITH_AES_128_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
  15650. #endif
  15651. #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA
  15652. SUITE_INFO("AES256-SHA","TLS_RSA_WITH_AES_256_CBC_SHA",CIPHER_BYTE,TLS_RSA_WITH_AES_256_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
  15653. #endif
  15654. #ifdef BUILD_TLS_RSA_WITH_NULL_MD5
  15655. SUITE_INFO("NULL-MD5","TLS_RSA_WITH_NULL_MD5",CIPHER_BYTE,TLS_RSA_WITH_NULL_MD5,SSLv3_MINOR,SSLv3_MAJOR),
  15656. #endif
  15657. #ifdef BUILD_TLS_RSA_WITH_NULL_SHA
  15658. SUITE_INFO("NULL-SHA","TLS_RSA_WITH_NULL_SHA",CIPHER_BYTE,TLS_RSA_WITH_NULL_SHA,SSLv3_MINOR,SSLv3_MAJOR),
  15659. #endif
  15660. #ifdef BUILD_TLS_RSA_WITH_NULL_SHA256
  15661. SUITE_INFO("NULL-SHA256","TLS_RSA_WITH_NULL_SHA256",CIPHER_BYTE,TLS_RSA_WITH_NULL_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
  15662. #endif
  15663. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
  15664. 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),
  15665. #endif
  15666. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
  15667. 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),
  15668. #endif
  15669. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
  15670. 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),
  15671. #endif
  15672. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
  15673. 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),
  15674. #endif
  15675. #ifdef BUILD_TLS_PSK_WITH_AES_256_GCM_SHA384
  15676. 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),
  15677. #endif
  15678. #ifdef BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256
  15679. 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),
  15680. #endif
  15681. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
  15682. 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),
  15683. #endif
  15684. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
  15685. 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),
  15686. #endif
  15687. #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA384
  15688. 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),
  15689. #endif
  15690. #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA256
  15691. 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),
  15692. #endif
  15693. #ifdef BUILD_TLS_PSK_WITH_AES_128_CBC_SHA
  15694. 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),
  15695. #endif
  15696. #ifdef BUILD_TLS_PSK_WITH_AES_256_CBC_SHA
  15697. 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),
  15698. #endif
  15699. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_128_CCM
  15700. 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),
  15701. #endif
  15702. #ifdef BUILD_TLS_DHE_PSK_WITH_AES_256_CCM
  15703. 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),
  15704. #endif
  15705. #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM
  15706. SUITE_INFO("PSK-AES128-CCM","TLS_PSK_WITH_AES_128_CCM",ECC_BYTE,TLS_PSK_WITH_AES_128_CCM,TLSv1_MINOR,SSLv3_MAJOR),
  15707. #endif
  15708. #ifdef BUILD_TLS_PSK_WITH_AES_256_CCM
  15709. SUITE_INFO("PSK-AES256-CCM","TLS_PSK_WITH_AES_256_CCM",ECC_BYTE,TLS_PSK_WITH_AES_256_CCM,TLSv1_MINOR,SSLv3_MAJOR),
  15710. #endif
  15711. #ifdef BUILD_TLS_PSK_WITH_AES_128_CCM_8
  15712. 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),
  15713. #endif
  15714. #ifdef BUILD_TLS_PSK_WITH_AES_256_CCM_8
  15715. 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),
  15716. #endif
  15717. #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA384
  15718. SUITE_INFO("DHE-PSK-NULL-SHA384","TLS_DHE_PSK_WITH_NULL_SHA384",CIPHER_BYTE,TLS_DHE_PSK_WITH_NULL_SHA384,TLSv1_MINOR,SSLv3_MAJOR),
  15719. #endif
  15720. #ifdef BUILD_TLS_DHE_PSK_WITH_NULL_SHA256
  15721. SUITE_INFO("DHE-PSK-NULL-SHA256","TLS_DHE_PSK_WITH_NULL_SHA256",CIPHER_BYTE,TLS_DHE_PSK_WITH_NULL_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  15722. #endif
  15723. #ifdef BUILD_TLS_PSK_WITH_NULL_SHA384
  15724. SUITE_INFO("PSK-NULL-SHA384","TLS_PSK_WITH_NULL_SHA384",CIPHER_BYTE,TLS_PSK_WITH_NULL_SHA384,TLSv1_MINOR,SSLv3_MAJOR),
  15725. #endif
  15726. #ifdef BUILD_TLS_PSK_WITH_NULL_SHA256
  15727. SUITE_INFO("PSK-NULL-SHA256","TLS_PSK_WITH_NULL_SHA256",CIPHER_BYTE,TLS_PSK_WITH_NULL_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  15728. #endif
  15729. #ifdef BUILD_TLS_PSK_WITH_NULL_SHA
  15730. SUITE_INFO("PSK-NULL-SHA","TLS_PSK_WITH_NULL_SHA",CIPHER_BYTE,TLS_PSK_WITH_NULL_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  15731. #endif
  15732. #ifdef BUILD_TLS_RSA_WITH_HC_128_MD5
  15733. SUITE_INFO("HC128-MD5","TLS_RSA_WITH_HC_128_MD5",CIPHER_BYTE,TLS_RSA_WITH_HC_128_MD5,TLSv1_MINOR,SSLv3_MAJOR),
  15734. #endif
  15735. #ifdef BUILD_TLS_RSA_WITH_HC_128_SHA
  15736. SUITE_INFO("HC128-SHA","TLS_RSA_WITH_HC_128_SHA",CIPHER_BYTE,TLS_RSA_WITH_HC_128_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  15737. #endif
  15738. #ifdef BUILD_TLS_RSA_WITH_RABBIT_SHA
  15739. SUITE_INFO("RABBIT-SHA","TLS_RSA_WITH_RABBIT_SHA",CIPHER_BYTE,TLS_RSA_WITH_RABBIT_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  15740. #endif
  15741. #ifdef BUILD_TLS_NTRU_RSA_WITH_RC4_128_SHA
  15742. SUITE_INFO("NTRU-RC4-SHA","TLS_NTRU_RSA_WITH_RC4_128_SHA",CIPHER_BYTE,TLS_NTRU_RSA_WITH_RC4_128_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  15743. #endif
  15744. #ifdef BUILD_TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA
  15745. SUITE_INFO("NTRU-DES-CBC3-SHA","TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA",CIPHER_BYTE,TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  15746. #endif
  15747. #ifdef BUILD_TLS_NTRU_RSA_WITH_AES_128_CBC_SHA
  15748. SUITE_INFO("NTRU-AES128-SHA","TLS_NTRU_RSA_WITH_AES_128_CBC_SHA",CIPHER_BYTE,TLS_NTRU_RSA_WITH_AES_128_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  15749. #endif
  15750. #ifdef BUILD_TLS_NTRU_RSA_WITH_AES_256_CBC_SHA
  15751. SUITE_INFO("NTRU-AES256-SHA","TLS_NTRU_RSA_WITH_AES_256_CBC_SHA",CIPHER_BYTE,TLS_NTRU_RSA_WITH_AES_256_CBC_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  15752. #endif
  15753. #ifdef BUILD_TLS_RSA_WITH_AES_128_CCM_8
  15754. 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),
  15755. #endif
  15756. #ifdef BUILD_TLS_RSA_WITH_AES_256_CCM_8
  15757. 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),
  15758. #endif
  15759. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM
  15760. 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),
  15761. #endif
  15762. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
  15763. 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),
  15764. #endif
  15765. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8
  15766. 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),
  15767. #endif
  15768. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
  15769. 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),
  15770. #endif
  15771. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
  15772. 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),
  15773. #endif
  15774. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
  15775. 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),
  15776. #endif
  15777. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
  15778. 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),
  15779. #endif
  15780. #ifdef BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA
  15781. 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),
  15782. #endif
  15783. #ifdef BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
  15784. 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),
  15785. #endif
  15786. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
  15787. 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),
  15788. #endif
  15789. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
  15790. 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),
  15791. #endif
  15792. #ifdef BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256
  15793. SUITE_INFO("AES128-SHA256","TLS_RSA_WITH_AES_128_CBC_SHA256",CIPHER_BYTE,TLS_RSA_WITH_AES_128_CBC_SHA256, TLSv1_MINOR, SSLv3_MAJOR),
  15794. #endif
  15795. #ifdef BUILD_TLS_RSA_WITH_AES_256_CBC_SHA256
  15796. 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),
  15797. #endif
  15798. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
  15799. 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),
  15800. #endif
  15801. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
  15802. 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),
  15803. #endif
  15804. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
  15805. 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),
  15806. #endif
  15807. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
  15808. 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),
  15809. #endif
  15810. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
  15811. 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),
  15812. #endif
  15813. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
  15814. 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),
  15815. #endif
  15816. #ifdef BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA
  15817. 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),
  15818. #endif
  15819. #ifdef BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
  15820. 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),
  15821. #endif
  15822. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA
  15823. 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),
  15824. #endif
  15825. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
  15826. 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),
  15827. #endif
  15828. #ifdef BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256
  15829. 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),
  15830. #endif
  15831. #ifdef BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384
  15832. 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),
  15833. #endif
  15834. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
  15835. 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),
  15836. #endif
  15837. #ifdef BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
  15838. 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),
  15839. #endif
  15840. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  15841. 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),
  15842. #endif
  15843. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
  15844. 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),
  15845. #endif
  15846. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
  15847. 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),
  15848. #endif
  15849. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
  15850. 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),
  15851. #endif
  15852. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
  15853. 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),
  15854. #endif
  15855. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
  15856. 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),
  15857. #endif
  15858. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
  15859. 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),
  15860. #endif
  15861. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
  15862. 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),
  15863. #endif
  15864. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
  15865. SUITE_INFO("CAMELLIA128-SHA","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA",CIPHER_BYTE,TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  15866. #endif
  15867. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
  15868. 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),
  15869. #endif
  15870. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
  15871. SUITE_INFO("CAMELLIA256-SHA","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA",CIPHER_BYTE,TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,TLSv1_MINOR,SSLv3_MAJOR),
  15872. #endif
  15873. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
  15874. 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),
  15875. #endif
  15876. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
  15877. SUITE_INFO("CAMELLIA128-SHA256","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256",CIPHER_BYTE,TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  15878. #endif
  15879. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
  15880. 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),
  15881. #endif
  15882. #ifdef BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256
  15883. SUITE_INFO("CAMELLIA256-SHA256","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256",CIPHER_BYTE,TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  15884. #endif
  15885. #ifdef BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
  15886. 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),
  15887. #endif
  15888. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
  15889. 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),
  15890. #endif
  15891. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
  15892. 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),
  15893. #endif
  15894. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
  15895. 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),
  15896. #endif
  15897. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
  15898. 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),
  15899. #endif
  15900. #ifdef BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
  15901. 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),
  15902. #endif
  15903. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
  15904. 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),
  15905. #endif
  15906. #ifdef BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
  15907. 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),
  15908. #endif
  15909. #ifdef BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
  15910. 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),
  15911. #endif
  15912. #ifdef BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
  15913. 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),
  15914. #endif
  15915. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
  15916. 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),
  15917. #endif
  15918. #ifdef BUILD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
  15919. 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),
  15920. #endif
  15921. #ifdef BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
  15922. 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),
  15923. #endif
  15924. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256
  15925. 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),
  15926. #endif
  15927. #ifdef BUILD_TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
  15928. 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),
  15929. #endif
  15930. #ifdef BUILD_TLS_DH_anon_WITH_AES_128_CBC_SHA
  15931. 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),
  15932. #endif
  15933. #ifdef BUILD_TLS_DH_anon_WITH_AES_256_GCM_SHA384
  15934. 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),
  15935. #endif
  15936. #ifdef BUILD_TLS_QSH
  15937. SUITE_INFO("QSH","TLS_QSH",QSH_BYTE,TLS_QSH, TLSv1_MINOR, SSLv3_MAJOR),
  15938. #endif
  15939. #ifdef HAVE_RENEGOTIATION_INDICATION
  15940. SUITE_INFO("RENEGOTIATION-INFO","TLS_EMPTY_RENEGOTIATION_INFO_SCSV",CIPHER_BYTE,TLS_EMPTY_RENEGOTIATION_INFO_SCSV,SSLv3_MINOR,SSLv3_MAJOR),
  15941. #endif
  15942. #ifdef BUILD_SSL_RSA_WITH_IDEA_CBC_SHA
  15943. SUITE_INFO("IDEA-CBC-SHA","SSL_RSA_WITH_IDEA_CBC_SHA",CIPHER_BYTE,SSL_RSA_WITH_IDEA_CBC_SHA,SSLv3_MINOR,SSLv3_MAJOR),
  15944. #endif
  15945. #ifdef BUILD_TLS_ECDHE_ECDSA_WITH_NULL_SHA
  15946. SUITE_INFO("ECDHE-ECDSA-NULL-SHA","TLS_ECDHE_ECDSA_WITH_NULL_SHA",ECC_BYTE,TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLSv1_MINOR, SSLv3_MAJOR),
  15947. #endif
  15948. #ifdef BUILD_TLS_ECDHE_PSK_WITH_NULL_SHA256
  15949. SUITE_INFO("ECDHE-PSK-NULL-SHA256","TLS_ECDHE_PSK_WITH_NULL_SHA256",ECC_BYTE,TLS_ECDHE_PSK_WITH_NULL_SHA256,TLSv1_MINOR,SSLv3_MAJOR),
  15950. #endif
  15951. #ifdef BUILD_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
  15952. 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),
  15953. #endif
  15954. #ifdef BUILD_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256
  15955. SUITE_INFO("PSK-CHACHA20-POLY1305","TLS_PSK_WITH_CHACHA20_POLY1305_SHA256",CHACHA_BYTE,TLS_PSK_WITH_CHACHA20_POLY1305_SHA256,TLSv1_2_MINOR,SSLv3_MAJOR),
  15956. #endif
  15957. #ifdef BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256
  15958. 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),
  15959. #endif
  15960. #ifdef BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256
  15961. 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),
  15962. #endif
  15963. #ifdef BUILD_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
  15964. 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),
  15965. #endif
  15966. #ifdef BUILD_WDM_WITH_NULL_SHA256
  15967. SUITE_INFO("WDM-NULL-SHA256","WDM_WITH_NULL_SHA256",CIPHER_BYTE,WDM_WITH_NULL_SHA256, TLSv1_3_MINOR, SSLv3_MAJOR)
  15968. #endif
  15969. #endif /* WOLFSSL_NO_TLS12 */
  15970. };
  15971. /* returns the cipher_names array */
  15972. const CipherSuiteInfo* GetCipherNames(void)
  15973. {
  15974. return cipher_names;
  15975. }
  15976. /* returns the number of elements in the cipher_names array */
  15977. int GetCipherNamesSize(void)
  15978. {
  15979. return (int)(sizeof(cipher_names) / sizeof(CipherSuiteInfo));
  15980. }
  15981. const char* GetCipherNameInternal(const byte cipherSuite0, const byte cipherSuite)
  15982. {
  15983. int i;
  15984. const char* nameInternal = "None";
  15985. for (i = 0; i < GetCipherNamesSize(); i++) {
  15986. if ((cipher_names[i].cipherSuite0 == cipherSuite0) &&
  15987. (cipher_names[i].cipherSuite == cipherSuite)) {
  15988. nameInternal = cipher_names[i].name;
  15989. break;
  15990. }
  15991. }
  15992. return nameInternal;
  15993. }
  15994. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
  15995. const char* GetCipherKeaStr(char n[][MAX_SEGMENT_SZ]) {
  15996. const char* keaStr = NULL;
  15997. const char *n0,*n1,*n2,*n3,*n4;
  15998. n0 = n[0];
  15999. n1 = n[1];
  16000. n2 = n[2];
  16001. n3 = n[3];
  16002. n4 = n[4];
  16003. if (XSTRNCMP(n0,"ECDHE",5) == 0 && XSTRNCMP(n1,"PSK",3) == 0)
  16004. keaStr = "ECDHEPSK";
  16005. else if (XSTRNCMP(n0,"ECDH",4) == 0)
  16006. keaStr = "ECDH";
  16007. else if (XSTRNCMP(n0,"DHE",3) == 0 && XSTRNCMP(n1,"PSK",3) == 0)
  16008. keaStr = "DHEPSK";
  16009. else if (XSTRNCMP(n0,"DHE",3) == 0)
  16010. keaStr = "DH";
  16011. else if (XSTRNCMP(n0,"RSA",3) == 0 && XSTRNCMP(n1,"PSK",3) == 0)
  16012. keaStr = "RSAPSK";
  16013. else if (XSTRNCMP(n0,"SRP",3) == 0)
  16014. keaStr = "SRP";
  16015. else if (XSTRNCMP(n0,"PSK",3) == 0)
  16016. keaStr = "PSK";
  16017. else if (XSTRNCMP(n0,"EDH",3) == 0)
  16018. keaStr = "EDH";
  16019. else if ((XSTRNCMP(n1,"SHA",3) == 0) || (XSTRNCMP(n2,"SHA",3) == 0) ||
  16020. (XSTRNCMP(n3,"SHA",3) == 0) || (XSTRNCMP(n4,"SHA",3) == 0) ||
  16021. (XSTRNCMP(n2,"RSA",3) == 0) || (XSTRNCMP(n0,"AES128",6) == 0) ||
  16022. (XSTRNCMP(n0,"AES256",6) == 0) || (XSTRNCMP(n1,"MD5",3) == 0))
  16023. keaStr = "RSA";
  16024. else
  16025. keaStr = "unknown";
  16026. return keaStr;
  16027. }
  16028. const char* GetCipherAuthStr(char n[][MAX_SEGMENT_SZ]) {
  16029. const char* authStr = NULL;
  16030. const char *n0,*n1,*n2;
  16031. n0 = n[0];
  16032. n1 = n[1];
  16033. n2 = n[2];
  16034. if ((XSTRNCMP(n0,"AES128",6) == 0) || (XSTRNCMP(n0,"AES256",6) == 0) ||
  16035. ((XSTRNCMP(n0,"TLS13",5) == 0) && ((XSTRNCMP(n1,"AES128",6) == 0) ||
  16036. (XSTRNCMP(n1,"AES256",6) == 0) || (XSTRNCMP(n1,"CHACHA20",8) == 0))) ||
  16037. (XSTRNCMP(n0,"RSA",3) == 0) || (XSTRNCMP(n1,"RSA",3) == 0) ||
  16038. (XSTRNCMP(n1,"SHA",3) == 0) || (XSTRNCMP(n2,"SHA",3) == 0) ||
  16039. (XSTRNCMP(n1,"MD5",3) == 0))
  16040. authStr = "RSA";
  16041. else if (XSTRNCMP(n0,"PSK",3) == 0 || XSTRNCMP(n1,"PSK",3) == 0)
  16042. authStr = "PSK";
  16043. else if (XSTRNCMP(n0,"SRP",3) == 0 && XSTRNCMP(n1,"AES",3) == 0)
  16044. authStr = "SRP";
  16045. else if (XSTRNCMP(n1,"ECDSA",5) == 0)
  16046. authStr = "ECDSA";
  16047. else
  16048. authStr = "unknown";
  16049. return authStr;
  16050. }
  16051. const char* GetCipherEncStr(char n[][MAX_SEGMENT_SZ]) {
  16052. const char* encStr = NULL;
  16053. const char *n0,*n1,*n2,*n3;
  16054. n0 = n[0];
  16055. n1 = n[1];
  16056. n2 = n[2];
  16057. n3 = n[3];
  16058. if ((XSTRNCMP(n0,"AES256",6) == 0 && XSTRNCMP(n1,"GCM",3) == 0) ||
  16059. (XSTRNCMP(n1,"AES256",6) == 0 && XSTRNCMP(n2,"GCM",3) == 0) ||
  16060. (XSTRNCMP(n2,"AES256",6) == 0 && XSTRNCMP(n3,"GCM",3) == 0))
  16061. encStr = "AESGCM(256)";
  16062. else if ((XSTRNCMP(n0,"AES128",6) == 0 && XSTRNCMP(n1,"GCM",3) == 0) ||
  16063. (XSTRNCMP(n1,"AES128",6) == 0 && XSTRNCMP(n2,"GCM",3) == 0) ||
  16064. (XSTRNCMP(n2,"AES128",6) == 0 && XSTRNCMP(n3,"GCM",3) == 0))
  16065. encStr = "AESGCM(128)";
  16066. else if ((XSTRNCMP(n0,"AES128",6) == 0 && XSTRNCMP(n1,"CCM",3) == 0) ||
  16067. (XSTRNCMP(n1,"AES128",6) == 0 && XSTRNCMP(n2,"CCM",3) == 0) ||
  16068. (XSTRNCMP(n2,"AES128",6) == 0 && XSTRNCMP(n3,"CCM",3) == 0))
  16069. encStr = "AESCCM(128)";
  16070. else if ((XSTRNCMP(n0,"AES128",6) == 0) ||
  16071. (XSTRNCMP(n1,"AES128",6) == 0) ||
  16072. (XSTRNCMP(n2,"AES128",6) == 0) ||
  16073. (XSTRNCMP(n1,"AES",3) == 0 && XSTRNCMP(n2,"128",3) == 0) ||
  16074. (XSTRNCMP(n2,"AES",3) == 0 && XSTRNCMP(n3,"128",3) == 0))
  16075. encStr = "AES(128)";
  16076. else if ((XSTRNCMP(n0,"AES256",6) == 0) ||
  16077. (XSTRNCMP(n1,"AES256",6) == 0) ||
  16078. (XSTRNCMP(n2,"AES256",6) == 0) ||
  16079. (XSTRNCMP(n1,"AES",3) == 0 && XSTRNCMP(n2,"256",3) == 0) ||
  16080. (XSTRNCMP(n2,"AES",3) == 0 && XSTRNCMP(n3,"256",3) == 0))
  16081. encStr = "AES(256)";
  16082. else if ((XSTRNCMP(n0,"CAMELLIA256",11) == 0) ||
  16083. (XSTRNCMP(n2,"CAMELLIA256",11) == 0))
  16084. encStr = "CAMELLIA(256)";
  16085. else if ((XSTRNCMP(n0,"CAMELLIA128",11) == 0) ||
  16086. (XSTRNCMP(n2,"CAMELLIA128",11) == 0))
  16087. encStr = "CAMELLIA(128)";
  16088. else if ((XSTRNCMP(n0,"RC4",3) == 0) || (XSTRNCMP(n2,"RC4",3) == 0))
  16089. encStr = "RC4";
  16090. else if (((XSTRNCMP(n0,"DES",3) == 0) || (XSTRNCMP(n2,"DES",3) == 0)) &&
  16091. ((XSTRNCMP(n1,"CBC3",4) == 0) || (XSTRNCMP(n3,"CBC3",4) == 0)))
  16092. encStr = "3DES";
  16093. else if ((XSTRNCMP(n1,"CHACHA20",8) == 0 && XSTRNCMP(n2,"POLY1305",8) == 0) ||
  16094. (XSTRNCMP(n2,"CHACHA20",8) == 0 && XSTRNCMP(n3,"POLY1305",8) == 0))
  16095. encStr = "CHACHA20/POLY1305(256)";
  16096. else if ((XSTRNCMP(n0,"NULL",4) == 0) || (XSTRNCMP(n1,"NULL",4) == 0) ||
  16097. (XSTRNCMP(n2,"NULL",4) == 0) ||
  16098. ((XSTRNCMP(n0,"TLS13",5) == 0) && (XSTRNCMP(n3,"",0) == 0)))
  16099. encStr = "None";
  16100. else if ((XSTRNCMP(n0,"IDEA",4) == 0))
  16101. encStr = "IDEA";
  16102. else if ((XSTRNCMP(n0,"RABBIT",4) == 0))
  16103. encStr = "RABBIT";
  16104. else if ((XSTRNCMP(n0,"HC128",5) == 0))
  16105. encStr = "HC128";
  16106. else
  16107. encStr = "unknown";
  16108. return encStr;
  16109. }
  16110. /* Returns the MAC string of a cipher or "unknown" on failure */
  16111. const char* GetCipherMacStr(char n[][MAX_SEGMENT_SZ]) {
  16112. const char* macStr = NULL;
  16113. const char *n1,*n2,*n3,*n4;
  16114. n1 = n[1];
  16115. n2 = n[2];
  16116. n3 = n[3];
  16117. n4 = n[4];
  16118. if ((XSTRNCMP(n4,"SHA256",6) == 0) || (XSTRNCMP(n3,"SHA256",6) == 0) ||
  16119. (XSTRNCMP(n2,"SHA256",6) == 0) || (XSTRNCMP(n1,"SHA256",6) == 0))
  16120. macStr = "SHA256";
  16121. else if ((XSTRNCMP(n4,"SHA384",6) == 0) ||
  16122. (XSTRNCMP(n3,"SHA384",6) == 0) ||
  16123. (XSTRNCMP(n2,"SHA384",6) == 0) ||
  16124. (XSTRNCMP(n1,"SHA384",6) == 0))
  16125. macStr = "SHA384";
  16126. else if ((XSTRNCMP(n4,"SHA",3) == 0) || (XSTRNCMP(n3,"SHA",3) == 0) ||
  16127. (XSTRNCMP(n2,"SHA",3) == 0) || (XSTRNCMP(n1,"SHA",3) == 0) ||
  16128. (XSTRNCMP(n1,"MD5",3) == 0))
  16129. macStr = "SHA1";
  16130. else if ((XSTRNCMP(n3,"GCM",3) == 0) ||
  16131. (XSTRNCMP(n1,"CCM",3) == 0) ||
  16132. (XSTRNCMP(n2,"CCM",3) == 0) || (XSTRNCMP(n3,"CCM",3) == 0) ||
  16133. (XSTRNCMP(n1,"CHACHA20",8) == 0 && XSTRNCMP(n2,"POLY1305",8) == 0) ||
  16134. (XSTRNCMP(n2,"CHACHA20",8) == 0 && XSTRNCMP(n3,"POLY1305",8) == 0))
  16135. macStr = "AEAD";
  16136. else
  16137. macStr = "unknown";
  16138. return macStr;
  16139. }
  16140. /* Returns the number of bits based on the cipher enc string, or 0 on failure */
  16141. int SetCipherBits(const char* enc) {
  16142. int ret = WOLFSSL_FAILURE;
  16143. if ((XSTRNCMP(enc,"AESGCM(256)",11) == 0) ||
  16144. (XSTRNCMP(enc,"AES(256)",8) == 0) ||
  16145. (XSTRNCMP(enc,"CAMELLIA(256)",13) == 0) ||
  16146. (XSTRNCMP(enc,"CHACHA20/POLY1305(256)",22) == 0))
  16147. ret = 256;
  16148. else if
  16149. ((XSTRNCMP(enc,"3DES",4) == 0))
  16150. ret = 168;
  16151. else if
  16152. ((XSTRNCMP(enc,"AESGCM(128)",11) == 0) ||
  16153. (XSTRNCMP(enc,"AES(128)",8) == 0) ||
  16154. (XSTRNCMP(enc,"CAMELLIA(128)",13) == 0) ||
  16155. (XSTRNCMP(enc,"IDEA",4) == 0) ||
  16156. (XSTRNCMP(enc,"RC4",3) == 0))
  16157. ret = 128;
  16158. else if
  16159. ((XSTRNCMP(enc,"DES",3) == 0))
  16160. ret = 56;
  16161. return ret;
  16162. }
  16163. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  16164. const char* GetCipherNameIana(const byte cipherSuite0, const byte cipherSuite)
  16165. {
  16166. #ifndef NO_ERROR_STRINGS
  16167. int i;
  16168. const char* nameIana = "NONE";
  16169. for (i = 0; i < GetCipherNamesSize(); i++) {
  16170. if ((cipher_names[i].cipherSuite0 == cipherSuite0) &&
  16171. (cipher_names[i].cipherSuite == cipherSuite)) {
  16172. nameIana = cipher_names[i].name_iana;
  16173. break;
  16174. }
  16175. }
  16176. return nameIana;
  16177. #else
  16178. (void)cipherSuite0;
  16179. (void)cipherSuite;
  16180. return NULL;
  16181. #endif
  16182. }
  16183. const char* wolfSSL_get_cipher_name_internal(WOLFSSL* ssl)
  16184. {
  16185. if (ssl == NULL) {
  16186. return NULL;
  16187. }
  16188. return GetCipherNameInternal(ssl->options.cipherSuite0, ssl->options.cipherSuite);
  16189. }
  16190. const char* wolfSSL_get_cipher_name_iana(WOLFSSL* ssl)
  16191. {
  16192. if (ssl == NULL) {
  16193. return NULL;
  16194. }
  16195. return GetCipherNameIana(ssl->options.cipherSuite0, ssl->options.cipherSuite);
  16196. }
  16197. int GetCipherSuiteFromName(const char* name, byte* cipherSuite0,
  16198. byte* cipherSuite)
  16199. {
  16200. int ret = BAD_FUNC_ARG;
  16201. int i;
  16202. unsigned long len = (unsigned long)XSTRLEN(name);
  16203. for (i = 0; i < GetCipherNamesSize(); i++) {
  16204. if (XSTRNCMP(name, cipher_names[i].name, len) == 0) {
  16205. *cipherSuite0 = cipher_names[i].cipherSuite0;
  16206. *cipherSuite = cipher_names[i].cipherSuite;
  16207. ret = 0;
  16208. break;
  16209. }
  16210. }
  16211. return ret;
  16212. }
  16213. /**
  16214. Set the enabled cipher suites.
  16215. @param [out] suites Suites structure.
  16216. @param [in] list List of cipher suites, only supports full name from
  16217. cipher_names[] delimited by ':'.
  16218. @return true on success, else false.
  16219. */
  16220. int SetCipherList(WOLFSSL_CTX* ctx, Suites* suites, const char* list)
  16221. {
  16222. int ret = 0;
  16223. int idx = 0;
  16224. int haveRSAsig = 0;
  16225. int haveECDSAsig = 0;
  16226. int haveAnon = 0;
  16227. const int suiteSz = GetCipherNamesSize();
  16228. char* next = (char*)list;
  16229. if (suites == NULL || list == NULL) {
  16230. WOLFSSL_MSG("SetCipherList parameter error");
  16231. return 0;
  16232. }
  16233. if (next[0] == 0 || XSTRNCMP(next, "ALL", 3) == 0 ||
  16234. XSTRNCMP(next, "DEFAULT", 7) == 0)
  16235. return 1; /* wolfSSL default */
  16236. do {
  16237. char* current = next;
  16238. char name[MAX_SUITE_NAME + 1];
  16239. int i;
  16240. word32 length;
  16241. next = XSTRSTR(next, ":");
  16242. length = min(sizeof(name), !next ? (word32)XSTRLEN(current) /* last */
  16243. : (word32)(next - current));
  16244. XSTRNCPY(name, current, length);
  16245. name[(length == sizeof(name)) ? length - 1 : length] = 0;
  16246. for (i = 0; i < suiteSz; i++) {
  16247. if (XSTRNCMP(name, cipher_names[i].name, sizeof(name)) == 0
  16248. #ifndef NO_ERROR_STRINGS
  16249. || XSTRNCMP(name, cipher_names[i].name_iana, sizeof(name)) == 0
  16250. #endif
  16251. ) {
  16252. #ifdef WOLFSSL_DTLS
  16253. /* don't allow stream ciphers with DTLS */
  16254. if (ctx->method->version.major == DTLS_MAJOR) {
  16255. if (XSTRSTR(name, "RC4") ||
  16256. XSTRSTR(name, "HC128") ||
  16257. XSTRSTR(name, "RABBIT"))
  16258. {
  16259. WOLFSSL_MSG("Stream ciphers not supported with DTLS");
  16260. continue;
  16261. }
  16262. }
  16263. #endif /* WOLFSSL_DTLS */
  16264. if (idx + 1 >= WOLFSSL_MAX_SUITE_SZ) {
  16265. WOLFSSL_MSG("WOLFSSL_MAX_SUITE_SZ set too low");
  16266. return 0; /* suites buffer not large enough, error out */
  16267. }
  16268. suites->suites[idx++] = cipher_names[i].cipherSuite0;
  16269. suites->suites[idx++] = cipher_names[i].cipherSuite;
  16270. /* The suites are either ECDSA, RSA, PSK, or Anon. The RSA
  16271. * suites don't necessarily have RSA in the name. */
  16272. #ifdef WOLFSSL_TLS13
  16273. if (cipher_names[i].cipherSuite0 == TLS13_BYTE ||
  16274. (cipher_names[i].cipherSuite0 == ECC_BYTE &&
  16275. (cipher_names[i].cipherSuite == TLS_SHA256_SHA256 ||
  16276. cipher_names[i].cipherSuite == TLS_SHA384_SHA384))) {
  16277. #ifndef NO_RSA
  16278. haveRSAsig = 1;
  16279. #endif
  16280. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  16281. defined(HAVE_ED448)
  16282. haveECDSAsig = 1;
  16283. #endif
  16284. }
  16285. else
  16286. #endif
  16287. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  16288. defined(HAVE_ED448)
  16289. if ((haveECDSAsig == 0) && XSTRSTR(name, "ECDSA"))
  16290. haveECDSAsig = 1;
  16291. else
  16292. #endif
  16293. #ifdef HAVE_ANON
  16294. if (XSTRSTR(name, "ADH"))
  16295. haveAnon = 1;
  16296. else
  16297. #endif
  16298. if (haveRSAsig == 0
  16299. #ifndef NO_PSK
  16300. && (XSTRSTR(name, "PSK") == NULL)
  16301. #endif
  16302. ) {
  16303. haveRSAsig = 1;
  16304. }
  16305. ret = 1; /* found at least one */
  16306. break;
  16307. }
  16308. }
  16309. }
  16310. while (next++); /* ++ needed to skip ':' */
  16311. if (ret) {
  16312. int keySz = 0;
  16313. #ifndef NO_CERTS
  16314. keySz = ctx->privateKeySz;
  16315. #endif
  16316. suites->setSuites = 1;
  16317. suites->suiteSz = (word16)idx;
  16318. InitSuitesHashSigAlgo(suites, haveECDSAsig, haveRSAsig, haveAnon, 1,
  16319. keySz);
  16320. }
  16321. (void)ctx;
  16322. return ret;
  16323. }
  16324. #if !defined(NO_WOLFSSL_SERVER) || !defined(NO_CERTS)
  16325. int PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo, word32 hashSigAlgoSz)
  16326. {
  16327. word32 i;
  16328. int ret = MATCH_SUITE_ERROR;
  16329. ssl->suites->sigAlgo = ssl->specs.sig_algo;
  16330. /* set defaults */
  16331. if (IsAtLeastTLSv1_3(ssl->version)) {
  16332. ssl->suites->hashAlgo = sha256_mac;
  16333. #ifndef NO_CERTS
  16334. ssl->suites->sigAlgo = ssl->buffers.keyType;
  16335. #endif
  16336. }
  16337. #ifndef WOLFSSL_NO_TLS12
  16338. else if (IsAtLeastTLSv1_2(ssl)) {
  16339. #ifdef WOLFSSL_ALLOW_TLS_SHA1
  16340. ssl->suites->hashAlgo = sha_mac;
  16341. #else
  16342. ssl->suites->hashAlgo = sha256_mac;
  16343. #endif
  16344. }
  16345. else {
  16346. ssl->suites->hashAlgo = sha_mac;
  16347. }
  16348. #endif
  16349. if (hashSigAlgoSz == 0)
  16350. return 0;
  16351. /* i+1 since peek a byte ahead for type */
  16352. for (i = 0; (i+1) < hashSigAlgoSz; i += HELLO_EXT_SIGALGO_SZ) {
  16353. byte hashAlgo = 0, sigAlgo = 0;
  16354. DecodeSigAlg(&hashSigAlgo[i], &hashAlgo, &sigAlgo);
  16355. #ifdef HAVE_ED25519
  16356. if (ssl->pkCurveOID == ECC_ED25519_OID) {
  16357. if (sigAlgo != ed25519_sa_algo)
  16358. continue;
  16359. if (sigAlgo == ed25519_sa_algo &&
  16360. ssl->suites->sigAlgo == ecc_dsa_sa_algo) {
  16361. ssl->suites->sigAlgo = sigAlgo;
  16362. ssl->suites->hashAlgo = sha512_mac;
  16363. ret = 0;
  16364. break;
  16365. }
  16366. }
  16367. #endif
  16368. #ifdef HAVE_ED448
  16369. if (ssl->pkCurveOID == ECC_ED448_OID) {
  16370. if (sigAlgo != ed448_sa_algo)
  16371. continue;
  16372. if (sigAlgo == ed448_sa_algo &&
  16373. ssl->suites->sigAlgo == ecc_dsa_sa_algo) {
  16374. ssl->suites->sigAlgo = sigAlgo;
  16375. ssl->suites->hashAlgo = sha512_mac;
  16376. ret = 0;
  16377. break;
  16378. }
  16379. }
  16380. #endif
  16381. #if defined(WOLFSSL_TLS13) && defined(HAVE_ECC)
  16382. if (IsAtLeastTLSv1_3(ssl->version) && sigAlgo == ssl->suites->sigAlgo &&
  16383. sigAlgo == ecc_dsa_sa_algo) {
  16384. int digestSz = GetMacDigestSize(hashAlgo);
  16385. if (digestSz <= 0)
  16386. continue;
  16387. /* TLS 1.3 signature algorithms for ECDSA match hash length with
  16388. * key size.
  16389. */
  16390. if (digestSz != ssl->buffers.keySz)
  16391. continue;
  16392. ssl->suites->hashAlgo = hashAlgo;
  16393. ssl->suites->sigAlgo = sigAlgo;
  16394. ret = 0;
  16395. break; /* done selected sig/hash algorithms */
  16396. }
  16397. else
  16398. #endif
  16399. /* For ECDSA the `USE_ECDSA_KEYSZ_HASH_ALGO` build option will choose a hash
  16400. * algorithm that matches the ephemeral ECDHE key size or the next highest
  16401. * available. This workaround resolves issue with some peer's that do not
  16402. * properly support scenarios such as a P-256 key hashed with SHA512.
  16403. */
  16404. #if defined(HAVE_ECC) && defined(USE_ECDSA_KEYSZ_HASH_ALGO)
  16405. if (sigAlgo == ssl->suites->sigAlgo && sigAlgo == ecc_dsa_sa_algo) {
  16406. int digestSz = GetMacDigestSize(hashAlgo);
  16407. if (digestSz <= 0)
  16408. continue;
  16409. /* For ecc_dsa_sa_algo, pick hash algo that is curve size unless
  16410. algorithm in not compiled in, then choose next highest */
  16411. if (digestSz == ssl->eccTempKeySz) {
  16412. ssl->suites->hashAlgo = hashAlgo;
  16413. ssl->suites->sigAlgo = sigAlgo;
  16414. #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
  16415. ssl->namedGroup = 0;
  16416. #endif
  16417. ret = 0;
  16418. break; /* done selected sig/hash algorithms */
  16419. }
  16420. /* not strong enough, so keep checking hashSigAlso list */
  16421. if (digestSz < ssl->eccTempKeySz)
  16422. continue;
  16423. /* mark as highest and check remainder of hashSigAlgo list */
  16424. ssl->suites->hashAlgo = hashAlgo;
  16425. ssl->suites->sigAlgo = sigAlgo;
  16426. ret = 0;
  16427. }
  16428. else
  16429. #endif
  16430. #ifdef WC_RSA_PSS
  16431. if (IsAtLeastTLSv1_3(ssl->version) &&
  16432. ssl->suites->sigAlgo == rsa_sa_algo &&
  16433. sigAlgo != rsa_pss_sa_algo) {
  16434. continue;
  16435. }
  16436. else if (sigAlgo == ssl->suites->sigAlgo ||
  16437. (sigAlgo == rsa_pss_sa_algo &&
  16438. (ssl->suites->sigAlgo == rsa_sa_algo)))
  16439. #else
  16440. if (sigAlgo == ssl->suites->sigAlgo)
  16441. #endif
  16442. {
  16443. /* pick highest available between both server and client */
  16444. switch (hashAlgo) {
  16445. case sha_mac:
  16446. #ifdef WOLFSSL_SHA224
  16447. case sha224_mac:
  16448. #endif
  16449. #ifndef NO_SHA256
  16450. case sha256_mac:
  16451. #endif
  16452. #ifdef WOLFSSL_SHA384
  16453. case sha384_mac:
  16454. #endif
  16455. #ifdef WOLFSSL_SHA512
  16456. case sha512_mac:
  16457. #endif
  16458. /* not strong enough, so keep checking hashSigAlso list */
  16459. if (hashAlgo < ssl->suites->hashAlgo) {
  16460. ret = 0;
  16461. continue;
  16462. }
  16463. /* mark as highest and check remainder of hashSigAlgo list */
  16464. ssl->suites->hashAlgo = hashAlgo;
  16465. ssl->suites->sigAlgo = sigAlgo;
  16466. break;
  16467. default:
  16468. continue;
  16469. }
  16470. ret = 0;
  16471. break;
  16472. }
  16473. #if defined(WOLFSSL_TLS13)
  16474. else if (ssl->specs.sig_algo == 0 && IsAtLeastTLSv1_3(ssl->version)) {
  16475. }
  16476. #endif
  16477. else if (ssl->specs.sig_algo == 0)
  16478. {
  16479. ssl->suites->hashAlgo = ssl->specs.mac_algorithm;
  16480. ret = 0;
  16481. }
  16482. }
  16483. return ret;
  16484. }
  16485. #endif /* !defined(NO_WOLFSSL_SERVER) || !defined(NO_CERTS) */
  16486. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  16487. /* Initialize HandShakeInfo */
  16488. void InitHandShakeInfo(HandShakeInfo* info, WOLFSSL* ssl)
  16489. {
  16490. int i;
  16491. info->ssl = ssl;
  16492. info->cipherName[0] = 0;
  16493. for (i = 0; i < MAX_PACKETS_HANDSHAKE; i++)
  16494. info->packetNames[i][0] = 0;
  16495. info->numberPackets = 0;
  16496. info->negotiationError = 0;
  16497. }
  16498. /* Set Final HandShakeInfo parameters */
  16499. void FinishHandShakeInfo(HandShakeInfo* info)
  16500. {
  16501. int i;
  16502. int sz = GetCipherNamesSize();
  16503. for (i = 0; i < sz; i++)
  16504. if (info->ssl->options.cipherSuite ==
  16505. (byte)cipher_names[i].cipherSuite) {
  16506. if (info->ssl->options.cipherSuite0 == ECC_BYTE)
  16507. continue; /* ECC suites at end */
  16508. XSTRNCPY(info->cipherName, cipher_names[i].name, MAX_CIPHERNAME_SZ);
  16509. info->cipherName[MAX_CIPHERNAME_SZ] = '\0';
  16510. break;
  16511. }
  16512. /* error max and min are negative numbers */
  16513. if (info->ssl->error <= MIN_PARAM_ERR && info->ssl->error >= MAX_PARAM_ERR)
  16514. info->negotiationError = info->ssl->error;
  16515. }
  16516. /* Add name to info packet names, increase packet name count */
  16517. void AddPacketName(WOLFSSL* ssl, const char* name)
  16518. {
  16519. #ifdef WOLFSSL_CALLBACKS
  16520. HandShakeInfo* info = &ssl->handShakeInfo;
  16521. if (info->numberPackets < MAX_PACKETS_HANDSHAKE) {
  16522. char* packetName = info->packetNames[info->numberPackets];
  16523. XSTRNCPY(packetName, name, MAX_PACKETNAME_SZ);
  16524. packetName[MAX_PACKETNAME_SZ] = '\0';
  16525. info->numberPackets++;
  16526. }
  16527. #endif
  16528. (void)ssl;
  16529. (void)name;
  16530. }
  16531. #ifdef WOLFSSL_CALLBACKS
  16532. /* Initialize TimeoutInfo */
  16533. void InitTimeoutInfo(TimeoutInfo* info)
  16534. {
  16535. int i;
  16536. info->timeoutName[0] = 0;
  16537. info->flags = 0;
  16538. for (i = 0; i < MAX_PACKETS_HANDSHAKE; i++) {
  16539. info->packets[i].packetName[0] = 0;
  16540. info->packets[i].timestamp.tv_sec = 0;
  16541. info->packets[i].timestamp.tv_usec = 0;
  16542. info->packets[i].bufferValue = 0;
  16543. info->packets[i].valueSz = 0;
  16544. }
  16545. info->numberPackets = 0;
  16546. info->timeoutValue.tv_sec = 0;
  16547. info->timeoutValue.tv_usec = 0;
  16548. }
  16549. /* Free TimeoutInfo */
  16550. void FreeTimeoutInfo(TimeoutInfo* info, void* heap)
  16551. {
  16552. int i;
  16553. (void)heap;
  16554. for (i = 0; i < MAX_PACKETS_HANDSHAKE; i++)
  16555. if (info->packets[i].bufferValue) {
  16556. XFREE(info->packets[i].bufferValue, heap, DYNAMIC_TYPE_INFO);
  16557. info->packets[i].bufferValue = 0;
  16558. }
  16559. }
  16560. /* Add packet name to previously added packet info */
  16561. void AddLateName(const char* name, TimeoutInfo* info)
  16562. {
  16563. /* make sure we have a valid previous one */
  16564. if (info->numberPackets > 0 && info->numberPackets <
  16565. MAX_PACKETS_HANDSHAKE) {
  16566. char* packetName = info->packets[info->numberPackets-1].packetName;
  16567. XSTRNCPY(packetName, name, MAX_PACKETNAME_SZ);
  16568. packetName[MAX_PACKETNAME_SZ] = '\0';
  16569. }
  16570. }
  16571. /* Add record header to previously added packet info */
  16572. void AddLateRecordHeader(const RecordLayerHeader* rl, TimeoutInfo* info)
  16573. {
  16574. /* make sure we have a valid previous one */
  16575. if (info->numberPackets > 0 && info->numberPackets <
  16576. MAX_PACKETS_HANDSHAKE) {
  16577. if (info->packets[info->numberPackets - 1].bufferValue)
  16578. XMEMCPY(info->packets[info->numberPackets - 1].bufferValue, rl,
  16579. RECORD_HEADER_SZ);
  16580. else
  16581. XMEMCPY(info->packets[info->numberPackets - 1].value, rl,
  16582. RECORD_HEADER_SZ);
  16583. }
  16584. }
  16585. #endif /* WOLFSSL_CALLBACKS */
  16586. /* Add PacketInfo to TimeoutInfo
  16587. *
  16588. * ssl WOLFSSL structure sending or receiving packet
  16589. * name name of packet being sent
  16590. * type type of packet being sent
  16591. * data data bing sent with packet
  16592. * sz size of data buffer
  16593. * written 1 if this packet is being written to wire, 0 if being read
  16594. * heap custom heap to use for mallocs/frees
  16595. */
  16596. void AddPacketInfo(WOLFSSL* ssl, const char* name, int type,
  16597. const byte* data, int sz, int written, void* heap)
  16598. {
  16599. #ifdef WOLFSSL_CALLBACKS
  16600. TimeoutInfo* info = &ssl->timeoutInfo;
  16601. if (info->numberPackets < (MAX_PACKETS_HANDSHAKE - 1)) {
  16602. WOLFSSL_TIMEVAL currTime;
  16603. /* may add name after */
  16604. if (name) {
  16605. char* packetName = info->packets[info->numberPackets].packetName;
  16606. XSTRNCPY(packetName, name, MAX_PACKETNAME_SZ);
  16607. packetName[MAX_PACKETNAME_SZ] = '\0';
  16608. }
  16609. /* add data, put in buffer if bigger than static buffer */
  16610. info->packets[info->numberPackets].valueSz = sz;
  16611. if (sz < MAX_VALUE_SZ)
  16612. XMEMCPY(info->packets[info->numberPackets].value, data, sz);
  16613. else {
  16614. info->packets[info->numberPackets].bufferValue =
  16615. (byte*)XMALLOC(sz, heap, DYNAMIC_TYPE_INFO);
  16616. if (!info->packets[info->numberPackets].bufferValue)
  16617. /* let next alloc catch, just don't fill, not fatal here */
  16618. info->packets[info->numberPackets].valueSz = 0;
  16619. else
  16620. XMEMCPY(info->packets[info->numberPackets].bufferValue,
  16621. data, sz);
  16622. }
  16623. gettimeofday(&currTime, 0);
  16624. info->packets[info->numberPackets].timestamp.tv_sec =
  16625. currTime.tv_sec;
  16626. info->packets[info->numberPackets].timestamp.tv_usec =
  16627. currTime.tv_usec;
  16628. info->numberPackets++;
  16629. }
  16630. #endif /* WOLFSSL_CALLBACKS */
  16631. #ifdef OPENSSL_EXTRA
  16632. if (ssl->protoMsgCb != NULL && sz > RECORD_HEADER_SZ) {
  16633. /* version from hex to dec 16 is 16^1, 256 from 16^2 and
  16634. 4096 from 16^3 */
  16635. int version = (ssl->version.minor & 0X0F) +
  16636. (ssl->version.minor & 0xF0) * 16 +
  16637. (ssl->version.major & 0X0F) * 256 +
  16638. (ssl->version.major & 0xF0) * 4096;
  16639. ssl->protoMsgCb(written, version, type,
  16640. (const void *)(data + RECORD_HEADER_SZ),
  16641. (size_t)(sz - RECORD_HEADER_SZ),
  16642. ssl, ssl->protoMsgCtx);
  16643. }
  16644. #endif /* OPENSSL_EXTRA */
  16645. (void)written;
  16646. (void)name;
  16647. (void)heap;
  16648. (void)type;
  16649. (void)ssl;
  16650. }
  16651. #endif /* WOLFSSL_CALLBACKS */
  16652. #if !defined(NO_CERTS)
  16653. /* Decode the private key - RSA/ECC/Ed25519/Ed448 - and creates a key object.
  16654. * The signature type is set as well.
  16655. * The maximum length of a signature is returned.
  16656. *
  16657. * ssl The SSL/TLS object.
  16658. * length The length of a signature.
  16659. * returns 0 on success, otherwise failure.
  16660. */
  16661. int DecodePrivateKey(WOLFSSL *ssl, word16* length)
  16662. {
  16663. int ret = BAD_FUNC_ARG;
  16664. int keySz;
  16665. word32 idx;
  16666. #ifdef HAVE_PK_CALLBACKS
  16667. /* allow no private key if using PK callbacks and CB is set */
  16668. if (wolfSSL_IsPrivatePkSet(ssl)) {
  16669. *length = GetPrivateKeySigSize(ssl);
  16670. return 0;
  16671. }
  16672. else
  16673. #endif
  16674. /* make sure private key exists */
  16675. if (ssl->buffers.key == NULL || ssl->buffers.key->buffer == NULL) {
  16676. WOLFSSL_MSG("Private key missing!");
  16677. ERROR_OUT(NO_PRIVATE_KEY, exit_dpk);
  16678. }
  16679. #ifdef HAVE_PKCS11
  16680. if (ssl->buffers.keyDevId != INVALID_DEVID && ssl->buffers.keyId) {
  16681. if (ssl->buffers.keyType == rsa_sa_algo)
  16682. ssl->hsType = DYNAMIC_TYPE_RSA;
  16683. else if (ssl->buffers.keyType == ecc_dsa_sa_algo)
  16684. ssl->hsType = DYNAMIC_TYPE_ECC;
  16685. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  16686. if (ret != 0) {
  16687. goto exit_dpk;
  16688. }
  16689. if (ssl->buffers.keyType == rsa_sa_algo) {
  16690. #ifndef NO_RSA
  16691. ret = wc_InitRsaKey_Id((RsaKey*)ssl->hsKey,
  16692. ssl->buffers.key->buffer, ssl->buffers.key->length,
  16693. ssl->heap, ssl->buffers.keyDevId);
  16694. if (ret == 0) {
  16695. if (ssl->buffers.keySz < ssl->options.minRsaKeySz) {
  16696. WOLFSSL_MSG("RSA key size too small");
  16697. ERROR_OUT(RSA_KEY_SIZE_E, exit_dpk);
  16698. }
  16699. /* Return the maximum signature length. */
  16700. *length = (word16)ssl->buffers.keySz;
  16701. }
  16702. #else
  16703. ret = NOT_COMPILED_IN;
  16704. #endif
  16705. }
  16706. else if (ssl->buffers.keyType == ecc_dsa_sa_algo) {
  16707. #ifdef HAVE_ECC
  16708. ret = wc_ecc_init_id((ecc_key*)ssl->hsKey, ssl->buffers.key->buffer,
  16709. ssl->buffers.key->length, ssl->heap,
  16710. ssl->buffers.keyDevId);
  16711. if (ret == 0) {
  16712. if (ssl->buffers.keySz < ssl->options.minEccKeySz) {
  16713. WOLFSSL_MSG("ECC key size too small");
  16714. ERROR_OUT(ECC_KEY_SIZE_E, exit_dpk);
  16715. }
  16716. /* Return the maximum signature length. */
  16717. *length = (word16)wc_ecc_sig_size_calc(ssl->buffers.keySz);
  16718. }
  16719. #else
  16720. ret = NOT_COMPILED_IN;
  16721. #endif
  16722. }
  16723. goto exit_dpk;
  16724. }
  16725. #endif
  16726. #ifndef NO_RSA
  16727. if (ssl->buffers.keyType == rsa_sa_algo || ssl->buffers.keyType == 0) {
  16728. ssl->hsType = DYNAMIC_TYPE_RSA;
  16729. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  16730. if (ret != 0) {
  16731. goto exit_dpk;
  16732. }
  16733. WOLFSSL_MSG("Trying RSA private key");
  16734. /* Set start of data to beginning of buffer. */
  16735. idx = 0;
  16736. /* Decode the key assuming it is an RSA private key. */
  16737. ret = wc_RsaPrivateKeyDecode(ssl->buffers.key->buffer, &idx,
  16738. (RsaKey*)ssl->hsKey, ssl->buffers.key->length);
  16739. if (ret == 0) {
  16740. WOLFSSL_MSG("Using RSA private key");
  16741. /* It worked so check it meets minimum key size requirements. */
  16742. keySz = wc_RsaEncryptSize((RsaKey*)ssl->hsKey);
  16743. if (keySz < 0) { /* check if keySz has error case */
  16744. ERROR_OUT(keySz, exit_dpk);
  16745. }
  16746. if (keySz < ssl->options.minRsaKeySz) {
  16747. WOLFSSL_MSG("RSA key size too small");
  16748. ERROR_OUT(RSA_KEY_SIZE_E, exit_dpk);
  16749. }
  16750. /* Return the maximum signature length. */
  16751. *length = (word16)keySz;
  16752. goto exit_dpk;
  16753. }
  16754. }
  16755. #endif /* !NO_RSA */
  16756. #ifdef HAVE_ECC
  16757. #ifndef NO_RSA
  16758. FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey);
  16759. #endif /* !NO_RSA */
  16760. if (ssl->buffers.keyType == ecc_dsa_sa_algo || ssl->buffers.keyType == 0) {
  16761. ssl->hsType = DYNAMIC_TYPE_ECC;
  16762. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  16763. if (ret != 0) {
  16764. goto exit_dpk;
  16765. }
  16766. #ifndef NO_RSA
  16767. WOLFSSL_MSG("Trying ECC private key, RSA didn't work");
  16768. #else
  16769. WOLFSSL_MSG("Trying ECC private key");
  16770. #endif
  16771. /* Set start of data to beginning of buffer. */
  16772. idx = 0;
  16773. /* Decode the key assuming it is an ECC private key. */
  16774. ret = wc_EccPrivateKeyDecode(ssl->buffers.key->buffer, &idx,
  16775. (ecc_key*)ssl->hsKey,
  16776. ssl->buffers.key->length);
  16777. if (ret == 0) {
  16778. WOLFSSL_MSG("Using ECC private key");
  16779. /* Check it meets the minimum ECC key size requirements. */
  16780. keySz = wc_ecc_size((ecc_key*)ssl->hsKey);
  16781. if (keySz < ssl->options.minEccKeySz) {
  16782. WOLFSSL_MSG("ECC key size too small");
  16783. ERROR_OUT(ECC_KEY_SIZE_E, exit_dpk);
  16784. }
  16785. /* Return the maximum signature length. */
  16786. *length = (word16)wc_ecc_sig_size((ecc_key*)ssl->hsKey);
  16787. goto exit_dpk;
  16788. }
  16789. }
  16790. #endif
  16791. #ifdef HAVE_ED25519
  16792. #if !defined(NO_RSA) || defined(HAVE_ECC)
  16793. FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey);
  16794. #endif
  16795. if (ssl->buffers.keyType == ed25519_sa_algo || ssl->buffers.keyType == 0) {
  16796. ssl->hsType = DYNAMIC_TYPE_ED25519;
  16797. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  16798. if (ret != 0) {
  16799. goto exit_dpk;
  16800. }
  16801. #ifdef HAVE_ECC
  16802. WOLFSSL_MSG("Trying ED25519 private key, ECC didn't work");
  16803. #elif !defined(NO_RSA)
  16804. WOLFSSL_MSG("Trying ED25519 private key, RSA didn't work");
  16805. #else
  16806. WOLFSSL_MSG("Trying ED25519 private key");
  16807. #endif
  16808. /* Set start of data to beginning of buffer. */
  16809. idx = 0;
  16810. /* Decode the key assuming it is an ED25519 private key. */
  16811. ret = wc_Ed25519PrivateKeyDecode(ssl->buffers.key->buffer, &idx,
  16812. (ed25519_key*)ssl->hsKey,
  16813. ssl->buffers.key->length);
  16814. if (ret == 0) {
  16815. WOLFSSL_MSG("Using ED25519 private key");
  16816. /* Check it meets the minimum ECC key size requirements. */
  16817. if (ED25519_KEY_SIZE < ssl->options.minEccKeySz) {
  16818. WOLFSSL_MSG("ED25519 key size too small");
  16819. ERROR_OUT(ECC_KEY_SIZE_E, exit_dpk);
  16820. }
  16821. /* Return the maximum signature length. */
  16822. *length = ED25519_SIG_SIZE;
  16823. goto exit_dpk;
  16824. }
  16825. }
  16826. #endif /* HAVE_ED25519 */
  16827. #ifdef HAVE_ED448
  16828. #if !defined(NO_RSA) || defined(HAVE_ECC)
  16829. FreeKey(ssl, ssl->hsType, (void**)&ssl->hsKey);
  16830. #endif
  16831. if (ssl->buffers.keyType == ed448_sa_algo || ssl->buffers.keyType == 0) {
  16832. ssl->hsType = DYNAMIC_TYPE_ED448;
  16833. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  16834. if (ret != 0) {
  16835. goto exit_dpk;
  16836. }
  16837. #ifdef HAVE_ED25519
  16838. WOLFSSL_MSG("Trying ED448 private key, ED25519 didn't work");
  16839. #elif defined(HAVE_ECC)
  16840. WOLFSSL_MSG("Trying ED448 private key, ECC didn't work");
  16841. #elif !defined(NO_RSA)
  16842. WOLFSSL_MSG("Trying ED448 private key, RSA didn't work");
  16843. #else
  16844. WOLFSSL_MSG("Trying ED447 private key");
  16845. #endif
  16846. /* Set start of data to beginning of buffer. */
  16847. idx = 0;
  16848. /* Decode the key assuming it is an ED448 private key. */
  16849. ret = wc_Ed448PrivateKeyDecode(ssl->buffers.key->buffer, &idx,
  16850. (ed448_key*)ssl->hsKey,
  16851. ssl->buffers.key->length);
  16852. if (ret == 0) {
  16853. WOLFSSL_MSG("Using ED448 private key");
  16854. /* Check it meets the minimum ECC key size requirements. */
  16855. if (ED448_KEY_SIZE < ssl->options.minEccKeySz) {
  16856. WOLFSSL_MSG("ED448 key size too small");
  16857. ERROR_OUT(ECC_KEY_SIZE_E, exit_dpk);
  16858. }
  16859. /* Return the maximum signature length. */
  16860. *length = ED448_SIG_SIZE;
  16861. goto exit_dpk;
  16862. }
  16863. }
  16864. #endif /* HAVE_ED448 */
  16865. (void)idx;
  16866. (void)keySz;
  16867. (void)length;
  16868. exit_dpk:
  16869. return ret;
  16870. }
  16871. #endif /* WOLFSSL_TLS13 || !NO_WOLFSSL_CLIENT */
  16872. /* client only parts */
  16873. #ifndef NO_WOLFSSL_CLIENT
  16874. #ifndef WOLFSSL_NO_TLS12
  16875. /* handle generation of client_hello (1) */
  16876. int SendClientHello(WOLFSSL* ssl)
  16877. {
  16878. byte *output;
  16879. word32 length, idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  16880. int sendSz;
  16881. int idSz = ssl->options.resuming
  16882. ? ssl->session.sessionIDSz
  16883. : 0;
  16884. int ret;
  16885. word16 extSz = 0;
  16886. #ifdef WOLFSSL_TLS13
  16887. if (IsAtLeastTLSv1_3(ssl->version))
  16888. return SendTls13ClientHello(ssl);
  16889. #endif
  16890. WOLFSSL_START(WC_FUNC_CLIENT_HELLO_SEND);
  16891. WOLFSSL_ENTER("SendClientHello");
  16892. if (ssl->suites == NULL) {
  16893. WOLFSSL_MSG("Bad suites pointer in SendClientHello");
  16894. return SUITES_ERROR;
  16895. }
  16896. #ifdef HAVE_SESSION_TICKET
  16897. if (ssl->options.resuming && ssl->session.ticketLen > 0) {
  16898. SessionTicket* ticket;
  16899. ticket = TLSX_SessionTicket_Create(0, ssl->session.ticket,
  16900. ssl->session.ticketLen, ssl->heap);
  16901. if (ticket == NULL) return MEMORY_E;
  16902. ret = TLSX_UseSessionTicket(&ssl->extensions, ticket, ssl->heap);
  16903. if (ret != WOLFSSL_SUCCESS) {
  16904. TLSX_SessionTicket_Free(ticket, ssl->heap);
  16905. return ret;
  16906. }
  16907. idSz = 0;
  16908. }
  16909. #endif
  16910. length = VERSION_SZ + RAN_LEN
  16911. + idSz + ENUM_LEN
  16912. + ssl->suites->suiteSz + SUITE_LEN
  16913. + COMP_LEN + ENUM_LEN;
  16914. #ifdef HAVE_TLS_EXTENSIONS
  16915. /* auto populate extensions supported unless user defined */
  16916. if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
  16917. return ret;
  16918. #ifdef HAVE_QSH
  16919. if (QSH_Init(ssl) != 0)
  16920. return MEMORY_E;
  16921. #endif
  16922. extSz = 0;
  16923. ret = TLSX_GetRequestSize(ssl, client_hello, &extSz);
  16924. if (ret != 0)
  16925. return ret;
  16926. length += extSz;
  16927. #else
  16928. if (IsAtLeastTLSv1_2(ssl) && ssl->suites->hashSigAlgoSz)
  16929. extSz += HELLO_EXT_SZ + HELLO_EXT_SIGALGO_SZ
  16930. + ssl->suites->hashSigAlgoSz;
  16931. #ifdef HAVE_EXTENDED_MASTER
  16932. if (ssl->options.haveEMS)
  16933. extSz += HELLO_EXT_SZ;
  16934. #endif
  16935. if (extSz != 0)
  16936. length += extSz + HELLO_EXT_SZ_SZ;
  16937. #endif
  16938. sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  16939. #ifdef WOLFSSL_DTLS
  16940. if (ssl->options.dtls) {
  16941. length += ENUM_LEN; /* cookie */
  16942. if (ssl->arrays->cookieSz != 0) length += ssl->arrays->cookieSz;
  16943. sendSz = length + DTLS_HANDSHAKE_HEADER_SZ + DTLS_RECORD_HEADER_SZ;
  16944. idx += DTLS_HANDSHAKE_EXTRA + DTLS_RECORD_EXTRA;
  16945. }
  16946. #endif
  16947. if (IsEncryptionOn(ssl, 1))
  16948. sendSz += MAX_MSG_EXTRA;
  16949. /* check for available size */
  16950. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  16951. return ret;
  16952. /* get output buffer */
  16953. output = ssl->buffers.outputBuffer.buffer +
  16954. ssl->buffers.outputBuffer.length;
  16955. AddHeaders(output, length, client_hello, ssl);
  16956. /* client hello, first version */
  16957. output[idx++] = ssl->version.major;
  16958. output[idx++] = ssl->version.minor;
  16959. ssl->chVersion = ssl->version; /* store in case changed */
  16960. /* then random */
  16961. if (ssl->options.connectState == CONNECT_BEGIN) {
  16962. ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN);
  16963. if (ret != 0)
  16964. return ret;
  16965. /* store random */
  16966. XMEMCPY(ssl->arrays->clientRandom, output + idx, RAN_LEN);
  16967. } else {
  16968. #ifdef WOLFSSL_DTLS
  16969. /* send same random on hello again */
  16970. XMEMCPY(output + idx, ssl->arrays->clientRandom, RAN_LEN);
  16971. #endif
  16972. }
  16973. idx += RAN_LEN;
  16974. /* then session id */
  16975. output[idx++] = (byte)idSz;
  16976. if (idSz) {
  16977. XMEMCPY(output + idx, ssl->session.sessionID,
  16978. ssl->session.sessionIDSz);
  16979. idx += ssl->session.sessionIDSz;
  16980. }
  16981. /* then DTLS cookie */
  16982. #ifdef WOLFSSL_DTLS
  16983. if (ssl->options.dtls) {
  16984. byte cookieSz = ssl->arrays->cookieSz;
  16985. output[idx++] = cookieSz;
  16986. if (cookieSz) {
  16987. XMEMCPY(&output[idx], ssl->arrays->cookie, cookieSz);
  16988. idx += cookieSz;
  16989. }
  16990. }
  16991. #endif
  16992. /* then cipher suites */
  16993. c16toa(ssl->suites->suiteSz, output + idx);
  16994. idx += OPAQUE16_LEN;
  16995. XMEMCPY(output + idx, &ssl->suites->suites, ssl->suites->suiteSz);
  16996. idx += ssl->suites->suiteSz;
  16997. /* last, compression */
  16998. output[idx++] = COMP_LEN;
  16999. if (ssl->options.usingCompression)
  17000. output[idx++] = ZLIB_COMPRESSION;
  17001. else
  17002. output[idx++] = NO_COMPRESSION;
  17003. #ifdef HAVE_TLS_EXTENSIONS
  17004. extSz = 0;
  17005. ret = TLSX_WriteRequest(ssl, output + idx, client_hello, &extSz);
  17006. if (ret != 0)
  17007. return ret;
  17008. idx += extSz;
  17009. (void)idx; /* suppress analyzer warning, keep idx current */
  17010. #else
  17011. if (extSz != 0) {
  17012. c16toa(extSz, output + idx);
  17013. idx += HELLO_EXT_SZ_SZ;
  17014. if (IsAtLeastTLSv1_2(ssl)) {
  17015. if (ssl->suites->hashSigAlgoSz) {
  17016. word16 i;
  17017. /* extension type */
  17018. c16toa(HELLO_EXT_SIG_ALGO, output + idx);
  17019. idx += HELLO_EXT_TYPE_SZ;
  17020. /* extension data length */
  17021. c16toa(HELLO_EXT_SIGALGO_SZ + ssl->suites->hashSigAlgoSz,
  17022. output + idx);
  17023. idx += HELLO_EXT_SZ_SZ;
  17024. /* sig algos length */
  17025. c16toa(ssl->suites->hashSigAlgoSz, output + idx);
  17026. idx += HELLO_EXT_SIGALGO_SZ;
  17027. for (i=0; i < ssl->suites->hashSigAlgoSz; i++, idx++) {
  17028. output[idx] = ssl->suites->hashSigAlgo[i];
  17029. }
  17030. }
  17031. }
  17032. #ifdef HAVE_EXTENDED_MASTER
  17033. if (ssl->options.haveEMS) {
  17034. c16toa(HELLO_EXT_EXTMS, output + idx);
  17035. idx += HELLO_EXT_TYPE_SZ;
  17036. c16toa(0, output + idx);
  17037. idx += HELLO_EXT_SZ_SZ;
  17038. }
  17039. #endif
  17040. }
  17041. #endif
  17042. if (IsEncryptionOn(ssl, 1)) {
  17043. byte* input;
  17044. int inputSz = idx - RECORD_HEADER_SZ; /* build msg adds rec hdr */
  17045. input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  17046. if (input == NULL)
  17047. return MEMORY_E;
  17048. XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
  17049. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  17050. handshake, 1, 0, 0);
  17051. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  17052. if (sendSz < 0)
  17053. return sendSz;
  17054. } else {
  17055. #ifdef WOLFSSL_DTLS
  17056. if (IsDtlsNotSctpMode(ssl)) {
  17057. if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
  17058. return ret;
  17059. }
  17060. if (ssl->options.dtls)
  17061. DtlsSEQIncrement(ssl, CUR_ORDER);
  17062. #endif
  17063. ret = HashOutput(ssl, output, sendSz, 0);
  17064. if (ret != 0)
  17065. return ret;
  17066. }
  17067. ssl->options.clientState = CLIENT_HELLO_COMPLETE;
  17068. #ifdef OPENSSL_EXTRA
  17069. ssl->cbmode = SSL_CB_MODE_WRITE;
  17070. if (ssl->CBIS != NULL)
  17071. ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, SSL_SUCCESS);
  17072. #endif
  17073. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  17074. if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
  17075. if (ssl->toInfoOn)
  17076. AddPacketInfo(ssl, "ClientHello", handshake, output, sendSz,
  17077. WRITE_PROTO, ssl->heap);
  17078. #endif
  17079. ssl->buffers.outputBuffer.length += sendSz;
  17080. ret = SendBuffered(ssl);
  17081. WOLFSSL_LEAVE("SendClientHello", ret);
  17082. WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
  17083. return ret;
  17084. }
  17085. /* handle processing of DTLS hello_verify_request (3) */
  17086. static int DoHelloVerifyRequest(WOLFSSL* ssl, const byte* input,
  17087. word32* inOutIdx, word32 size)
  17088. {
  17089. ProtocolVersion pv;
  17090. byte cookieSz;
  17091. word32 begin = *inOutIdx;
  17092. #ifdef WOLFSSL_CALLBACKS
  17093. if (ssl->hsInfoOn) AddPacketName(ssl, "HelloVerifyRequest");
  17094. if (ssl->toInfoOn) AddLateName("HelloVerifyRequest", &ssl->timeoutInfo);
  17095. #endif
  17096. #ifdef WOLFSSL_DTLS
  17097. if (ssl->options.dtls) {
  17098. DtlsMsgPoolReset(ssl);
  17099. }
  17100. #endif
  17101. if (OPAQUE16_LEN + OPAQUE8_LEN > size)
  17102. return BUFFER_ERROR;
  17103. XMEMCPY(&pv, input + *inOutIdx, OPAQUE16_LEN);
  17104. *inOutIdx += OPAQUE16_LEN;
  17105. if (pv.major != DTLS_MAJOR ||
  17106. (pv.minor != DTLS_MINOR && pv.minor != DTLSv1_2_MINOR))
  17107. return VERSION_ERROR;
  17108. cookieSz = input[(*inOutIdx)++];
  17109. if (cookieSz) {
  17110. if ((*inOutIdx - begin) + cookieSz > size)
  17111. return BUFFER_ERROR;
  17112. #ifdef WOLFSSL_DTLS
  17113. if (cookieSz <= MAX_COOKIE_LEN) {
  17114. XMEMCPY(ssl->arrays->cookie, input + *inOutIdx, cookieSz);
  17115. ssl->arrays->cookieSz = cookieSz;
  17116. }
  17117. #endif
  17118. *inOutIdx += cookieSz;
  17119. }
  17120. ssl->options.serverState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
  17121. return 0;
  17122. }
  17123. static WC_INLINE int DSH_CheckSessionId(WOLFSSL* ssl)
  17124. {
  17125. int ret = 0;
  17126. #ifdef HAVE_SECRET_CALLBACK
  17127. /* If a session secret callback exists, we are using that
  17128. * key instead of the saved session key. */
  17129. ret = ret || (ssl->sessionSecretCb != NULL);
  17130. #endif
  17131. #ifdef HAVE_SESSION_TICKET
  17132. /* server may send blank ticket which may not be expected to indicate
  17133. * existing one ok but will also be sending a new one */
  17134. ret = ret || (ssl->session.ticketLen > 0);
  17135. #endif
  17136. ret = ret ||
  17137. (ssl->options.haveSessionId && XMEMCMP(ssl->arrays->sessionID,
  17138. ssl->session.sessionID, ID_LEN) == 0);
  17139. return ret;
  17140. }
  17141. /* Check the version in the received message is valid and set protocol
  17142. * version to use.
  17143. *
  17144. * ssl The SSL/TLS object.
  17145. * pv The protocol version from the packet.
  17146. * returns 0 on success, otherwise failure.
  17147. */
  17148. int CheckVersion(WOLFSSL *ssl, ProtocolVersion pv)
  17149. {
  17150. #ifdef WOLFSSL_TLS13_DRAFT
  17151. if (pv.major == TLS_DRAFT_MAJOR) {
  17152. pv.major = SSLv3_MAJOR;
  17153. pv.minor = TLSv1_3_MINOR;
  17154. }
  17155. #endif
  17156. #ifdef OPENSSL_EXTRA
  17157. if (ssl->CBIS != NULL) {
  17158. ssl->CBIS(ssl, SSL_CB_HANDSHAKE_START, SSL_SUCCESS);
  17159. }
  17160. #endif
  17161. if (pv.minor > ssl->version.minor) {
  17162. WOLFSSL_MSG("Server using higher version, fatal error");
  17163. return VERSION_ERROR;
  17164. }
  17165. if (pv.minor < ssl->version.minor) {
  17166. WOLFSSL_MSG("server using lower version");
  17167. /* Check for downgrade attack. */
  17168. if (!ssl->options.downgrade) {
  17169. WOLFSSL_MSG("\tno downgrade allowed, fatal error");
  17170. return VERSION_ERROR;
  17171. }
  17172. if (pv.minor < ssl->options.minDowngrade) {
  17173. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  17174. return VERSION_ERROR;
  17175. }
  17176. #ifdef HAVE_SECURE_RENEGOTIATION
  17177. if (ssl->secure_renegotiation &&
  17178. ssl->secure_renegotiation->enabled &&
  17179. ssl->options.handShakeDone) {
  17180. WOLFSSL_MSG("Server changed version during scr");
  17181. return VERSION_ERROR;
  17182. }
  17183. #endif
  17184. /* Checks made - OK to downgrade. */
  17185. if (pv.minor == SSLv3_MINOR) {
  17186. /* turn off tls */
  17187. WOLFSSL_MSG("\tdowngrading to SSLv3");
  17188. ssl->options.tls = 0;
  17189. ssl->options.tls1_1 = 0;
  17190. ssl->version.minor = SSLv3_MINOR;
  17191. }
  17192. else if (pv.minor == TLSv1_MINOR) {
  17193. /* turn off tls 1.1+ */
  17194. WOLFSSL_MSG("\tdowngrading to TLSv1");
  17195. ssl->options.tls1_1 = 0;
  17196. ssl->version.minor = TLSv1_MINOR;
  17197. }
  17198. else if (pv.minor == TLSv1_1_MINOR) {
  17199. WOLFSSL_MSG("\tdowngrading to TLSv1.1");
  17200. ssl->version.minor = TLSv1_1_MINOR;
  17201. }
  17202. else if (pv.minor == TLSv1_2_MINOR) {
  17203. WOLFSSL_MSG(" downgrading to TLSv1.2");
  17204. ssl->version.minor = TLSv1_2_MINOR;
  17205. }
  17206. }
  17207. #ifdef OPENSSL_EXTRA
  17208. /* check if option is set to not allow the current version
  17209. * set from either wolfSSL_set_options or wolfSSL_CTX_set_options */
  17210. if (!ssl->options.dtls && ssl->options.downgrade &&
  17211. ssl->options.mask > 0) {
  17212. if (ssl->version.minor == TLSv1_2_MINOR &&
  17213. (ssl->options.mask & SSL_OP_NO_TLSv1_2) == SSL_OP_NO_TLSv1_2) {
  17214. WOLFSSL_MSG("\tOption set to not allow TLSv1.2, Downgrading");
  17215. ssl->version.minor = TLSv1_1_MINOR;
  17216. }
  17217. if (ssl->version.minor == TLSv1_1_MINOR &&
  17218. (ssl->options.mask & SSL_OP_NO_TLSv1_1) == SSL_OP_NO_TLSv1_1) {
  17219. WOLFSSL_MSG("\tOption set to not allow TLSv1.1, Downgrading");
  17220. ssl->options.tls1_1 = 0;
  17221. ssl->version.minor = TLSv1_MINOR;
  17222. }
  17223. if (ssl->version.minor == TLSv1_MINOR &&
  17224. (ssl->options.mask & SSL_OP_NO_TLSv1) == SSL_OP_NO_TLSv1) {
  17225. WOLFSSL_MSG("\tOption set to not allow TLSv1, Downgrading");
  17226. ssl->options.tls = 0;
  17227. ssl->options.tls1_1 = 0;
  17228. ssl->version.minor = SSLv3_MINOR;
  17229. }
  17230. if (ssl->version.minor == SSLv3_MINOR &&
  17231. (ssl->options.mask & SSL_OP_NO_SSLv3) == SSL_OP_NO_SSLv3) {
  17232. WOLFSSL_MSG("\tError, option set to not allow SSLv3");
  17233. return VERSION_ERROR;
  17234. }
  17235. if (ssl->version.minor < ssl->options.minDowngrade) {
  17236. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  17237. return VERSION_ERROR;
  17238. }
  17239. }
  17240. #endif
  17241. return 0;
  17242. }
  17243. /* handle processing of server_hello (2) */
  17244. int DoServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  17245. word32 helloSz)
  17246. {
  17247. byte cs0; /* cipher suite bytes 0, 1 */
  17248. byte cs1;
  17249. ProtocolVersion pv;
  17250. byte compression;
  17251. word32 i = *inOutIdx;
  17252. word32 begin = i;
  17253. int ret;
  17254. WOLFSSL_START(WC_FUNC_SERVER_HELLO_DO);
  17255. WOLFSSL_ENTER("DoServerHello");
  17256. #ifdef WOLFSSL_CALLBACKS
  17257. if (ssl->hsInfoOn) AddPacketName(ssl, "ServerHello");
  17258. if (ssl->toInfoOn) AddLateName("ServerHello", &ssl->timeoutInfo);
  17259. #endif
  17260. /* protocol version, random and session id length check */
  17261. if (OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz)
  17262. return BUFFER_ERROR;
  17263. /* protocol version */
  17264. XMEMCPY(&pv, input + i, OPAQUE16_LEN);
  17265. i += OPAQUE16_LEN;
  17266. ret = CheckVersion(ssl, pv);
  17267. if (ret != 0)
  17268. return ret;
  17269. #ifdef WOLFSSL_TLS13
  17270. if (IsAtLeastTLSv1_3(pv)) {
  17271. byte type = server_hello;
  17272. return DoTls13ServerHello(ssl, input, inOutIdx, helloSz, &type);
  17273. }
  17274. #endif
  17275. /* random */
  17276. XMEMCPY(ssl->arrays->serverRandom, input + i, RAN_LEN);
  17277. i += RAN_LEN;
  17278. /* session id */
  17279. ssl->arrays->sessionIDSz = input[i++];
  17280. if (ssl->arrays->sessionIDSz > ID_LEN) {
  17281. WOLFSSL_MSG("Invalid session ID size");
  17282. ssl->arrays->sessionIDSz = 0;
  17283. return BUFFER_ERROR;
  17284. }
  17285. else if (ssl->arrays->sessionIDSz) {
  17286. if ((i - begin) + ssl->arrays->sessionIDSz > helloSz)
  17287. return BUFFER_ERROR;
  17288. XMEMCPY(ssl->arrays->sessionID, input + i,
  17289. ssl->arrays->sessionIDSz);
  17290. i += ssl->arrays->sessionIDSz;
  17291. ssl->options.haveSessionId = 1;
  17292. }
  17293. /* suite and compression */
  17294. if ((i - begin) + OPAQUE16_LEN + OPAQUE8_LEN > helloSz)
  17295. return BUFFER_ERROR;
  17296. cs0 = input[i++];
  17297. cs1 = input[i++];
  17298. #ifdef HAVE_SECURE_RENEGOTIATION
  17299. if (ssl->secure_renegotiation && ssl->secure_renegotiation->enabled &&
  17300. ssl->options.handShakeDone) {
  17301. if (ssl->options.cipherSuite0 != cs0 ||
  17302. ssl->options.cipherSuite != cs1) {
  17303. WOLFSSL_MSG("Server changed cipher suite during scr");
  17304. return MATCH_SUITE_ERROR;
  17305. }
  17306. }
  17307. #endif
  17308. ssl->options.cipherSuite0 = cs0;
  17309. ssl->options.cipherSuite = cs1;
  17310. compression = input[i++];
  17311. #ifndef WOLFSSL_NO_STRICT_CIPHER_SUITE
  17312. {
  17313. word32 idx, found = 0;
  17314. /* confirm server_hello cipher suite is one sent in client_hello */
  17315. for (idx = 0; idx < ssl->suites->suiteSz; idx += 2) {
  17316. if (ssl->suites->suites[idx] == cs0 &&
  17317. ssl->suites->suites[idx+1] == cs1) {
  17318. found = 1;
  17319. break;
  17320. }
  17321. }
  17322. if (!found) {
  17323. WOLFSSL_MSG("ServerHello did not use cipher suite from ClientHello");
  17324. return MATCH_SUITE_ERROR;
  17325. }
  17326. }
  17327. #endif /* !WOLFSSL_NO_STRICT_CIPHER_SUITE */
  17328. if (compression != NO_COMPRESSION && !ssl->options.usingCompression) {
  17329. WOLFSSL_MSG("Server forcing compression w/o support");
  17330. return COMPRESSION_ERROR;
  17331. }
  17332. if (compression != ZLIB_COMPRESSION && ssl->options.usingCompression) {
  17333. WOLFSSL_MSG("Server refused compression, turning off");
  17334. ssl->options.usingCompression = 0; /* turn off if server refused */
  17335. }
  17336. *inOutIdx = i;
  17337. #ifdef HAVE_TLS_EXTENSIONS
  17338. if ( (i - begin) < helloSz) {
  17339. if (TLSX_SupportExtensions(ssl)) {
  17340. word16 totalExtSz;
  17341. if ((i - begin) + OPAQUE16_LEN > helloSz)
  17342. return BUFFER_ERROR;
  17343. ato16(&input[i], &totalExtSz);
  17344. i += OPAQUE16_LEN;
  17345. if ((i - begin) + totalExtSz > helloSz)
  17346. return BUFFER_ERROR;
  17347. if ((ret = TLSX_Parse(ssl, (byte *) input + i, totalExtSz,
  17348. server_hello, NULL)))
  17349. return ret;
  17350. i += totalExtSz;
  17351. *inOutIdx = i;
  17352. }
  17353. else
  17354. *inOutIdx = begin + helloSz; /* skip extensions */
  17355. }
  17356. else
  17357. ssl->options.haveEMS = 0; /* If no extensions, no EMS */
  17358. #else
  17359. {
  17360. int allowExt = 0;
  17361. byte pendingEMS = 0;
  17362. if ( (i - begin) < helloSz) {
  17363. if (ssl->version.major == SSLv3_MAJOR &&
  17364. ssl->version.minor >= TLSv1_MINOR) {
  17365. allowExt = 1;
  17366. }
  17367. #ifdef WOLFSSL_DTLS
  17368. if (ssl->version.major == DTLS_MAJOR)
  17369. allowExt = 1;
  17370. #endif
  17371. if (allowExt) {
  17372. word16 totalExtSz;
  17373. if ((i - begin) + OPAQUE16_LEN > helloSz)
  17374. return BUFFER_ERROR;
  17375. ato16(&input[i], &totalExtSz);
  17376. i += OPAQUE16_LEN;
  17377. if ((i - begin) + totalExtSz > helloSz)
  17378. return BUFFER_ERROR;
  17379. while (totalExtSz) {
  17380. word16 extId, extSz;
  17381. if (OPAQUE16_LEN + OPAQUE16_LEN > totalExtSz)
  17382. return BUFFER_ERROR;
  17383. ato16(&input[i], &extId);
  17384. i += OPAQUE16_LEN;
  17385. ato16(&input[i], &extSz);
  17386. i += OPAQUE16_LEN;
  17387. if (OPAQUE16_LEN + OPAQUE16_LEN + extSz > totalExtSz)
  17388. return BUFFER_ERROR;
  17389. if (extId == HELLO_EXT_EXTMS)
  17390. pendingEMS = 1;
  17391. else
  17392. i += extSz;
  17393. totalExtSz -= OPAQUE16_LEN + OPAQUE16_LEN + extSz;
  17394. }
  17395. *inOutIdx = i;
  17396. }
  17397. else
  17398. *inOutIdx = begin + helloSz; /* skip extensions */
  17399. }
  17400. if (!pendingEMS && ssl->options.haveEMS)
  17401. ssl->options.haveEMS = 0;
  17402. }
  17403. #endif
  17404. ssl->options.serverState = SERVER_HELLO_COMPLETE;
  17405. if (IsEncryptionOn(ssl, 0)) {
  17406. *inOutIdx += ssl->keys.padSz;
  17407. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  17408. if (ssl->options.startedETMWrite &&
  17409. ssl->specs.cipher_type == block) {
  17410. *inOutIdx += MacSize(ssl);
  17411. }
  17412. #endif
  17413. }
  17414. #ifdef HAVE_SECRET_CALLBACK
  17415. if (ssl->sessionSecretCb != NULL) {
  17416. int secretSz = SECRET_LEN;
  17417. ret = ssl->sessionSecretCb(ssl, ssl->session.masterSecret,
  17418. &secretSz, ssl->sessionSecretCtx);
  17419. if (ret != 0 || secretSz != SECRET_LEN)
  17420. return SESSION_SECRET_CB_E;
  17421. }
  17422. #endif /* HAVE_SECRET_CALLBACK */
  17423. ret = CompleteServerHello(ssl);
  17424. WOLFSSL_LEAVE("DoServerHello", ret);
  17425. WOLFSSL_END(WC_FUNC_SERVER_HELLO_DO);
  17426. return ret;
  17427. }
  17428. #ifdef WOLFSSL_TLS13
  17429. /* returns 1 if able to do TLS 1.3 otherwise 0 */
  17430. static int TLSv1_3_Capable(WOLFSSL* ssl)
  17431. {
  17432. #ifndef WOLFSSL_TLS13
  17433. return 0;
  17434. #else
  17435. int ret = 0;
  17436. if (IsAtLeastTLSv1_3(ssl->ctx->method->version)) {
  17437. ret = 1;
  17438. }
  17439. #ifdef OPENSSL_EXTRA
  17440. if ((wolfSSL_get_options(ssl) & SSL_OP_NO_TLSv1_3)) {
  17441. /* option set at run time to disable TLS 1.3 */
  17442. ret = 0;
  17443. }
  17444. #endif
  17445. return ret;
  17446. #endif
  17447. }
  17448. #endif /* WOLFSSL_TLS13 */
  17449. int CompleteServerHello(WOLFSSL* ssl)
  17450. {
  17451. int ret;
  17452. if (!ssl->options.resuming) {
  17453. byte* down = ssl->arrays->serverRandom + RAN_LEN -
  17454. TLS13_DOWNGRADE_SZ - 1;
  17455. byte vers = ssl->arrays->serverRandom[RAN_LEN - 1];
  17456. #ifdef WOLFSSL_TLS13
  17457. if (TLSv1_3_Capable(ssl)) {
  17458. /* TLS v1.3 capable client not allowed to downgrade when
  17459. * connecting to TLS v1.3 capable server unless cipher suite
  17460. * demands it.
  17461. */
  17462. if (XMEMCMP(down, tls13Downgrade, TLS13_DOWNGRADE_SZ) == 0 &&
  17463. (vers == 0 || vers == 1)) {
  17464. SendAlert(ssl, alert_fatal, illegal_parameter);
  17465. return VERSION_ERROR;
  17466. }
  17467. }
  17468. else
  17469. #endif
  17470. if (ssl->ctx->method->version.major == SSLv3_MAJOR &&
  17471. ssl->ctx->method->version.minor == TLSv1_2_MINOR) {
  17472. /* TLS v1.2 capable client not allowed to downgrade when
  17473. * connecting to TLS v1.2 capable server.
  17474. */
  17475. if (XMEMCMP(down, tls13Downgrade, TLS13_DOWNGRADE_SZ) == 0 &&
  17476. vers == 0) {
  17477. SendAlert(ssl, alert_fatal, illegal_parameter);
  17478. return VERSION_ERROR;
  17479. }
  17480. }
  17481. }
  17482. else {
  17483. if (DSH_CheckSessionId(ssl)) {
  17484. if (SetCipherSpecs(ssl) == 0) {
  17485. XMEMCPY(ssl->arrays->masterSecret,
  17486. ssl->session.masterSecret, SECRET_LEN);
  17487. #ifdef NO_OLD_TLS
  17488. ret = DeriveTlsKeys(ssl);
  17489. #else
  17490. ret = -1; /* default value */
  17491. #ifndef NO_TLS
  17492. if (ssl->options.tls)
  17493. ret = DeriveTlsKeys(ssl);
  17494. #endif
  17495. if (!ssl->options.tls)
  17496. ret = DeriveKeys(ssl);
  17497. #endif /* NO_OLD_TLS */
  17498. ssl->options.serverState = SERVER_HELLODONE_COMPLETE;
  17499. return ret;
  17500. }
  17501. else {
  17502. WOLFSSL_MSG("Unsupported cipher suite, DoServerHello");
  17503. return UNSUPPORTED_SUITE;
  17504. }
  17505. }
  17506. else {
  17507. WOLFSSL_MSG("Server denied resumption attempt");
  17508. ssl->options.resuming = 0; /* server denied resumption try */
  17509. }
  17510. }
  17511. #ifdef WOLFSSL_DTLS
  17512. if (ssl->options.dtls) {
  17513. DtlsMsgPoolReset(ssl);
  17514. }
  17515. #endif
  17516. return SetCipherSpecs(ssl);
  17517. }
  17518. #endif /* WOLFSSL_NO_TLS12 */
  17519. /* Make sure client setup is valid for this suite, true on success */
  17520. int VerifyClientSuite(WOLFSSL* ssl)
  17521. {
  17522. int havePSK = 0;
  17523. byte first = ssl->options.cipherSuite0;
  17524. byte second = ssl->options.cipherSuite;
  17525. WOLFSSL_ENTER("VerifyClientSuite");
  17526. #ifndef NO_PSK
  17527. havePSK = ssl->options.havePSK;
  17528. #endif
  17529. if (CipherRequires(first, second, REQUIRES_PSK)) {
  17530. WOLFSSL_MSG("Requires PSK");
  17531. if (havePSK == 0) {
  17532. WOLFSSL_MSG("Don't have PSK");
  17533. return 0;
  17534. }
  17535. }
  17536. return 1; /* success */
  17537. }
  17538. #ifndef WOLFSSL_NO_TLS12
  17539. #ifndef NO_CERTS
  17540. /* handle processing of certificate_request (13) */
  17541. static int DoCertificateRequest(WOLFSSL* ssl, const byte* input, word32*
  17542. inOutIdx, word32 size)
  17543. {
  17544. word16 len;
  17545. word32 begin = *inOutIdx;
  17546. #ifdef OPENSSL_EXTRA
  17547. int ret;
  17548. WOLFSSL_X509* x509 = NULL;
  17549. WOLFSSL_EVP_PKEY* pkey = NULL;
  17550. #endif
  17551. WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_DO);
  17552. WOLFSSL_ENTER("DoCertificateRequest");
  17553. #ifdef WOLFSSL_CALLBACKS
  17554. if (ssl->hsInfoOn)
  17555. AddPacketName(ssl, "CertificateRequest");
  17556. if (ssl->toInfoOn)
  17557. AddLateName("CertificateRequest", &ssl->timeoutInfo);
  17558. #endif
  17559. if (OPAQUE8_LEN > size)
  17560. return BUFFER_ERROR;
  17561. len = input[(*inOutIdx)++];
  17562. if ((*inOutIdx - begin) + len > size)
  17563. return BUFFER_ERROR;
  17564. /* types, read in here */
  17565. *inOutIdx += len;
  17566. /* signature and hash signature algorithm */
  17567. if (IsAtLeastTLSv1_2(ssl)) {
  17568. if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
  17569. return BUFFER_ERROR;
  17570. ato16(input + *inOutIdx, &len);
  17571. *inOutIdx += OPAQUE16_LEN;
  17572. if ((*inOutIdx - begin) + len > size)
  17573. return BUFFER_ERROR;
  17574. if (PickHashSigAlgo(ssl, input + *inOutIdx, len) != 0 &&
  17575. ssl->buffers.certificate &&
  17576. ssl->buffers.certificate->buffer) {
  17577. #ifdef HAVE_PK_CALLBACKS
  17578. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
  17579. WOLFSSL_MSG("Using PK for client private key");
  17580. return INVALID_PARAMETER;
  17581. }
  17582. #endif
  17583. if (ssl->buffers.key && ssl->buffers.key->buffer) {
  17584. return INVALID_PARAMETER;
  17585. }
  17586. }
  17587. *inOutIdx += len;
  17588. #ifdef WC_RSA_PSS
  17589. ssl->pssAlgo = 0;
  17590. if (ssl->suites->sigAlgo == rsa_pss_sa_algo)
  17591. ssl->pssAlgo |= 1 << ssl->suites->hashAlgo;
  17592. #endif
  17593. }
  17594. /* authorities */
  17595. if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
  17596. return BUFFER_ERROR;
  17597. ato16(input + *inOutIdx, &len);
  17598. *inOutIdx += OPAQUE16_LEN;
  17599. if ((*inOutIdx - begin) + len > size)
  17600. return BUFFER_ERROR;
  17601. while (len) {
  17602. word16 dnSz;
  17603. if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
  17604. return BUFFER_ERROR;
  17605. ato16(input + *inOutIdx, &dnSz);
  17606. *inOutIdx += OPAQUE16_LEN;
  17607. if ((*inOutIdx - begin) + dnSz > size)
  17608. return BUFFER_ERROR;
  17609. *inOutIdx += dnSz;
  17610. len -= OPAQUE16_LEN + dnSz;
  17611. }
  17612. #ifdef OPENSSL_EXTRA
  17613. /* call client cert callback if no cert has been loaded */
  17614. if ((ssl->ctx->CBClientCert != NULL) &&
  17615. (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer)) {
  17616. ret = ssl->ctx->CBClientCert(ssl, &x509, &pkey);
  17617. if (ret == 1) {
  17618. if ((wolfSSL_use_certificate(ssl, x509) != WOLFSSL_SUCCESS) ||
  17619. (wolfSSL_use_PrivateKey(ssl, pkey) != WOLFSSL_SUCCESS)) {
  17620. return CLIENT_CERT_CB_ERROR;
  17621. }
  17622. wolfSSL_X509_free(x509);
  17623. wolfSSL_EVP_PKEY_free(pkey);
  17624. } else if (ret < 0) {
  17625. return WOLFSSL_ERROR_WANT_X509_LOOKUP;
  17626. }
  17627. }
  17628. #endif
  17629. /* don't send client cert or cert verify if user hasn't provided
  17630. cert and private key */
  17631. if (ssl->buffers.certificate && ssl->buffers.certificate->buffer) {
  17632. #ifdef HAVE_PK_CALLBACKS
  17633. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
  17634. WOLFSSL_MSG("Using PK for client private key");
  17635. ssl->options.sendVerify = SEND_CERT;
  17636. }
  17637. #endif
  17638. if (ssl->buffers.key && ssl->buffers.key->buffer) {
  17639. ssl->options.sendVerify = SEND_CERT;
  17640. }
  17641. }
  17642. #ifdef OPENSSL_EXTRA
  17643. else
  17644. #else
  17645. else if (IsTLS(ssl))
  17646. #endif
  17647. {
  17648. ssl->options.sendVerify = SEND_BLANK_CERT;
  17649. }
  17650. if (IsEncryptionOn(ssl, 0)) {
  17651. *inOutIdx += ssl->keys.padSz;
  17652. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  17653. if (ssl->options.startedETMRead)
  17654. *inOutIdx += MacSize(ssl);
  17655. #endif
  17656. }
  17657. WOLFSSL_LEAVE("DoCertificateRequest", 0);
  17658. WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_DO);
  17659. return 0;
  17660. }
  17661. #endif /* !NO_CERTS */
  17662. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  17663. static int CheckCurveId(int tlsCurveId)
  17664. {
  17665. int ret = ECC_CURVE_ERROR;
  17666. switch (tlsCurveId) {
  17667. #if defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)
  17668. #ifndef NO_ECC_SECP
  17669. case WOLFSSL_ECC_SECP160R1: return ECC_SECP160R1_OID;
  17670. #endif /* !NO_ECC_SECP */
  17671. #ifdef HAVE_ECC_SECPR2
  17672. case WOLFSSL_ECC_SECP160R2: return ECC_SECP160R2_OID;
  17673. #endif /* HAVE_ECC_SECPR2 */
  17674. #ifdef HAVE_ECC_KOBLITZ
  17675. case WOLFSSL_ECC_SECP160K1: return ECC_SECP160K1_OID;
  17676. #endif /* HAVE_ECC_KOBLITZ */
  17677. #endif
  17678. #if defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)
  17679. #ifndef NO_ECC_SECP
  17680. case WOLFSSL_ECC_SECP192R1: return ECC_SECP192R1_OID;
  17681. #endif /* !NO_ECC_SECP */
  17682. #ifdef HAVE_ECC_KOBLITZ
  17683. case WOLFSSL_ECC_SECP192K1: return ECC_SECP192K1_OID;
  17684. #endif /* HAVE_ECC_KOBLITZ */
  17685. #endif
  17686. #if defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)
  17687. #ifndef NO_ECC_SECP
  17688. case WOLFSSL_ECC_SECP224R1: return ECC_SECP224R1_OID;
  17689. #endif /* !NO_ECC_SECP */
  17690. #ifdef HAVE_ECC_KOBLITZ
  17691. case WOLFSSL_ECC_SECP224K1: return ECC_SECP224K1_OID;
  17692. #endif /* HAVE_ECC_KOBLITZ */
  17693. #endif
  17694. #ifdef HAVE_CURVE25519
  17695. case WOLFSSL_ECC_X25519: return ECC_X25519_OID;
  17696. #endif
  17697. #if !defined(NO_ECC256) || defined(HAVE_ALL_CURVES)
  17698. #ifndef NO_ECC_SECP
  17699. case WOLFSSL_ECC_SECP256R1: return ECC_SECP256R1_OID;
  17700. #endif /* !NO_ECC_SECP */
  17701. #ifdef HAVE_ECC_KOBLITZ
  17702. case WOLFSSL_ECC_SECP256K1: return ECC_SECP256K1_OID;
  17703. #endif /* HAVE_ECC_KOBLITZ */
  17704. #ifdef HAVE_ECC_BRAINPOOL
  17705. case WOLFSSL_ECC_BRAINPOOLP256R1: return ECC_BRAINPOOLP256R1_OID;
  17706. #endif /* HAVE_ECC_BRAINPOOL */
  17707. #endif
  17708. #ifdef HAVE_CURVE448
  17709. case WOLFSSL_ECC_X448: return ECC_X448_OID;
  17710. #endif
  17711. #if defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)
  17712. #ifndef NO_ECC_SECP
  17713. case WOLFSSL_ECC_SECP384R1: return ECC_SECP384R1_OID;
  17714. #endif /* !NO_ECC_SECP */
  17715. #ifdef HAVE_ECC_BRAINPOOL
  17716. case WOLFSSL_ECC_BRAINPOOLP384R1: return ECC_BRAINPOOLP384R1_OID;
  17717. #endif /* HAVE_ECC_BRAINPOOL */
  17718. #endif
  17719. #if defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)
  17720. #ifdef HAVE_ECC_BRAINPOOL
  17721. case WOLFSSL_ECC_BRAINPOOLP512R1: return ECC_BRAINPOOLP512R1_OID;
  17722. #endif /* HAVE_ECC_BRAINPOOL */
  17723. #endif
  17724. #if defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)
  17725. #ifndef NO_ECC_SECP
  17726. case WOLFSSL_ECC_SECP521R1: return ECC_SECP521R1_OID;
  17727. #endif /* !NO_ECC_SECP */
  17728. #endif
  17729. }
  17730. return ret;
  17731. }
  17732. #endif /* HAVE_ECC */
  17733. /* Persistable DoServerKeyExchange arguments */
  17734. typedef struct DskeArgs {
  17735. byte* output; /* not allocated */
  17736. #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  17737. defined(HAVE_ED448)
  17738. byte* verifySig;
  17739. #endif
  17740. word32 idx;
  17741. word32 begin;
  17742. #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  17743. defined(HAVE_ED448)
  17744. word16 verifySigSz;
  17745. #endif
  17746. word16 sigSz;
  17747. byte sigAlgo;
  17748. byte hashAlgo;
  17749. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  17750. int bits;
  17751. #endif
  17752. } DskeArgs;
  17753. static void FreeDskeArgs(WOLFSSL* ssl, void* pArgs)
  17754. {
  17755. DskeArgs* args = (DskeArgs*)pArgs;
  17756. (void)ssl;
  17757. (void)args;
  17758. #if !defined(NO_DH) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  17759. defined(HAVE_ED448)
  17760. if (args->verifySig) {
  17761. XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  17762. args->verifySig = NULL;
  17763. }
  17764. #endif
  17765. }
  17766. #ifndef NO_DH
  17767. static int GetDhPublicKey(WOLFSSL* ssl, const byte* input, word32 size,
  17768. DskeArgs* args)
  17769. {
  17770. int ret = 0;
  17771. word16 length;
  17772. #ifdef HAVE_FFDHE
  17773. const DhParams* params = NULL;
  17774. int group = 0;
  17775. #endif
  17776. ssl->buffers.weOwnDH = 1;
  17777. ssl->buffers.serverDH_P.buffer = NULL;
  17778. ssl->buffers.serverDH_G.buffer = NULL;
  17779. ssl->buffers.serverDH_Pub.buffer = NULL;
  17780. /* p */
  17781. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  17782. ERROR_OUT(BUFFER_ERROR, exit_gdpk);
  17783. }
  17784. ato16(input + args->idx, &length);
  17785. args->idx += OPAQUE16_LEN;
  17786. if ((args->idx - args->begin) + length > size) {
  17787. ERROR_OUT(BUFFER_ERROR, exit_gdpk);
  17788. }
  17789. if (length < ssl->options.minDhKeySz) {
  17790. WOLFSSL_MSG("Server using a DH key that is too small");
  17791. SendAlert(ssl, alert_fatal, handshake_failure);
  17792. ERROR_OUT(DH_KEY_SIZE_E, exit_gdpk);
  17793. }
  17794. if (length > ssl->options.maxDhKeySz) {
  17795. WOLFSSL_MSG("Server using a DH key that is too big");
  17796. SendAlert(ssl, alert_fatal, handshake_failure);
  17797. ERROR_OUT(DH_KEY_SIZE_E, exit_gdpk);
  17798. }
  17799. ssl->buffers.serverDH_P.buffer =
  17800. (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  17801. if (ssl->buffers.serverDH_P.buffer) {
  17802. ssl->buffers.serverDH_P.length = length;
  17803. }
  17804. else {
  17805. ERROR_OUT(MEMORY_ERROR, exit_gdpk);
  17806. }
  17807. XMEMCPY(ssl->buffers.serverDH_P.buffer, input + args->idx,
  17808. length);
  17809. args->idx += length;
  17810. ssl->options.dhKeySz = length;
  17811. /* g */
  17812. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  17813. ERROR_OUT(BUFFER_ERROR, exit_gdpk);
  17814. }
  17815. ato16(input + args->idx, &length);
  17816. args->idx += OPAQUE16_LEN;
  17817. if ((args->idx - args->begin) + length > size) {
  17818. ERROR_OUT(BUFFER_ERROR, exit_gdpk);
  17819. }
  17820. ssl->buffers.serverDH_G.buffer =
  17821. (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  17822. if (ssl->buffers.serverDH_G.buffer) {
  17823. ssl->buffers.serverDH_G.length = length;
  17824. }
  17825. else {
  17826. ERROR_OUT(MEMORY_ERROR, exit_gdpk);
  17827. }
  17828. XMEMCPY(ssl->buffers.serverDH_G.buffer, input + args->idx,
  17829. length);
  17830. args->idx += length;
  17831. /* pub */
  17832. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  17833. ERROR_OUT(BUFFER_ERROR, exit_gdpk);
  17834. }
  17835. ato16(input + args->idx, &length);
  17836. args->idx += OPAQUE16_LEN;
  17837. if ((args->idx - args->begin) + length > size) {
  17838. ERROR_OUT(BUFFER_ERROR, exit_gdpk);
  17839. }
  17840. ssl->buffers.serverDH_Pub.buffer =
  17841. (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  17842. if (ssl->buffers.serverDH_Pub.buffer) {
  17843. ssl->buffers.serverDH_Pub.length = length;
  17844. }
  17845. else {
  17846. ERROR_OUT(MEMORY_ERROR, exit_gdpk);
  17847. }
  17848. XMEMCPY(ssl->buffers.serverDH_Pub.buffer, input + args->idx,
  17849. length);
  17850. args->idx += length;
  17851. #ifdef HAVE_FFDHE
  17852. switch (ssl->options.dhKeySz) {
  17853. #ifdef HAVE_FFDHE_2048
  17854. case 2048/8:
  17855. params = wc_Dh_ffdhe2048_Get();
  17856. group = WOLFSSL_FFDHE_2048;
  17857. break;
  17858. #endif
  17859. #ifdef HAVE_FFDHE_3072
  17860. case 3072/8:
  17861. params = wc_Dh_ffdhe3072_Get();
  17862. group = WOLFSSL_FFDHE_3072;
  17863. break;
  17864. #endif
  17865. #ifdef HAVE_FFDHE_4096
  17866. case 4096/8:
  17867. params = wc_Dh_ffdhe4096_Get();
  17868. group = WOLFSSL_FFDHE_4096;
  17869. break;
  17870. #endif
  17871. #ifdef HAVE_FFDHE_6144
  17872. case 6144/8:
  17873. params = wc_Dh_ffdhe6144_Get();
  17874. group = WOLFSSL_FFDHE_6144;
  17875. break;
  17876. #endif
  17877. #ifdef HAVE_FFDHE_8192
  17878. case 8192/8:
  17879. params = wc_Dh_ffdhe8192_Get();
  17880. group = WOLFSSL_FFDHE_8192;
  17881. break;
  17882. #endif
  17883. default:
  17884. break;
  17885. }
  17886. if (params == NULL || params->g_len != ssl->buffers.serverDH_G.length ||
  17887. (XMEMCMP(ssl->buffers.serverDH_G.buffer, params->g,
  17888. params->g_len) != 0) ||
  17889. (XMEMCMP(ssl->buffers.serverDH_P.buffer, params->p,
  17890. params->p_len) != 0)) {
  17891. WOLFSSL_MSG("Server not using FFDHE parameters");
  17892. #ifdef WOLFSSL_REQUIRE_FFDHE
  17893. SendAlert(ssl, alert_fatal, handshake_failure);
  17894. ERROR_OUT(DH_PARAMS_NOT_FFDHE_E, exit_gdpk);
  17895. #endif
  17896. }
  17897. else {
  17898. ssl->namedGroup = group;
  17899. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
  17900. !defined(HAVE_SELFTEST)
  17901. ssl->options.dhDoKeyTest = 0;
  17902. #endif
  17903. }
  17904. #endif /* HAVE_FFDHE */
  17905. exit_gdpk:
  17906. return ret;
  17907. }
  17908. #endif
  17909. /* handle processing of server_key_exchange (12) */
  17910. static int DoServerKeyExchange(WOLFSSL* ssl, const byte* input,
  17911. word32* inOutIdx, word32 size)
  17912. {
  17913. int ret = 0;
  17914. #ifdef WOLFSSL_ASYNC_CRYPT
  17915. DskeArgs* args = (DskeArgs*)ssl->async.args;
  17916. typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
  17917. (void)sizeof(args_test);
  17918. #else
  17919. DskeArgs args[1];
  17920. #endif
  17921. (void)input;
  17922. (void)size;
  17923. WOLFSSL_START(WC_FUNC_SERVER_KEY_EXCHANGE_DO);
  17924. WOLFSSL_ENTER("DoServerKeyExchange");
  17925. #ifdef WOLFSSL_ASYNC_CRYPT
  17926. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  17927. if (ret != WC_NOT_PENDING_E) {
  17928. /* Check for error */
  17929. if (ret < 0)
  17930. goto exit_dske;
  17931. }
  17932. else
  17933. #endif
  17934. {
  17935. /* Reset state */
  17936. ret = 0;
  17937. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  17938. XMEMSET(args, 0, sizeof(DskeArgs));
  17939. args->idx = *inOutIdx;
  17940. args->begin = *inOutIdx;
  17941. args->sigAlgo = ssl->specs.sig_algo;
  17942. args->hashAlgo = sha_mac;
  17943. #ifdef WOLFSSL_ASYNC_CRYPT
  17944. ssl->async.freeArgs = FreeDskeArgs;
  17945. #endif
  17946. }
  17947. switch(ssl->options.asyncState)
  17948. {
  17949. case TLS_ASYNC_BEGIN:
  17950. {
  17951. #ifdef WOLFSSL_CALLBACKS
  17952. if (ssl->hsInfoOn)
  17953. AddPacketName(ssl, "ServerKeyExchange");
  17954. if (ssl->toInfoOn)
  17955. AddLateName("ServerKeyExchange", &ssl->timeoutInfo);
  17956. #endif
  17957. switch(ssl->specs.kea)
  17958. {
  17959. #ifndef NO_PSK
  17960. case psk_kea:
  17961. {
  17962. int srvHintLen;
  17963. word16 length;
  17964. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  17965. ERROR_OUT(BUFFER_ERROR, exit_dske);
  17966. }
  17967. ato16(input + args->idx, &length);
  17968. args->idx += OPAQUE16_LEN;
  17969. if ((args->idx - args->begin) + length > size) {
  17970. ERROR_OUT(BUFFER_ERROR, exit_dske);
  17971. }
  17972. /* get PSK server hint from the wire */
  17973. srvHintLen = min(length, MAX_PSK_ID_LEN);
  17974. XMEMCPY(ssl->arrays->server_hint, input + args->idx,
  17975. srvHintLen);
  17976. ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */
  17977. args->idx += length;
  17978. break;
  17979. }
  17980. #endif /* !NO_PSK */
  17981. #ifndef NO_DH
  17982. case diffie_hellman_kea:
  17983. {
  17984. ret = GetDhPublicKey(ssl, input, size, args);
  17985. if (ret != 0)
  17986. goto exit_dske;
  17987. break;
  17988. }
  17989. #endif /* !NO_DH */
  17990. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  17991. defined(HAVE_CURVE448)
  17992. case ecc_diffie_hellman_kea:
  17993. {
  17994. byte b;
  17995. #ifdef HAVE_ECC
  17996. int curveId;
  17997. #endif
  17998. int curveOid;
  17999. word16 length;
  18000. if ((args->idx - args->begin) + ENUM_LEN + OPAQUE16_LEN +
  18001. OPAQUE8_LEN > size) {
  18002. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18003. }
  18004. b = input[args->idx++];
  18005. if (b != named_curve) {
  18006. ERROR_OUT(ECC_CURVETYPE_ERROR, exit_dske);
  18007. }
  18008. args->idx += 1; /* curve type, eat leading 0 */
  18009. b = input[args->idx++];
  18010. if ((curveOid = CheckCurveId(b)) < 0) {
  18011. ERROR_OUT(ECC_CURVE_ERROR, exit_dske);
  18012. }
  18013. ssl->ecdhCurveOID = curveOid;
  18014. #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
  18015. ssl->namedGroup = 0;
  18016. #endif
  18017. length = input[args->idx++];
  18018. if ((args->idx - args->begin) + length > size) {
  18019. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18020. }
  18021. #ifdef HAVE_CURVE25519
  18022. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  18023. if (ssl->peerX25519Key == NULL) {
  18024. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
  18025. (void**)&ssl->peerX25519Key);
  18026. if (ret != 0) {
  18027. goto exit_dske;
  18028. }
  18029. } else if (ssl->peerX25519KeyPresent) {
  18030. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE25519,
  18031. ssl->peerX25519Key);
  18032. ssl->peerX25519KeyPresent = 0;
  18033. if (ret != 0) {
  18034. goto exit_dske;
  18035. }
  18036. }
  18037. if ((ret = wc_curve25519_check_public(
  18038. input + args->idx, length,
  18039. EC25519_LITTLE_ENDIAN)) != 0) {
  18040. #ifdef WOLFSSL_EXTRA_ALERTS
  18041. if (ret == BUFFER_E)
  18042. SendAlert(ssl, alert_fatal, decode_error);
  18043. else if (ret == ECC_OUT_OF_RANGE_E)
  18044. SendAlert(ssl, alert_fatal, bad_record_mac);
  18045. else {
  18046. SendAlert(ssl, alert_fatal, illegal_parameter);
  18047. }
  18048. #endif
  18049. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  18050. }
  18051. if (wc_curve25519_import_public_ex(input + args->idx,
  18052. length, ssl->peerX25519Key,
  18053. EC25519_LITTLE_ENDIAN) != 0) {
  18054. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  18055. }
  18056. args->idx += length;
  18057. ssl->peerX25519KeyPresent = 1;
  18058. break;
  18059. }
  18060. #endif
  18061. #ifdef HAVE_CURVE448
  18062. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  18063. if (ssl->peerX448Key == NULL) {
  18064. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
  18065. (void**)&ssl->peerX448Key);
  18066. if (ret != 0) {
  18067. goto exit_dske;
  18068. }
  18069. } else if (ssl->peerX448KeyPresent) {
  18070. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE448,
  18071. ssl->peerX448Key);
  18072. ssl->peerX448KeyPresent = 0;
  18073. if (ret != 0) {
  18074. goto exit_dske;
  18075. }
  18076. }
  18077. if ((ret = wc_curve448_check_public(
  18078. input + args->idx, length,
  18079. EC448_LITTLE_ENDIAN)) != 0) {
  18080. #ifdef WOLFSSL_EXTRA_ALERTS
  18081. if (ret == BUFFER_E)
  18082. SendAlert(ssl, alert_fatal, decode_error);
  18083. else if (ret == ECC_OUT_OF_RANGE_E)
  18084. SendAlert(ssl, alert_fatal, bad_record_mac);
  18085. else {
  18086. SendAlert(ssl, alert_fatal, illegal_parameter);
  18087. }
  18088. #endif
  18089. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  18090. }
  18091. if (wc_curve448_import_public_ex(input + args->idx,
  18092. length, ssl->peerX448Key,
  18093. EC448_LITTLE_ENDIAN) != 0) {
  18094. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  18095. }
  18096. args->idx += length;
  18097. ssl->peerX448KeyPresent = 1;
  18098. break;
  18099. }
  18100. #endif
  18101. #ifdef HAVE_ECC
  18102. if (ssl->peerEccKey == NULL) {
  18103. ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
  18104. (void**)&ssl->peerEccKey);
  18105. if (ret != 0) {
  18106. goto exit_dske;
  18107. }
  18108. } else if (ssl->peerEccKeyPresent) {
  18109. ret = ReuseKey(ssl, DYNAMIC_TYPE_ECC, ssl->peerEccKey);
  18110. ssl->peerEccKeyPresent = 0;
  18111. if (ret != 0) {
  18112. goto exit_dske;
  18113. }
  18114. }
  18115. curveId = wc_ecc_get_oid(curveOid, NULL, NULL);
  18116. if (wc_ecc_import_x963_ex(input + args->idx, length,
  18117. ssl->peerEccKey, curveId) != 0) {
  18118. #ifdef WOLFSSL_EXTRA_ALERTS
  18119. SendAlert(ssl, alert_fatal, illegal_parameter);
  18120. #endif
  18121. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  18122. }
  18123. args->idx += length;
  18124. ssl->peerEccKeyPresent = 1;
  18125. #endif
  18126. break;
  18127. }
  18128. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  18129. #if !defined(NO_DH) && !defined(NO_PSK)
  18130. case dhe_psk_kea:
  18131. {
  18132. int srvHintLen;
  18133. word16 length;
  18134. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  18135. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18136. }
  18137. ato16(input + args->idx, &length);
  18138. args->idx += OPAQUE16_LEN;
  18139. if ((args->idx - args->begin) + length > size) {
  18140. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18141. }
  18142. /* get PSK server hint from the wire */
  18143. srvHintLen = min(length, MAX_PSK_ID_LEN);
  18144. XMEMCPY(ssl->arrays->server_hint, input + args->idx,
  18145. srvHintLen);
  18146. ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */
  18147. args->idx += length;
  18148. ret = GetDhPublicKey(ssl, input, size, args);
  18149. if (ret != 0)
  18150. goto exit_dske;
  18151. break;
  18152. }
  18153. #endif /* !NO_DH && !NO_PSK */
  18154. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  18155. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  18156. case ecdhe_psk_kea:
  18157. {
  18158. byte b;
  18159. int curveOid, curveId;
  18160. int srvHintLen;
  18161. word16 length;
  18162. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  18163. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18164. }
  18165. ato16(input + args->idx, &length);
  18166. args->idx += OPAQUE16_LEN;
  18167. if ((args->idx - args->begin) + length > size) {
  18168. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18169. }
  18170. /* get PSK server hint from the wire */
  18171. srvHintLen = min(length, MAX_PSK_ID_LEN);
  18172. XMEMCPY(ssl->arrays->server_hint, input + args->idx,
  18173. srvHintLen);
  18174. ssl->arrays->server_hint[srvHintLen] = '\0'; /* null term */
  18175. args->idx += length;
  18176. if ((args->idx - args->begin) + ENUM_LEN + OPAQUE16_LEN +
  18177. OPAQUE8_LEN > size) {
  18178. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18179. }
  18180. /* Check curve name and ID */
  18181. b = input[args->idx++];
  18182. if (b != named_curve) {
  18183. ERROR_OUT(ECC_CURVETYPE_ERROR, exit_dske);
  18184. }
  18185. args->idx += 1; /* curve type, eat leading 0 */
  18186. b = input[args->idx++];
  18187. if ((curveOid = CheckCurveId(b)) < 0) {
  18188. ERROR_OUT(ECC_CURVE_ERROR, exit_dske);
  18189. }
  18190. length = input[args->idx++];
  18191. if ((args->idx - args->begin) + length > size) {
  18192. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18193. }
  18194. #ifdef HAVE_CURVE25519
  18195. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  18196. if (ssl->peerX25519Key == NULL) {
  18197. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
  18198. (void**)&ssl->peerX25519Key);
  18199. if (ret != 0) {
  18200. goto exit_dske;
  18201. }
  18202. } else if (ssl->peerEccKeyPresent) {
  18203. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE25519,
  18204. ssl->peerX25519Key);
  18205. ssl->peerX25519KeyPresent = 0;
  18206. if (ret != 0) {
  18207. goto exit_dske;
  18208. }
  18209. }
  18210. if ((ret = wc_curve25519_check_public(
  18211. input + args->idx, length,
  18212. EC25519_LITTLE_ENDIAN)) != 0) {
  18213. #ifdef WOLFSSL_EXTRA_ALERTS
  18214. if (ret == BUFFER_E)
  18215. SendAlert(ssl, alert_fatal, decode_error);
  18216. else if (ret == ECC_OUT_OF_RANGE_E)
  18217. SendAlert(ssl, alert_fatal, bad_record_mac);
  18218. else {
  18219. SendAlert(ssl, alert_fatal, illegal_parameter);
  18220. }
  18221. #endif
  18222. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  18223. }
  18224. if (wc_curve25519_import_public_ex(input + args->idx,
  18225. length, ssl->peerX25519Key,
  18226. EC25519_LITTLE_ENDIAN) != 0) {
  18227. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  18228. }
  18229. args->idx += length;
  18230. ssl->peerX25519KeyPresent = 1;
  18231. break;
  18232. }
  18233. #endif
  18234. #ifdef HAVE_CURVE448
  18235. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  18236. if (ssl->peerX448Key == NULL) {
  18237. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
  18238. (void**)&ssl->peerX448Key);
  18239. if (ret != 0) {
  18240. goto exit_dske;
  18241. }
  18242. } else if (ssl->peerEccKeyPresent) {
  18243. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE448,
  18244. ssl->peerX448Key);
  18245. ssl->peerX448KeyPresent = 0;
  18246. if (ret != 0) {
  18247. goto exit_dske;
  18248. }
  18249. }
  18250. if ((ret = wc_curve448_check_public(
  18251. input + args->idx, length,
  18252. EC448_LITTLE_ENDIAN)) != 0) {
  18253. #ifdef WOLFSSL_EXTRA_ALERTS
  18254. if (ret == BUFFER_E)
  18255. SendAlert(ssl, alert_fatal, decode_error);
  18256. else if (ret == ECC_OUT_OF_RANGE_E)
  18257. SendAlert(ssl, alert_fatal, bad_record_mac);
  18258. else {
  18259. SendAlert(ssl, alert_fatal, illegal_parameter);
  18260. }
  18261. #endif
  18262. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  18263. }
  18264. if (wc_curve448_import_public_ex(input + args->idx,
  18265. length, ssl->peerX448Key,
  18266. EC448_LITTLE_ENDIAN) != 0) {
  18267. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  18268. }
  18269. args->idx += length;
  18270. ssl->peerX448KeyPresent = 1;
  18271. break;
  18272. }
  18273. #endif
  18274. if (ssl->peerEccKey == NULL) {
  18275. ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
  18276. (void**)&ssl->peerEccKey);
  18277. if (ret != 0) {
  18278. goto exit_dske;
  18279. }
  18280. } else if (ssl->peerEccKeyPresent) {
  18281. ret = ReuseKey(ssl, DYNAMIC_TYPE_ECC, ssl->peerEccKey);
  18282. ssl->peerEccKeyPresent = 0;
  18283. if (ret != 0) {
  18284. goto exit_dske;
  18285. }
  18286. }
  18287. curveId = wc_ecc_get_oid(curveOid, NULL, NULL);
  18288. if (wc_ecc_import_x963_ex(input + args->idx, length,
  18289. ssl->peerEccKey, curveId) != 0) {
  18290. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dske);
  18291. }
  18292. args->idx += length;
  18293. ssl->peerEccKeyPresent = 1;
  18294. break;
  18295. }
  18296. #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
  18297. default:
  18298. ret = BAD_KEA_TYPE_E;
  18299. } /* switch(ssl->specs.kea) */
  18300. /* Check for error */
  18301. if (ret != 0) {
  18302. goto exit_dske;
  18303. }
  18304. /* Advance state and proceed */
  18305. ssl->options.asyncState = TLS_ASYNC_BUILD;
  18306. } /* case TLS_ASYNC_BEGIN */
  18307. FALL_THROUGH;
  18308. case TLS_ASYNC_BUILD:
  18309. {
  18310. switch(ssl->specs.kea)
  18311. {
  18312. case psk_kea:
  18313. case dhe_psk_kea:
  18314. case ecdhe_psk_kea:
  18315. {
  18316. /* Nothing to do in this sub-state */
  18317. break;
  18318. }
  18319. case diffie_hellman_kea:
  18320. case ecc_diffie_hellman_kea:
  18321. {
  18322. #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(HAVE_ED25519) \
  18323. && !defined(HAVE_ED448)
  18324. ERROR_OUT(NOT_COMPILED_IN, exit_dske);
  18325. #else
  18326. enum wc_HashType hashType;
  18327. word16 verifySz;
  18328. if (ssl->options.usingAnon_cipher) {
  18329. break;
  18330. }
  18331. verifySz = (word16)(args->idx - args->begin);
  18332. if (verifySz > MAX_DH_SZ) {
  18333. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18334. }
  18335. if (IsAtLeastTLSv1_2(ssl)) {
  18336. if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN >
  18337. size) {
  18338. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18339. }
  18340. DecodeSigAlg(&input[args->idx], &args->hashAlgo,
  18341. &args->sigAlgo);
  18342. args->idx += 2;
  18343. hashType = HashAlgoToType(args->hashAlgo);
  18344. if (hashType == WC_HASH_TYPE_NONE) {
  18345. ERROR_OUT(ALGO_ID_E, exit_dske);
  18346. }
  18347. } else {
  18348. /* only using sha and md5 for rsa */
  18349. #ifndef NO_OLD_TLS
  18350. hashType = WC_HASH_TYPE_SHA;
  18351. if (args->sigAlgo == rsa_sa_algo) {
  18352. hashType = WC_HASH_TYPE_MD5_SHA;
  18353. }
  18354. #else
  18355. ERROR_OUT(ALGO_ID_E, exit_dske);
  18356. #endif
  18357. }
  18358. /* signature */
  18359. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  18360. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18361. }
  18362. ato16(input + args->idx, &args->verifySigSz);
  18363. args->idx += OPAQUE16_LEN;
  18364. if ((args->idx - args->begin) + args->verifySigSz > size) {
  18365. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18366. }
  18367. /* buffer for signature */
  18368. ssl->buffers.sig.buffer = (byte*)XMALLOC(SEED_LEN + verifySz,
  18369. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  18370. if (ssl->buffers.sig.buffer == NULL) {
  18371. ERROR_OUT(MEMORY_E, exit_dske);
  18372. }
  18373. ssl->buffers.sig.length = SEED_LEN + verifySz;
  18374. /* build message to hash */
  18375. XMEMCPY(ssl->buffers.sig.buffer,
  18376. ssl->arrays->clientRandom, RAN_LEN);
  18377. XMEMCPY(&ssl->buffers.sig.buffer[RAN_LEN],
  18378. ssl->arrays->serverRandom, RAN_LEN);
  18379. XMEMCPY(&ssl->buffers.sig.buffer[RAN_LEN * 2],
  18380. input + args->begin, verifySz); /* message */
  18381. if (args->sigAlgo != ed25519_sa_algo) {
  18382. int digest_sz = wc_HashGetDigestSize(hashType);
  18383. if (digest_sz <= 0) {
  18384. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18385. }
  18386. ssl->buffers.digest.length = (unsigned int)digest_sz;
  18387. /* buffer for hash */
  18388. ssl->buffers.digest.buffer = (byte*)XMALLOC(
  18389. ssl->buffers.digest.length, ssl->heap,
  18390. DYNAMIC_TYPE_DIGEST);
  18391. if (ssl->buffers.digest.buffer == NULL) {
  18392. ERROR_OUT(MEMORY_E, exit_dske);
  18393. }
  18394. /* Perform hash */
  18395. ret = wc_Hash(hashType, ssl->buffers.sig.buffer,
  18396. ssl->buffers.sig.length,
  18397. ssl->buffers.digest.buffer,
  18398. ssl->buffers.digest.length);
  18399. if (ret != 0) {
  18400. goto exit_dske;
  18401. }
  18402. }
  18403. switch (args->sigAlgo)
  18404. {
  18405. #ifndef NO_RSA
  18406. #ifdef WC_RSA_PSS
  18407. case rsa_pss_sa_algo:
  18408. #endif
  18409. case rsa_sa_algo:
  18410. {
  18411. if (ssl->peerRsaKey == NULL ||
  18412. !ssl->peerRsaKeyPresent) {
  18413. ERROR_OUT(NO_PEER_KEY, exit_dske);
  18414. }
  18415. break;
  18416. }
  18417. #endif /* !NO_RSA */
  18418. #ifdef HAVE_ECC
  18419. case ecc_dsa_sa_algo:
  18420. {
  18421. if (!ssl->peerEccDsaKeyPresent) {
  18422. ERROR_OUT(NO_PEER_KEY, exit_dske);
  18423. }
  18424. break;
  18425. }
  18426. #endif /* HAVE_ECC */
  18427. #if defined(HAVE_ED25519)
  18428. case ed25519_sa_algo:
  18429. {
  18430. if (!ssl->peerEd25519KeyPresent) {
  18431. ERROR_OUT(NO_PEER_KEY, exit_dske);
  18432. }
  18433. break;
  18434. }
  18435. #endif /* HAVE_ED25519 */
  18436. #if defined(HAVE_ED448)
  18437. case ed448_sa_algo:
  18438. {
  18439. if (!ssl->peerEd448KeyPresent) {
  18440. ERROR_OUT(NO_PEER_KEY, exit_dske);
  18441. }
  18442. break;
  18443. }
  18444. #endif /* HAVE_ED448 */
  18445. default:
  18446. ret = ALGO_ID_E;
  18447. } /* switch (args->sigAlgo) */
  18448. #endif /* NO_DH && !HAVE_ECC && !HAVE_ED25519 && !HAVE_ED448 */
  18449. break;
  18450. }
  18451. default:
  18452. ret = BAD_KEA_TYPE_E;
  18453. } /* switch(ssl->specs.kea) */
  18454. /* Check for error */
  18455. if (ret != 0) {
  18456. goto exit_dske;
  18457. }
  18458. /* Advance state and proceed */
  18459. ssl->options.asyncState = TLS_ASYNC_DO;
  18460. } /* case TLS_ASYNC_BUILD */
  18461. FALL_THROUGH;
  18462. case TLS_ASYNC_DO:
  18463. {
  18464. switch(ssl->specs.kea)
  18465. {
  18466. case psk_kea:
  18467. case dhe_psk_kea:
  18468. case ecdhe_psk_kea:
  18469. {
  18470. /* Nothing to do in this sub-state */
  18471. break;
  18472. }
  18473. case diffie_hellman_kea:
  18474. case ecc_diffie_hellman_kea:
  18475. {
  18476. #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(HAVE_ED25519) \
  18477. && !defined(HAVE_ED448)
  18478. ERROR_OUT(NOT_COMPILED_IN, exit_dske);
  18479. #else
  18480. if (ssl->options.usingAnon_cipher) {
  18481. break;
  18482. }
  18483. if (args->verifySig == NULL) {
  18484. args->verifySig = (byte*)XMALLOC(args->verifySigSz,
  18485. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  18486. if (args->verifySig == NULL) {
  18487. ERROR_OUT(MEMORY_E, exit_dske);
  18488. }
  18489. XMEMCPY(args->verifySig, input + args->idx,
  18490. args->verifySigSz);
  18491. }
  18492. switch (args->sigAlgo)
  18493. {
  18494. #ifndef NO_RSA
  18495. #ifdef WC_RSA_PSS
  18496. case rsa_pss_sa_algo:
  18497. #endif
  18498. case rsa_sa_algo:
  18499. {
  18500. ret = RsaVerify(ssl,
  18501. args->verifySig, args->verifySigSz,
  18502. &args->output,
  18503. args->sigAlgo, args->hashAlgo,
  18504. ssl->peerRsaKey,
  18505. #ifdef HAVE_PK_CALLBACKS
  18506. &ssl->buffers.peerRsaKey
  18507. #else
  18508. NULL
  18509. #endif
  18510. );
  18511. if (ret >= 0) {
  18512. args->sigSz = (word16)ret;
  18513. #ifdef WC_RSA_PSS
  18514. args->bits = mp_count_bits(&ssl->peerRsaKey->n);
  18515. #endif
  18516. ret = 0;
  18517. }
  18518. #ifdef WOLFSSL_ASYNC_CRYPT
  18519. if (ret != WC_PENDING_E)
  18520. #endif
  18521. {
  18522. /* peerRsaKey */
  18523. FreeKey(ssl, DYNAMIC_TYPE_RSA,
  18524. (void**)&ssl->peerRsaKey);
  18525. ssl->peerRsaKeyPresent = 0;
  18526. }
  18527. break;
  18528. }
  18529. #endif /* !NO_RSA */
  18530. #ifdef HAVE_ECC
  18531. case ecc_dsa_sa_algo:
  18532. {
  18533. ret = EccVerify(ssl,
  18534. args->verifySig, args->verifySigSz,
  18535. ssl->buffers.digest.buffer,
  18536. ssl->buffers.digest.length,
  18537. ssl->peerEccDsaKey,
  18538. #ifdef HAVE_PK_CALLBACKS
  18539. &ssl->buffers.peerEccDsaKey
  18540. #else
  18541. NULL
  18542. #endif
  18543. );
  18544. #ifdef WOLFSSL_ASYNC_CRYPT
  18545. if (ret != WC_PENDING_E)
  18546. #endif
  18547. {
  18548. /* peerEccDsaKey */
  18549. FreeKey(ssl, DYNAMIC_TYPE_ECC,
  18550. (void**)&ssl->peerEccDsaKey);
  18551. ssl->peerEccDsaKeyPresent = 0;
  18552. }
  18553. break;
  18554. }
  18555. #endif /* HAVE_ECC */
  18556. #if defined(HAVE_ED25519)
  18557. case ed25519_sa_algo:
  18558. {
  18559. ret = Ed25519Verify(ssl,
  18560. args->verifySig, args->verifySigSz,
  18561. ssl->buffers.sig.buffer,
  18562. ssl->buffers.sig.length,
  18563. ssl->peerEd25519Key,
  18564. #ifdef HAVE_PK_CALLBACKS
  18565. &ssl->buffers.peerEd25519Key
  18566. #else
  18567. NULL
  18568. #endif
  18569. );
  18570. #ifdef WOLFSSL_ASYNC_CRYPT
  18571. if (ret != WC_PENDING_E)
  18572. #endif
  18573. {
  18574. /* peerEccDsaKey */
  18575. FreeKey(ssl, DYNAMIC_TYPE_ED25519,
  18576. (void**)&ssl->peerEd25519Key);
  18577. ssl->peerEd25519KeyPresent = 0;
  18578. }
  18579. break;
  18580. }
  18581. #endif /* HAVE_ED25519 */
  18582. #if defined(HAVE_ED448)
  18583. case ed448_sa_algo:
  18584. {
  18585. ret = Ed448Verify(ssl,
  18586. args->verifySig, args->verifySigSz,
  18587. ssl->buffers.sig.buffer,
  18588. ssl->buffers.sig.length,
  18589. ssl->peerEd448Key,
  18590. #ifdef HAVE_PK_CALLBACKS
  18591. &ssl->buffers.peerEd448Key
  18592. #else
  18593. NULL
  18594. #endif
  18595. );
  18596. #ifdef WOLFSSL_ASYNC_CRYPT
  18597. if (ret != WC_PENDING_E)
  18598. #endif
  18599. {
  18600. /* peerEccDsaKey */
  18601. FreeKey(ssl, DYNAMIC_TYPE_ED448,
  18602. (void**)&ssl->peerEd448Key);
  18603. ssl->peerEd448KeyPresent = 0;
  18604. }
  18605. break;
  18606. }
  18607. #endif /* HAVE_ED448 */
  18608. default:
  18609. ret = ALGO_ID_E;
  18610. } /* switch (sigAlgo) */
  18611. #endif /* NO_DH && !HAVE_ECC && !HAVE_ED25519 && !HAVE_ED448 */
  18612. break;
  18613. }
  18614. default:
  18615. ret = BAD_KEA_TYPE_E;
  18616. } /* switch(ssl->specs.kea) */
  18617. /* Check for error */
  18618. if (ret != 0) {
  18619. goto exit_dske;
  18620. }
  18621. /* Advance state and proceed */
  18622. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  18623. } /* case TLS_ASYNC_DO */
  18624. FALL_THROUGH;
  18625. case TLS_ASYNC_VERIFY:
  18626. {
  18627. switch(ssl->specs.kea)
  18628. {
  18629. case psk_kea:
  18630. case dhe_psk_kea:
  18631. case ecdhe_psk_kea:
  18632. {
  18633. /* Nothing to do in this sub-state */
  18634. break;
  18635. }
  18636. case diffie_hellman_kea:
  18637. case ecc_diffie_hellman_kea:
  18638. {
  18639. #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(HAVE_ED25519) \
  18640. && !defined(HAVE_ED448)
  18641. ERROR_OUT(NOT_COMPILED_IN, exit_dske);
  18642. #else
  18643. if (ssl->options.usingAnon_cipher) {
  18644. break;
  18645. }
  18646. /* increment index after verify is done */
  18647. args->idx += args->verifySigSz;
  18648. switch(args->sigAlgo)
  18649. {
  18650. #ifndef NO_RSA
  18651. #ifdef WC_RSA_PSS
  18652. case rsa_pss_sa_algo:
  18653. #ifdef HAVE_SELFTEST
  18654. ret = wc_RsaPSS_CheckPadding(
  18655. ssl->buffers.digest.buffer,
  18656. ssl->buffers.digest.length,
  18657. args->output, args->sigSz,
  18658. HashAlgoToType(args->hashAlgo));
  18659. #else
  18660. ret = wc_RsaPSS_CheckPadding_ex(
  18661. ssl->buffers.digest.buffer,
  18662. ssl->buffers.digest.length,
  18663. args->output, args->sigSz,
  18664. HashAlgoToType(args->hashAlgo),
  18665. -1, args->bits);
  18666. #endif
  18667. if (ret != 0)
  18668. return ret;
  18669. break;
  18670. #endif
  18671. case rsa_sa_algo:
  18672. {
  18673. if (IsAtLeastTLSv1_2(ssl)) {
  18674. #ifdef WOLFSSL_SMALL_STACK
  18675. byte* encodedSig;
  18676. #else
  18677. byte encodedSig[MAX_ENCODED_SIG_SZ];
  18678. #endif
  18679. word32 encSigSz;
  18680. #ifdef WOLFSSL_SMALL_STACK
  18681. encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  18682. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  18683. if (encodedSig == NULL) {
  18684. ERROR_OUT(MEMORY_E, exit_dske);
  18685. }
  18686. #endif
  18687. encSigSz = wc_EncodeSignature(encodedSig,
  18688. ssl->buffers.digest.buffer,
  18689. ssl->buffers.digest.length,
  18690. TypeHash(args->hashAlgo));
  18691. if (encSigSz != args->sigSz || !args->output ||
  18692. XMEMCMP(args->output, encodedSig,
  18693. min(encSigSz, MAX_ENCODED_SIG_SZ)) != 0) {
  18694. ret = VERIFY_SIGN_ERROR;
  18695. }
  18696. #ifdef WOLFSSL_SMALL_STACK
  18697. XFREE(encodedSig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  18698. #endif
  18699. if (ret != 0) {
  18700. goto exit_dske;
  18701. }
  18702. }
  18703. else if (args->sigSz != FINISHED_SZ ||
  18704. !args->output ||
  18705. XMEMCMP(args->output,
  18706. ssl->buffers.digest.buffer,
  18707. FINISHED_SZ) != 0) {
  18708. ERROR_OUT(VERIFY_SIGN_ERROR, exit_dske);
  18709. }
  18710. break;
  18711. }
  18712. #endif /* !NO_RSA */
  18713. #ifdef HAVE_ECC
  18714. case ecc_dsa_sa_algo:
  18715. /* Nothing to do in this algo */
  18716. break;
  18717. #endif /* HAVE_ECC */
  18718. #if defined(HAVE_ED25519)
  18719. case ed25519_sa_algo:
  18720. /* Nothing to do in this algo */
  18721. break;
  18722. #endif /* HAVE_ED25519 */
  18723. #if defined(HAVE_ED448)
  18724. case ed448_sa_algo:
  18725. /* Nothing to do in this algo */
  18726. break;
  18727. #endif /* HAVE_ED448 */
  18728. default:
  18729. ret = ALGO_ID_E;
  18730. } /* switch (sigAlgo) */
  18731. #endif /* NO_DH && !HAVE_ECC && !HAVE_ED25519 && !HAVE_ED448 */
  18732. break;
  18733. }
  18734. default:
  18735. ret = BAD_KEA_TYPE_E;
  18736. } /* switch(ssl->specs.kea) */
  18737. /* Check for error */
  18738. if (ret != 0) {
  18739. goto exit_dske;
  18740. }
  18741. /* Advance state and proceed */
  18742. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  18743. } /* case TLS_ASYNC_VERIFY */
  18744. FALL_THROUGH;
  18745. case TLS_ASYNC_FINALIZE:
  18746. {
  18747. if (IsEncryptionOn(ssl, 0)) {
  18748. args->idx += ssl->keys.padSz;
  18749. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  18750. if (ssl->options.startedETMRead)
  18751. args->idx += MacSize(ssl);
  18752. #endif
  18753. }
  18754. /* QSH extensions */
  18755. #ifdef HAVE_QSH
  18756. if (ssl->peerQSHKeyPresent) {
  18757. word16 name;
  18758. int qshSz;
  18759. /* extension name */
  18760. ato16(input + args->idx, &name);
  18761. args->idx += OPAQUE16_LEN;
  18762. if (name == TLSX_QUANTUM_SAFE_HYBRID) {
  18763. /* if qshSz is larger than 0 it is the length of
  18764. buffer used */
  18765. if ((qshSz = TLSX_QSHCipher_Parse(ssl, input + args->idx,
  18766. size, 0)) < 0) {
  18767. ERROR_OUT(qshSz, exit_dske);
  18768. }
  18769. args->idx += qshSz;
  18770. }
  18771. else {
  18772. /* unknown extension sent server ignored handshake */
  18773. ERROR_OUT(BUFFER_ERROR, exit_dske);
  18774. }
  18775. }
  18776. #endif
  18777. /* Advance state and proceed */
  18778. ssl->options.asyncState = TLS_ASYNC_END;
  18779. } /* case TLS_ASYNC_FINALIZE */
  18780. FALL_THROUGH;
  18781. case TLS_ASYNC_END:
  18782. {
  18783. /* return index */
  18784. *inOutIdx = args->idx;
  18785. ssl->options.serverState = SERVER_KEYEXCHANGE_COMPLETE;
  18786. break;
  18787. }
  18788. default:
  18789. ret = INPUT_CASE_ERROR;
  18790. } /* switch(ssl->options.asyncState) */
  18791. exit_dske:
  18792. WOLFSSL_LEAVE("DoServerKeyExchange", ret);
  18793. WOLFSSL_END(WC_FUNC_SERVER_KEY_EXCHANGE_DO);
  18794. #ifdef WOLFSSL_ASYNC_CRYPT
  18795. /* Handle async operation */
  18796. if (ret == WC_PENDING_E) {
  18797. /* Mark message as not received so it can process again */
  18798. ssl->msgsReceived.got_server_key_exchange = 0;
  18799. return ret;
  18800. }
  18801. #endif /* WOLFSSL_ASYNC_CRYPT */
  18802. /* Final cleanup */
  18803. FreeDskeArgs(ssl, args);
  18804. FreeKeyExchange(ssl);
  18805. return ret;
  18806. }
  18807. #ifdef HAVE_QSH
  18808. #ifdef HAVE_NTRU
  18809. /* Encrypt a byte array using ntru
  18810. key a struct containing the public key to use
  18811. bufIn array to be encrypted
  18812. inSz size of bufIn array
  18813. bufOut cipher text out
  18814. outSz will be set to the new size of cipher text
  18815. */
  18816. static int NtruSecretEncrypt(QSHKey* key, byte* bufIn, word32 inSz,
  18817. byte* bufOut, word16* outSz)
  18818. {
  18819. int ret;
  18820. DRBG_HANDLE drbg;
  18821. /* sanity checks on input arguments */
  18822. if (key == NULL || bufIn == NULL || bufOut == NULL || outSz == NULL)
  18823. return BAD_FUNC_ARG;
  18824. if (key->pub.buffer == NULL)
  18825. return BAD_FUNC_ARG;
  18826. switch (key->name) {
  18827. case WOLFSSL_NTRU_EESS439:
  18828. case WOLFSSL_NTRU_EESS593:
  18829. case WOLFSSL_NTRU_EESS743:
  18830. break;
  18831. default:
  18832. WOLFSSL_MSG("Unknown QSH encryption key!");
  18833. return -1;
  18834. }
  18835. /* set up ntru drbg */
  18836. ret = ntru_crypto_drbg_external_instantiate(GetEntropy, &drbg);
  18837. if (ret != DRBG_OK)
  18838. return NTRU_DRBG_ERROR;
  18839. /* encrypt the byte array */
  18840. ret = ntru_crypto_ntru_encrypt(drbg, key->pub.length, key->pub.buffer,
  18841. inSz, bufIn, outSz, bufOut);
  18842. ntru_crypto_drbg_uninstantiate(drbg);
  18843. if (ret != NTRU_OK)
  18844. return NTRU_ENCRYPT_ERROR;
  18845. return ret;
  18846. }
  18847. /* Decrypt a byte array using ntru
  18848. key a struct containing the private key to use
  18849. bufIn array to be decrypted
  18850. inSz size of bufIn array
  18851. bufOut plain text out
  18852. outSz will be set to the new size of plain text
  18853. */
  18854. static int NtruSecretDecrypt(QSHKey* key, byte* bufIn, word32 inSz,
  18855. byte* bufOut, word16* outSz)
  18856. {
  18857. int ret;
  18858. DRBG_HANDLE drbg;
  18859. /* sanity checks on input arguments */
  18860. if (key == NULL || bufIn == NULL || bufOut == NULL || outSz == NULL)
  18861. return BAD_FUNC_ARG;
  18862. if (key->pri.buffer == NULL)
  18863. return BAD_FUNC_ARG;
  18864. switch (key->name) {
  18865. case WOLFSSL_NTRU_EESS439:
  18866. case WOLFSSL_NTRU_EESS593:
  18867. case WOLFSSL_NTRU_EESS743:
  18868. break;
  18869. default:
  18870. WOLFSSL_MSG("Unknown QSH decryption key!");
  18871. return -1;
  18872. }
  18873. /* set up drbg */
  18874. ret = ntru_crypto_drbg_external_instantiate(GetEntropy, &drbg);
  18875. if (ret != DRBG_OK)
  18876. return NTRU_DRBG_ERROR;
  18877. /* decrypt cipher text */
  18878. ret = ntru_crypto_ntru_decrypt(key->pri.length, key->pri.buffer,
  18879. inSz, bufIn, outSz, bufOut);
  18880. ntru_crypto_drbg_uninstantiate(drbg);
  18881. if (ret != NTRU_OK)
  18882. return NTRU_ENCRYPT_ERROR;
  18883. return ret;
  18884. }
  18885. #endif /* HAVE_NTRU */
  18886. int QSH_Init(WOLFSSL* ssl)
  18887. {
  18888. /* check so not initializing twice when running DTLS */
  18889. if (ssl->QSH_secret != NULL)
  18890. return 0;
  18891. /* malloc memory for holding generated secret information */
  18892. if ((ssl->QSH_secret = (QSHSecret*)XMALLOC(sizeof(QSHSecret), ssl->heap,
  18893. DYNAMIC_TYPE_QSH)) == NULL)
  18894. return MEMORY_E;
  18895. ssl->QSH_secret->CliSi = (buffer*)XMALLOC(sizeof(buffer), ssl->heap,
  18896. DYNAMIC_TYPE_SECRET);
  18897. if (ssl->QSH_secret->CliSi == NULL)
  18898. return MEMORY_E;
  18899. ssl->QSH_secret->SerSi = (buffer*)XMALLOC(sizeof(buffer), ssl->heap,
  18900. DYNAMIC_TYPE_SECRET);
  18901. if (ssl->QSH_secret->SerSi == NULL)
  18902. return MEMORY_E;
  18903. /* initialize variables */
  18904. ssl->QSH_secret->list = NULL;
  18905. ssl->QSH_secret->CliSi->length = 0;
  18906. ssl->QSH_secret->CliSi->buffer = NULL;
  18907. ssl->QSH_secret->SerSi->length = 0;
  18908. ssl->QSH_secret->SerSi->buffer = NULL;
  18909. return 0;
  18910. }
  18911. static int QSH_Encrypt(QSHKey* key, byte* in, word32 szIn,
  18912. byte* out, word32* szOut)
  18913. {
  18914. int ret = 0;
  18915. word16 size = *szOut;
  18916. (void)in;
  18917. (void)szIn;
  18918. (void)out;
  18919. (void)szOut;
  18920. WOLFSSL_MSG("Encrypting QSH key material");
  18921. switch (key->name) {
  18922. #ifdef HAVE_NTRU
  18923. case WOLFSSL_NTRU_EESS439:
  18924. case WOLFSSL_NTRU_EESS593:
  18925. case WOLFSSL_NTRU_EESS743:
  18926. ret = NtruSecretEncrypt(key, in, szIn, out, &size);
  18927. break;
  18928. #endif
  18929. default:
  18930. WOLFSSL_MSG("Unknown QSH encryption key!");
  18931. return -1;
  18932. }
  18933. *szOut = size;
  18934. return ret;
  18935. }
  18936. /* Decrypt using Quantum Safe Handshake algorithms */
  18937. int QSH_Decrypt(QSHKey* key, byte* in, word32 szIn, byte* out, word16* szOut)
  18938. {
  18939. int ret = 0;
  18940. word16 size = *szOut;
  18941. (void)in;
  18942. (void)szIn;
  18943. (void)out;
  18944. (void)szOut;
  18945. WOLFSSL_MSG("Decrypting QSH key material");
  18946. switch (key->name) {
  18947. #ifdef HAVE_NTRU
  18948. case WOLFSSL_NTRU_EESS439:
  18949. case WOLFSSL_NTRU_EESS593:
  18950. case WOLFSSL_NTRU_EESS743:
  18951. ret = NtruSecretDecrypt(key, in, szIn, out, &size);
  18952. break;
  18953. #endif
  18954. default:
  18955. WOLFSSL_MSG("Unknown QSH decryption key!");
  18956. return -1;
  18957. }
  18958. *szOut = size;
  18959. return ret;
  18960. }
  18961. /* Get the max cipher text for corresponding encryption scheme
  18962. (encrypting 48 or max plain text whichever is smaller)
  18963. */
  18964. static word32 QSH_MaxSecret(QSHKey* key)
  18965. {
  18966. int ret = 0;
  18967. #ifdef HAVE_NTRU
  18968. byte isNtru = 0;
  18969. word16 inSz = 48;
  18970. word16 outSz;
  18971. DRBG_HANDLE drbg = 0;
  18972. byte bufIn[48];
  18973. #endif
  18974. if (key == NULL || key->pub.length == 0)
  18975. return 0;
  18976. switch(key->name) {
  18977. #ifdef HAVE_NTRU
  18978. case WOLFSSL_NTRU_EESS439:
  18979. isNtru = 1;
  18980. break;
  18981. case WOLFSSL_NTRU_EESS593:
  18982. isNtru = 1;
  18983. break;
  18984. case WOLFSSL_NTRU_EESS743:
  18985. isNtru = 1;
  18986. break;
  18987. #endif
  18988. default:
  18989. WOLFSSL_MSG("Unknown QSH encryption scheme size!");
  18990. return 0;
  18991. }
  18992. #ifdef HAVE_NTRU
  18993. if (isNtru) {
  18994. ret = ntru_crypto_drbg_external_instantiate(GetEntropy, &drbg);
  18995. if (ret != DRBG_OK)
  18996. return NTRU_DRBG_ERROR;
  18997. ret = ntru_crypto_ntru_encrypt(drbg, key->pub.length,
  18998. key->pub.buffer, inSz, bufIn, &outSz, NULL);
  18999. if (ret != NTRU_OK) {
  19000. return NTRU_ENCRYPT_ERROR;
  19001. }
  19002. ntru_crypto_drbg_uninstantiate(drbg);
  19003. ret = outSz;
  19004. }
  19005. #endif
  19006. return ret;
  19007. }
  19008. /* Generate the secret byte material for pms
  19009. returns length on success and -1 on fail
  19010. */
  19011. static int QSH_GenerateSerCliSecret(WOLFSSL* ssl, byte isServer)
  19012. {
  19013. int sz = 0;
  19014. int plainSz = 48; /* lesser of 48 and max plain text able to encrypt */
  19015. int offset = 0;
  19016. word32 tmpSz = 0;
  19017. buffer* buf;
  19018. QSHKey* current;
  19019. QSHScheme* schmPre = NULL;
  19020. QSHScheme* schm = NULL;
  19021. if (ssl == NULL)
  19022. return -1;
  19023. WOLFSSL_MSG("Generating QSH secret key material");
  19024. current = ssl->peerQSHKey;
  19025. /* get size of buffer needed */
  19026. while (current) {
  19027. if (current->pub.length != 0) {
  19028. sz += plainSz;
  19029. }
  19030. current = (QSHKey*)current->next;
  19031. }
  19032. /* allocate memory for buffer */
  19033. if (isServer) {
  19034. buf = ssl->QSH_secret->SerSi;
  19035. }
  19036. else {
  19037. buf = ssl->QSH_secret->CliSi;
  19038. }
  19039. buf->length = sz;
  19040. buf->buffer = (byte*)XMALLOC(sz, ssl->heap, DYNAMIC_TYPE_SECRET);
  19041. if (buf->buffer == NULL) {
  19042. WOLFSSL_ERROR(MEMORY_E);
  19043. }
  19044. /* create secret information */
  19045. sz = 0;
  19046. current = ssl->peerQSHKey;
  19047. while (current) {
  19048. schm = (QSHScheme*)XMALLOC(sizeof(QSHScheme), ssl->heap,
  19049. DYNAMIC_TYPE_QSH);
  19050. if (schm == NULL)
  19051. return MEMORY_E;
  19052. /* initialize variables */
  19053. schm->name = 0;
  19054. schm->PK = NULL;
  19055. schm->PKLen = 0;
  19056. schm->next = NULL;
  19057. if (ssl->QSH_secret->list == NULL) {
  19058. ssl->QSH_secret->list = schm;
  19059. }
  19060. else {
  19061. if (schmPre)
  19062. schmPre->next = schm;
  19063. }
  19064. tmpSz = QSH_MaxSecret(current);
  19065. if ((schm->PK = (byte*)XMALLOC(tmpSz, ssl->heap,
  19066. DYNAMIC_TYPE_SECRET)) == NULL)
  19067. return -1;
  19068. /* store info for writing extension */
  19069. schm->name = current->name;
  19070. /* no key to use for encryption */
  19071. if (tmpSz == 0) {
  19072. current = (QSHKey*)current->next;
  19073. continue;
  19074. }
  19075. if (wc_RNG_GenerateBlock(ssl->rng, buf->buffer + offset, plainSz)
  19076. != 0) {
  19077. return -1;
  19078. }
  19079. if (QSH_Encrypt(current, buf->buffer + offset, plainSz, schm->PK,
  19080. &tmpSz) != 0) {
  19081. return -1;
  19082. }
  19083. schm->PKLen = tmpSz;
  19084. sz += tmpSz;
  19085. offset += plainSz;
  19086. schmPre = schm;
  19087. current = (QSHKey*)current->next;
  19088. }
  19089. return sz;
  19090. }
  19091. static word32 QSH_KeyGetSize(WOLFSSL* ssl)
  19092. {
  19093. word32 sz = 0;
  19094. QSHKey* current;
  19095. if (ssl == NULL)
  19096. return -1;
  19097. current = ssl->peerQSHKey;
  19098. sz += OPAQUE16_LEN; /* type of extension ie 0x00 0x18 */
  19099. sz += OPAQUE24_LEN;
  19100. /* get size of buffer needed */
  19101. while (current) {
  19102. sz += OPAQUE16_LEN; /* scheme id */
  19103. sz += OPAQUE16_LEN; /* encrypted key len*/
  19104. sz += QSH_MaxSecret(current);
  19105. current = (QSHKey*)current->next;
  19106. }
  19107. return sz;
  19108. }
  19109. /* handle QSH key Exchange
  19110. return 0 on success
  19111. */
  19112. static word32 QSH_KeyExchangeWrite(WOLFSSL* ssl, byte isServer)
  19113. {
  19114. int ret = 0;
  19115. WOLFSSL_ENTER("QSH KeyExchange");
  19116. ret = QSH_GenerateSerCliSecret(ssl, isServer);
  19117. if (ret < 0)
  19118. return MEMORY_E;
  19119. return 0;
  19120. }
  19121. #endif /* HAVE_QSH */
  19122. typedef struct SckeArgs {
  19123. byte* output; /* not allocated */
  19124. byte* encSecret;
  19125. byte* input;
  19126. word32 encSz;
  19127. word32 length;
  19128. int sendSz;
  19129. int inputSz;
  19130. } SckeArgs;
  19131. static void FreeSckeArgs(WOLFSSL* ssl, void* pArgs)
  19132. {
  19133. SckeArgs* args = (SckeArgs*)pArgs;
  19134. (void)ssl;
  19135. if (args->encSecret) {
  19136. XFREE(args->encSecret, ssl->heap, DYNAMIC_TYPE_SECRET);
  19137. args->encSecret = NULL;
  19138. }
  19139. if (args->input) {
  19140. XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  19141. args->input = NULL;
  19142. }
  19143. }
  19144. /* handle generation client_key_exchange (16) */
  19145. int SendClientKeyExchange(WOLFSSL* ssl)
  19146. {
  19147. int ret = 0;
  19148. #ifdef WOLFSSL_ASYNC_CRYPT
  19149. SckeArgs* args = (SckeArgs*)ssl->async.args;
  19150. typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
  19151. (void)sizeof(args_test);
  19152. #else
  19153. SckeArgs args[1];
  19154. #endif
  19155. WOLFSSL_START(WC_FUNC_CLIENT_KEY_EXCHANGE_SEND);
  19156. WOLFSSL_ENTER("SendClientKeyExchange");
  19157. #ifdef OPENSSL_EXTRA
  19158. ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
  19159. ssl->cbmode = SSL_CB_MODE_WRITE;
  19160. if (ssl->CBIS != NULL)
  19161. ssl->CBIS(ssl, SSL_CB_CONNECT_LOOP, SSL_SUCCESS);
  19162. #endif
  19163. #ifdef WOLFSSL_ASYNC_CRYPT
  19164. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  19165. if (ret != WC_NOT_PENDING_E) {
  19166. /* Check for error */
  19167. if (ret < 0)
  19168. goto exit_scke;
  19169. }
  19170. else
  19171. #endif
  19172. {
  19173. /* Reset state */
  19174. ret = 0;
  19175. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  19176. XMEMSET(args, 0, sizeof(SckeArgs));
  19177. #ifdef WOLFSSL_ASYNC_CRYPT
  19178. ssl->async.freeArgs = FreeSckeArgs;
  19179. #endif
  19180. }
  19181. switch(ssl->options.asyncState)
  19182. {
  19183. case TLS_ASYNC_BEGIN:
  19184. {
  19185. switch (ssl->specs.kea) {
  19186. #ifndef NO_RSA
  19187. case rsa_kea:
  19188. if (ssl->peerRsaKey == NULL ||
  19189. ssl->peerRsaKeyPresent == 0) {
  19190. ERROR_OUT(NO_PEER_KEY, exit_scke);
  19191. }
  19192. break;
  19193. #endif
  19194. #ifndef NO_DH
  19195. case diffie_hellman_kea:
  19196. if (ssl->buffers.serverDH_P.buffer == NULL ||
  19197. ssl->buffers.serverDH_G.buffer == NULL ||
  19198. ssl->buffers.serverDH_Pub.buffer == NULL) {
  19199. ERROR_OUT(NO_PEER_KEY, exit_scke);
  19200. }
  19201. break;
  19202. #endif /* NO_DH */
  19203. #ifndef NO_PSK
  19204. case psk_kea:
  19205. /* sanity check that PSK client callback has been set */
  19206. if (ssl->options.client_psk_cb == NULL) {
  19207. WOLFSSL_MSG("No client PSK callback set");
  19208. ERROR_OUT(PSK_KEY_ERROR, exit_scke);
  19209. }
  19210. break;
  19211. #endif /* NO_PSK */
  19212. #if !defined(NO_DH) && !defined(NO_PSK)
  19213. case dhe_psk_kea:
  19214. if (ssl->buffers.serverDH_P.buffer == NULL ||
  19215. ssl->buffers.serverDH_G.buffer == NULL ||
  19216. ssl->buffers.serverDH_Pub.buffer == NULL) {
  19217. ERROR_OUT(NO_PEER_KEY, exit_scke);
  19218. }
  19219. /* sanity check that PSK client callback has been set */
  19220. if (ssl->options.client_psk_cb == NULL) {
  19221. WOLFSSL_MSG("No client PSK callback set");
  19222. ERROR_OUT(PSK_KEY_ERROR, exit_scke);
  19223. }
  19224. break;
  19225. #endif /* !NO_DH && !NO_PSK */
  19226. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  19227. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  19228. case ecdhe_psk_kea:
  19229. /* sanity check that PSK client callback has been set */
  19230. if (ssl->options.client_psk_cb == NULL) {
  19231. WOLFSSL_MSG("No client PSK callback set");
  19232. ERROR_OUT(PSK_KEY_ERROR, exit_scke);
  19233. }
  19234. #ifdef HAVE_CURVE25519
  19235. if (ssl->peerX25519KeyPresent) {
  19236. /* Check client ECC public key */
  19237. if (!ssl->peerX25519Key || !ssl->peerX25519Key->dp) {
  19238. ERROR_OUT(NO_PEER_KEY, exit_scke);
  19239. }
  19240. #ifdef HAVE_PK_CALLBACKS
  19241. /* if callback then use it for shared secret */
  19242. if (ssl->ctx->X25519SharedSecretCb != NULL) {
  19243. break;
  19244. }
  19245. #endif
  19246. /* create private key */
  19247. ssl->hsType = DYNAMIC_TYPE_CURVE25519;
  19248. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  19249. if (ret != 0) {
  19250. goto exit_scke;
  19251. }
  19252. ret = X25519MakeKey(ssl, (curve25519_key*)ssl->hsKey,
  19253. ssl->peerX25519Key);
  19254. break;
  19255. }
  19256. #endif
  19257. #ifdef HAVE_CURVE448
  19258. if (ssl->peerX448KeyPresent) {
  19259. /* Check client ECC public key */
  19260. if (!ssl->peerX448Key) {
  19261. ERROR_OUT(NO_PEER_KEY, exit_scke);
  19262. }
  19263. #ifdef HAVE_PK_CALLBACKS
  19264. /* if callback then use it for shared secret */
  19265. if (ssl->ctx->X448SharedSecretCb != NULL) {
  19266. break;
  19267. }
  19268. #endif
  19269. /* create private key */
  19270. ssl->hsType = DYNAMIC_TYPE_CURVE448;
  19271. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  19272. if (ret != 0) {
  19273. goto exit_scke;
  19274. }
  19275. ret = X448MakeKey(ssl, (curve448_key*)ssl->hsKey,
  19276. ssl->peerX448Key);
  19277. break;
  19278. }
  19279. #endif
  19280. /* Check client ECC public key */
  19281. if (!ssl->peerEccKey || !ssl->peerEccKeyPresent ||
  19282. !ssl->peerEccKey->dp) {
  19283. ERROR_OUT(NO_PEER_KEY, exit_scke);
  19284. }
  19285. #ifdef HAVE_PK_CALLBACKS
  19286. /* if callback then use it for shared secret */
  19287. if (ssl->ctx->EccSharedSecretCb != NULL) {
  19288. break;
  19289. }
  19290. #endif
  19291. /* create ephemeral private key */
  19292. ssl->hsType = DYNAMIC_TYPE_ECC;
  19293. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  19294. if (ret != 0) {
  19295. goto exit_scke;
  19296. }
  19297. ret = EccMakeKey(ssl, (ecc_key*)ssl->hsKey, ssl->peerEccKey);
  19298. break;
  19299. #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
  19300. #ifdef HAVE_NTRU
  19301. case ntru_kea:
  19302. if (ssl->peerNtruKeyPresent == 0) {
  19303. ERROR_OUT(NO_PEER_KEY, exit_scke);
  19304. }
  19305. break;
  19306. #endif /* HAVE_NTRU */
  19307. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  19308. defined(HAVE_CURVE448)
  19309. case ecc_diffie_hellman_kea:
  19310. {
  19311. #ifdef HAVE_ECC
  19312. ecc_key* peerKey;
  19313. #endif
  19314. #ifdef HAVE_PK_CALLBACKS
  19315. /* if callback then use it for shared secret */
  19316. #ifdef HAVE_CURVE25519
  19317. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  19318. if (ssl->ctx->X25519SharedSecretCb != NULL)
  19319. break;
  19320. }
  19321. else
  19322. #endif
  19323. #ifdef HAVE_CURVE448
  19324. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  19325. if (ssl->ctx->X448SharedSecretCb != NULL)
  19326. break;
  19327. }
  19328. else
  19329. #endif
  19330. if (ssl->ctx->EccSharedSecretCb != NULL) {
  19331. break;
  19332. }
  19333. #endif /* HAVE_PK_CALLBACKS */
  19334. #ifdef HAVE_CURVE25519
  19335. if (ssl->peerX25519KeyPresent) {
  19336. if (!ssl->peerX25519Key || !ssl->peerX25519Key->dp) {
  19337. ERROR_OUT(NO_PEER_KEY, exit_scke);
  19338. }
  19339. /* create private key */
  19340. ssl->hsType = DYNAMIC_TYPE_CURVE25519;
  19341. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  19342. if (ret != 0) {
  19343. goto exit_scke;
  19344. }
  19345. ret = X25519MakeKey(ssl, (curve25519_key*)ssl->hsKey,
  19346. ssl->peerX25519Key);
  19347. break;
  19348. }
  19349. #endif
  19350. #ifdef HAVE_CURVE448
  19351. if (ssl->peerX448KeyPresent) {
  19352. if (!ssl->peerX448Key) {
  19353. ERROR_OUT(NO_PEER_KEY, exit_scke);
  19354. }
  19355. /* create private key */
  19356. ssl->hsType = DYNAMIC_TYPE_CURVE448;
  19357. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  19358. if (ret != 0) {
  19359. goto exit_scke;
  19360. }
  19361. ret = X448MakeKey(ssl, (curve448_key*)ssl->hsKey,
  19362. ssl->peerX448Key);
  19363. break;
  19364. }
  19365. #endif
  19366. #ifdef HAVE_ECC
  19367. if (ssl->specs.static_ecdh) {
  19368. /* Note: EccDsa is really fixed Ecc key here */
  19369. if (!ssl->peerEccDsaKey || !ssl->peerEccDsaKeyPresent) {
  19370. ERROR_OUT(NO_PEER_KEY, exit_scke);
  19371. }
  19372. peerKey = ssl->peerEccDsaKey;
  19373. }
  19374. else {
  19375. if (!ssl->peerEccKey || !ssl->peerEccKeyPresent) {
  19376. ERROR_OUT(NO_PEER_KEY, exit_scke);
  19377. }
  19378. peerKey = ssl->peerEccKey;
  19379. }
  19380. if (peerKey == NULL) {
  19381. ERROR_OUT(NO_PEER_KEY, exit_scke);
  19382. }
  19383. /* create ephemeral private key */
  19384. ssl->hsType = DYNAMIC_TYPE_ECC;
  19385. ret = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
  19386. if (ret != 0) {
  19387. goto exit_scke;
  19388. }
  19389. ret = EccMakeKey(ssl, (ecc_key*)ssl->hsKey, peerKey);
  19390. #endif
  19391. break;
  19392. }
  19393. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  19394. default:
  19395. ret = BAD_KEA_TYPE_E;
  19396. } /* switch(ssl->specs.kea) */
  19397. /* Check for error */
  19398. if (ret != 0) {
  19399. goto exit_scke;
  19400. }
  19401. /* Advance state and proceed */
  19402. ssl->options.asyncState = TLS_ASYNC_BUILD;
  19403. } /* case TLS_ASYNC_BEGIN */
  19404. FALL_THROUGH;
  19405. case TLS_ASYNC_BUILD:
  19406. {
  19407. args->encSz = MAX_ENCRYPT_SZ;
  19408. args->encSecret = (byte*)XMALLOC(args->encSz, ssl->heap,
  19409. DYNAMIC_TYPE_SECRET);
  19410. if (args->encSecret == NULL) {
  19411. ERROR_OUT(MEMORY_E, exit_scke);
  19412. }
  19413. if (ssl->arrays->preMasterSecret == NULL) {
  19414. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  19415. ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN,
  19416. ssl->heap, DYNAMIC_TYPE_SECRET);
  19417. if (ssl->arrays->preMasterSecret == NULL) {
  19418. ERROR_OUT(MEMORY_E, exit_scke);
  19419. }
  19420. XMEMSET(ssl->arrays->preMasterSecret, 0, ENCRYPT_LEN);
  19421. }
  19422. switch(ssl->specs.kea)
  19423. {
  19424. #ifndef NO_RSA
  19425. case rsa_kea:
  19426. {
  19427. /* build PreMasterSecret with RNG data */
  19428. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && \
  19429. !defined(NO_WOLFSSL_RENESAS_TSIP_TLS_SESSION)
  19430. if (tsip_useable(ssl)) {
  19431. ret = tsip_generatePremasterSecret(
  19432. &ssl->arrays->preMasterSecret[VERSION_SZ],
  19433. ENCRYPT_LEN - VERSION_SZ);
  19434. } else {
  19435. #endif
  19436. ret = wc_RNG_GenerateBlock(ssl->rng,
  19437. &ssl->arrays->preMasterSecret[VERSION_SZ],
  19438. SECRET_LEN - VERSION_SZ);
  19439. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && \
  19440. !defined(NO_WOLFSSL_RENESAS_TSIP_TLS_SESSION)
  19441. }
  19442. #endif
  19443. if (ret != 0) {
  19444. goto exit_scke;
  19445. }
  19446. ssl->arrays->preMasterSecret[0] = ssl->chVersion.major;
  19447. ssl->arrays->preMasterSecret[1] = ssl->chVersion.minor;
  19448. ssl->arrays->preMasterSz = SECRET_LEN;
  19449. break;
  19450. }
  19451. #endif /* !NO_RSA */
  19452. #ifndef NO_DH
  19453. case diffie_hellman_kea:
  19454. {
  19455. ssl->buffers.sig.length = ENCRYPT_LEN;
  19456. ssl->buffers.sig.buffer = (byte*)XMALLOC(ENCRYPT_LEN,
  19457. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  19458. if (ssl->buffers.sig.buffer == NULL) {
  19459. ERROR_OUT(MEMORY_E, exit_scke);
  19460. }
  19461. ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
  19462. (void**)&ssl->buffers.serverDH_Key);
  19463. if (ret != 0) {
  19464. goto exit_scke;
  19465. }
  19466. #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \
  19467. !defined(WOLFSSL_OLD_PRIME_CHECK)
  19468. if (ssl->options.dhDoKeyTest &&
  19469. !ssl->options.dhKeyTested)
  19470. {
  19471. ret = wc_DhSetCheckKey(ssl->buffers.serverDH_Key,
  19472. ssl->buffers.serverDH_P.buffer,
  19473. ssl->buffers.serverDH_P.length,
  19474. ssl->buffers.serverDH_G.buffer,
  19475. ssl->buffers.serverDH_G.length,
  19476. NULL, 0, 0, ssl->rng);
  19477. if (ret != 0) {
  19478. goto exit_scke;
  19479. }
  19480. ssl->options.dhKeyTested = 1;
  19481. }
  19482. else
  19483. #endif
  19484. {
  19485. ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
  19486. ssl->buffers.serverDH_P.buffer,
  19487. ssl->buffers.serverDH_P.length,
  19488. ssl->buffers.serverDH_G.buffer,
  19489. ssl->buffers.serverDH_G.length);
  19490. if (ret != 0) {
  19491. goto exit_scke;
  19492. }
  19493. }
  19494. /* for DH, encSecret is Yc, agree is pre-master */
  19495. ret = DhGenKeyPair(ssl, ssl->buffers.serverDH_Key,
  19496. ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
  19497. args->encSecret, &args->encSz);
  19498. /* set the max agree result size */
  19499. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  19500. break;
  19501. }
  19502. #endif /* !NO_DH */
  19503. #ifndef NO_PSK
  19504. case psk_kea:
  19505. {
  19506. byte* pms = ssl->arrays->preMasterSecret;
  19507. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  19508. ssl->arrays->server_hint, ssl->arrays->client_identity,
  19509. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  19510. if (ssl->arrays->psk_keySz == 0 ||
  19511. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  19512. ERROR_OUT(PSK_KEY_ERROR, exit_scke);
  19513. }
  19514. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0'; /* null term */
  19515. args->encSz = (word32)XSTRLEN(ssl->arrays->client_identity);
  19516. if (args->encSz > MAX_PSK_ID_LEN) {
  19517. ERROR_OUT(CLIENT_ID_ERROR, exit_scke);
  19518. }
  19519. XMEMCPY(args->encSecret, ssl->arrays->client_identity,
  19520. args->encSz);
  19521. /* make psk pre master secret */
  19522. /* length of key + length 0s + length of key + key */
  19523. c16toa((word16)ssl->arrays->psk_keySz, pms);
  19524. pms += OPAQUE16_LEN;
  19525. XMEMSET(pms, 0, ssl->arrays->psk_keySz);
  19526. pms += ssl->arrays->psk_keySz;
  19527. c16toa((word16)ssl->arrays->psk_keySz, pms);
  19528. pms += OPAQUE16_LEN;
  19529. XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  19530. ssl->arrays->preMasterSz = (ssl->arrays->psk_keySz * 2) +
  19531. (2 * OPAQUE16_LEN);
  19532. ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  19533. ssl->arrays->psk_keySz = 0; /* No further need */
  19534. break;
  19535. }
  19536. #endif /* !NO_PSK */
  19537. #if !defined(NO_DH) && !defined(NO_PSK)
  19538. case dhe_psk_kea:
  19539. {
  19540. word32 esSz = 0;
  19541. args->output = args->encSecret;
  19542. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  19543. ssl->arrays->server_hint, ssl->arrays->client_identity,
  19544. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  19545. if (ssl->arrays->psk_keySz == 0 ||
  19546. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  19547. ERROR_OUT(PSK_KEY_ERROR, exit_scke);
  19548. }
  19549. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0'; /* null term */
  19550. esSz = (word32)XSTRLEN(ssl->arrays->client_identity);
  19551. if (esSz > MAX_PSK_ID_LEN) {
  19552. ERROR_OUT(CLIENT_ID_ERROR, exit_scke);
  19553. }
  19554. ssl->buffers.sig.length = ENCRYPT_LEN;
  19555. ssl->buffers.sig.buffer = (byte*)XMALLOC(ENCRYPT_LEN,
  19556. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  19557. if (ssl->buffers.sig.buffer == NULL) {
  19558. ERROR_OUT(MEMORY_E, exit_scke);
  19559. }
  19560. c16toa((word16)esSz, args->output);
  19561. args->output += OPAQUE16_LEN;
  19562. XMEMCPY(args->output, ssl->arrays->client_identity, esSz);
  19563. args->output += esSz;
  19564. args->encSz = esSz + OPAQUE16_LEN;
  19565. args->length = 0;
  19566. ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
  19567. (void**)&ssl->buffers.serverDH_Key);
  19568. if (ret != 0) {
  19569. goto exit_scke;
  19570. }
  19571. #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && \
  19572. !defined(WOLFSSL_OLD_PRIME_CHECK)
  19573. if (ssl->options.dhDoKeyTest &&
  19574. !ssl->options.dhKeyTested)
  19575. {
  19576. ret = wc_DhSetCheckKey(ssl->buffers.serverDH_Key,
  19577. ssl->buffers.serverDH_P.buffer,
  19578. ssl->buffers.serverDH_P.length,
  19579. ssl->buffers.serverDH_G.buffer,
  19580. ssl->buffers.serverDH_G.length,
  19581. NULL, 0, 0, ssl->rng);
  19582. if (ret != 0) {
  19583. goto exit_scke;
  19584. }
  19585. ssl->options.dhKeyTested = 1;
  19586. }
  19587. else
  19588. #endif
  19589. {
  19590. ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
  19591. ssl->buffers.serverDH_P.buffer,
  19592. ssl->buffers.serverDH_P.length,
  19593. ssl->buffers.serverDH_G.buffer,
  19594. ssl->buffers.serverDH_G.length);
  19595. if (ret != 0) {
  19596. goto exit_scke;
  19597. }
  19598. }
  19599. /* for DH, encSecret is Yc, agree is pre-master */
  19600. ret = DhGenKeyPair(ssl, ssl->buffers.serverDH_Key,
  19601. ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
  19602. args->output + OPAQUE16_LEN, &args->length);
  19603. break;
  19604. }
  19605. #endif /* !NO_DH && !NO_PSK */
  19606. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  19607. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  19608. case ecdhe_psk_kea:
  19609. {
  19610. word32 esSz = 0;
  19611. args->output = args->encSecret;
  19612. /* Send PSK client identity */
  19613. ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
  19614. ssl->arrays->server_hint, ssl->arrays->client_identity,
  19615. MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
  19616. if (ssl->arrays->psk_keySz == 0 ||
  19617. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  19618. ERROR_OUT(PSK_KEY_ERROR, exit_scke);
  19619. }
  19620. ssl->arrays->client_identity[MAX_PSK_ID_LEN] = '\0'; /* null term */
  19621. esSz = (word32)XSTRLEN(ssl->arrays->client_identity);
  19622. if (esSz > MAX_PSK_ID_LEN) {
  19623. ERROR_OUT(CLIENT_ID_ERROR, exit_scke);
  19624. }
  19625. /* place size and identity in output buffer sz:identity */
  19626. c16toa((word16)esSz, args->output);
  19627. args->output += OPAQUE16_LEN;
  19628. XMEMCPY(args->output, ssl->arrays->client_identity, esSz);
  19629. args->output += esSz;
  19630. args->encSz = esSz + OPAQUE16_LEN;
  19631. /* length is used for public key size */
  19632. args->length = MAX_ENCRYPT_SZ;
  19633. /* Create shared ECC key leaving room at the beginning
  19634. of buffer for size of shared key. */
  19635. ssl->arrays->preMasterSz = ENCRYPT_LEN - OPAQUE16_LEN;
  19636. #ifdef HAVE_CURVE25519
  19637. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  19638. #ifdef HAVE_PK_CALLBACKS
  19639. /* if callback then use it for shared secret */
  19640. if (ssl->ctx->X25519SharedSecretCb != NULL) {
  19641. break;
  19642. }
  19643. #endif
  19644. ret = wc_curve25519_export_public_ex(
  19645. (curve25519_key*)ssl->hsKey,
  19646. args->output + OPAQUE8_LEN, &args->length,
  19647. EC25519_LITTLE_ENDIAN);
  19648. if (ret != 0) {
  19649. ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
  19650. }
  19651. break;
  19652. }
  19653. #endif
  19654. #ifdef HAVE_CURVE448
  19655. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  19656. #ifdef HAVE_PK_CALLBACKS
  19657. /* if callback then use it for shared secret */
  19658. if (ssl->ctx->X448SharedSecretCb != NULL) {
  19659. break;
  19660. }
  19661. #endif
  19662. ret = wc_curve448_export_public_ex(
  19663. (curve448_key*)ssl->hsKey,
  19664. args->output + OPAQUE8_LEN, &args->length,
  19665. EC448_LITTLE_ENDIAN);
  19666. if (ret != 0) {
  19667. ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
  19668. }
  19669. break;
  19670. }
  19671. #endif
  19672. #ifdef HAVE_PK_CALLBACKS
  19673. /* if callback then use it for shared secret */
  19674. if (ssl->ctx->EccSharedSecretCb != NULL) {
  19675. break;
  19676. }
  19677. #endif
  19678. /* Place ECC key in output buffer, leaving room for size */
  19679. ret = wc_ecc_export_x963((ecc_key*)ssl->hsKey,
  19680. args->output + OPAQUE8_LEN, &args->length);
  19681. if (ret != 0) {
  19682. ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
  19683. }
  19684. break;
  19685. }
  19686. #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
  19687. #ifdef HAVE_NTRU
  19688. case ntru_kea:
  19689. {
  19690. ret = wc_RNG_GenerateBlock(ssl->rng,
  19691. ssl->arrays->preMasterSecret, SECRET_LEN);
  19692. if (ret != 0) {
  19693. goto exit_scke;
  19694. }
  19695. ssl->arrays->preMasterSz = SECRET_LEN;
  19696. args->encSz = MAX_ENCRYPT_SZ;
  19697. break;
  19698. }
  19699. #endif /* HAVE_NTRU */
  19700. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  19701. defined(HAVE_CURVE448)
  19702. case ecc_diffie_hellman_kea:
  19703. {
  19704. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  19705. #ifdef HAVE_CURVE25519
  19706. if (ssl->hsType == DYNAMIC_TYPE_CURVE25519) {
  19707. #ifdef HAVE_PK_CALLBACKS
  19708. /* if callback then use it for shared secret */
  19709. if (ssl->ctx->X25519SharedSecretCb != NULL) {
  19710. break;
  19711. }
  19712. #endif
  19713. ret = wc_curve25519_export_public_ex(
  19714. (curve25519_key*)ssl->hsKey,
  19715. args->encSecret + OPAQUE8_LEN, &args->encSz,
  19716. EC25519_LITTLE_ENDIAN);
  19717. if (ret != 0) {
  19718. ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
  19719. }
  19720. break;
  19721. }
  19722. #endif
  19723. #ifdef HAVE_CURVE448
  19724. if (ssl->hsType == DYNAMIC_TYPE_CURVE448) {
  19725. #ifdef HAVE_PK_CALLBACKS
  19726. /* if callback then use it for shared secret */
  19727. if (ssl->ctx->X448SharedSecretCb != NULL) {
  19728. break;
  19729. }
  19730. #endif
  19731. ret = wc_curve448_export_public_ex(
  19732. (curve448_key*)ssl->hsKey,
  19733. args->encSecret + OPAQUE8_LEN, &args->encSz,
  19734. EC448_LITTLE_ENDIAN);
  19735. if (ret != 0) {
  19736. ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
  19737. }
  19738. break;
  19739. }
  19740. #endif
  19741. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  19742. #ifdef HAVE_PK_CALLBACKS
  19743. /* if callback then use it for shared secret */
  19744. if (ssl->ctx->EccSharedSecretCb != NULL) {
  19745. break;
  19746. }
  19747. #endif
  19748. /* Place ECC key in buffer, leaving room for size */
  19749. ret = wc_ecc_export_x963((ecc_key*)ssl->hsKey,
  19750. args->encSecret + OPAQUE8_LEN, &args->encSz);
  19751. if (ret != 0) {
  19752. ERROR_OUT(ECC_EXPORT_ERROR, exit_scke);
  19753. }
  19754. #endif /* HAVE_ECC */
  19755. break;
  19756. }
  19757. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  19758. default:
  19759. ret = BAD_KEA_TYPE_E;
  19760. } /* switch(ssl->specs.kea) */
  19761. /* Check for error */
  19762. if (ret != 0) {
  19763. goto exit_scke;
  19764. }
  19765. /* Advance state and proceed */
  19766. ssl->options.asyncState = TLS_ASYNC_DO;
  19767. } /* case TLS_ASYNC_BUILD */
  19768. FALL_THROUGH;
  19769. case TLS_ASYNC_DO:
  19770. {
  19771. switch(ssl->specs.kea)
  19772. {
  19773. #ifndef NO_RSA
  19774. case rsa_kea:
  19775. {
  19776. #if defined(WOLFSSL_RENESAS_TSIP_TLS) && \
  19777. !defined(NO_WOLFSSL_RENESAS_TSIP_TLS_SESSION)
  19778. if (tsip_useable(ssl) &&
  19779. wc_RsaEncryptSize(ssl->peerRsaKey) == 256) {
  19780. ret = tsip_generateEncryptPreMasterSecret(ssl,
  19781. args->encSecret,
  19782. &args->encSz);
  19783. } else
  19784. #endif
  19785. ret = RsaEnc(ssl,
  19786. ssl->arrays->preMasterSecret, SECRET_LEN,
  19787. args->encSecret, &args->encSz,
  19788. ssl->peerRsaKey,
  19789. #if defined(HAVE_PK_CALLBACKS)
  19790. &ssl->buffers.peerRsaKey
  19791. #else
  19792. NULL
  19793. #endif
  19794. );
  19795. break;
  19796. }
  19797. #endif /* !NO_RSA */
  19798. #ifndef NO_DH
  19799. case diffie_hellman_kea:
  19800. {
  19801. ret = DhAgree(ssl, ssl->buffers.serverDH_Key,
  19802. ssl->buffers.sig.buffer, ssl->buffers.sig.length,
  19803. ssl->buffers.serverDH_Pub.buffer,
  19804. ssl->buffers.serverDH_Pub.length,
  19805. ssl->arrays->preMasterSecret,
  19806. &ssl->arrays->preMasterSz);
  19807. break;
  19808. }
  19809. #endif /* !NO_DH */
  19810. #ifndef NO_PSK
  19811. case psk_kea:
  19812. {
  19813. break;
  19814. }
  19815. #endif /* !NO_PSK */
  19816. #if !defined(NO_DH) && !defined(NO_PSK)
  19817. case dhe_psk_kea:
  19818. {
  19819. ret = DhAgree(ssl, ssl->buffers.serverDH_Key,
  19820. ssl->buffers.sig.buffer, ssl->buffers.sig.length,
  19821. ssl->buffers.serverDH_Pub.buffer,
  19822. ssl->buffers.serverDH_Pub.length,
  19823. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  19824. &ssl->arrays->preMasterSz);
  19825. break;
  19826. }
  19827. #endif /* !NO_DH && !NO_PSK */
  19828. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  19829. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  19830. case ecdhe_psk_kea:
  19831. {
  19832. #ifdef HAVE_CURVE25519
  19833. if (ssl->peerX25519KeyPresent) {
  19834. ret = X25519SharedSecret(ssl,
  19835. (curve25519_key*)ssl->hsKey, ssl->peerX25519Key,
  19836. args->output + OPAQUE8_LEN, &args->length,
  19837. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  19838. &ssl->arrays->preMasterSz,
  19839. WOLFSSL_CLIENT_END
  19840. );
  19841. if (!ssl->specs.static_ecdh
  19842. #ifdef WOLFSSL_ASYNC_CRYPT
  19843. && ret != WC_PENDING_E
  19844. #endif
  19845. ) {
  19846. FreeKey(ssl, DYNAMIC_TYPE_CURVE25519,
  19847. (void**)&ssl->peerX25519Key);
  19848. ssl->peerX25519KeyPresent = 0;
  19849. }
  19850. break;
  19851. }
  19852. #endif
  19853. #ifdef HAVE_CURVE448
  19854. if (ssl->peerX448KeyPresent) {
  19855. ret = X448SharedSecret(ssl,
  19856. (curve448_key*)ssl->hsKey, ssl->peerX448Key,
  19857. args->output + OPAQUE8_LEN, &args->length,
  19858. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  19859. &ssl->arrays->preMasterSz,
  19860. WOLFSSL_CLIENT_END
  19861. );
  19862. if (!ssl->specs.static_ecdh
  19863. #ifdef WOLFSSL_ASYNC_CRYPT
  19864. && ret != WC_PENDING_E
  19865. #endif
  19866. ) {
  19867. FreeKey(ssl, DYNAMIC_TYPE_CURVE448,
  19868. (void**)&ssl->peerX448Key);
  19869. ssl->peerX448KeyPresent = 0;
  19870. }
  19871. break;
  19872. }
  19873. #endif
  19874. ret = EccSharedSecret(ssl,
  19875. (ecc_key*)ssl->hsKey, ssl->peerEccKey,
  19876. args->output + OPAQUE8_LEN, &args->length,
  19877. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  19878. &ssl->arrays->preMasterSz,
  19879. WOLFSSL_CLIENT_END
  19880. );
  19881. #ifdef WOLFSSL_ASYNC_CRYPT
  19882. if (ret != WC_PENDING_E)
  19883. #endif
  19884. {
  19885. FreeKey(ssl, DYNAMIC_TYPE_ECC,
  19886. (void**)&ssl->peerEccKey);
  19887. ssl->peerEccKeyPresent = 0;
  19888. }
  19889. break;
  19890. }
  19891. #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
  19892. #ifdef HAVE_NTRU
  19893. case ntru_kea:
  19894. {
  19895. word32 rc;
  19896. word16 tmpEncSz = (word16)args->encSz;
  19897. DRBG_HANDLE drbg;
  19898. rc = ntru_crypto_drbg_external_instantiate(GetEntropy, &drbg);
  19899. if (rc != DRBG_OK) {
  19900. ERROR_OUT(NTRU_DRBG_ERROR, exit_scke);
  19901. }
  19902. rc = ntru_crypto_ntru_encrypt(drbg, ssl->peerNtruKeyLen,
  19903. ssl->peerNtruKey,
  19904. ssl->arrays->preMasterSz,
  19905. ssl->arrays->preMasterSecret,
  19906. &tmpEncSz,
  19907. args->encSecret);
  19908. args->encSz = tmpEncSz;
  19909. ntru_crypto_drbg_uninstantiate(drbg);
  19910. if (rc != NTRU_OK) {
  19911. ERROR_OUT(NTRU_ENCRYPT_ERROR, exit_scke);
  19912. }
  19913. ret = 0;
  19914. break;
  19915. }
  19916. #endif /* HAVE_NTRU */
  19917. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  19918. defined(HAVE_CURVE448)
  19919. case ecc_diffie_hellman_kea:
  19920. {
  19921. #ifdef HAVE_ECC
  19922. ecc_key* peerKey;
  19923. #endif
  19924. #ifdef HAVE_CURVE25519
  19925. if (ssl->peerX25519KeyPresent) {
  19926. ret = X25519SharedSecret(ssl,
  19927. (curve25519_key*)ssl->hsKey, ssl->peerX25519Key,
  19928. args->encSecret + OPAQUE8_LEN, &args->encSz,
  19929. ssl->arrays->preMasterSecret,
  19930. &ssl->arrays->preMasterSz,
  19931. WOLFSSL_CLIENT_END
  19932. );
  19933. if (!ssl->specs.static_ecdh
  19934. #ifdef WOLFSSL_ASYNC_CRYPT
  19935. && ret != WC_PENDING_E
  19936. #endif
  19937. ) {
  19938. FreeKey(ssl, DYNAMIC_TYPE_CURVE25519,
  19939. (void**)&ssl->peerX25519Key);
  19940. ssl->peerX25519KeyPresent = 0;
  19941. }
  19942. break;
  19943. }
  19944. #endif
  19945. #ifdef HAVE_CURVE448
  19946. if (ssl->peerX448KeyPresent) {
  19947. ret = X448SharedSecret(ssl,
  19948. (curve448_key*)ssl->hsKey, ssl->peerX448Key,
  19949. args->encSecret + OPAQUE8_LEN, &args->encSz,
  19950. ssl->arrays->preMasterSecret,
  19951. &ssl->arrays->preMasterSz,
  19952. WOLFSSL_CLIENT_END
  19953. );
  19954. if (!ssl->specs.static_ecdh
  19955. #ifdef WOLFSSL_ASYNC_CRYPT
  19956. && ret != WC_PENDING_E
  19957. #endif
  19958. ) {
  19959. FreeKey(ssl, DYNAMIC_TYPE_CURVE448,
  19960. (void**)&ssl->peerX448Key);
  19961. ssl->peerX448KeyPresent = 0;
  19962. }
  19963. break;
  19964. }
  19965. #endif
  19966. #ifdef HAVE_ECC
  19967. peerKey = (ssl->specs.static_ecdh) ?
  19968. ssl->peerEccDsaKey : ssl->peerEccKey;
  19969. ret = EccSharedSecret(ssl,
  19970. (ecc_key*)ssl->hsKey, peerKey,
  19971. args->encSecret + OPAQUE8_LEN, &args->encSz,
  19972. ssl->arrays->preMasterSecret,
  19973. &ssl->arrays->preMasterSz,
  19974. WOLFSSL_CLIENT_END
  19975. );
  19976. if (!ssl->specs.static_ecdh
  19977. #ifdef WOLFSSL_ASYNC_CRYPT
  19978. && ret != WC_PENDING_E
  19979. #endif
  19980. && !ssl->options.keepResources) {
  19981. FreeKey(ssl, DYNAMIC_TYPE_ECC,
  19982. (void**)&ssl->peerEccKey);
  19983. ssl->peerEccKeyPresent = 0;
  19984. }
  19985. #endif
  19986. break;
  19987. }
  19988. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  19989. default:
  19990. ret = BAD_KEA_TYPE_E;
  19991. } /* switch(ssl->specs.kea) */
  19992. /* Check for error */
  19993. if (ret != 0) {
  19994. goto exit_scke;
  19995. }
  19996. /* Advance state and proceed */
  19997. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  19998. } /* case TLS_ASYNC_DO */
  19999. FALL_THROUGH;
  20000. case TLS_ASYNC_VERIFY:
  20001. {
  20002. switch(ssl->specs.kea)
  20003. {
  20004. #ifndef NO_RSA
  20005. case rsa_kea:
  20006. {
  20007. break;
  20008. }
  20009. #endif /* !NO_RSA */
  20010. #ifndef NO_DH
  20011. case diffie_hellman_kea:
  20012. {
  20013. break;
  20014. }
  20015. #endif /* !NO_DH */
  20016. #ifndef NO_PSK
  20017. case psk_kea:
  20018. {
  20019. break;
  20020. }
  20021. #endif /* !NO_PSK */
  20022. #if !defined(NO_DH) && !defined(NO_PSK)
  20023. case dhe_psk_kea:
  20024. {
  20025. byte* pms = ssl->arrays->preMasterSecret;
  20026. /* validate args */
  20027. if (args->output == NULL || args->length == 0) {
  20028. ERROR_OUT(BAD_FUNC_ARG, exit_scke);
  20029. }
  20030. c16toa((word16)args->length, args->output);
  20031. args->encSz += args->length + OPAQUE16_LEN;
  20032. c16toa((word16)ssl->arrays->preMasterSz, pms);
  20033. ssl->arrays->preMasterSz += OPAQUE16_LEN;
  20034. pms += ssl->arrays->preMasterSz;
  20035. /* make psk pre master secret */
  20036. /* length of key + length 0s + length of key + key */
  20037. c16toa((word16)ssl->arrays->psk_keySz, pms);
  20038. pms += OPAQUE16_LEN;
  20039. XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  20040. ssl->arrays->preMasterSz +=
  20041. ssl->arrays->psk_keySz + OPAQUE16_LEN;
  20042. ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  20043. ssl->arrays->psk_keySz = 0; /* No further need */
  20044. break;
  20045. }
  20046. #endif /* !NO_DH && !NO_PSK */
  20047. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  20048. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  20049. case ecdhe_psk_kea:
  20050. {
  20051. byte* pms = ssl->arrays->preMasterSecret;
  20052. /* validate args */
  20053. if (args->output == NULL || args->length > ENCRYPT_LEN) {
  20054. ERROR_OUT(BAD_FUNC_ARG, exit_scke);
  20055. }
  20056. /* place size of public key in output buffer */
  20057. *args->output = (byte)args->length;
  20058. args->encSz += args->length + OPAQUE8_LEN;
  20059. /* Create pre master secret is the concatenation of
  20060. eccSize + eccSharedKey + pskSize + pskKey */
  20061. c16toa((word16)ssl->arrays->preMasterSz, pms);
  20062. ssl->arrays->preMasterSz += OPAQUE16_LEN;
  20063. pms += ssl->arrays->preMasterSz;
  20064. c16toa((word16)ssl->arrays->psk_keySz, pms);
  20065. pms += OPAQUE16_LEN;
  20066. XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  20067. ssl->arrays->preMasterSz +=
  20068. ssl->arrays->psk_keySz + OPAQUE16_LEN;
  20069. ForceZero(ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  20070. ssl->arrays->psk_keySz = 0; /* No further need */
  20071. break;
  20072. }
  20073. #endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) && !NO_PSK */
  20074. #ifdef HAVE_NTRU
  20075. case ntru_kea:
  20076. {
  20077. break;
  20078. }
  20079. #endif /* HAVE_NTRU */
  20080. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  20081. defined(HAVE_CURVE448)
  20082. case ecc_diffie_hellman_kea:
  20083. {
  20084. /* place size of public key in buffer */
  20085. *args->encSecret = (byte)args->encSz;
  20086. args->encSz += OPAQUE8_LEN;
  20087. break;
  20088. }
  20089. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  20090. default:
  20091. ret = BAD_KEA_TYPE_E;
  20092. } /* switch(ssl->specs.kea) */
  20093. /* Check for error */
  20094. if (ret != 0) {
  20095. goto exit_scke;
  20096. }
  20097. /* Advance state and proceed */
  20098. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  20099. } /* case TLS_ASYNC_VERIFY */
  20100. FALL_THROUGH;
  20101. case TLS_ASYNC_FINALIZE:
  20102. {
  20103. word32 tlsSz = 0;
  20104. word32 idx = 0;
  20105. #ifdef HAVE_QSH
  20106. word32 qshSz = 0;
  20107. if (ssl->peerQSHKeyPresent) {
  20108. qshSz = QSH_KeyGetSize(ssl);
  20109. }
  20110. #endif
  20111. if (ssl->options.tls || ssl->specs.kea == diffie_hellman_kea) {
  20112. tlsSz = 2;
  20113. }
  20114. if (ssl->specs.kea == ecc_diffie_hellman_kea ||
  20115. ssl->specs.kea == dhe_psk_kea ||
  20116. ssl->specs.kea == ecdhe_psk_kea) { /* always off */
  20117. tlsSz = 0;
  20118. }
  20119. idx = HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  20120. args->sendSz = args->encSz + tlsSz + idx;
  20121. #ifdef WOLFSSL_DTLS
  20122. if (ssl->options.dtls) {
  20123. idx += DTLS_HANDSHAKE_EXTRA + DTLS_RECORD_EXTRA;
  20124. args->sendSz += DTLS_HANDSHAKE_EXTRA + DTLS_RECORD_EXTRA;
  20125. }
  20126. #endif
  20127. if (IsEncryptionOn(ssl, 1)) {
  20128. args->sendSz += MAX_MSG_EXTRA;
  20129. }
  20130. #ifdef HAVE_QSH
  20131. args->encSz += qshSz;
  20132. args->sendSz += qshSz;
  20133. #endif
  20134. /* check for available size */
  20135. if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
  20136. goto exit_scke;
  20137. }
  20138. /* get output buffer */
  20139. args->output = ssl->buffers.outputBuffer.buffer +
  20140. ssl->buffers.outputBuffer.length;
  20141. #ifdef HAVE_QSH
  20142. if (ssl->peerQSHKeyPresent) {
  20143. byte idxSave = idx;
  20144. idx = args->sendSz - qshSz;
  20145. if (QSH_KeyExchangeWrite(ssl, 0) != 0) {
  20146. ERROR_OUT(MEMORY_E, exit_scke);
  20147. }
  20148. /* extension type */
  20149. c16toa(TLSX_QUANTUM_SAFE_HYBRID, args->output + idx);
  20150. idx += OPAQUE16_LEN;
  20151. /* write to output and check amount written */
  20152. if (TLSX_QSHPK_Write(ssl->QSH_secret->list,
  20153. args->output + idx) > qshSz - OPAQUE16_LEN) {
  20154. ERROR_OUT(MEMORY_E, exit_scke);
  20155. }
  20156. idx = idxSave;
  20157. }
  20158. #endif
  20159. AddHeaders(args->output, args->encSz + tlsSz, client_key_exchange, ssl);
  20160. #ifdef HAVE_QSH
  20161. if (ssl->peerQSHKeyPresent) {
  20162. args->encSz -= qshSz;
  20163. }
  20164. #endif
  20165. if (tlsSz) {
  20166. c16toa((word16)args->encSz, &args->output[idx]);
  20167. idx += OPAQUE16_LEN;
  20168. }
  20169. XMEMCPY(args->output + idx, args->encSecret, args->encSz);
  20170. idx += args->encSz;
  20171. if (IsEncryptionOn(ssl, 1)) {
  20172. args->inputSz = idx - RECORD_HEADER_SZ; /* buildmsg adds rechdr */
  20173. args->input = (byte*)XMALLOC(args->inputSz, ssl->heap,
  20174. DYNAMIC_TYPE_IN_BUFFER);
  20175. if (args->input == NULL) {
  20176. ERROR_OUT(MEMORY_E, exit_scke);
  20177. }
  20178. XMEMCPY(args->input, args->output + RECORD_HEADER_SZ,
  20179. args->inputSz);
  20180. }
  20181. /* Advance state and proceed */
  20182. ssl->options.asyncState = TLS_ASYNC_END;
  20183. } /* case TLS_ASYNC_FINALIZE */
  20184. FALL_THROUGH;
  20185. case TLS_ASYNC_END:
  20186. {
  20187. if (IsEncryptionOn(ssl, 1)) {
  20188. ret = BuildMessage(ssl, args->output, args->sendSz,
  20189. args->input, args->inputSz, handshake, 1, 0, 0);
  20190. XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  20191. args->input = NULL; /* make sure its not double free'd on cleanup */
  20192. if (ret >= 0) {
  20193. args->sendSz = ret;
  20194. ret = 0;
  20195. }
  20196. }
  20197. else {
  20198. #ifdef WOLFSSL_DTLS
  20199. if (ssl->options.dtls)
  20200. DtlsSEQIncrement(ssl, CUR_ORDER);
  20201. #endif
  20202. ret = HashOutput(ssl, args->output, args->sendSz, 0);
  20203. }
  20204. if (ret != 0) {
  20205. goto exit_scke;
  20206. }
  20207. #ifdef WOLFSSL_DTLS
  20208. if (IsDtlsNotSctpMode(ssl)) {
  20209. if ((ret = DtlsMsgPoolSave(ssl, args->output, args->sendSz)) != 0) {
  20210. goto exit_scke;
  20211. }
  20212. }
  20213. #endif
  20214. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  20215. if (ssl->hsInfoOn)
  20216. AddPacketName(ssl, "ClientKeyExchange");
  20217. if (ssl->toInfoOn)
  20218. AddPacketInfo(ssl, "ClientKeyExchange", handshake,
  20219. args->output, args->sendSz, WRITE_PROTO, ssl->heap);
  20220. #endif
  20221. ssl->buffers.outputBuffer.length += args->sendSz;
  20222. if (!ssl->options.groupMessages) {
  20223. ret = SendBuffered(ssl);
  20224. }
  20225. if (ret == 0 || ret == WANT_WRITE) {
  20226. int tmpRet = MakeMasterSecret(ssl);
  20227. if (tmpRet != 0) {
  20228. ret = tmpRet; /* save WANT_WRITE unless more serious */
  20229. }
  20230. ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
  20231. }
  20232. break;
  20233. }
  20234. default:
  20235. ret = INPUT_CASE_ERROR;
  20236. } /* switch(ssl->options.asyncState) */
  20237. exit_scke:
  20238. WOLFSSL_LEAVE("SendClientKeyExchange", ret);
  20239. WOLFSSL_END(WC_FUNC_CLIENT_KEY_EXCHANGE_SEND);
  20240. #ifdef WOLFSSL_ASYNC_CRYPT
  20241. /* Handle async operation */
  20242. if (ret == WC_PENDING_E)
  20243. return ret;
  20244. #endif
  20245. /* No further need for PMS */
  20246. if (ssl->arrays->preMasterSecret != NULL) {
  20247. ForceZero(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  20248. }
  20249. ssl->arrays->preMasterSz = 0;
  20250. /* Final cleanup */
  20251. FreeSckeArgs(ssl, args);
  20252. FreeKeyExchange(ssl);
  20253. return ret;
  20254. }
  20255. #endif /* !WOLFSSL_NO_TLS12 */
  20256. #ifndef NO_CERTS
  20257. #ifdef HAVE_PK_CALLBACKS
  20258. int GetPrivateKeySigSize(WOLFSSL* ssl)
  20259. {
  20260. int sigSz = 0;
  20261. if (ssl == NULL)
  20262. return 0;
  20263. switch (ssl->buffers.keyType) {
  20264. #ifndef NO_RSA
  20265. #ifdef WC_RSA_PSS
  20266. case rsa_pss_sa_algo:
  20267. #endif
  20268. case rsa_sa_algo:
  20269. sigSz = ssl->buffers.keySz;
  20270. ssl->hsType = DYNAMIC_TYPE_RSA;
  20271. break;
  20272. #endif
  20273. #ifdef HAVE_ECC
  20274. case ecc_dsa_sa_algo:
  20275. sigSz = wc_ecc_sig_size_calc(ssl->buffers.keySz);
  20276. ssl->hsType = DYNAMIC_TYPE_ECC;
  20277. break;
  20278. #endif
  20279. #ifdef HAVE_ED25519
  20280. case ed25519_sa_algo:
  20281. sigSz = ED25519_SIG_SIZE; /* fixed known value */
  20282. ssl->hsType = DYNAMIC_TYPE_ED25519;
  20283. break;
  20284. #endif
  20285. #ifdef HAVE_ED448
  20286. case ed448_sa_algo:
  20287. sigSz = ED448_SIG_SIZE; /* fixed known value */
  20288. ssl->hsType = DYNAMIC_TYPE_ED448;
  20289. break;
  20290. #endif
  20291. default:
  20292. break;
  20293. }
  20294. return sigSz;
  20295. }
  20296. #endif /* HAVE_PK_CALLBACKS */
  20297. #ifndef WOLFSSL_NO_TLS12
  20298. #ifndef WOLFSSL_NO_CLIENT_AUTH
  20299. typedef struct ScvArgs {
  20300. byte* output; /* not allocated */
  20301. #ifndef NO_RSA
  20302. byte* verifySig;
  20303. #endif
  20304. byte* verify; /* not allocated */
  20305. byte* input;
  20306. word32 idx;
  20307. word32 extraSz;
  20308. word32 sigSz;
  20309. int sendSz;
  20310. int inputSz;
  20311. word16 length;
  20312. byte sigAlgo;
  20313. } ScvArgs;
  20314. static void FreeScvArgs(WOLFSSL* ssl, void* pArgs)
  20315. {
  20316. ScvArgs* args = (ScvArgs*)pArgs;
  20317. (void)ssl;
  20318. #ifndef NO_RSA
  20319. if (args->verifySig) {
  20320. XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  20321. args->verifySig = NULL;
  20322. }
  20323. #endif
  20324. if (args->input) {
  20325. XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  20326. args->input = NULL;
  20327. }
  20328. }
  20329. /* handle generation of certificate_verify (15) */
  20330. int SendCertificateVerify(WOLFSSL* ssl)
  20331. {
  20332. int ret = 0;
  20333. #ifdef WOLFSSL_ASYNC_CRYPT
  20334. ScvArgs* args = (ScvArgs*)ssl->async.args;
  20335. typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
  20336. (void)sizeof(args_test);
  20337. #else
  20338. ScvArgs args[1];
  20339. #endif
  20340. WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_SEND);
  20341. WOLFSSL_ENTER("SendCertificateVerify");
  20342. #ifdef WOLFSSL_ASYNC_CRYPT
  20343. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  20344. if (ret != WC_NOT_PENDING_E) {
  20345. /* Check for error */
  20346. if (ret < 0)
  20347. goto exit_scv;
  20348. }
  20349. else
  20350. #endif
  20351. {
  20352. /* Reset state */
  20353. ret = 0;
  20354. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  20355. XMEMSET(args, 0, sizeof(ScvArgs));
  20356. #ifdef WOLFSSL_ASYNC_CRYPT
  20357. ssl->async.freeArgs = FreeScvArgs;
  20358. #endif
  20359. }
  20360. switch(ssl->options.asyncState)
  20361. {
  20362. case TLS_ASYNC_BEGIN:
  20363. {
  20364. if (ssl->options.sendVerify == SEND_BLANK_CERT) {
  20365. return 0; /* sent blank cert, can't verify */
  20366. }
  20367. args->sendSz = MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA;
  20368. if (IsEncryptionOn(ssl, 1)) {
  20369. args->sendSz += MAX_MSG_EXTRA;
  20370. }
  20371. /* check for available size */
  20372. if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
  20373. goto exit_scv;
  20374. }
  20375. /* get output buffer */
  20376. args->output = ssl->buffers.outputBuffer.buffer +
  20377. ssl->buffers.outputBuffer.length;
  20378. /* Advance state and proceed */
  20379. ssl->options.asyncState = TLS_ASYNC_BUILD;
  20380. } /* case TLS_ASYNC_BEGIN */
  20381. FALL_THROUGH;
  20382. case TLS_ASYNC_BUILD:
  20383. {
  20384. ret = BuildCertHashes(ssl, &ssl->hsHashes->certHashes);
  20385. if (ret != 0) {
  20386. goto exit_scv;
  20387. }
  20388. if (ssl->buffers.key == NULL) {
  20389. #ifdef HAVE_PK_CALLBACKS
  20390. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
  20391. args->length = GetPrivateKeySigSize(ssl);
  20392. else
  20393. #endif
  20394. ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
  20395. }
  20396. else {
  20397. /* Decode private key. */
  20398. ret = DecodePrivateKey(ssl, &args->length);
  20399. if (ret != 0) {
  20400. goto exit_scv;
  20401. }
  20402. }
  20403. if (args->length == 0) {
  20404. ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
  20405. }
  20406. /* idx is used to track verify pointer offset to output */
  20407. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  20408. args->verify = &args->output[RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ];
  20409. args->extraSz = 0; /* tls 1.2 hash/sig */
  20410. /* build encoded signature buffer */
  20411. ssl->buffers.sig.length = MAX_ENCODED_SIG_SZ;
  20412. ssl->buffers.sig.buffer = (byte*)XMALLOC(ssl->buffers.sig.length,
  20413. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  20414. if (ssl->buffers.sig.buffer == NULL) {
  20415. ERROR_OUT(MEMORY_E, exit_scv);
  20416. }
  20417. #ifdef WOLFSSL_DTLS
  20418. if (ssl->options.dtls) {
  20419. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  20420. args->verify += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  20421. }
  20422. #endif
  20423. #ifndef NO_OLD_TLS
  20424. #ifndef NO_SHA
  20425. /* old tls default */
  20426. SetDigest(ssl, sha_mac);
  20427. #endif
  20428. #else
  20429. #ifndef NO_SHA256
  20430. /* new tls default */
  20431. SetDigest(ssl, sha256_mac);
  20432. #endif
  20433. #endif /* !NO_OLD_TLS */
  20434. if (ssl->hsType == DYNAMIC_TYPE_RSA) {
  20435. #ifdef WC_RSA_PSS
  20436. if (IsAtLeastTLSv1_2(ssl) &&
  20437. (ssl->pssAlgo & (1 << ssl->suites->hashAlgo))) {
  20438. args->sigAlgo = rsa_pss_sa_algo;
  20439. }
  20440. else
  20441. #endif
  20442. args->sigAlgo = rsa_sa_algo;
  20443. }
  20444. else if (ssl->hsType == DYNAMIC_TYPE_ECC)
  20445. args->sigAlgo = ecc_dsa_sa_algo;
  20446. else if (ssl->hsType == DYNAMIC_TYPE_ED25519)
  20447. args->sigAlgo = ed25519_sa_algo;
  20448. else if (ssl->hsType == DYNAMIC_TYPE_ED448)
  20449. args->sigAlgo = ed448_sa_algo;
  20450. if (IsAtLeastTLSv1_2(ssl)) {
  20451. EncodeSigAlg(ssl->suites->hashAlgo, args->sigAlgo,
  20452. args->verify);
  20453. args->extraSz = HASH_SIG_SIZE;
  20454. SetDigest(ssl, ssl->suites->hashAlgo);
  20455. }
  20456. #ifndef NO_OLD_TLS
  20457. else {
  20458. /* if old TLS load MD5 and SHA hash as value to sign */
  20459. XMEMCPY(ssl->buffers.sig.buffer,
  20460. (byte*)ssl->hsHashes->certHashes.md5, FINISHED_SZ);
  20461. }
  20462. #endif
  20463. #ifndef NO_RSA
  20464. if (args->sigAlgo == rsa_sa_algo) {
  20465. ssl->buffers.sig.length = FINISHED_SZ;
  20466. args->sigSz = ENCRYPT_LEN;
  20467. if (IsAtLeastTLSv1_2(ssl)) {
  20468. ssl->buffers.sig.length = wc_EncodeSignature(
  20469. ssl->buffers.sig.buffer, ssl->buffers.digest.buffer,
  20470. ssl->buffers.digest.length,
  20471. TypeHash(ssl->suites->hashAlgo));
  20472. }
  20473. /* prepend hdr */
  20474. c16toa(args->length, args->verify + args->extraSz);
  20475. }
  20476. #ifdef WC_RSA_PSS
  20477. else if (args->sigAlgo == rsa_pss_sa_algo) {
  20478. XMEMCPY(ssl->buffers.sig.buffer, ssl->buffers.digest.buffer,
  20479. ssl->buffers.digest.length);
  20480. ssl->buffers.sig.length = ssl->buffers.digest.length;
  20481. args->sigSz = ENCRYPT_LEN;
  20482. /* prepend hdr */
  20483. c16toa(args->length, args->verify + args->extraSz);
  20484. }
  20485. #endif
  20486. #endif /* !NO_RSA */
  20487. #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
  20488. if (args->sigAlgo == ed25519_sa_algo) {
  20489. ret = Ed25519CheckPubKey(ssl);
  20490. if (ret != 0)
  20491. goto exit_scv;
  20492. }
  20493. #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
  20494. #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
  20495. if (args->sigAlgo == ed448_sa_algo) {
  20496. ret = Ed448CheckPubKey(ssl);
  20497. if (ret != 0)
  20498. goto exit_scv;
  20499. }
  20500. #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
  20501. /* Advance state and proceed */
  20502. ssl->options.asyncState = TLS_ASYNC_DO;
  20503. } /* case TLS_ASYNC_BUILD */
  20504. FALL_THROUGH;
  20505. case TLS_ASYNC_DO:
  20506. {
  20507. #ifdef HAVE_ECC
  20508. if (ssl->hsType == DYNAMIC_TYPE_ECC) {
  20509. ecc_key* key = (ecc_key*)ssl->hsKey;
  20510. ret = EccSign(ssl,
  20511. ssl->buffers.digest.buffer, ssl->buffers.digest.length,
  20512. ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
  20513. key,
  20514. #ifdef HAVE_PK_CALLBACKS
  20515. ssl->buffers.key
  20516. #else
  20517. NULL
  20518. #endif
  20519. );
  20520. }
  20521. #endif /* HAVE_ECC */
  20522. #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
  20523. if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
  20524. ed25519_key* key = (ed25519_key*)ssl->hsKey;
  20525. ret = Ed25519Sign(ssl,
  20526. ssl->hsHashes->messages, ssl->hsHashes->length,
  20527. ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
  20528. key,
  20529. #ifdef HAVE_PK_CALLBACKS
  20530. ssl->buffers.key
  20531. #else
  20532. NULL
  20533. #endif
  20534. );
  20535. }
  20536. #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
  20537. #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
  20538. if (ssl->hsType == DYNAMIC_TYPE_ED448) {
  20539. ed448_key* key = (ed448_key*)ssl->hsKey;
  20540. ret = Ed448Sign(ssl,
  20541. ssl->hsHashes->messages, ssl->hsHashes->length,
  20542. ssl->buffers.sig.buffer, (word32*)&ssl->buffers.sig.length,
  20543. key,
  20544. #ifdef HAVE_PK_CALLBACKS
  20545. ssl->buffers.key
  20546. #else
  20547. NULL
  20548. #endif
  20549. );
  20550. }
  20551. #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
  20552. #ifndef NO_RSA
  20553. if (ssl->hsType == DYNAMIC_TYPE_RSA) {
  20554. RsaKey* key = (RsaKey*)ssl->hsKey;
  20555. /* restore verify pointer */
  20556. args->verify = &args->output[args->idx];
  20557. ret = RsaSign(ssl,
  20558. ssl->buffers.sig.buffer, ssl->buffers.sig.length,
  20559. args->verify + args->extraSz + VERIFY_HEADER, &args->sigSz,
  20560. args->sigAlgo, ssl->suites->hashAlgo, key,
  20561. ssl->buffers.key
  20562. );
  20563. }
  20564. #endif /* !NO_RSA */
  20565. /* Check for error */
  20566. if (ret != 0) {
  20567. goto exit_scv;
  20568. }
  20569. /* Advance state and proceed */
  20570. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  20571. } /* case TLS_ASYNC_DO */
  20572. FALL_THROUGH;
  20573. case TLS_ASYNC_VERIFY:
  20574. {
  20575. /* restore verify pointer */
  20576. args->verify = &args->output[args->idx];
  20577. switch (ssl->hsType) {
  20578. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
  20579. #ifdef HAVE_ECC
  20580. case DYNAMIC_TYPE_ECC:
  20581. #endif
  20582. #ifdef HAVE_ED25519
  20583. case DYNAMIC_TYPE_ED25519:
  20584. #endif
  20585. #ifdef HAVE_ED448
  20586. case DYNAMIC_TYPE_ED448:
  20587. #endif
  20588. args->length = (word16)ssl->buffers.sig.length;
  20589. /* prepend hdr */
  20590. c16toa(args->length, args->verify + args->extraSz);
  20591. XMEMCPY(args->verify + args->extraSz + VERIFY_HEADER,
  20592. ssl->buffers.sig.buffer, ssl->buffers.sig.length);
  20593. break;
  20594. #endif
  20595. #ifndef NO_RSA
  20596. case DYNAMIC_TYPE_RSA:
  20597. {
  20598. RsaKey* key = (RsaKey*)ssl->hsKey;
  20599. if (args->verifySig == NULL) {
  20600. args->verifySig = (byte*)XMALLOC(args->sigSz, ssl->heap,
  20601. DYNAMIC_TYPE_SIGNATURE);
  20602. if (args->verifySig == NULL) {
  20603. ERROR_OUT(MEMORY_E, exit_scv);
  20604. }
  20605. XMEMCPY(args->verifySig, args->verify + args->extraSz +
  20606. VERIFY_HEADER, args->sigSz);
  20607. }
  20608. /* check for signature faults */
  20609. ret = VerifyRsaSign(ssl,
  20610. args->verifySig, args->sigSz,
  20611. ssl->buffers.sig.buffer, ssl->buffers.sig.length,
  20612. args->sigAlgo, ssl->suites->hashAlgo, key,
  20613. ssl->buffers.key
  20614. );
  20615. break;
  20616. }
  20617. #endif /* !NO_RSA */
  20618. default:
  20619. break;
  20620. }
  20621. /* Check for error */
  20622. if (ret != 0) {
  20623. goto exit_scv;
  20624. }
  20625. /* Advance state and proceed */
  20626. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  20627. } /* case TLS_ASYNC_VERIFY */
  20628. FALL_THROUGH;
  20629. case TLS_ASYNC_FINALIZE:
  20630. {
  20631. if (args->output == NULL) {
  20632. ERROR_OUT(BUFFER_ERROR, exit_scv);
  20633. }
  20634. AddHeaders(args->output, (word32)args->length + args->extraSz +
  20635. VERIFY_HEADER, certificate_verify, ssl);
  20636. args->sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
  20637. (word32)args->length + args->extraSz + VERIFY_HEADER;
  20638. #ifdef WOLFSSL_DTLS
  20639. if (ssl->options.dtls) {
  20640. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  20641. }
  20642. #endif
  20643. if (IsEncryptionOn(ssl, 1)) {
  20644. args->inputSz = args->sendSz - RECORD_HEADER_SZ;
  20645. /* build msg adds rec hdr */
  20646. args->input = (byte*)XMALLOC(args->inputSz, ssl->heap,
  20647. DYNAMIC_TYPE_IN_BUFFER);
  20648. if (args->input == NULL) {
  20649. ERROR_OUT(MEMORY_E, exit_scv);
  20650. }
  20651. XMEMCPY(args->input, args->output + RECORD_HEADER_SZ,
  20652. args->inputSz);
  20653. }
  20654. /* Advance state and proceed */
  20655. ssl->options.asyncState = TLS_ASYNC_END;
  20656. } /* case TLS_ASYNC_FINALIZE */
  20657. FALL_THROUGH;
  20658. case TLS_ASYNC_END:
  20659. {
  20660. if (IsEncryptionOn(ssl, 1)) {
  20661. ret = BuildMessage(ssl, args->output,
  20662. MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA,
  20663. args->input, args->inputSz, handshake,
  20664. 1, 0, 1);
  20665. #ifdef WOLFSSL_ASYNC_CRYPT
  20666. if (ret == WC_PENDING_E)
  20667. goto exit_scv;
  20668. #endif
  20669. XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  20670. args->input = NULL; /* make sure its not double free'd on cleanup */
  20671. if (ret >= 0) {
  20672. args->sendSz = ret;
  20673. ret = 0;
  20674. }
  20675. }
  20676. else {
  20677. #ifdef WOLFSSL_DTLS
  20678. if (ssl->options.dtls)
  20679. DtlsSEQIncrement(ssl, CUR_ORDER);
  20680. #endif
  20681. ret = HashOutput(ssl, args->output, args->sendSz, 0);
  20682. }
  20683. if (ret != 0) {
  20684. goto exit_scv;
  20685. }
  20686. #ifdef WOLFSSL_DTLS
  20687. if (IsDtlsNotSctpMode(ssl)) {
  20688. ret = DtlsMsgPoolSave(ssl, args->output, args->sendSz);
  20689. }
  20690. #endif
  20691. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  20692. if (ssl->hsInfoOn)
  20693. AddPacketName(ssl, "CertificateVerify");
  20694. if (ssl->toInfoOn)
  20695. AddPacketInfo(ssl, "CertificateVerify", handshake,
  20696. args->output, args->sendSz, WRITE_PROTO, ssl->heap);
  20697. #endif
  20698. ssl->buffers.outputBuffer.length += args->sendSz;
  20699. if (!ssl->options.groupMessages) {
  20700. ret = SendBuffered(ssl);
  20701. }
  20702. break;
  20703. }
  20704. default:
  20705. ret = INPUT_CASE_ERROR;
  20706. } /* switch(ssl->options.asyncState) */
  20707. exit_scv:
  20708. WOLFSSL_LEAVE("SendCertificateVerify", ret);
  20709. WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_SEND);
  20710. #ifdef WOLFSSL_ASYNC_CRYPT
  20711. /* Handle async operation */
  20712. if (ret == WC_PENDING_E) {
  20713. return ret;
  20714. }
  20715. #endif /* WOLFSSL_ASYNC_CRYPT */
  20716. /* Digest is not allocated, so do this to prevent free */
  20717. ssl->buffers.digest.buffer = NULL;
  20718. ssl->buffers.digest.length = 0;
  20719. /* Final cleanup */
  20720. FreeScvArgs(ssl, args);
  20721. FreeKeyExchange(ssl);
  20722. return ret;
  20723. }
  20724. #endif /* WOLFSSL_NO_CLIENT_AUTH */
  20725. #endif /* WOLFSSL_NO_TLS12 */
  20726. #endif /* NO_CERTS */
  20727. #ifdef HAVE_SESSION_TICKET
  20728. int SetTicket(WOLFSSL* ssl, const byte* ticket, word32 length)
  20729. {
  20730. /* Free old dynamic ticket if we already had one */
  20731. if (ssl->session.isDynamic) {
  20732. XFREE(ssl->session.ticket, ssl->heap, DYNAMIC_TYPE_SESSION_TICK);
  20733. ssl->session.ticket = ssl->session.staticTicket;
  20734. ssl->session.isDynamic = 0;
  20735. }
  20736. if (length > sizeof(ssl->session.staticTicket)) {
  20737. byte* sessionTicket =
  20738. (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_SESSION_TICK);
  20739. if (sessionTicket == NULL)
  20740. return MEMORY_E;
  20741. ssl->session.ticket = sessionTicket;
  20742. ssl->session.isDynamic = 1;
  20743. }
  20744. ssl->session.ticketLen = (word16)length;
  20745. if (length > 0) {
  20746. XMEMCPY(ssl->session.ticket, ticket, length);
  20747. if (ssl->session_ticket_cb != NULL) {
  20748. ssl->session_ticket_cb(ssl,
  20749. ssl->session.ticket, ssl->session.ticketLen,
  20750. ssl->session_ticket_ctx);
  20751. }
  20752. /* Create a fake sessionID based on the ticket, this will
  20753. * supersede the existing session cache info. */
  20754. ssl->options.haveSessionId = 1;
  20755. #ifdef WOLFSSL_TLS13
  20756. if (ssl->options.tls1_3) {
  20757. XMEMCPY(ssl->session.sessionID,
  20758. ssl->session.ticket + length - ID_LEN, ID_LEN);
  20759. }
  20760. else
  20761. #endif
  20762. XMEMCPY(ssl->arrays->sessionID,
  20763. ssl->session.ticket + length - ID_LEN, ID_LEN);
  20764. }
  20765. return 0;
  20766. }
  20767. #ifndef WOLFSSL_NO_TLS12
  20768. /* handle processing of session_ticket (4) */
  20769. static int DoSessionTicket(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  20770. word32 size)
  20771. {
  20772. word32 begin = *inOutIdx;
  20773. word32 lifetime;
  20774. word16 length;
  20775. int ret;
  20776. if (ssl->expect_session_ticket == 0) {
  20777. WOLFSSL_MSG("Unexpected session ticket");
  20778. return SESSION_TICKET_EXPECT_E;
  20779. }
  20780. if (OPAQUE32_LEN > size)
  20781. return BUFFER_ERROR;
  20782. ato32(input + *inOutIdx, &lifetime);
  20783. *inOutIdx += OPAQUE32_LEN;
  20784. if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
  20785. return BUFFER_ERROR;
  20786. ato16(input + *inOutIdx, &length);
  20787. *inOutIdx += OPAQUE16_LEN;
  20788. if ((*inOutIdx - begin) + length > size)
  20789. return BUFFER_ERROR;
  20790. if ((ret = SetTicket(ssl, input + *inOutIdx, length)) != 0)
  20791. return ret;
  20792. *inOutIdx += length;
  20793. if (length > 0) {
  20794. ssl->timeout = lifetime;
  20795. #ifndef NO_SESSION_CACHE
  20796. AddSession(ssl);
  20797. #endif
  20798. }
  20799. if (IsEncryptionOn(ssl, 0)) {
  20800. *inOutIdx += ssl->keys.padSz;
  20801. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  20802. if (ssl->options.startedETMRead)
  20803. *inOutIdx += MacSize(ssl);
  20804. #endif
  20805. }
  20806. ssl->expect_session_ticket = 0;
  20807. return 0;
  20808. }
  20809. #endif /* !WOLFSSL_NO_TLS12 */
  20810. #endif /* HAVE_SESSION_TICKET */
  20811. #endif /* NO_WOLFSSL_CLIENT */
  20812. #ifdef HAVE_ECC
  20813. /* returns the WOLFSSL_* version of the curve from the OID sum */
  20814. word16 GetCurveByOID(int oidSum) {
  20815. switch(oidSum) {
  20816. #if defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)
  20817. #ifndef NO_ECC_SECP
  20818. case ECC_SECP160R1_OID:
  20819. return WOLFSSL_ECC_SECP160R1;
  20820. #endif /* !NO_ECC_SECP */
  20821. #ifdef HAVE_ECC_SECPR2
  20822. case ECC_SECP160R2_OID:
  20823. return WOLFSSL_ECC_SECP160R2;
  20824. #endif /* HAVE_ECC_SECPR2 */
  20825. #ifdef HAVE_ECC_KOBLITZ
  20826. case ECC_SECP160K1_OID:
  20827. return WOLFSSL_ECC_SECP160K1;
  20828. #endif /* HAVE_ECC_KOBLITZ */
  20829. #endif
  20830. #if defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)
  20831. #ifndef NO_ECC_SECP
  20832. case ECC_SECP192R1_OID:
  20833. return WOLFSSL_ECC_SECP192R1;
  20834. #endif /* !NO_ECC_SECP */
  20835. #ifdef HAVE_ECC_KOBLITZ
  20836. case ECC_SECP192K1_OID:
  20837. return WOLFSSL_ECC_SECP192K1;
  20838. #endif /* HAVE_ECC_KOBLITZ */
  20839. #endif
  20840. #if defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)
  20841. #ifndef NO_ECC_SECP
  20842. case ECC_SECP224R1_OID:
  20843. return WOLFSSL_ECC_SECP224R1;
  20844. #endif /* !NO_ECC_SECP */
  20845. #ifdef HAVE_ECC_KOBLITZ
  20846. case ECC_SECP224K1_OID:
  20847. return WOLFSSL_ECC_SECP224K1;
  20848. #endif /* HAVE_ECC_KOBLITZ */
  20849. #endif
  20850. #if !defined(NO_ECC256) || defined(HAVE_ALL_CURVES)
  20851. #ifndef NO_ECC_SECP
  20852. case ECC_SECP256R1_OID:
  20853. return WOLFSSL_ECC_SECP256R1;
  20854. #endif /* !NO_ECC_SECP */
  20855. #ifdef HAVE_ECC_KOBLITZ
  20856. case ECC_SECP256K1_OID:
  20857. return WOLFSSL_ECC_SECP256K1;
  20858. #endif /* HAVE_ECC_KOBLITZ */
  20859. #ifdef HAVE_ECC_BRAINPOOL
  20860. case ECC_BRAINPOOLP256R1_OID:
  20861. return WOLFSSL_ECC_BRAINPOOLP256R1;
  20862. #endif /* HAVE_ECC_BRAINPOOL */
  20863. #endif
  20864. #if defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)
  20865. #ifndef NO_ECC_SECP
  20866. case ECC_SECP384R1_OID:
  20867. return WOLFSSL_ECC_SECP384R1;
  20868. #endif /* !NO_ECC_SECP */
  20869. #ifdef HAVE_ECC_BRAINPOOL
  20870. case ECC_BRAINPOOLP384R1_OID:
  20871. return WOLFSSL_ECC_BRAINPOOLP384R1;
  20872. #endif /* HAVE_ECC_BRAINPOOL */
  20873. #endif
  20874. #if defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)
  20875. #ifdef HAVE_ECC_BRAINPOOL
  20876. case ECC_BRAINPOOLP512R1_OID:
  20877. return WOLFSSL_ECC_BRAINPOOLP512R1;
  20878. #endif /* HAVE_ECC_BRAINPOOL */
  20879. #endif
  20880. #if defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)
  20881. #ifndef NO_ECC_SECP
  20882. case ECC_SECP521R1_OID:
  20883. return WOLFSSL_ECC_SECP521R1;
  20884. #endif /* !NO_ECC_SECP */
  20885. #endif
  20886. default:
  20887. WOLFSSL_MSG("Curve OID not compiled in or implemented");
  20888. return 0;
  20889. }
  20890. }
  20891. #endif /* HAVE_ECC */
  20892. #ifndef NO_WOLFSSL_SERVER
  20893. #ifndef WOLFSSL_NO_TLS12
  20894. /* handle generation of server_hello (2) */
  20895. int SendServerHello(WOLFSSL* ssl)
  20896. {
  20897. int ret;
  20898. byte *output;
  20899. word16 length;
  20900. word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  20901. int sendSz;
  20902. byte sessIdSz = ID_LEN;
  20903. byte echoId = 0; /* ticket echo id flag */
  20904. byte cacheOff = 0; /* session cache off flag */
  20905. WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND);
  20906. WOLFSSL_ENTER("SendServerHello");
  20907. length = VERSION_SZ + RAN_LEN
  20908. + ID_LEN + ENUM_LEN
  20909. + SUITE_LEN
  20910. + ENUM_LEN;
  20911. #ifdef HAVE_TLS_EXTENSIONS
  20912. ret = TLSX_GetResponseSize(ssl, server_hello, &length);
  20913. if (ret != 0)
  20914. return ret;
  20915. #ifdef HAVE_SESSION_TICKET
  20916. if (ssl->options.useTicket) {
  20917. /* echo session id sz can be 0,32 or bogus len in between */
  20918. sessIdSz = ssl->arrays->sessionIDSz;
  20919. if (sessIdSz > ID_LEN) {
  20920. WOLFSSL_MSG("Bad bogus session id len");
  20921. return BUFFER_ERROR;
  20922. }
  20923. if (!IsAtLeastTLSv1_3(ssl->version))
  20924. length -= (ID_LEN - sessIdSz); /* adjust ID_LEN assumption */
  20925. echoId = 1;
  20926. }
  20927. #endif /* HAVE_SESSION_TICKET */
  20928. #else
  20929. if (ssl->options.haveEMS) {
  20930. length += HELLO_EXT_SZ_SZ + HELLO_EXT_SZ;
  20931. }
  20932. #endif
  20933. /* is the session cache off at build or runtime */
  20934. #ifdef NO_SESSION_CACHE
  20935. cacheOff = 1;
  20936. #else
  20937. if (ssl->options.sessionCacheOff == 1) {
  20938. cacheOff = 1;
  20939. }
  20940. #endif
  20941. /* if no session cache don't send a session ID unless we're echoing
  20942. * an ID as part of session tickets */
  20943. if (echoId == 0 && cacheOff == 1) {
  20944. length -= ID_LEN; /* adjust ID_LEN assumption */
  20945. sessIdSz = 0;
  20946. }
  20947. sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  20948. #ifdef WOLFSSL_DTLS
  20949. if (ssl->options.dtls) {
  20950. /* Server Hello should use the same sequence number as the
  20951. * Client Hello. */
  20952. ssl->keys.dtls_sequence_number_hi = ssl->keys.curSeq_hi;
  20953. ssl->keys.dtls_sequence_number_lo = ssl->keys.curSeq_lo;
  20954. idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  20955. sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  20956. }
  20957. #endif /* WOLFSSL_DTLS */
  20958. if (IsEncryptionOn(ssl, 1))
  20959. sendSz += MAX_MSG_EXTRA;
  20960. /* check for available size */
  20961. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  20962. return ret;
  20963. /* get output buffer */
  20964. output = ssl->buffers.outputBuffer.buffer +
  20965. ssl->buffers.outputBuffer.length;
  20966. AddHeaders(output, length, server_hello, ssl);
  20967. /* now write to output */
  20968. /* first version */
  20969. output[idx++] = (byte)ssl->version.major;
  20970. output[idx++] = (byte)ssl->version.minor;
  20971. /* then random and session id */
  20972. if (!ssl->options.resuming) {
  20973. /* generate random part and session id */
  20974. ret = wc_RNG_GenerateBlock(ssl->rng, output + idx,
  20975. RAN_LEN + sizeof(sessIdSz) + sessIdSz);
  20976. if (ret != 0)
  20977. return ret;
  20978. #ifdef WOLFSSL_TLS13
  20979. if (TLSv1_3_Capable(ssl)) {
  20980. /* TLS v1.3 capable server downgraded. */
  20981. XMEMCPY(output + idx + RAN_LEN - (TLS13_DOWNGRADE_SZ + 1),
  20982. tls13Downgrade, TLS13_DOWNGRADE_SZ);
  20983. output[idx + RAN_LEN - 1] = (byte)IsAtLeastTLSv1_2(ssl);
  20984. }
  20985. else
  20986. #endif
  20987. if (ssl->ctx->method->version.major == SSLv3_MAJOR &&
  20988. ssl->ctx->method->version.minor == TLSv1_2_MINOR &&
  20989. !IsAtLeastTLSv1_2(ssl)) {
  20990. /* TLS v1.2 capable server downgraded. */
  20991. XMEMCPY(output + idx + RAN_LEN - (TLS13_DOWNGRADE_SZ + 1),
  20992. tls13Downgrade, TLS13_DOWNGRADE_SZ);
  20993. output[idx + RAN_LEN - 1] = 0;
  20994. }
  20995. /* store info in SSL for later */
  20996. XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
  20997. idx += RAN_LEN;
  20998. output[idx++] = sessIdSz;
  20999. XMEMCPY(ssl->arrays->sessionID, output + idx, sessIdSz);
  21000. ssl->arrays->sessionIDSz = sessIdSz;
  21001. }
  21002. else {
  21003. /* If resuming, use info from SSL */
  21004. XMEMCPY(output + idx, ssl->arrays->serverRandom, RAN_LEN);
  21005. idx += RAN_LEN;
  21006. output[idx++] = sessIdSz;
  21007. XMEMCPY(output + idx, ssl->arrays->sessionID, sessIdSz);
  21008. }
  21009. idx += sessIdSz;
  21010. #ifdef SHOW_SECRETS
  21011. {
  21012. int j;
  21013. printf("server random: ");
  21014. for (j = 0; j < RAN_LEN; j++)
  21015. printf("%02x", ssl->arrays->serverRandom[j]);
  21016. printf("\n");
  21017. }
  21018. #endif
  21019. /* then cipher suite */
  21020. output[idx++] = ssl->options.cipherSuite0;
  21021. output[idx++] = ssl->options.cipherSuite;
  21022. /* then compression */
  21023. if (ssl->options.usingCompression)
  21024. output[idx++] = ZLIB_COMPRESSION;
  21025. else
  21026. output[idx++] = NO_COMPRESSION;
  21027. /* last, extensions */
  21028. #ifdef HAVE_TLS_EXTENSIONS
  21029. {
  21030. word16 offset = 0;
  21031. ret = TLSX_WriteResponse(ssl, output + idx, server_hello, &offset);
  21032. if (ret != 0)
  21033. return ret;
  21034. idx += offset;
  21035. }
  21036. #else
  21037. #ifdef HAVE_EXTENDED_MASTER
  21038. if (ssl->options.haveEMS) {
  21039. c16toa(HELLO_EXT_SZ, output + idx);
  21040. idx += HELLO_EXT_SZ_SZ;
  21041. c16toa(HELLO_EXT_EXTMS, output + idx);
  21042. idx += HELLO_EXT_TYPE_SZ;
  21043. c16toa(0, output + idx);
  21044. /*idx += HELLO_EXT_SZ_SZ;*/
  21045. /* idx is not used after this point. uncomment the line above
  21046. * if adding any more extensions in the future. */
  21047. }
  21048. #endif
  21049. #endif
  21050. if (IsEncryptionOn(ssl, 1)) {
  21051. byte* input;
  21052. int inputSz = idx - RECORD_HEADER_SZ; /* build msg adds rec hdr */
  21053. input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  21054. if (input == NULL)
  21055. return MEMORY_E;
  21056. XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
  21057. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  21058. handshake, 1, 0, 0);
  21059. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  21060. if (sendSz < 0)
  21061. return sendSz;
  21062. } else {
  21063. #ifdef WOLFSSL_DTLS
  21064. if (ssl->options.dtls)
  21065. DtlsSEQIncrement(ssl, CUR_ORDER);
  21066. #endif
  21067. ret = HashOutput(ssl, output, sendSz, 0);
  21068. if (ret != 0)
  21069. return ret;
  21070. }
  21071. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  21072. if (ssl->hsInfoOn)
  21073. AddPacketName(ssl, "ServerHello");
  21074. if (ssl->toInfoOn)
  21075. AddPacketInfo(ssl, "ServerHello", handshake, output, sendSz,
  21076. WRITE_PROTO, ssl->heap);
  21077. #endif
  21078. ssl->options.serverState = SERVER_HELLO_COMPLETE;
  21079. ssl->buffers.outputBuffer.length += sendSz;
  21080. #ifdef WOLFSSL_DTLS
  21081. if (IsDtlsNotSctpMode(ssl)) {
  21082. if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
  21083. return ret;
  21084. }
  21085. #endif
  21086. if (ssl->options.groupMessages)
  21087. ret = 0;
  21088. else
  21089. ret = SendBuffered(ssl);
  21090. WOLFSSL_LEAVE("SendServerHello", ret);
  21091. WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
  21092. return ret;
  21093. }
  21094. #if defined(HAVE_ECC)
  21095. static byte SetCurveId(ecc_key* key)
  21096. {
  21097. if (key == NULL || key->dp == NULL) {
  21098. WOLFSSL_MSG("SetCurveId: Invalid key!");
  21099. return 0;
  21100. }
  21101. return (byte)GetCurveByOID(key->dp->oidSum);
  21102. }
  21103. #endif /* HAVE_ECC */
  21104. typedef struct SskeArgs {
  21105. byte* output; /* not allocated */
  21106. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  21107. (!defined(NO_DH) && !defined(NO_RSA))
  21108. byte* sigDataBuf;
  21109. #endif
  21110. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  21111. byte* exportBuf;
  21112. #endif
  21113. #ifndef NO_RSA
  21114. byte* verifySig;
  21115. #endif
  21116. byte* input;
  21117. word32 idx;
  21118. word32 tmpSigSz;
  21119. word32 length;
  21120. word32 sigSz;
  21121. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  21122. (!defined(NO_DH) && !defined(NO_RSA))
  21123. word32 sigDataSz;
  21124. #endif
  21125. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  21126. word32 exportSz;
  21127. #endif
  21128. #ifdef HAVE_QSH
  21129. word32 qshSz;
  21130. #endif
  21131. int sendSz;
  21132. int inputSz;
  21133. } SskeArgs;
  21134. static void FreeSskeArgs(WOLFSSL* ssl, void* pArgs)
  21135. {
  21136. SskeArgs* args = (SskeArgs*)pArgs;
  21137. (void)ssl;
  21138. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  21139. if (args->exportBuf) {
  21140. XFREE(args->exportBuf, ssl->heap, DYNAMIC_TYPE_DER);
  21141. args->exportBuf = NULL;
  21142. }
  21143. #endif
  21144. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  21145. (!defined(NO_DH) && !defined(NO_RSA))
  21146. if (args->sigDataBuf) {
  21147. XFREE(args->sigDataBuf, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  21148. args->sigDataBuf = NULL;
  21149. }
  21150. #endif
  21151. #ifndef NO_RSA
  21152. if (args->verifySig) {
  21153. XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  21154. args->verifySig = NULL;
  21155. }
  21156. #endif
  21157. (void)args;
  21158. }
  21159. /* handle generation of server_key_exchange (12) */
  21160. int SendServerKeyExchange(WOLFSSL* ssl)
  21161. {
  21162. int ret;
  21163. #ifdef WOLFSSL_ASYNC_CRYPT
  21164. SskeArgs* args = (SskeArgs*)ssl->async.args;
  21165. typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
  21166. (void)sizeof(args_test);
  21167. #else
  21168. SskeArgs args[1];
  21169. #endif
  21170. WOLFSSL_START(WC_FUNC_SERVER_KEY_EXCHANGE_SEND);
  21171. WOLFSSL_ENTER("SendServerKeyExchange");
  21172. #ifdef WOLFSSL_ASYNC_CRYPT
  21173. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  21174. if (ret != WC_NOT_PENDING_E) {
  21175. /* Check for error */
  21176. if (ret < 0)
  21177. goto exit_sske;
  21178. }
  21179. else
  21180. #endif
  21181. {
  21182. /* Reset state */
  21183. ret = 0;
  21184. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  21185. XMEMSET(args, 0, sizeof(SskeArgs));
  21186. #ifdef WOLFSSL_ASYNC_CRYPT
  21187. ssl->async.freeArgs = FreeSskeArgs;
  21188. #endif
  21189. }
  21190. switch(ssl->options.asyncState)
  21191. {
  21192. case TLS_ASYNC_BEGIN:
  21193. {
  21194. #ifdef HAVE_QSH
  21195. if (ssl->peerQSHKeyPresent && ssl->options.haveQSH) {
  21196. args->qshSz = QSH_KeyGetSize(ssl);
  21197. }
  21198. #endif
  21199. /* Do some checks / debug msgs */
  21200. switch(ssl->specs.kea)
  21201. {
  21202. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  21203. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  21204. case ecdhe_psk_kea:
  21205. {
  21206. WOLFSSL_MSG("Using ephemeral ECDH PSK");
  21207. break;
  21208. }
  21209. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  21210. #if defined(HAVE_ECC)
  21211. case ecc_diffie_hellman_kea:
  21212. {
  21213. if (ssl->specs.static_ecdh) {
  21214. WOLFSSL_MSG("Using Static ECDH, not sending "
  21215. "ServerKeyExchange");
  21216. ERROR_OUT(0, exit_sske);
  21217. }
  21218. WOLFSSL_MSG("Using ephemeral ECDH");
  21219. break;
  21220. }
  21221. #endif /* HAVE_ECC */
  21222. }
  21223. /* Preparing keys */
  21224. switch(ssl->specs.kea)
  21225. {
  21226. #ifndef NO_PSK
  21227. case psk_kea:
  21228. {
  21229. /* Nothing to do in this sub-state */
  21230. break;
  21231. }
  21232. #endif /* !NO_PSK */
  21233. #if !defined(NO_DH) && (!defined(NO_PSK) || !defined(NO_RSA))
  21234. #if !defined(NO_PSK)
  21235. case dhe_psk_kea:
  21236. #endif
  21237. #if !defined(NO_RSA)
  21238. case diffie_hellman_kea:
  21239. #endif
  21240. {
  21241. /* Allocate DH key buffers and generate key */
  21242. if (ssl->buffers.serverDH_P.buffer == NULL ||
  21243. ssl->buffers.serverDH_G.buffer == NULL) {
  21244. ERROR_OUT(NO_DH_PARAMS, exit_sske);
  21245. }
  21246. if (ssl->buffers.serverDH_Pub.buffer == NULL) {
  21247. /* Free'd in SSL_ResourceFree and FreeHandshakeResources */
  21248. ssl->buffers.serverDH_Pub.buffer = (byte*)XMALLOC(
  21249. ssl->buffers.serverDH_P.length + OPAQUE16_LEN,
  21250. ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  21251. if (ssl->buffers.serverDH_Pub.buffer == NULL) {
  21252. ERROR_OUT(MEMORY_E, exit_sske);
  21253. }
  21254. }
  21255. if (ssl->buffers.serverDH_Priv.buffer == NULL) {
  21256. /* Free'd in SSL_ResourceFree and FreeHandshakeResources */
  21257. ssl->buffers.serverDH_Priv.buffer = (byte*)XMALLOC(
  21258. ssl->buffers.serverDH_P.length + OPAQUE16_LEN,
  21259. ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  21260. if (ssl->buffers.serverDH_Priv.buffer == NULL) {
  21261. ERROR_OUT(MEMORY_E, exit_sske);
  21262. }
  21263. }
  21264. ssl->options.dhKeySz =
  21265. (word16)ssl->buffers.serverDH_P.length;
  21266. ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
  21267. (void**)&ssl->buffers.serverDH_Key);
  21268. if (ret != 0) {
  21269. goto exit_sske;
  21270. }
  21271. #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
  21272. !defined(HAVE_FIPS) && \
  21273. !defined(HAVE_SELFTEST)
  21274. if (ssl->options.dhDoKeyTest &&
  21275. !ssl->options.dhKeyTested)
  21276. {
  21277. ret = wc_DhSetCheckKey(
  21278. ssl->buffers.serverDH_Key,
  21279. ssl->buffers.serverDH_P.buffer,
  21280. ssl->buffers.serverDH_P.length,
  21281. ssl->buffers.serverDH_G.buffer,
  21282. ssl->buffers.serverDH_G.length,
  21283. NULL, 0, 0, ssl->rng);
  21284. if (ret != 0) {
  21285. goto exit_sske;
  21286. }
  21287. ssl->options.dhKeyTested = 1;
  21288. }
  21289. else
  21290. #endif
  21291. {
  21292. ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
  21293. ssl->buffers.serverDH_P.buffer,
  21294. ssl->buffers.serverDH_P.length,
  21295. ssl->buffers.serverDH_G.buffer,
  21296. ssl->buffers.serverDH_G.length);
  21297. if (ret != 0) {
  21298. goto exit_sske;
  21299. }
  21300. }
  21301. ret = DhGenKeyPair(ssl, ssl->buffers.serverDH_Key,
  21302. ssl->buffers.serverDH_Priv.buffer,
  21303. (word32*)&ssl->buffers.serverDH_Priv.length,
  21304. ssl->buffers.serverDH_Pub.buffer,
  21305. (word32*)&ssl->buffers.serverDH_Pub.length);
  21306. break;
  21307. }
  21308. #endif /* !NO_DH && (!NO_PSK || !NO_RSA) */
  21309. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  21310. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  21311. case ecdhe_psk_kea:
  21312. /* Fall through to create temp ECC key */
  21313. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  21314. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  21315. defined(HAVE_CURVE448)
  21316. case ecc_diffie_hellman_kea:
  21317. {
  21318. #ifdef HAVE_CURVE25519
  21319. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  21320. /* need ephemeral key now, create it if missing */
  21321. if (ssl->eccTempKey == NULL) {
  21322. /* alloc/init on demand */
  21323. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
  21324. (void**)&ssl->eccTempKey);
  21325. if (ret != 0) {
  21326. goto exit_sske;
  21327. }
  21328. }
  21329. if (ssl->eccTempKeyPresent == 0) {
  21330. ret = X25519MakeKey(ssl,
  21331. (curve25519_key*)ssl->eccTempKey, NULL);
  21332. if (ret == 0 || ret == WC_PENDING_E) {
  21333. ssl->eccTempKeyPresent =
  21334. DYNAMIC_TYPE_CURVE25519;
  21335. }
  21336. }
  21337. break;
  21338. }
  21339. #endif
  21340. #ifdef HAVE_CURVE448
  21341. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  21342. /* need ephemeral key now, create it if missing */
  21343. if (ssl->eccTempKey == NULL) {
  21344. /* alloc/init on demand */
  21345. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
  21346. (void**)&ssl->eccTempKey);
  21347. if (ret != 0) {
  21348. goto exit_sske;
  21349. }
  21350. }
  21351. if (ssl->eccTempKeyPresent == 0) {
  21352. ret = X448MakeKey(ssl,
  21353. (curve448_key*)ssl->eccTempKey, NULL);
  21354. if (ret == 0 || ret == WC_PENDING_E) {
  21355. ssl->eccTempKeyPresent =
  21356. DYNAMIC_TYPE_CURVE448;
  21357. }
  21358. }
  21359. break;
  21360. }
  21361. #endif
  21362. #ifdef HAVE_ECC
  21363. /* need ephemeral key now, create it if missing */
  21364. if (ssl->eccTempKey == NULL) {
  21365. /* alloc/init on demand */
  21366. ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
  21367. (void**)&ssl->eccTempKey);
  21368. if (ret != 0) {
  21369. goto exit_sske;
  21370. }
  21371. }
  21372. if (ssl->eccTempKeyPresent == 0) {
  21373. ret = EccMakeKey(ssl, ssl->eccTempKey, NULL);
  21374. if (ret == 0 || ret == WC_PENDING_E) {
  21375. ssl->eccTempKeyPresent = DYNAMIC_TYPE_ECC;
  21376. }
  21377. }
  21378. #endif
  21379. break;
  21380. }
  21381. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  21382. default:
  21383. /* Skip ServerKeyExchange */
  21384. goto exit_sske;
  21385. } /* switch(ssl->specs.kea) */
  21386. /* Check for error */
  21387. if (ret != 0) {
  21388. goto exit_sske;
  21389. }
  21390. /* Advance state and proceed */
  21391. ssl->options.asyncState = TLS_ASYNC_BUILD;
  21392. } /* case TLS_ASYNC_BEGIN */
  21393. FALL_THROUGH;
  21394. case TLS_ASYNC_BUILD:
  21395. {
  21396. #if (!defined(NO_DH) && !defined(NO_RSA)) || (defined(HAVE_ECC) || \
  21397. defined(HAVE_CURVE25519) || defined(HAVE_CURVE448))
  21398. word32 preSigSz, preSigIdx;
  21399. #endif
  21400. switch(ssl->specs.kea)
  21401. {
  21402. #ifndef NO_PSK
  21403. case psk_kea:
  21404. {
  21405. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  21406. if (ssl->arrays->server_hint[0] == 0) {
  21407. ERROR_OUT(0, exit_sske); /* don't send */
  21408. }
  21409. /* include size part */
  21410. args->length = (word32)XSTRLEN(ssl->arrays->server_hint);
  21411. if (args->length > MAX_PSK_ID_LEN) {
  21412. ERROR_OUT(SERVER_HINT_ERROR, exit_sske);
  21413. }
  21414. args->length += HINT_LEN_SZ;
  21415. args->sendSz = args->length + HANDSHAKE_HEADER_SZ +
  21416. RECORD_HEADER_SZ;
  21417. #ifdef HAVE_QSH
  21418. args->length += args->qshSz;
  21419. args->sendSz += args->qshSz;
  21420. #endif
  21421. #ifdef WOLFSSL_DTLS
  21422. if (ssl->options.dtls) {
  21423. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  21424. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  21425. }
  21426. #endif
  21427. if (IsEncryptionOn(ssl, 1)) {
  21428. args->sendSz += MAX_MSG_EXTRA;
  21429. }
  21430. /* check for available size */
  21431. if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
  21432. goto exit_sske;
  21433. }
  21434. /* get output buffer */
  21435. args->output = ssl->buffers.outputBuffer.buffer +
  21436. ssl->buffers.outputBuffer.length;
  21437. AddHeaders(args->output, args->length,
  21438. server_key_exchange, ssl);
  21439. /* key data */
  21440. #ifdef HAVE_QSH
  21441. c16toa((word16)(args->length - args->qshSz -
  21442. HINT_LEN_SZ), args->output + args->idx);
  21443. #else
  21444. c16toa((word16)(args->length - HINT_LEN_SZ),
  21445. args->output + args->idx);
  21446. #endif
  21447. args->idx += HINT_LEN_SZ;
  21448. XMEMCPY(args->output + args->idx,
  21449. ssl->arrays->server_hint,
  21450. args->length - HINT_LEN_SZ);
  21451. break;
  21452. }
  21453. #endif /* !NO_PSK */
  21454. #if !defined(NO_DH) && !defined(NO_PSK)
  21455. case dhe_psk_kea:
  21456. {
  21457. word32 hintLen;
  21458. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  21459. args->length = LENGTH_SZ * 3 + /* p, g, pub */
  21460. ssl->buffers.serverDH_P.length +
  21461. ssl->buffers.serverDH_G.length +
  21462. ssl->buffers.serverDH_Pub.length;
  21463. /* include size part */
  21464. hintLen = (word32)XSTRLEN(ssl->arrays->server_hint);
  21465. if (hintLen > MAX_PSK_ID_LEN) {
  21466. ERROR_OUT(SERVER_HINT_ERROR, exit_sske);
  21467. }
  21468. args->length += hintLen + HINT_LEN_SZ;
  21469. args->sendSz = args->length + HANDSHAKE_HEADER_SZ +
  21470. RECORD_HEADER_SZ;
  21471. #ifdef HAVE_QSH
  21472. args->length += args->qshSz;
  21473. args->sendSz += args->qshSz;
  21474. #endif
  21475. #ifdef WOLFSSL_DTLS
  21476. if (ssl->options.dtls) {
  21477. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  21478. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  21479. }
  21480. #endif
  21481. if (IsEncryptionOn(ssl, 1)) {
  21482. args->sendSz += MAX_MSG_EXTRA;
  21483. }
  21484. /* check for available size */
  21485. if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
  21486. goto exit_sske;
  21487. }
  21488. /* get output buffer */
  21489. args->output = ssl->buffers.outputBuffer.buffer +
  21490. ssl->buffers.outputBuffer.length;
  21491. AddHeaders(args->output, args->length,
  21492. server_key_exchange, ssl);
  21493. /* key data */
  21494. c16toa((word16)hintLen, args->output + args->idx);
  21495. args->idx += HINT_LEN_SZ;
  21496. XMEMCPY(args->output + args->idx,
  21497. ssl->arrays->server_hint, hintLen);
  21498. args->idx += hintLen;
  21499. /* add p, g, pub */
  21500. c16toa((word16)ssl->buffers.serverDH_P.length,
  21501. args->output + args->idx);
  21502. args->idx += LENGTH_SZ;
  21503. XMEMCPY(args->output + args->idx,
  21504. ssl->buffers.serverDH_P.buffer,
  21505. ssl->buffers.serverDH_P.length);
  21506. args->idx += ssl->buffers.serverDH_P.length;
  21507. /* g */
  21508. c16toa((word16)ssl->buffers.serverDH_G.length,
  21509. args->output + args->idx);
  21510. args->idx += LENGTH_SZ;
  21511. XMEMCPY(args->output + args->idx,
  21512. ssl->buffers.serverDH_G.buffer,
  21513. ssl->buffers.serverDH_G.length);
  21514. args->idx += ssl->buffers.serverDH_G.length;
  21515. /* pub */
  21516. c16toa((word16)ssl->buffers.serverDH_Pub.length,
  21517. args->output + args->idx);
  21518. args->idx += LENGTH_SZ;
  21519. XMEMCPY(args->output + args->idx,
  21520. ssl->buffers.serverDH_Pub.buffer,
  21521. ssl->buffers.serverDH_Pub.length);
  21522. /* No need to update idx, since sizes are already set */
  21523. /* args->idx += ssl->buffers.serverDH_Pub.length; */
  21524. break;
  21525. }
  21526. #endif /* !defined(NO_DH) && !defined(NO_PSK) */
  21527. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  21528. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  21529. case ecdhe_psk_kea:
  21530. {
  21531. word32 hintLen;
  21532. /* curve type, named curve, length(1) */
  21533. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  21534. args->length = ENUM_LEN + CURVE_LEN + ENUM_LEN;
  21535. args->exportSz = MAX_EXPORT_ECC_SZ;
  21536. args->exportBuf = (byte*)XMALLOC(args->exportSz,
  21537. ssl->heap, DYNAMIC_TYPE_DER);
  21538. if (args->exportBuf == NULL) {
  21539. ERROR_OUT(MEMORY_E, exit_sske);
  21540. }
  21541. #ifdef HAVE_CURVE25519
  21542. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  21543. if (wc_curve25519_export_public_ex(
  21544. (curve25519_key*)ssl->eccTempKey,
  21545. args->exportBuf, &args->exportSz,
  21546. EC25519_LITTLE_ENDIAN) != 0) {
  21547. ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
  21548. }
  21549. }
  21550. else
  21551. #endif
  21552. #ifdef HAVE_CURVE448
  21553. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  21554. if (wc_curve448_export_public_ex(
  21555. (curve448_key*)ssl->eccTempKey,
  21556. args->exportBuf, &args->exportSz,
  21557. EC448_LITTLE_ENDIAN) != 0) {
  21558. ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
  21559. }
  21560. }
  21561. else
  21562. #endif
  21563. {
  21564. if (wc_ecc_export_x963(ssl->eccTempKey,
  21565. args->exportBuf, &args->exportSz) != 0) {
  21566. ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
  21567. }
  21568. }
  21569. args->length += args->exportSz;
  21570. /* include size part */
  21571. hintLen = (word32)XSTRLEN(ssl->arrays->server_hint);
  21572. if (hintLen > MAX_PSK_ID_LEN) {
  21573. ERROR_OUT(SERVER_HINT_ERROR, exit_sske);
  21574. }
  21575. args->length += hintLen + HINT_LEN_SZ;
  21576. args->sendSz = args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  21577. #ifdef HAVE_QSH
  21578. args->length += args->qshSz;
  21579. args->sendSz += args->qshSz;
  21580. #endif
  21581. #ifdef WOLFSSL_DTLS
  21582. if (ssl->options.dtls) {
  21583. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  21584. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  21585. }
  21586. #endif
  21587. if (IsEncryptionOn(ssl, 1)) {
  21588. args->sendSz += MAX_MSG_EXTRA;
  21589. }
  21590. /* check for available size */
  21591. if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
  21592. goto exit_sske;
  21593. }
  21594. /* get output buffer */
  21595. args->output = ssl->buffers.outputBuffer.buffer +
  21596. ssl->buffers.outputBuffer.length;
  21597. /* key data */
  21598. c16toa((word16)hintLen, args->output + args->idx);
  21599. args->idx += HINT_LEN_SZ;
  21600. XMEMCPY(args->output + args->idx,
  21601. ssl->arrays->server_hint, hintLen);
  21602. args->idx += hintLen;
  21603. /* ECC key exchange data */
  21604. args->output[args->idx++] = named_curve;
  21605. args->output[args->idx++] = 0x00; /* leading zero */
  21606. #ifdef HAVE_CURVE25519
  21607. if (ssl->ecdhCurveOID == ECC_X25519_OID)
  21608. args->output[args->idx++] = WOLFSSL_ECC_X25519;
  21609. else
  21610. #endif
  21611. #ifdef HAVE_CURVE448
  21612. if (ssl->ecdhCurveOID == ECC_X448_OID)
  21613. args->output[args->idx++] = WOLFSSL_ECC_X448;
  21614. else
  21615. #endif
  21616. {
  21617. #ifdef HAVE_ECC
  21618. args->output[args->idx++] =
  21619. SetCurveId(ssl->eccTempKey);
  21620. #endif
  21621. }
  21622. args->output[args->idx++] = (byte)args->exportSz;
  21623. XMEMCPY(args->output + args->idx, args->exportBuf,
  21624. args->exportSz);
  21625. break;
  21626. }
  21627. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  21628. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  21629. defined(HAVE_CURVE448)
  21630. case ecc_diffie_hellman_kea:
  21631. {
  21632. enum wc_HashType hashType;
  21633. /* curve type, named curve, length(1) */
  21634. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  21635. args->length = ENUM_LEN + CURVE_LEN + ENUM_LEN;
  21636. /* Export temp ECC key and add to length */
  21637. args->exportSz = MAX_EXPORT_ECC_SZ;
  21638. args->exportBuf = (byte*)XMALLOC(args->exportSz,
  21639. ssl->heap, DYNAMIC_TYPE_DER);
  21640. if (args->exportBuf == NULL) {
  21641. ERROR_OUT(MEMORY_E, exit_sske);
  21642. }
  21643. #ifdef HAVE_CURVE25519
  21644. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  21645. if (wc_curve25519_export_public_ex(
  21646. (curve25519_key*)ssl->eccTempKey,
  21647. args->exportBuf, &args->exportSz,
  21648. EC25519_LITTLE_ENDIAN) != 0) {
  21649. ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
  21650. }
  21651. }
  21652. else
  21653. #endif
  21654. #ifdef HAVE_CURVE448
  21655. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  21656. if (wc_curve448_export_public_ex(
  21657. (curve448_key*)ssl->eccTempKey,
  21658. args->exportBuf, &args->exportSz,
  21659. EC448_LITTLE_ENDIAN) != 0) {
  21660. ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
  21661. }
  21662. }
  21663. else
  21664. #endif
  21665. {
  21666. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  21667. if (wc_ecc_export_x963(ssl->eccTempKey,
  21668. args->exportBuf, &args->exportSz) != 0) {
  21669. ERROR_OUT(ECC_EXPORT_ERROR, exit_sske);
  21670. }
  21671. #endif
  21672. }
  21673. args->length += args->exportSz;
  21674. preSigSz = args->length;
  21675. preSigIdx = args->idx;
  21676. if (ssl->buffers.key == NULL) {
  21677. #ifdef HAVE_PK_CALLBACKS
  21678. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
  21679. args->tmpSigSz = GetPrivateKeySigSize(ssl);
  21680. if (args->tmpSigSz == 0) {
  21681. ERROR_OUT(NO_PRIVATE_KEY, exit_sske);
  21682. }
  21683. }
  21684. else
  21685. #endif
  21686. ERROR_OUT(NO_PRIVATE_KEY, exit_sske);
  21687. }
  21688. else {
  21689. switch(ssl->suites->sigAlgo) {
  21690. #ifndef NO_RSA
  21691. #ifdef WC_RSA_PSS
  21692. case rsa_pss_sa_algo:
  21693. #endif
  21694. case rsa_sa_algo:
  21695. {
  21696. word16 keySz;
  21697. ssl->buffers.keyType = rsa_sa_algo;
  21698. ret = DecodePrivateKey(ssl, &keySz);
  21699. if (ret != 0) {
  21700. goto exit_sske;
  21701. }
  21702. args->tmpSigSz = (word32)keySz;
  21703. break;
  21704. }
  21705. #endif /* !NO_RSA */
  21706. #ifdef HAVE_ECC
  21707. case ecc_dsa_sa_algo:
  21708. {
  21709. word16 keySz;
  21710. ssl->buffers.keyType = ecc_dsa_sa_algo;
  21711. ret = DecodePrivateKey(ssl, &keySz);
  21712. if (ret != 0) {
  21713. goto exit_sske;
  21714. }
  21715. /* worst case estimate */
  21716. args->tmpSigSz = keySz;
  21717. break;
  21718. }
  21719. #endif
  21720. #ifdef HAVE_ED25519
  21721. case ed25519_sa_algo:
  21722. {
  21723. word16 keySz;
  21724. ssl->buffers.keyType = ed25519_sa_algo;
  21725. ret = DecodePrivateKey(ssl, &keySz);
  21726. if (ret != 0) {
  21727. goto exit_sske;
  21728. }
  21729. /* worst case estimate */
  21730. args->tmpSigSz = ED25519_SIG_SIZE;
  21731. break;
  21732. }
  21733. #endif /* HAVE_ED25519 */
  21734. #ifdef HAVE_ED448
  21735. case ed448_sa_algo:
  21736. {
  21737. word16 keySz;
  21738. ssl->buffers.keyType = ed448_sa_algo;
  21739. ret = DecodePrivateKey(ssl, &keySz);
  21740. if (ret != 0) {
  21741. goto exit_sske;
  21742. }
  21743. /* worst case estimate */
  21744. args->tmpSigSz = ED448_SIG_SIZE;
  21745. break;
  21746. }
  21747. #endif /* HAVE_ED448 */
  21748. default:
  21749. ERROR_OUT(ALGO_ID_E, exit_sske); /* unsupported type */
  21750. } /* switch(ssl->specs.sig_algo) */
  21751. }
  21752. /* sig length */
  21753. args->length += LENGTH_SZ;
  21754. args->length += args->tmpSigSz;
  21755. if (IsAtLeastTLSv1_2(ssl)) {
  21756. args->length += HASH_SIG_SIZE;
  21757. }
  21758. args->sendSz = args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  21759. #ifdef HAVE_QSH
  21760. args->length += args->qshSz;
  21761. args->sendSz += args->qshSz;
  21762. #endif
  21763. #ifdef WOLFSSL_DTLS
  21764. if (ssl->options.dtls) {
  21765. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  21766. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  21767. preSigIdx = args->idx;
  21768. }
  21769. #endif
  21770. if (IsEncryptionOn(ssl, 1)) {
  21771. args->sendSz += MAX_MSG_EXTRA;
  21772. }
  21773. /* check for available size */
  21774. if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
  21775. goto exit_sske;
  21776. }
  21777. /* get output buffer */
  21778. args->output = ssl->buffers.outputBuffer.buffer +
  21779. ssl->buffers.outputBuffer.length;
  21780. /* record and message headers will be added below, when we're sure
  21781. of the sig length */
  21782. /* key exchange data */
  21783. args->output[args->idx++] = named_curve;
  21784. args->output[args->idx++] = 0x00; /* leading zero */
  21785. #ifdef HAVE_CURVE25519
  21786. if (ssl->ecdhCurveOID == ECC_X25519_OID)
  21787. args->output[args->idx++] = WOLFSSL_ECC_X25519;
  21788. else
  21789. #endif
  21790. #ifdef HAVE_CURVE448
  21791. if (ssl->ecdhCurveOID == ECC_X448_OID)
  21792. args->output[args->idx++] = WOLFSSL_ECC_X448;
  21793. else
  21794. #endif
  21795. {
  21796. #ifdef HAVE_ECC
  21797. args->output[args->idx++] =
  21798. SetCurveId(ssl->eccTempKey);
  21799. #endif
  21800. }
  21801. args->output[args->idx++] = (byte)args->exportSz;
  21802. XMEMCPY(args->output + args->idx, args->exportBuf, args->exportSz);
  21803. args->idx += args->exportSz;
  21804. /* Determine hash type */
  21805. if (IsAtLeastTLSv1_2(ssl)) {
  21806. EncodeSigAlg(ssl->suites->hashAlgo,
  21807. ssl->suites->sigAlgo,
  21808. &args->output[args->idx]);
  21809. args->idx += 2;
  21810. hashType = HashAlgoToType(ssl->suites->hashAlgo);
  21811. if (hashType == WC_HASH_TYPE_NONE) {
  21812. ERROR_OUT(ALGO_ID_E, exit_sske);
  21813. }
  21814. } else {
  21815. /* only using sha and md5 for rsa */
  21816. #ifndef NO_OLD_TLS
  21817. hashType = WC_HASH_TYPE_SHA;
  21818. if (ssl->suites->sigAlgo == rsa_sa_algo) {
  21819. hashType = WC_HASH_TYPE_MD5_SHA;
  21820. }
  21821. #else
  21822. ERROR_OUT(ALGO_ID_E, exit_sske);
  21823. #endif
  21824. }
  21825. /* Signature length will be written later, when we're sure what it is */
  21826. #ifdef HAVE_FUZZER
  21827. if (ssl->fuzzerCb) {
  21828. ssl->fuzzerCb(ssl, args->output + preSigIdx,
  21829. preSigSz, FUZZ_SIGNATURE, ssl->fuzzerCtx);
  21830. }
  21831. #endif
  21832. /* Assemble buffer to hash for signature */
  21833. args->sigDataSz = RAN_LEN + RAN_LEN + preSigSz;
  21834. args->sigDataBuf = (byte*)XMALLOC(args->sigDataSz,
  21835. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  21836. if (args->sigDataBuf == NULL) {
  21837. ERROR_OUT(MEMORY_E, exit_sske);
  21838. }
  21839. XMEMCPY(args->sigDataBuf, ssl->arrays->clientRandom,
  21840. RAN_LEN);
  21841. XMEMCPY(args->sigDataBuf+RAN_LEN,
  21842. ssl->arrays->serverRandom, RAN_LEN);
  21843. XMEMCPY(args->sigDataBuf+RAN_LEN+RAN_LEN,
  21844. args->output + preSigIdx, preSigSz);
  21845. if (ssl->suites->sigAlgo != ed25519_sa_algo &&
  21846. ssl->suites->sigAlgo != ed448_sa_algo) {
  21847. ssl->buffers.sig.length =
  21848. wc_HashGetDigestSize(hashType);
  21849. if ((int)ssl->buffers.sig.length < 0) {
  21850. ERROR_OUT(HASH_TYPE_E, exit_sske);
  21851. }
  21852. ssl->buffers.sig.buffer = (byte*)XMALLOC(
  21853. ssl->buffers.sig.length,
  21854. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  21855. if (ssl->buffers.sig.buffer == NULL) {
  21856. ERROR_OUT(MEMORY_E, exit_sske);
  21857. }
  21858. /* Perform hash */
  21859. ret = wc_Hash(hashType, args->sigDataBuf,
  21860. args->sigDataSz,
  21861. ssl->buffers.sig.buffer,
  21862. ssl->buffers.sig.length);
  21863. if (ret != 0) {
  21864. goto exit_sske;
  21865. }
  21866. }
  21867. args->sigSz = args->tmpSigSz;
  21868. /* Sign hash to create signature */
  21869. switch (ssl->suites->sigAlgo)
  21870. {
  21871. #ifndef NO_RSA
  21872. case rsa_sa_algo:
  21873. {
  21874. /* For TLS 1.2 re-encode signature */
  21875. if (IsAtLeastTLSv1_2(ssl)) {
  21876. byte* encodedSig = (byte*)XMALLOC(
  21877. MAX_ENCODED_SIG_SZ, ssl->heap,
  21878. DYNAMIC_TYPE_SIGNATURE);
  21879. if (encodedSig == NULL) {
  21880. ERROR_OUT(MEMORY_E, exit_sske);
  21881. }
  21882. ssl->buffers.sig.length =
  21883. wc_EncodeSignature(encodedSig,
  21884. ssl->buffers.sig.buffer,
  21885. ssl->buffers.sig.length,
  21886. TypeHash(ssl->suites->hashAlgo));
  21887. /* Replace sig buffer with new one */
  21888. XFREE(ssl->buffers.sig.buffer, ssl->heap,
  21889. DYNAMIC_TYPE_SIGNATURE);
  21890. ssl->buffers.sig.buffer = encodedSig;
  21891. }
  21892. /* write sig size here */
  21893. c16toa((word16)args->sigSz,
  21894. args->output + args->idx);
  21895. args->idx += LENGTH_SZ;
  21896. break;
  21897. }
  21898. #ifdef WC_RSA_PSS
  21899. case rsa_pss_sa_algo:
  21900. /* write sig size here */
  21901. c16toa((word16)args->sigSz,
  21902. args->output + args->idx);
  21903. args->idx += LENGTH_SZ;
  21904. break;
  21905. #endif
  21906. #endif /* !NO_RSA */
  21907. case ecc_dsa_sa_algo:
  21908. {
  21909. break;
  21910. }
  21911. #ifdef HAVE_ED25519
  21912. case ed25519_sa_algo:
  21913. ret = Ed25519CheckPubKey(ssl);
  21914. if (ret != 0)
  21915. goto exit_sske;
  21916. break;
  21917. #endif /* HAVE_ED25519 */
  21918. #ifdef HAVE_ED448
  21919. case ed448_sa_algo:
  21920. ret = Ed448CheckPubKey(ssl);
  21921. if (ret != 0)
  21922. goto exit_sske;
  21923. break;
  21924. #endif /* HAVE_ED448 */
  21925. } /* switch(ssl->specs.sig_algo) */
  21926. break;
  21927. }
  21928. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  21929. #if !defined(NO_DH) && !defined(NO_RSA)
  21930. case diffie_hellman_kea:
  21931. {
  21932. enum wc_HashType hashType;
  21933. args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  21934. args->length = LENGTH_SZ * 3; /* p, g, pub */
  21935. args->length += ssl->buffers.serverDH_P.length +
  21936. ssl->buffers.serverDH_G.length +
  21937. ssl->buffers.serverDH_Pub.length;
  21938. preSigIdx = args->idx;
  21939. preSigSz = args->length;
  21940. if (!ssl->options.usingAnon_cipher) {
  21941. word16 keySz;
  21942. /* sig length */
  21943. args->length += LENGTH_SZ;
  21944. if (ssl->buffers.key == NULL) {
  21945. #ifdef HAVE_PK_CALLBACKS
  21946. if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
  21947. keySz = (word32)GetPrivateKeySigSize(ssl);
  21948. else
  21949. #endif
  21950. ERROR_OUT(NO_PRIVATE_KEY, exit_sske);
  21951. }
  21952. else
  21953. {
  21954. if (ssl->buffers.keyType == 0)
  21955. ssl->buffers.keyType = rsa_sa_algo;
  21956. ret = DecodePrivateKey(ssl, &keySz);
  21957. if (ret != 0) {
  21958. goto exit_sske;
  21959. }
  21960. }
  21961. if (keySz == 0) { /* test if keySz has error */
  21962. ERROR_OUT(keySz, exit_sske);
  21963. }
  21964. args->tmpSigSz = (word32)keySz;
  21965. args->length += args->tmpSigSz;
  21966. if (IsAtLeastTLSv1_2(ssl)) {
  21967. args->length += HASH_SIG_SIZE;
  21968. }
  21969. }
  21970. args->sendSz = args->length + HANDSHAKE_HEADER_SZ +
  21971. RECORD_HEADER_SZ;
  21972. #ifdef HAVE_QSH
  21973. args->length += args->qshSz;
  21974. args->sendSz += args->qshSz;
  21975. #endif
  21976. #ifdef WOLFSSL_DTLS
  21977. if (ssl->options.dtls) {
  21978. args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  21979. args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  21980. preSigIdx = args->idx;
  21981. }
  21982. #endif
  21983. if (IsEncryptionOn(ssl, 1)) {
  21984. args->sendSz += MAX_MSG_EXTRA;
  21985. }
  21986. /* check for available size */
  21987. if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
  21988. goto exit_sske;
  21989. }
  21990. /* get output buffer */
  21991. args->output = ssl->buffers.outputBuffer.buffer +
  21992. ssl->buffers.outputBuffer.length;
  21993. AddHeaders(args->output, args->length,
  21994. server_key_exchange, ssl);
  21995. /* add p, g, pub */
  21996. c16toa((word16)ssl->buffers.serverDH_P.length,
  21997. args->output + args->idx);
  21998. args->idx += LENGTH_SZ;
  21999. XMEMCPY(args->output + args->idx,
  22000. ssl->buffers.serverDH_P.buffer,
  22001. ssl->buffers.serverDH_P.length);
  22002. args->idx += ssl->buffers.serverDH_P.length;
  22003. /* g */
  22004. c16toa((word16)ssl->buffers.serverDH_G.length,
  22005. args->output + args->idx);
  22006. args->idx += LENGTH_SZ;
  22007. XMEMCPY(args->output + args->idx,
  22008. ssl->buffers.serverDH_G.buffer,
  22009. ssl->buffers.serverDH_G.length);
  22010. args->idx += ssl->buffers.serverDH_G.length;
  22011. /* pub */
  22012. c16toa((word16)ssl->buffers.serverDH_Pub.length,
  22013. args->output + args->idx);
  22014. args->idx += LENGTH_SZ;
  22015. XMEMCPY(args->output + args->idx,
  22016. ssl->buffers.serverDH_Pub.buffer,
  22017. ssl->buffers.serverDH_Pub.length);
  22018. args->idx += ssl->buffers.serverDH_Pub.length;
  22019. #ifdef HAVE_FUZZER
  22020. if (ssl->fuzzerCb) {
  22021. ssl->fuzzerCb(ssl, args->output + preSigIdx,
  22022. preSigSz, FUZZ_SIGNATURE, ssl->fuzzerCtx);
  22023. }
  22024. #endif
  22025. if (ssl->options.usingAnon_cipher) {
  22026. break;
  22027. }
  22028. /* Determine hash type */
  22029. if (IsAtLeastTLSv1_2(ssl)) {
  22030. EncodeSigAlg(ssl->suites->hashAlgo,
  22031. ssl->suites->sigAlgo,
  22032. &args->output[args->idx]);
  22033. args->idx += 2;
  22034. hashType = HashAlgoToType(ssl->suites->hashAlgo);
  22035. if (hashType == WC_HASH_TYPE_NONE) {
  22036. ERROR_OUT(ALGO_ID_E, exit_sske);
  22037. }
  22038. } else {
  22039. /* only using sha and md5 for rsa */
  22040. #ifndef NO_OLD_TLS
  22041. hashType = WC_HASH_TYPE_SHA;
  22042. if (ssl->suites->sigAlgo == rsa_sa_algo) {
  22043. hashType = WC_HASH_TYPE_MD5_SHA;
  22044. }
  22045. #else
  22046. ERROR_OUT(ALGO_ID_E, exit_sske);
  22047. #endif
  22048. }
  22049. /* signature size */
  22050. c16toa((word16)args->tmpSigSz, args->output + args->idx);
  22051. args->idx += LENGTH_SZ;
  22052. /* Assemble buffer to hash for signature */
  22053. args->sigDataSz = RAN_LEN + RAN_LEN + preSigSz;
  22054. args->sigDataBuf = (byte*)XMALLOC(args->sigDataSz,
  22055. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  22056. if (args->sigDataBuf == NULL) {
  22057. ERROR_OUT(MEMORY_E, exit_sske);
  22058. }
  22059. XMEMCPY(args->sigDataBuf, ssl->arrays->clientRandom,
  22060. RAN_LEN);
  22061. XMEMCPY(args->sigDataBuf+RAN_LEN,
  22062. ssl->arrays->serverRandom, RAN_LEN);
  22063. XMEMCPY(args->sigDataBuf+RAN_LEN+RAN_LEN,
  22064. args->output + preSigIdx, preSigSz);
  22065. if (ssl->suites->sigAlgo != ed25519_sa_algo &&
  22066. ssl->suites->sigAlgo != ed448_sa_algo) {
  22067. ssl->buffers.sig.length =
  22068. wc_HashGetDigestSize(hashType);
  22069. ssl->buffers.sig.buffer = (byte*)XMALLOC(
  22070. ssl->buffers.sig.length, ssl->heap,
  22071. DYNAMIC_TYPE_SIGNATURE);
  22072. if (ssl->buffers.sig.buffer == NULL) {
  22073. ERROR_OUT(MEMORY_E, exit_sske);
  22074. }
  22075. /* Perform hash */
  22076. ret = wc_Hash(hashType, args->sigDataBuf,
  22077. args->sigDataSz,
  22078. ssl->buffers.sig.buffer,
  22079. ssl->buffers.sig.length);
  22080. if (ret != 0) {
  22081. goto exit_sske;
  22082. }
  22083. }
  22084. args->sigSz = args->tmpSigSz;
  22085. /* Sign hash to create signature */
  22086. switch (ssl->suites->sigAlgo)
  22087. {
  22088. #ifndef NO_RSA
  22089. case rsa_sa_algo:
  22090. {
  22091. /* For TLS 1.2 re-encode signature */
  22092. if (IsAtLeastTLSv1_2(ssl)) {
  22093. byte* encodedSig = (byte*)XMALLOC(
  22094. MAX_ENCODED_SIG_SZ, ssl->heap,
  22095. DYNAMIC_TYPE_SIGNATURE);
  22096. if (encodedSig == NULL) {
  22097. ERROR_OUT(MEMORY_E, exit_sske);
  22098. }
  22099. ssl->buffers.sig.length =
  22100. wc_EncodeSignature(encodedSig,
  22101. ssl->buffers.sig.buffer,
  22102. ssl->buffers.sig.length,
  22103. TypeHash(ssl->suites->hashAlgo));
  22104. /* Replace sig buffer with new one */
  22105. XFREE(ssl->buffers.sig.buffer, ssl->heap,
  22106. DYNAMIC_TYPE_SIGNATURE);
  22107. ssl->buffers.sig.buffer = encodedSig;
  22108. }
  22109. break;
  22110. }
  22111. #endif /* NO_RSA */
  22112. } /* switch (ssl->suites->sigAlgo) */
  22113. break;
  22114. }
  22115. #endif /* !defined(NO_DH) && !defined(NO_RSA) */
  22116. } /* switch(ssl->specs.kea) */
  22117. /* Check for error */
  22118. if (ret != 0) {
  22119. goto exit_sske;
  22120. }
  22121. /* Advance state and proceed */
  22122. ssl->options.asyncState = TLS_ASYNC_DO;
  22123. } /* case TLS_ASYNC_BUILD */
  22124. FALL_THROUGH;
  22125. case TLS_ASYNC_DO:
  22126. {
  22127. switch(ssl->specs.kea)
  22128. {
  22129. #ifndef NO_PSK
  22130. case psk_kea:
  22131. {
  22132. break;
  22133. }
  22134. #endif /* !NO_PSK */
  22135. #if !defined(NO_DH) && !defined(NO_PSK)
  22136. case dhe_psk_kea:
  22137. {
  22138. break;
  22139. }
  22140. #endif /* !defined(NO_DH) && !defined(NO_PSK) */
  22141. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  22142. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  22143. case ecdhe_psk_kea:
  22144. {
  22145. break;
  22146. }
  22147. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  22148. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  22149. defined(HAVE_ED448)
  22150. case ecc_diffie_hellman_kea:
  22151. {
  22152. /* Sign hash to create signature */
  22153. switch (ssl->suites->sigAlgo)
  22154. {
  22155. #ifndef NO_RSA
  22156. #ifdef WC_RSA_PSS
  22157. case rsa_pss_sa_algo:
  22158. #endif
  22159. case rsa_sa_algo:
  22160. {
  22161. RsaKey* key = (RsaKey*)ssl->hsKey;
  22162. ret = RsaSign(ssl,
  22163. ssl->buffers.sig.buffer,
  22164. ssl->buffers.sig.length,
  22165. args->output + args->idx,
  22166. &args->sigSz,
  22167. ssl->suites->sigAlgo, ssl->suites->hashAlgo,
  22168. key,
  22169. ssl->buffers.key
  22170. );
  22171. break;
  22172. }
  22173. #endif /* !NO_RSA */
  22174. #ifdef HAVE_ECC
  22175. case ecc_dsa_sa_algo:
  22176. {
  22177. ecc_key* key = (ecc_key*)ssl->hsKey;
  22178. ret = EccSign(ssl,
  22179. ssl->buffers.sig.buffer,
  22180. ssl->buffers.sig.length,
  22181. args->output + LENGTH_SZ + args->idx,
  22182. &args->sigSz,
  22183. key,
  22184. #ifdef HAVE_PK_CALLBACKS
  22185. ssl->buffers.key
  22186. #else
  22187. NULL
  22188. #endif
  22189. );
  22190. break;
  22191. }
  22192. #endif /* HAVE_ECC */
  22193. #ifdef HAVE_ED25519
  22194. case ed25519_sa_algo:
  22195. {
  22196. ed25519_key* key = (ed25519_key*)ssl->hsKey;
  22197. ret = Ed25519Sign(ssl,
  22198. args->sigDataBuf, args->sigDataSz,
  22199. args->output + LENGTH_SZ + args->idx,
  22200. &args->sigSz,
  22201. key,
  22202. #ifdef HAVE_PK_CALLBACKS
  22203. ssl->buffers.key
  22204. #else
  22205. NULL
  22206. #endif
  22207. );
  22208. break;
  22209. }
  22210. #endif
  22211. #ifdef HAVE_ED448
  22212. case ed448_sa_algo:
  22213. {
  22214. ed448_key* key = (ed448_key*)ssl->hsKey;
  22215. ret = Ed448Sign(ssl,
  22216. args->sigDataBuf, args->sigDataSz,
  22217. args->output + LENGTH_SZ + args->idx,
  22218. &args->sigSz,
  22219. key,
  22220. #ifdef HAVE_PK_CALLBACKS
  22221. ssl->buffers.key
  22222. #else
  22223. NULL
  22224. #endif
  22225. );
  22226. break;
  22227. }
  22228. #endif
  22229. } /* switch(ssl->specs.sig_algo) */
  22230. break;
  22231. }
  22232. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  22233. #if !defined(NO_DH) && !defined(NO_RSA)
  22234. case diffie_hellman_kea:
  22235. {
  22236. /* Sign hash to create signature */
  22237. switch (ssl->suites->sigAlgo)
  22238. {
  22239. #ifndef NO_RSA
  22240. #ifdef WC_RSA_PSS
  22241. case rsa_pss_sa_algo:
  22242. #endif
  22243. case rsa_sa_algo:
  22244. {
  22245. RsaKey* key = (RsaKey*)ssl->hsKey;
  22246. if (ssl->options.usingAnon_cipher) {
  22247. break;
  22248. }
  22249. ret = RsaSign(ssl,
  22250. ssl->buffers.sig.buffer,
  22251. ssl->buffers.sig.length,
  22252. args->output + args->idx,
  22253. &args->sigSz,
  22254. ssl->suites->sigAlgo, ssl->suites->hashAlgo,
  22255. key,
  22256. ssl->buffers.key
  22257. );
  22258. break;
  22259. }
  22260. #endif /* NO_RSA */
  22261. } /* switch (ssl->suites->sigAlgo) */
  22262. break;
  22263. }
  22264. #endif /* !defined(NO_DH) && !defined(NO_RSA) */
  22265. } /* switch(ssl->specs.kea) */
  22266. /* Check for error */
  22267. if (ret != 0) {
  22268. goto exit_sske;
  22269. }
  22270. /* Advance state and proceed */
  22271. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  22272. } /* case TLS_ASYNC_DO */
  22273. FALL_THROUGH;
  22274. case TLS_ASYNC_VERIFY:
  22275. {
  22276. switch(ssl->specs.kea)
  22277. {
  22278. #ifndef NO_PSK
  22279. case psk_kea:
  22280. {
  22281. /* Nothing to do in this sub-state */
  22282. break;
  22283. }
  22284. #endif /* !NO_PSK */
  22285. #if !defined(NO_DH) && !defined(NO_PSK)
  22286. case dhe_psk_kea:
  22287. {
  22288. /* Nothing to do in this sub-state */
  22289. break;
  22290. }
  22291. #endif /* !defined(NO_DH) && !defined(NO_PSK) */
  22292. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  22293. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  22294. case ecdhe_psk_kea:
  22295. {
  22296. /* Nothing to do in this sub-state */
  22297. break;
  22298. }
  22299. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  22300. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  22301. defined(HAVE_CURVE448)
  22302. case ecc_diffie_hellman_kea:
  22303. {
  22304. switch(ssl->suites->sigAlgo)
  22305. {
  22306. #ifndef NO_RSA
  22307. #ifdef WC_RSA_PSS
  22308. case rsa_pss_sa_algo:
  22309. #endif
  22310. case rsa_sa_algo:
  22311. {
  22312. RsaKey* key = (RsaKey*)ssl->hsKey;
  22313. if (args->verifySig == NULL) {
  22314. if (args->sigSz == 0) {
  22315. ERROR_OUT(BAD_COND_E, exit_sske);
  22316. }
  22317. args->verifySig = (byte*)XMALLOC(
  22318. args->sigSz, ssl->heap,
  22319. DYNAMIC_TYPE_SIGNATURE);
  22320. if (!args->verifySig) {
  22321. ERROR_OUT(MEMORY_E, exit_sske);
  22322. }
  22323. XMEMCPY(args->verifySig,
  22324. args->output + args->idx, args->sigSz);
  22325. }
  22326. /* check for signature faults */
  22327. ret = VerifyRsaSign(ssl,
  22328. args->verifySig, args->sigSz,
  22329. ssl->buffers.sig.buffer,
  22330. ssl->buffers.sig.length,
  22331. ssl->suites->sigAlgo, ssl->suites->hashAlgo,
  22332. key, ssl->buffers.key
  22333. );
  22334. break;
  22335. }
  22336. #endif
  22337. case ecc_dsa_sa_algo:
  22338. #ifdef HAVE_ED25519
  22339. case ed25519_sa_algo:
  22340. #endif
  22341. #ifdef HAVE_ED448
  22342. case ed448_sa_algo:
  22343. #endif
  22344. {
  22345. /* Now that we know the real sig size, write it. */
  22346. c16toa((word16)args->sigSz,
  22347. args->output + args->idx);
  22348. /* And adjust length and sendSz from estimates */
  22349. args->length += args->sigSz - args->tmpSigSz;
  22350. args->sendSz += args->sigSz - args->tmpSigSz;
  22351. break;
  22352. }
  22353. default:
  22354. ERROR_OUT(ALGO_ID_E, exit_sske); /* unsupported type */
  22355. } /* switch(ssl->specs.sig_algo) */
  22356. break;
  22357. }
  22358. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  22359. #if !defined(NO_DH) && !defined(NO_RSA)
  22360. case diffie_hellman_kea:
  22361. {
  22362. switch (ssl->suites->sigAlgo)
  22363. {
  22364. #ifndef NO_RSA
  22365. #ifndef WC_RSA_PSS
  22366. case rsa_pss_sa_algo:
  22367. #endif
  22368. case rsa_sa_algo:
  22369. {
  22370. RsaKey* key = (RsaKey*)ssl->hsKey;
  22371. if (ssl->options.usingAnon_cipher) {
  22372. break;
  22373. }
  22374. if (args->verifySig == NULL) {
  22375. if (args->sigSz == 0) {
  22376. ERROR_OUT(BAD_COND_E, exit_sske);
  22377. }
  22378. args->verifySig = (byte*)XMALLOC(
  22379. args->sigSz, ssl->heap,
  22380. DYNAMIC_TYPE_SIGNATURE);
  22381. if (!args->verifySig) {
  22382. ERROR_OUT(MEMORY_E, exit_sske);
  22383. }
  22384. XMEMCPY(args->verifySig,
  22385. args->output + args->idx, args->sigSz);
  22386. }
  22387. /* check for signature faults */
  22388. ret = VerifyRsaSign(ssl,
  22389. args->verifySig, args->sigSz,
  22390. ssl->buffers.sig.buffer,
  22391. ssl->buffers.sig.length,
  22392. ssl->suites->sigAlgo, ssl->suites->hashAlgo,
  22393. key, ssl->buffers.key
  22394. );
  22395. break;
  22396. }
  22397. #endif
  22398. } /* switch (ssl->suites->sigAlgo) */
  22399. break;
  22400. }
  22401. #endif /* !defined(NO_DH) && !defined(NO_RSA) */
  22402. } /* switch(ssl->specs.kea) */
  22403. /* Check for error */
  22404. if (ret != 0) {
  22405. goto exit_sske;
  22406. }
  22407. /* Advance state and proceed */
  22408. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  22409. } /* case TLS_ASYNC_VERIFY */
  22410. FALL_THROUGH;
  22411. case TLS_ASYNC_FINALIZE:
  22412. {
  22413. #ifdef HAVE_QSH
  22414. if (ssl->peerQSHKeyPresent) {
  22415. if (args->qshSz > 0) {
  22416. args->idx = args->sendSz - args->qshSz;
  22417. if (QSH_KeyExchangeWrite(ssl, 1) != 0) {
  22418. ERROR_OUT(MEMORY_E, exit_sske);
  22419. }
  22420. /* extension type */
  22421. c16toa(TLSX_QUANTUM_SAFE_HYBRID,
  22422. args->output + args->idx);
  22423. args->idx += OPAQUE16_LEN;
  22424. /* write to output and check amount written */
  22425. if (TLSX_QSHPK_Write(ssl->QSH_secret->list,
  22426. args->output + args->idx) >
  22427. args->qshSz - OPAQUE16_LEN) {
  22428. ERROR_OUT(MEMORY_E, exit_sske);
  22429. }
  22430. }
  22431. }
  22432. #endif
  22433. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  22434. defined(HAVE_CURVE448)
  22435. if (ssl->specs.kea == ecdhe_psk_kea ||
  22436. ssl->specs.kea == ecc_diffie_hellman_kea) {
  22437. /* Check output to make sure it was set */
  22438. if (args->output) {
  22439. AddHeaders(args->output, args->length,
  22440. server_key_exchange, ssl);
  22441. }
  22442. else {
  22443. ERROR_OUT(BUFFER_ERROR, exit_sske);
  22444. }
  22445. }
  22446. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  22447. if (IsEncryptionOn(ssl, 1)) {
  22448. args->inputSz = args->length + HANDSHAKE_HEADER_SZ;
  22449. /* buildmsg adds rechdr */
  22450. args->input = (byte*)XMALLOC(args->inputSz, ssl->heap,
  22451. DYNAMIC_TYPE_IN_BUFFER);
  22452. if (args->input == NULL) {
  22453. ERROR_OUT(MEMORY_E, exit_sske);
  22454. }
  22455. if (args->output == NULL) {
  22456. ERROR_OUT(BUFFER_ERROR, exit_sske);
  22457. }
  22458. XMEMCPY(args->input, args->output + RECORD_HEADER_SZ,
  22459. args->inputSz);
  22460. ret = BuildMessage(ssl, args->output, args->sendSz,
  22461. args->input, args->inputSz, handshake, 1, 0, 0);
  22462. XFREE(args->input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  22463. args->input = NULL;
  22464. /* make sure its not double free'd on cleanup */
  22465. if (ret >= 0) {
  22466. args->sendSz = ret;
  22467. ret = 0;
  22468. }
  22469. }
  22470. else {
  22471. #ifdef WOLFSSL_DTLS
  22472. if (IsDtlsNotSctpMode(ssl)) {
  22473. if ((ret = DtlsMsgPoolSave(ssl,
  22474. args->output, args->sendSz)) != 0) {
  22475. goto exit_sske;
  22476. }
  22477. }
  22478. if (ssl->options.dtls)
  22479. DtlsSEQIncrement(ssl, CUR_ORDER);
  22480. #endif
  22481. ret = HashOutput(ssl, args->output, args->sendSz, 0);
  22482. if (ret != 0) {
  22483. goto exit_sske;
  22484. }
  22485. }
  22486. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  22487. if (ssl->hsInfoOn) {
  22488. AddPacketName(ssl, "ServerKeyExchange");
  22489. }
  22490. if (ssl->toInfoOn) {
  22491. AddPacketInfo(ssl, "ServerKeyExchange", handshake,
  22492. args->output, args->sendSz, WRITE_PROTO, ssl->heap);
  22493. }
  22494. #endif
  22495. /* Advance state and proceed */
  22496. ssl->options.asyncState = TLS_ASYNC_END;
  22497. } /* case TLS_ASYNC_FINALIZE */
  22498. FALL_THROUGH;
  22499. case TLS_ASYNC_END:
  22500. {
  22501. ssl->buffers.outputBuffer.length += args->sendSz;
  22502. if (!ssl->options.groupMessages) {
  22503. ret = SendBuffered(ssl);
  22504. }
  22505. ssl->options.serverState = SERVER_KEYEXCHANGE_COMPLETE;
  22506. break;
  22507. }
  22508. default:
  22509. ret = INPUT_CASE_ERROR;
  22510. } /* switch(ssl->options.asyncState) */
  22511. exit_sske:
  22512. WOLFSSL_LEAVE("SendServerKeyExchange", ret);
  22513. WOLFSSL_END(WC_FUNC_SERVER_KEY_EXCHANGE_SEND);
  22514. #ifdef WOLFSSL_ASYNC_CRYPT
  22515. /* Handle async operation */
  22516. if (ret == WC_PENDING_E)
  22517. return ret;
  22518. #endif /* WOLFSSL_ASYNC_CRYPT */
  22519. /* Final cleanup */
  22520. FreeSskeArgs(ssl, args);
  22521. FreeKeyExchange(ssl);
  22522. return ret;
  22523. }
  22524. #if defined(HAVE_SERVER_RENEGOTIATION_INFO) || defined(HAVE_FALLBACK_SCSV) || \
  22525. defined(OPENSSL_ALL)
  22526. /* search suites for specific one, idx on success, negative on error */
  22527. #ifndef WOLFSSL_TLS13
  22528. static
  22529. #endif
  22530. int FindSuite(Suites* suites, byte first, byte second)
  22531. {
  22532. int i;
  22533. if (suites == NULL || suites->suiteSz == 0) {
  22534. WOLFSSL_MSG("Suites pointer error or suiteSz 0");
  22535. return SUITES_ERROR;
  22536. }
  22537. for (i = 0; i < suites->suiteSz-1; i += SUITE_LEN) {
  22538. if (suites->suites[i] == first &&
  22539. suites->suites[i+1] == second )
  22540. return i;
  22541. }
  22542. return MATCH_SUITE_ERROR;
  22543. }
  22544. #endif
  22545. #endif /* !WOLFSSL_NO_TLS12 */
  22546. /* Make sure server cert/key are valid for this suite, true on success */
  22547. static int VerifyServerSuite(WOLFSSL* ssl, word16 idx)
  22548. {
  22549. int haveRSA = !ssl->options.haveStaticECC;
  22550. int havePSK = 0;
  22551. byte first;
  22552. byte second;
  22553. WOLFSSL_ENTER("VerifyServerSuite");
  22554. if (ssl->suites == NULL) {
  22555. WOLFSSL_MSG("Suites pointer error");
  22556. return 0;
  22557. }
  22558. first = ssl->suites->suites[idx];
  22559. second = ssl->suites->suites[idx+1];
  22560. #ifndef NO_PSK
  22561. havePSK = ssl->options.havePSK;
  22562. #endif
  22563. if (ssl->options.haveNTRU)
  22564. haveRSA = 0;
  22565. if (CipherRequires(first, second, REQUIRES_RSA)) {
  22566. WOLFSSL_MSG("Requires RSA");
  22567. if (haveRSA == 0) {
  22568. WOLFSSL_MSG("Don't have RSA");
  22569. return 0;
  22570. }
  22571. }
  22572. if (CipherRequires(first, second, REQUIRES_DHE)) {
  22573. WOLFSSL_MSG("Requires DHE");
  22574. if (ssl->options.haveDH == 0) {
  22575. WOLFSSL_MSG("Don't have DHE");
  22576. return 0;
  22577. }
  22578. }
  22579. if (CipherRequires(first, second, REQUIRES_ECC)) {
  22580. WOLFSSL_MSG("Requires ECC");
  22581. if (ssl->options.haveECC == 0) {
  22582. WOLFSSL_MSG("Don't have ECC");
  22583. return 0;
  22584. }
  22585. }
  22586. if (CipherRequires(first, second, REQUIRES_ECC_STATIC)) {
  22587. WOLFSSL_MSG("Requires static ECC");
  22588. if (ssl->options.haveStaticECC == 0) {
  22589. WOLFSSL_MSG("Don't have static ECC");
  22590. return 0;
  22591. }
  22592. }
  22593. if (CipherRequires(first, second, REQUIRES_PSK)) {
  22594. WOLFSSL_MSG("Requires PSK");
  22595. if (havePSK == 0) {
  22596. WOLFSSL_MSG("Don't have PSK");
  22597. return 0;
  22598. }
  22599. }
  22600. if (CipherRequires(first, second, REQUIRES_NTRU)) {
  22601. WOLFSSL_MSG("Requires NTRU");
  22602. if (ssl->options.haveNTRU == 0) {
  22603. WOLFSSL_MSG("Don't have NTRU");
  22604. return 0;
  22605. }
  22606. }
  22607. if (CipherRequires(first, second, REQUIRES_RSA_SIG)) {
  22608. WOLFSSL_MSG("Requires RSA Signature");
  22609. if (ssl->options.side == WOLFSSL_SERVER_END &&
  22610. ssl->options.haveECDSAsig == 1) {
  22611. WOLFSSL_MSG("Don't have RSA Signature");
  22612. return 0;
  22613. }
  22614. }
  22615. #if !defined(WOLFSSL_OLDTLS_AEAD_CIPHERSUITES)
  22616. if (CipherRequires(first, second, REQUIRES_AEAD)) {
  22617. WOLFSSL_MSG("Requires AEAD");
  22618. if (ssl->version.major == SSLv3_MAJOR &&
  22619. ssl->version.minor < TLSv1_2_MINOR) {
  22620. WOLFSSL_MSG("Version of SSL does not support AEAD ciphers");
  22621. return 0;
  22622. }
  22623. }
  22624. #endif
  22625. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  22626. defined(HAVE_CURVE448)) && defined(HAVE_SUPPORTED_CURVES)
  22627. if (!TLSX_ValidateSupportedCurves(ssl, first, second)) {
  22628. WOLFSSL_MSG("Don't have matching curves");
  22629. return 0;
  22630. }
  22631. #endif
  22632. /* ECCDHE is always supported if ECC on */
  22633. #ifdef HAVE_QSH
  22634. /* need to negotiate a classic suite in addition to TLS_QSH */
  22635. if (first == QSH_BYTE && second == TLS_QSH) {
  22636. if (TLSX_SupportExtensions(ssl)) {
  22637. ssl->options.haveQSH = 1; /* matched TLS_QSH */
  22638. }
  22639. else {
  22640. WOLFSSL_MSG("Version of SSL connection does not support "
  22641. "TLS_QSH");
  22642. }
  22643. return 0;
  22644. }
  22645. #endif
  22646. #ifdef WOLFSSL_TLS13
  22647. if (IsAtLeastTLSv1_3(ssl->version) &&
  22648. ssl->options.side == WOLFSSL_SERVER_END) {
  22649. /* Try to establish a key share. */
  22650. int ret = TLSX_KeyShare_Establish(ssl);
  22651. if (ret == KEY_SHARE_ERROR)
  22652. ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
  22653. else if (ret != 0)
  22654. return 0;
  22655. }
  22656. else if (first == TLS13_BYTE || (first == ECC_BYTE &&
  22657. (second == TLS_SHA256_SHA256 || second == TLS_SHA384_SHA384))) {
  22658. /* Can't negotiate TLS 1.3 cipher suites with lower protocol
  22659. * version. */
  22660. return 0;
  22661. }
  22662. #endif
  22663. return 1;
  22664. }
  22665. #ifndef NO_WOLFSSL_SERVER
  22666. static int CompareSuites(WOLFSSL* ssl, Suites* peerSuites, word16 i,
  22667. word16 j)
  22668. {
  22669. if (ssl->suites->suites[i] == peerSuites->suites[j] &&
  22670. ssl->suites->suites[i+1] == peerSuites->suites[j+1] ) {
  22671. if (VerifyServerSuite(ssl, i)) {
  22672. int result;
  22673. WOLFSSL_MSG("Verified suite validity");
  22674. ssl->options.cipherSuite0 = ssl->suites->suites[i];
  22675. ssl->options.cipherSuite = ssl->suites->suites[i+1];
  22676. result = SetCipherSpecs(ssl);
  22677. if (result == 0) {
  22678. result = PickHashSigAlgo(ssl, peerSuites->hashSigAlgo,
  22679. peerSuites->hashSigAlgoSz);
  22680. }
  22681. return result;
  22682. }
  22683. else {
  22684. WOLFSSL_MSG("Could not verify suite validity, continue");
  22685. }
  22686. }
  22687. return MATCH_SUITE_ERROR;
  22688. }
  22689. int MatchSuite(WOLFSSL* ssl, Suites* peerSuites)
  22690. {
  22691. int ret;
  22692. word16 i, j;
  22693. WOLFSSL_ENTER("MatchSuite");
  22694. /* & 0x1 equivalent % 2 */
  22695. if (peerSuites->suiteSz == 0 || peerSuites->suiteSz & 0x1)
  22696. return BUFFER_ERROR;
  22697. if (ssl->suites == NULL)
  22698. return SUITES_ERROR;
  22699. if (!ssl->options.useClientOrder) {
  22700. /* Server order */
  22701. for (i = 0; i < ssl->suites->suiteSz; i += 2) {
  22702. for (j = 0; j < peerSuites->suiteSz; j += 2) {
  22703. ret = CompareSuites(ssl, peerSuites, i, j);
  22704. if (ret != MATCH_SUITE_ERROR)
  22705. return ret;
  22706. }
  22707. }
  22708. }
  22709. else {
  22710. /* Client order */
  22711. for (j = 0; j < peerSuites->suiteSz; j += 2) {
  22712. for (i = 0; i < ssl->suites->suiteSz; i += 2) {
  22713. ret = CompareSuites(ssl, peerSuites, i, j);
  22714. if (ret != MATCH_SUITE_ERROR)
  22715. return ret;
  22716. }
  22717. }
  22718. }
  22719. return MATCH_SUITE_ERROR;
  22720. }
  22721. #endif
  22722. #ifdef OLD_HELLO_ALLOWED
  22723. /* process old style client hello, deprecate? */
  22724. int ProcessOldClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  22725. word32 inSz, word16 sz)
  22726. {
  22727. word32 idx = *inOutIdx;
  22728. word16 sessionSz;
  22729. word16 randomSz;
  22730. word16 i, j;
  22731. ProtocolVersion pv;
  22732. Suites clSuites;
  22733. int ret = -1;
  22734. (void)inSz;
  22735. WOLFSSL_MSG("Got old format client hello");
  22736. #ifdef WOLFSSL_CALLBACKS
  22737. if (ssl->hsInfoOn)
  22738. AddPacketName(ssl, "ClientHello");
  22739. if (ssl->toInfoOn)
  22740. AddLateName("ClientHello", &ssl->timeoutInfo);
  22741. #endif
  22742. /* manually hash input since different format */
  22743. #ifndef NO_OLD_TLS
  22744. #ifndef NO_MD5
  22745. wc_Md5Update(&ssl->hsHashes->hashMd5, input + idx, sz);
  22746. #endif
  22747. #ifndef NO_SHA
  22748. wc_ShaUpdate(&ssl->hsHashes->hashSha, input + idx, sz);
  22749. #endif
  22750. #endif
  22751. #ifndef NO_SHA256
  22752. if (IsAtLeastTLSv1_2(ssl)) {
  22753. int shaRet = wc_Sha256Update(&ssl->hsHashes->hashSha256,
  22754. input + idx, sz);
  22755. if (shaRet != 0)
  22756. return shaRet;
  22757. }
  22758. #endif
  22759. /* does this value mean client_hello? */
  22760. idx++;
  22761. /* version */
  22762. pv.major = input[idx++];
  22763. pv.minor = input[idx++];
  22764. ssl->chVersion = pv; /* store */
  22765. if (ssl->version.minor > pv.minor) {
  22766. byte haveRSA = 0;
  22767. byte havePSK = 0;
  22768. int keySz = 0;
  22769. if (!ssl->options.downgrade) {
  22770. WOLFSSL_MSG("Client trying to connect with lesser version");
  22771. return VERSION_ERROR;
  22772. }
  22773. if (pv.minor < ssl->options.minDowngrade) {
  22774. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  22775. return VERSION_ERROR;
  22776. }
  22777. if (pv.minor == SSLv3_MINOR) {
  22778. /* turn off tls */
  22779. WOLFSSL_MSG("\tdowngrading to SSLv3");
  22780. ssl->options.tls = 0;
  22781. ssl->options.tls1_1 = 0;
  22782. ssl->version.minor = SSLv3_MINOR;
  22783. }
  22784. else if (pv.minor == TLSv1_MINOR) {
  22785. WOLFSSL_MSG("\tdowngrading to TLSv1");
  22786. /* turn off tls 1.1+ */
  22787. ssl->options.tls1_1 = 0;
  22788. ssl->version.minor = TLSv1_MINOR;
  22789. }
  22790. else if (pv.minor == TLSv1_1_MINOR) {
  22791. WOLFSSL_MSG("\tdowngrading to TLSv1.1");
  22792. ssl->version.minor = TLSv1_1_MINOR;
  22793. }
  22794. else if (pv.minor == TLSv1_2_MINOR) {
  22795. WOLFSSL_MSG(" downgrading to TLSv1.2");
  22796. ssl->version.minor = TLSv1_2_MINOR;
  22797. }
  22798. #ifndef NO_RSA
  22799. haveRSA = 1;
  22800. #endif
  22801. #ifndef NO_PSK
  22802. havePSK = ssl->options.havePSK;
  22803. #endif
  22804. #ifndef NO_CERTS
  22805. keySz = ssl->buffers.keySz;
  22806. #endif
  22807. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
  22808. ssl->options.haveDH, ssl->options.haveNTRU,
  22809. ssl->options.haveECDSAsig, ssl->options.haveECC,
  22810. ssl->options.haveStaticECC, ssl->options.side);
  22811. }
  22812. /* suite size */
  22813. ato16(&input[idx], &clSuites.suiteSz);
  22814. idx += OPAQUE16_LEN;
  22815. if (clSuites.suiteSz > WOLFSSL_MAX_SUITE_SZ)
  22816. return BUFFER_ERROR;
  22817. clSuites.hashSigAlgoSz = 0;
  22818. /* session size */
  22819. ato16(&input[idx], &sessionSz);
  22820. idx += OPAQUE16_LEN;
  22821. if (sessionSz > ID_LEN)
  22822. return BUFFER_ERROR;
  22823. /* random size */
  22824. ato16(&input[idx], &randomSz);
  22825. idx += OPAQUE16_LEN;
  22826. if (randomSz > RAN_LEN)
  22827. return BUFFER_ERROR;
  22828. /* suites */
  22829. for (i = 0, j = 0; i < clSuites.suiteSz; i += 3) {
  22830. byte first = input[idx++];
  22831. if (!first) { /* implicit: skip sslv2 type */
  22832. XMEMCPY(&clSuites.suites[j], &input[idx], SUITE_LEN);
  22833. j += SUITE_LEN;
  22834. }
  22835. idx += SUITE_LEN;
  22836. }
  22837. clSuites.suiteSz = j;
  22838. /* session id */
  22839. if (sessionSz) {
  22840. XMEMCPY(ssl->arrays->sessionID, input + idx, sessionSz);
  22841. ssl->arrays->sessionIDSz = (byte)sessionSz;
  22842. idx += sessionSz;
  22843. ssl->options.resuming = 1;
  22844. }
  22845. /* random */
  22846. if (randomSz < RAN_LEN)
  22847. XMEMSET(ssl->arrays->clientRandom, 0, RAN_LEN - randomSz);
  22848. XMEMCPY(&ssl->arrays->clientRandom[RAN_LEN - randomSz], input + idx,
  22849. randomSz);
  22850. idx += randomSz;
  22851. if (ssl->options.usingCompression)
  22852. ssl->options.usingCompression = 0; /* turn off */
  22853. ssl->options.clientState = CLIENT_HELLO_COMPLETE;
  22854. ssl->cbmode = SSL_CB_MODE_WRITE;
  22855. *inOutIdx = idx;
  22856. ssl->options.haveSessionId = 1;
  22857. /* DoClientHello uses same resume code */
  22858. if (ssl->options.resuming) { /* let's try */
  22859. WOLFSSL_SESSION* session = GetSession(ssl,
  22860. ssl->arrays->masterSecret, 1);
  22861. #ifdef HAVE_SESSION_TICKET
  22862. if (ssl->options.useTicket == 1) {
  22863. session = &ssl->session;
  22864. }
  22865. #endif
  22866. if (!session) {
  22867. WOLFSSL_MSG("Session lookup for resume failed");
  22868. ssl->options.resuming = 0;
  22869. } else {
  22870. #ifdef HAVE_EXT_CACHE
  22871. wolfSSL_SESSION_free(session);
  22872. #endif
  22873. if (MatchSuite(ssl, &clSuites) < 0) {
  22874. WOLFSSL_MSG("Unsupported cipher suite, OldClientHello");
  22875. return UNSUPPORTED_SUITE;
  22876. }
  22877. ret = wc_RNG_GenerateBlock(ssl->rng, ssl->arrays->serverRandom,
  22878. RAN_LEN);
  22879. if (ret != 0)
  22880. return ret;
  22881. #ifdef NO_OLD_TLS
  22882. ret = DeriveTlsKeys(ssl);
  22883. #else
  22884. #ifndef NO_TLS
  22885. if (ssl->options.tls)
  22886. ret = DeriveTlsKeys(ssl);
  22887. #endif
  22888. if (!ssl->options.tls)
  22889. ret = DeriveKeys(ssl);
  22890. #endif
  22891. ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
  22892. return ret;
  22893. }
  22894. }
  22895. ret = MatchSuite(ssl, &clSuites);
  22896. if (ret != 0)return ret;
  22897. return SanityCheckMsgReceived(ssl, client_hello);
  22898. }
  22899. #endif /* OLD_HELLO_ALLOWED */
  22900. #ifndef WOLFSSL_NO_TLS12
  22901. int HandleTlsResumption(WOLFSSL* ssl, int bogusID, Suites* clSuites)
  22902. {
  22903. int ret = 0;
  22904. WOLFSSL_SESSION* session;
  22905. (void)bogusID;
  22906. session = GetSession(ssl, ssl->arrays->masterSecret, 1);
  22907. #ifdef HAVE_SESSION_TICKET
  22908. if (ssl->options.useTicket == 1) {
  22909. session = &ssl->session;
  22910. } else if (bogusID == 1 && ssl->options.rejectTicket == 0) {
  22911. WOLFSSL_MSG("Bogus session ID without session ticket");
  22912. return BUFFER_ERROR;
  22913. }
  22914. #endif
  22915. if (!session) {
  22916. WOLFSSL_MSG("Session lookup for resume failed");
  22917. ssl->options.resuming = 0;
  22918. }
  22919. else if (session->haveEMS != ssl->options.haveEMS) {
  22920. /* RFC 7627, 5.3, server-side */
  22921. /* if old sess didn't have EMS, but new does, full handshake */
  22922. if (!session->haveEMS && ssl->options.haveEMS) {
  22923. WOLFSSL_MSG("Attempting to resume a session that didn't "
  22924. "use EMS with a new session with EMS. Do full "
  22925. "handshake.");
  22926. ssl->options.resuming = 0;
  22927. }
  22928. /* if old sess used EMS, but new doesn't, MUST abort */
  22929. else if (session->haveEMS && !ssl->options.haveEMS) {
  22930. WOLFSSL_MSG("Trying to resume a session with EMS without "
  22931. "using EMS");
  22932. #ifdef WOLFSSL_EXTRA_ALERTS
  22933. SendAlert(ssl, alert_fatal, handshake_failure);
  22934. #endif
  22935. return EXT_MASTER_SECRET_NEEDED_E;
  22936. }
  22937. #ifdef HAVE_EXT_CACHE
  22938. wolfSSL_SESSION_free(session);
  22939. #endif
  22940. }
  22941. else {
  22942. #ifndef NO_RESUME_SUITE_CHECK
  22943. int j;
  22944. /* Check client suites include the one in session */
  22945. for (j = 0; j < clSuites->suiteSz; j += 2) {
  22946. if (clSuites->suites[j] == session->cipherSuite0 &&
  22947. clSuites->suites[j+1] == session->cipherSuite) {
  22948. break;
  22949. }
  22950. }
  22951. if (j == clSuites->suiteSz) {
  22952. WOLFSSL_MSG("Prev session's cipher suite not in ClientHello");
  22953. #ifdef WOLFSSL_EXTRA_ALERTS
  22954. SendAlert(ssl, alert_fatal, illegal_parameter);
  22955. #endif
  22956. return UNSUPPORTED_SUITE;
  22957. }
  22958. #endif
  22959. #ifdef HAVE_EXT_CACHE
  22960. wolfSSL_SESSION_free(session);
  22961. #endif
  22962. if (MatchSuite(ssl, clSuites) < 0) {
  22963. WOLFSSL_MSG("Unsupported cipher suite, ClientHello");
  22964. return UNSUPPORTED_SUITE;
  22965. }
  22966. ret = wc_RNG_GenerateBlock(ssl->rng, ssl->arrays->serverRandom,
  22967. RAN_LEN);
  22968. if (ret != 0)
  22969. return ret;
  22970. #ifdef NO_OLD_TLS
  22971. ret = DeriveTlsKeys(ssl);
  22972. #else
  22973. #ifndef NO_TLS
  22974. if (ssl->options.tls)
  22975. ret = DeriveTlsKeys(ssl);
  22976. #endif
  22977. if (!ssl->options.tls)
  22978. ret = DeriveKeys(ssl);
  22979. #endif
  22980. ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
  22981. }
  22982. return ret;
  22983. }
  22984. /* handle processing of client_hello (1) */
  22985. int DoClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
  22986. word32 helloSz)
  22987. {
  22988. byte b;
  22989. byte bogusID = 0; /* flag for a bogus session id */
  22990. ProtocolVersion pv;
  22991. Suites clSuites;
  22992. word32 i = *inOutIdx;
  22993. word32 begin = i;
  22994. int ret = 0;
  22995. #ifdef WOLFSSL_DTLS
  22996. Hmac cookieHmac;
  22997. byte peerCookie[MAX_COOKIE_LEN];
  22998. byte peerCookieSz = 0;
  22999. byte cookieType;
  23000. byte cookieSz = 0;
  23001. XMEMSET(&cookieHmac, 0, sizeof(Hmac));
  23002. #endif /* WOLFSSL_DTLS */
  23003. WOLFSSL_START(WC_FUNC_CLIENT_HELLO_DO);
  23004. WOLFSSL_ENTER("DoClientHello");
  23005. #ifdef WOLFSSL_CALLBACKS
  23006. if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
  23007. if (ssl->toInfoOn) AddLateName("ClientHello", &ssl->timeoutInfo);
  23008. #endif
  23009. /* protocol version, random and session id length check */
  23010. if (OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz)
  23011. return BUFFER_ERROR;
  23012. /* protocol version */
  23013. XMEMCPY(&pv, input + i, OPAQUE16_LEN);
  23014. ssl->chVersion = pv; /* store */
  23015. #ifdef WOLFSSL_DTLS
  23016. if (IsDtlsNotSctpMode(ssl)) {
  23017. #if defined(NO_SHA) && defined(NO_SHA256)
  23018. #error "DTLS needs either SHA or SHA-256"
  23019. #endif /* NO_SHA && NO_SHA256 */
  23020. #if !defined(NO_SHA) && defined(NO_SHA256)
  23021. cookieType = WC_SHA;
  23022. cookieSz = WC_SHA_DIGEST_SIZE;
  23023. #endif /* NO_SHA */
  23024. #ifndef NO_SHA256
  23025. cookieType = WC_SHA256;
  23026. cookieSz = WC_SHA256_DIGEST_SIZE;
  23027. #endif /* NO_SHA256 */
  23028. ret = wc_HmacSetKey(&cookieHmac, cookieType,
  23029. ssl->buffers.dtlsCookieSecret.buffer,
  23030. ssl->buffers.dtlsCookieSecret.length);
  23031. if (ret != 0) return ret;
  23032. ret = wc_HmacUpdate(&cookieHmac,
  23033. (const byte*)ssl->buffers.dtlsCtx.peer.sa,
  23034. ssl->buffers.dtlsCtx.peer.sz);
  23035. if (ret != 0) return ret;
  23036. ret = wc_HmacUpdate(&cookieHmac, input + i, OPAQUE16_LEN);
  23037. if (ret != 0) return ret;
  23038. }
  23039. #endif /* WOLFSSL_DTLS */
  23040. i += OPAQUE16_LEN;
  23041. /* Legacy protocol version cannot negotiate TLS 1.3 or higher. */
  23042. if (pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_3_MINOR)
  23043. pv.minor = TLSv1_2_MINOR;
  23044. if ((!ssl->options.dtls && ssl->version.minor > pv.minor) ||
  23045. (ssl->options.dtls && ssl->version.minor != DTLS_MINOR
  23046. && ssl->version.minor != DTLSv1_2_MINOR && pv.minor != DTLS_MINOR
  23047. && pv.minor != DTLSv1_2_MINOR)) {
  23048. word16 haveRSA = 0;
  23049. word16 havePSK = 0;
  23050. int keySz = 0;
  23051. if (!ssl->options.downgrade) {
  23052. WOLFSSL_MSG("Client trying to connect with lesser version");
  23053. return VERSION_ERROR;
  23054. }
  23055. if (pv.minor < ssl->options.minDowngrade) {
  23056. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  23057. return VERSION_ERROR;
  23058. }
  23059. if (pv.minor == SSLv3_MINOR) {
  23060. /* turn off tls */
  23061. WOLFSSL_MSG("\tdowngrading to SSLv3");
  23062. ssl->options.tls = 0;
  23063. ssl->options.tls1_1 = 0;
  23064. ssl->version.minor = SSLv3_MINOR;
  23065. }
  23066. else if (pv.minor == TLSv1_MINOR) {
  23067. /* turn off tls 1.1+ */
  23068. WOLFSSL_MSG("\tdowngrading to TLSv1");
  23069. ssl->options.tls1_1 = 0;
  23070. ssl->version.minor = TLSv1_MINOR;
  23071. }
  23072. else if (pv.minor == TLSv1_1_MINOR) {
  23073. WOLFSSL_MSG("\tdowngrading to TLSv1.1");
  23074. ssl->version.minor = TLSv1_1_MINOR;
  23075. }
  23076. else if (pv.minor == TLSv1_2_MINOR) {
  23077. WOLFSSL_MSG(" downgrading to TLSv1.2");
  23078. ssl->version.minor = TLSv1_2_MINOR;
  23079. }
  23080. #ifndef NO_RSA
  23081. haveRSA = 1;
  23082. #endif
  23083. #ifndef NO_PSK
  23084. havePSK = ssl->options.havePSK;
  23085. #endif
  23086. #ifndef NO_CERTS
  23087. keySz = ssl->buffers.keySz;
  23088. #endif
  23089. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
  23090. ssl->options.haveDH, ssl->options.haveNTRU,
  23091. ssl->options.haveECDSAsig, ssl->options.haveECC,
  23092. ssl->options.haveStaticECC, ssl->options.side);
  23093. }
  23094. #ifdef OPENSSL_EXTRA
  23095. /* check if option is set to not allow the current version
  23096. * set from either wolfSSL_set_options or wolfSSL_CTX_set_options */
  23097. if (!ssl->options.dtls && ssl->options.downgrade &&
  23098. ssl->options.mask > 0) {
  23099. int reset = 0;
  23100. if (ssl->version.minor == TLSv1_2_MINOR &&
  23101. (ssl->options.mask & SSL_OP_NO_TLSv1_2) == SSL_OP_NO_TLSv1_2) {
  23102. WOLFSSL_MSG("\tOption set to not allow TLSv1.2, Downgrading");
  23103. ssl->version.minor = TLSv1_1_MINOR;
  23104. reset = 1;
  23105. }
  23106. if (ssl->version.minor == TLSv1_1_MINOR &&
  23107. (ssl->options.mask & SSL_OP_NO_TLSv1_1) == SSL_OP_NO_TLSv1_1) {
  23108. WOLFSSL_MSG("\tOption set to not allow TLSv1.1, Downgrading");
  23109. ssl->options.tls1_1 = 0;
  23110. ssl->version.minor = TLSv1_MINOR;
  23111. reset = 1;
  23112. }
  23113. if (ssl->version.minor == TLSv1_MINOR &&
  23114. (ssl->options.mask & SSL_OP_NO_TLSv1) == SSL_OP_NO_TLSv1) {
  23115. WOLFSSL_MSG("\tOption set to not allow TLSv1, Downgrading");
  23116. ssl->options.tls = 0;
  23117. ssl->options.tls1_1 = 0;
  23118. ssl->version.minor = SSLv3_MINOR;
  23119. reset = 1;
  23120. }
  23121. if (ssl->version.minor == SSLv3_MINOR &&
  23122. (ssl->options.mask & SSL_OP_NO_SSLv3) == SSL_OP_NO_SSLv3) {
  23123. WOLFSSL_MSG("\tError, option set to not allow SSLv3");
  23124. return VERSION_ERROR;
  23125. }
  23126. if (ssl->version.minor < ssl->options.minDowngrade) {
  23127. WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
  23128. return VERSION_ERROR;
  23129. }
  23130. if (reset) {
  23131. word16 haveRSA = 0;
  23132. word16 havePSK = 0;
  23133. int keySz = 0;
  23134. #ifndef NO_RSA
  23135. haveRSA = 1;
  23136. #endif
  23137. #ifndef NO_PSK
  23138. havePSK = ssl->options.havePSK;
  23139. #endif
  23140. #ifndef NO_CERTS
  23141. keySz = ssl->buffers.keySz;
  23142. #endif
  23143. /* reset cipher suites to account for TLS version change */
  23144. InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
  23145. ssl->options.haveDH, ssl->options.haveNTRU,
  23146. ssl->options.haveECDSAsig, ssl->options.haveECC,
  23147. ssl->options.haveStaticECC, ssl->options.side);
  23148. }
  23149. }
  23150. #endif
  23151. /* random */
  23152. XMEMCPY(ssl->arrays->clientRandom, input + i, RAN_LEN);
  23153. #ifdef WOLFSSL_DTLS
  23154. if (IsDtlsNotSctpMode(ssl)) {
  23155. ret = wc_HmacUpdate(&cookieHmac, input + i, RAN_LEN);
  23156. if (ret != 0) return ret;
  23157. }
  23158. #endif /* WOLFSSL_DTLS */
  23159. i += RAN_LEN;
  23160. #ifdef SHOW_SECRETS
  23161. {
  23162. int j;
  23163. printf("client random: ");
  23164. for (j = 0; j < RAN_LEN; j++)
  23165. printf("%02x", ssl->arrays->clientRandom[j]);
  23166. printf("\n");
  23167. }
  23168. #endif
  23169. /* session id */
  23170. b = input[i++];
  23171. #ifdef HAVE_SESSION_TICKET
  23172. if (b > 0 && b < ID_LEN) {
  23173. bogusID = 1;
  23174. WOLFSSL_MSG("Client sent bogus session id, let's allow for echo");
  23175. }
  23176. #endif
  23177. if (b == ID_LEN || bogusID) {
  23178. if ((i - begin) + b > helloSz)
  23179. return BUFFER_ERROR;
  23180. XMEMCPY(ssl->arrays->sessionID, input + i, b);
  23181. #ifdef WOLFSSL_DTLS
  23182. if (IsDtlsNotSctpMode(ssl)) {
  23183. ret = wc_HmacUpdate(&cookieHmac, input + i - 1, b + 1);
  23184. if (ret != 0) return ret;
  23185. }
  23186. #endif /* WOLFSSL_DTLS */
  23187. ssl->arrays->sessionIDSz = b;
  23188. i += b;
  23189. ssl->options.resuming = 1; /* client wants to resume */
  23190. WOLFSSL_MSG("Client wants to resume session");
  23191. }
  23192. else if (b) {
  23193. WOLFSSL_MSG("Invalid session ID size");
  23194. return BUFFER_ERROR; /* session ID nor 0 neither 32 bytes long */
  23195. }
  23196. #ifdef WOLFSSL_DTLS
  23197. /* cookie */
  23198. if (ssl->options.dtls) {
  23199. if ((i - begin) + OPAQUE8_LEN > helloSz)
  23200. return BUFFER_ERROR;
  23201. peerCookieSz = input[i++];
  23202. if (peerCookieSz) {
  23203. if (peerCookieSz > MAX_COOKIE_LEN)
  23204. return BUFFER_ERROR;
  23205. if ((i - begin) + peerCookieSz > helloSz)
  23206. return BUFFER_ERROR;
  23207. XMEMCPY(peerCookie, input + i, peerCookieSz);
  23208. i += peerCookieSz;
  23209. }
  23210. }
  23211. #endif
  23212. /* suites */
  23213. if ((i - begin) + OPAQUE16_LEN > helloSz)
  23214. return BUFFER_ERROR;
  23215. ato16(&input[i], &clSuites.suiteSz);
  23216. i += OPAQUE16_LEN;
  23217. /* suites and compression length check */
  23218. if ((i - begin) + clSuites.suiteSz + OPAQUE8_LEN > helloSz)
  23219. return BUFFER_ERROR;
  23220. if (clSuites.suiteSz > WOLFSSL_MAX_SUITE_SZ)
  23221. return BUFFER_ERROR;
  23222. XMEMCPY(clSuites.suites, input + i, clSuites.suiteSz);
  23223. #ifdef HAVE_SERVER_RENEGOTIATION_INFO
  23224. /* check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV suite */
  23225. if (FindSuite(&clSuites, 0, TLS_EMPTY_RENEGOTIATION_INFO_SCSV) >= 0) {
  23226. TLSX* extension;
  23227. /* check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV suite */
  23228. ret = TLSX_AddEmptyRenegotiationInfo(&ssl->extensions, ssl->heap);
  23229. if (ret != WOLFSSL_SUCCESS)
  23230. return ret;
  23231. extension = TLSX_Find(ssl->extensions, TLSX_RENEGOTIATION_INFO);
  23232. if (extension) {
  23233. ssl->secure_renegotiation =
  23234. (SecureRenegotiation*)extension->data;
  23235. ssl->secure_renegotiation->enabled = 1;
  23236. }
  23237. }
  23238. #endif /* HAVE_SERVER_RENEGOTIATION_INFO */
  23239. #if defined(HAVE_FALLBACK_SCSV) || defined(OPENSSL_ALL)
  23240. /* check for TLS_FALLBACK_SCSV suite */
  23241. if (FindSuite(&clSuites, TLS_FALLBACK_SCSV, 0) >= 0) {
  23242. WOLFSSL_MSG("Found Fallback SCSV");
  23243. if (ssl->ctx->method->version.minor > pv.minor) {
  23244. WOLFSSL_MSG("Client trying to connect with lesser version");
  23245. SendAlert(ssl, alert_fatal, inappropriate_fallback);
  23246. return VERSION_ERROR;
  23247. }
  23248. }
  23249. #endif
  23250. #ifdef WOLFSSL_DTLS
  23251. if (IsDtlsNotSctpMode(ssl)) {
  23252. ret = wc_HmacUpdate(&cookieHmac,
  23253. input + i - OPAQUE16_LEN,
  23254. clSuites.suiteSz + OPAQUE16_LEN);
  23255. if (ret != 0) return ret;
  23256. }
  23257. #endif /* WOLFSSL_DTLS */
  23258. i += clSuites.suiteSz;
  23259. clSuites.hashSigAlgoSz = 0;
  23260. /* compression length */
  23261. b = input[i++];
  23262. if ((i - begin) + b > helloSz)
  23263. return BUFFER_ERROR;
  23264. if (b == 0) {
  23265. WOLFSSL_MSG("No compression types in list");
  23266. #ifdef WOLFSSL_EXTRA_ALERTS
  23267. SendAlert(ssl, alert_fatal, decode_error);
  23268. #endif
  23269. return COMPRESSION_ERROR;
  23270. }
  23271. #ifdef WOLFSSL_DTLS
  23272. if (IsDtlsNotSctpMode(ssl)) {
  23273. byte newCookie[MAX_COOKIE_LEN];
  23274. ret = wc_HmacUpdate(&cookieHmac, input + i - 1, b + 1);
  23275. if (ret != 0) return ret;
  23276. ret = wc_HmacFinal(&cookieHmac, newCookie);
  23277. if (ret != 0) return ret;
  23278. /* If a cookie callback is set, call it to overwrite the cookie.
  23279. * This should be deprecated. The code now calculates the cookie
  23280. * using an HMAC as expected. */
  23281. if (ssl->ctx->CBIOCookie != NULL &&
  23282. ssl->ctx->CBIOCookie(ssl, newCookie, cookieSz,
  23283. ssl->IOCB_CookieCtx) != cookieSz) {
  23284. return COOKIE_ERROR;
  23285. }
  23286. /* Check the cookie, see if we progress the state machine. */
  23287. if (peerCookieSz != cookieSz ||
  23288. XMEMCMP(peerCookie, newCookie, cookieSz) != 0) {
  23289. /* Send newCookie to client in a HelloVerifyRequest message
  23290. * and let the state machine alone. */
  23291. ssl->msgsReceived.got_client_hello = 0;
  23292. ssl->keys.dtls_handshake_number = 0;
  23293. ssl->keys.dtls_expected_peer_handshake_number = 0;
  23294. *inOutIdx += helloSz;
  23295. return SendHelloVerifyRequest(ssl, newCookie, cookieSz);
  23296. }
  23297. /* This was skipped in the DTLS case so we could handle the hello
  23298. * verify request. */
  23299. ret = HashInput(ssl, input + *inOutIdx, helloSz);
  23300. if (ret != 0) return ret;
  23301. }
  23302. #endif /* WOLFSSL_DTLS */
  23303. {
  23304. /* compression match types */
  23305. int matchNo = 0;
  23306. int matchZlib = 0;
  23307. while (b--) {
  23308. byte comp = input[i++];
  23309. if (comp == NO_COMPRESSION) {
  23310. matchNo = 1;
  23311. }
  23312. if (comp == ZLIB_COMPRESSION) {
  23313. matchZlib = 1;
  23314. }
  23315. }
  23316. if (ssl->options.usingCompression == 0 && matchNo) {
  23317. WOLFSSL_MSG("Matched No Compression");
  23318. } else if (ssl->options.usingCompression && matchZlib) {
  23319. WOLFSSL_MSG("Matched zlib Compression");
  23320. } else if (ssl->options.usingCompression && matchNo) {
  23321. WOLFSSL_MSG("Could only match no compression, turning off");
  23322. ssl->options.usingCompression = 0; /* turn off */
  23323. } else {
  23324. WOLFSSL_MSG("Could not match compression");
  23325. #ifdef WOLFSSL_EXTRA_ALERTS
  23326. SendAlert(ssl, alert_fatal, illegal_parameter);
  23327. #endif
  23328. return COMPRESSION_ERROR;
  23329. }
  23330. }
  23331. *inOutIdx = i;
  23332. /* tls extensions */
  23333. if ((i - begin) < helloSz) {
  23334. #ifdef HAVE_TLS_EXTENSIONS
  23335. #ifdef HAVE_QSH
  23336. QSH_Init(ssl);
  23337. #endif
  23338. if (TLSX_SupportExtensions(ssl))
  23339. #else
  23340. if (IsAtLeastTLSv1_2(ssl))
  23341. #endif
  23342. {
  23343. /* Process the hello extension. Skip unsupported. */
  23344. word16 totalExtSz;
  23345. #ifdef HAVE_TLS_EXTENSIONS
  23346. /* auto populate extensions supported unless user defined */
  23347. if ((ret = TLSX_PopulateExtensions(ssl, 1)) != 0)
  23348. return ret;
  23349. #endif
  23350. if ((i - begin) + OPAQUE16_LEN > helloSz)
  23351. return BUFFER_ERROR;
  23352. ato16(&input[i], &totalExtSz);
  23353. i += OPAQUE16_LEN;
  23354. if ((i - begin) + totalExtSz > helloSz)
  23355. return BUFFER_ERROR;
  23356. #ifdef HAVE_TLS_EXTENSIONS
  23357. /* tls extensions */
  23358. if ((ret = TLSX_Parse(ssl, (byte *) input + i, totalExtSz,
  23359. client_hello, &clSuites)))
  23360. return ret;
  23361. #ifdef WOLFSSL_TLS13
  23362. if (TLSX_Find(ssl->extensions,
  23363. TLSX_SUPPORTED_VERSIONS) != NULL) {
  23364. WOLFSSL_MSG(
  23365. "Client attempting to connect with higher version");
  23366. return VERSION_ERROR;
  23367. }
  23368. #endif
  23369. #if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  23370. if((ret=SNI_Callback(ssl)))
  23371. return ret;
  23372. ssl->options.side = WOLFSSL_SERVER_END;
  23373. #endif
  23374. i += totalExtSz;
  23375. #else
  23376. while (totalExtSz) {
  23377. word16 extId, extSz;
  23378. if (OPAQUE16_LEN + OPAQUE16_LEN > totalExtSz)
  23379. return BUFFER_ERROR;
  23380. ato16(&input[i], &extId);
  23381. i += OPAQUE16_LEN;
  23382. ato16(&input[i], &extSz);
  23383. i += OPAQUE16_LEN;
  23384. if (OPAQUE16_LEN + OPAQUE16_LEN + extSz > totalExtSz)
  23385. return BUFFER_ERROR;
  23386. if (extId == HELLO_EXT_SIG_ALGO) {
  23387. word16 hashSigAlgoSz;
  23388. ato16(&input[i], &hashSigAlgoSz);
  23389. i += OPAQUE16_LEN;
  23390. if (OPAQUE16_LEN + hashSigAlgoSz > extSz)
  23391. return BUFFER_ERROR;
  23392. clSuites.hashSigAlgoSz = hashSigAlgoSz;
  23393. if (clSuites.hashSigAlgoSz > WOLFSSL_MAX_SIGALGO) {
  23394. WOLFSSL_MSG("ClientHello SigAlgo list exceeds max, "
  23395. "truncating");
  23396. clSuites.hashSigAlgoSz = WOLFSSL_MAX_SIGALGO;
  23397. }
  23398. XMEMCPY(clSuites.hashSigAlgo, &input[i],
  23399. clSuites.hashSigAlgoSz);
  23400. i += hashSigAlgoSz;
  23401. }
  23402. #ifdef HAVE_EXTENDED_MASTER
  23403. else if (extId == HELLO_EXT_EXTMS)
  23404. ssl->options.haveEMS = 1;
  23405. #endif
  23406. else
  23407. i += extSz;
  23408. totalExtSz -= OPAQUE16_LEN + OPAQUE16_LEN + extSz;
  23409. }
  23410. #endif
  23411. *inOutIdx = i;
  23412. }
  23413. else
  23414. *inOutIdx = begin + helloSz; /* skip extensions */
  23415. }
  23416. ssl->options.clientState = CLIENT_HELLO_COMPLETE;
  23417. ssl->options.haveSessionId = 1;
  23418. /* ProcessOld uses same resume code */
  23419. if (ssl->options.resuming) {
  23420. ret = HandleTlsResumption(ssl, bogusID, &clSuites);
  23421. if (ret != 0)
  23422. return ret;
  23423. #ifdef HAVE_SECURE_RENEGOTIATION
  23424. if (ssl->secure_renegotiation &&
  23425. ssl->secure_renegotiation->enabled &&
  23426. IsEncryptionOn(ssl, 0))
  23427. ssl->secure_renegotiation->startScr = 1;
  23428. #endif
  23429. if (ssl->options.clientState == CLIENT_KEYEXCHANGE_COMPLETE) {
  23430. WOLFSSL_LEAVE("DoClientHello", ret);
  23431. WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
  23432. return ret;
  23433. }
  23434. }
  23435. #if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_DH_DEFAULT_PARAMS)
  23436. #if defined(HAVE_FFDHE) && defined(HAVE_SUPPORTED_CURVES)
  23437. if (TLSX_Find(ssl->extensions, TLSX_SUPPORTED_GROUPS) != NULL) {
  23438. /* Set FFDHE parameters or clear DHE parameters if FFDH parameters
  23439. * present and no matches in the server's list. */
  23440. ret = TLSX_SupportedFFDHE_Set(ssl);
  23441. if (ret != 0)
  23442. return ret;
  23443. }
  23444. #endif
  23445. #endif
  23446. ret = MatchSuite(ssl, &clSuites);
  23447. #ifdef WOLFSSL_EXTRA_ALERTS
  23448. if (ret == BUFFER_ERROR)
  23449. SendAlert(ssl, alert_fatal, decode_error);
  23450. else if (ret < 0)
  23451. SendAlert(ssl, alert_fatal, handshake_failure);
  23452. #endif
  23453. #ifdef HAVE_SECURE_RENEGOTIATION
  23454. if (ssl->secure_renegotiation && ssl->secure_renegotiation->enabled &&
  23455. IsEncryptionOn(ssl, 0)) {
  23456. ssl->secure_renegotiation->startScr = 1;
  23457. }
  23458. #endif
  23459. WOLFSSL_LEAVE("DoClientHello", ret);
  23460. WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
  23461. return ret;
  23462. }
  23463. #if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
  23464. defined(HAVE_ED448)) && !defined(WOLFSSL_NO_CLIENT_AUTH)
  23465. typedef struct DcvArgs {
  23466. byte* output; /* not allocated */
  23467. word32 sendSz;
  23468. word16 sz;
  23469. word32 sigSz;
  23470. word32 idx;
  23471. word32 begin;
  23472. byte hashAlgo;
  23473. byte sigAlgo;
  23474. } DcvArgs;
  23475. static void FreeDcvArgs(WOLFSSL* ssl, void* pArgs)
  23476. {
  23477. DcvArgs* args = (DcvArgs*)pArgs;
  23478. (void)ssl;
  23479. (void)args;
  23480. }
  23481. /* handle processing of certificate_verify (15) */
  23482. static int DoCertificateVerify(WOLFSSL* ssl, byte* input,
  23483. word32* inOutIdx, word32 size)
  23484. {
  23485. int ret = 0;
  23486. #ifdef WOLFSSL_ASYNC_CRYPT
  23487. DcvArgs* args = (DcvArgs*)ssl->async.args;
  23488. typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
  23489. (void)sizeof(args_test);
  23490. #else
  23491. DcvArgs args[1];
  23492. #endif
  23493. WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_DO);
  23494. WOLFSSL_ENTER("DoCertificateVerify");
  23495. #ifdef WOLFSSL_ASYNC_CRYPT
  23496. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  23497. if (ret != WC_NOT_PENDING_E) {
  23498. /* Check for error */
  23499. if (ret < 0)
  23500. goto exit_dcv;
  23501. }
  23502. else
  23503. #endif
  23504. {
  23505. /* Reset state */
  23506. ret = 0;
  23507. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  23508. XMEMSET(args, 0, sizeof(DcvArgs));
  23509. args->hashAlgo = sha_mac;
  23510. args->sigAlgo = anonymous_sa_algo;
  23511. args->idx = *inOutIdx;
  23512. args->begin = *inOutIdx;
  23513. #ifdef WOLFSSL_ASYNC_CRYPT
  23514. ssl->async.freeArgs = FreeDcvArgs;
  23515. #endif
  23516. }
  23517. switch(ssl->options.asyncState)
  23518. {
  23519. case TLS_ASYNC_BEGIN:
  23520. {
  23521. #ifdef WOLFSSL_CALLBACKS
  23522. if (ssl->hsInfoOn)
  23523. AddPacketName(ssl, "CertificateVerify");
  23524. if (ssl->toInfoOn)
  23525. AddLateName("CertificateVerify", &ssl->timeoutInfo);
  23526. #endif
  23527. /* Advance state and proceed */
  23528. ssl->options.asyncState = TLS_ASYNC_BUILD;
  23529. } /* case TLS_ASYNC_BEGIN */
  23530. FALL_THROUGH;
  23531. case TLS_ASYNC_BUILD:
  23532. {
  23533. if (IsAtLeastTLSv1_2(ssl)) {
  23534. if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN > size) {
  23535. ERROR_OUT(BUFFER_ERROR, exit_dcv);
  23536. }
  23537. DecodeSigAlg(&input[args->idx], &args->hashAlgo,
  23538. &args->sigAlgo);
  23539. args->idx += 2;
  23540. }
  23541. #ifndef NO_RSA
  23542. else if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0)
  23543. args->sigAlgo = rsa_sa_algo;
  23544. #endif
  23545. #ifdef HAVE_ECC
  23546. else if (ssl->peerEccDsaKeyPresent)
  23547. args->sigAlgo = ecc_dsa_sa_algo;
  23548. #endif
  23549. #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
  23550. else if (ssl->peerEd25519KeyPresent)
  23551. args->sigAlgo = ed25519_sa_algo;
  23552. #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
  23553. #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
  23554. else if (ssl->peerEd448KeyPresent)
  23555. args->sigAlgo = ed448_sa_algo;
  23556. #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
  23557. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  23558. ERROR_OUT(BUFFER_ERROR, exit_dcv);
  23559. }
  23560. ato16(input + args->idx, &args->sz);
  23561. args->idx += OPAQUE16_LEN;
  23562. if ((args->idx - args->begin) + args->sz > size ||
  23563. args->sz > ENCRYPT_LEN) {
  23564. ERROR_OUT(BUFFER_ERROR, exit_dcv);
  23565. }
  23566. #ifdef HAVE_ECC
  23567. if (ssl->peerEccDsaKeyPresent) {
  23568. WOLFSSL_MSG("Doing ECC peer cert verify");
  23569. /* make sure a default is defined */
  23570. #if !defined(NO_SHA)
  23571. SetDigest(ssl, sha_mac);
  23572. #elif !defined(NO_SHA256)
  23573. SetDigest(ssl, sha256_mac);
  23574. #elif defined(WOLFSSL_SHA384)
  23575. SetDigest(ssl, sha384_mac);
  23576. #elif defined(WOLFSSL_SHA512)
  23577. SetDigest(ssl, sha512_mac);
  23578. #else
  23579. #error No digest enabled for ECC sig verify
  23580. #endif
  23581. if (IsAtLeastTLSv1_2(ssl)) {
  23582. if (args->sigAlgo != ecc_dsa_sa_algo) {
  23583. WOLFSSL_MSG("Oops, peer sent ECC key but not in verify");
  23584. }
  23585. SetDigest(ssl, args->hashAlgo);
  23586. }
  23587. }
  23588. #endif /* HAVE_ECC */
  23589. #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
  23590. if (ssl->peerEd25519KeyPresent) {
  23591. WOLFSSL_MSG("Doing ED25519 peer cert verify");
  23592. if (IsAtLeastTLSv1_2(ssl) &&
  23593. args->sigAlgo != ed25519_sa_algo) {
  23594. WOLFSSL_MSG(
  23595. "Oops, peer sent ED25519 key but not in verify");
  23596. }
  23597. }
  23598. #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
  23599. #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
  23600. if (ssl->peerEd448KeyPresent) {
  23601. WOLFSSL_MSG("Doing ED448 peer cert verify");
  23602. if (IsAtLeastTLSv1_2(ssl) &&
  23603. args->sigAlgo != ed448_sa_algo) {
  23604. WOLFSSL_MSG(
  23605. "Oops, peer sent ED448 key but not in verify");
  23606. }
  23607. }
  23608. #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
  23609. /* Advance state and proceed */
  23610. ssl->options.asyncState = TLS_ASYNC_DO;
  23611. } /* case TLS_ASYNC_BUILD */
  23612. FALL_THROUGH;
  23613. case TLS_ASYNC_DO:
  23614. {
  23615. #ifndef NO_RSA
  23616. if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
  23617. WOLFSSL_MSG("Doing RSA peer cert verify");
  23618. ret = RsaVerify(ssl,
  23619. input + args->idx,
  23620. args->sz,
  23621. &args->output,
  23622. args->sigAlgo, args->hashAlgo,
  23623. ssl->peerRsaKey,
  23624. #ifdef HAVE_PK_CALLBACKS
  23625. &ssl->buffers.peerRsaKey
  23626. #else
  23627. NULL
  23628. #endif
  23629. );
  23630. if (ret >= 0) {
  23631. if (args->sigAlgo == rsa_sa_algo)
  23632. args->sendSz = ret;
  23633. else {
  23634. args->sigSz = ret;
  23635. args->sendSz = ssl->buffers.digest.length;
  23636. }
  23637. ret = 0;
  23638. }
  23639. }
  23640. #endif /* !NO_RSA */
  23641. #ifdef HAVE_ECC
  23642. if (ssl->peerEccDsaKeyPresent) {
  23643. WOLFSSL_MSG("Doing ECC peer cert verify");
  23644. ret = EccVerify(ssl,
  23645. input + args->idx, args->sz,
  23646. ssl->buffers.digest.buffer, ssl->buffers.digest.length,
  23647. ssl->peerEccDsaKey,
  23648. #ifdef HAVE_PK_CALLBACKS
  23649. &ssl->buffers.peerEccDsaKey
  23650. #else
  23651. NULL
  23652. #endif
  23653. );
  23654. }
  23655. #endif /* HAVE_ECC */
  23656. #if defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)
  23657. if (ssl->peerEd25519KeyPresent) {
  23658. WOLFSSL_MSG("Doing Ed25519 peer cert verify");
  23659. ret = Ed25519Verify(ssl,
  23660. input + args->idx, args->sz,
  23661. ssl->hsHashes->messages, ssl->hsHashes->prevLen,
  23662. ssl->peerEd25519Key,
  23663. #ifdef HAVE_PK_CALLBACKS
  23664. &ssl->buffers.peerEd25519Key
  23665. #else
  23666. NULL
  23667. #endif
  23668. );
  23669. }
  23670. #endif /* HAVE_ED25519 && !NO_ED25519_CLIENT_AUTH */
  23671. #if defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)
  23672. if (ssl->peerEd448KeyPresent) {
  23673. WOLFSSL_MSG("Doing Ed448 peer cert verify");
  23674. ret = Ed448Verify(ssl,
  23675. input + args->idx, args->sz,
  23676. ssl->hsHashes->messages, ssl->hsHashes->prevLen,
  23677. ssl->peerEd448Key,
  23678. #ifdef HAVE_PK_CALLBACKS
  23679. &ssl->buffers.peerEd448Key
  23680. #else
  23681. NULL
  23682. #endif
  23683. );
  23684. }
  23685. #endif /* HAVE_ED448 && !NO_ED448_CLIENT_AUTH */
  23686. #ifdef WOLFSSL_ASYNC_CRYPT
  23687. /* handle async pending */
  23688. if (ret == WC_PENDING_E)
  23689. goto exit_dcv;
  23690. #endif
  23691. /* Check for error */
  23692. if (ret != 0) {
  23693. ret = SIG_VERIFY_E;
  23694. goto exit_dcv;
  23695. }
  23696. /* Advance state and proceed */
  23697. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  23698. } /* case TLS_ASYNC_DO */
  23699. FALL_THROUGH;
  23700. case TLS_ASYNC_VERIFY:
  23701. {
  23702. #ifndef NO_RSA
  23703. if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
  23704. if (IsAtLeastTLSv1_2(ssl)) {
  23705. #ifdef WC_RSA_PSS
  23706. if (args->sigAlgo == rsa_pss_sa_algo) {
  23707. SetDigest(ssl, args->hashAlgo);
  23708. #ifdef HAVE_SELFTEST
  23709. ret = wc_RsaPSS_CheckPadding(
  23710. ssl->buffers.digest.buffer,
  23711. ssl->buffers.digest.length,
  23712. args->output, args->sigSz,
  23713. HashAlgoToType(args->hashAlgo));
  23714. #else
  23715. ret = wc_RsaPSS_CheckPadding_ex(
  23716. ssl->buffers.digest.buffer,
  23717. ssl->buffers.digest.length,
  23718. args->output, args->sigSz,
  23719. HashAlgoToType(args->hashAlgo), -1,
  23720. mp_count_bits(&ssl->peerRsaKey->n));
  23721. #endif
  23722. if (ret != 0) {
  23723. ret = SIG_VERIFY_E;
  23724. goto exit_dcv;
  23725. }
  23726. }
  23727. else
  23728. #endif
  23729. {
  23730. #ifdef WOLFSSL_SMALL_STACK
  23731. byte* encodedSig;
  23732. #else
  23733. byte encodedSig[MAX_ENCODED_SIG_SZ];
  23734. #endif
  23735. #ifdef WOLFSSL_SMALL_STACK
  23736. encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  23737. ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  23738. if (encodedSig == NULL) {
  23739. ERROR_OUT(MEMORY_E, exit_dcv);
  23740. }
  23741. #endif
  23742. if (args->sigAlgo != rsa_sa_algo) {
  23743. WOLFSSL_MSG("Oops, peer sent RSA key but not "
  23744. "in verify");
  23745. }
  23746. SetDigest(ssl, args->hashAlgo);
  23747. args->sigSz = wc_EncodeSignature(encodedSig,
  23748. ssl->buffers.digest.buffer,
  23749. ssl->buffers.digest.length,
  23750. TypeHash(args->hashAlgo));
  23751. if (args->sendSz != args->sigSz || !args->output ||
  23752. XMEMCMP(args->output, encodedSig,
  23753. min(args->sigSz, MAX_ENCODED_SIG_SZ)) != 0) {
  23754. ret = VERIFY_CERT_ERROR;
  23755. }
  23756. #ifdef WOLFSSL_SMALL_STACK
  23757. XFREE(encodedSig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
  23758. #endif
  23759. }
  23760. }
  23761. else {
  23762. if (args->sendSz != FINISHED_SZ || !args->output ||
  23763. XMEMCMP(args->output,
  23764. &ssl->hsHashes->certHashes, FINISHED_SZ) != 0) {
  23765. ret = VERIFY_CERT_ERROR;
  23766. }
  23767. }
  23768. }
  23769. #endif /* !NO_RSA */
  23770. /* Advance state and proceed */
  23771. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  23772. } /* case TLS_ASYNC_VERIFY */
  23773. FALL_THROUGH;
  23774. case TLS_ASYNC_FINALIZE:
  23775. {
  23776. if (IsEncryptionOn(ssl, 0)) {
  23777. args->idx += ssl->keys.padSz;
  23778. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  23779. if (ssl->options.startedETMRead)
  23780. args->idx += MacSize(ssl);
  23781. #endif
  23782. }
  23783. ssl->options.havePeerVerify = 1;
  23784. /* Set final index */
  23785. args->idx += args->sz;
  23786. *inOutIdx = args->idx;
  23787. /* Advance state and proceed */
  23788. ssl->options.asyncState = TLS_ASYNC_END;
  23789. } /* case TLS_ASYNC_FINALIZE */
  23790. case TLS_ASYNC_END:
  23791. {
  23792. break;
  23793. }
  23794. default:
  23795. ret = INPUT_CASE_ERROR;
  23796. } /* switch(ssl->options.asyncState) */
  23797. exit_dcv:
  23798. WOLFSSL_LEAVE("DoCertificateVerify", ret);
  23799. WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_DO);
  23800. #ifdef WOLFSSL_ASYNC_CRYPT
  23801. /* Handle async operation */
  23802. if (ret == WC_PENDING_E) {
  23803. /* Mark message as not received so it can process again */
  23804. ssl->msgsReceived.got_certificate_verify = 0;
  23805. return ret;
  23806. }
  23807. #endif /* WOLFSSL_ASYNC_CRYPT */
  23808. #ifdef WOLFSSL_EXTRA_ALERTS
  23809. if (ret == BUFFER_ERROR)
  23810. SendAlert(ssl, alert_fatal, decode_error);
  23811. else if (ret == SIG_VERIFY_E)
  23812. SendAlert(ssl, alert_fatal, decrypt_error);
  23813. else if (ret != 0)
  23814. SendAlert(ssl, alert_fatal, bad_certificate);
  23815. #endif
  23816. /* Digest is not allocated, so do this to prevent free */
  23817. ssl->buffers.digest.buffer = NULL;
  23818. ssl->buffers.digest.length = 0;
  23819. /* Final cleanup */
  23820. FreeDcvArgs(ssl, args);
  23821. FreeKeyExchange(ssl);
  23822. return ret;
  23823. }
  23824. #endif /* (!NO_RSA || ECC || ED25519 || ED448) && !WOLFSSL_NO_CLIENT_AUTH */
  23825. /* handle generation of server_hello_done (14) */
  23826. int SendServerHelloDone(WOLFSSL* ssl)
  23827. {
  23828. byte* output;
  23829. int sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  23830. int ret;
  23831. WOLFSSL_START(WC_FUNC_SERVER_HELLO_DONE_SEND);
  23832. WOLFSSL_ENTER("SendServerHelloDone");
  23833. #ifdef WOLFSSL_DTLS
  23834. if (ssl->options.dtls)
  23835. sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  23836. #endif
  23837. if (IsEncryptionOn(ssl, 1))
  23838. sendSz += MAX_MSG_EXTRA;
  23839. /* check for available size */
  23840. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  23841. return ret;
  23842. /* get output buffer */
  23843. output = ssl->buffers.outputBuffer.buffer +
  23844. ssl->buffers.outputBuffer.length;
  23845. AddHeaders(output, 0, server_hello_done, ssl);
  23846. if (IsEncryptionOn(ssl, 1)) {
  23847. byte* input;
  23848. int inputSz = HANDSHAKE_HEADER_SZ; /* build msg adds rec hdr */
  23849. input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  23850. if (input == NULL)
  23851. return MEMORY_E;
  23852. XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
  23853. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  23854. handshake, 1, 0, 0);
  23855. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  23856. if (sendSz < 0)
  23857. return sendSz;
  23858. } else {
  23859. #ifdef WOLFSSL_DTLS
  23860. if (IsDtlsNotSctpMode(ssl)) {
  23861. if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
  23862. return ret;
  23863. }
  23864. if (ssl->options.dtls)
  23865. DtlsSEQIncrement(ssl, CUR_ORDER);
  23866. #endif
  23867. ret = HashOutput(ssl, output, sendSz, 0);
  23868. if (ret != 0)
  23869. return ret;
  23870. }
  23871. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  23872. if (ssl->hsInfoOn)
  23873. AddPacketName(ssl, "ServerHelloDone");
  23874. if (ssl->toInfoOn)
  23875. AddPacketInfo(ssl, "ServerHelloDone", handshake, output, sendSz,
  23876. WRITE_PROTO, ssl->heap);
  23877. #endif
  23878. ssl->options.serverState = SERVER_HELLODONE_COMPLETE;
  23879. ssl->buffers.outputBuffer.length += sendSz;
  23880. ret = SendBuffered(ssl);
  23881. WOLFSSL_LEAVE("SendServerHelloDone", ret);
  23882. WOLFSSL_END(WC_FUNC_SERVER_HELLO_DONE_SEND);
  23883. return ret;
  23884. }
  23885. #endif /* !WOLFSSL_NO_TLS12 */
  23886. #ifdef HAVE_SESSION_TICKET
  23887. #define WOLFSSL_TICKET_FIXED_SZ (WOLFSSL_TICKET_NAME_SZ + \
  23888. WOLFSSL_TICKET_IV_SZ + WOLFSSL_TICKET_MAC_SZ + LENGTH_SZ)
  23889. #define WOLFSSL_TICKET_ENC_SZ (SESSION_TICKET_LEN - WOLFSSL_TICKET_FIXED_SZ)
  23890. /* our ticket format */
  23891. typedef struct InternalTicket {
  23892. ProtocolVersion pv; /* version when ticket created */
  23893. byte suite[SUITE_LEN]; /* cipher suite when created */
  23894. byte msecret[SECRET_LEN]; /* master secret */
  23895. word32 timestamp; /* born on */
  23896. word16 haveEMS; /* have extended master secret */
  23897. #ifdef WOLFSSL_TLS13
  23898. word32 ageAdd; /* Obfuscation of age */
  23899. word16 namedGroup; /* Named group used */
  23900. #ifndef WOLFSSL_TLS13_DRAFT_18
  23901. TicketNonce ticketNonce; /* Ticket nonce */
  23902. #endif
  23903. #ifdef WOLFSSL_EARLY_DATA
  23904. word32 maxEarlyDataSz; /* Max size of early data */
  23905. #endif
  23906. #endif
  23907. } InternalTicket;
  23908. /* fit within SESSION_TICKET_LEN */
  23909. typedef struct ExternalTicket {
  23910. byte key_name[WOLFSSL_TICKET_NAME_SZ]; /* key context name */
  23911. byte iv[WOLFSSL_TICKET_IV_SZ]; /* this ticket's iv */
  23912. byte enc_len[LENGTH_SZ]; /* encrypted length */
  23913. byte enc_ticket[WOLFSSL_TICKET_ENC_SZ]; /* encrypted internal ticket */
  23914. byte mac[WOLFSSL_TICKET_MAC_SZ]; /* total mac */
  23915. /* !! if add to structure, add to TICKET_FIXED_SZ !! */
  23916. } ExternalTicket;
  23917. /* create a new session ticket, 0 on success */
  23918. int CreateTicket(WOLFSSL* ssl)
  23919. {
  23920. InternalTicket it;
  23921. ExternalTicket* et = (ExternalTicket*)ssl->session.ticket;
  23922. int encLen;
  23923. int ret;
  23924. byte zeros[WOLFSSL_TICKET_MAC_SZ]; /* biggest cmp size */
  23925. XMEMSET(&it, 0, sizeof(it));
  23926. /* build internal */
  23927. it.pv.major = ssl->version.major;
  23928. it.pv.minor = ssl->version.minor;
  23929. it.suite[0] = ssl->options.cipherSuite0;
  23930. it.suite[1] = ssl->options.cipherSuite;
  23931. #ifdef WOLFSSL_EARLY_DATA
  23932. it.maxEarlyDataSz = ssl->options.maxEarlyDataSz;
  23933. #endif
  23934. if (!ssl->options.tls1_3) {
  23935. XMEMCPY(it.msecret, ssl->arrays->masterSecret, SECRET_LEN);
  23936. c32toa(LowResTimer(), (byte*)&it.timestamp);
  23937. it.haveEMS = ssl->options.haveEMS;
  23938. }
  23939. else {
  23940. #ifdef WOLFSSL_TLS13
  23941. /* Client adds to ticket age to obfuscate. */
  23942. ret = wc_RNG_GenerateBlock(ssl->rng, (byte*)&it.ageAdd,
  23943. sizeof(it.ageAdd));
  23944. if (ret != 0)
  23945. return BAD_TICKET_ENCRYPT;
  23946. ssl->session.ticketAdd = it.ageAdd;
  23947. it.namedGroup = ssl->session.namedGroup;
  23948. it.timestamp = TimeNowInMilliseconds();
  23949. /* Resumption master secret. */
  23950. XMEMCPY(it.msecret, ssl->session.masterSecret, SECRET_LEN);
  23951. #ifndef WOLFSSL_TLS13_DRAFT_18
  23952. XMEMCPY(&it.ticketNonce, &ssl->session.ticketNonce,
  23953. sizeof(TicketNonce));
  23954. #endif
  23955. #endif
  23956. }
  23957. /* build external */
  23958. XMEMCPY(et->enc_ticket, &it, sizeof(InternalTicket));
  23959. /* encrypt */
  23960. encLen = WOLFSSL_TICKET_ENC_SZ; /* max size user can use */
  23961. if (ssl->ctx->ticketEncCb == NULL) {
  23962. ret = WOLFSSL_TICKET_RET_FATAL;
  23963. }
  23964. else {
  23965. ret = ssl->ctx->ticketEncCb(ssl, et->key_name, et->iv, et->mac, 1,
  23966. et->enc_ticket, sizeof(InternalTicket),
  23967. &encLen, ssl->ctx->ticketEncCtx);
  23968. }
  23969. if (ret == WOLFSSL_TICKET_RET_OK) {
  23970. if (encLen < (int)sizeof(InternalTicket) ||
  23971. encLen > WOLFSSL_TICKET_ENC_SZ) {
  23972. WOLFSSL_MSG("Bad user ticket encrypt size");
  23973. return BAD_TICKET_KEY_CB_SZ;
  23974. }
  23975. /* sanity checks on encrypt callback */
  23976. /* internal ticket can't be the same if encrypted */
  23977. if (XMEMCMP(et->enc_ticket, &it, sizeof(InternalTicket)) == 0) {
  23978. WOLFSSL_MSG("User ticket encrypt didn't encrypt");
  23979. return BAD_TICKET_ENCRYPT;
  23980. }
  23981. XMEMSET(zeros, 0, sizeof(zeros));
  23982. /* name */
  23983. if (XMEMCMP(et->key_name, zeros, WOLFSSL_TICKET_NAME_SZ) == 0) {
  23984. WOLFSSL_MSG("User ticket encrypt didn't set name");
  23985. return BAD_TICKET_ENCRYPT;
  23986. }
  23987. /* iv */
  23988. if (XMEMCMP(et->iv, zeros, WOLFSSL_TICKET_IV_SZ) == 0) {
  23989. WOLFSSL_MSG("User ticket encrypt didn't set iv");
  23990. return BAD_TICKET_ENCRYPT;
  23991. }
  23992. /* mac */
  23993. if (XMEMCMP(et->mac, zeros, WOLFSSL_TICKET_MAC_SZ) == 0) {
  23994. WOLFSSL_MSG("User ticket encrypt didn't set mac");
  23995. return BAD_TICKET_ENCRYPT;
  23996. }
  23997. /* set size */
  23998. c16toa((word16)encLen, et->enc_len);
  23999. ssl->session.ticketLen = (word16)(encLen + WOLFSSL_TICKET_FIXED_SZ);
  24000. if (encLen < WOLFSSL_TICKET_ENC_SZ) {
  24001. /* move mac up since whole enc buffer not used */
  24002. XMEMMOVE(et->enc_ticket +encLen, et->mac,WOLFSSL_TICKET_MAC_SZ);
  24003. }
  24004. }
  24005. return ret;
  24006. }
  24007. /* Parse ticket sent by client, returns callback return value */
  24008. int DoClientTicket(WOLFSSL* ssl, const byte* input, word32 len)
  24009. {
  24010. ExternalTicket* et;
  24011. InternalTicket* it;
  24012. int ret;
  24013. int outLen;
  24014. word16 inLen;
  24015. WOLFSSL_START(WC_FUNC_TICKET_DO);
  24016. WOLFSSL_ENTER("DoClientTicket");
  24017. if (len > SESSION_TICKET_LEN ||
  24018. len < (word32)(sizeof(InternalTicket) + WOLFSSL_TICKET_FIXED_SZ)) {
  24019. return BAD_TICKET_MSG_SZ;
  24020. }
  24021. et = (ExternalTicket*)input;
  24022. it = (InternalTicket*)et->enc_ticket;
  24023. /* decrypt */
  24024. ato16(et->enc_len, &inLen);
  24025. if (inLen > (word16)(len - WOLFSSL_TICKET_FIXED_SZ)) {
  24026. return BAD_TICKET_MSG_SZ;
  24027. }
  24028. outLen = inLen; /* may be reduced by user padding */
  24029. if (ssl->ctx->ticketEncCb == NULL) {
  24030. ret = WOLFSSL_TICKET_RET_FATAL;
  24031. }
  24032. else {
  24033. ret = ssl->ctx->ticketEncCb(ssl, et->key_name, et->iv,
  24034. et->enc_ticket + inLen, 0,
  24035. et->enc_ticket, inLen, &outLen,
  24036. ssl->ctx->ticketEncCtx);
  24037. }
  24038. if (ret == WOLFSSL_TICKET_RET_FATAL || ret < 0) return ret;
  24039. if (outLen > (int)inLen || outLen < (int)sizeof(InternalTicket)) {
  24040. WOLFSSL_MSG("Bad user ticket decrypt len");
  24041. return BAD_TICKET_KEY_CB_SZ;
  24042. }
  24043. /* get master secret */
  24044. if (ret == WOLFSSL_TICKET_RET_OK || ret == WOLFSSL_TICKET_RET_CREATE) {
  24045. if (ssl->version.minor < it->pv.minor) {
  24046. WOLFSSL_MSG("Ticket has greater version");
  24047. return VERSION_ERROR;
  24048. }
  24049. else if (ssl->version.minor > it->pv.minor) {
  24050. if (!ssl->options.downgrade) {
  24051. WOLFSSL_MSG("Ticket has lesser version");
  24052. return VERSION_ERROR;
  24053. }
  24054. WOLFSSL_MSG("Downgrading protocol due to ticket");
  24055. if (it->pv.minor < ssl->options.minDowngrade)
  24056. return VERSION_ERROR;
  24057. ssl->version.minor = it->pv.minor;
  24058. }
  24059. if (!IsAtLeastTLSv1_3(ssl->version)) {
  24060. XMEMCPY(ssl->arrays->masterSecret, it->msecret, SECRET_LEN);
  24061. /* Copy the haveExtendedMasterSecret property from the ticket to
  24062. * the saved session, so the property may be checked later. */
  24063. ssl->session.haveEMS = it->haveEMS;
  24064. #ifndef NO_RESUME_SUITE_CHECK
  24065. ssl->session.cipherSuite0 = it->suite[0];
  24066. ssl->session.cipherSuite = it->suite[1];
  24067. #endif
  24068. }
  24069. else {
  24070. #ifdef WOLFSSL_TLS13
  24071. /* Restore information to renegotiate. */
  24072. ssl->session.ticketSeen = it->timestamp;
  24073. ssl->session.ticketAdd = it->ageAdd;
  24074. ssl->session.cipherSuite0 = it->suite[0];
  24075. ssl->session.cipherSuite = it->suite[1];
  24076. #ifdef WOLFSSL_EARLY_DATA
  24077. ssl->session.maxEarlyDataSz = it->maxEarlyDataSz;
  24078. #endif
  24079. /* Resumption master secret. */
  24080. XMEMCPY(ssl->session.masterSecret, it->msecret, SECRET_LEN);
  24081. #ifndef WOLFSSL_TLS13_DRAFT_18
  24082. XMEMCPY(&ssl->session.ticketNonce, &it->ticketNonce,
  24083. sizeof(TicketNonce));
  24084. #endif
  24085. ssl->session.namedGroup = it->namedGroup;
  24086. #endif
  24087. }
  24088. }
  24089. WOLFSSL_LEAVE("DoClientTicket", ret);
  24090. WOLFSSL_END(WC_FUNC_TICKET_DO);
  24091. return ret;
  24092. }
  24093. /* send Session Ticket */
  24094. int SendTicket(WOLFSSL* ssl)
  24095. {
  24096. byte* output;
  24097. int ret;
  24098. int sendSz;
  24099. word32 length = SESSION_HINT_SZ + LENGTH_SZ;
  24100. word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  24101. WOLFSSL_START(WC_FUNC_TICKET_SEND);
  24102. WOLFSSL_ENTER("SendTicket");
  24103. if (ssl->options.createTicket) {
  24104. ret = CreateTicket(ssl);
  24105. if (ret != 0) return ret;
  24106. }
  24107. length += ssl->session.ticketLen;
  24108. sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
  24109. if (!ssl->options.dtls) {
  24110. if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone)
  24111. sendSz += MAX_MSG_EXTRA;
  24112. }
  24113. else {
  24114. #ifdef WOLFSSL_DTLS
  24115. sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  24116. idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
  24117. #endif
  24118. }
  24119. /* check for available size */
  24120. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  24121. return ret;
  24122. /* get output buffer */
  24123. output = ssl->buffers.outputBuffer.buffer +
  24124. ssl->buffers.outputBuffer.length;
  24125. AddHeaders(output, length, session_ticket, ssl);
  24126. /* hint */
  24127. c32toa(ssl->ctx->ticketHint, output + idx);
  24128. idx += SESSION_HINT_SZ;
  24129. /* length */
  24130. c16toa(ssl->session.ticketLen, output + idx);
  24131. idx += LENGTH_SZ;
  24132. /* ticket */
  24133. XMEMCPY(output + idx, ssl->session.ticket, ssl->session.ticketLen);
  24134. idx += ssl->session.ticketLen;
  24135. if (IsEncryptionOn(ssl, 1) && ssl->options.handShakeDone) {
  24136. byte* input;
  24137. int inputSz = idx - RECORD_HEADER_SZ; /* build msg adds rec hdr */
  24138. input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  24139. if (input == NULL)
  24140. return MEMORY_E;
  24141. XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
  24142. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  24143. handshake, 1, 0, 0);
  24144. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  24145. if (sendSz < 0)
  24146. return sendSz;
  24147. }
  24148. else {
  24149. #ifdef WOLFSSL_DTLS
  24150. if (ssl->options.dtls) {
  24151. if ((ret = DtlsMsgPoolSave(ssl, output, sendSz)) != 0)
  24152. return ret;
  24153. DtlsSEQIncrement(ssl, CUR_ORDER);
  24154. }
  24155. #endif
  24156. ret = HashOutput(ssl, output, sendSz, 0);
  24157. if (ret != 0)
  24158. return ret;
  24159. }
  24160. ssl->buffers.outputBuffer.length += sendSz;
  24161. ret = SendBuffered(ssl);
  24162. WOLFSSL_LEAVE("SendTicket", ret);
  24163. WOLFSSL_END(WC_FUNC_TICKET_SEND);
  24164. return ret;
  24165. }
  24166. #endif /* HAVE_SESSION_TICKET */
  24167. #ifndef WOLFSSL_NO_TLS12
  24168. #if defined(HAVE_SECURE_RENEGOTIATION) && \
  24169. defined(HAVE_SERVER_RENEGOTIATION_INFO) && \
  24170. !defined(WOLFSSL_NO_SERVER)
  24171. /* handle generation of server's hello_request (0) */
  24172. int SendHelloRequest(WOLFSSL* ssl)
  24173. {
  24174. byte* output;
  24175. int sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
  24176. int ret;
  24177. WOLFSSL_START(WC_FUNC_HELLO_REQUEST_SEND);
  24178. WOLFSSL_ENTER("SendHelloRequest");
  24179. if (IsEncryptionOn(ssl, 1))
  24180. sendSz += MAX_MSG_EXTRA;
  24181. /* check for available size */
  24182. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  24183. return ret;
  24184. /* get output buffer */
  24185. output = ssl->buffers.outputBuffer.buffer +
  24186. ssl->buffers.outputBuffer.length;
  24187. AddHeaders(output, 0, hello_request, ssl);
  24188. if (IsEncryptionOn(ssl, 1)) {
  24189. byte* input;
  24190. int inputSz = HANDSHAKE_HEADER_SZ; /* build msg adds rec hdr */
  24191. input = (byte*)XMALLOC(inputSz, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  24192. if (input == NULL)
  24193. return MEMORY_E;
  24194. XMEMCPY(input, output + RECORD_HEADER_SZ, inputSz);
  24195. sendSz = BuildMessage(ssl, output, sendSz, input, inputSz,
  24196. handshake, 0, 0, 0);
  24197. XFREE(input, ssl->heap, DYNAMIC_TYPE_IN_BUFFER);
  24198. if (sendSz < 0)
  24199. return sendSz;
  24200. }
  24201. ssl->buffers.outputBuffer.length += sendSz;
  24202. ret = SendBuffered(ssl);
  24203. WOLFSSL_LEAVE("SendHelloRequest", ret);
  24204. WOLFSSL_END(WC_FUNC_HELLO_REQUEST_SEND);
  24205. return ret;
  24206. }
  24207. #endif /* HAVE_SECURE_RENEGOTIATION && HAVE_SERVER_RENEGOTIATION_INFO */
  24208. #ifdef WOLFSSL_DTLS
  24209. /* handle generation of DTLS hello_verify_request (3) */
  24210. static int SendHelloVerifyRequest(WOLFSSL* ssl,
  24211. const byte* cookie, byte cookieSz)
  24212. {
  24213. byte* output;
  24214. int length = VERSION_SZ + ENUM_LEN + cookieSz;
  24215. int idx = DTLS_RECORD_HEADER_SZ + DTLS_HANDSHAKE_HEADER_SZ;
  24216. int sendSz = length + idx;
  24217. int ret;
  24218. /* check for available size */
  24219. if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
  24220. return ret;
  24221. /* get output buffer */
  24222. output = ssl->buffers.outputBuffer.buffer +
  24223. ssl->buffers.outputBuffer.length;
  24224. /* Hello Verify Request should use the same sequence number as the
  24225. * Client Hello. */
  24226. ssl->keys.dtls_sequence_number_hi = ssl->keys.curSeq_hi;
  24227. ssl->keys.dtls_sequence_number_lo = ssl->keys.curSeq_lo;
  24228. AddHeaders(output, length, hello_verify_request, ssl);
  24229. #ifdef OPENSSL_EXTRA
  24230. output[idx++] = DTLS_MAJOR;
  24231. output[idx++] = DTLS_MINOR;
  24232. #else
  24233. output[idx++] = ssl->version.major;
  24234. output[idx++] = ssl->version.minor;
  24235. #endif
  24236. output[idx++] = cookieSz;
  24237. if (cookie == NULL || cookieSz == 0)
  24238. return COOKIE_ERROR;
  24239. XMEMCPY(output + idx, cookie, cookieSz);
  24240. #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
  24241. if (ssl->hsInfoOn)
  24242. AddPacketName(ssl, "HelloVerifyRequest");
  24243. if (ssl->toInfoOn)
  24244. AddPacketInfo(ssl, "HelloVerifyRequest", handshake, output,
  24245. sendSz, WRITE_PROTO, ssl->heap);
  24246. #endif
  24247. ssl->buffers.outputBuffer.length += sendSz;
  24248. return SendBuffered(ssl);
  24249. }
  24250. #endif /* WOLFSSL_DTLS */
  24251. typedef struct DckeArgs {
  24252. byte* output; /* not allocated */
  24253. word32 length;
  24254. word32 idx;
  24255. word32 begin;
  24256. word32 sigSz;
  24257. #ifndef NO_RSA
  24258. int lastErr;
  24259. #endif
  24260. } DckeArgs;
  24261. static void FreeDckeArgs(WOLFSSL* ssl, void* pArgs)
  24262. {
  24263. DckeArgs* args = (DckeArgs*)pArgs;
  24264. (void)ssl;
  24265. (void)args;
  24266. }
  24267. /* handle processing client_key_exchange (16) */
  24268. static int DoClientKeyExchange(WOLFSSL* ssl, byte* input, word32* inOutIdx,
  24269. word32 size)
  24270. {
  24271. int ret;
  24272. #ifdef WOLFSSL_ASYNC_CRYPT
  24273. DckeArgs* args = (DckeArgs*)ssl->async.args;
  24274. typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
  24275. (void)sizeof(args_test);
  24276. #else
  24277. DckeArgs args[1];
  24278. #endif
  24279. (void)size;
  24280. (void)input;
  24281. WOLFSSL_START(WC_FUNC_CLIENT_KEY_EXCHANGE_DO);
  24282. WOLFSSL_ENTER("DoClientKeyExchange");
  24283. #ifdef WOLFSSL_ASYNC_CRYPT
  24284. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  24285. if (ret != WC_NOT_PENDING_E) {
  24286. /* Check for error */
  24287. if (ret < 0)
  24288. goto exit_dcke;
  24289. }
  24290. else
  24291. #endif /* WOLFSSL_ASYNC_CRYPT */
  24292. {
  24293. /* Reset state */
  24294. ret = 0;
  24295. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  24296. XMEMSET(args, 0, sizeof(DckeArgs));
  24297. args->idx = *inOutIdx;
  24298. args->begin = *inOutIdx;
  24299. #ifdef WOLFSSL_ASYNC_CRYPT
  24300. ssl->async.freeArgs = FreeDckeArgs;
  24301. #endif
  24302. }
  24303. /* Do Client Key Exchange State Machine */
  24304. switch(ssl->options.asyncState)
  24305. {
  24306. case TLS_ASYNC_BEGIN:
  24307. {
  24308. /* Sanity checks */
  24309. if (ssl->options.side != WOLFSSL_SERVER_END) {
  24310. WOLFSSL_MSG("Client received client keyexchange, attack?");
  24311. WOLFSSL_ERROR(ssl->error = SIDE_ERROR);
  24312. ERROR_OUT(WOLFSSL_FATAL_ERROR, exit_dcke);
  24313. }
  24314. if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
  24315. WOLFSSL_MSG("Client sending keyexchange at wrong time");
  24316. SendAlert(ssl, alert_fatal, unexpected_message);
  24317. ERROR_OUT(OUT_OF_ORDER_E, exit_dcke);
  24318. }
  24319. #ifndef NO_CERTS
  24320. if (ssl->options.verifyPeer && ssl->options.failNoCert) {
  24321. if (!ssl->options.havePeerCert) {
  24322. WOLFSSL_MSG("client didn't present peer cert");
  24323. ERROR_OUT(NO_PEER_CERT, exit_dcke);
  24324. }
  24325. }
  24326. if (ssl->options.verifyPeer && ssl->options.failNoCertxPSK) {
  24327. if (!ssl->options.havePeerCert &&
  24328. !ssl->options.usingPSK_cipher) {
  24329. WOLFSSL_MSG("client didn't present peer cert");
  24330. return NO_PEER_CERT;
  24331. }
  24332. }
  24333. #endif /* !NO_CERTS */
  24334. #if defined(WOLFSSL_CALLBACKS)
  24335. if (ssl->hsInfoOn) {
  24336. AddPacketName(ssl, "ClientKeyExchange");
  24337. }
  24338. if (ssl->toInfoOn) {
  24339. AddLateName("ClientKeyExchange", &ssl->timeoutInfo);
  24340. }
  24341. #endif
  24342. if (ssl->arrays->preMasterSecret == NULL) {
  24343. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  24344. ssl->arrays->preMasterSecret = (byte*)XMALLOC(ENCRYPT_LEN,
  24345. ssl->heap, DYNAMIC_TYPE_SECRET);
  24346. if (ssl->arrays->preMasterSecret == NULL) {
  24347. ERROR_OUT(MEMORY_E, exit_dcke);
  24348. }
  24349. XMEMSET(ssl->arrays->preMasterSecret, 0, ENCRYPT_LEN);
  24350. }
  24351. switch (ssl->specs.kea) {
  24352. #ifndef NO_RSA
  24353. case rsa_kea:
  24354. {
  24355. break;
  24356. } /* rsa_kea */
  24357. #endif /* !NO_RSA */
  24358. #ifndef NO_PSK
  24359. case psk_kea:
  24360. {
  24361. /* sanity check that PSK server callback has been set */
  24362. if (ssl->options.server_psk_cb == NULL) {
  24363. WOLFSSL_MSG("No server PSK callback set");
  24364. ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
  24365. }
  24366. break;
  24367. }
  24368. #endif /* !NO_PSK */
  24369. #ifdef HAVE_NTRU
  24370. case ntru_kea:
  24371. {
  24372. /* make sure private key exists */
  24373. if (ssl->buffers.key == NULL ||
  24374. ssl->buffers.key->buffer == NULL) {
  24375. ERROR_OUT(NO_PRIVATE_KEY, exit_dcke);
  24376. }
  24377. break;
  24378. }
  24379. #endif /* HAVE_NTRU */
  24380. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  24381. defined(HAVE_CURVE448)
  24382. case ecc_diffie_hellman_kea:
  24383. {
  24384. break;
  24385. }
  24386. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  24387. #ifndef NO_DH
  24388. case diffie_hellman_kea:
  24389. {
  24390. break;
  24391. }
  24392. #endif /* !NO_DH */
  24393. #if !defined(NO_DH) && !defined(NO_PSK)
  24394. case dhe_psk_kea:
  24395. {
  24396. /* sanity check that PSK server callback has been set */
  24397. if (ssl->options.server_psk_cb == NULL) {
  24398. WOLFSSL_MSG("No server PSK callback set");
  24399. ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
  24400. }
  24401. break;
  24402. }
  24403. #endif /* !NO_DH && !NO_PSK */
  24404. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  24405. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  24406. case ecdhe_psk_kea:
  24407. {
  24408. /* sanity check that PSK server callback has been set */
  24409. if (ssl->options.server_psk_cb == NULL) {
  24410. WOLFSSL_MSG("No server PSK callback set");
  24411. ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
  24412. }
  24413. break;
  24414. }
  24415. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  24416. default:
  24417. WOLFSSL_MSG("Bad kea type");
  24418. ret = BAD_KEA_TYPE_E;
  24419. } /* switch (ssl->specs.kea) */
  24420. /* Check for error */
  24421. if (ret != 0) {
  24422. goto exit_dcke;
  24423. }
  24424. /* Advance state and proceed */
  24425. ssl->options.asyncState = TLS_ASYNC_BUILD;
  24426. } /* TLS_ASYNC_BEGIN */
  24427. FALL_THROUGH;
  24428. case TLS_ASYNC_BUILD:
  24429. {
  24430. switch (ssl->specs.kea) {
  24431. #ifndef NO_RSA
  24432. case rsa_kea:
  24433. {
  24434. word16 keySz;
  24435. ssl->buffers.keyType = rsa_sa_algo;
  24436. ret = DecodePrivateKey(ssl, &keySz);
  24437. if (ret != 0) {
  24438. goto exit_dcke;
  24439. }
  24440. args->length = (word32)keySz;
  24441. ssl->arrays->preMasterSz = SECRET_LEN;
  24442. if (ssl->options.tls) {
  24443. word16 check;
  24444. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  24445. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24446. }
  24447. ato16(input + args->idx, &check);
  24448. args->idx += OPAQUE16_LEN;
  24449. if ((word32)check != args->length) {
  24450. WOLFSSL_MSG("RSA explicit size doesn't match");
  24451. #ifdef WOLFSSL_EXTRA_ALERTS
  24452. SendAlert(ssl, alert_fatal, bad_record_mac);
  24453. #endif
  24454. ERROR_OUT(RSA_PRIVATE_ERROR, exit_dcke);
  24455. }
  24456. }
  24457. if ((args->idx - args->begin) + args->length > size) {
  24458. WOLFSSL_MSG("RSA message too big");
  24459. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24460. }
  24461. /* pre-load PreMasterSecret with RNG data */
  24462. ret = wc_RNG_GenerateBlock(ssl->rng,
  24463. &ssl->arrays->preMasterSecret[VERSION_SZ],
  24464. SECRET_LEN - VERSION_SZ);
  24465. if (ret != 0) {
  24466. goto exit_dcke;
  24467. }
  24468. args->output = NULL;
  24469. break;
  24470. } /* rsa_kea */
  24471. #endif /* !NO_RSA */
  24472. #ifndef NO_PSK
  24473. case psk_kea:
  24474. {
  24475. byte* pms = ssl->arrays->preMasterSecret;
  24476. word16 ci_sz;
  24477. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  24478. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24479. }
  24480. ato16(input + args->idx, &ci_sz);
  24481. args->idx += OPAQUE16_LEN;
  24482. if (ci_sz > MAX_PSK_ID_LEN) {
  24483. ERROR_OUT(CLIENT_ID_ERROR, exit_dcke);
  24484. }
  24485. if ((args->idx - args->begin) + ci_sz > size) {
  24486. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24487. }
  24488. XMEMCPY(ssl->arrays->client_identity,
  24489. input + args->idx, ci_sz);
  24490. args->idx += ci_sz;
  24491. ssl->arrays->client_identity[ci_sz] = '\0'; /* null term */
  24492. ssl->arrays->psk_keySz = ssl->options.server_psk_cb(ssl,
  24493. ssl->arrays->client_identity, ssl->arrays->psk_key,
  24494. MAX_PSK_KEY_LEN);
  24495. if (ssl->arrays->psk_keySz == 0 ||
  24496. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  24497. ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
  24498. }
  24499. /* make psk pre master secret */
  24500. /* length of key + length 0s + length of key + key */
  24501. c16toa((word16) ssl->arrays->psk_keySz, pms);
  24502. pms += OPAQUE16_LEN;
  24503. XMEMSET(pms, 0, ssl->arrays->psk_keySz);
  24504. pms += ssl->arrays->psk_keySz;
  24505. c16toa((word16) ssl->arrays->psk_keySz, pms);
  24506. pms += OPAQUE16_LEN;
  24507. XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  24508. ssl->arrays->preMasterSz =
  24509. (ssl->arrays->psk_keySz * 2) + (OPAQUE16_LEN * 2);
  24510. break;
  24511. }
  24512. #endif /* !NO_PSK */
  24513. #ifdef HAVE_NTRU
  24514. case ntru_kea:
  24515. {
  24516. word16 cipherLen;
  24517. word16 plainLen = ENCRYPT_LEN;
  24518. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  24519. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24520. }
  24521. ato16(input + args->idx, &cipherLen);
  24522. args->idx += OPAQUE16_LEN;
  24523. if (cipherLen > MAX_NTRU_ENCRYPT_SZ) {
  24524. ERROR_OUT(NTRU_KEY_ERROR, exit_dcke);
  24525. }
  24526. if ((args->idx - args->begin) + cipherLen > size) {
  24527. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24528. }
  24529. if (NTRU_OK != ntru_crypto_ntru_decrypt(
  24530. (word16) ssl->buffers.key->length,
  24531. ssl->buffers.key->buffer, cipherLen,
  24532. input + args->idx, &plainLen,
  24533. ssl->arrays->preMasterSecret)) {
  24534. ERROR_OUT(NTRU_DECRYPT_ERROR, exit_dcke);
  24535. }
  24536. if (plainLen != SECRET_LEN) {
  24537. ERROR_OUT(NTRU_DECRYPT_ERROR, exit_dcke);
  24538. }
  24539. args->idx += cipherLen;
  24540. ssl->arrays->preMasterSz = plainLen;
  24541. break;
  24542. }
  24543. #endif /* HAVE_NTRU */
  24544. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  24545. defined(HAVE_CURVE448)
  24546. case ecc_diffie_hellman_kea:
  24547. {
  24548. #ifdef HAVE_ECC
  24549. ecc_key* private_key = ssl->eccTempKey;
  24550. /* handle static private key */
  24551. if (ssl->specs.static_ecdh &&
  24552. ssl->ecdhCurveOID != ECC_X25519_OID &&
  24553. ssl->ecdhCurveOID != ECC_X448_OID) {
  24554. word16 keySz;
  24555. ssl->buffers.keyType = ecc_dsa_sa_algo;
  24556. ret = DecodePrivateKey(ssl, &keySz);
  24557. if (ret != 0) {
  24558. goto exit_dcke;
  24559. }
  24560. private_key = (ecc_key*)ssl->hsKey;
  24561. }
  24562. #endif
  24563. /* import peer ECC key */
  24564. if ((args->idx - args->begin) + OPAQUE8_LEN > size) {
  24565. #ifdef WOLFSSL_EXTRA_ALERTS
  24566. SendAlert(ssl, alert_fatal, decode_error);
  24567. #endif
  24568. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24569. }
  24570. args->length = input[args->idx++];
  24571. if ((args->idx - args->begin) + args->length > size) {
  24572. #ifdef WOLFSSL_EXTRA_ALERTS
  24573. SendAlert(ssl, alert_fatal, decode_error);
  24574. #endif
  24575. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24576. }
  24577. #ifdef HAVE_CURVE25519
  24578. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  24579. #ifdef HAVE_PK_CALLBACKS
  24580. /* if callback then use it for shared secret */
  24581. if (ssl->ctx->X25519SharedSecretCb != NULL) {
  24582. break;
  24583. }
  24584. #endif
  24585. if (ssl->peerX25519Key == NULL) {
  24586. /* alloc/init on demand */
  24587. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
  24588. (void**)&ssl->peerX25519Key);
  24589. if (ret != 0) {
  24590. goto exit_dcke;
  24591. }
  24592. } else if (ssl->peerX25519KeyPresent) {
  24593. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE25519,
  24594. ssl->peerX25519Key);
  24595. ssl->peerX25519KeyPresent = 0;
  24596. if (ret != 0) {
  24597. goto exit_dcke;
  24598. }
  24599. }
  24600. if ((ret = wc_curve25519_check_public(
  24601. input + args->idx, args->length,
  24602. EC25519_LITTLE_ENDIAN)) != 0) {
  24603. #ifdef WOLFSSL_EXTRA_ALERTS
  24604. if (ret == BUFFER_E)
  24605. SendAlert(ssl, alert_fatal, decode_error);
  24606. else if (ret == ECC_OUT_OF_RANGE_E)
  24607. SendAlert(ssl, alert_fatal, bad_record_mac);
  24608. else {
  24609. SendAlert(ssl, alert_fatal,
  24610. illegal_parameter);
  24611. }
  24612. #endif
  24613. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  24614. }
  24615. if (wc_curve25519_import_public_ex(
  24616. input + args->idx, args->length,
  24617. ssl->peerX25519Key,
  24618. EC25519_LITTLE_ENDIAN)) {
  24619. #ifdef WOLFSSL_EXTRA_ALERTS
  24620. SendAlert(ssl, alert_fatal, illegal_parameter);
  24621. #endif
  24622. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  24623. }
  24624. ssl->arrays->preMasterSz = CURVE25519_KEYSIZE;
  24625. ssl->peerX25519KeyPresent = 1;
  24626. break;
  24627. }
  24628. #endif
  24629. #ifdef HAVE_CURVE448
  24630. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  24631. #ifdef HAVE_PK_CALLBACKS
  24632. /* if callback then use it for shared secret */
  24633. if (ssl->ctx->X448SharedSecretCb != NULL) {
  24634. break;
  24635. }
  24636. #endif
  24637. if (ssl->peerX448Key == NULL) {
  24638. /* alloc/init on demand */
  24639. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
  24640. (void**)&ssl->peerX448Key);
  24641. if (ret != 0) {
  24642. goto exit_dcke;
  24643. }
  24644. } else if (ssl->peerX448KeyPresent) {
  24645. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE448,
  24646. ssl->peerX448Key);
  24647. ssl->peerX448KeyPresent = 0;
  24648. if (ret != 0) {
  24649. goto exit_dcke;
  24650. }
  24651. }
  24652. if ((ret = wc_curve448_check_public(
  24653. input + args->idx, args->length,
  24654. EC448_LITTLE_ENDIAN)) != 0) {
  24655. #ifdef WOLFSSL_EXTRA_ALERTS
  24656. if (ret == BUFFER_E)
  24657. SendAlert(ssl, alert_fatal, decode_error);
  24658. else if (ret == ECC_OUT_OF_RANGE_E)
  24659. SendAlert(ssl, alert_fatal, bad_record_mac);
  24660. else {
  24661. SendAlert(ssl, alert_fatal,
  24662. illegal_parameter);
  24663. }
  24664. #endif
  24665. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  24666. }
  24667. if (wc_curve448_import_public_ex(
  24668. input + args->idx, args->length,
  24669. ssl->peerX448Key,
  24670. EC448_LITTLE_ENDIAN)) {
  24671. #ifdef WOLFSSL_EXTRA_ALERTS
  24672. SendAlert(ssl, alert_fatal, illegal_parameter);
  24673. #endif
  24674. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  24675. }
  24676. ssl->arrays->preMasterSz = CURVE448_KEY_SIZE;
  24677. ssl->peerX448KeyPresent = 1;
  24678. break;
  24679. }
  24680. #endif
  24681. #ifdef HAVE_ECC
  24682. #ifdef HAVE_PK_CALLBACKS
  24683. /* if callback then use it for shared secret */
  24684. if (ssl->ctx->EccSharedSecretCb != NULL) {
  24685. break;
  24686. }
  24687. #endif
  24688. if (!ssl->specs.static_ecdh &&
  24689. ssl->eccTempKeyPresent == 0) {
  24690. WOLFSSL_MSG("Ecc ephemeral key not made correctly");
  24691. ERROR_OUT(ECC_MAKEKEY_ERROR, exit_dcke);
  24692. }
  24693. if (ssl->peerEccKey == NULL) {
  24694. /* alloc/init on demand */
  24695. ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
  24696. (void**)&ssl->peerEccKey);
  24697. if (ret != 0) {
  24698. goto exit_dcke;
  24699. }
  24700. } else if (ssl->peerEccKeyPresent) {
  24701. ret = ReuseKey(ssl, DYNAMIC_TYPE_ECC,
  24702. ssl->peerEccKey);
  24703. ssl->peerEccKeyPresent = 0;
  24704. if (ret != 0) {
  24705. goto exit_dcke;
  24706. }
  24707. }
  24708. if (wc_ecc_import_x963_ex(input + args->idx,
  24709. args->length, ssl->peerEccKey,
  24710. private_key->dp->id)) {
  24711. #ifdef WOLFSSL_EXTRA_ALERTS
  24712. SendAlert(ssl, alert_fatal, illegal_parameter);
  24713. #endif
  24714. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  24715. }
  24716. ssl->arrays->preMasterSz = private_key->dp->size;
  24717. ssl->peerEccKeyPresent = 1;
  24718. #endif /* HAVE_ECC */
  24719. break;
  24720. }
  24721. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  24722. #ifndef NO_DH
  24723. case diffie_hellman_kea:
  24724. {
  24725. word16 clientPubSz;
  24726. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  24727. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24728. }
  24729. ato16(input + args->idx, &clientPubSz);
  24730. args->idx += OPAQUE16_LEN;
  24731. if ((args->idx - args->begin) + clientPubSz > size) {
  24732. #ifdef WOLFSSL_EXTRA_ALERTS
  24733. SendAlert(ssl, alert_fatal, decode_error);
  24734. #endif
  24735. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24736. }
  24737. args->sigSz = clientPubSz;
  24738. ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
  24739. (void**)&ssl->buffers.serverDH_Key);
  24740. if (ret != 0) {
  24741. goto exit_dcke;
  24742. }
  24743. ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
  24744. ssl->buffers.serverDH_P.buffer,
  24745. ssl->buffers.serverDH_P.length,
  24746. ssl->buffers.serverDH_G.buffer,
  24747. ssl->buffers.serverDH_G.length);
  24748. /* set the max agree result size */
  24749. ssl->arrays->preMasterSz = ENCRYPT_LEN;
  24750. break;
  24751. }
  24752. #endif /* !NO_DH */
  24753. #if !defined(NO_DH) && !defined(NO_PSK)
  24754. case dhe_psk_kea:
  24755. {
  24756. word16 clientSz;
  24757. /* Read in the PSK hint */
  24758. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  24759. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24760. }
  24761. ato16(input + args->idx, &clientSz);
  24762. args->idx += OPAQUE16_LEN;
  24763. if (clientSz > MAX_PSK_ID_LEN) {
  24764. ERROR_OUT(CLIENT_ID_ERROR, exit_dcke);
  24765. }
  24766. if ((args->idx - args->begin) + clientSz > size) {
  24767. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24768. }
  24769. XMEMCPY(ssl->arrays->client_identity, input + args->idx,
  24770. clientSz);
  24771. args->idx += clientSz;
  24772. ssl->arrays->client_identity[clientSz] = '\0'; /* null term */
  24773. /* Read in the DHE business */
  24774. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  24775. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24776. }
  24777. ato16(input + args->idx, &clientSz);
  24778. args->idx += OPAQUE16_LEN;
  24779. if ((args->idx - args->begin) + clientSz > size) {
  24780. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24781. }
  24782. args->sigSz = clientSz;
  24783. ret = AllocKey(ssl, DYNAMIC_TYPE_DH,
  24784. (void**)&ssl->buffers.serverDH_Key);
  24785. if (ret != 0) {
  24786. goto exit_dcke;
  24787. }
  24788. ret = wc_DhSetKey(ssl->buffers.serverDH_Key,
  24789. ssl->buffers.serverDH_P.buffer,
  24790. ssl->buffers.serverDH_P.length,
  24791. ssl->buffers.serverDH_G.buffer,
  24792. ssl->buffers.serverDH_G.length);
  24793. break;
  24794. }
  24795. #endif /* !NO_DH && !NO_PSK */
  24796. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  24797. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  24798. case ecdhe_psk_kea:
  24799. {
  24800. word16 clientSz;
  24801. /* Read in the PSK hint */
  24802. if ((args->idx - args->begin) + OPAQUE16_LEN > size) {
  24803. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24804. }
  24805. ato16(input + args->idx, &clientSz);
  24806. args->idx += OPAQUE16_LEN;
  24807. if (clientSz > MAX_PSK_ID_LEN) {
  24808. ERROR_OUT(CLIENT_ID_ERROR, exit_dcke);
  24809. }
  24810. if ((args->idx - args->begin) + clientSz > size) {
  24811. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24812. }
  24813. XMEMCPY(ssl->arrays->client_identity,
  24814. input + args->idx, clientSz);
  24815. args->idx += clientSz;
  24816. ssl->arrays->client_identity[clientSz] = '\0'; /* null term */
  24817. /* import peer ECC key */
  24818. if ((args->idx - args->begin) + OPAQUE8_LEN > size) {
  24819. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24820. }
  24821. args->length = input[args->idx++];
  24822. if ((args->idx - args->begin) + args->length > size) {
  24823. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  24824. }
  24825. args->sigSz = ENCRYPT_LEN - OPAQUE16_LEN;
  24826. #ifdef HAVE_CURVE25519
  24827. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  24828. #ifdef HAVE_PK_CALLBACKS
  24829. /* if callback then use it for shared secret */
  24830. if (ssl->ctx->X25519SharedSecretCb != NULL) {
  24831. break;
  24832. }
  24833. #endif
  24834. if (ssl->eccTempKeyPresent == 0) {
  24835. WOLFSSL_MSG(
  24836. "X25519 ephemeral key not made correctly");
  24837. ERROR_OUT(ECC_MAKEKEY_ERROR, exit_dcke);
  24838. }
  24839. if (ssl->peerX25519Key == NULL) {
  24840. /* alloc/init on demand */
  24841. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE25519,
  24842. (void**)&ssl->peerX25519Key);
  24843. if (ret != 0) {
  24844. goto exit_dcke;
  24845. }
  24846. } else if (ssl->peerX25519KeyPresent) {
  24847. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE25519,
  24848. ssl->peerX25519Key);
  24849. ssl->peerX25519KeyPresent = 0;
  24850. if (ret != 0) {
  24851. goto exit_dcke;
  24852. }
  24853. }
  24854. if ((ret = wc_curve25519_check_public(
  24855. input + args->idx, args->length,
  24856. EC25519_LITTLE_ENDIAN)) != 0) {
  24857. #ifdef WOLFSSL_EXTRA_ALERTS
  24858. if (ret == BUFFER_E)
  24859. SendAlert(ssl, alert_fatal, decode_error);
  24860. else if (ret == ECC_OUT_OF_RANGE_E)
  24861. SendAlert(ssl, alert_fatal, bad_record_mac);
  24862. else {
  24863. SendAlert(ssl, alert_fatal,
  24864. illegal_parameter);
  24865. }
  24866. #endif
  24867. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  24868. }
  24869. if (wc_curve25519_import_public_ex(
  24870. input + args->idx, args->length,
  24871. ssl->peerX25519Key,
  24872. EC25519_LITTLE_ENDIAN)) {
  24873. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  24874. }
  24875. ssl->peerX25519KeyPresent = 1;
  24876. break;
  24877. }
  24878. #endif
  24879. #ifdef HAVE_CURVE448
  24880. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  24881. #ifdef HAVE_PK_CALLBACKS
  24882. /* if callback then use it for shared secret */
  24883. if (ssl->ctx->X448SharedSecretCb != NULL) {
  24884. break;
  24885. }
  24886. #endif
  24887. if (ssl->eccTempKeyPresent == 0) {
  24888. WOLFSSL_MSG(
  24889. "X448 ephemeral key not made correctly");
  24890. ERROR_OUT(ECC_MAKEKEY_ERROR, exit_dcke);
  24891. }
  24892. if (ssl->peerX448Key == NULL) {
  24893. /* alloc/init on demand */
  24894. ret = AllocKey(ssl, DYNAMIC_TYPE_CURVE448,
  24895. (void**)&ssl->peerX448Key);
  24896. if (ret != 0) {
  24897. goto exit_dcke;
  24898. }
  24899. } else if (ssl->peerX448KeyPresent) {
  24900. ret = ReuseKey(ssl, DYNAMIC_TYPE_CURVE448,
  24901. ssl->peerX448Key);
  24902. ssl->peerX448KeyPresent = 0;
  24903. if (ret != 0) {
  24904. goto exit_dcke;
  24905. }
  24906. }
  24907. if ((ret = wc_curve448_check_public(
  24908. input + args->idx, args->length,
  24909. EC448_LITTLE_ENDIAN)) != 0) {
  24910. #ifdef WOLFSSL_EXTRA_ALERTS
  24911. if (ret == BUFFER_E)
  24912. SendAlert(ssl, alert_fatal, decode_error);
  24913. else if (ret == ECC_OUT_OF_RANGE_E)
  24914. SendAlert(ssl, alert_fatal, bad_record_mac);
  24915. else {
  24916. SendAlert(ssl, alert_fatal,
  24917. illegal_parameter);
  24918. }
  24919. #endif
  24920. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  24921. }
  24922. if (wc_curve448_import_public_ex(
  24923. input + args->idx, args->length,
  24924. ssl->peerX448Key,
  24925. EC448_LITTLE_ENDIAN)) {
  24926. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  24927. }
  24928. ssl->peerX448KeyPresent = 1;
  24929. break;
  24930. }
  24931. #endif
  24932. #ifdef HAVE_PK_CALLBACKS
  24933. /* if callback then use it for shared secret */
  24934. if (ssl->ctx->EccSharedSecretCb != NULL) {
  24935. break;
  24936. }
  24937. #endif
  24938. if (ssl->eccTempKeyPresent == 0) {
  24939. WOLFSSL_MSG("Ecc ephemeral key not made correctly");
  24940. ERROR_OUT(ECC_MAKEKEY_ERROR, exit_dcke);
  24941. }
  24942. if (ssl->peerEccKey == NULL) {
  24943. /* alloc/init on demand */
  24944. ret = AllocKey(ssl, DYNAMIC_TYPE_ECC,
  24945. (void**)&ssl->peerEccKey);
  24946. if (ret != 0) {
  24947. goto exit_dcke;
  24948. }
  24949. }
  24950. else if (ssl->peerEccKeyPresent) {
  24951. ret = ReuseKey(ssl, DYNAMIC_TYPE_ECC,
  24952. ssl->peerEccKey);
  24953. ssl->peerEccKeyPresent = 0;
  24954. if (ret != 0) {
  24955. goto exit_dcke;
  24956. }
  24957. }
  24958. if (wc_ecc_import_x963_ex(input + args->idx,
  24959. args->length, ssl->peerEccKey,
  24960. ssl->eccTempKey->dp->id)) {
  24961. ERROR_OUT(ECC_PEERKEY_ERROR, exit_dcke);
  24962. }
  24963. ssl->peerEccKeyPresent = 1;
  24964. break;
  24965. }
  24966. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  24967. default:
  24968. ret = BAD_KEA_TYPE_E;
  24969. } /* switch (ssl->specs.kea) */
  24970. /* Check for error */
  24971. if (ret != 0) {
  24972. goto exit_dcke;
  24973. }
  24974. /* Advance state and proceed */
  24975. ssl->options.asyncState = TLS_ASYNC_DO;
  24976. } /* TLS_ASYNC_BUILD */
  24977. FALL_THROUGH;
  24978. case TLS_ASYNC_DO:
  24979. {
  24980. switch (ssl->specs.kea) {
  24981. #ifndef NO_RSA
  24982. case rsa_kea:
  24983. {
  24984. RsaKey* key = (RsaKey*)ssl->hsKey;
  24985. ret = RsaDec(ssl,
  24986. input + args->idx,
  24987. args->length,
  24988. &args->output,
  24989. &args->sigSz,
  24990. key,
  24991. #ifdef HAVE_PK_CALLBACKS
  24992. ssl->buffers.key
  24993. #else
  24994. NULL
  24995. #endif
  24996. );
  24997. /* Errors that can occur here that should be
  24998. * indistinguishable:
  24999. * RSA_BUFFER_E, RSA_PAD_E and RSA_PRIVATE_ERROR
  25000. */
  25001. #ifdef WOLFSSL_ASYNC_CRYPT
  25002. if (ret == WC_PENDING_E)
  25003. goto exit_dcke;
  25004. #endif
  25005. if (ret == BAD_FUNC_ARG)
  25006. goto exit_dcke;
  25007. args->lastErr = ret - (SECRET_LEN - args->sigSz);
  25008. ret = 0;
  25009. break;
  25010. } /* rsa_kea */
  25011. #endif /* !NO_RSA */
  25012. #ifndef NO_PSK
  25013. case psk_kea:
  25014. {
  25015. break;
  25016. }
  25017. #endif /* !NO_PSK */
  25018. #ifdef HAVE_NTRU
  25019. case ntru_kea:
  25020. {
  25021. break;
  25022. }
  25023. #endif /* HAVE_NTRU */
  25024. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  25025. defined(HAVE_CURVE448)
  25026. case ecc_diffie_hellman_kea:
  25027. {
  25028. void* private_key = ssl->eccTempKey;
  25029. (void)private_key;
  25030. #ifdef HAVE_CURVE25519
  25031. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  25032. ret = X25519SharedSecret(ssl,
  25033. (curve25519_key*)private_key,
  25034. ssl->peerX25519Key,
  25035. input + args->idx, &args->length,
  25036. ssl->arrays->preMasterSecret,
  25037. &ssl->arrays->preMasterSz,
  25038. WOLFSSL_SERVER_END
  25039. );
  25040. break;
  25041. }
  25042. #endif
  25043. #ifdef HAVE_CURVE448
  25044. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  25045. ret = X448SharedSecret(ssl,
  25046. (curve448_key*)private_key,
  25047. ssl->peerX448Key,
  25048. input + args->idx, &args->length,
  25049. ssl->arrays->preMasterSecret,
  25050. &ssl->arrays->preMasterSz,
  25051. WOLFSSL_SERVER_END
  25052. );
  25053. break;
  25054. }
  25055. #endif
  25056. #ifdef HAVE_ECC
  25057. if (ssl->specs.static_ecdh) {
  25058. private_key = ssl->hsKey;
  25059. }
  25060. /* Generate shared secret */
  25061. ret = EccSharedSecret(ssl,
  25062. (ecc_key*)private_key, ssl->peerEccKey,
  25063. input + args->idx, &args->length,
  25064. ssl->arrays->preMasterSecret,
  25065. &ssl->arrays->preMasterSz,
  25066. WOLFSSL_SERVER_END
  25067. );
  25068. #ifdef WOLFSSL_ASYNC_CRYPT
  25069. if (ret != WC_PENDING_E)
  25070. #endif
  25071. {
  25072. FreeKey(ssl, DYNAMIC_TYPE_ECC,
  25073. (void**)&ssl->peerEccKey);
  25074. ssl->peerEccKeyPresent = 0;
  25075. }
  25076. #endif
  25077. break;
  25078. }
  25079. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  25080. #ifndef NO_DH
  25081. case diffie_hellman_kea:
  25082. {
  25083. ret = DhAgree(ssl, ssl->buffers.serverDH_Key,
  25084. ssl->buffers.serverDH_Priv.buffer,
  25085. ssl->buffers.serverDH_Priv.length,
  25086. input + args->idx,
  25087. (word16)args->sigSz,
  25088. ssl->arrays->preMasterSecret,
  25089. &ssl->arrays->preMasterSz);
  25090. break;
  25091. }
  25092. #endif /* !NO_DH */
  25093. #if !defined(NO_DH) && !defined(NO_PSK)
  25094. case dhe_psk_kea:
  25095. {
  25096. ret = DhAgree(ssl, ssl->buffers.serverDH_Key,
  25097. ssl->buffers.serverDH_Priv.buffer,
  25098. ssl->buffers.serverDH_Priv.length,
  25099. input + args->idx,
  25100. (word16)args->sigSz,
  25101. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  25102. &ssl->arrays->preMasterSz);
  25103. break;
  25104. }
  25105. #endif /* !NO_DH && !NO_PSK */
  25106. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  25107. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  25108. case ecdhe_psk_kea:
  25109. {
  25110. #ifdef HAVE_CURVE25519
  25111. if (ssl->ecdhCurveOID == ECC_X25519_OID) {
  25112. ret = X25519SharedSecret(ssl,
  25113. (curve25519_key*)ssl->eccTempKey,
  25114. ssl->peerX25519Key,
  25115. input + args->idx, &args->length,
  25116. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  25117. &args->sigSz,
  25118. WOLFSSL_SERVER_END
  25119. );
  25120. #ifdef WOLFSSL_ASYNC_CRYPT
  25121. if (ret != WC_PENDING_E)
  25122. #endif
  25123. {
  25124. FreeKey(ssl, DYNAMIC_TYPE_CURVE25519,
  25125. (void**)&ssl->peerX25519Key);
  25126. ssl->peerX25519KeyPresent = 0;
  25127. }
  25128. break;
  25129. }
  25130. #endif
  25131. #ifdef HAVE_CURVE448
  25132. if (ssl->ecdhCurveOID == ECC_X448_OID) {
  25133. ret = X448SharedSecret(ssl,
  25134. (curve448_key*)ssl->eccTempKey,
  25135. ssl->peerX448Key,
  25136. input + args->idx, &args->length,
  25137. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  25138. &args->sigSz,
  25139. WOLFSSL_SERVER_END
  25140. );
  25141. #ifdef WOLFSSL_ASYNC_CRYPT
  25142. if (ret != WC_PENDING_E)
  25143. #endif
  25144. {
  25145. FreeKey(ssl, DYNAMIC_TYPE_CURVE448,
  25146. (void**)&ssl->peerX448Key);
  25147. ssl->peerX448KeyPresent = 0;
  25148. }
  25149. break;
  25150. }
  25151. #endif
  25152. /* Generate shared secret */
  25153. ret = EccSharedSecret(ssl,
  25154. ssl->eccTempKey, ssl->peerEccKey,
  25155. input + args->idx, &args->length,
  25156. ssl->arrays->preMasterSecret + OPAQUE16_LEN,
  25157. &args->sigSz,
  25158. WOLFSSL_SERVER_END
  25159. );
  25160. if (!ssl->specs.static_ecdh
  25161. #ifdef WOLFSSL_ASYNC_CRYPT
  25162. && ret != WC_PENDING_E
  25163. #endif
  25164. ) {
  25165. FreeKey(ssl, DYNAMIC_TYPE_ECC,
  25166. (void**)&ssl->peerEccKey);
  25167. ssl->peerEccKeyPresent = 0;
  25168. }
  25169. break;
  25170. }
  25171. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  25172. default:
  25173. ret = BAD_KEA_TYPE_E;
  25174. } /* switch (ssl->specs.kea) */
  25175. /* Check for error */
  25176. if (ret != 0) {
  25177. goto exit_dcke;
  25178. }
  25179. /* Advance state and proceed */
  25180. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  25181. } /* TLS_ASYNC_DO */
  25182. FALL_THROUGH;
  25183. case TLS_ASYNC_VERIFY:
  25184. {
  25185. switch (ssl->specs.kea) {
  25186. #ifndef NO_RSA
  25187. case rsa_kea:
  25188. {
  25189. byte mask;
  25190. int i;
  25191. /* Add the signature length to idx */
  25192. args->idx += args->length;
  25193. #ifdef DEBUG_WOLFSSL
  25194. /* check version (debug warning message only) */
  25195. if (args->output != NULL) {
  25196. if (args->output[0] != ssl->chVersion.major ||
  25197. args->output[1] != ssl->chVersion.minor) {
  25198. WOLFSSL_MSG("preMasterSecret version mismatch");
  25199. }
  25200. }
  25201. #endif
  25202. /* RFC5246 7.4.7.1:
  25203. * Treat incorrectly formatted message blocks and/or
  25204. * mismatched version numbers in a manner
  25205. * indistinguishable from correctly formatted RSA blocks
  25206. */
  25207. ret = args->lastErr;
  25208. args->lastErr = 0; /* reset */
  25209. /* On error 'ret' will be negative - top bit set */
  25210. mask = ((unsigned int)ret >>
  25211. ((sizeof(ret) * 8) - 1)) - 1;
  25212. /* build PreMasterSecret */
  25213. ssl->arrays->preMasterSecret[0] = ssl->chVersion.major;
  25214. ssl->arrays->preMasterSecret[1] = ssl->chVersion.minor;
  25215. if (args->output != NULL) {
  25216. /* Use random secret on error */
  25217. for (i = VERSION_SZ; i < SECRET_LEN; i++) {
  25218. ssl->arrays->preMasterSecret[i] =
  25219. ctMaskSel(mask, args->output[i],
  25220. ssl->arrays->preMasterSecret[i]);
  25221. }
  25222. }
  25223. /* preMasterSecret has RNG and version set
  25224. * return proper length and ignore error
  25225. * error will be caught as decryption error
  25226. */
  25227. args->sigSz = SECRET_LEN;
  25228. ret = 0;
  25229. break;
  25230. } /* rsa_kea */
  25231. #endif /* !NO_RSA */
  25232. #ifndef NO_PSK
  25233. case psk_kea:
  25234. {
  25235. break;
  25236. }
  25237. #endif /* !NO_PSK */
  25238. #ifdef HAVE_NTRU
  25239. case ntru_kea:
  25240. {
  25241. break;
  25242. }
  25243. #endif /* HAVE_NTRU */
  25244. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  25245. defined(HAVE_CURVE448)
  25246. case ecc_diffie_hellman_kea:
  25247. {
  25248. /* skip past the imported peer key */
  25249. args->idx += args->length;
  25250. break;
  25251. }
  25252. #endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
  25253. #ifndef NO_DH
  25254. case diffie_hellman_kea:
  25255. {
  25256. args->idx += (word16)args->sigSz;
  25257. break;
  25258. }
  25259. #endif /* !NO_DH */
  25260. #if !defined(NO_DH) && !defined(NO_PSK)
  25261. case dhe_psk_kea:
  25262. {
  25263. byte* pms = ssl->arrays->preMasterSecret;
  25264. word16 clientSz = (word16)args->sigSz;
  25265. args->idx += clientSz;
  25266. c16toa((word16)ssl->arrays->preMasterSz, pms);
  25267. ssl->arrays->preMasterSz += OPAQUE16_LEN;
  25268. pms += ssl->arrays->preMasterSz;
  25269. /* Use the PSK hint to look up the PSK and add it to the
  25270. * preMasterSecret here. */
  25271. ssl->arrays->psk_keySz = ssl->options.server_psk_cb(ssl,
  25272. ssl->arrays->client_identity, ssl->arrays->psk_key,
  25273. MAX_PSK_KEY_LEN);
  25274. if (ssl->arrays->psk_keySz == 0 ||
  25275. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  25276. ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
  25277. }
  25278. c16toa((word16) ssl->arrays->psk_keySz, pms);
  25279. pms += OPAQUE16_LEN;
  25280. XMEMCPY(pms, ssl->arrays->psk_key,
  25281. ssl->arrays->psk_keySz);
  25282. ssl->arrays->preMasterSz += ssl->arrays->psk_keySz +
  25283. OPAQUE16_LEN;
  25284. break;
  25285. }
  25286. #endif /* !NO_DH && !NO_PSK */
  25287. #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
  25288. defined(HAVE_CURVE448)) && !defined(NO_PSK)
  25289. case ecdhe_psk_kea:
  25290. {
  25291. byte* pms = ssl->arrays->preMasterSecret;
  25292. word16 clientSz = (word16)args->sigSz;
  25293. /* skip past the imported peer key */
  25294. args->idx += args->length;
  25295. /* Add preMasterSecret */
  25296. c16toa(clientSz, pms);
  25297. ssl->arrays->preMasterSz = OPAQUE16_LEN + clientSz;
  25298. pms += ssl->arrays->preMasterSz;
  25299. /* Use the PSK hint to look up the PSK and add it to the
  25300. * preMasterSecret here. */
  25301. ssl->arrays->psk_keySz = ssl->options.server_psk_cb(ssl,
  25302. ssl->arrays->client_identity, ssl->arrays->psk_key,
  25303. MAX_PSK_KEY_LEN);
  25304. if (ssl->arrays->psk_keySz == 0 ||
  25305. ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
  25306. ERROR_OUT(PSK_KEY_ERROR, exit_dcke);
  25307. }
  25308. c16toa((word16) ssl->arrays->psk_keySz, pms);
  25309. pms += OPAQUE16_LEN;
  25310. XMEMCPY(pms, ssl->arrays->psk_key, ssl->arrays->psk_keySz);
  25311. ssl->arrays->preMasterSz +=
  25312. ssl->arrays->psk_keySz + OPAQUE16_LEN;
  25313. break;
  25314. }
  25315. #endif /* (HAVE_ECC || CURVE25519 || CURVE448) && !NO_PSK */
  25316. default:
  25317. ret = BAD_KEA_TYPE_E;
  25318. } /* switch (ssl->specs.kea) */
  25319. /* Check for error */
  25320. if (ret != 0) {
  25321. goto exit_dcke;
  25322. }
  25323. /* Advance state and proceed */
  25324. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  25325. } /* TLS_ASYNC_VERIFY */
  25326. FALL_THROUGH;
  25327. case TLS_ASYNC_FINALIZE:
  25328. {
  25329. if (IsEncryptionOn(ssl, 0)) {
  25330. args->idx += ssl->keys.padSz;
  25331. #if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
  25332. if (ssl->options.startedETMRead)
  25333. args->idx += MacSize(ssl);
  25334. #endif
  25335. }
  25336. #ifdef HAVE_QSH
  25337. word16 name;
  25338. if (ssl->options.haveQSH) {
  25339. /* extension name */
  25340. ato16(input + args->idx, &name);
  25341. args->idx += OPAQUE16_LEN;
  25342. if (name == TLSX_QUANTUM_SAFE_HYBRID) {
  25343. int qshSz;
  25344. /* if qshSz is larger than 0 it is the
  25345. length of buffer used */
  25346. if ((qshSz = TLSX_QSHCipher_Parse(ssl,
  25347. input + args->idx,
  25348. size - args->idx + args->begin, 1)) < 0) {
  25349. ERROR_OUT(qshSz, exit_dcke);
  25350. }
  25351. args->idx += qshSz;
  25352. }
  25353. else {
  25354. /* unknown extension sent client ignored handshake */
  25355. ERROR_OUT(BUFFER_ERROR, exit_dcke);
  25356. }
  25357. }
  25358. #endif /* HAVE_QSH */
  25359. ret = MakeMasterSecret(ssl);
  25360. /* Check for error */
  25361. if (ret != 0) {
  25362. goto exit_dcke;
  25363. }
  25364. /* Advance state and proceed */
  25365. ssl->options.asyncState = TLS_ASYNC_END;
  25366. } /* TLS_ASYNC_FINALIZE */
  25367. FALL_THROUGH;
  25368. case TLS_ASYNC_END:
  25369. {
  25370. /* Set final index */
  25371. *inOutIdx = args->idx;
  25372. ssl->options.clientState = CLIENT_KEYEXCHANGE_COMPLETE;
  25373. #ifndef NO_CERTS
  25374. if (ssl->options.verifyPeer) {
  25375. ret = BuildCertHashes(ssl, &ssl->hsHashes->certHashes);
  25376. }
  25377. #endif
  25378. break;
  25379. } /* TLS_ASYNC_END */
  25380. default:
  25381. ret = INPUT_CASE_ERROR;
  25382. } /* switch(ssl->options.asyncState) */
  25383. exit_dcke:
  25384. WOLFSSL_LEAVE("DoClientKeyExchange", ret);
  25385. WOLFSSL_END(WC_FUNC_CLIENT_KEY_EXCHANGE_DO);
  25386. #ifdef WOLFSSL_ASYNC_CRYPT
  25387. /* Handle async operation */
  25388. if (ret == WC_PENDING_E) {
  25389. /* Mark message as not received so it can process again */
  25390. ssl->msgsReceived.got_client_key_exchange = 0;
  25391. return ret;
  25392. }
  25393. #endif /* WOLFSSL_ASYNC_CRYPT */
  25394. /* Cleanup PMS */
  25395. if (ssl->arrays->preMasterSecret != NULL) {
  25396. ForceZero(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
  25397. }
  25398. ssl->arrays->preMasterSz = 0;
  25399. /* Final cleanup */
  25400. FreeDckeArgs(ssl, args);
  25401. FreeKeyExchange(ssl);
  25402. return ret;
  25403. }
  25404. #endif /* !WOLFSSL_NO_TLS12 */
  25405. #if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
  25406. defined(WOLFSSL_HAPROXY)
  25407. int SNI_Callback(WOLFSSL* ssl)
  25408. {
  25409. /* Stunnel supports a custom sni callback to switch an SSL's ctx
  25410. * when SNI is received. Call it now if exists */
  25411. if(ssl && ssl->ctx && ssl->ctx->sniRecvCb) {
  25412. WOLFSSL_MSG("Calling custom sni callback");
  25413. if(ssl->ctx->sniRecvCb(ssl, NULL, ssl->ctx->sniRecvCbArg)
  25414. == alert_fatal) {
  25415. WOLFSSL_MSG("Error in custom sni callback. Fatal alert");
  25416. SendAlert(ssl, alert_fatal, unrecognized_name);
  25417. return FATAL_ERROR;
  25418. }
  25419. }
  25420. return 0;
  25421. }
  25422. #endif /* OPENSSL_ALL || HAVE_STUNNEL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  25423. #endif /* NO_WOLFSSL_SERVER */
  25424. #ifdef WOLFSSL_ASYNC_CRYPT
  25425. int wolfSSL_AsyncPop(WOLFSSL* ssl, byte* state)
  25426. {
  25427. int ret = 0;
  25428. WC_ASYNC_DEV* asyncDev;
  25429. WOLF_EVENT* event;
  25430. if (ssl == NULL) {
  25431. return BAD_FUNC_ARG;
  25432. }
  25433. /* check for pending async */
  25434. asyncDev = ssl->async.dev;
  25435. if (asyncDev) {
  25436. /* grab event pointer */
  25437. event = &asyncDev->event;
  25438. ret = wolfAsync_EventPop(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL);
  25439. if (ret != WC_NOT_PENDING_E && ret != WC_PENDING_E) {
  25440. /* advance key share state if doesn't need called again */
  25441. if (state && (asyncDev->event.flags & WC_ASYNC_FLAG_CALL_AGAIN) == 0) {
  25442. (*state)++;
  25443. }
  25444. /* clear event */
  25445. XMEMSET(&asyncDev->event, 0, sizeof(WOLF_EVENT));
  25446. /* clear async dev */
  25447. ssl->async.dev = NULL;
  25448. }
  25449. }
  25450. else {
  25451. ret = WC_NOT_PENDING_E;
  25452. }
  25453. WOLFSSL_LEAVE("wolfSSL_AsyncPop", ret);
  25454. return ret;
  25455. }
  25456. int wolfSSL_AsyncInit(WOLFSSL* ssl, WC_ASYNC_DEV* asyncDev, word32 flags)
  25457. {
  25458. int ret;
  25459. WOLF_EVENT* event;
  25460. if (ssl == NULL || asyncDev == NULL) {
  25461. return BAD_FUNC_ARG;
  25462. }
  25463. /* grab event pointer */
  25464. event = &asyncDev->event;
  25465. /* init event */
  25466. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL, ssl, flags);
  25467. WOLFSSL_LEAVE("wolfSSL_AsyncInit", ret);
  25468. return ret;
  25469. }
  25470. int wolfSSL_AsyncPush(WOLFSSL* ssl, WC_ASYNC_DEV* asyncDev)
  25471. {
  25472. int ret;
  25473. WOLF_EVENT* event;
  25474. if (ssl == NULL || asyncDev == NULL) {
  25475. return BAD_FUNC_ARG;
  25476. }
  25477. /* grab event pointer */
  25478. event = &asyncDev->event;
  25479. /* store reference to active async operation */
  25480. ssl->async.dev = asyncDev;
  25481. /* place event into queue */
  25482. ret = wolfAsync_EventQueuePush(&ssl->ctx->event_queue, event);
  25483. /* success means return WC_PENDING_E */
  25484. if (ret == 0) {
  25485. ret = WC_PENDING_E;
  25486. }
  25487. WOLFSSL_LEAVE("wolfSSL_AsyncPush", ret);
  25488. return ret;
  25489. }
  25490. #endif /* WOLFSSL_ASYNC_CRYPT */
  25491. /* return the max record size */
  25492. int wolfSSL_GetMaxRecordSize(WOLFSSL* ssl, int maxFragment)
  25493. {
  25494. (void) ssl; /* Avoid compiler warnings */
  25495. if (maxFragment > MAX_RECORD_SIZE) {
  25496. maxFragment = MAX_RECORD_SIZE;
  25497. }
  25498. #ifdef HAVE_MAX_FRAGMENT
  25499. if ((ssl->max_fragment != 0) && ((word16)maxFragment > ssl->max_fragment)) {
  25500. maxFragment = ssl->max_fragment;
  25501. }
  25502. #endif /* HAVE_MAX_FRAGMENT */
  25503. #ifdef WOLFSSL_DTLS
  25504. if ((ssl->options.dtls) && (maxFragment > MAX_UDP_SIZE)) {
  25505. maxFragment = MAX_UDP_SIZE;
  25506. }
  25507. #endif
  25508. return maxFragment;
  25509. }
  25510. #undef ERROR_OUT
  25511. #endif /* WOLFCRYPT_ONLY */