Repository: gin-gonic/gin
Pull request #3500 (2023-02-14 17:52:37)

Add escape logic for header
# Add escape logic for header  

Hi, Team.
I added a `escape logic` to the header reflecting user input values for the following.
I'd appreciate it if you could review it.

## Description

Basically `X-Forwarded-Prefix` is not required for any purpose other than the `/` delimiter. However, unintended execution by crafted request.

`X-Forwarded-Prefix` has a potential problems. Although actively exploiting this flaw is unlikely, Need to prevents abuse in scenarios such as [cache poisoning](https://portswigger.net/web-security/web-cache-poisoning).


## How to reproduce

```go
package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {

	r := gin.Default()

	r.GET("/bug", func(c *gin.Context) {
		c.JSON(http.StatusBadRequest, gin.H{"msg": "bug"})
	})

	r.Run()
}

```

## Case 1. Modulate 

### Expectations

```bash
$ curl -L --path-as-is -i "http://192.168.1.19:8080/bug/" -H "x-forwarded-prefix: ../../bug#?"

HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=utf-8
Location: ../../../bug%2523%253F/bug
Date: Tue, 14 Feb 2023 17:17:42 GMT
Content-Length: 61

HTTP/1.1 404 Not Found
Content-Type: text/plain
Date: Tue, 14 Feb 2023 17:17:42 GMT
Content-Length: 18

404 page not found
```

## Actual result


```bash
$ curl -L --path-as-is -i "http://192.168.1.19:8080/bug/" -H "x-forwarded-prefix: ../../bug#?"

HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=utf-8
Location: ../../bug#?//../../bug%23%3F//bug
Date: Tue, 14 Feb 2023 17:10:43 GMT
Content-Length: 68

HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Date: Tue, 14 Feb 2023 17:10:43 GMT
Content-Length: 13

{"msg":"bug"}
```

## Case 2. Redirect

### Expectations

```bash
$ curl -L --path-as-is -i "http://192.168.1.19:8080/bug/" -H "x-forwarded-prefix: https://gin-gonic.com/#"

HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=utf-8
Location: https%3A/gin-gonic.com/%23/https%253A/gin-gonic.com/%2523/bug
Date: Tue, 14 Feb 2023 17:16:27 GMT
Content-Length: 96

HTTP/1.1 404 Not Found
Content-Type: text/plain
Date: Tue, 14 Feb 2023 17:16:27 GMT
Content-Length: 18

404 page not found
```

## Actual result

```bash
$ curl -L --path-as-is -i "http://192.168.1.19:8080/bug/" -H "x-forwarded-prefix: https://gin-gonic.com/#"

HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=utf-8
Location: https:/gin-gonic.com/#/https:/gin-gonic.com/%23/bug
Date: Tue, 14 Feb 2023 17:13:50 GMT
Content-Length: 86

HTTP/2 200 
server: GitHub.com
content-type: text/html; charset=utf-8
last-modified: Fri, 29 Apr 2022 07:17:57 GMT
access-control-allow-origin: *
etag: "626b9125-6605"
expires: Tue, 14 Feb 2023 17:23:50 GMT
cache-control: max-age=600
x-proxy-cache: MISS
x-github-request-id: 77D4:63EE:1951BF:1A6FCE:63EBC14E
accept-ranges: bytes
date: Tue, 14 Feb 2023 17:13:50 GMT
via: 1.1 varnish
age: 0
x-served-by: cache-tyo11949-TYO
x-cache: MISS
x-cache-hits: 0
x-timer: S1676394830.054868,VS0,VE181
vary: Accept-Encoding
x-fastly-request-id: a7775619919d2344b41c5b64e35a19b5f1db36c0
content-length: 26117

# ... skip ...
```

## Case 3. Infinite Loop

### Expectations

```bash
$ curl -L --path-as-is -i "http://192.168.1.19:8080/bug/" -H "x-forwarded-prefix: #bug"

HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=utf-8
Location: %23bug/%2523bug/bug
Date: Tue, 14 Feb 2023 17:19:00 GMT
Content-Length: 54

HTTP/1.1 404 Not Found
Content-Type: text/plain
Date: Tue, 14 Feb 2023 17:19:00 GMT
Content-Length: 18

404 page not found
```

## Actual result


```bash
$ curl -L --path-as-is -i "http://192.168.1.19:8080/bug/" -H "x-forwarded-prefix: #bug"

HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=utf-8
Location: #bug/%23bug/bug
Date: Tue, 14 Feb 2023 17:20:09 GMT
Content-Length: 50

# ... Loop ...

HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=utf-8
Location: #bug/%23bug/bug
Date: Tue, 14 Feb 2023 17:20:19 GMT
Content-Length: 50

curl: (47) Maximum (50) redirects followed
```

## Environment

- go version: go version go1.19 windows/amd64
- gin version (or commit ref): latest
- operating system: windows

## Reference

- https://github.com/advisories/GHSA-6qq8-5wq3-86rp
- https://github.com/advisories/GHSA-6vm3-jj99-7229
- https://cwe.mitre.org/data/definitions/20.html
- https://cwe.mitre.org/data/definitions/601.html
- https://cwe.mitre.org/data/definitions/835.html
- https://github.com/gin-gonic/gin/pull/2237



codecov[bot]: # [Codecov](https://codecov.io/gh/gin-gonic/gin/pull/3500?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gin-gonic) Report
> Merging [#3500](https://codecov.io/gh/gin-gonic/gin/pull/3500?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gin-gonic) (ec759ae) into [master](https://codecov.io/gh/gin-gonic/gin/commit/c1d06e3d08692f9eddde381a5e277b41fff5a297?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gin-gonic) (c1d06e3) will **decrease** coverage by `0.10%`.
> The diff coverage is `100.00%`.

```diff
@@            Coverage Diff             @@
##           master    #3500      +/-   ##
==========================================
- Coverage   98.63%   98.54%   -0.10%     
==========================================
  Files          42       42              
  Lines        3148     3151       +3     
==========================================
  Hits         3105     3105              
- Misses         29       31       +2     
- Partials       14       15       +1     
```

| Flag | Coverage Δ | |
|---|---|---|
|  | `98.54% <100.00%> (-0.10%)` | :arrow_down: |
| go-1.16 | `∅ <ø> (∅)` | |
| go-1.17 | `98.54% <100.00%> (+<0.01%)` | :arrow_up: |
| go-1.18 | `?` | |
| go-1.19 | `?` | |
| go-1.20 | `?` | |
| macos-latest | `∅ <ø> (∅)` | |
| ubuntu-latest | `98.54% <100.00%> (-0.10%)` | :arrow_down: |

Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gin-gonic#carryforward-flags-in-the-pull-request-comment) to find out more.

| [Impacted Files](https://codecov.io/gh/gin-gonic/gin/pull/3500?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gin-gonic) | Coverage Δ | |
|---|---|---|
| [gin.go](https://codecov.io/gh/gin-gonic/gin/pull/3500?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gin-gonic#diff-Z2luLmdv) | `99.19% <100.00%> (+<0.01%)` | :arrow_up: |
| [context.go](https://codecov.io/gh/gin-gonic/gin/pull/3500?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gin-gonic#diff-Y29udGV4dC5nbw==) | `97.47% <0.00%> (-0.51%)` | :arrow_down: |

Help us with your feedback. Take ten seconds to tell us [how you rate us](https://about.codecov.io/nps?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gin-gonic). Have a feature suggestion? [Share it here.](https://app.codecov.io/gh/feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gin-gonic)

appleboy: @t0rchwo0d testing fail. Please take a look.

Patch:
diff --git a/gin.go b/gin.go
index 35159d0..32dae24 100644
--- a/gin.go
+++ b/gin.go
@@ -9,6 +9,7 @@ import (
 	"html/template"
 	"net"
 	"net/http"
+	"net/url"
 	"os"
 	"path"
 	"strings"
@@ -668,6 +669,9 @@ func redirectTrailingSlash(c *Context) {
 	req := c.Request
 	p := req.URL.Path
 	if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." {
+		prefix = url.QueryEscape(prefix)
+		prefix = strings.ReplaceAll(prefix, "%2F", "/")
+
 		p = prefix + "/" + req.URL.Path
 	}
 	req.URL.Path = p + "/"


Test patch:
diff --git a/routes_test.go b/routes_test.go
index ada8e1e..5310cae 100644
--- a/routes_test.go
+++ b/routes_test.go
@@ -185,6 +185,18 @@ func TestRouteRedirectTrailingSlash(t *testing.T) {
 	w = PerformRequest(router, http.MethodGet, "/path2/", header{Key: "X-Forwarded-Prefix", Value: "/api/"})
 	assert.Equal(t, 200, w.Code)
 
+	w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "../../bug#?"})
+	assert.Equal(t, "../../../bug%2523%253F/path", w.Header().Get("Location"))
+	assert.Equal(t, 301, w.Code)
+
+	w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "https://gin-gonic.com/#"})
+	assert.Equal(t, "https%3A/gin-gonic.com/%23/https%253A/gin-gonic.com/%2523/path", w.Header().Get("Location"))
+	assert.Equal(t, 301, w.Code)
+
+	w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "#bug"})
+	assert.Equal(t, "%23bug/%2523bug/path", w.Header().Get("Location"))
+	assert.Equal(t, 301, w.Code)
+
 	router.RedirectTrailingSlash = false
 
 	w = PerformRequest(router, http.MethodGet, "/path/")