server_test.go 103 KB

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