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