remoteServerList_test.go 11 KB

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