server_test.go 91 KB

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