tlsDialer.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. "context"
  67. "crypto/x509"
  68. "encoding/hex"
  69. "errors"
  70. "net"
  71. "time"
  72. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  73. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tls"
  74. )
  75. const (
  76. TLSProfileAndroid = "Android"
  77. TLSProfileChrome = "Chrome"
  78. )
  79. // CustomTLSConfig contains parameters to determine the behavior
  80. // of CustomTLSDial.
  81. type CustomTLSConfig struct {
  82. // Dial is the network connection dialer. TLS is layered on
  83. // top of a new network connection created with dialer.
  84. Dial Dialer
  85. // DialAddr overrides the "addr" input to Dial when specified
  86. DialAddr string
  87. // UseDialAddrSNI specifies whether to always use the dial "addr"
  88. // host name in the SNI server_name field. When DialAddr is set,
  89. // its host name is used.
  90. UseDialAddrSNI bool
  91. // SNIServerName specifies the value to set in the SNI
  92. // server_name field. When blank, SNI is omitted. Note that
  93. // underlying TLS code also automatically omits SNI when
  94. // the server_name is an IP address.
  95. // SNIServerName is ignored when UseDialAddrSNI is true.
  96. SNIServerName string
  97. // SkipVerify completely disables server certificate verification.
  98. SkipVerify bool
  99. // VerifyLegacyCertificate is a special case self-signed server
  100. // certificate case. Ignores IP SANs and basic constraints. No
  101. // certificate chain. Just checks that the server presented the
  102. // specified certificate. SNI is disbled when this is set.
  103. VerifyLegacyCertificate *x509.Certificate
  104. // UseIndistinguishableTLS specifies whether to try to use an
  105. // alternative profile for TLS dials. From a circumvention perspective,
  106. // Go's TLS has a distinct fingerprint that may be used for blocking.
  107. UseIndistinguishableTLS bool
  108. // TLSProfile specifies a particular indistinguishable TLS profile
  109. // to use for the TLS dial. UseIndistinguishableTLS must be set for
  110. // TLSProfile to take effect.
  111. // When TLSProfile is "" and UseIndistinguishableTLS is set, a profile
  112. // is selected at random. Setting TLSProfile allows the caller to pin
  113. // the selection so all TLS connections in a certain context (e.g. a
  114. // single meek connection) use a consistent value.
  115. // Valid values include "Android" and "Chrome". The value should be
  116. // selected by calling SelectTLSProfile, which will pick a value at
  117. // random, but subject to compatibility constraints.
  118. TLSProfile string
  119. // TrustedCACertificatesFilename specifies a file containing trusted
  120. // CA certs. Directory contents should be compatible with OpenSSL's
  121. // SSL_CTX_load_verify_locations
  122. // Only applies to UseIndistinguishableTLS connections.
  123. TrustedCACertificatesFilename string
  124. // ObfuscatedSessionTicketKey enables obfuscated session tickets
  125. // using the specified key.
  126. ObfuscatedSessionTicketKey string
  127. }
  128. func SelectTLSProfile(
  129. useIndistinguishableTLS, useObfuscatedSessionTickets,
  130. skipVerify, haveTrustedCACertificates bool) string {
  131. selectedTLSProfile := ""
  132. if useIndistinguishableTLS {
  133. // OpenSSL cannot be used in all cases
  134. canUseOpenSSL := openSSLSupported() &&
  135. !useObfuscatedSessionTickets &&
  136. // TODO: (... || config.VerifyLegacyCertificate != nil)
  137. (skipVerify || haveTrustedCACertificates)
  138. if canUseOpenSSL && common.FlipCoin() {
  139. selectedTLSProfile = TLSProfileAndroid
  140. } else {
  141. selectedTLSProfile = TLSProfileChrome
  142. }
  143. }
  144. return selectedTLSProfile
  145. }
  146. func NewCustomTLSDialer(config *CustomTLSConfig) Dialer {
  147. return func(ctx context.Context, network, addr string) (net.Conn, error) {
  148. return CustomTLSDial(ctx, network, addr, config)
  149. }
  150. }
  151. // handshakeConn is a net.Conn that can perform a TLS handshake
  152. type handshakeConn interface {
  153. net.Conn
  154. Handshake() error
  155. }
  156. // CustomTLSDialWithDialer is a customized replacement for tls.Dial.
  157. // Based on tlsdialer.DialWithDialer which is based on crypto/tls.DialWithDialer.
  158. //
  159. // tlsdialer comment:
  160. // Note - if sendServerName is false, the VerifiedChains field on the
  161. // connection's ConnectionState will never get populated.
  162. func CustomTLSDial(
  163. ctx context.Context,
  164. network, addr string,
  165. config *CustomTLSConfig) (net.Conn, error) {
  166. dialAddr := addr
  167. if config.DialAddr != "" {
  168. dialAddr = config.DialAddr
  169. }
  170. rawConn, err := config.Dial(ctx, network, dialAddr)
  171. if err != nil {
  172. return nil, common.ContextError(err)
  173. }
  174. hostname, _, err := net.SplitHostPort(dialAddr)
  175. if err != nil {
  176. rawConn.Close()
  177. return nil, common.ContextError(err)
  178. }
  179. tlsConfig := &tls.Config{}
  180. // Select indistinguishable TLS implementation
  181. useOpenSSL := false
  182. if config.UseIndistinguishableTLS {
  183. selectedTLSProfile := config.TLSProfile
  184. if selectedTLSProfile == "" {
  185. selectedTLSProfile = SelectTLSProfile(
  186. true,
  187. config.ObfuscatedSessionTicketKey != "",
  188. config.SkipVerify,
  189. config.TrustedCACertificatesFilename != "")
  190. }
  191. switch selectedTLSProfile {
  192. case TLSProfileAndroid:
  193. // Validate selection; if config.TLSProfile was preset, it should
  194. // have been selected using SelectTLSProfile.
  195. if !openSSLSupported() ||
  196. config.ObfuscatedSessionTicketKey != "" ||
  197. // TODO: (... || config.VerifyLegacyCertificate != nil)
  198. !(config.SkipVerify || config.TrustedCACertificatesFilename != "") {
  199. return nil, common.ContextError(errors.New("TLSProfileAndroid not supported"))
  200. }
  201. useOpenSSL = true
  202. case TLSProfileChrome:
  203. tlsConfig.EmulateChrome = true
  204. tlsConfig.ClientSessionCache = tls.NewLRUClientSessionCache(0)
  205. }
  206. }
  207. if config.SkipVerify {
  208. tlsConfig.InsecureSkipVerify = true
  209. }
  210. if config.UseDialAddrSNI {
  211. tlsConfig.ServerName = hostname
  212. } else if config.SNIServerName != "" && config.VerifyLegacyCertificate == nil {
  213. // Set the ServerName and rely on the usual logic in
  214. // tls.Conn.Handshake() to do its verification.
  215. // Note: Go TLS will automatically omit this ServerName when it's an IP address
  216. tlsConfig.ServerName = config.SNIServerName
  217. } else {
  218. // No SNI.
  219. // Disable verification in tls.Conn.Handshake(). We'll verify manually
  220. // after handshaking
  221. tlsConfig.InsecureSkipVerify = true
  222. }
  223. if config.ObfuscatedSessionTicketKey != "" {
  224. // See obfuscated session ticket overview
  225. // in tls.NewObfuscatedClientSessionCache
  226. var obfuscatedSessionTicketKey [32]byte
  227. key, err := hex.DecodeString(config.ObfuscatedSessionTicketKey)
  228. if err == nil && len(key) != 32 {
  229. err = errors.New("invalid obfuscated session key length")
  230. }
  231. if err != nil {
  232. return nil, common.ContextError(err)
  233. }
  234. copy(obfuscatedSessionTicketKey[:], key)
  235. tlsConfig.ClientSessionCache = tls.NewObfuscatedClientSessionCache(
  236. obfuscatedSessionTicketKey)
  237. }
  238. var conn handshakeConn
  239. // When supported, use OpenSSL TLS as a more indistinguishable TLS.
  240. if useOpenSSL {
  241. conn, err = newOpenSSLConn(rawConn, hostname, config)
  242. if err != nil {
  243. rawConn.Close()
  244. return nil, common.ContextError(err)
  245. }
  246. } else {
  247. conn = tls.Client(rawConn, tlsConfig)
  248. }
  249. resultChannel := make(chan error)
  250. go func() {
  251. resultChannel <- conn.Handshake()
  252. }()
  253. select {
  254. case err = <-resultChannel:
  255. case <-ctx.Done():
  256. err = ctx.Err()
  257. // Interrupt the goroutine
  258. rawConn.Close()
  259. <-resultChannel
  260. }
  261. // openSSLConns complete verification automatically. For Go TLS,
  262. // we need to complete the process from crypto/tls.Dial.
  263. // NOTE: for (config.SendServerName && !config.tlsConfig.InsecureSkipVerify),
  264. // the tls.Conn.Handshake() does the complete verification, including host name.
  265. tlsConn, isTlsConn := conn.(*tls.Conn)
  266. if err == nil && isTlsConn &&
  267. !config.SkipVerify && tlsConfig.InsecureSkipVerify {
  268. if config.VerifyLegacyCertificate != nil {
  269. err = verifyLegacyCertificate(tlsConn, config.VerifyLegacyCertificate)
  270. } else {
  271. // Manually verify certificates
  272. err = verifyServerCerts(tlsConn, hostname, tlsConfig)
  273. }
  274. }
  275. if err != nil {
  276. rawConn.Close()
  277. return nil, common.ContextError(err)
  278. }
  279. return conn, nil
  280. }
  281. func verifyLegacyCertificate(conn *tls.Conn, expectedCertificate *x509.Certificate) error {
  282. certs := conn.ConnectionState().PeerCertificates
  283. if len(certs) < 1 {
  284. return common.ContextError(errors.New("no certificate to verify"))
  285. }
  286. if !bytes.Equal(certs[0].Raw, expectedCertificate.Raw) {
  287. return common.ContextError(errors.New("unexpected certificate"))
  288. }
  289. return nil
  290. }
  291. func verifyServerCerts(conn *tls.Conn, hostname string, config *tls.Config) error {
  292. certs := conn.ConnectionState().PeerCertificates
  293. opts := x509.VerifyOptions{
  294. Roots: config.RootCAs,
  295. CurrentTime: time.Now(),
  296. DNSName: hostname,
  297. Intermediates: x509.NewCertPool(),
  298. }
  299. for i, cert := range certs {
  300. if i == 0 {
  301. continue
  302. }
  303. opts.Intermediates.AddCert(cert)
  304. }
  305. _, err := certs[0].Verify(opts)
  306. if err != nil {
  307. return common.ContextError(err)
  308. }
  309. return nil
  310. }