remoteServerList.go 15 KB

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