tls.go 9.6 KB

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