server_test.go 91 KB

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