net.go 9.6 KB

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