tls.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. package tls
  6. // BUG(agl): The crypto/tls package does not implement countermeasures
  7. // against Lucky13 attacks on CBC-mode encryption. See
  8. // http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and
  9. // https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
  10. import (
  11. "crypto"
  12. "crypto/ecdsa"
  13. "crypto/rsa"
  14. "crypto/x509"
  15. "encoding/pem"
  16. "errors"
  17. "fmt"
  18. "net"
  19. "os"
  20. "strings"
  21. "time"
  22. )
  23. // Server returns a new TLS server side connection
  24. // using conn as the underlying transport.
  25. // The configuration config must be non-nil and must include
  26. // at least one certificate or else set GetCertificate.
  27. func Server(conn net.Conn, config *Config) *Conn {
  28. return &Conn{conn: conn, config: config}
  29. }
  30. // Client returns a new TLS client side connection
  31. // using conn as the underlying transport.
  32. // The config cannot be nil: users must set either ServerName or
  33. // InsecureSkipVerify in the config.
  34. func Client(conn net.Conn, config *Config) *Conn {
  35. return &Conn{conn: conn, config: config, isClient: true}
  36. }
  37. // A listener implements a network listener (net.Listener) for TLS connections.
  38. type listener struct {
  39. net.Listener
  40. config *Config
  41. }
  42. // Accept waits for and returns the next incoming TLS connection.
  43. // The returned connection c is a *tls.Conn.
  44. func (l *listener) Accept() (c net.Conn, err error) {
  45. c, err = l.Listener.Accept()
  46. if err != nil {
  47. return
  48. }
  49. c = Server(c, l.config)
  50. return
  51. }
  52. // NewListener creates a Listener which accepts connections from an inner
  53. // Listener and wraps each connection with Server.
  54. // The configuration config must be non-nil and must include
  55. // at least one certificate or else set GetCertificate.
  56. func NewListener(inner net.Listener, config *Config) net.Listener {
  57. l := new(listener)
  58. l.Listener = inner
  59. l.config = config
  60. return l
  61. }
  62. // Listen creates a TLS listener accepting connections on the
  63. // given network address using net.Listen.
  64. // The configuration config must be non-nil and must include
  65. // at least one certificate or else set GetCertificate.
  66. func Listen(network, laddr string, config *Config) (net.Listener, error) {
  67. if config == nil || (len(config.Certificates) == 0 && config.GetCertificate == nil) {
  68. return nil, errors.New("tls: neither Certificates nor GetCertificate set in Config")
  69. }
  70. l, err := net.Listen(network, laddr)
  71. if err != nil {
  72. return nil, err
  73. }
  74. return NewListener(l, config), nil
  75. }
  76. type timeoutError struct{}
  77. func (timeoutError) Error() string { return "tls: DialWithDialer timed out" }
  78. func (timeoutError) Timeout() bool { return true }
  79. func (timeoutError) Temporary() bool { return true }
  80. // DialWithDialer connects to the given network address using dialer.Dial and
  81. // then initiates a TLS handshake, returning the resulting TLS connection. Any
  82. // timeout or deadline given in the dialer apply to connection and TLS
  83. // handshake as a whole.
  84. //
  85. // DialWithDialer interprets a nil configuration as equivalent to the zero
  86. // configuration; see the documentation of Config for the defaults.
  87. func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
  88. // We want the Timeout and Deadline values from dialer to cover the
  89. // whole process: TCP connection and TLS handshake. This means that we
  90. // also need to start our own timers now.
  91. timeout := dialer.Timeout
  92. if !dialer.Deadline.IsZero() {
  93. deadlineTimeout := dialer.Deadline.Sub(time.Now())
  94. if timeout == 0 || deadlineTimeout < timeout {
  95. timeout = deadlineTimeout
  96. }
  97. }
  98. var errChannel chan error
  99. if timeout != 0 {
  100. errChannel = make(chan error, 2)
  101. time.AfterFunc(timeout, func() {
  102. errChannel <- timeoutError{}
  103. })
  104. }
  105. rawConn, err := dialer.Dial(network, addr)
  106. if err != nil {
  107. return nil, err
  108. }
  109. colonPos := strings.LastIndex(addr, ":")
  110. if colonPos == -1 {
  111. colonPos = len(addr)
  112. }
  113. hostname := addr[:colonPos]
  114. if config == nil {
  115. config = defaultConfig()
  116. }
  117. // If no ServerName is set, infer the ServerName
  118. // from the hostname we're connecting to.
  119. if config.ServerName == "" {
  120. // Make a copy to avoid polluting argument or default.
  121. c := *config
  122. c.ServerName = hostname
  123. config = &c
  124. }
  125. conn := Client(rawConn, config)
  126. if timeout == 0 {
  127. err = conn.Handshake()
  128. } else {
  129. go func() {
  130. errChannel <- conn.Handshake()
  131. }()
  132. err = <-errChannel
  133. }
  134. if err != nil {
  135. rawConn.Close()
  136. return nil, err
  137. }
  138. return conn, nil
  139. }
  140. // Dial connects to the given network address using net.Dial
  141. // and then initiates a TLS handshake, returning the resulting
  142. // TLS connection.
  143. // Dial interprets a nil configuration as equivalent to
  144. // the zero configuration; see the documentation of Config
  145. // for the defaults.
  146. func Dial(network, addr string, config *Config) (*Conn, error) {
  147. return DialWithDialer(new(net.Dialer), network, addr, config)
  148. }
  149. // LoadX509KeyPair reads and parses a public/private key pair from a pair of
  150. // files. The files must contain PEM encoded data. On successful return,
  151. // Certificate.Leaf will be nil because the parsed form of the certificate is
  152. // not retained.
  153. func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
  154. certPEMBlock, err := os.ReadFile(certFile)
  155. if err != nil {
  156. return Certificate{}, err
  157. }
  158. keyPEMBlock, err := os.ReadFile(keyFile)
  159. if err != nil {
  160. return Certificate{}, err
  161. }
  162. return X509KeyPair(certPEMBlock, keyPEMBlock)
  163. }
  164. // X509KeyPair parses a public/private key pair from a pair of
  165. // PEM encoded data. On successful return, Certificate.Leaf will be nil because
  166. // the parsed form of the certificate is not retained.
  167. func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
  168. fail := func(err error) (Certificate, error) { return Certificate{}, err }
  169. var cert Certificate
  170. var skippedBlockTypes []string
  171. for {
  172. var certDERBlock *pem.Block
  173. certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
  174. if certDERBlock == nil {
  175. break
  176. }
  177. if certDERBlock.Type == "CERTIFICATE" {
  178. cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
  179. } else {
  180. skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
  181. }
  182. }
  183. if len(cert.Certificate) == 0 {
  184. if len(skippedBlockTypes) == 0 {
  185. return fail(errors.New("crypto/tls: failed to find any PEM data in certificate input"))
  186. } else if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
  187. return fail(errors.New("crypto/tls: failed to find certificate PEM data in certificate input, but did find a private key; PEM inputs may have been switched"))
  188. } else {
  189. return fail(fmt.Errorf("crypto/tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
  190. }
  191. }
  192. skippedBlockTypes = skippedBlockTypes[:0]
  193. var keyDERBlock *pem.Block
  194. for {
  195. keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
  196. if keyDERBlock == nil {
  197. if len(skippedBlockTypes) == 0 {
  198. return fail(errors.New("crypto/tls: failed to find any PEM data in key input"))
  199. } else if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
  200. return fail(errors.New("crypto/tls: found a certificate rather than a key in the PEM for the private key"))
  201. } else {
  202. return fail(fmt.Errorf("crypto/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))
  203. }
  204. }
  205. if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
  206. break
  207. }
  208. skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
  209. }
  210. var err error
  211. cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
  212. if err != nil {
  213. return fail(err)
  214. }
  215. // We don't need to parse the public key for TLS, but we so do anyway
  216. // to check that it looks sane and matches the private key.
  217. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  218. if err != nil {
  219. return fail(err)
  220. }
  221. switch pub := x509Cert.PublicKey.(type) {
  222. case *rsa.PublicKey:
  223. priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
  224. if !ok {
  225. return fail(errors.New("crypto/tls: private key type does not match public key type"))
  226. }
  227. if pub.N.Cmp(priv.N) != 0 {
  228. return fail(errors.New("crypto/tls: private key does not match public key"))
  229. }
  230. case *ecdsa.PublicKey:
  231. priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
  232. if !ok {
  233. return fail(errors.New("crypto/tls: private key type does not match public key type"))
  234. }
  235. if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
  236. return fail(errors.New("crypto/tls: private key does not match public key"))
  237. }
  238. default:
  239. return fail(errors.New("crypto/tls: unknown public key algorithm"))
  240. }
  241. return cert, nil
  242. }
  243. // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
  244. // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
  245. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
  246. func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
  247. if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
  248. return key, nil
  249. }
  250. if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
  251. switch key := key.(type) {
  252. case *rsa.PrivateKey, *ecdsa.PrivateKey:
  253. return key, nil
  254. default:
  255. return nil, errors.New("crypto/tls: found unknown private key type in PKCS#8 wrapping")
  256. }
  257. }
  258. if key, err := x509.ParseECPrivateKey(der); err == nil {
  259. return key, nil
  260. }
  261. return nil, errors.New("crypto/tls: failed to parse private key")
  262. }