store.go 4.6 KB

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