Avoid HTTP header injection (Python) | CAST Appmarq

Avoid HTTP header injection (Python)

CRITICAL

Rule Definition
CR and LF characters in an HTTP header may give attackers control of the remaining headers and body of the response the application intends to send, as well as allowing them to create additional responses entirely under their control. This can lead to: cookie injection, open redirect, proxy cache poisoning, log corruption, or rewriting the body of the response.

Remediation
Use authorized sanitization methods of the framework, if available. Remove CR, LF characters for values coming from user inputs and used in HTTP headers

Violation Code Sample
app = FastAPI()

@app.get("/sample/")
def sample(req):
    content = {"message": "Hello World"}

    tainted= req.query_params.get("my_param")

    headers = {"X-whatever": tainted, "Content-Language": "en-US"}
    return JSONResponse(content=content, headers=headers)  # violation
Fixed Code Sample
app = FastAPI()

@app.get("/sample/")
def sample(req):
    content = {"message": "Hello World"}
    tainted= req.query_params.get("my_param")

    param_safe = re.sub('[\n\r]', '', tainted)  # the data is sanitized against CR/LF
    param_safe = html.escape(param_safe)  # the data is sanitized against "<script>"

    headers = {"X-whatever": param_safe, "Content-Language": "en-US"}
    return JSONResponse(content=content, headers=headers)

Reference
CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting') https://cwe.mitre.org/data/definitions/113.html CWE-644: Improper Neutralization of HTTP Headers for Scripting Syntax https://cwe.mitre.org/data/definitions/644.html Open Web Application Security Project (OWASP) https://www.owasp.org/index.php/Top_10_2007

Related Technologies

Health Factor

  Total Quality Index


Technical Criterion
Secure Coding - Input Validation

About CAST Appmarq

CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.

Benchmark Statistics

Global Compliance

nan%

Total Violations
0
Total Opportunities
0
Average Violations / App.
nan
The compliance score represents 1 minus the ratio between the number of times a rule has been violated compared to the number of opportunities in a set of applications that the rule could have been violated.

Industry Insights

Don't Know

100.00%

Select from drop-down

100.00%