splitTunnel.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. "bufio"
  22. "bytes"
  23. "compress/zlib"
  24. "encoding/base64"
  25. "encoding/binary"
  26. "errors"
  27. "fmt"
  28. "io/ioutil"
  29. "net"
  30. "net/http"
  31. "sort"
  32. "strings"
  33. "sync"
  34. "time"
  35. "github.com/Psiphon-Inc/goarista/monotime"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  37. )
  38. // SplitTunnelClassifier determines whether a network destination
  39. // should be accessed through a tunnel or accessed directly.
  40. //
  41. // The classifier uses tables of IP address data, routes data,
  42. // to determine if a given IP is to be tunneled or not. If presented
  43. // with a hostname, the classifier performs a tunneled (uncensored)
  44. // DNS request to first determine the IP address for that hostname;
  45. // then a classification is made based on the IP address.
  46. //
  47. // Classification results (both the hostname resolution and the
  48. // following IP address classification) are cached for the duration
  49. // of the DNS record TTL.
  50. //
  51. // Classification is by geographical region (country code). When the
  52. // split tunnel feature is configured to be on, and if the IP
  53. // address is within the user's region, it may be accessed untunneled.
  54. // Otherwise, the IP address must be accessed through a tunnel. The
  55. // user's current region is revealed to a Tunnel via the Psiphon server
  56. // API handshake.
  57. //
  58. // When a Tunnel has a blank region (e.g., when DisableApi is set and
  59. // the tunnel registers without performing a handshake) then no routes
  60. // data is set and all IP addresses are classified as requiring tunneling.
  61. //
  62. // Split tunnel is made on a best effort basis. After the classifier is
  63. // started, but before routes data is available for the given region,
  64. // all IP addresses will be classified as requiring tunneling.
  65. //
  66. // Routes data is fetched asynchronously after Start() is called. Routes
  67. // data is cached in the data store so it need not be downloaded in full
  68. // when fresh data is in the cache.
  69. type SplitTunnelClassifier struct {
  70. mutex sync.RWMutex
  71. fetchRoutesUrlFormat string
  72. routesSignaturePublicKey string
  73. dnsServerAddress string
  74. dnsTunneler Tunneler
  75. fetchRoutesWaitGroup *sync.WaitGroup
  76. isRoutesSet bool
  77. cache map[string]*classification
  78. routes networkList
  79. }
  80. type classification struct {
  81. isUntunneled bool
  82. expiry monotime.Time
  83. }
  84. func NewSplitTunnelClassifier(config *Config, tunneler Tunneler) *SplitTunnelClassifier {
  85. return &SplitTunnelClassifier{
  86. fetchRoutesUrlFormat: config.SplitTunnelRoutesUrlFormat,
  87. routesSignaturePublicKey: config.SplitTunnelRoutesSignaturePublicKey,
  88. dnsServerAddress: config.SplitTunnelDnsServer,
  89. dnsTunneler: tunneler,
  90. fetchRoutesWaitGroup: new(sync.WaitGroup),
  91. isRoutesSet: false,
  92. cache: make(map[string]*classification),
  93. }
  94. }
  95. // Start resets the state of the classifier. In the default state,
  96. // all IP addresses are classified as requiring tunneling. With
  97. // sufficient configuration and region info, this function starts
  98. // a goroutine to asynchronously fetch and install the routes data.
  99. func (classifier *SplitTunnelClassifier) Start(fetchRoutesTunnel *Tunnel) {
  100. classifier.mutex.Lock()
  101. defer classifier.mutex.Unlock()
  102. classifier.isRoutesSet = false
  103. if classifier.dnsServerAddress == "" ||
  104. classifier.routesSignaturePublicKey == "" ||
  105. classifier.fetchRoutesUrlFormat == "" {
  106. // Split tunnel capability is not configured
  107. return
  108. }
  109. if fetchRoutesTunnel.serverContext == nil {
  110. // Tunnel has no serverContext
  111. return
  112. }
  113. if fetchRoutesTunnel.serverContext.clientRegion == "" {
  114. // Split tunnel region is unknown
  115. return
  116. }
  117. classifier.fetchRoutesWaitGroup.Add(1)
  118. go classifier.setRoutes(fetchRoutesTunnel)
  119. }
  120. // Shutdown waits until the background setRoutes() goroutine is finished.
  121. // There is no explicit shutdown signal sent to setRoutes() -- instead
  122. // we assume that in an overall shutdown situation, the tunnel used for
  123. // network access in setRoutes() is closed and network events won't delay
  124. // the completion of the goroutine.
  125. func (classifier *SplitTunnelClassifier) Shutdown() {
  126. classifier.mutex.Lock()
  127. defer classifier.mutex.Unlock()
  128. if classifier.fetchRoutesWaitGroup != nil {
  129. classifier.fetchRoutesWaitGroup.Wait()
  130. classifier.fetchRoutesWaitGroup = nil
  131. classifier.isRoutesSet = false
  132. }
  133. }
  134. // IsUntunneled takes a destination hostname or IP address and determines
  135. // if it should be accessed through a tunnel. When a hostname is presented, it
  136. // is first resolved to an IP address which can be matched against the routes data.
  137. // Multiple goroutines may invoke RequiresTunnel simultaneously. Multi-reader
  138. // locks are used in the implementation to enable concurrent access, with no locks
  139. // held during network access.
  140. func (classifier *SplitTunnelClassifier) IsUntunneled(targetAddress string) bool {
  141. if !classifier.hasRoutes() {
  142. return false
  143. }
  144. classifier.mutex.RLock()
  145. cachedClassification, ok := classifier.cache[targetAddress]
  146. classifier.mutex.RUnlock()
  147. if ok && cachedClassification.expiry.After(monotime.Now()) {
  148. return cachedClassification.isUntunneled
  149. }
  150. ipAddr, ttl, err := tunneledLookupIP(
  151. classifier.dnsServerAddress, classifier.dnsTunneler, targetAddress)
  152. if err != nil {
  153. NoticeAlert("failed to resolve address for split tunnel classification: %s", err)
  154. return false
  155. }
  156. expiry := monotime.Now().Add(ttl)
  157. isUntunneled := classifier.ipAddressInRoutes(ipAddr)
  158. // TODO: garbage collect expired items from cache?
  159. classifier.mutex.Lock()
  160. classifier.cache[targetAddress] = &classification{isUntunneled, expiry}
  161. classifier.mutex.Unlock()
  162. if isUntunneled {
  163. NoticeUntunneled(targetAddress)
  164. }
  165. return isUntunneled
  166. }
  167. // setRoutes is a background routine that fetches routes data and installs it,
  168. // which sets the isRoutesSet flag, indicating that IP addresses may now be classified.
  169. func (classifier *SplitTunnelClassifier) setRoutes(tunnel *Tunnel) {
  170. defer classifier.fetchRoutesWaitGroup.Done()
  171. // Note: a possible optimization is to install cached routes
  172. // before making the request. That would ensure some split
  173. // tunneling for the duration of the request.
  174. routesData, err := classifier.getRoutes(tunnel)
  175. if err != nil {
  176. NoticeAlert("failed to get split tunnel routes: %s", err)
  177. return
  178. }
  179. err = classifier.installRoutes(routesData)
  180. if err != nil {
  181. NoticeAlert("failed to install split tunnel routes: %s", err)
  182. return
  183. }
  184. NoticeSplitTunnelRegion(tunnel.serverContext.clientRegion)
  185. }
  186. // getRoutes makes a web request to download fresh routes data for the
  187. // given region, as indicated by the tunnel. It uses web caching, If-None-Match/ETag,
  188. // to save downloading known routes data repeatedly. If the web request
  189. // fails and cached routes data is present, that cached data is returned.
  190. func (classifier *SplitTunnelClassifier) getRoutes(tunnel *Tunnel) (routesData []byte, err error) {
  191. url := fmt.Sprintf(classifier.fetchRoutesUrlFormat, tunnel.serverContext.clientRegion)
  192. request, err := http.NewRequest("GET", url, nil)
  193. if err != nil {
  194. return nil, common.ContextError(err)
  195. }
  196. etag, err := GetSplitTunnelRoutesETag(tunnel.serverContext.clientRegion)
  197. if err != nil {
  198. return nil, common.ContextError(err)
  199. }
  200. if etag != "" {
  201. request.Header.Add("If-None-Match", etag)
  202. }
  203. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  204. return tunnel.sshClient.Dial("tcp", addr)
  205. }
  206. transport := &http.Transport{
  207. Dial: tunneledDialer,
  208. ResponseHeaderTimeout: time.Duration(*tunnel.config.FetchRoutesTimeoutSeconds) * time.Second,
  209. }
  210. httpClient := &http.Client{
  211. Transport: transport,
  212. Timeout: time.Duration(*tunnel.config.FetchRoutesTimeoutSeconds) * time.Second,
  213. }
  214. // At this time, the largest uncompressed routes data set is ~1MB. For now,
  215. // the processing pipeline is done all in-memory.
  216. useCachedRoutes := false
  217. response, err := httpClient.Do(request)
  218. if err == nil &&
  219. (response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotModified) {
  220. response.Body.Close()
  221. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  222. }
  223. if err != nil {
  224. NoticeAlert("failed to request split tunnel routes package: %s", common.ContextError(err))
  225. useCachedRoutes = true
  226. }
  227. if !useCachedRoutes {
  228. defer response.Body.Close()
  229. if response.StatusCode == http.StatusNotModified {
  230. useCachedRoutes = true
  231. }
  232. }
  233. var routesDataPackage []byte
  234. if !useCachedRoutes {
  235. routesDataPackage, err = ioutil.ReadAll(response.Body)
  236. if err != nil {
  237. NoticeAlert("failed to download split tunnel routes package: %s", common.ContextError(err))
  238. useCachedRoutes = true
  239. }
  240. }
  241. var encodedRoutesData string
  242. if !useCachedRoutes {
  243. encodedRoutesData, err = ReadAuthenticatedDataPackage(
  244. routesDataPackage, classifier.routesSignaturePublicKey)
  245. if err != nil {
  246. NoticeAlert("failed to read split tunnel routes package: %s", common.ContextError(err))
  247. useCachedRoutes = true
  248. }
  249. }
  250. var compressedRoutesData []byte
  251. if !useCachedRoutes {
  252. compressedRoutesData, err = base64.StdEncoding.DecodeString(encodedRoutesData)
  253. if err != nil {
  254. NoticeAlert("failed to decode split tunnel routes: %s", common.ContextError(err))
  255. useCachedRoutes = true
  256. }
  257. }
  258. if !useCachedRoutes {
  259. zlibReader, err := zlib.NewReader(bytes.NewReader(compressedRoutesData))
  260. if err == nil {
  261. routesData, err = ioutil.ReadAll(zlibReader)
  262. zlibReader.Close()
  263. }
  264. if err != nil {
  265. NoticeAlert("failed to decompress split tunnel routes: %s", common.ContextError(err))
  266. useCachedRoutes = true
  267. }
  268. }
  269. if !useCachedRoutes {
  270. etag := response.Header.Get("ETag")
  271. if etag != "" {
  272. err := SetSplitTunnelRoutes(tunnel.serverContext.clientRegion, etag, routesData)
  273. if err != nil {
  274. NoticeAlert("failed to cache split tunnel routes: %s", common.ContextError(err))
  275. // Proceed with fetched data, even when we can't cache it
  276. }
  277. }
  278. }
  279. if useCachedRoutes {
  280. routesData, err = GetSplitTunnelRoutesData(tunnel.serverContext.clientRegion)
  281. if err != nil {
  282. return nil, common.ContextError(err)
  283. }
  284. if routesData == nil {
  285. return nil, common.ContextError(errors.New("no cached routes"))
  286. }
  287. }
  288. return routesData, nil
  289. }
  290. // hasRoutes checks if the classifier has routes installed.
  291. func (classifier *SplitTunnelClassifier) hasRoutes() bool {
  292. classifier.mutex.RLock()
  293. defer classifier.mutex.RUnlock()
  294. return classifier.isRoutesSet
  295. }
  296. // installRoutes parses the raw routes data and creates data structures
  297. // for fast in-memory classification.
  298. func (classifier *SplitTunnelClassifier) installRoutes(routesData []byte) (err error) {
  299. classifier.mutex.Lock()
  300. defer classifier.mutex.Unlock()
  301. classifier.routes, err = NewNetworkList(routesData)
  302. if err != nil {
  303. return common.ContextError(err)
  304. }
  305. classifier.isRoutesSet = true
  306. return nil
  307. }
  308. // ipAddressInRoutes searches for a split tunnel candidate IP address in the routes data.
  309. func (classifier *SplitTunnelClassifier) ipAddressInRoutes(ipAddr net.IP) bool {
  310. classifier.mutex.RLock()
  311. defer classifier.mutex.RUnlock()
  312. return classifier.routes.ContainsIpAddress(ipAddr)
  313. }
  314. // networkList is a sorted list of network ranges. It's used to
  315. // lookup candidate IP addresses for split tunnel classification.
  316. // networkList implements Sort.Interface.
  317. type networkList []net.IPNet
  318. // NewNetworkList parses text routes data and produces a networkList
  319. // for fast ContainsIpAddress lookup.
  320. // The input format is expected to be text lines where each line
  321. // is, e.g., "1.2.3.0\t255.255.255.0\n"
  322. func NewNetworkList(routesData []byte) (networkList, error) {
  323. // Parse text routes data
  324. var list networkList
  325. scanner := bufio.NewScanner(bytes.NewReader(routesData))
  326. scanner.Split(bufio.ScanLines)
  327. for scanner.Scan() {
  328. s := strings.Split(scanner.Text(), "\t")
  329. if len(s) != 2 {
  330. continue
  331. }
  332. ip := parseIPv4(s[0])
  333. mask := parseIPv4Mask(s[1])
  334. if ip == nil || mask == nil {
  335. continue
  336. }
  337. list = append(list, net.IPNet{IP: ip.Mask(mask), Mask: mask})
  338. }
  339. if len(list) == 0 {
  340. return nil, common.ContextError(errors.New("Routes data contains no networks"))
  341. }
  342. // Sort data for fast lookup
  343. sort.Sort(list)
  344. return list, nil
  345. }
  346. func parseIPv4(s string) net.IP {
  347. ip := net.ParseIP(s)
  348. if ip == nil {
  349. return nil
  350. }
  351. return ip.To4()
  352. }
  353. func parseIPv4Mask(s string) net.IPMask {
  354. ip := parseIPv4(s)
  355. if ip == nil {
  356. return nil
  357. }
  358. mask := net.IPMask(ip)
  359. if bits, size := mask.Size(); bits == 0 || size == 0 {
  360. return nil
  361. }
  362. return mask
  363. }
  364. // Len implementes Sort.Interface
  365. func (list networkList) Len() int {
  366. return len(list)
  367. }
  368. // Swap implementes Sort.Interface
  369. func (list networkList) Swap(i, j int) {
  370. list[i], list[j] = list[j], list[i]
  371. }
  372. // Less implementes Sort.Interface
  373. func (list networkList) Less(i, j int) bool {
  374. return binary.BigEndian.Uint32(list[i].IP) < binary.BigEndian.Uint32(list[j].IP)
  375. }
  376. // ContainsIpAddress performs a binary search on the networkList to
  377. // find a network containing the candidate IP address.
  378. func (list networkList) ContainsIpAddress(addr net.IP) bool {
  379. // Search criteria
  380. //
  381. // The following conditions are satisfied when address_IP is in the network:
  382. // 1. address_IP ^ network_mask == network_IP ^ network_mask
  383. // 2. address_IP >= network_IP.
  384. // We are also assuming that network ranges do not overlap.
  385. //
  386. // For an ascending array of networks, the sort.Search returns the smallest
  387. // index idx for which condition network_IP > address_IP is satisfied, so we
  388. // are checking whether or not adrress_IP belongs to the network[idx-1].
  389. // Edge conditions check
  390. //
  391. // idx == 0 means that address_IP is lesser than the first (smallest) network_IP
  392. // thus never satisfies search condition 2.
  393. // idx == array_length means that address_IP is larger than the last (largest)
  394. // network_IP so we need to check the last element for condition 1.
  395. addrValue := binary.BigEndian.Uint32(addr.To4())
  396. index := sort.Search(len(list), func(i int) bool {
  397. networkValue := binary.BigEndian.Uint32(list[i].IP)
  398. return networkValue > addrValue
  399. })
  400. return index > 0 && list[index-1].IP.Equal(addr.Mask(list[index-1].Mask))
  401. }
  402. // tunneledLookupIP resolves a split tunnel candidate hostname with a tunneled
  403. // DNS request.
  404. func tunneledLookupIP(
  405. dnsServerAddress string, dnsTunneler Tunneler, host string) (addr net.IP, ttl time.Duration, err error) {
  406. ipAddr := net.ParseIP(host)
  407. if ipAddr != nil {
  408. // maxDuration from golang.org/src/time/time.go
  409. return ipAddr, time.Duration(1<<63 - 1), nil
  410. }
  411. // dnsServerAddress must be an IP address
  412. ipAddr = net.ParseIP(dnsServerAddress)
  413. if ipAddr == nil {
  414. return nil, 0, common.ContextError(errors.New("invalid IP address"))
  415. }
  416. // Dial's alwaysTunnel is set to true to ensure this connection
  417. // is tunneled (also ensures this code path isn't circular).
  418. // Assumes tunnel dialer conn configures timeouts and interruptibility.
  419. conn, err := dnsTunneler.Dial(fmt.Sprintf(
  420. "%s:%d", dnsServerAddress, DNS_PORT), true, nil)
  421. if err != nil {
  422. return nil, 0, common.ContextError(err)
  423. }
  424. ipAddrs, ttls, err := ResolveIP(host, conn)
  425. if err != nil {
  426. return nil, 0, common.ContextError(err)
  427. }
  428. if len(ipAddrs) < 1 {
  429. return nil, 0, common.ContextError(errors.New("no IP address"))
  430. }
  431. return ipAddrs[0], ttls[0], nil
  432. }