Skip to content

Commit 2d4bbec

Browse files
fix lack of escaping of filename in Content-Disposition (#3556)
* fix lack of escaping of filename in Content-Disposition * add test for Content-Disposition filename escaping process * fix filename escape bypass problem fix backslashes before backquotes were not properly escaped problem.
1 parent 9f5ecd4 commit 2d4bbec

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

context.go

+7-1
Original file line numberDiff line numberDiff line change
@@ -1052,11 +1052,17 @@ func (c *Context) FileFromFS(filepath string, fs http.FileSystem) {
10521052
http.FileServer(fs).ServeHTTP(c.Writer, c.Request)
10531053
}
10541054

1055+
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
1056+
1057+
func escapeQuotes(s string) string {
1058+
return quoteEscaper.Replace(s)
1059+
}
1060+
10551061
// FileAttachment writes the specified file into the body stream in an efficient way
10561062
// On the client side, the file will typically be downloaded with the given filename
10571063
func (c *Context) FileAttachment(filepath, filename string) {
10581064
if isASCII(filename) {
1059-
c.Writer.Header().Set("Content-Disposition", `attachment; filename="`+filename+`"`)
1065+
c.Writer.Header().Set("Content-Disposition", `attachment; filename="`+escapeQuotes(filename)+`"`)
10601066
} else {
10611067
c.Writer.Header().Set("Content-Disposition", `attachment; filename*=UTF-8''`+url.QueryEscape(filename))
10621068
}

context_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -1032,6 +1032,20 @@ func TestContextRenderAttachment(t *testing.T) {
10321032
assert.Equal(t, fmt.Sprintf("attachment; filename=\"%s\"", newFilename), w.Header().Get("Content-Disposition"))
10331033
}
10341034

1035+
func TestContextRenderAndEscapeAttachment(t *testing.T) {
1036+
w := httptest.NewRecorder()
1037+
c, _ := CreateTestContext(w)
1038+
maliciousFilename := "tampering_field.sh\"; \\\"; dummy=.go"
1039+
actualEscapedResponseFilename := "tampering_field.sh\\\"; \\\\\\\"; dummy=.go"
1040+
1041+
c.Request, _ = http.NewRequest("GET", "/", nil)
1042+
c.FileAttachment("./gin.go", maliciousFilename)
1043+
1044+
assert.Equal(t, 200, w.Code)
1045+
assert.Contains(t, w.Body.String(), "func New() *Engine {")
1046+
assert.Equal(t, fmt.Sprintf("attachment; filename=\"%s\"", actualEscapedResponseFilename), w.Header().Get("Content-Disposition"))
1047+
}
1048+
10351049
func TestContextRenderUTF8Attachment(t *testing.T) {
10361050
w := httptest.NewRecorder()
10371051
c, _ := CreateTestContext(w)

0 commit comments

Comments
 (0)