tlsutil.go 9.4 KB

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