remoteServerList_test.go 11 KB

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