std_server.go 6.2 KB

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