server_test.go 118 KB

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