store.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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.CertificateStoreNone:
  52. systemPool = nil
  53. default:
  54. return nil, E.New("unknown certificate store: ", options.Store)
  55. }
  56. store := &Store{
  57. systemPool: systemPool,
  58. certificate: strings.Join(options.Certificate, "\n"),
  59. certificatePaths: options.CertificatePath,
  60. certificateDirectoryPaths: options.CertificateDirectoryPath,
  61. }
  62. var watchPaths []string
  63. for _, target := range options.CertificatePath {
  64. watchPaths = append(watchPaths, target)
  65. }
  66. for _, target := range options.CertificateDirectoryPath {
  67. watchPaths = append(watchPaths, target)
  68. }
  69. if len(watchPaths) > 0 {
  70. watcher, err := fswatch.NewWatcher(fswatch.Options{
  71. Path: watchPaths,
  72. Logger: logger,
  73. Callback: func(_ string) {
  74. err := store.update()
  75. if err != nil {
  76. logger.Error(E.Cause(err, "reload certificates"))
  77. }
  78. },
  79. })
  80. if err != nil {
  81. return nil, E.Cause(err, "fswatch: create fsnotify watcher")
  82. }
  83. store.watcher = watcher
  84. }
  85. err := store.update()
  86. if err != nil {
  87. return nil, E.Cause(err, "initializing certificate store")
  88. }
  89. return store, nil
  90. }
  91. func (s *Store) Name() string {
  92. return "certificate"
  93. }
  94. func (s *Store) Start(stage adapter.StartStage) error {
  95. if stage != adapter.StartStateStart {
  96. return nil
  97. }
  98. if s.watcher != nil {
  99. return s.watcher.Start()
  100. }
  101. return nil
  102. }
  103. func (s *Store) Close() error {
  104. if s.watcher != nil {
  105. return s.watcher.Close()
  106. }
  107. return nil
  108. }
  109. func (s *Store) Pool() *x509.CertPool {
  110. s.access.RLock()
  111. defer s.access.RUnlock()
  112. return s.currentPool
  113. }
  114. func (s *Store) update() error {
  115. s.access.Lock()
  116. defer s.access.Unlock()
  117. var currentPool *x509.CertPool
  118. if s.systemPool == nil {
  119. currentPool = x509.NewCertPool()
  120. } else {
  121. currentPool = s.systemPool.Clone()
  122. }
  123. if s.certificate != "" {
  124. if !currentPool.AppendCertsFromPEM([]byte(s.certificate)) {
  125. return E.New("invalid certificate PEM strings")
  126. }
  127. }
  128. for _, path := range s.certificatePaths {
  129. pemContent, err := os.ReadFile(path)
  130. if err != nil {
  131. return err
  132. }
  133. if !currentPool.AppendCertsFromPEM(pemContent) {
  134. return E.New("invalid certificate PEM file: ", path)
  135. }
  136. }
  137. var firstErr error
  138. for _, directoryPath := range s.certificateDirectoryPaths {
  139. directoryEntries, err := readUniqueDirectoryEntries(directoryPath)
  140. if err != nil {
  141. if firstErr == nil && !os.IsNotExist(err) {
  142. firstErr = E.Cause(err, "invalid certificate directory: ", directoryPath)
  143. }
  144. continue
  145. }
  146. for _, directoryEntry := range directoryEntries {
  147. pemContent, err := os.ReadFile(filepath.Join(directoryPath, directoryEntry.Name()))
  148. if err == nil {
  149. currentPool.AppendCertsFromPEM(pemContent)
  150. }
  151. }
  152. }
  153. if firstErr != nil {
  154. return firstErr
  155. }
  156. s.currentPool = currentPool
  157. return nil
  158. }
  159. func readUniqueDirectoryEntries(dir string) ([]fs.DirEntry, error) {
  160. files, err := os.ReadDir(dir)
  161. if err != nil {
  162. return nil, err
  163. }
  164. uniq := files[:0]
  165. for _, f := range files {
  166. if !isSameDirSymlink(f, dir) {
  167. uniq = append(uniq, f)
  168. }
  169. }
  170. return uniq, nil
  171. }
  172. func isSameDirSymlink(f fs.DirEntry, dir string) bool {
  173. if f.Type()&fs.ModeSymlink == 0 {
  174. return false
  175. }
  176. target, err := os.Readlink(filepath.Join(dir, f.Name()))
  177. return err == nil && !strings.Contains(target, "/")
  178. }