Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

276 rindas
7.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. 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 ServerHostname 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) (cert Certificate, err error) {
  147. certPEMBlock, err := ioutil.ReadFile(certFile)
  148. if err != nil {
  149. return
  150. }
  151. keyPEMBlock, err := ioutil.ReadFile(keyFile)
  152. if err != nil {
  153. return
  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) (cert Certificate, err error) {
  160. var certDERBlock *pem.Block
  161. for {
  162. certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
  163. if certDERBlock == nil {
  164. break
  165. }
  166. if certDERBlock.Type == "CERTIFICATE" {
  167. cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
  168. }
  169. }
  170. if len(cert.Certificate) == 0 {
  171. err = errors.New("crypto/tls: failed to parse certificate PEM data")
  172. return
  173. }
  174. var keyDERBlock *pem.Block
  175. for {
  176. keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
  177. if keyDERBlock == nil {
  178. err = errors.New("crypto/tls: failed to parse key PEM data")
  179. return
  180. }
  181. if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
  182. break
  183. }
  184. }
  185. cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
  186. if err != nil {
  187. return
  188. }
  189. // We don't need to parse the public key for TLS, but we so do anyway
  190. // to check that it looks sane and matches the private key.
  191. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  192. if err != nil {
  193. return
  194. }
  195. switch pub := x509Cert.PublicKey.(type) {
  196. case *rsa.PublicKey:
  197. priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
  198. if !ok {
  199. err = errors.New("crypto/tls: private key type does not match public key type")
  200. return
  201. }
  202. if pub.N.Cmp(priv.N) != 0 {
  203. err = errors.New("crypto/tls: private key does not match public key")
  204. return
  205. }
  206. case *ecdsa.PublicKey:
  207. priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
  208. if !ok {
  209. err = errors.New("crypto/tls: private key type does not match public key type")
  210. return
  211. }
  212. if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
  213. err = errors.New("crypto/tls: private key does not match public key")
  214. return
  215. }
  216. default:
  217. err = errors.New("crypto/tls: unknown public key algorithm")
  218. return
  219. }
  220. return
  221. }
  222. // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
  223. // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
  224. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
  225. func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
  226. if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
  227. return key, nil
  228. }
  229. if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
  230. switch key := key.(type) {
  231. case *rsa.PrivateKey, *ecdsa.PrivateKey:
  232. return key, nil
  233. default:
  234. return nil, errors.New("crypto/tls: found unknown private key type in PKCS#8 wrapping")
  235. }
  236. }
  237. if key, err := x509.ParseECPrivateKey(der); err == nil {
  238. return key, nil
  239. }
  240. return nil, errors.New("crypto/tls: failed to parse private key")
  241. }