sniffer.c 174 KB

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