store.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package certificate
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "io/fs"
  6. "os"
  7. "path/filepath"
  8. "strings"
  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/experimental/libbox/platform"
  13. "github.com/sagernet/sing-box/option"
  14. E "github.com/sagernet/sing/common/exceptions"
  15. "github.com/sagernet/sing/common/logger"
  16. "github.com/sagernet/sing/service"
  17. )
  18. var _ adapter.CertificateStore = (*Store)(nil)
  19. type Store struct {
  20. systemPool *x509.CertPool
  21. currentPool *x509.CertPool
  22. certificate string
  23. certificatePaths []string
  24. certificateDirectoryPaths []string
  25. watcher *fswatch.Watcher
  26. }
  27. func NewStore(ctx context.Context, logger logger.Logger, options option.CertificateOptions) (*Store, error) {
  28. var systemPool *x509.CertPool
  29. switch options.Store {
  30. case C.CertificateStoreSystem, "":
  31. systemPool = x509.NewCertPool()
  32. var systemValid bool
  33. for _, cert := range service.FromContext[platform.Interface](ctx).SystemCertificates() {
  34. if systemPool.AppendCertsFromPEM([]byte(cert)) {
  35. systemValid = true
  36. }
  37. }
  38. if !systemValid {
  39. certPool, err := x509.SystemCertPool()
  40. if err != nil {
  41. return nil, err
  42. }
  43. systemPool = certPool
  44. }
  45. case C.CertificateStoreMozilla:
  46. systemPool = mozillaIncluded
  47. case C.CertificateStoreNone:
  48. systemPool = nil
  49. default:
  50. return nil, E.New("unknown certificate store: ", options.Store)
  51. }
  52. store := &Store{
  53. systemPool: systemPool,
  54. certificate: strings.Join(options.Certificate, "\n"),
  55. certificatePaths: options.CertificatePath,
  56. certificateDirectoryPaths: options.CertificateDirectoryPath,
  57. }
  58. var watchPaths []string
  59. for _, target := range options.CertificatePath {
  60. watchPaths = append(watchPaths, target)
  61. }
  62. for _, target := range options.CertificateDirectoryPath {
  63. watchPaths = append(watchPaths, target)
  64. }
  65. if len(watchPaths) > 0 {
  66. watcher, err := fswatch.NewWatcher(fswatch.Options{
  67. Path: watchPaths,
  68. Logger: logger,
  69. Callback: func(_ string) {
  70. err := store.update()
  71. if err != nil {
  72. logger.Error(E.Cause(err, "reload certificates"))
  73. }
  74. },
  75. })
  76. if err != nil {
  77. return nil, E.Cause(err, "fswatch: create fsnotify watcher")
  78. }
  79. store.watcher = watcher
  80. }
  81. err := store.update()
  82. if err != nil {
  83. return nil, E.Cause(err, "initializing certificate store")
  84. }
  85. return store, nil
  86. }
  87. func (s *Store) Name() string {
  88. return "certificate"
  89. }
  90. func (s *Store) Start(stage adapter.StartStage) error {
  91. if stage != adapter.StartStateStart {
  92. return nil
  93. }
  94. if s.watcher != nil {
  95. return s.watcher.Start()
  96. }
  97. return nil
  98. }
  99. func (s *Store) Close() error {
  100. if s.watcher != nil {
  101. return s.watcher.Close()
  102. }
  103. return nil
  104. }
  105. func (s *Store) Pool() *x509.CertPool {
  106. return s.currentPool
  107. }
  108. func (s *Store) update() error {
  109. var currentPool *x509.CertPool
  110. if s.systemPool == nil {
  111. currentPool = x509.NewCertPool()
  112. } else {
  113. currentPool = s.systemPool.Clone()
  114. }
  115. if s.certificate != "" {
  116. if !currentPool.AppendCertsFromPEM([]byte(s.certificate)) {
  117. return E.New("invalid certificate PEM strings")
  118. }
  119. }
  120. for _, path := range s.certificatePaths {
  121. pemContent, err := os.ReadFile(path)
  122. if err != nil {
  123. return err
  124. }
  125. if !currentPool.AppendCertsFromPEM(pemContent) {
  126. return E.New("invalid certificate PEM file: ", path)
  127. }
  128. }
  129. var firstErr error
  130. for _, directoryPath := range s.certificateDirectoryPaths {
  131. directoryEntries, err := readUniqueDirectoryEntries(directoryPath)
  132. if err != nil {
  133. if firstErr == nil && !os.IsNotExist(err) {
  134. firstErr = E.Cause(err, "invalid certificate directory: ", directoryPath)
  135. }
  136. continue
  137. }
  138. for _, directoryEntry := range directoryEntries {
  139. pemContent, err := os.ReadFile(filepath.Join(directoryPath, directoryEntry.Name()))
  140. if err == nil {
  141. currentPool.AppendCertsFromPEM(pemContent)
  142. }
  143. }
  144. }
  145. if firstErr != nil {
  146. return firstErr
  147. }
  148. s.currentPool = currentPool
  149. return nil
  150. }
  151. func readUniqueDirectoryEntries(dir string) ([]fs.DirEntry, error) {
  152. files, err := os.ReadDir(dir)
  153. if err != nil {
  154. return nil, err
  155. }
  156. uniq := files[:0]
  157. for _, f := range files {
  158. if !isSameDirSymlink(f, dir) {
  159. uniq = append(uniq, f)
  160. }
  161. }
  162. return uniq, nil
  163. }
  164. func isSameDirSymlink(f fs.DirEntry, dir string) bool {
  165. if f.Type()&fs.ModeSymlink == 0 {
  166. return false
  167. }
  168. target, err := os.Readlink(filepath.Join(dir, f.Name()))
  169. return err == nil && !strings.Contains(target, "/")
  170. }