remoteServerList.go 17 KB

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