tlsutil.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package tlsutil
  7. import (
  8. "crypto/ecdsa"
  9. "crypto/elliptic"
  10. "crypto/rsa"
  11. "crypto/tls"
  12. "crypto/x509"
  13. "crypto/x509/pkix"
  14. "encoding/pem"
  15. "math/big"
  16. "net"
  17. "os"
  18. "time"
  19. "github.com/pkg/errors"
  20. "github.com/syncthing/syncthing/lib/rand"
  21. )
  22. var (
  23. ErrIdentificationFailed = errors.New("failed to identify socket type")
  24. )
  25. var (
  26. // The list of cipher suites we will use / suggest for TLS 1.2 connections.
  27. cipherSuites = []uint16{
  28. // Suites that are good and fast on hardware *without* AES-NI.
  29. tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  30. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  31. // Suites that are good and fast on hardware with AES-NI. These are
  32. // reordered from the Go default to put the 256 bit ciphers above the
  33. // 128 bit ones - because that looks cooler, even though there is
  34. // probably no relevant difference in strength yet.
  35. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  36. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  37. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  38. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  39. // The rest of the suites, minus DES stuff.
  40. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
  41. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  42. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
  43. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  44. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  45. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  46. tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
  47. tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
  48. tls.TLS_RSA_WITH_AES_128_CBC_SHA256,
  49. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  50. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  51. }
  52. )
  53. // SecureDefault returns a tls.Config with reasonable, secure defaults set.
  54. // This variant allows only TLS 1.3.
  55. func SecureDefaultTLS13() *tls.Config {
  56. return &tls.Config{
  57. // TLS 1.3 is the minimum we accept
  58. MinVersion: tls.VersionTLS13,
  59. }
  60. }
  61. // SecureDefaultWithTLS12 returns a tls.Config with reasonable, secure
  62. // defaults set. This variant allows TLS 1.2.
  63. func SecureDefaultWithTLS12() *tls.Config {
  64. // paranoia
  65. cs := make([]uint16, len(cipherSuites))
  66. copy(cs, cipherSuites)
  67. return &tls.Config{
  68. // TLS 1.2 is the minimum we accept
  69. MinVersion: tls.VersionTLS12,
  70. // The cipher suite lists built above. These are ignored in TLS 1.3.
  71. CipherSuites: cs,
  72. // We've put some thought into this choice and would like it to
  73. // matter.
  74. PreferServerCipherSuites: true,
  75. }
  76. }
  77. // NewCertificate generates and returns a new TLS certificate.
  78. func NewCertificate(certFile, keyFile, commonName string, lifetimeDays int) (tls.Certificate, error) {
  79. priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
  80. if err != nil {
  81. return tls.Certificate{}, errors.Wrap(err, "generate key")
  82. }
  83. notBefore := time.Now().Truncate(24 * time.Hour)
  84. notAfter := notBefore.Add(time.Duration(lifetimeDays*24) * time.Hour)
  85. // NOTE: update lib/api.shouldRegenerateCertificate() appropriately if
  86. // you add or change attributes in here, especially DNSNames or
  87. // IPAddresses.
  88. template := x509.Certificate{
  89. SerialNumber: new(big.Int).SetUint64(rand.Uint64()),
  90. Subject: pkix.Name{
  91. CommonName: commonName,
  92. Organization: []string{"Syncthing"},
  93. OrganizationalUnit: []string{"Automatically Generated"},
  94. },
  95. DNSNames: []string{commonName},
  96. NotBefore: notBefore,
  97. NotAfter: notAfter,
  98. SignatureAlgorithm: x509.ECDSAWithSHA256,
  99. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  100. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
  101. BasicConstraintsValid: true,
  102. }
  103. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
  104. if err != nil {
  105. return tls.Certificate{}, errors.Wrap(err, "create cert")
  106. }
  107. certOut, err := os.Create(certFile)
  108. if err != nil {
  109. return tls.Certificate{}, errors.Wrap(err, "save cert")
  110. }
  111. err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  112. if err != nil {
  113. return tls.Certificate{}, errors.Wrap(err, "save cert")
  114. }
  115. err = certOut.Close()
  116. if err != nil {
  117. return tls.Certificate{}, errors.Wrap(err, "save cert")
  118. }
  119. keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  120. if err != nil {
  121. return tls.Certificate{}, errors.Wrap(err, "save key")
  122. }
  123. block, err := pemBlockForKey(priv)
  124. if err != nil {
  125. return tls.Certificate{}, errors.Wrap(err, "save key")
  126. }
  127. err = pem.Encode(keyOut, block)
  128. if err != nil {
  129. return tls.Certificate{}, errors.Wrap(err, "save key")
  130. }
  131. err = keyOut.Close()
  132. if err != nil {
  133. return tls.Certificate{}, errors.Wrap(err, "save key")
  134. }
  135. return tls.LoadX509KeyPair(certFile, keyFile)
  136. }
  137. type DowngradingListener struct {
  138. net.Listener
  139. TLSConfig *tls.Config
  140. }
  141. func (l *DowngradingListener) Accept() (net.Conn, error) {
  142. conn, isTLS, err := l.AcceptNoWrapTLS()
  143. // We failed to identify the socket type, pretend that everything is fine,
  144. // and pass it to the underlying handler, and let them deal with it.
  145. if err == ErrIdentificationFailed {
  146. return conn, nil
  147. }
  148. if err != nil {
  149. return conn, err
  150. }
  151. if isTLS {
  152. return tls.Server(conn, l.TLSConfig), nil
  153. }
  154. return conn, nil
  155. }
  156. func (l *DowngradingListener) AcceptNoWrapTLS() (net.Conn, bool, error) {
  157. conn, err := l.Listener.Accept()
  158. if err != nil {
  159. return nil, false, err
  160. }
  161. var first [1]byte
  162. conn.SetReadDeadline(time.Now().Add(1 * time.Second))
  163. n, err := conn.Read(first[:])
  164. conn.SetReadDeadline(time.Time{})
  165. if err != nil || n == 0 {
  166. // We hit a read error here, but the Accept() call succeeded so we must not return an error.
  167. // We return the connection as is with a special error which handles this
  168. // special case in Accept().
  169. return conn, false, ErrIdentificationFailed
  170. }
  171. return &UnionedConnection{&first, conn}, first[0] == 0x16, nil
  172. }
  173. type UnionedConnection struct {
  174. first *[1]byte
  175. net.Conn
  176. }
  177. func (c *UnionedConnection) Read(b []byte) (n int, err error) {
  178. if c.first != nil {
  179. if len(b) == 0 {
  180. // this probably doesn't happen, but handle it anyway
  181. return 0, nil
  182. }
  183. b[0] = c.first[0]
  184. c.first = nil
  185. return 1, nil
  186. }
  187. return c.Conn.Read(b)
  188. }
  189. func publicKey(priv interface{}) interface{} {
  190. switch k := priv.(type) {
  191. case *rsa.PrivateKey:
  192. return &k.PublicKey
  193. case *ecdsa.PrivateKey:
  194. return &k.PublicKey
  195. default:
  196. return nil
  197. }
  198. }
  199. func pemBlockForKey(priv interface{}) (*pem.Block, error) {
  200. switch k := priv.(type) {
  201. case *rsa.PrivateKey:
  202. return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}, nil
  203. case *ecdsa.PrivateKey:
  204. b, err := x509.MarshalECPrivateKey(k)
  205. if err != nil {
  206. return nil, err
  207. }
  208. return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}, nil
  209. default:
  210. return nil, errors.New("unknown key type")
  211. }
  212. }