server_test.go 113 KB

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