sniffer.c 230 KB

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