remoteServerList.go 12 KB

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