std_server.go 8.0 KB

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