std_server.go 6.0 KB

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