server_test.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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. "sync"
  34. "syscall"
  35. "testing"
  36. "time"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/marionette"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  44. "golang.org/x/net/proxy"
  45. )
  46. var serverIPAddress, testDataDirName string
  47. var mockWebServerURL, mockWebServerExpectedResponse string
  48. var mockWebServerPort = 8080
  49. func TestMain(m *testing.M) {
  50. flag.Parse()
  51. var err error
  52. for _, interfaceName := range []string{"eth0", "en0"} {
  53. var serverIPv4Address, serverIPv6Address net.IP
  54. serverIPv4Address, serverIPv6Address, err = common.GetInterfaceIPAddresses(interfaceName)
  55. if err == nil {
  56. if serverIPv4Address != nil {
  57. serverIPAddress = serverIPv4Address.String()
  58. } else {
  59. serverIPAddress = serverIPv6Address.String()
  60. }
  61. break
  62. }
  63. }
  64. if err != nil {
  65. fmt.Printf("error getting server IP address: %s\n", err)
  66. os.Exit(1)
  67. }
  68. testDataDirName, err = ioutil.TempDir("", "psiphon-server-test")
  69. if err != nil {
  70. fmt.Printf("TempDir failed: %s\n", err)
  71. os.Exit(1)
  72. }
  73. defer os.RemoveAll(testDataDirName)
  74. psiphon.SetEmitDiagnosticNotices(true)
  75. mockWebServerURL, mockWebServerExpectedResponse = runMockWebServer()
  76. os.Exit(m.Run())
  77. }
  78. func runMockWebServer() (string, string) {
  79. responseBody, _ := common.MakeSecureRandomStringHex(100000)
  80. serveMux := http.NewServeMux()
  81. serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  82. w.Write([]byte(responseBody))
  83. })
  84. webServerAddress := fmt.Sprintf("%s:%d", serverIPAddress, mockWebServerPort)
  85. server := &http.Server{
  86. Addr: webServerAddress,
  87. Handler: serveMux,
  88. }
  89. go func() {
  90. err := server.ListenAndServe()
  91. if err != nil {
  92. fmt.Printf("error running mock web server: %s\n", err)
  93. os.Exit(1)
  94. }
  95. }()
  96. // TODO: properly synchronize with web server readiness
  97. time.Sleep(1 * time.Second)
  98. return fmt.Sprintf("http://%s/", webServerAddress), responseBody
  99. }
  100. // Note: not testing fronting meek protocols, which client is
  101. // hard-wired to except running on privileged ports 80 and 443.
  102. func TestSSH(t *testing.T) {
  103. runServer(t,
  104. &runServerConfig{
  105. tunnelProtocol: "SSH",
  106. enableSSHAPIRequests: true,
  107. doHotReload: false,
  108. doDefaultSponsorID: false,
  109. denyTrafficRules: false,
  110. requireAuthorization: true,
  111. omitAuthorization: false,
  112. doTunneledWebRequest: true,
  113. doTunneledNTPRequest: true,
  114. forceFragmenting: false,
  115. })
  116. }
  117. func TestOSSH(t *testing.T) {
  118. runServer(t,
  119. &runServerConfig{
  120. tunnelProtocol: "OSSH",
  121. enableSSHAPIRequests: true,
  122. doHotReload: false,
  123. doDefaultSponsorID: false,
  124. denyTrafficRules: false,
  125. requireAuthorization: true,
  126. omitAuthorization: false,
  127. doTunneledWebRequest: true,
  128. doTunneledNTPRequest: true,
  129. forceFragmenting: false,
  130. })
  131. }
  132. func TestFragmentedOSSH(t *testing.T) {
  133. runServer(t,
  134. &runServerConfig{
  135. tunnelProtocol: "OSSH",
  136. enableSSHAPIRequests: true,
  137. doHotReload: false,
  138. doDefaultSponsorID: false,
  139. denyTrafficRules: false,
  140. requireAuthorization: true,
  141. omitAuthorization: false,
  142. doTunneledWebRequest: true,
  143. doTunneledNTPRequest: true,
  144. forceFragmenting: true,
  145. })
  146. }
  147. func TestUnfrontedMeek(t *testing.T) {
  148. runServer(t,
  149. &runServerConfig{
  150. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  151. enableSSHAPIRequests: true,
  152. doHotReload: false,
  153. doDefaultSponsorID: false,
  154. denyTrafficRules: false,
  155. requireAuthorization: true,
  156. omitAuthorization: false,
  157. doTunneledWebRequest: true,
  158. doTunneledNTPRequest: true,
  159. forceFragmenting: false,
  160. })
  161. }
  162. func TestUnfrontedMeekHTTPS(t *testing.T) {
  163. runServer(t,
  164. &runServerConfig{
  165. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  166. tlsProfile: protocol.TLS_PROFILE_RANDOMIZED,
  167. enableSSHAPIRequests: true,
  168. doHotReload: false,
  169. doDefaultSponsorID: false,
  170. denyTrafficRules: false,
  171. requireAuthorization: true,
  172. omitAuthorization: false,
  173. doTunneledWebRequest: true,
  174. doTunneledNTPRequest: true,
  175. forceFragmenting: false,
  176. })
  177. }
  178. func TestUnfrontedMeekHTTPSTLS13(t *testing.T) {
  179. runServer(t,
  180. &runServerConfig{
  181. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  182. tlsProfile: protocol.TLS_PROFILE_TLS13_RANDOMIZED,
  183. enableSSHAPIRequests: true,
  184. doHotReload: false,
  185. doDefaultSponsorID: false,
  186. denyTrafficRules: false,
  187. requireAuthorization: true,
  188. omitAuthorization: false,
  189. doTunneledWebRequest: true,
  190. doTunneledNTPRequest: true,
  191. forceFragmenting: false,
  192. })
  193. }
  194. func TestUnfrontedMeekSessionTicket(t *testing.T) {
  195. runServer(t,
  196. &runServerConfig{
  197. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  198. tlsProfile: protocol.TLS_PROFILE_RANDOMIZED,
  199. enableSSHAPIRequests: true,
  200. doHotReload: false,
  201. doDefaultSponsorID: false,
  202. denyTrafficRules: false,
  203. requireAuthorization: true,
  204. omitAuthorization: false,
  205. doTunneledWebRequest: true,
  206. doTunneledNTPRequest: true,
  207. forceFragmenting: false,
  208. })
  209. }
  210. func TestUnfrontedMeekSessionTicketTLS13(t *testing.T) {
  211. runServer(t,
  212. &runServerConfig{
  213. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  214. tlsProfile: protocol.TLS_PROFILE_TLS13_RANDOMIZED,
  215. enableSSHAPIRequests: true,
  216. doHotReload: false,
  217. doDefaultSponsorID: false,
  218. denyTrafficRules: false,
  219. requireAuthorization: true,
  220. omitAuthorization: false,
  221. doTunneledWebRequest: true,
  222. doTunneledNTPRequest: true,
  223. forceFragmenting: false,
  224. })
  225. }
  226. func TestQUICOSSH(t *testing.T) {
  227. runServer(t,
  228. &runServerConfig{
  229. tunnelProtocol: "QUIC-OSSH",
  230. enableSSHAPIRequests: true,
  231. doHotReload: false,
  232. doDefaultSponsorID: false,
  233. denyTrafficRules: false,
  234. requireAuthorization: true,
  235. omitAuthorization: false,
  236. doTunneledWebRequest: true,
  237. doTunneledNTPRequest: true,
  238. forceFragmenting: false,
  239. })
  240. }
  241. func TestMarionetteOSSH(t *testing.T) {
  242. if !marionette.Enabled() {
  243. t.Skip("Marionette is not enabled")
  244. }
  245. runServer(t,
  246. &runServerConfig{
  247. tunnelProtocol: "MARIONETTE-OSSH",
  248. enableSSHAPIRequests: true,
  249. doHotReload: false,
  250. doDefaultSponsorID: false,
  251. denyTrafficRules: false,
  252. requireAuthorization: true,
  253. omitAuthorization: false,
  254. doTunneledWebRequest: true,
  255. doTunneledNTPRequest: true,
  256. forceFragmenting: false,
  257. })
  258. }
  259. func TestWebTransportAPIRequests(t *testing.T) {
  260. runServer(t,
  261. &runServerConfig{
  262. tunnelProtocol: "OSSH",
  263. enableSSHAPIRequests: false,
  264. doHotReload: false,
  265. doDefaultSponsorID: false,
  266. denyTrafficRules: false,
  267. requireAuthorization: false,
  268. omitAuthorization: true,
  269. doTunneledWebRequest: true,
  270. doTunneledNTPRequest: true,
  271. forceFragmenting: false,
  272. })
  273. }
  274. func TestHotReload(t *testing.T) {
  275. runServer(t,
  276. &runServerConfig{
  277. tunnelProtocol: "OSSH",
  278. enableSSHAPIRequests: true,
  279. doHotReload: true,
  280. doDefaultSponsorID: false,
  281. denyTrafficRules: false,
  282. requireAuthorization: true,
  283. omitAuthorization: false,
  284. doTunneledWebRequest: true,
  285. doTunneledNTPRequest: true,
  286. forceFragmenting: false,
  287. })
  288. }
  289. func TestDefaultSessionID(t *testing.T) {
  290. runServer(t,
  291. &runServerConfig{
  292. tunnelProtocol: "OSSH",
  293. enableSSHAPIRequests: true,
  294. doHotReload: true,
  295. doDefaultSponsorID: true,
  296. denyTrafficRules: false,
  297. requireAuthorization: true,
  298. omitAuthorization: false,
  299. doTunneledWebRequest: true,
  300. doTunneledNTPRequest: true,
  301. forceFragmenting: false,
  302. })
  303. }
  304. func TestDenyTrafficRules(t *testing.T) {
  305. runServer(t,
  306. &runServerConfig{
  307. tunnelProtocol: "OSSH",
  308. enableSSHAPIRequests: true,
  309. doHotReload: true,
  310. doDefaultSponsorID: false,
  311. denyTrafficRules: true,
  312. requireAuthorization: true,
  313. omitAuthorization: false,
  314. doTunneledWebRequest: true,
  315. doTunneledNTPRequest: true,
  316. forceFragmenting: false,
  317. })
  318. }
  319. func TestOmitAuthorization(t *testing.T) {
  320. runServer(t,
  321. &runServerConfig{
  322. tunnelProtocol: "OSSH",
  323. enableSSHAPIRequests: true,
  324. doHotReload: true,
  325. doDefaultSponsorID: false,
  326. denyTrafficRules: false,
  327. requireAuthorization: true,
  328. omitAuthorization: true,
  329. doTunneledWebRequest: true,
  330. doTunneledNTPRequest: true,
  331. forceFragmenting: false,
  332. })
  333. }
  334. func TestNoAuthorization(t *testing.T) {
  335. runServer(t,
  336. &runServerConfig{
  337. tunnelProtocol: "OSSH",
  338. enableSSHAPIRequests: true,
  339. doHotReload: true,
  340. doDefaultSponsorID: false,
  341. denyTrafficRules: false,
  342. requireAuthorization: false,
  343. omitAuthorization: true,
  344. doTunneledWebRequest: true,
  345. doTunneledNTPRequest: true,
  346. forceFragmenting: false,
  347. })
  348. }
  349. func TestUnusedAuthorization(t *testing.T) {
  350. runServer(t,
  351. &runServerConfig{
  352. tunnelProtocol: "OSSH",
  353. enableSSHAPIRequests: true,
  354. doHotReload: true,
  355. doDefaultSponsorID: false,
  356. denyTrafficRules: false,
  357. requireAuthorization: false,
  358. omitAuthorization: false,
  359. doTunneledWebRequest: true,
  360. doTunneledNTPRequest: true,
  361. forceFragmenting: false,
  362. })
  363. }
  364. func TestTCPOnlySLOK(t *testing.T) {
  365. runServer(t,
  366. &runServerConfig{
  367. tunnelProtocol: "OSSH",
  368. enableSSHAPIRequests: true,
  369. doHotReload: false,
  370. doDefaultSponsorID: false,
  371. denyTrafficRules: false,
  372. requireAuthorization: true,
  373. omitAuthorization: false,
  374. doTunneledWebRequest: true,
  375. doTunneledNTPRequest: false,
  376. forceFragmenting: false,
  377. })
  378. }
  379. func TestUDPOnlySLOK(t *testing.T) {
  380. runServer(t,
  381. &runServerConfig{
  382. tunnelProtocol: "OSSH",
  383. enableSSHAPIRequests: true,
  384. doHotReload: false,
  385. doDefaultSponsorID: false,
  386. denyTrafficRules: false,
  387. requireAuthorization: true,
  388. omitAuthorization: false,
  389. doTunneledWebRequest: false,
  390. doTunneledNTPRequest: true,
  391. forceFragmenting: false,
  392. })
  393. }
  394. type runServerConfig struct {
  395. tunnelProtocol string
  396. tlsProfile string
  397. enableSSHAPIRequests bool
  398. doHotReload bool
  399. doDefaultSponsorID bool
  400. denyTrafficRules bool
  401. requireAuthorization bool
  402. omitAuthorization bool
  403. doTunneledWebRequest bool
  404. doTunneledNTPRequest bool
  405. forceFragmenting bool
  406. }
  407. func runServer(t *testing.T, runConfig *runServerConfig) {
  408. // configure authorized access
  409. accessType := "test-access-type"
  410. accessControlSigningKey, accessControlVerificationKey, err := accesscontrol.NewKeyPair(accessType)
  411. if err != nil {
  412. t.Fatalf("error creating access control key pair: %s", err)
  413. }
  414. accessControlVerificationKeyRing := accesscontrol.VerificationKeyRing{
  415. Keys: []*accesscontrol.VerificationKey{accessControlVerificationKey},
  416. }
  417. var authorizationID [32]byte
  418. clientAuthorization, err := accesscontrol.IssueAuthorization(
  419. accessControlSigningKey,
  420. authorizationID[:],
  421. time.Now().Add(1*time.Hour))
  422. if err != nil {
  423. t.Fatalf("error issuing authorization: %s", err)
  424. }
  425. // Enable tactics when the test protocol is meek. Both the client and the
  426. // server will be configured to support tactics. The client config will be
  427. // set with a nonfunctional config so that the tactics request must
  428. // succeed, overriding the nonfunctional values, for the tunnel to
  429. // establish.
  430. doClientTactics := protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol)
  431. doServerTactics := doClientTactics || runConfig.forceFragmenting
  432. // All servers require a tactics config with valid keys.
  433. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err :=
  434. tactics.GenerateKeys()
  435. if err != nil {
  436. t.Fatalf("error generating tactics keys: %s", err)
  437. }
  438. // create a server
  439. psiphonServerIPAddress := serverIPAddress
  440. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) ||
  441. protocol.TunnelProtocolUsesMarionette(runConfig.tunnelProtocol) {
  442. // Workaround for macOS firewall.
  443. psiphonServerIPAddress = "127.0.0.1"
  444. }
  445. generateConfigParams := &GenerateConfigParams{
  446. ServerIPAddress: psiphonServerIPAddress,
  447. EnableSSHAPIRequests: runConfig.enableSSHAPIRequests,
  448. WebServerPort: 8000,
  449. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: 4000},
  450. }
  451. if protocol.TunnelProtocolUsesMarionette(runConfig.tunnelProtocol) {
  452. generateConfigParams.TunnelProtocolPorts[runConfig.tunnelProtocol] = 0
  453. generateConfigParams.MarionetteFormat = "http_simple_nonblocking"
  454. }
  455. if doServerTactics {
  456. generateConfigParams.TacticsRequestPublicKey = tacticsRequestPublicKey
  457. generateConfigParams.TacticsRequestObfuscatedKey = tacticsRequestObfuscatedKey
  458. }
  459. serverConfigJSON, _, _, _, encodedServerEntry, err := GenerateConfig(generateConfigParams)
  460. if err != nil {
  461. t.Fatalf("error generating server config: %s", err)
  462. }
  463. // customize server config
  464. // Pave psinet with random values to test handshake homepages.
  465. psinetFilename := filepath.Join(testDataDirName, "psinet.json")
  466. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(
  467. t, runConfig.doDefaultSponsorID, psinetFilename)
  468. // Pave OSL config for SLOK testing
  469. oslConfigFilename := filepath.Join(testDataDirName, "osl_config.json")
  470. propagationChannelID := paveOSLConfigFile(t, oslConfigFilename)
  471. // Pave traffic rules file which exercises handshake parameter filtering. Client
  472. // must handshake with specified sponsor ID in order to allow ports for tunneled
  473. // requests.
  474. trafficRulesFilename := filepath.Join(testDataDirName, "traffic_rules.json")
  475. paveTrafficRulesFile(
  476. t, trafficRulesFilename, propagationChannelID, accessType,
  477. runConfig.requireAuthorization, runConfig.denyTrafficRules)
  478. var tacticsConfigFilename string
  479. // Only pave the tactics config when tactics are required. This exercises the
  480. // case where the tactics config is omitted.
  481. if doServerTactics {
  482. tacticsConfigFilename = filepath.Join(testDataDirName, "tactics_config.json")
  483. paveTacticsConfigFile(
  484. t, tacticsConfigFilename,
  485. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  486. runConfig.tunnelProtocol,
  487. propagationChannelID)
  488. }
  489. var serverConfig map[string]interface{}
  490. json.Unmarshal(serverConfigJSON, &serverConfig)
  491. serverConfig["GeoIPDatabaseFilename"] = ""
  492. serverConfig["PsinetDatabaseFilename"] = psinetFilename
  493. serverConfig["TrafficRulesFilename"] = trafficRulesFilename
  494. serverConfig["OSLConfigFilename"] = oslConfigFilename
  495. if doServerTactics {
  496. serverConfig["TacticsConfigFilename"] = tacticsConfigFilename
  497. }
  498. serverConfig["LogFilename"] = filepath.Join(testDataDirName, "psiphond.log")
  499. serverConfig["LogLevel"] = "debug"
  500. serverConfig["AccessControlVerificationKeyRing"] = accessControlVerificationKeyRing
  501. // Set this parameter so at least the semaphore functions are called.
  502. // TODO: test that the concurrency limit is correctly enforced.
  503. serverConfig["MaxConcurrentSSHHandshakes"] = 1
  504. // Exercise this option.
  505. serverConfig["PeriodicGarbageCollectionSeconds"] = 1
  506. serverConfigJSON, _ = json.Marshal(serverConfig)
  507. // run server
  508. serverWaitGroup := new(sync.WaitGroup)
  509. serverWaitGroup.Add(1)
  510. go func() {
  511. defer serverWaitGroup.Done()
  512. err := RunServices(serverConfigJSON)
  513. if err != nil {
  514. // TODO: wrong goroutine for t.FatalNow()
  515. t.Fatalf("error running server: %s", err)
  516. }
  517. }()
  518. defer func() {
  519. // Test: orderly server shutdown
  520. p, _ := os.FindProcess(os.Getpid())
  521. p.Signal(os.Interrupt)
  522. shutdownTimeout := time.NewTimer(5 * time.Second)
  523. shutdownOk := make(chan struct{}, 1)
  524. go func() {
  525. serverWaitGroup.Wait()
  526. shutdownOk <- *new(struct{})
  527. }()
  528. select {
  529. case <-shutdownOk:
  530. case <-shutdownTimeout.C:
  531. t.Fatalf("server shutdown timeout exceeded")
  532. }
  533. }()
  534. // TODO: monitor logs for more robust wait-until-loaded. For example,
  535. // especially with the race detector on, QUIC-OSSH tests can fail as the
  536. // client sends its initial pacjet before the server is ready.
  537. time.Sleep(1 * time.Second)
  538. // Test: hot reload (of psinet and traffic rules)
  539. if runConfig.doHotReload {
  540. // Pave new config files with different random values.
  541. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(
  542. t, runConfig.doDefaultSponsorID, psinetFilename)
  543. propagationChannelID = paveOSLConfigFile(t, oslConfigFilename)
  544. paveTrafficRulesFile(
  545. t, trafficRulesFilename, propagationChannelID, accessType,
  546. runConfig.requireAuthorization, runConfig.denyTrafficRules)
  547. p, _ := os.FindProcess(os.Getpid())
  548. p.Signal(syscall.SIGUSR1)
  549. // TODO: monitor logs for more robust wait-until-reloaded
  550. time.Sleep(1 * time.Second)
  551. // After reloading psinet, the new sponsorID/expectedHomepageURL
  552. // should be active, as tested in the client "Homepage" notice
  553. // handler below.
  554. }
  555. // Exercise server_load logging
  556. p, _ := os.FindProcess(os.Getpid())
  557. p.Signal(syscall.SIGUSR2)
  558. // connect to server with client
  559. // TODO: currently, TargetServerEntry only works with one tunnel
  560. numTunnels := 1
  561. localSOCKSProxyPort := 1081
  562. localHTTPProxyPort := 8081
  563. jsonNetworkID := ""
  564. if doClientTactics {
  565. // Use a distinct prefix for network ID for each test run to
  566. // ensure tactics from different runs don't apply; this is
  567. // a workaround for the singleton datastore.
  568. prefix := time.Now().String()
  569. jsonNetworkID = fmt.Sprintf(`,"NetworkID" : "%s-%s"`, prefix, "NETWORK1")
  570. }
  571. jsonLimitTLSProfiles := ""
  572. if runConfig.tlsProfile != "" {
  573. jsonLimitTLSProfiles = fmt.Sprintf(`,"LimitTLSProfiles" : ["%s"]`, runConfig.tlsProfile)
  574. }
  575. clientConfigJSON := fmt.Sprintf(`
  576. {
  577. "ClientPlatform" : "Windows",
  578. "ClientVersion" : "0",
  579. "SponsorId" : "0",
  580. "PropagationChannelId" : "0",
  581. "DisableRemoteServerListFetcher" : true,
  582. "EstablishTunnelPausePeriodSeconds" : 1,
  583. "ConnectionWorkerPoolSize" : %d,
  584. "LimitTunnelProtocols" : ["%s"]
  585. %s
  586. %s
  587. }`, numTunnels, runConfig.tunnelProtocol, jsonLimitTLSProfiles, jsonNetworkID)
  588. clientConfig, err := psiphon.LoadConfig([]byte(clientConfigJSON))
  589. if err != nil {
  590. t.Fatalf("error processing configuration file: %s", err)
  591. }
  592. clientConfig.DataStoreDirectory = testDataDirName
  593. if !runConfig.doDefaultSponsorID {
  594. clientConfig.SponsorId = sponsorID
  595. }
  596. clientConfig.PropagationChannelId = propagationChannelID
  597. clientConfig.TunnelPoolSize = numTunnels
  598. clientConfig.TargetServerEntry = string(encodedServerEntry)
  599. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  600. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  601. clientConfig.EmitSLOKs = true
  602. if !runConfig.omitAuthorization {
  603. clientConfig.Authorizations = []string{clientAuthorization}
  604. }
  605. err = clientConfig.Commit()
  606. if err != nil {
  607. t.Fatalf("error committing configuration file: %s", err)
  608. }
  609. if doClientTactics {
  610. // Configure nonfunctional values that must be overridden by tactics.
  611. applyParameters := make(map[string]interface{})
  612. applyParameters[parameters.TunnelConnectTimeout] = "1s"
  613. applyParameters[parameters.TunnelRateLimits] = common.RateLimits{WriteBytesPerSecond: 1}
  614. err = clientConfig.SetClientParameters("", true, applyParameters)
  615. if err != nil {
  616. t.Fatalf("SetClientParameters failed: %s", err)
  617. }
  618. } else if runConfig.forceFragmenting {
  619. // Directly apply same parameters that would've come from tactics.
  620. applyParameters := make(map[string]interface{})
  621. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols{runConfig.tunnelProtocol}
  622. applyParameters[parameters.FragmentorProbability] = 1.0
  623. applyParameters[parameters.FragmentorMinTotalBytes] = 1000
  624. applyParameters[parameters.FragmentorMaxTotalBytes] = 2000
  625. applyParameters[parameters.FragmentorMinWriteBytes] = 1
  626. applyParameters[parameters.FragmentorMaxWriteBytes] = 100
  627. applyParameters[parameters.FragmentorMinDelay] = 1 * time.Millisecond
  628. applyParameters[parameters.FragmentorMaxDelay] = 10 * time.Millisecond
  629. err = clientConfig.SetClientParameters("", true, applyParameters)
  630. if err != nil {
  631. t.Fatalf("SetClientParameters failed: %s", err)
  632. }
  633. }
  634. err = psiphon.OpenDataStore(clientConfig)
  635. if err != nil {
  636. t.Fatalf("error initializing client datastore: %s", err)
  637. }
  638. defer psiphon.CloseDataStore()
  639. psiphon.DeleteSLOKs()
  640. controller, err := psiphon.NewController(clientConfig)
  641. if err != nil {
  642. t.Fatalf("error creating client controller: %s", err)
  643. }
  644. tunnelsEstablished := make(chan struct{}, 1)
  645. homepageReceived := make(chan struct{}, 1)
  646. slokSeeded := make(chan struct{}, 1)
  647. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  648. func(notice []byte) {
  649. //fmt.Printf("%s\n", string(notice))
  650. noticeType, payload, err := psiphon.GetNotice(notice)
  651. if err != nil {
  652. return
  653. }
  654. switch noticeType {
  655. case "Tunnels":
  656. count := int(payload["count"].(float64))
  657. if count >= numTunnels {
  658. sendNotificationReceived(tunnelsEstablished)
  659. }
  660. case "Homepage":
  661. homepageURL := payload["url"].(string)
  662. if homepageURL != expectedHomepageURL {
  663. // TODO: wrong goroutine for t.FatalNow()
  664. t.Fatalf("unexpected homepage: %s", homepageURL)
  665. }
  666. sendNotificationReceived(homepageReceived)
  667. case "SLOKSeeded":
  668. sendNotificationReceived(slokSeeded)
  669. }
  670. }))
  671. ctx, cancelFunc := context.WithCancel(context.Background())
  672. controllerWaitGroup := new(sync.WaitGroup)
  673. controllerWaitGroup.Add(1)
  674. go func() {
  675. defer controllerWaitGroup.Done()
  676. controller.Run(ctx)
  677. }()
  678. defer func() {
  679. cancelFunc()
  680. shutdownTimeout := time.NewTimer(20 * time.Second)
  681. shutdownOk := make(chan struct{}, 1)
  682. go func() {
  683. controllerWaitGroup.Wait()
  684. shutdownOk <- *new(struct{})
  685. }()
  686. select {
  687. case <-shutdownOk:
  688. case <-shutdownTimeout.C:
  689. t.Fatalf("controller shutdown timeout exceeded")
  690. }
  691. }()
  692. // Test: tunnels must be established, and correct homepage
  693. // must be received, within 30 seconds
  694. timeoutSignal := make(chan struct{})
  695. go func() {
  696. timer := time.NewTimer(30 * time.Second)
  697. <-timer.C
  698. close(timeoutSignal)
  699. }()
  700. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel establish timeout exceeded")
  701. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  702. expectTrafficFailure := runConfig.denyTrafficRules || (runConfig.omitAuthorization && runConfig.requireAuthorization)
  703. if runConfig.doTunneledWebRequest {
  704. // Test: tunneled web site fetch
  705. err = makeTunneledWebRequest(
  706. t, localHTTPProxyPort, mockWebServerURL, mockWebServerExpectedResponse)
  707. if err == nil {
  708. if expectTrafficFailure {
  709. t.Fatalf("unexpected tunneled web request success")
  710. }
  711. } else {
  712. if !expectTrafficFailure {
  713. t.Fatalf("tunneled web request failed: %s", err)
  714. }
  715. }
  716. }
  717. if runConfig.doTunneledNTPRequest {
  718. // Test: tunneled UDP packets
  719. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  720. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  721. if err == nil {
  722. if expectTrafficFailure {
  723. t.Fatalf("unexpected tunneled NTP request success")
  724. }
  725. } else {
  726. if !expectTrafficFailure {
  727. t.Fatalf("tunneled NTP request failed: %s", err)
  728. }
  729. }
  730. }
  731. // Test: await SLOK payload
  732. if !expectTrafficFailure {
  733. time.Sleep(1 * time.Second)
  734. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  735. numSLOKs := psiphon.CountSLOKs()
  736. if numSLOKs != expectedNumSLOKs {
  737. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  738. }
  739. }
  740. }
  741. func makeTunneledWebRequest(
  742. t *testing.T,
  743. localHTTPProxyPort int,
  744. requestURL, expectedResponseBody string) error {
  745. roundTripTimeout := 30 * time.Second
  746. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  747. if err != nil {
  748. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  749. }
  750. httpClient := &http.Client{
  751. Transport: &http.Transport{
  752. Proxy: http.ProxyURL(proxyUrl),
  753. },
  754. Timeout: roundTripTimeout,
  755. }
  756. response, err := httpClient.Get(requestURL)
  757. if err != nil {
  758. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  759. }
  760. body, err := ioutil.ReadAll(response.Body)
  761. if err != nil {
  762. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  763. }
  764. response.Body.Close()
  765. if string(body) != expectedResponseBody {
  766. return fmt.Errorf("unexpected proxied HTTP response")
  767. }
  768. return nil
  769. }
  770. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  771. timeout := 20 * time.Second
  772. var err error
  773. for _, testHostname := range []string{"time.google.com", "time.nist.gov", "pool.ntp.org"} {
  774. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  775. if err == nil {
  776. break
  777. }
  778. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  779. }
  780. return err
  781. }
  782. var nextUDPProxyPort = 7300
  783. func makeTunneledNTPRequestAttempt(
  784. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  785. nextUDPProxyPort++
  786. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  787. if err != nil {
  788. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  789. }
  790. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  791. // handles it, and then terminates.
  792. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  793. if waitGroup != nil {
  794. defer waitGroup.Done()
  795. }
  796. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  797. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  798. if err != nil {
  799. t.Logf("ListenUDP for %s failed: %s", destination, err)
  800. return
  801. }
  802. defer serverUDPConn.Close()
  803. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  804. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  805. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  806. buffer[udpgwPreambleSize:])
  807. if err != nil {
  808. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  809. return
  810. }
  811. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  812. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  813. if err != nil {
  814. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  815. return
  816. }
  817. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  818. if err != nil {
  819. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  820. return
  821. }
  822. defer socksTCPConn.Close()
  823. flags := uint8(0)
  824. if destinationPort == 53 {
  825. flags = udpgwProtocolFlagDNS
  826. }
  827. err = writeUdpgwPreamble(
  828. udpgwPreambleSize,
  829. flags,
  830. 0,
  831. destinationIP,
  832. destinationPort,
  833. uint16(packetSize),
  834. buffer)
  835. if err != nil {
  836. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  837. return
  838. }
  839. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  840. if err != nil {
  841. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  842. return
  843. }
  844. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  845. if err != nil {
  846. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  847. return
  848. }
  849. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  850. if err != nil {
  851. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  852. return
  853. }
  854. }
  855. // Tunneled DNS request
  856. waitGroup := new(sync.WaitGroup)
  857. waitGroup.Add(1)
  858. go localUDPProxy(
  859. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  860. 53,
  861. waitGroup)
  862. // TODO: properly synchronize with local UDP proxy startup
  863. time.Sleep(1 * time.Second)
  864. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  865. if err != nil {
  866. return fmt.Errorf("DialUDP failed: %s", err)
  867. }
  868. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  869. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  870. addrs, _, err := psiphon.ResolveIP(testHostname, clientUDPConn)
  871. clientUDPConn.Close()
  872. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  873. err = errors.New("no address")
  874. }
  875. if err != nil {
  876. return fmt.Errorf("ResolveIP failed: %s", err)
  877. }
  878. waitGroup.Wait()
  879. // Tunneled NTP request
  880. waitGroup = new(sync.WaitGroup)
  881. waitGroup.Add(1)
  882. go localUDPProxy(
  883. addrs[0][len(addrs[0])-4:],
  884. 123,
  885. waitGroup)
  886. // TODO: properly synchronize with local UDP proxy startup
  887. time.Sleep(1 * time.Second)
  888. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  889. if err != nil {
  890. return fmt.Errorf("DialUDP failed: %s", err)
  891. }
  892. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  893. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  894. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  895. ntpData := make([]byte, 48)
  896. ntpData[0] = 3<<3 | 3
  897. _, err = clientUDPConn.Write(ntpData)
  898. if err != nil {
  899. clientUDPConn.Close()
  900. return fmt.Errorf("NTP Write failed: %s", err)
  901. }
  902. _, err = clientUDPConn.Read(ntpData)
  903. if err != nil {
  904. clientUDPConn.Close()
  905. return fmt.Errorf("NTP Read failed: %s", err)
  906. }
  907. clientUDPConn.Close()
  908. var sec, frac uint64
  909. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  910. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  911. nsec := sec * 1e9
  912. nsec += (frac * 1e9) >> 32
  913. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  914. now := time.Now()
  915. diff := ntpNow.Sub(now)
  916. if diff < 0 {
  917. diff = -diff
  918. }
  919. if diff > 1*time.Minute {
  920. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  921. }
  922. waitGroup.Wait()
  923. return nil
  924. }
  925. func pavePsinetDatabaseFile(
  926. t *testing.T, useDefaultSponsorID bool, psinetFilename string) (string, string) {
  927. sponsorID, _ := common.MakeSecureRandomStringHex(8)
  928. fakeDomain, _ := common.MakeSecureRandomStringHex(4)
  929. fakePath, _ := common.MakeSecureRandomStringHex(4)
  930. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  931. psinetJSONFormat := `
  932. {
  933. "default_sponsor_id" : "%s",
  934. "sponsors": {
  935. "%s": {
  936. "home_pages": {
  937. "None": [
  938. {
  939. "region": null,
  940. "url": "%s"
  941. }
  942. ]
  943. }
  944. }
  945. }
  946. }
  947. `
  948. defaultSponsorID := ""
  949. if useDefaultSponsorID {
  950. defaultSponsorID = sponsorID
  951. }
  952. psinetJSON := fmt.Sprintf(
  953. psinetJSONFormat, defaultSponsorID, sponsorID, expectedHomepageURL)
  954. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  955. if err != nil {
  956. t.Fatalf("error paving psinet database file: %s", err)
  957. }
  958. return sponsorID, expectedHomepageURL
  959. }
  960. func paveTrafficRulesFile(
  961. t *testing.T, trafficRulesFilename, propagationChannelID, accessType string,
  962. requireAuthorization, deny bool) {
  963. allowTCPPorts := fmt.Sprintf("%d", mockWebServerPort)
  964. allowUDPPorts := "53, 123"
  965. if deny {
  966. allowTCPPorts = "0"
  967. allowUDPPorts = "0"
  968. }
  969. authorizationFilterFormat := `,
  970. "AuthorizedAccessTypes" : ["%s"]
  971. `
  972. authorizationFilter := ""
  973. if requireAuthorization {
  974. authorizationFilter = fmt.Sprintf(authorizationFilterFormat, accessType)
  975. }
  976. trafficRulesJSONFormat := `
  977. {
  978. "DefaultRules" : {
  979. "RateLimits" : {
  980. "ReadBytesPerSecond": 16384,
  981. "WriteBytesPerSecond": 16384
  982. },
  983. "AllowTCPPorts" : [0],
  984. "AllowUDPPorts" : [0],
  985. "MeekRateLimiterHistorySize" : 10,
  986. "MeekRateLimiterThresholdSeconds" : 1,
  987. "MeekRateLimiterGarbageCollectionTriggerCount" : 1,
  988. "MeekRateLimiterReapHistoryFrequencySeconds" : 1,
  989. "MeekRateLimiterRegions" : []
  990. },
  991. "FilteredRules" : [
  992. {
  993. "Filter" : {
  994. "HandshakeParameters" : {
  995. "propagation_channel_id" : ["%s"]
  996. }%s
  997. },
  998. "Rules" : {
  999. "RateLimits" : {
  1000. "ReadUnthrottledBytes": 132352,
  1001. "WriteUnthrottledBytes": 132352
  1002. },
  1003. "AllowTCPPorts" : [%s],
  1004. "AllowUDPPorts" : [%s]
  1005. }
  1006. }
  1007. ]
  1008. }
  1009. `
  1010. trafficRulesJSON := fmt.Sprintf(
  1011. trafficRulesJSONFormat, propagationChannelID, authorizationFilter, allowTCPPorts, allowUDPPorts)
  1012. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  1013. if err != nil {
  1014. t.Fatalf("error paving traffic rules file: %s", err)
  1015. }
  1016. }
  1017. var expectedNumSLOKs = 3
  1018. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  1019. oslConfigJSONFormat := `
  1020. {
  1021. "Schemes" : [
  1022. {
  1023. "Epoch" : "%s",
  1024. "Regions" : [],
  1025. "PropagationChannelIDs" : ["%s"],
  1026. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  1027. "SeedSpecs" : [
  1028. {
  1029. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  1030. "UpstreamSubnets" : ["0.0.0.0/0"],
  1031. "Targets" :
  1032. {
  1033. "BytesRead" : 1,
  1034. "BytesWritten" : 1,
  1035. "PortForwardDurationNanoseconds" : 1
  1036. }
  1037. },
  1038. {
  1039. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  1040. "UpstreamSubnets" : ["0.0.0.0/0"],
  1041. "Targets" :
  1042. {
  1043. "BytesRead" : 1,
  1044. "BytesWritten" : 1,
  1045. "PortForwardDurationNanoseconds" : 1
  1046. }
  1047. }
  1048. ],
  1049. "SeedSpecThreshold" : 2,
  1050. "SeedPeriodNanoseconds" : 2592000000000000,
  1051. "SeedPeriodKeySplits": [
  1052. {
  1053. "Total": 2,
  1054. "Threshold": 2
  1055. }
  1056. ]
  1057. },
  1058. {
  1059. "Epoch" : "%s",
  1060. "Regions" : [],
  1061. "PropagationChannelIDs" : ["%s"],
  1062. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  1063. "SeedSpecs" : [
  1064. {
  1065. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  1066. "UpstreamSubnets" : ["0.0.0.0/0"],
  1067. "Targets" :
  1068. {
  1069. "BytesRead" : 1,
  1070. "BytesWritten" : 1,
  1071. "PortForwardDurationNanoseconds" : 1
  1072. }
  1073. }
  1074. ],
  1075. "SeedSpecThreshold" : 1,
  1076. "SeedPeriodNanoseconds" : 2592000000000000,
  1077. "SeedPeriodKeySplits": [
  1078. {
  1079. "Total": 1,
  1080. "Threshold": 1
  1081. }
  1082. ]
  1083. }
  1084. ]
  1085. }
  1086. `
  1087. propagationChannelID, _ := common.MakeSecureRandomStringHex(8)
  1088. now := time.Now().UTC()
  1089. epoch := now.Truncate(720 * time.Hour)
  1090. epochStr := epoch.Format(time.RFC3339Nano)
  1091. oslConfigJSON := fmt.Sprintf(
  1092. oslConfigJSONFormat,
  1093. epochStr, propagationChannelID,
  1094. epochStr, propagationChannelID)
  1095. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  1096. if err != nil {
  1097. t.Fatalf("error paving osl config file: %s", err)
  1098. }
  1099. return propagationChannelID
  1100. }
  1101. func paveTacticsConfigFile(
  1102. t *testing.T, tacticsConfigFilename string,
  1103. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey string,
  1104. tunnelProtocol string,
  1105. propagationChannelID string) {
  1106. // Setting LimitTunnelProtocols passively exercises the
  1107. // server-side LimitTunnelProtocols enforcement.
  1108. tacticsConfigJSONFormat := `
  1109. {
  1110. "RequestPublicKey" : "%s",
  1111. "RequestPrivateKey" : "%s",
  1112. "RequestObfuscatedKey" : "%s",
  1113. "EnforceServerSide" : true,
  1114. "DefaultTactics" : {
  1115. "TTL" : "60s",
  1116. "Probability" : 1.0,
  1117. "Parameters" : {
  1118. "LimitTunnelProtocols" : ["%s"],
  1119. "FragmentorLimitProtocols" : ["%s"],
  1120. "FragmentorProbability" : 1.0,
  1121. "FragmentorMinTotalBytes" : 1000,
  1122. "FragmentorMaxTotalBytes" : 2000,
  1123. "FragmentorMinWriteBytes" : 1,
  1124. "FragmentorMaxWriteBytes" : 100,
  1125. "FragmentorMinDelay" : "1ms",
  1126. "FragmentorMaxDelay" : "10ms",
  1127. "FragmentorDownstreamLimitProtocols" : ["%s"],
  1128. "FragmentorDownstreamProbability" : 1.0,
  1129. "FragmentorDownstreamMinTotalBytes" : 1000,
  1130. "FragmentorDownstreamMaxTotalBytes" : 2000,
  1131. "FragmentorDownstreamMinWriteBytes" : 1,
  1132. "FragmentorDownstreamMaxWriteBytes" : 100,
  1133. "FragmentorDownstreamMinDelay" : "1ms",
  1134. "FragmentorDownstreamMaxDelay" : "10ms"
  1135. }
  1136. },
  1137. "FilteredTactics" : [
  1138. {
  1139. "Filter" : {
  1140. "APIParameters" : {"propagation_channel_id" : ["%s"]},
  1141. "SpeedTestRTTMilliseconds" : {
  1142. "Aggregation" : "Median",
  1143. "AtLeast" : 1
  1144. }
  1145. },
  1146. "Tactics" : {
  1147. "Parameters" : {
  1148. "TunnelConnectTimeout" : "20s",
  1149. "TunnelRateLimits" : {"WriteBytesPerSecond": 1000000}
  1150. }
  1151. }
  1152. }
  1153. ]
  1154. }
  1155. `
  1156. tacticsConfigJSON := fmt.Sprintf(
  1157. tacticsConfigJSONFormat,
  1158. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  1159. tunnelProtocol,
  1160. tunnelProtocol,
  1161. tunnelProtocol,
  1162. propagationChannelID)
  1163. err := ioutil.WriteFile(tacticsConfigFilename, []byte(tacticsConfigJSON), 0600)
  1164. if err != nil {
  1165. t.Fatalf("error paving tactics config file: %s", err)
  1166. }
  1167. }
  1168. func sendNotificationReceived(c chan<- struct{}) {
  1169. select {
  1170. case c <- *new(struct{}):
  1171. default:
  1172. }
  1173. }
  1174. func waitOnNotification(t *testing.T, c, timeoutSignal <-chan struct{}, timeoutMessage string) {
  1175. select {
  1176. case <-c:
  1177. case <-timeoutSignal:
  1178. t.Fatalf(timeoutMessage)
  1179. }
  1180. }