std_server.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package tls
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "net"
  6. "os"
  7. "github.com/sagernet/sing-box/adapter"
  8. "github.com/sagernet/sing-box/log"
  9. "github.com/sagernet/sing-box/option"
  10. "github.com/sagernet/sing/common"
  11. E "github.com/sagernet/sing/common/exceptions"
  12. "github.com/fsnotify/fsnotify"
  13. )
  14. type STDServerConfig struct {
  15. config *tls.Config
  16. logger log.Logger
  17. acmeService adapter.Service
  18. certificate []byte
  19. key []byte
  20. certificatePath string
  21. keyPath string
  22. watcher *fsnotify.Watcher
  23. }
  24. func NewServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) {
  25. if !options.Enabled {
  26. return nil, nil
  27. }
  28. var tlsConfig *tls.Config
  29. var acmeService adapter.Service
  30. var err error
  31. if options.ACME != nil && len(options.ACME.Domain) > 0 {
  32. tlsConfig, acmeService, err = startACME(ctx, common.PtrValueOrDefault(options.ACME))
  33. if err != nil {
  34. return nil, err
  35. }
  36. } else {
  37. tlsConfig = &tls.Config{}
  38. }
  39. if options.ServerName != "" {
  40. tlsConfig.ServerName = options.ServerName
  41. }
  42. if len(options.ALPN) > 0 {
  43. tlsConfig.NextProtos = append(tlsConfig.NextProtos, options.ALPN...)
  44. }
  45. if options.MinVersion != "" {
  46. minVersion, err := ParseTLSVersion(options.MinVersion)
  47. if err != nil {
  48. return nil, E.Cause(err, "parse min_version")
  49. }
  50. tlsConfig.MinVersion = minVersion
  51. }
  52. if options.MaxVersion != "" {
  53. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  54. if err != nil {
  55. return nil, E.Cause(err, "parse max_version")
  56. }
  57. tlsConfig.MaxVersion = maxVersion
  58. }
  59. if options.CipherSuites != nil {
  60. find:
  61. for _, cipherSuite := range options.CipherSuites {
  62. for _, tlsCipherSuite := range tls.CipherSuites() {
  63. if cipherSuite == tlsCipherSuite.Name {
  64. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  65. continue find
  66. }
  67. }
  68. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  69. }
  70. }
  71. var certificate []byte
  72. var key []byte
  73. if acmeService == nil {
  74. if options.Certificate != "" {
  75. certificate = []byte(options.Certificate)
  76. } else if options.CertificatePath != "" {
  77. content, err := os.ReadFile(options.CertificatePath)
  78. if err != nil {
  79. return nil, E.Cause(err, "read certificate")
  80. }
  81. certificate = content
  82. }
  83. if options.Key != "" {
  84. key = []byte(options.Key)
  85. } else if options.KeyPath != "" {
  86. content, err := os.ReadFile(options.KeyPath)
  87. if err != nil {
  88. return nil, E.Cause(err, "read key")
  89. }
  90. key = content
  91. }
  92. if certificate == nil {
  93. return nil, E.New("missing certificate")
  94. }
  95. if key == nil {
  96. return nil, E.New("missing key")
  97. }
  98. keyPair, err := tls.X509KeyPair(certificate, key)
  99. if err != nil {
  100. return nil, E.Cause(err, "parse x509 key pair")
  101. }
  102. tlsConfig.Certificates = []tls.Certificate{keyPair}
  103. }
  104. return &STDServerConfig{
  105. config: tlsConfig,
  106. logger: logger,
  107. acmeService: acmeService,
  108. certificate: certificate,
  109. key: key,
  110. certificatePath: options.CertificatePath,
  111. keyPath: options.KeyPath,
  112. }, nil
  113. }
  114. func (c *STDServerConfig) Config() (*STDConfig, error) {
  115. return c.config, nil
  116. }
  117. func (c *STDServerConfig) Client(conn net.Conn) Conn {
  118. return tls.Client(conn, c.config)
  119. }
  120. func (c *STDServerConfig) Server(conn net.Conn) Conn {
  121. return tls.Server(conn, c.config)
  122. }
  123. func (c *STDServerConfig) Start() error {
  124. if c.acmeService != nil {
  125. return c.acmeService.Start()
  126. } else {
  127. if c.certificatePath == "" && c.keyPath == "" {
  128. return nil
  129. }
  130. err := c.startWatcher()
  131. if err != nil {
  132. c.logger.Warn("create fsnotify watcher: ", err)
  133. }
  134. return nil
  135. }
  136. }
  137. func (c *STDServerConfig) startWatcher() error {
  138. watcher, err := fsnotify.NewWatcher()
  139. if err != nil {
  140. return err
  141. }
  142. if c.certificatePath != "" {
  143. err = watcher.Add(c.certificatePath)
  144. if err != nil {
  145. return err
  146. }
  147. }
  148. if c.keyPath != "" {
  149. err = watcher.Add(c.keyPath)
  150. if err != nil {
  151. return err
  152. }
  153. }
  154. c.watcher = watcher
  155. go c.loopUpdate()
  156. return nil
  157. }
  158. func (c *STDServerConfig) loopUpdate() {
  159. for {
  160. select {
  161. case event, ok := <-c.watcher.Events:
  162. if !ok {
  163. return
  164. }
  165. if event.Op&fsnotify.Write != fsnotify.Write {
  166. continue
  167. }
  168. err := c.reloadKeyPair()
  169. if err != nil {
  170. c.logger.Error(E.Cause(err, "reload TLS key pair"))
  171. }
  172. case err, ok := <-c.watcher.Errors:
  173. if !ok {
  174. return
  175. }
  176. c.logger.Error(E.Cause(err, "fsnotify error"))
  177. }
  178. }
  179. }
  180. func (c *STDServerConfig) reloadKeyPair() error {
  181. if c.certificatePath != "" {
  182. certificate, err := os.ReadFile(c.certificatePath)
  183. if err != nil {
  184. return E.Cause(err, "reload certificate from ", c.certificatePath)
  185. }
  186. c.certificate = certificate
  187. }
  188. if c.keyPath != "" {
  189. key, err := os.ReadFile(c.keyPath)
  190. if err != nil {
  191. return E.Cause(err, "reload key from ", c.keyPath)
  192. }
  193. c.key = key
  194. }
  195. keyPair, err := tls.X509KeyPair(c.certificate, c.key)
  196. if err != nil {
  197. return E.Cause(err, "reload key pair")
  198. }
  199. c.config.Certificates = []tls.Certificate{keyPair}
  200. c.logger.Info("reloaded TLS certificate")
  201. return nil
  202. }
  203. func (c *STDServerConfig) Close() error {
  204. if c.acmeService != nil {
  205. return c.acmeService.Close()
  206. }
  207. if c.watcher != nil {
  208. return c.watcher.Close()
  209. }
  210. return nil
  211. }