46 lines
1.0 KiB
Go
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, ".")
|
|
}
|