acme.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. // Copyright (C) 2019-2023 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 acme provides automatic access to certificates from Let's Encrypt and any other ACME-based CA
  15. // The code here is largely coiped from https://github.com/go-acme/lego/tree/master/cmd
  16. // This package is intended to provide basic functionality for obtaining and renewing certificates
  17. // and implements the "HTTP-01" and "TLSALPN-01" challenge types.
  18. // For more advanced features use external tools such as "lego"
  19. package acme
  20. import (
  21. "crypto"
  22. "crypto/x509"
  23. "encoding/json"
  24. "encoding/pem"
  25. "errors"
  26. "fmt"
  27. "math/rand"
  28. "net/url"
  29. "os"
  30. "path/filepath"
  31. "strconv"
  32. "strings"
  33. "time"
  34. "github.com/go-acme/lego/v4/certcrypto"
  35. "github.com/go-acme/lego/v4/certificate"
  36. "github.com/go-acme/lego/v4/challenge"
  37. "github.com/go-acme/lego/v4/challenge/http01"
  38. "github.com/go-acme/lego/v4/challenge/tlsalpn01"
  39. "github.com/go-acme/lego/v4/lego"
  40. "github.com/go-acme/lego/v4/log"
  41. "github.com/go-acme/lego/v4/providers/http/webroot"
  42. "github.com/go-acme/lego/v4/registration"
  43. "github.com/robfig/cron/v3"
  44. "github.com/drakkan/sftpgo/v2/internal/common"
  45. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  46. "github.com/drakkan/sftpgo/v2/internal/ftpd"
  47. "github.com/drakkan/sftpgo/v2/internal/logger"
  48. "github.com/drakkan/sftpgo/v2/internal/telemetry"
  49. "github.com/drakkan/sftpgo/v2/internal/util"
  50. "github.com/drakkan/sftpgo/v2/internal/version"
  51. "github.com/drakkan/sftpgo/v2/internal/webdavd"
  52. )
  53. const (
  54. logSender = "acme"
  55. )
  56. var (
  57. config *Configuration
  58. initialConfig Configuration
  59. scheduler *cron.Cron
  60. logMode int
  61. supportedKeyTypes = []string{
  62. string(certcrypto.EC256),
  63. string(certcrypto.EC384),
  64. string(certcrypto.RSA2048),
  65. string(certcrypto.RSA4096),
  66. string(certcrypto.RSA8192),
  67. }
  68. fnReloadHTTPDCerts func() error
  69. )
  70. // SetReloadHTTPDCertsFn set the function to call to reload HTTPD certificates
  71. func SetReloadHTTPDCertsFn(fn func() error) {
  72. fnReloadHTTPDCerts = fn
  73. }
  74. // GetCertificates tries to obtain the certificates using the global configuration
  75. func GetCertificates() error {
  76. if config == nil {
  77. return errors.New("acme is disabled")
  78. }
  79. return config.getCertificates()
  80. }
  81. // GetCertificatesForConfig tries to obtain the certificates using the provided
  82. // configuration override. This is a NOOP if we already have certificates
  83. func GetCertificatesForConfig(c *dataprovider.ACMEConfigs, configDir string) error {
  84. if c.Domain == "" {
  85. acmeLog(logger.LevelDebug, "no domain configured, nothing to do")
  86. return nil
  87. }
  88. config := mergeConfig(getConfiguration(), c)
  89. if err := config.Initialize(configDir); err != nil {
  90. return err
  91. }
  92. hasCerts, err := config.hasCertificates(c.Domain)
  93. if err != nil {
  94. return fmt.Errorf("unable to check if we already have certificates for domain %q: %w", c.Domain, err)
  95. }
  96. if hasCerts {
  97. return nil
  98. }
  99. return config.getCertificates()
  100. }
  101. // GetHTTP01WebRoot returns the web root for HTTP-01 challenge
  102. func GetHTTP01WebRoot() string {
  103. return initialConfig.HTTP01Challenge.WebRoot
  104. }
  105. func mergeConfig(config Configuration, c *dataprovider.ACMEConfigs) Configuration {
  106. config.Domains = []string{c.Domain}
  107. config.Email = c.Email
  108. config.HTTP01Challenge.Port = c.HTTP01Challenge.Port
  109. config.TLSALPN01Challenge.Port = 0
  110. return config
  111. }
  112. // getConfiguration returns the configuration set using config file and env vars
  113. func getConfiguration() Configuration {
  114. return initialConfig
  115. }
  116. func loadProviderConf(c Configuration) (Configuration, error) {
  117. configs, err := dataprovider.GetConfigs()
  118. if err != nil {
  119. return c, fmt.Errorf("unable to load config from provider: %w", err)
  120. }
  121. configs.SetNilsToEmpty()
  122. if configs.ACME.Domain == "" {
  123. return c, nil
  124. }
  125. return mergeConfig(c, configs.ACME), nil
  126. }
  127. // Initialize validates and set the configuration
  128. func Initialize(c Configuration, configDir string, checkRenew bool) error {
  129. config = nil
  130. initialConfig = c
  131. c, err := loadProviderConf(c)
  132. if err != nil {
  133. return err
  134. }
  135. util.CertsBasePath = ""
  136. setLogMode(checkRenew)
  137. if err := c.Initialize(configDir); err != nil {
  138. return err
  139. }
  140. if len(c.Domains) == 0 {
  141. return nil
  142. }
  143. util.CertsBasePath = c.CertsPath
  144. acmeLog(logger.LevelInfo, "configured domains: %+v, certs base path %q", c.Domains, c.CertsPath)
  145. config = &c
  146. if checkRenew {
  147. return startScheduler()
  148. }
  149. return nil
  150. }
  151. // HTTP01Challenge defines the configuration for HTTP-01 challenge type
  152. type HTTP01Challenge struct {
  153. Port int `json:"port" mapstructure:"port"`
  154. WebRoot string `json:"webroot" mapstructure:"webroot"`
  155. ProxyHeader string `json:"proxy_header" mapstructure:"proxy_header"`
  156. }
  157. func (c *HTTP01Challenge) isEnabled() bool {
  158. return c.Port > 0 || c.WebRoot != ""
  159. }
  160. func (c *HTTP01Challenge) validate() error {
  161. if !c.isEnabled() {
  162. return nil
  163. }
  164. if c.WebRoot != "" {
  165. if !filepath.IsAbs(c.WebRoot) {
  166. return fmt.Errorf("invalid HTTP-01 challenge web root, please set an absolute path")
  167. }
  168. _, err := os.Stat(c.WebRoot)
  169. if err != nil {
  170. return fmt.Errorf("invalid HTTP-01 challenge web root: %w", err)
  171. }
  172. } else {
  173. if c.Port > 65535 {
  174. return fmt.Errorf("invalid HTTP-01 challenge port: %d", c.Port)
  175. }
  176. }
  177. return nil
  178. }
  179. // TLSALPN01Challenge defines the configuration for TLSALPN-01 challenge type
  180. type TLSALPN01Challenge struct {
  181. Port int `json:"port" mapstructure:"port"`
  182. }
  183. func (c *TLSALPN01Challenge) isEnabled() bool {
  184. return c.Port > 0
  185. }
  186. func (c *TLSALPN01Challenge) validate() error {
  187. if !c.isEnabled() {
  188. return nil
  189. }
  190. if c.Port > 65535 {
  191. return fmt.Errorf("invalid TLSALPN-01 challenge port: %d", c.Port)
  192. }
  193. return nil
  194. }
  195. // Configuration holds the ACME configuration
  196. type Configuration struct {
  197. Email string `json:"email" mapstructure:"email"`
  198. KeyType string `json:"key_type" mapstructure:"key_type"`
  199. CertsPath string `json:"certs_path" mapstructure:"certs_path"`
  200. CAEndpoint string `json:"ca_endpoint" mapstructure:"ca_endpoint"`
  201. // if a certificate is to be valid for multiple domains specify the names separated by commas,
  202. // for example: example.com,www.example.com
  203. Domains []string `json:"domains" mapstructure:"domains"`
  204. RenewDays int `json:"renew_days" mapstructure:"renew_days"`
  205. HTTP01Challenge HTTP01Challenge `json:"http01_challenge" mapstructure:"http01_challenge"`
  206. TLSALPN01Challenge TLSALPN01Challenge `json:"tls_alpn01_challenge" mapstructure:"tls_alpn01_challenge"`
  207. accountConfigPath string
  208. accountKeyPath string
  209. lockPath string
  210. tempDir string
  211. }
  212. // Initialize validates and initialize the configuration
  213. func (c *Configuration) Initialize(configDir string) error {
  214. c.checkDomains()
  215. if len(c.Domains) == 0 {
  216. acmeLog(logger.LevelInfo, "no domains configured, acme disabled")
  217. return nil
  218. }
  219. if c.Email == "" || !util.IsEmailValid(c.Email) {
  220. return fmt.Errorf("invalid email address %q", c.Email)
  221. }
  222. if c.RenewDays < 1 {
  223. return fmt.Errorf("invalid number of days remaining before renewal: %d", c.RenewDays)
  224. }
  225. if !util.Contains(supportedKeyTypes, c.KeyType) {
  226. return fmt.Errorf("invalid key type %q", c.KeyType)
  227. }
  228. caURL, err := url.Parse(c.CAEndpoint)
  229. if err != nil {
  230. return fmt.Errorf("invalid CA endopoint: %w", err)
  231. }
  232. if !util.IsFileInputValid(c.CertsPath) {
  233. return fmt.Errorf("invalid certs path %q", c.CertsPath)
  234. }
  235. if !filepath.IsAbs(c.CertsPath) {
  236. c.CertsPath = filepath.Join(configDir, c.CertsPath)
  237. }
  238. err = os.MkdirAll(c.CertsPath, 0700)
  239. if err != nil {
  240. return fmt.Errorf("unable to create certs path %q: %w", c.CertsPath, err)
  241. }
  242. c.tempDir = filepath.Join(c.CertsPath, "temp")
  243. err = os.MkdirAll(c.CertsPath, 0700)
  244. if err != nil {
  245. return fmt.Errorf("unable to create certs temp path %q: %w", c.tempDir, err)
  246. }
  247. serverPath := strings.NewReplacer(":", "_", "/", string(os.PathSeparator)).Replace(caURL.Host)
  248. accountPath := filepath.Join(c.CertsPath, serverPath)
  249. err = os.MkdirAll(accountPath, 0700)
  250. if err != nil {
  251. return fmt.Errorf("unable to create account path %q: %w", accountPath, err)
  252. }
  253. c.accountConfigPath = filepath.Join(accountPath, c.Email+".json")
  254. c.accountKeyPath = filepath.Join(accountPath, c.Email+".key")
  255. c.lockPath = filepath.Join(c.CertsPath, "lock")
  256. return c.validateChallenges()
  257. }
  258. func (c *Configuration) validateChallenges() error {
  259. if !c.HTTP01Challenge.isEnabled() && !c.TLSALPN01Challenge.isEnabled() {
  260. return fmt.Errorf("no challenge type defined")
  261. }
  262. if err := c.HTTP01Challenge.validate(); err != nil {
  263. return err
  264. }
  265. return c.TLSALPN01Challenge.validate()
  266. }
  267. func (c *Configuration) checkDomains() {
  268. var domains []string
  269. for _, domain := range c.Domains {
  270. domain = strings.TrimSpace(domain)
  271. if domain == "" {
  272. continue
  273. }
  274. if d, ok := isDomainValid(domain); ok {
  275. domains = append(domains, d)
  276. }
  277. }
  278. c.Domains = util.RemoveDuplicates(domains, true)
  279. }
  280. func (c *Configuration) setLockTime() error {
  281. lockTime := fmt.Sprintf("%v", util.GetTimeAsMsSinceEpoch(time.Now()))
  282. err := os.WriteFile(c.lockPath, []byte(lockTime), 0600)
  283. if err != nil {
  284. acmeLog(logger.LevelError, "unable to save lock time to %q: %v", c.lockPath, err)
  285. return fmt.Errorf("unable to save lock time: %w", err)
  286. }
  287. acmeLog(logger.LevelDebug, "lock time saved: %q", lockTime)
  288. return nil
  289. }
  290. func (c *Configuration) getLockTime() (time.Time, error) {
  291. content, err := os.ReadFile(c.lockPath)
  292. if err != nil {
  293. if os.IsNotExist(err) {
  294. acmeLog(logger.LevelDebug, "lock file %q not found", c.lockPath)
  295. return time.Time{}, nil
  296. }
  297. acmeLog(logger.LevelError, "unable to read lock file %q: %v", c.lockPath, err)
  298. return time.Time{}, err
  299. }
  300. msec, err := strconv.ParseInt(strings.TrimSpace(string(content)), 10, 64)
  301. if err != nil {
  302. acmeLog(logger.LevelError, "unable to parse lock time: %v", err)
  303. return time.Time{}, fmt.Errorf("unable to parse lock time: %w", err)
  304. }
  305. return util.GetTimeFromMsecSinceEpoch(msec), nil
  306. }
  307. func (c *Configuration) saveAccount(account *account) error {
  308. jsonBytes, err := json.MarshalIndent(account, "", "\t")
  309. if err != nil {
  310. return err
  311. }
  312. err = os.WriteFile(c.accountConfigPath, jsonBytes, 0600)
  313. if err != nil {
  314. acmeLog(logger.LevelError, "unable to save account to file %q: %v", c.accountConfigPath, err)
  315. return fmt.Errorf("unable to save account: %w", err)
  316. }
  317. return nil
  318. }
  319. func (c *Configuration) getAccount(privateKey crypto.PrivateKey) (account, error) {
  320. _, err := os.Stat(c.accountConfigPath)
  321. if err != nil && os.IsNotExist(err) {
  322. acmeLog(logger.LevelDebug, "account does not exist")
  323. return account{Email: c.Email, key: privateKey}, nil
  324. }
  325. var account account
  326. fileBytes, err := os.ReadFile(c.accountConfigPath)
  327. if err != nil {
  328. acmeLog(logger.LevelError, "unable to read account from file %q: %v", c.accountConfigPath, err)
  329. return account, fmt.Errorf("unable to read account from file: %w", err)
  330. }
  331. err = json.Unmarshal(fileBytes, &account)
  332. if err != nil {
  333. acmeLog(logger.LevelError, "invalid account file content: %v", err)
  334. return account, fmt.Errorf("unable to parse account file as JSON: %w", err)
  335. }
  336. account.key = privateKey
  337. if account.Registration == nil || account.Registration.Body.Status == "" {
  338. acmeLog(logger.LevelInfo, "couldn't load account but got a key. Try to look the account up")
  339. reg, err := c.tryRecoverRegistration(privateKey)
  340. if err != nil {
  341. acmeLog(logger.LevelError, "unable to look the account up: %v", err)
  342. return account, fmt.Errorf("unable to look the account up: %w", err)
  343. }
  344. account.Registration = reg
  345. err = c.saveAccount(&account)
  346. if err != nil {
  347. return account, err
  348. }
  349. }
  350. return account, nil
  351. }
  352. func (c *Configuration) loadPrivateKey() (crypto.PrivateKey, error) {
  353. keyBytes, err := os.ReadFile(c.accountKeyPath)
  354. if err != nil {
  355. acmeLog(logger.LevelError, "unable to read account key from file %q: %v", c.accountKeyPath, err)
  356. return nil, fmt.Errorf("unable to read account key: %w", err)
  357. }
  358. keyBlock, _ := pem.Decode(keyBytes)
  359. var privateKey crypto.PrivateKey
  360. switch keyBlock.Type {
  361. case "RSA PRIVATE KEY":
  362. privateKey, err = x509.ParsePKCS1PrivateKey(keyBlock.Bytes)
  363. case "EC PRIVATE KEY":
  364. privateKey, err = x509.ParseECPrivateKey(keyBlock.Bytes)
  365. default:
  366. err = fmt.Errorf("unknown private key type %q", keyBlock.Type)
  367. }
  368. if err != nil {
  369. acmeLog(logger.LevelError, "unable to parse private key from file %q: %v", c.accountKeyPath, err)
  370. return privateKey, fmt.Errorf("unable to parse private key: %w", err)
  371. }
  372. return privateKey, nil
  373. }
  374. func (c *Configuration) generatePrivateKey() (crypto.PrivateKey, error) {
  375. privateKey, err := certcrypto.GeneratePrivateKey(certcrypto.KeyType(c.KeyType))
  376. if err != nil {
  377. acmeLog(logger.LevelError, "unable to generate private key: %v", err)
  378. return nil, fmt.Errorf("unable to generate private key: %w", err)
  379. }
  380. certOut, err := os.Create(c.accountKeyPath)
  381. if err != nil {
  382. acmeLog(logger.LevelError, "unable to save private key to file %q: %v", c.accountKeyPath, err)
  383. return nil, fmt.Errorf("unable to save private key: %w", err)
  384. }
  385. defer certOut.Close()
  386. pemKey := certcrypto.PEMBlock(privateKey)
  387. err = pem.Encode(certOut, pemKey)
  388. if err != nil {
  389. acmeLog(logger.LevelError, "unable to encode private key: %v", err)
  390. return nil, fmt.Errorf("unable to encode private key: %w", err)
  391. }
  392. acmeLog(logger.LevelDebug, "new account private key generated")
  393. return privateKey, nil
  394. }
  395. func (c *Configuration) getPrivateKey() (crypto.PrivateKey, error) {
  396. _, err := os.Stat(c.accountKeyPath)
  397. if err != nil && os.IsNotExist(err) {
  398. acmeLog(logger.LevelDebug, "private key file %q does not exist, generating new private key", c.accountKeyPath)
  399. return c.generatePrivateKey()
  400. }
  401. acmeLog(logger.LevelDebug, "loading private key from file %q, stat error: %v", c.accountKeyPath, err)
  402. return c.loadPrivateKey()
  403. }
  404. func (c *Configuration) loadCertificatesForDomain(domain string) ([]*x509.Certificate, error) {
  405. domain = util.SanitizeDomain(domain)
  406. acmeLog(logger.LevelDebug, "loading certificates for domain %q", domain)
  407. content, err := os.ReadFile(filepath.Join(c.CertsPath, domain+".crt"))
  408. if err != nil {
  409. acmeLog(logger.LevelError, "unable to load certificates for domain %q: %v", domain, err)
  410. return nil, fmt.Errorf("unable to load certificates for domain %q: %w", domain, err)
  411. }
  412. certs, err := certcrypto.ParsePEMBundle(content)
  413. if err != nil {
  414. acmeLog(logger.LevelError, "unable to parse certificates for domain %q: %v", domain, err)
  415. return certs, fmt.Errorf("unable to parse certificates for domain %q: %w", domain, err)
  416. }
  417. return certs, nil
  418. }
  419. func (c *Configuration) needRenewal(x509Cert *x509.Certificate, domain string) bool {
  420. if x509Cert.IsCA {
  421. acmeLog(logger.LevelError, "certificate bundle starts with a CA certificate, cannot renew domain %v", domain)
  422. return false
  423. }
  424. notAfter := int(time.Until(x509Cert.NotAfter).Hours() / 24.0)
  425. if notAfter > c.RenewDays {
  426. acmeLog(logger.LevelDebug, "the certificate for domain %q expires in %d days, no renewal", domain, notAfter)
  427. return false
  428. }
  429. return true
  430. }
  431. func (c *Configuration) setup() (*account, *lego.Client, error) {
  432. privateKey, err := c.getPrivateKey()
  433. if err != nil {
  434. return nil, nil, err
  435. }
  436. account, err := c.getAccount(privateKey)
  437. if err != nil {
  438. return nil, nil, err
  439. }
  440. config := lego.NewConfig(&account)
  441. config.CADirURL = c.CAEndpoint
  442. config.Certificate.KeyType = certcrypto.KeyType(c.KeyType)
  443. config.UserAgent = fmt.Sprintf("SFTPGo/%v", version.Get().Version)
  444. client, err := lego.NewClient(config)
  445. if err != nil {
  446. acmeLog(logger.LevelError, "unable to get ACME client: %v", err)
  447. return nil, nil, fmt.Errorf("unable to get ACME client: %w", err)
  448. }
  449. err = c.setupChalleges(client)
  450. if err != nil {
  451. return nil, nil, err
  452. }
  453. return &account, client, nil
  454. }
  455. func (c *Configuration) setupChalleges(client *lego.Client) error {
  456. client.Challenge.Remove(challenge.DNS01)
  457. if c.HTTP01Challenge.isEnabled() {
  458. if c.HTTP01Challenge.WebRoot != "" {
  459. acmeLog(logger.LevelDebug, "configuring HTTP-01 web root challenge, path %q", c.HTTP01Challenge.WebRoot)
  460. providerServer, err := webroot.NewHTTPProvider(c.HTTP01Challenge.WebRoot)
  461. if err != nil {
  462. acmeLog(logger.LevelError, "unable to create HTTP-01 web root challenge provider from path %q: %v",
  463. c.HTTP01Challenge.WebRoot, err)
  464. return fmt.Errorf("unable to create HTTP-01 web root challenge provider: %w", err)
  465. }
  466. err = client.Challenge.SetHTTP01Provider(providerServer)
  467. if err != nil {
  468. acmeLog(logger.LevelError, "unable to set HTTP-01 challenge provider: %v", err)
  469. return fmt.Errorf("unable to set HTTP-01 challenge provider: %w", err)
  470. }
  471. } else {
  472. acmeLog(logger.LevelDebug, "configuring HTTP-01 challenge, port %d", c.HTTP01Challenge.Port)
  473. providerServer := http01.NewProviderServer("", fmt.Sprintf("%d", c.HTTP01Challenge.Port))
  474. if c.HTTP01Challenge.ProxyHeader != "" {
  475. acmeLog(logger.LevelDebug, "setting proxy header to \"%s\"", c.HTTP01Challenge.ProxyHeader)
  476. providerServer.SetProxyHeader(c.HTTP01Challenge.ProxyHeader)
  477. }
  478. err := client.Challenge.SetHTTP01Provider(providerServer)
  479. if err != nil {
  480. acmeLog(logger.LevelError, "unable to set HTTP-01 challenge provider: %v", err)
  481. return fmt.Errorf("unable to set HTTP-01 challenge provider: %w", err)
  482. }
  483. }
  484. } else {
  485. client.Challenge.Remove(challenge.HTTP01)
  486. }
  487. if c.TLSALPN01Challenge.isEnabled() {
  488. acmeLog(logger.LevelDebug, "configuring TLSALPN-01 challenge, port %d", c.TLSALPN01Challenge.Port)
  489. err := client.Challenge.SetTLSALPN01Provider(tlsalpn01.NewProviderServer("", fmt.Sprintf("%d", c.TLSALPN01Challenge.Port)))
  490. if err != nil {
  491. acmeLog(logger.LevelError, "unable to set TLSALPN-01 challenge provider: %v", err)
  492. return fmt.Errorf("unable to set TLSALPN-01 challenge provider: %w", err)
  493. }
  494. } else {
  495. client.Challenge.Remove(challenge.TLSALPN01)
  496. }
  497. return nil
  498. }
  499. func (c *Configuration) register(client *lego.Client) (*registration.Resource, error) {
  500. return client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
  501. }
  502. func (c *Configuration) tryRecoverRegistration(privateKey crypto.PrivateKey) (*registration.Resource, error) {
  503. config := lego.NewConfig(&account{key: privateKey})
  504. config.CADirURL = c.CAEndpoint
  505. config.UserAgent = fmt.Sprintf("SFTPGo/%v", version.Get().Version)
  506. client, err := lego.NewClient(config)
  507. if err != nil {
  508. acmeLog(logger.LevelError, "unable to get the ACME client: %v", err)
  509. return nil, err
  510. }
  511. return client.Registration.ResolveAccountByKey()
  512. }
  513. func (c *Configuration) getCrtPath(domain string) string {
  514. return filepath.Join(c.CertsPath, domain+".crt")
  515. }
  516. func (c *Configuration) getKeyPath(domain string) string {
  517. return filepath.Join(c.CertsPath, domain+".key")
  518. }
  519. func (c *Configuration) getResourcePath(domain string) string {
  520. return filepath.Join(c.CertsPath, domain+".json")
  521. }
  522. func (c *Configuration) obtainAndSaveCertificate(client *lego.Client, domain string) error {
  523. domains := getDomains(domain)
  524. acmeLog(logger.LevelInfo, "requesting certificates for domains %+v", domains)
  525. request := certificate.ObtainRequest{
  526. Domains: domains,
  527. Bundle: true,
  528. MustStaple: false,
  529. PreferredChain: "",
  530. AlwaysDeactivateAuthorizations: false,
  531. }
  532. cert, err := client.Certificate.Obtain(request)
  533. if err != nil {
  534. acmeLog(logger.LevelError, "unable to obtain certificates for domains %+v: %v", domains, err)
  535. return fmt.Errorf("unable to obtain certificates: %w", err)
  536. }
  537. domain = util.SanitizeDomain(domain)
  538. err = os.WriteFile(c.getCrtPath(domain), cert.Certificate, 0600)
  539. if err != nil {
  540. acmeLog(logger.LevelError, "unable to save certificate for domain %s: %v", domain, err)
  541. return fmt.Errorf("unable to save certificate: %w", err)
  542. }
  543. err = os.WriteFile(c.getKeyPath(domain), cert.PrivateKey, 0600)
  544. if err != nil {
  545. acmeLog(logger.LevelError, "unable to save private key for domain %s: %v", domain, err)
  546. return fmt.Errorf("unable to save private key: %w", err)
  547. }
  548. jsonBytes, err := json.MarshalIndent(cert, "", "\t")
  549. if err != nil {
  550. acmeLog(logger.LevelError, "unable to marshal certificate resources for domain %v: %v", domain, err)
  551. return err
  552. }
  553. err = os.WriteFile(c.getResourcePath(domain), jsonBytes, 0600)
  554. if err != nil {
  555. acmeLog(logger.LevelError, "unable to save certificate resources for domain %v: %v", domain, err)
  556. return fmt.Errorf("unable to save certificate resources: %w", err)
  557. }
  558. acmeLog(logger.LevelInfo, "certificates for domains %+v saved", domains)
  559. return nil
  560. }
  561. // hasCertificates returns true if certificates for the specified domain has already been issued
  562. func (c *Configuration) hasCertificates(domain string) (bool, error) {
  563. domain = util.SanitizeDomain(domain)
  564. if _, err := os.Stat(c.getCrtPath(domain)); err != nil {
  565. if os.IsNotExist(err) {
  566. return false, nil
  567. }
  568. return false, err
  569. }
  570. if _, err := os.Stat(c.getKeyPath(domain)); err != nil {
  571. if os.IsNotExist(err) {
  572. return false, nil
  573. }
  574. return false, err
  575. }
  576. return true, nil
  577. }
  578. // getCertificates tries to obtain the certificates for the configured domains
  579. func (c *Configuration) getCertificates() error {
  580. account, client, err := c.setup()
  581. if err != nil {
  582. return err
  583. }
  584. if account.Registration == nil {
  585. reg, err := c.register(client)
  586. if err != nil {
  587. acmeLog(logger.LevelError, "unable to register account: %v", err)
  588. return fmt.Errorf("unable to register account: %w", err)
  589. }
  590. account.Registration = reg
  591. err = c.saveAccount(account)
  592. if err != nil {
  593. return err
  594. }
  595. }
  596. for _, domain := range c.Domains {
  597. err = c.obtainAndSaveCertificate(client, domain)
  598. if err != nil {
  599. return err
  600. }
  601. }
  602. return nil
  603. }
  604. func (c *Configuration) notifyCertificateRenewal(domain string, err error) {
  605. if domain == "" {
  606. domain = strings.Join(c.Domains, ",")
  607. }
  608. params := common.EventParams{
  609. Name: domain,
  610. Event: "Certificate renewal",
  611. Timestamp: time.Now().UnixNano(),
  612. }
  613. if err != nil {
  614. params.Status = 2
  615. params.AddError(err)
  616. } else {
  617. params.Status = 1
  618. }
  619. common.HandleCertificateEvent(params)
  620. }
  621. func (c *Configuration) renewCertificates() error {
  622. lockTime, err := c.getLockTime()
  623. if err != nil {
  624. return err
  625. }
  626. acmeLog(logger.LevelDebug, "certificate renew lock time %v", lockTime)
  627. if lockTime.Add(-30*time.Second).Before(time.Now()) && lockTime.Add(5*time.Minute).After(time.Now()) {
  628. acmeLog(logger.LevelInfo, "certificate renew skipped, lock time too close: %v", lockTime)
  629. return nil
  630. }
  631. err = c.setLockTime()
  632. if err != nil {
  633. c.notifyCertificateRenewal("", err)
  634. return err
  635. }
  636. account, client, err := c.setup()
  637. if err != nil {
  638. c.notifyCertificateRenewal("", err)
  639. return err
  640. }
  641. if account.Registration == nil {
  642. acmeLog(logger.LevelError, "cannot renew certificates, your account is not registered")
  643. err = errors.New("cannot renew certificates, your account is not registered")
  644. c.notifyCertificateRenewal("", err)
  645. return err
  646. }
  647. var errRenew error
  648. needReload := false
  649. for _, domain := range c.Domains {
  650. certificates, err := c.loadCertificatesForDomain(domain)
  651. if err != nil {
  652. c.notifyCertificateRenewal(domain, err)
  653. errRenew = err
  654. continue
  655. }
  656. cert := certificates[0]
  657. if !c.needRenewal(cert, domain) {
  658. continue
  659. }
  660. err = c.obtainAndSaveCertificate(client, domain)
  661. if err != nil {
  662. c.notifyCertificateRenewal(domain, err)
  663. errRenew = err
  664. } else {
  665. c.notifyCertificateRenewal(domain, nil)
  666. needReload = true
  667. }
  668. }
  669. if needReload {
  670. // at least one certificate has been renewed, sends a reload to all services that may be using certificates
  671. err = ftpd.ReloadCertificateMgr()
  672. acmeLog(logger.LevelInfo, "ftpd certificate manager reloaded , error: %v", err)
  673. if fnReloadHTTPDCerts != nil {
  674. err = fnReloadHTTPDCerts()
  675. acmeLog(logger.LevelInfo, "httpd certificates manager reloaded , error: %v", err)
  676. }
  677. err = webdavd.ReloadCertificateMgr()
  678. acmeLog(logger.LevelInfo, "webdav certificates manager reloaded , error: %v", err)
  679. err = telemetry.ReloadCertificateMgr()
  680. acmeLog(logger.LevelInfo, "telemetry certificates manager reloaded , error: %v", err)
  681. }
  682. return errRenew
  683. }
  684. func isDomainValid(domain string) (string, bool) {
  685. isValid := false
  686. for _, d := range strings.Split(domain, ",") {
  687. d = strings.TrimSpace(d)
  688. if d != "" {
  689. isValid = true
  690. break
  691. }
  692. }
  693. return domain, isValid
  694. }
  695. func getDomains(domain string) []string {
  696. var domains []string
  697. delimiter := ","
  698. if !strings.Contains(domain, ",") && strings.Contains(domain, " ") {
  699. delimiter = " "
  700. }
  701. for _, d := range strings.Split(domain, delimiter) {
  702. d = strings.TrimSpace(d)
  703. if d != "" {
  704. domains = append(domains, d)
  705. }
  706. }
  707. return util.RemoveDuplicates(domains, false)
  708. }
  709. func stopScheduler() {
  710. if scheduler != nil {
  711. scheduler.Stop()
  712. scheduler = nil
  713. }
  714. }
  715. func startScheduler() error {
  716. stopScheduler()
  717. randSecs := rand.Intn(59)
  718. scheduler = cron.New(cron.WithLocation(time.UTC), cron.WithLogger(cron.DiscardLogger))
  719. _, err := scheduler.AddFunc(fmt.Sprintf("@every 12h0m%ds", randSecs), renewCertificates)
  720. if err != nil {
  721. return fmt.Errorf("unable to schedule certificates renewal: %w", err)
  722. }
  723. acmeLog(logger.LevelInfo, "starting scheduler, initial certificates check in %d seconds", randSecs)
  724. initialTimer := time.NewTimer(time.Duration(randSecs) * time.Second)
  725. go func() {
  726. <-initialTimer.C
  727. renewCertificates()
  728. }()
  729. scheduler.Start()
  730. return nil
  731. }
  732. func renewCertificates() {
  733. if config != nil {
  734. if err := config.renewCertificates(); err != nil {
  735. acmeLog(logger.LevelError, "unable to renew certificates: %v", err)
  736. }
  737. }
  738. }
  739. func setLogMode(checkRenew bool) {
  740. if checkRenew {
  741. logMode = 1
  742. } else {
  743. logMode = 2
  744. }
  745. log.Logger = &logger.LegoAdapter{
  746. LogToConsole: logMode != 1,
  747. }
  748. }
  749. func acmeLog(level logger.LogLevel, format string, v ...any) {
  750. if logMode == 1 {
  751. logger.Log(level, logSender, "", format, v...)
  752. } else {
  753. switch level {
  754. case logger.LevelDebug:
  755. logger.DebugToConsole(format, v...)
  756. case logger.LevelInfo:
  757. logger.InfoToConsole(format, v...)
  758. case logger.LevelWarn:
  759. logger.WarnToConsole(format, v...)
  760. default:
  761. logger.ErrorToConsole(format, v...)
  762. }
  763. }
  764. }