Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

tls.go 7.6 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 main
  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. c := &Conn{conn: conn, config: config}
  24. c.init()
  25. return c
  26. }
  27. // Client returns a new TLS client side connection
  28. // using conn as the underlying transport.
  29. // The config cannot be nil: users must set either ServerHostname or
  30. // InsecureSkipVerify in the config.
  31. func Client(conn net.Conn, config *Config) *Conn {
  32. c := &Conn{conn: conn, config: config, isClient: true}
  33. c.init()
  34. return c
  35. }
  36. // A listener implements a network listener (net.Listener) for TLS connections.
  37. type listener struct {
  38. net.Listener
  39. config *Config
  40. }
  41. // Accept waits for and returns the next incoming TLS connection.
  42. // The returned connection c is a *tls.Conn.
  43. func (l *listener) Accept() (c net.Conn, err error) {
  44. c, err = l.Listener.Accept()
  45. if err != nil {
  46. return
  47. }
  48. c = Server(c, l.config)
  49. return
  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 have
  54. // at least one certificate.
  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 have
  64. // at least one certificate.
  65. func Listen(network, laddr string, config *Config) (net.Listener, error) {
  66. if config == nil || len(config.Certificates) == 0 {
  67. return nil, errors.New("tls.Listen: no certificates in configuration")
  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 := dialer.Deadline.Sub(time.Now())
  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
  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 of
  149. // files. The files must contain PEM encoded data.
  150. func LoadX509KeyPair(certFile, keyFile string) (cert Certificate, err error) {
  151. certPEMBlock, err := ioutil.ReadFile(certFile)
  152. if err != nil {
  153. return
  154. }
  155. keyPEMBlock, err := ioutil.ReadFile(keyFile)
  156. if err != nil {
  157. return
  158. }
  159. return X509KeyPair(certPEMBlock, keyPEMBlock)
  160. }
  161. // X509KeyPair parses a public/private key pair from a pair of
  162. // PEM encoded data.
  163. func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (cert Certificate, err error) {
  164. var certDERBlock *pem.Block
  165. for {
  166. certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
  167. if certDERBlock == nil {
  168. break
  169. }
  170. if certDERBlock.Type == "CERTIFICATE" {
  171. cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
  172. }
  173. }
  174. if len(cert.Certificate) == 0 {
  175. err = errors.New("crypto/tls: failed to parse certificate PEM data")
  176. return
  177. }
  178. var keyDERBlock *pem.Block
  179. for {
  180. keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
  181. if keyDERBlock == nil {
  182. err = errors.New("crypto/tls: failed to parse key PEM data")
  183. return
  184. }
  185. if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
  186. break
  187. }
  188. }
  189. cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
  190. if err != nil {
  191. return
  192. }
  193. // We don't need to parse the public key for TLS, but we so do anyway
  194. // to check that it looks sane and matches the private key.
  195. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  196. if err != nil {
  197. return
  198. }
  199. switch pub := x509Cert.PublicKey.(type) {
  200. case *rsa.PublicKey:
  201. priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
  202. if !ok {
  203. err = errors.New("crypto/tls: private key type does not match public key type")
  204. return
  205. }
  206. if pub.N.Cmp(priv.N) != 0 {
  207. err = errors.New("crypto/tls: private key does not match public key")
  208. return
  209. }
  210. case *ecdsa.PublicKey:
  211. priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
  212. if !ok {
  213. err = errors.New("crypto/tls: private key type does not match public key type")
  214. return
  215. }
  216. if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
  217. err = errors.New("crypto/tls: private key does not match public key")
  218. return
  219. }
  220. default:
  221. err = errors.New("crypto/tls: unknown public key algorithm")
  222. return
  223. }
  224. return
  225. }
  226. // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
  227. // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
  228. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
  229. func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
  230. if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
  231. return key, nil
  232. }
  233. if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
  234. switch key := key.(type) {
  235. case *rsa.PrivateKey, *ecdsa.PrivateKey:
  236. return key, nil
  237. default:
  238. return nil, errors.New("crypto/tls: found unknown private key type in PKCS#8 wrapping")
  239. }
  240. }
  241. if key, err := x509.ParseECPrivateKey(der); err == nil {
  242. return key, nil
  243. }
  244. return nil, errors.New("crypto/tls: failed to parse private key")
  245. }