server_test.go 164 KB

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