Skip to content

Document CRLF handling for http.server #142533

Closed

Description

@aydinnyunus

Bug report

Bug description:

Vulnerability Description

The send_header method in Lib/http/server.py writes headers directly to the output stream without checking for line breaks. When user-controlled input is passed to send_header, an attacker can inject CRLF sequences (\r\n) to terminate the current header and inject new headers or manipulate the response.

Vulnerable Code:

def send_header(self, keyword, value):
    """Send a MIME header to the headers buffer."""
    if self.request_version != 'HTTP/0.9':
        if not hasattr(self, '_headers_buffer'):
            self._headers_buffer = []
        self._headers_buffer.append(
            ("%s: %s\r\n" % (keyword, value)).encode('latin-1', 'strict'))
    # No validation for \r or \n characters!

Attack Scenarios

Scenario 1: Set-Cookie Injection (Session Fixation)

Vulnerable Application:

from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse

class VulnerableHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        query = parse_qs(urlparse(self.path).query)
        custom_val = query.get('val', [''])[0]
        
        self.send_response(200)
        # VULNERABLE: Direct injection into header
        self.send_header('X-Custom', custom_val)
        self.end_headers()
        self.wfile.write(b"Hello World")

Attack URL:

http://localhost:8000/?val=test%0d%0aSet-Cookie:%20pwned=true

Result:

HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.x
Date: ...
X-Custom: test
Set-Cookie: pwned=true

Impact: Attacker can inject session cookies, leading to session fixation attacks.


Scenario 2: Location Header Injection (Malicious Redirect)

Attack URL:

http://localhost:8000/?val=test%0d%0ALocation:%20http://evil.com/

Result:

HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.x
Date: ...
X-Custom: test
Location: http://evil.com/

Impact:

  • Users are redirected to malicious websites
  • Phishing attacks
  • Open redirect vulnerabilities
  • Cache poisoning (if cached responses include the injected Location header)

Verified Test Results:

✓ LOCATION HEADER INJECTION CONFIRMED!
  Injected Location: http://evil.com/
✓ MALICIOUS REDIRECT CONFIRMED!
  Browser would redirect to: http://evil.com/
✓ MALICIOUS REDIRECT SUCCESSFUL!

Attack Vector

  • Type: Remote
  • Prerequisites:
    • Application uses http.server.BaseHTTPRequestHandler
    • User input is reflected in HTTP headers via send_header()
    • Common patterns: query parameters, user-agent reflection, custom headers
  • Complexity: Low - Simple URL manipulation
  • Authentication: Not required

Impact

  1. Session Fixation: Inject Set-Cookie headers to control user sessions
  2. Malicious Redirects: Inject Location headers to redirect users to attacker-controlled sites
  3. Cache Poisoning: Inject headers that affect cached responses
  4. Cross-Site Scripting (XSS): Inject headers that enable XSS attacks
  5. Web Cache Deception: Manipulate cache behavior via injected headers

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. tadejmagajna commented on Dec 10, 2025

    @tadejmagajna
    Contributor

    Thank you for reporting, the bug makes sense. Goes without saying both keyword and value are vulnerable.

    I would like to work on this if that's okay.

  2. added
    stdlibStandard Library Python modules in the Lib/ directory
    on Dec 11, 2025
  3. picnixz commented on Dec 11, 2025

    @picnixz
    Member

    http.server is not meant to be used in production, I honestly don't consider this a vulnerability worth the change. If the validation is small, we could consider it but there is a huge warning saying that we are aware of those vulns (or if it's not mentioned, we just update the docs).

  4. added
    pendingThe issue will be closed if no feedback is provided
    on Dec 11, 2025
  5. aydinnyunus commented on Dec 11, 2025

    @aydinnyunus
    Author

    There’s a warning advising against using it in production, but I haven’t found any specific explanation about whether CRLF injection vulnerabilities are taken into account.

    The relevant section is here: https://docs.python.org/3/library/http.server.html#security-considerations

  6. picnixz commented on Dec 11, 2025

    @picnixz
    Member

    Yes, so we have two possibilities:

    • Make the validation. But honestly, I don't want the code to become more and more complex. The module is not meant for advanced use, and usually only for local testing. Now, if the validation algorithm is not too big, we can add it. What matters is that we don't overcomplicate code for which there are better replacements on PyPI.
    • Update the docs. That's minimal effort on our side, and at least we would mention this. I know that there are CRLF vulns in wsgiref for instance that were reported (and maybe fixed I don't remember now) so maybe people do expect to have the same minimal guards for whatever server we provide.
  7. aydinnyunus commented on Dec 11, 2025

    @aydinnyunus
    Author

    I think the fix is straightforward. A simple validation check should be enough. I also reviewed the wsgiref implementation and didn't see any existing safeguard for this. We can apply the same fix to both components without much complexity. What do you think?

    if '\r' in value or '\n' in value:
        raise ValueError("Header value contains invalid characters (CR or LF)")
  8. added 3 commits that reference this issue on Dec 11, 2025
  9. tadejmagajna commented on Dec 12, 2025

    @tadejmagajna
    Contributor

    The suggestion to apply fixes for both wsgiref and http.server makes sense.
    Taking into account the above suggestion to keep changes minimal, I implemented the change in the linked PR.

    Also adjusted the ValueError message slightly for consistency with other wsgiref exceptions.

  10. vadmium commented on Dec 12, 2025

    @vadmium
    Member

    HTTP server previously reported in Issue #73610, also covering the send_response_only method. If any change is made I’d prefer to raise an exception than quietly alter the fields as proposed there.

    Issues #72964 and #55880 are open reports for wsgiref.headers.

  11. 14 remaining items

  12. added 2 commits that reference this issue on Jan 4, 2026
  13. aydinnyunus commented on Feb 4, 2026

    @aydinnyunus
    Author

    Hi team, I think document is not updated yet. Is there any deadline so I can close the issue 🙏

  14. picnixz commented on Feb 4, 2026

    @picnixz
    Member

    Do not close the issue, maintainers will take care of it when needed (in particular because there might have backports). I haven't time to read through it but I will try to do so this week-end (my daily job takes my time).

    EDIT: actually I already approved the PR. Victor was waiting for someone else if needed. I'll merge it this week-end then.

  15. added 3 commits that reference this issue on Apr 1, 2026
  16. added a commit that references this issue on Apr 2, 2026
  17. added 2 commits that reference this issue on Apr 2, 2026
  18. added 2 commits that reference this issue on Apr 2, 2026
  19. added a commit that references this issue on Apr 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions