sniffer.c 209 KB

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