1
Fork 0

use Clean() but not Abs() to prevent directory traversal

This commit is contained in:
WindLi001 2023-02-10 21:05:17 +08:00
parent dcc05f4ea8
commit 6bebed4693
1 changed files with 5 additions and 10 deletions

View File

@ -3,6 +3,7 @@ package routes
import ( import (
"net/http" "net/http"
"os" "os"
"path"
"path/filepath" "path/filepath"
) )
@ -27,20 +28,14 @@ func NewSpaHandler(staticPath string, indexPath string) SpaHandler {
// file located at the index path on the SPA handler will be served. This // file located at the index path on the SPA handler will be served. This
// is suitable behavior for serving an SPA (single page application). // is suitable behavior for serving an SPA (single page application).
func (h SpaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (h SpaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// get the absolute path to prevent directory traversal // get the clean path to prevent directory traversal
path, err := filepath.Abs(r.URL.Path) servePath := path.Clean(r.URL.Path)
if err != nil {
// if we failed to get the absolute path respond with a 400 bad request
// and stop
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// prepend the path with the path to the static directory // prepend the path with the path to the static directory
path = filepath.Join(h.staticPath, path) servePath = filepath.Join(h.staticPath, servePath)
// check whether a file exists at the given path // check whether a file exists at the given path
_, err = os.Stat(path) _, err := os.Stat(servePath)
if os.IsNotExist(err) { if os.IsNotExist(err) {
// file does not exist, serve index.html // file does not exist, serve index.html
http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath)) http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))