tls.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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 config == nil || len(config.Certificates) == 0 &&
  81. config.GetCertificate == nil && config.GetConfigForClient == nil {
  82. return nil, errors.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config")
  83. }
  84. l, err := net.Listen(network, laddr)
  85. if err != nil {
  86. return nil, err
  87. }
  88. return NewListener(l, config), nil
  89. }
  90. type timeoutError struct{}
  91. func (timeoutError) Error() string { return "tls: DialWithDialer timed out" }
  92. func (timeoutError) Timeout() bool { return true }
  93. func (timeoutError) Temporary() bool { return true }
  94. // DialWithDialer connects to the given network address using dialer.Dial and
  95. // then initiates a TLS handshake, returning the resulting TLS connection. Any
  96. // timeout or deadline given in the dialer apply to connection and TLS
  97. // handshake as a whole.
  98. //
  99. // DialWithDialer interprets a nil configuration as equivalent to the zero
  100. // configuration; see the documentation of Config for the defaults.
  101. //
  102. // DialWithDialer uses context.Background internally; to specify the context,
  103. // use Dialer.DialContext with NetDialer set to the desired dialer.
  104. func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
  105. return dial(context.Background(), dialer, network, addr, config)
  106. }
  107. func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
  108. if netDialer.Timeout != 0 {
  109. var cancel context.CancelFunc
  110. ctx, cancel = context.WithTimeout(ctx, netDialer.Timeout)
  111. defer cancel()
  112. }
  113. if !netDialer.Deadline.IsZero() {
  114. var cancel context.CancelFunc
  115. ctx, cancel = context.WithDeadline(ctx, netDialer.Deadline)
  116. defer cancel()
  117. }
  118. rawConn, err := netDialer.DialContext(ctx, network, addr)
  119. if err != nil {
  120. return nil, err
  121. }
  122. colonPos := strings.LastIndex(addr, ":")
  123. if colonPos == -1 {
  124. colonPos = len(addr)
  125. }
  126. hostname := addr[:colonPos]
  127. if config == nil {
  128. config = defaultConfig()
  129. }
  130. // If no ServerName is set, infer the ServerName
  131. // from the hostname we're connecting to.
  132. if config.ServerName == "" {
  133. // Make a copy to avoid polluting argument or default.
  134. c := config.Clone()
  135. c.ServerName = hostname
  136. config = c
  137. }
  138. conn := Client(rawConn, config)
  139. if err := conn.HandshakeContext(ctx); err != nil {
  140. rawConn.Close()
  141. return nil, err
  142. }
  143. return conn, nil
  144. }
  145. // Dial connects to the given network address using net.Dial
  146. // and then initiates a TLS handshake, returning the resulting
  147. // TLS connection.
  148. // Dial interprets a nil configuration as equivalent to
  149. // the zero configuration; see the documentation of Config
  150. // for the defaults.
  151. func Dial(network, addr string, config *Config) (*Conn, error) {
  152. return DialWithDialer(new(net.Dialer), network, addr, config)
  153. }
  154. // Dialer dials TLS connections given a configuration and a Dialer for the
  155. // underlying connection.
  156. type Dialer struct {
  157. // NetDialer is the optional dialer to use for the TLS connections'
  158. // underlying TCP connections.
  159. // A nil NetDialer is equivalent to the net.Dialer zero value.
  160. NetDialer *net.Dialer
  161. // Config is the TLS configuration to use for new connections.
  162. // A nil configuration is equivalent to the zero
  163. // configuration; see the documentation of Config for the
  164. // defaults.
  165. Config *Config
  166. }
  167. // Dial connects to the given network address and initiates a TLS
  168. // handshake, returning the resulting TLS connection.
  169. //
  170. // The returned Conn, if any, will always be of type *Conn.
  171. //
  172. // Dial uses context.Background internally; to specify the context,
  173. // use DialContext.
  174. func (d *Dialer) Dial(network, addr string) (net.Conn, error) {
  175. return d.DialContext(context.Background(), network, addr)
  176. }
  177. func (d *Dialer) netDialer() *net.Dialer {
  178. if d.NetDialer != nil {
  179. return d.NetDialer
  180. }
  181. return new(net.Dialer)
  182. }
  183. // DialContext connects to the given network address and initiates a TLS
  184. // handshake, returning the resulting TLS connection.
  185. //
  186. // The provided Context must be non-nil. If the context expires before
  187. // the connection is complete, an error is returned. Once successfully
  188. // connected, any expiration of the context will not affect the
  189. // connection.
  190. //
  191. // The returned Conn, if any, will always be of type *Conn.
  192. func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
  193. c, err := dial(ctx, d.netDialer(), network, addr, d.Config)
  194. if err != nil {
  195. // Don't return c (a typed nil) in an interface.
  196. return nil, err
  197. }
  198. return c, nil
  199. }
  200. // LoadX509KeyPair reads and parses a public/private key pair from a pair
  201. // of files. The files must contain PEM encoded data. The certificate file
  202. // may contain intermediate certificates following the leaf certificate to
  203. // form a certificate chain. On successful return, Certificate.Leaf will
  204. // be nil because the parsed form of the certificate is not retained.
  205. func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
  206. certPEMBlock, err := os.ReadFile(certFile)
  207. if err != nil {
  208. return Certificate{}, err
  209. }
  210. keyPEMBlock, err := os.ReadFile(keyFile)
  211. if err != nil {
  212. return Certificate{}, err
  213. }
  214. return X509KeyPair(certPEMBlock, keyPEMBlock)
  215. }
  216. // X509KeyPair parses a public/private key pair from a pair of
  217. // PEM encoded data. On successful return, Certificate.Leaf will be nil because
  218. // the parsed form of the certificate is not retained.
  219. func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
  220. fail := func(err error) (Certificate, error) { return Certificate{}, err }
  221. var cert Certificate
  222. var skippedBlockTypes []string
  223. for {
  224. var certDERBlock *pem.Block
  225. certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
  226. if certDERBlock == nil {
  227. break
  228. }
  229. if certDERBlock.Type == "CERTIFICATE" {
  230. cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
  231. } else {
  232. skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
  233. }
  234. }
  235. if len(cert.Certificate) == 0 {
  236. if len(skippedBlockTypes) == 0 {
  237. return fail(errors.New("tls: failed to find any PEM data in certificate input"))
  238. }
  239. if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
  240. 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"))
  241. }
  242. return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
  243. }
  244. skippedBlockTypes = skippedBlockTypes[:0]
  245. var keyDERBlock *pem.Block
  246. for {
  247. keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
  248. if keyDERBlock == nil {
  249. if len(skippedBlockTypes) == 0 {
  250. return fail(errors.New("tls: failed to find any PEM data in key input"))
  251. }
  252. if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
  253. return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
  254. }
  255. 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))
  256. }
  257. if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
  258. break
  259. }
  260. skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
  261. }
  262. // We don't need to parse the public key for TLS, but we so do anyway
  263. // to check that it looks sane and matches the private key.
  264. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  265. if err != nil {
  266. return fail(err)
  267. }
  268. cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
  269. if err != nil {
  270. return fail(err)
  271. }
  272. switch pub := x509Cert.PublicKey.(type) {
  273. case *rsa.PublicKey:
  274. priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
  275. if !ok {
  276. return fail(errors.New("tls: private key type does not match public key type"))
  277. }
  278. if pub.N.Cmp(priv.N) != 0 {
  279. return fail(errors.New("tls: private key does not match public key"))
  280. }
  281. case *ecdsa.PublicKey:
  282. priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
  283. if !ok {
  284. return fail(errors.New("tls: private key type does not match public key type"))
  285. }
  286. if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
  287. return fail(errors.New("tls: private key does not match public key"))
  288. }
  289. case ed25519.PublicKey:
  290. priv, ok := cert.PrivateKey.(ed25519.PrivateKey)
  291. if !ok {
  292. return fail(errors.New("tls: private key type does not match public key type"))
  293. }
  294. if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) {
  295. return fail(errors.New("tls: private key does not match public key"))
  296. }
  297. default:
  298. return fail(errors.New("tls: unknown public key algorithm"))
  299. }
  300. return cert, nil
  301. }
  302. // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
  303. // PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys.
  304. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
  305. func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
  306. if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
  307. return key, nil
  308. }
  309. if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
  310. switch key := key.(type) {
  311. case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey:
  312. return key, nil
  313. default:
  314. return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
  315. }
  316. }
  317. if key, err := x509.ParseECPrivateKey(der); err == nil {
  318. return key, nil
  319. }
  320. return nil, errors.New("tls: failed to parse private key")
  321. }