Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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. 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. var err error
  211. cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
  212. if err != nil {
  213. return fail(err)
  214. }
  215. // We don't need to parse the public key for TLS, but we so do anyway
  216. // to check that it looks sane and matches the private key.
  217. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  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. }