net.go 12 KB

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