Skip to content

Commit 63e00a9

Browse files
authored
fix(middleware): harden redirect URL construction (#3220)
* fix(middleware): harden redirect URL construction * fix(middleware): reject invalid redirect hosts and skip asterisk targets
1 parent 7af8fac commit 63e00a9

2 files changed

Lines changed: 191 additions & 11 deletions

File tree

‎middleware/redirect.go‎

Lines changed: 52 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -134,16 +134,57 @@ func (config RedirectConfig) ToMiddleware() (echo.MiddlewareFunc, error) {
134134
}
135135

136136
req, scheme := c.Request(), c.Scheme()
137+
if req.URL.Path == "*" {
138+
return next(c)
139+
}
140+
switch scheme {
141+
case "ws":
142+
scheme = "http"
143+
case "wss":
144+
scheme = "https"
145+
}
137146
host := req.Host
138-
if ok, url := config.redirect(scheme, host, req.RequestURI); ok {
139-
return c.Redirect(config.Code, url)
147+
ok, target := config.redirect(scheme, host, "")
148+
if !ok {
149+
return next(c)
140150
}
141-
142-
return next(c)
151+
if !isValidRedirectHost(host) {
152+
return echo.ErrBadRequest
153+
}
154+
uri := req.RequestURI
155+
if uri == "" || uri[0] != '/' {
156+
uri = req.URL.RequestURI()
157+
}
158+
// The host already anchors this absolute URL, so preserve leading path
159+
// slashes. Only control characters need escaping here.
160+
return c.Redirect(config.Code, target+escapeControlChars(uri))
143161
}
144162
}, nil
145163
}
146164

165+
func hasWWWPrefix(host string) bool {
166+
return len(host) >= len(www) && strings.EqualFold(host[:len(www)], www)
167+
}
168+
169+
func stripWWWPrefix(host string) string {
170+
if hasWWWPrefix(host) {
171+
return host[len(www):]
172+
}
173+
return host
174+
}
175+
176+
// isValidRedirectHost checks the authority before it is used in a Location.
177+
// Check the stripped host too, as removing a bare www. would leave no hostname.
178+
func isValidRedirectHost(host string) bool {
179+
host = stripWWWPrefix(host)
180+
if host == "" || host[0] == ':' || host[0] == '.' {
181+
return false
182+
}
183+
// net/http validates Host syntax. Reject percent escapes too, since a
184+
// browser could interpret them as authority delimiters in Location.
185+
return !strings.Contains(host, "%")
186+
}
187+
147188
var redirectHTTPS = func(scheme, host, uri string) (bool, string) {
148189
if scheme != "https" {
149190
return true, "https://" + host + uri
@@ -153,32 +194,32 @@ var redirectHTTPS = func(scheme, host, uri string) (bool, string) {
153194

154195
var redirectHTTPSWWW = func(scheme, host, uri string) (bool, string) {
155196
// Redirect if not HTTPS OR missing www prefix (needs either fix)
156-
if scheme != "https" || !strings.HasPrefix(host, www) {
157-
host = strings.TrimPrefix(host, www) // Remove www if present to avoid duplication
197+
if scheme != "https" || !hasWWWPrefix(host) {
198+
host = stripWWWPrefix(host) // Remove www if present to avoid duplication
158199
return true, "https://www." + host + uri
159200
}
160201
return false, ""
161202
}
162203

163204
var redirectNonHTTPSWWW = func(scheme, host, uri string) (ok bool, url string) {
164205
// Redirect if not HTTPS OR has www prefix (needs either fix)
165-
if scheme != "https" || strings.HasPrefix(host, www) {
166-
host = strings.TrimPrefix(host, www)
206+
if scheme != "https" || hasWWWPrefix(host) {
207+
host = stripWWWPrefix(host)
167208
return true, "https://" + host + uri
168209
}
169210
return false, ""
170211
}
171212

172213
var redirectWWW = func(scheme, host, uri string) (bool, string) {
173-
if !strings.HasPrefix(host, www) {
214+
if !hasWWWPrefix(host) {
174215
return true, scheme + "://www." + host + uri
175216
}
176217
return false, ""
177218
}
178219

179220
var redirectNonWWW = func(scheme, host, uri string) (bool, string) {
180-
if strings.HasPrefix(host, www) {
181-
return true, scheme + "://" + host[4:] + uri
221+
if hasWWWPrefix(host) {
222+
return true, scheme + "://" + host[len(www):] + uri
182223
}
183224
return false, ""
184225
}

‎middleware/redirect_test.go‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,3 +336,142 @@ func TestRedirectHTTPSRedirect_forwardedProtoTrust(t *testing.T) {
336336
})
337337
}
338338
}
339+
340+
func TestRedirectMalformedHost(t *testing.T) {
341+
for _, tc := range []struct {
342+
host string
343+
hasWWW bool
344+
}{{"", false}, {"www.", true}, {"www.:80", true}, {"WWW.", true}, {":80", false}, {".example.com", false}, {"example.com%2fpath", false}} {
345+
for _, mw := range []struct {
346+
name string
347+
make func() echo.MiddlewareFunc
348+
reject bool
349+
}{{"https", HTTPSRedirect, true}, {"https-www", HTTPSWWWRedirect, true}, {"https-non-www", HTTPSNonWWWRedirect, true}, {"www", WWWRedirect, !tc.hasWWW}, {"non-www", NonWWWRedirect, tc.hasWWW}} {
350+
t.Run(mw.name+"/"+tc.host, func(t *testing.T) {
351+
e := echo.New()
352+
e.Pre(mw.make())
353+
called := false
354+
e.GET("/*", func(c *echo.Context) error { called = true; return c.NoContent(http.StatusOK) })
355+
req := httptest.NewRequest(http.MethodGet, "/attacker.com/login", nil)
356+
req.Host = tc.host
357+
rec := httptest.NewRecorder()
358+
e.ServeHTTP(rec, req)
359+
want := http.StatusOK
360+
if mw.reject {
361+
want = http.StatusBadRequest
362+
}
363+
assert.Equal(t, want, rec.Code)
364+
assert.Equal(t, !mw.reject, called)
365+
assert.Empty(t, rec.Header().Get(echo.HeaderLocation))
366+
})
367+
}
368+
}
369+
}
370+
371+
func TestRedirectBareWWWHostOverHTTP(t *testing.T) {
372+
e := echo.New()
373+
e.Pre(HTTPSNonWWWRedirect())
374+
e.GET("/*", func(c *echo.Context) error { return c.NoContent(http.StatusOK) })
375+
server := httptest.NewServer(e)
376+
defer server.Close()
377+
req, err := http.NewRequest(http.MethodGet, server.URL+"/attacker.com/login", nil)
378+
if !assert.NoError(t, err) {
379+
return
380+
}
381+
req.Host = "www."
382+
client := server.Client()
383+
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
384+
resp, err := client.Do(req)
385+
if !assert.NoError(t, err) {
386+
return
387+
}
388+
defer resp.Body.Close()
389+
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
390+
assert.Empty(t, resp.Header.Get(echo.HeaderLocation))
391+
}
392+
393+
func TestRedirectRequestTarget(t *testing.T) {
394+
for _, tc := range []struct{ uri, want string }{
395+
{"", "https://example.com/files/a%2Fb?x=1"},
396+
{"http://example.com/files/a%2Fb?x=1", "https://example.com/files/a%2Fb?x=1"},
397+
{"//attacker.com/x", "https://example.com//attacker.com/x"},
398+
{"/x\t/y", "https://example.com/x%09/y"},
399+
} {
400+
t.Run(tc.uri, func(t *testing.T) {
401+
e := echo.New()
402+
req := httptest.NewRequest(http.MethodGet, "http://example.com/files/a%2Fb?x=1", nil)
403+
req.RequestURI = tc.uri
404+
rec := httptest.NewRecorder()
405+
c := e.NewContext(req, rec)
406+
assert.NoError(t, HTTPSRedirect()(func(*echo.Context) error { return nil })(c))
407+
assert.Equal(t, tc.want, rec.Header().Get(echo.HeaderLocation))
408+
})
409+
}
410+
}
411+
412+
func TestRedirectValidAuthority(t *testing.T) {
413+
for _, host := range []string{"example.com", "example.com:8080", "[::1]", "[::1]:8080"} {
414+
t.Run(host, func(t *testing.T) {
415+
e := echo.New()
416+
req := httptest.NewRequest(http.MethodGet, "/docs", nil)
417+
req.Host = host
418+
rec := httptest.NewRecorder()
419+
assert.NoError(t, HTTPSRedirect()(func(*echo.Context) error { return nil })(e.NewContext(req, rec)))
420+
assert.Equal(t, "https://"+host+"/docs", rec.Header().Get(echo.HeaderLocation))
421+
})
422+
}
423+
}
424+
425+
func TestRedirectWWWCaseAndWebSocketScheme(t *testing.T) {
426+
for _, tc := range []struct {
427+
name, host, proto, want string
428+
make func() echo.MiddlewareFunc
429+
}{
430+
{"strip uppercase", "WWW.example.com", "http", "http://example.com/docs", NonWWWRedirect},
431+
{"avoid duplicate", "WWW.example.com", "http", "https://www.example.com/docs", HTTPSWWWRedirect},
432+
{"already www", "WWW.example.com", "https", "", WWWRedirect},
433+
{"ws", "example.com", "ws", "http://www.example.com/docs", WWWRedirect},
434+
{"wss", "www.example.com", "wss", "https://example.com/docs", NonWWWRedirect},
435+
{"already secure", "example.com", "wss", "", HTTPSRedirect},
436+
} {
437+
t.Run(tc.name, func(t *testing.T) {
438+
e := echo.New()
439+
req := httptest.NewRequest(http.MethodGet, "/docs", nil)
440+
req.Host = tc.host
441+
req.RemoteAddr = "127.0.0.1:1234"
442+
req.Header.Set(echo.HeaderXForwardedProto, tc.proto)
443+
rec := httptest.NewRecorder()
444+
assert.NoError(t, tc.make()(func(*echo.Context) error { return nil })(e.NewContext(req, rec)))
445+
assert.Equal(t, tc.want, rec.Header().Get(echo.HeaderLocation))
446+
})
447+
}
448+
}
449+
450+
func TestRedirectAsteriskTarget(t *testing.T) {
451+
e := echo.New()
452+
req := httptest.NewRequest(http.MethodOptions, "*", nil)
453+
req.Host = "example.com"
454+
rec := httptest.NewRecorder()
455+
called := false
456+
err := HTTPSRedirect()(func(c *echo.Context) error { called = true; return c.NoContent(http.StatusNoContent) })(e.NewContext(req, rec))
457+
assert.NoError(t, err)
458+
assert.True(t, called)
459+
assert.Equal(t, http.StatusNoContent, rec.Code)
460+
assert.Empty(t, rec.Header().Get(echo.HeaderLocation))
461+
}
462+
463+
func TestRedirectUnchangedHost(t *testing.T) {
464+
e := echo.New()
465+
req := httptest.NewRequest(http.MethodGet, "https://example.com/docs", nil)
466+
req.Host = ""
467+
rec := httptest.NewRecorder()
468+
called := false
469+
err := HTTPSRedirect()(func(c *echo.Context) error {
470+
called = true
471+
return c.NoContent(http.StatusOK)
472+
})(e.NewContext(req, rec))
473+
assert.NoError(t, err)
474+
assert.True(t, called)
475+
assert.Equal(t, http.StatusOK, rec.Code)
476+
assert.Empty(t, rec.Header().Get(echo.HeaderLocation))
477+
}

0 commit comments

Comments
 (0)