server_test.go 131 KB

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