tls.go 9.7 KB

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