server_test.go 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511
  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. "errors"
  25. "flag"
  26. "fmt"
  27. "io/ioutil"
  28. "net"
  29. "net/http"
  30. "net/url"
  31. "os"
  32. "path/filepath"
  33. "strconv"
  34. "strings"
  35. "sync"
  36. "syscall"
  37. "testing"
  38. "time"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/marionette"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  44. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  45. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  46. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  47. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  48. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  49. "golang.org/x/net/proxy"
  50. )
  51. var serverIPAddress, testDataDirName string
  52. var mockWebServerURL, mockWebServerExpectedResponse string
  53. var mockWebServerPort = 8080
  54. func TestMain(m *testing.M) {
  55. flag.Parse()
  56. serverIPv4Address, serverIPv6Address, err := common.GetRoutableInterfaceIPAddresses()
  57. if err != nil {
  58. fmt.Printf("error getting server IP address: %s\n", err)
  59. os.Exit(1)
  60. }
  61. if serverIPv4Address != nil {
  62. serverIPAddress = serverIPv4Address.String()
  63. } else {
  64. serverIPAddress = serverIPv6Address.String()
  65. }
  66. testDataDirName, err = ioutil.TempDir("", "psiphon-server-test")
  67. if err != nil {
  68. fmt.Printf("TempDir failed: %s\n", err)
  69. os.Exit(1)
  70. }
  71. defer os.RemoveAll(testDataDirName)
  72. psiphon.SetEmitDiagnosticNotices(true, true)
  73. mockWebServerURL, mockWebServerExpectedResponse = runMockWebServer()
  74. os.Exit(m.Run())
  75. }
  76. func runMockWebServer() (string, string) {
  77. responseBody := prng.HexString(100000)
  78. serveMux := http.NewServeMux()
  79. serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  80. w.Write([]byte(responseBody))
  81. })
  82. webServerAddress := fmt.Sprintf("%s:%d", serverIPAddress, mockWebServerPort)
  83. server := &http.Server{
  84. Addr: webServerAddress,
  85. Handler: serveMux,
  86. }
  87. go func() {
  88. err := server.ListenAndServe()
  89. if err != nil {
  90. fmt.Printf("error running mock web server: %s\n", err)
  91. os.Exit(1)
  92. }
  93. }()
  94. // TODO: properly synchronize with web server readiness
  95. time.Sleep(1 * time.Second)
  96. return fmt.Sprintf("http://%s/", webServerAddress), responseBody
  97. }
  98. // Note: not testing fronted meek protocols, which client is
  99. // hard-wired to expect running on privileged ports 80 and 443.
  100. func TestSSH(t *testing.T) {
  101. runServer(t,
  102. &runServerConfig{
  103. tunnelProtocol: "SSH",
  104. enableSSHAPIRequests: true,
  105. doHotReload: false,
  106. doDefaultSponsorID: false,
  107. denyTrafficRules: false,
  108. requireAuthorization: true,
  109. omitAuthorization: false,
  110. doTunneledWebRequest: true,
  111. doTunneledNTPRequest: true,
  112. forceFragmenting: false,
  113. forceLivenessTest: false,
  114. doPruneServerEntries: false,
  115. doDanglingTCPConn: true,
  116. doPacketManipulation: false,
  117. doBurstMonitor: false,
  118. })
  119. }
  120. func TestOSSH(t *testing.T) {
  121. runServer(t,
  122. &runServerConfig{
  123. tunnelProtocol: "OSSH",
  124. enableSSHAPIRequests: true,
  125. doHotReload: false,
  126. doDefaultSponsorID: false,
  127. denyTrafficRules: false,
  128. requireAuthorization: true,
  129. omitAuthorization: false,
  130. doTunneledWebRequest: true,
  131. doTunneledNTPRequest: true,
  132. forceFragmenting: false,
  133. forceLivenessTest: false,
  134. doPruneServerEntries: false,
  135. doDanglingTCPConn: true,
  136. doPacketManipulation: false,
  137. doBurstMonitor: false,
  138. })
  139. }
  140. func TestFragmentedOSSH(t *testing.T) {
  141. runServer(t,
  142. &runServerConfig{
  143. tunnelProtocol: "OSSH",
  144. enableSSHAPIRequests: true,
  145. doHotReload: false,
  146. doDefaultSponsorID: false,
  147. denyTrafficRules: false,
  148. requireAuthorization: true,
  149. omitAuthorization: false,
  150. doTunneledWebRequest: true,
  151. doTunneledNTPRequest: true,
  152. forceFragmenting: true,
  153. forceLivenessTest: false,
  154. doPruneServerEntries: false,
  155. doDanglingTCPConn: true,
  156. doPacketManipulation: false,
  157. doBurstMonitor: false,
  158. })
  159. }
  160. func TestUnfrontedMeek(t *testing.T) {
  161. runServer(t,
  162. &runServerConfig{
  163. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  164. enableSSHAPIRequests: true,
  165. doHotReload: false,
  166. doDefaultSponsorID: false,
  167. denyTrafficRules: false,
  168. requireAuthorization: true,
  169. omitAuthorization: false,
  170. doTunneledWebRequest: true,
  171. doTunneledNTPRequest: true,
  172. forceFragmenting: false,
  173. forceLivenessTest: false,
  174. doPruneServerEntries: false,
  175. doDanglingTCPConn: true,
  176. doPacketManipulation: false,
  177. doBurstMonitor: false,
  178. })
  179. }
  180. func TestUnfrontedMeekHTTPS(t *testing.T) {
  181. runServer(t,
  182. &runServerConfig{
  183. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  184. tlsProfile: protocol.TLS_PROFILE_RANDOMIZED,
  185. enableSSHAPIRequests: true,
  186. doHotReload: false,
  187. doDefaultSponsorID: false,
  188. denyTrafficRules: false,
  189. requireAuthorization: true,
  190. omitAuthorization: false,
  191. doTunneledWebRequest: true,
  192. doTunneledNTPRequest: true,
  193. forceFragmenting: false,
  194. forceLivenessTest: false,
  195. doPruneServerEntries: false,
  196. doDanglingTCPConn: true,
  197. doPacketManipulation: false,
  198. doBurstMonitor: false,
  199. })
  200. }
  201. func TestUnfrontedMeekHTTPSTLS13(t *testing.T) {
  202. runServer(t,
  203. &runServerConfig{
  204. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  205. tlsProfile: protocol.TLS_PROFILE_CHROME_70,
  206. enableSSHAPIRequests: true,
  207. doHotReload: false,
  208. doDefaultSponsorID: false,
  209. denyTrafficRules: false,
  210. requireAuthorization: true,
  211. omitAuthorization: false,
  212. doTunneledWebRequest: true,
  213. doTunneledNTPRequest: true,
  214. forceFragmenting: false,
  215. forceLivenessTest: false,
  216. doPruneServerEntries: false,
  217. doDanglingTCPConn: true,
  218. doPacketManipulation: false,
  219. doBurstMonitor: false,
  220. })
  221. }
  222. func TestUnfrontedMeekSessionTicket(t *testing.T) {
  223. runServer(t,
  224. &runServerConfig{
  225. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  226. tlsProfile: protocol.TLS_PROFILE_CHROME_58,
  227. enableSSHAPIRequests: true,
  228. doHotReload: false,
  229. doDefaultSponsorID: false,
  230. denyTrafficRules: false,
  231. requireAuthorization: true,
  232. omitAuthorization: false,
  233. doTunneledWebRequest: true,
  234. doTunneledNTPRequest: true,
  235. forceFragmenting: false,
  236. forceLivenessTest: false,
  237. doPruneServerEntries: false,
  238. doDanglingTCPConn: true,
  239. doPacketManipulation: false,
  240. doBurstMonitor: false,
  241. })
  242. }
  243. func TestUnfrontedMeekSessionTicketTLS13(t *testing.T) {
  244. runServer(t,
  245. &runServerConfig{
  246. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  247. tlsProfile: protocol.TLS_PROFILE_CHROME_70,
  248. enableSSHAPIRequests: true,
  249. doHotReload: false,
  250. doDefaultSponsorID: false,
  251. denyTrafficRules: false,
  252. requireAuthorization: true,
  253. omitAuthorization: false,
  254. doTunneledWebRequest: true,
  255. doTunneledNTPRequest: true,
  256. forceFragmenting: false,
  257. forceLivenessTest: false,
  258. doPruneServerEntries: false,
  259. doDanglingTCPConn: true,
  260. doPacketManipulation: false,
  261. doBurstMonitor: false,
  262. })
  263. }
  264. func TestQUICOSSH(t *testing.T) {
  265. if !quic.Enabled() {
  266. t.Skip("QUIC is not enabled")
  267. }
  268. runServer(t,
  269. &runServerConfig{
  270. tunnelProtocol: "QUIC-OSSH",
  271. enableSSHAPIRequests: true,
  272. doHotReload: false,
  273. doDefaultSponsorID: false,
  274. denyTrafficRules: false,
  275. requireAuthorization: true,
  276. omitAuthorization: false,
  277. doTunneledWebRequest: true,
  278. doTunneledNTPRequest: true,
  279. forceFragmenting: false,
  280. forceLivenessTest: false,
  281. doPruneServerEntries: false,
  282. doDanglingTCPConn: false,
  283. doPacketManipulation: false,
  284. doBurstMonitor: false,
  285. })
  286. }
  287. func TestMarionetteOSSH(t *testing.T) {
  288. if !marionette.Enabled() {
  289. t.Skip("Marionette is not enabled")
  290. }
  291. runServer(t,
  292. &runServerConfig{
  293. tunnelProtocol: "MARIONETTE-OSSH",
  294. enableSSHAPIRequests: true,
  295. doHotReload: false,
  296. doDefaultSponsorID: false,
  297. denyTrafficRules: false,
  298. requireAuthorization: true,
  299. omitAuthorization: false,
  300. doTunneledWebRequest: true,
  301. doTunneledNTPRequest: true,
  302. forceFragmenting: false,
  303. forceLivenessTest: false,
  304. doPruneServerEntries: false,
  305. doDanglingTCPConn: false,
  306. doPacketManipulation: false,
  307. doBurstMonitor: false,
  308. })
  309. }
  310. func TestWebTransportAPIRequests(t *testing.T) {
  311. runServer(t,
  312. &runServerConfig{
  313. tunnelProtocol: "OSSH",
  314. enableSSHAPIRequests: false,
  315. doHotReload: false,
  316. doDefaultSponsorID: false,
  317. denyTrafficRules: false,
  318. requireAuthorization: false,
  319. omitAuthorization: true,
  320. doTunneledWebRequest: true,
  321. doTunneledNTPRequest: true,
  322. forceFragmenting: false,
  323. forceLivenessTest: false,
  324. doPruneServerEntries: false,
  325. doDanglingTCPConn: false,
  326. doPacketManipulation: false,
  327. doBurstMonitor: false,
  328. })
  329. }
  330. func TestHotReload(t *testing.T) {
  331. runServer(t,
  332. &runServerConfig{
  333. tunnelProtocol: "OSSH",
  334. enableSSHAPIRequests: true,
  335. doHotReload: true,
  336. doDefaultSponsorID: false,
  337. denyTrafficRules: false,
  338. requireAuthorization: true,
  339. omitAuthorization: false,
  340. doTunneledWebRequest: true,
  341. doTunneledNTPRequest: true,
  342. forceFragmenting: false,
  343. forceLivenessTest: false,
  344. doPruneServerEntries: false,
  345. doDanglingTCPConn: false,
  346. doPacketManipulation: false,
  347. doBurstMonitor: false,
  348. })
  349. }
  350. func TestDefaultSponsorID(t *testing.T) {
  351. runServer(t,
  352. &runServerConfig{
  353. tunnelProtocol: "OSSH",
  354. enableSSHAPIRequests: true,
  355. doHotReload: true,
  356. doDefaultSponsorID: true,
  357. denyTrafficRules: false,
  358. requireAuthorization: true,
  359. omitAuthorization: false,
  360. doTunneledWebRequest: true,
  361. doTunneledNTPRequest: true,
  362. forceFragmenting: false,
  363. forceLivenessTest: false,
  364. doPruneServerEntries: false,
  365. doDanglingTCPConn: false,
  366. doPacketManipulation: false,
  367. doBurstMonitor: false,
  368. })
  369. }
  370. func TestDenyTrafficRules(t *testing.T) {
  371. runServer(t,
  372. &runServerConfig{
  373. tunnelProtocol: "OSSH",
  374. enableSSHAPIRequests: true,
  375. doHotReload: true,
  376. doDefaultSponsorID: false,
  377. denyTrafficRules: true,
  378. requireAuthorization: true,
  379. omitAuthorization: false,
  380. doTunneledWebRequest: true,
  381. doTunneledNTPRequest: true,
  382. forceFragmenting: false,
  383. forceLivenessTest: false,
  384. doPruneServerEntries: false,
  385. doDanglingTCPConn: false,
  386. doPacketManipulation: false,
  387. doBurstMonitor: false,
  388. })
  389. }
  390. func TestOmitAuthorization(t *testing.T) {
  391. runServer(t,
  392. &runServerConfig{
  393. tunnelProtocol: "OSSH",
  394. enableSSHAPIRequests: true,
  395. doHotReload: true,
  396. doDefaultSponsorID: false,
  397. denyTrafficRules: false,
  398. requireAuthorization: true,
  399. omitAuthorization: true,
  400. doTunneledWebRequest: true,
  401. doTunneledNTPRequest: true,
  402. forceFragmenting: false,
  403. forceLivenessTest: false,
  404. doPruneServerEntries: false,
  405. doDanglingTCPConn: false,
  406. doPacketManipulation: false,
  407. doBurstMonitor: false,
  408. })
  409. }
  410. func TestNoAuthorization(t *testing.T) {
  411. runServer(t,
  412. &runServerConfig{
  413. tunnelProtocol: "OSSH",
  414. enableSSHAPIRequests: true,
  415. doHotReload: true,
  416. doDefaultSponsorID: false,
  417. denyTrafficRules: false,
  418. requireAuthorization: false,
  419. omitAuthorization: true,
  420. doTunneledWebRequest: true,
  421. doTunneledNTPRequest: true,
  422. forceFragmenting: false,
  423. forceLivenessTest: false,
  424. doPruneServerEntries: false,
  425. doDanglingTCPConn: false,
  426. doPacketManipulation: false,
  427. doBurstMonitor: false,
  428. })
  429. }
  430. func TestUnusedAuthorization(t *testing.T) {
  431. runServer(t,
  432. &runServerConfig{
  433. tunnelProtocol: "OSSH",
  434. enableSSHAPIRequests: true,
  435. doHotReload: true,
  436. doDefaultSponsorID: false,
  437. denyTrafficRules: false,
  438. requireAuthorization: false,
  439. omitAuthorization: false,
  440. doTunneledWebRequest: true,
  441. doTunneledNTPRequest: true,
  442. forceFragmenting: false,
  443. forceLivenessTest: false,
  444. doPruneServerEntries: false,
  445. doDanglingTCPConn: false,
  446. doPacketManipulation: false,
  447. doBurstMonitor: false,
  448. })
  449. }
  450. func TestTCPOnlySLOK(t *testing.T) {
  451. runServer(t,
  452. &runServerConfig{
  453. tunnelProtocol: "OSSH",
  454. enableSSHAPIRequests: true,
  455. doHotReload: false,
  456. doDefaultSponsorID: false,
  457. denyTrafficRules: false,
  458. requireAuthorization: true,
  459. omitAuthorization: false,
  460. doTunneledWebRequest: true,
  461. doTunneledNTPRequest: false,
  462. forceFragmenting: false,
  463. forceLivenessTest: false,
  464. doPruneServerEntries: false,
  465. doDanglingTCPConn: false,
  466. doPacketManipulation: false,
  467. doBurstMonitor: false,
  468. })
  469. }
  470. func TestUDPOnlySLOK(t *testing.T) {
  471. runServer(t,
  472. &runServerConfig{
  473. tunnelProtocol: "OSSH",
  474. enableSSHAPIRequests: true,
  475. doHotReload: false,
  476. doDefaultSponsorID: false,
  477. denyTrafficRules: false,
  478. requireAuthorization: true,
  479. omitAuthorization: false,
  480. doTunneledWebRequest: false,
  481. doTunneledNTPRequest: true,
  482. forceFragmenting: false,
  483. forceLivenessTest: false,
  484. doPruneServerEntries: false,
  485. doDanglingTCPConn: false,
  486. doPacketManipulation: false,
  487. doBurstMonitor: false,
  488. })
  489. }
  490. func TestLivenessTest(t *testing.T) {
  491. runServer(t,
  492. &runServerConfig{
  493. tunnelProtocol: "OSSH",
  494. enableSSHAPIRequests: true,
  495. doHotReload: false,
  496. doDefaultSponsorID: false,
  497. denyTrafficRules: false,
  498. requireAuthorization: true,
  499. omitAuthorization: false,
  500. doTunneledWebRequest: true,
  501. doTunneledNTPRequest: true,
  502. forceFragmenting: false,
  503. forceLivenessTest: true,
  504. doPruneServerEntries: false,
  505. doDanglingTCPConn: false,
  506. doPacketManipulation: false,
  507. doBurstMonitor: false,
  508. })
  509. }
  510. func TestPruneServerEntries(t *testing.T) {
  511. runServer(t,
  512. &runServerConfig{
  513. tunnelProtocol: "OSSH",
  514. enableSSHAPIRequests: true,
  515. doHotReload: false,
  516. doDefaultSponsorID: false,
  517. denyTrafficRules: false,
  518. requireAuthorization: true,
  519. omitAuthorization: false,
  520. doTunneledWebRequest: true,
  521. doTunneledNTPRequest: true,
  522. forceFragmenting: false,
  523. forceLivenessTest: true,
  524. doPruneServerEntries: true,
  525. doDanglingTCPConn: false,
  526. doPacketManipulation: false,
  527. doBurstMonitor: false,
  528. })
  529. }
  530. func TestBurstMonitor(t *testing.T) {
  531. runServer(t,
  532. &runServerConfig{
  533. tunnelProtocol: "OSSH",
  534. enableSSHAPIRequests: true,
  535. doHotReload: false,
  536. doDefaultSponsorID: false,
  537. denyTrafficRules: false,
  538. requireAuthorization: true,
  539. omitAuthorization: false,
  540. doTunneledWebRequest: true,
  541. doTunneledNTPRequest: true,
  542. forceFragmenting: false,
  543. forceLivenessTest: false,
  544. doPruneServerEntries: false,
  545. doDanglingTCPConn: true,
  546. doPacketManipulation: false,
  547. doBurstMonitor: true,
  548. })
  549. }
  550. type runServerConfig struct {
  551. tunnelProtocol string
  552. tlsProfile string
  553. enableSSHAPIRequests bool
  554. doHotReload bool
  555. doDefaultSponsorID bool
  556. denyTrafficRules bool
  557. requireAuthorization bool
  558. omitAuthorization bool
  559. doTunneledWebRequest bool
  560. doTunneledNTPRequest bool
  561. forceFragmenting bool
  562. forceLivenessTest bool
  563. doPruneServerEntries bool
  564. doDanglingTCPConn bool
  565. doPacketManipulation bool
  566. doBurstMonitor bool
  567. }
  568. var (
  569. testSSHClientVersions = []string{"SSH-2.0-A", "SSH-2.0-B", "SSH-2.0-C"}
  570. testUserAgents = []string{"ua1", "ua2", "ua3"}
  571. testNetworkType = "WIFI"
  572. )
  573. var serverRuns = 0
  574. func runServer(t *testing.T, runConfig *runServerConfig) {
  575. serverRuns += 1
  576. // configure authorized access
  577. accessType := "test-access-type"
  578. accessControlSigningKey, accessControlVerificationKey, err := accesscontrol.NewKeyPair(accessType)
  579. if err != nil {
  580. t.Fatalf("error creating access control key pair: %s", err)
  581. }
  582. accessControlVerificationKeyRing := accesscontrol.VerificationKeyRing{
  583. Keys: []*accesscontrol.VerificationKey{accessControlVerificationKey},
  584. }
  585. var seedAuthorizationID [32]byte
  586. clientAuthorization, authorizationID, err := accesscontrol.IssueAuthorization(
  587. accessControlSigningKey,
  588. seedAuthorizationID[:],
  589. time.Now().Add(1*time.Hour))
  590. if err != nil {
  591. t.Fatalf("error issuing authorization: %s", err)
  592. }
  593. authorizationIDStr := base64.StdEncoding.EncodeToString(authorizationID)
  594. // Enable tactics when the test protocol is meek. Both the client and the
  595. // server will be configured to support tactics. The client config will be
  596. // set with a nonfunctional config so that the tactics request must
  597. // succeed, overriding the nonfunctional values, for the tunnel to
  598. // establish.
  599. doClientTactics := protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol)
  600. doServerTactics := doClientTactics || runConfig.forceFragmenting || runConfig.doBurstMonitor
  601. // All servers require a tactics config with valid keys.
  602. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err :=
  603. tactics.GenerateKeys()
  604. if err != nil {
  605. t.Fatalf("error generating tactics keys: %s", err)
  606. }
  607. livenessTestSize := 0
  608. if doClientTactics || runConfig.forceLivenessTest {
  609. livenessTestSize = 1048576
  610. }
  611. // create a server
  612. psiphonServerIPAddress := serverIPAddress
  613. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) ||
  614. protocol.TunnelProtocolUsesMarionette(runConfig.tunnelProtocol) {
  615. // Workaround for macOS firewall.
  616. psiphonServerIPAddress = "127.0.0.1"
  617. }
  618. psiphonServerPort := 4000
  619. generateConfigParams := &GenerateConfigParams{
  620. ServerIPAddress: psiphonServerIPAddress,
  621. EnableSSHAPIRequests: runConfig.enableSSHAPIRequests,
  622. WebServerPort: 8000,
  623. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: psiphonServerPort},
  624. }
  625. if protocol.TunnelProtocolUsesMarionette(runConfig.tunnelProtocol) {
  626. generateConfigParams.TunnelProtocolPorts[runConfig.tunnelProtocol] = 0
  627. generateConfigParams.MarionetteFormat = "http_simple_nonblocking"
  628. }
  629. if doServerTactics {
  630. generateConfigParams.TacticsRequestPublicKey = tacticsRequestPublicKey
  631. generateConfigParams.TacticsRequestObfuscatedKey = tacticsRequestObfuscatedKey
  632. }
  633. serverConfigJSON, _, _, _, encodedServerEntry, err := GenerateConfig(generateConfigParams)
  634. if err != nil {
  635. t.Fatalf("error generating server config: %s", err)
  636. }
  637. // customize server config
  638. // Initialize prune server entry test cases and associated data to pave into psinet.
  639. pruneServerEntryTestCases, psinetValidServerEntryTags, expectedNumPruneNotices :=
  640. initializePruneServerEntriesTest(t, runConfig)
  641. // Pave psinet with random values to test handshake homepages.
  642. psinetFilename := filepath.Join(testDataDirName, "psinet.json")
  643. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(
  644. t, runConfig.doDefaultSponsorID, psinetFilename, psinetValidServerEntryTags)
  645. // Pave OSL config for SLOK testing
  646. oslConfigFilename := filepath.Join(testDataDirName, "osl_config.json")
  647. propagationChannelID := paveOSLConfigFile(t, oslConfigFilename)
  648. // Pave traffic rules file which exercises handshake parameter filtering. Client
  649. // must handshake with specified sponsor ID in order to allow ports for tunneled
  650. // requests.
  651. trafficRulesFilename := filepath.Join(testDataDirName, "traffic_rules.json")
  652. paveTrafficRulesFile(
  653. t,
  654. trafficRulesFilename,
  655. propagationChannelID,
  656. accessType,
  657. authorizationIDStr,
  658. runConfig.requireAuthorization,
  659. runConfig.denyTrafficRules,
  660. livenessTestSize)
  661. var tacticsConfigFilename string
  662. // Only pave the tactics config when tactics are required. This exercises the
  663. // case where the tactics config is omitted.
  664. if doServerTactics {
  665. tacticsConfigFilename = filepath.Join(testDataDirName, "tactics_config.json")
  666. paveTacticsConfigFile(
  667. t,
  668. tacticsConfigFilename,
  669. tacticsRequestPublicKey,
  670. tacticsRequestPrivateKey,
  671. tacticsRequestObfuscatedKey,
  672. runConfig.tunnelProtocol,
  673. propagationChannelID,
  674. livenessTestSize,
  675. runConfig.doBurstMonitor)
  676. }
  677. blocklistFilename := filepath.Join(testDataDirName, "blocklist.csv")
  678. paveBlocklistFile(t, blocklistFilename)
  679. var serverConfig map[string]interface{}
  680. json.Unmarshal(serverConfigJSON, &serverConfig)
  681. serverConfig["GeoIPDatabaseFilename"] = ""
  682. serverConfig["PsinetDatabaseFilename"] = psinetFilename
  683. serverConfig["TrafficRulesFilename"] = trafficRulesFilename
  684. serverConfig["OSLConfigFilename"] = oslConfigFilename
  685. if doServerTactics {
  686. serverConfig["TacticsConfigFilename"] = tacticsConfigFilename
  687. }
  688. serverConfig["BlocklistFilename"] = blocklistFilename
  689. serverConfig["LogFilename"] = filepath.Join(testDataDirName, "psiphond.log")
  690. serverConfig["LogLevel"] = "debug"
  691. serverConfig["AccessControlVerificationKeyRing"] = accessControlVerificationKeyRing
  692. // Set this parameter so at least the semaphore functions are called.
  693. // TODO: test that the concurrency limit is correctly enforced.
  694. serverConfig["MaxConcurrentSSHHandshakes"] = 1
  695. // Exercise this option.
  696. serverConfig["PeriodicGarbageCollectionSeconds"] = 1
  697. // Allow port forwards to local test web server.
  698. serverConfig["AllowBogons"] = true
  699. serverConfig["RunPacketManipulator"] = runConfig.doPacketManipulation
  700. serverConfigJSON, _ = json.Marshal(serverConfig)
  701. serverTunnelLog := make(chan map[string]interface{}, 1)
  702. uniqueUserLog := make(chan map[string]interface{}, 1)
  703. setLogCallback(func(log []byte) {
  704. logFields := make(map[string]interface{})
  705. err := json.Unmarshal(log, &logFields)
  706. if err != nil {
  707. return
  708. }
  709. if logFields["event_name"] == nil {
  710. return
  711. }
  712. switch logFields["event_name"].(string) {
  713. case "unique_user":
  714. select {
  715. case uniqueUserLog <- logFields:
  716. default:
  717. }
  718. case "server_tunnel":
  719. select {
  720. case serverTunnelLog <- logFields:
  721. default:
  722. }
  723. }
  724. })
  725. // run server
  726. serverWaitGroup := new(sync.WaitGroup)
  727. serverWaitGroup.Add(1)
  728. go func() {
  729. defer serverWaitGroup.Done()
  730. err := RunServices(serverConfigJSON)
  731. if err != nil {
  732. // TODO: wrong goroutine for t.FatalNow()
  733. t.Errorf("error running server: %s", err)
  734. }
  735. }()
  736. stopServer := func() {
  737. // Test: orderly server shutdown
  738. p, _ := os.FindProcess(os.Getpid())
  739. p.Signal(os.Interrupt)
  740. shutdownTimeout := time.NewTimer(5 * time.Second)
  741. shutdownOk := make(chan struct{}, 1)
  742. go func() {
  743. serverWaitGroup.Wait()
  744. shutdownOk <- struct{}{}
  745. }()
  746. select {
  747. case <-shutdownOk:
  748. case <-shutdownTimeout.C:
  749. t.Errorf("server shutdown timeout exceeded")
  750. }
  751. }
  752. // Stop server on early exits due to failure.
  753. defer func() {
  754. if stopServer != nil {
  755. stopServer()
  756. }
  757. }()
  758. // TODO: monitor logs for more robust wait-until-loaded. For example,
  759. // especially with the race detector on, QUIC-OSSH tests can fail as the
  760. // client sends its initial packet before the server is ready.
  761. time.Sleep(1 * time.Second)
  762. // Test: hot reload (of psinet and traffic rules)
  763. if runConfig.doHotReload {
  764. // Pave new config files with different random values.
  765. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(
  766. t, runConfig.doDefaultSponsorID, psinetFilename, psinetValidServerEntryTags)
  767. propagationChannelID = paveOSLConfigFile(t, oslConfigFilename)
  768. paveTrafficRulesFile(
  769. t,
  770. trafficRulesFilename,
  771. propagationChannelID,
  772. accessType,
  773. authorizationIDStr,
  774. runConfig.requireAuthorization,
  775. runConfig.denyTrafficRules,
  776. livenessTestSize)
  777. p, _ := os.FindProcess(os.Getpid())
  778. p.Signal(syscall.SIGUSR1)
  779. // TODO: monitor logs for more robust wait-until-reloaded
  780. time.Sleep(1 * time.Second)
  781. // After reloading psinet, the new sponsorID/expectedHomepageURL
  782. // should be active, as tested in the client "Homepage" notice
  783. // handler below.
  784. }
  785. // Exercise server_load logging
  786. p, _ := os.FindProcess(os.Getpid())
  787. p.Signal(syscall.SIGUSR2)
  788. // configure client
  789. values.SetSSHClientVersionsSpec(values.NewPickOneSpec(testSSHClientVersions))
  790. values.SetUserAgentsSpec(values.NewPickOneSpec(testUserAgents))
  791. // TODO: currently, TargetServerEntry only works with one tunnel
  792. numTunnels := 1
  793. localSOCKSProxyPort := 1081
  794. localHTTPProxyPort := 8081
  795. // Use a distinct suffix for network ID for each test run to ensure tactics
  796. // from different runs don't apply; this is a workaround for the singleton
  797. // datastore.
  798. jsonNetworkID := fmt.Sprintf(`,"NetworkID" : "WIFI-%s"`, time.Now().String())
  799. jsonLimitTLSProfiles := ""
  800. if runConfig.tlsProfile != "" {
  801. jsonLimitTLSProfiles = fmt.Sprintf(`,"LimitTLSProfiles" : ["%s"]`, runConfig.tlsProfile)
  802. }
  803. clientConfigJSON := fmt.Sprintf(`
  804. {
  805. "ClientPlatform" : "Android_10_com.test.app",
  806. "ClientVersion" : "0",
  807. "SponsorId" : "0",
  808. "PropagationChannelId" : "0",
  809. "TunnelWholeDevice" : 1,
  810. "DeviceRegion" : "US",
  811. "DisableRemoteServerListFetcher" : true,
  812. "EstablishTunnelPausePeriodSeconds" : 1,
  813. "ConnectionWorkerPoolSize" : %d,
  814. "LimitTunnelProtocols" : ["%s"]
  815. %s
  816. %s
  817. }`, numTunnels, runConfig.tunnelProtocol, jsonLimitTLSProfiles, jsonNetworkID)
  818. clientConfig, err := psiphon.LoadConfig([]byte(clientConfigJSON))
  819. if err != nil {
  820. t.Fatalf("error processing configuration file: %s", err)
  821. }
  822. clientConfig.DataRootDirectory = testDataDirName
  823. if !runConfig.doDefaultSponsorID {
  824. clientConfig.SponsorId = sponsorID
  825. }
  826. clientConfig.PropagationChannelId = propagationChannelID
  827. clientConfig.TunnelPoolSize = numTunnels
  828. clientConfig.TargetServerEntry = string(encodedServerEntry)
  829. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  830. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  831. clientConfig.EmitSLOKs = true
  832. clientConfig.EmitServerAlerts = true
  833. if !runConfig.omitAuthorization {
  834. clientConfig.Authorizations = []string{clientAuthorization}
  835. }
  836. err = clientConfig.Commit(false)
  837. if err != nil {
  838. t.Fatalf("error committing configuration file: %s", err)
  839. }
  840. if doClientTactics {
  841. // Configure nonfunctional values that must be overridden by tactics.
  842. applyParameters := make(map[string]interface{})
  843. applyParameters[parameters.TunnelConnectTimeout] = "1s"
  844. applyParameters[parameters.TunnelRateLimits] = common.RateLimits{WriteBytesPerSecond: 1}
  845. err = clientConfig.SetParameters("", true, applyParameters)
  846. if err != nil {
  847. t.Fatalf("SetParameters failed: %s", err)
  848. }
  849. } else {
  850. // Directly apply same parameters that would've come from tactics.
  851. applyParameters := make(map[string]interface{})
  852. if runConfig.forceFragmenting {
  853. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols{runConfig.tunnelProtocol}
  854. applyParameters[parameters.FragmentorProbability] = 1.0
  855. applyParameters[parameters.FragmentorMinTotalBytes] = 1000
  856. applyParameters[parameters.FragmentorMaxTotalBytes] = 2000
  857. applyParameters[parameters.FragmentorMinWriteBytes] = 1
  858. applyParameters[parameters.FragmentorMaxWriteBytes] = 100
  859. applyParameters[parameters.FragmentorMinDelay] = 1 * time.Millisecond
  860. applyParameters[parameters.FragmentorMaxDelay] = 10 * time.Millisecond
  861. }
  862. if runConfig.forceLivenessTest {
  863. applyParameters[parameters.LivenessTestMinUpstreamBytes] = livenessTestSize
  864. applyParameters[parameters.LivenessTestMaxUpstreamBytes] = livenessTestSize
  865. applyParameters[parameters.LivenessTestMinDownstreamBytes] = livenessTestSize
  866. applyParameters[parameters.LivenessTestMaxDownstreamBytes] = livenessTestSize
  867. }
  868. if runConfig.doPruneServerEntries {
  869. applyParameters[parameters.PsiphonAPIStatusRequestShortPeriodMin] = 1 * time.Millisecond
  870. applyParameters[parameters.PsiphonAPIStatusRequestShortPeriodMax] = 1 * time.Millisecond
  871. }
  872. err = clientConfig.SetParameters("", true, applyParameters)
  873. if err != nil {
  874. t.Fatalf("SetParameters failed: %s", err)
  875. }
  876. }
  877. // connect to server with client
  878. err = psiphon.OpenDataStore(clientConfig)
  879. if err != nil {
  880. t.Fatalf("error initializing client datastore: %s", err)
  881. }
  882. defer psiphon.CloseDataStore()
  883. // Test unique user counting cases.
  884. var expectUniqueUser bool
  885. switch serverRuns % 3 {
  886. case 0:
  887. // Mock no last_connected.
  888. psiphon.SetKeyValue("lastConnected", "")
  889. expectUniqueUser = true
  890. case 1:
  891. // Mock previous day last_connected.
  892. psiphon.SetKeyValue(
  893. "lastConnected",
  894. time.Now().UTC().AddDate(0, 0, -1).Truncate(1*time.Hour).Format(time.RFC3339))
  895. expectUniqueUser = true
  896. case 2:
  897. // Leave previous last_connected.
  898. expectUniqueUser = false
  899. }
  900. // Clear SLOKs from previous test runs.
  901. psiphon.DeleteSLOKs()
  902. // Store prune server entry test server entries and failed tunnel records.
  903. storePruneServerEntriesTest(
  904. t, runConfig, testDataDirName, pruneServerEntryTestCases)
  905. controller, err := psiphon.NewController(clientConfig)
  906. if err != nil {
  907. t.Fatalf("error creating client controller: %s", err)
  908. }
  909. connectedServer := make(chan struct{}, 1)
  910. tunnelsEstablished := make(chan struct{}, 1)
  911. homepageReceived := make(chan struct{}, 1)
  912. slokSeeded := make(chan struct{}, 1)
  913. numPruneNotices := 0
  914. pruneServerEntriesNoticesEmitted := make(chan struct{}, 1)
  915. serverAlertDisallowedNoticesEmitted := make(chan struct{}, 1)
  916. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  917. func(notice []byte) {
  918. //fmt.Printf("%s\n", string(notice))
  919. noticeType, payload, err := psiphon.GetNotice(notice)
  920. if err != nil {
  921. return
  922. }
  923. switch noticeType {
  924. case "ConnectedServer":
  925. sendNotificationReceived(connectedServer)
  926. case "Tunnels":
  927. count := int(payload["count"].(float64))
  928. if count >= numTunnels {
  929. sendNotificationReceived(tunnelsEstablished)
  930. }
  931. case "Homepage":
  932. homepageURL := payload["url"].(string)
  933. if homepageURL != expectedHomepageURL {
  934. // TODO: wrong goroutine for t.FatalNow()
  935. t.Errorf("unexpected homepage: %s", homepageURL)
  936. }
  937. sendNotificationReceived(homepageReceived)
  938. case "SLOKSeeded":
  939. sendNotificationReceived(slokSeeded)
  940. case "PruneServerEntry":
  941. numPruneNotices += 1
  942. if numPruneNotices == expectedNumPruneNotices {
  943. sendNotificationReceived(pruneServerEntriesNoticesEmitted)
  944. }
  945. case "ServerAlert":
  946. reason := payload["reason"].(string)
  947. if reason == protocol.PSIPHON_API_ALERT_DISALLOWED_TRAFFIC {
  948. sendNotificationReceived(serverAlertDisallowedNoticesEmitted)
  949. }
  950. }
  951. }))
  952. ctx, cancelFunc := context.WithCancel(context.Background())
  953. controllerWaitGroup := new(sync.WaitGroup)
  954. controllerWaitGroup.Add(1)
  955. go func() {
  956. defer controllerWaitGroup.Done()
  957. controller.Run(ctx)
  958. }()
  959. stopClient := func() {
  960. cancelFunc()
  961. shutdownTimeout := time.NewTimer(20 * time.Second)
  962. shutdownOk := make(chan struct{}, 1)
  963. go func() {
  964. controllerWaitGroup.Wait()
  965. shutdownOk <- struct{}{}
  966. }()
  967. select {
  968. case <-shutdownOk:
  969. case <-shutdownTimeout.C:
  970. t.Errorf("controller shutdown timeout exceeded")
  971. }
  972. }
  973. // Stop client on early exits due to failure.
  974. defer func() {
  975. if stopClient != nil {
  976. stopClient()
  977. }
  978. }()
  979. // Test: tunnels must be established, and correct homepage
  980. // must be received, within 30 seconds
  981. timeoutSignal := make(chan struct{})
  982. go func() {
  983. timer := time.NewTimer(30 * time.Second)
  984. <-timer.C
  985. close(timeoutSignal)
  986. }()
  987. waitOnNotification(t, connectedServer, timeoutSignal, "connected server timeout exceeded")
  988. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel established timeout exceeded")
  989. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  990. expectTrafficFailure := runConfig.denyTrafficRules || (runConfig.omitAuthorization && runConfig.requireAuthorization)
  991. if runConfig.doTunneledWebRequest {
  992. // Test: tunneled web site fetch
  993. err = makeTunneledWebRequest(
  994. t, localHTTPProxyPort, mockWebServerURL, mockWebServerExpectedResponse)
  995. if err == nil {
  996. if expectTrafficFailure {
  997. t.Fatalf("unexpected tunneled web request success")
  998. }
  999. } else {
  1000. if !expectTrafficFailure {
  1001. t.Fatalf("tunneled web request failed: %s", err)
  1002. }
  1003. }
  1004. }
  1005. if runConfig.doTunneledNTPRequest {
  1006. // Test: tunneled UDP packets
  1007. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  1008. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  1009. if err == nil {
  1010. if expectTrafficFailure {
  1011. t.Fatalf("unexpected tunneled NTP request success")
  1012. }
  1013. } else {
  1014. if !expectTrafficFailure {
  1015. t.Fatalf("tunneled NTP request failed: %s", err)
  1016. }
  1017. }
  1018. }
  1019. // Test: await SLOK payload or server alert notice
  1020. time.Sleep(1 * time.Second)
  1021. if !expectTrafficFailure {
  1022. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  1023. numSLOKs := psiphon.CountSLOKs()
  1024. if numSLOKs != expectedNumSLOKs {
  1025. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  1026. }
  1027. } else {
  1028. // Note: in expectTrafficFailure case, timeoutSignal may have already fired.
  1029. waitOnNotification(t, serverAlertDisallowedNoticesEmitted, nil, "")
  1030. }
  1031. // Test: await expected prune server entry notices
  1032. //
  1033. // Note: will take up to PsiphonAPIStatusRequestShortPeriodMax to emit.
  1034. if expectedNumPruneNotices > 0 {
  1035. waitOnNotification(t, pruneServerEntriesNoticesEmitted, nil, "")
  1036. }
  1037. if runConfig.doDanglingTCPConn {
  1038. // Test: client that has established TCP connection but not completed
  1039. // any handshakes must not block/delay server shutdown
  1040. danglingConn, err := net.Dial(
  1041. "tcp", net.JoinHostPort(psiphonServerIPAddress, strconv.Itoa(psiphonServerPort)))
  1042. if err != nil {
  1043. t.Fatalf("TCP dial failed: %s", err)
  1044. }
  1045. defer danglingConn.Close()
  1046. }
  1047. // Shutdown to ensure logs/notices are flushed
  1048. stopClient()
  1049. stopClient = nil
  1050. stopServer()
  1051. stopServer = nil
  1052. // Test: all expected server logs were emitted
  1053. // TODO: stops should be fully synchronous, but, intermittently,
  1054. // server_tunnel fails to appear ("missing server tunnel log")
  1055. // without this delay.
  1056. time.Sleep(100 * time.Millisecond)
  1057. expectClientBPFField := psiphon.ClientBPFEnabled() && doClientTactics
  1058. expectServerBPFField := ServerBPFEnabled() && doServerTactics
  1059. expectServerPacketManipulationField := runConfig.doPacketManipulation
  1060. expectBurstFields := runConfig.doBurstMonitor
  1061. select {
  1062. case logFields := <-serverTunnelLog:
  1063. err := checkExpectedServerTunnelLogFields(
  1064. runConfig,
  1065. expectClientBPFField,
  1066. expectServerBPFField,
  1067. expectServerPacketManipulationField,
  1068. expectBurstFields,
  1069. logFields)
  1070. if err != nil {
  1071. t.Fatalf("invalid server tunnel log fields: %s", err)
  1072. }
  1073. default:
  1074. t.Fatalf("missing server tunnel log")
  1075. }
  1076. if expectUniqueUser {
  1077. select {
  1078. case logFields := <-uniqueUserLog:
  1079. err := checkExpectedUniqueUserLogFields(
  1080. runConfig,
  1081. logFields)
  1082. if err != nil {
  1083. t.Fatalf("invalid unique user log fields: %s", err)
  1084. }
  1085. default:
  1086. t.Fatalf("missing unique user log")
  1087. }
  1088. } else {
  1089. select {
  1090. case <-uniqueUserLog:
  1091. t.Fatalf("unexpected unique user log")
  1092. default:
  1093. }
  1094. }
  1095. // Check that datastore had retained/pruned server entries as expected.
  1096. checkPruneServerEntriesTest(t, runConfig, testDataDirName, pruneServerEntryTestCases)
  1097. }
  1098. func checkExpectedServerTunnelLogFields(
  1099. runConfig *runServerConfig,
  1100. expectClientBPFField bool,
  1101. expectServerBPFField bool,
  1102. expectServerPacketManipulationField bool,
  1103. expectBurstFields bool,
  1104. fields map[string]interface{}) error {
  1105. // Limitations:
  1106. //
  1107. // - client_build_rev not set in test build (see common/buildinfo.go)
  1108. // - egress_region, upstream_proxy_type, upstream_proxy_custom_header_names not exercised in test
  1109. // - fronting_provider_id/meek_dial_ip_address/meek_resolved_ip_address only logged for FRONTED meek protocols
  1110. for _, name := range []string{
  1111. "start_time",
  1112. "duration",
  1113. "session_id",
  1114. "is_first_tunnel_in_session",
  1115. "last_connected",
  1116. "establishment_duration",
  1117. "propagation_channel_id",
  1118. "sponsor_id",
  1119. "client_platform",
  1120. "relay_protocol",
  1121. "tunnel_whole_device",
  1122. "device_region",
  1123. "ssh_client_version",
  1124. "server_entry_region",
  1125. "server_entry_source",
  1126. "server_entry_timestamp",
  1127. "dial_port_number",
  1128. "is_replay",
  1129. "dial_duration",
  1130. "candidate_number",
  1131. "established_tunnels_count",
  1132. "network_latency_multiplier",
  1133. "network_type",
  1134. } {
  1135. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1136. return fmt.Errorf("missing expected field '%s'", name)
  1137. }
  1138. }
  1139. if fields["relay_protocol"].(string) != runConfig.tunnelProtocol {
  1140. return fmt.Errorf("unexpected relay_protocol '%s'", fields["relay_protocol"])
  1141. }
  1142. if !common.Contains(testSSHClientVersions, fields["ssh_client_version"].(string)) {
  1143. return fmt.Errorf("unexpected relay_protocol '%s'", fields["ssh_client_version"])
  1144. }
  1145. if protocol.TunnelProtocolUsesObfuscatedSSH(runConfig.tunnelProtocol) {
  1146. for _, name := range []string{
  1147. "padding",
  1148. "pad_response",
  1149. } {
  1150. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1151. return fmt.Errorf("missing expected field '%s'", name)
  1152. }
  1153. }
  1154. }
  1155. if protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol) {
  1156. for _, name := range []string{
  1157. "user_agent",
  1158. "meek_transformed_host_name",
  1159. "meek_cookie_size",
  1160. "meek_limit_request",
  1161. tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME,
  1162. } {
  1163. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1164. return fmt.Errorf("missing expected field '%s'", name)
  1165. }
  1166. }
  1167. if !common.Contains(testUserAgents, fields["user_agent"].(string)) {
  1168. return fmt.Errorf("unexpected user_agent '%s'", fields["user_agent"])
  1169. }
  1170. }
  1171. if protocol.TunnelProtocolUsesMeekHTTP(runConfig.tunnelProtocol) {
  1172. for _, name := range []string{
  1173. "meek_host_header",
  1174. } {
  1175. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1176. return fmt.Errorf("missing expected field '%s'", name)
  1177. }
  1178. }
  1179. for _, name := range []string{
  1180. "meek_dial_ip_address",
  1181. "meek_resolved_ip_address",
  1182. } {
  1183. if fields[name] != nil {
  1184. return fmt.Errorf("unexpected field '%s'", name)
  1185. }
  1186. }
  1187. }
  1188. if protocol.TunnelProtocolUsesMeekHTTPS(runConfig.tunnelProtocol) {
  1189. for _, name := range []string{
  1190. "tls_profile",
  1191. "tls_version",
  1192. "meek_sni_server_name",
  1193. } {
  1194. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1195. return fmt.Errorf("missing expected field '%s'", name)
  1196. }
  1197. }
  1198. for _, name := range []string{
  1199. "meek_dial_ip_address",
  1200. "meek_resolved_ip_address",
  1201. "meek_host_header",
  1202. } {
  1203. if fields[name] != nil {
  1204. return fmt.Errorf("unexpected field '%s'", name)
  1205. }
  1206. }
  1207. if !common.Contains(protocol.SupportedTLSProfiles, fields["tls_profile"].(string)) {
  1208. return fmt.Errorf("unexpected tls_profile '%s'", fields["tls_profile"])
  1209. }
  1210. tlsVersion := fields["tls_version"].(string)
  1211. if !strings.HasPrefix(tlsVersion, protocol.TLS_VERSION_12) &&
  1212. !strings.HasPrefix(tlsVersion, protocol.TLS_VERSION_13) {
  1213. return fmt.Errorf("unexpected tls_version '%s'", fields["tls_version"])
  1214. }
  1215. }
  1216. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) {
  1217. for _, name := range []string{
  1218. "quic_version",
  1219. "quic_dial_sni_address",
  1220. } {
  1221. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1222. return fmt.Errorf("missing expected field '%s'", name)
  1223. }
  1224. }
  1225. if !common.Contains(protocol.SupportedQUICVersions, fields["quic_version"].(string)) {
  1226. return fmt.Errorf("unexpected quic_version '%s'", fields["quic_version"])
  1227. }
  1228. }
  1229. if runConfig.forceFragmenting {
  1230. for _, name := range []string{
  1231. "upstream_bytes_fragmented",
  1232. "upstream_min_bytes_written",
  1233. "upstream_max_bytes_written",
  1234. "upstream_min_delayed",
  1235. "upstream_max_delayed",
  1236. } {
  1237. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1238. return fmt.Errorf("missing expected field '%s'", name)
  1239. }
  1240. }
  1241. }
  1242. if expectClientBPFField {
  1243. name := "client_bpf"
  1244. if fields[name] == nil {
  1245. return fmt.Errorf("missing expected field '%s'", name)
  1246. } else if fmt.Sprintf("%s", fields[name]) != "test-client-bpf" {
  1247. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  1248. }
  1249. }
  1250. if expectServerBPFField {
  1251. name := "server_bpf"
  1252. if fields[name] == nil {
  1253. return fmt.Errorf("missing expected field '%s'", name)
  1254. } else if fmt.Sprintf("%s", fields[name]) != "test-server-bpf" {
  1255. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  1256. }
  1257. }
  1258. if expectServerPacketManipulationField {
  1259. name := "server_packet_manipulation"
  1260. if fields[name] == nil {
  1261. return fmt.Errorf("missing expected field '%s'", name)
  1262. } else if fmt.Sprintf("%s", fields[name]) != "test-packetman-spec" {
  1263. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  1264. }
  1265. }
  1266. if expectBurstFields {
  1267. // common.TestBurstMonitoredConn covers inclusion of additional fields.
  1268. for _, name := range []string{
  1269. "burst_upstream_first_rate",
  1270. "burst_upstream_last_rate",
  1271. "burst_upstream_min_rate",
  1272. "burst_upstream_max_rate",
  1273. "burst_downstream_first_rate",
  1274. "burst_downstream_last_rate",
  1275. "burst_downstream_min_rate",
  1276. "burst_downstream_max_rate",
  1277. } {
  1278. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1279. return fmt.Errorf("missing expected field '%s'", name)
  1280. }
  1281. }
  1282. }
  1283. if fields["network_type"].(string) != testNetworkType {
  1284. return fmt.Errorf("unexpected network_type '%s'", fields["network_type"])
  1285. }
  1286. return nil
  1287. }
  1288. func checkExpectedUniqueUserLogFields(
  1289. runConfig *runServerConfig,
  1290. fields map[string]interface{}) error {
  1291. for _, name := range []string{
  1292. "session_id",
  1293. "last_connected",
  1294. "propagation_channel_id",
  1295. "sponsor_id",
  1296. "client_platform",
  1297. "tunnel_whole_device",
  1298. "device_region",
  1299. } {
  1300. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1301. return fmt.Errorf("missing expected field '%s'", name)
  1302. }
  1303. }
  1304. return nil
  1305. }
  1306. func makeTunneledWebRequest(
  1307. t *testing.T,
  1308. localHTTPProxyPort int,
  1309. requestURL, expectedResponseBody string) error {
  1310. roundTripTimeout := 30 * time.Second
  1311. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  1312. if err != nil {
  1313. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  1314. }
  1315. httpClient := &http.Client{
  1316. Transport: &http.Transport{
  1317. Proxy: http.ProxyURL(proxyUrl),
  1318. },
  1319. Timeout: roundTripTimeout,
  1320. }
  1321. response, err := httpClient.Get(requestURL)
  1322. if err != nil {
  1323. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  1324. }
  1325. body, err := ioutil.ReadAll(response.Body)
  1326. if err != nil {
  1327. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  1328. }
  1329. response.Body.Close()
  1330. if string(body) != expectedResponseBody {
  1331. return fmt.Errorf("unexpected proxied HTTP response")
  1332. }
  1333. return nil
  1334. }
  1335. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  1336. timeout := 20 * time.Second
  1337. var err error
  1338. for _, testHostname := range []string{"time.google.com", "time.nist.gov", "pool.ntp.org"} {
  1339. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  1340. if err == nil {
  1341. break
  1342. }
  1343. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  1344. }
  1345. return err
  1346. }
  1347. var nextUDPProxyPort = 7300
  1348. func makeTunneledNTPRequestAttempt(
  1349. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  1350. nextUDPProxyPort++
  1351. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  1352. if err != nil {
  1353. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  1354. }
  1355. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  1356. // handles it, and then terminates.
  1357. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  1358. if waitGroup != nil {
  1359. defer waitGroup.Done()
  1360. }
  1361. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  1362. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  1363. if err != nil {
  1364. t.Logf("ListenUDP for %s failed: %s", destination, err)
  1365. return
  1366. }
  1367. defer serverUDPConn.Close()
  1368. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  1369. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  1370. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  1371. buffer[udpgwPreambleSize:])
  1372. if err != nil {
  1373. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  1374. return
  1375. }
  1376. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  1377. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  1378. if err != nil {
  1379. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  1380. return
  1381. }
  1382. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  1383. if err != nil {
  1384. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  1385. return
  1386. }
  1387. defer socksTCPConn.Close()
  1388. flags := uint8(0)
  1389. if destinationPort == 53 {
  1390. flags = udpgwProtocolFlagDNS
  1391. }
  1392. err = writeUdpgwPreamble(
  1393. udpgwPreambleSize,
  1394. flags,
  1395. 0,
  1396. destinationIP,
  1397. destinationPort,
  1398. uint16(packetSize),
  1399. buffer)
  1400. if err != nil {
  1401. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  1402. return
  1403. }
  1404. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  1405. if err != nil {
  1406. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  1407. return
  1408. }
  1409. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  1410. if err != nil {
  1411. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  1412. return
  1413. }
  1414. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  1415. if err != nil {
  1416. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  1417. return
  1418. }
  1419. }
  1420. // Tunneled DNS request
  1421. waitGroup := new(sync.WaitGroup)
  1422. waitGroup.Add(1)
  1423. go localUDPProxy(
  1424. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  1425. 53,
  1426. waitGroup)
  1427. // TODO: properly synchronize with local UDP proxy startup
  1428. time.Sleep(1 * time.Second)
  1429. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  1430. if err != nil {
  1431. return fmt.Errorf("DialUDP failed: %s", err)
  1432. }
  1433. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  1434. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  1435. addrs, _, err := psiphon.ResolveIP(testHostname, clientUDPConn)
  1436. clientUDPConn.Close()
  1437. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  1438. err = errors.New("no address")
  1439. }
  1440. if err != nil {
  1441. return fmt.Errorf("ResolveIP failed: %s", err)
  1442. }
  1443. waitGroup.Wait()
  1444. // Tunneled NTP request
  1445. waitGroup = new(sync.WaitGroup)
  1446. waitGroup.Add(1)
  1447. go localUDPProxy(
  1448. addrs[0][len(addrs[0])-4:],
  1449. 123,
  1450. waitGroup)
  1451. // TODO: properly synchronize with local UDP proxy startup
  1452. time.Sleep(1 * time.Second)
  1453. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  1454. if err != nil {
  1455. return fmt.Errorf("DialUDP failed: %s", err)
  1456. }
  1457. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  1458. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  1459. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  1460. ntpData := make([]byte, 48)
  1461. ntpData[0] = 3<<3 | 3
  1462. _, err = clientUDPConn.Write(ntpData)
  1463. if err != nil {
  1464. clientUDPConn.Close()
  1465. return fmt.Errorf("NTP Write failed: %s", err)
  1466. }
  1467. _, err = clientUDPConn.Read(ntpData)
  1468. if err != nil {
  1469. clientUDPConn.Close()
  1470. return fmt.Errorf("NTP Read failed: %s", err)
  1471. }
  1472. clientUDPConn.Close()
  1473. var sec, frac uint64
  1474. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  1475. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  1476. nsec := sec * 1e9
  1477. nsec += (frac * 1e9) >> 32
  1478. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  1479. now := time.Now()
  1480. diff := ntpNow.Sub(now)
  1481. if diff < 0 {
  1482. diff = -diff
  1483. }
  1484. if diff > 1*time.Minute {
  1485. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  1486. }
  1487. waitGroup.Wait()
  1488. return nil
  1489. }
  1490. func pavePsinetDatabaseFile(
  1491. t *testing.T,
  1492. useDefaultSponsorID bool,
  1493. psinetFilename string,
  1494. validServerEntryTags []string) (string, string) {
  1495. sponsorID := prng.HexString(8)
  1496. defaultSponsorID := ""
  1497. if useDefaultSponsorID {
  1498. defaultSponsorID = sponsorID
  1499. }
  1500. fakeDomain := prng.HexString(4)
  1501. fakePath := prng.HexString(4)
  1502. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  1503. psinetJSONFormat := `
  1504. {
  1505. "default_sponsor_id" : "%s",
  1506. "sponsors": {
  1507. "%s": {
  1508. "home_pages": {
  1509. "None": [
  1510. {
  1511. "region": null,
  1512. "url": "%s"
  1513. }
  1514. ]
  1515. }
  1516. }
  1517. },
  1518. "valid_server_entry_tags" : {
  1519. %s
  1520. }
  1521. }
  1522. `
  1523. validServerEntryTagsJSON := ""
  1524. for _, serverEntryTag := range validServerEntryTags {
  1525. if len(validServerEntryTagsJSON) > 0 {
  1526. validServerEntryTagsJSON += ", "
  1527. }
  1528. validServerEntryTagsJSON += fmt.Sprintf("\"%s\" : true", serverEntryTag)
  1529. }
  1530. psinetJSON := fmt.Sprintf(
  1531. psinetJSONFormat,
  1532. defaultSponsorID,
  1533. sponsorID,
  1534. expectedHomepageURL,
  1535. validServerEntryTagsJSON)
  1536. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  1537. if err != nil {
  1538. t.Fatalf("error paving psinet database file: %s", err)
  1539. }
  1540. return sponsorID, expectedHomepageURL
  1541. }
  1542. func paveTrafficRulesFile(
  1543. t *testing.T,
  1544. trafficRulesFilename string,
  1545. propagationChannelID string,
  1546. accessType string,
  1547. authorizationID string,
  1548. requireAuthorization bool,
  1549. deny bool,
  1550. livenessTestSize int) {
  1551. // Test both default and fast lookups
  1552. if intLookupThreshold != 10 {
  1553. t.Fatalf("unexpected intLookupThreshold")
  1554. }
  1555. TCPPorts := fmt.Sprintf("%d", mockWebServerPort)
  1556. UDPPorts := "53, 123, 10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008, 10009, 10010"
  1557. allowTCPPorts := TCPPorts
  1558. allowUDPPorts := UDPPorts
  1559. disallowTCPPorts := "0"
  1560. disallowUDPPorts := "0"
  1561. if deny {
  1562. allowTCPPorts = "0"
  1563. allowUDPPorts = "0"
  1564. disallowTCPPorts = TCPPorts
  1565. disallowUDPPorts = UDPPorts
  1566. }
  1567. authorizationFilterFormat := `,
  1568. "AuthorizedAccessTypes" : ["%s"],
  1569. "ActiveAuthorizationIDs" : ["%s"]
  1570. `
  1571. authorizationFilter := ""
  1572. if requireAuthorization {
  1573. authorizationFilter = fmt.Sprintf(
  1574. authorizationFilterFormat, accessType, authorizationID)
  1575. }
  1576. // Supports two traffic rule test cases:
  1577. //
  1578. // 1. no ports are allowed until after the filtered rule is applied
  1579. // 2. no required ports are allowed (deny = true)
  1580. trafficRulesJSONFormat := `
  1581. {
  1582. "DefaultRules" : {
  1583. "RateLimits" : {
  1584. "ReadBytesPerSecond": 16384,
  1585. "WriteBytesPerSecond": 16384,
  1586. "ReadUnthrottledBytes": %d,
  1587. "WriteUnthrottledBytes": %d
  1588. },
  1589. "AllowTCPPorts" : [0],
  1590. "AllowUDPPorts" : [0],
  1591. "MeekRateLimiterHistorySize" : 10,
  1592. "MeekRateLimiterThresholdSeconds" : 1,
  1593. "MeekRateLimiterGarbageCollectionTriggerCount" : 1,
  1594. "MeekRateLimiterReapHistoryFrequencySeconds" : 1,
  1595. "MeekRateLimiterRegions" : []
  1596. },
  1597. "FilteredRules" : [
  1598. {
  1599. "Filter" : {
  1600. "HandshakeParameters" : {
  1601. "propagation_channel_id" : ["%s"]
  1602. }%s
  1603. },
  1604. "Rules" : {
  1605. "RateLimits" : {
  1606. "ReadBytesPerSecond": 2097152,
  1607. "WriteBytesPerSecond": 2097152
  1608. },
  1609. "AllowTCPPorts" : [%s],
  1610. "AllowUDPPorts" : [%s],
  1611. "DisallowTCPPorts" : [%s],
  1612. "DisallowUDPPorts" : [%s]
  1613. }
  1614. }
  1615. ]
  1616. }
  1617. `
  1618. trafficRulesJSON := fmt.Sprintf(
  1619. trafficRulesJSONFormat,
  1620. livenessTestSize, livenessTestSize,
  1621. propagationChannelID, authorizationFilter,
  1622. allowTCPPorts, allowUDPPorts, disallowTCPPorts, disallowUDPPorts)
  1623. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  1624. if err != nil {
  1625. t.Fatalf("error paving traffic rules file: %s", err)
  1626. }
  1627. }
  1628. var expectedNumSLOKs = 3
  1629. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  1630. oslConfigJSONFormat := `
  1631. {
  1632. "Schemes" : [
  1633. {
  1634. "Epoch" : "%s",
  1635. "Regions" : [],
  1636. "PropagationChannelIDs" : ["%s"],
  1637. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  1638. "SeedSpecs" : [
  1639. {
  1640. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  1641. "UpstreamSubnets" : ["0.0.0.0/0"],
  1642. "Targets" :
  1643. {
  1644. "BytesRead" : 1,
  1645. "BytesWritten" : 1,
  1646. "PortForwardDurationNanoseconds" : 1
  1647. }
  1648. },
  1649. {
  1650. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  1651. "UpstreamSubnets" : ["0.0.0.0/0"],
  1652. "Targets" :
  1653. {
  1654. "BytesRead" : 1,
  1655. "BytesWritten" : 1,
  1656. "PortForwardDurationNanoseconds" : 1
  1657. }
  1658. }
  1659. ],
  1660. "SeedSpecThreshold" : 2,
  1661. "SeedPeriodNanoseconds" : 2592000000000000,
  1662. "SeedPeriodKeySplits": [
  1663. {
  1664. "Total": 2,
  1665. "Threshold": 2
  1666. }
  1667. ]
  1668. },
  1669. {
  1670. "Epoch" : "%s",
  1671. "Regions" : [],
  1672. "PropagationChannelIDs" : ["%s"],
  1673. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  1674. "SeedSpecs" : [
  1675. {
  1676. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  1677. "UpstreamSubnets" : ["0.0.0.0/0"],
  1678. "Targets" :
  1679. {
  1680. "BytesRead" : 1,
  1681. "BytesWritten" : 1,
  1682. "PortForwardDurationNanoseconds" : 1
  1683. }
  1684. }
  1685. ],
  1686. "SeedSpecThreshold" : 1,
  1687. "SeedPeriodNanoseconds" : 2592000000000000,
  1688. "SeedPeriodKeySplits": [
  1689. {
  1690. "Total": 1,
  1691. "Threshold": 1
  1692. }
  1693. ]
  1694. }
  1695. ]
  1696. }
  1697. `
  1698. propagationChannelID := prng.HexString(8)
  1699. now := time.Now().UTC()
  1700. epoch := now.Truncate(720 * time.Hour)
  1701. epochStr := epoch.Format(time.RFC3339Nano)
  1702. oslConfigJSON := fmt.Sprintf(
  1703. oslConfigJSONFormat,
  1704. epochStr, propagationChannelID,
  1705. epochStr, propagationChannelID)
  1706. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  1707. if err != nil {
  1708. t.Fatalf("error paving osl config file: %s", err)
  1709. }
  1710. return propagationChannelID
  1711. }
  1712. func paveTacticsConfigFile(
  1713. t *testing.T, tacticsConfigFilename string,
  1714. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey string,
  1715. tunnelProtocol string,
  1716. propagationChannelID string,
  1717. livenessTestSize int,
  1718. doBurstMonitor bool) {
  1719. // Setting LimitTunnelProtocols passively exercises the
  1720. // server-side LimitTunnelProtocols enforcement.
  1721. tacticsConfigJSONFormat := `
  1722. {
  1723. "RequestPublicKey" : "%s",
  1724. "RequestPrivateKey" : "%s",
  1725. "RequestObfuscatedKey" : "%s",
  1726. "DefaultTactics" : {
  1727. "TTL" : "60s",
  1728. "Probability" : 1.0,
  1729. "Parameters" : {
  1730. %s
  1731. "LimitTunnelProtocols" : ["%s"],
  1732. "FragmentorLimitProtocols" : ["%s"],
  1733. "FragmentorProbability" : 1.0,
  1734. "FragmentorMinTotalBytes" : 1000,
  1735. "FragmentorMaxTotalBytes" : 2000,
  1736. "FragmentorMinWriteBytes" : 1,
  1737. "FragmentorMaxWriteBytes" : 100,
  1738. "FragmentorMinDelay" : "1ms",
  1739. "FragmentorMaxDelay" : "10ms",
  1740. "FragmentorDownstreamLimitProtocols" : ["%s"],
  1741. "FragmentorDownstreamProbability" : 1.0,
  1742. "FragmentorDownstreamMinTotalBytes" : 1000,
  1743. "FragmentorDownstreamMaxTotalBytes" : 2000,
  1744. "FragmentorDownstreamMinWriteBytes" : 1,
  1745. "FragmentorDownstreamMaxWriteBytes" : 100,
  1746. "FragmentorDownstreamMinDelay" : "1ms",
  1747. "FragmentorDownstreamMaxDelay" : "10ms",
  1748. "LivenessTestMinUpstreamBytes" : %d,
  1749. "LivenessTestMaxUpstreamBytes" : %d,
  1750. "LivenessTestMinDownstreamBytes" : %d,
  1751. "LivenessTestMaxDownstreamBytes" : %d,
  1752. "BPFServerTCPProgram": {
  1753. "Name" : "test-server-bpf",
  1754. "Instructions" : [
  1755. {"Op": "RetConstant", "Args": {"Val": 65535}}]},
  1756. "BPFServerTCPProbability" : 1.0,
  1757. "BPFClientTCPProgram": {
  1758. "Name" : "test-client-bpf",
  1759. "Instructions" : [
  1760. {"Op": "RetConstant", "Args": {"Val": 65535}}]},
  1761. "BPFClientTCPProbability" : 1.0,
  1762. "ServerPacketManipulationSpecs" : [{"Name": "test-packetman-spec", "PacketSpecs": [["TCP-flags S"]]}],
  1763. "ServerPacketManipulationProbability" : 1.0,
  1764. "ServerProtocolPacketManipulations": {"All" : ["test-packetman-spec"]}
  1765. }
  1766. },
  1767. "FilteredTactics" : [
  1768. {
  1769. "Filter" : {
  1770. "APIParameters" : {"propagation_channel_id" : ["%s"]},
  1771. "SpeedTestRTTMilliseconds" : {
  1772. "Aggregation" : "Median",
  1773. "AtLeast" : 1
  1774. }
  1775. },
  1776. "Tactics" : {
  1777. "Parameters" : {
  1778. "TunnelConnectTimeout" : "20s",
  1779. "TunnelRateLimits" : {"WriteBytesPerSecond": 1000000},
  1780. "TransformHostNameProbability" : 1.0,
  1781. "PickUserAgentProbability" : 1.0,
  1782. "ApplicationParameters" : {
  1783. "AppFlag1" : true,
  1784. "AppConfig1" : {"Option1" : "A", "Option2" : "B"},
  1785. "AppSwitches1" : [1, 2, 3, 4]
  1786. }
  1787. }
  1788. }
  1789. }
  1790. ]
  1791. }
  1792. `
  1793. burstParameters := ""
  1794. if doBurstMonitor {
  1795. burstParameters = `
  1796. "ServerBurstUpstreamDeadline" : "100ms",
  1797. "ServerBurstUpstreamTargetBytes" : 1000,
  1798. "ServerBurstDownstreamDeadline" : "100ms",
  1799. "ServerBurstDownstreamTargetBytes" : 100000,
  1800. "ClientBurstUpstreamDeadline" : "100ms",
  1801. "ClientBurstUpstreamTargetBytes" : 1000,
  1802. "ClientBurstDownstreamDeadline" : "100ms",
  1803. "ClientBurstDownstreamTargetBytes" : 100000,
  1804. `
  1805. }
  1806. tacticsConfigJSON := fmt.Sprintf(
  1807. tacticsConfigJSONFormat,
  1808. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  1809. burstParameters,
  1810. tunnelProtocol,
  1811. tunnelProtocol,
  1812. tunnelProtocol,
  1813. livenessTestSize, livenessTestSize, livenessTestSize, livenessTestSize,
  1814. propagationChannelID)
  1815. err := ioutil.WriteFile(tacticsConfigFilename, []byte(tacticsConfigJSON), 0600)
  1816. if err != nil {
  1817. t.Fatalf("error paving tactics config file: %s", err)
  1818. }
  1819. }
  1820. func paveBlocklistFile(t *testing.T, blocklistFilename string) {
  1821. blocklistContent :=
  1822. "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"
  1823. err := ioutil.WriteFile(blocklistFilename, []byte(blocklistContent), 0600)
  1824. if err != nil {
  1825. t.Fatalf("error paving blocklist file: %s", err)
  1826. }
  1827. }
  1828. func sendNotificationReceived(c chan<- struct{}) {
  1829. select {
  1830. case c <- struct{}{}:
  1831. default:
  1832. }
  1833. }
  1834. func waitOnNotification(t *testing.T, c, timeoutSignal <-chan struct{}, timeoutMessage string) {
  1835. if timeoutSignal == nil {
  1836. <-c
  1837. } else {
  1838. select {
  1839. case <-c:
  1840. case <-timeoutSignal:
  1841. t.Fatalf(timeoutMessage)
  1842. }
  1843. }
  1844. }
  1845. type pruneServerEntryTestCase struct {
  1846. IPAddress string
  1847. ExplicitTag bool
  1848. ExpectedTag string
  1849. LocalTimestamp string
  1850. PsinetValid bool
  1851. ExpectPrune bool
  1852. IsEmbedded bool
  1853. DialPort0 bool
  1854. ServerEntryFields protocol.ServerEntryFields
  1855. }
  1856. func initializePruneServerEntriesTest(
  1857. t *testing.T,
  1858. runConfig *runServerConfig) ([]*pruneServerEntryTestCase, []string, int) {
  1859. if !runConfig.doPruneServerEntries {
  1860. return nil, nil, 0
  1861. }
  1862. newTimeStamp := time.Now().UTC().Format(time.RFC3339)
  1863. oldTimeStamp := time.Now().Add(-30 * 24 * time.Hour).UTC().Format(time.RFC3339)
  1864. // Test Cases:
  1865. // - ExplicitTag: server entry includes a tag; vs. generate a derived tag
  1866. // - LocalTimestamp: server entry is sufficiently old to be pruned; vs. not
  1867. // - PsinetValid: server entry is reported valid by psinet; vs. deleted
  1868. // - ExpectPrune: prune outcome based on flags above
  1869. // - IsEmbedded: pruned embedded server entries leave a tombstone and cannot
  1870. // be reimported
  1871. // - DialPort0: set dial port to 0, a special prune case (see statusAPIRequestHandler)
  1872. pruneServerEntryTestCases := []*pruneServerEntryTestCase{
  1873. &pruneServerEntryTestCase{IPAddress: "192.0.2.1", ExplicitTag: true, LocalTimestamp: newTimeStamp, PsinetValid: true, ExpectPrune: false},
  1874. &pruneServerEntryTestCase{IPAddress: "192.0.2.2", ExplicitTag: false, LocalTimestamp: newTimeStamp, PsinetValid: true, ExpectPrune: false},
  1875. &pruneServerEntryTestCase{IPAddress: "192.0.2.3", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: false},
  1876. &pruneServerEntryTestCase{IPAddress: "192.0.2.4", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: false},
  1877. &pruneServerEntryTestCase{IPAddress: "192.0.2.5", ExplicitTag: true, LocalTimestamp: newTimeStamp, PsinetValid: false, ExpectPrune: false},
  1878. &pruneServerEntryTestCase{IPAddress: "192.0.2.6", ExplicitTag: false, LocalTimestamp: newTimeStamp, PsinetValid: false, ExpectPrune: false},
  1879. &pruneServerEntryTestCase{IPAddress: "192.0.2.7", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: false},
  1880. &pruneServerEntryTestCase{IPAddress: "192.0.2.8", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: false},
  1881. &pruneServerEntryTestCase{IPAddress: "192.0.2.9", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: true},
  1882. &pruneServerEntryTestCase{IPAddress: "192.0.2.10", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: true},
  1883. &pruneServerEntryTestCase{IPAddress: "192.0.2.11", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: false, DialPort0: true},
  1884. &pruneServerEntryTestCase{IPAddress: "192.0.2.12", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: true, DialPort0: true},
  1885. &pruneServerEntryTestCase{IPAddress: "192.0.2.13", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: true, DialPort0: true},
  1886. }
  1887. for _, testCase := range pruneServerEntryTestCases {
  1888. dialPort := 4000
  1889. if testCase.DialPort0 {
  1890. dialPort = 0
  1891. }
  1892. _, _, _, _, encodedServerEntry, err := GenerateConfig(
  1893. &GenerateConfigParams{
  1894. ServerIPAddress: testCase.IPAddress,
  1895. WebServerPort: 8000,
  1896. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: dialPort},
  1897. })
  1898. if err != nil {
  1899. t.Fatalf("GenerateConfig failed: %s", err)
  1900. }
  1901. serverEntrySource := protocol.SERVER_ENTRY_SOURCE_REMOTE
  1902. if testCase.IsEmbedded {
  1903. serverEntrySource = protocol.SERVER_ENTRY_SOURCE_EMBEDDED
  1904. }
  1905. serverEntryFields, err := protocol.DecodeServerEntryFields(
  1906. string(encodedServerEntry),
  1907. testCase.LocalTimestamp,
  1908. serverEntrySource)
  1909. if err != nil {
  1910. t.Fatalf("DecodeServerEntryFields failed: %s", err)
  1911. }
  1912. if testCase.ExplicitTag {
  1913. testCase.ExpectedTag = prng.Base64String(32)
  1914. serverEntryFields.SetTag(testCase.ExpectedTag)
  1915. } else {
  1916. testCase.ExpectedTag = protocol.GenerateServerEntryTag(
  1917. serverEntryFields.GetIPAddress(),
  1918. serverEntryFields.GetWebServerSecret())
  1919. }
  1920. testCase.ServerEntryFields = serverEntryFields
  1921. }
  1922. psinetValidServerEntryTags := make([]string, 0)
  1923. expectedNumPruneNotices := 0
  1924. for _, testCase := range pruneServerEntryTestCases {
  1925. if testCase.PsinetValid {
  1926. psinetValidServerEntryTags = append(
  1927. psinetValidServerEntryTags, testCase.ExpectedTag)
  1928. }
  1929. if testCase.ExpectPrune {
  1930. expectedNumPruneNotices += 1
  1931. }
  1932. }
  1933. return pruneServerEntryTestCases,
  1934. psinetValidServerEntryTags,
  1935. expectedNumPruneNotices
  1936. }
  1937. func storePruneServerEntriesTest(
  1938. t *testing.T,
  1939. runConfig *runServerConfig,
  1940. testDataDirName string,
  1941. pruneServerEntryTestCases []*pruneServerEntryTestCase) {
  1942. if !runConfig.doPruneServerEntries {
  1943. return
  1944. }
  1945. for _, testCase := range pruneServerEntryTestCases {
  1946. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  1947. if err != nil {
  1948. t.Fatalf("StoreServerEntry failed: %s", err)
  1949. }
  1950. }
  1951. clientConfig := &psiphon.Config{
  1952. SponsorId: "0",
  1953. PropagationChannelId: "0",
  1954. // DataRootDirectory must to be set to avoid a migration in the current
  1955. // working directory.
  1956. DataRootDirectory: testDataDirName,
  1957. }
  1958. err := clientConfig.Commit(false)
  1959. if err != nil {
  1960. t.Fatalf("Commit failed: %s", err)
  1961. }
  1962. applyParameters := make(map[string]interface{})
  1963. applyParameters[parameters.RecordFailedTunnelPersistentStatsProbability] = 1.0
  1964. err = clientConfig.SetParameters("", true, applyParameters)
  1965. if err != nil {
  1966. t.Fatalf("SetParameters failed: %s", err)
  1967. }
  1968. verifyTestCasesStored := make(verifyTestCasesStoredLookup)
  1969. for _, testCase := range pruneServerEntryTestCases {
  1970. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  1971. }
  1972. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  1973. t *testing.T,
  1974. testCase *pruneServerEntryTestCase,
  1975. serverEntry *protocol.ServerEntry) {
  1976. verifyTestCasesStored.isStored(testCase.IPAddress)
  1977. // Check that random tag was retained or derived tag was calculated as
  1978. // expected
  1979. if serverEntry.Tag != testCase.ExpectedTag {
  1980. t.Fatalf("unexpected tag for %s got %s expected %s",
  1981. testCase.IPAddress, serverEntry.Tag, testCase.ExpectedTag)
  1982. }
  1983. // Create failed tunnel event records to exercise pruning
  1984. dialParams, err := psiphon.MakeDialParameters(
  1985. clientConfig,
  1986. nil,
  1987. func(_ *protocol.ServerEntry, _ string) bool { return true },
  1988. func(serverEntry *protocol.ServerEntry) (string, bool) {
  1989. return runConfig.tunnelProtocol, true
  1990. },
  1991. serverEntry,
  1992. false,
  1993. 0,
  1994. 0)
  1995. if err != nil {
  1996. t.Fatalf("MakeDialParameters failed: %s", err)
  1997. }
  1998. err = psiphon.RecordFailedTunnelStat(
  1999. clientConfig, dialParams, nil, 0, 0, errors.New("test error"))
  2000. if err != nil {
  2001. t.Fatalf("RecordFailedTunnelStat failed: %s", err)
  2002. }
  2003. })
  2004. verifyTestCasesStored.checkStored(
  2005. t, "missing prune test case server entries")
  2006. }
  2007. func checkPruneServerEntriesTest(
  2008. t *testing.T,
  2009. runConfig *runServerConfig,
  2010. testDataDirName string,
  2011. pruneServerEntryTestCases []*pruneServerEntryTestCase) {
  2012. if !runConfig.doPruneServerEntries {
  2013. return
  2014. }
  2015. clientConfig := &psiphon.Config{
  2016. SponsorId: "0",
  2017. PropagationChannelId: "0",
  2018. // DataRootDirectory must to be set to avoid a migration in the current
  2019. // working directory.
  2020. DataRootDirectory: testDataDirName,
  2021. }
  2022. err := clientConfig.Commit(false)
  2023. if err != nil {
  2024. t.Fatalf("Commit failed: %s", err)
  2025. }
  2026. // Check that server entries remain or are pruned as expected
  2027. verifyTestCasesStored := make(verifyTestCasesStoredLookup)
  2028. for _, testCase := range pruneServerEntryTestCases {
  2029. if !testCase.ExpectPrune {
  2030. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  2031. }
  2032. }
  2033. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  2034. t *testing.T,
  2035. testCase *pruneServerEntryTestCase,
  2036. serverEntry *protocol.ServerEntry) {
  2037. if testCase.ExpectPrune {
  2038. t.Fatalf("expected prune for %s", testCase.IPAddress)
  2039. } else {
  2040. verifyTestCasesStored.isStored(testCase.IPAddress)
  2041. }
  2042. })
  2043. verifyTestCasesStored.checkStored(
  2044. t, "missing prune test case server entries")
  2045. // Check that pruned server entries reimport or not, as expected
  2046. for _, testCase := range pruneServerEntryTestCases {
  2047. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  2048. if err != nil {
  2049. t.Fatalf("StoreServerEntry failed: %s", err)
  2050. }
  2051. }
  2052. verifyTestCasesStored = make(verifyTestCasesStoredLookup)
  2053. for _, testCase := range pruneServerEntryTestCases {
  2054. if !testCase.ExpectPrune || !testCase.IsEmbedded {
  2055. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  2056. }
  2057. }
  2058. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  2059. t *testing.T,
  2060. testCase *pruneServerEntryTestCase,
  2061. serverEntry *protocol.ServerEntry) {
  2062. if testCase.ExpectPrune && testCase.IsEmbedded {
  2063. t.Fatalf("expected tombstone for %s", testCase.IPAddress)
  2064. } else {
  2065. verifyTestCasesStored.isStored(testCase.IPAddress)
  2066. }
  2067. })
  2068. verifyTestCasesStored.checkStored(
  2069. t, "missing reimported prune test case server entries")
  2070. // Non-embedded server entries with tombstones _can_ be reimported
  2071. for _, testCase := range pruneServerEntryTestCases {
  2072. testCase.ServerEntryFields.SetLocalSource(protocol.SERVER_ENTRY_SOURCE_REMOTE)
  2073. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  2074. if err != nil {
  2075. t.Fatalf("StoreServerEntry failed: %s", err)
  2076. }
  2077. }
  2078. verifyTestCasesStored = make(verifyTestCasesStoredLookup)
  2079. for _, testCase := range pruneServerEntryTestCases {
  2080. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  2081. }
  2082. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  2083. t *testing.T,
  2084. testCase *pruneServerEntryTestCase,
  2085. serverEntry *protocol.ServerEntry) {
  2086. verifyTestCasesStored.isStored(testCase.IPAddress)
  2087. })
  2088. verifyTestCasesStored.checkStored(
  2089. t, "missing non-embedded reimported prune test case server entries")
  2090. }
  2091. func scanServerEntries(
  2092. t *testing.T,
  2093. clientConfig *psiphon.Config,
  2094. pruneServerEntryTestCases []*pruneServerEntryTestCase,
  2095. scanner func(
  2096. t *testing.T,
  2097. testCase *pruneServerEntryTestCase,
  2098. serverEntry *protocol.ServerEntry)) {
  2099. _, iterator, err := psiphon.NewServerEntryIterator(clientConfig)
  2100. if err != nil {
  2101. t.Fatalf("NewServerEntryIterator failed: %s", err)
  2102. }
  2103. defer iterator.Close()
  2104. for {
  2105. serverEntry, err := iterator.Next()
  2106. if err != nil {
  2107. t.Fatalf("ServerIterator.Next failed: %s", err)
  2108. }
  2109. if serverEntry == nil {
  2110. break
  2111. }
  2112. for _, testCase := range pruneServerEntryTestCases {
  2113. if testCase.IPAddress == serverEntry.IpAddress {
  2114. scanner(t, testCase, serverEntry)
  2115. break
  2116. }
  2117. }
  2118. }
  2119. }
  2120. type verifyTestCasesStoredLookup map[string]bool
  2121. func (v verifyTestCasesStoredLookup) mustBeStored(s string) {
  2122. v[s] = true
  2123. }
  2124. func (v verifyTestCasesStoredLookup) isStored(s string) {
  2125. delete(v, s)
  2126. }
  2127. func (v verifyTestCasesStoredLookup) checkStored(t *testing.T, errMessage string) {
  2128. if len(v) != 0 {
  2129. t.Fatalf("%s: %+v", errMessage, v)
  2130. }
  2131. }