splitTunnel.go 13 KB

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