tls.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. // and TLS 1.3, as specified in RFC 8446.
  6. package tls
  7. // BUG(agl): The crypto/tls package only implements some countermeasures
  8. // against Lucky13 attacks on CBC-mode encryption, and only on SHA1
  9. // variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and
  10. // https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
  11. import (
  12. "bytes"
  13. "context"
  14. "crypto"
  15. "crypto/ecdsa"
  16. "crypto/ed25519"
  17. "crypto/rsa"
  18. "crypto/x509"
  19. "encoding/pem"
  20. "errors"
  21. "fmt"
  22. "net"
  23. "os"
  24. "strings"
  25. )
  26. // Server returns a new TLS server side connection
  27. // using conn as the underlying transport.
  28. // The configuration config must be non-nil and must include
  29. // at least one certificate or else set GetCertificate.
  30. func Server(conn net.Conn, config *Config) *Conn {
  31. // [Psiphon]
  32. // Initialize traffic recording to facilitate playback in the case of
  33. // passthrough.
  34. if config.PassthroughAddress != "" {
  35. conn = newRecorderConn(conn)
  36. }
  37. c := &Conn{
  38. conn: conn,
  39. config: config,
  40. }
  41. c.handshakeFn = c.serverHandshake
  42. return c
  43. }
  44. // Client returns a new TLS client side connection
  45. // using conn as the underlying transport.
  46. // The config cannot be nil: users must set either ServerName or
  47. // InsecureSkipVerify in the config.
  48. func Client(conn net.Conn, config *Config) *Conn {
  49. c := &Conn{
  50. conn: conn,
  51. config: config,
  52. isClient: true,
  53. }
  54. c.handshakeFn = c.clientHandshake
  55. return c
  56. }
  57. // A listener implements a network listener (net.Listener) for TLS connections.
  58. type listener struct {
  59. net.Listener
  60. config *Config
  61. }
  62. // Accept waits for and returns the next incoming TLS connection.
  63. // The returned connection is of type *Conn.
  64. func (l *listener) Accept() (net.Conn, error) {
  65. c, err := l.Listener.Accept()
  66. if err != nil {
  67. return nil, err
  68. }
  69. return Server(c, l.config), nil
  70. }
  71. // NewListener creates a Listener which accepts connections from an inner
  72. // Listener and wraps each connection with Server.
  73. // The configuration config must be non-nil and must include
  74. // at least one certificate or else set GetCertificate.
  75. func NewListener(inner net.Listener, config *Config) net.Listener {
  76. l := new(listener)
  77. l.Listener = inner
  78. l.config = config
  79. return l
  80. }
  81. // Listen creates a TLS listener accepting connections on the
  82. // given network address using net.Listen.
  83. // The configuration config must be non-nil and must include
  84. // at least one certificate or else set GetCertificate.
  85. func Listen(network, laddr string, config *Config) (net.Listener, error) {
  86. if config == nil || len(config.Certificates) == 0 &&
  87. config.GetCertificate == nil && config.GetConfigForClient == nil {
  88. return nil, errors.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config")
  89. }
  90. l, err := net.Listen(network, laddr)
  91. if err != nil {
  92. return nil, err
  93. }
  94. return NewListener(l, config), nil
  95. }
  96. type timeoutError struct{}
  97. func (timeoutError) Error() string { return "tls: DialWithDialer timed out" }
  98. func (timeoutError) Timeout() bool { return true }
  99. func (timeoutError) Temporary() bool { return true }
  100. // DialWithDialer connects to the given network address using dialer.Dial and
  101. // then initiates a TLS handshake, returning the resulting TLS connection. Any
  102. // timeout or deadline given in the dialer apply to connection and TLS
  103. // handshake as a whole.
  104. //
  105. // DialWithDialer interprets a nil configuration as equivalent to the zero
  106. // configuration; see the documentation of Config for the defaults.
  107. //
  108. // DialWithDialer uses context.Background internally; to specify the context,
  109. // use Dialer.DialContext with NetDialer set to the desired dialer.
  110. func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
  111. return dial(context.Background(), dialer, network, addr, config)
  112. }
  113. func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
  114. if netDialer.Timeout != 0 {
  115. var cancel context.CancelFunc
  116. ctx, cancel = context.WithTimeout(ctx, netDialer.Timeout)
  117. defer cancel()
  118. }
  119. if !netDialer.Deadline.IsZero() {
  120. var cancel context.CancelFunc
  121. ctx, cancel = context.WithDeadline(ctx, netDialer.Deadline)
  122. defer cancel()
  123. }
  124. rawConn, err := netDialer.DialContext(ctx, network, addr)
  125. if err != nil {
  126. return nil, err
  127. }
  128. colonPos := strings.LastIndex(addr, ":")
  129. if colonPos == -1 {
  130. colonPos = len(addr)
  131. }
  132. hostname := addr[:colonPos]
  133. if config == nil {
  134. config = defaultConfig()
  135. }
  136. // If no ServerName is set, infer the ServerName
  137. // from the hostname we're connecting to.
  138. if config.ServerName == "" {
  139. // Make a copy to avoid polluting argument or default.
  140. c := config.Clone()
  141. c.ServerName = hostname
  142. config = c
  143. }
  144. conn := Client(rawConn, config)
  145. if err := conn.HandshakeContext(ctx); err != nil {
  146. rawConn.Close()
  147. return nil, err
  148. }
  149. return conn, nil
  150. }
  151. // Dial connects to the given network address using net.Dial
  152. // and then initiates a TLS handshake, returning the resulting
  153. // TLS connection.
  154. // Dial interprets a nil configuration as equivalent to
  155. // the zero configuration; see the documentation of Config
  156. // for the defaults.
  157. func Dial(network, addr string, config *Config) (*Conn, error) {
  158. return DialWithDialer(new(net.Dialer), network, addr, config)
  159. }
  160. // Dialer dials TLS connections given a configuration and a Dialer for the
  161. // underlying connection.
  162. type Dialer struct {
  163. // NetDialer is the optional dialer to use for the TLS connections'
  164. // underlying TCP connections.
  165. // A nil NetDialer is equivalent to the net.Dialer zero value.
  166. NetDialer *net.Dialer
  167. // Config is the TLS configuration to use for new connections.
  168. // A nil configuration is equivalent to the zero
  169. // configuration; see the documentation of Config for the
  170. // defaults.
  171. Config *Config
  172. }
  173. // Dial connects to the given network address and initiates a TLS
  174. // handshake, returning the resulting TLS connection.
  175. //
  176. // The returned Conn, if any, will always be of type *Conn.
  177. //
  178. // Dial uses context.Background internally; to specify the context,
  179. // use DialContext.
  180. func (d *Dialer) Dial(network, addr string) (net.Conn, error) {
  181. return d.DialContext(context.Background(), network, addr)
  182. }
  183. func (d *Dialer) netDialer() *net.Dialer {
  184. if d.NetDialer != nil {
  185. return d.NetDialer
  186. }
  187. return new(net.Dialer)
  188. }
  189. // DialContext connects to the given network address and initiates a TLS
  190. // handshake, returning the resulting TLS connection.
  191. //
  192. // The provided Context must be non-nil. If the context expires before
  193. // the connection is complete, an error is returned. Once successfully
  194. // connected, any expiration of the context will not affect the
  195. // connection.
  196. //
  197. // The returned Conn, if any, will always be of type *Conn.
  198. func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
  199. c, err := dial(ctx, d.netDialer(), network, addr, d.Config)
  200. if err != nil {
  201. // Don't return c (a typed nil) in an interface.
  202. return nil, err
  203. }
  204. return c, nil
  205. }
  206. // LoadX509KeyPair reads and parses a public/private key pair from a pair
  207. // of files. The files must contain PEM encoded data. The certificate file
  208. // may contain intermediate certificates following the leaf certificate to
  209. // form a certificate chain. On successful return, Certificate.Leaf will
  210. // be nil because the parsed form of the certificate is not retained.
  211. func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
  212. certPEMBlock, err := os.ReadFile(certFile)
  213. if err != nil {
  214. return Certificate{}, err
  215. }
  216. keyPEMBlock, err := os.ReadFile(keyFile)
  217. if err != nil {
  218. return Certificate{}, err
  219. }
  220. return X509KeyPair(certPEMBlock, keyPEMBlock)
  221. }
  222. // X509KeyPair parses a public/private key pair from a pair of
  223. // PEM encoded data. On successful return, Certificate.Leaf will be nil because
  224. // the parsed form of the certificate is not retained.
  225. func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
  226. fail := func(err error) (Certificate, error) { return Certificate{}, err }
  227. var cert Certificate
  228. var skippedBlockTypes []string
  229. for {
  230. var certDERBlock *pem.Block
  231. certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
  232. if certDERBlock == nil {
  233. break
  234. }
  235. if certDERBlock.Type == "CERTIFICATE" {
  236. cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
  237. } else {
  238. skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
  239. }
  240. }
  241. if len(cert.Certificate) == 0 {
  242. if len(skippedBlockTypes) == 0 {
  243. return fail(errors.New("tls: failed to find any PEM data in certificate input"))
  244. }
  245. if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
  246. 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"))
  247. }
  248. return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
  249. }
  250. skippedBlockTypes = skippedBlockTypes[:0]
  251. var keyDERBlock *pem.Block
  252. for {
  253. keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
  254. if keyDERBlock == nil {
  255. if len(skippedBlockTypes) == 0 {
  256. return fail(errors.New("tls: failed to find any PEM data in key input"))
  257. }
  258. if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
  259. return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
  260. }
  261. 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))
  262. }
  263. if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
  264. break
  265. }
  266. skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
  267. }
  268. // We don't need to parse the public key for TLS, but we so do anyway
  269. // to check that it looks sane and matches the private key.
  270. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  271. if err != nil {
  272. return fail(err)
  273. }
  274. cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
  275. if err != nil {
  276. return fail(err)
  277. }
  278. switch pub := x509Cert.PublicKey.(type) {
  279. case *rsa.PublicKey:
  280. priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
  281. if !ok {
  282. return fail(errors.New("tls: private key type does not match public key type"))
  283. }
  284. if pub.N.Cmp(priv.N) != 0 {
  285. return fail(errors.New("tls: private key does not match public key"))
  286. }
  287. case *ecdsa.PublicKey:
  288. priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
  289. if !ok {
  290. return fail(errors.New("tls: private key type does not match public key type"))
  291. }
  292. if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
  293. return fail(errors.New("tls: private key does not match public key"))
  294. }
  295. case ed25519.PublicKey:
  296. priv, ok := cert.PrivateKey.(ed25519.PrivateKey)
  297. if !ok {
  298. return fail(errors.New("tls: private key type does not match public key type"))
  299. }
  300. if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) {
  301. return fail(errors.New("tls: private key does not match public key"))
  302. }
  303. default:
  304. return fail(errors.New("tls: unknown public key algorithm"))
  305. }
  306. return cert, nil
  307. }
  308. // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
  309. // PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys.
  310. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
  311. func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
  312. if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
  313. return key, nil
  314. }
  315. if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
  316. switch key := key.(type) {
  317. case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey:
  318. return key, nil
  319. default:
  320. return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
  321. }
  322. }
  323. if key, err := x509.ParseECPrivateKey(der); err == nil {
  324. return key, nil
  325. }
  326. return nil, errors.New("tls: failed to parse private key")
  327. }