remoteServerList.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. "context"
  22. "encoding/hex"
  23. "fmt"
  24. "os"
  25. "sync/atomic"
  26. "time"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  32. )
  33. type RemoteServerListFetcher func(
  34. ctx context.Context, config *Config, attempt int, tunnel *Tunnel, untunneledDialConfig *DialConfig) error
  35. // FetchCommonRemoteServerList downloads the common remote server list from
  36. // config.RemoteServerListURLs. It validates its digital signature using the
  37. // public key config.RemoteServerListSignaturePublicKey and parses the
  38. // data field into ServerEntry records.
  39. // config.GetRemoteServerListDownloadFilename() is the location to store the
  40. // download. As the download is resumed after failure, this filename must
  41. // be unique and persistent.
  42. func FetchCommonRemoteServerList(
  43. ctx context.Context,
  44. config *Config,
  45. attempt int,
  46. tunnel *Tunnel,
  47. untunneledDialConfig *DialConfig) error {
  48. NoticeInfo("fetching common remote server list")
  49. p := config.GetClientParameters().Get()
  50. publicKey := p.String(parameters.RemoteServerListSignaturePublicKey)
  51. urls := p.DownloadURLs(parameters.RemoteServerListURLs)
  52. downloadTimeout := p.Duration(parameters.FetchRemoteServerListTimeout)
  53. p.Close()
  54. downloadURL, canonicalURL, skipVerify := urls.Select(attempt)
  55. newETag, downloadStatRecorder, err := downloadRemoteServerListFile(
  56. ctx,
  57. config,
  58. tunnel,
  59. untunneledDialConfig,
  60. downloadTimeout,
  61. downloadURL,
  62. canonicalURL,
  63. skipVerify,
  64. "",
  65. config.GetRemoteServerListDownloadFilename())
  66. if err != nil {
  67. return errors.Tracef("failed to download common remote server list: %s", errors.Trace(err))
  68. }
  69. authenticatedDownload := false
  70. if downloadStatRecorder != nil {
  71. defer func() { downloadStatRecorder(authenticatedDownload) }()
  72. }
  73. // When the resource is unchanged, skip.
  74. if newETag == "" {
  75. return nil
  76. }
  77. file, err := os.Open(config.GetRemoteServerListDownloadFilename())
  78. if err != nil {
  79. return errors.Tracef("failed to open common remote server list: %s", errors.Trace(err))
  80. }
  81. defer file.Close()
  82. serverListPayloadReader, err := common.NewAuthenticatedDataPackageReader(
  83. file, publicKey)
  84. if err != nil {
  85. return errors.Tracef("failed to read remote server list: %s", errors.Trace(err))
  86. }
  87. // NewAuthenticatedDataPackageReader authenticates the file before returning.
  88. authenticatedDownload = true
  89. err = StreamingStoreServerEntries(
  90. config,
  91. protocol.NewStreamingServerEntryDecoder(
  92. serverListPayloadReader,
  93. common.GetCurrentTimestamp(),
  94. protocol.SERVER_ENTRY_SOURCE_REMOTE),
  95. true)
  96. if err != nil {
  97. return errors.Tracef("failed to store common remote server list: %s", errors.Trace(err))
  98. }
  99. // Now that the server entries are successfully imported, store the response
  100. // ETag so we won't re-download this same data again.
  101. err = SetUrlETag(canonicalURL, newETag)
  102. if err != nil {
  103. NoticeWarning("failed to set ETag for common remote server list: %s", errors.Trace(err))
  104. // This fetch is still reported as a success, even if we can't store the etag
  105. }
  106. return nil
  107. }
  108. // FetchObfuscatedServerLists downloads the obfuscated remote server lists
  109. // from config.ObfuscatedServerListRootURLs.
  110. // It first downloads the OSL registry, and then downloads each seeded OSL
  111. // advertised in the registry. All downloads are resumable, ETags are used
  112. // to skip both an unchanged registry or unchanged OSL files, and when an
  113. // individual download fails, the fetch proceeds if it can.
  114. // Authenticated package digital signatures are validated using the
  115. // public key config.RemoteServerListSignaturePublicKey.
  116. // config.GetObfuscatedServerListDownloadDirectory() is the location to store
  117. // the downloaded files. As downloads are resumed after failure, this directory
  118. // must be unique and persistent.
  119. func FetchObfuscatedServerLists(
  120. ctx context.Context,
  121. config *Config,
  122. attempt int,
  123. tunnel *Tunnel,
  124. untunneledDialConfig *DialConfig) error {
  125. NoticeInfo("fetching obfuscated remote server lists")
  126. p := config.GetClientParameters().Get()
  127. publicKey := p.String(parameters.RemoteServerListSignaturePublicKey)
  128. urls := p.DownloadURLs(parameters.ObfuscatedServerListRootURLs)
  129. downloadTimeout := p.Duration(parameters.FetchRemoteServerListTimeout)
  130. p.Close()
  131. rootURL, canonicalRootURL, skipVerify := urls.Select(attempt)
  132. downloadURL := osl.GetOSLRegistryURL(rootURL)
  133. canonicalURL := osl.GetOSLRegistryURL(canonicalRootURL)
  134. downloadFilename := osl.GetOSLRegistryFilename(config.GetObfuscatedServerListDownloadDirectory())
  135. cachedFilename := downloadFilename + ".cached"
  136. // If the cached registry is not present, we need to download or resume downloading
  137. // the registry, so clear the ETag to ensure that always happens.
  138. _, err := os.Stat(cachedFilename)
  139. if os.IsNotExist(err) {
  140. SetUrlETag(canonicalURL, "")
  141. }
  142. // failed is set if any operation fails and should trigger a retry. When the OSL registry
  143. // fails to download, any cached registry is used instead; when any single OSL fails
  144. // to download, the overall operation proceeds. So this flag records whether to report
  145. // failure at the end when downloading has proceeded after a failure.
  146. // TODO: should disk-full conditions not trigger retries?
  147. var failed bool
  148. // updateCache is set when modifed registry content is downloaded. Both the cached
  149. // file and the persisted ETag will be updated in this case. The update is deferred
  150. // until after the registry has been authenticated.
  151. updateCache := false
  152. registryFilename := cachedFilename
  153. newETag, downloadStatRecorder, err := downloadRemoteServerListFile(
  154. ctx,
  155. config,
  156. tunnel,
  157. untunneledDialConfig,
  158. downloadTimeout,
  159. downloadURL,
  160. canonicalURL,
  161. skipVerify,
  162. "",
  163. downloadFilename)
  164. if err != nil {
  165. failed = true
  166. NoticeWarning("failed to download obfuscated server list registry: %s", errors.Trace(err))
  167. // Proceed with any existing cached OSL registry.
  168. }
  169. authenticatedDownload := false
  170. if downloadStatRecorder != nil {
  171. defer func() { downloadStatRecorder(authenticatedDownload) }()
  172. }
  173. if newETag != "" {
  174. updateCache = true
  175. registryFilename = downloadFilename
  176. }
  177. // Prevent excessive notice noise in cases such as a general database
  178. // failure, as GetSLOK may be called thousands of times per fetch.
  179. emittedGetSLOKAlert := int32(0)
  180. lookupSLOKs := func(slokID []byte) []byte {
  181. // Lookup SLOKs in local datastore
  182. key, err := GetSLOK(slokID)
  183. if err != nil && atomic.CompareAndSwapInt32(&emittedGetSLOKAlert, 0, 1) {
  184. NoticeWarning("GetSLOK failed: %s", err)
  185. }
  186. return key
  187. }
  188. registryFile, err := os.Open(registryFilename)
  189. if err != nil {
  190. return errors.Tracef("failed to read obfuscated server list registry: %s", errors.Trace(err))
  191. }
  192. defer registryFile.Close()
  193. registryStreamer, err := osl.NewRegistryStreamer(
  194. registryFile,
  195. publicKey,
  196. lookupSLOKs)
  197. if err != nil {
  198. // TODO: delete file? redownload if corrupt?
  199. return errors.Tracef("failed to read obfuscated server list registry: %s", errors.Trace(err))
  200. }
  201. authenticatedDownload = true
  202. // NewRegistryStreamer authenticates the downloaded registry, so now it would be
  203. // ok to update the cache. However, we defer that until after processing so we
  204. // can close the file first before copying it, avoiding related complications on
  205. // platforms such as Windows.
  206. // Note: we proceed to check individual OSLs even if the directory is unchanged,
  207. // as the set of local SLOKs may have changed.
  208. for {
  209. oslFileSpec, err := registryStreamer.Next()
  210. if err != nil {
  211. failed = true
  212. NoticeWarning("failed to stream obfuscated server list registry: %s", errors.Trace(err))
  213. break
  214. }
  215. if oslFileSpec == nil {
  216. break
  217. }
  218. if !downloadOSLFileSpec(
  219. ctx,
  220. config,
  221. tunnel,
  222. untunneledDialConfig,
  223. downloadTimeout,
  224. rootURL,
  225. canonicalRootURL,
  226. skipVerify,
  227. publicKey,
  228. lookupSLOKs,
  229. oslFileSpec) {
  230. // downloadOSLFileSpec emits notices with failure information. In the case
  231. // of a failure, set the retry flag but continue to process other OSL file
  232. // specs.
  233. failed = true
  234. }
  235. // Run a garbage collection to reclaim memory from the downloadOSLFileSpec
  236. // operation before processing the next file.
  237. DoGarbageCollection()
  238. }
  239. // Now that a new registry is downloaded, validated, and parsed, store
  240. // the response ETag so we won't re-download this same data again. First
  241. // close the file to avoid complications on platforms such as Windows.
  242. if updateCache {
  243. registryFile.Close()
  244. err := os.Rename(downloadFilename, cachedFilename)
  245. if err != nil {
  246. NoticeWarning("failed to set cached obfuscated server list registry: %s", errors.Trace(err))
  247. // This fetch is still reported as a success, even if we can't update the cache
  248. }
  249. err = SetUrlETag(canonicalURL, newETag)
  250. if err != nil {
  251. NoticeWarning("failed to set ETag for obfuscated server list registry: %s", errors.Trace(err))
  252. // This fetch is still reported as a success, even if we can't store the ETag
  253. }
  254. }
  255. if failed {
  256. return errors.TraceNew("one or more operations failed")
  257. }
  258. return nil
  259. }
  260. // downloadOSLFileSpec downloads, authenticates, and imports the OSL specified
  261. // by oslFileSpec. The return value indicates whether the operation succeeded.
  262. // Failure information is emitted in notices.
  263. func downloadOSLFileSpec(
  264. ctx context.Context,
  265. config *Config,
  266. tunnel *Tunnel,
  267. untunneledDialConfig *DialConfig,
  268. downloadTimeout time.Duration,
  269. rootURL string,
  270. canonicalRootURL string,
  271. skipVerify bool,
  272. publicKey string,
  273. lookupSLOKs func(slokID []byte) []byte,
  274. oslFileSpec *osl.OSLFileSpec) bool {
  275. downloadFilename := osl.GetOSLFilename(
  276. config.GetObfuscatedServerListDownloadDirectory(), oslFileSpec.ID)
  277. downloadURL := osl.GetOSLFileURL(rootURL, oslFileSpec.ID)
  278. canonicalURL := osl.GetOSLFileURL(canonicalRootURL, oslFileSpec.ID)
  279. hexID := hex.EncodeToString(oslFileSpec.ID)
  280. // Note: the MD5 checksum step assumes the remote server list host's ETag uses MD5
  281. // with a hex encoding. If this is not the case, the sourceETag should be left blank.
  282. sourceETag := fmt.Sprintf("\"%s\"", hex.EncodeToString(oslFileSpec.MD5Sum))
  283. newETag, downloadStatRecorder, err := downloadRemoteServerListFile(
  284. ctx,
  285. config,
  286. tunnel,
  287. untunneledDialConfig,
  288. downloadTimeout,
  289. downloadURL,
  290. canonicalURL,
  291. skipVerify,
  292. sourceETag,
  293. downloadFilename)
  294. if err != nil {
  295. NoticeWarning("failed to download obfuscated server list file (%s): %s", hexID, errors.Trace(err))
  296. return false
  297. }
  298. authenticatedDownload := false
  299. if downloadStatRecorder != nil {
  300. defer func() { downloadStatRecorder(authenticatedDownload) }()
  301. }
  302. // When the resource is unchanged, skip.
  303. if newETag == "" {
  304. return true
  305. }
  306. file, err := os.Open(downloadFilename)
  307. if err != nil {
  308. NoticeWarning("failed to open obfuscated server list file (%s): %s", hexID, errors.Trace(err))
  309. return false
  310. }
  311. defer file.Close()
  312. serverListPayloadReader, err := osl.NewOSLReader(
  313. file,
  314. oslFileSpec,
  315. lookupSLOKs,
  316. publicKey)
  317. if err != nil {
  318. NoticeWarning("failed to read obfuscated server list file (%s): %s", hexID, errors.Trace(err))
  319. return false
  320. }
  321. // NewOSLReader authenticates the file before returning.
  322. authenticatedDownload = true
  323. err = StreamingStoreServerEntries(
  324. config,
  325. protocol.NewStreamingServerEntryDecoder(
  326. serverListPayloadReader,
  327. common.GetCurrentTimestamp(),
  328. protocol.SERVER_ENTRY_SOURCE_OBFUSCATED),
  329. true)
  330. if err != nil {
  331. NoticeWarning("failed to store obfuscated server list file (%s): %s", hexID, errors.Trace(err))
  332. return false
  333. }
  334. // Now that the server entries are successfully imported, store the response
  335. // ETag so we won't re-download this same data again.
  336. err = SetUrlETag(canonicalURL, newETag)
  337. if err != nil {
  338. NoticeWarning("failed to set ETag for obfuscated server list file (%s): %s", hexID, errors.Trace(err))
  339. // This fetch is still reported as a success, even if we can't store the ETag
  340. return true
  341. }
  342. return true
  343. }
  344. // downloadRemoteServerListFile downloads the source URL to the destination
  345. // file, performing a resumable download. When the download completes and the
  346. // file content has changed, the new resource ETag is returned. Otherwise,
  347. // blank is returned. The caller is responsible for calling SetUrlETag once
  348. // the file content has been validated.
  349. //
  350. // The downloadStatReporter return value is a function that will invoke
  351. // RecordRemoteServerListStat to record a remote server list download event.
  352. // The caller must call this function if the return value is not nil,
  353. // providing a boolean argument indicating whether the download was
  354. // successfully authenticated.
  355. func downloadRemoteServerListFile(
  356. ctx context.Context,
  357. config *Config,
  358. tunnel *Tunnel,
  359. untunneledDialConfig *DialConfig,
  360. downloadTimeout time.Duration,
  361. sourceURL string,
  362. canonicalURL string,
  363. skipVerify bool,
  364. sourceETag string,
  365. destinationFilename string) (string, func(bool), error) {
  366. // All download URLs with the same canonicalURL
  367. // must have the same entity and ETag.
  368. lastETag, err := GetUrlETag(canonicalURL)
  369. if err != nil {
  370. return "", nil, errors.Trace(err)
  371. }
  372. // sourceETag, when specified, is prior knowledge of the
  373. // remote ETag that can be used to skip the request entirely.
  374. // This will be set in the case of OSL files, from the MD5Sum
  375. // values stored in the registry.
  376. if lastETag != "" && sourceETag == lastETag {
  377. // TODO: notice?
  378. return "", nil, nil
  379. }
  380. var cancelFunc context.CancelFunc
  381. ctx, cancelFunc = context.WithTimeout(ctx, downloadTimeout)
  382. defer cancelFunc()
  383. // MakeDownloadHttpClient will select either a tunneled
  384. // or untunneled configuration.
  385. httpClient, tunneled, err := MakeDownloadHTTPClient(
  386. ctx,
  387. config,
  388. tunnel,
  389. untunneledDialConfig,
  390. skipVerify)
  391. if err != nil {
  392. return "", nil, errors.Trace(err)
  393. }
  394. n, responseETag, err := ResumeDownload(
  395. ctx,
  396. httpClient,
  397. sourceURL,
  398. MakePsiphonUserAgent(config),
  399. destinationFilename,
  400. lastETag)
  401. NoticeRemoteServerListResourceDownloadedBytes(sourceURL, n)
  402. if err != nil {
  403. return "", nil, errors.Trace(err)
  404. }
  405. if responseETag == lastETag {
  406. return "", nil, nil
  407. }
  408. NoticeRemoteServerListResourceDownloaded(sourceURL)
  409. downloadStatRecorder := func(authenticated bool) {
  410. _ = RecordRemoteServerListStat(
  411. config, tunneled, sourceURL, responseETag, authenticated)
  412. }
  413. return responseETag, downloadStatRecorder, nil
  414. }