server_test.go 98 KB

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