splitTunnel.go 13 KB

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