std_server.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. package tls
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "net"
  6. "os"
  7. "strings"
  8. "github.com/sagernet/fswatch"
  9. "github.com/sagernet/sing-box/adapter"
  10. "github.com/sagernet/sing-box/log"
  11. "github.com/sagernet/sing-box/option"
  12. "github.com/sagernet/sing/common"
  13. E "github.com/sagernet/sing/common/exceptions"
  14. "github.com/sagernet/sing/common/ntp"
  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 *fswatch.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. var watchPath []string
  77. if c.certificatePath != "" {
  78. watchPath = append(watchPath, c.certificatePath)
  79. }
  80. if c.keyPath != "" {
  81. watchPath = append(watchPath, c.keyPath)
  82. }
  83. watcher, err := fswatch.NewWatcher(fswatch.Options{
  84. Path: watchPath,
  85. Callback: func(path string) {
  86. err := c.certificateUpdated(path)
  87. if err != nil {
  88. c.logger.Error(err)
  89. }
  90. },
  91. })
  92. if err != nil {
  93. return err
  94. }
  95. err = watcher.Start()
  96. if err != nil {
  97. return err
  98. }
  99. c.watcher = watcher
  100. return nil
  101. }
  102. func (c *STDServerConfig) certificateUpdated(path string) error {
  103. if path == c.certificatePath {
  104. certificate, err := os.ReadFile(c.certificatePath)
  105. if err != nil {
  106. return E.Cause(err, "reload certificate from ", c.certificatePath)
  107. }
  108. c.certificate = certificate
  109. } else if path == c.keyPath {
  110. key, err := os.ReadFile(c.keyPath)
  111. if err != nil {
  112. return E.Cause(err, "reload key from ", c.keyPath)
  113. }
  114. c.key = key
  115. }
  116. keyPair, err := tls.X509KeyPair(c.certificate, c.key)
  117. if err != nil {
  118. return E.Cause(err, "reload key pair")
  119. }
  120. c.config.Certificates = []tls.Certificate{keyPair}
  121. c.logger.Info("reloaded TLS certificate")
  122. return nil
  123. }
  124. func (c *STDServerConfig) Close() error {
  125. if c.acmeService != nil {
  126. return c.acmeService.Close()
  127. }
  128. if c.watcher != nil {
  129. return c.watcher.Close()
  130. }
  131. return nil
  132. }
  133. func NewSTDServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) {
  134. if !options.Enabled {
  135. return nil, nil
  136. }
  137. var tlsConfig *tls.Config
  138. var acmeService adapter.Service
  139. var err error
  140. if options.ACME != nil && len(options.ACME.Domain) > 0 {
  141. //nolint:staticcheck
  142. tlsConfig, acmeService, err = startACME(ctx, common.PtrValueOrDefault(options.ACME))
  143. if err != nil {
  144. return nil, err
  145. }
  146. if options.Insecure {
  147. return nil, errInsecureUnused
  148. }
  149. } else {
  150. tlsConfig = &tls.Config{}
  151. }
  152. tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
  153. if options.ServerName != "" {
  154. tlsConfig.ServerName = options.ServerName
  155. }
  156. if len(options.ALPN) > 0 {
  157. tlsConfig.NextProtos = append(options.ALPN, tlsConfig.NextProtos...)
  158. }
  159. if options.MinVersion != "" {
  160. minVersion, err := ParseTLSVersion(options.MinVersion)
  161. if err != nil {
  162. return nil, E.Cause(err, "parse min_version")
  163. }
  164. tlsConfig.MinVersion = minVersion
  165. }
  166. if options.MaxVersion != "" {
  167. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  168. if err != nil {
  169. return nil, E.Cause(err, "parse max_version")
  170. }
  171. tlsConfig.MaxVersion = maxVersion
  172. }
  173. if options.CipherSuites != nil {
  174. find:
  175. for _, cipherSuite := range options.CipherSuites {
  176. for _, tlsCipherSuite := range tls.CipherSuites() {
  177. if cipherSuite == tlsCipherSuite.Name {
  178. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  179. continue find
  180. }
  181. }
  182. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  183. }
  184. }
  185. var certificate []byte
  186. var key []byte
  187. if acmeService == nil {
  188. if len(options.Certificate) > 0 {
  189. certificate = []byte(strings.Join(options.Certificate, "\n"))
  190. } else if options.CertificatePath != "" {
  191. content, err := os.ReadFile(options.CertificatePath)
  192. if err != nil {
  193. return nil, E.Cause(err, "read certificate")
  194. }
  195. certificate = content
  196. }
  197. if len(options.Key) > 0 {
  198. key = []byte(strings.Join(options.Key, "\n"))
  199. } else if options.KeyPath != "" {
  200. content, err := os.ReadFile(options.KeyPath)
  201. if err != nil {
  202. return nil, E.Cause(err, "read key")
  203. }
  204. key = content
  205. }
  206. if certificate == nil && key == nil && options.Insecure {
  207. tlsConfig.GetCertificate = func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
  208. return GenerateCertificate(ntp.TimeFuncFromContext(ctx), info.ServerName)
  209. }
  210. } else {
  211. if certificate == nil {
  212. return nil, E.New("missing certificate")
  213. } else if key == nil {
  214. return nil, E.New("missing key")
  215. }
  216. keyPair, err := tls.X509KeyPair(certificate, key)
  217. if err != nil {
  218. return nil, E.Cause(err, "parse x509 key pair")
  219. }
  220. tlsConfig.Certificates = []tls.Certificate{keyPair}
  221. }
  222. }
  223. return &STDServerConfig{
  224. config: tlsConfig,
  225. logger: logger,
  226. acmeService: acmeService,
  227. certificate: certificate,
  228. key: key,
  229. certificatePath: options.CertificatePath,
  230. keyPath: options.KeyPath,
  231. }, nil
  232. }