tlsDialer.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. /*
  20. Copyright (c) 2012 The Go Authors. All rights reserved.
  21. Redistribution and use in source and binary forms, with or without
  22. modification, are permitted provided that the following conditions are
  23. met:
  24. * Redistributions of source code must retain the above copyright
  25. notice, this list of conditions and the following disclaimer.
  26. * Redistributions in binary form must reproduce the above
  27. copyright notice, this list of conditions and the following disclaimer
  28. in the documentation and/or other materials provided with the
  29. distribution.
  30. * Neither the name of Google Inc. nor the names of its
  31. contributors may be used to endorse or promote products derived from
  32. this software without specific prior written permission.
  33. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  34. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  35. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  36. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  37. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  38. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  39. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  40. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  41. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  42. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  43. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. // Fork of https://github.com/getlantern/tlsdialer (http://gopkg.in/getlantern/tlsdialer.v1)
  46. // which itself is a "Fork of crypto/tls.Dial and DialWithDialer"
  47. // Adds two capabilities to tlsdialer:
  48. //
  49. // 1. HTTP proxy support, so the dialer may be used with http.Transport.
  50. //
  51. // 2. Support for self-signed Psiphon server certificates, which Go's certificate
  52. // verification rejects due to two short comings:
  53. // - lack of IP address SANs.
  54. // see: "...because it doesn't contain any IP SANs" case in crypto/x509/verify.go
  55. // - non-compliant constraint configuration (RFC 5280, 4.2.1.9).
  56. // see: CheckSignatureFrom() in crypto/x509/x509.go
  57. // Since the client has to be able to handle existing Psiphon server certificates,
  58. // we need to be able to perform some form of verification in these cases.
  59. // tlsdialer:
  60. // package tlsdialer contains a customized version of crypto/tls.Dial that
  61. // allows control over whether or not to send the ServerName extension in the
  62. // client handshake.
  63. package psiphon
  64. import (
  65. "bytes"
  66. "crypto/x509"
  67. "encoding/hex"
  68. "errors"
  69. "net"
  70. "time"
  71. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  72. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tls"
  73. )
  74. const (
  75. TLSProfileAndroid = "Android"
  76. TLSProfileChrome = "Chrome"
  77. )
  78. // CustomTLSConfig contains parameters to determine the behavior
  79. // of CustomTLSDial.
  80. type CustomTLSConfig struct {
  81. // Dial is the network connection dialer. TLS is layered on
  82. // top of a new network connection created with dialer.
  83. Dial Dialer
  84. // Timeout is and optional timeout for combined network
  85. // connection dial and TLS handshake.
  86. Timeout time.Duration
  87. // DialAddr overrides the "addr" input to Dial when specified
  88. DialAddr string
  89. // SNIServerName specifies the value to set in the SNI
  90. // server_name field. When blank, SNI is omitted. Note that
  91. // underlying TLS code also automatically omits SNI when
  92. // the server_name is an IP address.
  93. SNIServerName string
  94. // SkipVerify completely disables server certificate verification.
  95. SkipVerify bool
  96. // VerifyLegacyCertificate is a special case self-signed server
  97. // certificate case. Ignores IP SANs and basic constraints. No
  98. // certificate chain. Just checks that the server presented the
  99. // specified certificate. SNI is disbled when this is set.
  100. VerifyLegacyCertificate *x509.Certificate
  101. // UseIndistinguishableTLS specifies whether to try to use an
  102. // alternative stack for TLS. From a circumvention perspective,
  103. // Go's TLS has a distinct fingerprint that may be used for blocking.
  104. UseIndistinguishableTLS bool
  105. // TLSProfile specifies a particular indistinguishable TLS profile
  106. // to use for the TLS dial. UseIndistinguishableTLS must be set for
  107. // TLSProfile to take effect.
  108. // When TLSProfile is "" and UseIndistinguishableTLS is set, a profile
  109. // is selected at random. Setting TLSProfile allows the caller to pin
  110. // the selection so all TLS connections in a certain context (e.g. a
  111. // single meek connection) use a consistent value.
  112. // Valid values include "Android" and "Chrome". The value should be
  113. // selected by calling SelectTLSProfile, which will pick a value at
  114. // random, but subject to compatibility constraints.
  115. TLSProfile string
  116. // TrustedCACertificatesFilename specifies a file containing trusted
  117. // CA certs. Directory contents should be compatible with OpenSSL's
  118. // SSL_CTX_load_verify_locations
  119. // Only applies to UseIndistinguishableTLS connections.
  120. TrustedCACertificatesFilename string
  121. // ObfuscatedSessionTicketKey enables obfuscated session tickets
  122. // using the specified key.
  123. ObfuscatedSessionTicketKey string
  124. }
  125. func SelectTLSProfile(
  126. useIndistinguishableTLS, useObfuscatedSessionTickets,
  127. skipVerify, haveTrustedCACertificates bool) string {
  128. selectedTLSProfile := ""
  129. if useIndistinguishableTLS {
  130. // OpenSSL cannot be used in all cases
  131. canUseOpenSSL := openSSLSupported() &&
  132. !useObfuscatedSessionTickets &&
  133. // TODO: (... || config.VerifyLegacyCertificate != nil)
  134. (skipVerify || haveTrustedCACertificates)
  135. if canUseOpenSSL && common.FlipCoin() {
  136. selectedTLSProfile = TLSProfileAndroid
  137. } else {
  138. selectedTLSProfile = TLSProfileChrome
  139. }
  140. }
  141. return selectedTLSProfile
  142. }
  143. func NewCustomTLSDialer(config *CustomTLSConfig) Dialer {
  144. return func(network, addr string) (net.Conn, error) {
  145. return CustomTLSDial(network, addr, config)
  146. }
  147. }
  148. // handshakeConn is a net.Conn that can perform a TLS handshake
  149. type handshakeConn interface {
  150. net.Conn
  151. Handshake() error
  152. }
  153. // CustomTLSDialWithDialer is a customized replacement for tls.Dial.
  154. // Based on tlsdialer.DialWithDialer which is based on crypto/tls.DialWithDialer.
  155. //
  156. // tlsdialer comment:
  157. // Note - if sendServerName is false, the VerifiedChains field on the
  158. // connection's ConnectionState will never get populated.
  159. func CustomTLSDial(network, addr string, config *CustomTLSConfig) (net.Conn, error) {
  160. // We want the Timeout and Deadline values from dialer to cover the
  161. // whole process: TCP connection and TLS handshake. This means that we
  162. // also need to start our own timers now.
  163. var errChannel chan error
  164. if config.Timeout != 0 {
  165. errChannel = make(chan error, 2)
  166. time.AfterFunc(config.Timeout, func() {
  167. errChannel <- errors.New("timed out")
  168. })
  169. }
  170. dialAddr := addr
  171. if config.DialAddr != "" {
  172. dialAddr = config.DialAddr
  173. }
  174. rawConn, err := config.Dial(network, dialAddr)
  175. if err != nil {
  176. return nil, common.ContextError(err)
  177. }
  178. hostname, _, err := net.SplitHostPort(dialAddr)
  179. if err != nil {
  180. rawConn.Close()
  181. return nil, common.ContextError(err)
  182. }
  183. tlsConfig := &tls.Config{}
  184. // Select indistinguishable TLS implementation
  185. useOpenSSL := false
  186. if config.UseIndistinguishableTLS {
  187. selectedTLSProfile := config.TLSProfile
  188. if selectedTLSProfile == "" {
  189. selectedTLSProfile = SelectTLSProfile(
  190. true,
  191. config.ObfuscatedSessionTicketKey != "",
  192. config.SkipVerify,
  193. config.TrustedCACertificatesFilename != "")
  194. }
  195. switch selectedTLSProfile {
  196. case TLSProfileAndroid:
  197. // Validate selection; if config.TLSProfile was preset, it should
  198. // have been selected using SelectTLSProfile.
  199. if !openSSLSupported() ||
  200. config.ObfuscatedSessionTicketKey != "" ||
  201. // TODO: (... || config.VerifyLegacyCertificate != nil)
  202. !(config.SkipVerify || config.TrustedCACertificatesFilename != "") {
  203. return nil, common.ContextError(errors.New("TLSProfileAndroid not supported"))
  204. }
  205. useOpenSSL = true
  206. case TLSProfileChrome:
  207. tlsConfig.EmulateChrome = true
  208. tlsConfig.ClientSessionCache = tls.NewLRUClientSessionCache(0)
  209. }
  210. }
  211. if config.SkipVerify {
  212. tlsConfig.InsecureSkipVerify = true
  213. }
  214. if config.SNIServerName != "" && config.VerifyLegacyCertificate == nil {
  215. // Set the ServerName and rely on the usual logic in
  216. // tls.Conn.Handshake() to do its verification.
  217. // Note: Go TLS will automatically omit this ServerName when it's an IP address
  218. tlsConfig.ServerName = config.SNIServerName
  219. } else {
  220. // No SNI.
  221. // Disable verification in tls.Conn.Handshake(). We'll verify manually
  222. // after handshaking
  223. tlsConfig.InsecureSkipVerify = true
  224. }
  225. if config.ObfuscatedSessionTicketKey != "" {
  226. // See obfuscated session ticket overview
  227. // in tls.NewObfuscatedClientSessionCache
  228. var obfuscatedSessionTicketKey [32]byte
  229. key, err := hex.DecodeString(config.ObfuscatedSessionTicketKey)
  230. if err == nil && len(key) != 32 {
  231. err = errors.New("invalid obfuscated session key length")
  232. }
  233. if err != nil {
  234. return nil, common.ContextError(err)
  235. }
  236. copy(obfuscatedSessionTicketKey[:], key)
  237. tlsConfig.ClientSessionCache = tls.NewObfuscatedClientSessionCache(
  238. obfuscatedSessionTicketKey)
  239. }
  240. var conn handshakeConn
  241. // When supported, use OpenSSL TLS as a more indistinguishable TLS.
  242. if useOpenSSL {
  243. conn, err = newOpenSSLConn(rawConn, hostname, config)
  244. if err != nil {
  245. rawConn.Close()
  246. return nil, common.ContextError(err)
  247. }
  248. } else {
  249. conn = tls.Client(rawConn, tlsConfig)
  250. }
  251. if config.Timeout == 0 {
  252. err = conn.Handshake()
  253. } else {
  254. go func() {
  255. errChannel <- conn.Handshake()
  256. }()
  257. err = <-errChannel
  258. }
  259. // openSSLConns complete verification automatically. For Go TLS,
  260. // we need to complete the process from crypto/tls.Dial.
  261. // NOTE: for (config.SendServerName && !config.tlsConfig.InsecureSkipVerify),
  262. // the tls.Conn.Handshake() does the complete verification, including host name.
  263. tlsConn, isTlsConn := conn.(*tls.Conn)
  264. if err == nil && isTlsConn &&
  265. !config.SkipVerify && tlsConfig.InsecureSkipVerify {
  266. if config.VerifyLegacyCertificate != nil {
  267. err = verifyLegacyCertificate(tlsConn, config.VerifyLegacyCertificate)
  268. } else {
  269. // Manually verify certificates
  270. err = verifyServerCerts(tlsConn, hostname, tlsConfig)
  271. }
  272. }
  273. if err != nil {
  274. rawConn.Close()
  275. return nil, common.ContextError(err)
  276. }
  277. return conn, nil
  278. }
  279. func verifyLegacyCertificate(conn *tls.Conn, expectedCertificate *x509.Certificate) error {
  280. certs := conn.ConnectionState().PeerCertificates
  281. if len(certs) < 1 {
  282. return common.ContextError(errors.New("no certificate to verify"))
  283. }
  284. if !bytes.Equal(certs[0].Raw, expectedCertificate.Raw) {
  285. return common.ContextError(errors.New("unexpected certificate"))
  286. }
  287. return nil
  288. }
  289. func verifyServerCerts(conn *tls.Conn, hostname string, config *tls.Config) error {
  290. certs := conn.ConnectionState().PeerCertificates
  291. opts := x509.VerifyOptions{
  292. Roots: config.RootCAs,
  293. CurrentTime: time.Now(),
  294. DNSName: hostname,
  295. Intermediates: x509.NewCertPool(),
  296. }
  297. for i, cert := range certs {
  298. if i == 0 {
  299. continue
  300. }
  301. opts.Intermediates.AddCert(cert)
  302. }
  303. _, err := certs[0].Verify(opts)
  304. if err != nil {
  305. return common.ContextError(err)
  306. }
  307. return nil
  308. }