Skip to content
2 changes: 1 addition & 1 deletion cmd/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ func setPort(port string) error {
defaultLocalURL += ":" + setting.HTTPPort + "/"

// Save LOCAL_ROOT_URL if port changed
setting.CreateOrAppendToCustomConf(func(cfg *ini.File) {
setting.CreateOrAppendToCustomConf("server.LOCAL_ROOT_URL", func(cfg *ini.File) {
cfg.Section("server").Key("LOCAL_ROOT_URL").SetValue(defaultLocalURL)
})
}
Expand Down
11 changes: 8 additions & 3 deletions custom/conf/app.example.ini
Original file line number Diff line number Diff line change
Expand Up @@ -379,14 +379,19 @@ LOG_SQL = false ; if unset defaults to true
;; Whether the installer is disabled (set to true to disable the installer)
INSTALL_LOCK = false
;;
;; Global secret key that will be used - if blank will be regenerated.
;; Global secret key that will be used
;; This key is VERY IMPORTANT. If you lose it, the data encrypted by it (like 2FA secret) can't be decrypted anymore.
SECRET_KEY =
;;
;; Alternative location to specify secret key, instead of this file; you cannot specify both this and SECRET_KEY, and must pick one
;; This key is VERY IMPORTANT. If you lose it, the data encrypted by it (like 2FA secret) can't be decrypted anymore.
;SECRET_KEY_URI = file:/etc/gitea/secret_key
;;
;; Secret used to validate communication within Gitea binary.
INTERNAL_TOKEN=
;;
;; Instead of defining internal token in the configuration, this configuration option can be used to give Gitea a path to a file that contains the internal token (example value: file:/etc/gitea/internal_token)
;INTERNAL_TOKEN_URI = ;e.g. /etc/gitea/internal_token
;; Alternative location to specify internal token, instead of this file; you cannot specify both this and INTERNAL_TOKEN, and must pick one
;INTERNAL_TOKEN_URI = file:/etc/gitea/internal_token
;;
;; How long to remember that a user is logged in before requiring relogin (in days)
;LOGIN_REMEMBER_DAYS = 7
Expand Down
5 changes: 3 additions & 2 deletions docs/content/doc/advanced/config-cheat-sheet.en-us.md
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,8 @@ Certain queues have defaults that override the defaults set in `[queue]` (this o
## Security (`security`)

- `INSTALL_LOCK`: **false**: Controls access to the installation page. When set to "true", the installation page is not accessible.
- `SECRET_KEY`: **\<random at every install\>**: Global secret key. This should be changed.
- `SECRET_KEY`: **\<random at every install\>**: Global secret key. This key is VERY IMPORTANT, if you lost it, the data encrypted by it (like 2FA secret) can't be decrypted anymore.
- `SECRET_KEY_URI`: **<empty>**: Instead of defining SECRET_KEY, this option can be used to use the key stored in a file (example value: `file:/etc/gitea/secret_token`). It shouldn't be lost like SECRET_KEY.
- `LOGIN_REMEMBER_DAYS`: **7**: Cookie lifetime, in days.
- `COOKIE_USERNAME`: **gitea\_awesome**: Name of the cookie used to store the current username.
- `COOKIE_REMEMBER_NAME`: **gitea\_incredible**: Name of cookie used to store authentication
Expand All @@ -520,7 +521,7 @@ Certain queues have defaults that override the defaults set in `[queue]` (this o
- `ONLY_ALLOW_PUSH_IF_GITEA_ENVIRONMENT_SET`: **true**: Set to `false` to allow local users to push to gitea-repositories without setting up the Gitea environment. This is not recommended and if you want local users to push to Gitea repositories you should set the environment appropriately.
- `IMPORT_LOCAL_PATHS`: **false**: Set to `false` to prevent all users (including admin) from importing local path on server.
- `INTERNAL_TOKEN`: **\<random at every install if no uri set\>**: Secret used to validate communication within Gitea binary.
- `INTERNAL_TOKEN_URI`: **<empty>**: Instead of defining internal token in the configuration, this configuration option can be used to give Gitea a path to a file that contains the internal token (example value: `file:/etc/gitea/internal_token`)
- `INTERNAL_TOKEN_URI`: **<empty>**: Instead of defining INTERNAL_TOKEN in the configuration, this configuration option can be used to give Gitea a path to a file that contains the internal token (example value: `file:/etc/gitea/internal_token`)
- `PASSWORD_HASH_ALGO`: **pbkdf2**: The hash algorithm to use \[argon2, pbkdf2, scrypt, bcrypt\], argon2 will spend more memory than others.
- `CSRF_COOKIE_HTTP_ONLY`: **true**: Set false to allow JavaScript to read CSRF cookie.
- `MIN_PASSWORD_LENGTH`: **6**: Minimum password length for new users.
Expand Down
2 changes: 1 addition & 1 deletion modules/setting/lfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func newLFSService() {
}

// Save secret
CreateOrAppendToCustomConf(func(cfg *ini.File) {
CreateOrAppendToCustomConf("server.LFS_JWT_SECRET", func(cfg *ini.File) {
cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(LFS.JWTSecretBase64)
})
}
Expand Down
94 changes: 62 additions & 32 deletions modules/setting/setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -923,9 +923,15 @@ func loadFromConf(allowEmpty bool, extraConfig string) {

sec = Cfg.Section("security")
InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
SecretKey = loadOrGenerateSecret(sec, "SECRET_KEY_URI", "SECRET_KEY", nil)
if SecretKey == "" {
// FIXME: https://github.com/go-gitea/gitea/issues/16832
// Until it supports rotating an existing secret key, we shouldn't move users off of the widely used default value
SecretKey = "!#@FDEWREWR&*(" // nolint:gosec
}

CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")

ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
Expand All @@ -948,11 +954,7 @@ func loadFromConf(allowEmpty bool, extraConfig string) {
PasswordCheckPwn = sec.Key("PASSWORD_CHECK_PWN").MustBool(false)
SuccessfulTokensCacheSize = sec.Key("SUCCESSFUL_TOKENS_CACHE_SIZE").MustInt(20)

InternalToken = loadInternalToken(sec)
if InstallLock && InternalToken == "" {
// if Gitea has been installed but the InternalToken hasn't been generated (upgrade from an old release), we should generate
generateSaveInternalToken()
}
InternalToken = loadOrGenerateSecret(sec, "INTERNAL_TOKEN_URI", "INTERNAL_TOKEN", generate.NewInternalToken)

cfgdata := sec.Key("PASSWORD_COMPLEXITY").Strings(",")
if len(cfgdata) == 0 {
Expand Down Expand Up @@ -1141,51 +1143,75 @@ func parseAuthorizedPrincipalsAllow(values []string) ([]string, bool) {
return authorizedPrincipalsAllow, true
}

func loadInternalToken(sec *ini.Section) string {
uri := sec.Key("INTERNAL_TOKEN_URI").String()
// loadOrGenerateSecret loads the secret if it exists in the config file,
// or generates a new one and saves it into the config file
func loadOrGenerateSecret(
sec *ini.Section,
uriKey string,
verbatimKey string,
generator func() (string, error),
) string {
// don't allow setting both URI and verbatim string
uri := sec.Key(uriKey).String()
verbatim := sec.Key(verbatimKey).String()
if uri != "" && verbatim != "" {
log.Fatal("Cannot specify both %s and %s", uriKey, verbatimKey)
}

// if we have no URI, use verbatim
if uri == "" {
return sec.Key("INTERNAL_TOKEN").String()
// if verbatim isn't provided, generate one
if verbatim == "" && generator != nil {
secret, err := generator()
if err != nil {
log.Fatal("Error trying to generate %s: %v", verbatimKey, err)
}
CreateOrAppendToCustomConf(sec.Name()+"."+verbatimKey, func(cfg *ini.File) {
cfg.Section(sec.Name()).Key(verbatimKey).SetValue(secret)
})
return secret
}

return verbatim
}

tempURI, err := url.Parse(uri)
if err != nil {
log.Fatal("Failed to parse INTERNAL_TOKEN_URI (%s): %v", uri, err)
log.Fatal("Failed to parse %s (%s): %v", uriKey, uri, err)
}
switch tempURI.Scheme {
case "file":
buf, err := os.ReadFile(tempURI.RequestURI())
if err != nil && !os.IsNotExist(err) {
log.Fatal("Failed to open InternalTokenURI (%s): %v", uri, err)
log.Fatal("Failed to open %s (%s): %v", uriKey, uri, err)
}
// No token in the file, generate one and store it.
if len(buf) == 0 {
token, err := generate.NewInternalToken()

// empty file; generate secret and store it
if len(buf) == 0 && generator != nil {
token, err := generator()
if err != nil {
log.Fatal("Error generate internal token: %v", err)
log.Fatal("Error generating %s: %v", verbatimKey, err)
}

err = os.WriteFile(tempURI.RequestURI(), []byte(token), 0o600)
if err != nil {
log.Fatal("Error writing to InternalTokenURI (%s): %v", uri, err)
log.Fatal("Error writing to %s (%s): %v", uriKey, uri, err)
}

// we assume generator gives pre-parsed token
return token
}

return strings.TrimSpace(string(buf))

// only file URIs are allowed
default:
log.Fatal("Unsupported URI-Scheme %q (INTERNAL_TOKEN_URI = %q)", tempURI.Scheme, uri)
}
return ""
}

// generateSaveInternalToken generates and saves the internal token to app.ini
func generateSaveInternalToken() {
token, err := generate.NewInternalToken()
if err != nil {
log.Fatal("Error generate internal token: %v", err)
}

InternalToken = token
CreateOrAppendToCustomConf(func(cfg *ini.File) {
cfg.Section("security").Key("INTERNAL_TOKEN").SetValue(token)
})
// we should never get here
log.Fatal("Unknown error when loading %s", verbatimKey)
return ""
}

// MakeAbsoluteAssetURL returns the absolute asset url prefix without a trailing slash
Expand Down Expand Up @@ -1249,7 +1275,12 @@ func MakeManifestData(appName, appURL, absoluteAssetURL string) []byte {

// CreateOrAppendToCustomConf creates or updates the custom config.
// Use the callback to set individual values.
func CreateOrAppendToCustomConf(callback func(cfg *ini.File)) {
func CreateOrAppendToCustomConf(purpose string, callback func(cfg *ini.File)) {
if CustomConf == "" {
log.Error("Custom config path must not be empty")
return
}

cfg := ini.Empty()
isFile, err := util.IsFile(CustomConf)
if err != nil {
Expand All @@ -1264,15 +1295,14 @@ func CreateOrAppendToCustomConf(callback func(cfg *ini.File)) {

callback(cfg)

log.Info("Settings saved to: %q", CustomConf)

if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
log.Fatal("failed to create '%s': %v", CustomConf, err)
return
}
if err := cfg.SaveTo(CustomConf); err != nil {
log.Fatal("error saving to custom config: %v", err)
}
log.Info("Settings for %s saved to: %q", purpose, CustomConf)

// Change permissions to be more restrictive
fi, err := os.Stat(CustomConf)
Expand Down
2 changes: 1 addition & 1 deletion services/auth/source/oauth2/jwtsigningkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ func loadOrCreateSymmetricKey() (interface{}, error) {
return nil, err
}

setting.CreateOrAppendToCustomConf(func(cfg *ini.File) {
setting.CreateOrAppendToCustomConf("oauth2.JWT_SECRET", func(cfg *ini.File) {
secretBase64 := base64.RawURLEncoding.EncodeToString(key)
cfg.Section("oauth2").Key("JWT_SECRET").SetValue(secretBase64)
})
Expand Down