sniffer.c 230 KB

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