std_server.go 7.9 KB

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