server_test.go 161 KB

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