1
0

std_server.go 6.5 KB

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