server_test.go 117 KB

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