std_server.go 6.9 KB

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