Skip to content
Myr

fix(engine): add default ReadHeaderTimeout to http.Server in Run methods (#4800)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Engine.Run, RunTLS, and RunListener created an http.Server without ReadHeaderTimeout, leaving applications exposed to slowloris-style resource exhaustion. A new Engine.ReadHeaderTimeout field (default 10s) is now applied to the http.Server created by these methods. Users can customize the value or use a custom http.Server for full control. Fixes #4760

authored by Ruben Pari · committed by GitHub · parent 8ad9f9c · Browse files · 2 files+54 added−5 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>

Diff stats

2 files+54 added−5 removed

  • other:+54 added−5 removed

2 files+54 added−5 removed

modified:gin_test.go+20 added
1022 unmodified lines
1023 assertRoutePresent(t, routes, RouteInfo{Path: "/test1", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest1"})1024 assertRoutePresent(t, routes, RouteInfo{Path: "/test2", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest2"})1025}10261027func TestReadHeaderTimeoutDefault(t *testing.T) {1028 engine := New()1029 assert.Equal(t, defaultReadHeaderTimeout, engine.ReadHeaderTimeout)1030 assert.Equal(t, defaultReadHeaderTimeout, engine.getReadHeaderTimeout())1031}10321033func TestReadHeaderTimeoutCustom(t *testing.T) {1034 engine := New(func(e *Engine) {1035 e.ReadHeaderTimeout = 30 * time.Second1036 })1037 assert.Equal(t, 30*time.Second, engine.ReadHeaderTimeout)1038 assert.Equal(t, 30*time.Second, engine.getReadHeaderTimeout())1039}10401041func TestReadHeaderTimeoutZeroFallsBackToDefault(t *testing.T) {1042 engine := New()1043 engine.ReadHeaderTimeout = 01044 assert.Equal(t, defaultReadHeaderTimeout, engine.getReadHeaderTimeout())1045}10461047type Birthday string10481049func (b *Birthday) UnmarshalParam(param string) error {1050 *b = Birthday(strings.ReplaceAll(param, "-", "/"))
147 unmodified lines
modified:gin.go+34 added-5 removed
11 unmodified lines
12 "os"13 "path"14 "strings"15 "sync"16 "time"1718 "github.com/gin-gonic/gin/internal/bytesconv"19 filesystem "github.com/gin-gonic/gin/internal/fs"20 "github.com/gin-gonic/gin/render"
8 unmodified lines
29 colon = ":"30 backslash = "\\"31)3233// defaultReadHeaderTimeout is the default ReadHeaderTimeout applied to the34// http.Server created by Run, RunTLS and RunListener. It protects against35// slowloris-style resource exhaustion when the caller does not configure a36// custom http.Server.37const defaultReadHeaderTimeout = 10 * time.Second3839var (40 default404Body = []byte("404 page not found")41 default405Body = []byte("405 method not allowed")42)
129 unmodified lines
172 // MaxMultipartMemory value of 'maxMemory' param that is given to http.Request's ParseMultipartForm173 // method call.174 MaxMultipartMemory int64175176 // ReadHeaderTimeout is the maximum duration allowed for reading the request177 // headers by the http.Server created through Run, RunTLS and RunListener.178 // If zero or negative, a default of 10 seconds is used. Set to a positive179 // value to customize, or use a custom http.Server directly to disable it.180 ReadHeaderTimeout time.Duration181182 // UseH2C enable h2c support.183 UseH2C bool184185 // ContextWithFallback enable fallback Context.Deadline(), Context.Done(), Context.Err() and Context.Value() when Context.Request.Context() is not nil.
45 unmodified lines
231 UseEscapedPath: false,232 RemoveExtraSlash: false,233 UnescapePathValues: true,234 MaxMultipartMemory: defaultMultipartMemory,235 ReadHeaderTimeout: defaultReadHeaderTimeout,236 trees: make(methodTrees, 0, 9),237 delims: render.Delims{Left: "{{", Right: "}}"},238 secureJSONPrefix: "while(1);",239 trustedProxies: []string{"0.0.0.0/0", "::/0"},
28 unmodified lines
268 skippedNodes := make([]skippedNode, 0, engine.maxSections)269 return &Context{engine: engine, params: &v, skippedNodes: &skippedNodes}270}271272// getReadHeaderTimeout returns the configured ReadHeaderTimeout, or the273// default if it is zero or negative.274func (engine *Engine) getReadHeaderTimeout() time.Duration {275 if engine.ReadHeaderTimeout <= 0 {276 return defaultReadHeaderTimeout277 }278 return engine.ReadHeaderTimeout279}280281// Delims sets template left and right delims and returns an Engine instance.282func (engine *Engine) Delims(left, right string) *Engine {283 engine.delims = render.Delims{Left: left, Right: right}284 return engine
274 unmodified lines
559560// Run attaches the router to a http.Server and starts listening and serving HTTP requests.561// It is a shortcut for http.ListenAndServe(addr, router)562// Note: this method will block the calling goroutine indefinitely unless an error happens.563// The created http.Server is configured with a default ReadHeaderTimeout of 10 seconds564// (configurable via Engine.ReadHeaderTimeout) to mitigate slowloris attacks.565// For full control over timeouts, create a custom http.Server and use ServeHTTP.566func (engine *Engine) Run(addr ...string) (err error) {567 defer func() { debugPrintError(err) }()568569 if engine.isUnsafeTrustedProxies() {
3 unmodified lines
573 engine.updateRouteTrees()574 address := resolveAddress(addr)575 debugPrint("Listening and serving HTTP on %s\n", address)576 server := &http.Server{ // #nosec G112551 Addr: address,552 Handler: engine.Handler(),577 Addr: address,578 Handler: engine.Handler(),579 ReadHeaderTimeout: engine.getReadHeaderTimeout(),580 }581 err = server.ListenAndServe()582 return583}
10 unmodified lines
594 "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")595 }596597 server := &http.Server{ // #nosec G112571 Addr: addr,572 Handler: engine.Handler(),598 Addr: addr,599 Handler: engine.Handler(),600 ReadHeaderTimeout: engine.getReadHeaderTimeout(),601 }602 err = server.ListenAndServeTLS(certFile, keyFile)603 return604}
74 unmodified lines
679 "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")680 }681682 server := &http.Server{ // #nosec G112655 Handler: engine.Handler(),683 Handler: engine.Handler(),684 ReadHeaderTimeout: engine.getReadHeaderTimeout(),685 }686 err = server.Serve(listener)687 return688}
173 unmodified lines