server_test.go 139 KB

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