server_test.go 98 KB

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