remoteServerList_test.go 8.7 KB

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