2
0
mirror of synced 2025-02-24 14:48:27 +00:00
torrent/storage/safe-path.go
Matt Joiner 89235e180f Sanitize metainfo file paths for file-based storage
Fixes exploit where specially crafted infos can cause the client to write files to arbitrary locations on local storage when using file-based storages like mmap and file.
2020-10-15 15:45:08 +11:00

32 lines
900 B
Go

package storage
import (
"errors"
"log"
"path/filepath"
"strings"
)
// Get the first file path component. We can't use filepath.Split because that breaks off the last
// one. We could optimize this to avoid allocating a slice down the track.
func firstComponent(filePath string) string {
return strings.SplitN(filePath, string(filepath.Separator), 2)[0]
}
// Combines file info path components, ensuring the result won't escape into parent directories.
func ToSafeFilePath(fileInfoComponents ...string) (string, error) {
safeComps := make([]string, 0, len(fileInfoComponents))
for _, comp := range fileInfoComponents {
safeComps = append(safeComps, filepath.Clean(comp))
}
safeFilePath := filepath.Join(safeComps...)
fc := firstComponent(safeFilePath)
log.Printf("%q", fc)
switch fc {
case "..":
return "", errors.New("escapes root dir")
default:
return safeFilePath, nil
}
}