TL;DR
This guide shows how to calculate the Content-Length header correctly when crafting HTTP requests, particularly to avoid vulnerabilities like HTTP Request Smuggling. Incorrectly calculating this value can lead to attackers injecting malicious requests.
Understanding Content-Length
The Content-Length header tells the server how many bytes to expect in the request body. It’s crucial for servers that don’t use chunked encoding. If you send a wrong value, the server might misinterpret the request.
Calculating Content-Length: Step-by-Step
- Determine the Body Length: First, figure out exactly how many bytes your request body contains. This depends on what data you’re sending (e.g., JSON, XML, form data).
- Encoding Matters: If you are using UTF-8 encoding for text data, remember that some characters take up more than one byte. Count the bytes, not the number of characters.
- Manual Calculation (Example): Let’s say you have this JSON payload:
{ "name": "John Doe", "age": 30 }If saved as UTF-8, the actual byte length might be more than just counting characters. Use a tool or programming language to determine this.
- Using Programming Languages: Most languages have built-in functions for getting the byte length of strings.
- Python:
payload = '{"name": "John Doe", "age": 30}' content_length = len(payload.encode('utf-8')) print(f'Content-Length: {content_length}') - JavaScript:
const payload = '{"name": "John Doe""
- Python: