std_server.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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) Config() (*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. echKeys, err := parseECHKeys(echKey)
  152. if err != nil {
  153. return err
  154. }
  155. c.access.Lock()
  156. config := c.config.Clone()
  157. config.EncryptedClientHelloKeys = echKeys
  158. c.config = config
  159. c.access.Unlock()
  160. c.logger.Info("reloaded ECH keys")
  161. }
  162. return nil
  163. }
  164. func (c *STDServerConfig) Close() error {
  165. if c.acmeService != nil {
  166. return c.acmeService.Close()
  167. }
  168. if c.watcher != nil {
  169. return c.watcher.Close()
  170. }
  171. return nil
  172. }
  173. func NewSTDServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) {
  174. if !options.Enabled {
  175. return nil, nil
  176. }
  177. var tlsConfig *tls.Config
  178. var acmeService adapter.SimpleLifecycle
  179. var err error
  180. if options.ACME != nil && len(options.ACME.Domain) > 0 {
  181. //nolint:staticcheck
  182. tlsConfig, acmeService, err = startACME(ctx, logger, common.PtrValueOrDefault(options.ACME))
  183. if err != nil {
  184. return nil, err
  185. }
  186. if options.Insecure {
  187. return nil, errInsecureUnused
  188. }
  189. } else {
  190. tlsConfig = &tls.Config{}
  191. }
  192. tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
  193. if options.ServerName != "" {
  194. tlsConfig.ServerName = options.ServerName
  195. }
  196. if len(options.ALPN) > 0 {
  197. tlsConfig.NextProtos = append(options.ALPN, tlsConfig.NextProtos...)
  198. }
  199. if options.MinVersion != "" {
  200. minVersion, err := ParseTLSVersion(options.MinVersion)
  201. if err != nil {
  202. return nil, E.Cause(err, "parse min_version")
  203. }
  204. tlsConfig.MinVersion = minVersion
  205. }
  206. if options.MaxVersion != "" {
  207. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  208. if err != nil {
  209. return nil, E.Cause(err, "parse max_version")
  210. }
  211. tlsConfig.MaxVersion = maxVersion
  212. }
  213. if options.CipherSuites != nil {
  214. find:
  215. for _, cipherSuite := range options.CipherSuites {
  216. for _, tlsCipherSuite := range tls.CipherSuites() {
  217. if cipherSuite == tlsCipherSuite.Name {
  218. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  219. continue find
  220. }
  221. }
  222. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  223. }
  224. }
  225. var certificate []byte
  226. var key []byte
  227. if acmeService == nil {
  228. if len(options.Certificate) > 0 {
  229. certificate = []byte(strings.Join(options.Certificate, "\n"))
  230. } else if options.CertificatePath != "" {
  231. content, err := os.ReadFile(options.CertificatePath)
  232. if err != nil {
  233. return nil, E.Cause(err, "read certificate")
  234. }
  235. certificate = content
  236. }
  237. if len(options.Key) > 0 {
  238. key = []byte(strings.Join(options.Key, "\n"))
  239. } else if options.KeyPath != "" {
  240. content, err := os.ReadFile(options.KeyPath)
  241. if err != nil {
  242. return nil, E.Cause(err, "read key")
  243. }
  244. key = content
  245. }
  246. if certificate == nil && key == nil && options.Insecure {
  247. timeFunc := ntp.TimeFuncFromContext(ctx)
  248. if timeFunc == nil {
  249. timeFunc = time.Now
  250. }
  251. tlsConfig.GetCertificate = func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
  252. return GenerateKeyPair(nil, nil, timeFunc, info.ServerName)
  253. }
  254. } else {
  255. if certificate == nil {
  256. return nil, E.New("missing certificate")
  257. } else if key == nil {
  258. return nil, E.New("missing key")
  259. }
  260. keyPair, err := tls.X509KeyPair(certificate, key)
  261. if err != nil {
  262. return nil, E.Cause(err, "parse x509 key pair")
  263. }
  264. tlsConfig.Certificates = []tls.Certificate{keyPair}
  265. }
  266. }
  267. var echKeyPath string
  268. if options.ECH != nil && options.ECH.Enabled {
  269. err = parseECHServerConfig(ctx, options, tlsConfig, &echKeyPath)
  270. if err != nil {
  271. return nil, err
  272. }
  273. }
  274. serverConfig := &STDServerConfig{
  275. config: tlsConfig,
  276. logger: logger,
  277. acmeService: acmeService,
  278. certificate: certificate,
  279. key: key,
  280. certificatePath: options.CertificatePath,
  281. keyPath: options.KeyPath,
  282. echKeyPath: echKeyPath,
  283. }
  284. serverConfig.config.GetConfigForClient = func(info *tls.ClientHelloInfo) (*tls.Config, error) {
  285. serverConfig.access.Lock()
  286. defer serverConfig.access.Unlock()
  287. return serverConfig.config, nil
  288. }
  289. return serverConfig, nil
  290. }