acme.go 26 KB

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