ソースを参照

修复路径检查逻辑并添加子路径验证功能

在 `dir.go` 中新增了对文件路径是否为指定目录子路径的检查,以增强安全性。同时,更正了 `path.go` 中的函数名拼写错误,并增加了新的路径处理函数来支持子路径判断。
SongZihuan 3 ヶ月 前
コミット
95797d3645
3 ファイル変更37 行追加4 行削除
  1. 1 1
      src/config/config.go
  2. 5 0
      src/server/dir.go
  3. 31 3
      src/utils/path.go

+ 1 - 1
src/config/config.go

@@ -35,7 +35,7 @@ func newConfig(configPath string) (*ConfigStruct, error) {
 		configPath = flagparser.ConfigFile()
 	}
 
-	configPath, err := utils.ClearFilePathAbs(configPath)
+	configPath, err := utils.CleanFilePathAbs(configPath)
 	if err != nil {
 		return nil, err
 	}

+ 5 - 0
src/server/dir.go

@@ -67,6 +67,11 @@ func (s *HTTPServer) dirServer(rule *rulescompile.RuleCompileConfig, w http.Resp
 		}
 	}
 
+	if !utils.CheckIfSubPath(dirBasePath, filePath) {
+		s.abortForbidden(w)
+		return
+	}
+
 	file, err := os.ReadFile(filePath)
 	if err != nil {
 		s.abortNotFound(w)

+ 31 - 3
src/utils/path.go

@@ -6,7 +6,7 @@ import (
 	"strings"
 )
 
-func ClearFilePathAbs(pathstr string) (string, error) {
+func CleanFilePathAbs(pathstr string) (string, error) {
 	pathstr, err := filepath.Abs(filepath.Clean(pathstr))
 	if err != nil {
 		return "", err
@@ -23,15 +23,43 @@ func ClearFilePathAbs(pathstr string) (string, error) {
 }
 
 func FilePathEqual(path1, path2 string) bool {
-	path1, err := ClearFilePathAbs(path1)
+	path1, err := CleanFilePathAbs(path1)
 	if err != nil {
 		return false
 	}
 
-	path2, err = ClearFilePathAbs(path2)
+	path2, err = CleanFilePathAbs(path2)
 	if err != nil {
 		return false
 	}
 
 	return path1 == path2
 }
+
+func CheckIfSubPath(parentPath, childPath string) bool {
+	parentPath, err := CleanFilePathAbs(parentPath)
+	if err != nil {
+		return false
+	}
+
+	childPath, err = CleanFilePathAbs(childPath)
+	if err != nil {
+		return false
+	}
+
+	return strings.HasPrefix(childPath, parentPath)
+}
+
+func CheckIfSubPathNotEqaule(parentPath, childPath string) bool {
+	parentPath, err := CleanFilePathAbs(parentPath)
+	if err != nil {
+		return false
+	}
+
+	childPath, err = CleanFilePathAbs(childPath)
+	if err != nil {
+		return false
+	}
+
+	return strings.HasPrefix(childPath, parentPath) && childPath != parentPath
+}