tls.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. "crypto"
  13. "crypto/ecdsa"
  14. "crypto/rsa"
  15. "crypto/x509"
  16. "encoding/pem"
  17. "errors"
  18. "fmt"
  19. "io/ioutil"
  20. "net"
  21. "strings"
  22. "time"
  23. )
  24. // Server returns a new TLS server side connection
  25. // using conn as the underlying transport.
  26. // The configuration config must be non-nil and must include
  27. // at least one certificate or else set GetCertificate.
  28. func Server(conn net.Conn, config *Config) *Conn {
  29. return &Conn{conn: conn, config: config}
  30. }
  31. // Client returns a new TLS client side connection
  32. // using conn as the underlying transport.
  33. // The config cannot be nil: users must set either ServerName or
  34. // InsecureSkipVerify in the config.
  35. func Client(conn net.Conn, config *Config) *Conn {
  36. return &Conn{conn: conn, config: config, isClient: true}
  37. }
  38. // A listener implements a network listener (net.Listener) for TLS connections.
  39. type listener struct {
  40. net.Listener
  41. config *Config
  42. }
  43. // Accept waits for and returns the next incoming TLS connection.
  44. // The returned connection is of type *Conn.
  45. func (l *listener) Accept() (net.Conn, error) {
  46. c, err := l.Listener.Accept()
  47. if err != nil {
  48. return nil, err
  49. }
  50. return Server(c, l.config), nil
  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 := time.Until(dialer.Deadline)
  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.Clone()
  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
  150. // of files. The files must contain PEM encoded data. The certificate file
  151. // may contain intermediate certificates following the leaf certificate to
  152. // form a certificate chain. On successful return, Certificate.Leaf will
  153. // be nil because the parsed form of the certificate is not retained.
  154. func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
  155. certPEMBlock, err := ioutil.ReadFile(certFile)
  156. if err != nil {
  157. return Certificate{}, err
  158. }
  159. keyPEMBlock, err := ioutil.ReadFile(keyFile)
  160. if err != nil {
  161. return Certificate{}, err
  162. }
  163. return X509KeyPair(certPEMBlock, keyPEMBlock)
  164. }
  165. // X509KeyPair parses a public/private key pair from a pair of
  166. // PEM encoded data. On successful return, Certificate.Leaf will be nil because
  167. // the parsed form of the certificate is not retained.
  168. func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
  169. fail := func(err error) (Certificate, error) { return Certificate{}, err }
  170. var cert Certificate
  171. var skippedBlockTypes []string
  172. for {
  173. var certDERBlock *pem.Block
  174. certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
  175. if certDERBlock == nil {
  176. break
  177. }
  178. if certDERBlock.Type == "CERTIFICATE" {
  179. cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
  180. } else {
  181. skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
  182. }
  183. }
  184. if len(cert.Certificate) == 0 {
  185. if len(skippedBlockTypes) == 0 {
  186. return fail(errors.New("tls: failed to find any PEM data in certificate input"))
  187. }
  188. if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
  189. 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"))
  190. }
  191. return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
  192. }
  193. skippedBlockTypes = skippedBlockTypes[:0]
  194. var keyDERBlock *pem.Block
  195. for {
  196. keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
  197. if keyDERBlock == nil {
  198. if len(skippedBlockTypes) == 0 {
  199. return fail(errors.New("tls: failed to find any PEM data in key input"))
  200. }
  201. if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
  202. return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
  203. }
  204. 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))
  205. }
  206. if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
  207. break
  208. }
  209. skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
  210. }
  211. // We don't need to parse the public key for TLS, but we so do anyway
  212. // to check that it looks sane and matches the private key.
  213. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  214. if err != nil {
  215. return fail(err)
  216. }
  217. cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
  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("tls: private key type does not match public key type"))
  226. }
  227. if pub.N.Cmp(priv.N) != 0 {
  228. return fail(errors.New("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("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("tls: private key does not match public key"))
  237. }
  238. default:
  239. return fail(errors.New("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("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("tls: failed to parse private key")
  262. }