server_test.go 75 KB

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