std_server.go 7.3 KB

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