server_test.go 94 KB

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