sniffer.c 216 KB

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