std_server.go 6.8 KB

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