Usage of vulnerable 'serve' function

  • Rule ID: go_gosec_http_http_serve
  • Languages: go
  • Source: http_serve.yml

Description

The net/http serve functions in Go, when used with default settings, are vulnerable to resource consumption attacks. Attackers can exploit this by creating numerous connections to the server, intentionally not completing data transfers or leaving connections open, which can exhaust the server's resources and prevent it from accepting new legitimate connections.

Remediations

To mitigate such attacks, specific server configurations are necessary:

❌ Avoid Default Serve Functions for Production

Functions like http.ListenAndServe and http.Serve should not be used in a production setting as they do not allow for timeout configurations.

✅ Configure Timeouts on Custom http.Server Object

Create a custom http.Server object and set appropriate timeouts to prevent resource exhaustion.

import (
"net/http"
"time"
"log"
)

func main() {
srv := &http.Server{
Addr: "localhost:8000",
ReadHeaderTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 30 * time.Second,
}

if err := srv.ListenAndServe(); err != nil {
log.Fatal(err)
}
}

✅ Use http.TimeoutHandler for Per Request Timeouts

To set timeouts for individual requests, use the http.TimeoutHandler wrapper on your handlers. This ensures that the server does not wait indefinitely for a request to complete.

Resources

Associated CWE

Configuration

To skip this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --skip-rule=go_gosec_http_http_serve

To run only this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --only-rule=go_gosec_http_http_serve