tls.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. circlSign "github.com/cloudflare/circl/sign"
  26. )
  27. // Server returns a new TLS server side connection
  28. // using conn as the underlying transport.
  29. // The configuration config must be non-nil and must include
  30. // at least one certificate or else set GetCertificate.
  31. func Server(conn net.Conn, config *Config) *Conn {
  32. c := &Conn{
  33. conn: conn,
  34. config: config,
  35. }
  36. c.handshakeFn = c.serverHandshake
  37. return c
  38. }
  39. // Client returns a new TLS client side connection
  40. // using conn as the underlying transport.
  41. // The config cannot be nil: users must set either ServerName or
  42. // InsecureSkipVerify in the config.
  43. func Client(conn net.Conn, config *Config) *Conn {
  44. c := &Conn{
  45. conn: conn,
  46. config: config,
  47. isClient: true,
  48. }
  49. c.handshakeFn = c.clientHandshake
  50. return c
  51. }
  52. // A listener implements a network listener (net.Listener) for TLS connections.
  53. type listener struct {
  54. net.Listener
  55. config *Config
  56. }
  57. // Accept waits for and returns the next incoming TLS connection.
  58. // The returned connection is of type *Conn.
  59. func (l *listener) Accept() (net.Conn, error) {
  60. c, err := l.Listener.Accept()
  61. if err != nil {
  62. return nil, err
  63. }
  64. return Server(c, l.config), nil
  65. }
  66. // NewListener creates a Listener which accepts connections from an inner
  67. // Listener and wraps each connection with [Server].
  68. // The configuration config must be non-nil and must include
  69. // at least one certificate or else set GetCertificate.
  70. func NewListener(inner net.Listener, config *Config) net.Listener {
  71. l := new(listener)
  72. l.Listener = inner
  73. l.config = config
  74. return l
  75. }
  76. // Listen creates a TLS listener accepting connections on the
  77. // given network address using net.Listen.
  78. // The configuration config must be non-nil and must include
  79. // at least one certificate or else set GetCertificate.
  80. func Listen(network, laddr string, config *Config) (net.Listener, error) {
  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
  202. // of files. The files must contain PEM encoded data. The certificate file
  203. // may contain intermediate certificates following the leaf certificate to
  204. // form a certificate chain. On successful return, Certificate.Leaf will
  205. // be nil because the parsed form of the certificate is not retained.
  206. func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
  207. certPEMBlock, err := os.ReadFile(certFile)
  208. if err != nil {
  209. return Certificate{}, err
  210. }
  211. keyPEMBlock, err := os.ReadFile(keyFile)
  212. if err != nil {
  213. return Certificate{}, err
  214. }
  215. return X509KeyPair(certPEMBlock, keyPEMBlock)
  216. }
  217. // X509KeyPair parses a public/private key pair from a pair of
  218. // PEM encoded data. On successful return, Certificate.Leaf will be nil because
  219. // the parsed form of the certificate is not retained.
  220. func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
  221. fail := func(err error) (Certificate, error) { return Certificate{}, err }
  222. var cert Certificate
  223. var skippedBlockTypes []string
  224. for {
  225. var certDERBlock *pem.Block
  226. certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
  227. if certDERBlock == nil {
  228. break
  229. }
  230. if certDERBlock.Type == "CERTIFICATE" {
  231. cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
  232. } else {
  233. skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
  234. }
  235. }
  236. if len(cert.Certificate) == 0 {
  237. if len(skippedBlockTypes) == 0 {
  238. return fail(errors.New("tls: failed to find any PEM data in certificate input"))
  239. }
  240. if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
  241. 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"))
  242. }
  243. return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
  244. }
  245. skippedBlockTypes = skippedBlockTypes[:0]
  246. var keyDERBlock *pem.Block
  247. for {
  248. keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
  249. if keyDERBlock == nil {
  250. if len(skippedBlockTypes) == 0 {
  251. return fail(errors.New("tls: failed to find any PEM data in key input"))
  252. }
  253. if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
  254. return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
  255. }
  256. 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))
  257. }
  258. if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
  259. break
  260. }
  261. skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
  262. }
  263. // We don't need to parse the public key for TLS, but we so do anyway
  264. // to check that it looks sane and matches the private key.
  265. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  266. if err != nil {
  267. return fail(err)
  268. }
  269. cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
  270. if err != nil {
  271. return fail(err)
  272. }
  273. switch pub := x509Cert.PublicKey.(type) {
  274. case *rsa.PublicKey:
  275. priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
  276. if !ok {
  277. return fail(errors.New("tls: private key type does not match public key type"))
  278. }
  279. if pub.N.Cmp(priv.N) != 0 {
  280. return fail(errors.New("tls: private key does not match public key"))
  281. }
  282. case *ecdsa.PublicKey:
  283. priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
  284. if !ok {
  285. return fail(errors.New("tls: private key type does not match public key type"))
  286. }
  287. if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
  288. return fail(errors.New("tls: private key does not match public key"))
  289. }
  290. case ed25519.PublicKey:
  291. priv, ok := cert.PrivateKey.(ed25519.PrivateKey)
  292. if !ok {
  293. return fail(errors.New("tls: private key type does not match public key type"))
  294. }
  295. if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) {
  296. return fail(errors.New("tls: private key does not match public key"))
  297. }
  298. // [UTLS SECTION BEGINS]
  299. // Ported from cloudflare/go
  300. case circlSign.PublicKey:
  301. priv, ok := cert.PrivateKey.(circlSign.PrivateKey)
  302. if !ok {
  303. return fail(errors.New("tls: private key type does not match public key type"))
  304. }
  305. pkBytes, err := priv.Public().(circlSign.PublicKey).MarshalBinary()
  306. pkBytes2, err2 := pub.MarshalBinary()
  307. if err != nil || err2 != nil || !bytes.Equal(pkBytes, pkBytes2) {
  308. return fail(errors.New("tls: private key does not match public key"))
  309. }
  310. // [UTLS SECTION ENDS]
  311. default:
  312. return fail(errors.New("tls: unknown public key algorithm"))
  313. }
  314. return cert, nil
  315. }
  316. // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
  317. // PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys.
  318. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
  319. func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
  320. if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
  321. return key, nil
  322. }
  323. if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
  324. switch key := key.(type) {
  325. case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey, circlSign.PrivateKey: // [uTLS] ported from cloudflare/go
  326. return key, nil
  327. default:
  328. return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
  329. }
  330. }
  331. if key, err := x509.ParseECPrivateKey(der); err == nil {
  332. return key, nil
  333. }
  334. return nil, errors.New("tls: failed to parse private key")
  335. }