tlsutil.go 9.2 KB

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