remoteServerList.go 15 KB

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