server_test.go 120 KB

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