Alternative TLS implementation in Go
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

297 lignes
9.5 KiB

  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 only implements some countermeasures
  7. // against Lucky13 attacks on CBC-mode encryption, and only on SHA1
  8. // variants. See 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. "io/ioutil"
  19. "net"
  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 is of type *Conn.
  44. func (l *listener) Accept() (net.Conn, error) {
  45. c, err := l.Listener.Accept()
  46. if err != nil {
  47. return nil, err
  48. }
  49. return Server(c, l.config), nil
  50. }
  51. // NewListener creates a Listener which accepts connections from an inner
  52. // Listener and wraps each connection with Server.
  53. // The configuration config must be non-nil and must include
  54. // at least one certificate or else set GetCertificate.
  55. func NewListener(inner net.Listener, config *Config) net.Listener {
  56. l := new(listener)
  57. l.Listener = inner
  58. l.config = config
  59. return l
  60. }
  61. // Listen creates a TLS listener accepting connections on the
  62. // given network address using net.Listen.
  63. // The configuration config must be non-nil and must include
  64. // at least one certificate or else set GetCertificate.
  65. func Listen(network, laddr string, config *Config) (net.Listener, error) {
  66. if config == nil || (len(config.Certificates) == 0 && config.GetCertificate == nil) {
  67. return nil, errors.New("tls: neither Certificates nor GetCertificate set in Config")
  68. }
  69. l, err := net.Listen(network, laddr)
  70. if err != nil {
  71. return nil, err
  72. }
  73. return NewListener(l, config), nil
  74. }
  75. type timeoutError struct{}
  76. func (timeoutError) Error() string { return "tls: DialWithDialer timed out" }
  77. func (timeoutError) Timeout() bool { return true }
  78. func (timeoutError) Temporary() bool { return true }
  79. // DialWithDialer connects to the given network address using dialer.Dial and
  80. // then initiates a TLS handshake, returning the resulting TLS connection. Any
  81. // timeout or deadline given in the dialer apply to connection and TLS
  82. // handshake as a whole.
  83. //
  84. // DialWithDialer interprets a nil configuration as equivalent to the zero
  85. // configuration; see the documentation of Config for the defaults.
  86. func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
  87. // We want the Timeout and Deadline values from dialer to cover the
  88. // whole process: TCP connection and TLS handshake. This means that we
  89. // also need to start our own timers now.
  90. timeout := dialer.Timeout
  91. if !dialer.Deadline.IsZero() {
  92. deadlineTimeout := time.Until(dialer.Deadline)
  93. if timeout == 0 || deadlineTimeout < timeout {
  94. timeout = deadlineTimeout
  95. }
  96. }
  97. var errChannel chan error
  98. if timeout != 0 {
  99. errChannel = make(chan error, 2)
  100. time.AfterFunc(timeout, func() {
  101. errChannel <- timeoutError{}
  102. })
  103. }
  104. rawConn, err := dialer.Dial(network, addr)
  105. if err != nil {
  106. return nil, err
  107. }
  108. colonPos := strings.LastIndex(addr, ":")
  109. if colonPos == -1 {
  110. colonPos = len(addr)
  111. }
  112. hostname := addr[:colonPos]
  113. if config == nil {
  114. config = defaultConfig()
  115. }
  116. // If no ServerName is set, infer the ServerName
  117. // from the hostname we're connecting to.
  118. if config.ServerName == "" {
  119. // Make a copy to avoid polluting argument or default.
  120. c := config.Clone()
  121. c.ServerName = hostname
  122. config = c
  123. }
  124. conn := Client(rawConn, config)
  125. if timeout == 0 {
  126. err = conn.Handshake()
  127. } else {
  128. go func() {
  129. errChannel <- conn.Handshake()
  130. }()
  131. err = <-errChannel
  132. }
  133. if err != nil {
  134. rawConn.Close()
  135. return nil, err
  136. }
  137. return conn, nil
  138. }
  139. // Dial connects to the given network address using net.Dial
  140. // and then initiates a TLS handshake, returning the resulting
  141. // TLS connection.
  142. // Dial interprets a nil configuration as equivalent to
  143. // the zero configuration; see the documentation of Config
  144. // for the defaults.
  145. func Dial(network, addr string, config *Config) (*Conn, error) {
  146. return DialWithDialer(new(net.Dialer), network, addr, config)
  147. }
  148. // LoadX509KeyPair reads and parses a public/private key pair from a pair
  149. // of files. The files must contain PEM encoded data. The certificate file
  150. // may contain intermediate certificates following the leaf certificate to
  151. // form a certificate chain. On successful return, Certificate.Leaf will
  152. // be nil because the parsed form of the certificate is not retained.
  153. func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
  154. certPEMBlock, err := ioutil.ReadFile(certFile)
  155. if err != nil {
  156. return Certificate{}, err
  157. }
  158. keyPEMBlock, err := ioutil.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("tls: failed to find any PEM data in certificate input"))
  186. }
  187. if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
  188. 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"))
  189. }
  190. return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
  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("tls: failed to find any PEM data in key input"))
  199. }
  200. if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
  201. return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
  202. }
  203. 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))
  204. }
  205. if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
  206. break
  207. }
  208. skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
  209. }
  210. // We don't need to parse the public key for TLS, but we so do anyway
  211. // to check that it looks sane and matches the private key.
  212. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  213. if err != nil {
  214. return fail(err)
  215. }
  216. cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
  217. if err != nil {
  218. return fail(err)
  219. }
  220. switch pub := x509Cert.PublicKey.(type) {
  221. case *rsa.PublicKey:
  222. priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
  223. if !ok {
  224. return fail(errors.New("tls: private key type does not match public key type"))
  225. }
  226. if pub.N.Cmp(priv.N) != 0 {
  227. return fail(errors.New("tls: private key does not match public key"))
  228. }
  229. case *ecdsa.PublicKey:
  230. priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
  231. if !ok {
  232. return fail(errors.New("tls: private key type does not match public key type"))
  233. }
  234. if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
  235. return fail(errors.New("tls: private key does not match public key"))
  236. }
  237. default:
  238. return fail(errors.New("tls: unknown public key algorithm"))
  239. }
  240. return cert, nil
  241. }
  242. // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
  243. // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
  244. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
  245. func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
  246. if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
  247. return key, nil
  248. }
  249. if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
  250. switch key := key.(type) {
  251. case *rsa.PrivateKey, *ecdsa.PrivateKey:
  252. return key, nil
  253. default:
  254. return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
  255. }
  256. }
  257. if key, err := x509.ParseECPrivateKey(der); err == nil {
  258. return key, nil
  259. }
  260. return nil, errors.New("tls: failed to parse private key")
  261. }