Skip to content

Commit 6bd9385

Browse files
committed
static: clean the path URL before redirecting.
This prevents a malicious redirect with a crafted URL.
1 parent 002c0ce commit 6bd9385

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

static.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ func staticHandler(ctx *Context, log *log.Logger, opt StaticOptions) bool {
123123
return false
124124
}
125125

126-
file := ctx.Req.URL.Path
126+
file := path.Clean(ctx.Req.URL.Path)
127127
// if we have a prefix, filter requests by stripping the prefix
128128
if opt.Prefix != "" {
129129
if !strings.HasPrefix(file, opt.Prefix) {
@@ -149,8 +149,9 @@ func staticHandler(ctx *Context, log *log.Logger, opt StaticOptions) bool {
149149
// Try to serve index file
150150
if fi.IsDir() {
151151
// Redirect if missing trailing slash.
152-
if !strings.HasSuffix(ctx.Req.URL.Path, "/") {
153-
http.Redirect(ctx.Resp, ctx.Req.Request, ctx.Req.URL.Path+"/", http.StatusFound)
152+
redirPath := path.Clean(ctx.Req.URL.Path)
153+
if !strings.HasSuffix(redirPath, "/") {
154+
http.Redirect(ctx.Resp, ctx.Req.Request, redirPath+"/", http.StatusFound)
154155
return true
155156
}
156157

static_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,18 @@ func Test_Static_Redirect(t *testing.T) {
218218
So(resp.Code, ShouldEqual, http.StatusFound)
219219
So(resp.Header().Get("Location"), ShouldEqual, "/public/")
220220
})
221+
222+
Convey("Serve static files with improper request", t, func() {
223+
m := New()
224+
m.Use(Static(currentRoot))
225+
226+
resp := httptest.NewRecorder()
227+
req, err := http.NewRequest("GET", `http://localhost:4000//example.com%2f..`, nil)
228+
So(err, ShouldBeNil)
229+
m.ServeHTTP(resp, req)
230+
231+
So(resp.Code, ShouldEqual, http.StatusNotFound)
232+
})
221233
}
222234

223235
func Test_Statics(t *testing.T) {

0 commit comments

Comments
 (0)