gpt4 book ai didi

file - 检查文件是否位于基本目录中的最安全方法是什么?

转载 作者:行者123 更新时间:2023-12-01 22:07:14 25 4
gpt4 key购买 nike

在任何平台上验证给定文件路径位于基本路径中的最安全,最安全的方法是什么?

路径最初是作为字符串提供的,并使用“/”作为分隔符,但是它们是用户提供的,因此我需要承担大量的恶意输入。我应该执行哪种路径规范化以确保例如会评估“..”之类的序列,因此我可以安全地检查基本路径吗?在各种文件系统和平台上需要注意哪些异常(exception)?在这方面哪个Go库应该是安全的?

结果将被馈送到os.Createsqlite3.Open等外部函数,并且任何无法识别出保留基本路径的行为都会违反安全性。

最佳答案

我相信您可以为此使用filepath.Rel(并检查它是否返回不以..开头的值)。

Rel returns a relative path that is lexically equivalent to targpath when joined to basepath with an intervening separator. That is, Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself. On success, the returned path will always be relative to basepath, even if basepath and targpath share no elements. An error is returned if targpath can't be made relative to basepath or if knowing the current working directory would be necessary to compute it. Rel calls Clean on the result.


filepath.Rel还在其输入路径上调用 filepath.Clean,从而解析了 ...

Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:

  1. Replace multiple Separator elements with a single one.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path, assuming Separator is '/'.


您也可以直接使用 filepath.Clean并在完成后检查前缀。以下是 filepath.Clean的一些示例输出:
ps := []string{
"/a/../b",
"/a/b/./c/../../d",
"/b",
}
for _, p := range ps {
fmt.Println(p, filepath.Clean(p))
}

打印:
/a/../b /b
/a/b/./c/../../d /a/d
/b /b

就是说, 路径操作不应成为部署的唯一安全机制。如果您真的担心漏洞利用,请通过沙盒,创建虚拟文件系统/容器等来深入利用防御。

关于file - 检查文件是否位于基本目录中的最安全方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60829712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com