splitTunnel.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. "bytes"
  22. "compress/zlib"
  23. "encoding/base64"
  24. "errors"
  25. "fmt"
  26. "io/ioutil"
  27. "net"
  28. "net/http"
  29. "sync"
  30. "time"
  31. "github.com/Psiphon-Inc/goarista/monotime"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  33. )
  34. // SplitTunnelClassifier determines whether a network destination
  35. // should be accessed through a tunnel or accessed directly.
  36. //
  37. // The classifier uses tables of IP address data, routes data,
  38. // to determine if a given IP is to be tunneled or not. If presented
  39. // with a hostname, the classifier performs a tunneled (uncensored)
  40. // DNS request to first determine the IP address for that hostname;
  41. // then a classification is made based on the IP address.
  42. //
  43. // Classification results (both the hostname resolution and the
  44. // following IP address classification) are cached for the duration
  45. // of the DNS record TTL.
  46. //
  47. // Classification is by geographical region (country code). When the
  48. // split tunnel feature is configured to be on, and if the IP
  49. // address is within the user's region, it may be accessed untunneled.
  50. // Otherwise, the IP address must be accessed through a tunnel. The
  51. // user's current region is revealed to a Tunnel via the Psiphon server
  52. // API handshake.
  53. //
  54. // When a Tunnel has a blank region (e.g., when DisableApi is set and
  55. // the tunnel registers without performing a handshake) then no routes
  56. // data is set and all IP addresses are classified as requiring tunneling.
  57. //
  58. // Split tunnel is made on a best effort basis. After the classifier is
  59. // started, but before routes data is available for the given region,
  60. // all IP addresses will be classified as requiring tunneling.
  61. //
  62. // Routes data is fetched asynchronously after Start() is called. Routes
  63. // data is cached in the data store so it need not be downloaded in full
  64. // when fresh data is in the cache.
  65. type SplitTunnelClassifier struct {
  66. mutex sync.RWMutex
  67. fetchRoutesUrlFormat string
  68. routesSignaturePublicKey string
  69. dnsServerAddress string
  70. dnsTunneler Tunneler
  71. fetchRoutesWaitGroup *sync.WaitGroup
  72. isRoutesSet bool
  73. cache map[string]*classification
  74. routes common.SubnetLookup
  75. }
  76. type classification struct {
  77. isUntunneled bool
  78. expiry monotime.Time
  79. }
  80. func NewSplitTunnelClassifier(config *Config, tunneler Tunneler) *SplitTunnelClassifier {
  81. return &SplitTunnelClassifier{
  82. fetchRoutesUrlFormat: config.SplitTunnelRoutesUrlFormat,
  83. routesSignaturePublicKey: config.SplitTunnelRoutesSignaturePublicKey,
  84. dnsServerAddress: config.SplitTunnelDnsServer,
  85. dnsTunneler: tunneler,
  86. fetchRoutesWaitGroup: new(sync.WaitGroup),
  87. isRoutesSet: false,
  88. cache: make(map[string]*classification),
  89. }
  90. }
  91. // Start resets the state of the classifier. In the default state,
  92. // all IP addresses are classified as requiring tunneling. With
  93. // sufficient configuration and region info, this function starts
  94. // a goroutine to asynchronously fetch and install the routes data.
  95. func (classifier *SplitTunnelClassifier) Start(fetchRoutesTunnel *Tunnel) {
  96. classifier.mutex.Lock()
  97. defer classifier.mutex.Unlock()
  98. classifier.isRoutesSet = false
  99. if classifier.dnsServerAddress == "" ||
  100. classifier.routesSignaturePublicKey == "" ||
  101. classifier.fetchRoutesUrlFormat == "" {
  102. // Split tunnel capability is not configured
  103. return
  104. }
  105. if fetchRoutesTunnel.serverContext == nil {
  106. // Tunnel has no serverContext
  107. return
  108. }
  109. if fetchRoutesTunnel.serverContext.clientRegion == "" {
  110. // Split tunnel region is unknown
  111. return
  112. }
  113. classifier.fetchRoutesWaitGroup.Add(1)
  114. go classifier.setRoutes(fetchRoutesTunnel)
  115. }
  116. // Shutdown waits until the background setRoutes() goroutine is finished.
  117. // There is no explicit shutdown signal sent to setRoutes() -- instead
  118. // we assume that in an overall shutdown situation, the tunnel used for
  119. // network access in setRoutes() is closed and network events won't delay
  120. // the completion of the goroutine.
  121. func (classifier *SplitTunnelClassifier) Shutdown() {
  122. classifier.mutex.Lock()
  123. defer classifier.mutex.Unlock()
  124. if classifier.fetchRoutesWaitGroup != nil {
  125. classifier.fetchRoutesWaitGroup.Wait()
  126. classifier.fetchRoutesWaitGroup = nil
  127. classifier.isRoutesSet = false
  128. }
  129. }
  130. // IsUntunneled takes a destination hostname or IP address and determines
  131. // if it should be accessed through a tunnel. When a hostname is presented, it
  132. // is first resolved to an IP address which can be matched against the routes data.
  133. // Multiple goroutines may invoke RequiresTunnel simultaneously. Multi-reader
  134. // locks are used in the implementation to enable concurrent access, with no locks
  135. // held during network access.
  136. func (classifier *SplitTunnelClassifier) IsUntunneled(targetAddress string) bool {
  137. if !classifier.hasRoutes() {
  138. return false
  139. }
  140. classifier.mutex.RLock()
  141. cachedClassification, ok := classifier.cache[targetAddress]
  142. classifier.mutex.RUnlock()
  143. if ok && cachedClassification.expiry.After(monotime.Now()) {
  144. return cachedClassification.isUntunneled
  145. }
  146. ipAddr, ttl, err := tunneledLookupIP(
  147. classifier.dnsServerAddress, classifier.dnsTunneler, targetAddress)
  148. if err != nil {
  149. NoticeAlert("failed to resolve address for split tunnel classification: %s", err)
  150. return false
  151. }
  152. expiry := monotime.Now().Add(ttl)
  153. isUntunneled := classifier.ipAddressInRoutes(ipAddr)
  154. // TODO: garbage collect expired items from cache?
  155. classifier.mutex.Lock()
  156. classifier.cache[targetAddress] = &classification{isUntunneled, expiry}
  157. classifier.mutex.Unlock()
  158. if isUntunneled {
  159. NoticeUntunneled(targetAddress)
  160. }
  161. return isUntunneled
  162. }
  163. // setRoutes is a background routine that fetches routes data and installs it,
  164. // which sets the isRoutesSet flag, indicating that IP addresses may now be classified.
  165. func (classifier *SplitTunnelClassifier) setRoutes(tunnel *Tunnel) {
  166. defer classifier.fetchRoutesWaitGroup.Done()
  167. // Note: a possible optimization is to install cached routes
  168. // before making the request. That would ensure some split
  169. // tunneling for the duration of the request.
  170. routesData, err := classifier.getRoutes(tunnel)
  171. if err != nil {
  172. NoticeAlert("failed to get split tunnel routes: %s", err)
  173. return
  174. }
  175. err = classifier.installRoutes(routesData)
  176. if err != nil {
  177. NoticeAlert("failed to install split tunnel routes: %s", err)
  178. return
  179. }
  180. NoticeSplitTunnelRegion(tunnel.serverContext.clientRegion)
  181. }
  182. // getRoutes makes a web request to download fresh routes data for the
  183. // given region, as indicated by the tunnel. It uses web caching, If-None-Match/ETag,
  184. // to save downloading known routes data repeatedly. If the web request
  185. // fails and cached routes data is present, that cached data is returned.
  186. func (classifier *SplitTunnelClassifier) getRoutes(tunnel *Tunnel) (routesData []byte, err error) {
  187. url := fmt.Sprintf(classifier.fetchRoutesUrlFormat, tunnel.serverContext.clientRegion)
  188. request, err := http.NewRequest("GET", url, nil)
  189. if err != nil {
  190. return nil, common.ContextError(err)
  191. }
  192. etag, err := GetSplitTunnelRoutesETag(tunnel.serverContext.clientRegion)
  193. if err != nil {
  194. return nil, common.ContextError(err)
  195. }
  196. if etag != "" {
  197. request.Header.Add("If-None-Match", etag)
  198. }
  199. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  200. return tunnel.sshClient.Dial("tcp", addr)
  201. }
  202. transport := &http.Transport{
  203. Dial: tunneledDialer,
  204. ResponseHeaderTimeout: time.Duration(*tunnel.config.FetchRoutesTimeoutSeconds) * time.Second,
  205. }
  206. httpClient := &http.Client{
  207. Transport: transport,
  208. Timeout: time.Duration(*tunnel.config.FetchRoutesTimeoutSeconds) * time.Second,
  209. }
  210. // At this time, the largest uncompressed routes data set is ~1MB. For now,
  211. // the processing pipeline is done all in-memory.
  212. useCachedRoutes := false
  213. response, err := httpClient.Do(request)
  214. if err == nil &&
  215. (response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNotModified) {
  216. response.Body.Close()
  217. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  218. }
  219. if err != nil {
  220. NoticeAlert("failed to request split tunnel routes package: %s", common.ContextError(err))
  221. useCachedRoutes = true
  222. }
  223. if !useCachedRoutes {
  224. defer response.Body.Close()
  225. if response.StatusCode == http.StatusNotModified {
  226. useCachedRoutes = true
  227. }
  228. }
  229. var routesDataPackage []byte
  230. if !useCachedRoutes {
  231. routesDataPackage, err = ioutil.ReadAll(response.Body)
  232. if err != nil {
  233. NoticeAlert("failed to download split tunnel routes package: %s", common.ContextError(err))
  234. useCachedRoutes = true
  235. }
  236. }
  237. var encodedRoutesData string
  238. if !useCachedRoutes {
  239. encodedRoutesData, err = common.ReadAuthenticatedDataPackage(
  240. routesDataPackage, classifier.routesSignaturePublicKey)
  241. if err != nil {
  242. NoticeAlert("failed to read split tunnel routes package: %s", common.ContextError(err))
  243. useCachedRoutes = true
  244. }
  245. }
  246. var compressedRoutesData []byte
  247. if !useCachedRoutes {
  248. compressedRoutesData, err = base64.StdEncoding.DecodeString(encodedRoutesData)
  249. if err != nil {
  250. NoticeAlert("failed to decode split tunnel routes: %s", common.ContextError(err))
  251. useCachedRoutes = true
  252. }
  253. }
  254. if !useCachedRoutes {
  255. zlibReader, err := zlib.NewReader(bytes.NewReader(compressedRoutesData))
  256. if err == nil {
  257. routesData, err = ioutil.ReadAll(zlibReader)
  258. zlibReader.Close()
  259. }
  260. if err != nil {
  261. NoticeAlert("failed to decompress split tunnel routes: %s", common.ContextError(err))
  262. useCachedRoutes = true
  263. }
  264. }
  265. if !useCachedRoutes {
  266. etag := response.Header.Get("ETag")
  267. if etag != "" {
  268. err := SetSplitTunnelRoutes(tunnel.serverContext.clientRegion, etag, routesData)
  269. if err != nil {
  270. NoticeAlert("failed to cache split tunnel routes: %s", common.ContextError(err))
  271. // Proceed with fetched data, even when we can't cache it
  272. }
  273. }
  274. }
  275. if useCachedRoutes {
  276. routesData, err = GetSplitTunnelRoutesData(tunnel.serverContext.clientRegion)
  277. if err != nil {
  278. return nil, common.ContextError(err)
  279. }
  280. if routesData == nil {
  281. return nil, common.ContextError(errors.New("no cached routes"))
  282. }
  283. }
  284. return routesData, nil
  285. }
  286. // hasRoutes checks if the classifier has routes installed.
  287. func (classifier *SplitTunnelClassifier) hasRoutes() bool {
  288. classifier.mutex.RLock()
  289. defer classifier.mutex.RUnlock()
  290. return classifier.isRoutesSet
  291. }
  292. // installRoutes parses the raw routes data and creates data structures
  293. // for fast in-memory classification.
  294. func (classifier *SplitTunnelClassifier) installRoutes(routesData []byte) (err error) {
  295. classifier.mutex.Lock()
  296. defer classifier.mutex.Unlock()
  297. classifier.routes, err = common.NewSubnetLookupFromRoutes(routesData)
  298. if err != nil {
  299. return common.ContextError(err)
  300. }
  301. classifier.isRoutesSet = true
  302. return nil
  303. }
  304. // ipAddressInRoutes searches for a split tunnel candidate IP address in the routes data.
  305. func (classifier *SplitTunnelClassifier) ipAddressInRoutes(ipAddr net.IP) bool {
  306. classifier.mutex.RLock()
  307. defer classifier.mutex.RUnlock()
  308. return classifier.routes.ContainsIPAddress(ipAddr)
  309. }
  310. // tunneledLookupIP resolves a split tunnel candidate hostname with a tunneled
  311. // DNS request.
  312. func tunneledLookupIP(
  313. dnsServerAddress string, dnsTunneler Tunneler, host string) (addr net.IP, ttl time.Duration, err error) {
  314. ipAddr := net.ParseIP(host)
  315. if ipAddr != nil {
  316. // maxDuration from golang.org/src/time/time.go
  317. return ipAddr, time.Duration(1<<63 - 1), nil
  318. }
  319. // dnsServerAddress must be an IP address
  320. ipAddr = net.ParseIP(dnsServerAddress)
  321. if ipAddr == nil {
  322. return nil, 0, common.ContextError(errors.New("invalid IP address"))
  323. }
  324. // Dial's alwaysTunnel is set to true to ensure this connection
  325. // is tunneled (also ensures this code path isn't circular).
  326. // Assumes tunnel dialer conn configures timeouts and interruptibility.
  327. conn, err := dnsTunneler.Dial(fmt.Sprintf(
  328. "%s:%d", dnsServerAddress, DNS_PORT), true, nil)
  329. if err != nil {
  330. return nil, 0, common.ContextError(err)
  331. }
  332. ipAddrs, ttls, err := ResolveIP(host, conn)
  333. if err != nil {
  334. return nil, 0, common.ContextError(err)
  335. }
  336. if len(ipAddrs) < 1 {
  337. return nil, 0, common.ContextError(errors.New("no IP address"))
  338. }
  339. return ipAddrs[0], ttls[0], nil
  340. }