tlsutil.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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/rand"
  21. )
  22. var (
  23. ErrIdentificationFailed = fmt.Errorf("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. // We want the longer curves at the front, because that's more
  73. // secure (so the web tells me, don't ask me to explain the
  74. // details).
  75. CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
  76. // The cipher suite lists built above.
  77. CipherSuites: cs,
  78. // We've put some thought into this choice and would like it to
  79. // matter.
  80. PreferServerCipherSuites: true,
  81. }
  82. }
  83. // NewCertificate generates and returns a new TLS certificate.
  84. func NewCertificate(certFile, keyFile, commonName string) (tls.Certificate, error) {
  85. priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
  86. if err != nil {
  87. return tls.Certificate{}, fmt.Errorf("generate key: %s", err)
  88. }
  89. notBefore := time.Now()
  90. notAfter := time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC)
  91. template := x509.Certificate{
  92. SerialNumber: new(big.Int).SetInt64(rand.Int63()),
  93. Subject: pkix.Name{
  94. CommonName: commonName,
  95. },
  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{}, fmt.Errorf("create cert: %s", err)
  106. }
  107. certOut, err := os.Create(certFile)
  108. if err != nil {
  109. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  110. }
  111. err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  112. if err != nil {
  113. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  114. }
  115. err = certOut.Close()
  116. if err != nil {
  117. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  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{}, fmt.Errorf("save key: %s", err)
  122. }
  123. block, err := pemBlockForKey(priv)
  124. if err != nil {
  125. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  126. }
  127. err = pem.Encode(keyOut, block)
  128. if err != nil {
  129. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  130. }
  131. err = keyOut.Close()
  132. if err != nil {
  133. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  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, fmt.Errorf("unknown key type")
  211. }
  212. }
  213. // buildCipherSuites returns a list of cipher suites with either AES-GCM or
  214. // ChaCha20 at the top. This takes advantage of the CPU detection that the
  215. // TLS package does to create an optimal cipher suite list for the current
  216. // hardware.
  217. func buildCipherSuites() []uint16 {
  218. pref := preferredCipherSuite()
  219. for _, suite := range gcmSuites {
  220. if suite == pref {
  221. // Go preferred an AES-GCM suite. Use those first.
  222. return append(gcmSuites, append(chaChaSuites, otherSuites...)...)
  223. }
  224. }
  225. // Use ChaCha20 at the top, then AES-GCM etc.
  226. return append(chaChaSuites, append(gcmSuites, otherSuites...)...)
  227. }
  228. // preferredCipherSuite returns the cipher suite that is selected for a TLS
  229. // connection made with the Go defaults to ourselves. This is (currently,
  230. // probably) either a ChaCha20 suite or an AES-GCM suite, depending on what
  231. // the CPU detection has decided is fastest on this hardware.
  232. //
  233. // The function will return zero if something odd happens, and there's no
  234. // guarantee what cipher suite would be chosen anyway, so the return value
  235. // should be taken with a grain of salt.
  236. func preferredCipherSuite() uint16 {
  237. // This is one of our certs from NewCertificate above, to avoid having
  238. // to generate one at init time just for this function.
  239. crtBs := []byte(`-----BEGIN CERTIFICATE-----
  240. MIIBXDCCAQOgAwIBAgIIQUODl2/bE4owCgYIKoZIzj0EAwIwFDESMBAGA1UEAxMJ
  241. c3luY3RoaW5nMB4XDTE4MTAxNDA2MjU0M1oXDTQ5MTIzMTIzNTk1OVowFDESMBAG
  242. A1UEAxMJc3luY3RoaW5nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEMqP+1lL4
  243. 0s/xtI3ygExzYc/GvLHr0qetpBrUVHaDwS/cR1yXDsYaJpJcUNtrf1XK49IlpWW1
  244. Ds8seQsSg7/9BaM/MD0wDgYDVR0PAQH/BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUF
  245. BwMBBggrBgEFBQcDAjAMBgNVHRMBAf8EAjAAMAoGCCqGSM49BAMCA0cAMEQCIFxY
  246. MDBA92FKqZYSZjmfdIbT1OI6S9CnAFvL/pJZJwNuAiAV7osre2NiCHtXABOvsGrH
  247. vKWqDvXcHr6Tlo+LmTAdyg==
  248. -----END CERTIFICATE-----
  249. `)
  250. keyBs := []byte(`-----BEGIN EC PRIVATE KEY-----
  251. MHcCAQEEIHtPxVHlj6Bhi9RgSR2/lAtIQ7APM9wmpaJAcds6TD2CoAoGCCqGSM49
  252. AwEHoUQDQgAEMqP+1lL40s/xtI3ygExzYc/GvLHr0qetpBrUVHaDwS/cR1yXDsYa
  253. JpJcUNtrf1XK49IlpWW1Ds8seQsSg7/9BQ==
  254. -----END EC PRIVATE KEY-----
  255. `)
  256. cert, err := tls.X509KeyPair(crtBs, keyBs)
  257. if err != nil {
  258. return 0
  259. }
  260. serverCfg := &tls.Config{
  261. MinVersion: tls.VersionTLS12,
  262. PreferServerCipherSuites: true,
  263. Certificates: []tls.Certificate{cert},
  264. }
  265. clientCfg := &tls.Config{
  266. MinVersion: tls.VersionTLS12,
  267. InsecureSkipVerify: true,
  268. }
  269. c0, c1 := net.Pipe()
  270. c := tls.Client(c0, clientCfg)
  271. go func() {
  272. c.Handshake()
  273. }()
  274. s := tls.Server(c1, serverCfg)
  275. if err := s.Handshake(); err != nil {
  276. return 0
  277. }
  278. return c.ConnectionState().CipherSuite
  279. }