remoteServerList.go 12 KB

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