ech_server.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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/sing-box/log"
  12. "github.com/sagernet/sing-box/option"
  13. E "github.com/sagernet/sing/common/exceptions"
  14. "github.com/sagernet/sing/common/ntp"
  15. "github.com/fsnotify/fsnotify"
  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. watcher *fsnotify.Watcher
  25. echKeyPath string
  26. echWatcher *fsnotify.Watcher
  27. }
  28. func (c *echServerConfig) ServerName() string {
  29. return c.config.ServerName
  30. }
  31. func (c *echServerConfig) SetServerName(serverName string) {
  32. c.config.ServerName = serverName
  33. }
  34. func (c *echServerConfig) NextProtos() []string {
  35. return c.config.NextProtos
  36. }
  37. func (c *echServerConfig) SetNextProtos(nextProto []string) {
  38. c.config.NextProtos = nextProto
  39. }
  40. func (c *echServerConfig) Config() (*STDConfig, error) {
  41. return nil, E.New("unsupported usage for ECH")
  42. }
  43. func (c *echServerConfig) Client(conn net.Conn) (Conn, error) {
  44. return &echConnWrapper{cftls.Client(conn, c.config)}, nil
  45. }
  46. func (c *echServerConfig) Server(conn net.Conn) (Conn, error) {
  47. return &echConnWrapper{cftls.Server(conn, c.config)}, nil
  48. }
  49. func (c *echServerConfig) Clone() Config {
  50. return &echServerConfig{
  51. config: c.config.Clone(),
  52. }
  53. }
  54. func (c *echServerConfig) Start() error {
  55. if c.certificatePath != "" && c.keyPath != "" {
  56. err := c.startWatcher()
  57. if err != nil {
  58. c.logger.Warn("create fsnotify watcher: ", err)
  59. }
  60. }
  61. if c.echKeyPath != "" {
  62. err := c.startECHWatcher()
  63. if err != nil {
  64. c.logger.Warn("create fsnotify watcher: ", err)
  65. }
  66. }
  67. return nil
  68. }
  69. func (c *echServerConfig) startWatcher() error {
  70. watcher, err := fsnotify.NewWatcher()
  71. if err != nil {
  72. return err
  73. }
  74. if c.certificatePath != "" {
  75. err = watcher.Add(c.certificatePath)
  76. if err != nil {
  77. return err
  78. }
  79. }
  80. if c.keyPath != "" {
  81. err = watcher.Add(c.keyPath)
  82. if err != nil {
  83. return err
  84. }
  85. }
  86. c.watcher = watcher
  87. go c.loopUpdate()
  88. return nil
  89. }
  90. func (c *echServerConfig) loopUpdate() {
  91. for {
  92. select {
  93. case event, ok := <-c.watcher.Events:
  94. if !ok {
  95. return
  96. }
  97. if event.Op&fsnotify.Write != fsnotify.Write {
  98. continue
  99. }
  100. err := c.reloadKeyPair()
  101. if err != nil {
  102. c.logger.Error(E.Cause(err, "reload TLS key pair"))
  103. }
  104. case err, ok := <-c.watcher.Errors:
  105. if !ok {
  106. return
  107. }
  108. c.logger.Error(E.Cause(err, "fsnotify error"))
  109. }
  110. }
  111. }
  112. func (c *echServerConfig) reloadKeyPair() error {
  113. if c.certificatePath != "" {
  114. certificate, err := os.ReadFile(c.certificatePath)
  115. if err != nil {
  116. return E.Cause(err, "reload certificate from ", c.certificatePath)
  117. }
  118. c.certificate = certificate
  119. }
  120. if c.keyPath != "" {
  121. key, err := os.ReadFile(c.keyPath)
  122. if err != nil {
  123. return E.Cause(err, "reload key from ", c.keyPath)
  124. }
  125. c.key = key
  126. }
  127. keyPair, err := cftls.X509KeyPair(c.certificate, c.key)
  128. if err != nil {
  129. return E.Cause(err, "reload key pair")
  130. }
  131. c.config.Certificates = []cftls.Certificate{keyPair}
  132. c.logger.Info("reloaded TLS certificate")
  133. return nil
  134. }
  135. func (c *echServerConfig) startECHWatcher() error {
  136. watcher, err := fsnotify.NewWatcher()
  137. if err != nil {
  138. return err
  139. }
  140. err = watcher.Add(c.echKeyPath)
  141. if err != nil {
  142. return err
  143. }
  144. c.echWatcher = watcher
  145. go c.loopECHUpdate()
  146. return nil
  147. }
  148. func (c *echServerConfig) loopECHUpdate() {
  149. for {
  150. select {
  151. case event, ok := <-c.echWatcher.Events:
  152. if !ok {
  153. return
  154. }
  155. if event.Op&fsnotify.Write != fsnotify.Write {
  156. continue
  157. }
  158. err := c.reloadECHKey()
  159. if err != nil {
  160. c.logger.Error(E.Cause(err, "reload ECH key"))
  161. }
  162. case err, ok := <-c.echWatcher.Errors:
  163. if !ok {
  164. return
  165. }
  166. c.logger.Error(E.Cause(err, "fsnotify error"))
  167. }
  168. }
  169. }
  170. func (c *echServerConfig) reloadECHKey() error {
  171. echKeyContent, err := os.ReadFile(c.echKeyPath)
  172. if err != nil {
  173. return err
  174. }
  175. block, rest := pem.Decode(echKeyContent)
  176. if block == nil || block.Type != "ECH KEYS" || len(rest) > 0 {
  177. return E.New("invalid ECH keys pem")
  178. }
  179. echKeys, err := cftls.EXP_UnmarshalECHKeys(block.Bytes)
  180. if err != nil {
  181. return E.Cause(err, "parse ECH keys")
  182. }
  183. echKeySet, err := cftls.EXP_NewECHKeySet(echKeys)
  184. if err != nil {
  185. return E.Cause(err, "create ECH key set")
  186. }
  187. c.config.ServerECHProvider = echKeySet
  188. c.logger.Info("reloaded ECH keys")
  189. return nil
  190. }
  191. func (c *echServerConfig) Close() error {
  192. var err error
  193. if c.watcher != nil {
  194. err = E.Append(err, c.watcher.Close(), func(err error) error {
  195. return E.Cause(err, "close certificate watcher")
  196. })
  197. }
  198. if c.echWatcher != nil {
  199. err = E.Append(err, c.echWatcher.Close(), func(err error) error {
  200. return E.Cause(err, "close ECH key watcher")
  201. })
  202. }
  203. return err
  204. }
  205. func NewECHServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) {
  206. if !options.Enabled {
  207. return nil, nil
  208. }
  209. var tlsConfig cftls.Config
  210. if options.ACME != nil && len(options.ACME.Domain) > 0 {
  211. return nil, E.New("acme is unavailable in ech")
  212. }
  213. tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
  214. if options.ServerName != "" {
  215. tlsConfig.ServerName = options.ServerName
  216. }
  217. if len(options.ALPN) > 0 {
  218. tlsConfig.NextProtos = append(options.ALPN, tlsConfig.NextProtos...)
  219. }
  220. if options.MinVersion != "" {
  221. minVersion, err := ParseTLSVersion(options.MinVersion)
  222. if err != nil {
  223. return nil, E.Cause(err, "parse min_version")
  224. }
  225. tlsConfig.MinVersion = minVersion
  226. }
  227. if options.MaxVersion != "" {
  228. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  229. if err != nil {
  230. return nil, E.Cause(err, "parse max_version")
  231. }
  232. tlsConfig.MaxVersion = maxVersion
  233. }
  234. if options.CipherSuites != nil {
  235. find:
  236. for _, cipherSuite := range options.CipherSuites {
  237. for _, tlsCipherSuite := range tls.CipherSuites() {
  238. if cipherSuite == tlsCipherSuite.Name {
  239. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  240. continue find
  241. }
  242. }
  243. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  244. }
  245. }
  246. var certificate []byte
  247. var key []byte
  248. if len(options.Certificate) > 0 {
  249. certificate = []byte(strings.Join(options.Certificate, "\n"))
  250. } else if options.CertificatePath != "" {
  251. content, err := os.ReadFile(options.CertificatePath)
  252. if err != nil {
  253. return nil, E.Cause(err, "read certificate")
  254. }
  255. certificate = content
  256. }
  257. if len(options.Key) > 0 {
  258. key = []byte(strings.Join(options.Key, "\n"))
  259. } else if options.KeyPath != "" {
  260. content, err := os.ReadFile(options.KeyPath)
  261. if err != nil {
  262. return nil, E.Cause(err, "read key")
  263. }
  264. key = content
  265. }
  266. if certificate == nil {
  267. return nil, E.New("missing certificate")
  268. } else if key == nil {
  269. return nil, E.New("missing key")
  270. }
  271. keyPair, err := cftls.X509KeyPair(certificate, key)
  272. if err != nil {
  273. return nil, E.Cause(err, "parse x509 key pair")
  274. }
  275. tlsConfig.Certificates = []cftls.Certificate{keyPair}
  276. var echKey []byte
  277. if len(options.ECH.Key) > 0 {
  278. echKey = []byte(strings.Join(options.ECH.Key, "\n"))
  279. } else if options.KeyPath != "" {
  280. content, err := os.ReadFile(options.ECH.KeyPath)
  281. if err != nil {
  282. return nil, E.Cause(err, "read ECH key")
  283. }
  284. echKey = content
  285. } else {
  286. return nil, E.New("missing ECH key")
  287. }
  288. block, rest := pem.Decode(echKey)
  289. if block == nil || block.Type != "ECH KEYS" || len(rest) > 0 {
  290. return nil, E.New("invalid ECH keys pem")
  291. }
  292. echKeys, err := cftls.EXP_UnmarshalECHKeys(block.Bytes)
  293. if err != nil {
  294. return nil, E.Cause(err, "parse ECH keys")
  295. }
  296. echKeySet, err := cftls.EXP_NewECHKeySet(echKeys)
  297. if err != nil {
  298. return nil, E.Cause(err, "create ECH key set")
  299. }
  300. tlsConfig.ECHEnabled = true
  301. tlsConfig.PQSignatureSchemesEnabled = options.ECH.PQSignatureSchemesEnabled
  302. tlsConfig.DynamicRecordSizingDisabled = options.ECH.DynamicRecordSizingDisabled
  303. tlsConfig.ServerECHProvider = echKeySet
  304. return &echServerConfig{
  305. config: &tlsConfig,
  306. logger: logger,
  307. certificate: certificate,
  308. key: key,
  309. certificatePath: options.CertificatePath,
  310. keyPath: options.KeyPath,
  311. echKeyPath: options.ECH.KeyPath,
  312. }, nil
  313. }