remoteServerList.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /*
  2. * Copyright (c) 2015, 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. "compress/zlib"
  22. "encoding/hex"
  23. "errors"
  24. "fmt"
  25. "io/ioutil"
  26. "os"
  27. "time"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  31. )
  32. type RemoteServerListFetcher func(
  33. config *Config, tunnel *Tunnel, untunneledDialConfig *DialConfig) error
  34. // FetchCommonRemoteServerList downloads the common remote server list from
  35. // config.RemoteServerListUrl. It validates its digital signature using the
  36. // public key config.RemoteServerListSignaturePublicKey and parses the
  37. // data field into ServerEntry records.
  38. // config.RemoteServerListDownloadFilename is the location to store the
  39. // download. As the download is resumed after failure, this filename must
  40. // be unique and persistent.
  41. func FetchCommonRemoteServerList(
  42. config *Config,
  43. tunnel *Tunnel,
  44. untunneledDialConfig *DialConfig) error {
  45. NoticeInfo("fetching common remote server list")
  46. newETag, err := downloadRemoteServerListFile(
  47. config,
  48. tunnel,
  49. untunneledDialConfig,
  50. config.RemoteServerListUrl,
  51. "",
  52. config.RemoteServerListDownloadFilename)
  53. if err != nil {
  54. return fmt.Errorf("failed to download common remote server list: %s", common.ContextError(err))
  55. }
  56. // When the resource is unchanged, skip.
  57. if newETag == "" {
  58. return nil
  59. }
  60. serverListPayload, err := unpackRemoteServerListFile(config, config.RemoteServerListDownloadFilename)
  61. if err != nil {
  62. return fmt.Errorf("failed to unpack common remote server list: %s", common.ContextError(err))
  63. }
  64. err = storeServerEntries(serverListPayload)
  65. if err != nil {
  66. return fmt.Errorf("failed to store common remote server list: %s", common.ContextError(err))
  67. }
  68. // Now that the server entries are successfully imported, store the response
  69. // ETag so we won't re-download this same data again.
  70. err = SetUrlETag(config.RemoteServerListUrl, newETag)
  71. if err != nil {
  72. NoticeAlert("failed to set ETag for common remote server list: %s", common.ContextError(err))
  73. // This fetch is still reported as a success, even if we can't store the etag
  74. }
  75. return nil
  76. }
  77. // FetchObfuscatedServerLists downloads the obfuscated remote server lists
  78. // from config.ObfuscatedServerListRootURL.
  79. // It first downloads the OSL registry, and then downloads each seeded OSL
  80. // advertised in the registry. All downloads are resumable, ETags are used
  81. // to skip both an unchanged registry or unchanged OSL files, and when an
  82. // individual download fails, the fetch proceeds if it can.
  83. // Authenticated package digital signatures are validated using the
  84. // public key config.RemoteServerListSignaturePublicKey.
  85. // config.ObfuscatedServerListDownloadDirectory is the location to store the
  86. // downloaded files. As downloads are resumed after failure, this directory
  87. // must be unique and persistent.
  88. func FetchObfuscatedServerLists(
  89. config *Config,
  90. tunnel *Tunnel,
  91. untunneledDialConfig *DialConfig) error {
  92. NoticeInfo("fetching obfuscated remote server lists")
  93. downloadFilename := osl.GetOSLRegistryFilename(config.ObfuscatedServerListDownloadDirectory)
  94. downloadURL := osl.GetOSLRegistryURL(config.ObfuscatedServerListRootURL)
  95. // failed is set if any operation fails and should trigger a retry. When the OSL registry
  96. // fails to download, any cached registry is used instead; when any single OSL fails
  97. // to download, the overall operation proceeds. So this flag records whether to report
  98. // failure at the end when downloading has proceeded after a failure.
  99. // TODO: should disk-full conditions not trigger retries?
  100. var failed bool
  101. var oslRegistry *osl.Registry
  102. newETag, err := downloadRemoteServerListFile(
  103. config,
  104. tunnel,
  105. untunneledDialConfig,
  106. downloadURL,
  107. "",
  108. downloadFilename)
  109. if err != nil {
  110. failed = true
  111. NoticeAlert("failed to download obfuscated server list registry: %s", common.ContextError(err))
  112. } else if newETag != "" {
  113. fileContent, err := ioutil.ReadFile(downloadFilename)
  114. if err != nil {
  115. failed = true
  116. NoticeAlert("failed to read obfuscated server list registry: %s", common.ContextError(err))
  117. }
  118. var oslRegistryJSON []byte
  119. if err == nil {
  120. oslRegistry, oslRegistryJSON, err = osl.UnpackRegistry(
  121. fileContent, config.RemoteServerListSignaturePublicKey)
  122. if err != nil {
  123. failed = true
  124. NoticeAlert("failed to unpack obfuscated server list registry: %s", common.ContextError(err))
  125. }
  126. }
  127. if err == nil {
  128. err = SetKeyValue(DATA_STORE_OSL_REGISTRY_KEY, string(oslRegistryJSON))
  129. if err != nil {
  130. failed = true
  131. NoticeAlert("failed to set cached obfuscated server list registry: %s", common.ContextError(err))
  132. }
  133. }
  134. }
  135. if failed || newETag == "" {
  136. // Proceed with the cached OSL registry.
  137. oslRegistryJSON, err := GetKeyValue(DATA_STORE_OSL_REGISTRY_KEY)
  138. if err == nil && oslRegistryJSON == "" {
  139. err = errors.New("not found")
  140. }
  141. if err != nil {
  142. return fmt.Errorf("failed to get cached obfuscated server list registry: %s", common.ContextError(err))
  143. }
  144. oslRegistry, err = osl.LoadRegistry([]byte(oslRegistryJSON))
  145. if err != nil {
  146. return fmt.Errorf("failed to load obfuscated server list registry: %s", common.ContextError(err))
  147. }
  148. }
  149. // When a new registry is downloaded, validated, and parsed, store the
  150. // response ETag so we won't re-download this same data again.
  151. if !failed && newETag != "" {
  152. err = SetUrlETag(downloadURL, newETag)
  153. if err != nil {
  154. NoticeAlert("failed to set ETag for obfuscated server list registry: %s", common.ContextError(err))
  155. // This fetch is still reported as a success, even if we can't store the etag
  156. }
  157. }
  158. // Note: we proceed to check individual OSLs even if the direcory is unchanged,
  159. // as the set of local SLOKs may have changed.
  160. lookupSLOKs := func(slokID []byte) []byte {
  161. // Lookup SLOKs in local datastore
  162. key, err := GetSLOK(slokID)
  163. if err != nil {
  164. NoticeAlert("GetSLOK failed: %s", err)
  165. }
  166. return key
  167. }
  168. oslIDs := oslRegistry.GetSeededOSLIDs(
  169. lookupSLOKs,
  170. func(err error) {
  171. NoticeAlert("GetSeededOSLIDs failed: %s", err)
  172. })
  173. for _, oslID := range oslIDs {
  174. downloadFilename := osl.GetOSLFilename(config.ObfuscatedServerListDownloadDirectory, oslID)
  175. downloadURL := osl.GetOSLFileURL(config.ObfuscatedServerListRootURL, oslID)
  176. hexID := hex.EncodeToString(oslID)
  177. // Note: the MD5 checksum step assumes the remote server list host's ETag uses MD5
  178. // with a hex encoding. If this is not the case, the remoteETag should be left blank.
  179. remoteETag := ""
  180. md5sum, err := oslRegistry.GetOSLMD5Sum(oslID)
  181. if err == nil {
  182. remoteETag = hex.EncodeToString(md5sum)
  183. }
  184. // TODO: store ETags in OSL registry to enable skipping requests entirely
  185. newETag, err := downloadRemoteServerListFile(
  186. config,
  187. tunnel,
  188. untunneledDialConfig,
  189. downloadURL,
  190. remoteETag,
  191. downloadFilename)
  192. if err != nil {
  193. failed = true
  194. NoticeAlert("failed to download obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  195. continue
  196. }
  197. // When the resource is unchanged, skip.
  198. if newETag == "" {
  199. continue
  200. }
  201. fileContent, err := ioutil.ReadFile(downloadFilename)
  202. if err != nil {
  203. failed = true
  204. NoticeAlert("failed to read obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  205. continue
  206. }
  207. serverListPayload, err := oslRegistry.UnpackOSL(
  208. lookupSLOKs, oslID, fileContent, config.RemoteServerListSignaturePublicKey)
  209. if err != nil {
  210. failed = true
  211. NoticeAlert("failed to unpack obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  212. continue
  213. }
  214. err = storeServerEntries(serverListPayload)
  215. if err != nil {
  216. failed = true
  217. NoticeAlert("failed to store obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  218. continue
  219. }
  220. // Now that the server entries are successfully imported, store the response
  221. // ETag so we won't re-download this same data again.
  222. err = SetUrlETag(downloadURL, newETag)
  223. if err != nil {
  224. failed = true
  225. NoticeAlert("failed to set Etag for obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  226. continue
  227. // This fetch is still reported as a success, even if we can't store the etag
  228. }
  229. }
  230. if failed {
  231. return errors.New("one or more operations failed")
  232. }
  233. return nil
  234. }
  235. // downloadRemoteServerListFile downloads the source URL to
  236. // the destination file, performing a resumable download. When
  237. // the download completes and the file content has changed, the
  238. // new resource ETag is returned. Otherwise, blank is returned.
  239. // The caller is responsible for calling SetUrlETag once the file
  240. // content has been validated.
  241. func downloadRemoteServerListFile(
  242. config *Config,
  243. tunnel *Tunnel,
  244. untunneledDialConfig *DialConfig,
  245. sourceURL, sourceETag, destinationFilename string) (string, error) {
  246. lastETag, err := GetUrlETag(sourceURL)
  247. if err != nil {
  248. return "", common.ContextError(err)
  249. }
  250. // sourceETag, when specified, is prior knowlegde of the
  251. // remote ETag that can be used to skip the request entirely.
  252. // This will be set in the case of OSL files, from the MD5Sum
  253. // values stored in the registry.
  254. if lastETag != "" && sourceETag == lastETag {
  255. // TODO: notice?
  256. return "", nil
  257. }
  258. // MakeDownloadHttpClient will select either a tunneled
  259. // or untunneled configuration.
  260. httpClient, requestURL, err := MakeDownloadHttpClient(
  261. config,
  262. tunnel,
  263. untunneledDialConfig,
  264. sourceURL,
  265. time.Duration(*config.FetchRemoteServerListTimeoutSeconds)*time.Second)
  266. if err != nil {
  267. return "", common.ContextError(err)
  268. }
  269. n, responseETag, err := ResumeDownload(
  270. httpClient, requestURL, destinationFilename, lastETag)
  271. NoticeRemoteServerListResourceDownloadedBytes(sourceURL, n)
  272. if err != nil {
  273. return "", common.ContextError(err)
  274. }
  275. if responseETag == lastETag {
  276. return "", nil
  277. }
  278. NoticeRemoteServerListResourceDownloaded(sourceURL)
  279. RecordRemoteServerListStat(sourceURL, responseETag)
  280. return responseETag, nil
  281. }
  282. // unpackRemoteServerListFile reads a file that contains a
  283. // zlib compressed authenticated data package, validates
  284. // the package, and returns the payload.
  285. func unpackRemoteServerListFile(
  286. config *Config, filename string) (string, error) {
  287. fileReader, err := os.Open(filename)
  288. if err != nil {
  289. return "", common.ContextError(err)
  290. }
  291. defer fileReader.Close()
  292. zlibReader, err := zlib.NewReader(fileReader)
  293. if err != nil {
  294. return "", common.ContextError(err)
  295. }
  296. dataPackage, err := ioutil.ReadAll(zlibReader)
  297. zlibReader.Close()
  298. if err != nil {
  299. return "", common.ContextError(err)
  300. }
  301. payload, err := common.ReadAuthenticatedDataPackage(
  302. dataPackage, config.RemoteServerListSignaturePublicKey)
  303. if err != nil {
  304. return "", common.ContextError(err)
  305. }
  306. return payload, nil
  307. }
  308. func storeServerEntries(serverList string) error {
  309. serverEntries, err := protocol.DecodeAndValidateServerEntryList(
  310. serverList,
  311. common.GetCurrentTimestamp(),
  312. protocol.SERVER_ENTRY_SOURCE_REMOTE)
  313. if err != nil {
  314. return common.ContextError(err)
  315. }
  316. // TODO: record stats for newly discovered servers
  317. err = StoreServerEntries(serverEntries, true)
  318. if err != nil {
  319. return common.ContextError(err)
  320. }
  321. return nil
  322. }