server_test.go 119 KB

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