tlsDialer.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. /*
  2. * Copyright (c) 2014, 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/tls"
  67. "crypto/x509"
  68. "errors"
  69. "net"
  70. "time"
  71. )
  72. // CustomTLSConfig contains parameters to determine the behavior
  73. // of CustomTLSDial.
  74. type CustomTLSConfig struct {
  75. // Dial is the network connection dialer. TLS is layered on
  76. // top of a new network connection created with dialer.
  77. Dial Dialer
  78. // Timeout is and optional timeout for combined network
  79. // connection dial and TLS handshake.
  80. Timeout time.Duration
  81. // FrontingAddr overrides the "addr" input to Dial when specified
  82. FrontingAddr string
  83. // SendServerName specifies whether to use SNI
  84. // (tlsdialer functionality)
  85. SendServerName bool
  86. // SkipVerify completely disables server certificate verification.
  87. SkipVerify bool
  88. // VerifyLegacyCertificate is a special case self-signed server
  89. // certificate case. Ignores IP SANs and basic constraints. No
  90. // certificate chain. Just checks that the server presented the
  91. // specified certificate.
  92. VerifyLegacyCertificate *x509.Certificate
  93. // TlsConfig is a tls.Config to use in the
  94. // non-verifyLegacyCertificate case.
  95. TlsConfig *tls.Config
  96. }
  97. func NewCustomTLSDialer(config *CustomTLSConfig) Dialer {
  98. return func(network, addr string) (net.Conn, error) {
  99. return CustomTLSDial(network, addr, config)
  100. }
  101. }
  102. // CustomTLSDialWithDialer is a customized replacement for tls.Dial.
  103. // Based on tlsdialer.DialWithDialer which is based on crypto/tls.DialWithDialer.
  104. //
  105. // tlsdialer comment:
  106. // Note - if sendServerName is false, the VerifiedChains field on the
  107. // connection's ConnectionState will never get populated.
  108. func CustomTLSDial(network, addr string, config *CustomTLSConfig) (*tls.Conn, error) {
  109. // We want the Timeout and Deadline values from dialer to cover the
  110. // whole process: TCP connection and TLS handshake. This means that we
  111. // also need to start our own timers now.
  112. var errChannel chan error
  113. if config.Timeout != 0 {
  114. errChannel = make(chan error, 2)
  115. time.AfterFunc(config.Timeout, func() {
  116. errChannel <- TimeoutError{}
  117. })
  118. }
  119. dialAddr := addr
  120. if config.FrontingAddr != "" {
  121. dialAddr = config.FrontingAddr
  122. }
  123. rawConn, err := config.Dial(network, dialAddr)
  124. if err != nil {
  125. return nil, ContextError(err)
  126. }
  127. hostname, _, err := net.SplitHostPort(dialAddr)
  128. if err != nil {
  129. return nil, ContextError(err)
  130. }
  131. tlsConfig := config.TlsConfig
  132. if tlsConfig == nil {
  133. tlsConfig = &tls.Config{}
  134. }
  135. // Copy config so we can tweak it
  136. tlsConfigCopy := new(tls.Config)
  137. *tlsConfigCopy = *tlsConfig
  138. serverName := tlsConfig.ServerName
  139. // If no ServerName is set, infer the ServerName
  140. // from the hostname we're connecting to.
  141. if serverName == "" {
  142. serverName = hostname
  143. }
  144. if config.SendServerName {
  145. // Set the ServerName and rely on the usual logic in
  146. // tls.Conn.Handshake() to do its verification
  147. tlsConfigCopy.ServerName = serverName
  148. } else {
  149. // Disable verification in tls.Conn.Handshake(). We'll verify manually
  150. // after handshaking
  151. tlsConfigCopy.InsecureSkipVerify = true
  152. }
  153. conn := tls.Client(rawConn, tlsConfigCopy)
  154. if config.Timeout == 0 {
  155. err = conn.Handshake()
  156. } else {
  157. go func() {
  158. errChannel <- conn.Handshake()
  159. }()
  160. err = <-errChannel
  161. }
  162. if !config.SkipVerify {
  163. if err == nil && config.VerifyLegacyCertificate != nil {
  164. err = verifyLegacyCertificate(conn, config.VerifyLegacyCertificate)
  165. } else if err == nil && !config.SendServerName && !tlsConfig.InsecureSkipVerify {
  166. // Manually verify certificates
  167. err = verifyServerCerts(conn, serverName, tlsConfigCopy)
  168. }
  169. }
  170. if err != nil {
  171. rawConn.Close()
  172. return nil, ContextError(err)
  173. }
  174. return conn, nil
  175. }
  176. func verifyLegacyCertificate(conn *tls.Conn, expectedCertificate *x509.Certificate) error {
  177. certs := conn.ConnectionState().PeerCertificates
  178. if len(certs) < 1 {
  179. return ContextError(errors.New("no certificate to verify"))
  180. }
  181. if !bytes.Equal(certs[0].Raw, expectedCertificate.Raw) {
  182. return ContextError(errors.New("unexpected certificate"))
  183. }
  184. return nil
  185. }
  186. func verifyServerCerts(conn *tls.Conn, serverName string, config *tls.Config) error {
  187. certs := conn.ConnectionState().PeerCertificates
  188. opts := x509.VerifyOptions{
  189. Roots: config.RootCAs,
  190. CurrentTime: time.Now(),
  191. DNSName: serverName,
  192. Intermediates: x509.NewCertPool(),
  193. }
  194. for i, cert := range certs {
  195. if i == 0 {
  196. continue
  197. }
  198. opts.Intermediates.AddCert(cert)
  199. }
  200. _, err := certs[0].Verify(opts)
  201. if err != nil {
  202. return ContextError(err)
  203. }
  204. return nil
  205. }