liuhaijun e94826ce29 add server
Change-Id: I0760f17f6a01c0121b59fcbfafc666032dbc30af
2024-09-19 09:44:15 +00:00

46 lines
1.0 KiB
Go

package file_utils
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// CheckFilePathSlip 用于检查文件路径是否包含滑动漏洞
func CheckFilePathSlip(filePath string) error {
//借助临时目录检测
tempDir := os.TempDir()
joined := filepath.Join(tempDir, filePath)
// 检查路径,你可以根据自己需求进行相应的操作
return CheckSlip(tempDir, joined)
}
// CheckSlip 用于检查文件路径是否包含滑动漏洞
func CheckSlip(parentFilePath string, filePath string) error {
absParentPath, err := filepath.Abs(parentFilePath)
if err != nil {
return err
}
absFilePath, err := filepath.Abs(filePath)
if err != nil {
return err
}
if !IsSub(absParentPath, absFilePath) {
return fmt.Errorf("New file is outside of the parent dir: %s", absFilePath)
}
return nil
}
// 判断路径是否是目录的子目录
func IsSub(parentDir string, file string) bool {
rel, err := filepath.Rel(parentDir, file)
if err != nil {
return false
}
return !strings.HasPrefix(rel, "..") && !strings.HasPrefix(rel, ".")
}