sniffer.c 190 KB

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