smtp.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. // Package smtp provides supports for sending emails
  15. package smtp
  16. import (
  17. "bytes"
  18. "context"
  19. "errors"
  20. "fmt"
  21. "html/template"
  22. "path/filepath"
  23. "sync"
  24. "time"
  25. "github.com/rs/xid"
  26. "github.com/wneessen/go-mail"
  27. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  28. "github.com/drakkan/sftpgo/v2/internal/kms"
  29. "github.com/drakkan/sftpgo/v2/internal/logger"
  30. "github.com/drakkan/sftpgo/v2/internal/util"
  31. "github.com/drakkan/sftpgo/v2/internal/version"
  32. )
  33. const (
  34. logSender = "smtp"
  35. )
  36. // EmailContentType defines the support content types for email body
  37. type EmailContentType int
  38. // Supported email body content type
  39. const (
  40. EmailContentTypeTextPlain EmailContentType = iota
  41. EmailContentTypeTextHTML
  42. )
  43. const (
  44. templateEmailDir = "email"
  45. templatePasswordReset = "reset-password.html"
  46. templatePasswordExpiration = "password-expiration.html"
  47. dialTimeout = 10 * time.Second
  48. )
  49. var (
  50. config = &activeConfig{}
  51. initialConfig *Config
  52. emailTemplates = make(map[string]*template.Template)
  53. )
  54. type activeConfig struct {
  55. sync.RWMutex
  56. config *Config
  57. }
  58. func (c *activeConfig) isEnabled() bool {
  59. c.RLock()
  60. defer c.RUnlock()
  61. return c.config != nil && c.config.Host != ""
  62. }
  63. func (c *activeConfig) Set(cfg *dataprovider.SMTPConfigs) {
  64. var config *Config
  65. if cfg != nil {
  66. config = &Config{
  67. Host: cfg.Host,
  68. Port: cfg.Port,
  69. From: cfg.From,
  70. User: cfg.User,
  71. Password: cfg.Password.GetPayload(),
  72. AuthType: cfg.AuthType,
  73. Encryption: cfg.Encryption,
  74. Domain: cfg.Domain,
  75. Debug: cfg.Debug,
  76. OAuth2: OAuth2Config{
  77. Provider: cfg.OAuth2.Provider,
  78. Tenant: cfg.OAuth2.Tenant,
  79. ClientID: cfg.OAuth2.ClientID,
  80. ClientSecret: cfg.OAuth2.ClientSecret.GetPayload(),
  81. RefreshToken: cfg.OAuth2.RefreshToken.GetPayload(),
  82. },
  83. }
  84. config.OAuth2.initialize()
  85. }
  86. c.Lock()
  87. defer c.Unlock()
  88. if config != nil && config.Host != "" {
  89. if c.config != nil && c.config.isEqual(config) {
  90. return
  91. }
  92. c.config = config
  93. logger.Info(logSender, "", "activated new config, server %s:%d", c.config.Host, c.config.Port)
  94. } else {
  95. logger.Debug(logSender, "", "activating initial config")
  96. c.config = initialConfig
  97. if c.config == nil || c.config.Host == "" {
  98. logger.Debug(logSender, "", "configuration disabled, email capabilities will not be available")
  99. }
  100. }
  101. }
  102. func (c *activeConfig) getSMTPClientAndMsg(to, bcc []string, subject, body string, contentType EmailContentType,
  103. attachments ...*mail.File,
  104. ) (*mail.Client, *mail.Msg, error) {
  105. c.RLock()
  106. defer c.RUnlock()
  107. if c.config == nil || c.config.Host == "" {
  108. return nil, nil, errors.New("smtp: not configured")
  109. }
  110. return c.config.getSMTPClientAndMsg(to, bcc, subject, body, contentType, attachments...)
  111. }
  112. func (c *activeConfig) sendEmail(to, bcc []string, subject, body string, contentType EmailContentType, attachments ...*mail.File) error {
  113. client, msg, err := c.getSMTPClientAndMsg(to, bcc, subject, body, contentType, attachments...)
  114. if err != nil {
  115. return err
  116. }
  117. ctx, cancelFn := context.WithTimeout(context.Background(), dialTimeout)
  118. defer cancelFn()
  119. return client.DialAndSendWithContext(ctx, msg)
  120. }
  121. // IsEnabled returns true if an SMTP server is configured
  122. func IsEnabled() bool {
  123. return config.isEnabled()
  124. }
  125. // Activate sets the specified config as active
  126. func Activate(c *dataprovider.SMTPConfigs) {
  127. config.Set(c)
  128. }
  129. // Config defines the SMTP configuration to use to send emails
  130. type Config struct {
  131. // Location of SMTP email server. Leavy empty to disable email sending capabilities
  132. Host string `json:"host" mapstructure:"host"`
  133. // Port of SMTP email server
  134. Port int `json:"port" mapstructure:"port"`
  135. // From address, for example "SFTPGo <[email protected]>".
  136. // Many SMTP servers reject emails without a `From` header so, if not set,
  137. // SFTPGo will try to use the username as fallback, this may or may not be appropriate
  138. From string `json:"from" mapstructure:"from"`
  139. // SMTP username
  140. User string `json:"user" mapstructure:"user"`
  141. // SMTP password. Leaving both username and password empty the SMTP authentication
  142. // will be disabled
  143. Password string `json:"password" mapstructure:"password"`
  144. // 0 Plain
  145. // 1 Login
  146. // 2 CRAM-MD5
  147. // 3 OAuth2
  148. AuthType int `json:"auth_type" mapstructure:"auth_type"`
  149. // 0 no encryption
  150. // 1 TLS
  151. // 2 start TLS
  152. Encryption int `json:"encryption" mapstructure:"encryption"`
  153. // Domain to use for HELO command, if empty localhost will be used
  154. Domain string `json:"domain" mapstructure:"domain"`
  155. // Path to the email templates. This can be an absolute path or a path relative to the config dir.
  156. // Templates are searched within a subdirectory named "email" in the specified path
  157. TemplatesPath string `json:"templates_path" mapstructure:"templates_path"`
  158. // Set to 1 to enable debug logs
  159. Debug int `json:"debug" mapstructure:"debug"`
  160. // OAuth2 related settings
  161. OAuth2 OAuth2Config `json:"oauth2" mapstructure:"oauth2"`
  162. }
  163. func (c *Config) isEqual(other *Config) bool {
  164. if c.Host != other.Host {
  165. return false
  166. }
  167. if c.Port != other.Port {
  168. return false
  169. }
  170. if c.From != other.From {
  171. return false
  172. }
  173. if c.User != other.User {
  174. return false
  175. }
  176. if c.Password != other.Password {
  177. return false
  178. }
  179. if c.AuthType != other.AuthType {
  180. return false
  181. }
  182. if c.Encryption != other.Encryption {
  183. return false
  184. }
  185. if c.Domain != other.Domain {
  186. return false
  187. }
  188. if c.Debug != other.Debug {
  189. return false
  190. }
  191. return c.OAuth2.isEqual(&other.OAuth2)
  192. }
  193. func (c *Config) validate() error {
  194. if c.Port <= 0 || c.Port > 65535 {
  195. return fmt.Errorf("smtp: invalid port %d", c.Port)
  196. }
  197. if c.AuthType < 0 || c.AuthType > 3 {
  198. return fmt.Errorf("smtp: invalid auth type %d", c.AuthType)
  199. }
  200. if c.Encryption < 0 || c.Encryption > 2 {
  201. return fmt.Errorf("smtp: invalid encryption %d", c.Encryption)
  202. }
  203. if c.From == "" && c.User == "" {
  204. return errors.New(`smtp: from address and user cannot both be empty`)
  205. }
  206. if c.AuthType == 3 {
  207. return c.OAuth2.Validate()
  208. }
  209. return nil
  210. }
  211. func (c *Config) loadTemplates(configDir string) error {
  212. if c.TemplatesPath == "" {
  213. logger.Debug(logSender, "", "templates path empty, using default")
  214. c.TemplatesPath = "templates"
  215. }
  216. templatesPath := util.FindSharedDataPath(c.TemplatesPath, configDir)
  217. if templatesPath == "" {
  218. return fmt.Errorf("smtp: invalid templates path %q", templatesPath)
  219. }
  220. loadTemplates(filepath.Join(templatesPath, templateEmailDir))
  221. return nil
  222. }
  223. // Initialize initializes and validates the SMTP configuration
  224. func (c *Config) Initialize(configDir string, isService bool) error {
  225. if !isService && c.Host == "" {
  226. if err := loadConfigFromProvider(); err != nil {
  227. return err
  228. }
  229. if !config.isEnabled() {
  230. return nil
  231. }
  232. // If not running as a service, templates will only be loaded if required.
  233. return c.loadTemplates(configDir)
  234. }
  235. // In service mode SMTP can be enabled from the WebAdmin at runtime so we
  236. // always load templates.
  237. if err := c.loadTemplates(configDir); err != nil {
  238. return err
  239. }
  240. if c.Host == "" {
  241. return loadConfigFromProvider()
  242. }
  243. if err := c.validate(); err != nil {
  244. return err
  245. }
  246. initialConfig = c
  247. config.Set(nil)
  248. logger.Debug(logSender, "", "configuration successfully initialized, host: %q, port: %d, username: %q, auth: %d, encryption: %d, helo: %q",
  249. c.Host, c.Port, c.User, c.AuthType, c.Encryption, c.Domain)
  250. return loadConfigFromProvider()
  251. }
  252. func (c *Config) getMailClientOptions() []mail.Option {
  253. options := []mail.Option{mail.WithoutNoop()}
  254. switch c.Encryption {
  255. case 1:
  256. options = append(options, mail.WithSSLPort(false))
  257. case 2:
  258. options = append(options, mail.WithTLSPortPolicy(mail.TLSMandatory))
  259. default:
  260. options = append(options, mail.WithTLSPortPolicy(mail.NoTLS))
  261. }
  262. if c.User != "" {
  263. options = append(options, mail.WithUsername(c.User))
  264. }
  265. if c.Password != "" {
  266. options = append(options, mail.WithPassword(c.Password))
  267. }
  268. if c.User != "" || c.Password != "" {
  269. switch c.AuthType {
  270. case 1:
  271. options = append(options, mail.WithSMTPAuth(mail.SMTPAuthLogin))
  272. case 2:
  273. options = append(options, mail.WithSMTPAuth(mail.SMTPAuthCramMD5))
  274. case 3:
  275. options = append(options, mail.WithSMTPAuth(mail.SMTPAuthXOAUTH2))
  276. default:
  277. options = append(options, mail.WithSMTPAuth(mail.SMTPAuthPlain))
  278. }
  279. }
  280. if c.Domain != "" {
  281. options = append(options, mail.WithHELO(c.Domain))
  282. }
  283. if c.Debug > 0 {
  284. options = append(options,
  285. mail.WithLogger(&logger.MailAdapter{
  286. ConnectionID: xid.New().String(),
  287. }),
  288. mail.WithDebugLog())
  289. }
  290. options = append(options, mail.WithPort(c.Port))
  291. return options
  292. }
  293. func (c *Config) getSMTPClientAndMsg(to, bcc []string, subject, body string, contentType EmailContentType,
  294. attachments ...*mail.File) (*mail.Client, *mail.Msg, error) {
  295. msg := mail.NewMsg()
  296. msg.SetUserAgent(version.GetServerVersion(" ", true))
  297. var from string
  298. if c.From != "" {
  299. from = c.From
  300. } else {
  301. from = c.User
  302. }
  303. if err := msg.From(from); err != nil {
  304. return nil, nil, fmt.Errorf("invalid from address: %w", err)
  305. }
  306. if err := msg.To(to...); err != nil {
  307. return nil, nil, err
  308. }
  309. if len(bcc) > 0 {
  310. if err := msg.Bcc(bcc...); err != nil {
  311. return nil, nil, err
  312. }
  313. }
  314. msg.Subject(subject)
  315. msg.SetDate()
  316. msg.SetMessageID()
  317. msg.SetAttachements(attachments)
  318. switch contentType {
  319. case EmailContentTypeTextPlain:
  320. msg.SetBodyString(mail.TypeTextPlain, body)
  321. case EmailContentTypeTextHTML:
  322. msg.SetBodyString(mail.TypeTextHTML, body)
  323. default:
  324. return nil, nil, fmt.Errorf("smtp: unsupported body content type %v", contentType)
  325. }
  326. client, err := mail.NewClient(c.Host, c.getMailClientOptions()...)
  327. if err != nil {
  328. return nil, nil, fmt.Errorf("unable to create mail client: %w", err)
  329. }
  330. if c.AuthType == 3 {
  331. token, err := c.OAuth2.getAccessToken()
  332. if err != nil {
  333. return nil, nil, fmt.Errorf("unable to get oauth2 access token: %w", err)
  334. }
  335. client.SetPassword(token)
  336. }
  337. return client, msg, nil
  338. }
  339. // SendEmail tries to send an email using the specified parameters
  340. func (c *Config) SendEmail(to, bcc []string, subject, body string, contentType EmailContentType, attachments ...*mail.File) error {
  341. client, msg, err := c.getSMTPClientAndMsg(to, bcc, subject, body, contentType, attachments...)
  342. if err != nil {
  343. return err
  344. }
  345. ctx, cancelFn := context.WithTimeout(context.Background(), dialTimeout)
  346. defer cancelFn()
  347. return client.DialAndSendWithContext(ctx, msg)
  348. }
  349. func loadTemplates(templatesPath string) {
  350. logger.Debug(logSender, "", "loading templates from %q", templatesPath)
  351. passwordResetPath := filepath.Join(templatesPath, templatePasswordReset)
  352. pwdResetTmpl := util.LoadTemplate(nil, passwordResetPath)
  353. passwordExpirationPath := filepath.Join(templatesPath, templatePasswordExpiration)
  354. pwdExpirationTmpl := util.LoadTemplate(nil, passwordExpirationPath)
  355. emailTemplates[templatePasswordReset] = pwdResetTmpl
  356. emailTemplates[templatePasswordExpiration] = pwdExpirationTmpl
  357. }
  358. // RenderPasswordResetTemplate executes the password reset template
  359. func RenderPasswordResetTemplate(buf *bytes.Buffer, data any) error {
  360. if !IsEnabled() {
  361. return errors.New("smtp: not configured")
  362. }
  363. return emailTemplates[templatePasswordReset].Execute(buf, data)
  364. }
  365. // RenderPasswordExpirationTemplate executes the password expiration template
  366. func RenderPasswordExpirationTemplate(buf *bytes.Buffer, data any) error {
  367. if !IsEnabled() {
  368. return errors.New("smtp: not configured")
  369. }
  370. return emailTemplates[templatePasswordExpiration].Execute(buf, data)
  371. }
  372. // SendEmail tries to send an email using the specified parameters.
  373. func SendEmail(to, bcc []string, subject, body string, contentType EmailContentType, attachments ...*mail.File) error {
  374. return config.sendEmail(to, bcc, subject, body, contentType, attachments...)
  375. }
  376. // ReloadProviderConf reloads the configuration from the provider
  377. // and apply it if different from the active one
  378. func ReloadProviderConf() {
  379. loadConfigFromProvider() //nolint:errcheck
  380. }
  381. func loadConfigFromProvider() error {
  382. configs, err := dataprovider.GetConfigs()
  383. if err != nil {
  384. logger.Error(logSender, "", "unable to load config from provider: %v", err)
  385. return fmt.Errorf("smtp: unable to load config from provider: %w", err)
  386. }
  387. configs.SetNilsToEmpty()
  388. if err := configs.SMTP.TryDecrypt(); err != nil {
  389. logger.Error(logSender, "", "unable to decrypt smtp config: %v", err)
  390. return fmt.Errorf("smtp: unable to decrypt smtp config: %w", err)
  391. }
  392. config.Set(configs.SMTP)
  393. return nil
  394. }
  395. func updateRefreshToken(token string) {
  396. configs, err := dataprovider.GetConfigs()
  397. if err != nil {
  398. logger.Error(logSender, "", "unable to load config from provider, updating refresh token not possible: %v", err)
  399. return
  400. }
  401. configs.SetNilsToEmpty()
  402. if configs.SMTP.IsEmpty() {
  403. logger.Warn(logSender, "", "unable to update refresh token, smtp not configured in the data provider")
  404. return
  405. }
  406. configs.SMTP.OAuth2.RefreshToken = kms.NewPlainSecret(token)
  407. if err := dataprovider.UpdateConfigs(&configs, dataprovider.ActionExecutorSystem, "", ""); err != nil {
  408. logger.Error(logSender, "", "unable to save new refresh token: %v", err)
  409. return
  410. }
  411. logger.Info(logSender, "", "refresh token updated")
  412. }