net.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. // NetworkConnectivityChecker defines the interface to the external
  87. // HasNetworkConnectivity provider
  88. type NetworkConnectivityChecker interface {
  89. // TODO: change to bool return value once gobind supports that type
  90. HasNetworkConnectivity() int
  91. }
  92. // DeviceBinder defines the interface to the external BindToDevice provider
  93. type DeviceBinder interface {
  94. BindToDevice(fileDescriptor int) error
  95. }
  96. // DnsServerGetter defines the interface to the external GetDnsServer provider
  97. type DnsServerGetter interface {
  98. GetPrimaryDnsServer() string
  99. GetSecondaryDnsServer() string
  100. }
  101. // HostNameTransformer defines the interface for pluggable hostname
  102. // transformation circumvention strategies.
  103. type HostNameTransformer interface {
  104. TransformHostName(hostname string) (string, bool)
  105. }
  106. // IdentityHostNameTransformer is the default HostNameTransformer, which
  107. // returns the hostname unchanged.
  108. type IdentityHostNameTransformer struct{}
  109. func (IdentityHostNameTransformer) TransformHostName(hostname string) (string, bool) {
  110. return hostname, false
  111. }
  112. // TimeoutError implements the error interface
  113. type TimeoutError struct{}
  114. func (TimeoutError) Error() string { return "timed out" }
  115. func (TimeoutError) Timeout() bool { return true }
  116. func (TimeoutError) Temporary() bool { return true }
  117. // Dialer is a custom dialer compatible with http.Transport.Dial.
  118. type Dialer func(string, string) (net.Conn, error)
  119. // Conns is a synchronized list of Conns that is used to coordinate
  120. // interrupting a set of goroutines establishing connections, or
  121. // close a set of open connections, etc.
  122. // Once the list is closed, no more items may be added to the
  123. // list (unless it is reset).
  124. type Conns struct {
  125. mutex sync.Mutex
  126. isClosed bool
  127. conns map[net.Conn]bool
  128. }
  129. func (conns *Conns) Reset() {
  130. conns.mutex.Lock()
  131. defer conns.mutex.Unlock()
  132. conns.isClosed = false
  133. conns.conns = make(map[net.Conn]bool)
  134. }
  135. func (conns *Conns) Add(conn net.Conn) bool {
  136. conns.mutex.Lock()
  137. defer conns.mutex.Unlock()
  138. if conns.isClosed {
  139. return false
  140. }
  141. if conns.conns == nil {
  142. conns.conns = make(map[net.Conn]bool)
  143. }
  144. conns.conns[conn] = true
  145. return true
  146. }
  147. func (conns *Conns) Remove(conn net.Conn) {
  148. conns.mutex.Lock()
  149. defer conns.mutex.Unlock()
  150. delete(conns.conns, conn)
  151. }
  152. func (conns *Conns) CloseAll() {
  153. conns.mutex.Lock()
  154. defer conns.mutex.Unlock()
  155. conns.isClosed = true
  156. for conn, _ := range conns.conns {
  157. conn.Close()
  158. }
  159. conns.conns = make(map[net.Conn]bool)
  160. }
  161. // LocalProxyRelay sends to remoteConn bytes received from localConn,
  162. // and sends to localConn bytes received from remoteConn.
  163. func LocalProxyRelay(proxyType string, localConn, remoteConn net.Conn) {
  164. copyWaitGroup := new(sync.WaitGroup)
  165. copyWaitGroup.Add(1)
  166. go func() {
  167. defer copyWaitGroup.Done()
  168. _, err := io.Copy(localConn, remoteConn)
  169. if err != nil {
  170. err = fmt.Errorf("Relay failed: %s", ContextError(err))
  171. NoticeLocalProxyError(proxyType, err)
  172. }
  173. }()
  174. _, err := io.Copy(remoteConn, localConn)
  175. if err != nil {
  176. err = fmt.Errorf("Relay failed: %s", ContextError(err))
  177. NoticeLocalProxyError(proxyType, err)
  178. }
  179. copyWaitGroup.Wait()
  180. }
  181. // WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
  182. // periodically check for network connectivity. It returns true if
  183. // no NetworkConnectivityChecker is provided (waiting is disabled)
  184. // or when NetworkConnectivityChecker.HasNetworkConnectivity()
  185. // indicates connectivity. It waits and polls the checker once a second.
  186. // If any stop is broadcast, false is returned immediately.
  187. func WaitForNetworkConnectivity(
  188. connectivityChecker NetworkConnectivityChecker, stopBroadcasts ...<-chan struct{}) bool {
  189. if connectivityChecker == nil || 1 == connectivityChecker.HasNetworkConnectivity() {
  190. return true
  191. }
  192. NoticeInfo("waiting for network connectivity")
  193. ticker := time.NewTicker(1 * time.Second)
  194. for {
  195. if 1 == connectivityChecker.HasNetworkConnectivity() {
  196. return true
  197. }
  198. selectCases := make([]reflect.SelectCase, 1+len(stopBroadcasts))
  199. selectCases[0] = reflect.SelectCase{
  200. Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ticker.C)}
  201. for i, stopBroadcast := range stopBroadcasts {
  202. selectCases[i+1] = reflect.SelectCase{
  203. Dir: reflect.SelectRecv, Chan: reflect.ValueOf(stopBroadcast)}
  204. }
  205. chosen, _, ok := reflect.Select(selectCases)
  206. if chosen == 0 && ok {
  207. // Ticker case, so check again
  208. } else {
  209. // Stop case
  210. return false
  211. }
  212. }
  213. }
  214. // ResolveIP uses a custom dns stack to make a DNS query over the
  215. // given TCP or UDP conn. This is used, e.g., when we need to ensure
  216. // that a DNS connection bypasses a VPN interface (BindToDevice) or
  217. // when we need to ensure that a DNS connection is tunneled.
  218. // Caller must set timeouts or interruptibility as required for conn.
  219. func ResolveIP(host string, conn net.Conn) (addrs []net.IP, ttls []time.Duration, err error) {
  220. // Send the DNS query
  221. dnsConn := &dns.Conn{Conn: conn}
  222. defer dnsConn.Close()
  223. query := new(dns.Msg)
  224. query.SetQuestion(dns.Fqdn(host), dns.TypeA)
  225. query.RecursionDesired = true
  226. dnsConn.WriteMsg(query)
  227. // Process the response
  228. response, err := dnsConn.ReadMsg()
  229. if err != nil {
  230. return nil, nil, ContextError(err)
  231. }
  232. addrs = make([]net.IP, 0)
  233. ttls = make([]time.Duration, 0)
  234. for _, answer := range response.Answer {
  235. if a, ok := answer.(*dns.A); ok {
  236. addrs = append(addrs, a.A)
  237. ttl := time.Duration(a.Hdr.Ttl) * time.Second
  238. ttls = append(ttls, ttl)
  239. }
  240. }
  241. return addrs, ttls, nil
  242. }
  243. // MakeUntunneledHttpsClient returns a net/http.Client which is
  244. // configured to use custom dialing features -- including BindToDevice,
  245. // UseIndistinguishableTLS, etc. -- for a specific HTTPS request URL.
  246. // If verifyLegacyCertificate is not nil, it's used for certificate
  247. // verification.
  248. // Because UseIndistinguishableTLS requires a hack to work with
  249. // net/http, MakeUntunneledHttpClient may return a modified request URL
  250. // to be used. Callers should always use this return value to make
  251. // requests, not the input value.
  252. func MakeUntunneledHttpsClient(
  253. dialConfig *DialConfig,
  254. verifyLegacyCertificate *x509.Certificate,
  255. requestUrl string,
  256. requestTimeout time.Duration) (*http.Client, string, error) {
  257. // Change the scheme to "http"; otherwise http.Transport will try to do
  258. // another TLS handshake inside the explicit TLS session. Also need to
  259. // force an explicit port, as the default for "http", 80, won't talk TLS.
  260. urlComponents, err := url.Parse(requestUrl)
  261. if err != nil {
  262. return nil, "", ContextError(err)
  263. }
  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. // Note: IndistinguishableTLS mode doesn't support VerifyLegacyCertificate
  276. useIndistinguishableTLS := dialConfig.UseIndistinguishableTLS && verifyLegacyCertificate == nil
  277. dialer := NewCustomTLSDialer(
  278. // Note: when verifyLegacyCertificate is not nil, some
  279. // of the other CustomTLSConfig is overridden.
  280. &CustomTLSConfig{
  281. Dial: NewTCPDialer(dialConfig),
  282. VerifyLegacyCertificate: verifyLegacyCertificate,
  283. SNIServerName: host,
  284. SkipVerify: false,
  285. UseIndistinguishableTLS: useIndistinguishableTLS,
  286. TrustedCACertificatesFilename: dialConfig.TrustedCACertificatesFilename,
  287. })
  288. transport := &http.Transport{
  289. Dial: dialer,
  290. }
  291. httpClient := &http.Client{
  292. Timeout: requestTimeout,
  293. Transport: transport,
  294. }
  295. return httpClient, urlComponents.String(), nil
  296. }
  297. // MakeTunneledHttpClient returns a net/http.Client which is
  298. // configured to use custom dialing features including tunneled
  299. // dialing and, optionally, UseTrustedCACertificatesForStockTLS.
  300. // Unlike MakeUntunneledHttpsClient and makePsiphonHttpsClient,
  301. // This http.Client uses stock TLS and no scheme transformation
  302. // hack is required.
  303. func MakeTunneledHttpClient(
  304. config *Config,
  305. tunnel *Tunnel,
  306. requestTimeout time.Duration) (*http.Client, error) {
  307. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  308. return tunnel.sshClient.Dial("tcp", addr)
  309. }
  310. transport := &http.Transport{
  311. Dial: tunneledDialer,
  312. ResponseHeaderTimeout: requestTimeout,
  313. }
  314. if config.UseTrustedCACertificatesForStockTLS {
  315. if config.TrustedCACertificatesFilename == "" {
  316. return nil, ContextError(errors.New(
  317. "UseTrustedCACertificatesForStockTLS requires TrustedCACertificatesFilename"))
  318. }
  319. rootCAs := x509.NewCertPool()
  320. certData, err := ioutil.ReadFile(config.TrustedCACertificatesFilename)
  321. if err != nil {
  322. return nil, ContextError(err)
  323. }
  324. rootCAs.AppendCertsFromPEM(certData)
  325. transport.TLSClientConfig = &tls.Config{RootCAs: rootCAs}
  326. }
  327. return &http.Client{
  328. Transport: transport,
  329. Timeout: requestTimeout,
  330. }, nil
  331. }