server_test.go 136 KB

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