Go是否清理Web请求的URL?

Uld*_*isK 5 go web

我在Go中实现了一个简单的Web服务器.由于我没有网络开发的经验,这对我来说是一个严肃的问题.

假设我loadPage这里提供具有修改功能的网页

func loadPage(title string) []byte {
    filename := title 
    body, _ := ioutil.ReadFile(filename)
    return body
}

func handler(w http.ResponseWriter, req *http.Request) {
    content := loadPage(req.URL.Path[1:])
    fmt.Fprintf(w, "%s", content)
}
Run Code Online (Sandbox Code Playgroud)

从技术上讲,这允许我以一种形式写一个请求

 http://example.com/../../etc/passwd
Run Code Online (Sandbox Code Playgroud)

并且代码很乐意提供/ etc/passwd文件,但事实并非如此.这是否意味着../在Go http包或http协议本身中存在某种形式的保护,或者我只是做错了什么并且它是一个安全漏洞?

Ash*_*she 8

net/http在HTTP请求多路复用器中执行此操作ServeMux:

ServeMux还负责清理URL请求路径,重定向包含的任何请求.或..元素到等效的.-和..-免费URL.

相关函数是私有函数cleanPath(p string) string,它调用path.Clean:

1415        np := path.Clean(p)
Run Code Online (Sandbox Code Playgroud)

path.Clean 做适当的删除:

 97         case path[r] == '.' && path[r+1] == '.' && (r+2 == n || path[r+2] == '/'):
 98             // .. element: remove to last /
 99             r += 2
100             switch {
101             case out.w > dotdot:
102                 // can backtrack
103                 out.w--
104                 for out.w > dotdot && out.index(out.w) != '/' {
105                     out.w--
106                 }
Run Code Online (Sandbox Code Playgroud)

如果路径没有生根,还有一个额外的情况,但是cleanPath上面确保它是这样的,如果没有已经存在的话,通过在要清理的路径前加上正斜杠.