tlsutil.go 9.2 KB

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