store.go 4.7 KB

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