Description
Open download, upload, and extraction paths under a fixed root. A path inside that root after normalization can still lead outside it through a symlink.
Potential impact
Reads can expose configuration or credentials available to the process. Writes may corrupt files or change content that will later execute.
Remediation
- Accept a single component when only a filename is needed. For relative paths, use
filepath.Relto reject results outside the root. - On Go 1.24 or later, open files through a root obtained with
os.OpenRoot. A path can change between afilepath.CleanorEvalSymlinkscheck and a separate open. - Enforce per-file access and any extension, size, or depth limits. Stop when a check fails.
Examples
This example requires administrators to control /var/app/data and its descendants, with no links leading outside. The service must also authenticate callers, authorize files, and decide whether to allow directory listings.
Before
go
package main
import (
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
)
func download(c *gin.Context) {
// Before: use user input directly as a path
// Example: ?file=../../etc/passwd
file := c.Query("file")
baseDir := "/var/app/data"
// Join cleans the path but can still produce a parent escape
fullPath := filepath.Join(baseDir, file)
if _, err := os.Stat(fullPath); err != nil {
c.String(http.StatusNotFound, "not found")
return
}
http.ServeFile(c.Writer, c.Request, fullPath)
}
func main() {
r := gin.Default()
r.GET("/download", download)
r.Run()
}
After
go
package main
import (
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/gin-gonic/gin"
)
func isUnderBase(base, target string) bool {
// Normalize paths and include the separator when comparing the base
b := filepath.Clean(base)
t := filepath.Clean(target)
sep := string(os.PathSeparator)
if runtime.GOOS == "windows" {
b = strings.ToLower(b)
t = strings.ToLower(t)
}
return strings.HasPrefix(t+sep, b+sep)
}
func safeDownload(c *gin.Context) {
file := c.Query("file")
baseDir := "/var/app/data" // Fixed root directory
// 1) Require the joined path to remain lexically inside baseDir
target := filepath.Join(baseDir, file)
if !isUnderBase(baseDir, target) {
c.String(http.StatusBadRequest, "invalid path")
return
}
// 2) Optional extension allow-list
// if !strings.HasSuffix(strings.ToLower(target), ".txt") { ... }
// 3) Serve the file
if _, err := os.Stat(target); err != nil {
c.String(http.StatusNotFound, "not found")
return
}
http.ServeFile(c.Writer, c.Request, target)
}
func main() {
r := gin.Default()
r.GET("/download", safeDownload)
r.Run()
}
isUnderBase compares path strings including the separator. The target supplied to ServeFile comes from a query value, so checking the request URL path alone cannot establish its location.