server_test.go 76 KB

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