server_test.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  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. // Use a distinct prefix for network ID for each test run to
  607. // ensure tactics from different runs don't apply; this is
  608. // a workaround for the singleton datastore.
  609. jsonNetworkID := fmt.Sprintf(`,"NetworkID" : "%s-%s"`, time.Now().String(), "NETWORK1")
  610. jsonLimitTLSProfiles := ""
  611. if runConfig.tlsProfile != "" {
  612. jsonLimitTLSProfiles = fmt.Sprintf(`,"LimitTLSProfiles" : ["%s"]`, runConfig.tlsProfile)
  613. }
  614. clientConfigJSON := fmt.Sprintf(`
  615. {
  616. "ClientPlatform" : "Windows",
  617. "ClientVersion" : "0",
  618. "SponsorId" : "0",
  619. "PropagationChannelId" : "0",
  620. "DisableRemoteServerListFetcher" : true,
  621. "EstablishTunnelPausePeriodSeconds" : 1,
  622. "ConnectionWorkerPoolSize" : %d,
  623. "LimitTunnelProtocols" : ["%s"]
  624. %s
  625. %s
  626. }`, numTunnels, runConfig.tunnelProtocol, jsonLimitTLSProfiles, jsonNetworkID)
  627. clientConfig, err := psiphon.LoadConfig([]byte(clientConfigJSON))
  628. if err != nil {
  629. t.Fatalf("error processing configuration file: %s", err)
  630. }
  631. clientConfig.DataStoreDirectory = testDataDirName
  632. if !runConfig.doDefaultSponsorID {
  633. clientConfig.SponsorId = sponsorID
  634. }
  635. clientConfig.PropagationChannelId = propagationChannelID
  636. clientConfig.TunnelPoolSize = numTunnels
  637. clientConfig.TargetServerEntry = string(encodedServerEntry)
  638. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  639. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  640. clientConfig.EmitSLOKs = true
  641. if !runConfig.omitAuthorization {
  642. clientConfig.Authorizations = []string{clientAuthorization}
  643. }
  644. err = clientConfig.Commit()
  645. if err != nil {
  646. t.Fatalf("error committing configuration file: %s", err)
  647. }
  648. if doClientTactics {
  649. // Configure nonfunctional values that must be overridden by tactics.
  650. applyParameters := make(map[string]interface{})
  651. applyParameters[parameters.TunnelConnectTimeout] = "1s"
  652. applyParameters[parameters.TunnelRateLimits] = common.RateLimits{WriteBytesPerSecond: 1}
  653. err = clientConfig.SetClientParameters("", true, applyParameters)
  654. if err != nil {
  655. t.Fatalf("SetClientParameters failed: %s", err)
  656. }
  657. } else {
  658. // Directly apply same parameters that would've come from tactics.
  659. applyParameters := make(map[string]interface{})
  660. if runConfig.forceFragmenting {
  661. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols{runConfig.tunnelProtocol}
  662. applyParameters[parameters.FragmentorProbability] = 1.0
  663. applyParameters[parameters.FragmentorMinTotalBytes] = 1000
  664. applyParameters[parameters.FragmentorMaxTotalBytes] = 2000
  665. applyParameters[parameters.FragmentorMinWriteBytes] = 1
  666. applyParameters[parameters.FragmentorMaxWriteBytes] = 100
  667. applyParameters[parameters.FragmentorMinDelay] = 1 * time.Millisecond
  668. applyParameters[parameters.FragmentorMaxDelay] = 10 * time.Millisecond
  669. }
  670. if runConfig.forceLivenessTest {
  671. applyParameters[parameters.LivenessTestMinUpstreamBytes] = livenessTestSize
  672. applyParameters[parameters.LivenessTestMaxUpstreamBytes] = livenessTestSize
  673. applyParameters[parameters.LivenessTestMinDownstreamBytes] = livenessTestSize
  674. applyParameters[parameters.LivenessTestMaxDownstreamBytes] = livenessTestSize
  675. }
  676. err = clientConfig.SetClientParameters("", true, applyParameters)
  677. if err != nil {
  678. t.Fatalf("SetClientParameters failed: %s", err)
  679. }
  680. }
  681. err = psiphon.OpenDataStore(clientConfig)
  682. if err != nil {
  683. t.Fatalf("error initializing client datastore: %s", err)
  684. }
  685. defer psiphon.CloseDataStore()
  686. psiphon.DeleteSLOKs()
  687. controller, err := psiphon.NewController(clientConfig)
  688. if err != nil {
  689. t.Fatalf("error creating client controller: %s", err)
  690. }
  691. tunnelsEstablished := make(chan struct{}, 1)
  692. homepageReceived := make(chan struct{}, 1)
  693. slokSeeded := make(chan struct{}, 1)
  694. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  695. func(notice []byte) {
  696. //fmt.Printf("%s\n", string(notice))
  697. noticeType, payload, err := psiphon.GetNotice(notice)
  698. if err != nil {
  699. return
  700. }
  701. switch noticeType {
  702. case "Tunnels":
  703. count := int(payload["count"].(float64))
  704. if count >= numTunnels {
  705. sendNotificationReceived(tunnelsEstablished)
  706. }
  707. case "Homepage":
  708. homepageURL := payload["url"].(string)
  709. if homepageURL != expectedHomepageURL {
  710. // TODO: wrong goroutine for t.FatalNow()
  711. t.Fatalf("unexpected homepage: %s", homepageURL)
  712. }
  713. sendNotificationReceived(homepageReceived)
  714. case "SLOKSeeded":
  715. sendNotificationReceived(slokSeeded)
  716. }
  717. }))
  718. ctx, cancelFunc := context.WithCancel(context.Background())
  719. controllerWaitGroup := new(sync.WaitGroup)
  720. controllerWaitGroup.Add(1)
  721. go func() {
  722. defer controllerWaitGroup.Done()
  723. controller.Run(ctx)
  724. }()
  725. defer func() {
  726. cancelFunc()
  727. shutdownTimeout := time.NewTimer(20 * time.Second)
  728. shutdownOk := make(chan struct{}, 1)
  729. go func() {
  730. controllerWaitGroup.Wait()
  731. shutdownOk <- *new(struct{})
  732. }()
  733. select {
  734. case <-shutdownOk:
  735. case <-shutdownTimeout.C:
  736. t.Fatalf("controller shutdown timeout exceeded")
  737. }
  738. }()
  739. // Test: tunnels must be established, and correct homepage
  740. // must be received, within 30 seconds
  741. timeoutSignal := make(chan struct{})
  742. go func() {
  743. timer := time.NewTimer(30 * time.Second)
  744. <-timer.C
  745. close(timeoutSignal)
  746. }()
  747. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel establish timeout exceeded")
  748. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  749. expectTrafficFailure := runConfig.denyTrafficRules || (runConfig.omitAuthorization && runConfig.requireAuthorization)
  750. if runConfig.doTunneledWebRequest {
  751. // Test: tunneled web site fetch
  752. err = makeTunneledWebRequest(
  753. t, localHTTPProxyPort, mockWebServerURL, mockWebServerExpectedResponse)
  754. if err == nil {
  755. if expectTrafficFailure {
  756. t.Fatalf("unexpected tunneled web request success")
  757. }
  758. } else {
  759. if !expectTrafficFailure {
  760. t.Fatalf("tunneled web request failed: %s", err)
  761. }
  762. }
  763. }
  764. if runConfig.doTunneledNTPRequest {
  765. // Test: tunneled UDP packets
  766. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  767. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  768. if err == nil {
  769. if expectTrafficFailure {
  770. t.Fatalf("unexpected tunneled NTP request success")
  771. }
  772. } else {
  773. if !expectTrafficFailure {
  774. t.Fatalf("tunneled NTP request failed: %s", err)
  775. }
  776. }
  777. }
  778. // Test: await SLOK payload
  779. if !expectTrafficFailure {
  780. time.Sleep(1 * time.Second)
  781. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  782. numSLOKs := psiphon.CountSLOKs()
  783. if numSLOKs != expectedNumSLOKs {
  784. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  785. }
  786. }
  787. }
  788. func makeTunneledWebRequest(
  789. t *testing.T,
  790. localHTTPProxyPort int,
  791. requestURL, expectedResponseBody string) error {
  792. roundTripTimeout := 30 * time.Second
  793. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  794. if err != nil {
  795. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  796. }
  797. httpClient := &http.Client{
  798. Transport: &http.Transport{
  799. Proxy: http.ProxyURL(proxyUrl),
  800. },
  801. Timeout: roundTripTimeout,
  802. }
  803. response, err := httpClient.Get(requestURL)
  804. if err != nil {
  805. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  806. }
  807. body, err := ioutil.ReadAll(response.Body)
  808. if err != nil {
  809. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  810. }
  811. response.Body.Close()
  812. if string(body) != expectedResponseBody {
  813. return fmt.Errorf("unexpected proxied HTTP response")
  814. }
  815. return nil
  816. }
  817. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  818. timeout := 20 * time.Second
  819. var err error
  820. for _, testHostname := range []string{"time.google.com", "time.nist.gov", "pool.ntp.org"} {
  821. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  822. if err == nil {
  823. break
  824. }
  825. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  826. }
  827. return err
  828. }
  829. var nextUDPProxyPort = 7300
  830. func makeTunneledNTPRequestAttempt(
  831. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  832. nextUDPProxyPort++
  833. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  834. if err != nil {
  835. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  836. }
  837. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  838. // handles it, and then terminates.
  839. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  840. if waitGroup != nil {
  841. defer waitGroup.Done()
  842. }
  843. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  844. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  845. if err != nil {
  846. t.Logf("ListenUDP for %s failed: %s", destination, err)
  847. return
  848. }
  849. defer serverUDPConn.Close()
  850. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  851. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  852. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  853. buffer[udpgwPreambleSize:])
  854. if err != nil {
  855. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  856. return
  857. }
  858. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  859. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  860. if err != nil {
  861. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  862. return
  863. }
  864. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  865. if err != nil {
  866. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  867. return
  868. }
  869. defer socksTCPConn.Close()
  870. flags := uint8(0)
  871. if destinationPort == 53 {
  872. flags = udpgwProtocolFlagDNS
  873. }
  874. err = writeUdpgwPreamble(
  875. udpgwPreambleSize,
  876. flags,
  877. 0,
  878. destinationIP,
  879. destinationPort,
  880. uint16(packetSize),
  881. buffer)
  882. if err != nil {
  883. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  884. return
  885. }
  886. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  887. if err != nil {
  888. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  889. return
  890. }
  891. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  892. if err != nil {
  893. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  894. return
  895. }
  896. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  897. if err != nil {
  898. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  899. return
  900. }
  901. }
  902. // Tunneled DNS request
  903. waitGroup := new(sync.WaitGroup)
  904. waitGroup.Add(1)
  905. go localUDPProxy(
  906. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  907. 53,
  908. waitGroup)
  909. // TODO: properly synchronize with local UDP proxy startup
  910. time.Sleep(1 * time.Second)
  911. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  912. if err != nil {
  913. return fmt.Errorf("DialUDP failed: %s", err)
  914. }
  915. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  916. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  917. addrs, _, err := psiphon.ResolveIP(testHostname, clientUDPConn)
  918. clientUDPConn.Close()
  919. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  920. err = errors.New("no address")
  921. }
  922. if err != nil {
  923. return fmt.Errorf("ResolveIP failed: %s", err)
  924. }
  925. waitGroup.Wait()
  926. // Tunneled NTP request
  927. waitGroup = new(sync.WaitGroup)
  928. waitGroup.Add(1)
  929. go localUDPProxy(
  930. addrs[0][len(addrs[0])-4:],
  931. 123,
  932. waitGroup)
  933. // TODO: properly synchronize with local UDP proxy startup
  934. time.Sleep(1 * time.Second)
  935. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  936. if err != nil {
  937. return fmt.Errorf("DialUDP failed: %s", err)
  938. }
  939. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  940. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  941. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  942. ntpData := make([]byte, 48)
  943. ntpData[0] = 3<<3 | 3
  944. _, err = clientUDPConn.Write(ntpData)
  945. if err != nil {
  946. clientUDPConn.Close()
  947. return fmt.Errorf("NTP Write failed: %s", err)
  948. }
  949. _, err = clientUDPConn.Read(ntpData)
  950. if err != nil {
  951. clientUDPConn.Close()
  952. return fmt.Errorf("NTP Read failed: %s", err)
  953. }
  954. clientUDPConn.Close()
  955. var sec, frac uint64
  956. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  957. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  958. nsec := sec * 1e9
  959. nsec += (frac * 1e9) >> 32
  960. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  961. now := time.Now()
  962. diff := ntpNow.Sub(now)
  963. if diff < 0 {
  964. diff = -diff
  965. }
  966. if diff > 1*time.Minute {
  967. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  968. }
  969. waitGroup.Wait()
  970. return nil
  971. }
  972. func pavePsinetDatabaseFile(
  973. t *testing.T, useDefaultSponsorID bool, psinetFilename string) (string, string) {
  974. sponsorID := prng.HexString(8)
  975. fakeDomain := prng.HexString(4)
  976. fakePath := prng.HexString(4)
  977. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  978. psinetJSONFormat := `
  979. {
  980. "default_sponsor_id" : "%s",
  981. "sponsors": {
  982. "%s": {
  983. "home_pages": {
  984. "None": [
  985. {
  986. "region": null,
  987. "url": "%s"
  988. }
  989. ]
  990. }
  991. }
  992. }
  993. }
  994. `
  995. defaultSponsorID := ""
  996. if useDefaultSponsorID {
  997. defaultSponsorID = sponsorID
  998. }
  999. psinetJSON := fmt.Sprintf(
  1000. psinetJSONFormat, defaultSponsorID, sponsorID, expectedHomepageURL)
  1001. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  1002. if err != nil {
  1003. t.Fatalf("error paving psinet database file: %s", err)
  1004. }
  1005. return sponsorID, expectedHomepageURL
  1006. }
  1007. func paveTrafficRulesFile(
  1008. t *testing.T, trafficRulesFilename, propagationChannelID, accessType string,
  1009. requireAuthorization, deny bool,
  1010. livenessTestSize int) {
  1011. allowTCPPorts := fmt.Sprintf("%d", mockWebServerPort)
  1012. allowUDPPorts := "53, 123"
  1013. if deny {
  1014. allowTCPPorts = "0"
  1015. allowUDPPorts = "0"
  1016. }
  1017. authorizationFilterFormat := `,
  1018. "AuthorizedAccessTypes" : ["%s"]
  1019. `
  1020. authorizationFilter := ""
  1021. if requireAuthorization {
  1022. authorizationFilter = fmt.Sprintf(authorizationFilterFormat, accessType)
  1023. }
  1024. trafficRulesJSONFormat := `
  1025. {
  1026. "DefaultRules" : {
  1027. "RateLimits" : {
  1028. "ReadBytesPerSecond": 16384,
  1029. "WriteBytesPerSecond": 16384,
  1030. "ReadUnthrottledBytes": %d,
  1031. "WriteUnthrottledBytes": %d
  1032. },
  1033. "AllowTCPPorts" : [0],
  1034. "AllowUDPPorts" : [0],
  1035. "MeekRateLimiterHistorySize" : 10,
  1036. "MeekRateLimiterThresholdSeconds" : 1,
  1037. "MeekRateLimiterGarbageCollectionTriggerCount" : 1,
  1038. "MeekRateLimiterReapHistoryFrequencySeconds" : 1,
  1039. "MeekRateLimiterRegions" : []
  1040. },
  1041. "FilteredRules" : [
  1042. {
  1043. "Filter" : {
  1044. "HandshakeParameters" : {
  1045. "propagation_channel_id" : ["%s"]
  1046. }%s
  1047. },
  1048. "Rules" : {
  1049. "RateLimits" : {
  1050. "ReadBytesPerSecond": 2097152,
  1051. "WriteBytesPerSecond": 2097152
  1052. },
  1053. "AllowTCPPorts" : [%s],
  1054. "AllowUDPPorts" : [%s]
  1055. }
  1056. }
  1057. ]
  1058. }
  1059. `
  1060. trafficRulesJSON := fmt.Sprintf(
  1061. trafficRulesJSONFormat,
  1062. livenessTestSize, livenessTestSize,
  1063. propagationChannelID, authorizationFilter, allowTCPPorts, allowUDPPorts)
  1064. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  1065. if err != nil {
  1066. t.Fatalf("error paving traffic rules file: %s", err)
  1067. }
  1068. }
  1069. var expectedNumSLOKs = 3
  1070. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  1071. oslConfigJSONFormat := `
  1072. {
  1073. "Schemes" : [
  1074. {
  1075. "Epoch" : "%s",
  1076. "Regions" : [],
  1077. "PropagationChannelIDs" : ["%s"],
  1078. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  1079. "SeedSpecs" : [
  1080. {
  1081. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  1082. "UpstreamSubnets" : ["0.0.0.0/0"],
  1083. "Targets" :
  1084. {
  1085. "BytesRead" : 1,
  1086. "BytesWritten" : 1,
  1087. "PortForwardDurationNanoseconds" : 1
  1088. }
  1089. },
  1090. {
  1091. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  1092. "UpstreamSubnets" : ["0.0.0.0/0"],
  1093. "Targets" :
  1094. {
  1095. "BytesRead" : 1,
  1096. "BytesWritten" : 1,
  1097. "PortForwardDurationNanoseconds" : 1
  1098. }
  1099. }
  1100. ],
  1101. "SeedSpecThreshold" : 2,
  1102. "SeedPeriodNanoseconds" : 2592000000000000,
  1103. "SeedPeriodKeySplits": [
  1104. {
  1105. "Total": 2,
  1106. "Threshold": 2
  1107. }
  1108. ]
  1109. },
  1110. {
  1111. "Epoch" : "%s",
  1112. "Regions" : [],
  1113. "PropagationChannelIDs" : ["%s"],
  1114. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  1115. "SeedSpecs" : [
  1116. {
  1117. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  1118. "UpstreamSubnets" : ["0.0.0.0/0"],
  1119. "Targets" :
  1120. {
  1121. "BytesRead" : 1,
  1122. "BytesWritten" : 1,
  1123. "PortForwardDurationNanoseconds" : 1
  1124. }
  1125. }
  1126. ],
  1127. "SeedSpecThreshold" : 1,
  1128. "SeedPeriodNanoseconds" : 2592000000000000,
  1129. "SeedPeriodKeySplits": [
  1130. {
  1131. "Total": 1,
  1132. "Threshold": 1
  1133. }
  1134. ]
  1135. }
  1136. ]
  1137. }
  1138. `
  1139. propagationChannelID := prng.HexString(8)
  1140. now := time.Now().UTC()
  1141. epoch := now.Truncate(720 * time.Hour)
  1142. epochStr := epoch.Format(time.RFC3339Nano)
  1143. oslConfigJSON := fmt.Sprintf(
  1144. oslConfigJSONFormat,
  1145. epochStr, propagationChannelID,
  1146. epochStr, propagationChannelID)
  1147. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  1148. if err != nil {
  1149. t.Fatalf("error paving osl config file: %s", err)
  1150. }
  1151. return propagationChannelID
  1152. }
  1153. func paveTacticsConfigFile(
  1154. t *testing.T, tacticsConfigFilename string,
  1155. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey string,
  1156. tunnelProtocol string,
  1157. propagationChannelID string,
  1158. livenessTestSize int) {
  1159. // Setting LimitTunnelProtocols passively exercises the
  1160. // server-side LimitTunnelProtocols enforcement.
  1161. tacticsConfigJSONFormat := `
  1162. {
  1163. "RequestPublicKey" : "%s",
  1164. "RequestPrivateKey" : "%s",
  1165. "RequestObfuscatedKey" : "%s",
  1166. "EnforceServerSide" : true,
  1167. "DefaultTactics" : {
  1168. "TTL" : "60s",
  1169. "Probability" : 1.0,
  1170. "Parameters" : {
  1171. "LimitTunnelProtocols" : ["%s"],
  1172. "FragmentorLimitProtocols" : ["%s"],
  1173. "FragmentorProbability" : 1.0,
  1174. "FragmentorMinTotalBytes" : 1000,
  1175. "FragmentorMaxTotalBytes" : 2000,
  1176. "FragmentorMinWriteBytes" : 1,
  1177. "FragmentorMaxWriteBytes" : 100,
  1178. "FragmentorMinDelay" : "1ms",
  1179. "FragmentorMaxDelay" : "10ms",
  1180. "FragmentorDownstreamLimitProtocols" : ["%s"],
  1181. "FragmentorDownstreamProbability" : 1.0,
  1182. "FragmentorDownstreamMinTotalBytes" : 1000,
  1183. "FragmentorDownstreamMaxTotalBytes" : 2000,
  1184. "FragmentorDownstreamMinWriteBytes" : 1,
  1185. "FragmentorDownstreamMaxWriteBytes" : 100,
  1186. "FragmentorDownstreamMinDelay" : "1ms",
  1187. "FragmentorDownstreamMaxDelay" : "10ms",
  1188. "LivenessTestMinUpstreamBytes" : %d,
  1189. "LivenessTestMaxUpstreamBytes" : %d,
  1190. "LivenessTestMinDownstreamBytes" : %d,
  1191. "LivenessTestMaxDownstreamBytes" : %d
  1192. }
  1193. },
  1194. "FilteredTactics" : [
  1195. {
  1196. "Filter" : {
  1197. "APIParameters" : {"propagation_channel_id" : ["%s"]},
  1198. "SpeedTestRTTMilliseconds" : {
  1199. "Aggregation" : "Median",
  1200. "AtLeast" : 1
  1201. }
  1202. },
  1203. "Tactics" : {
  1204. "Parameters" : {
  1205. "TunnelConnectTimeout" : "20s",
  1206. "TunnelRateLimits" : {"WriteBytesPerSecond": 1000000}
  1207. }
  1208. }
  1209. }
  1210. ]
  1211. }
  1212. `
  1213. tacticsConfigJSON := fmt.Sprintf(
  1214. tacticsConfigJSONFormat,
  1215. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  1216. tunnelProtocol,
  1217. tunnelProtocol,
  1218. tunnelProtocol,
  1219. livenessTestSize, livenessTestSize, livenessTestSize, livenessTestSize,
  1220. propagationChannelID)
  1221. err := ioutil.WriteFile(tacticsConfigFilename, []byte(tacticsConfigJSON), 0600)
  1222. if err != nil {
  1223. t.Fatalf("error paving tactics config file: %s", err)
  1224. }
  1225. }
  1226. func sendNotificationReceived(c chan<- struct{}) {
  1227. select {
  1228. case c <- *new(struct{}):
  1229. default:
  1230. }
  1231. }
  1232. func waitOnNotification(t *testing.T, c, timeoutSignal <-chan struct{}, timeoutMessage string) {
  1233. select {
  1234. case <-c:
  1235. case <-timeoutSignal:
  1236. t.Fatalf(timeoutMessage)
  1237. }
  1238. }