server_test.go 95 KB

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