std_server.go 6.4 KB

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