server_test.go 61 KB

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