remoteServerList_test.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. if err != nil {
  134. t.Fatalf("error paving OSL files: %s", err)
  135. }
  136. //
  137. // mock seeding SLOKs
  138. //
  139. singleton = dataStore{}
  140. os.Remove(filepath.Join(testDataDirName, DATA_STORE_FILENAME))
  141. err = InitDataStore(&Config{DataStoreDirectory: testDataDirName})
  142. if err != nil {
  143. t.Fatalf("error initializing client datastore: %s", err)
  144. }
  145. if CountServerEntries("", "") > 0 {
  146. t.Fatalf("unexpected server entries")
  147. }
  148. seedState := oslConfig.NewClientSeedState("", propagationChannelID, nil)
  149. seedPortForward := seedState.NewClientSeedPortForward(net.ParseIP("0.0.0.0"))
  150. seedPortForward.UpdateProgress(1, 1, 1)
  151. payload := seedState.GetSeedPayload()
  152. if len(payload.SLOKs) != 1 {
  153. t.Fatalf("expected 1 SLOKs, got %d", len(payload.SLOKs))
  154. }
  155. SetSLOK(payload.SLOKs[0].ID, payload.SLOKs[0].Key)
  156. //
  157. // run mock remote server list host
  158. //
  159. remoteServerListHostAddress := net.JoinHostPort(serverIPaddress, "8081")
  160. // The common remote server list fetches will 404
  161. remoteServerListURL := fmt.Sprintf("http://%s/server_list_compressed", remoteServerListHostAddress)
  162. remoteServerListDownloadFilename := filepath.Join(testDataDirName, "server_list_compressed")
  163. obfuscatedServerListRootURL := fmt.Sprintf("http://%s/", remoteServerListHostAddress)
  164. obfuscatedServerListDownloadDirectory := testDataDirName
  165. go func() {
  166. startTime := time.Now()
  167. serveMux := http.NewServeMux()
  168. for _, paveFile := range paveFiles {
  169. file := paveFile
  170. serveMux.HandleFunc("/"+file.Name, func(w http.ResponseWriter, req *http.Request) {
  171. md5sum := md5.Sum(file.Contents)
  172. w.Header().Add("Content-Type", "application/octet-stream")
  173. w.Header().Add("ETag", hex.EncodeToString(md5sum[:]))
  174. http.ServeContent(w, req, file.Name, startTime, bytes.NewReader(file.Contents))
  175. })
  176. }
  177. httpServer := &http.Server{
  178. Addr: remoteServerListHostAddress,
  179. Handler: serveMux,
  180. }
  181. err := httpServer.ListenAndServe()
  182. if err != nil {
  183. // TODO: wrong goroutine for t.FatalNow()
  184. t.Fatalf("error running remote server list host: %s", err)
  185. }
  186. }()
  187. //
  188. // run Psiphon server
  189. //
  190. go func() {
  191. err := server.RunServices(serverConfigJSON)
  192. if err != nil {
  193. // TODO: wrong goroutine for t.FatalNow()
  194. t.Fatalf("error running server: %s", err)
  195. }
  196. }()
  197. //
  198. // disrupt remote server list downloads
  199. //
  200. disruptorProxyAddress := "127.0.0.1:2162"
  201. disruptorProxyURL := "socks4a://" + disruptorProxyAddress
  202. go func() {
  203. listener, err := socks.ListenSocks("tcp", disruptorProxyAddress)
  204. if err != nil {
  205. fmt.Errorf("disruptor proxy listen error: %s", err)
  206. return
  207. }
  208. for {
  209. localConn, err := listener.AcceptSocks()
  210. if err != nil {
  211. fmt.Errorf("disruptor proxy accept error: %s", err)
  212. return
  213. }
  214. go func() {
  215. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  216. if err != nil {
  217. fmt.Errorf("disruptor proxy dial error: %s", err)
  218. return
  219. }
  220. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  221. if err != nil {
  222. fmt.Errorf("disruptor proxy grant error: %s", err)
  223. return
  224. }
  225. waitGroup := new(sync.WaitGroup)
  226. waitGroup.Add(1)
  227. go func() {
  228. defer waitGroup.Done()
  229. io.Copy(remoteConn, localConn)
  230. }()
  231. if localConn.Req.Target == remoteServerListHostAddress {
  232. io.CopyN(localConn, remoteConn, 500)
  233. } else {
  234. io.Copy(localConn, remoteConn)
  235. }
  236. localConn.Close()
  237. remoteConn.Close()
  238. waitGroup.Wait()
  239. }()
  240. }
  241. }()
  242. //
  243. // connect to Psiphon server with Psiphon client
  244. //
  245. SetEmitDiagnosticNotices(true)
  246. // Note: calling LoadConfig ensures all *int config fields are initialized
  247. clientConfigJSONTemplate := `
  248. {
  249. "ClientPlatform" : "",
  250. "ClientVersion" : "0",
  251. "SponsorId" : "0",
  252. "PropagationChannelId" : "0",
  253. "ConnectionPoolSize" : 1,
  254. "EstablishTunnelPausePeriodSeconds" : 1,
  255. "FetchRemoteServerListRetryPeriodSeconds" : 1,
  256. "RemoteServerListSignaturePublicKey" : "%s",
  257. "RemoteServerListUrl" : "%s",
  258. "RemoteServerListDownloadFilename" : "%s",
  259. "ObfuscatedServerListRootURL" : "%s",
  260. "ObfuscatedServerListDownloadDirectory" : "%s",
  261. "UpstreamProxyUrl" : "%s"
  262. }`
  263. clientConfigJSON := fmt.Sprintf(
  264. clientConfigJSONTemplate,
  265. signingPublicKey,
  266. remoteServerListURL,
  267. remoteServerListDownloadFilename,
  268. obfuscatedServerListRootURL,
  269. obfuscatedServerListDownloadDirectory,
  270. disruptorProxyURL)
  271. clientConfig, _ := LoadConfig([]byte(clientConfigJSON))
  272. controller, err := NewController(clientConfig)
  273. if err != nil {
  274. t.Fatalf("error creating client controller: %s", err)
  275. }
  276. tunnelEstablished := make(chan struct{}, 1)
  277. SetNoticeOutput(NewNoticeReceiver(
  278. func(notice []byte) {
  279. noticeType, payload, err := GetNotice(notice)
  280. if err != nil {
  281. return
  282. }
  283. printNotice := false
  284. switch noticeType {
  285. case "Tunnels":
  286. printNotice = true
  287. count := int(payload["count"].(float64))
  288. if count == 1 {
  289. tunnelEstablished <- *new(struct{})
  290. }
  291. case "RemoteServerListResourceDownloadedBytes":
  292. // TODO: check for resumed download for each URL
  293. //url := payload["url"].(string)
  294. printNotice = true
  295. case "RemoteServerListResourceDownloaded":
  296. printNotice = true
  297. }
  298. if printNotice {
  299. fmt.Printf("%s\n", string(notice))
  300. }
  301. }))
  302. go func() {
  303. controller.Run(make(chan struct{}))
  304. }()
  305. establishTimeout := time.NewTimer(30 * time.Second)
  306. select {
  307. case <-tunnelEstablished:
  308. case <-establishTimeout.C:
  309. t.Fatalf("tunnel establish timeout exceeded")
  310. }
  311. for _, paveFile := range paveFiles {
  312. u, _ := url.Parse(obfuscatedServerListRootURL)
  313. u.Path = path.Join(u.Path, paveFile.Name)
  314. etag, _ := GetUrlETag(u.String())
  315. md5sum := md5.Sum(paveFile.Contents)
  316. if etag != hex.EncodeToString(md5sum[:]) {
  317. t.Fatalf("unexpected ETag for %s", u)
  318. }
  319. }
  320. }