server_test.go 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357
  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/json"
  23. "errors"
  24. "flag"
  25. "fmt"
  26. "io/ioutil"
  27. "net"
  28. "net/http"
  29. "net/url"
  30. "os"
  31. "path/filepath"
  32. "strconv"
  33. "strings"
  34. "sync"
  35. "syscall"
  36. "testing"
  37. "time"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/marionette"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  44. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  45. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  46. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  47. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  48. "golang.org/x/net/proxy"
  49. )
  50. var serverIPAddress, testDataDirName string
  51. var mockWebServerURL, mockWebServerExpectedResponse string
  52. var mockWebServerPort = 8080
  53. func TestMain(m *testing.M) {
  54. flag.Parse()
  55. serverIPv4Address, serverIPv6Address, err := common.GetRoutableInterfaceIPAddresses()
  56. if err != nil {
  57. fmt.Printf("error getting server IP address: %s\n", err)
  58. os.Exit(1)
  59. }
  60. if serverIPv4Address != nil {
  61. serverIPAddress = serverIPv4Address.String()
  62. } else {
  63. serverIPAddress = serverIPv6Address.String()
  64. }
  65. testDataDirName, err = ioutil.TempDir("", "psiphon-server-test")
  66. if err != nil {
  67. fmt.Printf("TempDir failed: %s\n", err)
  68. os.Exit(1)
  69. }
  70. defer os.RemoveAll(testDataDirName)
  71. psiphon.SetEmitDiagnosticNotices(true, true)
  72. mockWebServerURL, mockWebServerExpectedResponse = runMockWebServer()
  73. os.Exit(m.Run())
  74. }
  75. func runMockWebServer() (string, string) {
  76. responseBody := prng.HexString(100000)
  77. serveMux := http.NewServeMux()
  78. serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  79. w.Write([]byte(responseBody))
  80. })
  81. webServerAddress := fmt.Sprintf("%s:%d", serverIPAddress, mockWebServerPort)
  82. server := &http.Server{
  83. Addr: webServerAddress,
  84. Handler: serveMux,
  85. }
  86. go func() {
  87. err := server.ListenAndServe()
  88. if err != nil {
  89. fmt.Printf("error running mock web server: %s\n", err)
  90. os.Exit(1)
  91. }
  92. }()
  93. // TODO: properly synchronize with web server readiness
  94. time.Sleep(1 * time.Second)
  95. return fmt.Sprintf("http://%s/", webServerAddress), responseBody
  96. }
  97. // Note: not testing fronted meek protocols, which client is
  98. // hard-wired to expect running on privileged ports 80 and 443.
  99. func TestSSH(t *testing.T) {
  100. runServer(t,
  101. &runServerConfig{
  102. tunnelProtocol: "SSH",
  103. enableSSHAPIRequests: true,
  104. doHotReload: false,
  105. doDefaultSponsorID: false,
  106. denyTrafficRules: false,
  107. requireAuthorization: true,
  108. omitAuthorization: false,
  109. doTunneledWebRequest: true,
  110. doTunneledNTPRequest: true,
  111. forceFragmenting: false,
  112. forceLivenessTest: false,
  113. doPruneServerEntries: false,
  114. doDanglingTCPConn: true,
  115. })
  116. }
  117. func TestOSSH(t *testing.T) {
  118. runServer(t,
  119. &runServerConfig{
  120. tunnelProtocol: "OSSH",
  121. enableSSHAPIRequests: true,
  122. doHotReload: false,
  123. doDefaultSponsorID: false,
  124. denyTrafficRules: false,
  125. requireAuthorization: true,
  126. omitAuthorization: false,
  127. doTunneledWebRequest: true,
  128. doTunneledNTPRequest: true,
  129. forceFragmenting: false,
  130. forceLivenessTest: false,
  131. doPruneServerEntries: false,
  132. doDanglingTCPConn: true,
  133. })
  134. }
  135. func TestFragmentedOSSH(t *testing.T) {
  136. runServer(t,
  137. &runServerConfig{
  138. tunnelProtocol: "OSSH",
  139. enableSSHAPIRequests: true,
  140. doHotReload: false,
  141. doDefaultSponsorID: false,
  142. denyTrafficRules: false,
  143. requireAuthorization: true,
  144. omitAuthorization: false,
  145. doTunneledWebRequest: true,
  146. doTunneledNTPRequest: true,
  147. forceFragmenting: true,
  148. forceLivenessTest: false,
  149. doPruneServerEntries: false,
  150. doDanglingTCPConn: true,
  151. })
  152. }
  153. func TestUnfrontedMeek(t *testing.T) {
  154. runServer(t,
  155. &runServerConfig{
  156. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  157. enableSSHAPIRequests: true,
  158. doHotReload: false,
  159. doDefaultSponsorID: false,
  160. denyTrafficRules: false,
  161. requireAuthorization: true,
  162. omitAuthorization: false,
  163. doTunneledWebRequest: true,
  164. doTunneledNTPRequest: true,
  165. forceFragmenting: false,
  166. forceLivenessTest: false,
  167. doPruneServerEntries: false,
  168. doDanglingTCPConn: true,
  169. })
  170. }
  171. func TestUnfrontedMeekHTTPS(t *testing.T) {
  172. runServer(t,
  173. &runServerConfig{
  174. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  175. tlsProfile: protocol.TLS_PROFILE_RANDOMIZED,
  176. enableSSHAPIRequests: true,
  177. doHotReload: false,
  178. doDefaultSponsorID: false,
  179. denyTrafficRules: false,
  180. requireAuthorization: true,
  181. omitAuthorization: false,
  182. doTunneledWebRequest: true,
  183. doTunneledNTPRequest: true,
  184. forceFragmenting: false,
  185. forceLivenessTest: false,
  186. doPruneServerEntries: false,
  187. doDanglingTCPConn: true,
  188. })
  189. }
  190. func TestUnfrontedMeekHTTPSTLS13(t *testing.T) {
  191. runServer(t,
  192. &runServerConfig{
  193. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  194. tlsProfile: protocol.TLS_PROFILE_CHROME_70,
  195. enableSSHAPIRequests: true,
  196. doHotReload: false,
  197. doDefaultSponsorID: false,
  198. denyTrafficRules: false,
  199. requireAuthorization: true,
  200. omitAuthorization: false,
  201. doTunneledWebRequest: true,
  202. doTunneledNTPRequest: true,
  203. forceFragmenting: false,
  204. forceLivenessTest: false,
  205. doPruneServerEntries: false,
  206. doDanglingTCPConn: true,
  207. })
  208. }
  209. func TestUnfrontedMeekSessionTicket(t *testing.T) {
  210. runServer(t,
  211. &runServerConfig{
  212. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  213. tlsProfile: protocol.TLS_PROFILE_CHROME_58,
  214. enableSSHAPIRequests: true,
  215. doHotReload: false,
  216. doDefaultSponsorID: false,
  217. denyTrafficRules: false,
  218. requireAuthorization: true,
  219. omitAuthorization: false,
  220. doTunneledWebRequest: true,
  221. doTunneledNTPRequest: true,
  222. forceFragmenting: false,
  223. forceLivenessTest: false,
  224. doPruneServerEntries: false,
  225. doDanglingTCPConn: true,
  226. })
  227. }
  228. func TestUnfrontedMeekSessionTicketTLS13(t *testing.T) {
  229. runServer(t,
  230. &runServerConfig{
  231. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  232. tlsProfile: protocol.TLS_PROFILE_CHROME_70,
  233. enableSSHAPIRequests: true,
  234. doHotReload: false,
  235. doDefaultSponsorID: false,
  236. denyTrafficRules: false,
  237. requireAuthorization: true,
  238. omitAuthorization: false,
  239. doTunneledWebRequest: true,
  240. doTunneledNTPRequest: true,
  241. forceFragmenting: false,
  242. forceLivenessTest: false,
  243. doPruneServerEntries: false,
  244. doDanglingTCPConn: true,
  245. })
  246. }
  247. func TestQUICOSSH(t *testing.T) {
  248. if !quic.Enabled() {
  249. t.Skip("QUIC is not enabled")
  250. }
  251. runServer(t,
  252. &runServerConfig{
  253. tunnelProtocol: "QUIC-OSSH",
  254. enableSSHAPIRequests: true,
  255. doHotReload: false,
  256. doDefaultSponsorID: false,
  257. denyTrafficRules: false,
  258. requireAuthorization: true,
  259. omitAuthorization: false,
  260. doTunneledWebRequest: true,
  261. doTunneledNTPRequest: true,
  262. forceFragmenting: false,
  263. forceLivenessTest: false,
  264. doPruneServerEntries: false,
  265. doDanglingTCPConn: false,
  266. })
  267. }
  268. func TestMarionetteOSSH(t *testing.T) {
  269. if !marionette.Enabled() {
  270. t.Skip("Marionette is not enabled")
  271. }
  272. runServer(t,
  273. &runServerConfig{
  274. tunnelProtocol: "MARIONETTE-OSSH",
  275. enableSSHAPIRequests: true,
  276. doHotReload: false,
  277. doDefaultSponsorID: false,
  278. denyTrafficRules: false,
  279. requireAuthorization: true,
  280. omitAuthorization: false,
  281. doTunneledWebRequest: true,
  282. doTunneledNTPRequest: true,
  283. forceFragmenting: false,
  284. forceLivenessTest: false,
  285. doPruneServerEntries: false,
  286. doDanglingTCPConn: false,
  287. })
  288. }
  289. func TestWebTransportAPIRequests(t *testing.T) {
  290. runServer(t,
  291. &runServerConfig{
  292. tunnelProtocol: "OSSH",
  293. enableSSHAPIRequests: false,
  294. doHotReload: false,
  295. doDefaultSponsorID: false,
  296. denyTrafficRules: false,
  297. requireAuthorization: false,
  298. omitAuthorization: true,
  299. doTunneledWebRequest: true,
  300. doTunneledNTPRequest: true,
  301. forceFragmenting: false,
  302. forceLivenessTest: false,
  303. doPruneServerEntries: false,
  304. doDanglingTCPConn: false,
  305. })
  306. }
  307. func TestHotReload(t *testing.T) {
  308. runServer(t,
  309. &runServerConfig{
  310. tunnelProtocol: "OSSH",
  311. enableSSHAPIRequests: true,
  312. doHotReload: true,
  313. doDefaultSponsorID: false,
  314. denyTrafficRules: false,
  315. requireAuthorization: true,
  316. omitAuthorization: false,
  317. doTunneledWebRequest: true,
  318. doTunneledNTPRequest: true,
  319. forceFragmenting: false,
  320. forceLivenessTest: false,
  321. doPruneServerEntries: false,
  322. doDanglingTCPConn: false,
  323. })
  324. }
  325. func TestDefaultSponsorID(t *testing.T) {
  326. runServer(t,
  327. &runServerConfig{
  328. tunnelProtocol: "OSSH",
  329. enableSSHAPIRequests: true,
  330. doHotReload: true,
  331. doDefaultSponsorID: true,
  332. denyTrafficRules: false,
  333. requireAuthorization: true,
  334. omitAuthorization: false,
  335. doTunneledWebRequest: true,
  336. doTunneledNTPRequest: true,
  337. forceFragmenting: false,
  338. forceLivenessTest: false,
  339. doPruneServerEntries: false,
  340. doDanglingTCPConn: false,
  341. })
  342. }
  343. func TestDenyTrafficRules(t *testing.T) {
  344. runServer(t,
  345. &runServerConfig{
  346. tunnelProtocol: "OSSH",
  347. enableSSHAPIRequests: true,
  348. doHotReload: true,
  349. doDefaultSponsorID: false,
  350. denyTrafficRules: true,
  351. requireAuthorization: true,
  352. omitAuthorization: false,
  353. doTunneledWebRequest: true,
  354. doTunneledNTPRequest: true,
  355. forceFragmenting: false,
  356. forceLivenessTest: false,
  357. doPruneServerEntries: false,
  358. doDanglingTCPConn: false,
  359. })
  360. }
  361. func TestOmitAuthorization(t *testing.T) {
  362. runServer(t,
  363. &runServerConfig{
  364. tunnelProtocol: "OSSH",
  365. enableSSHAPIRequests: true,
  366. doHotReload: true,
  367. doDefaultSponsorID: false,
  368. denyTrafficRules: false,
  369. requireAuthorization: true,
  370. omitAuthorization: true,
  371. doTunneledWebRequest: true,
  372. doTunneledNTPRequest: true,
  373. forceFragmenting: false,
  374. forceLivenessTest: false,
  375. doPruneServerEntries: false,
  376. doDanglingTCPConn: false,
  377. })
  378. }
  379. func TestNoAuthorization(t *testing.T) {
  380. runServer(t,
  381. &runServerConfig{
  382. tunnelProtocol: "OSSH",
  383. enableSSHAPIRequests: true,
  384. doHotReload: true,
  385. doDefaultSponsorID: false,
  386. denyTrafficRules: false,
  387. requireAuthorization: false,
  388. omitAuthorization: true,
  389. doTunneledWebRequest: true,
  390. doTunneledNTPRequest: true,
  391. forceFragmenting: false,
  392. forceLivenessTest: false,
  393. doPruneServerEntries: false,
  394. doDanglingTCPConn: false,
  395. })
  396. }
  397. func TestUnusedAuthorization(t *testing.T) {
  398. runServer(t,
  399. &runServerConfig{
  400. tunnelProtocol: "OSSH",
  401. enableSSHAPIRequests: true,
  402. doHotReload: true,
  403. doDefaultSponsorID: false,
  404. denyTrafficRules: false,
  405. requireAuthorization: false,
  406. omitAuthorization: false,
  407. doTunneledWebRequest: true,
  408. doTunneledNTPRequest: true,
  409. forceFragmenting: false,
  410. forceLivenessTest: false,
  411. doPruneServerEntries: false,
  412. doDanglingTCPConn: false,
  413. })
  414. }
  415. func TestTCPOnlySLOK(t *testing.T) {
  416. runServer(t,
  417. &runServerConfig{
  418. tunnelProtocol: "OSSH",
  419. enableSSHAPIRequests: true,
  420. doHotReload: false,
  421. doDefaultSponsorID: false,
  422. denyTrafficRules: false,
  423. requireAuthorization: true,
  424. omitAuthorization: false,
  425. doTunneledWebRequest: true,
  426. doTunneledNTPRequest: false,
  427. forceFragmenting: false,
  428. forceLivenessTest: false,
  429. doPruneServerEntries: false,
  430. doDanglingTCPConn: false,
  431. })
  432. }
  433. func TestUDPOnlySLOK(t *testing.T) {
  434. runServer(t,
  435. &runServerConfig{
  436. tunnelProtocol: "OSSH",
  437. enableSSHAPIRequests: true,
  438. doHotReload: false,
  439. doDefaultSponsorID: false,
  440. denyTrafficRules: false,
  441. requireAuthorization: true,
  442. omitAuthorization: false,
  443. doTunneledWebRequest: false,
  444. doTunneledNTPRequest: true,
  445. forceFragmenting: false,
  446. forceLivenessTest: false,
  447. doPruneServerEntries: false,
  448. doDanglingTCPConn: false,
  449. })
  450. }
  451. func TestLivenessTest(t *testing.T) {
  452. runServer(t,
  453. &runServerConfig{
  454. tunnelProtocol: "OSSH",
  455. enableSSHAPIRequests: true,
  456. doHotReload: false,
  457. doDefaultSponsorID: false,
  458. denyTrafficRules: false,
  459. requireAuthorization: true,
  460. omitAuthorization: false,
  461. doTunneledWebRequest: true,
  462. doTunneledNTPRequest: true,
  463. forceFragmenting: false,
  464. forceLivenessTest: true,
  465. doPruneServerEntries: false,
  466. doDanglingTCPConn: false,
  467. })
  468. }
  469. func TestPruneServerEntries(t *testing.T) {
  470. runServer(t,
  471. &runServerConfig{
  472. tunnelProtocol: "OSSH",
  473. enableSSHAPIRequests: true,
  474. doHotReload: false,
  475. doDefaultSponsorID: false,
  476. denyTrafficRules: false,
  477. requireAuthorization: true,
  478. omitAuthorization: false,
  479. doTunneledWebRequest: true,
  480. doTunneledNTPRequest: true,
  481. forceFragmenting: false,
  482. forceLivenessTest: true,
  483. doPruneServerEntries: true,
  484. doDanglingTCPConn: false,
  485. })
  486. }
  487. type runServerConfig struct {
  488. tunnelProtocol string
  489. tlsProfile string
  490. enableSSHAPIRequests bool
  491. doHotReload bool
  492. doDefaultSponsorID bool
  493. denyTrafficRules bool
  494. requireAuthorization bool
  495. omitAuthorization bool
  496. doTunneledWebRequest bool
  497. doTunneledNTPRequest bool
  498. forceFragmenting bool
  499. forceLivenessTest bool
  500. doPruneServerEntries bool
  501. doDanglingTCPConn bool
  502. }
  503. var (
  504. testSSHClientVersions = []string{"SSH-2.0-A", "SSH-2.0-B", "SSH-2.0-C"}
  505. testUserAgents = []string{"ua1", "ua2", "ua3"}
  506. testNetworkType = "WIFI"
  507. )
  508. var serverRuns = 0
  509. func runServer(t *testing.T, runConfig *runServerConfig) {
  510. serverRuns += 1
  511. // configure authorized access
  512. accessType := "test-access-type"
  513. accessControlSigningKey, accessControlVerificationKey, err := accesscontrol.NewKeyPair(accessType)
  514. if err != nil {
  515. t.Fatalf("error creating access control key pair: %s", err)
  516. }
  517. accessControlVerificationKeyRing := accesscontrol.VerificationKeyRing{
  518. Keys: []*accesscontrol.VerificationKey{accessControlVerificationKey},
  519. }
  520. var authorizationID [32]byte
  521. clientAuthorization, _, err := accesscontrol.IssueAuthorization(
  522. accessControlSigningKey,
  523. authorizationID[:],
  524. time.Now().Add(1*time.Hour))
  525. if err != nil {
  526. t.Fatalf("error issuing authorization: %s", err)
  527. }
  528. // Enable tactics when the test protocol is meek. Both the client and the
  529. // server will be configured to support tactics. The client config will be
  530. // set with a nonfunctional config so that the tactics request must
  531. // succeed, overriding the nonfunctional values, for the tunnel to
  532. // establish.
  533. doClientTactics := protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol)
  534. doServerTactics := doClientTactics || runConfig.forceFragmenting
  535. // All servers require a tactics config with valid keys.
  536. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err :=
  537. tactics.GenerateKeys()
  538. if err != nil {
  539. t.Fatalf("error generating tactics keys: %s", err)
  540. }
  541. livenessTestSize := 0
  542. if doClientTactics || runConfig.forceLivenessTest {
  543. livenessTestSize = 1048576
  544. }
  545. // create a server
  546. psiphonServerIPAddress := serverIPAddress
  547. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) ||
  548. protocol.TunnelProtocolUsesMarionette(runConfig.tunnelProtocol) {
  549. // Workaround for macOS firewall.
  550. psiphonServerIPAddress = "127.0.0.1"
  551. }
  552. psiphonServerPort := 4000
  553. generateConfigParams := &GenerateConfigParams{
  554. ServerIPAddress: psiphonServerIPAddress,
  555. EnableSSHAPIRequests: runConfig.enableSSHAPIRequests,
  556. WebServerPort: 8000,
  557. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: psiphonServerPort},
  558. }
  559. if protocol.TunnelProtocolUsesMarionette(runConfig.tunnelProtocol) {
  560. generateConfigParams.TunnelProtocolPorts[runConfig.tunnelProtocol] = 0
  561. generateConfigParams.MarionetteFormat = "http_simple_nonblocking"
  562. }
  563. if doServerTactics {
  564. generateConfigParams.TacticsRequestPublicKey = tacticsRequestPublicKey
  565. generateConfigParams.TacticsRequestObfuscatedKey = tacticsRequestObfuscatedKey
  566. }
  567. serverConfigJSON, _, _, _, encodedServerEntry, err := GenerateConfig(generateConfigParams)
  568. if err != nil {
  569. t.Fatalf("error generating server config: %s", err)
  570. }
  571. // customize server config
  572. // Initialize prune server entry test cases and associated data to pave into psinet.
  573. pruneServerEntryTestCases, psinetValidServerEntryTags, expectedNumPruneNotices :=
  574. initializePruneServerEntriesTest(t, runConfig)
  575. // Pave psinet with random values to test handshake homepages.
  576. psinetFilename := filepath.Join(testDataDirName, "psinet.json")
  577. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(
  578. t, runConfig.doDefaultSponsorID, psinetFilename, psinetValidServerEntryTags)
  579. // Pave OSL config for SLOK testing
  580. oslConfigFilename := filepath.Join(testDataDirName, "osl_config.json")
  581. propagationChannelID := paveOSLConfigFile(t, oslConfigFilename)
  582. // Pave traffic rules file which exercises handshake parameter filtering. Client
  583. // must handshake with specified sponsor ID in order to allow ports for tunneled
  584. // requests.
  585. trafficRulesFilename := filepath.Join(testDataDirName, "traffic_rules.json")
  586. paveTrafficRulesFile(
  587. t, trafficRulesFilename, propagationChannelID, accessType,
  588. runConfig.requireAuthorization, runConfig.denyTrafficRules, livenessTestSize)
  589. var tacticsConfigFilename string
  590. // Only pave the tactics config when tactics are required. This exercises the
  591. // case where the tactics config is omitted.
  592. if doServerTactics {
  593. tacticsConfigFilename = filepath.Join(testDataDirName, "tactics_config.json")
  594. paveTacticsConfigFile(
  595. t, tacticsConfigFilename,
  596. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  597. runConfig.tunnelProtocol,
  598. propagationChannelID,
  599. livenessTestSize)
  600. }
  601. blocklistFilename := filepath.Join(testDataDirName, "blocklist.csv")
  602. paveBlocklistFile(t, blocklistFilename)
  603. var serverConfig map[string]interface{}
  604. json.Unmarshal(serverConfigJSON, &serverConfig)
  605. serverConfig["GeoIPDatabaseFilename"] = ""
  606. serverConfig["PsinetDatabaseFilename"] = psinetFilename
  607. serverConfig["TrafficRulesFilename"] = trafficRulesFilename
  608. serverConfig["OSLConfigFilename"] = oslConfigFilename
  609. if doServerTactics {
  610. serverConfig["TacticsConfigFilename"] = tacticsConfigFilename
  611. }
  612. serverConfig["BlocklistFilename"] = blocklistFilename
  613. serverConfig["LogFilename"] = filepath.Join(testDataDirName, "psiphond.log")
  614. serverConfig["LogLevel"] = "debug"
  615. serverConfig["AccessControlVerificationKeyRing"] = accessControlVerificationKeyRing
  616. // Set this parameter so at least the semaphore functions are called.
  617. // TODO: test that the concurrency limit is correctly enforced.
  618. serverConfig["MaxConcurrentSSHHandshakes"] = 1
  619. // Exercise this option.
  620. serverConfig["PeriodicGarbageCollectionSeconds"] = 1
  621. // Allow port forwards to local test web server.
  622. serverConfig["AllowBogons"] = true
  623. serverConfigJSON, _ = json.Marshal(serverConfig)
  624. serverTunnelLog := make(chan map[string]interface{}, 1)
  625. uniqueUserLog := make(chan map[string]interface{}, 1)
  626. setLogCallback(func(log []byte) {
  627. logFields := make(map[string]interface{})
  628. err := json.Unmarshal(log, &logFields)
  629. if err != nil {
  630. return
  631. }
  632. if logFields["event_name"] == nil {
  633. return
  634. }
  635. switch logFields["event_name"].(string) {
  636. case "unique_user":
  637. select {
  638. case uniqueUserLog <- logFields:
  639. default:
  640. }
  641. case "server_tunnel":
  642. select {
  643. case serverTunnelLog <- logFields:
  644. default:
  645. }
  646. }
  647. })
  648. // run server
  649. serverWaitGroup := new(sync.WaitGroup)
  650. serverWaitGroup.Add(1)
  651. go func() {
  652. defer serverWaitGroup.Done()
  653. err := RunServices(serverConfigJSON)
  654. if err != nil {
  655. // TODO: wrong goroutine for t.FatalNow()
  656. t.Errorf("error running server: %s", err)
  657. }
  658. }()
  659. stopServer := func() {
  660. // Test: orderly server shutdown
  661. p, _ := os.FindProcess(os.Getpid())
  662. p.Signal(os.Interrupt)
  663. shutdownTimeout := time.NewTimer(5 * time.Second)
  664. shutdownOk := make(chan struct{}, 1)
  665. go func() {
  666. serverWaitGroup.Wait()
  667. shutdownOk <- struct{}{}
  668. }()
  669. select {
  670. case <-shutdownOk:
  671. case <-shutdownTimeout.C:
  672. t.Errorf("server shutdown timeout exceeded")
  673. }
  674. }
  675. // Stop server on early exits due to failure.
  676. defer func() {
  677. if stopServer != nil {
  678. stopServer()
  679. }
  680. }()
  681. // TODO: monitor logs for more robust wait-until-loaded. For example,
  682. // especially with the race detector on, QUIC-OSSH tests can fail as the
  683. // client sends its initial packet before the server is ready.
  684. time.Sleep(1 * time.Second)
  685. // Test: hot reload (of psinet and traffic rules)
  686. if runConfig.doHotReload {
  687. // Pave new config files with different random values.
  688. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(
  689. t, runConfig.doDefaultSponsorID, psinetFilename, psinetValidServerEntryTags)
  690. propagationChannelID = paveOSLConfigFile(t, oslConfigFilename)
  691. paveTrafficRulesFile(
  692. t, trafficRulesFilename, propagationChannelID, accessType,
  693. runConfig.requireAuthorization, runConfig.denyTrafficRules,
  694. livenessTestSize)
  695. p, _ := os.FindProcess(os.Getpid())
  696. p.Signal(syscall.SIGUSR1)
  697. // TODO: monitor logs for more robust wait-until-reloaded
  698. time.Sleep(1 * time.Second)
  699. // After reloading psinet, the new sponsorID/expectedHomepageURL
  700. // should be active, as tested in the client "Homepage" notice
  701. // handler below.
  702. }
  703. // Exercise server_load logging
  704. p, _ := os.FindProcess(os.Getpid())
  705. p.Signal(syscall.SIGUSR2)
  706. // configure client
  707. values.SetSSHClientVersionsSpec(values.NewPickOneSpec(testSSHClientVersions))
  708. values.SetUserAgentsSpec(values.NewPickOneSpec(testUserAgents))
  709. // TODO: currently, TargetServerEntry only works with one tunnel
  710. numTunnels := 1
  711. localSOCKSProxyPort := 1081
  712. localHTTPProxyPort := 8081
  713. // Use a distinct suffix for network ID for each test run to ensure tactics
  714. // from different runs don't apply; this is a workaround for the singleton
  715. // datastore.
  716. jsonNetworkID := fmt.Sprintf(`,"NetworkID" : "WIFI-%s"`, time.Now().String())
  717. jsonLimitTLSProfiles := ""
  718. if runConfig.tlsProfile != "" {
  719. jsonLimitTLSProfiles = fmt.Sprintf(`,"LimitTLSProfiles" : ["%s"]`, runConfig.tlsProfile)
  720. }
  721. clientConfigJSON := fmt.Sprintf(`
  722. {
  723. "ClientPlatform" : "Android_10_com.test.app",
  724. "ClientVersion" : "0",
  725. "SponsorId" : "0",
  726. "PropagationChannelId" : "0",
  727. "TunnelWholeDevice" : 1,
  728. "DeviceRegion" : "US",
  729. "DisableRemoteServerListFetcher" : true,
  730. "EstablishTunnelPausePeriodSeconds" : 1,
  731. "ConnectionWorkerPoolSize" : %d,
  732. "LimitTunnelProtocols" : ["%s"]
  733. %s
  734. %s
  735. }`, numTunnels, runConfig.tunnelProtocol, jsonLimitTLSProfiles, jsonNetworkID)
  736. clientConfig, err := psiphon.LoadConfig([]byte(clientConfigJSON))
  737. if err != nil {
  738. t.Fatalf("error processing configuration file: %s", err)
  739. }
  740. clientConfig.DataRootDirectory = testDataDirName
  741. if !runConfig.doDefaultSponsorID {
  742. clientConfig.SponsorId = sponsorID
  743. }
  744. clientConfig.PropagationChannelId = propagationChannelID
  745. clientConfig.TunnelPoolSize = numTunnels
  746. clientConfig.TargetServerEntry = string(encodedServerEntry)
  747. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  748. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  749. clientConfig.EmitSLOKs = true
  750. clientConfig.EmitServerAlerts = true
  751. if !runConfig.omitAuthorization {
  752. clientConfig.Authorizations = []string{clientAuthorization}
  753. }
  754. err = clientConfig.Commit(false)
  755. if err != nil {
  756. t.Fatalf("error committing configuration file: %s", err)
  757. }
  758. if doClientTactics {
  759. // Configure nonfunctional values that must be overridden by tactics.
  760. applyParameters := make(map[string]interface{})
  761. applyParameters[parameters.TunnelConnectTimeout] = "1s"
  762. applyParameters[parameters.TunnelRateLimits] = common.RateLimits{WriteBytesPerSecond: 1}
  763. err = clientConfig.SetClientParameters("", true, applyParameters)
  764. if err != nil {
  765. t.Fatalf("SetClientParameters failed: %s", err)
  766. }
  767. } else {
  768. // Directly apply same parameters that would've come from tactics.
  769. applyParameters := make(map[string]interface{})
  770. if runConfig.forceFragmenting {
  771. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols{runConfig.tunnelProtocol}
  772. applyParameters[parameters.FragmentorProbability] = 1.0
  773. applyParameters[parameters.FragmentorMinTotalBytes] = 1000
  774. applyParameters[parameters.FragmentorMaxTotalBytes] = 2000
  775. applyParameters[parameters.FragmentorMinWriteBytes] = 1
  776. applyParameters[parameters.FragmentorMaxWriteBytes] = 100
  777. applyParameters[parameters.FragmentorMinDelay] = 1 * time.Millisecond
  778. applyParameters[parameters.FragmentorMaxDelay] = 10 * time.Millisecond
  779. }
  780. if runConfig.forceLivenessTest {
  781. applyParameters[parameters.LivenessTestMinUpstreamBytes] = livenessTestSize
  782. applyParameters[parameters.LivenessTestMaxUpstreamBytes] = livenessTestSize
  783. applyParameters[parameters.LivenessTestMinDownstreamBytes] = livenessTestSize
  784. applyParameters[parameters.LivenessTestMaxDownstreamBytes] = livenessTestSize
  785. }
  786. if runConfig.doPruneServerEntries {
  787. applyParameters[parameters.PsiphonAPIStatusRequestShortPeriodMin] = 1 * time.Millisecond
  788. applyParameters[parameters.PsiphonAPIStatusRequestShortPeriodMax] = 1 * time.Millisecond
  789. }
  790. err = clientConfig.SetClientParameters("", true, applyParameters)
  791. if err != nil {
  792. t.Fatalf("SetClientParameters failed: %s", err)
  793. }
  794. }
  795. // connect to server with client
  796. err = psiphon.OpenDataStore(clientConfig)
  797. if err != nil {
  798. t.Fatalf("error initializing client datastore: %s", err)
  799. }
  800. defer psiphon.CloseDataStore()
  801. // Test unique user counting cases.
  802. var expectUniqueUser bool
  803. switch serverRuns % 3 {
  804. case 0:
  805. // Mock no last_connected.
  806. psiphon.SetKeyValue("lastConnected", "")
  807. expectUniqueUser = true
  808. case 1:
  809. // Mock previous day last_connected.
  810. psiphon.SetKeyValue(
  811. "lastConnected",
  812. time.Now().UTC().AddDate(0, 0, -1).Truncate(1*time.Hour).Format(time.RFC3339))
  813. expectUniqueUser = true
  814. case 2:
  815. // Leave previous last_connected.
  816. expectUniqueUser = false
  817. }
  818. // Clear SLOKs from previous test runs.
  819. psiphon.DeleteSLOKs()
  820. // Store prune server entry test server entries and failed tunnel records.
  821. storePruneServerEntriesTest(
  822. t, runConfig, testDataDirName, pruneServerEntryTestCases)
  823. controller, err := psiphon.NewController(clientConfig)
  824. if err != nil {
  825. t.Fatalf("error creating client controller: %s", err)
  826. }
  827. connectedServer := make(chan struct{}, 1)
  828. tunnelsEstablished := make(chan struct{}, 1)
  829. homepageReceived := make(chan struct{}, 1)
  830. slokSeeded := make(chan struct{}, 1)
  831. numPruneNotices := 0
  832. pruneServerEntriesNoticesEmitted := make(chan struct{}, 1)
  833. serverAlertDisallowedNoticesEmitted := make(chan struct{}, 1)
  834. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  835. func(notice []byte) {
  836. //fmt.Printf("%s\n", string(notice))
  837. noticeType, payload, err := psiphon.GetNotice(notice)
  838. if err != nil {
  839. return
  840. }
  841. switch noticeType {
  842. case "ConnectedServer":
  843. sendNotificationReceived(connectedServer)
  844. case "Tunnels":
  845. count := int(payload["count"].(float64))
  846. if count >= numTunnels {
  847. sendNotificationReceived(tunnelsEstablished)
  848. }
  849. case "Homepage":
  850. homepageURL := payload["url"].(string)
  851. if homepageURL != expectedHomepageURL {
  852. // TODO: wrong goroutine for t.FatalNow()
  853. t.Errorf("unexpected homepage: %s", homepageURL)
  854. }
  855. sendNotificationReceived(homepageReceived)
  856. case "SLOKSeeded":
  857. sendNotificationReceived(slokSeeded)
  858. case "PruneServerEntry":
  859. numPruneNotices += 1
  860. if numPruneNotices == expectedNumPruneNotices {
  861. sendNotificationReceived(pruneServerEntriesNoticesEmitted)
  862. }
  863. case "ServerAlert":
  864. reason := payload["reason"].(string)
  865. if reason == protocol.PSIPHON_API_ALERT_DISALLOWED_TRAFFIC {
  866. sendNotificationReceived(serverAlertDisallowedNoticesEmitted)
  867. }
  868. }
  869. }))
  870. ctx, cancelFunc := context.WithCancel(context.Background())
  871. controllerWaitGroup := new(sync.WaitGroup)
  872. controllerWaitGroup.Add(1)
  873. go func() {
  874. defer controllerWaitGroup.Done()
  875. controller.Run(ctx)
  876. }()
  877. stopClient := func() {
  878. cancelFunc()
  879. shutdownTimeout := time.NewTimer(20 * time.Second)
  880. shutdownOk := make(chan struct{}, 1)
  881. go func() {
  882. controllerWaitGroup.Wait()
  883. shutdownOk <- struct{}{}
  884. }()
  885. select {
  886. case <-shutdownOk:
  887. case <-shutdownTimeout.C:
  888. t.Errorf("controller shutdown timeout exceeded")
  889. }
  890. }
  891. // Stop client on early exits due to failure.
  892. defer func() {
  893. if stopClient != nil {
  894. stopClient()
  895. }
  896. }()
  897. // Test: tunnels must be established, and correct homepage
  898. // must be received, within 30 seconds
  899. timeoutSignal := make(chan struct{})
  900. go func() {
  901. timer := time.NewTimer(30 * time.Second)
  902. <-timer.C
  903. close(timeoutSignal)
  904. }()
  905. waitOnNotification(t, connectedServer, timeoutSignal, "connected server timeout exceeded")
  906. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel established timeout exceeded")
  907. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  908. expectTrafficFailure := runConfig.denyTrafficRules || (runConfig.omitAuthorization && runConfig.requireAuthorization)
  909. if runConfig.doTunneledWebRequest {
  910. // Test: tunneled web site fetch
  911. err = makeTunneledWebRequest(
  912. t, localHTTPProxyPort, mockWebServerURL, mockWebServerExpectedResponse)
  913. if err == nil {
  914. if expectTrafficFailure {
  915. t.Fatalf("unexpected tunneled web request success")
  916. }
  917. } else {
  918. if !expectTrafficFailure {
  919. t.Fatalf("tunneled web request failed: %s", err)
  920. }
  921. }
  922. }
  923. if runConfig.doTunneledNTPRequest {
  924. // Test: tunneled UDP packets
  925. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  926. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  927. if err == nil {
  928. if expectTrafficFailure {
  929. t.Fatalf("unexpected tunneled NTP request success")
  930. }
  931. } else {
  932. if !expectTrafficFailure {
  933. t.Fatalf("tunneled NTP request failed: %s", err)
  934. }
  935. }
  936. }
  937. // Test: await SLOK payload or server alert notice
  938. time.Sleep(1 * time.Second)
  939. if !expectTrafficFailure {
  940. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  941. numSLOKs := psiphon.CountSLOKs()
  942. if numSLOKs != expectedNumSLOKs {
  943. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  944. }
  945. } else {
  946. // Note: in expectTrafficFailure case, timeoutSignal may have already fired.
  947. waitOnNotification(t, serverAlertDisallowedNoticesEmitted, nil, "")
  948. }
  949. // Test: await expected prune server entry notices
  950. //
  951. // Note: will take up to PsiphonAPIStatusRequestShortPeriodMax to emit.
  952. if expectedNumPruneNotices > 0 {
  953. waitOnNotification(t, pruneServerEntriesNoticesEmitted, nil, "")
  954. }
  955. if runConfig.doDanglingTCPConn {
  956. // Test: client that has established TCP connection but not completed
  957. // any handshakes must not block/delay server shutdown
  958. danglingConn, err := net.Dial(
  959. "tcp", net.JoinHostPort(psiphonServerIPAddress, strconv.Itoa(psiphonServerPort)))
  960. if err != nil {
  961. t.Fatalf("TCP dial failed: %s", err)
  962. }
  963. defer danglingConn.Close()
  964. }
  965. // Shutdown to ensure logs/notices are flushed
  966. stopClient()
  967. stopClient = nil
  968. stopServer()
  969. stopServer = nil
  970. // Test: all expected server logs were emitted
  971. // TODO: stops should be fully synchronous, but, intermittently,
  972. // server_tunnel fails to appear ("missing server tunnel log")
  973. // without this delay.
  974. time.Sleep(100 * time.Millisecond)
  975. expectClientBPFField := psiphon.ClientBPFEnabled() && doClientTactics
  976. expectServerBPFField := ServerBPFEnabled() && doServerTactics
  977. select {
  978. case logFields := <-serverTunnelLog:
  979. err := checkExpectedServerTunnelLogFields(
  980. runConfig, expectClientBPFField, expectServerBPFField, logFields)
  981. if err != nil {
  982. t.Fatalf("invalid server tunnel log fields: %s", err)
  983. }
  984. default:
  985. t.Fatalf("missing server tunnel log")
  986. }
  987. if expectUniqueUser {
  988. select {
  989. case logFields := <-uniqueUserLog:
  990. err := checkExpectedUniqueUserLogFields(runConfig, logFields)
  991. if err != nil {
  992. t.Fatalf("invalid unique user log fields: %s", err)
  993. }
  994. default:
  995. t.Fatalf("missing unique user log")
  996. }
  997. } else {
  998. select {
  999. case <-uniqueUserLog:
  1000. t.Fatalf("unexpected unique user log")
  1001. default:
  1002. }
  1003. }
  1004. // Check that datastore had retained/pruned server entries as expected.
  1005. checkPruneServerEntriesTest(t, runConfig, testDataDirName, pruneServerEntryTestCases)
  1006. }
  1007. func checkExpectedServerTunnelLogFields(
  1008. runConfig *runServerConfig,
  1009. expectClientBPFField bool,
  1010. expectServerBPFField bool,
  1011. fields map[string]interface{}) error {
  1012. // Limitations:
  1013. //
  1014. // - client_build_rev not set in test build (see common/buildinfo.go)
  1015. // - egress_region, upstream_proxy_type, upstream_proxy_custom_header_names not exercised in test
  1016. // - fronting_provider_id/meek_dial_ip_address/meek_resolved_ip_address only logged for FRONTED meek protocols
  1017. for _, name := range []string{
  1018. "session_id",
  1019. "last_connected",
  1020. "establishment_duration",
  1021. "propagation_channel_id",
  1022. "sponsor_id",
  1023. "client_platform",
  1024. "relay_protocol",
  1025. "tunnel_whole_device",
  1026. "device_region",
  1027. "ssh_client_version",
  1028. "server_entry_region",
  1029. "server_entry_source",
  1030. "server_entry_timestamp",
  1031. "dial_port_number",
  1032. "is_replay",
  1033. "dial_duration",
  1034. "candidate_number",
  1035. "established_tunnels_count",
  1036. "network_latency_multiplier",
  1037. "network_type",
  1038. } {
  1039. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1040. return fmt.Errorf("missing expected field '%s'", name)
  1041. }
  1042. }
  1043. if fields["relay_protocol"].(string) != runConfig.tunnelProtocol {
  1044. return fmt.Errorf("unexpected relay_protocol '%s'", fields["relay_protocol"])
  1045. }
  1046. if !common.Contains(testSSHClientVersions, fields["ssh_client_version"].(string)) {
  1047. return fmt.Errorf("unexpected relay_protocol '%s'", fields["ssh_client_version"])
  1048. }
  1049. if protocol.TunnelProtocolUsesObfuscatedSSH(runConfig.tunnelProtocol) {
  1050. for _, name := range []string{
  1051. "padding",
  1052. "pad_response",
  1053. } {
  1054. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1055. return fmt.Errorf("missing expected field '%s'", name)
  1056. }
  1057. }
  1058. }
  1059. if protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol) {
  1060. for _, name := range []string{
  1061. "user_agent",
  1062. "meek_transformed_host_name",
  1063. "meek_cookie_size",
  1064. "meek_limit_request",
  1065. tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME,
  1066. } {
  1067. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1068. return fmt.Errorf("missing expected field '%s'", name)
  1069. }
  1070. }
  1071. if !common.Contains(testUserAgents, fields["user_agent"].(string)) {
  1072. return fmt.Errorf("unexpected user_agent '%s'", fields["user_agent"])
  1073. }
  1074. }
  1075. if protocol.TunnelProtocolUsesMeekHTTP(runConfig.tunnelProtocol) {
  1076. for _, name := range []string{
  1077. "meek_host_header",
  1078. } {
  1079. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1080. return fmt.Errorf("missing expected field '%s'", name)
  1081. }
  1082. }
  1083. for _, name := range []string{
  1084. "meek_dial_ip_address",
  1085. "meek_resolved_ip_address",
  1086. } {
  1087. if fields[name] != nil {
  1088. return fmt.Errorf("unexpected field '%s'", name)
  1089. }
  1090. }
  1091. }
  1092. if protocol.TunnelProtocolUsesMeekHTTPS(runConfig.tunnelProtocol) {
  1093. for _, name := range []string{
  1094. "tls_profile",
  1095. "tls_version",
  1096. "meek_sni_server_name",
  1097. } {
  1098. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1099. return fmt.Errorf("missing expected field '%s'", name)
  1100. }
  1101. }
  1102. for _, name := range []string{
  1103. "meek_dial_ip_address",
  1104. "meek_resolved_ip_address",
  1105. "meek_host_header",
  1106. } {
  1107. if fields[name] != nil {
  1108. return fmt.Errorf("unexpected field '%s'", name)
  1109. }
  1110. }
  1111. if !common.Contains(protocol.SupportedTLSProfiles, fields["tls_profile"].(string)) {
  1112. return fmt.Errorf("unexpected tls_profile '%s'", fields["tls_profile"])
  1113. }
  1114. tlsVersion := fields["tls_version"].(string)
  1115. if !strings.HasPrefix(tlsVersion, protocol.TLS_VERSION_12) &&
  1116. !strings.HasPrefix(tlsVersion, protocol.TLS_VERSION_13) {
  1117. return fmt.Errorf("unexpected tls_version '%s'", fields["tls_version"])
  1118. }
  1119. }
  1120. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) {
  1121. for _, name := range []string{
  1122. "quic_version",
  1123. "quic_dial_sni_address",
  1124. } {
  1125. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1126. return fmt.Errorf("missing expected field '%s'", name)
  1127. }
  1128. }
  1129. if !common.Contains(protocol.SupportedQUICVersions, fields["quic_version"].(string)) {
  1130. return fmt.Errorf("unexpected quic_version '%s'", fields["quic_version"])
  1131. }
  1132. }
  1133. if runConfig.forceFragmenting {
  1134. for _, name := range []string{
  1135. "upstream_bytes_fragmented",
  1136. "upstream_min_bytes_written",
  1137. "upstream_max_bytes_written",
  1138. "upstream_min_delayed",
  1139. "upstream_max_delayed",
  1140. } {
  1141. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1142. return fmt.Errorf("missing expected field '%s'", name)
  1143. }
  1144. }
  1145. }
  1146. if expectClientBPFField {
  1147. name := "client_bpf"
  1148. if fields[name] == nil {
  1149. return fmt.Errorf("missing expected field '%s'", name)
  1150. } else if fmt.Sprintf("%s", fields[name]) != "test-client-bpf" {
  1151. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  1152. }
  1153. }
  1154. if expectServerBPFField {
  1155. name := "server_bpf"
  1156. if fields[name] == nil {
  1157. return fmt.Errorf("missing expected field '%s'", name)
  1158. } else if fmt.Sprintf("%s", fields[name]) != "test-server-bpf" {
  1159. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  1160. }
  1161. }
  1162. if fields["network_type"].(string) != testNetworkType {
  1163. return fmt.Errorf("unexpected network_type '%s'", fields["network_type"])
  1164. }
  1165. return nil
  1166. }
  1167. func checkExpectedUniqueUserLogFields(
  1168. runConfig *runServerConfig,
  1169. fields map[string]interface{}) error {
  1170. for _, name := range []string{
  1171. "session_id",
  1172. "last_connected",
  1173. "propagation_channel_id",
  1174. "sponsor_id",
  1175. "client_platform",
  1176. "tunnel_whole_device",
  1177. "device_region",
  1178. } {
  1179. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1180. return fmt.Errorf("missing expected field '%s'", name)
  1181. }
  1182. }
  1183. return nil
  1184. }
  1185. func makeTunneledWebRequest(
  1186. t *testing.T,
  1187. localHTTPProxyPort int,
  1188. requestURL, expectedResponseBody string) error {
  1189. roundTripTimeout := 30 * time.Second
  1190. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  1191. if err != nil {
  1192. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  1193. }
  1194. httpClient := &http.Client{
  1195. Transport: &http.Transport{
  1196. Proxy: http.ProxyURL(proxyUrl),
  1197. },
  1198. Timeout: roundTripTimeout,
  1199. }
  1200. response, err := httpClient.Get(requestURL)
  1201. if err != nil {
  1202. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  1203. }
  1204. body, err := ioutil.ReadAll(response.Body)
  1205. if err != nil {
  1206. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  1207. }
  1208. response.Body.Close()
  1209. if string(body) != expectedResponseBody {
  1210. return fmt.Errorf("unexpected proxied HTTP response")
  1211. }
  1212. return nil
  1213. }
  1214. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  1215. timeout := 20 * time.Second
  1216. var err error
  1217. for _, testHostname := range []string{"time.google.com", "time.nist.gov", "pool.ntp.org"} {
  1218. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  1219. if err == nil {
  1220. break
  1221. }
  1222. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  1223. }
  1224. return err
  1225. }
  1226. var nextUDPProxyPort = 7300
  1227. func makeTunneledNTPRequestAttempt(
  1228. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  1229. nextUDPProxyPort++
  1230. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  1231. if err != nil {
  1232. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  1233. }
  1234. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  1235. // handles it, and then terminates.
  1236. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  1237. if waitGroup != nil {
  1238. defer waitGroup.Done()
  1239. }
  1240. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  1241. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  1242. if err != nil {
  1243. t.Logf("ListenUDP for %s failed: %s", destination, err)
  1244. return
  1245. }
  1246. defer serverUDPConn.Close()
  1247. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  1248. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  1249. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  1250. buffer[udpgwPreambleSize:])
  1251. if err != nil {
  1252. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  1253. return
  1254. }
  1255. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  1256. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  1257. if err != nil {
  1258. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  1259. return
  1260. }
  1261. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  1262. if err != nil {
  1263. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  1264. return
  1265. }
  1266. defer socksTCPConn.Close()
  1267. flags := uint8(0)
  1268. if destinationPort == 53 {
  1269. flags = udpgwProtocolFlagDNS
  1270. }
  1271. err = writeUdpgwPreamble(
  1272. udpgwPreambleSize,
  1273. flags,
  1274. 0,
  1275. destinationIP,
  1276. destinationPort,
  1277. uint16(packetSize),
  1278. buffer)
  1279. if err != nil {
  1280. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  1281. return
  1282. }
  1283. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  1284. if err != nil {
  1285. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  1286. return
  1287. }
  1288. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  1289. if err != nil {
  1290. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  1291. return
  1292. }
  1293. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  1294. if err != nil {
  1295. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  1296. return
  1297. }
  1298. }
  1299. // Tunneled DNS request
  1300. waitGroup := new(sync.WaitGroup)
  1301. waitGroup.Add(1)
  1302. go localUDPProxy(
  1303. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  1304. 53,
  1305. waitGroup)
  1306. // TODO: properly synchronize with local UDP proxy startup
  1307. time.Sleep(1 * time.Second)
  1308. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  1309. if err != nil {
  1310. return fmt.Errorf("DialUDP failed: %s", err)
  1311. }
  1312. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  1313. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  1314. addrs, _, err := psiphon.ResolveIP(testHostname, clientUDPConn)
  1315. clientUDPConn.Close()
  1316. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  1317. err = errors.New("no address")
  1318. }
  1319. if err != nil {
  1320. return fmt.Errorf("ResolveIP failed: %s", err)
  1321. }
  1322. waitGroup.Wait()
  1323. // Tunneled NTP request
  1324. waitGroup = new(sync.WaitGroup)
  1325. waitGroup.Add(1)
  1326. go localUDPProxy(
  1327. addrs[0][len(addrs[0])-4:],
  1328. 123,
  1329. waitGroup)
  1330. // TODO: properly synchronize with local UDP proxy startup
  1331. time.Sleep(1 * time.Second)
  1332. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  1333. if err != nil {
  1334. return fmt.Errorf("DialUDP failed: %s", err)
  1335. }
  1336. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  1337. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  1338. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  1339. ntpData := make([]byte, 48)
  1340. ntpData[0] = 3<<3 | 3
  1341. _, err = clientUDPConn.Write(ntpData)
  1342. if err != nil {
  1343. clientUDPConn.Close()
  1344. return fmt.Errorf("NTP Write failed: %s", err)
  1345. }
  1346. _, err = clientUDPConn.Read(ntpData)
  1347. if err != nil {
  1348. clientUDPConn.Close()
  1349. return fmt.Errorf("NTP Read failed: %s", err)
  1350. }
  1351. clientUDPConn.Close()
  1352. var sec, frac uint64
  1353. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  1354. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  1355. nsec := sec * 1e9
  1356. nsec += (frac * 1e9) >> 32
  1357. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  1358. now := time.Now()
  1359. diff := ntpNow.Sub(now)
  1360. if diff < 0 {
  1361. diff = -diff
  1362. }
  1363. if diff > 1*time.Minute {
  1364. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  1365. }
  1366. waitGroup.Wait()
  1367. return nil
  1368. }
  1369. func pavePsinetDatabaseFile(
  1370. t *testing.T,
  1371. useDefaultSponsorID bool,
  1372. psinetFilename string,
  1373. validServerEntryTags []string) (string, string) {
  1374. sponsorID := prng.HexString(8)
  1375. defaultSponsorID := ""
  1376. if useDefaultSponsorID {
  1377. defaultSponsorID = sponsorID
  1378. }
  1379. fakeDomain := prng.HexString(4)
  1380. fakePath := prng.HexString(4)
  1381. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  1382. psinetJSONFormat := `
  1383. {
  1384. "default_sponsor_id" : "%s",
  1385. "sponsors": {
  1386. "%s": {
  1387. "home_pages": {
  1388. "None": [
  1389. {
  1390. "region": null,
  1391. "url": "%s"
  1392. }
  1393. ]
  1394. }
  1395. }
  1396. },
  1397. "valid_server_entry_tags" : {
  1398. %s
  1399. }
  1400. }
  1401. `
  1402. validServerEntryTagsJSON := ""
  1403. for _, serverEntryTag := range validServerEntryTags {
  1404. if len(validServerEntryTagsJSON) > 0 {
  1405. validServerEntryTagsJSON += ", "
  1406. }
  1407. validServerEntryTagsJSON += fmt.Sprintf("\"%s\" : true", serverEntryTag)
  1408. }
  1409. psinetJSON := fmt.Sprintf(
  1410. psinetJSONFormat,
  1411. defaultSponsorID,
  1412. sponsorID,
  1413. expectedHomepageURL,
  1414. validServerEntryTagsJSON)
  1415. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  1416. if err != nil {
  1417. t.Fatalf("error paving psinet database file: %s", err)
  1418. }
  1419. return sponsorID, expectedHomepageURL
  1420. }
  1421. func paveTrafficRulesFile(
  1422. t *testing.T, trafficRulesFilename, propagationChannelID, accessType string,
  1423. requireAuthorization, deny bool,
  1424. livenessTestSize int) {
  1425. // Test both default and fast lookups
  1426. if intLookupThreshold != 10 {
  1427. t.Fatalf("unexpected intLookupThreshold")
  1428. }
  1429. TCPPorts := fmt.Sprintf("%d", mockWebServerPort)
  1430. UDPPorts := "53, 123, 10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008, 10009, 10010"
  1431. allowTCPPorts := TCPPorts
  1432. allowUDPPorts := UDPPorts
  1433. disallowTCPPorts := "0"
  1434. disallowUDPPorts := "0"
  1435. if deny {
  1436. allowTCPPorts = "0"
  1437. allowUDPPorts = "0"
  1438. disallowTCPPorts = TCPPorts
  1439. disallowUDPPorts = UDPPorts
  1440. }
  1441. authorizationFilterFormat := `,
  1442. "AuthorizedAccessTypes" : ["%s"]
  1443. `
  1444. authorizationFilter := ""
  1445. if requireAuthorization {
  1446. authorizationFilter = fmt.Sprintf(authorizationFilterFormat, accessType)
  1447. }
  1448. // Supports two traffic rule test cases:
  1449. //
  1450. // 1. no ports are allowed until after the filtered rule is applied
  1451. // 2. no required ports are allowed (deny = true)
  1452. trafficRulesJSONFormat := `
  1453. {
  1454. "DefaultRules" : {
  1455. "RateLimits" : {
  1456. "ReadBytesPerSecond": 16384,
  1457. "WriteBytesPerSecond": 16384,
  1458. "ReadUnthrottledBytes": %d,
  1459. "WriteUnthrottledBytes": %d
  1460. },
  1461. "AllowTCPPorts" : [0],
  1462. "AllowUDPPorts" : [0],
  1463. "MeekRateLimiterHistorySize" : 10,
  1464. "MeekRateLimiterThresholdSeconds" : 1,
  1465. "MeekRateLimiterGarbageCollectionTriggerCount" : 1,
  1466. "MeekRateLimiterReapHistoryFrequencySeconds" : 1,
  1467. "MeekRateLimiterRegions" : []
  1468. },
  1469. "FilteredRules" : [
  1470. {
  1471. "Filter" : {
  1472. "HandshakeParameters" : {
  1473. "propagation_channel_id" : ["%s"]
  1474. }%s
  1475. },
  1476. "Rules" : {
  1477. "RateLimits" : {
  1478. "ReadBytesPerSecond": 2097152,
  1479. "WriteBytesPerSecond": 2097152
  1480. },
  1481. "AllowTCPPorts" : [%s],
  1482. "AllowUDPPorts" : [%s],
  1483. "DisallowTCPPorts" : [%s],
  1484. "DisallowUDPPorts" : [%s]
  1485. }
  1486. }
  1487. ]
  1488. }
  1489. `
  1490. trafficRulesJSON := fmt.Sprintf(
  1491. trafficRulesJSONFormat,
  1492. livenessTestSize, livenessTestSize,
  1493. propagationChannelID, authorizationFilter,
  1494. allowTCPPorts, allowUDPPorts, disallowTCPPorts, disallowUDPPorts)
  1495. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  1496. if err != nil {
  1497. t.Fatalf("error paving traffic rules file: %s", err)
  1498. }
  1499. }
  1500. var expectedNumSLOKs = 3
  1501. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  1502. oslConfigJSONFormat := `
  1503. {
  1504. "Schemes" : [
  1505. {
  1506. "Epoch" : "%s",
  1507. "Regions" : [],
  1508. "PropagationChannelIDs" : ["%s"],
  1509. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  1510. "SeedSpecs" : [
  1511. {
  1512. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  1513. "UpstreamSubnets" : ["0.0.0.0/0"],
  1514. "Targets" :
  1515. {
  1516. "BytesRead" : 1,
  1517. "BytesWritten" : 1,
  1518. "PortForwardDurationNanoseconds" : 1
  1519. }
  1520. },
  1521. {
  1522. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  1523. "UpstreamSubnets" : ["0.0.0.0/0"],
  1524. "Targets" :
  1525. {
  1526. "BytesRead" : 1,
  1527. "BytesWritten" : 1,
  1528. "PortForwardDurationNanoseconds" : 1
  1529. }
  1530. }
  1531. ],
  1532. "SeedSpecThreshold" : 2,
  1533. "SeedPeriodNanoseconds" : 2592000000000000,
  1534. "SeedPeriodKeySplits": [
  1535. {
  1536. "Total": 2,
  1537. "Threshold": 2
  1538. }
  1539. ]
  1540. },
  1541. {
  1542. "Epoch" : "%s",
  1543. "Regions" : [],
  1544. "PropagationChannelIDs" : ["%s"],
  1545. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  1546. "SeedSpecs" : [
  1547. {
  1548. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  1549. "UpstreamSubnets" : ["0.0.0.0/0"],
  1550. "Targets" :
  1551. {
  1552. "BytesRead" : 1,
  1553. "BytesWritten" : 1,
  1554. "PortForwardDurationNanoseconds" : 1
  1555. }
  1556. }
  1557. ],
  1558. "SeedSpecThreshold" : 1,
  1559. "SeedPeriodNanoseconds" : 2592000000000000,
  1560. "SeedPeriodKeySplits": [
  1561. {
  1562. "Total": 1,
  1563. "Threshold": 1
  1564. }
  1565. ]
  1566. }
  1567. ]
  1568. }
  1569. `
  1570. propagationChannelID := prng.HexString(8)
  1571. now := time.Now().UTC()
  1572. epoch := now.Truncate(720 * time.Hour)
  1573. epochStr := epoch.Format(time.RFC3339Nano)
  1574. oslConfigJSON := fmt.Sprintf(
  1575. oslConfigJSONFormat,
  1576. epochStr, propagationChannelID,
  1577. epochStr, propagationChannelID)
  1578. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  1579. if err != nil {
  1580. t.Fatalf("error paving osl config file: %s", err)
  1581. }
  1582. return propagationChannelID
  1583. }
  1584. func paveTacticsConfigFile(
  1585. t *testing.T, tacticsConfigFilename string,
  1586. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey string,
  1587. tunnelProtocol string,
  1588. propagationChannelID string,
  1589. livenessTestSize int) {
  1590. // Setting LimitTunnelProtocols passively exercises the
  1591. // server-side LimitTunnelProtocols enforcement.
  1592. tacticsConfigJSONFormat := `
  1593. {
  1594. "RequestPublicKey" : "%s",
  1595. "RequestPrivateKey" : "%s",
  1596. "RequestObfuscatedKey" : "%s",
  1597. "EnforceServerSide" : true,
  1598. "DefaultTactics" : {
  1599. "TTL" : "60s",
  1600. "Probability" : 1.0,
  1601. "Parameters" : {
  1602. "LimitTunnelProtocols" : ["%s"],
  1603. "FragmentorLimitProtocols" : ["%s"],
  1604. "FragmentorProbability" : 1.0,
  1605. "FragmentorMinTotalBytes" : 1000,
  1606. "FragmentorMaxTotalBytes" : 2000,
  1607. "FragmentorMinWriteBytes" : 1,
  1608. "FragmentorMaxWriteBytes" : 100,
  1609. "FragmentorMinDelay" : "1ms",
  1610. "FragmentorMaxDelay" : "10ms",
  1611. "FragmentorDownstreamLimitProtocols" : ["%s"],
  1612. "FragmentorDownstreamProbability" : 1.0,
  1613. "FragmentorDownstreamMinTotalBytes" : 1000,
  1614. "FragmentorDownstreamMaxTotalBytes" : 2000,
  1615. "FragmentorDownstreamMinWriteBytes" : 1,
  1616. "FragmentorDownstreamMaxWriteBytes" : 100,
  1617. "FragmentorDownstreamMinDelay" : "1ms",
  1618. "FragmentorDownstreamMaxDelay" : "10ms",
  1619. "LivenessTestMinUpstreamBytes" : %d,
  1620. "LivenessTestMaxUpstreamBytes" : %d,
  1621. "LivenessTestMinDownstreamBytes" : %d,
  1622. "LivenessTestMaxDownstreamBytes" : %d,
  1623. "BPFServerTCPProgram": {
  1624. "Name" : "test-server-bpf",
  1625. "Instructions" : [
  1626. {"Op": "RetConstant", "Args": {"Val": 65535}}]},
  1627. "BPFServerTCPProbability" : 1.0,
  1628. "BPFClientTCPProgram": {
  1629. "Name" : "test-client-bpf",
  1630. "Instructions" : [
  1631. {"Op": "RetConstant", "Args": {"Val": 65535}}]},
  1632. "BPFClientTCPProbability" : 1.0
  1633. }
  1634. },
  1635. "FilteredTactics" : [
  1636. {
  1637. "Filter" : {
  1638. "APIParameters" : {"propagation_channel_id" : ["%s"]},
  1639. "SpeedTestRTTMilliseconds" : {
  1640. "Aggregation" : "Median",
  1641. "AtLeast" : 1
  1642. }
  1643. },
  1644. "Tactics" : {
  1645. "Parameters" : {
  1646. "TunnelConnectTimeout" : "20s",
  1647. "TunnelRateLimits" : {"WriteBytesPerSecond": 1000000},
  1648. "TransformHostNameProbability" : 1.0,
  1649. "PickUserAgentProbability" : 1.0,
  1650. "ApplicationParameters" : {
  1651. "AppFlag1" : true,
  1652. "AppConfig1" : {"Option1" : "A", "Option2" : "B"},
  1653. "AppSwitches1" : [1, 2, 3, 4]
  1654. }
  1655. }
  1656. }
  1657. }
  1658. ]
  1659. }
  1660. `
  1661. tacticsConfigJSON := fmt.Sprintf(
  1662. tacticsConfigJSONFormat,
  1663. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  1664. tunnelProtocol,
  1665. tunnelProtocol,
  1666. tunnelProtocol,
  1667. livenessTestSize, livenessTestSize, livenessTestSize, livenessTestSize,
  1668. propagationChannelID)
  1669. err := ioutil.WriteFile(tacticsConfigFilename, []byte(tacticsConfigJSON), 0600)
  1670. if err != nil {
  1671. t.Fatalf("error paving tactics config file: %s", err)
  1672. }
  1673. }
  1674. func paveBlocklistFile(t *testing.T, blocklistFilename string) {
  1675. blocklistContent :=
  1676. "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"
  1677. err := ioutil.WriteFile(blocklistFilename, []byte(blocklistContent), 0600)
  1678. if err != nil {
  1679. t.Fatalf("error paving blocklist file: %s", err)
  1680. }
  1681. }
  1682. func sendNotificationReceived(c chan<- struct{}) {
  1683. select {
  1684. case c <- struct{}{}:
  1685. default:
  1686. }
  1687. }
  1688. func waitOnNotification(t *testing.T, c, timeoutSignal <-chan struct{}, timeoutMessage string) {
  1689. if timeoutSignal == nil {
  1690. <-c
  1691. } else {
  1692. select {
  1693. case <-c:
  1694. case <-timeoutSignal:
  1695. t.Fatalf(timeoutMessage)
  1696. }
  1697. }
  1698. }
  1699. type pruneServerEntryTestCase struct {
  1700. IPAddress string
  1701. ExplicitTag bool
  1702. ExpectedTag string
  1703. LocalTimestamp string
  1704. PsinetValid bool
  1705. ExpectPrune bool
  1706. IsEmbedded bool
  1707. DialPort0 bool
  1708. ServerEntryFields protocol.ServerEntryFields
  1709. }
  1710. func initializePruneServerEntriesTest(
  1711. t *testing.T,
  1712. runConfig *runServerConfig) ([]*pruneServerEntryTestCase, []string, int) {
  1713. if !runConfig.doPruneServerEntries {
  1714. return nil, nil, 0
  1715. }
  1716. newTimeStamp := time.Now().UTC().Format(time.RFC3339)
  1717. oldTimeStamp := time.Now().Add(-30 * 24 * time.Hour).UTC().Format(time.RFC3339)
  1718. // Test Cases:
  1719. // - ExplicitTag: server entry includes a tag; vs. generate a derived tag
  1720. // - LocalTimestamp: server entry is sufficiently old to be pruned; vs. not
  1721. // - PsinetValid: server entry is reported valid by psinet; vs. deleted
  1722. // - ExpectPrune: prune outcome based on flags above
  1723. // - IsEmbedded: pruned embedded server entries leave a tombstone and cannot
  1724. // be reimported
  1725. // - DialPort0: set dial port to 0, a special prune case (see statusAPIRequestHandler)
  1726. pruneServerEntryTestCases := []*pruneServerEntryTestCase{
  1727. &pruneServerEntryTestCase{IPAddress: "192.0.2.1", ExplicitTag: true, LocalTimestamp: newTimeStamp, PsinetValid: true, ExpectPrune: false},
  1728. &pruneServerEntryTestCase{IPAddress: "192.0.2.2", ExplicitTag: false, LocalTimestamp: newTimeStamp, PsinetValid: true, ExpectPrune: false},
  1729. &pruneServerEntryTestCase{IPAddress: "192.0.2.3", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: false},
  1730. &pruneServerEntryTestCase{IPAddress: "192.0.2.4", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: false},
  1731. &pruneServerEntryTestCase{IPAddress: "192.0.2.5", ExplicitTag: true, LocalTimestamp: newTimeStamp, PsinetValid: false, ExpectPrune: false},
  1732. &pruneServerEntryTestCase{IPAddress: "192.0.2.6", ExplicitTag: false, LocalTimestamp: newTimeStamp, PsinetValid: false, ExpectPrune: false},
  1733. &pruneServerEntryTestCase{IPAddress: "192.0.2.7", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: false},
  1734. &pruneServerEntryTestCase{IPAddress: "192.0.2.8", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: false},
  1735. &pruneServerEntryTestCase{IPAddress: "192.0.2.9", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: true},
  1736. &pruneServerEntryTestCase{IPAddress: "192.0.2.10", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: true},
  1737. &pruneServerEntryTestCase{IPAddress: "192.0.2.11", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: false, DialPort0: true},
  1738. &pruneServerEntryTestCase{IPAddress: "192.0.2.12", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: true, DialPort0: true},
  1739. &pruneServerEntryTestCase{IPAddress: "192.0.2.13", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: true, DialPort0: true},
  1740. }
  1741. for _, testCase := range pruneServerEntryTestCases {
  1742. dialPort := 4000
  1743. if testCase.DialPort0 {
  1744. dialPort = 0
  1745. }
  1746. _, _, _, _, encodedServerEntry, err := GenerateConfig(
  1747. &GenerateConfigParams{
  1748. ServerIPAddress: testCase.IPAddress,
  1749. WebServerPort: 8000,
  1750. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: dialPort},
  1751. })
  1752. if err != nil {
  1753. t.Fatalf("GenerateConfig failed: %s", err)
  1754. }
  1755. serverEntrySource := protocol.SERVER_ENTRY_SOURCE_REMOTE
  1756. if testCase.IsEmbedded {
  1757. serverEntrySource = protocol.SERVER_ENTRY_SOURCE_EMBEDDED
  1758. }
  1759. serverEntryFields, err := protocol.DecodeServerEntryFields(
  1760. string(encodedServerEntry),
  1761. testCase.LocalTimestamp,
  1762. serverEntrySource)
  1763. if err != nil {
  1764. t.Fatalf("DecodeServerEntryFields failed: %s", err)
  1765. }
  1766. if testCase.ExplicitTag {
  1767. testCase.ExpectedTag = prng.Base64String(32)
  1768. serverEntryFields.SetTag(testCase.ExpectedTag)
  1769. } else {
  1770. testCase.ExpectedTag = protocol.GenerateServerEntryTag(
  1771. serverEntryFields.GetIPAddress(),
  1772. serverEntryFields.GetWebServerSecret())
  1773. }
  1774. testCase.ServerEntryFields = serverEntryFields
  1775. }
  1776. psinetValidServerEntryTags := make([]string, 0)
  1777. expectedNumPruneNotices := 0
  1778. for _, testCase := range pruneServerEntryTestCases {
  1779. if testCase.PsinetValid {
  1780. psinetValidServerEntryTags = append(
  1781. psinetValidServerEntryTags, testCase.ExpectedTag)
  1782. }
  1783. if testCase.ExpectPrune {
  1784. expectedNumPruneNotices += 1
  1785. }
  1786. }
  1787. return pruneServerEntryTestCases,
  1788. psinetValidServerEntryTags,
  1789. expectedNumPruneNotices
  1790. }
  1791. func storePruneServerEntriesTest(
  1792. t *testing.T,
  1793. runConfig *runServerConfig,
  1794. testDataDirName string,
  1795. pruneServerEntryTestCases []*pruneServerEntryTestCase) {
  1796. if !runConfig.doPruneServerEntries {
  1797. return
  1798. }
  1799. for _, testCase := range pruneServerEntryTestCases {
  1800. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  1801. if err != nil {
  1802. t.Fatalf("StoreServerEntry failed: %s", err)
  1803. }
  1804. }
  1805. clientConfig := &psiphon.Config{
  1806. SponsorId: "0",
  1807. PropagationChannelId: "0",
  1808. // DataRootDirectory must to be set to avoid a migration in the current
  1809. // working directory.
  1810. DataRootDirectory: testDataDirName,
  1811. }
  1812. err := clientConfig.Commit(false)
  1813. if err != nil {
  1814. t.Fatalf("Commit failed: %s", err)
  1815. }
  1816. applyParameters := make(map[string]interface{})
  1817. applyParameters[parameters.RecordFailedTunnelPersistentStatsProbability] = 1.0
  1818. err = clientConfig.SetClientParameters("", true, applyParameters)
  1819. if err != nil {
  1820. t.Fatalf("SetClientParameters failed: %s", err)
  1821. }
  1822. verifyTestCasesStored := make(verifyTestCasesStoredLookup)
  1823. for _, testCase := range pruneServerEntryTestCases {
  1824. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  1825. }
  1826. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  1827. t *testing.T,
  1828. testCase *pruneServerEntryTestCase,
  1829. serverEntry *protocol.ServerEntry) {
  1830. verifyTestCasesStored.isStored(testCase.IPAddress)
  1831. // Check that random tag was retained or derived tag was calculated as
  1832. // expected
  1833. if serverEntry.Tag != testCase.ExpectedTag {
  1834. t.Fatalf("unexpected tag for %s got %s expected %s",
  1835. testCase.IPAddress, serverEntry.Tag, testCase.ExpectedTag)
  1836. }
  1837. // Create failed tunnel event records to exercise pruning
  1838. dialParams, err := psiphon.MakeDialParameters(
  1839. clientConfig,
  1840. func(_ *protocol.ServerEntry, _ string) bool { return true },
  1841. func(serverEntry *protocol.ServerEntry) (string, bool) {
  1842. return runConfig.tunnelProtocol, true
  1843. },
  1844. serverEntry,
  1845. false,
  1846. 0,
  1847. 0)
  1848. if err != nil {
  1849. t.Fatalf("MakeDialParameters failed: %s", err)
  1850. }
  1851. err = psiphon.RecordFailedTunnelStat(
  1852. clientConfig, dialParams, nil, 0, 0, errors.New("test error"))
  1853. if err != nil {
  1854. t.Fatalf("RecordFailedTunnelStat failed: %s", err)
  1855. }
  1856. })
  1857. verifyTestCasesStored.checkStored(
  1858. t, "missing prune test case server entries")
  1859. }
  1860. func checkPruneServerEntriesTest(
  1861. t *testing.T,
  1862. runConfig *runServerConfig,
  1863. testDataDirName string,
  1864. pruneServerEntryTestCases []*pruneServerEntryTestCase) {
  1865. if !runConfig.doPruneServerEntries {
  1866. return
  1867. }
  1868. clientConfig := &psiphon.Config{
  1869. SponsorId: "0",
  1870. PropagationChannelId: "0",
  1871. // DataRootDirectory must to be set to avoid a migration in the current
  1872. // working directory.
  1873. DataRootDirectory: testDataDirName,
  1874. }
  1875. err := clientConfig.Commit(false)
  1876. if err != nil {
  1877. t.Fatalf("Commit failed: %s", err)
  1878. }
  1879. // Check that server entries remain or are pruned as expected
  1880. verifyTestCasesStored := make(verifyTestCasesStoredLookup)
  1881. for _, testCase := range pruneServerEntryTestCases {
  1882. if !testCase.ExpectPrune {
  1883. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  1884. }
  1885. }
  1886. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  1887. t *testing.T,
  1888. testCase *pruneServerEntryTestCase,
  1889. serverEntry *protocol.ServerEntry) {
  1890. if testCase.ExpectPrune {
  1891. t.Fatalf("expected prune for %s", testCase.IPAddress)
  1892. } else {
  1893. verifyTestCasesStored.isStored(testCase.IPAddress)
  1894. }
  1895. })
  1896. verifyTestCasesStored.checkStored(
  1897. t, "missing prune test case server entries")
  1898. // Check that pruned server entries reimport or not, as expected
  1899. for _, testCase := range pruneServerEntryTestCases {
  1900. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  1901. if err != nil {
  1902. t.Fatalf("StoreServerEntry failed: %s", err)
  1903. }
  1904. }
  1905. verifyTestCasesStored = make(verifyTestCasesStoredLookup)
  1906. for _, testCase := range pruneServerEntryTestCases {
  1907. if !testCase.ExpectPrune || !testCase.IsEmbedded {
  1908. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  1909. }
  1910. }
  1911. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  1912. t *testing.T,
  1913. testCase *pruneServerEntryTestCase,
  1914. serverEntry *protocol.ServerEntry) {
  1915. if testCase.ExpectPrune && testCase.IsEmbedded {
  1916. t.Fatalf("expected tombstone for %s", testCase.IPAddress)
  1917. } else {
  1918. verifyTestCasesStored.isStored(testCase.IPAddress)
  1919. }
  1920. })
  1921. verifyTestCasesStored.checkStored(
  1922. t, "missing reimported prune test case server entries")
  1923. // Non-embedded server entries with tombstones _can_ be reimported
  1924. for _, testCase := range pruneServerEntryTestCases {
  1925. testCase.ServerEntryFields.SetLocalSource(protocol.SERVER_ENTRY_SOURCE_REMOTE)
  1926. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  1927. if err != nil {
  1928. t.Fatalf("StoreServerEntry failed: %s", err)
  1929. }
  1930. }
  1931. verifyTestCasesStored = make(verifyTestCasesStoredLookup)
  1932. for _, testCase := range pruneServerEntryTestCases {
  1933. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  1934. }
  1935. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  1936. t *testing.T,
  1937. testCase *pruneServerEntryTestCase,
  1938. serverEntry *protocol.ServerEntry) {
  1939. verifyTestCasesStored.isStored(testCase.IPAddress)
  1940. })
  1941. verifyTestCasesStored.checkStored(
  1942. t, "missing non-embedded reimported prune test case server entries")
  1943. }
  1944. func scanServerEntries(
  1945. t *testing.T,
  1946. clientConfig *psiphon.Config,
  1947. pruneServerEntryTestCases []*pruneServerEntryTestCase,
  1948. scanner func(
  1949. t *testing.T,
  1950. testCase *pruneServerEntryTestCase,
  1951. serverEntry *protocol.ServerEntry)) {
  1952. _, iterator, err := psiphon.NewServerEntryIterator(clientConfig)
  1953. if err != nil {
  1954. t.Fatalf("NewServerEntryIterator failed: %s", err)
  1955. }
  1956. defer iterator.Close()
  1957. for {
  1958. serverEntry, err := iterator.Next()
  1959. if err != nil {
  1960. t.Fatalf("ServerIterator.Next failed: %s", err)
  1961. }
  1962. if serverEntry == nil {
  1963. break
  1964. }
  1965. for _, testCase := range pruneServerEntryTestCases {
  1966. if testCase.IPAddress == serverEntry.IpAddress {
  1967. scanner(t, testCase, serverEntry)
  1968. break
  1969. }
  1970. }
  1971. }
  1972. }
  1973. type verifyTestCasesStoredLookup map[string]bool
  1974. func (v verifyTestCasesStoredLookup) mustBeStored(s string) {
  1975. v[s] = true
  1976. }
  1977. func (v verifyTestCasesStoredLookup) isStored(s string) {
  1978. delete(v, s)
  1979. }
  1980. func (v verifyTestCasesStoredLookup) checkStored(t *testing.T, errMessage string) {
  1981. if len(v) != 0 {
  1982. t.Fatalf("%s: %+v", errMessage, v)
  1983. }
  1984. }