store.go 4.7 KB

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