tlsutil.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. // NewCertificate generates and returns a new TLS certificate. If tlsRSABits
  26. // is greater than zero we generate an RSA certificate with the specified
  27. // number of bits. Otherwise we create a 384 bit ECDSA certificate.
  28. func NewCertificate(certFile, keyFile, tlsDefaultCommonName string, tlsRSABits int) (tls.Certificate, error) {
  29. var priv interface{}
  30. var err error
  31. if tlsRSABits > 0 {
  32. priv, err = rsa.GenerateKey(rand.Reader, tlsRSABits)
  33. } else {
  34. priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
  35. }
  36. if err != nil {
  37. return tls.Certificate{}, fmt.Errorf("generate key: %s", err)
  38. }
  39. notBefore := time.Now()
  40. notAfter := time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC)
  41. template := x509.Certificate{
  42. SerialNumber: new(big.Int).SetInt64(rand.Int63()),
  43. Subject: pkix.Name{
  44. CommonName: tlsDefaultCommonName,
  45. },
  46. NotBefore: notBefore,
  47. NotAfter: notAfter,
  48. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  49. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
  50. BasicConstraintsValid: true,
  51. }
  52. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
  53. if err != nil {
  54. return tls.Certificate{}, fmt.Errorf("create cert: %s", err)
  55. }
  56. certOut, err := os.Create(certFile)
  57. if err != nil {
  58. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  59. }
  60. err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  61. if err != nil {
  62. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  63. }
  64. err = certOut.Close()
  65. if err != nil {
  66. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  67. }
  68. keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  69. if err != nil {
  70. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  71. }
  72. block, err := pemBlockForKey(priv)
  73. if err != nil {
  74. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  75. }
  76. err = pem.Encode(keyOut, block)
  77. if err != nil {
  78. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  79. }
  80. err = keyOut.Close()
  81. if err != nil {
  82. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  83. }
  84. return tls.LoadX509KeyPair(certFile, keyFile)
  85. }
  86. type DowngradingListener struct {
  87. net.Listener
  88. TLSConfig *tls.Config
  89. }
  90. func (l *DowngradingListener) Accept() (net.Conn, error) {
  91. conn, isTLS, err := l.AcceptNoWrapTLS()
  92. // We failed to identify the socket type, pretend that everything is fine,
  93. // and pass it to the underlying handler, and let them deal with it.
  94. if err == ErrIdentificationFailed {
  95. return conn, nil
  96. }
  97. if err != nil {
  98. return conn, err
  99. }
  100. if isTLS {
  101. return tls.Server(conn, l.TLSConfig), nil
  102. }
  103. return conn, nil
  104. }
  105. func (l *DowngradingListener) AcceptNoWrapTLS() (net.Conn, bool, error) {
  106. conn, err := l.Listener.Accept()
  107. if err != nil {
  108. return nil, false, err
  109. }
  110. var first [1]byte
  111. conn.SetReadDeadline(time.Now().Add(1 * time.Second))
  112. n, err := conn.Read(first[:])
  113. conn.SetReadDeadline(time.Time{})
  114. if err != nil || n == 0 {
  115. // We hit a read error here, but the Accept() call succeeded so we must not return an error.
  116. // We return the connection as is with a special error which handles this
  117. // special case in Accept().
  118. return conn, false, ErrIdentificationFailed
  119. }
  120. return &UnionedConnection{&first, conn}, first[0] == 0x16, nil
  121. }
  122. type UnionedConnection struct {
  123. first *[1]byte
  124. net.Conn
  125. }
  126. func (c *UnionedConnection) Read(b []byte) (n int, err error) {
  127. if c.first != nil {
  128. if len(b) == 0 {
  129. // this probably doesn't happen, but handle it anyway
  130. return 0, nil
  131. }
  132. b[0] = c.first[0]
  133. c.first = nil
  134. return 1, nil
  135. }
  136. return c.Conn.Read(b)
  137. }
  138. func publicKey(priv interface{}) interface{} {
  139. switch k := priv.(type) {
  140. case *rsa.PrivateKey:
  141. return &k.PublicKey
  142. case *ecdsa.PrivateKey:
  143. return &k.PublicKey
  144. default:
  145. return nil
  146. }
  147. }
  148. func pemBlockForKey(priv interface{}) (*pem.Block, error) {
  149. switch k := priv.(type) {
  150. case *rsa.PrivateKey:
  151. return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}, nil
  152. case *ecdsa.PrivateKey:
  153. b, err := x509.MarshalECPrivateKey(k)
  154. if err != nil {
  155. return nil, err
  156. }
  157. return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}, nil
  158. default:
  159. return nil, fmt.Errorf("unknown key type")
  160. }
  161. }