tls.go 12 KB

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