remoteServerList_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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 psiphon
  20. import (
  21. "bytes"
  22. "crypto/md5"
  23. "encoding/base64"
  24. "encoding/hex"
  25. "fmt"
  26. "io"
  27. "io/ioutil"
  28. "net"
  29. "net/http"
  30. "net/url"
  31. "os"
  32. "path"
  33. "path/filepath"
  34. "sync"
  35. "testing"
  36. "time"
  37. socks "github.com/Psiphon-Inc/goptlib"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server"
  41. )
  42. // TODO: TestCommonRemoteServerList (this is currently covered by controller_test.go)
  43. func TestObfuscatedRemoteServerLists(t *testing.T) {
  44. testDataDirName, err := ioutil.TempDir("", "psiphon-remote-server-list-test")
  45. if err != nil {
  46. t.Fatalf("TempDir failed: %s", err)
  47. }
  48. defer os.RemoveAll(testDataDirName)
  49. //
  50. // create a server
  51. //
  52. serverIPaddress := ""
  53. for _, interfaceName := range []string{"eth0", "en0"} {
  54. serverIPaddress, err = common.GetInterfaceIPAddress(interfaceName)
  55. if err == nil {
  56. break
  57. }
  58. }
  59. if err != nil {
  60. t.Fatalf("error getting server IP address: %s", err)
  61. }
  62. serverConfigJSON, _, encodedServerEntry, err := server.GenerateConfig(
  63. &server.GenerateConfigParams{
  64. ServerIPAddress: serverIPaddress,
  65. EnableSSHAPIRequests: true,
  66. WebServerPort: 8001,
  67. TunnelProtocolPorts: map[string]int{"OSSH": 4001},
  68. })
  69. if err != nil {
  70. t.Fatalf("error generating server config: %s", err)
  71. }
  72. //
  73. // pave OSLs
  74. //
  75. oslConfigJSONTemplate := `
  76. {
  77. "Schemes" : [
  78. {
  79. "Epoch" : "%s",
  80. "Regions" : [],
  81. "PropagationChannelIDs" : ["%s"],
  82. "MasterKey" : "vwab2WY3eNyMBpyFVPtsivMxF4MOpNHM/T7rHJIXctg=",
  83. "SeedSpecs" : [
  84. {
  85. "ID" : "KuP2V6gLcROIFzb/27fUVu4SxtEfm2omUoISlrWv1mA=",
  86. "UpstreamSubnets" : ["0.0.0.0/0"],
  87. "Targets" :
  88. {
  89. "BytesRead" : 1,
  90. "BytesWritten" : 1,
  91. "PortForwardDurationNanoseconds" : 1
  92. }
  93. }
  94. ],
  95. "SeedSpecThreshold" : 1,
  96. "SeedPeriodNanoseconds" : %d,
  97. "SeedPeriodKeySplits": [
  98. {
  99. "Total": 1,
  100. "Threshold": 1
  101. }
  102. ]
  103. }
  104. ]
  105. }`
  106. now := time.Now().UTC()
  107. seedPeriod := 24 * time.Hour
  108. epoch := now.Truncate(seedPeriod)
  109. epochStr := epoch.Format(time.RFC3339Nano)
  110. propagationChannelID, _ := common.MakeRandomStringHex(8)
  111. oslConfigJSON := fmt.Sprintf(
  112. oslConfigJSONTemplate,
  113. epochStr,
  114. propagationChannelID,
  115. seedPeriod)
  116. oslConfig, err := osl.LoadConfig([]byte(oslConfigJSON))
  117. if err != nil {
  118. t.Fatalf("error loading OSL config: %s", err)
  119. }
  120. signingPublicKey, signingPrivateKey, err := common.GenerateAuthenticatedDataPackageKeys()
  121. if err != nil {
  122. t.Fatalf("error generating package keys: %s", err)
  123. }
  124. // First Pave() call is to get the OSL ID to pave into
  125. oslID := ""
  126. paveFiles, err := oslConfig.Pave(
  127. epoch,
  128. propagationChannelID,
  129. signingPublicKey,
  130. signingPrivateKey,
  131. map[string][]string{},
  132. func(logInfo *osl.PaveLogInfo) {
  133. oslID = logInfo.OSLID
  134. })
  135. if err != nil {
  136. t.Fatalf("error paving OSL files: %s", err)
  137. }
  138. paveFiles, err = oslConfig.Pave(
  139. epoch,
  140. propagationChannelID,
  141. signingPublicKey,
  142. signingPrivateKey,
  143. map[string][]string{
  144. oslID: []string{string(encodedServerEntry)},
  145. },
  146. nil)
  147. if err != nil {
  148. t.Fatalf("error paving OSL files: %s", err)
  149. }
  150. //
  151. // mock seeding SLOKs
  152. //
  153. singleton = dataStore{}
  154. os.Remove(filepath.Join(testDataDirName, DATA_STORE_FILENAME))
  155. err = InitDataStore(&Config{DataStoreDirectory: testDataDirName})
  156. if err != nil {
  157. t.Fatalf("error initializing client datastore: %s", err)
  158. }
  159. if CountServerEntries("", "") > 0 {
  160. t.Fatalf("unexpected server entries")
  161. }
  162. seedState := oslConfig.NewClientSeedState("", propagationChannelID, nil)
  163. seedPortForward := seedState.NewClientSeedPortForward(net.ParseIP("0.0.0.0"))
  164. seedPortForward.UpdateProgress(1, 1, 1)
  165. payload := seedState.GetSeedPayload()
  166. if len(payload.SLOKs) != 1 {
  167. t.Fatalf("expected 1 SLOKs, got %d", len(payload.SLOKs))
  168. }
  169. SetSLOK(payload.SLOKs[0].ID, payload.SLOKs[0].Key)
  170. //
  171. // run mock remote server list host
  172. //
  173. // Exercise using multiple download URLs
  174. remoteServerListHostAddresses := []string{
  175. net.JoinHostPort(serverIPaddress, "8081"),
  176. net.JoinHostPort(serverIPaddress, "8082"),
  177. }
  178. // The common remote server list fetches will 404
  179. remoteServerListURL := fmt.Sprintf("http://%s/server_list_compressed", remoteServerListHostAddresses[0])
  180. remoteServerListDownloadFilename := filepath.Join(testDataDirName, "server_list_compressed")
  181. obfuscatedServerListRootURLsJSONConfig := "["
  182. obfuscatedServerListRootURLs := make([]string, len(remoteServerListHostAddresses))
  183. for i := 0; i < len(remoteServerListHostAddresses); i++ {
  184. obfuscatedServerListRootURLs[i] = fmt.Sprintf("http://%s/", remoteServerListHostAddresses[i])
  185. obfuscatedServerListRootURLsJSONConfig += fmt.Sprintf(
  186. "{\"URL\" : \"%s\"}", base64.StdEncoding.EncodeToString([]byte(obfuscatedServerListRootURLs[i])))
  187. if i == len(remoteServerListHostAddresses)-1 {
  188. obfuscatedServerListRootURLsJSONConfig += "]"
  189. } else {
  190. obfuscatedServerListRootURLsJSONConfig += ","
  191. }
  192. go func(remoteServerListHostAddress string) {
  193. startTime := time.Now()
  194. serveMux := http.NewServeMux()
  195. for _, paveFile := range paveFiles {
  196. file := paveFile
  197. serveMux.HandleFunc("/"+file.Name, func(w http.ResponseWriter, req *http.Request) {
  198. md5sum := md5.Sum(file.Contents)
  199. w.Header().Add("Content-Type", "application/octet-stream")
  200. w.Header().Add("ETag", fmt.Sprintf("\"%s\"", hex.EncodeToString(md5sum[:])))
  201. http.ServeContent(w, req, file.Name, startTime, bytes.NewReader(file.Contents))
  202. })
  203. }
  204. httpServer := &http.Server{
  205. Addr: remoteServerListHostAddress,
  206. Handler: serveMux,
  207. }
  208. err := httpServer.ListenAndServe()
  209. if err != nil {
  210. // TODO: wrong goroutine for t.FatalNow()
  211. t.Fatalf("error running remote server list host: %s", err)
  212. }
  213. }(remoteServerListHostAddresses[i])
  214. }
  215. obfuscatedServerListDownloadDirectory := testDataDirName
  216. //
  217. // run Psiphon server
  218. //
  219. go func() {
  220. err := server.RunServices(serverConfigJSON)
  221. if err != nil {
  222. // TODO: wrong goroutine for t.FatalNow()
  223. t.Fatalf("error running server: %s", err)
  224. }
  225. }()
  226. //
  227. // disrupt remote server list downloads
  228. //
  229. disruptorProxyAddress := "127.0.0.1:2162"
  230. disruptorProxyURL := "socks4a://" + disruptorProxyAddress
  231. go func() {
  232. listener, err := socks.ListenSocks("tcp", disruptorProxyAddress)
  233. if err != nil {
  234. fmt.Printf("disruptor proxy listen error: %s\n", err)
  235. return
  236. }
  237. for {
  238. localConn, err := listener.AcceptSocks()
  239. if err != nil {
  240. fmt.Printf("disruptor proxy accept error: %s\n", err)
  241. return
  242. }
  243. go func() {
  244. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  245. if err != nil {
  246. fmt.Printf("disruptor proxy dial error: %s\n", err)
  247. return
  248. }
  249. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  250. if err != nil {
  251. fmt.Printf("disruptor proxy grant error: %s\n", err)
  252. return
  253. }
  254. waitGroup := new(sync.WaitGroup)
  255. waitGroup.Add(1)
  256. go func() {
  257. defer waitGroup.Done()
  258. io.Copy(remoteConn, localConn)
  259. }()
  260. if common.Contains(remoteServerListHostAddresses, localConn.Req.Target) {
  261. io.CopyN(localConn, remoteConn, 500)
  262. } else {
  263. io.Copy(localConn, remoteConn)
  264. }
  265. localConn.Close()
  266. remoteConn.Close()
  267. waitGroup.Wait()
  268. }()
  269. }
  270. }()
  271. //
  272. // connect to Psiphon server with Psiphon client
  273. //
  274. SetEmitDiagnosticNotices(true)
  275. // Note: calling LoadConfig ensures all *int config fields are initialized
  276. clientConfigJSONTemplate := `
  277. {
  278. "ClientPlatform" : "",
  279. "ClientVersion" : "0",
  280. "SponsorId" : "0",
  281. "PropagationChannelId" : "0",
  282. "ConnectionPoolSize" : 1,
  283. "EstablishTunnelPausePeriodSeconds" : 1,
  284. "FetchRemoteServerListRetryPeriodSeconds" : 1,
  285. "RemoteServerListSignaturePublicKey" : "%s",
  286. "RemoteServerListUrl" : "%s",
  287. "RemoteServerListDownloadFilename" : "%s",
  288. "ObfuscatedServerListRootURLs" : %s,
  289. "ObfuscatedServerListDownloadDirectory" : "%s",
  290. "UpstreamProxyUrl" : "%s"
  291. }`
  292. clientConfigJSON := fmt.Sprintf(
  293. clientConfigJSONTemplate,
  294. signingPublicKey,
  295. remoteServerListURL,
  296. remoteServerListDownloadFilename,
  297. obfuscatedServerListRootURLsJSONConfig,
  298. obfuscatedServerListDownloadDirectory,
  299. disruptorProxyURL)
  300. clientConfig, _ := LoadConfig([]byte(clientConfigJSON))
  301. controller, err := NewController(clientConfig)
  302. if err != nil {
  303. t.Fatalf("error creating client controller: %s", err)
  304. }
  305. tunnelEstablished := make(chan struct{}, 1)
  306. SetNoticeOutput(NewNoticeReceiver(
  307. func(notice []byte) {
  308. noticeType, payload, err := GetNotice(notice)
  309. if err != nil {
  310. return
  311. }
  312. printNotice := false
  313. switch noticeType {
  314. case "Tunnels":
  315. printNotice = true
  316. count := int(payload["count"].(float64))
  317. if count == 1 {
  318. tunnelEstablished <- *new(struct{})
  319. }
  320. case "RemoteServerListResourceDownloadedBytes":
  321. // TODO: check for resumed download for each URL
  322. //url := payload["url"].(string)
  323. printNotice = true
  324. case "RemoteServerListResourceDownloaded":
  325. printNotice = true
  326. }
  327. if printNotice {
  328. fmt.Printf("%s\n", string(notice))
  329. }
  330. }))
  331. go func() {
  332. controller.Run(make(chan struct{}))
  333. }()
  334. establishTimeout := time.NewTimer(30 * time.Second)
  335. select {
  336. case <-tunnelEstablished:
  337. case <-establishTimeout.C:
  338. t.Fatalf("tunnel establish timeout exceeded")
  339. }
  340. for _, paveFile := range paveFiles {
  341. u, _ := url.Parse(obfuscatedServerListRootURLs[0])
  342. u.Path = path.Join(u.Path, paveFile.Name)
  343. etag, _ := GetUrlETag(u.String())
  344. md5sum := md5.Sum(paveFile.Contents)
  345. if etag != fmt.Sprintf("\"%s\"", hex.EncodeToString(md5sum[:])) {
  346. t.Fatalf("unexpected ETag for %s", u)
  347. }
  348. }
  349. }