tls.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package tls partially implements TLS 1.2, as specified in RFC 5246,
  5. // and TLS 1.3, as specified in RFC 8446.
  6. package tls
  7. // BUG(agl): The crypto/tls package only implements some countermeasures
  8. // against Lucky13 attacks on CBC-mode encryption, and only on SHA1
  9. // variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and
  10. // https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
  11. import (
  12. "bytes"
  13. "context"
  14. "crypto"
  15. "crypto/ecdsa"
  16. "crypto/ed25519"
  17. "crypto/rsa"
  18. "crypto/x509"
  19. "encoding/pem"
  20. "errors"
  21. "fmt"
  22. // [Psiphon]
  23. // "internal/godebug"
  24. "net"
  25. "os"
  26. "strings"
  27. )
  28. // Server returns a new TLS server side connection
  29. // using conn as the underlying transport.
  30. // The configuration config must be non-nil and must include
  31. // at least one certificate or else set GetCertificate.
  32. func Server(conn net.Conn, config *Config) *Conn {
  33. // [Psiphon]
  34. // Initialize traffic recording to facilitate playback in the case of
  35. // passthrough.
  36. if config.PassthroughAddress != "" {
  37. conn = newRecorderConn(conn)
  38. }
  39. c := &Conn{
  40. conn: conn,
  41. config: config,
  42. }
  43. c.handshakeFn = c.serverHandshake
  44. return c
  45. }
  46. // Client returns a new TLS client side connection
  47. // using conn as the underlying transport.
  48. // The config cannot be nil: users must set either ServerName or
  49. // InsecureSkipVerify in the config.
  50. func Client(conn net.Conn, config *Config) *Conn {
  51. c := &Conn{
  52. conn: conn,
  53. config: config,
  54. isClient: true,
  55. }
  56. c.handshakeFn = c.clientHandshake
  57. return c
  58. }
  59. // A listener implements a network listener (net.Listener) for TLS connections.
  60. type listener struct {
  61. net.Listener
  62. config *Config
  63. }
  64. // Accept waits for and returns the next incoming TLS connection.
  65. // The returned connection is of type *Conn.
  66. func (l *listener) Accept() (net.Conn, error) {
  67. c, err := l.Listener.Accept()
  68. if err != nil {
  69. return nil, err
  70. }
  71. return Server(c, l.config), nil
  72. }
  73. // NewListener creates a Listener which accepts connections from an inner
  74. // Listener and wraps each connection with [Server].
  75. // The configuration config must be non-nil and must include
  76. // at least one certificate or else set GetCertificate.
  77. func NewListener(inner net.Listener, config *Config) net.Listener {
  78. l := new(listener)
  79. l.Listener = inner
  80. l.config = config
  81. return l
  82. }
  83. // Listen creates a TLS listener accepting connections on the
  84. // given network address using net.Listen.
  85. // The configuration config must be non-nil and must include
  86. // at least one certificate or else set GetCertificate.
  87. func Listen(network, laddr string, config *Config) (net.Listener, error) {
  88. // If this condition changes, consider updating http.Server.ServeTLS too.
  89. if config == nil || len(config.Certificates) == 0 &&
  90. config.GetCertificate == nil && config.GetConfigForClient == nil {
  91. return nil, errors.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config")
  92. }
  93. l, err := net.Listen(network, laddr)
  94. if err != nil {
  95. return nil, err
  96. }
  97. return NewListener(l, config), nil
  98. }
  99. type timeoutError struct{}
  100. func (timeoutError) Error() string { return "tls: DialWithDialer timed out" }
  101. func (timeoutError) Timeout() bool { return true }
  102. func (timeoutError) Temporary() bool { return true }
  103. // DialWithDialer connects to the given network address using dialer.Dial and
  104. // then initiates a TLS handshake, returning the resulting TLS connection. Any
  105. // timeout or deadline given in the dialer apply to connection and TLS
  106. // handshake as a whole.
  107. //
  108. // DialWithDialer interprets a nil configuration as equivalent to the zero
  109. // configuration; see the documentation of [Config] for the defaults.
  110. //
  111. // DialWithDialer uses context.Background internally; to specify the context,
  112. // use [Dialer.DialContext] with NetDialer set to the desired dialer.
  113. func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
  114. return dial(context.Background(), dialer, network, addr, config)
  115. }
  116. func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
  117. if netDialer.Timeout != 0 {
  118. var cancel context.CancelFunc
  119. ctx, cancel = context.WithTimeout(ctx, netDialer.Timeout)
  120. defer cancel()
  121. }
  122. if !netDialer.Deadline.IsZero() {
  123. var cancel context.CancelFunc
  124. ctx, cancel = context.WithDeadline(ctx, netDialer.Deadline)
  125. defer cancel()
  126. }
  127. rawConn, err := netDialer.DialContext(ctx, network, addr)
  128. if err != nil {
  129. return nil, err
  130. }
  131. colonPos := strings.LastIndex(addr, ":")
  132. if colonPos == -1 {
  133. colonPos = len(addr)
  134. }
  135. hostname := addr[:colonPos]
  136. if config == nil {
  137. config = defaultConfig()
  138. }
  139. // If no ServerName is set, infer the ServerName
  140. // from the hostname we're connecting to.
  141. if config.ServerName == "" {
  142. // Make a copy to avoid polluting argument or default.
  143. c := config.Clone()
  144. c.ServerName = hostname
  145. config = c
  146. }
  147. conn := Client(rawConn, config)
  148. if err := conn.HandshakeContext(ctx); err != nil {
  149. rawConn.Close()
  150. return nil, err
  151. }
  152. return conn, nil
  153. }
  154. // Dial connects to the given network address using net.Dial
  155. // and then initiates a TLS handshake, returning the resulting
  156. // TLS connection.
  157. // Dial interprets a nil configuration as equivalent to
  158. // the zero configuration; see the documentation of Config
  159. // for the defaults.
  160. func Dial(network, addr string, config *Config) (*Conn, error) {
  161. return DialWithDialer(new(net.Dialer), network, addr, config)
  162. }
  163. // Dialer dials TLS connections given a configuration and a Dialer for the
  164. // underlying connection.
  165. type Dialer struct {
  166. // NetDialer is the optional dialer to use for the TLS connections'
  167. // underlying TCP connections.
  168. // A nil NetDialer is equivalent to the net.Dialer zero value.
  169. NetDialer *net.Dialer
  170. // Config is the TLS configuration to use for new connections.
  171. // A nil configuration is equivalent to the zero
  172. // configuration; see the documentation of Config for the
  173. // defaults.
  174. Config *Config
  175. }
  176. // Dial connects to the given network address and initiates a TLS
  177. // handshake, returning the resulting TLS connection.
  178. //
  179. // The returned [Conn], if any, will always be of type *[Conn].
  180. //
  181. // Dial uses context.Background internally; to specify the context,
  182. // use [Dialer.DialContext].
  183. func (d *Dialer) Dial(network, addr string) (net.Conn, error) {
  184. return d.DialContext(context.Background(), network, addr)
  185. }
  186. func (d *Dialer) netDialer() *net.Dialer {
  187. if d.NetDialer != nil {
  188. return d.NetDialer
  189. }
  190. return new(net.Dialer)
  191. }
  192. // DialContext connects to the given network address and initiates a TLS
  193. // handshake, returning the resulting TLS connection.
  194. //
  195. // The provided Context must be non-nil. If the context expires before
  196. // the connection is complete, an error is returned. Once successfully
  197. // connected, any expiration of the context will not affect the
  198. // connection.
  199. //
  200. // The returned [Conn], if any, will always be of type *[Conn].
  201. func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
  202. c, err := dial(ctx, d.netDialer(), network, addr, d.Config)
  203. if err != nil {
  204. // Don't return c (a typed nil) in an interface.
  205. return nil, err
  206. }
  207. return c, nil
  208. }
  209. // LoadX509KeyPair reads and parses a public/private key pair from a pair of
  210. // files. The files must contain PEM encoded data. The certificate file may
  211. // contain intermediate certificates following the leaf certificate to form a
  212. // certificate chain. On successful return, Certificate.Leaf will be populated.
  213. //
  214. // Before Go 1.23 Certificate.Leaf was left nil, and the parsed certificate was
  215. // discarded. This behavior can be re-enabled by setting "x509keypairleaf=0"
  216. // in the GODEBUG environment variable.
  217. func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
  218. certPEMBlock, err := os.ReadFile(certFile)
  219. if err != nil {
  220. return Certificate{}, err
  221. }
  222. keyPEMBlock, err := os.ReadFile(keyFile)
  223. if err != nil {
  224. return Certificate{}, err
  225. }
  226. return X509KeyPair(certPEMBlock, keyPEMBlock)
  227. }
  228. // [Psiphon]
  229. // var x509keypairleaf = godebug.New("x509keypairleaf")
  230. // X509KeyPair parses a public/private key pair from a pair of
  231. // PEM encoded data. On successful return, Certificate.Leaf will be populated.
  232. //
  233. // Before Go 1.23 Certificate.Leaf was left nil, and the parsed certificate was
  234. // discarded. This behavior can be re-enabled by setting "x509keypairleaf=0"
  235. // in the GODEBUG environment variable.
  236. func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
  237. fail := func(err error) (Certificate, error) { return Certificate{}, err }
  238. var cert Certificate
  239. var skippedBlockTypes []string
  240. for {
  241. var certDERBlock *pem.Block
  242. certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
  243. if certDERBlock == nil {
  244. break
  245. }
  246. if certDERBlock.Type == "CERTIFICATE" {
  247. cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
  248. } else {
  249. skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
  250. }
  251. }
  252. if len(cert.Certificate) == 0 {
  253. if len(skippedBlockTypes) == 0 {
  254. return fail(errors.New("tls: failed to find any PEM data in certificate input"))
  255. }
  256. if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
  257. return fail(errors.New("tls: failed to find certificate PEM data in certificate input, but did find a private key; PEM inputs may have been switched"))
  258. }
  259. return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
  260. }
  261. skippedBlockTypes = skippedBlockTypes[:0]
  262. var keyDERBlock *pem.Block
  263. for {
  264. keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
  265. if keyDERBlock == nil {
  266. if len(skippedBlockTypes) == 0 {
  267. return fail(errors.New("tls: failed to find any PEM data in key input"))
  268. }
  269. if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
  270. return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
  271. }
  272. return fail(fmt.Errorf("tls: failed to find PEM block with type ending in \"PRIVATE KEY\" in key input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
  273. }
  274. if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
  275. break
  276. }
  277. skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
  278. }
  279. // We don't need to parse the public key for TLS, but we so do anyway
  280. // to check that it looks sane and matches the private key.
  281. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  282. if err != nil {
  283. return fail(err)
  284. }
  285. // [Psiphon] godebug is not supported, but we
  286. // populate Leaf in X509KeyPair by default.
  287. // if x509keypairleaf.Value() != "0" {
  288. cert.Leaf = x509Cert
  289. // } else {
  290. // x509keypairleaf.IncNonDefault()
  291. // }
  292. cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
  293. if err != nil {
  294. return fail(err)
  295. }
  296. switch pub := x509Cert.PublicKey.(type) {
  297. case *rsa.PublicKey:
  298. priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
  299. if !ok {
  300. return fail(errors.New("tls: private key type does not match public key type"))
  301. }
  302. if pub.N.Cmp(priv.N) != 0 {
  303. return fail(errors.New("tls: private key does not match public key"))
  304. }
  305. case *ecdsa.PublicKey:
  306. priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
  307. if !ok {
  308. return fail(errors.New("tls: private key type does not match public key type"))
  309. }
  310. if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
  311. return fail(errors.New("tls: private key does not match public key"))
  312. }
  313. case ed25519.PublicKey:
  314. priv, ok := cert.PrivateKey.(ed25519.PrivateKey)
  315. if !ok {
  316. return fail(errors.New("tls: private key type does not match public key type"))
  317. }
  318. if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) {
  319. return fail(errors.New("tls: private key does not match public key"))
  320. }
  321. default:
  322. return fail(errors.New("tls: unknown public key algorithm"))
  323. }
  324. return cert, nil
  325. }
  326. // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
  327. // PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys.
  328. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
  329. func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
  330. if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
  331. return key, nil
  332. }
  333. if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
  334. switch key := key.(type) {
  335. case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey:
  336. return key, nil
  337. default:
  338. return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
  339. }
  340. }
  341. if key, err := x509.ParseECPrivateKey(der); err == nil {
  342. return key, nil
  343. }
  344. return nil, errors.New("tls: failed to parse private key")
  345. }