std_server.go 5.3 KB

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