sniffer.c 228 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571
  1. /* sniffer.c
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #include <wolfssl/wolfcrypt/types.h>
  26. #include <wolfssl/wolfcrypt/wc_port.h>
  27. #ifdef WOLFSSL_ASYNC_CRYPT
  28. #include <wolfssl/wolfcrypt/async.h>
  29. #endif
  30. /* Build Options:
  31. * WOLFSSL_SNIFFER_NO_RECOVERY: Do not track missed data count.
  32. */
  33. /* xctime */
  34. #ifndef XCTIME
  35. #define XCTIME ctime
  36. #endif
  37. /* only in this file, to avoid confusing future ports leave
  38. * these defines here. Do not move to wc_port.h */
  39. #ifdef USER_CUSTOM_SNIFFX
  40. /* To be implemented in user_settings.h */
  41. #elif defined(FUSION_RTOS)
  42. #include <fcl_network.h>
  43. #define XINET_NTOA FNS_INET_NTOA
  44. #define XINET_ATON FNS_INET_ATON
  45. #define XINET_PTON(a,b,c,d) FNS_INET_PTON((a),(b),(c),(d),NULL)
  46. #define XINET_NTOP(a,b,c,d) FNS_INET_NTOP((a),(b),(c),(d),NULL)
  47. #define XINET_ADDR FNS_INET_ADDR
  48. #define XHTONS FNS_HTONS
  49. #define XNTOHS FNS_NTOHS
  50. #define XHTONL FNS_HTONL
  51. #define XNTOHL FNS_NTOHL
  52. #define XINADDR_NONE FNS_INADDR_NONE
  53. #else
  54. /* default */
  55. #define XINET_NTOA inet_ntoa
  56. #define XINET_ATON inet_aton
  57. #define XINET_PTON(a,b,c) inet_pton((a),(b),(c))
  58. #define XINET_NTOP inet_ntop
  59. #define XINET_ADDR inet_addr
  60. #define XHTONS htons
  61. #define XNTOHS ntohs
  62. #define XHTONL htonl
  63. #define XNTOHL ntohl
  64. #define XINADDR_NONE INADDR_NONE
  65. #endif
  66. #if !defined(WOLFCRYPT_ONLY) && !defined(NO_FILESYSTEM)
  67. #ifdef WOLFSSL_SNIFFER
  68. #include <time.h>
  69. #ifdef FUSION_RTOS
  70. #include <fns_inet.h>
  71. #ifdef TCP_PROTOCOL
  72. #undef TCP_PROTOCOL
  73. #endif
  74. #else
  75. #ifndef _WIN32
  76. #include <arpa/inet.h>
  77. #else
  78. #include <ws2tcpip.h>
  79. #endif
  80. #endif
  81. #ifdef _WIN32
  82. #define SNPRINTF _snprintf
  83. #else
  84. #define SNPRINTF snprintf
  85. #endif
  86. #include <wolfssl/internal.h>
  87. #include <wolfssl/error-ssl.h>
  88. #include <wolfssl/sniffer.h>
  89. #include <wolfssl/sniffer_error.h>
  90. #ifndef NO_RSA
  91. #include <wolfssl/wolfcrypt/rsa.h>
  92. #endif
  93. #ifndef NO_DH
  94. #include <wolfssl/wolfcrypt/dh.h>
  95. #endif
  96. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519)
  97. #include <wolfssl/wolfcrypt/ecc.h>
  98. #endif
  99. #ifdef HAVE_CURVE25519
  100. #include <wolfssl/wolfcrypt/curve25519.h>
  101. #endif
  102. #ifdef NO_INLINE
  103. #include <wolfssl/wolfcrypt/misc.h>
  104. #else
  105. #define WOLFSSL_MISC_INCLUDED
  106. #include <wolfcrypt/src/misc.c>
  107. #endif
  108. #ifdef WOLF_CRYPTO_CB
  109. #include <wolfssl/wolfcrypt/cryptocb.h>
  110. #ifdef HAVE_INTEL_QA_SYNC
  111. #include <wolfssl/wolfcrypt/port/intel/quickassist_sync.h>
  112. #endif
  113. #ifdef HAVE_CAVIUM_OCTEON_SYNC
  114. #include <wolfssl/wolfcrypt/port/cavium/cavium_octeon_sync.h>
  115. #endif
  116. #endif
  117. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  118. #ifndef WOLFSSL_SNIFFER_TIMEOUT
  119. #define WOLFSSL_SNIFFER_TIMEOUT 900
  120. /* Cache unclosed Sessions for 15 minutes since last used */
  121. #endif
  122. /* Misc constants */
  123. enum {
  124. MAX_SERVER_ADDRESS = 128, /* maximum server address length */
  125. MAX_SERVER_NAME = 128, /* maximum server name length */
  126. MAX_ERROR_LEN = 80, /* maximum error length */
  127. ETHER_IF_ADDR_LEN = 6, /* ethernet interface address length */
  128. LOCAL_IF_ADDR_LEN = 4, /* localhost interface address length, !windows */
  129. TCP_PROTO = 6, /* TCP_PROTOCOL */
  130. IP_HDR_SZ = 20, /* IPv4 header length, min */
  131. IP6_HDR_SZ = 40, /* IPv6 header length, min */
  132. TCP_HDR_SZ = 20, /* TCP header length, min */
  133. IPV4 = 4, /* IP version 4 */
  134. IPV6 = 6, /* IP version 6 */
  135. TCP_PROTOCOL = 6, /* TCP Protocol id */
  136. NO_NEXT_HEADER = 59, /* IPv6 no headers follow */
  137. TRACE_MSG_SZ = 80, /* Trace Message buffer size */
  138. HASH_SIZE = 499, /* Session Hash Table Rows */
  139. PSEUDO_HDR_SZ = 12, /* TCP Pseudo Header size in bytes */
  140. STREAM_INFO_SZ = 44, /* SnifferStreamInfo size in bytes */
  141. FATAL_ERROR_STATE = 1, /* SnifferSession fatal error state */
  142. TICKET_HINT_LEN = 4, /* Session Ticket Hint length */
  143. TICKET_HINT_AGE_LEN= 4, /* Session Ticket Age add length */
  144. EXT_TYPE_SZ = 2, /* Extension type length */
  145. MAX_INPUT_SZ = MAX_RECORD_SIZE + COMP_EXTRA + MAX_MSG_EXTRA +
  146. MTU_EXTRA, /* Max input sz of reassembly */
  147. /* TLS Extensions */
  148. EXT_SERVER_NAME = 0x0000, /* a.k.a. SNI */
  149. EXT_MAX_FRAGMENT_LENGTH = 0x0001,
  150. EXT_TRUSTED_CA_KEYS = 0x0003,
  151. EXT_TRUNCATED_HMAC = 0x0004,
  152. EXT_STATUS_REQUEST = 0x0005, /* a.k.a. OCSP stapling */
  153. EXT_SUPPORTED_GROUPS = 0x000a, /* a.k.a. Supported Curves */
  154. EXT_EC_POINT_FORMATS = 0x000b,
  155. EXT_SIGNATURE_ALGORITHMS = 0x000d,
  156. EXT_APPLICATION_LAYER_PROTOCOL = 0x0010, /* a.k.a. ALPN */
  157. EXT_STATUS_REQUEST_V2 = 0x0011, /* a.k.a. OCSP stapling v2 */
  158. EXT_ENCRYPT_THEN_MAC = 0x0016, /* RFC 7366 */
  159. EXT_MASTER_SECRET = 0x0017, /* Extended Master Secret Extension ID */
  160. EXT_TICKET_ID = 0x0023, /* Session Ticket Extension ID */
  161. EXT_PRE_SHARED_KEY = 0x0029,
  162. EXT_EARLY_DATA = 0x002a,
  163. EXT_SUPPORTED_VERSIONS = 0x002b,
  164. EXT_COOKIE = 0x002c,
  165. EXT_PSK_KEY_EXCHANGE_MODES = 0x002d,
  166. EXT_POST_HANDSHAKE_AUTH = 0x0031,
  167. EXT_SIGNATURE_ALGORITHMS_CERT = 0x0032,
  168. EXT_KEY_SHARE = 0x0033,
  169. EXT_RENEGOTIATION_INFO = 0xff01
  170. };
  171. #ifdef _WIN32
  172. static HMODULE dllModule; /* for error string resources */
  173. BOOL APIENTRY DllMain( HMODULE hModule,
  174. DWORD ul_reason_for_call,
  175. LPVOID lpReserved
  176. )
  177. {
  178. static int didInit = 0;
  179. switch (ul_reason_for_call)
  180. {
  181. case DLL_PROCESS_ATTACH:
  182. if (didInit == 0) {
  183. dllModule = hModule;
  184. ssl_InitSniffer();
  185. didInit = 1;
  186. }
  187. break;
  188. case DLL_THREAD_ATTACH:
  189. break;
  190. case DLL_THREAD_DETACH:
  191. break;
  192. case DLL_PROCESS_DETACH:
  193. if (didInit) {
  194. ssl_FreeSniffer();
  195. didInit = 0;
  196. }
  197. break;
  198. }
  199. return TRUE;
  200. }
  201. #endif /* _WIN32 */
  202. static WOLFSSL_GLOBAL int TraceOn = 0; /* Trace is off by default */
  203. static WOLFSSL_GLOBAL XFILE TraceFile = 0;
  204. /* windows uses .rc table for this */
  205. #ifndef _WIN32
  206. static const char* const msgTable[] =
  207. {
  208. /* 1 */
  209. "Out of Memory",
  210. "New SSL Sniffer Server Registered",
  211. "Checking IP Header",
  212. "SSL Sniffer Server Not Registered",
  213. "Checking TCP Header",
  214. /* 6 */
  215. "SSL Sniffer Server Port Not Registered",
  216. "RSA Private Decrypt Error",
  217. "RSA Private Decode Error",
  218. "Set Cipher Spec Error",
  219. "Server Hello Input Malformed",
  220. /* 11 */
  221. "Couldn't Resume Session Error",
  222. "Server Did Resumption",
  223. "Client Hello Input Malformed",
  224. "Client Trying to Resume",
  225. "Handshake Input Malformed",
  226. /* 16 */
  227. "Got Hello Verify msg",
  228. "Got Server Hello msg",
  229. "Got Cert Request msg",
  230. "Got Server Key Exchange msg",
  231. "Got Cert msg",
  232. /* 21 */
  233. "Got Server Hello Done msg",
  234. "Got Finished msg",
  235. "Got Client Hello msg",
  236. "Got Client Key Exchange msg",
  237. "Got Cert Verify msg",
  238. /* 26 */
  239. "Got Unknown Handshake msg",
  240. "New SSL Sniffer Session created",
  241. "Couldn't create new SSL",
  242. "Got a Packet to decode",
  243. "No data present",
  244. /* 31 */
  245. "Session Not Found",
  246. "Got an Old Client Hello msg",
  247. "Old Client Hello Input Malformed",
  248. "Old Client Hello OK",
  249. "Bad Old Client Hello",
  250. /* 36 */
  251. "Bad Record Header",
  252. "Record Header Input Malformed",
  253. "Got a HandShake msg",
  254. "Bad HandShake msg",
  255. "Got a Change Cipher Spec msg",
  256. /* 41 */
  257. "Got Application Data msg",
  258. "Bad Application Data",
  259. "Got an Alert msg",
  260. "Another msg to Process",
  261. "Removing Session From Table",
  262. /* 46 */
  263. "Bad Key File",
  264. "Wrong IP Version",
  265. "Wrong Protocol type",
  266. "Packet Short for header processing",
  267. "Got Unknown Record Type",
  268. /* 51 */
  269. "Can't Open Trace File",
  270. "Session in Fatal Error State",
  271. "Partial SSL record received",
  272. "Buffer Error, malformed input",
  273. "Added to Partial Input",
  274. /* 56 */
  275. "Received a Duplicate Packet",
  276. "Received an Out of Order Packet",
  277. "Received an Overlap Duplicate Packet",
  278. "Received an Overlap Reassembly Begin Duplicate Packet",
  279. "Received an Overlap Reassembly End Duplicate Packet",
  280. /* 61 */
  281. "Missed the Client Hello Entirely",
  282. "Got Hello Request msg",
  283. "Got Session Ticket msg",
  284. "Bad Input",
  285. "Bad Decrypt Type",
  286. /* 66 */
  287. "Bad Finished Message Processing",
  288. "Bad Compression Type",
  289. "Bad DeriveKeys Error",
  290. "Saw ACK for Missing Packet Error",
  291. "Bad Decrypt Operation",
  292. /* 71 */
  293. "Decrypt Keys Not Set Up",
  294. "Late Key Load Error",
  295. "Got Certificate Status msg",
  296. "RSA Key Missing Error",
  297. "Secure Renegotiation Not Supported",
  298. /* 76 */
  299. "Get Session Stats Failure",
  300. "Reassembly Buffer Size Exceeded",
  301. "Dropping Lost Fragment",
  302. "Dropping Partial Record",
  303. "Clear ACK Fault",
  304. /* 81 */
  305. "Bad Decrypt Size",
  306. "Extended Master Secret Hash Error",
  307. "Handshake Message Split Across TLS Records",
  308. "ECC Private Decode Error",
  309. "ECC Public Decode Error",
  310. /* 86 */
  311. "Watch callback not set",
  312. "Watch hash failed",
  313. "Watch callback failed",
  314. "Bad Certificate Message",
  315. "Store data callback not set",
  316. /* 91 */
  317. "No data destination Error",
  318. "Store data callback failed",
  319. "Loading chain input",
  320. "Got encrypted extension",
  321. "Got Hello Retry Request",
  322. /* 96 */
  323. "Setting up keys",
  324. "Unsupported TLS Version",
  325. "Server Client Key Mismatch",
  326. /* 99 */
  327. "Invalid or missing keylog file",
  328. };
  329. /* *nix version uses table above */
  330. static void GetError(int idx, char* str)
  331. {
  332. if (str == NULL ||
  333. idx <= 0 || idx > (int)(sizeof(msgTable)/sizeof(const char* const)))
  334. return;
  335. XSTRNCPY(str, msgTable[idx - 1], MAX_ERROR_LEN-1);
  336. str[MAX_ERROR_LEN-1] = '\0';
  337. }
  338. #else /* _WIN32 */
  339. /* Windows version uses .rc table */
  340. static void GetError(int idx, char* buffer)
  341. {
  342. if (buffer == NULL)
  343. return;
  344. if (!LoadStringA(dllModule, idx, buffer, MAX_ERROR_LEN))
  345. buffer[0] = 0;
  346. }
  347. #endif /* _WIN32 */
  348. /* Packet Buffer for reassembly list and ready list */
  349. typedef struct PacketBuffer {
  350. word32 begin; /* relative sequence begin */
  351. word32 end; /* relative sequence end */
  352. byte* data; /* actual data */
  353. struct PacketBuffer* next; /* next on reassembly list or ready list */
  354. } PacketBuffer;
  355. #ifdef HAVE_SNI
  356. /* NamedKey maps a SNI name to a specific private key */
  357. typedef struct NamedKey {
  358. char name[MAX_SERVER_NAME]; /* server DNS name */
  359. word32 nameSz; /* size of server DNS name */
  360. byte* key; /* DER private key */
  361. word32 keySz; /* size of DER private key */
  362. int isEphemeralKey;
  363. struct NamedKey* next; /* for list */
  364. } NamedKey;
  365. #endif
  366. /* Sniffer Server holds info for each server/port monitored */
  367. typedef struct SnifferServer {
  368. WOLFSSL_CTX* ctx; /* SSL context */
  369. char address[MAX_SERVER_ADDRESS]; /* passed in server address */
  370. IpAddrInfo server; /* network order address */
  371. int port; /* server port */
  372. #ifdef HAVE_SNI
  373. NamedKey* namedKeys; /* mapping of names and keys */
  374. wolfSSL_Mutex namedKeysMutex; /* mutex for namedKey list */
  375. #endif
  376. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  377. byte useKeyLogFile; /* True if session secrets are coming from a
  378. keylog file */
  379. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  380. struct SnifferServer* next; /* for list */
  381. } SnifferServer;
  382. /* Session Flags */
  383. typedef struct Flags {
  384. byte side; /* which end is current packet headed */
  385. byte serverCipherOn; /* indicates whether cipher is active */
  386. byte clientCipherOn; /* indicates whether cipher is active */
  387. byte resuming; /* did this session come from resumption */
  388. byte cached; /* have we cached this session yet */
  389. byte clientHello; /* processed client hello yet, for SSLv2 */
  390. byte finCount; /* get both FINs before removing */
  391. byte fatalError; /* fatal error state */
  392. byte cliAckFault; /* client acked unseen data from server */
  393. byte srvAckFault; /* server acked unseen data from client */
  394. byte cliSkipPartial; /* client skips partial data to catch up */
  395. byte srvSkipPartial; /* server skips partial data to catch up */
  396. #ifdef HAVE_EXTENDED_MASTER
  397. byte expectEms; /* expect extended master secret */
  398. #endif
  399. byte gotFinished; /* processed finished */
  400. byte secRenegEn; /* secure renegotiation enabled */
  401. #ifdef WOLFSSL_ASYNC_CRYPT
  402. byte wasPolled;
  403. #endif
  404. } Flags;
  405. /* Out of Order FIN capture */
  406. typedef struct FinCapture {
  407. word32 cliFinSeq; /* client relative sequence FIN 0 is no */
  408. word32 srvFinSeq; /* server relative sequence FIN, 0 is no */
  409. byte cliCounted; /* did we count yet, detects duplicates */
  410. byte srvCounted; /* did we count yet, detects duplicates */
  411. } FinCapture;
  412. typedef struct HsHashes {
  413. #ifndef NO_OLD_TLS
  414. #ifndef NO_SHA
  415. wc_Sha hashSha;
  416. #endif
  417. #ifndef NO_MD5
  418. wc_Md5 hashMd5;
  419. #endif
  420. #endif /* !NO_OLD_TLS */
  421. #ifndef NO_SHA256
  422. wc_Sha256 hashSha256;
  423. #endif
  424. #ifdef WOLFSSL_SHA384
  425. wc_Sha384 hashSha384;
  426. #endif
  427. } HsHashes;
  428. typedef struct KeyShareInfo {
  429. word16 named_group;
  430. int key_len;
  431. const byte* key;
  432. /* additional info */
  433. int dh_key_bits;
  434. int curve_id;
  435. } KeyShareInfo;
  436. /* maximum previous acks to capture */
  437. #ifndef WC_SNIFFER_HS_ACK_HIST_MAX
  438. #define WC_SNIFFER_HS_ACK_HIST_MAX 10
  439. #endif
  440. /* Sniffer Session holds info for each client/server SSL/TLS session */
  441. typedef struct SnifferSession {
  442. SnifferServer* context; /* server context */
  443. WOLFSSL* sslServer; /* SSL server side decode */
  444. WOLFSSL* sslClient; /* SSL client side decode */
  445. IpAddrInfo server; /* server address in network byte order */
  446. IpAddrInfo client; /* client address in network byte order */
  447. word16 srvPort; /* server port */
  448. word16 cliPort; /* client port */
  449. word32 cliSeqStart; /* client start sequence */
  450. word32 srvSeqStart; /* server start sequence */
  451. word32 cliExpected; /* client expected sequence (relative) */
  452. word32 srvExpected; /* server expected sequence (relative) */
  453. word32 cliAcks[WC_SNIFFER_HS_ACK_HIST_MAX]; /* history of acks during handshake */
  454. word32 srvAcks[WC_SNIFFER_HS_ACK_HIST_MAX]; /* history of acks during handshake */
  455. FinCapture finCapture; /* retain out of order FIN s */
  456. Flags flags; /* session flags */
  457. time_t lastUsed; /* last used ticks */
  458. word32 keySz; /* size of the private key */
  459. PacketBuffer* cliReassemblyList; /* client out of order packets */
  460. PacketBuffer* srvReassemblyList; /* server out of order packets */
  461. word32 cliReassemblyMemory; /* client packet memory used */
  462. word32 srvReassemblyMemory; /* server packet memory used */
  463. struct SnifferSession* next; /* for hash table list */
  464. byte* ticketID; /* mac ID of session ticket */
  465. #ifdef HAVE_MAX_FRAGMENT
  466. byte* tlsFragBuf;
  467. word32 tlsFragOffset;
  468. word32 tlsFragSize;
  469. #endif
  470. #ifdef HAVE_SNI
  471. const char* sni; /* server name indication */
  472. #endif
  473. #ifdef HAVE_EXTENDED_MASTER
  474. HsHashes* hash;
  475. #endif
  476. #ifdef WOLFSSL_TLS13
  477. byte* cliKeyShare;
  478. word32 cliKeyShareSz;
  479. KeyShareInfo srvKs;
  480. KeyShareInfo cliKs;
  481. #endif
  482. #ifdef WOLFSSL_ASYNC_CRYPT
  483. void* userCtx;
  484. word32 pendSeq; /* when WC_PENDING_E is returned capture sequence */
  485. #endif
  486. int error; /* store the last set error number */
  487. byte verboseErr; /* Last set error is helpful and should
  488. * not be overwritten by FATAL_ERROR_STATE */
  489. } SnifferSession;
  490. /* Sniffer Server List and mutex */
  491. static THREAD_LS_T WOLFSSL_GLOBAL SnifferServer* ServerList = NULL;
  492. #ifndef HAVE_C___ATOMIC
  493. static WOLFSSL_GLOBAL wolfSSL_Mutex ServerListMutex;
  494. #endif
  495. /* Session Hash Table, mutex, and count */
  496. static THREAD_LS_T WOLFSSL_GLOBAL SnifferSession* SessionTable[HASH_SIZE];
  497. #ifndef HAVE_C___ATOMIC
  498. static WOLFSSL_GLOBAL wolfSSL_Mutex SessionMutex;
  499. #endif
  500. static THREAD_LS_T WOLFSSL_GLOBAL int SessionCount = 0;
  501. static WOLFSSL_GLOBAL int RecoveryEnabled = 0; /* global switch */
  502. static WOLFSSL_GLOBAL int MaxRecoveryMemory = -1;
  503. /* per session max recovery memory */
  504. #ifndef WOLFSSL_SNIFFER_NO_RECOVERY
  505. /* Recovery of missed data switches and stats */
  506. static WOLFSSL_GLOBAL wolfSSL_Mutex RecoveryMutex; /* for stats */
  507. /* # of sessions with missed data */
  508. static WOLFSSL_GLOBAL word32 MissedDataSessions = 0;
  509. #endif
  510. /* Connection Info Callback */
  511. static WOLFSSL_GLOBAL SSLConnCb ConnectionCb;
  512. static WOLFSSL_GLOBAL void* ConnectionCbCtx = NULL;
  513. #ifdef WOLFSSL_SNIFFER_STATS
  514. /* Sessions Statistics */
  515. static WOLFSSL_GLOBAL SSLStats SnifferStats;
  516. static WOLFSSL_GLOBAL wolfSSL_Mutex StatsMutex;
  517. #endif
  518. #ifdef WOLFSSL_SNIFFER_KEY_CALLBACK
  519. static WOLFSSL_GLOBAL SSLKeyCb KeyCb;
  520. static WOLFSSL_GLOBAL void* KeyCbCtx = NULL;
  521. #endif
  522. #ifdef WOLFSSL_SNIFFER_WATCH
  523. /* Watch Key Callback */
  524. static WOLFSSL_GLOBAL SSLWatchCb WatchCb;
  525. static WOLFSSL_GLOBAL void* WatchCbCtx = NULL;
  526. #endif
  527. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  528. /* Store Data Callback */
  529. static WOLFSSL_GLOBAL SSLStoreDataCb StoreDataCb;
  530. #endif
  531. #ifndef WOLFSSL_SNIFFER_NO_RECOVERY
  532. static void UpdateMissedDataSessions(void)
  533. {
  534. wc_LockMutex(&RecoveryMutex);
  535. MissedDataSessions += 1;
  536. wc_UnLockMutex(&RecoveryMutex);
  537. }
  538. #endif
  539. #ifdef WOLFSSL_SNIFFER_STATS
  540. #ifdef HAVE_C___ATOMIC
  541. #define LOCK_STAT() WC_DO_NOTHING
  542. #define UNLOCK_STAT() WC_DO_NOTHING
  543. #define NOLOCK_ADD_TO_STAT(x,y) ({ TraceStat(#x, y); \
  544. __atomic_fetch_add(&x, y, __ATOMIC_RELAXED); })
  545. #else
  546. #define LOCK_STAT() wc_LockMutex(&StatsMutex)
  547. #define UNLOCK_STAT() wc_UnLockMutex(&StatsMutex)
  548. #define NOLOCK_ADD_TO_STAT(x,y) ({ TraceStat(#x, y); x += y; })
  549. #endif
  550. #define NOLOCK_INC_STAT(x) NOLOCK_ADD_TO_STAT(x,1)
  551. #define ADD_TO_STAT(x,y) do { LOCK_STAT(); \
  552. NOLOCK_ADD_TO_STAT(x,y); UNLOCK_STAT(); } while (0)
  553. #define INC_STAT(x) do { LOCK_STAT(); \
  554. NOLOCK_INC_STAT(x); UNLOCK_STAT(); } while (0)
  555. #endif /* WOLFSSL_SNIFFER_STATS */
  556. #ifdef HAVE_C___ATOMIC
  557. #define LOCK_SESSION() WC_DO_NOTHING
  558. #define UNLOCK_SESSION() WC_DO_NOTHING
  559. #define LOCK_SERVER_LIST() WC_DO_NOTHING
  560. #define UNLOCK_SERVER_LIST() WC_DO_NOTHING
  561. #else
  562. #define LOCK_SESSION() wc_LockMutex(&SessionMutex)
  563. #define UNLOCK_SESSION() wc_UnLockMutex(&SessionMutex)
  564. #define LOCK_SERVER_LIST() wc_LockMutex(&ServerListMutex)
  565. #define UNLOCK_SERVER_LIST() wc_UnLockMutex(&ServerListMutex)
  566. #endif
  567. #if defined(WOLF_CRYPTO_CB) || defined(WOLFSSL_ASYNC_CRYPT)
  568. static WOLFSSL_GLOBAL int CryptoDeviceId = INVALID_DEVID;
  569. #endif
  570. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  571. static int addSecretNode(unsigned char* clientRandom,
  572. unsigned char* masterSecret,
  573. char* error);
  574. static void hexToBin(const char* hex, unsigned char* bin, int binLength);
  575. static int parseKeyLogFile(const char* fileName, char* error);
  576. static unsigned char* findMasterSecret(unsigned char* clientRandom);
  577. static void freeSecretList(void);
  578. static int snifferSecretCb(unsigned char* client_random,
  579. unsigned char* output_secret);
  580. static void setSnifferSecretCb(SnifferSession* session);
  581. static int addKeyLogSnifferServerHelper(const char* address,
  582. int port,
  583. char* error);
  584. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  585. /* Initialize overall Sniffer */
  586. void ssl_InitSniffer_ex(int devId)
  587. {
  588. wolfSSL_Init();
  589. #ifndef HAVE_C___ATOMIC
  590. wc_InitMutex(&ServerListMutex);
  591. wc_InitMutex(&SessionMutex);
  592. #endif
  593. #ifndef WOLFSSL_SNIFFER_NO_RECOVERY
  594. wc_InitMutex(&RecoveryMutex);
  595. #endif
  596. #ifdef WOLFSSL_SNIFFER_STATS
  597. XMEMSET(&SnifferStats, 0, sizeof(SSLStats));
  598. wc_InitMutex(&StatsMutex);
  599. #endif
  600. #if defined(WOLF_CRYPTO_CB) || defined(WOLFSSL_ASYNC_CRYPT)
  601. CryptoDeviceId = devId;
  602. #endif
  603. (void)devId;
  604. }
  605. static int GetDevId(void)
  606. {
  607. int devId = INVALID_DEVID;
  608. #ifdef WOLF_CRYPTO_CB
  609. #ifdef HAVE_INTEL_QA_SYNC
  610. devId = wc_CryptoCb_InitIntelQa();
  611. if (devId == INVALID_DEVID) {
  612. fprintf(stderr, "Couldn't init the Intel QA\n");
  613. }
  614. #endif
  615. #ifdef HAVE_CAVIUM_OCTEON_SYNC
  616. devId = wc_CryptoCb_InitOcteon();
  617. if (devId == INVALID_DEVID) {
  618. fprintf(stderr, "Couldn't init the Octeon\n");
  619. }
  620. #endif
  621. #endif
  622. return devId;
  623. }
  624. void ssl_InitSniffer(void)
  625. {
  626. int devId = GetDevId();
  627. #ifdef WOLFSSL_ASYNC_CRYPT
  628. if (wolfAsync_DevOpen(&devId) < 0) {
  629. fprintf(stderr, "Async device open failed\nRunning without async\n");
  630. devId = INVALID_DEVID;
  631. }
  632. #endif /* WOLFSSL_ASYNC_CRYPT */
  633. (void)devId;
  634. ssl_InitSniffer_ex(devId);
  635. }
  636. void ssl_InitSniffer_ex2(int threadNum)
  637. {
  638. int devId = GetDevId();
  639. #ifdef WOLFSSL_ASYNC_CRYPT
  640. #ifndef WC_NO_ASYNC_THREADING
  641. if (wolfAsync_DevOpenThread(&devId, &threadNum) < 0)
  642. #else
  643. if (wolfAsync_DevOpen(&devId) < 0)
  644. #endif
  645. {
  646. fprintf(stderr, "Async device open failed\nRunning without async\n");
  647. devId = INVALID_DEVID;
  648. }
  649. #endif /* WOLFSSL_ASYNC_CRYPT */
  650. (void)devId;
  651. (void)threadNum;
  652. ssl_InitSniffer_ex(devId);
  653. }
  654. #ifdef HAVE_SNI
  655. /* Free Named Key and the zero out the private key it holds */
  656. static void FreeNamedKey(NamedKey* in)
  657. {
  658. if (in) {
  659. if (in->key) {
  660. ForceZero(in->key, in->keySz);
  661. XFREE(in->key, NULL, DYNAMIC_TYPE_X509);
  662. }
  663. XFREE(in, NULL, DYNAMIC_TYPE_SNIFFER_NAMED_KEY);
  664. }
  665. }
  666. static void FreeNamedKeyList(NamedKey* in)
  667. {
  668. NamedKey* next;
  669. while (in) {
  670. next = in->next;
  671. FreeNamedKey(in);
  672. in = next;
  673. }
  674. }
  675. #endif
  676. /* Free Sniffer Server's resources/self */
  677. static void FreeSnifferServer(SnifferServer* srv)
  678. {
  679. if (srv) {
  680. #ifdef HAVE_SNI
  681. wc_LockMutex(&srv->namedKeysMutex);
  682. FreeNamedKeyList(srv->namedKeys);
  683. wc_UnLockMutex(&srv->namedKeysMutex);
  684. wc_FreeMutex(&srv->namedKeysMutex);
  685. #endif
  686. wolfSSL_CTX_free(srv->ctx);
  687. }
  688. XFREE(srv, NULL, DYNAMIC_TYPE_SNIFFER_SERVER);
  689. }
  690. /* free PacketBuffer's resources/self */
  691. static void FreePacketBuffer(PacketBuffer* del)
  692. {
  693. if (del) {
  694. XFREE(del->data, NULL, DYNAMIC_TYPE_SNIFFER_PB_BUFFER);
  695. XFREE(del, NULL, DYNAMIC_TYPE_SNIFFER_PB);
  696. }
  697. }
  698. /* remove PacketBuffer List */
  699. static void FreePacketList(PacketBuffer* in)
  700. {
  701. if (in) {
  702. PacketBuffer* del;
  703. PacketBuffer* packet = in;
  704. while (packet) {
  705. del = packet;
  706. packet = packet->next;
  707. FreePacketBuffer(del);
  708. }
  709. }
  710. }
  711. /* Free Sniffer Session's resources/self */
  712. static void FreeSnifferSession(SnifferSession* session)
  713. {
  714. if (session) {
  715. wolfSSL_free(session->sslClient);
  716. wolfSSL_free(session->sslServer);
  717. FreePacketList(session->cliReassemblyList);
  718. FreePacketList(session->srvReassemblyList);
  719. XFREE(session->ticketID, NULL, DYNAMIC_TYPE_SNIFFER_TICKET_ID);
  720. #ifdef HAVE_EXTENDED_MASTER
  721. XFREE(session->hash, NULL, DYNAMIC_TYPE_HASHES);
  722. #endif
  723. #ifdef WOLFSSL_TLS13
  724. if (session->cliKeyShare)
  725. XFREE(session->cliKeyShare, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  726. #endif
  727. #ifdef HAVE_MAX_FRAGMENT
  728. if (session->tlsFragBuf) {
  729. XFREE(session->tlsFragBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  730. session->tlsFragBuf = NULL;
  731. }
  732. #endif
  733. }
  734. XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  735. }
  736. /* Free overall Sniffer */
  737. void ssl_FreeSniffer(void)
  738. {
  739. SnifferServer* srv;
  740. SnifferServer* removeServer;
  741. SnifferSession* session;
  742. SnifferSession* removeSession;
  743. int i;
  744. LOCK_SERVER_LIST();
  745. LOCK_SESSION();
  746. /* Free sessions (wolfSSL objects) first */
  747. for (i = 0; i < HASH_SIZE; i++) {
  748. session = SessionTable[i];
  749. while (session) {
  750. removeSession = session;
  751. session = session->next;
  752. FreeSnifferSession(removeSession);
  753. }
  754. }
  755. XMEMSET(SessionTable, 0, sizeof(SessionTable));
  756. SessionCount = 0;
  757. /* Then server (wolfSSL_CTX) */
  758. srv = ServerList;
  759. while (srv) {
  760. removeServer = srv;
  761. srv = srv->next;
  762. FreeSnifferServer(removeServer);
  763. }
  764. ServerList = NULL;
  765. UNLOCK_SESSION();
  766. UNLOCK_SERVER_LIST();
  767. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  768. freeSecretList();
  769. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  770. #ifndef WOLFSSL_SNIFFER_NO_RECOVERY
  771. wc_FreeMutex(&RecoveryMutex);
  772. #endif
  773. #ifndef HAVE_C___ATOMIC
  774. wc_FreeMutex(&SessionMutex);
  775. wc_FreeMutex(&ServerListMutex);
  776. #endif
  777. #ifdef WOLF_CRYPTO_CB
  778. #ifdef HAVE_INTEL_QA_SYNC
  779. wc_CryptoCb_CleanupIntelQa(&CryptoDeviceId);
  780. #endif
  781. #ifdef HAVE_CAVIUM_OCTEON_SYNC
  782. wc_CryptoCb_CleanupOcteon(&CryptoDeviceId);
  783. #endif
  784. #endif
  785. #ifdef WOLFSSL_ASYNC_CRYPT
  786. wolfAsync_DevClose(&CryptoDeviceId);
  787. #endif
  788. if (TraceFile) {
  789. TraceOn = 0;
  790. XFCLOSE(TraceFile);
  791. TraceFile = NULL;
  792. }
  793. wolfSSL_Cleanup();
  794. }
  795. #ifdef HAVE_EXTENDED_MASTER
  796. static int HashInit(HsHashes* hash)
  797. {
  798. int ret = 0;
  799. XMEMSET(hash, 0, sizeof(HsHashes));
  800. #ifndef NO_OLD_TLS
  801. #ifndef NO_SHA
  802. if (ret == 0)
  803. ret = wc_InitSha(&hash->hashSha);
  804. #endif
  805. #ifndef NO_MD5
  806. if (ret == 0)
  807. ret = wc_InitMd5(&hash->hashMd5);
  808. #endif
  809. #endif /* !NO_OLD_TLS */
  810. #ifndef NO_SHA256
  811. if (ret == 0)
  812. ret = wc_InitSha256(&hash->hashSha256);
  813. #endif
  814. #ifdef WOLFSSL_SHA384
  815. if (ret == 0)
  816. ret = wc_InitSha384(&hash->hashSha384);
  817. #endif
  818. return ret;
  819. }
  820. static int HashUpdate(HsHashes* hash, const byte* input, int sz)
  821. {
  822. int ret = 0;
  823. input -= HANDSHAKE_HEADER_SZ;
  824. sz += HANDSHAKE_HEADER_SZ;
  825. #ifndef NO_OLD_TLS
  826. #ifndef NO_SHA
  827. if (ret == 0)
  828. ret = wc_ShaUpdate(&hash->hashSha, input, sz);
  829. #endif
  830. #ifndef NO_MD5
  831. if (ret == 0)
  832. ret = wc_Md5Update(&hash->hashMd5, input, sz);
  833. #endif
  834. #endif /* !NO_OLD_TLS */
  835. #ifndef NO_SHA256
  836. if (ret == 0)
  837. ret = wc_Sha256Update(&hash->hashSha256, input, sz);
  838. #endif
  839. #ifdef WOLFSSL_SHA384
  840. if (ret == 0)
  841. ret = wc_Sha384Update(&hash->hashSha384, input, sz);
  842. #endif
  843. return ret;
  844. }
  845. static int HashCopy(HS_Hashes* d, HsHashes* s)
  846. {
  847. #ifndef NO_OLD_TLS
  848. #ifndef NO_SHA
  849. XMEMCPY(&d->hashSha, &s->hashSha, sizeof(wc_Sha));
  850. #endif
  851. #ifndef NO_MD5
  852. XMEMCPY(&d->hashMd5, &s->hashMd5, sizeof(wc_Md5));
  853. #endif
  854. #endif /* !NO_OLD_TLS */
  855. #ifndef NO_SHA256
  856. XMEMCPY(&d->hashSha256, &s->hashSha256, sizeof(wc_Sha256));
  857. #endif
  858. #ifdef WOLFSSL_SHA384
  859. XMEMCPY(&d->hashSha384, &s->hashSha384, sizeof(wc_Sha384));
  860. #endif
  861. return 0;
  862. }
  863. #endif
  864. /* Initialize a SnifferServer */
  865. static void InitSnifferServer(SnifferServer* sniffer)
  866. {
  867. XMEMSET(sniffer, 0, sizeof(SnifferServer));
  868. }
  869. /* Initialize session flags */
  870. static void InitFlags(Flags* flags)
  871. {
  872. XMEMSET(flags, 0, sizeof(Flags));
  873. }
  874. /* Initialize FIN Capture */
  875. static void InitFinCapture(FinCapture* cap)
  876. {
  877. XMEMSET(cap, 0, sizeof(FinCapture));
  878. }
  879. /* Initialize a Sniffer Session */
  880. static void InitSession(SnifferSession* session)
  881. {
  882. XMEMSET(session, 0, sizeof(SnifferSession));
  883. InitFlags(&session->flags);
  884. InitFinCapture(&session->finCapture);
  885. }
  886. /* IP Info from IP Header */
  887. typedef struct IpInfo {
  888. int length; /* length of this header */
  889. int total; /* total length of fragment */
  890. IpAddrInfo src; /* network order source address */
  891. IpAddrInfo dst; /* network order destination address */
  892. } IpInfo;
  893. /* TCP Info from TCP Header */
  894. typedef struct TcpInfo {
  895. int srcPort; /* source port */
  896. int dstPort; /* destination port */
  897. int length; /* length of this header */
  898. word32 sequence; /* sequence number */
  899. word32 ackNumber; /* ack number */
  900. byte fin; /* FIN set */
  901. byte rst; /* RST set */
  902. byte syn; /* SYN set */
  903. byte ack; /* ACK set */
  904. } TcpInfo;
  905. /* Tcp Pseudo Header for Checksum calculation */
  906. typedef struct TcpPseudoHdr {
  907. word32 src; /* source address */
  908. word32 dst; /* destination address */
  909. byte rsv; /* reserved, always 0 */
  910. byte protocol; /* IP protocol */
  911. word16 length; /* tcp header length + data length (doesn't include */
  912. /* pseudo header length) network order */
  913. } TcpPseudoHdr;
  914. #ifdef WOLFSSL_ENCRYPTED_KEYS
  915. /* Password Setting Callback */
  916. static int SetPassword(char* passwd, int sz, int rw, void* userdata)
  917. {
  918. (void)rw;
  919. XSTRNCPY(passwd, (const char*)userdata, sz);
  920. return (int)XSTRLEN((const char*)userdata);
  921. }
  922. #endif
  923. /* Ethernet Header */
  924. typedef struct EthernetHdr {
  925. byte dst[ETHER_IF_ADDR_LEN]; /* destination host address */
  926. byte src[ETHER_IF_ADDR_LEN]; /* source host address */
  927. word16 type; /* IP, ARP, etc */
  928. } EthernetHdr;
  929. /* IPv4 Header */
  930. typedef struct IpHdr {
  931. byte ver_hl; /* version/header length */
  932. byte tos; /* type of service */
  933. word16 length; /* total length */
  934. word16 id; /* identification */
  935. word16 offset; /* fragment offset field */
  936. byte ttl; /* time to live */
  937. byte protocol; /* protocol */
  938. word16 sum; /* checksum */
  939. word32 src; /* source address */
  940. word32 dst; /* destination address */
  941. } IpHdr;
  942. /* IPv6 Header */
  943. typedef struct Ip6Hdr {
  944. byte ver_hl; /* version/traffic class high */
  945. byte tc_fl; /* traffic class low/flow label high */
  946. word16 fl; /* flow label low */
  947. word16 length; /* payload length */
  948. byte next_header; /* next header (6 for TCP, any other skip) */
  949. byte hl; /* hop limit */
  950. byte src[16]; /* source address */
  951. byte dst[16]; /* destination address */
  952. } Ip6Hdr;
  953. /* IPv6 extension header */
  954. typedef struct Ip6ExtHdr {
  955. byte next_header; /* next header (6 for TCP, any other skip) */
  956. byte length; /* length in 8-octet units - 1 */
  957. byte reserved[6];
  958. } Ip6ExtHdr;
  959. #define IP_HL(ip) ( (((ip)->ver_hl) & 0x0f) * 4)
  960. #define IP_V(ip) ( ((ip)->ver_hl) >> 4)
  961. /* TCP Header */
  962. typedef struct TcpHdr {
  963. word16 srcPort; /* source port */
  964. word16 dstPort; /* destination port */
  965. word32 sequence; /* sequence number */
  966. word32 ack; /* acknowledgment number */
  967. byte offset; /* data offset, reserved */
  968. byte flags; /* option flags */
  969. word16 window; /* window */
  970. word16 sum; /* checksum */
  971. word16 urgent; /* urgent pointer */
  972. } TcpHdr;
  973. #define TCP_LEN(tcp) ( (((tcp)->offset & 0xf0) >> 4) * 4)
  974. #define TCP_FIN 0x01
  975. #define TCP_SYN 0x02
  976. #define TCP_RST 0x04
  977. #define TCP_ACK 0x10
  978. /* Use platform specific GetError to write to trace file if tracing */
  979. static void TraceError(int idx, char* error)
  980. {
  981. if (TraceOn) {
  982. char myBuffer[MAX_ERROR_LEN];
  983. if (error == NULL) {
  984. error = myBuffer;
  985. GetError(idx, myBuffer);
  986. }
  987. XFPRINTF(TraceFile, "\t%s\n", error);
  988. #ifdef DEBUG_SNIFFER
  989. XFPRINTF(stderr, "\t%s\n", error);
  990. #endif
  991. }
  992. }
  993. static void Trace(int idx)
  994. {
  995. TraceError(idx, NULL);
  996. }
  997. /* Show TimeStamp for beginning of packet Trace */
  998. static void TraceHeader(void)
  999. {
  1000. if (TraceOn) {
  1001. time_t ticks = wc_Time(NULL);
  1002. XFPRINTF(TraceFile, "\n%s", XCTIME(&ticks));
  1003. }
  1004. }
  1005. /* Show Set Server info for Trace */
  1006. static void TraceSetServer(const char* srv, int port, const char* keyFile)
  1007. {
  1008. if (TraceOn) {
  1009. XFPRINTF(TraceFile, "\tTrying to install a new Sniffer Server with\n");
  1010. if (keyFile != NULL) {
  1011. XFPRINTF(TraceFile, "\tserver: %s, port: %d, keyFile: %s\n",
  1012. srv, port, keyFile);
  1013. }
  1014. else {
  1015. XFPRINTF(TraceFile, "\tserver: %s, port: %d\n",
  1016. srv, port);
  1017. }
  1018. }
  1019. }
  1020. #ifdef HAVE_SNI
  1021. /* Show Set Named Server info for Trace */
  1022. static void TraceSetNamedServer(const char* name,
  1023. const char* srv, int port, const char* keyFile)
  1024. {
  1025. if (TraceOn) {
  1026. XFPRINTF(TraceFile, "\tTrying to install a new Sniffer Server with\n");
  1027. XFPRINTF(TraceFile, "\tname: %s, server: %s, port: %d, keyFile: %s\n",
  1028. name ? name : "",
  1029. srv ? srv : "",
  1030. port,
  1031. keyFile ? keyFile : "");
  1032. }
  1033. }
  1034. #endif
  1035. /* Trace got packet number */
  1036. static void TracePacket(void)
  1037. {
  1038. if (TraceOn) {
  1039. static word32 packetNumber = 0;
  1040. XFPRINTF(TraceFile, "\tGot a Packet to decode, packet %u\n",
  1041. ++packetNumber);
  1042. }
  1043. }
  1044. /* Convert network byte order address into human readable */
  1045. static const char* IpToS(int version, void* src, char* dst)
  1046. {
  1047. return XINET_NTOP(version, src, dst, TRACE_MSG_SZ);
  1048. }
  1049. /* Show destination and source address from Ip Hdr for packet Trace */
  1050. static void TraceIP(IpHdr* iphdr)
  1051. {
  1052. if (TraceOn) {
  1053. char src[TRACE_MSG_SZ];
  1054. char dst[TRACE_MSG_SZ];
  1055. XFPRINTF(TraceFile, "\tdst:%s src:%s\n",
  1056. IpToS(AF_INET, &iphdr->dst, dst),
  1057. IpToS(AF_INET, &iphdr->src, src));
  1058. }
  1059. }
  1060. /* Show destination and source address from Ip6Hdr for packet Trace */
  1061. static void TraceIP6(Ip6Hdr* iphdr)
  1062. {
  1063. if (TraceOn) {
  1064. char src[TRACE_MSG_SZ];
  1065. char dst[TRACE_MSG_SZ];
  1066. XFPRINTF(TraceFile, "\tdst: %s src: %s\n",
  1067. IpToS(AF_INET6, iphdr->dst, dst),
  1068. IpToS(AF_INET6, iphdr->src, src));
  1069. }
  1070. }
  1071. /* Show destination and source port from Tcp Hdr for packet Trace */
  1072. static void TraceTcp(TcpHdr* tcphdr)
  1073. {
  1074. if (TraceOn) {
  1075. XFPRINTF(TraceFile, "\tdstPort:%u srcPort:%u\n", XNTOHS(tcphdr->dstPort),
  1076. XNTOHS(tcphdr->srcPort));
  1077. }
  1078. }
  1079. /* Show sequence and payload length for Trace */
  1080. static void TraceSequence(word32 seq, int len)
  1081. {
  1082. if (TraceOn) {
  1083. XFPRINTF(TraceFile, "\tSequence:%u, payload length:%d\n", seq, len);
  1084. }
  1085. }
  1086. /* Show sequence and payload length for Trace */
  1087. static void TraceAck(word32 acknowledgement, word32 expected)
  1088. {
  1089. if (TraceOn) {
  1090. XFPRINTF(TraceFile, "\tAck:%u Expected:%u\n", acknowledgement,
  1091. expected);
  1092. }
  1093. }
  1094. /* Show relative expected and relative received sequences */
  1095. static void TraceRelativeSequence(word32 expected, word32 got)
  1096. {
  1097. if (TraceOn) {
  1098. XFPRINTF(TraceFile, "\tExpected sequence:%u, received sequence:%u\n",
  1099. expected, got);
  1100. }
  1101. }
  1102. /* Show server sequence startup from SYN */
  1103. static void TraceServerSyn(word32 seq)
  1104. {
  1105. if (TraceOn) {
  1106. XFPRINTF(TraceFile, "\tServer SYN, Sequence Start:%u\n", seq);
  1107. }
  1108. }
  1109. /* Show client sequence startup from SYN */
  1110. static void TraceClientSyn(word32 seq)
  1111. {
  1112. if (TraceOn) {
  1113. XFPRINTF(TraceFile, "\tClient SYN, Sequence Start:%u\n", seq);
  1114. }
  1115. }
  1116. /* Show client FIN capture */
  1117. static void TraceClientFin(word32 finSeq, word32 relSeq)
  1118. {
  1119. if (TraceOn) {
  1120. XFPRINTF(TraceFile, "\tClient FIN capture:%u, current SEQ:%u\n",
  1121. finSeq, relSeq);
  1122. }
  1123. }
  1124. /* Show server FIN capture */
  1125. static void TraceServerFin(word32 finSeq, word32 relSeq)
  1126. {
  1127. if (TraceOn) {
  1128. XFPRINTF(TraceFile, "\tServer FIN capture:%u, current SEQ:%u\n",
  1129. finSeq, relSeq);
  1130. }
  1131. }
  1132. /* Show number of SSL data bytes decoded, could be 0 (ok) */
  1133. static void TraceGotData(int bytes)
  1134. {
  1135. if (TraceOn) {
  1136. XFPRINTF(TraceFile, "\t%d bytes of SSL App data processed\n", bytes);
  1137. }
  1138. }
  1139. /* Show bytes added to old SSL App data */
  1140. static void TraceAddedData(int newBytes, int existingBytes)
  1141. {
  1142. if (TraceOn) {
  1143. XFPRINTF(TraceFile,
  1144. "\t%d bytes added to %d existing bytes in User Buffer\n",
  1145. newBytes, existingBytes);
  1146. }
  1147. }
  1148. /* Show Stale Session */
  1149. static void TraceStaleSession(void)
  1150. {
  1151. if (TraceOn) {
  1152. XFPRINTF(TraceFile, "\tFound a stale session\n");
  1153. }
  1154. }
  1155. /* Show Finding Stale Sessions */
  1156. static void TraceFindingStale(void)
  1157. {
  1158. if (TraceOn) {
  1159. XFPRINTF(TraceFile, "\tTrying to find Stale Sessions\n");
  1160. }
  1161. }
  1162. /* Show Removed Session */
  1163. static void TraceRemovedSession(void)
  1164. {
  1165. if (TraceOn) {
  1166. XFPRINTF(TraceFile, "\tRemoved it\n");
  1167. }
  1168. }
  1169. /* Show SSLInfo if provided and is valid. */
  1170. static void TraceSessionInfo(SSLInfo* sslInfo)
  1171. {
  1172. if (TraceOn) {
  1173. if (sslInfo != NULL && sslInfo->isValid) {
  1174. XFPRINTF(TraceFile,
  1175. "\tver:(%u %u) suiteId:(%02x %02x) suiteName:(%s) "
  1176. #ifdef HAVE_SNI
  1177. "sni:(%s) "
  1178. #endif
  1179. "keySize:(%u)\n",
  1180. sslInfo->protocolVersionMajor,
  1181. sslInfo->protocolVersionMinor,
  1182. sslInfo->serverCipherSuite0,
  1183. sslInfo->serverCipherSuite,
  1184. sslInfo->serverCipherSuiteName,
  1185. #ifdef HAVE_SNI
  1186. sslInfo->serverNameIndication,
  1187. #endif
  1188. sslInfo->keySize);
  1189. }
  1190. }
  1191. }
  1192. #ifdef WOLFSSL_SNIFFER_STATS
  1193. /* Show value added to a named statistic. */
  1194. static void TraceStat(const char* name, int add)
  1195. {
  1196. if (TraceOn) {
  1197. XFPRINTF(TraceFile, "\tAdding %d to %s\n", add, name);
  1198. }
  1199. }
  1200. #endif
  1201. /* Set user error string */
  1202. static void SetError(int idx, char* error, SnifferSession* session, int fatal)
  1203. {
  1204. GetError(idx, error);
  1205. TraceError(idx, error);
  1206. if (session)
  1207. session->error = idx;
  1208. if (session && fatal == FATAL_ERROR_STATE)
  1209. session->flags.fatalError = 1;
  1210. }
  1211. /* Compare IpAddrInfo structs */
  1212. static WC_INLINE int MatchAddr(IpAddrInfo l, IpAddrInfo r)
  1213. {
  1214. if (l.version == r.version) {
  1215. if (l.version == IPV4)
  1216. return (l.ip4 == r.ip4);
  1217. else if (l.version == IPV6)
  1218. return (0 == XMEMCMP(l.ip6, r.ip6, sizeof(l.ip6)));
  1219. }
  1220. return 0;
  1221. }
  1222. #ifndef WOLFSSL_SNIFFER_WATCH
  1223. /* See if this IPV4 network order address has been registered */
  1224. /* return 1 is true, 0 is false */
  1225. static int IsServerRegistered(word32 addr)
  1226. {
  1227. int ret = 0; /* false */
  1228. SnifferServer* sniffer;
  1229. LOCK_SERVER_LIST();
  1230. sniffer = ServerList;
  1231. while (sniffer) {
  1232. if (sniffer->server.ip4 == addr) {
  1233. ret = 1;
  1234. break;
  1235. }
  1236. sniffer = sniffer->next;
  1237. }
  1238. UNLOCK_SERVER_LIST();
  1239. return ret;
  1240. }
  1241. /* See if this port has been registered to watch */
  1242. /* See if this IPV4 network order address has been registered */
  1243. /* return 1 is true, 0 is false */
  1244. static int IsServerRegistered6(byte* addr)
  1245. {
  1246. int ret = 0; /* false */
  1247. SnifferServer* sniffer;
  1248. LOCK_SERVER_LIST();
  1249. sniffer = ServerList;
  1250. while (sniffer) {
  1251. if (sniffer->server.version == IPV6 &&
  1252. 0 == XMEMCMP(sniffer->server.ip6, addr, sizeof(sniffer->server.ip6))) {
  1253. ret = 1;
  1254. break;
  1255. }
  1256. sniffer = sniffer->next;
  1257. }
  1258. UNLOCK_SERVER_LIST();
  1259. return ret;
  1260. }
  1261. /* See if this port has been registered to watch */
  1262. /* return 1 is true, 0 is false */
  1263. static int IsPortRegistered(word32 port)
  1264. {
  1265. int ret = 0; /* false */
  1266. SnifferServer* sniffer;
  1267. LOCK_SERVER_LIST();
  1268. sniffer = ServerList;
  1269. while (sniffer) {
  1270. if (sniffer->port == (int)port) {
  1271. ret = 1;
  1272. break;
  1273. }
  1274. sniffer = sniffer->next;
  1275. }
  1276. UNLOCK_SERVER_LIST();
  1277. return ret;
  1278. }
  1279. #endif
  1280. /* Get SnifferServer from IP and Port */
  1281. static SnifferServer* GetSnifferServer(IpInfo* ipInfo, TcpInfo* tcpInfo)
  1282. {
  1283. SnifferServer* sniffer;
  1284. LOCK_SERVER_LIST();
  1285. sniffer = ServerList;
  1286. #ifndef WOLFSSL_SNIFFER_WATCH
  1287. while (sniffer) {
  1288. if (sniffer->port == tcpInfo->srcPort &&
  1289. MatchAddr(sniffer->server, ipInfo->src))
  1290. break;
  1291. if (sniffer->port == tcpInfo->dstPort &&
  1292. MatchAddr(sniffer->server, ipInfo->dst))
  1293. break;
  1294. if (sniffer->next)
  1295. sniffer = sniffer->next;
  1296. else
  1297. break;
  1298. }
  1299. #else
  1300. (void)ipInfo;
  1301. (void)tcpInfo;
  1302. #endif
  1303. UNLOCK_SERVER_LIST();
  1304. return sniffer;
  1305. }
  1306. /* Hash the Session Info, return hash row */
  1307. static word32 SessionHash(IpInfo* ipInfo, TcpInfo* tcpInfo)
  1308. {
  1309. word32 hash = 1;
  1310. if (ipInfo->src.version == IPV4) {
  1311. hash *= ipInfo->src.ip4 * ipInfo->dst.ip4;
  1312. }
  1313. else if (ipInfo->src.version == IPV6) {
  1314. word32* x;
  1315. word32 y;
  1316. x = (word32*)ipInfo->src.ip6;
  1317. y = x[0] ^ x[1] ^ x[2] ^ x[3];
  1318. hash *= y;
  1319. x = (word32*)ipInfo->dst.ip6;
  1320. y = x[0] ^ x[1] ^ x[2] ^ x[3];
  1321. hash *= y;
  1322. }
  1323. hash *= tcpInfo->srcPort * tcpInfo->dstPort;
  1324. return hash % HASH_SIZE;
  1325. }
  1326. /* Get Existing SnifferSession from IP and Port */
  1327. static SnifferSession* GetSnifferSession(IpInfo* ipInfo, TcpInfo* tcpInfo)
  1328. {
  1329. SnifferSession* session;
  1330. time_t currTime = wc_Time(NULL);
  1331. word32 row = SessionHash(ipInfo, tcpInfo);
  1332. LOCK_SESSION();
  1333. session = SessionTable[row];
  1334. while (session) {
  1335. if (MatchAddr(session->server, ipInfo->src) &&
  1336. MatchAddr(session->client, ipInfo->dst) &&
  1337. session->srvPort == tcpInfo->srcPort &&
  1338. session->cliPort == tcpInfo->dstPort)
  1339. break;
  1340. if (MatchAddr(session->client, ipInfo->src) &&
  1341. MatchAddr(session->server, ipInfo->dst) &&
  1342. session->cliPort == tcpInfo->srcPort &&
  1343. session->srvPort == tcpInfo->dstPort)
  1344. break;
  1345. session = session->next;
  1346. }
  1347. if (session)
  1348. session->lastUsed= currTime; /* keep session alive, remove stale will */
  1349. /* leave alone */
  1350. UNLOCK_SESSION();
  1351. /* determine side */
  1352. if (session) {
  1353. if (MatchAddr(ipInfo->dst, session->server) &&
  1354. tcpInfo->dstPort == session->srvPort) {
  1355. session->flags.side = WOLFSSL_SERVER_END;
  1356. }
  1357. else {
  1358. session->flags.side = WOLFSSL_CLIENT_END;
  1359. }
  1360. }
  1361. return session;
  1362. }
  1363. #if defined(HAVE_SNI) || defined(WOLFSSL_SNIFFER_WATCH)
  1364. static int LoadKeyFile(byte** keyBuf, word32* keyBufSz,
  1365. const char* keyFile, int keySz, int typeKey,
  1366. const char* password)
  1367. {
  1368. byte* loadBuf;
  1369. long fileSz = 0;
  1370. XFILE file;
  1371. int ret = -1;
  1372. if (keyBuf == NULL || keyBufSz == NULL || keyFile == NULL) {
  1373. return -1;
  1374. }
  1375. if (keySz == 0) {
  1376. /* load from file */
  1377. file = XFOPEN(keyFile, "rb");
  1378. if (file == XBADFILE) return -1;
  1379. if(XFSEEK(file, 0, XSEEK_END) != 0) {
  1380. XFCLOSE(file);
  1381. return -1;
  1382. }
  1383. fileSz = XFTELL(file);
  1384. if (fileSz > MAX_WOLFSSL_FILE_SIZE || fileSz < 0) {
  1385. XFCLOSE(file);
  1386. return -1;
  1387. }
  1388. if(XFSEEK(file, 0, XSEEK_SET) != 0) {
  1389. XFCLOSE(file);
  1390. return -1;
  1391. }
  1392. loadBuf = (byte*)XMALLOC(fileSz, NULL, DYNAMIC_TYPE_FILE);
  1393. if (loadBuf == NULL) {
  1394. XFCLOSE(file);
  1395. return -1;
  1396. }
  1397. ret = (int)XFREAD(loadBuf, 1, fileSz, file);
  1398. XFCLOSE(file);
  1399. if (ret != fileSz) {
  1400. XFREE(loadBuf, NULL, DYNAMIC_TYPE_FILE);
  1401. return -1;
  1402. }
  1403. }
  1404. else {
  1405. /* use buffer directly */
  1406. loadBuf = (byte*)XMALLOC(keySz, NULL, DYNAMIC_TYPE_FILE);
  1407. if (loadBuf == NULL) {
  1408. return -1;
  1409. }
  1410. fileSz = keySz;
  1411. XMEMCPY(loadBuf, keyFile, fileSz);
  1412. }
  1413. if (typeKey == WOLFSSL_FILETYPE_PEM) {
  1414. byte* saveBuf = (byte*)XMALLOC(fileSz, NULL, DYNAMIC_TYPE_X509);
  1415. int saveBufSz = 0;
  1416. ret = -1;
  1417. if (saveBuf != NULL) {
  1418. saveBufSz = wc_KeyPemToDer(loadBuf, (int)fileSz,
  1419. saveBuf, (int)fileSz, password);
  1420. if (saveBufSz < 0) {
  1421. saveBufSz = 0;
  1422. XFREE(saveBuf, NULL, DYNAMIC_TYPE_X509);
  1423. saveBuf = NULL;
  1424. }
  1425. else
  1426. ret = 0;
  1427. }
  1428. ForceZero(loadBuf, (word32)fileSz);
  1429. XFREE(loadBuf, NULL, DYNAMIC_TYPE_FILE);
  1430. if (saveBuf) {
  1431. *keyBuf = saveBuf;
  1432. *keyBufSz = (word32)saveBufSz;
  1433. }
  1434. }
  1435. else {
  1436. *keyBuf = loadBuf;
  1437. *keyBufSz = (word32)fileSz;
  1438. }
  1439. if (ret < 0) {
  1440. return -1;
  1441. }
  1442. return ret;
  1443. }
  1444. #endif
  1445. #ifdef WOLFSSL_SNIFFER_WATCH
  1446. static int CreateWatchSnifferServer(char* error)
  1447. {
  1448. SnifferServer* sniffer;
  1449. sniffer = (SnifferServer*)XMALLOC(sizeof(SnifferServer), NULL,
  1450. DYNAMIC_TYPE_SNIFFER_SERVER);
  1451. if (sniffer == NULL) {
  1452. SetError(MEMORY_STR, error, NULL, 0);
  1453. return -1;
  1454. }
  1455. InitSnifferServer(sniffer);
  1456. sniffer->ctx = wolfSSL_CTX_new(wolfSSLv23_client_method());
  1457. if (!sniffer->ctx) {
  1458. SetError(MEMORY_STR, error, NULL, 0);
  1459. FreeSnifferServer(sniffer);
  1460. return -1;
  1461. }
  1462. #if defined(WOLF_CRYPTO_CB) || defined(WOLFSSL_ASYNC_CRYPT)
  1463. if (CryptoDeviceId != INVALID_DEVID)
  1464. wolfSSL_CTX_SetDevId(sniffer->ctx, CryptoDeviceId);
  1465. #endif
  1466. /* add to server list */
  1467. LOCK_SERVER_LIST();
  1468. sniffer->next = ServerList;
  1469. ServerList = sniffer;
  1470. UNLOCK_SERVER_LIST();
  1471. return 0;
  1472. }
  1473. #endif
  1474. /* Caller locks ServerListMutex */
  1475. static int SetNamedPrivateKey(const char* name, const char* address, int port,
  1476. const char* keyFile, int keySz, int typeKey, const char* password,
  1477. char* error, int isEphemeralKey)
  1478. {
  1479. SnifferServer* sniffer;
  1480. int ret;
  1481. int type = (typeKey == FILETYPE_PEM) ? WOLFSSL_FILETYPE_PEM :
  1482. WOLFSSL_FILETYPE_ASN1;
  1483. int isNew = 0;
  1484. IpAddrInfo serverIp;
  1485. #ifdef HAVE_SNI
  1486. NamedKey* namedKey = NULL;
  1487. #endif
  1488. (void)name;
  1489. #ifdef HAVE_SNI
  1490. if (name != NULL) {
  1491. namedKey = (NamedKey*)XMALLOC(sizeof(NamedKey),
  1492. NULL, DYNAMIC_TYPE_SNIFFER_NAMED_KEY);
  1493. if (namedKey == NULL) {
  1494. SetError(MEMORY_STR, error, NULL, 0);
  1495. return -1;
  1496. }
  1497. XMEMSET(namedKey, 0, sizeof(NamedKey));
  1498. namedKey->nameSz = (word32)XSTRLEN(name);
  1499. if (namedKey->nameSz > sizeof(namedKey->name)-1)
  1500. namedKey->nameSz = sizeof(namedKey->name)-1;
  1501. XSTRNCPY(namedKey->name, name, namedKey->nameSz);
  1502. namedKey->name[MAX_SERVER_NAME-1] = '\0';
  1503. namedKey->isEphemeralKey = isEphemeralKey;
  1504. ret = LoadKeyFile(&namedKey->key, &namedKey->keySz,
  1505. keyFile, keySz, type, password);
  1506. if (ret < 0) {
  1507. SetError(KEY_FILE_STR, error, NULL, 0);
  1508. FreeNamedKey(namedKey);
  1509. return -1;
  1510. }
  1511. }
  1512. #endif
  1513. serverIp.version = IPV4;
  1514. serverIp.ip4 = XINET_ADDR(address);
  1515. if (serverIp.ip4 == XINADDR_NONE) {
  1516. #ifdef FUSION_RTOS
  1517. if (XINET_PTON(AF_INET6, address, serverIp.ip6,
  1518. sizeof(serverIp.ip4)) == 1)
  1519. #else
  1520. if (XINET_PTON(AF_INET6, address, serverIp.ip6) == 1)
  1521. #endif
  1522. {
  1523. serverIp.version = IPV6;
  1524. }
  1525. }
  1526. sniffer = ServerList;
  1527. while (sniffer != NULL &&
  1528. (!MatchAddr(sniffer->server, serverIp) || sniffer->port != port)) {
  1529. sniffer = sniffer->next;
  1530. }
  1531. if (sniffer == NULL) {
  1532. isNew = 1;
  1533. sniffer = (SnifferServer*)XMALLOC(sizeof(SnifferServer),
  1534. NULL, DYNAMIC_TYPE_SNIFFER_SERVER);
  1535. if (sniffer == NULL) {
  1536. SetError(MEMORY_STR, error, NULL, 0);
  1537. #ifdef HAVE_SNI
  1538. FreeNamedKey(namedKey);
  1539. #endif
  1540. return -1;
  1541. }
  1542. InitSnifferServer(sniffer);
  1543. XSTRNCPY(sniffer->address, address, MAX_SERVER_ADDRESS-1);
  1544. sniffer->address[MAX_SERVER_ADDRESS-1] = '\0';
  1545. sniffer->server = serverIp;
  1546. sniffer->port = port;
  1547. sniffer->ctx = wolfSSL_CTX_new(wolfSSLv23_client_method());
  1548. if (!sniffer->ctx) {
  1549. SetError(MEMORY_STR, error, NULL, 0);
  1550. #ifdef HAVE_SNI
  1551. FreeNamedKey(namedKey);
  1552. #endif
  1553. FreeSnifferServer(sniffer);
  1554. return -1;
  1555. }
  1556. #if defined(WOLF_CRYPTO_CB) || defined(WOLFSSL_ASYNC_CRYPT)
  1557. if (CryptoDeviceId != INVALID_DEVID)
  1558. wolfSSL_CTX_SetDevId(sniffer->ctx, CryptoDeviceId);
  1559. #endif
  1560. }
  1561. if (name == NULL) {
  1562. if (password) {
  1563. #ifdef WOLFSSL_ENCRYPTED_KEYS
  1564. wolfSSL_CTX_set_default_passwd_cb(sniffer->ctx, SetPassword);
  1565. wolfSSL_CTX_set_default_passwd_cb_userdata(
  1566. sniffer->ctx, (void*)password);
  1567. #endif
  1568. }
  1569. #ifdef WOLFSSL_STATIC_EPHEMERAL
  1570. if (isEphemeralKey) {
  1571. /* auto detect key type with WC_PK_TYPE_NONE */
  1572. /* keySz == 0 mean load file */
  1573. ret = wolfSSL_CTX_set_ephemeral_key(sniffer->ctx, WC_PK_TYPE_NONE,
  1574. keyFile, keySz, type);
  1575. if (ret == 0)
  1576. ret = WOLFSSL_SUCCESS;
  1577. }
  1578. else
  1579. #endif
  1580. {
  1581. if (keySz == 0) {
  1582. ret = wolfSSL_CTX_use_PrivateKey_file(sniffer->ctx, keyFile, type);
  1583. }
  1584. else {
  1585. ret = wolfSSL_CTX_use_PrivateKey_buffer(sniffer->ctx,
  1586. (const byte*)keyFile, keySz, type);
  1587. }
  1588. }
  1589. if (ret != WOLFSSL_SUCCESS) {
  1590. SetError(KEY_FILE_STR, error, NULL, 0);
  1591. if (isNew)
  1592. FreeSnifferServer(sniffer);
  1593. return -1;
  1594. }
  1595. #ifdef WOLF_CRYPTO_CB
  1596. wolfSSL_CTX_SetDevId(sniffer->ctx, CryptoDeviceId);
  1597. #endif
  1598. }
  1599. #ifdef HAVE_SNI
  1600. else {
  1601. wc_LockMutex(&sniffer->namedKeysMutex);
  1602. namedKey->next = sniffer->namedKeys;
  1603. sniffer->namedKeys = namedKey;
  1604. wc_UnLockMutex(&sniffer->namedKeysMutex);
  1605. }
  1606. #endif
  1607. if (isNew) {
  1608. sniffer->next = ServerList;
  1609. ServerList = sniffer;
  1610. }
  1611. #ifndef WOLFSSL_STATIC_EPHEMERAL
  1612. (void)isEphemeralKey;
  1613. #endif
  1614. return 0;
  1615. }
  1616. #ifdef HAVE_SNI
  1617. /* Sets the private key for a specific name, server and port */
  1618. /* returns 0 on success, -1 on error */
  1619. int ssl_SetNamedPrivateKey(const char* name,
  1620. const char* address, int port,
  1621. const char* keyFile, int typeKey,
  1622. const char* password, char* error)
  1623. {
  1624. int ret;
  1625. TraceHeader();
  1626. TraceSetNamedServer(name, address, port, keyFile);
  1627. LOCK_SERVER_LIST();
  1628. ret = SetNamedPrivateKey(name, address, port, keyFile, 0,
  1629. typeKey, password, error, 0);
  1630. UNLOCK_SERVER_LIST();
  1631. if (ret == 0)
  1632. Trace(NEW_SERVER_STR);
  1633. return ret;
  1634. }
  1635. int ssl_SetNamedPrivateKeyBuffer(const char* name,
  1636. const char* address, int port,
  1637. const char* keyBuf, int keySz, int typeKey,
  1638. const char* password, char* error)
  1639. {
  1640. int ret;
  1641. TraceHeader();
  1642. TraceSetNamedServer(name, address, port, NULL);
  1643. LOCK_SERVER_LIST();
  1644. ret = SetNamedPrivateKey(name, address, port, keyBuf, keySz,
  1645. typeKey, password, error, 0);
  1646. UNLOCK_SERVER_LIST();
  1647. if (ret == 0)
  1648. Trace(NEW_SERVER_STR);
  1649. return ret;
  1650. }
  1651. #endif /* HAVE_SNI */
  1652. /* Sets the private key for a specific server and port */
  1653. /* returns 0 on success, -1 on error */
  1654. int ssl_SetPrivateKey(const char* address, int port,
  1655. const char* keyFile, int typeKey,
  1656. const char* password, char* error)
  1657. {
  1658. int ret;
  1659. TraceHeader();
  1660. TraceSetServer(address, port, keyFile);
  1661. LOCK_SERVER_LIST();
  1662. ret = SetNamedPrivateKey(NULL, address, port, keyFile, 0,
  1663. typeKey, password, error, 0);
  1664. UNLOCK_SERVER_LIST();
  1665. if (ret == 0)
  1666. Trace(NEW_SERVER_STR);
  1667. return ret;
  1668. }
  1669. int ssl_SetPrivateKeyBuffer(const char* address, int port,
  1670. const char* keyBuf, int keySz, int typeKey,
  1671. const char* password, char* error)
  1672. {
  1673. int ret;
  1674. TraceHeader();
  1675. TraceSetServer(address, port, "from buffer");
  1676. LOCK_SERVER_LIST();
  1677. ret = SetNamedPrivateKey(NULL, address, port, keyBuf, keySz,
  1678. typeKey, password, error, 0);
  1679. UNLOCK_SERVER_LIST();
  1680. if (ret == 0)
  1681. Trace(NEW_SERVER_STR);
  1682. return ret;
  1683. }
  1684. #ifdef WOLFSSL_STATIC_EPHEMERAL
  1685. #ifdef HAVE_SNI
  1686. /* Sets the ephemeral key for a specific name, server and port */
  1687. /* returns 0 on success, -1 on error */
  1688. int ssl_SetNamedEphemeralKey(const char* name,
  1689. const char* address, int port,
  1690. const char* keyFile, int typeKey,
  1691. const char* password, char* error)
  1692. {
  1693. int ret;
  1694. TraceHeader();
  1695. TraceSetNamedServer(name, address, port, keyFile);
  1696. LOCK_SERVER_LIST();
  1697. ret = SetNamedPrivateKey(name, address, port, keyFile, 0,
  1698. typeKey, password, error, 1);
  1699. UNLOCK_SERVER_LIST();
  1700. if (ret == 0)
  1701. Trace(NEW_SERVER_STR);
  1702. return ret;
  1703. }
  1704. int ssl_SetNamedEphemeralKeyBuffer(const char* name,
  1705. const char* address, int port,
  1706. const char* keyBuf, int keySz, int typeKey,
  1707. const char* password, char* error)
  1708. {
  1709. int ret;
  1710. TraceHeader();
  1711. TraceSetNamedServer(name, address, port, NULL);
  1712. LOCK_SERVER_LIST();
  1713. ret = SetNamedPrivateKey(name, address, port, keyBuf, keySz,
  1714. typeKey, password, error, 1);
  1715. UNLOCK_SERVER_LIST();
  1716. if (ret == 0)
  1717. Trace(NEW_SERVER_STR);
  1718. return ret;
  1719. }
  1720. #endif /* HAVE_SNI */
  1721. /* Sets the ephemeral key for a specific server and port */
  1722. /* returns 0 on success, -1 on error */
  1723. int ssl_SetEphemeralKey(const char* address, int port,
  1724. const char* keyFile, int typeKey,
  1725. const char* password, char* error)
  1726. {
  1727. int ret;
  1728. TraceHeader();
  1729. TraceSetServer(address, port, keyFile);
  1730. LOCK_SERVER_LIST();
  1731. ret = SetNamedPrivateKey(NULL, address, port, keyFile, 0,
  1732. typeKey, password, error, 1);
  1733. UNLOCK_SERVER_LIST();
  1734. if (ret == 0)
  1735. Trace(NEW_SERVER_STR);
  1736. return ret;
  1737. }
  1738. int ssl_SetEphemeralKeyBuffer(const char* address, int port,
  1739. const char* keyBuf, int keySz, int typeKey,
  1740. const char* password, char* error)
  1741. {
  1742. int ret;
  1743. TraceHeader();
  1744. TraceSetServer(address, port, "from buffer");
  1745. LOCK_SERVER_LIST();
  1746. ret = SetNamedPrivateKey(NULL, address, port, keyBuf, keySz,
  1747. typeKey, password, error, 1);
  1748. UNLOCK_SERVER_LIST();
  1749. if (ret == 0)
  1750. Trace(NEW_SERVER_STR);
  1751. return ret;
  1752. }
  1753. #endif /* WOLFSSL_STATIC_EPHEMERAL */
  1754. /* Check IP Header for IPV6, TCP, and a registered server address */
  1755. /* returns 0 on success, -1 on error */
  1756. static int CheckIp6Hdr(Ip6Hdr* iphdr, IpInfo* info, int length, char* error)
  1757. {
  1758. int version = IP_V(iphdr);
  1759. int exthdrsz = IP6_HDR_SZ;
  1760. TraceIP6(iphdr);
  1761. Trace(IP_CHECK_STR);
  1762. if (version != IPV6) {
  1763. SetError(BAD_IPVER_STR, error, NULL, 0);
  1764. return -1;
  1765. }
  1766. /* Here, we need to move onto next header if not TCP. */
  1767. if (iphdr->next_header != TCP_PROTOCOL) {
  1768. Ip6ExtHdr* exthdr = (Ip6ExtHdr*)((byte*)iphdr + IP6_HDR_SZ);
  1769. do {
  1770. int hdrsz = (exthdr->length + 1) * 8;
  1771. if (hdrsz > length - exthdrsz) {
  1772. SetError(PACKET_HDR_SHORT_STR, error, NULL, 0);
  1773. return -1;
  1774. }
  1775. exthdrsz += hdrsz;
  1776. exthdr = (Ip6ExtHdr*)((byte*)exthdr + hdrsz);
  1777. }
  1778. while (exthdr->next_header != TCP_PROTOCOL &&
  1779. exthdr->next_header != NO_NEXT_HEADER);
  1780. }
  1781. #ifndef WOLFSSL_SNIFFER_WATCH
  1782. if (!IsServerRegistered6(iphdr->src) && !IsServerRegistered6(iphdr->dst)) {
  1783. SetError(SERVER_NOT_REG_STR, error, NULL, 0);
  1784. return -1;
  1785. }
  1786. #endif
  1787. info->length = exthdrsz;
  1788. info->total = XNTOHS(iphdr->length) + info->length;
  1789. /* IPv6 doesn't include its own header size in the length like v4. */
  1790. info->src.version = IPV6;
  1791. XMEMCPY(info->src.ip6, iphdr->src, sizeof(info->src.ip6));
  1792. info->dst.version = IPV6;
  1793. XMEMCPY(info->dst.ip6, iphdr->dst, sizeof(info->dst.ip6));
  1794. return 0;
  1795. }
  1796. /* Check IP Header for IPV4, TCP, and a registered server address */
  1797. /* If header IPv6, pass to CheckIp6Hdr(). */
  1798. /* returns 0 on success, -1 on error */
  1799. static int CheckIpHdr(IpHdr* iphdr, IpInfo* info, int length, char* error,
  1800. int trace)
  1801. {
  1802. int version = IP_V(iphdr);
  1803. if (version == IPV6)
  1804. return CheckIp6Hdr((Ip6Hdr*)iphdr, info, length, error);
  1805. if (trace) {
  1806. TraceIP(iphdr);
  1807. Trace(IP_CHECK_STR);
  1808. }
  1809. if (version != IPV4) {
  1810. SetError(BAD_IPVER_STR, error, NULL, 0);
  1811. return -1;
  1812. }
  1813. if (iphdr->protocol != TCP_PROTOCOL) {
  1814. SetError(BAD_PROTO_STR, error, NULL, 0);
  1815. return -1;
  1816. }
  1817. info->length = IP_HL(iphdr);
  1818. info->total = XNTOHS(iphdr->length);
  1819. info->src.version = IPV4;
  1820. info->src.ip4 = iphdr->src;
  1821. info->dst.version = IPV4;
  1822. info->dst.ip4 = iphdr->dst;
  1823. if (info->total == 0)
  1824. info->total = length; /* reassembled may be off */
  1825. return 0;
  1826. }
  1827. /* Check TCP Header for a registered port */
  1828. /* returns 0 on success, -1 on error */
  1829. static int CheckTcpHdr(TcpHdr* tcphdr, TcpInfo* info, char* error, int trace)
  1830. {
  1831. if (trace) {
  1832. TraceTcp(tcphdr);
  1833. Trace(TCP_CHECK_STR);
  1834. }
  1835. info->srcPort = XNTOHS(tcphdr->srcPort);
  1836. info->dstPort = XNTOHS(tcphdr->dstPort);
  1837. info->length = TCP_LEN(tcphdr);
  1838. info->sequence = XNTOHL(tcphdr->sequence);
  1839. info->fin = tcphdr->flags & TCP_FIN;
  1840. info->rst = tcphdr->flags & TCP_RST;
  1841. info->syn = tcphdr->flags & TCP_SYN;
  1842. info->ack = tcphdr->flags & TCP_ACK;
  1843. if (info->ack)
  1844. info->ackNumber = XNTOHL(tcphdr->ack);
  1845. (void)error;
  1846. return 0;
  1847. }
  1848. /* Decode Record Layer Header */
  1849. static int GetRecordHeader(const byte* input, RecordLayerHeader* rh, int* size)
  1850. {
  1851. XMEMCPY(rh, input, RECORD_HEADER_SZ);
  1852. *size = (rh->length[0] << 8) | rh->length[1];
  1853. if (*size > (MAX_RECORD_SIZE + COMP_EXTRA + MAX_MSG_EXTRA))
  1854. return LENGTH_ERROR;
  1855. return 0;
  1856. }
  1857. /* Copies the session's information to the provided sslInfo. Skip copy if
  1858. * SSLInfo is not provided. */
  1859. static void CopySessionInfo(SnifferSession* session, SSLInfo* sslInfo)
  1860. {
  1861. if (NULL != sslInfo) {
  1862. XMEMSET(sslInfo, 0, sizeof(SSLInfo));
  1863. /* Pass back Session Info after we have processed the Server Hello. */
  1864. if (0 != session->sslServer->options.cipherSuite) {
  1865. const char* pCipher;
  1866. sslInfo->isValid = 1;
  1867. sslInfo->protocolVersionMajor = session->sslServer->version.major;
  1868. sslInfo->protocolVersionMinor = session->sslServer->version.minor;
  1869. sslInfo->serverCipherSuite0 =
  1870. session->sslServer->options.cipherSuite0;
  1871. sslInfo->serverCipherSuite =
  1872. session->sslServer->options.cipherSuite;
  1873. pCipher = wolfSSL_get_cipher(session->sslServer);
  1874. if (NULL != pCipher) {
  1875. XSTRNCPY((char*)sslInfo->serverCipherSuiteName, pCipher,
  1876. sizeof(sslInfo->serverCipherSuiteName) - 1);
  1877. sslInfo->serverCipherSuiteName
  1878. [sizeof(sslInfo->serverCipherSuiteName) - 1] = '\0';
  1879. }
  1880. sslInfo->keySize = session->keySz;
  1881. #ifdef HAVE_SNI
  1882. if (NULL != session->sni) {
  1883. XSTRNCPY((char*)sslInfo->serverNameIndication,
  1884. session->sni, sizeof(sslInfo->serverNameIndication) - 1);
  1885. sslInfo->serverNameIndication
  1886. [sizeof(sslInfo->serverNameIndication) - 1] = '\0';
  1887. }
  1888. #endif
  1889. TraceSessionInfo(sslInfo);
  1890. }
  1891. }
  1892. }
  1893. /* Call the session connection start callback. */
  1894. static void CallConnectionCb(SnifferSession* session)
  1895. {
  1896. if (ConnectionCb != NULL) {
  1897. SSLInfo info;
  1898. CopySessionInfo(session, &info);
  1899. ConnectionCb((const void*)session, &info, ConnectionCbCtx);
  1900. }
  1901. }
  1902. #ifdef SHOW_SECRETS
  1903. static void PrintSecret(const char* desc, const byte* buf, int sz)
  1904. {
  1905. int i;
  1906. printf("%s: ", desc);
  1907. for (i = 0; i < sz; i++) {
  1908. printf("%02x", buf[i]);
  1909. }
  1910. printf("\n");
  1911. }
  1912. static void ShowTlsSecrets(SnifferSession* session)
  1913. {
  1914. PrintSecret("server master secret", session->sslServer->arrays->masterSecret, SECRET_LEN);
  1915. PrintSecret("client master secret", session->sslClient->arrays->masterSecret, SECRET_LEN);
  1916. printf("server suite = %d\n", session->sslServer->options.cipherSuite);
  1917. printf("client suite = %d\n", session->sslClient->options.cipherSuite);
  1918. }
  1919. #endif /* SHOW_SECRETS */
  1920. typedef struct {
  1921. int type;
  1922. union {
  1923. #ifndef NO_RSA
  1924. RsaKey rsa;
  1925. #endif
  1926. #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)
  1927. struct {
  1928. word32 pLen; /* modulus length */
  1929. word32 privKeySz;
  1930. byte privKey[WC_DH_PRIV_MAX_SZ]; /* max for TLS */
  1931. DhKey key;
  1932. } dh;
  1933. #endif
  1934. #ifdef HAVE_ECC
  1935. ecc_key ecc;
  1936. #endif
  1937. #ifdef HAVE_CURVE25519
  1938. curve25519_key x25519;
  1939. #endif
  1940. #ifdef HAVE_CURVE448
  1941. curve448_key x448;
  1942. #endif
  1943. } priv;
  1944. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  1945. union {
  1946. /* RSA is for static RSA only */
  1947. /* DH does not use public DhKey for Agree */
  1948. #ifdef HAVE_ECC
  1949. ecc_key ecc;
  1950. #endif
  1951. #ifdef HAVE_CURVE25519
  1952. curve25519_key x25519;
  1953. #endif
  1954. #ifdef HAVE_CURVE448
  1955. curve448_key x448;
  1956. #endif
  1957. } pub;
  1958. #endif
  1959. byte initPriv:1;
  1960. byte initPub:1;
  1961. } SnifferKey;
  1962. typedef struct SetupKeysArgs {
  1963. #ifdef WOLFSSL_ASYNC_CRYPT
  1964. SnifferKey* key;
  1965. #else
  1966. SnifferKey key[1];
  1967. #endif
  1968. DerBuffer* keyBuf;
  1969. int length;
  1970. byte keyBufFree:1;
  1971. byte keyLocked:1;
  1972. } SetupKeysArgs;
  1973. static void FreeSetupKeysArgs(WOLFSSL* ssl, void* pArgs)
  1974. {
  1975. SetupKeysArgs* args = (SetupKeysArgs*)pArgs;
  1976. if (args == NULL) {
  1977. return;
  1978. }
  1979. (void)ssl;
  1980. #ifdef WOLFSSL_ASYNC_CRYPT
  1981. if (args->key != NULL)
  1982. #endif
  1983. {
  1984. #ifndef NO_RSA
  1985. if (args->key->type == WC_PK_TYPE_RSA) {
  1986. if (args->key->initPriv) {
  1987. wc_FreeRsaKey(&args->key->priv.rsa);
  1988. }
  1989. }
  1990. #endif
  1991. #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)
  1992. if (args->key->type == WC_PK_TYPE_DH) {
  1993. if (args->key->initPriv) {
  1994. wc_FreeDhKey(&args->key->priv.dh.key);
  1995. }
  1996. }
  1997. #endif
  1998. #ifdef HAVE_ECC
  1999. if (args->key->type == WC_PK_TYPE_ECDH) {
  2000. if (args->key->initPriv) {
  2001. wc_ecc_free(&args->key->priv.ecc);
  2002. }
  2003. if (args->key->initPub) {
  2004. wc_ecc_free(&args->key->pub.ecc);
  2005. }
  2006. }
  2007. #endif
  2008. #ifdef HAVE_CURVE25519
  2009. if (args->key->type == WC_PK_TYPE_CURVE25519) {
  2010. if (args->key->initPriv) {
  2011. wc_curve25519_free(&args->key->priv.x25519);
  2012. }
  2013. if (args->key->initPub) {
  2014. wc_curve25519_free(&args->key->pub.x25519);
  2015. }
  2016. }
  2017. #endif
  2018. #ifdef HAVE_CURVE448
  2019. if (args->key->type == WC_PK_TYPE_CURVE448) {
  2020. if (args->key->initPriv) {
  2021. wc_curve448_free(&args->key->priv.x448);
  2022. }
  2023. if (args->key->initPub) {
  2024. wc_curve448_free(&args->key->pub.x448);
  2025. }
  2026. }
  2027. #endif
  2028. args->key->type = WC_PK_TYPE_NONE;
  2029. args->key->initPriv = 0; args->key->initPub = 0;
  2030. #ifdef WOLFSSL_ASYNC_CRYPT
  2031. XFREE(args->key, NULL, DYNAMIC_TYPE_SNIFFER_KEY);
  2032. args->key = NULL;
  2033. #else
  2034. XMEMSET(args->key, 0, sizeof(args->key));
  2035. #endif
  2036. }
  2037. if (args->keyBuf != NULL && args->keyBufFree) {
  2038. FreeDer(&args->keyBuf);
  2039. args->keyBufFree = 0;
  2040. }
  2041. }
  2042. /* Process Keys */
  2043. static int SetupKeys(const byte* input, int* sslBytes, SnifferSession* session,
  2044. char* error, KeyShareInfo* ksInfo)
  2045. {
  2046. word32 idx;
  2047. int ret;
  2048. int devId = INVALID_DEVID;
  2049. WOLFSSL_CTX* ctx = session->context->ctx;
  2050. WOLFSSL* ssl = session->sslServer;
  2051. #ifdef WOLFSSL_ASYNC_CRYPT
  2052. SetupKeysArgs* args = NULL;
  2053. WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
  2054. #else
  2055. SetupKeysArgs args[1];
  2056. #endif
  2057. Trace(SNIFFER_KEY_SETUP_STR);
  2058. if (session->sslServer->arrays == NULL ||
  2059. session->sslClient->arrays == NULL) {
  2060. /* Secret's have already been established and released.
  2061. * This can happen with secure renegotiation. */
  2062. return 0;
  2063. }
  2064. #ifdef WOLFSSL_ASYNC_CRYPT
  2065. if (ssl->async == NULL) {
  2066. ssl->async = (struct WOLFSSL_ASYNC*)
  2067. XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
  2068. DYNAMIC_TYPE_ASYNC);
  2069. if (ssl->async == NULL)
  2070. ERROR_OUT(MEMORY_E, exit_sk);
  2071. }
  2072. args = (SetupKeysArgs*)ssl->async->args;
  2073. ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
  2074. if (ret != WC_NOT_PENDING_E) {
  2075. /* Check for error */
  2076. if (ret < 0)
  2077. goto exit_sk;
  2078. }
  2079. else
  2080. #endif
  2081. {
  2082. /* Reset state */
  2083. ret = 0;
  2084. ssl->options.asyncState = TLS_ASYNC_BEGIN;
  2085. XMEMSET(args, 0, sizeof(SetupKeysArgs));
  2086. #ifdef WOLFSSL_ASYNC_CRYPT
  2087. ssl->async->freeArgs = FreeSetupKeysArgs;
  2088. #endif
  2089. #ifdef WOLFSSL_ASYNC_CRYPT
  2090. args->key = (SnifferKey*)XMALLOC(sizeof(SnifferKey), NULL,
  2091. DYNAMIC_TYPE_SNIFFER_KEY);
  2092. #endif
  2093. }
  2094. #if defined(WOLF_CRYPTO_CB) || defined(WOLFSSL_ASYNC_CRYPT)
  2095. devId = CryptoDeviceId;
  2096. #endif
  2097. #ifdef WOLFSSL_ASYNC_CRYPT
  2098. if (args->key == NULL) {
  2099. ERROR_OUT(MEMORY_E, exit_sk);
  2100. }
  2101. #endif
  2102. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  2103. if (session->context->useKeyLogFile) {
  2104. ret = 0;
  2105. XMEMSET(args, 0, sizeof(SetupKeysArgs));
  2106. /* We want to skip all the key setup and go right to master secret generation, which is
  2107. * where we inject the master secret obtained from the keylog file */
  2108. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  2109. }
  2110. #endif
  2111. switch (ssl->options.asyncState) {
  2112. case TLS_ASYNC_BEGIN:
  2113. {
  2114. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
  2115. int useCurveId = 0;
  2116. if (ksInfo && ksInfo->curve_id != 0) {
  2117. useCurveId = ksInfo->curve_id;
  2118. }
  2119. #endif
  2120. #if defined(WOLFSSL_STATIC_EPHEMERAL) && !defined(SINGLE_THREADED)
  2121. if (ctx->staticKELockInit &&
  2122. wc_LockMutex(&ctx->staticKELock) == 0) {
  2123. args->keyLocked = 1;
  2124. }
  2125. #endif
  2126. #ifndef NO_RSA
  2127. /* Static RSA */
  2128. if (ksInfo == NULL && ssl->buffers.key) {
  2129. ret = wc_InitRsaKey_ex(&args->key->priv.rsa, NULL, devId);
  2130. if (ret == 0) {
  2131. args->key->type = WC_PK_TYPE_RSA;
  2132. args->key->initPriv = 1;
  2133. args->keyBuf = ssl->buffers.key;
  2134. #ifdef WOLFSSL_ASYNC_CRYPT
  2135. ret = wolfSSL_AsyncInit(ssl, &args->key->priv.rsa.asyncDev,
  2136. WC_ASYNC_FLAG_CALL_AGAIN);
  2137. #endif
  2138. }
  2139. if (ret == 0) {
  2140. idx = 0;
  2141. ret = wc_RsaPrivateKeyDecode(args->keyBuf->buffer, &idx,
  2142. &args->key->priv.rsa, args->keyBuf->length);
  2143. if (ret != 0) {
  2144. #ifndef HAVE_ECC
  2145. SetError(RSA_DECODE_STR, error, session,
  2146. FATAL_ERROR_STATE);
  2147. break;
  2148. #else
  2149. /* If we can do ECC, this isn't fatal. Not loading a key
  2150. * later will be fatal, though. */
  2151. SetError(RSA_DECODE_STR, error, session, 0);
  2152. args->keyBuf = NULL;
  2153. #endif
  2154. }
  2155. }
  2156. if (ret == 0) {
  2157. args->length = wc_RsaEncryptSize(&args->key->priv.rsa);
  2158. if (IsTLS(session->sslServer)) {
  2159. input += 2; /* tls pre length */
  2160. }
  2161. if (args->length > *sslBytes) {
  2162. SetError(PARTIAL_INPUT_STR, error, session,
  2163. FATAL_ERROR_STATE);
  2164. ret = -1;
  2165. }
  2166. }
  2167. #ifdef WC_RSA_BLINDING
  2168. if (ret == 0) {
  2169. ret = wc_RsaSetRNG(&args->key->priv.rsa,
  2170. session->sslServer->rng);
  2171. if (ret != 0) {
  2172. SetError(RSA_DECRYPT_STR, error, session,
  2173. FATAL_ERROR_STATE);
  2174. }
  2175. }
  2176. #endif
  2177. if (ret == 0) {
  2178. session->keySz = args->length * WOLFSSL_BIT_SIZE;
  2179. /* length is the key size in bytes */
  2180. session->sslServer->arrays->preMasterSz = SECRET_LEN;
  2181. }
  2182. }
  2183. #endif /* !NO_RSA */
  2184. #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)
  2185. /* Static DH Key */
  2186. if (ksInfo && ksInfo->dh_key_bits != 0 && args->keyBuf == NULL) {
  2187. #ifdef HAVE_PUBLIC_FFDHE
  2188. const DhParams* params;
  2189. #endif
  2190. /* try and load static ephemeral */
  2191. #ifdef WOLFSSL_STATIC_EPHEMERAL
  2192. args->keyBuf = ssl->staticKE.dhKey;
  2193. if (args->keyBuf == NULL)
  2194. args->keyBuf = ctx->staticKE.dhKey;
  2195. #endif
  2196. ret = 0;
  2197. #ifdef WOLFSSL_SNIFFER_KEY_CALLBACK
  2198. if (KeyCb != NULL) {
  2199. if (args->keyBuf == NULL) {
  2200. ret = AllocDer(&args->keyBuf, FILE_BUFFER_SIZE,
  2201. PRIVATEKEY_TYPE, NULL);
  2202. if (ret == 0)
  2203. args->keyBufFree = 1;
  2204. }
  2205. ret = KeyCb(session, ksInfo->named_group,
  2206. session->srvKs.key, session->srvKs.key_len,
  2207. session->cliKs.key, session->cliKs.key_len,
  2208. args->keyBuf, KeyCbCtx, error);
  2209. if (ret != 0) {
  2210. SetError(-1, error, session, FATAL_ERROR_STATE);
  2211. }
  2212. }
  2213. #endif
  2214. if (ret == 0 && args->keyBuf == NULL) {
  2215. ret = BUFFER_E;
  2216. }
  2217. #ifdef HAVE_PUBLIC_FFDHE
  2218. if (ret == 0) {
  2219. /* get DH params */
  2220. switch (ksInfo->named_group) {
  2221. #ifdef HAVE_FFDHE_2048
  2222. case WOLFSSL_FFDHE_2048:
  2223. params = wc_Dh_ffdhe2048_Get();
  2224. args->key->priv.dh.privKeySz = 29;
  2225. break;
  2226. #endif
  2227. #ifdef HAVE_FFDHE_3072
  2228. case WOLFSSL_FFDHE_3072:
  2229. params = wc_Dh_ffdhe3072_Get();
  2230. args->key->priv.dh.privKeySz = 34;
  2231. break;
  2232. #endif
  2233. #ifdef HAVE_FFDHE_4096
  2234. case WOLFSSL_FFDHE_4096:
  2235. params = wc_Dh_ffdhe4096_Get();
  2236. args->key->priv.dh.privKeySz = 39;
  2237. break;
  2238. #endif
  2239. #ifdef HAVE_FFDHE_6144
  2240. case WOLFSSL_FFDHE_6144:
  2241. params = wc_Dh_ffdhe6144_Get();
  2242. args->key->priv.dh.privKeySz = 46;
  2243. break;
  2244. #endif
  2245. #ifdef HAVE_FFDHE_8192
  2246. case WOLFSSL_FFDHE_8192:
  2247. params = wc_Dh_ffdhe8192_Get();
  2248. args->key->priv.dh.privKeySz = 52;
  2249. break;
  2250. #endif
  2251. default:
  2252. ret = BAD_FUNC_ARG;
  2253. }
  2254. }
  2255. #endif
  2256. if (ret == 0) {
  2257. ret = wc_InitDhKey_ex(&args->key->priv.dh.key, NULL, devId);
  2258. if (ret == 0) {
  2259. args->key->type = WC_PK_TYPE_DH;
  2260. args->key->initPriv = 1;
  2261. #ifdef WOLFSSL_ASYNC_CRYPT
  2262. ret = wolfSSL_AsyncInit(ssl,
  2263. &args->key->priv.dh.key.asyncDev, WC_ASYNC_FLAG_NONE);
  2264. #endif
  2265. }
  2266. }
  2267. if (ret == 0) {
  2268. #ifdef HAVE_PUBLIC_FFDHE
  2269. ret = wc_DhSetKey(&args->key->priv.dh.key,
  2270. (byte*)params->p, params->p_len,
  2271. (byte*)params->g, params->g_len);
  2272. args->key->priv.dh.pLen = params->p_len;
  2273. #else
  2274. ret = wc_DhSetNamedKey(&args->key->priv.dh.key,
  2275. ksInfo->named_group);
  2276. if (ret == 0) {
  2277. args->key->priv.dh.privKeySz =
  2278. wc_DhGetNamedKeyMinSize(ksInfo->named_group);
  2279. ret = wc_DhGetNamedKeyParamSize(ksInfo->named_group,
  2280. &args->key->priv.dh.pLen, NULL, NULL);
  2281. }
  2282. #endif
  2283. }
  2284. if (ret == 0) {
  2285. idx = 0;
  2286. ret = wc_DhKeyDecode(args->keyBuf->buffer, &idx,
  2287. &args->key->priv.dh.key, args->keyBuf->length);
  2288. }
  2289. if (ret == 0) {
  2290. ret = wc_DhExportKeyPair(&args->key->priv.dh.key,
  2291. args->key->priv.dh.privKey, &args->key->priv.dh.privKeySz,
  2292. NULL, NULL);
  2293. }
  2294. }
  2295. #endif /* !NO_DH && WOLFSSL_DH_EXTRA */
  2296. #ifdef HAVE_ECC
  2297. /* Static ECC Key */
  2298. if (useCurveId >= 0 && args->keyBuf == NULL
  2299. #ifdef HAVE_CURVE25519
  2300. && useCurveId != ECC_X25519
  2301. #endif
  2302. #ifdef HAVE_CURVE448
  2303. && useCurveId != ECC_X448
  2304. #endif
  2305. ) {
  2306. /* try and load static ephemeral */
  2307. #ifdef WOLFSSL_STATIC_EPHEMERAL
  2308. args->keyBuf = ssl->staticKE.ecKey;
  2309. if (args->keyBuf == NULL)
  2310. args->keyBuf = ctx->staticKE.ecKey;
  2311. #endif
  2312. /* try static ECC */
  2313. if (args->keyBuf == NULL) {
  2314. args->keyBuf = session->sslServer->buffers.key;
  2315. }
  2316. ret = 0;
  2317. #ifdef WOLFSSL_SNIFFER_KEY_CALLBACK
  2318. if (KeyCb != NULL && ksInfo) {
  2319. if (args->keyBuf == NULL) {
  2320. ret = AllocDer(&args->keyBuf, FILE_BUFFER_SIZE,
  2321. PRIVATEKEY_TYPE, NULL);
  2322. if (ret == 0)
  2323. args->keyBufFree = 1;
  2324. }
  2325. ret = KeyCb(session, ksInfo->named_group,
  2326. session->srvKs.key, session->srvKs.key_len,
  2327. session->cliKs.key, session->cliKs.key_len,
  2328. args->keyBuf, KeyCbCtx, error);
  2329. if (ret != 0) {
  2330. SetError(-1, error, session, FATAL_ERROR_STATE);
  2331. }
  2332. }
  2333. #endif
  2334. if (ret == 0 && args->keyBuf == NULL) {
  2335. ret = BUFFER_E;
  2336. }
  2337. if (ret == 0) {
  2338. ret = wc_ecc_init_ex(&args->key->priv.ecc, NULL, devId);
  2339. if (ret == 0) {
  2340. args->key->type = WC_PK_TYPE_ECDH;
  2341. args->key->initPriv = 1;
  2342. #ifdef WOLFSSL_ASYNC_CRYPT
  2343. ret = wolfSSL_AsyncInit(ssl, &args->key->priv.ecc.asyncDev,
  2344. WC_ASYNC_FLAG_CALL_AGAIN);
  2345. #endif
  2346. }
  2347. }
  2348. #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
  2349. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
  2350. !defined(HAVE_SELFTEST)
  2351. if (ret == 0) {
  2352. ret = wc_ecc_set_rng(&args->key->priv.ecc,
  2353. session->sslServer->rng);
  2354. }
  2355. #endif
  2356. if (ret == 0) {
  2357. idx = 0;
  2358. ret = wc_EccPrivateKeyDecode(args->keyBuf->buffer, &idx,
  2359. &args->key->priv.ecc, args->keyBuf->length);
  2360. if (ret != 0) {
  2361. SetError(ECC_DECODE_STR, error, session, FATAL_ERROR_STATE);
  2362. }
  2363. }
  2364. if (ret == 0) {
  2365. args->length = wc_ecc_size(&args->key->priv.ecc) * 2 + 1;
  2366. /* The length should be 2 times the key size (x and y), plus 1
  2367. * for the type byte. */
  2368. if (!IsAtLeastTLSv1_3(session->sslServer->version)) {
  2369. input += 1; /* Don't include the TLS length for the key. */
  2370. }
  2371. if (args->length > *sslBytes) {
  2372. SetError(PARTIAL_INPUT_STR, error, session,
  2373. FATAL_ERROR_STATE);
  2374. ret = -1;
  2375. }
  2376. /* if curve not provided in key share data, then use private
  2377. * key curve */
  2378. if (useCurveId == 0 && args->key->priv.ecc.dp) {
  2379. /* this is for the static ECC case */
  2380. useCurveId = args->key->priv.ecc.dp->id;
  2381. }
  2382. }
  2383. if (ret == 0) {
  2384. ret = wc_ecc_init(&args->key->pub.ecc);
  2385. if (ret == 0)
  2386. args->key->initPub = 1;
  2387. }
  2388. if (ret == 0) {
  2389. ret = wc_ecc_import_x963_ex(input, args->length,
  2390. &args->key->pub.ecc, useCurveId);
  2391. if (ret != 0) {
  2392. SetError(ECC_PUB_DECODE_STR, error, session,
  2393. FATAL_ERROR_STATE);
  2394. }
  2395. }
  2396. if (ret == 0) {
  2397. session->keySz = ((args->length - 1) / 2) * WOLFSSL_BIT_SIZE;
  2398. /* Length is in bytes. Subtract 1 for the ECC key type. Divide
  2399. * by two as the key is in (x,y) coordinates, where x and y are
  2400. * the same size, the key size. Convert from bytes to bits. */
  2401. session->sslServer->arrays->preMasterSz = ENCRYPT_LEN;
  2402. }
  2403. }
  2404. #endif /* HAVE_ECC */
  2405. #ifdef HAVE_CURVE25519
  2406. /* Static Curve25519 Key */
  2407. if (useCurveId == ECC_X25519) {
  2408. /* try and load static ephemeral */
  2409. #ifdef WOLFSSL_STATIC_EPHEMERAL
  2410. args->keyBuf = ssl->staticKE.x25519Key;
  2411. if (args->keyBuf == NULL)
  2412. args->keyBuf = ctx->staticKE.x25519Key;
  2413. #endif
  2414. ret = 0;
  2415. #ifdef WOLFSSL_SNIFFER_KEY_CALLBACK
  2416. if (KeyCb != NULL && ksInfo) {
  2417. if (args->keyBuf == NULL) {
  2418. ret = AllocDer(&args->keyBuf, FILE_BUFFER_SIZE,
  2419. PRIVATEKEY_TYPE, NULL);
  2420. if (ret == 0)
  2421. args->keyBufFree = 1;
  2422. }
  2423. ret = KeyCb(session, ksInfo->named_group,
  2424. session->srvKs.key, session->srvKs.key_len,
  2425. session->cliKs.key, session->cliKs.key_len,
  2426. args->keyBuf, KeyCbCtx, error);
  2427. if (ret != 0) {
  2428. SetError(-1, error, session, FATAL_ERROR_STATE);
  2429. break;
  2430. }
  2431. }
  2432. #endif
  2433. if (ret == 0 && args->keyBuf == NULL) {
  2434. ret = BUFFER_E;
  2435. }
  2436. if (ret == 0) {
  2437. ret = wc_curve25519_init_ex(&args->key->priv.x25519, NULL,
  2438. devId);
  2439. if (ret == 0) {
  2440. args->key->type = WC_PK_TYPE_CURVE25519;
  2441. args->key->initPriv = 1;
  2442. #ifdef WOLFSSL_ASYNC_CRYPT
  2443. ret = wolfSSL_AsyncInit(ssl,
  2444. &args->key->priv.x25519.asyncDev,
  2445. WC_ASYNC_FLAG_CALL_AGAIN);
  2446. #endif
  2447. }
  2448. }
  2449. if (ret == 0) {
  2450. idx = 0;
  2451. ret = wc_Curve25519PrivateKeyDecode(args->keyBuf->buffer, &idx,
  2452. &args->key->priv.x25519, args->keyBuf->length);
  2453. if (ret != 0) {
  2454. SetError(ECC_DECODE_STR, error, session, FATAL_ERROR_STATE);
  2455. }
  2456. }
  2457. if (ret == 0) {
  2458. args->length = CURVE25519_KEYSIZE;
  2459. if (args->length > *sslBytes) {
  2460. SetError(PARTIAL_INPUT_STR, error, session,
  2461. FATAL_ERROR_STATE);
  2462. ret = -1;
  2463. }
  2464. }
  2465. if (ret == 0) {
  2466. ret = wc_curve25519_init(&args->key->pub.x25519);
  2467. if (ret == 0)
  2468. args->key->initPub = 1;
  2469. }
  2470. if (ret == 0) {
  2471. ret = wc_curve25519_import_public_ex(input, args->length,
  2472. &args->key->pub.x25519, EC25519_LITTLE_ENDIAN);
  2473. if (ret != 0) {
  2474. SetError(ECC_PUB_DECODE_STR, error, session,
  2475. FATAL_ERROR_STATE);
  2476. }
  2477. }
  2478. if (ret == 0) {
  2479. /* For Curve25519 length is always 32 */
  2480. session->keySz = CURVE25519_KEYSIZE;
  2481. session->sslServer->arrays->preMasterSz = ENCRYPT_LEN;
  2482. }
  2483. }
  2484. #endif /* HAVE_CURVE25519 */
  2485. #ifdef HAVE_CURVE448
  2486. /* Static Curve448 Key */
  2487. if (useCurveId == ECC_X448) {
  2488. /* try and load static ephemeral */
  2489. #ifdef WOLFSSL_STATIC_EPHEMERAL
  2490. args->keyBuf = ssl->staticKE.x448Key;
  2491. if (args->keyBuf == NULL)
  2492. args->keyBuf = ctx->staticKE.x448Key;
  2493. #endif
  2494. ret = 0;
  2495. #ifdef WOLFSSL_SNIFFER_KEY_CALLBACK
  2496. if (KeyCb != NULL && ksInfo) {
  2497. if (args->keyBuf == NULL) {
  2498. ret = AllocDer(&args->keyBuf, FILE_BUFFER_SIZE,
  2499. PRIVATEKEY_TYPE, NULL);
  2500. if (ret == 0)
  2501. args->keyBufFree = 1;
  2502. }
  2503. ret = KeyCb(session, ksInfo->named_group,
  2504. session->srvKs.key, session->srvKs.key_len,
  2505. session->cliKs.key, session->cliKs.key_len,
  2506. args->keyBuf, KeyCbCtx, error);
  2507. if (ret != 0) {
  2508. SetError(-1, error, session, FATAL_ERROR_STATE);
  2509. break;
  2510. }
  2511. }
  2512. #endif
  2513. if (ret == 0 && args->keyBuf == NULL) {
  2514. ret = BUFFER_E;
  2515. }
  2516. if (ret == 0) {
  2517. ret = wc_curve448_init(&args->key->priv.x448);
  2518. if (ret == 0) {
  2519. args->key->type = WC_PK_TYPE_CURVE448;
  2520. args->key->initPriv = 1;
  2521. #ifdef WOLFSSL_ASYNC_CRYPT
  2522. ret = wolfSSL_AsyncInit(ssl, &args->key->priv.x448.asyncDev,
  2523. WC_ASYNC_FLAG_CALL_AGAIN);
  2524. #endif
  2525. }
  2526. }
  2527. if (ret == 0) {
  2528. idx = 0;
  2529. ret = wc_Curve448PrivateKeyDecode(args->keyBuf->buffer, &idx,
  2530. &args->key->priv.x448, args->keyBuf->length);
  2531. if (ret != 0) {
  2532. SetError(ECC_DECODE_STR, error, session, FATAL_ERROR_STATE);
  2533. }
  2534. }
  2535. if (ret == 0) {
  2536. args->length = CURVE448_KEY_SIZE;
  2537. if (args->length > *sslBytes) {
  2538. SetError(PARTIAL_INPUT_STR, error, session,
  2539. FATAL_ERROR_STATE);
  2540. ret = -1;
  2541. }
  2542. }
  2543. if (ret == 0) {
  2544. ret = wc_curve448_init(&args->key->pub.x448);
  2545. if (ret == 0)
  2546. args->key->initPub = 1;
  2547. }
  2548. if (ret == 0) {
  2549. ret = wc_curve448_import_public_ex(input, args->length,
  2550. &args->key->pub.x448, EC448_LITTLE_ENDIAN);
  2551. if (ret != 0) {
  2552. SetError(ECC_PUB_DECODE_STR, error, session,
  2553. FATAL_ERROR_STATE);
  2554. }
  2555. }
  2556. if (ret == 0) {
  2557. session->keySz = CURVE448_KEY_SIZE;
  2558. session->sslServer->arrays->preMasterSz = ENCRYPT_LEN;
  2559. }
  2560. }
  2561. #endif /* HAVE_CURVE448 */
  2562. #if defined(WOLFSSL_STATIC_EPHEMERAL) && !defined(SINGLE_THREADED)
  2563. if (args->keyLocked) {
  2564. wc_UnLockMutex(&ctx->staticKELock);
  2565. }
  2566. #endif
  2567. /* make sure a key type was found */
  2568. if (args->key->type == WC_PK_TYPE_NONE) {
  2569. ret = NOT_COMPILED_IN;
  2570. }
  2571. /* check for errors before moving to next state */
  2572. if (ret < 0) {
  2573. break;
  2574. }
  2575. /* Advance state and proceed */
  2576. ssl->options.asyncState = TLS_ASYNC_DO;
  2577. } /* case TLS_ASYNC_BEGIN */
  2578. FALL_THROUGH;
  2579. case TLS_ASYNC_DO:
  2580. {
  2581. #ifdef WOLFSSL_ASYNC_CRYPT
  2582. WC_ASYNC_DEV* asyncDev = NULL;
  2583. #endif
  2584. #ifndef NO_RSA
  2585. if (args->key->type == WC_PK_TYPE_RSA) {
  2586. ret = wc_RsaPrivateDecrypt(input, args->length,
  2587. session->sslServer->arrays->preMasterSecret,
  2588. session->sslServer->arrays->preMasterSz,
  2589. &args->key->priv.rsa);
  2590. #ifdef WOLFSSL_ASYNC_CRYPT
  2591. asyncDev = &args->key->priv.rsa.asyncDev;
  2592. #endif
  2593. }
  2594. #endif /* !NO_RSA */
  2595. #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)
  2596. if (args->key->type == WC_PK_TYPE_DH) {
  2597. /* Derive secret from private key and peer's public key */
  2598. ret = wc_DhAgree(&args->key->priv.dh.key,
  2599. session->sslServer->arrays->preMasterSecret,
  2600. &session->sslServer->arrays->preMasterSz,
  2601. args->key->priv.dh.privKey, args->key->priv.dh.privKeySz,
  2602. input, *sslBytes);
  2603. #ifdef WOLFSSL_ASYNC_CRYPT
  2604. asyncDev = &args->key->priv.dh.key.asyncDev;
  2605. #endif
  2606. }
  2607. #endif /* !NO_DH && WOLFSSL_DH_EXTRA */
  2608. #ifdef HAVE_ECC
  2609. if (args->key->type == WC_PK_TYPE_ECDH) {
  2610. ret = wc_ecc_shared_secret(&args->key->priv.ecc,
  2611. &args->key->pub.ecc,
  2612. session->sslServer->arrays->preMasterSecret,
  2613. &session->sslServer->arrays->preMasterSz);
  2614. #ifdef WOLFSSL_ASYNC_CRYPT
  2615. asyncDev = &args->key->priv.ecc.asyncDev;
  2616. #endif
  2617. }
  2618. #endif /* HAVE_ECC */
  2619. #ifdef HAVE_CURVE25519
  2620. if (args->key->type == WC_PK_TYPE_CURVE25519) {
  2621. ret = wc_curve25519_shared_secret_ex(&args->key->priv.x25519,
  2622. &args->key->pub.x25519,
  2623. session->sslServer->arrays->preMasterSecret,
  2624. &session->sslServer->arrays->preMasterSz,
  2625. EC25519_LITTLE_ENDIAN);
  2626. #ifdef WOLFSSL_ASYNC_CRYPT
  2627. asyncDev = &args->key->priv.x25519.asyncDev;
  2628. #endif
  2629. }
  2630. #endif /* HAVE_CURVE25519 */
  2631. #ifdef HAVE_CURVE448
  2632. if (args->key->type == WC_PK_TYPE_CURVE448) {
  2633. ret = wc_curve448_shared_secret_ex(&args->key->priv.x448,
  2634. &args->key->pub.x448,
  2635. session->sslServer->arrays->preMasterSecret,
  2636. &session->sslServer->arrays->preMasterSz, EC448_LITTLE_ENDIAN);
  2637. #ifdef WOLFSSL_ASYNC_CRYPT
  2638. asyncDev = &args->key->priv.x448.asyncDev;
  2639. #endif
  2640. }
  2641. #endif /* HAVE_CURVE448 */
  2642. #ifdef WOLFSSL_ASYNC_CRYPT
  2643. if (ret == WC_PENDING_E) {
  2644. /* Handle async pending response */
  2645. ret = wolfSSL_AsyncPush(ssl, asyncDev);
  2646. break;
  2647. }
  2648. #endif /* WOLFSSL_ASYNC_CRYPT */
  2649. /* check for errors before moving to next state */
  2650. if (ret < 0) {
  2651. break;
  2652. }
  2653. /* Advance state and proceed */
  2654. ssl->options.asyncState = TLS_ASYNC_VERIFY;
  2655. } /* case TLS_ASYNC_DO */
  2656. FALL_THROUGH;
  2657. case TLS_ASYNC_VERIFY:
  2658. {
  2659. #ifndef NO_RSA
  2660. if (args->key->type == WC_PK_TYPE_RSA) {
  2661. if (ret != SECRET_LEN) {
  2662. SetError(RSA_DECRYPT_STR, error, session, FATAL_ERROR_STATE);
  2663. ret = RSA_BUFFER_E;
  2664. }
  2665. }
  2666. #endif /* !NO_RSA */
  2667. #if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)
  2668. if (args->key->type == WC_PK_TYPE_DH) {
  2669. /* left-padded with zeros up to the size of the prime */
  2670. if (args->key->priv.dh.pLen >
  2671. session->sslServer->arrays->preMasterSz) {
  2672. word32 diff = args->key->priv.dh.pLen -
  2673. session->sslServer->arrays->preMasterSz;
  2674. XMEMMOVE(session->sslServer->arrays->preMasterSecret + diff,
  2675. session->sslServer->arrays->preMasterSecret,
  2676. session->sslServer->arrays->preMasterSz);
  2677. XMEMSET(session->sslServer->arrays->preMasterSecret, 0, diff);
  2678. session->sslServer->arrays->preMasterSz=args->key->priv.dh.pLen;
  2679. }
  2680. }
  2681. #endif /* !NO_DH && WOLFSSL_DH_EXTRA */
  2682. /* check for errors before moving to next state */
  2683. if (ret < 0) {
  2684. break;
  2685. }
  2686. /* Advance state and proceed */
  2687. ssl->options.asyncState = TLS_ASYNC_FINALIZE;
  2688. } /* case TLS_ASYNC_VERIFY */
  2689. FALL_THROUGH;
  2690. case TLS_ASYNC_FINALIZE:
  2691. {
  2692. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  2693. if (!session->context->useKeyLogFile)
  2694. #endif /* !WOLFSSL_SNIFFER_KEYLOGFILE */
  2695. {
  2696. /* store for client side as well */
  2697. XMEMCPY(session->sslClient->arrays->preMasterSecret,
  2698. session->sslServer->arrays->preMasterSecret,
  2699. session->sslServer->arrays->preMasterSz);
  2700. session->sslClient->arrays->preMasterSz =
  2701. session->sslServer->arrays->preMasterSz;
  2702. }
  2703. #ifdef SHOW_SECRETS
  2704. PrintSecret("pre master secret",
  2705. session->sslServer->arrays->preMasterSecret,
  2706. session->sslServer->arrays->preMasterSz);
  2707. #endif
  2708. if (SetCipherSpecs(session->sslServer) != 0) {
  2709. SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
  2710. session->verboseErr = 1;
  2711. ret = -1; break;
  2712. }
  2713. if (SetCipherSpecs(session->sslClient) != 0) {
  2714. SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
  2715. session->verboseErr = 1;
  2716. ret = -1; break;
  2717. }
  2718. #ifdef WOLFSSL_TLS13
  2719. /* TLS v1.3 derive handshake key */
  2720. if (IsAtLeastTLSv1_3(session->sslServer->version)) {
  2721. ret = DeriveEarlySecret(session->sslServer);
  2722. ret += DeriveEarlySecret(session->sslClient);
  2723. ret += DeriveHandshakeSecret(session->sslServer);
  2724. ret += DeriveHandshakeSecret(session->sslClient);
  2725. ret += DeriveTls13Keys(session->sslServer, handshake_key,
  2726. ENCRYPT_AND_DECRYPT_SIDE, 1);
  2727. ret += DeriveTls13Keys(session->sslClient, handshake_key,
  2728. ENCRYPT_AND_DECRYPT_SIDE, 1);
  2729. #ifdef WOLFSSL_EARLY_DATA
  2730. ret += SetKeysSide(session->sslServer, DECRYPT_SIDE_ONLY);
  2731. ret += SetKeysSide(session->sslClient, DECRYPT_SIDE_ONLY);
  2732. #else
  2733. ret += SetKeysSide(session->sslServer, ENCRYPT_AND_DECRYPT_SIDE);
  2734. ret += SetKeysSide(session->sslClient, ENCRYPT_AND_DECRYPT_SIDE);
  2735. #endif
  2736. }
  2737. else
  2738. #endif /* WOLFSSL_TLS13 */
  2739. {
  2740. ret = MakeMasterSecret(session->sslServer);
  2741. ret += MakeMasterSecret(session->sslClient);
  2742. ret += SetKeysSide(session->sslServer, ENCRYPT_AND_DECRYPT_SIDE);
  2743. ret += SetKeysSide(session->sslClient, ENCRYPT_AND_DECRYPT_SIDE);
  2744. }
  2745. if (ret != 0) {
  2746. SetError(BAD_DERIVE_STR, error, session, FATAL_ERROR_STATE);
  2747. ret = -1; break;
  2748. }
  2749. #ifdef SHOW_SECRETS
  2750. #ifdef WOLFSSL_TLS13
  2751. if (!IsAtLeastTLSv1_3(session->sslServer->version))
  2752. #endif
  2753. {
  2754. ShowTlsSecrets(session);
  2755. }
  2756. #endif
  2757. CallConnectionCb(session);
  2758. break;
  2759. } /* case TLS_ASYNC_FINALIZE */
  2760. default:
  2761. ret = INPUT_CASE_ERROR;
  2762. } /* switch(ssl->options.asyncState) */
  2763. #ifdef WOLFSSL_ASYNC_CRYPT
  2764. exit_sk:
  2765. /* Handle async pending response */
  2766. if (ret == WC_PENDING_E) {
  2767. return ret;
  2768. }
  2769. #endif /* WOLFSSL_ASYNC_CRYPT */
  2770. #ifdef WOLFSSL_SNIFFER_STATS
  2771. if (ret < 0)
  2772. INC_STAT(SnifferStats.sslKeyFails);
  2773. #endif
  2774. /* Final cleanup */
  2775. #ifdef WOLFSSL_ASYNC_CRYPT
  2776. FreeAsyncCtx(ssl, 1);
  2777. #else
  2778. FreeSetupKeysArgs(ssl, args);
  2779. #endif
  2780. #ifndef WOLFSSL_STATIC_EPHEMERAL
  2781. (void)ctx;
  2782. #endif
  2783. return ret;
  2784. }
  2785. /* Process Client Key Exchange */
  2786. static int ProcessClientKeyExchange(const byte* input, int* sslBytes,
  2787. SnifferSession* session, char* error)
  2788. {
  2789. int ret;
  2790. #ifndef WOLFSSL_STATIC_EPHEMERAL
  2791. if (session->sslServer->buffers.key == NULL ||
  2792. session->sslServer->buffers.key->buffer == NULL ||
  2793. session->sslServer->buffers.key->length == 0) {
  2794. SetError(RSA_KEY_MISSING_STR, error, session, FATAL_ERROR_STATE);
  2795. return -1;
  2796. }
  2797. #endif
  2798. ret = SetupKeys(input, sslBytes, session, error, NULL);
  2799. return ret;
  2800. }
  2801. #ifdef WOLFSSL_TLS13
  2802. static int ProcessKeyShare(KeyShareInfo* info, const byte* input, int len,
  2803. word16 filter_group)
  2804. {
  2805. int index = 0;
  2806. while (index < len) {
  2807. /* clear info (reset dh_key_bits and curve_id) */
  2808. XMEMSET(info, 0, sizeof(KeyShareInfo));
  2809. /* Named group and public key */
  2810. info->named_group = (word16)((input[index] << 8) | input[index+1]);
  2811. index += OPAQUE16_LEN;
  2812. info->key_len = 0;
  2813. info->key = NULL;
  2814. /* If key was provided... (a hello_retry_request will not send a key) */
  2815. if (index + 2 <= len) {
  2816. info->key_len = (word16)((input[index] << 8) | input[index+1]);
  2817. index += OPAQUE16_LEN;
  2818. if (info->key_len == 0 || info->key_len > len - index) {
  2819. return -1;
  2820. }
  2821. info->key = &input[index];
  2822. index += info->key_len;
  2823. }
  2824. switch (info->named_group) {
  2825. #ifndef NO_DH
  2826. #ifdef HAVE_FFDHE_2048
  2827. case WOLFSSL_FFDHE_2048:
  2828. info->dh_key_bits = 2048;
  2829. break;
  2830. #endif
  2831. #ifdef HAVE_FFDHE_3072
  2832. case WOLFSSL_FFDHE_3072:
  2833. info->dh_key_bits = 3072;
  2834. break;
  2835. #endif
  2836. #ifdef HAVE_FFDHE_4096
  2837. case WOLFSSL_FFDHE_4096:
  2838. info->dh_key_bits = 4096;
  2839. break;
  2840. #endif
  2841. #ifdef HAVE_FFDHE_6144
  2842. case WOLFSSL_FFDHE_6144:
  2843. info->dh_key_bits = 6144;
  2844. break;
  2845. #endif
  2846. #ifdef HAVE_FFDHE_8192
  2847. case WOLFSSL_FFDHE_8192:
  2848. info->dh_key_bits = 8192;
  2849. break;
  2850. #endif
  2851. #endif /* !NO_DH */
  2852. #ifdef HAVE_ECC
  2853. #if !defined(NO_ECC256) || defined(HAVE_ALL_CURVES)
  2854. #ifndef NO_ECC_SECP
  2855. case WOLFSSL_ECC_SECP256R1:
  2856. info->curve_id = ECC_SECP256R1;
  2857. break;
  2858. #endif /* !NO_ECC_SECP */
  2859. #ifdef WOLFSSL_SM2
  2860. case WOLFSSL_ECC_SM2P256V1:
  2861. info->curve_id = ECC_SM2P256V1;
  2862. break;
  2863. #endif /* WOLFSSL_SM2 */
  2864. #endif
  2865. #if defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)
  2866. #ifndef NO_ECC_SECP
  2867. case WOLFSSL_ECC_SECP384R1:
  2868. info->curve_id = ECC_SECP384R1;
  2869. break;
  2870. #endif /* !NO_ECC_SECP */
  2871. #endif
  2872. #if defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)
  2873. #ifndef NO_ECC_SECP
  2874. case WOLFSSL_ECC_SECP521R1:
  2875. info->curve_id = ECC_SECP521R1;
  2876. break;
  2877. #endif /* !NO_ECC_SECP */
  2878. #endif
  2879. #endif /* HAVE_ECC */
  2880. #ifdef HAVE_CURVE25519
  2881. case WOLFSSL_ECC_X25519:
  2882. info->curve_id = ECC_X25519;
  2883. break;
  2884. #endif
  2885. #ifdef HAVE_CURVE448
  2886. case WOLFSSL_ECC_X448:
  2887. info->curve_id = ECC_X448;
  2888. break;
  2889. #endif
  2890. default:
  2891. /* do not throw error here, keep iterating the client key share */
  2892. break;
  2893. }
  2894. if (filter_group == 0 || filter_group == info->named_group) {
  2895. return 0;
  2896. }
  2897. }
  2898. return NO_PEER_KEY; /* unsupported key type */
  2899. }
  2900. static int ProcessServerKeyShare(SnifferSession* session, const byte* input, int len,
  2901. char* error)
  2902. {
  2903. int ret;
  2904. if (session->cliKeyShare == NULL || session->cliKeyShareSz == 0) {
  2905. /* session->cliKeyShareSz could not be provided yet if the client_hello
  2906. did not send a key share to force a hello_retry_request */
  2907. return 0;
  2908. }
  2909. /* Get server_hello key share (and key) */
  2910. ret = ProcessKeyShare(&session->srvKs, input, len, 0);
  2911. if (ret == 0 && session->srvKs.key_len > 0) {
  2912. /* Get client_hello key share */
  2913. ret = ProcessKeyShare(&session->cliKs, session->cliKeyShare,
  2914. session->cliKeyShareSz, session->srvKs.named_group);
  2915. }
  2916. if (ret != 0) {
  2917. SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2918. return -1;
  2919. }
  2920. return ret;
  2921. }
  2922. #endif /* WOLFSSL_TLS13 */
  2923. /* Process Session Ticket */
  2924. static int ProcessSessionTicket(const byte* input, int* sslBytes,
  2925. SnifferSession* session, char* error)
  2926. {
  2927. word16 len;
  2928. #ifdef WOLFSSL_TLS13
  2929. WOLFSSL* ssl;
  2930. if (session->flags.side == WOLFSSL_SERVER_END)
  2931. ssl = session->sslServer;
  2932. else
  2933. ssl = session->sslClient;
  2934. #endif
  2935. /* make sure can read through hint len */
  2936. if (TICKET_HINT_LEN > *sslBytes) {
  2937. SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2938. return -1;
  2939. }
  2940. input += TICKET_HINT_LEN; /* skip over hint len */
  2941. *sslBytes -= TICKET_HINT_LEN;
  2942. #ifdef WOLFSSL_TLS13
  2943. /* TLS v1.3 has hint age and nonce */
  2944. if (IsAtLeastTLSv1_3(ssl->version)) {
  2945. /* make sure can read through hint age and nonce len */
  2946. if (TICKET_HINT_AGE_LEN + 1 > *sslBytes) {
  2947. SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2948. return -1;
  2949. }
  2950. input += TICKET_HINT_AGE_LEN; /* skip over hint age */
  2951. *sslBytes -= TICKET_HINT_AGE_LEN;
  2952. /* ticket nonce */
  2953. len = input[0];
  2954. if (len > MAX_TICKET_NONCE_STATIC_SZ) {
  2955. SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2956. return -1;
  2957. }
  2958. input += OPAQUE8_LEN;
  2959. *sslBytes -= OPAQUE8_LEN;
  2960. #ifdef HAVE_SESSION_TICKET
  2961. /* store nonce in server for DeriveResumptionPSK */
  2962. session->sslServer->session->ticketNonce.len = len;
  2963. if (len > 0)
  2964. XMEMCPY(session->sslServer->session->ticketNonce.data, input, len);
  2965. #endif
  2966. input += len;
  2967. *sslBytes -= len;
  2968. }
  2969. #endif
  2970. /* make sure can read through len */
  2971. if (OPAQUE16_LEN > *sslBytes) {
  2972. SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2973. return -1;
  2974. }
  2975. len = (word16)((input[0] << 8) | input[1]);
  2976. input += OPAQUE16_LEN;
  2977. *sslBytes -= OPAQUE16_LEN;
  2978. /* make sure can read through ticket */
  2979. if (len > *sslBytes) {
  2980. SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2981. return -1;
  2982. }
  2983. #ifdef WOLFSSL_TLS13
  2984. /* TLS v1.3 has hint age and nonce */
  2985. if (IsAtLeastTLSv1_3(ssl->version)) {
  2986. /* Note: Must use server session for sessions */
  2987. #ifdef HAVE_SESSION_TICKET
  2988. if (SetTicket(session->sslServer, input, len) != 0) {
  2989. SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2990. return -1;
  2991. }
  2992. /* set haveSessionId to use the wolfSession cache */
  2993. session->sslServer->options.haveSessionId = 1;
  2994. /* Use the wolf Session cache to retain resumption secret */
  2995. if (session->flags.cached == 0) {
  2996. WOLFSSL_SESSION* sess = wolfSSL_GetSession(session->sslServer,
  2997. NULL, 0);
  2998. if (sess == NULL) {
  2999. SetupSession(session->sslServer);
  3000. AddSession(session->sslServer); /* don't re add */
  3001. #ifdef WOLFSSL_SNIFFER_STATS
  3002. INC_STAT(SnifferStats.sslResumptionInserts);
  3003. #endif
  3004. }
  3005. session->flags.cached = 1;
  3006. }
  3007. #endif /* HAVE_SESSION_TICKET */
  3008. }
  3009. else
  3010. #endif /* WOLFSSL_TLS13 */
  3011. {
  3012. /* capture last part of sessionID as macID (32 bytes) */
  3013. if (len < ID_LEN) {
  3014. SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3015. return -1;
  3016. }
  3017. /* store session with macID as sessionID */
  3018. session->sslServer->options.haveSessionId = 1;
  3019. if (session->sslServer->arrays) {
  3020. XMEMCPY(session->sslServer->arrays->sessionID,
  3021. input + len - ID_LEN, ID_LEN);
  3022. session->sslServer->arrays->sessionIDSz = ID_LEN;
  3023. }
  3024. }
  3025. return 0;
  3026. }
  3027. static int DoResume(SnifferSession* session, char* error)
  3028. {
  3029. int ret = 0;
  3030. WOLFSSL_SESSION* resume;
  3031. #ifdef WOLFSSL_TLS13
  3032. if (IsAtLeastTLSv1_3(session->sslServer->version)) {
  3033. resume = wolfSSL_GetSession(session->sslServer,
  3034. session->sslServer->session->masterSecret, 0);
  3035. if (resume == NULL) {
  3036. /* TLS v1.3 with hello_retry uses session_id even for new session,
  3037. so ignore error here */
  3038. return 0;
  3039. }
  3040. }
  3041. else
  3042. #endif
  3043. {
  3044. #ifdef HAVE_SESSION_TICKET
  3045. /* make sure "useTicket" is not set, otherwise the session will not be
  3046. * properly retrieved */
  3047. session->sslServer->options.useTicket = 0;
  3048. #endif
  3049. resume = wolfSSL_GetSession(session->sslServer,
  3050. session->sslServer->arrays->masterSecret, 0);
  3051. if (resume == NULL) {
  3052. #ifdef WOLFSSL_SNIFFER_STATS
  3053. INC_STAT(SnifferStats.sslResumeMisses);
  3054. #endif
  3055. SetError(BAD_SESSION_RESUME_STR, error, session, FATAL_ERROR_STATE);
  3056. return -1;
  3057. }
  3058. }
  3059. /* make sure client has master secret too */
  3060. #ifdef WOLFSSL_TLS13
  3061. if (IsAtLeastTLSv1_3(session->sslServer->version)) {
  3062. XMEMCPY(session->sslClient->session->masterSecret,
  3063. session->sslServer->session->masterSecret, SECRET_LEN);
  3064. }
  3065. else
  3066. #endif
  3067. {
  3068. XMEMCPY(session->sslClient->arrays->masterSecret,
  3069. session->sslServer->arrays->masterSecret, SECRET_LEN);
  3070. }
  3071. session->flags.resuming = 1;
  3072. Trace(SERVER_DID_RESUMPTION_STR);
  3073. #ifdef WOLFSSL_SNIFFER_STATS
  3074. INC_STAT(SnifferStats.sslResumedConns);
  3075. #endif
  3076. if (SetCipherSpecs(session->sslServer) != 0) {
  3077. SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
  3078. session->verboseErr = 1;
  3079. return -1;
  3080. }
  3081. if (SetCipherSpecs(session->sslClient) != 0) {
  3082. SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
  3083. session->verboseErr = 1;
  3084. return -1;
  3085. }
  3086. #ifdef WOLFSSL_TLS13
  3087. if (IsAtLeastTLSv1_3(session->sslServer->version)) {
  3088. #ifdef HAVE_SESSION_TICKET
  3089. /* Resumption PSK is resumption master secret. */
  3090. session->sslServer->arrays->psk_keySz = session->sslServer->specs.hash_size;
  3091. session->sslClient->arrays->psk_keySz = session->sslClient->specs.hash_size;
  3092. ret = DeriveResumptionPSK(session->sslServer,
  3093. session->sslServer->session->ticketNonce.data,
  3094. session->sslServer->session->ticketNonce.len,
  3095. session->sslServer->arrays->psk_key);
  3096. /* Copy resumption PSK to client */
  3097. XMEMCPY(session->sslClient->arrays->psk_key,
  3098. session->sslServer->arrays->psk_key,
  3099. session->sslServer->arrays->psk_keySz);
  3100. #endif
  3101. /* handshake key setup below and traffic keys done in SetupKeys */
  3102. }
  3103. else
  3104. #endif
  3105. {
  3106. if (IsTLS(session->sslServer)) {
  3107. ret = DeriveTlsKeys(session->sslServer);
  3108. ret += DeriveTlsKeys(session->sslClient);
  3109. }
  3110. else {
  3111. #ifndef NO_OLD_TLS
  3112. ret = DeriveKeys(session->sslServer);
  3113. ret += DeriveKeys(session->sslClient);
  3114. #endif
  3115. }
  3116. ret += SetKeysSide(session->sslServer, ENCRYPT_AND_DECRYPT_SIDE);
  3117. ret += SetKeysSide(session->sslClient, ENCRYPT_AND_DECRYPT_SIDE);
  3118. }
  3119. if (ret != 0) {
  3120. SetError(BAD_DERIVE_STR, error, session, FATAL_ERROR_STATE);
  3121. return -1;
  3122. }
  3123. return ret;
  3124. }
  3125. /* Process Server Hello */
  3126. static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes,
  3127. SnifferSession* session, char* error)
  3128. {
  3129. int ret = 0;
  3130. ProtocolVersion pv;
  3131. byte b, b0;
  3132. int toRead = VERSION_SZ + RAN_LEN + ENUM_LEN;
  3133. int doResume = 0;
  3134. const byte* inputHello = input;
  3135. int initialBytes = *sslBytes;
  3136. (void)msgSz;
  3137. /* make sure we didn't miss ClientHello */
  3138. if (session->flags.clientHello == 0 || session->sslClient->arrays == NULL) {
  3139. SetError(MISSED_CLIENT_HELLO_STR, error, session, 0);
  3140. return 0; /* do not throw error, just ignore packet */
  3141. }
  3142. /* make sure can read through session len */
  3143. if (toRead > *sslBytes) {
  3144. SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3145. return -1;
  3146. }
  3147. XMEMCPY(&pv, input, VERSION_SZ);
  3148. input += VERSION_SZ;
  3149. *sslBytes -= VERSION_SZ;
  3150. session->sslServer->version = pv;
  3151. session->sslClient->version = pv;
  3152. if (pv.minor >= TLSv1_MINOR) {
  3153. session->sslServer->options.tls = 1;
  3154. session->sslClient->options.tls = 1;
  3155. }
  3156. XMEMCPY(session->sslServer->arrays->serverRandom, input, RAN_LEN);
  3157. XMEMCPY(session->sslClient->arrays->serverRandom, input, RAN_LEN);
  3158. input += RAN_LEN;
  3159. *sslBytes -= RAN_LEN;
  3160. b = *input++;
  3161. *sslBytes -= 1;
  3162. /* make sure can read through compression */
  3163. if ( (b + SUITE_LEN + ENUM_LEN) > *sslBytes) {
  3164. SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3165. return -1;
  3166. }
  3167. if (b) {
  3168. #ifdef WOLFSSL_TLS13
  3169. XMEMCPY(session->sslServer->session->sessionID, input, ID_LEN);
  3170. session->sslServer->session->sessionIDSz = ID_LEN;
  3171. #endif
  3172. XMEMCPY(session->sslServer->arrays->sessionID, input, ID_LEN);
  3173. session->sslServer->arrays->sessionIDSz = ID_LEN;
  3174. session->sslServer->options.haveSessionId = 1;
  3175. }
  3176. input += b;
  3177. *sslBytes -= b;
  3178. /* cipher suite */
  3179. b0 = *input++; /* first byte, ECC or not */
  3180. session->sslServer->options.cipherSuite0 = b0;
  3181. session->sslClient->options.cipherSuite0 = b0;
  3182. b = *input++;
  3183. session->sslServer->options.cipherSuite = b;
  3184. session->sslClient->options.cipherSuite = b;
  3185. *sslBytes -= SUITE_LEN;
  3186. #ifdef WOLFSSL_SNIFFER_STATS
  3187. {
  3188. const CipherSuiteInfo* suites = GetCipherNames();
  3189. int suitesSz = GetCipherNamesSize();
  3190. int match = 0;
  3191. while (suitesSz) {
  3192. if (b0 == suites->cipherSuite0 && b == suites->cipherSuite) {
  3193. match = 1;
  3194. break;
  3195. }
  3196. suites++;
  3197. suitesSz--;
  3198. }
  3199. if (!match)
  3200. INC_STAT(SnifferStats.sslCiphersUnsupported);
  3201. }
  3202. #endif /* WOLFSSL_SNIFFER_STATS */
  3203. /* compression */
  3204. b = *input++;
  3205. *sslBytes -= ENUM_LEN;
  3206. if (b) {
  3207. SetError(BAD_COMPRESSION_STR, error, session, FATAL_ERROR_STATE);
  3208. return -1;
  3209. }
  3210. /* extensions */
  3211. if ((initialBytes - *sslBytes) < msgSz) {
  3212. word16 len;
  3213. /* skip extensions until extended master secret */
  3214. /* make sure can read len */
  3215. if (SUITE_LEN > *sslBytes) {
  3216. SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3217. return -1;
  3218. }
  3219. len = (word16)((input[0] << 8) | input[1]);
  3220. input += SUITE_LEN;
  3221. *sslBytes -= SUITE_LEN;
  3222. /* make sure can read through all extensions */
  3223. if (len > *sslBytes) {
  3224. SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3225. return -1;
  3226. }
  3227. while (len >= EXT_TYPE_SZ + LENGTH_SZ) {
  3228. word16 extType;
  3229. word16 extLen;
  3230. extType = (word16)((input[0] << 8) | input[1]);
  3231. input += EXT_TYPE_SZ;
  3232. *sslBytes -= EXT_TYPE_SZ;
  3233. extLen = (word16)((input[0] << 8) | input[1]);
  3234. input += LENGTH_SZ;
  3235. *sslBytes -= LENGTH_SZ;
  3236. /* make sure can read through individual extension */
  3237. if (extLen > *sslBytes) {
  3238. SetError(SERVER_HELLO_INPUT_STR, error, session,
  3239. FATAL_ERROR_STATE);
  3240. return -1;
  3241. }
  3242. #ifdef DEBUG_SNIFFER
  3243. printf("\tserver_hello ext: 0x%02x (len %d)\n", extType, extLen);
  3244. #endif
  3245. switch (extType) {
  3246. #ifdef WOLFSSL_TLS13
  3247. case EXT_KEY_SHARE:
  3248. ret = ProcessServerKeyShare(session, input, extLen, error);
  3249. if (ret != 0) {
  3250. SetError(SERVER_HELLO_INPUT_STR, error, session,
  3251. FATAL_ERROR_STATE);
  3252. return -1;
  3253. }
  3254. break;
  3255. #endif
  3256. #ifdef HAVE_SESSION_TICKET
  3257. case EXT_PRE_SHARED_KEY:
  3258. /* indicates we want to use resumption */
  3259. session->sslServer->options.resuming = 1;
  3260. session->sslClient->options.resuming = 1;
  3261. #ifdef WOLFSSL_TLS13
  3262. /* default nonce to len = 1, data = 0 */
  3263. session->sslServer->session->ticketNonce.len = 1;
  3264. session->sslServer->session->ticketNonce.data[0] = 0;
  3265. session->sslClient->session->ticketNonce.len = 1;
  3266. session->sslClient->session->ticketNonce.data[0] = 0;
  3267. #endif
  3268. break;
  3269. #endif
  3270. #ifdef HAVE_MAX_FRAGMENT
  3271. case EXT_MAX_FRAGMENT_LENGTH:
  3272. {
  3273. word16 max_fragment = MAX_RECORD_SIZE;
  3274. switch (input[0]) {
  3275. case WOLFSSL_MFL_2_8 : max_fragment = 256; break;
  3276. case WOLFSSL_MFL_2_9 : max_fragment = 512; break;
  3277. case WOLFSSL_MFL_2_10: max_fragment = 1024; break;
  3278. case WOLFSSL_MFL_2_11: max_fragment = 2048; break;
  3279. case WOLFSSL_MFL_2_12: max_fragment = 4096; break;
  3280. case WOLFSSL_MFL_2_13: max_fragment = 8192; break;
  3281. default: break;
  3282. }
  3283. session->sslServer->max_fragment = max_fragment;
  3284. session->sslClient->max_fragment = max_fragment;
  3285. break;
  3286. }
  3287. #endif
  3288. case EXT_SUPPORTED_VERSIONS:
  3289. session->sslServer->version.major = input[0];
  3290. session->sslServer->version.minor = input[1];
  3291. session->sslClient->version.major = input[0];
  3292. session->sslClient->version.minor = input[1];
  3293. if (IsAtLeastTLSv1_3(session->sslServer->version)) {
  3294. /* The server side handshake encryption is on for future packets */
  3295. session->flags.serverCipherOn = 1;
  3296. }
  3297. break;
  3298. case EXT_MASTER_SECRET:
  3299. #ifdef HAVE_EXTENDED_MASTER
  3300. session->flags.expectEms = 1;
  3301. #endif
  3302. break;
  3303. case EXT_RENEGOTIATION_INFO:
  3304. session->flags.secRenegEn = 1;
  3305. break;
  3306. } /* switch (extType) */
  3307. input += extLen;
  3308. *sslBytes -= extLen;
  3309. len -= extLen + EXT_TYPE_SZ + LENGTH_SZ;
  3310. }
  3311. }
  3312. if (IsAtLeastTLSv1_3(session->sslServer->version)) {
  3313. #ifndef WOLFSSL_TLS13
  3314. SetError(UNSUPPORTED_TLS_VER_STR, error, session, FATAL_ERROR_STATE);
  3315. session->verboseErr = 1;
  3316. return -1;
  3317. #endif
  3318. }
  3319. else {
  3320. #ifdef WOLFSSL_NO_TLS12
  3321. SetError(UNSUPPORTED_TLS_VER_STR, error, session, FATAL_ERROR_STATE);
  3322. session->verboseErr = 1;
  3323. return -1;
  3324. #endif
  3325. }
  3326. #ifdef HAVE_EXTENDED_MASTER
  3327. if (!session->flags.expectEms) {
  3328. XFREE(session->hash, NULL, DYNAMIC_TYPE_HASHES);
  3329. session->hash = NULL;
  3330. }
  3331. #endif
  3332. if (session->sslServer->options.haveSessionId) {
  3333. if (XMEMCMP(session->sslServer->arrays->sessionID,
  3334. session->sslClient->arrays->sessionID, ID_LEN) == 0) {
  3335. doResume = 1;
  3336. }
  3337. }
  3338. else if (session->sslClient->options.haveSessionId == 0 &&
  3339. session->sslServer->options.haveSessionId == 0 &&
  3340. session->ticketID) {
  3341. doResume = 1;
  3342. }
  3343. if (session->ticketID && doResume) {
  3344. /* use ticketID to retrieve from session, prefer over sessionID */
  3345. XMEMCPY(session->sslServer->arrays->sessionID,session->ticketID,ID_LEN);
  3346. session->sslServer->arrays->sessionIDSz = ID_LEN;
  3347. session->sslServer->options.haveSessionId = 1; /* may not have
  3348. actual sessionID */
  3349. }
  3350. #ifdef WOLFSSL_TLS13
  3351. /* Is TLS v1.3 hello_retry_request? */
  3352. if (IsAtLeastTLSv1_3(session->sslServer->version) && session->srvKs.key_len == 0) {
  3353. Trace(GOT_HELLO_RETRY_REQ_STR);
  3354. /* do not compute keys yet */
  3355. session->flags.serverCipherOn = 0;
  3356. /* make sure the mac and digest size are set */
  3357. SetCipherSpecs(session->sslServer);
  3358. SetCipherSpecs(session->sslClient);
  3359. /* reset hashes */
  3360. RestartHandshakeHash(session->sslServer);
  3361. RestartHandshakeHash(session->sslClient);
  3362. doResume = 0;
  3363. }
  3364. #endif
  3365. #ifdef WOLFSSL_ASYNC_CRYPT
  3366. if (session->sslServer->error != WC_PENDING_E && session->pendSeq == 0)
  3367. #endif
  3368. {
  3369. /* hash server_hello */
  3370. HashRaw(session->sslServer, inputHello - HANDSHAKE_HEADER_SZ,
  3371. initialBytes + HANDSHAKE_HEADER_SZ);
  3372. HashRaw(session->sslClient, inputHello - HANDSHAKE_HEADER_SZ,
  3373. initialBytes + HANDSHAKE_HEADER_SZ);
  3374. }
  3375. if (doResume) {
  3376. ret = DoResume(session, error);
  3377. if (ret != 0) {
  3378. return ret;
  3379. }
  3380. }
  3381. else {
  3382. #ifdef WOLFSSL_SNIFFER_STATS
  3383. INC_STAT(SnifferStats.sslStandardConns);
  3384. #endif
  3385. }
  3386. #ifdef SHOW_SECRETS
  3387. printf("cipher suite = 0x%02x\n", session->sslServer->options.cipherSuite);
  3388. PrintSecret("server random", session->sslServer->arrays->serverRandom, RAN_LEN);
  3389. #endif
  3390. #ifdef WOLFSSL_TLS13
  3391. /* Setup handshake keys */
  3392. if (IsAtLeastTLSv1_3(session->sslServer->version) && session->srvKs.key_len > 0) {
  3393. ret = SetupKeys(session->cliKs.key, &session->cliKs.key_len,
  3394. session, error, &session->cliKs);
  3395. if (ret != 0) {
  3396. #ifdef WOLFSSL_ASYNC_CRYPT
  3397. if (ret == WC_PENDING_E) {
  3398. return ret;
  3399. }
  3400. #endif
  3401. SetError(KEY_MISMATCH_STR, error, session, FATAL_ERROR_STATE);
  3402. session->verboseErr = 1;
  3403. return ret;
  3404. }
  3405. if (session->flags.side == WOLFSSL_SERVER_END)
  3406. session->flags.serverCipherOn = 1;
  3407. else
  3408. session->flags.clientCipherOn = 1;
  3409. }
  3410. #endif
  3411. return 0;
  3412. }
  3413. #ifdef HAVE_SNI
  3414. /* Function return value must be 0 for success */
  3415. static int LoadNamedKey(SnifferSession* session, const byte* name, word16 nameSz)
  3416. {
  3417. int ret = 0;
  3418. WOLFSSL* ssl = session->sslServer;
  3419. NamedKey* namedKey;
  3420. wc_LockMutex(&session->context->namedKeysMutex);
  3421. namedKey = session->context->namedKeys;
  3422. while (namedKey != NULL) {
  3423. if (nameSz == namedKey->nameSz &&
  3424. XSTRNCMP((char*)name, namedKey->name, nameSz) == 0) {
  3425. #ifdef WOLFSSL_STATIC_EPHEMERAL
  3426. if (namedKey->isEphemeralKey) {
  3427. /* auto detect key type with WC_PK_TYPE_NONE */
  3428. ret = wolfSSL_set_ephemeral_key(ssl,
  3429. WC_PK_TYPE_NONE, (const char*)namedKey->key,
  3430. namedKey->keySz, WOLFSSL_FILETYPE_ASN1);
  3431. }
  3432. else
  3433. #endif
  3434. {
  3435. ret = wolfSSL_use_PrivateKey_buffer(ssl,
  3436. namedKey->key, namedKey->keySz,
  3437. WOLFSSL_FILETYPE_ASN1);
  3438. /* translate return code */
  3439. ret = (ret == WOLFSSL_SUCCESS) ? 0 : -1;
  3440. }
  3441. if (ret == 0) {
  3442. session->sni = namedKey->name;
  3443. }
  3444. break;
  3445. }
  3446. namedKey = namedKey->next;
  3447. }
  3448. wc_UnLockMutex(&session->context->namedKeysMutex);
  3449. return ret;
  3450. }
  3451. #endif
  3452. /* Process normal Client Hello */
  3453. static int ProcessClientHello(const byte* input, int* sslBytes,
  3454. SnifferSession* session, char* error)
  3455. {
  3456. int ret = 0;
  3457. byte bLen;
  3458. word16 len;
  3459. int toRead = VERSION_SZ + RAN_LEN + ENUM_LEN;
  3460. const byte* inputHello = input;
  3461. int inputHelloSz = *sslBytes;
  3462. WOLFSSL* ssl = session->sslServer;
  3463. int didHash = 0;
  3464. session->flags.clientHello = 1; /* don't process again */
  3465. /* make sure can read up to session len */
  3466. if (toRead > *sslBytes) {
  3467. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3468. return -1;
  3469. }
  3470. /* skip, get negotiated one from server hello */
  3471. input += VERSION_SZ;
  3472. *sslBytes -= VERSION_SZ;
  3473. /* for secure renegotiation server arrays can be NULL */
  3474. if (session->sslServer->arrays)
  3475. XMEMCPY(session->sslServer->arrays->clientRandom, input, RAN_LEN);
  3476. if (session->sslClient->arrays)
  3477. XMEMCPY(session->sslClient->arrays->clientRandom, input, RAN_LEN);
  3478. input += RAN_LEN;
  3479. *sslBytes -= RAN_LEN;
  3480. /* store session in case trying to resume */
  3481. bLen = *input++;
  3482. *sslBytes -= ENUM_LEN;
  3483. if (bLen) {
  3484. if (ID_LEN > *sslBytes) {
  3485. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3486. return -1;
  3487. }
  3488. Trace(CLIENT_RESUME_TRY_STR);
  3489. #ifdef WOLFSSL_TLS13
  3490. XMEMCPY(session->sslClient->session->sessionID, input, ID_LEN);
  3491. session->sslClient->session->sessionIDSz = ID_LEN;
  3492. #endif
  3493. if (session->sslClient->arrays) {
  3494. XMEMCPY(session->sslClient->arrays->sessionID, input, ID_LEN);
  3495. session->sslClient->arrays->sessionIDSz = ID_LEN;
  3496. }
  3497. session->sslClient->options.haveSessionId = 1;
  3498. }
  3499. #ifdef SHOW_SECRETS
  3500. if (ssl->arrays)
  3501. PrintSecret("client random", ssl->arrays->clientRandom, RAN_LEN);
  3502. #endif
  3503. input += bLen;
  3504. *sslBytes -= bLen;
  3505. /* skip cipher suites */
  3506. /* make sure can read len */
  3507. if (SUITE_LEN > *sslBytes) {
  3508. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3509. return -1;
  3510. }
  3511. len = (word16)((input[0] << 8) | input[1]);
  3512. input += SUITE_LEN;
  3513. *sslBytes -= SUITE_LEN;
  3514. /* make sure can read suites + comp len */
  3515. if (len + ENUM_LEN > *sslBytes) {
  3516. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3517. return -1;
  3518. }
  3519. input += len;
  3520. *sslBytes -= len;
  3521. /* skip compression */
  3522. bLen = *input++;
  3523. *sslBytes -= ENUM_LEN;
  3524. /* make sure can read len */
  3525. if (bLen > *sslBytes) {
  3526. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3527. return -1;
  3528. }
  3529. input += bLen;
  3530. *sslBytes -= bLen;
  3531. if (*sslBytes == 0) {
  3532. /* no extensions */
  3533. return 0;
  3534. }
  3535. /* skip extensions until session ticket */
  3536. /* make sure can read len */
  3537. if (SUITE_LEN > *sslBytes) {
  3538. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3539. return -1;
  3540. }
  3541. len = (word16)((input[0] << 8) | input[1]);
  3542. input += SUITE_LEN;
  3543. *sslBytes -= SUITE_LEN;
  3544. /* make sure can read through all extensions */
  3545. if (len > *sslBytes) {
  3546. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3547. return -1;
  3548. }
  3549. while (len >= EXT_TYPE_SZ + LENGTH_SZ) {
  3550. word16 extType;
  3551. word16 extLen;
  3552. extType = (word16)((input[0] << 8) | input[1]);
  3553. input += EXT_TYPE_SZ;
  3554. *sslBytes -= EXT_TYPE_SZ;
  3555. extLen = (word16)((input[0] << 8) | input[1]);
  3556. input += LENGTH_SZ;
  3557. *sslBytes -= LENGTH_SZ;
  3558. /* make sure can read through individual extension */
  3559. if (extLen > *sslBytes) {
  3560. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3561. return -1;
  3562. }
  3563. #ifdef DEBUG_SNIFFER
  3564. printf("\tclient_hello ext: 0x%02x (len %d)\n", extType, extLen);
  3565. #endif
  3566. switch (extType) {
  3567. #ifdef HAVE_SNI
  3568. case EXT_SERVER_NAME:
  3569. {
  3570. word16 listLen = 0, offset = 0;
  3571. ato16(input + offset, &listLen);
  3572. offset += OPAQUE16_LEN;
  3573. if (extLen < offset + listLen)
  3574. return BUFFER_ERROR;
  3575. while (listLen > ENUM_LEN + OPAQUE16_LEN) {
  3576. byte sniType = input[offset++];
  3577. word16 sniLen;
  3578. ato16(input + offset, &sniLen);
  3579. offset += OPAQUE16_LEN;
  3580. if (extLen < offset + sniLen)
  3581. return BUFFER_ERROR;
  3582. if (sniType == WOLFSSL_SNI_HOST_NAME) {
  3583. ret = LoadNamedKey(session, input + offset, sniLen);
  3584. if (ret < 0) {
  3585. /* don't treat this as fatal error */
  3586. SetError(CLIENT_HELLO_LATE_KEY_STR, error, session, 0);
  3587. break;
  3588. }
  3589. }
  3590. offset += sniLen;
  3591. listLen -= min(ENUM_LEN + OPAQUE16_LEN + sniLen, listLen);
  3592. }
  3593. break;
  3594. }
  3595. #endif
  3596. #ifdef WOLFSSL_TLS13
  3597. case EXT_KEY_SHARE:
  3598. {
  3599. word16 ksLen = (word16)((input[0] << 8) | input[1]);
  3600. if (ksLen + OPAQUE16_LEN > extLen) {
  3601. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3602. return -1;
  3603. }
  3604. /* cache key share data till server_hello */
  3605. session->cliKeyShareSz = ksLen;
  3606. if (ksLen > 0) {
  3607. session->cliKeyShare = (byte*)XMALLOC(ksLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3608. if (session->cliKeyShare == NULL) {
  3609. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  3610. break;
  3611. }
  3612. XMEMCPY(session->cliKeyShare, &input[2], ksLen);
  3613. }
  3614. break;
  3615. }
  3616. #ifdef HAVE_SESSION_TICKET
  3617. case EXT_PRE_SHARED_KEY:
  3618. {
  3619. word16 idsLen, idLen, bindersLen, idx = 0;
  3620. word32 ticketAge;
  3621. const byte *identity, *binders;
  3622. idsLen = (word16)((input[idx] << 8) | input[idx+1]);
  3623. if (idsLen + OPAQUE16_LEN + idx > extLen) {
  3624. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3625. return -1;
  3626. }
  3627. idx += OPAQUE16_LEN;
  3628. /* PSK identity */
  3629. idLen = (word16)((input[idx] << 8) | input[idx+1]);
  3630. if (idLen + OPAQUE16_LEN + idx > extLen) {
  3631. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3632. return -1;
  3633. }
  3634. idx += OPAQUE16_LEN;
  3635. identity = &input[idx];
  3636. idx += idLen;
  3637. /* Obfuscated Ticket Age 32-bits */
  3638. ticketAge = (word32)((input[idx] << 24) | (input[idx+1] << 16) |
  3639. (input[idx+2] << 8) | input[idx+3]);
  3640. (void)ticketAge; /* not used */
  3641. idx += OPAQUE32_LEN;
  3642. /* binders - all binders */
  3643. bindersLen = (word16)((input[idx] << 8) | input[idx+1]);
  3644. if (bindersLen + OPAQUE16_LEN + idx > extLen) {
  3645. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3646. return -1;
  3647. }
  3648. idx += OPAQUE16_LEN;
  3649. binders = &input[idx];
  3650. bindersLen += OPAQUE16_LEN; /* includes 2 bytes for total len */
  3651. (void)binders; /* not used */
  3652. /* Hash data up to binders for deriving binders in PSK extension. */
  3653. HashRaw(session->sslServer, inputHello - HANDSHAKE_HEADER_SZ,
  3654. inputHelloSz - bindersLen + HANDSHAKE_HEADER_SZ);
  3655. HashRaw(session->sslClient, inputHello - HANDSHAKE_HEADER_SZ,
  3656. inputHelloSz - bindersLen + HANDSHAKE_HEADER_SZ);
  3657. /* call to decrypt session ticket */
  3658. if (DoClientTicket(ssl, identity, idLen) != WOLFSSL_TICKET_RET_OK) {
  3659. /* we aren't decrypting the resumption, since we know the master secret */
  3660. /* ignore errors */
  3661. }
  3662. ssl->options.resuming = 1;
  3663. /* Hash the rest of the ClientHello. */
  3664. HashRaw(session->sslServer, inputHello + inputHelloSz - bindersLen, bindersLen);
  3665. HashRaw(session->sslClient, inputHello + inputHelloSz - bindersLen, bindersLen);
  3666. didHash = 1;
  3667. break;
  3668. }
  3669. #endif /* HAVE_SESSION_TICKET */
  3670. #endif /* WOLFSSL_TLS13 */
  3671. case EXT_SUPPORTED_VERSIONS:
  3672. break;
  3673. case EXT_TICKET_ID:
  3674. /* make sure can read through ticket if there is a non blank one */
  3675. if (extLen && extLen < ID_LEN) {
  3676. SetError(CLIENT_HELLO_INPUT_STR, error, session,
  3677. FATAL_ERROR_STATE);
  3678. return -1;
  3679. }
  3680. if (extLen) {
  3681. if (session->ticketID == NULL) {
  3682. session->ticketID = (byte*)XMALLOC(ID_LEN,
  3683. NULL, DYNAMIC_TYPE_SNIFFER_TICKET_ID);
  3684. if (session->ticketID == 0) {
  3685. SetError(MEMORY_STR, error, session,
  3686. FATAL_ERROR_STATE);
  3687. return -1;
  3688. }
  3689. }
  3690. #ifdef HAVE_SESSION_TICKET
  3691. /* do not set "ssl->options.useTicket", since the sniffer uses
  3692. * the cache differently for retaining the master secret only */
  3693. #endif
  3694. XMEMCPY(session->ticketID, input + extLen - ID_LEN, ID_LEN);
  3695. }
  3696. break;
  3697. }
  3698. input += extLen;
  3699. *sslBytes -= extLen;
  3700. len -= extLen + EXT_TYPE_SZ + LENGTH_SZ;
  3701. }
  3702. if (!didHash) {
  3703. HashRaw(session->sslServer, inputHello - HANDSHAKE_HEADER_SZ,
  3704. inputHelloSz + HANDSHAKE_HEADER_SZ);
  3705. HashRaw(session->sslClient, inputHello - HANDSHAKE_HEADER_SZ,
  3706. inputHelloSz + HANDSHAKE_HEADER_SZ);
  3707. }
  3708. (void)ssl;
  3709. return ret;
  3710. }
  3711. #ifdef WOLFSSL_SNIFFER_WATCH
  3712. static int KeyWatchCall(SnifferSession* session, const byte* data, int dataSz,
  3713. char* error)
  3714. {
  3715. int ret;
  3716. Sha256 sha;
  3717. byte digest[SHA256_DIGEST_SIZE];
  3718. if (WatchCb == NULL) {
  3719. SetError(WATCH_CB_MISSING_STR, error, session, FATAL_ERROR_STATE);
  3720. return -1;
  3721. }
  3722. ret = wc_InitSha256(&sha);
  3723. if (ret == 0)
  3724. ret = wc_Sha256Update(&sha, data, dataSz);
  3725. if (ret == 0)
  3726. ret = wc_Sha256Final(&sha, digest);
  3727. if (ret != 0) {
  3728. SetError(WATCH_HASH_STR, error, session, FATAL_ERROR_STATE);
  3729. return -1;
  3730. }
  3731. ret = WatchCb((void*)session, digest, sizeof(digest),
  3732. data, dataSz, WatchCbCtx, error);
  3733. if (ret != 0) {
  3734. #ifdef WOLFSSL_SNIFFER_STATS
  3735. INC_STAT(SnifferStats.sslKeysUnmatched);
  3736. #endif
  3737. SetError(WATCH_FAIL_STR, error, session, FATAL_ERROR_STATE);
  3738. ret = -1;
  3739. }
  3740. else {
  3741. #ifdef WOLFSSL_SNIFFER_STATS
  3742. INC_STAT(SnifferStats.sslKeyMatches);
  3743. #endif
  3744. }
  3745. return ret;
  3746. }
  3747. /* Process Certificate */
  3748. static int ProcessCertificate(const byte* input, int* sslBytes,
  3749. SnifferSession* session, char* error)
  3750. {
  3751. word32 certChainSz;
  3752. word32 certSz;
  3753. /* If the receiver is the server, this is the client certificate message,
  3754. * and it should be ignored at this point. */
  3755. if (session->flags.side == WOLFSSL_SERVER_END)
  3756. return 0;
  3757. if (*sslBytes < CERT_HEADER_SZ) {
  3758. SetError(BAD_CERT_MSG_STR, error, session, FATAL_ERROR_STATE);
  3759. return -1;
  3760. }
  3761. #ifdef WOLFSSL_TLS13
  3762. if (IsAtLeastTLSv1_3(session->sslServer->version)) {
  3763. /* skip 1 byte (Request context len) */
  3764. input += OPAQUE8_LEN;
  3765. *sslBytes -= OPAQUE8_LEN;
  3766. }
  3767. #endif
  3768. ato24(input, &certChainSz);
  3769. *sslBytes -= CERT_HEADER_SZ;
  3770. input += CERT_HEADER_SZ;
  3771. if (*sslBytes < (int)certChainSz) {
  3772. SetError(BAD_CERT_MSG_STR, error, session, FATAL_ERROR_STATE);
  3773. return -1;
  3774. }
  3775. ato24(input, &certSz);
  3776. input += OPAQUE24_LEN;
  3777. if (*sslBytes < (int)certSz) {
  3778. SetError(BAD_CERT_MSG_STR, error, session, FATAL_ERROR_STATE);
  3779. return -1;
  3780. }
  3781. *sslBytes -= certChainSz;
  3782. return KeyWatchCall(session, input, certSz, error);
  3783. }
  3784. #endif /* WOLFSSL_SNIFFER_WATCH */
  3785. /* Process Finished */
  3786. static int ProcessFinished(const byte* input, int size, int* sslBytes,
  3787. SnifferSession* session, char* error)
  3788. {
  3789. WOLFSSL* ssl;
  3790. word32 inOutIdx = 0;
  3791. int ret;
  3792. if (session->flags.side == WOLFSSL_SERVER_END)
  3793. ssl = session->sslServer;
  3794. else
  3795. ssl = session->sslClient;
  3796. #ifdef WOLFSSL_TLS13
  3797. if (IsAtLeastTLSv1_3(ssl->version)) {
  3798. ret = DoTls13Finished(ssl, input, &inOutIdx, (word32)size,
  3799. (word32)*sslBytes, SNIFF);
  3800. ssl->options.handShakeState = HANDSHAKE_DONE;
  3801. ssl->options.handShakeDone = 1;
  3802. }
  3803. else
  3804. #endif
  3805. {
  3806. ret = DoFinished(ssl, input, &inOutIdx, (word32)size,
  3807. (word32)*sslBytes, SNIFF);
  3808. }
  3809. *sslBytes -= (int)inOutIdx;
  3810. if (ret < 0) {
  3811. SetError(BAD_FINISHED_MSG, error, session, FATAL_ERROR_STATE);
  3812. return ret;
  3813. }
  3814. if (ret == 0 && session->flags.cached == 0) {
  3815. if (session->sslServer->options.haveSessionId) {
  3816. #ifndef NO_SESSION_CACHE
  3817. WOLFSSL_SESSION* sess = wolfSSL_GetSession(session->sslServer, NULL, 0);
  3818. if (sess == NULL) {
  3819. SetupSession(session->sslServer);
  3820. AddSession(session->sslServer); /* don't re add */
  3821. #ifdef WOLFSSL_SNIFFER_STATS
  3822. INC_STAT(SnifferStats.sslResumptionInserts);
  3823. #endif
  3824. }
  3825. session->flags.cached = 1;
  3826. #endif
  3827. }
  3828. }
  3829. #ifdef WOLFSSL_TLS13
  3830. /* Derive TLS v1.3 traffic keys */
  3831. if (IsAtLeastTLSv1_3(ssl->version)) {
  3832. if (!session->flags.gotFinished) {
  3833. /* When either side gets "finished" derive master secret and keys */
  3834. ret = DeriveMasterSecret(session->sslServer);
  3835. ret += DeriveMasterSecret(session->sslClient);
  3836. #ifdef WOLFSSL_EARLY_DATA
  3837. ret += DeriveTls13Keys(session->sslServer, traffic_key, ENCRYPT_AND_DECRYPT_SIDE, ssl->earlyData == no_early_data);
  3838. ret += DeriveTls13Keys(session->sslClient, traffic_key, ENCRYPT_AND_DECRYPT_SIDE, ssl->earlyData == no_early_data);
  3839. #else
  3840. ret += DeriveTls13Keys(session->sslServer, traffic_key, ENCRYPT_AND_DECRYPT_SIDE, 1);
  3841. ret += DeriveTls13Keys(session->sslClient, traffic_key, ENCRYPT_AND_DECRYPT_SIDE, 1);
  3842. #endif
  3843. if (ret != 0) {
  3844. SetError(BAD_FINISHED_MSG, error, session, FATAL_ERROR_STATE);
  3845. return -1;
  3846. }
  3847. session->flags.gotFinished = 1;
  3848. #ifdef SHOW_SECRETS
  3849. ShowTlsSecrets(session);
  3850. #endif
  3851. }
  3852. if (session->flags.side == WOLFSSL_SERVER_END) {
  3853. /* finished from client to server */
  3854. ret = SetKeysSide(session->sslServer, DECRYPT_SIDE_ONLY);
  3855. ret += SetKeysSide(session->sslClient, ENCRYPT_SIDE_ONLY);
  3856. #ifdef HAVE_SESSION_TICKET
  3857. /* derive resumption secret for next session - on finished (from client) */
  3858. ret += DeriveResumptionSecret(session->sslClient,
  3859. session->sslClient->session->masterSecret);
  3860. /* copy resumption secret to server */
  3861. XMEMCPY(session->sslServer->session->masterSecret,
  3862. session->sslClient->session->masterSecret, SECRET_LEN);
  3863. #ifdef SHOW_SECRETS
  3864. PrintSecret("resumption secret",
  3865. session->sslClient->session->masterSecret, SECRET_LEN);
  3866. #endif
  3867. #endif
  3868. }
  3869. else {
  3870. /* finished from server to client */
  3871. ret = SetKeysSide(session->sslServer, ENCRYPT_SIDE_ONLY);
  3872. ret += SetKeysSide(session->sslClient, DECRYPT_SIDE_ONLY);
  3873. }
  3874. if (ret != 0) {
  3875. SetError(BAD_FINISHED_MSG, error, session, FATAL_ERROR_STATE);
  3876. return -1;
  3877. }
  3878. }
  3879. #endif
  3880. /* Do not free handshake resources yet if secure renegotiation */
  3881. if (session->flags.secRenegEn == 0) {
  3882. /* If receiving a finished message from one side, free the resources
  3883. * from the other side's tracker. */
  3884. if (session->flags.side == WOLFSSL_SERVER_END)
  3885. FreeHandshakeResources(session->sslClient);
  3886. else
  3887. FreeHandshakeResources(session->sslServer);
  3888. }
  3889. return ret;
  3890. }
  3891. /* Process HandShake input */
  3892. static int DoHandShake(const byte* input, int* sslBytes,
  3893. SnifferSession* session, char* error, word16 rhSize)
  3894. {
  3895. byte type;
  3896. int size;
  3897. int ret = 0;
  3898. WOLFSSL* ssl;
  3899. int startBytes;
  3900. (void)rhSize;
  3901. #ifdef HAVE_MAX_FRAGMENT
  3902. if (session->tlsFragBuf) {
  3903. XMEMCPY(session->tlsFragBuf + session->tlsFragOffset, input, rhSize);
  3904. session->tlsFragOffset += rhSize;
  3905. *sslBytes -= rhSize;
  3906. if (session->tlsFragOffset < session->tlsFragSize) {
  3907. return 0;
  3908. }
  3909. /* reassembled complete fragment */
  3910. input = session->tlsFragBuf;
  3911. *sslBytes = session->tlsFragSize;
  3912. rhSize = session->tlsFragSize;
  3913. }
  3914. #endif
  3915. if (*sslBytes < HANDSHAKE_HEADER_SZ) {
  3916. SetError(HANDSHAKE_INPUT_STR, error, session, FATAL_ERROR_STATE);
  3917. return -1;
  3918. }
  3919. type = input[0];
  3920. size = (input[1] << 16) | (input[2] << 8) | input[3];
  3921. input += HANDSHAKE_HEADER_SZ;
  3922. *sslBytes -= HANDSHAKE_HEADER_SZ;
  3923. startBytes = *sslBytes;
  3924. if (*sslBytes < size) {
  3925. Trace(SPLIT_HANDSHAKE_MSG_STR);
  3926. *sslBytes = 0;
  3927. return ret;
  3928. }
  3929. if (session->flags.side == WOLFSSL_SERVER_END)
  3930. ssl = session->sslServer;
  3931. else
  3932. ssl = session->sslClient;
  3933. #ifdef HAVE_MAX_FRAGMENT
  3934. if (rhSize < size) {
  3935. /* partial fragment, let's reassemble */
  3936. if (session->tlsFragBuf == NULL) {
  3937. session->tlsFragOffset = 0;
  3938. session->tlsFragSize = size + HANDSHAKE_HEADER_SZ;
  3939. session->tlsFragBuf = (byte*)XMALLOC(session->tlsFragSize, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3940. if (session->tlsFragBuf == NULL) {
  3941. SetError(MEMORY_STR, error, NULL, 0);
  3942. return 0;
  3943. }
  3944. /* include the handshake header */
  3945. input -= HANDSHAKE_HEADER_SZ;
  3946. *sslBytes += HANDSHAKE_HEADER_SZ;
  3947. }
  3948. XMEMCPY(session->tlsFragBuf + session->tlsFragOffset, input, rhSize);
  3949. session->tlsFragOffset += rhSize;
  3950. *sslBytes -= rhSize;
  3951. return 0;
  3952. }
  3953. #endif
  3954. #ifdef WOLFSSL_TLS13
  3955. if (type != client_hello && type != server_hello
  3956. #ifdef WOLFSSL_ASYNC_CRYPT
  3957. && session->sslServer->error != WC_PENDING_E && session->pendSeq == 0
  3958. #endif
  3959. ) {
  3960. /* For resumption the hash is before / after client_hello PSK binder */
  3961. /* hash the packet including header */
  3962. /* TLS v1.3 requires the hash for the handshake and transfer key derivation */
  3963. /* we hash even for non TLS v1.3, since we don't know if its actually
  3964. TLS v1.3 till later at EXT_SUPPORTED_VERSIONS in server_hello */
  3965. /* hello retry request restarts hash prior to server_hello hash calc */
  3966. HashRaw(session->sslServer, input - HANDSHAKE_HEADER_SZ, size + HANDSHAKE_HEADER_SZ);
  3967. HashRaw(session->sslClient, input - HANDSHAKE_HEADER_SZ, size + HANDSHAKE_HEADER_SZ);
  3968. }
  3969. #endif
  3970. #ifdef HAVE_EXTENDED_MASTER
  3971. if (session->hash) {
  3972. if (HashUpdate(session->hash, input, size) != 0) {
  3973. SetError(EXTENDED_MASTER_HASH_STR, error,
  3974. session, FATAL_ERROR_STATE);
  3975. ret = -1;
  3976. goto exit;
  3977. }
  3978. }
  3979. #endif
  3980. switch (type) {
  3981. case hello_verify_request:
  3982. Trace(GOT_HELLO_VERIFY_STR);
  3983. break;
  3984. case hello_request:
  3985. Trace(GOT_HELLO_REQUEST_STR);
  3986. break;
  3987. case session_ticket:
  3988. Trace(GOT_SESSION_TICKET_STR);
  3989. ret = ProcessSessionTicket(input, sslBytes, session, error);
  3990. break;
  3991. case server_hello:
  3992. Trace(GOT_SERVER_HELLO_STR);
  3993. ret = ProcessServerHello(size, input, sslBytes, session, error);
  3994. break;
  3995. case certificate_request:
  3996. Trace(GOT_CERT_REQ_STR);
  3997. break;
  3998. case server_key_exchange:
  3999. Trace(GOT_SERVER_KEY_EX_STR);
  4000. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  4001. if (!session->context->useKeyLogFile)
  4002. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  4003. {
  4004. /* can't know temp key passively */
  4005. SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
  4006. session->verboseErr = 1;
  4007. ret = -1;
  4008. #if defined(WOLFSSL_SNIFFER_STATS)
  4009. INC_STAT(SnifferStats.sslEphemeralMisses);
  4010. #endif /* WOLFSSL_SNIFFER_STATS */
  4011. }
  4012. break;
  4013. case encrypted_extensions:
  4014. Trace(GOT_ENC_EXT_STR);
  4015. ssl->msgsReceived.got_encrypted_extensions = 1;
  4016. break;
  4017. case certificate:
  4018. Trace(GOT_CERT_STR);
  4019. if (session->flags.side == WOLFSSL_SERVER_END) {
  4020. #ifdef WOLFSSL_SNIFFER_STATS
  4021. INC_STAT(SnifferStats.sslClientAuthConns);
  4022. #endif
  4023. }
  4024. #ifdef WOLFSSL_SNIFFER_WATCH
  4025. ret = ProcessCertificate(input, sslBytes, session, error);
  4026. #endif
  4027. break;
  4028. case server_hello_done:
  4029. Trace(GOT_SERVER_HELLO_DONE_STR);
  4030. break;
  4031. case finished:
  4032. Trace(GOT_FINISHED_STR);
  4033. ret = ProcessFinished(input, size, sslBytes, session, error);
  4034. break;
  4035. case client_hello:
  4036. Trace(GOT_CLIENT_HELLO_STR);
  4037. ret = ProcessClientHello(input, sslBytes, session, error);
  4038. break;
  4039. case client_key_exchange:
  4040. Trace(GOT_CLIENT_KEY_EX_STR);
  4041. #ifdef HAVE_EXTENDED_MASTER
  4042. if (session->flags.expectEms) {
  4043. /* on async reentry the session->hash is already copied
  4044. * and free'd */
  4045. if (session->hash != NULL) {
  4046. if (HashCopy(session->sslServer->hsHashes,
  4047. session->hash) == 0 &&
  4048. HashCopy(session->sslClient->hsHashes,
  4049. session->hash) == 0) {
  4050. session->sslServer->options.haveEMS = 1;
  4051. session->sslClient->options.haveEMS = 1;
  4052. }
  4053. else {
  4054. SetError(EXTENDED_MASTER_HASH_STR, error,
  4055. session, FATAL_ERROR_STATE);
  4056. ret = -1;
  4057. }
  4058. XMEMSET(session->hash, 0, sizeof(HsHashes));
  4059. XFREE(session->hash, NULL, DYNAMIC_TYPE_HASHES);
  4060. session->hash = NULL;
  4061. }
  4062. }
  4063. else {
  4064. session->sslServer->options.haveEMS = 0;
  4065. session->sslClient->options.haveEMS = 0;
  4066. }
  4067. #endif
  4068. if (ret == 0) {
  4069. ret = ProcessClientKeyExchange(input, sslBytes, session, error);
  4070. #ifdef WOLFSSL_ASYNC_CRYPT
  4071. if (ret == WC_PENDING_E)
  4072. return ret;
  4073. #endif
  4074. if (ret != 0) {
  4075. SetError(KEY_MISMATCH_STR, error, session, FATAL_ERROR_STATE);
  4076. session->verboseErr = 1;
  4077. }
  4078. }
  4079. break;
  4080. case certificate_verify:
  4081. Trace(GOT_CERT_VER_STR);
  4082. break;
  4083. case certificate_status:
  4084. Trace(GOT_CERT_STATUS_STR);
  4085. break;
  4086. default:
  4087. SetError(GOT_UNKNOWN_HANDSHAKE_STR, error, session, 0);
  4088. ret = -1;
  4089. break;
  4090. }
  4091. #ifdef HAVE_EXTENDED_MASTER
  4092. exit:
  4093. #endif
  4094. #ifdef HAVE_MAX_FRAGMENT
  4095. if (session->tlsFragBuf) {
  4096. XFREE(session->tlsFragBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  4097. session->tlsFragBuf = NULL;
  4098. }
  4099. #endif
  4100. *sslBytes = startBytes - size; /* actual bytes of full process */
  4101. return ret;
  4102. }
  4103. /* For ciphers that use AEAD use the encrypt routine to
  4104. * bypass the auth tag checking */
  4105. static int DecryptDo(WOLFSSL* ssl, byte* plain, const byte* input,
  4106. word16 sz)
  4107. {
  4108. int ret = 0;
  4109. (void)plain;
  4110. (void)input;
  4111. (void)sz;
  4112. switch (ssl->specs.bulk_cipher_algorithm)
  4113. {
  4114. #ifndef NO_RC4
  4115. case wolfssl_rc4:
  4116. wc_Arc4Process(ssl->decrypt.arc4, plain, input, sz);
  4117. break;
  4118. #endif
  4119. #ifndef NO_DES3
  4120. case wolfssl_triple_des:
  4121. #ifdef WOLFSSL_ASYNC_CRYPT
  4122. /* initialize event */
  4123. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.des3->asyncDev,
  4124. WC_ASYNC_FLAG_CALL_AGAIN);
  4125. if (ret != 0)
  4126. break;
  4127. #endif
  4128. ret = wc_Des3_CbcDecrypt(ssl->decrypt.des3, plain, input, sz);
  4129. #ifdef WOLFSSL_ASYNC_CRYPT
  4130. if (ret == WC_PENDING_E) {
  4131. ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.des3->asyncDev);
  4132. }
  4133. #endif
  4134. break;
  4135. #endif
  4136. #if !defined(NO_AES) && defined(HAVE_AES_CBC)
  4137. case wolfssl_aes:
  4138. #ifdef WOLFSSL_ASYNC_CRYPT
  4139. /* initialize event */
  4140. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
  4141. WC_ASYNC_FLAG_CALL_AGAIN);
  4142. if (ret != 0)
  4143. break;
  4144. #endif
  4145. ret = wc_AesCbcDecrypt(ssl->decrypt.aes, plain, input, sz);
  4146. #ifdef WOLFSSL_ASYNC_CRYPT
  4147. if (ret == WC_PENDING_E) {
  4148. ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev);
  4149. }
  4150. #endif
  4151. break;
  4152. #endif
  4153. #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM)
  4154. case wolfssl_aes_gcm:
  4155. case wolfssl_aes_ccm: /* GCM AEAD macros use same size as CCM */
  4156. {
  4157. /* For ciphers that use AEAD use the encrypt routine to
  4158. * bypass the auth tag checking */
  4159. wc_AesAuthEncryptFunc aes_auth_fn;
  4160. #ifdef WOLFSSL_ASYNC_CRYPT
  4161. /* initialize event */
  4162. ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
  4163. WC_ASYNC_FLAG_CALL_AGAIN);
  4164. if (ret != 0)
  4165. break;
  4166. #endif
  4167. #if defined(HAVE_AESGCM) && defined(HAVE_AESCCM)
  4168. aes_auth_fn = (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm)
  4169. ? wc_AesGcmEncrypt : wc_AesCcmEncrypt;
  4170. #elif defined(HAVE_AESGCM)
  4171. aes_auth_fn = wc_AesGcmEncrypt;
  4172. #else
  4173. aes_auth_fn = wc_AesCcmEncrypt;
  4174. #endif
  4175. XMEMSET(ssl->decrypt.additional, 0, AEAD_AUTH_DATA_SZ);
  4176. XMEMCPY(ssl->decrypt.nonce, ssl->keys.aead_dec_imp_IV, AESGCM_IMP_IV_SZ);
  4177. XMEMCPY(ssl->decrypt.nonce + AESGCM_IMP_IV_SZ, input, AESGCM_EXP_IV_SZ);
  4178. if ((ret = aes_auth_fn(ssl->decrypt.aes,
  4179. plain,
  4180. input + AESGCM_EXP_IV_SZ,
  4181. sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  4182. ssl->decrypt.nonce, AESGCM_NONCE_SZ,
  4183. ssl->decrypt.additional, AEAD_AUTH_DATA_SZ,
  4184. NULL, 0)) < 0) {
  4185. #ifdef WOLFSSL_ASYNC_CRYPT
  4186. if (ret == WC_PENDING_E) {
  4187. ret = wolfSSL_AsyncPush(ssl, &ssl->decrypt.aes->asyncDev);
  4188. }
  4189. #endif
  4190. }
  4191. }
  4192. break;
  4193. #endif /* HAVE_AESGCM || HAVE_AESCCM */
  4194. #ifdef HAVE_ARIA
  4195. case wolfssl_aria_gcm:
  4196. ret = wc_AriaDecrypt(ssl->decrypt.aria,
  4197. plain,
  4198. (byte *)input + AESGCM_EXP_IV_SZ,
  4199. sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  4200. ssl->decrypt.nonce, AESGCM_NONCE_SZ,
  4201. ssl->decrypt.additional, ssl->specs.aead_mac_size,
  4202. NULL, 0);
  4203. break;
  4204. #endif
  4205. #ifdef HAVE_CAMELLIA
  4206. case wolfssl_camellia:
  4207. ret = wc_CamelliaCbcDecrypt(ssl->decrypt.cam, plain, input, sz);
  4208. break;
  4209. #endif
  4210. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \
  4211. !defined(NO_CHAPOL_AEAD)
  4212. case wolfssl_chacha:
  4213. ret = ChachaAEADDecrypt(ssl, plain, input, sz);
  4214. break;
  4215. #endif
  4216. #ifdef HAVE_NULL_CIPHER
  4217. case wolfssl_cipher_null:
  4218. if (input != plain) {
  4219. XMEMMOVE(plain, input, sz);
  4220. }
  4221. break;
  4222. #endif
  4223. default:
  4224. WOLFSSL_MSG("wolfSSL Decrypt programming error");
  4225. ret = DECRYPT_ERROR;
  4226. }
  4227. return ret;
  4228. }
  4229. static int DecryptTls(WOLFSSL* ssl, byte* plain, const byte* input,
  4230. word16 sz)
  4231. {
  4232. int ret = 0;
  4233. #ifdef WOLFSSL_ASYNC_CRYPT
  4234. if (ssl->decrypt.state != CIPHER_STATE_BEGIN) {
  4235. ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state);
  4236. if (ret != WC_NOT_PENDING_E) {
  4237. /* check for still pending */
  4238. if (ret == WC_PENDING_E)
  4239. return ret;
  4240. ssl->error = 0; /* clear async */
  4241. /* let failures through so CIPHER_STATE_END logic is run */
  4242. }
  4243. }
  4244. else
  4245. #endif
  4246. {
  4247. /* Reset state */
  4248. ret = 0;
  4249. ssl->decrypt.state = CIPHER_STATE_BEGIN;
  4250. }
  4251. switch (ssl->decrypt.state) {
  4252. case CIPHER_STATE_BEGIN:
  4253. {
  4254. if (ssl->decrypt.setup == 0) {
  4255. WOLFSSL_MSG("Decrypt ciphers not setup");
  4256. return DECRYPT_ERROR;
  4257. }
  4258. #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM)
  4259. /* make sure AES GCM/CCM memory is allocated */
  4260. /* free for these happens in FreeCiphers */
  4261. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
  4262. ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
  4263. /* make sure auth iv and auth are allocated */
  4264. if (ssl->decrypt.additional == NULL)
  4265. ssl->decrypt.additional = (byte*)XMALLOC(AEAD_AUTH_DATA_SZ,
  4266. ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  4267. if (ssl->decrypt.nonce == NULL)
  4268. ssl->decrypt.nonce = (byte*)XMALLOC(AESGCM_NONCE_SZ,
  4269. ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
  4270. if (ssl->decrypt.additional == NULL ||
  4271. ssl->decrypt.nonce == NULL) {
  4272. return MEMORY_E;
  4273. }
  4274. }
  4275. #endif /* HAVE_AESGCM || HAVE_AESCCM */
  4276. /* Advance state and proceed */
  4277. ssl->decrypt.state = CIPHER_STATE_DO;
  4278. }
  4279. FALL_THROUGH;
  4280. case CIPHER_STATE_DO:
  4281. {
  4282. ret = DecryptDo(ssl, plain, input, sz);
  4283. /* Advance state */
  4284. ssl->decrypt.state = CIPHER_STATE_END;
  4285. #ifdef WOLFSSL_ASYNC_CRYPT
  4286. /* If pending, return now */
  4287. if (ret == WC_PENDING_E) {
  4288. return ret;
  4289. }
  4290. #endif
  4291. }
  4292. FALL_THROUGH;
  4293. case CIPHER_STATE_END:
  4294. {
  4295. #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM)
  4296. /* make sure AES GCM/CCM nonce is cleared */
  4297. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm ||
  4298. ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
  4299. if (ssl->decrypt.nonce)
  4300. ForceZero(ssl->decrypt.nonce, AESGCM_NONCE_SZ);
  4301. if (ret < 0)
  4302. ret = VERIFY_MAC_ERROR;
  4303. }
  4304. #endif /* HAVE_AESGCM || HAVE_AESCCM */
  4305. break;
  4306. }
  4307. default:
  4308. break;
  4309. }
  4310. /* Reset state */
  4311. ssl->decrypt.state = CIPHER_STATE_BEGIN;
  4312. return ret;
  4313. }
  4314. /* Decrypt input message into output, adjust output steam if needed */
  4315. static const byte* DecryptMessage(WOLFSSL* ssl, const byte* input, word32 sz,
  4316. byte* output, int* error, int* advance, RecordLayerHeader* rh)
  4317. {
  4318. int ivExtra = 0;
  4319. int ret;
  4320. #ifdef WOLFSSL_TLS13
  4321. if (IsAtLeastTLSv1_3(ssl->version)) {
  4322. ret = DecryptTls13(ssl, output, input, sz, (byte*)rh, RECORD_HEADER_SZ);
  4323. }
  4324. else
  4325. #endif
  4326. {
  4327. XMEMCPY(&ssl->curRL, rh, RECORD_HEADER_SZ);
  4328. ret = DecryptTls(ssl, output, input, sz);
  4329. }
  4330. #ifdef WOLFSSL_ASYNC_CRYPT
  4331. /* for async the symmetric operations are blocking */
  4332. if (ret == WC_PENDING_E) {
  4333. do {
  4334. ret = wolfSSL_AsyncPoll(ssl, WOLF_POLL_FLAG_CHECK_HW);
  4335. } while (ret == 0);
  4336. if (ret >= 0) {
  4337. /* remove from event queue list */
  4338. ret = wolfSSL_AsyncPop(ssl, NULL);
  4339. }
  4340. }
  4341. #endif
  4342. if (ret != 0) {
  4343. *error = ret;
  4344. return NULL;
  4345. }
  4346. ssl->keys.encryptSz = sz;
  4347. if (ssl->options.tls1_1 && ssl->specs.cipher_type == block) {
  4348. output += ssl->specs.block_size; /* go past TLSv1.1 IV */
  4349. ivExtra = ssl->specs.block_size;
  4350. *advance = ssl->specs.block_size;
  4351. }
  4352. if (ssl->specs.cipher_type == aead) {
  4353. *advance = ssl->specs.aead_mac_size;
  4354. ssl->keys.padSz = ssl->specs.aead_mac_size;
  4355. }
  4356. else
  4357. ssl->keys.padSz = ssl->specs.hash_size;
  4358. if (ssl->specs.cipher_type == block) {
  4359. /* last pad bytes indicates length */
  4360. word32 pad = 0;
  4361. if ((int)sz > ivExtra) {
  4362. /* get value of last pad byte */
  4363. pad = *(output + sz - ivExtra - 1) + 1;
  4364. }
  4365. ssl->keys.padSz += pad;
  4366. }
  4367. #ifdef WOLFSSL_TLS13
  4368. if (IsAtLeastTLSv1_3(ssl->version)) {
  4369. word16 i = (word16)(sz - ssl->keys.padSz);
  4370. /* Remove padding from end of plain text. */
  4371. for (--i; i > 0; i--) {
  4372. if (output[i] != 0)
  4373. break;
  4374. }
  4375. /* Get the real content type from the end of the data. */
  4376. rh->type = output[i];
  4377. ssl->keys.padSz = sz - i;
  4378. }
  4379. #endif
  4380. (void)rh;
  4381. return output;
  4382. }
  4383. /* remove session from table, use rowHint if no info (means we have a lock) */
  4384. static void RemoveSession(SnifferSession* session, IpInfo* ipInfo,
  4385. TcpInfo* tcpInfo, word32 rowHint)
  4386. {
  4387. SnifferSession* previous = 0;
  4388. SnifferSession* current;
  4389. word32 row = rowHint;
  4390. #ifndef HAVE_C___ATOMIC
  4391. int haveLock = 0;
  4392. #endif
  4393. Trace(REMOVE_SESSION_STR);
  4394. if (ipInfo && tcpInfo)
  4395. row = SessionHash(ipInfo, tcpInfo);
  4396. #ifndef HAVE_C___ATOMIC
  4397. else
  4398. haveLock = 1;
  4399. #endif
  4400. if (row >= HASH_SIZE)
  4401. return;
  4402. #ifndef HAVE_C___ATOMIC
  4403. if (!haveLock) {
  4404. LOCK_SESSION();
  4405. }
  4406. #endif
  4407. current = SessionTable[row];
  4408. while (current) {
  4409. if (current == session) {
  4410. if (previous)
  4411. previous->next = current->next;
  4412. else
  4413. SessionTable[row] = current->next;
  4414. FreeSnifferSession(session);
  4415. TraceRemovedSession();
  4416. break;
  4417. }
  4418. previous = current;
  4419. current = current->next;
  4420. }
  4421. #ifndef HAVE_C___ATOMIC
  4422. if (!haveLock) {
  4423. UNLOCK_SESSION();
  4424. }
  4425. #endif
  4426. }
  4427. /* Remove stale sessions from the Session Table, have a lock */
  4428. static void RemoveStaleSessions(void)
  4429. {
  4430. word32 i;
  4431. SnifferSession* session;
  4432. for (i = 0; i < HASH_SIZE; i++) {
  4433. session = SessionTable[i];
  4434. while (session) {
  4435. SnifferSession* next = session->next;
  4436. if (wc_Time(NULL) >= session->lastUsed + WOLFSSL_SNIFFER_TIMEOUT) {
  4437. TraceStaleSession();
  4438. RemoveSession(session, NULL, NULL, i);
  4439. }
  4440. session = next;
  4441. }
  4442. }
  4443. }
  4444. /* Create a new Sniffer Session */
  4445. static SnifferSession* CreateSession(IpInfo* ipInfo, TcpInfo* tcpInfo,
  4446. char* error)
  4447. {
  4448. SnifferSession* session = 0;
  4449. int row;
  4450. Trace(NEW_SESSION_STR);
  4451. /* create a new one */
  4452. session = (SnifferSession*)XMALLOC(sizeof(SnifferSession),
  4453. NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  4454. if (session == NULL) {
  4455. SetError(MEMORY_STR, error, NULL, 0);
  4456. return NULL;
  4457. }
  4458. InitSession(session);
  4459. #ifdef HAVE_EXTENDED_MASTER
  4460. {
  4461. HsHashes* newHash = (HsHashes*)XMALLOC(sizeof(HsHashes),
  4462. NULL, DYNAMIC_TYPE_HASHES);
  4463. if (newHash == NULL) {
  4464. SetError(MEMORY_STR, error, NULL, 0);
  4465. XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  4466. return NULL;
  4467. }
  4468. if (HashInit(newHash) != 0) {
  4469. SetError(EXTENDED_MASTER_HASH_STR, error, NULL, 0);
  4470. XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  4471. return NULL;
  4472. }
  4473. session->hash = newHash;
  4474. }
  4475. #endif
  4476. session->server = ipInfo->dst;
  4477. session->client = ipInfo->src;
  4478. session->srvPort = (word16)tcpInfo->dstPort;
  4479. session->cliPort = (word16)tcpInfo->srcPort;
  4480. session->cliSeqStart = tcpInfo->sequence;
  4481. session->cliExpected = 1; /* relative */
  4482. session->lastUsed= wc_Time(NULL);
  4483. session->keySz = 0;
  4484. session->error = 0;
  4485. session->verboseErr = 0;
  4486. #ifdef HAVE_SNI
  4487. session->sni = NULL;
  4488. #endif
  4489. session->context = GetSnifferServer(ipInfo, tcpInfo);
  4490. if (session->context == NULL) {
  4491. SetError(SERVER_NOT_REG_STR, error, NULL, 0);
  4492. XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  4493. return NULL;
  4494. }
  4495. session->sslServer = wolfSSL_new(session->context->ctx);
  4496. if (session->sslServer == NULL) {
  4497. SetError(BAD_NEW_SSL_STR, error, session, FATAL_ERROR_STATE);
  4498. XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  4499. return NULL;
  4500. }
  4501. session->sslClient = wolfSSL_new(session->context->ctx);
  4502. if (session->sslClient == NULL) {
  4503. wolfSSL_free(session->sslServer);
  4504. session->sslServer = 0;
  4505. SetError(BAD_NEW_SSL_STR, error, session, FATAL_ERROR_STATE);
  4506. XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  4507. return NULL;
  4508. }
  4509. /* put server back into server mode */
  4510. session->sslServer->options.side = WOLFSSL_SERVER_END;
  4511. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  4512. if (session->context->useKeyLogFile) {
  4513. setSnifferSecretCb(session);
  4514. }
  4515. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  4516. row = SessionHash(ipInfo, tcpInfo);
  4517. /* add it to the session table */
  4518. LOCK_SESSION();
  4519. session->next = SessionTable[row];
  4520. SessionTable[row] = session;
  4521. SessionCount++;
  4522. if ( (SessionCount % HASH_SIZE) == 0) {
  4523. TraceFindingStale();
  4524. RemoveStaleSessions();
  4525. }
  4526. UNLOCK_SESSION();
  4527. /* CreateSession is called in response to a SYN packet, we know this
  4528. * is headed to the server. Also we know the server is one we care
  4529. * about as we've passed the GetSnifferServer() successfully. */
  4530. session->flags.side = WOLFSSL_SERVER_END;
  4531. return session;
  4532. }
  4533. #ifdef OLD_HELLO_ALLOWED
  4534. /* Process Old Client Hello Input */
  4535. static int DoOldHello(SnifferSession* session, const byte* sslFrame,
  4536. int* rhSize, int* sslBytes, char* error)
  4537. {
  4538. const byte* input = sslFrame;
  4539. byte b0, b1;
  4540. word32 idx = 0;
  4541. int ret;
  4542. Trace(GOT_OLD_CLIENT_HELLO_STR);
  4543. session->flags.clientHello = 1; /* don't process again */
  4544. b0 = *input++;
  4545. b1 = *input++;
  4546. *sslBytes -= 2;
  4547. *rhSize = ((b0 & 0x7f) << 8) | b1;
  4548. if (*rhSize > *sslBytes) {
  4549. SetError(OLD_CLIENT_INPUT_STR, error, session, FATAL_ERROR_STATE);
  4550. return -1;
  4551. }
  4552. ret = ProcessOldClientHello(session->sslServer, input, &idx, *sslBytes,
  4553. (word16)*rhSize);
  4554. if (ret < 0 && ret != MATCH_SUITE_ERROR) {
  4555. SetError(BAD_OLD_CLIENT_STR, error, session, FATAL_ERROR_STATE);
  4556. return -1;
  4557. }
  4558. Trace(OLD_CLIENT_OK_STR);
  4559. XMEMCPY(session->sslClient->arrays->clientRandom,
  4560. session->sslServer->arrays->clientRandom, RAN_LEN);
  4561. *sslBytes -= *rhSize;
  4562. return 0;
  4563. }
  4564. #endif /* OLD_HELLO_ALLOWED */
  4565. #if 0
  4566. /* Calculate the TCP checksum, see RFC 1071 */
  4567. /* return 0 for success, -1 on error */
  4568. /* can be called from decode() with
  4569. TcpChecksum(&ipInfo, &tcpInfo, sslBytes, packet + ipInfo.length);
  4570. could also add a 64bit version if type available and using this
  4571. */
  4572. static int TcpChecksum(IpInfo* ipInfo, TcpInfo* tcpInfo, int dataLen,
  4573. const byte* packet)
  4574. {
  4575. TcpPseudoHdr pseudo;
  4576. int count = PSEUDO_HDR_SZ;
  4577. const word16* data = (word16*)&pseudo;
  4578. word32 sum = 0;
  4579. word16 checksum;
  4580. pseudo.src = ipInfo->src.ip4;
  4581. pseudo.dst = ipInfo->dst.ip4;
  4582. pseudo.rsv = 0;
  4583. pseudo.protocol = TCP_PROTO;
  4584. pseudo.length = htons(tcpInfo->length + dataLen);
  4585. /* pseudo header sum */
  4586. while (count >= 2) {
  4587. sum += *data++;
  4588. count -= 2;
  4589. }
  4590. count = tcpInfo->length + dataLen;
  4591. data = (word16*)packet;
  4592. /* main sum */
  4593. while (count > 1) {
  4594. sum += *data++;
  4595. count -=2;
  4596. }
  4597. /* get left-over, if any */
  4598. packet = (byte*)data;
  4599. if (count > 0) {
  4600. sum += *packet;
  4601. }
  4602. /* fold 32bit sum into 16 bits */
  4603. while (sum >> 16)
  4604. sum = (sum & 0xffff) + (sum >> 16);
  4605. checksum = (word16)~sum;
  4606. /* checksum should now equal 0, since included already calcd checksum */
  4607. /* field, but tcp checksum offloading could negate calculation */
  4608. if (checksum == 0)
  4609. return 0;
  4610. return -1;
  4611. }
  4612. #endif
  4613. /* Check IP and TCP headers, set payload */
  4614. /* returns 0 on success, -1 on error */
  4615. static int CheckHeaders(IpInfo* ipInfo, TcpInfo* tcpInfo, const byte* packet,
  4616. int length, const byte** sslFrame, int* sslBytes, char* error,
  4617. int checkReg, int trace)
  4618. {
  4619. IpHdr* iphdr = (IpHdr*)packet;
  4620. TcpHdr* tcphdr;
  4621. int version;
  4622. if (trace) {
  4623. TraceHeader();
  4624. TracePacket();
  4625. }
  4626. /* ip header */
  4627. if (length < IP_HDR_SZ) {
  4628. SetError(PACKET_HDR_SHORT_STR, error, NULL, 0);
  4629. return -1;
  4630. }
  4631. version = IP_V(iphdr);
  4632. if (version != IPV6 && version != IPV4) {
  4633. /* Is this VLAN IEEE 802.1Q Frame? TPID = 0x8100 */
  4634. if (packet[2] == 0x81 && packet[3] == 0x00) {
  4635. /* trim VLAN header and try again */
  4636. packet += 8;
  4637. length -= 8;
  4638. }
  4639. }
  4640. if (CheckIpHdr(iphdr, ipInfo, length, error, trace) != 0)
  4641. return -1;
  4642. #ifndef WOLFSSL_SNIFFER_WATCH
  4643. if (checkReg &&
  4644. !IsServerRegistered(iphdr->src) && !IsServerRegistered(iphdr->dst)) {
  4645. SetError(SERVER_NOT_REG_STR, error, NULL, 0);
  4646. return -1;
  4647. }
  4648. #endif
  4649. /* tcp header */
  4650. if (length < (ipInfo->length + TCP_HDR_SZ)) {
  4651. SetError(PACKET_HDR_SHORT_STR, error, NULL, 0);
  4652. return -1;
  4653. }
  4654. tcphdr = (TcpHdr*)(packet + ipInfo->length);
  4655. if (CheckTcpHdr(tcphdr, tcpInfo, error, trace) != 0)
  4656. return -1;
  4657. #ifndef WOLFSSL_SNIFFER_WATCH
  4658. if (checkReg &&
  4659. !IsPortRegistered(tcpInfo->srcPort) &&
  4660. !IsPortRegistered(tcpInfo->dstPort)) {
  4661. SetError(SERVER_PORT_NOT_REG_STR, error, NULL, 0);
  4662. return -1;
  4663. }
  4664. #endif
  4665. /* setup */
  4666. *sslFrame = packet + ipInfo->length + tcpInfo->length;
  4667. if (*sslFrame > packet + length) {
  4668. SetError(PACKET_HDR_SHORT_STR, error, NULL, 0);
  4669. return -1;
  4670. }
  4671. /* We only care about the data in the TCP/IP record. There may be extra
  4672. * data after the IP record for the FCS for Ethernet. */
  4673. *sslBytes = (int)(packet + ipInfo->total - *sslFrame);
  4674. (void)checkReg;
  4675. return 0;
  4676. }
  4677. /* Create or Find existing session */
  4678. /* returns 0 on success (continue), -1 on error, 1 on success (end) */
  4679. static int CheckSession(IpInfo* ipInfo, TcpInfo* tcpInfo, int sslBytes,
  4680. SnifferSession** session, char* error)
  4681. {
  4682. /* create a new SnifferSession on client SYN */
  4683. if (tcpInfo->syn && !tcpInfo->ack) {
  4684. #ifdef WOLFSSL_ASYNC_CRYPT
  4685. /* if session already exists and is pending do not create another */
  4686. *session = GetSnifferSession(ipInfo, tcpInfo);
  4687. if (*session != NULL) {
  4688. if ((*session)->pendSeq != 0) {
  4689. return WC_PENDING_E;
  4690. }
  4691. }
  4692. #endif
  4693. TraceClientSyn(tcpInfo->sequence);
  4694. #ifdef WOLFSSL_SNIFFER_STATS
  4695. INC_STAT(SnifferStats.sslEncryptedConns);
  4696. #endif
  4697. *session = CreateSession(ipInfo, tcpInfo, error);
  4698. if (*session == NULL) {
  4699. *session = GetSnifferSession(ipInfo, tcpInfo);
  4700. /* already had existing, so OK */
  4701. if (*session)
  4702. return 1;
  4703. SetError(MEMORY_STR, error, NULL, 0);
  4704. return -1;
  4705. }
  4706. return 1;
  4707. }
  4708. /* get existing sniffer session */
  4709. else {
  4710. *session = GetSnifferSession(ipInfo, tcpInfo);
  4711. if (*session == NULL) {
  4712. /* don't worry about extraneous RST or duplicate FINs */
  4713. if (tcpInfo->fin || tcpInfo->rst)
  4714. return 1;
  4715. /* don't worry about duplicate ACKs either */
  4716. if (sslBytes == 0 && tcpInfo->ack)
  4717. return 1;
  4718. #ifdef WOLFSSL_SNIFFER_STATS
  4719. LOCK_STAT();
  4720. NOLOCK_INC_STAT(SnifferStats.sslDecryptedPackets);
  4721. NOLOCK_ADD_TO_STAT(SnifferStats.sslDecryptedBytes, sslBytes);
  4722. UNLOCK_STAT();
  4723. #endif
  4724. SetError(BAD_SESSION_STR, error, NULL, 0);
  4725. return -1;
  4726. }
  4727. }
  4728. return 0;
  4729. }
  4730. /* Create a Packet Buffer from *begin - end, adjust new *begin and bytesLeft */
  4731. static PacketBuffer* CreateBuffer(word32* begin, word32 end, const byte* data,
  4732. int* bytesLeft)
  4733. {
  4734. PacketBuffer* pb;
  4735. int added = (int)(end - *begin + 1);
  4736. if (added <= 0) {
  4737. return NULL;
  4738. }
  4739. pb = (PacketBuffer*)XMALLOC(sizeof(PacketBuffer),
  4740. NULL, DYNAMIC_TYPE_SNIFFER_PB);
  4741. if (pb == NULL) return NULL;
  4742. pb->next = 0;
  4743. pb->begin = *begin;
  4744. pb->end = end;
  4745. pb->data = (byte*)XMALLOC(added, NULL, DYNAMIC_TYPE_SNIFFER_PB_BUFFER);
  4746. if (pb->data == NULL) {
  4747. XFREE(pb, NULL, DYNAMIC_TYPE_SNIFFER_PB);
  4748. return NULL;
  4749. }
  4750. XMEMCPY(pb->data, data, added);
  4751. *bytesLeft -= added;
  4752. *begin = pb->end + 1;
  4753. return pb;
  4754. }
  4755. /* Add sslFrame to Reassembly List */
  4756. /* returns 1 (end) on success, -1, on error */
  4757. static int AddToReassembly(byte from, word32 seq, const byte* sslFrame,
  4758. int sslBytes, SnifferSession* session, char* error)
  4759. {
  4760. PacketBuffer* add;
  4761. PacketBuffer** front = (from == WOLFSSL_SERVER_END) ?
  4762. &session->cliReassemblyList: &session->srvReassemblyList;
  4763. PacketBuffer* curr = *front;
  4764. PacketBuffer* prev = curr;
  4765. word32* reassemblyMemory = (from == WOLFSSL_SERVER_END) ?
  4766. &session->cliReassemblyMemory : &session->srvReassemblyMemory;
  4767. word32 startSeq = seq;
  4768. int added;
  4769. int bytesLeft = sslBytes; /* could be overlapping fragment */
  4770. /* if list is empty add full frame to front */
  4771. if (!curr) {
  4772. if (MaxRecoveryMemory != -1 &&
  4773. (int)(*reassemblyMemory + sslBytes) > MaxRecoveryMemory) {
  4774. SetError(REASSEMBLY_MAX_STR, error, session, FATAL_ERROR_STATE);
  4775. return -1;
  4776. }
  4777. add = CreateBuffer(&seq, seq + sslBytes - 1, sslFrame, &bytesLeft);
  4778. if (add == NULL) {
  4779. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  4780. return -1;
  4781. }
  4782. *front = add;
  4783. *reassemblyMemory += sslBytes;
  4784. return 1;
  4785. }
  4786. /* add to front if before current front, up to next->begin */
  4787. if (seq < curr->begin) {
  4788. word32 end = seq + sslBytes - 1;
  4789. if (end >= curr->begin)
  4790. end = curr->begin - 1;
  4791. if (MaxRecoveryMemory -1 &&
  4792. (int)(*reassemblyMemory + sslBytes) > MaxRecoveryMemory) {
  4793. SetError(REASSEMBLY_MAX_STR, error, session, FATAL_ERROR_STATE);
  4794. return -1;
  4795. }
  4796. add = CreateBuffer(&seq, end, sslFrame, &bytesLeft);
  4797. if (add == NULL) {
  4798. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  4799. return -1;
  4800. }
  4801. add->next = curr;
  4802. *front = add;
  4803. *reassemblyMemory += sslBytes;
  4804. }
  4805. /* while we have bytes left, try to find a gap to fill */
  4806. while (bytesLeft > 0) {
  4807. /* get previous packet in list */
  4808. while (curr && (seq >= curr->begin)) {
  4809. prev = curr;
  4810. curr = curr->next;
  4811. }
  4812. /* don't add duplicate data */
  4813. if (prev->end >= seq) {
  4814. if ( (seq + bytesLeft - 1) <= prev->end)
  4815. return 1;
  4816. seq = prev->end + 1;
  4817. bytesLeft = startSeq + sslBytes - seq;
  4818. }
  4819. if (!curr)
  4820. /* we're at the end */
  4821. added = bytesLeft;
  4822. else
  4823. /* we're in between two frames */
  4824. added = min(bytesLeft, (int)(curr->begin - seq));
  4825. /* data already there */
  4826. if (added <= 0)
  4827. continue;
  4828. if (MaxRecoveryMemory != -1 &&
  4829. (int)(*reassemblyMemory + added) > MaxRecoveryMemory) {
  4830. SetError(REASSEMBLY_MAX_STR, error, session, FATAL_ERROR_STATE);
  4831. return -1;
  4832. }
  4833. add = CreateBuffer(&seq, seq + added - 1, &sslFrame[seq - startSeq],
  4834. &bytesLeft);
  4835. if (add == NULL) {
  4836. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  4837. return -1;
  4838. }
  4839. add->next = prev->next;
  4840. prev->next = add;
  4841. *reassemblyMemory += added;
  4842. }
  4843. return 1;
  4844. }
  4845. /* Add out of order FIN capture */
  4846. /* returns 1 for success (end) */
  4847. static int AddFinCapture(SnifferSession* session, word32 sequence)
  4848. {
  4849. if (session->flags.side == WOLFSSL_SERVER_END) {
  4850. if (session->finCapture.cliCounted == 0)
  4851. session->finCapture.cliFinSeq = sequence;
  4852. }
  4853. else {
  4854. if (session->finCapture.srvCounted == 0)
  4855. session->finCapture.srvFinSeq = sequence;
  4856. }
  4857. return 1;
  4858. }
  4859. static int FindPrevAck(SnifferSession* session, word32 realAck)
  4860. {
  4861. int i;
  4862. word32* acks = (session->flags.side == WOLFSSL_SERVER_END) ?
  4863. session->cliAcks : session->srvAcks;
  4864. /* if previous ack found return 1, otherwise 0 */
  4865. for (i=0; i<WC_SNIFFER_HS_ACK_HIST_MAX; i++) {
  4866. if (acks[i] == realAck) {
  4867. return 1;
  4868. }
  4869. }
  4870. return 0;
  4871. }
  4872. static void AddAck(SnifferSession* session, word32 realAck)
  4873. {
  4874. int i;
  4875. word32* acks = (session->flags.side == WOLFSSL_SERVER_END) ?
  4876. session->cliAcks : session->srvAcks;
  4877. /* find first empty ack slot */
  4878. for (i=0; i<WC_SNIFFER_HS_ACK_HIST_MAX; i++) {
  4879. if (acks[i] == 0) {
  4880. break;
  4881. }
  4882. }
  4883. /* if out of slots, find oldest */
  4884. if (i == WC_SNIFFER_HS_ACK_HIST_MAX) {
  4885. int idx = 0;
  4886. word32 lastAck = realAck;
  4887. for (i=0; i<WC_SNIFFER_HS_ACK_HIST_MAX; i++) {
  4888. if (acks[i] < lastAck) {
  4889. idx = i;
  4890. lastAck = acks[i];
  4891. }
  4892. }
  4893. i = idx;
  4894. }
  4895. acks[i] = realAck;
  4896. }
  4897. /* Adjust incoming sequence based on side */
  4898. /* returns 0 on success (continue), -1 on error, 1 on success (end) */
  4899. static int AdjustSequence(TcpInfo* tcpInfo, SnifferSession* session,
  4900. int* sslBytes, const byte** sslFrame, char* error)
  4901. {
  4902. int ret = 0;
  4903. word32 seqStart = (session->flags.side == WOLFSSL_SERVER_END) ?
  4904. session->cliSeqStart :session->srvSeqStart;
  4905. word32 real = tcpInfo->sequence - seqStart;
  4906. word32* expected = (session->flags.side == WOLFSSL_SERVER_END) ?
  4907. &session->cliExpected : &session->srvExpected;
  4908. PacketBuffer* reassemblyList = (session->flags.side == WOLFSSL_SERVER_END) ?
  4909. session->cliReassemblyList : session->srvReassemblyList;
  4910. byte skipPartial = (session->flags.side == WOLFSSL_SERVER_END) ?
  4911. session->flags.srvSkipPartial :
  4912. session->flags.cliSkipPartial;
  4913. /* handle rollover of sequence */
  4914. if (tcpInfo->sequence < seqStart)
  4915. real = 0xffffffffU - seqStart + tcpInfo->sequence + 1;
  4916. TraceRelativeSequence(*expected, real);
  4917. if (real < *expected) {
  4918. if (real + *sslBytes > *expected) {
  4919. #ifdef WOLFSSL_ASYNC_CRYPT
  4920. if (session->sslServer->error != WC_PENDING_E &&
  4921. session->pendSeq != tcpInfo->sequence)
  4922. #endif
  4923. {
  4924. Trace(OVERLAP_DUPLICATE_STR);
  4925. }
  4926. /* The following conditional block is duplicated below. It is the
  4927. * same action but for a different setup case. If changing this
  4928. * block be sure to also update the block below. */
  4929. if (reassemblyList) {
  4930. int overlap = *expected - real;
  4931. word32 newEnd;
  4932. /* adjust to expected, remove duplicate */
  4933. *sslFrame += overlap;
  4934. *sslBytes = (*sslBytes > overlap) ? *sslBytes - overlap : 0;
  4935. newEnd = *expected + *sslBytes;
  4936. if (newEnd > reassemblyList->begin) {
  4937. int covered_data_len;
  4938. Trace(OVERLAP_REASSEMBLY_BEGIN_STR);
  4939. /* remove bytes already on reassembly list */
  4940. covered_data_len = newEnd - reassemblyList->begin;
  4941. *sslFrame += covered_data_len;
  4942. *sslBytes = (*sslBytes > covered_data_len) ?
  4943. *sslBytes - covered_data_len : 0;
  4944. }
  4945. if ((*sslBytes > 0) && (newEnd > reassemblyList->end)) {
  4946. Trace(OVERLAP_REASSEMBLY_END_STR);
  4947. /* may be past reassembly list end (could have more on list)
  4948. so try to add what's past the front->end */
  4949. AddToReassembly(session->flags.side, reassemblyList->end + 1,
  4950. *sslFrame + (reassemblyList->end - *expected + 1),
  4951. newEnd - reassemblyList->end, session, error);
  4952. }
  4953. }
  4954. else {
  4955. /* DUP overlap, allow */
  4956. if (*sslBytes > 0) {
  4957. skipPartial = 0; /* do not reset sslBytes */
  4958. }
  4959. }
  4960. ret = 0;
  4961. }
  4962. else {
  4963. /* This can happen with unseen acks, out of order packets, or
  4964. * possible spurious retransmission. */
  4965. if (*sslBytes > 0) {
  4966. /* If packet has data attempt to process packet, if hasn't
  4967. * already been ack'd during handshake */
  4968. if (
  4969. #ifdef WOLFSSL_ASYNC_CRYPT
  4970. session->sslServer->error != WC_PENDING_E &&
  4971. session->pendSeq != tcpInfo->sequence &&
  4972. #endif
  4973. FindPrevAck(session, real)) {
  4974. Trace(DUPLICATE_STR);
  4975. ret = 1;
  4976. }
  4977. else {
  4978. /* DUP: allow */
  4979. skipPartial = 0; /* do not reset sslBytes */
  4980. ret = 0;
  4981. }
  4982. }
  4983. else {
  4984. /* DUP empty, ignore */
  4985. ret = 1;
  4986. }
  4987. }
  4988. }
  4989. else if (real > *expected) {
  4990. Trace(OUT_OF_ORDER_STR);
  4991. if (*sslBytes > 0) {
  4992. int addResult = AddToReassembly(session->flags.side, real,
  4993. *sslFrame, *sslBytes, session, error);
  4994. ret = (skipPartial) ? 0 : addResult;
  4995. }
  4996. else if (tcpInfo->fin) {
  4997. ret = AddFinCapture(session, real);
  4998. }
  4999. }
  5000. else if (*sslBytes > 0) {
  5001. if (skipPartial) {
  5002. AddToReassembly(session->flags.side, real,
  5003. *sslFrame, *sslBytes, session, error);
  5004. ret = 0;
  5005. }
  5006. /* The following conditional block is duplicated above. It is the
  5007. * same action but for a different setup case. If changing this
  5008. * block be sure to also update the block above. */
  5009. else if (reassemblyList) {
  5010. word32 newEnd = *expected + *sslBytes;
  5011. if (newEnd > reassemblyList->begin) {
  5012. int covered_data_len;
  5013. Trace(OVERLAP_REASSEMBLY_BEGIN_STR);
  5014. /* remove bytes already on reassembly list */
  5015. covered_data_len = newEnd - reassemblyList->begin;
  5016. *sslFrame += covered_data_len;
  5017. *sslBytes = (*sslBytes > covered_data_len) ?
  5018. *sslBytes - covered_data_len : 0;
  5019. }
  5020. if ((*sslBytes > 0) && (newEnd > reassemblyList->end)) {
  5021. Trace(OVERLAP_REASSEMBLY_END_STR);
  5022. /* may be past reassembly list end (could have more on list)
  5023. so try to add what's past the front->end */
  5024. AddToReassembly(session->flags.side, reassemblyList->end + 1,
  5025. *sslFrame + (reassemblyList->end - *expected + 1),
  5026. newEnd - reassemblyList->end, session, error);
  5027. }
  5028. }
  5029. }
  5030. else {
  5031. /* no data present */
  5032. }
  5033. if (ret == 0) {
  5034. /* got expected sequence */
  5035. *expected += *sslBytes;
  5036. if (tcpInfo->fin)
  5037. *expected += 1;
  5038. }
  5039. if (*sslBytes > 0) {
  5040. AddAck(session, real);
  5041. }
  5042. if (*sslBytes > 0 && skipPartial) {
  5043. *sslBytes = 0;
  5044. }
  5045. return ret;
  5046. }
  5047. static int FindNextRecordInAssembly(SnifferSession* session,
  5048. const byte** sslFrame, int* sslBytes,
  5049. const byte** end, char* error)
  5050. {
  5051. PacketBuffer** front = (session->flags.side == WOLFSSL_SERVER_END) ?
  5052. &session->cliReassemblyList :
  5053. &session->srvReassemblyList;
  5054. PacketBuffer* curr = *front;
  5055. PacketBuffer* prev = NULL;
  5056. byte* skipPartial = (session->flags.side == WOLFSSL_SERVER_END) ?
  5057. &session->flags.srvSkipPartial :
  5058. &session->flags.cliSkipPartial;
  5059. int* reassemblyMemory = (session->flags.side == WOLFSSL_SERVER_END) ?
  5060. (int*)&session->cliReassemblyMemory :
  5061. (int*)&session->srvReassemblyMemory;
  5062. WOLFSSL* ssl = (session->flags.side == WOLFSSL_SERVER_END) ?
  5063. session->sslServer :
  5064. session->sslClient;
  5065. ProtocolVersion pv = ssl->version;
  5066. word32* expected = (session->flags.side == WOLFSSL_SERVER_END) ?
  5067. &session->cliExpected :
  5068. &session->srvExpected;
  5069. while (curr != NULL) {
  5070. *expected = curr->end + 1;
  5071. if (curr->data[0] == application_data &&
  5072. curr->data[1] == pv.major &&
  5073. curr->data[2] == pv.minor) {
  5074. if (ssl->buffers.inputBuffer.length > 0)
  5075. Trace(DROPPING_PARTIAL_RECORD);
  5076. *sslBytes = (int)(curr->end - curr->begin + 1);
  5077. if ( *sslBytes > (int)ssl->buffers.inputBuffer.bufferSize) {
  5078. if (GrowInputBuffer(ssl, *sslBytes, 0) < 0) {
  5079. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  5080. return -1;
  5081. }
  5082. }
  5083. XMEMCPY(ssl->buffers.inputBuffer.buffer, curr->data, *sslBytes);
  5084. *front = curr->next;
  5085. *reassemblyMemory -= *sslBytes;
  5086. FreePacketBuffer(curr);
  5087. ssl->buffers.inputBuffer.length = *sslBytes;
  5088. *sslFrame = ssl->buffers.inputBuffer.buffer;
  5089. *end = *sslFrame + *sslBytes;
  5090. *skipPartial = 0;
  5091. return 0;
  5092. }
  5093. else if (ssl->specs.cipher_type == block) {
  5094. int ivPos = (int)(curr->end - curr->begin -
  5095. ssl->specs.block_size + 1);
  5096. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes) {
  5097. #ifndef NO_AES
  5098. if (ivPos >= 0)
  5099. wc_AesSetIV(ssl->decrypt.aes, curr->data + ivPos);
  5100. #endif
  5101. }
  5102. else if (ssl->specs.bulk_cipher_algorithm == wolfssl_triple_des) {
  5103. #ifndef NO_DES3
  5104. if (ivPos >= 0)
  5105. wc_Des3_SetIV(ssl->decrypt.des3, curr->data + ivPos);
  5106. #endif
  5107. }
  5108. }
  5109. Trace(DROPPING_LOST_FRAG_STR);
  5110. #ifdef WOLFSSL_SNIFFER_STATS
  5111. INC_STAT(SnifferStats.sslDecodeFails);
  5112. #endif
  5113. prev = curr;
  5114. curr = curr->next;
  5115. *reassemblyMemory -= (int)(prev->end - prev->begin + 1);
  5116. FreePacketBuffer(prev);
  5117. }
  5118. *front = curr;
  5119. return 0;
  5120. }
  5121. static int FixSequence(TcpInfo* tcpInfo, SnifferSession* session)
  5122. {
  5123. word32* expected = (session->flags.side == WOLFSSL_SERVER_END) ?
  5124. &session->srvExpected : &session->cliExpected;
  5125. word32 seqStart = (session->flags.side == WOLFSSL_SERVER_END) ?
  5126. session->srvSeqStart : session->cliSeqStart;
  5127. PacketBuffer* list = (session->flags.side == WOLFSSL_SERVER_END) ?
  5128. session->srvReassemblyList :
  5129. session->cliReassemblyList;
  5130. byte* skipPartial = (session->flags.side != WOLFSSL_SERVER_END) ?
  5131. &session->flags.srvSkipPartial :
  5132. &session->flags.cliSkipPartial;
  5133. *skipPartial = 1;
  5134. if (list != NULL)
  5135. *expected = list->begin;
  5136. else
  5137. *expected = tcpInfo->ackNumber - seqStart;
  5138. return 1;
  5139. }
  5140. /* Check latest ack number for missing packets
  5141. return 0 ok, <0 on error */
  5142. static int CheckAck(TcpInfo* tcpInfo, SnifferSession* session)
  5143. {
  5144. if (tcpInfo->ack) {
  5145. word32 seqStart = (session->flags.side == WOLFSSL_SERVER_END) ?
  5146. session->srvSeqStart :session->cliSeqStart;
  5147. word32 real = tcpInfo->ackNumber - seqStart;
  5148. word32 expected = (session->flags.side == WOLFSSL_SERVER_END) ?
  5149. session->srvExpected : session->cliExpected;
  5150. /* handle rollover of sequence */
  5151. if (tcpInfo->ackNumber < seqStart)
  5152. real = 0xffffffffU - seqStart + tcpInfo->ackNumber + 1;
  5153. TraceAck(real, expected);
  5154. if (real > expected)
  5155. return -1; /* we missed a packet, ACKing data we never saw */
  5156. }
  5157. return 0;
  5158. }
  5159. /* Check TCP Sequence status */
  5160. /* returns 0 on success (continue), -1 on error, 1 on success (end) */
  5161. static int CheckSequence(IpInfo* ipInfo, TcpInfo* tcpInfo,
  5162. SnifferSession* session, int* sslBytes,
  5163. const byte** sslFrame, char* error)
  5164. {
  5165. int actualLen;
  5166. byte* ackFault = (session->flags.side == WOLFSSL_SERVER_END) ?
  5167. &session->flags.cliAckFault :
  5168. &session->flags.srvAckFault;
  5169. #ifdef WOLFSSL_ASYNC_CRYPT
  5170. if (session->sslServer->error == 0 && session->pendSeq != 0 &&
  5171. session->pendSeq == tcpInfo->sequence) {
  5172. return 0; /* ready to process, but skip sequence checking below (already done) */
  5173. }
  5174. /* check if this session is pending */
  5175. else if (session->pendSeq != 0 && session->pendSeq != tcpInfo->sequence) {
  5176. return WC_PENDING_E;
  5177. }
  5178. #endif
  5179. /* init SEQ from server to client - if not ack fault */
  5180. if (tcpInfo->syn && tcpInfo->ack && !*ackFault) {
  5181. session->srvSeqStart = tcpInfo->sequence;
  5182. session->srvExpected = 1;
  5183. TraceServerSyn(tcpInfo->sequence);
  5184. return 1;
  5185. }
  5186. /* adjust potential ethernet trailer */
  5187. actualLen = ipInfo->total - ipInfo->length - tcpInfo->length;
  5188. if (*sslBytes > actualLen) {
  5189. *sslBytes = actualLen;
  5190. }
  5191. TraceSequence(tcpInfo->sequence, *sslBytes);
  5192. if (CheckAck(tcpInfo, session) < 0) {
  5193. if (!RecoveryEnabled) {
  5194. #ifndef WOLFSSL_SNIFFER_NO_RECOVERY
  5195. UpdateMissedDataSessions();
  5196. #endif
  5197. SetError(ACK_MISSED_STR, error, session, FATAL_ERROR_STATE);
  5198. return -1;
  5199. }
  5200. else {
  5201. SetError(ACK_MISSED_STR, error, session, 0);
  5202. if (*ackFault == 0) {
  5203. *ackFault = 1;
  5204. #ifndef WOLFSSL_SNIFFER_NO_RECOVERY
  5205. UpdateMissedDataSessions();
  5206. #endif
  5207. }
  5208. return FixSequence(tcpInfo, session);
  5209. }
  5210. }
  5211. if (*ackFault) {
  5212. Trace(CLEAR_ACK_FAULT);
  5213. *ackFault = 0;
  5214. }
  5215. return AdjustSequence(tcpInfo, session, sslBytes, sslFrame, error);
  5216. }
  5217. /* Check Status before record processing */
  5218. /* returns 0 on success (continue), -1 on error, 1 on success (end) */
  5219. static int CheckPreRecord(IpInfo* ipInfo, TcpInfo* tcpInfo,
  5220. const byte** sslFrame, SnifferSession** pSession,
  5221. int* sslBytes, const byte** end,
  5222. void* vChain, word32 chainSz, char* error)
  5223. {
  5224. word32 length;
  5225. SnifferSession* session = *pSession;
  5226. WOLFSSL* ssl = (session->flags.side == WOLFSSL_SERVER_END) ?
  5227. session->sslServer : session->sslClient;
  5228. byte skipPartial = (session->flags.side == WOLFSSL_SERVER_END) ?
  5229. session->flags.srvSkipPartial :
  5230. session->flags.cliSkipPartial;
  5231. #ifdef WOLFSSL_ASYNC_CRYPT
  5232. /* if this is a pending async packet do not "grow" on partial (we already did) */
  5233. if (session->pendSeq == tcpInfo->sequence) {
  5234. if (session->sslServer->error == WC_PENDING_E) {
  5235. return 0; /* don't check pre-record again */
  5236. }
  5237. /* if record check already done then restore, otherwise process normal */
  5238. if (ssl->buffers.inputBuffer.length > 0) {
  5239. *sslBytes = ssl->buffers.inputBuffer.length;
  5240. *sslFrame = ssl->buffers.inputBuffer.buffer;
  5241. *end = *sslFrame + *sslBytes;
  5242. return 0;
  5243. }
  5244. }
  5245. #endif
  5246. /* remove SnifferSession on 2nd FIN or RST */
  5247. if (tcpInfo->fin || tcpInfo->rst) {
  5248. /* flag FIN and RST */
  5249. if (tcpInfo->fin)
  5250. session->flags.finCount += 1;
  5251. else if (tcpInfo->rst)
  5252. session->flags.finCount += 2;
  5253. if (session->flags.finCount >= 2) {
  5254. RemoveSession(session, ipInfo, tcpInfo, 0);
  5255. *pSession = NULL;
  5256. return 1;
  5257. }
  5258. }
  5259. if (session->flags.fatalError == FATAL_ERROR_STATE) {
  5260. SetError(FATAL_ERROR_STR, error, NULL, 0);
  5261. return -1;
  5262. }
  5263. if (skipPartial) {
  5264. if (FindNextRecordInAssembly(session,
  5265. sslFrame, sslBytes, end, error) < 0) {
  5266. return -1;
  5267. }
  5268. }
  5269. if (*sslBytes <= 0) {
  5270. Trace(NO_DATA_STR);
  5271. return 1;
  5272. }
  5273. /* if current partial data, add to end of partial */
  5274. /* if skipping, the data is already at the end of partial */
  5275. length = ssl->buffers.inputBuffer.length;
  5276. if ( !skipPartial && length ) {
  5277. Trace(PARTIAL_ADD_STR);
  5278. if ( (*sslBytes + length) > ssl->buffers.inputBuffer.bufferSize) {
  5279. if (GrowInputBuffer(ssl, *sslBytes, length) < 0) {
  5280. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  5281. return -1;
  5282. }
  5283. }
  5284. if (vChain == NULL) {
  5285. XMEMCPY(&ssl->buffers.inputBuffer.buffer[length],
  5286. *sslFrame, *sslBytes);
  5287. *sslBytes += length;
  5288. ssl->buffers.inputBuffer.length = *sslBytes;
  5289. *sslFrame = ssl->buffers.inputBuffer.buffer;
  5290. *end = *sslFrame + *sslBytes;
  5291. }
  5292. else {
  5293. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  5294. struct iovec* chain = (struct iovec*)vChain;
  5295. word32 i, offset, headerSz, qty, remainder;
  5296. Trace(CHAIN_INPUT_STR);
  5297. headerSz = (word32)((const byte*)*sslFrame - (const byte*)chain[0].iov_base);
  5298. remainder = *sslBytes;
  5299. if ( (*sslBytes + length) > ssl->buffers.inputBuffer.bufferSize) {
  5300. if (GrowInputBuffer(ssl, *sslBytes, length) < 0) {
  5301. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  5302. return -1;
  5303. }
  5304. }
  5305. qty = min(*sslBytes, (word32)chain[0].iov_len - headerSz);
  5306. XMEMCPY(&ssl->buffers.inputBuffer.buffer[length],
  5307. (byte*)chain[0].iov_base + headerSz, qty);
  5308. offset = length;
  5309. for (i = 1; i < chainSz; i++) {
  5310. offset += qty;
  5311. remainder -= qty;
  5312. if (chain[i].iov_len > remainder)
  5313. qty = remainder;
  5314. else
  5315. qty = (word32)chain[i].iov_len;
  5316. XMEMCPY(ssl->buffers.inputBuffer.buffer + offset,
  5317. chain[i].iov_base, qty);
  5318. }
  5319. *sslBytes += length;
  5320. ssl->buffers.inputBuffer.length = *sslBytes;
  5321. *sslFrame = ssl->buffers.inputBuffer.buffer;
  5322. *end = *sslFrame + *sslBytes;
  5323. #endif
  5324. (void)chainSz;
  5325. }
  5326. }
  5327. if (session->flags.clientHello == 0 && **sslFrame != handshake) {
  5328. /* Sanity check the packet for an old style client hello. */
  5329. int rhSize = (((*sslFrame)[0] & 0x7f) << 8) | ((*sslFrame)[1]);
  5330. if ((rhSize <= (*sslBytes - 2)) &&
  5331. (*sslFrame)[2] == OLD_HELLO_ID && (*sslFrame)[3] == SSLv3_MAJOR) {
  5332. #ifdef OLD_HELLO_ALLOWED
  5333. int ret = DoOldHello(session, *sslFrame, &rhSize, sslBytes, error);
  5334. if (ret < 0)
  5335. return -1; /* error already set */
  5336. if (*sslBytes <= 0)
  5337. return 1;
  5338. #endif
  5339. }
  5340. else {
  5341. #ifdef STARTTLS_ALLOWED
  5342. if (ssl->buffers.inputBuffer.dynamicFlag) {
  5343. ssl->buffers.inputBuffer.length = 0;
  5344. ShrinkInputBuffer(ssl, NO_FORCED_FREE);
  5345. }
  5346. return 1;
  5347. #endif
  5348. }
  5349. }
  5350. return 0;
  5351. }
  5352. /* See if input on the reassembly list is ready for consuming */
  5353. /* returns 1 for TRUE, 0 for FALSE */
  5354. static int HaveMoreInput(SnifferSession* session, const byte** sslFrame,
  5355. int* sslBytes, const byte** end, char* error)
  5356. {
  5357. /* sequence and reassembly based on from, not to */
  5358. int moreInput = 0;
  5359. PacketBuffer** front = (session->flags.side == WOLFSSL_SERVER_END) ?
  5360. &session->cliReassemblyList : &session->srvReassemblyList;
  5361. word32* expected = (session->flags.side == WOLFSSL_SERVER_END) ?
  5362. &session->cliExpected : &session->srvExpected;
  5363. /* buffer is on receiving end */
  5364. word32* length = (session->flags.side == WOLFSSL_SERVER_END) ?
  5365. &session->sslServer->buffers.inputBuffer.length :
  5366. &session->sslClient->buffers.inputBuffer.length;
  5367. byte** myBuffer = (session->flags.side == WOLFSSL_SERVER_END) ?
  5368. &session->sslServer->buffers.inputBuffer.buffer :
  5369. &session->sslClient->buffers.inputBuffer.buffer;
  5370. word32* bufferSize = (session->flags.side == WOLFSSL_SERVER_END) ?
  5371. &session->sslServer->buffers.inputBuffer.bufferSize :
  5372. &session->sslClient->buffers.inputBuffer.bufferSize;
  5373. WOLFSSL* ssl = (session->flags.side == WOLFSSL_SERVER_END) ?
  5374. session->sslServer : session->sslClient;
  5375. word32* reassemblyMemory = (session->flags.side == WOLFSSL_SERVER_END) ?
  5376. &session->cliReassemblyMemory : &session->srvReassemblyMemory;
  5377. while (*front && ((*front)->begin == *expected) ) {
  5378. int room = (int)(*bufferSize - *length);
  5379. int packetLen = (int)((*front)->end - (*front)->begin + 1);
  5380. if (packetLen > room && *bufferSize < MAX_INPUT_SZ) {
  5381. if (GrowInputBuffer(ssl, packetLen, *length) < 0) {
  5382. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  5383. return 0;
  5384. }
  5385. room = *bufferSize - *length; /* bufferSize is now bigger */
  5386. }
  5387. if (packetLen <= room) {
  5388. PacketBuffer* del = *front;
  5389. byte* buf = *myBuffer;
  5390. XMEMCPY(&buf[*length], (*front)->data, packetLen);
  5391. *length += packetLen;
  5392. *expected += packetLen;
  5393. /* remove used packet */
  5394. *front = (*front)->next;
  5395. *reassemblyMemory -= packetLen;
  5396. FreePacketBuffer(del);
  5397. moreInput = 1;
  5398. }
  5399. else
  5400. break;
  5401. }
  5402. if (moreInput) {
  5403. *sslFrame = *myBuffer;
  5404. *sslBytes = *length;
  5405. *end = *myBuffer + *length;
  5406. }
  5407. return moreInput;
  5408. }
  5409. /* Process Message(s) from sslFrame */
  5410. /* return Number of bytes on success, 0 for no data yet, and -1 on error */
  5411. static int ProcessMessage(const byte* sslFrame, SnifferSession* session,
  5412. int sslBytes, byte** data, const byte* end,
  5413. void* ctx, char* error)
  5414. {
  5415. const byte* sslBegin = sslFrame;
  5416. const byte* recordEnd; /* end of record indicator */
  5417. const byte* inRecordEnd; /* indicator from input stream not decrypt */
  5418. RecordLayerHeader rh;
  5419. int rhSize;
  5420. int ret;
  5421. int errCode = 0;
  5422. int decoded = 0; /* bytes stored for user in data */
  5423. int notEnough; /* notEnough bytes yet flag */
  5424. int decrypted = 0; /* was current msg decrypted */
  5425. WOLFSSL* ssl = (session->flags.side == WOLFSSL_SERVER_END) ?
  5426. session->sslServer : session->sslClient;
  5427. doMessage:
  5428. notEnough = 0;
  5429. rhSize = 0;
  5430. if (sslBytes < 0) {
  5431. SetError(PACKET_HDR_SHORT_STR, error, session, FATAL_ERROR_STATE);
  5432. return -1;
  5433. }
  5434. if (sslBytes >= RECORD_HEADER_SZ) {
  5435. if (GetRecordHeader(sslFrame, &rh, &rhSize) != 0) {
  5436. /* ignore packet if record header errors */
  5437. SetError(BAD_RECORD_HDR_STR, error, session, 0);
  5438. return 0;
  5439. }
  5440. }
  5441. else {
  5442. notEnough = 1;
  5443. }
  5444. if (notEnough || rhSize > (sslBytes - RECORD_HEADER_SZ)) {
  5445. /* don't have enough input yet to process full SSL record */
  5446. Trace(PARTIAL_INPUT_STR);
  5447. /* store partial if not there already or we advanced */
  5448. if (ssl->buffers.inputBuffer.length == 0 || sslBegin != sslFrame) {
  5449. if (sslBytes > (int)ssl->buffers.inputBuffer.bufferSize) {
  5450. if (GrowInputBuffer(ssl, sslBytes, 0) < 0) {
  5451. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  5452. return -1;
  5453. }
  5454. }
  5455. XMEMMOVE(ssl->buffers.inputBuffer.buffer, sslFrame, sslBytes);
  5456. ssl->buffers.inputBuffer.length = sslBytes;
  5457. }
  5458. if (HaveMoreInput(session, &sslFrame, &sslBytes, &end, error))
  5459. goto doMessage;
  5460. return decoded;
  5461. }
  5462. sslFrame += RECORD_HEADER_SZ;
  5463. sslBytes -= RECORD_HEADER_SZ;
  5464. recordEnd = sslFrame + rhSize; /* may have more than one record */
  5465. inRecordEnd = recordEnd;
  5466. /* Make sure cipher is on for client, if we get an application data packet
  5467. * and handshake is done for server. This workaround is required if client
  5468. * handshake packets were missed, retransmitted or sent out of order. */
  5469. if ((enum ContentType)rh.type == application_data &&
  5470. ssl->options.handShakeDone && session->flags.serverCipherOn) {
  5471. session->flags.clientCipherOn = 1;
  5472. session->sslClient->options.handShakeState = HANDSHAKE_DONE;
  5473. session->sslClient->options.handShakeDone = 1;
  5474. }
  5475. /* decrypt if needed */
  5476. if ((session->flags.side == WOLFSSL_SERVER_END &&
  5477. session->flags.serverCipherOn)
  5478. || (session->flags.side == WOLFSSL_CLIENT_END &&
  5479. session->flags.clientCipherOn)) {
  5480. int ivAdvance = 0; /* TLSv1.1 advance amount */
  5481. /* change_cipher_spec is not encrypted */
  5482. if (rh.type == change_cipher_spec) {
  5483. goto doPart;
  5484. }
  5485. if (ssl->decrypt.setup != 1) {
  5486. SetError(DECRYPT_KEYS_NOT_SETUP, error, session, FATAL_ERROR_STATE);
  5487. return -1;
  5488. }
  5489. if (CheckAvailableSize(ssl, rhSize) < 0) {
  5490. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  5491. return -1;
  5492. }
  5493. sslFrame = DecryptMessage(ssl, sslFrame, rhSize,
  5494. ssl->buffers.outputBuffer.buffer, &errCode,
  5495. &ivAdvance, &rh);
  5496. recordEnd = sslFrame - ivAdvance + rhSize; /* sslFrame moved so
  5497. should recordEnd */
  5498. decrypted = 1;
  5499. #ifdef WOLFSSL_SNIFFER_STATS
  5500. if (errCode != 0) {
  5501. INC_STAT(SnifferStats.sslKeyFails);
  5502. }
  5503. else {
  5504. LOCK_STAT();
  5505. NOLOCK_INC_STAT(SnifferStats.sslDecryptedPackets);
  5506. NOLOCK_ADD_TO_STAT(SnifferStats.sslDecryptedBytes, sslBytes);
  5507. UNLOCK_STAT();
  5508. }
  5509. #endif
  5510. if (errCode != 0) {
  5511. if ((enum ContentType)rh.type == application_data) {
  5512. SetError(BAD_DECRYPT, error, session, FATAL_ERROR_STATE);
  5513. return -1;
  5514. }
  5515. /* do not end session for failures on handshake packets */
  5516. return 0;
  5517. }
  5518. }
  5519. doPart:
  5520. switch ((enum ContentType)rh.type) {
  5521. case handshake:
  5522. {
  5523. int startIdx = sslBytes;
  5524. int used;
  5525. Trace(GOT_HANDSHAKE_STR);
  5526. ret = DoHandShake(sslFrame, &sslBytes, session, error, rhSize);
  5527. #ifdef WOLFSSL_ASYNC_CRYPT
  5528. if (ret == WC_PENDING_E)
  5529. return ret;
  5530. #endif
  5531. if (ret != 0 || sslBytes > startIdx) {
  5532. if (session->flags.fatalError == 0)
  5533. SetError(BAD_HANDSHAKE_STR, error, session,
  5534. FATAL_ERROR_STATE);
  5535. return -1;
  5536. }
  5537. /* DoHandShake now fully decrements sslBytes to remaining */
  5538. used = startIdx - sslBytes;
  5539. sslFrame += used;
  5540. if (decrypted)
  5541. sslFrame += ssl->keys.padSz;
  5542. }
  5543. break;
  5544. case change_cipher_spec:
  5545. if (session->flags.side == WOLFSSL_SERVER_END) {
  5546. #ifdef WOLFSSL_TLS13
  5547. if (IsAtLeastTLSv1_3(session->sslServer->version) && session->srvKs.key_len == 0) {
  5548. session->flags.serverCipherOn = 0;
  5549. }
  5550. else
  5551. #endif
  5552. {
  5553. session->flags.serverCipherOn = 1;
  5554. }
  5555. }
  5556. else
  5557. session->flags.clientCipherOn = 1;
  5558. Trace(GOT_CHANGE_CIPHER_STR);
  5559. ssl->options.handShakeState = HANDSHAKE_DONE;
  5560. ssl->options.handShakeDone = 1;
  5561. sslFrame += 1;
  5562. sslBytes -= 1;
  5563. break;
  5564. case application_data:
  5565. Trace(GOT_APP_DATA_STR);
  5566. {
  5567. word32 inOutIdx = 0;
  5568. ret = DoApplicationData(ssl, (byte*)sslFrame, &inOutIdx, SNIFF);
  5569. if (ret == 0) {
  5570. ret = ssl->buffers.clearOutputBuffer.length;
  5571. TraceGotData(ret);
  5572. if (ret) { /* may be blank message */
  5573. if (data != NULL) {
  5574. byte* tmpData; /* don't leak on realloc free */
  5575. /* add an extra byte at end of allocation in case
  5576. * user wants to null terminate plaintext */
  5577. tmpData = (byte*)XREALLOC(*data, decoded + ret + 1,
  5578. NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5579. if (tmpData == NULL) {
  5580. ForceZero(*data, decoded);
  5581. XFREE(*data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5582. *data = NULL;
  5583. SetError(MEMORY_STR, error, session,
  5584. FATAL_ERROR_STATE);
  5585. return -1;
  5586. }
  5587. *data = tmpData;
  5588. XMEMCPY(*data + decoded,
  5589. ssl->buffers.clearOutputBuffer.buffer, ret);
  5590. }
  5591. else {
  5592. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  5593. if (StoreDataCb) {
  5594. const byte* buf;
  5595. word32 offset = 0;
  5596. word32 bufSz;
  5597. int stored;
  5598. buf = ssl->buffers.clearOutputBuffer.buffer;
  5599. bufSz = ssl->buffers.clearOutputBuffer.length;
  5600. do {
  5601. stored = StoreDataCb(buf, bufSz, offset,
  5602. ctx);
  5603. if (stored <= 0) {
  5604. return -1;
  5605. }
  5606. offset += stored;
  5607. } while (offset < bufSz);
  5608. }
  5609. else {
  5610. SetError(STORE_DATA_CB_MISSING_STR, error,
  5611. session, FATAL_ERROR_STATE);
  5612. return -1;
  5613. }
  5614. #else
  5615. (void)ctx;
  5616. SetError(NO_DATA_DEST_STR, error, session,
  5617. FATAL_ERROR_STATE);
  5618. return -1;
  5619. #endif
  5620. }
  5621. TraceAddedData(ret, decoded);
  5622. decoded += ret;
  5623. ssl->buffers.clearOutputBuffer.length = 0;
  5624. }
  5625. }
  5626. else {
  5627. /* set error, but do not treat fatal */
  5628. SetError(BAD_APP_DATA_STR, error,session, 0);
  5629. return -1;
  5630. }
  5631. if (ssl->buffers.outputBuffer.dynamicFlag)
  5632. ShrinkOutputBuffer(ssl);
  5633. sslFrame += inOutIdx;
  5634. sslBytes -= inOutIdx;
  5635. }
  5636. break;
  5637. case alert:
  5638. Trace(GOT_ALERT_STR);
  5639. #ifdef WOLFSSL_SNIFFER_STATS
  5640. INC_STAT(SnifferStats.sslAlerts);
  5641. #endif
  5642. sslFrame += rhSize;
  5643. sslBytes -= rhSize;
  5644. break;
  5645. #ifdef WOLFSSL_DTLS13
  5646. case ack:
  5647. /* TODO */
  5648. #endif /* WOLFSSL_DTLS13 */
  5649. case no_type:
  5650. default:
  5651. SetError(GOT_UNKNOWN_RECORD_STR, error, session, FATAL_ERROR_STATE);
  5652. return -1;
  5653. }
  5654. /* do we have another msg in record ? */
  5655. if (sslFrame < recordEnd) {
  5656. Trace(ANOTHER_MSG_STR);
  5657. goto doPart;
  5658. }
  5659. /* back to input stream instead of potential decrypt buffer */
  5660. recordEnd = inRecordEnd;
  5661. /* do we have more records ? */
  5662. if (recordEnd < end) {
  5663. Trace(ANOTHER_MSG_STR);
  5664. sslFrame = recordEnd;
  5665. sslBytes = (int)(end - recordEnd);
  5666. goto doMessage;
  5667. }
  5668. /* clear used input */
  5669. ssl->buffers.inputBuffer.length = 0;
  5670. /* could have more input ready now */
  5671. if (HaveMoreInput(session, &sslFrame, &sslBytes, &end, error))
  5672. goto doMessage;
  5673. if (ssl->buffers.inputBuffer.dynamicFlag)
  5674. ShrinkInputBuffer(ssl, NO_FORCED_FREE);
  5675. return decoded;
  5676. }
  5677. /* See if we need to process any pending FIN captures */
  5678. /* Return 0=normal, else = session removed */
  5679. static int CheckFinCapture(IpInfo* ipInfo, TcpInfo* tcpInfo,
  5680. SnifferSession* session)
  5681. {
  5682. int ret = 0;
  5683. if (session->finCapture.cliFinSeq && session->finCapture.cliFinSeq <=
  5684. session->cliExpected) {
  5685. if (session->finCapture.cliCounted == 0) {
  5686. session->flags.finCount += 1;
  5687. session->finCapture.cliCounted = 1;
  5688. TraceClientFin(session->finCapture.cliFinSeq, session->cliExpected);
  5689. }
  5690. }
  5691. if (session->finCapture.srvFinSeq && session->finCapture.srvFinSeq <=
  5692. session->srvExpected) {
  5693. if (session->finCapture.srvCounted == 0) {
  5694. session->flags.finCount += 1;
  5695. session->finCapture.srvCounted = 1;
  5696. TraceServerFin(session->finCapture.srvFinSeq, session->srvExpected);
  5697. }
  5698. }
  5699. if (session->flags.finCount >= 2) {
  5700. RemoveSession(session, ipInfo, tcpInfo, 0);
  5701. ret = 1;
  5702. }
  5703. return ret;
  5704. }
  5705. /* If session is in fatal error state free resources now
  5706. return true if removed, 0 otherwise */
  5707. static int RemoveFatalSession(IpInfo* ipInfo, TcpInfo* tcpInfo,
  5708. SnifferSession* session, char* error)
  5709. {
  5710. if (session && session->flags.fatalError == FATAL_ERROR_STATE) {
  5711. if (!session->verboseErr) {
  5712. SetError(FATAL_ERROR_STR, error, NULL, 0);
  5713. }
  5714. RemoveSession(session, ipInfo, tcpInfo, 0);
  5715. return 1;
  5716. }
  5717. return 0;
  5718. }
  5719. int ssl_DecodePacket_GetStream(SnifferStreamInfo* info, const byte* packet,
  5720. int length, char* error )
  5721. {
  5722. TcpInfo tcpInfo;
  5723. IpInfo ipInfo;
  5724. const byte* sslFrame = NULL;
  5725. int sslBytes = 0;
  5726. XMEMSET(&tcpInfo, 0, sizeof(tcpInfo));
  5727. XMEMSET(&ipInfo, 0, sizeof(ipInfo));
  5728. if (CheckHeaders(&ipInfo, &tcpInfo, packet, length, &sslFrame, &sslBytes,
  5729. error, 0, 0) != 0) {
  5730. return WOLFSSL_SNIFFER_ERROR;
  5731. }
  5732. info->src = ipInfo.src;
  5733. info->dst = ipInfo.dst;
  5734. info->srcPort = tcpInfo.srcPort;
  5735. info->dstPort = tcpInfo.dstPort;
  5736. return 0;
  5737. }
  5738. /* Passes in an IP/TCP packet for decoding (ethernet/localhost frame) removed */
  5739. /* returns Number of bytes on success, 0 for no data yet, and
  5740. * WOLFSSL_SNIFFER_ERROR on error and WOLFSSL_SNIFFER_FATAL_ERROR on fatal state
  5741. * error
  5742. */
  5743. static int ssl_DecodePacketInternal(const byte* packet, int length, int isChain,
  5744. byte** data, SSLInfo* sslInfo,
  5745. void* ctx, char* error, int asyncOkay)
  5746. {
  5747. TcpInfo tcpInfo;
  5748. IpInfo ipInfo;
  5749. const byte* sslFrame;
  5750. const byte* end;
  5751. int sslBytes; /* ssl bytes unconsumed */
  5752. int ret;
  5753. SnifferSession* session = NULL;
  5754. void* vChain = NULL;
  5755. word32 chainSz = 0;
  5756. if (isChain) {
  5757. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  5758. struct iovec* chain;
  5759. word32 i;
  5760. vChain = (void*)packet;
  5761. chainSz = (word32)length;
  5762. chain = (struct iovec*)vChain;
  5763. length = 0;
  5764. for (i = 0; i < chainSz; i++)
  5765. length += chain[i].iov_len;
  5766. packet = (const byte*)chain[0].iov_base;
  5767. #else
  5768. SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
  5769. return WOLFSSL_SNIFFER_ERROR;
  5770. #endif
  5771. }
  5772. if (CheckHeaders(&ipInfo, &tcpInfo, packet, length, &sslFrame, &sslBytes,
  5773. error, 1, 1) != 0) {
  5774. return WOLFSSL_SNIFFER_ERROR;
  5775. }
  5776. end = sslFrame + sslBytes;
  5777. ret = CheckSession(&ipInfo, &tcpInfo, sslBytes, &session, error);
  5778. if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error))
  5779. return WOLFSSL_SNIFFER_FATAL_ERROR;
  5780. #ifdef WOLFSSL_ASYNC_CRYPT
  5781. else if (ret == WC_PENDING_E) return WC_PENDING_E;
  5782. #endif
  5783. else if (ret == -1) return WOLFSSL_SNIFFER_ERROR;
  5784. else if (ret == 1) {
  5785. #ifdef WOLFSSL_SNIFFER_STATS
  5786. if (sslBytes > 0) {
  5787. LOCK_STAT();
  5788. NOLOCK_INC_STAT(SnifferStats.sslEncryptedPackets);
  5789. NOLOCK_ADD_TO_STAT(SnifferStats.sslEncryptedBytes, sslBytes);
  5790. UNLOCK_STAT();
  5791. }
  5792. else {
  5793. INC_STAT(SnifferStats.sslDecryptedPackets);
  5794. }
  5795. #endif
  5796. return 0; /* done for now */
  5797. }
  5798. #ifdef WOLFSSL_ASYNC_CRYPT
  5799. session->userCtx = ctx;
  5800. #endif
  5801. ret = CheckSequence(&ipInfo, &tcpInfo, session, &sslBytes, &sslFrame,error);
  5802. if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error))
  5803. return WOLFSSL_SNIFFER_FATAL_ERROR;
  5804. else if (ret == -1) return WOLFSSL_SNIFFER_ERROR;
  5805. else if (ret == 1) {
  5806. #ifdef WOLFSSL_SNIFFER_STATS
  5807. INC_STAT(SnifferStats.sslDecryptedPackets);
  5808. #endif
  5809. return 0; /* done for now */
  5810. }
  5811. else if (ret != 0) {
  5812. /* return specific error case */
  5813. return ret;
  5814. }
  5815. ret = CheckPreRecord(&ipInfo, &tcpInfo, &sslFrame, &session, &sslBytes,
  5816. &end, vChain, chainSz, error);
  5817. if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error))
  5818. return WOLFSSL_SNIFFER_FATAL_ERROR;
  5819. else if (ret == -1) return WOLFSSL_SNIFFER_ERROR;
  5820. else if (ret == 1) {
  5821. #ifdef WOLFSSL_SNIFFER_STATS
  5822. INC_STAT(SnifferStats.sslDecryptedPackets);
  5823. #endif
  5824. return 0; /* done for now */
  5825. }
  5826. #ifdef WOLFSSL_ASYNC_CRYPT
  5827. /* make sure this server was polled */
  5828. if (asyncOkay && session->sslServer->error == WC_PENDING_E &&
  5829. !session->flags.wasPolled) {
  5830. return WC_PENDING_E;
  5831. }
  5832. #endif
  5833. #ifdef WOLFSSL_SNIFFER_STATS
  5834. #ifdef WOLFSSL_ASYNC_CRYPT
  5835. if (session->sslServer->error != WC_PENDING_E)
  5836. #endif
  5837. {
  5838. if (sslBytes > 0) {
  5839. LOCK_STAT();
  5840. NOLOCK_INC_STAT(SnifferStats.sslEncryptedPackets);
  5841. NOLOCK_ADD_TO_STAT(SnifferStats.sslEncryptedBytes, sslBytes);
  5842. UNLOCK_STAT();
  5843. }
  5844. else {
  5845. INC_STAT(SnifferStats.sslDecryptedPackets);
  5846. }
  5847. }
  5848. #endif
  5849. #ifdef WOLFSSL_ASYNC_CRYPT
  5850. do {
  5851. #endif
  5852. ret = ProcessMessage(sslFrame, session, sslBytes, data, end, ctx, error);
  5853. session->sslServer->error = ret;
  5854. #ifdef WOLFSSL_ASYNC_CRYPT
  5855. /* capture the seq pending for this session */
  5856. if (ret == WC_PENDING_E) {
  5857. session->flags.wasPolled = 0;
  5858. session->pendSeq = tcpInfo.sequence;
  5859. if (!asyncOkay || CryptoDeviceId == INVALID_DEVID) {
  5860. /* If devId has not been set then we need to block here by
  5861. * polling and looping */
  5862. wolfSSL_AsyncPoll(session->sslServer, WOLF_POLL_FLAG_CHECK_HW);
  5863. }
  5864. else {
  5865. return ret; /* return to caller */
  5866. }
  5867. }
  5868. else {
  5869. session->pendSeq = 0;
  5870. }
  5871. } while (ret == WC_PENDING_E);
  5872. #else
  5873. (void)asyncOkay;
  5874. #endif
  5875. if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error))
  5876. return WOLFSSL_SNIFFER_FATAL_ERROR;
  5877. if (CheckFinCapture(&ipInfo, &tcpInfo, session) == 0) {
  5878. CopySessionInfo(session, sslInfo);
  5879. }
  5880. return ret;
  5881. }
  5882. /* Passes in an IP/TCP packet for decoding (ethernet/localhost frame) removed */
  5883. /* returns Number of bytes on success, 0 for no data yet, WOLFSSL_SNIFFER_ERROR.
  5884. * on error and WOLFSSL_SNIFFER_FATAL_ERROR on fatal state error */
  5885. /* Also returns Session Info if available */
  5886. int ssl_DecodePacketWithSessionInfo(const unsigned char* packet, int length,
  5887. unsigned char** data, SSLInfo* sslInfo, char* error)
  5888. {
  5889. return ssl_DecodePacketInternal(packet, length, 0, data, sslInfo,
  5890. NULL, error, 0);
  5891. }
  5892. /* Passes in an IP/TCP packet for decoding (ethernet/localhost frame) removed */
  5893. /* returns Number of bytes on success, 0 for no data yet, WOLFSSL_SNIFFER_ERROR.
  5894. * on error and WOLFSSL_SNIFFER_FATAL_ERROR on fatal state error */
  5895. int ssl_DecodePacket(const byte* packet, int length, byte** data, char* error)
  5896. {
  5897. return ssl_DecodePacketInternal(packet, length, 0, data, NULL, NULL,
  5898. error, 0);
  5899. }
  5900. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  5901. /* returns Number of bytes on success, 0 for no data yet, WOLFSSL_SNIFFER_ERROR.
  5902. * on error and WOLFSSL_SNIFFER_FATAL_ERROR on fatal state error */
  5903. int ssl_DecodePacketWithSessionInfoStoreData(const unsigned char* packet,
  5904. int length, void* ctx, SSLInfo* sslInfo, char* error)
  5905. {
  5906. return ssl_DecodePacketInternal(packet, length, 0, NULL, sslInfo,
  5907. ctx, error, 0);
  5908. }
  5909. #endif
  5910. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  5911. /* returns Number of bytes on success, 0 for no data yet, WOLFSSL_SNIFFER_ERROR.
  5912. * on error and WOLFSSL_SNIFFER_FATAL_ERROR on fatal state error */
  5913. int ssl_DecodePacketWithChain(void* vChain, word32 chainSz, byte** data,
  5914. char* error)
  5915. {
  5916. return ssl_DecodePacketInternal((const byte*)vChain, chainSz, 1, data,
  5917. NULL, NULL, error, 0);
  5918. }
  5919. #endif
  5920. #if defined(WOLFSSL_SNIFFER_CHAIN_INPUT) && \
  5921. defined(WOLFSSL_SNIFFER_STORE_DATA_CB)
  5922. /*
  5923. * returns WOLFSSL_SNIFFER_ERROR on error and WOLFSSL_SNIFFER_FATAL_ERROR on
  5924. * fatal state error
  5925. */
  5926. int ssl_DecodePacketWithChainSessionInfoStoreData(void* vChain, word32 chainSz,
  5927. void* ctx, SSLInfo* sslInfo, char* error)
  5928. {
  5929. return ssl_DecodePacketInternal(vChain, chainSz, 1, NULL, sslInfo,
  5930. ctx, error, 0);
  5931. }
  5932. #endif
  5933. /* Deallocator for the decoded data buffer. */
  5934. /* returns 0 on success, -1 on error */
  5935. int ssl_FreeDecodeBuffer(byte** data, char* error)
  5936. {
  5937. return ssl_FreeZeroDecodeBuffer(data, 0, error);
  5938. }
  5939. /* Deallocator for the decoded data buffer, zeros out buffer. */
  5940. /* returns 0 on success, -1 on error */
  5941. int ssl_FreeZeroDecodeBuffer(byte** data, int sz, char* error)
  5942. {
  5943. (void)error;
  5944. if (sz < 0) {
  5945. return -1;
  5946. }
  5947. if (data != NULL) {
  5948. ForceZero(*data, (word32)sz);
  5949. XFREE(*data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5950. *data = NULL;
  5951. }
  5952. return 0;
  5953. }
  5954. /* Enables (if traceFile)/ Disables debug tracing */
  5955. /* returns 0 on success, -1 on error */
  5956. int ssl_Trace(const char* traceFile, char* error)
  5957. {
  5958. if (traceFile) {
  5959. /* Don't try to reopen the file */
  5960. if (TraceFile == NULL) {
  5961. TraceFile = XFOPEN(traceFile, "a");
  5962. if (!TraceFile) {
  5963. SetError(BAD_TRACE_FILE_STR, error, NULL, 0);
  5964. return -1;
  5965. }
  5966. TraceOn = 1;
  5967. }
  5968. }
  5969. else
  5970. TraceOn = 0;
  5971. return 0;
  5972. }
  5973. /* Enables/Disables Recovery of missed data if later packets allow
  5974. * maxMemory is number of bytes to use for reassembly buffering per session,
  5975. * -1 means unlimited
  5976. * returns 0 on success, -1 on error */
  5977. int ssl_EnableRecovery(int onOff, int maxMemory, char* error)
  5978. {
  5979. (void)error;
  5980. RecoveryEnabled = onOff;
  5981. if (onOff)
  5982. MaxRecoveryMemory = maxMemory;
  5983. return 0;
  5984. }
  5985. #if defined(WOLFSSL_SESSION_STATS) && !defined(NO_SESSION_CACHE)
  5986. int ssl_GetSessionStats(unsigned int* active, unsigned int* total,
  5987. unsigned int* peak, unsigned int* maxSessions,
  5988. unsigned int* missedData, unsigned int* reassemblyMem,
  5989. char* error)
  5990. {
  5991. int ret;
  5992. if (missedData) {
  5993. #ifndef WOLFSSL_SNIFFER_NO_RECOVERY
  5994. wc_LockMutex(&RecoveryMutex);
  5995. *missedData = MissedDataSessions;
  5996. wc_UnLockMutex(&RecoveryMutex);
  5997. #endif
  5998. }
  5999. if (reassemblyMem) {
  6000. SnifferSession* session;
  6001. int i;
  6002. *reassemblyMem = 0;
  6003. LOCK_SESSION();
  6004. for (i = 0; i < HASH_SIZE; i++) {
  6005. session = SessionTable[i];
  6006. while (session) {
  6007. *reassemblyMem += session->cliReassemblyMemory;
  6008. *reassemblyMem += session->srvReassemblyMemory;
  6009. session = session->next;
  6010. }
  6011. }
  6012. UNLOCK_SESSION();
  6013. }
  6014. ret = wolfSSL_get_session_stats(active, total, peak, maxSessions);
  6015. if (ret == WOLFSSL_SUCCESS)
  6016. return 0;
  6017. else {
  6018. SetError(BAD_SESSION_STATS, error, NULL, 0);
  6019. return -1;
  6020. }
  6021. }
  6022. #endif
  6023. int ssl_SetConnectionCb(SSLConnCb cb)
  6024. {
  6025. ConnectionCb = cb;
  6026. return 0;
  6027. }
  6028. int ssl_SetConnectionCtx(void* ctx)
  6029. {
  6030. ConnectionCbCtx = ctx;
  6031. return 0;
  6032. }
  6033. #ifdef WOLFSSL_SNIFFER_STATS
  6034. /* Resets the statistics tracking global structure.
  6035. * returns 0 on success, -1 on error */
  6036. int ssl_ResetStatistics(void)
  6037. {
  6038. wc_LockMutex(&StatsMutex);
  6039. XMEMSET(&SnifferStats, 0, sizeof(SSLStats));
  6040. wc_UnLockMutex(&StatsMutex);
  6041. return 0;
  6042. }
  6043. /* Copies the SSL statistics into the provided stats record.
  6044. * returns 0 on success, -1 on error */
  6045. int ssl_ReadStatistics(SSLStats* stats)
  6046. {
  6047. if (stats == NULL)
  6048. return -1;
  6049. LOCK_STAT();
  6050. XMEMCPY(stats, &SnifferStats, sizeof(SSLStats));
  6051. UNLOCK_STAT();
  6052. return 0;
  6053. }
  6054. /* Copies the SSL statistics into the provided stats record then
  6055. * resets the statistics tracking global structure.
  6056. * returns 0 on success, -1 on error */
  6057. int ssl_ReadResetStatistics(SSLStats* stats)
  6058. {
  6059. if (stats == NULL)
  6060. return -1;
  6061. LOCK_STAT();
  6062. XMEMCPY(stats, &SnifferStats, sizeof(SSLStats));
  6063. XMEMSET(&SnifferStats, 0, sizeof(SSLStats));
  6064. UNLOCK_STAT();
  6065. return 0;
  6066. }
  6067. #endif /* WOLFSSL_SNIFFER_STATS */
  6068. #ifdef WOLFSSL_SNIFFER_WATCH
  6069. int ssl_SetWatchKeyCallback_ex(SSLWatchCb cb, int devId, char* error)
  6070. {
  6071. #ifdef WOLF_CRYPTO_CB
  6072. if (CryptoDeviceId == INVALID_DEVID)
  6073. CryptoDeviceId = devId;
  6074. #else
  6075. (void)devId;
  6076. #endif
  6077. WatchCb = cb;
  6078. return CreateWatchSnifferServer(error);
  6079. }
  6080. int ssl_SetWatchKeyCallback(SSLWatchCb cb, char* error)
  6081. {
  6082. WatchCb = cb;
  6083. return CreateWatchSnifferServer(error);
  6084. }
  6085. int ssl_SetWatchKeyCtx(void* ctx, char* error)
  6086. {
  6087. (void)error;
  6088. WatchCbCtx = ctx;
  6089. return 0;
  6090. }
  6091. int ssl_SetWatchKey_buffer(void* vSniffer, const byte* key, word32 keySz,
  6092. int keyType, char* error)
  6093. {
  6094. SnifferSession* sniffer;
  6095. int ret;
  6096. if (vSniffer == NULL) {
  6097. return -1;
  6098. }
  6099. if (key == NULL || keySz == 0) {
  6100. return -1;
  6101. }
  6102. sniffer = (SnifferSession*)vSniffer;
  6103. /* Remap the keyType from what the user can use to
  6104. * what wolfSSL_use_PrivateKey_buffer expects. */
  6105. keyType = (keyType == FILETYPE_PEM) ? WOLFSSL_FILETYPE_PEM :
  6106. WOLFSSL_FILETYPE_ASN1;
  6107. #ifdef WOLFSSL_STATIC_EPHEMERAL
  6108. /* try setting static ephemeral first */
  6109. /* auto detect key type with WC_PK_TYPE_NONE */
  6110. ret = wolfSSL_set_ephemeral_key(sniffer->sslServer,
  6111. WC_PK_TYPE_NONE, (const char*)key, keySz,
  6112. WOLFSSL_FILETYPE_ASN1);
  6113. if (ret != 0) {
  6114. #ifdef DEBUG_SNIFFER
  6115. /* print warnings */
  6116. fprintf(stderr, "key watch set ephemeral failed %d\n", ret);
  6117. #endif
  6118. }
  6119. #endif
  6120. /* always try and load private key */
  6121. ret = wolfSSL_use_PrivateKey_buffer(sniffer->sslServer,
  6122. key, keySz, keyType);
  6123. if (ret != WOLFSSL_SUCCESS) {
  6124. SetError(KEY_FILE_STR, error, sniffer, FATAL_ERROR_STATE);
  6125. return -1;
  6126. }
  6127. return 0;
  6128. }
  6129. int ssl_SetWatchKey_file(void* vSniffer, const char* keyFile, int keyType,
  6130. const char* password, char* error)
  6131. {
  6132. byte* keyBuf = NULL;
  6133. word32 keyBufSz = 0;
  6134. int ret;
  6135. if (vSniffer == NULL) {
  6136. return -1;
  6137. }
  6138. if (keyFile == NULL) {
  6139. return -1;
  6140. }
  6141. /* Remap the keyType from what the user can use to
  6142. * what LoadKeyFile expects. */
  6143. keyType = (keyType == FILETYPE_PEM) ? WOLFSSL_FILETYPE_PEM :
  6144. WOLFSSL_FILETYPE_ASN1;
  6145. ret = LoadKeyFile(&keyBuf, &keyBufSz, keyFile, 0, keyType, password);
  6146. if (ret < 0) {
  6147. SetError(KEY_FILE_STR, error, NULL, 0);
  6148. XFREE(keyBuf, NULL, DYNAMIC_TYPE_X509);
  6149. return -1;
  6150. }
  6151. ret = ssl_SetWatchKey_buffer(vSniffer, keyBuf, keyBufSz, FILETYPE_DER,
  6152. error);
  6153. XFREE(keyBuf, NULL, DYNAMIC_TYPE_X509);
  6154. return ret;
  6155. }
  6156. #endif /* WOLFSSL_SNIFFER_WATCH */
  6157. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  6158. int ssl_SetStoreDataCallback(SSLStoreDataCb cb)
  6159. {
  6160. StoreDataCb = cb;
  6161. return 0;
  6162. }
  6163. #endif /* WOLFSSL_SNIFFER_STORE_DATA_CB */
  6164. #ifdef WOLFSSL_SNIFFER_KEY_CALLBACK
  6165. int ssl_SetKeyCallback(SSLKeyCb cb, void* cbCtx)
  6166. {
  6167. KeyCb = cb;
  6168. KeyCbCtx = cbCtx;
  6169. return 0;
  6170. }
  6171. #endif
  6172. #ifdef WOLFSSL_ASYNC_CRYPT
  6173. int ssl_DecodePacketAsync(void* packet, unsigned int packetSz,
  6174. int isChain, unsigned char** data, char* error, SSLInfo* sslInfo,
  6175. void* userCtx)
  6176. {
  6177. return ssl_DecodePacketInternal(packet, packetSz, isChain, data, sslInfo,
  6178. userCtx, error, 1);
  6179. }
  6180. static SnifferSession* FindSession(WOLFSSL* ssl)
  6181. {
  6182. int i;
  6183. SnifferSession* session;
  6184. for (i = 0; i < HASH_SIZE; i++) {
  6185. session = SessionTable[i];
  6186. while (session) {
  6187. if (session->sslServer == ssl) {
  6188. return session;
  6189. }
  6190. session = session->next;
  6191. }
  6192. }
  6193. return NULL;
  6194. }
  6195. int ssl_PollSniffer(WOLF_EVENT** events, int maxEvents, WOLF_EVENT_FLAG flags,
  6196. int* pEventCount)
  6197. {
  6198. int ret = 0;
  6199. int eventCount = 0;
  6200. int i;
  6201. SnifferServer* srv;
  6202. LOCK_SERVER_LIST();
  6203. /* Iterate the open sniffer sessions calling wolfSSL_CTX_AsyncPoll */
  6204. srv = ServerList;
  6205. while (srv) {
  6206. int nMax = maxEvents - eventCount, nReady = 0;
  6207. if (nMax <= 0) {
  6208. break; /* out of room in events list */
  6209. }
  6210. ret = wolfSSL_CTX_AsyncPoll(srv->ctx, events + nReady, nMax, flags,
  6211. &nReady);
  6212. if (ret == 0) {
  6213. eventCount += nReady;
  6214. }
  6215. else {
  6216. #ifdef DEBUG_SNIFFER
  6217. fprintf(stderr, "Sniffer Server %p: Poll error: %d\n", srv, ret);
  6218. #endif
  6219. break;
  6220. }
  6221. srv = srv->next;
  6222. }
  6223. UNLOCK_SERVER_LIST();
  6224. /* iterate list and mark polled */
  6225. LOCK_SESSION();
  6226. for (i=0; i<eventCount; i++) {
  6227. WOLFSSL* ssl = (WOLFSSL*)events[i]->context;
  6228. SnifferSession* session = FindSession(ssl);
  6229. if (session) {
  6230. session->flags.wasPolled = 1;
  6231. session->sslServer->error = events[i]->ret;
  6232. }
  6233. }
  6234. UNLOCK_SESSION();
  6235. *pEventCount = eventCount;
  6236. return ret;
  6237. }
  6238. #endif
  6239. #if defined(WOLFSSL_SNIFFER_KEYLOGFILE)
  6240. #define CLIENT_RANDOM_LABEL_LENGTH 13
  6241. #define CLIENT_RANDOM_LENGTH 32
  6242. #define MASTER_SECRET_LENGTH 48
  6243. #define CLIENT_RANDOM_BITS ((CLIENT_RANDOM_LENGTH) * 8)
  6244. typedef struct SecretNode {
  6245. unsigned char clientRandom[CLIENT_RANDOM_LENGTH];
  6246. unsigned char masterSecret[MASTER_SECRET_LENGTH];
  6247. struct SecretNode* next;
  6248. } SecretNode;
  6249. /* Default to the same size hash table as the session table,
  6250. * but allow user to override */
  6251. #ifndef WOLFSSL_SNIFFER_KEYLOGFILE_HASH_TABLE_SIZE
  6252. #define WOLFSSL_SNIFFER_KEYLOGFILE_HASH_TABLE_SIZE HASH_SIZE
  6253. #endif
  6254. static THREAD_LS_T WOLFSSL_GLOBAL
  6255. SecretNode*
  6256. secretHashTable[WOLFSSL_SNIFFER_KEYLOGFILE_HASH_TABLE_SIZE] = {NULL};
  6257. #ifndef HAVE_C___ATOMIC
  6258. static WOLFSSL_GLOBAL wolfSSL_Mutex secretListMutex;
  6259. #endif
  6260. static unsigned int secretHashFunction(unsigned char* clientRandom);
  6261. #ifdef HAVE_C___ATOMIC
  6262. #define LOCK_SECRET_LIST() WC_DO_NOTHING
  6263. #define UNLOCK_SECRET_LIST() WC_DO_NOTHING
  6264. #else
  6265. #define LOCK_SECRET_LIST() wc_LockMutex(&secretListMutex)
  6266. #define UNLOCK_SECRET_LIST() wc_UnLockMutex(&secretListMutex)
  6267. #endif
  6268. /*
  6269. * Basic polynomial hash function that maps a 32-byte client random value to an
  6270. * array index
  6271. */
  6272. static unsigned int secretHashFunction(unsigned char* clientRandom)
  6273. {
  6274. int i = 0;
  6275. unsigned int hash = 0;
  6276. for (i = 0; i < CLIENT_RANDOM_LENGTH; i++) {
  6277. hash = (hash * CLIENT_RANDOM_BITS + clientRandom[i])
  6278. % WOLFSSL_SNIFFER_KEYLOGFILE_HASH_TABLE_SIZE;
  6279. }
  6280. return hash;
  6281. }
  6282. static int addSecretNode(unsigned char* clientRandom,
  6283. unsigned char* masterSecret,
  6284. char* error)
  6285. {
  6286. unsigned int index = 0;
  6287. SecretNode* newSecretNode = NULL;
  6288. newSecretNode = (SecretNode*)XMALLOC(sizeof(SecretNode),
  6289. NULL,
  6290. DYNAMIC_TYPE_SNIFFER_KEYLOG_NODE);
  6291. if (newSecretNode == NULL) {
  6292. SetError(MEMORY_STR, error, NULL, 0);
  6293. return WOLFSSL_SNIFFER_ERROR;
  6294. }
  6295. XMEMCPY(newSecretNode->clientRandom, clientRandom, CLIENT_RANDOM_LENGTH);
  6296. XMEMCPY(newSecretNode->masterSecret, masterSecret, MASTER_SECRET_LENGTH);
  6297. LOCK_SECRET_LIST();
  6298. index = secretHashFunction(clientRandom);
  6299. newSecretNode->next = NULL;
  6300. if (secretHashTable[index] == NULL) {
  6301. secretHashTable[index] = newSecretNode;
  6302. }
  6303. else {
  6304. SecretNode* current = secretHashTable[index];
  6305. while (current != NULL) {
  6306. if (memcmp(current->clientRandom,
  6307. clientRandom,
  6308. CLIENT_RANDOM_LENGTH) == 0) {
  6309. /* No need for a new node, since it already exists */
  6310. fprintf(stderr, "Found duplicate client random value in "
  6311. "keylog file. Rejecting.\n");
  6312. XFREE(newSecretNode, NULL, DYNAMIC_TYPE_SNIFFER_KEYLOG_NODE);
  6313. break;
  6314. }
  6315. if (current->next == NULL) {
  6316. current->next = newSecretNode;
  6317. break;
  6318. }
  6319. current = current->next;
  6320. }
  6321. }
  6322. UNLOCK_SECRET_LIST();
  6323. return 0;
  6324. }
  6325. /*
  6326. * Looks up a master secret for a given client random from the keylog file
  6327. */
  6328. static unsigned char* findMasterSecret(unsigned char* clientRandom)
  6329. {
  6330. unsigned char* secret = NULL;
  6331. SecretNode* node = NULL;
  6332. unsigned int index = 0;
  6333. LOCK_SECRET_LIST();
  6334. index = secretHashFunction(clientRandom);
  6335. node = secretHashTable[index];
  6336. while (node != NULL) {
  6337. if (XMEMCMP(node->clientRandom,
  6338. clientRandom, CLIENT_RANDOM_LENGTH) == 0) {
  6339. secret = node->masterSecret;
  6340. break;
  6341. }
  6342. node = node->next;
  6343. }
  6344. UNLOCK_SECRET_LIST();
  6345. return secret;
  6346. }
  6347. static void hexToBin(const char* hex, unsigned char* bin, int binLength)
  6348. {
  6349. int i = 0;
  6350. for (i = 0; i < binLength; i++) {
  6351. sscanf(hex + 2 * i, "%02hhx", &bin[i]);
  6352. }
  6353. }
  6354. static int parseKeyLogFile(const char* fileName, char* error)
  6355. {
  6356. const char CLIENT_RANDOM_LABEL_STR[] = "CLIENT_RANDOM";
  6357. unsigned char clientRandom[CLIENT_RANDOM_LENGTH];
  6358. unsigned char masterSecret[MASTER_SECRET_LENGTH];
  6359. FILE* file = NULL;
  6360. int ret = 0;
  6361. /* +1 for null terminator */
  6362. char clientRandomLabel[CLIENT_RANDOM_LABEL_LENGTH + 1] = {0};
  6363. /* 2 chars for Hexadecimal representation, plus null terminator */
  6364. char clientRandomHex[2 * CLIENT_RANDOM_LENGTH + 1] = {0};
  6365. char masterSecretHex[2 * MASTER_SECRET_LENGTH + 1] = {0};
  6366. file = fopen(fileName, "r");
  6367. if (file == NULL) {
  6368. fprintf(stderr, "Could not open keylog file: %s\n", fileName);
  6369. SetError(KEYLOG_FILE_INVALID, error, NULL, 0);
  6370. return WOLFSSL_SNIFFER_ERROR;
  6371. }
  6372. while (fscanf(file, "%13s %64s %96s",
  6373. clientRandomLabel, clientRandomHex, masterSecretHex) == 3) {
  6374. if (XSTRCMP(clientRandomLabel, CLIENT_RANDOM_LABEL_STR) == 0) {
  6375. hexToBin(clientRandomHex, clientRandom, CLIENT_RANDOM_LENGTH);
  6376. hexToBin(masterSecretHex, masterSecret, MASTER_SECRET_LENGTH);
  6377. ret = addSecretNode(clientRandom, masterSecret, error);
  6378. if (ret != 0) {
  6379. fclose(file);
  6380. return ret;
  6381. }
  6382. }
  6383. }
  6384. fclose(file);
  6385. return 0;
  6386. }
  6387. static void freeSecretList(void)
  6388. {
  6389. int i = 0;
  6390. LOCK_SECRET_LIST();
  6391. for (i=0; i<WOLFSSL_SNIFFER_KEYLOGFILE_HASH_TABLE_SIZE; i++)
  6392. {
  6393. SecretNode* current = secretHashTable[i];
  6394. SecretNode * next = NULL;
  6395. while (current != NULL) {
  6396. next = current->next;
  6397. XFREE(current, NULL, DYNAMIC_TYPE_SNIFFER_KEYLOG_NODE);
  6398. current = next;
  6399. }
  6400. }
  6401. UNLOCK_SECRET_LIST();
  6402. }
  6403. /*
  6404. * Looks up secret based on client random and copies it to output_secret
  6405. */
  6406. static int snifferSecretCb(unsigned char* client_random,
  6407. unsigned char* output_secret)
  6408. {
  6409. unsigned char* secret = NULL;
  6410. if (client_random == NULL || output_secret == NULL) {
  6411. return WOLFSSL_SNIFFER_FATAL_ERROR;
  6412. }
  6413. /* get secret from secret table based on client random */
  6414. secret = findMasterSecret(client_random);
  6415. if (secret != NULL) {
  6416. XMEMCPY(output_secret, secret, MASTER_SECRET_LENGTH);
  6417. return 0;
  6418. }
  6419. /* didn't find the secret */
  6420. return WOLFSSL_SNIFFER_ERROR;
  6421. }
  6422. static void setSnifferSecretCb(SnifferSession* session)
  6423. {
  6424. session->context->useKeyLogFile = 1;
  6425. session->sslServer->snifferSecretCb = snifferSecretCb;
  6426. session->sslClient->snifferSecretCb = snifferSecretCb;
  6427. }
  6428. /*
  6429. * Helper function that creates a sniffer server object that can decrypt using
  6430. * a keylog file, and adds it to the server list
  6431. *
  6432. * NOTE: the caller is responsible for locking and unlocking the server list
  6433. */
  6434. static int addKeyLogSnifferServerHelper(const char* address,
  6435. int port,
  6436. char* error)
  6437. {
  6438. IpAddrInfo serverIp = {0};
  6439. SnifferServer *sniffer = NULL;
  6440. TraceHeader();
  6441. TraceSetServer(address, port, NULL);
  6442. serverIp.version = IPV4;
  6443. serverIp.ip4 = XINET_ADDR(address);
  6444. if (serverIp.ip4 == XINADDR_NONE) {
  6445. #ifdef FUSION_RTOS
  6446. if (XINET_PTON(AF_INET6, address, serverIp.ip6,
  6447. sizeof(serverIp.ip4)) == 1)
  6448. #else
  6449. if (XINET_PTON(AF_INET6, address, serverIp.ip6) == 1)
  6450. #endif
  6451. {
  6452. serverIp.version = IPV6;
  6453. }
  6454. }
  6455. sniffer = ServerList;
  6456. while (sniffer != NULL &&
  6457. (!MatchAddr(sniffer->server, serverIp) || sniffer->port != port)) {
  6458. sniffer = sniffer->next;
  6459. }
  6460. if (sniffer == NULL) {
  6461. sniffer = (SnifferServer*)XMALLOC(sizeof(SnifferServer),
  6462. NULL, DYNAMIC_TYPE_SNIFFER_SERVER);
  6463. if (sniffer == NULL) {
  6464. SetError(MEMORY_STR, error, NULL, 0);
  6465. return WOLFSSL_SNIFFER_ERROR;
  6466. }
  6467. InitSnifferServer(sniffer);
  6468. XSTRNCPY(sniffer->address, address, MAX_SERVER_ADDRESS-1);
  6469. sniffer->address[MAX_SERVER_ADDRESS-1] = '\0';
  6470. sniffer->server = serverIp;
  6471. sniffer->port = port;
  6472. sniffer->ctx = wolfSSL_CTX_new(wolfSSLv23_client_method());
  6473. if (!sniffer->ctx) {
  6474. SetError(MEMORY_STR, error, NULL, 0);
  6475. FreeSnifferServer(sniffer);
  6476. return WOLFSSL_SNIFFER_ERROR;
  6477. }
  6478. #if defined(WOLF_CRYPTO_CB) || defined(WOLFSSL_ASYNC_CRYPT)
  6479. if (CryptoDeviceId != INVALID_DEVID)
  6480. wolfSSL_CTX_SetDevId(sniffer->ctx, CryptoDeviceId);
  6481. #endif
  6482. sniffer->next = ServerList;
  6483. ServerList = sniffer;
  6484. }
  6485. else {
  6486. printf("SESSION ALREADY EXISTS\n");
  6487. }
  6488. /* Tag the new or existing server as requiring keylog support to
  6489. * decrypt, otherwise it won't be useable */
  6490. sniffer->useKeyLogFile = 1;
  6491. return 0;
  6492. }
  6493. /*
  6494. * Creates a sniffer server that is able to decrypt using secrets from a
  6495. * keylog file, and adds it to the server list
  6496. *
  6497. * If a server at the address and port already exists, it will be marked
  6498. * for keylog file decryption
  6499. */
  6500. int ssl_CreateKeyLogSnifferServer(const char* address, int port, char* error)
  6501. {
  6502. int ret = 0;
  6503. if (address == NULL) {
  6504. SetError(KEYLOG_FILE_INVALID, error, NULL, 0);
  6505. return WOLFSSL_SNIFFER_ERROR;
  6506. }
  6507. LOCK_SERVER_LIST();
  6508. ret = addKeyLogSnifferServerHelper(address, port, error);
  6509. UNLOCK_SERVER_LIST();
  6510. return ret;
  6511. }
  6512. /*
  6513. * Loads secrets to decrypt TLS traffic from a keylog file. Only sniffer
  6514. * servers registered with ssl_createKeyLogSnifferServer() will be able to
  6515. * decrypt using these secrets
  6516. */
  6517. int ssl_LoadSecretsFromKeyLogFile(const char* keylogfile, char* error)
  6518. {
  6519. if (keylogfile == NULL) {
  6520. SetError(KEYLOG_FILE_INVALID, error, NULL, 0);
  6521. return WOLFSSL_SNIFFER_ERROR;
  6522. }
  6523. return parseKeyLogFile(keylogfile, error);
  6524. }
  6525. #endif /* WOLFSSL_SNIFFER_KEYLOGFILE */
  6526. #undef ERROR_OUT
  6527. #endif /* WOLFSSL_SNIFFER */
  6528. #endif /* !WOLFCRYPT_ONLY && !NO_FILESYSTEM */