GHSA-QFWJ-23J7-6939
0xJacky/nginx-ui Backup Restore ZIP Symlink Handling Can Pollute Nginx Configuration Directory
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Divulgación | Publicada | GHSA-QFWJ-23J7-6939 divulgada | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
## Summary
0xJacky/nginx-ui v2.4.3 contains a candidate backup-restore symlink handling vulnerability affecting Nginx configuration restoration. The restore process permits ZIP symlink entries that point to absolute paths under the Nginx configuration or modules directories, creates those symlinks in the temporary restore tree, and later copies them into the real Nginx configuration directory when `restore_nginx=true`.
An authenticated attacker who can pass the secure-session requirement and supply a correctly formatted encrypted backup may be able to pollute the Nginx configuration directory with malicious symlinks, causing configuration integrity compromise, unexpected configuration loading, or denial of service. The vulnerable code paths are present in source; full exploitability should be confirmed with a dynamically generated backup archive matching the project's manifest/AES format.
## Details
The vulnerable path starts in `api/backup/restore.go:RestoreBackup`. The endpoint accepts a multipart backup upload, reads restore options such as `restore_nginx`, saves the uploaded `backup_file`, and calls `backup.Restore(options)`. Under the stated preconditions, the uploaded archive content is controlled by the authenticated requester.
In `internal/backup/restore.go`, `Restore` extracts the main archive and nested Nginx archive using `extractZipArchive`. `extractZipFile` checks for `..` in entry names, but it preserves ZIP entries marked as symlinks. For symlink entries, it reads the entry contents as the link target, cleans it, and permits absolute targets that are under `nginx.GetConfPath()` or `nginx.GetModulesPath()`. It then calls `os.Symlink(cleanLinkTarget, filePath)` to create the link in the temporary restore directory. This is the trust-boundary failure: attacker-controlled archive metadata is converted into filesystem symlinks pointing at real Nginx configuration or module locations.
When `restore_nginx=true`, `restoreNginxConfigs` obtains the real Nginx configuration directory, clears it with `cleanDirectoryPreservingStructure(destDir)`, and copies the extracted backup tree into it with `copyDirectory(nginxBackupDir, destDir)`. In `internal/backup/utils.go`, `copyDirectory` handles symlinks by reading the link target with `os.Readlink(path)` and recreating the same link with `os.Symlink(linkTarget, targetPath)`. There is no second validation of the target, no rejection of absolute symlinks, and no conversion to safe regular files. As a result, symlinks allowed in the temporary restore tree can be propagated into the real Nginx configuration directory.
Core vulnerable code path:
// api/backup/restore.go:31-107
func RestoreBackup(c *gin.Context) {
// Get restore options
restoreNginx := c.PostForm("restore_nginx") == "true"
restoreNginxUI := c.PostForm("restore_nginx_ui") == "true"
verifyHash := c.PostForm("verify_hash") == "true"
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
}
...
// Save backup file
backupPath := uploadedBackupPath(tempDir)
if err := c.SaveUploadedFile(backupFile, backupPath); err != nil {
cosy.ErrHandler(c, cosy.WrapErrorWithParams(backup.ErrCreateBackupFile, err.Error()))
return
}
...
// Perform restore
result, err := backup.Restore(options)The restore endpoint accepts an attacker-supplied backup archive, saves it, and passes it to the internal restore process. Authentication and secure session are required, but the archive content remains attacker-controlled.
// internal/backup/restore.go:178-230
// Check if this is a symlink by examining mode bits
if file.Mode()&os.ModeSymlink != 0 {
// Open source file in zip to read the link target
srcFile, err := file.Open()
if err != nil {
return cosy.WrapErrorWithParams(ErrOpenZipEntry, fmt.Sprintf("failed to open symlink source %s: %v", file.Name, err))
}
defer srcFile.Close()
// Read the link target
linkTargetBytes, err := io.ReadAll(srcFile)
if err != nil {
return cosy.WrapErrorWithParams(ErrReadSymlink, fmt.Sprintf("failed to read symlink target for %s: %v", file.Name, err))
}
linkTarget := string(linkTargetBytes)
...
// Check if symlink target is to an allowed path (conf path or modules path)
isAllowedSymlink := false
...
// If this is a symlink to an allowed path, create it
if isAllowedSymlink {
if err := os.Symlink(cleanLinkTarget, filePath); err != nil {
return cosy.WrapErrorWithParams(ErrCreateSymlink, fmt.Sprintf("failed to create symlink %s -> %s: %v", filePath, cleanLinkTarget, err))
}
return nil
}During ZIP extraction, symlink entries are preserved. If the symlink target is an absolute path under the Nginx configuration or modules path, the code creates the symlink in the temporary restore directory.
// internal/backup/restore.go:308-326
// restoreNginxConfigs restores nginx configuration files
func restoreNginxConfigs(nginxBackupDir string) error {
destDir := nginx.GetConfPath()
if destDir == "" {
return ErrNginxConfigDirEmpty
}
logger.Infof("Starting Nginx config restore from %s to %s", nginxBackupDir, destDir)
// Recursively clean destination directory preserving the directory structure
logger.Info("Cleaning destination directory before restore")
if err := cleanDirectoryPreservingStructure(destDir); err != nil {
logger.Errorf("Failed to clean directory %s: %v", destDir, err)
return cosy.WrapErrorWithParams(ErrCopyNginxConfigDir, "failed to clean directory: "+err.Error())
}
// Copy files from backup to nginx config directory
logger.Infof("Copying backup files to destination: %s", destDir)
if err := copyDirectory(nginxBackupDir, destDir); err != nil {
logger.Errorf("Failed to copy backup files: %v", err)
return err
}When Nginx restore is selected, the real Nginx configuration directory is cleaned and then repopulated from the extracted backup tree, amplifying the impact of malicious symlink entries.
// internal/backup/utils.go:167-190
// Walk through source directory and copy all contents
return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
...
// Construct target path
targetPath := filepath.Join(dst, relPath)
// Handle symbolic links by recreating them
if info.Mode()&os.ModeSymlink != 0 {
linkTarget, err := os.Readlink(path)
if err != nil {
return err
}
return os.Symlink(linkTarget, targetPath)
}The copy helper recreates symlinks without revalidating the link target or rejecting absolute symlinks. This can propagate attacker-supplied links into the real Nginx configuration directory.
## POC
Preconditions: the attacker has a valid authenticated account and can satisfy the restore endpoint's `RequireSecureSession()` requirement, for example with the current password or an established 2FA secure session; the attacker can construct a backup archive matching the project's backup format and provide the corresponding AES key/IV in `security_token`; and the target permits restoring Nginx configuration.
Reproduction steps:
1. Locally generate a malicious backup archive. The outer backup must satisfy nginx-ui's restore format. The internal `nginx.zip` contains a symlink ZIP entry such as `sites-enabled/poc.conf`, with a link target that is an absolute path under the deployment's Nginx configuration directory, for example a `sites-available` target. Encrypt the internal ZIP according to the project backup format using an attacker-chosen AES key/IV and prepare the matching `security_token`.
2. Send an authenticated `POST /api/restore` request with `multipart/form-data`. The form fields include `restore_nginx=true`, `restore_nginx_ui=false`, `verify_hash` as appropriate for the test, `security_token=<base64-key>:<base64-iv>`, and `backup_file=<evil-backup.zip>`. Expected result: the API enters the Nginx restore path and either returns `nginx_restored: true` or proceeds to the asynchronous Nginx restart.
3. Confirm the restored state by requesting `GET /api/configs?dir=sites-enabled`, checking the server filesystem, or observing Nginx behavior. Expected result: the real Nginx configuration directory contains the attacker-provided symlink such as `sites-enabled/poc.conf`; Nginx reload/restart is influenced by that linked configuration and may load unexpected configuration or fail to start/reload.
The exact archive layout and encryption details must be aligned with the target version's backup manifest/AES format during dynamic verification.
## Impact
A malicious backup can corrupt the Nginx configuration directory structure by planting symlinks that point to arbitrary locations under the Nginx configuration or modules paths. This can cause persistent unexpected configuration references, Nginx reload or restart failures, and denial of service. In deployments where the attacker can combine this with another capability to write the symlink target file, Nginx may load attacker-controlled configuration content.
## Remediation
Reject symlink entries by default during backup restoration, or only allow relative symlinks whose final `EvalSymlinks` target remains inside the temporary restore directory. Before copying restored content into the real Nginx configuration directory, perform a second validation pass over every symlink target, reject absolute symlinks, and reject links to unexpected locations. Where possible, copy the target file contents as regular files instead of recreating symlinks. Complete manifest validation, format validation, and a security scan of the restore tree should occur before clearing the real configuration directory. Add regression tests for ZIP symlink entries, absolute links, relative traversal links, links into conf/modules paths, nested ZIP extraction, and the copy-stage revalidation.
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
gogithub.com/0xJacky/Nginx-UI |
Sin parche | — | — | v1.9.9 no afectada |
2.5.0Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/0xJacky/nginx-ui/security/advisories/GHSA-qfwj-23j7-6939Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
