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.

tls.go 7.7 KiB

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