ech_server.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. //go:build with_ech
  2. package tls
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "encoding/pem"
  7. "net"
  8. "os"
  9. "strings"
  10. cftls "github.com/sagernet/cloudflare-tls"
  11. "github.com/sagernet/fswatch"
  12. "github.com/sagernet/sing-box/log"
  13. "github.com/sagernet/sing-box/option"
  14. E "github.com/sagernet/sing/common/exceptions"
  15. "github.com/sagernet/sing/common/ntp"
  16. )
  17. type echServerConfig struct {
  18. config *cftls.Config
  19. logger log.Logger
  20. certificate []byte
  21. key []byte
  22. certificatePath string
  23. keyPath string
  24. echKeyPath string
  25. watcher *fswatch.Watcher
  26. }
  27. func (c *echServerConfig) ServerName() string {
  28. return c.config.ServerName
  29. }
  30. func (c *echServerConfig) SetServerName(serverName string) {
  31. c.config.ServerName = serverName
  32. }
  33. func (c *echServerConfig) NextProtos() []string {
  34. return c.config.NextProtos
  35. }
  36. func (c *echServerConfig) SetNextProtos(nextProto []string) {
  37. c.config.NextProtos = nextProto
  38. }
  39. func (c *echServerConfig) Config() (*STDConfig, error) {
  40. return nil, E.New("unsupported usage for ECH")
  41. }
  42. func (c *echServerConfig) Client(conn net.Conn) (Conn, error) {
  43. return &echConnWrapper{cftls.Client(conn, c.config)}, nil
  44. }
  45. func (c *echServerConfig) Server(conn net.Conn) (Conn, error) {
  46. return &echConnWrapper{cftls.Server(conn, c.config)}, nil
  47. }
  48. func (c *echServerConfig) Clone() Config {
  49. return &echServerConfig{
  50. config: c.config.Clone(),
  51. }
  52. }
  53. func (c *echServerConfig) Start() error {
  54. err := c.startWatcher()
  55. if err != nil {
  56. c.logger.Warn("create credentials watcher: ", err)
  57. }
  58. return nil
  59. }
  60. func (c *echServerConfig) startWatcher() error {
  61. var watchPath []string
  62. if c.certificatePath != "" {
  63. watchPath = append(watchPath, c.certificatePath)
  64. }
  65. if c.keyPath != "" {
  66. watchPath = append(watchPath, c.keyPath)
  67. }
  68. if c.echKeyPath != "" {
  69. watchPath = append(watchPath, c.echKeyPath)
  70. }
  71. if len(watchPath) == 0 {
  72. return nil
  73. }
  74. watcher, err := fswatch.NewWatcher(fswatch.Options{
  75. Path: watchPath,
  76. Callback: func(path string) {
  77. err := c.credentialsUpdated(path)
  78. if err != nil {
  79. c.logger.Error(E.Cause(err, "reload credentials"))
  80. }
  81. },
  82. })
  83. if err != nil {
  84. return err
  85. }
  86. err = watcher.Start()
  87. if err != nil {
  88. return err
  89. }
  90. c.watcher = watcher
  91. return nil
  92. }
  93. func (c *echServerConfig) credentialsUpdated(path string) error {
  94. if path == c.certificatePath || path == c.keyPath {
  95. if path == c.certificatePath {
  96. certificate, err := os.ReadFile(c.certificatePath)
  97. if err != nil {
  98. return err
  99. }
  100. c.certificate = certificate
  101. } else {
  102. key, err := os.ReadFile(c.keyPath)
  103. if err != nil {
  104. return err
  105. }
  106. c.key = key
  107. }
  108. keyPair, err := cftls.X509KeyPair(c.certificate, c.key)
  109. if err != nil {
  110. return E.Cause(err, "parse key pair")
  111. }
  112. c.config.Certificates = []cftls.Certificate{keyPair}
  113. c.logger.Info("reloaded TLS certificate")
  114. } else {
  115. echKeyContent, err := os.ReadFile(c.echKeyPath)
  116. if err != nil {
  117. return err
  118. }
  119. block, rest := pem.Decode(echKeyContent)
  120. if block == nil || block.Type != "ECH KEYS" || len(rest) > 0 {
  121. return E.New("invalid ECH keys pem")
  122. }
  123. echKeys, err := cftls.EXP_UnmarshalECHKeys(block.Bytes)
  124. if err != nil {
  125. return E.Cause(err, "parse ECH keys")
  126. }
  127. echKeySet, err := cftls.EXP_NewECHKeySet(echKeys)
  128. if err != nil {
  129. return E.Cause(err, "create ECH key set")
  130. }
  131. c.config.ServerECHProvider = echKeySet
  132. c.logger.Info("reloaded ECH keys")
  133. }
  134. return nil
  135. }
  136. func (c *echServerConfig) Close() error {
  137. var err error
  138. if c.watcher != nil {
  139. err = E.Append(err, c.watcher.Close(), func(err error) error {
  140. return E.Cause(err, "close credentials watcher")
  141. })
  142. }
  143. return err
  144. }
  145. func NewECHServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) {
  146. if !options.Enabled {
  147. return nil, nil
  148. }
  149. var tlsConfig cftls.Config
  150. if options.ACME != nil && len(options.ACME.Domain) > 0 {
  151. return nil, E.New("acme is unavailable in ech")
  152. }
  153. tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
  154. if options.ServerName != "" {
  155. tlsConfig.ServerName = options.ServerName
  156. }
  157. if len(options.ALPN) > 0 {
  158. tlsConfig.NextProtos = append(options.ALPN, tlsConfig.NextProtos...)
  159. }
  160. if options.MinVersion != "" {
  161. minVersion, err := ParseTLSVersion(options.MinVersion)
  162. if err != nil {
  163. return nil, E.Cause(err, "parse min_version")
  164. }
  165. tlsConfig.MinVersion = minVersion
  166. }
  167. if options.MaxVersion != "" {
  168. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  169. if err != nil {
  170. return nil, E.Cause(err, "parse max_version")
  171. }
  172. tlsConfig.MaxVersion = maxVersion
  173. }
  174. if options.CipherSuites != nil {
  175. find:
  176. for _, cipherSuite := range options.CipherSuites {
  177. for _, tlsCipherSuite := range tls.CipherSuites() {
  178. if cipherSuite == tlsCipherSuite.Name {
  179. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  180. continue find
  181. }
  182. }
  183. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  184. }
  185. }
  186. var certificate []byte
  187. var key []byte
  188. if len(options.Certificate) > 0 {
  189. certificate = []byte(strings.Join(options.Certificate, "\n"))
  190. } else if options.CertificatePath != "" {
  191. content, err := os.ReadFile(options.CertificatePath)
  192. if err != nil {
  193. return nil, E.Cause(err, "read certificate")
  194. }
  195. certificate = content
  196. }
  197. if len(options.Key) > 0 {
  198. key = []byte(strings.Join(options.Key, "\n"))
  199. } else if options.KeyPath != "" {
  200. content, err := os.ReadFile(options.KeyPath)
  201. if err != nil {
  202. return nil, E.Cause(err, "read key")
  203. }
  204. key = content
  205. }
  206. if certificate == nil {
  207. return nil, E.New("missing certificate")
  208. } else if key == nil {
  209. return nil, E.New("missing key")
  210. }
  211. keyPair, err := cftls.X509KeyPair(certificate, key)
  212. if err != nil {
  213. return nil, E.Cause(err, "parse x509 key pair")
  214. }
  215. tlsConfig.Certificates = []cftls.Certificate{keyPair}
  216. var echKey []byte
  217. if len(options.ECH.Key) > 0 {
  218. echKey = []byte(strings.Join(options.ECH.Key, "\n"))
  219. } else if options.ECH.KeyPath != "" {
  220. content, err := os.ReadFile(options.ECH.KeyPath)
  221. if err != nil {
  222. return nil, E.Cause(err, "read ECH key")
  223. }
  224. echKey = content
  225. } else {
  226. return nil, E.New("missing ECH key")
  227. }
  228. block, rest := pem.Decode(echKey)
  229. if block == nil || block.Type != "ECH KEYS" || len(rest) > 0 {
  230. return nil, E.New("invalid ECH keys pem")
  231. }
  232. echKeys, err := cftls.EXP_UnmarshalECHKeys(block.Bytes)
  233. if err != nil {
  234. return nil, E.Cause(err, "parse ECH keys")
  235. }
  236. echKeySet, err := cftls.EXP_NewECHKeySet(echKeys)
  237. if err != nil {
  238. return nil, E.Cause(err, "create ECH key set")
  239. }
  240. tlsConfig.ECHEnabled = true
  241. tlsConfig.PQSignatureSchemesEnabled = options.ECH.PQSignatureSchemesEnabled
  242. tlsConfig.DynamicRecordSizingDisabled = options.ECH.DynamicRecordSizingDisabled
  243. tlsConfig.ServerECHProvider = echKeySet
  244. return &echServerConfig{
  245. config: &tlsConfig,
  246. logger: logger,
  247. certificate: certificate,
  248. key: key,
  249. certificatePath: options.CertificatePath,
  250. keyPath: options.KeyPath,
  251. echKeyPath: options.ECH.KeyPath,
  252. }, nil
  253. }