server_test.go 73 KB

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