std_server.go 6.2 KB

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