net.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. "crypto/tls"
  22. "crypto/x509"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "net"
  28. "net/http"
  29. "net/url"
  30. "reflect"
  31. "sync"
  32. "time"
  33. "github.com/Psiphon-Inc/dns"
  34. )
  35. const DNS_PORT = 53
  36. // DialConfig contains parameters to determine the behavior
  37. // of a Psiphon dialer (TCPDial, MeekDial, etc.)
  38. type DialConfig struct {
  39. // UpstreamProxyUrl specifies a proxy to connect through.
  40. // E.g., "http://proxyhost:8080"
  41. // "socks5://user:password@proxyhost:1080"
  42. // "socks4a://proxyhost:1080"
  43. // "http://NTDOMAIN\NTUser:password@proxyhost:3375"
  44. //
  45. // Certain tunnel protocols require HTTP CONNECT support
  46. // when a HTTP proxy is specified. If CONNECT is not
  47. // supported, those protocols will not connect.
  48. UpstreamProxyUrl string
  49. ConnectTimeout time.Duration
  50. // PendingConns is used to track and interrupt dials in progress.
  51. // Dials may be interrupted using PendingConns.CloseAll(). Once instantiated,
  52. // a conn is added to pendingConns before the network connect begins and
  53. // removed from pendingConns once the connect succeeds or fails.
  54. PendingConns *Conns
  55. // BindToDevice parameters are used to exclude connections and
  56. // associated DNS requests from VPN routing.
  57. // When DeviceBinder is set, any underlying socket is
  58. // submitted to the device binding servicebefore connecting.
  59. // The service should bind the socket to a device so that it doesn't route
  60. // through a VPN interface. This service is also used to bind UDP sockets used
  61. // for DNS requests, in which case DnsServerGetter is used to get the
  62. // current active untunneled network DNS server.
  63. DeviceBinder DeviceBinder
  64. DnsServerGetter DnsServerGetter
  65. // UseIndistinguishableTLS specifies whether to try to use an
  66. // alternative stack for TLS. From a circumvention perspective,
  67. // Go's TLS has a distinct fingerprint that may be used for blocking.
  68. // Only applies to TLS connections.
  69. UseIndistinguishableTLS bool
  70. // TrustedCACertificatesFilename specifies a file containing trusted
  71. // CA certs. The file contents should be compatible with OpenSSL's
  72. // SSL_CTX_load_verify_locations.
  73. // Only applies to UseIndistinguishableTLS connections.
  74. TrustedCACertificatesFilename string
  75. // DeviceRegion is the reported region the host device is running in.
  76. // When set, this value may be used, pre-connection, to select performance
  77. // or circumvention optimization strategies for the given region.
  78. DeviceRegion string
  79. // ResolvedIPCallback, when set, is called with the IP address that was
  80. // dialed. This is either the specified IP address in the dial address,
  81. // or the resolved IP address in the case where the dial address is a
  82. // domain name.
  83. // The callback may be invoked by a concurrent goroutine.
  84. ResolvedIPCallback func(string)
  85. }
  86. // DeviceBinder defines the interface to the external BindToDevice provider
  87. type DeviceBinder interface {
  88. BindToDevice(fileDescriptor int) error
  89. }
  90. // NetworkConnectivityChecker defines the interface to the external
  91. // HasNetworkConnectivity provider
  92. type NetworkConnectivityChecker interface {
  93. // TODO: change to bool return value once gobind supports that type
  94. HasNetworkConnectivity() int
  95. }
  96. // DnsServerGetter defines the interface to the external GetDnsServer provider
  97. type DnsServerGetter interface {
  98. GetPrimaryDnsServer() string
  99. GetSecondaryDnsServer() string
  100. }
  101. // TimeoutError implements the error interface
  102. type TimeoutError struct{}
  103. func (TimeoutError) Error() string { return "timed out" }
  104. func (TimeoutError) Timeout() bool { return true }
  105. func (TimeoutError) Temporary() bool { return true }
  106. // Dialer is a custom dialer compatible with http.Transport.Dial.
  107. type Dialer func(string, string) (net.Conn, error)
  108. // Conns is a synchronized list of Conns that is used to coordinate
  109. // interrupting a set of goroutines establishing connections, or
  110. // close a set of open connections, etc.
  111. // Once the list is closed, no more items may be added to the
  112. // list (unless it is reset).
  113. type Conns struct {
  114. mutex sync.Mutex
  115. isClosed bool
  116. conns map[net.Conn]bool
  117. }
  118. func (conns *Conns) Reset() {
  119. conns.mutex.Lock()
  120. defer conns.mutex.Unlock()
  121. conns.isClosed = false
  122. conns.conns = make(map[net.Conn]bool)
  123. }
  124. func (conns *Conns) Add(conn net.Conn) bool {
  125. conns.mutex.Lock()
  126. defer conns.mutex.Unlock()
  127. if conns.isClosed {
  128. return false
  129. }
  130. if conns.conns == nil {
  131. conns.conns = make(map[net.Conn]bool)
  132. }
  133. conns.conns[conn] = true
  134. return true
  135. }
  136. func (conns *Conns) Remove(conn net.Conn) {
  137. conns.mutex.Lock()
  138. defer conns.mutex.Unlock()
  139. delete(conns.conns, conn)
  140. }
  141. func (conns *Conns) CloseAll() {
  142. conns.mutex.Lock()
  143. defer conns.mutex.Unlock()
  144. conns.isClosed = true
  145. for conn, _ := range conns.conns {
  146. conn.Close()
  147. }
  148. conns.conns = make(map[net.Conn]bool)
  149. }
  150. // LocalProxyRelay sends to remoteConn bytes received from localConn,
  151. // and sends to localConn bytes received from remoteConn.
  152. func LocalProxyRelay(proxyType string, localConn, remoteConn net.Conn) {
  153. copyWaitGroup := new(sync.WaitGroup)
  154. copyWaitGroup.Add(1)
  155. go func() {
  156. defer copyWaitGroup.Done()
  157. _, err := io.Copy(localConn, remoteConn)
  158. if err != nil {
  159. err = fmt.Errorf("Relay failed: %s", ContextError(err))
  160. NoticeLocalProxyError(proxyType, err)
  161. }
  162. }()
  163. _, err := io.Copy(remoteConn, localConn)
  164. if err != nil {
  165. err = fmt.Errorf("Relay failed: %s", ContextError(err))
  166. NoticeLocalProxyError(proxyType, err)
  167. }
  168. copyWaitGroup.Wait()
  169. }
  170. // WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
  171. // periodically check for network connectivity. It returns true if
  172. // no NetworkConnectivityChecker is provided (waiting is disabled)
  173. // or when NetworkConnectivityChecker.HasNetworkConnectivity()
  174. // indicates connectivity. It waits and polls the checker once a second.
  175. // If any stop is broadcast, false is returned immediately.
  176. func WaitForNetworkConnectivity(
  177. connectivityChecker NetworkConnectivityChecker, stopBroadcasts ...<-chan struct{}) bool {
  178. if connectivityChecker == nil || 1 == connectivityChecker.HasNetworkConnectivity() {
  179. return true
  180. }
  181. NoticeInfo("waiting for network connectivity")
  182. ticker := time.NewTicker(1 * time.Second)
  183. for {
  184. if 1 == connectivityChecker.HasNetworkConnectivity() {
  185. return true
  186. }
  187. selectCases := make([]reflect.SelectCase, 1+len(stopBroadcasts))
  188. selectCases[0] = reflect.SelectCase{
  189. Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ticker.C)}
  190. for i, stopBroadcast := range stopBroadcasts {
  191. selectCases[i+1] = reflect.SelectCase{
  192. Dir: reflect.SelectRecv, Chan: reflect.ValueOf(stopBroadcast)}
  193. }
  194. chosen, _, ok := reflect.Select(selectCases)
  195. if chosen == 0 && ok {
  196. // Ticker case, so check again
  197. } else {
  198. // Stop case
  199. return false
  200. }
  201. }
  202. }
  203. // ResolveIP uses a custom dns stack to make a DNS query over the
  204. // given TCP or UDP conn. This is used, e.g., when we need to ensure
  205. // that a DNS connection bypasses a VPN interface (BindToDevice) or
  206. // when we need to ensure that a DNS connection is tunneled.
  207. // Caller must set timeouts or interruptibility as required for conn.
  208. func ResolveIP(host string, conn net.Conn) (addrs []net.IP, ttls []time.Duration, err error) {
  209. // Send the DNS query
  210. dnsConn := &dns.Conn{Conn: conn}
  211. defer dnsConn.Close()
  212. query := new(dns.Msg)
  213. query.SetQuestion(dns.Fqdn(host), dns.TypeA)
  214. query.RecursionDesired = true
  215. dnsConn.WriteMsg(query)
  216. // Process the response
  217. response, err := dnsConn.ReadMsg()
  218. if err != nil {
  219. return nil, nil, ContextError(err)
  220. }
  221. addrs = make([]net.IP, 0)
  222. ttls = make([]time.Duration, 0)
  223. for _, answer := range response.Answer {
  224. if a, ok := answer.(*dns.A); ok {
  225. addrs = append(addrs, a.A)
  226. ttl := time.Duration(a.Hdr.Ttl) * time.Second
  227. ttls = append(ttls, ttl)
  228. }
  229. }
  230. return addrs, ttls, nil
  231. }
  232. // MakeUntunneledHttpsClient returns a net/http.Client which is
  233. // configured to use custom dialing features -- including BindToDevice,
  234. // UseIndistinguishableTLS, etc. -- for a specific HTTPS request URL.
  235. // If verifyLegacyCertificate is not nil, it's used for certificate
  236. // verification.
  237. // Because UseIndistinguishableTLS requires a hack to work with
  238. // net/http, MakeUntunneledHttpClient may return a modified request URL
  239. // to be used. Callers should always use this return value to make
  240. // requests, not the input value.
  241. func MakeUntunneledHttpsClient(
  242. dialConfig *DialConfig,
  243. verifyLegacyCertificate *x509.Certificate,
  244. requestUrl string,
  245. requestTimeout time.Duration) (*http.Client, string, error) {
  246. dialer := NewCustomTLSDialer(
  247. // Note: when verifyLegacyCertificate is not nil, some
  248. // of the other CustomTLSConfig is overridden.
  249. &CustomTLSConfig{
  250. Dial: NewTCPDialer(dialConfig),
  251. VerifyLegacyCertificate: verifyLegacyCertificate,
  252. SendServerName: true,
  253. SkipVerify: false,
  254. UseIndistinguishableTLS: dialConfig.UseIndistinguishableTLS,
  255. TrustedCACertificatesFilename: dialConfig.TrustedCACertificatesFilename,
  256. })
  257. urlComponents, err := url.Parse(requestUrl)
  258. if err != nil {
  259. return nil, "", ContextError(err)
  260. }
  261. // Change the scheme to "http"; otherwise http.Transport will try to do
  262. // another TLS handshake inside the explicit TLS session. Also need to
  263. // force an explicit port, as the default for "http", 80, won't talk TLS.
  264. urlComponents.Scheme = "http"
  265. host, port, err := net.SplitHostPort(urlComponents.Host)
  266. if err != nil {
  267. // Assume there's no port
  268. host = urlComponents.Host
  269. port = ""
  270. }
  271. if port == "" {
  272. port = "443"
  273. }
  274. urlComponents.Host = net.JoinHostPort(host, port)
  275. transport := &http.Transport{
  276. Dial: dialer,
  277. }
  278. httpClient := &http.Client{
  279. Timeout: requestTimeout,
  280. Transport: transport,
  281. }
  282. return httpClient, urlComponents.String(), nil
  283. }
  284. // MakeTunneledHttpClient returns a net/http.Client which is
  285. // configured to use custom dialing features including tunneled
  286. // dialing and, optionally, UseTrustedCACertificatesForStockTLS.
  287. // Unlike MakeUntunneledHttpsClient and makePsiphonHttpsClient,
  288. // This http.Client uses stock TLS and no scheme transformation
  289. // hack is required.
  290. func MakeTunneledHttpClient(
  291. config *Config,
  292. tunnel *Tunnel,
  293. requestTimeout time.Duration) (*http.Client, error) {
  294. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  295. return tunnel.sshClient.Dial("tcp", addr)
  296. }
  297. transport := &http.Transport{
  298. Dial: tunneledDialer,
  299. ResponseHeaderTimeout: requestTimeout,
  300. }
  301. if config.UseTrustedCACertificatesForStockTLS {
  302. if config.TrustedCACertificatesFilename == "" {
  303. return nil, ContextError(errors.New(
  304. "UseTrustedCACertificatesForStockTLS requires TrustedCACertificatesFilename"))
  305. }
  306. rootCAs := x509.NewCertPool()
  307. certData, err := ioutil.ReadFile(config.TrustedCACertificatesFilename)
  308. if err != nil {
  309. return nil, ContextError(err)
  310. }
  311. rootCAs.AppendCertsFromPEM(certData)
  312. transport.TLSClientConfig = &tls.Config{RootCAs: rootCAs}
  313. }
  314. return &http.Client{
  315. Transport: transport,
  316. Timeout: requestTimeout,
  317. }, nil
  318. }