net.go 11 KB

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