store.go 5.4 KB

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