store.go 4.5 KB

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