Protect HTTP response headers from response splitting
Description
Allowing newline characters in an HTTP response header can change the boundaries of the response. If the framework or server accepts them, this may lead to cross-site scripting (XSS) or cache poisoning.
Potential impact
- XSS: Injected scripts may run in the client.
- Cache poisoning: Malicious content may be cached and served to other users.
- Information disclosure: Manipulated responses may expose sensitive data.
Remediation
- Validate each input for the intended header and reject or remove carriage returns (
\r) and line feeds (\n). - Use the framework’s header API and verify how the framework and server handle header values that contain newlines.
Examples
All three examples set X-My-Header from external input. The revised versions remove newlines before setting the header. Django’s header API and Werkzeug, which Flask uses, reject newlines in header values, so the original code may raise an exception.
Django
Before
python
# Django without application input validation
from django.http import HttpResponse
def unsafe_view(request):
user_input = request.GET.get('input', '')
response = HttpResponse()
response['X-My-Header'] = user_input
return response
After
python
# Django with newline removal
from django.http import HttpResponse
import re
def safe_view(request):
user_input = request.GET.get('input', '')
sanitized_input = re.sub(r'[\r\n]', '', user_input)
response = HttpResponse()
response['X-My-Header'] = sanitized_input
return response
Flask
Before
python
# Flask without application input validation
from flask import Flask, request, Response
app = Flask(__name__)
@app.route('/unsafe')
def unsafe():
user_input = request.args.get('input', '')
response = Response()
response.headers['X-My-Header'] = user_input
return response
After
python
# Flask with newline removal
from flask import Flask, request, Response
import re
app = Flask(__name__)
@app.route('/safe')
def safe():
user_input = request.args.get('input', '')
sanitized_input = re.sub(r'[\r\n]', '', user_input)
response = Response()
response.headers['X-My-Header'] = sanitized_input
return response
FastAPI
Before
python
# FastAPI without application input validation
from fastapi import FastAPI, Request, Response
app = FastAPI()
@app.get("/unsafe")
async def unsafe(request: Request):
user_input = request.query_params.get('input', '')
response = Response()
response.headers['X-My-Header'] = user_input
return response
After
python
# FastAPI with newline removal
from fastapi import FastAPI, Request, Response
import re
app = FastAPI()
@app.get("/safe")
async def safe(request: Request):
user_input = request.query_params.get('input', '')
sanitized_input = re.sub(r'[\r\n]', '', user_input)
response = Response()
response.headers['X-My-Header'] = sanitized_input
return response