server_test.go 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158
  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. "context"
  22. "encoding/base64"
  23. "encoding/json"
  24. std_errors "errors"
  25. "flag"
  26. "fmt"
  27. "io/ioutil"
  28. "net"
  29. "net/http"
  30. "net/url"
  31. "os"
  32. "path/filepath"
  33. "reflect"
  34. "regexp"
  35. "strconv"
  36. "strings"
  37. "sync"
  38. "syscall"
  39. "testing"
  40. "time"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  44. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  45. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  46. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  47. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  48. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  49. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  50. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  51. "github.com/miekg/dns"
  52. "golang.org/x/net/proxy"
  53. )
  54. var serverIPAddress, testDataDirName string
  55. var mockWebServerURL, mockWebServerExpectedResponse string
  56. var mockWebServerPort = "8080"
  57. func TestMain(m *testing.M) {
  58. flag.Parse()
  59. serverIPv4Address, serverIPv6Address, err := common.GetRoutableInterfaceIPAddresses()
  60. if err != nil {
  61. fmt.Printf("error getting server IP address: %s\n", err)
  62. os.Exit(1)
  63. }
  64. if serverIPv4Address != nil {
  65. serverIPAddress = serverIPv4Address.String()
  66. } else {
  67. serverIPAddress = serverIPv6Address.String()
  68. }
  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. webServerAddress := net.JoinHostPort(serverIPAddress, mockWebServerPort)
  86. server := &http.Server{
  87. Addr: webServerAddress,
  88. Handler: serveMux,
  89. }
  90. go func() {
  91. err := server.ListenAndServe()
  92. if err != nil {
  93. fmt.Printf("error running mock web server: %s\n", err)
  94. os.Exit(1)
  95. }
  96. }()
  97. // TODO: properly synchronize with web server readiness
  98. time.Sleep(1 * time.Second)
  99. return fmt.Sprintf("http://%s/", webServerAddress), responseBody
  100. }
  101. // Note: not testing fronted meek protocols, which client is
  102. // hard-wired to expect running on privileged ports 80 and 443.
  103. func TestSSH(t *testing.T) {
  104. runServer(t,
  105. &runServerConfig{
  106. tunnelProtocol: "SSH",
  107. enableSSHAPIRequests: true,
  108. doHotReload: false,
  109. doDefaultSponsorID: false,
  110. denyTrafficRules: false,
  111. requireAuthorization: true,
  112. omitAuthorization: false,
  113. doTunneledWebRequest: true,
  114. doTunneledNTPRequest: true,
  115. forceFragmenting: false,
  116. forceLivenessTest: false,
  117. doPruneServerEntries: false,
  118. doDanglingTCPConn: true,
  119. doPacketManipulation: false,
  120. doBurstMonitor: false,
  121. doSplitTunnel: false,
  122. limitQUICVersions: false,
  123. doDestinationBytes: false,
  124. doChangeBytesConfig: false,
  125. })
  126. }
  127. func TestOSSH(t *testing.T) {
  128. runServer(t,
  129. &runServerConfig{
  130. tunnelProtocol: "OSSH",
  131. enableSSHAPIRequests: true,
  132. doHotReload: false,
  133. doDefaultSponsorID: false,
  134. denyTrafficRules: false,
  135. requireAuthorization: true,
  136. omitAuthorization: false,
  137. doTunneledWebRequest: true,
  138. doTunneledNTPRequest: true,
  139. forceFragmenting: false,
  140. forceLivenessTest: false,
  141. doPruneServerEntries: false,
  142. doDanglingTCPConn: true,
  143. doPacketManipulation: false,
  144. doBurstMonitor: false,
  145. doSplitTunnel: false,
  146. limitQUICVersions: false,
  147. doDestinationBytes: false,
  148. doChangeBytesConfig: false,
  149. })
  150. }
  151. func TestFragmentedOSSH(t *testing.T) {
  152. runServer(t,
  153. &runServerConfig{
  154. tunnelProtocol: "OSSH",
  155. enableSSHAPIRequests: true,
  156. doHotReload: false,
  157. doDefaultSponsorID: false,
  158. denyTrafficRules: false,
  159. requireAuthorization: true,
  160. omitAuthorization: false,
  161. doTunneledWebRequest: true,
  162. doTunneledNTPRequest: true,
  163. forceFragmenting: true,
  164. forceLivenessTest: false,
  165. doPruneServerEntries: false,
  166. doDanglingTCPConn: true,
  167. doPacketManipulation: false,
  168. doBurstMonitor: false,
  169. doSplitTunnel: false,
  170. limitQUICVersions: false,
  171. doDestinationBytes: false,
  172. doChangeBytesConfig: false,
  173. })
  174. }
  175. func TestUnfrontedMeek(t *testing.T) {
  176. runServer(t,
  177. &runServerConfig{
  178. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  179. enableSSHAPIRequests: true,
  180. doHotReload: false,
  181. doDefaultSponsorID: false,
  182. denyTrafficRules: false,
  183. requireAuthorization: true,
  184. omitAuthorization: false,
  185. doTunneledWebRequest: true,
  186. doTunneledNTPRequest: true,
  187. forceFragmenting: false,
  188. forceLivenessTest: false,
  189. doPruneServerEntries: false,
  190. doDanglingTCPConn: true,
  191. doPacketManipulation: false,
  192. doBurstMonitor: false,
  193. doSplitTunnel: false,
  194. limitQUICVersions: false,
  195. doDestinationBytes: false,
  196. doChangeBytesConfig: false,
  197. })
  198. }
  199. func TestUnfrontedMeekHTTPS(t *testing.T) {
  200. runServer(t,
  201. &runServerConfig{
  202. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  203. tlsProfile: protocol.TLS_PROFILE_RANDOMIZED,
  204. enableSSHAPIRequests: true,
  205. doHotReload: false,
  206. doDefaultSponsorID: false,
  207. denyTrafficRules: false,
  208. requireAuthorization: true,
  209. omitAuthorization: false,
  210. doTunneledWebRequest: true,
  211. doTunneledNTPRequest: true,
  212. forceFragmenting: false,
  213. forceLivenessTest: false,
  214. doPruneServerEntries: false,
  215. doDanglingTCPConn: true,
  216. doPacketManipulation: false,
  217. doBurstMonitor: false,
  218. doSplitTunnel: false,
  219. limitQUICVersions: false,
  220. doDestinationBytes: false,
  221. doChangeBytesConfig: false,
  222. })
  223. }
  224. func TestUnfrontedMeekHTTPSTLS13(t *testing.T) {
  225. runServer(t,
  226. &runServerConfig{
  227. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  228. tlsProfile: protocol.TLS_PROFILE_CHROME_70,
  229. enableSSHAPIRequests: true,
  230. doHotReload: false,
  231. doDefaultSponsorID: false,
  232. denyTrafficRules: false,
  233. requireAuthorization: true,
  234. omitAuthorization: false,
  235. doTunneledWebRequest: true,
  236. doTunneledNTPRequest: true,
  237. forceFragmenting: false,
  238. forceLivenessTest: false,
  239. doPruneServerEntries: false,
  240. doDanglingTCPConn: true,
  241. doPacketManipulation: false,
  242. doBurstMonitor: false,
  243. doSplitTunnel: false,
  244. limitQUICVersions: false,
  245. doDestinationBytes: false,
  246. doChangeBytesConfig: false,
  247. })
  248. }
  249. func TestUnfrontedMeekSessionTicket(t *testing.T) {
  250. runServer(t,
  251. &runServerConfig{
  252. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  253. tlsProfile: protocol.TLS_PROFILE_CHROME_58,
  254. enableSSHAPIRequests: true,
  255. doHotReload: false,
  256. doDefaultSponsorID: false,
  257. denyTrafficRules: false,
  258. requireAuthorization: true,
  259. omitAuthorization: false,
  260. doTunneledWebRequest: true,
  261. doTunneledNTPRequest: true,
  262. forceFragmenting: false,
  263. forceLivenessTest: false,
  264. doPruneServerEntries: false,
  265. doDanglingTCPConn: true,
  266. doPacketManipulation: false,
  267. doBurstMonitor: false,
  268. doSplitTunnel: false,
  269. limitQUICVersions: false,
  270. doDestinationBytes: false,
  271. doChangeBytesConfig: false,
  272. })
  273. }
  274. func TestUnfrontedMeekSessionTicketTLS13(t *testing.T) {
  275. runServer(t,
  276. &runServerConfig{
  277. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  278. tlsProfile: protocol.TLS_PROFILE_CHROME_70,
  279. enableSSHAPIRequests: true,
  280. doHotReload: false,
  281. doDefaultSponsorID: false,
  282. denyTrafficRules: false,
  283. requireAuthorization: true,
  284. omitAuthorization: false,
  285. doTunneledWebRequest: true,
  286. doTunneledNTPRequest: true,
  287. forceFragmenting: false,
  288. forceLivenessTest: false,
  289. doPruneServerEntries: false,
  290. doDanglingTCPConn: true,
  291. doPacketManipulation: false,
  292. doBurstMonitor: false,
  293. doSplitTunnel: false,
  294. limitQUICVersions: false,
  295. doDestinationBytes: false,
  296. doChangeBytesConfig: false,
  297. })
  298. }
  299. func TestQUICOSSH(t *testing.T) {
  300. if !quic.Enabled() {
  301. t.Skip("QUIC is not enabled")
  302. }
  303. runServer(t,
  304. &runServerConfig{
  305. tunnelProtocol: "QUIC-OSSH",
  306. enableSSHAPIRequests: true,
  307. doHotReload: false,
  308. doDefaultSponsorID: false,
  309. denyTrafficRules: false,
  310. requireAuthorization: true,
  311. omitAuthorization: false,
  312. doTunneledWebRequest: true,
  313. doTunneledNTPRequest: true,
  314. forceFragmenting: false,
  315. forceLivenessTest: false,
  316. doPruneServerEntries: false,
  317. doDanglingTCPConn: false,
  318. doPacketManipulation: false,
  319. doBurstMonitor: false,
  320. doSplitTunnel: false,
  321. limitQUICVersions: false,
  322. doDestinationBytes: false,
  323. doChangeBytesConfig: false,
  324. })
  325. }
  326. func TestLimitedQUICOSSH(t *testing.T) {
  327. if !quic.Enabled() {
  328. t.Skip("QUIC is not enabled")
  329. }
  330. runServer(t,
  331. &runServerConfig{
  332. tunnelProtocol: "QUIC-OSSH",
  333. enableSSHAPIRequests: true,
  334. doHotReload: false,
  335. doDefaultSponsorID: false,
  336. denyTrafficRules: false,
  337. requireAuthorization: true,
  338. omitAuthorization: false,
  339. doTunneledWebRequest: true,
  340. doTunneledNTPRequest: true,
  341. forceFragmenting: false,
  342. forceLivenessTest: false,
  343. doPruneServerEntries: false,
  344. doDanglingTCPConn: false,
  345. doPacketManipulation: false,
  346. doBurstMonitor: false,
  347. doSplitTunnel: false,
  348. limitQUICVersions: true,
  349. doDestinationBytes: false,
  350. doChangeBytesConfig: false,
  351. })
  352. }
  353. func TestWebTransportAPIRequests(t *testing.T) {
  354. runServer(t,
  355. &runServerConfig{
  356. tunnelProtocol: "OSSH",
  357. enableSSHAPIRequests: false,
  358. doHotReload: false,
  359. doDefaultSponsorID: false,
  360. denyTrafficRules: false,
  361. requireAuthorization: false,
  362. omitAuthorization: true,
  363. doTunneledWebRequest: true,
  364. doTunneledNTPRequest: true,
  365. forceFragmenting: false,
  366. forceLivenessTest: false,
  367. doPruneServerEntries: false,
  368. doDanglingTCPConn: false,
  369. doPacketManipulation: false,
  370. doBurstMonitor: false,
  371. doSplitTunnel: false,
  372. limitQUICVersions: false,
  373. doDestinationBytes: false,
  374. doChangeBytesConfig: false,
  375. })
  376. }
  377. func TestHotReload(t *testing.T) {
  378. runServer(t,
  379. &runServerConfig{
  380. tunnelProtocol: "OSSH",
  381. enableSSHAPIRequests: true,
  382. doHotReload: true,
  383. doDefaultSponsorID: false,
  384. denyTrafficRules: false,
  385. requireAuthorization: true,
  386. omitAuthorization: false,
  387. doTunneledWebRequest: true,
  388. doTunneledNTPRequest: true,
  389. forceFragmenting: false,
  390. forceLivenessTest: false,
  391. doPruneServerEntries: false,
  392. doDanglingTCPConn: false,
  393. doPacketManipulation: false,
  394. doBurstMonitor: false,
  395. doSplitTunnel: false,
  396. limitQUICVersions: false,
  397. doDestinationBytes: false,
  398. doChangeBytesConfig: false,
  399. })
  400. }
  401. func TestDefaultSponsorID(t *testing.T) {
  402. runServer(t,
  403. &runServerConfig{
  404. tunnelProtocol: "OSSH",
  405. enableSSHAPIRequests: true,
  406. doHotReload: true,
  407. doDefaultSponsorID: true,
  408. denyTrafficRules: false,
  409. requireAuthorization: true,
  410. omitAuthorization: false,
  411. doTunneledWebRequest: true,
  412. doTunneledNTPRequest: true,
  413. forceFragmenting: false,
  414. forceLivenessTest: false,
  415. doPruneServerEntries: false,
  416. doDanglingTCPConn: false,
  417. doPacketManipulation: false,
  418. doBurstMonitor: false,
  419. doSplitTunnel: false,
  420. limitQUICVersions: false,
  421. doDestinationBytes: false,
  422. doChangeBytesConfig: false,
  423. })
  424. }
  425. func TestDenyTrafficRules(t *testing.T) {
  426. runServer(t,
  427. &runServerConfig{
  428. tunnelProtocol: "OSSH",
  429. enableSSHAPIRequests: true,
  430. doHotReload: true,
  431. doDefaultSponsorID: false,
  432. denyTrafficRules: true,
  433. requireAuthorization: true,
  434. omitAuthorization: false,
  435. doTunneledWebRequest: true,
  436. doTunneledNTPRequest: true,
  437. forceFragmenting: false,
  438. forceLivenessTest: false,
  439. doPruneServerEntries: false,
  440. doDanglingTCPConn: false,
  441. doPacketManipulation: false,
  442. doBurstMonitor: false,
  443. doSplitTunnel: false,
  444. limitQUICVersions: false,
  445. doDestinationBytes: false,
  446. doChangeBytesConfig: false,
  447. })
  448. }
  449. func TestOmitAuthorization(t *testing.T) {
  450. runServer(t,
  451. &runServerConfig{
  452. tunnelProtocol: "OSSH",
  453. enableSSHAPIRequests: true,
  454. doHotReload: true,
  455. doDefaultSponsorID: false,
  456. denyTrafficRules: false,
  457. requireAuthorization: true,
  458. omitAuthorization: true,
  459. doTunneledWebRequest: true,
  460. doTunneledNTPRequest: true,
  461. forceFragmenting: false,
  462. forceLivenessTest: false,
  463. doPruneServerEntries: false,
  464. doDanglingTCPConn: false,
  465. doPacketManipulation: false,
  466. doBurstMonitor: false,
  467. doSplitTunnel: false,
  468. limitQUICVersions: false,
  469. doDestinationBytes: false,
  470. doChangeBytesConfig: false,
  471. })
  472. }
  473. func TestNoAuthorization(t *testing.T) {
  474. runServer(t,
  475. &runServerConfig{
  476. tunnelProtocol: "OSSH",
  477. enableSSHAPIRequests: true,
  478. doHotReload: true,
  479. doDefaultSponsorID: false,
  480. denyTrafficRules: false,
  481. requireAuthorization: false,
  482. omitAuthorization: true,
  483. doTunneledWebRequest: true,
  484. doTunneledNTPRequest: true,
  485. forceFragmenting: false,
  486. forceLivenessTest: false,
  487. doPruneServerEntries: false,
  488. doDanglingTCPConn: false,
  489. doPacketManipulation: false,
  490. doBurstMonitor: false,
  491. doSplitTunnel: false,
  492. limitQUICVersions: false,
  493. doDestinationBytes: false,
  494. doChangeBytesConfig: false,
  495. })
  496. }
  497. func TestUnusedAuthorization(t *testing.T) {
  498. runServer(t,
  499. &runServerConfig{
  500. tunnelProtocol: "OSSH",
  501. enableSSHAPIRequests: true,
  502. doHotReload: true,
  503. doDefaultSponsorID: false,
  504. denyTrafficRules: false,
  505. requireAuthorization: false,
  506. omitAuthorization: false,
  507. doTunneledWebRequest: true,
  508. doTunneledNTPRequest: true,
  509. forceFragmenting: false,
  510. forceLivenessTest: false,
  511. doPruneServerEntries: false,
  512. doDanglingTCPConn: false,
  513. doPacketManipulation: false,
  514. doBurstMonitor: false,
  515. doSplitTunnel: false,
  516. limitQUICVersions: false,
  517. doDestinationBytes: false,
  518. doChangeBytesConfig: false,
  519. })
  520. }
  521. func TestTCPOnlySLOK(t *testing.T) {
  522. runServer(t,
  523. &runServerConfig{
  524. tunnelProtocol: "OSSH",
  525. enableSSHAPIRequests: true,
  526. doHotReload: false,
  527. doDefaultSponsorID: false,
  528. denyTrafficRules: false,
  529. requireAuthorization: true,
  530. omitAuthorization: false,
  531. doTunneledWebRequest: true,
  532. doTunneledNTPRequest: false,
  533. forceFragmenting: false,
  534. forceLivenessTest: false,
  535. doPruneServerEntries: false,
  536. doDanglingTCPConn: false,
  537. doPacketManipulation: false,
  538. doBurstMonitor: false,
  539. doSplitTunnel: false,
  540. limitQUICVersions: false,
  541. doDestinationBytes: false,
  542. doChangeBytesConfig: false,
  543. })
  544. }
  545. func TestUDPOnlySLOK(t *testing.T) {
  546. runServer(t,
  547. &runServerConfig{
  548. tunnelProtocol: "OSSH",
  549. enableSSHAPIRequests: true,
  550. doHotReload: false,
  551. doDefaultSponsorID: false,
  552. denyTrafficRules: false,
  553. requireAuthorization: true,
  554. omitAuthorization: false,
  555. doTunneledWebRequest: false,
  556. doTunneledNTPRequest: true,
  557. forceFragmenting: false,
  558. forceLivenessTest: false,
  559. doPruneServerEntries: false,
  560. doDanglingTCPConn: false,
  561. doPacketManipulation: false,
  562. doBurstMonitor: false,
  563. doSplitTunnel: false,
  564. limitQUICVersions: false,
  565. doDestinationBytes: false,
  566. doChangeBytesConfig: false,
  567. })
  568. }
  569. func TestLivenessTest(t *testing.T) {
  570. runServer(t,
  571. &runServerConfig{
  572. tunnelProtocol: "OSSH",
  573. enableSSHAPIRequests: true,
  574. doHotReload: false,
  575. doDefaultSponsorID: false,
  576. denyTrafficRules: false,
  577. requireAuthorization: true,
  578. omitAuthorization: false,
  579. doTunneledWebRequest: true,
  580. doTunneledNTPRequest: true,
  581. forceFragmenting: false,
  582. forceLivenessTest: true,
  583. doPruneServerEntries: false,
  584. doDanglingTCPConn: false,
  585. doPacketManipulation: false,
  586. doBurstMonitor: false,
  587. doSplitTunnel: false,
  588. limitQUICVersions: false,
  589. doDestinationBytes: false,
  590. doChangeBytesConfig: false,
  591. })
  592. }
  593. func TestPruneServerEntries(t *testing.T) {
  594. runServer(t,
  595. &runServerConfig{
  596. tunnelProtocol: "OSSH",
  597. enableSSHAPIRequests: true,
  598. doHotReload: false,
  599. doDefaultSponsorID: false,
  600. denyTrafficRules: false,
  601. requireAuthorization: true,
  602. omitAuthorization: false,
  603. doTunneledWebRequest: true,
  604. doTunneledNTPRequest: true,
  605. forceFragmenting: false,
  606. forceLivenessTest: true,
  607. doPruneServerEntries: true,
  608. doDanglingTCPConn: false,
  609. doPacketManipulation: false,
  610. doBurstMonitor: false,
  611. doSplitTunnel: false,
  612. limitQUICVersions: false,
  613. doDestinationBytes: false,
  614. doChangeBytesConfig: false,
  615. })
  616. }
  617. func TestBurstMonitorAndDestinationBytes(t *testing.T) {
  618. runServer(t,
  619. &runServerConfig{
  620. tunnelProtocol: "OSSH",
  621. enableSSHAPIRequests: true,
  622. doHotReload: false,
  623. doDefaultSponsorID: false,
  624. denyTrafficRules: false,
  625. requireAuthorization: true,
  626. omitAuthorization: false,
  627. doTunneledWebRequest: true,
  628. doTunneledNTPRequest: true,
  629. forceFragmenting: false,
  630. forceLivenessTest: false,
  631. doPruneServerEntries: false,
  632. doDanglingTCPConn: true,
  633. doPacketManipulation: false,
  634. doBurstMonitor: true,
  635. doSplitTunnel: false,
  636. limitQUICVersions: false,
  637. doDestinationBytes: true,
  638. doChangeBytesConfig: false,
  639. })
  640. }
  641. func TestChangeBytesConfig(t *testing.T) {
  642. runServer(t,
  643. &runServerConfig{
  644. tunnelProtocol: "OSSH",
  645. enableSSHAPIRequests: true,
  646. doHotReload: false,
  647. doDefaultSponsorID: false,
  648. denyTrafficRules: false,
  649. requireAuthorization: true,
  650. omitAuthorization: false,
  651. doTunneledWebRequest: true,
  652. doTunneledNTPRequest: true,
  653. forceFragmenting: false,
  654. forceLivenessTest: false,
  655. doPruneServerEntries: false,
  656. doDanglingTCPConn: true,
  657. doPacketManipulation: false,
  658. doBurstMonitor: false,
  659. doSplitTunnel: false,
  660. limitQUICVersions: false,
  661. doDestinationBytes: true,
  662. doChangeBytesConfig: true,
  663. })
  664. }
  665. func TestSplitTunnel(t *testing.T) {
  666. runServer(t,
  667. &runServerConfig{
  668. tunnelProtocol: "OSSH",
  669. enableSSHAPIRequests: true,
  670. doHotReload: false,
  671. doDefaultSponsorID: false,
  672. denyTrafficRules: false,
  673. requireAuthorization: true,
  674. omitAuthorization: false,
  675. doTunneledWebRequest: true,
  676. doTunneledNTPRequest: true,
  677. forceFragmenting: false,
  678. forceLivenessTest: false,
  679. doPruneServerEntries: false,
  680. doDanglingTCPConn: true,
  681. doPacketManipulation: false,
  682. doBurstMonitor: false,
  683. doSplitTunnel: true,
  684. limitQUICVersions: false,
  685. doDestinationBytes: false,
  686. doChangeBytesConfig: false,
  687. })
  688. }
  689. type runServerConfig struct {
  690. tunnelProtocol string
  691. tlsProfile string
  692. enableSSHAPIRequests bool
  693. doHotReload bool
  694. doDefaultSponsorID bool
  695. denyTrafficRules bool
  696. requireAuthorization bool
  697. omitAuthorization bool
  698. doTunneledWebRequest bool
  699. doTunneledNTPRequest bool
  700. forceFragmenting bool
  701. forceLivenessTest bool
  702. doPruneServerEntries bool
  703. doDanglingTCPConn bool
  704. doPacketManipulation bool
  705. doBurstMonitor bool
  706. doSplitTunnel bool
  707. limitQUICVersions bool
  708. doDestinationBytes bool
  709. doChangeBytesConfig bool
  710. }
  711. var (
  712. testSSHClientVersions = []string{"SSH-2.0-A", "SSH-2.0-B", "SSH-2.0-C"}
  713. testUserAgents = []string{"ua1", "ua2", "ua3"}
  714. testNetworkType = "WIFI"
  715. testCustomHostNameRegex = `[a-z0-9]{5,10}\.example\.org`
  716. testClientFeatures = []string{"feature 1", "feature 2"}
  717. testDisallowedTrafficAlertActionURLs = []string{"https://example.org/disallowed"}
  718. )
  719. var serverRuns = 0
  720. func runServer(t *testing.T, runConfig *runServerConfig) {
  721. serverRuns += 1
  722. // configure authorized access
  723. accessType := "test-access-type"
  724. accessControlSigningKey, accessControlVerificationKey, err := accesscontrol.NewKeyPair(accessType)
  725. if err != nil {
  726. t.Fatalf("error creating access control key pair: %s", err)
  727. }
  728. accessControlVerificationKeyRing := accesscontrol.VerificationKeyRing{
  729. Keys: []*accesscontrol.VerificationKey{accessControlVerificationKey},
  730. }
  731. var seedAuthorizationID [32]byte
  732. clientAuthorization, authorizationID, err := accesscontrol.IssueAuthorization(
  733. accessControlSigningKey,
  734. seedAuthorizationID[:],
  735. time.Now().Add(1*time.Hour))
  736. if err != nil {
  737. t.Fatalf("error issuing authorization: %s", err)
  738. }
  739. authorizationIDStr := base64.StdEncoding.EncodeToString(authorizationID)
  740. // Enable tactics when the test protocol is meek. Both the client and the
  741. // server will be configured to support tactics. The client config will be
  742. // set with a nonfunctional config so that the tactics request must
  743. // succeed, overriding the nonfunctional values, for the tunnel to
  744. // establish.
  745. doClientTactics := protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol)
  746. doServerTactics := doClientTactics ||
  747. runConfig.forceFragmenting ||
  748. runConfig.doBurstMonitor ||
  749. runConfig.doDestinationBytes
  750. // All servers require a tactics config with valid keys.
  751. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err :=
  752. tactics.GenerateKeys()
  753. if err != nil {
  754. t.Fatalf("error generating tactics keys: %s", err)
  755. }
  756. livenessTestSize := 0
  757. if doClientTactics || runConfig.forceLivenessTest {
  758. livenessTestSize = 1048576
  759. }
  760. // create a server
  761. psiphonServerIPAddress := serverIPAddress
  762. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) {
  763. // Workaround for macOS firewall.
  764. psiphonServerIPAddress = "127.0.0.1"
  765. }
  766. psiphonServerPort := 4000
  767. var limitQUICVersions protocol.QUICVersions
  768. if runConfig.limitQUICVersions {
  769. // Limit the server entry to one specific QUICv1 version, and check
  770. // that this is used (see expectQUICVersion below). This test case
  771. // also exercises disabling gQUIC in the server config and
  772. // using "QUICv1" as the server entry capability.
  773. selectedQUICVersion := protocol.SupportedQUICv1Versions[prng.Intn(
  774. len(protocol.SupportedQUICv1Versions))]
  775. limitQUICVersions = protocol.QUICVersions{selectedQUICVersion}
  776. }
  777. generateConfigParams := &GenerateConfigParams{
  778. ServerIPAddress: psiphonServerIPAddress,
  779. EnableSSHAPIRequests: runConfig.enableSSHAPIRequests,
  780. WebServerPort: 8000,
  781. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: psiphonServerPort},
  782. LimitQUICVersions: limitQUICVersions,
  783. EnableGQUIC: !runConfig.limitQUICVersions,
  784. }
  785. if doServerTactics {
  786. generateConfigParams.TacticsRequestPublicKey = tacticsRequestPublicKey
  787. generateConfigParams.TacticsRequestObfuscatedKey = tacticsRequestObfuscatedKey
  788. }
  789. serverConfigJSON, _, _, _, encodedServerEntry, err := GenerateConfig(generateConfigParams)
  790. if err != nil {
  791. t.Fatalf("error generating server config: %s", err)
  792. }
  793. // customize server config
  794. // Initialize prune server entry test cases and associated data to pave into psinet.
  795. pruneServerEntryTestCases, psinetValidServerEntryTags, expectedNumPruneNotices :=
  796. initializePruneServerEntriesTest(t, runConfig)
  797. // Pave psinet with random values to test handshake homepages.
  798. psinetFilename := filepath.Join(testDataDirName, "psinet.json")
  799. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(
  800. t, psinetFilename, "", runConfig.doDefaultSponsorID, true, psinetValidServerEntryTags)
  801. // Pave OSL config for SLOK testing
  802. oslConfigFilename := filepath.Join(testDataDirName, "osl_config.json")
  803. propagationChannelID := paveOSLConfigFile(t, oslConfigFilename)
  804. // Pave traffic rules file which exercises handshake parameter filtering. Client
  805. // must handshake with specified sponsor ID in order to allow ports for tunneled
  806. // requests.
  807. trafficRulesFilename := filepath.Join(testDataDirName, "traffic_rules.json")
  808. paveTrafficRulesFile(
  809. t,
  810. trafficRulesFilename,
  811. propagationChannelID,
  812. accessType,
  813. authorizationIDStr,
  814. runConfig.requireAuthorization,
  815. runConfig.denyTrafficRules,
  816. livenessTestSize)
  817. var tacticsConfigFilename string
  818. // Only pave the tactics config when tactics are required. This exercises the
  819. // case where the tactics config is omitted.
  820. if doServerTactics {
  821. tacticsConfigFilename = filepath.Join(testDataDirName, "tactics_config.json")
  822. paveTacticsConfigFile(
  823. t,
  824. tacticsConfigFilename,
  825. tacticsRequestPublicKey,
  826. tacticsRequestPrivateKey,
  827. tacticsRequestObfuscatedKey,
  828. runConfig.tunnelProtocol,
  829. propagationChannelID,
  830. livenessTestSize,
  831. runConfig.doBurstMonitor,
  832. runConfig.doDestinationBytes)
  833. }
  834. blocklistFilename := filepath.Join(testDataDirName, "blocklist.csv")
  835. paveBlocklistFile(t, blocklistFilename)
  836. var serverConfig map[string]interface{}
  837. json.Unmarshal(serverConfigJSON, &serverConfig)
  838. // The test GeoIP databases map all IPs to a single, non-"None" country
  839. // and ASN.
  840. //
  841. // When split tunnel mode is enabled, this should cause port forwards to
  842. // be untunneled. When split tunnel mode is not enabled, port forwards
  843. // should be tunneled despite the country match.
  844. //
  845. // When destination bytes metrics are enabled, all traffic will map to the
  846. // single ASN.
  847. geoIPCityDatabaseFilename := filepath.Join(testDataDirName, "geoip_city_database.mmbd")
  848. geoIPISPDatabaseFilename := filepath.Join(testDataDirName, "geoip_isp_database.mmbd")
  849. paveGeoIPDatabaseFiles(t, geoIPCityDatabaseFilename, geoIPISPDatabaseFilename)
  850. serverConfig["GeoIPDatabaseFilenames"] = []string{geoIPCityDatabaseFilename, geoIPISPDatabaseFilename}
  851. serverConfig["PsinetDatabaseFilename"] = psinetFilename
  852. serverConfig["TrafficRulesFilename"] = trafficRulesFilename
  853. serverConfig["OSLConfigFilename"] = oslConfigFilename
  854. if doServerTactics {
  855. serverConfig["TacticsConfigFilename"] = tacticsConfigFilename
  856. }
  857. serverConfig["BlocklistFilename"] = blocklistFilename
  858. serverConfig["LogFilename"] = filepath.Join(testDataDirName, "psiphond.log")
  859. serverConfig["LogLevel"] = "debug"
  860. serverConfig["AccessControlVerificationKeyRing"] = accessControlVerificationKeyRing
  861. // Set this parameter so at least the semaphore functions are called.
  862. // TODO: test that the concurrency limit is correctly enforced.
  863. serverConfig["MaxConcurrentSSHHandshakes"] = 1
  864. // Ensure peak failure rate log fields for a single port forward attempt
  865. serverConfig["PeakUpstreamFailureRateMinimumSampleSize"] = 1
  866. // Exercise this option.
  867. serverConfig["PeriodicGarbageCollectionSeconds"] = 1
  868. // Allow port forwards to local test web server.
  869. serverConfig["AllowBogons"] = true
  870. serverConfig["RunPacketManipulator"] = runConfig.doPacketManipulation
  871. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) && quic.GQUICEnabled() {
  872. // Enable legacy QUIC version support.
  873. serverConfig["EnableGQUIC"] = true
  874. }
  875. serverConfigJSON, _ = json.Marshal(serverConfig)
  876. uniqueUserLog := make(chan map[string]interface{}, 1)
  877. domainBytesLog := make(chan map[string]interface{}, 1)
  878. serverTunnelLog := make(chan map[string]interface{}, 1)
  879. setLogCallback(func(log []byte) {
  880. logFields := make(map[string]interface{})
  881. err := json.Unmarshal(log, &logFields)
  882. if err != nil {
  883. return
  884. }
  885. if logFields["event_name"] == nil {
  886. return
  887. }
  888. switch logFields["event_name"].(string) {
  889. case "unique_user":
  890. select {
  891. case uniqueUserLog <- logFields:
  892. default:
  893. }
  894. case "domain_bytes":
  895. select {
  896. case domainBytesLog <- logFields:
  897. default:
  898. }
  899. case "server_tunnel":
  900. select {
  901. case serverTunnelLog <- logFields:
  902. default:
  903. }
  904. }
  905. })
  906. // run server
  907. serverWaitGroup := new(sync.WaitGroup)
  908. serverWaitGroup.Add(1)
  909. go func() {
  910. defer serverWaitGroup.Done()
  911. err := RunServices(serverConfigJSON)
  912. if err != nil {
  913. // TODO: wrong goroutine for t.FatalNow()
  914. t.Errorf("error running server: %s", err)
  915. }
  916. }()
  917. stopServer := func() {
  918. // Test: orderly server shutdown
  919. p, _ := os.FindProcess(os.Getpid())
  920. p.Signal(os.Interrupt)
  921. shutdownTimeout := time.NewTimer(5 * time.Second)
  922. shutdownOk := make(chan struct{}, 1)
  923. go func() {
  924. serverWaitGroup.Wait()
  925. shutdownOk <- struct{}{}
  926. }()
  927. select {
  928. case <-shutdownOk:
  929. case <-shutdownTimeout.C:
  930. t.Errorf("server shutdown timeout exceeded")
  931. }
  932. }
  933. // Stop server on early exits due to failure.
  934. defer func() {
  935. if stopServer != nil {
  936. stopServer()
  937. }
  938. }()
  939. // TODO: monitor logs for more robust wait-until-loaded. For example,
  940. // especially with the race detector on, QUIC-OSSH tests can fail as the
  941. // client sends its initial packet before the server is ready.
  942. time.Sleep(1 * time.Second)
  943. // Test: hot reload (of psinet and traffic rules)
  944. if runConfig.doHotReload {
  945. // Pave new config files with different random values.
  946. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(
  947. t, psinetFilename, "", runConfig.doDefaultSponsorID, true, psinetValidServerEntryTags)
  948. propagationChannelID = paveOSLConfigFile(t, oslConfigFilename)
  949. paveTrafficRulesFile(
  950. t,
  951. trafficRulesFilename,
  952. propagationChannelID,
  953. accessType,
  954. authorizationIDStr,
  955. runConfig.requireAuthorization,
  956. runConfig.denyTrafficRules,
  957. livenessTestSize)
  958. p, _ := os.FindProcess(os.Getpid())
  959. p.Signal(syscall.SIGUSR1)
  960. // TODO: monitor logs for more robust wait-until-reloaded
  961. time.Sleep(1 * time.Second)
  962. // After reloading psinet, the new sponsorID/expectedHomepageURL
  963. // should be active, as tested in the client "Homepage" notice
  964. // handler below.
  965. }
  966. // Exercise server_load logging
  967. p, _ := os.FindProcess(os.Getpid())
  968. p.Signal(syscall.SIGUSR2)
  969. // configure client
  970. values.SetSSHClientVersionsSpec(values.NewPickOneSpec(testSSHClientVersions))
  971. values.SetUserAgentsSpec(values.NewPickOneSpec(testUserAgents))
  972. // TODO: currently, TargetServerEntry only works with one tunnel
  973. numTunnels := 1
  974. localSOCKSProxyPort := 1081
  975. localHTTPProxyPort := 8081
  976. // Use a distinct suffix for network ID for each test run to ensure tactics
  977. // from different runs don't apply; this is a workaround for the singleton
  978. // datastore.
  979. jsonNetworkID := fmt.Sprintf(`,"NetworkID" : "WIFI-%s"`, time.Now().String())
  980. jsonLimitTLSProfiles := ""
  981. if runConfig.tlsProfile != "" {
  982. jsonLimitTLSProfiles = fmt.Sprintf(`,"LimitTLSProfiles" : ["%s"]`, runConfig.tlsProfile)
  983. }
  984. testClientFeaturesJSON, _ := json.Marshal(testClientFeatures)
  985. clientConfigJSON := fmt.Sprintf(`
  986. {
  987. "ClientPlatform" : "Android_10_com.test.app",
  988. "ClientVersion" : "0",
  989. "ClientFeatures" : %s,
  990. "SponsorId" : "0",
  991. "PropagationChannelId" : "0",
  992. "DeviceRegion" : "US",
  993. "DisableRemoteServerListFetcher" : true,
  994. "EstablishTunnelPausePeriodSeconds" : 1,
  995. "ConnectionWorkerPoolSize" : %d,
  996. "LimitTunnelProtocols" : ["%s"]
  997. %s
  998. %s
  999. }`,
  1000. string(testClientFeaturesJSON),
  1001. numTunnels,
  1002. runConfig.tunnelProtocol,
  1003. jsonLimitTLSProfiles,
  1004. jsonNetworkID)
  1005. clientConfig, err := psiphon.LoadConfig([]byte(clientConfigJSON))
  1006. if err != nil {
  1007. t.Fatalf("error processing configuration file: %s", err)
  1008. }
  1009. clientConfig.DataRootDirectory = testDataDirName
  1010. if !runConfig.doDefaultSponsorID {
  1011. clientConfig.SponsorId = sponsorID
  1012. }
  1013. clientConfig.PropagationChannelId = propagationChannelID
  1014. clientConfig.TunnelPoolSize = numTunnels
  1015. clientConfig.TargetServerEntry = string(encodedServerEntry)
  1016. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  1017. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  1018. clientConfig.EmitSLOKs = true
  1019. clientConfig.EmitServerAlerts = true
  1020. if runConfig.doSplitTunnel {
  1021. clientConfig.SplitTunnelOwnRegion = true
  1022. }
  1023. if !runConfig.omitAuthorization {
  1024. clientConfig.Authorizations = []string{clientAuthorization}
  1025. }
  1026. err = clientConfig.Commit(false)
  1027. if err != nil {
  1028. t.Fatalf("error committing configuration file: %s", err)
  1029. }
  1030. if doClientTactics {
  1031. // Configure nonfunctional values that must be overridden by tactics.
  1032. applyParameters := make(map[string]interface{})
  1033. applyParameters[parameters.TunnelConnectTimeout] = "1s"
  1034. applyParameters[parameters.TunnelRateLimits] = common.RateLimits{WriteBytesPerSecond: 1}
  1035. err = clientConfig.SetParameters("", true, applyParameters)
  1036. if err != nil {
  1037. t.Fatalf("SetParameters failed: %s", err)
  1038. }
  1039. } else {
  1040. // Directly apply same parameters that would've come from tactics.
  1041. applyParameters := make(map[string]interface{})
  1042. if runConfig.forceFragmenting {
  1043. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols{runConfig.tunnelProtocol}
  1044. applyParameters[parameters.FragmentorProbability] = 1.0
  1045. applyParameters[parameters.FragmentorMinTotalBytes] = 1000
  1046. applyParameters[parameters.FragmentorMaxTotalBytes] = 2000
  1047. applyParameters[parameters.FragmentorMinWriteBytes] = 1
  1048. applyParameters[parameters.FragmentorMaxWriteBytes] = 100
  1049. applyParameters[parameters.FragmentorMinDelay] = 1 * time.Millisecond
  1050. applyParameters[parameters.FragmentorMaxDelay] = 10 * time.Millisecond
  1051. }
  1052. if runConfig.forceLivenessTest {
  1053. applyParameters[parameters.LivenessTestMinUpstreamBytes] = livenessTestSize
  1054. applyParameters[parameters.LivenessTestMaxUpstreamBytes] = livenessTestSize
  1055. applyParameters[parameters.LivenessTestMinDownstreamBytes] = livenessTestSize
  1056. applyParameters[parameters.LivenessTestMaxDownstreamBytes] = livenessTestSize
  1057. }
  1058. if runConfig.doPruneServerEntries {
  1059. applyParameters[parameters.PsiphonAPIStatusRequestShortPeriodMin] = 1 * time.Millisecond
  1060. applyParameters[parameters.PsiphonAPIStatusRequestShortPeriodMax] = 1 * time.Millisecond
  1061. }
  1062. err = clientConfig.SetParameters("", true, applyParameters)
  1063. if err != nil {
  1064. t.Fatalf("SetParameters failed: %s", err)
  1065. }
  1066. }
  1067. // connect to server with client
  1068. err = psiphon.OpenDataStore(clientConfig)
  1069. if err != nil {
  1070. t.Fatalf("error initializing client datastore: %s", err)
  1071. }
  1072. defer psiphon.CloseDataStore()
  1073. // Test unique user counting cases.
  1074. var expectUniqueUser bool
  1075. switch serverRuns % 3 {
  1076. case 0:
  1077. // Mock no last_connected.
  1078. psiphon.SetKeyValue("lastConnected", "")
  1079. expectUniqueUser = true
  1080. case 1:
  1081. // Mock previous day last_connected.
  1082. psiphon.SetKeyValue(
  1083. "lastConnected",
  1084. time.Now().UTC().AddDate(0, 0, -1).Truncate(1*time.Hour).Format(time.RFC3339))
  1085. expectUniqueUser = true
  1086. case 2:
  1087. // Leave previous last_connected.
  1088. expectUniqueUser = false
  1089. }
  1090. // Clear SLOKs from previous test runs.
  1091. psiphon.DeleteSLOKs()
  1092. // Store prune server entry test server entries and failed tunnel records.
  1093. storePruneServerEntriesTest(
  1094. t, runConfig, testDataDirName, pruneServerEntryTestCases)
  1095. controller, err := psiphon.NewController(clientConfig)
  1096. if err != nil {
  1097. t.Fatalf("error creating client controller: %s", err)
  1098. }
  1099. connectedServer := make(chan struct{}, 1)
  1100. tunnelsEstablished := make(chan struct{}, 1)
  1101. homepageReceived := make(chan struct{}, 1)
  1102. slokSeeded := make(chan struct{}, 1)
  1103. numPruneNotices := 0
  1104. pruneServerEntriesNoticesEmitted := make(chan struct{}, 1)
  1105. serverAlertDisallowedNoticesEmitted := make(chan struct{}, 1)
  1106. untunneledPortForward := make(chan struct{}, 1)
  1107. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  1108. func(notice []byte) {
  1109. //fmt.Printf("%s\n", string(notice))
  1110. noticeType, payload, err := psiphon.GetNotice(notice)
  1111. if err != nil {
  1112. return
  1113. }
  1114. switch noticeType {
  1115. case "ConnectedServer":
  1116. sendNotificationReceived(connectedServer)
  1117. case "Tunnels":
  1118. count := int(payload["count"].(float64))
  1119. if count >= numTunnels {
  1120. sendNotificationReceived(tunnelsEstablished)
  1121. }
  1122. case "Homepage":
  1123. homepageURL := payload["url"].(string)
  1124. if homepageURL != expectedHomepageURL {
  1125. // TODO: wrong goroutine for t.FatalNow()
  1126. t.Errorf("unexpected homepage: %s", homepageURL)
  1127. }
  1128. sendNotificationReceived(homepageReceived)
  1129. case "SLOKSeeded":
  1130. sendNotificationReceived(slokSeeded)
  1131. case "PruneServerEntry":
  1132. numPruneNotices += 1
  1133. if numPruneNotices == expectedNumPruneNotices {
  1134. sendNotificationReceived(pruneServerEntriesNoticesEmitted)
  1135. }
  1136. case "ServerAlert":
  1137. reason := payload["reason"].(string)
  1138. actionURLsPayload := payload["actionURLs"].([]interface{})
  1139. actionURLs := make([]string, len(actionURLsPayload))
  1140. for i, value := range actionURLsPayload {
  1141. actionURLs[i] = value.(string)
  1142. }
  1143. if reason == protocol.PSIPHON_API_ALERT_DISALLOWED_TRAFFIC &&
  1144. reflect.DeepEqual(actionURLs, testDisallowedTrafficAlertActionURLs) {
  1145. sendNotificationReceived(serverAlertDisallowedNoticesEmitted)
  1146. }
  1147. case "Untunneled":
  1148. sendNotificationReceived(untunneledPortForward)
  1149. }
  1150. }))
  1151. ctx, cancelFunc := context.WithCancel(context.Background())
  1152. controllerWaitGroup := new(sync.WaitGroup)
  1153. controllerWaitGroup.Add(1)
  1154. go func() {
  1155. defer controllerWaitGroup.Done()
  1156. controller.Run(ctx)
  1157. }()
  1158. stopClient := func() {
  1159. cancelFunc()
  1160. shutdownTimeout := time.NewTimer(20 * time.Second)
  1161. shutdownOk := make(chan struct{}, 1)
  1162. go func() {
  1163. controllerWaitGroup.Wait()
  1164. shutdownOk <- struct{}{}
  1165. }()
  1166. select {
  1167. case <-shutdownOk:
  1168. case <-shutdownTimeout.C:
  1169. t.Errorf("controller shutdown timeout exceeded")
  1170. }
  1171. }
  1172. // Stop client on early exits due to failure.
  1173. defer func() {
  1174. if stopClient != nil {
  1175. stopClient()
  1176. }
  1177. }()
  1178. // Test: tunnels must be established, and correct homepage
  1179. // must be received, within 30 seconds
  1180. timeoutSignal := make(chan struct{})
  1181. go func() {
  1182. timer := time.NewTimer(30 * time.Second)
  1183. <-timer.C
  1184. close(timeoutSignal)
  1185. }()
  1186. waitOnNotification(t, connectedServer, timeoutSignal, "connected server timeout exceeded")
  1187. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel established timeout exceeded")
  1188. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  1189. if runConfig.doChangeBytesConfig {
  1190. if !runConfig.doDestinationBytes {
  1191. t.Fatalf("invalid test configuration")
  1192. }
  1193. // Test: now that the client is connected, change the domain bytes and
  1194. // destination bytes configurations. No stats should be logged, even
  1195. // with an already connected client.
  1196. // Pave psinet without domain bytes; retain the same sponsor ID. The
  1197. // random homepage URLs will change, but this has no effect on the
  1198. // already connected client.
  1199. _, _ = pavePsinetDatabaseFile(
  1200. t, psinetFilename, sponsorID, runConfig.doDefaultSponsorID, false, psinetValidServerEntryTags)
  1201. // Pave tactics without destination bytes.
  1202. paveTacticsConfigFile(
  1203. t,
  1204. tacticsConfigFilename,
  1205. tacticsRequestPublicKey,
  1206. tacticsRequestPrivateKey,
  1207. tacticsRequestObfuscatedKey,
  1208. runConfig.tunnelProtocol,
  1209. propagationChannelID,
  1210. livenessTestSize,
  1211. runConfig.doBurstMonitor,
  1212. false)
  1213. p, _ := os.FindProcess(os.Getpid())
  1214. p.Signal(syscall.SIGUSR1)
  1215. // TODO: monitor logs for more robust wait-until-reloaded
  1216. time.Sleep(1 * time.Second)
  1217. }
  1218. expectTrafficFailure := runConfig.denyTrafficRules || (runConfig.omitAuthorization && runConfig.requireAuthorization)
  1219. // The client still reports zero domain_bytes when no port forwards are allowed (expectTrafficFailure)
  1220. expectDomainBytes := !runConfig.doChangeBytesConfig
  1221. if runConfig.doTunneledWebRequest {
  1222. // Test: tunneled web site fetch
  1223. err = makeTunneledWebRequest(
  1224. t, localHTTPProxyPort, mockWebServerURL, mockWebServerExpectedResponse)
  1225. if err == nil {
  1226. if expectTrafficFailure {
  1227. t.Fatalf("unexpected tunneled web request success")
  1228. }
  1229. } else {
  1230. if !expectTrafficFailure {
  1231. t.Fatalf("tunneled web request failed: %s", err)
  1232. }
  1233. }
  1234. }
  1235. if runConfig.doTunneledNTPRequest {
  1236. // Test: tunneled UDP packets
  1237. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  1238. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  1239. if err == nil {
  1240. if expectTrafficFailure {
  1241. t.Fatalf("unexpected tunneled NTP request success")
  1242. }
  1243. } else {
  1244. if !expectTrafficFailure {
  1245. t.Fatalf("tunneled NTP request failed: %s", err)
  1246. }
  1247. }
  1248. }
  1249. // Test: await SLOK payload or server alert notice
  1250. time.Sleep(1 * time.Second)
  1251. if !expectTrafficFailure {
  1252. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  1253. numSLOKs := psiphon.CountSLOKs()
  1254. if numSLOKs != expectedNumSLOKs {
  1255. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  1256. }
  1257. } else {
  1258. // Note: in expectTrafficFailure case, timeoutSignal may have already fired.
  1259. waitOnNotification(t, serverAlertDisallowedNoticesEmitted, nil, "")
  1260. }
  1261. // Test: await expected prune server entry notices
  1262. //
  1263. // Note: will take up to PsiphonAPIStatusRequestShortPeriodMax to emit.
  1264. if expectedNumPruneNotices > 0 {
  1265. waitOnNotification(t, pruneServerEntriesNoticesEmitted, nil, "")
  1266. }
  1267. if runConfig.doDanglingTCPConn {
  1268. // Test: client that has established TCP connection but not completed
  1269. // any handshakes must not block/delay server shutdown
  1270. danglingConn, err := net.Dial(
  1271. "tcp", net.JoinHostPort(psiphonServerIPAddress, strconv.Itoa(psiphonServerPort)))
  1272. if err != nil {
  1273. t.Fatalf("TCP dial failed: %s", err)
  1274. }
  1275. defer danglingConn.Close()
  1276. }
  1277. // Test: check for split tunnel notice
  1278. if runConfig.doSplitTunnel {
  1279. if !runConfig.doTunneledWebRequest || expectTrafficFailure {
  1280. t.Fatalf("invalid test run configuration")
  1281. }
  1282. waitOnNotification(t, untunneledPortForward, nil, "")
  1283. } else {
  1284. // There should be no "Untunneled" notice. This check assumes that any
  1285. // unexpected Untunneled notice will have been delivered at this point,
  1286. // after the SLOK notice.
  1287. select {
  1288. case <-untunneledPortForward:
  1289. t.Fatalf("unexpected untunnedl port forward")
  1290. default:
  1291. }
  1292. }
  1293. // Trigger server_load logging once more, to exercise
  1294. // sshClient.peakMetrics. As we don't have a reference to the server's
  1295. // Support struct, we can't invoke logServerLoad directly and there's a
  1296. // potential race between asynchronous logServerLoad invocation and
  1297. // client shutdown. For now, we sleep as a workaround.
  1298. p.Signal(syscall.SIGUSR2)
  1299. time.Sleep(1 * time.Second)
  1300. // Shutdown to ensure logs/notices are flushed
  1301. stopClient()
  1302. stopClient = nil
  1303. stopServer()
  1304. stopServer = nil
  1305. // Test: all expected server logs were emitted
  1306. // TODO: stops should be fully synchronous, but, intermittently,
  1307. // server_tunnel fails to appear ("missing server tunnel log")
  1308. // without this delay.
  1309. time.Sleep(100 * time.Millisecond)
  1310. expectClientBPFField := psiphon.ClientBPFEnabled() && doClientTactics
  1311. expectServerBPFField := ServerBPFEnabled() && doServerTactics
  1312. expectServerPacketManipulationField := runConfig.doPacketManipulation
  1313. expectBurstFields := runConfig.doBurstMonitor
  1314. expectTCPPortForwardDial := runConfig.doTunneledWebRequest
  1315. expectTCPDataTransfer := runConfig.doTunneledWebRequest && !expectTrafficFailure && !runConfig.doSplitTunnel
  1316. // Even with expectTrafficFailure, DNS port forwards will succeed
  1317. expectUDPDataTransfer := runConfig.doTunneledNTPRequest
  1318. expectQUICVersion := ""
  1319. if runConfig.limitQUICVersions {
  1320. expectQUICVersion = limitQUICVersions[0]
  1321. }
  1322. expectDestinationBytesFields := runConfig.doDestinationBytes && !runConfig.doChangeBytesConfig
  1323. select {
  1324. case logFields := <-serverTunnelLog:
  1325. err := checkExpectedServerTunnelLogFields(
  1326. runConfig,
  1327. expectClientBPFField,
  1328. expectServerBPFField,
  1329. expectServerPacketManipulationField,
  1330. expectBurstFields,
  1331. expectTCPPortForwardDial,
  1332. expectTCPDataTransfer,
  1333. expectUDPDataTransfer,
  1334. expectQUICVersion,
  1335. expectDestinationBytesFields,
  1336. logFields)
  1337. if err != nil {
  1338. t.Fatalf("invalid server tunnel log fields: %s", err)
  1339. }
  1340. default:
  1341. t.Fatalf("missing server tunnel log")
  1342. }
  1343. if expectUniqueUser {
  1344. select {
  1345. case logFields := <-uniqueUserLog:
  1346. err := checkExpectedUniqueUserLogFields(
  1347. runConfig,
  1348. logFields)
  1349. if err != nil {
  1350. t.Fatalf("invalid unique user log fields: %s", err)
  1351. }
  1352. default:
  1353. t.Fatalf("missing unique user log")
  1354. }
  1355. } else {
  1356. select {
  1357. case <-uniqueUserLog:
  1358. t.Fatalf("unexpected unique user log")
  1359. default:
  1360. }
  1361. }
  1362. if expectDomainBytes {
  1363. select {
  1364. case logFields := <-domainBytesLog:
  1365. err := checkExpectedDomainBytesLogFields(
  1366. runConfig,
  1367. logFields)
  1368. if err != nil {
  1369. t.Fatalf("invalid domain bytes log fields: %s", err)
  1370. }
  1371. default:
  1372. t.Fatalf("missing domain bytes log")
  1373. }
  1374. } else {
  1375. select {
  1376. case <-domainBytesLog:
  1377. t.Fatalf("unexpected domain bytes log")
  1378. default:
  1379. }
  1380. }
  1381. // Check that datastore had retained/pruned server entries as expected.
  1382. checkPruneServerEntriesTest(t, runConfig, testDataDirName, pruneServerEntryTestCases)
  1383. }
  1384. func sendNotificationReceived(c chan<- struct{}) {
  1385. select {
  1386. case c <- struct{}{}:
  1387. default:
  1388. }
  1389. }
  1390. func waitOnNotification(t *testing.T, c, timeoutSignal <-chan struct{}, timeoutMessage string) {
  1391. if timeoutSignal == nil {
  1392. <-c
  1393. } else {
  1394. select {
  1395. case <-c:
  1396. case <-timeoutSignal:
  1397. t.Fatalf(timeoutMessage)
  1398. }
  1399. }
  1400. }
  1401. func checkExpectedServerTunnelLogFields(
  1402. runConfig *runServerConfig,
  1403. expectClientBPFField bool,
  1404. expectServerBPFField bool,
  1405. expectServerPacketManipulationField bool,
  1406. expectBurstFields bool,
  1407. expectTCPPortForwardDial bool,
  1408. expectTCPDataTransfer bool,
  1409. expectUDPDataTransfer bool,
  1410. expectQUICVersion string,
  1411. expectDestinationBytesFields bool,
  1412. fields map[string]interface{}) error {
  1413. // Limitations:
  1414. //
  1415. // - client_build_rev not set in test build (see common/buildinfo.go)
  1416. // - egress_region, upstream_proxy_type, upstream_proxy_custom_header_names not exercised in test
  1417. // - fronting_provider_id/meek_dial_ip_address/meek_resolved_ip_address only logged for FRONTED meek protocols
  1418. for _, name := range []string{
  1419. "start_time",
  1420. "duration",
  1421. "session_id",
  1422. "is_first_tunnel_in_session",
  1423. "last_connected",
  1424. "establishment_duration",
  1425. "propagation_channel_id",
  1426. "sponsor_id",
  1427. "client_platform",
  1428. "client_features",
  1429. "relay_protocol",
  1430. "device_region",
  1431. "ssh_client_version",
  1432. "server_entry_region",
  1433. "server_entry_source",
  1434. "server_entry_timestamp",
  1435. "dial_port_number",
  1436. "is_replay",
  1437. "dial_duration",
  1438. "candidate_number",
  1439. "established_tunnels_count",
  1440. "network_latency_multiplier",
  1441. "network_type",
  1442. // The test run ensures that logServerLoad is invoked while the client
  1443. // is connected, so the following must be logged.
  1444. "peak_concurrent_proximate_accepted_clients",
  1445. "peak_concurrent_proximate_established_clients",
  1446. } {
  1447. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1448. return fmt.Errorf("missing expected field '%s'", name)
  1449. }
  1450. }
  1451. if fields["relay_protocol"].(string) != runConfig.tunnelProtocol {
  1452. return fmt.Errorf("unexpected relay_protocol '%s'", fields["relay_protocol"])
  1453. }
  1454. if !common.Contains(testSSHClientVersions, fields["ssh_client_version"].(string)) {
  1455. return fmt.Errorf("unexpected relay_protocol '%s'", fields["ssh_client_version"])
  1456. }
  1457. clientFeatures := fields["client_features"].([]interface{})
  1458. if len(clientFeatures) != len(testClientFeatures) {
  1459. return fmt.Errorf("unexpected client_features '%s'", fields["client_features"])
  1460. }
  1461. for i, feature := range testClientFeatures {
  1462. if clientFeatures[i].(string) != feature {
  1463. return fmt.Errorf("unexpected client_features '%s'", fields["client_features"])
  1464. }
  1465. }
  1466. if fields["network_type"].(string) != testNetworkType {
  1467. return fmt.Errorf("unexpected network_type '%s'", fields["network_type"])
  1468. }
  1469. // With interruptions, timeouts, and retries in some tests, there may be
  1470. // more than one dangling accepted_client.
  1471. peakConcurrentProximateAcceptedClients :=
  1472. int(fields["peak_concurrent_proximate_accepted_clients"].(float64))
  1473. if peakConcurrentProximateAcceptedClients < 0 ||
  1474. peakConcurrentProximateAcceptedClients > 10 {
  1475. return fmt.Errorf(
  1476. "unexpected peak_concurrent_proximate_accepted_clients '%v'",
  1477. fields["peak_concurrent_proximate_accepted_clients"])
  1478. }
  1479. peakConcurrentProximateEstablishedClients :=
  1480. int(fields["peak_concurrent_proximate_established_clients"].(float64))
  1481. if peakConcurrentProximateEstablishedClients != 0 {
  1482. return fmt.Errorf(
  1483. "unexpected peak_concurrent_proximate_established_clients '%v'",
  1484. fields["peak_concurrent_proximate_established_clients"])
  1485. }
  1486. // In some negative test cases, no port forwards are attempted, in which
  1487. // case these fields are not logged.
  1488. if expectTCPDataTransfer {
  1489. if fields["peak_tcp_port_forward_failure_rate"] == nil {
  1490. return fmt.Errorf("missing expected field 'peak_tcp_port_forward_failure_rate'")
  1491. }
  1492. if fields["peak_tcp_port_forward_failure_rate"].(float64) != 0.0 {
  1493. return fmt.Errorf(
  1494. "unexpected peak_tcp_port_forward_failure_rate '%v'",
  1495. fields["peak_tcp_port_forward_failure_rate"])
  1496. }
  1497. if fields["peak_tcp_port_forward_failure_rate_sample_size"] == nil {
  1498. return fmt.Errorf("missing expected field 'peak_tcp_port_forward_failure_rate_sample_size'")
  1499. }
  1500. if fields["peak_tcp_port_forward_failure_rate_sample_size"].(float64) <= 0.0 {
  1501. return fmt.Errorf(
  1502. "unexpected peak_tcp_port_forward_failure_rate_sample_size '%v'",
  1503. fields["peak_tcp_port_forward_failure_rate_sample_size"])
  1504. }
  1505. } else {
  1506. if fields["peak_tcp_port_forward_failure_rate"] != nil {
  1507. return fmt.Errorf("unexpected field 'peak_tcp_port_forward_failure_rate'")
  1508. }
  1509. if fields["peak_tcp_port_forward_failure_rate_sample_size"] != nil {
  1510. return fmt.Errorf("unexpected field 'peak_tcp_port_forward_failure_rate_sample_size'")
  1511. }
  1512. }
  1513. if expectUDPDataTransfer {
  1514. if fields["peak_dns_failure_rate"] == nil {
  1515. return fmt.Errorf("missing expected field 'peak_dns_failure_rate'")
  1516. }
  1517. if fields["peak_dns_failure_rate"].(float64) != 0.0 {
  1518. return fmt.Errorf(
  1519. "unexpected peak_dns_failure_rate '%v'", fields["peak_dns_failure_rate"])
  1520. }
  1521. if fields["peak_dns_failure_rate_sample_size"] == nil {
  1522. return fmt.Errorf("missing expected field 'peak_dns_failure_rate_sample_size'")
  1523. }
  1524. if fields["peak_dns_failure_rate_sample_size"].(float64) <= 0.0 {
  1525. return fmt.Errorf(
  1526. "unexpected peak_dns_failure_rate_sample_size '%v'",
  1527. fields["peak_dns_failure_rate_sample_size"])
  1528. }
  1529. } else {
  1530. if fields["peak_dns_failure_rate"] != nil {
  1531. return fmt.Errorf("unexpected field 'peak_dns_failure_rate'")
  1532. }
  1533. if fields["peak_dns_failure_rate_sample_size"] != nil {
  1534. return fmt.Errorf("unexpected field 'peak_dns_failure_rate_sample_size'")
  1535. }
  1536. }
  1537. // TODO: the following cases should check that fields are not logged when
  1538. // not expected.
  1539. if runConfig.doSplitTunnel {
  1540. if fields["split_tunnel"] == nil {
  1541. return fmt.Errorf("missing expected field 'split_tunnel'")
  1542. }
  1543. if fields["split_tunnel"].(bool) != true {
  1544. return fmt.Errorf("missing split_tunnel value")
  1545. }
  1546. }
  1547. if protocol.TunnelProtocolUsesObfuscatedSSH(runConfig.tunnelProtocol) {
  1548. for _, name := range []string{
  1549. "padding",
  1550. "pad_response",
  1551. } {
  1552. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1553. return fmt.Errorf("missing expected field '%s'", name)
  1554. }
  1555. }
  1556. }
  1557. if protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol) {
  1558. for _, name := range []string{
  1559. "user_agent",
  1560. "meek_transformed_host_name",
  1561. "meek_cookie_size",
  1562. "meek_limit_request",
  1563. "meek_underlying_connection_count",
  1564. tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME,
  1565. } {
  1566. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1567. return fmt.Errorf("missing expected field '%s'", name)
  1568. }
  1569. }
  1570. if !common.Contains(testUserAgents, fields["user_agent"].(string)) {
  1571. return fmt.Errorf("unexpected user_agent '%s'", fields["user_agent"])
  1572. }
  1573. }
  1574. if protocol.TunnelProtocolUsesMeekHTTP(runConfig.tunnelProtocol) {
  1575. for _, name := range []string{
  1576. "meek_host_header",
  1577. } {
  1578. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1579. return fmt.Errorf("missing expected field '%s'", name)
  1580. }
  1581. }
  1582. hostName := fields["meek_host_header"].(string)
  1583. dialPortNumber := int(fields["dial_port_number"].(float64))
  1584. if dialPortNumber != 80 {
  1585. hostName, _, _ = net.SplitHostPort(hostName)
  1586. }
  1587. if regexp.MustCompile(testCustomHostNameRegex).FindString(hostName) != hostName {
  1588. return fmt.Errorf("unexpected meek_host_header '%s'", fields["meek_host_header"])
  1589. }
  1590. for _, name := range []string{
  1591. "meek_dial_ip_address",
  1592. "meek_resolved_ip_address",
  1593. } {
  1594. if fields[name] != nil {
  1595. return fmt.Errorf("unexpected field '%s'", name)
  1596. }
  1597. }
  1598. }
  1599. if protocol.TunnelProtocolUsesMeekHTTPS(runConfig.tunnelProtocol) {
  1600. for _, name := range []string{
  1601. "tls_profile",
  1602. "tls_version",
  1603. "meek_sni_server_name",
  1604. } {
  1605. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1606. return fmt.Errorf("missing expected field '%s'", name)
  1607. }
  1608. }
  1609. hostName := fields["meek_sni_server_name"].(string)
  1610. if regexp.MustCompile(testCustomHostNameRegex).FindString(hostName) != hostName {
  1611. return fmt.Errorf("unexpected meek_sni_server_name '%s'", fields["meek_sni_server_name"])
  1612. }
  1613. for _, name := range []string{
  1614. "meek_dial_ip_address",
  1615. "meek_resolved_ip_address",
  1616. "meek_host_header",
  1617. } {
  1618. if fields[name] != nil {
  1619. return fmt.Errorf("unexpected field '%s'", name)
  1620. }
  1621. }
  1622. if !common.Contains(protocol.SupportedTLSProfiles, fields["tls_profile"].(string)) {
  1623. return fmt.Errorf("unexpected tls_profile '%s'", fields["tls_profile"])
  1624. }
  1625. tlsVersion := fields["tls_version"].(string)
  1626. if !strings.HasPrefix(tlsVersion, protocol.TLS_VERSION_12) &&
  1627. !strings.HasPrefix(tlsVersion, protocol.TLS_VERSION_13) {
  1628. return fmt.Errorf("unexpected tls_version '%s'", fields["tls_version"])
  1629. }
  1630. }
  1631. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) {
  1632. for _, name := range []string{
  1633. "quic_version",
  1634. "quic_dial_sni_address",
  1635. } {
  1636. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1637. return fmt.Errorf("missing expected field '%s'", name)
  1638. }
  1639. }
  1640. quicVersion := fields["quic_version"].(string)
  1641. if !common.Contains(protocol.SupportedQUICVersions, quicVersion) ||
  1642. (runConfig.limitQUICVersions && quicVersion != expectQUICVersion) {
  1643. return fmt.Errorf("unexpected quic_version '%s'", fields["quic_version"])
  1644. }
  1645. }
  1646. if runConfig.forceFragmenting {
  1647. for _, name := range []string{
  1648. "upstream_bytes_fragmented",
  1649. "upstream_min_bytes_written",
  1650. "upstream_max_bytes_written",
  1651. "upstream_min_delayed",
  1652. "upstream_max_delayed",
  1653. } {
  1654. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1655. return fmt.Errorf("missing expected field '%s'", name)
  1656. }
  1657. }
  1658. }
  1659. if expectClientBPFField {
  1660. name := "client_bpf"
  1661. if fields[name] == nil {
  1662. return fmt.Errorf("missing expected field '%s'", name)
  1663. } else if fmt.Sprintf("%s", fields[name]) != "test-client-bpf" {
  1664. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  1665. }
  1666. }
  1667. if expectServerBPFField {
  1668. name := "server_bpf"
  1669. if fields[name] == nil {
  1670. return fmt.Errorf("missing expected field '%s'", name)
  1671. } else if fmt.Sprintf("%s", fields[name]) != "test-server-bpf" {
  1672. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  1673. }
  1674. }
  1675. if expectServerPacketManipulationField {
  1676. name := "server_packet_manipulation"
  1677. if fields[name] == nil {
  1678. return fmt.Errorf("missing expected field '%s'", name)
  1679. } else if fmt.Sprintf("%s", fields[name]) != "test-packetman-spec" {
  1680. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  1681. }
  1682. }
  1683. if expectBurstFields {
  1684. // common.TestBurstMonitoredConn covers inclusion of additional fields.
  1685. for _, name := range []string{
  1686. "burst_upstream_first_rate",
  1687. "burst_upstream_last_rate",
  1688. "burst_upstream_min_rate",
  1689. "burst_upstream_max_rate",
  1690. "burst_downstream_first_rate",
  1691. "burst_downstream_last_rate",
  1692. "burst_downstream_min_rate",
  1693. "burst_downstream_max_rate",
  1694. } {
  1695. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1696. return fmt.Errorf("missing expected field '%s'", name)
  1697. }
  1698. }
  1699. }
  1700. var checkTCPMetric func(float64) bool
  1701. if expectTCPPortForwardDial {
  1702. checkTCPMetric = func(f float64) bool { return f > 0 }
  1703. } else {
  1704. checkTCPMetric = func(f float64) bool { return f == 0 }
  1705. }
  1706. for _, name := range []string{
  1707. "peak_concurrent_dialing_port_forward_count_tcp",
  1708. } {
  1709. if fields[name] == nil {
  1710. return fmt.Errorf("missing expected field '%s'", name)
  1711. }
  1712. if !checkTCPMetric(fields[name].(float64)) {
  1713. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  1714. }
  1715. }
  1716. if expectTCPDataTransfer {
  1717. checkTCPMetric = func(f float64) bool { return f > 0 }
  1718. } else {
  1719. checkTCPMetric = func(f float64) bool { return f == 0 }
  1720. }
  1721. for _, name := range []string{
  1722. "bytes_up_tcp",
  1723. "bytes_down_tcp",
  1724. "peak_concurrent_port_forward_count_tcp",
  1725. "total_port_forward_count_tcp",
  1726. } {
  1727. if fields[name] == nil {
  1728. return fmt.Errorf("missing expected field '%s'", name)
  1729. }
  1730. if !checkTCPMetric(fields[name].(float64)) {
  1731. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  1732. }
  1733. }
  1734. var checkUDPMetric func(float64) bool
  1735. if expectUDPDataTransfer {
  1736. checkUDPMetric = func(f float64) bool { return f > 0 }
  1737. } else {
  1738. checkUDPMetric = func(f float64) bool { return f == 0 }
  1739. }
  1740. for _, name := range []string{
  1741. "bytes_up_udp",
  1742. "bytes_down_udp",
  1743. "peak_concurrent_port_forward_count_udp",
  1744. "total_port_forward_count_udp",
  1745. "total_udpgw_channel_count",
  1746. } {
  1747. if fields[name] == nil {
  1748. return fmt.Errorf("missing expected field '%s'", name)
  1749. }
  1750. if !checkUDPMetric(fields[name].(float64)) {
  1751. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  1752. }
  1753. }
  1754. for _, name := range []string{
  1755. "dest_bytes_asn",
  1756. "dest_bytes_up_tcp",
  1757. "dest_bytes_down_tcp",
  1758. "dest_bytes_up_udp",
  1759. "dest_bytes_down_udp",
  1760. "dest_bytes",
  1761. } {
  1762. if expectDestinationBytesFields && fields[name] == nil {
  1763. return fmt.Errorf("missing expected field '%s'", name)
  1764. } else if !expectDestinationBytesFields && fields[name] != nil {
  1765. return fmt.Errorf("unexpected field '%s'", name)
  1766. }
  1767. }
  1768. if expectDestinationBytesFields {
  1769. name := "dest_bytes_asn"
  1770. if fields[name].(string) != testGeoIPASN {
  1771. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  1772. }
  1773. for _, pair := range [][]string{
  1774. []string{"dest_bytes_up_tcp", "bytes_up_tcp"},
  1775. []string{"dest_bytes_down_tcp", "bytes_down_tcp"},
  1776. []string{"dest_bytes_up_udp", "bytes_up_udp"},
  1777. []string{"dest_bytes_down_udp", "bytes_down_udp"},
  1778. []string{"dest_bytes", "bytes"},
  1779. } {
  1780. value0 := int64(fields[pair[0]].(float64))
  1781. value1 := int64(fields[pair[1]].(float64))
  1782. ok := value0 == value1
  1783. if pair[0] == "dest_bytes_up_udp" || pair[0] == "dest_bytes_down_udp" || pair[0] == "dest_bytes" {
  1784. // DNS requests are excluded from destination bytes counting
  1785. ok = value0 > 0 && value0 < value1
  1786. }
  1787. if !ok {
  1788. return fmt.Errorf("unexpected field value %s: %v != %v", pair[0], fields[pair[0]], fields[pair[1]])
  1789. }
  1790. }
  1791. }
  1792. return nil
  1793. }
  1794. func checkExpectedUniqueUserLogFields(
  1795. runConfig *runServerConfig,
  1796. fields map[string]interface{}) error {
  1797. for _, name := range []string{
  1798. "session_id",
  1799. "last_connected",
  1800. "propagation_channel_id",
  1801. "sponsor_id",
  1802. "client_platform",
  1803. "device_region",
  1804. } {
  1805. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1806. return fmt.Errorf("missing expected field '%s'", name)
  1807. }
  1808. }
  1809. return nil
  1810. }
  1811. func checkExpectedDomainBytesLogFields(
  1812. runConfig *runServerConfig,
  1813. fields map[string]interface{}) error {
  1814. for _, name := range []string{
  1815. "session_id",
  1816. "propagation_channel_id",
  1817. "sponsor_id",
  1818. "client_platform",
  1819. "device_region",
  1820. "domain",
  1821. "bytes",
  1822. } {
  1823. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1824. return fmt.Errorf("missing expected field '%s'", name)
  1825. }
  1826. if name == "domain" {
  1827. if fields[name].(string) != "ALL" && fields[name].(string) != "(OTHER)" {
  1828. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  1829. }
  1830. }
  1831. }
  1832. return nil
  1833. }
  1834. func makeTunneledWebRequest(
  1835. t *testing.T,
  1836. localHTTPProxyPort int,
  1837. requestURL, expectedResponseBody string) error {
  1838. roundTripTimeout := 30 * time.Second
  1839. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  1840. if err != nil {
  1841. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  1842. }
  1843. httpClient := &http.Client{
  1844. Transport: &http.Transport{
  1845. Proxy: http.ProxyURL(proxyUrl),
  1846. },
  1847. Timeout: roundTripTimeout,
  1848. }
  1849. response, err := httpClient.Get(requestURL)
  1850. if err != nil {
  1851. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  1852. }
  1853. body, err := ioutil.ReadAll(response.Body)
  1854. if err != nil {
  1855. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  1856. }
  1857. response.Body.Close()
  1858. if string(body) != expectedResponseBody {
  1859. return fmt.Errorf("unexpected proxied HTTP response")
  1860. }
  1861. return nil
  1862. }
  1863. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  1864. timeout := 20 * time.Second
  1865. var err error
  1866. testHostnames := []string{"time.google.com", "time.nist.gov", "pool.ntp.org"}
  1867. indexes := prng.Perm(len(testHostnames))
  1868. for _, index := range indexes {
  1869. testHostname := testHostnames[index]
  1870. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  1871. if err == nil {
  1872. break
  1873. }
  1874. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  1875. }
  1876. return err
  1877. }
  1878. var nextUDPProxyPort = 7300
  1879. func makeTunneledNTPRequestAttempt(
  1880. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  1881. nextUDPProxyPort++
  1882. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  1883. if err != nil {
  1884. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  1885. }
  1886. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  1887. // handles it, and then terminates.
  1888. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  1889. if waitGroup != nil {
  1890. defer waitGroup.Done()
  1891. }
  1892. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  1893. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  1894. if err != nil {
  1895. t.Logf("ListenUDP for %s failed: %s", destination, err)
  1896. return
  1897. }
  1898. defer serverUDPConn.Close()
  1899. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  1900. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  1901. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  1902. buffer[udpgwPreambleSize:])
  1903. if err != nil {
  1904. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  1905. return
  1906. }
  1907. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  1908. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  1909. if err != nil {
  1910. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  1911. return
  1912. }
  1913. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  1914. if err != nil {
  1915. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  1916. return
  1917. }
  1918. defer socksTCPConn.Close()
  1919. flags := uint8(0)
  1920. if destinationPort == 53 {
  1921. flags = udpgwProtocolFlagDNS
  1922. }
  1923. err = writeUdpgwPreamble(
  1924. udpgwPreambleSize,
  1925. flags,
  1926. 0,
  1927. destinationIP,
  1928. destinationPort,
  1929. uint16(packetSize),
  1930. buffer)
  1931. if err != nil {
  1932. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  1933. return
  1934. }
  1935. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  1936. if err != nil {
  1937. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  1938. return
  1939. }
  1940. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  1941. if err != nil {
  1942. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  1943. return
  1944. }
  1945. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  1946. if err != nil {
  1947. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  1948. return
  1949. }
  1950. }
  1951. // Tunneled DNS request
  1952. waitGroup := new(sync.WaitGroup)
  1953. waitGroup.Add(1)
  1954. go localUDPProxy(
  1955. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  1956. 53,
  1957. waitGroup)
  1958. // TODO: properly synchronize with local UDP proxy startup
  1959. time.Sleep(1 * time.Second)
  1960. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  1961. if err != nil {
  1962. return fmt.Errorf("DialUDP failed: %s", err)
  1963. }
  1964. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  1965. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  1966. addrs, err := resolveIP(testHostname, clientUDPConn)
  1967. clientUDPConn.Close()
  1968. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  1969. err = std_errors.New("no address")
  1970. }
  1971. if err != nil {
  1972. return fmt.Errorf("resolveIP failed: %s", err)
  1973. }
  1974. waitGroup.Wait()
  1975. // Tunneled NTP request
  1976. waitGroup = new(sync.WaitGroup)
  1977. waitGroup.Add(1)
  1978. go localUDPProxy(
  1979. addrs[0][len(addrs[0])-4:],
  1980. 123,
  1981. waitGroup)
  1982. // TODO: properly synchronize with local UDP proxy startup
  1983. time.Sleep(1 * time.Second)
  1984. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  1985. if err != nil {
  1986. return fmt.Errorf("DialUDP failed: %s", err)
  1987. }
  1988. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  1989. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  1990. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  1991. ntpData := make([]byte, 48)
  1992. ntpData[0] = 3<<3 | 3
  1993. _, err = clientUDPConn.Write(ntpData)
  1994. if err != nil {
  1995. clientUDPConn.Close()
  1996. return fmt.Errorf("NTP Write failed: %s", err)
  1997. }
  1998. _, err = clientUDPConn.Read(ntpData)
  1999. if err != nil {
  2000. clientUDPConn.Close()
  2001. return fmt.Errorf("NTP Read failed: %s", err)
  2002. }
  2003. clientUDPConn.Close()
  2004. var sec, frac uint64
  2005. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  2006. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  2007. nsec := sec * 1e9
  2008. nsec += (frac * 1e9) >> 32
  2009. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  2010. now := time.Now()
  2011. diff := ntpNow.Sub(now)
  2012. if diff < 0 {
  2013. diff = -diff
  2014. }
  2015. if diff > 1*time.Minute {
  2016. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  2017. }
  2018. waitGroup.Wait()
  2019. return nil
  2020. }
  2021. func resolveIP(host string, conn net.Conn) (addrs []net.IP, err error) {
  2022. // Send the DNS query (A record only)
  2023. dnsConn := &dns.Conn{Conn: conn}
  2024. defer dnsConn.Close()
  2025. query := new(dns.Msg)
  2026. query.SetQuestion(dns.Fqdn(host), dns.TypeA)
  2027. query.RecursionDesired = true
  2028. dnsConn.WriteMsg(query)
  2029. // Process the response
  2030. response, err := dnsConn.ReadMsg()
  2031. if err == nil && response.MsgHdr.Id != query.MsgHdr.Id {
  2032. err = dns.ErrId
  2033. }
  2034. if err != nil {
  2035. return nil, errors.Trace(err)
  2036. }
  2037. addrs = make([]net.IP, 0)
  2038. for _, answer := range response.Answer {
  2039. if a, ok := answer.(*dns.A); ok {
  2040. addrs = append(addrs, a.A)
  2041. }
  2042. }
  2043. return addrs, nil
  2044. }
  2045. func pavePsinetDatabaseFile(
  2046. t *testing.T,
  2047. psinetFilename string,
  2048. sponsorID string,
  2049. useDefaultSponsorID bool,
  2050. doDomainBytes bool,
  2051. validServerEntryTags []string) (string, string) {
  2052. if sponsorID == "" {
  2053. sponsorID = prng.HexString(8)
  2054. }
  2055. defaultSponsorID := ""
  2056. if useDefaultSponsorID {
  2057. defaultSponsorID = sponsorID
  2058. }
  2059. fakeDomain := prng.HexString(4)
  2060. fakePath := prng.HexString(4)
  2061. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  2062. psinetJSONFormat := `
  2063. {
  2064. "default_sponsor_id" : "%s",
  2065. "sponsors" : {
  2066. "%s" : {
  2067. %s
  2068. "home_pages" : {
  2069. "None" : [
  2070. {
  2071. "region" : null,
  2072. "url" : "%s"
  2073. }
  2074. ]
  2075. }
  2076. }
  2077. },
  2078. "default_alert_action_urls" : {
  2079. "%s" : %s
  2080. },
  2081. "valid_server_entry_tags" : {
  2082. %s
  2083. }
  2084. }
  2085. `
  2086. domainBytes := ""
  2087. if doDomainBytes {
  2088. domainBytes = `
  2089. "https_request_regexes" : [
  2090. {
  2091. "regex" : ".*",
  2092. "replace" : "ALL"
  2093. }
  2094. ],
  2095. `
  2096. }
  2097. actionURLsJSON, _ := json.Marshal(testDisallowedTrafficAlertActionURLs)
  2098. validServerEntryTagsJSON := ""
  2099. for _, serverEntryTag := range validServerEntryTags {
  2100. if len(validServerEntryTagsJSON) > 0 {
  2101. validServerEntryTagsJSON += ", "
  2102. }
  2103. validServerEntryTagsJSON += fmt.Sprintf("\"%s\" : true", serverEntryTag)
  2104. }
  2105. psinetJSON := fmt.Sprintf(
  2106. psinetJSONFormat,
  2107. defaultSponsorID,
  2108. sponsorID,
  2109. domainBytes,
  2110. expectedHomepageURL,
  2111. protocol.PSIPHON_API_ALERT_DISALLOWED_TRAFFIC,
  2112. actionURLsJSON,
  2113. validServerEntryTagsJSON)
  2114. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  2115. if err != nil {
  2116. t.Fatalf("error paving psinet database file: %s", err)
  2117. }
  2118. return sponsorID, expectedHomepageURL
  2119. }
  2120. func paveTrafficRulesFile(
  2121. t *testing.T,
  2122. trafficRulesFilename string,
  2123. propagationChannelID string,
  2124. accessType string,
  2125. authorizationID string,
  2126. requireAuthorization bool,
  2127. deny bool,
  2128. livenessTestSize int) {
  2129. // Test both default and fast lookups
  2130. if intLookupThreshold != 10 {
  2131. t.Fatalf("unexpected intLookupThreshold")
  2132. }
  2133. TCPPorts := mockWebServerPort
  2134. UDPPorts := "53, 123, 10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008, 10009, 10010"
  2135. allowTCPPorts := TCPPorts
  2136. allowUDPPorts := UDPPorts
  2137. disallowTCPPorts := "1"
  2138. disallowUDPPorts := "1"
  2139. if deny {
  2140. allowTCPPorts = "1"
  2141. allowUDPPorts = "1"
  2142. disallowTCPPorts = TCPPorts
  2143. disallowUDPPorts = UDPPorts
  2144. }
  2145. authorizationFilterFormat := `,
  2146. "AuthorizedAccessTypes" : ["%s"],
  2147. "ActiveAuthorizationIDs" : ["%s"]
  2148. `
  2149. authorizationFilter := ""
  2150. if requireAuthorization {
  2151. authorizationFilter = fmt.Sprintf(
  2152. authorizationFilterFormat, accessType, authorizationID)
  2153. }
  2154. // Supports two traffic rule test cases:
  2155. //
  2156. // 1. no ports are allowed until after the filtered rule is applied
  2157. // 2. no required ports are allowed (deny = true)
  2158. trafficRulesJSONFormat := `
  2159. {
  2160. "DefaultRules" : {
  2161. "RateLimits" : {
  2162. "ReadBytesPerSecond": 16384,
  2163. "WriteBytesPerSecond": 16384,
  2164. "ReadUnthrottledBytes": %d,
  2165. "WriteUnthrottledBytes": %d
  2166. },
  2167. "AllowTCPPorts" : [1],
  2168. "AllowUDPPorts" : [1],
  2169. "MeekRateLimiterHistorySize" : 10,
  2170. "MeekRateLimiterThresholdSeconds" : 1,
  2171. "MeekRateLimiterGarbageCollectionTriggerCount" : 1,
  2172. "MeekRateLimiterReapHistoryFrequencySeconds" : 1,
  2173. "MeekRateLimiterRegions" : []
  2174. },
  2175. "FilteredRules" : [
  2176. {
  2177. "Filter" : {
  2178. "HandshakeParameters" : {
  2179. "propagation_channel_id" : ["%s"]
  2180. }%s
  2181. },
  2182. "Rules" : {
  2183. "RateLimits" : {
  2184. "ReadBytesPerSecond": 2097152,
  2185. "WriteBytesPerSecond": 2097152
  2186. },
  2187. "AllowTCPPorts" : [%s],
  2188. "AllowUDPPorts" : [%s],
  2189. "DisallowTCPPorts" : [%s],
  2190. "DisallowUDPPorts" : [%s]
  2191. }
  2192. }
  2193. ]
  2194. }
  2195. `
  2196. trafficRulesJSON := fmt.Sprintf(
  2197. trafficRulesJSONFormat,
  2198. livenessTestSize, livenessTestSize,
  2199. propagationChannelID, authorizationFilter,
  2200. allowTCPPorts, allowUDPPorts, disallowTCPPorts, disallowUDPPorts)
  2201. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  2202. if err != nil {
  2203. t.Fatalf("error paving traffic rules file: %s", err)
  2204. }
  2205. }
  2206. var expectedNumSLOKs = 3
  2207. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  2208. oslConfigJSONFormat := `
  2209. {
  2210. "Schemes" : [
  2211. {
  2212. "Epoch" : "%s",
  2213. "Regions" : [],
  2214. "PropagationChannelIDs" : ["%s"],
  2215. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  2216. "SeedSpecs" : [
  2217. {
  2218. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  2219. "UpstreamSubnets" : ["0.0.0.0/0"],
  2220. "Targets" :
  2221. {
  2222. "BytesRead" : 1,
  2223. "BytesWritten" : 1,
  2224. "PortForwardDurationNanoseconds" : 1
  2225. }
  2226. },
  2227. {
  2228. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  2229. "UpstreamSubnets" : ["0.0.0.0/0"],
  2230. "Targets" :
  2231. {
  2232. "BytesRead" : 1,
  2233. "BytesWritten" : 1,
  2234. "PortForwardDurationNanoseconds" : 1
  2235. }
  2236. }
  2237. ],
  2238. "SeedSpecThreshold" : 2,
  2239. "SeedPeriodNanoseconds" : 2592000000000000,
  2240. "SeedPeriodKeySplits": [
  2241. {
  2242. "Total": 2,
  2243. "Threshold": 2
  2244. }
  2245. ]
  2246. },
  2247. {
  2248. "Epoch" : "%s",
  2249. "Regions" : [],
  2250. "PropagationChannelIDs" : ["%s"],
  2251. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  2252. "SeedSpecs" : [
  2253. {
  2254. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  2255. "UpstreamSubnets" : ["0.0.0.0/0"],
  2256. "Targets" :
  2257. {
  2258. "BytesRead" : 1,
  2259. "BytesWritten" : 1,
  2260. "PortForwardDurationNanoseconds" : 1
  2261. }
  2262. }
  2263. ],
  2264. "SeedSpecThreshold" : 1,
  2265. "SeedPeriodNanoseconds" : 2592000000000000,
  2266. "SeedPeriodKeySplits": [
  2267. {
  2268. "Total": 1,
  2269. "Threshold": 1
  2270. }
  2271. ]
  2272. }
  2273. ]
  2274. }
  2275. `
  2276. propagationChannelID := prng.HexString(8)
  2277. now := time.Now().UTC()
  2278. epoch := now.Truncate(720 * time.Hour)
  2279. epochStr := epoch.Format(time.RFC3339Nano)
  2280. oslConfigJSON := fmt.Sprintf(
  2281. oslConfigJSONFormat,
  2282. epochStr, propagationChannelID,
  2283. epochStr, propagationChannelID)
  2284. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  2285. if err != nil {
  2286. t.Fatalf("error paving osl config file: %s", err)
  2287. }
  2288. return propagationChannelID
  2289. }
  2290. func paveTacticsConfigFile(
  2291. t *testing.T, tacticsConfigFilename string,
  2292. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey string,
  2293. tunnelProtocol string,
  2294. propagationChannelID string,
  2295. livenessTestSize int,
  2296. doBurstMonitor bool,
  2297. doDestinationBytes bool) {
  2298. // Setting LimitTunnelProtocols passively exercises the
  2299. // server-side LimitTunnelProtocols enforcement.
  2300. tacticsConfigJSONFormat := `
  2301. {
  2302. "RequestPublicKey" : "%s",
  2303. "RequestPrivateKey" : "%s",
  2304. "RequestObfuscatedKey" : "%s",
  2305. "DefaultTactics" : {
  2306. "TTL" : "60s",
  2307. "Probability" : 1.0,
  2308. "Parameters" : {
  2309. %s
  2310. %s
  2311. "LimitTunnelProtocols" : ["%s"],
  2312. "FragmentorLimitProtocols" : ["%s"],
  2313. "FragmentorProbability" : 1.0,
  2314. "FragmentorMinTotalBytes" : 1000,
  2315. "FragmentorMaxTotalBytes" : 2000,
  2316. "FragmentorMinWriteBytes" : 1,
  2317. "FragmentorMaxWriteBytes" : 100,
  2318. "FragmentorMinDelay" : "1ms",
  2319. "FragmentorMaxDelay" : "10ms",
  2320. "FragmentorDownstreamLimitProtocols" : ["%s"],
  2321. "FragmentorDownstreamProbability" : 1.0,
  2322. "FragmentorDownstreamMinTotalBytes" : 1000,
  2323. "FragmentorDownstreamMaxTotalBytes" : 2000,
  2324. "FragmentorDownstreamMinWriteBytes" : 1,
  2325. "FragmentorDownstreamMaxWriteBytes" : 100,
  2326. "FragmentorDownstreamMinDelay" : "1ms",
  2327. "FragmentorDownstreamMaxDelay" : "10ms",
  2328. "LivenessTestMinUpstreamBytes" : %d,
  2329. "LivenessTestMaxUpstreamBytes" : %d,
  2330. "LivenessTestMinDownstreamBytes" : %d,
  2331. "LivenessTestMaxDownstreamBytes" : %d,
  2332. "BPFServerTCPProgram": {
  2333. "Name" : "test-server-bpf",
  2334. "Instructions" : [
  2335. {"Op": "RetConstant", "Args": {"Val": 65535}}]},
  2336. "BPFServerTCPProbability" : 1.0,
  2337. "BPFClientTCPProgram": {
  2338. "Name" : "test-client-bpf",
  2339. "Instructions" : [
  2340. {"Op": "RetConstant", "Args": {"Val": 65535}}]},
  2341. "BPFClientTCPProbability" : 1.0,
  2342. "ServerPacketManipulationSpecs" : [{"Name": "test-packetman-spec", "PacketSpecs": [["TCP-flags S"]]}],
  2343. "ServerPacketManipulationProbability" : 1.0,
  2344. "ServerProtocolPacketManipulations": {"All" : ["test-packetman-spec"]}
  2345. }
  2346. },
  2347. "FilteredTactics" : [
  2348. {
  2349. "Filter" : {
  2350. "APIParameters" : {"propagation_channel_id" : ["%s"]},
  2351. "SpeedTestRTTMilliseconds" : {
  2352. "Aggregation" : "Median",
  2353. "AtLeast" : 1
  2354. }
  2355. },
  2356. "Tactics" : {
  2357. "Parameters" : {
  2358. "TunnelConnectTimeout" : "20s",
  2359. "TunnelRateLimits" : {"WriteBytesPerSecond": 1000000},
  2360. "TransformHostNameProbability" : 1.0,
  2361. "PickUserAgentProbability" : 1.0,
  2362. "ApplicationParameters" : {
  2363. "AppFlag1" : true,
  2364. "AppConfig1" : {"Option1" : "A", "Option2" : "B"},
  2365. "AppSwitches1" : [1, 2, 3, 4]
  2366. },
  2367. "CustomHostNameRegexes": ["%s"],
  2368. "CustomHostNameProbability": 1.0,
  2369. "CustomHostNameLimitProtocols": ["%s"]
  2370. }
  2371. }
  2372. }
  2373. ]
  2374. }
  2375. `
  2376. burstParameters := ""
  2377. if doBurstMonitor {
  2378. burstParameters = `
  2379. "ServerBurstUpstreamDeadline" : "100ms",
  2380. "ServerBurstUpstreamTargetBytes" : 1000,
  2381. "ServerBurstDownstreamDeadline" : "100ms",
  2382. "ServerBurstDownstreamTargetBytes" : 100000,
  2383. "ClientBurstUpstreamDeadline" : "100ms",
  2384. "ClientBurstUpstreamTargetBytes" : 1000,
  2385. "ClientBurstDownstreamDeadline" : "100ms",
  2386. "ClientBurstDownstreamTargetBytes" : 100000,
  2387. `
  2388. }
  2389. destinationBytesParameters := ""
  2390. if doDestinationBytes {
  2391. destinationBytesParameters = fmt.Sprintf(`
  2392. "DestinationBytesMetricsASN" : "%s",
  2393. `, testGeoIPASN)
  2394. }
  2395. tacticsConfigJSON := fmt.Sprintf(
  2396. tacticsConfigJSONFormat,
  2397. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  2398. burstParameters,
  2399. destinationBytesParameters,
  2400. tunnelProtocol,
  2401. tunnelProtocol,
  2402. tunnelProtocol,
  2403. livenessTestSize, livenessTestSize, livenessTestSize, livenessTestSize,
  2404. propagationChannelID,
  2405. strings.ReplaceAll(testCustomHostNameRegex, `\`, `\\`),
  2406. tunnelProtocol)
  2407. err := ioutil.WriteFile(tacticsConfigFilename, []byte(tacticsConfigJSON), 0600)
  2408. if err != nil {
  2409. t.Fatalf("error paving tactics config file: %s", err)
  2410. }
  2411. }
  2412. func paveBlocklistFile(t *testing.T, blocklistFilename string) {
  2413. blocklistContent :=
  2414. "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"
  2415. err := ioutil.WriteFile(blocklistFilename, []byte(blocklistContent), 0600)
  2416. if err != nil {
  2417. t.Fatalf("error paving blocklist file: %s", err)
  2418. }
  2419. }
  2420. type pruneServerEntryTestCase struct {
  2421. IPAddress string
  2422. ExplicitTag bool
  2423. ExpectedTag string
  2424. LocalTimestamp string
  2425. PsinetValid bool
  2426. ExpectPrune bool
  2427. IsEmbedded bool
  2428. DialPort0 bool
  2429. ServerEntryFields protocol.ServerEntryFields
  2430. }
  2431. func initializePruneServerEntriesTest(
  2432. t *testing.T,
  2433. runConfig *runServerConfig) ([]*pruneServerEntryTestCase, []string, int) {
  2434. if !runConfig.doPruneServerEntries {
  2435. return nil, nil, 0
  2436. }
  2437. newTimeStamp := time.Now().UTC().Format(time.RFC3339)
  2438. oldTimeStamp := time.Now().Add(-30 * 24 * time.Hour).UTC().Format(time.RFC3339)
  2439. // Test Cases:
  2440. // - ExplicitTag: server entry includes a tag; vs. generate a derived tag
  2441. // - LocalTimestamp: server entry is sufficiently old to be pruned; vs. not
  2442. // - PsinetValid: server entry is reported valid by psinet; vs. deleted
  2443. // - ExpectPrune: prune outcome based on flags above
  2444. // - IsEmbedded: pruned embedded server entries leave a tombstone and cannot
  2445. // be reimported
  2446. // - DialPort0: set dial port to 0, a special prune case (see statusAPIRequestHandler)
  2447. pruneServerEntryTestCases := []*pruneServerEntryTestCase{
  2448. &pruneServerEntryTestCase{IPAddress: "192.0.2.1", ExplicitTag: true, LocalTimestamp: newTimeStamp, PsinetValid: true, ExpectPrune: false},
  2449. &pruneServerEntryTestCase{IPAddress: "192.0.2.2", ExplicitTag: false, LocalTimestamp: newTimeStamp, PsinetValid: true, ExpectPrune: false},
  2450. &pruneServerEntryTestCase{IPAddress: "192.0.2.3", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: false},
  2451. &pruneServerEntryTestCase{IPAddress: "192.0.2.4", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: false},
  2452. &pruneServerEntryTestCase{IPAddress: "192.0.2.5", ExplicitTag: true, LocalTimestamp: newTimeStamp, PsinetValid: false, ExpectPrune: false},
  2453. &pruneServerEntryTestCase{IPAddress: "192.0.2.6", ExplicitTag: false, LocalTimestamp: newTimeStamp, PsinetValid: false, ExpectPrune: false},
  2454. &pruneServerEntryTestCase{IPAddress: "192.0.2.7", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: false},
  2455. &pruneServerEntryTestCase{IPAddress: "192.0.2.8", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: false},
  2456. &pruneServerEntryTestCase{IPAddress: "192.0.2.9", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: true},
  2457. &pruneServerEntryTestCase{IPAddress: "192.0.2.10", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: true},
  2458. &pruneServerEntryTestCase{IPAddress: "192.0.2.11", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: false, DialPort0: true},
  2459. &pruneServerEntryTestCase{IPAddress: "192.0.2.12", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: true, DialPort0: true},
  2460. &pruneServerEntryTestCase{IPAddress: "192.0.2.13", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: true, DialPort0: true},
  2461. }
  2462. for _, testCase := range pruneServerEntryTestCases {
  2463. dialPort := 4000
  2464. if testCase.DialPort0 {
  2465. dialPort = 0
  2466. }
  2467. _, _, _, _, encodedServerEntry, err := GenerateConfig(
  2468. &GenerateConfigParams{
  2469. ServerIPAddress: testCase.IPAddress,
  2470. WebServerPort: 8000,
  2471. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: dialPort},
  2472. })
  2473. if err != nil {
  2474. t.Fatalf("GenerateConfig failed: %s", err)
  2475. }
  2476. serverEntrySource := protocol.SERVER_ENTRY_SOURCE_REMOTE
  2477. if testCase.IsEmbedded {
  2478. serverEntrySource = protocol.SERVER_ENTRY_SOURCE_EMBEDDED
  2479. }
  2480. serverEntryFields, err := protocol.DecodeServerEntryFields(
  2481. string(encodedServerEntry),
  2482. testCase.LocalTimestamp,
  2483. serverEntrySource)
  2484. if err != nil {
  2485. t.Fatalf("DecodeServerEntryFields failed: %s", err)
  2486. }
  2487. if testCase.ExplicitTag {
  2488. testCase.ExpectedTag = prng.Base64String(32)
  2489. serverEntryFields.SetTag(testCase.ExpectedTag)
  2490. } else {
  2491. testCase.ExpectedTag = protocol.GenerateServerEntryTag(
  2492. serverEntryFields.GetIPAddress(),
  2493. serverEntryFields.GetWebServerSecret())
  2494. }
  2495. testCase.ServerEntryFields = serverEntryFields
  2496. }
  2497. psinetValidServerEntryTags := make([]string, 0)
  2498. expectedNumPruneNotices := 0
  2499. for _, testCase := range pruneServerEntryTestCases {
  2500. if testCase.PsinetValid {
  2501. psinetValidServerEntryTags = append(
  2502. psinetValidServerEntryTags, testCase.ExpectedTag)
  2503. }
  2504. if testCase.ExpectPrune {
  2505. expectedNumPruneNotices += 1
  2506. }
  2507. }
  2508. return pruneServerEntryTestCases,
  2509. psinetValidServerEntryTags,
  2510. expectedNumPruneNotices
  2511. }
  2512. func storePruneServerEntriesTest(
  2513. t *testing.T,
  2514. runConfig *runServerConfig,
  2515. testDataDirName string,
  2516. pruneServerEntryTestCases []*pruneServerEntryTestCase) {
  2517. if !runConfig.doPruneServerEntries {
  2518. return
  2519. }
  2520. for _, testCase := range pruneServerEntryTestCases {
  2521. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  2522. if err != nil {
  2523. t.Fatalf("StoreServerEntry failed: %s", err)
  2524. }
  2525. }
  2526. clientConfig := &psiphon.Config{
  2527. SponsorId: "0",
  2528. PropagationChannelId: "0",
  2529. // DataRootDirectory must to be set to avoid a migration in the current
  2530. // working directory.
  2531. DataRootDirectory: testDataDirName,
  2532. }
  2533. err := clientConfig.Commit(false)
  2534. if err != nil {
  2535. t.Fatalf("Commit failed: %s", err)
  2536. }
  2537. resolver := psiphon.NewResolver(clientConfig, true)
  2538. defer resolver.Stop()
  2539. clientConfig.SetResolver(resolver)
  2540. applyParameters := make(map[string]interface{})
  2541. applyParameters[parameters.RecordFailedTunnelPersistentStatsProbability] = 1.0
  2542. err = clientConfig.SetParameters("", true, applyParameters)
  2543. if err != nil {
  2544. t.Fatalf("SetParameters failed: %s", err)
  2545. }
  2546. verifyTestCasesStored := make(verifyTestCasesStoredLookup)
  2547. for _, testCase := range pruneServerEntryTestCases {
  2548. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  2549. }
  2550. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  2551. t *testing.T,
  2552. testCase *pruneServerEntryTestCase,
  2553. serverEntry *protocol.ServerEntry) {
  2554. verifyTestCasesStored.isStored(testCase.IPAddress)
  2555. // Check that random tag was retained or derived tag was calculated as
  2556. // expected
  2557. if serverEntry.Tag != testCase.ExpectedTag {
  2558. t.Fatalf("unexpected tag for %s got %s expected %s",
  2559. testCase.IPAddress, serverEntry.Tag, testCase.ExpectedTag)
  2560. }
  2561. // Create failed tunnel event records to exercise pruning
  2562. dialParams, err := psiphon.MakeDialParameters(
  2563. clientConfig,
  2564. nil,
  2565. func(_ *protocol.ServerEntry, _ string) bool { return true },
  2566. func(serverEntry *protocol.ServerEntry) (string, bool) {
  2567. return runConfig.tunnelProtocol, true
  2568. },
  2569. serverEntry,
  2570. false,
  2571. 0,
  2572. 0)
  2573. if err != nil {
  2574. t.Fatalf("MakeDialParameters failed: %s", err)
  2575. }
  2576. err = psiphon.RecordFailedTunnelStat(
  2577. clientConfig, dialParams, nil, 0, 0, std_errors.New("test error"))
  2578. if err != nil {
  2579. t.Fatalf("RecordFailedTunnelStat failed: %s", err)
  2580. }
  2581. })
  2582. verifyTestCasesStored.checkStored(
  2583. t, "missing prune test case server entries")
  2584. }
  2585. func checkPruneServerEntriesTest(
  2586. t *testing.T,
  2587. runConfig *runServerConfig,
  2588. testDataDirName string,
  2589. pruneServerEntryTestCases []*pruneServerEntryTestCase) {
  2590. if !runConfig.doPruneServerEntries {
  2591. return
  2592. }
  2593. clientConfig := &psiphon.Config{
  2594. SponsorId: "0",
  2595. PropagationChannelId: "0",
  2596. // DataRootDirectory must to be set to avoid a migration in the current
  2597. // working directory.
  2598. DataRootDirectory: testDataDirName,
  2599. }
  2600. err := clientConfig.Commit(false)
  2601. if err != nil {
  2602. t.Fatalf("Commit failed: %s", err)
  2603. }
  2604. // Check that server entries remain or are pruned as expected
  2605. verifyTestCasesStored := make(verifyTestCasesStoredLookup)
  2606. for _, testCase := range pruneServerEntryTestCases {
  2607. if !testCase.ExpectPrune {
  2608. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  2609. }
  2610. }
  2611. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  2612. t *testing.T,
  2613. testCase *pruneServerEntryTestCase,
  2614. serverEntry *protocol.ServerEntry) {
  2615. if testCase.ExpectPrune {
  2616. t.Fatalf("expected prune for %s", testCase.IPAddress)
  2617. } else {
  2618. verifyTestCasesStored.isStored(testCase.IPAddress)
  2619. }
  2620. })
  2621. verifyTestCasesStored.checkStored(
  2622. t, "missing prune test case server entries")
  2623. // Check that pruned server entries reimport or not, as expected
  2624. for _, testCase := range pruneServerEntryTestCases {
  2625. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  2626. if err != nil {
  2627. t.Fatalf("StoreServerEntry failed: %s", err)
  2628. }
  2629. }
  2630. verifyTestCasesStored = make(verifyTestCasesStoredLookup)
  2631. for _, testCase := range pruneServerEntryTestCases {
  2632. if !testCase.ExpectPrune || !testCase.IsEmbedded {
  2633. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  2634. }
  2635. }
  2636. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  2637. t *testing.T,
  2638. testCase *pruneServerEntryTestCase,
  2639. serverEntry *protocol.ServerEntry) {
  2640. if testCase.ExpectPrune && testCase.IsEmbedded {
  2641. t.Fatalf("expected tombstone for %s", testCase.IPAddress)
  2642. } else {
  2643. verifyTestCasesStored.isStored(testCase.IPAddress)
  2644. }
  2645. })
  2646. verifyTestCasesStored.checkStored(
  2647. t, "missing reimported prune test case server entries")
  2648. // Non-embedded server entries with tombstones _can_ be reimported
  2649. for _, testCase := range pruneServerEntryTestCases {
  2650. testCase.ServerEntryFields.SetLocalSource(protocol.SERVER_ENTRY_SOURCE_REMOTE)
  2651. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  2652. if err != nil {
  2653. t.Fatalf("StoreServerEntry failed: %s", err)
  2654. }
  2655. }
  2656. verifyTestCasesStored = make(verifyTestCasesStoredLookup)
  2657. for _, testCase := range pruneServerEntryTestCases {
  2658. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  2659. }
  2660. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  2661. t *testing.T,
  2662. testCase *pruneServerEntryTestCase,
  2663. serverEntry *protocol.ServerEntry) {
  2664. verifyTestCasesStored.isStored(testCase.IPAddress)
  2665. })
  2666. verifyTestCasesStored.checkStored(
  2667. t, "missing non-embedded reimported prune test case server entries")
  2668. }
  2669. func scanServerEntries(
  2670. t *testing.T,
  2671. clientConfig *psiphon.Config,
  2672. pruneServerEntryTestCases []*pruneServerEntryTestCase,
  2673. scanner func(
  2674. t *testing.T,
  2675. testCase *pruneServerEntryTestCase,
  2676. serverEntry *protocol.ServerEntry)) {
  2677. _, iterator, err := psiphon.NewServerEntryIterator(clientConfig)
  2678. if err != nil {
  2679. t.Fatalf("NewServerEntryIterator failed: %s", err)
  2680. }
  2681. defer iterator.Close()
  2682. for {
  2683. serverEntry, err := iterator.Next()
  2684. if err != nil {
  2685. t.Fatalf("ServerIterator.Next failed: %s", err)
  2686. }
  2687. if serverEntry == nil {
  2688. break
  2689. }
  2690. for _, testCase := range pruneServerEntryTestCases {
  2691. if testCase.IPAddress == serverEntry.IpAddress {
  2692. scanner(t, testCase, serverEntry)
  2693. break
  2694. }
  2695. }
  2696. }
  2697. }
  2698. type verifyTestCasesStoredLookup map[string]bool
  2699. func (v verifyTestCasesStoredLookup) mustBeStored(s string) {
  2700. v[s] = true
  2701. }
  2702. func (v verifyTestCasesStoredLookup) isStored(s string) {
  2703. delete(v, s)
  2704. }
  2705. func (v verifyTestCasesStoredLookup) checkStored(t *testing.T, errMessage string) {
  2706. if len(v) != 0 {
  2707. t.Fatalf("%s: %+v", errMessage, v)
  2708. }
  2709. }