server_test.go 40 KB

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