tlsutil.go 9.4 KB

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