splitTunnel.go 16 KB

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