tlsutil.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 connections.
  27. // This is built based on the component slices below, depending on what
  28. // the hardware prefers.
  29. cipherSuites []uint16
  30. // Suites that are good and fast on hardware with AES-NI. These are
  31. // reordered from the Go default to put the 256 bit ciphers above the
  32. // 128 bit ones - because that looks cooler, even though there is
  33. // probably no relevant difference in strength yet.
  34. gcmSuites = []uint16{
  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. }
  40. // Suites that are good and fast on hardware *without* AES-NI.
  41. chaChaSuites = []uint16{
  42. tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  43. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  44. }
  45. // The rest of the suites, minus DES stuff.
  46. otherSuites = []uint16{
  47. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
  48. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  49. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
  50. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  51. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  52. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  53. tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
  54. tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
  55. tls.TLS_RSA_WITH_AES_128_CBC_SHA256,
  56. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  57. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  58. }
  59. )
  60. func init() {
  61. // Creates the list of ciper suites that SecureDefault uses.
  62. cipherSuites = buildCipherSuites()
  63. }
  64. // SecureDefault returns a tls.Config with reasonable, secure defaults set.
  65. func SecureDefault() *tls.Config {
  66. // paranoia
  67. cs := make([]uint16, len(cipherSuites))
  68. copy(cs, cipherSuites)
  69. return &tls.Config{
  70. // TLS 1.2 is the minimum we accept
  71. MinVersion: tls.VersionTLS12,
  72. // The cipher suite lists built above. These are ignored in TLS 1.3.
  73. CipherSuites: cs,
  74. // We've put some thought into this choice and would like it to
  75. // matter.
  76. PreferServerCipherSuites: true,
  77. }
  78. }
  79. // NewCertificate generates and returns a new TLS certificate.
  80. func NewCertificate(certFile, keyFile, commonName string, lifetimeDays int) (tls.Certificate, error) {
  81. priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
  82. if err != nil {
  83. return tls.Certificate{}, errors.Wrap(err, "generate key")
  84. }
  85. notBefore := time.Now().Truncate(24 * time.Hour)
  86. notAfter := notBefore.Add(time.Duration(lifetimeDays*24) * time.Hour)
  87. // NOTE: update lib/api.shouldRegenerateCertificate() appropriately if
  88. // you add or change attributes in here, especially DNSNames or
  89. // IPAddresses.
  90. template := x509.Certificate{
  91. SerialNumber: new(big.Int).SetUint64(rand.Uint64()),
  92. Subject: pkix.Name{
  93. CommonName: commonName,
  94. Organization: []string{"Syncthing"},
  95. OrganizationalUnit: []string{"Automatically Generated"},
  96. },
  97. DNSNames: []string{commonName},
  98. NotBefore: notBefore,
  99. NotAfter: notAfter,
  100. SignatureAlgorithm: x509.ECDSAWithSHA256,
  101. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  102. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
  103. BasicConstraintsValid: true,
  104. }
  105. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
  106. if err != nil {
  107. return tls.Certificate{}, errors.Wrap(err, "create cert")
  108. }
  109. certOut, err := os.Create(certFile)
  110. if err != nil {
  111. return tls.Certificate{}, errors.Wrap(err, "save cert")
  112. }
  113. err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  114. if err != nil {
  115. return tls.Certificate{}, errors.Wrap(err, "save cert")
  116. }
  117. err = certOut.Close()
  118. if err != nil {
  119. return tls.Certificate{}, errors.Wrap(err, "save cert")
  120. }
  121. keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  122. if err != nil {
  123. return tls.Certificate{}, errors.Wrap(err, "save key")
  124. }
  125. block, err := pemBlockForKey(priv)
  126. if err != nil {
  127. return tls.Certificate{}, errors.Wrap(err, "save key")
  128. }
  129. err = pem.Encode(keyOut, block)
  130. if err != nil {
  131. return tls.Certificate{}, errors.Wrap(err, "save key")
  132. }
  133. err = keyOut.Close()
  134. if err != nil {
  135. return tls.Certificate{}, errors.Wrap(err, "save key")
  136. }
  137. return tls.LoadX509KeyPair(certFile, keyFile)
  138. }
  139. type DowngradingListener struct {
  140. net.Listener
  141. TLSConfig *tls.Config
  142. }
  143. func (l *DowngradingListener) Accept() (net.Conn, error) {
  144. conn, isTLS, err := l.AcceptNoWrapTLS()
  145. // We failed to identify the socket type, pretend that everything is fine,
  146. // and pass it to the underlying handler, and let them deal with it.
  147. if err == ErrIdentificationFailed {
  148. return conn, nil
  149. }
  150. if err != nil {
  151. return conn, err
  152. }
  153. if isTLS {
  154. return tls.Server(conn, l.TLSConfig), nil
  155. }
  156. return conn, nil
  157. }
  158. func (l *DowngradingListener) AcceptNoWrapTLS() (net.Conn, bool, error) {
  159. conn, err := l.Listener.Accept()
  160. if err != nil {
  161. return nil, false, err
  162. }
  163. var first [1]byte
  164. conn.SetReadDeadline(time.Now().Add(1 * time.Second))
  165. n, err := conn.Read(first[:])
  166. conn.SetReadDeadline(time.Time{})
  167. if err != nil || n == 0 {
  168. // We hit a read error here, but the Accept() call succeeded so we must not return an error.
  169. // We return the connection as is with a special error which handles this
  170. // special case in Accept().
  171. return conn, false, ErrIdentificationFailed
  172. }
  173. return &UnionedConnection{&first, conn}, first[0] == 0x16, nil
  174. }
  175. type UnionedConnection struct {
  176. first *[1]byte
  177. net.Conn
  178. }
  179. func (c *UnionedConnection) Read(b []byte) (n int, err error) {
  180. if c.first != nil {
  181. if len(b) == 0 {
  182. // this probably doesn't happen, but handle it anyway
  183. return 0, nil
  184. }
  185. b[0] = c.first[0]
  186. c.first = nil
  187. return 1, nil
  188. }
  189. return c.Conn.Read(b)
  190. }
  191. func publicKey(priv interface{}) interface{} {
  192. switch k := priv.(type) {
  193. case *rsa.PrivateKey:
  194. return &k.PublicKey
  195. case *ecdsa.PrivateKey:
  196. return &k.PublicKey
  197. default:
  198. return nil
  199. }
  200. }
  201. func pemBlockForKey(priv interface{}) (*pem.Block, error) {
  202. switch k := priv.(type) {
  203. case *rsa.PrivateKey:
  204. return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}, nil
  205. case *ecdsa.PrivateKey:
  206. b, err := x509.MarshalECPrivateKey(k)
  207. if err != nil {
  208. return nil, err
  209. }
  210. return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}, nil
  211. default:
  212. return nil, errors.New("unknown key type")
  213. }
  214. }
  215. // buildCipherSuites returns a list of cipher suites with either AES-GCM or
  216. // ChaCha20 at the top. This takes advantage of the CPU detection that the
  217. // TLS package does to create an optimal cipher suite list for the current
  218. // hardware.
  219. func buildCipherSuites() []uint16 {
  220. pref := preferredCipherSuite()
  221. for _, suite := range gcmSuites {
  222. if suite == pref {
  223. // Go preferred an AES-GCM suite. Use those first.
  224. return append(gcmSuites, append(chaChaSuites, otherSuites...)...)
  225. }
  226. }
  227. // Use ChaCha20 at the top, then AES-GCM etc.
  228. return append(chaChaSuites, append(gcmSuites, otherSuites...)...)
  229. }
  230. // preferredCipherSuite returns the cipher suite that is selected for a TLS
  231. // connection made with the Go defaults to ourselves. This is (currently,
  232. // probably) either a ChaCha20 suite or an AES-GCM suite, depending on what
  233. // the CPU detection has decided is fastest on this hardware.
  234. //
  235. // The function will return zero if something odd happens, and there's no
  236. // guarantee what cipher suite would be chosen anyway, so the return value
  237. // should be taken with a grain of salt.
  238. func preferredCipherSuite() uint16 {
  239. // This is one of our certs from NewCertificate above, to avoid having
  240. // to generate one at init time just for this function.
  241. crtBs := []byte(`-----BEGIN CERTIFICATE-----
  242. MIIBXDCCAQOgAwIBAgIIQUODl2/bE4owCgYIKoZIzj0EAwIwFDESMBAGA1UEAxMJ
  243. c3luY3RoaW5nMB4XDTE4MTAxNDA2MjU0M1oXDTQ5MTIzMTIzNTk1OVowFDESMBAG
  244. A1UEAxMJc3luY3RoaW5nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEMqP+1lL4
  245. 0s/xtI3ygExzYc/GvLHr0qetpBrUVHaDwS/cR1yXDsYaJpJcUNtrf1XK49IlpWW1
  246. Ds8seQsSg7/9BaM/MD0wDgYDVR0PAQH/BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUF
  247. BwMBBggrBgEFBQcDAjAMBgNVHRMBAf8EAjAAMAoGCCqGSM49BAMCA0cAMEQCIFxY
  248. MDBA92FKqZYSZjmfdIbT1OI6S9CnAFvL/pJZJwNuAiAV7osre2NiCHtXABOvsGrH
  249. vKWqDvXcHr6Tlo+LmTAdyg==
  250. -----END CERTIFICATE-----
  251. `)
  252. keyBs := []byte(`-----BEGIN EC PRIVATE KEY-----
  253. MHcCAQEEIHtPxVHlj6Bhi9RgSR2/lAtIQ7APM9wmpaJAcds6TD2CoAoGCCqGSM49
  254. AwEHoUQDQgAEMqP+1lL40s/xtI3ygExzYc/GvLHr0qetpBrUVHaDwS/cR1yXDsYa
  255. JpJcUNtrf1XK49IlpWW1Ds8seQsSg7/9BQ==
  256. -----END EC PRIVATE KEY-----
  257. `)
  258. cert, err := tls.X509KeyPair(crtBs, keyBs)
  259. if err != nil {
  260. return 0
  261. }
  262. serverCfg := &tls.Config{
  263. MinVersion: tls.VersionTLS12,
  264. PreferServerCipherSuites: true,
  265. Certificates: []tls.Certificate{cert},
  266. }
  267. clientCfg := &tls.Config{
  268. MinVersion: tls.VersionTLS12,
  269. InsecureSkipVerify: true,
  270. }
  271. c0, c1 := net.Pipe()
  272. c := tls.Client(c0, clientCfg)
  273. go func() {
  274. c.Handshake()
  275. }()
  276. s := tls.Server(c1, serverCfg)
  277. if err := s.Handshake(); err != nil {
  278. return 0
  279. }
  280. return c.ConnectionState().CipherSuite
  281. }