server_test.go 96 KB

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