Skip to content

Commit 60f2033

Browse files
authored
Support custom ACME provider (#18340)
* Added ACMECAURL option to support custom ACME provider. Closes #18306 * Refactor setting.go https settings, renamed options and variables, and documented app.example.ini * Refactored runLetsEncrypt to runACME * Improved documentation
1 parent a60e8be commit 60f2033

File tree

6 files changed

+159
-50
lines changed

6 files changed

+159
-50
lines changed

cmd/web.go

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -222,18 +222,19 @@ func listen(m http.Handler, handleRedirector bool) error {
222222
}
223223
err = runHTTP("tcp", listenAddr, "Web", m)
224224
case setting.HTTPS:
225-
if setting.EnableLetsEncrypt {
226-
err = runLetsEncrypt(listenAddr, setting.Domain, setting.LetsEncryptDirectory, setting.LetsEncryptEmail, m)
225+
if setting.EnableAcme {
226+
err = runACME(listenAddr, m)
227227
break
228-
}
229-
if handleRedirector {
230-
if setting.RedirectOtherPort {
231-
go runHTTPRedirector()
232-
} else {
233-
NoHTTPRedirector()
228+
} else {
229+
if handleRedirector {
230+
if setting.RedirectOtherPort {
231+
go runHTTPRedirector()
232+
} else {
233+
NoHTTPRedirector()
234+
}
234235
}
236+
err = runHTTPS("tcp", listenAddr, "Web", setting.CertFile, setting.KeyFile, m)
235237
}
236-
err = runHTTPS("tcp", listenAddr, "Web", setting.CertFile, setting.KeyFile, m)
237238
case setting.FCGI:
238239
if handleRedirector {
239240
NoHTTPRedirector()

cmd/web_letsencrypt.go renamed to cmd/web_acme.go

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@
55
package cmd
66

77
import (
8+
"crypto/x509"
9+
"encoding/pem"
10+
"fmt"
811
"net/http"
12+
"os"
913
"strconv"
1014
"strings"
1115

@@ -16,7 +20,25 @@ import (
1620
"github.com/caddyserver/certmagic"
1721
)
1822

19-
func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler) error {
23+
func getCARoot(path string) (*x509.CertPool, error) {
24+
r, err := os.ReadFile(path)
25+
if err != nil {
26+
return nil, err
27+
}
28+
block, _ := pem.Decode(r)
29+
if block == nil {
30+
return nil, fmt.Errorf("no PEM found in the file %s", path)
31+
}
32+
caRoot, err := x509.ParseCertificate(block.Bytes)
33+
if err != nil {
34+
return nil, err
35+
}
36+
certPool := x509.NewCertPool()
37+
certPool.AddCert(caRoot)
38+
return certPool, nil
39+
}
40+
41+
func runACME(listenAddr string, m http.Handler) error {
2042
// If HTTP Challenge enabled, needs to be serving on port 80. For TLSALPN needs 443.
2143
// Due to docker port mapping this can't be checked programmatically
2244
// TODO: these are placeholders until we add options for each in settings with appropriate warning
@@ -33,10 +55,21 @@ func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler)
3355
}
3456

3557
magic := certmagic.NewDefault()
36-
magic.Storage = &certmagic.FileStorage{Path: directory}
58+
magic.Storage = &certmagic.FileStorage{Path: setting.AcmeLiveDirectory}
59+
// Try to use private CA root if provided, otherwise defaults to system's trust
60+
var certPool *x509.CertPool
61+
if setting.AcmeCARoot != "" {
62+
var err error
63+
certPool, err = getCARoot(setting.AcmeCARoot)
64+
if err != nil {
65+
log.Warn("Failed to parse CA Root certificate, using default CA trust: %v", err)
66+
}
67+
}
3768
myACME := certmagic.NewACMEManager(magic, certmagic.ACMEManager{
38-
Email: email,
39-
Agreed: setting.LetsEncryptTOS,
69+
CA: setting.AcmeURL,
70+
TrustedRoots: certPool,
71+
Email: setting.AcmeEmail,
72+
Agreed: setting.AcmeTOS,
4073
DisableHTTPChallenge: !enableHTTPChallenge,
4174
DisableTLSALPNChallenge: !enableTLSALPNChallenge,
4275
ListenHost: setting.HTTPAddr,
@@ -47,7 +80,7 @@ func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler)
4780
magic.Issuers = []certmagic.Issuer{myACME}
4881

4982
// this obtains certificates or renews them if necessary
50-
err := magic.ManageSync(graceful.GetManager().HammerContext(), []string{domain})
83+
err := magic.ManageSync(graceful.GetManager().HammerContext(), []string{setting.Domain})
5184
if err != nil {
5285
return err
5386
}

custom/conf/app.example.ini

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,36 @@ RUN_MODE = ; prod
178178
;OFFLINE_MODE = false
179179
;DISABLE_ROUTER_LOG = false
180180
;;
181+
;; TLS Settings: Either ACME or manual
182+
;; (Other common TLS configuration are found before)
183+
;ENABLE_ACME = false
184+
;;
185+
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
186+
;;
187+
;; ACME automatic TLS settings
188+
;;
189+
;; ACME directory URL (e.g. LetsEncrypt's staging/testing URL: https://acme-staging-v02.api.letsencrypt.org/directory)
190+
;; Leave empty to default to LetsEncrypt's (production) URL
191+
;ACME_URL =
192+
;;
193+
;; Explicitly accept the ACME's TOS. The specific TOS cannot be retrieved at the moment.
194+
;ACME_ACCEPTTOS = false
195+
;;
196+
;; If the ACME CA is not in your system's CA trust chain, it can be manually added here
197+
;ACME_CA_ROOT =
198+
;;
199+
;; Email used for the ACME registration service
200+
;; Can be left blank to initialize at first run and use the cached value
201+
;ACME_EMAIL =
202+
;;
203+
;; ACME live directory (not to be confused with ACME directory URL: ACME_URL)
204+
;; (Refer to caddy's ACME manager https://github.com/caddyserver/certmagic)
205+
;ACME_DIRECTORY = https
206+
;;
207+
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
208+
;;
209+
;; Manual TLS settings: (Only applicable if ENABLE_ACME=false)
210+
;;
181211
;; Generate steps:
182212
;; $ ./gitea cert -ca=true -duration=8760h0m0s -host=myhost.example.com
183213
;;

docs/content/doc/advanced/config-cheat-sheet.en-us.md

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -292,8 +292,8 @@ The following configuration set `Content-Type: application/vnd.android.package-a
292292
- `MINIMUM_KEY_SIZE_CHECK`: **true**: Indicate whether to check minimum key size with corresponding type.
293293

294294
- `OFFLINE_MODE`: **false**: Disables use of CDN for static files and Gravatar for profile pictures.
295-
- `CERT_FILE`: **https/cert.pem**: Cert file path used for HTTPS. When chaining, the server certificate must come first, then intermediate CA certificates (if any). From 1.11 paths are relative to `CUSTOM_PATH`.
296-
- `KEY_FILE`: **https/key.pem**: Key file path used for HTTPS. From 1.11 paths are relative to `CUSTOM_PATH`.
295+
- `CERT_FILE`: **https/cert.pem**: Cert file path used for HTTPS. When chaining, the server certificate must come first, then intermediate CA certificates (if any). This is ignored if `ENABLE_ACME=true`. From 1.11 paths are relative to `CUSTOM_PATH`.
296+
- `KEY_FILE`: **https/key.pem**: Key file path used for HTTPS. This is ignored if `ENABLE_ACME=true`. From 1.11 paths are relative to `CUSTOM_PATH`.
297297
- `STATIC_ROOT_PATH`: **./**: Upper level of template and static files path.
298298
- `APP_DATA_PATH`: **data** (**/data/gitea** on docker): Default path for application data.
299299
- `STATIC_CACHE_TIME`: **6h**: Web browser cache time for static resources on `custom/`, `public/` and all uploaded avatars. Note that this cache is disabled when `RUN_MODE` is "dev".
@@ -347,11 +347,12 @@ The following configuration set `Content-Type: application/vnd.android.package-a
347347
- Aliased names
348348
- "ecdhe_rsa_with_chacha20_poly1305" is an alias for "ecdhe_rsa_with_chacha20_poly1305_sha256"
349349
- "ecdhe_ecdsa_with_chacha20_poly1305" is alias for "ecdhe_ecdsa_with_chacha20_poly1305_sha256"
350-
- `ENABLE_LETSENCRYPT`: **false**: If enabled you must set `DOMAIN` to valid internet facing domain (ensure DNS is set and port 80 is accessible by letsencrypt validation server).
351-
By using Lets Encrypt **you must consent** to their [terms of service](https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf).
352-
- `LETSENCRYPT_ACCEPTTOS`: **false**: This is an explicit check that you accept the terms of service for Let's Encrypt.
353-
- `LETSENCRYPT_DIRECTORY`: **https**: Directory that Letsencrypt will use to cache information such as certs and private keys.
354-
- `LETSENCRYPT_EMAIL`: **[email protected]**: Email used by Letsencrypt to notify about problems with issued certificates. (No default)
350+
- `ENABLE_ACME`: **false**: Flag to enable automatic certificate management via an ACME capable Certificate Authority (CA) server (default: Lets Encrypt). If enabled, `CERT_FILE` and `KEY_FILE` are ignored, and the CA must resolve `DOMAIN` to this gitea server. Ensure that DNS records are set and either port `80` or port `443` are accessible by the CA server (the public internet by default), and redirected to the appropriate ports `PORT_TO_REDIRECT` or `HTTP_PORT` respectively.
351+
- `ACME_URL`: **\<empty\>**: The CA's ACME directory URL, e.g. for a self-hosted [smallstep CA server](https://github.com/smallstep/certificates), it can look like `https://ca.example.com/acme/acme/directory`. If left empty, it defaults to using Let's Encerypt's production CA (check `LETSENCRYPT_ACCEPTTOS` as well).
352+
- `ACME_ACCEPTTOS`: **false**: This is an explicit check that you accept the terms of service of the ACME provider. The default is Lets Encrypt [terms of service](https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf).
353+
- `ACME_DIRECTORY`: **https**: Directory that the certificate manager will use to cache information such as certs and private keys.
354+
- `ACME_EMAIL`: **\<empty\>**: Email used for the ACME registration. Usually it is to notify about problems with issued certificates.
355+
- `ACME_CA_ROOT`: **\<empty\>**: The CA's root certificate. If left empty, it defaults to using the system's trust chain.
355356
- `ALLOW_GRACEFUL_RESTARTS`: **true**: Perform a graceful restart on SIGHUP
356357
- `GRACEFUL_HAMMER_TIME`: **60s**: After a restart the parent process will stop accepting new connections and will allow requests to finish before stopping. Shutdown will be forced if it takes longer than this time.
357358
- `STARTUP_TIMEOUT`: **0**: Shutsdown the server if startup takes longer than the provided time. On Windows setting this sends a waithint to the SVC host to tell the SVC host startup may take some time. Please note startup is determined by the opening of the listeners - HTTP/HTTPS/SSH. Indexers may take longer to startup and can have their own timeouts.

docs/content/doc/usage/https-support.md

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,20 +55,34 @@ PORT_TO_REDIRECT = 3080
5555

5656
If you are using Docker, make sure that this port is configured in your `docker-compose.yml` file.
5757

58-
## Using Let's Encrypt
58+
## Using ACME (Default: Let's Encrypt)
5959

60-
[Let's Encrypt](https://letsencrypt.org/) is a Certificate Authority that allows you to automatically request and renew SSL/TLS certificates. In addition to starting Gitea on your configured port, to request HTTPS certificates, Gitea will also need to listed on port 80, and will set up an autoredirect to HTTPS for you. Let's Encrypt will need to be able to access Gitea via the Internet to verify your ownership of the domain.
60+
[ACME](https://tools.ietf.org/html/rfc8555) is a Certificate Authority standard protocol that allows you to automatically request and renew SSL/TLS certificates. [Let's Encrypt](https://letsencrypt.org/) is a free publicly trusted Certificate Authority server using this standard. Only `HTTP-01` and `TLS-ALPN-01` challenges are implemented. In order for ACME challenges to pass and verify your domain ownership, external traffic to the gitea domain on port `80` (`HTTP-01`) or port `443` (`TLS-ALPN-01`) has to be served by the gitea instance. Setting up [HTTP redirection](#setting-up-http-redirection) and port-forwards might be needed for external traffic to route correctly. Normal traffic to port `80` will otherwise be automatically redirected to HTTPS. **You must consent** to the ACME provider's terms of service (default Let's Encrypt's [terms of service](https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf)).
6161

62-
By using Let's Encrypt **you must consent** to their [terms of service](https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf).
62+
Minimum setup using the default Let's Encrypt:
63+
```ini
64+
[server]
65+
PROTOCOL=https
66+
DOMAIN=git.example.com
67+
ENABLE_ACME=true
68+
ACME_ACCEPTTOS=true
69+
ACME_DIRECTORY=https
70+
;; Email can be omitted here and provided manually at first run, after which it is cached
71+
72+
```
6373

74+
Minimumg setup using a [smallstep CA](https://github.com/smallstep/certificates), refer to [their tutorial](https://smallstep.com/docs/tutorials/acme-challenge) for more information.
6475
```ini
6576
[server]
6677
PROTOCOL=https
6778
DOMAIN=git.example.com
68-
ENABLE_LETSENCRYPT=true
69-
LETSENCRYPT_ACCEPTTOS=true
70-
LETSENCRYPT_DIRECTORY=https
71-
LETSENCRYPT_EMAIL[email protected]
79+
ENABLE_ACME=true
80+
ACME_ACCEPTTOS=true
81+
ACME_URL=https://ca.example.com/acme/acme/directory
82+
;; Can be omitted if using the system's trust is preferred
83+
;ACME_CA_ROOT=/path/to/root_ca.crt
84+
ACME_DIRECTORY=https
85+
7286
```
7387

7488
To learn more about the config values, please checkout the [Config Cheat Sheet](../config-cheat-sheet#server-server).

modules/setting/setting.go

Lines changed: 52 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,12 @@ var (
108108
UnixSocketPermission uint32
109109
EnablePprof bool
110110
PprofDataPath string
111-
EnableLetsEncrypt bool
112-
LetsEncryptTOS bool
113-
LetsEncryptDirectory string
114-
LetsEncryptEmail string
111+
EnableAcme bool
112+
AcmeTOS bool
113+
AcmeLiveDirectory string
114+
AcmeEmail string
115+
AcmeURL string
116+
AcmeCARoot string
115117
SSLMinimumVersion string
116118
SSLMaximumVersion string
117119
SSLCurvePreferences []string
@@ -622,14 +624,54 @@ func loadFromConf(allowEmpty bool, extraConfig string) {
622624
switch protocolCfg {
623625
case "https":
624626
Protocol = HTTPS
625-
CertFile = sec.Key("CERT_FILE").String()
626-
KeyFile = sec.Key("KEY_FILE").String()
627-
if !filepath.IsAbs(CertFile) && len(CertFile) > 0 {
628-
CertFile = filepath.Join(CustomPath, CertFile)
627+
// FIXME: DEPRECATED to be removed in v1.18.0
628+
if sec.HasKey("ENABLE_ACME") {
629+
EnableAcme = sec.Key("ENABLE_ACME").MustBool(false)
630+
} else {
631+
deprecatedSetting("server", "ENABLE_LETSENCRYPT", "server", "ENABLE_ACME")
632+
EnableAcme = sec.Key("ENABLE_LETSENCRYPT").MustBool(false)
629633
}
630-
if !filepath.IsAbs(KeyFile) && len(KeyFile) > 0 {
631-
KeyFile = filepath.Join(CustomPath, KeyFile)
634+
if EnableAcme {
635+
AcmeURL = sec.Key("ACME_URL").MustString("")
636+
AcmeCARoot = sec.Key("ACME_CA_ROOT").MustString("")
637+
// FIXME: DEPRECATED to be removed in v1.18.0
638+
if sec.HasKey("ACME_ACCEPTTOS") {
639+
AcmeTOS = sec.Key("ACME_ACCEPTTOS").MustBool(false)
640+
} else {
641+
deprecatedSetting("server", "LETSENCRYPT_ACCEPTTOS", "server", "ACME_ACCEPTTOS")
642+
AcmeTOS = sec.Key("LETSENCRYPT_ACCEPTTOS").MustBool(false)
643+
}
644+
if !AcmeTOS {
645+
log.Fatal("ACME TOS is not accepted (ACME_ACCEPTTOS).")
646+
}
647+
// FIXME: DEPRECATED to be removed in v1.18.0
648+
if sec.HasKey("ACME_DIRECTORY") {
649+
AcmeLiveDirectory = sec.Key("ACME_DIRECTORY").MustString("https")
650+
} else {
651+
deprecatedSetting("server", "LETSENCRYPT_DIRECTORY", "server", "ACME_DIRECTORY")
652+
AcmeLiveDirectory = sec.Key("LETSENCRYPT_DIRECTORY").MustString("https")
653+
}
654+
// FIXME: DEPRECATED to be removed in v1.18.0
655+
if sec.HasKey("ACME_EMAIL") {
656+
AcmeEmail = sec.Key("ACME_EMAIL").MustString("")
657+
} else {
658+
deprecatedSetting("server", "LETSENCRYPT_EMAIL", "server", "ACME_EMAIL")
659+
AcmeEmail = sec.Key("LETSENCRYPT_EMAIL").MustString("")
660+
}
661+
} else {
662+
CertFile = sec.Key("CERT_FILE").String()
663+
KeyFile = sec.Key("KEY_FILE").String()
664+
if len(CertFile) > 0 && !filepath.IsAbs(CertFile) {
665+
CertFile = filepath.Join(CustomPath, CertFile)
666+
}
667+
if len(KeyFile) > 0 && !filepath.IsAbs(KeyFile) {
668+
KeyFile = filepath.Join(CustomPath, KeyFile)
669+
}
632670
}
671+
SSLMinimumVersion = sec.Key("SSL_MIN_VERSION").MustString("")
672+
SSLMaximumVersion = sec.Key("SSL_MAX_VERSION").MustString("")
673+
SSLCurvePreferences = sec.Key("SSL_CURVE_PREFERENCES").Strings(",")
674+
SSLCipherSuites = sec.Key("SSL_CIPHER_SUITES").Strings(",")
633675
case "fcgi":
634676
Protocol = FCGI
635677
case "fcgi+unix", "unix", "http+unix":
@@ -653,18 +695,6 @@ func loadFromConf(allowEmpty bool, extraConfig string) {
653695
HTTPAddr = filepath.Join(AppWorkPath, HTTPAddr)
654696
}
655697
}
656-
EnableLetsEncrypt = sec.Key("ENABLE_LETSENCRYPT").MustBool(false)
657-
LetsEncryptTOS = sec.Key("LETSENCRYPT_ACCEPTTOS").MustBool(false)
658-
if !LetsEncryptTOS && EnableLetsEncrypt {
659-
log.Warn("Failed to enable Let's Encrypt due to Let's Encrypt TOS not being accepted")
660-
EnableLetsEncrypt = false
661-
}
662-
LetsEncryptDirectory = sec.Key("LETSENCRYPT_DIRECTORY").MustString("https")
663-
LetsEncryptEmail = sec.Key("LETSENCRYPT_EMAIL").MustString("")
664-
SSLMinimumVersion = sec.Key("SSL_MIN_VERSION").MustString("")
665-
SSLMaximumVersion = sec.Key("SSL_MAX_VERSION").MustString("")
666-
SSLCurvePreferences = sec.Key("SSL_CURVE_PREFERENCES").Strings(",")
667-
SSLCipherSuites = sec.Key("SSL_CIPHER_SUITES").Strings(",")
668698
GracefulRestartable = sec.Key("ALLOW_GRACEFUL_RESTARTS").MustBool(true)
669699
GracefulHammerTime = sec.Key("GRACEFUL_HAMMER_TIME").MustDuration(60 * time.Second)
670700
StartupTimeout = sec.Key("STARTUP_TIMEOUT").MustDuration(0 * time.Second)

0 commit comments

Comments
 (0)