1
0

plugin.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // Package plugin provides support for the SFTPGo plugin system
  2. package plugin
  3. import (
  4. "crypto/x509"
  5. "errors"
  6. "fmt"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/hashicorp/go-hclog"
  11. "github.com/drakkan/sftpgo/v2/kms"
  12. "github.com/drakkan/sftpgo/v2/logger"
  13. "github.com/drakkan/sftpgo/v2/sdk/plugin/auth"
  14. "github.com/drakkan/sftpgo/v2/sdk/plugin/eventsearcher"
  15. kmsplugin "github.com/drakkan/sftpgo/v2/sdk/plugin/kms"
  16. "github.com/drakkan/sftpgo/v2/sdk/plugin/notifier"
  17. "github.com/drakkan/sftpgo/v2/util"
  18. )
  19. const (
  20. logSender = "plugins"
  21. )
  22. var (
  23. // Handler defines the plugins manager
  24. Handler Manager
  25. pluginsLogLevel = hclog.Debug
  26. // ErrNoSearcher defines the error to return for events searches if no plugin is configured
  27. ErrNoSearcher = errors.New("no events searcher plugin defined")
  28. )
  29. // Renderer defines the interface for generic objects rendering
  30. type Renderer interface {
  31. RenderAsJSON(reload bool) ([]byte, error)
  32. }
  33. // Config defines a plugin configuration
  34. type Config struct {
  35. // Plugin type
  36. Type string `json:"type" mapstructure:"type"`
  37. // NotifierOptions defines options for notifiers plugins
  38. NotifierOptions NotifierConfig `json:"notifier_options" mapstructure:"notifier_options"`
  39. // KMSOptions defines options for a KMS plugin
  40. KMSOptions KMSConfig `json:"kms_options" mapstructure:"kms_options"`
  41. // AuthOptions defines options for authentication plugins
  42. AuthOptions AuthConfig `json:"auth_options" mapstructure:"auth_options"`
  43. // Path to the plugin executable
  44. Cmd string `json:"cmd" mapstructure:"cmd"`
  45. // Args to pass to the plugin executable
  46. Args []string `json:"args" mapstructure:"args"`
  47. // SHA256 checksum for the plugin executable.
  48. // If not empty it will be used to verify the integrity of the executable
  49. SHA256Sum string `json:"sha256sum" mapstructure:"sha256sum"`
  50. // If enabled the client and the server automatically negotiate mTLS for
  51. // transport authentication. This ensures that only the original client will
  52. // be allowed to connect to the server, and all other connections will be
  53. // rejected. The client will also refuse to connect to any server that isn't
  54. // the original instance started by the client.
  55. AutoMTLS bool `json:"auto_mtls" mapstructure:"auto_mtls"`
  56. // unique identifier for kms plugins
  57. kmsID int
  58. }
  59. func (c *Config) newKMSPluginSecretProvider(base kms.BaseSecret, url, masterKey string) kms.SecretProvider {
  60. return &kmsPluginSecretProvider{
  61. BaseSecret: base,
  62. URL: url,
  63. MasterKey: masterKey,
  64. config: c,
  65. }
  66. }
  67. // Manager handles enabled plugins
  68. type Manager struct {
  69. closed int32
  70. done chan bool
  71. // List of configured plugins
  72. Configs []Config `json:"plugins" mapstructure:"plugins"`
  73. notifLock sync.RWMutex
  74. notifiers []*notifierPlugin
  75. kmsLock sync.RWMutex
  76. kms []*kmsPlugin
  77. authLock sync.RWMutex
  78. auths []*authPlugin
  79. searcherLock sync.RWMutex
  80. searcher *searcherPlugin
  81. authScopes int
  82. hasSearcher bool
  83. }
  84. // Initialize initializes the configured plugins
  85. func Initialize(configs []Config, logVerbose bool) error {
  86. logger.Debug(logSender, "", "initialize")
  87. Handler = Manager{
  88. Configs: configs,
  89. done: make(chan bool),
  90. closed: 0,
  91. authScopes: -1,
  92. }
  93. if len(configs) == 0 {
  94. return nil
  95. }
  96. if err := Handler.validateConfigs(); err != nil {
  97. return err
  98. }
  99. if logVerbose {
  100. pluginsLogLevel = hclog.Debug
  101. } else {
  102. pluginsLogLevel = hclog.Info
  103. }
  104. kmsID := 0
  105. for idx, config := range Handler.Configs {
  106. switch config.Type {
  107. case notifier.PluginName:
  108. plugin, err := newNotifierPlugin(config)
  109. if err != nil {
  110. return err
  111. }
  112. Handler.notifiers = append(Handler.notifiers, plugin)
  113. case kmsplugin.PluginName:
  114. plugin, err := newKMSPlugin(config)
  115. if err != nil {
  116. return err
  117. }
  118. Handler.kms = append(Handler.kms, plugin)
  119. Handler.Configs[idx].kmsID = kmsID
  120. kmsID++
  121. kms.RegisterSecretProvider(config.KMSOptions.Scheme, config.KMSOptions.EncryptedStatus,
  122. Handler.Configs[idx].newKMSPluginSecretProvider)
  123. logger.Debug(logSender, "", "registered secret provider for scheme: %v, encrypted status: %v",
  124. config.KMSOptions.Scheme, config.KMSOptions.EncryptedStatus)
  125. case auth.PluginName:
  126. plugin, err := newAuthPlugin(config)
  127. if err != nil {
  128. return err
  129. }
  130. Handler.auths = append(Handler.auths, plugin)
  131. if Handler.authScopes == -1 {
  132. Handler.authScopes = config.AuthOptions.Scope
  133. } else {
  134. Handler.authScopes |= config.AuthOptions.Scope
  135. }
  136. case eventsearcher.PluginName:
  137. plugin, err := newSearcherPlugin(config)
  138. if err != nil {
  139. return err
  140. }
  141. Handler.searcher = plugin
  142. default:
  143. return fmt.Errorf("unsupported plugin type: %v", config.Type)
  144. }
  145. }
  146. startCheckTicker()
  147. return nil
  148. }
  149. func (m *Manager) validateConfigs() error {
  150. kmsSchemes := make(map[string]bool)
  151. kmsEncryptions := make(map[string]bool)
  152. m.hasSearcher = false
  153. for _, config := range m.Configs {
  154. if config.Type == kmsplugin.PluginName {
  155. if _, ok := kmsSchemes[config.KMSOptions.Scheme]; ok {
  156. return fmt.Errorf("invalid KMS configuration, duplicated scheme %#v", config.KMSOptions.Scheme)
  157. }
  158. if _, ok := kmsEncryptions[config.KMSOptions.EncryptedStatus]; ok {
  159. return fmt.Errorf("invalid KMS configuration, duplicated encrypted status %#v", config.KMSOptions.EncryptedStatus)
  160. }
  161. kmsSchemes[config.KMSOptions.Scheme] = true
  162. kmsEncryptions[config.KMSOptions.EncryptedStatus] = true
  163. }
  164. if config.Type == eventsearcher.PluginName {
  165. if m.hasSearcher {
  166. return fmt.Errorf("only one eventsearcher plugin can be defined")
  167. }
  168. m.hasSearcher = true
  169. }
  170. }
  171. return nil
  172. }
  173. // NotifyFsEvent sends the fs event notifications using any defined notifier plugins
  174. func (m *Manager) NotifyFsEvent(timestamp int64, action, username, fsPath, fsTargetPath, sshCmd, protocol, ip,
  175. virtualPath, virtualTargetPath, sessionID string, fileSize int64, err error,
  176. ) {
  177. m.notifLock.RLock()
  178. defer m.notifLock.RUnlock()
  179. for _, n := range m.notifiers {
  180. n.notifyFsAction(timestamp, action, username, fsPath, fsTargetPath, sshCmd, protocol, ip, virtualPath,
  181. virtualTargetPath, sessionID, fileSize, err)
  182. }
  183. }
  184. // NotifyProviderEvent sends the provider event notifications using any defined notifier plugins
  185. func (m *Manager) NotifyProviderEvent(timestamp int64, action, username, objectType, objectName, ip string,
  186. object Renderer,
  187. ) {
  188. m.notifLock.RLock()
  189. defer m.notifLock.RUnlock()
  190. for _, n := range m.notifiers {
  191. n.notifyProviderAction(timestamp, action, username, objectType, objectName, ip, object)
  192. }
  193. }
  194. // SearchFsEvents returns the filesystem events matching the specified filter and a continuation token
  195. // to use for cursor based pagination
  196. func (m *Manager) SearchFsEvents(startTimestamp, endTimestamp int64, username, ip, sshCmd string, actions,
  197. protocols, instanceIDs, excludeIDs []string, statuses []int32, limit, order int,
  198. ) ([]byte, []string, []string, error) {
  199. if !m.hasSearcher {
  200. return nil, nil, nil, ErrNoSearcher
  201. }
  202. m.searcherLock.RLock()
  203. plugin := m.searcher
  204. m.searcherLock.RUnlock()
  205. return plugin.searchear.SearchFsEvents(startTimestamp, endTimestamp, username, ip, sshCmd, actions, protocols,
  206. instanceIDs, excludeIDs, statuses, limit, order)
  207. }
  208. // SearchProviderEvents returns the provider events matching the specified filter and a continuation token
  209. // to use for cursor based pagination
  210. func (m *Manager) SearchProviderEvents(startTimestamp, endTimestamp int64, username, ip, objectName string,
  211. limit, order int, actions, objectTypes, instanceIDs, excludeIDs []string,
  212. ) ([]byte, []string, []string, error) {
  213. if !m.hasSearcher {
  214. return nil, nil, nil, ErrNoSearcher
  215. }
  216. m.searcherLock.RLock()
  217. plugin := m.searcher
  218. m.searcherLock.RUnlock()
  219. return plugin.searchear.SearchProviderEvents(startTimestamp, endTimestamp, username, ip, objectName, limit,
  220. order, actions, objectTypes, instanceIDs, excludeIDs)
  221. }
  222. func (m *Manager) kmsEncrypt(secret kms.BaseSecret, url string, masterKey string, kmsID int) (string, string, int32, error) {
  223. m.kmsLock.RLock()
  224. plugin := m.kms[kmsID]
  225. m.kmsLock.RUnlock()
  226. return plugin.Encrypt(secret, url, masterKey)
  227. }
  228. func (m *Manager) kmsDecrypt(secret kms.BaseSecret, url string, masterKey string, kmsID int) (string, error) {
  229. m.kmsLock.RLock()
  230. plugin := m.kms[kmsID]
  231. m.kmsLock.RUnlock()
  232. return plugin.Decrypt(secret, url, masterKey)
  233. }
  234. // HasAuthScope returns true if there is an auth plugin that support the specified scope
  235. func (m *Manager) HasAuthScope(scope int) bool {
  236. if m.authScopes == -1 {
  237. return false
  238. }
  239. return m.authScopes&scope != 0
  240. }
  241. // Authenticate tries to authenticate the specified user using an external plugin
  242. func (m *Manager) Authenticate(username, password, ip, protocol string, pkey string,
  243. tlsCert *x509.Certificate, authScope int, userAsJSON []byte,
  244. ) ([]byte, error) {
  245. switch authScope {
  246. case AuthScopePassword:
  247. return m.checkUserAndPass(username, password, ip, protocol, userAsJSON)
  248. case AuthScopePublicKey:
  249. return m.checkUserAndPublicKey(username, pkey, ip, protocol, userAsJSON)
  250. case AuthScopeKeyboardInteractive:
  251. return m.checkUserAndKeyboardInteractive(username, ip, protocol, userAsJSON)
  252. case AuthScopeTLSCertificate:
  253. cert, err := util.EncodeTLSCertToPem(tlsCert)
  254. if err != nil {
  255. logger.Warn(logSender, "", "unable to encode tls certificate to pem: %v", err)
  256. return nil, fmt.Errorf("unable to encode tls cert to pem: %w", err)
  257. }
  258. return m.checkUserAndTLSCert(username, cert, ip, protocol, userAsJSON)
  259. default:
  260. return nil, fmt.Errorf("unsupported auth scope: %v", authScope)
  261. }
  262. }
  263. // ExecuteKeyboardInteractiveStep executes a keyboard interactive step
  264. func (m *Manager) ExecuteKeyboardInteractiveStep(req *KeyboardAuthRequest) (*KeyboardAuthResponse, error) {
  265. var plugin *authPlugin
  266. m.authLock.Lock()
  267. for _, p := range m.auths {
  268. if p.config.AuthOptions.Scope&AuthScopePassword != 0 {
  269. plugin = p
  270. break
  271. }
  272. }
  273. m.authLock.Unlock()
  274. if plugin == nil {
  275. return nil, errors.New("no auth plugin configured for keyaboard interactive authentication step")
  276. }
  277. return plugin.sendKeyboardIteractiveRequest(req)
  278. }
  279. func (m *Manager) checkUserAndPass(username, password, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  280. var plugin *authPlugin
  281. m.authLock.Lock()
  282. for _, p := range m.auths {
  283. if p.config.AuthOptions.Scope&AuthScopePassword != 0 {
  284. plugin = p
  285. break
  286. }
  287. }
  288. m.authLock.Unlock()
  289. if plugin == nil {
  290. return nil, errors.New("no auth plugin configured for password checking")
  291. }
  292. return plugin.checkUserAndPass(username, password, ip, protocol, userAsJSON)
  293. }
  294. func (m *Manager) checkUserAndPublicKey(username, pubKey, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  295. var plugin *authPlugin
  296. m.authLock.Lock()
  297. for _, p := range m.auths {
  298. if p.config.AuthOptions.Scope&AuthScopePublicKey != 0 {
  299. plugin = p
  300. break
  301. }
  302. }
  303. m.authLock.Unlock()
  304. if plugin == nil {
  305. return nil, errors.New("no auth plugin configured for public key checking")
  306. }
  307. return plugin.checkUserAndPublicKey(username, pubKey, ip, protocol, userAsJSON)
  308. }
  309. func (m *Manager) checkUserAndTLSCert(username, tlsCert, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  310. var plugin *authPlugin
  311. m.authLock.Lock()
  312. for _, p := range m.auths {
  313. if p.config.AuthOptions.Scope&AuthScopeTLSCertificate != 0 {
  314. plugin = p
  315. break
  316. }
  317. }
  318. m.authLock.Unlock()
  319. if plugin == nil {
  320. return nil, errors.New("no auth plugin configured for TLS certificate checking")
  321. }
  322. return plugin.checkUserAndTLSCertificate(username, tlsCert, ip, protocol, userAsJSON)
  323. }
  324. func (m *Manager) checkUserAndKeyboardInteractive(username, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  325. var plugin *authPlugin
  326. m.authLock.Lock()
  327. for _, p := range m.auths {
  328. if p.config.AuthOptions.Scope&AuthScopeKeyboardInteractive != 0 {
  329. plugin = p
  330. break
  331. }
  332. }
  333. m.authLock.Unlock()
  334. if plugin == nil {
  335. return nil, errors.New("no auth plugin configured for keyboard interactive checking")
  336. }
  337. return plugin.checkUserAndKeyboardInteractive(username, ip, protocol, userAsJSON)
  338. }
  339. func (m *Manager) checkCrashedPlugins() {
  340. m.notifLock.RLock()
  341. for idx, n := range m.notifiers {
  342. if n.exited() {
  343. defer func(cfg Config, index int) {
  344. Handler.restartNotifierPlugin(cfg, index)
  345. }(n.config, idx)
  346. } else {
  347. n.sendQueuedEvents()
  348. }
  349. }
  350. m.notifLock.RUnlock()
  351. m.kmsLock.RLock()
  352. for idx, k := range m.kms {
  353. if k.exited() {
  354. defer func(cfg Config, index int) {
  355. Handler.restartKMSPlugin(cfg, index)
  356. }(k.config, idx)
  357. }
  358. }
  359. m.kmsLock.RUnlock()
  360. m.authLock.RLock()
  361. for idx, a := range m.auths {
  362. if a.exited() {
  363. defer func(cfg Config, index int) {
  364. Handler.restartAuthPlugin(cfg, index)
  365. }(a.config, idx)
  366. }
  367. }
  368. m.authLock.RUnlock()
  369. if m.hasSearcher {
  370. m.searcherLock.RLock()
  371. if m.searcher.exited() {
  372. defer func(cfg Config) {
  373. Handler.restartSearcherPlugin(cfg)
  374. }(m.searcher.config)
  375. }
  376. m.searcherLock.RUnlock()
  377. }
  378. }
  379. func (m *Manager) restartNotifierPlugin(config Config, idx int) {
  380. if atomic.LoadInt32(&m.closed) == 1 {
  381. return
  382. }
  383. logger.Info(logSender, "", "try to restart crashed notifier plugin %#v, idx: %v", config.Cmd, idx)
  384. plugin, err := newNotifierPlugin(config)
  385. if err != nil {
  386. logger.Warn(logSender, "", "unable to restart notifier plugin %#v, err: %v", config.Cmd, err)
  387. return
  388. }
  389. m.notifLock.Lock()
  390. plugin.queue = m.notifiers[idx].queue
  391. m.notifiers[idx] = plugin
  392. m.notifLock.Unlock()
  393. plugin.sendQueuedEvents()
  394. }
  395. func (m *Manager) restartKMSPlugin(config Config, idx int) {
  396. if atomic.LoadInt32(&m.closed) == 1 {
  397. return
  398. }
  399. logger.Info(logSender, "", "try to restart crashed kms plugin %#v, idx: %v", config.Cmd, idx)
  400. plugin, err := newKMSPlugin(config)
  401. if err != nil {
  402. logger.Warn(logSender, "", "unable to restart kms plugin %#v, err: %v", config.Cmd, err)
  403. return
  404. }
  405. m.kmsLock.Lock()
  406. m.kms[idx] = plugin
  407. m.kmsLock.Unlock()
  408. }
  409. func (m *Manager) restartAuthPlugin(config Config, idx int) {
  410. if atomic.LoadInt32(&m.closed) == 1 {
  411. return
  412. }
  413. logger.Info(logSender, "", "try to restart crashed auth plugin %#v, idx: %v", config.Cmd, idx)
  414. plugin, err := newAuthPlugin(config)
  415. if err != nil {
  416. logger.Warn(logSender, "", "unable to restart auth plugin %#v, err: %v", config.Cmd, err)
  417. return
  418. }
  419. m.authLock.Lock()
  420. m.auths[idx] = plugin
  421. m.authLock.Unlock()
  422. }
  423. func (m *Manager) restartSearcherPlugin(config Config) {
  424. if atomic.LoadInt32(&m.closed) == 1 {
  425. return
  426. }
  427. logger.Info(logSender, "", "try to restart crashed searcher plugin %#v", config.Cmd)
  428. plugin, err := newSearcherPlugin(config)
  429. if err != nil {
  430. logger.Warn(logSender, "", "unable to restart searcher plugin %#v, err: %v", config.Cmd, err)
  431. return
  432. }
  433. m.searcherLock.Lock()
  434. m.searcher = plugin
  435. m.searcherLock.Unlock()
  436. }
  437. // Cleanup releases all the active plugins
  438. func (m *Manager) Cleanup() {
  439. logger.Debug(logSender, "", "cleanup")
  440. atomic.StoreInt32(&m.closed, 1)
  441. close(m.done)
  442. m.notifLock.Lock()
  443. for _, n := range m.notifiers {
  444. logger.Debug(logSender, "", "cleanup notifier plugin %v", n.config.Cmd)
  445. n.cleanup()
  446. }
  447. m.notifLock.Unlock()
  448. m.kmsLock.Lock()
  449. for _, k := range m.kms {
  450. logger.Debug(logSender, "", "cleanup kms plugin %v", k.config.Cmd)
  451. k.cleanup()
  452. }
  453. m.kmsLock.Unlock()
  454. m.authLock.Lock()
  455. for _, a := range m.auths {
  456. logger.Debug(logSender, "", "cleanup auth plugin %v", a.config.Cmd)
  457. a.cleanup()
  458. }
  459. m.authLock.Unlock()
  460. if m.hasSearcher {
  461. m.searcherLock.Lock()
  462. logger.Debug(logSender, "", "cleanup searcher plugin %v", m.searcher.config.Cmd)
  463. m.searcher.cleanup()
  464. m.searcherLock.Unlock()
  465. }
  466. }
  467. func startCheckTicker() {
  468. logger.Debug(logSender, "", "start plugins checker")
  469. checker := time.NewTicker(30 * time.Second)
  470. go func() {
  471. for {
  472. select {
  473. case <-Handler.done:
  474. logger.Debug(logSender, "", "handler done, stop plugins checker")
  475. checker.Stop()
  476. return
  477. case <-checker.C:
  478. Handler.checkCrashedPlugins()
  479. }
  480. }
  481. }()
  482. }