std_server.go 6.1 KB

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