server_test.go 165 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "bytes"
  22. "context"
  23. "encoding/base64"
  24. "encoding/hex"
  25. "encoding/json"
  26. std_errors "errors"
  27. "flag"
  28. "fmt"
  29. "io"
  30. "io/ioutil"
  31. "math"
  32. "net"
  33. "net/http"
  34. "net/url"
  35. "os"
  36. "path/filepath"
  37. "reflect"
  38. "regexp"
  39. "slices"
  40. "strconv"
  41. "strings"
  42. "sync"
  43. "syscall"
  44. "testing"
  45. "time"
  46. "unsafe"
  47. udsipc "github.com/Psiphon-Inc/uds-ipc"
  48. socks "github.com/Psiphon-Labs/goptlib"
  49. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  50. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  51. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  52. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/dsl"
  53. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  54. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/inproxy"
  55. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  56. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  57. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  58. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  59. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  60. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  61. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/transforms"
  62. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  63. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/internal/testutils"
  64. pb "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server/pb/psiphond"
  65. pbr "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server/pb/router"
  66. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server/psinet"
  67. lrucache "github.com/cognusion/go-cache-lru"
  68. "github.com/miekg/dns"
  69. "golang.org/x/net/nettest"
  70. "golang.org/x/net/proxy"
  71. "google.golang.org/protobuf/proto"
  72. "google.golang.org/protobuf/reflect/protoreflect"
  73. "google.golang.org/protobuf/types/known/timestamppb"
  74. )
  75. var useProtobufLogging bool
  76. var testDataDirName string
  77. var mockWebServerURL, mockWebServerPort, mockWebServerExpectedResponse string
  78. func TestMain(m *testing.M) {
  79. flag.Parse()
  80. var err error
  81. testDataDirName, err = ioutil.TempDir("", "psiphon-server-test")
  82. if err != nil {
  83. fmt.Printf("TempDir failed: %s\n", err)
  84. os.Exit(1)
  85. }
  86. defer os.RemoveAll(testDataDirName)
  87. psiphon.SetEmitDiagnosticNotices(true, true)
  88. mockWebServerURL, mockWebServerExpectedResponse = runMockWebServer()
  89. os.Exit(m.Run())
  90. }
  91. func runMockWebServer() (string, string) {
  92. responseBody := prng.HexString(100000)
  93. serveMux := http.NewServeMux()
  94. serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  95. w.Write([]byte(responseBody))
  96. })
  97. server := &http.Server{
  98. Handler: serveMux,
  99. }
  100. listener, err := net.Listen("tcp", "127.0.0.1:0")
  101. if err != nil {
  102. fmt.Printf("net.Listen failed: %s\n", err)
  103. os.Exit(1)
  104. }
  105. listenAddress := listener.Addr().String()
  106. _, mockWebServerPort, _ = net.SplitHostPort(listenAddress)
  107. go func() {
  108. err := server.Serve(listener)
  109. if err != nil {
  110. fmt.Printf("http.Server.Serve failed: %s\n", err)
  111. os.Exit(1)
  112. }
  113. }()
  114. // TODO: properly synchronize with web server readiness
  115. time.Sleep(1 * time.Second)
  116. return fmt.Sprintf("http://%s/", listenAddress), responseBody
  117. }
  118. // Note: not testing fronted meek protocols, which client is
  119. // hard-wired to expect running on privileged ports 80 and 443.
  120. func TestSSH(t *testing.T) {
  121. runServer(t,
  122. &runServerConfig{
  123. tunnelProtocol: "SSH",
  124. requireAuthorization: true,
  125. doTunneledWebRequest: true,
  126. doTunneledNTPRequest: true,
  127. doDanglingTCPConn: true,
  128. doLogHostProvider: true,
  129. doLogProtobuf: useProtobufLogging,
  130. })
  131. }
  132. func TestOSSH(t *testing.T) {
  133. runServer(t,
  134. &runServerConfig{
  135. tunnelProtocol: "OSSH",
  136. requireAuthorization: true,
  137. doTunneledWebRequest: true,
  138. doTunneledNTPRequest: true,
  139. doDanglingTCPConn: true,
  140. doLogHostProvider: true,
  141. doLogProtobuf: useProtobufLogging,
  142. })
  143. }
  144. func TestFragmentedOSSH(t *testing.T) {
  145. runServer(t,
  146. &runServerConfig{
  147. tunnelProtocol: "OSSH",
  148. requireAuthorization: true,
  149. doTunneledWebRequest: true,
  150. doTunneledNTPRequest: true,
  151. forceFragmenting: true,
  152. doDanglingTCPConn: true,
  153. doLogHostProvider: true,
  154. doLogProtobuf: useProtobufLogging,
  155. })
  156. }
  157. func TestPrefixedOSSH(t *testing.T) {
  158. runServer(t,
  159. &runServerConfig{
  160. tunnelProtocol: "OSSH",
  161. requireAuthorization: true,
  162. doTunneledWebRequest: true,
  163. doTunneledNTPRequest: true,
  164. applyPrefix: true,
  165. doDanglingTCPConn: true,
  166. doLogHostProvider: true,
  167. inspectFlows: true,
  168. doLogProtobuf: useProtobufLogging,
  169. })
  170. }
  171. func TestFragmentedPrefixedOSSH(t *testing.T) {
  172. runServer(t,
  173. &runServerConfig{
  174. tunnelProtocol: "OSSH",
  175. requireAuthorization: true,
  176. doTunneledWebRequest: true,
  177. doTunneledNTPRequest: true,
  178. applyPrefix: true,
  179. forceFragmenting: true,
  180. doDanglingTCPConn: true,
  181. doLogHostProvider: true,
  182. inspectFlows: true,
  183. doLogProtobuf: useProtobufLogging,
  184. })
  185. }
  186. // NOTE: breaks the naming convention of dropping the OSSH suffix
  187. // because TestTLS is ambiguous as there are other protocols which
  188. // use TLS, e.g. UNFRONTED-MEEK-HTTPS-OSSH.
  189. func TestTLSOSSH(t *testing.T) {
  190. runServer(t,
  191. &runServerConfig{
  192. tunnelProtocol: "TLS-OSSH",
  193. passthrough: true,
  194. requireAuthorization: true,
  195. doTunneledWebRequest: true,
  196. doTunneledNTPRequest: true,
  197. doDanglingTCPConn: true,
  198. doLogProtobuf: useProtobufLogging,
  199. })
  200. }
  201. func TestShadowsocks(t *testing.T) {
  202. runServer(t,
  203. &runServerConfig{
  204. tunnelProtocol: "SHADOWSOCKS-OSSH",
  205. requireAuthorization: true,
  206. doTunneledWebRequest: true,
  207. doTunneledNTPRequest: true,
  208. doDanglingTCPConn: true,
  209. applyPrefix: true,
  210. doLogProtobuf: useProtobufLogging,
  211. })
  212. }
  213. func TestUnfrontedMeek(t *testing.T) {
  214. runServer(t,
  215. &runServerConfig{
  216. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  217. requireAuthorization: true,
  218. doTunneledWebRequest: true,
  219. doTunneledNTPRequest: true,
  220. doDanglingTCPConn: true,
  221. doLogHostProvider: true,
  222. doLogProtobuf: useProtobufLogging,
  223. })
  224. }
  225. func TestFragmentedUnfrontedMeek(t *testing.T) {
  226. runServer(t,
  227. &runServerConfig{
  228. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  229. requireAuthorization: true,
  230. doTunneledWebRequest: true,
  231. doTunneledNTPRequest: true,
  232. forceFragmenting: true,
  233. doDanglingTCPConn: true,
  234. doLogHostProvider: true,
  235. doLogProtobuf: useProtobufLogging,
  236. })
  237. }
  238. func TestUnfrontedMeekHTTPS(t *testing.T) {
  239. runServer(t,
  240. &runServerConfig{
  241. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  242. tlsProfile: protocol.TLS_PROFILE_RANDOMIZED,
  243. requireAuthorization: true,
  244. doTunneledWebRequest: true,
  245. doTunneledNTPRequest: true,
  246. doDanglingTCPConn: true,
  247. doLogHostProvider: true,
  248. doLogProtobuf: useProtobufLogging,
  249. })
  250. }
  251. func TestFragmentedUnfrontedMeekHTTPS(t *testing.T) {
  252. runServer(t,
  253. &runServerConfig{
  254. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  255. tlsProfile: protocol.TLS_PROFILE_RANDOMIZED,
  256. requireAuthorization: true,
  257. doTunneledWebRequest: true,
  258. doTunneledNTPRequest: true,
  259. forceFragmenting: true,
  260. doDanglingTCPConn: true,
  261. doLogHostProvider: true,
  262. doLogProtobuf: useProtobufLogging,
  263. })
  264. }
  265. func TestUnfrontedMeekHTTPSTLS13(t *testing.T) {
  266. runServer(t,
  267. &runServerConfig{
  268. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  269. tlsProfile: protocol.TLS_PROFILE_CHROME_70,
  270. requireAuthorization: true,
  271. doTunneledWebRequest: true,
  272. doTunneledNTPRequest: true,
  273. doDanglingTCPConn: true,
  274. doLogHostProvider: true,
  275. doLogProtobuf: useProtobufLogging,
  276. })
  277. }
  278. func TestUnfrontedMeekSessionTicket(t *testing.T) {
  279. runServer(t,
  280. &runServerConfig{
  281. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  282. tlsProfile: protocol.TLS_PROFILE_CHROME_58,
  283. requireAuthorization: true,
  284. doTunneledWebRequest: true,
  285. doTunneledNTPRequest: true,
  286. doDanglingTCPConn: true,
  287. doLogHostProvider: true,
  288. doLogProtobuf: useProtobufLogging,
  289. })
  290. }
  291. func TestUnfrontedMeekSessionTicketTLS13(t *testing.T) {
  292. runServer(t,
  293. &runServerConfig{
  294. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  295. tlsProfile: protocol.TLS_PROFILE_CHROME_70,
  296. requireAuthorization: true,
  297. doTunneledWebRequest: true,
  298. doTunneledNTPRequest: true,
  299. doDanglingTCPConn: true,
  300. doLogHostProvider: true,
  301. doLogProtobuf: useProtobufLogging,
  302. doUncompressedTactics: true,
  303. })
  304. }
  305. func TestTLSOSSHOverUnfrontedMeekHTTPSDemux(t *testing.T) {
  306. runServer(t,
  307. &runServerConfig{
  308. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  309. clientTunnelProtocol: "TLS-OSSH",
  310. passthrough: true,
  311. tlsProfile: protocol.TLS_PROFILE_CHROME_96, // TLS-OSSH requires TLS 1.3 support
  312. requireAuthorization: true,
  313. doTunneledWebRequest: true,
  314. doTunneledNTPRequest: true,
  315. doDanglingTCPConn: true,
  316. doLogProtobuf: useProtobufLogging,
  317. })
  318. }
  319. func TestTLSOSSHOverUnfrontedMeekSessionTicketDemux(t *testing.T) {
  320. runServer(t,
  321. &runServerConfig{
  322. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  323. clientTunnelProtocol: "TLS-OSSH",
  324. passthrough: true,
  325. tlsProfile: protocol.TLS_PROFILE_CHROME_96, // TLS-OSSH requires TLS 1.3 support
  326. requireAuthorization: true,
  327. doTunneledWebRequest: true,
  328. doTunneledNTPRequest: true,
  329. doDanglingTCPConn: true,
  330. doLogProtobuf: useProtobufLogging,
  331. })
  332. }
  333. func TestQUICOSSH(t *testing.T) {
  334. if !quic.Enabled() {
  335. t.Skip("QUIC is not enabled")
  336. }
  337. runServer(t,
  338. &runServerConfig{
  339. tunnelProtocol: "QUIC-OSSH",
  340. requireAuthorization: true,
  341. doTunneledWebRequest: true,
  342. doTunneledNTPRequest: true,
  343. doLogHostProvider: true,
  344. doLogProtobuf: useProtobufLogging,
  345. })
  346. }
  347. func TestLimitedQUICOSSH(t *testing.T) {
  348. if !quic.Enabled() {
  349. t.Skip("QUIC is not enabled")
  350. }
  351. runServer(t,
  352. &runServerConfig{
  353. tunnelProtocol: "QUIC-OSSH",
  354. requireAuthorization: true,
  355. doTunneledWebRequest: true,
  356. doTunneledNTPRequest: true,
  357. limitQUICVersions: true,
  358. doLogHostProvider: true,
  359. doLogProtobuf: useProtobufLogging,
  360. })
  361. }
  362. func TestInproxyOSSH(t *testing.T) {
  363. if !inproxy.Enabled() {
  364. t.Skip("inproxy is not enabled")
  365. }
  366. runServer(t,
  367. &runServerConfig{
  368. tunnelProtocol: "INPROXY-WEBRTC-OSSH",
  369. requireAuthorization: true,
  370. doTunneledWebRequest: true,
  371. doTunneledNTPRequest: true,
  372. doDanglingTCPConn: true,
  373. doLogHostProvider: true,
  374. doTargetBrokerSpecs: true,
  375. doLogProtobuf: useProtobufLogging,
  376. })
  377. }
  378. func TestRestrictInproxy(t *testing.T) {
  379. if !inproxy.Enabled() {
  380. t.Skip("inproxy is not enabled")
  381. }
  382. runServer(t,
  383. &runServerConfig{
  384. tunnelProtocol: "INPROXY-WEBRTC-OSSH",
  385. doRestrictInproxy: true,
  386. doLogProtobuf: useProtobufLogging,
  387. })
  388. }
  389. func TestInproxyQUICOSSH(t *testing.T) {
  390. if !quic.Enabled() {
  391. t.Skip("QUIC is not enabled")
  392. }
  393. if !inproxy.Enabled() {
  394. t.Skip("inproxy is not enabled")
  395. }
  396. runServer(t,
  397. &runServerConfig{
  398. tunnelProtocol: "INPROXY-WEBRTC-QUIC-OSSH",
  399. requireAuthorization: true,
  400. doTunneledWebRequest: true,
  401. doTunneledNTPRequest: true,
  402. doLogHostProvider: true,
  403. doLogProtobuf: useProtobufLogging,
  404. })
  405. }
  406. func TestInproxyUnfrontedMeekHTTPS(t *testing.T) {
  407. if !inproxy.Enabled() {
  408. t.Skip("inproxy is not enabled")
  409. }
  410. runServer(t,
  411. &runServerConfig{
  412. tunnelProtocol: "INPROXY-WEBRTC-UNFRONTED-MEEK-HTTPS-OSSH",
  413. requireAuthorization: true,
  414. doTunneledWebRequest: true,
  415. doTunneledNTPRequest: true,
  416. doDanglingTCPConn: true,
  417. doLogHostProvider: true,
  418. doLogProtobuf: useProtobufLogging,
  419. })
  420. }
  421. func TestInproxyTLSOSSH(t *testing.T) {
  422. if !inproxy.Enabled() {
  423. t.Skip("inproxy is not enabled")
  424. }
  425. runServer(t,
  426. &runServerConfig{
  427. tunnelProtocol: "INPROXY-WEBRTC-TLS-OSSH",
  428. requireAuthorization: true,
  429. doTunneledWebRequest: true,
  430. doTunneledNTPRequest: true,
  431. doDanglingTCPConn: true,
  432. doLogHostProvider: true,
  433. doLogProtobuf: useProtobufLogging,
  434. doUncompressedTactics: true,
  435. })
  436. }
  437. func TestInproxyPersonalPairing(t *testing.T) {
  438. if !inproxy.Enabled() {
  439. t.Skip("inproxy is not enabled")
  440. }
  441. runServer(t,
  442. &runServerConfig{
  443. tunnelProtocol: "INPROXY-WEBRTC-OSSH",
  444. requireAuthorization: true,
  445. doTunneledWebRequest: true,
  446. doTunneledNTPRequest: true,
  447. doDanglingTCPConn: true,
  448. doLogHostProvider: true,
  449. doTargetBrokerSpecs: true,
  450. doPersonalPairing: true,
  451. doLogProtobuf: useProtobufLogging,
  452. })
  453. }
  454. func TestInproxyOSSHMediaStreams(t *testing.T) {
  455. if !inproxy.Enabled() {
  456. t.Skip("inproxy is not enabled")
  457. }
  458. runServer(t,
  459. &runServerConfig{
  460. tunnelProtocol: "INPROXY-WEBRTC-OSSH",
  461. requireAuthorization: true,
  462. doTunneledWebRequest: true,
  463. doTunneledNTPRequest: true,
  464. doDanglingTCPConn: true,
  465. doLogHostProvider: true,
  466. doTargetBrokerSpecs: true,
  467. useInproxyMediaStreams: true,
  468. doLogProtobuf: useProtobufLogging,
  469. })
  470. }
  471. func TestInproxyQUICOSSHMediaStreams(t *testing.T) {
  472. if !inproxy.Enabled() {
  473. t.Skip("inproxy is not enabled")
  474. }
  475. runServer(t,
  476. &runServerConfig{
  477. tunnelProtocol: "INPROXY-WEBRTC-QUIC-OSSH",
  478. requireAuthorization: true,
  479. doTunneledWebRequest: true,
  480. doTunneledNTPRequest: true,
  481. doLogHostProvider: true,
  482. doTargetBrokerSpecs: true,
  483. useInproxyMediaStreams: true,
  484. doLogProtobuf: useProtobufLogging,
  485. })
  486. }
  487. func TestHotReload(t *testing.T) {
  488. runServer(t,
  489. &runServerConfig{
  490. tunnelProtocol: "OSSH",
  491. doHotReload: true,
  492. requireAuthorization: true,
  493. doTunneledWebRequest: true,
  494. doTunneledNTPRequest: true,
  495. doLogHostProvider: true,
  496. doLogProtobuf: useProtobufLogging,
  497. })
  498. }
  499. func TestHotReloadWithTactics(t *testing.T) {
  500. runServer(t,
  501. &runServerConfig{
  502. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  503. doHotReload: true,
  504. requireAuthorization: true,
  505. doTunneledWebRequest: true,
  506. doTunneledNTPRequest: true,
  507. doLogHostProvider: true,
  508. doLogProtobuf: useProtobufLogging,
  509. })
  510. }
  511. func TestDefaultSponsorID(t *testing.T) {
  512. runServer(t,
  513. &runServerConfig{
  514. tunnelProtocol: "OSSH",
  515. doHotReload: true,
  516. doDefaultSponsorID: true,
  517. requireAuthorization: true,
  518. doTunneledWebRequest: true,
  519. doTunneledNTPRequest: true,
  520. doLogHostProvider: true,
  521. doLogProtobuf: useProtobufLogging,
  522. })
  523. }
  524. func TestDenyTrafficRules(t *testing.T) {
  525. runServer(t,
  526. &runServerConfig{
  527. tunnelProtocol: "OSSH",
  528. doHotReload: true,
  529. denyTrafficRules: true,
  530. requireAuthorization: true,
  531. doTunneledWebRequest: true,
  532. doTunneledNTPRequest: true,
  533. doLogHostProvider: true,
  534. doLogProtobuf: useProtobufLogging,
  535. })
  536. }
  537. func TestOmitAuthorization(t *testing.T) {
  538. runServer(t,
  539. &runServerConfig{
  540. tunnelProtocol: "OSSH",
  541. doHotReload: true,
  542. requireAuthorization: true,
  543. omitAuthorization: true,
  544. doTunneledWebRequest: true,
  545. doTunneledNTPRequest: true,
  546. doLogHostProvider: true,
  547. doLogProtobuf: useProtobufLogging,
  548. })
  549. }
  550. func TestNoAuthorization(t *testing.T) {
  551. runServer(t,
  552. &runServerConfig{
  553. tunnelProtocol: "OSSH",
  554. doHotReload: true,
  555. omitAuthorization: true,
  556. doTunneledWebRequest: true,
  557. doTunneledNTPRequest: true,
  558. doLogHostProvider: true,
  559. doLogProtobuf: useProtobufLogging,
  560. })
  561. }
  562. func TestUnusedAuthorization(t *testing.T) {
  563. runServer(t,
  564. &runServerConfig{
  565. tunnelProtocol: "OSSH",
  566. doHotReload: true,
  567. doTunneledWebRequest: true,
  568. doTunneledNTPRequest: true,
  569. doLogHostProvider: true,
  570. doLogProtobuf: useProtobufLogging,
  571. })
  572. }
  573. func TestTCPOnlySLOK(t *testing.T) {
  574. runServer(t,
  575. &runServerConfig{
  576. tunnelProtocol: "OSSH",
  577. requireAuthorization: true,
  578. doTunneledWebRequest: true,
  579. doLogHostProvider: true,
  580. doLogProtobuf: useProtobufLogging,
  581. })
  582. }
  583. func TestUDPOnlySLOK(t *testing.T) {
  584. runServer(t,
  585. &runServerConfig{
  586. tunnelProtocol: "OSSH",
  587. requireAuthorization: true,
  588. doTunneledNTPRequest: true,
  589. doLogHostProvider: true,
  590. doLogProtobuf: useProtobufLogging,
  591. })
  592. }
  593. func TestLivenessTest(t *testing.T) {
  594. runServer(t,
  595. &runServerConfig{
  596. tunnelProtocol: "OSSH",
  597. requireAuthorization: true,
  598. doTunneledWebRequest: true,
  599. doTunneledNTPRequest: true,
  600. forceLivenessTest: true,
  601. doLogHostProvider: true,
  602. doLogProtobuf: useProtobufLogging,
  603. })
  604. }
  605. func TestPruneServerEntries(t *testing.T) {
  606. runServer(t,
  607. &runServerConfig{
  608. tunnelProtocol: "OSSH",
  609. requireAuthorization: true,
  610. doTunneledWebRequest: true,
  611. doTunneledNTPRequest: true,
  612. forceLivenessTest: true,
  613. doPruneServerEntries: true,
  614. doLogHostProvider: true,
  615. doLogProtobuf: useProtobufLogging,
  616. })
  617. }
  618. func TestCheckPruneServerEntries(t *testing.T) {
  619. runServer(t,
  620. &runServerConfig{
  621. tunnelProtocol: "OSSH",
  622. requireAuthorization: true,
  623. doTunneledWebRequest: true,
  624. doTunneledNTPRequest: true,
  625. forceLivenessTest: true,
  626. doPruneServerEntries: true,
  627. checkPruneServerEntries: true,
  628. doLogHostProvider: true,
  629. doLogProtobuf: useProtobufLogging,
  630. })
  631. }
  632. func TestBurstMonitorAndDestinationBytes(t *testing.T) {
  633. runServer(t,
  634. &runServerConfig{
  635. tunnelProtocol: "OSSH",
  636. requireAuthorization: true,
  637. doTunneledWebRequest: true,
  638. doTunneledNTPRequest: true,
  639. doDanglingTCPConn: true,
  640. doBurstMonitor: true,
  641. doDestinationBytes: true,
  642. doLogHostProvider: true,
  643. doLogProtobuf: useProtobufLogging,
  644. })
  645. }
  646. func TestBurstMonitorAndLegacyDestinationBytes(t *testing.T) {
  647. runServer(t,
  648. &runServerConfig{
  649. tunnelProtocol: "OSSH",
  650. requireAuthorization: true,
  651. doTunneledWebRequest: true,
  652. doTunneledNTPRequest: true,
  653. doDanglingTCPConn: true,
  654. doBurstMonitor: true,
  655. doLegacyDestinationBytes: true,
  656. doLogHostProvider: true,
  657. doLogProtobuf: useProtobufLogging,
  658. })
  659. }
  660. func TestChangeBytesConfig(t *testing.T) {
  661. runServer(t,
  662. &runServerConfig{
  663. tunnelProtocol: "OSSH",
  664. requireAuthorization: true,
  665. doTunneledWebRequest: true,
  666. doTunneledNTPRequest: true,
  667. doDanglingTCPConn: true,
  668. doDestinationBytes: true,
  669. doLegacyDestinationBytes: true,
  670. doChangeBytesConfig: true,
  671. doLogHostProvider: true,
  672. doLogProtobuf: useProtobufLogging,
  673. })
  674. }
  675. func TestSplitTunnel(t *testing.T) {
  676. runServer(t,
  677. &runServerConfig{
  678. tunnelProtocol: "OSSH",
  679. requireAuthorization: true,
  680. doTunneledWebRequest: true,
  681. doTunneledNTPRequest: true,
  682. doDanglingTCPConn: true,
  683. doSplitTunnel: true,
  684. doLogHostProvider: true,
  685. doLogProtobuf: useProtobufLogging,
  686. })
  687. }
  688. func TestOmitProvider(t *testing.T) {
  689. runServer(t,
  690. &runServerConfig{
  691. tunnelProtocol: "OSSH",
  692. requireAuthorization: true,
  693. doTunneledWebRequest: true,
  694. doTunneledNTPRequest: true,
  695. doDanglingTCPConn: true,
  696. doLogProtobuf: useProtobufLogging,
  697. })
  698. }
  699. func TestSteeringIP(t *testing.T) {
  700. runServer(t,
  701. &runServerConfig{
  702. tunnelProtocol: "FRONTED-MEEK-OSSH",
  703. // use a TLS profile that offers h2 in the ALPN
  704. tlsProfile: protocol.TLS_PROFILE_CHROME_102,
  705. requireAuthorization: true,
  706. doTunneledWebRequest: true,
  707. doTunneledNTPRequest: true,
  708. forceFragmenting: true,
  709. doDanglingTCPConn: true,
  710. doLogHostProvider: true,
  711. doSteeringIP: true,
  712. doLogProtobuf: useProtobufLogging,
  713. })
  714. }
  715. func TestLegacyAPIEncoding(t *testing.T) {
  716. runServer(t,
  717. &runServerConfig{
  718. tunnelProtocol: "OSSH",
  719. requireAuthorization: true,
  720. doTunneledWebRequest: true,
  721. doTunneledNTPRequest: true,
  722. doDanglingTCPConn: true,
  723. doLogHostProvider: true,
  724. useLegacyAPIEncoding: true,
  725. doLogProtobuf: useProtobufLogging,
  726. })
  727. }
  728. func TestDomainRequest(t *testing.T) {
  729. runServer(t,
  730. &runServerConfig{
  731. tunnelProtocol: "SSH",
  732. requireAuthorization: true,
  733. doTunneledDomainRequest: true,
  734. doLogHostProvider: true,
  735. doLogProtobuf: useProtobufLogging,
  736. })
  737. }
  738. type runServerConfig struct {
  739. tunnelProtocol string
  740. clientTunnelProtocol string
  741. passthrough bool
  742. tlsProfile string
  743. doHotReload bool
  744. doDefaultSponsorID bool
  745. denyTrafficRules bool
  746. requireAuthorization bool
  747. omitAuthorization bool
  748. doTunneledWebRequest bool
  749. doTunneledDomainRequest bool
  750. doTunneledNTPRequest bool
  751. applyPrefix bool
  752. forceFragmenting bool
  753. forceLivenessTest bool
  754. doPruneServerEntries bool
  755. checkPruneServerEntries bool
  756. doDanglingTCPConn bool
  757. doPacketManipulation bool
  758. doBurstMonitor bool
  759. doSplitTunnel bool
  760. limitQUICVersions bool
  761. doDestinationBytes bool
  762. doLegacyDestinationBytes bool
  763. doChangeBytesConfig bool
  764. doLogHostProvider bool
  765. inspectFlows bool
  766. doSteeringIP bool
  767. doTargetBrokerSpecs bool
  768. useLegacyAPIEncoding bool
  769. doPersonalPairing bool
  770. doRestrictInproxy bool
  771. useInproxyMediaStreams bool
  772. doUncompressedTactics bool
  773. doLogProtobuf bool
  774. }
  775. var (
  776. testSSHClientVersions = []string{"SSH-2.0-A", "SSH-2.0-B", "SSH-2.0-C"}
  777. testUserAgents = []string{"ua1", "ua2", "ua3"}
  778. testNetworkType = "WIFI"
  779. testCustomHostNameRegex = `[a-z0-9]{5,10}\.example\.org`
  780. testClientVersion = 1
  781. testClientPlatform = "Android_10_com.test.app"
  782. testClientFeatures = []string{"feature 1", "feature 2"}
  783. testDeviceRegion = "US"
  784. testServerRegion = "US"
  785. testDeviceLocation = "gzzzz"
  786. testDisallowedTrafficAlertActionURLs = []string{"https://example.org/disallowed"}
  787. testHostID = "example-host-id"
  788. // A steering IP must not be a bogon; this address is not dialed.
  789. testSteeringIP = "1.1.1.1"
  790. )
  791. var lastConnectedUpdateCount = 0
  792. func runServer(t *testing.T, runConfig *runServerConfig) {
  793. psiphonServerIPAddress := "127.0.0.1"
  794. psiphonServerPort := 4000
  795. // initialize server entry signing
  796. serverEntrySignaturePublicKey,
  797. serverEntrySignaturePrivateKey, err := protocol.NewServerEntrySignatureKeyPair()
  798. if err != nil {
  799. t.Fatalf("error generating server entry signature key pair: %s", err)
  800. }
  801. // generate inproxy configuration
  802. doInproxy := protocol.TunnelProtocolUsesInproxy(runConfig.tunnelProtocol)
  803. var inproxyTestConfig *inproxyTestConfig
  804. if doInproxy {
  805. addMeekServerForBroker := true
  806. brokerIPAddress := "127.0.0.1"
  807. brokerPort := 4001
  808. if protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol) {
  809. // Use the existing meek server as the broker server
  810. addMeekServerForBroker = false
  811. brokerPort = 4000
  812. }
  813. var err error
  814. inproxyTestConfig, err = generateInproxyTestConfig(
  815. addMeekServerForBroker,
  816. runConfig.doTargetBrokerSpecs,
  817. brokerIPAddress,
  818. brokerPort,
  819. serverEntrySignaturePublicKey,
  820. runConfig.useInproxyMediaStreams)
  821. if err != nil {
  822. t.Fatalf("error generating inproxy test config: %s", err)
  823. }
  824. }
  825. // set up DSL components
  826. // Add the DSL tests, including an initial untunneled DSL request to get
  827. // the primary server entry, when an in-proxy broker is available to be
  828. // the DSL relay.
  829. //
  830. // Limiting this to addMeekServerForBroker ensures the
  831. // configureDSLTestServerEntries bootstrap can only perform tactics
  832. // requests and not dial a tunnel, so the DSL request must succeed.
  833. doDSL := doInproxy && inproxyTestConfig.addMeekServerForBroker
  834. var dslTestConfig *dslTestConfig
  835. enableDSLFetcher := "false"
  836. if doDSL {
  837. t.Log("testing DSL")
  838. dslTestConfig, err = generateDSLTestConfig()
  839. if err != nil {
  840. t.Fatalf("error generating DSL test config: %s", err)
  841. }
  842. err = dslTestConfig.backend.Start()
  843. if err != nil {
  844. t.Fatalf("error starting DSL backend: %s", err)
  845. }
  846. defer dslTestConfig.backend.Stop()
  847. enableDSLFetcher = "true"
  848. }
  849. // configure authorized access
  850. accessType := "test-access-type"
  851. accessControlSigningKey, accessControlVerificationKey, err := accesscontrol.NewKeyPair(accessType)
  852. if err != nil {
  853. t.Fatalf("error creating access control key pair: %s", err)
  854. }
  855. accessControlVerificationKeyRing := &accesscontrol.VerificationKeyRing{
  856. Keys: []*accesscontrol.VerificationKey{accessControlVerificationKey},
  857. }
  858. var seedAuthorizationID [32]byte
  859. clientAuthorization, authorizationID, err := accesscontrol.IssueAuthorization(
  860. accessControlSigningKey,
  861. seedAuthorizationID[:],
  862. time.Now().Add(1*time.Hour))
  863. if err != nil {
  864. t.Fatalf("error issuing authorization: %s", err)
  865. }
  866. authorizationIDStr := base64.StdEncoding.EncodeToString(authorizationID)
  867. // Enable tactics when the test protocol is meek or uses inproxy. Both the
  868. // client and the server will be configured to support tactics. The
  869. // client config will be set with a nonfunctional config so that the
  870. // tactics request must succeed, overriding the nonfunctional values, for
  871. // the tunnel to establish.
  872. doClientTactics := protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol) ||
  873. doInproxy
  874. doServerTactics := doClientTactics ||
  875. runConfig.applyPrefix ||
  876. runConfig.forceFragmenting ||
  877. runConfig.doBurstMonitor ||
  878. runConfig.doDestinationBytes ||
  879. runConfig.doLegacyDestinationBytes ||
  880. runConfig.doTunneledDomainRequest
  881. // All servers require a tactics config with valid keys.
  882. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err :=
  883. tactics.GenerateKeys()
  884. if err != nil {
  885. t.Fatalf("error generating tactics keys: %s", err)
  886. }
  887. livenessTestSize := 0
  888. if doClientTactics || runConfig.forceLivenessTest {
  889. livenessTestSize = 1048576
  890. }
  891. // create a server
  892. var limitQUICVersions protocol.QUICVersions
  893. if runConfig.limitQUICVersions {
  894. // Limit the server entry to one specific QUICv1 version, and check
  895. // that this is used (see expectQUICVersion below). This test case
  896. // also exercises disabling gQUIC in the server config and
  897. // using "QUICv1" as the server entry capability.
  898. selectedQUICVersion := protocol.SupportedQUICv1Versions[prng.Intn(
  899. len(protocol.SupportedQUICv1Versions))]
  900. limitQUICVersions = protocol.QUICVersions{selectedQUICVersion}
  901. }
  902. var tunnelProtocolPassthroughAddresses map[string]string
  903. var passthroughAddress *string
  904. if runConfig.passthrough {
  905. passthroughAddress = new(string)
  906. *passthroughAddress = "x.x.x.x:x"
  907. tunnelProtocolPassthroughAddresses = map[string]string{
  908. // Tests do not trigger passthrough so set invalid IP and port.
  909. runConfig.tunnelProtocol: *passthroughAddress,
  910. }
  911. }
  912. tunnelProtocolPorts := map[string]int{runConfig.tunnelProtocol: psiphonServerPort}
  913. if doInproxy && inproxyTestConfig.addMeekServerForBroker {
  914. tunnelProtocolPorts["UNFRONTED-MEEK-HTTPS-OSSH"] = inproxyTestConfig.brokerPort
  915. }
  916. generateConfigParams := &GenerateConfigParams{
  917. ServerEntrySignaturePublicKey: serverEntrySignaturePublicKey,
  918. ServerEntrySignaturePrivateKey: serverEntrySignaturePrivateKey,
  919. ServerIPAddress: psiphonServerIPAddress,
  920. TunnelProtocolPorts: tunnelProtocolPorts,
  921. TunnelProtocolPassthroughAddresses: tunnelProtocolPassthroughAddresses,
  922. Passthrough: runConfig.passthrough,
  923. LimitQUICVersions: limitQUICVersions,
  924. EnableGQUIC: !runConfig.limitQUICVersions,
  925. ProviderID: strings.ToUpper(prng.HexString(8)),
  926. Region: testServerRegion,
  927. }
  928. if doServerTactics {
  929. generateConfigParams.TacticsRequestPublicKey = tacticsRequestPublicKey
  930. generateConfigParams.TacticsRequestObfuscatedKey = tacticsRequestObfuscatedKey
  931. }
  932. if protocol.TunnelProtocolUsesFrontedMeek(runConfig.tunnelProtocol) {
  933. generateConfigParams.FrontingProviderID = prng.HexString(8)
  934. }
  935. var configTacticsRequestPublicKey, configTacticsRequestPrivateKey, configTacticsRequestObfuscatedKey string
  936. if prng.FlipCoin() {
  937. // Exercise specifying the tactics key parameters in the main server
  938. // config file and not in the tactics config file.
  939. configTacticsRequestPublicKey = tacticsRequestPublicKey
  940. configTacticsRequestPrivateKey = tacticsRequestPrivateKey
  941. configTacticsRequestObfuscatedKey = tacticsRequestObfuscatedKey
  942. tacticsRequestPublicKey = ""
  943. tacticsRequestPrivateKey = ""
  944. tacticsRequestObfuscatedKey = ""
  945. }
  946. serverConfigJSON, _, _, _, encodedServerEntry, err := GenerateConfig(generateConfigParams)
  947. if err != nil {
  948. t.Fatalf("error generating server config: %s", err)
  949. }
  950. // customize server config
  951. discoveryServers, err := newDiscoveryServers([]string{"1.1.1.1", "2.2.2.2"})
  952. if err != nil {
  953. t.Fatalf("newDiscoveryServers failed: %s\n", err)
  954. }
  955. // Initialize prune server entry test cases and associated data to pave into psinet.
  956. pruneServerEntryTestCases, psinetValidServerEntryTags, expectedNumPruneNotices :=
  957. initializePruneServerEntriesTest(t, runConfig)
  958. // Pave psinet with random values to test handshake homepages.
  959. psinetFilename := filepath.Join(testDataDirName, "psinet.json")
  960. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(
  961. t, psinetFilename, "", runConfig.doDefaultSponsorID, true, psinetValidServerEntryTags, discoveryServers)
  962. // Pave OSL config for SLOK testing
  963. oslConfigFilename := filepath.Join(testDataDirName, "osl_config.json")
  964. propagationChannelID := paveOSLConfigFile(t, oslConfigFilename)
  965. // Pave traffic rules file which exercises handshake parameter filtering. Client
  966. // must handshake with specified sponsor ID in order to allow ports for tunneled
  967. // requests.
  968. trafficRulesFilename := filepath.Join(testDataDirName, "traffic_rules.json")
  969. paveTrafficRulesFile(
  970. t,
  971. trafficRulesFilename,
  972. propagationChannelID,
  973. accessType,
  974. authorizationIDStr,
  975. runConfig.requireAuthorization,
  976. runConfig.denyTrafficRules,
  977. livenessTestSize)
  978. var tacticsConfigFilename string
  979. var tacticsTunnelProtocol string
  980. var inproxyTacticsParametersJSON string
  981. // Only pave the tactics config when tactics are required. This exercises the
  982. // case where the tactics config is omitted.
  983. if doServerTactics {
  984. tacticsConfigFilename = filepath.Join(testDataDirName, "tactics_config.json")
  985. if runConfig.clientTunnelProtocol != "" {
  986. tacticsTunnelProtocol = runConfig.clientTunnelProtocol
  987. } else {
  988. tacticsTunnelProtocol = runConfig.tunnelProtocol
  989. }
  990. if doInproxy {
  991. inproxyTacticsParametersJSON = inproxyTestConfig.tacticsParametersJSON
  992. }
  993. paveTacticsConfigFile(
  994. t,
  995. tacticsConfigFilename,
  996. tacticsRequestPublicKey,
  997. tacticsRequestPrivateKey,
  998. tacticsRequestObfuscatedKey,
  999. tacticsTunnelProtocol,
  1000. propagationChannelID,
  1001. livenessTestSize,
  1002. runConfig.doBurstMonitor,
  1003. runConfig.doDestinationBytes,
  1004. runConfig.doLegacyDestinationBytes,
  1005. runConfig.applyPrefix,
  1006. runConfig.forceFragmenting,
  1007. "classic",
  1008. enableDSLFetcher,
  1009. inproxyTacticsParametersJSON,
  1010. runConfig.doRestrictInproxy,
  1011. generateConfigParams.ProviderID)
  1012. }
  1013. blocklistFilename := filepath.Join(testDataDirName, "blocklist.csv")
  1014. paveBlocklistFile(t, blocklistFilename)
  1015. var serverConfig map[string]interface{}
  1016. json.Unmarshal(serverConfigJSON, &serverConfig)
  1017. serverConfig["HostID"] = testHostID
  1018. // The test GeoIP databases map all IPs to a single, non-"None" country
  1019. // and ASN.
  1020. //
  1021. // When split tunnel mode is enabled, this should cause port forwards to
  1022. // be untunneled. When split tunnel mode is not enabled, port forwards
  1023. // should be tunneled despite the country match.
  1024. //
  1025. // When destination bytes metrics are enabled, all traffic will map to the
  1026. // single ASN.
  1027. geoIPCityDatabaseFilename := filepath.Join(testDataDirName, "geoip_city_database.mmbd")
  1028. geoIPISPDatabaseFilename := filepath.Join(testDataDirName, "geoip_isp_database.mmbd")
  1029. paveGeoIPDatabaseFiles(t, geoIPCityDatabaseFilename, geoIPISPDatabaseFilename)
  1030. serverConfig["GeoIPDatabaseFilenames"] = []string{geoIPCityDatabaseFilename, geoIPISPDatabaseFilename}
  1031. serverConfig["PsinetDatabaseFilename"] = psinetFilename
  1032. serverConfig["TrafficRulesFilename"] = trafficRulesFilename
  1033. serverConfig["OSLConfigFilename"] = oslConfigFilename
  1034. if doServerTactics {
  1035. serverConfig["TacticsConfigFilename"] = tacticsConfigFilename
  1036. if configTacticsRequestPublicKey != "" {
  1037. serverConfig["TacticsRequestPublicKey"] = configTacticsRequestPublicKey
  1038. }
  1039. if configTacticsRequestPrivateKey != "" {
  1040. serverConfig["TacticsRequestPrivateKey"] = configTacticsRequestPrivateKey
  1041. }
  1042. if configTacticsRequestObfuscatedKey != "" {
  1043. serverConfig["TacticsRequestObfuscatedKey"] = configTacticsRequestObfuscatedKey
  1044. }
  1045. }
  1046. serverConfig["BlocklistFilename"] = blocklistFilename
  1047. serverConfig["LogFilename"] = filepath.Join(testDataDirName, "psiphond.log")
  1048. serverConfig["LogLevel"] = "debug"
  1049. serverConfig["AccessControlVerificationKeyRing"] = accessControlVerificationKeyRing
  1050. // Set this parameter so at least the semaphore functions are called.
  1051. // TODO: test that the concurrency limit is correctly enforced.
  1052. serverConfig["MaxConcurrentSSHHandshakes"] = 1
  1053. // Ensure peak failure rate log fields for a single port forward attempt
  1054. serverConfig["PeakUpstreamFailureRateMinimumSampleSize"] = 1
  1055. // Exercise this option.
  1056. serverConfig["PeriodicGarbageCollectionSeconds"] = 1
  1057. // Allow port forwards to local test web server.
  1058. serverConfig["AllowBogons"] = true
  1059. serverConfig["RunPacketManipulator"] = runConfig.doPacketManipulation
  1060. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) &&
  1061. !runConfig.limitQUICVersions &&
  1062. quic.GQUICEnabled() {
  1063. // Enable legacy QUIC version support.
  1064. serverConfig["EnableGQUIC"] = true
  1065. }
  1066. if runConfig.doLogHostProvider {
  1067. serverConfig["HostProvider"] = "example-host-provider"
  1068. }
  1069. if runConfig.doSteeringIP {
  1070. serverConfig["EnableSteeringIPs"] = true
  1071. }
  1072. // In-proxy setup.
  1073. if doInproxy {
  1074. serverConfig["MeekServerRunInproxyBroker"] = true
  1075. // Limitation: can't exercise MeekServerInproxyBrokerOnly, as the
  1076. // single meek server must also provide a tactics endpoint.
  1077. serverConfig["MeekServerCertificate"] = inproxyTestConfig.brokerServerCertificate
  1078. serverConfig["MeekServerPrivateKey"] = inproxyTestConfig.brokerServerPrivateKey
  1079. serverConfig["MeekRequiredHeaders"] = inproxyTestConfig.brokerMeekRequiredHeaders
  1080. serverConfig["InproxyBrokerSessionPrivateKey"] =
  1081. inproxyTestConfig.brokerSessionPrivateKey
  1082. serverConfig["InproxyBrokerObfuscationRootSecret"] =
  1083. inproxyTestConfig.brokerObfuscationRootSecret
  1084. serverConfig["InproxyBrokerServerEntrySignaturePublicKey"] =
  1085. inproxyTestConfig.brokerServerEntrySignaturePublicKey
  1086. serverConfig["InproxyBrokerAllowCommonASNMatching"] = true
  1087. serverConfig["InproxyBrokerAllowBogonWebRTCConnections"] = true
  1088. }
  1089. if runConfig.doLogProtobuf {
  1090. serverConfig["LogFormat"] = "protobuf"
  1091. metricSocketPath, _ := nettest.LocalPath()
  1092. defer os.Remove(metricSocketPath)
  1093. serverConfig["MetricSocketPath"] = metricSocketPath
  1094. serverConfig["LogDestinationPrefix"] = "testprefix"
  1095. }
  1096. if doDSL {
  1097. serverConfig["DSLRelayServiceAddress"] = dslTestConfig.backend.GetAddress()
  1098. serverConfig["DSLRelayCACertificatesFilename"] = dslTestConfig.relayCACertificatesFilename
  1099. serverConfig["DSLRelayHostCertificateFilename"] = dslTestConfig.relayHostCertificateFilename
  1100. serverConfig["DSLRelayHostKeyFilename"] = dslTestConfig.relayHostKeyFilename
  1101. }
  1102. // Uncomment to enable SIGUSR2 profile dumps
  1103. //serverConfig["ProcessProfileOutputDirectory"] = "/tmp"
  1104. serverConfigJSON, _ = json.Marshal(serverConfig)
  1105. // Reset server_load log reassembly with the expected number of protocol
  1106. // log components.
  1107. expectedServerLoadProtocolLogs := len(tunnelProtocolPorts)
  1108. if runConfig.clientTunnelProtocol != "" {
  1109. expectedServerLoadProtocolLogs += 1 // Demux case
  1110. }
  1111. if runConfig.denyTrafficRules || runConfig.omitAuthorization {
  1112. expectedServerLoadProtocolLogs = 0
  1113. }
  1114. resetReassembleServerLoadLogs(expectedServerLoadProtocolLogs)
  1115. expectedTunnelLogs := 1
  1116. if runConfig.doDestinationBytes && !runConfig.doChangeBytesConfig {
  1117. expectedTunnelLogs++ // 1 base + 1 ASN
  1118. }
  1119. resetReassembleServerTunnelLogs(expectedTunnelLogs)
  1120. uniqueUserLog := make(chan map[string]interface{}, 1)
  1121. domainBytesLog := make(chan map[string]interface{}, 1)
  1122. serverTunnelLog := make(chan map[string]interface{}, 1)
  1123. // Max 3 discovery logs:
  1124. // 1. server startup
  1125. // 2. hot reload of psinet db (runConfig.doHotReload)
  1126. // 3. hot reload of server tactics (runConfig.doHotReload && doServerTactics)
  1127. discoveryLog := make(chan map[string]interface{}, 3)
  1128. // Up to 3 server_load logs: one without a region on start up, followed by
  1129. // a pair including a region after the client connects.
  1130. serverLoadLog := make(chan map[string]interface{}, 3)
  1131. inproxyProxyAnnounceLog := make(chan map[string]interface{}, 1)
  1132. inproxyClientOfferLog := make(chan map[string]interface{}, 1)
  1133. inproxyProxyAnswerLog := make(chan map[string]interface{}, 1)
  1134. inproxyServerProxyQualityLog := make(chan map[string]interface{}, 1)
  1135. logCallback := func(log []byte) {
  1136. logFields := make(map[string]interface{})
  1137. err := json.Unmarshal(log, &logFields)
  1138. if err != nil {
  1139. return
  1140. }
  1141. if logFields["event_name"] == nil {
  1142. if logFields["discovery_strategy"] != nil {
  1143. select {
  1144. case discoveryLog <- logFields:
  1145. default:
  1146. }
  1147. }
  1148. return
  1149. }
  1150. switch logFields["event_name"].(string) {
  1151. case "unique_user":
  1152. select {
  1153. case uniqueUserLog <- logFields:
  1154. default:
  1155. }
  1156. case "domain_bytes":
  1157. select {
  1158. case domainBytesLog <- logFields:
  1159. default:
  1160. }
  1161. case "server_tunnel":
  1162. select {
  1163. case serverTunnelLog <- logFields:
  1164. default:
  1165. }
  1166. case "server_load":
  1167. select {
  1168. case serverLoadLog <- logFields:
  1169. default:
  1170. }
  1171. case "inproxy_broker":
  1172. event, ok := logFields["broker_event"].(string)
  1173. if !ok {
  1174. t.Errorf("missing inproxy_broker.broker_event")
  1175. }
  1176. switch event {
  1177. case "proxy-announce":
  1178. select {
  1179. case inproxyProxyAnnounceLog <- logFields:
  1180. default:
  1181. }
  1182. case "client-offer":
  1183. select {
  1184. case inproxyClientOfferLog <- logFields:
  1185. default:
  1186. }
  1187. case "proxy-answer":
  1188. select {
  1189. case inproxyProxyAnswerLog <- logFields:
  1190. default:
  1191. }
  1192. case "server-proxy-quality":
  1193. select {
  1194. case inproxyServerProxyQualityLog <- logFields:
  1195. default:
  1196. }
  1197. }
  1198. }
  1199. }
  1200. // Capture log events in order to check both that events are logged and
  1201. // verify expected log contents.
  1202. //
  1203. // For JSON logging mode, the debug helper setLogCallback directly
  1204. // captures each log line.
  1205. //
  1206. // For protobuf logging mode, exercise the IPC mechanism and capture the
  1207. // logs via the IPC recipient handler. Protobuf logs are converted to
  1208. // JSON in order to use the same content checking helpers.
  1209. setLogCallback(logCallback)
  1210. var socketReader *udsipc.Reader
  1211. if runConfig.doLogProtobuf {
  1212. handler := func(data []byte) (retErr error) {
  1213. defer func() {
  1214. if retErr != nil {
  1215. t.Error(retErr.Error())
  1216. }
  1217. }()
  1218. // The Router message is not needed in testing, so we deserialize it to
  1219. // get the byte slice from the Value field, containing the seriailized
  1220. // Psiphond message that we want to work with to reconstruct the log map.
  1221. routedMsg := &pbr.Router{}
  1222. err := proto.Unmarshal(data, routedMsg)
  1223. if err != nil {
  1224. return errors.Trace(err)
  1225. }
  1226. protoMsg := &pb.Psiphond{}
  1227. err = proto.Unmarshal(routedMsg.GetValue(), protoMsg)
  1228. if err != nil {
  1229. return errors.Trace(err)
  1230. }
  1231. routedMsg = nil
  1232. reflectedLogFields := map[string]interface{}{}
  1233. protoToLogFields(protoMsg, reflectedLogFields, runConfig)
  1234. eventName, _ := reflectedLogFields["event_name"].(string)
  1235. if strings.HasPrefix(eventName, "server_load") {
  1236. // Multiple protobuf server_load* logs are reassembled into
  1237. // one JSON server_load log.
  1238. reflectedLogFields, err = reassembleServerLoadLog(
  1239. eventName, reflectedLogFields)
  1240. if err != nil {
  1241. return errors.Trace(err)
  1242. }
  1243. } else if strings.HasPrefix(eventName, "server_tunnel") {
  1244. // Multiple protobuf server_tunnel* logs are reassembled into
  1245. // one JSON server_tunnel log.
  1246. reflectedLogFields, err = reassembleServerTunnelLog(
  1247. eventName, reflectedLogFields)
  1248. if err != nil {
  1249. return errors.Trace(err)
  1250. }
  1251. }
  1252. if reflectedLogFields != nil {
  1253. jsonLog, err := json.Marshal(reflectedLogFields)
  1254. if err != nil {
  1255. return errors.Trace(err)
  1256. }
  1257. logCallback(jsonLog)
  1258. }
  1259. return nil
  1260. }
  1261. socketReader, err = udsipc.NewReader(
  1262. handler,
  1263. serverConfig["MetricSocketPath"].(string))
  1264. if err != nil {
  1265. t.Fatalf("error creating metric socket reader: %s", err)
  1266. }
  1267. socketReader.Start()
  1268. readerShutdownCtx, readerShutdownCtxCancel :=
  1269. context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))
  1270. defer func() {
  1271. readerShutdownCtxCancel()
  1272. socketReader.Stop(readerShutdownCtx)
  1273. }()
  1274. }
  1275. // run flow inspector if requested
  1276. var flowInspectorProxy *flowInspectorProxy
  1277. if runConfig.inspectFlows {
  1278. flowInspectorProxy, err = newFlowInspectorProxy()
  1279. if err != nil {
  1280. t.Fatalf("error starting flow inspector: %s", err)
  1281. }
  1282. flowInspectorProxy.start()
  1283. defer flowInspectorProxy.close()
  1284. }
  1285. // run server
  1286. serverWaitGroup := new(sync.WaitGroup)
  1287. serverWaitGroup.Add(1)
  1288. go func() {
  1289. defer serverWaitGroup.Done()
  1290. // Workaround for one-time logging initialization that persists across
  1291. // test runs. Reset logging to uninitialized. This assumes the
  1292. // previous run has completed and not left any dangling goroutines
  1293. // that may access these variables.
  1294. if log != nil {
  1295. log = nil
  1296. initLogging = sync.Once{}
  1297. }
  1298. err := RunServices(serverConfigJSON)
  1299. if err != nil {
  1300. // TODO: wrong goroutine for t.FatalNow()
  1301. t.Errorf("error running server: %s", err)
  1302. }
  1303. }()
  1304. stopServer := func() {
  1305. // Test: orderly server shutdown
  1306. p, _ := os.FindProcess(os.Getpid())
  1307. p.Signal(os.Interrupt)
  1308. shutdownTimeout := time.NewTimer(5 * time.Second)
  1309. shutdownOk := make(chan struct{}, 1)
  1310. go func() {
  1311. serverWaitGroup.Wait()
  1312. shutdownOk <- struct{}{}
  1313. }()
  1314. select {
  1315. case <-shutdownOk:
  1316. case <-shutdownTimeout.C:
  1317. t.Fatalf("server shutdown timeout exceeded")
  1318. }
  1319. }
  1320. // Stop server on early exits due to failure.
  1321. defer func() {
  1322. if stopServer != nil {
  1323. stopServer()
  1324. }
  1325. }()
  1326. // TODO: monitor logs for more robust wait-until-loaded. For example,
  1327. // especially with the race detector on, QUIC-OSSH tests can fail as the
  1328. // client sends its initial packet before the server is ready.
  1329. time.Sleep(1 * time.Second)
  1330. // Test: hot reload (of psinet and traffic rules)
  1331. if runConfig.doHotReload {
  1332. // Change discovery servers. Tests that discovery switches over to
  1333. // these new servers.
  1334. discoveryServers, err = newDiscoveryServers([]string{"3.3.3.3"})
  1335. if err != nil {
  1336. t.Fatalf("newDiscoveryServers failed: %s\n", err)
  1337. }
  1338. // Pave new config files with different random values.
  1339. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(
  1340. t, psinetFilename, "", runConfig.doDefaultSponsorID, true, psinetValidServerEntryTags, discoveryServers)
  1341. propagationChannelID = paveOSLConfigFile(t, oslConfigFilename)
  1342. paveTrafficRulesFile(
  1343. t,
  1344. trafficRulesFilename,
  1345. propagationChannelID,
  1346. accessType,
  1347. authorizationIDStr,
  1348. runConfig.requireAuthorization,
  1349. runConfig.denyTrafficRules,
  1350. livenessTestSize)
  1351. if doServerTactics {
  1352. // Pave new tactics file with different discovery strategy. Tests
  1353. // that discovery switches over to the new strategy.
  1354. paveTacticsConfigFile(
  1355. t,
  1356. tacticsConfigFilename,
  1357. tacticsRequestPublicKey,
  1358. tacticsRequestPrivateKey,
  1359. tacticsRequestObfuscatedKey,
  1360. tacticsTunnelProtocol,
  1361. propagationChannelID,
  1362. livenessTestSize,
  1363. runConfig.doBurstMonitor,
  1364. runConfig.doDestinationBytes,
  1365. runConfig.doLegacyDestinationBytes,
  1366. runConfig.applyPrefix,
  1367. runConfig.forceFragmenting,
  1368. "consistent",
  1369. enableDSLFetcher,
  1370. inproxyTacticsParametersJSON,
  1371. runConfig.doRestrictInproxy,
  1372. generateConfigParams.ProviderID)
  1373. }
  1374. p, _ := os.FindProcess(os.Getpid())
  1375. p.Signal(syscall.SIGUSR1)
  1376. // TODO: monitor logs for more robust wait-until-reloaded
  1377. time.Sleep(1 * time.Second)
  1378. // After reloading psinet, the new sponsorID/expectedHomepageURL
  1379. // should be active, as tested in the client "Homepage" notice
  1380. // handler below.
  1381. }
  1382. // Exercise server_load logging
  1383. p, _ := os.FindProcess(os.Getpid())
  1384. p.Signal(syscall.SIGUSR2)
  1385. timer := time.NewTimer(1 * time.Second)
  1386. select {
  1387. case <-serverLoadLog:
  1388. case <-timer.C:
  1389. t.Fatalf("missing server load log")
  1390. }
  1391. timer.Stop()
  1392. // reset client datastore
  1393. _ = os.RemoveAll(filepath.Join(testDataDirName, psiphon.PsiphonDataDirectoryName))
  1394. // configure client
  1395. values.SetSSHClientVersionsSpec(values.NewPickOneSpec(testSSHClientVersions))
  1396. values.SetUserAgentsSpec(values.NewPickOneSpec(testUserAgents))
  1397. // TODO: currently, TargetServerEntry only works with one tunnel
  1398. numTunnels := 1
  1399. localSOCKSProxyPort := 1081
  1400. localHTTPProxyPort := 8081
  1401. // Use a distinct suffix for network ID for each test run to ensure tactics
  1402. // from different runs don't apply; this is a workaround for the singleton
  1403. // datastore.
  1404. networkID := fmt.Sprintf("WIFI-%s", time.Now().String())
  1405. jsonNetworkID := fmt.Sprintf(`,"NetworkID" : "%s"`, networkID)
  1406. jsonLimitTLSProfiles := ""
  1407. if runConfig.tlsProfile != "" {
  1408. jsonLimitTLSProfiles = fmt.Sprintf(`,"LimitTLSProfiles" : ["%s"]`, runConfig.tlsProfile)
  1409. }
  1410. testClientFeaturesJSON, _ := json.Marshal(testClientFeatures)
  1411. clientTunnelProtocol := runConfig.tunnelProtocol
  1412. if runConfig.clientTunnelProtocol != "" {
  1413. clientTunnelProtocol = runConfig.clientTunnelProtocol
  1414. }
  1415. clientConfigJSON := fmt.Sprintf(`
  1416. {
  1417. "ClientVersion" : "%d",
  1418. "ClientPlatform" : "%s",
  1419. "ClientFeatures" : %s,
  1420. "SponsorId" : "0000000000000000",
  1421. "PropagationChannelId" : "0000000000000000",
  1422. "DeviceRegion" : "%s",
  1423. "DeviceLocation" : "%s",
  1424. "DisableRemoteServerListFetcher" : true,
  1425. "EstablishTunnelPausePeriodSeconds" : 1,
  1426. "ConnectionWorkerPoolSize" : %d,
  1427. "LimitTunnelProtocols" : ["%s"]
  1428. %s
  1429. %s
  1430. }`,
  1431. testClientVersion,
  1432. testClientPlatform,
  1433. string(testClientFeaturesJSON),
  1434. testDeviceRegion,
  1435. testDeviceLocation,
  1436. numTunnels,
  1437. clientTunnelProtocol,
  1438. jsonLimitTLSProfiles,
  1439. jsonNetworkID)
  1440. // Don't print initial config setup notices
  1441. err = psiphon.SetNoticeWriter(io.Discard)
  1442. if err != nil {
  1443. t.Fatalf("error setting notice writer: %s", err)
  1444. }
  1445. defer psiphon.ResetNoticeWriter()
  1446. clientConfig, err := psiphon.LoadConfig([]byte(clientConfigJSON))
  1447. if err != nil {
  1448. t.Fatalf("error processing configuration file: %s", err)
  1449. }
  1450. clientConfig.DataRootDirectory = testDataDirName
  1451. if !runConfig.doDefaultSponsorID {
  1452. clientConfig.SponsorId = sponsorID
  1453. }
  1454. clientConfig.PropagationChannelId = propagationChannelID
  1455. clientConfig.TunnelPoolSize = numTunnels
  1456. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  1457. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  1458. clientConfig.EmitSLOKs = true
  1459. clientConfig.EmitServerAlerts = true
  1460. // In the classic test path, TargetServerEntry is used to specify the
  1461. // server enrty. In the DSL test case, the server entry is fetched from
  1462. // the mock.DSL backend.
  1463. if !doDSL {
  1464. clientConfig.TargetServerEntry = string(encodedServerEntry)
  1465. }
  1466. // Exercise the WaitForNetworkConnectivity wired-up code path.
  1467. clientConfig.NetworkConnectivityChecker = &networkConnectivityChecker{}
  1468. if runConfig.inspectFlows {
  1469. trueVal := true
  1470. clientConfig.UpstreamProxyURL = fmt.Sprintf("socks5://%s", flowInspectorProxy.listener.Addr())
  1471. clientConfig.UpstreamProxyAllowAllServerEntrySources = &trueVal
  1472. }
  1473. if runConfig.doSplitTunnel {
  1474. clientConfig.SplitTunnelOwnRegion = true
  1475. }
  1476. if !runConfig.omitAuthorization {
  1477. clientConfig.Authorizations = []string{clientAuthorization}
  1478. }
  1479. // When using TLS-OSSH the test expects the server to log the fields
  1480. // tls_ossh_sni_server_name and tls_ossh_transformed_host_name, which are
  1481. // only shipped by the client when the host name is transformed.
  1482. if protocol.TunnelProtocolUsesTLSOSSH(clientTunnelProtocol) {
  1483. transformHostNameProbability := 1.0
  1484. clientConfig.TransformHostNameProbability = &transformHostNameProbability
  1485. clientConfig.CustomHostNameRegexes = []string{testCustomHostNameRegex}
  1486. customHostNameProbability := 1.0
  1487. clientConfig.CustomHostNameProbability = &customHostNameProbability
  1488. clientConfig.CustomHostNameLimitProtocols = []string{clientTunnelProtocol}
  1489. }
  1490. if runConfig.doSteeringIP {
  1491. if runConfig.tunnelProtocol != protocol.TUNNEL_PROTOCOL_FRONTED_MEEK {
  1492. t.Fatalf("steering IP test requires FRONTED-MEEK-OSSH")
  1493. }
  1494. protocol.SetFrontedMeekHTTPDialPortNumber(psiphonServerPort)
  1495. // Note that in an actual fronting deployment, the steering IP header
  1496. // is added to the HTTP request by the CDN and any ingress steering
  1497. // IP header would be stripped to avoid spoofing. To facilitate this
  1498. // test case, we just have the client add the steering IP header as
  1499. // if it were the CDN.
  1500. headers := make(http.Header)
  1501. headers.Set("X-Psiphon-Steering-Ip", testSteeringIP)
  1502. clientConfig.MeekAdditionalHeaders = headers
  1503. }
  1504. if runConfig.useLegacyAPIEncoding {
  1505. clientConfig.TargetAPIEncoding = protocol.PSIPHON_API_ENCODING_JSON
  1506. }
  1507. if doInproxy {
  1508. // Limitation: can't exercise DisableTunnels = true since the client
  1509. // is a singleton and so the single instance must act as both a
  1510. // client and proxy. This self-proxy scheme also requires setting
  1511. // InproxySkipAwaitFullyConnected.
  1512. clientConfig.DisableTunnels = false
  1513. clientConfig.InproxyEnableProxy = true
  1514. clientConfig.InproxySkipAwaitFullyConnected = true
  1515. clientConfig.InproxyProxySessionPrivateKey = inproxyTestConfig.proxySessionPrivateKey
  1516. clientConfig.InproxyMaxClients = 1
  1517. clientConfig.InproxyLimitUpstreamBytesPerSecond = 0
  1518. clientConfig.InproxyLimitDownstreamBytesPerSecond = 0
  1519. clientConfig.ServerEntrySignaturePublicKey = inproxyTestConfig.brokerServerEntrySignaturePublicKey
  1520. if runConfig.doPersonalPairing {
  1521. psiphon.SetAllowOverlappingPersonalCompartmentIDs(true)
  1522. defer psiphon.SetAllowOverlappingPersonalCompartmentIDs(false)
  1523. clientConfig.InproxyClientPersonalCompartmentID = inproxyTestConfig.personalCompartmentID
  1524. clientConfig.InproxyProxyPersonalCompartmentID = inproxyTestConfig.personalCompartmentID
  1525. }
  1526. // Simulate a CDN adding required HTTP headers by injecting them at
  1527. // the client.
  1528. headers := make(http.Header)
  1529. for name, value := range inproxyTestConfig.brokerMeekRequiredHeaders {
  1530. headers.Add(name, value)
  1531. }
  1532. clientConfig.MeekAdditionalHeaders = headers
  1533. // Configure the CAs required to verify the broker TLS certificate.
  1534. clientConfig.TrustedCACertificatesFilename = filepath.Join(testDataDirName, "rootCAs")
  1535. err = ioutil.WriteFile(
  1536. clientConfig.TrustedCACertificatesFilename,
  1537. []byte(inproxyTestConfig.brokerServerCertificate),
  1538. 0600)
  1539. if err != nil {
  1540. t.Fatalf("WriteFile failed: %s", err)
  1541. }
  1542. }
  1543. if runConfig.doUncompressedTactics {
  1544. compressTactics := false
  1545. clientConfig.CompressTactics = &compressTactics
  1546. }
  1547. err = clientConfig.Commit(false)
  1548. if err != nil {
  1549. t.Fatalf("error committing configuration file: %s", err)
  1550. }
  1551. if doClientTactics {
  1552. // Configure nonfunctional values that must be overridden by tactics.
  1553. applyParameters := make(map[string]interface{})
  1554. applyParameters[parameters.TunnelConnectTimeout] = "1s"
  1555. applyParameters[parameters.TunnelRateLimits] = common.RateLimits{WriteBytesPerSecond: 1}
  1556. err = clientConfig.SetParameters("", true, applyParameters)
  1557. if err != nil {
  1558. t.Fatalf("SetParameters failed: %s", err)
  1559. }
  1560. } else {
  1561. // Directly apply same parameters that would've come from tactics.
  1562. applyParameters := make(map[string]interface{})
  1563. if runConfig.applyPrefix {
  1564. if protocol.TunnelProtocolIsObfuscatedSSH(runConfig.tunnelProtocol) {
  1565. applyParameters[parameters.OSSHPrefixSpecs] = transforms.Specs{
  1566. "TEST": {{"", "\x00{200}"}},
  1567. }
  1568. applyParameters[parameters.OSSHPrefixScopedSpecNames] = transforms.ScopedSpecNames{
  1569. "": {"TEST"},
  1570. }
  1571. applyParameters[parameters.OSSHPrefixProbability] = 1.0
  1572. applyParameters[parameters.OSSHPrefixSplitMinDelay] = "10ms"
  1573. applyParameters[parameters.OSSHPrefixSplitMaxDelay] = "20ms"
  1574. applyParameters[parameters.OSSHPrefixEnableFragmentor] = runConfig.forceFragmenting
  1575. } else if protocol.TunnelProtocolUsesShadowsocks(runConfig.tunnelProtocol) {
  1576. applyParameters[parameters.ShadowsocksPrefixSpecs] = transforms.Specs{
  1577. "TEST": {{"", "\x00{16}"}},
  1578. }
  1579. applyParameters[parameters.ShadowsocksPrefixScopedSpecNames] = transforms.ScopedSpecNames{
  1580. "": {"TEST"},
  1581. }
  1582. applyParameters[parameters.ShadowsocksPrefixProbability] = 1.0
  1583. }
  1584. }
  1585. if runConfig.forceFragmenting {
  1586. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols{runConfig.tunnelProtocol}
  1587. applyParameters[parameters.FragmentorProbability] = 1.0
  1588. applyParameters[parameters.FragmentorMinTotalBytes] = 1000
  1589. applyParameters[parameters.FragmentorMaxTotalBytes] = 2000
  1590. applyParameters[parameters.FragmentorMinWriteBytes] = 1
  1591. applyParameters[parameters.FragmentorMaxWriteBytes] = 100
  1592. applyParameters[parameters.FragmentorMinDelay] = 1 * time.Millisecond
  1593. applyParameters[parameters.FragmentorMaxDelay] = 10 * time.Millisecond
  1594. }
  1595. if runConfig.forceLivenessTest {
  1596. applyParameters[parameters.InitialLivenessTest] = parameters.LivenessTestSpecs{
  1597. "": &parameters.LivenessTestSpec{
  1598. MinUpstreamBytes: livenessTestSize,
  1599. MaxUpstreamBytes: livenessTestSize,
  1600. MinDownstreamBytes: livenessTestSize,
  1601. MaxDownstreamBytes: livenessTestSize,
  1602. },
  1603. }
  1604. applyParameters[parameters.LivenessTest] = parameters.LivenessTestSpecs{
  1605. "": &parameters.LivenessTestSpec{
  1606. MinUpstreamBytes: livenessTestSize,
  1607. MaxUpstreamBytes: livenessTestSize,
  1608. MinDownstreamBytes: livenessTestSize,
  1609. MaxDownstreamBytes: livenessTestSize,
  1610. },
  1611. }
  1612. }
  1613. if runConfig.doPruneServerEntries {
  1614. applyParameters[parameters.PsiphonAPIStatusRequestShortPeriodMin] = 1 * time.Second
  1615. applyParameters[parameters.PsiphonAPIStatusRequestShortPeriodMax] = 1 * time.Second
  1616. if runConfig.checkPruneServerEntries {
  1617. // Set a low MaxSendBytes in order to exercise repeated check
  1618. // prune requests. Also set a short deadline for the
  1619. // subsequent status requests, as the default is minutes later.
  1620. applyParameters[parameters.CheckServerEntryTagsRepeatRatio] = 0.0001
  1621. applyParameters[parameters.CheckServerEntryTagsRepeatMinimum] = 0
  1622. applyParameters[parameters.CheckServerEntryTagsMaxSendBytes] =
  1623. (len(pruneServerEntryTestCases) / 2) * 43
  1624. applyParameters[parameters.PsiphonAPIStatusRequestPeriodMin] = 1 * time.Second
  1625. applyParameters[parameters.PsiphonAPIStatusRequestPeriodMax] = 1 * time.Second
  1626. } else {
  1627. // Force exercising the failed_tunnel prune code path.
  1628. applyParameters[parameters.CheckServerEntryTagsEnabled] = false
  1629. }
  1630. }
  1631. err = clientConfig.SetParameters("", false, applyParameters)
  1632. if err != nil {
  1633. t.Fatalf("SetParameters failed: %s", err)
  1634. }
  1635. }
  1636. // connect to server with client
  1637. err = psiphon.OpenDataStore(clientConfig)
  1638. if err != nil {
  1639. t.Fatalf("error initializing client datastore: %s", err)
  1640. }
  1641. defer psiphon.CloseDataStore()
  1642. // Test unique user counting cases.
  1643. var expectUniqueUser bool
  1644. switch lastConnectedUpdateCount % 3 {
  1645. case 0:
  1646. // Mock no last_connected.
  1647. psiphon.SetKeyValue("lastConnected", "")
  1648. expectUniqueUser = true
  1649. case 1:
  1650. // Mock previous day last_connected.
  1651. psiphon.SetKeyValue(
  1652. "lastConnected",
  1653. time.Now().UTC().AddDate(0, 0, -1).Truncate(1*time.Hour).Format(time.RFC3339))
  1654. expectUniqueUser = true
  1655. case 2:
  1656. // Mock same day last_connected.
  1657. psiphon.SetKeyValue(
  1658. "lastConnected",
  1659. time.Now().UTC().Add(-1*time.Minute).Truncate(1*time.Hour).Format(time.RFC3339))
  1660. expectUniqueUser = false
  1661. }
  1662. // Store prune server entry test server entries and failed tunnel records.
  1663. storePruneServerEntriesTest(
  1664. t, runConfig, testDataDirName, pruneServerEntryTestCases)
  1665. if doDSL {
  1666. // Set up SLOKs and server entries required for the DSL test.
  1667. err := configureDSLTestServerEntries(
  1668. dslTestConfig,
  1669. string(encodedServerEntry),
  1670. serverEntrySignaturePublicKey,
  1671. serverEntrySignaturePrivateKey)
  1672. if err != nil {
  1673. t.Fatalf("configureDSLTestServerEntries failed: %s", err)
  1674. }
  1675. }
  1676. controller, err := psiphon.NewController(clientConfig)
  1677. if err != nil {
  1678. t.Fatalf("error creating client controller: %s", err)
  1679. }
  1680. connectedServer := make(chan struct{}, 1)
  1681. inproxyActivity := make(chan struct{}, 1)
  1682. tunnelsEstablished := make(chan struct{}, 1)
  1683. homepageReceived := make(chan struct{}, 1)
  1684. slokSeeded := make(chan struct{}, 1)
  1685. numPruneNotices := 0
  1686. pruneServerEntriesNoticesEmitted := make(chan struct{}, 1)
  1687. serverAlertDisallowedNoticesEmitted := make(chan struct{}, 1)
  1688. untunneledPortForward := make(chan struct{}, 1)
  1689. discardTunnel := make(chan struct{}, 1)
  1690. tunneledDSLFetched := make(chan struct{}, 1)
  1691. psiphon.ResetNoticeWriter()
  1692. err = psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  1693. func(notice []byte) {
  1694. noticeType, payload, err := psiphon.GetNotice(notice)
  1695. if err != nil {
  1696. return
  1697. }
  1698. printNotice := false
  1699. switch noticeType {
  1700. case "ConnectedServer":
  1701. // Check that client connected with the expected protocol.
  1702. protocol := payload["protocol"].(string)
  1703. if protocol != clientTunnelProtocol {
  1704. // TODO: wrong goroutine for t.FatalNow()
  1705. t.Errorf("unexpected protocol: %s", protocol)
  1706. }
  1707. sendNotificationReceived(connectedServer)
  1708. case "Tunnels":
  1709. count := int(payload["count"].(float64))
  1710. if count >= numTunnels {
  1711. sendNotificationReceived(tunnelsEstablished)
  1712. }
  1713. case "Homepage":
  1714. homepageURL := payload["url"].(string)
  1715. if homepageURL != expectedHomepageURL {
  1716. // TODO: wrong goroutine for t.FatalNow()
  1717. t.Errorf("unexpected homepage: %s", homepageURL)
  1718. }
  1719. sendNotificationReceived(homepageReceived)
  1720. case "SLOKSeeded":
  1721. sendNotificationReceived(slokSeeded)
  1722. case "PruneServerEntry":
  1723. numPruneNotices += 1
  1724. if numPruneNotices == expectedNumPruneNotices {
  1725. sendNotificationReceived(pruneServerEntriesNoticesEmitted)
  1726. }
  1727. case "ServerAlert":
  1728. reason := payload["reason"].(string)
  1729. actionURLsPayload := payload["actionURLs"].([]interface{})
  1730. actionURLs := make([]string, len(actionURLsPayload))
  1731. for i, value := range actionURLsPayload {
  1732. actionURLs[i] = value.(string)
  1733. }
  1734. if reason == protocol.PSIPHON_API_ALERT_DISALLOWED_TRAFFIC &&
  1735. reflect.DeepEqual(actionURLs, testDisallowedTrafficAlertActionURLs) {
  1736. sendNotificationReceived(serverAlertDisallowedNoticesEmitted)
  1737. }
  1738. case "Untunneled":
  1739. sendNotificationReceived(untunneledPortForward)
  1740. case "InproxyProxyTotalActivity":
  1741. // This assumes that both non-zero bytes up and down are
  1742. // reported in at least same notice, although there's some
  1743. // unlikely chance it's only one or the other.
  1744. connectedClients := int(payload["connectedClients"].(float64))
  1745. bytesUp := int(payload["totalBytesUp"].(float64))
  1746. bytesDown := int(payload["totalBytesDown"].(float64))
  1747. if connectedClients == 1 && bytesUp > 0 && bytesDown > 0 {
  1748. sendNotificationReceived(inproxyActivity)
  1749. }
  1750. case "Info":
  1751. if strings.Contains(payload["message"].(string), "discard tunnel") {
  1752. sendNotificationReceived(discardTunnel)
  1753. }
  1754. if strings.HasPrefix(payload["message"].(string), "DSL: fetched server entries") {
  1755. tunneled := payload["tunneled"].(bool)
  1756. updated := int(payload["updated"].(float64))
  1757. if tunneled && updated > 0 {
  1758. err := checkExpectedDSLPendingPrioritizeDial(clientConfig, networkID)
  1759. if err != nil {
  1760. t.Fatalf("checkExpectedDSLPendingPrioritizeDial failed: %v", err)
  1761. }
  1762. sendNotificationReceived(tunneledDSLFetched)
  1763. }
  1764. }
  1765. }
  1766. if printNotice {
  1767. fmt.Printf("%s\n", string(notice))
  1768. }
  1769. }))
  1770. if err != nil {
  1771. t.Fatalf("error setting notice writer: %s", err)
  1772. }
  1773. defer psiphon.ResetNoticeWriter()
  1774. ctx, cancelFunc := context.WithCancel(context.Background())
  1775. controllerWaitGroup := new(sync.WaitGroup)
  1776. controllerWaitGroup.Add(1)
  1777. go func() {
  1778. defer controllerWaitGroup.Done()
  1779. controller.Run(ctx)
  1780. }()
  1781. stopClient := func() {
  1782. cancelFunc()
  1783. shutdownTimeout := time.NewTimer(20 * time.Second)
  1784. shutdownOk := make(chan struct{}, 1)
  1785. go func() {
  1786. controllerWaitGroup.Wait()
  1787. shutdownOk <- struct{}{}
  1788. }()
  1789. select {
  1790. case <-shutdownOk:
  1791. case <-shutdownTimeout.C:
  1792. t.Errorf("controller shutdown timeout exceeded")
  1793. }
  1794. }
  1795. // Stop client on early exits due to failure.
  1796. defer func() {
  1797. if stopClient != nil {
  1798. stopClient()
  1799. }
  1800. }()
  1801. // Test: tunnels must be established, and correct homepage
  1802. // must be received, within 30 seconds
  1803. timeoutSignal := make(chan struct{})
  1804. go func() {
  1805. timer := time.NewTimer(30 * time.Second)
  1806. <-timer.C
  1807. close(timeoutSignal)
  1808. }()
  1809. expectDiscardTunnel := runConfig.doRestrictInproxy
  1810. if expectDiscardTunnel {
  1811. waitOnNotification(t, discardTunnel, timeoutSignal, "discard tunnel timeout exceeded")
  1812. return
  1813. } else {
  1814. waitOnNotification(t, connectedServer, timeoutSignal, "connected server timeout exceeded")
  1815. if doInproxy {
  1816. waitOnNotification(t, inproxyActivity, timeoutSignal, "inproxy activity timeout exceeded")
  1817. }
  1818. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel established timeout exceeded")
  1819. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  1820. if doDSL {
  1821. waitOnNotification(t, tunneledDSLFetched, timeoutSignal, "tunneled DSL timeout exceeded")
  1822. }
  1823. // The tunnel connected, so the local last_connected has been updated.
  1824. lastConnectedUpdateCount += 1
  1825. }
  1826. if runConfig.doChangeBytesConfig {
  1827. if !runConfig.doDestinationBytes || !runConfig.doLegacyDestinationBytes {
  1828. t.Fatalf("invalid test configuration")
  1829. }
  1830. // Test: now that the client is connected, change the domain bytes and
  1831. // destination bytes configurations. No stats should be logged, even
  1832. // with an already connected client.
  1833. // Pave psinet without domain bytes; retain the same sponsor ID. The
  1834. // random homepage URLs will change, but this has no effect on the
  1835. // already connected client.
  1836. _, _ = pavePsinetDatabaseFile(
  1837. t, psinetFilename, sponsorID, runConfig.doDefaultSponsorID, false, psinetValidServerEntryTags, discoveryServers)
  1838. // Pave tactics without destination bytes.
  1839. paveTacticsConfigFile(
  1840. t,
  1841. tacticsConfigFilename,
  1842. tacticsRequestPublicKey,
  1843. tacticsRequestPrivateKey,
  1844. tacticsRequestObfuscatedKey,
  1845. tacticsTunnelProtocol,
  1846. propagationChannelID,
  1847. livenessTestSize,
  1848. runConfig.doBurstMonitor,
  1849. false,
  1850. false,
  1851. runConfig.applyPrefix,
  1852. runConfig.forceFragmenting,
  1853. "consistent",
  1854. enableDSLFetcher,
  1855. inproxyTacticsParametersJSON,
  1856. runConfig.doRestrictInproxy,
  1857. generateConfigParams.ProviderID)
  1858. p, _ := os.FindProcess(os.Getpid())
  1859. p.Signal(syscall.SIGUSR1)
  1860. // TODO: monitor logs for more robust wait-until-reloaded
  1861. time.Sleep(1 * time.Second)
  1862. }
  1863. expectTrafficFailure := runConfig.denyTrafficRules || (runConfig.omitAuthorization && runConfig.requireAuthorization)
  1864. if runConfig.doTunneledWebRequest {
  1865. // Test: tunneled web site fetch
  1866. err = makeTunneledWebRequest(
  1867. t, localHTTPProxyPort, mockWebServerURL, true, mockWebServerExpectedResponse)
  1868. if err == nil {
  1869. if expectTrafficFailure {
  1870. t.Fatalf("unexpected tunneled web request success")
  1871. }
  1872. } else {
  1873. if !expectTrafficFailure {
  1874. t.Fatalf("tunneled web request failed: %s", err)
  1875. }
  1876. }
  1877. }
  1878. if runConfig.doTunneledDomainRequest && !expectTrafficFailure {
  1879. // Test: tunneled web site fetch exercising the handleTCPChannel DNS
  1880. // resolver and cache
  1881. err = makeTunneledWebRequest(
  1882. t, localHTTPProxyPort, "https://psiphon.ca", false, "")
  1883. if err != nil {
  1884. t.Fatalf("tunneled web request failed: %s", err)
  1885. }
  1886. // Establish a second port forward to the same domain. The DNS
  1887. // resolution is expected to be cached. This is checked below via the
  1888. // dns_count reported in the server_load log.
  1889. err = makeTunneledWebRequest(
  1890. t, localHTTPProxyPort, "https://psiphon.ca", false, "")
  1891. if err != nil {
  1892. t.Fatalf("tunneled web request failed: %s", err)
  1893. }
  1894. }
  1895. if runConfig.doTunneledNTPRequest {
  1896. // Test: tunneled UDP packets
  1897. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  1898. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  1899. if err == nil {
  1900. if expectTrafficFailure {
  1901. t.Fatalf("unexpected tunneled NTP request success")
  1902. }
  1903. } else {
  1904. if !expectTrafficFailure {
  1905. t.Fatalf("tunneled NTP request failed: %s", err)
  1906. }
  1907. }
  1908. }
  1909. // Test: await SLOK payload or server alert notice
  1910. time.Sleep(1 * time.Second)
  1911. if !expectTrafficFailure {
  1912. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  1913. expected := expectedNumSLOKs
  1914. if doDSL {
  1915. expected += len(dslTestConfig.clientSLOKs)
  1916. }
  1917. numSLOKs := psiphon.CountSLOKs()
  1918. if numSLOKs != expected {
  1919. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  1920. }
  1921. } else {
  1922. // Note: in expectTrafficFailure case, timeoutSignal may have already fired.
  1923. waitOnNotification(t, serverAlertDisallowedNoticesEmitted, nil, "")
  1924. }
  1925. // Test: await expected prune server entry notices
  1926. //
  1927. // Note: will take up to PsiphonAPIStatusRequestShortPeriodMax to emit.
  1928. if expectedNumPruneNotices > 0 {
  1929. waitOnNotification(t, pruneServerEntriesNoticesEmitted, nil, "")
  1930. }
  1931. if runConfig.doDanglingTCPConn {
  1932. // Test: client that has established TCP connection but not completed
  1933. // any handshakes must not block/delay server shutdown
  1934. danglingConn, err := net.Dial(
  1935. "tcp", net.JoinHostPort(psiphonServerIPAddress, strconv.Itoa(psiphonServerPort)))
  1936. if err != nil {
  1937. t.Fatalf("TCP dial failed: %s", err)
  1938. }
  1939. defer danglingConn.Close()
  1940. }
  1941. // Test: check for split tunnel notice
  1942. if runConfig.doSplitTunnel {
  1943. if !runConfig.doTunneledWebRequest || expectTrafficFailure {
  1944. t.Fatalf("invalid test run configuration")
  1945. }
  1946. waitOnNotification(t, untunneledPortForward, nil, "")
  1947. } else {
  1948. // There should be no "Untunneled" notice. This check assumes that any
  1949. // unexpected Untunneled notice will have been delivered at this point,
  1950. // after the SLOK notice.
  1951. select {
  1952. case <-untunneledPortForward:
  1953. t.Fatalf("unexpected untunneled port forward")
  1954. default:
  1955. }
  1956. }
  1957. // Trigger server_load logging once more, to exercise
  1958. // sshClient.peakMetrics. As we don't have a reference to the server's
  1959. // Support struct, we can't invoke logServerLoad directly and there's a
  1960. // potential race between asynchronous logServerLoad invocation and
  1961. // client shutdown. For now, we sleep as a workaround.
  1962. p.Signal(syscall.SIGUSR2)
  1963. time.Sleep(1 * time.Second)
  1964. // Shutdown to ensure logs/notices are flushed
  1965. stopClient()
  1966. stopClient = nil
  1967. stopServer()
  1968. stopServer = nil
  1969. if runConfig.doLogProtobuf {
  1970. // Ensure logs are drained on the reader side.
  1971. readerShutdownCtx, readerShutdownCtxCancel :=
  1972. context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))
  1973. defer readerShutdownCtxCancel()
  1974. socketReader.Stop(readerShutdownCtx)
  1975. }
  1976. // Test: all expected server logs were emitted
  1977. // For in-proxy tunnel protocols, client BPF tactics are currently ignored and not applied by the 2nd hop.
  1978. expectClientBPFField := psiphon.ClientBPFEnabled() && doClientTactics && !protocol.TunnelProtocolUsesInproxy(runConfig.tunnelProtocol)
  1979. expectServerBPFField := ServerBPFEnabled() && protocol.TunnelProtocolIsDirect(runConfig.tunnelProtocol) && doServerTactics
  1980. expectServerPacketManipulationField := runConfig.doPacketManipulation
  1981. expectBurstFields := runConfig.doBurstMonitor
  1982. expectTCPPortForwardDial := (runConfig.doTunneledWebRequest || runConfig.doTunneledDomainRequest)
  1983. expectTCPDataTransfer := (runConfig.doTunneledWebRequest || runConfig.doTunneledDomainRequest) && !expectTrafficFailure && !runConfig.doSplitTunnel
  1984. expectDomainPortForward := runConfig.doTunneledDomainRequest
  1985. // Even with expectTrafficFailure, DNS port forwards will succeed
  1986. expectUDPDataTransfer := runConfig.doTunneledNTPRequest
  1987. expectQUICVersion := ""
  1988. if runConfig.limitQUICVersions {
  1989. expectQUICVersion = limitQUICVersions[0]
  1990. }
  1991. expectDestinationBytesFields := runConfig.doDestinationBytes && !runConfig.doChangeBytesConfig
  1992. expectLegacyDestinationBytesFields := runConfig.doLegacyDestinationBytes && !runConfig.doChangeBytesConfig
  1993. expectMeekHTTPVersion := ""
  1994. if protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol) {
  1995. if protocol.TunnelProtocolUsesFrontedMeek(runConfig.tunnelProtocol) {
  1996. expectMeekHTTPVersion = "HTTP/2.0"
  1997. } else {
  1998. expectMeekHTTPVersion = "HTTP/1.1"
  1999. }
  2000. }
  2001. expectServerEntryCount := 0
  2002. if doDSL || runConfig.doPruneServerEntries {
  2003. expectServerEntryCount = protocol.ServerEntryCountRoundingIncrement
  2004. }
  2005. expectDSLPrioritized := doDSL
  2006. // The client still reports zero domain_bytes when no port forwards are
  2007. // allowed (expectTrafficFailure).
  2008. //
  2009. // Limitation: this check is disabled in the in-proxy case since, in the
  2010. // self-proxy scheme, the proxy shuts down before the client can send its
  2011. // final status request.
  2012. expectDomainBytes := !runConfig.doChangeBytesConfig && !doInproxy
  2013. select {
  2014. case logFields := <-serverTunnelLog:
  2015. expectCheckServerEntryPruneCount := 0
  2016. if runConfig.checkPruneServerEntries {
  2017. expectCheckServerEntryPruneCount = expectedNumPruneNotices
  2018. }
  2019. err := checkExpectedServerTunnelLogFields(
  2020. runConfig,
  2021. propagationChannelID,
  2022. clientConfig.SponsorId,
  2023. doClientTactics,
  2024. expectClientBPFField,
  2025. expectServerBPFField,
  2026. expectServerPacketManipulationField,
  2027. expectBurstFields,
  2028. expectTCPPortForwardDial,
  2029. expectTCPDataTransfer,
  2030. expectUDPDataTransfer,
  2031. expectDomainPortForward,
  2032. expectQUICVersion,
  2033. expectDestinationBytesFields,
  2034. expectLegacyDestinationBytesFields,
  2035. passthroughAddress,
  2036. expectMeekHTTPVersion,
  2037. expectCheckServerEntryPruneCount,
  2038. expectServerEntryCount,
  2039. expectDSLPrioritized,
  2040. inproxyTestConfig,
  2041. logFields)
  2042. if err != nil {
  2043. t.Fatalf("invalid server tunnel log fields: %s", err)
  2044. }
  2045. default:
  2046. t.Fatalf("missing server tunnel log")
  2047. }
  2048. if expectUniqueUser {
  2049. select {
  2050. case logFields := <-uniqueUserLog:
  2051. err := checkExpectedUniqueUserLogFields(
  2052. runConfig,
  2053. logFields)
  2054. if err != nil {
  2055. t.Fatalf("invalid unique user log fields: %s", err)
  2056. }
  2057. default:
  2058. t.Fatalf("missing unique user log")
  2059. }
  2060. } else {
  2061. select {
  2062. case <-uniqueUserLog:
  2063. t.Fatalf("unexpected unique user log")
  2064. default:
  2065. }
  2066. }
  2067. if expectDomainBytes {
  2068. select {
  2069. case logFields := <-domainBytesLog:
  2070. err := checkExpectedDomainBytesLogFields(
  2071. runConfig,
  2072. logFields)
  2073. if err != nil {
  2074. t.Fatalf("invalid domain bytes log fields: %s", err)
  2075. }
  2076. default:
  2077. t.Fatalf("missing domain bytes log")
  2078. }
  2079. } else {
  2080. select {
  2081. case <-domainBytesLog:
  2082. t.Fatalf("unexpected domain bytes log")
  2083. default:
  2084. }
  2085. }
  2086. select {
  2087. case logFields := <-serverLoadLog:
  2088. if logFields["server_entry_tag"] == nil ||
  2089. fmt.Sprintf("%s", logFields["server_entry_tag"]) == "" {
  2090. t.Fatalf("missing server_entry_tag")
  2091. }
  2092. if expectDomainPortForward {
  2093. dnsCount := int(logFields["dns_count"].(map[string]any)["ALL"].(float64))
  2094. if dnsCount != 1 {
  2095. t.Fatalf("unexpected dns_count: %d", dnsCount)
  2096. }
  2097. }
  2098. default:
  2099. t.Fatalf("missing server load log")
  2100. }
  2101. // Check logs emitted by discovery.
  2102. var expectedDiscoveryStrategy []string
  2103. // Discovery emits 1 log on startup.
  2104. if doServerTactics {
  2105. expectedDiscoveryStrategy = append(expectedDiscoveryStrategy, "classic")
  2106. } else {
  2107. expectedDiscoveryStrategy = append(expectedDiscoveryStrategy, "consistent")
  2108. }
  2109. if runConfig.doHotReload {
  2110. if doServerTactics {
  2111. // Discovery emits 1 log when tactics are reloaded, which happens
  2112. // before the psinet database is reloaded.
  2113. expectedDiscoveryStrategy = append(expectedDiscoveryStrategy, "classic")
  2114. }
  2115. // Discovery emits 1 when the psinet database is reloaded.
  2116. expectedDiscoveryStrategy = append(expectedDiscoveryStrategy, "consistent")
  2117. }
  2118. for _, expectedStrategy := range expectedDiscoveryStrategy {
  2119. select {
  2120. case logFields := <-discoveryLog:
  2121. if strategy, ok := logFields["discovery_strategy"].(string); ok {
  2122. if strategy != expectedStrategy {
  2123. t.Fatalf("expected discovery strategy \"%s\"", expectedStrategy)
  2124. }
  2125. } else {
  2126. t.Fatalf("missing discovery_strategy field")
  2127. }
  2128. default:
  2129. t.Fatalf("missing discovery log")
  2130. }
  2131. }
  2132. // Check in-proxy broker logs. This check also confirms that the server
  2133. // proxy quality report request succeeded.
  2134. logChannels := []chan map[string]interface{}{
  2135. inproxyProxyAnnounceLog,
  2136. inproxyClientOfferLog,
  2137. inproxyProxyAnswerLog,
  2138. inproxyServerProxyQualityLog}
  2139. for _, logChannel := range logChannels {
  2140. // There's no proxy quality report in personal pairing mode.
  2141. expectLog := !(logChannel == inproxyServerProxyQualityLog && runConfig.doPersonalPairing)
  2142. if doInproxy && expectLog {
  2143. select {
  2144. case logFields := <-logChannel:
  2145. // Check that broker receives the correct fronting provider ID.
  2146. //
  2147. // TODO: check more fields
  2148. if logChannel == inproxyProxyAnnounceLog ||
  2149. logChannel == inproxyClientOfferLog ||
  2150. logChannel == inproxyServerProxyQualityLog {
  2151. fronting_provider_id, ok := logFields["fronting_provider_id"].(string)
  2152. if !ok || fronting_provider_id != inproxyTestConfig.brokerFrontingProviderID {
  2153. t.Errorf("unexpected inproxy_broker.fronting_provider_id")
  2154. }
  2155. }
  2156. default:
  2157. t.Fatalf("missing in-proxy broker log")
  2158. }
  2159. } else {
  2160. select {
  2161. case <-logChannel:
  2162. t.Fatalf("unexpected in-proxy broker log")
  2163. default:
  2164. }
  2165. }
  2166. }
  2167. // Emit a dummy DSL relay cached request log to check that the event is
  2168. // properly wired up in protobuf mode.
  2169. //
  2170. // Currently the DSL test here doesn't exercise relay cached requests; see
  2171. // common/dsl/dsl_test.go for unit test coverage.
  2172. CommonLogger(log).LogMetric("dsl_relay_get_server_entries", common.LogFields{})
  2173. // Check that datastore had retained/pruned server entries as expected.
  2174. checkPruneServerEntriesTest(t, runConfig, testDataDirName, pruneServerEntryTestCases)
  2175. // Inspect OSSH prefix flows, if applicable.
  2176. if runConfig.inspectFlows && runConfig.applyPrefix && protocol.TunnelProtocolIsObfuscatedSSH(runConfig.tunnelProtocol) {
  2177. flows := <-flowInspectorProxy.ch
  2178. serverFlows := flows[0]
  2179. clientFlows := flows[1]
  2180. expectedClientPrefix := bytes.Repeat([]byte{0x00}, 200)
  2181. expectedServerPrefix := bytes.Repeat([]byte{0x01}, 200)
  2182. if runConfig.forceFragmenting {
  2183. // Fragmentor was applied, so check for prefix in stream dump.
  2184. if !bytes.Equal(clientFlows.streamDump.Bytes()[:200], expectedClientPrefix) {
  2185. t.Fatal("client flow does not have expected prefix")
  2186. }
  2187. if !bytes.Equal(serverFlows.streamDump.Bytes()[:200], expectedServerPrefix) {
  2188. t.Fatal("server flow does not have expected prefix")
  2189. }
  2190. fragmentorMaxWriteBytes := 100
  2191. if len(clientFlows.flows[0].data) > fragmentorMaxWriteBytes {
  2192. t.Fatal("client flow was not fragmented")
  2193. }
  2194. if len(serverFlows.flows[0].data) > fragmentorMaxWriteBytes {
  2195. t.Fatal("server flow was not fragmented")
  2196. }
  2197. } else {
  2198. // Fragmentor was not applied, so check for prefix in first flow.
  2199. if !bytes.Equal(clientFlows.flows[0].data, expectedClientPrefix) {
  2200. t.Fatal("client flow does not have expected prefix")
  2201. }
  2202. if !bytes.Equal(serverFlows.flows[0].data, expectedServerPrefix) {
  2203. t.Fatal("server flow does not have expected prefix")
  2204. }
  2205. // Analyze time between prefix and next packet.
  2206. // client 10-20ms, 30-40ms for server with standard deviation of 2ms.
  2207. clientZtest := testSampleInUniformRange(clientFlows.flows[1].timeDelta.Microseconds(), 10000, 20000, 2000)
  2208. serverZtest := testSampleInUniformRange(serverFlows.flows[1].timeDelta.Microseconds(), 30000, 40000, 2000)
  2209. if !clientZtest {
  2210. t.Fatalf("client write delay after prefix too high: %f ms",
  2211. clientFlows.flows[1].timeDelta.Seconds()*1e3)
  2212. }
  2213. if !serverZtest {
  2214. t.Fatalf("server write delay after prefix too high: %f ms",
  2215. serverFlows.flows[1].timeDelta.Seconds()*1e3)
  2216. }
  2217. }
  2218. }
  2219. if runConfig.doSteeringIP {
  2220. // Access the unexported controller.steeringIPCache
  2221. controllerStruct := reflect.ValueOf(controller).Elem()
  2222. steeringIPCacheField := controllerStruct.FieldByName("steeringIPCache")
  2223. steeringIPCacheField = reflect.NewAt(
  2224. steeringIPCacheField.Type(), unsafe.Pointer(steeringIPCacheField.UnsafeAddr())).Elem()
  2225. steeringIPCache := steeringIPCacheField.Interface().(*lrucache.Cache)
  2226. if steeringIPCache.ItemCount() != 1 {
  2227. t.Fatalf("unexpected steering IP cache size: %d", steeringIPCache.ItemCount())
  2228. }
  2229. key := fmt.Sprintf(
  2230. "%s %s %s",
  2231. networkID,
  2232. generateConfigParams.FrontingProviderID,
  2233. runConfig.tunnelProtocol)
  2234. entry, ok := steeringIPCache.Get(key)
  2235. if !ok {
  2236. t.Fatalf("no entry for steering IP cache key: %s", key)
  2237. }
  2238. if entry.(string) != testSteeringIP {
  2239. t.Fatalf("unexpected cached steering IP: %v", entry)
  2240. }
  2241. }
  2242. err = checkExpectedDiscoveredServer(clientConfig, discoveryServers)
  2243. if err != nil {
  2244. t.Fatalf("error checking client discovered server: %v", err)
  2245. }
  2246. }
  2247. func sendNotificationReceived(c chan<- struct{}) {
  2248. select {
  2249. case c <- struct{}{}:
  2250. default:
  2251. }
  2252. }
  2253. func waitOnNotification(t *testing.T, c, timeoutSignal <-chan struct{}, timeoutMessage string) {
  2254. if timeoutSignal == nil {
  2255. <-c
  2256. } else {
  2257. select {
  2258. case <-c:
  2259. case <-timeoutSignal:
  2260. t.Fatal(timeoutMessage)
  2261. }
  2262. }
  2263. }
  2264. type networkConnectivityChecker struct {
  2265. }
  2266. func (c *networkConnectivityChecker) HasNetworkConnectivity() int {
  2267. return 1
  2268. }
  2269. func protoToLogFields(msg proto.Message, logFields map[string]interface{}, runConfig *runServerConfig) {
  2270. r := msg.ProtoReflect()
  2271. md := r.Descriptor()
  2272. fds := md.Fields()
  2273. getMetricType := func(m *pb.Psiphond) string {
  2274. md := m.ProtoReflect().Descriptor()
  2275. populatedMetric := m.ProtoReflect().WhichOneof(
  2276. md.Oneofs().ByName("metric"),
  2277. )
  2278. return populatedMetric.TextName()
  2279. }
  2280. shouldSkipField := func(fd protoreflect.FieldDescriptor) bool {
  2281. if r.Has(fd) {
  2282. return false
  2283. }
  2284. // Never skip these fields, even if unset
  2285. if slices.Contains([]string{"last_connected"}, fd.TextName()) {
  2286. return false
  2287. }
  2288. return true
  2289. }
  2290. if logFields == nil {
  2291. logFields = map[string]interface{}{}
  2292. }
  2293. if _, ok := logFields["event_name"]; !ok {
  2294. logFields["event_name"] = getMetricType(msg.(*pb.Psiphond))
  2295. }
  2296. for i := range fds.Len() {
  2297. fd := fds.Get(i)
  2298. fieldValue := r.Get(fd)
  2299. if shouldSkipField(fd) {
  2300. continue
  2301. }
  2302. switch fd.Kind() {
  2303. case protoreflect.MessageKind:
  2304. switch fieldValue.Message().Interface().(type) {
  2305. case *timestamppb.Timestamp:
  2306. if fieldValue.Message().IsValid() {
  2307. ts := fieldValue.Message().Interface().(*timestamppb.Timestamp)
  2308. logFields[fd.TextName()] = ts.AsTime()
  2309. } else {
  2310. logFields[fd.TextName()] = "None"
  2311. }
  2312. default:
  2313. if fieldValue.Message().IsValid() {
  2314. protoToLogFields(fieldValue.Message().Interface(), logFields, runConfig)
  2315. } else if fd.ContainingOneof() == nil {
  2316. protoToLogFields(fieldValue.Message().New().Interface(), logFields, runConfig)
  2317. }
  2318. }
  2319. default:
  2320. if fd.IsList() {
  2321. list := fieldValue.List()
  2322. switch fd.Kind() {
  2323. case protoreflect.StringKind:
  2324. result := make([]string, list.Len())
  2325. for i := 0; i < list.Len(); i++ {
  2326. result[i] = list.Get(i).String()
  2327. }
  2328. logFields[fd.TextName()] = result
  2329. }
  2330. } else {
  2331. logFields[fd.TextName()] = fieldValue.Interface()
  2332. }
  2333. }
  2334. }
  2335. }
  2336. var (
  2337. reassembledServerLoadLogFields map[string]interface{}
  2338. serverLoadLogComponentSequence []int
  2339. reassembledServerTunnelLogFields map[string]interface{}
  2340. serverTunnelComponentSequence []int
  2341. )
  2342. func resetReassembleServerLoadLogs(expectedProtocolLogs int) {
  2343. // For each runServer test run, the currently expected sequences are:
  2344. // - One server_load triggered at "Exercise server_load logging", with no
  2345. // server_load_protocol components.
  2346. // - A pair of server_loads at "Trigger server_load logging once more",
  2347. // with multiple server_load_protocol components, including "ALL"; one
  2348. // server_load has a region.
  2349. expectedProtocolLogs += 1 // for "ALL"
  2350. serverLoadLogComponentSequence = []int{
  2351. 2,
  2352. 2 + expectedProtocolLogs,
  2353. 2 + expectedProtocolLogs}
  2354. }
  2355. func resetReassembleServerTunnelLogs(expectedTunnelLogs int) {
  2356. serverTunnelComponentSequence = []int{expectedTunnelLogs}
  2357. reassembledServerTunnelLogFields = nil
  2358. }
  2359. func reassembleServerLoadLog(
  2360. eventName string,
  2361. reflectedLogFields map[string]interface{}) (map[string]interface{}, error) {
  2362. // Reassemble protobuf server_load components into a single set of fields
  2363. // compatible with the existing JSON log content checker.
  2364. if !strings.HasPrefix(eventName, "server_load") {
  2365. return nil, errors.TraceNew("unexpected non-server_load log")
  2366. }
  2367. i := 0
  2368. for ; i < len(serverLoadLogComponentSequence); i++ {
  2369. if serverLoadLogComponentSequence[i] > 0 {
  2370. break
  2371. }
  2372. }
  2373. if i >= len(serverLoadLogComponentSequence) {
  2374. return nil, errors.TraceNew("unexpected server_load sequence")
  2375. }
  2376. serverLoadLogComponentSequence[i] -= 1
  2377. sequenceComplete := serverLoadLogComponentSequence[i] == 0
  2378. if reassembledServerLoadLogFields == nil {
  2379. reassembledServerLoadLogFields = make(map[string]interface{})
  2380. }
  2381. serverLoadLogFields := reassembledServerLoadLogFields
  2382. switch eventName {
  2383. case "server_load":
  2384. for k, v := range reflectedLogFields {
  2385. serverLoadLogFields[k] = v
  2386. }
  2387. case "server_load_dns":
  2388. if serverLoadLogFields["dns_count"] == nil {
  2389. serverLoadLogFields["dns_count"] = make(map[string]interface{})
  2390. }
  2391. if serverLoadLogFields["dns_failed_count"] == nil {
  2392. serverLoadLogFields["dns_failed_count"] = make(map[string]interface{})
  2393. }
  2394. if serverLoadLogFields["dns_duration"] == nil {
  2395. serverLoadLogFields["dns_duration"] = make(map[string]interface{})
  2396. }
  2397. if serverLoadLogFields["dns_failed_duration"] == nil {
  2398. serverLoadLogFields["dns_failed_duration"] = make(map[string]interface{})
  2399. }
  2400. if dnsServer, ok := reflectedLogFields["dns_server"].(string); ok {
  2401. if dnsCount, ok := reflectedLogFields["dns_count"].(int64); ok {
  2402. serverLoadLogFields["dns_count"].(map[string]interface{})[dnsServer] = float64(dnsCount)
  2403. }
  2404. if dnsFailedCount, ok := reflectedLogFields["dns_failed_count"].(int64); ok {
  2405. serverLoadLogFields["dns_failed_count"].(map[string]interface{})[dnsServer] = float64(dnsFailedCount)
  2406. }
  2407. if dnsDuration, ok := reflectedLogFields["dns_duration"].(int64); ok {
  2408. serverLoadLogFields["dns_duration"].(map[string]interface{})[dnsServer] = float64(dnsDuration)
  2409. }
  2410. if dnsFailedDuration, ok := reflectedLogFields["dns_failed_duration"].(int64); ok {
  2411. serverLoadLogFields["dns_failed_duration"].(map[string]interface{})[dnsServer] = float64(dnsFailedDuration)
  2412. }
  2413. }
  2414. case "server_load_protocol":
  2415. if protocol, ok := reflectedLogFields["protocol"].(string); ok {
  2416. if serverLoadLogFields[protocol] == nil {
  2417. serverLoadLogFields[protocol] = make(map[string]interface{})
  2418. }
  2419. protocolMap := serverLoadLogFields[protocol].(map[string]interface{})
  2420. if acceptedClients, ok := reflectedLogFields["accepted_clients"].(int64); ok {
  2421. protocolMap["accepted_clients"] = acceptedClients
  2422. }
  2423. if establishedClients, ok := reflectedLogFields["established_clients"].(int64); ok {
  2424. protocolMap["established_clients"] = establishedClients
  2425. }
  2426. }
  2427. }
  2428. if sequenceComplete {
  2429. return serverLoadLogFields, nil
  2430. }
  2431. return nil, nil
  2432. }
  2433. func reassembleServerTunnelLog(
  2434. eventName string,
  2435. reflectedLogFields map[string]interface{}) (map[string]interface{}, error) {
  2436. // Reassemble protobuf server_tunnel components into a single set of fields
  2437. // compatible with the existing JSON log content checker.
  2438. if !strings.HasPrefix(eventName, "server_tunnel") {
  2439. return nil, errors.TraceNew("unexpected non-server_tunnel log")
  2440. }
  2441. i := 0
  2442. for ; i < len(serverTunnelComponentSequence); i++ {
  2443. if serverTunnelComponentSequence[i] > 0 {
  2444. break
  2445. }
  2446. }
  2447. if i >= len(serverTunnelComponentSequence) {
  2448. return nil, errors.TraceNew("unexpected server_tunnel sequence")
  2449. }
  2450. serverTunnelComponentSequence[i] -= 1
  2451. sequenceComplete := serverTunnelComponentSequence[i] == 0
  2452. if reassembledServerTunnelLogFields == nil {
  2453. reassembledServerTunnelLogFields = make(map[string]interface{})
  2454. }
  2455. serverTunnelLogFields := reassembledServerTunnelLogFields
  2456. switch eventName {
  2457. case "server_tunnel":
  2458. // Base server_tunnel message - copy all fields
  2459. for k, v := range reflectedLogFields {
  2460. serverTunnelLogFields[k] = v
  2461. }
  2462. case "server_tunnel_asn_dest_bytes":
  2463. // Initialize ASN byte maps if they don't exist
  2464. if serverTunnelLogFields["asn_dest_bytes"] == nil {
  2465. serverTunnelLogFields["asn_dest_bytes"] = make(map[string]interface{})
  2466. }
  2467. if serverTunnelLogFields["asn_dest_bytes_up_tcp"] == nil {
  2468. serverTunnelLogFields["asn_dest_bytes_up_tcp"] = make(map[string]interface{})
  2469. }
  2470. if serverTunnelLogFields["asn_dest_bytes_down_tcp"] == nil {
  2471. serverTunnelLogFields["asn_dest_bytes_down_tcp"] = make(map[string]interface{})
  2472. }
  2473. if serverTunnelLogFields["asn_dest_bytes_up_udp"] == nil {
  2474. serverTunnelLogFields["asn_dest_bytes_up_udp"] = make(map[string]interface{})
  2475. }
  2476. if serverTunnelLogFields["asn_dest_bytes_down_udp"] == nil {
  2477. serverTunnelLogFields["asn_dest_bytes_down_udp"] = make(map[string]interface{})
  2478. }
  2479. // Populate ASN-specific byte counts
  2480. if destAsn, ok := reflectedLogFields["dest_asn"].(string); ok {
  2481. if destBytes, ok := reflectedLogFields["dest_bytes"].(int64); ok {
  2482. serverTunnelLogFields["asn_dest_bytes"].(map[string]interface{})[destAsn] = destBytes
  2483. }
  2484. if destBytesUpTcp, ok := reflectedLogFields["dest_bytes_up_tcp"].(int64); ok {
  2485. serverTunnelLogFields["asn_dest_bytes_up_tcp"].(map[string]interface{})[destAsn] = destBytesUpTcp
  2486. }
  2487. if destBytesDownTcp, ok := reflectedLogFields["dest_bytes_down_tcp"].(int64); ok {
  2488. serverTunnelLogFields["asn_dest_bytes_down_tcp"].(map[string]interface{})[destAsn] = destBytesDownTcp
  2489. }
  2490. if destBytesUpUdp, ok := reflectedLogFields["dest_bytes_up_udp"].(int64); ok {
  2491. serverTunnelLogFields["asn_dest_bytes_up_udp"].(map[string]interface{})[destAsn] = destBytesUpUdp
  2492. }
  2493. if destBytesDownUdp, ok := reflectedLogFields["dest_bytes_down_udp"].(int64); ok {
  2494. serverTunnelLogFields["asn_dest_bytes_down_udp"].(map[string]interface{})[destAsn] = destBytesDownUdp
  2495. }
  2496. }
  2497. default:
  2498. return nil, fmt.Errorf("unmatched server_tunnel event: %s", eventName)
  2499. }
  2500. if sequenceComplete {
  2501. serverTunnelLogFields["event_name"] = "server_tunnel"
  2502. return serverTunnelLogFields, nil
  2503. }
  2504. return nil, nil
  2505. }
  2506. func checkExpectedServerTunnelLogFields(
  2507. runConfig *runServerConfig,
  2508. expectPropagationChannelID string,
  2509. expectSponsorID string,
  2510. expectAppliedTacticsTag bool,
  2511. expectClientBPFField bool,
  2512. expectServerBPFField bool,
  2513. expectServerPacketManipulationField bool,
  2514. expectBurstFields bool,
  2515. expectTCPPortForwardDial bool,
  2516. expectTCPDataTransfer bool,
  2517. expectUDPDataTransfer bool,
  2518. expectDomainPortForward bool,
  2519. expectQUICVersion string,
  2520. expectDestinationBytesFields bool,
  2521. expectLegacyDestinationBytesFields bool,
  2522. expectPassthroughAddress *string,
  2523. expectMeekHTTPVersion string,
  2524. expectCheckServerEntryPruneCount int,
  2525. expectServerEntryCount int,
  2526. expectDSLPrioritized bool,
  2527. inproxyTestConfig *inproxyTestConfig,
  2528. fields map[string]interface{}) error {
  2529. // Limitations:
  2530. //
  2531. // - client_build_rev not set in test build (see common/buildinfo.go)
  2532. // - egress_region, upstream_proxy_type, upstream_proxy_custom_header_names not exercised in test
  2533. // - fronting_provider_id/meek_dial_ip_address/meek_resolved_ip_address only logged for FRONTED meek protocols
  2534. for _, name := range []string{
  2535. "host_id",
  2536. "server_entry_tag",
  2537. "tunnel_id",
  2538. "start_time",
  2539. "duration",
  2540. "session_id",
  2541. "is_first_tunnel_in_session",
  2542. "last_connected",
  2543. "establishment_duration",
  2544. "propagation_channel_id",
  2545. "sponsor_id",
  2546. "client_version",
  2547. "client_platform",
  2548. "client_features",
  2549. "relay_protocol",
  2550. "device_region",
  2551. "device_location",
  2552. "ssh_client_version",
  2553. "server_entry_region",
  2554. "server_entry_source",
  2555. "server_entry_timestamp",
  2556. "dial_port_number",
  2557. "is_replay",
  2558. "replay_ignored_change",
  2559. "dsl_prioritized",
  2560. "dial_duration",
  2561. "candidate_number",
  2562. "established_tunnels_count",
  2563. "network_latency_multiplier",
  2564. "network_type",
  2565. "bytes",
  2566. "ssh_protocol_bytes",
  2567. "ssh_protocol_bytes_overhead",
  2568. "server_entry_count",
  2569. // The test run ensures that logServerLoad is invoked while the client
  2570. // is connected, so the following must be logged.
  2571. "peak_concurrent_proximate_accepted_clients",
  2572. "peak_concurrent_proximate_established_clients",
  2573. } {
  2574. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2575. return fmt.Errorf("missing expected field '%s'", name)
  2576. }
  2577. }
  2578. appliedTacticsTag := len(fields[tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME].(string)) > 0
  2579. if expectAppliedTacticsTag != appliedTacticsTag {
  2580. return fmt.Errorf("unexpected applied_tactics_tag")
  2581. }
  2582. if fields["host_id"].(string) != "example-host-id" {
  2583. return fmt.Errorf("unexpected host_id '%s'", fields["host_id"])
  2584. }
  2585. if fields["propagation_channel_id"].(string) != expectPropagationChannelID {
  2586. return fmt.Errorf("unexpected propagation_channel_id '%s'", fields["propagation_channel_id"])
  2587. }
  2588. if fields["sponsor_id"].(string) != expectSponsorID {
  2589. return fmt.Errorf("unexpected sponsor_id '%s'", fields["sponsor_id"])
  2590. }
  2591. if int(fields["client_version"].(float64)) != testClientVersion {
  2592. return fmt.Errorf("unexpected client_version '%s'", fields["client_version"])
  2593. }
  2594. if fields["client_platform"].(string) != testClientPlatform {
  2595. return fmt.Errorf("unexpected client_platform '%s'", fields["client_platform"])
  2596. }
  2597. clientFeatures := fields["client_features"].([]interface{})
  2598. if len(clientFeatures) != len(testClientFeatures) {
  2599. return fmt.Errorf("unexpected client_features '%s'", fields["client_features"])
  2600. }
  2601. for i, feature := range testClientFeatures {
  2602. if clientFeatures[i].(string) != feature {
  2603. return fmt.Errorf("unexpected client_features '%s'", fields["client_features"])
  2604. }
  2605. }
  2606. tunnelProtocol := runConfig.tunnelProtocol
  2607. if runConfig.clientTunnelProtocol != "" {
  2608. // In cases such as UNFRONTED-HTTPS-OSSH/TLS-OSSH demux,
  2609. // runConfig.tunnelProtocol is the server listening protocol and
  2610. // runConfig.clientTunnelProtocol is the actual tunnel protocol.
  2611. tunnelProtocol = runConfig.clientTunnelProtocol
  2612. }
  2613. if fields["relay_protocol"].(string) != tunnelProtocol {
  2614. return fmt.Errorf("unexpected relay_protocol '%s'", fields["relay_protocol"])
  2615. }
  2616. if !common.Contains(testSSHClientVersions, fields["ssh_client_version"].(string)) {
  2617. return fmt.Errorf("unexpected ssh_client_version '%s'", fields["ssh_client_version"])
  2618. }
  2619. if fields["network_type"].(string) != testNetworkType {
  2620. return fmt.Errorf("unexpected network_type '%s'", fields["network_type"])
  2621. }
  2622. if !(fields["ssh_protocol_bytes"].(float64) > 0) {
  2623. return fmt.Errorf("unexpected zero ssh_protocol_bytes")
  2624. }
  2625. if !(fields["ssh_protocol_bytes"].(float64) > fields["bytes"].(float64)) {
  2626. return fmt.Errorf("unexpected ssh_protocol_bytes < bytes")
  2627. }
  2628. if fields["server_entry_count"].(float64) != float64(expectServerEntryCount) {
  2629. return fmt.Errorf("unexpected server_entry_count: '%d'",
  2630. int(fields["server_entry_count"].(float64)))
  2631. }
  2632. // With interruptions, timeouts, and retries in some tests, there may be
  2633. // more than one dangling accepted_client.
  2634. peakConcurrentProximateAcceptedClients :=
  2635. int(fields["peak_concurrent_proximate_accepted_clients"].(float64))
  2636. if peakConcurrentProximateAcceptedClients < 0 ||
  2637. peakConcurrentProximateAcceptedClients > 10 {
  2638. return fmt.Errorf(
  2639. "unexpected peak_concurrent_proximate_accepted_clients '%v'",
  2640. fields["peak_concurrent_proximate_accepted_clients"])
  2641. }
  2642. peakConcurrentProximateEstablishedClients :=
  2643. int(fields["peak_concurrent_proximate_established_clients"].(float64))
  2644. if peakConcurrentProximateEstablishedClients != 0 {
  2645. return fmt.Errorf(
  2646. "unexpected peak_concurrent_proximate_established_clients '%v'",
  2647. fields["peak_concurrent_proximate_established_clients"])
  2648. }
  2649. // In some negative test cases, no port forwards are attempted, in which
  2650. // case these fields are not logged.
  2651. if expectTCPDataTransfer {
  2652. if fields["peak_tcp_port_forward_failure_rate"] == nil {
  2653. return fmt.Errorf("missing expected field 'peak_tcp_port_forward_failure_rate'")
  2654. }
  2655. if fields["peak_tcp_port_forward_failure_rate"].(float64) != 0.0 {
  2656. return fmt.Errorf(
  2657. "unexpected peak_tcp_port_forward_failure_rate '%v'",
  2658. fields["peak_tcp_port_forward_failure_rate"])
  2659. }
  2660. if fields["peak_tcp_port_forward_failure_rate_sample_size"] == nil {
  2661. return fmt.Errorf("missing expected field 'peak_tcp_port_forward_failure_rate_sample_size'")
  2662. }
  2663. if fields["peak_tcp_port_forward_failure_rate_sample_size"].(float64) <= 0.0 {
  2664. return fmt.Errorf(
  2665. "unexpected peak_tcp_port_forward_failure_rate_sample_size '%v'",
  2666. fields["peak_tcp_port_forward_failure_rate_sample_size"])
  2667. }
  2668. } else {
  2669. if fields["peak_tcp_port_forward_failure_rate"] != nil {
  2670. return fmt.Errorf("unexpected field 'peak_tcp_port_forward_failure_rate'")
  2671. }
  2672. if fields["peak_tcp_port_forward_failure_rate_sample_size"] != nil {
  2673. return fmt.Errorf("unexpected field 'peak_tcp_port_forward_failure_rate_sample_size'")
  2674. }
  2675. }
  2676. if expectUDPDataTransfer || expectDomainPortForward {
  2677. if fields["peak_dns_failure_rate"] == nil {
  2678. return fmt.Errorf("missing expected field 'peak_dns_failure_rate'")
  2679. }
  2680. if fields["peak_dns_failure_rate"].(float64) != 0.0 {
  2681. return fmt.Errorf(
  2682. "unexpected peak_dns_failure_rate '%v'", fields["peak_dns_failure_rate"])
  2683. }
  2684. if fields["peak_dns_failure_rate_sample_size"] == nil {
  2685. return fmt.Errorf("missing expected field 'peak_dns_failure_rate_sample_size'")
  2686. }
  2687. if fields["peak_dns_failure_rate_sample_size"].(float64) <= 0.0 {
  2688. return fmt.Errorf(
  2689. "unexpected peak_dns_failure_rate_sample_size '%v'",
  2690. fields["peak_dns_failure_rate_sample_size"])
  2691. }
  2692. } else {
  2693. if fields["peak_dns_failure_rate"] != nil {
  2694. return fmt.Errorf("unexpected field 'peak_dns_failure_rate'")
  2695. }
  2696. if fields["peak_dns_failure_rate_sample_size"] != nil {
  2697. return fmt.Errorf("unexpected field 'peak_dns_failure_rate_sample_size'")
  2698. }
  2699. }
  2700. // TODO: the following cases should check that fields are not logged when
  2701. // not expected.
  2702. if runConfig.doSplitTunnel {
  2703. if fields["split_tunnel"] == nil {
  2704. return fmt.Errorf("missing expected field 'split_tunnel'")
  2705. }
  2706. if fields["split_tunnel"].(bool) != true {
  2707. return fmt.Errorf("missing split_tunnel value")
  2708. }
  2709. }
  2710. if protocol.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  2711. for _, name := range []string{
  2712. "padding",
  2713. "pad_response",
  2714. } {
  2715. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2716. return fmt.Errorf("missing expected field '%s'", name)
  2717. }
  2718. }
  2719. }
  2720. if protocol.TunnelProtocolUsesMeek(tunnelProtocol) {
  2721. for _, name := range []string{
  2722. "user_agent",
  2723. "meek_transformed_host_name",
  2724. "meek_cookie_size",
  2725. "meek_limit_request",
  2726. "meek_underlying_connection_count",
  2727. "meek_server_http_version",
  2728. } {
  2729. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2730. return fmt.Errorf("missing expected field '%s'", name)
  2731. }
  2732. }
  2733. if !common.Contains(testUserAgents, fields["user_agent"].(string)) {
  2734. return fmt.Errorf("unexpected user_agent '%s'", fields["user_agent"])
  2735. }
  2736. if fields["meek_server_http_version"].(string) != expectMeekHTTPVersion {
  2737. return fmt.Errorf("unexpected meek_server_http_version '%s'", fields["meek_server_http_version"])
  2738. }
  2739. }
  2740. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) {
  2741. for _, name := range []string{
  2742. "meek_host_header",
  2743. } {
  2744. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2745. return fmt.Errorf("missing expected field '%s'", name)
  2746. }
  2747. }
  2748. hostName := fields["meek_host_header"].(string)
  2749. dialPortNumber := int(fields["dial_port_number"].(float64))
  2750. if dialPortNumber != 80 {
  2751. hostName, _, _ = net.SplitHostPort(hostName)
  2752. }
  2753. if regexp.MustCompile(testCustomHostNameRegex).FindString(hostName) != hostName {
  2754. return fmt.Errorf("unexpected meek_host_header '%s'", fields["meek_host_header"])
  2755. }
  2756. if !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  2757. for _, name := range []string{
  2758. "meek_dial_ip_address",
  2759. "meek_resolved_ip_address",
  2760. } {
  2761. if fields[name] != nil {
  2762. return fmt.Errorf("unexpected field '%s'", name)
  2763. }
  2764. }
  2765. }
  2766. }
  2767. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  2768. for _, name := range []string{
  2769. "meek_tls_padding",
  2770. "meek_sni_server_name",
  2771. } {
  2772. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2773. return fmt.Errorf("missing expected field '%s'", name)
  2774. }
  2775. }
  2776. hostName := fields["meek_sni_server_name"].(string)
  2777. if regexp.MustCompile(testCustomHostNameRegex).FindString(hostName) != hostName {
  2778. return fmt.Errorf("unexpected meek_sni_server_name '%s'", fields["meek_sni_server_name"])
  2779. }
  2780. if !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  2781. for _, name := range []string{
  2782. "meek_dial_ip_address",
  2783. "meek_resolved_ip_address",
  2784. "meek_host_header",
  2785. } {
  2786. if fields[name] != nil {
  2787. return fmt.Errorf("unexpected field '%s'", name)
  2788. }
  2789. }
  2790. }
  2791. }
  2792. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) ||
  2793. protocol.TunnelProtocolUsesTLSOSSH(tunnelProtocol) {
  2794. for _, name := range []string{
  2795. "tls_profile",
  2796. "tls_version",
  2797. "tls_sent_ticket",
  2798. "tls_did_resume",
  2799. } {
  2800. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2801. return fmt.Errorf("missing expected field '%s'", name)
  2802. }
  2803. }
  2804. if !common.Contains(protocol.SupportedTLSProfiles, fields["tls_profile"].(string)) {
  2805. return fmt.Errorf("unexpected tls_profile '%s'", fields["tls_profile"])
  2806. }
  2807. tlsVersion := fields["tls_version"].(string)
  2808. if !strings.HasPrefix(tlsVersion, protocol.TLS_VERSION_12) &&
  2809. !strings.HasPrefix(tlsVersion, protocol.TLS_VERSION_13) {
  2810. return fmt.Errorf("unexpected tls_version '%s'", fields["tls_version"])
  2811. }
  2812. }
  2813. if protocol.TunnelProtocolUsesTLSOSSH(tunnelProtocol) {
  2814. for _, name := range []string{
  2815. "tls_padding",
  2816. "tls_ossh_sni_server_name",
  2817. "tls_ossh_transformed_host_name",
  2818. } {
  2819. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2820. return fmt.Errorf("missing expected field '%s'", name)
  2821. }
  2822. }
  2823. hostName := fields["tls_ossh_sni_server_name"].(string)
  2824. if regexp.MustCompile(testCustomHostNameRegex).FindString(hostName) != hostName {
  2825. return fmt.Errorf("unexpected tls_ossh_sni_server_name '%s'", fields["tls_ossh_sni_server_name"])
  2826. }
  2827. }
  2828. if protocol.TunnelProtocolUsesQUIC(tunnelProtocol) {
  2829. for _, name := range []string{
  2830. "quic_version",
  2831. "quic_dial_sni_address",
  2832. "quic_dial_early",
  2833. "quic_sent_ticket",
  2834. "quic_did_resume",
  2835. "quic_obfuscated_psk",
  2836. } {
  2837. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2838. return fmt.Errorf("missing expected field '%s'", name)
  2839. }
  2840. }
  2841. quicVersion := fields["quic_version"].(string)
  2842. if !common.Contains(protocol.SupportedQUICVersions, quicVersion) ||
  2843. (runConfig.limitQUICVersions && quicVersion != expectQUICVersion) {
  2844. return fmt.Errorf("unexpected quic_version '%s'", fields["quic_version"])
  2845. }
  2846. }
  2847. if protocol.TunnelProtocolUsesInproxy(tunnelProtocol) {
  2848. for _, name := range []string{
  2849. // Fields sent by the broker and populated via
  2850. // inproxy.ServerBrokerSessions.HandlePacket
  2851. "inproxy_broker_id",
  2852. "inproxy_connection_id",
  2853. "inproxy_proxy_id",
  2854. "inproxy_matched_common_compartments",
  2855. "inproxy_client_nat_type",
  2856. "inproxy_proxy_propagation_channel_id",
  2857. "inproxy_proxy_sponsor_id",
  2858. "inproxy_proxy_client_version",
  2859. "inproxy_proxy_client_platform",
  2860. "inproxy_proxy_client_features",
  2861. "inproxy_proxy_device_region",
  2862. "inproxy_proxy_device_location",
  2863. "inproxy_proxy_network_type",
  2864. "inproxy_proxy_protocol_version",
  2865. "inproxy_proxy_nat_type",
  2866. "inproxy_proxy_max_clients",
  2867. "inproxy_proxy_connecting_clients",
  2868. "inproxy_proxy_connected_clients",
  2869. "inproxy_proxy_limit_upstream_bytes_per_second",
  2870. "inproxy_proxy_limit_downstream_bytes_per_second",
  2871. "inproxy_proxy_peak_upstream_bytes_per_second",
  2872. "inproxy_proxy_peak_downstream_bytes_per_second",
  2873. "inproxy_proxy_is_priority",
  2874. // These ProxyMetrics fields are not populated in this test:
  2875. // "inproxy_proxy_client_build_rev",
  2876. // "inproxy_proxy_port_mapping_types",
  2877. // Fields sent by the client
  2878. "inproxy_broker_is_replay",
  2879. "inproxy_broker_is_reuse",
  2880. "inproxy_broker_transport",
  2881. "inproxy_broker_fronting_provider_id",
  2882. "inproxy_broker_dial_address",
  2883. "inproxy_broker_resolved_ip_address",
  2884. "inproxy_webrtc_randomize_dtls",
  2885. "inproxy_webrtc_use_media_streams",
  2886. "inproxy_webrtc_padded_messages_sent",
  2887. "inproxy_webrtc_padded_messages_received",
  2888. "inproxy_webrtc_decoy_messages_sent",
  2889. "inproxy_webrtc_decoy_messages_received",
  2890. "inproxy_dial_webrtc_ice_gathering_duration",
  2891. "inproxy_dial_broker_offer_duration",
  2892. "inproxy_dial_webrtc_connection_duration",
  2893. } {
  2894. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2895. return fmt.Errorf("missing expected field '%s'", name)
  2896. }
  2897. }
  2898. if fields["inproxy_broker_id"].(string) != inproxyTestConfig.brokerSessionPublicKeyCurve25519 {
  2899. return fmt.Errorf("unexpected inproxy_broker_id '%s'", fields["inproxy_broker_id"])
  2900. }
  2901. if fields["inproxy_proxy_id"].(string) != inproxyTestConfig.proxySessionPublicKeyCurve25519 {
  2902. return fmt.Errorf("unexpected inproxy_proxy_id '%s'", fields["inproxy_proxy_id"])
  2903. }
  2904. if fields["inproxy_matched_common_compartments"].(bool) != !runConfig.doPersonalPairing {
  2905. return fmt.Errorf("unexpected inproxy_matched_common_compartments '%s'", fields["inproxy_matched_common_compartments"])
  2906. }
  2907. if fields["inproxy_broker_fronting_provider_id"].(string) != inproxyTestConfig.brokerFrontingProviderID {
  2908. return fmt.Errorf("unexpected inproxy_broker_fronting_provider_id '%s'", fields["inproxy_broker_fronting_provider_id"])
  2909. }
  2910. // Check some fields from ProxyMetrics. Since the proxy and client are
  2911. // the same tunnel core instance, fields such as session_id are the
  2912. // same for both the client and the proxy.
  2913. if fields["inproxy_proxy_session_id"].(string) != fields["session_id"].(string) {
  2914. return fmt.Errorf("unexpected inproxy_proxy_session_id '%s'", fields["session_id"])
  2915. }
  2916. if fields["inproxy_proxy_propagation_channel_id"].(string) != expectPropagationChannelID {
  2917. return fmt.Errorf("unexpected inproxy_proxy_propagation_channel_id '%s'", fields["inproxy_proxy_propagation_channel_id"])
  2918. }
  2919. if fields["inproxy_proxy_sponsor_id"].(string) != expectSponsorID {
  2920. return fmt.Errorf("unexpected inproxy_proxy_sponsor_id '%s'", fields["inproxy_proxy_sponsor_id"])
  2921. }
  2922. if int(fields["inproxy_proxy_client_version"].(float64)) != testClientVersion {
  2923. return fmt.Errorf("unexpected inproxy_proxy_client_version '%s'", fields["inproxy_proxy_client_version"])
  2924. }
  2925. if fields["inproxy_proxy_client_platform"].(string) != testClientPlatform {
  2926. return fmt.Errorf("unexpected inproxy_proxy_client_platform '%s'", fields["inproxy_proxy_client_platform"])
  2927. }
  2928. clientFeatures := fields["inproxy_proxy_client_features"].([]interface{})
  2929. if len(clientFeatures) != len(testClientFeatures) {
  2930. return fmt.Errorf("unexpected inproxy_proxy_client_features '%s'", fields["inproxy_proxy_client_features"])
  2931. }
  2932. for i, feature := range testClientFeatures {
  2933. if clientFeatures[i].(string) != feature {
  2934. return fmt.Errorf("unexpected inproxy_proxy_client_features '%s'", fields["inproxy_proxy_client_features"])
  2935. }
  2936. }
  2937. if fields["inproxy_proxy_device_region"].(string) != testDeviceRegion {
  2938. return fmt.Errorf("unexpected inproxy_proxy_device_region '%s'", fields["inproxy_proxy_device_region"])
  2939. }
  2940. if fields["inproxy_proxy_device_location"].(string) != testDeviceLocation {
  2941. return fmt.Errorf("unexpected inproxy_proxy_device_location '%s'", fields["inproxy_proxy_device_location"])
  2942. }
  2943. if fields["inproxy_proxy_network_type"].(string) != testNetworkType {
  2944. return fmt.Errorf("unexpected inproxy_proxy_network_type '%s'", fields["inproxy_proxy_network_type"])
  2945. }
  2946. if fields["inproxy_webrtc_use_media_streams"].(bool) != runConfig.useInproxyMediaStreams {
  2947. return fmt.Errorf("unexpected inproxy_webrtc_use_media_streams '%v'", fields["inproxy_webrtc_use_media_streams"])
  2948. }
  2949. }
  2950. if runConfig.applyPrefix {
  2951. if protocol.TunnelProtocolIsObfuscatedSSH(runConfig.tunnelProtocol) {
  2952. if fields["ossh_prefix"] == nil || fmt.Sprintf("%s", fields["ossh_prefix"]) == "" {
  2953. return fmt.Errorf("missing expected field 'ossh_prefix'")
  2954. }
  2955. } else if protocol.TunnelProtocolUsesShadowsocks(runConfig.tunnelProtocol) {
  2956. if fields["shadowsocks_prefix"] == nil || fmt.Sprintf("%s", fields["shadowsocks_prefix"]) == "" {
  2957. return fmt.Errorf("missing expected field 'shadowsocks_prefix'")
  2958. }
  2959. }
  2960. }
  2961. if runConfig.forceFragmenting {
  2962. for _, name := range []string{
  2963. "upstream_bytes_fragmented",
  2964. "upstream_min_bytes_written",
  2965. "upstream_max_bytes_written",
  2966. "upstream_min_delayed",
  2967. "upstream_max_delayed",
  2968. } {
  2969. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2970. return fmt.Errorf("missing expected field '%s'", name)
  2971. }
  2972. }
  2973. }
  2974. if expectClientBPFField {
  2975. name := "client_bpf"
  2976. if fields[name] == nil {
  2977. return fmt.Errorf("missing expected field '%s'", name)
  2978. } else if fmt.Sprintf("%s", fields[name]) != "test-client-bpf" {
  2979. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  2980. }
  2981. }
  2982. if expectServerBPFField {
  2983. name := "server_bpf"
  2984. if fields[name] == nil {
  2985. return fmt.Errorf("missing expected field '%s'", name)
  2986. } else if fmt.Sprintf("%s", fields[name]) != "test-server-bpf" {
  2987. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  2988. }
  2989. }
  2990. if expectServerPacketManipulationField {
  2991. name := "server_packet_manipulation"
  2992. if fields[name] == nil {
  2993. return fmt.Errorf("missing expected field '%s'", name)
  2994. } else if fmt.Sprintf("%s", fields[name]) != "test-packetman-spec" {
  2995. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  2996. }
  2997. }
  2998. if expectBurstFields {
  2999. // common.TestBurstMonitoredConn covers inclusion of additional fields.
  3000. for _, name := range []string{
  3001. "burst_upstream_first_rate",
  3002. "burst_upstream_last_rate",
  3003. "burst_upstream_min_rate",
  3004. "burst_upstream_max_rate",
  3005. "burst_downstream_first_rate",
  3006. "burst_downstream_last_rate",
  3007. "burst_downstream_min_rate",
  3008. "burst_downstream_max_rate",
  3009. } {
  3010. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  3011. return fmt.Errorf("missing expected field '%s'", name)
  3012. }
  3013. }
  3014. }
  3015. var checkTCPMetric func(float64) bool
  3016. if expectTCPPortForwardDial {
  3017. checkTCPMetric = func(f float64) bool { return f > 0 }
  3018. } else {
  3019. checkTCPMetric = func(f float64) bool { return f == 0 }
  3020. }
  3021. for _, name := range []string{
  3022. "peak_concurrent_dialing_port_forward_count_tcp",
  3023. } {
  3024. if fields[name] == nil {
  3025. return fmt.Errorf("missing expected field '%s'", name)
  3026. }
  3027. if !checkTCPMetric(fields[name].(float64)) {
  3028. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  3029. }
  3030. }
  3031. if expectTCPDataTransfer {
  3032. checkTCPMetric = func(f float64) bool { return f > 0 }
  3033. } else {
  3034. checkTCPMetric = func(f float64) bool { return f == 0 }
  3035. }
  3036. for _, name := range []string{
  3037. "bytes_up_tcp",
  3038. "bytes_down_tcp",
  3039. "peak_concurrent_port_forward_count_tcp",
  3040. "total_port_forward_count_tcp",
  3041. } {
  3042. if fields[name] == nil {
  3043. return fmt.Errorf("missing expected field '%s'", name)
  3044. }
  3045. if !checkTCPMetric(fields[name].(float64)) {
  3046. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  3047. }
  3048. }
  3049. var checkUDPMetric func(float64) bool
  3050. if expectUDPDataTransfer {
  3051. checkUDPMetric = func(f float64) bool { return f > 0 }
  3052. } else {
  3053. checkUDPMetric = func(f float64) bool { return f == 0 }
  3054. }
  3055. for _, name := range []string{
  3056. "bytes_up_udp",
  3057. "bytes_down_udp",
  3058. "peak_concurrent_port_forward_count_udp",
  3059. "total_port_forward_count_udp",
  3060. "total_udpgw_channel_count",
  3061. } {
  3062. if fields[name] == nil {
  3063. return fmt.Errorf("missing expected field '%s'", name)
  3064. }
  3065. if !checkUDPMetric(fields[name].(float64)) {
  3066. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  3067. }
  3068. }
  3069. for _, name := range []string{
  3070. "asn_dest_bytes",
  3071. "asn_dest_bytes_up_tcp",
  3072. "asn_dest_bytes_down_tcp",
  3073. "asn_dest_bytes_up_udp",
  3074. "asn_dest_bytes_down_udp",
  3075. } {
  3076. if expectDestinationBytesFields && fields[name] == nil {
  3077. return fmt.Errorf("missing expected field '%s'", name)
  3078. } else if !expectDestinationBytesFields && fields[name] != nil {
  3079. return fmt.Errorf("unexpected field '%s'", name)
  3080. }
  3081. }
  3082. if expectDestinationBytesFields {
  3083. for _, pair := range [][]string{
  3084. {"asn_dest_bytes", "bytes"},
  3085. {"asn_dest_bytes_up_tcp", "bytes_up_tcp"},
  3086. {"asn_dest_bytes_down_tcp", "bytes_down_tcp"},
  3087. {"asn_dest_bytes_up_udp", "bytes_up_udp"},
  3088. {"asn_dest_bytes_down_udp", "bytes_down_udp"},
  3089. } {
  3090. if _, ok := fields[pair[0]].(map[string]any)[testGeoIPASN].(float64); !ok {
  3091. return fmt.Errorf("missing field entry %s: '%v'", pair[0], testGeoIPASN)
  3092. }
  3093. value0 := int64(fields[pair[0]].(map[string]any)[testGeoIPASN].(float64))
  3094. value1 := int64(fields[pair[1]].(float64))
  3095. ok := value0 == value1
  3096. if pair[0] == "asn_dest_bytes_up_udp" || pair[0] == "asn_dest_bytes_down_udp" || pair[0] == "asn_dest_bytes" {
  3097. // DNS requests are excluded from destination bytes counting
  3098. ok = value0 > 0 && value0 < value1
  3099. }
  3100. if !ok {
  3101. return fmt.Errorf("unexpected field value %s: %v != %v", pair[0], fields[pair[0]], fields[pair[1]])
  3102. }
  3103. }
  3104. }
  3105. for _, name := range []string{
  3106. "dest_bytes_asn",
  3107. "dest_bytes_up_tcp",
  3108. "dest_bytes_down_tcp",
  3109. "dest_bytes_up_udp",
  3110. "dest_bytes_down_udp",
  3111. "dest_bytes",
  3112. } {
  3113. if expectLegacyDestinationBytesFields && fields[name] == nil {
  3114. return fmt.Errorf("missing expected field '%s'", name)
  3115. } else if !expectLegacyDestinationBytesFields && fields[name] != nil {
  3116. return fmt.Errorf("unexpected field '%s'", name)
  3117. }
  3118. }
  3119. if expectLegacyDestinationBytesFields {
  3120. name := "dest_bytes_asn"
  3121. if fields[name].(string) != testGeoIPASN {
  3122. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  3123. }
  3124. for _, pair := range [][]string{
  3125. {"dest_bytes_up_tcp", "bytes_up_tcp"},
  3126. {"dest_bytes_down_tcp", "bytes_down_tcp"},
  3127. {"dest_bytes_up_udp", "bytes_up_udp"},
  3128. {"dest_bytes_down_udp", "bytes_down_udp"},
  3129. {"dest_bytes", "bytes"},
  3130. } {
  3131. value0 := int64(fields[pair[0]].(float64))
  3132. value1 := int64(fields[pair[1]].(float64))
  3133. ok := value0 == value1
  3134. if pair[0] == "dest_bytes_up_udp" || pair[0] == "dest_bytes_down_udp" || pair[0] == "dest_bytes" {
  3135. // DNS requests are excluded from destination bytes counting
  3136. ok = value0 > 0 && value0 < value1
  3137. }
  3138. if !ok {
  3139. return fmt.Errorf("unexpected field value %s: %v != %v", pair[0], fields[pair[0]], fields[pair[1]])
  3140. }
  3141. }
  3142. }
  3143. if expectPassthroughAddress != nil {
  3144. name := "passthrough_address"
  3145. if fields[name] == nil {
  3146. return fmt.Errorf("missing expected field '%s'", name)
  3147. }
  3148. if fields[name] != *expectPassthroughAddress {
  3149. return fmt.Errorf("unexpected field value %s: %v != %v", name, fields[name], *expectPassthroughAddress)
  3150. }
  3151. }
  3152. if runConfig.doLogHostProvider {
  3153. name := "provider"
  3154. if fields[name] == nil {
  3155. return fmt.Errorf("missing expected field '%s'", name)
  3156. } else if fmt.Sprintf("%s", fields[name]) != "example-host-provider" {
  3157. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  3158. }
  3159. } else {
  3160. name := "provider"
  3161. if fields[name] != nil {
  3162. return fmt.Errorf("unexpected field '%s'", name)
  3163. }
  3164. }
  3165. if runConfig.doSteeringIP {
  3166. name := "relayed_steering_ip"
  3167. if fields[name] == nil {
  3168. return fmt.Errorf("missing expected field '%s'", name)
  3169. }
  3170. if fields[name] != testSteeringIP {
  3171. return fmt.Errorf("unexpected field value %s: %v != %v", name, fields[name], testSteeringIP)
  3172. }
  3173. name = "steering_ip"
  3174. if fields[name] != nil {
  3175. return fmt.Errorf("unexpected field '%s'", name)
  3176. }
  3177. }
  3178. for _, name := range []string{
  3179. "request_check_server_entry_tags",
  3180. "checked_server_entry_tags",
  3181. "invalid_server_entry_tags",
  3182. } {
  3183. if expectCheckServerEntryPruneCount > 0 && fields[name] == nil {
  3184. return fmt.Errorf("missing expected field '%s'", name)
  3185. } else if expectCheckServerEntryPruneCount <= 0 && fields[name] != nil {
  3186. return fmt.Errorf("unexpected field '%s'", name)
  3187. }
  3188. }
  3189. if expectCheckServerEntryPruneCount > 0 {
  3190. name := "request_check_server_entry_tags"
  3191. if fields[name].(float64) < 2 {
  3192. return fmt.Errorf("unexpected field value %s: %v", name, fields[name])
  3193. }
  3194. name = "checked_server_entry_tags"
  3195. if fields[name].(float64) < 1 {
  3196. return fmt.Errorf("unexpected field value %s: %v", name, fields[name])
  3197. }
  3198. // invalid_server_entry_tags may exceed expectCheckServerEntryPruneCount,
  3199. // due to repeated requests and min prune age.
  3200. name = "invalid_server_entry_tags"
  3201. if int(fields[name].(float64)) < expectCheckServerEntryPruneCount {
  3202. return fmt.Errorf("unexpected field value %s: %v", name, fields[name])
  3203. }
  3204. }
  3205. if fields["dsl_prioritized"] != expectDSLPrioritized {
  3206. return fmt.Errorf("unexpected dsl_prioritized %v", fields["dsl_prioritized"])
  3207. }
  3208. return nil
  3209. }
  3210. func checkExpectedUniqueUserLogFields(
  3211. runConfig *runServerConfig,
  3212. fields map[string]interface{}) error {
  3213. for _, name := range []string{
  3214. "session_id",
  3215. "last_connected",
  3216. "propagation_channel_id",
  3217. "sponsor_id",
  3218. "client_platform",
  3219. "device_region",
  3220. "device_location",
  3221. } {
  3222. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  3223. return fmt.Errorf("missing expected field '%s'", name)
  3224. }
  3225. }
  3226. return nil
  3227. }
  3228. func checkExpectedDomainBytesLogFields(
  3229. runConfig *runServerConfig,
  3230. fields map[string]interface{}) error {
  3231. for _, name := range []string{
  3232. "session_id",
  3233. "propagation_channel_id",
  3234. "sponsor_id",
  3235. "client_platform",
  3236. "device_region",
  3237. "device_location",
  3238. "domain",
  3239. "bytes",
  3240. } {
  3241. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  3242. return fmt.Errorf("missing expected field '%s'", name)
  3243. }
  3244. if name == "domain" {
  3245. if fields[name].(string) != "ALL" && fields[name].(string) != "(OTHER)" {
  3246. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  3247. }
  3248. }
  3249. }
  3250. return nil
  3251. }
  3252. func checkExpectedDSLPendingPrioritizeDial(
  3253. clientConfig *psiphon.Config,
  3254. networkID string) error {
  3255. // The server entry discovered in the tunneled DSL request should have a
  3256. // DSLPendingPrioritizeDial placeholder.
  3257. dialParams, err := psiphon.GetDialParameters(
  3258. clientConfig, tunneledDSLServerEntryIPAddress, networkID)
  3259. if err != nil {
  3260. return errors.Trace(err)
  3261. }
  3262. if dialParams == nil ||
  3263. !dialParams.DSLPendingPrioritizeDial ||
  3264. dialParams.DSLPrioritizedDial {
  3265. return errors.TraceNew("unexpected server entry state")
  3266. }
  3267. return nil
  3268. }
  3269. func checkExpectedDiscoveredServer(
  3270. clientConfig *psiphon.Config,
  3271. discoveryServers []*psinet.DiscoveryServer) error {
  3272. discoveredServers := make(map[string]*protocol.ServerEntry)
  3273. // Otherwise NewServerEntryIterator only returns TargetServerEntry.
  3274. clientConfig.TargetServerEntry = ""
  3275. _, iterator, err := psiphon.NewServerEntryIterator(clientConfig)
  3276. if err != nil {
  3277. return errors.Trace(err)
  3278. }
  3279. defer iterator.Close()
  3280. for {
  3281. serverEntry, err := iterator.Next()
  3282. if err != nil {
  3283. return errors.Trace(err)
  3284. }
  3285. if serverEntry == nil {
  3286. break
  3287. }
  3288. discoveredServers[serverEntry.IpAddress] = serverEntry
  3289. }
  3290. foundOne := false
  3291. for _, server := range discoveryServers {
  3292. serverEntry, err := protocol.DecodeServerEntry(server.EncodedServerEntry, "", "")
  3293. if err != nil {
  3294. return errors.Trace(err)
  3295. }
  3296. if v, ok := discoveredServers[serverEntry.IpAddress]; ok {
  3297. if v.Tag == serverEntry.Tag {
  3298. foundOne = true
  3299. break
  3300. }
  3301. }
  3302. }
  3303. if !foundOne {
  3304. return errors.TraceNew("expected client to discover at least one server")
  3305. }
  3306. return nil
  3307. }
  3308. func makeTunneledWebRequest(
  3309. t *testing.T,
  3310. localHTTPProxyPort int,
  3311. requestURL string,
  3312. checkResponseBody bool,
  3313. expectedResponseBody string) error {
  3314. roundTripTimeout := 30 * time.Second
  3315. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  3316. if err != nil {
  3317. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  3318. }
  3319. httpClient := &http.Client{
  3320. Transport: &http.Transport{
  3321. Proxy: http.ProxyURL(proxyUrl),
  3322. },
  3323. Timeout: roundTripTimeout,
  3324. }
  3325. response, err := httpClient.Get(requestURL)
  3326. if err != nil {
  3327. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  3328. }
  3329. body, err := ioutil.ReadAll(response.Body)
  3330. if err != nil {
  3331. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  3332. }
  3333. response.Body.Close()
  3334. if checkResponseBody && string(body) != expectedResponseBody {
  3335. return fmt.Errorf("unexpected proxied HTTP response")
  3336. }
  3337. return nil
  3338. }
  3339. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  3340. timeout := 10 * time.Second
  3341. var err error
  3342. testHostnames := []string{"time.google.com", "time.nist.gov", "pool.ntp.org"}
  3343. indexes := prng.Perm(len(testHostnames))
  3344. for _, index := range indexes {
  3345. testHostname := testHostnames[index]
  3346. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  3347. if err == nil {
  3348. break
  3349. }
  3350. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  3351. }
  3352. return err
  3353. }
  3354. var nextUDPProxyPort = 7300
  3355. func makeTunneledNTPRequestAttempt(
  3356. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  3357. nextUDPProxyPort++
  3358. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  3359. if err != nil {
  3360. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  3361. }
  3362. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  3363. // handles it, and then terminates.
  3364. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  3365. if waitGroup != nil {
  3366. defer waitGroup.Done()
  3367. }
  3368. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  3369. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  3370. if err != nil {
  3371. t.Logf("ListenUDP for %s failed: %s", destination, err)
  3372. return
  3373. }
  3374. defer serverUDPConn.Close()
  3375. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  3376. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  3377. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  3378. buffer[udpgwPreambleSize:])
  3379. if err != nil {
  3380. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  3381. return
  3382. }
  3383. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  3384. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  3385. if err != nil {
  3386. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  3387. return
  3388. }
  3389. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  3390. if err != nil {
  3391. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  3392. return
  3393. }
  3394. defer socksTCPConn.Close()
  3395. flags := uint8(0)
  3396. if destinationPort == 53 {
  3397. flags = udpgwProtocolFlagDNS
  3398. }
  3399. err = writeUdpgwPreamble(
  3400. udpgwPreambleSize,
  3401. flags,
  3402. 0,
  3403. destinationIP,
  3404. destinationPort,
  3405. uint16(packetSize),
  3406. buffer)
  3407. if err != nil {
  3408. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  3409. return
  3410. }
  3411. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  3412. if err != nil {
  3413. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  3414. return
  3415. }
  3416. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  3417. if err != nil {
  3418. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  3419. return
  3420. }
  3421. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  3422. if err != nil {
  3423. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  3424. return
  3425. }
  3426. }
  3427. // Tunneled DNS request
  3428. waitGroup := new(sync.WaitGroup)
  3429. waitGroup.Add(1)
  3430. go localUDPProxy(
  3431. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  3432. 53,
  3433. waitGroup)
  3434. // TODO: properly synchronize with local UDP proxy startup
  3435. time.Sleep(1 * time.Second)
  3436. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  3437. if err != nil {
  3438. return fmt.Errorf("DialUDP failed: %s", err)
  3439. }
  3440. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  3441. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  3442. addrs, err := resolveIP(testHostname, clientUDPConn)
  3443. clientUDPConn.Close()
  3444. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  3445. err = std_errors.New("no address")
  3446. }
  3447. if err != nil {
  3448. return fmt.Errorf("resolveIP failed: %s", err)
  3449. }
  3450. waitGroup.Wait()
  3451. // Tunneled NTP request
  3452. waitGroup = new(sync.WaitGroup)
  3453. waitGroup.Add(1)
  3454. go localUDPProxy(
  3455. addrs[0][len(addrs[0])-4:],
  3456. 123,
  3457. waitGroup)
  3458. // TODO: properly synchronize with local UDP proxy startup
  3459. time.Sleep(1 * time.Second)
  3460. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  3461. if err != nil {
  3462. return fmt.Errorf("DialUDP failed: %s", err)
  3463. }
  3464. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  3465. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  3466. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  3467. ntpData := make([]byte, 48)
  3468. ntpData[0] = 3<<3 | 3
  3469. _, err = clientUDPConn.Write(ntpData)
  3470. if err != nil {
  3471. clientUDPConn.Close()
  3472. return fmt.Errorf("NTP Write failed: %s", err)
  3473. }
  3474. _, err = clientUDPConn.Read(ntpData)
  3475. if err != nil {
  3476. clientUDPConn.Close()
  3477. return fmt.Errorf("NTP Read failed: %s", err)
  3478. }
  3479. clientUDPConn.Close()
  3480. var sec, frac uint64
  3481. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  3482. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  3483. nsec := sec * 1e9
  3484. nsec += (frac * 1e9) >> 32
  3485. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  3486. now := time.Now()
  3487. diff := ntpNow.Sub(now)
  3488. if diff < 0 {
  3489. diff = -diff
  3490. }
  3491. if diff > 1*time.Minute {
  3492. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  3493. }
  3494. waitGroup.Wait()
  3495. return nil
  3496. }
  3497. func resolveIP(host string, conn net.Conn) (addrs []net.IP, err error) {
  3498. // Send the DNS query (A record only)
  3499. dnsConn := &dns.Conn{Conn: conn}
  3500. defer dnsConn.Close()
  3501. query := new(dns.Msg)
  3502. query.SetQuestion(dns.Fqdn(host), dns.TypeA)
  3503. query.RecursionDesired = true
  3504. dnsConn.WriteMsg(query)
  3505. // Process the response
  3506. response, err := dnsConn.ReadMsg()
  3507. if err == nil && response.MsgHdr.Id != query.MsgHdr.Id {
  3508. err = dns.ErrId
  3509. }
  3510. if err != nil {
  3511. return nil, errors.Trace(err)
  3512. }
  3513. addrs = make([]net.IP, 0)
  3514. for _, answer := range response.Answer {
  3515. if a, ok := answer.(*dns.A); ok {
  3516. addrs = append(addrs, a.A)
  3517. }
  3518. }
  3519. return addrs, nil
  3520. }
  3521. func pavePsinetDatabaseFile(
  3522. t *testing.T,
  3523. psinetFilename string,
  3524. sponsorID string,
  3525. useDefaultSponsorID bool,
  3526. doDomainBytes bool,
  3527. validServerEntryTags []string,
  3528. discoveryServers []*psinet.DiscoveryServer) (string, string) {
  3529. if sponsorID == "" {
  3530. sponsorID = strings.ToUpper(prng.HexString(8))
  3531. }
  3532. defaultSponsorID := ""
  3533. if useDefaultSponsorID {
  3534. defaultSponsorID = sponsorID
  3535. }
  3536. fakeDomain := prng.HexString(4)
  3537. fakePath := prng.HexString(4)
  3538. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  3539. discoverServersJSON, err := json.Marshal(discoveryServers)
  3540. if err != nil {
  3541. t.Fatalf("json.Marshal failed: %s\n", err)
  3542. }
  3543. psinetJSONFormat := `
  3544. {
  3545. "default_sponsor_id" : "%s",
  3546. "sponsors" : {
  3547. "%s" : {
  3548. %s
  3549. "home_pages" : {
  3550. "None" : [
  3551. {
  3552. "region" : null,
  3553. "url" : "%s"
  3554. }
  3555. ]
  3556. }
  3557. }
  3558. },
  3559. "default_alert_action_urls" : {
  3560. "%s" : %s
  3561. },
  3562. "valid_server_entry_tags" : {
  3563. %s
  3564. },
  3565. "discovery_servers" : %s
  3566. }
  3567. `
  3568. domainBytes := ""
  3569. if doDomainBytes {
  3570. domainBytes = `
  3571. "https_request_regexes" : [
  3572. {
  3573. "regex" : ".*",
  3574. "replace" : "ALL"
  3575. }
  3576. ],
  3577. `
  3578. }
  3579. actionURLsJSON, _ := json.Marshal(testDisallowedTrafficAlertActionURLs)
  3580. validServerEntryTagsJSON := ""
  3581. for _, serverEntryTag := range validServerEntryTags {
  3582. if len(validServerEntryTagsJSON) > 0 {
  3583. validServerEntryTagsJSON += ", "
  3584. }
  3585. validServerEntryTagsJSON += fmt.Sprintf("\"%s\" : true", serverEntryTag)
  3586. }
  3587. psinetJSON := fmt.Sprintf(
  3588. psinetJSONFormat,
  3589. defaultSponsorID,
  3590. sponsorID,
  3591. domainBytes,
  3592. expectedHomepageURL,
  3593. protocol.PSIPHON_API_ALERT_DISALLOWED_TRAFFIC,
  3594. actionURLsJSON,
  3595. validServerEntryTagsJSON,
  3596. discoverServersJSON)
  3597. err = ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  3598. if err != nil {
  3599. t.Fatalf("error paving psinet database file: %s", err)
  3600. }
  3601. return sponsorID, expectedHomepageURL
  3602. }
  3603. func paveTrafficRulesFile(
  3604. t *testing.T,
  3605. trafficRulesFilename string,
  3606. propagationChannelID string,
  3607. accessType string,
  3608. authorizationID string,
  3609. requireAuthorization bool,
  3610. deny bool,
  3611. livenessTestSize int) {
  3612. // Test both default and fast lookups
  3613. if intLookupThreshold != 10 {
  3614. t.Fatalf("unexpected intLookupThreshold")
  3615. }
  3616. TCPPorts := fmt.Sprintf("443, %s", mockWebServerPort)
  3617. UDPPorts := "53, 123, 10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008, 10009, 10010"
  3618. allowTCPPorts := TCPPorts
  3619. allowUDPPorts := UDPPorts
  3620. disallowTCPPorts := "1"
  3621. disallowUDPPorts := "1"
  3622. if deny {
  3623. allowTCPPorts = "1"
  3624. allowUDPPorts = "1"
  3625. disallowTCPPorts = TCPPorts
  3626. disallowUDPPorts = UDPPorts
  3627. }
  3628. authorizationFilterFormat := `,
  3629. "AuthorizedAccessTypes" : ["%s"],
  3630. "ActiveAuthorizationIDs" : ["%s"]
  3631. `
  3632. authorizationFilter := ""
  3633. if requireAuthorization {
  3634. authorizationFilter = fmt.Sprintf(
  3635. authorizationFilterFormat, accessType, authorizationID)
  3636. }
  3637. // Supports two traffic rule test cases:
  3638. //
  3639. // 1. no ports are allowed until after the filtered rule is applied
  3640. // 2. no required ports are allowed (deny = true)
  3641. trafficRulesJSONFormat := `
  3642. {
  3643. "DefaultRules" : {
  3644. "RateLimits" : {
  3645. "ReadBytesPerSecond": 16384,
  3646. "WriteBytesPerSecond": 16384,
  3647. "ReadUnthrottledBytes": %d,
  3648. "WriteUnthrottledBytes": %d
  3649. },
  3650. "AllowTCPPorts" : [1],
  3651. "AllowUDPPorts" : [1],
  3652. "MeekRateLimiterHistorySize" : 10,
  3653. "MeekRateLimiterThresholdSeconds" : 1,
  3654. "MeekRateLimiterGarbageCollectionTriggerCount" : 1,
  3655. "MeekRateLimiterReapHistoryFrequencySeconds" : 1,
  3656. "MeekRateLimiterRegions" : []
  3657. },
  3658. "FilteredRules" : [
  3659. {
  3660. "Filter" : {
  3661. "HandshakeParameters" : {
  3662. "propagation_channel_id" : ["%s"]
  3663. }%s
  3664. },
  3665. "Rules" : {
  3666. "RateLimits" : {
  3667. "ReadBytesPerSecond": 2097152,
  3668. "WriteBytesPerSecond": 2097152
  3669. },
  3670. "AllowTCPPorts" : [%s],
  3671. "AllowUDPPorts" : [%s],
  3672. "DisallowTCPPorts" : [%s],
  3673. "DisallowUDPPorts" : [%s]
  3674. }
  3675. }
  3676. ]
  3677. }
  3678. `
  3679. trafficRulesJSON := fmt.Sprintf(
  3680. trafficRulesJSONFormat,
  3681. livenessTestSize, livenessTestSize,
  3682. propagationChannelID, authorizationFilter,
  3683. allowTCPPorts, allowUDPPorts, disallowTCPPorts, disallowUDPPorts)
  3684. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  3685. if err != nil {
  3686. t.Fatalf("error paving traffic rules file: %s", err)
  3687. }
  3688. }
  3689. var expectedNumSLOKs = 3
  3690. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  3691. oslConfigJSONFormat := `
  3692. {
  3693. "Schemes" : [
  3694. {
  3695. "Epoch" : "%s",
  3696. "Regions" : [],
  3697. "PropagationChannelIDs" : ["%s"],
  3698. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  3699. "SeedSpecs" : [
  3700. {
  3701. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  3702. "UpstreamSubnets" : ["0.0.0.0/0"],
  3703. "Targets" :
  3704. {
  3705. "BytesRead" : 1,
  3706. "BytesWritten" : 1,
  3707. "PortForwardDurationNanoseconds" : 1
  3708. }
  3709. },
  3710. {
  3711. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  3712. "UpstreamSubnets" : ["0.0.0.0/0"],
  3713. "Targets" :
  3714. {
  3715. "BytesRead" : 1,
  3716. "BytesWritten" : 1,
  3717. "PortForwardDurationNanoseconds" : 1
  3718. }
  3719. }
  3720. ],
  3721. "SeedSpecThreshold" : 2,
  3722. "SeedPeriodNanoseconds" : 2592000000000000,
  3723. "SeedPeriodKeySplits": [
  3724. {
  3725. "Total": 2,
  3726. "Threshold": 2
  3727. }
  3728. ]
  3729. },
  3730. {
  3731. "Epoch" : "%s",
  3732. "Regions" : [],
  3733. "PropagationChannelIDs" : ["%s"],
  3734. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  3735. "SeedSpecs" : [
  3736. {
  3737. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  3738. "UpstreamSubnets" : ["0.0.0.0/0"],
  3739. "Targets" :
  3740. {
  3741. "BytesRead" : 1,
  3742. "BytesWritten" : 1,
  3743. "PortForwardDurationNanoseconds" : 1
  3744. }
  3745. }
  3746. ],
  3747. "SeedSpecThreshold" : 1,
  3748. "SeedPeriodNanoseconds" : 2592000000000000,
  3749. "SeedPeriodKeySplits": [
  3750. {
  3751. "Total": 1,
  3752. "Threshold": 1
  3753. }
  3754. ]
  3755. }
  3756. ]
  3757. }
  3758. `
  3759. propagationChannelID := strings.ToUpper(prng.HexString(8))
  3760. now := time.Now().UTC()
  3761. epoch := now.Truncate(720 * time.Hour)
  3762. epochStr := epoch.Format(time.RFC3339Nano)
  3763. oslConfigJSON := fmt.Sprintf(
  3764. oslConfigJSONFormat,
  3765. epochStr, propagationChannelID,
  3766. epochStr, propagationChannelID)
  3767. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  3768. if err != nil {
  3769. t.Fatalf("error paving osl config file: %s", err)
  3770. }
  3771. return propagationChannelID
  3772. }
  3773. func paveTacticsConfigFile(
  3774. t *testing.T,
  3775. tacticsConfigFilename string,
  3776. tacticsRequestPublicKey string,
  3777. tacticsRequestPrivateKey string,
  3778. tacticsRequestObfuscatedKey string,
  3779. tunnelProtocol string,
  3780. propagationChannelID string,
  3781. livenessTestSize int,
  3782. doBurstMonitor bool,
  3783. doDestinationBytes bool,
  3784. doLegacyDestinationBytes bool,
  3785. applyOsshPrefix bool,
  3786. enableOsshPrefixFragmenting bool,
  3787. discoveryStategy string,
  3788. enableDSLFetcher string,
  3789. inproxyParametersJSON string,
  3790. doRestrictAllInproxyProviderRegions bool,
  3791. providerID string) {
  3792. // Setting LimitTunnelProtocols passively exercises the
  3793. // server-side LimitTunnelProtocols enforcement.
  3794. tacticsConfigJSONFormat := `
  3795. {
  3796. "RequestPublicKey" : "%s",
  3797. "RequestPrivateKey" : "%s",
  3798. "RequestObfuscatedKey" : "%s",
  3799. "DefaultTactics" : {
  3800. "TTL" : "60s",
  3801. "Probability" : 1.0,
  3802. "Parameters" : {
  3803. %s
  3804. %s
  3805. %s
  3806. %s
  3807. %s
  3808. %s
  3809. "LimitTunnelProtocols" : ["%s"],
  3810. "FragmentorLimitProtocols" : ["%s"],
  3811. "FragmentorProbability" : 1.0,
  3812. "FragmentorMinTotalBytes" : 1000,
  3813. "FragmentorMaxTotalBytes" : 2000,
  3814. "FragmentorMinWriteBytes" : 1,
  3815. "FragmentorMaxWriteBytes" : 100,
  3816. "FragmentorMinDelay" : "1ms",
  3817. "FragmentorMaxDelay" : "10ms",
  3818. "FragmentorDownstreamLimitProtocols" : ["%s"],
  3819. "FragmentorDownstreamProbability" : 1.0,
  3820. "FragmentorDownstreamMinTotalBytes" : 1000,
  3821. "FragmentorDownstreamMaxTotalBytes" : 2000,
  3822. "FragmentorDownstreamMinWriteBytes" : 1,
  3823. "FragmentorDownstreamMaxWriteBytes" : 100,
  3824. "FragmentorDownstreamMinDelay" : "1ms",
  3825. "FragmentorDownstreamMaxDelay" : "10ms",
  3826. "LivenessTestMinUpstreamBytes" : %d,
  3827. "LivenessTestMaxUpstreamBytes" : %d,
  3828. "LivenessTestMinDownstreamBytes" : %d,
  3829. "LivenessTestMaxDownstreamBytes" : %d,
  3830. "BPFServerTCPProgram": {
  3831. "Name" : "test-server-bpf",
  3832. "Instructions" : [
  3833. {"Op": "RetConstant", "Args": {"Val": 65535}}]},
  3834. "BPFServerTCPProbability" : 1.0,
  3835. "BPFClientTCPProgram": {
  3836. "Name" : "test-client-bpf",
  3837. "Instructions" : [
  3838. {"Op": "RetConstant", "Args": {"Val": 65535}}]},
  3839. "BPFClientTCPProbability" : 1.0,
  3840. "ServerPacketManipulationSpecs" : [{"Name": "test-packetman-spec", "PacketSpecs": [["TCP-flags S"]]}],
  3841. "ServerPacketManipulationProbability" : 1.0,
  3842. "ServerProtocolPacketManipulations": {"All" : ["test-packetman-spec"]},
  3843. "ServerDiscoveryStrategy": "%s",
  3844. "EnableDSLFetcher": %s,
  3845. "DSLPrioritizeDialNewServerEntryProbability" : 1.0,
  3846. "DSLPrioritizeDialExistingServerEntryProbability" : 1.0,
  3847. "EstablishTunnelWorkTime" : "1s"
  3848. }
  3849. },
  3850. "FilteredTactics" : [
  3851. {
  3852. "Filter" : {
  3853. "APIParameters" : {"propagation_channel_id" : ["%s"]},
  3854. "SpeedTestRTTMilliseconds" : {
  3855. "Aggregation" : "Median",
  3856. "AtLeast" : 1
  3857. }
  3858. },
  3859. "Tactics" : {
  3860. "Parameters" : {
  3861. "TunnelConnectTimeout" : "20s",
  3862. "TunnelRateLimits" : {"WriteBytesPerSecond": 1000000},
  3863. "TransformHostNameProbability" : 1.0,
  3864. "PickUserAgentProbability" : 1.0,
  3865. "ApplicationParameters" : {
  3866. "AppFlag1" : true,
  3867. "AppConfig1" : {"Option1" : "A", "Option2" : "B"},
  3868. "AppSwitches1" : [1, 2, 3, 4]
  3869. },
  3870. "CustomHostNameRegexes": ["%s"],
  3871. "CustomHostNameProbability": 1.0,
  3872. "CustomHostNameLimitProtocols": ["%s"]
  3873. }
  3874. }
  3875. }
  3876. ]
  3877. }
  3878. `
  3879. burstParameters := ""
  3880. if doBurstMonitor {
  3881. burstParameters = `
  3882. "ServerBurstUpstreamDeadline" : "100ms",
  3883. "ServerBurstUpstreamTargetBytes" : 1000,
  3884. "ServerBurstDownstreamDeadline" : "100ms",
  3885. "ServerBurstDownstreamTargetBytes" : 100000,
  3886. "ClientBurstUpstreamDeadline" : "100ms",
  3887. "ClientBurstUpstreamTargetBytes" : 1000,
  3888. "ClientBurstDownstreamDeadline" : "100ms",
  3889. "ClientBurstDownstreamTargetBytes" : 100000,
  3890. `
  3891. }
  3892. destinationBytesParameters := ""
  3893. if doDestinationBytes {
  3894. destinationBytesParameters = fmt.Sprintf(`
  3895. "DestinationBytesMetricsASNs" : ["%s"],
  3896. `, testGeoIPASN)
  3897. }
  3898. legacyDestinationBytesParameters := ""
  3899. if doLegacyDestinationBytes {
  3900. legacyDestinationBytesParameters = fmt.Sprintf(`
  3901. "DestinationBytesMetricsASN" : "%s",
  3902. `, testGeoIPASN)
  3903. }
  3904. osshPrefix := ""
  3905. if applyOsshPrefix {
  3906. osshPrefix = fmt.Sprintf(`
  3907. "ServerOSSHPrefixSpecs": {
  3908. "TEST": [["", "\\x01{200}"]]
  3909. },
  3910. "OSSHPrefixSplitMinDelay": "30ms",
  3911. "OSSHPrefixSplitMaxDelay": "40ms",
  3912. "OSSHPrefixEnableFragmentor": %s,
  3913. `, strconv.FormatBool(enableOsshPrefixFragmenting))
  3914. }
  3915. restrictInproxyParameters := ""
  3916. if doRestrictAllInproxyProviderRegions {
  3917. restrictInproxyParameters = fmt.Sprintf(`
  3918. "RestrictInproxyProviderRegions": {"%s" : ["%s"]},
  3919. "RestrictInproxyProviderIDsServerProbability": 1.0,
  3920. `, providerID, testServerRegion)
  3921. }
  3922. tacticsConfigJSON := fmt.Sprintf(
  3923. tacticsConfigJSONFormat,
  3924. tacticsRequestPublicKey,
  3925. tacticsRequestPrivateKey,
  3926. tacticsRequestObfuscatedKey,
  3927. burstParameters,
  3928. destinationBytesParameters,
  3929. legacyDestinationBytesParameters,
  3930. osshPrefix,
  3931. inproxyParametersJSON,
  3932. restrictInproxyParameters,
  3933. tunnelProtocol,
  3934. tunnelProtocol,
  3935. tunnelProtocol,
  3936. livenessTestSize,
  3937. livenessTestSize,
  3938. livenessTestSize,
  3939. livenessTestSize,
  3940. discoveryStategy,
  3941. enableDSLFetcher,
  3942. propagationChannelID,
  3943. strings.ReplaceAll(testCustomHostNameRegex, `\`, `\\`),
  3944. tunnelProtocol)
  3945. err := ioutil.WriteFile(tacticsConfigFilename, []byte(tacticsConfigJSON), 0600)
  3946. if err != nil {
  3947. t.Fatalf("error paving tactics config file: %s", err)
  3948. }
  3949. }
  3950. func paveBlocklistFile(t *testing.T, blocklistFilename string) {
  3951. blocklistContent :=
  3952. "255.255.255.255,test-source,test-subject\n2001:db8:f75c::0951:58bc:ef22,test-source,test-subject\nexample.org,test-source,test-subject\n"
  3953. err := ioutil.WriteFile(blocklistFilename, []byte(blocklistContent), 0600)
  3954. if err != nil {
  3955. t.Fatalf("error paving blocklist file: %s", err)
  3956. }
  3957. }
  3958. type inproxyTestConfig struct {
  3959. tacticsParametersJSON string
  3960. addMeekServerForBroker bool
  3961. brokerIPAddress string
  3962. brokerPort int
  3963. brokerSessionPublicKey string
  3964. brokerSessionPublicKeyCurve25519 string
  3965. brokerSessionPrivateKey string
  3966. brokerObfuscationRootSecret string
  3967. brokerServerEntrySignaturePublicKey string
  3968. brokerFrontingProviderID string
  3969. brokerServerCertificate string
  3970. brokerServerPrivateKey string
  3971. brokerMeekRequiredHeaders map[string]string
  3972. proxySessionPublicKey string
  3973. proxySessionPublicKeyCurve25519 string
  3974. proxySessionPrivateKey string
  3975. personalCompartmentID string
  3976. }
  3977. func generateInproxyTestConfig(
  3978. addMeekServerForBroker bool,
  3979. doTargetBrokerSpecs bool,
  3980. brokerIPAddress string,
  3981. brokerPort int,
  3982. serverEntrySignaturePublicKey string,
  3983. useInproxyMediaStreams bool) (*inproxyTestConfig, error) {
  3984. // Generate in-proxy configuration.
  3985. //
  3986. // In this test, a single common compartment ID is issued to all clients;
  3987. // the test client will get it via tactics.
  3988. //
  3989. // Because of singletons in the Psiphon client, there can only be a single
  3990. // Psiphon client instance in this test process, and so it must act as
  3991. // it's own in-proxy proxy.
  3992. //
  3993. // To minimize external dependencies, STUN testing is disabled here; it is
  3994. // exercised in the common/inproxy package tests.
  3995. //
  3996. // InproxyBrokerAllowCommonASNMatching and
  3997. // InproxyBrokerAllowBogonWebRTCConnections must be set to true in the
  3998. // server/broker config, to allow matches with the same local network
  3999. // address. InproxyDisableIPv6ICECandidates is turned on, in tactics,
  4000. // since the test GeoIP database is IPv4-only (see paveGeoIPDatabaseFiles).
  4001. commonCompartmentID, err := inproxy.MakeID()
  4002. if err != nil {
  4003. return nil, errors.Trace(err)
  4004. }
  4005. commonCompartmentIDStr := commonCompartmentID.String()
  4006. personalCompartmentID, err := inproxy.MakeID()
  4007. if err != nil {
  4008. return nil, errors.Trace(err)
  4009. }
  4010. personalCompartmentIDStr := personalCompartmentID.String()
  4011. brokerSessionPrivateKey, err := inproxy.GenerateSessionPrivateKey()
  4012. if err != nil {
  4013. return nil, errors.Trace(err)
  4014. }
  4015. brokerSessionPrivateKeyStr := brokerSessionPrivateKey.String()
  4016. brokerSessionPublicKey, err := brokerSessionPrivateKey.GetPublicKey()
  4017. if err != nil {
  4018. return nil, errors.Trace(err)
  4019. }
  4020. brokerSessionPublicKeyStr := brokerSessionPublicKey.String()
  4021. brokerSessionPublicKeyCurve25519, err := brokerSessionPublicKey.ToCurve25519()
  4022. if err != nil {
  4023. return nil, errors.Trace(err)
  4024. }
  4025. brokerSessionPublicKeyCurve25519Str := brokerSessionPublicKeyCurve25519.String()
  4026. brokerRootObfuscationSecret, err := inproxy.GenerateRootObfuscationSecret()
  4027. if err != nil {
  4028. return nil, errors.Trace(err)
  4029. }
  4030. brokerRootObfuscationSecretStr := brokerRootObfuscationSecret.String()
  4031. brokerFrontingProviderID := strings.ToUpper(prng.HexString(8))
  4032. brokerFrontingHostName := values.GetHostName()
  4033. brokerServerCertificate, brokerServerPrivateKey, brokerVerifyPin, err :=
  4034. common.GenerateWebServerCertificate(brokerFrontingHostName)
  4035. if err != nil {
  4036. return nil, errors.Trace(err)
  4037. }
  4038. brokerMeekRequiredHeaders := map[string]string{"X-MeekRequiredHeader": prng.HexString(32)}
  4039. proxySessionPrivateKey, err := inproxy.GenerateSessionPrivateKey()
  4040. if err != nil {
  4041. return nil, errors.Trace(err)
  4042. }
  4043. proxySessionPrivateKeyStr := proxySessionPrivateKey.String()
  4044. proxySessionPublicKey, err := proxySessionPrivateKey.GetPublicKey()
  4045. if err != nil {
  4046. return nil, errors.Trace(err)
  4047. }
  4048. proxySessionPublicKeyStr := proxySessionPublicKey.String()
  4049. proxySessionPublicKeyCurve25519, err := proxySessionPublicKey.ToCurve25519()
  4050. if err != nil {
  4051. return nil, errors.Trace(err)
  4052. }
  4053. proxySessionPublicKeyCurve25519Str := proxySessionPublicKeyCurve25519.String()
  4054. address := net.JoinHostPort(brokerIPAddress, strconv.Itoa(brokerPort))
  4055. addressRegex := strings.ReplaceAll(address, ".", "\\\\.")
  4056. skipVerify := false
  4057. verifyServerName := brokerFrontingHostName
  4058. verifyPins := fmt.Sprintf("[\"%s\"]", brokerVerifyPin)
  4059. if prng.FlipCoin() {
  4060. skipVerify = true
  4061. verifyServerName = ""
  4062. verifyPins = "[]"
  4063. }
  4064. brokerSpecJSONFormat := `
  4065. {
  4066. "BrokerPublicKey": "%s",
  4067. "BrokerRootObfuscationSecret": "%s",
  4068. "BrokerFrontingSpecs": [{
  4069. "FrontingProviderID": "%s",
  4070. "Addresses": ["%s"],
  4071. "DisableSNI": true,
  4072. "SkipVerify": %v,
  4073. "VerifyServerName": "%s",
  4074. "VerifyPins": %s,
  4075. "Host": "%s"
  4076. }]
  4077. }
  4078. `
  4079. validBrokerSpecJSON := fmt.Sprintf(
  4080. brokerSpecJSONFormat,
  4081. brokerSessionPublicKeyStr,
  4082. brokerRootObfuscationSecretStr,
  4083. brokerFrontingProviderID,
  4084. addressRegex,
  4085. skipVerify,
  4086. verifyServerName,
  4087. verifyPins,
  4088. brokerFrontingHostName)
  4089. otherSessionPrivateKey, _ := inproxy.GenerateSessionPrivateKey()
  4090. otherSessionPublicKey, _ := otherSessionPrivateKey.GetPublicKey()
  4091. otherRootObfuscationSecret, _ := inproxy.GenerateRootObfuscationSecret()
  4092. invalidBrokerSpecJSON := fmt.Sprintf(
  4093. brokerSpecJSONFormat,
  4094. otherSessionPublicKey.String(),
  4095. otherRootObfuscationSecret.String(),
  4096. prng.HexString(16),
  4097. prng.HexString(16),
  4098. false,
  4099. prng.HexString(16),
  4100. fmt.Sprintf("[\"%s\"]", prng.HexString(16)),
  4101. prng.HexString(16))
  4102. validBrokerSpecsJSON := fmt.Sprintf("[%s]", validBrokerSpecJSON)
  4103. invalidBrokerSpecsJSON := fmt.Sprintf("[%s]", invalidBrokerSpecJSON)
  4104. allBrokerSpecsJSON := fmt.Sprintf("[%s, %s]", validBrokerSpecJSON, invalidBrokerSpecJSON)
  4105. var brokerSpecsJSON, proxyBrokerSpecsJSON, clientBrokerSpecsJSON string
  4106. if doTargetBrokerSpecs {
  4107. // invalidBrokerSpecsJSON should be ignored when specific proxy/client
  4108. // broker specs are set.
  4109. brokerSpecsJSON = invalidBrokerSpecsJSON
  4110. proxyBrokerSpecsJSON = validBrokerSpecsJSON
  4111. clientBrokerSpecsJSON = validBrokerSpecsJSON
  4112. } else {
  4113. brokerSpecsJSON = validBrokerSpecsJSON
  4114. proxyBrokerSpecsJSON = "[]"
  4115. clientBrokerSpecsJSON = "[]"
  4116. }
  4117. additionalHeaders := http.Header{}
  4118. for name, value := range brokerMeekRequiredHeaders {
  4119. additionalHeaders[name] = []string{value}
  4120. }
  4121. additionalHeadersJSONBytes, _ := json.Marshal(additionalHeaders)
  4122. additionalHeadersJSON := string(additionalHeadersJSONBytes)
  4123. maxRequestTimeoutsJSON := ""
  4124. if prng.FlipCoin() {
  4125. maxRequestTimeoutsJSONFormat := `
  4126. "InproxyFrontingProviderClientMaxRequestTimeouts": {"%s": "10s"},
  4127. "InproxyFrontingProviderServerMaxRequestTimeouts": {"%s": "5s"},
  4128. `
  4129. maxRequestTimeoutsJSON = fmt.Sprintf(
  4130. maxRequestTimeoutsJSONFormat,
  4131. brokerFrontingProviderID,
  4132. brokerFrontingProviderID)
  4133. }
  4134. tacticsParametersJSONFormat := `
  4135. "InproxyAllowProxy": true,
  4136. "InproxyAllowClient": true,
  4137. "InproxyAllowMatchByRegion": {"%s":["%s"]},
  4138. "InproxyAllowMatchByASN": {"%s":["%s"]},
  4139. "InproxyDisallowMatchByRegion": {"%s":["%s"]},
  4140. "InproxyDisallowMatchByASN": {"%s":["%s"]},
  4141. "InproxyTunnelProtocolSelectionProbability": 1.0,
  4142. "InproxyAllBrokerSpecs": %s,
  4143. "InproxyBrokerSpecs": %s,
  4144. "InproxyProxyBrokerSpecs": %s,
  4145. "InproxyClientBrokerSpecs": %s,
  4146. "InproxyAllCommonCompartmentIDs": ["%s"],
  4147. "InproxyCommonCompartmentIDs": ["%s"],
  4148. "InproxyClientDiscoverNATProbability": 0.0,
  4149. "InproxyDisableSTUN": true,
  4150. "InproxyDisablePortMapping": true,
  4151. "InproxyDisableIPv6ICECandidates": true,
  4152. "InproxyWebRTCMediaStreamsProbability": %s,
  4153. "InproxyEnableProxyQuality": true,
  4154. "InproxyProxyQualityTargetUpstreamBytes": 1,
  4155. "InproxyProxyQualityTargetDownstreamBytes": 1,
  4156. "InproxyProxyQualityTargetDuration": "1ns",
  4157. "InproxyProxyQualityReporterTrustedCACertificates": "%s",
  4158. "InproxyProxyQualityReporterAdditionalHeaders": %s,
  4159. "InproxyProxyQualityReporterRequestDelay": 0,
  4160. %s
  4161. `
  4162. mediaStreamsProbability := "0.0"
  4163. if useInproxyMediaStreams {
  4164. mediaStreamsProbability = "1.0"
  4165. }
  4166. tacticsParametersJSON := fmt.Sprintf(
  4167. tacticsParametersJSONFormat,
  4168. testGeoIPCountry, testGeoIPCountry,
  4169. testGeoIPASN, testGeoIPASN,
  4170. testGeoIPCountry, "_"+testGeoIPCountry,
  4171. testGeoIPASN, "_"+testGeoIPASN,
  4172. allBrokerSpecsJSON,
  4173. brokerSpecsJSON,
  4174. proxyBrokerSpecsJSON,
  4175. clientBrokerSpecsJSON,
  4176. commonCompartmentIDStr,
  4177. commonCompartmentIDStr,
  4178. mediaStreamsProbability,
  4179. strings.ReplaceAll(brokerServerCertificate, "\n", "\\n"),
  4180. additionalHeadersJSON,
  4181. maxRequestTimeoutsJSON)
  4182. config := &inproxyTestConfig{
  4183. tacticsParametersJSON: tacticsParametersJSON,
  4184. addMeekServerForBroker: addMeekServerForBroker,
  4185. brokerIPAddress: brokerIPAddress,
  4186. brokerPort: brokerPort,
  4187. brokerSessionPrivateKey: brokerSessionPrivateKeyStr,
  4188. brokerSessionPublicKey: brokerSessionPublicKeyStr,
  4189. brokerSessionPublicKeyCurve25519: brokerSessionPublicKeyCurve25519Str,
  4190. brokerObfuscationRootSecret: brokerRootObfuscationSecretStr,
  4191. brokerServerEntrySignaturePublicKey: serverEntrySignaturePublicKey,
  4192. brokerFrontingProviderID: brokerFrontingProviderID,
  4193. brokerServerCertificate: brokerServerCertificate,
  4194. brokerServerPrivateKey: brokerServerPrivateKey,
  4195. brokerMeekRequiredHeaders: brokerMeekRequiredHeaders,
  4196. proxySessionPublicKey: proxySessionPublicKeyStr,
  4197. proxySessionPublicKeyCurve25519: proxySessionPublicKeyCurve25519Str,
  4198. proxySessionPrivateKey: proxySessionPrivateKeyStr,
  4199. personalCompartmentID: personalCompartmentIDStr,
  4200. }
  4201. return config, nil
  4202. }
  4203. type dslTestConfig struct {
  4204. relayTLSConfig *testutils.TestDSLTLSConfig
  4205. relayCACertificatesFilename string
  4206. relayHostCertificateFilename string
  4207. relayHostKeyFilename string
  4208. oslPaveData []*osl.PaveData
  4209. clientSLOKs []*osl.SLOK
  4210. backend *testutils.TestDSLBackend
  4211. }
  4212. func generateDSLTestConfig() (*dslTestConfig, error) {
  4213. relayTLSConfig, err := testutils.NewTestDSLTLSConfig()
  4214. if err != nil {
  4215. return nil, errors.Trace(err)
  4216. }
  4217. relayCACertificatesFilename,
  4218. relayHostCertificateFilename,
  4219. relayHostKeyFilename,
  4220. err := relayTLSConfig.WriteRelayFiles(testDataDirName)
  4221. if err != nil {
  4222. return nil, errors.Trace(err)
  4223. }
  4224. oslPaveData, _, clientSLOKs, err :=
  4225. testutils.InitializeTestOSLPaveData()
  4226. if err != nil {
  4227. return nil, errors.Trace(err)
  4228. }
  4229. backend, err := testutils.NewTestDSLBackend(
  4230. dsl.NewBackendTestShim(),
  4231. relayTLSConfig,
  4232. "",
  4233. nil,
  4234. testHostID,
  4235. oslPaveData)
  4236. if err != nil {
  4237. return nil, errors.Trace(err)
  4238. }
  4239. config := &dslTestConfig{
  4240. relayTLSConfig: relayTLSConfig,
  4241. relayCACertificatesFilename: relayCACertificatesFilename,
  4242. relayHostCertificateFilename: relayHostCertificateFilename,
  4243. relayHostKeyFilename: relayHostKeyFilename,
  4244. oslPaveData: oslPaveData,
  4245. clientSLOKs: clientSLOKs,
  4246. backend: backend,
  4247. }
  4248. return config, nil
  4249. }
  4250. type pruneServerEntryTestCase struct {
  4251. IPAddress string
  4252. ExplicitTag bool
  4253. ExpectedTag string
  4254. LocalTimestamp string
  4255. PsinetValid bool
  4256. ExpectPrune bool
  4257. IsEmbedded bool
  4258. DialPort0 bool
  4259. ServerEntryFields protocol.ServerEntryFields
  4260. }
  4261. func initializePruneServerEntriesTest(
  4262. t *testing.T,
  4263. runConfig *runServerConfig) ([]*pruneServerEntryTestCase, []string, int) {
  4264. if !runConfig.doPruneServerEntries {
  4265. return nil, nil, 0
  4266. }
  4267. newTimeStamp := time.Now().UTC().Format(time.RFC3339)
  4268. oldTimeStamp := time.Now().Add(-30 * 24 * time.Hour).UTC().Format(time.RFC3339)
  4269. // Test Cases:
  4270. // - ExplicitTag: server entry includes a tag; vs. generate a derived tag
  4271. // - LocalTimestamp: server entry is sufficiently old to be pruned; vs. not
  4272. // - PsinetValid: server entry is reported valid by psinet; vs. deleted
  4273. // - ExpectPrune: prune outcome based on flags above
  4274. // - IsEmbedded: pruned embedded server entries leave a tombstone and cannot
  4275. // be reimported
  4276. // - DialPort0: set dial port to 0, a special prune case (see statusAPIRequestHandler)
  4277. pruneServerEntryTestCases := []*pruneServerEntryTestCase{
  4278. {IPAddress: "192.0.2.1", ExplicitTag: true, LocalTimestamp: newTimeStamp, PsinetValid: true, ExpectPrune: false},
  4279. {IPAddress: "192.0.2.2", ExplicitTag: false, LocalTimestamp: newTimeStamp, PsinetValid: true, ExpectPrune: false},
  4280. {IPAddress: "192.0.2.3", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: false},
  4281. {IPAddress: "192.0.2.4", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: false},
  4282. {IPAddress: "192.0.2.5", ExplicitTag: true, LocalTimestamp: newTimeStamp, PsinetValid: false, ExpectPrune: false},
  4283. {IPAddress: "192.0.2.6", ExplicitTag: false, LocalTimestamp: newTimeStamp, PsinetValid: false, ExpectPrune: false},
  4284. {IPAddress: "192.0.2.7", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: false},
  4285. {IPAddress: "192.0.2.8", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: false},
  4286. {IPAddress: "192.0.2.9", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: true},
  4287. {IPAddress: "192.0.2.10", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: true},
  4288. {IPAddress: "192.0.2.11", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: false, DialPort0: true},
  4289. {IPAddress: "192.0.2.12", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: true, DialPort0: true},
  4290. {IPAddress: "192.0.2.13", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: true, DialPort0: true},
  4291. }
  4292. if runConfig.checkPruneServerEntries {
  4293. // Skip the dial port 0 cases, since the prune check doesn't send the
  4294. // dial port number in its request.
  4295. pruneServerEntryTestCases = pruneServerEntryTestCases[0:10]
  4296. }
  4297. for _, testCase := range pruneServerEntryTestCases {
  4298. dialPort := 4000
  4299. if testCase.DialPort0 {
  4300. dialPort = 0
  4301. }
  4302. _, _, _, _, encodedServerEntry, err := GenerateConfig(
  4303. &GenerateConfigParams{
  4304. ServerIPAddress: testCase.IPAddress,
  4305. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: dialPort},
  4306. })
  4307. if err != nil {
  4308. t.Fatalf("GenerateConfig failed: %s", err)
  4309. }
  4310. serverEntrySource := protocol.SERVER_ENTRY_SOURCE_REMOTE
  4311. if testCase.IsEmbedded {
  4312. serverEntrySource = protocol.SERVER_ENTRY_SOURCE_EMBEDDED
  4313. }
  4314. serverEntryFields, err := protocol.DecodeServerEntryFields(
  4315. string(encodedServerEntry),
  4316. testCase.LocalTimestamp,
  4317. serverEntrySource)
  4318. if err != nil {
  4319. t.Fatalf("DecodeServerEntryFields failed: %s", err)
  4320. }
  4321. // GenerateConfig now generates an explict tag for each server entry.
  4322. // To test the legacy case with no tag, delete it here.
  4323. delete(serverEntryFields, "tag")
  4324. if testCase.ExplicitTag {
  4325. testCase.ExpectedTag = prng.Base64String(32)
  4326. serverEntryFields.SetTag(testCase.ExpectedTag)
  4327. } else {
  4328. testCase.ExpectedTag = protocol.GenerateServerEntryTag(
  4329. serverEntryFields.GetIPAddress(),
  4330. serverEntryFields.GetWebServerSecret())
  4331. }
  4332. testCase.ServerEntryFields = serverEntryFields
  4333. }
  4334. psinetValidServerEntryTags := make([]string, 0)
  4335. expectedNumPruneNotices := 0
  4336. for _, testCase := range pruneServerEntryTestCases {
  4337. if testCase.PsinetValid {
  4338. psinetValidServerEntryTags = append(
  4339. psinetValidServerEntryTags, testCase.ExpectedTag)
  4340. }
  4341. if testCase.ExpectPrune {
  4342. expectedNumPruneNotices += 1
  4343. }
  4344. }
  4345. return pruneServerEntryTestCases,
  4346. psinetValidServerEntryTags,
  4347. expectedNumPruneNotices
  4348. }
  4349. func storePruneServerEntriesTest(
  4350. t *testing.T,
  4351. runConfig *runServerConfig,
  4352. testDataDirName string,
  4353. pruneServerEntryTestCases []*pruneServerEntryTestCase) {
  4354. if !runConfig.doPruneServerEntries {
  4355. return
  4356. }
  4357. for _, testCase := range pruneServerEntryTestCases {
  4358. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  4359. if err != nil {
  4360. t.Fatalf("StoreServerEntry failed: %s", err)
  4361. }
  4362. }
  4363. if runConfig.checkPruneServerEntries {
  4364. // The prune check case doesn't create failed_tunnel records.
  4365. return
  4366. }
  4367. clientConfig := &psiphon.Config{
  4368. SponsorId: "0000000000000000",
  4369. PropagationChannelId: "0000000000000000",
  4370. // DataRootDirectory must to be set to avoid a migration in the current
  4371. // working directory.
  4372. DataRootDirectory: testDataDirName,
  4373. }
  4374. err := clientConfig.Commit(false)
  4375. if err != nil {
  4376. t.Fatalf("Commit failed: %s", err)
  4377. }
  4378. resolver := psiphon.NewResolver(clientConfig, true)
  4379. defer resolver.Stop()
  4380. clientConfig.SetResolver(resolver)
  4381. applyParameters := make(map[string]interface{})
  4382. applyParameters[parameters.RecordFailedTunnelPersistentStatsProbability] = 1.0
  4383. // In order to reach the server-side status request failed_tunnel dial
  4384. // port 0 handling, disable ServerEntryPruneDialPortNumberZero so that
  4385. // the following MakeDialParameters will ignore the dial port 0 and not
  4386. // try to immediately prune the server entry.
  4387. applyParameters[parameters.ServerEntryPruneDialPortNumberZero] = false
  4388. err = clientConfig.SetParameters("", true, applyParameters)
  4389. if err != nil {
  4390. t.Fatalf("SetParameters failed: %s", err)
  4391. }
  4392. verifyTestCasesStored := make(verifyTestCasesStoredLookup)
  4393. for _, testCase := range pruneServerEntryTestCases {
  4394. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  4395. }
  4396. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  4397. t *testing.T,
  4398. testCase *pruneServerEntryTestCase,
  4399. serverEntry *protocol.ServerEntry) {
  4400. verifyTestCasesStored.isStored(testCase.IPAddress)
  4401. // Check that random tag was retained or derived tag was calculated as
  4402. // expected
  4403. if serverEntry.Tag != testCase.ExpectedTag {
  4404. t.Fatalf("unexpected tag for %s got %s expected %s",
  4405. testCase.IPAddress, serverEntry.Tag, testCase.ExpectedTag)
  4406. }
  4407. // Create failed tunnel event records to exercise pruning
  4408. dialParams, err := psiphon.MakeDialParameters(
  4409. clientConfig,
  4410. nil,
  4411. nil,
  4412. nil,
  4413. nil,
  4414. func(_ *protocol.ServerEntry, _ string) bool { return true },
  4415. func(serverEntry *protocol.ServerEntry) (string, bool) {
  4416. return runConfig.tunnelProtocol, true
  4417. },
  4418. serverEntry,
  4419. nil,
  4420. nil,
  4421. false,
  4422. 0,
  4423. 0)
  4424. if err != nil {
  4425. t.Fatalf("MakeDialParameters failed: %s", err)
  4426. }
  4427. err = psiphon.RecordFailedTunnelStat(
  4428. clientConfig, dialParams, nil, 0, 0, std_errors.New("test error"))
  4429. if err != nil {
  4430. t.Fatalf("RecordFailedTunnelStat failed: %s", err)
  4431. }
  4432. })
  4433. verifyTestCasesStored.checkStored(
  4434. t, "missing prune test case server entries")
  4435. }
  4436. func checkPruneServerEntriesTest(
  4437. t *testing.T,
  4438. runConfig *runServerConfig,
  4439. testDataDirName string,
  4440. pruneServerEntryTestCases []*pruneServerEntryTestCase) {
  4441. if !runConfig.doPruneServerEntries {
  4442. return
  4443. }
  4444. clientConfig := &psiphon.Config{
  4445. SponsorId: "0",
  4446. PropagationChannelId: "0",
  4447. // DataRootDirectory must to be set to avoid a migration in the current
  4448. // working directory.
  4449. DataRootDirectory: testDataDirName,
  4450. }
  4451. err := clientConfig.Commit(false)
  4452. if err != nil {
  4453. t.Fatalf("Commit failed: %s", err)
  4454. }
  4455. // Check that server entries remain or are pruned as expected
  4456. verifyTestCasesStored := make(verifyTestCasesStoredLookup)
  4457. for _, testCase := range pruneServerEntryTestCases {
  4458. if !testCase.ExpectPrune {
  4459. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  4460. }
  4461. }
  4462. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  4463. t *testing.T,
  4464. testCase *pruneServerEntryTestCase,
  4465. serverEntry *protocol.ServerEntry) {
  4466. if testCase.ExpectPrune {
  4467. t.Fatalf("expected prune for %s", testCase.IPAddress)
  4468. } else {
  4469. verifyTestCasesStored.isStored(testCase.IPAddress)
  4470. }
  4471. })
  4472. verifyTestCasesStored.checkStored(
  4473. t, "missing prune test case server entries")
  4474. // Check that pruned server entries reimport or not, as expected
  4475. for _, testCase := range pruneServerEntryTestCases {
  4476. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  4477. if err != nil {
  4478. t.Fatalf("StoreServerEntry failed: %s", err)
  4479. }
  4480. }
  4481. verifyTestCasesStored = make(verifyTestCasesStoredLookup)
  4482. for _, testCase := range pruneServerEntryTestCases {
  4483. if !testCase.ExpectPrune || !testCase.IsEmbedded {
  4484. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  4485. }
  4486. }
  4487. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  4488. t *testing.T,
  4489. testCase *pruneServerEntryTestCase,
  4490. serverEntry *protocol.ServerEntry) {
  4491. if testCase.ExpectPrune && testCase.IsEmbedded {
  4492. t.Fatalf("expected tombstone for %s", testCase.IPAddress)
  4493. } else {
  4494. verifyTestCasesStored.isStored(testCase.IPAddress)
  4495. }
  4496. })
  4497. verifyTestCasesStored.checkStored(
  4498. t, "missing reimported prune test case server entries")
  4499. // Non-embedded server entries with tombstones _can_ be reimported
  4500. for _, testCase := range pruneServerEntryTestCases {
  4501. testCase.ServerEntryFields.SetLocalSource(protocol.SERVER_ENTRY_SOURCE_REMOTE)
  4502. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  4503. if err != nil {
  4504. t.Fatalf("StoreServerEntry failed: %s", err)
  4505. }
  4506. }
  4507. verifyTestCasesStored = make(verifyTestCasesStoredLookup)
  4508. for _, testCase := range pruneServerEntryTestCases {
  4509. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  4510. }
  4511. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  4512. t *testing.T,
  4513. testCase *pruneServerEntryTestCase,
  4514. serverEntry *protocol.ServerEntry) {
  4515. verifyTestCasesStored.isStored(testCase.IPAddress)
  4516. })
  4517. verifyTestCasesStored.checkStored(
  4518. t, "missing non-embedded reimported prune test case server entries")
  4519. }
  4520. func scanServerEntries(
  4521. t *testing.T,
  4522. clientConfig *psiphon.Config,
  4523. pruneServerEntryTestCases []*pruneServerEntryTestCase,
  4524. scanner func(
  4525. t *testing.T,
  4526. testCase *pruneServerEntryTestCase,
  4527. serverEntry *protocol.ServerEntry)) {
  4528. _, iterator, err := psiphon.NewServerEntryIterator(clientConfig)
  4529. if err != nil {
  4530. t.Fatalf("NewServerEntryIterator failed: %s", err)
  4531. }
  4532. defer iterator.Close()
  4533. for {
  4534. serverEntry, err := iterator.Next()
  4535. if err != nil {
  4536. t.Fatalf("ServerIterator.Next failed: %s", err)
  4537. }
  4538. if serverEntry == nil {
  4539. break
  4540. }
  4541. for _, testCase := range pruneServerEntryTestCases {
  4542. if testCase.IPAddress == serverEntry.IpAddress {
  4543. scanner(t, testCase, serverEntry)
  4544. break
  4545. }
  4546. }
  4547. }
  4548. }
  4549. type verifyTestCasesStoredLookup map[string]bool
  4550. func (v verifyTestCasesStoredLookup) mustBeStored(s string) {
  4551. v[s] = true
  4552. }
  4553. func (v verifyTestCasesStoredLookup) isStored(s string) {
  4554. delete(v, s)
  4555. }
  4556. func (v verifyTestCasesStoredLookup) checkStored(t *testing.T, errMessage string) {
  4557. if len(v) != 0 {
  4558. t.Fatalf("%s: %+v", errMessage, v)
  4559. }
  4560. }
  4561. type Number interface {
  4562. int64 | float64
  4563. }
  4564. // testSampleInUniformRange returns true if sample is in the range [a, b],
  4565. // or within 2 standard deviations of the range.
  4566. func testSampleInUniformRange[V Number](sample, a, b, stddev V) bool {
  4567. if sample >= a && sample <= b {
  4568. return true
  4569. }
  4570. lower := math.Abs(float64(sample-a) / float64(stddev))
  4571. higher := math.Abs(float64(sample-b) / float64(stddev))
  4572. return lower <= 2.0 || higher <= 2.0
  4573. }
  4574. type flowInspectorProxy struct {
  4575. listener *socks.SocksListener
  4576. ch chan []*flows
  4577. }
  4578. func newFlowInspectorProxy() (*flowInspectorProxy, error) {
  4579. listener, err := socks.ListenSocks("tcp", "127.0.0.1:0")
  4580. if err != nil {
  4581. fmt.Printf("socks.ListenSocks failed: %s\n", err)
  4582. return nil, err
  4583. }
  4584. return &flowInspectorProxy{
  4585. listener: listener,
  4586. ch: make(chan []*flows, 1),
  4587. }, nil
  4588. }
  4589. func (f *flowInspectorProxy) start() {
  4590. go func() {
  4591. for {
  4592. localConn, err := f.listener.AcceptSocks()
  4593. if err != nil {
  4594. return
  4595. }
  4596. go func() {
  4597. defer localConn.Close()
  4598. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  4599. if err != nil {
  4600. fmt.Printf("net.Dial failed: %s\n", err)
  4601. return
  4602. }
  4603. defer remoteConn.Close()
  4604. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  4605. if err != nil {
  4606. fmt.Printf("localConn.Grant failed: %s\n", err)
  4607. return
  4608. }
  4609. waitGroup := new(sync.WaitGroup)
  4610. waitGroup.Add(1)
  4611. serverFlowWriter := newFlowWriter(true)
  4612. clientFlowWriter := newFlowWriter(false)
  4613. go func() {
  4614. defer waitGroup.Done()
  4615. // Copy from remote to local, and tee to serverFlowWriter.
  4616. io.Copy(localConn, io.TeeReader(remoteConn, serverFlowWriter))
  4617. // fmt.Printf("Server Flows:\n%s\n\n", serverFlowWriter.String())
  4618. localConn.Close()
  4619. remoteConn.Close()
  4620. }()
  4621. // Copy from local to remote, and tee to clientFlowWriter.
  4622. io.Copy(remoteConn, io.TeeReader(localConn, clientFlowWriter))
  4623. // fmt.Printf("Client Flows:\n%s\n\n", clientFlowWriter.String())
  4624. localConn.Close()
  4625. remoteConn.Close()
  4626. waitGroup.Wait()
  4627. // clientFlowWriter and serverFlowWriter are synchronized by waitGroup.
  4628. f.ch <- []*flows{serverFlowWriter, clientFlowWriter}
  4629. }()
  4630. }
  4631. }()
  4632. }
  4633. func (f *flowInspectorProxy) close() error {
  4634. return f.listener.Close()
  4635. }
  4636. type flow struct {
  4637. // timeDelta is the time elapsed since the last flow
  4638. timeDelta time.Duration
  4639. data []byte
  4640. }
  4641. type flows struct {
  4642. lastTime time.Time
  4643. server bool
  4644. streamDump *bytes.Buffer
  4645. flows []flow
  4646. }
  4647. func newFlowWriter(server bool) *flows {
  4648. return &flows{
  4649. lastTime: time.Now(),
  4650. streamDump: new(bytes.Buffer),
  4651. server: server,
  4652. }
  4653. }
  4654. // String returns a string representation of the first 10 flows.
  4655. func (f *flows) String() string {
  4656. var sb strings.Builder
  4657. for i, flow := range f.flows[:10] {
  4658. sb.WriteString(fmt.Sprintf("Flow %d: %.5f ms: %s\n",
  4659. i, flow.timeDelta.Seconds()*1000, hex.EncodeToString(flow.data)))
  4660. }
  4661. if len(f.flows) > 10 {
  4662. sb.WriteString("...\n")
  4663. }
  4664. return sb.String()
  4665. }
  4666. func (f *flows) Write(p []byte) (n int, err error) {
  4667. curTime := time.Now()
  4668. _, err = f.streamDump.Write(p)
  4669. if err != nil {
  4670. return 0, err
  4671. }
  4672. data := make([]byte, len(p))
  4673. n = copy(data, p)
  4674. if n < len(p) {
  4675. return n, io.ErrShortWrite
  4676. }
  4677. f.flows = append(f.flows, flow{
  4678. timeDelta: time.Since(f.lastTime),
  4679. data: data,
  4680. })
  4681. f.lastTime = curTime
  4682. return n, err
  4683. }
  4684. // newDiscoveryServers returns len(ipAddresses) discovery servers with the
  4685. // given IP addresses and randomly generated tags.
  4686. func newDiscoveryServers(ipAddresses []string) ([]*psinet.DiscoveryServer, error) {
  4687. servers := make([]*psinet.DiscoveryServer, len(ipAddresses))
  4688. for i, ipAddress := range ipAddresses {
  4689. encodedServer, err := protocol.EncodeServerEntry(&protocol.ServerEntry{
  4690. IpAddress: ipAddress,
  4691. Tag: prng.HexString(16),
  4692. })
  4693. if err != nil {
  4694. return nil, errors.Trace(err)
  4695. }
  4696. servers[i] = &psinet.DiscoveryServer{
  4697. DiscoveryDateRange: []time.Time{
  4698. time.Now().Add(-time.Hour).UTC(),
  4699. time.Now().Add(time.Hour).UTC(),
  4700. },
  4701. EncodedServerEntry: encodedServer,
  4702. }
  4703. }
  4704. return servers, nil
  4705. }
  4706. // Won't conflict with initializePruneServerEntriesTest
  4707. var tunneledDSLServerEntryIPAddress = "192.0.3.1"
  4708. func configureDSLTestServerEntries(
  4709. dslTestConfig *dslTestConfig,
  4710. encodedServerEntry string,
  4711. serverEntrySignaturePublicKey string,
  4712. serverEntrySignaturePrivateKey string) error {
  4713. // In the DSL test case, the client must get the full tunnel protocol
  4714. // server entry from an untunneled DSL fetch; a tactics-only copy of
  4715. // the server entry is stored locally to be used to bootstrap tactics
  4716. // and get the broker spec required for the untunneled RSL fetch.
  4717. // This sequence requires a low EstablishTunnelWorkTime, set to 1s, since
  4718. // the triggerFetches condition in Controller establishCandidateGenerator
  4719. // isn't triggered via candidateServerEntryCount.
  4720. // Store mock SLOKs, which are used to reassemble the OSL key required to
  4721. // access the DSL server entries.
  4722. for _, slok := range dslTestConfig.clientSLOKs {
  4723. _, err := psiphon.SetSLOK(slok.ID, slok.Key)
  4724. if err != nil {
  4725. return errors.Trace(err)
  4726. }
  4727. }
  4728. // Store the full tunnel protocol server entry in the mock DSL backend.
  4729. // TODO: also excersize prioritizeDial = false?
  4730. isTunneled := false
  4731. prioritizeDial := true
  4732. dslTestConfig.backend.SetServerEntries(
  4733. isTunneled,
  4734. prioritizeDial,
  4735. []string{encodedServerEntry})
  4736. // Add an EMBEDDED tactics-only server entry to the client's datastore.
  4737. serverEntryFields, err := protocol.DecodeServerEntryFields(
  4738. encodedServerEntry, "", "")
  4739. if err != nil {
  4740. return errors.Trace(err)
  4741. }
  4742. // Strip non-tactics capabilities. Assumes addMeekServerForBroker has
  4743. // added UNFRONTED-MEEK-HTTPS-OSSH for tactics, and only for tactics.
  4744. serverEntryFields["capabilities"] = []string{
  4745. "UNFRONTED-MEEK-HTTPS", "UNFRONTED-MEEK-HTTPS-TACTICS"}
  4746. err = serverEntryFields.AddSignature(
  4747. serverEntrySignaturePublicKey,
  4748. serverEntrySignaturePrivateKey)
  4749. if err != nil {
  4750. return errors.Trace(err)
  4751. }
  4752. serverEntryFields.SetLocalSource(protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  4753. serverEntryFields.SetLocalTimestamp(
  4754. common.TruncateTimestampToHour(common.GetCurrentTimestamp()))
  4755. err = psiphon.StoreServerEntry(serverEntryFields, true)
  4756. if err != nil {
  4757. return errors.Trace(err)
  4758. }
  4759. // Prepare one additional server entry for the tunneled DSL request.
  4760. dialPort := 4000
  4761. _, _, _, _, encodedServerEntryBytes, err := GenerateConfig(
  4762. &GenerateConfigParams{
  4763. ServerEntrySignaturePublicKey: serverEntrySignaturePublicKey,
  4764. ServerEntrySignaturePrivateKey: serverEntrySignaturePrivateKey,
  4765. ServerIPAddress: tunneledDSLServerEntryIPAddress,
  4766. TunnelProtocolPorts: map[string]int{protocol.TUNNEL_PROTOCOL_SSH: dialPort},
  4767. })
  4768. isTunneled = true
  4769. dslTestConfig.backend.SetServerEntries(
  4770. isTunneled,
  4771. prioritizeDial,
  4772. []string{string(encodedServerEntryBytes)})
  4773. return nil
  4774. }