remoteServerList.go 12 KB

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