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