server_test.go 159 KB

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