psinet.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * Copyright (c) 2016, 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 psinet implements psinet database services. The psinet database is a
  20. // JSON-format file containing information about the Psiphon network, including
  21. // sponsors, home pages, stats regexes, available upgrades, and other servers for
  22. // discovery. This package also implements the Psiphon discovery algorithm.
  23. package psinet
  24. import (
  25. "encoding/json"
  26. "math"
  27. "math/rand"
  28. "strconv"
  29. "strings"
  30. "time"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  33. )
  34. const (
  35. MAX_DATABASE_AGE_FOR_SERVER_ENTRY_VALIDITY = 48 * time.Hour
  36. )
  37. // Database serves Psiphon API data requests. It's safe for
  38. // concurrent usage. The Reload function supports hot reloading
  39. // of Psiphon network data while the server is running.
  40. type Database struct {
  41. common.ReloadableFile
  42. Sponsors map[string]*Sponsor `json:"sponsors"`
  43. Versions map[string][]ClientVersion `json:"client_versions"`
  44. DefaultSponsorID string `json:"default_sponsor_id"`
  45. ValidServerEntryTags map[string]bool `json:"valid_server_entry_tags"`
  46. DiscoveryServers []*DiscoveryServer `json:"discovery_servers"`
  47. fileModTime time.Time
  48. }
  49. type DiscoveryServer struct {
  50. DiscoveryDateRange []time.Time `json:"discovery_date_range"`
  51. EncodedServerEntry string `json:"encoded_server_entry"`
  52. }
  53. type Sponsor struct {
  54. ID string `json:"id"`
  55. HomePages map[string][]HomePage `json:"home_pages"`
  56. MobileHomePages map[string][]HomePage `json:"mobile_home_pages"`
  57. HttpsRequestRegexes []HttpsRequestRegex `json:"https_request_regexes"`
  58. }
  59. type ClientVersion struct {
  60. Version string `json:"version"`
  61. }
  62. type HomePage struct {
  63. Region string `json:"region"`
  64. URL string `json:"url"`
  65. }
  66. type HttpsRequestRegex struct {
  67. Regex string `json:"regex"`
  68. Replace string `json:"replace"`
  69. }
  70. // NewDatabase initializes a Database, calling Reload on the specified
  71. // filename.
  72. func NewDatabase(filename string) (*Database, error) {
  73. database := &Database{}
  74. database.ReloadableFile = common.NewReloadableFile(
  75. filename,
  76. true,
  77. func(fileContent []byte, fileModTime time.Time) error {
  78. var newDatabase *Database
  79. err := json.Unmarshal(fileContent, &newDatabase)
  80. if err != nil {
  81. return errors.Trace(err)
  82. }
  83. // Note: an unmarshal directly into &database would fail
  84. // to reset to zero value fields not present in the JSON.
  85. database.Sponsors = newDatabase.Sponsors
  86. database.Versions = newDatabase.Versions
  87. database.DefaultSponsorID = newDatabase.DefaultSponsorID
  88. database.ValidServerEntryTags = newDatabase.ValidServerEntryTags
  89. database.DiscoveryServers = newDatabase.DiscoveryServers
  90. database.fileModTime = fileModTime
  91. return nil
  92. })
  93. _, err := database.Reload()
  94. if err != nil {
  95. return nil, errors.Trace(err)
  96. }
  97. return database, nil
  98. }
  99. // GetRandomizedHomepages returns a randomly ordered list of home pages
  100. // for the specified sponsor, region, and platform.
  101. func (db *Database) GetRandomizedHomepages(
  102. sponsorID, clientRegion, clientASN string, isMobilePlatform bool) []string {
  103. homepages := db.GetHomepages(sponsorID, clientRegion, clientASN, isMobilePlatform)
  104. if len(homepages) > 1 {
  105. shuffledHomepages := make([]string, len(homepages))
  106. perm := rand.Perm(len(homepages))
  107. for i, v := range perm {
  108. shuffledHomepages[v] = homepages[i]
  109. }
  110. return shuffledHomepages
  111. }
  112. return homepages
  113. }
  114. // GetHomepages returns a list of home pages for the specified sponsor,
  115. // region, and platform.
  116. func (db *Database) GetHomepages(
  117. sponsorID, clientRegion, clientASN string, isMobilePlatform bool) []string {
  118. db.ReloadableFile.RLock()
  119. defer db.ReloadableFile.RUnlock()
  120. sponsorHomePages := make([]string, 0)
  121. // Sponsor id does not exist: fail gracefully
  122. sponsor, ok := db.Sponsors[sponsorID]
  123. if !ok {
  124. sponsor, ok = db.Sponsors[db.DefaultSponsorID]
  125. if !ok {
  126. return sponsorHomePages
  127. }
  128. }
  129. if sponsor == nil {
  130. return sponsorHomePages
  131. }
  132. homePages := sponsor.HomePages
  133. if isMobilePlatform {
  134. if len(sponsor.MobileHomePages) > 0 {
  135. homePages = sponsor.MobileHomePages
  136. }
  137. }
  138. // Case: lookup succeeded and corresponding homepages found for region
  139. homePagesByRegion, ok := homePages[clientRegion]
  140. if ok {
  141. for _, homePage := range homePagesByRegion {
  142. sponsorHomePages = append(
  143. sponsorHomePages, homepageQueryParameterSubstitution(homePage.URL, clientRegion, clientASN))
  144. }
  145. }
  146. // Case: lookup failed or no corresponding homepages found for region --> use default
  147. if len(sponsorHomePages) == 0 {
  148. defaultHomePages, ok := homePages["None"]
  149. if ok {
  150. for _, homePage := range defaultHomePages {
  151. // client_region query parameter substitution
  152. sponsorHomePages = append(
  153. sponsorHomePages, homepageQueryParameterSubstitution(homePage.URL, clientRegion, clientASN))
  154. }
  155. }
  156. }
  157. return sponsorHomePages
  158. }
  159. func homepageQueryParameterSubstitution(
  160. url, clientRegion, clientASN string) string {
  161. return strings.Replace(
  162. strings.Replace(url, "client_region=XX", "client_region="+clientRegion, 1),
  163. "client_asn=XX", "client_asn="+clientASN, 1)
  164. }
  165. // GetUpgradeClientVersion returns a new client version when an upgrade is
  166. // indicated for the specified client current version. The result is "" when
  167. // no upgrade is available. Caller should normalize clientPlatform.
  168. func (db *Database) GetUpgradeClientVersion(clientVersion, clientPlatform string) string {
  169. db.ReloadableFile.RLock()
  170. defer db.ReloadableFile.RUnlock()
  171. // Check lastest version number against client version number
  172. clientVersions, ok := db.Versions[clientPlatform]
  173. if !ok {
  174. return ""
  175. }
  176. if len(clientVersions) == 0 {
  177. return ""
  178. }
  179. // NOTE: Assumes versions list is in ascending version order
  180. lastVersion := clientVersions[len(clientVersions)-1].Version
  181. lastVersionInt, err := strconv.Atoi(lastVersion)
  182. if err != nil {
  183. return ""
  184. }
  185. clientVersionInt, err := strconv.Atoi(clientVersion)
  186. if err != nil {
  187. return ""
  188. }
  189. // Return latest version if upgrade needed
  190. if lastVersionInt > clientVersionInt {
  191. return lastVersion
  192. }
  193. return ""
  194. }
  195. // GetHttpsRequestRegexes returns bytes transferred stats regexes for the
  196. // specified sponsor.
  197. func (db *Database) GetHttpsRequestRegexes(sponsorID string) []map[string]string {
  198. db.ReloadableFile.RLock()
  199. defer db.ReloadableFile.RUnlock()
  200. regexes := make([]map[string]string, 0)
  201. sponsor, ok := db.Sponsors[sponsorID]
  202. if !ok {
  203. sponsor = db.Sponsors[db.DefaultSponsorID]
  204. }
  205. if sponsor == nil {
  206. return regexes
  207. }
  208. // If neither sponsorID or DefaultSponsorID were found, sponsor will be the
  209. // zero value of the map, an empty Sponsor struct.
  210. for _, sponsorRegex := range sponsor.HttpsRequestRegexes {
  211. regex := make(map[string]string)
  212. regex["replace"] = sponsorRegex.Replace
  213. regex["regex"] = sponsorRegex.Regex
  214. regexes = append(regexes, regex)
  215. }
  216. return regexes
  217. }
  218. // DiscoverServers selects new encoded server entries to be "discovered" by
  219. // the client, using the discoveryValue -- a function of the client's IP
  220. // address -- as the input into the discovery algorithm.
  221. func (db *Database) DiscoverServers(discoveryValue int) []string {
  222. db.ReloadableFile.RLock()
  223. defer db.ReloadableFile.RUnlock()
  224. var servers []*DiscoveryServer
  225. discoveryDate := time.Now().UTC()
  226. candidateServers := make([]*DiscoveryServer, 0)
  227. for _, server := range db.DiscoveryServers {
  228. // All servers that are discoverable on this day are eligible for discovery
  229. if len(server.DiscoveryDateRange) == 2 &&
  230. discoveryDate.After(server.DiscoveryDateRange[0]) &&
  231. discoveryDate.Before(server.DiscoveryDateRange[1]) {
  232. candidateServers = append(candidateServers, server)
  233. }
  234. }
  235. timeInSeconds := int(discoveryDate.Unix())
  236. servers = selectServers(candidateServers, timeInSeconds, discoveryValue)
  237. encodedServerEntries := make([]string, 0)
  238. for _, server := range servers {
  239. encodedServerEntries = append(encodedServerEntries, server.EncodedServerEntry)
  240. }
  241. return encodedServerEntries
  242. }
  243. // Combine client IP address and time-of-day strategies to give out different
  244. // discovery servers to different clients. The aim is to achieve defense against
  245. // enumerability. We also want to achieve a degree of load balancing clients
  246. // and these strategies are expected to have reasonably random distribution,
  247. // even for a cluster of users coming from the same network.
  248. //
  249. // We only select one server: multiple results makes enumeration easier; the
  250. // strategies have a built-in load balancing effect; and date range discoverability
  251. // means a client will actually learn more servers later even if they happen to
  252. // always pick the same result at this point.
  253. //
  254. // This is a blended strategy: as long as there are enough servers to pick from,
  255. // both aspects determine which server is selected. IP address is given the
  256. // priority: if there are only a couple of servers, for example, IP address alone
  257. // determines the outcome.
  258. func selectServers(
  259. servers []*DiscoveryServer, timeInSeconds, discoveryValue int) []*DiscoveryServer {
  260. TIME_GRANULARITY := 3600
  261. if len(servers) == 0 {
  262. return nil
  263. }
  264. // Time truncated to an hour
  265. timeStrategyValue := timeInSeconds / TIME_GRANULARITY
  266. // Divide servers into buckets. The bucket count is chosen such that the number
  267. // of buckets and the number of items in each bucket are close (using sqrt).
  268. // IP address selects the bucket, time selects the item in the bucket.
  269. // NOTE: this code assumes that the range of possible timeStrategyValues
  270. // and discoveryValues are sufficient to index to all bucket items.
  271. bucketCount := calculateBucketCount(len(servers))
  272. buckets := bucketizeServerList(servers, bucketCount)
  273. if len(buckets) == 0 {
  274. return nil
  275. }
  276. bucket := buckets[discoveryValue%len(buckets)]
  277. if len(bucket) == 0 {
  278. return nil
  279. }
  280. server := bucket[timeStrategyValue%len(bucket)]
  281. serverList := make([]*DiscoveryServer, 1)
  282. serverList[0] = server
  283. return serverList
  284. }
  285. // Number of buckets such that first strategy picks among about the same number
  286. // of choices as the second strategy. Gives an edge to the "outer" strategy.
  287. func calculateBucketCount(length int) int {
  288. return int(math.Ceil(math.Sqrt(float64(length))))
  289. }
  290. // bucketizeServerList creates nearly equal sized slices of the input list.
  291. func bucketizeServerList(servers []*DiscoveryServer, bucketCount int) [][]*DiscoveryServer {
  292. // This code creates the same partitions as legacy servers:
  293. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/03bc1a7e51e7c85a816e370bb3a6c755fd9c6fee/Automation/psi_ops_discovery.py
  294. //
  295. // Both use the same algorithm from:
  296. // http://stackoverflow.com/questions/2659900/python-slicing-a-list-into-n-nearly-equal-length-partitions
  297. // TODO: this partition is constant for fixed Database content, so it could
  298. // be done once and cached in the Database ReloadableFile reloadAction.
  299. buckets := make([][]*DiscoveryServer, bucketCount)
  300. division := float64(len(servers)) / float64(bucketCount)
  301. for i := 0; i < bucketCount; i++ {
  302. start := int((division * float64(i)) + 0.5)
  303. end := int((division * (float64(i) + 1)) + 0.5)
  304. buckets[i] = servers[start:end]
  305. }
  306. return buckets
  307. }
  308. // IsValidServerEntryTag checks if the specified server entry tag is valid.
  309. func (db *Database) IsValidServerEntryTag(serverEntryTag string) bool {
  310. db.ReloadableFile.RLock()
  311. defer db.ReloadableFile.RUnlock()
  312. // Default to "valid" if the valid list is unexpectedly empty or stale. This
  313. // helps prevent premature client-side server-entry pruning when there is an
  314. // issue with updating the database.
  315. if len(db.ValidServerEntryTags) == 0 ||
  316. db.fileModTime.Add(MAX_DATABASE_AGE_FOR_SERVER_ENTRY_VALIDITY).Before(time.Now()) {
  317. return true
  318. }
  319. // The tag must be in the map and have the value "true".
  320. return db.ValidServerEntryTags[serverEntryTag]
  321. }