server_test.go 82 KB

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