remoteServerList_test.go 9.3 KB

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