HTTP Content-Length请求头是否安全可信?能否被伪造?
Great question—let’s break this down clearly, since it ties into how user agents handle request headers and edge cases where control shifts.
First: What’s a "Forbidden Header Name"?
As you noted, Content-Length falls into this category. The core rule here is that these headers are exclusively controlled by the user agent (like Chrome, Firefox, or a native app’s HTTP client). For regular web apps running in a standard browser sandbox, any attempt to set or modify Content-Length via client-side code (using XMLHttpRequest or fetch) will be completely ignored. Browsers override the value to match the actual length of the request body they’re sending—this is a built-in safeguard for consistency and security, so servers get an accurate value aligned with the payload.
But What If You Control the User Agent?
This is the critical edge case. If you’re not restricted to a standard browser environment—say you’re using a custom HTTP client (curl, Postman, a Python requests script), or you’ve modified a browser’s behavior (via extensions, debugging tools, or patched binaries)—you absolutely can forge the Content-Length header.
For example:
- With curl, sending a fake
Content-Lengthis trivial:
Here, the actual body length is 10, but you’re telling the server it’s 100. The server will either wait for missing data (timing out eventually) or throw an error due to a mismatched payload, depending on its configuration.curl -X POST https://example.com/api -H "Content-Length: 100" -d "short-body" - In any custom client you build or control, you have full authority over every header in the request—
Content-Lengthis no different from any other header you set.
How Trustworthy Is It, Then?
It all depends on the context:
- Requests from standard, unmodified browsers: You can generally trust
Content-Lengthhere. The browser enforces that the value matches the actual body, and client-side tampering attempts are blocked. - Requests from non-browser clients or modified user agents: You can’t trust it at all. Attackers or custom tools can easily set a
Content-Lengththat doesn’t match the body length, which can lead to issues like request smuggling, buffer overflows (if the server isn’t handling validation properly), or incorrect payload parsing.
Final Takeaway
Treat Content-Length as a hint, not a guarantee unless you’re dealing with requests from a trusted, unmodified user agent. Always validate the actual incoming data length against the header value on the server side—never rely solely on the header to determine how much data to read.
内容的提问来源于stack exchange,提问作者Charlie Fish

