server_test.go 60 KB

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