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
Provenance
- Commit
d8f2d58- Tree
c42793c- Author
Ruben Pari <73421813+RubenPari@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
8ad9f9c
2 files changed+54 added−5 removed
modified:gin_test.go+20 added
1022 unmodified lines1023 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 }1026 1027+func TestReadHeaderTimeoutDefault(t *testing.T) {1028+ engine := New()1029+ assert.Equal(t, defaultReadHeaderTimeout, engine.ReadHeaderTimeout)1030+ assert.Equal(t, defaultReadHeaderTimeout, engine.getReadHeaderTimeout())1031+}1032+1033+func 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+}1040+1041+func TestReadHeaderTimeoutZeroFallsBackToDefault(t *testing.T) {1042+ engine := New()1043+ engine.ReadHeaderTimeout = 01044+ assert.Equal(t, defaultReadHeaderTimeout, engine.getReadHeaderTimeout())1045+}1046+1047 type Birthday string1048 1049 func (b *Birthday) UnmarshalParam(param string) error {1050 *b = Birthday(strings.ReplaceAll(param, "-", "/"))147 unmodified linesmodified:gin.go+34 added-5 removed
11 unmodified lines12 "os"13 "path"14 "strings"15 "sync"16+ "time"17 18 "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 lines29 colon = ":"30 backslash = "\\"31 )32 33+// 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.37+const defaultReadHeaderTimeout = 10 * time.Second38+39 var (40 default404Body = []byte("404 page not found")41 default405Body = []byte("405 method not allowed")42 )129 unmodified lines172 // MaxMultipartMemory value of 'maxMemory' param that is given to http.Request's ParseMultipartForm173 // method call.174 MaxMultipartMemory int64175 176+ // 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.Duration181+182 // UseH2C enable h2c support.183 UseH2C bool184 185 // ContextWithFallback enable fallback Context.Deadline(), Context.Done(), Context.Err() and Context.Value() when Context.Request.Context() is not nil.45 unmodified lines231 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 lines268 skippedNodes := make([]skippedNode, 0, engine.maxSections)269 return &Context{engine: engine, params: &v, skippedNodes: &skippedNodes}270 }271 272+// getReadHeaderTimeout returns the configured ReadHeaderTimeout, or the273+// default if it is zero or negative.274+func (engine *Engine) getReadHeaderTimeout() time.Duration {275+ if engine.ReadHeaderTimeout <= 0 {276+ return defaultReadHeaderTimeout277+ }278+ return engine.ReadHeaderTimeout279+}280+281 // Delims sets template left and right delims and returns an Engine instance.282 func (engine *Engine) Delims(left, right string) *Engine {283 engine.delims = render.Delims{Left: left, Right: right}284 return engine274 unmodified lines559 560 // 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.566 func (engine *Engine) Run(addr ...string) (err error) {567 defer func() { debugPrintError(err) }()568 569 if engine.isUnsafeTrustedProxies() {3 unmodified lines573 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 lines594 "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")595 }596 597 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 lines679 "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")680 }681 682 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