Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions servefiles/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"html/template"
"log"
"net/http"
"net/url"
"os"
"path/filepath"

Expand Down Expand Up @@ -62,6 +63,12 @@ func httpRequestHandler(w http.ResponseWriter, req *http.Request) {
func fileHandler(w http.ResponseWriter, req *http.Request) {
// Strip the "/files" prefix from the request URL
path := "." + req.URL.Path[len("/files"):]
// Decode percent-encoded characters
path, err := url.PathUnescape(path)
if err != nil {
http.Error(w, "Invalid URL", http.StatusBadRequest)
return
}
Comment on lines +66 to +71
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add path sanitization to prevent directory traversal.

While the URL decoding is implemented correctly, the decoded path needs to be sanitized before use to prevent potential directory traversal attacks.

Apply this diff to add path sanitization:

 	// Decode percent-encoded characters
 	path, err := url.PathUnescape(path)
 	if err != nil {
-		http.Error(w, "Invalid URL", http.StatusBadRequest)
+		http.Error(w, "Invalid URL encoding", http.StatusBadRequest)
 		return
 	}
+	// Clean the path to prevent directory traversal
+	path = filepath.Clean(path)
+	if strings.HasPrefix(path, "..") {
+		http.Error(w, "Invalid path", http.StatusBadRequest)
+		return
+	}

Don't forget to add the required import:

+	"strings"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Decode percent-encoded characters
path, err := url.PathUnescape(path)
if err != nil {
http.Error(w, "Invalid URL", http.StatusBadRequest)
return
}
// Decode percent-encoded characters
path, err := url.PathUnescape(path)
if err != nil {
http.Error(w, "Invalid URL encoding", http.StatusBadRequest)
return
}
// Clean the path to prevent directory traversal
path = filepath.Clean(path)
if strings.HasPrefix(path, "..") {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}


// Check if the path is a directory or a file
fileInfo, err := os.Stat(path)
Expand Down