std_server.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package tls
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "encoding/pem"
  6. "net"
  7. "os"
  8. "strings"
  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. "golang.org/x/crypto/cryptobyte"
  17. )
  18. var errInsecureUnused = E.New("tls: insecure unused")
  19. type STDServerConfig struct {
  20. config *tls.Config
  21. logger log.Logger
  22. acmeService adapter.Service
  23. certificate []byte
  24. key []byte
  25. certificatePath string
  26. keyPath 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. watcher, err := fswatch.NewWatcher(fswatch.Options{
  86. Path: watchPath,
  87. Callback: func(path string) {
  88. err := c.certificateUpdated(path)
  89. if err != nil {
  90. c.logger.Error(err)
  91. }
  92. },
  93. })
  94. if err != nil {
  95. return err
  96. }
  97. err = watcher.Start()
  98. if err != nil {
  99. return err
  100. }
  101. c.watcher = watcher
  102. return nil
  103. }
  104. func (c *STDServerConfig) certificateUpdated(path string) error {
  105. if path == c.certificatePath {
  106. certificate, err := os.ReadFile(c.certificatePath)
  107. if err != nil {
  108. return E.Cause(err, "reload certificate from ", c.certificatePath)
  109. }
  110. c.certificate = certificate
  111. } else if path == c.keyPath {
  112. key, err := os.ReadFile(c.keyPath)
  113. if err != nil {
  114. return E.Cause(err, "reload key from ", c.keyPath)
  115. }
  116. c.key = key
  117. }
  118. keyPair, err := tls.X509KeyPair(c.certificate, c.key)
  119. if err != nil {
  120. return E.Cause(err, "reload key pair")
  121. }
  122. c.config.Certificates = []tls.Certificate{keyPair}
  123. c.logger.Info("reloaded TLS certificate")
  124. return nil
  125. }
  126. func (c *STDServerConfig) Close() error {
  127. if c.acmeService != nil {
  128. return c.acmeService.Close()
  129. }
  130. if c.watcher != nil {
  131. return c.watcher.Close()
  132. }
  133. return nil
  134. }
  135. func NewSTDServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) {
  136. if !options.Enabled {
  137. return nil, nil
  138. }
  139. var tlsConfig *tls.Config
  140. var acmeService adapter.Service
  141. var err error
  142. if options.ACME != nil && len(options.ACME.Domain) > 0 {
  143. //nolint:staticcheck
  144. tlsConfig, acmeService, err = startACME(ctx, common.PtrValueOrDefault(options.ACME))
  145. if err != nil {
  146. return nil, err
  147. }
  148. if options.Insecure {
  149. return nil, errInsecureUnused
  150. }
  151. } else {
  152. tlsConfig = &tls.Config{}
  153. }
  154. tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
  155. if options.ServerName != "" {
  156. tlsConfig.ServerName = options.ServerName
  157. }
  158. if len(options.ALPN) > 0 {
  159. tlsConfig.NextProtos = append(options.ALPN, tlsConfig.NextProtos...)
  160. }
  161. if options.MinVersion != "" {
  162. minVersion, err := ParseTLSVersion(options.MinVersion)
  163. if err != nil {
  164. return nil, E.Cause(err, "parse min_version")
  165. }
  166. tlsConfig.MinVersion = minVersion
  167. }
  168. if options.MaxVersion != "" {
  169. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  170. if err != nil {
  171. return nil, E.Cause(err, "parse max_version")
  172. }
  173. tlsConfig.MaxVersion = maxVersion
  174. }
  175. if options.CipherSuites != nil {
  176. find:
  177. for _, cipherSuite := range options.CipherSuites {
  178. for _, tlsCipherSuite := range tls.CipherSuites() {
  179. if cipherSuite == tlsCipherSuite.Name {
  180. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  181. continue find
  182. }
  183. }
  184. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  185. }
  186. }
  187. var certificate []byte
  188. var key []byte
  189. if acmeService == nil {
  190. if len(options.Certificate) > 0 {
  191. certificate = []byte(strings.Join(options.Certificate, "\n"))
  192. } else if options.CertificatePath != "" {
  193. content, err := os.ReadFile(options.CertificatePath)
  194. if err != nil {
  195. return nil, E.Cause(err, "read certificate")
  196. }
  197. certificate = content
  198. }
  199. if len(options.Key) > 0 {
  200. key = []byte(strings.Join(options.Key, "\n"))
  201. } else if options.KeyPath != "" {
  202. content, err := os.ReadFile(options.KeyPath)
  203. if err != nil {
  204. return nil, E.Cause(err, "read key")
  205. }
  206. key = content
  207. }
  208. if certificate == nil && key == nil && options.Insecure {
  209. tlsConfig.GetCertificate = func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
  210. return GenerateCertificate(ntp.TimeFuncFromContext(ctx), info.ServerName)
  211. }
  212. } else {
  213. if certificate == nil {
  214. return nil, E.New("missing certificate")
  215. } else if key == nil {
  216. return nil, E.New("missing key")
  217. }
  218. keyPair, err := tls.X509KeyPair(certificate, key)
  219. if err != nil {
  220. return nil, E.Cause(err, "parse x509 key pair")
  221. }
  222. tlsConfig.Certificates = []tls.Certificate{keyPair}
  223. }
  224. }
  225. if options.ECH != nil && options.ECH.Enabled {
  226. var echKey []byte
  227. if len(options.ECH.Key) > 0 {
  228. echKey = []byte(strings.Join(options.ECH.Key, "\n"))
  229. } else if options.ECH.KeyPath != "" {
  230. content, err := os.ReadFile(options.ECH.KeyPath)
  231. if err != nil {
  232. return nil, E.Cause(err, "read ECH key")
  233. }
  234. echKey = content
  235. } else {
  236. return nil, E.New("missing ECH key")
  237. }
  238. block, rest := pem.Decode(echKey)
  239. if block == nil || block.Type != "ECH KEYS" || len(rest) > 0 {
  240. return nil, E.New("invalid ECH keys pem")
  241. }
  242. echKeys, err := UnmarshalECHKeys(block.Bytes)
  243. if err != nil {
  244. return nil, E.Cause(err, "parse ECH keys")
  245. }
  246. tlsConfig.EncryptedClientHelloKeys = echKeys
  247. }
  248. return &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. }, nil
  257. }
  258. func UnmarshalECHKeys(raw []byte) ([]tls.EncryptedClientHelloKey, error) {
  259. var keys []tls.EncryptedClientHelloKey
  260. rawString := cryptobyte.String(raw)
  261. for !rawString.Empty() {
  262. var key tls.EncryptedClientHelloKey
  263. if !rawString.ReadUint16LengthPrefixed((*cryptobyte.String)(&key.PrivateKey)) {
  264. return nil, E.New("error parsing private key")
  265. }
  266. if !rawString.ReadUint16LengthPrefixed((*cryptobyte.String)(&key.Config)) {
  267. return nil, E.New("error parsing config")
  268. }
  269. keys = append(keys, key)
  270. }
  271. if len(keys) == 0 {
  272. return nil, E.New("empty ECH keys")
  273. }
  274. return keys, nil
  275. }