sniffer.c 134 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611
  1. /* sniffer.c
  2. *
  3. * Copyright (C) 2006-2020 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. #ifndef WOLFCRYPT_ONLY
  26. #ifdef WOLFSSL_SNIFFER
  27. #include <assert.h>
  28. #include <time.h>
  29. #ifndef _WIN32
  30. #include <arpa/inet.h>
  31. #else
  32. #include <WS2tcpip.h>
  33. #endif
  34. #ifdef _WIN32
  35. #define SNPRINTF _snprintf
  36. #else
  37. #define SNPRINTF snprintf
  38. #endif
  39. #include <wolfssl/openssl/ssl.h>
  40. #include <wolfssl/internal.h>
  41. #include <wolfssl/error-ssl.h>
  42. #include <wolfssl/sniffer.h>
  43. #include <wolfssl/sniffer_error.h>
  44. #ifdef NO_INLINE
  45. #include <wolfssl/wolfcrypt/misc.h>
  46. #else
  47. #define WOLFSSL_MISC_INCLUDED
  48. #include <wolfcrypt/src/misc.c>
  49. #endif
  50. #ifdef WOLF_CRYPTO_CB
  51. #include <wolfssl/wolfcrypt/cryptocb.h>
  52. #ifdef HAVE_INTEL_QA_SYNC
  53. #include <wolfssl/wolfcrypt/port/intel/quickassist_sync.h>
  54. #endif
  55. #ifdef HAVE_CAVIUM_OCTEON_SYNC
  56. #include <wolfssl/wolfcrypt/port/cavium/cavium_octeon_sync.h>
  57. #endif
  58. #endif
  59. #ifndef WOLFSSL_SNIFFER_TIMEOUT
  60. #define WOLFSSL_SNIFFER_TIMEOUT 900
  61. /* Cache unclosed Sessions for 15 minutes since last used */
  62. #endif
  63. /* Misc constants */
  64. enum {
  65. MAX_SERVER_ADDRESS = 128, /* maximum server address length */
  66. MAX_SERVER_NAME = 128, /* maximum server name length */
  67. MAX_ERROR_LEN = 80, /* maximum error length */
  68. ETHER_IF_ADDR_LEN = 6, /* ethernet interface address length */
  69. LOCAL_IF_ADDR_LEN = 4, /* localhost interface address length, !windows */
  70. TCP_PROTO = 6, /* TCP_PROTOCOL */
  71. IP_HDR_SZ = 20, /* IPv4 header length, min */
  72. IP6_HDR_SZ = 40, /* IPv6 header length, min */
  73. TCP_HDR_SZ = 20, /* TCP header length, min */
  74. IPV4 = 4, /* IP version 4 */
  75. IPV6 = 6, /* IP version 6 */
  76. TCP_PROTOCOL = 6, /* TCP Protocol id */
  77. NO_NEXT_HEADER = 59, /* IPv6 no headers follow */
  78. TRACE_MSG_SZ = 80, /* Trace Message buffer size */
  79. HASH_SIZE = 499, /* Session Hash Table Rows */
  80. PSEUDO_HDR_SZ = 12, /* TCP Pseudo Header size in bytes */
  81. FATAL_ERROR_STATE = 1, /* SnifferSession fatal error state */
  82. TICKET_HINT_LEN = 4, /* Session Ticket Hint length */
  83. EXT_TYPE_SZ = 2, /* Extension length */
  84. MAX_INPUT_SZ = MAX_RECORD_SIZE + COMP_EXTRA + MAX_MSG_EXTRA +
  85. MTU_EXTRA, /* Max input sz of reassembly */
  86. EXT_MASTER_SECRET = 0x17, /* Extended Master Secret Extension ID */
  87. TICKET_EXT_ID = 0x23 /* Session Ticket Extension ID */
  88. };
  89. #ifdef _WIN32
  90. static HMODULE dllModule; /* for error string resources */
  91. BOOL APIENTRY DllMain( HMODULE hModule,
  92. DWORD ul_reason_for_call,
  93. LPVOID lpReserved
  94. )
  95. {
  96. static int didInit = 0;
  97. switch (ul_reason_for_call)
  98. {
  99. case DLL_PROCESS_ATTACH:
  100. if (didInit == 0) {
  101. dllModule = hModule;
  102. ssl_InitSniffer();
  103. didInit = 1;
  104. }
  105. break;
  106. case DLL_THREAD_ATTACH:
  107. break;
  108. case DLL_THREAD_DETACH:
  109. break;
  110. case DLL_PROCESS_DETACH:
  111. if (didInit) {
  112. ssl_FreeSniffer();
  113. didInit = 0;
  114. }
  115. break;
  116. }
  117. return TRUE;
  118. }
  119. #endif /* _WIN32 */
  120. static WOLFSSL_GLOBAL int TraceOn = 0; /* Trace is off by default */
  121. static WOLFSSL_GLOBAL FILE* TraceFile = 0;
  122. /* windows uses .rc table for this */
  123. #ifndef _WIN32
  124. static const char* const msgTable[] =
  125. {
  126. /* 1 */
  127. "Out of Memory",
  128. "New SSL Sniffer Server Registered",
  129. "Checking IP Header",
  130. "SSL Sniffer Server Not Registered",
  131. "Checking TCP Header",
  132. /* 6 */
  133. "SSL Sniffer Server Port Not Registered",
  134. "RSA Private Decrypt Error",
  135. "RSA Private Decode Error",
  136. "Set Cipher Spec Error",
  137. "Server Hello Input Malformed",
  138. /* 11 */
  139. "Couldn't Resume Session Error",
  140. "Server Did Resumption",
  141. "Client Hello Input Malformed",
  142. "Client Trying to Resume",
  143. "Handshake Input Malformed",
  144. /* 16 */
  145. "Got Hello Verify msg",
  146. "Got Server Hello msg",
  147. "Got Cert Request msg",
  148. "Got Server Key Exchange msg",
  149. "Got Cert msg",
  150. /* 21 */
  151. "Got Server Hello Done msg",
  152. "Got Finished msg",
  153. "Got Client Hello msg",
  154. "Got Client Key Exchange msg",
  155. "Got Cert Verify msg",
  156. /* 26 */
  157. "Got Unknown Handshake msg",
  158. "New SSL Sniffer Session created",
  159. "Couldn't create new SSL",
  160. "Got a Packet to decode",
  161. "No data present",
  162. /* 31 */
  163. "Session Not Found",
  164. "Got an Old Client Hello msg",
  165. "Old Client Hello Input Malformed",
  166. "Old Client Hello OK",
  167. "Bad Old Client Hello",
  168. /* 36 */
  169. "Bad Record Header",
  170. "Record Header Input Malformed",
  171. "Got a HandShake msg",
  172. "Bad HandShake msg",
  173. "Got a Change Cipher Spec msg",
  174. /* 41 */
  175. "Got Application Data msg",
  176. "Bad Application Data",
  177. "Got an Alert msg",
  178. "Another msg to Process",
  179. "Removing Session From Table",
  180. /* 46 */
  181. "Bad Key File",
  182. "Wrong IP Version",
  183. "Wrong Protocol type",
  184. "Packet Short for header processing",
  185. "Got Unknown Record Type",
  186. /* 51 */
  187. "Can't Open Trace File",
  188. "Session in Fatal Error State",
  189. "Partial SSL record received",
  190. "Buffer Error, malformed input",
  191. "Added to Partial Input",
  192. /* 56 */
  193. "Received a Duplicate Packet",
  194. "Received an Out of Order Packet",
  195. "Received an Overlap Duplicate Packet",
  196. "Received an Overlap Reassembly Begin Duplicate Packet",
  197. "Received an Overlap Reassembly End Duplicate Packet",
  198. /* 61 */
  199. "Missed the Client Hello Entirely",
  200. "Got Hello Request msg",
  201. "Got Session Ticket msg",
  202. "Bad Input",
  203. "Bad Decrypt Type",
  204. /* 66 */
  205. "Bad Finished Message Processing",
  206. "Bad Compression Type",
  207. "Bad DeriveKeys Error",
  208. "Saw ACK for Missing Packet Error",
  209. "Bad Decrypt Operation",
  210. /* 71 */
  211. "Decrypt Keys Not Set Up",
  212. "Late Key Load Error",
  213. "Got Certificate Status msg",
  214. "RSA Key Missing Error",
  215. "Secure Renegotiation Not Supported",
  216. /* 76 */
  217. "Get Session Stats Failure",
  218. "Reassembly Buffer Size Exceeded",
  219. "Dropping Lost Fragment",
  220. "Dropping Partial Record",
  221. "Clear ACK Fault",
  222. /* 81 */
  223. "Bad Decrypt Size",
  224. "Extended Master Secret Hash Error",
  225. "Handshake Message Split Across TLS Records",
  226. "ECC Private Decode Error",
  227. "ECC Public Decode Error",
  228. /* 86 */
  229. "Watch callback not set",
  230. "Watch hash failed",
  231. "Watch callback failed",
  232. "Bad Certificate Message",
  233. "Store data callback not set",
  234. /* 91 */
  235. "No data destination Error",
  236. "Store data callback failed",
  237. "Loading chain input"
  238. };
  239. /* *nix version uses table above */
  240. static void GetError(int idx, char* str)
  241. {
  242. XSTRNCPY(str, msgTable[idx - 1], MAX_ERROR_LEN-1);
  243. str[MAX_ERROR_LEN-1] = '\0';
  244. }
  245. #else /* _WIN32 */
  246. /* Windows version uses .rc table */
  247. static void GetError(int idx, char* buffer)
  248. {
  249. if (!LoadStringA(dllModule, idx, buffer, MAX_ERROR_LEN))
  250. buffer[0] = 0;
  251. }
  252. #endif /* _WIN32 */
  253. /* Packet Buffer for reassembly list and ready list */
  254. typedef struct PacketBuffer {
  255. word32 begin; /* relative sequence begin */
  256. word32 end; /* relative sequence end */
  257. byte* data; /* actual data */
  258. struct PacketBuffer* next; /* next on reassembly list or ready list */
  259. } PacketBuffer;
  260. #ifdef HAVE_SNI
  261. /* NamedKey maps a SNI name to a specific private key */
  262. typedef struct NamedKey {
  263. char name[MAX_SERVER_NAME]; /* server DNS name */
  264. word32 nameSz; /* size of server DNS name */
  265. byte* key; /* DER private key */
  266. word32 keySz; /* size of DER private key */
  267. struct NamedKey* next; /* for list */
  268. } NamedKey;
  269. #endif
  270. typedef struct IpAddrInfo {
  271. int version;
  272. union {
  273. word32 ip4;
  274. byte ip6[16];
  275. };
  276. } IpAddrInfo;
  277. /* Sniffer Server holds info for each server/port monitored */
  278. typedef struct SnifferServer {
  279. SSL_CTX* ctx; /* SSL context */
  280. char address[MAX_SERVER_ADDRESS]; /* passed in server address */
  281. IpAddrInfo server; /* network order address */
  282. int port; /* server port */
  283. #ifdef HAVE_SNI
  284. NamedKey* namedKeys; /* mapping of names and keys */
  285. wolfSSL_Mutex namedKeysMutex; /* mutex for namedKey list */
  286. #endif
  287. struct SnifferServer* next; /* for list */
  288. } SnifferServer;
  289. /* Session Flags */
  290. typedef struct Flags {
  291. byte side; /* which end is current packet headed */
  292. byte serverCipherOn; /* indicates whether cipher is active */
  293. byte clientCipherOn; /* indicates whether cipher is active */
  294. byte resuming; /* did this session come from resumption */
  295. byte cached; /* have we cached this session yet */
  296. byte clientHello; /* processed client hello yet, for SSLv2 */
  297. byte finCount; /* get both FINs before removing */
  298. byte fatalError; /* fatal error state */
  299. byte cliAckFault; /* client acked unseen data from server */
  300. byte srvAckFault; /* server acked unseen data from client */
  301. byte cliSkipPartial; /* client skips partial data to catch up */
  302. byte srvSkipPartial; /* server skips partial data to catch up */
  303. #ifdef HAVE_EXTENDED_MASTER
  304. byte expectEms; /* expect extended master secret */
  305. #endif
  306. } Flags;
  307. /* Out of Order FIN capture */
  308. typedef struct FinCaputre {
  309. word32 cliFinSeq; /* client relative sequence FIN 0 is no */
  310. word32 srvFinSeq; /* server relative sequence FIN, 0 is no */
  311. byte cliCounted; /* did we count yet, detects duplicates */
  312. byte srvCounted; /* did we count yet, detects duplicates */
  313. } FinCaputre;
  314. typedef struct HsHashes {
  315. #ifndef NO_OLD_TLS
  316. #ifndef NO_SHA
  317. wc_Sha hashSha;
  318. #endif
  319. #ifndef NO_MD5
  320. wc_Md5 hashMd5;
  321. #endif
  322. #endif
  323. #ifndef NO_SHA256
  324. wc_Sha256 hashSha256;
  325. #endif
  326. #ifdef WOLFSSL_SHA384
  327. wc_Sha384 hashSha384;
  328. #endif
  329. } HsHashes;
  330. /* Sniffer Session holds info for each client/server SSL/TLS session */
  331. typedef struct SnifferSession {
  332. SnifferServer* context; /* server context */
  333. SSL* sslServer; /* SSL server side decode */
  334. SSL* sslClient; /* SSL client side decode */
  335. IpAddrInfo server; /* server address in network byte order */
  336. IpAddrInfo client; /* client address in network byte order */
  337. word16 srvPort; /* server port */
  338. word16 cliPort; /* client port */
  339. word32 cliSeqStart; /* client start sequence */
  340. word32 srvSeqStart; /* server start sequence */
  341. word32 cliExpected; /* client expected sequence (relative) */
  342. word32 srvExpected; /* server expected sequence (relative) */
  343. FinCaputre finCaputre; /* retain out of order FIN s */
  344. Flags flags; /* session flags */
  345. time_t lastUsed; /* last used ticks */
  346. word32 keySz; /* size of the private key */
  347. PacketBuffer* cliReassemblyList; /* client out of order packets */
  348. PacketBuffer* srvReassemblyList; /* server out of order packets */
  349. word32 cliReassemblyMemory; /* client packet memory used */
  350. word32 srvReassemblyMemory; /* server packet memory used */
  351. struct SnifferSession* next; /* for hash table list */
  352. byte* ticketID; /* mac ID of session ticket */
  353. #ifdef HAVE_SNI
  354. const char* sni; /* server name indication */
  355. #endif
  356. #ifdef HAVE_EXTENDED_MASTER
  357. HsHashes* hash;
  358. #endif
  359. } SnifferSession;
  360. /* Sniffer Server List and mutex */
  361. static WOLFSSL_GLOBAL SnifferServer* ServerList = 0;
  362. static WOLFSSL_GLOBAL wolfSSL_Mutex ServerListMutex;
  363. /* Session Hash Table, mutex, and count */
  364. static WOLFSSL_GLOBAL SnifferSession* SessionTable[HASH_SIZE];
  365. static WOLFSSL_GLOBAL wolfSSL_Mutex SessionMutex;
  366. static WOLFSSL_GLOBAL int SessionCount = 0;
  367. /* Recovery of missed data switches and stats */
  368. static WOLFSSL_GLOBAL wolfSSL_Mutex RecoveryMutex; /* for stats */
  369. static WOLFSSL_GLOBAL int RecoveryEnabled = 0; /* global switch */
  370. static WOLFSSL_GLOBAL int MaxRecoveryMemory = -1;
  371. /* per session max recovery memory */
  372. static WOLFSSL_GLOBAL word32 MissedDataSessions = 0;
  373. /* # of sessions with missed data */
  374. /* Connection Info Callback */
  375. static WOLFSSL_GLOBAL SSLConnCb ConnectionCb;
  376. static WOLFSSL_GLOBAL void* ConnectionCbCtx = NULL;
  377. #ifdef WOLFSSL_SNIFFER_STATS
  378. /* Sessions Statistics */
  379. static WOLFSSL_GLOBAL SSLStats SnifferStats;
  380. static WOLFSSL_GLOBAL wolfSSL_Mutex StatsMutex;
  381. #endif
  382. #ifdef WOLFSSL_SNIFFER_WATCH
  383. /* Watch Key Callback */
  384. static WOLFSSL_GLOBAL SSLWatchCb WatchCb;
  385. static WOLFSSL_GLOBAL void* WatchCbCtx = NULL;
  386. #endif
  387. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  388. /* Store Data Callback */
  389. static WOLFSSL_GLOBAL SSLStoreDataCb StoreDataCb;
  390. #endif
  391. static void UpdateMissedDataSessions(void)
  392. {
  393. wc_LockMutex(&RecoveryMutex);
  394. MissedDataSessions += 1;
  395. wc_UnLockMutex(&RecoveryMutex);
  396. }
  397. #ifdef WOLFSSL_SNIFFER_STATS
  398. #define LOCK_STAT() do { wc_LockMutex(&StatsMutex); } while (0)
  399. #define UNLOCK_STAT() do { wc_UnLockMutex(&StatsMutex); } while (0)
  400. #define NOLOCK_ADD_TO_STAT(x,y) do { TraceStat(#x, y); x += y; } while (0)
  401. #define NOLOCK_INC_STAT(x) NOLOCK_ADD_TO_STAT(x,1)
  402. #define ADD_TO_STAT(x,y) do { LOCK_STAT(); \
  403. NOLOCK_ADD_TO_STAT(x,y); UNLOCK_STAT(); } while (0)
  404. #define INC_STAT(x) do { LOCK_STAT(); \
  405. NOLOCK_INC_STAT(x); UNLOCK_STAT(); } while (0)
  406. #endif
  407. #ifdef WOLF_CRYPTO_CB
  408. static WOLFSSL_GLOBAL int CryptoDeviceId = INVALID_DEVID;
  409. #endif
  410. /* Initialize overall Sniffer */
  411. void ssl_InitSniffer(void)
  412. {
  413. wolfSSL_Init();
  414. wc_InitMutex(&ServerListMutex);
  415. wc_InitMutex(&SessionMutex);
  416. wc_InitMutex(&RecoveryMutex);
  417. #ifdef WOLFSSL_SNIFFER_STATS
  418. XMEMSET(&SnifferStats, 0, sizeof(SSLStats));
  419. wc_InitMutex(&StatsMutex);
  420. #endif
  421. #ifdef WOLF_CRYPTO_CB
  422. #ifdef HAVE_INTEL_QA_SYNC
  423. CryptoDeviceId = wc_CryptoCb_InitIntelQa();
  424. if (INVALID_DEVID == CryptoDeviceId) {
  425. printf("Couldn't init the Intel QA\n");
  426. }
  427. #endif
  428. #ifdef HAVE_CAVIUM_OCTEON_SYNC
  429. CryptoDeviceId = wc_CryptoCb_InitOcteon();
  430. if (INVALID_DEVID == CryptoDeviceId) {
  431. printf("Couldn't init the Intel QA\n");
  432. }
  433. #endif
  434. #endif
  435. }
  436. #ifdef HAVE_SNI
  437. /* Free Named Key and the zero out the private key it holds */
  438. static void FreeNamedKey(NamedKey* in)
  439. {
  440. if (in) {
  441. if (in->key) {
  442. ForceZero(in->key, in->keySz);
  443. XFREE(in->key, NULL, DYNAMIC_TYPE_X509);
  444. }
  445. XFREE(in, NULL, DYNAMIC_TYPE_SNIFFER_NAMED_KEY);
  446. }
  447. }
  448. static void FreeNamedKeyList(NamedKey* in)
  449. {
  450. NamedKey* next;
  451. while (in) {
  452. next = in->next;
  453. FreeNamedKey(in);
  454. in = next;
  455. }
  456. }
  457. #endif
  458. /* Free Sniffer Server's resources/self */
  459. static void FreeSnifferServer(SnifferServer* srv)
  460. {
  461. if (srv) {
  462. #ifdef HAVE_SNI
  463. wc_LockMutex(&srv->namedKeysMutex);
  464. FreeNamedKeyList(srv->namedKeys);
  465. wc_UnLockMutex(&srv->namedKeysMutex);
  466. wc_FreeMutex(&srv->namedKeysMutex);
  467. #endif
  468. SSL_CTX_free(srv->ctx);
  469. }
  470. XFREE(srv, NULL, DYNAMIC_TYPE_SNIFFER_SERVER);
  471. }
  472. /* free PacketBuffer's resources/self */
  473. static void FreePacketBuffer(PacketBuffer* del)
  474. {
  475. if (del) {
  476. XFREE(del->data, NULL, DYNAMIC_TYPE_SNIFFER_PB_BUFFER);
  477. XFREE(del, NULL, DYNAMIC_TYPE_SNIFFER_PB);
  478. }
  479. }
  480. /* remove PacketBuffer List */
  481. static void FreePacketList(PacketBuffer* in)
  482. {
  483. if (in) {
  484. PacketBuffer* del;
  485. PacketBuffer* packet = in;
  486. while (packet) {
  487. del = packet;
  488. packet = packet->next;
  489. FreePacketBuffer(del);
  490. }
  491. }
  492. }
  493. /* Free Sniffer Session's resources/self */
  494. static void FreeSnifferSession(SnifferSession* session)
  495. {
  496. if (session) {
  497. SSL_free(session->sslClient);
  498. SSL_free(session->sslServer);
  499. FreePacketList(session->cliReassemblyList);
  500. FreePacketList(session->srvReassemblyList);
  501. XFREE(session->ticketID, NULL, DYNAMIC_TYPE_SNIFFER_TICKET_ID);
  502. #ifdef HAVE_EXTENDED_MASTER
  503. XFREE(session->hash, NULL, DYNAMIC_TYPE_HASHES);
  504. #endif
  505. }
  506. XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  507. }
  508. /* Free overall Sniffer */
  509. void ssl_FreeSniffer(void)
  510. {
  511. SnifferServer* srv;
  512. SnifferServer* removeServer;
  513. SnifferSession* session;
  514. SnifferSession* removeSession;
  515. int i;
  516. wc_LockMutex(&ServerListMutex);
  517. wc_LockMutex(&SessionMutex);
  518. srv = ServerList;
  519. while (srv) {
  520. removeServer = srv;
  521. srv = srv->next;
  522. FreeSnifferServer(removeServer);
  523. }
  524. for (i = 0; i < HASH_SIZE; i++) {
  525. session = SessionTable[i];
  526. while (session) {
  527. removeSession = session;
  528. session = session->next;
  529. FreeSnifferSession(removeSession);
  530. }
  531. }
  532. wc_UnLockMutex(&SessionMutex);
  533. wc_UnLockMutex(&ServerListMutex);
  534. wc_FreeMutex(&RecoveryMutex);
  535. wc_FreeMutex(&SessionMutex);
  536. wc_FreeMutex(&ServerListMutex);
  537. #ifdef WOLF_CRYPTO_CB
  538. #ifdef HAVE_INTEL_QA_SYNC
  539. wc_CryptoCb_CleanupIntelQa(&CryptoDeviceId);
  540. #endif
  541. #ifdef HAVE_CAVIUM_OCTEON_SYNC
  542. wc_CryptoCb_CleanupOcteon(&CryptoDeviceId);
  543. #endif
  544. #endif
  545. if (TraceFile) {
  546. TraceOn = 0;
  547. fclose(TraceFile);
  548. TraceFile = NULL;
  549. }
  550. wolfSSL_Cleanup();
  551. }
  552. #ifdef HAVE_EXTENDED_MASTER
  553. static int HashInit(HsHashes* hash)
  554. {
  555. int ret = 0;
  556. XMEMSET(hash, 0, sizeof(HsHashes));
  557. #ifndef NO_OLD_TLS
  558. #ifndef NO_SHA
  559. if (ret == 0)
  560. ret = wc_InitSha(&hash->hashSha);
  561. #endif
  562. #ifndef NO_MD5
  563. if (ret == 0) {
  564. ret = wc_InitMd5(&hash->hashMd5);
  565. }
  566. #endif
  567. #endif
  568. #ifndef NO_SHA256
  569. if (ret == 0)
  570. ret = wc_InitSha256(&hash->hashSha256);
  571. #endif
  572. #ifdef WOLFSSL_SHA384
  573. if (ret == 0)
  574. ret = wc_InitSha384(&hash->hashSha384);
  575. #endif
  576. return ret;
  577. }
  578. static int HashUpdate(HsHashes* hash, const byte* input, int sz)
  579. {
  580. int ret = 0;
  581. input -= HANDSHAKE_HEADER_SZ;
  582. sz += HANDSHAKE_HEADER_SZ;
  583. #ifndef NO_OLD_TLS
  584. #ifndef NO_SHA
  585. if (ret == 0)
  586. ret = wc_ShaUpdate(&hash->hashSha, input, sz);
  587. #endif
  588. #ifndef NO_MD5
  589. if (ret == 0) {
  590. ret = wc_Md5Update(&hash->hashMd5, input, sz);
  591. }
  592. #endif
  593. #endif
  594. #ifndef NO_SHA256
  595. if (ret == 0)
  596. ret = wc_Sha256Update(&hash->hashSha256, input, sz);
  597. #endif
  598. #ifdef WOLFSSL_SHA384
  599. if (ret == 0)
  600. ret = wc_Sha384Update(&hash->hashSha384, input, sz);
  601. #endif
  602. return ret;
  603. }
  604. static int HashCopy(HS_Hashes* d, HsHashes* s)
  605. {
  606. #ifndef NO_OLD_TLS
  607. #ifndef NO_SHA
  608. XMEMCPY(&d->hashSha, &s->hashSha, sizeof(wc_Sha));
  609. #endif
  610. #ifndef NO_MD5
  611. XMEMCPY(&d->hashMd5, &s->hashMd5, sizeof(wc_Md5));
  612. #endif
  613. #endif
  614. #ifndef NO_SHA256
  615. XMEMCPY(&d->hashSha256, &s->hashSha256, sizeof(wc_Sha256));
  616. #endif
  617. #ifdef WOLFSSL_SHA384
  618. XMEMCPY(&d->hashSha384, &s->hashSha384, sizeof(wc_Sha384));
  619. #endif
  620. return 0;
  621. }
  622. #endif
  623. /* Initialize a SnifferServer */
  624. static void InitSnifferServer(SnifferServer* sniffer)
  625. {
  626. XMEMSET(sniffer, 0, sizeof(SnifferServer));
  627. }
  628. /* Initialize session flags */
  629. static void InitFlags(Flags* flags)
  630. {
  631. XMEMSET(flags, 0, sizeof(Flags));
  632. }
  633. /* Initialize FIN Capture */
  634. static void InitFinCapture(FinCaputre* cap)
  635. {
  636. XMEMSET(cap, 0, sizeof(FinCaputre));
  637. }
  638. /* Initialize a Sniffer Session */
  639. static void InitSession(SnifferSession* session)
  640. {
  641. XMEMSET(session, 0, sizeof(SnifferSession));
  642. InitFlags(&session->flags);
  643. InitFinCapture(&session->finCaputre);
  644. }
  645. /* IP Info from IP Header */
  646. typedef struct IpInfo {
  647. int length; /* length of this header */
  648. int total; /* total length of fragment */
  649. IpAddrInfo src; /* network order source address */
  650. IpAddrInfo dst; /* network order destination address */
  651. } IpInfo;
  652. /* TCP Info from TCP Header */
  653. typedef struct TcpInfo {
  654. int srcPort; /* source port */
  655. int dstPort; /* source port */
  656. int length; /* length of this header */
  657. word32 sequence; /* sequence number */
  658. word32 ackNumber; /* ack number */
  659. byte fin; /* FIN set */
  660. byte rst; /* RST set */
  661. byte syn; /* SYN set */
  662. byte ack; /* ACK set */
  663. } TcpInfo;
  664. /* Tcp Pseudo Header for Checksum calculation */
  665. typedef struct TcpPseudoHdr {
  666. word32 src; /* source address */
  667. word32 dst; /* destination address */
  668. byte rsv; /* reserved, always 0 */
  669. byte protocol; /* IP protocol */
  670. word16 length; /* tcp header length + data length (doesn't include */
  671. /* pseudo header length) network order */
  672. } TcpPseudoHdr;
  673. /* Password Setting Callback */
  674. static int SetPassword(char* passwd, int sz, int rw, void* userdata)
  675. {
  676. (void)rw;
  677. XSTRNCPY(passwd, (const char*)userdata, sz);
  678. return (int)XSTRLEN((const char*)userdata);
  679. }
  680. /* Ethernet Header */
  681. typedef struct EthernetHdr {
  682. byte dst[ETHER_IF_ADDR_LEN]; /* destination host address */
  683. byte src[ETHER_IF_ADDR_LEN]; /* source host address */
  684. word16 type; /* IP, ARP, etc */
  685. } EthernetHdr;
  686. /* IPv4 Header */
  687. typedef struct IpHdr {
  688. byte ver_hl; /* version/header length */
  689. byte tos; /* type of service */
  690. word16 length; /* total length */
  691. word16 id; /* identification */
  692. word16 offset; /* fragment offset field */
  693. byte ttl; /* time to live */
  694. byte protocol; /* protocol */
  695. word16 sum; /* checksum */
  696. word32 src; /* source address */
  697. word32 dst; /* destination address */
  698. } IpHdr;
  699. /* IPv6 Header */
  700. typedef struct Ip6Hdr {
  701. byte ver_hl; /* version/traffic class high */
  702. byte tc_fl; /* traffic class low/flow label high */
  703. word16 fl; /* flow label low */
  704. word16 length; /* payload length */
  705. byte next_header; /* next header (6 for TCP, any other skip) */
  706. byte hl; /* hop limit */
  707. byte src[16]; /* source address */
  708. byte dst[16]; /* destination address */
  709. } Ip6Hdr;
  710. /* IPv6 extension header */
  711. typedef struct Ip6ExtHdr {
  712. byte next_header; /* next header (6 for TCP, any other skip) */
  713. byte length; /* length in 8-octet units - 1 */
  714. byte reserved[6];
  715. } Ip6ExtHdr;
  716. #define IP_HL(ip) ( (((ip)->ver_hl) & 0x0f) * 4)
  717. #define IP_V(ip) ( ((ip)->ver_hl) >> 4)
  718. /* TCP Header */
  719. typedef struct TcpHdr {
  720. word16 srcPort; /* source port */
  721. word16 dstPort; /* destination port */
  722. word32 sequence; /* sequence number */
  723. word32 ack; /* acknowledgment number */
  724. byte offset; /* data offset, reserved */
  725. byte flags; /* option flags */
  726. word16 window; /* window */
  727. word16 sum; /* checksum */
  728. word16 urgent; /* urgent pointer */
  729. } TcpHdr;
  730. #define TCP_LEN(tcp) ( (((tcp)->offset & 0xf0) >> 4) * 4)
  731. #define TCP_FIN 0x01
  732. #define TCP_SYN 0x02
  733. #define TCP_RST 0x04
  734. #define TCP_ACK 0x10
  735. /* Use platform specific GetError to write to trace file if tracing */
  736. static void Trace(int idx)
  737. {
  738. if (TraceOn) {
  739. char myBuffer[MAX_ERROR_LEN];
  740. GetError(idx, myBuffer);
  741. fprintf(TraceFile, "\t%s\n", myBuffer);
  742. #ifdef DEBUG_SNIFFER
  743. fprintf(stderr, "\t%s\n", myBuffer);
  744. #endif
  745. }
  746. }
  747. /* Show TimeStamp for beginning of packet Trace */
  748. static void TraceHeader(void)
  749. {
  750. if (TraceOn) {
  751. time_t ticks = time(NULL);
  752. fprintf(TraceFile, "\n%s", ctime(&ticks));
  753. }
  754. }
  755. /* Show Set Server info for Trace */
  756. static void TraceSetServer(const char* srv, int port, const char* keyFile)
  757. {
  758. if (TraceOn) {
  759. fprintf(TraceFile, "\tTrying to install a new Sniffer Server with\n");
  760. fprintf(TraceFile, "\tserver: %s, port: %d, keyFile: %s\n", srv, port,
  761. keyFile);
  762. }
  763. }
  764. #ifdef HAVE_SNI
  765. /* Show Set Named Server info for Trace */
  766. static void TraceSetNamedServer(const char* name,
  767. const char* srv, int port, const char* keyFile)
  768. {
  769. if (TraceOn) {
  770. fprintf(TraceFile, "\tTrying to install a new Sniffer Server with\n");
  771. fprintf(TraceFile, "\tname: %s, server: %s, port: %d, keyFile: %s\n",
  772. name, srv, port, keyFile);
  773. }
  774. }
  775. #endif
  776. /* Trace got packet number */
  777. static void TracePacket(void)
  778. {
  779. if (TraceOn) {
  780. static word32 packetNumber = 0;
  781. fprintf(TraceFile, "\tGot a Packet to decode, packet %u\n",
  782. ++packetNumber);
  783. }
  784. }
  785. /* Convert network byte order address into human readable */
  786. static const char* IpToS(int version, void* src, char* dst)
  787. {
  788. return inet_ntop(version, src, dst, TRACE_MSG_SZ);
  789. }
  790. /* Show destination and source address from Ip Hdr for packet Trace */
  791. static void TraceIP(IpHdr* iphdr)
  792. {
  793. if (TraceOn) {
  794. char src[TRACE_MSG_SZ];
  795. char dst[TRACE_MSG_SZ];
  796. fprintf(TraceFile, "\tdst:%s src:%s\n",
  797. IpToS(AF_INET, &iphdr->dst, dst),
  798. IpToS(AF_INET, &iphdr->src, src));
  799. }
  800. }
  801. /* Show destination and source address from Ip6Hdr for packet Trace */
  802. static void TraceIP6(Ip6Hdr* iphdr)
  803. {
  804. if (TraceOn) {
  805. char src[TRACE_MSG_SZ];
  806. char dst[TRACE_MSG_SZ];
  807. fprintf(TraceFile, "\tdst: %s src: %s\n",
  808. IpToS(AF_INET6, iphdr->dst, dst),
  809. IpToS(AF_INET6, iphdr->src, src));
  810. }
  811. }
  812. /* Show destination and source port from Tcp Hdr for packet Trace */
  813. static void TraceTcp(TcpHdr* tcphdr)
  814. {
  815. if (TraceOn) {
  816. fprintf(TraceFile, "\tdstPort:%u srcPort:%u\n", ntohs(tcphdr->dstPort),
  817. ntohs(tcphdr->srcPort));
  818. }
  819. }
  820. /* Show sequence and payload length for Trace */
  821. static void TraceSequence(word32 seq, int len)
  822. {
  823. if (TraceOn) {
  824. fprintf(TraceFile, "\tSequence:%u, payload length:%d\n", seq, len);
  825. }
  826. }
  827. /* Show sequence and payload length for Trace */
  828. static void TraceAck(word32 ack, word32 expected)
  829. {
  830. if (TraceOn) {
  831. fprintf(TraceFile, "\tAck:%u Expected:%u\n", ack, expected);
  832. }
  833. }
  834. /* Show relative expected and relative received sequences */
  835. static void TraceRelativeSequence(word32 expected, word32 got)
  836. {
  837. if (TraceOn) {
  838. fprintf(TraceFile, "\tExpected sequence:%u, received sequence:%u\n",
  839. expected, got);
  840. }
  841. }
  842. /* Show server sequence startup from SYN */
  843. static void TraceServerSyn(word32 seq)
  844. {
  845. if (TraceOn) {
  846. fprintf(TraceFile, "\tServer SYN, Sequence Start:%u\n", seq);
  847. }
  848. }
  849. /* Show client sequence startup from SYN */
  850. static void TraceClientSyn(word32 seq)
  851. {
  852. if (TraceOn) {
  853. fprintf(TraceFile, "\tClient SYN, Sequence Start:%u\n", seq);
  854. }
  855. }
  856. /* Show client FIN capture */
  857. static void TraceClientFin(word32 finSeq, word32 relSeq)
  858. {
  859. if (TraceOn) {
  860. fprintf(TraceFile, "\tClient FIN capture:%u, current SEQ:%u\n",
  861. finSeq, relSeq);
  862. }
  863. }
  864. /* Show server FIN capture */
  865. static void TraceServerFin(word32 finSeq, word32 relSeq)
  866. {
  867. if (TraceOn) {
  868. fprintf(TraceFile, "\tServer FIN capture:%u, current SEQ:%u\n",
  869. finSeq, relSeq);
  870. }
  871. }
  872. /* Show number of SSL data bytes decoded, could be 0 (ok) */
  873. static void TraceGotData(int bytes)
  874. {
  875. if (TraceOn) {
  876. fprintf(TraceFile, "\t%d bytes of SSL App data processed\n", bytes);
  877. }
  878. }
  879. /* Show bytes added to old SSL App data */
  880. static void TraceAddedData(int newBytes, int existingBytes)
  881. {
  882. if (TraceOn) {
  883. fprintf(TraceFile,
  884. "\t%d bytes added to %d existing bytes in User Buffer\n",
  885. newBytes, existingBytes);
  886. }
  887. }
  888. /* Show Stale Session */
  889. static void TraceStaleSession(void)
  890. {
  891. if (TraceOn) {
  892. fprintf(TraceFile, "\tFound a stale session\n");
  893. }
  894. }
  895. /* Show Finding Stale Sessions */
  896. static void TraceFindingStale(void)
  897. {
  898. if (TraceOn) {
  899. fprintf(TraceFile, "\tTrying to find Stale Sessions\n");
  900. }
  901. }
  902. /* Show Removed Session */
  903. static void TraceRemovedSession(void)
  904. {
  905. if (TraceOn) {
  906. fprintf(TraceFile, "\tRemoved it\n");
  907. }
  908. }
  909. /* Show SSLInfo if provided and is valid. */
  910. static void TraceSessionInfo(SSLInfo* sslInfo)
  911. {
  912. if (TraceOn) {
  913. if (sslInfo != NULL && sslInfo->isValid) {
  914. fprintf(TraceFile,
  915. "\tver:(%u %u) suiteId:(%02x %02x) suiteName:(%s) "
  916. #ifdef HAVE_SNI
  917. "sni:(%s) "
  918. #endif
  919. "keySize:(%u)\n",
  920. sslInfo->protocolVersionMajor,
  921. sslInfo->protocolVersionMinor,
  922. sslInfo->serverCipherSuite0,
  923. sslInfo->serverCipherSuite,
  924. sslInfo->serverCipherSuiteName,
  925. #ifdef HAVE_SNI
  926. sslInfo->serverNameIndication,
  927. #endif
  928. sslInfo->keySize);
  929. }
  930. }
  931. }
  932. #ifdef WOLFSSL_SNIFFER_STATS
  933. /* Show value added to a named statistic. */
  934. static void TraceStat(const char* name, int add)
  935. {
  936. if (TraceOn) {
  937. fprintf(TraceFile, "\tAdding %d to %s\n", add, name);
  938. }
  939. }
  940. #endif
  941. /* Set user error string */
  942. static void SetError(int idx, char* error, SnifferSession* session, int fatal)
  943. {
  944. GetError(idx, error);
  945. Trace(idx);
  946. if (session && fatal == FATAL_ERROR_STATE)
  947. session->flags.fatalError = 1;
  948. }
  949. /* Compare IpAddrInfo structs */
  950. static WC_INLINE int MatchAddr(IpAddrInfo l, IpAddrInfo r)
  951. {
  952. if (l.version == r.version) {
  953. if (l.version == IPV4)
  954. return (l.ip4 == r.ip4);
  955. else if (l.version == IPV6)
  956. return (0 == XMEMCMP(l.ip6, r.ip6, sizeof(l.ip6)));
  957. }
  958. return 0;
  959. }
  960. #ifndef WOLFSSL_SNIFFER_WATCH
  961. /* See if this IPV4 network order address has been registered */
  962. /* return 1 is true, 0 is false */
  963. static int IsServerRegistered(word32 addr)
  964. {
  965. int ret = 0; /* false */
  966. SnifferServer* sniffer;
  967. wc_LockMutex(&ServerListMutex);
  968. sniffer = ServerList;
  969. while (sniffer) {
  970. if (sniffer->server.ip4 == addr) {
  971. ret = 1;
  972. break;
  973. }
  974. sniffer = sniffer->next;
  975. }
  976. wc_UnLockMutex(&ServerListMutex);
  977. return ret;
  978. }
  979. /* See if this port has been registered to watch */
  980. /* See if this IPV4 network order address has been registered */
  981. /* return 1 is true, 0 is false */
  982. static int IsServerRegistered6(byte* addr)
  983. {
  984. int ret = 0; /* false */
  985. SnifferServer* sniffer;
  986. wc_LockMutex(&ServerListMutex);
  987. sniffer = ServerList;
  988. while (sniffer) {
  989. if (sniffer->server.version == IPV6 &&
  990. 0 == XMEMCMP(sniffer->server.ip6, addr, sizeof(sniffer->server.ip6))) {
  991. ret = 1;
  992. break;
  993. }
  994. sniffer = sniffer->next;
  995. }
  996. wc_UnLockMutex(&ServerListMutex);
  997. return ret;
  998. }
  999. /* See if this port has been registered to watch */
  1000. /* return 1 is true, 0 is false */
  1001. static int IsPortRegistered(word32 port)
  1002. {
  1003. int ret = 0; /* false */
  1004. SnifferServer* sniffer;
  1005. wc_LockMutex(&ServerListMutex);
  1006. sniffer = ServerList;
  1007. while (sniffer) {
  1008. if (sniffer->port == (int)port) {
  1009. ret = 1;
  1010. break;
  1011. }
  1012. sniffer = sniffer->next;
  1013. }
  1014. wc_UnLockMutex(&ServerListMutex);
  1015. return ret;
  1016. }
  1017. #endif
  1018. /* Get SnifferServer from IP and Port */
  1019. static SnifferServer* GetSnifferServer(IpInfo* ipInfo, TcpInfo* tcpInfo)
  1020. {
  1021. SnifferServer* sniffer;
  1022. wc_LockMutex(&ServerListMutex);
  1023. sniffer = ServerList;
  1024. #ifndef WOLFSSL_SNIFFER_WATCH
  1025. while (sniffer) {
  1026. if (sniffer->port == tcpInfo->srcPort &&
  1027. MatchAddr(sniffer->server, ipInfo->src))
  1028. break;
  1029. if (sniffer->port == tcpInfo->dstPort &&
  1030. MatchAddr(sniffer->server, ipInfo->dst))
  1031. break;
  1032. sniffer = sniffer->next;
  1033. }
  1034. #else
  1035. (void)ipInfo;
  1036. (void)tcpInfo;
  1037. #endif
  1038. wc_UnLockMutex(&ServerListMutex);
  1039. return sniffer;
  1040. }
  1041. /* Hash the Session Info, return hash row */
  1042. static word32 SessionHash(IpInfo* ipInfo, TcpInfo* tcpInfo)
  1043. {
  1044. word32 hash = 1;
  1045. if (ipInfo->src.version == IPV4) {
  1046. hash *= ipInfo->src.ip4 * ipInfo->dst.ip4;
  1047. }
  1048. else if (ipInfo->src.version == IPV6) {
  1049. word32* x;
  1050. word32 y;
  1051. x = (word32*)ipInfo->src.ip6;
  1052. y = x[0] ^ x[1] ^ x[2] ^ x[3];
  1053. hash *= y;
  1054. x = (word32*)ipInfo->dst.ip6;
  1055. y = x[0] ^ x[1] ^ x[2] ^ x[3];
  1056. hash *= y;
  1057. }
  1058. hash *= tcpInfo->srcPort * tcpInfo->dstPort;
  1059. return hash % HASH_SIZE;
  1060. }
  1061. /* Get Existing SnifferSession from IP and Port */
  1062. static SnifferSession* GetSnifferSession(IpInfo* ipInfo, TcpInfo* tcpInfo)
  1063. {
  1064. SnifferSession* session;
  1065. time_t currTime = time(NULL);
  1066. word32 row = SessionHash(ipInfo, tcpInfo);
  1067. assert(row <= HASH_SIZE);
  1068. wc_LockMutex(&SessionMutex);
  1069. session = SessionTable[row];
  1070. while (session) {
  1071. if (MatchAddr(session->server, ipInfo->src) &&
  1072. MatchAddr(session->client, ipInfo->dst) &&
  1073. session->srvPort == tcpInfo->srcPort &&
  1074. session->cliPort == tcpInfo->dstPort)
  1075. break;
  1076. if (MatchAddr(session->client, ipInfo->src) &&
  1077. MatchAddr(session->server, ipInfo->dst) &&
  1078. session->cliPort == tcpInfo->srcPort &&
  1079. session->srvPort == tcpInfo->dstPort)
  1080. break;
  1081. session = session->next;
  1082. }
  1083. if (session)
  1084. session->lastUsed= currTime; /* keep session alive, remove stale will */
  1085. /* leave alone */
  1086. wc_UnLockMutex(&SessionMutex);
  1087. /* determine side */
  1088. if (session) {
  1089. if (MatchAddr(ipInfo->dst, session->server) &&
  1090. tcpInfo->dstPort == session->srvPort) {
  1091. session->flags.side = WOLFSSL_SERVER_END;
  1092. }
  1093. else {
  1094. session->flags.side = WOLFSSL_CLIENT_END;
  1095. }
  1096. }
  1097. return session;
  1098. }
  1099. #if defined(HAVE_SNI) || defined(WOLFSSL_SNIFFER_WATCH)
  1100. static int LoadKeyFile(byte** keyBuf, word32* keyBufSz,
  1101. const char* keyFile, int typeKey,
  1102. const char* password)
  1103. {
  1104. byte* loadBuf;
  1105. long fileSz = 0;
  1106. XFILE file;
  1107. int ret;
  1108. if (keyBuf == NULL || keyBufSz == NULL || keyFile == NULL) {
  1109. return -1;
  1110. }
  1111. file = XFOPEN(keyFile, "rb");
  1112. if (file == XBADFILE) return -1;
  1113. if(XFSEEK(file, 0, XSEEK_END) != 0) {
  1114. XFCLOSE(file);
  1115. return -1;
  1116. }
  1117. fileSz = XFTELL(file);
  1118. if (fileSz > MAX_WOLFSSL_FILE_SIZE || fileSz < 0) {
  1119. XFCLOSE(file);
  1120. return -1;
  1121. }
  1122. XREWIND(file);
  1123. loadBuf = (byte*)XMALLOC(fileSz, NULL, DYNAMIC_TYPE_FILE);
  1124. if (loadBuf == NULL) {
  1125. XFCLOSE(file);
  1126. return -1;
  1127. }
  1128. ret = (int)XFREAD(loadBuf, 1, fileSz, file);
  1129. XFCLOSE(file);
  1130. if (ret != fileSz) {
  1131. XFREE(loadBuf, NULL, DYNAMIC_TYPE_FILE);
  1132. return -1;
  1133. }
  1134. if (typeKey == WOLFSSL_FILETYPE_PEM) {
  1135. byte* saveBuf = (byte*)XMALLOC(fileSz, NULL, DYNAMIC_TYPE_X509);
  1136. int saveBufSz = 0;
  1137. ret = -1;
  1138. if (saveBuf != NULL) {
  1139. saveBufSz = wc_KeyPemToDer(loadBuf, (int)fileSz,
  1140. saveBuf, (int)fileSz, password);
  1141. if (saveBufSz < 0) {
  1142. saveBufSz = 0;
  1143. XFREE(saveBuf, NULL, DYNAMIC_TYPE_X509);
  1144. saveBuf = NULL;
  1145. }
  1146. else
  1147. ret = 0;
  1148. }
  1149. ForceZero(loadBuf, (word32)fileSz);
  1150. XFREE(loadBuf, NULL, DYNAMIC_TYPE_FILE);
  1151. if (saveBuf) {
  1152. *keyBuf = saveBuf;
  1153. *keyBufSz = (word32)saveBufSz;
  1154. }
  1155. }
  1156. else {
  1157. *keyBuf = loadBuf;
  1158. *keyBufSz = (word32)fileSz;
  1159. }
  1160. if (ret < 0) {
  1161. return -1;
  1162. }
  1163. return ret;
  1164. }
  1165. #endif
  1166. #ifdef WOLFSSL_SNIFFER_WATCH
  1167. static int CreateWatchSnifferServer(char* error)
  1168. {
  1169. SnifferServer* sniffer;
  1170. sniffer = (SnifferServer*)XMALLOC(sizeof(SnifferServer), NULL,
  1171. DYNAMIC_TYPE_SNIFFER_SERVER);
  1172. if (sniffer == NULL) {
  1173. SetError(MEMORY_STR, error, NULL, 0);
  1174. return -1;
  1175. }
  1176. InitSnifferServer(sniffer);
  1177. sniffer->ctx = SSL_CTX_new(TLSv1_2_client_method());
  1178. if (!sniffer->ctx) {
  1179. SetError(MEMORY_STR, error, NULL, 0);
  1180. FreeSnifferServer(sniffer);
  1181. return -1;
  1182. }
  1183. #ifdef WOLF_CRYPTO_CB
  1184. if (CryptoDeviceId != INVALID_DEVID)
  1185. wolfSSL_CTX_SetDevId(sniffer->ctx, CryptoDeviceId);
  1186. #endif
  1187. ServerList = sniffer;
  1188. return 0;
  1189. }
  1190. #endif
  1191. static int SetNamedPrivateKey(const char* name, const char* address, int port,
  1192. const char* keyFile, int typeKey, const char* password, char* error)
  1193. {
  1194. SnifferServer* sniffer;
  1195. int ret;
  1196. int type = (typeKey == FILETYPE_PEM) ? WOLFSSL_FILETYPE_PEM :
  1197. WOLFSSL_FILETYPE_ASN1;
  1198. int isNew = 0;
  1199. IpAddrInfo serverIp;
  1200. #ifdef HAVE_SNI
  1201. NamedKey* namedKey = NULL;
  1202. #endif
  1203. (void)name;
  1204. #ifdef HAVE_SNI
  1205. if (name != NULL) {
  1206. namedKey = (NamedKey*)XMALLOC(sizeof(NamedKey),
  1207. NULL, DYNAMIC_TYPE_SNIFFER_NAMED_KEY);
  1208. if (namedKey == NULL) {
  1209. SetError(MEMORY_STR, error, NULL, 0);
  1210. return -1;
  1211. }
  1212. XMEMSET(namedKey, 0, sizeof(NamedKey));
  1213. namedKey->nameSz = (word32)XSTRLEN(name);
  1214. if (namedKey->nameSz > sizeof(namedKey->name)-1)
  1215. namedKey->nameSz = sizeof(namedKey->name)-1;
  1216. XSTRNCPY(namedKey->name, name, namedKey->nameSz);
  1217. namedKey->name[MAX_SERVER_NAME-1] = '\0';
  1218. ret = LoadKeyFile(&namedKey->key, &namedKey->keySz,
  1219. keyFile, type, password);
  1220. if (ret < 0) {
  1221. SetError(KEY_FILE_STR, error, NULL, 0);
  1222. FreeNamedKey(namedKey);
  1223. return -1;
  1224. }
  1225. }
  1226. #endif
  1227. serverIp.version = IPV4;
  1228. serverIp.ip4 = inet_addr(address);
  1229. if (serverIp.ip4 == INADDR_NONE) {
  1230. if (inet_pton(AF_INET6, address, serverIp.ip6) == 1) {
  1231. serverIp.version = IPV6;
  1232. }
  1233. }
  1234. sniffer = ServerList;
  1235. while (sniffer != NULL &&
  1236. (!MatchAddr(sniffer->server, serverIp) || sniffer->port != port)) {
  1237. sniffer = sniffer->next;
  1238. }
  1239. if (sniffer == NULL) {
  1240. isNew = 1;
  1241. sniffer = (SnifferServer*)XMALLOC(sizeof(SnifferServer),
  1242. NULL, DYNAMIC_TYPE_SNIFFER_SERVER);
  1243. if (sniffer == NULL) {
  1244. SetError(MEMORY_STR, error, NULL, 0);
  1245. #ifdef HAVE_SNI
  1246. FreeNamedKey(namedKey);
  1247. #endif
  1248. return -1;
  1249. }
  1250. InitSnifferServer(sniffer);
  1251. XSTRNCPY(sniffer->address, address, MAX_SERVER_ADDRESS-1);
  1252. sniffer->address[MAX_SERVER_ADDRESS-1] = '\0';
  1253. sniffer->server = serverIp;
  1254. sniffer->port = port;
  1255. sniffer->ctx = SSL_CTX_new(TLSv1_2_client_method());
  1256. if (!sniffer->ctx) {
  1257. SetError(MEMORY_STR, error, NULL, 0);
  1258. #ifdef HAVE_SNI
  1259. FreeNamedKey(namedKey);
  1260. #endif
  1261. FreeSnifferServer(sniffer);
  1262. return -1;
  1263. }
  1264. }
  1265. if (name == NULL) {
  1266. if (password) {
  1267. #ifdef WOLFSSL_ENCRYPTED_KEYS
  1268. SSL_CTX_set_default_passwd_cb(sniffer->ctx, SetPassword);
  1269. SSL_CTX_set_default_passwd_cb_userdata(
  1270. sniffer->ctx, (void*)password);
  1271. #endif
  1272. }
  1273. ret = SSL_CTX_use_PrivateKey_file(sniffer->ctx, keyFile, type);
  1274. if (ret != WOLFSSL_SUCCESS) {
  1275. SetError(KEY_FILE_STR, error, NULL, 0);
  1276. if (isNew)
  1277. FreeSnifferServer(sniffer);
  1278. return -1;
  1279. }
  1280. #ifdef WOLF_CRYPTO_CB
  1281. wolfSSL_CTX_SetDevId(sniffer->ctx, CryptoDeviceId);
  1282. #endif
  1283. }
  1284. #ifdef HAVE_SNI
  1285. else {
  1286. wc_LockMutex(&sniffer->namedKeysMutex);
  1287. namedKey->next = sniffer->namedKeys;
  1288. sniffer->namedKeys = namedKey;
  1289. wc_UnLockMutex(&sniffer->namedKeysMutex);
  1290. }
  1291. #endif
  1292. if (isNew) {
  1293. sniffer->next = ServerList;
  1294. ServerList = sniffer;
  1295. }
  1296. return 0;
  1297. }
  1298. #ifdef HAVE_SNI
  1299. /* Sets the private key for a specific name, server and port */
  1300. /* returns 0 on success, -1 on error */
  1301. int ssl_SetNamedPrivateKey(const char* name,
  1302. const char* address, int port,
  1303. const char* keyFile, int typeKey,
  1304. const char* password, char* error)
  1305. {
  1306. int ret;
  1307. TraceHeader();
  1308. TraceSetNamedServer(name, address, port, keyFile);
  1309. wc_LockMutex(&ServerListMutex);
  1310. ret = SetNamedPrivateKey(name, address, port, keyFile,
  1311. typeKey, password, error);
  1312. wc_UnLockMutex(&ServerListMutex);
  1313. if (ret == 0)
  1314. Trace(NEW_SERVER_STR);
  1315. return ret;
  1316. }
  1317. #endif
  1318. /* Sets the private key for a specific server and port */
  1319. /* returns 0 on success, -1 on error */
  1320. int ssl_SetPrivateKey(const char* address, int port, const char* keyFile,
  1321. int typeKey, const char* password, char* error)
  1322. {
  1323. int ret;
  1324. TraceHeader();
  1325. TraceSetServer(address, port, keyFile);
  1326. wc_LockMutex(&ServerListMutex);
  1327. ret = SetNamedPrivateKey(NULL, address, port, keyFile,
  1328. typeKey, password, error);
  1329. wc_UnLockMutex(&ServerListMutex);
  1330. if (ret == 0)
  1331. Trace(NEW_SERVER_STR);
  1332. return ret;
  1333. }
  1334. /* Check IP Header for IPV6, TCP, and a registered server address */
  1335. /* returns 0 on success, -1 on error */
  1336. static int CheckIp6Hdr(Ip6Hdr* iphdr, IpInfo* info, int length, char* error)
  1337. {
  1338. int version = IP_V(iphdr);
  1339. int exthdrsz = IP6_HDR_SZ;
  1340. TraceIP6(iphdr);
  1341. Trace(IP_CHECK_STR);
  1342. if (version != IPV6) {
  1343. SetError(BAD_IPVER_STR, error, NULL, 0);
  1344. return -1;
  1345. }
  1346. /* Here, we need to move onto next header if not TCP. */
  1347. if (iphdr->next_header != TCP_PROTOCOL) {
  1348. Ip6ExtHdr* exthdr = (Ip6ExtHdr*)((byte*)iphdr + IP6_HDR_SZ);
  1349. do {
  1350. int hdrsz = (exthdr->length + 1) * 8;
  1351. if (hdrsz > length - exthdrsz) {
  1352. SetError(PACKET_HDR_SHORT_STR, error, NULL, 0);
  1353. return -1;
  1354. }
  1355. exthdrsz += hdrsz;
  1356. exthdr = (Ip6ExtHdr*)((byte*)exthdr + hdrsz);
  1357. }
  1358. while (exthdr->next_header != TCP_PROTOCOL &&
  1359. exthdr->next_header != NO_NEXT_HEADER);
  1360. }
  1361. #ifndef WOLFSSL_SNIFFER_WATCH
  1362. if (!IsServerRegistered6(iphdr->src) && !IsServerRegistered6(iphdr->dst)) {
  1363. SetError(SERVER_NOT_REG_STR, error, NULL, 0);
  1364. return -1;
  1365. }
  1366. #endif
  1367. info->length = exthdrsz;
  1368. info->total = ntohs(iphdr->length) + info->length;
  1369. /* IPv6 doesn't include its own header size in the length like v4. */
  1370. info->src.version = IPV6;
  1371. XMEMCPY(info->src.ip6, iphdr->src, sizeof(info->src.ip6));
  1372. info->dst.version = IPV6;
  1373. XMEMCPY(info->dst.ip6, iphdr->dst, sizeof(info->dst.ip6));
  1374. return 0;
  1375. }
  1376. /* Check IP Header for IPV4, TCP, and a registered server address */
  1377. /* If header IPv6, pass to CheckIp6Hdr(). */
  1378. /* returns 0 on success, -1 on error */
  1379. static int CheckIpHdr(IpHdr* iphdr, IpInfo* info, int length, char* error)
  1380. {
  1381. int version = IP_V(iphdr);
  1382. if (version == IPV6)
  1383. return CheckIp6Hdr((Ip6Hdr*)iphdr, info, length, error);
  1384. TraceIP(iphdr);
  1385. Trace(IP_CHECK_STR);
  1386. if (version != IPV4) {
  1387. SetError(BAD_IPVER_STR, error, NULL, 0);
  1388. return -1;
  1389. }
  1390. if (iphdr->protocol != TCP_PROTOCOL) {
  1391. SetError(BAD_PROTO_STR, error, NULL, 0);
  1392. return -1;
  1393. }
  1394. #ifndef WOLFSSL_SNIFFER_WATCH
  1395. if (!IsServerRegistered(iphdr->src) && !IsServerRegistered(iphdr->dst)) {
  1396. SetError(SERVER_NOT_REG_STR, error, NULL, 0);
  1397. return -1;
  1398. }
  1399. #endif
  1400. info->length = IP_HL(iphdr);
  1401. info->total = ntohs(iphdr->length);
  1402. info->src.version = IPV4;
  1403. info->src.ip4 = iphdr->src;
  1404. info->dst.version = IPV4;
  1405. info->dst.ip4 = iphdr->dst;
  1406. if (info->total == 0)
  1407. info->total = length; /* reassembled may be off */
  1408. return 0;
  1409. }
  1410. /* Check TCP Header for a registered port */
  1411. /* returns 0 on success, -1 on error */
  1412. static int CheckTcpHdr(TcpHdr* tcphdr, TcpInfo* info, char* error)
  1413. {
  1414. TraceTcp(tcphdr);
  1415. Trace(TCP_CHECK_STR);
  1416. info->srcPort = ntohs(tcphdr->srcPort);
  1417. info->dstPort = ntohs(tcphdr->dstPort);
  1418. info->length = TCP_LEN(tcphdr);
  1419. info->sequence = ntohl(tcphdr->sequence);
  1420. info->fin = tcphdr->flags & TCP_FIN;
  1421. info->rst = tcphdr->flags & TCP_RST;
  1422. info->syn = tcphdr->flags & TCP_SYN;
  1423. info->ack = tcphdr->flags & TCP_ACK;
  1424. if (info->ack)
  1425. info->ackNumber = ntohl(tcphdr->ack);
  1426. #ifndef WOLFSSL_SNIFFER_WATCH
  1427. if (!IsPortRegistered(info->srcPort) && !IsPortRegistered(info->dstPort)) {
  1428. SetError(SERVER_PORT_NOT_REG_STR, error, NULL, 0);
  1429. return -1;
  1430. }
  1431. #else
  1432. (void)error;
  1433. #endif
  1434. return 0;
  1435. }
  1436. /* Decode Record Layer Header */
  1437. static int GetRecordHeader(const byte* input, RecordLayerHeader* rh, int* size)
  1438. {
  1439. XMEMCPY(rh, input, RECORD_HEADER_SZ);
  1440. *size = (rh->length[0] << 8) | rh->length[1];
  1441. if (*size > (MAX_RECORD_SIZE + COMP_EXTRA + MAX_MSG_EXTRA))
  1442. return LENGTH_ERROR;
  1443. return 0;
  1444. }
  1445. /* Copies the session's information to the provided sslInfo. Skip copy if
  1446. * SSLInfo is not provided. */
  1447. static void CopySessionInfo(SnifferSession* session, SSLInfo* sslInfo)
  1448. {
  1449. if (NULL != sslInfo) {
  1450. XMEMSET(sslInfo, 0, sizeof(SSLInfo));
  1451. /* Pass back Session Info after we have processed the Server Hello. */
  1452. if (0 != session->sslServer->options.cipherSuite) {
  1453. const char* pCipher;
  1454. sslInfo->isValid = 1;
  1455. sslInfo->protocolVersionMajor = session->sslServer->version.major;
  1456. sslInfo->protocolVersionMinor = session->sslServer->version.minor;
  1457. sslInfo->serverCipherSuite0 =
  1458. session->sslServer->options.cipherSuite0;
  1459. sslInfo->serverCipherSuite =
  1460. session->sslServer->options.cipherSuite;
  1461. pCipher = wolfSSL_get_cipher(session->sslServer);
  1462. if (NULL != pCipher) {
  1463. XSTRNCPY((char*)sslInfo->serverCipherSuiteName, pCipher,
  1464. sizeof(sslInfo->serverCipherSuiteName));
  1465. sslInfo->serverCipherSuiteName
  1466. [sizeof(sslInfo->serverCipherSuiteName) - 1] = '\0';
  1467. }
  1468. sslInfo->keySize = session->keySz;
  1469. #ifdef HAVE_SNI
  1470. if (NULL != session->sni) {
  1471. XSTRNCPY((char*)sslInfo->serverNameIndication,
  1472. session->sni, sizeof(sslInfo->serverNameIndication));
  1473. sslInfo->serverNameIndication
  1474. [sizeof(sslInfo->serverNameIndication) - 1] = '\0';
  1475. }
  1476. #endif
  1477. TraceSessionInfo(sslInfo);
  1478. }
  1479. }
  1480. }
  1481. /* Call the session connection start callback. */
  1482. static void CallConnectionCb(SnifferSession* session)
  1483. {
  1484. if (ConnectionCb != NULL) {
  1485. SSLInfo info;
  1486. CopySessionInfo(session, &info);
  1487. ConnectionCb((const void*)session, &info, ConnectionCbCtx);
  1488. }
  1489. }
  1490. /* Process Client Key Exchange, RSA or static ECDH */
  1491. static int ProcessClientKeyExchange(const byte* input, int* sslBytes,
  1492. SnifferSession* session, char* error)
  1493. {
  1494. word32 idx = 0;
  1495. int tryEcc = 0;
  1496. int ret;
  1497. if (session->sslServer->buffers.key == NULL ||
  1498. session->sslServer->buffers.key->buffer == NULL ||
  1499. session->sslServer->buffers.key->length == 0) {
  1500. SetError(RSA_KEY_MISSING_STR, error, session, FATAL_ERROR_STATE);
  1501. return -1;
  1502. }
  1503. {
  1504. RsaKey key;
  1505. int length;
  1506. ret = wc_InitRsaKey(&key, 0);
  1507. if (ret == 0) {
  1508. ret = wc_RsaPrivateKeyDecode(
  1509. session->sslServer->buffers.key->buffer,
  1510. &idx, &key, session->sslServer->buffers.key->length);
  1511. if (ret != 0) {
  1512. tryEcc = 1;
  1513. #ifndef HAVE_ECC
  1514. SetError(RSA_DECODE_STR, error, session, FATAL_ERROR_STATE);
  1515. #else
  1516. /* If we can do ECC, this isn't fatal. Not loading an ECC
  1517. * key will be fatal, though. */
  1518. SetError(RSA_DECODE_STR, error, session, 0);
  1519. #endif
  1520. }
  1521. }
  1522. if (ret == 0) {
  1523. length = wc_RsaEncryptSize(&key);
  1524. if (IsTLS(session->sslServer)) {
  1525. input += 2; /* tls pre length */
  1526. }
  1527. if (length > *sslBytes) {
  1528. SetError(PARTIAL_INPUT_STR, error, session, FATAL_ERROR_STATE);
  1529. ret = -1;
  1530. }
  1531. }
  1532. #ifdef WC_RSA_BLINDING
  1533. if (ret == 0) {
  1534. ret = wc_RsaSetRNG(&key, session->sslServer->rng);
  1535. if (ret != 0) {
  1536. SetError(RSA_DECRYPT_STR, error, session, FATAL_ERROR_STATE);
  1537. }
  1538. }
  1539. #endif
  1540. if (ret == 0) {
  1541. session->keySz = length * WOLFSSL_BIT_SIZE;
  1542. /* length is the key size in bytes */
  1543. session->sslServer->arrays->preMasterSz = SECRET_LEN;
  1544. do {
  1545. #ifdef WOLFSSL_ASYNC_CRYPT
  1546. ret = wc_AsyncWait(ret, &key.asyncDev,
  1547. WC_ASYNC_FLAG_CALL_AGAIN);
  1548. #endif
  1549. if (ret >= 0) {
  1550. ret = wc_RsaPrivateDecrypt(input, length,
  1551. session->sslServer->arrays->preMasterSecret,
  1552. session->sslServer->arrays->preMasterSz, &key);
  1553. }
  1554. } while (ret == WC_PENDING_E);
  1555. if (ret != SECRET_LEN) {
  1556. SetError(RSA_DECRYPT_STR, error, session, FATAL_ERROR_STATE);
  1557. }
  1558. }
  1559. wc_FreeRsaKey(&key);
  1560. }
  1561. if (tryEcc) {
  1562. #ifdef HAVE_ECC
  1563. ecc_key key;
  1564. ecc_key pubKey;
  1565. int length, keyInit = 0, pubKeyInit = 0;
  1566. idx = 0;
  1567. ret = wc_ecc_init(&key);
  1568. if (ret == 0) {
  1569. keyInit = 1;
  1570. ret = wc_ecc_init(&pubKey);
  1571. }
  1572. if (ret == 0) {
  1573. pubKeyInit = 1;
  1574. ret = wc_EccPrivateKeyDecode(
  1575. session->sslServer->buffers.key->buffer,
  1576. &idx, &key, session->sslServer->buffers.key->length);
  1577. if (ret != 0) {
  1578. SetError(ECC_DECODE_STR, error, session, FATAL_ERROR_STATE);
  1579. }
  1580. }
  1581. if (ret == 0) {
  1582. length = wc_ecc_size(&key) * 2 + 1;
  1583. /* The length should be 2 times the key size (x and y), plus 1
  1584. * for the type byte. */
  1585. if (IsTLS(session->sslServer)) {
  1586. input += 1; /* Don't include the TLS length for the key. */
  1587. }
  1588. if (length + 1 > *sslBytes) {
  1589. SetError(PARTIAL_INPUT_STR,
  1590. error, session, FATAL_ERROR_STATE);
  1591. ret = -1;
  1592. }
  1593. }
  1594. if (ret == 0) {
  1595. ret = wc_ecc_import_x963_ex(input, length, &pubKey, ECC_CURVE_DEF);
  1596. if (ret != 0) {
  1597. SetError(ECC_PUB_DECODE_STR, error, session, FATAL_ERROR_STATE);
  1598. }
  1599. }
  1600. if (ret == 0) {
  1601. session->keySz = ((length - 1) / 2) * WOLFSSL_BIT_SIZE;
  1602. /* Length is in bytes. Subtract 1 for the ECC key type. Divide
  1603. * by two as the key is in (x,y) coordinates, where x and y are
  1604. * the same size, the key size. Convert from bytes to bits. */
  1605. session->sslServer->arrays->preMasterSz = ENCRYPT_LEN;
  1606. do {
  1607. #ifdef WOLFSSL_ASYNC_CRYPT
  1608. ret = wc_AsyncWait(ret, &key.asyncDev,
  1609. WC_ASYNC_FLAG_CALL_AGAIN);
  1610. #endif
  1611. if (ret >= 0) {
  1612. ret = wc_ecc_shared_secret(&key, &pubKey,
  1613. session->sslServer->arrays->preMasterSecret,
  1614. &session->sslServer->arrays->preMasterSz);
  1615. }
  1616. } while (ret == WC_PENDING_E);
  1617. }
  1618. #ifdef WOLFSSL_SNIFFER_STATS
  1619. if (ret != 0)
  1620. INC_STAT(SnifferStats.sslKeyFails);
  1621. #endif
  1622. if (keyInit)
  1623. wc_ecc_free(&key);
  1624. if (pubKeyInit)
  1625. wc_ecc_free(&pubKey);
  1626. #endif
  1627. }
  1628. /* store for client side as well */
  1629. XMEMCPY(session->sslClient->arrays->preMasterSecret,
  1630. session->sslServer->arrays->preMasterSecret,
  1631. session->sslServer->arrays->preMasterSz);
  1632. session->sslClient->arrays->preMasterSz =
  1633. session->sslServer->arrays->preMasterSz;
  1634. #ifdef SHOW_SECRETS
  1635. {
  1636. word32 i;
  1637. printf("pre master secret: ");
  1638. for (i = 0; i < session->sslServer->arrays->preMasterSz; i++)
  1639. printf("%02x", session->sslServer->arrays->preMasterSecret[i]);
  1640. printf("\n");
  1641. }
  1642. #endif
  1643. if (SetCipherSpecs(session->sslServer) != 0) {
  1644. SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
  1645. return -1;
  1646. }
  1647. if (SetCipherSpecs(session->sslClient) != 0) {
  1648. SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
  1649. return -1;
  1650. }
  1651. ret = MakeMasterSecret(session->sslServer);
  1652. ret += MakeMasterSecret(session->sslClient);
  1653. ret += SetKeysSide(session->sslServer, ENCRYPT_AND_DECRYPT_SIDE);
  1654. ret += SetKeysSide(session->sslClient, ENCRYPT_AND_DECRYPT_SIDE);
  1655. if (ret != 0) {
  1656. SetError(BAD_DERIVE_STR, error, session, FATAL_ERROR_STATE);
  1657. return -1;
  1658. }
  1659. #ifdef SHOW_SECRETS
  1660. {
  1661. int i;
  1662. printf("server master secret: ");
  1663. for (i = 0; i < SECRET_LEN; i++)
  1664. printf("%02x", session->sslServer->arrays->masterSecret[i]);
  1665. printf("\n");
  1666. printf("client master secret: ");
  1667. for (i = 0; i < SECRET_LEN; i++)
  1668. printf("%02x", session->sslClient->arrays->masterSecret[i]);
  1669. printf("\n");
  1670. printf("server suite = %d\n", session->sslServer->options.cipherSuite);
  1671. printf("client suite = %d\n", session->sslClient->options.cipherSuite);
  1672. }
  1673. #endif
  1674. CallConnectionCb(session);
  1675. return ret;
  1676. }
  1677. /* Process Session Ticket */
  1678. static int ProcessSessionTicket(const byte* input, int* sslBytes,
  1679. SnifferSession* session, char* error)
  1680. {
  1681. word16 len;
  1682. /* make sure can read through hint and len */
  1683. if (TICKET_HINT_LEN + LENGTH_SZ > *sslBytes) {
  1684. SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
  1685. return -1;
  1686. }
  1687. input += TICKET_HINT_LEN; /* skip over hint */
  1688. *sslBytes -= TICKET_HINT_LEN;
  1689. len = (word16)((input[0] << 8) | input[1]);
  1690. input += LENGTH_SZ;
  1691. *sslBytes -= LENGTH_SZ;
  1692. /* make sure can read through ticket */
  1693. if (len > *sslBytes || len < ID_LEN) {
  1694. SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
  1695. return -1;
  1696. }
  1697. /* store session with macID as sessionID */
  1698. session->sslServer->options.haveSessionId = 1;
  1699. XMEMCPY(session->sslServer->arrays->sessionID, input + len - ID_LEN,ID_LEN);
  1700. return 0;
  1701. }
  1702. /* Process Server Hello */
  1703. static int ProcessServerHello(int msgSz, const byte* input, int* sslBytes,
  1704. SnifferSession* session, char* error)
  1705. {
  1706. ProtocolVersion pv;
  1707. byte b, b0;
  1708. int toRead = VERSION_SZ + RAN_LEN + ENUM_LEN;
  1709. int doResume = 0;
  1710. int initialBytes = *sslBytes;
  1711. (void)msgSz;
  1712. (void)initialBytes;
  1713. /* make sure we didn't miss ClientHello */
  1714. if (session->flags.clientHello == 0) {
  1715. SetError(MISSED_CLIENT_HELLO_STR, error, session, FATAL_ERROR_STATE);
  1716. return -1;
  1717. }
  1718. /* make sure can read through session len */
  1719. if (toRead > *sslBytes) {
  1720. SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  1721. return -1;
  1722. }
  1723. XMEMCPY(&pv, input, VERSION_SZ);
  1724. input += VERSION_SZ;
  1725. *sslBytes -= VERSION_SZ;
  1726. session->sslServer->version = pv;
  1727. session->sslClient->version = pv;
  1728. XMEMCPY(session->sslServer->arrays->serverRandom, input, RAN_LEN);
  1729. XMEMCPY(session->sslClient->arrays->serverRandom, input, RAN_LEN);
  1730. input += RAN_LEN;
  1731. *sslBytes -= RAN_LEN;
  1732. b = *input++;
  1733. *sslBytes -= 1;
  1734. /* make sure can read through compression */
  1735. if ( (b + SUITE_LEN + ENUM_LEN) > *sslBytes) {
  1736. SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  1737. return -1;
  1738. }
  1739. if (b) {
  1740. XMEMCPY(session->sslServer->arrays->sessionID, input, ID_LEN);
  1741. session->sslServer->options.haveSessionId = 1;
  1742. }
  1743. input += b;
  1744. *sslBytes -= b;
  1745. /* cipher suite */
  1746. b0 = *input++; /* first byte, ECC or not */
  1747. session->sslServer->options.cipherSuite0 = b0;
  1748. session->sslClient->options.cipherSuite0 = b0;
  1749. b = *input++;
  1750. session->sslServer->options.cipherSuite = b;
  1751. session->sslClient->options.cipherSuite = b;
  1752. *sslBytes -= SUITE_LEN;
  1753. #ifdef WOLFSSL_SNIFFER_STATS
  1754. {
  1755. const CipherSuiteInfo* suites = GetCipherNames();
  1756. int suitesSz = GetCipherNamesSize();
  1757. int match = 0;
  1758. while (suitesSz) {
  1759. if (b0 == suites->cipherSuite0 && b == suites->cipherSuite) {
  1760. match = 1;
  1761. break;
  1762. }
  1763. suites++;
  1764. suitesSz--;
  1765. }
  1766. if (!match)
  1767. INC_STAT(SnifferStats.sslCiphersUnsupported);
  1768. }
  1769. #endif /* WOLFSSL_SNIFFER_STATS */
  1770. /* compression */
  1771. b = *input++;
  1772. *sslBytes -= ENUM_LEN;
  1773. if (b) {
  1774. SetError(BAD_COMPRESSION_STR, error, session, FATAL_ERROR_STATE);
  1775. return -1;
  1776. }
  1777. #ifdef HAVE_EXTENDED_MASTER
  1778. /* extensions */
  1779. if ((initialBytes - *sslBytes) < msgSz) {
  1780. word16 len;
  1781. /* skip extensions until extended master secret */
  1782. /* make sure can read len */
  1783. if (SUITE_LEN > *sslBytes) {
  1784. SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  1785. return -1;
  1786. }
  1787. len = (word16)((input[0] << 8) | input[1]);
  1788. input += SUITE_LEN;
  1789. *sslBytes -= SUITE_LEN;
  1790. /* make sure can read through all extensions */
  1791. if (len > *sslBytes) {
  1792. SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  1793. return -1;
  1794. }
  1795. while (len >= EXT_TYPE_SZ + LENGTH_SZ) {
  1796. byte extType[EXT_TYPE_SZ];
  1797. word16 extLen;
  1798. extType[0] = input[0];
  1799. extType[1] = input[1];
  1800. input += EXT_TYPE_SZ;
  1801. *sslBytes -= EXT_TYPE_SZ;
  1802. extLen = (word16)((input[0] << 8) | input[1]);
  1803. input += LENGTH_SZ;
  1804. *sslBytes -= LENGTH_SZ;
  1805. /* make sure can read through individual extension */
  1806. if (extLen > *sslBytes) {
  1807. SetError(SERVER_HELLO_INPUT_STR, error, session,
  1808. FATAL_ERROR_STATE);
  1809. return -1;
  1810. }
  1811. if (extType[0] == 0x00 && extType[1] == EXT_MASTER_SECRET) {
  1812. session->flags.expectEms = 1;
  1813. }
  1814. input += extLen;
  1815. *sslBytes -= extLen;
  1816. len -= extLen + EXT_TYPE_SZ + LENGTH_SZ;
  1817. }
  1818. }
  1819. if (!session->flags.expectEms) {
  1820. XFREE(session->hash, NULL, DYNAMIC_TYPE_HASHES);
  1821. session->hash = NULL;
  1822. }
  1823. #endif
  1824. if (session->sslServer->options.haveSessionId) {
  1825. if (XMEMCMP(session->sslServer->arrays->sessionID,
  1826. session->sslClient->arrays->sessionID, ID_LEN) == 0)
  1827. doResume = 1;
  1828. }
  1829. else if (session->sslClient->options.haveSessionId == 0 &&
  1830. session->sslServer->options.haveSessionId == 0 &&
  1831. session->ticketID)
  1832. doResume = 1;
  1833. if (session->ticketID && doResume) {
  1834. /* use ticketID to retrieve from session, prefer over sessionID */
  1835. XMEMCPY(session->sslServer->arrays->sessionID,session->ticketID,ID_LEN);
  1836. session->sslServer->options.haveSessionId = 1; /* may not have
  1837. actual sessionID */
  1838. }
  1839. if (doResume ) {
  1840. int ret = 0;
  1841. SSL_SESSION* resume = GetSession(session->sslServer,
  1842. session->sslServer->arrays->masterSecret, 0);
  1843. if (resume == NULL) {
  1844. #ifdef WOLFSSL_SNIFFER_STATS
  1845. INC_STAT(SnifferStats.sslResumeMisses);
  1846. #endif
  1847. SetError(BAD_SESSION_RESUME_STR, error, session, FATAL_ERROR_STATE);
  1848. return -1;
  1849. }
  1850. /* make sure client has master secret too */
  1851. XMEMCPY(session->sslClient->arrays->masterSecret,
  1852. session->sslServer->arrays->masterSecret, SECRET_LEN);
  1853. session->flags.resuming = 1;
  1854. Trace(SERVER_DID_RESUMPTION_STR);
  1855. #ifdef WOLFSSL_SNIFFER_STATS
  1856. INC_STAT(SnifferStats.sslResumedConns);
  1857. INC_STAT(SnifferStats.sslResumptionValid);
  1858. #endif
  1859. if (SetCipherSpecs(session->sslServer) != 0) {
  1860. SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
  1861. return -1;
  1862. }
  1863. if (SetCipherSpecs(session->sslClient) != 0) {
  1864. SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
  1865. return -1;
  1866. }
  1867. if (session->sslServer->options.tls) {
  1868. ret = DeriveTlsKeys(session->sslServer);
  1869. ret += DeriveTlsKeys(session->sslClient);
  1870. }
  1871. else {
  1872. ret = DeriveKeys(session->sslServer);
  1873. ret += DeriveKeys(session->sslClient);
  1874. }
  1875. ret += SetKeysSide(session->sslServer, ENCRYPT_AND_DECRYPT_SIDE);
  1876. ret += SetKeysSide(session->sslClient, ENCRYPT_AND_DECRYPT_SIDE);
  1877. if (ret != 0) {
  1878. SetError(BAD_DERIVE_STR, error, session, FATAL_ERROR_STATE);
  1879. return -1;
  1880. }
  1881. }
  1882. else {
  1883. #ifdef WOLFSSL_SNIFFER_STATS
  1884. INC_STAT(SnifferStats.sslStandardConns);
  1885. #endif
  1886. }
  1887. #ifdef SHOW_SECRETS
  1888. {
  1889. int i;
  1890. printf("cipher suite = 0x%02x\n",
  1891. session->sslServer->options.cipherSuite);
  1892. printf("server random: ");
  1893. for (i = 0; i < RAN_LEN; i++)
  1894. printf("%02x", session->sslServer->arrays->serverRandom[i]);
  1895. printf("\n");
  1896. }
  1897. #endif
  1898. return 0;
  1899. }
  1900. /* Process normal Client Hello */
  1901. static int ProcessClientHello(const byte* input, int* sslBytes,
  1902. SnifferSession* session, char* error)
  1903. {
  1904. byte bLen;
  1905. word16 len;
  1906. int toRead = VERSION_SZ + RAN_LEN + ENUM_LEN;
  1907. #ifdef HAVE_SNI
  1908. {
  1909. byte name[MAX_SERVER_NAME];
  1910. word32 nameSz = sizeof(name);
  1911. int ret;
  1912. ret = wolfSSL_SNI_GetFromBuffer(
  1913. input - HANDSHAKE_HEADER_SZ - RECORD_HEADER_SZ,
  1914. *sslBytes + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ,
  1915. WOLFSSL_SNI_HOST_NAME, name, &nameSz);
  1916. if (ret == WOLFSSL_SUCCESS) {
  1917. NamedKey* namedKey;
  1918. if (nameSz > sizeof(name) - 1)
  1919. nameSz = sizeof(name) - 1;
  1920. name[nameSz] = 0;
  1921. wc_LockMutex(&session->context->namedKeysMutex);
  1922. namedKey = session->context->namedKeys;
  1923. while (namedKey != NULL) {
  1924. if (nameSz == namedKey->nameSz &&
  1925. XSTRNCMP((char*)name, namedKey->name, nameSz) == 0) {
  1926. if (wolfSSL_use_PrivateKey_buffer(session->sslServer,
  1927. namedKey->key, namedKey->keySz,
  1928. WOLFSSL_FILETYPE_ASN1) != WOLFSSL_SUCCESS) {
  1929. wc_UnLockMutex(&session->context->namedKeysMutex);
  1930. SetError(CLIENT_HELLO_LATE_KEY_STR, error, session,
  1931. FATAL_ERROR_STATE);
  1932. return -1;
  1933. }
  1934. session->sni = namedKey->name;
  1935. break;
  1936. }
  1937. else
  1938. namedKey = namedKey->next;
  1939. }
  1940. wc_UnLockMutex(&session->context->namedKeysMutex);
  1941. }
  1942. }
  1943. #endif
  1944. session->flags.clientHello = 1; /* don't process again */
  1945. /* make sure can read up to session len */
  1946. if (toRead > *sslBytes) {
  1947. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  1948. return -1;
  1949. }
  1950. /* skip, get negotiated one from server hello */
  1951. input += VERSION_SZ;
  1952. *sslBytes -= VERSION_SZ;
  1953. XMEMCPY(session->sslServer->arrays->clientRandom, input, RAN_LEN);
  1954. XMEMCPY(session->sslClient->arrays->clientRandom, input, RAN_LEN);
  1955. input += RAN_LEN;
  1956. *sslBytes -= RAN_LEN;
  1957. /* store session in case trying to resume */
  1958. bLen = *input++;
  1959. *sslBytes -= ENUM_LEN;
  1960. if (bLen) {
  1961. if (ID_LEN > *sslBytes) {
  1962. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  1963. return -1;
  1964. }
  1965. Trace(CLIENT_RESUME_TRY_STR);
  1966. XMEMCPY(session->sslClient->arrays->sessionID, input, ID_LEN);
  1967. session->sslClient->options.haveSessionId = 1;
  1968. }
  1969. #ifdef SHOW_SECRETS
  1970. {
  1971. int i;
  1972. printf("client random: ");
  1973. for (i = 0; i < RAN_LEN; i++)
  1974. printf("%02x", session->sslServer->arrays->clientRandom[i]);
  1975. printf("\n");
  1976. }
  1977. #endif
  1978. input += bLen;
  1979. *sslBytes -= bLen;
  1980. /* skip cipher suites */
  1981. /* make sure can read len */
  1982. if (SUITE_LEN > *sslBytes) {
  1983. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  1984. return -1;
  1985. }
  1986. len = (word16)((input[0] << 8) | input[1]);
  1987. input += SUITE_LEN;
  1988. *sslBytes -= SUITE_LEN;
  1989. /* make sure can read suites + comp len */
  1990. if (len + ENUM_LEN > *sslBytes) {
  1991. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  1992. return -1;
  1993. }
  1994. input += len;
  1995. *sslBytes -= len;
  1996. /* skip compression */
  1997. bLen = *input++;
  1998. *sslBytes -= ENUM_LEN;
  1999. /* make sure can read len */
  2000. if (bLen > *sslBytes) {
  2001. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2002. return -1;
  2003. }
  2004. input += bLen;
  2005. *sslBytes -= bLen;
  2006. if (*sslBytes == 0) {
  2007. /* no extensions */
  2008. return 0;
  2009. }
  2010. /* skip extensions until session ticket */
  2011. /* make sure can read len */
  2012. if (SUITE_LEN > *sslBytes) {
  2013. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2014. return -1;
  2015. }
  2016. len = (word16)((input[0] << 8) | input[1]);
  2017. input += SUITE_LEN;
  2018. *sslBytes -= SUITE_LEN;
  2019. /* make sure can read through all extensions */
  2020. if (len > *sslBytes) {
  2021. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2022. return -1;
  2023. }
  2024. while (len >= EXT_TYPE_SZ + LENGTH_SZ) {
  2025. byte extType[EXT_TYPE_SZ];
  2026. word16 extLen;
  2027. extType[0] = input[0];
  2028. extType[1] = input[1];
  2029. input += EXT_TYPE_SZ;
  2030. *sslBytes -= EXT_TYPE_SZ;
  2031. extLen = (word16)((input[0] << 8) | input[1]);
  2032. input += LENGTH_SZ;
  2033. *sslBytes -= LENGTH_SZ;
  2034. /* make sure can read through individual extension */
  2035. if (extLen > *sslBytes) {
  2036. SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2037. return -1;
  2038. }
  2039. if (extType[0] == 0x00 && extType[1] == TICKET_EXT_ID) {
  2040. /* make sure can read through ticket if there is a non blank one */
  2041. if (extLen && extLen < ID_LEN) {
  2042. SetError(CLIENT_HELLO_INPUT_STR, error, session,
  2043. FATAL_ERROR_STATE);
  2044. return -1;
  2045. }
  2046. if (extLen) {
  2047. if (session->ticketID == 0) {
  2048. session->ticketID = (byte*)XMALLOC(ID_LEN,
  2049. NULL, DYNAMIC_TYPE_SNIFFER_TICKET_ID);
  2050. if (session->ticketID == 0) {
  2051. SetError(MEMORY_STR, error, session,
  2052. FATAL_ERROR_STATE);
  2053. return -1;
  2054. }
  2055. }
  2056. XMEMCPY(session->ticketID, input + extLen - ID_LEN, ID_LEN);
  2057. }
  2058. }
  2059. input += extLen;
  2060. *sslBytes -= extLen;
  2061. len -= extLen + EXT_TYPE_SZ + LENGTH_SZ;
  2062. }
  2063. return 0;
  2064. }
  2065. #ifdef WOLFSSL_SNIFFER_WATCH
  2066. /* Process Certificate */
  2067. static int ProcessCertificate(const byte* input, int* sslBytes,
  2068. SnifferSession* session, char* error)
  2069. {
  2070. Sha256 sha;
  2071. const byte* certChain;
  2072. word32 certChainSz;
  2073. word32 certSz;
  2074. int ret;
  2075. byte digest[SHA256_DIGEST_SIZE];
  2076. /* If the receiver is the server, this is the client certificate message,
  2077. * and it should be ignored at this point. */
  2078. if (session->flags.side == WOLFSSL_SERVER_END)
  2079. return 0;
  2080. if (WatchCb == NULL) {
  2081. SetError(WATCH_CB_MISSING_STR, error, session, FATAL_ERROR_STATE);
  2082. return -1;
  2083. }
  2084. if (*sslBytes < CERT_HEADER_SZ) {
  2085. SetError(BAD_CERT_MSG_STR, error, session, FATAL_ERROR_STATE);
  2086. return -1;
  2087. }
  2088. ato24(input, &certChainSz);
  2089. *sslBytes -= CERT_HEADER_SZ;
  2090. input += CERT_HEADER_SZ;
  2091. if (*sslBytes < (int)certChainSz) {
  2092. SetError(BAD_CERT_MSG_STR, error, session, FATAL_ERROR_STATE);
  2093. return -1;
  2094. }
  2095. certChain = input;
  2096. ato24(input, &certSz);
  2097. input += OPAQUE24_LEN;
  2098. if (*sslBytes < (int)certSz) {
  2099. SetError(BAD_CERT_MSG_STR, error, session, FATAL_ERROR_STATE);
  2100. return -1;
  2101. }
  2102. *sslBytes -= certChainSz;
  2103. ret = wc_InitSha256(&sha);
  2104. if (ret == 0)
  2105. ret = wc_Sha256Update(&sha, input, certSz);
  2106. if (ret == 0)
  2107. ret = wc_Sha256Final(&sha, digest);
  2108. if (ret != 0) {
  2109. SetError(WATCH_HASH_STR, error, session, FATAL_ERROR_STATE);
  2110. return -1;
  2111. }
  2112. ret = WatchCb((void*)session, digest, sizeof(digest),
  2113. certChain, certChainSz, WatchCbCtx, error);
  2114. if (ret != 0) {
  2115. #ifdef WOLFSSL_SNIFFER_STATS
  2116. INC_STAT(SnifferStats.sslKeysUnmatched);
  2117. #endif
  2118. SetError(WATCH_FAIL_STR, error, session, FATAL_ERROR_STATE);
  2119. return -1;
  2120. }
  2121. else {
  2122. #ifdef WOLFSSL_SNIFFER_STATS
  2123. INC_STAT(SnifferStats.sslKeyMatches);
  2124. #endif
  2125. }
  2126. return 0;
  2127. }
  2128. #endif
  2129. /* Process Finished */
  2130. static int ProcessFinished(const byte* input, int size, int* sslBytes,
  2131. SnifferSession* session, char* error)
  2132. {
  2133. SSL* ssl;
  2134. word32 inOutIdx = 0;
  2135. int ret;
  2136. if (session->flags.side == WOLFSSL_SERVER_END)
  2137. ssl = session->sslServer;
  2138. else
  2139. ssl = session->sslClient;
  2140. ret = DoFinished(ssl, input, &inOutIdx, (word32) size, (word32) *sslBytes,
  2141. SNIFF);
  2142. *sslBytes -= (int)inOutIdx;
  2143. if (ret < 0) {
  2144. SetError(BAD_FINISHED_MSG, error, session, FATAL_ERROR_STATE);
  2145. return ret;
  2146. }
  2147. if (ret == 0 && session->flags.cached == 0) {
  2148. if (session->sslServer->options.haveSessionId) {
  2149. WOLFSSL_SESSION* sess = GetSession(session->sslServer, NULL, 0);
  2150. if (sess == NULL) {
  2151. AddSession(session->sslServer); /* don't re add */
  2152. #ifdef WOLFSSL_SNIFFER_STATS
  2153. INC_STAT(SnifferStats.sslResumptionInserts);
  2154. #endif
  2155. }
  2156. session->flags.cached = 1;
  2157. }
  2158. }
  2159. /* If receiving a finished message from one side, free the resources
  2160. * from the other side's tracker. */
  2161. if (session->flags.side == WOLFSSL_SERVER_END)
  2162. FreeHandshakeResources(session->sslClient);
  2163. else
  2164. FreeHandshakeResources(session->sslServer);
  2165. return ret;
  2166. }
  2167. /* Process HandShake input */
  2168. static int DoHandShake(const byte* input, int* sslBytes,
  2169. SnifferSession* session, char* error)
  2170. {
  2171. byte type;
  2172. int size;
  2173. int ret = 0;
  2174. int startBytes;
  2175. if (*sslBytes < HANDSHAKE_HEADER_SZ) {
  2176. SetError(HANDSHAKE_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2177. return -1;
  2178. }
  2179. type = input[0];
  2180. size = (input[1] << 16) | (input[2] << 8) | input[3];
  2181. input += HANDSHAKE_HEADER_SZ;
  2182. *sslBytes -= HANDSHAKE_HEADER_SZ;
  2183. startBytes = *sslBytes;
  2184. if (*sslBytes < size) {
  2185. Trace(SPLIT_HANDSHAKE_MSG_STR);
  2186. *sslBytes = 0;
  2187. return ret;
  2188. }
  2189. /* A session's arrays are released when the handshake is completed. */
  2190. if (session->sslServer->arrays == NULL &&
  2191. session->sslClient->arrays == NULL) {
  2192. SetError(NO_SECURE_RENEGOTIATION, error, session, FATAL_ERROR_STATE);
  2193. return -1;
  2194. }
  2195. #ifdef HAVE_EXTENDED_MASTER
  2196. if (session->hash) {
  2197. if (HashUpdate(session->hash, input, size) != 0) {
  2198. SetError(EXTENDED_MASTER_HASH_STR, error,
  2199. session, FATAL_ERROR_STATE);
  2200. return -1;
  2201. }
  2202. }
  2203. #endif
  2204. switch (type) {
  2205. case hello_verify_request:
  2206. Trace(GOT_HELLO_VERIFY_STR);
  2207. break;
  2208. case hello_request:
  2209. Trace(GOT_HELLO_REQUEST_STR);
  2210. break;
  2211. case session_ticket:
  2212. Trace(GOT_SESSION_TICKET_STR);
  2213. ret = ProcessSessionTicket(input, sslBytes, session, error);
  2214. break;
  2215. case server_hello:
  2216. Trace(GOT_SERVER_HELLO_STR);
  2217. ret = ProcessServerHello(size, input, sslBytes, session, error);
  2218. break;
  2219. case certificate_request:
  2220. Trace(GOT_CERT_REQ_STR);
  2221. break;
  2222. case server_key_exchange:
  2223. #ifdef WOLFSSL_SNIFFER_STATS
  2224. INC_STAT(SnifferStats.sslEphemeralMisses);
  2225. #endif
  2226. Trace(GOT_SERVER_KEY_EX_STR);
  2227. /* can't know temp key passively */
  2228. SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
  2229. ret = -1;
  2230. break;
  2231. case certificate:
  2232. Trace(GOT_CERT_STR);
  2233. if (session->flags.side == WOLFSSL_SERVER_END) {
  2234. #ifdef WOLFSSL_SNIFFER_STATS
  2235. INC_STAT(SnifferStats.sslClientAuthConns);
  2236. #endif
  2237. }
  2238. #ifdef WOLFSSL_SNIFFER_WATCH
  2239. ret = ProcessCertificate(input, sslBytes, session, error);
  2240. #endif
  2241. break;
  2242. case server_hello_done:
  2243. Trace(GOT_SERVER_HELLO_DONE_STR);
  2244. break;
  2245. case finished:
  2246. Trace(GOT_FINISHED_STR);
  2247. ret = ProcessFinished(input, size, sslBytes, session, error);
  2248. break;
  2249. case client_hello:
  2250. Trace(GOT_CLIENT_HELLO_STR);
  2251. ret = ProcessClientHello(input, sslBytes, session, error);
  2252. break;
  2253. case client_key_exchange:
  2254. Trace(GOT_CLIENT_KEY_EX_STR);
  2255. #ifdef HAVE_EXTENDED_MASTER
  2256. if (session->flags.expectEms && session->hash != NULL) {
  2257. if (HashCopy(session->sslServer->hsHashes,
  2258. session->hash) == 0 &&
  2259. HashCopy(session->sslClient->hsHashes,
  2260. session->hash) == 0) {
  2261. session->sslServer->options.haveEMS = 1;
  2262. session->sslClient->options.haveEMS = 1;
  2263. }
  2264. else {
  2265. SetError(EXTENDED_MASTER_HASH_STR, error,
  2266. session, FATAL_ERROR_STATE);
  2267. ret = -1;
  2268. }
  2269. XMEMSET(session->hash, 0, sizeof(HsHashes));
  2270. XFREE(session->hash, NULL, DYNAMIC_TYPE_HASHES);
  2271. session->hash = NULL;
  2272. }
  2273. else {
  2274. session->sslServer->options.haveEMS = 0;
  2275. session->sslClient->options.haveEMS = 0;
  2276. }
  2277. #endif
  2278. if (ret == 0)
  2279. ret = ProcessClientKeyExchange(input, sslBytes, session, error);
  2280. break;
  2281. case certificate_verify:
  2282. Trace(GOT_CERT_VER_STR);
  2283. break;
  2284. case certificate_status:
  2285. Trace(GOT_CERT_STATUS_STR);
  2286. break;
  2287. default:
  2288. SetError(GOT_UNKNOWN_HANDSHAKE_STR, error, session, 0);
  2289. return -1;
  2290. }
  2291. *sslBytes = startBytes - size; /* actual bytes of full process */
  2292. return ret;
  2293. }
  2294. /* Decrypt input into plain output, 0 on success */
  2295. static int Decrypt(SSL* ssl, byte* output, const byte* input, word32 sz)
  2296. {
  2297. int ret = 0;
  2298. (void)output;
  2299. (void)input;
  2300. (void)sz;
  2301. switch (ssl->specs.bulk_cipher_algorithm) {
  2302. #ifdef BUILD_ARC4
  2303. case wolfssl_rc4:
  2304. wc_Arc4Process(ssl->decrypt.arc4, output, input, sz);
  2305. break;
  2306. #endif
  2307. #ifdef BUILD_DES3
  2308. case wolfssl_triple_des:
  2309. ret = wc_Des3_CbcDecrypt(ssl->decrypt.des3, output, input, sz);
  2310. break;
  2311. #endif
  2312. #ifdef BUILD_AES
  2313. case wolfssl_aes:
  2314. ret = wc_AesCbcDecrypt(ssl->decrypt.aes, output, input, sz);
  2315. break;
  2316. #endif
  2317. #ifdef HAVE_HC128
  2318. case wolfssl_hc128:
  2319. wc_Hc128_Process(ssl->decrypt.hc128, output, input, sz);
  2320. break;
  2321. #endif
  2322. #ifdef BUILD_RABBIT
  2323. case wolfssl_rabbit:
  2324. wc_RabbitProcess(ssl->decrypt.rabbit, output, input, sz);
  2325. break;
  2326. #endif
  2327. #ifdef HAVE_CAMELLIA
  2328. case wolfssl_camellia:
  2329. wc_CamelliaCbcDecrypt(ssl->decrypt.cam, output, input, sz);
  2330. break;
  2331. #endif
  2332. #ifdef HAVE_IDEA
  2333. case wolfssl_idea:
  2334. wc_IdeaCbcDecrypt(ssl->decrypt.idea, output, input, sz);
  2335. break;
  2336. #endif
  2337. #ifdef HAVE_AESGCM
  2338. case wolfssl_aes_gcm:
  2339. if (sz >= (word32)(AESGCM_EXP_IV_SZ + ssl->specs.aead_mac_size))
  2340. {
  2341. /* scratch buffer, sniffer ignores auth tag*/
  2342. byte authTag[WOLFSSL_MIN_AUTH_TAG_SZ];
  2343. byte nonce[AESGCM_NONCE_SZ];
  2344. XMEMCPY(nonce, ssl->keys.aead_dec_imp_IV, AESGCM_IMP_IV_SZ);
  2345. XMEMCPY(nonce + AESGCM_IMP_IV_SZ, input, AESGCM_EXP_IV_SZ);
  2346. if (wc_AesGcmEncrypt(ssl->decrypt.aes,
  2347. output,
  2348. input + AESGCM_EXP_IV_SZ,
  2349. sz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
  2350. nonce, AESGCM_NONCE_SZ,
  2351. authTag, sizeof(authTag),
  2352. NULL, 0) < 0) {
  2353. Trace(BAD_DECRYPT);
  2354. ret = -1;
  2355. }
  2356. ForceZero(nonce, AESGCM_NONCE_SZ);
  2357. }
  2358. else {
  2359. Trace(BAD_DECRYPT_SIZE);
  2360. ret = -1;
  2361. }
  2362. break;
  2363. #endif
  2364. #ifdef HAVE_NULL_CIPHER
  2365. case wolfssl_cipher_null:
  2366. XMEMCPY(output, input, sz);
  2367. break;
  2368. #endif
  2369. default:
  2370. Trace(BAD_DECRYPT_TYPE);
  2371. ret = -1;
  2372. break;
  2373. }
  2374. return ret;
  2375. }
  2376. /* Decrypt input message into output, adjust output steam if needed */
  2377. static const byte* DecryptMessage(SSL* ssl, const byte* input, word32 sz,
  2378. byte* output, int* error, int* advance)
  2379. {
  2380. int ivExtra = 0;
  2381. int ret = Decrypt(ssl, output, input, sz);
  2382. if (ret != 0) {
  2383. *error = ret;
  2384. return NULL;
  2385. }
  2386. ssl->keys.encryptSz = sz;
  2387. if (ssl->options.tls1_1 && ssl->specs.cipher_type == block) {
  2388. output += ssl->specs.block_size; /* go past TLSv1.1 IV */
  2389. ivExtra = ssl->specs.block_size;
  2390. *advance = ssl->specs.block_size;
  2391. }
  2392. if (ssl->specs.cipher_type == aead) {
  2393. *advance = ssl->specs.aead_mac_size;
  2394. ssl->keys.padSz = ssl->specs.aead_mac_size;
  2395. }
  2396. else
  2397. ssl->keys.padSz = ssl->specs.hash_size;
  2398. if (ssl->specs.cipher_type == block)
  2399. ssl->keys.padSz += *(output + sz - ivExtra - 1) + 1;
  2400. return output;
  2401. }
  2402. /* remove session from table, use rowHint if no info (means we have a lock) */
  2403. static void RemoveSession(SnifferSession* session, IpInfo* ipInfo,
  2404. TcpInfo* tcpInfo, word32 rowHint)
  2405. {
  2406. SnifferSession* previous = 0;
  2407. SnifferSession* current;
  2408. word32 row = rowHint;
  2409. int haveLock = 0;
  2410. if (ipInfo && tcpInfo)
  2411. row = SessionHash(ipInfo, tcpInfo);
  2412. else
  2413. haveLock = 1;
  2414. assert(row <= HASH_SIZE);
  2415. Trace(REMOVE_SESSION_STR);
  2416. if (!haveLock)
  2417. wc_LockMutex(&SessionMutex);
  2418. current = SessionTable[row];
  2419. while (current) {
  2420. if (current == session) {
  2421. if (previous)
  2422. previous->next = current->next;
  2423. else
  2424. SessionTable[row] = current->next;
  2425. FreeSnifferSession(session);
  2426. TraceRemovedSession();
  2427. break;
  2428. }
  2429. previous = current;
  2430. current = current->next;
  2431. }
  2432. if (!haveLock)
  2433. wc_UnLockMutex(&SessionMutex);
  2434. }
  2435. /* Remove stale sessions from the Session Table, have a lock */
  2436. static void RemoveStaleSessions(void)
  2437. {
  2438. word32 i;
  2439. SnifferSession* session;
  2440. for (i = 0; i < HASH_SIZE; i++) {
  2441. session = SessionTable[i];
  2442. while (session) {
  2443. SnifferSession* next = session->next;
  2444. if (time(NULL) >= session->lastUsed + WOLFSSL_SNIFFER_TIMEOUT) {
  2445. TraceStaleSession();
  2446. RemoveSession(session, NULL, NULL, i);
  2447. }
  2448. session = next;
  2449. }
  2450. }
  2451. }
  2452. /* Create a new Sniffer Session */
  2453. static SnifferSession* CreateSession(IpInfo* ipInfo, TcpInfo* tcpInfo,
  2454. char* error)
  2455. {
  2456. SnifferSession* session = 0;
  2457. int row;
  2458. Trace(NEW_SESSION_STR);
  2459. /* create a new one */
  2460. session = (SnifferSession*)XMALLOC(sizeof(SnifferSession),
  2461. NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  2462. if (session == NULL) {
  2463. SetError(MEMORY_STR, error, NULL, 0);
  2464. return 0;
  2465. }
  2466. InitSession(session);
  2467. #ifdef HAVE_EXTENDED_MASTER
  2468. {
  2469. HsHashes* newHash = (HsHashes*)XMALLOC(sizeof(HsHashes),
  2470. NULL, DYNAMIC_TYPE_HASHES);
  2471. if (newHash == NULL) {
  2472. SetError(MEMORY_STR, error, NULL, 0);
  2473. XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  2474. return 0;
  2475. }
  2476. if (HashInit(newHash) != 0) {
  2477. SetError(EXTENDED_MASTER_HASH_STR, error, NULL, 0);
  2478. XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  2479. return 0;
  2480. }
  2481. session->hash = newHash;
  2482. }
  2483. #endif
  2484. session->server = ipInfo->dst;
  2485. session->client = ipInfo->src;
  2486. session->srvPort = (word16)tcpInfo->dstPort;
  2487. session->cliPort = (word16)tcpInfo->srcPort;
  2488. session->cliSeqStart = tcpInfo->sequence;
  2489. session->cliExpected = 1; /* relative */
  2490. session->lastUsed= time(NULL);
  2491. session->keySz = 0;
  2492. #ifdef HAVE_SNI
  2493. session->sni = NULL;
  2494. #endif
  2495. session->context = GetSnifferServer(ipInfo, tcpInfo);
  2496. if (session->context == NULL) {
  2497. SetError(SERVER_NOT_REG_STR, error, NULL, 0);
  2498. XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  2499. return 0;
  2500. }
  2501. session->sslServer = SSL_new(session->context->ctx);
  2502. if (session->sslServer == NULL) {
  2503. SetError(BAD_NEW_SSL_STR, error, session, FATAL_ERROR_STATE);
  2504. XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  2505. return 0;
  2506. }
  2507. session->sslClient = SSL_new(session->context->ctx);
  2508. if (session->sslClient == NULL) {
  2509. SSL_free(session->sslServer);
  2510. session->sslServer = 0;
  2511. SetError(BAD_NEW_SSL_STR, error, session, FATAL_ERROR_STATE);
  2512. XFREE(session, NULL, DYNAMIC_TYPE_SNIFFER_SESSION);
  2513. return 0;
  2514. }
  2515. /* put server back into server mode */
  2516. session->sslServer->options.side = WOLFSSL_SERVER_END;
  2517. row = SessionHash(ipInfo, tcpInfo);
  2518. /* add it to the session table */
  2519. wc_LockMutex(&SessionMutex);
  2520. session->next = SessionTable[row];
  2521. SessionTable[row] = session;
  2522. SessionCount++;
  2523. if ( (SessionCount % HASH_SIZE) == 0) {
  2524. TraceFindingStale();
  2525. RemoveStaleSessions();
  2526. }
  2527. wc_UnLockMutex(&SessionMutex);
  2528. /* CreateSession is called in response to a SYN packet, we know this
  2529. * is headed to the server. Also we know the server is one we care
  2530. * about as we've passed the GetSnifferServer() successfully. */
  2531. session->flags.side = WOLFSSL_SERVER_END;
  2532. return session;
  2533. }
  2534. #ifdef OLD_HELLO_ALLOWED
  2535. /* Process Old Client Hello Input */
  2536. static int DoOldHello(SnifferSession* session, const byte* sslFrame,
  2537. int* rhSize, int* sslBytes, char* error)
  2538. {
  2539. const byte* input = sslFrame;
  2540. byte b0, b1;
  2541. word32 idx = 0;
  2542. int ret;
  2543. Trace(GOT_OLD_CLIENT_HELLO_STR);
  2544. session->flags.clientHello = 1; /* don't process again */
  2545. b0 = *input++;
  2546. b1 = *input++;
  2547. *sslBytes -= 2;
  2548. *rhSize = ((b0 & 0x7f) << 8) | b1;
  2549. if (*rhSize > *sslBytes) {
  2550. SetError(OLD_CLIENT_INPUT_STR, error, session, FATAL_ERROR_STATE);
  2551. return -1;
  2552. }
  2553. ret = ProcessOldClientHello(session->sslServer, input, &idx, *sslBytes,
  2554. (word16)*rhSize);
  2555. if (ret < 0 && ret != MATCH_SUITE_ERROR) {
  2556. SetError(BAD_OLD_CLIENT_STR, error, session, FATAL_ERROR_STATE);
  2557. return -1;
  2558. }
  2559. Trace(OLD_CLIENT_OK_STR);
  2560. XMEMCPY(session->sslClient->arrays->clientRandom,
  2561. session->sslServer->arrays->clientRandom, RAN_LEN);
  2562. *sslBytes -= *rhSize;
  2563. return 0;
  2564. }
  2565. #endif /* OLD_HELLO_ALLOWED */
  2566. #if 0
  2567. /* Calculate the TCP checksum, see RFC 1071 */
  2568. /* return 0 for success, -1 on error */
  2569. /* can be called from decode() with
  2570. TcpChecksum(&ipInfo, &tcpInfo, sslBytes, packet + ipInfo.length);
  2571. could also add a 64bit version if type available and using this
  2572. */
  2573. int TcpChecksum(IpInfo* ipInfo, TcpInfo* tcpInfo, int dataLen,
  2574. const byte* packet)
  2575. {
  2576. TcpPseudoHdr pseudo;
  2577. int count = PSEUDO_HDR_SZ;
  2578. const word16* data = (word16*)&pseudo;
  2579. word32 sum = 0;
  2580. word16 checksum;
  2581. pseudo.src = ipInfo->src;
  2582. pseudo.dst = ipInfo->dst;
  2583. pseudo.rsv = 0;
  2584. pseudo.protocol = TCP_PROTO;
  2585. pseudo.length = htons(tcpInfo->length + dataLen);
  2586. /* pseudo header sum */
  2587. while (count >= 2) {
  2588. sum += *data++;
  2589. count -= 2;
  2590. }
  2591. count = tcpInfo->length + dataLen;
  2592. data = (word16*)packet;
  2593. /* main sum */
  2594. while (count > 1) {
  2595. sum += *data++;
  2596. count -=2;
  2597. }
  2598. /* get left-over, if any */
  2599. packet = (byte*)data;
  2600. if (count > 0) {
  2601. sum += *packet;
  2602. }
  2603. /* fold 32bit sum into 16 bits */
  2604. while (sum >> 16)
  2605. sum = (sum & 0xffff) + (sum >> 16);
  2606. checksum = (word16)~sum;
  2607. /* checksum should now equal 0, since included already calcd checksum */
  2608. /* field, but tcp checksum offloading could negate calculation */
  2609. if (checksum == 0)
  2610. return 0;
  2611. return -1;
  2612. }
  2613. #endif
  2614. /* Check IP and TCP headers, set payload */
  2615. /* returns 0 on success, -1 on error */
  2616. static int CheckHeaders(IpInfo* ipInfo, TcpInfo* tcpInfo, const byte* packet,
  2617. int length, const byte** sslFrame, int* sslBytes, char* error)
  2618. {
  2619. TraceHeader();
  2620. TracePacket();
  2621. /* ip header */
  2622. if (length < IP_HDR_SZ) {
  2623. SetError(PACKET_HDR_SHORT_STR, error, NULL, 0);
  2624. return -1;
  2625. }
  2626. if (CheckIpHdr((IpHdr*)packet, ipInfo, length, error) != 0)
  2627. return -1;
  2628. /* tcp header */
  2629. if (length < (ipInfo->length + TCP_HDR_SZ)) {
  2630. SetError(PACKET_HDR_SHORT_STR, error, NULL, 0);
  2631. return -1;
  2632. }
  2633. if (CheckTcpHdr((TcpHdr*)(packet + ipInfo->length), tcpInfo, error) != 0)
  2634. return -1;
  2635. /* setup */
  2636. *sslFrame = packet + ipInfo->length + tcpInfo->length;
  2637. if (*sslFrame > packet + length) {
  2638. SetError(PACKET_HDR_SHORT_STR, error, NULL, 0);
  2639. return -1;
  2640. }
  2641. /* We only care about the data in the TCP/IP record. There may be extra
  2642. * data after the IP record for the FCS for Ethernet. */
  2643. *sslBytes = (int)(packet + ipInfo->total - *sslFrame);
  2644. return 0;
  2645. }
  2646. /* Create or Find existing session */
  2647. /* returns 0 on success (continue), -1 on error, 1 on success (end) */
  2648. static int CheckSession(IpInfo* ipInfo, TcpInfo* tcpInfo, int sslBytes,
  2649. SnifferSession** session, char* error)
  2650. {
  2651. /* create a new SnifferSession on client SYN */
  2652. if (tcpInfo->syn && !tcpInfo->ack) {
  2653. TraceClientSyn(tcpInfo->sequence);
  2654. #ifdef WOLFSSL_SNIFFER_STATS
  2655. INC_STAT(SnifferStats.sslEncryptedConns);
  2656. #endif
  2657. *session = CreateSession(ipInfo, tcpInfo, error);
  2658. if (*session == NULL) {
  2659. *session = GetSnifferSession(ipInfo, tcpInfo);
  2660. /* already had existing, so OK */
  2661. if (*session)
  2662. return 1;
  2663. SetError(MEMORY_STR, error, NULL, 0);
  2664. return -1;
  2665. }
  2666. return 1;
  2667. }
  2668. /* get existing sniffer session */
  2669. else {
  2670. *session = GetSnifferSession(ipInfo, tcpInfo);
  2671. if (*session == NULL) {
  2672. /* don't worry about extraneous RST or duplicate FINs */
  2673. if (tcpInfo->fin || tcpInfo->rst)
  2674. return 1;
  2675. /* don't worry about duplicate ACKs either */
  2676. if (sslBytes == 0 && tcpInfo->ack)
  2677. return 1;
  2678. #ifdef WOLFSSL_SNIFFER_STATS
  2679. LOCK_STAT();
  2680. NOLOCK_INC_STAT(SnifferStats.sslDecryptedPackets);
  2681. NOLOCK_ADD_TO_STAT(SnifferStats.sslDecryptedBytes, sslBytes);
  2682. UNLOCK_STAT();
  2683. #endif
  2684. SetError(BAD_SESSION_STR, error, NULL, 0);
  2685. return -1;
  2686. }
  2687. }
  2688. return 0;
  2689. }
  2690. /* Create a Packet Buffer from *begin - end, adjust new *begin and bytesLeft */
  2691. static PacketBuffer* CreateBuffer(word32* begin, word32 end, const byte* data,
  2692. int* bytesLeft)
  2693. {
  2694. PacketBuffer* pb;
  2695. int added = end - *begin + 1;
  2696. assert(*begin <= end);
  2697. pb = (PacketBuffer*)XMALLOC(sizeof(PacketBuffer),
  2698. NULL, DYNAMIC_TYPE_SNIFFER_PB);
  2699. if (pb == NULL) return NULL;
  2700. pb->next = 0;
  2701. pb->begin = *begin;
  2702. pb->end = end;
  2703. pb->data = (byte*)XMALLOC(added, NULL, DYNAMIC_TYPE_SNIFFER_PB_BUFFER);
  2704. if (pb->data == NULL) {
  2705. XFREE(pb, NULL, DYNAMIC_TYPE_SNIFFER_PB);
  2706. return NULL;
  2707. }
  2708. XMEMCPY(pb->data, data, added);
  2709. *bytesLeft -= added;
  2710. *begin = pb->end + 1;
  2711. return pb;
  2712. }
  2713. /* Add sslFrame to Reassembly List */
  2714. /* returns 1 (end) on success, -1, on error */
  2715. static int AddToReassembly(byte from, word32 seq, const byte* sslFrame,
  2716. int sslBytes, SnifferSession* session, char* error)
  2717. {
  2718. PacketBuffer* add;
  2719. PacketBuffer** front = (from == WOLFSSL_SERVER_END) ?
  2720. &session->cliReassemblyList: &session->srvReassemblyList;
  2721. PacketBuffer* curr = *front;
  2722. PacketBuffer* prev = curr;
  2723. word32* reassemblyMemory = (from == WOLFSSL_SERVER_END) ?
  2724. &session->cliReassemblyMemory : &session->srvReassemblyMemory;
  2725. word32 startSeq = seq;
  2726. word32 added;
  2727. int bytesLeft = sslBytes; /* could be overlapping fragment */
  2728. /* if list is empty add full frame to front */
  2729. if (!curr) {
  2730. if (MaxRecoveryMemory != -1 &&
  2731. (int)(*reassemblyMemory + sslBytes) > MaxRecoveryMemory) {
  2732. SetError(REASSEMBLY_MAX_STR, error, session, FATAL_ERROR_STATE);
  2733. return -1;
  2734. }
  2735. add = CreateBuffer(&seq, seq + sslBytes - 1, sslFrame, &bytesLeft);
  2736. if (add == NULL) {
  2737. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  2738. return -1;
  2739. }
  2740. *front = add;
  2741. *reassemblyMemory += sslBytes;
  2742. return 1;
  2743. }
  2744. /* add to front if before current front, up to next->begin */
  2745. if (seq < curr->begin) {
  2746. word32 end = seq + sslBytes - 1;
  2747. if (end >= curr->begin)
  2748. end = curr->begin - 1;
  2749. if (MaxRecoveryMemory -1 &&
  2750. (int)(*reassemblyMemory + sslBytes) > MaxRecoveryMemory) {
  2751. SetError(REASSEMBLY_MAX_STR, error, session, FATAL_ERROR_STATE);
  2752. return -1;
  2753. }
  2754. add = CreateBuffer(&seq, end, sslFrame, &bytesLeft);
  2755. if (add == NULL) {
  2756. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  2757. return -1;
  2758. }
  2759. add->next = curr;
  2760. *front = add;
  2761. *reassemblyMemory += sslBytes;
  2762. }
  2763. /* while we have bytes left, try to find a gap to fill */
  2764. while (bytesLeft > 0) {
  2765. /* get previous packet in list */
  2766. while (curr && (seq >= curr->begin)) {
  2767. prev = curr;
  2768. curr = curr->next;
  2769. }
  2770. /* don't add duplicate data */
  2771. if (prev->end >= seq) {
  2772. if ( (seq + bytesLeft - 1) <= prev->end)
  2773. return 1;
  2774. seq = prev->end + 1;
  2775. bytesLeft = startSeq + sslBytes - seq;
  2776. }
  2777. if (!curr)
  2778. /* we're at the end */
  2779. added = bytesLeft;
  2780. else
  2781. /* we're in between two frames */
  2782. added = min((word32)bytesLeft, curr->begin - seq);
  2783. /* data already there */
  2784. if (added == 0)
  2785. continue;
  2786. if (MaxRecoveryMemory != -1 &&
  2787. (int)(*reassemblyMemory + added) > MaxRecoveryMemory) {
  2788. SetError(REASSEMBLY_MAX_STR, error, session, FATAL_ERROR_STATE);
  2789. return -1;
  2790. }
  2791. add = CreateBuffer(&seq, seq + added - 1, &sslFrame[seq - startSeq],
  2792. &bytesLeft);
  2793. if (add == NULL) {
  2794. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  2795. return -1;
  2796. }
  2797. add->next = prev->next;
  2798. prev->next = add;
  2799. *reassemblyMemory += added;
  2800. }
  2801. return 1;
  2802. }
  2803. /* Add out of order FIN capture */
  2804. /* returns 1 for success (end) */
  2805. static int AddFinCapture(SnifferSession* session, word32 sequence)
  2806. {
  2807. if (session->flags.side == WOLFSSL_SERVER_END) {
  2808. if (session->finCaputre.cliCounted == 0)
  2809. session->finCaputre.cliFinSeq = sequence;
  2810. }
  2811. else {
  2812. if (session->finCaputre.srvCounted == 0)
  2813. session->finCaputre.srvFinSeq = sequence;
  2814. }
  2815. return 1;
  2816. }
  2817. /* Adjust incoming sequence based on side */
  2818. /* returns 0 on success (continue), -1 on error, 1 on success (end) */
  2819. static int AdjustSequence(TcpInfo* tcpInfo, SnifferSession* session,
  2820. int* sslBytes, const byte** sslFrame, char* error)
  2821. {
  2822. word32 seqStart = (session->flags.side == WOLFSSL_SERVER_END) ?
  2823. session->cliSeqStart :session->srvSeqStart;
  2824. word32 real = tcpInfo->sequence - seqStart;
  2825. word32* expected = (session->flags.side == WOLFSSL_SERVER_END) ?
  2826. &session->cliExpected : &session->srvExpected;
  2827. PacketBuffer* reassemblyList = (session->flags.side == WOLFSSL_SERVER_END) ?
  2828. session->cliReassemblyList : session->srvReassemblyList;
  2829. byte skipPartial = (session->flags.side == WOLFSSL_SERVER_END) ?
  2830. session->flags.srvSkipPartial :
  2831. session->flags.cliSkipPartial;
  2832. /* handle rollover of sequence */
  2833. if (tcpInfo->sequence < seqStart)
  2834. real = 0xffffffffU - seqStart + tcpInfo->sequence;
  2835. TraceRelativeSequence(*expected, real);
  2836. if (real < *expected) {
  2837. Trace(DUPLICATE_STR);
  2838. if (real + *sslBytes > *expected) {
  2839. int overlap = *expected - real;
  2840. Trace(OVERLAP_DUPLICATE_STR);
  2841. /* adjust to expected, remove duplicate */
  2842. *sslFrame += overlap;
  2843. *sslBytes -= overlap;
  2844. /* The following conditional block is duplicated below. It is the
  2845. * same action but for a different setup case. If changing this
  2846. * block be sure to also update the block below. */
  2847. if (reassemblyList) {
  2848. word32 newEnd = *expected + *sslBytes;
  2849. if (newEnd > reassemblyList->begin) {
  2850. Trace(OVERLAP_REASSEMBLY_BEGIN_STR);
  2851. /* remove bytes already on reassembly list */
  2852. *sslBytes -= newEnd - reassemblyList->begin;
  2853. }
  2854. if (newEnd > reassemblyList->end) {
  2855. Trace(OVERLAP_REASSEMBLY_END_STR);
  2856. /* may be past reassembly list end (could have more on list)
  2857. so try to add what's past the front->end */
  2858. AddToReassembly(session->flags.side, reassemblyList->end +1,
  2859. *sslFrame + reassemblyList->end - *expected + 1,
  2860. newEnd - reassemblyList->end, session, error);
  2861. }
  2862. }
  2863. }
  2864. else
  2865. return 1;
  2866. }
  2867. else if (real > *expected) {
  2868. Trace(OUT_OF_ORDER_STR);
  2869. if (*sslBytes > 0) {
  2870. int addResult = AddToReassembly(session->flags.side, real,
  2871. *sslFrame, *sslBytes, session, error);
  2872. if (skipPartial) {
  2873. *sslBytes = 0;
  2874. return 0;
  2875. }
  2876. else
  2877. return addResult;
  2878. }
  2879. else if (tcpInfo->fin)
  2880. return AddFinCapture(session, real);
  2881. }
  2882. else if (*sslBytes > 0) {
  2883. if (skipPartial) {
  2884. AddToReassembly(session->flags.side, real,
  2885. *sslFrame, *sslBytes, session, error);
  2886. *expected += *sslBytes;
  2887. *sslBytes = 0;
  2888. if (tcpInfo->fin)
  2889. *expected += 1;
  2890. return 0;
  2891. }
  2892. /* The following conditional block is duplicated above. It is the
  2893. * same action but for a different setup case. If changing this
  2894. * block be sure to also update the block above. */
  2895. else if (reassemblyList) {
  2896. word32 newEnd = *expected + *sslBytes;
  2897. if (newEnd > reassemblyList->begin) {
  2898. Trace(OVERLAP_REASSEMBLY_BEGIN_STR);
  2899. /* remove bytes already on reassembly list */
  2900. *sslBytes -= newEnd - reassemblyList->begin;
  2901. }
  2902. if (newEnd > reassemblyList->end) {
  2903. Trace(OVERLAP_REASSEMBLY_END_STR);
  2904. /* may be past reassembly list end (could have more on list)
  2905. so try to add what's past the front->end */
  2906. AddToReassembly(session->flags.side, reassemblyList->end +1,
  2907. *sslFrame + reassemblyList->end - *expected + 1,
  2908. newEnd - reassemblyList->end, session, error);
  2909. }
  2910. }
  2911. }
  2912. /* got expected sequence */
  2913. *expected += *sslBytes;
  2914. if (tcpInfo->fin)
  2915. *expected += 1;
  2916. return 0;
  2917. }
  2918. static int FindNextRecordInAssembly(SnifferSession* session,
  2919. const byte** sslFrame, int* sslBytes,
  2920. const byte** end, char* error)
  2921. {
  2922. PacketBuffer** front = (session->flags.side == WOLFSSL_SERVER_END) ?
  2923. &session->cliReassemblyList :
  2924. &session->srvReassemblyList;
  2925. PacketBuffer* curr = *front;
  2926. PacketBuffer* prev = NULL;
  2927. byte* skipPartial = (session->flags.side == WOLFSSL_SERVER_END) ?
  2928. &session->flags.srvSkipPartial :
  2929. &session->flags.cliSkipPartial;
  2930. word32* reassemblyMemory = (session->flags.side == WOLFSSL_SERVER_END) ?
  2931. &session->cliReassemblyMemory :
  2932. &session->srvReassemblyMemory;
  2933. SSL* ssl = (session->flags.side == WOLFSSL_SERVER_END) ?
  2934. session->sslServer :
  2935. session->sslClient;
  2936. ProtocolVersion pv = ssl->version;
  2937. word32* expected = (session->flags.side == WOLFSSL_SERVER_END) ?
  2938. &session->cliExpected :
  2939. &session->srvExpected;
  2940. while (curr != NULL) {
  2941. *expected = curr->end + 1;
  2942. if (curr->data[0] == application_data &&
  2943. curr->data[1] == pv.major &&
  2944. curr->data[2] == pv.minor) {
  2945. if (ssl->buffers.inputBuffer.length > 0)
  2946. Trace(DROPPING_PARTIAL_RECORD);
  2947. *sslBytes = curr->end - curr->begin + 1;
  2948. if ( (word32)*sslBytes > ssl->buffers.inputBuffer.bufferSize) {
  2949. if (GrowInputBuffer(ssl, *sslBytes, 0) < 0) {
  2950. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  2951. return -1;
  2952. }
  2953. }
  2954. XMEMCPY(ssl->buffers.inputBuffer.buffer, curr->data, *sslBytes);
  2955. *front = curr->next;
  2956. *reassemblyMemory -= *sslBytes;
  2957. FreePacketBuffer(curr);
  2958. ssl->buffers.inputBuffer.length = *sslBytes;
  2959. *sslFrame = ssl->buffers.inputBuffer.buffer;
  2960. *end = *sslFrame + *sslBytes;
  2961. *skipPartial = 0;
  2962. return 0;
  2963. }
  2964. else if (ssl->specs.cipher_type == block) {
  2965. if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes) {
  2966. #ifdef BUILD_AES
  2967. wc_AesSetIV(ssl->decrypt.aes,
  2968. curr->data + curr->end - curr->begin
  2969. - ssl->specs.block_size + 1);
  2970. #endif
  2971. }
  2972. else if (ssl->specs.bulk_cipher_algorithm == wolfssl_triple_des) {
  2973. #ifdef BUILD_DES3
  2974. wc_Des3_SetIV(ssl->decrypt.des3,
  2975. curr->data + curr->end - curr->begin
  2976. - ssl->specs.block_size + 1);
  2977. #endif
  2978. }
  2979. }
  2980. Trace(DROPPING_LOST_FRAG_STR);
  2981. #ifdef WOLFSSL_SNIFFER_STATS
  2982. INC_STAT(SnifferStats.sslDecodeFails);
  2983. #endif
  2984. prev = curr;
  2985. curr = curr->next;
  2986. *reassemblyMemory -= (prev->end - prev->begin + 1);
  2987. FreePacketBuffer(prev);
  2988. }
  2989. *front = curr;
  2990. return 0;
  2991. }
  2992. static int FixSequence(TcpInfo* tcpInfo, SnifferSession* session)
  2993. {
  2994. word32* expected = (session->flags.side == WOLFSSL_SERVER_END) ?
  2995. &session->srvExpected : &session->cliExpected;
  2996. PacketBuffer* list = (session->flags.side == WOLFSSL_SERVER_END) ?
  2997. session->srvReassemblyList :
  2998. session->cliReassemblyList;
  2999. byte* skipPartial = (session->flags.side != WOLFSSL_SERVER_END) ?
  3000. &session->flags.srvSkipPartial :
  3001. &session->flags.cliSkipPartial;
  3002. *skipPartial = 1;
  3003. if (list != NULL)
  3004. *expected = list->begin;
  3005. else {
  3006. word32 seqStart = (session->flags.side == WOLFSSL_SERVER_END) ?
  3007. session->srvSeqStart : session->cliSeqStart;
  3008. word32 real = tcpInfo->ackNumber - seqStart;
  3009. *expected = real;
  3010. }
  3011. return 1;
  3012. }
  3013. /* Check latest ack number for missing packets
  3014. return 0 ok, <0 on error */
  3015. static int CheckAck(TcpInfo* tcpInfo, SnifferSession* session)
  3016. {
  3017. if (tcpInfo->ack) {
  3018. word32 seqStart = (session->flags.side == WOLFSSL_SERVER_END) ?
  3019. session->srvSeqStart :session->cliSeqStart;
  3020. word32 real = tcpInfo->ackNumber - seqStart;
  3021. word32 expected = (session->flags.side == WOLFSSL_SERVER_END) ?
  3022. session->srvExpected : session->cliExpected;
  3023. /* handle rollover of sequence */
  3024. if (tcpInfo->ackNumber < seqStart)
  3025. real = 0xffffffffU - seqStart + tcpInfo->ackNumber;
  3026. TraceAck(real, expected);
  3027. if (real > expected)
  3028. return -1; /* we missed a packet, ACKing data we never saw */
  3029. }
  3030. return 0;
  3031. }
  3032. /* Check TCP Sequence status */
  3033. /* returns 0 on success (continue), -1 on error, 1 on success (end) */
  3034. static int CheckSequence(IpInfo* ipInfo, TcpInfo* tcpInfo,
  3035. SnifferSession* session, int* sslBytes,
  3036. const byte** sslFrame, char* error)
  3037. {
  3038. int actualLen;
  3039. byte* ackFault = (session->flags.side == WOLFSSL_SERVER_END) ?
  3040. &session->flags.cliAckFault :
  3041. &session->flags.srvAckFault;
  3042. /* init SEQ from server to client */
  3043. if (tcpInfo->syn && tcpInfo->ack) {
  3044. session->srvSeqStart = tcpInfo->sequence;
  3045. session->srvExpected = 1;
  3046. TraceServerSyn(tcpInfo->sequence);
  3047. return 1;
  3048. }
  3049. /* adjust potential ethernet trailer */
  3050. actualLen = ipInfo->total - ipInfo->length - tcpInfo->length;
  3051. if (*sslBytes > actualLen) {
  3052. *sslBytes = actualLen;
  3053. }
  3054. TraceSequence(tcpInfo->sequence, *sslBytes);
  3055. if (CheckAck(tcpInfo, session) < 0) {
  3056. if (!RecoveryEnabled) {
  3057. UpdateMissedDataSessions();
  3058. SetError(ACK_MISSED_STR, error, session, FATAL_ERROR_STATE);
  3059. return -1;
  3060. }
  3061. else {
  3062. SetError(ACK_MISSED_STR, error, session, 0);
  3063. if (*ackFault == 0) {
  3064. *ackFault = 1;
  3065. UpdateMissedDataSessions();
  3066. }
  3067. return FixSequence(tcpInfo, session);
  3068. }
  3069. }
  3070. if (*ackFault) {
  3071. Trace(CLEAR_ACK_FAULT);
  3072. *ackFault = 0;
  3073. }
  3074. return AdjustSequence(tcpInfo, session, sslBytes, sslFrame, error);
  3075. }
  3076. /* Check Status before record processing */
  3077. /* returns 0 on success (continue), -1 on error, 1 on success (end) */
  3078. static int CheckPreRecord(IpInfo* ipInfo, TcpInfo* tcpInfo,
  3079. const byte** sslFrame, SnifferSession** session,
  3080. int* sslBytes, const byte** end,
  3081. void* vChain, word32 chainSz, char* error)
  3082. {
  3083. word32 length;
  3084. SSL* ssl = ((*session)->flags.side == WOLFSSL_SERVER_END) ?
  3085. (*session)->sslServer : (*session)->sslClient;
  3086. byte skipPartial = ((*session)->flags.side == WOLFSSL_SERVER_END) ?
  3087. (*session)->flags.srvSkipPartial :
  3088. (*session)->flags.cliSkipPartial;
  3089. /* remove SnifferSession on 2nd FIN or RST */
  3090. if (tcpInfo->fin || tcpInfo->rst) {
  3091. /* flag FIN and RST */
  3092. if (tcpInfo->fin)
  3093. (*session)->flags.finCount += 1;
  3094. else if (tcpInfo->rst)
  3095. (*session)->flags.finCount += 2;
  3096. if ((*session)->flags.finCount >= 2) {
  3097. RemoveSession(*session, ipInfo, tcpInfo, 0);
  3098. *session = NULL;
  3099. return 1;
  3100. }
  3101. }
  3102. if ((*session)->flags.fatalError == FATAL_ERROR_STATE) {
  3103. SetError(FATAL_ERROR_STR, error, NULL, 0);
  3104. return -1;
  3105. }
  3106. if (skipPartial) {
  3107. if (FindNextRecordInAssembly(*session,
  3108. sslFrame, sslBytes, end, error) < 0) {
  3109. return -1;
  3110. }
  3111. }
  3112. if (*sslBytes == 0) {
  3113. Trace(NO_DATA_STR);
  3114. return 1;
  3115. }
  3116. /* if current partial data, add to end of partial */
  3117. /* if skipping, the data is already at the end of partial */
  3118. if ( !skipPartial && (length = ssl->buffers.inputBuffer.length) ) {
  3119. Trace(PARTIAL_ADD_STR);
  3120. if ( (*sslBytes + length) > ssl->buffers.inputBuffer.bufferSize) {
  3121. if (GrowInputBuffer(ssl, *sslBytes, length) < 0) {
  3122. SetError(MEMORY_STR, error, *session, FATAL_ERROR_STATE);
  3123. return -1;
  3124. }
  3125. }
  3126. if (vChain == NULL) {
  3127. XMEMCPY(&ssl->buffers.inputBuffer.buffer[length],
  3128. *sslFrame, *sslBytes);
  3129. *sslBytes += length;
  3130. ssl->buffers.inputBuffer.length = *sslBytes;
  3131. *sslFrame = ssl->buffers.inputBuffer.buffer;
  3132. *end = *sslFrame + *sslBytes;
  3133. }
  3134. }
  3135. if (vChain != NULL) {
  3136. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  3137. struct iovec* chain = (struct iovec*)vChain;
  3138. word32 i, offset, headerSz, qty, remainder;
  3139. Trace(CHAIN_INPUT_STR);
  3140. headerSz = (word32)*sslFrame - (word32)chain[0].iov_base;
  3141. remainder = *sslBytes;
  3142. if ( (*sslBytes + length) > ssl->buffers.inputBuffer.bufferSize) {
  3143. if (GrowInputBuffer(ssl, *sslBytes, length) < 0) {
  3144. SetError(MEMORY_STR, error, *session, FATAL_ERROR_STATE);
  3145. return -1;
  3146. }
  3147. }
  3148. qty = min(*sslBytes, (word32)chain[0].iov_len - headerSz);
  3149. XMEMCPY(&ssl->buffers.inputBuffer.buffer[length],
  3150. (byte*)chain[0].iov_base + headerSz, qty);
  3151. offset = length;
  3152. for (i = 1; i < chainSz; i++) {
  3153. offset += qty;
  3154. remainder -= qty;
  3155. if (chain[i].iov_len > remainder)
  3156. qty = remainder;
  3157. else
  3158. qty = (word32)chain[i].iov_len;
  3159. XMEMCPY(ssl->buffers.inputBuffer.buffer + offset,
  3160. chain[i].iov_base, qty);
  3161. }
  3162. *sslBytes += length;
  3163. ssl->buffers.inputBuffer.length = *sslBytes;
  3164. *sslFrame = ssl->buffers.inputBuffer.buffer;
  3165. *end = *sslFrame + *sslBytes;
  3166. #endif
  3167. (void)chainSz;
  3168. }
  3169. if ((*session)->flags.clientHello == 0 && **sslFrame != handshake) {
  3170. /* Sanity check the packet for an old style client hello. */
  3171. int rhSize = (((*sslFrame)[0] & 0x7f) << 8) | ((*sslFrame)[1]);
  3172. if ((rhSize <= (*sslBytes - 2)) &&
  3173. (*sslFrame)[2] == OLD_HELLO_ID && (*sslFrame)[3] == SSLv3_MAJOR) {
  3174. #ifdef OLD_HELLO_ALLOWED
  3175. int ret = DoOldHello(*session, *sslFrame, &rhSize, sslBytes, error);
  3176. if (ret < 0)
  3177. return -1; /* error already set */
  3178. if (*sslBytes <= 0)
  3179. return 1;
  3180. #endif
  3181. }
  3182. else {
  3183. #ifdef STARTTLS_ALLOWED
  3184. if (ssl->buffers.inputBuffer.dynamicFlag) {
  3185. ssl->buffers.inputBuffer.length = 0;
  3186. ShrinkInputBuffer(ssl, NO_FORCED_FREE);
  3187. }
  3188. return 1;
  3189. #endif
  3190. }
  3191. }
  3192. return 0;
  3193. }
  3194. /* See if input on the reassembly list is ready for consuming */
  3195. /* returns 1 for TRUE, 0 for FALSE */
  3196. static int HaveMoreInput(SnifferSession* session, const byte** sslFrame,
  3197. int* sslBytes, const byte** end, char* error)
  3198. {
  3199. /* sequence and reassembly based on from, not to */
  3200. int moreInput = 0;
  3201. PacketBuffer** front = (session->flags.side == WOLFSSL_SERVER_END) ?
  3202. &session->cliReassemblyList : &session->srvReassemblyList;
  3203. word32* expected = (session->flags.side == WOLFSSL_SERVER_END) ?
  3204. &session->cliExpected : &session->srvExpected;
  3205. /* buffer is on receiving end */
  3206. word32* length = (session->flags.side == WOLFSSL_SERVER_END) ?
  3207. &session->sslServer->buffers.inputBuffer.length :
  3208. &session->sslClient->buffers.inputBuffer.length;
  3209. byte** myBuffer = (session->flags.side == WOLFSSL_SERVER_END) ?
  3210. &session->sslServer->buffers.inputBuffer.buffer :
  3211. &session->sslClient->buffers.inputBuffer.buffer;
  3212. word32* bufferSize = (session->flags.side == WOLFSSL_SERVER_END) ?
  3213. &session->sslServer->buffers.inputBuffer.bufferSize :
  3214. &session->sslClient->buffers.inputBuffer.bufferSize;
  3215. SSL* ssl = (session->flags.side == WOLFSSL_SERVER_END) ?
  3216. session->sslServer : session->sslClient;
  3217. word32* reassemblyMemory = (session->flags.side == WOLFSSL_SERVER_END) ?
  3218. &session->cliReassemblyMemory : &session->srvReassemblyMemory;
  3219. while (*front && ((*front)->begin == *expected) ) {
  3220. word32 room = *bufferSize - *length;
  3221. word32 packetLen = (*front)->end - (*front)->begin + 1;
  3222. if (packetLen > room && *bufferSize < MAX_INPUT_SZ) {
  3223. if (GrowInputBuffer(ssl, packetLen, *length) < 0) {
  3224. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  3225. return 0;
  3226. }
  3227. room = *bufferSize - *length; /* bufferSize is now bigger */
  3228. }
  3229. if (packetLen <= room) {
  3230. PacketBuffer* del = *front;
  3231. byte* buf = *myBuffer;
  3232. XMEMCPY(&buf[*length], (*front)->data, packetLen);
  3233. *length += packetLen;
  3234. *expected += packetLen;
  3235. /* remove used packet */
  3236. *front = (*front)->next;
  3237. *reassemblyMemory -= packetLen;
  3238. FreePacketBuffer(del);
  3239. moreInput = 1;
  3240. }
  3241. else
  3242. break;
  3243. }
  3244. if (moreInput) {
  3245. *sslFrame = *myBuffer;
  3246. *sslBytes = *length;
  3247. *end = *myBuffer + *length;
  3248. }
  3249. return moreInput;
  3250. }
  3251. /* Process Message(s) from sslFrame */
  3252. /* return Number of bytes on success, 0 for no data yet, and -1 on error */
  3253. static int ProcessMessage(const byte* sslFrame, SnifferSession* session,
  3254. int sslBytes, byte** data, const byte* end,
  3255. void* ctx, char* error)
  3256. {
  3257. const byte* sslBegin = sslFrame;
  3258. const byte* recordEnd; /* end of record indicator */
  3259. const byte* inRecordEnd; /* indicator from input stream not decrypt */
  3260. RecordLayerHeader rh;
  3261. int rhSize = 0;
  3262. int ret;
  3263. int errCode = 0;
  3264. int decoded = 0; /* bytes stored for user in data */
  3265. int notEnough; /* notEnough bytes yet flag */
  3266. int decrypted = 0; /* was current msg decrypted */
  3267. SSL* ssl = (session->flags.side == WOLFSSL_SERVER_END) ?
  3268. session->sslServer : session->sslClient;
  3269. doMessage:
  3270. notEnough = 0;
  3271. if (sslBytes < 0) {
  3272. SetError(PACKET_HDR_SHORT_STR, error, session, FATAL_ERROR_STATE);
  3273. return -1;
  3274. }
  3275. if (sslBytes >= RECORD_HEADER_SZ) {
  3276. if (GetRecordHeader(sslFrame, &rh, &rhSize) != 0) {
  3277. SetError(BAD_RECORD_HDR_STR, error, session, FATAL_ERROR_STATE);
  3278. return -1;
  3279. }
  3280. }
  3281. else
  3282. notEnough = 1;
  3283. if (notEnough || rhSize > (sslBytes - RECORD_HEADER_SZ)) {
  3284. /* don't have enough input yet to process full SSL record */
  3285. Trace(PARTIAL_INPUT_STR);
  3286. /* store partial if not there already or we advanced */
  3287. if (ssl->buffers.inputBuffer.length == 0 || sslBegin != sslFrame) {
  3288. if (sslBytes > (int)ssl->buffers.inputBuffer.bufferSize) {
  3289. if (GrowInputBuffer(ssl, sslBytes, 0) < 0) {
  3290. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  3291. return -1;
  3292. }
  3293. }
  3294. XMEMMOVE(ssl->buffers.inputBuffer.buffer, sslFrame, sslBytes);
  3295. ssl->buffers.inputBuffer.length = sslBytes;
  3296. }
  3297. if (HaveMoreInput(session, &sslFrame, &sslBytes, &end, error))
  3298. goto doMessage;
  3299. return decoded;
  3300. }
  3301. sslFrame += RECORD_HEADER_SZ;
  3302. sslBytes -= RECORD_HEADER_SZ;
  3303. recordEnd = sslFrame + rhSize; /* may have more than one record */
  3304. inRecordEnd = recordEnd;
  3305. /* decrypt if needed */
  3306. if ((session->flags.side == WOLFSSL_SERVER_END &&
  3307. session->flags.serverCipherOn)
  3308. || (session->flags.side == WOLFSSL_CLIENT_END &&
  3309. session->flags.clientCipherOn)) {
  3310. int ivAdvance = 0; /* TLSv1.1 advance amount */
  3311. if (ssl->decrypt.setup != 1) {
  3312. SetError(DECRYPT_KEYS_NOT_SETUP, error, session, FATAL_ERROR_STATE);
  3313. return -1;
  3314. }
  3315. if (CheckAvailableSize(ssl, rhSize) < 0) {
  3316. SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
  3317. return -1;
  3318. }
  3319. sslFrame = DecryptMessage(ssl, sslFrame, rhSize,
  3320. ssl->buffers.outputBuffer.buffer, &errCode,
  3321. &ivAdvance);
  3322. recordEnd = sslFrame - ivAdvance + rhSize; /* sslFrame moved so
  3323. should recordEnd */
  3324. decrypted = 1;
  3325. #ifdef WOLFSSL_SNIFFER_STATS
  3326. if (errCode != 0) {
  3327. INC_STAT(SnifferStats.sslKeyFails);
  3328. }
  3329. else {
  3330. LOCK_STAT();
  3331. NOLOCK_INC_STAT(SnifferStats.sslDecryptedPackets);
  3332. NOLOCK_ADD_TO_STAT(SnifferStats.sslDecryptedBytes, sslBytes);
  3333. UNLOCK_STAT();
  3334. }
  3335. #endif
  3336. if (errCode != 0) {
  3337. SetError(BAD_DECRYPT, error, session, FATAL_ERROR_STATE);
  3338. return -1;
  3339. }
  3340. }
  3341. doPart:
  3342. switch ((enum ContentType)rh.type) {
  3343. case handshake:
  3344. {
  3345. int startIdx = sslBytes;
  3346. int used;
  3347. Trace(GOT_HANDSHAKE_STR);
  3348. ret = DoHandShake(sslFrame, &sslBytes, session, error);
  3349. if (ret != 0) {
  3350. if (session->flags.fatalError == 0)
  3351. SetError(BAD_HANDSHAKE_STR, error, session,
  3352. FATAL_ERROR_STATE);
  3353. return -1;
  3354. }
  3355. /* DoHandShake now fully decrements sslBytes to remaining */
  3356. used = startIdx - sslBytes;
  3357. sslFrame += used;
  3358. if (decrypted)
  3359. sslFrame += ssl->keys.padSz;
  3360. }
  3361. break;
  3362. case change_cipher_spec:
  3363. if (session->flags.side == WOLFSSL_SERVER_END)
  3364. session->flags.serverCipherOn = 1;
  3365. else
  3366. session->flags.clientCipherOn = 1;
  3367. Trace(GOT_CHANGE_CIPHER_STR);
  3368. ssl->options.handShakeState = HANDSHAKE_DONE;
  3369. ssl->options.handShakeDone = 1;
  3370. sslFrame += 1;
  3371. sslBytes -= 1;
  3372. break;
  3373. case application_data:
  3374. Trace(GOT_APP_DATA_STR);
  3375. {
  3376. word32 inOutIdx = 0;
  3377. ret = DoApplicationData(ssl, (byte*)sslFrame, &inOutIdx);
  3378. if (ret == 0) {
  3379. ret = ssl->buffers.clearOutputBuffer.length;
  3380. TraceGotData(ret);
  3381. if (ret) { /* may be blank message */
  3382. if (data != NULL) {
  3383. byte* tmpData; /* don't leak on realloc free */
  3384. /* add an extra byte at end of allocation in case
  3385. * user wants to null terminate plaintext */
  3386. tmpData = (byte*)XREALLOC(*data, decoded + ret + 1,
  3387. NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3388. if (tmpData == NULL) {
  3389. ForceZero(*data, decoded);
  3390. XFREE(*data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3391. *data = NULL;
  3392. SetError(MEMORY_STR, error, session,
  3393. FATAL_ERROR_STATE);
  3394. return -1;
  3395. }
  3396. *data = tmpData;
  3397. XMEMCPY(*data + decoded,
  3398. ssl->buffers.clearOutputBuffer.buffer, ret);
  3399. }
  3400. else {
  3401. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  3402. if (StoreDataCb) {
  3403. const byte* buf;
  3404. word32 offset = 0;
  3405. word32 bufSz;
  3406. int stored;
  3407. buf = ssl->buffers.clearOutputBuffer.buffer;
  3408. bufSz = ssl->buffers.clearOutputBuffer.length;
  3409. do {
  3410. stored = StoreDataCb(buf, bufSz, offset,
  3411. ctx);
  3412. if (stored <= 0) {
  3413. return -1;
  3414. }
  3415. offset += stored;
  3416. } while (offset < bufSz);
  3417. }
  3418. else {
  3419. SetError(STORE_DATA_CB_MISSING_STR, error,
  3420. session, FATAL_ERROR_STATE);
  3421. return -1;
  3422. }
  3423. #else
  3424. (void)ctx;
  3425. SetError(NO_DATA_DEST_STR, error, session,
  3426. FATAL_ERROR_STATE);
  3427. return -1;
  3428. #endif
  3429. }
  3430. TraceAddedData(ret, decoded);
  3431. decoded += ret;
  3432. ssl->buffers.clearOutputBuffer.length = 0;
  3433. }
  3434. }
  3435. else {
  3436. SetError(BAD_APP_DATA_STR, error,session,FATAL_ERROR_STATE);
  3437. return -1;
  3438. }
  3439. if (ssl->buffers.outputBuffer.dynamicFlag)
  3440. ShrinkOutputBuffer(ssl);
  3441. sslFrame += inOutIdx;
  3442. sslBytes -= inOutIdx;
  3443. }
  3444. break;
  3445. case alert:
  3446. Trace(GOT_ALERT_STR);
  3447. #ifdef WOLFSSL_SNIFFER_STATS
  3448. INC_STAT(SnifferStats.sslAlerts);
  3449. #endif
  3450. sslFrame += rhSize;
  3451. sslBytes -= rhSize;
  3452. break;
  3453. case no_type:
  3454. default:
  3455. SetError(GOT_UNKNOWN_RECORD_STR, error, session, FATAL_ERROR_STATE);
  3456. return -1;
  3457. }
  3458. /* do we have another msg in record ? */
  3459. if (sslFrame < recordEnd) {
  3460. Trace(ANOTHER_MSG_STR);
  3461. goto doPart;
  3462. }
  3463. /* back to input stream instead of potential decrypt buffer */
  3464. recordEnd = inRecordEnd;
  3465. /* do we have more records ? */
  3466. if (recordEnd < end) {
  3467. Trace(ANOTHER_MSG_STR);
  3468. sslFrame = recordEnd;
  3469. sslBytes = (int)(end - recordEnd);
  3470. goto doMessage;
  3471. }
  3472. /* clear used input */
  3473. ssl->buffers.inputBuffer.length = 0;
  3474. /* could have more input ready now */
  3475. if (HaveMoreInput(session, &sslFrame, &sslBytes, &end, error))
  3476. goto doMessage;
  3477. if (ssl->buffers.inputBuffer.dynamicFlag)
  3478. ShrinkInputBuffer(ssl, NO_FORCED_FREE);
  3479. return decoded;
  3480. }
  3481. /* See if we need to process any pending FIN captures */
  3482. /* Return 0=normal, else = session removed */
  3483. static int CheckFinCapture(IpInfo* ipInfo, TcpInfo* tcpInfo,
  3484. SnifferSession* session)
  3485. {
  3486. int ret = 0;
  3487. if (session->finCaputre.cliFinSeq && session->finCaputre.cliFinSeq <=
  3488. session->cliExpected) {
  3489. if (session->finCaputre.cliCounted == 0) {
  3490. session->flags.finCount += 1;
  3491. session->finCaputre.cliCounted = 1;
  3492. TraceClientFin(session->finCaputre.cliFinSeq, session->cliExpected);
  3493. }
  3494. }
  3495. if (session->finCaputre.srvFinSeq && session->finCaputre.srvFinSeq <=
  3496. session->srvExpected) {
  3497. if (session->finCaputre.srvCounted == 0) {
  3498. session->flags.finCount += 1;
  3499. session->finCaputre.srvCounted = 1;
  3500. TraceServerFin(session->finCaputre.srvFinSeq, session->srvExpected);
  3501. }
  3502. }
  3503. if (session->flags.finCount >= 2) {
  3504. RemoveSession(session, ipInfo, tcpInfo, 0);
  3505. ret = 1;
  3506. }
  3507. return ret;
  3508. }
  3509. /* If session is in fatal error state free resources now
  3510. return true if removed, 0 otherwise */
  3511. static int RemoveFatalSession(IpInfo* ipInfo, TcpInfo* tcpInfo,
  3512. SnifferSession* session, char* error)
  3513. {
  3514. if (session && session->flags.fatalError == FATAL_ERROR_STATE) {
  3515. RemoveSession(session, ipInfo, tcpInfo, 0);
  3516. SetError(FATAL_ERROR_STR, error, NULL, 0);
  3517. return 1;
  3518. }
  3519. return 0;
  3520. }
  3521. /* Passes in an IP/TCP packet for decoding (ethernet/localhost frame) removed */
  3522. /* returns Number of bytes on success, 0 for no data yet, and -1 on error */
  3523. static int ssl_DecodePacketInternal(const byte* packet, int length,
  3524. void* vChain, word32 chainSz,
  3525. byte** data, SSLInfo* sslInfo,
  3526. void* ctx, char* error)
  3527. {
  3528. TcpInfo tcpInfo;
  3529. IpInfo ipInfo;
  3530. const byte* sslFrame;
  3531. const byte* end;
  3532. int sslBytes; /* ssl bytes unconsumed */
  3533. int ret;
  3534. SnifferSession* session = 0;
  3535. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  3536. if (packet == NULL && vChain != NULL) {
  3537. struct iovec* chain = (struct iovec*)vChain;
  3538. word32 i;
  3539. length = 0;
  3540. for (i = 0; i < chainSz; i++)
  3541. length += chain[i].iov_len;
  3542. packet = (const byte*)chain[0].iov_base;
  3543. }
  3544. #endif
  3545. if (CheckHeaders(&ipInfo, &tcpInfo, packet, length, &sslFrame, &sslBytes,
  3546. error) != 0)
  3547. return -1;
  3548. end = sslFrame + sslBytes;
  3549. ret = CheckSession(&ipInfo, &tcpInfo, sslBytes, &session, error);
  3550. if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) return -1;
  3551. else if (ret == -1) return -1;
  3552. else if (ret == 1) {
  3553. #ifdef WOLFSSL_SNIFFER_STATS
  3554. if (sslBytes > 0) {
  3555. LOCK_STAT();
  3556. NOLOCK_INC_STAT(SnifferStats.sslEncryptedPackets);
  3557. NOLOCK_ADD_TO_STAT(SnifferStats.sslEncryptedBytes, sslBytes);
  3558. UNLOCK_STAT();
  3559. }
  3560. else
  3561. INC_STAT(SnifferStats.sslDecryptedPackets);
  3562. #endif
  3563. return 0; /* done for now */
  3564. }
  3565. ret = CheckSequence(&ipInfo, &tcpInfo, session, &sslBytes, &sslFrame,error);
  3566. if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) return -1;
  3567. else if (ret == -1) return -1;
  3568. else if (ret == 1) {
  3569. #ifdef WOLFSSL_SNIFFER_STATS
  3570. INC_STAT(SnifferStats.sslDecryptedPackets);
  3571. #endif
  3572. return 0; /* done for now */
  3573. }
  3574. ret = CheckPreRecord(&ipInfo, &tcpInfo, &sslFrame, &session, &sslBytes,
  3575. &end, vChain, chainSz, error);
  3576. if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) return -1;
  3577. else if (ret == -1) return -1;
  3578. else if (ret == 1) {
  3579. #ifdef WOLFSSL_SNIFFER_STATS
  3580. INC_STAT(SnifferStats.sslDecryptedPackets);
  3581. #endif
  3582. return 0; /* done for now */
  3583. }
  3584. #ifdef WOLFSSL_SNIFFER_STATS
  3585. if (sslBytes > 0) {
  3586. LOCK_STAT();
  3587. NOLOCK_INC_STAT(SnifferStats.sslEncryptedPackets);
  3588. NOLOCK_ADD_TO_STAT(SnifferStats.sslEncryptedBytes, sslBytes);
  3589. UNLOCK_STAT();
  3590. }
  3591. else
  3592. INC_STAT(SnifferStats.sslDecryptedPackets);
  3593. #endif
  3594. ret = ProcessMessage(sslFrame, session, sslBytes, data, end, ctx, error);
  3595. if (RemoveFatalSession(&ipInfo, &tcpInfo, session, error)) return -1;
  3596. if (CheckFinCapture(&ipInfo, &tcpInfo, session) == 0) {
  3597. CopySessionInfo(session, sslInfo);
  3598. }
  3599. return ret;
  3600. }
  3601. /* Passes in an IP/TCP packet for decoding (ethernet/localhost frame) removed */
  3602. /* returns Number of bytes on success, 0 for no data yet, and -1 on error */
  3603. /* Also returns Session Info if available */
  3604. int ssl_DecodePacketWithSessionInfo(const unsigned char* packet, int length,
  3605. unsigned char** data, SSLInfo* sslInfo, char* error)
  3606. {
  3607. return ssl_DecodePacketInternal(packet, length, NULL, 0, data, sslInfo,
  3608. NULL, error);
  3609. }
  3610. /* Passes in an IP/TCP packet for decoding (ethernet/localhost frame) removed */
  3611. /* returns Number of bytes on success, 0 for no data yet, and -1 on error */
  3612. int ssl_DecodePacket(const byte* packet, int length, byte** data, char* error)
  3613. {
  3614. return ssl_DecodePacketInternal(packet, length, NULL, 0, data, NULL, NULL,
  3615. error);
  3616. }
  3617. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  3618. int ssl_DecodePacketWithSessionInfoStoreData(const unsigned char* packet,
  3619. int length, void* ctx, SSLInfo* sslInfo, char* error)
  3620. {
  3621. return ssl_DecodePacketInternal(packet, length, NULL, 0, NULL, sslInfo,
  3622. ctx, error);
  3623. }
  3624. #endif
  3625. #ifdef WOLFSSL_SNIFFER_CHAIN_INPUT
  3626. int ssl_DecodePacketWithChain(void* vChain, word32 chainSz, byte** data,
  3627. char* error)
  3628. {
  3629. return ssl_DecodePacketInternal(NULL, 0, vChain, chainSz, data, NULL, NULL,
  3630. error);
  3631. }
  3632. #endif
  3633. #if defined(WOLFSSL_SNIFFER_CHAIN_INPUT) && \
  3634. defined(WOLFSSL_SNIFFER_STORE_DATA_CB)
  3635. int ssl_DecodePacketWithChainSessionInfoStoreData(void* vChain, word32 chainSz,
  3636. void* ctx, SSLInfo* sslInfo, char* error)
  3637. {
  3638. return ssl_DecodePacketInternal(NULL, 0, vChain, chainSz, NULL, sslInfo,
  3639. ctx, error);
  3640. }
  3641. #endif
  3642. /* Deallocator for the decoded data buffer. */
  3643. /* returns 0 on success, -1 on error */
  3644. int ssl_FreeDecodeBuffer(byte** data, char* error)
  3645. {
  3646. return ssl_FreeZeroDecodeBuffer(data, 0, error);
  3647. }
  3648. /* Deallocator for the decoded data buffer, zeros out buffer. */
  3649. /* returns 0 on success, -1 on error */
  3650. int ssl_FreeZeroDecodeBuffer(byte** data, int sz, char* error)
  3651. {
  3652. (void)error;
  3653. if (sz < 0) {
  3654. return -1;
  3655. }
  3656. if (data != NULL) {
  3657. ForceZero(*data, (word32)sz);
  3658. XFREE(*data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3659. *data = NULL;
  3660. }
  3661. return 0;
  3662. }
  3663. /* Enables (if traceFile)/ Disables debug tracing */
  3664. /* returns 0 on success, -1 on error */
  3665. int ssl_Trace(const char* traceFile, char* error)
  3666. {
  3667. if (traceFile) {
  3668. /* Don't try to reopen the file */
  3669. if (TraceFile == NULL) {
  3670. TraceFile = fopen(traceFile, "a");
  3671. if (!TraceFile) {
  3672. SetError(BAD_TRACE_FILE_STR, error, NULL, 0);
  3673. return -1;
  3674. }
  3675. TraceOn = 1;
  3676. }
  3677. }
  3678. else
  3679. TraceOn = 0;
  3680. return 0;
  3681. }
  3682. /* Enables/Disables Recovery of missed data if later packets allow
  3683. * maxMemory is number of bytes to use for reassembly buffering per session,
  3684. * -1 means unlimited
  3685. * returns 0 on success, -1 on error */
  3686. int ssl_EnableRecovery(int onOff, int maxMemory, char* error)
  3687. {
  3688. (void)error;
  3689. RecoveryEnabled = onOff;
  3690. if (onOff)
  3691. MaxRecoveryMemory = maxMemory;
  3692. return 0;
  3693. }
  3694. #ifdef WOLFSSL_SESSION_STATS
  3695. int ssl_GetSessionStats(unsigned int* active, unsigned int* total,
  3696. unsigned int* peak, unsigned int* maxSessions,
  3697. unsigned int* missedData, unsigned int* reassemblyMem,
  3698. char* error)
  3699. {
  3700. int ret;
  3701. if (missedData) {
  3702. wc_LockMutex(&RecoveryMutex);
  3703. *missedData = MissedDataSessions;
  3704. wc_UnLockMutex(&RecoveryMutex);
  3705. }
  3706. if (reassemblyMem) {
  3707. SnifferSession* session;
  3708. int i;
  3709. *reassemblyMem = 0;
  3710. wc_LockMutex(&SessionMutex);
  3711. for (i = 0; i < HASH_SIZE; i++) {
  3712. session = SessionTable[i];
  3713. while (session) {
  3714. *reassemblyMem += session->cliReassemblyMemory;
  3715. *reassemblyMem += session->srvReassemblyMemory;
  3716. session = session->next;
  3717. }
  3718. }
  3719. wc_UnLockMutex(&SessionMutex);
  3720. }
  3721. ret = wolfSSL_get_session_stats(active, total, peak, maxSessions);
  3722. if (ret == WOLFSSL_SUCCESS)
  3723. return 0;
  3724. else {
  3725. SetError(BAD_SESSION_STATS, error, NULL, 0);
  3726. return -1;
  3727. }
  3728. }
  3729. #endif
  3730. int ssl_SetConnectionCb(SSLConnCb cb)
  3731. {
  3732. ConnectionCb = cb;
  3733. return 0;
  3734. }
  3735. int ssl_SetConnectionCtx(void* ctx)
  3736. {
  3737. ConnectionCbCtx = ctx;
  3738. return 0;
  3739. }
  3740. #ifdef WOLFSSL_SNIFFER_STATS
  3741. /* Resets the statistics tracking global structure.
  3742. * returns 0 on success, -1 on error */
  3743. int ssl_ResetStatistics(void)
  3744. {
  3745. wc_LockMutex(&StatsMutex);
  3746. XMEMSET(&SnifferStats, 0, sizeof(SSLStats));
  3747. wc_UnLockMutex(&StatsMutex);
  3748. return 0;
  3749. }
  3750. /* Copies the SSL statistics into the provided stats record.
  3751. * returns 0 on success, -1 on error */
  3752. int ssl_ReadStatistics(SSLStats* stats)
  3753. {
  3754. if (stats == NULL)
  3755. return -1;
  3756. LOCK_STAT();
  3757. XMEMCPY(stats, &SnifferStats, sizeof(SSLStats));
  3758. UNLOCK_STAT();
  3759. return 0;
  3760. }
  3761. /* Copies the SSL statistics into the provided stats record then
  3762. * resets the statistics tracking global structure.
  3763. * returns 0 on success, -1 on error */
  3764. int ssl_ReadResetStatistics(SSLStats* stats)
  3765. {
  3766. if (stats == NULL)
  3767. return -1;
  3768. LOCK_STAT();
  3769. XMEMCPY(stats, &SnifferStats, sizeof(SSLStats));
  3770. XMEMSET(&SnifferStats, 0, sizeof(SSLStats));
  3771. UNLOCK_STAT();
  3772. return 0;
  3773. }
  3774. #endif /* WOLFSSL_SNIFFER_STATS */
  3775. #ifdef WOLFSSL_SNIFFER_WATCH
  3776. int ssl_SetWatchKeyCallback_ex(SSLWatchCb cb, int devId, char* error)
  3777. {
  3778. (void)devId;
  3779. WatchCb = cb;
  3780. return CreateWatchSnifferServer(error);
  3781. }
  3782. int ssl_SetWatchKeyCallback(SSLWatchCb cb, char* error)
  3783. {
  3784. WatchCb = cb;
  3785. return CreateWatchSnifferServer(error);
  3786. }
  3787. int ssl_SetWatchKeyCtx(void* ctx, char* error)
  3788. {
  3789. (void)error;
  3790. WatchCbCtx = ctx;
  3791. return 0;
  3792. }
  3793. int ssl_SetWatchKey_buffer(void* vSniffer, const byte* key, word32 keySz,
  3794. int keyType, char* error)
  3795. {
  3796. SnifferSession* sniffer;
  3797. int ret;
  3798. if (vSniffer == NULL) {
  3799. return -1;
  3800. }
  3801. if (key == NULL || keySz == 0) {
  3802. return -1;
  3803. }
  3804. sniffer = (SnifferSession*)vSniffer;
  3805. /* Remap the keyType from what the user can use to
  3806. * what wolfSSL_use_PrivateKey_buffer expects. */
  3807. keyType = (keyType == FILETYPE_PEM) ? WOLFSSL_FILETYPE_PEM :
  3808. WOLFSSL_FILETYPE_ASN1;
  3809. ret = wolfSSL_use_PrivateKey_buffer(sniffer->sslServer,
  3810. key, keySz, keyType);
  3811. if (ret != WOLFSSL_SUCCESS) {
  3812. SetError(KEY_FILE_STR, error, sniffer, FATAL_ERROR_STATE);
  3813. return -1;
  3814. }
  3815. return 0;
  3816. }
  3817. int ssl_SetWatchKey_file(void* vSniffer, const char* keyFile, int keyType,
  3818. const char* password, char* error)
  3819. {
  3820. byte* keyBuf = NULL;
  3821. word32 keyBufSz = 0;
  3822. int ret;
  3823. if (vSniffer == NULL) {
  3824. return -1;
  3825. }
  3826. if (keyFile == NULL) {
  3827. return -1;
  3828. }
  3829. /* Remap the keyType from what the user can use to
  3830. * what LoadKeyFile expects. */
  3831. keyType = (keyType == FILETYPE_PEM) ? WOLFSSL_FILETYPE_PEM :
  3832. WOLFSSL_FILETYPE_ASN1;
  3833. ret = LoadKeyFile(&keyBuf, &keyBufSz, keyFile, keyType, password);
  3834. if (ret < 0) {
  3835. SetError(KEY_FILE_STR, error, NULL, 0);
  3836. XFREE(keyBuf, NULL, DYNAMIC_TYPE_X509);
  3837. return -1;
  3838. }
  3839. ret = ssl_SetWatchKey_buffer(vSniffer, keyBuf, keyBufSz, FILETYPE_DER,
  3840. error);
  3841. XFREE(keyBuf, NULL, DYNAMIC_TYPE_X509);
  3842. return ret;
  3843. }
  3844. #endif /* WOLFSSL_SNIFFER_WATCH */
  3845. #ifdef WOLFSSL_SNIFFER_STORE_DATA_CB
  3846. int ssl_SetStoreDataCallback(SSLStoreDataCb cb)
  3847. {
  3848. StoreDataCb = cb;
  3849. return 0;
  3850. }
  3851. #endif /* WOLFSSL_SNIFFER_STORE_DATA_CB */
  3852. #endif /* WOLFSSL_SNIFFER */
  3853. #endif /* WOLFCRYPT_ONLY */